
# File-related commands.
#
# Copyright (c) 1993, 1994 Pacific Marketing and Consulting
# Author:  Wayne A. Christopher, wayne@pmac.com
#          Pacific Marketing and Consulting, Berkeley, California
#

proc file_notes {} {
    set d [form_init .notes "Title/notes"]
    if {$d != ""} {
	form_label $d.titlel Title {0 0}
	form_entry $d.title job_title string {0 1}
	form_text $d.notes Notes job_notes {1 0 -cols 2}
	form_finish bot 1 1
    }
    if [form_wait .notes] {
	update_title
	db_dirty model
    }
}

proc file_subgeo {form but} {
    return bot
    
    not quite right
    
    set x [expr {[winfo rootx $form] + [winfo width $form]}]
    set y [winfo rooty $but]
    return +$x+$y
}

# --------------------------------

proc file_import_points_lines {what} {
    global file_import_type file_import_name file_import_job auto_import_types
    global file_import_scale file_import_switch type_name no_import_tetin
    global iges_nlines iges_npoints tdv_default type_visible
    
    if {$file_import_name == ""} {
	set file_import_name [pwd]
    }
    
    set file [file_selection -title "Select $what file" -default \
		  $file_import_name -extra_widgets \
		  file_import_extra_widgets_points_lines]
    if {$file == ""} return
    set file_import_name $file
    
    foreach i {xs xe ys ye zs ze} {
	global iges_$i
	catch {unset iges_$i}
    }
    
    set iges_nlines 0
    set iges_npoints 0

    busy 1
    mess "Loading $what file ...\n"
    switch $what {
	IGES {
	    mess "Note that only iges entities of types 110 (line)\
		and 116 (point) are imported by this function.\n"
	    if [catch {load_iges 0 $file 0 iges_handle} stuff] {
		mess "Warning: $stuff\n" red
	    }
	}
	DXF {
	    if [catch {load_dxf 0 $file 0 ""} stuff] {
		mess "Warning: $stuff\n" red
	    }
	}
    }
    mess "$iges_nlines lines, $iges_npoints vertices loaded.\n"
    mess "Done.\n"
    busy 0
    
    if {$file_import_scale && [info exists iges_xs]} {
	set dom [db_list_objects domain]
	[$dom getval body_shape] setval point1 "$iges_xs $iges_ys $iges_zs" \
	    point2 "$iges_xe $iges_ye $iges_ze" 
	tdv_home $tdv_default
    }
    set type_visible(cad_line) 1
    set type_visible(cad_point) 1
    update_type_visible cad_line
    update_type_visible cad_point
}

proc file_import_surfaces_curves {what} {
    global file_import_name file_import_scale tdv_default
    
    if {$file_import_name == ""} {
	set file_import_name [pwd]
    }
    
    set file [file_selection -title "Select $what file" -default \
		  $file_import_name]
    if {$file == ""} return
    set file_import_name $file
    
    busy 1
    mess "Loading $what file ...\n"
    switch $what {
	IGES {
	    cad_load_iges $file
	}
	DWG {
	    user_error "not yet implemented"
	}
	ACIS {
	    user_error "not yet implemented"
	}
	tetin {
	    cad_do_load_tetin $file 0 ""
	}
    }
    app_domain_autoscale
    mess "Done.\n"
    busy 0
}

proc file_import_new_job {what} {
    global file_import_name file_import_job tdv_default form_tail_var
    
    if {$file_import_name == ""} {
	set file_import_name [pwd]
    }
    set file_import_job ""
    switch $what {
	ECO {
	    set file [file_selection -title "Select $what file" -default \
		  $file_import_name -extra_widgets \
		  file_import_extra_widgets_new_job]
	    if {$file == ""} return
	    set file_import_name $file
	    set njob [eco_do_import $file $file_import_job]
	    job_load $njob ""
	}
	IDF {
	    board_wizard_idf .import
	}
    }
}

proc file_import_extra_widgets_points_lines {d} {
    global type_name
    form_checkbutton $d.scale "Scale $type_name(domain) to fit objects" \
	file_import_scale {0 0}
}

proc file_import_extra_widgets_new_job {d} {
    form_label $d.namel "Job name" {0 0}
    # We really should have a file selection dialog here but we can't have
    # nested file selections ...  so we have to live with this.
    form_entry $d.name file_import_job string {0 1}
}

# -----------------------------------------------------

proc file_save {ask {version ""} {part ""} {switch_version 1} \
		    {def_name ""} {mat_lib 0} {try_picture 1}} {
    global file_save post_objects job_name job_version filetype_data
    global bindir app_name saving_as_version solve_id message_save_directory
    global can_do_open_operation tdv_default use_builtin_file_dialogs
    global toplevel batch_mode
    global problem_power_profile_count problem_power_profile_fname
    
    # sometimes users are too quick giving this command and get into a
    # recursive file/open situation.  But maybe there was an error so set
    # this variable again ...
    if ![info exists can_do_open_operation] {
	mess "You selected the Save operation a second time before the first Save was completed.\n" red
	set can_do_open_operation 1
	return 0
    }
    unset can_do_open_operation
    
    set file_save(name) $job_name  ;# or [directory] ??
    set file_save(version) $job_version
    set file_save(sol) 0
    set file_save(mesh) 1
    set file_save(post) 1
    set file_save(save_31) 0
    
    set oldname $job_name
    
    set file_save(haspost) [expr {[array names post_objects] != ""}]
    set file_save(hasmesh) [expr {[glob_fixed [directory]/grid_output*] != ""}]
    set file_save(hassolv) [expr {[glob_fixed [directory]/*.resd*] != ""}]
    
    if $ask {
	set file_save(image) 1
	if {$part == ""} {
	    if [db_check_dirty model] {
		set file_save(string) "Save needed (job modified)"
	    } else {
		set file_save(string) "Save not needed"
	    }
	} elseif $mat_lib {
	    set file_save(string) "Saving material library"
	} else {
	    set file_save(string) "Saving part or group"
	}
	if {!$mat_lib && (($app_name == "icepak") ||
			  ($app_name == "airpak"))} {
	    set file_save(image) $try_picture
	}
	set file_save(version) ""
	
	if {$def_name == ""} { set def_name $job_name }
	
	# This is only temporary
	set get_dir [expr ![info exists use_builtin_file_dialogs]]
	
	while 1 {
	    set nn [file_selection -message "Save to what project?" \
			-default $def_name -title "Save project" \
			-get_dir $get_dir \
			-warn_overwrite 0 -is_save_dialog 1\
			-new_ok 2 -ok_func directory_is_job_new \
			-extra_widgets {on_side file_save_extra_widgets} \
			-ok_to_select "valid projects" \
			-dir_leaf_image ${app_name}_is_job \
			-dir_leaf_label "Project"]
	    if {$nn == ""} { set can_do_open_operation 1; return 0 }
	    if ![job_name_is_valid $nn] continue
	    if {$file_save(version) == ""} {
		if 0 { this check was already done
		    if [file exists $nn/model] {
			if [tk_dialog .warn_over "Overwrite project" \
				"Project \"$nn\" already exists - overwrite?" \
				"" -1 Overwrite Cancel] continue
		    }
		}
	    } else {
		if [file exists $nn/$file_save(version).model] {
		    if [tk_dialog .warn_over "Overwrite version" \
			    "Project \"$nn\", version \"$file_save(version)\"\
			    already exists - overwrite?" \
			    "" -1 Overwrite Cancel] continue
		}
	    }
	    break
	}
	set file_save(name) $nn
	
    } else {
	set file_save(image) 0
	
	if {$version != ""} {
	    set file_save(version) $version
	    if {$version == "no_version"} { set file_save(version) "" }
	}
	if {$def_name != ""} { set file_save(name) $def_name }
    }
    if {$file_save(name) == ""} {
	user_error "No project name given for save command"
	set can_do_open_operation 1
	return 0
    }
    
    if [regsub -all {/| |\t} $file_save(version) - newvers] {
	mess "Warning: changed the version name to $newvers\n" red
	set file_save(version) $newvers
    }
    
    set jn $job_name
    if {[file pathtype $jn] == "relative"} { set jn [pwd]/$jn }
    
    set jn2 $file_save(name)
    if {[file pathtype $jn2] == "relative"} { set jn2 [pwd]/$jn2 }

    if 0 {
	if {([file split $jn2] != [file split $jn]) && \
		[file exists $file_save(name)/model]} {
	    set message "Project \"$file_save(name)\" already exists -- overwrite?"
	    if ![tk_dialog .exists "Project exists" $message "" 0 No Yes] {
		mess "Warning: not saving project.\n" red
		set can_do_open_operation 1
		return 0
	    }
	}
    }
    if $file_save(save_31) { set saving_as_version 31 }
    
    set vers ""
    if {$file_save(version) != ""} {
	set vers " version \"$file_save(version)\""
    }
    mess "Saving project \"$file_save(name)\"$vers\n"
    busy 1
    if {$file_save(version) != ""} {
	job_save $file_save(name) $file_save(version)
    }
    job_save $file_save(name) "" $part
    set saving_as_version 0
    
    if {$file_save(post) && $file_save(haspost) && ($part == "")} {
	post_save $file_save(name)/post_objects
	if {$job_name != $file_save(name)} {
	    mess "Copying postprocessing objects ...\n"
	}
    } else {
	# exec /bin/rm -f $file_save(name)/post_objects
    }
    if {($oldname != $file_save(name)) && ($part == "")} {
	set stuff ""
	if {$file_save(mesh) && $file_save(hasmesh) && \
		[info exists filetype_data(mesh)]} {
	    set stuff "$stuff [lrange $filetype_data(mesh) 1 end]"
	}
	if {$file_save(sol) && $file_save(hassolv)} {
	    set stuff "$stuff *.resd *.res *.grid_output \
		*.grid_mapping *.model *.problem *.fmap *.pmon *.res \
        	*.out *.cas *.dat *.fdat *.ff_out *.ff_rec \
               *.netzones *.fanzones optimization.tab"
	}
	if {[info exists problem_power_profile_count] && ($problem_power_profile_count > 0)} {
	    lappend stuff $problem_power_profile_fname
	}
	foreach pat $stuff {
	    foreach f [glob_fixed [directory]/$pat] {
		mess "Copying file \"[file tail $f]\" ...\n"
		if ![cmd_cp $f $file_save(name)/[file tail $f]] {
		    user_error "Can't save to $file_save(name)"
		    busy 0
		    set can_do_open_operation 1
		    return 0
		}
	    }
	}
	
	set solve_id ""
    }
    if {$file_save(image) && !$batch_mode} {
	foreach im [$tdv_default list_images] {
	    $im configure -width [expr [$im get -width] * 2]
	}
	set fig $file_save(name)/image
	if {$file_save(version) != ""} {
	    append fig .$file_save(version)
	}
	append fig .ppm
	raise .v
	$tdv_default redraw
	mess "Making picture ... "
	set fp [open [list |$bindir/pnmscale .35 > $fig] w]
	if [catch {$tdv_default write_ppm $fp portrait 0 0 0 0 0} res] {
	    mess "Warning: $res\n" red
	}
	catch {close $fp} res ;# it's just scaling information
	if $toplevel(single) { lower .v }
	mess "done.\n"
	foreach im [$tdv_default list_images] {
	    $im configure -width [expr [$im get -width] / 2]
	}
    }
    
    if {$part == ""} {
	if $switch_version {
	    set job_name $file_save(name)
	    set job_version $file_save(version)
	    update_title
	    if !$file_save(mesh) {
		# make sure we don't think we already have a mesh when we don't
		db_dirty mesh
	    }
	}
	db_dirty off
    }
    set message_save_directory [directory]
    message_log_reopen [directory]/messages.log 0
    
    mess "Done saving.\n"
    
    busy 0
    set can_do_open_operation 1
    return 1
}

proc file_save_extra_widgets {d} {
    global file_save app_name

    switch $app_name {
	icepak - airpak {}
	default return
    }
    
    form_label $d.label "" {0 0 -cols 2}
    $d.label configure -textvariable file_save(string)
    
    form_label $d.versl "Version" {5 0}
    form_entry $d.vers file_save(version) string {5 1}
    
    form_checkbutton $d.copym "Copy mesh data" file_save(mesh) \
	{10 0 -cols 2} file_save(hasmesh)
    form_checkbutton $d.copys "Copy solution data" file_save(sol) \
	{11 0 -cols 2} file_save(hassolv)
    form_checkbutton $d.savep "Save postprocessing objects" \
	file_save(post) {12 0 -cols 2} file_save(haspost)
    form_checkbutton $d.savei "Save picture file" \
	file_save(image) {13 0 -cols 2}
    if 0 {
	# this doesn't make sense for 4.1
	switch $app_name {
	    icepak {
		form_checkbutton $d.save31 "Write 3.1 project" \
		    file_save(save_31) {14 0 -cols 2}
	    }
	    airpak {
		form_checkbutton $d.save31 "Write 1.0 project" \
		    file_save(save_31) {14 0 -cols 2}
	    }
	}
    }
}

proc get_print_cmd {file which} {
    global job_printcmd_$which env
    
    if ![info exists env(PRINTER)] {
	mess "Warning: no PRINTER environment variable was found: using\
	      default printer name\"PostScript\"\n" red
	set env(PRINTER) PostScript
    }
    
    set tempf /tmp/autohex.[pid]
    if [file exists $tempf] { cmd_rm $tempf }
    
    set cmd [set job_printcmd_$which]
    regsub -all -nocase %p $cmd $env(PRINTER) cmd
    regsub -all -nocase %t $cmd $tempf cmd
    if ![regsub -all -nocase %f $cmd $file cmd] { set cmd "$cmd $file" }

    return $cmd
}

proc file_quit {{ask 0}} {
    global no_exit_job
    
    if !$ask do_quit
    
    if [info exists no_exit_job] {
	set mess "Warning: the $no_exit_job is currently running. \
		If you quit now it will not finish correctly.  Do it anyway?"
	if ![tk_dialog .busy Busy $mess "" 0 No Yes] return
    }
    
    if {[winfo exists .save] && [winfo ismapped .save]} {
	raise .save
	bell
	return
    }
    
    if [db_check_dirty model] {
	set message "Project has been modified -- save before quitting?"
	switch [tk_dialog .confirm Confirm $message "" 0 "Save and quit" \
		    "Quit without saving" "Cancel quit"] {
			0 { if [file_save 0 ""] do_quit }
			1 { do_quit }
			2 { return }
		    }
    } else {
	set message "Please confirm quit."
	switch [tk_dialog .confirm Confirm $message "" 0 Quit Cancel] {
	    0 { do_quit }
	    1 { return }
	}
    }
}

proc do_quit {} {
    global fpp

    if [info exists fpp] { $fpp end; $fpp delete }
    exit 0
}

proc file_shell {} {
    global host_vendor job_xterm_opts is_win
    
    if $is_win {
	mess "Opening command prompt in project directory...\n"
    } else {
	mess "Opening UNIX shell in project directory...\n"
    }
    set here [pwd]
    cd [directory shell]
    eval cmd_xterm -sb -geometry +0+0 $job_xterm_opts &
    cd $here
}

proc file_pguide {} {
    global prog_guide_files source_dirs whoami version
    
    set file [file_selection -message "Select the output HTML file." \
		  -default [pwd]/prog_guide.html \
		  -title "Output file"]
    if {$file == ""} return
    
    set files ""
    foreach f $prog_guide_files {
	foreach dir $source_dirs {
	    if [file exists $dir/$f.tcl] {
		lappend files $dir/$f.tcl
		break
	    }
	}
    }
    makedoc $file $files "$whoami $version programmer's guide"
    mess "Wrote programmer's guide ([llength $files] files) to $file\n"
}

proc update_parameters_and_remesh {file} {
    expression_set_some_file $file
    grid_generate
    auto_save_all
    exit 0
}
