source: trunk/gsascmds.tcl @ 673

Last change on this file since 673 was 673, checked in by toby, 14 years ago

# on 2003/04/10 22:13:02, toby did:
implement GRWND startup (Win-9x)
warn on names with spaces

  • Property rcs:author set to toby
  • Property rcs:date set to 2003/04/10 22:13:02
  • Property rcs:lines set to +62 -1
  • Property rcs:rev set to 1.49
  • Property rcs:state set to Exp
  • Property svn:keywords set to Author Date Revision Id
File size: 82.7 KB
Line 
1# $Id: gsascmds.tcl 673 2009-12-04 23:10:06Z toby $
2#------------------------------------------------------------------------------
3# display routines
4#------------------------------------------------------------------------------
5#       Message box code that centers the message box over the parent.
6#          or along the edge, if too close,
7#          but leave a border along +x & +y for reasons I don't remember
8#       It also allows the button names to be defined using
9#            -type $list  -- where $list has a list of button names
10#       larger messages are placed in a scrolled text widget
11#       capitalization is now ignored for -default
12#       The command returns the name button in all lower case letters
13#       otherwise see  tk_messageBox for a description
14#
15#       This is a modification of tkMessageBox (msgbox.tcl v1.5)
16#
17proc MyMessageBox {args} {
18    global tkPriv tcl_platform
19
20    set w tkPrivMsgBox
21    upvar #0 $w data
22
23    #
24    # The default value of the title is space (" ") not the empty string
25    # because for some window managers, a
26    #           wm title .foo ""
27    # causes the window title to be "foo" instead of the empty string.
28    #
29    set specs {
30        {-default "" "" ""}
31        {-icon "" "" "info"}
32        {-message "" "" ""}
33        {-parent "" "" .}
34        {-title "" "" " "}
35        {-type "" "" "ok"}
36        {-helplink "" "" ""}
37    }
38
39    tclParseConfigSpec $w $specs "" $args
40
41    if {[lsearch {info warning error question} $data(-icon)] == -1} {
42        error "bad -icon value \"$data(-icon)\": must be error, info, question, or warning"
43    }
44    if {![string compare $tcl_platform(platform) "macintosh"]} {
45      switch -- $data(-icon) {
46          "error"     {set data(-icon) "stop"}
47          "warning"   {set data(-icon) "caution"}
48          "info"      {set data(-icon) "note"}
49        }
50    }
51
52    if {![winfo exists $data(-parent)]} {
53        error "bad window path name \"$data(-parent)\""
54    }
55
56    switch -- $data(-type) {
57        abortretryignore {
58            set buttons {
59                {abort  -width 6 -text Abort -under 0}
60                {retry  -width 6 -text Retry -under 0}
61                {ignore -width 6 -text Ignore -under 0}
62            }
63        }
64        ok {
65            set buttons {
66                {ok -width 6 -text OK -under 0}
67            }
68          if {![string compare $data(-default) ""]} {
69                set data(-default) "ok"
70            }
71        }
72        okcancel {
73            set buttons {
74                {ok     -width 6 -text OK     -under 0}
75                {cancel -width 6 -text Cancel -under 0}
76            }
77        }
78        retrycancel {
79            set buttons {
80                {retry  -width 6 -text Retry  -under 0}
81                {cancel -width 6 -text Cancel -under 0}
82            }
83        }
84        yesno {
85            set buttons {
86                {yes    -width 6 -text Yes -under 0}
87                {no     -width 6 -text No  -under 0}
88            }
89        }
90        yesnocancel {
91            set buttons {
92                {yes    -width 6 -text Yes -under 0}
93                {no     -width 6 -text No  -under 0}
94                {cancel -width 6 -text Cancel -under 0}
95            }
96        }
97        default {
98#           error "bad -type value \"$data(-type)\": must be abortretryignore, ok, okcancel, retrycancel, yesno, or yesnocancel"
99            foreach item $data(-type) {
100                lappend buttons [list [string tolower $item] -text $item -under 0]
101            }
102        }
103    }
104
105    if {[string compare $data(-default) ""]} {
106        set valid 0
107        foreach btn $buttons {
108            if {![string compare [lindex $btn 0] [string tolower $data(-default)]]} {
109                set valid 1
110                break
111            }
112        }
113        if {!$valid} {
114            error "invalid default button \"$data(-default)\""
115        }
116    }
117
118    # 2. Set the dialog to be a child window of $parent
119    #
120    #
121    if {[string compare $data(-parent) .]} {
122        set w $data(-parent).__tk__messagebox
123    } else {
124        set w .__tk__messagebox
125    }
126
127    # 3. Create the top-level window and divide it into top
128    # and bottom parts.
129
130    catch {destroy $w}
131    toplevel $w -class Dialog
132    wm title $w $data(-title)
133    wm iconname $w Dialog
134    wm protocol $w WM_DELETE_WINDOW { }
135    wm transient $w $data(-parent)
136    if {![string compare $tcl_platform(platform) "macintosh"]} {
137        unsupported1 style $w dBoxProc
138    }
139
140    frame $w.bot
141    pack $w.bot -side bottom -fill both
142    frame $w.top
143    pack $w.top -side top -fill both -expand 1
144    if {$data(-helplink) != ""} {
145#       frame $w.help
146#       pack $w.help -side top -fill both
147        pack [button $w.top.1 -text Help -bg yellow \
148                -command "MakeWWWHelp $data(-helplink)"] \
149                -side right -anchor ne
150        bind $w <Key-F1> "MakeWWWHelp $data(-helplink)"
151    }
152    if {[string compare $tcl_platform(platform) "macintosh"]} {
153        $w.bot configure -relief raised -bd 1
154        $w.top configure -relief raised -bd 1
155    }
156
157    # 4. Fill the top part with bitmap and message (use the option
158    # database for -wraplength and -font so that they can be
159    # overridden by the caller).
160
161    option add *Dialog.msg.wrapLength 6i widgetDefault
162
163    if {[string length $data(-message)] > 300} {
164        if {![string compare $tcl_platform(platform) "macintosh"]} {
165            option add *Dialog.msg.t.font system widgetDefault
166        } else {
167            option add *Dialog.msg.t.font {Times 18} widgetDefault
168        }
169        frame $w.msg
170        grid [text  $w.msg.t  \
171                -height 20 -width 55 -relief flat -wrap word \
172                -yscrollcommand "$w.msg.rscr set" \
173                ] -row 1 -column 0 -sticky news
174        grid [scrollbar $w.msg.rscr  -command "$w.msg.t yview" \
175                ] -row 1 -column 1 -sticky ns
176        # give extra space to the text box
177        grid columnconfigure $w.msg 0 -weight 1
178        grid rowconfigure $w.msg 1 -weight 1
179        $w.msg.t insert end $data(-message)
180    } else {
181        if {![string compare $tcl_platform(platform) "macintosh"]} {
182            option add *Dialog.msg.font system widgetDefault
183        } else {
184            option add *Dialog.msg.font {Times 18} widgetDefault
185        }
186        label $w.msg -justify left -text $data(-message)
187    }
188    pack $w.msg -in $w.top -side right -expand 1 -fill both -padx 3m -pady 3m
189    if {[string compare $data(-icon) ""]} {
190        label $w.bitmap -bitmap $data(-icon)
191        pack $w.bitmap -in $w.top -side left -padx 3m -pady 3m
192    }
193
194    # 5. Create a row of buttons at the bottom of the dialog.
195
196    set i 0
197    foreach but $buttons {
198        set name [lindex $but 0]
199        set opts [lrange $but 1 end]
200      if {![llength $opts]} {
201            # Capitalize the first letter of $name
202          set capName [string toupper \
203                    [string index $name 0]][string range $name 1 end]
204            set opts [list -text $capName]
205        }
206
207      eval button [list $w.$name] $opts [list -command [list set tkPriv(button) $name]]
208
209        if {![string compare $name [string tolower $data(-default)]]} {
210            $w.$name configure -default active
211        }
212      pack $w.$name -in $w.bot -side left -expand 1 -padx 3m -pady 2m
213
214        # create the binding for the key accelerator, based on the underline
215        #
216        set underIdx [$w.$name cget -under]
217        if {$underIdx >= 0} {
218            set key [string index [$w.$name cget -text] $underIdx]
219          bind $w <Alt-[string tolower $key]>  [list $w.$name invoke]
220          bind $w <Alt-[string toupper $key]>  [list $w.$name invoke]
221        }
222        incr i
223    }
224
225    # 6. Create a binding for <Return> on the dialog if there is a
226    # default button.
227
228    if {[string compare $data(-default) ""]} {
229      bind $w <Return> [list tkButtonInvoke $w.[string tolower $data(-default)]]
230    }
231
232    # 7. Withdraw the window, then update all the geometry information
233    # so we know how big it wants to be, then center the window in the
234    # display and de-iconify it.
235
236    wm withdraw $w
237    update idletasks
238    set wp $data(-parent)
239    # center the new window in the middle of the parent
240    set x [expr [winfo x $wp] + [winfo width $wp]/2 - \
241            [winfo reqwidth $w]/2 - [winfo vrootx $wp]]
242    set y [expr [winfo y $wp] + [winfo height $wp]/2 - \
243            [winfo reqheight $w]/2 - [winfo vrooty $wp]]
244    # make sure that we can see the entire window
245    set xborder 10
246    set yborder 25
247    if {$x < 0} {set x 0}
248    if {$x+[winfo reqwidth $w] +$xborder > [winfo screenwidth $w]} {
249        incr x [expr \
250                [winfo screenwidth $w] - ($x+[winfo reqwidth $w] + $xborder)]
251    }
252    if {$y < 0} {set y 0}
253    if {$y+[winfo reqheight $w] +$yborder > [winfo screenheight $w]} {
254        incr y [expr \
255                [winfo screenheight $w] - ($y+[winfo reqheight $w] + $yborder)]
256    }
257    wm geom $w +$x+$y
258    wm deiconify $w
259
260    # 8. Set a grab and claim the focus too.
261
262    catch {set oldFocus [focus]}
263    catch {set oldGrab [grab current $w]}
264    catch {
265        grab $w
266        if {[string compare $data(-default) ""]} {
267            focus $w.[string tolower $data(-default)]
268        } else {
269            focus $w
270        }
271    }
272
273    # 9. Wait for the user to respond, then restore the focus and
274    # return the index of the selected button.  Restore the focus
275    # before deleting the window, since otherwise the window manager
276    # may take the focus away so we can't redirect it.  Finally,
277    # restore any grab that was in effect.
278
279    tkwait variable tkPriv(button)
280    catch {focus $oldFocus}
281    destroy $w
282    catch {grab $oldGrab}
283    return $tkPriv(button)
284}
285
286# tell'em what is happening
287#    message    is a text message to display
288#    statusvar  is a variable name containing a message that gets updated
289#    parent     is the name of the parent window
290#    button     defines a button for the window. Element 0 in $button is the
291#               text for the button and Element 1 is the command to execute.
292proc pleasewait {{message {}} {statusvar {}} {parent .} {button ""}} {
293    catch {destroy .msg}
294    toplevel .msg
295    wm transient .msg [winfo toplevel .]
296    pack [frame .msg.f -bd 4 -relief groove] -padx 5 -pady 5
297    pack [message .msg.f.m -text "Please wait $message"] -side top
298    if {$statusvar != ""} {
299        pack [label .msg.f.status -textvariable $statusvar] -side top
300    }
301    if {$button != ""} {
302        pack [button .msg.f.button -text [lindex $button 0] \
303                -command [lindex $button 1]] -side top
304    }
305    wm withdraw .msg
306    update idletasks
307    # place the message on top of the parent window
308    set x [expr [winfo x $parent] + [winfo width $parent]/2 - \
309            [winfo reqwidth .msg]/2 - [winfo vrootx $parent]]
310    if {$x < 0} {set x 0}
311    set y [expr [winfo y $parent] + [winfo height $parent]/2 - \
312            [winfo reqheight .msg]/2 - [winfo vrooty $parent]]
313    if {$y < 0} {set y 0}
314    wm geom .msg +$x+$y
315    wm deiconify .msg
316    global makenew
317    set makenew(OldGrab) ""
318    set makenew(OldFocus) ""
319    # save focus & grab
320    catch {set makenew(OldFocus) [focus]}
321    catch {set makenew(OldGrab) [grab current .msg]}
322    catch {grab .msg}
323    update
324}
325
326# clear the message
327proc donewait {} {
328    global makenew
329    catch {destroy .msg}
330    # reset focus & grab
331    catch {
332        if {$makenew(OldFocus) != ""} {
333            focus $makenew(OldFocus)
334        }
335    }
336    catch {
337        if {$makenew(OldGrab) != ""} {
338            grab $makenew(OldGrab)
339        }
340    }
341}
342
343proc putontop {w} {
344    # center window $w above its parent and make it stay on top
345    set wp [winfo parent $w]
346    wm transient $w [winfo toplevel $wp]
347    wm withdraw $w
348    update idletasks
349    # center the new window in the middle of the parent
350    set x [expr [winfo x $wp] + [winfo width $wp]/2 - \
351            [winfo reqwidth $w]/2 - [winfo vrootx $wp]]
352    if {$x < 0} {set x 0}
353    set xborder 10
354    if {$x+[winfo reqwidth $w] +$xborder > [winfo screenwidth $w]} {
355        incr x [expr \
356                [winfo screenwidth $w] - ($x+[winfo reqwidth $w] + $xborder)]
357    }
358    set y [expr [winfo y $wp] + [winfo height $wp]/2 - \
359            [winfo reqheight $w]/2 - [winfo vrooty $wp]]
360    if {$y < 0} {set y 0}
361    set yborder 25
362    if {$y+[winfo reqheight $w] +$yborder > [winfo screenheight $w]} {
363        incr y [expr \
364                [winfo screenheight $w] - ($y+[winfo reqheight $w] + $yborder)]
365    }
366    wm geom $w +$x+$y
367    wm deiconify $w
368
369    global makenew
370    set makenew(OldGrab) ""
371    set makenew(OldFocus) ""
372    catch {set makenew(OldFocus) [focus]}
373    catch {set makenew(OldGrab) [grab current $w]}
374    catch {grab $w}
375}
376
377proc afterputontop {} {
378    # restore focus
379    global makenew
380    # reset focus & grab
381    catch {
382        if {$makenew(OldFocus) != ""} {
383            focus $makenew(OldFocus)
384        }
385    }
386    catch {
387        if {$makenew(OldGrab) != ""} {
388            grab $makenew(OldGrab)
389        }
390    }
391}
392
393proc ShowBigMessage {win labeltext msg "optionlist OK" "link {}" "err 0"} {
394    catch {destroy $win}
395    toplevel $win
396
397    pack [label $win.l1 -text $labeltext] -side top
398    if {$err} {$win.l1 config -fg red}
399    pack [frame $win.f1] -side top -expand yes -fill both
400    grid [text  $win.f1.t  \
401            -height 20 -width 55  -wrap none -font Courier \
402            -xscrollcommand "$win.f1.bscr set" \
403            -yscrollcommand "$win.f1.rscr set" \
404            ] -row 1 -column 0 -sticky news
405    grid [scrollbar $win.f1.bscr -orient horizontal \
406            -command "$win.f1.t xview" \
407            ] -row 2 -column 0 -sticky ew
408    grid [scrollbar $win.f1.rscr  -command "$win.f1.t yview" \
409            ] -row 1 -column 1 -sticky ns
410    # give extra space to the text box
411    grid columnconfigure $win.f1 0 -weight 1
412    grid rowconfigure $win.f1 1 -weight 1
413    $win.f1.t insert end $msg
414
415    global makenew
416    set makenew(result) 0
417    bind $win <Return> "destroy $win"
418    bind $win <KeyPress-Prior> "$win.f1.t yview scroll -1 page"
419    bind $win <KeyPress-Next> "$win.f1.t yview scroll 1 page"
420    bind $win <KeyPress-Right> "$win.f1.t xview scroll 1 unit"
421    bind $win <KeyPress-Left> "$win.f1.t xview scroll -1 unit"
422    bind $win <KeyPress-Up> "$win.f1.t yview scroll -1 unit"
423    bind $win <KeyPress-Down> "$win.f1.t yview scroll 1 unit"
424    bind $win <KeyPress-Home> "$win.f1.t yview 0"
425    bind $win <KeyPress-End> "$win.f1.t yview end"
426    set i 0
427    foreach item $optionlist {
428        pack [button $win.q[incr i] \
429                -command "set makenew(result) $i; destroy $win" -text $item] -side left
430    }
431    if {$link != ""} {
432        pack [button $win.help -text Help -bg yellow \
433            -command "MakeWWWHelp $link"] \
434            -side right
435        bind $win <Key-F1> "MakeWWWHelp $link"
436    }
437    putontop $win
438    tkwait window $win
439
440    # fix grab...
441    afterputontop
442    return $makenew(result)
443}
444
445# get a value in a modal dialog
446proc getstring {what "chars 40" "quit 1" "initvalue {}"} {
447    global expgui expmap
448    set w .global
449    catch {destroy $w}
450    toplevel $w -bg beige
451    bind $w <Key-F1> "MakeWWWHelp expguierr.html Input[lindex $what 0]"
452    wm title $w "Input $what"
453    set expgui(temp) {}
454    pack [frame $w.0 -bd 6 -relief groove -bg beige] \
455            -side top -expand yes -fill both
456    grid [label $w.0.a -text "Input a value for the $what" \
457            -bg beige] \
458            -row 0 -column 0 -columnspan 10
459    grid [entry $w.0.b -textvariable expgui(temp) -width $chars] \
460            -row 1 -column 0 
461
462    set expgui(temp) $initvalue
463    pack [frame $w.b -bg beige] -side top -fill x -expand yes
464    pack [button $w.b.2 -text Set -command "destroy $w"] -side left
465    if $quit {
466        pack [button $w.b.3 -text Quit \
467                -command "set expgui(temp) {}; destroy $w"] -side left
468    }
469    bind $w <Return> "destroy $w"
470    pack [button $w.b.help -text Help -bg yellow \
471            -command "MakeWWWHelp expguierr.html Input[lindex $what 0]"] \
472            -side right
473
474    # force the window to stay on top
475    putontop $w
476
477    focus $w.b.2
478    tkwait window $w
479    afterputontop
480
481    return $expgui(temp)
482}
483
484#------------------------------------------------------------------------------
485# profile/symmetry routines
486#------------------------------------------------------------------------------
487# profile terms
488array set expgui {
489    prof-T-1 {alp-0 alp-1 bet-0 bet-1 sig-0 sig-1 sig-2 rstr rsta \
490            rsca s1ec s2ec }
491    prof-T-2 {alp-0 alp-1 beta switch sig-0 sig-1 sig-2 gam-0 gam-1 \
492            gam-2 ptec stec difc difa zero }
493    prof-T-3 {alp bet-0 bet-1 sig-0 sig-1 sig-2 gam-0 gam-1 \
494            gam-2 gsf g1ec g2ec rstr rsta rsca L11 L22 L33 L12 L13 L23 }
495    prof-T-4 {alp bet-0 bet-1 sig-1 sig-2 gam-2 g2ec gsf \
496            rstr rsta rsca eta}
497    prof-C-1 {GU GV GW asym F1 F2 }
498    prof-C-2 {GU GV GW LX LY trns asym shft GP stec ptec sfec \
499            L11 L22 L33 L12 L13 L23 }
500    prof-C-3 {GU GV GW GP LX LY S/L H/L trns shft stec ptec sfec \
501            L11 L22 L33 L12 L13 L23 }
502    prof-C-4 {GU GV GW GP LX ptec trns shft sfec S/L H/L eta} 
503    prof-E-1 {A B C ds cds}
504}
505
506# number of profile terms depends on the histogram type
507# the LAUE symmetry and the profile number
508proc GetProfileTerms {phase hist ptype} {
509    global expmap expgui
510    if {$hist == "C" || $hist == "T" || $hist == "E"} {
511        set htype $hist
512    } else {
513        set htype [string range $expmap(htype_$hist) 2 2]
514    }
515    # get the cached copy of the profile term labels, when possible
516    set lbls {}
517    catch {
518        set lbls $expmap(ProfileTerms${phase}_${ptype}_${htype})
519    }
520    if {$lbls != ""} {return $lbls}
521
522    catch {set lbls $expgui(prof-$htype-$ptype)}
523    if {$lbls == ""} {return}
524    # add terms based on the Laue symmetry
525    if {($htype == "C" || $htype == "T") && $ptype == 4} {
526        set laueaxis [GetLaue [phaseinfo $phase spacegroup]]
527        eval lappend lbls [Profile4Terms $laueaxis]
528    }
529    set expmap(ProfileTerms${phase}_${ptype}_${htype}) $lbls
530    return $lbls
531}
532
533proc Profile4Terms {laueaxis} {
534    switch -exact $laueaxis {
535        1bar {return \
536                "S400 S040 S004 S220 S202 S022 S310 S103 S031 \
537                S130 S301 S013 S211 S121 S112"}
538        2/ma {return "S400 S040 S004 S220 S202 S022 S013 S031 S211"}
539        2/mb {return "S400 S040 S004 S220 S202 S022 S301 S103 S121"}
540        2/mc {return "S400 S040 S004 S220 S202 S022 S130 S310 S112"}
541        mmm  {return "S400 S040 S004 S220 S202 S022"}
542        4/{return "S400 S004 S220 S202"}
543        4/mmm {return "S400 S004 S220 S202"}
544        3barR     {return "S400 S220 S310 S211"}
545        "3bar mR" {return "S400 S220 S310 S211"}
546        3bar    {return "S400 S004 S202 S211"}
547        3barm1 {return "S400 S004 S202"}
548        3bar1m  {return "S400 S004 S202 S211"}
549        6/m    {return "S400 S004 S202"}
550        6/mmm  {return "S400 S004 S202"}
551        "m 3"  {return "S400 S220"}
552        m3m    {return "S400 S220"}
553        default {return ""}
554    }
555}
556
557proc GetLaue {spg} {
558    global tcl_platform expgui
559    # check the space group
560    set fp [open spg.in w]
561    puts $fp "N"
562    puts $fp "N"
563    puts $fp $spg
564    puts $fp "Q"
565    close $fp
566    catch {
567        if {$tcl_platform(platform) == "windows"} {
568            exec [file join $expgui(gsasexe) spcgroup.exe] < spg.in >& spg.out
569        } else {
570            exec [file join $expgui(gsasexe) spcgroup] < spg.in >& spg.out
571        }
572    }
573    set fp [open spg.out r]
574    set laue {}
575    set uniqueaxis {}
576    while {[gets $fp line] >= 0} {
577        regexp {Laue symmetry (.*)} $line junk laue
578        regexp {The unique axis is (.*)} $line junk uniqueaxis
579    }
580    close $fp
581    catch {file delete -force spg.in spg.out}
582    set laue [string trim $laue]
583    # add a R suffix for rhombohedral settings
584    if {[string range [string trim $spg] end end] == "R"} {
585        return "${laue}${uniqueaxis}R"
586    }
587    return "${laue}$uniqueaxis"
588}
589
590# set up to change the profile type for a series of histogram/phase entries
591# (histlist & phaselist should be lists of the same length)
592#
593proc ChangeProfileType {histlist phaselist} {
594    global expgui expmap
595    set w .profile
596    catch {destroy $w}
597    toplevel $w -bg beige
598    wm title $w "Change Profile Function"
599   
600    # all histogram/phases better be the same type, so we can just use the 1st
601    set hist [lindex $histlist 0]
602    set phase [lindex $phaselist 0]
603    set ptype [string trim [hapinfo $hist $phase proftype]]
604
605    # get list of allowed profile terms for the current histogram type
606    set i 1
607    while {[set lbls [GetProfileTerms $phase $hist $i]] != ""} {
608        lappend lbllist $lbls
609        incr i
610    }
611    # labels for the current type
612    set i $ptype
613    set oldlbls [lindex $lbllist [incr i -1]]
614   
615    if {[llength $histlist] == 1} {
616        pack [label $w.a -bg beige \
617                -text "Change profile function for Histogram #$hist Phase #$phase" \
618                ] -side top
619    } else {
620        # make a list of histograms by phase
621        foreach h $histlist p $phaselist {
622            lappend phlist($p) $h
623        }
624        set num 0
625        pack [frame $w.a -bg beige] -side top
626        pack [label $w.a.$num -bg beige \
627                -text "Change profile function for:" \
628                ] -side top -anchor w
629        foreach i [lsort [array names phlist]] {
630            incr num
631            pack [label $w.a.$num -bg beige -text \
632                    "\tPhase #$i, Histograms [CompressList $phlist($i)]" \
633                    ] -side top -anchor w
634        }
635    }
636    pack [label $w.e1 \
637            -text "Current function is type $ptype." \
638            -bg beige] -side top -anchor w
639    pack [frame $w.e -bg beige] -side top -expand yes -fill both
640    pack [label $w.e.1 \
641            -text "Set function to type" \
642            -bg beige] -side left
643    set menu [tk_optionMenu $w.e.2 expgui(newpeaktype) junk]
644    pack $w.e.2 -side left -anchor w
645
646    pack [radiobutton $w.e.4 -bg beige -variable expgui(DefaultPeakType) \
647            -command "set expgui(newpeaktype) $ptype; \
648            FillChangeProfileType $w.c $hist $phase $ptype [list $oldlbls] [list $oldlbls]" \
649            -value 1 -text "Current value overrides"] -side right
650    pack [radiobutton $w.e.3 -bg beige -variable expgui(DefaultPeakType) \
651            -command \
652            "set expgui(newpeaktype) $ptype; \
653            FillChangeProfileType $w.c $hist $phase $ptype [list $oldlbls] [list $oldlbls]" \
654            -value 0 -text "Default value overrides"] -side right
655
656    $w.e.2 config -bg beige
657    pack [frame $w.c -bg beige] -side top -expand yes -fill both
658    pack [frame $w.d -bg beige] -side top -expand yes -fill both
659    pack [button $w.d.2 -text Set  \
660            -command "SaveChangeProfileType $w.c $histlist $phaselist; destroy $w"\
661            ] -side left
662    pack [button $w.d.3 -text Quit \
663            -command "destroy $w"] -side left
664    pack [button $w.d.help -text Help -bg yellow \
665            -command "MakeWWWHelp expgui5.html ChangeType"] \
666            -side right
667    bind $w <Key-F1> "MakeWWWHelp expgui5.html ChangeType"
668    bind $w <Return> "destroy $w"
669
670    $menu delete 0 end
671    set i 0
672    foreach lbls $lbllist {
673        incr i
674        $menu add command -label $i -command \
675                "set expgui(newpeaktype) $i; \
676                FillChangeProfileType $w.c $hist $phase $i [list $lbls] [list $oldlbls]"
677    }
678    set expgui(newpeaktype) $ptype
679    FillChangeProfileType $w.c $hist $phase $ptype $oldlbls $oldlbls
680
681    # force the window to stay on top
682    putontop $w
683    focus $w.e.2
684    tkwait window $w
685    afterputontop
686    sethistlist
687}
688
689# save the changes to the profile
690proc SaveChangeProfileType {w histlist phaselist} {
691    global expgui
692    foreach phase $phaselist hist $histlist {
693        hapinfo $hist $phase proftype set $expgui(newpeaktype)
694        hapinfo $hist $phase profterms set $expgui(newProfileTerms)
695        for {set i 1} {$i <=  $expgui(newProfileTerms)} {incr i} {
696            hapinfo $hist $phase pterm$i set [$w.ent${i} get]
697            hapinfo $hist $phase pref$i set $expgui(ProfRef$i)
698        }
699        set i [expr 1+$expgui(newProfileTerms)]
700        hapinfo $hist $phase pcut set [$w.ent$i get]
701        incr expgui(changed) [expr 3 + $expgui(newProfileTerms)]
702    }
703}
704
705# file the contents of the "Change Profile Type" Menu
706proc FillChangeProfileType {w hist phase newtype lbls oldlbls} {
707    global expgui expmap
708    set ptype [string trim [hapinfo $hist $phase proftype]]
709    catch {unset oldval}
710    # loop through the old terms and set up an array of starting values
711    set num 0
712    foreach term $oldlbls {
713        incr num
714        set oldval($term) [hapinfo $hist $phase pterm$num]
715    }
716    set oldval(Peak\nCutoff) [hapinfo $hist $phase pcut]
717
718    # is the new type the same as the current?
719    if {$ptype == $newtype} {
720        set nterms [hapinfo $hist $phase profterms]
721    } else {
722        set nterms [llength $lbls]
723    }
724    set expgui(newProfileTerms) $nterms
725    set expgui(CurrentProfileTerms) $nterms
726    # which default profile set matches the new type
727    set setnum {}
728    foreach j {" " 1 2 3 4 5 6 7 8 9} {
729        set i [profdefinfo $hist $j proftype]
730        if {$i == ""} continue
731        if {$i == $newtype} {
732            set setnum $j
733            break
734        }
735    }
736
737    eval destroy [winfo children $w]
738
739    set colstr 0
740    set row 2
741    set maxrow [expr $row + $nterms/2]
742    for { set num 1 } { $num <= $nterms + 1} { incr num } {
743        # get the default value (originally from the in .INS file)
744        set val {}
745        if {$setnum != ""} {
746            set val 0.0
747            catch {
748                set val [profdefinfo $hist $setnum pterm$num]
749                # pretty up the number
750                if {$val == 0.0} {
751                    set val 0.0
752                } elseif {abs($val) < 1e-2 || abs($val) > 1e6} {
753                    set val [format %.3e $val]
754                } elseif {abs($val) > 1e-2 && abs($val) < 10} {
755                    set val [format %.5f $val]
756                } elseif {abs($val) < 9999} {
757                    set val [format %.2f $val]
758                } elseif {abs($val) < 1e6} {
759                    set val [format %.0f $val]
760                }
761            }
762        }
763        # heading
764        if {$row == 2} {
765            set col $colstr
766            grid [label $w.h0${num} -text "lbl" -bg beige] \
767                -row $row -column $col
768            grid [label $w.h2${num} -text "ref" -bg beige] \
769                -row $row -column [incr col]
770            grid [label $w.h3${num} -text "next value" -bg beige] \
771                -row $row -column [incr col]
772            grid [label $w.h4${num} -text "default" -bg beige] \
773                -row $row -column [incr col]
774            grid [label $w.h5${num} -text "current" -bg beige] \
775                -row $row -column [incr col]
776        }
777        set col $colstr
778        incr row
779        set term {}
780        catch {set term [lindex $lbls [expr $num-1]]}
781        if {$term == ""} {set term $num}
782        if {$num == $nterms + 1} {
783            set term "Peak\nCutoff"
784            set val {}
785            if {$setnum != ""} {
786                set val 0.0
787                catch {set val [profdefinfo $hist $setnum pcut]}
788            }
789        }
790
791        grid [label $w.l${num} -text "$term" -bg beige] \
792                -row $row -column $col
793        grid [checkbutton $w.chk${num} -variable expgui(ProfRef$num) \
794                -bg beige -activebackground beige] -row $row -column [incr col]
795        grid [entry $w.ent${num} \
796                -width 12] -row $row -column [incr col]
797        if {$val != ""} {
798            grid [button $w.def${num} -text $val -command \
799                    "$w.ent${num} delete 0 end; $w.ent${num} insert end $val" \
800                    ] -row $row -column [incr col] -sticky ew
801        } else {
802            grid [label $w.def${num} -text (none) \
803                    ] -row $row -column [incr col]
804        }
805        set curval {}
806        catch {
807            set curval [expr $oldval($term)]
808            # pretty up the number
809            if {$curval == 0.0} {
810                set curval 0.0
811            } elseif {abs($curval) < 1e-2 || abs($curval) > 1e6} {
812                set curval [format %.3e $curval]
813            } elseif {abs($curval) > 1e-2 && abs($curval) < 10} {
814                set curval [format %.5f $curval]
815            } elseif {abs($curval) < 9999} {
816                set curval [format %.2f $curval]
817            } elseif {abs($curval) < 1e6} {
818                set curval [format %.0f $curval]
819            }
820            grid [button $w.cur${num} -text $curval -command  \
821                    "$w.ent${num} delete 0 end; $w.ent${num} insert end $curval" \
822                    ] -row $row -column [incr col] -sticky ew
823        }
824        # set default values for flag and value
825        set ref 0
826        if {$setnum != ""} {
827            catch {
828                if {[profdefinfo $hist $setnum pref$num] == "Y"} {set ref 1}
829            }
830        }
831        set expgui(ProfRef$num) $ref
832       
833        $w.ent${num} delete 0 end
834        if {!$expgui(DefaultPeakType) && $val != ""} {
835            $w.ent${num} insert end $val
836        } elseif {$curval != ""} {
837            $w.ent${num} insert end $curval
838        } elseif {$val != ""} {
839            $w.ent${num} insert end $val
840        } else {
841            $w.ent${num} insert end 0.0
842        }
843        if {$row > $maxrow} {
844            set row 2
845            incr colstr 5
846        }
847    }
848}
849
850#------------------------------------------------------------------------------
851# WWW/help routines
852#------------------------------------------------------------------------------
853# browse a WWW page with URL. The URL may contain a #anchor
854# On UNIX assume netscape is in the path or env(BROWSER) is loaded.
855# On Windows search the registry for a browser. Mac branch not tested.
856# This is taken from http://mini.net/cgi-bin/wikit/557.html with many thanks
857# to the contributers
858proc urlOpen {url} {
859    global env tcl_platform
860    switch $tcl_platform(platform) {
861        "unix" {
862            if {![info exists env(BROWSER)]} {
863                set progs [auto_execok netscape]
864                if {[llength $progs]} {
865                    set env(BROWSER) [list $progs]
866                }
867            }
868            if {[info exists env(BROWSER)]} {
869                if {[catch {exec $env(BROWSER) -remote openURL($url)}]} {
870                    # perhaps browser doesn't understand -remote flag
871                    if {[catch {exec $env(BROWSER) $url &} emsg]} {
872                        error "Error displaying $url in browser\n$emsg"
873                    }
874                }
875            } else {
876                MyMessageBox -parent . -title "No Browser" \
877                        -message "Could not find a browser. Netscape is not in path. Define environment variable BROWSER to be full path name of browser." \
878                        -icon warn
879            }
880        }
881        "windows" {
882            package require registry
883            # Look for the application under
884            # HKEY_CLASSES_ROOT
885            set root HKEY_CLASSES_ROOT
886
887            # Get the application key for HTML files
888            set appKey [registry get $root\\.html ""]
889
890            # Get the command for opening HTML files
891            set appCmd [registry get \
892                    $root\\$appKey\\shell\\open\\command ""]
893
894            # Substitute the HTML filename into the command for %1
895            # or stick it on the end
896            if {[string first %1 $appCmd] != -1} {
897                regsub %1 $appCmd $url appCmd
898            } else {
899                append appCmd " " $url
900            }
901           
902            # Double up the backslashes for eval (below)
903            regsub -all {\\} $appCmd  {\\\\} appCmd
904           
905            # Invoke the command
906            eval exec $appCmd &
907        }
908        "macintosh" {
909            if {0 == [info exists env(BROWSER)]} {
910                set env(BROWSER) "Browse the Internet"
911            }
912            if {[catch {
913                AppleScript execute\
914                    "tell application \"$env(BROWSER)\"
915                         open url \"$url\"
916                     end tell
917                "} emsg]
918            } then {
919                error "Error displaying $url in browser\n$emsg"
920            }
921        }
922    }
923}
924
925proc NetHelp {file anchor localloc netloc} {
926    if {[file exists [file join $localloc $file]]} {
927        set url "[file join $localloc $file]"
928    } else {
929        set url "http://$netloc/$file"
930    }
931    catch {
932        pleasewait "Starting web browser..."
933        after 2000 donewait
934    }
935    if {$anchor != ""} {
936        append url # $anchor
937    }
938    urlOpen $url
939}
940
941proc MakeWWWHelp {"topic {}" "anchor {}"} {
942    global expgui
943    if {$topic == ""} {
944        foreach item $expgui(notebookpagelist) {
945            if {[lindex $item 0] == $expgui(pagenow)} {
946                NetHelp [lindex $item 5] [lindex $item 6] $expgui(docdir) $expgui(website)
947                return
948            }
949        }
950        # this should not happen
951        NetHelp expgui.html "" $expgui(docdir) $expgui(website)
952    } elseif {$topic == "menu"} {
953        NetHelp expguic.html "" $expgui(docdir) $expgui(website)
954    } else {
955        NetHelp $topic $anchor $expgui(docdir) $expgui(website)
956    }
957}
958
959# show help information
960proc showhelp {} {
961    global expgui_helplist helpmsg
962    set helpmsg {}
963    set frm .help
964    catch {destroy $frm}
965    toplevel $frm
966    wm title $frm "Help Summary"
967    grid [label $frm.0 -text \
968            "Click on an entry below to see information on the EXPGUI/GSAS topic" ] \
969        -column 0 -columnspan 4 -row 0
970#    grid [message $frm.help -textvariable helpmsg -relief groove] \
971#          -column 0 -columnspan 4 -row 2 -sticky nsew
972    grid [text $frm.help -relief groove -bg beige -width 0\
973            -height 0 -wrap word -yscrollcommand "$frm.escroll set"] \
974           -column 0 -columnspan 3 -row 2 -sticky nsew
975    grid [scrollbar $frm.escroll -command "$frm.help yview"] \
976            -column 4 -row 2 -sticky nsew
977    grid rowconfig $frm 1 -weight 1 -minsize 50
978    grid rowconfig $frm 2 -weight 2 -pad 20 -minsize 150
979    grid columnconfig $frm 0 -weight 1
980    grid columnconfig $frm 2 -weight 1
981    set lst [array names expgui_helplist]
982    grid [listbox $frm.cmds -relief raised -bd 2 \
983            -yscrollcommand "$frm.scroll set" \
984            -height 8 -width 0 -exportselection 0 ] \
985            -column 0 -row 1 -sticky nse
986    grid [scrollbar $frm.scroll -command "$frm.cmds yview"] \
987            -column 1 -row 1 -sticky nsew
988    foreach item [lsort -dictionary $lst] {
989        $frm.cmds insert end $item 
990    }
991    if {[$frm.cmds curselection] == ""} {$frm.cmds selection set 0}
992    grid [button $frm.done -text Done -command "destroy $frm"] \
993            -column 2 -row 1
994#    bind $frm.cmds <ButtonRelease-1> \
995#           "+set helpmsg \$expgui_helplist(\[$frm.cmds get \[$frm.cmds curselection\]\])"
996    bind $frm.cmds <ButtonRelease-1> \
997            "+$frm.help config -state normal; $frm.help delete 0.0 end; \
998             $frm.help insert end \$expgui_helplist(\[$frm.cmds get \[$frm.cmds curselection\]\]); \
999             $frm.help config -state disabled"
1000
1001    # get the size of the window and expand the message boxes to match
1002#    update
1003#    $frm.help config -width [winfo width $frm.help ]
1004}
1005
1006
1007#------------------------------------------------------------------------------
1008# utilities
1009#------------------------------------------------------------------------------
1010# run liveplot
1011proc liveplot {} {
1012    global expgui liveplot wishshell expmap
1013    set expnam [file root [file tail $expgui(expfile)]]
1014    # which histograms are ready for use?
1015    set validlist {}
1016    foreach ihist $expmap(powderlist) {
1017        if {[string trim [string range $expmap(htype_$ihist) 3 3]] == "" || \
1018                [string range $expmap(htype_$ihist) 3 3] == "D"} {
1019            lappend validlist $ihist
1020        }
1021    }
1022    if {[llength $validlist] == 0} {
1023        MyMessageBox -parent . -title "No Valid Histograms" \
1024                -message "No histograms are ready to plot. Run GENLES and try again" \
1025                -icon warning -helplink "expguierr.html NoValidHist"
1026        return
1027    }
1028    # use $liveplot(hst) if valid, the 1st entry otherwise
1029    if {[lsearch $validlist $liveplot(hst)] != -1} {
1030        exec $wishshell [file join $expgui(scriptdir) liveplot] \
1031                $expnam $liveplot(hst) $liveplot(legend) &
1032    } else {
1033        exec $wishshell [file join $expgui(scriptdir) liveplot] \
1034                $expnam [lindex $validlist 0] $liveplot(legend) &
1035    }
1036}
1037
1038# run lstview
1039proc lstview {} {
1040    global expgui wishshell
1041    set expnam [file root [file tail $expgui(expfile)]]
1042    exec $wishshell [file join $expgui(scriptdir) lstview] $expnam &
1043}
1044
1045# run widplt
1046proc widplt {"prog widplt"} {
1047    global expgui wishshell
1048    exec $wishshell [file join $expgui(scriptdir) $prog] \
1049            $expgui(expfile) &
1050}
1051
1052# run bkgedit
1053proc bkgedit {"hst {}"} {
1054    global expgui liveplot wishshell expmap
1055    set expnam [file root [file tail $expgui(expfile)]]
1056    if {$hst == ""} {
1057        # which histograms are ready for use?
1058        set validlist {}
1059        foreach ihist $expmap(powderlist) {
1060            if {[string trim [string range $expmap(htype_$ihist) 3 3]] == "" || \
1061                    [string range $expmap(htype_$ihist) 3 3] == "*"} {
1062                lappend validlist $ihist
1063            }
1064        }
1065        if {[llength $validlist] == 0} {
1066            MyMessageBox -parent . -title "No Valid Histograms" \
1067                    -message "No histograms are ready to plot. Run POWPREF and try again" \
1068                    -icon warning -helplink "expguierr.html NoValidHist"
1069            return
1070        }
1071        # use $liveplot(hst) if valid, the 1st entry otherwise
1072        if {[lsearch $validlist $liveplot(hst)] != -1} {
1073            set hst $liveplot(hst)
1074        } else {
1075            set hst [lindex $validlist 0]
1076        }
1077    }
1078    if {$expgui(autoiconify)} {wm iconify .}
1079    exec $wishshell [file join $expgui(scriptdir) bkgedit] \
1080            $expnam $hst $liveplot(legend)
1081    if {$expgui(autoiconify)} {wm deiconify .}
1082    # check for changes in the .EXP file immediately
1083    whenidle
1084}
1085
1086# run excledt
1087proc excledit {} {
1088    global expgui liveplot wishshell expmap
1089    set expnam [file root [file tail $expgui(expfile)]]
1090    # which histograms are ready for use?
1091    set validlist {}
1092    foreach ihist $expmap(powderlist) {
1093        if {[string trim [string range $expmap(htype_$ihist) 3 3]] == "" || \
1094                [string range $expmap(htype_$ihist) 3 3] == "*" || \
1095                [string range $expmap(htype_$ihist) 3 3] == "D"} {
1096            lappend validlist $ihist
1097        }
1098    }
1099    if {[llength $validlist] == 0} {
1100        MyMessageBox -parent . -title "No Valid Histograms" \
1101                -message "No histograms are ready to plot. Run POWPREF and try again" \
1102                -icon warning -helplink "expguierr.html NoValidHist"
1103        return
1104    }
1105    #if {$expgui(autoiconify)} {wm iconify .}
1106    StartExcl 
1107    #if {$expgui(autoiconify)} {wm deiconify .}
1108}
1109
1110# compute the composition for each phase and display in a dialog
1111proc composition {} {
1112    global expmap expgui
1113    set Z 1
1114    foreach phase $expmap(phaselist) type $expmap(phasetype) {
1115        if {$type > 2} continue
1116        catch {unset total}
1117        foreach atom $expmap(atomlist_$phase) {
1118            set type [atominfo $phase $atom type]
1119            set mult [atominfo $phase $atom mult]
1120            if [catch {set total($type)}] {
1121                set total($type) [expr \
1122                        $mult * [atominfo $phase $atom frac]]
1123            } else {
1124                set total($type) [expr $total($type) + \
1125                        $mult * [atominfo $phase $atom frac]]
1126            }
1127            if {$mult > $Z} {set Z $mult}
1128        }
1129        append text "\nPhase $phase\n"
1130        append text "  Unit cell contents\n"
1131        foreach type [lsort [array names total]] {
1132            append text "   $type[format %8.3f $total($type)]"
1133        }
1134        append text "\n\n"
1135       
1136        append text "  Asymmetric Unit contents (Z=$Z)\n"
1137        foreach type [lsort [array names total]] {
1138            append text "   $type[format %8.3f [expr $total($type)/$Z]]"
1139        }
1140        append text "\n"
1141    }
1142   
1143    catch {destroy .comp}
1144    toplevel .comp -class MonoSpc
1145    bind .comp <Key-F1> "MakeWWWHelp expgui.html Composition"
1146    wm title .comp Composition
1147    pack [label .comp.results -text $text \
1148            -justify left] -side top
1149    pack [frame .comp.box]  -side top -expand y -fill x
1150    pack [button .comp.box.1 -text Close -command "destroy .comp"] -side left
1151
1152    set lstnam [string toupper [file tail [file rootname $expgui(expfile)].LST]]
1153    pack [button .comp.box.2 -text "Save to $lstnam file" \
1154            -command "writelst [list $text] ; destroy .comp"] -side left
1155    pack [button .comp.box.help -text Help -bg yellow \
1156            -command "MakeWWWHelp expgui.html Composition"] \
1157            -side right
1158}
1159
1160# Delete History Records
1161proc DeleteHistoryRecords {{msg ""}} {
1162    global expgui
1163    set frm .history
1164    catch {destroy $frm}
1165    toplevel $frm
1166    bind $frm <Key-F1> "MakeWWWHelp expgui.html DeleteHistoryRecords"
1167    if {[string trim $msg] == ""} {
1168        set msg "There are [CountHistory] history records"
1169    }
1170    pack [frame $frm.1 -bd 2 -relief groove] -padx 3 -pady 3 -side left
1171    pack [label $frm.1.0 -text $msg] -side top
1172    pack [frame $frm.1.1] -side top
1173    pack [label $frm.1.1.1 -text "Number of entries to keep"] -side left
1174    pack [entry $frm.1.1.2 -width 3 -textvariable expgui(historyKeep)\
1175            ] -side left
1176    set expgui(historyKeep) 10
1177    pack [checkbutton $frm.1.2 -text renumber -variable expgui(renumber)] -side top
1178    set expgui(renumber) 1
1179    pack [frame $frm.2] -padx 3 -pady 3 -side left -fill both -expand yes
1180    pack [button $frm.2.help -text Help -bg yellow \
1181            -command "MakeWWWHelp expgui.html DeleteHistoryRecords"] -side top
1182    pack [button $frm.2.4 -text Quit \
1183            -command {destroy .history}] -side bottom
1184    pack [button $frm.2.3 -text OK \
1185            -command { 
1186        if ![catch {expr $expgui(historyKeep)}] {
1187            DeleteHistory $expgui(historyKeep) $expgui(renumber)
1188            set expgui(changed) 1
1189            destroy .history
1190        }
1191    }] -side bottom
1192    bind $frm <Return> "$frm.2.3 invoke"
1193   
1194    # force the window to stay on top
1195    putontop $frm 
1196    focus $frm.2.3
1197    tkwait window $frm
1198    afterputontop
1199}
1200
1201proc archiveexp {} {
1202    global expgui tcl_platform
1203    # is there a file to archive?
1204    if {![file exists $expgui(expfile)]} return
1205    set expnam [file rootname $expgui(expfile)]
1206    # get the last archived version
1207    set lastf [lindex [lsort [glob -nocomplain $expnam.{O\[0-9A-F\]\[0-9A-F\]}]] end]
1208    if {$lastf == ""} {
1209        set num 01
1210    } else {
1211        regexp {.*\.O([0-9A-F][0-9A-F])$} $lastf a num
1212        scan $num %x num
1213        if {$num >= 255} {
1214            set num FF
1215        } else {
1216            set num [string toupper [format %.2x [incr num]]]
1217        }
1218    }
1219    catch {
1220        set file $expnam.O$num
1221        file rename -force $expgui(expfile) $file
1222        set fp [open $expnam.LST a+]
1223        puts $fp "\n----------------------------------------------"
1224        puts $fp "     Archiving [file tail $expnam.EXP] as [file tail $file]"
1225        puts $fp "----------------------------------------------\n"
1226        close $fp
1227    } errmsg
1228    if {$errmsg != ""} {
1229        tk_dialog .warn Confirm "Error archiving the current .EXP file: $errmsg" warning 0 OK
1230    }
1231}
1232
1233# save and optionally archive the expfile
1234proc savearchiveexp {} {
1235    global expgui expmap
1236    if {$expgui(expfile) == ""} {
1237        SaveAsFile
1238        return
1239    }
1240    if !$expgui(changed) return
1241    if {$expgui(archive)} archiveexp
1242    # add a history record
1243    exphistory add " EXPGUI [lindex $expgui(Revision) 1] [lindex $expmap(Revision) 1] ($expgui(changed) changes) -- [clock format [clock seconds]]"
1244    # now save the file
1245    expwrite $expgui(expfile)
1246    set expgui(changed) 0
1247    set expgui(expModifiedLast) [file mtime $expgui(expfile)]
1248    set expgui(last_History) [string range [string trim [lindex [exphistory last] 1]] 0 50 ]
1249    wm title . $expgui(expfile)
1250    set expgui(titleunchanged) 1
1251    # set convergence criterion
1252    InitLSvars
1253}
1254
1255#------------------------------------------------------------------------------
1256# GSAS interface routines
1257#------------------------------------------------------------------------------
1258# run a GSAS program that does not require an experiment file
1259proc runGSASprog {proglist "concurrent 1"} {
1260    # if concurrent is 0, EXPGUI runs the GSAS program in background
1261    # -- this is not currently needed anywhere where the .EXP file is not.
1262    global expgui tcl_platform
1263    set cmd {}
1264    foreach prog $proglist {
1265        StartGRWND $prog
1266        if {$tcl_platform(platform) == "windows"} {
1267            append cmd " \"$expgui(gsasexe)/${prog}.exe \" "
1268        } else {
1269            if {$cmd != ""} {append cmd "\;"}
1270            append cmd "[file join $expgui(gsasexe) $prog]"
1271        }
1272    }
1273    forknewterm $prog $cmd [expr !$concurrent] 1
1274}
1275
1276# dummy routine, overridden if needed
1277proc StartGRWND {prog} {
1278}
1279
1280# run a GSAS program that requires an experiment file for input/output
1281proc runGSASwEXP {proglist "concurrent 0"} {
1282    # most programs that require the .EXP file change it and
1283    # cannot be run concurrently
1284    global expgui tcl_platform
1285    # Save the current exp file
1286    savearchiveexp
1287    # load the changed .EXP file automatically?
1288    if {$expgui(autoexpload)} {
1289        # disable the file changed monitor
1290        set expgui(expModifiedLast) 0
1291    }
1292    set cmd {}
1293    set expnam [file root [file tail $expgui(expfile)]]
1294    foreach prog $proglist {
1295        if {$prog == "powpref"} {
1296            set expgui(needpowpref) 0
1297            set expgui(needpowpref_why) ""
1298        } elseif {$prog == "genles" && $expgui(needpowpref) != 0} {
1299            set msg "You are attempting to run GENLES, after making changes that require POWPREF:\n\n$expgui(needpowpref_why) \nRun POWPREF first?"
1300            set ans [MyMessageBox -parent . -title "Run POWPREF" \
1301                    -message $msg -icon warning -type "Yes No" -default yes \
1302                    -helplink "expguierr.html RunPowpref"]
1303            if {$ans == "yes"} {
1304                set expgui(needpowpref) 0
1305                set expgui(needpowpref_why) ""
1306                if {$tcl_platform(platform) == "windows"} {
1307                    append cmd " \"$expgui(gsasexe)/powpref.exe $expnam \" "
1308                } else {
1309                    if {$cmd != ""} {append cmd "\;"}
1310                    append cmd "[file join $expgui(gsasexe) powpref] $expnam"
1311                }
1312            }
1313        }
1314        StartGRWND $prog
1315        if {$tcl_platform(platform) == "windows"} {
1316            append cmd " \"$expgui(gsasexe)/${prog}.exe $expnam \" "
1317        } else {
1318            if {$cmd != ""} {append cmd "\;"}
1319            append cmd "[file join $expgui(gsasexe) $prog] $expnam"
1320        }
1321    }
1322    forknewterm "$prog -- $expnam" $cmd [expr !$concurrent] 1
1323    # load the changed .EXP file automatically?
1324    if {$expgui(autoexpload)} {
1325        # load the revised exp file
1326        loadexp $expgui(expfile)
1327    }
1328}
1329
1330# write text to the .LST file
1331proc writelst {text} {
1332    global expgui
1333    set lstnam [file rootname $expgui(expfile)].LST
1334    set fp [open $lstnam a]
1335    puts $fp "\n-----------------------------------------------------------------"
1336    puts $fp $text
1337    puts $fp "-----------------------------------------------------------------\n"
1338    close $fp
1339}
1340
1341
1342# rename file current to suggested,
1343#   delete window if supplied
1344#   use parent, if supplied or .
1345proc RenameAsFile {current suggested "window {}" "parent {}"} {
1346    if {$parent == "" && $window != ""} {set parent $window}
1347    if {$parent == ""} {set parent .}
1348    set newfile [tk_getSaveFile -initialfile $suggested -parent $parent]
1349    if {$newfile == ""} return
1350    file rename -force $current $newfile
1351    if {$window != ""} {destroy $window}
1352}
1353
1354# optionally run disagl as a windowless process, w/results in a separate window
1355proc rundisagl {} {
1356    global expgui txtvw tcl_version tcl_platform
1357    if {$expgui(disaglSeparateBox)} {
1358        set root [file root $expgui(expfile)] 
1359        catch {file delete -force $root.tmp}
1360        catch {file rename -force $root.LST $root.OLS}
1361        # PSW reports this does not happen right away on windows
1362        set i 0
1363        while {$i < 10 && [file exists $root.LST]} {
1364            # debug code
1365            #catch {console show}
1366            #puts "try $i"
1367            # end debug code
1368            after 100
1369            incr i
1370        }
1371        if {[file exists $root.LST]} {
1372            # it was not possible to rename the file
1373            MyMessageBox -parent . -title "Rename Problem" \
1374                -message "Unable to rename $root.LST. Please close LSTVIEW and try again" \
1375                -icon warning -helplink "expguierr.html NoRename"
1376            return
1377        }
1378
1379        #run the program
1380        pleasewait "Running DISAGL"     
1381        # create an empty input file
1382        close [open disagl.inp w]
1383        catch {exec [file join $expgui(gsasexe) disagl] \
1384                [file tail $root] < disagl.inp > disagl.out}
1385        catch {file rename -force $root.LST $root.tmp}
1386        catch {file delete -force disagl.inp disagl.out}
1387        catch {file rename -force $root.OLS $root.LST}
1388        donewait
1389        # open a new window
1390        catch {toplevel .disagl}
1391        catch {eval grid forget [grid slaves .disagl]}
1392        text .disagl.txt -width 100 -wrap none \
1393                -yscrollcommand ".disagl.yscroll set" \
1394                -xscrollcommand ".disagl.xscroll set" 
1395        scrollbar .disagl.yscroll -command ".disagl.txt yview"
1396        scrollbar .disagl.xscroll -command ".disagl.txt xview" -orient horizontal
1397        grid .disagl.xscroll -column 0 -row 2 -sticky ew
1398        grid .disagl.txt -column 0 -row 1 -sticky nsew
1399        grid .disagl.yscroll -column 1 -row 1 -sticky ns
1400        grid [frame .disagl.f] -column 0 -columnspan 2 -row 3 -sticky ew
1401        grid columnconfig .disagl.f 2 -weight 1
1402        grid [button .disagl.f.close -text "Close & Delete" \
1403                -command "destroy .disagl; file delete $root.tmp"] \
1404                -column 3 -row 0 -sticky e
1405        grid [button .disagl.f.rename \
1406                -command "RenameAsFile $root.tmp $root.DIS .disagl" \
1407                -text "Close & Save as..."] \
1408                -column 4 -row 0 -sticky e
1409        # allow font changes on the fly
1410        if {$tcl_version >= 8.0} {
1411            .disagl.txt config -font $txtvw(font)
1412            set fontbut [tk_optionMenu .disagl.f.font txtvw(font) ""]
1413            grid .disagl.f.font -column 1 -row 0 -sticky w
1414            grid [label .disagl.f.t -text font:] -column 0 -row 0 -sticky w
1415            $fontbut delete 0 end
1416            foreach f {5 6 7 8 9 10 11 12 13 14 15 16} {
1417                $fontbut add command -label "Courier $f" -font "Courier $f"\
1418                        -command "set txtvw(font) \"Courier $f\"; \
1419                        .disagl.txt config -font \$txtvw(font)"
1420            }
1421        }
1422       
1423        grid columnconfigure .disagl 0 -weight 1
1424        grid rowconfigure .disagl 1 -weight 1
1425        wm title .disagl "DISAGL results $expgui(expfile)"
1426        wm iconname .disagl "DISAGL $root"
1427        set in [open $root.tmp r]
1428        .disagl.txt insert end [read $in]
1429        close $in
1430        bind all  {destroy .disagl}
1431        bind .disagl  ".disagl.txt yview scroll -1 page"
1432        bind .disagl  ".disagl.txt yview scroll 1 page"
1433        bind .disagl  ".disagl.txt xview scroll 1 unit"
1434        bind .disagl  ".disagl.txt xview scroll -1 unit"
1435        bind .disagl  ".disagl.txt yview scroll -1 unit"
1436        bind .disagl  ".disagl.txt yview scroll 1 unit"
1437        bind .disagl  ".disagl.txt yview 0"
1438        bind .disagl  ".disagl.txt yview end"
1439        # don't disable in Win as this prevents the highlighting of selected text
1440        if {$tcl_platform(platform) != "windows"} {
1441            .disagl.txt config -state disabled
1442        }
1443    } else {
1444        runGSASwEXP disagl
1445    }
1446}
1447
1448#------------------------------------------------------------------------------
1449# file conversions
1450#------------------------------------------------------------------------------
1451proc convfile {} {
1452    global expgui
1453    set frm .file
1454    catch {destroy $frm}
1455    toplevel $frm
1456    wm title $frm "Convert File"
1457    bind $frm <Key-F1> "MakeWWWHelp expgui.html ConvertWin"
1458    pack [frame [set frmA $frm.1] -bd 2 -relief groove] -padx 3 -pady 3 -side left
1459    pack [frame [set frmC $frm.3] ] -padx 3 -pady 3 \
1460            -side left -fill y -expand yes
1461    pack [button $frmC.help -text Help -bg yellow \
1462            -command "MakeWWWHelp expgui.html ConvertWin"] -side top
1463    pack [button $frmC.q -text Quit -command "destroy $frm"] -side bottom
1464    pack [button $frmC.b -text Convert -command "ValidWinCnv $frm"] \
1465            -side bottom
1466    pack [label $frmA.0 -text "Select a file to convert"] -side top -anchor center
1467    winfilebox $frm
1468    bind $frm <Return> "ValidWinCnv $frm"
1469
1470    # force the window to stay on top
1471    putontop $frm
1472    focus $frmC.q 
1473    tkwait window $frm
1474    afterputontop
1475}
1476
1477# validate the files and make the conversion
1478proc ValidWinCnv {frm} {
1479    global expgui
1480    # change backslashes to something sensible
1481    regsub -all {\\} $expgui(FileMenuCnvName) / expgui(FileMenuCnvName)
1482    # allow entry of D: for D:/ and D:TEST for d:/TEST
1483    if {[string first : $expgui(FileMenuCnvName)] != -1 && \
1484            [string first :/ $expgui(FileMenuCnvName)] == -1} {
1485        regsub : $expgui(FileMenuCnvName) :/ expgui(FileMenuCnvName)
1486    }
1487    if {$expgui(FileMenuCnvName) == "<Parent>"} {
1488        set expgui(FileMenuDir) [file dirname [set expgui(FileMenuDir)] ]
1489        ChooseWinCnv $frm
1490        return
1491    } elseif [file isdirectory \
1492            [file join $expgui(FileMenuDir) $expgui(FileMenuCnvName)]] {
1493        if {$expgui(FileMenuCnvName) != "."} {
1494            set expgui(FileMenuDir) \
1495                [file join $expgui(FileMenuDir) $expgui(FileMenuCnvName)]
1496        }
1497        ChooseWinCnv $frm
1498        return
1499    }
1500 
1501    set file [file join $expgui(FileMenuDir) $expgui(FileMenuCnvName)]
1502    if ![file exists $file] {
1503        MyMessageBox -parent $frm -title "Convert Error" \
1504                -message "File $file does not exist" -icon error
1505        return
1506    }
1507
1508    set tmpname "[file join [file dirname $file] tempfile.xxx]"
1509    set oldname "[file rootname $file].org"
1510    if [file exists $oldname] {
1511        set ans [MyMessageBox -parent . -title "Overwrite?" \
1512                -message "File [file tail $oldname] exists in [file dirname $oldname]. OK to overwrite?" \
1513                -icon warning -type {Overwrite Cancel} -default Overwrite \
1514                -helplink "expguierr.html OverwriteCnv"]
1515        if {[string tolower $ans] == "cancel"} return
1516        catch {file delete $oldname}
1517    }
1518
1519    if [catch {
1520        set in [open $file r]
1521        set out [open $tmpname w]
1522        fconfigure $out -translation crlf
1523        set len [gets $in line]
1524        if {$len > 160} {
1525            # this is a UNIX file. Hope there are no control characters
1526            set i 0
1527            set j 79
1528            while {$j < $len} {
1529                puts $out [string range $line $i $j]
1530                incr i 80
1531                incr j 80
1532            }
1533        } else {
1534            while {$len >= 0} {
1535                append line "                                        "
1536                append line "                                        "
1537                set line [string range $line 0 79]
1538                puts $out $line
1539                set len [gets $in line]
1540            }
1541        }
1542        close $in
1543        close $out
1544        file rename -force $file $oldname
1545        file rename -force $tmpname $file
1546    } errmsg] {
1547        MyMessageBox -parent $frm -title "Conversion error" \
1548                -message "Error in conversion:\n$errmsg" -icon warning
1549    } else {
1550        set ans [MyMessageBox -parent $frm -title "More?" \
1551                -message "File [file tail $file] converted.\n(Original saved as [file tail $oldname]).\n\n Convert more files?" \
1552                -type yesno -default no]
1553        if {$ans == "no"} {destroy $frm}
1554    }
1555}
1556
1557# create a file box
1558proc winfilebox {frm} {
1559    global expgui
1560    set bx $frm.1
1561    pack [frame $bx.top] -side top
1562    pack [label $bx.top.a -text "Directory" ] -side left
1563    set expgui(FileDirButtonMenu) [tk_optionMenu $bx.top.d expgui(FileMenuDir) [pwd] ]
1564    pack $bx.top.d -side left
1565    set expgui(FileMenuDir) [pwd]
1566    # the icon below is from tk8.0/tkfbox.tcl
1567    set upfolder [image create bitmap -data {
1568#define updir_width 28
1569#define updir_height 16
1570static char updir_bits[] = {
1571   0x00, 0x00, 0x00, 0x00, 0x80, 0x1f, 0x00, 0x00, 0x40, 0x20, 0x00, 0x00,
1572   0x20, 0x40, 0x00, 0x00, 0xf0, 0xff, 0xff, 0x01, 0x10, 0x00, 0x00, 0x01,
1573   0x10, 0x02, 0x00, 0x01, 0x10, 0x07, 0x00, 0x01, 0x90, 0x0f, 0x00, 0x01,
1574   0x10, 0x02, 0x00, 0x01, 0x10, 0x02, 0x00, 0x01, 0x10, 0x02, 0x00, 0x01,
1575   0x10, 0xfe, 0x07, 0x01, 0x10, 0x00, 0x00, 0x01, 0x10, 0x00, 0x00, 0x01,
1576   0xf0, 0xff, 0xff, 0x01};}]
1577
1578    pack [button $bx.top.b -image $upfolder \
1579            -command "updir; ChooseWinCnv $frm" ]
1580    pack [frame $bx.a -width 200 -height 75] -side top -expand yes -fill both
1581    listbox $bx.a.files -relief raised -bd 2 \
1582            -yscrollcommand "sync2boxesY $bx.a.files $bx.a.dates $bx.a.scroll" \
1583            -height 15 -width 0 -exportselection 0 
1584    listbox $bx.a.dates -relief raised -bd 2 \
1585            -yscrollcommand "sync2boxesY $bx.a.dates $bx.a.files $bx.a.scroll" \
1586            -height 15 -width 0 -takefocus 0 -exportselection 0 
1587    scrollbar $bx.a.scroll -command "move2boxesY \" $bx.a.files $bx.a.dates \" "
1588    ChooseWinCnv $frm
1589    bind $bx.a.files <ButtonRelease-1> "ReleaseWinCnv $frm"
1590    bind $bx.a.dates <ButtonRelease-1> "ReleaseWinCnv $frm"
1591    bind $bx.a.files <Double-1> "SelectWinCnv $frm"
1592    bind $bx.a.dates <Double-1> "SelectWinCnv $frm"
1593    pack $bx.a.scroll -side left -fill y
1594    pack $bx.a.files $bx.a.dates -side left -fill both -expand yes
1595    pack [entry $bx.c -textvariable expgui(FileMenuCnvName)] -side top
1596}
1597
1598# set the box or file in the selection window
1599proc ReleaseWinCnv {frm} {
1600    global expgui
1601    set files $frm.1.a.files
1602    set dates $frm.1.a.dates
1603    set select [$files curselection]
1604    if {$select == ""} {
1605        set select [$dates curselection]
1606    }
1607    if {$select == ""} {
1608        set expgui(FileMenuCnvName) ""
1609    } else {
1610        set expgui(FileMenuCnvName) [string trim [$files get $select]]
1611    }
1612    if {$expgui(FileMenuCnvName) == "<Parent>"} {
1613        set expgui(FileMenuDir) [file dirname $expgui(FileMenuDir)]
1614        ChooseWinCnv $frm
1615    } elseif [file isdirectory \
1616            [file join [set expgui(FileMenuDir)] $expgui(FileMenuCnvName)]] {
1617        if {$expgui(FileMenuCnvName) != "."} {
1618            set expgui(FileMenuDir) [file join $expgui(FileMenuDir) $expgui(FileMenuCnvName)]
1619            ChooseWinCnv $frm
1620        }
1621    }
1622    return
1623}
1624
1625# select a file or directory -- called on double click
1626proc SelectWinCnv {frm} {
1627    global expgui
1628    set files $frm.1.a.files
1629    set dates $frm.1.a.dates
1630    set select [$files curselection]
1631    if {$select == ""} {
1632        set select [$dates curselection]
1633    }
1634    if {$select == ""} {
1635        set file .
1636    } else {
1637        set file [string trim [$files get $select]]
1638    }
1639    if {$file == "<Parent>"} {
1640        set expgui(FileMenuDir) [file dirname [set expgui(FileMenuDir)] ]
1641        ChooseWinCnv $frm
1642    } elseif [file isdirectory [file join [set expgui(FileMenuDir)] $file]] {
1643        if {$file != "."} {
1644            set expgui(FileMenuDir) [file join [set expgui(FileMenuDir)] $file]
1645            ChooseWinCnv $frm
1646        }
1647    } else {
1648        set expgui(FileMenuCnvName) [file tail $file]
1649        ValidWinCnv $frm
1650    }
1651}
1652
1653# fill the files & dates & Directory selection box with current directory,
1654# also called when box is created to fill it
1655proc ChooseWinCnv {frm} {
1656    global expgui
1657    set files $frm.1.a.files
1658    set dates $frm.1.a.dates
1659    set expgui(FileMenuCnvName) {}
1660    $files delete 0 end
1661    $dates delete 0 end
1662    $files insert end {<Parent>}
1663    $dates insert end {(Directory)}
1664    set filelist [glob -nocomplain \
1665            [file join [set expgui(FileMenuDir)] *] ]
1666    foreach file [lsort -dictionary $filelist] {
1667        if {[file isdirectory $file]} {
1668            $files insert end [file tail $file]
1669            $dates insert end {(Directory)}
1670        }
1671    }
1672    foreach file [lsort -dictionary $filelist] {
1673        if {![file isdirectory $file]} {
1674            set modified [clock format [file mtime $file] -format "%T %D"]
1675            $files insert end [file tail $file]
1676            $dates insert end $modified
1677        }
1678    }
1679    $expgui(FileDirButtonMenu)  delete 0 end
1680    set list ""
1681    global tcl_version
1682    if {$tcl_version > 8.0} {
1683        catch {set list [string tolower [file volume]]}
1684    }
1685    set dir ""
1686    foreach subdir [file split [set expgui(FileMenuDir)]] {
1687        set dir [string tolower [file join $dir $subdir]]
1688        if {[lsearch $list $dir] == -1} {lappend list $dir}
1689    }
1690    foreach path $list {
1691        $expgui(FileDirButtonMenu) add command -label $path \
1692                -command "[list set expgui(FileMenuDir) $path]; \
1693                ChooseWinCnv $frm"
1694    }
1695    return
1696}
1697
1698#------------------------------------------------------------------------------
1699# set options for liveplot
1700proc liveplotopt {} {
1701    global liveplot expmap
1702    set frm .file
1703    catch {destroy $frm}
1704    toplevel $frm
1705    pack [frame [set frmA $frm.1] -bd 2 -relief groove] -padx 3 -pady 3 -side left
1706    set last [lindex [lsort -integer $expmap(powderlist)] end]
1707    if {$last == ""} {set last 1}
1708    pack [scale  $frmA.1 -label "Histogram number" -from 1 -to $last \
1709            -length  150 -orient horizontal -variable liveplot(hst)] -side top
1710    pack [checkbutton $frmA.2 -text {include plot legend}\
1711            -variable liveplot(legend)] -side top
1712    pack [button $frm.2 -text OK \
1713            -command {if ![catch {expr $liveplot(hst)}] "destroy .file"} \
1714            ] -side top
1715    bind $frm <Return> {if ![catch {expr $liveplot(hst)}] "destroy .file"}
1716   
1717    # force the window to stay on top
1718    putontop $frm 
1719    focus $frm.2
1720    tkwait window $frm
1721    afterputontop
1722}
1723
1724#------------------------------------------------------------------------------
1725# get an experiment file name
1726#------------------------------------------------------------------------------
1727proc getExpFileName {mode} {
1728    global expgui tcl_platform
1729    set frm .file
1730    catch {destroy $frm}
1731    toplevel $frm
1732    wm title $frm "Experiment file"
1733    bind $frm <Key-F1> "MakeWWWHelp expguierr.html open"
1734    pack [frame [set frmA $frm.1] -bd 2 -relief groove] -padx 3 -pady 3 -side left
1735    pack [frame [set frmC $frm.3] ] -padx 3 -pady 3 -side left \
1736            -fill y -expand yes
1737    pack [button $frmC.help -text Help -bg yellow \
1738            -command "MakeWWWHelp expguierr.html open"] \
1739            -side top -anchor e
1740    pack [label $frmC.2 -text "Sort .EXP files by" ] -side top
1741    pack [radiobutton $frmC.1 -text "File Name" -value 1 \
1742            -variable expgui(filesort) -command "ChooseExpFil $frmA"] -side top
1743    pack [radiobutton $frmC.0 -text "Mod. Date" -value 0 \
1744            -variable expgui(filesort) -command "ChooseExpFil $frmA"] -side top
1745
1746    set expgui(includearchived) 0
1747    set expgui(FileInfoBox) $frmC.info
1748    if {$mode == "old"} {
1749        pack [checkbutton $frmC.ar -text "Include Archived Files" \
1750                -variable expgui(includearchived) \
1751                -command "ChooseExpFil $frmA"] -side top -pady 10
1752        pack [frame $expgui(FileInfoBox) -bd 4 -relief groove \
1753                -class SmallFont] \
1754                -side top -fill both -expand yes -pady 5
1755    }
1756    pack [button $frmC.b -text Read \
1757            -command "valid_exp_file $frmA $mode"] -side bottom
1758    if {$mode == "new"} {
1759        $frmC.b config -text Save
1760    }
1761    pack [button $frmC.q -text Quit \
1762            -command "set expgui(FileMenuEXPNAM) {}; destroy $frm"] -side bottom
1763    bind $frm <Return> "$frmC.b invoke"
1764
1765    if {$mode == "new"} {
1766        pack [label $frmA.0 -text "Enter an experiment file to create"] \
1767                -side top -anchor center
1768    } else {
1769        pack [label $frmA.0 -text "Select an experiment file to read"] \
1770                -side top -anchor center
1771    }
1772    expfilebox $frmA $mode
1773    # force the window to stay on top
1774    putontop $frm
1775    focus $frmC.b
1776    tkwait window $frm
1777    afterputontop
1778    if {$expgui(FileMenuEXPNAM) == ""} return
1779    # is there a space in the EXP name?
1780    if {[string first " " [file tail $expgui(FileMenuEXPNAM)]] != -1} {
1781        update
1782        MyMessageBox -parent . -title "File Name Error" \
1783            -message "File name \"$expgui(FileMenuEXPNAM)\" is invalid -- EXPGUI cannot process experiment files with spaces in the name" \
1784            -icon warning -type Continue -default continue
1785#               -helplink "expguierr.html OpenErr"
1786        return
1787    }
1788    if {[string first " " $expgui(FileMenuDir)] != -1} {
1789        update
1790        MyMessageBox -parent . -title "Good luck..." \
1791            -message "You are using a directory with a space in the name ([file dirname $expgui(FileMenuDir)]) -- You may encounter bugs in EXPGUI. Please e-mail them to Brian.Toby@NIST.gov so they can be fixed." \
1792            -icon warning -type Continue -default continue
1793#               -helplink "expguierr.html OpenErr"
1794    }
1795    return [file join $expgui(FileMenuDir) $expgui(FileMenuEXPNAM)]
1796}
1797
1798# validation routine
1799proc valid_exp_file {frm mode} {
1800    global expgui tcl_platform
1801    # windows fixes
1802    if {$tcl_platform(platform) == "windows"} {
1803        # change backslashes to something sensible
1804        regsub -all {\\} $expgui(FileMenuEXPNAM) / expgui(FileMenuEXPNAM)
1805        # allow entry of D: for D:/ and D:TEST for d:/TEST
1806        if {[string first : $expgui(FileMenuEXPNAM)] != -1 && \
1807                [string first :/ $expgui(FileMenuEXPNAM)] == -1} {
1808            regsub : $expgui(FileMenuEXPNAM) :/ expgui(FileMenuEXPNAM)
1809        }
1810    }
1811    if {$expgui(FileMenuEXPNAM) == "<Parent>"} {
1812        set expgui(FileMenuDir) [file dirname [set expgui(FileMenuDir)] ]
1813        ChooseExpFil $frm
1814        return
1815    } elseif [file isdirectory \
1816            [file join $expgui(FileMenuDir) $expgui(FileMenuEXPNAM)]] {
1817        if {$expgui(FileMenuEXPNAM) != "."} {
1818            set expgui(FileMenuDir) \
1819                [file join $expgui(FileMenuDir) $expgui(FileMenuEXPNAM)]
1820        }
1821        ChooseExpFil $frm
1822        return
1823    }
1824    # append a .EXP if not present
1825    if {[file extension $expgui(FileMenuEXPNAM)] == ""} {
1826        append expgui(FileMenuEXPNAM) ".EXP"
1827    }
1828    # is there a space in the name?
1829    if {[string first " " $expgui(FileMenuEXPNAM)] != -1} {
1830        MyMessageBox -parent . -title "File Name Error" \
1831                -message "File name $expgui(FileMenuEXPNAM) is invalid -- EXPGUI cannot process experiment files with spaces in the name" \
1832                -icon warning -type Continue -default continue
1833#               -helplink "expguierr.html OpenErr"
1834        return
1835    }
1836    # check for archive files
1837    if {[string match {*.O[0-9A-F][0-9A-F]} $expgui(FileMenuEXPNAM)] && \
1838            $mode == "old" && [file exists $expgui(FileMenuEXPNAM)]} {
1839        destroy .file
1840        return
1841    } elseif {[string toupper [file extension $expgui(FileMenuEXPNAM)]] != ".EXP"} {
1842        # check for files that end in something other than .EXP .exp or .Exp...
1843        MyMessageBox -parent . -title "File Open Error" \
1844                -message "File [file tail $expgui(FileMenuEXPNAM)] is not a valid name. Experiment files must end in \".EXP\"" \
1845                -icon error
1846        return
1847    }
1848    # check on the file status
1849    set file [file join $expgui(FileMenuDir) $expgui(FileMenuEXPNAM)]
1850    if {$mode == "new" && [file exists $file]} {
1851        set ans [
1852        MyMessageBox -parent . -title "File Open Error" \
1853                -message "File [file tail $file] already exists in [file dirname $file]. OK to overwrite?" \
1854                -icon question -type {"Select other" "Overwrite"} -default "select other" \
1855                -helplink "expguierr.html OverwriteErr"
1856        ]
1857        if {[string tolower $ans] == "overwrite"} {destroy .file}
1858        return
1859    }
1860    # if file does not exist in case provided, set the name to all
1861    # upper case letters, since that is the best choice.
1862    # if it does exist, read from it as is. For UNIX we will force uppercase later.
1863    if {![file exists $file]} {
1864        set expgui(FileMenuEXPNAM) [string toupper $expgui(FileMenuEXPNAM)]
1865        set file [file join $expgui(FileMenuDir) $expgui(FileMenuEXPNAM)]
1866    }
1867    if {$mode == "old" && ![file exists $file]} {
1868        set ans [
1869        MyMessageBox -parent . -title "File Open Error" \
1870                -message "File [file tail $file] does not exist in [file dirname $file]. OK to create?" \
1871                -icon question -type {"Select other" "Create"} -default "select other" \
1872                -helplink "expguierr.html OpenErr"
1873        ]
1874        if {[string tolower $ans] == "create"} {destroy .file}
1875        return
1876    }
1877    destroy .file
1878}
1879
1880proc updir {} {
1881    global expgui
1882    set expgui(FileMenuDir) [file dirname [set expgui(FileMenuDir)]]
1883}
1884
1885# create a file box
1886proc expfilebox {bx mode} {
1887    global expgui
1888    pack [frame $bx.top] -side top
1889    pack [label $bx.top.a -text "Directory" ] -side left
1890    set expgui(FileDirButtonMenu) [tk_optionMenu $bx.top.d expgui(FileMenuDir) [pwd] ]
1891    pack $bx.top.d -side left
1892    set expgui(FileMenuDir) [pwd]
1893    # the icon below is from tk8.0/tkfbox.tcl
1894    set upfolder [image create bitmap -data {
1895#define updir_width 28
1896#define updir_height 16
1897static char updir_bits[] = {
1898   0x00, 0x00, 0x00, 0x00, 0x80, 0x1f, 0x00, 0x00, 0x40, 0x20, 0x00, 0x00,
1899   0x20, 0x40, 0x00, 0x00, 0xf0, 0xff, 0xff, 0x01, 0x10, 0x00, 0x00, 0x01,
1900   0x10, 0x02, 0x00, 0x01, 0x10, 0x07, 0x00, 0x01, 0x90, 0x0f, 0x00, 0x01,
1901   0x10, 0x02, 0x00, 0x01, 0x10, 0x02, 0x00, 0x01, 0x10, 0x02, 0x00, 0x01,
1902   0x10, 0xfe, 0x07, 0x01, 0x10, 0x00, 0x00, 0x01, 0x10, 0x00, 0x00, 0x01,
1903   0xf0, 0xff, 0xff, 0x01};}]
1904
1905    pack [button $bx.top.b -image $upfolder \
1906            -command "updir; ChooseExpFil $bx" ]
1907    pack [frame $bx.a -width 200 -height 75] -side top -expand yes -fill both
1908    listbox $bx.a.files -relief raised -bd 2 \
1909            -yscrollcommand "sync2boxesY $bx.a.files $bx.a.dates $bx.a.scroll" \
1910            -height 15 -width 0 -exportselection 0 
1911    listbox $bx.a.dates -relief raised -bd 2 \
1912            -yscrollcommand "sync2boxesY $bx.a.dates $bx.a.files $bx.a.scroll" \
1913            -height 15 -width 0 -takefocus 0 -exportselection 0 
1914    scrollbar $bx.a.scroll -command "move2boxesY \" $bx.a.files $bx.a.dates \" "
1915    ChooseExpFil $bx
1916    bind $bx.a.files <ButtonRelease-1> "ReleaseExpFil $bx"
1917    bind $bx.a.dates <ButtonRelease-1> "ReleaseExpFil $bx"
1918    bind $bx.a.files <Double-1> "SelectExpFil $bx $mode"
1919    bind $bx.a.dates <Double-1> "SelectExpFil $bx $mode"
1920    pack $bx.a.scroll -side left -fill y
1921    pack $bx.a.files $bx.a.dates -side left -fill both -expand yes
1922    pack [entry $bx.c -textvariable expgui(FileMenuEXPNAM)] -side top
1923}
1924proc sync2boxesX {master slave scroll args} {
1925    $slave xview moveto [lindex [$master xview] 0]
1926    eval $scroll set $args
1927}
1928proc move2boxesX {boxlist args} {
1929    foreach listbox $boxlist { 
1930        eval $listbox xview $args
1931    }
1932}
1933proc sync2boxesY {master slave scroll args} {
1934    $slave yview moveto [lindex [$master yview] 0]
1935    eval $scroll set $args
1936}
1937proc move2boxesY {boxlist args} {
1938    foreach listbox $boxlist { 
1939        eval $listbox yview $args
1940    }
1941}
1942
1943# creates a table that is scrollable in both x and y, use ResizeScrollTable
1944# to set sizes after gridding the boxes
1945proc MakeScrollTable {box} {
1946    grid [label $box.0] -col 0 -row 0
1947    grid [set tbox [canvas $box.top \
1948            -scrollregion {0 0 10 10} \
1949            -xscrollcommand "sync2boxesX $box.top $box.can $box.scroll" \
1950            -width 10 -height 10]] \
1951            -sticky sew -row 0 -column 1
1952    grid [set sbox [canvas $box.side \
1953            -scrollregion {0 0 10 10} \
1954            -yscrollcommand "sync2boxesY $box.side $box.can $box.yscroll" \
1955            -width 10 -height 10]] \
1956            -sticky nes -row 1 -column 0
1957    grid [set bbox [canvas $box.can \
1958            -scrollregion {0 0 10 10} \
1959            -yscrollcommand "sync2boxesY $box.can $box.side $box.yscroll" \
1960            -xscrollcommand "sync2boxesX $box.can $box.top $box.scroll" \
1961            -width 200 -height 200 -bg lightgrey]] \
1962            -sticky news -row 1 -column 1
1963    grid [set sxbox [scrollbar $box.scroll -orient horizontal \
1964            -command "move2boxesX \" $box.can $box.top \" "]] \
1965            -sticky ew -row 2 -column 1
1966    grid [set sybox [scrollbar $box.yscroll \
1967            -command "move2boxesY \" $box.can $box.side \" "]] \
1968            -sticky ns -row 1 -column 2
1969    frame $tbox.f -bd 0
1970    $tbox create window 0 0 -anchor nw  -window $tbox.f
1971    frame $bbox.f -bd 2
1972    $bbox create window 0 0 -anchor nw  -window $bbox.f
1973    frame $sbox.f -bd 2 -relief raised
1974    $sbox create window 0 0 -anchor nw  -window $sbox.f
1975    grid columnconfig $box 1 -weight 1
1976    grid rowconfig $box 1 -weight 1
1977    return [list  $tbox.f  $bbox.f $sbox.f $box.0]
1978}
1979
1980proc ResizeScrollTable {box} {
1981    update idletasks
1982    for {set i 0} {$i < [lindex [grid size $box.can.f] 0]} {incr i} {
1983        set x1 [lindex [grid bbox $box.can.f $i 0] 2]
1984        set x2 [lindex [grid bbox $box.top.f $i 0] 2]
1985        if {$x2 > $x1} {set x1 $x2}
1986        grid columnconfigure $box.top.f $i -minsize $x1
1987        grid columnconfigure $box.can.f $i -minsize $x1
1988    }
1989    for {set i 0} {$i < [lindex [grid size $box.can.f] 1]} {incr i} {
1990        set x1 [lindex [grid bbox $box.can.f 0 $i] 3]
1991        set x2 [lindex [grid bbox $box.side.f 0 $i] 3]
1992        if {$x2 > $x1} {set x1 $x2}
1993        grid rowconfigure $box.can.f $i -minsize $x1
1994        grid rowconfigure $box.side.f $i -minsize $x1
1995    }
1996    update idletasks
1997    set sizes [grid bbox $box.can.f]
1998    $box.can config -scrollregion $sizes
1999    $box.side config -scrollregion $sizes
2000    $box.top config -scrollregion $sizes
2001    $box.top config -height [lindex [grid bbox $box.top.f] 3]
2002    $box.side config -width [lindex [grid bbox $box.side.f] 2]
2003}
2004proc ExpandScrollTable {box} {
2005    # set height & width of central box
2006    $box.can config -width \
2007            [expr [winfo width [winfo toplevel $box]] \
2008            - [winfo width $box.side] - [winfo width $box.yscroll]-20]
2009    $box.can config -height \
2010            [expr [winfo height [winfo toplevel $box]] \
2011            - [winfo height $box.top] - [winfo height $box.scroll]-25]
2012}
2013
2014
2015# support routine for SetHistUseFlags
2016proc InitHistUseFlags {} {
2017    global expmap expgui
2018    for {set i 1} {$i <= $expmap(nhst)} {incr i} {
2019#       if {[string range $expmap(htype_$i) 0 0] == "P"} {
2020            set expgui(useflag_$i) [histinfo $i use]
2021#       }
2022    }
2023}
2024
2025# show all Powder histograms; set use/do not use flags
2026proc SetHistUseFlags {} {
2027    set box .test
2028    catch {toplevel $box}
2029    eval destroy [winfo children $box]
2030    grid [label $box.0 -text "Set histogram \"Use/Do Not Use\" flags" -bg white] -row 0 -column 0 -columnspan 2
2031    grid [frame $box.a] -row 1 -column 0 -columnspan 2
2032    grid [button $box.b -text Save -command "destroy $box"] -row 2 -column 0 -sticky e
2033    grid [button $box.c -text Cancel -command "InitHistUseFlags;destroy $box"] -row 2 -column 1 -sticky w
2034    grid columnconfig $box 0 -weight 1
2035    grid columnconfig $box 1 -weight 1
2036    foreach a [MakeScrollTable $box.a] b {tbox bbox sbox cbox} {set $b $a}
2037    $cbox config -text "Use\nFlag"
2038    [winfo parent $bbox] config -height 250 -width 400
2039    global expmap expgui
2040    set px 5
2041    set row -1
2042    for {set i 1} {$i <= $expmap(nhst)} {incr i} {
2043        if {[string range $expmap(htype_$i) 2 2] == "T"} {
2044            set det [format %8.2f [histinfo $i tofangle]]
2045        } elseif {[string range $expmap(htype_$i) 2 2] == "C"} {
2046            set det [format %8.5f [histinfo $i lam1]]
2047        } elseif {[string range $expmap(htype_$i) 2 2] == "E"} {
2048            set det [format %8.2f [histinfo $i lam1]]
2049        } else {
2050            set det {}
2051        }
2052        incr row
2053#       if {[string range $expmap(htype_$i) 0 0] == "P"} {
2054            grid [checkbutton $sbox.$i -text $i -variable expgui(useflag_$i)] -row $row -col 0 
2055            set expgui(useflag_$i) [histinfo $i use]
2056#       }
2057        grid [label $bbox.0$i \
2058                -text [string range $expmap(htype_$i) 0 3] \
2059                ] -row $row -col 0 -padx $px
2060        grid [label $bbox.1$i -text [histinfo $i bank] \
2061                ] -row $row -col 1 -padx $px
2062        grid [label $bbox.2$i -text $det] -row $row -col 2 -padx $px
2063        grid [label $bbox.3$i -text [string range [histinfo $i title] 0 66] \
2064                ] -row $row -col 3 -padx $px -sticky ew
2065    }
2066    grid [label $tbox.0 -text type -bd 2 -relief raised] -row 0 -col 0 -padx $px
2067    grid [label $tbox.1 -text bank -bd 2 -relief raised] -row 0 -col 1 -padx $px
2068    grid [label $tbox.2 -text "ang/wave" -bd 2 -relief raised] -row 0 -col 2 -padx $px
2069    grid [label $tbox.3 -text "histogram title" -bd 2 -relief raised] -row 0 -col 3 -sticky w -padx $px
2070    ResizeScrollTable $box.a
2071    InitHistUseFlags
2072    putontop $box
2073    tkwait window $box
2074    afterputontop
2075    set prevchages $expgui(changed)
2076    for {set i 1} {$i <= $expmap(nhst)} {incr i} {
2077#       if {[string range $expmap(htype_$i) 0 0] == "P"} {
2078            if {$expgui(useflag_$i) != [histinfo $i use]} {
2079                histinfo $i use set $expgui(useflag_$i)
2080                incr expgui(changed)
2081            }
2082#       }
2083    }
2084    if {$prevchages != $expgui(changed)} {
2085        set msg "You have changed [expr $expgui(changed)-$prevchages] "
2086        append msg "histogram flag(s). You must run POWPREF "
2087        append msg "to include/remove these histograms. Do you want to "
2088        append msg "run POWPREF?"
2089        set ans [MyMessageBox -parent . -message $msg \
2090                -title "Process changes?"\
2091                -helplink "expguierr.html ProcessUse" \
2092                -default {Run POWPREF} \
2093                -type {{Run POWPREF} Skip}]
2094       
2095        if {$ans == "skip"} {
2096            # save and reload the experiment file
2097            savearchiveexp
2098            loadexp $expgui(expfile)
2099        } else {
2100            # run powpref and force a reload
2101            set saveautoload $expgui(autoexpload)
2102            set expgui(autoexpload) 1
2103            runGSASwEXP powpref
2104            set expgui(autoexpload) $saveautoload
2105        }
2106    }
2107}
2108
2109# set the box or file in the selection window
2110proc ReleaseExpFil {frm} {
2111    global expgui
2112    set files $frm.a.files
2113    set dates $frm.a.dates
2114    set select [$files curselection]
2115    if {$select == ""} {
2116        set select [$dates curselection]
2117    }
2118    if {$select == ""} {
2119        set expgui(FileMenuEXPNAM) ""
2120    } else {
2121        set expgui(FileMenuEXPNAM) [string trim [$files get $select]]
2122        after idle UpdateInfoBox
2123    }
2124    if {$expgui(FileMenuEXPNAM) == "<Parent>"} {
2125        set expgui(FileMenuDir) [file dirname $expgui(FileMenuDir)]
2126        ChooseExpFil $frm
2127    } elseif [file isdirectory \
2128            [file join [set expgui(FileMenuDir)] $expgui(FileMenuEXPNAM)]] {
2129        if {$expgui(FileMenuEXPNAM) != "."} {
2130            set expgui(FileMenuDir) [file join $expgui(FileMenuDir) $expgui(FileMenuEXPNAM)]
2131            ChooseExpFil $frm
2132        }
2133    }
2134    return
2135}
2136proc UpdateInfoBox {} {
2137    global expgui
2138    if {![winfo exists $expgui(FileInfoBox)]} return
2139    eval destroy [winfo children $expgui(FileInfoBox)]
2140    set file [file join [set expgui(FileMenuDir)] $expgui(FileMenuEXPNAM)]
2141    if [file isdirectory $file] return
2142    if [file exists $file] {
2143        pack [label $expgui(FileInfoBox).1 -text $expgui(FileMenuEXPNAM)] \
2144                -side top
2145        catch {
2146            set fp [open $file r]
2147            global testline
2148            set testline [read $fp]
2149            close $fp
2150            update
2151            regexp {GNLS  RUN on (.*) +Total.*run +([0-9]+) } \
2152                    $testline a last cycles
2153            pack [label $expgui(FileInfoBox).2 -justify left \
2154                    -text "last GENLES run:\n  $last\n  total cycles: $cycles"] \
2155                -side top -anchor w
2156            regexp {REFN GDNFT.*= *([0-9]*\.[0-9]*) +for *([0-9]+) variables} \
2157                    $testline a chi2 vars
2158            pack [frame $expgui(FileInfoBox).3 -class SmallFont] \
2159                    -side top -anchor w
2160            pack [label $expgui(FileInfoBox).3.a -justify left \
2161                    -text "c" -font symbol] \
2162                    -side left -anchor w
2163            pack [label $expgui(FileInfoBox).3.b -justify left \
2164                    -text "2: $chi2, $vars vars"] \
2165                    -side top -anchor w
2166            # check first 9 histograms
2167            set lbl "h  Rwp     R(F2)"
2168            set n 0
2169            foreach k {1 2 3 4 5 6 7 8 9} {
2170                set key "HST  $k"
2171                append key { RPOWD +([0-9]*\.[0-9]*) }
2172                set i [regexp $key $testline a Rwp]
2173                set key "HST  $k"
2174                append key { R-FAC +[0-9]+ +([0-9]*\.[0-9]*) }
2175                set j [regexp $key $testline a Rb]
2176                if {$i || $j} {
2177                    incr n
2178                    append lbl "\n$k  "
2179                    if {$i} {
2180                        append lbl [string range $Rwp 0 5]
2181                    } else {
2182                        append lbl "    "
2183                    }
2184                }
2185                if {$j} {
2186                    append lbl " [string range $Rb 0 5]"
2187                }
2188                # stick 1st 3 entries in box
2189                if {$n >= 3} break
2190            }
2191            pack [label $expgui(FileInfoBox).4 -justify left \
2192                    -text $lbl] \
2193                    -side top -anchor w     
2194        }
2195    }
2196}
2197
2198# select a file or directory -- called on double click
2199proc SelectExpFil {frm mode} {
2200    global expgui
2201    set files $frm.a.files
2202    set dates $frm.a.dates
2203    set select [$files curselection]
2204    if {$select == ""} {
2205        set select [$dates curselection]
2206    }
2207    if {$select == ""} {
2208        set file .
2209    } else {
2210        set file [string trim [$files get $select]]
2211    }
2212    if {$file == "<Parent>"} {
2213        set expgui(FileMenuDir) [file dirname [set expgui(FileMenuDir)] ]
2214        ChooseExpFil $frm
2215    } elseif [file isdirectory [file join [set expgui(FileMenuDir)] $file]] {
2216        if {$file != "."} {
2217            set expgui(FileMenuDir) [file join [set expgui(FileMenuDir)] $file]
2218            ChooseExpFil $frm
2219        }
2220    } else {
2221        set expgui(FileMenuEXPNAM) [file tail $file]
2222        valid_exp_file $frm $mode
2223    }
2224}
2225
2226# fill the files & dates & Directory selection box with current directory,
2227# also called when box is created to fill it
2228proc ChooseExpFil {frm} {
2229    global expgui
2230    set files $frm.a.files
2231    set dates $frm.a.dates
2232    set expgui(FileMenuEXPNAM) {}
2233    $files delete 0 end
2234    $dates delete 0 end
2235    $files insert end {<Parent>}
2236    $dates insert end {(Directory)}
2237    set filelist [glob -nocomplain \
2238            [file join [set expgui(FileMenuDir)] *] ]
2239    foreach file [lsort -dictionary $filelist] {
2240        if {[file isdirectory $file]} {
2241            $files insert end [file tail $file]
2242            $dates insert end {(Directory)}
2243        }
2244    }
2245    set pairlist {}
2246    foreach file [lsort -dictionary $filelist] {
2247        if {![file isdirectory $file]  && \
2248                [string toupper [file extension $file]] == ".EXP"} {
2249            set modified [file mtime $file]
2250            lappend pairlist [list $file $modified]
2251        } elseif {![file isdirectory $file] && $expgui(includearchived) && \
2252                [string match {*.O[0-9A-F][0-9A-F]} $file]} {
2253            set modified [file mtime $file]
2254            lappend pairlist [list $file $modified]
2255        }
2256    }
2257    if {$expgui(filesort) == 0} {
2258        foreach pair [lsort -index 1 -integer -decreasing $pairlist] {
2259            set file [lindex $pair 0]
2260            set modified [clock format [lindex $pair 1] -format "%T %D"]
2261            $files insert end [file tail $file]
2262            $dates insert end $modified
2263        }
2264    } else {
2265        foreach pair [lsort -dictionary -index 0 $pairlist] {
2266            set file [lindex $pair 0]
2267            set modified [clock format [lindex $pair 1] -format "%T %D"]
2268            $files insert end [file tail $file]
2269            $dates insert end $modified
2270        }
2271    }
2272    $expgui(FileDirButtonMenu)  delete 0 end
2273    set list ""
2274    global tcl_platform tcl_version
2275    if {$tcl_platform(platform) == "windows" && $tcl_version > 8.0} {
2276        catch {set list [string tolower [file volume]]}
2277    }
2278    set dir ""
2279    foreach subdir [file split [set expgui(FileMenuDir)]] {
2280        set dir [file join $dir $subdir]
2281        if {$tcl_platform(platform) == "windows"} {
2282            set dir [string tolower $dir]
2283            if {[lsearch $list $dir] == -1} {lappend list $dir}
2284        } else {
2285            lappend list $dir
2286        }
2287    }
2288    foreach path $list {
2289        $expgui(FileDirButtonMenu) add command -label $path \
2290                -command "[list set expgui(FileMenuDir) $path]; \
2291                ChooseExpFil $frm"
2292    }
2293    # highlight the current experiment -- if present
2294    for {set i 0} {$i < [$files size]} {incr i} {
2295        set file [$files get $i]
2296        if {$expgui(expfile) == [file join $expgui(FileMenuDir) $file]} {
2297            $files selection set $i
2298        }
2299    }
2300    return
2301}
2302
2303
2304#------------------------------------------------------------------------------
2305# platform-specific definitions
2306if {$tcl_platform(platform) == "windows" && $tcl_platform(os) == "Windows 95"} {
2307    # windows-95, -98 and presumably -me do not allow Tcl/Tk to run the
2308    # DOS box synchronously, so we create a "lock" file that is deleted
2309    # at the end of the DOS run so we can tell when the run is done.
2310    # We create a window to force the deleting of the file so that if
2311    # the DOS process crashes, the user can continue anyway.
2312    #
2313    # procedure to check if the lock file is still there (Win-9x/me only)
2314    proc checklockfile {file window} {
2315        if [file exists $file] {
2316            after 500 checklockfile $file $window
2317        } else {
2318            catch {destroy $window}
2319        }
2320    }
2321    # this procedure starts the GRWND program, if needed for program $prog
2322    proc StartGRWND {prog} {
2323        global expgui
2324        if {!$expgui(autoGRWND)} return
2325        # at some point we might want to have a real list
2326        if {$prog != "genles" && $prog != "powpref"} {
2327            # get a list of running jobs
2328            exec [file join $expgui(scriptdir) win9xbin tlist.exe] > tlist.tlist
2329            set fp [open tlist.tlist r]
2330            set text [read $fp]
2331            close $fp
2332            file delete -force tlist.tlist
2333            # if GRWND.EXE is not currently running, start it
2334            if {[lsearch [string toupper $text] GRWND.EXE] == -1} {
2335                exec [file join $expgui(gsasexe) grwnd.exe] &
2336                # give grwnd a 1 second head start
2337                after 1000
2338            }
2339        }
2340    }
2341    # this creates a DOS box to run a program in
2342    proc forknewterm {title command "wait 1" "scrollbar 1"} {
2343        global env expgui
2344        # Windows environment variables
2345        set env(GSAS) [file nativename $expgui(gsasdir)]
2346        # PGPLOT_FONT is needed by PGPLOT
2347        set env(PGPLOT_FONT) [file nativename [file join $expgui(gsasdir) pgl grfont.dat]]
2348        # this is the number of lines/page in the .LST (etc.) file
2349        set env(LENPAGE) 60
2350        set pwd [file nativename [pwd]]
2351       
2352        # check the .EXP path -- can DOS use it?
2353        if {[string first // [pwd]] != -1} {
2354            MyMessageBox -parent . -title "Invalid Path" \
2355                    -message {Error -- Use "Map network drive" to access this directory with a letter (e.g. F:) GSAS can't directly access a network drive} \
2356                    -icon error -type ok -default ok \
2357                    -helplink "expgui_Win_readme.html NetPath"
2358            return
2359        }
2360        # pause is hard coded in the .BAT file
2361        #
2362        # loop over multiple commands
2363        foreach cmd $command {
2364            # simulate the wait with a lock file
2365            if {$wait} {
2366                if {$expgui(autoiconify)} {wm iconify .}
2367                # create a blank lock file and a message window
2368                close [open expgui.lck w]
2369                toplevel .lock
2370                grid [button .lock.0 -text Help -bg yellow \
2371                        -command "MakeWWWHelp expguierr.html lock"] \
2372                        -column 1 -row 0
2373                grid [label .lock.1 \
2374                        -text "Please wait while the GSAS program finishes."] \
2375                        -column 0 -row 0
2376                grid [label .lock.2 -text \
2377                        "In case a problem occurs, close the DOS box"] \
2378                        -column 0 -columnspan 2 -row 1
2379                grid [label .lock.3 -text \
2380                        "and press the \"Continue\" button (below)"] \
2381                        -column 0 -columnspan 2 -row 2
2382                grid [button .lock.b -text "Continue" \
2383                        -command "destroy .lock; wm deiconify ."] \
2384                        -column 0 -columnspan 2 -row 3
2385                putontop .lock
2386                update
2387                checklockfile expgui.lck .lock
2388            }
2389            # replace the forward slashes with backward
2390            regsub -all / $cmd \\ cmd
2391            winexec -d [file nativename [pwd]] \
2392                    [file join $expgui(scriptdir) gsastcl.bat] $cmd
2393            if {$wait} {
2394                tkwait window .lock
2395                file delete -force expgui.lck
2396            }
2397        }
2398        if {$expgui(autoiconify) && $wait} {wm deiconify .}
2399        # check for changes in the .EXP file immediately
2400        whenidle
2401    }
2402} elseif {$tcl_platform(platform) == "windows"} {
2403    # now for Windows-NT, where we can run synchronously
2404    #
2405    # this creates a DOS box to run a program in
2406    proc forknewterm {title command  "wait 1" "scrollbar 1"} {
2407        global env expgui
2408        # Windows environment variables
2409        set env(GSAS) [file nativename $expgui(gsasdir)]
2410        # PGPLOT_FONT is needed by PGPLOT
2411        set env(PGPLOT_FONT) [file nativename [file join $expgui(gsasdir) pgl grfont.dat]]
2412        # this is the number of lines/page in the .LST (etc.) file
2413        set env(LENPAGE) 60
2414        set pwd [file nativename [pwd]]
2415        # check the path -- can DOS use it?
2416        if {[string first // [pwd]] != -1} {
2417            MyMessageBox -parent . -title "Invalid Path" \
2418                    -message {Error -- Use "Map network drive" to access this directory with a letter (e.g. F:) GSAS can't directly access a network drive} \
2419                    -icon error -type ok -default ok \
2420                    -helplink "expgui_Win_readme.html NetPath"
2421            return
2422        }
2423        # pause is hard coded in the .BAT file
2424
2425        if {$wait} {
2426            if {$expgui(autoiconify)} {wm iconify .}
2427            # create a blank lock file (keep liveplot from running)
2428            close [open expgui.lck w]
2429            # loop over commands
2430            foreach cmd $command {
2431                # replace the forward slashes with backward
2432                regsub -all / $cmd \\ cmd
2433                exec $env(COMSPEC) /c \
2434                        "start [file join $expgui(scriptdir) gsastcl.bat] $cmd"
2435            }
2436            file delete -force expgui.lck
2437            if {$expgui(autoiconify)} {wm deiconify .}
2438            # check for changes in the .EXP file immediately
2439            whenidle
2440        } else {
2441            # loop over commands
2442            foreach cmd $command {
2443                # replace the forward slashes with backward
2444                regsub -all / $cmd \\ cmd
2445                # run in background
2446                exec $env(COMSPEC) /c \
2447                        "start [file join $expgui(scriptdir) gsastcl.bat] $cmd" &
2448            }
2449        }
2450    }
2451} else {
2452    # this creates a xterm window to run a program in
2453    proc forknewterm {title command "wait 1" "scrollbar 1"} {
2454        global env expgui
2455        # UNIX environment variables
2456        set env(GSAS) [file nativename $expgui(gsasdir)]
2457        set env(gsas) [file nativename $expgui(gsasdir)]
2458        set env(GSASEXE) $expgui(gsasexe)
2459        set env(ATOMDATA) [file join $expgui(gsasdir) data atmdata.dat]
2460        set env(ATMXSECT) [file join $expgui(gsasdir) data atmxsect.dat]
2461        # PGPLOT_DIR is needed by PGPLOT
2462        set env(PGPLOT_DIR) [file join $expgui(gsasdir) pgl]
2463        # this is the number of lines/page in the .LST (etc.) file
2464        set env(LENPAGE) 60
2465        set termopts {}
2466        if $env(GSASBACKSPACE) {
2467            append termopts \
2468                    {-xrm "xterm*VT100.Translations: #override\\n <KeyPress>BackSpace: string(\\177)"}
2469        }
2470        if $scrollbar {
2471            append termopts " -sb"
2472        } else {
2473            append termopts " +sb"
2474        }
2475        if {$wait} {
2476            set suffix {}
2477        } else {
2478            set suffix {&}
2479        }
2480        #
2481        #if $wait {
2482            append command "\; echo -n Press Enter to continue \; read x"
2483        #}
2484        if {$wait && $expgui(autoiconify)} {wm iconify .}
2485        catch {eval exec xterm $termopts -title [list $title] \
2486                -e /bin/sh -c [list $command] $suffix} errmsg
2487        if $expgui(debug) {puts "xterm result = $errmsg"}
2488        if {$wait} {
2489            if {$expgui(autoiconify)} {wm deiconify .}
2490            # check for changes in the .EXP file immediately
2491            whenidle
2492        }
2493    }
2494}
Note: See TracBrowser for help on using the repository browser.