

#
# ChangeLayers
#

proc SetSelection { { what selected } } {
    global LayersSelection wChangeLay
    set LayersSelection ""
    set n [$wChangeLay.middle.tbl size]
    if { $n == 1 } { 
	$wChangeLay.middle.tbl selection set 0 
    }
    for { set i 0 } { $i < $n } { incr i } {
	if { [$wChangeLay.middle.tbl selection includes $i] || $what == "all" } {
	    lappend LayersSelection [lindex [$wChangeLay.middle.tbl get $i] 1]
	}
    }
}

proc SetLayerAsSelection { layer } {
    global wChangeLay

    if { ![info exists wChangeLay] || ![winfo exists $wChangeLay.middle.tbl] } { return }
    $wChangeLay.middle.tbl selection clear 0 end

    for { set i 0 } { $i < [$wChangeLay.middle.tbl size] } { incr i } {
	if { [lindex [$wChangeLay.middle.tbl get $i] 1] == $layer } {
	    $wChangeLay.middle.tbl selection set $i
	    break
	}
    }
    SetSelection
}

proc SelectLayersByRegexp {} {
    global wChangeLay LayerSelRegexp LayerSelAdd LayerSelCase

    catch { destroy $wChangeLay.sel}
    frame $wChangeLay.sel -relief ridge -bd 4
    frame $wChangeLay.sel.up
    entry $wChangeLay.sel.up.e -relief sunken
    focus $wChangeLay.sel.up.e
    button $wChangeLay.sel.up.ok -text [_ "OK"] -command {
	if { $LayerSelAdd == "substitute" } {
	    $wChangeLay.middle.tbl sel clear 0 end
	}
	set idx 0
	foreach i [$wChangeLay.middle.tbl get 0 end] {
	    set i [lindex $i 1]
	    set change ""
	    if { $LayerSelRegexp != "regex" } {
		if { $LayerSelCase != "case" } {
		    if { [string match [string tolower [$wChangeLay.sel.up.e get]] \
		            [string tolower $i]] } { set change yes }
		} else {
		    if { [string match [$wChangeLay.sel.up.e get] $i] } {
		        set change yes
		    }
		}
	    } else {
		if { $LayerSelCase != "case" } {
		    if { [regexp -nocase -- [$wChangeLay.sel.up.e get] $i res] } {
		        if { $i == $res } { set change yes }
		    }
		} else {
		    if { [regexp -- [$wChangeLay.sel.up.e get] $i res] } {
		        if { $i == $res } { set change yes }
		    }
		}
	    }
	    if { $change == "yes" } {
		if { $LayerSelAdd != "substract" } {
		    $wChangeLay.middle.tbl sel set $idx
		} else {
		    $wChangeLay.middle.tbl sel clear $idx
		}
	    }
	    incr idx
	}        
	SetSelection
	destroy $wChangeLay.sel
	focus $wChangeLay.ent.e
    } -padx 5
    pack $wChangeLay.sel.up.e $wChangeLay.sel.up.ok -side left
    
    frame $wChangeLay.sel.down
    checkbutton $wChangeLay.sel.down.reg -text [_ "Regexp"] -onvalue regex \
	    -variable LayerSelRegexp
    checkbutton $wChangeLay.sel.down.case -text [_ "Case"] -onvalue case \
	    -variable LayerSelCase

    frame $wChangeLay.sel.rad
    radiobutton $wChangeLay.sel.rad.substitute -text [_ "Substitute"] -value substitute \
	    -variable LayerSelAdd
    radiobutton $wChangeLay.sel.rad.add -text [_ "Add"] -value add \
	    -variable LayerSelAdd
    radiobutton $wChangeLay.sel.rad.substract -text [_ "Substract"] -value substract \
	    -variable LayerSelAdd

    set LayerSelRegexp ""
    set LayerSelAdd substitute
    set LayerSelCase ""
    pack $wChangeLay.sel.down.reg $wChangeLay.sel.down.case \
	    -side left -ipadx 3
    pack $wChangeLay.sel.rad.substitute $wChangeLay.sel.rad.add \
	    $wChangeLay.sel.rad.substract -side left
    pack $wChangeLay.sel.up $wChangeLay.sel.down $wChangeLay.sel.rad -side top

    place $wChangeLay.sel -x 0 -rely 0.6

    bind $wChangeLay.sel.up.e <Return> { $wChangeLay.sel.up.ok invoke }

}

proc SendAndFill { layerList col } {
    global LayersNoRedraw
    if { $LayersNoRedraw != 2 } { .central.s process layer }
    foreach i $layerList {
	GiD_Process color $i $col
    }
    FillInfoLayers
    if { $LayersNoRedraw == 0 } { .central.s process escape }
    if { $LayersNoRedraw == 1 } { set LayersNoRedraw 2 }
}

proc FillInfoLayers { { new_layer ""} } {
    global wChangeLay LayerNames LayersSelection GidPriv
    
    if { ![info exists wChangeLay] || ![winfo exists $wChangeLay] } { return }
    
    set tbl $wChangeLay.middle.tbl
    set hsb $wChangeLay.middle.hsb1
    set vsb $wChangeLay.middle.vsb1
    
    set LayersSelection ""
    set LayerNames [.central.s info layers]
    set BackLayerNames [.central.s info back_layers]
    
    if { "$BackLayerNames" != "" } {
	regsub -all {_\*back\*} $BackLayerNames {} pp
	set BackLayerNames $pp
    }
    
    if { "$new_layer" == "" } {
	set sellayers ""
	foreach i [$tbl curselection] {
	    lappend sellayers [lindex [$tbl get $i] 1]
	}
    } else {
	set sellayers $new_layer
    }
    
    
    $tbl delete 0 end
    
    set LayerToUse [lindex [.central.s info Project] 3]
    $wChangeLay.touse.l conf -text $LayerToUse
    
    if { [info exists GidPriv(LayersAlphabetic)] && $GidPriv(LayersAlphabetic) } {
	set LayerNames [lsort -dictionary $LayerNames]
    }
    foreach i $LayerNames {
	set LayersProp [lindex [.central.s info layers $i] 0]
	$tbl insert end [list "" $i "" "" ""]
	
	set cur_col [ format "#%02x%02x%02x" [lindex $LayersProp 2] \
		[lindex $LayersProp 3] [lindex $LayersProp 4]]
	
	$tbl cellconfigure end,0 -background $cur_col -text "" -selectbackground $cur_col
        if { $i == $LayerToUse } {
	    $tbl cellconfigure end,1 -image [GetImage layer_touse.gif]
	} else {
	    $tbl cellconfigure end,1 -image [GetImage layer_nottouse.gif] ;#void image
	}

	if { [lindex $LayersProp 0] } {
	    $tbl cellconfigure end,2 -image [GetImage layer_on.gif]
	} else {
	    $tbl cellconfigure end,2 -image [GetImage layer_off.gif]
	}
	
	if { [lindex $LayersProp 1] } {
	    $tbl cellconfigure end,3 -image [GetImage layer_freeze.gif]
	} else {
	    $tbl cellconfigure end,3 -image [GetImage layer_unfreeze.gif]
	}
	
	if { [ lsearch $BackLayerNames $i] != -1 } {
	    $tbl cellconfigure end,4 -image [GetImage layer_bringtofront.gif]
	} else {
	    $tbl cellconfigure end,4 -image [GetImage layer_sendtoback.gif] ;#void image
	}
	
	if { [lsearch -exact $sellayers $i] != -1 } {
	    $tbl selection set end
	}
    }
    
    #$tbl yview [$tbl nearest 0]
    #ConfigureListScrollbars $tbl $hsb $vsb
}

set LayersSelection ""

proc SetLayersToDelete { } {
    global LayersSelection wChangeLay LayersNoRedraw 
    SetSelection
    if { $LayersSelection == "" } {
	tk_dialogRAM  $wChangeLay.modal [_ "error"] \
		[_ "before applying operation delete it is necessary to select layers"] \
		error 0 [_ "OK"]
	return
    }

    if { $LayersNoRedraw != 2 } { .central.s process layer }
    set warnmessage 1
    foreach i $LayersSelection {
	GiD_Process delete $i
	
	if { $warnmessage && [catch { .central.s info layers $i } ] == 0 } {
	    set ret [tk_dialogRAM  $wChangeLay.modal [_ "error"] \
		         [_ "Layer '%s' can't be erased.\n(see the message bar for details)" $i] \
		         error 0 [_ "OK"] [_ "OK to all"]]
	    if { $ret == 1 } { set warnmessage 0 }
	}
    }
    
    if { $LayersNoRedraw == 0 } { .central.s process escape }
    if { $LayersNoRedraw == 1 } { set LayersNoRedraw 2 }
    FillInfoLayers

}

proc SetLayersToColor { } {
    global LayersSelection wChangeLay LayersNoRedraw 
    SetSelection
    if { $LayersSelection == "" } {
	tk_dialogRAM  $wChangeLay.modal [_ "error"] \
	[_ "before applying operation color it is necessary to select layers"] \
	error 0 [_ "OK"]
	return
    }

    if { $LayersNoRedraw != 2 } { .central.s process layer }

    set LayersProp [lindex [.central.s info layers [lindex $LayersSelection 0]] 0]
    set cur_col [ format "#%02x%02x%02x" [lindex $LayersProp 2] \
	    [lindex $LayersProp 3] [lindex $LayersProp 4]]

    #set retcol [tk_chooseColor -parent $wChangeLay -title [_ "Select color"] -initialcolor $cur_col]
    set retcol [BWChooseColor  $wChangeLay.selectcolor -title [_ "Select color"] -color $cur_col]

    if { $retcol != "" } {
	scan [string range $retcol 1 end] %2x%2x%2x col1 col2 col3
	set col [format %03i%03i%03i $col1 $col2 $col3]
	foreach i $LayersSelection {
	    GiD_Process color $i $col
	}

	#    RamColor .ramcolor "SendAndFill [list $LayersSelection]"
    }
    if { $LayersNoRedraw == 0 } { .central.s process escape }
    if { $LayersNoRedraw == 1 } { set LayersNoRedraw 2 }
    FillInfoLayers

}


proc SetLayersTo { type {newname ""} } {
    global LayersSelection wChangeLay LayersNoRedraw 
    
    SetSelection
    if { $LayersSelection == "" } {
	tk_dialogRAM  $wChangeLay.modal [_ "error"] \
		[_ "before applying operation %s it is necessary to select layers" $type] \
		error 0 [_ "OK"]
	return
    }

    set VarToSend GiD_Process
    if { $LayersNoRedraw != 2 } { lappend VarToSend layer }
    foreach i $LayersSelection {
	switch $type {
	    ON {
		lappend VarToSend on $i
	    }
	    OFF {
		lappend VarToSend off $i
	    }
	    FREEZE {
		lappend VarToSend freeze $i
	    }
	    UNFREEZE {
		lappend VarToSend unfreeze $i
	    }
	    TOUSE {
		lappend VarToSend Touse $i
	    }
	    RENAME {
		lappend VarToSend changename $i $newname
	    }
	    BRINGTOFRONT {
		lappend VarToSend bringtofront $i
	    }
	}
    }    
    if { $LayersNoRedraw == 0 } { lappend VarToSend escape }
    
    eval $VarToSend
    if { $LayersNoRedraw == 1 } { set LayersNoRedraw 2 }
    FillInfoLayers
}

proc SendLayerEntitiesAA { what } {
    global LayersSelection wChangeLay GidPriv

    if { [llength $LayersSelection] !=1 } {
	tk_dialogRAM  $wChangeLay.modal [_ "error"] \
       [_ "before applying 'Entities' it is necessary to select 1 layer"] error \
		0 [_ "OK"]
	return
    }
    set layer [lindex $LayersSelection 0]

    if { $GidPriv(LayersAlsoLower) == 0 } {
	GiD_Process layer entities $layer $what
    } else {
	GiD_Process layer entities $layer LowerEntities $what
    }

    set SmallWinSelecting [.central.s info variable SmallWinSelecting]
    FinishButton $wChangeLay $wChangeLay.buts \
	    [_ "Press 'Finish' to end selection"] \
	    "" disableall $SmallWinSelecting
}


proc SendLayerEntities {} {                 
    global wChangeLay
    SetSelection

    AddEntitiesToMenuAfter 0 $wChangeLay.buts.act.m "SendLayerEntitiesAA " \
	    [list [_ "Points"] [_ "Lines"] [_ "Surfaces"] [_ "Volumes"] [_ "Dimensions"] [_ "All"]] \
	    {Points Lines Surfaces Volumes Dimensions All} \
	    [list [_ "Nodes"] [_ "Elements"] [_ "Dimensions"] [_ "All"]] \
	    {Nodes Elements Dimensions All}

}

proc EndLayerToUseEntitiesAA { what } {
    global GidPriv

    foreach i [trace vinfo GidPriv(selection)] {
	trace vdelete GidPriv(selection) [lindex $i 0] [lindex $i 1] 
    }

    set num [lindex [lindex $GidPriv(selection) 0] 1]
    set nnum ""
    regexp {[0-9]*} $num nnum
    if { $nnum != "" } {
	set retval [.central.s info list_entities $what $nnum]
	set layername ""
	regexp {LAYER:([^\n\r]+)} $retval {} layername
	set layername [string trim $layername]
	if { $layername != "" } {
	    GiD_Process Layer ToUse $layername

	    FillInfoLayers

	    global wChangeLay
	    $wChangeLay.middle.tbl selection clear 0 end
	    for { set i 0 } { $i < [$wChangeLay.middle.tbl size] } { incr i } {
		if { [lindex [$wChangeLay.middle.tbl get $i] 1] == $layername } {
		    $wChangeLay.middle.tbl selection set $i
		    $wChangeLay.middle.tbl see $i
		    break
		}
	    }
	} else {
	    WarnWin [_ "Selected entity does not belong to one layer"]
	}
    }
}

proc LayerToUseEntitiesAA { what } {
    global GidPriv
    
    if { [trace vinfo GidPriv(selection)] != "" } {
	foreach i [trace vinfo GidPriv(selection)] {
	    trace vdelete GidPriv(selection) [lindex $i 0] [lindex $i 1] 
	}
	.central.s process escape
    }

    .central.s process SelectEntities JustOne $what
    trace var GidPriv(selection) w "EndLayerToUseEntitiesAA $what ;#"
}

proc LayerToUseEntities { menu } {
    AddEntitiesToMenu $menu "LayerToUseEntitiesAA " \
	    [list [_ "Point"] [_ "Line"] [_ "Surface"] [_ "Volume"] ] {Points Lines Surfaces Volumes} \
	    [list [_ "Node"] [_ "Element"] ] {Nodes Elements}
}

proc SendLayerEntitiesToBackAA { what } {
    global wChangeLay GidPriv

    if { $GidPriv(LayersBackOpposite) } {
	if { $GidPriv(LayersAlsoLower) == 0 } {
	    .central.s process layer SendToBackOpposite $what
	} else {
	    .central.s process layer SendToBackOpposite LowerEntities $what
	}
    } else {
	if { $GidPriv(LayersAlsoLower) == 0 } {
	    .central.s process layer SendToBack $what
	} else {
	    .central.s process layer SendToBack LowerEntities $what
	}
    }
    set SmallWinSelecting [.central.s info variable SmallWinSelecting]
    FinishButton $wChangeLay $wChangeLay.dr.bdel \
	    [_ "Press 'Finish' to end selection"] \
	    "FillInfoLayers" disableall $SmallWinSelecting
    
}


proc SendLayerEntitiesToBack {} {                 
    global  wChangeLay
    SetSelection

    AddEntitiesToMenuAfter 1 $wChangeLay.buts.back.m "SendLayerEntitiesToBackAA " \
	    [list [_ "Points"] [_ "Lines"] [_ "Surfaces"] [_ "Volumes"] [_ "All"]] \
	    {Points Lines Surfaces Volumes All} \
	    [list [_ "Nodes"] [_ "Elements"] [_ "All"]] \
	    {Nodes Elements All}

    $wChangeLay.buts.back.m add separator
    if { [.central.s info layers -hasbacklayers] } {
	$wChangeLay.buts.back.m add command -label [_ "Bring to front"] -command \
		"SetLayersTo BRINGTOFRONT"
	$wChangeLay.buts.back.m add command -label [_ "Bring all to front"] -command \
		".central.s process Layer BringToFrontAll escape ; FillInfoLayers"
    } else {
	$wChangeLay.buts.back.m add command -label [_ "Bring to front"] -state disabled
	$wChangeLay.buts.back.m add command -label [_ "Bring all to front"] -state disabled
    }

}

proc EnterNewLayer { w } {
    global LayerNames

    set name [string trim [$w.ent.e get]]
    regsub -all {[ ]+} $name {_} name
   
    if { $name == "" } {
	for {set i 0} {$i<10000} {incr i} {
	  set name Layer$i
	    set ipos [lsearch -exact $LayerNames $name]
	    if { $ipos == -1 } { break } 
	}
    } 

    if { $name == "" } {
	tk_dialogRAM  $w.modal [_ "error"] \
		[_ "A layer name must be written before selecting 'New'"] error 0 [_ "OK"]
	return
    }

    set ipos [lsearch -exact [string tolower $LayerNames] [string tolower $name]]
    if { $ipos != -1 } {
	tk_dialogRAM  $w.modal [_ "error"] \
		[_ "Layer %s already exists" [lindex $LayerNames $ipos]] error 0 [_ "OK"]
	return
    }

    .central.s process layer new $name escape 
    FillInfoLayers "$name"
    $w.ent.e delete 0 end
}

proc ConfigureListScrollbars { listbox sx sy } {
    foreach i "x y" {
	if { ![info exists s${i}] || ![winfo exists [set s${i}]] } { continue }
	foreach "${i}1 ${i}2" [$listbox ${i}view] break
	if { [set ${i}1] == 0 && [set ${i}2] == 1 } {
	    after idle grid remove [set s${i}]
	} else {
	    after idle grid [set s${i}]
	}
    }
}   

proc DoubleClickTableList { x y W tbl} { 
    set tablelist::x [expr {$x + [winfo x $W]}]
    set tablelist::y [expr {$y + [winfo y $W]}]
    set cell [$tbl nearestcell $tablelist::x $tablelist::y]
    #tk_messageBox -message "Selection: [$tbl curselection]. Clicked on cell $cell"
    foreach {row col} [ split $cell ,] break
    $tbl selection set $row
    if { $col == 0 } {
	SetLayersToColor
    } elseif { $col == 1 } {
	SetLayersTo TOUSE
    } elseif { $col == 2 } {
	if { [lindex [$tbl cellconfigure $row,$col -image] 4] == [GetImage layer_off.gif] } {
	    SetLayersTo ON
	    #$tbl cellconfigure $row,$col -image [GetImage layer_on.gif]
	} else {
	    SetLayersTo OFF
	    #$tbl cellconfigure $row,$col -image [GetImage layer_off.gif]
	}
    } elseif { $col == 3 } {
	if { [lindex [$tbl cellconfigure $row,$col -image] 4] == [GetImage layer_freeze.gif] } {
	    SetLayersTo UNFREEZE
	    #$tbl cellconfigure $row,$col -image [GetImage layer_unfreeze.gif]
	} else {
	    SetLayersTo FREEZE
	    #$tbl cellconfigure $row,$col -image [GetImage layer_freeze.gif]
	}
    } elseif { $col == 4 } {
	if { [lindex [$tbl cellconfigure $row,$col -image] 4] == [GetImage layer_bringtofront.gif] } {
	   SetLayersTo BRINGTOFRONT
	    #$tbl cellconfigure $row,$col -image layer_bringtofront.gif
	} else {
	    #$tbl cellconfigure $row,$col -image layer_sendtoback.gif
	}
    }
    
}

proc LayersCreateListWin { w} {
    global GidPriv

    set vsb $w.vsb1
    set hsb $w.hsb1
    set tbl [tablelist::tablelist $w.tbl \
            -exportselection 0 \
            -columns [list \
                0 "" left \
                5 "Name" left \
                0 "" left \
                0 "" left \
		0 "" left \
                ] \
            -selectbackground black -selectforeground white \
            -background $GidPriv(Color,BackgroundListbox) \
            -stretch 1 \
            -selectmode extended \
            -highlightthickness 0 \
            -labelborderwidth 1 \
	    -labelcommand tablelist::sortByColumn \
            -labelpady 0 \
            -showarrow 0 \
            -showseparators 0 \
            -xscrollcommand [list $hsb set] \
            -yscrollcommand [list $vsb set] \
            -resizablecolumns 0]
            #-labelcommand tablelist::sortByColumn -showarrow 1

    $tbl columnconfigure 2 -selectbackground $GidPriv(Color,BackgroundListbox) -selectforeground black
    $tbl columnconfigure 3 -selectbackground $GidPriv(Color,BackgroundListbox) -selectforeground black
    $tbl columnconfigure 4 -selectbackground $GidPriv(Color,BackgroundListbox) -selectforeground black

    scrollbar $vsb -orient vertical   -command [list $tbl yview]
    scrollbar $hsb -orient horizontal -command [list $tbl xview]

    bind [$tbl bodypath] <Double-Button-1> "DoubleClickTableList %x %y %W $tbl" 

    grid $tbl $vsb -sticky nsew
    grid configure $vsb -sticky ns
    grid $hsb -sticky ew
    grid remove $vsb $hsb
    bind $tbl <Configure> [list ConfigureListScrollbars $tbl $hsb $vsb]

    grid columnconfigure $w 0 -weight 1
    grid rowconfigure $w 0 -weight 1
}

proc ChangeLayers { { w .gid.wlay } } {
    global wChangeLay LayersNoRedraw GidPriv LayerImage GIDDEFAULT
    set wChangeLay $w
    set LayersNoRedraw 0
    InitWindow $w [_ "Layers"] LayersWindowGeom ChangeLayers

    frame $w.middle -relief ridge -bd 2

    LayersCreateListWin $w.middle
    GidHelp "$w.middle " \
	[_ "Layer properties:\n Color, Name, Visible/Hidden, Frozen/Unfrozen, Exists back entities."]

    pack $w.middle -expand yes -fill both

    frame $w.options -bd 1 -relief sunken
    button $w.options.col -text [_ "Color"]... -command "SetLayersToColor" -bd 1 -padx 5
    set mw [expr [DWGetMaxWidth $w.options.col 6 "Color" "On" "Off" "Sel" "New"]+1]
    $w.options.col configure -width $mw
    GidHelp "$w.options.col " \
	[_ "Changes the color used to draw the entities in render mode."]
    button $w.options.on -text [_ "On"] -command "SetLayersTo ON" -bd 1 -padx 2 -und 0 -width $mw
    GidHelp "$w.options.on " \
	[_ "Entities belonging to a layer ON will be drawn."]
    button $w.options.off -text [_ "Off"] -command "SetLayersTo OFF" -bd 1 -padx 2 -und 1 -width $mw
    GidHelp "$w.options.off " \
	[_ "Entities belonging to a layer OFF will not be drawn."]
    grid $w.options.on -sticky e -row 0 -column 0 -padx 2 -pady 1
    grid $w.options.off -sticky w -row 0 -column 1 -padx 2 -pady 1
    grid $w.options.col -sticky e -row 0 -column 2 -padx 2 -pady 1
    grid rowconfigure $w.options 0 -weight 1
    grid columnconfigure $w.options 0 -weight 1
    grid columnconfigure $w.options 1 -weight 1
    grid columnconfigure $w.options 2 -weight 1

    frame $w.options2 -bd 1 -relief sunken
    #button $w.options2.fr -text [_ "Freeze"] -command "SetLayersTo FREEZE" -bd 1 -padx 5 -und 2
    #button $w.options2.ufr -text [_ "Unfreeze"] -command "SetLayersTo UNFREEZE" -bd 1 -padx 5 -und 0
    if { ![ info exist LayerImage(Freeze)] } {
	set LayerImage(Freeze) [ image create photo -file [ file join $GIDDEFAULT bitmaps Lock-on.gif]]
    }
    if { ![ info exist LayerImage(UnFreeze)] } {
	set LayerImage(UnFreeze) [ image create photo -file [ file join $GIDDEFAULT bitmaps Lock-off.gif]]
    }
    set def_back [ $w.options2 cget -background]
    BotonPlano $w.options2.fr On "SetLayersTo FREEZE" $def_back [ CCColorActivo $def_back]
    $w.options2.fr conf -image $LayerImage(Freeze) -takefocus 0 -padx 4 -pady 2 -width 26 -height 26
    GidHelp "$w.options2.fr " \
	[_ "Entities belonging to a freeze layer will be drawn but cannot be selected or modified."]
    BotonPlano $w.options2.ufr Off "SetLayersTo UNFREEZE" $def_back [ CCColorActivo $def_back]
    $w.options2.ufr conf -image $LayerImage(UnFreeze) -takefocus 0 -padx 4 -pady 2 -width 26 -height 26
    GidHelp "$w.options2.ufr " \
	[_ "Entities belonging to a unfreeze layer will be selected and modified."]

    button $w.options2.sel -text [_ "Sel"]... -command "SelectLayersByRegexp" -bd 1 -padx 5 -width $mw
    GidHelp "$w.options2.sel " \
	[_ "Select layers with filters (for example: 'b*' select all the layers with name beginning by 'b')"]
    grid $w.options2.fr -sticky e -row 0 -column 0 -padx 2 -pady 1
    grid $w.options2.ufr -sticky w -row 0 -column 1 -padx 2 -pady 1
    grid $w.options2.sel -sticky e -row 0 -column 2 -padx 2 -pady 1
    grid rowconfigure $w.options2 0 -weight 1
    grid columnconfigure $w.options2 0 -weight 1
    grid columnconfigure $w.options2 1 -weight 1
    grid columnconfigure $w.options2 2 -weight 1

    bind $w <Alt-o> "$w.options.on invoke; break"
    bind $w <Alt-f> "$w.options.off invoke; break"
    bind $w <Alt-e> "$w.options2.fr invoke; break"
    bind $w <Alt-u> "$w.options2.ufr invoke; break"

    bind $w <Control-o> "$w.options.on invoke; break"
    bind $w <Control-f> "$w.options.off invoke; break"
    bind $w <Control-e> "$w.options2.fr invoke; break"
    bind $w <Control-u> "$w.options2.ufr invoke; break"

    frame $w.touse -bd 0
    button $w.touse.b -text [_ "Layer To use"]: -command "SetLayersTo TOUSE" -bd 1 -padx 5 
    GidHelp "$w.touse.b " \
	[_ "Set the current layer (the new entities are created in this layer)."]

    menubutton $w.touse.m -image [imagefrom arrow_down_vsmall.gif] -menu $w.touse.m.m \
	    -relief raised -bd 1 -direction flush
    GidHelp "$w.touse.m " \
	[_ "This option permmits to select one entity and retrieve its layer."]
    menu $w.touse.m.m -postcommand "LayerToUseEntities $w.touse.m.m"
    bind $w.touse.m <1> {
	if {$tkPriv(inMenubutton) != ""} {
	    tkMbPost_ram $tkPriv(inMenubutton) $wChangeLay.touse.b 
	}
	break
    }

    label $w.touse.l -foreground blue

    set aa [.central.s info Project]

    if { [lindex $aa 3] == "*****" } { 
	$w.touse.l conf -text "*****"
    } else { $w.touse.l conf -text "[lindex $aa 3]" }
    grid $w.touse.b -row 0 -column 0 -sticky e -padx 0 -pady 1
    grid $w.touse.m -row 0 -column 1 -sticky wns -padx 0 -pady 1
    grid $w.touse.l -row 0 -column 2 -sticky w -padx 3 -pady 1

    grid rowconfigure $w.touse 0 -weight 1
    grid columnconfigure $w.touse 2 -weight 1

    

    frame $w.ent -bd 0
    entry $w.ent.e -relief sunken -bd 1
    button $w.ent.b -text [_ "New"] -command "EnterNewLayer $w" -bd 1 -padx 5 -width $mw
    GidHelp "$w.ent.b " \
	[_ "Create a new layer."]

    bind $w.ent.e <Return> { 
	$wChangeLay.ent.b config -relief sunken
	update idletasks
	$wChangeLay.ent.b invoke
	$wChangeLay.ent.b config -relief raised
    }
 
    grid $w.ent.e $w.ent.b -sticky ew -padx 2 -pady 1
    grid rowconfigure $w.ent 0 -weight 1
    grid columnconfigure $w.ent 0 -weight 1


    frame $w.dr -bd 0
    button $w.dr.bdel -text [_ "Delete"] -command "SetLayersToDelete" -bd 1 -padx 5
    set mw [expr [DWGetMaxWidth $w.dr.bdel 0 "Delete" "Rename"]+1]
    $w.dr.bdel configure -width $mw
    GidHelp "$w.dr.bdel " \
	[_ "Delete a layer."]
    button $w.dr.bren -text [_ "Rename"] -bd 1 -padx 5 -width $mw -command {
	SetSelection
	if { [llength $LayersSelection] !=1 } {
	    tk_dialogRAM $wChangeLay.m [_ "error"] \
		    [_ "Before applying rename it is necessary to select 1 layer"] \
		    error 0 [_ "OK"]
	    return
	}
	set name [string trim [$wChangeLay.ent.e get]]
	if { $name != "" } {
	    foreach i $LayerNames {
		if { $i == $name } {
		    tk_dialogRAM $wChangeLay.m [_ "error"] \
		            [_ "Layer '%s' already exists" $i] \
		            error 0 [_ "OK"]
		    return
		}
	    }
	    SetLayersTo RENAME $name
	    $wChangeLay.ent.e delete 0 end
	} else {
	    tk_dialogRAM $wChangeLay.m [_ "error"] \
		    [_ "To rename one layer select it and write a new name before pressing the button"] \
		    error 0 [_ "OK"]
	    return
	}
    }  
    GidHelp "$w.dr.bren " \
	[_ "Rename a layer."]

    checkbutton $w.dr.bred -text [_ "alphabetic"] -variable GidPriv(LayersAlphabetic) \
	    -command FillInfoLayers
    GidHelp "$w.dr.bred " \
	[_ "Sort the list of layers by name."]
    
    grid $w.dr.bdel $w.dr.bren $w.dr.bred -sticky we -padx 1 -pady 1
    
    #frame $w.buts -bd 0
    set def_back [$w cget -background]
    frame $w.buts -bg [CCColorActivo $def_back]

    if { ![info exists GidPriv(LayersAlsoLower)] } {
	set GidPriv(LayersAlsoLower) 0
    }
    if { ![info exists GidPriv(LayersBackOpposite)] } {
	set GidPriv(LayersBackOpposite) 0
    }

    menubutton $w.buts.back -text [_ "To back"] -menu $w.buts.back.m  -relief raised 
    set mw [DWGetMaxWidth  $w.buts.back 6 "To back" "Send To" "Close"]
    $w.buts.back configure -width $mw
    GidHelp "$w.buts.back " \
	[_ "Send entities to back/front of a layer (entities in back are not drawn and frozen)"]
    menu $w.buts.back.m -postcommand SendLayerEntitiesToBack
    $w.buts.back.m add check -label [_ "Also lower entities"] \
	    -var GidPriv(LayersAlsoLower)
    $w.buts.back.m add check -label [_ "Opposite"] \
	    -var GidPriv(LayersBackOpposite)

    $w.buts.back conf -bd 1 -highlightthickness 1
    $w.buts.back.m conf -bd 1 -activeborderwidth 1

    menubutton $w.buts.act -text [_ "Send To"] -menu $w.buts.act.m  -relief raised -width $mw
    GidHelp "$w.buts.act " \
	[_ "Send the selected entities to a layer.\
	   If 'Also lower entities' is checked, the subentities are also send to the layer"]
    menu $w.buts.act.m -postcommand SendLayerEntities
    $w.buts.act.m add check -label [_ "Also lower entities"] \
	    -var GidPriv(LayersAlsoLower)
    
    $w.buts.act conf -bd 1 -highlightthickness 1
    $w.buts.act.m conf -bd 1 -activeborderwidth 1
    
    button $w.buts.can -text [_ "Close"] -command "destroy $w" -width $mw

    grid $w.buts.back $w.buts.act $w.buts.can -sticky ew -padx 5 -pady 6

    grid $w.middle -sticky wens -pady 0
    grid $w.touse -sticky we -pady 0
    grid $w.options -sticky we -pady 0
    grid $w.options2 -sticky we -pady 0
    grid $w.ent -sticky we -pady 0
    grid $w.dr -sticky ew -pady 0
    grid $w.buts -sticky ews

    grid columnconfigure $w 0 -weight 1
    grid rowconfigure $w 0 -weight 1

    FillInfoLayers

    bind $w <FocusIn> "focus $w.ent.e ; bind $w <FocusIn> {}"
    bind $w <Alt-c> "tkButtonInvoke $w.buts.can"
    bind $w <Escape> "tkButtonInvoke $w.buts.can"
}

proc tkMbPost_ram {w wbut {x {}} {y {}}} {
    global tkPriv errorInfo
    global tcl_platform

    if {([$w cget -state] == "disabled") || ($w == $tkPriv(postedMb))} {
	return
    }
    set menu [$w cget -menu]
    if {$menu == ""} {
	return
    }
    set tearoff [expr {($tcl_platform(platform) == "unix") \
		     || ([$menu cget -type] == "tearoff")}]
    if {[string first $w $menu] != 0} {
	error "can't post $menu:  it isn't a descendant of $w (this is a new requirement in Tk versions 3.0 and later)"
    }
    set cur $tkPriv(postedMb)
    if {$cur != ""} {
	tkMenuUnpost {}
    }
    set tkPriv(cursor) [$w cget -cursor]
    set tkPriv(relief) [$w cget -relief]
    $w configure -cursor arrow
    $w configure -relief raised

    set tkPriv(postedMb) $w
    set tkPriv(focus) [focus]
    $menu activate none
    tkGenerateMenuSelect $menu

    # If this looks like an option menubutton then post the menu so
    # that the current entry is on top of the mouse.  Otherwise post
    # the menu just below the menubutton, as for a pull-down.

    update idletasks
    if {[catch {
	     switch [$w cget -direction] {
		above {
		        set x [winfo rootx $wbut]
		        set y [expr {[winfo rooty $wbut] - [winfo reqheight $menu]}]
		        $menu post $x $y
		}
		below {
		        set x [winfo rootx $wbut]
		        set y [expr {[winfo rooty $wbut] + [winfo height $wbut]}]
		        $menu post $x $y
		}
		left {
		        set x [expr {[winfo rootx $wbut] - [winfo reqwidth $menu]}]
		        set y [expr {(2 * [winfo rooty $wbut] + [winfo height $wbut]) / 2}]
		        set entry [tkMenuFindName $menu [$w cget -text]]
		        if {[$w cget -indicatoron]} {
		    if {$entry == [$menu index last]} {
		            incr y [expr {-([$menu yposition $entry] \
		                    + [winfo reqheight $menu])/2}]
		    } else {
		            incr y [expr {-([$menu yposition $entry] \
		                + [$menu yposition [expr {$entry+1}]])/2}]
		    }
		        }
		        $menu post $x $y
		        if {($entry != {}) && ([$menu entrycget $entry -state] != "disabled")} {
		            $menu activate $entry
		    tkGenerateMenuSelect $menu
		        }
		}
		right {
		        set x [expr {[winfo rootx $wbut] + [winfo width $wbut]}]
		        set y [expr {(2 * [winfo rooty $wbut] + [winfo height $wbut]) / 2}]
		        set entry [tkMenuFindName $menu [$w cget -text]]
		        if {[$w cget -indicatoron]} {
		    if {$entry == [$menu index last]} {
		            incr y [expr {-([$menu yposition $entry] \
		                    + [winfo reqheight $menu])/2}]
		    } else {
		            incr y [expr {-([$menu yposition $entry] \
		                + [$menu yposition [expr {$entry+1}]])/2}]
		    }
		        }
		        $menu post $x $y
		        if {($entry != {}) && ([$menu entrycget $entry -state] != "disabled")} {
		            $menu activate $entry
		    tkGenerateMenuSelect $menu
		        }
		}
		default {
		        if {[$w cget -indicatoron]} {
		        if {$y == ""} {
		        set x [expr {[winfo rootx $wbut] + [winfo width $wbut]/2}]
		        set y [expr {[winfo rooty $wbut] + [winfo height $wbut]/2}]
		        }
		    tkPostOverPoint $menu $x $y [tkMenuFindName $menu [$w cget -text]]
		} else {
		        $menu post [winfo rootx $wbut] [expr {[winfo rooty $wbut]+[winfo height $wbut]}]
		        }  
		}
	     }
     } msg]} {
	# Error posting menu (e.g. bogus -postcommand). Unpost it and
	# reflect the error.
	
	set savedInfo $errorInfo
	tkMenuUnpost {}
	error $msg $savedInfo

    }

    set tkPriv(tearoff) $tearoff
    if {$tearoff != 0} {
	    focus $menu
	    tkSaveGrabInfo $w
	    grab -global $w
    }
}
