
#-------------------------------------------------------------------------------
# Module:     file.tk
# Activation: Loaded during GOBLET startup
# Scope:      File menu item, bindings, some small dialogs
#             Resuming sessions
#             Browser shutdown
#             Transitions from one graph object to another
#
# Updated: 2003/01/01 File compression
#-------------------------------------------------------------------------------



menu .mbar.file.menu
.mbar.file.menu add command -label "New Graph Object..." -underline 0 \
    -command SaveAndNew
.mbar.file.menu add command -label "New Linear Program" \
    -command {
        global ThisGraph OrigFileName FileName TraceDir w FileCounter \
            goblinExtension Unchanged ThisBackup

        $ThisGraph delete
        DeleteTempFiles
        goblin mip $ThisGraph 20 20
        set OrigFileName [file join [pwd] unnamed]
        set FileName [file join $env(HOME) unnamed]
        wm title . "GOBLET: unnamed"
        InitFile
    }
.mbar.file.menu add command -label Open... -accelerator Ctrl+O \
    -command SaveAndOpen
.mbar.file.menu add command -label Save -accelerator Ctrl+S \
    -command SaveFile
.mbar.file.menu add separator
.mbar.file.menu add command -label "Print Object..." \
    -accelerator Ctrl+P -command PrintLayout
.mbar.file.menu add command -label "Save as..." -underline 5 \
    -command {source [file join $GoblinTclPath saveas.tk]}
.mbar.file.menu add command -label "Compression..." -command SetCompression
.mbar.file.menu add command -label "Save Settings" -underline 0 \
    -command SaveSettings
.mbar.file.menu add separator
.mbar.file.menu add command -label Quit -accelerator Ctrl+Q \
    -command SaveAndQuit

proc SaveAndNew {} {
    global Unchanged GoblinTclPath PromptCommand
    set PromptCommand "source [file join $GoblinTclPath new.tk]"
    source [file join $GoblinTclPath changes.tk]
}

proc SaveAndOpen {} {
    global Unchanged GoblinTclPath PromptCommand
    set PromptCommand "source [file join $GoblinTclPath open.tk]"
    source [file join $GoblinTclPath changes.tk]
}

proc OpenFile {} {
    global ThisGraph OrigFileName FileName TraceDir w FileCounter \
        goblinExtension Unchanged ThisBackup

    if {[file exists $OrigFileName.$goblinExtension]} {
        $ThisGraph delete
        DeleteTempFiles
        set FileName [file join $TraceDir [file tail $OrigFileName]]
        ResumeSession
        if {[file exists $FileName.backup$ThisBackup.$goblinExtension]} {
            file copy -force $FileName.backup$ThisBackup.$goblinExtension \
                $FileName.$goblinExtension
            goblin read $ThisGraph $FileName.$goblinExtension
            InitFile
            set Unchanged 0
        } else {
            file copy -force $OrigFileName.$goblinExtension $FileName.$goblinExtension
            goblin read $ThisGraph $FileName.$goblinExtension
            InitFile
        }
    }
}

proc InitFile {} {
    global FileName OrigFileName Unchanged ThisGraph FileCounter LastCommand \
        statusInfo goblinTraceCounter AlignOnOpen StartCompleted \
        ThisBackup FirstBackup LastBackup CanvasRegion

    if {$OrigFileName=="unnamed" && $StartCompleted} {
        DeleteTempFiles
        goblin restart
    }
    $ThisGraph set label $FileName
    $ThisGraph master

    wm title . "GOBLET: [file tail $OrigFileName]"
    
    set Unchanged 1
    set FileCounter 1
    set FirstBackup 1
    set ThisBackup 1
    set LastBackup 1
    set LastCommand ""

    if {[$ThisGraph is mip] || [$ThisGraph #nodes]>0} {
        $ThisGraph write $FileName.backup$ThisBackup.gob
    }

    if {[winfo exists $CanvasRegion]} {InitDisplay}
    MakeMenus
}

proc SaveFile {} {
    global ThisGraph OrigFileName goblinExtension Unchanged ZipEnabled ZipCommand
    
    $ThisGraph write $OrigFileName.$goblinExtension
    if {$ZipEnabled} {
        eval exec $ZipCommand $OrigFileName.$goblinExtension
    }

    wm title . "GOBLET: [file tail $OrigFileName]"
    set Unchanged 1
}

proc PrintLayout {} {
    global PrintCommand GoCommand UploadCommand WDInput InternalWindowing

    set GoCommand {
        PrintLayout2
        if {$InternalWindowing} {
            DestroyActiveDialog
        } else {
            destroy $WDInput
        }
    }
    set UploadCommand {}
    
    DisplayInputDialog "Print Layout" "PrintLayout" "Print" "Cancel" {
        label $WDInput.frame.text -text "Print Queue:  "
        entry $WDInput.frame.entry -textvariable PrintCommand \
            -bg white -width 19
        pack $WDInput.frame.text $WDInput.frame.entry -side left
        bind $WDInput.frame.entry <Return> $GoCommand
    }
    
    focus $WDInput.frame.entry
}

proc PrintLayout2 {} {
    global FileName FileCounter PrintCommand goblinExtension ThisGraph Mode \
        ThisBackup

    if {$Mode=="navigate"} {
        set traceFile $FileName.$FileCounter
    } else {
        global ThisGraph
        $ThisGraph write $FileName.backup$ThisBackup.gob
        set traceFile $FileName.backup$ThisBackup
    }
    
    if {[$ThisGraph is mip]} {
        goblin export ascii $traceFile.gob $traceFile.ascii
        exec $PrintCommand $traceFile.ascii
        file delete $traceFile.ascii
    } else {
        if {[$ThisGraph max cx]<=0 && [$ThisGraph max cy]<=0} {
            exec $PrintCommand $traceFile.gob
        } else {
            goblin export xfig $traceFile.$goblinExtension $traceFile.fig 
            exec fig2dev -L ps $traceFile.fig $traceFile.ps
            exec $PrintCommand $traceFile.ps
            file delete $traceFile.ps
            file delete $traceFile.fig
        }
    }
}

proc ExportLayout {} {
    global FileName FileCounter
    
    set traceFile $FileName.$FileCounter
    
    exec fig2dev -L eps "$traceFile.fig" "$traceFile.eps"
}

proc SaveAndQuit {} {
    global Unchanged GoblinTclPath PromptCommand
    set PromptCommand QuitGoblet
    source [file join $GoblinTclPath changes.tk]
}

proc SetCompression {} {
    global PrintCommand GoCommand UploadCommand WDInput InternalWindowing

    set GoCommand {
        if {$InternalWindowing} {
            DestroyActiveDialog
        } else {
            destroy $WDInput
        }
    }
    set UploadCommand {}
    
    DisplayInputDialog "File Compression" "SetCompression" "Done" "Cancel" {
        global ZipCommand UnzipCommand ZipExtension
        
        frame $WDInput.frame.frame1
        frame $WDInput.frame.frame2
        frame $WDInput.frame.frame3
        pack $WDInput.frame.frame1 $WDInput.frame.frame2 $WDInput.frame.frame3 \
            -side top -pady 1m -fill x -expand 1
        
        label $WDInput.frame.frame1.text -text "Zip:  "
        entry $WDInput.frame.frame1.entry -textvariable ZipCommand \
            -bg white -width 19
        pack $WDInput.frame.frame1.text -side left
        pack $WDInput.frame.frame1.entry -side right
        bind $WDInput.frame.frame1.entry <Return> {
            focus $WDInput.frame.frame2.entry
        }
        
        label $WDInput.frame.frame2.text -text "Unzip:  "
        entry $WDInput.frame.frame2.entry -textvariable UnzipCommand \
            -bg white -width 19
        pack $WDInput.frame.frame2.text -side left
        pack $WDInput.frame.frame2.entry -side right
        bind $WDInput.frame.frame2.entry <Return> {
            focus $WDInput.frame.frame3.entry
        }
        
        label $WDInput.frame.frame3.text -text "Extension:  "
        entry $WDInput.frame.frame3.entry -textvariable ZipExtension \
            -bg white -width 16
        pack $WDInput.frame.frame3.text -side left
        pack $WDInput.frame.frame3.entry -side right
        bind $WDInput.frame.frame3.entry <Return> $GoCommand
    }
    
    focus $WDInput.frame.frame1.entry
}

proc SaveSettings {} {
    destroy .saveChanges
    toplevel .saveChanges
    wm title .saveChanges "GOBLET Prompt"
    wm resizable .saveChanges 0 0
    grab set .saveChanges

    global FileName
     
    frame .saveChanges.buttons
    button .saveChanges.buttons.cancel -text "Cancel" -command { \
        destroy .saveChanges
    }
    
    button .saveChanges.buttons.save -text "Yes" -command { \
        goblin export settings
        destroy .saveChanges
    }
    
    pack .saveChanges.buttons.save .saveChanges.buttons.cancel \
        -side left -fill x -padx 3m
     
    pack .saveChanges.buttons -padx 3m -pady 3m -side bottom
    
    label .saveChanges.warn -image msg_warn
    message .saveChanges.msg -width 10c \
        -text "Save changes to .goshrc ?"
    pack .saveChanges.warn .saveChanges.msg -padx 2m -pady 3m -side left
}

proc QuitGoblet {} {
    global ThisGraph FileName goblinExtension StatusInfo
    if {![goblin solver idle]} {
        set StatusInfo "Stop solver before exiting!"
        return
    }
    
    goblin restart
    goblin messenger restart
    $ThisGraph delete
    DeleteTempFiles
    exit
}

proc RestartEngine {} {
    if {![goblin solver idle]} {return}

    goblin restart
    goblin messenger restart
    DeleteTempFiles
    global FileCounter Log CanvasRegion PrevTime TotalTime \
        FirstBackup ThisBackup LastBackup
    set FileCounter 1
    set TotalTime 0
    set PrevTime idle
    set FirstBackup 1
    set ThisBackup 1
    set LastBackup 1
    if {[winfo exists $CanvasRegion]} {InitDisplay}
    if {[winfo exists $Log]} {LoadLogFile}
}

proc DeleteTempFiles {} {
    global FileName goblinExtension
    catch {
        foreach {x} [glob $FileName*.$goblinExtension] {
            file delete $x
        }
    }
}

proc ResumeSession {} {
    global FileName goblinExtension goblinTraceCounter ThisBackup
    set max 0
    catch {
        foreach {x} [glob $FileName.*.$goblinExtension] {
            set item [string trim [file extension [file rootname \
                [file tail $x]]] .]
            if {![string match tmp* $item] && [expr $max<$item]} {
                set max $item
            }
        }
    }
    
    file delete -force $FileName.tcl
    
    set goblinTraceCounter $max
    if {[file exists $FileName.backup$ThisBackup.$goblinExtension]} {
        destroy .info
        toplevel .info
        wm title .info "GOBLIN Info"
        wm resizable .info 0 0
    
        frame .info.frame
        pack .info.frame -padx 2m -pady 3m -side top -anchor w
    
        label .info.frame.warn -image msg_warn
        message .info.frame.msg -width 200 -anchor w \
            -text "Old session has been restored!"
        pack .info.frame.warn .info.frame.msg -side left -padx 2m
    
        frame .info.buttons
        pack .info.buttons -padx 3m -pady 3m -side bottom
        button .info.buttons.ok -text "OK" -command {destroy .info}
        pack .info.buttons.ok -side left -fill x -padx 2m
    }
}

wm protocol . WM_DELETE_WINDOW SaveAndQuit

bind . <Control-o> {SaveAndOpen}
bind . <Control-q> {SaveAndQuit}
bind . <Control-p> {PrintLayout2}
bind . <Control-s> {SaveFile}
