#!./avview_shell
#
# The line above is only for testing.. You should really start avview
# with start_avview
#
#
#     avview preliminary version
#
#       (C) Vladimir Dergachev 2001-2003
#       
#       GNU Public License
#       

proc print_help {} {
puts stderr {
Usage:
	start_avview [options]
	
Options:
	--help             		print this message
	--control-screen=display        display control windows on specified 
					display
	--screen-size=WxH		start TV window with size WxH
	--geometry=geometry		specify TV window geometry, using
					usual X11 notation	
  	--lircconf=files		LIRC config file name
}
}

foreach {variable value} {
	debug 0
	show_control_window 0
	file_save_path "."
	current_capture_filename "test3.avi"
	fullscreen_mode "false"
	remember_fullscreen_state "false"
	always_start_fullscreen "false"
	display_setup_window_on_startup "false"
	current_v4l_mode "double-interpolate"
	v4l_capture_on "false"
	current_video_codec "MPEG-1"
	current_audio_codec "MPEG-2"
	current_v4l_rrate "one half"
	current_v4l_device "none"
	current_av_format "MPEG"
	current_port "none"
	current_encoding "none"
	current_encoding_name "none"
	current_table "none"
	current_table_name "none"
	current_channel "none"
	current_connector "none"
	current_alsa_device1 "none"
	use_physical_screen_size "true"
	aspect_ratio {4 3}
	port_grabbed "false"
	screen_off "false"
	dpms_off_on_fullscreen_power_off "false"
	disable_fullscreen_switching "false"
	message_visible_secs	14
	save_settings_on_exit	"unset"
	warn_about_missing_km	"true"
	control_screen ""
	startup_script ""
	mute_when_minimized   "false"
	transparent_when_minimized "true"
	transparency_ratio	200
	is_minimized		"false"
	user_encoding_themes	{}
	} {
	global $variable
	set $variable $value
	}

foreach option $argv {
	switch -glob -- $option {
		"--help"  { print_help ; exit}
		"--control-screen=*" { 
			regexp -- {--control-screen=([^ ]+)} $option {} control_screen
			puts "control_screen=$control_screen"
			}
		"--screen-size=*" {
			regexp -- {--screen-size=([0-9]+)x([0-9]+)} $option {} width height
			append startup_script "set_video_window_size $width $height\n"
			}
		"--geometry=*" {
			regexp -- {--geometry=(.+)} $option {} geometry
			append startup_script "wm geometry . \"$geometry\"\n"
			}
		"--lircconf=*" {
			global lirc_config_files
			regexp -- {--lircconf=(.+)} $option {} files
 			set lirc_config_files [split $files ,]
			}
		"--lircconf=*" {
			global lirc_config_files
			regexp -- {--lircconf=(.+)} $option {} files
 			set lirc_config_files [split $files ,]
			}
		}
	}



global TABLE_LIST
set TABLE_LIST [freq_get_table_list]

proc skip_args3 { a b c } {
}

proc no_editing {a} {
if { $a < 0 } { return 1 }
return 0
}


foreach file {xmisc.scp tree.scp setup.scp themes.scp alsa.scp
	v4l.scp xv.scp channel_scan.scp ffmpeg.scp 
	video_device.scp diag.scp bindings.scp vbi.scp km.scp
	lirc.scp} {
	source $avview_directory/$file
	}


global VIDEO_WINDOW

set VIDEO_WINDOW .video

destroy .video


. configure -width 320 -height 240 -background black

#frame .video -background #102030
eval canvas .video [get_settings .video AVview]
.video configure -borderwidth 0
place .video -relx 0.0 -rely 0.0 -relwidth 1.0 -relheight 1.0 -anchor nw

bind . <Configure> place_video_window
bind . <Unmap> unmap_video_window
bind . <Map> map_video_window


proc place_video_window {} {
global aspect_ratio use_physical_screen_size
set h [winfo height .]
set w [winfo width .]
set rw 1.0
set rh 1.0
catch {
	if { $use_physical_screen_size } {
		set a_x [expr ([lindex $aspect_ratio 0]*[winfo screenwidth .]*1.0)/[winfo screenmmwidth .]]
		set a_y [expr ([lindex $aspect_ratio 1]*[winfo screenheight .]*1.0)/[winfo screenmmheight .]]
		} {
		set a_x [lindex $aspect_ratio 0]
		set a_y [lindex $aspect_ratio 1]
		}
	if { $a_x*$h>=$a_y*$w } {
		set rh [expr (1.0*$a_y*$w)/($a_x*$h)]
		set rw 1.0
		} {
		set rw [expr (1.0*$a_x*$h)/($a_y*$w)]
		set rh 1.0
		}
	}
place configure .video -relx [expr (1.0-$rw)/2.0] -rely [expr (1.0-$rh)/2.0] \
	-relw $rw -relh $rh -anchor nw
}

proc unmap_video_window {} {
global is_minimized mute_when_minimized transparent_when_minimized transparency_ratio \
	fullscreen_mode mute_index overlay_alpha_index alpha_mode_index previous_mute_value \
	VIDEO_WINDOW current_port in_set_fullscreen

if { $is_minimized || $fullscreen_mode || $in_set_fullscreen || ([wm state .]=="normal")} { return }
set is_minimized true

if { $mute_when_minimized && ($mute_index >= 0 )} { 
	catch {
		set previous_mute_value [xv_getportattribute $VIDEO_WINDOW $current_port "XV_MUTE"]
		set_attribute_by_index $mute_index 1
		}
	}
if { $transparent_when_minimized && ($overlay_alpha_index >=0 ) && ($alpha_mode_index >= 0) } {
	set_attribute_by_index $overlay_alpha_index $transparency_ratio
	set_attribute_by_index $alpha_mode_index 1
	}
}

proc map_video_window {} {
global is_minimized mute_when_minimized transparent_when_minimized transparency_ratio \
	fullscreen_mode mute_index overlay_alpha_index alpha_mode_index previous_mute_value \
	VIDEO_WINDOW current_port in_set_fullscreen

if { (! $is_minimized) || $fullscreen_mode || $in_set_fullscreen } { return }
set is_minimized false

if { $mute_when_minimized && ($mute_index >= 0 )} { 
	catch {
		set_attribute_by_index $mute_index $previous_mute_value
		}
	unset previous_mute_value
	}

if { $transparent_when_minimized && ($overlay_alpha_index >=0 ) && ($alpha_mode_index >= 0) } {
	set_attribute_by_index $overlay_alpha_index 255
	set_attribute_by_index $alpha_mode_index 0
	}
}

frame .video.onscreen_display -background [.video cget -background]
eval .video.onscreen_display configure [get_settings .video.onscreen_display AVview]
place .video.onscreen_display -relx 0.05 -rely 0.05 -anchor nw


if { $control_screen != "" } {
	toplevel .controlwin -screen "$control_screen" 
	} {
	toplevel .controlwin
	}
wm withdraw .controlwin
eval .controlwin configure [get_settings .controlwin AVview]

eval frame .controlwin.control [get_settings .controlwin.control]
eval frame .controlwin.allattributes [get_settings .controlwin.allattributes]
eval frame .controlwin.capture [get_settings .controlwin.capture]
eval frame .controlwin.alsamixer [get_settings .controlwin.alsamixer]

set c .controlwin.control

global current_port_menu
global current_encoding_menu

eval label $c.encodingl -text {{Encoding: }} [get_settings $c.encodingl label AVview]
set current_encoding_menu [tk_optionMenu $c.encoding_optionmenu current_encoding_name  none]
eval $c.encoding_optionmenu configure [get_settings $c.encoding_optionmenu AVview]
eval $current_encoding_menu configure [get_settings $current_encoding_menu AVview menu]
$current_encoding_menu delete 0 end
grid $c.encodingl $c.encoding_optionmenu -sticky news
grid configure $c.encodingl -sticky nws

eval label $c.channell -text {{Channel: }} [get_settings $c.channell label AVview]
set current_channel_menu [tk_optionMenu $c.channel_optionmenu current_channel none]
eval $c.channel_optionmenu configure [get_settings $c.channel_optionmenu AVview]
eval $current_channel_menu configure [get_settings $current_channel_menu AVview menu]
$current_channel_menu delete 0 end
grid $c.channell $c.channel_optionmenu -sticky news
grid configure $c.channell -sticky nsw

eval checkbutton $c.xv_attr -variable attributes_window -text {{Xv Attributes}} -indicatoron false -onvalue true -offvalue false [get_settings $c.xv_attr checkbutton AVview]
grid $c.xv_attr -row 0 -column 2 -padx 2 -pady 2 -sticky ew
eval checkbutton $c.capture_attr -variable capture_window -text {{Capture controls}} -indicatoron false -onvalue true -offvalue false [get_settings $c.capture_attr checkbutton AVview]
grid $c.capture_attr -row 0 -column 3 -padx 2 -pady 2
eval checkbutton $c.alsa_attr -variable alsa_window -text {{ALSA mixer}} -indicatoron false -onvalue true -offvalue false [get_settings $c.alsa_attr checkbutton AVview]
grid $c.alsa_attr -row 0 -column 4 -padx 2 -pady 2

eval button $c.setup_window -text {{Setup window}} -command create_setup_window [get_settings  $c.setup_window button AVview]
grid $c.setup_window -row 1 -column 2 -padx 2 -pady 2

grid $c - - -sticky nw
grid .controlwin.allattributes -column 0 -row 1 -rowspan 2 -sticky news -pady 2 
grid .controlwin.capture -column 1 -row 1 -rowspan 1 -sticky new -pady 2 
grid columnconfigure .controlwin 0 -weight 0
grid columnconfigure .controlwin 1 -weight 0
grid columnconfigure .controlwin 2 -weight 0
#grid columnconfigure .controlwin 2 -weight 1
grid rowconfigure .controlwin 2 -weight 1
#grid rowconfigure .controlwin 0 -weight 1
grid .controlwin.alsamixer -column 2 -row 1 -rowspan 2 -sticky news -pady 2 

update
update idletasks

xmisc_hidecursor .
xmisc_hidecursor .video


proc show_control_window_proc {} {
global show_control_window
if { $show_control_window } {
	wm deiconify .controlwin
	} {
	if { [winfo screen .controlwin] != [winfo screen . ] } {
		set ans [tk_dialog .controlwin.withdraw_question "Hide main control window ?" \
			"The main control window is displayed on the monitor different from main viewer window. If you hide it you will only be able to restore it from the main viewer window. Perhaps you would prefer to iconify control window?" "" 0 "Iconify" "Hide" "Never mind" ]
		update
		update idletasks
		switch "$ans" \
			"0"  { after idle {wm iconify .controlwin ; set show_control_window 1 } } \
			"1"  { after idle { wm withdraw .controlwin } } \
			"2"  { set show_control_window 1 }
		update
		} {
				wm withdraw .controlwin 
		}
	}
}

proc hide_cursor_timer { window } {
global hct_$window
incr hct_$window -1
if { [set hct_$window] < 1 } {
	incr hct_$window -1
	xmisc_hidecursor $window
	} {
	after 500 "hide_cursor_timer $window"
	}
}

proc set_hiding_cursor {window cursor} {
global hct_$window
set hct_$window -1
xmisc_hidecursor $window
bind $window <Motion> "global hct_$window;\
		  $window configure -cursor $cursor ; \
		  if { \[set hct_$window\] < 0 } {after 500 \"hide_cursor_timer $window\"} ;\
		 set hct_$window 4"
}

set_hiding_cursor .video left_ptr

proc set_channel_table {name1 name2 op} {
global TABLE_LIST
global current_table
global current_table_name
global current_channel_menu
global current_channel
set current_table [lsearch -exact $TABLE_LIST "$current_table_name"]
if { $current_table < 0 } { return }
set CHANNEL_LIST [freq_get_channel_list $current_table]
$current_channel_menu delete 0 end
foreach channel $CHANNEL_LIST {	
	$current_channel_menu add radiobutton -label "$channel" -value "$channel" -variable current_channel
 	}
set num_channels [llength $CHANNEL_LIST]
for {set i 16} { $i < $num_channels } {incr i 16 } {
	$current_channel_menu entryconfigure $i -columnbreak 1
	}
reflect_favorite_channels
}

proc set_channel {a b c} {
global current_table
global current_channel
if { $current_table < 0 } { return }
set CHANNEL_LIST [freq_get_channel_list $current_table]
global channel_freq
set channel_freq [freq_get_channel_value $current_table [lsearch -exact $CHANNEL_LIST "$current_channel" ]]
flash_message " [get_station_name $current_channel true] "
update
on_attribute_change XV_FREQ channel_freq a b
vbi_new_channel primary
for { set i 1 } { $i <= 8 } { incr i } {
	.video_menu.cc_menu entryconfigure $i -foreground black -label "$i"
	}
.video delete cc_text
}

proc display_video {} {

global VIDEO_WINDOW current_port current_encoding port_grabbed

if { $current_port == "none" } { return }
if { $current_encoding < 0 } { return }
if { ([lsearch -exact [xv_adaptor_type $VIDEO_WINDOW [find_port_adaptor $current_port] ] video] == -1) } { 
	flash_message "This port is not TV-in capable"
	return 
	}

set port_size [xv_port_encoding_size $VIDEO_WINDOW $current_port $current_encoding]

xv_setportattribute $VIDEO_WINDOW $current_port "XV_COLORKEY" [xv_getwindowbackgroundpixel $VIDEO_WINDOW]

if { ! $port_grabbed } {
	if { [xv_grabport $VIDEO_WINDOW $current_port] } {
		set port_grabbed true
		} {
		flash_message "Video port $current_port is being used\nby another program"
		return 		
		}
	}

xv_putvideo $VIDEO_WINDOW $current_port 0 0 [expr [lindex $port_size 0]-1] [expr [lindex $port_size 1]-1]
}

proc stop_video {} {
global VIDEO_WINDOW
global current_port

if { $current_port == "none" } { return }

xv_stopvideo $VIDEO_WINDOW $current_port
}

proc set_encoding {name1 name2 op} {
global current_encoding_name current_encoding current_port current_video_rate
global current_table_name current_table VIDEO_WINDOW current_connector


if { $current_port == "none" } { return }

set ENCODINGS [xv_port_encodings $VIDEO_WINDOW $current_port]
set current_encoding [lsearch $ENCODINGS $current_encoding_name]
if { ($current_encoding >= 0) } {
	on_attribute_change XV_ENCODING current_encoding a b
	switch -glob -- $current_encoding_name \
		"*pal*" {
			set current_video_rate 50.00
			} \
		"*secam*" {
			set current_video_rate 50.00
			} \
		"*ntsc*" {
			set current_video_rate 59.94
			}			
	switch -glob -- $current_encoding_name {
		"*tuner*"   { set current_connector "tuner" }
		"*composite*"   { set current_connector "composite" }
		"*svideo*"   { set current_connector "svideo" }
		default    { set current_connector "none" }
		}
			
	}

display_video
}

proc save_settings {} {
if { [catch {
	set fileid [open "~/.avview_state" w]
	} ] != 0 } { return }

global avview_version
puts $fileid "\n# AVview version this file was saved with\n"
puts $fileid "set saved_avview_version \"$avview_version\"\n"

save_station_names $fileid

puts $fileid "\n# General settings"

#
# The order these come in is really important
#

foreach variable {show_control_window warn_about_missing_km current_port current_encoding_name current_table_name
	current_channel  attributes_window capture_window alsa_window
	always_start_fullscreen remember_fullscreen_state
	display_setup_window_on_startup file_save_path dpms_off_on_fullscreen_power_off
	disable_fullscreen_switching use_physical_screen_size message_visible_secs
	on_screen_cc_page save_settings_on_exit transparent_when_minimized mute_when_minimized
	transparency_ratio current_file_extension ffmpeg_encoding_theme user_encoding_themes } {
	global $variable
	puts $fileid "\nglobal $variable"
	puts $fileid "set $variable \"[set $variable]\""
	}
global aspect_ratio
puts $fileid "\nglobal aspect_ratio"
puts $fileid "set aspect_ratio \[list $aspect_ratio\]"
save_theme $fileid
puts $fileid "update idletasks"

global current_alsa_device
puts $fileid "\nglobal current_alsa_device1"
puts $fileid "set current_alsa_device1 \"$current_alsa_device\""
puts $fileid ""
save_v4l_capture $fileid
puts $fileid ""
save_favorite_channels $fileid

global fullscreen_mode
if { $remember_fullscreen_state && $fullscreen_mode } {
	puts $fileid "\n# Restore fullscreen mode"
	puts $fileid "global fullscreen_mode"
	puts $fileid "set fullscreen_mode true"
	}
close $fileid
}

proc read_settings {} {
#
# Read user-specific customizations
#
set saved_avview_version ""
if { [file exists "~/.avview"] } {
	catch {
		set fileid [open "~/.avview" r]
		if { [catch "[read $fileid]" err_msg] } {
			puts "Error loading user customizations from ~/.avview: $err_msg"
			}
		close $fileid
		} 
	}
#
# Read settings saved automatically during exit
#
if { [file exists "~/.avview_state"] } {
	catch {
		set fileid [open "~/.avview_state" r]
		if { [catch "[read $fileid]" err_msg] } {
			puts "Error loading settings from ~/.avview_state: $err_msg"
			}
		close $fileid
		} err_msg
	}
global avview_version current_port
if { $avview_version != $saved_avview_version } {
	convert_favorite_channels
	wm deiconify .setup
	update
	update idletasks
	raise .setup
	update
	update idletasks
	if { $saved_avview_version != "" } {
		tk_messageBox -parent .setup -icon info\
			-type ok -message "It appears you have not run AVview $avview_version before.\nPlease verify that all settings are correct."
		} {
		tk_messageBox -parent .setup -icon info\
			-type ok -message "It appears you have not run AVview $avview_version before.\nPlease go through all settings and adjust them as appropriate."
		after idle {switch_to_pane "/Video device parameters"}
		}
	}
global save_settings_on_exit
if { $save_settings_on_exit == "unset" } { set save_settings_on_exit "true" }
}

proc convert_favorite_channels {} {
global is_favorite_channel all_favorites

catch {
# Convert old style is_favorite_channel array to all_favorites array
if { ![array exists is_favorite_channel] } { return }

	set names [array names is_favorite_channel]
	foreach id $names {
		if { [set is_favorite_channel($id)] } {
			regexp {(.+)_([0-9]+)_([0-9]+)} $id a b tableindex chindex
			set CHANNEL_LIST [freq_get_channel_list $tableindex]
			lappend all_favorites(${b}_${tableindex}) [lindex $CHANNEL_LIST $chindex]
			reflect_favorite_channels
			}
	}
}
}

proc exit_avview {} {
global save_settings_on_exit
global VIDEO_WINDOW saved_screensaver_mode
if { [ffmpeg_present] == "yes" } {
	ffmpeg_stop_encoding
        }
if { $save_settings_on_exit == "true" } { save_settings }
if {[info exists saved_screensaver_mode]} {
    xmisc_setscreensaver $VIDEO_WINDOW [lindex $saved_screensaver_mode 0]\
	[lindex $saved_screensaver_mode 1]\
	[lindex $saved_screensaver_mode 2]\
	[lindex $saved_screensaver_mode 3]\
	[lindex $saved_screensaver_mode 4]\
	[lindex $saved_screensaver_mode 5]\
	[lindex $saved_screensaver_mode 6]\
	[lindex $saved_screensaver_mode 7]\
	[lindex $saved_screensaver_mode 8]\
	[lindex $saved_screensaver_mode 9]
}
exit
}

proc check_mapped_state {} {
puts "4. state=[wm state .] mapped=[winfo ismapped .]"
after 300 check_mapped_state
}

# For debugging
#check_mapped_state

global in_set_fullscreen
set in_set_fullscreen false

proc set_fullscreen {} {
global VIDEO_WINDOW
global fullscreen_mode
global saved_screensaver_mode
global saved_main_window_geometry
global saved_vw_width
global saved_vw_height
global in_set_fullscreen

if { $in_set_fullscreen } { return }
set in_set_fullscreen true

if { $fullscreen_mode } {
	#
	# Save current settings
	#
	set saved_main_window_geometry [wm geometry .]
	set saved_screensaver_mode [xmisc_getscreensaver $VIDEO_WINDOW]
	set saved_vw_width [$VIDEO_WINDOW cget -width]
	set saved_vw_height [$VIDEO_WINDOW cget -height]

	xmisc_setscreensaver $VIDEO_WINDOW 0 0 DontPreferBlanking AllowExposures \
		0 0 0 0 off
	
	wm withdraw .
	wm overrideredirect . true
	update
#	after idle {
		while { [wm state .] != "normal" } {
			wm state . normal
			after 100
			update
			update idletasks
			}
		
		if { [xmisc_xinerama_active $VIDEO_WINDOW] } {
			puts stderr "Xinerama is active"
			set xinerama_info [xmisc_xinerama_query_screens $VIDEO_WINDOW]
			puts stderr "Xinerama info: $xinerama_info"
			puts stderr "Buggy - assuming adaptor is on screen [lindex $xinerama_info 1]"
			set coords [lindex $xinerama_info 3]
			set width [lindex $coords 2]
			set height [lindex $coords 3]
			set geometry ${width}x${height}+[lindex $coords 0]+[lindex $coords 1]
			} {
			set width [winfo screenwidth $VIDEO_WINDOW]
			set height [winfo screenheight $VIDEO_WINDOW]
			set geometry ${width}x$height+0+0
			}

		wm geometry . =$geometry
		place $VIDEO_WINDOW.onscreen_display -relx 0.05 -rely 0.05 -anchor nw
		
		update
		update idletasks
#		xmisc_setfullscreen .
		wm geometry . =$geometry

	#	. configure -width $screen_width \
	#		-height $screen_height  -background red
		$VIDEO_WINDOW configure -width $width \
			-height $height
		display_video
		update
#		puts "1. state=[wm state .]"
		while { [wm state .] != "normal" } {
#			puts "2. state=[wm state .]"
			after 100
			wm state . normal
			update
			update idletasks
			}
#		puts "3. state=[wm state .] mapped=[winfo ismapped .]"
		$VIDEO_WINDOW configure -width $width \
			-height $height
		wm geometry . =$geometry
		if { ! [xmisc_xinerama_active $VIDEO_WINDOW] } {
			grab -global .
			}
		focus -force .
#		}
	} {
	$VIDEO_WINDOW configure -width $saved_vw_width -height $saved_vw_height
	place $VIDEO_WINDOW.onscreen_display -relx 0.05 -rely 0.05 -anchor nw
	xmisc_setscreensaver $VIDEO_WINDOW [lindex $saved_screensaver_mode 0]\
					   [lindex $saved_screensaver_mode 1]\
					   [lindex $saved_screensaver_mode 2]\
					   [lindex $saved_screensaver_mode 3]\
					   [lindex $saved_screensaver_mode 4]\
					   [lindex $saved_screensaver_mode 5]\
					   [lindex $saved_screensaver_mode 6]\
					   [lindex $saved_screensaver_mode 7]\
					   [lindex $saved_screensaver_mode 8]\
					   [lindex $saved_screensaver_mode 9]
					   
	wm overrideredirect . false
	wm withdraw .
	wm geometry . =$saved_main_window_geometry
	update 
	update idletasks
	wm deiconify .
	update 
	update idletasks
	wm geometry . =$saved_main_window_geometry
	if { ! [xmisc_xinerama_active $VIDEO_WINDOW] } {
		grab release .
		}
	focus -force .
	}
set in_set_fullscreen false
}

proc set_video_window_size { w h } {
global VIDEO_WINDOW
global fullscreen_mode

if {$fullscreen_mode} {
	set fullscreen_mode 0
	after idle "set_video_window_size $w $h"
	return
	}
	
if { [ regexp {^\*} $w ] } {
	set new_width [expr [winfo width $VIDEO_WINDOW] $w ]
	} {
	set new_width $w
	}

if { [ regexp {^\*} $h ] } {
	set new_height [expr [winfo height $VIDEO_WINDOW] $h ]
	} {
	set new_height $h
	}

$VIDEO_WINDOW configure -width [expr $new_width] \
			-height [expr $new_height]
wm geometry . =[$VIDEO_WINDOW cget -width]x[$VIDEO_WINDOW cget -height]
}

global flash_counter
set flash_counter -1

proc fm_countdown {} {
global flash_counter
global VIDEO_WINDOW
incr flash_counter -1
if { $flash_counter<1} {
	destroy $VIDEO_WINDOW.onscreen_display.message 
	$VIDEO_WINDOW.onscreen_display configure -width 0 -height 0
	place forget $VIDEO_WINDOW.onscreen_display
	display_video
	incr flash_counter -1
	} {
	after 1000 fm_countdown
	}
}

proc adjust_message_font {} {
global VIDEO_WINDOW
set x_size  [expr [winfo width $VIDEO_WINDOW]/20]
set y_size [expr [winfo height $VIDEO_WINDOW]/8]

if { $x_size > $y_size } {
	set f_size $y_size
	} {
	set f_size $x_size
	}
catch {
	font delete message_font
	}
font create message_font -size -$f_size -family Helvetica -slant roman -weight normal
}

proc flash_message { message } {
global VIDEO_WINDOW
set bg [$VIDEO_WINDOW cget -background]
set f_size 0
#font delete message_font
adjust_message_font
#set message_font_id [font create message_font -size -$f_size -family Helvetica -slant roman -weight bold]

set m $VIDEO_WINDOW.onscreen_display.message
destroy $m
frame $m -background $bg
raise $m
grid $m
label $m.l -text $message -font message_font -background black -foreground "#FFAA88"
grid $m.l

wm title . "AVview: $message"

global flash_counter message_visible_secs
if { $flash_counter < 0 } { after 1000 fm_countdown }
set flash_counter $message_visible_secs
place $VIDEO_WINDOW.onscreen_display -relx 0.05 -rely 0.05 -anchor nw
}

menu .video_menu -type normal -tearoff false
menu .video_menu.size_menu -type normal -tearoff false
menu .video_menu.aspect_menu -type normal -tearoff false
menu .video_menu.channel_menu -type normal -tearoff false
menu .video_menu.channel_menu.more_menu -type normal -tearoff false
menu .video_menu.connector_menu -type normal -tearoff false
menu .video_menu.cc_menu -type normal -tearoff false

.video_menu add command -label "Toggle mute" -command toggle_mute 
.video_menu add command -label "Toggle fullscreen" -command toggle_fullscreen
.video_menu add cascade -menu .video_menu.channel_menu -label "Channel"
.video_menu add cascade -menu .video_menu.connector_menu -label "Connector"
.video_menu add cascade -menu .video_menu.cc_menu -label "Closed caption"
.video_menu add cascade -menu .video_menu.size_menu -label "Size"
.video_menu add cascade -menu .video_menu.aspect_menu -label "Aspect ratio"
.video_menu add separator
.video_menu add checkbutton -label "Show control window" -variable show_control_window  -onvalue true -offvalue false
.video_menu add command -label "Open setup window" -command "create_setup_window"
.video_menu add separator
.video_menu add command -label "Exit AVview" -command exit_avview
.video_menu add separator
.video_menu add command -label "Snapshot" -command capture_snapshot
.video_menu add separator
.video_menu add command -label "Dismiss this menu"

.video_menu.connector_menu add radiobutton -label "Tuner" -variable current_connector -command "change_connector tuner" -value "tuner"
.video_menu.connector_menu add radiobutton -label "Composite" -variable current_connector  -command "change_connector composite" -value "composite"
.video_menu.connector_menu add radiobutton -label "SVideo" -variable current_connector  -command "change_connector svideo" -value "svideo"

.video_menu.cc_menu add radiobutton -label "Off" -value "Off" -variable on_screen_cc_page
for { set i 1 } { $i <= 8 } { incr i } {
	.video_menu.cc_menu add radiobutton -label "$i" -value $i -variable on_screen_cc_page
	}

.video_menu.size_menu add checkbutton -variable fullscreen_mode -label "Fullscreen" -onvalue true -offvalue false
.video_menu.size_menu add command -label "Half size" -command "set_video_window_size *0.5 *0.5"
.video_menu.size_menu add command -label "Double size" -command "set_video_window_size *2 *2"
.video_menu.size_menu add command -label "160x120" -command "set_video_window_size 160 120"
.video_menu.size_menu add command -label "320x240" -command "set_video_window_size 320 240"
.video_menu.size_menu add command -label "480x360" -command "set_video_window_size 480 360"
.video_menu.size_menu add command -label "640x480" -command "set_video_window_size 640 480"
.video_menu.size_menu add command -label "800x600" -command "set_video_window_size 800 600"


.video_menu.aspect_menu add radiobutton -label "Unconstrained aspect ratio" -variable aspect_ratio -value [list NONE NONE]
.video_menu.aspect_menu add radiobutton -label "Aspect ratio 4:3" -variable aspect_ratio -value [list 4 3]
.video_menu.aspect_menu add radiobutton -label "Aspect ratio 3:4" -variable aspect_ratio -value [list 3 4]
.video_menu.aspect_menu add radiobutton -label "Aspect ratio 16:9" -variable aspect_ratio -value [list 16 9]
.video_menu.aspect_menu add radiobutton -label "Aspect ratio 9:16" -variable aspect_ratio -value [list 9 16]

.video_menu.channel_menu add cascade -menu .video_menu.channel_menu.more_menu -label "More..."

bind .video_menu <Unmap> {
	grab release .video_menu
	grab -global .
	focus -force .
	}
	
bind $VIDEO_WINDOW  <ButtonPress-3>  {
	global $VIDEO_WINDOW
	#.video_menu post [winfo pointerx $VIDEO_WINDOW] [winfo pointery $VIDEO_WINDOW]
	tk_popup .video_menu [winfo pointerx $VIDEO_WINDOW] [winfo pointery $VIDEO_WINDOW]
	grab .video_menu
	}


global current_port
trace variable current_port w set_port
global current_encoding_name
trace variable current_encoding_name w set_encoding
global current_table_name
trace variable current_table_name w set_channel_table
global current_channel
trace variable current_channel w "set_channel"
global fullscreen_mode
trace variable fullscreen_mode w "set_fullscreen ; skip_args3"
global current_v4l_device
trace variable current_v4l_device w  "set_v4l_device .controlwin.capture"
global current_v4l_mode
trace variable current_v4l_mode w {update_v4l_window_info .controlwin.capture ; skip_args3 }
global v4l_capture_on
trace variable v4l_capture_on w "on_v4l_capture_set .controlwin.capture"
trace variable aspect_ratio w "place_video_window ; skip_args3"
trace variable use_physical_screen_size w "place_video_window ; skip_args3"
global on_screen_cc_page
trace variable on_screen_cc_page w "vbi_set_cc_page_on_screen ; skip_args3"

bind $VIDEO_WINDOW <Configure> {
	global $VIDEO_WINDOW
	display_video
	place forget $VIDEO_WINDOW.onscreen_display
#	place $VIDEO_WINDOW.onscreen_display -relx 0.05 -rely 0.05 -anchor nw
	if { [winfo exists $VIDEO_WINDOW.control] } {
		destroy $VIDEO_WINDOW.control
		next_control 0
		}
	adjust_message_font
	}



wm protocol . WM_DELETE_WINDOW exit_avview

#wm protocol .controlwin WM_DELETE_WINDOW {
#        if { [ffmpeg_present] == "yes" } {
#                ffmpeg_stop_encoding
#                }
#	 save_settings
#	 exit 
#	 }

wm protocol .controlwin WM_DELETE_WINDOW {
	global show_control_window
	set show_control_window false
	}

wm title . "AVview"
wm title .controlwin "AV Control"

if { [alsa_present] } {
	add_parameter_pane "/Configuration/User interface settings" "User interface settings" \
		"Display setup window on startup" checkbutton display_setup_window_on_startup \
		"Display control window" checkbutton show_control_window \
		"Display attributes subsection" checkbutton attributes_window \
		"Display capture(V4L) subsection" checkbutton capture_window \
		"Display mixer(ALSA) subsection" checkbutton alsa_window \
		"Use physical screen size for aspect ratio" checkbutton use_physical_screen_size \
		"On screen message stays visible for as long as (secs)" choice { message_visible_secs 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 } \
		"Warn about missing km" checkbutton warn_about_missing_km \
		"Color theme" choice [concat theme_name $theme_names]
	} {
	add_parameter_pane "/Configuration/User interface settings" "User interface settings" \
		"Display setup window on startup" checkbutton display_setup_window_on_startup \
		"Display control window" checkbutton show_control_window \
		"Display attributes subsection" checkbutton attributes_window \
		"Display capture(V4L) subsection" checkbutton capture_window \
		"Use physical screen size for aspect ratio" checkbutton use_physical_screen_size \
		"Temporary message stays visible for as long as (secs)" choice { message_visible_secs 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 } \
		"Warn about missing km" checkbutton warn_about_missing_km \
		"Color theme" choice [concat theme_name $theme_names]
	}

add_parameter_pane "/Configuration/User interface settings/Fullscreen behaviour" "Fullscreen behaviour" \
		"Remember fullscreen state for new sessions" checkbutton remember_fullscreen_state \
		"Always start fullscreen" checkbutton always_start_fullscreen \
		"Disable fullscreen switching" checkbutton disable_fullscreen_switching \
		"Remote power off button turns off monitor in fullscreen mode" checkbutton dpms_off_on_fullscreen_power_off

add_parameter_pane "/Configuration/User interface settings/Minimize behaviour" "Minimize behaviour" \
		"Turn transparent when minimized" checkbutton transparent_when_minimized \
		"Mute when minimized" checkbutton mute_when_minimized \
		"Transparency" scale { transparency_ratio 0 255 }

Tree:open .setup.tree "/Configuration"
Tree:open .setup.tree "/Configuration/User interface settings"

regenerate_port_menu

proc set_default_settings {} {
foreach {var value} {
	capture_window   	"true"
	alsa_window		"true"	
	show_control_window	"true"
	ffmpeg_encoding_theme   "MPEG-1 HQ"
	} {
	global $var
	set $var $value
	}
set_encoding_theme
}

proc set_ui_traces {} {
global show_control_window attributes_window capture_window alsa_window theme_name ffmpeg_encoding_theme
foreach {var command} {
	show_control_window {show_control_window_proc ; skip_args3 }
	attributes_window { generate_attributes_window .controlwin.allattributes ; skip_args3 }
	capture_window { generate_capture_window .controlwin.capture ; skip_args3 }
	theme_name { global theme_name ; reset_theme $theme_name ; skip_args3 }
	ffmpeg_encoding_theme { set_encoding_theme ; skip_args3 }
	} {
	global $var
	trace variable $var w $command
	}
if {[alsa_present] == "yes" } {
	trace variable alsa_window w "generate_alsa_window .controlwin.alsamixer ; skip_args3"
	}


foreach var {attributes_window capture_window alsa_window theme_name} {
	set $var [set $var]
	}
update
set show_control_window $show_control_window
}

after idle {
	avview_set_icon . "avview-16x16.ppm"
	avview_set_icon .controlwin "avview-control-16x16.ppm"
	}

after 100 {
	assign_default_bindings
	set_default_settings
	read_settings
	rehash_themes
	set_encoding_theme
	switch_to_pane "/Configuration/User interface settings"
	if { $display_setup_window_on_startup } {
		create_setup_window
		}
	if { $always_start_fullscreen && ! $fullscreen_mode } {
		set fullscreen_mode true 
		}
	xv_pick_defaults
	set_ui_traces
	global startup_script
	eval $startup_script	
	}	

