gitkon commit gitk: Catch mkdtemp errors (ac54a4b)
   1#!/bin/sh
   2# Tcl ignores the next line -*- tcl -*- \
   3exec wish "$0" -- "$@"
   4
   5# Copyright © 2005-2014 Paul Mackerras.  All rights reserved.
   6# This program is free software; it may be used, copied, modified
   7# and distributed under the terms of the GNU General Public Licence,
   8# either version 2, or (at your option) any later version.
   9
  10package require Tk
  11
  12proc hasworktree {} {
  13    return [expr {[exec git rev-parse --is-bare-repository] == "false" &&
  14                  [exec git rev-parse --is-inside-git-dir] == "false"}]
  15}
  16
  17proc reponame {} {
  18    global gitdir
  19    set n [file normalize $gitdir]
  20    if {[string match "*/.git" $n]} {
  21        set n [string range $n 0 end-5]
  22    }
  23    return [file tail $n]
  24}
  25
  26proc gitworktree {} {
  27    variable _gitworktree
  28    if {[info exists _gitworktree]} {
  29        return $_gitworktree
  30    }
  31    # v1.7.0 introduced --show-toplevel to return the canonical work-tree
  32    if {[catch {set _gitworktree [exec git rev-parse --show-toplevel]}]} {
  33        # try to set work tree from environment, core.worktree or use
  34        # cdup to obtain a relative path to the top of the worktree. If
  35        # run from the top, the ./ prefix ensures normalize expands pwd.
  36        if {[catch { set _gitworktree $env(GIT_WORK_TREE) }]} {
  37            catch {set _gitworktree [exec git config --get core.worktree]}
  38            if {$_gitworktree eq ""} {
  39                set _gitworktree [file normalize ./[exec git rev-parse --show-cdup]]
  40            }
  41        }
  42    }
  43    return $_gitworktree
  44}
  45
  46# A simple scheduler for compute-intensive stuff.
  47# The aim is to make sure that event handlers for GUI actions can
  48# run at least every 50-100 ms.  Unfortunately fileevent handlers are
  49# run before X event handlers, so reading from a fast source can
  50# make the GUI completely unresponsive.
  51proc run args {
  52    global isonrunq runq currunq
  53
  54    set script $args
  55    if {[info exists isonrunq($script)]} return
  56    if {$runq eq {} && ![info exists currunq]} {
  57        after idle dorunq
  58    }
  59    lappend runq [list {} $script]
  60    set isonrunq($script) 1
  61}
  62
  63proc filerun {fd script} {
  64    fileevent $fd readable [list filereadable $fd $script]
  65}
  66
  67proc filereadable {fd script} {
  68    global runq currunq
  69
  70    fileevent $fd readable {}
  71    if {$runq eq {} && ![info exists currunq]} {
  72        after idle dorunq
  73    }
  74    lappend runq [list $fd $script]
  75}
  76
  77proc nukefile {fd} {
  78    global runq
  79
  80    for {set i 0} {$i < [llength $runq]} {} {
  81        if {[lindex $runq $i 0] eq $fd} {
  82            set runq [lreplace $runq $i $i]
  83        } else {
  84            incr i
  85        }
  86    }
  87}
  88
  89proc dorunq {} {
  90    global isonrunq runq currunq
  91
  92    set tstart [clock clicks -milliseconds]
  93    set t0 $tstart
  94    while {[llength $runq] > 0} {
  95        set fd [lindex $runq 0 0]
  96        set script [lindex $runq 0 1]
  97        set currunq [lindex $runq 0]
  98        set runq [lrange $runq 1 end]
  99        set repeat [eval $script]
 100        unset currunq
 101        set t1 [clock clicks -milliseconds]
 102        set t [expr {$t1 - $t0}]
 103        if {$repeat ne {} && $repeat} {
 104            if {$fd eq {} || $repeat == 2} {
 105                # script returns 1 if it wants to be readded
 106                # file readers return 2 if they could do more straight away
 107                lappend runq [list $fd $script]
 108            } else {
 109                fileevent $fd readable [list filereadable $fd $script]
 110            }
 111        } elseif {$fd eq {}} {
 112            unset isonrunq($script)
 113        }
 114        set t0 $t1
 115        if {$t1 - $tstart >= 80} break
 116    }
 117    if {$runq ne {}} {
 118        after idle dorunq
 119    }
 120}
 121
 122proc reg_instance {fd} {
 123    global commfd leftover loginstance
 124
 125    set i [incr loginstance]
 126    set commfd($i) $fd
 127    set leftover($i) {}
 128    return $i
 129}
 130
 131proc unmerged_files {files} {
 132    global nr_unmerged
 133
 134    # find the list of unmerged files
 135    set mlist {}
 136    set nr_unmerged 0
 137    if {[catch {
 138        set fd [open "| git ls-files -u" r]
 139    } err]} {
 140        show_error {} . "[mc "Couldn't get list of unmerged files:"] $err"
 141        exit 1
 142    }
 143    while {[gets $fd line] >= 0} {
 144        set i [string first "\t" $line]
 145        if {$i < 0} continue
 146        set fname [string range $line [expr {$i+1}] end]
 147        if {[lsearch -exact $mlist $fname] >= 0} continue
 148        incr nr_unmerged
 149        if {$files eq {} || [path_filter $files $fname]} {
 150            lappend mlist $fname
 151        }
 152    }
 153    catch {close $fd}
 154    return $mlist
 155}
 156
 157proc parseviewargs {n arglist} {
 158    global vdatemode vmergeonly vflags vdflags vrevs vfiltered vorigargs env
 159    global vinlinediff
 160    global worddiff git_version
 161
 162    set vdatemode($n) 0
 163    set vmergeonly($n) 0
 164    set vinlinediff($n) 0
 165    set glflags {}
 166    set diffargs {}
 167    set nextisval 0
 168    set revargs {}
 169    set origargs $arglist
 170    set allknown 1
 171    set filtered 0
 172    set i -1
 173    foreach arg $arglist {
 174        incr i
 175        if {$nextisval} {
 176            lappend glflags $arg
 177            set nextisval 0
 178            continue
 179        }
 180        switch -glob -- $arg {
 181            "-d" -
 182            "--date-order" {
 183                set vdatemode($n) 1
 184                # remove from origargs in case we hit an unknown option
 185                set origargs [lreplace $origargs $i $i]
 186                incr i -1
 187            }
 188            "-[puabwcrRBMC]" -
 189            "--no-renames" - "--full-index" - "--binary" - "--abbrev=*" -
 190            "--find-copies-harder" - "-l*" - "--ext-diff" - "--no-ext-diff" -
 191            "--src-prefix=*" - "--dst-prefix=*" - "--no-prefix" -
 192            "-O*" - "--text" - "--full-diff" - "--ignore-space-at-eol" -
 193            "--ignore-space-change" - "-U*" - "--unified=*" {
 194                # These request or affect diff output, which we don't want.
 195                # Some could be used to set our defaults for diff display.
 196                lappend diffargs $arg
 197            }
 198            "--raw" - "--patch-with-raw" - "--patch-with-stat" -
 199            "--name-only" - "--name-status" - "--color" -
 200            "--log-size" - "--pretty=*" - "--decorate" - "--abbrev-commit" -
 201            "--cc" - "-z" - "--header" - "--parents" - "--boundary" -
 202            "--no-color" - "-g" - "--walk-reflogs" - "--no-walk" -
 203            "--timestamp" - "relative-date" - "--date=*" - "--stdin" -
 204            "--objects" - "--objects-edge" - "--reverse" {
 205                # These cause our parsing of git log's output to fail, or else
 206                # they're options we want to set ourselves, so ignore them.
 207            }
 208            "--color-words*" - "--word-diff=color" {
 209                # These trigger a word diff in the console interface,
 210                # so help the user by enabling our own support
 211                if {[package vcompare $git_version "1.7.2"] >= 0} {
 212                    set worddiff [mc "Color words"]
 213                }
 214            }
 215            "--word-diff*" {
 216                if {[package vcompare $git_version "1.7.2"] >= 0} {
 217                    set worddiff [mc "Markup words"]
 218                }
 219            }
 220            "--stat=*" - "--numstat" - "--shortstat" - "--summary" -
 221            "--check" - "--exit-code" - "--quiet" - "--topo-order" -
 222            "--full-history" - "--dense" - "--sparse" -
 223            "--follow" - "--left-right" - "--encoding=*" {
 224                # These are harmless, and some are even useful
 225                lappend glflags $arg
 226            }
 227            "--diff-filter=*" - "--no-merges" - "--unpacked" -
 228            "--max-count=*" - "--skip=*" - "--since=*" - "--after=*" -
 229            "--until=*" - "--before=*" - "--max-age=*" - "--min-age=*" -
 230            "--author=*" - "--committer=*" - "--grep=*" - "-[iE]" -
 231            "--remove-empty" - "--first-parent" - "--cherry-pick" -
 232            "-S*" - "-G*" - "--pickaxe-all" - "--pickaxe-regex" -
 233            "--simplify-by-decoration" {
 234                # These mean that we get a subset of the commits
 235                set filtered 1
 236                lappend glflags $arg
 237            }
 238            "-L*" {
 239                # Line-log with 'stuck' argument (unstuck form is
 240                # not supported)
 241                set filtered 1
 242                set vinlinediff($n) 1
 243                set allknown 0
 244                lappend glflags $arg
 245            }
 246            "-n" {
 247                # This appears to be the only one that has a value as a
 248                # separate word following it
 249                set filtered 1
 250                set nextisval 1
 251                lappend glflags $arg
 252            }
 253            "--not" - "--all" {
 254                lappend revargs $arg
 255            }
 256            "--merge" {
 257                set vmergeonly($n) 1
 258                # git rev-parse doesn't understand --merge
 259                lappend revargs --gitk-symmetric-diff-marker MERGE_HEAD...HEAD
 260            }
 261            "--no-replace-objects" {
 262                set env(GIT_NO_REPLACE_OBJECTS) "1"
 263            }
 264            "-*" {
 265                # Other flag arguments including -<n>
 266                if {[string is digit -strict [string range $arg 1 end]]} {
 267                    set filtered 1
 268                } else {
 269                    # a flag argument that we don't recognize;
 270                    # that means we can't optimize
 271                    set allknown 0
 272                }
 273                lappend glflags $arg
 274            }
 275            default {
 276                # Non-flag arguments specify commits or ranges of commits
 277                if {[string match "*...*" $arg]} {
 278                    lappend revargs --gitk-symmetric-diff-marker
 279                }
 280                lappend revargs $arg
 281            }
 282        }
 283    }
 284    set vdflags($n) $diffargs
 285    set vflags($n) $glflags
 286    set vrevs($n) $revargs
 287    set vfiltered($n) $filtered
 288    set vorigargs($n) $origargs
 289    return $allknown
 290}
 291
 292proc parseviewrevs {view revs} {
 293    global vposids vnegids
 294
 295    if {$revs eq {}} {
 296        set revs HEAD
 297    }
 298    if {[catch {set ids [eval exec git rev-parse $revs]} err]} {
 299        # we get stdout followed by stderr in $err
 300        # for an unknown rev, git rev-parse echoes it and then errors out
 301        set errlines [split $err "\n"]
 302        set badrev {}
 303        for {set l 0} {$l < [llength $errlines]} {incr l} {
 304            set line [lindex $errlines $l]
 305            if {!([string length $line] == 40 && [string is xdigit $line])} {
 306                if {[string match "fatal:*" $line]} {
 307                    if {[string match "fatal: ambiguous argument*" $line]
 308                        && $badrev ne {}} {
 309                        if {[llength $badrev] == 1} {
 310                            set err "unknown revision $badrev"
 311                        } else {
 312                            set err "unknown revisions: [join $badrev ", "]"
 313                        }
 314                    } else {
 315                        set err [join [lrange $errlines $l end] "\n"]
 316                    }
 317                    break
 318                }
 319                lappend badrev $line
 320            }
 321        }
 322        error_popup "[mc "Error parsing revisions:"] $err"
 323        return {}
 324    }
 325    set ret {}
 326    set pos {}
 327    set neg {}
 328    set sdm 0
 329    foreach id [split $ids "\n"] {
 330        if {$id eq "--gitk-symmetric-diff-marker"} {
 331            set sdm 4
 332        } elseif {[string match "^*" $id]} {
 333            if {$sdm != 1} {
 334                lappend ret $id
 335                if {$sdm == 3} {
 336                    set sdm 0
 337                }
 338            }
 339            lappend neg [string range $id 1 end]
 340        } else {
 341            if {$sdm != 2} {
 342                lappend ret $id
 343            } else {
 344                lset ret end $id...[lindex $ret end]
 345            }
 346            lappend pos $id
 347        }
 348        incr sdm -1
 349    }
 350    set vposids($view) $pos
 351    set vnegids($view) $neg
 352    return $ret
 353}
 354
 355# Start off a git log process and arrange to read its output
 356proc start_rev_list {view} {
 357    global startmsecs commitidx viewcomplete curview
 358    global tclencoding
 359    global viewargs viewargscmd viewfiles vfilelimit
 360    global showlocalchanges
 361    global viewactive viewinstances vmergeonly
 362    global mainheadid viewmainheadid viewmainheadid_orig
 363    global vcanopt vflags vrevs vorigargs
 364    global show_notes
 365
 366    set startmsecs [clock clicks -milliseconds]
 367    set commitidx($view) 0
 368    # these are set this way for the error exits
 369    set viewcomplete($view) 1
 370    set viewactive($view) 0
 371    varcinit $view
 372
 373    set args $viewargs($view)
 374    if {$viewargscmd($view) ne {}} {
 375        if {[catch {
 376            set str [exec sh -c $viewargscmd($view)]
 377        } err]} {
 378            error_popup "[mc "Error executing --argscmd command:"] $err"
 379            return 0
 380        }
 381        set args [concat $args [split $str "\n"]]
 382    }
 383    set vcanopt($view) [parseviewargs $view $args]
 384
 385    set files $viewfiles($view)
 386    if {$vmergeonly($view)} {
 387        set files [unmerged_files $files]
 388        if {$files eq {}} {
 389            global nr_unmerged
 390            if {$nr_unmerged == 0} {
 391                error_popup [mc "No files selected: --merge specified but\
 392                             no files are unmerged."]
 393            } else {
 394                error_popup [mc "No files selected: --merge specified but\
 395                             no unmerged files are within file limit."]
 396            }
 397            return 0
 398        }
 399    }
 400    set vfilelimit($view) $files
 401
 402    if {$vcanopt($view)} {
 403        set revs [parseviewrevs $view $vrevs($view)]
 404        if {$revs eq {}} {
 405            return 0
 406        }
 407        set args [concat $vflags($view) $revs]
 408    } else {
 409        set args $vorigargs($view)
 410    }
 411
 412    if {[catch {
 413        set fd [open [concat | git log --no-color -z --pretty=raw $show_notes \
 414                        --parents --boundary $args "--" $files] r]
 415    } err]} {
 416        error_popup "[mc "Error executing git log:"] $err"
 417        return 0
 418    }
 419    set i [reg_instance $fd]
 420    set viewinstances($view) [list $i]
 421    set viewmainheadid($view) $mainheadid
 422    set viewmainheadid_orig($view) $mainheadid
 423    if {$files ne {} && $mainheadid ne {}} {
 424        get_viewmainhead $view
 425    }
 426    if {$showlocalchanges && $viewmainheadid($view) ne {}} {
 427        interestedin $viewmainheadid($view) dodiffindex
 428    }
 429    fconfigure $fd -blocking 0 -translation lf -eofchar {}
 430    if {$tclencoding != {}} {
 431        fconfigure $fd -encoding $tclencoding
 432    }
 433    filerun $fd [list getcommitlines $fd $i $view 0]
 434    nowbusy $view [mc "Reading"]
 435    set viewcomplete($view) 0
 436    set viewactive($view) 1
 437    return 1
 438}
 439
 440proc stop_instance {inst} {
 441    global commfd leftover
 442
 443    set fd $commfd($inst)
 444    catch {
 445        set pid [pid $fd]
 446
 447        if {$::tcl_platform(platform) eq {windows}} {
 448            exec kill -f $pid
 449        } else {
 450            exec kill $pid
 451        }
 452    }
 453    catch {close $fd}
 454    nukefile $fd
 455    unset commfd($inst)
 456    unset leftover($inst)
 457}
 458
 459proc stop_backends {} {
 460    global commfd
 461
 462    foreach inst [array names commfd] {
 463        stop_instance $inst
 464    }
 465}
 466
 467proc stop_rev_list {view} {
 468    global viewinstances
 469
 470    foreach inst $viewinstances($view) {
 471        stop_instance $inst
 472    }
 473    set viewinstances($view) {}
 474}
 475
 476proc reset_pending_select {selid} {
 477    global pending_select mainheadid selectheadid
 478
 479    if {$selid ne {}} {
 480        set pending_select $selid
 481    } elseif {$selectheadid ne {}} {
 482        set pending_select $selectheadid
 483    } else {
 484        set pending_select $mainheadid
 485    }
 486}
 487
 488proc getcommits {selid} {
 489    global canv curview need_redisplay viewactive
 490
 491    initlayout
 492    if {[start_rev_list $curview]} {
 493        reset_pending_select $selid
 494        show_status [mc "Reading commits..."]
 495        set need_redisplay 1
 496    } else {
 497        show_status [mc "No commits selected"]
 498    }
 499}
 500
 501proc updatecommits {} {
 502    global curview vcanopt vorigargs vfilelimit viewinstances
 503    global viewactive viewcomplete tclencoding
 504    global startmsecs showneartags showlocalchanges
 505    global mainheadid viewmainheadid viewmainheadid_orig pending_select
 506    global hasworktree
 507    global varcid vposids vnegids vflags vrevs
 508    global show_notes
 509
 510    set hasworktree [hasworktree]
 511    rereadrefs
 512    set view $curview
 513    if {$mainheadid ne $viewmainheadid_orig($view)} {
 514        if {$showlocalchanges} {
 515            dohidelocalchanges
 516        }
 517        set viewmainheadid($view) $mainheadid
 518        set viewmainheadid_orig($view) $mainheadid
 519        if {$vfilelimit($view) ne {}} {
 520            get_viewmainhead $view
 521        }
 522    }
 523    if {$showlocalchanges} {
 524        doshowlocalchanges
 525    }
 526    if {$vcanopt($view)} {
 527        set oldpos $vposids($view)
 528        set oldneg $vnegids($view)
 529        set revs [parseviewrevs $view $vrevs($view)]
 530        if {$revs eq {}} {
 531            return
 532        }
 533        # note: getting the delta when negative refs change is hard,
 534        # and could require multiple git log invocations, so in that
 535        # case we ask git log for all the commits (not just the delta)
 536        if {$oldneg eq $vnegids($view)} {
 537            set newrevs {}
 538            set npos 0
 539            # take out positive refs that we asked for before or
 540            # that we have already seen
 541            foreach rev $revs {
 542                if {[string length $rev] == 40} {
 543                    if {[lsearch -exact $oldpos $rev] < 0
 544                        && ![info exists varcid($view,$rev)]} {
 545                        lappend newrevs $rev
 546                        incr npos
 547                    }
 548                } else {
 549                    lappend $newrevs $rev
 550                }
 551            }
 552            if {$npos == 0} return
 553            set revs $newrevs
 554            set vposids($view) [lsort -unique [concat $oldpos $vposids($view)]]
 555        }
 556        set args [concat $vflags($view) $revs --not $oldpos]
 557    } else {
 558        set args $vorigargs($view)
 559    }
 560    if {[catch {
 561        set fd [open [concat | git log --no-color -z --pretty=raw $show_notes \
 562                        --parents --boundary $args "--" $vfilelimit($view)] r]
 563    } err]} {
 564        error_popup "[mc "Error executing git log:"] $err"
 565        return
 566    }
 567    if {$viewactive($view) == 0} {
 568        set startmsecs [clock clicks -milliseconds]
 569    }
 570    set i [reg_instance $fd]
 571    lappend viewinstances($view) $i
 572    fconfigure $fd -blocking 0 -translation lf -eofchar {}
 573    if {$tclencoding != {}} {
 574        fconfigure $fd -encoding $tclencoding
 575    }
 576    filerun $fd [list getcommitlines $fd $i $view 1]
 577    incr viewactive($view)
 578    set viewcomplete($view) 0
 579    reset_pending_select {}
 580    nowbusy $view [mc "Reading"]
 581    if {$showneartags} {
 582        getallcommits
 583    }
 584}
 585
 586proc reloadcommits {} {
 587    global curview viewcomplete selectedline currentid thickerline
 588    global showneartags treediffs commitinterest cached_commitrow
 589    global targetid
 590
 591    set selid {}
 592    if {$selectedline ne {}} {
 593        set selid $currentid
 594    }
 595
 596    if {!$viewcomplete($curview)} {
 597        stop_rev_list $curview
 598    }
 599    resetvarcs $curview
 600    set selectedline {}
 601    catch {unset currentid}
 602    catch {unset thickerline}
 603    catch {unset treediffs}
 604    readrefs
 605    changedrefs
 606    if {$showneartags} {
 607        getallcommits
 608    }
 609    clear_display
 610    catch {unset commitinterest}
 611    catch {unset cached_commitrow}
 612    catch {unset targetid}
 613    setcanvscroll
 614    getcommits $selid
 615    return 0
 616}
 617
 618# This makes a string representation of a positive integer which
 619# sorts as a string in numerical order
 620proc strrep {n} {
 621    if {$n < 16} {
 622        return [format "%x" $n]
 623    } elseif {$n < 256} {
 624        return [format "x%.2x" $n]
 625    } elseif {$n < 65536} {
 626        return [format "y%.4x" $n]
 627    }
 628    return [format "z%.8x" $n]
 629}
 630
 631# Procedures used in reordering commits from git log (without
 632# --topo-order) into the order for display.
 633
 634proc varcinit {view} {
 635    global varcstart vupptr vdownptr vleftptr vbackptr varctok varcrow
 636    global vtokmod varcmod vrowmod varcix vlastins
 637
 638    set varcstart($view) {{}}
 639    set vupptr($view) {0}
 640    set vdownptr($view) {0}
 641    set vleftptr($view) {0}
 642    set vbackptr($view) {0}
 643    set varctok($view) {{}}
 644    set varcrow($view) {{}}
 645    set vtokmod($view) {}
 646    set varcmod($view) 0
 647    set vrowmod($view) 0
 648    set varcix($view) {{}}
 649    set vlastins($view) {0}
 650}
 651
 652proc resetvarcs {view} {
 653    global varcid varccommits parents children vseedcount ordertok
 654    global vshortids
 655
 656    foreach vid [array names varcid $view,*] {
 657        unset varcid($vid)
 658        unset children($vid)
 659        unset parents($vid)
 660    }
 661    foreach vid [array names vshortids $view,*] {
 662        unset vshortids($vid)
 663    }
 664    # some commits might have children but haven't been seen yet
 665    foreach vid [array names children $view,*] {
 666        unset children($vid)
 667    }
 668    foreach va [array names varccommits $view,*] {
 669        unset varccommits($va)
 670    }
 671    foreach vd [array names vseedcount $view,*] {
 672        unset vseedcount($vd)
 673    }
 674    catch {unset ordertok}
 675}
 676
 677# returns a list of the commits with no children
 678proc seeds {v} {
 679    global vdownptr vleftptr varcstart
 680
 681    set ret {}
 682    set a [lindex $vdownptr($v) 0]
 683    while {$a != 0} {
 684        lappend ret [lindex $varcstart($v) $a]
 685        set a [lindex $vleftptr($v) $a]
 686    }
 687    return $ret
 688}
 689
 690proc newvarc {view id} {
 691    global varcid varctok parents children vdatemode
 692    global vupptr vdownptr vleftptr vbackptr varcrow varcix varcstart
 693    global commitdata commitinfo vseedcount varccommits vlastins
 694
 695    set a [llength $varctok($view)]
 696    set vid $view,$id
 697    if {[llength $children($vid)] == 0 || $vdatemode($view)} {
 698        if {![info exists commitinfo($id)]} {
 699            parsecommit $id $commitdata($id) 1
 700        }
 701        set cdate [lindex [lindex $commitinfo($id) 4] 0]
 702        if {![string is integer -strict $cdate]} {
 703            set cdate 0
 704        }
 705        if {![info exists vseedcount($view,$cdate)]} {
 706            set vseedcount($view,$cdate) -1
 707        }
 708        set c [incr vseedcount($view,$cdate)]
 709        set cdate [expr {$cdate ^ 0xffffffff}]
 710        set tok "s[strrep $cdate][strrep $c]"
 711    } else {
 712        set tok {}
 713    }
 714    set ka 0
 715    if {[llength $children($vid)] > 0} {
 716        set kid [lindex $children($vid) end]
 717        set k $varcid($view,$kid)
 718        if {[string compare [lindex $varctok($view) $k] $tok] > 0} {
 719            set ki $kid
 720            set ka $k
 721            set tok [lindex $varctok($view) $k]
 722        }
 723    }
 724    if {$ka != 0} {
 725        set i [lsearch -exact $parents($view,$ki) $id]
 726        set j [expr {[llength $parents($view,$ki)] - 1 - $i}]
 727        append tok [strrep $j]
 728    }
 729    set c [lindex $vlastins($view) $ka]
 730    if {$c == 0 || [string compare $tok [lindex $varctok($view) $c]] < 0} {
 731        set c $ka
 732        set b [lindex $vdownptr($view) $ka]
 733    } else {
 734        set b [lindex $vleftptr($view) $c]
 735    }
 736    while {$b != 0 && [string compare $tok [lindex $varctok($view) $b]] >= 0} {
 737        set c $b
 738        set b [lindex $vleftptr($view) $c]
 739    }
 740    if {$c == $ka} {
 741        lset vdownptr($view) $ka $a
 742        lappend vbackptr($view) 0
 743    } else {
 744        lset vleftptr($view) $c $a
 745        lappend vbackptr($view) $c
 746    }
 747    lset vlastins($view) $ka $a
 748    lappend vupptr($view) $ka
 749    lappend vleftptr($view) $b
 750    if {$b != 0} {
 751        lset vbackptr($view) $b $a
 752    }
 753    lappend varctok($view) $tok
 754    lappend varcstart($view) $id
 755    lappend vdownptr($view) 0
 756    lappend varcrow($view) {}
 757    lappend varcix($view) {}
 758    set varccommits($view,$a) {}
 759    lappend vlastins($view) 0
 760    return $a
 761}
 762
 763proc splitvarc {p v} {
 764    global varcid varcstart varccommits varctok vtokmod
 765    global vupptr vdownptr vleftptr vbackptr varcix varcrow vlastins
 766
 767    set oa $varcid($v,$p)
 768    set otok [lindex $varctok($v) $oa]
 769    set ac $varccommits($v,$oa)
 770    set i [lsearch -exact $varccommits($v,$oa) $p]
 771    if {$i <= 0} return
 772    set na [llength $varctok($v)]
 773    # "%" sorts before "0"...
 774    set tok "$otok%[strrep $i]"
 775    lappend varctok($v) $tok
 776    lappend varcrow($v) {}
 777    lappend varcix($v) {}
 778    set varccommits($v,$oa) [lrange $ac 0 [expr {$i - 1}]]
 779    set varccommits($v,$na) [lrange $ac $i end]
 780    lappend varcstart($v) $p
 781    foreach id $varccommits($v,$na) {
 782        set varcid($v,$id) $na
 783    }
 784    lappend vdownptr($v) [lindex $vdownptr($v) $oa]
 785    lappend vlastins($v) [lindex $vlastins($v) $oa]
 786    lset vdownptr($v) $oa $na
 787    lset vlastins($v) $oa 0
 788    lappend vupptr($v) $oa
 789    lappend vleftptr($v) 0
 790    lappend vbackptr($v) 0
 791    for {set b [lindex $vdownptr($v) $na]} {$b != 0} {set b [lindex $vleftptr($v) $b]} {
 792        lset vupptr($v) $b $na
 793    }
 794    if {[string compare $otok $vtokmod($v)] <= 0} {
 795        modify_arc $v $oa
 796    }
 797}
 798
 799proc renumbervarc {a v} {
 800    global parents children varctok varcstart varccommits
 801    global vupptr vdownptr vleftptr vbackptr vlastins varcid vtokmod vdatemode
 802
 803    set t1 [clock clicks -milliseconds]
 804    set todo {}
 805    set isrelated($a) 1
 806    set kidchanged($a) 1
 807    set ntot 0
 808    while {$a != 0} {
 809        if {[info exists isrelated($a)]} {
 810            lappend todo $a
 811            set id [lindex $varccommits($v,$a) end]
 812            foreach p $parents($v,$id) {
 813                if {[info exists varcid($v,$p)]} {
 814                    set isrelated($varcid($v,$p)) 1
 815                }
 816            }
 817        }
 818        incr ntot
 819        set b [lindex $vdownptr($v) $a]
 820        if {$b == 0} {
 821            while {$a != 0} {
 822                set b [lindex $vleftptr($v) $a]
 823                if {$b != 0} break
 824                set a [lindex $vupptr($v) $a]
 825            }
 826        }
 827        set a $b
 828    }
 829    foreach a $todo {
 830        if {![info exists kidchanged($a)]} continue
 831        set id [lindex $varcstart($v) $a]
 832        if {[llength $children($v,$id)] > 1} {
 833            set children($v,$id) [lsort -command [list vtokcmp $v] \
 834                                      $children($v,$id)]
 835        }
 836        set oldtok [lindex $varctok($v) $a]
 837        if {!$vdatemode($v)} {
 838            set tok {}
 839        } else {
 840            set tok $oldtok
 841        }
 842        set ka 0
 843        set kid [last_real_child $v,$id]
 844        if {$kid ne {}} {
 845            set k $varcid($v,$kid)
 846            if {[string compare [lindex $varctok($v) $k] $tok] > 0} {
 847                set ki $kid
 848                set ka $k
 849                set tok [lindex $varctok($v) $k]
 850            }
 851        }
 852        if {$ka != 0} {
 853            set i [lsearch -exact $parents($v,$ki) $id]
 854            set j [expr {[llength $parents($v,$ki)] - 1 - $i}]
 855            append tok [strrep $j]
 856        }
 857        if {$tok eq $oldtok} {
 858            continue
 859        }
 860        set id [lindex $varccommits($v,$a) end]
 861        foreach p $parents($v,$id) {
 862            if {[info exists varcid($v,$p)]} {
 863                set kidchanged($varcid($v,$p)) 1
 864            } else {
 865                set sortkids($p) 1
 866            }
 867        }
 868        lset varctok($v) $a $tok
 869        set b [lindex $vupptr($v) $a]
 870        if {$b != $ka} {
 871            if {[string compare [lindex $varctok($v) $ka] $vtokmod($v)] < 0} {
 872                modify_arc $v $ka
 873            }
 874            if {[string compare [lindex $varctok($v) $b] $vtokmod($v)] < 0} {
 875                modify_arc $v $b
 876            }
 877            set c [lindex $vbackptr($v) $a]
 878            set d [lindex $vleftptr($v) $a]
 879            if {$c == 0} {
 880                lset vdownptr($v) $b $d
 881            } else {
 882                lset vleftptr($v) $c $d
 883            }
 884            if {$d != 0} {
 885                lset vbackptr($v) $d $c
 886            }
 887            if {[lindex $vlastins($v) $b] == $a} {
 888                lset vlastins($v) $b $c
 889            }
 890            lset vupptr($v) $a $ka
 891            set c [lindex $vlastins($v) $ka]
 892            if {$c == 0 || \
 893                    [string compare $tok [lindex $varctok($v) $c]] < 0} {
 894                set c $ka
 895                set b [lindex $vdownptr($v) $ka]
 896            } else {
 897                set b [lindex $vleftptr($v) $c]
 898            }
 899            while {$b != 0 && \
 900                      [string compare $tok [lindex $varctok($v) $b]] >= 0} {
 901                set c $b
 902                set b [lindex $vleftptr($v) $c]
 903            }
 904            if {$c == $ka} {
 905                lset vdownptr($v) $ka $a
 906                lset vbackptr($v) $a 0
 907            } else {
 908                lset vleftptr($v) $c $a
 909                lset vbackptr($v) $a $c
 910            }
 911            lset vleftptr($v) $a $b
 912            if {$b != 0} {
 913                lset vbackptr($v) $b $a
 914            }
 915            lset vlastins($v) $ka $a
 916        }
 917    }
 918    foreach id [array names sortkids] {
 919        if {[llength $children($v,$id)] > 1} {
 920            set children($v,$id) [lsort -command [list vtokcmp $v] \
 921                                      $children($v,$id)]
 922        }
 923    }
 924    set t2 [clock clicks -milliseconds]
 925    #puts "renumbervarc did [llength $todo] of $ntot arcs in [expr {$t2-$t1}]ms"
 926}
 927
 928# Fix up the graph after we have found out that in view $v,
 929# $p (a commit that we have already seen) is actually the parent
 930# of the last commit in arc $a.
 931proc fix_reversal {p a v} {
 932    global varcid varcstart varctok vupptr
 933
 934    set pa $varcid($v,$p)
 935    if {$p ne [lindex $varcstart($v) $pa]} {
 936        splitvarc $p $v
 937        set pa $varcid($v,$p)
 938    }
 939    # seeds always need to be renumbered
 940    if {[lindex $vupptr($v) $pa] == 0 ||
 941        [string compare [lindex $varctok($v) $a] \
 942             [lindex $varctok($v) $pa]] > 0} {
 943        renumbervarc $pa $v
 944    }
 945}
 946
 947proc insertrow {id p v} {
 948    global cmitlisted children parents varcid varctok vtokmod
 949    global varccommits ordertok commitidx numcommits curview
 950    global targetid targetrow vshortids
 951
 952    readcommit $id
 953    set vid $v,$id
 954    set cmitlisted($vid) 1
 955    set children($vid) {}
 956    set parents($vid) [list $p]
 957    set a [newvarc $v $id]
 958    set varcid($vid) $a
 959    lappend vshortids($v,[string range $id 0 3]) $id
 960    if {[string compare [lindex $varctok($v) $a] $vtokmod($v)] < 0} {
 961        modify_arc $v $a
 962    }
 963    lappend varccommits($v,$a) $id
 964    set vp $v,$p
 965    if {[llength [lappend children($vp) $id]] > 1} {
 966        set children($vp) [lsort -command [list vtokcmp $v] $children($vp)]
 967        catch {unset ordertok}
 968    }
 969    fix_reversal $p $a $v
 970    incr commitidx($v)
 971    if {$v == $curview} {
 972        set numcommits $commitidx($v)
 973        setcanvscroll
 974        if {[info exists targetid]} {
 975            if {![comes_before $targetid $p]} {
 976                incr targetrow
 977            }
 978        }
 979    }
 980}
 981
 982proc insertfakerow {id p} {
 983    global varcid varccommits parents children cmitlisted
 984    global commitidx varctok vtokmod targetid targetrow curview numcommits
 985
 986    set v $curview
 987    set a $varcid($v,$p)
 988    set i [lsearch -exact $varccommits($v,$a) $p]
 989    if {$i < 0} {
 990        puts "oops: insertfakerow can't find [shortids $p] on arc $a"
 991        return
 992    }
 993    set children($v,$id) {}
 994    set parents($v,$id) [list $p]
 995    set varcid($v,$id) $a
 996    lappend children($v,$p) $id
 997    set cmitlisted($v,$id) 1
 998    set numcommits [incr commitidx($v)]
 999    # note we deliberately don't update varcstart($v) even if $i == 0
1000    set varccommits($v,$a) [linsert $varccommits($v,$a) $i $id]
1001    modify_arc $v $a $i
1002    if {[info exists targetid]} {
1003        if {![comes_before $targetid $p]} {
1004            incr targetrow
1005        }
1006    }
1007    setcanvscroll
1008    drawvisible
1009}
1010
1011proc removefakerow {id} {
1012    global varcid varccommits parents children commitidx
1013    global varctok vtokmod cmitlisted currentid selectedline
1014    global targetid curview numcommits
1015
1016    set v $curview
1017    if {[llength $parents($v,$id)] != 1} {
1018        puts "oops: removefakerow [shortids $id] has [llength $parents($v,$id)] parents"
1019        return
1020    }
1021    set p [lindex $parents($v,$id) 0]
1022    set a $varcid($v,$id)
1023    set i [lsearch -exact $varccommits($v,$a) $id]
1024    if {$i < 0} {
1025        puts "oops: removefakerow can't find [shortids $id] on arc $a"
1026        return
1027    }
1028    unset varcid($v,$id)
1029    set varccommits($v,$a) [lreplace $varccommits($v,$a) $i $i]
1030    unset parents($v,$id)
1031    unset children($v,$id)
1032    unset cmitlisted($v,$id)
1033    set numcommits [incr commitidx($v) -1]
1034    set j [lsearch -exact $children($v,$p) $id]
1035    if {$j >= 0} {
1036        set children($v,$p) [lreplace $children($v,$p) $j $j]
1037    }
1038    modify_arc $v $a $i
1039    if {[info exist currentid] && $id eq $currentid} {
1040        unset currentid
1041        set selectedline {}
1042    }
1043    if {[info exists targetid] && $targetid eq $id} {
1044        set targetid $p
1045    }
1046    setcanvscroll
1047    drawvisible
1048}
1049
1050proc real_children {vp} {
1051    global children nullid nullid2
1052
1053    set kids {}
1054    foreach id $children($vp) {
1055        if {$id ne $nullid && $id ne $nullid2} {
1056            lappend kids $id
1057        }
1058    }
1059    return $kids
1060}
1061
1062proc first_real_child {vp} {
1063    global children nullid nullid2
1064
1065    foreach id $children($vp) {
1066        if {$id ne $nullid && $id ne $nullid2} {
1067            return $id
1068        }
1069    }
1070    return {}
1071}
1072
1073proc last_real_child {vp} {
1074    global children nullid nullid2
1075
1076    set kids $children($vp)
1077    for {set i [llength $kids]} {[incr i -1] >= 0} {} {
1078        set id [lindex $kids $i]
1079        if {$id ne $nullid && $id ne $nullid2} {
1080            return $id
1081        }
1082    }
1083    return {}
1084}
1085
1086proc vtokcmp {v a b} {
1087    global varctok varcid
1088
1089    return [string compare [lindex $varctok($v) $varcid($v,$a)] \
1090                [lindex $varctok($v) $varcid($v,$b)]]
1091}
1092
1093# This assumes that if lim is not given, the caller has checked that
1094# arc a's token is less than $vtokmod($v)
1095proc modify_arc {v a {lim {}}} {
1096    global varctok vtokmod varcmod varcrow vupptr curview vrowmod varccommits
1097
1098    if {$lim ne {}} {
1099        set c [string compare [lindex $varctok($v) $a] $vtokmod($v)]
1100        if {$c > 0} return
1101        if {$c == 0} {
1102            set r [lindex $varcrow($v) $a]
1103            if {$r ne {} && $vrowmod($v) <= $r + $lim} return
1104        }
1105    }
1106    set vtokmod($v) [lindex $varctok($v) $a]
1107    set varcmod($v) $a
1108    if {$v == $curview} {
1109        while {$a != 0 && [lindex $varcrow($v) $a] eq {}} {
1110            set a [lindex $vupptr($v) $a]
1111            set lim {}
1112        }
1113        set r 0
1114        if {$a != 0} {
1115            if {$lim eq {}} {
1116                set lim [llength $varccommits($v,$a)]
1117            }
1118            set r [expr {[lindex $varcrow($v) $a] + $lim}]
1119        }
1120        set vrowmod($v) $r
1121        undolayout $r
1122    }
1123}
1124
1125proc update_arcrows {v} {
1126    global vtokmod varcmod vrowmod varcrow commitidx currentid selectedline
1127    global varcid vrownum varcorder varcix varccommits
1128    global vupptr vdownptr vleftptr varctok
1129    global displayorder parentlist curview cached_commitrow
1130
1131    if {$vrowmod($v) == $commitidx($v)} return
1132    if {$v == $curview} {
1133        if {[llength $displayorder] > $vrowmod($v)} {
1134            set displayorder [lrange $displayorder 0 [expr {$vrowmod($v) - 1}]]
1135            set parentlist [lrange $parentlist 0 [expr {$vrowmod($v) - 1}]]
1136        }
1137        catch {unset cached_commitrow}
1138    }
1139    set narctot [expr {[llength $varctok($v)] - 1}]
1140    set a $varcmod($v)
1141    while {$a != 0 && [lindex $varcix($v) $a] eq {}} {
1142        # go up the tree until we find something that has a row number,
1143        # or we get to a seed
1144        set a [lindex $vupptr($v) $a]
1145    }
1146    if {$a == 0} {
1147        set a [lindex $vdownptr($v) 0]
1148        if {$a == 0} return
1149        set vrownum($v) {0}
1150        set varcorder($v) [list $a]
1151        lset varcix($v) $a 0
1152        lset varcrow($v) $a 0
1153        set arcn 0
1154        set row 0
1155    } else {
1156        set arcn [lindex $varcix($v) $a]
1157        if {[llength $vrownum($v)] > $arcn + 1} {
1158            set vrownum($v) [lrange $vrownum($v) 0 $arcn]
1159            set varcorder($v) [lrange $varcorder($v) 0 $arcn]
1160        }
1161        set row [lindex $varcrow($v) $a]
1162    }
1163    while {1} {
1164        set p $a
1165        incr row [llength $varccommits($v,$a)]
1166        # go down if possible
1167        set b [lindex $vdownptr($v) $a]
1168        if {$b == 0} {
1169            # if not, go left, or go up until we can go left
1170            while {$a != 0} {
1171                set b [lindex $vleftptr($v) $a]
1172                if {$b != 0} break
1173                set a [lindex $vupptr($v) $a]
1174            }
1175            if {$a == 0} break
1176        }
1177        set a $b
1178        incr arcn
1179        lappend vrownum($v) $row
1180        lappend varcorder($v) $a
1181        lset varcix($v) $a $arcn
1182        lset varcrow($v) $a $row
1183    }
1184    set vtokmod($v) [lindex $varctok($v) $p]
1185    set varcmod($v) $p
1186    set vrowmod($v) $row
1187    if {[info exists currentid]} {
1188        set selectedline [rowofcommit $currentid]
1189    }
1190}
1191
1192# Test whether view $v contains commit $id
1193proc commitinview {id v} {
1194    global varcid
1195
1196    return [info exists varcid($v,$id)]
1197}
1198
1199# Return the row number for commit $id in the current view
1200proc rowofcommit {id} {
1201    global varcid varccommits varcrow curview cached_commitrow
1202    global varctok vtokmod
1203
1204    set v $curview
1205    if {![info exists varcid($v,$id)]} {
1206        puts "oops rowofcommit no arc for [shortids $id]"
1207        return {}
1208    }
1209    set a $varcid($v,$id)
1210    if {[string compare [lindex $varctok($v) $a] $vtokmod($v)] >= 0} {
1211        update_arcrows $v
1212    }
1213    if {[info exists cached_commitrow($id)]} {
1214        return $cached_commitrow($id)
1215    }
1216    set i [lsearch -exact $varccommits($v,$a) $id]
1217    if {$i < 0} {
1218        puts "oops didn't find commit [shortids $id] in arc $a"
1219        return {}
1220    }
1221    incr i [lindex $varcrow($v) $a]
1222    set cached_commitrow($id) $i
1223    return $i
1224}
1225
1226# Returns 1 if a is on an earlier row than b, otherwise 0
1227proc comes_before {a b} {
1228    global varcid varctok curview
1229
1230    set v $curview
1231    if {$a eq $b || ![info exists varcid($v,$a)] || \
1232            ![info exists varcid($v,$b)]} {
1233        return 0
1234    }
1235    if {$varcid($v,$a) != $varcid($v,$b)} {
1236        return [expr {[string compare [lindex $varctok($v) $varcid($v,$a)] \
1237                           [lindex $varctok($v) $varcid($v,$b)]] < 0}]
1238    }
1239    return [expr {[rowofcommit $a] < [rowofcommit $b]}]
1240}
1241
1242proc bsearch {l elt} {
1243    if {[llength $l] == 0 || $elt <= [lindex $l 0]} {
1244        return 0
1245    }
1246    set lo 0
1247    set hi [llength $l]
1248    while {$hi - $lo > 1} {
1249        set mid [expr {int(($lo + $hi) / 2)}]
1250        set t [lindex $l $mid]
1251        if {$elt < $t} {
1252            set hi $mid
1253        } elseif {$elt > $t} {
1254            set lo $mid
1255        } else {
1256            return $mid
1257        }
1258    }
1259    return $lo
1260}
1261
1262# Make sure rows $start..$end-1 are valid in displayorder and parentlist
1263proc make_disporder {start end} {
1264    global vrownum curview commitidx displayorder parentlist
1265    global varccommits varcorder parents vrowmod varcrow
1266    global d_valid_start d_valid_end
1267
1268    if {$end > $vrowmod($curview)} {
1269        update_arcrows $curview
1270    }
1271    set ai [bsearch $vrownum($curview) $start]
1272    set start [lindex $vrownum($curview) $ai]
1273    set narc [llength $vrownum($curview)]
1274    for {set r $start} {$ai < $narc && $r < $end} {incr ai} {
1275        set a [lindex $varcorder($curview) $ai]
1276        set l [llength $displayorder]
1277        set al [llength $varccommits($curview,$a)]
1278        if {$l < $r + $al} {
1279            if {$l < $r} {
1280                set pad [ntimes [expr {$r - $l}] {}]
1281                set displayorder [concat $displayorder $pad]
1282                set parentlist [concat $parentlist $pad]
1283            } elseif {$l > $r} {
1284                set displayorder [lrange $displayorder 0 [expr {$r - 1}]]
1285                set parentlist [lrange $parentlist 0 [expr {$r - 1}]]
1286            }
1287            foreach id $varccommits($curview,$a) {
1288                lappend displayorder $id
1289                lappend parentlist $parents($curview,$id)
1290            }
1291        } elseif {[lindex $displayorder [expr {$r + $al - 1}]] eq {}} {
1292            set i $r
1293            foreach id $varccommits($curview,$a) {
1294                lset displayorder $i $id
1295                lset parentlist $i $parents($curview,$id)
1296                incr i
1297            }
1298        }
1299        incr r $al
1300    }
1301}
1302
1303proc commitonrow {row} {
1304    global displayorder
1305
1306    set id [lindex $displayorder $row]
1307    if {$id eq {}} {
1308        make_disporder $row [expr {$row + 1}]
1309        set id [lindex $displayorder $row]
1310    }
1311    return $id
1312}
1313
1314proc closevarcs {v} {
1315    global varctok varccommits varcid parents children
1316    global cmitlisted commitidx vtokmod
1317
1318    set missing_parents 0
1319    set scripts {}
1320    set narcs [llength $varctok($v)]
1321    for {set a 1} {$a < $narcs} {incr a} {
1322        set id [lindex $varccommits($v,$a) end]
1323        foreach p $parents($v,$id) {
1324            if {[info exists varcid($v,$p)]} continue
1325            # add p as a new commit
1326            incr missing_parents
1327            set cmitlisted($v,$p) 0
1328            set parents($v,$p) {}
1329            if {[llength $children($v,$p)] == 1 &&
1330                [llength $parents($v,$id)] == 1} {
1331                set b $a
1332            } else {
1333                set b [newvarc $v $p]
1334            }
1335            set varcid($v,$p) $b
1336            if {[string compare [lindex $varctok($v) $b] $vtokmod($v)] < 0} {
1337                modify_arc $v $b
1338            }
1339            lappend varccommits($v,$b) $p
1340            incr commitidx($v)
1341            set scripts [check_interest $p $scripts]
1342        }
1343    }
1344    if {$missing_parents > 0} {
1345        foreach s $scripts {
1346            eval $s
1347        }
1348    }
1349}
1350
1351# Use $rwid as a substitute for $id, i.e. reparent $id's children to $rwid
1352# Assumes we already have an arc for $rwid.
1353proc rewrite_commit {v id rwid} {
1354    global children parents varcid varctok vtokmod varccommits
1355
1356    foreach ch $children($v,$id) {
1357        # make $rwid be $ch's parent in place of $id
1358        set i [lsearch -exact $parents($v,$ch) $id]
1359        if {$i < 0} {
1360            puts "oops rewrite_commit didn't find $id in parent list for $ch"
1361        }
1362        set parents($v,$ch) [lreplace $parents($v,$ch) $i $i $rwid]
1363        # add $ch to $rwid's children and sort the list if necessary
1364        if {[llength [lappend children($v,$rwid) $ch]] > 1} {
1365            set children($v,$rwid) [lsort -command [list vtokcmp $v] \
1366                                        $children($v,$rwid)]
1367        }
1368        # fix the graph after joining $id to $rwid
1369        set a $varcid($v,$ch)
1370        fix_reversal $rwid $a $v
1371        # parentlist is wrong for the last element of arc $a
1372        # even if displayorder is right, hence the 3rd arg here
1373        modify_arc $v $a [expr {[llength $varccommits($v,$a)] - 1}]
1374    }
1375}
1376
1377# Mechanism for registering a command to be executed when we come
1378# across a particular commit.  To handle the case when only the
1379# prefix of the commit is known, the commitinterest array is now
1380# indexed by the first 4 characters of the ID.  Each element is a
1381# list of id, cmd pairs.
1382proc interestedin {id cmd} {
1383    global commitinterest
1384
1385    lappend commitinterest([string range $id 0 3]) $id $cmd
1386}
1387
1388proc check_interest {id scripts} {
1389    global commitinterest
1390
1391    set prefix [string range $id 0 3]
1392    if {[info exists commitinterest($prefix)]} {
1393        set newlist {}
1394        foreach {i script} $commitinterest($prefix) {
1395            if {[string match "$i*" $id]} {
1396                lappend scripts [string map [list "%I" $id "%P" $i] $script]
1397            } else {
1398                lappend newlist $i $script
1399            }
1400        }
1401        if {$newlist ne {}} {
1402            set commitinterest($prefix) $newlist
1403        } else {
1404            unset commitinterest($prefix)
1405        }
1406    }
1407    return $scripts
1408}
1409
1410proc getcommitlines {fd inst view updating}  {
1411    global cmitlisted leftover
1412    global commitidx commitdata vdatemode
1413    global parents children curview hlview
1414    global idpending ordertok
1415    global varccommits varcid varctok vtokmod vfilelimit vshortids
1416
1417    set stuff [read $fd 500000]
1418    # git log doesn't terminate the last commit with a null...
1419    if {$stuff == {} && $leftover($inst) ne {} && [eof $fd]} {
1420        set stuff "\0"
1421    }
1422    if {$stuff == {}} {
1423        if {![eof $fd]} {
1424            return 1
1425        }
1426        global commfd viewcomplete viewactive viewname
1427        global viewinstances
1428        unset commfd($inst)
1429        set i [lsearch -exact $viewinstances($view) $inst]
1430        if {$i >= 0} {
1431            set viewinstances($view) [lreplace $viewinstances($view) $i $i]
1432        }
1433        # set it blocking so we wait for the process to terminate
1434        fconfigure $fd -blocking 1
1435        if {[catch {close $fd} err]} {
1436            set fv {}
1437            if {$view != $curview} {
1438                set fv " for the \"$viewname($view)\" view"
1439            }
1440            if {[string range $err 0 4] == "usage"} {
1441                set err "Gitk: error reading commits$fv:\
1442                        bad arguments to git log."
1443                if {$viewname($view) eq "Command line"} {
1444                    append err \
1445                        "  (Note: arguments to gitk are passed to git log\
1446                         to allow selection of commits to be displayed.)"
1447                }
1448            } else {
1449                set err "Error reading commits$fv: $err"
1450            }
1451            error_popup $err
1452        }
1453        if {[incr viewactive($view) -1] <= 0} {
1454            set viewcomplete($view) 1
1455            # Check if we have seen any ids listed as parents that haven't
1456            # appeared in the list
1457            closevarcs $view
1458            notbusy $view
1459        }
1460        if {$view == $curview} {
1461            run chewcommits
1462        }
1463        return 0
1464    }
1465    set start 0
1466    set gotsome 0
1467    set scripts {}
1468    while 1 {
1469        set i [string first "\0" $stuff $start]
1470        if {$i < 0} {
1471            append leftover($inst) [string range $stuff $start end]
1472            break
1473        }
1474        if {$start == 0} {
1475            set cmit $leftover($inst)
1476            append cmit [string range $stuff 0 [expr {$i - 1}]]
1477            set leftover($inst) {}
1478        } else {
1479            set cmit [string range $stuff $start [expr {$i - 1}]]
1480        }
1481        set start [expr {$i + 1}]
1482        set j [string first "\n" $cmit]
1483        set ok 0
1484        set listed 1
1485        if {$j >= 0 && [string match "commit *" $cmit]} {
1486            set ids [string range $cmit 7 [expr {$j - 1}]]
1487            if {[string match {[-^<>]*} $ids]} {
1488                switch -- [string index $ids 0] {
1489                    "-" {set listed 0}
1490                    "^" {set listed 2}
1491                    "<" {set listed 3}
1492                    ">" {set listed 4}
1493                }
1494                set ids [string range $ids 1 end]
1495            }
1496            set ok 1
1497            foreach id $ids {
1498                if {[string length $id] != 40} {
1499                    set ok 0
1500                    break
1501                }
1502            }
1503        }
1504        if {!$ok} {
1505            set shortcmit $cmit
1506            if {[string length $shortcmit] > 80} {
1507                set shortcmit "[string range $shortcmit 0 80]..."
1508            }
1509            error_popup "[mc "Can't parse git log output:"] {$shortcmit}"
1510            exit 1
1511        }
1512        set id [lindex $ids 0]
1513        set vid $view,$id
1514
1515        lappend vshortids($view,[string range $id 0 3]) $id
1516
1517        if {!$listed && $updating && ![info exists varcid($vid)] &&
1518            $vfilelimit($view) ne {}} {
1519            # git log doesn't rewrite parents for unlisted commits
1520            # when doing path limiting, so work around that here
1521            # by working out the rewritten parent with git rev-list
1522            # and if we already know about it, using the rewritten
1523            # parent as a substitute parent for $id's children.
1524            if {![catch {
1525                set rwid [exec git rev-list --first-parent --max-count=1 \
1526                              $id -- $vfilelimit($view)]
1527            }]} {
1528                if {$rwid ne {} && [info exists varcid($view,$rwid)]} {
1529                    # use $rwid in place of $id
1530                    rewrite_commit $view $id $rwid
1531                    continue
1532                }
1533            }
1534        }
1535
1536        set a 0
1537        if {[info exists varcid($vid)]} {
1538            if {$cmitlisted($vid) || !$listed} continue
1539            set a $varcid($vid)
1540        }
1541        if {$listed} {
1542            set olds [lrange $ids 1 end]
1543        } else {
1544            set olds {}
1545        }
1546        set commitdata($id) [string range $cmit [expr {$j + 1}] end]
1547        set cmitlisted($vid) $listed
1548        set parents($vid) $olds
1549        if {![info exists children($vid)]} {
1550            set children($vid) {}
1551        } elseif {$a == 0 && [llength $children($vid)] == 1} {
1552            set k [lindex $children($vid) 0]
1553            if {[llength $parents($view,$k)] == 1 &&
1554                (!$vdatemode($view) ||
1555                 $varcid($view,$k) == [llength $varctok($view)] - 1)} {
1556                set a $varcid($view,$k)
1557            }
1558        }
1559        if {$a == 0} {
1560            # new arc
1561            set a [newvarc $view $id]
1562        }
1563        if {[string compare [lindex $varctok($view) $a] $vtokmod($view)] < 0} {
1564            modify_arc $view $a
1565        }
1566        if {![info exists varcid($vid)]} {
1567            set varcid($vid) $a
1568            lappend varccommits($view,$a) $id
1569            incr commitidx($view)
1570        }
1571
1572        set i 0
1573        foreach p $olds {
1574            if {$i == 0 || [lsearch -exact $olds $p] >= $i} {
1575                set vp $view,$p
1576                if {[llength [lappend children($vp) $id]] > 1 &&
1577                    [vtokcmp $view [lindex $children($vp) end-1] $id] > 0} {
1578                    set children($vp) [lsort -command [list vtokcmp $view] \
1579                                           $children($vp)]
1580                    catch {unset ordertok}
1581                }
1582                if {[info exists varcid($view,$p)]} {
1583                    fix_reversal $p $a $view
1584                }
1585            }
1586            incr i
1587        }
1588
1589        set scripts [check_interest $id $scripts]
1590        set gotsome 1
1591    }
1592    if {$gotsome} {
1593        global numcommits hlview
1594
1595        if {$view == $curview} {
1596            set numcommits $commitidx($view)
1597            run chewcommits
1598        }
1599        if {[info exists hlview] && $view == $hlview} {
1600            # we never actually get here...
1601            run vhighlightmore
1602        }
1603        foreach s $scripts {
1604            eval $s
1605        }
1606    }
1607    return 2
1608}
1609
1610proc chewcommits {} {
1611    global curview hlview viewcomplete
1612    global pending_select
1613
1614    layoutmore
1615    if {$viewcomplete($curview)} {
1616        global commitidx varctok
1617        global numcommits startmsecs
1618
1619        if {[info exists pending_select]} {
1620            update
1621            reset_pending_select {}
1622
1623            if {[commitinview $pending_select $curview]} {
1624                selectline [rowofcommit $pending_select] 1
1625            } else {
1626                set row [first_real_row]
1627                selectline $row 1
1628            }
1629        }
1630        if {$commitidx($curview) > 0} {
1631            #set ms [expr {[clock clicks -milliseconds] - $startmsecs}]
1632            #puts "overall $ms ms for $numcommits commits"
1633            #puts "[llength $varctok($view)] arcs, $commitidx($view) commits"
1634        } else {
1635            show_status [mc "No commits selected"]
1636        }
1637        notbusy layout
1638    }
1639    return 0
1640}
1641
1642proc do_readcommit {id} {
1643    global tclencoding
1644
1645    # Invoke git-log to handle automatic encoding conversion
1646    set fd [open [concat | git log --no-color --pretty=raw -1 $id] r]
1647    # Read the results using i18n.logoutputencoding
1648    fconfigure $fd -translation lf -eofchar {}
1649    if {$tclencoding != {}} {
1650        fconfigure $fd -encoding $tclencoding
1651    }
1652    set contents [read $fd]
1653    close $fd
1654    # Remove the heading line
1655    regsub {^commit [0-9a-f]+\n} $contents {} contents
1656
1657    return $contents
1658}
1659
1660proc readcommit {id} {
1661    if {[catch {set contents [do_readcommit $id]}]} return
1662    parsecommit $id $contents 1
1663}
1664
1665proc parsecommit {id contents listed} {
1666    global commitinfo
1667
1668    set inhdr 1
1669    set comment {}
1670    set headline {}
1671    set auname {}
1672    set audate {}
1673    set comname {}
1674    set comdate {}
1675    set hdrend [string first "\n\n" $contents]
1676    if {$hdrend < 0} {
1677        # should never happen...
1678        set hdrend [string length $contents]
1679    }
1680    set header [string range $contents 0 [expr {$hdrend - 1}]]
1681    set comment [string range $contents [expr {$hdrend + 2}] end]
1682    foreach line [split $header "\n"] {
1683        set line [split $line " "]
1684        set tag [lindex $line 0]
1685        if {$tag == "author"} {
1686            set audate [lrange $line end-1 end]
1687            set auname [join [lrange $line 1 end-2] " "]
1688        } elseif {$tag == "committer"} {
1689            set comdate [lrange $line end-1 end]
1690            set comname [join [lrange $line 1 end-2] " "]
1691        }
1692    }
1693    set headline {}
1694    # take the first non-blank line of the comment as the headline
1695    set headline [string trimleft $comment]
1696    set i [string first "\n" $headline]
1697    if {$i >= 0} {
1698        set headline [string range $headline 0 $i]
1699    }
1700    set headline [string trimright $headline]
1701    set i [string first "\r" $headline]
1702    if {$i >= 0} {
1703        set headline [string trimright [string range $headline 0 $i]]
1704    }
1705    if {!$listed} {
1706        # git log indents the comment by 4 spaces;
1707        # if we got this via git cat-file, add the indentation
1708        set newcomment {}
1709        foreach line [split $comment "\n"] {
1710            append newcomment "    "
1711            append newcomment $line
1712            append newcomment "\n"
1713        }
1714        set comment $newcomment
1715    }
1716    set hasnote [string first "\nNotes:\n" $contents]
1717    set diff ""
1718    # If there is diff output shown in the git-log stream, split it
1719    # out.  But get rid of the empty line that always precedes the
1720    # diff.
1721    set i [string first "\n\ndiff" $comment]
1722    if {$i >= 0} {
1723        set diff [string range $comment $i+1 end]
1724        set comment [string range $comment 0 $i-1]
1725    }
1726    set commitinfo($id) [list $headline $auname $audate \
1727                             $comname $comdate $comment $hasnote $diff]
1728}
1729
1730proc getcommit {id} {
1731    global commitdata commitinfo
1732
1733    if {[info exists commitdata($id)]} {
1734        parsecommit $id $commitdata($id) 1
1735    } else {
1736        readcommit $id
1737        if {![info exists commitinfo($id)]} {
1738            set commitinfo($id) [list [mc "No commit information available"]]
1739        }
1740    }
1741    return 1
1742}
1743
1744# Expand an abbreviated commit ID to a list of full 40-char IDs that match
1745# and are present in the current view.
1746# This is fairly slow...
1747proc longid {prefix} {
1748    global varcid curview vshortids
1749
1750    set ids {}
1751    if {[string length $prefix] >= 4} {
1752        set vshortid $curview,[string range $prefix 0 3]
1753        if {[info exists vshortids($vshortid)]} {
1754            foreach id $vshortids($vshortid) {
1755                if {[string match "$prefix*" $id]} {
1756                    if {[lsearch -exact $ids $id] < 0} {
1757                        lappend ids $id
1758                        if {[llength $ids] >= 2} break
1759                    }
1760                }
1761            }
1762        }
1763    } else {
1764        foreach match [array names varcid "$curview,$prefix*"] {
1765            lappend ids [lindex [split $match ","] 1]
1766            if {[llength $ids] >= 2} break
1767        }
1768    }
1769    return $ids
1770}
1771
1772proc readrefs {} {
1773    global tagids idtags headids idheads tagobjid
1774    global otherrefids idotherrefs mainhead mainheadid
1775    global selecthead selectheadid
1776    global hideremotes
1777
1778    foreach v {tagids idtags headids idheads otherrefids idotherrefs} {
1779        catch {unset $v}
1780    }
1781    set refd [open [list | git show-ref -d] r]
1782    while {[gets $refd line] >= 0} {
1783        if {[string index $line 40] ne " "} continue
1784        set id [string range $line 0 39]
1785        set ref [string range $line 41 end]
1786        if {![string match "refs/*" $ref]} continue
1787        set name [string range $ref 5 end]
1788        if {[string match "remotes/*" $name]} {
1789            if {![string match "*/HEAD" $name] && !$hideremotes} {
1790                set headids($name) $id
1791                lappend idheads($id) $name
1792            }
1793        } elseif {[string match "heads/*" $name]} {
1794            set name [string range $name 6 end]
1795            set headids($name) $id
1796            lappend idheads($id) $name
1797        } elseif {[string match "tags/*" $name]} {
1798            # this lets refs/tags/foo^{} overwrite refs/tags/foo,
1799            # which is what we want since the former is the commit ID
1800            set name [string range $name 5 end]
1801            if {[string match "*^{}" $name]} {
1802                set name [string range $name 0 end-3]
1803            } else {
1804                set tagobjid($name) $id
1805            }
1806            set tagids($name) $id
1807            lappend idtags($id) $name
1808        } else {
1809            set otherrefids($name) $id
1810            lappend idotherrefs($id) $name
1811        }
1812    }
1813    catch {close $refd}
1814    set mainhead {}
1815    set mainheadid {}
1816    catch {
1817        set mainheadid [exec git rev-parse HEAD]
1818        set thehead [exec git symbolic-ref HEAD]
1819        if {[string match "refs/heads/*" $thehead]} {
1820            set mainhead [string range $thehead 11 end]
1821        }
1822    }
1823    set selectheadid {}
1824    if {$selecthead ne {}} {
1825        catch {
1826            set selectheadid [exec git rev-parse --verify $selecthead]
1827        }
1828    }
1829}
1830
1831# skip over fake commits
1832proc first_real_row {} {
1833    global nullid nullid2 numcommits
1834
1835    for {set row 0} {$row < $numcommits} {incr row} {
1836        set id [commitonrow $row]
1837        if {$id ne $nullid && $id ne $nullid2} {
1838            break
1839        }
1840    }
1841    return $row
1842}
1843
1844# update things for a head moved to a child of its previous location
1845proc movehead {id name} {
1846    global headids idheads
1847
1848    removehead $headids($name) $name
1849    set headids($name) $id
1850    lappend idheads($id) $name
1851}
1852
1853# update things when a head has been removed
1854proc removehead {id name} {
1855    global headids idheads
1856
1857    if {$idheads($id) eq $name} {
1858        unset idheads($id)
1859    } else {
1860        set i [lsearch -exact $idheads($id) $name]
1861        if {$i >= 0} {
1862            set idheads($id) [lreplace $idheads($id) $i $i]
1863        }
1864    }
1865    unset headids($name)
1866}
1867
1868proc ttk_toplevel {w args} {
1869    global use_ttk
1870    eval [linsert $args 0 ::toplevel $w]
1871    if {$use_ttk} {
1872        place [ttk::frame $w._toplevel_background] -x 0 -y 0 -relwidth 1 -relheight 1
1873    }
1874    return $w
1875}
1876
1877proc make_transient {window origin} {
1878    global have_tk85
1879
1880    # In MacOS Tk 8.4 transient appears to work by setting
1881    # overrideredirect, which is utterly useless, since the
1882    # windows get no border, and are not even kept above
1883    # the parent.
1884    if {!$have_tk85 && [tk windowingsystem] eq {aqua}} return
1885
1886    wm transient $window $origin
1887
1888    # Windows fails to place transient windows normally, so
1889    # schedule a callback to center them on the parent.
1890    if {[tk windowingsystem] eq {win32}} {
1891        after idle [list tk::PlaceWindow $window widget $origin]
1892    }
1893}
1894
1895proc show_error {w top msg {mc mc}} {
1896    global NS
1897    if {![info exists NS]} {set NS ""}
1898    if {[wm state $top] eq "withdrawn"} { wm deiconify $top }
1899    message $w.m -text $msg -justify center -aspect 400
1900    pack $w.m -side top -fill x -padx 20 -pady 20
1901    ${NS}::button $w.ok -default active -text [$mc OK] -command "destroy $top"
1902    pack $w.ok -side bottom -fill x
1903    bind $top <Visibility> "grab $top; focus $top"
1904    bind $top <Key-Return> "destroy $top"
1905    bind $top <Key-space>  "destroy $top"
1906    bind $top <Key-Escape> "destroy $top"
1907    tkwait window $top
1908}
1909
1910proc error_popup {msg {owner .}} {
1911    if {[tk windowingsystem] eq "win32"} {
1912        tk_messageBox -icon error -type ok -title [wm title .] \
1913            -parent $owner -message $msg
1914    } else {
1915        set w .error
1916        ttk_toplevel $w
1917        make_transient $w $owner
1918        show_error $w $w $msg
1919    }
1920}
1921
1922proc confirm_popup {msg {owner .}} {
1923    global confirm_ok NS
1924    set confirm_ok 0
1925    set w .confirm
1926    ttk_toplevel $w
1927    make_transient $w $owner
1928    message $w.m -text $msg -justify center -aspect 400
1929    pack $w.m -side top -fill x -padx 20 -pady 20
1930    ${NS}::button $w.ok -text [mc OK] -command "set confirm_ok 1; destroy $w"
1931    pack $w.ok -side left -fill x
1932    ${NS}::button $w.cancel -text [mc Cancel] -command "destroy $w"
1933    pack $w.cancel -side right -fill x
1934    bind $w <Visibility> "grab $w; focus $w"
1935    bind $w <Key-Return> "set confirm_ok 1; destroy $w"
1936    bind $w <Key-space>  "set confirm_ok 1; destroy $w"
1937    bind $w <Key-Escape> "destroy $w"
1938    tk::PlaceWindow $w widget $owner
1939    tkwait window $w
1940    return $confirm_ok
1941}
1942
1943proc setoptions {} {
1944    if {[tk windowingsystem] ne "win32"} {
1945        option add *Panedwindow.showHandle 1 startupFile
1946        option add *Panedwindow.sashRelief raised startupFile
1947        if {[tk windowingsystem] ne "aqua"} {
1948            option add *Menu.font uifont startupFile
1949        }
1950    } else {
1951        option add *Menu.TearOff 0 startupFile
1952    }
1953    option add *Button.font uifont startupFile
1954    option add *Checkbutton.font uifont startupFile
1955    option add *Radiobutton.font uifont startupFile
1956    option add *Menubutton.font uifont startupFile
1957    option add *Label.font uifont startupFile
1958    option add *Message.font uifont startupFile
1959    option add *Entry.font textfont startupFile
1960    option add *Text.font textfont startupFile
1961    option add *Labelframe.font uifont startupFile
1962    option add *Spinbox.font textfont startupFile
1963    option add *Listbox.font mainfont startupFile
1964}
1965
1966# Make a menu and submenus.
1967# m is the window name for the menu, items is the list of menu items to add.
1968# Each item is a list {mc label type description options...}
1969# mc is ignored; it's so we can put mc there to alert xgettext
1970# label is the string that appears in the menu
1971# type is cascade, command or radiobutton (should add checkbutton)
1972# description depends on type; it's the sublist for cascade, the
1973# command to invoke for command, or {variable value} for radiobutton
1974proc makemenu {m items} {
1975    menu $m
1976    if {[tk windowingsystem] eq {aqua}} {
1977        set Meta1 Cmd
1978    } else {
1979        set Meta1 Ctrl
1980    }
1981    foreach i $items {
1982        set name [mc [lindex $i 1]]
1983        set type [lindex $i 2]
1984        set thing [lindex $i 3]
1985        set params [list $type]
1986        if {$name ne {}} {
1987            set u [string first "&" [string map {&& x} $name]]
1988            lappend params -label [string map {&& & & {}} $name]
1989            if {$u >= 0} {
1990                lappend params -underline $u
1991            }
1992        }
1993        switch -- $type {
1994            "cascade" {
1995                set submenu [string tolower [string map {& ""} [lindex $i 1]]]
1996                lappend params -menu $m.$submenu
1997            }
1998            "command" {
1999                lappend params -command $thing
2000            }
2001            "radiobutton" {
2002                lappend params -variable [lindex $thing 0] \
2003                    -value [lindex $thing 1]
2004            }
2005        }
2006        set tail [lrange $i 4 end]
2007        regsub -all {\yMeta1\y} $tail $Meta1 tail
2008        eval $m add $params $tail
2009        if {$type eq "cascade"} {
2010            makemenu $m.$submenu $thing
2011        }
2012    }
2013}
2014
2015# translate string and remove ampersands
2016proc mca {str} {
2017    return [string map {&& & & {}} [mc $str]]
2018}
2019
2020proc cleardropsel {w} {
2021    $w selection clear
2022}
2023proc makedroplist {w varname args} {
2024    global use_ttk
2025    if {$use_ttk} {
2026        set width 0
2027        foreach label $args {
2028            set cx [string length $label]
2029            if {$cx > $width} {set width $cx}
2030        }
2031        set gm [ttk::combobox $w -width $width -state readonly\
2032                    -textvariable $varname -values $args \
2033                    -exportselection false]
2034        bind $gm <<ComboboxSelected>> [list $gm selection clear]
2035    } else {
2036        set gm [eval [linsert $args 0 tk_optionMenu $w $varname]]
2037    }
2038    return $gm
2039}
2040
2041proc makewindow {} {
2042    global canv canv2 canv3 linespc charspc ctext cflist cscroll
2043    global tabstop
2044    global findtype findtypemenu findloc findstring fstring geometry
2045    global entries sha1entry sha1string sha1but
2046    global diffcontextstring diffcontext
2047    global ignorespace
2048    global maincursor textcursor curtextcursor
2049    global rowctxmenu fakerowmenu mergemax wrapcomment
2050    global highlight_files gdttype
2051    global searchstring sstring
2052    global bgcolor fgcolor bglist fglist diffcolors selectbgcolor
2053    global uifgcolor uifgdisabledcolor
2054    global filesepbgcolor filesepfgcolor
2055    global mergecolors foundbgcolor currentsearchhitbgcolor
2056    global headctxmenu progresscanv progressitem progresscoords statusw
2057    global fprogitem fprogcoord lastprogupdate progupdatepending
2058    global rprogitem rprogcoord rownumsel numcommits
2059    global have_tk85 use_ttk NS
2060    global git_version
2061    global worddiff
2062
2063    # The "mc" arguments here are purely so that xgettext
2064    # sees the following string as needing to be translated
2065    set file {
2066        mc "File" cascade {
2067            {mc "Update" command updatecommits -accelerator F5}
2068            {mc "Reload" command reloadcommits -accelerator Shift-F5}
2069            {mc "Reread references" command rereadrefs}
2070            {mc "List references" command showrefs -accelerator F2}
2071            {xx "" separator}
2072            {mc "Start git gui" command {exec git gui &}}
2073            {xx "" separator}
2074            {mc "Quit" command doquit -accelerator Meta1-Q}
2075        }}
2076    set edit {
2077        mc "Edit" cascade {
2078            {mc "Preferences" command doprefs}
2079        }}
2080    set view {
2081        mc "View" cascade {
2082            {mc "New view..." command {newview 0} -accelerator Shift-F4}
2083            {mc "Edit view..." command editview -state disabled -accelerator F4}
2084            {mc "Delete view" command delview -state disabled}
2085            {xx "" separator}
2086            {mc "All files" radiobutton {selectedview 0} -command {showview 0}}
2087        }}
2088    if {[tk windowingsystem] ne "aqua"} {
2089        set help {
2090        mc "Help" cascade {
2091            {mc "About gitk" command about}
2092            {mc "Key bindings" command keys}
2093        }}
2094        set bar [list $file $edit $view $help]
2095    } else {
2096        proc ::tk::mac::ShowPreferences {} {doprefs}
2097        proc ::tk::mac::Quit {} {doquit}
2098        lset file end [lreplace [lindex $file end] end-1 end]
2099        set apple {
2100        xx "Apple" cascade {
2101            {mc "About gitk" command about}
2102            {xx "" separator}
2103        }}
2104        set help {
2105        mc "Help" cascade {
2106            {mc "Key bindings" command keys}
2107        }}
2108        set bar [list $apple $file $view $help]
2109    }
2110    makemenu .bar $bar
2111    . configure -menu .bar
2112
2113    if {$use_ttk} {
2114        # cover the non-themed toplevel with a themed frame.
2115        place [ttk::frame ._main_background] -x 0 -y 0 -relwidth 1 -relheight 1
2116    }
2117
2118    # the gui has upper and lower half, parts of a paned window.
2119    ${NS}::panedwindow .ctop -orient vertical
2120
2121    # possibly use assumed geometry
2122    if {![info exists geometry(pwsash0)]} {
2123        set geometry(topheight) [expr {15 * $linespc}]
2124        set geometry(topwidth) [expr {80 * $charspc}]
2125        set geometry(botheight) [expr {15 * $linespc}]
2126        set geometry(botwidth) [expr {50 * $charspc}]
2127        set geometry(pwsash0) [list [expr {40 * $charspc}] 2]
2128        set geometry(pwsash1) [list [expr {60 * $charspc}] 2]
2129    }
2130
2131    # the upper half will have a paned window, a scroll bar to the right, and some stuff below
2132    ${NS}::frame .tf -height $geometry(topheight) -width $geometry(topwidth)
2133    ${NS}::frame .tf.histframe
2134    ${NS}::panedwindow .tf.histframe.pwclist -orient horizontal
2135    if {!$use_ttk} {
2136        .tf.histframe.pwclist configure -sashpad 0 -handlesize 4
2137    }
2138
2139    # create three canvases
2140    set cscroll .tf.histframe.csb
2141    set canv .tf.histframe.pwclist.canv
2142    canvas $canv \
2143        -selectbackground $selectbgcolor \
2144        -background $bgcolor -bd 0 \
2145        -yscrollincr $linespc -yscrollcommand "scrollcanv $cscroll"
2146    .tf.histframe.pwclist add $canv
2147    set canv2 .tf.histframe.pwclist.canv2
2148    canvas $canv2 \
2149        -selectbackground $selectbgcolor \
2150        -background $bgcolor -bd 0 -yscrollincr $linespc
2151    .tf.histframe.pwclist add $canv2
2152    set canv3 .tf.histframe.pwclist.canv3
2153    canvas $canv3 \
2154        -selectbackground $selectbgcolor \
2155        -background $bgcolor -bd 0 -yscrollincr $linespc
2156    .tf.histframe.pwclist add $canv3
2157    if {$use_ttk} {
2158        bind .tf.histframe.pwclist <Map> {
2159            bind %W <Map> {}
2160            .tf.histframe.pwclist sashpos 1 [lindex $::geometry(pwsash1) 0]
2161            .tf.histframe.pwclist sashpos 0 [lindex $::geometry(pwsash0) 0]
2162        }
2163    } else {
2164        eval .tf.histframe.pwclist sash place 0 $geometry(pwsash0)
2165        eval .tf.histframe.pwclist sash place 1 $geometry(pwsash1)
2166    }
2167
2168    # a scroll bar to rule them
2169    ${NS}::scrollbar $cscroll -command {allcanvs yview}
2170    if {!$use_ttk} {$cscroll configure -highlightthickness 0}
2171    pack $cscroll -side right -fill y
2172    bind .tf.histframe.pwclist <Configure> {resizeclistpanes %W %w}
2173    lappend bglist $canv $canv2 $canv3
2174    pack .tf.histframe.pwclist -fill both -expand 1 -side left
2175
2176    # we have two button bars at bottom of top frame. Bar 1
2177    ${NS}::frame .tf.bar
2178    ${NS}::frame .tf.lbar -height 15
2179
2180    set sha1entry .tf.bar.sha1
2181    set entries $sha1entry
2182    set sha1but .tf.bar.sha1label
2183    button $sha1but -text "[mc "SHA1 ID:"] " -state disabled -relief flat \
2184        -command gotocommit -width 8
2185    $sha1but conf -disabledforeground [$sha1but cget -foreground]
2186    pack .tf.bar.sha1label -side left
2187    ${NS}::entry $sha1entry -width 40 -font textfont -textvariable sha1string
2188    trace add variable sha1string write sha1change
2189    pack $sha1entry -side left -pady 2
2190
2191    set bm_left_data {
2192        #define left_width 16
2193        #define left_height 16
2194        static unsigned char left_bits[] = {
2195        0x00, 0x00, 0xc0, 0x01, 0xe0, 0x00, 0x70, 0x00, 0x38, 0x00, 0x1c, 0x00,
2196        0x0e, 0x00, 0xff, 0x7f, 0xff, 0x7f, 0xff, 0x7f, 0x0e, 0x00, 0x1c, 0x00,
2197        0x38, 0x00, 0x70, 0x00, 0xe0, 0x00, 0xc0, 0x01};
2198    }
2199    set bm_right_data {
2200        #define right_width 16
2201        #define right_height 16
2202        static unsigned char right_bits[] = {
2203        0x00, 0x00, 0xc0, 0x01, 0x80, 0x03, 0x00, 0x07, 0x00, 0x0e, 0x00, 0x1c,
2204        0x00, 0x38, 0xff, 0x7f, 0xff, 0x7f, 0xff, 0x7f, 0x00, 0x38, 0x00, 0x1c,
2205        0x00, 0x0e, 0x00, 0x07, 0x80, 0x03, 0xc0, 0x01};
2206    }
2207    image create bitmap bm-left -data $bm_left_data -foreground $uifgcolor
2208    image create bitmap bm-left-gray -data $bm_left_data -foreground $uifgdisabledcolor
2209    image create bitmap bm-right -data $bm_right_data -foreground $uifgcolor
2210    image create bitmap bm-right-gray -data $bm_right_data -foreground $uifgdisabledcolor
2211
2212    ${NS}::button .tf.bar.leftbut -command goback -state disabled -width 26
2213    if {$use_ttk} {
2214        .tf.bar.leftbut configure -image [list bm-left disabled bm-left-gray]
2215    } else {
2216        .tf.bar.leftbut configure -image bm-left
2217    }
2218    pack .tf.bar.leftbut -side left -fill y
2219    ${NS}::button .tf.bar.rightbut -command goforw -state disabled -width 26
2220    if {$use_ttk} {
2221        .tf.bar.rightbut configure -image [list bm-right disabled bm-right-gray]
2222    } else {
2223        .tf.bar.rightbut configure -image bm-right
2224    }
2225    pack .tf.bar.rightbut -side left -fill y
2226
2227    ${NS}::label .tf.bar.rowlabel -text [mc "Row"]
2228    set rownumsel {}
2229    ${NS}::label .tf.bar.rownum -width 7 -textvariable rownumsel \
2230        -relief sunken -anchor e
2231    ${NS}::label .tf.bar.rowlabel2 -text "/"
2232    ${NS}::label .tf.bar.numcommits -width 7 -textvariable numcommits \
2233        -relief sunken -anchor e
2234    pack .tf.bar.rowlabel .tf.bar.rownum .tf.bar.rowlabel2 .tf.bar.numcommits \
2235        -side left
2236    if {!$use_ttk} {
2237        foreach w {rownum numcommits} {.tf.bar.$w configure -font textfont}
2238    }
2239    global selectedline
2240    trace add variable selectedline write selectedline_change
2241
2242    # Status label and progress bar
2243    set statusw .tf.bar.status
2244    ${NS}::label $statusw -width 15 -relief sunken
2245    pack $statusw -side left -padx 5
2246    if {$use_ttk} {
2247        set progresscanv [ttk::progressbar .tf.bar.progress]
2248    } else {
2249        set h [expr {[font metrics uifont -linespace] + 2}]
2250        set progresscanv .tf.bar.progress
2251        canvas $progresscanv -relief sunken -height $h -borderwidth 2
2252        set progressitem [$progresscanv create rect -1 0 0 $h -fill green]
2253        set fprogitem [$progresscanv create rect -1 0 0 $h -fill yellow]
2254        set rprogitem [$progresscanv create rect -1 0 0 $h -fill red]
2255    }
2256    pack $progresscanv -side right -expand 1 -fill x -padx {0 2}
2257    set progresscoords {0 0}
2258    set fprogcoord 0
2259    set rprogcoord 0
2260    bind $progresscanv <Configure> adjustprogress
2261    set lastprogupdate [clock clicks -milliseconds]
2262    set progupdatepending 0
2263
2264    # build up the bottom bar of upper window
2265    ${NS}::label .tf.lbar.flabel -text "[mc "Find"] "
2266
2267    set bm_down_data {
2268        #define down_width 16
2269        #define down_height 16
2270        static unsigned char down_bits[] = {
2271        0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01,
2272        0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01,
2273        0x87, 0xe1, 0x8e, 0x71, 0x9c, 0x39, 0xb8, 0x1d,
2274        0xf0, 0x0f, 0xe0, 0x07, 0xc0, 0x03, 0x80, 0x01};
2275    }
2276    image create bitmap bm-down -data $bm_down_data -foreground $uifgcolor
2277    ${NS}::button .tf.lbar.fnext -width 26 -command {dofind 1 1}
2278    .tf.lbar.fnext configure -image bm-down
2279
2280    set bm_up_data {
2281        #define up_width 16
2282        #define up_height 16
2283        static unsigned char up_bits[] = {
2284        0x80, 0x01, 0xc0, 0x03, 0xe0, 0x07, 0xf0, 0x0f,
2285        0xb8, 0x1d, 0x9c, 0x39, 0x8e, 0x71, 0x87, 0xe1,
2286        0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01,
2287        0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01};
2288    }
2289    image create bitmap bm-up -data $bm_up_data -foreground $uifgcolor
2290    ${NS}::button .tf.lbar.fprev -width 26 -command {dofind -1 1}
2291    .tf.lbar.fprev configure -image bm-up
2292
2293    ${NS}::label .tf.lbar.flab2 -text " [mc "commit"] "
2294
2295    pack .tf.lbar.flabel .tf.lbar.fnext .tf.lbar.fprev .tf.lbar.flab2 \
2296        -side left -fill y
2297    set gdttype [mc "containing:"]
2298    set gm [makedroplist .tf.lbar.gdttype gdttype \
2299                [mc "containing:"] \
2300                [mc "touching paths:"] \
2301                [mc "adding/removing string:"] \
2302                [mc "changing lines matching:"]]
2303    trace add variable gdttype write gdttype_change
2304    pack .tf.lbar.gdttype -side left -fill y
2305
2306    set findstring {}
2307    set fstring .tf.lbar.findstring
2308    lappend entries $fstring
2309    ${NS}::entry $fstring -width 30 -textvariable findstring
2310    trace add variable findstring write find_change
2311    set findtype [mc "Exact"]
2312    set findtypemenu [makedroplist .tf.lbar.findtype \
2313                          findtype [mc "Exact"] [mc "IgnCase"] [mc "Regexp"]]
2314    trace add variable findtype write findcom_change
2315    set findloc [mc "All fields"]
2316    makedroplist .tf.lbar.findloc findloc [mc "All fields"] [mc "Headline"] \
2317        [mc "Comments"] [mc "Author"] [mc "Committer"]
2318    trace add variable findloc write find_change
2319    pack .tf.lbar.findloc -side right
2320    pack .tf.lbar.findtype -side right
2321    pack $fstring -side left -expand 1 -fill x
2322
2323    # Finish putting the upper half of the viewer together
2324    pack .tf.lbar -in .tf -side bottom -fill x
2325    pack .tf.bar -in .tf -side bottom -fill x
2326    pack .tf.histframe -fill both -side top -expand 1
2327    .ctop add .tf
2328    if {!$use_ttk} {
2329        .ctop paneconfigure .tf -height $geometry(topheight)
2330        .ctop paneconfigure .tf -width $geometry(topwidth)
2331    }
2332
2333    # now build up the bottom
2334    ${NS}::panedwindow .pwbottom -orient horizontal
2335
2336    # lower left, a text box over search bar, scroll bar to the right
2337    # if we know window height, then that will set the lower text height, otherwise
2338    # we set lower text height which will drive window height
2339    if {[info exists geometry(main)]} {
2340        ${NS}::frame .bleft -width $geometry(botwidth)
2341    } else {
2342        ${NS}::frame .bleft -width $geometry(botwidth) -height $geometry(botheight)
2343    }
2344    ${NS}::frame .bleft.top
2345    ${NS}::frame .bleft.mid
2346    ${NS}::frame .bleft.bottom
2347
2348    ${NS}::button .bleft.top.search -text [mc "Search"] -command dosearch
2349    pack .bleft.top.search -side left -padx 5
2350    set sstring .bleft.top.sstring
2351    set searchstring ""
2352    ${NS}::entry $sstring -width 20 -textvariable searchstring
2353    lappend entries $sstring
2354    trace add variable searchstring write incrsearch
2355    pack $sstring -side left -expand 1 -fill x
2356    ${NS}::radiobutton .bleft.mid.diff -text [mc "Diff"] \
2357        -command changediffdisp -variable diffelide -value {0 0}
2358    ${NS}::radiobutton .bleft.mid.old -text [mc "Old version"] \
2359        -command changediffdisp -variable diffelide -value {0 1}
2360    ${NS}::radiobutton .bleft.mid.new -text [mc "New version"] \
2361        -command changediffdisp -variable diffelide -value {1 0}
2362    ${NS}::label .bleft.mid.labeldiffcontext -text "      [mc "Lines of context"]: "
2363    pack .bleft.mid.diff .bleft.mid.old .bleft.mid.new -side left
2364    spinbox .bleft.mid.diffcontext -width 5 \
2365        -from 0 -increment 1 -to 10000000 \
2366        -validate all -validatecommand "diffcontextvalidate %P" \
2367        -textvariable diffcontextstring
2368    .bleft.mid.diffcontext set $diffcontext
2369    trace add variable diffcontextstring write diffcontextchange
2370    lappend entries .bleft.mid.diffcontext
2371    pack .bleft.mid.labeldiffcontext .bleft.mid.diffcontext -side left
2372    ${NS}::checkbutton .bleft.mid.ignspace -text [mc "Ignore space change"] \
2373        -command changeignorespace -variable ignorespace
2374    pack .bleft.mid.ignspace -side left -padx 5
2375
2376    set worddiff [mc "Line diff"]
2377    if {[package vcompare $git_version "1.7.2"] >= 0} {
2378        makedroplist .bleft.mid.worddiff worddiff [mc "Line diff"] \
2379            [mc "Markup words"] [mc "Color words"]
2380        trace add variable worddiff write changeworddiff
2381        pack .bleft.mid.worddiff -side left -padx 5
2382    }
2383
2384    set ctext .bleft.bottom.ctext
2385    text $ctext -background $bgcolor -foreground $fgcolor \
2386        -state disabled -font textfont \
2387        -yscrollcommand scrolltext -wrap none \
2388        -xscrollcommand ".bleft.bottom.sbhorizontal set"
2389    if {$have_tk85} {
2390        $ctext conf -tabstyle wordprocessor
2391    }
2392    ${NS}::scrollbar .bleft.bottom.sb -command "$ctext yview"
2393    ${NS}::scrollbar .bleft.bottom.sbhorizontal -command "$ctext xview" -orient h
2394    pack .bleft.top -side top -fill x
2395    pack .bleft.mid -side top -fill x
2396    grid $ctext .bleft.bottom.sb -sticky nsew
2397    grid .bleft.bottom.sbhorizontal -sticky ew
2398    grid columnconfigure .bleft.bottom 0 -weight 1
2399    grid rowconfigure .bleft.bottom 0 -weight 1
2400    grid rowconfigure .bleft.bottom 1 -weight 0
2401    pack .bleft.bottom -side top -fill both -expand 1
2402    lappend bglist $ctext
2403    lappend fglist $ctext
2404
2405    $ctext tag conf comment -wrap $wrapcomment
2406    $ctext tag conf filesep -font textfontbold -fore $filesepfgcolor -back $filesepbgcolor
2407    $ctext tag conf hunksep -fore [lindex $diffcolors 2]
2408    $ctext tag conf d0 -fore [lindex $diffcolors 0]
2409    $ctext tag conf dresult -fore [lindex $diffcolors 1]
2410    $ctext tag conf m0 -fore [lindex $mergecolors 0]
2411    $ctext tag conf m1 -fore [lindex $mergecolors 1]
2412    $ctext tag conf m2 -fore [lindex $mergecolors 2]
2413    $ctext tag conf m3 -fore [lindex $mergecolors 3]
2414    $ctext tag conf m4 -fore [lindex $mergecolors 4]
2415    $ctext tag conf m5 -fore [lindex $mergecolors 5]
2416    $ctext tag conf m6 -fore [lindex $mergecolors 6]
2417    $ctext tag conf m7 -fore [lindex $mergecolors 7]
2418    $ctext tag conf m8 -fore [lindex $mergecolors 8]
2419    $ctext tag conf m9 -fore [lindex $mergecolors 9]
2420    $ctext tag conf m10 -fore [lindex $mergecolors 10]
2421    $ctext tag conf m11 -fore [lindex $mergecolors 11]
2422    $ctext tag conf m12 -fore [lindex $mergecolors 12]
2423    $ctext tag conf m13 -fore [lindex $mergecolors 13]
2424    $ctext tag conf m14 -fore [lindex $mergecolors 14]
2425    $ctext tag conf m15 -fore [lindex $mergecolors 15]
2426    $ctext tag conf mmax -fore darkgrey
2427    set mergemax 16
2428    $ctext tag conf mresult -font textfontbold
2429    $ctext tag conf msep -font textfontbold
2430    $ctext tag conf found -back $foundbgcolor
2431    $ctext tag conf currentsearchhit -back $currentsearchhitbgcolor
2432    $ctext tag conf wwrap -wrap word -lmargin2 1c
2433    $ctext tag conf bold -font textfontbold
2434
2435    .pwbottom add .bleft
2436    if {!$use_ttk} {
2437        .pwbottom paneconfigure .bleft -width $geometry(botwidth)
2438    }
2439
2440    # lower right
2441    ${NS}::frame .bright
2442    ${NS}::frame .bright.mode
2443    ${NS}::radiobutton .bright.mode.patch -text [mc "Patch"] \
2444        -command reselectline -variable cmitmode -value "patch"
2445    ${NS}::radiobutton .bright.mode.tree -text [mc "Tree"] \
2446        -command reselectline -variable cmitmode -value "tree"
2447    grid .bright.mode.patch .bright.mode.tree -sticky ew
2448    pack .bright.mode -side top -fill x
2449    set cflist .bright.cfiles
2450    set indent [font measure mainfont "nn"]
2451    text $cflist \
2452        -selectbackground $selectbgcolor \
2453        -background $bgcolor -foreground $fgcolor \
2454        -font mainfont \
2455        -tabs [list $indent [expr {2 * $indent}]] \
2456        -yscrollcommand ".bright.sb set" \
2457        -cursor [. cget -cursor] \
2458        -spacing1 1 -spacing3 1
2459    lappend bglist $cflist
2460    lappend fglist $cflist
2461    ${NS}::scrollbar .bright.sb -command "$cflist yview"
2462    pack .bright.sb -side right -fill y
2463    pack $cflist -side left -fill both -expand 1
2464    $cflist tag configure highlight \
2465        -background [$cflist cget -selectbackground]
2466    $cflist tag configure bold -font mainfontbold
2467
2468    .pwbottom add .bright
2469    .ctop add .pwbottom
2470
2471    # restore window width & height if known
2472    if {[info exists geometry(main)]} {
2473        if {[scan $geometry(main) "%dx%d" w h] >= 2} {
2474            if {$w > [winfo screenwidth .]} {
2475                set w [winfo screenwidth .]
2476            }
2477            if {$h > [winfo screenheight .]} {
2478                set h [winfo screenheight .]
2479            }
2480            wm geometry . "${w}x$h"
2481        }
2482    }
2483
2484    if {[info exists geometry(state)] && $geometry(state) eq "zoomed"} {
2485        wm state . $geometry(state)
2486    }
2487
2488    if {[tk windowingsystem] eq {aqua}} {
2489        set M1B M1
2490        set ::BM "3"
2491    } else {
2492        set M1B Control
2493        set ::BM "2"
2494    }
2495
2496    if {$use_ttk} {
2497        bind .ctop <Map> {
2498            bind %W <Map> {}
2499            %W sashpos 0 $::geometry(topheight)
2500        }
2501        bind .pwbottom <Map> {
2502            bind %W <Map> {}
2503            %W sashpos 0 $::geometry(botwidth)
2504        }
2505    }
2506
2507    bind .pwbottom <Configure> {resizecdetpanes %W %w}
2508    pack .ctop -fill both -expand 1
2509    bindall <1> {selcanvline %W %x %y}
2510    #bindall <B1-Motion> {selcanvline %W %x %y}
2511    if {[tk windowingsystem] == "win32"} {
2512        bind . <MouseWheel> { windows_mousewheel_redirector %W %X %Y %D }
2513        bind $ctext <MouseWheel> { windows_mousewheel_redirector %W %X %Y %D ; break }
2514    } else {
2515        bindall <ButtonRelease-4> "allcanvs yview scroll -5 units"
2516        bindall <ButtonRelease-5> "allcanvs yview scroll 5 units"
2517        if {[tk windowingsystem] eq "aqua"} {
2518            bindall <MouseWheel> {
2519                set delta [expr {- (%D)}]
2520                allcanvs yview scroll $delta units
2521            }
2522            bindall <Shift-MouseWheel> {
2523                set delta [expr {- (%D)}]
2524                $canv xview scroll $delta units
2525            }
2526        }
2527    }
2528    bindall <$::BM> "canvscan mark %W %x %y"
2529    bindall <B$::BM-Motion> "canvscan dragto %W %x %y"
2530    bind all <$M1B-Key-w> {destroy [winfo toplevel %W]}
2531    bind . <$M1B-Key-w> doquit
2532    bindkey <Home> selfirstline
2533    bindkey <End> sellastline
2534    bind . <Key-Up> "selnextline -1"
2535    bind . <Key-Down> "selnextline 1"
2536    bind . <Shift-Key-Up> "dofind -1 0"
2537    bind . <Shift-Key-Down> "dofind 1 0"
2538    bindkey <Key-Right> "goforw"
2539    bindkey <Key-Left> "goback"
2540    bind . <Key-Prior> "selnextpage -1"
2541    bind . <Key-Next> "selnextpage 1"
2542    bind . <$M1B-Home> "allcanvs yview moveto 0.0"
2543    bind . <$M1B-End> "allcanvs yview moveto 1.0"
2544    bind . <$M1B-Key-Up> "allcanvs yview scroll -1 units"
2545    bind . <$M1B-Key-Down> "allcanvs yview scroll 1 units"
2546    bind . <$M1B-Key-Prior> "allcanvs yview scroll -1 pages"
2547    bind . <$M1B-Key-Next> "allcanvs yview scroll 1 pages"
2548    bindkey <Key-Delete> "$ctext yview scroll -1 pages"
2549    bindkey <Key-BackSpace> "$ctext yview scroll -1 pages"
2550    bindkey <Key-space> "$ctext yview scroll 1 pages"
2551    bindkey p "selnextline -1"
2552    bindkey n "selnextline 1"
2553    bindkey z "goback"
2554    bindkey x "goforw"
2555    bindkey k "selnextline -1"
2556    bindkey j "selnextline 1"
2557    bindkey h "goback"
2558    bindkey l "goforw"
2559    bindkey b prevfile
2560    bindkey d "$ctext yview scroll 18 units"
2561    bindkey u "$ctext yview scroll -18 units"
2562    bindkey / {focus $fstring}
2563    bindkey <Key-KP_Divide> {focus $fstring}
2564    bindkey <Key-Return> {dofind 1 1}
2565    bindkey ? {dofind -1 1}
2566    bindkey f nextfile
2567    bind . <F5> updatecommits
2568    bindmodfunctionkey Shift 5 reloadcommits
2569    bind . <F2> showrefs
2570    bindmodfunctionkey Shift 4 {newview 0}
2571    bind . <F4> edit_or_newview
2572    bind . <$M1B-q> doquit
2573    bind . <$M1B-f> {dofind 1 1}
2574    bind . <$M1B-g> {dofind 1 0}
2575    bind . <$M1B-r> dosearchback
2576    bind . <$M1B-s> dosearch
2577    bind . <$M1B-equal> {incrfont 1}
2578    bind . <$M1B-plus> {incrfont 1}
2579    bind . <$M1B-KP_Add> {incrfont 1}
2580    bind . <$M1B-minus> {incrfont -1}
2581    bind . <$M1B-KP_Subtract> {incrfont -1}
2582    wm protocol . WM_DELETE_WINDOW doquit
2583    bind . <Destroy> {stop_backends}
2584    bind . <Button-1> "click %W"
2585    bind $fstring <Key-Return> {dofind 1 1}
2586    bind $sha1entry <Key-Return> {gotocommit; break}
2587    bind $sha1entry <<PasteSelection>> clearsha1
2588    bind $sha1entry <<Paste>> clearsha1
2589    bind $cflist <1> {sel_flist %W %x %y; break}
2590    bind $cflist <B1-Motion> {sel_flist %W %x %y; break}
2591    bind $cflist <ButtonRelease-1> {treeclick %W %x %y}
2592    global ctxbut
2593    bind $cflist $ctxbut {pop_flist_menu %W %X %Y %x %y}
2594    bind $ctext $ctxbut {pop_diff_menu %W %X %Y %x %y}
2595    bind $ctext <Button-1> {focus %W}
2596    bind $ctext <<Selection>> rehighlight_search_results
2597
2598    set maincursor [. cget -cursor]
2599    set textcursor [$ctext cget -cursor]
2600    set curtextcursor $textcursor
2601
2602    set rowctxmenu .rowctxmenu
2603    makemenu $rowctxmenu {
2604        {mc "Diff this -> selected" command {diffvssel 0}}
2605        {mc "Diff selected -> this" command {diffvssel 1}}
2606        {mc "Make patch" command mkpatch}
2607        {mc "Create tag" command mktag}
2608        {mc "Write commit to file" command writecommit}
2609        {mc "Create new branch" command mkbranch}
2610        {mc "Cherry-pick this commit" command cherrypick}
2611        {mc "Reset HEAD branch to here" command resethead}
2612        {mc "Mark this commit" command markhere}
2613        {mc "Return to mark" command gotomark}
2614        {mc "Find descendant of this and mark" command find_common_desc}
2615        {mc "Compare with marked commit" command compare_commits}
2616        {mc "Diff this -> marked commit" command {diffvsmark 0}}
2617        {mc "Diff marked commit -> this" command {diffvsmark 1}}
2618        {mc "Revert this commit" command revert}
2619    }
2620    $rowctxmenu configure -tearoff 0
2621
2622    set fakerowmenu .fakerowmenu
2623    makemenu $fakerowmenu {
2624        {mc "Diff this -> selected" command {diffvssel 0}}
2625        {mc "Diff selected -> this" command {diffvssel 1}}
2626        {mc "Make patch" command mkpatch}
2627        {mc "Diff this -> marked commit" command {diffvsmark 0}}
2628        {mc "Diff marked commit -> this" command {diffvsmark 1}}
2629    }
2630    $fakerowmenu configure -tearoff 0
2631
2632    set headctxmenu .headctxmenu
2633    makemenu $headctxmenu {
2634        {mc "Check out this branch" command cobranch}
2635        {mc "Remove this branch" command rmbranch}
2636    }
2637    $headctxmenu configure -tearoff 0
2638
2639    global flist_menu
2640    set flist_menu .flistctxmenu
2641    makemenu $flist_menu {
2642        {mc "Highlight this too" command {flist_hl 0}}
2643        {mc "Highlight this only" command {flist_hl 1}}
2644        {mc "External diff" command {external_diff}}
2645        {mc "Blame parent commit" command {external_blame 1}}
2646    }
2647    $flist_menu configure -tearoff 0
2648
2649    global diff_menu
2650    set diff_menu .diffctxmenu
2651    makemenu $diff_menu {
2652        {mc "Show origin of this line" command show_line_source}
2653        {mc "Run git gui blame on this line" command {external_blame_diff}}
2654    }
2655    $diff_menu configure -tearoff 0
2656}
2657
2658# Windows sends all mouse wheel events to the current focused window, not
2659# the one where the mouse hovers, so bind those events here and redirect
2660# to the correct window
2661proc windows_mousewheel_redirector {W X Y D} {
2662    global canv canv2 canv3
2663    set w [winfo containing -displayof $W $X $Y]
2664    if {$w ne ""} {
2665        set u [expr {$D < 0 ? 5 : -5}]
2666        if {$w == $canv || $w == $canv2 || $w == $canv3} {
2667            allcanvs yview scroll $u units
2668        } else {
2669            catch {
2670                $w yview scroll $u units
2671            }
2672        }
2673    }
2674}
2675
2676# Update row number label when selectedline changes
2677proc selectedline_change {n1 n2 op} {
2678    global selectedline rownumsel
2679
2680    if {$selectedline eq {}} {
2681        set rownumsel {}
2682    } else {
2683        set rownumsel [expr {$selectedline + 1}]
2684    }
2685}
2686
2687# mouse-2 makes all windows scan vertically, but only the one
2688# the cursor is in scans horizontally
2689proc canvscan {op w x y} {
2690    global canv canv2 canv3
2691    foreach c [list $canv $canv2 $canv3] {
2692        if {$c == $w} {
2693            $c scan $op $x $y
2694        } else {
2695            $c scan $op 0 $y
2696        }
2697    }
2698}
2699
2700proc scrollcanv {cscroll f0 f1} {
2701    $cscroll set $f0 $f1
2702    drawvisible
2703    flushhighlights
2704}
2705
2706# when we make a key binding for the toplevel, make sure
2707# it doesn't get triggered when that key is pressed in the
2708# find string entry widget.
2709proc bindkey {ev script} {
2710    global entries
2711    bind . $ev $script
2712    set escript [bind Entry $ev]
2713    if {$escript == {}} {
2714        set escript [bind Entry <Key>]
2715    }
2716    foreach e $entries {
2717        bind $e $ev "$escript; break"
2718    }
2719}
2720
2721proc bindmodfunctionkey {mod n script} {
2722    bind . <$mod-F$n> $script
2723    catch { bind . <$mod-XF86_Switch_VT_$n> $script }
2724}
2725
2726# set the focus back to the toplevel for any click outside
2727# the entry widgets
2728proc click {w} {
2729    global ctext entries
2730    foreach e [concat $entries $ctext] {
2731        if {$w == $e} return
2732    }
2733    focus .
2734}
2735
2736# Adjust the progress bar for a change in requested extent or canvas size
2737proc adjustprogress {} {
2738    global progresscanv progressitem progresscoords
2739    global fprogitem fprogcoord lastprogupdate progupdatepending
2740    global rprogitem rprogcoord use_ttk
2741
2742    if {$use_ttk} {
2743        $progresscanv configure -value [expr {int($fprogcoord * 100)}]
2744        return
2745    }
2746
2747    set w [expr {[winfo width $progresscanv] - 4}]
2748    set x0 [expr {$w * [lindex $progresscoords 0]}]
2749    set x1 [expr {$w * [lindex $progresscoords 1]}]
2750    set h [winfo height $progresscanv]
2751    $progresscanv coords $progressitem $x0 0 $x1 $h
2752    $progresscanv coords $fprogitem 0 0 [expr {$w * $fprogcoord}] $h
2753    $progresscanv coords $rprogitem 0 0 [expr {$w * $rprogcoord}] $h
2754    set now [clock clicks -milliseconds]
2755    if {$now >= $lastprogupdate + 100} {
2756        set progupdatepending 0
2757        update
2758    } elseif {!$progupdatepending} {
2759        set progupdatepending 1
2760        after [expr {$lastprogupdate + 100 - $now}] doprogupdate
2761    }
2762}
2763
2764proc doprogupdate {} {
2765    global lastprogupdate progupdatepending
2766
2767    if {$progupdatepending} {
2768        set progupdatepending 0
2769        set lastprogupdate [clock clicks -milliseconds]
2770        update
2771    }
2772}
2773
2774proc savestuff {w} {
2775    global canv canv2 canv3 mainfont textfont uifont tabstop
2776    global stuffsaved findmergefiles maxgraphpct
2777    global maxwidth showneartags showlocalchanges
2778    global viewname viewfiles viewargs viewargscmd viewperm nextviewnum
2779    global cmitmode wrapcomment datetimeformat limitdiffs
2780    global colors uicolor bgcolor fgcolor diffcolors diffcontext selectbgcolor
2781    global uifgcolor uifgdisabledcolor
2782    global headbgcolor headfgcolor headoutlinecolor remotebgcolor
2783    global tagbgcolor tagfgcolor tagoutlinecolor
2784    global reflinecolor filesepbgcolor filesepfgcolor
2785    global mergecolors foundbgcolor currentsearchhitbgcolor
2786    global linehoverbgcolor linehoverfgcolor linehoveroutlinecolor circlecolors
2787    global mainheadcirclecolor workingfilescirclecolor indexcirclecolor
2788    global linkfgcolor circleoutlinecolor
2789    global autoselect autosellen extdifftool perfile_attrs markbgcolor use_ttk
2790    global hideremotes want_ttk maxrefs
2791    global config_file config_file_tmp
2792
2793    if {$stuffsaved} return
2794    if {![winfo viewable .]} return
2795    catch {
2796        if {[file exists $config_file_tmp]} {
2797            file delete -force $config_file_tmp
2798        }
2799        set f [open $config_file_tmp w]
2800        if {$::tcl_platform(platform) eq {windows}} {
2801            file attributes $config_file_tmp -hidden true
2802        }
2803        puts $f [list set mainfont $mainfont]
2804        puts $f [list set textfont $textfont]
2805        puts $f [list set uifont $uifont]
2806        puts $f [list set tabstop $tabstop]
2807        puts $f [list set findmergefiles $findmergefiles]
2808        puts $f [list set maxgraphpct $maxgraphpct]
2809        puts $f [list set maxwidth $maxwidth]
2810        puts $f [list set cmitmode $cmitmode]
2811        puts $f [list set wrapcomment $wrapcomment]
2812        puts $f [list set autoselect $autoselect]
2813        puts $f [list set autosellen $autosellen]
2814        puts $f [list set showneartags $showneartags]
2815        puts $f [list set maxrefs $maxrefs]
2816        puts $f [list set hideremotes $hideremotes]
2817        puts $f [list set showlocalchanges $showlocalchanges]
2818        puts $f [list set datetimeformat $datetimeformat]
2819        puts $f [list set limitdiffs $limitdiffs]
2820        puts $f [list set uicolor $uicolor]
2821        puts $f [list set want_ttk $want_ttk]
2822        puts $f [list set bgcolor $bgcolor]
2823        puts $f [list set fgcolor $fgcolor]
2824        puts $f [list set uifgcolor $uifgcolor]
2825        puts $f [list set uifgdisabledcolor $uifgdisabledcolor]
2826        puts $f [list set colors $colors]
2827        puts $f [list set diffcolors $diffcolors]
2828        puts $f [list set mergecolors $mergecolors]
2829        puts $f [list set markbgcolor $markbgcolor]
2830        puts $f [list set diffcontext $diffcontext]
2831        puts $f [list set selectbgcolor $selectbgcolor]
2832        puts $f [list set foundbgcolor $foundbgcolor]
2833        puts $f [list set currentsearchhitbgcolor $currentsearchhitbgcolor]
2834        puts $f [list set extdifftool $extdifftool]
2835        puts $f [list set perfile_attrs $perfile_attrs]
2836        puts $f [list set headbgcolor $headbgcolor]
2837        puts $f [list set headfgcolor $headfgcolor]
2838        puts $f [list set headoutlinecolor $headoutlinecolor]
2839        puts $f [list set remotebgcolor $remotebgcolor]
2840        puts $f [list set tagbgcolor $tagbgcolor]
2841        puts $f [list set tagfgcolor $tagfgcolor]
2842        puts $f [list set tagoutlinecolor $tagoutlinecolor]
2843        puts $f [list set reflinecolor $reflinecolor]
2844        puts $f [list set filesepbgcolor $filesepbgcolor]
2845        puts $f [list set filesepfgcolor $filesepfgcolor]
2846        puts $f [list set linehoverbgcolor $linehoverbgcolor]
2847        puts $f [list set linehoverfgcolor $linehoverfgcolor]
2848        puts $f [list set linehoveroutlinecolor $linehoveroutlinecolor]
2849        puts $f [list set mainheadcirclecolor $mainheadcirclecolor]
2850        puts $f [list set workingfilescirclecolor $workingfilescirclecolor]
2851        puts $f [list set indexcirclecolor $indexcirclecolor]
2852        puts $f [list set circlecolors $circlecolors]
2853        puts $f [list set linkfgcolor $linkfgcolor]
2854        puts $f [list set circleoutlinecolor $circleoutlinecolor]
2855
2856        puts $f "set geometry(main) [wm geometry .]"
2857        puts $f "set geometry(state) [wm state .]"
2858        puts $f "set geometry(topwidth) [winfo width .tf]"
2859        puts $f "set geometry(topheight) [winfo height .tf]"
2860        if {$use_ttk} {
2861            puts $f "set geometry(pwsash0) \"[.tf.histframe.pwclist sashpos 0] 1\""
2862            puts $f "set geometry(pwsash1) \"[.tf.histframe.pwclist sashpos 1] 1\""
2863        } else {
2864            puts $f "set geometry(pwsash0) \"[.tf.histframe.pwclist sash coord 0]\""
2865            puts $f "set geometry(pwsash1) \"[.tf.histframe.pwclist sash coord 1]\""
2866        }
2867        puts $f "set geometry(botwidth) [winfo width .bleft]"
2868        puts $f "set geometry(botheight) [winfo height .bleft]"
2869
2870        puts -nonewline $f "set permviews {"
2871        for {set v 0} {$v < $nextviewnum} {incr v} {
2872            if {$viewperm($v)} {
2873                puts $f "{[list $viewname($v) $viewfiles($v) $viewargs($v) $viewargscmd($v)]}"
2874            }
2875        }
2876        puts $f "}"
2877        close $f
2878        file rename -force $config_file_tmp $config_file
2879    }
2880    set stuffsaved 1
2881}
2882
2883proc resizeclistpanes {win w} {
2884    global oldwidth use_ttk
2885    if {[info exists oldwidth($win)]} {
2886        if {$use_ttk} {
2887            set s0 [$win sashpos 0]
2888            set s1 [$win sashpos 1]
2889        } else {
2890            set s0 [$win sash coord 0]
2891            set s1 [$win sash coord 1]
2892        }
2893        if {$w < 60} {
2894            set sash0 [expr {int($w/2 - 2)}]
2895            set sash1 [expr {int($w*5/6 - 2)}]
2896        } else {
2897            set factor [expr {1.0 * $w / $oldwidth($win)}]
2898            set sash0 [expr {int($factor * [lindex $s0 0])}]
2899            set sash1 [expr {int($factor * [lindex $s1 0])}]
2900            if {$sash0 < 30} {
2901                set sash0 30
2902            }
2903            if {$sash1 < $sash0 + 20} {
2904                set sash1 [expr {$sash0 + 20}]
2905            }
2906            if {$sash1 > $w - 10} {
2907                set sash1 [expr {$w - 10}]
2908                if {$sash0 > $sash1 - 20} {
2909                    set sash0 [expr {$sash1 - 20}]
2910                }
2911            }
2912        }
2913        if {$use_ttk} {
2914            $win sashpos 0 $sash0
2915            $win sashpos 1 $sash1
2916        } else {
2917            $win sash place 0 $sash0 [lindex $s0 1]
2918            $win sash place 1 $sash1 [lindex $s1 1]
2919        }
2920    }
2921    set oldwidth($win) $w
2922}
2923
2924proc resizecdetpanes {win w} {
2925    global oldwidth use_ttk
2926    if {[info exists oldwidth($win)]} {
2927        if {$use_ttk} {
2928            set s0 [$win sashpos 0]
2929        } else {
2930            set s0 [$win sash coord 0]
2931        }
2932        if {$w < 60} {
2933            set sash0 [expr {int($w*3/4 - 2)}]
2934        } else {
2935            set factor [expr {1.0 * $w / $oldwidth($win)}]
2936            set sash0 [expr {int($factor * [lindex $s0 0])}]
2937            if {$sash0 < 45} {
2938                set sash0 45
2939            }
2940            if {$sash0 > $w - 15} {
2941                set sash0 [expr {$w - 15}]
2942            }
2943        }
2944        if {$use_ttk} {
2945            $win sashpos 0 $sash0
2946        } else {
2947            $win sash place 0 $sash0 [lindex $s0 1]
2948        }
2949    }
2950    set oldwidth($win) $w
2951}
2952
2953proc allcanvs args {
2954    global canv canv2 canv3
2955    eval $canv $args
2956    eval $canv2 $args
2957    eval $canv3 $args
2958}
2959
2960proc bindall {event action} {
2961    global canv canv2 canv3
2962    bind $canv $event $action
2963    bind $canv2 $event $action
2964    bind $canv3 $event $action
2965}
2966
2967proc about {} {
2968    global uifont NS
2969    set w .about
2970    if {[winfo exists $w]} {
2971        raise $w
2972        return
2973    }
2974    ttk_toplevel $w
2975    wm title $w [mc "About gitk"]
2976    make_transient $w .
2977    message $w.m -text [mc "
2978Gitk - a commit viewer for git
2979
2980Copyright \u00a9 2005-2014 Paul Mackerras
2981
2982Use and redistribute under the terms of the GNU General Public License"] \
2983            -justify center -aspect 400 -border 2 -bg white -relief groove
2984    pack $w.m -side top -fill x -padx 2 -pady 2
2985    ${NS}::button $w.ok -text [mc "Close"] -command "destroy $w" -default active
2986    pack $w.ok -side bottom
2987    bind $w <Visibility> "focus $w.ok"
2988    bind $w <Key-Escape> "destroy $w"
2989    bind $w <Key-Return> "destroy $w"
2990    tk::PlaceWindow $w widget .
2991}
2992
2993proc keys {} {
2994    global NS
2995    set w .keys
2996    if {[winfo exists $w]} {
2997        raise $w
2998        return
2999    }
3000    if {[tk windowingsystem] eq {aqua}} {
3001        set M1T Cmd
3002    } else {
3003        set M1T Ctrl
3004    }
3005    ttk_toplevel $w
3006    wm title $w [mc "Gitk key bindings"]
3007    make_transient $w .
3008    message $w.m -text "
3009[mc "Gitk key bindings:"]
3010
3011[mc "<%s-Q>             Quit" $M1T]
3012[mc "<%s-W>             Close window" $M1T]
3013[mc "<Home>             Move to first commit"]
3014[mc "<End>              Move to last commit"]
3015[mc "<Up>, p, k Move up one commit"]
3016[mc "<Down>, n, j       Move down one commit"]
3017[mc "<Left>, z, h       Go back in history list"]
3018[mc "<Right>, x, l      Go forward in history list"]
3019[mc "<PageUp>   Move up one page in commit list"]
3020[mc "<PageDown> Move down one page in commit list"]
3021[mc "<%s-Home>  Scroll to top of commit list" $M1T]
3022[mc "<%s-End>   Scroll to bottom of commit list" $M1T]
3023[mc "<%s-Up>    Scroll commit list up one line" $M1T]
3024[mc "<%s-Down>  Scroll commit list down one line" $M1T]
3025[mc "<%s-PageUp>        Scroll commit list up one page" $M1T]
3026[mc "<%s-PageDown>      Scroll commit list down one page" $M1T]
3027[mc "<Shift-Up> Find backwards (upwards, later commits)"]
3028[mc "<Shift-Down>       Find forwards (downwards, earlier commits)"]
3029[mc "<Delete>, b        Scroll diff view up one page"]
3030[mc "<Backspace>        Scroll diff view up one page"]
3031[mc "<Space>            Scroll diff view down one page"]
3032[mc "u          Scroll diff view up 18 lines"]
3033[mc "d          Scroll diff view down 18 lines"]
3034[mc "<%s-F>             Find" $M1T]
3035[mc "<%s-G>             Move to next find hit" $M1T]
3036[mc "<Return>   Move to next find hit"]
3037[mc "/          Focus the search box"]
3038[mc "?          Move to previous find hit"]
3039[mc "f          Scroll diff view to next file"]
3040[mc "<%s-S>             Search for next hit in diff view" $M1T]
3041[mc "<%s-R>             Search for previous hit in diff view" $M1T]
3042[mc "<%s-KP+>   Increase font size" $M1T]
3043[mc "<%s-plus>  Increase font size" $M1T]
3044[mc "<%s-KP->   Decrease font size" $M1T]
3045[mc "<%s-minus> Decrease font size" $M1T]
3046[mc "<F5>               Update"]
3047" \
3048            -justify left -bg white -border 2 -relief groove
3049    pack $w.m -side top -fill both -padx 2 -pady 2
3050    ${NS}::button $w.ok -text [mc "Close"] -command "destroy $w" -default active
3051    bind $w <Key-Escape> [list destroy $w]
3052    pack $w.ok -side bottom
3053    bind $w <Visibility> "focus $w.ok"
3054    bind $w <Key-Escape> "destroy $w"
3055    bind $w <Key-Return> "destroy $w"
3056}
3057
3058# Procedures for manipulating the file list window at the
3059# bottom right of the overall window.
3060
3061proc treeview {w l openlevs} {
3062    global treecontents treediropen treeheight treeparent treeindex
3063
3064    set ix 0
3065    set treeindex() 0
3066    set lev 0
3067    set prefix {}
3068    set prefixend -1
3069    set prefendstack {}
3070    set htstack {}
3071    set ht 0
3072    set treecontents() {}
3073    $w conf -state normal
3074    foreach f $l {
3075        while {[string range $f 0 $prefixend] ne $prefix} {
3076            if {$lev <= $openlevs} {
3077                $w mark set e:$treeindex($prefix) "end -1c"
3078                $w mark gravity e:$treeindex($prefix) left
3079            }
3080            set treeheight($prefix) $ht
3081            incr ht [lindex $htstack end]
3082            set htstack [lreplace $htstack end end]
3083            set prefixend [lindex $prefendstack end]
3084            set prefendstack [lreplace $prefendstack end end]
3085            set prefix [string range $prefix 0 $prefixend]
3086            incr lev -1
3087        }
3088        set tail [string range $f [expr {$prefixend+1}] end]
3089        while {[set slash [string first "/" $tail]] >= 0} {
3090            lappend htstack $ht
3091            set ht 0
3092            lappend prefendstack $prefixend
3093            incr prefixend [expr {$slash + 1}]
3094            set d [string range $tail 0 $slash]
3095            lappend treecontents($prefix) $d
3096            set oldprefix $prefix
3097            append prefix $d
3098            set treecontents($prefix) {}
3099            set treeindex($prefix) [incr ix]
3100            set treeparent($prefix) $oldprefix
3101            set tail [string range $tail [expr {$slash+1}] end]
3102            if {$lev <= $openlevs} {
3103                set ht 1
3104                set treediropen($prefix) [expr {$lev < $openlevs}]
3105                set bm [expr {$lev == $openlevs? "tri-rt": "tri-dn"}]
3106                $w mark set d:$ix "end -1c"
3107                $w mark gravity d:$ix left
3108                set str "\n"
3109                for {set i 0} {$i < $lev} {incr i} {append str "\t"}
3110                $w insert end $str
3111                $w image create end -align center -image $bm -padx 1 \
3112                    -name a:$ix
3113                $w insert end $d [highlight_tag $prefix]
3114                $w mark set s:$ix "end -1c"
3115                $w mark gravity s:$ix left
3116            }
3117            incr lev
3118        }
3119        if {$tail ne {}} {
3120            if {$lev <= $openlevs} {
3121                incr ht
3122                set str "\n"
3123                for {set i 0} {$i < $lev} {incr i} {append str "\t"}
3124                $w insert end $str
3125                $w insert end $tail [highlight_tag $f]
3126            }
3127            lappend treecontents($prefix) $tail
3128        }
3129    }
3130    while {$htstack ne {}} {
3131        set treeheight($prefix) $ht
3132        incr ht [lindex $htstack end]
3133        set htstack [lreplace $htstack end end]
3134        set prefixend [lindex $prefendstack end]
3135        set prefendstack [lreplace $prefendstack end end]
3136        set prefix [string range $prefix 0 $prefixend]
3137    }
3138    $w conf -state disabled
3139}
3140
3141proc linetoelt {l} {
3142    global treeheight treecontents
3143
3144    set y 2
3145    set prefix {}
3146    while {1} {
3147        foreach e $treecontents($prefix) {
3148            if {$y == $l} {
3149                return "$prefix$e"
3150            }
3151            set n 1
3152            if {[string index $e end] eq "/"} {
3153                set n $treeheight($prefix$e)
3154                if {$y + $n > $l} {
3155                    append prefix $e
3156                    incr y
3157                    break
3158                }
3159            }
3160            incr y $n
3161        }
3162    }
3163}
3164
3165proc highlight_tree {y prefix} {
3166    global treeheight treecontents cflist
3167
3168    foreach e $treecontents($prefix) {
3169        set path $prefix$e
3170        if {[highlight_tag $path] ne {}} {
3171            $cflist tag add bold $y.0 "$y.0 lineend"
3172        }
3173        incr y
3174        if {[string index $e end] eq "/" && $treeheight($path) > 1} {
3175            set y [highlight_tree $y $path]
3176        }
3177    }
3178    return $y
3179}
3180
3181proc treeclosedir {w dir} {
3182    global treediropen treeheight treeparent treeindex
3183
3184    set ix $treeindex($dir)
3185    $w conf -state normal
3186    $w delete s:$ix e:$ix
3187    set treediropen($dir) 0
3188    $w image configure a:$ix -image tri-rt
3189    $w conf -state disabled
3190    set n [expr {1 - $treeheight($dir)}]
3191    while {$dir ne {}} {
3192        incr treeheight($dir) $n
3193        set dir $treeparent($dir)
3194    }
3195}
3196
3197proc treeopendir {w dir} {
3198    global treediropen treeheight treeparent treecontents treeindex
3199
3200    set ix $treeindex($dir)
3201    $w conf -state normal
3202    $w image configure a:$ix -image tri-dn
3203    $w mark set e:$ix s:$ix
3204    $w mark gravity e:$ix right
3205    set lev 0
3206    set str "\n"
3207    set n [llength $treecontents($dir)]
3208    for {set x $dir} {$x ne {}} {set x $treeparent($x)} {
3209        incr lev
3210        append str "\t"
3211        incr treeheight($x) $n
3212    }
3213    foreach e $treecontents($dir) {
3214        set de $dir$e
3215        if {[string index $e end] eq "/"} {
3216            set iy $treeindex($de)
3217            $w mark set d:$iy e:$ix
3218            $w mark gravity d:$iy left
3219            $w insert e:$ix $str
3220            set treediropen($de) 0
3221            $w image create e:$ix -align center -image tri-rt -padx 1 \
3222                -name a:$iy
3223            $w insert e:$ix $e [highlight_tag $de]
3224            $w mark set s:$iy e:$ix
3225            $w mark gravity s:$iy left
3226            set treeheight($de) 1
3227        } else {
3228            $w insert e:$ix $str
3229            $w insert e:$ix $e [highlight_tag $de]
3230        }
3231    }
3232    $w mark gravity e:$ix right
3233    $w conf -state disabled
3234    set treediropen($dir) 1
3235    set top [lindex [split [$w index @0,0] .] 0]
3236    set ht [$w cget -height]
3237    set l [lindex [split [$w index s:$ix] .] 0]
3238    if {$l < $top} {
3239        $w yview $l.0
3240    } elseif {$l + $n + 1 > $top + $ht} {
3241        set top [expr {$l + $n + 2 - $ht}]
3242        if {$l < $top} {
3243            set top $l
3244        }
3245        $w yview $top.0
3246    }
3247}
3248
3249proc treeclick {w x y} {
3250    global treediropen cmitmode ctext cflist cflist_top
3251
3252    if {$cmitmode ne "tree"} return
3253    if {![info exists cflist_top]} return
3254    set l [lindex [split [$w index "@$x,$y"] "."] 0]
3255    $cflist tag remove highlight $cflist_top.0 "$cflist_top.0 lineend"
3256    $cflist tag add highlight $l.0 "$l.0 lineend"
3257    set cflist_top $l
3258    if {$l == 1} {
3259        $ctext yview 1.0
3260        return
3261    }
3262    set e [linetoelt $l]
3263    if {[string index $e end] ne "/"} {
3264        showfile $e
3265    } elseif {$treediropen($e)} {
3266        treeclosedir $w $e
3267    } else {
3268        treeopendir $w $e
3269    }
3270}
3271
3272proc setfilelist {id} {
3273    global treefilelist cflist jump_to_here
3274
3275    treeview $cflist $treefilelist($id) 0
3276    if {$jump_to_here ne {}} {
3277        set f [lindex $jump_to_here 0]
3278        if {[lsearch -exact $treefilelist($id) $f] >= 0} {
3279            showfile $f
3280        }
3281    }
3282}
3283
3284image create bitmap tri-rt -background black -foreground blue -data {
3285    #define tri-rt_width 13
3286    #define tri-rt_height 13
3287    static unsigned char tri-rt_bits[] = {
3288       0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x30, 0x00, 0x70, 0x00, 0xf0, 0x00,
3289       0xf0, 0x01, 0xf0, 0x00, 0x70, 0x00, 0x30, 0x00, 0x10, 0x00, 0x00, 0x00,
3290       0x00, 0x00};
3291} -maskdata {
3292    #define tri-rt-mask_width 13
3293    #define tri-rt-mask_height 13
3294    static unsigned char tri-rt-mask_bits[] = {
3295       0x08, 0x00, 0x18, 0x00, 0x38, 0x00, 0x78, 0x00, 0xf8, 0x00, 0xf8, 0x01,
3296       0xf8, 0x03, 0xf8, 0x01, 0xf8, 0x00, 0x78, 0x00, 0x38, 0x00, 0x18, 0x00,
3297       0x08, 0x00};
3298}
3299image create bitmap tri-dn -background black -foreground blue -data {
3300    #define tri-dn_width 13
3301    #define tri-dn_height 13
3302    static unsigned char tri-dn_bits[] = {
3303       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x07, 0xf8, 0x03,
3304       0xf0, 0x01, 0xe0, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
3305       0x00, 0x00};
3306} -maskdata {
3307    #define tri-dn-mask_width 13
3308    #define tri-dn-mask_height 13
3309    static unsigned char tri-dn-mask_bits[] = {
3310       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x1f, 0xfe, 0x0f, 0xfc, 0x07,
3311       0xf8, 0x03, 0xf0, 0x01, 0xe0, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00,
3312       0x00, 0x00};
3313}
3314
3315image create bitmap reficon-T -background black -foreground yellow -data {
3316    #define tagicon_width 13
3317    #define tagicon_height 9
3318    static unsigned char tagicon_bits[] = {
3319       0x00, 0x00, 0x00, 0x00, 0xf0, 0x07, 0xf8, 0x07,
3320       0xfc, 0x07, 0xf8, 0x07, 0xf0, 0x07, 0x00, 0x00, 0x00, 0x00};
3321} -maskdata {
3322    #define tagicon-mask_width 13
3323    #define tagicon-mask_height 9
3324    static unsigned char tagicon-mask_bits[] = {
3325       0x00, 0x00, 0xf0, 0x0f, 0xf8, 0x0f, 0xfc, 0x0f,
3326       0xfe, 0x0f, 0xfc, 0x0f, 0xf8, 0x0f, 0xf0, 0x0f, 0x00, 0x00};
3327}
3328set rectdata {
3329    #define headicon_width 13
3330    #define headicon_height 9
3331    static unsigned char headicon_bits[] = {
3332       0x00, 0x00, 0x00, 0x00, 0xf8, 0x07, 0xf8, 0x07,
3333       0xf8, 0x07, 0xf8, 0x07, 0xf8, 0x07, 0x00, 0x00, 0x00, 0x00};
3334}
3335set rectmask {
3336    #define headicon-mask_width 13
3337    #define headicon-mask_height 9
3338    static unsigned char headicon-mask_bits[] = {
3339       0x00, 0x00, 0xfc, 0x0f, 0xfc, 0x0f, 0xfc, 0x0f,
3340       0xfc, 0x0f, 0xfc, 0x0f, 0xfc, 0x0f, 0xfc, 0x0f, 0x00, 0x00};
3341}
3342image create bitmap reficon-H -background black -foreground green \
3343    -data $rectdata -maskdata $rectmask
3344image create bitmap reficon-o -background black -foreground "#ddddff" \
3345    -data $rectdata -maskdata $rectmask
3346
3347proc init_flist {first} {
3348    global cflist cflist_top difffilestart
3349
3350    $cflist conf -state normal
3351    $cflist delete 0.0 end
3352    if {$first ne {}} {
3353        $cflist insert end $first
3354        set cflist_top 1
3355        $cflist tag add highlight 1.0 "1.0 lineend"
3356    } else {
3357        catch {unset cflist_top}
3358    }
3359    $cflist conf -state disabled
3360    set difffilestart {}
3361}
3362
3363proc highlight_tag {f} {
3364    global highlight_paths
3365
3366    foreach p $highlight_paths {
3367        if {[string match $p $f]} {
3368            return "bold"
3369        }
3370    }
3371    return {}
3372}
3373
3374proc highlight_filelist {} {
3375    global cmitmode cflist
3376
3377    $cflist conf -state normal
3378    if {$cmitmode ne "tree"} {
3379        set end [lindex [split [$cflist index end] .] 0]
3380        for {set l 2} {$l < $end} {incr l} {
3381            set line [$cflist get $l.0 "$l.0 lineend"]
3382            if {[highlight_tag $line] ne {}} {
3383                $cflist tag add bold $l.0 "$l.0 lineend"
3384            }
3385        }
3386    } else {
3387        highlight_tree 2 {}
3388    }
3389    $cflist conf -state disabled
3390}
3391
3392proc unhighlight_filelist {} {
3393    global cflist
3394
3395    $cflist conf -state normal
3396    $cflist tag remove bold 1.0 end
3397    $cflist conf -state disabled
3398}
3399
3400proc add_flist {fl} {
3401    global cflist
3402
3403    $cflist conf -state normal
3404    foreach f $fl {
3405        $cflist insert end "\n"
3406        $cflist insert end $f [highlight_tag $f]
3407    }
3408    $cflist conf -state disabled
3409}
3410
3411proc sel_flist {w x y} {
3412    global ctext difffilestart cflist cflist_top cmitmode
3413
3414    if {$cmitmode eq "tree"} return
3415    if {![info exists cflist_top]} return
3416    set l [lindex [split [$w index "@$x,$y"] "."] 0]
3417    $cflist tag remove highlight $cflist_top.0 "$cflist_top.0 lineend"
3418    $cflist tag add highlight $l.0 "$l.0 lineend"
3419    set cflist_top $l
3420    if {$l == 1} {
3421        $ctext yview 1.0
3422    } else {
3423        catch {$ctext yview [lindex $difffilestart [expr {$l - 2}]]}
3424    }
3425    suppress_highlighting_file_for_current_scrollpos
3426}
3427
3428proc pop_flist_menu {w X Y x y} {
3429    global ctext cflist cmitmode flist_menu flist_menu_file
3430    global treediffs diffids
3431
3432    stopfinding
3433    set l [lindex [split [$w index "@$x,$y"] "."] 0]
3434    if {$l <= 1} return
3435    if {$cmitmode eq "tree"} {
3436        set e [linetoelt $l]
3437        if {[string index $e end] eq "/"} return
3438    } else {
3439        set e [lindex $treediffs($diffids) [expr {$l-2}]]
3440    }
3441    set flist_menu_file $e
3442    set xdiffstate "normal"
3443    if {$cmitmode eq "tree"} {
3444        set xdiffstate "disabled"
3445    }
3446    # Disable "External diff" item in tree mode
3447    $flist_menu entryconf 2 -state $xdiffstate
3448    tk_popup $flist_menu $X $Y
3449}
3450
3451proc find_ctext_fileinfo {line} {
3452    global ctext_file_names ctext_file_lines
3453
3454    set ok [bsearch $ctext_file_lines $line]
3455    set tline [lindex $ctext_file_lines $ok]
3456
3457    if {$ok >= [llength $ctext_file_lines] || $line < $tline} {
3458        return {}
3459    } else {
3460        return [list [lindex $ctext_file_names $ok] $tline]
3461    }
3462}
3463
3464proc pop_diff_menu {w X Y x y} {
3465    global ctext diff_menu flist_menu_file
3466    global diff_menu_txtpos diff_menu_line
3467    global diff_menu_filebase
3468
3469    set diff_menu_txtpos [split [$w index "@$x,$y"] "."]
3470    set diff_menu_line [lindex $diff_menu_txtpos 0]
3471    # don't pop up the menu on hunk-separator or file-separator lines
3472    if {[lsearch -glob [$ctext tag names $diff_menu_line.0] "*sep"] >= 0} {
3473        return
3474    }
3475    stopfinding
3476    set f [find_ctext_fileinfo $diff_menu_line]
3477    if {$f eq {}} return
3478    set flist_menu_file [lindex $f 0]
3479    set diff_menu_filebase [lindex $f 1]
3480    tk_popup $diff_menu $X $Y
3481}
3482
3483proc flist_hl {only} {
3484    global flist_menu_file findstring gdttype
3485
3486    set x [shellquote $flist_menu_file]
3487    if {$only || $findstring eq {} || $gdttype ne [mc "touching paths:"]} {
3488        set findstring $x
3489    } else {
3490        append findstring " " $x
3491    }
3492    set gdttype [mc "touching paths:"]
3493}
3494
3495proc gitknewtmpdir {} {
3496    global diffnum gitktmpdir gitdir env
3497
3498    if {![info exists gitktmpdir]} {
3499        if {[info exists env(GITK_TMPDIR)]} {
3500            set tmpdir $env(GITK_TMPDIR)
3501        } elseif {[info exists env(TMPDIR)]} {
3502            set tmpdir $env(TMPDIR)
3503        } else {
3504            set tmpdir $gitdir
3505        }
3506        set gitktmpformat [file join $tmpdir ".gitk-tmp.XXXXXX"]
3507        if {[catch {set gitktmpdir [exec mktemp -d $gitktmpformat]}]} {
3508            set gitktmpdir [file join $gitdir [format ".gitk-tmp.%s" [pid]]]
3509        }
3510        if {[catch {file mkdir $gitktmpdir} err]} {
3511            error_popup "[mc "Error creating temporary directory %s:" $gitktmpdir] $err"
3512            unset gitktmpdir
3513            return {}
3514        }
3515        set diffnum 0
3516    }
3517    incr diffnum
3518    set diffdir [file join $gitktmpdir $diffnum]
3519    if {[catch {file mkdir $diffdir} err]} {
3520        error_popup "[mc "Error creating temporary directory %s:" $diffdir] $err"
3521        return {}
3522    }
3523    return $diffdir
3524}
3525
3526proc save_file_from_commit {filename output what} {
3527    global nullfile
3528
3529    if {[catch {exec git show $filename -- > $output} err]} {
3530        if {[string match "fatal: bad revision *" $err]} {
3531            return $nullfile
3532        }
3533        error_popup "[mc "Error getting \"%s\" from %s:" $filename $what] $err"
3534        return {}
3535    }
3536    return $output
3537}
3538
3539proc external_diff_get_one_file {diffid filename diffdir} {
3540    global nullid nullid2 nullfile
3541    global worktree
3542
3543    if {$diffid == $nullid} {
3544        set difffile [file join $worktree $filename]
3545        if {[file exists $difffile]} {
3546            return $difffile
3547        }
3548        return $nullfile
3549    }
3550    if {$diffid == $nullid2} {
3551        set difffile [file join $diffdir "\[index\] [file tail $filename]"]
3552        return [save_file_from_commit :$filename $difffile index]
3553    }
3554    set difffile [file join $diffdir "\[$diffid\] [file tail $filename]"]
3555    return [save_file_from_commit $diffid:$filename $difffile \
3556               "revision $diffid"]
3557}
3558
3559proc external_diff {} {
3560    global nullid nullid2
3561    global flist_menu_file
3562    global diffids
3563    global extdifftool
3564
3565    if {[llength $diffids] == 1} {
3566        # no reference commit given
3567        set diffidto [lindex $diffids 0]
3568        if {$diffidto eq $nullid} {
3569            # diffing working copy with index
3570            set diffidfrom $nullid2
3571        } elseif {$diffidto eq $nullid2} {
3572            # diffing index with HEAD
3573            set diffidfrom "HEAD"
3574        } else {
3575            # use first parent commit
3576            global parentlist selectedline
3577            set diffidfrom [lindex $parentlist $selectedline 0]
3578        }
3579    } else {
3580        set diffidfrom [lindex $diffids 0]
3581        set diffidto [lindex $diffids 1]
3582    }
3583
3584    # make sure that several diffs wont collide
3585    set diffdir [gitknewtmpdir]
3586    if {$diffdir eq {}} return
3587
3588    # gather files to diff
3589    set difffromfile [external_diff_get_one_file $diffidfrom $flist_menu_file $diffdir]
3590    set difftofile [external_diff_get_one_file $diffidto $flist_menu_file $diffdir]
3591
3592    if {$difffromfile ne {} && $difftofile ne {}} {
3593        set cmd [list [shellsplit $extdifftool] $difffromfile $difftofile]
3594        if {[catch {set fl [open |$cmd r]} err]} {
3595            file delete -force $diffdir
3596            error_popup "$extdifftool: [mc "command failed:"] $err"
3597        } else {
3598            fconfigure $fl -blocking 0
3599            filerun $fl [list delete_at_eof $fl $diffdir]
3600        }
3601    }
3602}
3603
3604proc find_hunk_blamespec {base line} {
3605    global ctext
3606
3607    # Find and parse the hunk header
3608    set s_lix [$ctext search -backwards -regexp ^@@ "$line.0 lineend" $base.0]
3609    if {$s_lix eq {}} return
3610
3611    set s_line [$ctext get $s_lix "$s_lix + 1 lines"]
3612    if {![regexp {^@@@*(( -\d+(,\d+)?)+) \+(\d+)(,\d+)? @@} $s_line \
3613            s_line old_specs osz osz1 new_line nsz]} {
3614        return
3615    }
3616
3617    # base lines for the parents
3618    set base_lines [list $new_line]
3619    foreach old_spec [lrange [split $old_specs " "] 1 end] {
3620        if {![regexp -- {-(\d+)(,\d+)?} $old_spec \
3621                old_spec old_line osz]} {
3622            return
3623        }
3624        lappend base_lines $old_line
3625    }
3626
3627    # Now scan the lines to determine offset within the hunk
3628    set max_parent [expr {[llength $base_lines]-2}]
3629    set dline 0
3630    set s_lno [lindex [split $s_lix "."] 0]
3631
3632    # Determine if the line is removed
3633    set chunk [$ctext get $line.0 "$line.1 + $max_parent chars"]
3634    if {[string match {[-+ ]*} $chunk]} {
3635        set removed_idx [string first "-" $chunk]
3636        # Choose a parent index
3637        if {$removed_idx >= 0} {
3638            set parent $removed_idx
3639        } else {
3640            set unchanged_idx [string first " " $chunk]
3641            if {$unchanged_idx >= 0} {
3642                set parent $unchanged_idx
3643            } else {
3644                # blame the current commit
3645                set parent -1
3646            }
3647        }
3648        # then count other lines that belong to it
3649        for {set i $line} {[incr i -1] > $s_lno} {} {
3650            set chunk [$ctext get $i.0 "$i.1 + $max_parent chars"]
3651            # Determine if the line is removed
3652            set removed_idx [string first "-" $chunk]
3653            if {$parent >= 0} {
3654                set code [string index $chunk $parent]
3655                if {$code eq "-" || ($removed_idx < 0 && $code ne "+")} {
3656                    incr dline
3657                }
3658            } else {
3659                if {$removed_idx < 0} {
3660                    incr dline
3661                }
3662            }
3663        }
3664        incr parent
3665    } else {
3666        set parent 0
3667    }
3668
3669    incr dline [lindex $base_lines $parent]
3670    return [list $parent $dline]
3671}
3672
3673proc external_blame_diff {} {
3674    global currentid cmitmode
3675    global diff_menu_txtpos diff_menu_line
3676    global diff_menu_filebase flist_menu_file
3677
3678    if {$cmitmode eq "tree"} {
3679        set parent_idx 0
3680        set line [expr {$diff_menu_line - $diff_menu_filebase}]
3681    } else {
3682        set hinfo [find_hunk_blamespec $diff_menu_filebase $diff_menu_line]
3683        if {$hinfo ne {}} {
3684            set parent_idx [lindex $hinfo 0]
3685            set line [lindex $hinfo 1]
3686        } else {
3687            set parent_idx 0
3688            set line 0
3689        }
3690    }
3691
3692    external_blame $parent_idx $line
3693}
3694
3695# Find the SHA1 ID of the blob for file $fname in the index
3696# at stage 0 or 2
3697proc index_sha1 {fname} {
3698    set f [open [list | git ls-files -s $fname] r]
3699    while {[gets $f line] >= 0} {
3700        set info [lindex [split $line "\t"] 0]
3701        set stage [lindex $info 2]
3702        if {$stage eq "0" || $stage eq "2"} {
3703            close $f
3704            return [lindex $info 1]
3705        }
3706    }
3707    close $f
3708    return {}
3709}
3710
3711# Turn an absolute path into one relative to the current directory
3712proc make_relative {f} {
3713    if {[file pathtype $f] eq "relative"} {
3714        return $f
3715    }
3716    set elts [file split $f]
3717    set here [file split [pwd]]
3718    set ei 0
3719    set hi 0
3720    set res {}
3721    foreach d $here {
3722        if {$ei < $hi || $ei >= [llength $elts] || [lindex $elts $ei] ne $d} {
3723            lappend res ".."
3724        } else {
3725            incr ei
3726        }
3727        incr hi
3728    }
3729    set elts [concat $res [lrange $elts $ei end]]
3730    return [eval file join $elts]
3731}
3732
3733proc external_blame {parent_idx {line {}}} {
3734    global flist_menu_file cdup
3735    global nullid nullid2
3736    global parentlist selectedline currentid
3737
3738    if {$parent_idx > 0} {
3739        set base_commit [lindex $parentlist $selectedline [expr {$parent_idx-1}]]
3740    } else {
3741        set base_commit $currentid
3742    }
3743
3744    if {$base_commit eq {} || $base_commit eq $nullid || $base_commit eq $nullid2} {
3745        error_popup [mc "No such commit"]
3746        return
3747    }
3748
3749    set cmdline [list git gui blame]
3750    if {$line ne {} && $line > 1} {
3751        lappend cmdline "--line=$line"
3752    }
3753    set f [file join $cdup $flist_menu_file]
3754    # Unfortunately it seems git gui blame doesn't like
3755    # being given an absolute path...
3756    set f [make_relative $f]
3757    lappend cmdline $base_commit $f
3758    if {[catch {eval exec $cmdline &} err]} {
3759        error_popup "[mc "git gui blame: command failed:"] $err"
3760    }
3761}
3762
3763proc show_line_source {} {
3764    global cmitmode currentid parents curview blamestuff blameinst
3765    global diff_menu_line diff_menu_filebase flist_menu_file
3766    global nullid nullid2 gitdir cdup
3767
3768    set from_index {}
3769    if {$cmitmode eq "tree"} {
3770        set id $currentid
3771        set line [expr {$diff_menu_line - $diff_menu_filebase}]
3772    } else {
3773        set h [find_hunk_blamespec $diff_menu_filebase $diff_menu_line]
3774        if {$h eq {}} return
3775        set pi [lindex $h 0]
3776        if {$pi == 0} {
3777            mark_ctext_line $diff_menu_line
3778            return
3779        }
3780        incr pi -1
3781        if {$currentid eq $nullid} {
3782            if {$pi > 0} {
3783                # must be a merge in progress...
3784                if {[catch {
3785                    # get the last line from .git/MERGE_HEAD
3786                    set f [open [file join $gitdir MERGE_HEAD] r]
3787                    set id [lindex [split [read $f] "\n"] end-1]
3788                    close $f
3789                } err]} {
3790                    error_popup [mc "Couldn't read merge head: %s" $err]
3791                    return
3792                }
3793            } elseif {$parents($curview,$currentid) eq $nullid2} {
3794                # need to do the blame from the index
3795                if {[catch {
3796                    set from_index [index_sha1 $flist_menu_file]
3797                } err]} {
3798                    error_popup [mc "Error reading index: %s" $err]
3799                    return
3800                }
3801            } else {
3802                set id $parents($curview,$currentid)
3803            }
3804        } else {
3805            set id [lindex $parents($curview,$currentid) $pi]
3806        }
3807        set line [lindex $h 1]
3808    }
3809    set blameargs {}
3810    if {$from_index ne {}} {
3811        lappend blameargs | git cat-file blob $from_index
3812    }
3813    lappend blameargs | git blame -p -L$line,+1
3814    if {$from_index ne {}} {
3815        lappend blameargs --contents -
3816    } else {
3817        lappend blameargs $id
3818    }
3819    lappend blameargs -- [file join $cdup $flist_menu_file]
3820    if {[catch {
3821        set f [open $blameargs r]
3822    } err]} {
3823        error_popup [mc "Couldn't start git blame: %s" $err]
3824        return
3825    }
3826    nowbusy blaming [mc "Searching"]
3827    fconfigure $f -blocking 0
3828    set i [reg_instance $f]
3829    set blamestuff($i) {}
3830    set blameinst $i
3831    filerun $f [list read_line_source $f $i]
3832}
3833
3834proc stopblaming {} {
3835    global blameinst
3836
3837    if {[info exists blameinst]} {
3838        stop_instance $blameinst
3839        unset blameinst
3840        notbusy blaming
3841    }
3842}
3843
3844proc read_line_source {fd inst} {
3845    global blamestuff curview commfd blameinst nullid nullid2
3846
3847    while {[gets $fd line] >= 0} {
3848        lappend blamestuff($inst) $line
3849    }
3850    if {![eof $fd]} {
3851        return 1
3852    }
3853    unset commfd($inst)
3854    unset blameinst
3855    notbusy blaming
3856    fconfigure $fd -blocking 1
3857    if {[catch {close $fd} err]} {
3858        error_popup [mc "Error running git blame: %s" $err]
3859        return 0
3860    }
3861
3862    set fname {}
3863    set line [split [lindex $blamestuff($inst) 0] " "]
3864    set id [lindex $line 0]
3865    set lnum [lindex $line 1]
3866    if {[string length $id] == 40 && [string is xdigit $id] &&
3867        [string is digit -strict $lnum]} {
3868        # look for "filename" line
3869        foreach l $blamestuff($inst) {
3870            if {[string match "filename *" $l]} {
3871                set fname [string range $l 9 end]
3872                break
3873            }
3874        }
3875    }
3876    if {$fname ne {}} {
3877        # all looks good, select it
3878        if {$id eq $nullid} {
3879            # blame uses all-zeroes to mean not committed,
3880            # which would mean a change in the index
3881            set id $nullid2
3882        }
3883        if {[commitinview $id $curview]} {
3884            selectline [rowofcommit $id] 1 [list $fname $lnum] 1
3885        } else {
3886            error_popup [mc "That line comes from commit %s, \
3887                             which is not in this view" [shortids $id]]
3888        }
3889    } else {
3890        puts "oops couldn't parse git blame output"
3891    }
3892    return 0
3893}
3894
3895# delete $dir when we see eof on $f (presumably because the child has exited)
3896proc delete_at_eof {f dir} {
3897    while {[gets $f line] >= 0} {}
3898    if {[eof $f]} {
3899        if {[catch {close $f} err]} {
3900            error_popup "[mc "External diff viewer failed:"] $err"
3901        }
3902        file delete -force $dir
3903        return 0
3904    }
3905    return 1
3906}
3907
3908# Functions for adding and removing shell-type quoting
3909
3910proc shellquote {str} {
3911    if {![string match "*\['\"\\ \t]*" $str]} {
3912        return $str
3913    }
3914    if {![string match "*\['\"\\]*" $str]} {
3915        return "\"$str\""
3916    }
3917    if {![string match "*'*" $str]} {
3918        return "'$str'"
3919    }
3920    return "\"[string map {\" \\\" \\ \\\\} $str]\""
3921}
3922
3923proc shellarglist {l} {
3924    set str {}
3925    foreach a $l {
3926        if {$str ne {}} {
3927            append str " "
3928        }
3929        append str [shellquote $a]
3930    }
3931    return $str
3932}
3933
3934proc shelldequote {str} {
3935    set ret {}
3936    set used -1
3937    while {1} {
3938        incr used
3939        if {![regexp -start $used -indices "\['\"\\\\ \t]" $str first]} {
3940            append ret [string range $str $used end]
3941            set used [string length $str]
3942            break
3943        }
3944        set first [lindex $first 0]
3945        set ch [string index $str $first]
3946        if {$first > $used} {
3947            append ret [string range $str $used [expr {$first - 1}]]
3948            set used $first
3949        }
3950        if {$ch eq " " || $ch eq "\t"} break
3951        incr used
3952        if {$ch eq "'"} {
3953            set first [string first "'" $str $used]
3954            if {$first < 0} {
3955                error "unmatched single-quote"
3956            }
3957            append ret [string range $str $used [expr {$first - 1}]]
3958            set used $first
3959            continue
3960        }
3961        if {$ch eq "\\"} {
3962            if {$used >= [string length $str]} {
3963                error "trailing backslash"
3964            }
3965            append ret [string index $str $used]
3966            continue
3967        }
3968        # here ch == "\""
3969        while {1} {
3970            if {![regexp -start $used -indices "\[\"\\\\]" $str first]} {
3971                error "unmatched double-quote"
3972            }
3973            set first [lindex $first 0]
3974            set ch [string index $str $first]
3975            if {$first > $used} {
3976                append ret [string range $str $used [expr {$first - 1}]]
3977                set used $first
3978            }
3979            if {$ch eq "\""} break
3980            incr used
3981            append ret [string index $str $used]
3982            incr used
3983        }
3984    }
3985    return [list $used $ret]
3986}
3987
3988proc shellsplit {str} {
3989    set l {}
3990    while {1} {
3991        set str [string trimleft $str]
3992        if {$str eq {}} break
3993        set dq [shelldequote $str]
3994        set n [lindex $dq 0]
3995        set word [lindex $dq 1]
3996        set str [string range $str $n end]
3997        lappend l $word
3998    }
3999    return $l
4000}
4001
4002# Code to implement multiple views
4003
4004proc newview {ishighlight} {
4005    global nextviewnum newviewname newishighlight
4006    global revtreeargs viewargscmd newviewopts curview
4007
4008    set newishighlight $ishighlight
4009    set top .gitkview
4010    if {[winfo exists $top]} {
4011        raise $top
4012        return
4013    }
4014    decode_view_opts $nextviewnum $revtreeargs
4015    set newviewname($nextviewnum) "[mc "View"] $nextviewnum"
4016    set newviewopts($nextviewnum,perm) 0
4017    set newviewopts($nextviewnum,cmd)  $viewargscmd($curview)
4018    vieweditor $top $nextviewnum [mc "Gitk view definition"]
4019}
4020
4021set known_view_options {
4022    {perm      b    .  {}               {mc "Remember this view"}}
4023    {reflabel  l    +  {}               {mc "References (space separated list):"}}
4024    {refs      t15  .. {}               {mc "Branches & tags:"}}
4025    {allrefs   b    *. "--all"          {mc "All refs"}}
4026    {branches  b    .  "--branches"     {mc "All (local) branches"}}
4027    {tags      b    .  "--tags"         {mc "All tags"}}
4028    {remotes   b    .  "--remotes"      {mc "All remote-tracking branches"}}
4029    {commitlbl l    +  {}               {mc "Commit Info (regular expressions):"}}
4030    {author    t15  .. "--author=*"     {mc "Author:"}}
4031    {committer t15  .  "--committer=*"  {mc "Committer:"}}
4032    {loginfo   t15  .. "--grep=*"       {mc "Commit Message:"}}
4033    {allmatch  b    .. "--all-match"    {mc "Matches all Commit Info criteria"}}
4034    {changes_l l    +  {}               {mc "Changes to Files:"}}
4035    {pickaxe_s r0   .  {}               {mc "Fixed String"}}
4036    {pickaxe_t r1   .  "--pickaxe-regex"  {mc "Regular Expression"}}
4037    {pickaxe   t15  .. "-S*"            {mc "Search string:"}}
4038    {datelabel l    +  {}               {mc "Commit Dates (\"2 weeks ago\", \"2009-03-17 15:27:38\", \"March 17, 2009 15:27:38\"):"}}
4039    {since     t15  ..  {"--since=*" "--after=*"}  {mc "Since:"}}
4040    {until     t15  .   {"--until=*" "--before=*"} {mc "Until:"}}
4041    {limit_lbl l    +  {}               {mc "Limit and/or skip a number of revisions (positive integer):"}}
4042    {limit     t10  *. "--max-count=*"  {mc "Number to show:"}}
4043    {skip      t10  .  "--skip=*"       {mc "Number to skip:"}}
4044    {misc_lbl  l    +  {}               {mc "Miscellaneous options:"}}
4045    {dorder    b    *. {"--date-order" "-d"}      {mc "Strictly sort by date"}}
4046    {lright    b    .  "--left-right"   {mc "Mark branch sides"}}
4047    {first     b    .  "--first-parent" {mc "Limit to first parent"}}
4048    {smplhst   b    .  "--simplify-by-decoration"   {mc "Simple history"}}
4049    {args      t50  *. {}               {mc "Additional arguments to git log:"}}
4050    {allpaths  path +  {}               {mc "Enter files and directories to include, one per line:"}}
4051    {cmd       t50= +  {}               {mc "Command to generate more commits to include:"}}
4052    }
4053
4054# Convert $newviewopts($n, ...) into args for git log.
4055proc encode_view_opts {n} {
4056    global known_view_options newviewopts
4057
4058    set rargs [list]
4059    foreach opt $known_view_options {
4060        set patterns [lindex $opt 3]
4061        if {$patterns eq {}} continue
4062        set pattern [lindex $patterns 0]
4063
4064        if {[lindex $opt 1] eq "b"} {
4065            set val $newviewopts($n,[lindex $opt 0])
4066            if {$val} {
4067                lappend rargs $pattern
4068            }
4069        } elseif {[regexp {^r(\d+)$} [lindex $opt 1] type value]} {
4070            regexp {^(.*_)} [lindex $opt 0] uselessvar button_id
4071            set val $newviewopts($n,$button_id)
4072            if {$val eq $value} {
4073                lappend rargs $pattern
4074            }
4075        } else {
4076            set val $newviewopts($n,[lindex $opt 0])
4077            set val [string trim $val]
4078            if {$val ne {}} {
4079                set pfix [string range $pattern 0 end-1]
4080                lappend rargs $pfix$val
4081            }
4082        }
4083    }
4084    set rargs [concat $rargs [shellsplit $newviewopts($n,refs)]]
4085    return [concat $rargs [shellsplit $newviewopts($n,args)]]
4086}
4087
4088# Fill $newviewopts($n, ...) based on args for git log.
4089proc decode_view_opts {n view_args} {
4090    global known_view_options newviewopts
4091
4092    foreach opt $known_view_options {
4093        set id [lindex $opt 0]
4094        if {[lindex $opt 1] eq "b"} {
4095            # Checkboxes
4096            set val 0
4097        } elseif {[regexp {^r(\d+)$} [lindex $opt 1]]} {
4098            # Radiobuttons
4099            regexp {^(.*_)} $id uselessvar id
4100            set val 0
4101        } else {
4102            # Text fields
4103            set val {}
4104        }
4105        set newviewopts($n,$id) $val
4106    }
4107    set oargs [list]
4108    set refargs [list]
4109    foreach arg $view_args {
4110        if {[regexp -- {^-([0-9]+)$} $arg arg cnt]
4111            && ![info exists found(limit)]} {
4112            set newviewopts($n,limit) $cnt
4113            set found(limit) 1
4114            continue
4115        }
4116        catch { unset val }
4117        foreach opt $known_view_options {
4118            set id [lindex $opt 0]
4119            if {[info exists found($id)]} continue
4120            foreach pattern [lindex $opt 3] {
4121                if {![string match $pattern $arg]} continue
4122                if {[lindex $opt 1] eq "b"} {
4123                    # Check buttons
4124                    set val 1
4125                } elseif {[regexp {^r(\d+)$} [lindex $opt 1] match num]} {
4126                    # Radio buttons
4127                    regexp {^(.*_)} $id uselessvar id
4128                    set val $num
4129                } else {
4130                    # Text input fields
4131                    set size [string length $pattern]
4132                    set val [string range $arg [expr {$size-1}] end]
4133                }
4134                set newviewopts($n,$id) $val
4135                set found($id) 1
4136                break
4137            }
4138            if {[info exists val]} break
4139        }
4140        if {[info exists val]} continue
4141        if {[regexp {^-} $arg]} {
4142            lappend oargs $arg
4143        } else {
4144            lappend refargs $arg
4145        }
4146    }
4147    set newviewopts($n,refs) [shellarglist $refargs]
4148    set newviewopts($n,args) [shellarglist $oargs]
4149}
4150
4151proc edit_or_newview {} {
4152    global curview
4153
4154    if {$curview > 0} {
4155        editview
4156    } else {
4157        newview 0
4158    }
4159}
4160
4161proc editview {} {
4162    global curview
4163    global viewname viewperm newviewname newviewopts
4164    global viewargs viewargscmd
4165
4166    set top .gitkvedit-$curview
4167    if {[winfo exists $top]} {
4168        raise $top
4169        return
4170    }
4171    decode_view_opts $curview $viewargs($curview)
4172    set newviewname($curview)      $viewname($curview)
4173    set newviewopts($curview,perm) $viewperm($curview)
4174    set newviewopts($curview,cmd)  $viewargscmd($curview)
4175    vieweditor $top $curview "[mc "Gitk: edit view"] $viewname($curview)"
4176}
4177
4178proc vieweditor {top n title} {
4179    global newviewname newviewopts viewfiles bgcolor
4180    global known_view_options NS
4181
4182    ttk_toplevel $top
4183    wm title $top [concat $title [mc "-- criteria for selecting revisions"]]
4184    make_transient $top .
4185
4186    # View name
4187    ${NS}::frame $top.nfr
4188    ${NS}::label $top.nl -text [mc "View Name"]
4189    ${NS}::entry $top.name -width 20 -textvariable newviewname($n)
4190    pack $top.nfr -in $top -fill x -pady 5 -padx 3
4191    pack $top.nl -in $top.nfr -side left -padx {0 5}
4192    pack $top.name -in $top.nfr -side left -padx {0 25}
4193
4194    # View options
4195    set cframe $top.nfr
4196    set cexpand 0
4197    set cnt 0
4198    foreach opt $known_view_options {
4199        set id [lindex $opt 0]
4200        set type [lindex $opt 1]
4201        set flags [lindex $opt 2]
4202        set title [eval [lindex $opt 4]]
4203        set lxpad 0
4204
4205        if {$flags eq "+" || $flags eq "*"} {
4206            set cframe $top.fr$cnt
4207            incr cnt
4208            ${NS}::frame $cframe
4209            pack $cframe -in $top -fill x -pady 3 -padx 3
4210            set cexpand [expr {$flags eq "*"}]
4211        } elseif {$flags eq ".." || $flags eq "*."} {
4212            set cframe $top.fr$cnt
4213            incr cnt
4214            ${NS}::frame $cframe
4215            pack $cframe -in $top -fill x -pady 3 -padx [list 15 3]
4216            set cexpand [expr {$flags eq "*."}]
4217        } else {
4218            set lxpad 5
4219        }
4220
4221        if {$type eq "l"} {
4222            ${NS}::label $cframe.l_$id -text $title
4223            pack $cframe.l_$id -in $cframe -side left -pady [list 3 0] -anchor w
4224        } elseif {$type eq "b"} {
4225            ${NS}::checkbutton $cframe.c_$id -text $title -variable newviewopts($n,$id)
4226            pack $cframe.c_$id -in $cframe -side left \
4227                -padx [list $lxpad 0] -expand $cexpand -anchor w
4228        } elseif {[regexp {^r(\d+)$} $type type sz]} {
4229            regexp {^(.*_)} $id uselessvar button_id
4230            ${NS}::radiobutton $cframe.c_$id -text $title -variable newviewopts($n,$button_id) -value $sz
4231            pack $cframe.c_$id -in $cframe -side left \
4232                -padx [list $lxpad 0] -expand $cexpand -anchor w
4233        } elseif {[regexp {^t(\d+)$} $type type sz]} {
4234            ${NS}::label $cframe.l_$id -text $title
4235            ${NS}::entry $cframe.e_$id -width $sz -background $bgcolor \
4236                -textvariable newviewopts($n,$id)
4237            pack $cframe.l_$id -in $cframe -side left -padx [list $lxpad 0]
4238            pack $cframe.e_$id -in $cframe -side left -expand 1 -fill x
4239        } elseif {[regexp {^t(\d+)=$} $type type sz]} {
4240            ${NS}::label $cframe.l_$id -text $title
4241            ${NS}::entry $cframe.e_$id -width $sz -background $bgcolor \
4242                -textvariable newviewopts($n,$id)
4243            pack $cframe.l_$id -in $cframe -side top -pady [list 3 0] -anchor w
4244            pack $cframe.e_$id -in $cframe -side top -fill x
4245        } elseif {$type eq "path"} {
4246            ${NS}::label $top.l -text $title
4247            pack $top.l -in $top -side top -pady [list 3 0] -anchor w -padx 3
4248            text $top.t -width 40 -height 5 -background $bgcolor
4249            if {[info exists viewfiles($n)]} {
4250                foreach f $viewfiles($n) {
4251                    $top.t insert end $f
4252                    $top.t insert end "\n"
4253                }
4254                $top.t delete {end - 1c} end
4255                $top.t mark set insert 0.0
4256            }
4257            pack $top.t -in $top -side top -pady [list 0 5] -fill both -expand 1 -padx 3
4258        }
4259    }
4260
4261    ${NS}::frame $top.buts
4262    ${NS}::button $top.buts.ok -text [mc "OK"] -command [list newviewok $top $n]
4263    ${NS}::button $top.buts.apply -text [mc "Apply (F5)"] -command [list newviewok $top $n 1]
4264    ${NS}::button $top.buts.can -text [mc "Cancel"] -command [list destroy $top]
4265    bind $top <Control-Return> [list newviewok $top $n]
4266    bind $top <F5> [list newviewok $top $n 1]
4267    bind $top <Escape> [list destroy $top]
4268    grid $top.buts.ok $top.buts.apply $top.buts.can
4269    grid columnconfigure $top.buts 0 -weight 1 -uniform a
4270    grid columnconfigure $top.buts 1 -weight 1 -uniform a
4271    grid columnconfigure $top.buts 2 -weight 1 -uniform a
4272    pack $top.buts -in $top -side top -fill x
4273    focus $top.t
4274}
4275
4276proc doviewmenu {m first cmd op argv} {
4277    set nmenu [$m index end]
4278    for {set i $first} {$i <= $nmenu} {incr i} {
4279        if {[$m entrycget $i -command] eq $cmd} {
4280            eval $m $op $i $argv
4281            break
4282        }
4283    }
4284}
4285
4286proc allviewmenus {n op args} {
4287    # global viewhlmenu
4288
4289    doviewmenu .bar.view 5 [list showview $n] $op $args
4290    # doviewmenu $viewhlmenu 1 [list addvhighlight $n] $op $args
4291}
4292
4293proc newviewok {top n {apply 0}} {
4294    global nextviewnum newviewperm newviewname newishighlight
4295    global viewname viewfiles viewperm selectedview curview
4296    global viewargs viewargscmd newviewopts viewhlmenu
4297
4298    if {[catch {
4299        set newargs [encode_view_opts $n]
4300    } err]} {
4301        error_popup "[mc "Error in commit selection arguments:"] $err" $top
4302        return
4303    }
4304    set files {}
4305    foreach f [split [$top.t get 0.0 end] "\n"] {
4306        set ft [string trim $f]
4307        if {$ft ne {}} {
4308            lappend files $ft
4309        }
4310    }
4311    if {![info exists viewfiles($n)]} {
4312        # creating a new view
4313        incr nextviewnum
4314        set viewname($n) $newviewname($n)
4315        set viewperm($n) $newviewopts($n,perm)
4316        set viewfiles($n) $files
4317        set viewargs($n) $newargs
4318        set viewargscmd($n) $newviewopts($n,cmd)
4319        addviewmenu $n
4320        if {!$newishighlight} {
4321            run showview $n
4322        } else {
4323            run addvhighlight $n
4324        }
4325    } else {
4326        # editing an existing view
4327        set viewperm($n) $newviewopts($n,perm)
4328        if {$newviewname($n) ne $viewname($n)} {
4329            set viewname($n) $newviewname($n)
4330            doviewmenu .bar.view 5 [list showview $n] \
4331                entryconf [list -label $viewname($n)]
4332            # doviewmenu $viewhlmenu 1 [list addvhighlight $n] \
4333                # entryconf [list -label $viewname($n) -value $viewname($n)]
4334        }
4335        if {$files ne $viewfiles($n) || $newargs ne $viewargs($n) || \
4336                $newviewopts($n,cmd) ne $viewargscmd($n)} {
4337            set viewfiles($n) $files
4338            set viewargs($n) $newargs
4339            set viewargscmd($n) $newviewopts($n,cmd)
4340            if {$curview == $n} {
4341                run reloadcommits
4342            }
4343        }
4344    }
4345    if {$apply} return
4346    catch {destroy $top}
4347}
4348
4349proc delview {} {
4350    global curview viewperm hlview selectedhlview
4351
4352    if {$curview == 0} return
4353    if {[info exists hlview] && $hlview == $curview} {
4354        set selectedhlview [mc "None"]
4355        unset hlview
4356    }
4357    allviewmenus $curview delete
4358    set viewperm($curview) 0
4359    showview 0
4360}
4361
4362proc addviewmenu {n} {
4363    global viewname viewhlmenu
4364
4365    .bar.view add radiobutton -label $viewname($n) \
4366        -command [list showview $n] -variable selectedview -value $n
4367    #$viewhlmenu add radiobutton -label $viewname($n) \
4368    #   -command [list addvhighlight $n] -variable selectedhlview
4369}
4370
4371proc showview {n} {
4372    global curview cached_commitrow ordertok
4373    global displayorder parentlist rowidlist rowisopt rowfinal
4374    global colormap rowtextx nextcolor canvxmax
4375    global numcommits viewcomplete
4376    global selectedline currentid canv canvy0
4377    global treediffs
4378    global pending_select mainheadid
4379    global commitidx
4380    global selectedview
4381    global hlview selectedhlview commitinterest
4382
4383    if {$n == $curview} return
4384    set selid {}
4385    set ymax [lindex [$canv cget -scrollregion] 3]
4386    set span [$canv yview]
4387    set ytop [expr {[lindex $span 0] * $ymax}]
4388    set ybot [expr {[lindex $span 1] * $ymax}]
4389    set yscreen [expr {($ybot - $ytop) / 2}]
4390    if {$selectedline ne {}} {
4391        set selid $currentid
4392        set y [yc $selectedline]
4393        if {$ytop < $y && $y < $ybot} {
4394            set yscreen [expr {$y - $ytop}]
4395        }
4396    } elseif {[info exists pending_select]} {
4397        set selid $pending_select
4398        unset pending_select
4399    }
4400    unselectline
4401    normalline
4402    catch {unset treediffs}
4403    clear_display
4404    if {[info exists hlview] && $hlview == $n} {
4405        unset hlview
4406        set selectedhlview [mc "None"]
4407    }
4408    catch {unset commitinterest}
4409    catch {unset cached_commitrow}
4410    catch {unset ordertok}
4411
4412    set curview $n
4413    set selectedview $n
4414    .bar.view entryconf [mca "Edit view..."] -state [expr {$n == 0? "disabled": "normal"}]
4415    .bar.view entryconf [mca "Delete view"] -state [expr {$n == 0? "disabled": "normal"}]
4416
4417    run refill_reflist
4418    if {![info exists viewcomplete($n)]} {
4419        getcommits $selid
4420        return
4421    }
4422
4423    set displayorder {}
4424    set parentlist {}
4425    set rowidlist {}
4426    set rowisopt {}
4427    set rowfinal {}
4428    set numcommits $commitidx($n)
4429
4430    catch {unset colormap}
4431    catch {unset rowtextx}
4432    set nextcolor 0
4433    set canvxmax [$canv cget -width]
4434    set curview $n
4435    set row 0
4436    setcanvscroll
4437    set yf 0
4438    set row {}
4439    if {$selid ne {} && [commitinview $selid $n]} {
4440        set row [rowofcommit $selid]
4441        # try to get the selected row in the same position on the screen
4442        set ymax [lindex [$canv cget -scrollregion] 3]
4443        set ytop [expr {[yc $row] - $yscreen}]
4444        if {$ytop < 0} {
4445            set ytop 0
4446        }
4447        set yf [expr {$ytop * 1.0 / $ymax}]
4448    }
4449    allcanvs yview moveto $yf
4450    drawvisible
4451    if {$row ne {}} {
4452        selectline $row 0
4453    } elseif {!$viewcomplete($n)} {
4454        reset_pending_select $selid
4455    } else {
4456        reset_pending_select {}
4457
4458        if {[commitinview $pending_select $curview]} {
4459            selectline [rowofcommit $pending_select] 1
4460        } else {
4461            set row [first_real_row]
4462            if {$row < $numcommits} {
4463                selectline $row 0
4464            }
4465        }
4466    }
4467    if {!$viewcomplete($n)} {
4468        if {$numcommits == 0} {
4469            show_status [mc "Reading commits..."]
4470        }
4471    } elseif {$numcommits == 0} {
4472        show_status [mc "No commits selected"]
4473    }
4474}
4475
4476# Stuff relating to the highlighting facility
4477
4478proc ishighlighted {id} {
4479    global vhighlights fhighlights nhighlights rhighlights
4480
4481    if {[info exists nhighlights($id)] && $nhighlights($id) > 0} {
4482        return $nhighlights($id)
4483    }
4484    if {[info exists vhighlights($id)] && $vhighlights($id) > 0} {
4485        return $vhighlights($id)
4486    }
4487    if {[info exists fhighlights($id)] && $fhighlights($id) > 0} {
4488        return $fhighlights($id)
4489    }
4490    if {[info exists rhighlights($id)] && $rhighlights($id) > 0} {
4491        return $rhighlights($id)
4492    }
4493    return 0
4494}
4495
4496proc bolden {id font} {
4497    global canv linehtag currentid boldids need_redisplay markedid
4498
4499    # need_redisplay = 1 means the display is stale and about to be redrawn
4500    if {$need_redisplay} return
4501    lappend boldids $id
4502    $canv itemconf $linehtag($id) -font $font
4503    if {[info exists currentid] && $id eq $currentid} {
4504        $canv delete secsel
4505        set t [eval $canv create rect [$canv bbox $linehtag($id)] \
4506                   -outline {{}} -tags secsel \
4507                   -fill [$canv cget -selectbackground]]
4508        $canv lower $t
4509    }
4510    if {[info exists markedid] && $id eq $markedid} {
4511        make_idmark $id
4512    }
4513}
4514
4515proc bolden_name {id font} {
4516    global canv2 linentag currentid boldnameids need_redisplay
4517
4518    if {$need_redisplay} return
4519    lappend boldnameids $id
4520    $canv2 itemconf $linentag($id) -font $font
4521    if {[info exists currentid] && $id eq $currentid} {
4522        $canv2 delete secsel
4523        set t [eval $canv2 create rect [$canv2 bbox $linentag($id)] \
4524                   -outline {{}} -tags secsel \
4525                   -fill [$canv2 cget -selectbackground]]
4526        $canv2 lower $t
4527    }
4528}
4529
4530proc unbolden {} {
4531    global boldids
4532
4533    set stillbold {}
4534    foreach id $boldids {
4535        if {![ishighlighted $id]} {
4536            bolden $id mainfont
4537        } else {
4538            lappend stillbold $id
4539        }
4540    }
4541    set boldids $stillbold
4542}
4543
4544proc addvhighlight {n} {
4545    global hlview viewcomplete curview vhl_done commitidx
4546
4547    if {[info exists hlview]} {
4548        delvhighlight
4549    }
4550    set hlview $n
4551    if {$n != $curview && ![info exists viewcomplete($n)]} {
4552        start_rev_list $n
4553    }
4554    set vhl_done $commitidx($hlview)
4555    if {$vhl_done > 0} {
4556        drawvisible
4557    }
4558}
4559
4560proc delvhighlight {} {
4561    global hlview vhighlights
4562
4563    if {![info exists hlview]} return
4564    unset hlview
4565    catch {unset vhighlights}
4566    unbolden
4567}
4568
4569proc vhighlightmore {} {
4570    global hlview vhl_done commitidx vhighlights curview
4571
4572    set max $commitidx($hlview)
4573    set vr [visiblerows]
4574    set r0 [lindex $vr 0]
4575    set r1 [lindex $vr 1]
4576    for {set i $vhl_done} {$i < $max} {incr i} {
4577        set id [commitonrow $i $hlview]
4578        if {[commitinview $id $curview]} {
4579            set row [rowofcommit $id]
4580            if {$r0 <= $row && $row <= $r1} {
4581                if {![highlighted $row]} {
4582                    bolden $id mainfontbold
4583                }
4584                set vhighlights($id) 1
4585            }
4586        }
4587    }
4588    set vhl_done $max
4589    return 0
4590}
4591
4592proc askvhighlight {row id} {
4593    global hlview vhighlights iddrawn
4594
4595    if {[commitinview $id $hlview]} {
4596        if {[info exists iddrawn($id)] && ![ishighlighted $id]} {
4597            bolden $id mainfontbold
4598        }
4599        set vhighlights($id) 1
4600    } else {
4601        set vhighlights($id) 0
4602    }
4603}
4604
4605proc hfiles_change {} {
4606    global highlight_files filehighlight fhighlights fh_serial
4607    global highlight_paths
4608
4609    if {[info exists filehighlight]} {
4610        # delete previous highlights
4611        catch {close $filehighlight}
4612        unset filehighlight
4613        catch {unset fhighlights}
4614        unbolden
4615        unhighlight_filelist
4616    }
4617    set highlight_paths {}
4618    after cancel do_file_hl $fh_serial
4619    incr fh_serial
4620    if {$highlight_files ne {}} {
4621        after 300 do_file_hl $fh_serial
4622    }
4623}
4624
4625proc gdttype_change {name ix op} {
4626    global gdttype highlight_files findstring findpattern
4627
4628    stopfinding
4629    if {$findstring ne {}} {
4630        if {$gdttype eq [mc "containing:"]} {
4631            if {$highlight_files ne {}} {
4632                set highlight_files {}
4633                hfiles_change
4634            }
4635            findcom_change
4636        } else {
4637            if {$findpattern ne {}} {
4638                set findpattern {}
4639                findcom_change
4640            }
4641            set highlight_files $findstring
4642            hfiles_change
4643        }
4644        drawvisible
4645    }
4646    # enable/disable findtype/findloc menus too
4647}
4648
4649proc find_change {name ix op} {
4650    global gdttype findstring highlight_files
4651
4652    stopfinding
4653    if {$gdttype eq [mc "containing:"]} {
4654        findcom_change
4655    } else {
4656        if {$highlight_files ne $findstring} {
4657            set highlight_files $findstring
4658            hfiles_change
4659        }
4660    }
4661    drawvisible
4662}
4663
4664proc findcom_change args {
4665    global nhighlights boldnameids
4666    global findpattern findtype findstring gdttype
4667
4668    stopfinding
4669    # delete previous highlights, if any
4670    foreach id $boldnameids {
4671        bolden_name $id mainfont
4672    }
4673    set boldnameids {}
4674    catch {unset nhighlights}
4675    unbolden
4676    unmarkmatches
4677    if {$gdttype ne [mc "containing:"] || $findstring eq {}} {
4678        set findpattern {}
4679    } elseif {$findtype eq [mc "Regexp"]} {
4680        set findpattern $findstring
4681    } else {
4682        set e [string map {"*" "\\*" "?" "\\?" "\[" "\\\[" "\\" "\\\\"} \
4683                   $findstring]
4684        set findpattern "*$e*"
4685    }
4686}
4687
4688proc makepatterns {l} {
4689    set ret {}
4690    foreach e $l {
4691        set ee [string map {"*" "\\*" "?" "\\?" "\[" "\\\[" "\\" "\\\\"} $e]
4692        if {[string index $ee end] eq "/"} {
4693            lappend ret "$ee*"
4694        } else {
4695            lappend ret $ee
4696            lappend ret "$ee/*"
4697        }
4698    }
4699    return $ret
4700}
4701
4702proc do_file_hl {serial} {
4703    global highlight_files filehighlight highlight_paths gdttype fhl_list
4704    global cdup findtype
4705
4706    if {$gdttype eq [mc "touching paths:"]} {
4707        # If "exact" match then convert backslashes to forward slashes.
4708        # Most useful to support Windows-flavoured file paths.
4709        if {$findtype eq [mc "Exact"]} {
4710            set highlight_files [string map {"\\" "/"} $highlight_files]
4711        }
4712        if {[catch {set paths [shellsplit $highlight_files]}]} return
4713        set highlight_paths [makepatterns $paths]
4714        highlight_filelist
4715        set relative_paths {}
4716        foreach path $paths {
4717            lappend relative_paths [file join $cdup $path]
4718        }
4719        set gdtargs [concat -- $relative_paths]
4720    } elseif {$gdttype eq [mc "adding/removing string:"]} {
4721        set gdtargs [list "-S$highlight_files"]
4722    } elseif {$gdttype eq [mc "changing lines matching:"]} {
4723        set gdtargs [list "-G$highlight_files"]
4724    } else {
4725        # must be "containing:", i.e. we're searching commit info
4726        return
4727    }
4728    set cmd [concat | git diff-tree -r -s --stdin $gdtargs]
4729    set filehighlight [open $cmd r+]
4730    fconfigure $filehighlight -blocking 0
4731    filerun $filehighlight readfhighlight
4732    set fhl_list {}
4733    drawvisible
4734    flushhighlights
4735}
4736
4737proc flushhighlights {} {
4738    global filehighlight fhl_list
4739
4740    if {[info exists filehighlight]} {
4741        lappend fhl_list {}
4742        puts $filehighlight ""
4743        flush $filehighlight
4744    }
4745}
4746
4747proc askfilehighlight {row id} {
4748    global filehighlight fhighlights fhl_list
4749
4750    lappend fhl_list $id
4751    set fhighlights($id) -1
4752    puts $filehighlight $id
4753}
4754
4755proc readfhighlight {} {
4756    global filehighlight fhighlights curview iddrawn
4757    global fhl_list find_dirn
4758
4759    if {![info exists filehighlight]} {
4760        return 0
4761    }
4762    set nr 0
4763    while {[incr nr] <= 100 && [gets $filehighlight line] >= 0} {
4764        set line [string trim $line]
4765        set i [lsearch -exact $fhl_list $line]
4766        if {$i < 0} continue
4767        for {set j 0} {$j < $i} {incr j} {
4768            set id [lindex $fhl_list $j]
4769            set fhighlights($id) 0
4770        }
4771        set fhl_list [lrange $fhl_list [expr {$i+1}] end]
4772        if {$line eq {}} continue
4773        if {![commitinview $line $curview]} continue
4774        if {[info exists iddrawn($line)] && ![ishighlighted $line]} {
4775            bolden $line mainfontbold
4776        }
4777        set fhighlights($line) 1
4778    }
4779    if {[eof $filehighlight]} {
4780        # strange...
4781        puts "oops, git diff-tree died"
4782        catch {close $filehighlight}
4783        unset filehighlight
4784        return 0
4785    }
4786    if {[info exists find_dirn]} {
4787        run findmore
4788    }
4789    return 1
4790}
4791
4792proc doesmatch {f} {
4793    global findtype findpattern
4794
4795    if {$findtype eq [mc "Regexp"]} {
4796        return [regexp $findpattern $f]
4797    } elseif {$findtype eq [mc "IgnCase"]} {
4798        return [string match -nocase $findpattern $f]
4799    } else {
4800        return [string match $findpattern $f]
4801    }
4802}
4803
4804proc askfindhighlight {row id} {
4805    global nhighlights commitinfo iddrawn
4806    global findloc
4807    global markingmatches
4808
4809    if {![info exists commitinfo($id)]} {
4810        getcommit $id
4811    }
4812    set info $commitinfo($id)
4813    set isbold 0
4814    set fldtypes [list [mc Headline] [mc Author] "" [mc Committer] "" [mc Comments]]
4815    foreach f $info ty $fldtypes {
4816        if {$ty eq ""} continue
4817        if {($findloc eq [mc "All fields"] || $findloc eq $ty) &&
4818            [doesmatch $f]} {
4819            if {$ty eq [mc "Author"]} {
4820                set isbold 2
4821                break
4822            }
4823            set isbold 1
4824        }
4825    }
4826    if {$isbold && [info exists iddrawn($id)]} {
4827        if {![ishighlighted $id]} {
4828            bolden $id mainfontbold
4829            if {$isbold > 1} {
4830                bolden_name $id mainfontbold
4831            }
4832        }
4833        if {$markingmatches} {
4834            markrowmatches $row $id
4835        }
4836    }
4837    set nhighlights($id) $isbold
4838}
4839
4840proc markrowmatches {row id} {
4841    global canv canv2 linehtag linentag commitinfo findloc
4842
4843    set headline [lindex $commitinfo($id) 0]
4844    set author [lindex $commitinfo($id) 1]
4845    $canv delete match$row
4846    $canv2 delete match$row
4847    if {$findloc eq [mc "All fields"] || $findloc eq [mc "Headline"]} {
4848        set m [findmatches $headline]
4849        if {$m ne {}} {
4850            markmatches $canv $row $headline $linehtag($id) $m \
4851                [$canv itemcget $linehtag($id) -font] $row
4852        }
4853    }
4854    if {$findloc eq [mc "All fields"] || $findloc eq [mc "Author"]} {
4855        set m [findmatches $author]
4856        if {$m ne {}} {
4857            markmatches $canv2 $row $author $linentag($id) $m \
4858                [$canv2 itemcget $linentag($id) -font] $row
4859        }
4860    }
4861}
4862
4863proc vrel_change {name ix op} {
4864    global highlight_related
4865
4866    rhighlight_none
4867    if {$highlight_related ne [mc "None"]} {
4868        run drawvisible
4869    }
4870}
4871
4872# prepare for testing whether commits are descendents or ancestors of a
4873proc rhighlight_sel {a} {
4874    global descendent desc_todo ancestor anc_todo
4875    global highlight_related
4876
4877    catch {unset descendent}
4878    set desc_todo [list $a]
4879    catch {unset ancestor}
4880    set anc_todo [list $a]
4881    if {$highlight_related ne [mc "None"]} {
4882        rhighlight_none
4883        run drawvisible
4884    }
4885}
4886
4887proc rhighlight_none {} {
4888    global rhighlights
4889
4890    catch {unset rhighlights}
4891    unbolden
4892}
4893
4894proc is_descendent {a} {
4895    global curview children descendent desc_todo
4896
4897    set v $curview
4898    set la [rowofcommit $a]
4899    set todo $desc_todo
4900    set leftover {}
4901    set done 0
4902    for {set i 0} {$i < [llength $todo]} {incr i} {
4903        set do [lindex $todo $i]
4904        if {[rowofcommit $do] < $la} {
4905            lappend leftover $do
4906            continue
4907        }
4908        foreach nk $children($v,$do) {
4909            if {![info exists descendent($nk)]} {
4910                set descendent($nk) 1
4911                lappend todo $nk
4912                if {$nk eq $a} {
4913                    set done 1
4914                }
4915            }
4916        }
4917        if {$done} {
4918            set desc_todo [concat $leftover [lrange $todo [expr {$i+1}] end]]
4919            return
4920        }
4921    }
4922    set descendent($a) 0
4923    set desc_todo $leftover
4924}
4925
4926proc is_ancestor {a} {
4927    global curview parents ancestor anc_todo
4928
4929    set v $curview
4930    set la [rowofcommit $a]
4931    set todo $anc_todo
4932    set leftover {}
4933    set done 0
4934    for {set i 0} {$i < [llength $todo]} {incr i} {
4935        set do [lindex $todo $i]
4936        if {![commitinview $do $v] || [rowofcommit $do] > $la} {
4937            lappend leftover $do
4938            continue
4939        }
4940        foreach np $parents($v,$do) {
4941            if {![info exists ancestor($np)]} {
4942                set ancestor($np) 1
4943                lappend todo $np
4944                if {$np eq $a} {
4945                    set done 1
4946                }
4947            }
4948        }
4949        if {$done} {
4950            set anc_todo [concat $leftover [lrange $todo [expr {$i+1}] end]]
4951            return
4952        }
4953    }
4954    set ancestor($a) 0
4955    set anc_todo $leftover
4956}
4957
4958proc askrelhighlight {row id} {
4959    global descendent highlight_related iddrawn rhighlights
4960    global selectedline ancestor
4961
4962    if {$selectedline eq {}} return
4963    set isbold 0
4964    if {$highlight_related eq [mc "Descendant"] ||
4965        $highlight_related eq [mc "Not descendant"]} {
4966        if {![info exists descendent($id)]} {
4967            is_descendent $id
4968        }
4969        if {$descendent($id) == ($highlight_related eq [mc "Descendant"])} {
4970            set isbold 1
4971        }
4972    } elseif {$highlight_related eq [mc "Ancestor"] ||
4973              $highlight_related eq [mc "Not ancestor"]} {
4974        if {![info exists ancestor($id)]} {
4975            is_ancestor $id
4976        }
4977        if {$ancestor($id) == ($highlight_related eq [mc "Ancestor"])} {
4978            set isbold 1
4979        }
4980    }
4981    if {[info exists iddrawn($id)]} {
4982        if {$isbold && ![ishighlighted $id]} {
4983            bolden $id mainfontbold
4984        }
4985    }
4986    set rhighlights($id) $isbold
4987}
4988
4989# Graph layout functions
4990
4991proc shortids {ids} {
4992    set res {}
4993    foreach id $ids {
4994        if {[llength $id] > 1} {
4995            lappend res [shortids $id]
4996        } elseif {[regexp {^[0-9a-f]{40}$} $id]} {
4997            lappend res [string range $id 0 7]
4998        } else {
4999            lappend res $id
5000        }
5001    }
5002    return $res
5003}
5004
5005proc ntimes {n o} {
5006    set ret {}
5007    set o [list $o]
5008    for {set mask 1} {$mask <= $n} {incr mask $mask} {
5009        if {($n & $mask) != 0} {
5010            set ret [concat $ret $o]
5011        }
5012        set o [concat $o $o]
5013    }
5014    return $ret
5015}
5016
5017proc ordertoken {id} {
5018    global ordertok curview varcid varcstart varctok curview parents children
5019    global nullid nullid2
5020
5021    if {[info exists ordertok($id)]} {
5022        return $ordertok($id)
5023    }
5024    set origid $id
5025    set todo {}
5026    while {1} {
5027        if {[info exists varcid($curview,$id)]} {
5028            set a $varcid($curview,$id)
5029            set p [lindex $varcstart($curview) $a]
5030        } else {
5031            set p [lindex $children($curview,$id) 0]
5032        }
5033        if {[info exists ordertok($p)]} {
5034            set tok $ordertok($p)
5035            break
5036        }
5037        set id [first_real_child $curview,$p]
5038        if {$id eq {}} {
5039            # it's a root
5040            set tok [lindex $varctok($curview) $varcid($curview,$p)]
5041            break
5042        }
5043        if {[llength $parents($curview,$id)] == 1} {
5044            lappend todo [list $p {}]
5045        } else {
5046            set j [lsearch -exact $parents($curview,$id) $p]
5047            if {$j < 0} {
5048                puts "oops didn't find [shortids $p] in parents of [shortids $id]"
5049            }
5050            lappend todo [list $p [strrep $j]]
5051        }
5052    }
5053    for {set i [llength $todo]} {[incr i -1] >= 0} {} {
5054        set p [lindex $todo $i 0]
5055        append tok [lindex $todo $i 1]
5056        set ordertok($p) $tok
5057    }
5058    set ordertok($origid) $tok
5059    return $tok
5060}
5061
5062# Work out where id should go in idlist so that order-token
5063# values increase from left to right
5064proc idcol {idlist id {i 0}} {
5065    set t [ordertoken $id]
5066    if {$i < 0} {
5067        set i 0
5068    }
5069    if {$i >= [llength $idlist] || $t < [ordertoken [lindex $idlist $i]]} {
5070        if {$i > [llength $idlist]} {
5071            set i [llength $idlist]
5072        }
5073        while {[incr i -1] >= 0 && $t < [ordertoken [lindex $idlist $i]]} {}
5074        incr i
5075    } else {
5076        if {$t > [ordertoken [lindex $idlist $i]]} {
5077            while {[incr i] < [llength $idlist] &&
5078                   $t >= [ordertoken [lindex $idlist $i]]} {}
5079        }
5080    }
5081    return $i
5082}
5083
5084proc initlayout {} {
5085    global rowidlist rowisopt rowfinal displayorder parentlist
5086    global numcommits canvxmax canv
5087    global nextcolor
5088    global colormap rowtextx
5089
5090    set numcommits 0
5091    set displayorder {}
5092    set parentlist {}
5093    set nextcolor 0
5094    set rowidlist {}
5095    set rowisopt {}
5096    set rowfinal {}
5097    set canvxmax [$canv cget -width]
5098    catch {unset colormap}
5099    catch {unset rowtextx}
5100    setcanvscroll
5101}
5102
5103proc setcanvscroll {} {
5104    global canv canv2 canv3 numcommits linespc canvxmax canvy0
5105    global lastscrollset lastscrollrows
5106
5107    set ymax [expr {$canvy0 + ($numcommits - 0.5) * $linespc + 2}]
5108    $canv conf -scrollregion [list 0 0 $canvxmax $ymax]
5109    $canv2 conf -scrollregion [list 0 0 0 $ymax]
5110    $canv3 conf -scrollregion [list 0 0 0 $ymax]
5111    set lastscrollset [clock clicks -milliseconds]
5112    set lastscrollrows $numcommits
5113}
5114
5115proc visiblerows {} {
5116    global canv numcommits linespc
5117
5118    set ymax [lindex [$canv cget -scrollregion] 3]
5119    if {$ymax eq {} || $ymax == 0} return
5120    set f [$canv yview]
5121    set y0 [expr {int([lindex $f 0] * $ymax)}]
5122    set r0 [expr {int(($y0 - 3) / $linespc) - 1}]
5123    if {$r0 < 0} {
5124        set r0 0
5125    }
5126    set y1 [expr {int([lindex $f 1] * $ymax)}]
5127    set r1 [expr {int(($y1 - 3) / $linespc) + 1}]
5128    if {$r1 >= $numcommits} {
5129        set r1 [expr {$numcommits - 1}]
5130    }
5131    return [list $r0 $r1]
5132}
5133
5134proc layoutmore {} {
5135    global commitidx viewcomplete curview
5136    global numcommits pending_select curview
5137    global lastscrollset lastscrollrows
5138
5139    if {$lastscrollrows < 100 || $viewcomplete($curview) ||
5140        [clock clicks -milliseconds] - $lastscrollset > 500} {
5141        setcanvscroll
5142    }
5143    if {[info exists pending_select] &&
5144        [commitinview $pending_select $curview]} {
5145        update
5146        selectline [rowofcommit $pending_select] 1
5147    }
5148    drawvisible
5149}
5150
5151# With path limiting, we mightn't get the actual HEAD commit,
5152# so ask git rev-list what is the first ancestor of HEAD that
5153# touches a file in the path limit.
5154proc get_viewmainhead {view} {
5155    global viewmainheadid vfilelimit viewinstances mainheadid
5156
5157    catch {
5158        set rfd [open [concat | git rev-list -1 $mainheadid \
5159                           -- $vfilelimit($view)] r]
5160        set j [reg_instance $rfd]
5161        lappend viewinstances($view) $j
5162        fconfigure $rfd -blocking 0
5163        filerun $rfd [list getviewhead $rfd $j $view]
5164        set viewmainheadid($curview) {}
5165    }
5166}
5167
5168# git rev-list should give us just 1 line to use as viewmainheadid($view)
5169proc getviewhead {fd inst view} {
5170    global viewmainheadid commfd curview viewinstances showlocalchanges
5171
5172    set id {}
5173    if {[gets $fd line] < 0} {
5174        if {![eof $fd]} {
5175            return 1
5176        }
5177    } elseif {[string length $line] == 40 && [string is xdigit $line]} {
5178        set id $line
5179    }
5180    set viewmainheadid($view) $id
5181    close $fd
5182    unset commfd($inst)
5183    set i [lsearch -exact $viewinstances($view) $inst]
5184    if {$i >= 0} {
5185        set viewinstances($view) [lreplace $viewinstances($view) $i $i]
5186    }
5187    if {$showlocalchanges && $id ne {} && $view == $curview} {
5188        doshowlocalchanges
5189    }
5190    return 0
5191}
5192
5193proc doshowlocalchanges {} {
5194    global curview viewmainheadid
5195
5196    if {$viewmainheadid($curview) eq {}} return
5197    if {[commitinview $viewmainheadid($curview) $curview]} {
5198        dodiffindex
5199    } else {
5200        interestedin $viewmainheadid($curview) dodiffindex
5201    }
5202}
5203
5204proc dohidelocalchanges {} {
5205    global nullid nullid2 lserial curview
5206
5207    if {[commitinview $nullid $curview]} {
5208        removefakerow $nullid
5209    }
5210    if {[commitinview $nullid2 $curview]} {
5211        removefakerow $nullid2
5212    }
5213    incr lserial
5214}
5215
5216# spawn off a process to do git diff-index --cached HEAD
5217proc dodiffindex {} {
5218    global lserial showlocalchanges vfilelimit curview
5219    global hasworktree git_version
5220
5221    if {!$showlocalchanges || !$hasworktree} return
5222    incr lserial
5223    if {[package vcompare $git_version "1.7.2"] >= 0} {
5224        set cmd "|git diff-index --cached --ignore-submodules=dirty HEAD"
5225    } else {
5226        set cmd "|git diff-index --cached HEAD"
5227    }
5228    if {$vfilelimit($curview) ne {}} {
5229        set cmd [concat $cmd -- $vfilelimit($curview)]
5230    }
5231    set fd [open $cmd r]
5232    fconfigure $fd -blocking 0
5233    set i [reg_instance $fd]
5234    filerun $fd [list readdiffindex $fd $lserial $i]
5235}
5236
5237proc readdiffindex {fd serial inst} {
5238    global viewmainheadid nullid nullid2 curview commitinfo commitdata lserial
5239    global vfilelimit
5240
5241    set isdiff 1
5242    if {[gets $fd line] < 0} {
5243        if {![eof $fd]} {
5244            return 1
5245        }
5246        set isdiff 0
5247    }
5248    # we only need to see one line and we don't really care what it says...
5249    stop_instance $inst
5250
5251    if {$serial != $lserial} {
5252        return 0
5253    }
5254
5255    # now see if there are any local changes not checked in to the index
5256    set cmd "|git diff-files"
5257    if {$vfilelimit($curview) ne {}} {
5258        set cmd [concat $cmd -- $vfilelimit($curview)]
5259    }
5260    set fd [open $cmd r]
5261    fconfigure $fd -blocking 0
5262    set i [reg_instance $fd]
5263    filerun $fd [list readdifffiles $fd $serial $i]
5264
5265    if {$isdiff && ![commitinview $nullid2 $curview]} {
5266        # add the line for the changes in the index to the graph
5267        set hl [mc "Local changes checked in to index but not committed"]
5268        set commitinfo($nullid2) [list  $hl {} {} {} {} "    $hl\n"]
5269        set commitdata($nullid2) "\n    $hl\n"
5270        if {[commitinview $nullid $curview]} {
5271            removefakerow $nullid
5272        }
5273        insertfakerow $nullid2 $viewmainheadid($curview)
5274    } elseif {!$isdiff && [commitinview $nullid2 $curview]} {
5275        if {[commitinview $nullid $curview]} {
5276            removefakerow $nullid
5277        }
5278        removefakerow $nullid2
5279    }
5280    return 0
5281}
5282
5283proc readdifffiles {fd serial inst} {
5284    global viewmainheadid nullid nullid2 curview
5285    global commitinfo commitdata lserial
5286
5287    set isdiff 1
5288    if {[gets $fd line] < 0} {
5289        if {![eof $fd]} {
5290            return 1
5291        }
5292        set isdiff 0
5293    }
5294    # we only need to see one line and we don't really care what it says...
5295    stop_instance $inst
5296
5297    if {$serial != $lserial} {
5298        return 0
5299    }
5300
5301    if {$isdiff && ![commitinview $nullid $curview]} {
5302        # add the line for the local diff to the graph
5303        set hl [mc "Local uncommitted changes, not checked in to index"]
5304        set commitinfo($nullid) [list  $hl {} {} {} {} "    $hl\n"]
5305        set commitdata($nullid) "\n    $hl\n"
5306        if {[commitinview $nullid2 $curview]} {
5307            set p $nullid2
5308        } else {
5309            set p $viewmainheadid($curview)
5310        }
5311        insertfakerow $nullid $p
5312    } elseif {!$isdiff && [commitinview $nullid $curview]} {
5313        removefakerow $nullid
5314    }
5315    return 0
5316}
5317
5318proc nextuse {id row} {
5319    global curview children
5320
5321    if {[info exists children($curview,$id)]} {
5322        foreach kid $children($curview,$id) {
5323            if {![commitinview $kid $curview]} {
5324                return -1
5325            }
5326            if {[rowofcommit $kid] > $row} {
5327                return [rowofcommit $kid]
5328            }
5329        }
5330    }
5331    if {[commitinview $id $curview]} {
5332        return [rowofcommit $id]
5333    }
5334    return -1
5335}
5336
5337proc prevuse {id row} {
5338    global curview children
5339
5340    set ret -1
5341    if {[info exists children($curview,$id)]} {
5342        foreach kid $children($curview,$id) {
5343            if {![commitinview $kid $curview]} break
5344            if {[rowofcommit $kid] < $row} {
5345                set ret [rowofcommit $kid]
5346            }
5347        }
5348    }
5349    return $ret
5350}
5351
5352proc make_idlist {row} {
5353    global displayorder parentlist uparrowlen downarrowlen mingaplen
5354    global commitidx curview children
5355
5356    set r [expr {$row - $mingaplen - $downarrowlen - 1}]
5357    if {$r < 0} {
5358        set r 0
5359    }
5360    set ra [expr {$row - $downarrowlen}]
5361    if {$ra < 0} {
5362        set ra 0
5363    }
5364    set rb [expr {$row + $uparrowlen}]
5365    if {$rb > $commitidx($curview)} {
5366        set rb $commitidx($curview)
5367    }
5368    make_disporder $r [expr {$rb + 1}]
5369    set ids {}
5370    for {} {$r < $ra} {incr r} {
5371        set nextid [lindex $displayorder [expr {$r + 1}]]
5372        foreach p [lindex $parentlist $r] {
5373            if {$p eq $nextid} continue
5374            set rn [nextuse $p $r]
5375            if {$rn >= $row &&
5376                $rn <= $r + $downarrowlen + $mingaplen + $uparrowlen} {
5377                lappend ids [list [ordertoken $p] $p]
5378            }
5379        }
5380    }
5381    for {} {$r < $row} {incr r} {
5382        set nextid [lindex $displayorder [expr {$r + 1}]]
5383        foreach p [lindex $parentlist $r] {
5384            if {$p eq $nextid} continue
5385            set rn [nextuse $p $r]
5386            if {$rn < 0 || $rn >= $row} {
5387                lappend ids [list [ordertoken $p] $p]
5388            }
5389        }
5390    }
5391    set id [lindex $displayorder $row]
5392    lappend ids [list [ordertoken $id] $id]
5393    while {$r < $rb} {
5394        foreach p [lindex $parentlist $r] {
5395            set firstkid [lindex $children($curview,$p) 0]
5396            if {[rowofcommit $firstkid] < $row} {
5397                lappend ids [list [ordertoken $p] $p]
5398            }
5399        }
5400        incr r
5401        set id [lindex $displayorder $r]
5402        if {$id ne {}} {
5403            set firstkid [lindex $children($curview,$id) 0]
5404            if {$firstkid ne {} && [rowofcommit $firstkid] < $row} {
5405                lappend ids [list [ordertoken $id] $id]
5406            }
5407        }
5408    }
5409    set idlist {}
5410    foreach idx [lsort -unique $ids] {
5411        lappend idlist [lindex $idx 1]
5412    }
5413    return $idlist
5414}
5415
5416proc rowsequal {a b} {
5417    while {[set i [lsearch -exact $a {}]] >= 0} {
5418        set a [lreplace $a $i $i]
5419    }
5420    while {[set i [lsearch -exact $b {}]] >= 0} {
5421        set b [lreplace $b $i $i]
5422    }
5423    return [expr {$a eq $b}]
5424}
5425
5426proc makeupline {id row rend col} {
5427    global rowidlist uparrowlen downarrowlen mingaplen
5428
5429    for {set r $rend} {1} {set r $rstart} {
5430        set rstart [prevuse $id $r]
5431        if {$rstart < 0} return
5432        if {$rstart < $row} break
5433    }
5434    if {$rstart + $uparrowlen + $mingaplen + $downarrowlen < $rend} {
5435        set rstart [expr {$rend - $uparrowlen - 1}]
5436    }
5437    for {set r $rstart} {[incr r] <= $row} {} {
5438        set idlist [lindex $rowidlist $r]
5439        if {$idlist ne {} && [lsearch -exact $idlist $id] < 0} {
5440            set col [idcol $idlist $id $col]
5441            lset rowidlist $r [linsert $idlist $col $id]
5442            changedrow $r
5443        }
5444    }
5445}
5446
5447proc layoutrows {row endrow} {
5448    global rowidlist rowisopt rowfinal displayorder
5449    global uparrowlen downarrowlen maxwidth mingaplen
5450    global children parentlist
5451    global commitidx viewcomplete curview
5452
5453    make_disporder [expr {$row - 1}] [expr {$endrow + $uparrowlen}]
5454    set idlist {}
5455    if {$row > 0} {
5456        set rm1 [expr {$row - 1}]
5457        foreach id [lindex $rowidlist $rm1] {
5458            if {$id ne {}} {
5459                lappend idlist $id
5460            }
5461        }
5462        set final [lindex $rowfinal $rm1]
5463    }
5464    for {} {$row < $endrow} {incr row} {
5465        set rm1 [expr {$row - 1}]
5466        if {$rm1 < 0 || $idlist eq {}} {
5467            set idlist [make_idlist $row]
5468            set final 1
5469        } else {
5470            set id [lindex $displayorder $rm1]
5471            set col [lsearch -exact $idlist $id]
5472            set idlist [lreplace $idlist $col $col]
5473            foreach p [lindex $parentlist $rm1] {
5474                if {[lsearch -exact $idlist $p] < 0} {
5475                    set col [idcol $idlist $p $col]
5476                    set idlist [linsert $idlist $col $p]
5477                    # if not the first child, we have to insert a line going up
5478                    if {$id ne [lindex $children($curview,$p) 0]} {
5479                        makeupline $p $rm1 $row $col
5480                    }
5481                }
5482            }
5483            set id [lindex $displayorder $row]
5484            if {$row > $downarrowlen} {
5485                set termrow [expr {$row - $downarrowlen - 1}]
5486                foreach p [lindex $parentlist $termrow] {
5487                    set i [lsearch -exact $idlist $p]
5488                    if {$i < 0} continue
5489                    set nr [nextuse $p $termrow]
5490                    if {$nr < 0 || $nr >= $row + $mingaplen + $uparrowlen} {
5491                        set idlist [lreplace $idlist $i $i]
5492                    }
5493                }
5494            }
5495            set col [lsearch -exact $idlist $id]
5496            if {$col < 0} {
5497                set col [idcol $idlist $id]
5498                set idlist [linsert $idlist $col $id]
5499                if {$children($curview,$id) ne {}} {
5500                    makeupline $id $rm1 $row $col
5501                }
5502            }
5503            set r [expr {$row + $uparrowlen - 1}]
5504            if {$r < $commitidx($curview)} {
5505                set x $col
5506                foreach p [lindex $parentlist $r] {
5507                    if {[lsearch -exact $idlist $p] >= 0} continue
5508                    set fk [lindex $children($curview,$p) 0]
5509                    if {[rowofcommit $fk] < $row} {
5510                        set x [idcol $idlist $p $x]
5511                        set idlist [linsert $idlist $x $p]
5512                    }
5513                }
5514                if {[incr r] < $commitidx($curview)} {
5515                    set p [lindex $displayorder $r]
5516                    if {[lsearch -exact $idlist $p] < 0} {
5517                        set fk [lindex $children($curview,$p) 0]
5518                        if {$fk ne {} && [rowofcommit $fk] < $row} {
5519                            set x [idcol $idlist $p $x]
5520                            set idlist [linsert $idlist $x $p]
5521                        }
5522                    }
5523                }
5524            }
5525        }
5526        if {$final && !$viewcomplete($curview) &&
5527            $row + $uparrowlen + $mingaplen + $downarrowlen
5528                >= $commitidx($curview)} {
5529            set final 0
5530        }
5531        set l [llength $rowidlist]
5532        if {$row == $l} {
5533            lappend rowidlist $idlist
5534            lappend rowisopt 0
5535            lappend rowfinal $final
5536        } elseif {$row < $l} {
5537            if {![rowsequal $idlist [lindex $rowidlist $row]]} {
5538                lset rowidlist $row $idlist
5539                changedrow $row
5540            }
5541            lset rowfinal $row $final
5542        } else {
5543            set pad [ntimes [expr {$row - $l}] {}]
5544            set rowidlist [concat $rowidlist $pad]
5545            lappend rowidlist $idlist
5546            set rowfinal [concat $rowfinal $pad]
5547            lappend rowfinal $final
5548            set rowisopt [concat $rowisopt [ntimes [expr {$row - $l + 1}] 0]]
5549        }
5550    }
5551    return $row
5552}
5553
5554proc changedrow {row} {
5555    global displayorder iddrawn rowisopt need_redisplay
5556
5557    set l [llength $rowisopt]
5558    if {$row < $l} {
5559        lset rowisopt $row 0
5560        if {$row + 1 < $l} {
5561            lset rowisopt [expr {$row + 1}] 0
5562            if {$row + 2 < $l} {
5563                lset rowisopt [expr {$row + 2}] 0
5564            }
5565        }
5566    }
5567    set id [lindex $displayorder $row]
5568    if {[info exists iddrawn($id)]} {
5569        set need_redisplay 1
5570    }
5571}
5572
5573proc insert_pad {row col npad} {
5574    global rowidlist
5575
5576    set pad [ntimes $npad {}]
5577    set idlist [lindex $rowidlist $row]
5578    set bef [lrange $idlist 0 [expr {$col - 1}]]
5579    set aft [lrange $idlist $col end]
5580    set i [lsearch -exact $aft {}]
5581    if {$i > 0} {
5582        set aft [lreplace $aft $i $i]
5583    }
5584    lset rowidlist $row [concat $bef $pad $aft]
5585    changedrow $row
5586}
5587
5588proc optimize_rows {row col endrow} {
5589    global rowidlist rowisopt displayorder curview children
5590
5591    if {$row < 1} {
5592        set row 1
5593    }
5594    for {} {$row < $endrow} {incr row; set col 0} {
5595        if {[lindex $rowisopt $row]} continue
5596        set haspad 0
5597        set y0 [expr {$row - 1}]
5598        set ym [expr {$row - 2}]
5599        set idlist [lindex $rowidlist $row]
5600        set previdlist [lindex $rowidlist $y0]
5601        if {$idlist eq {} || $previdlist eq {}} continue
5602        if {$ym >= 0} {
5603            set pprevidlist [lindex $rowidlist $ym]
5604            if {$pprevidlist eq {}} continue
5605        } else {
5606            set pprevidlist {}
5607        }
5608        set x0 -1
5609        set xm -1
5610        for {} {$col < [llength $idlist]} {incr col} {
5611            set id [lindex $idlist $col]
5612            if {[lindex $previdlist $col] eq $id} continue
5613            if {$id eq {}} {
5614                set haspad 1
5615                continue
5616            }
5617            set x0 [lsearch -exact $previdlist $id]
5618            if {$x0 < 0} continue
5619            set z [expr {$x0 - $col}]
5620            set isarrow 0
5621            set z0 {}
5622            if {$ym >= 0} {
5623                set xm [lsearch -exact $pprevidlist $id]
5624                if {$xm >= 0} {
5625                    set z0 [expr {$xm - $x0}]
5626                }
5627            }
5628            if {$z0 eq {}} {
5629                # if row y0 is the first child of $id then it's not an arrow
5630                if {[lindex $children($curview,$id) 0] ne
5631                    [lindex $displayorder $y0]} {
5632                    set isarrow 1
5633                }
5634            }
5635            if {!$isarrow && $id ne [lindex $displayorder $row] &&
5636                [lsearch -exact [lindex $rowidlist [expr {$row+1}]] $id] < 0} {
5637                set isarrow 1
5638            }
5639            # Looking at lines from this row to the previous row,
5640            # make them go straight up if they end in an arrow on
5641            # the previous row; otherwise make them go straight up
5642            # or at 45 degrees.
5643            if {$z < -1 || ($z < 0 && $isarrow)} {
5644                # Line currently goes left too much;
5645                # insert pads in the previous row, then optimize it
5646                set npad [expr {-1 - $z + $isarrow}]
5647                insert_pad $y0 $x0 $npad
5648                if {$y0 > 0} {
5649                    optimize_rows $y0 $x0 $row
5650                }
5651                set previdlist [lindex $rowidlist $y0]
5652                set x0 [lsearch -exact $previdlist $id]
5653                set z [expr {$x0 - $col}]
5654                if {$z0 ne {}} {
5655                    set pprevidlist [lindex $rowidlist $ym]
5656                    set xm [lsearch -exact $pprevidlist $id]
5657                    set z0 [expr {$xm - $x0}]
5658                }
5659            } elseif {$z > 1 || ($z > 0 && $isarrow)} {
5660                # Line currently goes right too much;
5661                # insert pads in this line
5662                set npad [expr {$z - 1 + $isarrow}]
5663                insert_pad $row $col $npad
5664                set idlist [lindex $rowidlist $row]
5665                incr col $npad
5666                set z [expr {$x0 - $col}]
5667                set haspad 1
5668            }
5669            if {$z0 eq {} && !$isarrow && $ym >= 0} {
5670                # this line links to its first child on row $row-2
5671                set id [lindex $displayorder $ym]
5672                set xc [lsearch -exact $pprevidlist $id]
5673                if {$xc >= 0} {
5674                    set z0 [expr {$xc - $x0}]
5675                }
5676            }
5677            # avoid lines jigging left then immediately right
5678            if {$z0 ne {} && $z < 0 && $z0 > 0} {
5679                insert_pad $y0 $x0 1
5680                incr x0
5681                optimize_rows $y0 $x0 $row
5682                set previdlist [lindex $rowidlist $y0]
5683            }
5684        }
5685        if {!$haspad} {
5686            # Find the first column that doesn't have a line going right
5687            for {set col [llength $idlist]} {[incr col -1] >= 0} {} {
5688                set id [lindex $idlist $col]
5689                if {$id eq {}} break
5690                set x0 [lsearch -exact $previdlist $id]
5691                if {$x0 < 0} {
5692                    # check if this is the link to the first child
5693                    set kid [lindex $displayorder $y0]
5694                    if {[lindex $children($curview,$id) 0] eq $kid} {
5695                        # it is, work out offset to child
5696                        set x0 [lsearch -exact $previdlist $kid]
5697                    }
5698                }
5699                if {$x0 <= $col} break
5700            }
5701            # Insert a pad at that column as long as it has a line and
5702            # isn't the last column
5703            if {$x0 >= 0 && [incr col] < [llength $idlist]} {
5704                set idlist [linsert $idlist $col {}]
5705                lset rowidlist $row $idlist
5706                changedrow $row
5707            }
5708        }
5709    }
5710}
5711
5712proc xc {row col} {
5713    global canvx0 linespc
5714    return [expr {$canvx0 + $col * $linespc}]
5715}
5716
5717proc yc {row} {
5718    global canvy0 linespc
5719    return [expr {$canvy0 + $row * $linespc}]
5720}
5721
5722proc linewidth {id} {
5723    global thickerline lthickness
5724
5725    set wid $lthickness
5726    if {[info exists thickerline] && $id eq $thickerline} {
5727        set wid [expr {2 * $lthickness}]
5728    }
5729    return $wid
5730}
5731
5732proc rowranges {id} {
5733    global curview children uparrowlen downarrowlen
5734    global rowidlist
5735
5736    set kids $children($curview,$id)
5737    if {$kids eq {}} {
5738        return {}
5739    }
5740    set ret {}
5741    lappend kids $id
5742    foreach child $kids {
5743        if {![commitinview $child $curview]} break
5744        set row [rowofcommit $child]
5745        if {![info exists prev]} {
5746            lappend ret [expr {$row + 1}]
5747        } else {
5748            if {$row <= $prevrow} {
5749                puts "oops children of [shortids $id] out of order [shortids $child] $row <= [shortids $prev] $prevrow"
5750            }
5751            # see if the line extends the whole way from prevrow to row
5752            if {$row > $prevrow + $uparrowlen + $downarrowlen &&
5753                [lsearch -exact [lindex $rowidlist \
5754                            [expr {int(($row + $prevrow) / 2)}]] $id] < 0} {
5755                # it doesn't, see where it ends
5756                set r [expr {$prevrow + $downarrowlen}]
5757                if {[lsearch -exact [lindex $rowidlist $r] $id] < 0} {
5758                    while {[incr r -1] > $prevrow &&
5759                           [lsearch -exact [lindex $rowidlist $r] $id] < 0} {}
5760                } else {
5761                    while {[incr r] <= $row &&
5762                           [lsearch -exact [lindex $rowidlist $r] $id] >= 0} {}
5763                    incr r -1
5764                }
5765                lappend ret $r
5766                # see where it starts up again
5767                set r [expr {$row - $uparrowlen}]
5768                if {[lsearch -exact [lindex $rowidlist $r] $id] < 0} {
5769                    while {[incr r] < $row &&
5770                           [lsearch -exact [lindex $rowidlist $r] $id] < 0} {}
5771                } else {
5772                    while {[incr r -1] >= $prevrow &&
5773                           [lsearch -exact [lindex $rowidlist $r] $id] >= 0} {}
5774                    incr r
5775                }
5776                lappend ret $r
5777            }
5778        }
5779        if {$child eq $id} {
5780            lappend ret $row
5781        }
5782        set prev $child
5783        set prevrow $row
5784    }
5785    return $ret
5786}
5787
5788proc drawlineseg {id row endrow arrowlow} {
5789    global rowidlist displayorder iddrawn linesegs
5790    global canv colormap linespc curview maxlinelen parentlist
5791
5792    set cols [list [lsearch -exact [lindex $rowidlist $row] $id]]
5793    set le [expr {$row + 1}]
5794    set arrowhigh 1
5795    while {1} {
5796        set c [lsearch -exact [lindex $rowidlist $le] $id]
5797        if {$c < 0} {
5798            incr le -1
5799            break
5800        }
5801        lappend cols $c
5802        set x [lindex $displayorder $le]
5803        if {$x eq $id} {
5804            set arrowhigh 0
5805            break
5806        }
5807        if {[info exists iddrawn($x)] || $le == $endrow} {
5808            set c [lsearch -exact [lindex $rowidlist [expr {$le+1}]] $id]
5809            if {$c >= 0} {
5810                lappend cols $c
5811                set arrowhigh 0
5812            }
5813            break
5814        }
5815        incr le
5816    }
5817    if {$le <= $row} {
5818        return $row
5819    }
5820
5821    set lines {}
5822    set i 0
5823    set joinhigh 0
5824    if {[info exists linesegs($id)]} {
5825        set lines $linesegs($id)
5826        foreach li $lines {
5827            set r0 [lindex $li 0]
5828            if {$r0 > $row} {
5829                if {$r0 == $le && [lindex $li 1] - $row <= $maxlinelen} {
5830                    set joinhigh 1
5831                }
5832                break
5833            }
5834            incr i
5835        }
5836    }
5837    set joinlow 0
5838    if {$i > 0} {
5839        set li [lindex $lines [expr {$i-1}]]
5840        set r1 [lindex $li 1]
5841        if {$r1 == $row && $le - [lindex $li 0] <= $maxlinelen} {
5842            set joinlow 1
5843        }
5844    }
5845
5846    set x [lindex $cols [expr {$le - $row}]]
5847    set xp [lindex $cols [expr {$le - 1 - $row}]]
5848    set dir [expr {$xp - $x}]
5849    if {$joinhigh} {
5850        set ith [lindex $lines $i 2]
5851        set coords [$canv coords $ith]
5852        set ah [$canv itemcget $ith -arrow]
5853        set arrowhigh [expr {$ah eq "first" || $ah eq "both"}]
5854        set x2 [lindex $cols [expr {$le + 1 - $row}]]
5855        if {$x2 ne {} && $x - $x2 == $dir} {
5856            set coords [lrange $coords 0 end-2]
5857        }
5858    } else {
5859        set coords [list [xc $le $x] [yc $le]]
5860    }
5861    if {$joinlow} {
5862        set itl [lindex $lines [expr {$i-1}] 2]
5863        set al [$canv itemcget $itl -arrow]
5864        set arrowlow [expr {$al eq "last" || $al eq "both"}]
5865    } elseif {$arrowlow} {
5866        if {[lsearch -exact [lindex $rowidlist [expr {$row-1}]] $id] >= 0 ||
5867            [lsearch -exact [lindex $parentlist [expr {$row-1}]] $id] >= 0} {
5868            set arrowlow 0
5869        }
5870    }
5871    set arrow [lindex {none first last both} [expr {$arrowhigh + 2*$arrowlow}]]
5872    for {set y $le} {[incr y -1] > $row} {} {
5873        set x $xp
5874        set xp [lindex $cols [expr {$y - 1 - $row}]]
5875        set ndir [expr {$xp - $x}]
5876        if {$dir != $ndir || $xp < 0} {
5877            lappend coords [xc $y $x] [yc $y]
5878        }
5879        set dir $ndir
5880    }
5881    if {!$joinlow} {
5882        if {$xp < 0} {
5883            # join parent line to first child
5884            set ch [lindex $displayorder $row]
5885            set xc [lsearch -exact [lindex $rowidlist $row] $ch]
5886            if {$xc < 0} {
5887                puts "oops: drawlineseg: child $ch not on row $row"
5888            } elseif {$xc != $x} {
5889                if {($arrowhigh && $le == $row + 1) || $dir == 0} {
5890                    set d [expr {int(0.5 * $linespc)}]
5891                    set x1 [xc $row $x]
5892                    if {$xc < $x} {
5893                        set x2 [expr {$x1 - $d}]
5894                    } else {
5895                        set x2 [expr {$x1 + $d}]
5896                    }
5897                    set y2 [yc $row]
5898                    set y1 [expr {$y2 + $d}]
5899                    lappend coords $x1 $y1 $x2 $y2
5900                } elseif {$xc < $x - 1} {
5901                    lappend coords [xc $row [expr {$x-1}]] [yc $row]
5902                } elseif {$xc > $x + 1} {
5903                    lappend coords [xc $row [expr {$x+1}]] [yc $row]
5904                }
5905                set x $xc
5906            }
5907            lappend coords [xc $row $x] [yc $row]
5908        } else {
5909            set xn [xc $row $xp]
5910            set yn [yc $row]
5911            lappend coords $xn $yn
5912        }
5913        if {!$joinhigh} {
5914            assigncolor $id
5915            set t [$canv create line $coords -width [linewidth $id] \
5916                       -fill $colormap($id) -tags lines.$id -arrow $arrow]
5917            $canv lower $t
5918            bindline $t $id
5919            set lines [linsert $lines $i [list $row $le $t]]
5920        } else {
5921            $canv coords $ith $coords
5922            if {$arrow ne $ah} {
5923                $canv itemconf $ith -arrow $arrow
5924            }
5925            lset lines $i 0 $row
5926        }
5927    } else {
5928        set xo [lsearch -exact [lindex $rowidlist [expr {$row - 1}]] $id]
5929        set ndir [expr {$xo - $xp}]
5930        set clow [$canv coords $itl]
5931        if {$dir == $ndir} {
5932            set clow [lrange $clow 2 end]
5933        }
5934        set coords [concat $coords $clow]
5935        if {!$joinhigh} {
5936            lset lines [expr {$i-1}] 1 $le
5937        } else {
5938            # coalesce two pieces
5939            $canv delete $ith
5940            set b [lindex $lines [expr {$i-1}] 0]
5941            set e [lindex $lines $i 1]
5942            set lines [lreplace $lines [expr {$i-1}] $i [list $b $e $itl]]
5943        }
5944        $canv coords $itl $coords
5945        if {$arrow ne $al} {
5946            $canv itemconf $itl -arrow $arrow
5947        }
5948    }
5949
5950    set linesegs($id) $lines
5951    return $le
5952}
5953
5954proc drawparentlinks {id row} {
5955    global rowidlist canv colormap curview parentlist
5956    global idpos linespc
5957
5958    set rowids [lindex $rowidlist $row]
5959    set col [lsearch -exact $rowids $id]
5960    if {$col < 0} return
5961    set olds [lindex $parentlist $row]
5962    set row2 [expr {$row + 1}]
5963    set x [xc $row $col]
5964    set y [yc $row]
5965    set y2 [yc $row2]
5966    set d [expr {int(0.5 * $linespc)}]
5967    set ymid [expr {$y + $d}]
5968    set ids [lindex $rowidlist $row2]
5969    # rmx = right-most X coord used
5970    set rmx 0
5971    foreach p $olds {
5972        set i [lsearch -exact $ids $p]
5973        if {$i < 0} {
5974            puts "oops, parent $p of $id not in list"
5975            continue
5976        }
5977        set x2 [xc $row2 $i]
5978        if {$x2 > $rmx} {
5979            set rmx $x2
5980        }
5981        set j [lsearch -exact $rowids $p]
5982        if {$j < 0} {
5983            # drawlineseg will do this one for us
5984            continue
5985        }
5986        assigncolor $p
5987        # should handle duplicated parents here...
5988        set coords [list $x $y]
5989        if {$i != $col} {
5990            # if attaching to a vertical segment, draw a smaller
5991            # slant for visual distinctness
5992            if {$i == $j} {
5993                if {$i < $col} {
5994                    lappend coords [expr {$x2 + $d}] $y $x2 $ymid
5995                } else {
5996                    lappend coords [expr {$x2 - $d}] $y $x2 $ymid
5997                }
5998            } elseif {$i < $col && $i < $j} {
5999                # segment slants towards us already
6000                lappend coords [xc $row $j] $y
6001            } else {
6002                if {$i < $col - 1} {
6003                    lappend coords [expr {$x2 + $linespc}] $y
6004                } elseif {$i > $col + 1} {
6005                    lappend coords [expr {$x2 - $linespc}] $y
6006                }
6007                lappend coords $x2 $y2
6008            }
6009        } else {
6010            lappend coords $x2 $y2
6011        }
6012        set t [$canv create line $coords -width [linewidth $p] \
6013                   -fill $colormap($p) -tags lines.$p]
6014        $canv lower $t
6015        bindline $t $p
6016    }
6017    if {$rmx > [lindex $idpos($id) 1]} {
6018        lset idpos($id) 1 $rmx
6019        redrawtags $id
6020    }
6021}
6022
6023proc drawlines {id} {
6024    global canv
6025
6026    $canv itemconf lines.$id -width [linewidth $id]
6027}
6028
6029proc drawcmittext {id row col} {
6030    global linespc canv canv2 canv3 fgcolor curview
6031    global cmitlisted commitinfo rowidlist parentlist
6032    global rowtextx idpos idtags idheads idotherrefs
6033    global linehtag linentag linedtag selectedline
6034    global canvxmax boldids boldnameids fgcolor markedid
6035    global mainheadid nullid nullid2 circleitem circlecolors ctxbut
6036    global mainheadcirclecolor workingfilescirclecolor indexcirclecolor
6037    global circleoutlinecolor
6038
6039    # listed is 0 for boundary, 1 for normal, 2 for negative, 3 for left, 4 for right
6040    set listed $cmitlisted($curview,$id)
6041    if {$id eq $nullid} {
6042        set ofill $workingfilescirclecolor
6043    } elseif {$id eq $nullid2} {
6044        set ofill $indexcirclecolor
6045    } elseif {$id eq $mainheadid} {
6046        set ofill $mainheadcirclecolor
6047    } else {
6048        set ofill [lindex $circlecolors $listed]
6049    }
6050    set x [xc $row $col]
6051    set y [yc $row]
6052    set orad [expr {$linespc / 3}]
6053    if {$listed <= 2} {
6054        set t [$canv create oval [expr {$x - $orad}] [expr {$y - $orad}] \
6055                   [expr {$x + $orad - 1}] [expr {$y + $orad - 1}] \
6056                   -fill $ofill -outline $circleoutlinecolor -width 1 -tags circle]
6057    } elseif {$listed == 3} {
6058        # triangle pointing left for left-side commits
6059        set t [$canv create polygon \
6060                   [expr {$x - $orad}] $y \
6061                   [expr {$x + $orad - 1}] [expr {$y - $orad}] \
6062                   [expr {$x + $orad - 1}] [expr {$y + $orad - 1}] \
6063                   -fill $ofill -outline $circleoutlinecolor -width 1 -tags circle]
6064    } else {
6065        # triangle pointing right for right-side commits
6066        set t [$canv create polygon \
6067                   [expr {$x + $orad - 1}] $y \
6068                   [expr {$x - $orad}] [expr {$y - $orad}] \
6069                   [expr {$x - $orad}] [expr {$y + $orad - 1}] \
6070                   -fill $ofill -outline $circleoutlinecolor -width 1 -tags circle]
6071    }
6072    set circleitem($row) $t
6073    $canv raise $t
6074    $canv bind $t <1> {selcanvline {} %x %y}
6075    set rmx [llength [lindex $rowidlist $row]]
6076    set olds [lindex $parentlist $row]
6077    if {$olds ne {}} {
6078        set nextids [lindex $rowidlist [expr {$row + 1}]]
6079        foreach p $olds {
6080            set i [lsearch -exact $nextids $p]
6081            if {$i > $rmx} {
6082                set rmx $i
6083            }
6084        }
6085    }
6086    set xt [xc $row $rmx]
6087    set rowtextx($row) $xt
6088    set idpos($id) [list $x $xt $y]
6089    if {[info exists idtags($id)] || [info exists idheads($id)]
6090        || [info exists idotherrefs($id)]} {
6091        set xt [drawtags $id $x $xt $y]
6092    }
6093    if {[lindex $commitinfo($id) 6] > 0} {
6094        set xt [drawnotesign $xt $y]
6095    }
6096    set headline [lindex $commitinfo($id) 0]
6097    set name [lindex $commitinfo($id) 1]
6098    set date [lindex $commitinfo($id) 2]
6099    set date [formatdate $date]
6100    set font mainfont
6101    set nfont mainfont
6102    set isbold [ishighlighted $id]
6103    if {$isbold > 0} {
6104        lappend boldids $id
6105        set font mainfontbold
6106        if {$isbold > 1} {
6107            lappend boldnameids $id
6108            set nfont mainfontbold
6109        }
6110    }
6111    set linehtag($id) [$canv create text $xt $y -anchor w -fill $fgcolor \
6112                           -text $headline -font $font -tags text]
6113    $canv bind $linehtag($id) $ctxbut "rowmenu %X %Y $id"
6114    set linentag($id) [$canv2 create text 3 $y -anchor w -fill $fgcolor \
6115                           -text $name -font $nfont -tags text]
6116    set linedtag($id) [$canv3 create text 3 $y -anchor w -fill $fgcolor \
6117                           -text $date -font mainfont -tags text]
6118    if {$selectedline == $row} {
6119        make_secsel $id
6120    }
6121    if {[info exists markedid] && $markedid eq $id} {
6122        make_idmark $id
6123    }
6124    set xr [expr {$xt + [font measure $font $headline]}]
6125    if {$xr > $canvxmax} {
6126        set canvxmax $xr
6127        setcanvscroll
6128    }
6129}
6130
6131proc drawcmitrow {row} {
6132    global displayorder rowidlist nrows_drawn
6133    global iddrawn markingmatches
6134    global commitinfo numcommits
6135    global filehighlight fhighlights findpattern nhighlights
6136    global hlview vhighlights
6137    global highlight_related rhighlights
6138
6139    if {$row >= $numcommits} return
6140
6141    set id [lindex $displayorder $row]
6142    if {[info exists hlview] && ![info exists vhighlights($id)]} {
6143        askvhighlight $row $id
6144    }
6145    if {[info exists filehighlight] && ![info exists fhighlights($id)]} {
6146        askfilehighlight $row $id
6147    }
6148    if {$findpattern ne {} && ![info exists nhighlights($id)]} {
6149        askfindhighlight $row $id
6150    }
6151    if {$highlight_related ne [mc "None"] && ![info exists rhighlights($id)]} {
6152        askrelhighlight $row $id
6153    }
6154    if {![info exists iddrawn($id)]} {
6155        set col [lsearch -exact [lindex $rowidlist $row] $id]
6156        if {$col < 0} {
6157            puts "oops, row $row id $id not in list"
6158            return
6159        }
6160        if {![info exists commitinfo($id)]} {
6161            getcommit $id
6162        }
6163        assigncolor $id
6164        drawcmittext $id $row $col
6165        set iddrawn($id) 1
6166        incr nrows_drawn
6167    }
6168    if {$markingmatches} {
6169        markrowmatches $row $id
6170    }
6171}
6172
6173proc drawcommits {row {endrow {}}} {
6174    global numcommits iddrawn displayorder curview need_redisplay
6175    global parentlist rowidlist rowfinal uparrowlen downarrowlen nrows_drawn
6176
6177    if {$row < 0} {
6178        set row 0
6179    }
6180    if {$endrow eq {}} {
6181        set endrow $row
6182    }
6183    if {$endrow >= $numcommits} {
6184        set endrow [expr {$numcommits - 1}]
6185    }
6186
6187    set rl1 [expr {$row - $downarrowlen - 3}]
6188    if {$rl1 < 0} {
6189        set rl1 0
6190    }
6191    set ro1 [expr {$row - 3}]
6192    if {$ro1 < 0} {
6193        set ro1 0
6194    }
6195    set r2 [expr {$endrow + $uparrowlen + 3}]
6196    if {$r2 > $numcommits} {
6197        set r2 $numcommits
6198    }
6199    for {set r $rl1} {$r < $r2} {incr r} {
6200        if {[lindex $rowidlist $r] ne {} && [lindex $rowfinal $r]} {
6201            if {$rl1 < $r} {
6202                layoutrows $rl1 $r
6203            }
6204            set rl1 [expr {$r + 1}]
6205        }
6206    }
6207    if {$rl1 < $r} {
6208        layoutrows $rl1 $r
6209    }
6210    optimize_rows $ro1 0 $r2
6211    if {$need_redisplay || $nrows_drawn > 2000} {
6212        clear_display
6213    }
6214
6215    # make the lines join to already-drawn rows either side
6216    set r [expr {$row - 1}]
6217    if {$r < 0 || ![info exists iddrawn([lindex $displayorder $r])]} {
6218        set r $row
6219    }
6220    set er [expr {$endrow + 1}]
6221    if {$er >= $numcommits ||
6222        ![info exists iddrawn([lindex $displayorder $er])]} {
6223        set er $endrow
6224    }
6225    for {} {$r <= $er} {incr r} {
6226        set id [lindex $displayorder $r]
6227        set wasdrawn [info exists iddrawn($id)]
6228        drawcmitrow $r
6229        if {$r == $er} break
6230        set nextid [lindex $displayorder [expr {$r + 1}]]
6231        if {$wasdrawn && [info exists iddrawn($nextid)]} continue
6232        drawparentlinks $id $r
6233
6234        set rowids [lindex $rowidlist $r]
6235        foreach lid $rowids {
6236            if {$lid eq {}} continue
6237            if {[info exists lineend($lid)] && $lineend($lid) > $r} continue
6238            if {$lid eq $id} {
6239                # see if this is the first child of any of its parents
6240                foreach p [lindex $parentlist $r] {
6241                    if {[lsearch -exact $rowids $p] < 0} {
6242                        # make this line extend up to the child
6243                        set lineend($p) [drawlineseg $p $r $er 0]
6244                    }
6245                }
6246            } else {
6247                set lineend($lid) [drawlineseg $lid $r $er 1]
6248            }
6249        }
6250    }
6251}
6252
6253proc undolayout {row} {
6254    global uparrowlen mingaplen downarrowlen
6255    global rowidlist rowisopt rowfinal need_redisplay
6256
6257    set r [expr {$row - ($uparrowlen + $mingaplen + $downarrowlen)}]
6258    if {$r < 0} {
6259        set r 0
6260    }
6261    if {[llength $rowidlist] > $r} {
6262        incr r -1
6263        set rowidlist [lrange $rowidlist 0 $r]
6264        set rowfinal [lrange $rowfinal 0 $r]
6265        set rowisopt [lrange $rowisopt 0 $r]
6266        set need_redisplay 1
6267        run drawvisible
6268    }
6269}
6270
6271proc drawvisible {} {
6272    global canv linespc curview vrowmod selectedline targetrow targetid
6273    global need_redisplay cscroll numcommits
6274
6275    set fs [$canv yview]
6276    set ymax [lindex [$canv cget -scrollregion] 3]
6277    if {$ymax eq {} || $ymax == 0 || $numcommits == 0} return
6278    set f0 [lindex $fs 0]
6279    set f1 [lindex $fs 1]
6280    set y0 [expr {int($f0 * $ymax)}]
6281    set y1 [expr {int($f1 * $ymax)}]
6282
6283    if {[info exists targetid]} {
6284        if {[commitinview $targetid $curview]} {
6285            set r [rowofcommit $targetid]
6286            if {$r != $targetrow} {
6287                # Fix up the scrollregion and change the scrolling position
6288                # now that our target row has moved.
6289                set diff [expr {($r - $targetrow) * $linespc}]
6290                set targetrow $r
6291                setcanvscroll
6292                set ymax [lindex [$canv cget -scrollregion] 3]
6293                incr y0 $diff
6294                incr y1 $diff
6295                set f0 [expr {$y0 / $ymax}]
6296                set f1 [expr {$y1 / $ymax}]
6297                allcanvs yview moveto $f0
6298                $cscroll set $f0 $f1
6299                set need_redisplay 1
6300            }
6301        } else {
6302            unset targetid
6303        }
6304    }
6305
6306    set row [expr {int(($y0 - 3) / $linespc) - 1}]
6307    set endrow [expr {int(($y1 - 3) / $linespc) + 1}]
6308    if {$endrow >= $vrowmod($curview)} {
6309        update_arcrows $curview
6310    }
6311    if {$selectedline ne {} &&
6312        $row <= $selectedline && $selectedline <= $endrow} {
6313        set targetrow $selectedline
6314    } elseif {[info exists targetid]} {
6315        set targetrow [expr {int(($row + $endrow) / 2)}]
6316    }
6317    if {[info exists targetrow]} {
6318        if {$targetrow >= $numcommits} {
6319            set targetrow [expr {$numcommits - 1}]
6320        }
6321        set targetid [commitonrow $targetrow]
6322    }
6323    drawcommits $row $endrow
6324}
6325
6326proc clear_display {} {
6327    global iddrawn linesegs need_redisplay nrows_drawn
6328    global vhighlights fhighlights nhighlights rhighlights
6329    global linehtag linentag linedtag boldids boldnameids
6330
6331    allcanvs delete all
6332    catch {unset iddrawn}
6333    catch {unset linesegs}
6334    catch {unset linehtag}
6335    catch {unset linentag}
6336    catch {unset linedtag}
6337    set boldids {}
6338    set boldnameids {}
6339    catch {unset vhighlights}
6340    catch {unset fhighlights}
6341    catch {unset nhighlights}
6342    catch {unset rhighlights}
6343    set need_redisplay 0
6344    set nrows_drawn 0
6345}
6346
6347proc findcrossings {id} {
6348    global rowidlist parentlist numcommits displayorder
6349
6350    set cross {}
6351    set ccross {}
6352    foreach {s e} [rowranges $id] {
6353        if {$e >= $numcommits} {
6354            set e [expr {$numcommits - 1}]
6355        }
6356        if {$e <= $s} continue
6357        for {set row $e} {[incr row -1] >= $s} {} {
6358            set x [lsearch -exact [lindex $rowidlist $row] $id]
6359            if {$x < 0} break
6360            set olds [lindex $parentlist $row]
6361            set kid [lindex $displayorder $row]
6362            set kidx [lsearch -exact [lindex $rowidlist $row] $kid]
6363            if {$kidx < 0} continue
6364            set nextrow [lindex $rowidlist [expr {$row + 1}]]
6365            foreach p $olds {
6366                set px [lsearch -exact $nextrow $p]
6367                if {$px < 0} continue
6368                if {($kidx < $x && $x < $px) || ($px < $x && $x < $kidx)} {
6369                    if {[lsearch -exact $ccross $p] >= 0} continue
6370                    if {$x == $px + ($kidx < $px? -1: 1)} {
6371                        lappend ccross $p
6372                    } elseif {[lsearch -exact $cross $p] < 0} {
6373                        lappend cross $p
6374                    }
6375                }
6376            }
6377        }
6378    }
6379    return [concat $ccross {{}} $cross]
6380}
6381
6382proc assigncolor {id} {
6383    global colormap colors nextcolor
6384    global parents children children curview
6385
6386    if {[info exists colormap($id)]} return
6387    set ncolors [llength $colors]
6388    if {[info exists children($curview,$id)]} {
6389        set kids $children($curview,$id)
6390    } else {
6391        set kids {}
6392    }
6393    if {[llength $kids] == 1} {
6394        set child [lindex $kids 0]
6395        if {[info exists colormap($child)]
6396            && [llength $parents($curview,$child)] == 1} {
6397            set colormap($id) $colormap($child)
6398            return
6399        }
6400    }
6401    set badcolors {}
6402    set origbad {}
6403    foreach x [findcrossings $id] {
6404        if {$x eq {}} {
6405            # delimiter between corner crossings and other crossings
6406            if {[llength $badcolors] >= $ncolors - 1} break
6407            set origbad $badcolors
6408        }
6409        if {[info exists colormap($x)]
6410            && [lsearch -exact $badcolors $colormap($x)] < 0} {
6411            lappend badcolors $colormap($x)
6412        }
6413    }
6414    if {[llength $badcolors] >= $ncolors} {
6415        set badcolors $origbad
6416    }
6417    set origbad $badcolors
6418    if {[llength $badcolors] < $ncolors - 1} {
6419        foreach child $kids {
6420            if {[info exists colormap($child)]
6421                && [lsearch -exact $badcolors $colormap($child)] < 0} {
6422                lappend badcolors $colormap($child)
6423            }
6424            foreach p $parents($curview,$child) {
6425                if {[info exists colormap($p)]
6426                    && [lsearch -exact $badcolors $colormap($p)] < 0} {
6427                    lappend badcolors $colormap($p)
6428                }
6429            }
6430        }
6431        if {[llength $badcolors] >= $ncolors} {
6432            set badcolors $origbad
6433        }
6434    }
6435    for {set i 0} {$i <= $ncolors} {incr i} {
6436        set c [lindex $colors $nextcolor]
6437        if {[incr nextcolor] >= $ncolors} {
6438            set nextcolor 0
6439        }
6440        if {[lsearch -exact $badcolors $c]} break
6441    }
6442    set colormap($id) $c
6443}
6444
6445proc bindline {t id} {
6446    global canv
6447
6448    $canv bind $t <Enter> "lineenter %x %y $id"
6449    $canv bind $t <Motion> "linemotion %x %y $id"
6450    $canv bind $t <Leave> "lineleave $id"
6451    $canv bind $t <Button-1> "lineclick %x %y $id 1"
6452}
6453
6454proc graph_pane_width {} {
6455    global use_ttk
6456
6457    if {$use_ttk} {
6458        set g [.tf.histframe.pwclist sashpos 0]
6459    } else {
6460        set g [.tf.histframe.pwclist sash coord 0]
6461    }
6462    return [lindex $g 0]
6463}
6464
6465proc totalwidth {l font extra} {
6466    set tot 0
6467    foreach str $l {
6468        set tot [expr {$tot + [font measure $font $str] + $extra}]
6469    }
6470    return $tot
6471}
6472
6473proc drawtags {id x xt y1} {
6474    global idtags idheads idotherrefs mainhead
6475    global linespc lthickness
6476    global canv rowtextx curview fgcolor bgcolor ctxbut
6477    global headbgcolor headfgcolor headoutlinecolor remotebgcolor
6478    global tagbgcolor tagfgcolor tagoutlinecolor
6479    global reflinecolor
6480
6481    set marks {}
6482    set ntags 0
6483    set nheads 0
6484    set singletag 0
6485    set maxtags 3
6486    set maxtagpct 25
6487    set maxwidth [expr {[graph_pane_width] * $maxtagpct / 100}]
6488    set delta [expr {int(0.5 * ($linespc - $lthickness))}]
6489    set extra [expr {$delta + $lthickness + $linespc}]
6490
6491    if {[info exists idtags($id)]} {
6492        set marks $idtags($id)
6493        set ntags [llength $marks]
6494        if {$ntags > $maxtags ||
6495            [totalwidth $marks mainfont $extra] > $maxwidth} {
6496            # show just a single "n tags..." tag
6497            set singletag 1
6498            if {$ntags == 1} {
6499                set marks [list "tag..."]
6500            } else {
6501                set marks [list [format "%d tags..." $ntags]]
6502            }
6503            set ntags 1
6504        }
6505    }
6506    if {[info exists idheads($id)]} {
6507        set marks [concat $marks $idheads($id)]
6508        set nheads [llength $idheads($id)]
6509    }
6510    if {[info exists idotherrefs($id)]} {
6511        set marks [concat $marks $idotherrefs($id)]
6512    }
6513    if {$marks eq {}} {
6514        return $xt
6515    }
6516
6517    set yt [expr {$y1 - 0.5 * $linespc}]
6518    set yb [expr {$yt + $linespc - 1}]
6519    set xvals {}
6520    set wvals {}
6521    set i -1
6522    foreach tag $marks {
6523        incr i
6524        if {$i >= $ntags && $i < $ntags + $nheads && $tag eq $mainhead} {
6525            set wid [font measure mainfontbold $tag]
6526        } else {
6527            set wid [font measure mainfont $tag]
6528        }
6529        lappend xvals $xt
6530        lappend wvals $wid
6531        set xt [expr {$xt + $wid + $extra}]
6532    }
6533    set t [$canv create line $x $y1 [lindex $xvals end] $y1 \
6534               -width $lthickness -fill $reflinecolor -tags tag.$id]
6535    $canv lower $t
6536    foreach tag $marks x $xvals wid $wvals {
6537        set tag_quoted [string map {% %%} $tag]
6538        set xl [expr {$x + $delta}]
6539        set xr [expr {$x + $delta + $wid + $lthickness}]
6540        set font mainfont
6541        if {[incr ntags -1] >= 0} {
6542            # draw a tag
6543            set t [$canv create polygon $x [expr {$yt + $delta}] $xl $yt \
6544                       $xr $yt $xr $yb $xl $yb $x [expr {$yb - $delta}] \
6545                       -width 1 -outline $tagoutlinecolor -fill $tagbgcolor \
6546                       -tags tag.$id]
6547            if {$singletag} {
6548                set tagclick [list showtags $id 1]
6549            } else {
6550                set tagclick [list showtag $tag_quoted 1]
6551            }
6552            $canv bind $t <1> $tagclick
6553            set rowtextx([rowofcommit $id]) [expr {$xr + $linespc}]
6554        } else {
6555            # draw a head or other ref
6556            if {[incr nheads -1] >= 0} {
6557                set col $headbgcolor
6558                if {$tag eq $mainhead} {
6559                    set font mainfontbold
6560                }
6561            } else {
6562                set col "#ddddff"
6563            }
6564            set xl [expr {$xl - $delta/2}]
6565            $canv create polygon $x $yt $xr $yt $xr $yb $x $yb \
6566                -width 1 -outline black -fill $col -tags tag.$id
6567            if {[regexp {^(remotes/.*/|remotes/)} $tag match remoteprefix]} {
6568                set rwid [font measure mainfont $remoteprefix]
6569                set xi [expr {$x + 1}]
6570                set yti [expr {$yt + 1}]
6571                set xri [expr {$x + $rwid}]
6572                $canv create polygon $xi $yti $xri $yti $xri $yb $xi $yb \
6573                        -width 0 -fill $remotebgcolor -tags tag.$id
6574            }
6575        }
6576        set t [$canv create text $xl $y1 -anchor w -text $tag -fill $headfgcolor \
6577                   -font $font -tags [list tag.$id text]]
6578        if {$ntags >= 0} {
6579            $canv bind $t <1> $tagclick
6580        } elseif {$nheads >= 0} {
6581            $canv bind $t $ctxbut [list headmenu %X %Y $id $tag_quoted]
6582        }
6583    }
6584    return $xt
6585}
6586
6587proc drawnotesign {xt y} {
6588    global linespc canv fgcolor
6589
6590    set orad [expr {$linespc / 3}]
6591    set t [$canv create rectangle [expr {$xt - $orad}] [expr {$y - $orad}] \
6592               [expr {$xt + $orad - 1}] [expr {$y + $orad - 1}] \
6593               -fill yellow -outline $fgcolor -width 1 -tags circle]
6594    set xt [expr {$xt + $orad * 3}]
6595    return $xt
6596}
6597
6598proc xcoord {i level ln} {
6599    global canvx0 xspc1 xspc2
6600
6601    set x [expr {$canvx0 + $i * $xspc1($ln)}]
6602    if {$i > 0 && $i == $level} {
6603        set x [expr {$x + 0.5 * ($xspc2 - $xspc1($ln))}]
6604    } elseif {$i > $level} {
6605        set x [expr {$x + $xspc2 - $xspc1($ln)}]
6606    }
6607    return $x
6608}
6609
6610proc show_status {msg} {
6611    global canv fgcolor
6612
6613    clear_display
6614    $canv create text 3 3 -anchor nw -text $msg -font mainfont \
6615        -tags text -fill $fgcolor
6616}
6617
6618# Don't change the text pane cursor if it is currently the hand cursor,
6619# showing that we are over a sha1 ID link.
6620proc settextcursor {c} {
6621    global ctext curtextcursor
6622
6623    if {[$ctext cget -cursor] == $curtextcursor} {
6624        $ctext config -cursor $c
6625    }
6626    set curtextcursor $c
6627}
6628
6629proc nowbusy {what {name {}}} {
6630    global isbusy busyname statusw
6631
6632    if {[array names isbusy] eq {}} {
6633        . config -cursor watch
6634        settextcursor watch
6635    }
6636    set isbusy($what) 1
6637    set busyname($what) $name
6638    if {$name ne {}} {
6639        $statusw conf -text $name
6640    }
6641}
6642
6643proc notbusy {what} {
6644    global isbusy maincursor textcursor busyname statusw
6645
6646    catch {
6647        unset isbusy($what)
6648        if {$busyname($what) ne {} &&
6649            [$statusw cget -text] eq $busyname($what)} {
6650            $statusw conf -text {}
6651        }
6652    }
6653    if {[array names isbusy] eq {}} {
6654        . config -cursor $maincursor
6655        settextcursor $textcursor
6656    }
6657}
6658
6659proc findmatches {f} {
6660    global findtype findstring
6661    if {$findtype == [mc "Regexp"]} {
6662        set matches [regexp -indices -all -inline $findstring $f]
6663    } else {
6664        set fs $findstring
6665        if {$findtype == [mc "IgnCase"]} {
6666            set f [string tolower $f]
6667            set fs [string tolower $fs]
6668        }
6669        set matches {}
6670        set i 0
6671        set l [string length $fs]
6672        while {[set j [string first $fs $f $i]] >= 0} {
6673            lappend matches [list $j [expr {$j+$l-1}]]
6674            set i [expr {$j + $l}]
6675        }
6676    }
6677    return $matches
6678}
6679
6680proc dofind {{dirn 1} {wrap 1}} {
6681    global findstring findstartline findcurline selectedline numcommits
6682    global gdttype filehighlight fh_serial find_dirn findallowwrap
6683
6684    if {[info exists find_dirn]} {
6685        if {$find_dirn == $dirn} return
6686        stopfinding
6687    }
6688    focus .
6689    if {$findstring eq {} || $numcommits == 0} return
6690    if {$selectedline eq {}} {
6691        set findstartline [lindex [visiblerows] [expr {$dirn < 0}]]
6692    } else {
6693        set findstartline $selectedline
6694    }
6695    set findcurline $findstartline
6696    nowbusy finding [mc "Searching"]
6697    if {$gdttype ne [mc "containing:"] && ![info exists filehighlight]} {
6698        after cancel do_file_hl $fh_serial
6699        do_file_hl $fh_serial
6700    }
6701    set find_dirn $dirn
6702    set findallowwrap $wrap
6703    run findmore
6704}
6705
6706proc stopfinding {} {
6707    global find_dirn findcurline fprogcoord
6708
6709    if {[info exists find_dirn]} {
6710        unset find_dirn
6711        unset findcurline
6712        notbusy finding
6713        set fprogcoord 0
6714        adjustprogress
6715    }
6716    stopblaming
6717}
6718
6719proc findmore {} {
6720    global commitdata commitinfo numcommits findpattern findloc
6721    global findstartline findcurline findallowwrap
6722    global find_dirn gdttype fhighlights fprogcoord
6723    global curview varcorder vrownum varccommits vrowmod
6724
6725    if {![info exists find_dirn]} {
6726        return 0
6727    }
6728    set fldtypes [list [mc "Headline"] [mc "Author"] "" [mc "Committer"] "" [mc "Comments"]]
6729    set l $findcurline
6730    set moretodo 0
6731    if {$find_dirn > 0} {
6732        incr l
6733        if {$l >= $numcommits} {
6734            set l 0
6735        }
6736        if {$l <= $findstartline} {
6737            set lim [expr {$findstartline + 1}]
6738        } else {
6739            set lim $numcommits
6740            set moretodo $findallowwrap
6741        }
6742    } else {
6743        if {$l == 0} {
6744            set l $numcommits
6745        }
6746        incr l -1
6747        if {$l >= $findstartline} {
6748            set lim [expr {$findstartline - 1}]
6749        } else {
6750            set lim -1
6751            set moretodo $findallowwrap
6752        }
6753    }
6754    set n [expr {($lim - $l) * $find_dirn}]
6755    if {$n > 500} {
6756        set n 500
6757        set moretodo 1
6758    }
6759    if {$l + ($find_dirn > 0? $n: 1) > $vrowmod($curview)} {
6760        update_arcrows $curview
6761    }
6762    set found 0
6763    set domore 1
6764    set ai [bsearch $vrownum($curview) $l]
6765    set a [lindex $varcorder($curview) $ai]
6766    set arow [lindex $vrownum($curview) $ai]
6767    set ids [lindex $varccommits($curview,$a)]
6768    set arowend [expr {$arow + [llength $ids]}]
6769    if {$gdttype eq [mc "containing:"]} {
6770        for {} {$n > 0} {incr n -1; incr l $find_dirn} {
6771            if {$l < $arow || $l >= $arowend} {
6772                incr ai $find_dirn
6773                set a [lindex $varcorder($curview) $ai]
6774                set arow [lindex $vrownum($curview) $ai]
6775                set ids [lindex $varccommits($curview,$a)]
6776                set arowend [expr {$arow + [llength $ids]}]
6777            }
6778            set id [lindex $ids [expr {$l - $arow}]]
6779            # shouldn't happen unless git log doesn't give all the commits...
6780            if {![info exists commitdata($id)] ||
6781                ![doesmatch $commitdata($id)]} {
6782                continue
6783            }
6784            if {![info exists commitinfo($id)]} {
6785                getcommit $id
6786            }
6787            set info $commitinfo($id)
6788            foreach f $info ty $fldtypes {
6789                if {$ty eq ""} continue
6790                if {($findloc eq [mc "All fields"] || $findloc eq $ty) &&
6791                    [doesmatch $f]} {
6792                    set found 1
6793                    break
6794                }
6795            }
6796            if {$found} break
6797        }
6798    } else {
6799        for {} {$n > 0} {incr n -1; incr l $find_dirn} {
6800            if {$l < $arow || $l >= $arowend} {
6801                incr ai $find_dirn
6802                set a [lindex $varcorder($curview) $ai]
6803                set arow [lindex $vrownum($curview) $ai]
6804                set ids [lindex $varccommits($curview,$a)]
6805                set arowend [expr {$arow + [llength $ids]}]
6806            }
6807            set id [lindex $ids [expr {$l - $arow}]]
6808            if {![info exists fhighlights($id)]} {
6809                # this sets fhighlights($id) to -1
6810                askfilehighlight $l $id
6811            }
6812            if {$fhighlights($id) > 0} {
6813                set found $domore
6814                break
6815            }
6816            if {$fhighlights($id) < 0} {
6817                if {$domore} {
6818                    set domore 0
6819                    set findcurline [expr {$l - $find_dirn}]
6820                }
6821            }
6822        }
6823    }
6824    if {$found || ($domore && !$moretodo)} {
6825        unset findcurline
6826        unset find_dirn
6827        notbusy finding
6828        set fprogcoord 0
6829        adjustprogress
6830        if {$found} {
6831            findselectline $l
6832        } else {
6833            bell
6834        }
6835        return 0
6836    }
6837    if {!$domore} {
6838        flushhighlights
6839    } else {
6840        set findcurline [expr {$l - $find_dirn}]
6841    }
6842    set n [expr {($findcurline - $findstartline) * $find_dirn - 1}]
6843    if {$n < 0} {
6844        incr n $numcommits
6845    }
6846    set fprogcoord [expr {$n * 1.0 / $numcommits}]
6847    adjustprogress
6848    return $domore
6849}
6850
6851proc findselectline {l} {
6852    global findloc commentend ctext findcurline markingmatches gdttype
6853
6854    set markingmatches [expr {$gdttype eq [mc "containing:"]}]
6855    set findcurline $l
6856    selectline $l 1
6857    if {$markingmatches &&
6858        ($findloc eq [mc "All fields"] || $findloc eq [mc "Comments"])} {
6859        # highlight the matches in the comments
6860        set f [$ctext get 1.0 $commentend]
6861        set matches [findmatches $f]
6862        foreach match $matches {
6863            set start [lindex $match 0]
6864            set end [expr {[lindex $match 1] + 1}]
6865            $ctext tag add found "1.0 + $start c" "1.0 + $end c"
6866        }
6867    }
6868    drawvisible
6869}
6870
6871# mark the bits of a headline or author that match a find string
6872proc markmatches {canv l str tag matches font row} {
6873    global selectedline
6874
6875    set bbox [$canv bbox $tag]
6876    set x0 [lindex $bbox 0]
6877    set y0 [lindex $bbox 1]
6878    set y1 [lindex $bbox 3]
6879    foreach match $matches {
6880        set start [lindex $match 0]
6881        set end [lindex $match 1]
6882        if {$start > $end} continue
6883        set xoff [font measure $font [string range $str 0 [expr {$start-1}]]]
6884        set xlen [font measure $font [string range $str 0 [expr {$end}]]]
6885        set t [$canv create rect [expr {$x0+$xoff}] $y0 \
6886                   [expr {$x0+$xlen+2}] $y1 \
6887                   -outline {} -tags [list match$l matches] -fill yellow]
6888        $canv lower $t
6889        if {$row == $selectedline} {
6890            $canv raise $t secsel
6891        }
6892    }
6893}
6894
6895proc unmarkmatches {} {
6896    global markingmatches
6897
6898    allcanvs delete matches
6899    set markingmatches 0
6900    stopfinding
6901}
6902
6903proc selcanvline {w x y} {
6904    global canv canvy0 ctext linespc
6905    global rowtextx
6906    set ymax [lindex [$canv cget -scrollregion] 3]
6907    if {$ymax == {}} return
6908    set yfrac [lindex [$canv yview] 0]
6909    set y [expr {$y + $yfrac * $ymax}]
6910    set l [expr {int(($y - $canvy0) / $linespc + 0.5)}]
6911    if {$l < 0} {
6912        set l 0
6913    }
6914    if {$w eq $canv} {
6915        set xmax [lindex [$canv cget -scrollregion] 2]
6916        set xleft [expr {[lindex [$canv xview] 0] * $xmax}]
6917        if {![info exists rowtextx($l)] || $xleft + $x < $rowtextx($l)} return
6918    }
6919    unmarkmatches
6920    selectline $l 1
6921}
6922
6923proc commit_descriptor {p} {
6924    global commitinfo
6925    if {![info exists commitinfo($p)]} {
6926        getcommit $p
6927    }
6928    set l "..."
6929    if {[llength $commitinfo($p)] > 1} {
6930        set l [lindex $commitinfo($p) 0]
6931    }
6932    return "$p ($l)\n"
6933}
6934
6935# append some text to the ctext widget, and make any SHA1 ID
6936# that we know about be a clickable link.
6937proc appendwithlinks {text tags} {
6938    global ctext linknum curview
6939
6940    set start [$ctext index "end - 1c"]
6941    $ctext insert end $text $tags
6942    set links [regexp -indices -all -inline {(?:\m|-g)[0-9a-f]{6,40}\M} $text]
6943    foreach l $links {
6944        set s [lindex $l 0]
6945        set e [lindex $l 1]
6946        set linkid [string range $text $s $e]
6947        incr e
6948        $ctext tag delete link$linknum
6949        $ctext tag add link$linknum "$start + $s c" "$start + $e c"
6950        setlink $linkid link$linknum
6951        incr linknum
6952    }
6953}
6954
6955proc setlink {id lk} {
6956    global curview ctext pendinglinks
6957    global linkfgcolor
6958
6959    if {[string range $id 0 1] eq "-g"} {
6960      set id [string range $id 2 end]
6961    }
6962
6963    set known 0
6964    if {[string length $id] < 40} {
6965        set matches [longid $id]
6966        if {[llength $matches] > 0} {
6967            if {[llength $matches] > 1} return
6968            set known 1
6969            set id [lindex $matches 0]
6970        }
6971    } else {
6972        set known [commitinview $id $curview]
6973    }
6974    if {$known} {
6975        $ctext tag conf $lk -foreground $linkfgcolor -underline 1
6976        $ctext tag bind $lk <1> [list selbyid $id]
6977        $ctext tag bind $lk <Enter> {linkcursor %W 1}
6978        $ctext tag bind $lk <Leave> {linkcursor %W -1}
6979    } else {
6980        lappend pendinglinks($id) $lk
6981        interestedin $id {makelink %P}
6982    }
6983}
6984
6985proc appendshortlink {id {pre {}} {post {}}} {
6986    global ctext linknum
6987
6988    $ctext insert end $pre
6989    $ctext tag delete link$linknum
6990    $ctext insert end [string range $id 0 7] link$linknum
6991    $ctext insert end $post
6992    setlink $id link$linknum
6993    incr linknum
6994}
6995
6996proc makelink {id} {
6997    global pendinglinks
6998
6999    if {![info exists pendinglinks($id)]} return
7000    foreach lk $pendinglinks($id) {
7001        setlink $id $lk
7002    }
7003    unset pendinglinks($id)
7004}
7005
7006proc linkcursor {w inc} {
7007    global linkentercount curtextcursor
7008
7009    if {[incr linkentercount $inc] > 0} {
7010        $w configure -cursor hand2
7011    } else {
7012        $w configure -cursor $curtextcursor
7013        if {$linkentercount < 0} {
7014            set linkentercount 0
7015        }
7016    }
7017}
7018
7019proc viewnextline {dir} {
7020    global canv linespc
7021
7022    $canv delete hover
7023    set ymax [lindex [$canv cget -scrollregion] 3]
7024    set wnow [$canv yview]
7025    set wtop [expr {[lindex $wnow 0] * $ymax}]
7026    set newtop [expr {$wtop + $dir * $linespc}]
7027    if {$newtop < 0} {
7028        set newtop 0
7029    } elseif {$newtop > $ymax} {
7030        set newtop $ymax
7031    }
7032    allcanvs yview moveto [expr {$newtop * 1.0 / $ymax}]
7033}
7034
7035# add a list of tag or branch names at position pos
7036# returns the number of names inserted
7037proc appendrefs {pos ids var} {
7038    global ctext linknum curview $var maxrefs mainheadid
7039
7040    if {[catch {$ctext index $pos}]} {
7041        return 0
7042    }
7043    $ctext conf -state normal
7044    $ctext delete $pos "$pos lineend"
7045    set tags {}
7046    foreach id $ids {
7047        foreach tag [set $var\($id\)] {
7048            lappend tags [list $tag $id]
7049        }
7050    }
7051
7052    set sep {}
7053    set tags [lsort -index 0 -decreasing $tags]
7054    set nutags 0
7055
7056    if {[llength $tags] > $maxrefs} {
7057        # If we are displaying heads, and there are too many,
7058        # see if there are some important heads to display.
7059        # Currently this means "master" and the current head.
7060        set itags {}
7061        if {$var eq "idheads"} {
7062            set utags {}
7063            foreach ti $tags {
7064                set hname [lindex $ti 0]
7065                set id [lindex $ti 1]
7066                if {($hname eq "master" || $id eq $mainheadid) &&
7067                    [llength $itags] < $maxrefs} {
7068                    lappend itags $ti
7069                } else {
7070                    lappend utags $ti
7071                }
7072            }
7073            set tags $utags
7074        }
7075        if {$itags ne {}} {
7076            set str [mc "and many more"]
7077            set sep " "
7078        } else {
7079            set str [mc "many"]
7080        }
7081        $ctext insert $pos "$str ([llength $tags])"
7082        set nutags [llength $tags]
7083        set tags $itags
7084    }
7085
7086    foreach ti $tags {
7087        set id [lindex $ti 1]
7088        set lk link$linknum
7089        incr linknum
7090        $ctext tag delete $lk
7091        $ctext insert $pos $sep
7092        $ctext insert $pos [lindex $ti 0] $lk
7093        setlink $id $lk
7094        set sep ", "
7095    }
7096    $ctext tag add wwrap "$pos linestart" "$pos lineend"
7097    $ctext conf -state disabled
7098    return [expr {[llength $tags] + $nutags}]
7099}
7100
7101# called when we have finished computing the nearby tags
7102proc dispneartags {delay} {
7103    global selectedline currentid showneartags tagphase
7104
7105    if {$selectedline eq {} || !$showneartags} return
7106    after cancel dispnexttag
7107    if {$delay} {
7108        after 200 dispnexttag
7109        set tagphase -1
7110    } else {
7111        after idle dispnexttag
7112        set tagphase 0
7113    }
7114}
7115
7116proc dispnexttag {} {
7117    global selectedline currentid showneartags tagphase ctext
7118
7119    if {$selectedline eq {} || !$showneartags} return
7120    switch -- $tagphase {
7121        0 {
7122            set dtags [desctags $currentid]
7123            if {$dtags ne {}} {
7124                appendrefs precedes $dtags idtags
7125            }
7126        }
7127        1 {
7128            set atags [anctags $currentid]
7129            if {$atags ne {}} {
7130                appendrefs follows $atags idtags
7131            }
7132        }
7133        2 {
7134            set dheads [descheads $currentid]
7135            if {$dheads ne {}} {
7136                if {[appendrefs branch $dheads idheads] > 1
7137                    && [$ctext get "branch -3c"] eq "h"} {
7138                    # turn "Branch" into "Branches"
7139                    $ctext conf -state normal
7140                    $ctext insert "branch -2c" "es"
7141                    $ctext conf -state disabled
7142                }
7143            }
7144        }
7145    }
7146    if {[incr tagphase] <= 2} {
7147        after idle dispnexttag
7148    }
7149}
7150
7151proc make_secsel {id} {
7152    global linehtag linentag linedtag canv canv2 canv3
7153
7154    if {![info exists linehtag($id)]} return
7155    $canv delete secsel
7156    set t [eval $canv create rect [$canv bbox $linehtag($id)] -outline {{}} \
7157               -tags secsel -fill [$canv cget -selectbackground]]
7158    $canv lower $t
7159    $canv2 delete secsel
7160    set t [eval $canv2 create rect [$canv2 bbox $linentag($id)] -outline {{}} \
7161               -tags secsel -fill [$canv2 cget -selectbackground]]
7162    $canv2 lower $t
7163    $canv3 delete secsel
7164    set t [eval $canv3 create rect [$canv3 bbox $linedtag($id)] -outline {{}} \
7165               -tags secsel -fill [$canv3 cget -selectbackground]]
7166    $canv3 lower $t
7167}
7168
7169proc make_idmark {id} {
7170    global linehtag canv fgcolor
7171
7172    if {![info exists linehtag($id)]} return
7173    $canv delete markid
7174    set t [eval $canv create rect [$canv bbox $linehtag($id)] \
7175               -tags markid -outline $fgcolor]
7176    $canv raise $t
7177}
7178
7179proc selectline {l isnew {desired_loc {}} {switch_to_patch 0}} {
7180    global canv ctext commitinfo selectedline
7181    global canvy0 linespc parents children curview
7182    global currentid sha1entry
7183    global commentend idtags linknum
7184    global mergemax numcommits pending_select
7185    global cmitmode showneartags allcommits
7186    global targetrow targetid lastscrollrows
7187    global autoselect autosellen jump_to_here
7188    global vinlinediff
7189
7190    catch {unset pending_select}
7191    $canv delete hover
7192    normalline
7193    unsel_reflist
7194    stopfinding
7195    if {$l < 0 || $l >= $numcommits} return
7196    set id [commitonrow $l]
7197    set targetid $id
7198    set targetrow $l
7199    set selectedline $l
7200    set currentid $id
7201    if {$lastscrollrows < $numcommits} {
7202        setcanvscroll
7203    }
7204
7205    if {$cmitmode ne "patch" && $switch_to_patch} {
7206        set cmitmode "patch"
7207    }
7208
7209    set y [expr {$canvy0 + $l * $linespc}]
7210    set ymax [lindex [$canv cget -scrollregion] 3]
7211    set ytop [expr {$y - $linespc - 1}]
7212    set ybot [expr {$y + $linespc + 1}]
7213    set wnow [$canv yview]
7214    set wtop [expr {[lindex $wnow 0] * $ymax}]
7215    set wbot [expr {[lindex $wnow 1] * $ymax}]
7216    set wh [expr {$wbot - $wtop}]
7217    set newtop $wtop
7218    if {$ytop < $wtop} {
7219        if {$ybot < $wtop} {
7220            set newtop [expr {$y - $wh / 2.0}]
7221        } else {
7222            set newtop $ytop
7223            if {$newtop > $wtop - $linespc} {
7224                set newtop [expr {$wtop - $linespc}]
7225            }
7226        }
7227    } elseif {$ybot > $wbot} {
7228        if {$ytop > $wbot} {
7229            set newtop [expr {$y - $wh / 2.0}]
7230        } else {
7231            set newtop [expr {$ybot - $wh}]
7232            if {$newtop < $wtop + $linespc} {
7233                set newtop [expr {$wtop + $linespc}]
7234            }
7235        }
7236    }
7237    if {$newtop != $wtop} {
7238        if {$newtop < 0} {
7239            set newtop 0
7240        }
7241        allcanvs yview moveto [expr {$newtop * 1.0 / $ymax}]
7242        drawvisible
7243    }
7244
7245    make_secsel $id
7246
7247    if {$isnew} {
7248        addtohistory [list selbyid $id 0] savecmitpos
7249    }
7250
7251    $sha1entry delete 0 end
7252    $sha1entry insert 0 $id
7253    if {$autoselect} {
7254        $sha1entry selection range 0 $autosellen
7255    }
7256    rhighlight_sel $id
7257
7258    $ctext conf -state normal
7259    clear_ctext
7260    set linknum 0
7261    if {![info exists commitinfo($id)]} {
7262        getcommit $id
7263    }
7264    set info $commitinfo($id)
7265    set date [formatdate [lindex $info 2]]
7266    $ctext insert end "[mc "Author"]: [lindex $info 1]  $date\n"
7267    set date [formatdate [lindex $info 4]]
7268    $ctext insert end "[mc "Committer"]: [lindex $info 3]  $date\n"
7269    if {[info exists idtags($id)]} {
7270        $ctext insert end [mc "Tags:"]
7271        foreach tag $idtags($id) {
7272            $ctext insert end " $tag"
7273        }
7274        $ctext insert end "\n"
7275    }
7276
7277    set headers {}
7278    set olds $parents($curview,$id)
7279    if {[llength $olds] > 1} {
7280        set np 0
7281        foreach p $olds {
7282            if {$np >= $mergemax} {
7283                set tag mmax
7284            } else {
7285                set tag m$np
7286            }
7287            $ctext insert end "[mc "Parent"]: " $tag
7288            appendwithlinks [commit_descriptor $p] {}
7289            incr np
7290        }
7291    } else {
7292        foreach p $olds {
7293            append headers "[mc "Parent"]: [commit_descriptor $p]"
7294        }
7295    }
7296
7297    foreach c $children($curview,$id) {
7298        append headers "[mc "Child"]:  [commit_descriptor $c]"
7299    }
7300
7301    # make anything that looks like a SHA1 ID be a clickable link
7302    appendwithlinks $headers {}
7303    if {$showneartags} {
7304        if {![info exists allcommits]} {
7305            getallcommits
7306        }
7307        $ctext insert end "[mc "Branch"]: "
7308        $ctext mark set branch "end -1c"
7309        $ctext mark gravity branch left
7310        $ctext insert end "\n[mc "Follows"]: "
7311        $ctext mark set follows "end -1c"
7312        $ctext mark gravity follows left
7313        $ctext insert end "\n[mc "Precedes"]: "
7314        $ctext mark set precedes "end -1c"
7315        $ctext mark gravity precedes left
7316        $ctext insert end "\n"
7317        dispneartags 1
7318    }
7319    $ctext insert end "\n"
7320    set comment [lindex $info 5]
7321    if {[string first "\r" $comment] >= 0} {
7322        set comment [string map {"\r" "\n    "} $comment]
7323    }
7324    appendwithlinks $comment {comment}
7325
7326    $ctext tag remove found 1.0 end
7327    $ctext conf -state disabled
7328    set commentend [$ctext index "end - 1c"]
7329
7330    set jump_to_here $desired_loc
7331    init_flist [mc "Comments"]
7332    if {$cmitmode eq "tree"} {
7333        gettree $id
7334    } elseif {$vinlinediff($curview) == 1} {
7335        showinlinediff $id
7336    } elseif {[llength $olds] <= 1} {
7337        startdiff $id
7338    } else {
7339        mergediff $id
7340    }
7341}
7342
7343proc selfirstline {} {
7344    unmarkmatches
7345    selectline 0 1
7346}
7347
7348proc sellastline {} {
7349    global numcommits
7350    unmarkmatches
7351    set l [expr {$numcommits - 1}]
7352    selectline $l 1
7353}
7354
7355proc selnextline {dir} {
7356    global selectedline
7357    focus .
7358    if {$selectedline eq {}} return
7359    set l [expr {$selectedline + $dir}]
7360    unmarkmatches
7361    selectline $l 1
7362}
7363
7364proc selnextpage {dir} {
7365    global canv linespc selectedline numcommits
7366
7367    set lpp [expr {([winfo height $canv] - 2) / $linespc}]
7368    if {$lpp < 1} {
7369        set lpp 1
7370    }
7371    allcanvs yview scroll [expr {$dir * $lpp}] units
7372    drawvisible
7373    if {$selectedline eq {}} return
7374    set l [expr {$selectedline + $dir * $lpp}]
7375    if {$l < 0} {
7376        set l 0
7377    } elseif {$l >= $numcommits} {
7378        set l [expr $numcommits - 1]
7379    }
7380    unmarkmatches
7381    selectline $l 1
7382}
7383
7384proc unselectline {} {
7385    global selectedline currentid
7386
7387    set selectedline {}
7388    catch {unset currentid}
7389    allcanvs delete secsel
7390    rhighlight_none
7391}
7392
7393proc reselectline {} {
7394    global selectedline
7395
7396    if {$selectedline ne {}} {
7397        selectline $selectedline 0
7398    }
7399}
7400
7401proc addtohistory {cmd {saveproc {}}} {
7402    global history historyindex curview
7403
7404    unset_posvars
7405    save_position
7406    set elt [list $curview $cmd $saveproc {}]
7407    if {$historyindex > 0
7408        && [lindex $history [expr {$historyindex - 1}]] == $elt} {
7409        return
7410    }
7411
7412    if {$historyindex < [llength $history]} {
7413        set history [lreplace $history $historyindex end $elt]
7414    } else {
7415        lappend history $elt
7416    }
7417    incr historyindex
7418    if {$historyindex > 1} {
7419        .tf.bar.leftbut conf -state normal
7420    } else {
7421        .tf.bar.leftbut conf -state disabled
7422    }
7423    .tf.bar.rightbut conf -state disabled
7424}
7425
7426# save the scrolling position of the diff display pane
7427proc save_position {} {
7428    global historyindex history
7429
7430    if {$historyindex < 1} return
7431    set hi [expr {$historyindex - 1}]
7432    set fn [lindex $history $hi 2]
7433    if {$fn ne {}} {
7434        lset history $hi 3 [eval $fn]
7435    }
7436}
7437
7438proc unset_posvars {} {
7439    global last_posvars
7440
7441    if {[info exists last_posvars]} {
7442        foreach {var val} $last_posvars {
7443            global $var
7444            catch {unset $var}
7445        }
7446        unset last_posvars
7447    }
7448}
7449
7450proc godo {elt} {
7451    global curview last_posvars
7452
7453    set view [lindex $elt 0]
7454    set cmd [lindex $elt 1]
7455    set pv [lindex $elt 3]
7456    if {$curview != $view} {
7457        showview $view
7458    }
7459    unset_posvars
7460    foreach {var val} $pv {
7461        global $var
7462        set $var $val
7463    }
7464    set last_posvars $pv
7465    eval $cmd
7466}
7467
7468proc goback {} {
7469    global history historyindex
7470    focus .
7471
7472    if {$historyindex > 1} {
7473        save_position
7474        incr historyindex -1
7475        godo [lindex $history [expr {$historyindex - 1}]]
7476        .tf.bar.rightbut conf -state normal
7477    }
7478    if {$historyindex <= 1} {
7479        .tf.bar.leftbut conf -state disabled
7480    }
7481}
7482
7483proc goforw {} {
7484    global history historyindex
7485    focus .
7486
7487    if {$historyindex < [llength $history]} {
7488        save_position
7489        set cmd [lindex $history $historyindex]
7490        incr historyindex
7491        godo $cmd
7492        .tf.bar.leftbut conf -state normal
7493    }
7494    if {$historyindex >= [llength $history]} {
7495        .tf.bar.rightbut conf -state disabled
7496    }
7497}
7498
7499proc gettree {id} {
7500    global treefilelist treeidlist diffids diffmergeid treepending
7501    global nullid nullid2
7502
7503    set diffids $id
7504    catch {unset diffmergeid}
7505    if {![info exists treefilelist($id)]} {
7506        if {![info exists treepending]} {
7507            if {$id eq $nullid} {
7508                set cmd [list | git ls-files]
7509            } elseif {$id eq $nullid2} {
7510                set cmd [list | git ls-files --stage -t]
7511            } else {
7512                set cmd [list | git ls-tree -r $id]
7513            }
7514            if {[catch {set gtf [open $cmd r]}]} {
7515                return
7516            }
7517            set treepending $id
7518            set treefilelist($id) {}
7519            set treeidlist($id) {}
7520            fconfigure $gtf -blocking 0 -encoding binary
7521            filerun $gtf [list gettreeline $gtf $id]
7522        }
7523    } else {
7524        setfilelist $id
7525    }
7526}
7527
7528proc gettreeline {gtf id} {
7529    global treefilelist treeidlist treepending cmitmode diffids nullid nullid2
7530
7531    set nl 0
7532    while {[incr nl] <= 1000 && [gets $gtf line] >= 0} {
7533        if {$diffids eq $nullid} {
7534            set fname $line
7535        } else {
7536            set i [string first "\t" $line]
7537            if {$i < 0} continue
7538            set fname [string range $line [expr {$i+1}] end]
7539            set line [string range $line 0 [expr {$i-1}]]
7540            if {$diffids ne $nullid2 && [lindex $line 1] ne "blob"} continue
7541            set sha1 [lindex $line 2]
7542            lappend treeidlist($id) $sha1
7543        }
7544        if {[string index $fname 0] eq "\""} {
7545            set fname [lindex $fname 0]
7546        }
7547        set fname [encoding convertfrom $fname]
7548        lappend treefilelist($id) $fname
7549    }
7550    if {![eof $gtf]} {
7551        return [expr {$nl >= 1000? 2: 1}]
7552    }
7553    close $gtf
7554    unset treepending
7555    if {$cmitmode ne "tree"} {
7556        if {![info exists diffmergeid]} {
7557            gettreediffs $diffids
7558        }
7559    } elseif {$id ne $diffids} {
7560        gettree $diffids
7561    } else {
7562        setfilelist $id
7563    }
7564    return 0
7565}
7566
7567proc showfile {f} {
7568    global treefilelist treeidlist diffids nullid nullid2
7569    global ctext_file_names ctext_file_lines
7570    global ctext commentend
7571
7572    set i [lsearch -exact $treefilelist($diffids) $f]
7573    if {$i < 0} {
7574        puts "oops, $f not in list for id $diffids"
7575        return
7576    }
7577    if {$diffids eq $nullid} {
7578        if {[catch {set bf [open $f r]} err]} {
7579            puts "oops, can't read $f: $err"
7580            return
7581        }
7582    } else {
7583        set blob [lindex $treeidlist($diffids) $i]
7584        if {[catch {set bf [open [concat | git cat-file blob $blob] r]} err]} {
7585            puts "oops, error reading blob $blob: $err"
7586            return
7587        }
7588    }
7589    fconfigure $bf -blocking 0 -encoding [get_path_encoding $f]
7590    filerun $bf [list getblobline $bf $diffids]
7591    $ctext config -state normal
7592    clear_ctext $commentend
7593    lappend ctext_file_names $f
7594    lappend ctext_file_lines [lindex [split $commentend "."] 0]
7595    $ctext insert end "\n"
7596    $ctext insert end "$f\n" filesep
7597    $ctext config -state disabled
7598    $ctext yview $commentend
7599    settabs 0
7600}
7601
7602proc getblobline {bf id} {
7603    global diffids cmitmode ctext
7604
7605    if {$id ne $diffids || $cmitmode ne "tree"} {
7606        catch {close $bf}
7607        return 0
7608    }
7609    $ctext config -state normal
7610    set nl 0
7611    while {[incr nl] <= 1000 && [gets $bf line] >= 0} {
7612        $ctext insert end "$line\n"
7613    }
7614    if {[eof $bf]} {
7615        global jump_to_here ctext_file_names commentend
7616
7617        # delete last newline
7618        $ctext delete "end - 2c" "end - 1c"
7619        close $bf
7620        if {$jump_to_here ne {} &&
7621            [lindex $jump_to_here 0] eq [lindex $ctext_file_names 0]} {
7622            set lnum [expr {[lindex $jump_to_here 1] +
7623                            [lindex [split $commentend .] 0]}]
7624            mark_ctext_line $lnum
7625        }
7626        $ctext config -state disabled
7627        return 0
7628    }
7629    $ctext config -state disabled
7630    return [expr {$nl >= 1000? 2: 1}]
7631}
7632
7633proc mark_ctext_line {lnum} {
7634    global ctext markbgcolor
7635
7636    $ctext tag delete omark
7637    $ctext tag add omark $lnum.0 "$lnum.0 + 1 line"
7638    $ctext tag conf omark -background $markbgcolor
7639    $ctext see $lnum.0
7640}
7641
7642proc mergediff {id} {
7643    global diffmergeid
7644    global diffids treediffs
7645    global parents curview
7646
7647    set diffmergeid $id
7648    set diffids $id
7649    set treediffs($id) {}
7650    set np [llength $parents($curview,$id)]
7651    settabs $np
7652    getblobdiffs $id
7653}
7654
7655proc startdiff {ids} {
7656    global treediffs diffids treepending diffmergeid nullid nullid2
7657
7658    settabs 1
7659    set diffids $ids
7660    catch {unset diffmergeid}
7661    if {![info exists treediffs($ids)] ||
7662        [lsearch -exact $ids $nullid] >= 0 ||
7663        [lsearch -exact $ids $nullid2] >= 0} {
7664        if {![info exists treepending]} {
7665            gettreediffs $ids
7666        }
7667    } else {
7668        addtocflist $ids
7669    }
7670}
7671
7672proc showinlinediff {ids} {
7673    global commitinfo commitdata ctext
7674    global treediffs
7675
7676    set info $commitinfo($ids)
7677    set diff [lindex $info 7]
7678    set difflines [split $diff "\n"]
7679
7680    initblobdiffvars
7681    set treediff {}
7682
7683    set inhdr 0
7684    foreach line $difflines {
7685        if {![string compare -length 5 "diff " $line]} {
7686            set inhdr 1
7687        } elseif {$inhdr && ![string compare -length 4 "+++ " $line]} {
7688            # offset also accounts for the b/ prefix
7689            lappend treediff [string range $line 6 end]
7690            set inhdr 0
7691        }
7692    }
7693
7694    set treediffs($ids) $treediff
7695    add_flist $treediff
7696
7697    $ctext conf -state normal
7698    foreach line $difflines {
7699        parseblobdiffline $ids $line
7700    }
7701    maybe_scroll_ctext 1
7702    $ctext conf -state disabled
7703}
7704
7705# If the filename (name) is under any of the passed filter paths
7706# then return true to include the file in the listing.
7707proc path_filter {filter name} {
7708    set worktree [gitworktree]
7709    foreach p $filter {
7710        set fq_p [file normalize $p]
7711        set fq_n [file normalize [file join $worktree $name]]
7712        if {[string match [file normalize $fq_p]* $fq_n]} {
7713            return 1
7714        }
7715    }
7716    return 0
7717}
7718
7719proc addtocflist {ids} {
7720    global treediffs
7721
7722    add_flist $treediffs($ids)
7723    getblobdiffs $ids
7724}
7725
7726proc diffcmd {ids flags} {
7727    global log_showroot nullid nullid2 git_version
7728
7729    set i [lsearch -exact $ids $nullid]
7730    set j [lsearch -exact $ids $nullid2]
7731    if {$i >= 0} {
7732        if {[llength $ids] > 1 && $j < 0} {
7733            # comparing working directory with some specific revision
7734            set cmd [concat | git diff-index $flags]
7735            if {$i == 0} {
7736                lappend cmd -R [lindex $ids 1]
7737            } else {
7738                lappend cmd [lindex $ids 0]
7739            }
7740        } else {
7741            # comparing working directory with index
7742            set cmd [concat | git diff-files $flags]
7743            if {$j == 1} {
7744                lappend cmd -R
7745            }
7746        }
7747    } elseif {$j >= 0} {
7748        if {[package vcompare $git_version "1.7.2"] >= 0} {
7749            set flags "$flags --ignore-submodules=dirty"
7750        }
7751        set cmd [concat | git diff-index --cached $flags]
7752        if {[llength $ids] > 1} {
7753            # comparing index with specific revision
7754            if {$j == 0} {
7755                lappend cmd -R [lindex $ids 1]
7756            } else {
7757                lappend cmd [lindex $ids 0]
7758            }
7759        } else {
7760            # comparing index with HEAD
7761            lappend cmd HEAD
7762        }
7763    } else {
7764        if {$log_showroot} {
7765            lappend flags --root
7766        }
7767        set cmd [concat | git diff-tree -r $flags $ids]
7768    }
7769    return $cmd
7770}
7771
7772proc gettreediffs {ids} {
7773    global treediff treepending limitdiffs vfilelimit curview
7774
7775    set cmd [diffcmd $ids {--no-commit-id}]
7776    if {$limitdiffs && $vfilelimit($curview) ne {}} {
7777            set cmd [concat $cmd -- $vfilelimit($curview)]
7778    }
7779    if {[catch {set gdtf [open $cmd r]}]} return
7780
7781    set treepending $ids
7782    set treediff {}
7783    fconfigure $gdtf -blocking 0 -encoding binary
7784    filerun $gdtf [list gettreediffline $gdtf $ids]
7785}
7786
7787proc gettreediffline {gdtf ids} {
7788    global treediff treediffs treepending diffids diffmergeid
7789    global cmitmode vfilelimit curview limitdiffs perfile_attrs
7790
7791    set nr 0
7792    set sublist {}
7793    set max 1000
7794    if {$perfile_attrs} {
7795        # cache_gitattr is slow, and even slower on win32 where we
7796        # have to invoke it for only about 30 paths at a time
7797        set max 500
7798        if {[tk windowingsystem] == "win32"} {
7799            set max 120
7800        }
7801    }
7802    while {[incr nr] <= $max && [gets $gdtf line] >= 0} {
7803        set i [string first "\t" $line]
7804        if {$i >= 0} {
7805            set file [string range $line [expr {$i+1}] end]
7806            if {[string index $file 0] eq "\""} {
7807                set file [lindex $file 0]
7808            }
7809            set file [encoding convertfrom $file]
7810            if {$file ne [lindex $treediff end]} {
7811                lappend treediff $file
7812                lappend sublist $file
7813            }
7814        }
7815    }
7816    if {$perfile_attrs} {
7817        cache_gitattr encoding $sublist
7818    }
7819    if {![eof $gdtf]} {
7820        return [expr {$nr >= $max? 2: 1}]
7821    }
7822    close $gdtf
7823    set treediffs($ids) $treediff
7824    unset treepending
7825    if {$cmitmode eq "tree" && [llength $diffids] == 1} {
7826        gettree $diffids
7827    } elseif {$ids != $diffids} {
7828        if {![info exists diffmergeid]} {
7829            gettreediffs $diffids
7830        }
7831    } else {
7832        addtocflist $ids
7833    }
7834    return 0
7835}
7836
7837# empty string or positive integer
7838proc diffcontextvalidate {v} {
7839    return [regexp {^(|[1-9][0-9]*)$} $v]
7840}
7841
7842proc diffcontextchange {n1 n2 op} {
7843    global diffcontextstring diffcontext
7844
7845    if {[string is integer -strict $diffcontextstring]} {
7846        if {$diffcontextstring >= 0} {
7847            set diffcontext $diffcontextstring
7848            reselectline
7849        }
7850    }
7851}
7852
7853proc changeignorespace {} {
7854    reselectline
7855}
7856
7857proc changeworddiff {name ix op} {
7858    reselectline
7859}
7860
7861proc initblobdiffvars {} {
7862    global diffencoding targetline diffnparents
7863    global diffinhdr currdiffsubmod diffseehere
7864    set targetline {}
7865    set diffnparents 0
7866    set diffinhdr 0
7867    set diffencoding [get_path_encoding {}]
7868    set currdiffsubmod ""
7869    set diffseehere -1
7870}
7871
7872proc getblobdiffs {ids} {
7873    global blobdifffd diffids env
7874    global treediffs
7875    global diffcontext
7876    global ignorespace
7877    global worddiff
7878    global limitdiffs vfilelimit curview
7879    global git_version
7880
7881    set textconv {}
7882    if {[package vcompare $git_version "1.6.1"] >= 0} {
7883        set textconv "--textconv"
7884    }
7885    set submodule {}
7886    if {[package vcompare $git_version "1.6.6"] >= 0} {
7887        set submodule "--submodule"
7888    }
7889    set cmd [diffcmd $ids "-p $textconv $submodule  -C --cc --no-commit-id -U$diffcontext"]
7890    if {$ignorespace} {
7891        append cmd " -w"
7892    }
7893    if {$worddiff ne [mc "Line diff"]} {
7894        append cmd " --word-diff=porcelain"
7895    }
7896    if {$limitdiffs && $vfilelimit($curview) ne {}} {
7897        set cmd [concat $cmd -- $vfilelimit($curview)]
7898    }
7899    if {[catch {set bdf [open $cmd r]} err]} {
7900        error_popup [mc "Error getting diffs: %s" $err]
7901        return
7902    }
7903    fconfigure $bdf -blocking 0 -encoding binary -eofchar {}
7904    set blobdifffd($ids) $bdf
7905    initblobdiffvars
7906    filerun $bdf [list getblobdiffline $bdf $diffids]
7907}
7908
7909proc savecmitpos {} {
7910    global ctext cmitmode
7911
7912    if {$cmitmode eq "tree"} {
7913        return {}
7914    }
7915    return [list target_scrollpos [$ctext index @0,0]]
7916}
7917
7918proc savectextpos {} {
7919    global ctext
7920
7921    return [list target_scrollpos [$ctext index @0,0]]
7922}
7923
7924proc maybe_scroll_ctext {ateof} {
7925    global ctext target_scrollpos
7926
7927    if {![info exists target_scrollpos]} return
7928    if {!$ateof} {
7929        set nlines [expr {[winfo height $ctext]
7930                          / [font metrics textfont -linespace]}]
7931        if {[$ctext compare "$target_scrollpos + $nlines lines" <= end]} return
7932    }
7933    $ctext yview $target_scrollpos
7934    unset target_scrollpos
7935}
7936
7937proc setinlist {var i val} {
7938    global $var
7939
7940    while {[llength [set $var]] < $i} {
7941        lappend $var {}
7942    }
7943    if {[llength [set $var]] == $i} {
7944        lappend $var $val
7945    } else {
7946        lset $var $i $val
7947    }
7948}
7949
7950proc makediffhdr {fname ids} {
7951    global ctext curdiffstart treediffs diffencoding
7952    global ctext_file_names jump_to_here targetline diffline
7953
7954    set fname [encoding convertfrom $fname]
7955    set diffencoding [get_path_encoding $fname]
7956    set i [lsearch -exact $treediffs($ids) $fname]
7957    if {$i >= 0} {
7958        setinlist difffilestart $i $curdiffstart
7959    }
7960    lset ctext_file_names end $fname
7961    set l [expr {(78 - [string length $fname]) / 2}]
7962    set pad [string range "----------------------------------------" 1 $l]
7963    $ctext insert $curdiffstart "$pad $fname $pad" filesep
7964    set targetline {}
7965    if {$jump_to_here ne {} && [lindex $jump_to_here 0] eq $fname} {
7966        set targetline [lindex $jump_to_here 1]
7967    }
7968    set diffline 0
7969}
7970
7971proc blobdiffmaybeseehere {ateof} {
7972    global diffseehere
7973    if {$diffseehere >= 0} {
7974        mark_ctext_line [lindex [split $diffseehere .] 0]
7975    }
7976    maybe_scroll_ctext $ateof
7977}
7978
7979proc getblobdiffline {bdf ids} {
7980    global diffids blobdifffd
7981    global ctext
7982
7983    set nr 0
7984    $ctext conf -state normal
7985    while {[incr nr] <= 1000 && [gets $bdf line] >= 0} {
7986        if {$ids != $diffids || $bdf != $blobdifffd($ids)} {
7987            catch {close $bdf}
7988            return 0
7989        }
7990        parseblobdiffline $ids $line
7991    }
7992    $ctext conf -state disabled
7993    blobdiffmaybeseehere [eof $bdf]
7994    if {[eof $bdf]} {
7995        catch {close $bdf}
7996        return 0
7997    }
7998    return [expr {$nr >= 1000? 2: 1}]
7999}
8000
8001proc parseblobdiffline {ids line} {
8002    global ctext curdiffstart
8003    global diffnexthead diffnextnote difffilestart
8004    global ctext_file_names ctext_file_lines
8005    global diffinhdr treediffs mergemax diffnparents
8006    global diffencoding jump_to_here targetline diffline currdiffsubmod
8007    global worddiff diffseehere
8008
8009    if {![string compare -length 5 "diff " $line]} {
8010        if {![regexp {^diff (--cc|--git) } $line m type]} {
8011            set line [encoding convertfrom $line]
8012            $ctext insert end "$line\n" hunksep
8013            continue
8014        }
8015        # start of a new file
8016        set diffinhdr 1
8017        $ctext insert end "\n"
8018        set curdiffstart [$ctext index "end - 1c"]
8019        lappend ctext_file_names ""
8020        lappend ctext_file_lines [lindex [split $curdiffstart "."] 0]
8021        $ctext insert end "\n" filesep
8022
8023        if {$type eq "--cc"} {
8024            # start of a new file in a merge diff
8025            set fname [string range $line 10 end]
8026            if {[lsearch -exact $treediffs($ids) $fname] < 0} {
8027                lappend treediffs($ids) $fname
8028                add_flist [list $fname]
8029            }
8030
8031        } else {
8032            set line [string range $line 11 end]
8033            # If the name hasn't changed the length will be odd,
8034            # the middle char will be a space, and the two bits either
8035            # side will be a/name and b/name, or "a/name" and "b/name".
8036            # If the name has changed we'll get "rename from" and
8037            # "rename to" or "copy from" and "copy to" lines following
8038            # this, and we'll use them to get the filenames.
8039            # This complexity is necessary because spaces in the
8040            # filename(s) don't get escaped.
8041            set l [string length $line]
8042            set i [expr {$l / 2}]
8043            if {!(($l & 1) && [string index $line $i] eq " " &&
8044                  [string range $line 2 [expr {$i - 1}]] eq \
8045                      [string range $line [expr {$i + 3}] end])} {
8046                return
8047            }
8048            # unescape if quoted and chop off the a/ from the front
8049            if {[string index $line 0] eq "\""} {
8050                set fname [string range [lindex $line 0] 2 end]
8051            } else {
8052                set fname [string range $line 2 [expr {$i - 1}]]
8053            }
8054        }
8055        makediffhdr $fname $ids
8056
8057    } elseif {![string compare -length 16 "* Unmerged path " $line]} {
8058        set fname [encoding convertfrom [string range $line 16 end]]
8059        $ctext insert end "\n"
8060        set curdiffstart [$ctext index "end - 1c"]
8061        lappend ctext_file_names $fname
8062        lappend ctext_file_lines [lindex [split $curdiffstart "."] 0]
8063        $ctext insert end "$line\n" filesep
8064        set i [lsearch -exact $treediffs($ids) $fname]
8065        if {$i >= 0} {
8066            setinlist difffilestart $i $curdiffstart
8067        }
8068
8069    } elseif {![string compare -length 2 "@@" $line]} {
8070        regexp {^@@+} $line ats
8071        set line [encoding convertfrom $diffencoding $line]
8072        $ctext insert end "$line\n" hunksep
8073        if {[regexp { \+(\d+),\d+ @@} $line m nl]} {
8074            set diffline $nl
8075        }
8076        set diffnparents [expr {[string length $ats] - 1}]
8077        set diffinhdr 0
8078
8079    } elseif {![string compare -length 10 "Submodule " $line]} {
8080        # start of a new submodule
8081        if {[regexp -indices "\[0-9a-f\]+\\.\\." $line nameend]} {
8082            set fname [string range $line 10 [expr [lindex $nameend 0] - 2]]
8083        } else {
8084            set fname [string range $line 10 [expr [string first "contains " $line] - 2]]
8085        }
8086        if {$currdiffsubmod != $fname} {
8087            $ctext insert end "\n";     # Add newline after commit message
8088        }
8089        set curdiffstart [$ctext index "end - 1c"]
8090        lappend ctext_file_names ""
8091        if {$currdiffsubmod != $fname} {
8092            lappend ctext_file_lines $fname
8093            makediffhdr $fname $ids
8094            set currdiffsubmod $fname
8095            $ctext insert end "\n$line\n" filesep
8096        } else {
8097            $ctext insert end "$line\n" filesep
8098        }
8099    } elseif {![string compare -length 3 "  >" $line]} {
8100        set $currdiffsubmod ""
8101        set line [encoding convertfrom $diffencoding $line]
8102        $ctext insert end "$line\n" dresult
8103    } elseif {![string compare -length 3 "  <" $line]} {
8104        set $currdiffsubmod ""
8105        set line [encoding convertfrom $diffencoding $line]
8106        $ctext insert end "$line\n" d0
8107    } elseif {$diffinhdr} {
8108        if {![string compare -length 12 "rename from " $line]} {
8109            set fname [string range $line [expr 6 + [string first " from " $line] ] end]
8110            if {[string index $fname 0] eq "\""} {
8111                set fname [lindex $fname 0]
8112            }
8113            set fname [encoding convertfrom $fname]
8114            set i [lsearch -exact $treediffs($ids) $fname]
8115            if {$i >= 0} {
8116                setinlist difffilestart $i $curdiffstart
8117            }
8118        } elseif {![string compare -length 10 $line "rename to "] ||
8119                  ![string compare -length 8 $line "copy to "]} {
8120            set fname [string range $line [expr 4 + [string first " to " $line] ] end]
8121            if {[string index $fname 0] eq "\""} {
8122                set fname [lindex $fname 0]
8123            }
8124            makediffhdr $fname $ids
8125        } elseif {[string compare -length 3 $line "---"] == 0} {
8126            # do nothing
8127            return
8128        } elseif {[string compare -length 3 $line "+++"] == 0} {
8129            set diffinhdr 0
8130            return
8131        }
8132        $ctext insert end "$line\n" filesep
8133
8134    } else {
8135        set line [string map {\x1A ^Z} \
8136                      [encoding convertfrom $diffencoding $line]]
8137        # parse the prefix - one ' ', '-' or '+' for each parent
8138        set prefix [string range $line 0 [expr {$diffnparents - 1}]]
8139        set tag [expr {$diffnparents > 1? "m": "d"}]
8140        set dowords [expr {$worddiff ne [mc "Line diff"] && $diffnparents == 1}]
8141        set words_pre_markup ""
8142        set words_post_markup ""
8143        if {[string trim $prefix " -+"] eq {}} {
8144            # prefix only has " ", "-" and "+" in it: normal diff line
8145            set num [string first "-" $prefix]
8146            if {$dowords} {
8147                set line [string range $line 1 end]
8148            }
8149            if {$num >= 0} {
8150                # removed line, first parent with line is $num
8151                if {$num >= $mergemax} {
8152                    set num "max"
8153                }
8154                if {$dowords && $worddiff eq [mc "Markup words"]} {
8155                    $ctext insert end "\[-$line-\]" $tag$num
8156                } else {
8157                    $ctext insert end "$line" $tag$num
8158                }
8159                if {!$dowords} {
8160                    $ctext insert end "\n" $tag$num
8161                }
8162            } else {
8163                set tags {}
8164                if {[string first "+" $prefix] >= 0} {
8165                    # added line
8166                    lappend tags ${tag}result
8167                    if {$diffnparents > 1} {
8168                        set num [string first " " $prefix]
8169                        if {$num >= 0} {
8170                            if {$num >= $mergemax} {
8171                                set num "max"
8172                            }
8173                            lappend tags m$num
8174                        }
8175                    }
8176                    set words_pre_markup "{+"
8177                    set words_post_markup "+}"
8178                }
8179                if {$targetline ne {}} {
8180                    if {$diffline == $targetline} {
8181                        set diffseehere [$ctext index "end - 1 chars"]
8182                        set targetline {}
8183                    } else {
8184                        incr diffline
8185                    }
8186                }
8187                if {$dowords && $worddiff eq [mc "Markup words"]} {
8188                    $ctext insert end "$words_pre_markup$line$words_post_markup" $tags
8189                } else {
8190                    $ctext insert end "$line" $tags
8191                }
8192                if {!$dowords} {
8193                    $ctext insert end "\n" $tags
8194                }
8195            }
8196        } elseif {$dowords && $prefix eq "~"} {
8197            $ctext insert end "\n" {}
8198        } else {
8199            # "\ No newline at end of file",
8200            # or something else we don't recognize
8201            $ctext insert end "$line\n" hunksep
8202        }
8203    }
8204}
8205
8206proc changediffdisp {} {
8207    global ctext diffelide
8208
8209    $ctext tag conf d0 -elide [lindex $diffelide 0]
8210    $ctext tag conf dresult -elide [lindex $diffelide 1]
8211}
8212
8213proc highlightfile {cline} {
8214    global cflist cflist_top
8215
8216    if {![info exists cflist_top]} return
8217
8218    $cflist tag remove highlight $cflist_top.0 "$cflist_top.0 lineend"
8219    $cflist tag add highlight $cline.0 "$cline.0 lineend"
8220    $cflist see $cline.0
8221    set cflist_top $cline
8222}
8223
8224proc highlightfile_for_scrollpos {topidx} {
8225    global cmitmode difffilestart
8226
8227    if {$cmitmode eq "tree"} return
8228    if {![info exists difffilestart]} return
8229
8230    set top [lindex [split $topidx .] 0]
8231    if {$difffilestart eq {} || $top < [lindex $difffilestart 0]} {
8232        highlightfile 0
8233    } else {
8234        highlightfile [expr {[bsearch $difffilestart $top] + 2}]
8235    }
8236}
8237
8238proc prevfile {} {
8239    global difffilestart ctext cmitmode
8240
8241    if {$cmitmode eq "tree"} return
8242    set prev 0.0
8243    set here [$ctext index @0,0]
8244    foreach loc $difffilestart {
8245        if {[$ctext compare $loc >= $here]} {
8246            $ctext yview $prev
8247            return
8248        }
8249        set prev $loc
8250    }
8251    $ctext yview $prev
8252}
8253
8254proc nextfile {} {
8255    global difffilestart ctext cmitmode
8256
8257    if {$cmitmode eq "tree"} return
8258    set here [$ctext index @0,0]
8259    foreach loc $difffilestart {
8260        if {[$ctext compare $loc > $here]} {
8261            $ctext yview $loc
8262            return
8263        }
8264    }
8265}
8266
8267proc clear_ctext {{first 1.0}} {
8268    global ctext smarktop smarkbot
8269    global ctext_file_names ctext_file_lines
8270    global pendinglinks
8271
8272    set l [lindex [split $first .] 0]
8273    if {![info exists smarktop] || [$ctext compare $first < $smarktop.0]} {
8274        set smarktop $l
8275    }
8276    if {![info exists smarkbot] || [$ctext compare $first < $smarkbot.0]} {
8277        set smarkbot $l
8278    }
8279    $ctext delete $first end
8280    if {$first eq "1.0"} {
8281        catch {unset pendinglinks}
8282    }
8283    set ctext_file_names {}
8284    set ctext_file_lines {}
8285}
8286
8287proc settabs {{firstab {}}} {
8288    global firsttabstop tabstop ctext have_tk85
8289
8290    if {$firstab ne {} && $have_tk85} {
8291        set firsttabstop $firstab
8292    }
8293    set w [font measure textfont "0"]
8294    if {$firsttabstop != 0} {
8295        $ctext conf -tabs [list [expr {($firsttabstop + $tabstop) * $w}] \
8296                               [expr {($firsttabstop + 2 * $tabstop) * $w}]]
8297    } elseif {$have_tk85 || $tabstop != 8} {
8298        $ctext conf -tabs [expr {$tabstop * $w}]
8299    } else {
8300        $ctext conf -tabs {}
8301    }
8302}
8303
8304proc incrsearch {name ix op} {
8305    global ctext searchstring searchdirn
8306
8307    if {[catch {$ctext index anchor}]} {
8308        # no anchor set, use start of selection, or of visible area
8309        set sel [$ctext tag ranges sel]
8310        if {$sel ne {}} {
8311            $ctext mark set anchor [lindex $sel 0]
8312        } elseif {$searchdirn eq "-forwards"} {
8313            $ctext mark set anchor @0,0
8314        } else {
8315            $ctext mark set anchor @0,[winfo height $ctext]
8316        }
8317    }
8318    if {$searchstring ne {}} {
8319        set here [$ctext search -count mlen $searchdirn -- $searchstring anchor]
8320        if {$here ne {}} {
8321            $ctext see $here
8322            set mend "$here + $mlen c"
8323            $ctext tag remove sel 1.0 end
8324            $ctext tag add sel $here $mend
8325            suppress_highlighting_file_for_current_scrollpos
8326            highlightfile_for_scrollpos $here
8327        }
8328    }
8329    rehighlight_search_results
8330}
8331
8332proc dosearch {} {
8333    global sstring ctext searchstring searchdirn
8334
8335    focus $sstring
8336    $sstring icursor end
8337    set searchdirn -forwards
8338    if {$searchstring ne {}} {
8339        set sel [$ctext tag ranges sel]
8340        if {$sel ne {}} {
8341            set start "[lindex $sel 0] + 1c"
8342        } elseif {[catch {set start [$ctext index anchor]}]} {
8343            set start "@0,0"
8344        }
8345        set match [$ctext search -count mlen -- $searchstring $start]
8346        $ctext tag remove sel 1.0 end
8347        if {$match eq {}} {
8348            bell
8349            return
8350        }
8351        $ctext see $match
8352        suppress_highlighting_file_for_current_scrollpos
8353        highlightfile_for_scrollpos $match
8354        set mend "$match + $mlen c"
8355        $ctext tag add sel $match $mend
8356        $ctext mark unset anchor
8357        rehighlight_search_results
8358    }
8359}
8360
8361proc dosearchback {} {
8362    global sstring ctext searchstring searchdirn
8363
8364    focus $sstring
8365    $sstring icursor end
8366    set searchdirn -backwards
8367    if {$searchstring ne {}} {
8368        set sel [$ctext tag ranges sel]
8369        if {$sel ne {}} {
8370            set start [lindex $sel 0]
8371        } elseif {[catch {set start [$ctext index anchor]}]} {
8372            set start @0,[winfo height $ctext]
8373        }
8374        set match [$ctext search -backwards -count ml -- $searchstring $start]
8375        $ctext tag remove sel 1.0 end
8376        if {$match eq {}} {
8377            bell
8378            return
8379        }
8380        $ctext see $match
8381        suppress_highlighting_file_for_current_scrollpos
8382        highlightfile_for_scrollpos $match
8383        set mend "$match + $ml c"
8384        $ctext tag add sel $match $mend
8385        $ctext mark unset anchor
8386        rehighlight_search_results
8387    }
8388}
8389
8390proc rehighlight_search_results {} {
8391    global ctext searchstring
8392
8393    $ctext tag remove found 1.0 end
8394    $ctext tag remove currentsearchhit 1.0 end
8395
8396    if {$searchstring ne {}} {
8397        searchmarkvisible 1
8398    }
8399}
8400
8401proc searchmark {first last} {
8402    global ctext searchstring
8403
8404    set sel [$ctext tag ranges sel]
8405
8406    set mend $first.0
8407    while {1} {
8408        set match [$ctext search -count mlen -- $searchstring $mend $last.end]
8409        if {$match eq {}} break
8410        set mend "$match + $mlen c"
8411        if {$sel ne {} && [$ctext compare $match == [lindex $sel 0]]} {
8412            $ctext tag add currentsearchhit $match $mend
8413        } else {
8414            $ctext tag add found $match $mend
8415        }
8416    }
8417}
8418
8419proc searchmarkvisible {doall} {
8420    global ctext smarktop smarkbot
8421
8422    set topline [lindex [split [$ctext index @0,0] .] 0]
8423    set botline [lindex [split [$ctext index @0,[winfo height $ctext]] .] 0]
8424    if {$doall || $botline < $smarktop || $topline > $smarkbot} {
8425        # no overlap with previous
8426        searchmark $topline $botline
8427        set smarktop $topline
8428        set smarkbot $botline
8429    } else {
8430        if {$topline < $smarktop} {
8431            searchmark $topline [expr {$smarktop-1}]
8432            set smarktop $topline
8433        }
8434        if {$botline > $smarkbot} {
8435            searchmark [expr {$smarkbot+1}] $botline
8436            set smarkbot $botline
8437        }
8438    }
8439}
8440
8441proc suppress_highlighting_file_for_current_scrollpos {} {
8442    global ctext suppress_highlighting_file_for_this_scrollpos
8443
8444    set suppress_highlighting_file_for_this_scrollpos [$ctext index @0,0]
8445}
8446
8447proc scrolltext {f0 f1} {
8448    global searchstring cmitmode ctext
8449    global suppress_highlighting_file_for_this_scrollpos
8450
8451    set topidx [$ctext index @0,0]
8452    if {![info exists suppress_highlighting_file_for_this_scrollpos]
8453        || $topidx ne $suppress_highlighting_file_for_this_scrollpos} {
8454        highlightfile_for_scrollpos $topidx
8455    }
8456
8457    catch {unset suppress_highlighting_file_for_this_scrollpos}
8458
8459    .bleft.bottom.sb set $f0 $f1
8460    if {$searchstring ne {}} {
8461        searchmarkvisible 0
8462    }
8463}
8464
8465proc setcoords {} {
8466    global linespc charspc canvx0 canvy0
8467    global xspc1 xspc2 lthickness
8468
8469    set linespc [font metrics mainfont -linespace]
8470    set charspc [font measure mainfont "m"]
8471    set canvy0 [expr {int(3 + 0.5 * $linespc)}]
8472    set canvx0 [expr {int(3 + 0.5 * $linespc)}]
8473    set lthickness [expr {int($linespc / 9) + 1}]
8474    set xspc1(0) $linespc
8475    set xspc2 $linespc
8476}
8477
8478proc redisplay {} {
8479    global canv
8480    global selectedline
8481
8482    set ymax [lindex [$canv cget -scrollregion] 3]
8483    if {$ymax eq {} || $ymax == 0} return
8484    set span [$canv yview]
8485    clear_display
8486    setcanvscroll
8487    allcanvs yview moveto [lindex $span 0]
8488    drawvisible
8489    if {$selectedline ne {}} {
8490        selectline $selectedline 0
8491        allcanvs yview moveto [lindex $span 0]
8492    }
8493}
8494
8495proc parsefont {f n} {
8496    global fontattr
8497
8498    set fontattr($f,family) [lindex $n 0]
8499    set s [lindex $n 1]
8500    if {$s eq {} || $s == 0} {
8501        set s 10
8502    } elseif {$s < 0} {
8503        set s [expr {int(-$s / [winfo fpixels . 1p] + 0.5)}]
8504    }
8505    set fontattr($f,size) $s
8506    set fontattr($f,weight) normal
8507    set fontattr($f,slant) roman
8508    foreach style [lrange $n 2 end] {
8509        switch -- $style {
8510            "normal" -
8511            "bold"   {set fontattr($f,weight) $style}
8512            "roman" -
8513            "italic" {set fontattr($f,slant) $style}
8514        }
8515    }
8516}
8517
8518proc fontflags {f {isbold 0}} {
8519    global fontattr
8520
8521    return [list -family $fontattr($f,family) -size $fontattr($f,size) \
8522                -weight [expr {$isbold? "bold": $fontattr($f,weight)}] \
8523                -slant $fontattr($f,slant)]
8524}
8525
8526proc fontname {f} {
8527    global fontattr
8528
8529    set n [list $fontattr($f,family) $fontattr($f,size)]
8530    if {$fontattr($f,weight) eq "bold"} {
8531        lappend n "bold"
8532    }
8533    if {$fontattr($f,slant) eq "italic"} {
8534        lappend n "italic"
8535    }
8536    return $n
8537}
8538
8539proc incrfont {inc} {
8540    global mainfont textfont ctext canv cflist showrefstop
8541    global stopped entries fontattr
8542
8543    unmarkmatches
8544    set s $fontattr(mainfont,size)
8545    incr s $inc
8546    if {$s < 1} {
8547        set s 1
8548    }
8549    set fontattr(mainfont,size) $s
8550    font config mainfont -size $s
8551    font config mainfontbold -size $s
8552    set mainfont [fontname mainfont]
8553    set s $fontattr(textfont,size)
8554    incr s $inc
8555    if {$s < 1} {
8556        set s 1
8557    }
8558    set fontattr(textfont,size) $s
8559    font config textfont -size $s
8560    font config textfontbold -size $s
8561    set textfont [fontname textfont]
8562    setcoords
8563    settabs
8564    redisplay
8565}
8566
8567proc clearsha1 {} {
8568    global sha1entry sha1string
8569    if {[string length $sha1string] == 40} {
8570        $sha1entry delete 0 end
8571    }
8572}
8573
8574proc sha1change {n1 n2 op} {
8575    global sha1string currentid sha1but
8576    if {$sha1string == {}
8577        || ([info exists currentid] && $sha1string == $currentid)} {
8578        set state disabled
8579    } else {
8580        set state normal
8581    }
8582    if {[$sha1but cget -state] == $state} return
8583    if {$state == "normal"} {
8584        $sha1but conf -state normal -relief raised -text "[mc "Goto:"] "
8585    } else {
8586        $sha1but conf -state disabled -relief flat -text "[mc "SHA1 ID:"] "
8587    }
8588}
8589
8590proc gotocommit {} {
8591    global sha1string tagids headids curview varcid
8592
8593    if {$sha1string == {}
8594        || ([info exists currentid] && $sha1string == $currentid)} return
8595    if {[info exists tagids($sha1string)]} {
8596        set id $tagids($sha1string)
8597    } elseif {[info exists headids($sha1string)]} {
8598        set id $headids($sha1string)
8599    } else {
8600        set id [string tolower $sha1string]
8601        if {[regexp {^[0-9a-f]{4,39}$} $id]} {
8602            set matches [longid $id]
8603            if {$matches ne {}} {
8604                if {[llength $matches] > 1} {
8605                    error_popup [mc "Short SHA1 id %s is ambiguous" $id]
8606                    return
8607                }
8608                set id [lindex $matches 0]
8609            }
8610        } else {
8611            if {[catch {set id [exec git rev-parse --verify $sha1string]}]} {
8612                error_popup [mc "Revision %s is not known" $sha1string]
8613                return
8614            }
8615        }
8616    }
8617    if {[commitinview $id $curview]} {
8618        selectline [rowofcommit $id] 1
8619        return
8620    }
8621    if {[regexp {^[0-9a-fA-F]{4,}$} $sha1string]} {
8622        set msg [mc "SHA1 id %s is not known" $sha1string]
8623    } else {
8624        set msg [mc "Revision %s is not in the current view" $sha1string]
8625    }
8626    error_popup $msg
8627}
8628
8629proc lineenter {x y id} {
8630    global hoverx hovery hoverid hovertimer
8631    global commitinfo canv
8632
8633    if {![info exists commitinfo($id)] && ![getcommit $id]} return
8634    set hoverx $x
8635    set hovery $y
8636    set hoverid $id
8637    if {[info exists hovertimer]} {
8638        after cancel $hovertimer
8639    }
8640    set hovertimer [after 500 linehover]
8641    $canv delete hover
8642}
8643
8644proc linemotion {x y id} {
8645    global hoverx hovery hoverid hovertimer
8646
8647    if {[info exists hoverid] && $id == $hoverid} {
8648        set hoverx $x
8649        set hovery $y
8650        if {[info exists hovertimer]} {
8651            after cancel $hovertimer
8652        }
8653        set hovertimer [after 500 linehover]
8654    }
8655}
8656
8657proc lineleave {id} {
8658    global hoverid hovertimer canv
8659
8660    if {[info exists hoverid] && $id == $hoverid} {
8661        $canv delete hover
8662        if {[info exists hovertimer]} {
8663            after cancel $hovertimer
8664            unset hovertimer
8665        }
8666        unset hoverid
8667    }
8668}
8669
8670proc linehover {} {
8671    global hoverx hovery hoverid hovertimer
8672    global canv linespc lthickness
8673    global linehoverbgcolor linehoverfgcolor linehoveroutlinecolor
8674
8675    global commitinfo
8676
8677    set text [lindex $commitinfo($hoverid) 0]
8678    set ymax [lindex [$canv cget -scrollregion] 3]
8679    if {$ymax == {}} return
8680    set yfrac [lindex [$canv yview] 0]
8681    set x [expr {$hoverx + 2 * $linespc}]
8682    set y [expr {$hovery + $yfrac * $ymax - $linespc / 2}]
8683    set x0 [expr {$x - 2 * $lthickness}]
8684    set y0 [expr {$y - 2 * $lthickness}]
8685    set x1 [expr {$x + [font measure mainfont $text] + 2 * $lthickness}]
8686    set y1 [expr {$y + $linespc + 2 * $lthickness}]
8687    set t [$canv create rectangle $x0 $y0 $x1 $y1 \
8688               -fill $linehoverbgcolor -outline $linehoveroutlinecolor \
8689               -width 1 -tags hover]
8690    $canv raise $t
8691    set t [$canv create text $x $y -anchor nw -text $text -tags hover \
8692               -font mainfont -fill $linehoverfgcolor]
8693    $canv raise $t
8694}
8695
8696proc clickisonarrow {id y} {
8697    global lthickness
8698
8699    set ranges [rowranges $id]
8700    set thresh [expr {2 * $lthickness + 6}]
8701    set n [expr {[llength $ranges] - 1}]
8702    for {set i 1} {$i < $n} {incr i} {
8703        set row [lindex $ranges $i]
8704        if {abs([yc $row] - $y) < $thresh} {
8705            return $i
8706        }
8707    }
8708    return {}
8709}
8710
8711proc arrowjump {id n y} {
8712    global canv
8713
8714    # 1 <-> 2, 3 <-> 4, etc...
8715    set n [expr {(($n - 1) ^ 1) + 1}]
8716    set row [lindex [rowranges $id] $n]
8717    set yt [yc $row]
8718    set ymax [lindex [$canv cget -scrollregion] 3]
8719    if {$ymax eq {} || $ymax <= 0} return
8720    set view [$canv yview]
8721    set yspan [expr {[lindex $view 1] - [lindex $view 0]}]
8722    set yfrac [expr {$yt / $ymax - $yspan / 2}]
8723    if {$yfrac < 0} {
8724        set yfrac 0
8725    }
8726    allcanvs yview moveto $yfrac
8727}
8728
8729proc lineclick {x y id isnew} {
8730    global ctext commitinfo children canv thickerline curview
8731
8732    if {![info exists commitinfo($id)] && ![getcommit $id]} return
8733    unmarkmatches
8734    unselectline
8735    normalline
8736    $canv delete hover
8737    # draw this line thicker than normal
8738    set thickerline $id
8739    drawlines $id
8740    if {$isnew} {
8741        set ymax [lindex [$canv cget -scrollregion] 3]
8742        if {$ymax eq {}} return
8743        set yfrac [lindex [$canv yview] 0]
8744        set y [expr {$y + $yfrac * $ymax}]
8745    }
8746    set dirn [clickisonarrow $id $y]
8747    if {$dirn ne {}} {
8748        arrowjump $id $dirn $y
8749        return
8750    }
8751
8752    if {$isnew} {
8753        addtohistory [list lineclick $x $y $id 0] savectextpos
8754    }
8755    # fill the details pane with info about this line
8756    $ctext conf -state normal
8757    clear_ctext
8758    settabs 0
8759    $ctext insert end "[mc "Parent"]:\t"
8760    $ctext insert end $id link0
8761    setlink $id link0
8762    set info $commitinfo($id)
8763    $ctext insert end "\n\t[lindex $info 0]\n"
8764    $ctext insert end "\t[mc "Author"]:\t[lindex $info 1]\n"
8765    set date [formatdate [lindex $info 2]]
8766    $ctext insert end "\t[mc "Date"]:\t$date\n"
8767    set kids $children($curview,$id)
8768    if {$kids ne {}} {
8769        $ctext insert end "\n[mc "Children"]:"
8770        set i 0
8771        foreach child $kids {
8772            incr i
8773            if {![info exists commitinfo($child)] && ![getcommit $child]} continue
8774            set info $commitinfo($child)
8775            $ctext insert end "\n\t"
8776            $ctext insert end $child link$i
8777            setlink $child link$i
8778            $ctext insert end "\n\t[lindex $info 0]"
8779            $ctext insert end "\n\t[mc "Author"]:\t[lindex $info 1]"
8780            set date [formatdate [lindex $info 2]]
8781            $ctext insert end "\n\t[mc "Date"]:\t$date\n"
8782        }
8783    }
8784    maybe_scroll_ctext 1
8785    $ctext conf -state disabled
8786    init_flist {}
8787}
8788
8789proc normalline {} {
8790    global thickerline
8791    if {[info exists thickerline]} {
8792        set id $thickerline
8793        unset thickerline
8794        drawlines $id
8795    }
8796}
8797
8798proc selbyid {id {isnew 1}} {
8799    global curview
8800    if {[commitinview $id $curview]} {
8801        selectline [rowofcommit $id] $isnew
8802    }
8803}
8804
8805proc mstime {} {
8806    global startmstime
8807    if {![info exists startmstime]} {
8808        set startmstime [clock clicks -milliseconds]
8809    }
8810    return [format "%.3f" [expr {([clock click -milliseconds] - $startmstime) / 1000.0}]]
8811}
8812
8813proc rowmenu {x y id} {
8814    global rowctxmenu selectedline rowmenuid curview
8815    global nullid nullid2 fakerowmenu mainhead markedid
8816
8817    stopfinding
8818    set rowmenuid $id
8819    if {$selectedline eq {} || [rowofcommit $id] eq $selectedline} {
8820        set state disabled
8821    } else {
8822        set state normal
8823    }
8824    if {[info exists markedid] && $markedid ne $id} {
8825        set mstate normal
8826    } else {
8827        set mstate disabled
8828    }
8829    if {$id ne $nullid && $id ne $nullid2} {
8830        set menu $rowctxmenu
8831        if {$mainhead ne {}} {
8832            $menu entryconfigure 7 -label [mc "Reset %s branch to here" $mainhead] -state normal
8833        } else {
8834            $menu entryconfigure 7 -label [mc "Detached head: can't reset" $mainhead] -state disabled
8835        }
8836        $menu entryconfigure 9 -state $mstate
8837        $menu entryconfigure 10 -state $mstate
8838        $menu entryconfigure 11 -state $mstate
8839    } else {
8840        set menu $fakerowmenu
8841    }
8842    $menu entryconfigure [mca "Diff this -> selected"] -state $state
8843    $menu entryconfigure [mca "Diff selected -> this"] -state $state
8844    $menu entryconfigure [mca "Make patch"] -state $state
8845    $menu entryconfigure [mca "Diff this -> marked commit"] -state $mstate
8846    $menu entryconfigure [mca "Diff marked commit -> this"] -state $mstate
8847    tk_popup $menu $x $y
8848}
8849
8850proc markhere {} {
8851    global rowmenuid markedid canv
8852
8853    set markedid $rowmenuid
8854    make_idmark $markedid
8855}
8856
8857proc gotomark {} {
8858    global markedid
8859
8860    if {[info exists markedid]} {
8861        selbyid $markedid
8862    }
8863}
8864
8865proc replace_by_kids {l r} {
8866    global curview children
8867
8868    set id [commitonrow $r]
8869    set l [lreplace $l 0 0]
8870    foreach kid $children($curview,$id) {
8871        lappend l [rowofcommit $kid]
8872    }
8873    return [lsort -integer -decreasing -unique $l]
8874}
8875
8876proc find_common_desc {} {
8877    global markedid rowmenuid curview children
8878
8879    if {![info exists markedid]} return
8880    if {![commitinview $markedid $curview] ||
8881        ![commitinview $rowmenuid $curview]} return
8882    #set t1 [clock clicks -milliseconds]
8883    set l1 [list [rowofcommit $markedid]]
8884    set l2 [list [rowofcommit $rowmenuid]]
8885    while 1 {
8886        set r1 [lindex $l1 0]
8887        set r2 [lindex $l2 0]
8888        if {$r1 eq {} || $r2 eq {}} break
8889        if {$r1 == $r2} {
8890            selectline $r1 1
8891            break
8892        }
8893        if {$r1 > $r2} {
8894            set l1 [replace_by_kids $l1 $r1]
8895        } else {
8896            set l2 [replace_by_kids $l2 $r2]
8897        }
8898    }
8899    #set t2 [clock clicks -milliseconds]
8900    #puts "took [expr {$t2-$t1}]ms"
8901}
8902
8903proc compare_commits {} {
8904    global markedid rowmenuid curview children
8905
8906    if {![info exists markedid]} return
8907    if {![commitinview $markedid $curview]} return
8908    addtohistory [list do_cmp_commits $markedid $rowmenuid]
8909    do_cmp_commits $markedid $rowmenuid
8910}
8911
8912proc getpatchid {id} {
8913    global patchids
8914
8915    if {![info exists patchids($id)]} {
8916        set cmd [diffcmd [list $id] {-p --root}]
8917        # trim off the initial "|"
8918        set cmd [lrange $cmd 1 end]
8919        if {[catch {
8920            set x [eval exec $cmd | git patch-id]
8921            set patchids($id) [lindex $x 0]
8922        }]} {
8923            set patchids($id) "error"
8924        }
8925    }
8926    return $patchids($id)
8927}
8928
8929proc do_cmp_commits {a b} {
8930    global ctext curview parents children patchids commitinfo
8931
8932    $ctext conf -state normal
8933    clear_ctext
8934    init_flist {}
8935    for {set i 0} {$i < 100} {incr i} {
8936        set skipa 0
8937        set skipb 0
8938        if {[llength $parents($curview,$a)] > 1} {
8939            appendshortlink $a [mc "Skipping merge commit "] "\n"
8940            set skipa 1
8941        } else {
8942            set patcha [getpatchid $a]
8943        }
8944        if {[llength $parents($curview,$b)] > 1} {
8945            appendshortlink $b [mc "Skipping merge commit "] "\n"
8946            set skipb 1
8947        } else {
8948            set patchb [getpatchid $b]
8949        }
8950        if {!$skipa && !$skipb} {
8951            set heada [lindex $commitinfo($a) 0]
8952            set headb [lindex $commitinfo($b) 0]
8953            if {$patcha eq "error"} {
8954                appendshortlink $a [mc "Error getting patch ID for "] \
8955                    [mc " - stopping\n"]
8956                break
8957            }
8958            if {$patchb eq "error"} {
8959                appendshortlink $b [mc "Error getting patch ID for "] \
8960                    [mc " - stopping\n"]
8961                break
8962            }
8963            if {$patcha eq $patchb} {
8964                if {$heada eq $headb} {
8965                    appendshortlink $a [mc "Commit "]
8966                    appendshortlink $b " == " "  $heada\n"
8967                } else {
8968                    appendshortlink $a [mc "Commit "] "  $heada\n"
8969                    appendshortlink $b [mc " is the same patch as\n       "] \
8970                        "  $headb\n"
8971                }
8972                set skipa 1
8973                set skipb 1
8974            } else {
8975                $ctext insert end "\n"
8976                appendshortlink $a [mc "Commit "] "  $heada\n"
8977                appendshortlink $b [mc " differs from\n       "] \
8978                    "  $headb\n"
8979                $ctext insert end [mc "Diff of commits:\n\n"]
8980                $ctext conf -state disabled
8981                update
8982                diffcommits $a $b
8983                return
8984            }
8985        }
8986        if {$skipa} {
8987            set kids [real_children $curview,$a]
8988            if {[llength $kids] != 1} {
8989                $ctext insert end "\n"
8990                appendshortlink $a [mc "Commit "] \
8991                    [mc " has %s children - stopping\n" [llength $kids]]
8992                break
8993            }
8994            set a [lindex $kids 0]
8995        }
8996        if {$skipb} {
8997            set kids [real_children $curview,$b]
8998            if {[llength $kids] != 1} {
8999                appendshortlink $b [mc "Commit "] \
9000                    [mc " has %s children - stopping\n" [llength $kids]]
9001                break
9002            }
9003            set b [lindex $kids 0]
9004        }
9005    }
9006    $ctext conf -state disabled
9007}
9008
9009proc diffcommits {a b} {
9010    global diffcontext diffids blobdifffd diffinhdr currdiffsubmod
9011
9012    set tmpdir [gitknewtmpdir]
9013    set fna [file join $tmpdir "commit-[string range $a 0 7]"]
9014    set fnb [file join $tmpdir "commit-[string range $b 0 7]"]
9015    if {[catch {
9016        exec git diff-tree -p --pretty $a >$fna
9017        exec git diff-tree -p --pretty $b >$fnb
9018    } err]} {
9019        error_popup [mc "Error writing commit to file: %s" $err]
9020        return
9021    }
9022    if {[catch {
9023        set fd [open "| diff -U$diffcontext $fna $fnb" r]
9024    } err]} {
9025        error_popup [mc "Error diffing commits: %s" $err]
9026        return
9027    }
9028    set diffids [list commits $a $b]
9029    set blobdifffd($diffids) $fd
9030    set diffinhdr 0
9031    set currdiffsubmod ""
9032    filerun $fd [list getblobdiffline $fd $diffids]
9033}
9034
9035proc diffvssel {dirn} {
9036    global rowmenuid selectedline
9037
9038    if {$selectedline eq {}} return
9039    if {$dirn} {
9040        set oldid [commitonrow $selectedline]
9041        set newid $rowmenuid
9042    } else {
9043        set oldid $rowmenuid
9044        set newid [commitonrow $selectedline]
9045    }
9046    addtohistory [list doseldiff $oldid $newid] savectextpos
9047    doseldiff $oldid $newid
9048}
9049
9050proc diffvsmark {dirn} {
9051    global rowmenuid markedid
9052
9053    if {![info exists markedid]} return
9054    if {$dirn} {
9055        set oldid $markedid
9056        set newid $rowmenuid
9057    } else {
9058        set oldid $rowmenuid
9059        set newid $markedid
9060    }
9061    addtohistory [list doseldiff $oldid $newid] savectextpos
9062    doseldiff $oldid $newid
9063}
9064
9065proc doseldiff {oldid newid} {
9066    global ctext
9067    global commitinfo
9068
9069    $ctext conf -state normal
9070    clear_ctext
9071    init_flist [mc "Top"]
9072    $ctext insert end "[mc "From"] "
9073    $ctext insert end $oldid link0
9074    setlink $oldid link0
9075    $ctext insert end "\n     "
9076    $ctext insert end [lindex $commitinfo($oldid) 0]
9077    $ctext insert end "\n\n[mc "To"]   "
9078    $ctext insert end $newid link1
9079    setlink $newid link1
9080    $ctext insert end "\n     "
9081    $ctext insert end [lindex $commitinfo($newid) 0]
9082    $ctext insert end "\n"
9083    $ctext conf -state disabled
9084    $ctext tag remove found 1.0 end
9085    startdiff [list $oldid $newid]
9086}
9087
9088proc mkpatch {} {
9089    global rowmenuid currentid commitinfo patchtop patchnum NS
9090
9091    if {![info exists currentid]} return
9092    set oldid $currentid
9093    set oldhead [lindex $commitinfo($oldid) 0]
9094    set newid $rowmenuid
9095    set newhead [lindex $commitinfo($newid) 0]
9096    set top .patch
9097    set patchtop $top
9098    catch {destroy $top}
9099    ttk_toplevel $top
9100    make_transient $top .
9101    ${NS}::label $top.title -text [mc "Generate patch"]
9102    grid $top.title - -pady 10
9103    ${NS}::label $top.from -text [mc "From:"]
9104    ${NS}::entry $top.fromsha1 -width 40
9105    $top.fromsha1 insert 0 $oldid
9106    $top.fromsha1 conf -state readonly
9107    grid $top.from $top.fromsha1 -sticky w
9108    ${NS}::entry $top.fromhead -width 60
9109    $top.fromhead insert 0 $oldhead
9110    $top.fromhead conf -state readonly
9111    grid x $top.fromhead -sticky w
9112    ${NS}::label $top.to -text [mc "To:"]
9113    ${NS}::entry $top.tosha1 -width 40
9114    $top.tosha1 insert 0 $newid
9115    $top.tosha1 conf -state readonly
9116    grid $top.to $top.tosha1 -sticky w
9117    ${NS}::entry $top.tohead -width 60
9118    $top.tohead insert 0 $newhead
9119    $top.tohead conf -state readonly
9120    grid x $top.tohead -sticky w
9121    ${NS}::button $top.rev -text [mc "Reverse"] -command mkpatchrev
9122    grid $top.rev x -pady 10 -padx 5
9123    ${NS}::label $top.flab -text [mc "Output file:"]
9124    ${NS}::entry $top.fname -width 60
9125    $top.fname insert 0 [file normalize "patch$patchnum.patch"]
9126    incr patchnum
9127    grid $top.flab $top.fname -sticky w
9128    ${NS}::frame $top.buts
9129    ${NS}::button $top.buts.gen -text [mc "Generate"] -command mkpatchgo
9130    ${NS}::button $top.buts.can -text [mc "Cancel"] -command mkpatchcan
9131    bind $top <Key-Return> mkpatchgo
9132    bind $top <Key-Escape> mkpatchcan
9133    grid $top.buts.gen $top.buts.can
9134    grid columnconfigure $top.buts 0 -weight 1 -uniform a
9135    grid columnconfigure $top.buts 1 -weight 1 -uniform a
9136    grid $top.buts - -pady 10 -sticky ew
9137    focus $top.fname
9138}
9139
9140proc mkpatchrev {} {
9141    global patchtop
9142
9143    set oldid [$patchtop.fromsha1 get]
9144    set oldhead [$patchtop.fromhead get]
9145    set newid [$patchtop.tosha1 get]
9146    set newhead [$patchtop.tohead get]
9147    foreach e [list fromsha1 fromhead tosha1 tohead] \
9148            v [list $newid $newhead $oldid $oldhead] {
9149        $patchtop.$e conf -state normal
9150        $patchtop.$e delete 0 end
9151        $patchtop.$e insert 0 $v
9152        $patchtop.$e conf -state readonly
9153    }
9154}
9155
9156proc mkpatchgo {} {
9157    global patchtop nullid nullid2
9158
9159    set oldid [$patchtop.fromsha1 get]
9160    set newid [$patchtop.tosha1 get]
9161    set fname [$patchtop.fname get]
9162    set cmd [diffcmd [list $oldid $newid] -p]
9163    # trim off the initial "|"
9164    set cmd [lrange $cmd 1 end]
9165    lappend cmd >$fname &
9166    if {[catch {eval exec $cmd} err]} {
9167        error_popup "[mc "Error creating patch:"] $err" $patchtop
9168    }
9169    catch {destroy $patchtop}
9170    unset patchtop
9171}
9172
9173proc mkpatchcan {} {
9174    global patchtop
9175
9176    catch {destroy $patchtop}
9177    unset patchtop
9178}
9179
9180proc mktag {} {
9181    global rowmenuid mktagtop commitinfo NS
9182
9183    set top .maketag
9184    set mktagtop $top
9185    catch {destroy $top}
9186    ttk_toplevel $top
9187    make_transient $top .
9188    ${NS}::label $top.title -text [mc "Create tag"]
9189    grid $top.title - -pady 10
9190    ${NS}::label $top.id -text [mc "ID:"]
9191    ${NS}::entry $top.sha1 -width 40
9192    $top.sha1 insert 0 $rowmenuid
9193    $top.sha1 conf -state readonly
9194    grid $top.id $top.sha1 -sticky w
9195    ${NS}::entry $top.head -width 60
9196    $top.head insert 0 [lindex $commitinfo($rowmenuid) 0]
9197    $top.head conf -state readonly
9198    grid x $top.head -sticky w
9199    ${NS}::label $top.tlab -text [mc "Tag name:"]
9200    ${NS}::entry $top.tag -width 60
9201    grid $top.tlab $top.tag -sticky w
9202    ${NS}::label $top.op -text [mc "Tag message is optional"]
9203    grid $top.op -columnspan 2 -sticky we
9204    ${NS}::label $top.mlab -text [mc "Tag message:"]
9205    ${NS}::entry $top.msg -width 60
9206    grid $top.mlab $top.msg -sticky w
9207    ${NS}::frame $top.buts
9208    ${NS}::button $top.buts.gen -text [mc "Create"] -command mktaggo
9209    ${NS}::button $top.buts.can -text [mc "Cancel"] -command mktagcan
9210    bind $top <Key-Return> mktaggo
9211    bind $top <Key-Escape> mktagcan
9212    grid $top.buts.gen $top.buts.can
9213    grid columnconfigure $top.buts 0 -weight 1 -uniform a
9214    grid columnconfigure $top.buts 1 -weight 1 -uniform a
9215    grid $top.buts - -pady 10 -sticky ew
9216    focus $top.tag
9217}
9218
9219proc domktag {} {
9220    global mktagtop env tagids idtags
9221
9222    set id [$mktagtop.sha1 get]
9223    set tag [$mktagtop.tag get]
9224    set msg [$mktagtop.msg get]
9225    if {$tag == {}} {
9226        error_popup [mc "No tag name specified"] $mktagtop
9227        return 0
9228    }
9229    if {[info exists tagids($tag)]} {
9230        error_popup [mc "Tag \"%s\" already exists" $tag] $mktagtop
9231        return 0
9232    }
9233    if {[catch {
9234        if {$msg != {}} {
9235            exec git tag -a -m $msg $tag $id
9236        } else {
9237            exec git tag $tag $id
9238        }
9239    } err]} {
9240        error_popup "[mc "Error creating tag:"] $err" $mktagtop
9241        return 0
9242    }
9243
9244    set tagids($tag) $id
9245    lappend idtags($id) $tag
9246    redrawtags $id
9247    addedtag $id
9248    dispneartags 0
9249    run refill_reflist
9250    return 1
9251}
9252
9253proc redrawtags {id} {
9254    global canv linehtag idpos currentid curview cmitlisted markedid
9255    global canvxmax iddrawn circleitem mainheadid circlecolors
9256    global mainheadcirclecolor
9257
9258    if {![commitinview $id $curview]} return
9259    if {![info exists iddrawn($id)]} return
9260    set row [rowofcommit $id]
9261    if {$id eq $mainheadid} {
9262        set ofill $mainheadcirclecolor
9263    } else {
9264        set ofill [lindex $circlecolors $cmitlisted($curview,$id)]
9265    }
9266    $canv itemconf $circleitem($row) -fill $ofill
9267    $canv delete tag.$id
9268    set xt [eval drawtags $id $idpos($id)]
9269    $canv coords $linehtag($id) $xt [lindex $idpos($id) 2]
9270    set text [$canv itemcget $linehtag($id) -text]
9271    set font [$canv itemcget $linehtag($id) -font]
9272    set xr [expr {$xt + [font measure $font $text]}]
9273    if {$xr > $canvxmax} {
9274        set canvxmax $xr
9275        setcanvscroll
9276    }
9277    if {[info exists currentid] && $currentid == $id} {
9278        make_secsel $id
9279    }
9280    if {[info exists markedid] && $markedid eq $id} {
9281        make_idmark $id
9282    }
9283}
9284
9285proc mktagcan {} {
9286    global mktagtop
9287
9288    catch {destroy $mktagtop}
9289    unset mktagtop
9290}
9291
9292proc mktaggo {} {
9293    if {![domktag]} return
9294    mktagcan
9295}
9296
9297proc writecommit {} {
9298    global rowmenuid wrcomtop commitinfo wrcomcmd NS
9299
9300    set top .writecommit
9301    set wrcomtop $top
9302    catch {destroy $top}
9303    ttk_toplevel $top
9304    make_transient $top .
9305    ${NS}::label $top.title -text [mc "Write commit to file"]
9306    grid $top.title - -pady 10
9307    ${NS}::label $top.id -text [mc "ID:"]
9308    ${NS}::entry $top.sha1 -width 40
9309    $top.sha1 insert 0 $rowmenuid
9310    $top.sha1 conf -state readonly
9311    grid $top.id $top.sha1 -sticky w
9312    ${NS}::entry $top.head -width 60
9313    $top.head insert 0 [lindex $commitinfo($rowmenuid) 0]
9314    $top.head conf -state readonly
9315    grid x $top.head -sticky w
9316    ${NS}::label $top.clab -text [mc "Command:"]
9317    ${NS}::entry $top.cmd -width 60 -textvariable wrcomcmd
9318    grid $top.clab $top.cmd -sticky w -pady 10
9319    ${NS}::label $top.flab -text [mc "Output file:"]
9320    ${NS}::entry $top.fname -width 60
9321    $top.fname insert 0 [file normalize "commit-[string range $rowmenuid 0 6]"]
9322    grid $top.flab $top.fname -sticky w
9323    ${NS}::frame $top.buts
9324    ${NS}::button $top.buts.gen -text [mc "Write"] -command wrcomgo
9325    ${NS}::button $top.buts.can -text [mc "Cancel"] -command wrcomcan
9326    bind $top <Key-Return> wrcomgo
9327    bind $top <Key-Escape> wrcomcan
9328    grid $top.buts.gen $top.buts.can
9329    grid columnconfigure $top.buts 0 -weight 1 -uniform a
9330    grid columnconfigure $top.buts 1 -weight 1 -uniform a
9331    grid $top.buts - -pady 10 -sticky ew
9332    focus $top.fname
9333}
9334
9335proc wrcomgo {} {
9336    global wrcomtop
9337
9338    set id [$wrcomtop.sha1 get]
9339    set cmd "echo $id | [$wrcomtop.cmd get]"
9340    set fname [$wrcomtop.fname get]
9341    if {[catch {exec sh -c $cmd >$fname &} err]} {
9342        error_popup "[mc "Error writing commit:"] $err" $wrcomtop
9343    }
9344    catch {destroy $wrcomtop}
9345    unset wrcomtop
9346}
9347
9348proc wrcomcan {} {
9349    global wrcomtop
9350
9351    catch {destroy $wrcomtop}
9352    unset wrcomtop
9353}
9354
9355proc mkbranch {} {
9356    global rowmenuid mkbrtop NS
9357
9358    set top .makebranch
9359    catch {destroy $top}
9360    ttk_toplevel $top
9361    make_transient $top .
9362    ${NS}::label $top.title -text [mc "Create new branch"]
9363    grid $top.title - -pady 10
9364    ${NS}::label $top.id -text [mc "ID:"]
9365    ${NS}::entry $top.sha1 -width 40
9366    $top.sha1 insert 0 $rowmenuid
9367    $top.sha1 conf -state readonly
9368    grid $top.id $top.sha1 -sticky w
9369    ${NS}::label $top.nlab -text [mc "Name:"]
9370    ${NS}::entry $top.name -width 40
9371    grid $top.nlab $top.name -sticky w
9372    ${NS}::frame $top.buts
9373    ${NS}::button $top.buts.go -text [mc "Create"] -command [list mkbrgo $top]
9374    ${NS}::button $top.buts.can -text [mc "Cancel"] -command "catch {destroy $top}"
9375    bind $top <Key-Return> [list mkbrgo $top]
9376    bind $top <Key-Escape> "catch {destroy $top}"
9377    grid $top.buts.go $top.buts.can
9378    grid columnconfigure $top.buts 0 -weight 1 -uniform a
9379    grid columnconfigure $top.buts 1 -weight 1 -uniform a
9380    grid $top.buts - -pady 10 -sticky ew
9381    focus $top.name
9382}
9383
9384proc mkbrgo {top} {
9385    global headids idheads
9386
9387    set name [$top.name get]
9388    set id [$top.sha1 get]
9389    set cmdargs {}
9390    set old_id {}
9391    if {$name eq {}} {
9392        error_popup [mc "Please specify a name for the new branch"] $top
9393        return
9394    }
9395    if {[info exists headids($name)]} {
9396        if {![confirm_popup [mc \
9397                "Branch '%s' already exists. Overwrite?" $name] $top]} {
9398            return
9399        }
9400        set old_id $headids($name)
9401        lappend cmdargs -f
9402    }
9403    catch {destroy $top}
9404    lappend cmdargs $name $id
9405    nowbusy newbranch
9406    update
9407    if {[catch {
9408        eval exec git branch $cmdargs
9409    } err]} {
9410        notbusy newbranch
9411        error_popup $err
9412    } else {
9413        notbusy newbranch
9414        if {$old_id ne {}} {
9415            movehead $id $name
9416            movedhead $id $name
9417            redrawtags $old_id
9418            redrawtags $id
9419        } else {
9420            set headids($name) $id
9421            lappend idheads($id) $name
9422            addedhead $id $name
9423            redrawtags $id
9424        }
9425        dispneartags 0
9426        run refill_reflist
9427    }
9428}
9429
9430proc exec_citool {tool_args {baseid {}}} {
9431    global commitinfo env
9432
9433    set save_env [array get env GIT_AUTHOR_*]
9434
9435    if {$baseid ne {}} {
9436        if {![info exists commitinfo($baseid)]} {
9437            getcommit $baseid
9438        }
9439        set author [lindex $commitinfo($baseid) 1]
9440        set date [lindex $commitinfo($baseid) 2]
9441        if {[regexp {^\s*(\S.*\S|\S)\s*<(.*)>\s*$} \
9442                    $author author name email]
9443            && $date ne {}} {
9444            set env(GIT_AUTHOR_NAME) $name
9445            set env(GIT_AUTHOR_EMAIL) $email
9446            set env(GIT_AUTHOR_DATE) $date
9447        }
9448    }
9449
9450    eval exec git citool $tool_args &
9451
9452    array unset env GIT_AUTHOR_*
9453    array set env $save_env
9454}
9455
9456proc cherrypick {} {
9457    global rowmenuid curview
9458    global mainhead mainheadid
9459    global gitdir
9460
9461    set oldhead [exec git rev-parse HEAD]
9462    set dheads [descheads $rowmenuid]
9463    if {$dheads ne {} && [lsearch -exact $dheads $oldhead] >= 0} {
9464        set ok [confirm_popup [mc "Commit %s is already\
9465                included in branch %s -- really re-apply it?" \
9466                                   [string range $rowmenuid 0 7] $mainhead]]
9467        if {!$ok} return
9468    }
9469    nowbusy cherrypick [mc "Cherry-picking"]
9470    update
9471    # Unfortunately git-cherry-pick writes stuff to stderr even when
9472    # no error occurs, and exec takes that as an indication of error...
9473    if {[catch {exec sh -c "git cherry-pick -r $rowmenuid 2>&1"} err]} {
9474        notbusy cherrypick
9475        if {[regexp -line \
9476                 {Entry '(.*)' (would be overwritten by merge|not uptodate)} \
9477                 $err msg fname]} {
9478            error_popup [mc "Cherry-pick failed because of local changes\
9479                        to file '%s'.\nPlease commit, reset or stash\
9480                        your changes and try again." $fname]
9481        } elseif {[regexp -line \
9482                       {^(CONFLICT \(.*\):|Automatic cherry-pick failed|error: could not apply)} \
9483                       $err]} {
9484            if {[confirm_popup [mc "Cherry-pick failed because of merge\
9485                        conflict.\nDo you wish to run git citool to\
9486                        resolve it?"]]} {
9487                # Force citool to read MERGE_MSG
9488                file delete [file join $gitdir "GITGUI_MSG"]
9489                exec_citool {} $rowmenuid
9490            }
9491        } else {
9492            error_popup $err
9493        }
9494        run updatecommits
9495        return
9496    }
9497    set newhead [exec git rev-parse HEAD]
9498    if {$newhead eq $oldhead} {
9499        notbusy cherrypick
9500        error_popup [mc "No changes committed"]
9501        return
9502    }
9503    addnewchild $newhead $oldhead
9504    if {[commitinview $oldhead $curview]} {
9505        # XXX this isn't right if we have a path limit...
9506        insertrow $newhead $oldhead $curview
9507        if {$mainhead ne {}} {
9508            movehead $newhead $mainhead
9509            movedhead $newhead $mainhead
9510        }
9511        set mainheadid $newhead
9512        redrawtags $oldhead
9513        redrawtags $newhead
9514        selbyid $newhead
9515    }
9516    notbusy cherrypick
9517}
9518
9519proc revert {} {
9520    global rowmenuid curview
9521    global mainhead mainheadid
9522    global gitdir
9523
9524    set oldhead [exec git rev-parse HEAD]
9525    set dheads [descheads $rowmenuid]
9526    if { $dheads eq {} || [lsearch -exact $dheads $oldhead] == -1 } {
9527       set ok [confirm_popup [mc "Commit %s is not\
9528           included in branch %s -- really revert it?" \
9529                      [string range $rowmenuid 0 7] $mainhead]]
9530       if {!$ok} return
9531    }
9532    nowbusy revert [mc "Reverting"]
9533    update
9534
9535    if [catch {exec git revert --no-edit $rowmenuid} err] {
9536        notbusy revert
9537        if [regexp {files would be overwritten by merge:(\n(( |\t)+[^\n]+\n)+)}\
9538                $err match files] {
9539            regsub {\n( |\t)+} $files "\n" files
9540            error_popup [mc "Revert failed because of local changes to\
9541                the following files:%s Please commit, reset or stash \
9542                your changes and try again." $files]
9543        } elseif [regexp {error: could not revert} $err] {
9544            if [confirm_popup [mc "Revert failed because of merge conflict.\n\
9545                Do you wish to run git citool to resolve it?"]] {
9546                # Force citool to read MERGE_MSG
9547                file delete [file join $gitdir "GITGUI_MSG"]
9548                exec_citool {} $rowmenuid
9549            }
9550        } else { error_popup $err }
9551        run updatecommits
9552        return
9553    }
9554
9555    set newhead [exec git rev-parse HEAD]
9556    if { $newhead eq $oldhead } {
9557        notbusy revert
9558        error_popup [mc "No changes committed"]
9559        return
9560    }
9561
9562    addnewchild $newhead $oldhead
9563
9564    if [commitinview $oldhead $curview] {
9565        # XXX this isn't right if we have a path limit...
9566        insertrow $newhead $oldhead $curview
9567        if {$mainhead ne {}} {
9568            movehead $newhead $mainhead
9569            movedhead $newhead $mainhead
9570        }
9571        set mainheadid $newhead
9572        redrawtags $oldhead
9573        redrawtags $newhead
9574        selbyid $newhead
9575    }
9576
9577    notbusy revert
9578}
9579
9580proc resethead {} {
9581    global mainhead rowmenuid confirm_ok resettype NS
9582
9583    set confirm_ok 0
9584    set w ".confirmreset"
9585    ttk_toplevel $w
9586    make_transient $w .
9587    wm title $w [mc "Confirm reset"]
9588    ${NS}::label $w.m -text \
9589        [mc "Reset branch %s to %s?" $mainhead [string range $rowmenuid 0 7]]
9590    pack $w.m -side top -fill x -padx 20 -pady 20
9591    ${NS}::labelframe $w.f -text [mc "Reset type:"]
9592    set resettype mixed
9593    ${NS}::radiobutton $w.f.soft -value soft -variable resettype \
9594        -text [mc "Soft: Leave working tree and index untouched"]
9595    grid $w.f.soft -sticky w
9596    ${NS}::radiobutton $w.f.mixed -value mixed -variable resettype \
9597        -text [mc "Mixed: Leave working tree untouched, reset index"]
9598    grid $w.f.mixed -sticky w
9599    ${NS}::radiobutton $w.f.hard -value hard -variable resettype \
9600        -text [mc "Hard: Reset working tree and index\n(discard ALL local changes)"]
9601    grid $w.f.hard -sticky w
9602    pack $w.f -side top -fill x -padx 4
9603    ${NS}::button $w.ok -text [mc OK] -command "set confirm_ok 1; destroy $w"
9604    pack $w.ok -side left -fill x -padx 20 -pady 20
9605    ${NS}::button $w.cancel -text [mc Cancel] -command "destroy $w"
9606    bind $w <Key-Escape> [list destroy $w]
9607    pack $w.cancel -side right -fill x -padx 20 -pady 20
9608    bind $w <Visibility> "grab $w; focus $w"
9609    tkwait window $w
9610    if {!$confirm_ok} return
9611    if {[catch {set fd [open \
9612            [list | git reset --$resettype $rowmenuid 2>@1] r]} err]} {
9613        error_popup $err
9614    } else {
9615        dohidelocalchanges
9616        filerun $fd [list readresetstat $fd]
9617        nowbusy reset [mc "Resetting"]
9618        selbyid $rowmenuid
9619    }
9620}
9621
9622proc readresetstat {fd} {
9623    global mainhead mainheadid showlocalchanges rprogcoord
9624
9625    if {[gets $fd line] >= 0} {
9626        if {[regexp {([0-9]+)% \(([0-9]+)/([0-9]+)\)} $line match p m n]} {
9627            set rprogcoord [expr {1.0 * $m / $n}]
9628            adjustprogress
9629        }
9630        return 1
9631    }
9632    set rprogcoord 0
9633    adjustprogress
9634    notbusy reset
9635    if {[catch {close $fd} err]} {
9636        error_popup $err
9637    }
9638    set oldhead $mainheadid
9639    set newhead [exec git rev-parse HEAD]
9640    if {$newhead ne $oldhead} {
9641        movehead $newhead $mainhead
9642        movedhead $newhead $mainhead
9643        set mainheadid $newhead
9644        redrawtags $oldhead
9645        redrawtags $newhead
9646    }
9647    if {$showlocalchanges} {
9648        doshowlocalchanges
9649    }
9650    return 0
9651}
9652
9653# context menu for a head
9654proc headmenu {x y id head} {
9655    global headmenuid headmenuhead headctxmenu mainhead
9656
9657    stopfinding
9658    set headmenuid $id
9659    set headmenuhead $head
9660    set state normal
9661    if {[string match "remotes/*" $head]} {
9662        set state disabled
9663    }
9664    if {$head eq $mainhead} {
9665        set state disabled
9666    }
9667    $headctxmenu entryconfigure 0 -state $state
9668    $headctxmenu entryconfigure 1 -state $state
9669    tk_popup $headctxmenu $x $y
9670}
9671
9672proc cobranch {} {
9673    global headmenuid headmenuhead headids
9674    global showlocalchanges
9675
9676    # check the tree is clean first??
9677    nowbusy checkout [mc "Checking out"]
9678    update
9679    dohidelocalchanges
9680    if {[catch {
9681        set fd [open [list | git checkout $headmenuhead 2>@1] r]
9682    } err]} {
9683        notbusy checkout
9684        error_popup $err
9685        if {$showlocalchanges} {
9686            dodiffindex
9687        }
9688    } else {
9689        filerun $fd [list readcheckoutstat $fd $headmenuhead $headmenuid]
9690    }
9691}
9692
9693proc readcheckoutstat {fd newhead newheadid} {
9694    global mainhead mainheadid headids showlocalchanges progresscoords
9695    global viewmainheadid curview
9696
9697    if {[gets $fd line] >= 0} {
9698        if {[regexp {([0-9]+)% \(([0-9]+)/([0-9]+)\)} $line match p m n]} {
9699            set progresscoords [list 0 [expr {1.0 * $m / $n}]]
9700            adjustprogress
9701        }
9702        return 1
9703    }
9704    set progresscoords {0 0}
9705    adjustprogress
9706    notbusy checkout
9707    if {[catch {close $fd} err]} {
9708        error_popup $err
9709    }
9710    set oldmainid $mainheadid
9711    set mainhead $newhead
9712    set mainheadid $newheadid
9713    set viewmainheadid($curview) $newheadid
9714    redrawtags $oldmainid
9715    redrawtags $newheadid
9716    selbyid $newheadid
9717    if {$showlocalchanges} {
9718        dodiffindex
9719    }
9720}
9721
9722proc rmbranch {} {
9723    global headmenuid headmenuhead mainhead
9724    global idheads
9725
9726    set head $headmenuhead
9727    set id $headmenuid
9728    # this check shouldn't be needed any more...
9729    if {$head eq $mainhead} {
9730        error_popup [mc "Cannot delete the currently checked-out branch"]
9731        return
9732    }
9733    set dheads [descheads $id]
9734    if {[llength $dheads] == 1 && $idheads($dheads) eq $head} {
9735        # the stuff on this branch isn't on any other branch
9736        if {![confirm_popup [mc "The commits on branch %s aren't on any other\
9737                        branch.\nReally delete branch %s?" $head $head]]} return
9738    }
9739    nowbusy rmbranch
9740    update
9741    if {[catch {exec git branch -D $head} err]} {
9742        notbusy rmbranch
9743        error_popup $err
9744        return
9745    }
9746    removehead $id $head
9747    removedhead $id $head
9748    redrawtags $id
9749    notbusy rmbranch
9750    dispneartags 0
9751    run refill_reflist
9752}
9753
9754# Display a list of tags and heads
9755proc showrefs {} {
9756    global showrefstop bgcolor fgcolor selectbgcolor NS
9757    global bglist fglist reflistfilter reflist maincursor
9758
9759    set top .showrefs
9760    set showrefstop $top
9761    if {[winfo exists $top]} {
9762        raise $top
9763        refill_reflist
9764        return
9765    }
9766    ttk_toplevel $top
9767    wm title $top [mc "Tags and heads: %s" [file tail [pwd]]]
9768    make_transient $top .
9769    text $top.list -background $bgcolor -foreground $fgcolor \
9770        -selectbackground $selectbgcolor -font mainfont \
9771        -xscrollcommand "$top.xsb set" -yscrollcommand "$top.ysb set" \
9772        -width 30 -height 20 -cursor $maincursor \
9773        -spacing1 1 -spacing3 1 -state disabled
9774    $top.list tag configure highlight -background $selectbgcolor
9775    lappend bglist $top.list
9776    lappend fglist $top.list
9777    ${NS}::scrollbar $top.ysb -command "$top.list yview" -orient vertical
9778    ${NS}::scrollbar $top.xsb -command "$top.list xview" -orient horizontal
9779    grid $top.list $top.ysb -sticky nsew
9780    grid $top.xsb x -sticky ew
9781    ${NS}::frame $top.f
9782    ${NS}::label $top.f.l -text "[mc "Filter"]: "
9783    ${NS}::entry $top.f.e -width 20 -textvariable reflistfilter
9784    set reflistfilter "*"
9785    trace add variable reflistfilter write reflistfilter_change
9786    pack $top.f.e -side right -fill x -expand 1
9787    pack $top.f.l -side left
9788    grid $top.f - -sticky ew -pady 2
9789    ${NS}::button $top.close -command [list destroy $top] -text [mc "Close"]
9790    bind $top <Key-Escape> [list destroy $top]
9791    grid $top.close -
9792    grid columnconfigure $top 0 -weight 1
9793    grid rowconfigure $top 0 -weight 1
9794    bind $top.list <1> {break}
9795    bind $top.list <B1-Motion> {break}
9796    bind $top.list <ButtonRelease-1> {sel_reflist %W %x %y; break}
9797    set reflist {}
9798    refill_reflist
9799}
9800
9801proc sel_reflist {w x y} {
9802    global showrefstop reflist headids tagids otherrefids
9803
9804    if {![winfo exists $showrefstop]} return
9805    set l [lindex [split [$w index "@$x,$y"] "."] 0]
9806    set ref [lindex $reflist [expr {$l-1}]]
9807    set n [lindex $ref 0]
9808    switch -- [lindex $ref 1] {
9809        "H" {selbyid $headids($n)}
9810        "T" {selbyid $tagids($n)}
9811        "o" {selbyid $otherrefids($n)}
9812    }
9813    $showrefstop.list tag add highlight $l.0 "$l.0 lineend"
9814}
9815
9816proc unsel_reflist {} {
9817    global showrefstop
9818
9819    if {![info exists showrefstop] || ![winfo exists $showrefstop]} return
9820    $showrefstop.list tag remove highlight 0.0 end
9821}
9822
9823proc reflistfilter_change {n1 n2 op} {
9824    global reflistfilter
9825
9826    after cancel refill_reflist
9827    after 200 refill_reflist
9828}
9829
9830proc refill_reflist {} {
9831    global reflist reflistfilter showrefstop headids tagids otherrefids
9832    global curview
9833
9834    if {![info exists showrefstop] || ![winfo exists $showrefstop]} return
9835    set refs {}
9836    foreach n [array names headids] {
9837        if {[string match $reflistfilter $n]} {
9838            if {[commitinview $headids($n) $curview]} {
9839                lappend refs [list $n H]
9840            } else {
9841                interestedin $headids($n) {run refill_reflist}
9842            }
9843        }
9844    }
9845    foreach n [array names tagids] {
9846        if {[string match $reflistfilter $n]} {
9847            if {[commitinview $tagids($n) $curview]} {
9848                lappend refs [list $n T]
9849            } else {
9850                interestedin $tagids($n) {run refill_reflist}
9851            }
9852        }
9853    }
9854    foreach n [array names otherrefids] {
9855        if {[string match $reflistfilter $n]} {
9856            if {[commitinview $otherrefids($n) $curview]} {
9857                lappend refs [list $n o]
9858            } else {
9859                interestedin $otherrefids($n) {run refill_reflist}
9860            }
9861        }
9862    }
9863    set refs [lsort -index 0 $refs]
9864    if {$refs eq $reflist} return
9865
9866    # Update the contents of $showrefstop.list according to the
9867    # differences between $reflist (old) and $refs (new)
9868    $showrefstop.list conf -state normal
9869    $showrefstop.list insert end "\n"
9870    set i 0
9871    set j 0
9872    while {$i < [llength $reflist] || $j < [llength $refs]} {
9873        if {$i < [llength $reflist]} {
9874            if {$j < [llength $refs]} {
9875                set cmp [string compare [lindex $reflist $i 0] \
9876                             [lindex $refs $j 0]]
9877                if {$cmp == 0} {
9878                    set cmp [string compare [lindex $reflist $i 1] \
9879                                 [lindex $refs $j 1]]
9880                }
9881            } else {
9882                set cmp -1
9883            }
9884        } else {
9885            set cmp 1
9886        }
9887        switch -- $cmp {
9888            -1 {
9889                $showrefstop.list delete "[expr {$j+1}].0" "[expr {$j+2}].0"
9890                incr i
9891            }
9892            0 {
9893                incr i
9894                incr j
9895            }
9896            1 {
9897                set l [expr {$j + 1}]
9898                $showrefstop.list image create $l.0 -align baseline \
9899                    -image reficon-[lindex $refs $j 1] -padx 2
9900                $showrefstop.list insert $l.1 "[lindex $refs $j 0]\n"
9901                incr j
9902            }
9903        }
9904    }
9905    set reflist $refs
9906    # delete last newline
9907    $showrefstop.list delete end-2c end-1c
9908    $showrefstop.list conf -state disabled
9909}
9910
9911# Stuff for finding nearby tags
9912proc getallcommits {} {
9913    global allcommits nextarc seeds allccache allcwait cachedarcs allcupdate
9914    global idheads idtags idotherrefs allparents tagobjid
9915    global gitdir
9916
9917    if {![info exists allcommits]} {
9918        set nextarc 0
9919        set allcommits 0
9920        set seeds {}
9921        set allcwait 0
9922        set cachedarcs 0
9923        set allccache [file join $gitdir "gitk.cache"]
9924        if {![catch {
9925            set f [open $allccache r]
9926            set allcwait 1
9927            getcache $f
9928        }]} return
9929    }
9930
9931    if {$allcwait} {
9932        return
9933    }
9934    set cmd [list | git rev-list --parents]
9935    set allcupdate [expr {$seeds ne {}}]
9936    if {!$allcupdate} {
9937        set ids "--all"
9938    } else {
9939        set refs [concat [array names idheads] [array names idtags] \
9940                      [array names idotherrefs]]
9941        set ids {}
9942        set tagobjs {}
9943        foreach name [array names tagobjid] {
9944            lappend tagobjs $tagobjid($name)
9945        }
9946        foreach id [lsort -unique $refs] {
9947            if {![info exists allparents($id)] &&
9948                [lsearch -exact $tagobjs $id] < 0} {
9949                lappend ids $id
9950            }
9951        }
9952        if {$ids ne {}} {
9953            foreach id $seeds {
9954                lappend ids "^$id"
9955            }
9956        }
9957    }
9958    if {$ids ne {}} {
9959        set fd [open [concat $cmd $ids] r]
9960        fconfigure $fd -blocking 0
9961        incr allcommits
9962        nowbusy allcommits
9963        filerun $fd [list getallclines $fd]
9964    } else {
9965        dispneartags 0
9966    }
9967}
9968
9969# Since most commits have 1 parent and 1 child, we group strings of
9970# such commits into "arcs" joining branch/merge points (BMPs), which
9971# are commits that either don't have 1 parent or don't have 1 child.
9972#
9973# arcnos(id) - incoming arcs for BMP, arc we're on for other nodes
9974# arcout(id) - outgoing arcs for BMP
9975# arcids(a) - list of IDs on arc including end but not start
9976# arcstart(a) - BMP ID at start of arc
9977# arcend(a) - BMP ID at end of arc
9978# growing(a) - arc a is still growing
9979# arctags(a) - IDs out of arcids (excluding end) that have tags
9980# archeads(a) - IDs out of arcids (excluding end) that have heads
9981# The start of an arc is at the descendent end, so "incoming" means
9982# coming from descendents, and "outgoing" means going towards ancestors.
9983
9984proc getallclines {fd} {
9985    global allparents allchildren idtags idheads nextarc
9986    global arcnos arcids arctags arcout arcend arcstart archeads growing
9987    global seeds allcommits cachedarcs allcupdate
9988
9989    set nid 0
9990    while {[incr nid] <= 1000 && [gets $fd line] >= 0} {
9991        set id [lindex $line 0]
9992        if {[info exists allparents($id)]} {
9993            # seen it already
9994            continue
9995        }
9996        set cachedarcs 0
9997        set olds [lrange $line 1 end]
9998        set allparents($id) $olds
9999        if {![info exists allchildren($id)]} {
10000            set allchildren($id) {}
10001            set arcnos($id) {}
10002            lappend seeds $id
10003        } else {
10004            set a $arcnos($id)
10005            if {[llength $olds] == 1 && [llength $a] == 1} {
10006                lappend arcids($a) $id
10007                if {[info exists idtags($id)]} {
10008                    lappend arctags($a) $id
10009                }
10010                if {[info exists idheads($id)]} {
10011                    lappend archeads($a) $id
10012                }
10013                if {[info exists allparents($olds)]} {
10014                    # seen parent already
10015                    if {![info exists arcout($olds)]} {
10016                        splitarc $olds
10017                    }
10018                    lappend arcids($a) $olds
10019                    set arcend($a) $olds
10020                    unset growing($a)
10021                }
10022                lappend allchildren($olds) $id
10023                lappend arcnos($olds) $a
10024                continue
10025            }
10026        }
10027        foreach a $arcnos($id) {
10028            lappend arcids($a) $id
10029            set arcend($a) $id
10030            unset growing($a)
10031        }
10032
10033        set ao {}
10034        foreach p $olds {
10035            lappend allchildren($p) $id
10036            set a [incr nextarc]
10037            set arcstart($a) $id
10038            set archeads($a) {}
10039            set arctags($a) {}
10040            set archeads($a) {}
10041            set arcids($a) {}
10042            lappend ao $a
10043            set growing($a) 1
10044            if {[info exists allparents($p)]} {
10045                # seen it already, may need to make a new branch
10046                if {![info exists arcout($p)]} {
10047                    splitarc $p
10048                }
10049                lappend arcids($a) $p
10050                set arcend($a) $p
10051                unset growing($a)
10052            }
10053            lappend arcnos($p) $a
10054        }
10055        set arcout($id) $ao
10056    }
10057    if {$nid > 0} {
10058        global cached_dheads cached_dtags cached_atags
10059        catch {unset cached_dheads}
10060        catch {unset cached_dtags}
10061        catch {unset cached_atags}
10062    }
10063    if {![eof $fd]} {
10064        return [expr {$nid >= 1000? 2: 1}]
10065    }
10066    set cacheok 1
10067    if {[catch {
10068        fconfigure $fd -blocking 1
10069        close $fd
10070    } err]} {
10071        # got an error reading the list of commits
10072        # if we were updating, try rereading the whole thing again
10073        if {$allcupdate} {
10074            incr allcommits -1
10075            dropcache $err
10076            return
10077        }
10078        error_popup "[mc "Error reading commit topology information;\
10079                branch and preceding/following tag information\
10080                will be incomplete."]\n($err)"
10081        set cacheok 0
10082    }
10083    if {[incr allcommits -1] == 0} {
10084        notbusy allcommits
10085        if {$cacheok} {
10086            run savecache
10087        }
10088    }
10089    dispneartags 0
10090    return 0
10091}
10092
10093proc recalcarc {a} {
10094    global arctags archeads arcids idtags idheads
10095
10096    set at {}
10097    set ah {}
10098    foreach id [lrange $arcids($a) 0 end-1] {
10099        if {[info exists idtags($id)]} {
10100            lappend at $id
10101        }
10102        if {[info exists idheads($id)]} {
10103            lappend ah $id
10104        }
10105    }
10106    set arctags($a) $at
10107    set archeads($a) $ah
10108}
10109
10110proc splitarc {p} {
10111    global arcnos arcids nextarc arctags archeads idtags idheads
10112    global arcstart arcend arcout allparents growing
10113
10114    set a $arcnos($p)
10115    if {[llength $a] != 1} {
10116        puts "oops splitarc called but [llength $a] arcs already"
10117        return
10118    }
10119    set a [lindex $a 0]
10120    set i [lsearch -exact $arcids($a) $p]
10121    if {$i < 0} {
10122        puts "oops splitarc $p not in arc $a"
10123        return
10124    }
10125    set na [incr nextarc]
10126    if {[info exists arcend($a)]} {
10127        set arcend($na) $arcend($a)
10128    } else {
10129        set l [lindex $allparents([lindex $arcids($a) end]) 0]
10130        set j [lsearch -exact $arcnos($l) $a]
10131        set arcnos($l) [lreplace $arcnos($l) $j $j $na]
10132    }
10133    set tail [lrange $arcids($a) [expr {$i+1}] end]
10134    set arcids($a) [lrange $arcids($a) 0 $i]
10135    set arcend($a) $p
10136    set arcstart($na) $p
10137    set arcout($p) $na
10138    set arcids($na) $tail
10139    if {[info exists growing($a)]} {
10140        set growing($na) 1
10141        unset growing($a)
10142    }
10143
10144    foreach id $tail {
10145        if {[llength $arcnos($id)] == 1} {
10146            set arcnos($id) $na
10147        } else {
10148            set j [lsearch -exact $arcnos($id) $a]
10149            set arcnos($id) [lreplace $arcnos($id) $j $j $na]
10150        }
10151    }
10152
10153    # reconstruct tags and heads lists
10154    if {$arctags($a) ne {} || $archeads($a) ne {}} {
10155        recalcarc $a
10156        recalcarc $na
10157    } else {
10158        set arctags($na) {}
10159        set archeads($na) {}
10160    }
10161}
10162
10163# Update things for a new commit added that is a child of one
10164# existing commit.  Used when cherry-picking.
10165proc addnewchild {id p} {
10166    global allparents allchildren idtags nextarc
10167    global arcnos arcids arctags arcout arcend arcstart archeads growing
10168    global seeds allcommits
10169
10170    if {![info exists allcommits] || ![info exists arcnos($p)]} return
10171    set allparents($id) [list $p]
10172    set allchildren($id) {}
10173    set arcnos($id) {}
10174    lappend seeds $id
10175    lappend allchildren($p) $id
10176    set a [incr nextarc]
10177    set arcstart($a) $id
10178    set archeads($a) {}
10179    set arctags($a) {}
10180    set arcids($a) [list $p]
10181    set arcend($a) $p
10182    if {![info exists arcout($p)]} {
10183        splitarc $p
10184    }
10185    lappend arcnos($p) $a
10186    set arcout($id) [list $a]
10187}
10188
10189# This implements a cache for the topology information.
10190# The cache saves, for each arc, the start and end of the arc,
10191# the ids on the arc, and the outgoing arcs from the end.
10192proc readcache {f} {
10193    global arcnos arcids arcout arcstart arcend arctags archeads nextarc
10194    global idtags idheads allparents cachedarcs possible_seeds seeds growing
10195    global allcwait
10196
10197    set a $nextarc
10198    set lim $cachedarcs
10199    if {$lim - $a > 500} {
10200        set lim [expr {$a + 500}]
10201    }
10202    if {[catch {
10203        if {$a == $lim} {
10204            # finish reading the cache and setting up arctags, etc.
10205            set line [gets $f]
10206            if {$line ne "1"} {error "bad final version"}
10207            close $f
10208            foreach id [array names idtags] {
10209                if {[info exists arcnos($id)] && [llength $arcnos($id)] == 1 &&
10210                    [llength $allparents($id)] == 1} {
10211                    set a [lindex $arcnos($id) 0]
10212                    if {$arctags($a) eq {}} {
10213                        recalcarc $a
10214                    }
10215                }
10216            }
10217            foreach id [array names idheads] {
10218                if {[info exists arcnos($id)] && [llength $arcnos($id)] == 1 &&
10219                    [llength $allparents($id)] == 1} {
10220                    set a [lindex $arcnos($id) 0]
10221                    if {$archeads($a) eq {}} {
10222                        recalcarc $a
10223                    }
10224                }
10225            }
10226            foreach id [lsort -unique $possible_seeds] {
10227                if {$arcnos($id) eq {}} {
10228                    lappend seeds $id
10229                }
10230            }
10231            set allcwait 0
10232        } else {
10233            while {[incr a] <= $lim} {
10234                set line [gets $f]
10235                if {[llength $line] != 3} {error "bad line"}
10236                set s [lindex $line 0]
10237                set arcstart($a) $s
10238                lappend arcout($s) $a
10239                if {![info exists arcnos($s)]} {
10240                    lappend possible_seeds $s
10241                    set arcnos($s) {}
10242                }
10243                set e [lindex $line 1]
10244                if {$e eq {}} {
10245                    set growing($a) 1
10246                } else {
10247                    set arcend($a) $e
10248                    if {![info exists arcout($e)]} {
10249                        set arcout($e) {}
10250                    }
10251                }
10252                set arcids($a) [lindex $line 2]
10253                foreach id $arcids($a) {
10254                    lappend allparents($s) $id
10255                    set s $id
10256                    lappend arcnos($id) $a
10257                }
10258                if {![info exists allparents($s)]} {
10259                    set allparents($s) {}
10260                }
10261                set arctags($a) {}
10262                set archeads($a) {}
10263            }
10264            set nextarc [expr {$a - 1}]
10265        }
10266    } err]} {
10267        dropcache $err
10268        return 0
10269    }
10270    if {!$allcwait} {
10271        getallcommits
10272    }
10273    return $allcwait
10274}
10275
10276proc getcache {f} {
10277    global nextarc cachedarcs possible_seeds
10278
10279    if {[catch {
10280        set line [gets $f]
10281        if {[llength $line] != 2 || [lindex $line 0] ne "1"} {error "bad version"}
10282        # make sure it's an integer
10283        set cachedarcs [expr {int([lindex $line 1])}]
10284        if {$cachedarcs < 0} {error "bad number of arcs"}
10285        set nextarc 0
10286        set possible_seeds {}
10287        run readcache $f
10288    } err]} {
10289        dropcache $err
10290    }
10291    return 0
10292}
10293
10294proc dropcache {err} {
10295    global allcwait nextarc cachedarcs seeds
10296
10297    #puts "dropping cache ($err)"
10298    foreach v {arcnos arcout arcids arcstart arcend growing \
10299                   arctags archeads allparents allchildren} {
10300        global $v
10301        catch {unset $v}
10302    }
10303    set allcwait 0
10304    set nextarc 0
10305    set cachedarcs 0
10306    set seeds {}
10307    getallcommits
10308}
10309
10310proc writecache {f} {
10311    global cachearc cachedarcs allccache
10312    global arcstart arcend arcnos arcids arcout
10313
10314    set a $cachearc
10315    set lim $cachedarcs
10316    if {$lim - $a > 1000} {
10317        set lim [expr {$a + 1000}]
10318    }
10319    if {[catch {
10320        while {[incr a] <= $lim} {
10321            if {[info exists arcend($a)]} {
10322                puts $f [list $arcstart($a) $arcend($a) $arcids($a)]
10323            } else {
10324                puts $f [list $arcstart($a) {} $arcids($a)]
10325            }
10326        }
10327    } err]} {
10328        catch {close $f}
10329        catch {file delete $allccache}
10330        #puts "writing cache failed ($err)"
10331        return 0
10332    }
10333    set cachearc [expr {$a - 1}]
10334    if {$a > $cachedarcs} {
10335        puts $f "1"
10336        close $f
10337        return 0
10338    }
10339    return 1
10340}
10341
10342proc savecache {} {
10343    global nextarc cachedarcs cachearc allccache
10344
10345    if {$nextarc == $cachedarcs} return
10346    set cachearc 0
10347    set cachedarcs $nextarc
10348    catch {
10349        set f [open $allccache w]
10350        puts $f [list 1 $cachedarcs]
10351        run writecache $f
10352    }
10353}
10354
10355# Returns 1 if a is an ancestor of b, -1 if b is an ancestor of a,
10356# or 0 if neither is true.
10357proc anc_or_desc {a b} {
10358    global arcout arcstart arcend arcnos cached_isanc
10359
10360    if {$arcnos($a) eq $arcnos($b)} {
10361        # Both are on the same arc(s); either both are the same BMP,
10362        # or if one is not a BMP, the other is also not a BMP or is
10363        # the BMP at end of the arc (and it only has 1 incoming arc).
10364        # Or both can be BMPs with no incoming arcs.
10365        if {$a eq $b || $arcnos($a) eq {}} {
10366            return 0
10367        }
10368        # assert {[llength $arcnos($a)] == 1}
10369        set arc [lindex $arcnos($a) 0]
10370        set i [lsearch -exact $arcids($arc) $a]
10371        set j [lsearch -exact $arcids($arc) $b]
10372        if {$i < 0 || $i > $j} {
10373            return 1
10374        } else {
10375            return -1
10376        }
10377    }
10378
10379    if {![info exists arcout($a)]} {
10380        set arc [lindex $arcnos($a) 0]
10381        if {[info exists arcend($arc)]} {
10382            set aend $arcend($arc)
10383        } else {
10384            set aend {}
10385        }
10386        set a $arcstart($arc)
10387    } else {
10388        set aend $a
10389    }
10390    if {![info exists arcout($b)]} {
10391        set arc [lindex $arcnos($b) 0]
10392        if {[info exists arcend($arc)]} {
10393            set bend $arcend($arc)
10394        } else {
10395            set bend {}
10396        }
10397        set b $arcstart($arc)
10398    } else {
10399        set bend $b
10400    }
10401    if {$a eq $bend} {
10402        return 1
10403    }
10404    if {$b eq $aend} {
10405        return -1
10406    }
10407    if {[info exists cached_isanc($a,$bend)]} {
10408        if {$cached_isanc($a,$bend)} {
10409            return 1
10410        }
10411    }
10412    if {[info exists cached_isanc($b,$aend)]} {
10413        if {$cached_isanc($b,$aend)} {
10414            return -1
10415        }
10416        if {[info exists cached_isanc($a,$bend)]} {
10417            return 0
10418        }
10419    }
10420
10421    set todo [list $a $b]
10422    set anc($a) a
10423    set anc($b) b
10424    for {set i 0} {$i < [llength $todo]} {incr i} {
10425        set x [lindex $todo $i]
10426        if {$anc($x) eq {}} {
10427            continue
10428        }
10429        foreach arc $arcnos($x) {
10430            set xd $arcstart($arc)
10431            if {$xd eq $bend} {
10432                set cached_isanc($a,$bend) 1
10433                set cached_isanc($b,$aend) 0
10434                return 1
10435            } elseif {$xd eq $aend} {
10436                set cached_isanc($b,$aend) 1
10437                set cached_isanc($a,$bend) 0
10438                return -1
10439            }
10440            if {![info exists anc($xd)]} {
10441                set anc($xd) $anc($x)
10442                lappend todo $xd
10443            } elseif {$anc($xd) ne $anc($x)} {
10444                set anc($xd) {}
10445            }
10446        }
10447    }
10448    set cached_isanc($a,$bend) 0
10449    set cached_isanc($b,$aend) 0
10450    return 0
10451}
10452
10453# This identifies whether $desc has an ancestor that is
10454# a growing tip of the graph and which is not an ancestor of $anc
10455# and returns 0 if so and 1 if not.
10456# If we subsequently discover a tag on such a growing tip, and that
10457# turns out to be a descendent of $anc (which it could, since we
10458# don't necessarily see children before parents), then $desc
10459# isn't a good choice to display as a descendent tag of
10460# $anc (since it is the descendent of another tag which is
10461# a descendent of $anc).  Similarly, $anc isn't a good choice to
10462# display as a ancestor tag of $desc.
10463#
10464proc is_certain {desc anc} {
10465    global arcnos arcout arcstart arcend growing problems
10466
10467    set certain {}
10468    if {[llength $arcnos($anc)] == 1} {
10469        # tags on the same arc are certain
10470        if {$arcnos($desc) eq $arcnos($anc)} {
10471            return 1
10472        }
10473        if {![info exists arcout($anc)]} {
10474            # if $anc is partway along an arc, use the start of the arc instead
10475            set a [lindex $arcnos($anc) 0]
10476            set anc $arcstart($a)
10477        }
10478    }
10479    if {[llength $arcnos($desc)] > 1 || [info exists arcout($desc)]} {
10480        set x $desc
10481    } else {
10482        set a [lindex $arcnos($desc) 0]
10483        set x $arcend($a)
10484    }
10485    if {$x == $anc} {
10486        return 1
10487    }
10488    set anclist [list $x]
10489    set dl($x) 1
10490    set nnh 1
10491    set ngrowanc 0
10492    for {set i 0} {$i < [llength $anclist] && ($nnh > 0 || $ngrowanc > 0)} {incr i} {
10493        set x [lindex $anclist $i]
10494        if {$dl($x)} {
10495            incr nnh -1
10496        }
10497        set done($x) 1
10498        foreach a $arcout($x) {
10499            if {[info exists growing($a)]} {
10500                if {![info exists growanc($x)] && $dl($x)} {
10501                    set growanc($x) 1
10502                    incr ngrowanc
10503                }
10504            } else {
10505                set y $arcend($a)
10506                if {[info exists dl($y)]} {
10507                    if {$dl($y)} {
10508                        if {!$dl($x)} {
10509                            set dl($y) 0
10510                            if {![info exists done($y)]} {
10511                                incr nnh -1
10512                            }
10513                            if {[info exists growanc($x)]} {
10514                                incr ngrowanc -1
10515                            }
10516                            set xl [list $y]
10517                            for {set k 0} {$k < [llength $xl]} {incr k} {
10518                                set z [lindex $xl $k]
10519                                foreach c $arcout($z) {
10520                                    if {[info exists arcend($c)]} {
10521                                        set v $arcend($c)
10522                                        if {[info exists dl($v)] && $dl($v)} {
10523                                            set dl($v) 0
10524                                            if {![info exists done($v)]} {
10525                                                incr nnh -1
10526                                            }
10527                                            if {[info exists growanc($v)]} {
10528                                                incr ngrowanc -1
10529                                            }
10530                                            lappend xl $v
10531                                        }
10532                                    }
10533                                }
10534                            }
10535                        }
10536                    }
10537                } elseif {$y eq $anc || !$dl($x)} {
10538                    set dl($y) 0
10539                    lappend anclist $y
10540                } else {
10541                    set dl($y) 1
10542                    lappend anclist $y
10543                    incr nnh
10544                }
10545            }
10546        }
10547    }
10548    foreach x [array names growanc] {
10549        if {$dl($x)} {
10550            return 0
10551        }
10552        return 0
10553    }
10554    return 1
10555}
10556
10557proc validate_arctags {a} {
10558    global arctags idtags
10559
10560    set i -1
10561    set na $arctags($a)
10562    foreach id $arctags($a) {
10563        incr i
10564        if {![info exists idtags($id)]} {
10565            set na [lreplace $na $i $i]
10566            incr i -1
10567        }
10568    }
10569    set arctags($a) $na
10570}
10571
10572proc validate_archeads {a} {
10573    global archeads idheads
10574
10575    set i -1
10576    set na $archeads($a)
10577    foreach id $archeads($a) {
10578        incr i
10579        if {![info exists idheads($id)]} {
10580            set na [lreplace $na $i $i]
10581            incr i -1
10582        }
10583    }
10584    set archeads($a) $na
10585}
10586
10587# Return the list of IDs that have tags that are descendents of id,
10588# ignoring IDs that are descendents of IDs already reported.
10589proc desctags {id} {
10590    global arcnos arcstart arcids arctags idtags allparents
10591    global growing cached_dtags
10592
10593    if {![info exists allparents($id)]} {
10594        return {}
10595    }
10596    set t1 [clock clicks -milliseconds]
10597    set argid $id
10598    if {[llength $arcnos($id)] == 1 && [llength $allparents($id)] == 1} {
10599        # part-way along an arc; check that arc first
10600        set a [lindex $arcnos($id) 0]
10601        if {$arctags($a) ne {}} {
10602            validate_arctags $a
10603            set i [lsearch -exact $arcids($a) $id]
10604            set tid {}
10605            foreach t $arctags($a) {
10606                set j [lsearch -exact $arcids($a) $t]
10607                if {$j >= $i} break
10608                set tid $t
10609            }
10610            if {$tid ne {}} {
10611                return $tid
10612            }
10613        }
10614        set id $arcstart($a)
10615        if {[info exists idtags($id)]} {
10616            return $id
10617        }
10618    }
10619    if {[info exists cached_dtags($id)]} {
10620        return $cached_dtags($id)
10621    }
10622
10623    set origid $id
10624    set todo [list $id]
10625    set queued($id) 1
10626    set nc 1
10627    for {set i 0} {$i < [llength $todo] && $nc > 0} {incr i} {
10628        set id [lindex $todo $i]
10629        set done($id) 1
10630        set ta [info exists hastaggedancestor($id)]
10631        if {!$ta} {
10632            incr nc -1
10633        }
10634        # ignore tags on starting node
10635        if {!$ta && $i > 0} {
10636            if {[info exists idtags($id)]} {
10637                set tagloc($id) $id
10638                set ta 1
10639            } elseif {[info exists cached_dtags($id)]} {
10640                set tagloc($id) $cached_dtags($id)
10641                set ta 1
10642            }
10643        }
10644        foreach a $arcnos($id) {
10645            set d $arcstart($a)
10646            if {!$ta && $arctags($a) ne {}} {
10647                validate_arctags $a
10648                if {$arctags($a) ne {}} {
10649                    lappend tagloc($id) [lindex $arctags($a) end]
10650                }
10651            }
10652            if {$ta || $arctags($a) ne {}} {
10653                set tomark [list $d]
10654                for {set j 0} {$j < [llength $tomark]} {incr j} {
10655                    set dd [lindex $tomark $j]
10656                    if {![info exists hastaggedancestor($dd)]} {
10657                        if {[info exists done($dd)]} {
10658                            foreach b $arcnos($dd) {
10659                                lappend tomark $arcstart($b)
10660                            }
10661                            if {[info exists tagloc($dd)]} {
10662                                unset tagloc($dd)
10663                            }
10664                        } elseif {[info exists queued($dd)]} {
10665                            incr nc -1
10666                        }
10667                        set hastaggedancestor($dd) 1
10668                    }
10669                }
10670            }
10671            if {![info exists queued($d)]} {
10672                lappend todo $d
10673                set queued($d) 1
10674                if {![info exists hastaggedancestor($d)]} {
10675                    incr nc
10676                }
10677            }
10678        }
10679    }
10680    set tags {}
10681    foreach id [array names tagloc] {
10682        if {![info exists hastaggedancestor($id)]} {
10683            foreach t $tagloc($id) {
10684                if {[lsearch -exact $tags $t] < 0} {
10685                    lappend tags $t
10686                }
10687            }
10688        }
10689    }
10690    set t2 [clock clicks -milliseconds]
10691    set loopix $i
10692
10693    # remove tags that are descendents of other tags
10694    for {set i 0} {$i < [llength $tags]} {incr i} {
10695        set a [lindex $tags $i]
10696        for {set j 0} {$j < $i} {incr j} {
10697            set b [lindex $tags $j]
10698            set r [anc_or_desc $a $b]
10699            if {$r == 1} {
10700                set tags [lreplace $tags $j $j]
10701                incr j -1
10702                incr i -1
10703            } elseif {$r == -1} {
10704                set tags [lreplace $tags $i $i]
10705                incr i -1
10706                break
10707            }
10708        }
10709    }
10710
10711    if {[array names growing] ne {}} {
10712        # graph isn't finished, need to check if any tag could get
10713        # eclipsed by another tag coming later.  Simply ignore any
10714        # tags that could later get eclipsed.
10715        set ctags {}
10716        foreach t $tags {
10717            if {[is_certain $t $origid]} {
10718                lappend ctags $t
10719            }
10720        }
10721        if {$tags eq $ctags} {
10722            set cached_dtags($origid) $tags
10723        } else {
10724            set tags $ctags
10725        }
10726    } else {
10727        set cached_dtags($origid) $tags
10728    }
10729    set t3 [clock clicks -milliseconds]
10730    if {0 && $t3 - $t1 >= 100} {
10731        puts "iterating descendents ($loopix/[llength $todo] nodes) took\
10732            [expr {$t2-$t1}]+[expr {$t3-$t2}]ms, $nc candidates left"
10733    }
10734    return $tags
10735}
10736
10737proc anctags {id} {
10738    global arcnos arcids arcout arcend arctags idtags allparents
10739    global growing cached_atags
10740
10741    if {![info exists allparents($id)]} {
10742        return {}
10743    }
10744    set t1 [clock clicks -milliseconds]
10745    set argid $id
10746    if {[llength $arcnos($id)] == 1 && [llength $allparents($id)] == 1} {
10747        # part-way along an arc; check that arc first
10748        set a [lindex $arcnos($id) 0]
10749        if {$arctags($a) ne {}} {
10750            validate_arctags $a
10751            set i [lsearch -exact $arcids($a) $id]
10752            foreach t $arctags($a) {
10753                set j [lsearch -exact $arcids($a) $t]
10754                if {$j > $i} {
10755                    return $t
10756                }
10757            }
10758        }
10759        if {![info exists arcend($a)]} {
10760            return {}
10761        }
10762        set id $arcend($a)
10763        if {[info exists idtags($id)]} {
10764            return $id
10765        }
10766    }
10767    if {[info exists cached_atags($id)]} {
10768        return $cached_atags($id)
10769    }
10770
10771    set origid $id
10772    set todo [list $id]
10773    set queued($id) 1
10774    set taglist {}
10775    set nc 1
10776    for {set i 0} {$i < [llength $todo] && $nc > 0} {incr i} {
10777        set id [lindex $todo $i]
10778        set done($id) 1
10779        set td [info exists hastaggeddescendent($id)]
10780        if {!$td} {
10781            incr nc -1
10782        }
10783        # ignore tags on starting node
10784        if {!$td && $i > 0} {
10785            if {[info exists idtags($id)]} {
10786                set tagloc($id) $id
10787                set td 1
10788            } elseif {[info exists cached_atags($id)]} {
10789                set tagloc($id) $cached_atags($id)
10790                set td 1
10791            }
10792        }
10793        foreach a $arcout($id) {
10794            if {!$td && $arctags($a) ne {}} {
10795                validate_arctags $a
10796                if {$arctags($a) ne {}} {
10797                    lappend tagloc($id) [lindex $arctags($a) 0]
10798                }
10799            }
10800            if {![info exists arcend($a)]} continue
10801            set d $arcend($a)
10802            if {$td || $arctags($a) ne {}} {
10803                set tomark [list $d]
10804                for {set j 0} {$j < [llength $tomark]} {incr j} {
10805                    set dd [lindex $tomark $j]
10806                    if {![info exists hastaggeddescendent($dd)]} {
10807                        if {[info exists done($dd)]} {
10808                            foreach b $arcout($dd) {
10809                                if {[info exists arcend($b)]} {
10810                                    lappend tomark $arcend($b)
10811                                }
10812                            }
10813                            if {[info exists tagloc($dd)]} {
10814                                unset tagloc($dd)
10815                            }
10816                        } elseif {[info exists queued($dd)]} {
10817                            incr nc -1
10818                        }
10819                        set hastaggeddescendent($dd) 1
10820                    }
10821                }
10822            }
10823            if {![info exists queued($d)]} {
10824                lappend todo $d
10825                set queued($d) 1
10826                if {![info exists hastaggeddescendent($d)]} {
10827                    incr nc
10828                }
10829            }
10830        }
10831    }
10832    set t2 [clock clicks -milliseconds]
10833    set loopix $i
10834    set tags {}
10835    foreach id [array names tagloc] {
10836        if {![info exists hastaggeddescendent($id)]} {
10837            foreach t $tagloc($id) {
10838                if {[lsearch -exact $tags $t] < 0} {
10839                    lappend tags $t
10840                }
10841            }
10842        }
10843    }
10844
10845    # remove tags that are ancestors of other tags
10846    for {set i 0} {$i < [llength $tags]} {incr i} {
10847        set a [lindex $tags $i]
10848        for {set j 0} {$j < $i} {incr j} {
10849            set b [lindex $tags $j]
10850            set r [anc_or_desc $a $b]
10851            if {$r == -1} {
10852                set tags [lreplace $tags $j $j]
10853                incr j -1
10854                incr i -1
10855            } elseif {$r == 1} {
10856                set tags [lreplace $tags $i $i]
10857                incr i -1
10858                break
10859            }
10860        }
10861    }
10862
10863    if {[array names growing] ne {}} {
10864        # graph isn't finished, need to check if any tag could get
10865        # eclipsed by another tag coming later.  Simply ignore any
10866        # tags that could later get eclipsed.
10867        set ctags {}
10868        foreach t $tags {
10869            if {[is_certain $origid $t]} {
10870                lappend ctags $t
10871            }
10872        }
10873        if {$tags eq $ctags} {
10874            set cached_atags($origid) $tags
10875        } else {
10876            set tags $ctags
10877        }
10878    } else {
10879        set cached_atags($origid) $tags
10880    }
10881    set t3 [clock clicks -milliseconds]
10882    if {0 && $t3 - $t1 >= 100} {
10883        puts "iterating ancestors ($loopix/[llength $todo] nodes) took\
10884            [expr {$t2-$t1}]+[expr {$t3-$t2}]ms, $nc candidates left"
10885    }
10886    return $tags
10887}
10888
10889# Return the list of IDs that have heads that are descendents of id,
10890# including id itself if it has a head.
10891proc descheads {id} {
10892    global arcnos arcstart arcids archeads idheads cached_dheads
10893    global allparents arcout
10894
10895    if {![info exists allparents($id)]} {
10896        return {}
10897    }
10898    set aret {}
10899    if {![info exists arcout($id)]} {
10900        # part-way along an arc; check it first
10901        set a [lindex $arcnos($id) 0]
10902        if {$archeads($a) ne {}} {
10903            validate_archeads $a
10904            set i [lsearch -exact $arcids($a) $id]
10905            foreach t $archeads($a) {
10906                set j [lsearch -exact $arcids($a) $t]
10907                if {$j > $i} break
10908                lappend aret $t
10909            }
10910        }
10911        set id $arcstart($a)
10912    }
10913    set origid $id
10914    set todo [list $id]
10915    set seen($id) 1
10916    set ret {}
10917    for {set i 0} {$i < [llength $todo]} {incr i} {
10918        set id [lindex $todo $i]
10919        if {[info exists cached_dheads($id)]} {
10920            set ret [concat $ret $cached_dheads($id)]
10921        } else {
10922            if {[info exists idheads($id)]} {
10923                lappend ret $id
10924            }
10925            foreach a $arcnos($id) {
10926                if {$archeads($a) ne {}} {
10927                    validate_archeads $a
10928                    if {$archeads($a) ne {}} {
10929                        set ret [concat $ret $archeads($a)]
10930                    }
10931                }
10932                set d $arcstart($a)
10933                if {![info exists seen($d)]} {
10934                    lappend todo $d
10935                    set seen($d) 1
10936                }
10937            }
10938        }
10939    }
10940    set ret [lsort -unique $ret]
10941    set cached_dheads($origid) $ret
10942    return [concat $ret $aret]
10943}
10944
10945proc addedtag {id} {
10946    global arcnos arcout cached_dtags cached_atags
10947
10948    if {![info exists arcnos($id)]} return
10949    if {![info exists arcout($id)]} {
10950        recalcarc [lindex $arcnos($id) 0]
10951    }
10952    catch {unset cached_dtags}
10953    catch {unset cached_atags}
10954}
10955
10956proc addedhead {hid head} {
10957    global arcnos arcout cached_dheads
10958
10959    if {![info exists arcnos($hid)]} return
10960    if {![info exists arcout($hid)]} {
10961        recalcarc [lindex $arcnos($hid) 0]
10962    }
10963    catch {unset cached_dheads}
10964}
10965
10966proc removedhead {hid head} {
10967    global cached_dheads
10968
10969    catch {unset cached_dheads}
10970}
10971
10972proc movedhead {hid head} {
10973    global arcnos arcout cached_dheads
10974
10975    if {![info exists arcnos($hid)]} return
10976    if {![info exists arcout($hid)]} {
10977        recalcarc [lindex $arcnos($hid) 0]
10978    }
10979    catch {unset cached_dheads}
10980}
10981
10982proc changedrefs {} {
10983    global cached_dheads cached_dtags cached_atags cached_tagcontent
10984    global arctags archeads arcnos arcout idheads idtags
10985
10986    foreach id [concat [array names idheads] [array names idtags]] {
10987        if {[info exists arcnos($id)] && ![info exists arcout($id)]} {
10988            set a [lindex $arcnos($id) 0]
10989            if {![info exists donearc($a)]} {
10990                recalcarc $a
10991                set donearc($a) 1
10992            }
10993        }
10994    }
10995    catch {unset cached_tagcontent}
10996    catch {unset cached_dtags}
10997    catch {unset cached_atags}
10998    catch {unset cached_dheads}
10999}
11000
11001proc rereadrefs {} {
11002    global idtags idheads idotherrefs mainheadid
11003
11004    set refids [concat [array names idtags] \
11005                    [array names idheads] [array names idotherrefs]]
11006    foreach id $refids {
11007        if {![info exists ref($id)]} {
11008            set ref($id) [listrefs $id]
11009        }
11010    }
11011    set oldmainhead $mainheadid
11012    readrefs
11013    changedrefs
11014    set refids [lsort -unique [concat $refids [array names idtags] \
11015                        [array names idheads] [array names idotherrefs]]]
11016    foreach id $refids {
11017        set v [listrefs $id]
11018        if {![info exists ref($id)] || $ref($id) != $v} {
11019            redrawtags $id
11020        }
11021    }
11022    if {$oldmainhead ne $mainheadid} {
11023        redrawtags $oldmainhead
11024        redrawtags $mainheadid
11025    }
11026    run refill_reflist
11027}
11028
11029proc listrefs {id} {
11030    global idtags idheads idotherrefs
11031
11032    set x {}
11033    if {[info exists idtags($id)]} {
11034        set x $idtags($id)
11035    }
11036    set y {}
11037    if {[info exists idheads($id)]} {
11038        set y $idheads($id)
11039    }
11040    set z {}
11041    if {[info exists idotherrefs($id)]} {
11042        set z $idotherrefs($id)
11043    }
11044    return [list $x $y $z]
11045}
11046
11047proc add_tag_ctext {tag} {
11048    global ctext cached_tagcontent tagids
11049
11050    if {![info exists cached_tagcontent($tag)]} {
11051        catch {
11052            set cached_tagcontent($tag) [exec git cat-file -p $tag]
11053        }
11054    }
11055    $ctext insert end "[mc "Tag"]: $tag\n" bold
11056    if {[info exists cached_tagcontent($tag)]} {
11057        set text $cached_tagcontent($tag)
11058    } else {
11059        set text "[mc "Id"]:  $tagids($tag)"
11060    }
11061    appendwithlinks $text {}
11062}
11063
11064proc showtag {tag isnew} {
11065    global ctext cached_tagcontent tagids linknum tagobjid
11066
11067    if {$isnew} {
11068        addtohistory [list showtag $tag 0] savectextpos
11069    }
11070    $ctext conf -state normal
11071    clear_ctext
11072    settabs 0
11073    set linknum 0
11074    add_tag_ctext $tag
11075    maybe_scroll_ctext 1
11076    $ctext conf -state disabled
11077    init_flist {}
11078}
11079
11080proc showtags {id isnew} {
11081    global idtags ctext linknum
11082
11083    if {$isnew} {
11084        addtohistory [list showtags $id 0] savectextpos
11085    }
11086    $ctext conf -state normal
11087    clear_ctext
11088    settabs 0
11089    set linknum 0
11090    set sep {}
11091    foreach tag $idtags($id) {
11092        $ctext insert end $sep
11093        add_tag_ctext $tag
11094        set sep "\n\n"
11095    }
11096    maybe_scroll_ctext 1
11097    $ctext conf -state disabled
11098    init_flist {}
11099}
11100
11101proc doquit {} {
11102    global stopped
11103    global gitktmpdir
11104
11105    set stopped 100
11106    savestuff .
11107    destroy .
11108
11109    if {[info exists gitktmpdir]} {
11110        catch {file delete -force $gitktmpdir}
11111    }
11112}
11113
11114proc mkfontdisp {font top which} {
11115    global fontattr fontpref $font NS use_ttk
11116
11117    set fontpref($font) [set $font]
11118    ${NS}::button $top.${font}but -text $which \
11119        -command [list choosefont $font $which]
11120    ${NS}::label $top.$font -relief flat -font $font \
11121        -text $fontattr($font,family) -justify left
11122    grid x $top.${font}but $top.$font -sticky w
11123}
11124
11125proc choosefont {font which} {
11126    global fontparam fontlist fonttop fontattr
11127    global prefstop NS
11128
11129    set fontparam(which) $which
11130    set fontparam(font) $font
11131    set fontparam(family) [font actual $font -family]
11132    set fontparam(size) $fontattr($font,size)
11133    set fontparam(weight) $fontattr($font,weight)
11134    set fontparam(slant) $fontattr($font,slant)
11135    set top .gitkfont
11136    set fonttop $top
11137    if {![winfo exists $top]} {
11138        font create sample
11139        eval font config sample [font actual $font]
11140        ttk_toplevel $top
11141        make_transient $top $prefstop
11142        wm title $top [mc "Gitk font chooser"]
11143        ${NS}::label $top.l -textvariable fontparam(which)
11144        pack $top.l -side top
11145        set fontlist [lsort [font families]]
11146        ${NS}::frame $top.f
11147        listbox $top.f.fam -listvariable fontlist \
11148            -yscrollcommand [list $top.f.sb set]
11149        bind $top.f.fam <<ListboxSelect>> selfontfam
11150        ${NS}::scrollbar $top.f.sb -command [list $top.f.fam yview]
11151        pack $top.f.sb -side right -fill y
11152        pack $top.f.fam -side left -fill both -expand 1
11153        pack $top.f -side top -fill both -expand 1
11154        ${NS}::frame $top.g
11155        spinbox $top.g.size -from 4 -to 40 -width 4 \
11156            -textvariable fontparam(size) \
11157            -validatecommand {string is integer -strict %s}
11158        checkbutton $top.g.bold -padx 5 \
11159            -font {{Times New Roman} 12 bold} -text [mc "B"] -indicatoron 0 \
11160            -variable fontparam(weight) -onvalue bold -offvalue normal
11161        checkbutton $top.g.ital -padx 5 \
11162            -font {{Times New Roman} 12 italic} -text [mc "I"] -indicatoron 0  \
11163            -variable fontparam(slant) -onvalue italic -offvalue roman
11164        pack $top.g.size $top.g.bold $top.g.ital -side left
11165        pack $top.g -side top
11166        canvas $top.c -width 150 -height 50 -border 2 -relief sunk \
11167            -background white
11168        $top.c create text 100 25 -anchor center -text $which -font sample \
11169            -fill black -tags text
11170        bind $top.c <Configure> [list centertext $top.c]
11171        pack $top.c -side top -fill x
11172        ${NS}::frame $top.buts
11173        ${NS}::button $top.buts.ok -text [mc "OK"] -command fontok -default active
11174        ${NS}::button $top.buts.can -text [mc "Cancel"] -command fontcan -default normal
11175        bind $top <Key-Return> fontok
11176        bind $top <Key-Escape> fontcan
11177        grid $top.buts.ok $top.buts.can
11178        grid columnconfigure $top.buts 0 -weight 1 -uniform a
11179        grid columnconfigure $top.buts 1 -weight 1 -uniform a
11180        pack $top.buts -side bottom -fill x
11181        trace add variable fontparam write chg_fontparam
11182    } else {
11183        raise $top
11184        $top.c itemconf text -text $which
11185    }
11186    set i [lsearch -exact $fontlist $fontparam(family)]
11187    if {$i >= 0} {
11188        $top.f.fam selection set $i
11189        $top.f.fam see $i
11190    }
11191}
11192
11193proc centertext {w} {
11194    $w coords text [expr {[winfo width $w] / 2}] [expr {[winfo height $w] / 2}]
11195}
11196
11197proc fontok {} {
11198    global fontparam fontpref prefstop
11199
11200    set f $fontparam(font)
11201    set fontpref($f) [list $fontparam(family) $fontparam(size)]
11202    if {$fontparam(weight) eq "bold"} {
11203        lappend fontpref($f) "bold"
11204    }
11205    if {$fontparam(slant) eq "italic"} {
11206        lappend fontpref($f) "italic"
11207    }
11208    set w $prefstop.notebook.fonts.$f
11209    $w conf -text $fontparam(family) -font $fontpref($f)
11210
11211    fontcan
11212}
11213
11214proc fontcan {} {
11215    global fonttop fontparam
11216
11217    if {[info exists fonttop]} {
11218        catch {destroy $fonttop}
11219        catch {font delete sample}
11220        unset fonttop
11221        unset fontparam
11222    }
11223}
11224
11225if {[package vsatisfies [package provide Tk] 8.6]} {
11226    # In Tk 8.6 we have a native font chooser dialog. Overwrite the above
11227    # function to make use of it.
11228    proc choosefont {font which} {
11229        tk fontchooser configure -title $which -font $font \
11230            -command [list on_choosefont $font $which]
11231        tk fontchooser show
11232    }
11233    proc on_choosefont {font which newfont} {
11234        global fontparam
11235        puts stderr "$font $newfont"
11236        array set f [font actual $newfont]
11237        set fontparam(which) $which
11238        set fontparam(font) $font
11239        set fontparam(family) $f(-family)
11240        set fontparam(size) $f(-size)
11241        set fontparam(weight) $f(-weight)
11242        set fontparam(slant) $f(-slant)
11243        fontok
11244    }
11245}
11246
11247proc selfontfam {} {
11248    global fonttop fontparam
11249
11250    set i [$fonttop.f.fam curselection]
11251    if {$i ne {}} {
11252        set fontparam(family) [$fonttop.f.fam get $i]
11253    }
11254}
11255
11256proc chg_fontparam {v sub op} {
11257    global fontparam
11258
11259    font config sample -$sub $fontparam($sub)
11260}
11261
11262# Create a property sheet tab page
11263proc create_prefs_page {w} {
11264    global NS
11265    set parent [join [lrange [split $w .] 0 end-1] .]
11266    if {[winfo class $parent] eq "TNotebook"} {
11267        ${NS}::frame $w
11268    } else {
11269        ${NS}::labelframe $w
11270    }
11271}
11272
11273proc prefspage_general {notebook} {
11274    global NS maxwidth maxgraphpct showneartags showlocalchanges
11275    global tabstop limitdiffs autoselect autosellen extdifftool perfile_attrs
11276    global hideremotes want_ttk have_ttk maxrefs
11277
11278    set page [create_prefs_page $notebook.general]
11279
11280    ${NS}::label $page.ldisp -text [mc "Commit list display options"]
11281    grid $page.ldisp - -sticky w -pady 10
11282    ${NS}::label $page.spacer -text " "
11283    ${NS}::label $page.maxwidthl -text [mc "Maximum graph width (lines)"]
11284    spinbox $page.maxwidth -from 0 -to 100 -width 4 -textvariable maxwidth
11285    grid $page.spacer $page.maxwidthl $page.maxwidth -sticky w
11286    ${NS}::label $page.maxpctl -text [mc "Maximum graph width (% of pane)"]
11287    spinbox $page.maxpct -from 1 -to 100 -width 4 -textvariable maxgraphpct
11288    grid x $page.maxpctl $page.maxpct -sticky w
11289    ${NS}::checkbutton $page.showlocal -text [mc "Show local changes"] \
11290        -variable showlocalchanges
11291    grid x $page.showlocal -sticky w
11292    ${NS}::checkbutton $page.autoselect -text [mc "Auto-select SHA1 (length)"] \
11293        -variable autoselect
11294    spinbox $page.autosellen -from 1 -to 40 -width 4 -textvariable autosellen
11295    grid x $page.autoselect $page.autosellen -sticky w
11296    ${NS}::checkbutton $page.hideremotes -text [mc "Hide remote refs"] \
11297        -variable hideremotes
11298    grid x $page.hideremotes -sticky w
11299
11300    ${NS}::label $page.ddisp -text [mc "Diff display options"]
11301    grid $page.ddisp - -sticky w -pady 10
11302    ${NS}::label $page.tabstopl -text [mc "Tab spacing"]
11303    spinbox $page.tabstop -from 1 -to 20 -width 4 -textvariable tabstop
11304    grid x $page.tabstopl $page.tabstop -sticky w
11305    ${NS}::checkbutton $page.ntag -text [mc "Display nearby tags/heads"] \
11306        -variable showneartags
11307    grid x $page.ntag -sticky w
11308    ${NS}::label $page.maxrefsl -text [mc "Maximum # tags/heads to show"]
11309    spinbox $page.maxrefs -from 1 -to 1000 -width 4 -textvariable maxrefs
11310    grid x $page.maxrefsl $page.maxrefs -sticky w
11311    ${NS}::checkbutton $page.ldiff -text [mc "Limit diffs to listed paths"] \
11312        -variable limitdiffs
11313    grid x $page.ldiff -sticky w
11314    ${NS}::checkbutton $page.lattr -text [mc "Support per-file encodings"] \
11315        -variable perfile_attrs
11316    grid x $page.lattr -sticky w
11317
11318    ${NS}::entry $page.extdifft -textvariable extdifftool
11319    ${NS}::frame $page.extdifff
11320    ${NS}::label $page.extdifff.l -text [mc "External diff tool" ]
11321    ${NS}::button $page.extdifff.b -text [mc "Choose..."] -command choose_extdiff
11322    pack $page.extdifff.l $page.extdifff.b -side left
11323    pack configure $page.extdifff.l -padx 10
11324    grid x $page.extdifff $page.extdifft -sticky ew
11325
11326    ${NS}::label $page.lgen -text [mc "General options"]
11327    grid $page.lgen - -sticky w -pady 10
11328    ${NS}::checkbutton $page.want_ttk -variable want_ttk \
11329        -text [mc "Use themed widgets"]
11330    if {$have_ttk} {
11331        ${NS}::label $page.ttk_note -text [mc "(change requires restart)"]
11332    } else {
11333        ${NS}::label $page.ttk_note -text [mc "(currently unavailable)"]
11334    }
11335    grid x $page.want_ttk $page.ttk_note -sticky w
11336    return $page
11337}
11338
11339proc prefspage_colors {notebook} {
11340    global NS uicolor bgcolor fgcolor ctext diffcolors selectbgcolor markbgcolor
11341
11342    set page [create_prefs_page $notebook.colors]
11343
11344    ${NS}::label $page.cdisp -text [mc "Colors: press to choose"]
11345    grid $page.cdisp - -sticky w -pady 10
11346    label $page.ui -padx 40 -relief sunk -background $uicolor
11347    ${NS}::button $page.uibut -text [mc "Interface"] \
11348       -command [list choosecolor uicolor {} $page.ui [mc "interface"] setui]
11349    grid x $page.uibut $page.ui -sticky w
11350    label $page.bg -padx 40 -relief sunk -background $bgcolor
11351    ${NS}::button $page.bgbut -text [mc "Background"] \
11352        -command [list choosecolor bgcolor {} $page.bg [mc "background"] setbg]
11353    grid x $page.bgbut $page.bg -sticky w
11354    label $page.fg -padx 40 -relief sunk -background $fgcolor
11355    ${NS}::button $page.fgbut -text [mc "Foreground"] \
11356        -command [list choosecolor fgcolor {} $page.fg [mc "foreground"] setfg]
11357    grid x $page.fgbut $page.fg -sticky w
11358    label $page.diffold -padx 40 -relief sunk -background [lindex $diffcolors 0]
11359    ${NS}::button $page.diffoldbut -text [mc "Diff: old lines"] \
11360        -command [list choosecolor diffcolors 0 $page.diffold [mc "diff old lines"] \
11361                      [list $ctext tag conf d0 -foreground]]
11362    grid x $page.diffoldbut $page.diffold -sticky w
11363    label $page.diffnew -padx 40 -relief sunk -background [lindex $diffcolors 1]
11364    ${NS}::button $page.diffnewbut -text [mc "Diff: new lines"] \
11365        -command [list choosecolor diffcolors 1 $page.diffnew [mc "diff new lines"] \
11366                      [list $ctext tag conf dresult -foreground]]
11367    grid x $page.diffnewbut $page.diffnew -sticky w
11368    label $page.hunksep -padx 40 -relief sunk -background [lindex $diffcolors 2]
11369    ${NS}::button $page.hunksepbut -text [mc "Diff: hunk header"] \
11370        -command [list choosecolor diffcolors 2 $page.hunksep \
11371                      [mc "diff hunk header"] \
11372                      [list $ctext tag conf hunksep -foreground]]
11373    grid x $page.hunksepbut $page.hunksep -sticky w
11374    label $page.markbgsep -padx 40 -relief sunk -background $markbgcolor
11375    ${NS}::button $page.markbgbut -text [mc "Marked line bg"] \
11376        -command [list choosecolor markbgcolor {} $page.markbgsep \
11377                      [mc "marked line background"] \
11378                      [list $ctext tag conf omark -background]]
11379    grid x $page.markbgbut $page.markbgsep -sticky w
11380    label $page.selbgsep -padx 40 -relief sunk -background $selectbgcolor
11381    ${NS}::button $page.selbgbut -text [mc "Select bg"] \
11382        -command [list choosecolor selectbgcolor {} $page.selbgsep [mc "background"] setselbg]
11383    grid x $page.selbgbut $page.selbgsep -sticky w
11384    return $page
11385}
11386
11387proc prefspage_fonts {notebook} {
11388    global NS
11389    set page [create_prefs_page $notebook.fonts]
11390    ${NS}::label $page.cfont -text [mc "Fonts: press to choose"]
11391    grid $page.cfont - -sticky w -pady 10
11392    mkfontdisp mainfont $page [mc "Main font"]
11393    mkfontdisp textfont $page [mc "Diff display font"]
11394    mkfontdisp uifont $page [mc "User interface font"]
11395    return $page
11396}
11397
11398proc doprefs {} {
11399    global maxwidth maxgraphpct use_ttk NS
11400    global oldprefs prefstop showneartags showlocalchanges
11401    global uicolor bgcolor fgcolor ctext diffcolors selectbgcolor markbgcolor
11402    global tabstop limitdiffs autoselect autosellen extdifftool perfile_attrs
11403    global hideremotes want_ttk have_ttk
11404
11405    set top .gitkprefs
11406    set prefstop $top
11407    if {[winfo exists $top]} {
11408        raise $top
11409        return
11410    }
11411    foreach v {maxwidth maxgraphpct showneartags showlocalchanges \
11412                   limitdiffs tabstop perfile_attrs hideremotes want_ttk} {
11413        set oldprefs($v) [set $v]
11414    }
11415    ttk_toplevel $top
11416    wm title $top [mc "Gitk preferences"]
11417    make_transient $top .
11418
11419    if {[set use_notebook [expr {$use_ttk && [info command ::ttk::notebook] ne ""}]]} {
11420        set notebook [ttk::notebook $top.notebook]
11421    } else {
11422        set notebook [${NS}::frame $top.notebook -borderwidth 0 -relief flat]
11423    }
11424
11425    lappend pages [prefspage_general $notebook] [mc "General"]
11426    lappend pages [prefspage_colors $notebook] [mc "Colors"]
11427    lappend pages [prefspage_fonts $notebook] [mc "Fonts"]
11428    set col 0
11429    foreach {page title} $pages {
11430        if {$use_notebook} {
11431            $notebook add $page -text $title
11432        } else {
11433            set btn [${NS}::button $notebook.b_[string map {. X} $page] \
11434                         -text $title -command [list raise $page]]
11435            $page configure -text $title
11436            grid $btn -row 0 -column [incr col] -sticky w
11437            grid $page -row 1 -column 0 -sticky news -columnspan 100
11438        }
11439    }
11440
11441    if {!$use_notebook} {
11442        grid columnconfigure $notebook 0 -weight 1
11443        grid rowconfigure $notebook 1 -weight 1
11444        raise [lindex $pages 0]
11445    }
11446
11447    grid $notebook -sticky news -padx 2 -pady 2
11448    grid rowconfigure $top 0 -weight 1
11449    grid columnconfigure $top 0 -weight 1
11450
11451    ${NS}::frame $top.buts
11452    ${NS}::button $top.buts.ok -text [mc "OK"] -command prefsok -default active
11453    ${NS}::button $top.buts.can -text [mc "Cancel"] -command prefscan -default normal
11454    bind $top <Key-Return> prefsok
11455    bind $top <Key-Escape> prefscan
11456    grid $top.buts.ok $top.buts.can
11457    grid columnconfigure $top.buts 0 -weight 1 -uniform a
11458    grid columnconfigure $top.buts 1 -weight 1 -uniform a
11459    grid $top.buts - - -pady 10 -sticky ew
11460    grid columnconfigure $top 2 -weight 1
11461    bind $top <Visibility> [list focus $top.buts.ok]
11462}
11463
11464proc choose_extdiff {} {
11465    global extdifftool
11466
11467    set prog [tk_getOpenFile -title [mc "External diff tool"] -multiple false]
11468    if {$prog ne {}} {
11469        set extdifftool $prog
11470    }
11471}
11472
11473proc choosecolor {v vi w x cmd} {
11474    global $v
11475
11476    set c [tk_chooseColor -initialcolor [lindex [set $v] $vi] \
11477               -title [mc "Gitk: choose color for %s" $x]]
11478    if {$c eq {}} return
11479    $w conf -background $c
11480    lset $v $vi $c
11481    eval $cmd $c
11482}
11483
11484proc setselbg {c} {
11485    global bglist cflist
11486    foreach w $bglist {
11487        $w configure -selectbackground $c
11488    }
11489    $cflist tag configure highlight \
11490        -background [$cflist cget -selectbackground]
11491    allcanvs itemconf secsel -fill $c
11492}
11493
11494# This sets the background color and the color scheme for the whole UI.
11495# For some reason, tk_setPalette chooses a nasty dark red for selectColor
11496# if we don't specify one ourselves, which makes the checkbuttons and
11497# radiobuttons look bad.  This chooses white for selectColor if the
11498# background color is light, or black if it is dark.
11499proc setui {c} {
11500    if {[tk windowingsystem] eq "win32"} { return }
11501    set bg [winfo rgb . $c]
11502    set selc black
11503    if {[lindex $bg 0] + 1.5 * [lindex $bg 1] + 0.5 * [lindex $bg 2] > 100000} {
11504        set selc white
11505    }
11506    tk_setPalette background $c selectColor $selc
11507}
11508
11509proc setbg {c} {
11510    global bglist
11511
11512    foreach w $bglist {
11513        $w conf -background $c
11514    }
11515}
11516
11517proc setfg {c} {
11518    global fglist canv
11519
11520    foreach w $fglist {
11521        $w conf -foreground $c
11522    }
11523    allcanvs itemconf text -fill $c
11524    $canv itemconf circle -outline $c
11525    $canv itemconf markid -outline $c
11526}
11527
11528proc prefscan {} {
11529    global oldprefs prefstop
11530
11531    foreach v {maxwidth maxgraphpct showneartags showlocalchanges \
11532                   limitdiffs tabstop perfile_attrs hideremotes want_ttk} {
11533        global $v
11534        set $v $oldprefs($v)
11535    }
11536    catch {destroy $prefstop}
11537    unset prefstop
11538    fontcan
11539}
11540
11541proc prefsok {} {
11542    global maxwidth maxgraphpct
11543    global oldprefs prefstop showneartags showlocalchanges
11544    global fontpref mainfont textfont uifont
11545    global limitdiffs treediffs perfile_attrs
11546    global hideremotes
11547
11548    catch {destroy $prefstop}
11549    unset prefstop
11550    fontcan
11551    set fontchanged 0
11552    if {$mainfont ne $fontpref(mainfont)} {
11553        set mainfont $fontpref(mainfont)
11554        parsefont mainfont $mainfont
11555        eval font configure mainfont [fontflags mainfont]
11556        eval font configure mainfontbold [fontflags mainfont 1]
11557        setcoords
11558        set fontchanged 1
11559    }
11560    if {$textfont ne $fontpref(textfont)} {
11561        set textfont $fontpref(textfont)
11562        parsefont textfont $textfont
11563        eval font configure textfont [fontflags textfont]
11564        eval font configure textfontbold [fontflags textfont 1]
11565    }
11566    if {$uifont ne $fontpref(uifont)} {
11567        set uifont $fontpref(uifont)
11568        parsefont uifont $uifont
11569        eval font configure uifont [fontflags uifont]
11570    }
11571    settabs
11572    if {$showlocalchanges != $oldprefs(showlocalchanges)} {
11573        if {$showlocalchanges} {
11574            doshowlocalchanges
11575        } else {
11576            dohidelocalchanges
11577        }
11578    }
11579    if {$limitdiffs != $oldprefs(limitdiffs) ||
11580        ($perfile_attrs && !$oldprefs(perfile_attrs))} {
11581        # treediffs elements are limited by path;
11582        # won't have encodings cached if perfile_attrs was just turned on
11583        catch {unset treediffs}
11584    }
11585    if {$fontchanged || $maxwidth != $oldprefs(maxwidth)
11586        || $maxgraphpct != $oldprefs(maxgraphpct)} {
11587        redisplay
11588    } elseif {$showneartags != $oldprefs(showneartags) ||
11589          $limitdiffs != $oldprefs(limitdiffs)} {
11590        reselectline
11591    }
11592    if {$hideremotes != $oldprefs(hideremotes)} {
11593        rereadrefs
11594    }
11595}
11596
11597proc formatdate {d} {
11598    global datetimeformat
11599    if {$d ne {}} {
11600        # If $datetimeformat includes a timezone, display in the
11601        # timezone of the argument.  Otherwise, display in local time.
11602        if {[string match {*%[zZ]*} $datetimeformat]} {
11603            if {[catch {set d [clock format [lindex $d 0] -timezone [lindex $d 1] -format $datetimeformat]}]} {
11604                # Tcl < 8.5 does not support -timezone.  Emulate it by
11605                # setting TZ (e.g. TZ=<-0430>+04:30).
11606                global env
11607                if {[info exists env(TZ)]} {
11608                    set savedTZ $env(TZ)
11609                }
11610                set zone [lindex $d 1]
11611                set sign [string map {+ - - +} [string index $zone 0]]
11612                set env(TZ) <$zone>$sign[string range $zone 1 2]:[string range $zone 3 4]
11613                set d [clock format [lindex $d 0] -format $datetimeformat]
11614                if {[info exists savedTZ]} {
11615                    set env(TZ) $savedTZ
11616                } else {
11617                    unset env(TZ)
11618                }
11619            }
11620        } else {
11621            set d [clock format [lindex $d 0] -format $datetimeformat]
11622        }
11623    }
11624    return $d
11625}
11626
11627# This list of encoding names and aliases is distilled from
11628# http://www.iana.org/assignments/character-sets.
11629# Not all of them are supported by Tcl.
11630set encoding_aliases {
11631    { ANSI_X3.4-1968 iso-ir-6 ANSI_X3.4-1986 ISO_646.irv:1991 ASCII
11632      ISO646-US US-ASCII us IBM367 cp367 csASCII }
11633    { ISO-10646-UTF-1 csISO10646UTF1 }
11634    { ISO_646.basic:1983 ref csISO646basic1983 }
11635    { INVARIANT csINVARIANT }
11636    { ISO_646.irv:1983 iso-ir-2 irv csISO2IntlRefVersion }
11637    { BS_4730 iso-ir-4 ISO646-GB gb uk csISO4UnitedKingdom }
11638    { NATS-SEFI iso-ir-8-1 csNATSSEFI }
11639    { NATS-SEFI-ADD iso-ir-8-2 csNATSSEFIADD }
11640    { NATS-DANO iso-ir-9-1 csNATSDANO }
11641    { NATS-DANO-ADD iso-ir-9-2 csNATSDANOADD }
11642    { SEN_850200_B iso-ir-10 FI ISO646-FI ISO646-SE se csISO10Swedish }
11643    { SEN_850200_C iso-ir-11 ISO646-SE2 se2 csISO11SwedishForNames }
11644    { KS_C_5601-1987 iso-ir-149 KS_C_5601-1989 KSC_5601 korean csKSC56011987 }
11645    { ISO-2022-KR csISO2022KR }
11646    { EUC-KR csEUCKR }
11647    { ISO-2022-JP csISO2022JP }
11648    { ISO-2022-JP-2 csISO2022JP2 }
11649    { JIS_C6220-1969-jp JIS_C6220-1969 iso-ir-13 katakana x0201-7
11650      csISO13JISC6220jp }
11651    { JIS_C6220-1969-ro iso-ir-14 jp ISO646-JP csISO14JISC6220ro }
11652    { IT iso-ir-15 ISO646-IT csISO15Italian }
11653    { PT iso-ir-16 ISO646-PT csISO16Portuguese }
11654    { ES iso-ir-17 ISO646-ES csISO17Spanish }
11655    { greek7-old iso-ir-18 csISO18Greek7Old }
11656    { latin-greek iso-ir-19 csISO19LatinGreek }
11657    { DIN_66003 iso-ir-21 de ISO646-DE csISO21German }
11658    { NF_Z_62-010_(1973) iso-ir-25 ISO646-FR1 csISO25French }
11659    { Latin-greek-1 iso-ir-27 csISO27LatinGreek1 }
11660    { ISO_5427 iso-ir-37 csISO5427Cyrillic }
11661    { JIS_C6226-1978 iso-ir-42 csISO42JISC62261978 }
11662    { BS_viewdata iso-ir-47 csISO47BSViewdata }
11663    { INIS iso-ir-49 csISO49INIS }
11664    { INIS-8 iso-ir-50 csISO50INIS8 }
11665    { INIS-cyrillic iso-ir-51 csISO51INISCyrillic }
11666    { ISO_5427:1981 iso-ir-54 ISO5427Cyrillic1981 }
11667    { ISO_5428:1980 iso-ir-55 csISO5428Greek }
11668    { GB_1988-80 iso-ir-57 cn ISO646-CN csISO57GB1988 }
11669    { GB_2312-80 iso-ir-58 chinese csISO58GB231280 }
11670    { NS_4551-1 iso-ir-60 ISO646-NO no csISO60DanishNorwegian
11671      csISO60Norwegian1 }
11672    { NS_4551-2 ISO646-NO2 iso-ir-61 no2 csISO61Norwegian2 }
11673    { NF_Z_62-010 iso-ir-69 ISO646-FR fr csISO69French }
11674    { videotex-suppl iso-ir-70 csISO70VideotexSupp1 }
11675    { PT2 iso-ir-84 ISO646-PT2 csISO84Portuguese2 }
11676    { ES2 iso-ir-85 ISO646-ES2 csISO85Spanish2 }
11677    { MSZ_7795.3 iso-ir-86 ISO646-HU hu csISO86Hungarian }
11678    { JIS_C6226-1983 iso-ir-87 x0208 JIS_X0208-1983 csISO87JISX0208 }
11679    { greek7 iso-ir-88 csISO88Greek7 }
11680    { ASMO_449 ISO_9036 arabic7 iso-ir-89 csISO89ASMO449 }
11681    { iso-ir-90 csISO90 }
11682    { JIS_C6229-1984-a iso-ir-91 jp-ocr-a csISO91JISC62291984a }
11683    { JIS_C6229-1984-b iso-ir-92 ISO646-JP-OCR-B jp-ocr-b
11684      csISO92JISC62991984b }
11685    { JIS_C6229-1984-b-add iso-ir-93 jp-ocr-b-add csISO93JIS62291984badd }
11686    { JIS_C6229-1984-hand iso-ir-94 jp-ocr-hand csISO94JIS62291984hand }
11687    { JIS_C6229-1984-hand-add iso-ir-95 jp-ocr-hand-add
11688      csISO95JIS62291984handadd }
11689    { JIS_C6229-1984-kana iso-ir-96 csISO96JISC62291984kana }
11690    { ISO_2033-1983 iso-ir-98 e13b csISO2033 }
11691    { ANSI_X3.110-1983 iso-ir-99 CSA_T500-1983 NAPLPS csISO99NAPLPS }
11692    { ISO_8859-1:1987 iso-ir-100 ISO_8859-1 ISO-8859-1 latin1 l1 IBM819
11693      CP819 csISOLatin1 }
11694    { ISO_8859-2:1987 iso-ir-101 ISO_8859-2 ISO-8859-2 latin2 l2 csISOLatin2 }
11695    { T.61-7bit iso-ir-102 csISO102T617bit }
11696    { T.61-8bit T.61 iso-ir-103 csISO103T618bit }
11697    { ISO_8859-3:1988 iso-ir-109 ISO_8859-3 ISO-8859-3 latin3 l3 csISOLatin3 }
11698    { ISO_8859-4:1988 iso-ir-110 ISO_8859-4 ISO-8859-4 latin4 l4 csISOLatin4 }
11699    { ECMA-cyrillic iso-ir-111 KOI8-E csISO111ECMACyrillic }
11700    { CSA_Z243.4-1985-1 iso-ir-121 ISO646-CA csa7-1 ca csISO121Canadian1 }
11701    { CSA_Z243.4-1985-2 iso-ir-122 ISO646-CA2 csa7-2 csISO122Canadian2 }
11702    { CSA_Z243.4-1985-gr iso-ir-123 csISO123CSAZ24341985gr }
11703    { ISO_8859-6:1987 iso-ir-127 ISO_8859-6 ISO-8859-6 ECMA-114 ASMO-708
11704      arabic csISOLatinArabic }
11705    { ISO_8859-6-E csISO88596E ISO-8859-6-E }
11706    { ISO_8859-6-I csISO88596I ISO-8859-6-I }
11707    { ISO_8859-7:1987 iso-ir-126 ISO_8859-7 ISO-8859-7 ELOT_928 ECMA-118
11708      greek greek8 csISOLatinGreek }
11709    { T.101-G2 iso-ir-128 csISO128T101G2 }
11710    { ISO_8859-8:1988 iso-ir-138 ISO_8859-8 ISO-8859-8 hebrew
11711      csISOLatinHebrew }
11712    { ISO_8859-8-E csISO88598E ISO-8859-8-E }
11713    { ISO_8859-8-I csISO88598I ISO-8859-8-I }
11714    { CSN_369103 iso-ir-139 csISO139CSN369103 }
11715    { JUS_I.B1.002 iso-ir-141 ISO646-YU js yu csISO141JUSIB1002 }
11716    { ISO_6937-2-add iso-ir-142 csISOTextComm }
11717    { IEC_P27-1 iso-ir-143 csISO143IECP271 }
11718    { ISO_8859-5:1988 iso-ir-144 ISO_8859-5 ISO-8859-5 cyrillic
11719      csISOLatinCyrillic }
11720    { JUS_I.B1.003-serb iso-ir-146 serbian csISO146Serbian }
11721    { JUS_I.B1.003-mac macedonian iso-ir-147 csISO147Macedonian }
11722    { ISO_8859-9:1989 iso-ir-148 ISO_8859-9 ISO-8859-9 latin5 l5 csISOLatin5 }
11723    { greek-ccitt iso-ir-150 csISO150 csISO150GreekCCITT }
11724    { NC_NC00-10:81 cuba iso-ir-151 ISO646-CU csISO151Cuba }
11725    { ISO_6937-2-25 iso-ir-152 csISO6937Add }
11726    { GOST_19768-74 ST_SEV_358-88 iso-ir-153 csISO153GOST1976874 }
11727    { ISO_8859-supp iso-ir-154 latin1-2-5 csISO8859Supp }
11728    { ISO_10367-box iso-ir-155 csISO10367Box }
11729    { ISO-8859-10 iso-ir-157 l6 ISO_8859-10:1992 csISOLatin6 latin6 }
11730    { latin-lap lap iso-ir-158 csISO158Lap }
11731    { JIS_X0212-1990 x0212 iso-ir-159 csISO159JISX02121990 }
11732    { DS_2089 DS2089 ISO646-DK dk csISO646Danish }
11733    { us-dk csUSDK }
11734    { dk-us csDKUS }
11735    { JIS_X0201 X0201 csHalfWidthKatakana }
11736    { KSC5636 ISO646-KR csKSC5636 }
11737    { ISO-10646-UCS-2 csUnicode }
11738    { ISO-10646-UCS-4 csUCS4 }
11739    { DEC-MCS dec csDECMCS }
11740    { hp-roman8 roman8 r8 csHPRoman8 }
11741    { macintosh mac csMacintosh }
11742    { IBM037 cp037 ebcdic-cp-us ebcdic-cp-ca ebcdic-cp-wt ebcdic-cp-nl
11743      csIBM037 }
11744    { IBM038 EBCDIC-INT cp038 csIBM038 }
11745    { IBM273 CP273 csIBM273 }
11746    { IBM274 EBCDIC-BE CP274 csIBM274 }
11747    { IBM275 EBCDIC-BR cp275 csIBM275 }
11748    { IBM277 EBCDIC-CP-DK EBCDIC-CP-NO csIBM277 }
11749    { IBM278 CP278 ebcdic-cp-fi ebcdic-cp-se csIBM278 }
11750    { IBM280 CP280 ebcdic-cp-it csIBM280 }
11751    { IBM281 EBCDIC-JP-E cp281 csIBM281 }
11752    { IBM284 CP284 ebcdic-cp-es csIBM284 }
11753    { IBM285 CP285 ebcdic-cp-gb csIBM285 }
11754    { IBM290 cp290 EBCDIC-JP-kana csIBM290 }
11755    { IBM297 cp297 ebcdic-cp-fr csIBM297 }
11756    { IBM420 cp420 ebcdic-cp-ar1 csIBM420 }
11757    { IBM423 cp423 ebcdic-cp-gr csIBM423 }
11758    { IBM424 cp424 ebcdic-cp-he csIBM424 }
11759    { IBM437 cp437 437 csPC8CodePage437 }
11760    { IBM500 CP500 ebcdic-cp-be ebcdic-cp-ch csIBM500 }
11761    { IBM775 cp775 csPC775Baltic }
11762    { IBM850 cp850 850 csPC850Multilingual }
11763    { IBM851 cp851 851 csIBM851 }
11764    { IBM852 cp852 852 csPCp852 }
11765    { IBM855 cp855 855 csIBM855 }
11766    { IBM857 cp857 857 csIBM857 }
11767    { IBM860 cp860 860 csIBM860 }
11768    { IBM861 cp861 861 cp-is csIBM861 }
11769    { IBM862 cp862 862 csPC862LatinHebrew }
11770    { IBM863 cp863 863 csIBM863 }
11771    { IBM864 cp864 csIBM864 }
11772    { IBM865 cp865 865 csIBM865 }
11773    { IBM866 cp866 866 csIBM866 }
11774    { IBM868 CP868 cp-ar csIBM868 }
11775    { IBM869 cp869 869 cp-gr csIBM869 }
11776    { IBM870 CP870 ebcdic-cp-roece ebcdic-cp-yu csIBM870 }
11777    { IBM871 CP871 ebcdic-cp-is csIBM871 }
11778    { IBM880 cp880 EBCDIC-Cyrillic csIBM880 }
11779    { IBM891 cp891 csIBM891 }
11780    { IBM903 cp903 csIBM903 }
11781    { IBM904 cp904 904 csIBBM904 }
11782    { IBM905 CP905 ebcdic-cp-tr csIBM905 }
11783    { IBM918 CP918 ebcdic-cp-ar2 csIBM918 }
11784    { IBM1026 CP1026 csIBM1026 }
11785    { EBCDIC-AT-DE csIBMEBCDICATDE }
11786    { EBCDIC-AT-DE-A csEBCDICATDEA }
11787    { EBCDIC-CA-FR csEBCDICCAFR }
11788    { EBCDIC-DK-NO csEBCDICDKNO }
11789    { EBCDIC-DK-NO-A csEBCDICDKNOA }
11790    { EBCDIC-FI-SE csEBCDICFISE }
11791    { EBCDIC-FI-SE-A csEBCDICFISEA }
11792    { EBCDIC-FR csEBCDICFR }
11793    { EBCDIC-IT csEBCDICIT }
11794    { EBCDIC-PT csEBCDICPT }
11795    { EBCDIC-ES csEBCDICES }
11796    { EBCDIC-ES-A csEBCDICESA }
11797    { EBCDIC-ES-S csEBCDICESS }
11798    { EBCDIC-UK csEBCDICUK }
11799    { EBCDIC-US csEBCDICUS }
11800    { UNKNOWN-8BIT csUnknown8BiT }
11801    { MNEMONIC csMnemonic }
11802    { MNEM csMnem }
11803    { VISCII csVISCII }
11804    { VIQR csVIQR }
11805    { KOI8-R csKOI8R }
11806    { IBM00858 CCSID00858 CP00858 PC-Multilingual-850+euro }
11807    { IBM00924 CCSID00924 CP00924 ebcdic-Latin9--euro }
11808    { IBM01140 CCSID01140 CP01140 ebcdic-us-37+euro }
11809    { IBM01141 CCSID01141 CP01141 ebcdic-de-273+euro }
11810    { IBM01142 CCSID01142 CP01142 ebcdic-dk-277+euro ebcdic-no-277+euro }
11811    { IBM01143 CCSID01143 CP01143 ebcdic-fi-278+euro ebcdic-se-278+euro }
11812    { IBM01144 CCSID01144 CP01144 ebcdic-it-280+euro }
11813    { IBM01145 CCSID01145 CP01145 ebcdic-es-284+euro }
11814    { IBM01146 CCSID01146 CP01146 ebcdic-gb-285+euro }
11815    { IBM01147 CCSID01147 CP01147 ebcdic-fr-297+euro }
11816    { IBM01148 CCSID01148 CP01148 ebcdic-international-500+euro }
11817    { IBM01149 CCSID01149 CP01149 ebcdic-is-871+euro }
11818    { IBM1047 IBM-1047 }
11819    { PTCP154 csPTCP154 PT154 CP154 Cyrillic-Asian }
11820    { Amiga-1251 Ami1251 Amiga1251 Ami-1251 }
11821    { UNICODE-1-1 csUnicode11 }
11822    { CESU-8 csCESU-8 }
11823    { BOCU-1 csBOCU-1 }
11824    { UNICODE-1-1-UTF-7 csUnicode11UTF7 }
11825    { ISO-8859-14 iso-ir-199 ISO_8859-14:1998 ISO_8859-14 latin8 iso-celtic
11826      l8 }
11827    { ISO-8859-15 ISO_8859-15 Latin-9 }
11828    { ISO-8859-16 iso-ir-226 ISO_8859-16:2001 ISO_8859-16 latin10 l10 }
11829    { GBK CP936 MS936 windows-936 }
11830    { JIS_Encoding csJISEncoding }
11831    { Shift_JIS MS_Kanji csShiftJIS ShiftJIS Shift-JIS }
11832    { Extended_UNIX_Code_Packed_Format_for_Japanese csEUCPkdFmtJapanese
11833      EUC-JP }
11834    { Extended_UNIX_Code_Fixed_Width_for_Japanese csEUCFixWidJapanese }
11835    { ISO-10646-UCS-Basic csUnicodeASCII }
11836    { ISO-10646-Unicode-Latin1 csUnicodeLatin1 ISO-10646 }
11837    { ISO-Unicode-IBM-1261 csUnicodeIBM1261 }
11838    { ISO-Unicode-IBM-1268 csUnicodeIBM1268 }
11839    { ISO-Unicode-IBM-1276 csUnicodeIBM1276 }
11840    { ISO-Unicode-IBM-1264 csUnicodeIBM1264 }
11841    { ISO-Unicode-IBM-1265 csUnicodeIBM1265 }
11842    { ISO-8859-1-Windows-3.0-Latin-1 csWindows30Latin1 }
11843    { ISO-8859-1-Windows-3.1-Latin-1 csWindows31Latin1 }
11844    { ISO-8859-2-Windows-Latin-2 csWindows31Latin2 }
11845    { ISO-8859-9-Windows-Latin-5 csWindows31Latin5 }
11846    { Adobe-Standard-Encoding csAdobeStandardEncoding }
11847    { Ventura-US csVenturaUS }
11848    { Ventura-International csVenturaInternational }
11849    { PC8-Danish-Norwegian csPC8DanishNorwegian }
11850    { PC8-Turkish csPC8Turkish }
11851    { IBM-Symbols csIBMSymbols }
11852    { IBM-Thai csIBMThai }
11853    { HP-Legal csHPLegal }
11854    { HP-Pi-font csHPPiFont }
11855    { HP-Math8 csHPMath8 }
11856    { Adobe-Symbol-Encoding csHPPSMath }
11857    { HP-DeskTop csHPDesktop }
11858    { Ventura-Math csVenturaMath }
11859    { Microsoft-Publishing csMicrosoftPublishing }
11860    { Windows-31J csWindows31J }
11861    { GB2312 csGB2312 }
11862    { Big5 csBig5 }
11863}
11864
11865proc tcl_encoding {enc} {
11866    global encoding_aliases tcl_encoding_cache
11867    if {[info exists tcl_encoding_cache($enc)]} {
11868        return $tcl_encoding_cache($enc)
11869    }
11870    set names [encoding names]
11871    set lcnames [string tolower $names]
11872    set enc [string tolower $enc]
11873    set i [lsearch -exact $lcnames $enc]
11874    if {$i < 0} {
11875        # look for "isonnn" instead of "iso-nnn" or "iso_nnn"
11876        if {[regsub {^(iso|cp|ibm|jis)[-_]} $enc {\1} encx]} {
11877            set i [lsearch -exact $lcnames $encx]
11878        }
11879    }
11880    if {$i < 0} {
11881        foreach l $encoding_aliases {
11882            set ll [string tolower $l]
11883            if {[lsearch -exact $ll $enc] < 0} continue
11884            # look through the aliases for one that tcl knows about
11885            foreach e $ll {
11886                set i [lsearch -exact $lcnames $e]
11887                if {$i < 0} {
11888                    if {[regsub {^(iso|cp|ibm|jis)[-_]} $e {\1} ex]} {
11889                        set i [lsearch -exact $lcnames $ex]
11890                    }
11891                }
11892                if {$i >= 0} break
11893            }
11894            break
11895        }
11896    }
11897    set tclenc {}
11898    if {$i >= 0} {
11899        set tclenc [lindex $names $i]
11900    }
11901    set tcl_encoding_cache($enc) $tclenc
11902    return $tclenc
11903}
11904
11905proc gitattr {path attr default} {
11906    global path_attr_cache
11907    if {[info exists path_attr_cache($attr,$path)]} {
11908        set r $path_attr_cache($attr,$path)
11909    } else {
11910        set r "unspecified"
11911        if {![catch {set line [exec git check-attr $attr -- $path]}]} {
11912            regexp "(.*): $attr: (.*)" $line m f r
11913        }
11914        set path_attr_cache($attr,$path) $r
11915    }
11916    if {$r eq "unspecified"} {
11917        return $default
11918    }
11919    return $r
11920}
11921
11922proc cache_gitattr {attr pathlist} {
11923    global path_attr_cache
11924    set newlist {}
11925    foreach path $pathlist {
11926        if {![info exists path_attr_cache($attr,$path)]} {
11927            lappend newlist $path
11928        }
11929    }
11930    set lim 1000
11931    if {[tk windowingsystem] == "win32"} {
11932        # windows has a 32k limit on the arguments to a command...
11933        set lim 30
11934    }
11935    while {$newlist ne {}} {
11936        set head [lrange $newlist 0 [expr {$lim - 1}]]
11937        set newlist [lrange $newlist $lim end]
11938        if {![catch {set rlist [eval exec git check-attr $attr -- $head]}]} {
11939            foreach row [split $rlist "\n"] {
11940                if {[regexp "(.*): $attr: (.*)" $row m path value]} {
11941                    if {[string index $path 0] eq "\""} {
11942                        set path [encoding convertfrom [lindex $path 0]]
11943                    }
11944                    set path_attr_cache($attr,$path) $value
11945                }
11946            }
11947        }
11948    }
11949}
11950
11951proc get_path_encoding {path} {
11952    global gui_encoding perfile_attrs
11953    set tcl_enc $gui_encoding
11954    if {$path ne {} && $perfile_attrs} {
11955        set enc2 [tcl_encoding [gitattr $path encoding $tcl_enc]]
11956        if {$enc2 ne {}} {
11957            set tcl_enc $enc2
11958        }
11959    }
11960    return $tcl_enc
11961}
11962
11963# First check that Tcl/Tk is recent enough
11964if {[catch {package require Tk 8.4} err]} {
11965    show_error {} . "Sorry, gitk cannot run with this version of Tcl/Tk.\n\
11966                     Gitk requires at least Tcl/Tk 8.4." list
11967    exit 1
11968}
11969
11970# on OSX bring the current Wish process window to front
11971if {[tk windowingsystem] eq "aqua"} {
11972    exec osascript -e [format {
11973        tell application "System Events"
11974            set frontmost of processes whose unix id is %d to true
11975        end tell
11976    } [pid] ]
11977}
11978
11979# Unset GIT_TRACE var if set
11980if { [info exists ::env(GIT_TRACE)] } {
11981    unset ::env(GIT_TRACE)
11982}
11983
11984# defaults...
11985set wrcomcmd "git diff-tree --stdin -p --pretty"
11986
11987set gitencoding {}
11988catch {
11989    set gitencoding [exec git config --get i18n.commitencoding]
11990}
11991catch {
11992    set gitencoding [exec git config --get i18n.logoutputencoding]
11993}
11994if {$gitencoding == ""} {
11995    set gitencoding "utf-8"
11996}
11997set tclencoding [tcl_encoding $gitencoding]
11998if {$tclencoding == {}} {
11999    puts stderr "Warning: encoding $gitencoding is not supported by Tcl/Tk"
12000}
12001
12002set gui_encoding [encoding system]
12003catch {
12004    set enc [exec git config --get gui.encoding]
12005    if {$enc ne {}} {
12006        set tclenc [tcl_encoding $enc]
12007        if {$tclenc ne {}} {
12008            set gui_encoding $tclenc
12009        } else {
12010            puts stderr "Warning: encoding $enc is not supported by Tcl/Tk"
12011        }
12012    }
12013}
12014
12015set log_showroot true
12016catch {
12017    set log_showroot [exec git config --bool --get log.showroot]
12018}
12019
12020if {[tk windowingsystem] eq "aqua"} {
12021    set mainfont {{Lucida Grande} 9}
12022    set textfont {Monaco 9}
12023    set uifont {{Lucida Grande} 9 bold}
12024} elseif {![catch {::tk::pkgconfig get fontsystem} xft] && $xft eq "xft"} {
12025    # fontconfig!
12026    set mainfont {sans 9}
12027    set textfont {monospace 9}
12028    set uifont {sans 9 bold}
12029} else {
12030    set mainfont {Helvetica 9}
12031    set textfont {Courier 9}
12032    set uifont {Helvetica 9 bold}
12033}
12034set tabstop 8
12035set findmergefiles 0
12036set maxgraphpct 50
12037set maxwidth 16
12038set revlistorder 0
12039set fastdate 0
12040set uparrowlen 5
12041set downarrowlen 5
12042set mingaplen 100
12043set cmitmode "patch"
12044set wrapcomment "none"
12045set showneartags 1
12046set hideremotes 0
12047set maxrefs 20
12048set maxlinelen 200
12049set showlocalchanges 1
12050set limitdiffs 1
12051set datetimeformat "%Y-%m-%d %H:%M:%S"
12052set autoselect 1
12053set autosellen 40
12054set perfile_attrs 0
12055set want_ttk 1
12056
12057if {[tk windowingsystem] eq "aqua"} {
12058    set extdifftool "opendiff"
12059} else {
12060    set extdifftool "meld"
12061}
12062
12063set colors {green red blue magenta darkgrey brown orange}
12064if {[tk windowingsystem] eq "win32"} {
12065    set uicolor SystemButtonFace
12066    set uifgcolor SystemButtonText
12067    set uifgdisabledcolor SystemDisabledText
12068    set bgcolor SystemWindow
12069    set fgcolor SystemWindowText
12070    set selectbgcolor SystemHighlight
12071} else {
12072    set uicolor grey85
12073    set uifgcolor black
12074    set uifgdisabledcolor "#999"
12075    set bgcolor white
12076    set fgcolor black
12077    set selectbgcolor gray85
12078}
12079set diffcolors {red "#00a000" blue}
12080set diffcontext 3
12081set mergecolors {red blue green purple brown "#009090" magenta "#808000" "#009000" "#ff0080" cyan "#b07070" "#70b0f0" "#70f0b0" "#f0b070" "#ff70b0"}
12082set ignorespace 0
12083set worddiff ""
12084set markbgcolor "#e0e0ff"
12085
12086set headbgcolor green
12087set headfgcolor black
12088set headoutlinecolor black
12089set remotebgcolor #ffddaa
12090set tagbgcolor yellow
12091set tagfgcolor black
12092set tagoutlinecolor black
12093set reflinecolor black
12094set filesepbgcolor #aaaaaa
12095set filesepfgcolor black
12096set linehoverbgcolor #ffff80
12097set linehoverfgcolor black
12098set linehoveroutlinecolor black
12099set mainheadcirclecolor yellow
12100set workingfilescirclecolor red
12101set indexcirclecolor green
12102set circlecolors {white blue gray blue blue}
12103set linkfgcolor blue
12104set circleoutlinecolor $fgcolor
12105set foundbgcolor yellow
12106set currentsearchhitbgcolor orange
12107
12108# button for popping up context menus
12109if {[tk windowingsystem] eq "aqua"} {
12110    set ctxbut <Button-2>
12111} else {
12112    set ctxbut <Button-3>
12113}
12114
12115## For msgcat loading, first locate the installation location.
12116if { [info exists ::env(GITK_MSGSDIR)] } {
12117    ## Msgsdir was manually set in the environment.
12118    set gitk_msgsdir $::env(GITK_MSGSDIR)
12119} else {
12120    ## Let's guess the prefix from argv0.
12121    set gitk_prefix [file dirname [file dirname [file normalize $argv0]]]
12122    set gitk_libdir [file join $gitk_prefix share gitk lib]
12123    set gitk_msgsdir [file join $gitk_libdir msgs]
12124    unset gitk_prefix
12125}
12126
12127## Internationalization (i18n) through msgcat and gettext. See
12128## http://www.gnu.org/software/gettext/manual/html_node/Tcl.html
12129package require msgcat
12130namespace import ::msgcat::mc
12131## And eventually load the actual message catalog
12132::msgcat::mcload $gitk_msgsdir
12133
12134catch {
12135    # follow the XDG base directory specification by default. See
12136    # http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
12137    if {[info exists env(XDG_CONFIG_HOME)] && $env(XDG_CONFIG_HOME) ne ""} {
12138        # XDG_CONFIG_HOME environment variable is set
12139        set config_file [file join $env(XDG_CONFIG_HOME) git gitk]
12140        set config_file_tmp [file join $env(XDG_CONFIG_HOME) git gitk-tmp]
12141    } else {
12142        # default XDG_CONFIG_HOME
12143        set config_file "~/.config/git/gitk"
12144        set config_file_tmp "~/.config/git/gitk-tmp"
12145    }
12146    if {![file exists $config_file]} {
12147        # for backward compatibility use the old config file if it exists
12148        if {[file exists "~/.gitk"]} {
12149            set config_file "~/.gitk"
12150            set config_file_tmp "~/.gitk-tmp"
12151        } elseif {![file exists [file dirname $config_file]]} {
12152            file mkdir [file dirname $config_file]
12153        }
12154    }
12155    source $config_file
12156}
12157
12158parsefont mainfont $mainfont
12159eval font create mainfont [fontflags mainfont]
12160eval font create mainfontbold [fontflags mainfont 1]
12161
12162parsefont textfont $textfont
12163eval font create textfont [fontflags textfont]
12164eval font create textfontbold [fontflags textfont 1]
12165
12166parsefont uifont $uifont
12167eval font create uifont [fontflags uifont]
12168
12169setui $uicolor
12170
12171setoptions
12172
12173# check that we can find a .git directory somewhere...
12174if {[catch {set gitdir [exec git rev-parse --git-dir]}]} {
12175    show_error {} . [mc "Cannot find a git repository here."]
12176    exit 1
12177}
12178
12179set selecthead {}
12180set selectheadid {}
12181
12182set revtreeargs {}
12183set cmdline_files {}
12184set i 0
12185set revtreeargscmd {}
12186foreach arg $argv {
12187    switch -glob -- $arg {
12188        "" { }
12189        "--" {
12190            set cmdline_files [lrange $argv [expr {$i + 1}] end]
12191            break
12192        }
12193        "--select-commit=*" {
12194            set selecthead [string range $arg 16 end]
12195        }
12196        "--argscmd=*" {
12197            set revtreeargscmd [string range $arg 10 end]
12198        }
12199        default {
12200            lappend revtreeargs $arg
12201        }
12202    }
12203    incr i
12204}
12205
12206if {$selecthead eq "HEAD"} {
12207    set selecthead {}
12208}
12209
12210if {$i >= [llength $argv] && $revtreeargs ne {}} {
12211    # no -- on command line, but some arguments (other than --argscmd)
12212    if {[catch {
12213        set f [eval exec git rev-parse --no-revs --no-flags $revtreeargs]
12214        set cmdline_files [split $f "\n"]
12215        set n [llength $cmdline_files]
12216        set revtreeargs [lrange $revtreeargs 0 end-$n]
12217        # Unfortunately git rev-parse doesn't produce an error when
12218        # something is both a revision and a filename.  To be consistent
12219        # with git log and git rev-list, check revtreeargs for filenames.
12220        foreach arg $revtreeargs {
12221            if {[file exists $arg]} {
12222                show_error {} . [mc "Ambiguous argument '%s': both revision\
12223                                 and filename" $arg]
12224                exit 1
12225            }
12226        }
12227    } err]} {
12228        # unfortunately we get both stdout and stderr in $err,
12229        # so look for "fatal:".
12230        set i [string first "fatal:" $err]
12231        if {$i > 0} {
12232            set err [string range $err [expr {$i + 6}] end]
12233        }
12234        show_error {} . "[mc "Bad arguments to gitk:"]\n$err"
12235        exit 1
12236    }
12237}
12238
12239set nullid "0000000000000000000000000000000000000000"
12240set nullid2 "0000000000000000000000000000000000000001"
12241set nullfile "/dev/null"
12242
12243set have_tk85 [expr {[package vcompare $tk_version "8.5"] >= 0}]
12244if {![info exists have_ttk]} {
12245    set have_ttk [llength [info commands ::ttk::style]]
12246}
12247set use_ttk [expr {$have_ttk && $want_ttk}]
12248set NS [expr {$use_ttk ? "ttk" : ""}]
12249
12250regexp {^git version ([\d.]*\d)} [exec git version] _ git_version
12251
12252set show_notes {}
12253if {[package vcompare $git_version "1.6.6.2"] >= 0} {
12254    set show_notes "--show-notes"
12255}
12256
12257set appname "gitk"
12258
12259set runq {}
12260set history {}
12261set historyindex 0
12262set fh_serial 0
12263set nhl_names {}
12264set highlight_paths {}
12265set findpattern {}
12266set searchdirn -forwards
12267set boldids {}
12268set boldnameids {}
12269set diffelide {0 0}
12270set markingmatches 0
12271set linkentercount 0
12272set need_redisplay 0
12273set nrows_drawn 0
12274set firsttabstop 0
12275
12276set nextviewnum 1
12277set curview 0
12278set selectedview 0
12279set selectedhlview [mc "None"]
12280set highlight_related [mc "None"]
12281set highlight_files {}
12282set viewfiles(0) {}
12283set viewperm(0) 0
12284set viewargs(0) {}
12285set viewargscmd(0) {}
12286
12287set selectedline {}
12288set numcommits 0
12289set loginstance 0
12290set cmdlineok 0
12291set stopped 0
12292set stuffsaved 0
12293set patchnum 0
12294set lserial 0
12295set hasworktree [hasworktree]
12296set cdup {}
12297if {[expr {[exec git rev-parse --is-inside-work-tree] == "true"}]} {
12298    set cdup [exec git rev-parse --show-cdup]
12299}
12300set worktree [exec git rev-parse --show-toplevel]
12301setcoords
12302makewindow
12303catch {
12304    image create photo gitlogo      -width 16 -height 16
12305
12306    image create photo gitlogominus -width  4 -height  2
12307    gitlogominus put #C00000 -to 0 0 4 2
12308    gitlogo copy gitlogominus -to  1 5
12309    gitlogo copy gitlogominus -to  6 5
12310    gitlogo copy gitlogominus -to 11 5
12311    image delete gitlogominus
12312
12313    image create photo gitlogoplus  -width  4 -height  4
12314    gitlogoplus  put #008000 -to 1 0 3 4
12315    gitlogoplus  put #008000 -to 0 1 4 3
12316    gitlogo copy gitlogoplus  -to  1 9
12317    gitlogo copy gitlogoplus  -to  6 9
12318    gitlogo copy gitlogoplus  -to 11 9
12319    image delete gitlogoplus
12320
12321    image create photo gitlogo32    -width 32 -height 32
12322    gitlogo32 copy gitlogo -zoom 2 2
12323
12324    wm iconphoto . -default gitlogo gitlogo32
12325}
12326# wait for the window to become visible
12327tkwait visibility .
12328wm title . "$appname: [reponame]"
12329update
12330readrefs
12331
12332if {$cmdline_files ne {} || $revtreeargs ne {} || $revtreeargscmd ne {}} {
12333    # create a view for the files/dirs specified on the command line
12334    set curview 1
12335    set selectedview 1
12336    set nextviewnum 2
12337    set viewname(1) [mc "Command line"]
12338    set viewfiles(1) $cmdline_files
12339    set viewargs(1) $revtreeargs
12340    set viewargscmd(1) $revtreeargscmd
12341    set viewperm(1) 0
12342    set vdatemode(1) 0
12343    addviewmenu 1
12344    .bar.view entryconf [mca "Edit view..."] -state normal
12345    .bar.view entryconf [mca "Delete view"] -state normal
12346}
12347
12348if {[info exists permviews]} {
12349    foreach v $permviews {
12350        set n $nextviewnum
12351        incr nextviewnum
12352        set viewname($n) [lindex $v 0]
12353        set viewfiles($n) [lindex $v 1]
12354        set viewargs($n) [lindex $v 2]
12355        set viewargscmd($n) [lindex $v 3]
12356        set viewperm($n) 1
12357        addviewmenu $n
12358    }
12359}
12360
12361if {[tk windowingsystem] eq "win32"} {
12362    focus -force .
12363}
12364
12365getcommits {}
12366
12367# Local variables:
12368# mode: tcl
12369# indent-tabs-mode: t
12370# tab-width: 8
12371# End: