a45784c0579517db2a6f90762a1a2a070bbaf490
   1# git-gui blame viewer
   2# Copyright (C) 2006, 2007 Shawn Pearce
   3
   4class blame {
   5
   6image create photo ::blame::img_back_arrow -data {R0lGODlhGAAYAIUAAPwCBEzKXFTSZIz+nGzmhGzqfGTidIT+nEzGXHTqhGzmfGzifFzadETCVES+VARWDFzWbHzyjAReDGTadFTOZDSyRDyyTCymPARaFGTedFzSbDy2TCyqRCyqPARaDAyCHES6VDy6VCyiPAR6HCSeNByWLARyFARiDARqFGTifARiFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAAYABgAAAajQIBwSCwaj8ikcsk0BppJwRPqHEypQwHBis0WDAdEFyBIKBaMAKLBdjQeSkFBYTBAIvgEoS6JmhUTEwIUDQ4VFhcMGEhyCgoZExoUaxsWHB0THkgfAXUGAhoBDSAVFR0XBnCbDRmgog0hpSIiDJpJIyEQhBUcJCIlwA22SSYVogknEg8eD82qSigdDSknY0IqJQXPYxIl1dZCGNvWw+Dm510GQQAh/mhDcmVhdGVkIGJ5IEJNUFRvR0lGIFBybyB2ZXJzaW9uIDIuNQ0KqSBEZXZlbENvciAxOTk3LDE5OTguIEFsbCByaWdodHMgcmVzZXJ2ZWQuDQpodHRwOi8vd3d3LmRldmVsY29yLmNvbQA7}
   7
   8# Persistant data (survives loads)
   9#
  10field history {}; # viewer history: {commit path}
  11field header    ; # array commit,key -> header field
  12
  13# Tk UI control paths
  14#
  15field w          ; # top window in this viewer
  16field w_back     ; # our back button
  17field w_path     ; # label showing the current file path
  18field w_columns  ; # list of all column widgets in the viewer
  19field w_line     ; # text column: all line numbers
  20field w_amov     ; # text column: annotations + move tracking
  21field w_asim     ; # text column: annotations (simple computation)
  22field w_file     ; # text column: actual file data
  23field w_cviewer  ; # pane showing commit message
  24field finder     ; # find mini-dialog frame
  25field status     ; # status mega-widget instance
  26field old_height ; # last known height of $w.file_pane
  27
  28
  29# Tk UI colors
  30#
  31variable active_color #c0edc5
  32variable group_colors {
  33        #d6d6d6
  34        #e1e1e1
  35        #ececec
  36}
  37
  38# Current blame data; cleared/reset on each load
  39#
  40field commit               ; # input commit to blame
  41field path                 ; # input filename to view in $commit
  42
  43field current_fd        {} ; # background process running
  44field highlight_line    -1 ; # current line selected
  45field highlight_column  {} ; # current commit column selected
  46field highlight_commit  {} ; # sha1 of commit selected
  47
  48field total_lines       0  ; # total length of file
  49field blame_lines       0  ; # number of lines computed
  50field amov_data            ; # list of {commit origfile origline}
  51field asim_data            ; # list of {commit origfile origline}
  52
  53field r_commit             ; # commit currently being parsed
  54field r_orig_line          ; # original line number
  55field r_final_line         ; # final line number
  56field r_line_count         ; # lines in this region
  57
  58field tooltip_wm        {} ; # Current tooltip toplevel, if open
  59field tooltip_t         {} ; # Text widget in $tooltip_wm
  60field tooltip_timer     {} ; # Current timer event for our tooltip
  61field tooltip_commit    {} ; # Commit(s) in tooltip
  62
  63constructor new {i_commit i_path i_jump} {
  64        global cursor_ptr M1B M1T have_tk85
  65        variable active_color
  66        variable group_colors
  67
  68        set commit $i_commit
  69        set path   $i_path
  70
  71        make_toplevel top w
  72        wm title $top [append "[appname] ([reponame]): " [mc "File Viewer"]]
  73
  74        set font_w [font measure font_diff "0"]
  75
  76        frame $w.header -background gold
  77        label $w.header.commit_l \
  78                -text [mc "Commit:"] \
  79                -background gold \
  80                -foreground black \
  81                -anchor w \
  82                -justify left
  83        set w_back $w.header.commit_b
  84        label $w_back \
  85                -image ::blame::img_back_arrow \
  86                -borderwidth 0 \
  87                -relief flat \
  88                -state disabled \
  89                -background gold \
  90                -foreground black \
  91                -activebackground gold
  92        bind $w_back <Button-1> "
  93                if {\[$w_back cget -state\] eq {normal}} {
  94                        [cb _history_menu]
  95                }
  96                "
  97        label $w.header.commit \
  98                -textvariable @commit \
  99                -background gold \
 100                -foreground black \
 101                -anchor w \
 102                -justify left
 103        label $w.header.path_l \
 104                -text [mc "File:"] \
 105                -background gold \
 106                -foreground black \
 107                -anchor w \
 108                -justify left
 109        set w_path $w.header.path
 110        label $w_path \
 111                -background gold \
 112                -foreground black \
 113                -anchor w \
 114                -justify left
 115        pack $w.header.commit_l -side left
 116        pack $w_back -side left
 117        pack $w.header.commit -side left
 118        pack $w_path -fill x -side right
 119        pack $w.header.path_l -side right
 120
 121        panedwindow $w.file_pane -orient vertical -borderwidth 0 -sashwidth 3
 122        frame $w.file_pane.out -relief flat -borderwidth 1
 123        frame $w.file_pane.cm -relief sunken -borderwidth 1
 124        $w.file_pane add $w.file_pane.out \
 125                -sticky nsew \
 126                -minsize 100 \
 127                -height 100 \
 128                -width 100
 129        $w.file_pane add $w.file_pane.cm \
 130                -sticky nsew \
 131                -minsize 25 \
 132                -height 25 \
 133                -width 100
 134
 135        set w_line $w.file_pane.out.linenumber_t
 136        text $w_line \
 137                -takefocus 0 \
 138                -highlightthickness 0 \
 139                -padx 0 -pady 0 \
 140                -background white \
 141                -foreground black \
 142                -borderwidth 0 \
 143                -state disabled \
 144                -wrap none \
 145                -height 40 \
 146                -width 6 \
 147                -font font_diff
 148        $w_line tag conf linenumber -justify right -rmargin 5
 149
 150        set w_amov $w.file_pane.out.amove_t
 151        text $w_amov \
 152                -takefocus 0 \
 153                -highlightthickness 0 \
 154                -padx 0 -pady 0 \
 155                -background white \
 156                -foreground black \
 157                -borderwidth 0 \
 158                -state disabled \
 159                -wrap none \
 160                -height 40 \
 161                -width 5 \
 162                -font font_diff
 163        $w_amov tag conf author_abbr -justify right -rmargin 5
 164        $w_amov tag conf curr_commit
 165        $w_amov tag conf prior_commit -foreground blue -underline 1
 166        $w_amov tag bind prior_commit \
 167                <Button-1> \
 168                "[cb _load_commit $w_amov @amov_data @%x,%y];break"
 169
 170        set w_asim $w.file_pane.out.asimple_t
 171        text $w_asim \
 172                -takefocus 0 \
 173                -highlightthickness 0 \
 174                -padx 0 -pady 0 \
 175                -background white \
 176                -foreground black \
 177                -borderwidth 0 \
 178                -state disabled \
 179                -wrap none \
 180                -height 40 \
 181                -width 4 \
 182                -font font_diff
 183        $w_asim tag conf author_abbr -justify right
 184        $w_asim tag conf curr_commit
 185        $w_asim tag conf prior_commit -foreground blue -underline 1
 186        $w_asim tag bind prior_commit \
 187                <Button-1> \
 188                "[cb _load_commit $w_asim @asim_data @%x,%y];break"
 189
 190        set w_file $w.file_pane.out.file_t
 191        text $w_file \
 192                -takefocus 0 \
 193                -highlightthickness 0 \
 194                -padx 0 -pady 0 \
 195                -background white \
 196                -foreground black \
 197                -borderwidth 0 \
 198                -state disabled \
 199                -wrap none \
 200                -height 40 \
 201                -width 80 \
 202                -xscrollcommand [list $w.file_pane.out.sbx set] \
 203                -font font_diff
 204        if {$have_tk85} {
 205                $w_file configure -inactiveselectbackground darkblue
 206        }
 207        $w_file tag conf found \
 208                -background yellow
 209
 210        set w_columns [list $w_amov $w_asim $w_line $w_file]
 211
 212        scrollbar $w.file_pane.out.sbx \
 213                -orient h \
 214                -command [list $w_file xview]
 215        scrollbar $w.file_pane.out.sby \
 216                -orient v \
 217                -command [list scrollbar2many $w_columns yview]
 218        eval grid $w_columns $w.file_pane.out.sby -sticky nsew
 219        grid conf \
 220                $w.file_pane.out.sbx \
 221                -column [expr {[llength $w_columns] - 1}] \
 222                -sticky we
 223        grid columnconfigure \
 224                $w.file_pane.out \
 225                [expr {[llength $w_columns] - 1}] \
 226                -weight 1
 227        grid rowconfigure $w.file_pane.out 0 -weight 1
 228
 229        set finder [::searchbar::new \
 230                $w.file_pane.out.ff $w_file \
 231                -column [expr {[llength $w_columns] - 1}] \
 232                ]
 233
 234        set w_cviewer $w.file_pane.cm.t
 235        text $w_cviewer \
 236                -background white \
 237                -foreground black \
 238                -borderwidth 0 \
 239                -state disabled \
 240                -wrap none \
 241                -height 10 \
 242                -width 80 \
 243                -xscrollcommand [list $w.file_pane.cm.sbx set] \
 244                -yscrollcommand [list $w.file_pane.cm.sby set] \
 245                -font font_diff
 246        $w_cviewer tag conf still_loading \
 247                -font font_uiitalic \
 248                -justify center
 249        $w_cviewer tag conf header_key \
 250                -tabs {3c} \
 251                -background $active_color \
 252                -font font_uibold
 253        $w_cviewer tag conf header_val \
 254                -background $active_color \
 255                -font font_ui
 256        $w_cviewer tag raise sel
 257        scrollbar $w.file_pane.cm.sbx \
 258                -orient h \
 259                -command [list $w_cviewer xview]
 260        scrollbar $w.file_pane.cm.sby \
 261                -orient v \
 262                -command [list $w_cviewer yview]
 263        pack $w.file_pane.cm.sby -side right -fill y
 264        pack $w.file_pane.cm.sbx -side bottom -fill x
 265        pack $w_cviewer -expand 1 -fill both
 266
 267        set status [::status_bar::new $w.status]
 268
 269        menu $w.ctxm -tearoff 0
 270        $w.ctxm add command \
 271                -label [mc "Copy Commit"] \
 272                -command [cb _copycommit]
 273        $w.ctxm add separator
 274        $w.ctxm add command \
 275                -label [mc "Find Text..."] \
 276                -accelerator F7 \
 277                -command [list searchbar::show $finder]
 278        menu $w.ctxm.enc
 279        build_encoding_menu $w.ctxm.enc [cb _setencoding]
 280        $w.ctxm add cascade \
 281                -label [mc "Encoding"] \
 282                -menu $w.ctxm.enc
 283        $w.ctxm add command \
 284                -label [mc "Do Full Copy Detection"] \
 285                -command [cb _fullcopyblame]
 286        $w.ctxm add separator
 287        $w.ctxm add command \
 288                -label [mc "Show History Context"] \
 289                -command [cb _gitkcommit]
 290        $w.ctxm add command \
 291                -label [mc "Blame Parent Commit"] \
 292                -command [cb _blameparent]
 293
 294        foreach i $w_columns {
 295                for {set g 0} {$g < [llength $group_colors]} {incr g} {
 296                        $i tag conf color$g -background [lindex $group_colors $g]
 297                }
 298
 299                if {$i eq $w_file} {
 300                        $w_file tag raise found
 301                }
 302                $i tag raise sel
 303
 304                $i conf -cursor $cursor_ptr
 305                $i conf -yscrollcommand \
 306                        "[list ::searchbar::scrolled $finder]
 307                         [list many2scrollbar $w_columns yview $w.file_pane.out.sby]"
 308                bind $i <Button-1> "
 309                        [cb _hide_tooltip]
 310                        [cb _click $i @%x,%y]
 311                        focus $i
 312                "
 313                bind $i <Any-Motion>  [cb _show_tooltip $i @%x,%y]
 314                bind $i <Any-Enter>   [cb _hide_tooltip]
 315                bind $i <Any-Leave>   [cb _hide_tooltip]
 316                bind_button3 $i "
 317                        [cb _hide_tooltip]
 318                        set cursorX %x
 319                        set cursorY %y
 320                        set cursorW %W
 321                        tk_popup $w.ctxm %X %Y
 322                "
 323                bind $i <Shift-Tab> "[list focus $w_cviewer];break"
 324                bind $i <Tab>       "[list focus $w_cviewer];break"
 325        }
 326
 327        foreach i [concat $w_columns $w_cviewer] {
 328                bind $i <Key-Up>        {catch {%W yview scroll -1 units};break}
 329                bind $i <Key-Down>      {catch {%W yview scroll  1 units};break}
 330                bind $i <Key-Left>      {catch {%W xview scroll -1 units};break}
 331                bind $i <Key-Right>     {catch {%W xview scroll  1 units};break}
 332                bind $i <Key-k>         {catch {%W yview scroll -1 units};break}
 333                bind $i <Key-j>         {catch {%W yview scroll  1 units};break}
 334                bind $i <Key-h>         {catch {%W xview scroll -1 units};break}
 335                bind $i <Key-l>         {catch {%W xview scroll  1 units};break}
 336                bind $i <Control-Key-b> {catch {%W yview scroll -1 pages};break}
 337                bind $i <Control-Key-f> {catch {%W yview scroll  1 pages};break}
 338        }
 339
 340        bind $w_cviewer <Shift-Tab> "[list focus $w_file];break"
 341        bind $w_cviewer <Tab>       "[list focus $w_file];break"
 342        bind $w_cviewer <Button-1> [list focus $w_cviewer]
 343        bind $w_file    <Visibility> [list focus $w_file]
 344        bind $top       <F7>         [list searchbar::show $finder]
 345        bind $top       <Escape>     [list searchbar::hide $finder]
 346        bind $top       <F3>         [list searchbar::find_next $finder]
 347        bind $top       <Shift-F3>   [list searchbar::find_prev $finder]
 348        catch { bind $top <Shift-Key-XF86_Switch_VT_3> [list searchbar::find_prev $finder] }
 349
 350        grid configure $w.header -sticky ew
 351        grid configure $w.file_pane -sticky nsew
 352        grid configure $w.status -sticky ew
 353        grid columnconfigure $top 0 -weight 1
 354        grid rowconfigure $top 0 -weight 0
 355        grid rowconfigure $top 1 -weight 1
 356        grid rowconfigure $top 2 -weight 0
 357
 358        set req_w [winfo reqwidth  $top]
 359        set req_h [winfo reqheight $top]
 360        set scr_w [expr {[winfo screenwidth $top] - 40}]
 361        set scr_h [expr {[winfo screenheight $top] - 120}]
 362        set opt_w [expr {$font_w * (80 + 5*3 + 3)}]
 363        if {$req_w < $opt_w} {set req_w $opt_w}
 364        if {$req_w > $scr_w} {set req_w $scr_w}
 365        set opt_h [expr {$req_w*4/3}]
 366        if {$req_h < $scr_h} {set req_h $scr_h}
 367        if {$req_h > $opt_h} {set req_h $opt_h}
 368        set g "${req_w}x${req_h}"
 369        wm geometry $top $g
 370        update
 371
 372        set old_height [winfo height $w.file_pane]
 373        $w.file_pane sash place 0 \
 374                [lindex [$w.file_pane sash coord 0] 0] \
 375                [expr {int($old_height * 0.80)}]
 376        bind $w.file_pane <Configure> \
 377        "if {{$w.file_pane} eq {%W}} {[cb _resize %h]}"
 378
 379        wm protocol $top WM_DELETE_WINDOW "destroy $top"
 380        bind $top <Destroy> [cb _kill]
 381
 382        _load $this $i_jump
 383}
 384
 385method _kill {} {
 386        if {$current_fd ne {}} {
 387                kill_file_process $current_fd
 388                catch {close $current_fd}
 389                set current_fd {}
 390        }
 391}
 392
 393method _load {jump} {
 394        variable group_colors
 395
 396        _hide_tooltip $this
 397
 398        if {$total_lines != 0 || $current_fd ne {}} {
 399                _kill $this
 400
 401                foreach i $w_columns {
 402                        $i conf -state normal
 403                        $i delete 0.0 end
 404                        foreach g [$i tag names] {
 405                                if {[regexp {^g[0-9a-f]{40}$} $g]} {
 406                                        $i tag delete $g
 407                                }
 408                        }
 409                        $i conf -state disabled
 410                }
 411
 412                $w_cviewer conf -state normal
 413                $w_cviewer delete 0.0 end
 414                $w_cviewer conf -state disabled
 415
 416                set highlight_line -1
 417                set highlight_column {}
 418                set highlight_commit {}
 419                set total_lines 0
 420        }
 421
 422        if {$history eq {}} {
 423                $w_back conf -state disabled
 424        } else {
 425                $w_back conf -state normal
 426        }
 427
 428        # Index 0 is always empty.  There is never line 0 as
 429        # we use only 1 based lines, as that matches both with
 430        # git-blame output and with Tk's text widget.
 431        #
 432        set amov_data [list [list]]
 433        set asim_data [list [list]]
 434
 435        $status show [mc "Reading %s..." "$commit:[escape_path $path]"]
 436        $w_path conf -text [escape_path $path]
 437        if {$commit eq {}} {
 438                set fd [open $path r]
 439                fconfigure $fd -eofchar {}
 440        } else {
 441                set fd [git_read cat-file blob "$commit:$path"]
 442        }
 443        fconfigure $fd \
 444                -blocking 0 \
 445                -translation lf \
 446                -encoding [get_path_encoding $path]
 447        fileevent $fd readable [cb _read_file $fd $jump]
 448        set current_fd $fd
 449}
 450
 451method _history_menu {} {
 452        set m $w.backmenu
 453        if {[winfo exists $m]} {
 454                $m delete 0 end
 455        } else {
 456                menu $m -tearoff 0
 457        }
 458
 459        for {set i [expr {[llength $history] - 1}]
 460                } {$i >= 0} {incr i -1} {
 461                set e [lindex $history $i]
 462                set c [lindex $e 0]
 463                set f [lindex $e 1]
 464
 465                if {[regexp {^[0-9a-f]{40}$} $c]} {
 466                        set t [string range $c 0 8]...
 467                } elseif {$c eq {}} {
 468                        set t {Working Directory}
 469                } else {
 470                        set t $c
 471                }
 472                if {![catch {set summary $header($c,summary)}]} {
 473                        append t " $summary"
 474                        if {[string length $t] > 70} {
 475                                set t [string range $t 0 66]...
 476                        }
 477                }
 478
 479                $m add command -label $t -command [cb _goback $i]
 480        }
 481        set X [winfo rootx $w_back]
 482        set Y [expr {[winfo rooty $w_back] + [winfo height $w_back]}]
 483        tk_popup $m $X $Y
 484}
 485
 486method _goback {i} {
 487        set dat [lindex $history $i]
 488        set history [lrange $history 0 [expr {$i - 1}]]
 489        set commit [lindex $dat 0]
 490        set path [lindex $dat 1]
 491        _load $this [lrange $dat 2 5]
 492}
 493
 494method _read_file {fd jump} {
 495        if {$fd ne $current_fd} {
 496                catch {close $fd}
 497                return
 498        }
 499
 500        foreach i $w_columns {$i conf -state normal}
 501        while {[gets $fd line] >= 0} {
 502                regsub "\r\$" $line {} line
 503                incr total_lines
 504                lappend amov_data {}
 505                lappend asim_data {}
 506
 507                if {$total_lines > 1} {
 508                        foreach i $w_columns {$i insert end "\n"}
 509                }
 510
 511                $w_line insert end "$total_lines" linenumber
 512                $w_file insert end "$line"
 513        }
 514
 515        set ln_wc [expr {[string length $total_lines] + 2}]
 516        if {[$w_line cget -width] < $ln_wc} {
 517                $w_line conf -width $ln_wc
 518        }
 519
 520        foreach i $w_columns {$i conf -state disabled}
 521
 522        if {[eof $fd]} {
 523                close $fd
 524
 525                # If we don't force Tk to update the widgets *right now*
 526                # none of our jump commands will cause a change in the UI.
 527                #
 528                update
 529
 530                if {[llength $jump] == 1} {
 531                        set highlight_line [lindex $jump 0]
 532                        $w_file see "$highlight_line.0"
 533                } elseif {[llength $jump] == 4} {
 534                        set highlight_column [lindex $jump 0]
 535                        set highlight_line [lindex $jump 1]
 536                        $w_file xview moveto [lindex $jump 2]
 537                        $w_file yview moveto [lindex $jump 3]
 538                }
 539
 540                _exec_blame $this $w_asim @asim_data \
 541                        [list] \
 542                        [mc "Loading copy/move tracking annotations..."]
 543        }
 544} ifdeleted { catch {close $fd} }
 545
 546method _exec_blame {cur_w cur_d options cur_s} {
 547        lappend options --incremental
 548        if {$commit eq {}} {
 549                lappend options --contents $path
 550        } else {
 551                lappend options $commit
 552        }
 553        lappend options -- $path
 554        set fd [eval git_read --nice blame $options]
 555        fconfigure $fd -blocking 0 -translation lf -encoding utf-8
 556        fileevent $fd readable [cb _read_blame $fd $cur_w $cur_d]
 557        set current_fd $fd
 558        set blame_lines 0
 559
 560        $status start \
 561                $cur_s \
 562                [mc "lines annotated"]
 563}
 564
 565method _read_blame {fd cur_w cur_d} {
 566        upvar #0 $cur_d line_data
 567        variable group_colors
 568
 569        if {$fd ne $current_fd} {
 570                catch {close $fd}
 571                return
 572        }
 573
 574        $cur_w conf -state normal
 575        while {[gets $fd line] >= 0} {
 576                if {[regexp {^([a-z0-9]{40}) (\d+) (\d+) (\d+)$} $line line \
 577                        cmit original_line final_line line_count]} {
 578                        set r_commit     $cmit
 579                        set r_orig_line  $original_line
 580                        set r_final_line $final_line
 581                        set r_line_count $line_count
 582                } elseif {[string match {filename *} $line]} {
 583                        set file [string range $line 9 end]
 584                        set n    $r_line_count
 585                        set lno  $r_final_line
 586                        set oln  $r_orig_line
 587                        set cmit $r_commit
 588
 589                        if {[regexp {^0{40}$} $cmit]} {
 590                                set commit_abbr work
 591                                set commit_type curr_commit
 592                        } elseif {$cmit eq $commit} {
 593                                set commit_abbr this
 594                                set commit_type curr_commit
 595                        } else {
 596                                set commit_type prior_commit
 597                                set commit_abbr [string range $cmit 0 3]
 598                        }
 599
 600                        set author_abbr {}
 601                        set a_name {}
 602                        catch {set a_name $header($cmit,author)}
 603                        while {$a_name ne {}} {
 604                                if {$author_abbr ne {}
 605                                        && [string index $a_name 0] eq {'}} {
 606                                        regsub {^'[^']+'\s+} $a_name {} a_name
 607                                }
 608                                if {![regexp {^([[:upper:]])} $a_name _a]} break
 609                                append author_abbr $_a
 610                                unset _a
 611                                if {![regsub \
 612                                        {^[[:upper:]][^\s]*\s+} \
 613                                        $a_name {} a_name ]} break
 614                        }
 615                        if {$author_abbr eq {}} {
 616                                set author_abbr { |}
 617                        } else {
 618                                set author_abbr [string range $author_abbr 0 3]
 619                        }
 620                        unset a_name
 621
 622                        set first_lno $lno
 623                        while {
 624                           $first_lno > 1
 625                        && $cmit eq [lindex $line_data [expr {$first_lno - 1}] 0]
 626                        && $file eq [lindex $line_data [expr {$first_lno - 1}] 1]
 627                        } {
 628                                incr first_lno -1
 629                        }
 630
 631                        set color {}
 632                        if {$first_lno < $lno} {
 633                                foreach g [$w_file tag names $first_lno.0] {
 634                                        if {[regexp {^color[0-9]+$} $g]} {
 635                                                set color $g
 636                                                break
 637                                        }
 638                                }
 639                        } else {
 640                                set i [lsort [concat \
 641                                        [$w_file tag names "[expr {$first_lno - 1}].0"] \
 642                                        [$w_file tag names "[expr {$lno + $n}].0"] \
 643                                        ]]
 644                                for {set g 0} {$g < [llength $group_colors]} {incr g} {
 645                                        if {[lsearch -sorted -exact $i color$g] == -1} {
 646                                                set color color$g
 647                                                break
 648                                        }
 649                                }
 650                        }
 651                        if {$color eq {}} {
 652                                set color color0
 653                        }
 654
 655                        while {$n > 0} {
 656                                set lno_e "$lno.0 lineend + 1c"
 657                                if {[lindex $line_data $lno] ne {}} {
 658                                        set g [lindex $line_data $lno 0]
 659                                        foreach i $w_columns {
 660                                                $i tag remove g$g $lno.0 $lno_e
 661                                        }
 662                                }
 663                                lset line_data $lno [list $cmit $file $oln]
 664
 665                                $cur_w delete $lno.0 "$lno.0 lineend"
 666                                if {$lno == $first_lno} {
 667                                        $cur_w insert $lno.0 $commit_abbr $commit_type
 668                                } elseif {$lno == [expr {$first_lno + 1}]} {
 669                                        $cur_w insert $lno.0 $author_abbr author_abbr
 670                                } else {
 671                                        $cur_w insert $lno.0 { |}
 672                                }
 673
 674                                foreach i $w_columns {
 675                                        if {$cur_w eq $w_amov} {
 676                                                for {set g 0} \
 677                                                        {$g < [llength $group_colors]} \
 678                                                        {incr g} {
 679                                                        $i tag remove color$g $lno.0 $lno_e
 680                                                }
 681                                                $i tag add $color $lno.0 $lno_e
 682                                        }
 683                                        $i tag add g$cmit $lno.0 $lno_e
 684                                }
 685
 686                                if {$highlight_column eq $cur_w} {
 687                                        if {$highlight_line == -1
 688                                         && [lindex [$w_file yview] 0] == 0} {
 689                                                $w_file see $lno.0
 690                                                set highlight_line $lno
 691                                        }
 692                                        if {$highlight_line == $lno} {
 693                                                _showcommit $this $cur_w $lno
 694                                        }
 695                                }
 696
 697                                incr n -1
 698                                incr lno
 699                                incr oln
 700                                incr blame_lines
 701                        }
 702
 703                        while {
 704                           $cmit eq [lindex $line_data $lno 0]
 705                        && $file eq [lindex $line_data $lno 1]
 706                        } {
 707                                $cur_w delete $lno.0 "$lno.0 lineend"
 708
 709                                if {$lno == $first_lno} {
 710                                        $cur_w insert $lno.0 $commit_abbr $commit_type
 711                                } elseif {$lno == [expr {$first_lno + 1}]} {
 712                                        $cur_w insert $lno.0 $author_abbr author_abbr
 713                                } else {
 714                                        $cur_w insert $lno.0 { |}
 715                                }
 716
 717                                if {$cur_w eq $w_amov} {
 718                                        foreach i $w_columns {
 719                                                for {set g 0} \
 720                                                        {$g < [llength $group_colors]} \
 721                                                        {incr g} {
 722                                                        $i tag remove color$g $lno.0 $lno_e
 723                                                }
 724                                                $i tag add $color $lno.0 $lno_e
 725                                        }
 726                                }
 727
 728                                incr lno
 729                        }
 730
 731                } elseif {[regexp {^([a-z-]+) (.*)$} $line line key data]} {
 732                        set header($r_commit,$key) $data
 733                }
 734        }
 735        $cur_w conf -state disabled
 736
 737        if {[eof $fd]} {
 738                close $fd
 739                if {$cur_w eq $w_asim} {
 740                        # Switches for original location detection
 741                        set threshold [get_config gui.copyblamethreshold]
 742                        set original_options [list "-C$threshold"]
 743
 744                        if {![is_config_true gui.fastcopyblame]} {
 745                                # thorough copy search; insert before the threshold
 746                                set original_options [linsert $original_options 0 -C]
 747                        }
 748                        if {[git-version >= 1.5.3]} {
 749                                lappend original_options -w ; # ignore indentation changes
 750                        }
 751
 752                        _exec_blame $this $w_amov @amov_data \
 753                                $original_options \
 754                                [mc "Loading original location annotations..."]
 755                } else {
 756                        set current_fd {}
 757                        $status stop [mc "Annotation complete."]
 758                }
 759        } else {
 760                $status update $blame_lines $total_lines
 761        }
 762} ifdeleted { catch {close $fd} }
 763
 764method _find_commit_bound {data_list start_idx delta} {
 765        upvar #0 $data_list line_data
 766        set pos $start_idx
 767        set limit       [expr {[llength $line_data] - 1}]
 768        set base_commit [lindex $line_data $pos 0]
 769
 770        while {$pos > 0 && $pos < $limit} {
 771                set new_pos [expr {$pos + $delta}]
 772                if {[lindex $line_data $new_pos 0] ne $base_commit} {
 773                        return $pos
 774                }
 775
 776                set pos $new_pos
 777        }
 778
 779        return $pos
 780}
 781
 782method _fullcopyblame {} {
 783        if {$current_fd ne {}} {
 784                tk_messageBox \
 785                        -icon error \
 786                        -type ok \
 787                        -title [mc "Busy"] \
 788                        -message [mc "Annotation process is already running."]
 789
 790                return
 791        }
 792
 793        # Switches for original location detection
 794        set threshold [get_config gui.copyblamethreshold]
 795        set original_options [list -C -C "-C$threshold"]
 796
 797        if {[git-version >= 1.5.3]} {
 798                lappend original_options -w ; # ignore indentation changes
 799        }
 800
 801        # Find the line range
 802        set pos @$::cursorX,$::cursorY
 803        set lno [lindex [split [$::cursorW index $pos] .] 0]
 804        set min_amov_lno [_find_commit_bound $this @amov_data $lno -1]
 805        set max_amov_lno [_find_commit_bound $this @amov_data $lno 1]
 806        set min_asim_lno [_find_commit_bound $this @asim_data $lno -1]
 807        set max_asim_lno [_find_commit_bound $this @asim_data $lno 1]
 808
 809        if {$min_asim_lno < $min_amov_lno} {
 810                set min_amov_lno $min_asim_lno
 811        }
 812
 813        if {$max_asim_lno > $max_amov_lno} {
 814                set max_amov_lno $max_asim_lno
 815        }
 816
 817        lappend original_options -L "$min_amov_lno,$max_amov_lno"
 818
 819        # Clear lines
 820        for {set i $min_amov_lno} {$i <= $max_amov_lno} {incr i} {
 821                lset amov_data $i [list ]
 822        }
 823
 824        # Start the back-end process
 825        _exec_blame $this $w_amov @amov_data \
 826                $original_options \
 827                [mc "Running thorough copy detection..."]
 828}
 829
 830method _click {cur_w pos} {
 831        set lno [lindex [split [$cur_w index $pos] .] 0]
 832        _showcommit $this $cur_w $lno
 833}
 834
 835method _setencoding {enc} {
 836        force_path_encoding $path $enc
 837        _load $this [list \
 838                $highlight_column \
 839                $highlight_line \
 840                [lindex [$w_file xview] 0] \
 841                [lindex [$w_file yview] 0] \
 842                ]
 843}
 844
 845method _load_commit {cur_w cur_d pos} {
 846        upvar #0 $cur_d line_data
 847        set lno [lindex [split [$cur_w index $pos] .] 0]
 848        set dat [lindex $line_data $lno]
 849        if {$dat ne {}} {
 850                _load_new_commit $this  \
 851                        [lindex $dat 0] \
 852                        [lindex $dat 1] \
 853                        [list [lindex $dat 2]]
 854        }
 855}
 856
 857method _load_new_commit {new_commit new_path jump} {
 858        lappend history [list \
 859                $commit $path \
 860                $highlight_column \
 861                $highlight_line \
 862                [lindex [$w_file xview] 0] \
 863                [lindex [$w_file yview] 0] \
 864                ]
 865
 866        set commit $new_commit
 867        set path   $new_path
 868        _load $this $jump
 869}
 870
 871method _showcommit {cur_w lno} {
 872        global repo_config
 873        variable active_color
 874
 875        if {$highlight_commit ne {}} {
 876                foreach i $w_columns {
 877                        $i tag conf g$highlight_commit -background {}
 878                        $i tag lower g$highlight_commit
 879                }
 880        }
 881
 882        if {$cur_w eq $w_asim} {
 883                set dat [lindex $asim_data $lno]
 884                set highlight_column $w_asim
 885        } else {
 886                set dat [lindex $amov_data $lno]
 887                set highlight_column $w_amov
 888        }
 889
 890        $w_cviewer conf -state normal
 891        $w_cviewer delete 0.0 end
 892
 893        if {$dat eq {}} {
 894                set cmit {}
 895                $w_cviewer insert end [mc "Loading annotation..."] still_loading
 896        } else {
 897                set cmit [lindex $dat 0]
 898                set file [lindex $dat 1]
 899
 900                foreach i $w_columns {
 901                        $i tag conf g$cmit -background $active_color
 902                        $i tag raise g$cmit
 903                        if {$i eq $w_file} {
 904                                $w_file tag raise found
 905                        }
 906                        $i tag raise sel
 907                }
 908
 909                set author_name {}
 910                set author_email {}
 911                set author_time {}
 912                catch {set author_name $header($cmit,author)}
 913                catch {set author_email $header($cmit,author-mail)}
 914                catch {set author_time [format_date $header($cmit,author-time)]}
 915
 916                set committer_name {}
 917                set committer_email {}
 918                set committer_time {}
 919                catch {set committer_name $header($cmit,committer)}
 920                catch {set committer_email $header($cmit,committer-mail)}
 921                catch {set committer_time [format_date $header($cmit,committer-time)]}
 922
 923                if {[catch {set msg $header($cmit,message)}]} {
 924                        set msg {}
 925                        catch {
 926                                set fd [git_read cat-file commit $cmit]
 927                                fconfigure $fd -encoding binary -translation lf
 928                                if {[catch {set enc $repo_config(i18n.commitencoding)}]} {
 929                                        set enc utf-8
 930                                }
 931                                while {[gets $fd line] > 0} {
 932                                        if {[string match {encoding *} $line]} {
 933                                                set enc [string tolower [string range $line 9 end]]
 934                                        }
 935                                }
 936                                set msg [read $fd]
 937                                close $fd
 938
 939                                set enc [tcl_encoding $enc]
 940                                if {$enc ne {}} {
 941                                        set msg [encoding convertfrom $enc $msg]
 942                                }
 943                                set msg [string trim $msg]
 944                        }
 945                        set header($cmit,message) $msg
 946                }
 947
 948                $w_cviewer insert end "commit $cmit\n" header_key
 949                $w_cviewer insert end [strcat [mc "Author:"] "\t"] header_key
 950                $w_cviewer insert end "$author_name $author_email" header_val
 951                $w_cviewer insert end "  $author_time\n" header_val
 952
 953                $w_cviewer insert end [strcat [mc "Committer:"] "\t"] header_key
 954                $w_cviewer insert end "$committer_name $committer_email" header_val
 955                $w_cviewer insert end "  $committer_time\n" header_val
 956
 957                if {$file ne $path} {
 958                        $w_cviewer insert end [strcat [mc "Original File:"] "\t"] header_key
 959                        $w_cviewer insert end "[escape_path $file]\n" header_val
 960                }
 961
 962                $w_cviewer insert end "\n$msg"
 963        }
 964        $w_cviewer conf -state disabled
 965
 966        set highlight_line $lno
 967        set highlight_commit $cmit
 968
 969        if {[lsearch -exact $tooltip_commit $highlight_commit] != -1} {
 970                _hide_tooltip $this
 971        }
 972}
 973
 974method _get_click_amov_info {} {
 975        set pos @$::cursorX,$::cursorY
 976        set lno [lindex [split [$::cursorW index $pos] .] 0]
 977        return [lindex $amov_data $lno]
 978}
 979
 980method _copycommit {} {
 981        set dat [_get_click_amov_info $this]
 982        if {$dat ne {}} {
 983                clipboard clear
 984                clipboard append \
 985                        -format STRING \
 986                        -type STRING \
 987                        -- [lindex $dat 0]
 988        }
 989}
 990
 991method _format_offset_date {base offset} {
 992        set exval [expr {$base + $offset*24*60*60}]
 993        return [clock format $exval -format {%Y-%m-%d}]
 994}
 995
 996method _gitkcommit {} {
 997        global nullid
 998
 999        set dat [_get_click_amov_info $this]
1000        if {$dat ne {}} {
1001                set cmit [lindex $dat 0]
1002
1003                # If the line belongs to the working copy, use HEAD instead
1004                if {$cmit eq $nullid} {
1005                        if {[catch {set cmit [git rev-parse --verify HEAD]} err]} {
1006                                error_popup [strcat [mc "Cannot find HEAD commit:"] "\n\n$err"]
1007                                return;
1008                        }
1009                }
1010
1011                set radius [get_config gui.blamehistoryctx]
1012                set cmdline [list --select-commit=$cmit]
1013
1014                if {$radius > 0} {
1015                        set author_time {}
1016                        set committer_time {}
1017
1018                        catch {set author_time $header($cmit,author-time)}
1019                        catch {set committer_time $header($cmit,committer-time)}
1020
1021                        if {$committer_time eq {}} {
1022                                set committer_time $author_time
1023                        }
1024
1025                        set after_time [_format_offset_date $this $committer_time [expr {-$radius}]]
1026                        set before_time [_format_offset_date $this $committer_time $radius]
1027
1028                        lappend cmdline --after=$after_time --before=$before_time
1029                }
1030
1031                lappend cmdline $cmit
1032
1033                set base_rev "HEAD"
1034                if {$commit ne {}} {
1035                        set base_rev $commit
1036                }
1037
1038                if {$base_rev ne $cmit} {
1039                        lappend cmdline $base_rev
1040                }
1041
1042                do_gitk $cmdline
1043        }
1044}
1045
1046method _blameparent {} {
1047        global nullid
1048
1049        set dat [_get_click_amov_info $this]
1050        if {$dat ne {}} {
1051                set cmit [lindex $dat 0]
1052                set new_path [lindex $dat 1]
1053
1054                # Allow using Blame Parent on lines modified in the working copy
1055                if {$cmit eq $nullid} {
1056                        set parent_ref "HEAD"
1057                } else {
1058                        set parent_ref "$cmit^"
1059                }
1060                if {[catch {set cparent [git rev-parse --verify $parent_ref]} err]} {
1061                        error_popup [strcat [mc "Cannot find parent commit:"] "\n\n$err"]
1062                        return;
1063                }
1064
1065                _kill $this
1066
1067                # Generate a diff between the commit and its parent,
1068                # and use the hunks to update the line number.
1069                # Request zero context to simplify calculations.
1070                if {$cmit eq $nullid} {
1071                        set diffcmd [list diff-index --unified=0 $cparent -- $new_path]
1072                } else {
1073                        set diffcmd [list diff-tree --unified=0 $cparent $cmit -- $new_path]
1074                }
1075                if {[catch {set fd [eval git_read $diffcmd]} err]} {
1076                        $status stop [mc "Unable to display parent"]
1077                        error_popup [strcat [mc "Error loading diff:"] "\n\n$err"]
1078                        return
1079                }
1080
1081                set r_orig_line [lindex $dat 2]
1082
1083                fconfigure $fd \
1084                        -blocking 0 \
1085                        -encoding binary \
1086                        -translation binary
1087                fileevent $fd readable [cb _read_diff_load_commit \
1088                        $fd $cparent $new_path $r_orig_line]
1089                set current_fd $fd
1090        }
1091}
1092
1093method _read_diff_load_commit {fd cparent new_path tline} {
1094        if {$fd ne $current_fd} {
1095                catch {close $fd}
1096                return
1097        }
1098
1099        while {[gets $fd line] >= 0} {
1100                if {[regexp {^@@ -(\d+)(,(\d+))? \+(\d+)(,(\d+))? @@} $line line \
1101                        old_line osz old_size new_line nsz new_size]} {
1102
1103                        if {$osz eq {}} { set old_size 1 }
1104                        if {$nsz eq {}} { set new_size 1 }
1105
1106                        if {$new_line <= $tline} {
1107                                if {[expr {$new_line + $new_size}] > $tline} {
1108                                        # Target line within the hunk
1109                                        set line_shift [expr {
1110                                                ($new_size-$old_size)*($tline-$new_line)/$new_size
1111                                                }]
1112                                } else {
1113                                        set line_shift [expr {$new_size-$old_size}]
1114                                }
1115
1116                                set r_orig_line [expr {$r_orig_line - $line_shift}]
1117                        }
1118                }
1119        }
1120
1121        if {[eof $fd]} {
1122                close $fd;
1123                set current_fd {}
1124
1125                _load_new_commit $this  \
1126                        $cparent        \
1127                        $new_path       \
1128                        [list $r_orig_line]
1129        }
1130} ifdeleted { catch {close $fd} }
1131
1132method _show_tooltip {cur_w pos} {
1133        if {$tooltip_wm ne {}} {
1134                _open_tooltip $this $cur_w
1135        } elseif {$tooltip_timer eq {}} {
1136                set tooltip_timer [after 1000 [cb _open_tooltip $cur_w]]
1137        }
1138}
1139
1140method _open_tooltip {cur_w} {
1141        set tooltip_timer {}
1142        set pos_x [winfo pointerx $cur_w]
1143        set pos_y [winfo pointery $cur_w]
1144        if {[winfo containing $pos_x $pos_y] ne $cur_w} {
1145                _hide_tooltip $this
1146                return
1147        }
1148
1149        if {$tooltip_wm ne "$cur_w.tooltip"} {
1150                _hide_tooltip $this
1151
1152                set tooltip_wm [toplevel $cur_w.tooltip -borderwidth 1]
1153                wm overrideredirect $tooltip_wm 1
1154                wm transient $tooltip_wm [winfo toplevel $cur_w]
1155                set tooltip_t $tooltip_wm.label
1156                text $tooltip_t \
1157                        -takefocus 0 \
1158                        -highlightthickness 0 \
1159                        -relief flat \
1160                        -borderwidth 0 \
1161                        -wrap none \
1162                        -background lightyellow \
1163                        -foreground black
1164                $tooltip_t tag conf section_header -font font_uibold
1165                pack $tooltip_t
1166        } else {
1167                $tooltip_t conf -state normal
1168                $tooltip_t delete 0.0 end
1169        }
1170
1171        set pos @[join [list \
1172                [expr {$pos_x - [winfo rootx $cur_w]}] \
1173                [expr {$pos_y - [winfo rooty $cur_w]}]] ,]
1174        set lno [lindex [split [$cur_w index $pos] .] 0]
1175        if {$cur_w eq $w_amov} {
1176                set dat [lindex $amov_data $lno]
1177                set org {}
1178        } else {
1179                set dat [lindex $asim_data $lno]
1180                set org [lindex $amov_data $lno]
1181        }
1182
1183        if {$dat eq {}} {
1184                _hide_tooltip $this
1185                return
1186        }
1187
1188        set cmit [lindex $dat 0]
1189        set tooltip_commit [list $cmit]
1190
1191        set author_name {}
1192        set summary     {}
1193        set author_time {}
1194        catch {set author_name $header($cmit,author)}
1195        catch {set summary     $header($cmit,summary)}
1196        catch {set author_time [format_date $header($cmit,author-time)]}
1197
1198        $tooltip_t insert end "commit $cmit\n"
1199        $tooltip_t insert end "$author_name  $author_time\n"
1200        $tooltip_t insert end "$summary"
1201
1202        if {$org ne {} && [lindex $org 0] ne $cmit} {
1203                set save [$tooltip_t get 0.0 end]
1204                $tooltip_t delete 0.0 end
1205
1206                set cmit [lindex $org 0]
1207                set file [lindex $org 1]
1208                lappend tooltip_commit $cmit
1209
1210                set author_name {}
1211                set summary     {}
1212                set author_time {}
1213                catch {set author_name $header($cmit,author)}
1214                catch {set summary     $header($cmit,summary)}
1215                catch {set author_time [format_date $header($cmit,author-time)]}
1216
1217                $tooltip_t insert end [strcat [mc "Originally By:"] "\n"] section_header
1218                $tooltip_t insert end "commit $cmit\n"
1219                $tooltip_t insert end "$author_name  $author_time\n"
1220                $tooltip_t insert end "$summary\n"
1221
1222                if {$file ne $path} {
1223                        $tooltip_t insert end [strcat [mc "In File:"] " "] section_header
1224                        $tooltip_t insert end "$file\n"
1225                }
1226
1227                $tooltip_t insert end "\n"
1228                $tooltip_t insert end [strcat [mc "Copied Or Moved Here By:"] "\n"] section_header
1229                $tooltip_t insert end $save
1230        }
1231
1232        $tooltip_t conf -state disabled
1233        _position_tooltip $this
1234}
1235
1236method _position_tooltip {} {
1237        set max_h [lindex [split [$tooltip_t index end] .] 0]
1238        set max_w 0
1239        for {set i 1} {$i <= $max_h} {incr i} {
1240                set c [lindex [split [$tooltip_t index "$i.0 lineend"] .] 1]
1241                if {$c > $max_w} {set max_w $c}
1242        }
1243        $tooltip_t conf -width $max_w -height $max_h
1244
1245        set req_w [winfo reqwidth  $tooltip_t]
1246        set req_h [winfo reqheight $tooltip_t]
1247        set pos_x [expr {[winfo pointerx .] +  5}]
1248        set pos_y [expr {[winfo pointery .] + 10}]
1249
1250        set g "${req_w}x${req_h}"
1251        if {$pos_x >= 0} {append g +}
1252        append g $pos_x
1253        if {$pos_y >= 0} {append g +}
1254        append g $pos_y
1255
1256        wm geometry $tooltip_wm $g
1257        raise $tooltip_wm
1258}
1259
1260method _hide_tooltip {} {
1261        if {$tooltip_wm ne {}} {
1262                destroy $tooltip_wm
1263                set tooltip_wm {}
1264                set tooltip_commit {}
1265        }
1266        if {$tooltip_timer ne {}} {
1267                after cancel $tooltip_timer
1268                set tooltip_timer {}
1269        }
1270}
1271
1272method _resize {new_height} {
1273        set diff [expr {$new_height - $old_height}]
1274        if {$diff == 0} return
1275
1276        set my [expr {[winfo height $w.file_pane] - 25}]
1277        set o [$w.file_pane sash coord 0]
1278        set ox [lindex $o 0]
1279        set oy [expr {[lindex $o 1] + $diff}]
1280        if {$oy < 0}   {set oy 0}
1281        if {$oy > $my} {set oy $my}
1282        $w.file_pane sash place 0 $ox $oy
1283
1284        set old_height $new_height
1285}
1286
1287}