# AC3D
# Copyright (c) 2004, Inivis Limited. All rights reserved.


# some tcl code to make the frames resizeable
# very flickery but it works

proc frame_press { win } {
global viewsetting 
global prefs_window_3d_width_percent
global prefs_window_3d_height_percent
global frame_move_horiz
global frame_move_vert
global frame

    if { $viewsetting != "all" } { return }

	set col white
	$frame(0) configure -bg $col
	$frame(1) configure -bg $col
	$frame(2) configure -bg $col
	$frame(3) configure -bg $col


    set rx [winfo rootx .views]
    set ry [winfo rooty .views]
    set x [winfo pointerx $win]
    set y [winfo pointery $win]
    set xd [expr $x-$rx]
    set yd [expr $y-$ry]

    set w [winfo width .views]
    set h [winfo height .views ]

    set w2 [expr 100 - int (($xd.0/$w.0) *100)]
    set h2 [expr 100 - int (($yd.0/$h.0) *100)]

    set ha [expr abs( $prefs_window_3d_width_percent - $w2) ]
    set va [expr abs( $prefs_window_3d_height_percent - $h2) ]

    set frame_move_horiz false
    set frame_move_vert false


    if { ( $ha < 5 ) && ($va < 5) } {
        set frame_move_horiz true
        set frame_move_vert true
    } elseif { ($ha < 5) } {
        set frame_move_horiz true
    } elseif { ($va < 5) } {
        set frame_move_vert true
    }
}

proc frame_drag {win} {
global prefs_window_3d_width_percent
global prefs_window_3d_height_percent
global viewsetting 
global frame_move_horiz
global frame_move_vert
global frame

    if { $viewsetting != "all" } { return }

    set rx [winfo rootx .views]
    set ry [winfo rooty .views]
    set x [winfo pointerx $win]
    set y [winfo pointery $win]
    set xd [expr $x-$rx]
    set yd [expr $y-$ry]

    set w [winfo width .views]
    set h [winfo height .views ]

    set w2 [expr 100 - int (($xd.0/$w.0) *100)]
    set h2 [expr 100 - int (($yd.0/$h.0) *100)]

    if { ($w2 > 5) && ($w2 < 95) } {
        if { ($frame_move_horiz) } {
            set prefs_window_3d_width_percent $w2
        }
    }
    if { ($h2 > 5) && ($h2 < 95) } {
        if { $frame_move_vert } {
            set prefs_window_3d_height_percent $h2
        }
    }

    configure_views
}

proc frame_release {win} {
global frame

set col grey
$frame(0) configure -bg $col
$frame(1) configure -bg $col
$frame(2) configure -bg $col
$frame(3) configure -bg $col

}


proc bind_frame_resize {} {
global frame

bind $frame(0) <1> { frame_press %W }
bind $frame(1) <1> { frame_press %W }
bind $frame(2) <1> { frame_press %W }
bind $frame(3) <1> { frame_press %W }

bind $frame(0) <B1-Motion> { frame_drag %W }
bind $frame(1) <B1-Motion> { frame_drag %W }
bind $frame(2) <B1-Motion> { frame_drag %W }
bind $frame(3) <B1-Motion> { frame_drag %W }

bind $frame(0) <ButtonRelease-1> { frame_release %W }
bind $frame(1) <ButtonRelease-1> { frame_release %W }
bind $frame(2) <ButtonRelease-1> { frame_release %W }
bind $frame(3) <ButtonRelease-1> { frame_release %W }

}


proc configure_views {} {
global viewsetting
global prefs_window_3d_width_percent
global prefs_window_3d_height_percent
global frame

    set w [winfo width .views]
    set h [winfo height .views ]
    set w2 [expr $w/2]
    set h2 [expr $h/2]


   set w3 [expr ($w/100.0)*$prefs_window_3d_width_percent]
   set h3 [expr ($h/100.0)*$prefs_window_3d_height_percent]
   set fw [expr $w-$w3]
   set fh [expr $h-$h3]

    switch $viewsetting {
        "all" {
            .views itemconfigure xy -width $fw -height $fh  
            .views coords xy 0 0

            .views itemconfigure zy -width $w3 -height $fh
            .views coords zy $fw 0

            .views itemconfigure xz -width $fw -height $h3
            .views coords xz 0 $fh

            .views itemconfigure xyz -width $w3 -height $h3 
            .views coords xyz $fw $fh
         }
       "xy" {
            .views coords zy 5000 5000 
            .views coords xz 5000 5000 
            .views coords xyz 5000 5000 
            .views coords xy 0 0 
            .views itemconfigure xy -width $w -height $h
        }
       "zy" {
            .views coords xy 5000 5000 
            .views coords xz 5000 5000 
            .views coords xyz 5000 5000 
            .views coords zy 0 0 
            .views itemconfigure zy -width $w -height $h
        }
       "xz" {
            .views coords zy 5000 5000 
            .views coords xy 5000 5000 
            .views coords xyz 5000 5000 
            .views coords xz 0 0 
            .views itemconfigure xz -width $w -height $h
        }
       "xyz" {
            .views coords zy 5000 5000 
            .views coords xy 5000 5000 
            .views coords xz 5000 5000 
            .views coords xyz 0 0 
            .views itemconfigure xyz -width $w -height $h
        }
    }

}


proc view_max_min { viewid winname } {
global viewsetting

	if { $viewsetting == "all" } {
		#  all windows are now displayed - set view to current window
		if { $viewid == 0 } {
		set viewsetting xy ; configure_views ; display_message "Front XY"
		} elseif {$viewid == 1 } {
			set viewsetting zy ; configure_views ; display_message "Side ZY"
		} elseif {$viewid == 2 } {
			set viewsetting xz ; configure_views ; display_message "Plan XZ"
		} elseif {$viewid == 3 } {
			set viewsetting xyz ; configure_views ; display_message "3D XYZ"
		}

	} else {
		# single view is currently displayed - go back to all
		set viewsetting all ; configure_views ; display_message "All views"
	}

}


proc panbind { widget viewwin } {
global ac_platform
if { $ac_platform == "Mac" } {
	set mod Command
} else {
	set mod Alt
}
# binding to make a widget control panning
	bind $widget <Button-1> "$widget configure -relief sunken; event generate $viewwin <$mod-ButtonPress-2> \
    -x %x -y %y -rootx %X -rooty %Y -button 2 -time %t"

	bind $widget <Button1-Motion> "event generate $viewwin <$mod-Button2-Motion> \
    -x %x -y %y -rootx %X -rooty %Y -time %t"

	bind $widget <ButtonRelease-1> "event generate $viewwin <$mod-ButtonRelease-2> \
    -x %x -y %y -rootx %X -rooty %Y -button 2 -time %t;  $widget configure -relief flat;"
}

proc zoombind { widget viewwin } {
# binding to make a widget button 1 control zoom

global ac_platform

if { $ac_platform == "Mac" } {
	set mod Command
} else {
	set mod Alt
}

	bind $widget <Button-1> " $widget configure -relief sunken; event generate $viewwin <$mod-ButtonPress-3> \
    -x %x -y %y -rootx %X -rooty %Y -button 3 -time %t"

	bind $widget <Button1-Motion> "event generate $viewwin <$mod-Button3-Motion> \
    -x %x -y %y -rootx %X -rooty %Y -time %t"

	bind $widget <ButtonRelease-1> "event generate $viewwin <$mod-ButtonRelease-3> \
    -x %x -y %y -rootx %X -rooty %Y -button 3 -time %t; $widget configure -relief flat;"
}

proc rotatebind { widget viewwin } {
# binding to make a widget control rotate
global ac_platform

if { $ac_platform == "Mac" } {
	set mod Command
} else {
	set mod Alt
}

	bind $widget <Button-1> "$widget configure -relief sunken; event generate $viewwin <$mod-ButtonPress-1> \
    -x %x -y %y -rootx %X -rooty %Y -button 1 -time %t"

	bind $widget <Button1-Motion> "event generate $viewwin <$mod-Button1-Motion> \
    -x %x -y %y -rootx %X -rooty %Y -time %t"

	bind $widget <ButtonRelease-1> "event generate $viewwin <$mod-ButtonRelease-1> \
    -x %x -y %y -rootx %X -rooty %Y -button 1 -time %t; $widget configure -relief flat"
}


proc ui_view_set_proj { viewid proj } {
global ViewCurrentProjection ViewSpinButton ViewConfigMenu ViewShowEditableButton ViewAAButton
global ViewConfigOrthMenuButton ViewConfig3dMenuButton

	ac3d view_set_projection $viewid $proj

	# this stores the current projection for a view (used in radio buttons on view menu)
	set ViewCurrentProjection($viewid) $proj

	if { $proj == 6 } {
		#puts "3d view"
		pack $ViewSpinButton($viewid) -side right
#		pack $ViewShowEditableButton($viewid) -side right

#		pack $ViewAAButton($viewid) -side right

#		$ViewConfigMenu($viewid) entryconfigure 0 -state disabled
#		$ViewConfigMenu($viewid) entryconfigure 1 -state normal
		pack forget $ViewConfigOrthMenuButton($viewid)
		pack $ViewConfig3dMenuButton($viewid) -side left
	} else {
		#puts "orth view"
		pack forget $ViewSpinButton($viewid)
#		pack forget $ViewShowEditableButton($viewid)
#		pack forget $ViewAAButton($viewid)
#		$ViewConfigMenu($viewid) entryconfigure 1 -state disabled
#		$ViewConfigMenu($viewid) entryconfigure 0 -state normal
 		pack forget $ViewConfig3dMenuButton($viewid)
		pack $ViewConfigOrthMenuButton($viewid) -side left
	}

}

proc ui_view_camera_set_walk { viewid what } {
global ViewCurrentWalk ViewSpinButton ViewZoomButton ViewPanButton

	ac3d view_camera_set_walk $viewid $what
	set ViewCurrentWalk($viewid) $what

	image create bitmap tilt -file "tcl/tilt.xbm"
	image create bitmap walk -file "tcl/walk.xbm"

	if { $what } {
		# walk mode
		$ViewSpinButton($viewid) configure -image walk
		set_balloon $ViewSpinButton($viewid) "hold down and drag mouse to move and turn"
		$ViewZoomButton($viewid) configure -image tilt
		set_balloon $ViewZoomButton($viewid) "hold down and drag mouse to tilt the view"
		set_balloon $ViewPanButton($viewid) "hold down and drag mouse to move up/down and sideways"
	} else {
		# spin mode
		$ViewSpinButton($viewid) configure -image spin
		set_balloon $ViewSpinButton($viewid) "hold down and drag mouse to spin this view"

		$ViewZoomButton($viewid) configure -image zoom
		set_balloon $ViewZoomButton($viewid) "hold down and drag mouse to zoom this view"
		set_balloon $ViewPanButton($viewid) "hold down and drag mouse to pan view"

	}
#note that SET_baloon changes the exiting text, calling add_balloon will add another - nasty

}


proc view_toggle_showeditable { viewid } {
# called when edit toggle is pressed
	set v [ac3d viewid_to_entity $viewid]
	set current [ac3d entity_get_value $v "showeditable" ]
	set newsetting [ expr !$current ]
	ac3d entity_set_value $v "showeditable" $newsetting
	ac3d view_redraw $viewid
}


# my own pulldown menu because tcl/tk on the mac replaces a menubutton with some slow native rubbish
# lovely and neat

proc ac_menubutton { name text menu } {

	proc ac_popup_menu { button popup } {
		set x [winfo rootx $button]
		set y [expr [winfo rooty $button] + [winfo height $button] ]

		tk_popup $popup $x $y
	}

    set lab [label $name -text $text -pady 0 -padx 1 -highlightthickness 00]
	bind $lab <1> "ac_popup_menu $lab $menu "

	# these special cols only work under windows
#	bind $lab <Enter> "%W configure -bg SystemActiveCaption; %W configure -fg SystemHighlightText;"
#	bind $lab <Leave> "%W configure -bg SystemButtonFace; %W configure -fg SystemButtonText;$menu unpost"

}





proc make_control_frame { name viewwindow viewid spin showmaxmin} {
# make the frame that goes at the top of a view window, containing control button and title
global tcl_platform ac_platform
global ViewCurrentProjection ViewCurrentWalk ViewCurrentAA
global ViewZoomButton ViewSpinButton ViewPanButton ViewConfigMenu ViewShowEditableButton ViewAAButton
global ViewConfigOrthMenuButton ViewConfig3dMenuButton

	set controlframe [frame $name -bd 0 -relief solid -padx 0 -pady 0 -highlightthickness 0] 

	# MAX/MIN
#	label $controlframe.mm -text Max/Min -borderwidth 1 -relief raised -highlightthickness 0

	if { $showmaxmin } {
		image create bitmap maxmin -file "tcl/maxmin.xbm"
		label $controlframe.mm -image maxmin -borderwidth 1 -relief raised -highlightthickness 0
		pack  $controlframe.mm -side right
		bind $controlframe.mm <Button-1> "$controlframe.mm configure -relief sunken"
		bind $controlframe.mm <ButtonRelease-1> "view_max_min $viewid $viewwindow; $controlframe.mm configure -relief raised"
		add_balloon $controlframe.mm "press to maximise or minimise this view \[space key\]"
	}


	label $controlframe.spacer4 -text " "
	pack $controlframe.spacer4 -side right



	# CLEAN TOGGLE
	image create bitmap clean -file "tcl/clean.xbm"
	set ViewShowEditableButton($viewid) \
	[checkbutton $controlframe.showeditable -width 12 -height 12 -indicatoron 0 -variable showeditable$viewid -text Clean -bd 1 -relief raised -highlightthickness 0 -command "view_toggle_showeditable $viewid" -image clean]
	$ViewShowEditableButton($viewid) configure -selectcolor [$ViewShowEditableButton($viewid) cget -background]
	


#	set ViewShowEditableButton($viewid) \
#	[switch_button $controlframe.showeditable  Clean "view_toggle_showeditable $viewid" showeditable$viewid ]

	pack  $ViewShowEditableButton($viewid) -side right
	add_balloon $ViewShowEditableButton($viewid) "Show clean image"


	label $controlframe.spacer -text " "
	pack $controlframe.spacer -side right

	# ZOOM
	image create bitmap zoom -file "tcl/zoom.xbm"
	set ViewZoomButton($viewid) [label $controlframe.zoom -image zoom -bd 1 -relief flat -highlightthickness 0]
	pack  $controlframe.zoom -side right
	zoombind $controlframe.zoom $viewwindow
	add_balloon $controlframe.zoom "hold down and drag mouse up/down to zoom view"


	# PAN
	image create bitmap pan -file "tcl/pan.xbm"
	set ViewPanButton($viewid) [label $controlframe.pan -image pan -text Pan -borderwidth 1 -relief flat -highlightthickness 0]
	pack  $controlframe.pan -side right
	panbind $controlframe.pan $viewwindow
	add_balloon $controlframe.pan "hold down and drag mouse to move (pan) this view"




	# SPIN 
	if { $spin} {
#	    label $controlframe.spacer2 -text " "
#	    pack $controlframe.spacer2 -side right

		image create bitmap spin -file "tcl/spin.xbm"
		set ViewSpinButton($viewid) [label $controlframe.rot -image spin -bd 1 -relief flat -highlightthickness 0]
		pack  $controlframe.rot -side right
		rotatebind $controlframe.rot $viewwindow
		add_balloon $controlframe.rot "hold down and drag mouse to spin view"
	}


#	label $controlframe.spacer3 -text " "
	#pack $controlframe.spacer3 -side right

	
	# antialias button
	#set ViewAAButton($viewid) [checkbutton $controlframe.aa -text "AA" -command "ac3d view_set_aa $viewid $\ViewCurrentAA($viewid)" -variable ViewCurrentAA($viewid)]
	#pack  $ViewAAButton($viewid) -side right




	# title
#	label $controlframe.lab -text $title -highlightthickness 0 
#	pack $controlframe.lab -ipadx 0 -ipady 0 -side left


# PROJFRONT (0)
# PROJLEFT (1)
# PROJTOP (2)
# PROJBACK (3)
# PROJRIGHT (4)
# PROJBOTTOM (5)
# PROJ3D (6)




	set mbar [frame $controlframe.mbar]

    # nasty hack to stop native Mac menu thingy truncating the label
    set camlabel "Camera"
    if { $ac_platform == "Mac" } { set camlabel "$camlabel  " }

#    menubutton $mbar.menu -text $camlabel -menu $mbar.menu.$viewid -pady 0 -padx 1
ac_menubutton $mbar.menu $camlabel $mbar.menu.$viewid 

    menu $mbar.menu.$viewid -tearoff 0
	$mbar.menu.$viewid add radiobutton -label "Front" -command "ui_view_set_proj $viewid 0" -variable ViewCurrentProjection($viewid) -value 0
	$mbar.menu.$viewid add radiobutton -label "Back" -command "ui_view_set_proj $viewid 3" -variable ViewCurrentProjection($viewid)  -value 3
	$mbar.menu.$viewid add radiobutton -label "Left" -command "ui_view_set_proj $viewid 1" -variable ViewCurrentProjection($viewid)  -value 1
	$mbar.menu.$viewid add radiobutton -label "Right" -command "ui_view_set_proj $viewid 4" -variable ViewCurrentProjection($viewid)  -value 4
	$mbar.menu.$viewid add radiobutton -label "Top" -command "ui_view_set_proj $viewid 2" -variable ViewCurrentProjection($viewid)  -value 2
	$mbar.menu.$viewid add radiobutton -label "Bottom" -command "ui_view_set_proj $viewid 5" -variable ViewCurrentProjection($viewid)  -value 5
	$mbar.menu.$viewid add radiobutton -label "3D" -command "ui_view_set_proj $viewid 6" -variable ViewCurrentProjection($viewid)   -value 6


	if {$tcl_platform(platform) == "windows" } {
		$mbar.menu.$viewid add separator 
		$mbar.menu.$viewid add command -label "Copy Image to Windows Clipboard" -command "update; ac3d view_copy_to_clipboard $viewid"
	}

		
	if {$ac_platform == "Mac" } {
		$mbar.menu.$viewid add separator 
		$mbar.menu.$viewid add command -label "Copy Image to Mac Clipboard" -command "update; ac3d view_copy_to_clipboard $viewid"
	}


	add_menu_balloons $mbar.menu.$viewid { 
			"orth view from front" \
			"orth view from back" \
			"orth view from left" \
			"orth view from right" \
			"orth view from top" \
			"orth view from bottom" \
			"3D perspective view" "" "Copy image to Windows clipboard"}

    set viewlabel "View"
    if { $ac_platform == "Mac" } { set viewlabel "$viewlabel  " }

    ac_menubutton $mbar.menu2 $viewlabel $mbar.menu2.menu 
    menu $mbar.menu2.menu -tearoff 0
	$mbar.menu2.menu add command -label "Fit all" -command "ac3d view_fit_all $viewid"
	$mbar.menu2.menu add command -label "Fit Selection" -command "ac3d view_fit_selected $viewid" -accelerator f
	$mbar.menu2.menu add command -label "Look at Selection" -command "ac3d view_goto_selected $viewid"
	$mbar.menu2.menu add separator 
	$mbar.menu2.menu add command -label "Reset" -command "ac3d view_reset $viewid"

	add_menu_balloons $mbar.menu2.menu {
		"position viewpoint to view whole model"
		"position viewpoint to view the selection"
		"face to view centre the selection"
		""
		"reset viewpoint to default position"
		}

    set orthlabel "Orth"
    if { $ac_platform == "Mac" } { set orthlabel "$orthlabel  " }

    ac_menubutton $mbar.orthmenu $orthlabel $mbar.orthmenu.orth
	set ViewConfigOrthMenuButton($viewid) $mbar.orthmenu
	menu $mbar.orthmenu.orth -tearoff 0
	set ViewConfigOrthMenu($viewid) $mbar.orthmenu.orth
	$ViewConfigOrthMenu($viewid) add command -label "Set Background Image..." -command "ac3d file_select_background_image $viewid"
	$ViewConfigOrthMenu($viewid) add command -label "Clear Background Image" -command "ac3d view_clear_background_image $viewid"

	add_menu_balloons $ViewConfigOrthMenu($viewid) {
		"choose a picture to put on the background of the view"
		"remove the current background image"
		}

    set label3d "3D"
    if { $ac_platform == "Mac" } { set label3d "$label3d  " }

    ac_menubutton $mbar.3dmenu $label3d $mbar.3dmenu.3d 
	set ViewConfig3dMenuButton($viewid) $mbar.3dmenu
	menu $mbar.3dmenu.3d -tearoff 0
	set ViewConfig3dMenu($viewid) $mbar.3dmenu.3d
	$ViewConfig3dMenu($viewid) add radiobutton -label "Spin" -command "ui_view_camera_set_walk $viewid 0" -variable ViewCurrentWalk($viewid) -value 0 -accelerator 1
	$ViewConfig3dMenu($viewid) add radiobutton -label "Walk" -command "ui_view_camera_set_walk $viewid 1" -variable ViewCurrentWalk($viewid) -value 1 -accelerator 2
	$ViewConfig3dMenu($viewid) add separator 
	$ViewConfig3dMenu($viewid) add checkbutton -label "Anti-alias" -command "ac3d view_set_aa $viewid $\ViewCurrentAA($viewid)" -variable ViewCurrentAA($viewid)
	$ViewConfig3dMenu($viewid) add separator 
	$ViewConfig3dMenu($viewid) add checkbutton -label "Nav Select" -variable prefs_nav_select
	$ViewConfig3dMenu($viewid) add separator 
	$ViewConfig3dMenu($viewid) add command -label "FOV..." -command "dialog_FOV $viewid"

	pack $mbar.menu $mbar.menu2 $mbar.orthmenu -side left


	add_menu_balloons $ViewConfig3dMenu($viewid) {
		"mouse and arrow keys spin view"
		"mouse 'flys' and keys walk"
		""
		"Smooth image (warning - slows down redraw)"
		""
		"dragging mouse outside selection navigates"
		""
		"change the 3D camera's field of view"
		}

	pack $mbar -side left
#	tk_menuBar .mbar $mbar.menu $mbar.menu2 $mbar.config

	return $controlframe

	#  need to disable some menu items for 3d window e.g. background im,ages
	# disable some items for orth window e.g. fov

}


proc show_control_frames { } {
global controlframe ToglWinName

	pack forget $controlframe(0)
	pack forget $ToglWinName(0)
	pack forget $controlframe(1)
	pack forget $ToglWinName(1)
	pack forget $controlframe(2)
	pack forget $ToglWinName(2)
	pack forget $controlframe(3)
	pack forget $ToglWinName(3)

	set side top

	pack $controlframe(0) -side $side -fill x
	pack $ToglWinName(0) -side $side -fill both -expand 1
	pack $controlframe(1) -side $side -fill x
	pack $ToglWinName(1) -side $side -fill both -expand 1
	pack $controlframe(2) -side $side -fill x
	pack $ToglWinName(2) -side $side -fill both -expand 1
	pack $controlframe(3) -side $side -fill x
	pack $ToglWinName(3) -side $side -fill both -expand 1

}

proc hide_control_frames { } {
global controlframe

	pack forget $controlframe(0)
	pack forget $controlframe(1)
	pack forget $controlframe(2)
	pack forget $controlframe(3)
}




proc reconfigure_view_controls { } {

global prefs_show_view_controls

	if { $prefs_show_view_controls } {
		show_control_frames
	} else {
		hide_control_frames
	}
}


# make a single view window
proc make_view { viewid parent proj showmaxmin } {
global controlframe
global frame ToglWinName
global ViewCurrentProjection ViewCurrentWalk
global ViewWindowList ViewCurrentAA

	# define the border type of each viewframe
	set frame_relief sunken

	set ViewCurrentProjection($viewid) $proj
	set ViewCurrentWalk($viewid) 0
	set ViewCurrentAA($viewid) 0


	frame $parent.$viewid -bd 2 -relief $frame_relief 
	frame $parent.$viewid.f 

	pack $parent.$viewid -fill both -expand 1

	set controlframe($viewid) [ make_control_frame $parent.$viewid.f.controlframe $parent.$viewid.f.win  $viewid true $showmaxmin]
	pack $controlframe($viewid) -side top -fill x


	pack $parent.$viewid.f  -fill both -expand 1
	togl $parent.$viewid.f.win -rgba true -double true -depth true -accum true
	pack $parent.$viewid.f.win  -fill both -expand 1
	set frame($viewid) $parent.$viewid
	set ToglWinName($viewid) $parent.$viewid.f.win

	lappend ViewWindowList $ToglWinName($viewid)

	ac3d view_openglify $ToglWinName($viewid) $viewid $proj

	bind $frame($viewid) <Enter> "focus [winfo toplevel $frame($viewid)]"
	
	ui_view_set_proj $viewid $proj

	do_bindings $ToglWinName($viewid)

}

proc make_additional_view { } {

	set id [ac3d views_get_new_id]

	set top .view$id
	new_toplevel $top "AC3D View"

	# make a view, false is for not having a max/min icon
	make_view $id $top 6 false

	#additional windows need mnore work - binding to each view etc

	wm protocol $top WM_DELETE_WINDOW "ac3d view_destroy $id; destroy $top"
}



proc do_bindings { window } {
global prefs_mousewheel_factor

	set toplev [ winfo toplevel $window ]

	bind $toplev <MouseWheel> {
#puts mousewheel

# these didn't give correct values on the Mac
#		set x %X
#		set y %Y

		# these work on the Mac
		set x [winfo pointerx %W]
		set y [winfo pointery %W]


		set d %D
		set w %W
		set over [winfo containing $x $y]

		# warning - constant!
		set z [expr $d/$prefs_mousewheel_factor]
#	puts "mousewheel $x $y $d over window: '$over' w: $w "

		set view [ac3d view_window_name_to_viewid $over] 

		if { $view != -1 } {
			ac3d zoomview $view $z
		}

		# zoom the uv editor if necc
		catch {	if {$over == $UI(uveditview) } { uvedit_zoom $z } }
	}



	# stop window delete winodw message from alt-f4 causing a keypress
	bind $toplev <Alt-F4> {  }

	bind $toplev <KeyPress> {
		set x %X
		set y %Y
		set d %D
		set over [winfo containing $x $y]
#		puts "TCLTK key $over Keycode: %k   KeySym: %K %s" 

		set view [ac3d view_window_name_to_viewid $over] 


#set test [ac3d viewid_to_entity $view]
#puts "TEST ENTITY $test"
#set w [ac3d entity_get_value $test "window_width" ]
#puts "value $w"




		if { $view != -1 } {
			set key %k
			set keysym %K
			if { $keysym == "space" } {
				 view_max_min $view $over
			} else {
				ac3d keypresswin $over %K %s
			}
		} else {
#			puts "key not over a view"

		}
	}

	bind_keys $toplev

}




proc make_views {} {
global viewsetting copycontext
global frame ToglWinName
#global prefs_share_opengl_contexts
#global prefs_window_label_xyz prefs_window_label_xy prefs_window_label_xz prefs_window_label_zy
global controlframe
global prefs_proj0 prefs_proj1 prefs_proj2 prefs_proj3



	make_view 0 .views $prefs_proj0 true
	make_view 1 .views $prefs_proj1 true
	make_view 2 .views $prefs_proj2 true
	make_view 3 .views $prefs_proj3 true

#make_additional_view




# PROJFRONT (0)
# PROJLEFT (1)
# PROJTOP (2)
# PROJBACK (3)
# PROJRIGHT (4)
# PROJBOTTOM (5)
# PROJ3D (6)



	reconfigure_view_controls

	set viewsetting all


	.views create window 0 0 -anchor nw -window $frame(0) -tags  xy
	.views create window 400 0 -window $frame(1) -anchor nw -tags zy
	.views create window 0 400 -window $frame(2) -anchor nw -tags xz 
	.views create window 400 400  -window $frame(3) -anchor nw -tags xyz

	bind .views <Configure> { configure_views }

	#bind all <Escape> {ac3d clear_selection}




	bind_frame_resize


}


#define PROJFRONT (0)
#define PROJLEFT (1)
#define PROJTOP (2)
#define PROJBACK (3)
#define PROJRIGHT (4)
#define PROJBOTTOM (5)
#define PROJ3D (6)


proc menu_configure_views { } {
global prefs_proj0 prefs_proj1 prefs_proj2 prefs_proj3

	set top .configviews

	if ![winfo exists $top] {
		new_toplevel $top "Configure views"

		catch {namespace import combobox::*}

		set p { front left top back right bottom 3d }

		set wid 6

		set p0 [lindex $p $prefs_proj0 ]
		set p1 [lindex $p $prefs_proj1 ]
		set p2 [lindex $p $prefs_proj2 ]
		set p3 [lindex $p $prefs_proj3 ]

		combobox $top.p0 -editable false -textvariable p0 -width $wid
		eval $top.p0  list insert end $p

		combobox $top.p1 -editable false -textvariable p1 -width $wid
		eval $top.p1  list insert end $p

		combobox $top.p2 -editable false -textvariable p2 -width $wid
		eval $top.p2  list insert end $p

		combobox $top.p3 -editable false -textvariable p3 -width $wid
		eval $top.p3  list insert end $p

		$top.p0 select $prefs_proj0
		$top.p1 select $prefs_proj1
		$top.p2 select $prefs_proj2
		$top.p3 select $prefs_proj3

		grid $top.p0 -column 1 -row 1
		grid $top.p1 -column 2 -row 1
		grid $top.p2 -column 1 -row 2
		grid $top.p3 -column 2 -row 2

		button $top.ok -text "Apply" -command { 
			set p { front left top back right bottom 3d }

			set np0 [lsearch $p $p0 ]
			set np1 [lsearch $p $p1 ]
			set np2 [lsearch $p $p2 ]
			set np3 [lsearch $p $p3 ]

			set prefs_proj0 $np0; 
			set prefs_proj1 $np1; 
			set prefs_proj2 $np2; 
			set prefs_proj3 $np3;
			ui_view_set_proj 0 $np0
			ui_view_set_proj 1 $np1
			ui_view_set_proj 2 $np2
			ui_view_set_proj 3 $np3
		} 
		add_balloon $top.ok "Use this configuration for the views.  The config specified here will be saved when AC3D exits."

		button $top.cancel -text "Close" -command "wm withdraw $top"

		button $top.def -text "AC3D default" -command "\
			$top.p0 select 0; \
			$top.p1 select 1; \
			$top.p2 select 2; \
			$top.p3 select 6; "
		add_balloon $top.def "Set the view projections to AC3D's defaults"

	#	button $top.def2 -text "Third angle" -command "\
	#		$top.p0 select 2; \
	#		$top.p1 select 6; \
	#		$top.p2 select 0; \
	#		$top.p3 select 4; "

		grid $top.def -column 0 -row 2 -padx 10
	#	grid $top.def2 -column 0 -row 3

		grid $top.ok -column 1 -row 4 -pady 10
		grid $top.cancel -column 2 -row 4 -pady 10

		centre_window_on_screen $top
	}
	
	wm deiconify $top

}



proc acbind { w key command} {
global ac_platform

	if { $ac_platform != "Mac" } {
		bind $w $key $command
		return
	}

	set pos [string first Control $key]
	if { $pos == -1 } {
		bind $w $key $command
	} else {
		set nk [string replace $key $pos [expr $pos + 6] "Command"]
		bind $w $nk $command
	}
}


proc bind_keys { window } {
global ac_platform

	set top [ winfo toplevel $window ]

	# file menu
	if { $ac_platform == "Windows" } {
		acbind $top <Control-p> "dialog_windows_print"
	}

	 acbind $top <Control-n> "menu_clear"
     acbind $top <Control-o> { menu_open "" }
# used on Mac for Minimise     acbind $top <Control-m> "menu_merge"

     acbind $top <Control-i> "menu_import"
     acbind $top <Control-s> "menu_save_last"

    if { $ac_platform == "Mac" } {
        acbind $top <Command-q> "menu_quit"

#buggy - after iconise, app is dead to events
#		acbind $top <Command-m> "wm state . iconic"

    }


# KEY BINDINGS
# removed any single key press binding becasue they interfered with
# typing in the object name window. (code moved to keys.c)

# standard bindings for Entry widget but with break added so that
# the event doesn't permiate to the toplevel UI
# this was done because cutting and pasting into the object name or entry fields 
# caused AC3D cut.paste events to occur.
# updated for tk 8.4 (taken from Entry.tcl and break added at ends

	bind Entry <<Cut>> {
		if {![catch {tk::EntryGetSelection %W} tk::Priv(data)]} {
		clipboard clear -displayof %W
		clipboard append -displayof %W $tk::Priv(data)
		%W delete sel.first sel.last
		unset tk::Priv(data)
		}
		break
	}
	bind Entry <<Copy>> {
		if {![catch {tk::EntryGetSelection %W} tk::Priv(data)]} {
		clipboard clear -displayof %W
		clipboard append -displayof %W $tk::Priv(data)
		unset tk::Priv(data)
		}
		break
	}
	bind Entry <<Paste>> {
		global tcl_platform
		catch {
		if {[string compare [tk windowingsystem] "x11"]} {
			catch {
			%W delete sel.first sel.last
			}
		}
		%W insert insert [::tk::GetSelection %W CLIPBOARD]
		tk::EntrySeeInsert %W
		}
		break
	}


	# edit menu
	acbind $top <Control-x> "ac3d clipboard_cut ; break"
	acbind $top <Control-c> "ac3d clipboard_copy ; break"
	acbind $top <Control-v> "ac3d clipboard_paste ; break"
	acbind $top <Control-z> "ac3d undo"
	acbind $top <Control-Z> "ac3d redo"
	acbind $top <Control-y> "ac3d redo"

	acbind $top <Control-a> "ac3d select_all"
	acbind $top <Control-d> "ac3d duplicate"


	# view menu
	# f will fit the selction to a single view (key code in main program)
	# control f fits the selection to all views
	# control shift f fits everything to all views

     acbind $top <Control-f> "ac3d fit_selected_all"
	 acbind $top <Control-g> "ac3d goto_selected_all"
     acbind $top <Control-F> "ac3d fit_all"



	# OBJECT MENU
	acbind $top <Control-V> { ac3d optimize }
	acbind $top <Control-M> { ac3d object_merge ; ac3d redraw_all}
#	acbind $top <Control-F> { ac3d object_fragment ; ac3d redraw_all}
	acbind $top <Control-S> { ac3d object_subdivision }


	# SURFACE MENU
	acbind $top <Control-D> { ac3d surface_subdivide }
	acbind $top <Control-O> { ac3d surface_change_vertex_order }
	acbind $top <Control-N> { ac3d surface_flip_normals }
	acbind $top <Control-H> { ac3d surface_make_hole }
	acbind $top <Control-T> { ac3d surface_triangulate }
	acbind $top <Control-X> { ac3d surface_create_object }


	# VERTEX MENU
	acbind $top <Control-S> { ac3d createsurface }
	acbind $top <Control-t> {if {$select_mode == "vertex" || $select_mode == "surface" } {ac3d snaptogether} }
	acbind $top <Control-L> { ac3d surface_slice }
	acbind $top <Control-I> { ac3d insert_vertex } 
	acbind $top <Control-e> { if {$select_mode == "vertex" || $select_mode == "surface" }  {ac3d extrude_edges }  }
	acbind $top <Control-r> { if {$select_mode == "vertex" || $select_mode == "surface" }  {ac3d create_quad }  }


	# TOOLS MENU
	acbind $top <F6> { menu_info }
	acbind $top <F7> { menu_render }
	acbind $top <F8> { menu_hier }
	acbind $top <F9> { edit_dive_data }
	acbind $top <F10> { menu_uveditor }
	acbind $top <F11> { menu_replicator }
	acbind $top <F12> { ttfont_dialog }


	acbind . <F1> { set viewsetting xy ; configure_views ; display_message "changed view"}
	acbind . <F2> { set viewsetting zy ; configure_views ; display_message "changed view"}
	acbind . <F3> { set viewsetting xz ; configure_views ; display_message "changed view"}
	acbind . <F4> { set viewsetting xyz ; configure_views ; display_message "changed view"}
	acbind . <F5> { set viewsetting all ; configure_views ; display_message "All views"}

	acbind $top <Escape> { set escape_pressed 1 }
}
















