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

###########################################################
#                ENCODING files procedure                  #
###########################################################

proc GetCorrectEncode {latexEncode} {
    global files dir activeFile files
    set f [open "[file join $dir(work) encode.lst]" r]
    set encodeList [encoding names]
    while {[gets $f line]} {
        if {[string index [string trim $line] 0] == "#"} {
            continue
        }
        scan $line "%s%s" texEnc tclEnc
        #puts "$texEnc $tclEnc"
        
        if {$texEnc == $latexEncode} {
            close $f
            return $tclEnc
        } else {
            set ind [lsearch -exact $encodeList $latexEncode]
            #puts $latexEncode
            if {$ind == -1} {
                set answer [tk_messageBox\
                -message "[lindex $files($activeFile) 0] [::msgcat::mc "Don't find any system encoding for"] $latexEncode \
                [::msgcat::mc "You must write correctly encode name in"] [file join $dir(work) encode.lst] [::msgcat::mc "file"]"\
                -type ok -icon warning\
                -title [::msgcat::mc "Warning"]]
                case $answer {
                    ok {return}
                }
                close $f
                return $latexEncode
            } else {
                close $f
                return $latexEncode
            }
        }
    }
}

proc EncodeDialog {type} {
    global color files activeFile
    set w .encode
    # destroy the find window if it already exists
    if {[winfo exists .encode]} {
        destroy .encode
    }
    
    toplevel .encode
    wm title .encode [::msgcat::mc "Encoding"]
    wm resizable .encode 0 0
    wm transient .encode .
    
    frame .encode.encodings -width 10
    eval {
        listbox .encode.encodings.list -height 10 -width 20 -selectbackground $color(selectbg)\
        -selectborderwidth 0 -yscrollcommand {.encode.encodings.yscroll set}
    }
    eval {scrollbar .encode.encodings.yscroll -orient vertical -command {.encode.encodings.list yview}}
    pack .encode.encodings.list    -side left -expand true   -fill y
    pack .encode.encodings.yscroll -side left -expand false  -fill y
    pack .encode.encodings         -side top  -expand true   -fill both
    
    canvas .encode.line -border 0 -height 1 -background black -width 10
    pack   .encode.line -side top -expand true -fill x
    
    frame .encode.command -width 10
    if {$type == "file"} {
        eval {
            button .encode.command.ok -text [::msgcat::mc "Ok"] -command {
                SetEncode [.encode.encodings.list get [.encode.encodings.list curselection]]    
            }
        }
    } else {
        eval {
            button .encode.command.ok -text [::msgcat::mc "Ok"] -command {
                TextRecode [.encode.encodings.list get [.encode.encodings.list curselection]]
            }
        }
    }
    eval {button .encode.command.cancel  -text [::msgcat::mc "Cancel"] -command {destroy .encode }}
    grid .encode.command.ok -row 0 -column 0 -sticky e -pady 2 -padx 2
    grid .encode.command.cancel -row 0 -column 1 -sticky w -pady 2 -padx 2
    pack .encode.command -side top -expand true -fill x
    
    bind .encode.encodings.list <Double-1> {eval [.encode.command.ok    cget -command]}
    bind .encode.encodings.list <Return>   {eval [.encode.command.ok    cget -command]}
    bind .encode <Escape> {eval [.encode.command.cancel cget -command]}
    
    set i 0 ; set cur_encoding [encoding system]
    foreach { name_encodings } [lsort [encoding names] ] {
        .encode.encodings.list insert end $name_encodings
        if { $name_encodings == $cur_encoding } { set enc_pos $i }
        incr i
    } ;# foreach encoding names
    
    wm resizable .encode 0 0
    .encode.encodings.list activate $enc_pos
    .encode.encodings.list selection set $enc_pos $enc_pos
    .encode.encodings.list see $enc_pos
    focus -force .encode.encodings.list
}


## Source encode ##
proc DocRecode {pipe} {
    global files tree activeFile
    set parentNode [$tree parent $activeFile]
    if [info exists files($parentNode)] {
        set sourceEnc [lindex $files($parentNode) 2]
    } else {
        set sourceEnc [encoding system] ;#[EncodeDialog]
    }
    puts $sourceEnc
    while {[gets $pipe line]>=0} {
        if [regexp -nocase -all -- {(\\)(usepackage)(\[)(.*?)(\])(\{)inputenc(\})} $line match v1 v2 v3 sourceEnc v5 v6 v7] {
            if [set ind [string last "," $sourceEnc]] {
                set sourceEnc [string range $sourceEnc [expr $ind + 1] end]
            }
            puts "Кодировка документа $sourceEnc"
            set sourceEnc [GetCorrectEncode $sourceEnc]
            puts "Кодировка системы $sourceEnc"
            
        }
    }
    fconfigure $pipe -encoding binary
    seek $pipe 0 start
    return $sourceEnc
}

## CHANGE SOURCE FIELE ENCODING ##
proc SetEncode {encode} {
    global files activeFile status nb
    destroy .encode
    set files($activeFile) [list [lindex $files($activeFile) 0] [lindex $files($activeFile) 1] "$encode"]
    #puts $files($activeFile)
    $status(encode) configure -text "[lindex $files($activeFile) 2]"
}

## Reencoding text ##
proc TextRecode {encode} {
    global files activeFile status nb
    destroy .encode
    set text $nb.f$activeFile.f.text
    set contents [$text get 0.0 end]
    #puts "[lindex $files($activeFile) 2] $encode"
    set contents [encoding convertto [lindex $files($activeFile) 2] $contents]
    set contents [encoding convertfrom $encode $contents]
    $text delete 0.0 end
    $text insert end $contents
    unset text
    SetEncode $encode
}

proc CheckEncoding {text} {
    global files activeFile
    set sourceEnc "" ;#[EncodeDialog]
    set line [$text get 0.0 end]
    if [regexp -nocase -all -- {(\\)(usepackage)(\[)(.*?)(\])(\{)inputenc(\})} $line match v1 v2 v3 sourceEnc v5 v6 v7] {
        #break
        if {$sourceEnc != "[lindex $files($activeFile) 2]"} {
            set answer [tk_messageBox -message "[::msgcat::mc "Don't correctly setting document encoding! Save anyway?"]"\
            -type yesno -icon warning\
            -title [::msgcat::mc "Warning"]]
            case $answer {
                yes {return 1}
                no  {return 0}
            }
        }
        puts "DocEnc-$sourceEnc ViewEnc-[lindex $files($activeFile) 2]"
    }
}


## clipboard encode ##

set xselection ""
proc EncodeTextSelection {txt offset len} {
    set ::xselection [eval $txt get [$txt tag ranges sel]]
    encoding convertto \
    [crange $::xselection $offset [expr $offset + $len - 1]]
}

proc EncodeEntrySelection {txt offset len} {
    if [$txt selection present] {
        set idx1 [$txt index sel.first]        
        set idx2 [$txt index sel.last]
        set ::xselection [string range [$txt get] $idx1 $idx2]
        encoding convertto \
        [crange $::xselection $offset [expr $offset + $len - 1]]
    } else {
        set ::xselection ""
    }
}

if {$tcl_platform(platform) == "win"} {
    bind Text  <Map> { selection handle %W "EncodeTextSelection %W"}
    bind Entry <Map> { selection handle %W "EncodeEntrySelection %W"}
    bind Text  <Unmap> { selection handle %W {}}
    bind Entry <Unmap> { selection handle %W {}}
    
    bind Text <ButtonRelease-2> {
        if [catch {set sel [selection get]}] continue
        if {[selection own] == ""} {
            set sel [encoding convertfrom $sel]
        } else {
            set sel $xselection
        }
        %W insert current $sel
    }
    bind Entry <ButtonRelease-2> {
        if [catch {set sel [selection get]}] continue
        if {[selection own] == ""} {
            set sel [encoding convertfrom $sel]
        } else {
            set sel $xselection
        }
        %W insert insert $sel
    }        
}
#set class Text
#bind $class <Map> "selection handle %W \"unix::Encode${class}Selection %W\""
#bind $class <Unmap> { selection handle %W {}}
#proc EncodeTextSelection {txt offset len} {encoding convertto [eval $txt get [$txt tag ranges sel]]}







