git-gui: Fix the blame viewer destroy handler.
[git] / lib / blame.tcl
1 # git-gui blame viewer
2 # Copyright (C) 2006, 2007 Shawn Pearce
3
4 class blame {
5
6 image create photo ::blame::img_back_arrow -data {R0lGODlhGAAYAIUAAPwCBEzKXFTSZIz+nGzmhGzqfGTidIT+nEzGXHTqhGzmfGzifFzadETCVES+VARWDFzWbHzyjAReDGTadFTOZDSyRDyyTCymPARaFGTedFzSbDy2TCyqRCyqPARaDAyCHES6VDy6VCyiPAR6HCSeNByWLARyFARiDARqFGTifARiFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAAYABgAAAajQIBwSCwaj8ikcsk0BppJwRPqHEypQwHBis0WDAdEFyBIKBaMAKLBdjQeSkFBYTBAIvgEoS6JmhUTEwIUDQ4VFhcMGEhyCgoZExoUaxsWHB0THkgfAXUGAhoBDSAVFR0XBnCbDRmgog0hpSIiDJpJIyEQhBUcJCIlwA22SSYVogknEg8eD82qSigdDSknY0IqJQXPYxIl1dZCGNvWw+Dm510GQQAh/mhDcmVhdGVkIGJ5IEJNUFRvR0lGIFBybyB2ZXJzaW9uIDIuNQ0KqSBEZXZlbENvciAxOTk3LDE5OTguIEFsbCByaWdodHMgcmVzZXJ2ZWQuDQpodHRwOi8vd3d3LmRldmVsY29yLmNvbQA7}
7
8 # Persistant data (survives loads)
9 #
10 field history {}; # viewer history: {commit path}
11 field header    ; # array commit,key -> header field
12
13 # Tk UI control paths
14 #
15 field w          ; # top window in this viewer
16 field w_back     ; # our back button
17 field w_path     ; # label showing the current file path
18 field w_columns  ; # list of all column widgets in the viewer
19 field w_line     ; # text column: all line numbers
20 field w_amov     ; # text column: annotations + move tracking
21 field w_asim     ; # text column: annotations (simple computation)
22 field w_file     ; # text column: actual file data
23 field w_cviewer  ; # pane showing commit message
24 field finder     ; # find mini-dialog frame
25 field status     ; # status mega-widget instance
26 field old_height ; # last known height of $w.file_pane
27
28
29 # Tk UI colors
30 #
31 variable active_color #c0edc5
32 variable group_colors {
33         #d6d6d6
34         #e1e1e1
35         #ececec
36 }
37
38 # Current blame data; cleared/reset on each load
39 #
40 field commit               ; # input commit to blame
41 field path                 ; # input filename to view in $commit
42
43 field current_fd        {} ; # background process running
44 field highlight_line    -1 ; # current line selected
45 field highlight_column  {} ; # current commit column selected
46 field highlight_commit  {} ; # sha1 of commit selected
47
48 field total_lines       0  ; # total length of file
49 field blame_lines       0  ; # number of lines computed
50 field amov_data            ; # list of {commit origfile origline}
51 field asim_data            ; # list of {commit origfile origline}
52
53 field r_commit             ; # commit currently being parsed
54 field r_orig_line          ; # original line number
55 field r_final_line         ; # final line number
56 field r_line_count         ; # lines in this region
57
58 field tooltip_wm        {} ; # Current tooltip toplevel, if open
59 field tooltip_t         {} ; # Text widget in $tooltip_wm
60 field tooltip_timer     {} ; # Current timer event for our tooltip
61 field tooltip_commit    {} ; # Commit(s) in tooltip
62
63 constructor 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 _handle_destroy %W]
381
382         _load $this $i_jump
383 }
384
385 method _handle_destroy {win} {
386         if {$win eq $w} {
387                 _kill $this
388                 delete_this
389         }
390 }
391
392 method _kill {} {
393         if {$current_fd ne {}} {
394                 kill_file_process $current_fd
395                 catch {close $current_fd}
396                 set current_fd {}
397         }
398 }
399
400 method _load {jump} {
401         variable group_colors
402
403         _hide_tooltip $this
404
405         if {$total_lines != 0 || $current_fd ne {}} {
406                 _kill $this
407
408                 foreach i $w_columns {
409                         $i conf -state normal
410                         $i delete 0.0 end
411                         foreach g [$i tag names] {
412                                 if {[regexp {^g[0-9a-f]{40}$} $g]} {
413                                         $i tag delete $g
414                                 }
415                         }
416                         $i conf -state disabled
417                 }
418
419                 $w_cviewer conf -state normal
420                 $w_cviewer delete 0.0 end
421                 $w_cviewer conf -state disabled
422
423                 set highlight_line -1
424                 set highlight_column {}
425                 set highlight_commit {}
426                 set total_lines 0
427         }
428
429         if {$history eq {}} {
430                 $w_back conf -state disabled
431         } else {
432                 $w_back conf -state normal
433         }
434
435         # Index 0 is always empty.  There is never line 0 as
436         # we use only 1 based lines, as that matches both with
437         # git-blame output and with Tk's text widget.
438         #
439         set amov_data [list [list]]
440         set asim_data [list [list]]
441
442         $status show [mc "Reading %s..." "$commit:[escape_path $path]"]
443         $w_path conf -text [escape_path $path]
444         if {$commit eq {}} {
445                 set fd [open $path r]
446                 fconfigure $fd -eofchar {}
447         } else {
448                 set fd [git_read cat-file blob "$commit:$path"]
449         }
450         fconfigure $fd \
451                 -blocking 0 \
452                 -translation lf \
453                 -encoding [get_path_encoding $path]
454         fileevent $fd readable [cb _read_file $fd $jump]
455         set current_fd $fd
456 }
457
458 method _history_menu {} {
459         set m $w.backmenu
460         if {[winfo exists $m]} {
461                 $m delete 0 end
462         } else {
463                 menu $m -tearoff 0
464         }
465
466         for {set i [expr {[llength $history] - 1}]
467                 } {$i >= 0} {incr i -1} {
468                 set e [lindex $history $i]
469                 set c [lindex $e 0]
470                 set f [lindex $e 1]
471
472                 if {[regexp {^[0-9a-f]{40}$} $c]} {
473                         set t [string range $c 0 8]...
474                 } elseif {$c eq {}} {
475                         set t {Working Directory}
476                 } else {
477                         set t $c
478                 }
479                 if {![catch {set summary $header($c,summary)}]} {
480                         append t " $summary"
481                         if {[string length $t] > 70} {
482                                 set t [string range $t 0 66]...
483                         }
484                 }
485
486                 $m add command -label $t -command [cb _goback $i]
487         }
488         set X [winfo rootx $w_back]
489         set Y [expr {[winfo rooty $w_back] + [winfo height $w_back]}]
490         tk_popup $m $X $Y
491 }
492
493 method _goback {i} {
494         set dat [lindex $history $i]
495         set history [lrange $history 0 [expr {$i - 1}]]
496         set commit [lindex $dat 0]
497         set path [lindex $dat 1]
498         _load $this [lrange $dat 2 5]
499 }
500
501 method _read_file {fd jump} {
502         if {$fd ne $current_fd} {
503                 catch {close $fd}
504                 return
505         }
506
507         foreach i $w_columns {$i conf -state normal}
508         while {[gets $fd line] >= 0} {
509                 regsub "\r\$" $line {} line
510                 incr total_lines
511                 lappend amov_data {}
512                 lappend asim_data {}
513
514                 if {$total_lines > 1} {
515                         foreach i $w_columns {$i insert end "\n"}
516                 }
517
518                 $w_line insert end "$total_lines" linenumber
519                 $w_file insert end "$line"
520         }
521
522         set ln_wc [expr {[string length $total_lines] + 2}]
523         if {[$w_line cget -width] < $ln_wc} {
524                 $w_line conf -width $ln_wc
525         }
526
527         foreach i $w_columns {$i conf -state disabled}
528
529         if {[eof $fd]} {
530                 close $fd
531
532                 # If we don't force Tk to update the widgets *right now*
533                 # none of our jump commands will cause a change in the UI.
534                 #
535                 update
536
537                 if {[llength $jump] == 1} {
538                         set highlight_line [lindex $jump 0]
539                         $w_file see "$highlight_line.0"
540                 } elseif {[llength $jump] == 4} {
541                         set highlight_column [lindex $jump 0]
542                         set highlight_line [lindex $jump 1]
543                         $w_file xview moveto [lindex $jump 2]
544                         $w_file yview moveto [lindex $jump 3]
545                 }
546
547                 _exec_blame $this $w_asim @asim_data \
548                         [list] \
549                         [mc "Loading copy/move tracking annotations..."]
550         }
551 } ifdeleted { catch {close $fd} }
552
553 method _exec_blame {cur_w cur_d options cur_s} {
554         lappend options --incremental
555         if {$commit eq {}} {
556                 lappend options --contents $path
557         } else {
558                 lappend options $commit
559         }
560         lappend options -- $path
561         set fd [eval git_read --nice blame $options]
562         fconfigure $fd -blocking 0 -translation lf -encoding utf-8
563         fileevent $fd readable [cb _read_blame $fd $cur_w $cur_d]
564         set current_fd $fd
565         set blame_lines 0
566
567         $status start \
568                 $cur_s \
569                 [mc "lines annotated"]
570 }
571
572 method _read_blame {fd cur_w cur_d} {
573         upvar #0 $cur_d line_data
574         variable group_colors
575
576         if {$fd ne $current_fd} {
577                 catch {close $fd}
578                 return
579         }
580
581         $cur_w conf -state normal
582         while {[gets $fd line] >= 0} {
583                 if {[regexp {^([a-z0-9]{40}) (\d+) (\d+) (\d+)$} $line line \
584                         cmit original_line final_line line_count]} {
585                         set r_commit     $cmit
586                         set r_orig_line  $original_line
587                         set r_final_line $final_line
588                         set r_line_count $line_count
589                 } elseif {[string match {filename *} $line]} {
590                         set file [string range $line 9 end]
591                         set n    $r_line_count
592                         set lno  $r_final_line
593                         set oln  $r_orig_line
594                         set cmit $r_commit
595
596                         if {[regexp {^0{40}$} $cmit]} {
597                                 set commit_abbr work
598                                 set commit_type curr_commit
599                         } elseif {$cmit eq $commit} {
600                                 set commit_abbr this
601                                 set commit_type curr_commit
602                         } else {
603                                 set commit_type prior_commit
604                                 set commit_abbr [string range $cmit 0 3]
605                         }
606
607                         set author_abbr {}
608                         set a_name {}
609                         catch {set a_name $header($cmit,author)}
610                         while {$a_name ne {}} {
611                                 if {$author_abbr ne {}
612                                         && [string index $a_name 0] eq {'}} {
613                                         regsub {^'[^']+'\s+} $a_name {} a_name
614                                 }
615                                 if {![regexp {^([[:upper:]])} $a_name _a]} break
616                                 append author_abbr $_a
617                                 unset _a
618                                 if {![regsub \
619                                         {^[[:upper:]][^\s]*\s+} \
620                                         $a_name {} a_name ]} break
621                         }
622                         if {$author_abbr eq {}} {
623                                 set author_abbr { |}
624                         } else {
625                                 set author_abbr [string range $author_abbr 0 3]
626                         }
627                         unset a_name
628
629                         set first_lno $lno
630                         while {
631                            $first_lno > 1
632                         && $cmit eq [lindex $line_data [expr {$first_lno - 1}] 0]
633                         && $file eq [lindex $line_data [expr {$first_lno - 1}] 1]
634                         } {
635                                 incr first_lno -1
636                         }
637
638                         set color {}
639                         if {$first_lno < $lno} {
640                                 foreach g [$w_file tag names $first_lno.0] {
641                                         if {[regexp {^color[0-9]+$} $g]} {
642                                                 set color $g
643                                                 break
644                                         }
645                                 }
646                         } else {
647                                 set i [lsort [concat \
648                                         [$w_file tag names "[expr {$first_lno - 1}].0"] \
649                                         [$w_file tag names "[expr {$lno + $n}].0"] \
650                                         ]]
651                                 for {set g 0} {$g < [llength $group_colors]} {incr g} {
652                                         if {[lsearch -sorted -exact $i color$g] == -1} {
653                                                 set color color$g
654                                                 break
655                                         }
656                                 }
657                         }
658                         if {$color eq {}} {
659                                 set color color0
660                         }
661
662                         while {$n > 0} {
663                                 set lno_e "$lno.0 lineend + 1c"
664                                 if {[lindex $line_data $lno] ne {}} {
665                                         set g [lindex $line_data $lno 0]
666                                         foreach i $w_columns {
667                                                 $i tag remove g$g $lno.0 $lno_e
668                                         }
669                                 }
670                                 lset line_data $lno [list $cmit $file $oln]
671
672                                 $cur_w delete $lno.0 "$lno.0 lineend"
673                                 if {$lno == $first_lno} {
674                                         $cur_w insert $lno.0 $commit_abbr $commit_type
675                                 } elseif {$lno == [expr {$first_lno + 1}]} {
676                                         $cur_w insert $lno.0 $author_abbr author_abbr
677                                 } else {
678                                         $cur_w insert $lno.0 { |}
679                                 }
680
681                                 foreach i $w_columns {
682                                         if {$cur_w eq $w_amov} {
683                                                 for {set g 0} \
684                                                         {$g < [llength $group_colors]} \
685                                                         {incr g} {
686                                                         $i tag remove color$g $lno.0 $lno_e
687                                                 }
688                                                 $i tag add $color $lno.0 $lno_e
689                                         }
690                                         $i tag add g$cmit $lno.0 $lno_e
691                                 }
692
693                                 if {$highlight_column eq $cur_w} {
694                                         if {$highlight_line == -1
695                                          && [lindex [$w_file yview] 0] == 0} {
696                                                 $w_file see $lno.0
697                                                 set highlight_line $lno
698                                         }
699                                         if {$highlight_line == $lno} {
700                                                 _showcommit $this $cur_w $lno
701                                         }
702                                 }
703
704                                 incr n -1
705                                 incr lno
706                                 incr oln
707                                 incr blame_lines
708                         }
709
710                         while {
711                            $cmit eq [lindex $line_data $lno 0]
712                         && $file eq [lindex $line_data $lno 1]
713                         } {
714                                 $cur_w delete $lno.0 "$lno.0 lineend"
715
716                                 if {$lno == $first_lno} {
717                                         $cur_w insert $lno.0 $commit_abbr $commit_type
718                                 } elseif {$lno == [expr {$first_lno + 1}]} {
719                                         $cur_w insert $lno.0 $author_abbr author_abbr
720                                 } else {
721                                         $cur_w insert $lno.0 { |}
722                                 }
723
724                                 if {$cur_w eq $w_amov} {
725                                         foreach i $w_columns {
726                                                 for {set g 0} \
727                                                         {$g < [llength $group_colors]} \
728                                                         {incr g} {
729                                                         $i tag remove color$g $lno.0 $lno_e
730                                                 }
731                                                 $i tag add $color $lno.0 $lno_e
732                                         }
733                                 }
734
735                                 incr lno
736                         }
737
738                 } elseif {[regexp {^([a-z-]+) (.*)$} $line line key data]} {
739                         set header($r_commit,$key) $data
740                 }
741         }
742         $cur_w conf -state disabled
743
744         if {[eof $fd]} {
745                 close $fd
746                 if {$cur_w eq $w_asim} {
747                         # Switches for original location detection
748                         set threshold [get_config gui.copyblamethreshold]
749                         set original_options [list "-C$threshold"]
750
751                         if {![is_config_true gui.fastcopyblame]} {
752                                 # thorough copy search; insert before the threshold
753                                 set original_options [linsert $original_options 0 -C]
754                         }
755                         if {[git-version >= 1.5.3]} {
756                                 lappend original_options -w ; # ignore indentation changes
757                         }
758
759                         _exec_blame $this $w_amov @amov_data \
760                                 $original_options \
761                                 [mc "Loading original location annotations..."]
762                 } else {
763                         set current_fd {}
764                         $status stop [mc "Annotation complete."]
765                 }
766         } else {
767                 $status update $blame_lines $total_lines
768         }
769 } ifdeleted { catch {close $fd} }
770
771 method _find_commit_bound {data_list start_idx delta} {
772         upvar #0 $data_list line_data
773         set pos $start_idx
774         set limit       [expr {[llength $line_data] - 1}]
775         set base_commit [lindex $line_data $pos 0]
776
777         while {$pos > 0 && $pos < $limit} {
778                 set new_pos [expr {$pos + $delta}]
779                 if {[lindex $line_data $new_pos 0] ne $base_commit} {
780                         return $pos
781                 }
782
783                 set pos $new_pos
784         }
785
786         return $pos
787 }
788
789 method _fullcopyblame {} {
790         if {$current_fd ne {}} {
791                 tk_messageBox \
792                         -icon error \
793                         -type ok \
794                         -title [mc "Busy"] \
795                         -message [mc "Annotation process is already running."]
796
797                 return
798         }
799
800         # Switches for original location detection
801         set threshold [get_config gui.copyblamethreshold]
802         set original_options [list -C -C "-C$threshold"]
803
804         if {[git-version >= 1.5.3]} {
805                 lappend original_options -w ; # ignore indentation changes
806         }
807
808         # Find the line range
809         set pos @$::cursorX,$::cursorY
810         set lno [lindex [split [$::cursorW index $pos] .] 0]
811         set min_amov_lno [_find_commit_bound $this @amov_data $lno -1]
812         set max_amov_lno [_find_commit_bound $this @amov_data $lno 1]
813         set min_asim_lno [_find_commit_bound $this @asim_data $lno -1]
814         set max_asim_lno [_find_commit_bound $this @asim_data $lno 1]
815
816         if {$min_asim_lno < $min_amov_lno} {
817                 set min_amov_lno $min_asim_lno
818         }
819
820         if {$max_asim_lno > $max_amov_lno} {
821                 set max_amov_lno $max_asim_lno
822         }
823
824         lappend original_options -L "$min_amov_lno,$max_amov_lno"
825
826         # Clear lines
827         for {set i $min_amov_lno} {$i <= $max_amov_lno} {incr i} {
828                 lset amov_data $i [list ]
829         }
830
831         # Start the back-end process
832         _exec_blame $this $w_amov @amov_data \
833                 $original_options \
834                 [mc "Running thorough copy detection..."]
835 }
836
837 method _click {cur_w pos} {
838         set lno [lindex [split [$cur_w index $pos] .] 0]
839         _showcommit $this $cur_w $lno
840 }
841
842 method _setencoding {enc} {
843         force_path_encoding $path $enc
844         _load $this [list \
845                 $highlight_column \
846                 $highlight_line \
847                 [lindex [$w_file xview] 0] \
848                 [lindex [$w_file yview] 0] \
849                 ]
850 }
851
852 method _load_commit {cur_w cur_d pos} {
853         upvar #0 $cur_d line_data
854         set lno [lindex [split [$cur_w index $pos] .] 0]
855         set dat [lindex $line_data $lno]
856         if {$dat ne {}} {
857                 _load_new_commit $this  \
858                         [lindex $dat 0] \
859                         [lindex $dat 1] \
860                         [list [lindex $dat 2]]
861         }
862 }
863
864 method _load_new_commit {new_commit new_path jump} {
865         lappend history [list \
866                 $commit $path \
867                 $highlight_column \
868                 $highlight_line \
869                 [lindex [$w_file xview] 0] \
870                 [lindex [$w_file yview] 0] \
871                 ]
872
873         set commit $new_commit
874         set path   $new_path
875         _load $this $jump
876 }
877
878 method _showcommit {cur_w lno} {
879         global repo_config
880         variable active_color
881
882         if {$highlight_commit ne {}} {
883                 foreach i $w_columns {
884                         $i tag conf g$highlight_commit -background {}
885                         $i tag lower g$highlight_commit
886                 }
887         }
888
889         if {$cur_w eq $w_asim} {
890                 set dat [lindex $asim_data $lno]
891                 set highlight_column $w_asim
892         } else {
893                 set dat [lindex $amov_data $lno]
894                 set highlight_column $w_amov
895         }
896
897         $w_cviewer conf -state normal
898         $w_cviewer delete 0.0 end
899
900         if {$dat eq {}} {
901                 set cmit {}
902                 $w_cviewer insert end [mc "Loading annotation..."] still_loading
903         } else {
904                 set cmit [lindex $dat 0]
905                 set file [lindex $dat 1]
906
907                 foreach i $w_columns {
908                         $i tag conf g$cmit -background $active_color
909                         $i tag raise g$cmit
910                         if {$i eq $w_file} {
911                                 $w_file tag raise found
912                         }
913                         $i tag raise sel
914                 }
915
916                 set author_name {}
917                 set author_email {}
918                 set author_time {}
919                 catch {set author_name $header($cmit,author)}
920                 catch {set author_email $header($cmit,author-mail)}
921                 catch {set author_time [format_date $header($cmit,author-time)]}
922
923                 set committer_name {}
924                 set committer_email {}
925                 set committer_time {}
926                 catch {set committer_name $header($cmit,committer)}
927                 catch {set committer_email $header($cmit,committer-mail)}
928                 catch {set committer_time [format_date $header($cmit,committer-time)]}
929
930                 if {[catch {set msg $header($cmit,message)}]} {
931                         set msg {}
932                         catch {
933                                 set fd [git_read cat-file commit $cmit]
934                                 fconfigure $fd -encoding binary -translation lf
935                                 if {[catch {set enc $repo_config(i18n.commitencoding)}]} {
936                                         set enc utf-8
937                                 }
938                                 while {[gets $fd line] > 0} {
939                                         if {[string match {encoding *} $line]} {
940                                                 set enc [string tolower [string range $line 9 end]]
941                                         }
942                                 }
943                                 set msg [read $fd]
944                                 close $fd
945
946                                 set enc [tcl_encoding $enc]
947                                 if {$enc ne {}} {
948                                         set msg [encoding convertfrom $enc $msg]
949                                 }
950                                 set msg [string trim $msg]
951                         }
952                         set header($cmit,message) $msg
953                 }
954
955                 $w_cviewer insert end "commit $cmit\n" header_key
956                 $w_cviewer insert end [strcat [mc "Author:"] "\t"] header_key
957                 $w_cviewer insert end "$author_name $author_email" header_val
958                 $w_cviewer insert end "  $author_time\n" header_val
959
960                 $w_cviewer insert end [strcat [mc "Committer:"] "\t"] header_key
961                 $w_cviewer insert end "$committer_name $committer_email" header_val
962                 $w_cviewer insert end "  $committer_time\n" header_val
963
964                 if {$file ne $path} {
965                         $w_cviewer insert end [strcat [mc "Original File:"] "\t"] header_key
966                         $w_cviewer insert end "[escape_path $file]\n" header_val
967                 }
968
969                 $w_cviewer insert end "\n$msg"
970         }
971         $w_cviewer conf -state disabled
972
973         set highlight_line $lno
974         set highlight_commit $cmit
975
976         if {[lsearch -exact $tooltip_commit $highlight_commit] != -1} {
977                 _hide_tooltip $this
978         }
979 }
980
981 method _get_click_amov_info {} {
982         set pos @$::cursorX,$::cursorY
983         set lno [lindex [split [$::cursorW index $pos] .] 0]
984         return [lindex $amov_data $lno]
985 }
986
987 method _copycommit {} {
988         set dat [_get_click_amov_info $this]
989         if {$dat ne {}} {
990                 clipboard clear
991                 clipboard append \
992                         -format STRING \
993                         -type STRING \
994                         -- [lindex $dat 0]
995         }
996 }
997
998 method _format_offset_date {base offset} {
999         set exval [expr {$base + $offset*24*60*60}]
1000         return [clock format $exval -format {%Y-%m-%d}]
1001 }
1002
1003 method _gitkcommit {} {
1004         global nullid
1005
1006         set dat [_get_click_amov_info $this]
1007         if {$dat ne {}} {
1008                 set cmit [lindex $dat 0]
1009
1010                 # If the line belongs to the working copy, use HEAD instead
1011                 if {$cmit eq $nullid} {
1012                         if {[catch {set cmit [git rev-parse --verify HEAD]} err]} {
1013                                 error_popup [strcat [mc "Cannot find HEAD commit:"] "\n\n$err"]
1014                                 return;
1015                         }
1016                 }
1017
1018                 set radius [get_config gui.blamehistoryctx]
1019                 set cmdline [list --select-commit=$cmit]
1020
1021                 if {$radius > 0} {
1022                         set author_time {}
1023                         set committer_time {}
1024
1025                         catch {set author_time $header($cmit,author-time)}
1026                         catch {set committer_time $header($cmit,committer-time)}
1027
1028                         if {$committer_time eq {}} {
1029                                 set committer_time $author_time
1030                         }
1031
1032                         set after_time [_format_offset_date $this $committer_time [expr {-$radius}]]
1033                         set before_time [_format_offset_date $this $committer_time $radius]
1034
1035                         lappend cmdline --after=$after_time --before=$before_time
1036                 }
1037
1038                 lappend cmdline $cmit
1039
1040                 set base_rev "HEAD"
1041                 if {$commit ne {}} {
1042                         set base_rev $commit
1043                 }
1044
1045                 if {$base_rev ne $cmit} {
1046                         lappend cmdline $base_rev
1047                 }
1048
1049                 do_gitk $cmdline
1050         }
1051 }
1052
1053 method _blameparent {} {
1054         global nullid
1055
1056         set dat [_get_click_amov_info $this]
1057         if {$dat ne {}} {
1058                 set cmit [lindex $dat 0]
1059                 set new_path [lindex $dat 1]
1060
1061                 # Allow using Blame Parent on lines modified in the working copy
1062                 if {$cmit eq $nullid} {
1063                         set parent_ref "HEAD"
1064                 } else {
1065                         set parent_ref "$cmit^"
1066                 }
1067                 if {[catch {set cparent [git rev-parse --verify $parent_ref]} err]} {
1068                         error_popup [strcat [mc "Cannot find parent commit:"] "\n\n$err"]
1069                         return;
1070                 }
1071
1072                 _kill $this
1073
1074                 # Generate a diff between the commit and its parent,
1075                 # and use the hunks to update the line number.
1076                 # Request zero context to simplify calculations.
1077                 if {$cmit eq $nullid} {
1078                         set diffcmd [list diff-index --unified=0 $cparent -- $new_path]
1079                 } else {
1080                         set diffcmd [list diff-tree --unified=0 $cparent $cmit -- $new_path]
1081                 }
1082                 if {[catch {set fd [eval git_read $diffcmd]} err]} {
1083                         $status stop [mc "Unable to display parent"]
1084                         error_popup [strcat [mc "Error loading diff:"] "\n\n$err"]
1085                         return
1086                 }
1087
1088                 set r_orig_line [lindex $dat 2]
1089
1090                 fconfigure $fd \
1091                         -blocking 0 \
1092                         -encoding binary \
1093                         -translation binary
1094                 fileevent $fd readable [cb _read_diff_load_commit \
1095                         $fd $cparent $new_path $r_orig_line]
1096                 set current_fd $fd
1097         }
1098 }
1099
1100 method _read_diff_load_commit {fd cparent new_path tline} {
1101         if {$fd ne $current_fd} {
1102                 catch {close $fd}
1103                 return
1104         }
1105
1106         while {[gets $fd line] >= 0} {
1107                 if {[regexp {^@@ -(\d+)(,(\d+))? \+(\d+)(,(\d+))? @@} $line line \
1108                         old_line osz old_size new_line nsz new_size]} {
1109
1110                         if {$osz eq {}} { set old_size 1 }
1111                         if {$nsz eq {}} { set new_size 1 }
1112
1113                         if {$new_line <= $tline} {
1114                                 if {[expr {$new_line + $new_size}] > $tline} {
1115                                         # Target line within the hunk
1116                                         set line_shift [expr {
1117                                                 ($new_size-$old_size)*($tline-$new_line)/$new_size
1118                                                 }]
1119                                 } else {
1120                                         set line_shift [expr {$new_size-$old_size}]
1121                                 }
1122
1123                                 set r_orig_line [expr {$r_orig_line - $line_shift}]
1124                         }
1125                 }
1126         }
1127
1128         if {[eof $fd]} {
1129                 close $fd;
1130                 set current_fd {}
1131
1132                 _load_new_commit $this  \
1133                         $cparent        \
1134                         $new_path       \
1135                         [list $r_orig_line]
1136         }
1137 } ifdeleted { catch {close $fd} }
1138
1139 method _show_tooltip {cur_w pos} {
1140         if {$tooltip_wm ne {}} {
1141                 _open_tooltip $this $cur_w
1142         } elseif {$tooltip_timer eq {}} {
1143                 set tooltip_timer [after 1000 [cb _open_tooltip $cur_w]]
1144         }
1145 }
1146
1147 method _open_tooltip {cur_w} {
1148         set tooltip_timer {}
1149         set pos_x [winfo pointerx $cur_w]
1150         set pos_y [winfo pointery $cur_w]
1151         if {[winfo containing $pos_x $pos_y] ne $cur_w} {
1152                 _hide_tooltip $this
1153                 return
1154         }
1155
1156         if {$tooltip_wm ne "$cur_w.tooltip"} {
1157                 _hide_tooltip $this
1158
1159                 set tooltip_wm [toplevel $cur_w.tooltip -borderwidth 1]
1160                 wm overrideredirect $tooltip_wm 1
1161                 wm transient $tooltip_wm [winfo toplevel $cur_w]
1162                 set tooltip_t $tooltip_wm.label
1163                 text $tooltip_t \
1164                         -takefocus 0 \
1165                         -highlightthickness 0 \
1166                         -relief flat \
1167                         -borderwidth 0 \
1168                         -wrap none \
1169                         -background lightyellow \
1170                         -foreground black
1171                 $tooltip_t tag conf section_header -font font_uibold
1172                 pack $tooltip_t
1173         } else {
1174                 $tooltip_t conf -state normal
1175                 $tooltip_t delete 0.0 end
1176         }
1177
1178         set pos @[join [list \
1179                 [expr {$pos_x - [winfo rootx $cur_w]}] \
1180                 [expr {$pos_y - [winfo rooty $cur_w]}]] ,]
1181         set lno [lindex [split [$cur_w index $pos] .] 0]
1182         if {$cur_w eq $w_amov} {
1183                 set dat [lindex $amov_data $lno]
1184                 set org {}
1185         } else {
1186                 set dat [lindex $asim_data $lno]
1187                 set org [lindex $amov_data $lno]
1188         }
1189
1190         if {$dat eq {}} {
1191                 _hide_tooltip $this
1192                 return
1193         }
1194
1195         set cmit [lindex $dat 0]
1196         set tooltip_commit [list $cmit]
1197
1198         set author_name {}
1199         set summary     {}
1200         set author_time {}
1201         catch {set author_name $header($cmit,author)}
1202         catch {set summary     $header($cmit,summary)}
1203         catch {set author_time [format_date $header($cmit,author-time)]}
1204
1205         $tooltip_t insert end "commit $cmit\n"
1206         $tooltip_t insert end "$author_name  $author_time\n"
1207         $tooltip_t insert end "$summary"
1208
1209         if {$org ne {} && [lindex $org 0] ne $cmit} {
1210                 set save [$tooltip_t get 0.0 end]
1211                 $tooltip_t delete 0.0 end
1212
1213                 set cmit [lindex $org 0]
1214                 set file [lindex $org 1]
1215                 lappend tooltip_commit $cmit
1216
1217                 set author_name {}
1218                 set summary     {}
1219                 set author_time {}
1220                 catch {set author_name $header($cmit,author)}
1221                 catch {set summary     $header($cmit,summary)}
1222                 catch {set author_time [format_date $header($cmit,author-time)]}
1223
1224                 $tooltip_t insert end [strcat [mc "Originally By:"] "\n"] section_header
1225                 $tooltip_t insert end "commit $cmit\n"
1226                 $tooltip_t insert end "$author_name  $author_time\n"
1227                 $tooltip_t insert end "$summary\n"
1228
1229                 if {$file ne $path} {
1230                         $tooltip_t insert end [strcat [mc "In File:"] " "] section_header
1231                         $tooltip_t insert end "$file\n"
1232                 }
1233
1234                 $tooltip_t insert end "\n"
1235                 $tooltip_t insert end [strcat [mc "Copied Or Moved Here By:"] "\n"] section_header
1236                 $tooltip_t insert end $save
1237         }
1238
1239         $tooltip_t conf -state disabled
1240         _position_tooltip $this
1241 }
1242
1243 method _position_tooltip {} {
1244         set max_h [lindex [split [$tooltip_t index end] .] 0]
1245         set max_w 0
1246         for {set i 1} {$i <= $max_h} {incr i} {
1247                 set c [lindex [split [$tooltip_t index "$i.0 lineend"] .] 1]
1248                 if {$c > $max_w} {set max_w $c}
1249         }
1250         $tooltip_t conf -width $max_w -height $max_h
1251
1252         set req_w [winfo reqwidth  $tooltip_t]
1253         set req_h [winfo reqheight $tooltip_t]
1254         set pos_x [expr {[winfo pointerx .] +  5}]
1255         set pos_y [expr {[winfo pointery .] + 10}]
1256
1257         set g "${req_w}x${req_h}"
1258         if {$pos_x >= 0} {append g +}
1259         append g $pos_x
1260         if {$pos_y >= 0} {append g +}
1261         append g $pos_y
1262
1263         wm geometry $tooltip_wm $g
1264         raise $tooltip_wm
1265 }
1266
1267 method _hide_tooltip {} {
1268         if {$tooltip_wm ne {}} {
1269                 destroy $tooltip_wm
1270                 set tooltip_wm {}
1271                 set tooltip_commit {}
1272         }
1273         if {$tooltip_timer ne {}} {
1274                 after cancel $tooltip_timer
1275                 set tooltip_timer {}
1276         }
1277 }
1278
1279 method _resize {new_height} {
1280         set diff [expr {$new_height - $old_height}]
1281         if {$diff == 0} return
1282
1283         set my [expr {[winfo height $w.file_pane] - 25}]
1284         set o [$w.file_pane sash coord 0]
1285         set ox [lindex $o 0]
1286         set oy [expr {[lindex $o 1] + $diff}]
1287         if {$oy < 0}   {set oy 0}
1288         if {$oy > $my} {set oy $my}
1289         $w.file_pane sash place 0 $ox $oy
1290
1291         set old_height $new_height
1292 }
1293
1294 }