Class Editor 

Editor set uniqueID_ 0

Editor proc getid {} {
    set id [Editor set uniqueID_]
    Editor set uniqueID_ [expr $id + 1]
    return $id
}

Editor instproc init {tracefile} {

    $self instvar menulist_ SharedEnv id_ editorwindow_ scenarioname_ newView
    $self includeMenu 

    set id_ [Editor getid]

    toplevel .nameditor-$id_
    set editorwindow_ .nameditor-$id_
    wm title $editorwindow_ "NAM Editor-$id_"

    if {$tracefile == ""} {
        set scenarioname_ /tmp/scenario-$id_
    } else {
        set scenarioname_ $tracefile
	$self setmodelrange $tracefile
    }

    $self createMenu $editorwindow_ menu $menulist_
    $self create_editview $editorwindow_ 

    $self setCursor Select
    $self buttonReq .buttons .radiosr
    $self setCursor Select

}

Editor instproc setmodelrange {tracefile} {

    set stream [new NamStream $tracefile]
    set time "0"
    while {([$stream eof]==0)&&([string compare $time "*"]!=0)} {
        set line [$stream gets] 
        set time [get_trace_item "-t" $line]
    }

    while {([$stream eof]==0)&&([string compare $time "*"]==0)} {
        set cmd [lindex $line 0]
        set time [get_trace_item "-t" $line]
        if {[string compare $time "*"]!=0} {break}
        switch $cmd {
            "W" {
                    set minx [get_trace_item "-x" $line]
                    set miny [get_trace_item "-y" $line]
                    set maxx [get_trace_item "-X" $line]
                    set maxy [get_trace_item "-Y" $line]
                    NetworkModel/Editor set Wpxmin_ $minx
                    NetworkModel/Editor set Wpymin_ $miny
                    NetworkModel/Editor set Wpxmax_ $maxx
                    NetworkModel/Editor set Wpymax_ $maxy
                    break
            }
        }
        set line [$stream gets]
    }   
    $stream close

}

Editor instproc create_editview {m} {

    $self instvar id_ scenarioname_ SharedEnv netModel newView

    # create a tmp file
    if {![file exists $scenarioname_]} {
        exec > $scenarioname_
    }

    set w $m.editviewer
    frame $w
    frame $w.f

    #frame is just to sink the newView

    frame $w.f.f -borderwidth 2 -relief sunken

    # setup model first
    
    set netModel [new NetworkModel/Editor $self $scenarioname_]

    $netModel editview $w.f.f.net

    set newView $w.f.f.net
#    lappend netViews $newView

    set SharedEnv(CurrentCanvas) $newView
    pack $w.f.f.net -side top -expand true -fill both

    $newView xscroll $w.f.hsb
    scrollbar $w.f.hsb -orient horizontal -width 10 -borderwidth 1 \
            -command "$newView xview"
    $w.f.hsb set 0.0 1.0
    pack $w.f.hsb -side bottom -fill x
    pack $w.f.f -side top -fill both -expand true

    frame $w.f2
    $newView yscroll $w.f2.vsb
    scrollbar $w.f2.vsb -orient vertical -width 10 -borderwidth 1 \
            -command "$newView yview"
    $w.f2.vsb set 0.0 1.0
    pack $w.f2.vsb -side top -fill y -expand true
    frame $w.f2.l -width 12 -height 12
    pack $w.f2.l -side top

    frame $w.ctrl -borderwidth 2 -relief groove
    $self build-zoombar $newView $w.ctrl $w
    pack $w.ctrl -side left -fill y

    pack $w.f2 -side right -fill y
    pack $w.f -side left -fill both -expand true
    pack $w -side left -fill both -expand true
    $self view_bind $newView

}

Editor instproc view_bind {netView} {

	$self instvar SharedEnv

	bind $netView <Button-1> "$self leftButtonAction \%x \%y"
	bind $netView <Any-B1-Motion> "$self moveMouseAction \%x \%y"
	bind $netView <ButtonRelease-1> "$self leftButtonRAction \%x \%y"
	bind $netView <Motion> "$self generalMouseAction \%x \%y"
	bind $netView <Double-Button-1> "$self doubleLButtonAction \%x \%y"

#       bind $netView <ButtonPress-3> "$self start_info $netView \%x \%y right"
#       bind $netView <ButtonPress-2> "$self view_drag_start $netView \%x \%y"
#       bind $netView <B2-Motion> "$self view_drag_motion $netView \%x \%y"
#       bind $netView <ButtonRelease-3> "$self end_info $netView"
}

Editor instproc doubleLButtonAction {x y} {
$self instvar SharedEnv newView
    
        switch $SharedEnv(Cursor) {
    
            Select {
		set objinfo [$newView getObjectProperty $x $y]
		if {[string compare $objinfo "NONE"] == 0 } { return }
		set item [lindex $objinfo 0]
		set item [lindex $item 0]
		$self propRaise .prop $item $objinfo

	    }
	}

}

Editor instproc generalMouseAction {x y} {
	$self instvar SharedEnv newView

	switch $SharedEnv(Cursor) {

	    Cut -
	    Select {

		set objinfo [$newView getObject $x $y]
		if {[string compare $objinfo "NONE"] !=0} {
		    $self enterObject $newView $x $y $objinfo
		} else {
		    catch {destroy $newView.f}
		}

	    }
	
	}

}

Editor instproc leftButtonAction {x y } {
	$self instvar SharedEnv newView

        switch $SharedEnv(Cursor) {
            Select {
			 $newView setPoint $x $y 0
                    }
             Node {
                         $newView addNode $x $y
                   }
             Link {
                         $newView addLink $x $y
                   }
	     Cut   {
			 $newView deleteObj $x $y
		   }

        }

}

Editor instproc leftButtonRAction {x y } {
	$self instvar SharedEnv newView

        switch $SharedEnv(Cursor) {

            Select {
			 $newView relPoint $x $y
                    }

        }

}

Editor instproc moveMouseAction {x y } {
	$self instvar SharedEnv newView

        switch $SharedEnv(Cursor) {
            Select {
			 $newView moveTo $x $y
                    }
        }

}

Editor instproc propLower {name} {

        set w ${name}
        wm withdraw $w
}


Editor instproc propRaise {name item attrs} {
        $self instvar SharedEnv
                        
        set w ${name}
        set SharedEnv(PropReplace) $SharedEnv(CurrentCanvas)
        
        if {![winfo exists ${name}]} {
        	$self propRequestor $name $item $attrs
        }       

        set ph [winfo fpixels $SharedEnv(CurrentCanvas) $SharedEnv(PageHeight)]
        set pw [winfo fpixels $SharedEnv(CurrentCanvas) $SharedEnv(PageWidth)]

        if {$ph > $pw} {
                set pix [expr 200.0 / $ph]
        } else {
                set pix [expr 200.0 / $pw]
        }                       
        set ch [expr $pix * $ph]
        set cw [expr $pix * $pw]
        set sc $pix             
                  
#        $w.c configure -width $cw -height $ch
#        set or [getOrigin "$items"]
#        $w.s configure -to [expr [llength $items]] \
#                -command "propDraw $w $sc {$or} {$items}"
#        $w.s set 1
#        propDraw $w $sc "$or" "$items" 1
	$self propDisplay $name $item $attrs	
        wm deiconify $w
        raise $w
        focus $w
}

Editor instproc showpalette {} {
    
    $self colorPaletteReq .colorpalette \
                                {0000 3300 6600 9900 CC00 FF00} \
                                {0000 3300 6600 9900 CC00 FF00} \
                                {0000 3300 6600 9900 CC00 FF00} \
                .colorsp
}


Editor  instproc propDisplay {name item attrs} {
        $self instvar SharedEnv concmd colorarea
	set SharedEnv($item) $attrs
     
        if {[winfo exists $name.p.p]} {
                eval destroy [pack slaves $name.p.p]
        } else {
                frame $name.p.p
        }

        set props $SharedEnv($item)
        set i 0
        set concmd ""
	
        foreach prop $props {
                set propname [lindex $prop 0]
                $self instvar var${propname}

                set var${propname} [lindex $prop 1]

                frame $name.p.p.f$i
		if { [string compare $propname "COLOR"] == 0 } {
                    button $name.p.p.f$i.l${propname} -text "$propname" \
			-command "$self showpalette "
		    set colorarea $name.p.p.f$i.eCOLOR
		} else {
                    label $name.p.p.f$i.l${propname} -text "$propname"

		}

#               entry $name.p.p.f$i.e${propname} -textvariable var${propname} \
#                                -width 20

		if {$i == 0} {
		    label $name.p.p.f$i.e${propname} -text "[lindex $prop 1]"
		} else {

		    text $name.p.p.f$i.e${propname} -width 20 -height 2
                        $name.p.p.f$i.e${propname} insert 0.0 [lindex $prop 1]
                        set textwidget $name.p.p.f$i.e${propname}
		}

                pack $name.p.p.f$i.l${propname} -in $name.p.p.f$i -side left -fill x
                pack $name.p.p.f$i.e${propname} -in $name.p.p.f$i -side right
                pack $name.p.p.f$i -in $name.p.p -side top -fill x -expand true
                incr i
		if {$i > 1} {
		    append concmd " ${propname} \"${textwidget} get 0.0 1.end\""
		} else {
		    append concmd "${propname} \"[lindex $prop 1]\""
		}
        }


        button $name.p.p.ok -text "OK" -command "$self propLower $name"
        button $name.p.p.cancel -text "Cancel" -command "$self propLower $name"
        button $name.p.p.apply -text "Apply" \
                -command "$self setObjProperty"

	pack $name.p.p.ok $name.p.p.cancel $name.p.p.apply  -in $name.p.p \
		-side left -padx 1m -pady 1m

        pack $name.p.p -in $name.p
}    

Editor instproc setObjProperty {} {

	$self instvar concmd newView
	set i 0

	set type [lindex $concmd 0]
	set typeid [lindex $concmd 1]

	foreach prop $concmd {
	    if { [expr $i%2] == 0 } {
		set attrname $prop
	    } else {
		if { $i == 1 } {
		    set attr($attrname) $prop
		} else {
		    set attr($attrname) [eval $prop]
		}

	    }
	    incr i
	}
	
	foreach index [array names attr] {

	    switch "$type" {
		
		NODE {

		    switch "$index" {
		        SIZE {
			    $newView setNodeProperty $typeid $attr($index) 0
			}
			COLOR {
			    $newView setNodeProperty $typeid $attr($index) 1
			}
			LABEL {
			    $newView setNodeProperty $typeid $attr($index) 2
			}
	
		    }
		}

		LINK {

			set src_dst [split $typeid "."]
			set src [lindex $src_dst 0]
			set dst [lindex $src_dst 1]

		    switch "$index" {
                        BANDWIDTH {
                            $newView setLinkProperty $src $dst $attr($index) 0
                        }
                        COLOR {
                            $newView setLinkProperty $src $dst $attr($index) 1
                        }
                        DELAY {
                            $newView setLinkProperty $src $dst $attr($index) 2
                        }

                    }


		}


	    }


	}
}


Editor instproc propRequestor {name item attr} {
        $self instvar SharedEnv
     
        set w ${name}
     
        toplevel $w
        wm transient $w .
        wm protocol $w WM_DELETE_WINDOW {set dummy 1}
	
	frame $w.p
	$self propDisplay $name $item $attr
     
#        frame $w.f -borderwidth 0 -highlightthickness 0
#        frame $w.p
#        frame $w.fsel -borderwidth 0 -highlightthickness 0
#        frame $w.texttop -borderwidth 0 -highlightthickness 0
#        frame $w.textbottom -relief raised -bd 1
#        canvas $w.c -width 1.5i -height 1.5i -relief sunken -bd 1 -bg white
#        label $w.l
#        scale $w.s -orient horiz -resolution 1 -from 1 -to 1 \
#        -variable SharedEnv(PropItem) -bd 2 -relief raised -highlightthickness 0 \
#        -width 8 -showvalue true
     
#        button $w.ok -text "OK" -command "$self propLower $w"
#        button $w.cancel -text "Cancel" -command "$self propLower $w"
#        button $w.apply -text "Apply" \
#                -command "$self propLower $w"
        bind $w <Key-Escape> "$self propLower $w"
     
#        pack $w.c -in $w.texttop
#        pack $w.l -in $w.texttop -fill x
#        pack $w.s -in $w.texttop -fill x
#        pack $w.ok $w.cancel $w.apply -in $w.textbottom -side left -padx 1m -pady 1m
#        pack $w.texttop -anchor sw -in $w.fsel
#        pack $w.textbottom -anchor sw -in $w.p -fill x
        pack $w.p -in $w -anchor sw -side left
     
        wm withdraw $w
        return $w
}    


Editor instproc build-zoombar {view w mainW} {
        $self instvar magnification viewOffset
        set magnification 1.0
        set viewOffset(x) 0.0
        set viewOffset(y) 0.0
        frame $w.f
        pack $w.f -side top
        button $w.f.b1 -bitmap "zoomin" -command "$view zoom 1.6" \
                        -highlightthickness 0 -borderwidth 1
        pack $w.f.b1 -side top -ipady 3
        button $w.f.b2 -bitmap "zoomout" -command "$view zoom 0.625" \
                        -highlightthickness 0 -borderwidth 1
        pack $w.f.b2 -side top -ipady 3

}


Editor instproc explodeList {menu list parentmenu} {
        $self instvar menu_buttons SharedEnv editorwindow_

        set menuname [lindex $list 0]
        set menutitle [lindex $list 1]
        set menuopts [lindex $list 2]
        set menucmd [lindex $list 3]
        set newlist [lindex $list 4]

        # Menubutton
        if {"${parentmenu}" == "${menu}"} {
        menubutton ${parentmenu}.${menuname}_b -text "$menutitle" \
                        -menu ${parentmenu}.${menuname}_b.${menuname} -padx 4m
                if { "$menuopts" != ""} {
                        eval ${parentmenu}.${menuname}_b configure $menuopts
                }
                pack ${parentmenu}.${menuname}_b -side left -fill x
        menu ${parentmenu}.${menuname}_b.${menuname}
                lappend menu_buttons ${parentmenu}.${menuname}_b
                set menuname ${menuname}_b.${menuname}
        # MenuItem
        } elseif {"$newlist" == ""} {
                if {"${menutitle}" == ""} {
                        eval ${parentmenu} add separator ${menuopts}
                } else {
                        eval ${parentmenu} add command -label \"${menutitle}\" \
                                -command \"${menucmd}\" ${menuopts}
                } 
        # MenuCascade (subMenu)
        } else {
                eval ${parentmenu} add cascade -label \"$menutitle\" \
                        -menu ${parentmenu}.${menuname} ${menuopts}
                menu ${parentmenu}.${menuname}
        }
        set len [llength "$newlist"]
        if {$len} {
                for {set i 0} {$i < $len} {incr i} {
                        set l [lindex "$newlist" $i]
                        $self explodeList "$menu" "$l" "${parentmenu}.${menuname}"
                }
        }
        return $menu_buttons
}

Editor instproc createMenu {w name menulist} {
        $self instvar SharedEnv scenarioname_


        frame $w.${name}_frame
        pack $w.${name}_frame -fill x

        set newlist [lindex $menulist 4]
        set len [llength "$newlist"]
        for {set i 0} {$i < $len} {incr i} {
                set l [lindex "$newlist" $i]
                set menu_buttons \
                        [$self explodeList "$w.${name}_frame" "$l" "$w.${name}_frame"]
        }

	# add the editted scenario file name

	label $w.${name}_frame.name -text $scenarioname_ -font [smallfont] \
                -width 30 -borderwidth 2 -relief groove

#	label $w.${name}_frame.xpos -relief flat -textvariable SharedEnv(Xpos) -height 1 -width 10
#	label $w.${name}_frame.ypos -textvariable SharedEnv(Ypos) -height 1 -width 10

	label $w.${name}_frame.msg -relief flat -textvariable SharedEnv(Message) -height 1 -width 20

	pack $w.${name}_frame.name -side left -fill x -expand true -padx 4 -pady 1
#	pack $w.${name}_frame.xpos -side left -fill x -expand true -padx 4 -pady 1
#	pack $w.${name}_frame.ypos -side left -fill x -expand true -padx 4 -pady 1
	pack $w.${name}_frame.msg -side left -fill x -expand true -padx 4 -pady 1

	set SharedEnv(msgtitle) $w.${name}_frame.msg
	set SharedEnv(saveasfile) $w.${name}_frame.name

        bind . <Any-FocusIn> "
                if {(\"%d\" == \"NotifyVirtual\") && (\"%m\" == \"NotifyNormal\")} {
                        focus $w.${name}_frame
                }
        "

        return "$w.${name}_frame $menu_buttons"
}


Editor instproc buttonReq { name replace } {
	$self instvar SharedEnv

	set var $SharedEnv(Buttons)

	if {$SharedEnv(ButtonOrient) == "left"} {
		set suborient top
	} else {
		set suborient left
	}
	set w ${name}
	if {[winfo exists $w]} {
			wm deiconify $w
			raise $w
			return
	}
	set SharedEnv($name) $replace

	eval toplevel $w
	wm protocol $w WM_DELETE_WINDOW "wm withdraw $w"
	wm title $w "Toolsbar"

	
	frame $w.f

	set bframes "$w.f1 $w.f2 $w.f3 $w.f4 $w.f5 $w.f6 $w.f7 $w.f8 $w.f9"

	set i 0
	set bframe ""
	foreach buttontype $var {

		if {![expr $i % $SharedEnv(ButtonCount)]} {
			if {$bframe != ""} {
				pack $bframe -in $w.f -side $suborient
			}
			set bframe [lindex $bframes [expr $i / $SharedEnv(ButtonCount)]]
			frame $bframe
		}
		incr i
		set type [lindex $buttontype 0]
		set buttonName [lindex $buttontype 1]
		set buttonCanv [lindex $buttontype 2]
		switch "$type" {
			RadioButton {
				$self createRadioButton $w.b_${buttonName} \
					$SharedEnv(ButtonSize) $SharedEnv(ButtonSize) \
					"$buttonCanv" SharedEnv(Cursor) \
					$buttonName -bd 1 -highlightthickness 0
			}
			Button {
				$self createNormalButton $w.b_${buttonName} \
					$SharedEnv(ButtonSize) $SharedEnv(ButtonSize) \
					"$buttonCanv" \
					$buttonName -bd 1 -highlightthickness 0
			}
			JoinButton { 
				createRadioButton $w.b_${buttonName} \
					$SharedEnv(ButtonSize) $SharedEnv(ButtonSize) \
					"$buttonCanv" SharedEnv(JoinStyle) \
					$buttonName -bd 1 -highlightthickness 0
			}
			ArrowButton {
				createRadioButton $w.b_${buttonName} \
					$SharedEnv(ButtonSize) $SharedEnv(ButtonSize) \
					"$buttonCanv" SharedEnv(Arrow) \
					$buttonName -bd 1 -highlightthickness 0
			}
		}
		switch "$buttonName" {
			Paste {
				$self disablePaste
			}
			Rulers {
				bind $w.b_Rulers <Double-Button-1> {
					%W addtag disabled withtag all
                	$SharedEnv(CurrentCanvas) delete $SharedEnv(RulerX)
                	$SharedEnv(CurrentCanvas) delete $SharedEnv(RulerY)
        		}     
				bind $w.b_Rulers <ButtonRelease-1> {+
					%W dtag disabled
				}
			}
		}
		set SharedEnv(W_${buttonName}) $w.b_${buttonName}
		pack $w.b_${buttonName} -in $bframe -side $SharedEnv(ButtonOrient)
	}
	pack $bframe -in $w.f -side left
	pack $w.f -in $w
}

Editor instproc createRadioButton {name width height cmds var value args} {
        $self instvar SharedEnv                   
                         
        eval canvas $name -width $width -height $height \
                -relief $SharedEnv(ButtonRelief) $args

        set saveit $SharedEnv(CurrentCanvas)
        set SharedEnv(CurrentCanvas) $name 
        eval $cmds                      
        $self originObject all                
        $self scaleObject all "" [winfo fpixels $name $width] \
                [winfo fpixels $name $height]
        set SharedEnv(CurrentCanvas) $saveit
        bind $name <Button-1> " 
                if {\[%W find withtag disabled\] == \"\"} {
                        $self setRadioButton $var $value
                        if {\"$var\" == \"SharedEnv(Cursor)\"} {
                                $self popupCanvasSet $value
                        }       
                }                       
        "                               
        bind $name <Enter> "            
                if {\[%W find withtag disabled\] == \"\"} {
                        %W configure -bg $SharedEnv(ActiveBackground)
                        if {[info exists SharedEnv(Msg_$value)]} {
                                set SharedEnv(Message) \$SharedEnv(Msg_$value)
                        } else {
                                set SharedEnv(Message) $value
                        }
                        $self enterToolButtons %W %x %y $value
                }
        "
        bind $name <Leave> "
                if {\[%W find withtag disabled\] == \"\"} {
                        %W configure -bg $SharedEnv(Background)
                        set SharedEnv(Message) \[$self setMessage\]
                        $self leaveToolButtons %W
                }
        "
     
        return $name
}    

Editor instproc setMessage {} {
	$self instvar SharedEnv
	return $SharedEnv(Cursor)
}

Editor instproc originObject { name } {
        $self instvar SharedEnv
                
        set bb [$SharedEnv(CurrentCanvas) bbox $name]
        set x [lindex $bb 0]
        set y [lindex $bb 1]
        if {$x > 0} {
                set nx -$x
        } else {
                set nx [expr abs($x)]
        }
        if {$y > 0} {
                set ny -$y              
        } else {         
                set ny [expr abs($y)]
        }       
        $SharedEnv(CurrentCanvas) move $name $nx $ny
}    

Editor instproc scaleObject {name ratio width height} {
	$self instvar SharedEnv

	set bb [eval $SharedEnv(CurrentCanvas) bbox $name]
	if {"$bb" != ""} {
		set x [lindex $bb 2]
		set y [lindex $bb 3]
		if {$ratio == "variable"} {
			set scalex [expr ($width + 0.0) / $x]
			set scaley [expr ($height + 0.0) / $y]
			if {$scalex > $scaley} {
				set scale $scaley
			} else {
				set scale $scalex
			}
		} elseif {$ratio != ""} {
			set scalex $ratio
			set scaley $ratio
			set scale $ratio
		} else {
			set scalex [expr ($width + 0.0) / $x]
			set scaley [expr ($height + 0.0) / $y]
			if {$scalex > $scaley} {
				set scalex $scaley
				set scale $scaley
			} else {
				set scaley $scalex
				set scale $scalex
			}
		}
		$SharedEnv(CurrentCanvas) scale $name 0 0 $scalex $scaley
		foreach i [$SharedEnv(CurrentCanvas) find withtag all] {
			set type [$SharedEnv(CurrentCanvas) type $i]
			if {"$type" != "text"} {
				continue
			}
			if {$SharedEnv(FontScale)} {
				set fn [$SharedEnv(CurrentCanvas) itemcget $i -font]
				regexp \
				{([-][^-]*-[^-]*-[^-]*-[^-]*-[^-]*-[^-]*-[^-]*-)([^-]*)(-.*)}\
					$fn dummy d1 size d2;
				if {"$dummy" != ""} {
					set nsize [expr round($size * $scale)]
					if {$nsize < 20} {
						set nsize 20
					}
					$SharedEnv(CurrentCanvas) itemconfigure $i \
						-font ${d1}${nsize}${d2}
					set fnn [$SharedEnv(CurrentCanvas) itemcget $i -font]
					regexp \
						{([-][^-]*-[^-]*-[^-]*-[^-]*-[^-]*-[^-]*-[^-]*-)([^-]*)(-.*)}\
						$fnn dummy d1 nsize d2;
					if { ($scale < 1 && $nsize < $size ) || \
						 ($scale > 1 && $nsize > $size) } {
						$SharedEnv(CurrentCanvas) itemconfigure $i \
							-width [expr [$SharedEnv(CurrentCanvas) itemcget $i \
							-width] * $scale]
					} else {
						$SharedEnv(CurrentCanvas) itemconfigure $i \
							-font $fn
					}
				}
			} else {
				$SharedEnv(CurrentCanvas) itemconfigure $i \
					-width [expr [$SharedEnv(CurrentCanvas) itemcget $i -width] \
						* $scale]
			}
		}
	}
}

Editor instproc createNormalButton {name width height cmds value args} {
        $self instvar SharedEnv

        eval canvas $name -width $width -height $height \
                -relief $SharedEnv(ButtonRelief) $args
     
        set saveit $SharedEnv(CurrentCanvas)
        set SharedEnv(CurrentCanvas) $name
        eval $cmds
        $self originObject all
        $self scaleObject all "" [winfo fpixels $name $width] \
                [winfo fpixels $name $height]
        set SharedEnv(CurrentCanvas) $saveit
        bind $name <Button-1> "
                if {\[%W find withtag disabled\] == \"\"} {
                        set bd \[%W cget -bd\]
                        %W configure -relief sunken
                        %W move all \$bd \$bd
                        update idletasks
                }
        "
        bind $name <ButtonRelease-1> "
                if {\[%W find withtag disabled\] == \"\"} {
                        set bd \[%W cget -bd\]
                        $self popupCanvasSet $value
                        %W move all -\$bd -\$bd
                        %W configure -relief $SharedEnv(ButtonRelief)
                }
        "
        bind $name <Enter> "
                if {\[%W find withtag disabled\] == \"\"} {
                        %W configure -bg $SharedEnv(ActiveBackground)
                        if {[info exists SharedEnv(Msg_$value)]} {
                                set SharedEnv(Message) \$SharedEnv(Msg_$value)
                        } else {
                                set SharedEnv(Message) $value
                        }
                }
        "
        bind $name <Leave> " 
                if {\[%W find withtag disabled\] == \"\"} {
                        %W configure -bg $SharedEnv(Background)
                        set SharedEnv(Message) $SharedEnv(Cursor)
                }
        "
     
        return $name
}    

Editor instproc disablePaste {} {  
        $self instvar  SharedEnv  
     
        if {$SharedEnv(Cut) == ""} {
                $self disableButton .buttons.b_Paste
        }
}    

Editor instproc disableButton { name } {
        $self instvar SharedEnv
     
        $name create rectangle 0 0 $SharedEnv(ButtonSize) $SharedEnv(ButtonSize) \
                -fill $SharedEnv(Background) -stipple gray50 -outline {} -tags disabled
}   

Editor instproc setCursor { value } {                              
        $self instvar SharedEnv                                   
                                                        
        set SharedEnv(Cursor) $value                       
        $self setRadioButton SharedEnv(Cursor) $value    
}

Editor instproc setRadioButton { var value } {
        $self instvar SharedEnv

        if {[info exists SharedEnv(W_${value})]} {
                set bd [$SharedEnv(W_${value}) cget -bd]
                $self clearRadioVariable $var
                $SharedEnv(W_${value}) configure -relief sunken
                $SharedEnv(W_${value}) move all $bd $bd
                set SharedEnv($var) $SharedEnv(W_${value})
        }        
        set $var "$value"       
}

Editor instproc clearRadioVariable {var} { 
        $self instvar SharedEnv           
        if {[info exists SharedEnv($var)] && [winfo exists $SharedEnv($var)]} {
                set bd [$SharedEnv($var) cget -bd]
                $SharedEnv($var) configure -relief $SharedEnv(ButtonRelief)
                eval $SharedEnv($var) move all -$bd -$bd
        }       
        set $var ""  
}

Editor instproc enterObject { w x y value } {

    catch {destroy $w.f}
    frame $w.f -relief groove -borderwidth 2
    message $w.f.msg -width 8c -text $value
    pack $w.f.msg
    pack $w.f
    catch {place_frame $w $w.f [expr $x+10] [expr $y+10]}

}


Editor instproc enterToolButtons { w x y value } {
	$self instvar SharedEnv
    set geo [winfo geometry $w]
    set px [lindex [split $geo "+"] 1]
    set py [lindex [split $geo "+"] 2]
    set psize [lindex [split $geo "+"] 0]
    set pxsize [lindex [split $psize "x"] 0]
    set pysize [lindex [split $psize "x"] 1]
                        
    set w [winfo parent $w]

    catch {destroy $w.fm}

    frame $w.fm -relief groove -borderwidth 2
    message $w.fm.msg -width 10c -text $value -background yellow
    pack $w.fm.msg
    pack $w.fm 

    catch {place_frame $w $w.fm [expr $pxsize+$px] [expr $pysize+$py]}
}

Editor instproc leaveToolButtons { w } {
    set w [winfo parent $w]
    catch {destroy $w.fm} 
}


Editor instproc colorPaletteReq { name redlist greenlist bluelist replace } {
	$self instvar SharedEnv netModel

	# Setup
	set w ${name}
	if {[winfo exists $w]} {
			wm deiconify $w
			raise $w
			return
	}
	set SharedEnv($name) $replace
	eval toplevel $w $SharedEnv(PrivateCmap)

        wm protocol $w WM_DELETE_WINDOW "wm withdraw $w"

	frame $w.f

	foreach red $redlist {
		frame $w.f.rcol_${red}
		foreach green $greenlist {
			frame $w.f.grow_${red}${green}
			foreach blue $bluelist {
				if { [info exists SharedEnv($w.f.c${red}${green}${blue})] } {
					frame $w.f.c${red}${green}${blue} \
						-relief raised -height 2m -width 2m \
						-highlightthickness 0 \
						-bd 1 -bg $SharedEnv($w.f.c${red}${green}${blue})
				} else {
					frame $w.f.c${red}${green}${blue} \
						-relief raised -height 2m -width 2m \
						-highlightthickness 0 \
						-bd 1 -bg "#${red}${green}${blue}"
				}
				pack $w.f.c${red}${green}${blue} -side left \
					-in $w.f.grow_${red}${green} -fill both -expand true
				bind $w.f.c${red}${green}${blue} <1> {
					%W configure -relief sunken
				}
				bind $w.f.c${red}${green}${blue} <Double-Button-1> "
					set SharedEnv(NewColor) {None}
					colorRequestor .cr %W {$redlist} {$greenlist} {$bluelist} \
						$replace
					destroy $w 
				"
				bind $w.f.c${red}${green}${blue} <ButtonRelease-1> "
					$self getcolorname %W

				"
					
			}
			pack $w.f.grow_${red}${green} -side top \
				-in $w.f.rcol_${red} -fill both -expand true
		}
		pack $w.f.rcol_${red} -side left -in $w.f -fill both \
			-expand true
	}

        frame $w.f.c_none -width 4m -relief raised -bd 1 \
                -highlightthickness 0
        pack $w.f.c_none -in $w.f -side left -fill y 

	pack $w.f -in $w -expand true -fill both

	# Return
        wm geometry $w $SharedEnv(ColorWidth)x$SharedEnv(ColorHeight)

}

Editor instproc getcolorname {w} {
	$self instvar netModel colorarea

	$w configure -relief raised
	set colorv [$w cget -bg] 
	set rgb [winfo rgb $w $colorv]
	set colorn "[$netModel lookupColorName [lindex $rgb 0] \
               [lindex $rgb 1] [lindex $rgb 2]]"
	
	if {[info exists colorarea] && [winfo exists $colorarea]} {

	    $colorarea delete 0.0 end
	    $colorarea insert 0.0 $colorn 
	    catch { $colorarea tag add bgcolor 0.0 end }
	    $colorarea tag configure bgcolor -background $colorn
	
	}
	
}

Editor instproc popupCanvasSet { type } {
	$self instvar SharedEnv

	$self setCursor "$type"
	switch "$SharedEnv(Cursor)" {
		Cut {
			set SharedEnv(Message) Cut
			$self setCursor "Cut"
			#cutCopySelected Cut Imp_Selected 1
			#set SharedEnv(Message) Select
			#enableSelectionButtons
		}
		Paste {
			if {$SharedEnv(Cut) == ""} {
				setCursor "Select"
				set SharedEnv(Message) Select
				enableSelectionButtons
			}
		}
		Link -
		Node -
		Queue -
		Agent -
		Text {
			set SharedEnv(Sub-Cursor) ""
			#$SharedEnv(CurrentCanvas) delete SharedEnv(curline)
			#$SharedEnv(CurrentCanvas) delete selector
			$SharedEnv(CurrentCanvas) dctag
			set SharedEnv(Message) $SharedEnv(Cursor)
			#deselectAll
			#disableSelectionButtons
		}
		Select {
			set SharedEnv(Message) $SharedEnv(Cursor)
			#deselectAll
			#enableSelectionButtons
		}
	
		Print {
			#printRaise .print
			
			return
		}
	}
	focus $SharedEnv(CurrentCanvas)
}


Editor instproc saveFile {} {
	$self instvar SharedEnv scenarioname_
	set filename $scenarioname_

        catch {set f [open $filename w]}
        if { ! [info exists f] } {
             $self msgRaise .diagmsg "ERROR: Cannot open $filename fo r writing."
         } else {
			$self saveAll $filename
                        close $f
         }       

}

Editor instproc saveAsFile {} {
        $self instvar SharedEnv scenarioname_

        set filename [tk_getSaveFile \
                -filetypes {{{NS} {.nstcl}} {{eNAM} {.enam}}} \
                -parent .]

        if {"$filename" != ""} {
                catch {set f [open $filename w]}
                if { ! [info exists f] } {
                        $self msgRaise .diagmsg "ERROR: Cannot open $filename for writing."
                } else {
                        close $f
                	$self saveAll $filename
			set scenarioname_ $filename
			$SharedEnv(saveasfile) configure -text $filename
			update
                }
        }
}

Editor instproc saveAll {fn} {
	$self instvar netModel

	set fnsets [split $fn "."]
	set fnlength [llength $fnsets]
	set ftype [lindex $fnsets [expr $fnlength-1]]
	set ftype [string tolower $ftype]

	switch $ftype {
	    enam {
		$netModel saveasenam $fn
	
	    }	  

	    nstcl {
		$netModel saveasns $fn

	    }

	}
}

Editor instproc msgRaise {name message} {  
        $self instvar SharedEnv   

        set w ${name}   
        set SharedEnv(MsgReplace) $SharedEnv(CurrentCanvas)

        if {![winfo exists $name]} {
               $self  msgRequestor $name
        }
        $w.message configure -text "$message"
        wm deiconify $w
        focus $w
        
}

Editor instproc msgRequestor {name} {
        $self instvar SharedEnv

        set w ${name}   
                toplevel $w
#               wm transient $w .
                wm protocol $w WM_DELETE_WINDOW {set dummy 1}
        frame $w.f -borderwidth 0 -highlightthickness 0
        frame $w.texttop -borderwidth 0 -highlightthickness 0
        frame $w.textbottom -relief raised -bd 1
        label $w.message
        button $w.ok -text "Dismiss" -command "$self msgLower $w"
        pack $w.message -in $w.texttop -fill both -expand true
        pack $w.ok -in $w.textbottom -side left -padx 2m -pady 2m
        pack $w.texttop $w.textbottom -anchor sw -in $w -fill x -expand true
        pack $w.f -in $w
        wm withdraw $w
}

Editor instproc msgLower {name} {
        $self instvar SharedEnv

        set w ${name}
        wm withdraw $w
}











