#!/bin/sh  
# \
  exec oagwish "$0" "$@"

# $Log: not supported by cvs2svn $
# Revision 1.51  2011/04/18 14:37:02  flood
# changed medm launch from cleanup to attach
#
# Revision 1.50  2010/10/06 14:00:49  soliday
# Added missing catch statement.
#
# Revision 1.49  2009/03/04 15:14:32  flood
# Didn't delete enough lines before
#
# Revision 1.48  2009/03/04 15:05:26  flood
# Added tornado set up. Removed obsolete linac par booster rf setups
#
# Revision 1.47  2009/02/10 22:27:03  soliday
# Updated to use the newer linuxWorkSpaceSwitcherApplet
#
# Revision 1.46  2008/12/10 21:32:21  soliday
# Updated for Linux. It now sets the system workspace names so that when
# you move programs using the button at the top left of the window it
# will list the correct names.
#
# Revision 1.45  2008/12/04 22:04:24  soliday
# Fixed an issue on Linux when run multiple times.
#
# Revision 1.44  2008/10/03 21:04:47  soliday
# Fixed an issue on Linux if run multiple times.
#
# Revision 1.43  2008/09/30 21:30:53  soliday
# Added better support for Linux computers. It now uses the
# linuxWorkSpaceSwitcherApplet which is a custom gnome style applet
# written in tcl that sits on top of the bottom gnome panels and allows
# you to switch workspaces. The main benefit is that different screens
# can have different workspace names. This applet requires that a
# separator be placed on the bottom panel so that the right corner of
# the panel will not also contain the window list applet.
#
# Revision 1.42  2008/07/22 20:56:50  soliday
# Updated to work on Linux. Addtional changes need be made to support dual
# monitors.
#
# Revision 1.41  2008/07/02 20:34:08  shang
# added "Diagnostics" button for setup diagnostics workspace.
#
# Revision 1.40  2007/11/19 15:08:10  flood
# added new operator wsp
#
# Revision 1.39  2007/07/31 15:54:01  emery
# Added information on how to start editing a configuration in
# the Overview command.
#
# Revision 1.38  2004/03/23 01:16:40  emery
# Changed argument passign method in MakeSetupStructures.
# Changed variable names in MakeSetupStructures.
# This is to make the procedure comprehensible.
#
# Revision 1.37  2002/10/30 15:55:17  soliday
# Added the Phoenix setup
#
# Revision 1.36  2002/07/19 16:31:27  borland
# Added VIP workspace.
#
# Revision 1.35  2002/01/29 13:57:33  emery
# Added check button for optional restart of window manager.
#
# Revision 1.34  2001/10/24 19:39:07  soliday
# Added the Charis Setup button.
#
# Revision 1.33  2001/07/19 21:41:24  soliday
# Added the ability to restart the window manager automatically.
#
# Revision 1.32  2001/01/19 16:01:59  borland
# Reduced wait intervals to half previous values to reflect faster workstations.
#
# Revision 1.31  2000/10/27 00:27:40  emery
# Removed extraneous curly braces.
#
# Revision 1.30  2000/07/28 23:02:08  emery
# Indented again.
#
# Revision 1.29  2000/07/28 22:10:49  emery
# Indented code.
#
# Revision 1.28  1999/08/20 18:40:42  sereno
# Changed the workspace setup LASER to Laser.  N. Sereno.
#
# Revision 1.27  1999/08/20 17:48:41  sereno
# Added LASER workspace setup.  N. Sereno.
#
# Revision 1.26  1999/06/22 22:40:43  sereno
# Added LEUTL workspace setup button.  N. Sereno
#
# Revision 1.25  1998/11/17 19:02:50  borland
# Now accepts commands with '-' and other characters.  Deletes redundant &
# that some commands have.
#
# Revision 1.24  1998/10/30 14:17:42  borland
# Uses the ASDOPS files by default now.
#
# Revision 1.23  1997/03/28 15:29:30  borland
# Removed annoying feature that emailed borland when someone used the
# "wrong" workspace name.
#
# Revision 1.22  1997/02/13 22:15:37  borland
# Now sets value of display variable prior to bringing up dialog
# for manual entry of workspace name and display.
#
# Revision 1.21  1997/02/04 15:44:26  borland
# Added option to use OAG or ASDOPS setups.
#
# Revision 1.20  1997/01/17 21:35:49  borland
# Fixed incorrect directory name.
#
# Revision 1.19  1997/01/17 21:27:12  borland
# Uses wksplaunch to switch between workspaces automatically.
#
# Revision 1.18  1996/11/14 20:20:01  borland
# Works with TED window manager rather than VUE window manager.
#
# Revision 1.17  1996/10/01 13:22:11  borland
# Changed autopath statements to standard ones.
#
# Revision 1.16  1996/09/19 21:50:39  borland
# Changed from using "exec wish" to "exec oagwish".
#
# Revision 1.15  1996/04/03 03:27:29  borland
# Redirected command output to /dev/null.  Removed puts statements.
#
# Revision 1.14  1996/03/16  18:12:44  borland
# Added scrolled status display.  Now reverts to display 0 automatically.
#
# Revision 1.13  1996/03/04  19:55:03  saunders
# Added revision/author to Version menu.
#
# Revision 1.12  1996/02/21  23:09:19  borland
# Added support for two monitors.
#
# Revision 1.11  1996/02/14  00:29:17  borland
# Added raise calls to bring main window to foreground after MEDM screens (etc)
# come up.
#
# Revision 1.10  1996/02/12  23:37:10  borland
# Switched to using setup files in /home/helios/oagData/workspaceSetups .
#
# Revision 1.9  1996/02/12  15:41:05  borland
# Changed -clean_up to -cleanup on initial medm invocation.
#
# Revision 1.8  1996/02/12  14:55:58  borland
# Removed invalid options in call to APSSDDSCheckButtons
#
# Revision 1.7  1996/01/17  16:58:40  saunders
# Added /usr/local/oag/lib_patch to front to auto_path.
#
# Revision 1.6  1996/01/16  23:46:27  borland
# Added sleep statement after medm startup to give medm time to establish
# itself before user pushes any buttons.
#
# Revision 1.5  1996/01/16  21:11:22  saunders
# Fixed log entry problem, so now comments and version numbers
# appear properly. Also, renames X.tcl files to just X.
#
# Revision 1.4  1996/01/12 22:36:06  saunders
# Removing dependence on ~borland/tcl/rel auto_path entry. There are still
# references to personal directories. Also fixed minor bugs as encountered.
#
# Revision 1.3  1995/12/15  20:12:00  saunders
# Added proper installation Makefile and Log
#

set auto_path [linsert $auto_path 0  /usr/local/oag/apps/lib/$env(HOST_ARCH)]
set auto_path [linsert $auto_path 0 /usr/local/oag/lib_patch/$env(HOST_ARCH)]
set CVSRevisionAuthor "\$Revision: 1.52 $ \$Author: flood $"

set apsttk 1
set mainDirectory /home/helios/ASDOPS/workspaceSetups
#set mainDirectory /home/helios/oagData/workspaceSetups
set DisplayTail :0.0
if [lsearch [array names env] DISPLAY]==-1 {
    set DisplayRoot ""
} else {
    set cIndex [string first : $env(DISPLAY)]
    if {$cIndex<=0} {
        set DisplayRoot ""
    } else {
        set DisplayRoot [string range $env(DISPLAY) 0 [expr $cIndex-1]]
        set DisplayTail [string range $env(DISPLAY) $cIndex end]
    }
}
set Display ${DisplayRoot}$DisplayTail


proc IsRedhat7 {args} {
    set fid [open /etc/redhat-release r]
    set line [gets $fid]
    close $fid
    if {([string first "Red Hat" $line] != -1) && ([string first "release 7" $line] != -1)} {
        return 1
    }
    return 0
}
proc IsRedhat8 {args} {
    set fid [open /etc/redhat-release r]
    set line [gets $fid]
    close $fid
    if {([string first "Red Hat" $line] != -1) && ([string first "release 8" $line] != -1)} {
        return 1
    }
    return 0
}
if {([IsRedhat7] != 1) && ([IsRedhat8] != 1)} { 
  set multiMonitorWorkspace 0
} else {
  set multiMonitorWorkspace 1
}


set setups {Linac ITS PAR Booster SR SRRF LEUTL Laser Charis_SR Phoenix NewOperators DIAG Tornado Summit Shutdown}

proc SetWmSetupDirectory {machine} {
    global wmResources mainDirectory setups workspaceNames tcl_platform

    if {$tcl_platform(os) == "Linux"} {
	if {[catch {exec sdds2stream $mainDirectory/ted/${machine}-workspaces.sdds \
		      -col=Name,Screen} results]} {
	    APSSetVarAndUpdate status $results
	    return 0
	}
        unset -nocomplain workspaceNames
	foreach "name screen" $results {
	    lappend workspaceNames($machine,$screen) $name
	}
	return 1
    } else {

        if {[lsearch $setups $machine] == -1} {
            return 0
        } else {
            if {$machine == "Charis_SR"} {
                set wmResources $mainDirectory/ted/${machine}-Resources 
            } else {
                set wmResources $mainDirectory/ted/${machine}-resources 
            }
            return 1
        }
    }
}

# Setup workspace lists and arrays for the specified machine

proc DefineWorkspaceSetup {machine} {
    global mainDirectory setups multiMonitorWorkspace
    global wspcomfile workspaces wspoccurranceArray wspcommandArray wspDisplayArray
    if {$multiMonitorWorkspace} {
        set wspdir $mainDirectory/wspSetupsRH7
    } else {
        set wspdir $mainDirectory/wspSetups
    }
    if [info exists wspoccurranceArray] {unset wspoccurranceArray}
    if [info exists wspcommandArray] {unset wspcommandArray}
    if [info exists wspDisplayArray] {unset wspDisplayArray}

    if {[lsearch $setups $machine] == -1} {
        return 0
    } else {
        if {$machine == "Charis_SR"} {
            set wspcomfile $wspdir/AdditionalSRWspCommands.sdds	    
        } else {
            set wspcomfile $wspdir/${machine}WspCommands.sdds
        }
        set wspNames [APSGetSDDSColumn -fileName $wspcomfile -column WorkSpaceName]
        set wspSetupCommands [APSGetSDDSColumn -fileName $wspcomfile -column WorkSpaceCommand]
        set wspDisplays [APSGetSDDSColumn -fileName $wspcomfile -column Display]
        set workspaces [MakeSetupStructures -workspaceList $wspNames \
                          -commandList $wspSetupCommands \
                          -displayList $wspDisplays \
                          -occurranceArrayName wspoccurranceArray \
                          -commandArrayName wspcommandArray \
                          -displayArrayName wspDisplayArray]
        return 1
    }
}

# Make a list of workspaces from the command files list.  
# Make an array containing the number of occurrances
# of the various commands for each workspace and a two 
# dimensional array containing the specific commands.
# Returns 0 for the 0th elements of both arrays if one 
# or the other or both lists are empty.

proc MakeSetupStructures {args} {
    APSParseArguments {workspaceList commandList displayList \
                         occurranceArrayName commandArrayName displayArrayName}

    upvar $occurranceArrayName occurranceArray
    upvar $commandArrayName commandArray
    upvar $displayArrayName displayArray
    if {[info exists occurranceArray]} {unset occurranceArray}
    if {[info exists commandArray]} {unset commandArray}
    if [info exists displayArray] {unset displayArray}

    # variable workspaceList is column WorkSpaceName    from file $wspcomfile
    # variable commandList   is column WorkSpaceCommand from file $wspcomfile
    # variable displayList   is column Display          from file $wspcomfile

    if {[llength $workspaceList]==0 || [llength $commandList]==0} {
        set occurranceArray(0) 0
        set commandArray(0) 0
        return 0
    }
    set index 0
    set workspacelist ""
    set orderedWorkspaceList [lsort $workspaceList]
    set workspace [lindex $orderedWorkspaceList [expr $index + 1]]
    
    foreach elem $orderedWorkspaceList {
        if {($workspace != $elem)} {
            lappend workspacelist [lindex $orderedWorkspaceList $index]
        }
        incr index 
        set workspace [lindex $orderedWorkspaceList [expr $index + 1]] 
    }
    foreach elem $workspacelist {set occurranceArray($elem) 0}
    foreach elem $workspacelist {
        foreach commelem $orderedWorkspaceList {
            if {$elem == $commelem} {
                incr occurranceArray($elem)
            }
        }
    }
    foreach elem $workspacelist {
        set listindex 0
        set commandarrayindex 1
        foreach command $workspaceList {
            if {$command == $elem} {
                set commandArray($elem,$commandarrayindex) [lindex $commandList $listindex]
                set displayArray($elem,$commandarrayindex) [lindex $displayList $listindex]
                incr commandarrayindex
            } 
            incr listindex
        }
    } 
    return $workspacelist
}                       

# Set up machine workspaces based on a setup array, 
# an medm setup command file array, and a command occurrance array.

proc SetupMachineWorkspaces {machine workspacelist setupArrayName occurranceArrayName commandArrayName displayArrayName args} {
    global choice statusCallback multiMonitorWorkspace
    global Display DisplayRoot
    upvar $setupArrayName setupArray
    upvar $occurranceArrayName occurranceArray
    upvar $commandArrayName commandArray
    upvar $displayArrayName displayArray

    set statusCallback ""
    APSParseArguments {statusCallback}
    
    global tcl_platform
    if {$tcl_platform(os) == "Linux"} {
    } else {
        APSInfoWindow .info[APSTmpString] \
          -infoMessage "You should set the workspace setup tool to occupy all workspaces before continuing." -modal 1 \
          -name "Workspace setup information"
    }
    
    catch {unset wspAlias}
    catch {unset displayAlias}
    set expected -1
    global display workspace workspaceNames env

    foreach elem $workspacelist {
        if {$setupArray($elem)} {
            if {$statusCallback!=""} {
                $statusCallback "Doing setup for workspace $elem..."
            }
            set skip 0
            set display $DisplayRoot$displayArray($elem,1)
            set workspace $elem
            while 1 {
                if [info exists wspAlias($elem)] {
                    set workspace $wspAlias($elem)
                    set display   $displayAlias($elem)
                }
                if {$tcl_platform(os) == "Linux"} {
		    
                    set index0 [lsearch -exact $workspaceNames($machine,0) $elem]
                    set index1 [lsearch -exact $workspaceNames($machine,1) $elem]

                    if {($index0 == -1) && ($index1 == -1)} {
			break
		    }
                    if {!$multiMonitorWorkspace} {
		        if {[info exists env(DISPLAY)]} {
			    set origDisplay $env(DISPLAY)
		        } else {
			    set origDisplay :0.0
		        }
                        if {$index0 != -1} {
			    set env(DISPLAY) :0.0
                            if {[catch {socket 127.0.0.1 4590} sid]} {
			    } else {
			        fconfigure $sid -buffering line
			        puts $sid $index0
			    }
                            catch {exec wmctrl -s $index0}
			    set env(DISPLAY) $origDisplay
                            break
                        }
		        if {$index1 != -1} {
			    set env(DISPLAY) :0.1
			    if {[catch {socket 127.0.0.1 4591} sid]} {
			    } else {
			        fconfigure $sid -buffering line
			        puts $sid $index1
			    }
                            catch {exec wmctrl -s $index1}
			    set env(DISPLAY) $origDisplay
                            break
                        }
                    } else {
                        if {$index0 != -1} {
                            if {[catch {socket 127.0.0.1 4590} sid]} {
			    } else {
			        fconfigure $sid -buffering line
			        puts $sid $index0
			    }
                            #break
                        }
		        if {$index1 != -1} {
			    if {[catch {socket 127.0.0.1 4591} sid]} {
			    } else {
			        fconfigure $sid -buffering line
			        puts $sid $index1
			    }
                            #break
                        }
                        if {($index0 != -1) || ($index1 != -1)} {
                            break
                        }
                    }
		} else {
                    set code [catch {exec wksplaunch -display $display -wksp $workspace} result]
                    if $code {
                        if {$statusCallback!=""} {
                            $statusCallback "$result"
                        }
                        if {$code==1} {
                            global apsDialogChoice
                            set widget [APSUniqueName .]
                            APSDialogBox $widget -cancelCommand "set apsDialogChoice 0" \
                              -okCommand "set apsDialogChoice 1" 
                            label $widget.userFrame.label1 -text "Workspace $workspace not found on display $display."
                            label $widget.userFrame.label2 -text "Enter a new workspace name and/or display."
                            pack $widget.userFrame.label1 $widget.userFrame.label2
                            APSLabeledEntry .wsp -parent $widget.userFrame \
                              -label "Workspace: " -textVariable workspace -width 10
                            set display :0.0
                            APSRadioButtonFrame .rb -parent $widget.userFrame \
                              -label "Display: " -variable display \
                              -buttonList "0 1" -valueList ":0.0 :0.1" -orientation horizontal
                            APSEnableButton $widget.buttonRow.ok.button
                            APSEnableButton $widget.buttonRow.cancel.button
                            tkwait variable apsDialogChoice
                            set wspAlias($elem) $workspace
                            set displayAlias($elem) $display
                            if !$apsDialogChoice {
                                set skip 1
                                break
                            } 
                        } 
                        if ![string length $wspAlias($elem)] {
                            continue
                        }
                    } else break
                }
            }
            if $skip continue
            for {set occurrance 1} {$occurrance <= $occurranceArray($elem)} {incr occurrance} {
                set command0 "$commandArray($elem,$occurrance)"
                set wIndex 0
                while 1 {
                    set word1 [string wordend $command0 $wIndex]
                    set splitChar [string range $command0 $word1 $word1]
                    set wIndex [expr $word1+1]
                    if {[string length $splitChar]==0 || \
                          [string compare $splitChar " "]==0} {
                        break
                    }
                }
                set command1 [string trim [string range $command0 0 $word1]]
                set command2 \
                  [split [string trim [string trimright [string range $command0 $word1 end] &]]]
                if {!$multiMonitorWorkspace} {
                    if [string compare $command1 medm]==0 {
                        LaunchMedmForDisplay $display
                    }
                    eval exec $command1 -display $display $command2 >& /dev/null &
                } else {
                    eval exec $command1 $command2 >& /dev/null &
                }
                after 250
                raise .
            } 
	    after 5000
        }
    }
    if {$tcl_platform(os) == "Linux"} {
	if {[catch {socket 127.0.0.1 4590} sid]} {
	} else {
	    fconfigure $sid -buffering line
	    puts $sid 0
	}
	if {[catch {socket 127.0.0.1 4591} sid]} {
	} else {
	    fconfigure $sid -buffering line
	    puts $sid 0
	}
    }
    if {$statusCallback!=""} {
        $statusCallback "Setup completed."
    }
    return 1
}

proc MachineWorkSpaceSelect {machine args} {
    global wspcomfile workspaces wspChoiceArray wspoccurranceArray wspcommandArray setupchoice 
    global wmResources statusCallback wspDisplayArray wspRestart multiMonitorWorkspace
    
    set statusCallback ""
    set parent ""
    
    APSParseArguments {parent statusCallback}
    
    if {![SetWmSetupDirectory $machine]} {
        if {$statusCallback!=""} {
            $statusCallback "Machine name $machine is unknown."
        }
        APSAlertBox .alert[APSTmpString] -errorMessage "Machine name $machine is unknown."
        return 0
    }
    
    if {$statusCallback!=""} {
        $statusCallback "Reading data for $machine workspace setup..."
    }
    DefineWorkspaceSetup $machine
    
    global tcl_platform
    if {$tcl_platform(os) == "Linux"} {
        global workspaceNames
        if {!$multiMonitorWorkspace} {
        set panels [exec gconftool-2 --all-dirs /apps/panel/toplevels]
	set panels [split [string range [exec gconftool-2 -g /apps/panel/general/toplevel_id_list] 1 end-1] , ]
	set leftpanel ""
	set rightpanel ""
	set leftWindowListApplet ""
	set rightWindowListApplet ""
	set leftPanelSeparator ""
	set rightPanelSeparator ""
	foreach panel $panels {
	    set orientation [exec gconftool-2 -g /apps/panel/toplevels/${panel}/orientation]
	    set screen [exec gconftool-2 -g /apps/panel/toplevels/${panel}/screen]
	    if {($orientation == "bottom") && ($screen == 0)} {
		lappend leftpanel $panel
	    }
	    if {($orientation == "bottom") && ($screen == 1)} {
		lappend rightpanel $panel
	    }
	}
	foreach panel $leftpanel {
	    exec gconftool-2 --type=int -s /apps/panel/toplevels/${panel}/size 56
	}
	foreach panel $rightpanel {
	    exec gconftool-2 --type=int -s /apps/panel/toplevels/${panel}/size 56
	}
	set windowListApplets [exec gconftool-2 --all-dirs /apps/panel/applets]
	foreach windowListApplet $windowListApplets {
	    if {[catch {exec gconftool-2 -g ${windowListApplet}/bonobo_iid} id]} {
		continue
	    }
	    if {$id == "OAFIID:GNOME_WindowListApplet"} {
		set toplevel_id [exec gconftool-2 -g ${windowListApplet}/toplevel_id]
		if {[lsearch -exact $leftpanel $toplevel_id] != -1} {
		    lappend leftWindowListApplet $windowListApplet
		}
		if {[lsearch -exact $rightpanel $toplevel_id] != -1} {
		    lappend rightWindowListApplet $windowListApplet
		}
	    }
	}
	#This doesn't actually move the window list applet. I wish it did.
	foreach windowListApplet $leftWindowListApplet {
	    exec gconftool-2 --type=int -s ${windowListApplet}/position 0
	}
	foreach windowListApplet $rightWindowListApplet {
	    exec gconftool-2 --type=int -s ${windowListApplet}/position 0
	}

	set panelSeparators [exec gconftool-2 --all-dirs /apps/panel/objects]
	foreach panelSeparator $panelSeparators {
	    if {[catch {exec gconftool-2 -g ${panelSeparator}/object_type} id]} {
		continue
	    }
	    if {$id == "separator"} {
		set toplevel_id [exec gconftool-2 -g ${windowListApplet}/toplevel_id]
		if {[lsearch -exact $leftpanel $toplevel_id] != -1} {
		    lappend leftPanelSeparator $panelSeparator
		}
		if {[lsearch -exact $rightpanel $toplevel_id] != -1} {
		    lappend rightPanelSeparator $panelSeparator
		}
	    }
	}
	#This doesn't actually move the window list applet. I wish it did.
	foreach panelSeparator $leftPanelSeparator {
	    exec gconftool-2 --type=int -s ${panelSeparator}/position 1400
	}
	foreach panelSeparator $rightPanelSeparator {
	    exec gconftool-2 --type=int -s ${panelSeparator}/position 1400
	}
	
	if {[llength $workspaceNames($machine,0)] >= [llength $workspaceNames($machine,1)]} {
	    set numWS [llength $workspaceNames($machine,0)]
	} else {
	    set numWS [llength $workspaceNames($machine,1)]
	}
        }
    } else {
        if $wspRestart {
            RestartWorkSpace
        }
    }
    if {$statusCallback!=""} {
        $statusCallback "Pick choices from the list below."
    }
    set setupchoice [APSSDDSCheckButtons .cb -fileName $wspcomfile -parent $parent -column WorkSpaceName \
                       -arrayName wspChoiceArray -page 0 -limit 5 -duplicate 0 -modal 1]
    if {$setupchoice == 1} {
	if {$tcl_platform(os) == "Linux"} {
        if {!$multiMonitorWorkspace} {
	    #exec gconftool-2 --type=int -s /apps/metacity/general/num_workspaces 1
	    exec gconftool-2 --type=int -s /apps/metacity/general/num_workspaces $numWS
	    for {set i 1} {$i <= $numWS} {incr i} {
		set j [expr $i - 1]
		#exec gconftool-2 --type=string -s /apps/metacity/workspace_names/name_$i -- WorkSpace$i
                if {[llength [lindex $workspaceNames(${machine},0) $j]] && [llength [lindex $workspaceNames(${machine},1) $j]]} {
                    exec gconftool-2 --type=string -s /apps/metacity/workspace_names/name_$i -- "[lindex $workspaceNames(${machine},1) $j]//[lindex $workspaceNames(${machine},0) $j]"
                } elseif {[llength [lindex $workspaceNames(${machine},0) $j]]} {
                    exec gconftool-2 --type=string -s /apps/metacity/workspace_names/name_$i -- "//[lindex $workspaceNames(${machine},0) $j]"
                } elseif {[llength [lindex $workspaceNames(${machine},1) $j]]} {
                    exec gconftool-2 --type=string -s /apps/metacity/workspace_names/name_$i -- "[lindex $workspaceNames(${machine},1) $j]//"
                }
		
	    }
	    exec linuxWorkSpaceSwitcherApplet -screen 0 -rows 2 -workspaceNames "$workspaceNames(${machine},0)" -display :0.0 &
	    exec linuxWorkSpaceSwitcherApplet -screen 1 -rows 2 -workspaceNames "$workspaceNames(${machine},1)" -display :0.1 &
	} else {
#Workspace zero is expected to be the right window in the MCR
	    exec oagWindowManager -screen 0 -xrandrIndex 1 -rows 2 -wsNames "$workspaceNames(${machine},0)" &
            APSWaitWithUpdate -waitSeconds 2
	    exec oagWindowManager -screen 1 -xrandrIndex 0 -rows 2 -wsNames "$workspaceNames(${machine},1)" &
            APSWaitWithUpdate -waitSeconds 3
        }
        }
        if {$statusCallback!=""} {
            $statusCallback ""
        }
        if {![SetupMachineWorkspaces $machine $workspaces wspChoiceArray \
                wspoccurranceArray wspcommandArray wspDisplayArray -statusCallback $statusCallback]} {
            return 0
        }
        if {[info exists wspChoiceArray]} {unset wspChoiceArray}
    } else {
        if {$statusCallback!=""} {
            $statusCallback "Setup cancelled."
        }
        if {[info exists wspChoiceArray]} {unset wspChoiceArray}
    }
    return 1
}

proc RestartWorkSpace {args} {
    global wmResources
    set string "[exec ps -fed | grep dtwm]"
    set string [split $string \n]
    set pid ""
    foreach s $string {
        set i [string first "grep dtwm" $s]
        if {$i != -1} {
            continue
        }
        lappend pid [lindex $s 1]
    }
    foreach id $pid {
        exec kill -9 $id
    }
    exec xrdb -load $wmResources
    exec dtwm &

}

set medmLaunched($DisplayRoot:0.0) 0
set medmLaunched($DisplayRoot:0.1) 0


proc LaunchMedmForDisplay {display} {
    global medmLaunched 
    update
    if [lsearch [array names medmLaunched] $display]==-1 {
        return -code error -errorinfo "$display missing from array medmLaunched!"
    }
    if !$medmLaunched($display) {
    
        exec medm -display $display -x -attach >& /dev/null &
        after 750 
        raise .
        SetWSTStatus "Medm launched for $display"
    }
    incr medmLaunched($display) 
    if $medmLaunched($display)>=20 {
        set medmLaunched($display) 0
    }
}


APSApplication . -name "APSWorkspaceSetup" -version $CVSRevisionAuthor \
  -overview "This is an application to perform workspace setup for operating various accelerators. The setup configuration files are in /home/helios/oagData/workspaceSetups. The file README has the instructions for editing or creating a setup configuration."
set WSTStatus Ready.
APSScrolledStatus .status -textVariable WSTStatus -parent .userFrame -width 100 -packOption "-fill x"

# Button determines the resource file to load.
# For SR account, the resource file will be
# /home/helios/oagData/workspaceSetups/ted/SR-resources
APSRadioButtonFrame .setups -parent .userFrame \
  -label "Setups: " -variable mainDirectory \
  -buttonList {OAG ASDOPS} \
  -valueList  "/home/helios/oagData/workspaceSetups /home/helios/ASDOPS/workspaceSetups" \
  -orientation horizontal  \
  -contextHelp "Choose the setups that you want to use. The ASDOPS setups are designed by the Operations Group. The OAG setups are designed by the Operations Analysis Group."

set wspRestart 1 
#set wspRestart 0
if {$tcl_platform(os) != "Linux"} {
    APSCheckButtonFrame .restart -parent .userFrame.setups \
      -label "" -buttonList [list "Restart window manager"] \
      -variableList wspRestart \
      -packOption "-side top" \
      -orientation horizontal \
      -contextHelp "Check this is you want to restart the window manager with pre-set workspace names. Note that additional workspaces created up to now will be lost."
}

APSFrameGrid .mach -parent .userFrame -yList {catlist catlistRF} -relief ridge

pack .userFrame.mach -side top -fill x

APSButton .catlist.linac -parent .userFrame.mach \
  -text "Linac" -width "" \
  -command {RunMachineWorkSpaceSelect Linac } \
  -contextHelp "Brings up choices and buttons for LINAC workspace setup."
APSButton .catlist.its -parent .userFrame.mach \
  -text "ITS" -width "" \
  -command {RunMachineWorkSpaceSelect ITS } \
  -contextHelp "Brings up choices and buttons for ITS workspace setup."
APSButton .catlist.par -parent .userFrame.mach \
  -text "PAR" -width "" \
  -command {RunMachineWorkSpaceSelect PAR } \
  -contextHelp "Brings up choices and buttons for PAR workspace setup."
APSButton .catlist.booster -parent .userFrame.mach \
  -text "Booster" -width "" \
  -command {RunMachineWorkSpaceSelect Booster } \
  -contextHelp "Brings up choices and buttons for Booster workspace setup."
APSButton .catlist.sr -parent .userFrame.mach \
  -text "Storage Ring" -width "" \
  -command {RunMachineWorkSpaceSelect SR } \
  -contextHelp "Brings up choices and buttons for storage ring workspace setup."
APSButton .catlist.leutl -parent .userFrame.mach \
  -text "LEUTL" -width "" \
  -command {RunMachineWorkSpaceSelect LEUTL } \
  -contextHelp "Brings up choices and buttons for leutl workspace setup."
APSButton .catlist.laser -parent .userFrame.mach \
  -text "Laser" -width "" \
  -command {RunMachineWorkSpaceSelect Laser } \
  -contextHelp "Brings up choices and buttons for PC gun laser workspace setup."
APSButton .catlist.charis -parent .userFrame.mach \
  -text "Charis" -width "" \
  -command {RunMachineWorkSpaceSelect Charis_SR } \
  -contextHelp "Brings up choices and buttons for Charis workspace setup."
APSButton .catlist.phoenix -parent .userFrame.mach \
  -text "Phoenix" -width "" \
  -command {RunMachineWorkSpaceSelect Phoenix } \
  -contextHelp "Brings up choices and buttons for Phoenix workspace setup."

APSButton .catlistRF.sr -parent .userFrame.mach \
  -text "Storage Ring RF" -width "" \
  -command {RunMachineWorkSpaceSelect SRRF } \
  -contextHelp "Brings up choices and buttons for storage ring rf workspace setup."
APSButton .catlist.newop -parent .userFrame.mach \
  -text "New Operators" -width "" \
  -command {RunMachineWorkSpaceSelect NewOperators } \
  -contextHelp "Brings up choices and buttons to help new operators start a log book"
APSButton .catlist.diag -parent .userFrame.mach -text "Diagnostics" -width "" \
  -command {RunMachineWorkSpaceSelect DIAG} \
  -contextHelp "Brings up choices and buttons for diagnostics workspace setup"

APSButton .catlist.tornado -parent .userFrame.mach -text "Tornado" -width "" \
  -command {RunMachineWorkSpaceSelect Tornado} \
  -contextHelp "Brings up choices to set up remote workstation tornado"

APSButton .catlist.summit -parent .userFrame.mach -text "Summit" -width "" \
  -command {RunMachineWorkSpaceSelect Summit} \
  -contextHelp "Brings up workstation summit with rotating workspace displays"

APSButton .catlist.shutdown -parent .userFrame.mach -text "Shutdown" -width "" \
  -command {RunMachineWorkSpaceSelect Shutdown} \
  -contextHelp "Sets up workstations for shutdown activities"

proc SetWSTStatus {text} {
    global WSTStatus
    set WSTStatus $text     
    update
}

proc RunMachineWorkSpaceSelect {system} {
    DisableMachineChoiceButtons
    MachineWorkSpaceSelect $system -parent .userFrame  -statusCallback SetWSTStatus
    EnableMachineChoiceButtons
}

proc DisableMachineChoiceButtons {} {
    APSDisableButton .userFrame.mach.catlist.linac.button
    APSDisableButton .userFrame.mach.catlist.its.button
    APSDisableButton .userFrame.mach.catlist.par.button
    APSDisableButton .userFrame.mach.catlist.booster.button
    APSDisableButton .userFrame.mach.catlist.sr.button
    APSDisableButton .userFrame.mach.catlist.leutl.button
    APSDisableButton .userFrame.mach.catlist.laser.button
    APSDisableButton .userFrame.mach.catlistRF.sr.button
    APSDisableButton .userFrame.mach.catlist.charis.button
    APSDisableButton .userFrame.mach.catlist.phoenix.button
    APSDisableButton .userFrame.mach.catlist.newop.button
    APSDisableButton .userFrame.mach.catlist.diag.button
    APSDisableButton .userFrame.mach.catlist.tornado.button
    APSDisableButton .userFrame.mach.catlist.summit.button
    APSDisableButton .userFrame.mach.catlist.shutdown.button
}

proc EnableMachineChoiceButtons {} {
    APSEnableButton .userFrame.mach.catlist.linac.button
    APSEnableButton .userFrame.mach.catlist.its.button
    APSEnableButton .userFrame.mach.catlist.par.button
    APSEnableButton .userFrame.mach.catlist.booster.button
    APSEnableButton .userFrame.mach.catlist.sr.button
    APSEnableButton .userFrame.mach.catlist.leutl.button
    APSEnableButton .userFrame.mach.catlist.laser.button
    APSEnableButton .userFrame.mach.catlistRF.sr.button
    APSEnableButton .userFrame.mach.catlist.charis.button
    APSEnableButton .userFrame.mach.catlist.phoenix.button
    APSEnableButton .userFrame.mach.catlist.newop.button
    APSEnableButton .userFrame.mach.catlist.diag.button
    APSEnableButton .userFrame.mach.catlist.tornado.button
    APSEnableButton .userFrame.mach.catlist.summit.button
    APSEnableButton .userFrame.mach.catlist.shutdown.button
}




