#!/usr/bin/wish

###############################################################################
#
# TkDiff -- A graphical front-end to diff for Unix and NT.
# Copyright (C) 1994-1998 by John M. Klassa.
#
# 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
###############################################################################

set g(version) "TkDiff 2.06 Beta"
set g(preview) {}

###############################################################################
#                                                                             #
#                    TkDiff -- graphical diff, using Tcl/Tk                   #
#                                                                             #
# Author: John Klassa (klassa@ipass.net)                                      #
#                                                                             #
# Usage:                                                                      #
#         Plain files:                                                        #
#             tkdiff <file1> <file2>                                          #
#                                                                             #
#         Plain file with conflict markers:                                   #
#             tkdiff -conflict <file>                                         #
#                                                                             #
#         Source control RCS/CVS/SCCS/PVCS:                                   #
#             tkdiff <file> (same as -r)                                      #
#             tkdiff -r <file>                                                #
#             tkdiff -r<rev> <file>                                           #
#             tkdiff -r<rev> -r <file>                                        #
#             tkdiff -r<rev1> -r<rev2> <file>                                 #
#                                                                             #
###############################################################################

###############################################################################
# Set defaults...
###############################################################################

global opts
set g(debug) 1
wm withdraw .

# Fonts are selected based on platform.  Can anyone clean this
# up by finding one set of fonts that looks good everywhere?

switch $tcl_platform(platform) {
    windows {
	if [info exists env(TEMP)] {
	    set opts(tmpdir) $env(TEMP)
	} else {
	    set opts(tmpdir) C:/temp
	}
	if ![ info exists env(HOME) ] { set env(HOME) C: }
	set rcfile "$env(HOME)/_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 rcfile "$env(HOME)/.tkdiffrc"
    }
}

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
}

# Change these to hard code paths to executables
set g(perlexec) "perl"
set g(diffexec) "diff"

set g(started)    0
set g(destroy)    ""
set g(mergefile)  {tkdiff-merge.out}
set g(changefile) {tkdiff-change-bars.out}
set finfo(title) {}
set finfo(tmp,1) 0
set finfo(tmp,2) 0
set g(tempfiles) {}

###############################################################################
# These options cannot be changed at runtime
###############################################################################

# We want nice understandable diff regions
set g(compact) 0
# We don't want mega hysteria
set g(megascrollbar) 0
# Default startup window size
set opts(geometry) 40x20

###############################################################################
# These options may be changed at runtime
###############################################################################

# If true, centermost visible diff region is always selected
set g(autoselect) 0

# Default options to diff program
set opts(diffopt) {}

# Show map of diffs
set opts(showmap)    1
# True if next and prev buttons automatically center diff region in window
set opts(autocenter) 1
# True if scrollbars are synchronized
set opts(syncscroll) 1
# Show line numbers
set opts(showln)     1

###############################################################################
# Initialize
###############################################################################

set g(showmerge)  0
set g(mapheight) 0
set g(mapborder) 0
set g(ignore_event,1) 0
set g(ignore_event,2) 0
set g(ignore_hevent,1) 0
set g(ignore_hevent,2) 0

if {[string first "color" [winfo visual .]] >= 0} {
    # We have color
    set bg "#9977cc"
    set opts(textopt) "-background white -foreground gray  -font $font"
    set opts(currtag) "-background blue  -foreground yellow"
    set opts(difftag) "-background gray  -foreground black"

    set opts(deltag) "-background red1 -foreground black"
    set opts(instag) "-background green3 -foreground black"
    set opts(chgtag) "-background DodgerBlue1 -foreground black"
} else {
    # Assume only black and white
    set bg "black"
    set opts(textopt) "-background white -foreground black -font $font"
    set opts(currtag) "-background black -foreground white"
    set opts(difftag) "-background white -foreground black -font $bold"

    set opts(deltag) "-background black -foreground white"
    set opts(instag) "-background black -foreground white"
    set opts(chgtag) "-background black -foreground white"
}

set opts(textopt) "$opts(textopt) -wrap none"

set g(perlheading) "TkDiff Error: Embedded Perl Script Output"

###############################################################################
# Source ~/.tkdiffrc, to override defaults (if desired).
###############################################################################

catch {source $rcfile}

###############################################################################
# Work-around for bad font approximations,
# as suggested by Don Libes (libes@nist.gov).
###############################################################################
catch {tk scaling [expr 100.0 / 72]}

###############################################################################
# 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 -message "$msg" -title "Error" -icon error -type ok
	error "Fatal"
    } else {
	puts stderr $msg
	del-tmp
	exit
    }
}

###############################################################################
# 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
}


###############################################################################
# Pop up a window to display unexpected output from perl...
###############################################################################

proc make-popup {t title} {
    catch {destroy .popup}
    toplevel .popup
    wm title .popup $title

    pack [text .popup.t -height 10] -side top
    pack [button .popup.b -text Dismiss -command {destroy .popup}] -side top

    .popup.t insert end $t
}

###############################################################################
# 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 line numbers.
###############################################################################

proc do-show-linenumbers {} {
    global opts

    if {$opts(showln)} {
	pack .1.info -side left -fill y -before .1.text
	pack .2.info -side left -fill y
    } else {
	pack forget .1.info .2.info
    }
}

###############################################################################
# Show line numbers in info windows
###############################################################################

proc draw-line-numbers {} {
    global g
    
    .1.info configure -state normal
    .2.info configure -state normal

    foreach mod {1 2} {
	# Line count for text windows
	set lines($mod) [lindex [split [.$mod.text index end-1lines] .] 0]
    }

    # Smallest line count
    set minlines [min $lines(1) $lines(2)]
    
    for {set i 1} {$i < $minlines} {incr i} {
	.1.info insert end [format "%-6d\n" $i]
    }
    
    # Copy line numbers into other window
    set s [.1.info get 1.0 end-1lines]
    .2.info insert end $s
    
    # Insert remaining line numbers
    foreach mod {1 2} {
	for {set i $minlines} {$i < $lines($mod)} {incr i} {
	    .$mod.info insert end [format "%-6d\n" $i]
	}
    }

    .1.info configure -state disabled
    .2.info configure -state disabled
}

###############################################################################
# Pop up a window for file merge.
###############################################################################

proc popup-merge {{writeproc write-merge}} {
    global g

    catch {destroy .fmerge}
    toplevel .fmerge
    wm title .fmerge "TkDiff Merge"

    pack [frame .fmerge.f1] \
            -side top -expand y -fill both
    pack [label .fmerge.f1.l -text "Output Filename:"] \
            -side left
    pack [entry .fmerge.f1.e -textvariable g(mergefile)] \
            -side left -expand y -fill both

    pack [frame .fmerge.f2] \
            -side top
    pack [button .fmerge.f2.merge -text "Write File" -command $writeproc] \
            -side left
    pack [button .fmerge.f2.quit -text "Dismiss" -command {destroy .fmerge}] \
            -side left
}

###############################################################################
# Write merge file.
###############################################################################

proc write-merge {} {
    global g
    global finfo

    append cmd_arg $finfo(pth,1)\n
    append cmd_arg $finfo(pth,2)\n
    append cmd_arg $g(mergefile)\n
    append cmd_arg $g(count)\n

    for {set idx 1} {$idx <= $g(count)} {incr idx} {
        append cmd_arg $g(merge$idx)\n
    }

    for {set idx 1} {$idx <= $g(count)} {incr idx} {
        append cmd_arg [lindex $g(pdiff,$idx) 0]\n
    }

    catch { exec $g(perlexec) -e {

###########################################################################
# filename 1
# filename 2
# output filename
# number of diffs (N)
# diff 1
# diff 2
#  :
# diff N
# choice 1
# choice 2
#  :
# choice N
###########################################################################

#
# figure out which files to use and how many differences we've got
#

chop($filename_1      = <STDIN>);
chop($filename_2      = <STDIN>);
chop($output_filename = <STDIN>);
chop($num_diffs       = <STDIN>);

#
# read in the choices
#

for ($count = 0; $count < $num_diffs; $count++) {
    chop($choice = <STDIN>);
    push(@choices, $choice);
}

#
# read in the differences
#

for ($count = 0; $count < $num_diffs; $count++) {
    chop($diff = <STDIN>);
    push(@diffs, $diff);
}

#
# open/create all files
#

if (!open(FILE1, $filename_1)) {
    print "Couldn't open '$filename_1': $!\n";
    exit 0;
}

if (!open(FILE2, $filename_2)) {
    print "Couldn't open '$filename_2': $!\n";
    exit 0;
}

if (!open(FILE3, ">$output_filename")) {
    print "Couldn't create '$output_filename': $!\n";
    exit 0;
}

#
# do the merge
#

$pos_1 = 1;
$pos_2 = 1;

foreach $diff (@diffs) {

    $choice = shift(@choices);

    ($s1, $e1, $s2, $e2, $action) = &parse_diff($diff);

    #
    # fast-forward to the position of this diff (both files); loop on
    # both "s1" and "s2" to avoid forging ahead too far in the first
    # file
    #

    while ($pos_1 < $s1 && $pos_2 < $s2) {
        if ($pos_1 < $s1) {
            $line = <FILE1>;
            print FILE3 $line;
            ++$pos_1;
        }
        if ($pos_2 < $s2) {
            $line = <FILE2>;
            ++$pos_2;
        }
    }

    #
    # choose a fork and dump it
    #

    if ($choice == 1) {
        while ($pos_1 <= $e1) {
            $line = <FILE1>;
            print FILE3 $line;
            ++$pos_1;
        }
    }
    elsif ($choice == 2) {
        while ($pos_2 <= $e2) {
            $line = <FILE2>;
            print FILE3 $line;
            ++$pos_2;
        }
    }

    #
    # catch up on the bottom end
    #

    while ($pos_1 <= $e1) {
        $line = <FILE1>;
        ++$pos_1;
    }

    while ($pos_2 <= $e2) {
        $line = <FILE2>;
        ++$pos_2;
     }
}

#
# finish up, taking the rest from the first file
#

while (<FILE1>) {
    print FILE3;
}

#
# close all files
#

close(FILE3);
close(FILE2);
close(FILE1);

###########################################################################
# parse_diff: return start/end-points for both files, along with an action
###########################################################################

sub parse_diff {
    local($diff) = shift;

    if ($diff =~ /(\d+),(\d+)(a|c|d)(\d+),(\d+)/) {
        return ($1, $2, $4, $5, $3);
    }
    elsif ($diff =~ /(\d+)(a|c|d)(\d+),(\d+)/) {
        return ($1, $1, $3, $4, $2);
    }
    elsif ($diff =~ /(\d+),(\d+)(a|c|d)(\d+)/) {
        return ($1, $2, $4, $4, $3);
    }
    elsif ($diff =~ /(\d+)(a|c|d)(\d+)/) {
        return ($1, $1, $3, $3, $2);
    }
}

    } <<$cmd_arg } result

    if {$result != ""} { make-popup $result $g(perlheading) }

    catch {destroy .merge}
}

###############################################################################
# Pop up a window for change bars.
###############################################################################

proc popup-changes {} {
    global g
    global finfo

    catch {destroy .change}
    toplevel .change
    wm title .change "TkDiff Change-Bars"

    set g(cid) 1

    pack [frame .change.f1] \
            -side top -expand y -fill both
    pack [label .change.f1.l1 -text "Show:"] \
            -side left
    pack [radiobutton .change.f1.f1 -text $finfo(lbl,1) -value 1 \
            -variable g(cid)] \
            -side left
    pack [radiobutton .change.f1.f2 -text $finfo(lbl,2) -value 2 \
            -variable g(cid)] \
            -side left
    pack [label .change.f1.l2 -text "(with changes from the other)"] \
            -side left

    pack [frame .change.f2] \
            -side top
    pack [label .change.f2.l -text "Output Filename:"] \
            -side left
    pack [entry .change.f2.e -textvariable g(changefile)] \
            -side left -expand y -fill both

    pack [frame .change.f3] \
            -side top
    pack [button .change.f3.change -text "Write File" \
            -command write-changes] \
            -side left
    pack [button .change.f3.quit -text "Dismiss" -command {destroy .change}] \
            -side left
}

###############################################################################
# Write change-bar file.
###############################################################################

proc write-changes {} {
    global g
    global finfo
    global opts

    set one $g(cid)
    if {$g(cid) == 1} { set two 2 } { set two 1 }

    append cmd_arg $finfo(pth,$one)\n
    append cmd_arg $finfo(pth,$two)\n
    append cmd_arg $finfo(lbl,$one)\n
    append cmd_arg $finfo(lbl,$two)\n
    append cmd_arg $g(changefile)\n
    append cmd_arg $opts(diffopt)\n

    catch { exec $g(perlexec) -e {

###########################################################################
# filename 1
# filename 2
# label for filename 1
# label for filename 2
# output filename
# diff options
###########################################################################

#
# figure out which files to use and how many differences we've got
#

chop($file2    = <STDIN>);
chop($file1    = <STDIN>);
chop($label2   = <STDIN>);
chop($label1   = <STDIN>);
chop($outfile  = <STDIN>);
chop($diffopts = <STDIN>);

@diffs = grep(/^[0-9,]*(a|c|d)[0-9,]*$/,
	      `diff $diffopts '$file1' '$file2'`);

for $diff (@diffs) {
    if ($diff =~ /([acd])(\d+)$/) {
        $lno = $2;
        $tag{"$lno"} = $1;
        if ($diff =~ /^(\d+)d/) {
            $count{"$lno"} = 1;
        }
        elsif ($diff =~ /^(\d+),(\d+)d/) {
            $count{"$lno"} = "$2" - "$1" + 1;
        }
    }
    elsif ($diff =~ /([acd])(\d+),(\d+)/) {
        for $idx ($2..$3) {
            $tag{"$idx"} = $1;
        }
    }
}

$added   = 0;
$changed = 0;
$deleted = 0;

for $tag (keys %tag) {
    if ($tag{$tag} eq "a") {
        ++$added;
    }
    elsif ($tag{$tag} eq "c") {
        ++$changed;
    }
    elsif ($tag{$tag} eq "d") {
        ++$deleted;
    }
}

$total = 0;

for $key (keys %count) {
    $total += $count{"$key"};
}

if (!open(OUP, ">$outfile")) {
    print "Couldn't create '$outfile': $!\n";
    exit 0;
}

print OUP "\nListing of \"$label2\" with changes from\n\"$label1\" noted.\n\n";
print OUP "$added line";  &plural($added);
print OUP " added; $changed line";  &plural($changed);
print OUP " changed; $deleted region";  &plural($deleted);
print OUP " ($total line";  &plural($total);
print OUP " total) deleted\n\n";

if (!open(INP, $file2)) {
    print "Couldn't open '$file2': $!\n";
    exit 0;
}

$jdx = 0;

while (<INP>) {
    ++$jdx;
    $line = untabify($_);
    $ch  = defined($tag{"$jdx"}) ? $tag{"$jdx"} : " ";
    if ($ch eq "d") {
        printf OUP "    %-6d %s\n  <%d line",
                   $jdx, $line, $count{"$jdx"};
        &plural($count{"$jdx"});
        print OUP " deleted>\n\n";
    }
    elsif ($ch eq " ") {
        printf OUP "    %-6d %s", $jdx, $line;
    }
    else {
        printf OUP "%s | %-6d %s", $ch, $jdx, $line;
    }
}

close(INP);
close(OUP);

sub plural {
    local($count) = @_;
    if ($count == 0 || $count > 1) {
        print OUP "s";
    }
}

sub untabify {
    local($line) = @_;
    local(@chunks, $pos, $chunk, $spaces, $out);

    $out    = '';
    @chunks = split(/([\b\t\r])/, $line);
    $pos    = 0;

    for $chunk (@chunks) {
        if ($chunk eq "\t") {
            $spaces = 8 - ($pos % 8);
            $out .= " " x $spaces;
            $pos += $spaces;
        }
        else {
            if ($chunk eq "\r") {
                $pos = 0;
            }
            elsif ($chunk eq "\b") {
                --$pos unless $pos < 1;
            }
            else {
                $pos += length($chunk);
            }
            $out .= $chunk;
        }
    }

    return $out;
}

    } <<$cmd_arg } result

    if {$result != ""} { make-popup $result $g(perlheading) }

    catch {destroy .change}
}

###############################################################################
# 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

    if {"$r" == ""} {
	set rev "HEAD"
	set cvsopt  ""
	set rcsopt  ""
	set sccsopt ""
        set pvcsopt ""
    } else {
	set rev "r$r"
	set cvsopt  "-r $r"
	set rcsopt  "$r"
	set sccsopt "-r$r"
        set pvcsopt "-r$r"
    }
    
    set finfo(pth,$index) [tmpfile $index]
    set finfo(tmp,$index) 1

    set dirname [file dirname $f]
    if {[file isdirectory [file join $dirname CVS]]} {
	set finfo(lbl,$index) "$f (CVS $rev)"
	die-unless "exec cvs update -p $cvsopt $f" $finfo(pth,$index)
    } elseif {[file isdirectory [file join $dirname SCCS]]} {
	set finfo(lbl,$index) "$f (SCCS $rev)"
	die-unless "exec sccs get -p $sccsopt $f" $finfo(pth,$index)
    } elseif {[file isdirectory [file join $dirname RCS]]} {
	set finfo(lbl,$index) "$f (RCS $rev)"
	die-unless "exec co -p$rcsopt $f" $finfo(pth,$index)
    } elseif {[file exists [file join $dirname vcs.cfg]]} {
        set finfo(lbl,$index) "$f (PVCS $rev)"
        die-unless "exec get -p $pvcsopt $f" $finfo(pth,$index)
        filterCRCRLF $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

    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 {
	    "^-r$" {
		incr argindex
		incr revs
		set rev($revs) [lindex $argv $argindex]
	    }
	    "^-r.*" {
		incr revs
		set rev($revs) [string range $arg 2 end]
	    }
	    "^-conflict$" {
		set conflict 1
	    }
	    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 "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 <file1> or <file2> 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) "$finfo(lbl,1) vs. $finfo(lbl,2)"
}

###############################################################################
# Set up the display...
###############################################################################
proc create-display {} {
    global g opts bg tk_version

    # Initial window size. We want to set the window size and have the
    # contents resize. This seems not to work for Diff Map toggling.
    if {[catch "wm geometry . $opts(geometry)"]} {
	do-error "Invalid geometry setting"
    }
    # Highlighthickness for text widgets (size of black focus border)
    set hlthick 2

    # Pack the bottom-row buttons (inside .b).
    pack [frame .b1 -bd 2 -relief sunken] \
        -side top -fill x
    pack [frame .b -bd 2 -relief sunken] \
        -side top -fill x

    # File menu
    pack [menubutton .b1.em -menu .b1.em.menu -text "File" -underline 0] \
        -side left
    menu .b1.em.menu
    .b1.em.menu add command -label "Configure" -underline 3 -command customize
    .b1.em.menu add command -label "Restart" -underline 0 -command do-diff
    .b1.em.menu add separator
    .b1.em.menu add command -label "Write Merge File" -underline 6 \
	-command popup-merge
    .b1.em.menu add command -label "Write Change Summary" -underline 13 \
	-command popup-changes
    .b1.em.menu add separator
#     .b1.em.menu add command -label "Tcl" -underline 0 \
#         -command {exec [selection get]}
#    .b1.em.menu add separator
    .b1.em.menu add command -label "Exit" -underline 1 \
	-command "catch del-tmp; destroy ."

    # View menu
    pack [menubutton .b1.em2 -menu .b1.em2.menu -text View -underline 0] \
        -side left
    menu .b1.em2.menu
    .b1.em2.menu add checkbutton -label "Show Line Numbers" -underline 5 \
        -variable opts(showln) -command do-show-linenumbers
    if {! $g(megascrollbar)} {
	.b1.em2.menu add checkbutton -label "Synchronize Scrollbars" -underline 0 \
	    -variable opts(syncscroll)
    }
    .b1.em2.menu add checkbutton -label "Auto Center" -underline 0 \
	-variable opts(autocenter) -command {if {$opts(autocenter)} {center}}
    .b1.em2.menu add checkbutton -label "Diff Map" -underline 5 \
	-variable opts(showmap) -command do-show-map
    .b1.em2.menu add checkbutton -label "Merge Preview" -underline 9 \
	-variable g(showmerge) -command do-show-merge

    .b1.em2.menu add separator
    .b1.em2.menu add command -label "Next" -underline 0 -command { move 1 }
    .b1.em2.menu add command -label "Prev" -underline 0 -command { move -1 }
    .b1.em2.menu add command -label "Center" -underline 0 -command { center }

    pack [label .b1.label -textvariable finfo(title) -bg $bg -fg white \
	      -relief groove -bd 2 -justify center] \
        -side left -fill x -expand yes

    # Help menu
    pack [menubutton .b1.hm -menu .b1.hm.menu -text Help -underline 0] \
        -side right
    menu .b1.hm.menu
    .b1.hm.menu add command -label "On GUI" -underline 0 -command do-help
    .b1.hm.menu add command -label "On Command Line" -underline 0 -command do-usage
    .b1.hm.menu add command -label "About TkDiff" -underline 0 -command do-about

    # Pack the "current diff" widgets.
    pack [frame .b.pos -relief raised] \
        -side left -fill x
    pack [menubutton .b.pos.menubutton -menu .b.pos.menubutton.menu \
	      -width 5 -textvariable g(pos) -relief raised] \
        -side left
    menu .b.pos.menubutton.menu
    pack [label .b.pos.nlabel -text "of"] \
        -side left
    # Have to set width or label resizes itself and often the whole window
    pack [label .b.pos.num -textvariable g(count) -width 3] \
        -side left
    pack [label .b.pos.phdr -text ":"] \
        -side left
    # Have to set width or label resizes itself and often the whole window
    pack [label .b.pos.curr -textvariable g(currdiff) -anchor w -width 25] \
        -side left -fill x

    # Pack the next and prev buttons.
    pack [button .b.center -text Center -command center -takefocus 0] \
        -side right
    pack [button .b.prev -text Prev -command {move -1} -takefocus 0] \
        -side right
    pack [button .b.next -text Next -command {move 1} -takefocus 0] \
        -side right

    # Pack the merge widgets.
    pack [radiobutton .b.f2 -text 2 -value 2 -variable g(toggle) \
	      -command {do-merge-choice 2} -takefocus 0] \
        -side right
    pack [radiobutton .b.f1 -text 1 -value 1 -variable g(toggle) \
	      -command {do-merge-choice 1} -takefocus 0] \
        -side right
    pack [label .b.mhdr -text "Merge Choice:"] \
        -side right

    # Pack the horizontal balance bar and mega-scrollbar.
    if {$g(megascrollbar)} {
	pack [scrollbar .hscrmega -orient horizontal -command texts-xview] \
	    -side top -fill x
    }

    # Pack the "old" and "new" widgets (.1 and .2).
    pack [frame .1] \
        -side left -fill both -expand yes
    if {$g(megascrollbar)} {
	pack [scrollbar .scr -command {.1.text yview} -bd 1 -relief raised] \
	    -side left -fill y
    }

    pack [frame .2] \
        -side left -fill both -expand yes

    # Pack the text widgets and the scrollbars.

    if {$g(megascrollbar)} {
	set hside top
	set vside left
    } else {
	set hside bottom
	set vside right
    }

    # Left windows and scrollbars
    pack [scrollbar .1.hscr -orient horizontal -command {.1.text xview} \
	      -takefocus 0] \
        -side $hside -fill x
    text .1.info -width 6 -setgrid 1 -highlightthickness $hlthick \
        -yscrollcommand "vscroll-sync 1"
    pack [scrollbar .1.scr -command {.1.text yview} -takefocus 0] \
        -side $vside -fill y
    pack [text .1.text -width 1 -setgrid 1 -highlightthickness $hlthick \
	      -takefocus 1 \
	      -yscrollcommand "vscroll-sync 1" \
	      -xscrollcommand "hscroll-sync 1"] \
        -side left -fill both -expand yes

    # Right windows and scrollbars
    pack [scrollbar .2.hscr -orient horizontal -command {.2.text xview} \
	      -takefocus 0] \
        -side $hside -fill x
    text .2.info -width 12 -setgrid 1 -highlightthickness $hlthick \
        -yscrollcommand "vscroll-sync 2"
    pack [scrollbar .2.scr -command {.2.text yview} -takefocus 0] \
        -side right -fill y
    pack [text .2.text -width 1 -setgrid 1 -highlightthickness $hlthick \
	      -takefocus 1 \
	      -yscrollcommand "vscroll-sync 2" \
	      -xscrollcommand "hscroll-sync 2"] \
        -side right -fill both -expand yes

    # Map
    image create photo map
    canvas .2.map -width 10 -yscrollcommand map-resize -borderwidth 1 -relief raised
    .2.map create image 0 0 -image map -anchor nw
    bind .2.map <1> "map-scroll %y"
    bind .2.map <Button1-Motion> "map-scroll %y"
    bind .2.map <2> "map-scroll %y"
    bind .2.map <Button2-Motion> "map-scroll %y"


    # 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 w {.1.info .1.text .2.info .2.text} {
	eval "$w configure $opts(textopt)"
	foreach tag {currtag difftag deltag instag chgtag} {
	    eval "$w tag configure $tag $opts($tag)"
	}
        # Selection should have higher priority than other tags
        $w tag raise sel
    }

    # Make sure temporary files get deleted
    bind . <Destroy> { del-tmp }

    common-navigation {.1.text .2.text}

    # On Windows, tabbing doesn't work with tk8.0p2
    bind .1.text <Shift-Key-Tab> { focus .2.text }
    bind .2.text <Shift-Key-Tab> { focus .1.text }

    wm deiconify .
    focus -force .1.text
    update idletasks
}

###############################################################################
# Bind keys for Next, Prev, Center, Merge choices 1 and 2
###############################################################################
proc common-navigation {wlist} {
    foreach w $wlist {
        bind $w <Key-c> { .b.center invoke }
        bind $w <Key-n> { .b.next invoke }
        bind $w <Key-p> { .b.prev invoke }
        bind $w <Key-1> { .b.f1 invoke }
        bind $w <Key-2> { .b.f2 invoke }
    }
}

###############################################################################
# Customize the display (among other things).
###############################################################################

proc customize {} {
    global opts
    global tmpopts

    catch {destroy .cust}
    toplevel .cust
    wm title .cust "TkDiff Customization"
    wm minsize .cust 40 10

    set lbl(diffopt)  {Options for the 'diff' process:}
    set lbl(textopt)  {Text widget options (Tcl/Tk code):}
    set lbl(difftag)  {Tag options for diff regions (Tcl/Tk code):}
    set lbl(currtag)  {Tag options for the current diff region (Tcl/Tk code):}
    set lbl(deltag)   {Tag options for deleted diff region (Tcl/Tk code):}
    set lbl(instag)   {Tag options for inserted diff region (Tcl/Tk code):}
    set lbl(chgtag)   {Tag options for changed diff region (Tcl/Tk code):}
    set lbl(geometry) {Initial window size WIDTHxHEIGHT (for the *next* session):}
    set lbl(tmpdir)   {Directory for scratch files (for the *next* session):}

    set count 0

    # Text fields
    foreach key {diffopt textopt difftag currtag deltag instag chgtag \
		     geometry tmpdir} {
        pack [frame .cust.$count] \
                -side top -expand yes -fill both
        pack [label .cust.$count.l -text $lbl($key) -width 45 -anchor w] \
                -side left
        set tmpopts($key) $opts($key)
        pack [entry .cust.$count.e -textvariable tmpopts($key) -width 50 \
                -bd 2 -relief sunken] \
                -side left -expand yes -fill both
        incr count
    }

    set lbl(showmap)    {Show map of diffs:}
    set lbl(showln)     {Show line numbers:}
    set lbl(autocenter) {Automatically center current diff region in window:}
    set lbl(syncscroll) {Synchronize scrollbars:}

    # Option fields
    foreach key {showmap showln autocenter syncscroll} {
        pack [frame .cust.$count] \
                -side top -expand yes -fill both
        pack [label .cust.$count.l -text $lbl($key) -width 45 -anchor w] \
                -side left
        pack [radiobutton .cust.$count.e -text "Yes" -variable tmpopts($key) \
		  -value 1] \
	    [radiobutton .cust.$count.e2 -text "No" -variable tmpopts($key) \
		 -value 0] \
	    -side left -expand yes -fill both
        set tmpopts($key) $opts($key)
        incr count
    }

    pack [frame .cust.b] \
            -side top -expand yes -fill x
    pack [button .cust.b.apply -text apply -command apply] \
            -side left -expand yes -fill x
    pack [button .cust.b.save -text save -command save] \
            -side left -expand yes -fill x
    pack [button .cust.b.dismiss -text dismiss -command {destroy .cust}] \
            -side left -expand yes -fill x
}

###############################################################################
# Apply customization changes.
###############################################################################

proc apply {} {
    global opts
    global tmpopts

    if {! [file isdirectory $tmpopts(tmpdir)]} {
	do-error "Invalid temporary directory $tmpopts(tmpdir)"
    }
    
    if {[catch ".1.text configure $tmpopts(textopt)
                .2.text configure $tmpopts(textopt)"]} {
        do-error "Invalid settings!"
        eval ".1.text configure $opts(textopt)"
        eval ".2.text configure $opts(textopt)"
	return
    } 

    foreach tag {difftag currtag deltag instag chgtag} {
	foreach w {.1.text .2.text .2.info} {
	    if {[catch "$w tag configure $tag $tmpopts($tag)"]} {
		do-error "Invalid settings!\n$opts($tag)"
		eval "$w tag configure $tag $opts($tag)"
		return
	    }
	}
    }

    foreach key {diffopt textopt difftag currtag deltag instag chgtag tmpdir \
		     showmap showln autocenter syncscroll geometry} {
	set opts($key) $tmpopts($key)
    }
    do-show-linenumbers
    do-show-map
}

###############################################################################
# Save customization changes.
###############################################################################

proc save {} {
    global tmpopts rcfile tcl_platform

    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]

    foreach key {diffopt textopt difftag currtag deltag instag chgtag \
		     showmap showln autocenter syncscroll geometry} {
        puts $fid "set opts($key) {$tmpopts($key)}"
    }
    # Seems we can't use {$tmpdir} here or embedded \\ don't translate to \ 
    puts $fid "set opts(tmpdir) \"$tmpdir\""

    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

    # 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
    }

    if {$g(megascrollbar)} {
	eval ".hscrmega set $args"
    }

    # Scrollbar sizes
    set size1 [expr [lindex [.1.text xview] 1] - [lindex [.1.text xview] 0]]
    set size2 [expr [lindex [.2.text xview] 1] - [lindex [.2.text xview] 0]]

    if {$opts(syncscroll) || $id == 1} {
	set start [lindex $args 0]

        if {$id != 1} {
            set start [expr $start * $size2 / $size1]
        }
	eval ".1.hscr set $start [expr $start + $size1]"
	.1.text 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]
        }
	eval ".2.hscr set $start [expr $start + $size2]"
	.2.text 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_hevent.
    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 {id args} {
    global g opts

    # If ignore_event is true, we've already taken care of scrolling.
    # We're only interested in the first event.
    if {$g(ignore_event,$id)} {
	return
    }

    if {$g(megascrollbar)} {
	eval ".scr set $args"
    }

    # Topmost visible "line"
    set pos [expr double([lindex $args 0])]
    
    if {$opts(syncscroll) || $id == 1} {
	eval ".1.scr set $args"
	.1.text yview moveto $pos
	.1.info yview moveto $pos
	set g(ignore_event,1) 1
    }
    if {$opts(syncscroll) || $id == 2} {
	eval ".2.scr set $args"
	.2.text yview moveto $pos
	.2.info yview moveto $pos
	set g(ignore_event,2) 1
     }

    # Select nearest visible diff region
    if {$opts(syncscroll) && $g(autoselect) && $g(count) > 0} {
	set winhalf [expr [winfo height .2.text] / 2]
	set result [find-diff [expr int([.2.text index @1,$winhalf])]]
	scan $result "%d %d" i newtop
	move $i 0 0
    }

    # 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_event,1) 0
    set g(ignore_event,2) 0
}

###############################################################################
# Make a miniature map of the diff regions
###############################################################################

proc map-create {map mapwidth mapheight} {
    global g

    # Text widget always contains blank line at the end
    set lines [expr double([.1.text 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
	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]
    }
}

###############################################################################
# Resize map to fit window size
###############################################################################

proc map-resize {args} {
    global g opts

    set mapwidth  [winfo width .2.map]
    set g(mapborder) [expr \
			  [.2.map cget -borderwidth] + \
			  [.2.map cget -highlightthickness]]
    set mapheight [expr [winfo height .2.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 .2.map] is then 0...
    if {$mapheight < 1} {
        return
    }

    set g(mapheight) $mapheight
    map-create map $mapwidth $mapheight
}

###############################################################################
# Button down on map scrolls windows, selects nearest diff
###############################################################################

proc map-scroll {y} {
    global g
    
    set mapheight [winfo height .2.map]
    set yview [.2.text yview]
    # Half the window height for centering
    set half [expr ([lindex $yview 1] - [lindex $yview 0]) / 2]
    # Show text corresponding to map
    catch {.2.text yview moveto \
	       [expr double($y - $g(mapborder)) / $g(mapheight) - $half]}
    update idletasks

    # Select the diff region closest to the middle of the screen
    set winhalf [expr [winfo height .2.text] / 2]
    set result [find-diff [expr int([.2.text index @1,$winhalf])]]
    move [lindex $result 0] 0 0
    if {$g(showmerge)} {
	merge-center
    }
}

###############################################################################
# Toggle showing map or not
###############################################################################

proc do-show-map {} {
    global opts

    if {$opts(showmap)} {
	pack .2.map -side right -pady 16 -fill y -before .2.scr
    } else {
	pack forget .2.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
		
    set top $line
    set newtop [expr $top - int([.1.text index end]) + \
                            int([.2.text index end])]

    for {set low 1; set high $g(count); set i [expr ($low + $high) / 2]} \
            {$i >= $low}                                                 \
            {set i [expr ($low + $high) / 2]} {

        scan $g(scrdiff,$i) "%s %d %d %d %d" line s1 e1 s2 e2

        if {$s1 > $top} {
            set newtop [expr $top - $s1 + $s2]
            set high [expr $i-1]
        } else {
            set low [expr $i+1]
        }
    }

    # 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 "$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

    set lines [expr $e($version) - $s($version) + 1]
    if {$type == "d" && $version == 2} {incr lines -1}
    if {$type == "a" && $version == 1} {incr lines -1}
    return $lines
}

###############################################################################
# Scroll the windows horizontally.
###############################################################################

proc texts-xview {args} {
    eval .1.text xview $args
    eval .2.text xview $args
}

###############################################################################
# Toggle showing merge preview or not
###############################################################################

proc do-show-merge {} {
    global g
    
    if {$g(showmerge)} {
        set-cursor .
	merge-create-window
	if {[catch merge-read-file result]} {
	    catch {fatal-error $result}
	} else {
	    merge-add-marks
	}
        .merge.text configure -state disabled
        focus -force .merge.text
        merge-center
        restore-cursor .
    } else {
	catch { destroy .merge }
    }
}

###############################################################################
# Create Merge preview window
###############################################################################

proc merge-create-window {} {
    global opts
    
    catch {destroy .merge}
    toplevel .merge
    wm title .merge "TkDiff Merge Preview"
    wm minsize .merge 40 10

    # Menu bar
    pack [frame .merge.f -bd 2 -relief sunken] -side top -fill x

    # File menu
    pack [menubutton .merge.f.m -menu .merge.f.m.file -text File -underline 0] \
        -side left
    menu .merge.f.m.file
    .merge.f.m.file add command -label "Write Merge File" -underline 6 \
	-command {popup-merge merge-write-file}
    .merge.f.m.file add separator
    .merge.f.m.file add command -label "Close" -command {destroy .merge}

    # Window and scrollbars
    pack [scrollbar .merge.hscr -orient horizontal \
	      -command {.merge.text xview}] \
        -side bottom -fill x
    pack [scrollbar .merge.scr -command {.merge.text yview} -bd 1 \
	      -relief raised] \
        -side right -fill y
    pack [text .merge.text -takefocus 1 \
	      -yscrollcommand {.merge.scr set} \
	      -xscrollcommand {.merge.hscr set}] \
        -side left -fill both -expand yes

    eval ".merge.text configure $opts(textopt)"
    foreach tag {difftag currtag} {
	eval ".merge.text tag configure $tag $opts($tag)"
    }
    # Selection should have higher priority than other tags
    .merge.text tag raise sel

    bind .merge <Destroy> { set g(showmerge) 0 }
    common-navigation .merge.text
}

###############################################################################
# Read original file (left window file) into merge preview window.
# Not so good if it has changed.
###############################################################################

proc merge-read-file {} {
    global finfo

    set hndl [open "$finfo(pth,1)" r]
    .merge.text 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$} [.merge.text index "end-1lines lineend"]]} {
	.merge.text insert end "\n"
    }
}

###############################################################################
# Write merge preview to file
###############################################################################

proc merge-write-file {} {
    global g

    set hndl [open "$g(mergefile)" w]
    set text [.merge.text 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

    for {set i 1} {$i <= $g(count)} {incr i} {
	scan $g(pdiff,$i) "%s %d %d %d %d %s" \
            thisdiff s1 e1 s2 e2 type
	set delta [expr {$type == "a" ? 1 : 0}]
	.merge.text mark set mark$i $s1.0+${delta}lines
	.merge.text mark gravity mark$i left

	if {$g(merge$i) == 1} {
	    # (If it's an insert it's not visible)
	    if {$type != "a"} {
		set lines [expr $e1 - $s1 + 1]
		.merge.text 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)]
	.merge.text 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

    set oldlines [diff-size $pos $oldversion]
    .merge.text delete mark$pos "mark${pos}+${oldlines}lines"

    # Screen coordinates
    scan $g(scrdiff,$pos) "%s %d %d %d %d %s" \
	thisdiff s(1) e(1) s(2) e(2) type
    # Get the text directly from window
    set newlines [diff-size $pos $newversion]
    set newtext [.$newversion.text get $s($newversion).0 \
		     $s($newversion).0+${newlines}lines]
    # Insert it
    .merge.text insert mark$pos $newtext diff
    if {$pos == $g(pos)} {
	.merge.text tag add currtag mark$pos "mark${pos}+${newlines}lines"
    }
}

###############################################################################
# Center the merge region in the merge window
###############################################################################

proc merge-center {} {
    global g

    # Size of diff in lines of text
    set difflines [diff-size $g(pos) $g(merge$g(pos))]
    set yview [.merge.text yview]
    # Window height in percent
    set ywindow [expr [lindex $yview 1] - [lindex $yview 0]]
    # First line of diff
    set firstline [.merge.text index mark$g(pos)]
    # Total number of lines in window
    set totallines [.merge.text index end]

    if {$difflines / $totallines < $ywindow} {
	# Diff fits in window, center it
	.merge.text yview moveto [expr ($firstline + $difflines / 2) \
				  / $totallines - $ywindow / 2]
    } else {
	# Diff too big, show top part
	.merge.text 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

    if {$g(showmerge)} {
        .merge.text configure -state normal
	merge-select-version $g(pos) $g(merge$g(pos)) $newversion
        .merge.text 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} {
    global g

    if [regexp {^([0-9]+)(a|c|d)} $line d digit action] {
        set s1 $digit
        set e1 $digit
    } elseif [regexp {^([0-9]+),([0-9]+)(a|c|d)} $line d start end action] {
        set s1 $start
        set e1 $end
    }

    if [regexp {(a|c|d)([0-9]+)$} $line d action digit] {
        set s2 $digit
        set e2 $digit
    } elseif [regexp {(a|c|d)([0-9]+),([0-9]+)$} $line d action start end] {
        set s2 $start
        set e2 $end
    }

    if {[info exists s1] && [info exists s2]} {
        return "$line $s1 $e1 $s2 $e2 $action"
    } 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

    # Figure out which lines we need to address...
    catch { scan $g(pdiff,$pos) "%s %d %d %d %d %s" \
            thisdiff s1 e1 s2 e2 type } res
    if {$res != 6} { return }
    
    if {$g(compact)} {
	set g(scrdiff,$g(count)) "$thisdiff $s1 $e1 $s2 $e2 $type"
	return
    }

    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 text "Insert"
	    set tag instag
	    set idx 1
	    set count [expr $size(2) + 1]

	    incr s1
	    incr size(2)
	}
	
	"d" {
	    set text "Delete"
	    set tag deltag
	    set idx 2
	    set count [expr $size(1) + 1]

	    incr s2
	    incr size(1)
	}

	"c" {
	    set text "Change"
	    set tag chgtag
	    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 blank "++++++\n"
    } else {
	set blank "      \n"
    }

    # Insert blank lines to match other window
    set line [expr $s1 + $size($idx)]
    for {set i 0} {$i < $count} {incr i} {
	.$idx.text insert $line.0 "\n"
	.$idx.info insert $line.0 $blank
    }

    incr size($idx) $count
    set e1 [expr $s1 + $size(1) - 1]
    set e2 [expr $s2 + $size(2) - 1]
    incr g(delta,$idx) $count

    # Insert comments as to what has changed in right window
    for {set i $s1} {$i <= $e1} {incr i} {
	.2.info insert $i.6 $text $tag
    }

    # Save the diff block in window coordinates
    set g(scrdiff,$g(count)) "$thisdiff $s1 $e1 $s2 $e2 $type"
}

###############################################################################
# Add a tag to a region.
###############################################################################

proc add-tag {wgt tag start end type new} {
    global g
    
    if {! $g(compact) ||
	$type == "c" || ($type == "a" && $new) || ($type == "d" && !$new)} {
	# Mark block of lines
        $wgt tag add $tag $start.0 [expr $end + 1].0
    } else {
	# Put 6 char wide mark in left column
	for {set idx $start} {$idx <= $end} {incr idx} {
	    $wgt tag add $tag $idx.0 $idx.6
	}
    }
}

###############################################################################
# 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
    
    # Figure out which lines we need to address...
    catch { scan $g(scrdiff,$pos) "%s %d %d %d %d %s" \
            thisdiff s1 e1 s2 e2 dt } res
    if {$res != 6} { return }

    # Remove old tag
    if {"$oldtag" != ""} {
	.1.text tag remove $oldtag $s1.0 [expr $e1 + 1].0
	.2.text tag remove $oldtag $s2.0 [expr $e2 + 1].0
	if {$g(showmerge)} {
	    set lines [diff-size $pos $g(merge$pos)]
	    .merge.text tag remove $oldtag mark$pos "mark${pos}+${lines}lines"
	}
    }

    if {$g(compact)} {
	set coltag $newtag
    } else {
	switch $dt {
	    "d" { set coltag deltag }
	    "a" { set coltag instag }
	    "c" { set coltag chgtag }
	}
    }
    
    # Add new tag
    add-tag .1.text $newtag $s1 $e1 $dt 0
    add-tag .2.text $coltag $s2 $e2 $dt 1
    if {$g(showmerge)} {
	set lines [diff-size $pos $g(merge$pos)]
	.merge.text 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 {
	    .1.text see $s1.0
	    .2.text see $s2.0
	    if {$g(showmerge)} {
		.merge.text see mark$pos
	    }
	}
    }

    return $thisdiff
}

###############################################################################
# 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

    # 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) [min $g(pos) $g(count)]
    set g(pos) [max $g(pos) 1]

    # Set new 'curr' tag
    set g(currdiff) [set-tag $g(pos) currtag difftag $setpos]
    
    # Update the toggles.
    if {$g(count)} {
	set g(toggle) $g(merge$g(pos))
    }
}

###############################################################################
# Center the top line of the CDR in each window.
###############################################################################

proc center {} {
    global g

    scan $g(scrdiff,$g(pos)) "%s %d %d %d %d %s" dummy s1 e1 s2 e2 dt

    # Window requested height in pixels
    set opix [winfo reqheight .1.text]
    # Window requested lines
    set olin [.1.text cget -height]
    # Current window height in pixels
    set npix [winfo height .1.text]

    # Visible lines
    set winlines [expr $npix * $olin / $opix]
    # Lines in diff
    set diffsize [max [expr $e1 - $s1 + 1] [expr $e2 - $s2 + 1]]

    if {$diffsize < $winlines} {
	set h [expr ($winlines - $diffsize) / 2]
    } else {
	set h 2
    }
    
    set o [expr $s1 - $h]
    if {$o < 0} { set o 0 }
    set n [expr $s2 - $h]
    if {$n < 0} { set n 0 }

    .1.text yview $o
    .2.text yview $n

    if {$g(showmerge)} {
	merge-center
    }
}

###############################################################################
# Change the state on all of the diff-sensitive buttons.
###############################################################################

proc buttons {{newstate "normal"}} {
    foreach b { pos.menubutton next prev center f1 f2 } {
        ".b.$b" configure -state $newstate
    }
    foreach i { "Write M*" "Write C*" } {
	.b1.em.menu entryconfigure $i -state $newstate
    }
    foreach i { Next Prev Center } {
	.b1.em2.menu entryconfigure $i -state $newstate
    }
}

###############################################################################
# Wipe the slate clean...
###############################################################################

proc wipe {} {
    global g
    global finfo

    set g(pos)      0
    set g(count)    0
    set g(diff)     ""
    set g(currdiff) ""

    set g(delta,1)    0
    set g(delta,2)    0
}

###############################################################################
# Wipe all data and all windows
###############################################################################

proc wipe-window {} {
    global g

    wipe
    
    foreach mod {1 2} {
	.$mod.text configure -state normal
	.$mod.text tag remove difftag 1.0 end
	.$mod.text tag remove currtag 1.0 end
	.$mod.text delete 1.0 end

	.$mod.info configure -state normal
	.$mod.info delete 1.0 end
    }

    catch {.merge.text delete 1.0 end }

    if {[string length $g(destroy)] > 0} {
        eval $g(destroy)
        set g(destroy) ""
    }

    .b.pos.menubutton.menu delete 0 last
    buttons disabled
}

###############################################################################
# Mark difference regions and build up the jump menu.
###############################################################################

proc mark-diffs {} {
    global g

    set numdiff [llength "$g(diff)"]

    # If there are <= 30 diffs, do a one-level jump menu.  If there are
    # more than 30, do a two-level jump menu with sqrt(numdiff) in each
    # level.

    set g(count) 0

    set cascading [expr $numdiff > 30]
    if {$cascading} {
        set target 0
	set increment [expr int(pow($numdiff,0.5))]
    } else {
        set target [expr $numdiff + 1]
        set g(destroy) "$g(destroy) \
                catch \"eval .b.pos.menubutton.menu delete 0 last\"\n"
    }

    foreach d $g(diff) {
	set result [extract $d]

	if {$result != ""} {
	    incr g(count)
	    set g(merge$g(count)) 1

	    if {$g(count) >= $target} {
		# Create a new submenu
		.b.pos.menubutton.menu add cascade -label $target \
		    -menu .b.pos.menubutton.menu.$target
		menu .b.pos.menubutton.menu.$target

		set current $target
		set target [expr $target + $increment]
	    
		set g(destroy) \
		    "$g(destroy) \
	            catch \"eval .b.pos.menubutton.menu.$current \
   	            delete 0 last\"\n \
                    catch \"eval destroy .b.pos.menubutton.menu.$current\"\n"
	    }

	    set g(pdiff,$g(count)) "$result"
	    add-lines $g(count)

	    set-tag $g(count) difftag

	    if {$cascading} {
		.b.pos.menubutton.menu.$current add command \
		    -label [format "%-6d --> %s" $g(count) $d] \
		    -command "move $g(count) 0"
	    } else {
		.b.pos.menubutton.menu add command \
		    -label [format "%-6d --> %s" $g(count) $d] \
		    -command "move $g(count) 0"
	    }
	}
    }

    return $g(count)
}

###############################################################################
# Remark difference regions...
###############################################################################

proc remark-diffs {} {
    global g

    for {set i 1} {$i <= $g(count)} {incr i} {
	set-tag $i difftag
    }
}

###############################################################################
# Put up some informational text.
###############################################################################

proc show-info {message} {
    global g

    set g(currdiff) $message
    update idletasks
}

###############################################################################
# Compute differences (start over, basically).
###############################################################################

proc rediff {} {
    global g
    global opts
    global finfo
    global tcl_platform

    buttons disabled

    # Read the files into their respective widgets & add line numbers.
    foreach mod {1 2} {
        show-info "Reading [lindex {0 first second} $mod] file..."
        if [catch {set hndl [open "$finfo(pth,$mod)" r]}] {
	    fatal-error "Failed to open file: $finfo(pth,$mod)"
	}
        .$mod.text insert 1.0 [read $hndl]
        close $hndl

	# Check if last line doesn't end with newline
        if {![regexp {\.0$} [.$mod.text index "end-1lines lineend"]]} {
            .$mod.text insert end "  <-- newline inserted by tkdiff\n"
        }
    }

    # Diff the two files and store the summary lines into 'g(diff)'.
    show-info "Executing \"diff\"..."

    set diffcmd "{$g(diffexec)} $opts(diffopt) {$finfo(pth,1)} {$finfo(pth,2)}"

    set result [run-command "exec $diffcmd"]
    set stdout   [lindex $result 0]
    set stderr   [lindex $result 1]
    set exitcode [lindex $result 2]

    # The exit code is 0 if there are no differences and 1 if there
    # are differences. Any other exit code means trouble and we abort.
    if {$exitcode < 0 || $exitcode > 1 || $stderr != ""} {
        fatal-error "diff failed:\n$stderr"
    }
    
    set g(diff) {}
    set lines [split $stdout "\n"]

    # If there is no output and we got this far the files are equal,
    # otherwise check if the first line begins with a line number. If
    # not there was trouble and we abort. For instance, using a binary
    # file results in the message "Binary files ..." etc on stdout,
    # exit code 1. The message may wary depending on locale.
    if {$lines != "" && [string match {[0-9]*} $lines] != 1} {
        fatal-error "diff failed:\n$stdout"
    }

    # Collect all lines containing line numbers
    foreach line $lines {
	if [string match {[0-9]*} $line] { lappend g(diff) $line }
    }

    # Mark up the two text widgets and go to the first diff (if there
    # is one).

    show-info "Adding line numbers..."
    draw-line-numbers

    show-info "Marking differences..."

    foreach mod {1 2} {
        .$mod.info configure -state normal
    }

    if {[mark-diffs]} {
        set g(pos) 1
	update idletasks
        move 1 0
        buttons normal
    } else {
        show-info "Files are identical."
        buttons disabled
    }

    # Prevent tampering in the text widgets.
    foreach mod {1 2} {
        .$mod.text configure -state disabled
        .$mod.info configure -state disabled
    }
}

###############################################################################
# Set the X cursor to "watch" for a window and all of its descendants.
###############################################################################

proc set-cursor {w} {
    global current

    # Check if window already has watch cursor, might be torn off menu
    set cursor [$w cget -cursor]
    if {$cursor != "watch"} {
        set current($w) $cursor
        $w configure -cursor watch
    }
    foreach child [winfo children $w] {
        set-cursor $child
    }
}

###############################################################################
# Restore the X cursor for a window and all of its descendants.
###############################################################################

proc restore-cursor {w} {
    global current

    catch {$w configure -cursor $current($w)}
    foreach child [winfo children $w] {
        restore-cursor $child
    }
}

###############################################################################
# Check if error was thrown by us or unexpected
###############################################################################

proc check-error {result output} {
    global g errorInfo

    if {$g(debug) && $result && $output != "Fatal"} {
	error $result $errorInfo
    }
}

###############################################################################
# Flash the "rediff" button and then kick off a rediff.
###############################################################################

proc do-diff {} {
    global g map errorInfo
    
    set-cursor .
    update idletasks
    wipe-window
    set result \
	[catch {
	    if {$g(mapheight)} {
		map blank
	    }
	    init-files
	    rediff
	    
	    # If a map exists, recreate it
	    if {$g(mapheight)} {
		set g(mapheight) -1
		map-resize
	    }
	} output]
    check-error $result $output 

    restore-cursor .
}

###############################################################################
# Get things going...
###############################################################################

proc main {} {
    global g errorInfo
    
    wipe

    # Run init-files here to check existence of files; before there's
    # a window. If something goes wrong, the command line was probably
    # bad so there's no hope of accomplishing anything.
    set result [catch init-files output]
    check-error $result $output
    if {$result} {
	del-tmp
	exit 2
	return
    }
    create-display

    # Give the window a name
    wm title . $g(version)

    set g(started) 1

    do-show-linenumbers
    do-show-map

    # Compute the differences...
    set-cursor .
    update idletasks

    set result \
	[catch {
	    rediff
	    do-show-merge
	 } output]
    check-error $result $output

    # Do this to setup the scrollbar sizes, otherwise the
    # initial events are ignored on Windows
    hscroll-sync 1 0 1

    restore-cursor .
}

###############################################################################
# Erase tmp files (if necessary) and destroy the application.
###############################################################################

proc del-tmp {} {
    global g finfo

    if {$finfo(tmp,1)} {file delete $finfo(pth,1)}
    if {$finfo(tmp,2)} {file delete $finfo(pth,2)}
    foreach f $g(tempfiles) {file delete $f} 
}

###############################################################################
# Throw up a window with formatted text
# Note: Couldn't get .help.f.text to do the
# equivalent of an ipadx without resorting to another level of frames...
# What gives?
###############################################################################

proc do-text-info {w title text} {
    global g

    catch "destroy $w"
    toplevel $w
    wm title $w $title
    wm geometry $w 55x29
    wm minsize $w 30 5

    pack [frame $w.f] \
            -expand y -fill both
    pack [frame $w.f.f -background white] \
            -expand y -fill both
    pack [scrollbar $w.f.f.scr -command "$w.f.f.text yview"] \
            -side right -fill y -padx 1
    pack [text $w.f.f.text -wrap word -setgrid true \
            -width 50 -height 1 -yscroll "$w.f.f.scr set" \
            -background white -foreground black] \
            -side left -expand y -fill both -padx 5 -pady 5
    focus -force $w.f.f.text
    pack [button $w.f.done -text Dismiss -command "destroy $w"] \
            -side top -fill x
    put-text $w.f.f.text  [join "{$g(preview)} {$text}"]
    $w.f.f.text configure -state disabled
}

###############################################################################
# Throw up an "about" window.
###############################################################################

proc do-about {} {
    set text {
<itl>TkDiff</itl> is a Tcl/Tk front-end to <itl>diff</itl> for Unix and NT, and is Copyright (C) 1994-1998 by John M. Klassa.

<bld>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</bld>

    }
    do-text-info .about "About TkDiff" $text
}

###############################################################################
# Throw up a "command line usage" window.
###############################################################################

proc do-usage {} {
    set text {
<hdr>Startup</hdr>

<itl>TkDiff</itl> may be started in any of the following ways:

    Plain files:
<cmp>	tkdiff FILE1 FILE2</cmp>
	
    Plain file with conflict markers:
<cmp>	tkdiff -conflict FILE</cmp>
   	
    Source control RCS/CVS/SCCS/PVCS:
<cmp>	tkdiff FILE    </cmp>(same as -r)
<cmp>	tkdiff -r FILE
	tkdiff -rREV FILE
	tkdiff -rREV -r FILE
	tkdiff -rREV1 -rREV2 FILE</cmp>

TkDiff detects and supports RCS, CVS, and SCCS by looking for a directory with the same name.  It detects and supports PVCS by looking for a vcs.cfg file.

In the first form, at least one of the arguments must be the name of a plain text file.  Symbolic links are acceptable, but at least one of the filename arguments must point to a real file rather than to a directory.  In the other forms, <cmp>REV</cmp> (or <cmp>REV1</cmp> and <cmp>REV2</cmp>) must be a valid RCS, CVS or SCCS revision number for <cmp>FILE</cmp>.  Where RCS, CVS, or SCCS are implied but no revision number is specified, <cmp>FILE</cmp> is compared with the the revision most recently checked in.

To merge a file with conflict markers generated by "<cmp>merge</cmp>", "<cmp>cvs</cmp>", or "<cmp>vmrg</cmp>", use "<cmp>tkdiff -conflict FILE</cmp>".  The file is split into two temporary files which you can merge as usual (see below).

Note that "<cmp>tkdiff FILE</cmp>" is the same as "<cmp>tkdiff -r FILE</cmp>".  The CVS version has priority, followed by the SCCS version -- i.e. if a CVS directory is present, CVS; if not and an SCCS directory is present, SCCS is assumed; otherwise, if a CVS.CFG file is found, PVCS is assumed; otherwise RCS is assumed.

Note also that the "<cmp>tkdiff -rREV -r FILE</cmp>" form results in a comparison between revision <cmp>REV</cmp> and the head of the RCS, CVS, SCCS, or PVCS revision tree.
}

    do-text-info .usage "TkDiff Command Line Help" $text
}

###############################################################################
# Throw up a help window.
###############################################################################

proc do-help {} {
    set text {
<hdr>Layout</hdr>

The top row contains the File, View and Help menus, along with a label that identifies the contents of each text widget.  The second row, just under the top row, is the button row and contains the current diff indicator (and jump menu), the merge fork selector (applies to the CDR), and several navigation buttons (all of which are described below).

The left-most text widget displays the contents of <cmp>FILE1</cmp>, the most recently checked-in revision, <cmp>REV</cmp> or <cmp>REV1</cmp>, respectively (as per the startup options described above).  The right-most widget displays the contents of <cmp>FILE2</cmp>, <cmp>FILE</cmp> or <cmp>REV2</cmp>, respectively.

All difference regions (DRs) are highlighted to set them apart from the surrounding text.  The <itl>current</itl> DR, or CDR, is further set apart so that it can be correlated to its partner in the other text widget (that is, the CDR on the left matches the CDR on the right).

<hdr>Changing the CDR</hdr>

The CDR can be changed in a sequential manner by means of the <btn>Next</btn> and <btn>Previous</btn> buttons.  For random access to the DRs, use the menu under the current difference number label (in the second row) or the diff map, described below.

<hdr>Operations</hdr>

1.  From the <btn>File</btn> menu:

<btn>Configure</btn> pops up a dialog box from which display (and other) options can be changed and saved.  The <btn>Restart</btn> button recomputes the differences between the two files whose names appear at the top of the <itl>TkDiff</itl> window.  The <btn>Write Merge File</btn> button brings up a pop-up which lets you write a merged file to disk.  The <btn>Write Change Summary</btn> button brings up a pop-up which lets you generate a change summary (i.e. a listing of one of the files, with change bars to indicate deviations from the other).  Lastly, the <btn>Exit</btn> button terminates <itl>TkDiff</itl>.

2.  From the <btn>View</btn> menu:

<btn>Show Line Numbers</btn> toggles the display of line numbers in the text widgets.  If <btn>Synchronize Scrollbars</btn> is on, the left and right text widgets are synchronized i.e. scrolling one of the windows scrolls the other.  If <btn>Auto Center</btn> is on, pressing the Next or Prev buttons centers the new CDR automatically.  The <btn>Show Diff Map</btn> toggles the display of the diff map (see below) on or off. <btn>Show Merge Preview</btn> shows or hides the merge preview (see below).

3.  From the <btn>Help</btn> menu:

The <btn>About</btn> button displays copyright and author information; the <btn>Help</btn> button generates this window.

4.  From the button row:

The label next to the current difference number shows the <itl>diff</itl> mnemonic for the CDR.  The current difference number itself is a jump menu that allows you to jump directly to any DR (thereby making it the CDR).  The <btn>Next</btn> and <btn>Previous</btn> buttons take you to the "next" and "previous" DR, respectively.  The <btn>Center</btn> button centers the CDRs in their respective widgets.  You can set <btn>Auto Center</btn> to do this automatically for you.

<hdr>Keyboard Navigation</hdr>

When a text widget has the focus, you may use the following shortcut keys:
     c              Center current diff
     n              Next diff
     p              Previous diff
     1              Merge Choice 1
     2              Merge Choice 2

The cursor, Home, End, PageUp and PageDown keys work as expected.

Focus and tabbing may work poorly. Make sure the window is selected and use Shift+Tab to move the focus. To copy text on Windows, use Shift+Tab to move the focus to the right text widget, then select the text and press Ctrl+Insert to copy it.

<hdr>Scrolling</hdr>

To scroll the text widgets independently, make sure <btn>Synchronize Scrollbars</btn> on the View menu is off.  If it is on, scrolling any text widget scrolls all others.  Scrolling does not change the CDR.

<hdr>Diff Map</hdr>

The diff map is a map of all the diff regions.  It is shown at the far right of the main window if "Show Diff Map" on the View menu is on.  The map is a miniature of the file's diff regions from top to bottom.  Each diff region is rendered as a patch of color, Delete as red, Insert as green and Change as blue.  The height of each patch corresponds to the size of the diff region.

Clicking on the map takes you to the corresponding position in the file.  The diff region nearest to the center of the screen is automatically selected.  If you do not wish to change the CDR, use the right scrollbar and drag the slider until it is next to the diff region on the map instead.

All diff regions are drawn on the map even if too small to be visible.  For large files with small diff regions, this may result in patches overwriting each other.  The accuracy tends to degrade too, that is, matching the slider gets difficult.

Currently, it is not possible to change the colors of the map diff regions due to technical problems with the map's palette.

<hdr>Merging</hdr>

To merge the two files, go through the difference regions (via "Next", "Prev" or whatever other means you prefer) and select "1" or "2" (next to the "Choice:" label) for each.  Selecting "1" means that the the left-most file's version of the difference will be used in creating the final result; choosing "2" means that the right-most file's difference will be used.  Each choice is recorded, and can be changed arbitrarily many times.  To commit the final, merged result to disk, choose "Write Merge File" from the <btn>File</btn> menu.  To change the destination, edit the filename in the resulting pop-up.

<hdr>Merge Preview</hdr>

To see a preview of the file that would be written by "Write Merge File" set "Show Merge Preview" to on in the View menu.  A separate window is shown containing the preview.  It is updated as you change merge choices.  It is synchronized with the other text widgets if "Synchronize Scrollbars" is on.

<hdr>Change Summary</hdr>

To see a summary of the changes from one file to the other, select the <btn>Write Change Summary</btn> selection from the <btn>File</btn> menu.  Select one or the other of the two files as a baseline, choose the output filename (relative to the directory in which you invoked <itl>tkdiff</itl>) and then hit the <btn>Write File</btn> button.

<hdr>Credits</hdr>

Thanks to Wayne Throop for beta testing, and for giving valuable suggestions (and code!) along the way.  Thanks (and credit) to John Heidemann for his window tags routines, which I shamelessly stole (with permission) out of his great Tk-based Solitaire game, <itl>Klondike</itl>.  Thanks to D. Elson (author of <itl>tkCVS</itl>) for writing the code that extends the RCS support to include CVS.  Thanks to John Brown for writing the code that extends the revision control support to SCCS.

<bld>Major</bld> thanks to Warren Jones (wjones@tc.fluke.com) and Peter Brandstrom (qraprbm@era-lvk.ericsson.se) for going way above and beyond the call.  Warren added support for NT and cleaned up the Unix code as well.  Peter, independently, did the same thing and then added the new interface.  The end result is the current, much-improved version.  Many, many thanks to you both!

Many, many thanks also to the many others who have written and provided ideas and encouragement since <itl>TkDiff</itl> was first released!

<hdr>Comments</hdr>

  Questions and comments should be sent to John Klassa at <itl>klassa@ipass.net</itl>.

    }

    do-text-info .help "TkDiff Help" $text
}

######################################################################
#
# text formatting routines derived from Klondike
# Reproduced here with permission from their author.
#
# Copyright (C) 1993,1994 by John Heidemann <johnh@ficus.cs.ucla.edu>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
# 3. The name of John Heidemann may not be used to endorse or promote products
#    derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY JOHN HEIDEMANN ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL JOHN HEIDEMANN BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
######################################################################

proc put-text {tw txt} {
    global tk_version

    if {$tk_version >= 8.0} {
	$tw configure -font {Helvetica 10}
	
	$tw tag configure bld -font {Helvetica 12 bold}
	$tw tag configure cmp -font {Courier 10 bold}
	$tw tag configure hdr -font {Helvetica 14 bold} -underline 1
	$tw tag configure itl -font {Times 10 italic}
	
	$tw tag configure btn \
	    -font {Courier 10} \
	    -foreground black -background white \
	    -relief groove -borderwidth 2
    } else {
	$tw configure -font -*-Helvetica-Medium-R-Normal-*-14-*
	
	$tw tag configure bld -font -*-Helvetica-Bold-R-Normal-*-14-*
	$tw tag configure cmp -font -*-Courier-Medium-R-Normal-*-12-*
	$tw tag configure hdr -font -*-Helvetica-Bold-R-Normal-*-18-* \
	    -underline 1
	$tw tag configure itl -font -*-Times-Medium-I-Normal-*-14-*
	
	$tw tag configure btn \
	    -font -*-Courier-Medium-R-Normal-*-12-* \
	    -foreground black -background white \
	    -relief groove -borderwidth 2
    }
    $tw tag configure rev -foreground white -background black
	
    $tw mark set insert 0.0

    set t $txt

    while {[regexp -indices {<([^@>]*)>} $t match inds] == 1} {

        set start [lindex $inds 0]
        set end [lindex $inds 1]
        set keyword [string range $t $start $end]

        set oldend [$tw index end]

        $tw insert end [string range $t 0 [expr $start - 2]]

        purge-all-tags $tw $oldend insert

        if {[string range $keyword 0 0] == "/"} {
            set keyword [string trimleft $keyword "/"]
            if {[info exists tags($keyword)] == 0} {
                error "end tag $keyword without beginning"
            }
            $tw tag add $keyword $tags($keyword) insert
            unset tags($keyword)
        } else {
            if {[info exists tags($keyword)] == 1} {
                error "nesting of begin tag $keyword"
            }
            set tags($keyword) [$tw index insert]
        }

        set t [string range $t [expr $end + 2] end]
    }

    set oldend [$tw index end]
    $tw insert end $t
    purge-all-tags $tw $oldend insert
}

proc purge-all-tags {w start end} {
    foreach tag [$w tag names $start] {
        $w tag remove $tag $start $end
    }
}

main
