#############################################################
#                TkTeXEditor
#        Distributed under GNU Public License
# Author: Sergey Kalinin (BanZaj) banzaj@lrn.ru
# Copyright (c) "CONERO lab", 2002, http://conero.lrn.ru
#############################################################

#############################################################
#    Converts LaTeX formulas and texts to pixel graphics    #
#                                                           #
# Required software: latex, convert (image magic)           #
# to get color, the latex color package is required         #
#############################################################
#            Idea By Alex Dederer (aka Korwin)              #
#############################################################

## SELECTED TEXT EXTRACT ##
proc GenerateFormula {type} {
    global dir nb activeFile convert_cmd
    set text $nb.f$activeFile.f.text
    set pos [$text index insert]
    set curLine [lindex [split $pos "."] 0]
    set cursor [lindex [split $pos "."] 1]
    set selIndex [$text tag ranges sel]
    if {$selIndex != ""} {
        set posBegin [lindex $selIndex 0]
        set posEnd [lindex $selIndex 1]
        set formula [$text get $posBegin $posEnd]
    } else {
        return
    }
    #set cmdString "$convert_cmd(img) -o [file join $dir(tmp) formula.gif] $formula"
    #catch [exec $convert_cmd(img) -o [file join $dir(tmp) formula.gif] $formula] err
    #if {$err != ""} {puts $err}
    
    Render "$formula" $type ""
    PreviewFormula
}
## PREVIEW CONVERTED IMAGE ##
proc PreviewFormula {} {
    global nb font files color dir render
    set node [$nb raise]
    if {$node == "debug" || $node == ""} {
        return
    }
    set w .formula
    set text "$nb.f$node.f.text"
    set pos [$nb.f[$nb raise].f.text index insert]
    #    set findString ""
    # destroy the find window if it already exists
    if {[winfo exists $w]} {
        destroy $w
    }
    # create the new "find" window
    toplevel $w
    wm transient $w $nb.f$node
    wm overrideredirect $w 1
    set b_x [winfo pointerx .]
    set b_y [expr [winfo pointery .] - 200]
    wm geometry $w +$b_x+$b_y
    
    set f1 [frame $w.frmFind -background $color(bg)]
    pack $f1 -side top -fill x -expand true
    
    image create photo formula -format gif -file [file join $dir(tmp) tle_render.gif]
    
    label $f1.lblFind -background $color(bg) -image formula -relief ridge
    pack $f1.lblFind -side left -padx 0 -pady 0
    bind $w <Escape> "$text mark set insert $pos; $text see $pos; focus -force $text; destroy $w"
    bind $w <Button-1> "$text mark set insert $pos; $text see $pos; focus -force $text; destroy $w"
    focus -force $w
    
    
    unset text pos w
}
## DOCUMENT HEADER READER ##
proc ReadHeader {widget} {
    set posBegin [$widget search -regexp -- {\\documentclass} 0.0 end]
    if {$posBegin != ""} {
        set posEnd [$widget search -regexp -- {\\begin\{document\}} $posBegin end]
        #puts "$posBegin - $posEnd"; return;# debug
        if {$posEnd != ""} {
            set text [$widget get $posBegin $posEnd]
        } else {
            set text ""
        }
    } else {
        set text ""
    }
    return $text
}

## IMAGE GENERATOR WITH MATHEMATICS FORMALS AND TEXTS ##
proc Render {text type fileName} {
    global dir convert_cmd render activeFile files nb
    # Names for input and output files
    set enc "[lindex $files($activeFile) 2]"
    
    puts $files($activeFile) ;# debug
    
    if {$fileName == ""} {
        set name tle_render
        set texFile $name.tex
        set imgFile $name.$render(format)
        set _dir $dir(tmp)
    } else {
        set imgFile [file tail $fileName]
        set name [file rootname $imgFile]
        set texFile $name.tex
        set _dir [file dirname $fileName]
    }
    set txt $nb.f$activeFile.f.text
    set header [ReadHeader $txt]
    if {$header == ""} {
        set header "\\documentclass\[12pt\]\{article\}\n\\usepackage\[$enc\]\{inputenc\}\n\\usepackage\[english,russian\]\{babel\}"

    }
    if {$type == "math"} {
        append header "\\usepackage\{color\}\n\\pagestyle\{empty\}\n\\pagecolor\{$render(bg)\}\n"
        append header "\\begin\{document\}\n\\begin\{eqnarray\*\}\n\{\n\\color\{$render(fg)\}"
        set footer "\}\n\\end\{eqnarray*\}\n\\end\{document\}"
    } elseif {$type == "text"} {
        append header "\\usepackage\{color\}\n\n\\pagestyle\{empty\}\n"
        append header "\\pagecolor\{$render(bg)\}\n\\begin\{document\}\n"
        set footer "\\end\{document\}"
    }
    puts $header
    set f [open [file join $dir(tmp) $texFile] w]
    puts $f $header
    puts $f $text
    puts $f $footer
    close $f
    
    set err ""
    catch [cd $dir(tmp)]
    catch [exec $convert_cmd(dvi) -interaction=batchmode [file join $dir(tmp) $texFile]] err
    catch [exec dvips -o $dir(tmp)/$name.eps -E $dir(tmp)/$name.dvi 2> /dev/null] err
    # Transparent background
    if {$render(trans) == 1} {
        if {$render(aa) == 1} {
            catch [exec $convert_cmd(img) +adjoin -antialias -transparent $render(bg) -density $render(res) $dir(tmp)/$name.eps $_dir/$imgFile] err
        } else {
            catch [exec $convert_cmd(img) +adjoin +antialias -transparent $render(bg) -density $render(res) $dir(tmp)/name.eps $_dir/$imgFile] err
        }
    } else {
        if {$render(aa) == 1} {
            catch [exec $convert_cmd(img) +adjoin -antialias -density $render(res) $dir(tmp)/$name.eps $_dir/$imgFile] err
        } else {
            catch [exec $convert_cmd(img) +adjoin +antialias -density $render(res) $dir(tmp)/$name.eps $_dir/$imgFile] err
        }
    }
    if {$err != ""} {
        set answer [tk_messageBox -message "$err"\
        -type ok -icon warning -title [::msgcat::mc "Warning"]]
        case $answer {
            ok {return}
        }        
        puts $err
    }
    catch [cd $dir(current)]
}



