#!/bin/sh #-*-tcl-*- # the next line restarts using wish \ exec /usr/bin/wish "$0" -- ${1+"$@"} #exec runpjt "$0" -- ${1+"$@"} #exec wish "$0" -- ${1+"$@"} # $Id: tkdiff.tcl ac_extras_dpoole/14 1999/11/22 02:48:05 dpoole $ ############################################################################### # # TkDiff -- A graphical front-end to diff for Unix and NT. # Copyright (C) 1994-1998 by John M. Klassa. # # TkDiff Home Page: http://www.ede.com/free/tkdiff # Mailing list, mail archive, etc. # # Usage: # To interactively pick files: # tkdiff # # Plain files: # tkdiff # # Plain file with conflict markers: # tkdiff -conflict # # Source control AccuRev # tkdiff # tkdiff -v # tkdiff -v -v # # Source control CVS/RCS/Perforce/PVCS/SCCS: # tkdiff (same as -r) # tkdiff -r # tkdiff -r # tkdiff -r -r # tkdiff -r -r # # Options: # -a # -o # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # THINGS TO DO: # # the code that parses the command line ought to be separated from the # code that reads in the files. That way we can parse the command line # right up front and display potential problems on stdout instead of # waiting until the window display. ############################################################################### # get this out of the way -- we want to draw the whole user interface # behind the scenes, then pop up in all of its well-laid-out glory wm withdraw . # set a couple o' globals that we might need sooner than later set g(name) "TkDiff" set g(version) "3.05" set g(nativeMenus) 1 set g(started) 0 # ok, I'll admit -- this is a personal preference. I suppose I ought to # move this into the preferences or remove it entirely. Sue me. :-) option add "*TearOff" false 100 ############################################################################### # determine the name of the temporary directory and the name of # the rc file, both of which are dependent on the platform. ############################################################################### switch $tcl_platform(platform) { windows { if {[info exists env(TEMP)]} { set opts(tmpdir) $env(TEMP) } else { set opts(tmpdir) C:/temp } set basercfile "_tkdiff.rc" } default { # Make menus and buttons prettier option add *Font -*-Helvetica-Medium-R-Normal-*-12-* if {[info exists env(TMPDIR)]} { set opts(tmpdir) $env(TMPDIR) } else { set opts(tmpdir) /tmp } set basercfile ".tkdiffrc" } } ############################################################################### # compute preferences file location. Note that TKDIFFRC can hold either # a directory or a file, though we document it as being a file name ############################################################################### if {[info exists env(TKDIFFRC)]} { set rcfile $env(TKDIFFRC) if {[file isdirectory $rcfile]} { set rcfile [file join $rcfile $basercfile] } } elseif {[info exists env(HOME)]} { set rcfile [file join $env(HOME) $basercfile] } else { set rcfile [file join "/" $basercfile] } ############################################################################### # Fonts are selected based on platform. Can anyone clean this # up by finding one set of fonts that looks good everywhere? # bdo - probably not; fonts are probably best left platform-specific # For windows I personally recommend Monotype.com, free from Microsoft # (not that I like Microsoft, but Monotype is a decent fixed width # font). ############################################################################### if {$tcl_platform(platform) == "windows"} { if {$tk_version >= 8.0} { set font "{{Lucida Console} 7}" # Breaks if you're running set bold "{{Lucida Console} 7}" # Windows with a mono display. } else { # These XFDs are from Sun's font alias file # Also known as 6x13 set font -misc-fixed-medium-r-semicondensed--13-120-75-75-c-60-iso8859-1 # Also known as 6x13bold set bold -misc-fixed-bold-r-semicondensed--13-120-75-75-c-60-iso8859-1 } } else { set font 6x13 set bold 6x13bold } ############################################################################### # more initialization... ############################################################################### array set g { ancfileset 0 changefile "tkdiff-change-bars.out" destroy "" ignore_event,1 0 ignore_event,2 0 ignore_hevent,1 0 ignore_hevent,2 0 initOK 0 mapborder 0 mapheight 0 mergefile "tkdiff-merge.out" returnValue 0 showmerge 0 started 0 mergefileset 0 tempfiles "" thumbMinHeight 10 thumbHeight 10 } array set finfo { pth,1 "" pth,2 "" title {} tmp,1 0 tmp,2 0 } ############################################################################### # These options may be changed at runtime ############################################################################### array set opts { autocenter 1 autoselect 0 colorcbs 0 customCode {} diffcmd "diff" editor "" geometry "80x30" showcbs 1 showln 1 showmap 1 showlineview 0 syncscroll 1 toolbarIcons 1 tagcbs 0 tagln 0 tagtext 1 tabstops 8 } if {$tcl_platform(platform) == "windows"} { set opts(fancyButtons) 1 } else { set opts(fancyButtons) 0 } # reporting options array set report { doSideLeft 0 doLineNumbersLeft 1 doChangeMarkersLeft 1 doTextLeft 1 doSideRight 1 doLineNumbersRight 1 doChangeMarkersRight 1 doTextRight 1 filename "tkdiff.out" } if {[string first "color" [winfo visual .]] >= 0} { # We have color # (but, let's not go crazy...) array set opts [subst { textopt "-background white -foreground black -font $font" currtag "-background blue -foreground yellow" difftag "-background gray -foreground black -font $bold" deltag "-background red1 -foreground black" instag "-background green3 -foreground black" chgtag "-background DodgerBlue1 -foreground black" bytetag "-underline 1 -foreground white -background black" - "-background red1 -foreground red1" + "-background green -foreground green" ! "-background blue -foreground blue" }] } else { # Assume only black and white set bg "black" array set opts [subst { textopt "-background white -foreground black -font $font" currtag "-background black -foreground white" difftag "-background white -foreground black -font $bold" deltag "-background black -foreground white" instag "-background black -foreground white" chgtag "-background black -foreground white" bytetag "-underline 1" - "-background black -foreground white" + "-background black -foreground white" ! "-background black -foreground white" }] } # make sure wrapping is turned off. This might piss off a few people, # but it would screw up the display to have things wrap set opts(textopt) "$opts(textopt) -wrap none" ############################################################################### # Source the rc file, which may override some of the defaults # Any errors will be reported. Before doing so, we need to define the # "define" proc, which lets the rc file have a slightly more human-friendly # interface. Old-style .rc files should still load just fine for now, though # it ought to be noted new .rc files won't be able to be processed by older # versions of TkDiff. That shouldn't be a problem. ############################################################################### proc define {name value} { global opts set opts($name) $value } if {[file exists $rcfile]} { if {[catch {source $rcfile} error]} { set startupError [join [list "There was an error in processing your startup file." "\n$g(name) will still run, but some of your preferences" "\nmay not be in effect." "\n\nFile: $rcfile"\ "\nError: $error"] " "] } } # a hack to handle older preferences files... # if the user has a diffopt defined in their rc file, we'll magically # convert that to diffcmd... if {[info exists opts(diffopt)]} { set opts(diffcmd) "diff $opts(diffopt)" } ############################################################################### # Work-around for bad font approximations, # as suggested by Don Libes (libes@nist.gov). ############################################################################### catch {tk scaling [expr 100.0 / 72]} proc do-exit {{returncode {}}} { global g # we don't particularly care if del-tmp fails. catch {del-tmp} if {$returncode == ""} { set returncode $g(returnValue) } # exit with an appropriate return value exit $returncode } ############################################################################### # Throw up a modal error dialog. ############################################################################### proc do-error {msg} { global argv0 tk_messageBox\ -message "$msg"\ -title "$argv0: Error"\ -icon error\ -type ok } ############################################################################### # Throw up a modal error dialog or print a message to stderr. For # Unix we print to stderr and exit if the main window hasn't been # created, otherwise put up a dialog and throw an exception. ############################################################################### proc fatal-error {msg} { global g tcl_platform if {$tcl_platform(platform) == "windows" || $g(started)} { tk_messageBox\ -title "Error"\ -icon error\ -type ok\ -message $msg error "Fatal" } else { puts stderr $msg del-tmp do-exit 2 } } ############################################################################### # Return user name. Credit to Warren Jones (wjones@tc.fluke.com). ############################################################################### proc whoami {} { global env if {[info exists env(USER)]} { return $env(USER) } if {[info exists env(LOGNAME)]} { return $env(LOGNAME) } if {[info exists env(USERNAME)]} { return $env(USERNAME) } if {[info exists env(VCSID)]} { return $env(VCSID) } if {[catch {exec whoami} whoami]} { return nobody } return $whoami } ############################################################################### # Return the name of a temporary file ############################################################################### proc tmpfile {n} { global opts file join $opts(tmpdir) "[whoami][pid]-$n" } ############################################################################### # Execute a command. # Returns "$stdout $stderr $exitcode" if exit code != 0 ############################################################################### proc run-command {cmd} { global opts errorCode set stderr "" set exitcode 0 set errfile [tmpfile "r"] set failed [catch "$cmd 2>$errfile" stdout] # Read stderr output catch { set hndl [open "$errfile" r] set stderr [read $hndl] close $hndl } if {$failed} { switch [lindex $errorCode 0] { "CHILDSTATUS" { set exitcode [lindex $errorCode 2] } "POSIX" { if {$stderr == ""} { set stderr $stdout } set exitcode -1 } default { set exitcode -1 } } } catch {file delete $errfile} return [list "$stdout" "$stderr" "$exitcode"] } ############################################################################### # Execute a command. Die if unsuccessful. ############################################################################### proc die-unless {cmd file} { global opts errorCode set result [run-command "$cmd >$file"] set stdout [lindex $result 0] set stderr [lindex $result 1] set exitcode [lindex $result 2] if {$exitcode != 0} { fatal-error "$stderr\n$stdout" } } ############################################################################### # Filter PVCS output files that have CR-CR-LF end-of-lines ############################################################################### proc filterCRCRLF {file} { set outfile [tmpfile 9] set inp [open $file r] set out [open $outfile w] fconfigure $inp\ -translation binary fconfigure $out\ -translation binary set CR [format %c 13] while {![eof $inp]} { set line [gets $inp] if {[string length $line] && ![eof $inp]} { regsub\ -all "$CR$CR" $line $CR line puts $out $line } } close $inp close $out file rename\ -force $outfile $file } ############################################################################### # Return the smallest of two values ############################################################################### proc min {a b} { return [expr {$a < $b ? $a : $b}] } ############################################################################### # Return the largest of two values ############################################################################### proc max {a b} { return [expr {$a > $b ? $a : $b}] } ############################################################################### # Toggle change bars ############################################################################### proc do-show-changebars {{show {}}} { global opts global w if {$show != {}} { set opts(showcbs) $show } if {$opts(showcbs)} { grid $w(LeftCB)\ -row 0\ -column 2\ -sticky ns grid $w(RightCB)\ -row 0\ -column 1\ -sticky ns } else { grid forget $w(LeftCB) grid forget $w(RightCB) } } ############################################################################### # Toggle line numbers. ############################################################################### proc do-show-linenumbers {{showLn {}}} { global opts global w if {$showLn != {}} { set opts(showln) $showLn } if {$opts(showln)} { grid $w(LeftInfo)\ -row 0\ -column 1\ -sticky nsew grid $w(RightInfo)\ -row 0\ -column 0\ -sticky nsew } else { grid forget $w(LeftInfo) grid forget $w(RightInfo) } } ############################################################################### # Show line numbers in info windows ############################################################################### proc draw-line-numbers {} { global g global w $w(LeftInfo) configure\ -state normal $w(RightInfo) configure\ -state normal $w(LeftCB) configure\ -state normal $w(RightCB) configure\ -state normal set lines(Left) [lindex [split [$w(LeftText) index end-1lines] .] 0] set lines(Right) [lindex [split [$w(RightText) index end-1lines] .] 0] # Smallest line count set minlines [min $lines(Left) $lines(Right)] # cache all the blank lines for the info and cb windows, and do # one big insert after we're done. This seems to be much quicker # than inserting them in the widgets one line at a time. set linestuff {} set cbstuff {} for {set i 1} {$i < $minlines} {incr i} { append linestuff "$i\n" append cbstuff " \n" ;# for now, just put in place holders... } $w(LeftInfo) insert end $linestuff $w(RightInfo) insert end $linestuff $w(LeftCB) insert end $cbstuff $w(RightCB) insert end $cbstuff # Insert remaining line numbers. We'll cache the stuff to be # inserted so we can do just one call in to the widget. This # should be much faster, relatively speaking, then inserting # data one line at a time. foreach mod {Left Right} { set linestuff {} set cbstuff {} for {set i $minlines} {$i < $lines($mod)} {incr i} { append linestuff "$i\n" append cbstuff " \n" ;# for now, just put in place holders... } $w(${mod}Info) insert end $linestuff $w(${mod}CB) insert end $cbstuff } $w(LeftCB) configure\ -state disabled $w(RightCB) configure\ -state disabled $w(LeftInfo) configure\ -state disabled $w(RightInfo) configure\ -state disabled } ############################################################################### # Pop up a window for file merge. ############################################################################### proc popup-merge {{writeproc merge-write-file}} { global g global w if {$g(mergefileset)} { $writeproc return } set types { {{Text Files} {.txt}} {{All Files} {*}} } set path [tk_getSaveFile\ -defaultextension ".tcl"\ -filetypes $types\ -initialfile [file nativename $g(mergefile)]] if {[string length $path] > 0} { set g(mergefile) $path $writeproc } } ############################################################################### # Split a file containing CVS conflict markers into two temporary files # name Name of file containing conflict markers # Returns the names of the two temporary files and the names of the # files that were merged ############################################################################### proc split-cvs-conflicts {name} { global g opts set first ${name}.1 set second ${name}.2 set temp1 [tmpfile 1] set temp2 [tmpfile 2] if {[catch {set input [open $name r]}]} { fatal-error "Couldn't open file '$name'." } set first [open $temp1 w] lappend g(tempfiles) $temp1 set second [open $temp2 w] lappend g(tempfiles) $temp2 set firstname "" set secondname "" set output 3 set firstMatch "" set secondMatch "" set thirdMatch "" while {[gets $input line] >= 0} { if {$firstMatch == ""} { if {[regexp {^<<<<<<<* +(.*)} $line]} { set firstMatch {^<<<<<<<* +(.*)} set secondMatch {^=======*} set thirdMatch {^>>>>>>>* +(.*)} } elseif {[regexp {^>>>>>>>* +(.*)} $line]} { set firstMatch {^>>>>>>>* +(.*)} set secondMatch {^<<<<<<<* +(.*)} set thirdMatch {^=======*} } } if {$firstMatch != ""} { if {[regexp $firstMatch $line]} { set output 2 if {$secondname == ""} { regexp $firstMatch $line all secondname } } elseif {[regexp $secondMatch $line]} { set output 1 if {$firstname == ""} { regexp $secondMatch $line all firstname } } elseif {[regexp $thirdMatch $line]} { set output 3 if {$firstname == ""} { regexp $thirdMatch $line all firstname } } else { if {$output & 1} { puts $first $line } if {$output & 2} { puts $second $line } } } else { puts $first $line puts $second $line } } close $input close $first close $second if {$firstname == ""} { set firstname "old" } if {$secondname == ""} { set secondname "new" } return "{$temp1} {$temp2} {$firstname} {$secondname}" } ############################################################################### # Get a revision of a file # f file name # index index in finfo array # r revision, "" for head revision ############################################################################### proc get-file-rev {f index {r ""}} { global finfo global opts global tcl_platform if {"$r" == ""} { set rev "HEAD" set acrev "HEAD" set acopt "" set cvsopt "" set rcsopt "" set sccsopt "" set pvcsopt "" set p4file "$f" } else { set rev "r$r" set acrev "$r" set acopt "-v $r" set cvsopt "-r $r" set rcsopt "$r" set sccsopt "-r$r" set pvcsopt "-r$r" set p4file "$f#$r" } set finfo(pth,$index) [tmpfile $index] set finfo(tmp,$index) 1 # NB: it would probably be a Good Thing to move the definition # of the various command to exec, to the preferences dialog. set dirname [file dirname $f] set tailname [file tail $f] # For CVS, if it isn't checked out there is neither a CVS nor RCS # directory. It will however have a ,v suffix just like rcs. # There is not necessarily a RCS directory for RCS, either. The file # always has a ,v suffix. if {[file isdirectory [file join $dirname CVS]]} { set cmd "cvs" if {$tcl_platform(platform) == "windows"} { append cmd ".exe" } set finfo(lbl,$index) "$f (CVS $rev)" die-unless "exec $cmd update -p $cvsopt $f" $finfo(pth,$index) } elseif {[file isdirectory [file join $dirname SCCS]]} { set cmd "sccs" if {$tcl_platform(platform) == "windows"} { append cmd ".exe" } set finfo(lbl,$index) "$f (SCCS $rev)" die-unless "exec $cmd get -p $sccsopt $f" $finfo(pth,$index) } elseif {[file isdirectory [file join $dirname RCS]]} { set cmd "co" if {$tcl_platform(platform) == "windows"} { append cmd ".exe" } set finfo(lbl,$index) "$f (RCS $rev)" die-unless "exec $cmd -p$rcsopt $f" $finfo(pth,$index) } elseif {[regexp {,v$} $tailname]} { set cmd "co" if {$tcl_platform(platform) == "windows"} { append cmd ".exe" } set finfo(lbl,$index) "$f (RCS $rev)" die-unless "exec $cmd -p$rcsopt $f" $finfo(pth,$index) } elseif {[file exists [file join $dirname vcs.cfg]]} { set cmd "get" if {$tcl_platform(platform) == "windows"} { append cmd ".exe" } set finfo(lbl,$index) "$f (PVCS $rev)" die-unless "exec $cmd -p $pvcsopt $f" $finfo(pth,$index) filterCRCRLF $finfo(pth,$index) } elseif {[info exists ::env(P4CLIENT)]} { set cmd "p4" if {$tcl_platform(platform) == "windows"} { append cmd ".exe" } set finfo(lbl,$index) "$f (Perforce $rev)" die-unless "exec $cmd print -q $p4file" $finfo(pth,$index) } elseif {[info exists ::env(ACCUREV_BIN)]} { set cmd "accurev" if {$tcl_platform(platform) == "windows"} { append cmd ".exe" } set finfo(lbl,$index) "$f ($acrev)" die-unless "exec $cmd cat $acopt $f" $finfo(pth,$index) } else { fatal-error "File '$f' is not part of a revision control system." } } ############################################################################### # Setup ordinary file # f file name # index index in finfo array ############################################################################### proc get-file {f index} { global finfo if {[file exists $f] != 1} { fatal-error "File '$f' does not exist." } if {[file isdirectory $f]} { fatal-error "'$f' is a directory." } set finfo(lbl,$index) "$f" set finfo(pth,$index) "$f" set finfo(tmp,$index) 0 } ############################################################################### # Initialize file variables. ############################################################################### proc init-files {} { global argc argv global finfo global opts global g set g(initOK) 0 set argindex 0 set revs 0 set pths 0 set conflict 0 # Loop through argv, storing revision args in rev and file args in # finfo. revs and pths are counters. while {$argindex < $argc} { set arg [lindex $argv $argindex] switch -regexp -- $arg { "^-a$" { incr argindex set g(ancfile) [lindex $argv $argindex] set g(ancfileset) 1 } "^-a.*" { set g(ancfile) [string range $arg 2 end] set g(ancfileset) 1 } "^-r$" { incr argindex incr revs set rev($revs) [lindex $argv $argindex] } "^-r.*" { incr revs set rev($revs) [string range $arg 2 end] } "^-v$" { incr argindex incr revs set rev($revs) [lindex $argv $argindex] } "^-v.*" { incr revs set rev($revs) [string range $arg 2 end] } "^-conflict$" { set conflict 1 } "^-o$" { incr argindex set g(mergefile) [lindex $argv $argindex] set g(mergefileset) 1 } "^-o.*" { set g(mergefile) [string range $arg 2 end] set g(mergefileset) 1 } "^-" { append opts(diffcmd) " $arg " } default { incr pths set finfo(pth,$pths) $arg } } incr argindex } # Now check how many revision and file args we have. if {$conflict} { if {$revs == 0 && $pths == 1} { ############################################################ # tkdiff -conflict FILE ############################################################ set files [split-cvs-conflicts "$finfo(pth,1)"] get-file [lindex "$files" 0] 1 get-file [lindex "$files" 1] 2 set finfo(lbl,1) [lindex "$files" 2] set finfo(lbl,2) [lindex "$files" 3] } else { fatal-error "Usage: tkdiff -conflict FILE" } } else { if {$revs == 2 && $pths == 1} { ############################################################ # tkdiff -rREV1 -rREV2 FILE ############################################################ set f $finfo(pth,1) get-file-rev "$f" 1 "$rev(1)" get-file-rev "$f" 2 "$rev(2)" } elseif {$revs == 2 && $pths == 0} { ############################################################ # tkdiff -rREV -r FILE ############################################################ set f $rev(2) get-file-rev "$f" 1 "$rev(1)" get-file-rev "$f" 2 } elseif {$revs == 1 && $pths == 1} { ############################################################ # tkdiff -rREV FILE ############################################################ set f $finfo(pth,1) get-file-rev "$f" 1 "$rev(1)" get-file "$f" 2 } elseif {$revs == 1 && $pths == 0} { ############################################################ # tkdiff -r FILE ############################################################ set f $rev(1) get-file-rev "$f" 1 get-file "$f" 2 } elseif {$revs == 0 && $pths == 2} { ############################################################ # tkdiff FILE1 FILE2 ############################################################ set f1 $finfo(pth,1) set f2 $finfo(pth,2) if {[file isdirectory $f1] && [file isdirectory $f2]} { fatal-error "Either or must be a plain file." } if {[file isdirectory $f1]} { set f1 [file join $f1 [file tail $f2]] } elseif {[file isdirectory $f2]} { set f2 [file join $f2 [file tail $f1]] } get-file "$f1" 1 get-file "$f2" 2 } elseif {$revs == 0 && $pths == 1} { ############################################################ # tkdiff FILE ############################################################ set f $finfo(pth,1) get-file-rev "$f" 1 get-file "$f" 2 } else { do-error "Invalid command line!\n $argv\nSee the help for valid command line parameters." do-usage tkwait window .usage destroy . error "Fatal" } } set finfo(title) "[file tail $finfo(lbl,1)] vs. [file tail $finfo(lbl,2)]" set rootname [file rootname $finfo(pth,1)] # set path [file dirname $finfo(pth,1)] set path [pwd] set suffix [file extension $finfo(pth,1)] if {! $g(mergefileset)} { set g(mergefile) [file join $path "${rootname}-merge$suffix"] } set g(initOK) 1 wm title . "$finfo(title) - $g(name) $g(version)" } ############################################################################### # Set up the display... ############################################################################### proc create-display {} { global g opts bg tk_version global w global tmpopts # these are the four major areas of the GUI: # menubar - the menubar (duh) # toolbar - the toolbar (duh, again) # client - the area with the text widgets and the graphical map # status us - a bottom status line # this block of destroys is only for stand-alone testing of # the GUI code, and can be blown away (or not, if we want to # be able to call this routine to recreate the display...) catch { destroy .menubar destroy .toolbar destroy .client destroy .map destroy .status } # create the top level frames and store them in a global # array.. set w(client) .client set w(menubar) .menubar set w(toolbar) .toolbar set w(status) .status # other random windows... set w(preferences) .pref set w(findDialog) .findDialog set w(popupMenu) .popupMenu # now, simply build all the pieces build-menubar build-toolbar build-client build-status build-popupMenu # ... and fit it all together... if {$g(nativeMenus)} { . configure\ -menu $w(menubar) } else { pack $w(menubar)\ -side top\ -fill x\ -expand n } pack $w(toolbar)\ -side top\ -fill x\ -expand n pack $w(client)\ -side top\ -fill both\ -expand y pack $w(status)\ -side bottom\ -fill x\ -expand n # apply user preferences by calling the proc that gets # called when the user presses "Apply" from the preferences # window. That proc uses a global variable named "tmpopts" # which should have the values from the dialog. Since we # aren't using the dialog, we need to populate this array # manually foreach key [array names opts] { set ::tmpopts($key) $opts($key) } apply 0 # Make sure temporary files get deleted bind . {del-tmp} # other misc. bindings common-navigation $w(LeftText) $w(LeftInfo) $w(LeftCB) $w(RightText) $w(RightInfo) $w(RightCB) # normally, keyboard traversal using tab and shift-tab isn't # enabled for text widgets, since the default binding for these # keys is to actually insert the tab charater. Because all of # our text widgets are for display only, let's redefine the # default binding so the global and bindings # are used. bind Text {continue} bind Text {continue} # if the user toggles scrollbar syncing, we want to make sure # they sync up immediately trace variable opts(syncscroll) w toggleSyncScroll wm deiconify . focus\ -force $w(RightText) update idletasks set g(started) 1 } ############################################################################### # when the user changes the "sync scrollbars" option, we want to # sync up the left scrollbar with the right if they turn the option # on ############################################################################### proc toggleSyncScroll {args} { global opts global w if {$opts(syncscroll) == 1} { eval vscroll-sync {{}} 2 [$w(RightText) yview] } } ############################################################################### # show the popup menu, optionally changing some of the entries based on # where the user clicked ############################################################################### proc show-popupMenu {x y} { global w global g set window [winfo containing $x $y] if {[winfo class $window] == "Text"} { $w(popupMenu) entryconfigure "Find..."\ -state normal $w(popupMenu) entryconfigure "Find Nearest*"\ -state normal $w(popupMenu) entryconfigure "Edit*"\ -state normal if {$window == $w(LeftText) || $window == $w(LeftInfo) || $window == $w(LeftCB)} { $w(popupMenu) configure\ -title "File 1" set g(activeWindow) $w(LeftText) } else { $w(popupMenu) configure\ -title "File 2" set g(activeWindow) $w(RightText) } } else { $w(popupMenu) entryconfigure "Find..."\ -state disabled $w(popupMenu) entryconfigure "Find Nearest*"\ -state disabled $w(popupMenu) entryconfigure "Edit*"\ -state disabled } tk_popup $w(popupMenu) $x $y } ############################################################################### # build the right-click popup menu ############################################################################### proc build-popupMenu {} { global w g # this routine assumes the other windows already exist... menu $w(popupMenu) foreach win [list LeftText RightText LeftInfo RightInfo LeftCB RightCB mapCanvas] { bind $w($win) <3> {show-popupMenu %X %Y} } set m $w(popupMenu) $m add command\ -label "First Diff"\ -underline 0\ -command [list popupMenu first]\ -accelerator "F" $m add command\ -label "Previous Diff"\ -underline 0\ -command [list popupMenu previous]\ -accelerator "P" $m add command\ -label "Center Current Diff"\ -underline 0\ -command [list popupMenu center]\ -accelerator "C" $m add command\ -label "Next Diff"\ -underline 0\ -command [list popupMenu next]\ -accelerator "N" $m add command\ -label "Last Diff"\ -underline 0\ -command [list popupMenu last]\ -accelerator "L" $m add separator $m add command\ -label "Find Nearest Diff"\ -underline 0\ -command [list popupMenu nearest]\ -accelerator "Double-Click" $m add separator $m add command\ -label "Find..."\ -underline 0\ -command [list popupMenu find] $m add command\ -label "Edit"\ -underline 0\ -command [list popupMenu edit] } ############################################################################### # handle popup menu commands ############################################################################### proc popupMenu {command args} { global g global w switch $command { center { $w(centerDiffs) invoke } edit { do-edit } find { $w(find) invoke } first { $w(firstDiff) invoke } last { $w(lastDiff) invoke } next { $w(nextDiff) invoke } previous { $w(prevDiff) invoke } nearest { moveNearest $g(activeWindow) xy [winfo pointerx $g(activeWindow)] [winfo pointery $g(activeWindow)] } } } ############################################################################### # build the main client display (the text widgets, scrollbars, that # sort of fluff) ############################################################################### proc build-client {} { global g global w global opts global map frame $w(client)\ -bd 2\ -relief flat # set up global variables to reference the widgets, so # we don't have to use hardcoded widget paths elsewhere # in the code # # Text - holds the text of the file # Info - sort-of "invisible" text widget which is kept in sync # with the text widget and holds line numbers # CB - contains changebars or status or something like that... # VSB - vertical scrollbar # HSB - horizontal scrollbar # Label - label to hold the name of the file set w(LeftText) $w(client).left.text set w(LeftInfo) $w(client).left.info set w(LeftCB) $w(client).left.changeBars set w(LeftVSB) $w(client).left.vsb set w(LeftHSB) $w(client).left.hsb set w(LeftLabel) $w(client).leftlabel set w(RightText) $w(client).right.text set w(RightInfo) $w(client).right.info set w(RightCB) $w(client).right.changeBars set w(RightVSB) $w(client).right.vsb set w(RightHSB) $w(client).right.hsb set w(RightLabel) $w(client).rightlabel set w(BottomText) $w(client).bottomtext set w(map) $w(client).map set w(mapCanvas) $w(map).canvas # these don't need to be global... set leftFrame $w(client).left set rightFrame $w(client).right # we'll create each widget twice; once for the left side # and once for the right. label $w(LeftLabel)\ -bd 1\ -relief flat\ -textvariable finfo(lbl,1) label $w(RightLabel)\ -bd 1\ -relief flat\ -textvariable finfo(lbl,2) # this holds the text widgets and the scrollbars. The reason # for the frame is purely for aesthetics. It just looks # nicer, IMHO, to "embed" the scrollbars within the text # widget frame $leftFrame\ -bd 1\ -relief sunken frame $rightFrame\ -bd 1\ -relief sunken scrollbar $w(LeftHSB)\ -borderwidth 1\ -orient horizontal\ -command [list $w(LeftText) xview] scrollbar $w(RightHSB)\ -borderwidth 1\ -orient horizontal\ -command [list $w(RightText) xview] scrollbar $w(LeftVSB)\ -borderwidth 1\ -orient vertical\ -command [list $w(LeftText) yview] scrollbar $w(RightVSB)\ -borderwidth 1\ -orient vertical\ -command [list $w(RightText) yview] scan $opts(geometry) "%dx%d" width height text $w(LeftText)\ -padx 4\ -wrap none\ -width $width\ -height $height\ -borderwidth 0\ -setgrid 1\ -yscrollcommand [list vscroll-sync "$w(LeftInfo) $w(LeftCB)" 1]\ -xscrollcommand [list hscroll-sync 1] text $w(RightText)\ -padx 4\ -wrap none\ -width $width\ -height $height\ -borderwidth 0\ -setgrid 1\ -yscrollcommand [list vscroll-sync "$w(RightInfo) $w(RightCB)" 2]\ -xscrollcommand [list hscroll-sync 2] text $w(LeftInfo)\ -height 0\ -padx 0\ -width 6\ -borderwidth 0\ -setgrid 1\ -yscrollcommand [list vscroll-sync "$w(LeftCB) $w(LeftText)" 1] text $w(RightInfo)\ -height 0\ -padx 0\ -width 6\ -borderwidth 0\ -setgrid 1\ -yscrollcommand [list vscroll-sync "$w(RightCB) $w(RightText)" 2] # each and every line in a text window will have a corresponding line # in this widget. And each line in this widget will be composed of # a single character (either "+", "-" or "!" for insertion, deletion # or change, respectively text $w(LeftCB)\ -height 0\ -padx 0\ -highlightthickness 0\ -wrap none\ -foreground white\ -width 1\ -borderwidth 0\ -yscrollcommand [list vscroll-sync "$w(LeftInfo) $w(LeftText)" 1] text $w(RightCB)\ -height 0\ -padx 0\ -highlightthickness 0\ -wrap none\ -background white\ -foreground white\ -width 1\ -borderwidth 0\ -yscrollcommand [list vscroll-sync "$w(RightInfo) $w(RightText)" 2] # this widget is the two line display showing the current line, so # one can compare character by character if necessary. text $w(BottomText)\ -wrap none\ -borderwidth 1\ -height 2\ -width 0 # this is how we highlight bytes that are different... # the bottom window (lineview) uses reverse video to highlight # diffs, so we need to figure out what reverse video is, and # define the tag appropriately eval $w(BottomText) tag configure diff $opts(bytetag) # Set up text tags for the 'current diff' (the one chosen by the 'next' # and 'prev' buttons) and any ol' diff region. All diff regions are # given the 'diff' tag initially... As 'next' and 'prev' are pressed, # to scroll through the differences, one particular diff region is # always chosen as the 'current diff', and is set off from the others # via the 'diff' tag -- in particular, so that it's obvious which diffs # in the left and right-hand text widgets match. foreach widget [list $w(LeftText) $w(LeftInfo) $w(LeftCB) $w(RightText) $w(RightInfo) $w(RightCB)] { eval "$widget configure $opts(textopt)" foreach tag {difftag currtag deltag instag chgtag + - !} { eval "$widget tag configure $tag $opts($tag)" } } # adjust the tag priorities a bit... foreach window [list LeftText RightText LeftCB RightCB LeftInfo RightInfo] { $w($window) tag raise deltag currtag $w($window) tag raise chgtag currtag $w($window) tag raise instag currtag $w($window) tag raise currtag difftag } # these tags are specific to change bars foreach widget [list $w(LeftCB) $w(RightCB)] { eval "$widget tag configure + $opts(+)" eval "$widget tag configure - $opts(-)" eval "$widget tag configure ! $opts(!)" } # build the map... # we want the map to be the same width as a scrollbar, so we'll # steal some information from one of the scrollbars we just # created... set cwidth [winfo reqwidth $w(LeftVSB)] set color [$w(LeftVSB) cget -troughcolor] set map [frame $w(client).map\ -bd 1\ -relief sunken\ -takefocus 0\ -highlightthickness 0] # now for the real map... image create photo map canvas $w(mapCanvas)\ -width [expr {$cwidth + 1}]\ -yscrollcommand map-resize\ -background $color\ -borderwidth 0\ -relief sunken\ -highlightthickness 0 $w(mapCanvas) create image 1 1\ -image map\ -anchor nw pack $w(mapCanvas)\ -side top\ -fill both\ -expand y # I'm not too pleased with these bindings -- it results in a rather # jerky, cpu-intensive maneuver since with each move of the mouse # we are finding and tagging the nearest diff. But, what *should* # it do? # # I think what I *want* it to do is update the combobox and status # bar so the user can see where in the scheme of things they are, # but not actually select anything until they release the mouse. bind $w(mapCanvas) [list handleMapEvent B1-Press %y] bind $w(mapCanvas) [list handleMapEvent B1-Motion %y] bind $w(mapCanvas) [list handleMapEvent B1-Release %y] # this is a dummy frame we're going to create that's the # same height as a horizontal scrollbar. frame $w(client).dummyFrame\ -borderwidth 0\ -height [winfo reqheight $w(LeftHSB)] # use grid to manage the widgets in the left side frame grid $w(LeftVSB)\ -row 0\ -column 0\ -sticky ns grid $w(LeftInfo)\ -row 0\ -column 1\ -sticky nsew grid $w(LeftCB)\ -row 0\ -column 2\ -sticky ns grid $w(LeftText)\ -row 0\ -column 3\ -sticky nsew grid $w(LeftHSB)\ -row 1\ -column 1\ -sticky ew\ -columnspan 3 grid rowconfigure $leftFrame 0\ -weight 1 grid rowconfigure $leftFrame 1\ -weight 0 grid columnconfigure $leftFrame 0\ -weight 0 grid columnconfigure $leftFrame 1\ -weight 0 grid columnconfigure $leftFrame 2\ -weight 0 grid columnconfigure $leftFrame 3\ -weight 1 # likewise for the right... grid $w(RightVSB)\ -row 0\ -column 3\ -sticky ns grid $w(RightInfo)\ -row 0\ -column 0\ -sticky nsew grid $w(RightCB)\ -row 0\ -column 1\ -sticky ns grid $w(RightText)\ -row 0\ -column 2\ -sticky nsew grid $w(RightHSB)\ -row 1\ -column 0\ -sticky ew\ -columnspan 3 grid rowconfigure $rightFrame 0\ -weight 1 grid rowconfigure $rightFrame 1\ -weight 0 grid columnconfigure $rightFrame 0\ -weight 0 grid columnconfigure $rightFrame 1\ -weight 0 grid columnconfigure $rightFrame 2\ -weight 1 grid columnconfigure $rightFrame 3\ -weight 0 # use grid to manage the labels, frames and map. We're going to # toss in an extra row just for the benefit of our dummy frame. # the intent is that the dummy frame will match the height of # the horizontal scrollbars so the map stops at the right place... grid $w(LeftLabel)\ -row 0\ -column 0\ -sticky ew grid $w(RightLabel)\ -row 0\ -column 2\ -sticky ew grid $leftFrame\ -row 1\ -column 0\ -sticky nsew\ -rowspan 2 grid $map\ -row 1\ -column 1\ -stick ns grid $w(client).dummyFrame\ -row 2\ -column 1 grid $rightFrame\ -row 1\ -column 2\ -sticky nsew\ -rowspan 2 grid rowconfigure $w(client) 0\ -weight 0 grid rowconfigure $w(client) 1\ -weight 1 grid rowconfigure $w(client) 2\ -weight 0 grid rowconfigure $w(client) 3\ -weight 0 grid columnconfigure $w(client) 0\ -weight 1 grid columnconfigure $w(client) 1\ -weight 0 grid columnconfigure $w(client) 2\ -weight 1 # this adjusts the variable g(activeWindow) to be whatever text # widget has the focus... bind $w(LeftText) <1> {set g(activeWindow) $w(LeftText)} bind $w(RightText) <1> {set g(activeWindow) $w(RightText)} set g(activeWindow) $w(LeftText) ;# establish a default rename $w(RightText) $w(RightText)_ rename $w(LeftText) $w(LeftText)_ proc $w(RightText) {command args} $::text_widget_proc proc $w(LeftText) {command args} $::text_widget_proc } ############################################################################### # the following code is used as the replacement body for the left and # right widget procs. The purpose is to catch when the insertion point # changes so we can update the line comparison window ############################################################################### set text_widget_proc { global w set real "[lindex [info level [info level]] 0]_" set result [eval $real $command $args] if {$command == "mark"} { if {[lindex $args 0] == "set" && [lindex $args 1] == "insert"} { set i [lindex $args 2] set i0 "$i linestart" set i1 "$i lineend" set left [$w(LeftText)_ get $i0 $i1] set right [$w(RightText)_ get $i0 $i1] $w(BottomText) delete 1.0 end $w(BottomText) insert end "< $left\n> $right" # find characters that are different, and underline them if {$left != $right} { set left [split $left {}] set right [split $right {}] # n.b. we set c to an offset equal to whatever we have # prepended to the data... set c 2 foreach l $left r $right { if {[string compare $l $r] != 0} { $w(BottomText) tag add diff 1.$c "1.$c+1c" $w(BottomText) tag add diff 2.$c "2.$c+1c" } incr c } $w(BottomText) tag remove diff "1.0 lineend" $w(BottomText) tag remove diff "2.0 lineend" } } } return $result } ############################################################################### # create (if necessary) and show the find dialog ############################################################################### proc show-find {} { global w g if {![winfo exists $w(findDialog)]} { toplevel $w(findDialog) wm group $w(findDialog) . wm transient $w(findDialog) . wm title $w(findDialog) "$g(name) Find" # we don't want the window to be deleted, just hidden from view wm protocol $w(findDialog) WM_DELETE_WINDOW [list wm withdraw $w(findDialog)] wm withdraw $w(findDialog) update idletasks frame $w(findDialog).content\ -bd 2\ -relief groove pack $w(findDialog).content\ -side top\ -fill both\ -expand y\ -padx 5\ -pady 5 frame $w(findDialog).buttons pack $w(findDialog).buttons\ -side bottom\ -fill x\ -expand n button $w(findDialog).buttons.doit\ -text "Find Next"\ -command do-find button $w(findDialog).buttons.dismiss\ -text "Dismiss"\ -command "wm withdraw $w(findDialog)" pack $w(findDialog).buttons.dismiss\ -side right\ -pady 5\ -padx 5 pack $w(findDialog).buttons.doit\ -side right\ -pady 5\ -padx 1 set ff $w(findDialog).content.findFrame frame $ff\ -height 100\ -bd 2\ -relief flat pack $ff\ -side top\ -fill x\ -expand n\ -padx 5\ -pady 5 label $ff.label\ -text "Find what:"\ -underline 2 entry $ff.entry\ -textvariable g(findString) checkbutton $ff.searchCase\ -text "Ignore Case"\ -offvalue 0\ -onvalue 1\ -indicatoron true\ -variable g(findIgnoreCase) grid $ff.label\ -row 0\ -column 0\ -sticky e grid $ff.entry\ -row 0\ -column 1\ -sticky ew grid $ff.searchCase\ -row 0\ -column 2\ -sticky w grid columnconfigure $ff 0\ -weight 0 grid columnconfigure $ff 1\ -weight 1 grid columnconfigure $ff 2\ -weight 0 # we need this in other places... set w(findEntry) $ff.entry bind $ff.entry do-find set of $w(findDialog).content.optionsFrame frame $of\ -bd 2\ -relief flat pack $of\ -side top\ -fill y\ -expand y\ -padx 10\ -pady 10 label $of.directionLabel\ -text "Search Direction:"\ -anchor e radiobutton $of.directionForward\ -indicatoron true\ -text "Down"\ -value "-forward"\ -variable g(findDirection) radiobutton $of.directionBackward\ -text "Up"\ -value "-backward"\ -indicatoron true\ -variable g(findDirection) label $of.windowLabel\ -text "Window:"\ -anchor e radiobutton $of.windowLeft\ -indicatoron true\ -text "Left"\ -value $w(LeftText)\ -variable g(activeWindow) radiobutton $of.windowRight\ -indicatoron true\ -text "Right"\ -value $w(RightText)\ -variable g(activeWindow) label $of.searchLabel\ -text "Search Type:"\ -anchor e radiobutton $of.searchExact\ -indicatoron true\ -text "Exact"\ -value "-exact"\ -variable g(findType) radiobutton $of.searchRegexp\ -text "Regexp"\ -value "-regexp"\ -indicatoron true\ -variable g(findType) grid $of.directionLabel\ -row 1\ -column 0\ -sticky w grid $of.directionForward\ -row 1\ -column 1\ -sticky w grid $of.directionBackward\ -row 1\ -column 2\ -sticky w grid $of.windowLabel\ -row 0\ -column 0\ -sticky w grid $of.windowLeft\ -row 0\ -column 1\ -sticky w grid $of.windowRight\ -row 0\ -column 2\ -sticky w grid $of.searchLabel\ -row 2\ -column 0\ -sticky w grid $of.searchExact\ -row 2\ -column 1\ -sticky w grid $of.searchRegexp\ -row 2\ -column 2\ -sticky w grid columnconfigure $of 0\ -weight 0 grid columnconfigure $of 1\ -weight 0 grid columnconfigure $of 2\ -weight 1 set g(findDirection) "-forward" set g(findType) "-exact" set g(findIgnoreCase) 1 set g(lastSearch) "" if {$g(activeWindow) == ""} { set g(activeWindow) [focus] if {$g(activeWindow) != $w(LeftText) && $g(activeWindow) != $w(RightText)} { set g(activeWindow) $w(LeftText) } } } centerWindow $w(findDialog) wm deiconify $w(findDialog) after idle focus $w(findEntry) } ############################################################################### # do the "Edit->Copy" functionality, by copying the current selection # to the clipboard ############################################################################### proc do-copy {} { clipboard clear\ -displayof . # figure out which window has the selection... catch { clipboard append [selection get\ -displayof .] } } ############################################################################### # search for the text in the find dialog ############################################################################### proc do-find {} { global g global w if {![winfo exists $w(findDialog)] || ![winfo ismapped $w(findDialog)]} { show-find return } set win $g(activeWindow) if {$win == ""} { set win $w(LeftText) } if {$g(lastSearch) != ""} { if {$g(findDirection) == "-forward"} { set start [$win index "insert +1c"] } else { set start insert } } else { set start 1.0 } if {$g(findIgnoreCase)} { set result [$win search $g(findDirection) $g(findType)\ -nocase -- $g(findString) $start] } else { set result [$win search $g(findDirection) $g(findType)\ -- $g(findString) $start] } if {[string length $result] > 0} { # if this is a regular expression search, get the whole line and try # to figure out exactly what matched; otherwise we know we must # have matched the whole string... if {$g(findType) == "-regexp"} { set line [$win get $result "$result lineend"] regexp $g(findString) $line matchVar set length [string length $matchVar] } else { set length [string length $g(findString)] } set g(lastSearch) $result $win mark set insert $result $win tag remove sel 1.0 end $win tag add sel $result "$result + ${length}c" $win see $result focus $win # should I somehow snap to the nearest diff? Probably not... } else { bell } } proc build-menubar {} { global tooltip global w global g if {$g(nativeMenus)} { menu $w(menubar) } else { frame $w(menubar)\ -bd 2\ -relief flat } # this is just temporary shorthand ... set menubar $w(menubar) # First, the menu buttons... if {$g(nativeMenus)} { set fileMenu $w(menubar).file set viewMenu $w(menubar).view set helpMenu $w(menubar).help set editMenu $w(menubar).edit set mergeMenu $w(menubar).window set markMenu $w(menubar).marks $w(menubar) add cascade\ -label "File"\ -menu $fileMenu\ -underline 0 $w(menubar) add cascade\ -label "Edit"\ -menu $editMenu\ -underline 0 $w(menubar) add cascade\ -label "View"\ -menu $viewMenu\ -underline 0 $w(menubar) add cascade\ -label "Mark"\ -menu $markMenu\ -underline 3 $w(menubar) add cascade\ -label "Merge"\ -menu $mergeMenu\ -underline 0 $w(menubar) add cascade\ -label "Help"\ -menu $helpMenu\ -underline 0 } else { # these are shorthand used only in this routine... set fileButton $menubar.fileButton set viewButton $menubar.viewButton set helpButton $menubar.helpButton set editButton $menubar.editButton set mergeButton $menubar.mergeButton set markButton $menubar.markButton set fileMenu $fileButton.file set viewMenu $viewButton.view set helpMenu $helpButton.help set editMenu $editButton.edit set mergeMenu $mergeButton.window set markMenu $markButton.marks menubutton $fileButton\ -text "File"\ -menu $fileMenu\ -underline 0 menubutton $editButton\ -text "Edit"\ -menu $editMenu\ -underline 0 menubutton $viewButton\ -text "View"\ -menu $viewMenu\ -underline 0 menubutton $helpButton\ -text "Help"\ -menu $helpMenu\ -underline 0 menubutton $mergeButton\ -text "Merge"\ -menu $mergeMenu\ -underline 0 menubutton $markButton\ -text "Mark"\ -menu $markMenu\ -underline 3 pack $fileButton $editButton $viewButton $markButton $mergeButton\ -side left\ -fill none\ -expand n if {$::tcl_platform(platform) == "windows"} { pack $helpButton\ -side left\ -fill none\ -expand n } else { pack $helpButton\ -side right\ -fill none\ -expand n } } # these, however, are used in other places.. set w(fileMenu) $fileMenu set w(viewMenu) $viewMenu set w(helpMenu) $helpMenu set w(editMenu) $editMenu set w(mergeMenu) $mergeMenu set w(markMenu) $markMenu # Now, the menus... # Mark menu... menu $markMenu $markMenu add command\ -label "Mark Current Diff"\ -command [list diffmark set]\ -underline 0 $markMenu add command\ -label "Clear Current Diff Mark"\ -command [list diffmark clear]\ -underline 0 set "g(tooltip,Mark Current Diff)" "Create a marker for the current difference record" set "g(tooltip,Clear Current Diff Mark)" "Clear the marker for the current difference record" # File menu... menu $fileMenu $fileMenu add command\ -label "New..."\ -underline 0\ -command [list do-new-diff] $fileMenu add separator $fileMenu add command\ -label "Recompute Diffs"\ -underline 0\ -command recompute-diff $fileMenu add command\ -label "Write Report..."\ -command [list write-report popup]\ -underline 0 $fileMenu add separator $fileMenu add command\ -label "Exit"\ -underline 1\ -accelerator Q\ -command do-exit set "g(tooltip,Exit)" "Exit $g(name)" set "g(tooltip,Recompute Diffs)" "Recompute and redisplay the difference records." set "g(tooltip,Write Report...)" "Write the diff records to a file" # Edit menu... If you change, add or remove labels, be sure and # update the tooltips. menu $editMenu $editMenu add command\ -label "Copy"\ -underline 0\ -command do-copy $editMenu add separator $editMenu add command\ -label "Find..."\ -underline 0\ -command show-find $editMenu add separator $editMenu add command\ -label "Edit File 1"\ -command { global g w set g(activeWindow) $w(LeftText) do-edit }\ -underline 10 $editMenu add command\ -label "Edit File 2"\ -command { global g w set g(activeWindow) $w(RightText) do-edit }\ -underline 10 $editMenu add separator $editMenu add command\ -label "Preferences..."\ -underline 3\ -command customize set "g(tooltip,Copy)" "Copy the currently selected text to the clipboard." set "g(tooltip,Find...)" "Pop up a dialog to search for a string within either file." set "g(tooltip,Edit File 1)" "Launch an editor on the file on the left side of the window." set "g(tooltip,Edit File 2)" "Launch an editor on the file on the right side of the window." set "g(tooltip,Preferences...)" "Pop up a window to customize $g(name)." # View menu... If you change, add or remove labels, be sure and # update the tooltips. menu $viewMenu $viewMenu add checkbutton\ -label "Show Line Numbers"\ -underline 12\ -variable opts(showln)\ -command do-show-linenumbers $viewMenu add checkbutton\ -label "Show Change Bars"\ -underline 12\ -variable opts(showcbs)\ -command do-show-changebars $viewMenu add checkbutton\ -label "Show Diff Map"\ -underline 5\ -variable opts(showmap)\ -command do-show-map $viewMenu add checkbutton\ -label "Show Line Comparison"\ -underline 11\ -variable opts(showlineview)\ -command do-show-lineview $viewMenu add separator $viewMenu add checkbutton\ -label "Synchronize Scrollbars"\ -underline 0\ -variable opts(syncscroll) $viewMenu add checkbutton\ -label "Auto Center"\ -underline 0\ -variable opts(autocenter)\ -command {if {$opts(autocenter)} {center}} $viewMenu add checkbutton\ -label "Auto Select"\ -underline 1\ -variable opts(autoselect) $viewMenu add separator $viewMenu add command\ -label "First Diff"\ -underline 0\ -command {move first}\ -accelerator "F" $viewMenu add command\ -label "Previous Diff"\ -underline 0\ -command {move -1}\ -accelerator "P" $viewMenu add command\ -label "Center Current Diff"\ -underline 0\ -command {center}\ -accelerator "C" $viewMenu add command\ -label "Next Diff"\ -underline 0\ -command {move 1}\ -accelerator "N" $viewMenu add command\ -label "Last Diff"\ -underline 0\ -command {move last}\ -accelerator "L" set "g(tooltip,Show Line Comparison)" "If set, show the current line comparison window" set "g(tooltip,Show Change Bars)" "If set, show the changebar column for each line of each file" set "g(tooltip,Show Line Numbers)" "If set, show line numbers beside each line of each file" set "g(tooltip,Synchronize Scrollbars)" "If set, scrolling either window will scroll both windows." set "g(tooltip,Diff Map)" "If set, display the graphical \"Difference Map\" in the center of the display." set "g(tooltip,Auto Select)" "If set, automatically selects the nearest diff record while scrolling" set "g(tooltip,Auto Center)" "If set, moving to another diff record will center the diff on the screen." set "g(tooltip,Center Current Diff)" "Center the display around the current diff record." set "g(tooltip,First Diff)" "Go to the first difference." set "g(tooltip,Last Diff)" "Go to the last difference." set "g(tooltip,Previous Diff)" "Go to the diff record just prior to the current diff record." set "g(tooltip,Next Diff)" "Go to the diff record just after the current diff record." # Merge menu. If you change, add or remove labels, be sure and # update the tooltips. menu $mergeMenu $mergeMenu add checkbutton\ -label "Show Merge Window"\ -underline 9\ -variable g(showmerge)\ -command do-show-merge $mergeMenu add command\ -label "Write Merge File..."\ -underline 6\ -command popup-merge set "g(tooltip,Show Merge Window)" "Pops up a window showing the current merge results." set "g(tooltip,Write Merge File)" "Write the merge file to disk. You will be prompted for a filename." # Help menu. If you change, add or remove labels, be sure and # update the tooltips. menu $helpMenu $helpMenu add command\ -label "On GUI"\ -underline 3\ -command do-help $helpMenu add command\ -label "On Command Line"\ -underline 3\ -command do-usage $helpMenu add command\ -label "On Preferences"\ -underline 3\ -command do-help-preferences $helpMenu add separator $helpMenu add command\ -label "About $g(name)"\ -underline 0\ -command do-about bind $fileMenu <> {showTooltip menu %W} bind $editMenu <> {showTooltip menu %W} bind $viewMenu <> {showTooltip menu %W} bind $markMenu <> {showTooltip menu %W} bind $mergeMenu <> {showTooltip menu %W} bind $helpMenu <> {showTooltip menu %W} set "g(tooltip,On Preferences)" "Show help on the user-settable preferences" set "g(tooltip,On GUI)" "Show help on how to use the Graphical User Interface" set "g(tooltip,On Command Line)" "Show help on the command line arguments" set "g(tooltip,About $g(name))" "Show information about this application" } proc showTooltip {which w} { global tooltip global g switch $which { menu { if {[catch {$w entrycget active -label} label]} { set label "" } if {[info exists g(tooltip,$label)]} { set g(statusInfo) $g(tooltip,$label) } else { set g(statusInfo) $label } update idletasks } button { if {[info exists g(tooltip,$w)]} { set g(statusInfo) $g(tooltip,$w) } else { set g(statusInfo) "" } update idletasks } } } proc build-toolbar {} { global w g frame $w(toolbar)\ -bd 2\ -relief groove set toolbar $w(toolbar) # these are shorthand used only in this routine... set find $toolbar.find set prevDiff $toolbar.prev set firstDiff $toolbar.first set lastDiff $toolbar.last set nextDiff $toolbar.next set centerDiffs $toolbar.center set mergeChoice1 $toolbar.m1 set mergeChoice2 $toolbar.m2 set mergeChoice12 $toolbar.m12 set mergeChoice21 $toolbar.m21 set mergeChoiceLbl $toolbar.mlabel set currentPos $toolbar.cp set combo $toolbar.combo set rediff $toolbar.rediff set markclear $toolbar.clearMark set markset $toolbar.setMark # these, however, are used in other places.. set w(find) $find set w(prevDiff) $prevDiff set w(firstDiff) $firstDiff set w(lastDiff) $lastDiff set w(nextDiff) $nextDiff set w(centerDiffs) $centerDiffs set w(mergeChoice1) $mergeChoice1 set w(mergeChoice2) $mergeChoice2 set w(mergeChoice12) $mergeChoice12 set w(mergeChoice21) $mergeChoice21 set w(currentPos) $currentPos set w(combo) $combo set w(mergeChoiceLabel) $mergeChoiceLbl set w(rediff) $rediff set w(markSet) $markset set w(markClear) $markclear label $currentPos\ -textvariable g(pos) # some separators we'll use in other places toolsep $toolbar.sep1 toolsep $toolbar.sep2 toolsep $toolbar.sep3 toolsep $toolbar.sep4 toolsep $toolbar.sep5 toolsep $toolbar.sep6 toolsep $toolbar.sep7 toolsep $toolbar.sep8 # rediff... toolbutton $rediff\ -text "Rediff"\ -width 6\ -command recompute-diff # find... toolbutton $find\ -text "Find"\ -width 5\ -command do-find\ -bd 1 # navigation widgets toolbutton $prevDiff\ -text "Prev"\ -width 5\ -command [list move -1]\ -bd 1 toolbutton $nextDiff\ -text "Next"\ -width 5\ -command [list move 1]\ -bd 1 toolbutton $firstDiff\ -text "First"\ -width 5\ -command [list move first]\ -bd 1 toolbutton $lastDiff\ -text "Last"\ -width 5\ -command [list move last]\ -bd 1 toolbutton $centerDiffs\ -text "Center"\ -width 5\ -command center\ -bd 1 toolbutton $markset\ -text "Set Mark"\ -width 10\ -command [list diffmark set]\ -bd 1 toolbutton $markclear\ -text "Clear Mark"\ -width 10\ -command [list diffmark clear]\ -bd 1 ::combobox::combobox $combo\ -editable false\ -width 30\ -command moveTo # the merge widgets radiobutton $mergeChoice2\ -borderwidth 1\ -indicatoron true\ -text Right\ -value 2\ -variable g(toggle)\ -command [list do-merge-choice 2]\ -takefocus 0 radiobutton $mergeChoice1\ -borderwidth 1\ -indicatoron true\ -text Left\ -value 1\ -variable g(toggle)\ -command [list do-merge-choice 1]\ -takefocus 0 radiobutton $mergeChoice12\ -borderwidth 1\ -indicatoron true\ -text Left\ -value 12\ -variable g(toggle)\ -command [list do-merge-choice 12]\ -takefocus 0 radiobutton $mergeChoice21\ -borderwidth 1\ -indicatoron true\ -text Left\ -value 21\ -variable g(toggle)\ -command [list do-merge-choice 21]\ -takefocus 0 # this is gross. We want the label next to the radiobuttons to # be disabled if the radiobuttons are disabled. But, labels can't # be disabled, so we'll use a "dead" button button $mergeChoiceLbl\ -text "Merge Choice:"\ -borderwidth 0\ -command {}\ -highlightthickness 0 pack $combo\ -side left\ -padx 2 pack $toolbar.sep1\ -side left\ -fill y\ -pady 2\ -padx 2 pack $rediff\ -side left\ -padx 2 pack $toolbar.sep6\ -side left\ -fill y\ -pady 2\ -padx 2 pack $find\ -side left\ -padx 2 pack $toolbar.sep2\ -side left\ -fill y\ -pady 2\ -padx 2 pack $mergeChoiceLbl $mergeChoice12 $mergeChoice1 $mergeChoice2 $mergeChoice21\ -side left\ -padx 2 pack $toolbar.sep5\ -side left\ -fill y\ -pady 2\ -padx 3 pack $firstDiff $lastDiff $prevDiff $nextDiff\ -side left\ -pady 2\ -padx 0 pack $toolbar.sep3\ -side left\ -fill y\ -pady 2\ -padx 2 pack $centerDiffs\ -side left\ -pady 2\ -padx 0 pack $toolbar.sep7\ -side left\ -fill y\ -pady 2\ -padx 2 pack $markset $markclear\ -side left\ -padx 2 pack $toolbar.sep8\ -side left\ -fill y\ -pady 2\ -padx 2 # these bindings provide pseudo-tooltips. Note that if some menu # items change, these references need to be updated... Also, we # assume the menubar tooltips have already been defined.... set g(tooltip,$markset) $g(tooltip,Mark Current Diff) set g(tooltip,$markclear) $g(tooltip,Clear Current Diff Mark) set g(tooltip,$combo) "Shows current difference record; allows you to go to a specific difference." set g(tooltip,$prevDiff) $g(tooltip,Previous Diff) set g(tooltip,$nextDiff) $g(tooltip,Next Diff) set g(tooltip,$firstDiff) $g(tooltip,First Diff) set g(tooltip,$lastDiff) $g(tooltip,Last Diff) set g(tooltip,$centerDiffs) $g(tooltip,Center Current Diff) set g(tooltip,$find) $g(tooltip,Find...) set g(tooltip,$rediff) $g(tooltip,Recompute Diffs) set g(tooltip,$mergeChoice1) "select the diff record on the left for merging" set g(tooltip,$mergeChoice2) "select the diff record on the right for merging" set g(tooltip,$mergeChoice12) "select the diff record on the left then right for merging" set g(tooltip,$mergeChoice21) "select the diff record on the right then left for merging" # the toolbuttons have support for tooltips, the combobox and # radiobuttons do not. But, we can use the same callback. foreach widget [list $combo $mergeChoice1 $mergeChoice2 $mergeChoice12 $mergeChoice21] { bind $widget +[list toolbutton:handleEvent %W 0] bind $widget +[list toolbutton:handleEvent %W 0] bind $widget +[list toolbutton:handleEvent %W 0] bind $widget +[list toolbutton:handleEvent %W 0] } # this adjusts the image or label on the buttons according to the # user preferences reconfigure-toolbar } proc reconfigure-toolbar {} { global opts global w # standard button reliefs foreach button [list prevDiff nextDiff firstDiff lastDiff centerDiffs find markSet markClear rediff] { if {$opts(fancyButtons)} { $w($button) configure\ -relief flat } else { $w($button) configure\ -relief raised } } # diff mark buttons relief foreach widget [info commands $w(toolbar).mark*] { if {$opts(fancyButtons)} { $widget configure\ -relief flat } else { $widget configure\ -relief raised } } # standard button images and labels foreach button [list prevDiff nextDiff firstDiff lastDiff centerDiffs find markSet markClear rediff] { if {$opts(toolbarIcons)} { $w($button) configure\ -width 20\ -image ${button}Image } else { if {$button == "markSet" || $button == "markClear"} { $w($button) configure\ -width 10\ -image {} } else { $w($button) configure\ -width 5\ -image {} } } } # merge choice buttons images and labels if {$opts(toolbarIcons)} { foreach button [list mergeChoice1 mergeChoice2 mergeChoice12 mergeChoice21] { $w($button) configure\ -indicatoron false\ -image ${button}Image } # this, in effect, hides the text of the label without # actually destroying it $w(mergeChoiceLabel) configure\ -image nullImage } else { $w(mergeChoiceLabel) configure\ -image {} foreach button [list mergeChoice1 mergeChoice2 mergeChoice12 mergeChoice21] { $w($button) configure\ -indicatoron true\ -image {} } } } proc build-status {} { global w global g frame $w(status)\ -bd 1\ -relief flat set w(statusLabel) $w(status).label set w(statusCurrent) $w(status).current label $w(statusCurrent)\ -textvariable g(statusCurrent)\ -anchor e\ -width 14\ -borderwidth 1\ -relief sunken\ -padx 4\ -pady 2 label $w(statusLabel)\ -textvariable g(statusInfo)\ -anchor w\ -width 1\ -borderwidth 1\ -relief sunken\ -pady 2 pack $w(statusCurrent)\ -side right\ -fill y\ -expand n pack $w(statusLabel)\ -side left\ -fill both\ -expand y } ############################################################################### # handles events over the map ############################################################################### proc handleMapEvent {event y} { global opts global w global g switch $event { B1-Press { set ty1 [lindex $g(thumbBbox) 1] set ty2 [lindex $g(thumbBbox) 3] if {$y >= $ty1 && $y <= $ty2} { set g(mapScrolling) 1 } } B1-Motion { if {[info exists g(mapScrolling)]} { map-seek $y } } B1-Release { show-info "" set ty1 [lindex $g(thumbBbox) 1] set ty2 [lindex $g(thumbBbox) 3] # if we release over the trough (actually, *not* over the thumb), # just scroll by the size of the thumb if {$y < $ty1 || $y > $ty2} { if {$y < $ty1} { # if vertical scrollbar syncing is turned on, # all the other windows should toe the line # appropriately... $w(RightText) yview scroll\ -1 pages } else { $w(RightText) yview scroll 1 pages } } else { # do nothing } catch {unset g(mapScrolling)} } } } # makes a toolbar "separator" proc toolsep {w} { label $w\ -image [image create photo]\ -highlightthickness 0\ -bd 1\ -width 0\ -relief groove return $w } proc toolbutton {w args} { global tcl_platform global opts # create the button eval button $w $args # add minimal tooltip-like support bind $w [list toolbutton:handleEvent %W] bind $w [list toolbutton:handleEvent %W] bind $w [list toolbutton:handleEvent %W] bind $w [list toolbutton:handleEvent %W] # give a taste of the MS Windows "look and feel" if {$opts(fancyButtons)} { $w configure\ -relief flat } return $w } # handle events in our fancy toolbuttons... proc toolbutton:handleEvent {event w {isToolbutton 1}} { global g global opts switch $event { "" { showTooltip button $w if {$opts(fancyButtons) && $isToolbutton && [$w cget -state] == "normal"} { $w configure\ -relief raised } } "" { set g(statusInfo) "" if {$opts(fancyButtons) && $isToolbutton} { $w configure\ -relief flat } } "" { showTooltip button $w if {$opts(fancyButtons) && $isToolbutton && [$w cget -state] == "normal"} { $w configure\ -relief raised } } "" { set g(statusInfo) "" if {$opts(fancyButtons) && $isToolbutton} { $w configure\ -relief flat } } } } ############################################################################### # move the map thumb to correspond to current shown merge... ############################################################################### proc map-move-thumb {y1 y2} { global g global w set thumbheight [expr {($y2 - $y1) * $g(mapheight)}] if {$thumbheight < $g(thumbMinHeight)} { set thumbheight $g(thumbMinHeight) } if {![info exists g(mapwidth)]} { set g(mapwidth) 0 } set x1 1 set x2 [expr {$g(mapwidth) - 3}] # why -2? it's the thickness of our border... set y1 [expr {int(($y1 * $g(mapheight)) - 2)}] if {$y1 < 0} { set y1 0 } set y2 [expr {$y1 + $thumbheight}] if {$y2 > $g(mapheight)} { set y2 $g(mapheight) set y1 [expr {$y2 - $thumbheight}] } set dx1 [expr {$x1 + 1}] set dx2 [expr {$x2 - 1}] set dy1 [expr {$y1 + 1}] set dy2 [expr {$y2 - 1}] $w(mapCanvas) coords thumbUL $x1 $y2 $x1 $y1 $x2 $y1 $dx2 $dy1 $dx1 $dy1 $dx1 $dy2 $w(mapCanvas) coords thumbLR $dx1 $y2 $x2 $y2 $x2 $dy1 $dx2 $dy1 $dx2 $dy2 $dx1 $dy2 set g(thumbBbox) [list $x1 $y1 $x2 $y2] set g(thumbHeight) $thumbheight } ############################################################################### # Bind keys for Next, Prev, Center, Merge choices 1 and 2 # # N.B. This is GROSS! It might have been necessary in earlier versions, # but now I think it needs a serious rewriite. We are now overriding # the text widget, so we can probably just disable the insert and delete # commands, and use something like insert_ and delete_ internally. ############################################################################### proc common-navigation {args} { global w bind . do-find foreach widget $args { # this effectively disables the widget, without having to # resort to actually disabling the widget (the latter which # has some annoying side effects). What we really want is to # only disable keys that get inserted, but that's difficult # to do, and this works almost as well... bind $widget {break} bind $widget {continue} bind $widget <> {break} # ... but now we need to restore some navigation key bindings # which got lost because we disable all keys. Since we are # attaching bindings that duplicate class bindings, we need # to be sure and include the break, so the events don't fire # twice (once for the widget, once for the class). There is # probably a much better way to do all this, but I'm too # lazy to figure it out... foreach event [list Next Prior Up Down Left Right Home End] { foreach modifier [list {} Shift Control Shift-Control] { set binding [bind Text <${modifier}${event}>] if {[string length $binding] > 0} { bind $widget "<${modifier}${event}>" " ${binding} break " } } } # these bindings allow control-f, tab and shift-tab to work # in spite of the fact we bound Any-KeyPress to a null action bind $widget continue bind $widget continue bind $widget continue bind $widget " $w(centerDiffs) invoke break " bind $widget " $w(nextDiff) invoke break " bind $widget

" $w(prevDiff) invoke break " bind $widget " $w(firstDiff) invoke break " bind $widget " $w(lastDiff) invoke break " bind $widget " do-exit break " bind $widget " moveNearest $widget mark insert break " # these bindings keep Alt- modified keys from triggering # the above actions. This way, any Alt combinations that # should open a menu will... foreach key [list c n p f l] { bind $widget {continue} } bind $widget " moveNearest $widget xy %x %y break " bind $widget " $w(mergeChoice1) invoke break " bind $widget " $w(mergeChoice2) invoke break " bind $widget " $w(mergeChoice12) invoke break " bind $widget " $w(mergeChoice21) invoke break " } } ############################################################################### # set or clear a "diff mark" -- a hot button to move to a particular diff ############################################################################### proc diffmark {option {diff -1}} { global g global w if {$diff == -1} { set diff $g(pos) } set widget $w(toolbar).mark$diff switch $option { activate { move $diff 0 1 } set { if {![winfo exists $widget]} { toolbutton $widget\ -text "\[$diff\]"\ -command [list diffmark activate $diff]\ -bd 1 pack $widget\ -side left\ -padx 2 set g(tooltip,$widget) "Diff Marker: Jump to diff record number $diff" } update-display } clear { if {[winfo exists $widget]} { destroy $widget catch {unset g(tooltip,$widget)} } update-display } clearall { foreach widget [info commands $w(toolbar).mark*] { destroy $widget catch {unset g(tooltip,$widget)} } update-display } } } ############################################################################### # Customize the display (among other things). ############################################################################### proc customize {} { global pref global g global w global opts global tmpopts catch {destroy $w(preferences)} toplevel $w(preferences) wm title $w(preferences) "$g(name) Preferences" wm transient $w(preferences) . wm group $w(preferences) . wm withdraw $w(preferences) # the button frame... frame $w(preferences).buttons\ -bd 0 button $w(preferences).buttons.dismiss\ -width 8\ -text "Dismiss"\ -command {destroy $w(preferences)} button $w(preferences).buttons.apply\ -width 8\ -text "Apply"\ -command apply button $w(preferences).buttons.save\ -width 8\ -text "Save"\ -command save button $w(preferences).buttons.help\ -width 8\ -text "Help"\ -command do-help-preferences pack $w(preferences).buttons\ -side bottom\ -fill x pack $w(preferences).buttons.dismiss\ -side right\ -padx 10\ -pady 5 pack $w(preferences).buttons.help\ -side right\ -padx 10\ -pady 5 pack $w(preferences).buttons.save\ -side right\ -padx 1\ -pady 5 pack $w(preferences).buttons.apply\ -side right\ -padx 1\ -pady 5 # a series of checkbuttons to act as a poor mans notebook tab frame $w(preferences).notebook\ -bd 0 pack $w(preferences).notebook\ -side top\ -fill x\ -pady 4 set pagelist {} foreach page [list General Display Appearance] { set frame $w(preferences).f$page lappend pagelist $frame set rb $w(preferences).notebook.f$page radiobutton $rb\ -command "customize-selectPage $frame"\ -variable g(prefPage)\ -value $frame\ -text $page\ -indicatoron false\ -width 10\ -borderwidth 1 pack $rb\ -side left frame $frame\ -bd 2\ -relief groove\ -width 400\ -height 300 } set g(prefPage) $w(preferences).fGeneral # make sure our labels are defined customize-initLabels # this is an option that we support internally, but don't give # the user a way to directly edit (right now, anyway). But we # need to make sure tmpopts knows about it set tmpopts(customCode) $opts(customCode) # General set count 0 set frame $w(preferences).fGeneral foreach key {diffcmd tmpdir editor geometry} { label $frame.l$count\ -text "$pref($key): "\ -anchor w set tmpopts($key) $opts($key) entry $frame.e$count\ -textvariable tmpopts($key)\ -width 50\ -bd 2\ -relief sunken grid $frame.l$count\ -row $count\ -column 0\ -sticky w\ -padx 5\ -pady 2 grid $frame.e$count\ -row $count\ -column 1\ -sticky ew\ -padx 5\ -pady 2 incr count } # this is just for filler... label $frame.filler\ -text {} grid $frame.filler\ -row $count incr count foreach key {fancyButtons toolbarIcons autocenter syncscroll autoselect} { label $frame.l$count\ -text "$pref($key): "\ -anchor w set tmpopts($key) $opts($key) checkbutton $frame.c$count\ -indicatoron true\ -text "$pref($key)"\ -justify left\ -onvalue 1\ -offvalue 0\ -variable tmpopts($key) set tmpopts($key) $opts($key) grid $frame.c$count\ -row $count\ -column 0\ -sticky w\ -padx 5\ -columnspan 2 incr count } grid columnconfigure $frame 0\ -weight 0 grid columnconfigure $frame 1\ -weight 1 # this, in effect, adds a hidden row at the bottom which takes # up any extra room grid rowconfigure $frame $count\ -weight 1 # pack this window for a brief moment, and compute the window # size. We'll do this for each "page" and find the largest # size to be the size of the dialog pack $frame\ -side right\ -fill both\ -expand y update idletasks set maxwidth [winfo reqwidth $w(preferences)] set maxheight [winfo reqheight $w(preferences)] pack forget $frame # Appearance set frame $w(preferences).fAppearance set count 0 foreach key {textopt difftag deltag instag chgtag currtag bytetag} { label $frame.l$count\ -text "$pref($key): "\ -anchor w set tmpopts($key) $opts($key) entry $frame.e$count\ -textvariable tmpopts($key)\ -bd 2\ -relief sunken grid $frame.l$count\ -row $count\ -column 0\ -sticky w\ -padx 5\ -pady 2 grid $frame.e$count\ -row $count\ -column 1\ -sticky ew\ -padx 5\ -pady 2 incr count } grid columnconfigure $frame 0\ -weight 0 grid columnconfigure $frame 1\ -weight 1 # tabstops are placed after a little extra whitespace, since it is # slightly different than all of the other options (ie: it's not # a list of widget options) frame $frame.sep$count\ -bd 0\ -height 4 grid $frame.sep$count\ -row $count\ -column 0\ -stick ew\ -columnspan 2\ -padx 5\ -pady 2 incr count set key "tabstops" set tmpopts($key) $opts($key) label $frame.l$count\ -text "$pref($key):"\ -anchor w set tmpopts($key) $opts($key) entry $frame.e$count\ -textvariable tmpopts($key)\ -bd 2\ -relief sunken\ -width 3 grid $frame.l$count\ -row $count\ -column 0\ -sticky w\ -padx 5\ -pady 2 grid $frame.e$count\ -row $count\ -column 1\ -sticky w\ -padx 5\ -pady 2 incr count # add a tiny bit of validation, so the user can only enter numbers trace variable tmpopts($key) w [list validate integer] # this, in effect, adds a hidden row at the bottom which takes # up any extra room grid rowconfigure $frame $count\ -weight 1 pack $frame\ -side right\ -fill both\ -expand y update idletasks set maxwidth [max $maxwidth [winfo reqwidth $w(preferences)]] set maxheight [max $maxheight [winfo reqheight $w(preferences)]] pack forget $frame # Display set frame $w(preferences).fDisplay set row 0 # Option fields # Note that the order of the list is used to determine # the layout. So, if you add something to the list pay # attention to how it affects things. # # an x means an empty column; a - means an empty row set col 0 foreach key [list showln tagln showcbs tagcbs showmap colorcbs showlineview tagtext -] { if {$key == "x"} { set col [expr {$col ? 0 : 1}] if {$col == 0} { incr row } continue } if {$key == "-"} { frame $frame.f${row}\ -bd 0\ -height 4 grid $frame.f${row}\ -row $row\ -column 0\ -columnspan 2\ -padx 20\ -pady 4\ -sticky nsew set col 1 ;# will force next column to zero and incr row } else { checkbutton $frame.c${row}${col}\ -indicatoron true\ -text "$pref($key)"\ -onvalue 1\ -offvalue 0\ -variable tmpopts($key) set tmpopts($key) $opts($key) grid $frame.c${row}$col\ -row $row\ -column $col\ -sticky w\ -padx 5 } set col [expr {$col ? 0 : 1}] if {$col == 0} { incr row } } grid columnconfigure $frame 0\ -weight 0 grid columnconfigure $frame 1\ -weight 0 grid columnconfigure $frame 2\ -weight 0 grid columnconfigure $frame 3\ -weight 0 grid columnconfigure $frame 4\ -weight 1 # this, in effect, adds a hidden row at the bottom which takes # up any extra room grid rowconfigure $frame $row\ -weight 1 pack $frame\ -side right\ -fill both\ -expand y update idletasks set maxwidth [max $maxwidth [winfo reqwidth $w(preferences)]] set maxheight [max $maxheight [winfo reqheight $w(preferences)]] pack forget $frame customize-selectPage # compute a reasonable location for the window... centerWindow $w(preferences) [list $maxwidth $maxheight] wm deiconify $w(preferences) } proc validate {type name index op} { global tmpopts # if we fail the check, attempt to do something clever if {![string is $type $tmpopts($index)]} { bell switch -- $type { integer { regsub\ -all {[^0-9]} $tmpopts($index) {} tmpopts($index) } default { # this should never happen. If you use this routine, # make sure you add cases to handle all possible # values of $type used by this program. set tmpopts($index) "" } } } } proc customize-selectPage {{frame {}}} { global g w if {$frame == ""} { set frame $g(prefPage) } pack forget $w(preferences).fGeneral pack forget $w(preferences).fAppearance pack forget $w(preferences).fDisplay pack forget $w(preferences).fBehavior pack $frame\ -side right\ -fill both\ -expand y } ############################################################################### # define the labels for the preferences. This is done outside of # the customize proc since the labels are used in the help text. ############################################################################### proc customize-initLabels {} { global pref set pref(diffcmd) {diff command} set pref(textopt) {Text widget options} set pref(bytetag) {Tag options for characters in line view} set pref(difftag) {Tag options for diff regions} set pref(currtag) {Tag options for the current diff region} set pref(deltag) {Tag options for deleted diff region} set pref(instag) {Tag options for inserted diff region} set pref(chgtag) {Tag options for changed diff region} set pref(geometry) {Text window size} set pref(tmpdir) {Directory for scratch files} set pref(editor) {Program for editing files} set pref(fancyButtons) {Fancy toolbar buttons} set pref(showlineview) {Show current line comparison window} set pref(showmap) {Show graphical map of diffs} set pref(showln) {Show line numbers} set pref(showcbs) {Show change bars} set pref(autocenter) {Automatically center current diff region} set pref(syncscroll) {Synchronize scrollbars} set pref(toolbarIcons) {Use icons instead of labels in the toolbar} set pref(colorcbs) {Color change bars to match the diff map} set pref(tagtext) {Highlight file contents} set pref(tagcbs) {Highlight change bars} set pref(tagln) {Highlight line numbers} set pref(tabstops) {Tab stops} set pref(autoselect) "Automaticallly select the nearest diff region while scrolling" } ############################################################################### # Apply customization changes. ############################################################################### proc apply {{remark 0}} { global opts global tmpopts global w global pref if {! [file isdirectory $tmpopts(tmpdir)]} { do-error "Invalid temporary directory $tmpopts(tmpdir)" } if {[catch " $w(LeftText) configure $tmpopts(textopt) $w(RightText) configure $tmpopts(textopt) $w(BottomText) configure $tmpopts(textopt) "]} { do-error "Invalid text widget setting: \n\n'$tmpopts(textopt)'" eval "$w(LeftText) configure $opts(textopt)" eval "$w(RightText) configure $opts(textopt)" eval "$w(BottomText) configure $opts(textopt)" return } # the text options must be ok. Configure the other text widgets # similarly eval "$w(LeftCB) configure $tmpopts(textopt)" eval "$w(LeftInfo) configure $tmpopts(textopt)" eval "$w(RightCB) configure $tmpopts(textopt)" eval "$w(RightInfo) configure $tmpopts(textopt)" if {$tmpopts(geometry) == "" || [catch {scan $tmpopts(geometry) "%dx%d" width height} result]} { do-error "invalid geometry setting: $tmpopts(geometry)" return } if {[catch {$w(LeftText) configure\ -width $width\ -height $height} result]} { do-error "invalid geometry setting: $tmpopts(geometry)" return } $w(RightText) configure\ -width $width\ -height $height foreach tag {difftag currtag deltag instag chgtag} { foreach win [list $w(LeftText) $w(LeftInfo) $w(LeftCB) $w(RightText) $w(RightInfo) $w(RightCB)] { if {[catch "$win tag configure $tag $tmpopts($tag)"]} { do-error "Invalid settings for \"$pref($tag)\": \n\n'$tmpopts($tag)' is not a valid option string" eval "$win tag configure $tag $opts($tag)" return } } } if {[catch "$w(BottomText) tag configure diff $tmpopts(bytetag)"]} { do-error "Invalid settings for \"$pref(bytetag)\": \n\n'$tmpopts(bytetag)' is not a valid option string" eval "$w(BottomText) tag configure diff $opts(bytetag)" return } # tabstops require a little extra work. We need to figure out # the width of an "m" in the widget's font, then multiply that # by the tab stop width. For the bottom text widget the first tabstop # is adjusted by two to take into consideration the fact that we # add two bytes to each line (ie: "< " or "> "). set cwidth [font measure [$w(LeftText) cget -font] "m"] set tabstops [expr {$cwidth * $tmpopts(tabstops)}] $w(LeftText) configure\ -tabs $tabstops $w(RightText) configure\ -tabs $tabstops $w(BottomText) configure\ -tabs [list [expr {$tabstops +($cwidth * 2)}] $tabstops] if {[info exists w(mergeText)] && [winfo exists $w(mergeText)]} { $w(mergeText) configure\ -tabs $tabstops } # set opts to the values from tmpopts foreach key {diffcmd textopt difftag currtag deltag instag chgtag tmpdir editor showmap showln showcbs showlineview autocenter syncscroll tagln tagcbs tagtext autoselect toolbarIcons geometry\ fancyButtons colorcbs tabstops} { set opts($key) $tmpopts($key) } # reconfigure the toolbar buttons reconfigure-toolbar # remark all the diff regions, show (or hide) the line numbers, # change bars and diff map, and we are done. if {$remark} { remark-diffs } do-show-linenumbers do-show-changebars do-show-map do-show-lineview } ############################################################################### # Save customization changes. ############################################################################### proc save {} { global g global tmpopts rcfile tcl_platform global pref if {[file exists $rcfile]} { file rename\ -force $rcfile "$rcfile~" } # Need to quote backslashes, replace single \ with double \\ regsub\ -all {\\} $tmpopts(tmpdir) {\\\\} tmpdir set fid [open $rcfile w] # put the tkdiff version in the file. It might be handy later puts $fid "# This file was generated by $g(name) $g(version)" puts $fid "# [clock format [clock seconds]]\n" puts $fid "set prefsFileVersion {$g(version)}\n" # now, put all of the preferences in the file foreach key {diffcmd textopt difftag currtag deltag instag bytetag tabstops chgtag showmap showln showcbs showlineview autocenter syncscroll fancyButtons geometry editor colorcbs autoselect\ tagln tagcbs tagtext toolbarIcons} { regsub "\n" $pref($key) "\n# " comment puts $fid "# $comment" puts $fid "define $key {$tmpopts($key)}\n" } # Seems we can't use {$tmpdir} here or embedded \\ don't translate to puts $fid "# $pref(tmpdir)" puts $fid "define tmpdir \"$tmpdir\"\n" # ... and any custom code puts $fid "# custom code" puts $fid "# put any custom code you want to be executed in the" puts $fid "# following block. This code will be automatically executed" puts $fid "# after the GUI has been set up but before the diff is " puts $fid "# performed. Use this code to customize the interface if" puts $fid "# you so desire." puts $fid "# " puts $fid "# Even though you can't (as of version 3.05) edit this " puts $fid "# code via the preferences dialog, it will be automatically" puts $fid "# saved and restored if you do a SAVE from that dialog." puts $fid "" puts $fid "# Unless you really know what you are doing, it is probably" puts $fid "# wise to leave this unmodified." puts $fid "" puts $fid "define customCode {\n[string trim $tmpopts(customCode) \n]\n}\n" close $fid if {$tcl_platform(platform) == "windows"} { file attribute $rcfile\ -hidden 1 } } ############################################################################### # Text has scrolled, update scrollbars and synchronize windows ############################################################################### proc hscroll-sync {id args} { global g opts global w # If ignore_event is true, we've already taken care of scrolling. # We're only interested in the first event. if {$g(ignore_hevent,$id)} { return } # Scrollbar sizes set size1 [expr {[lindex [$w(LeftText) xview] 1] - [lindex [$w(LeftText) xview] 0]}] set size2 [expr {[lindex [$w(RightText) xview] 1] - [lindex [$w(RightText) xview] 0]}] if {$opts(syncscroll) || $id == 1} { set start [lindex $args 0] if {$id != 1} { set start [expr {$start * $size2 / $size1}] } $w(LeftHSB) set $start [expr {$start + $size1}] $w(LeftText) xview moveto $start set g(ignore_hevent,1) 1 } if {$opts(syncscroll) || $id == 2} { set start [lindex $args 0] if {$id != 2} { set start [expr {$start * $size1 / $size2}] } $w(RightHSB) set $start [expr {$start + $size2}] $w(RightText) xview moveto $start set g(ignore_hevent,2) 1 } # This forces all the event handlers for the view alterations # above to trigger, and we lock out the recursive (redundant) # events using ignore_event. update idletasks # Restore to normal set g(ignore_hevent,1) 0 set g(ignore_hevent,2) 0 } ############################################################################### # Text has scrolled, update scrollbars and synchronize windows ############################################################################### proc vscroll-sync {windowlist id y0 y1} { global g opts global w if {$id == 1} { $w(LeftVSB) set $y0 $y1 } else { $w(RightVSB) set $y0 $y1 } # if syncing is disabled, we're done. This prevents a nasty # set of recursive calls if {[info exists g(disableSyncing)]} { return } # set the flag; this makes sure we only get called once set g(disableSyncing) 1 # scroll the other windows on the same side as this window foreach window $windowlist { $window yview moveto $y0 } eval map-move-thumb $y0 $y1 # Select nearest visible diff region, if the appropriate # options are set if {$opts(syncscroll) && $opts(autoselect) && $g(count) > 0} { set winhalf [expr {[winfo height $w(RightText)] / 2}] set result [find-diff [expr {int([$w(RightText) index @1,$winhalf])}]] set i [lindex $result 0] # have we found a diff other than the current diff? if {$i != $g(pos)} { # Also, make sure the diff is visible. If not, we won't # change the current diff region... set topline [$w(RightText) index @0,0] set bottomline [$w(RightText) index @0,10000] foreach {line s1 e1 s2 e2 type} $g(scrdiff,$i) { } if {$s1 >= $topline && $s1 <= $bottomline} { move $i 0 1 } } } # if syncing is turned on, scroll other windows. # Annoyingly, sometimes the *Text windows won't scroll properly, # at least under windows. And I can't for the life of me figure # out why. Maybe a bug in tk? if {$opts(syncscroll)} { if {$id == 1} { $w(RightText) yview moveto $y0 $w(RightInfo) yview moveto $y0 $w(RightCB) yview moveto $y0 $w(RightVSB) set $y0 $y1 } else { $w(LeftText) yview moveto $y0 $w(LeftInfo) yview moveto $y0 $w(LeftCB) yview moveto $y0 $w(LeftVSB) set $y0 $y1 } } # we apparently automatically process idle events after this # proc is called. Once that is done we'll unset our flag after idle {catch {unset g(disableSyncing)}} } ############################################################################### # Make a miniature map of the diff regions ############################################################################### proc create-map {name mapwidth mapheight} { global g global w global map set map $name # Text widget always contains blank line at the end set lines [expr {double([$w(LeftText) index end]) - 2}] set factor [expr {$mapheight / $lines}] # We add some transparent stuff to make the map fill the canvas # in order to receive mouse events at the very bottom. $map blank $map put \#000\ -to 0 $mapheight $mapwidth $mapheight # Line numbers start at 1, not at 0. for {set i 1} {$i <= $g(count)} {incr i} { # scan $g(scrdiff,$i) "%s %d %d %d %d %s" line s1 e1 s2 e2 type foreach {line s1 e1 s2 e2 type} $g(scrdiff,$i) { } set y [expr {int(($s2 - 1) * $factor) + $g(mapborder)}] set size [expr {round(($e2 - $s2 + 1) * $factor)}] if {$size < 1} { set size 1 } switch $type { "d" { set color red1 } "a" { set color green } "c" { set color blue } } $map put $color\ -to 0 $y $mapwidth [expr {$y + $size}] } # let's draw a rectangle to simulate a scrollbar thumb. The size # isn't important since it will get resized when map-move-thumb # is called... $w(mapCanvas) create line 0 0 0 0\ -tags thumbUL\ -fill white $w(mapCanvas) create line 1 1 1 1\ -tags thumbLR\ -fill black $w(mapCanvas) raise thumb # now, move the thumb eval map-move-thumb [$w(LeftText) yview] } ############################################################################### # Resize map to fit window size ############################################################################### proc map-resize {args} { global g opts global w set mapwidth [winfo width $w(map)] set g(mapborder) [expr {[$w(map) cget -borderwidth] + [$w(map) cget -highlightthickness]}] set mapheight [expr {[winfo height $w(map)] - $g(mapborder) * 2}] # We'll get a couple of "resize" events, so don't draw a map # unless we've got the diffs and the map size has changed if {$g(count) == 0 || $mapheight == $g(mapheight)} { return } # If we don't have a map and don't want one, don't make one if {$g(mapheight) == 0 && $opts(showmap) == 0} { return } # This seems to happen on Windows!? _After_ the map is drawn the first time # another event triggers and [winfo height $w(map)] is then 0... if {$mapheight < 1} { return } set g(mapheight) $mapheight set g(mapwidth) $mapwidth create-map map $mapwidth $mapheight } ############################################################################### # scroll to diff region nearest to y ############################################################################### proc map-scroll {y} { global g global w global opts set yview [expr {double($y) / double($g(mapheight))}] # Show text corresponding to map catch {$w(RightText) yview moveto $yview} result update idletasks # Select the diff region closest to the middle of the screen set winhalf [expr {[winfo height $w(RightText)] / 2}] set result [find-diff [expr {int([$w(RightText) index @1,$winhalf])}]] move [lindex $result 0] 0 0 if {$opts(autocenter)} { center } if {$g(showmerge)} { merge-center } } ############################################################################### # Toggle showing the line comparison window ############################################################################### proc do-show-lineview {{showLineview {}}} { global opts global w if {$showLineview != {}} { set opts(showlineview) $showLineview } if {$opts(showlineview)} { grid $w(BottomText)\ -row 3\ -column 0\ -sticky ew\ -columnspan 4 } else { grid forget $w(BottomText) } } ############################################################################### # Toggle showing map or not ############################################################################### proc do-show-map {{showMap {}}} { global opts global w if {$showMap != {}} { set opts(showmap) $showMap } if {$opts(showmap)} { grid $w(map)\ -row 1\ -column 1\ -stick ns } else { grid forget $w(map) } } ############################################################################### # Find the diff nearest to $line. # Returns "$i $newtop" where $i is the index of the diff region # and $newtop is the new top line in the window to the right. ############################################################################### proc find-diff {line} { global g global w set top $line set newtop [expr {$top - int([$w(LeftText) index end]) + int([$w(RightText) index end])}] for {set low 1; set high $g(count); set i [expr {($low + $high) / 2}]} {$i >= $low} {set i [expr {($low + $high) / 2}]} { foreach {line s1 e1 s2 e2 type} $g(scrdiff,$i) { } if {$s1 > $top} { set newtop [expr {$top - $s1 + $s2}] set high [expr {$i-1}] } else { set low [expr {$i+1}] } } # do some range checking... set i [max 1 [min $i $g(count)]] # If next diff is closer than the one found, use it instead if {$i > 0 && $i < $g(count)} { set nexts1 [lindex $g(scrdiff,[expr {$i + 1}]) 1] set e1 [lindex $g(scrdiff,$i) 2] if {$nexts1 - $top < $top - $e1} { incr i } } return [list $i $newtop] } ############################################################################### # Calculate number of lines in diff region # pos Diff number # version 1 or 2, left or right window version # screen 1 for screen size, 0 for original diff size ############################################################################### proc diff-size {pos version {screen 0}} { global g if {$screen} { set diff scrdiff } else { set diff pdiff } # scan $g($diff,$pos) "%s %d %d %d %d %s" # thisdiff s(1) e(1) s(2) e(2) type foreach {thisdiff s(1) e(1) s(2) e(2) type} $g($diff,$pos) { } switch $version { 1 { set lines [expr {$e(1) - $s(1) + 1}] if {$type == "a"} { incr lines -1 } } 2 { set lines [expr {$e(2) - $s(2) + 1}] if {$type == "d"} { incr lines -1 } } 12 - 21 { set lines [expr {$e(1) - $s(1) + $e(2) - $s(2) + 1}] } } return $lines } ############################################################################### # Toggle showing merge preview or not ############################################################################### proc do-show-merge {{showMerge ""}} { global g global w if {$showMerge != ""} { set g(showmerge) $showMerge } if {$g(showmerge)} { set-cursor wm deiconify $w(merge) $w(mergeText) configure\ -state disabled focus\ -force $w(mergeText) merge-center restore-cursor } else { wm withdraw $w(merge) restore-cursor } } ############################################################################### # Create Merge preview window ############################################################################### proc merge-create-window {} { global opts global w global g set top .merge set w(merge) $top catch {destroy $top} toplevel $top set x [expr {[winfo rootx .] + 0}] set y [expr {[winfo rooty .] + 0}] wm geometry $top "+${x}+${y}" wm group $top . wm transient $top . wm title $top "$g(name) Merge Preview" frame $top.frame\ -bd 1\ -relief sunken pack $top.frame\ -side top\ -fill both\ -expand y\ -padx 10\ -pady 10 set w(mergeText) $top.frame.text set w(mergeVSB) $top.frame.vsb set w(mergeHSB) $top.frame.hsb set w(mergeDismiss) $top.dismiss set w(mergeWrite) $top.mergeWrite set w(mergeRecenter) $top.mergeRecenter # Window and scrollbars scrollbar $w(mergeHSB)\ -orient horizontal\ -command [list $w(mergeText) xview] scrollbar $w(mergeVSB)\ -orient vertical\ -command [list $w(mergeText) yview] text $w(mergeText)\ -bd 0\ -takefocus 1\ -yscrollcommand [list $w(mergeVSB) set]\ -xscrollcommand [list $w(mergeHSB) set] grid $w(mergeText)\ -row 0\ -column 0\ -sticky nsew grid $w(mergeVSB)\ -row 0\ -column 1\ -sticky ns grid $w(mergeHSB)\ -row 1\ -column 0\ -sticky ew grid rowconfigure $top.frame 0\ -weight 1 grid rowconfigure $top.frame 1\ -weight 0 grid columnconfigure $top.frame 0\ -weight 1 grid columnconfigure $top.frame 1\ -weight 0 # buttons button $w(mergeRecenter)\ -width 8\ -text "ReCenter"\ -underline 0\ -command merge-center button $w(mergeDismiss)\ -width 8\ -text "Dismiss"\ -underline 0\ -command [list do-show-merge 0] button $w(mergeWrite)\ -width 8\ -text "Save..."\ -underline 0\ -command [list popup-merge merge-write-file] pack $w(mergeDismiss)\ -side right\ -pady 5\ -padx 10 pack $w(mergeRecenter)\ -side right\ -pady 5\ -padx 1 pack $w(mergeWrite)\ -side right\ -pady 5\ -padx 1 eval $w(mergeText) configure $opts(textopt) foreach tag {difftag currtag} { eval $w(mergeText) tag configure $tag $opts($tag) } # adjust the tabstops set cwidth [font measure [$w(mergeText) cget -font] "m"] set tabstops [expr {$cwidth * $opts(tabstops)}] $w(mergeText) configure\ -tabs $tabstops wm protocol $w(merge) WM_DELETE_WINDOW {do-show-merge 0} # adjust the tag priorities a bit... $w(mergeText) tag raise sel $w(mergeText) tag raise currtag difftag common-navigation $w(mergeText) wm withdraw $w(merge) } ############################################################################### # Read original file (Left window file) into merge preview window. # Not so good if it has changed. ############################################################################### proc merge-read-file {} { global finfo global w # hack; need to find a cleaner way... catch {destroy .merge} merge-create-window set hndl [open "$finfo(pth,1)" r] $w(mergeText) configure\ -state normal $w(mergeText) delete 1.0 end $w(mergeText) insert 1.0 [read $hndl] close $hndl # If last line doesn't end with a newline, add one. Important when # writing out the merge preview. if {![regexp {\.0$} [$w(mergeText) index "end-1lines lineend"]]} { $w(mergeText) insert end "\n" } $w(mergeText) configure\ -state disabled } ############################################################################### # Write merge preview to file ############################################################################### proc merge-write-file {} { global g global w set hndl [open "$g(mergefile)" w] set text [$w(mergeText) get 1.0 end-1lines] puts\ -nonewline $hndl $text close $hndl } ############################################################################### # Add a mark where each diff begins and tag diff regions so they are visible. # Assumes text is initially the bare original (Left) version. ############################################################################### proc merge-add-marks {} { global g global w # mark all lines first, so selection won't mess up line numbers for {set i 1} {$i <= $g(count)} {incr i} { foreach [list thisdiff s1 e1 s2 e2 type] $g(pdiff,$i) { } # set delta [expr {$type == "a" ? 1 : 0}] # $w(mergeText) mark set mark$i $s1.0+${delta}lines if {$type == "a"} { incr s1 } $w(mergeText) mark set mark$i $s1.0 $w(mergeText) mark gravity mark$i left } # if a 3-way merge, select right window as needed if {$g(ancfileset) && $g(count) > 0} { for {set i 1} {$i <= $g(count)} {incr i} { set g(merge$i) 2 } set i 1 set s1 [lindex $g(pdiff,$i) 1] foreach as1 $g(diff3) { while {$as1 >= $s1} { if {$as1 == $s1} { set g(merge$i) 1 } if {$i >= $g(count)} break incr i set s1 [lindex $g(pdiff,$i) 1] } } } # select merged lines for {set i 1} {$i <= $g(count)} {incr i} { foreach [list thisdiff s1 e1 s2 e2 type] $g(pdiff,$i) { } if {$g(merge$i) == 1} { # (If it's an insert it's not visible) if {$type != "a"} { set lines [expr {$e1 - $s1 + 1}] $w(mergeText) tag add difftag mark$i mark$i+${lines}lines } } else { # Insert right window version merge-select-version $i 1 2 } } # Tag current if {$g(count) > 0} { set pos $g(pos) set lines [diff-size $pos $g(merge$pos)] $w(mergeText) tag add currtag mark$pos "mark$pos+${lines}lines" } } ############################################################################### # Add a mark where each diff begins # pos diff index # oldversion 1 or 2, previous merge choice # newversion 1 or 2, new merge choice ############################################################################### proc merge-select-version {pos oldversion newversion} { global g global w catch { switch $oldversion { 1 - 2 {set oldlines [diff-size $pos $oldversion]} 12 - 21 {set oldlines [expr {[diff-size $pos 1] + [diff-size $pos 2]}]} } $w(mergeText) configure\ -state normal $w(mergeText) delete mark$pos "mark${pos}+${oldlines}lines" $w(mergeText) configure\ -state disabled } # Screen coordinates foreach {thisdiff s(1) e(1) s(2) e(2) type} $g(scrdiff,$pos) { } # Get the text directly from window switch $newversion { 1 { set newlines [diff-size $pos 1] set newtext [$w(LeftText) get $s(1).0 $s(1).0+${newlines}lines] } 2 { set newlines [diff-size $pos 2] set newtext [$w(RightText) get $s(2).0 $s(2).0+${newlines}lines] } 12 { set newlines [diff-size $pos 1] set newtext [$w(LeftText) get $s(1).0 $s(1).0+${newlines}lines] set newlines [diff-size $pos 2] append newtext [$w(RightText) get $s(2).0 $s(2).0+${newlines}lines] incr newlines [diff-size $pos 1] } 21 { set newlines [diff-size $pos 2] set newtext [$w(RightText) get $s(2).0 $s(2).0+${newlines}lines] set newlines [diff-size $pos 1] append newtext [$w(LeftText) get $s(1).0 $s(1).0+${newlines}lines] incr newlines [diff-size $pos 2] } } # Insert it $w(mergeText) configure\ -state normal $w(mergeText) insert mark$pos $newtext diff $w(mergeText) configure\ -state disabled if {$pos == $g(pos)} { $w(mergeText) tag add currtag mark$pos "mark${pos}+${newlines}lines" } } ############################################################################### # Center the merge region in the merge window ############################################################################### proc merge-center {} { global g global w # Size of diff in lines of text set difflines [diff-size $g(pos) $g(merge$g(pos))] set yview [$w(mergeText) yview] # Window height in percent set ywindow [expr {[lindex $yview 1] - [lindex $yview 0]}] # First line of diff set firstline [$w(mergeText) index mark$g(pos)] # Total number of lines in window set totallines [$w(mergeText) index end] if {$difflines / $totallines < $ywindow} { # Diff fits in window, center it $w(mergeText) yview moveto [expr {($firstline + $difflines / 2) / $totallines - $ywindow / 2}] } else { # Diff too big, show top part $w(mergeText) yview moveto [expr {($firstline - 1) / $totallines}] } } ############################################################################### # Update the merge preview window with the current merge choice # newversion 1 or 2, new merge choice ############################################################################### proc do-merge-choice {newversion} { global g opts global w $w(mergeText) configure\ -state normal merge-select-version $g(pos) $g(merge$g(pos)) $newversion $w(mergeText) configure\ -state disabled set g(merge$g(pos)) $newversion if {$g(showmerge) && $opts(autocenter)} { merge-center } } ############################################################################### # Extract the start and end lines for file1 and file2 from the diff # stored in "line". ############################################################################### proc extract {line} { # the line darn well better be of the form , # where op is one of "a","c" or "d". range will either be a # single number or two numbers separated by a comma. # is this a cool regular expression, or what? :-) regexp {([0-9]*)(,([0-9]*))?([a-z])([0-9]*)(,([0-9]*))?} $line matchvar s1 x e1 op s2 x e2 if {[string length $e1] == 0} { set e1 $s1 } if {[string length $e2] == 0} { set e2 $s2 } if {[info exists s1] && [info exists s2]} { # return "$line $s1 $e1 $s2 $e2 $op" return [list $line $s1 $e1 $s2 $e2 $op] } else { fatal-error "Cannot parse output from diff:\n$line" } } ############################################################################### # Insert blank lines to match added/deleted lines in other file ############################################################################### proc add-lines {pos} { global g global w # Figure out which lines we need to address... foreach [list thisdiff s1 e1 s2 e2 type] $g(pdiff,$pos) { } set size(1) [expr {$e1 - $s1}] set size(2) [expr {$e2 - $s2}] incr s1 $g(delta,1) incr s2 $g(delta,2) # Figure out what kind of diff we're dealing with switch $type { "a" { set lefttext " " ;# insert set righttext "+" set idx 1 set count [expr {$size(2) + 1}] incr s1 incr size(2) } "d" { set lefttext "-" ;# delete set righttext " " set idx 2 set count [expr {$size(1) + 1}] incr s2 incr size(1) } "c" { set lefttext "!" ;# change set righttext "!" ;# change set idx [expr {$size(1) < $size(2) ? 1 : 2}] set count [expr {abs($size(1) - $size(2))}] incr size(1) incr size(2) } } # Put plus signs in left info column if {$idx == 1} { set textWidget $w(LeftText) set infoWidget $w(LeftInfo) set cbWidget $w(LeftCB) # set blank "++++++\n" set blank " \n" } else { set textWidget $w(RightText) set infoWidget $w(RightInfo) set cbWidget $w(RightCB) set blank " \n" } # Insert blank lines to match other window set line [expr {$s1 + $size($idx)}] for {set i 0} {$i < $count} {incr i} { $textWidget insert $line.0 "\n" $infoWidget insert $line.0 $blank $cbWidget insert $line.0 "\n" } incr size($idx) $count set e1 [expr {$s1 + $size(1) - 1}] set e2 [expr {$s2 + $size(2) - 1}] incr g(delta,$idx) $count # Insert change bars or text to show what has changed. $w(RightCB) configure\ -state normal $w(LeftCB) configure\ -state normal for {set i $s1} {$i <= $e1} {incr i} { $w(LeftCB) insert $i.0 $lefttext $w(RightCB) insert $i.0 $righttext } # Save the diff block in window coordinates set g(scrdiff,$g(count)) [list $thisdiff $s1 $e1 $s2 $e2 $type] } ############################################################################### # Add a tag to a region. ############################################################################### proc add-tag {wgt tag start end type new {exact 0}} { global g $wgt tag add $tag $start.0 [expr {$end + 1}].0 } ############################################################################### # Change the tag for a diff region. # 'pos' is the index in the diff array # If 'oldtag' is present, first remove it from the region # If 'setpos' is non-zero, make sure the region is visible. # Returns the diff expression. ############################################################################### proc set-tag {pos newtag {oldtag ""} {setpos 0}} { global g opts global w # Figure out which lines we need to address... if {![info exists g(scrdiff,$pos)]} { return } foreach {thisdiff s1 e1 s2 e2 dt} $g(scrdiff,$pos) { } # Remove old tag if {"$oldtag" != ""} { set e1next "[expr {$e1 + 1}].0" set e2next "[expr {$e2 + 1}].0" $w(LeftText) tag remove $oldtag $s1.0 $e1next $w(LeftInfo) tag remove $oldtag $s1.0 $e1next $w(RightText) tag remove $oldtag $s2.0 $e2next $w(RightInfo) tag remove $oldtag $s2.0 $e2next $w(LeftCB) tag remove $oldtag $s1.0 $e1next $w(RightCB) tag remove $oldtag $s2.0 $e2next catch { set lines [diff-size $pos $g(merge$pos)] $w(mergeText) tag remove $oldtag mark$pos "mark${pos}+${lines}lines" } } switch $dt { "d" { set coltag deltag set rcbtag " " set lcbtag "-" } "a" { set coltag instag set rcbtag "+" set lcbtag " " } "c" { set coltag chgtag set rcbtag "!" set lcbtag "!" } } # Add new tag if {$opts(tagtext)} { add-tag $w(LeftText) $newtag $s1 $e1 $dt 1 add-tag $w(RightText) $newtag $s2 $e2 $dt 1 add-tag $w(RightText) $coltag $s2 $e2 $dt 1 } if {$opts(tagcbs)} { if {$opts(colorcbs)} { add-tag $w(LeftCB) $lcbtag $s1 $e1 $dt 1 add-tag $w(RightCB) $rcbtag $s2 $e2 $dt 1 } else { add-tag $w(LeftCB) $newtag $s1 $e1 $dt 1 add-tag $w(RightCB) $newtag $s2 $e2 $dt 1 add-tag $w(RightCB) $coltag $s2 $e2 $dt 1 } } if {$opts(tagln)} { add-tag $w(LeftInfo) $newtag $s1 $e1 $dt 1 add-tag $w(RightInfo) $newtag $s2 $e2 $dt 1 add-tag $w(RightInfo) $coltag $s2 $e2 $dt 1 } catch { set lines [diff-size $pos $g(merge$pos)] $w(mergeText) tag add $newtag mark$pos "mark${pos}+${lines}lines" } # Move the view on both text widgets so that the new region is # visible. if {$setpos} { if {$opts(autocenter)} { center } else { $w(LeftText) see $s1.0 $w(RightText) see $s2.0 $w(LeftText) mark set insert $s1.0 $w(RightText) mark set insert $s2.0 if {$g(showmerge)} { $w(mergeText) see mark$pos } } } # make sure the sel tag has the highest priority foreach window [list LeftText RightText LeftCB RightCB LeftInfo RightInfo] { $w($window) tag raise sel } return $thisdiff } ############################################################################### # moves to the diff nearest the insertion cursor or the mouse click, # depending on $mode (which should be either "xy" or "mark") ############################################################################### proc moveNearest {window mode args} { switch $mode { "xy" { set x [lindex $args 0] set y [lindex $args 1] set index [$window index @$x,$y] set line [expr {int($index)}] set diff [find-diff $line] } "mark" { set index [$window index [lindex $args 0]] set line [expr {int($index)}] set diff [find-diff $line] } } # ok, we have an index move [lindex $diff 0] 0 1 } ############################################################################### ############################################################################### proc moveTo {window value} { global w global g # we know that the value is prefixed by the nunber/index of # the diff the user wants. So, just grab that out of the string regexp {([0-9]+) *:} $value matchVar index move $index 0 1 } ############################################################################### # this is called when the user scrolls the map thumb interactively. ############################################################################### proc map-seek {y} { global g global w incr y -2 set yview [expr {(double($y) / double($g(mapheight)))}] # Show text corresponding to map; $w(RightText) yview moveto $yview } ############################################################################### # Move the "current" diff indicator (i.e. go to the next or previous diff # region if "relative" is 1; go to an absolute diff number if "relative" # is 0). ############################################################################### proc move {value {relative 1} {setpos 1}} { global g global w if {$value == "first"} { set value 1 set relative 0 } if {$value == "last"} { set value $g(count) set relative 0 } # Remove old 'curr' tag set-tag $g(pos) difftag currtag # Bump 'pos' (one way or the other). if {$relative} { set g(pos) [expr {$g(pos) + $value}] } else { set g(pos) $value } # Range check 'pos'. set g(pos) [max $g(pos) 1] set g(pos) [min $g(pos) $g(count)] # Set new 'curr' tag set g(currdiff) [set-tag $g(pos) currtag "" $setpos] # update the buttons.. update-display } proc update-display {} { global g global w if {!$g(initOK)} { # disable darn near everything foreach widget [list combo prevDiff firstDiff nextDiff lastDiff centerDiffs mergeChoice1 mergeChoice2 mergeChoice12 mergeChoice21 find mergeChoiceLabel combo] { $w($widget) configure\ -state disabled } foreach menu [list $w(popupMenu) $w(viewMenu)] { $menu entryconfigure "Previous*"\ -state disabled $menu entryconfigure "First*"\ -state disabled $menu entryconfigure "Next*"\ -state disabled $menu entryconfigure "Last*"\ -state disabled $menu entryconfigure "Center*"\ -state disabled } $w(popupMenu) entryconfigure "Find..."\ -state disabled $w(popupMenu) entryconfigure "Find Nearest*"\ -state disabled $w(popupMenu) entryconfigure "Edit*"\ -state disabled $w(editMenu) entryconfigure "Find*"\ -state disabled $w(editMenu) entryconfigure "Edit File 1"\ -state disabled $w(editMenu) entryconfigure "Edit File 2"\ -state disabled $w(fileMenu) entryconfigure "Write*"\ -state disabled $w(fileMenu) entryconfigure "Recompute*"\ -state disabled $w(mergeMenu) entryconfigure "Show*"\ -state disabled $w(mergeMenu) entryconfigure "Write*"\ -state disabled $w(markMenu) entryconfigure "Mark*"\ -state disabled $w(markMenu) entryconfigure "Clear*"\ -state disabled } else { # these are always enabled, assuming we have properly # diffed a couple of files $w(popupMenu) entryconfigure "Find..."\ -state normal $w(popupMenu) entryconfigure "Find Nearest*"\ -state normal $w(popupMenu) entryconfigure "Edit*"\ -state normal $w(mergeChoice1) configure\ -state normal $w(mergeChoice2) configure\ -state normal $w(mergeChoice12) configure\ -state normal $w(mergeChoice21) configure\ -state normal $w(mergeChoiceLabel) configure\ -state normal $w(editMenu) entryconfigure "Find*"\ -state normal $w(editMenu) entryconfigure "Edit File 1"\ -state normal $w(editMenu) entryconfigure "Edit File 2"\ -state normal $w(fileMenu) entryconfigure "Write*"\ -state normal $w(fileMenu) entryconfigure "Recompute*"\ -state normal $w(mergeMenu) entryconfigure "Show*"\ -state normal $w(mergeMenu) entryconfigure "Write*"\ -state normal $w(find) configure\ -state normal $w(combo) configure\ -state normal } # Update the toggles. if {$g(count)} { set g(toggle) $g(merge$g(pos)) } # update the status line set g(statusCurrent) "$g(pos) of $g(count)" # update the combobox. We don't want it's command to fire, so # we'll disable it temporarily $w(combo) configure\ -commandstate "disabled" set i [expr {$g(pos) - 1}] $w(combo) configure\ -value [lindex [$w(combo) list get 0 end] $i] $w(combo) selection clear $w(combo) configure\ -commandstate "normal" # update the widgets if {$g(pos) <= 1} { $w(prevDiff) configure\ -state disabled $w(firstDiff) configure\ -state disabled $w(popupMenu) entryconfigure "Previous*"\ -state disabled $w(popupMenu) entryconfigure "First*"\ -state disabled $w(viewMenu) entryconfigure "Previous*"\ -state disabled $w(viewMenu) entryconfigure "First*"\ -state disabled } else { $w(prevDiff) configure\ -state normal $w(firstDiff) configure\ -state normal $w(popupMenu) entryconfigure "Previous*"\ -state normal $w(popupMenu) entryconfigure "First*"\ -state normal $w(viewMenu) entryconfigure "Previous*"\ -state normal $w(viewMenu) entryco