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


proc Latex2Html {} {
    global tree module cmdString
    set selFiles [$tree selection get]
    if {[llength $selFiles] == 0} {
        set answer [tk_messageBox\
        -message "[::msgcat::mc "Don't selected file"]"\
        -type ok -icon warning\
        -title [::msgcat::mc "Warning"]]
        case $answer {
            ok {return 0}
        }
    }
    if {[llength $selFiles] == 1} {
        if {$selFiles != ""} {
            set file [$tree itemcget $selFiles -data]
        }
        CommandStringDialog $file
    }
    #puts $command
}
proc ConvertDialog {action} {
    global nb files font color cmdString module tcl_platform module convert_cmd activeFile act
    set act $action
    if [info exists activeFile] {
        set nod $activeFile
    } else {
        return
    }
    if {[info exists files($nod)] == 0} {
        return
    }
    set file [lindex $files($nod) 0]    
    
    set w .cmd
    # destroy the find window if it already exists
    if {[winfo exists $w]} {
        destroy $w
    }
    
    toplevel $w
    wm title $w [::msgcat::mc "Command options"]
    wm resizable $w 0 0
    wm transient $w .
    frame $w.frmCombo -borderwidth 1 -background $color(bg)
    frame $w.frmBtn -borderwidth 1 -background $color(bg)
    pack $w.frmCombo $w.frmBtn -side top -fill x
    
    #    set combo [entry $w.frmCombo.entFind]
    label $w.frmCombo.lblModule -text "[::msgcat::mc "Convert to"] \"$action\"" -background $color(bg)
    label $w.frmCombo.lblFile -text "[::msgcat::mc "File"] \"$file\"" -background $color(bg)
    set combo [entry $w.frmCombo.txtString]
    
    pack $w.frmCombo.lblModule $w.frmCombo.lblFile $combo -fill x -padx 2 -pady 2 -side top
    
    button $w.frmBtn.btnFind -text [::msgcat::mc "Run"]\
    -font $font(normal) -width 12 -relief groove -background $color(bg)\
    -command {
        set convert_cmd($act) [.cmd.frmCombo.txtString get]
        Convert $act
        destroy .cmd
    }
    button $w.frmBtn.btnCancel -text [::msgcat::mc "Close"]\
    -relief groove -width 12 -font $font(normal) -background $color(bg)\
    -command "destroy $w"
    pack $w.frmBtn.btnFind $w.frmBtn.btnCancel -fill x -padx 2 -pady 2 -side left
    
    bind $w <Return> {
        set convert_cmd($act) [.cmd.frmCombo.txtString get]
        Convert $act
        destroy .cmd
    }
    bind $w <Escape> "destroy $w"
    $combo insert end "$convert_cmd($action)"
    focus -force $combo
    
}

proc Convert {action} {
    global dir nb files font activeFile tcl_platform module convert_cmd makeThread tree
    set curDir [pwd]
    #set node [$nb raise]
    if [info exists activeFile] {
        set nod $activeFile
        while {[set parentNode [$tree parent $nod]] != "root"} {
            set nod $parentNode
        }        
    } else {
        return
    }
    if {[info exists files($nod)] == 0} {
        return
    }
    if {$module(convert_$action) == ""} {
        set answer [tk_messageBox\
        -message "[::msgcat::mc "Don't find programm"] $convert_cmd($action)"\
        -type ok -icon warning\
        -title [::msgcat::mc "Warning"]]
        case $answer {
            ok {return 0}
        }
    }
    
    set text "$nb.f$nod.f.text"
    set fullPath [lindex $files($nod) 0]    
    set folder [file dirname $fullPath]
    set file [file tail $fullPath]
    set ext [string trim [file extension $file] {.}]
    set name [file rootname $file]
    
    ##
    set node "debug"
    if {[$nb index $node] != -1} {
        $nb delete debug
    }
    set w [$nb insert end $node -text [::msgcat::mc "Running project"]]
    # create array with file names #
    set w [frame $w.f]
    pack $w -side top -fill both -expand true
    
    frame $w.frame -borderwidth 2 -relief ridge
    pack $w.frame -side top -fill both -expand true
    
    
    text $w.frame.text -yscrollcommand "$w.frame.yscroll set" \
    -relief sunken -wrap word -highlightthickness 0 -font $font(normal)\
    -selectborderwidth 0 -selectbackground #55c4d1 -width 10 -height 10
    scrollbar $w.frame.yscroll -relief sunken -borderwidth {1} -width {10} -takefocus 0 \
    -command "$w.frame.text yview"
    
    pack $w.frame.text -side left -fill both -expand true
    pack $w.frame.yscroll -side left -fill y
    
    ## READLINE WIDGET ##
    frame $w.frmReadline -borderwidth 2 -relief ridge -height 5
    pack $w.frmReadline -side top -fill x
    text $w.frmReadline.text2 -yscrollcommand "$w.frmReadline.yscroll2 set" \
    -relief sunken -wrap word -highlightthickness 0 -font $font(normal)\
    -selectborderwidth 0 -selectbackground #55c4d1 -width 10 -height 5
    scrollbar $w.frmReadline.yscroll2 -relief sunken -borderwidth {1} -width {10} -takefocus 0 \
    -command "$w.frmReadline.text2 yview"
    pack $w.frmReadline.text2 -side left -fill both -expand true
    pack $w.frmReadline.yscroll2 -side left -fill y
    
    bind $w.frmReadline.text2 <Return> ReadLine
    
    balloon $w.frmReadline.text2 set [::msgcat::mc "Enter LaTeX command here and push Enter"]
    
    pane::create $w.frame $w.frmReadline -orient horizontal -percent 0.9
    
    
    # key bindings #
    
    $nb raise $node
    #insert debug data into text widget #
    set pos [$w.frame.text index insert]
    set lineNum [lindex [split $pos "."] 0]
    $w.frame.text insert end "[::msgcat::mc "Work with file"] $fullPath\n"
    
    if {[catch {cd $folder}] != 0} {return ""}
    FileDialog save
    set cmdString $convert_cmd($action)
    if [regexp -nocase "%dirName" $convert_cmd($action) v] {
        regsub -all -- {%dirName} $cmdString $folder cmdString
        puts "$cmdString"
    }
    if [regexp -nocase "%fileName" $convert_cmd($action) v] {
        regsub -all -- {%fileName} $cmdString $name cmdString
        puts "$cmdString"
    } else {
        set cmdString "$convert_cmd($action) $fullPath"
    }
    puts "$cmdString"
    $w.frame.text insert end "[::msgcat::mc "Make"] $action [::msgcat::mc "file"]\n"
    $w.frame.text insert end "$cmdString\n\n"
    
    set pipe [open "|$cmdString" "w+"]
    set makeThread $pipe
    
    $w.frame.text insert end "----------------- [::msgcat::mc "Programm output"] -----------------\n"
    $w.frame.text tag add bold $lineNum.0 $lineNum.end
    
    focus -force $w.frmReadline.text2
    
    fileevent $pipe readable [list DebugInfo $w.frame.text $pipe $folder]
    fconfigure $pipe -buffering none -blocking no
    catch {cd $curDir}
}

proc ReadLine {} {
    global makeThread
    set pos [.frmBody.frmEditor.noteBook.fdebug.f.frmReadline.text2 index insert]
    set lineNumber [lindex [split $pos "."] 0]
    set cmd  [.frmBody.frmEditor.noteBook.fdebug.f.frmReadline.text2 get $lineNumber.0 $lineNumber.end]
    puts $cmd
    fileevent $makeThread writable
    if [info exists makeThread] {
        puts $makeThread "$cmd"
    }
    
}

proc ConvertImage {file} {
    global dir convert_cmd render activeFile files nb thumb
    set file [string trimleft [string trimright $file "\}"] "\{"]
    set inFormat [GetExtention $file]
    set name [file rootname  [file tail $file]]
    set imgFile "$name.$thumb(format)"
    puts "$file\t$imgFile"
    set _dir [file join [file dirname $file] .thumb]
    
    if {[file exists $_dir] == 0} { file mkdir $_dir }
    if [file exists [file join $_dir $imgFile]] {
        puts "File exists [file join $_dir $imgFile]"
        return "[file join $_dir $imgFile]"
    } else {
        puts "$convert_cmd(img) +adjoin +antialias -quality 10 -transparent $render(bg) -density $render(res) $file $_dir/$imgFile"
    }
    
    #set file [file tail $file]
    if {$render(trans) == 1} {
        if {$render(aa) == 1} {
            catch [exec $convert_cmd(img) +adjoin -antialias -quality 10 -transparent $render(bg) -scale $thumb(resolution) $file [file join $_dir $imgFile]] err
        } else {
            catch [exec $convert_cmd(img) +adjoin +antialias -quality 10 -transparent $render(bg) -scale $thumb(resolution) $file [file join $_dir $imgFile]] err
        }
    } else {
        if {$render(aa) == 1} {
            catch [exec $convert_cmd(img) +adjoin -antialias -quality 10 -scale $thumb(resolution) $file [file join $_dir $imgFile]] err
        } else {
            catch [exec $convert_cmd(img) +adjoin +antialias -quality 10 -scale $thumb(resolution) $file [file join $_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
    }
    return "[file join $_dir $imgFile]"
}


