source: trunk/GSASIIctrls.py @ 2133

Last change on this file since 2133 was 2133, checked in by toby, 7 years ago

fix svn settings for revisions & line ends

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 173.3 KB
Line 
1# -*- coding: utf-8 -*-
2#GSASIIctrls - Custom GSAS-II GUI controls
3########### SVN repository information ###################
4# $Date: 2016-01-22 19:05:12 +0000 (Fri, 22 Jan 2016) $
5# $Author: toby $
6# $Revision: 2133 $
7# $URL: trunk/GSASIIctrls.py $
8# $Id: GSASIIctrls.py 2133 2016-01-22 19:05:12Z toby $
9########### SVN repository information ###################
10'''
11*GSASIIctrls: Custom GUI controls*
12-------------------------------------------
13
14A library of GUI controls for reuse throughout GSAS-II
15
16(at present many are still in GSASIIgrid, but with time will be moved here)
17
18'''
19import os
20import sys
21import wx
22import wx.grid as wg
23# import wx.wizard as wz
24import wx.aui
25import wx.lib.scrolledpanel as wxscroll
26import time
27import copy
28# import cPickle
29# import numpy as np
30# import numpy.ma as ma
31# import scipy.optimize as so
32import wx.html        # could postpone this for quicker startup
33import webbrowser     # could postpone this for quicker startup
34
35import GSASIIpath
36GSASIIpath.SetVersionNumber("$Revision: 2133 $")
37# import GSASIImath as G2mth
38# import GSASIIIO as G2IO
39# import GSASIIstrIO as G2stIO
40# import GSASIIlattice as G2lat
41# import GSASIIplot as G2plt
42import GSASIIpwdGUI as G2pdG
43# import GSASIIimgGUI as G2imG
44# import GSASIIphsGUI as G2phG
45# import GSASIIspc as G2spc
46# import GSASIImapvars as G2mv
47# import GSASIIconstrGUI as G2cnstG
48# import GSASIIrestrGUI as G2restG
49import GSASIIpy3 as G2py3
50# import GSASIIobj as G2obj
51# import GSASIIexprGUI as G2exG
52import GSASIIlog as log
53
54# Define a short names for convenience
55WHITE = (255,255,255)
56DULL_YELLOW = (230,230,190)
57VERY_LIGHT_GREY = wx.Colour(235,235,235)
58WACV = wx.ALIGN_CENTER_VERTICAL
59
60################################################################################
61#### Tree Control
62################################################################################
63class G2TreeCtrl(wx.TreeCtrl):
64    '''Create a wrapper around the standard TreeCtrl so we can "wrap"
65    various events.
66   
67    This logs when a tree item is selected (in :meth:`onSelectionChanged`)
68
69    This also wraps lists and dicts pulled out of the tree to track where
70    they were retrieved from.
71    '''
72    def __init__(self,parent=None,*args,**kwargs):
73        super(self.__class__,self).__init__(parent=parent,*args,**kwargs)
74        self.G2frame = parent.GetParent()
75        self.root = self.AddRoot('Loaded Data: ')
76        self.SelectionChanged = None
77        self.textlist = None
78        log.LogInfo['Tree'] = self
79
80    def _getTreeItemsList(self,item):
81        '''Get the full tree hierarchy from a reference to a tree item.
82        Note that this effectively hard-codes phase and histogram names in the
83        returned list. We may want to make these names relative in the future.
84        '''
85        textlist = [self.GetItemText(item)]
86        parent = self.GetItemParent(item)
87        while parent:
88            if parent == self.root: break
89            textlist.insert(0,self.GetItemText(parent))
90            parent = self.GetItemParent(parent)
91        return textlist
92
93    def onSelectionChanged(self,event):
94        '''Log each press on a tree item here.
95        '''
96        if self.SelectionChanged:
97            textlist = self._getTreeItemsList(event.GetItem())
98            if log.LogInfo['Logging'] and event.GetItem() != self.root:
99                textlist[0] = self.GetRelativeHistNum(textlist[0])
100                if textlist[0] == "Phases" and len(textlist) > 1:
101                    textlist[1] = self.GetRelativePhaseNum(textlist[1])
102                log.MakeTreeLog(textlist)
103            if textlist == self.textlist:
104                return      #same as last time - don't get it again
105            self.textlist = textlist
106            self.SelectionChanged(event)
107
108    def Bind(self,eventtype,handler,*args,**kwargs):
109        '''Override the Bind() function so that page change events can be trapped
110        '''
111        if eventtype == wx.EVT_TREE_SEL_CHANGED:
112            self.SelectionChanged = handler
113            wx.TreeCtrl.Bind(self,eventtype,self.onSelectionChanged)
114            return
115        wx.TreeCtrl.Bind(self,eventtype,handler,*args,**kwargs)
116
117    # commented out, disables Logging
118    # def GetItemPyData(self,*args,**kwargs):
119    #    '''Override the standard method to wrap the contents
120    #    so that the source can be logged when changed
121    #    '''
122    #    data = super(self.__class__,self).GetItemPyData(*args,**kwargs)
123    #    textlist = self._getTreeItemsList(args[0])
124    #    if type(data) is dict:
125    #        return log.dictLogged(data,textlist)
126    #    if type(data) is list:
127    #        return log.listLogged(data,textlist)
128    #    if type(data) is tuple: #N.B. tuples get converted to lists
129    #        return log.listLogged(list(data),textlist)
130    #    return data
131
132    def GetRelativeHistNum(self,histname):
133        '''Returns list with a histogram type and a relative number for that
134        histogram, or the original string if not a histogram
135        '''
136        histtype = histname.split()[0]
137        if histtype != histtype.upper(): # histograms (only) have a keyword all in caps
138            return histname
139        item, cookie = self.GetFirstChild(self.root)
140        i = 0
141        while item:
142            itemtext = self.GetItemText(item)
143            if itemtext == histname:
144                return histtype,i
145            elif itemtext.split()[0] == histtype:
146                i += 1
147            item, cookie = self.GetNextChild(self.root, cookie)
148        else:
149            raise Exception("Histogram not found: "+histname)
150
151    def ConvertRelativeHistNum(self,histtype,histnum):
152        '''Converts a histogram type and relative histogram number to a
153        histogram name in the current project
154        '''
155        item, cookie = self.GetFirstChild(self.root)
156        i = 0
157        while item:
158            itemtext = self.GetItemText(item)
159            if itemtext.split()[0] == histtype:
160                if i == histnum: return itemtext
161                i += 1
162            item, cookie = self.GetNextChild(self.root, cookie)
163        else:
164            raise Exception("Histogram #'+str(histnum)+' of type "+histtype+' not found')
165       
166    def GetRelativePhaseNum(self,phasename):
167        '''Returns a phase number if the string matches a phase name
168        or else returns the original string
169        '''
170        item, cookie = self.GetFirstChild(self.root)
171        while item:
172            itemtext = self.GetItemText(item)
173            if itemtext == "Phases":
174                parent = item
175                item, cookie = self.GetFirstChild(parent)
176                i = 0
177                while item:
178                    itemtext = self.GetItemText(item)
179                    if itemtext == phasename:
180                        return i
181                    item, cookie = self.GetNextChild(parent, cookie)
182                    i += 1
183                else:
184                    return phasename # not a phase name
185            item, cookie = self.GetNextChild(self.root, cookie)
186        else:
187            raise Exception("No phases found ")
188
189    def ConvertRelativePhaseNum(self,phasenum):
190        '''Converts relative phase number to a phase name in
191        the current project
192        '''
193        item, cookie = self.GetFirstChild(self.root)
194        while item:
195            itemtext = self.GetItemText(item)
196            if itemtext == "Phases":
197                parent = item
198                item, cookie = self.GetFirstChild(parent)
199                i = 0
200                while item:
201                    if i == phasenum:
202                        return self.GetItemText(item)
203                    item, cookie = self.GetNextChild(parent, cookie)
204                    i += 1
205                else:
206                    raise Exception("Phase "+str(phasenum)+" not found")
207            item, cookie = self.GetNextChild(self.root, cookie)
208        else:
209            raise Exception("No phases found ")
210
211    def GetImageLoc(self,TreeId):
212        '''Get Image data from the Tree. Handles cases where the
213        image name is specified, as well as where the image file name is
214        a tuple containing the image file and an image number
215        '''
216       
217        size,imagefile = self.GetItemPyData(TreeId)
218        if type(imagefile) is tuple or type(imagefile) is list:
219            return size,imagefile[0],imagefile[1]
220        else:
221            return size,imagefile,None
222
223################################################################################
224#### TextCtrl that stores input as entered with optional validation
225################################################################################
226class ValidatedTxtCtrl(wx.TextCtrl):
227    '''Create a TextCtrl widget that uses a validator to prevent the
228    entry of inappropriate characters and changes color to highlight
229    when invalid input is supplied. As valid values are typed,
230    they are placed into the dict or list where the initial value
231    came from. The type of the initial value must be int,
232    float or str or None (see :obj:`key` and :obj:`typeHint`);
233    this type (or the one in :obj:`typeHint`) is preserved.
234
235    Float values can be entered in the TextCtrl as numbers or also
236    as algebraic expressions using operators + - / \* () and \*\*,
237    in addition pi, sind(), cosd(), tand(), and sqrt() can be used,
238    as well as appreviations s, sin, c, cos, t, tan and sq.
239
240    :param wx.Panel parent: name of panel or frame that will be
241      the parent to the TextCtrl. Can be None.
242
243    :param dict/list loc: the dict or list with the initial value to be
244      placed in the TextCtrl.
245
246    :param int/str key: the dict key or the list index for the value to be
247      edited by the TextCtrl. The ``loc[key]`` element must exist, but may
248      have value None. If None, the type for the element is taken from
249      :obj:`typeHint` and the value for the control is set initially
250      blank (and thus invalid.) This is a way to specify a field without a
251      default value: a user must set a valid value.
252      If the value is not None, it must have a base
253      type of int, float, str or unicode; the TextCrtl will be initialized
254      from this value.
255     
256    :param list nDig: number of digits & places ([nDig,nPlc]) after decimal to use
257      for display of float. Alternately, None can be specified which causes
258      numbers to be displayed with approximately 5 significant figures
259      (Default=None).
260
261    :param bool notBlank: if True (default) blank values are invalid
262      for str inputs.
263     
264    :param number min: minimum allowed valid value. If None (default) the
265      lower limit is unbounded.
266
267    :param number max: maximum allowed valid value. If None (default) the
268      upper limit is unbounded
269
270    :param function OKcontrol: specifies a function or method that will be
271      called when the input is validated. The called function is supplied
272      with one argument which is False if the TextCtrl contains an invalid
273      value and True if the value is valid.
274      Note that this function should check all values
275      in the dialog when True, since other entries might be invalid.
276      The default for this is None, which indicates no function should
277      be called.
278
279    :param function OnLeave: specifies a function or method that will be
280      called when the focus for the control is lost.
281      The called function is supplied with (at present) three keyword arguments:
282
283         * invalid: (*bool*) True if the value for the TextCtrl is invalid
284         * value:   (*int/float/str*)  the value contained in the TextCtrl
285         * tc:      (*wx.TextCtrl*)  the TextCtrl name
286
287      The number of keyword arguments may be increased in the future should needs arise,
288      so it is best to code these functions with a \*\*kwargs argument so they will
289      continue to run without errors
290
291      The default for OnLeave is None, which indicates no function should
292      be called.
293
294    :param type typeHint: the value of typeHint is overrides the initial value
295      for the dict/list element ``loc[key]``, if set to
296      int or float, which specifies the type for input to the TextCtrl.
297      Defaults as None, which is ignored.
298
299    :param bool CIFinput: for str input, indicates that only printable
300      ASCII characters may be entered into the TextCtrl. Forces output
301      to be ASCII rather than Unicode. For float and int input, allows
302      use of a single '?' or '.' character as valid input.
303
304    :param dict OnLeaveArgs: a dict with keyword args that are passed to
305      the :attr:`OnLeave` function. Defaults to ``{}``
306
307    :param (other): other optional keyword parameters for the
308      wx.TextCtrl widget such as size or style may be specified.
309
310    '''
311    def __init__(self,parent,loc,key,nDig=None,notBlank=True,min=None,max=None,
312                 OKcontrol=None,OnLeave=None,typeHint=None,
313                 CIFinput=False, OnLeaveArgs={}, **kw):
314        # save passed values needed outside __init__
315        self.result = loc
316        self.key = key
317        self.nDig = nDig
318        self.OKcontrol=OKcontrol
319        self.OnLeave = OnLeave
320        self.OnLeaveArgs = OnLeaveArgs
321        self.CIFinput = CIFinput
322        self.notBlank = notBlank
323        self.type = str
324        # initialization
325        self.invalid = False   # indicates if the control has invalid contents
326        self.evaluated = False # set to True when the validator recognizes an expression
327        val = loc[key]
328        if 'style' in kw: # add a "Process Enter" to style
329            kw['style'] += kw['style'] | wx.TE_PROCESS_ENTER
330        else:
331            kw['style'] = wx.TE_PROCESS_ENTER
332        if isinstance(val,int) or typeHint is int:
333            self.type = int
334            wx.TextCtrl.__init__(
335                self,parent,wx.ID_ANY,
336                validator=NumberValidator(int,result=loc,key=key,
337                                          min=min,max=max,
338                                          OKcontrol=OKcontrol,
339                                          CIFinput=CIFinput),
340                **kw)
341            if val is not None:
342                self._setValue(val)
343            else: # no default is invalid for a number
344                self.invalid = True
345                self._IndicateValidity()
346
347        elif isinstance(val,float) or typeHint is float:
348            self.type = float
349            wx.TextCtrl.__init__(
350                self,parent,wx.ID_ANY,
351                validator=NumberValidator(float,result=loc,key=key,
352                                          min=min,max=max,
353                                          OKcontrol=OKcontrol,
354                                          CIFinput=CIFinput),
355                **kw)
356            if val is not None:
357                self._setValue(val)
358            else:
359                self.invalid = True
360                self._IndicateValidity()
361
362        elif isinstance(val,str) or isinstance(val,unicode) or typeHint is str:
363            if self.CIFinput:
364                wx.TextCtrl.__init__(
365                    self,parent,wx.ID_ANY,
366                    validator=ASCIIValidator(result=loc,key=key),
367                    **kw)
368            else:
369                wx.TextCtrl.__init__(self,parent,wx.ID_ANY,**kw)
370            if val is not None:
371                self.SetValue(val)
372            if notBlank:
373                self.Bind(wx.EVT_CHAR,self._onStringKey)
374                self.ShowStringValidity() # test if valid input
375            else:
376                self.invalid = False
377                self.Bind(wx.EVT_CHAR,self._GetStringValue)
378        elif val is None:
379            raise Exception,("ValidatedTxtCtrl error: value of "+str(key)+
380                             " element is None and typeHint not defined as int or float")
381        else:
382            raise Exception,("ValidatedTxtCtrl error: Unknown element ("+str(key)+
383                             ") type: "+str(type(val)))
384        # When the mouse is moved away or the widget loses focus,
385        # display the last saved value, if an expression
386        self.Bind(wx.EVT_LEAVE_WINDOW, self._onLeaveWindow)
387        self.Bind(wx.EVT_TEXT_ENTER, self._onLoseFocus)
388        self.Bind(wx.EVT_KILL_FOCUS, self._onLoseFocus)
389        # patch for wx 2.9 on Mac
390        i,j= wx.__version__.split('.')[0:2]
391        if int(i)+int(j)/10. > 2.8 and 'wxOSX' in wx.PlatformInfo:
392            self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
393
394    def SetValue(self,val):
395        if self.result is not None: # note that this bypasses formatting
396            self.result[self.key] = val
397            log.LogVarChange(self.result,self.key)
398        self._setValue(val)
399
400    def _setValue(self,val,show=True):
401        '''Check the validity of an int or float value and convert to a str.
402        Possibly format it. If show is True, display the formatted value in
403        the Text widget.
404        '''
405        self.invalid = False
406        if self.type is int:
407            try:
408                if int(val) != val:
409                    self.invalid = True
410                else:
411                    val = int(val)
412            except:
413                if self.CIFinput and (val == '?' or val == '.'):
414                    pass
415                else:
416                    self.invalid = True
417            if show: wx.TextCtrl.SetValue(self,str(val))
418        elif self.type is float:
419            try:
420                val = float(val) # convert strings, if needed
421            except:
422                if self.CIFinput and (val == '?' or val == '.'):
423                    pass
424                else:
425                    self.invalid = True
426            if self.nDig and show:
427                wx.TextCtrl.SetValue(self,str(G2py3.FormatValue(val,self.nDig)))
428            elif show:
429                wx.TextCtrl.SetValue(self,str(G2py3.FormatSigFigs(val)).rstrip('0'))
430        else:
431            if show: wx.TextCtrl.SetValue(self,str(val))
432            self.ShowStringValidity() # test if valid input
433            return
434       
435        self._IndicateValidity()
436        if self.OKcontrol:
437            self.OKcontrol(not self.invalid)
438
439    def OnKeyDown(self,event):
440        'Special callback for wx 2.9+ on Mac where backspace is not processed by validator'
441        key = event.GetKeyCode()
442        if key in [wx.WXK_BACK, wx.WXK_DELETE]:
443            if self.Validator: wx.CallAfter(self.Validator.TestValid,self)
444        if key == wx.WXK_RETURN or key == wx.WXK_NUMPAD_ENTER:
445            self._onLoseFocus(None)
446        event.Skip()
447                   
448    def _onStringKey(self,event):
449        event.Skip()
450        if self.invalid: # check for validity after processing the keystroke
451            wx.CallAfter(self.ShowStringValidity,True) # was invalid
452        else:
453            wx.CallAfter(self.ShowStringValidity,False) # was valid
454
455    def _IndicateValidity(self):
456        'Set the control colors to show invalid input'
457        if self.invalid:
458            self.SetForegroundColour("red")
459            self.SetBackgroundColour("yellow")
460            self.SetFocus()
461            self.Refresh()
462        else: # valid input
463            self.SetBackgroundColour(
464                wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW))
465            self.SetForegroundColour("black")
466            self.Refresh()
467
468    def ShowStringValidity(self,previousInvalid=True):
469        '''Check if input is valid. Anytime the input is
470        invalid, call self.OKcontrol (if defined) because it is fast.
471        If valid, check for any other invalid entries only when
472        changing from invalid to valid, since that is slower.
473       
474        :param bool previousInvalid: True if the TextCtrl contents were
475          invalid prior to the current change.
476         
477        '''
478        val = self.GetValue().strip()
479        if self.notBlank:
480            self.invalid = not val
481        else:
482            self.invalid = False
483        self._IndicateValidity()
484        if self.invalid:
485            if self.OKcontrol:
486                self.OKcontrol(False)
487        elif self.OKcontrol and previousInvalid:
488            self.OKcontrol(True)
489        # always store the result
490        if self.CIFinput: # for CIF make results ASCII
491            self.result[self.key] = val.encode('ascii','replace') 
492        else:
493            self.result[self.key] = val
494        log.LogVarChange(self.result,self.key)
495
496    def _GetStringValue(self,event):
497        '''Get string input and store.
498        '''
499        event.Skip() # process keystroke
500        wx.CallAfter(self._SaveStringValue)
501       
502    def _SaveStringValue(self):
503        val = self.GetValue().strip()
504        # always store the result
505        if self.CIFinput: # for CIF make results ASCII
506            self.result[self.key] = val.encode('ascii','replace') 
507        else:
508            self.result[self.key] = val
509        log.LogVarChange(self.result,self.key)
510
511    def _onLeaveWindow(self,event):
512        '''If the mouse leaves the text box, save the result, if valid,
513        but (unlike _onLoseFocus) don't update the textbox contents.
514        '''
515        if self.evaluated and not self.invalid: # deal with computed expressions
516            self.evaluated = False # expression has been recast as value, reset flag
517        if self.invalid: # don't update an invalid expression
518            if event: event.Skip()
519            return
520        self._setValue(self.result[self.key],show=False) # save value quietly
521        if self.OnLeave: self.OnLeave(invalid=self.invalid,
522                                      value=self.result[self.key],
523                                      tc=self,
524                                      **self.OnLeaveArgs)
525        if event: event.Skip()
526           
527    def _onLoseFocus(self,event):
528        '''Enter has been pressed or focus transferred to another control,
529        Evaluate and update the current control contents
530        '''
531        if self.evaluated: # deal with computed expressions
532            if self.invalid: # don't substitute for an invalid expression
533                if event: event.Skip()
534                return 
535            self.evaluated = False # expression has been recast as value, reset flag
536            self._setValue(self.result[self.key])
537        elif self.result is not None: # show formatted result, as Bob wants
538            if not self.invalid: # don't update an invalid expression
539                self._setValue(self.result[self.key])
540        if self.OnLeave: self.OnLeave(invalid=self.invalid,
541                                      value=self.result[self.key],
542                                      tc=self,
543                                      **self.OnLeaveArgs)
544        if event: event.Skip()
545
546################################################################################
547class NumberValidator(wx.PyValidator):
548    '''A validator to be used with a TextCtrl to prevent
549    entering characters other than digits, signs, and for float
550    input, a period and exponents.
551   
552    The value is checked for validity after every keystroke
553      If an invalid number is entered, the box is highlighted.
554      If the number is valid, it is saved in result[key]
555
556    :param type typ: the base data type. Must be int or float.
557
558    :param bool positiveonly: If True, negative integers are not allowed
559      (default False). This prevents the + or - keys from being pressed.
560      Used with typ=int; ignored for typ=float.
561
562    :param number min: Minimum allowed value. If None (default) the
563      lower limit is unbounded
564
565    :param number max: Maximum allowed value. If None (default) the
566      upper limit is unbounded
567     
568    :param dict/list result: List or dict where value should be placed when valid
569
570    :param any key: key to use for result (int for list)
571
572    :param function OKcontrol: function or class method to control
573      an OK button for a window.
574      Ignored if None (default)
575
576    :param bool CIFinput: allows use of a single '?' or '.' character
577      as valid input.
578     
579    '''
580    def __init__(self, typ, positiveonly=False, min=None, max=None,
581                 result=None, key=None, OKcontrol=None, CIFinput=False):
582        'Create the validator'
583        wx.PyValidator.__init__(self)
584        # save passed parameters
585        self.typ = typ
586        self.positiveonly = positiveonly
587        self.min = min
588        self.max = max
589        self.result = result
590        self.key = key
591        self.OKcontrol = OKcontrol
592        self.CIFinput = CIFinput
593        # set allowed keys by data type
594        self.Bind(wx.EVT_CHAR, self.OnChar)
595        if self.typ == int and self.positiveonly:
596            self.validchars = '0123456789'
597        elif self.typ == int:
598            self.validchars = '0123456789+-'
599        elif self.typ == float:
600            # allow for above and sind, cosd, sqrt, tand, pi, and abbreviations
601            # also addition, subtraction, division, multiplication, exponentiation
602            self.validchars = '0123456789.-+eE/cosindcqrtap()*'
603        else:
604            self.validchars = None
605            return
606        if self.CIFinput:
607            self.validchars += '?.'
608    def Clone(self):
609        'Create a copy of the validator, a strange, but required component'
610        return NumberValidator(typ=self.typ, 
611                               positiveonly=self.positiveonly,
612                               min=self.min, max=self.max,
613                               result=self.result, key=self.key,
614                               OKcontrol=self.OKcontrol,
615                               CIFinput=self.CIFinput)
616    def TransferToWindow(self):
617        'Needed by validator, strange, but required component'
618        return True # Prevent wxDialog from complaining.
619    def TransferFromWindow(self):
620        'Needed by validator, strange, but required component'
621        return True # Prevent wxDialog from complaining.
622    def TestValid(self,tc):
623        '''Check if the value is valid by casting the input string
624        into the current type.
625
626        Set the invalid variable in the TextCtrl object accordingly.
627
628        If the value is valid, save it in the dict/list where
629        the initial value was stored, if appropriate.
630
631        :param wx.TextCtrl tc: A reference to the TextCtrl that the validator
632          is associated with.
633        '''
634        tc.invalid = False # assume valid
635        if self.CIFinput:
636            val = tc.GetValue().strip()
637            if val == '?' or val == '.':
638                self.result[self.key] = val
639                log.LogVarChange(self.result,self.key)
640                return
641        try:
642            val = self.typ(tc.GetValue())
643        except (ValueError, SyntaxError) as e:
644            if self.typ is float: # for float values, see if an expression can be evaluated
645                val = G2py3.FormulaEval(tc.GetValue())
646                if val is None:
647                    tc.invalid = True
648                    return
649                else:
650                    tc.evaluated = True
651            else: 
652                tc.invalid = True
653                return
654        # if self.max != None and self.typ == int:
655        #     if val > self.max:
656        #         tc.invalid = True
657        # if self.min != None and self.typ == int:
658        #     if val < self.min:
659        #         tc.invalid = True  # invalid
660        if self.max != None:
661            if val > self.max:
662                tc.invalid = True
663        if self.min != None:
664            if val < self.min:
665                tc.invalid = True  # invalid
666        if self.key is not None and self.result is not None and not tc.invalid:
667            self.result[self.key] = val
668            log.LogVarChange(self.result,self.key)
669
670    def ShowValidity(self,tc):
671        '''Set the control colors to show invalid input
672
673        :param wx.TextCtrl tc: A reference to the TextCtrl that the validator
674          is associated with.
675
676        '''
677        if tc.invalid:
678            tc.SetForegroundColour("red")
679            tc.SetBackgroundColour("yellow")
680            tc.SetFocus()
681            tc.Refresh()
682            return False
683        else: # valid input
684            tc.SetBackgroundColour(
685                wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW))
686            tc.SetForegroundColour("black")
687            tc.Refresh()
688            return True
689
690    def CheckInput(self,previousInvalid):
691        '''called to test every change to the TextCtrl for validity and
692        to change the appearance of the TextCtrl
693
694        Anytime the input is invalid, call self.OKcontrol
695        (if defined) because it is fast.
696        If valid, check for any other invalid entries only when
697        changing from invalid to valid, since that is slower.
698
699        :param bool previousInvalid: True if the TextCtrl contents were
700          invalid prior to the current change.
701        '''
702        tc = self.GetWindow()
703        self.TestValid(tc)
704        self.ShowValidity(tc)
705        # if invalid
706        if tc.invalid and self.OKcontrol:
707            self.OKcontrol(False)
708        if not tc.invalid and self.OKcontrol and previousInvalid:
709            self.OKcontrol(True)
710
711    def OnChar(self, event):
712        '''Called each type a key is pressed
713        ignores keys that are not allowed for int and float types
714        '''
715        key = event.GetKeyCode()
716        tc = self.GetWindow()
717        if key == wx.WXK_RETURN or key == wx.WXK_NUMPAD_ENTER:
718            if tc.invalid:
719                self.CheckInput(True) 
720            else:
721                self.CheckInput(False) 
722            event.Skip()
723            return
724        if key < wx.WXK_SPACE or key == wx.WXK_DELETE or key > 255: # control characters get processed
725            event.Skip()
726            if tc.invalid:
727                wx.CallAfter(self.CheckInput,True) 
728            else:
729                wx.CallAfter(self.CheckInput,False) 
730            return
731        elif chr(key) in self.validchars: # valid char pressed?
732            event.Skip()
733            if tc.invalid:
734                wx.CallAfter(self.CheckInput,True) 
735            else:
736                wx.CallAfter(self.CheckInput,False) 
737            return
738        if not wx.Validator_IsSilent(): wx.Bell()
739        return  # Returning without calling event.Skip, which eats the keystroke
740
741################################################################################
742class ASCIIValidator(wx.PyValidator):
743    '''A validator to be used with a TextCtrl to prevent
744    entering characters other than ASCII characters.
745   
746    The value is checked for validity after every keystroke
747      If an invalid number is entered, the box is highlighted.
748      If the number is valid, it is saved in result[key]
749
750    :param dict/list result: List or dict where value should be placed when valid
751
752    :param any key: key to use for result (int for list)
753
754    '''
755    def __init__(self, result=None, key=None):
756        'Create the validator'
757        import string
758        wx.PyValidator.__init__(self)
759        # save passed parameters
760        self.result = result
761        self.key = key
762        self.validchars = string.ascii_letters + string.digits + string.punctuation + string.whitespace
763        self.Bind(wx.EVT_CHAR, self.OnChar)
764    def Clone(self):
765        'Create a copy of the validator, a strange, but required component'
766        return ASCIIValidator(result=self.result, key=self.key)
767        tc = self.GetWindow()
768        tc.invalid = False # make sure the validity flag is defined in parent
769    def TransferToWindow(self):
770        'Needed by validator, strange, but required component'
771        return True # Prevent wxDialog from complaining.
772    def TransferFromWindow(self):
773        'Needed by validator, strange, but required component'
774        return True # Prevent wxDialog from complaining.
775    def TestValid(self,tc):
776        '''Check if the value is valid by casting the input string
777        into ASCII.
778
779        Save it in the dict/list where the initial value was stored
780
781        :param wx.TextCtrl tc: A reference to the TextCtrl that the validator
782          is associated with.
783        '''
784        self.result[self.key] = tc.GetValue().encode('ascii','replace')
785        log.LogVarChange(self.result,self.key)
786
787    def OnChar(self, event):
788        '''Called each type a key is pressed
789        ignores keys that are not allowed for int and float types
790        '''
791        key = event.GetKeyCode()
792        tc = self.GetWindow()
793        if key == wx.WXK_RETURN or key == wx.WXK_NUMPAD_ENTER:
794            self.TestValid(tc)
795            event.Skip()
796            return
797        if key < wx.WXK_SPACE or key == wx.WXK_DELETE or key > 255: # control characters get processed
798            event.Skip()
799            self.TestValid(tc)
800            return
801        elif chr(key) in self.validchars: # valid char pressed?
802            event.Skip()
803            self.TestValid(tc)
804            return
805        if not wx.Validator_IsSilent():
806            wx.Bell()
807        return  # Returning without calling event.Skip, which eats the keystroke
808
809################################################################################
810def HorizontalLine(sizer,parent):
811    '''Draws a horizontal line as wide as the window.
812    This shows up on the Mac as a very thin line, no matter what I do
813    '''
814    line = wx.StaticLine(parent,-1, size=(-1,3), style=wx.LI_HORIZONTAL)
815    sizer.Add(line, 0, wx.EXPAND|wx.ALIGN_CENTER|wx.ALL, 10)
816
817################################################################################
818class G2LoggedButton(wx.Button):
819    '''A version of wx.Button that creates logging events. Bindings are saved
820    in the object, and are looked up rather than directly set with a bind.
821    An index to these buttons is saved as log.ButtonBindingLookup
822    :param wx.Panel parent: parent widget
823    :param int id: Id for button
824    :param str label: label for button
825    :param str locationcode: a label used internally to uniquely indentify the button
826    :param function handler: a routine to call when the button is pressed
827    '''
828    def __init__(self,parent,id=wx.ID_ANY,label='',locationcode='',
829                 handler=None,*args,**kwargs):
830        super(self.__class__,self).__init__(parent,id,label,*args,**kwargs)
831        self.label = label
832        self.handler = handler
833        self.locationcode = locationcode
834        key = locationcode + '+' + label # hash code to find button
835        self.Bind(wx.EVT_BUTTON,self.onPress)
836        log.ButtonBindingLookup[key] = self
837    def onPress(self,event):
838        'create log event and call handler'
839        log.MakeButtonLog(self.locationcode,self.label)
840        self.handler(event)
841       
842################################################################################
843class EnumSelector(wx.ComboBox):
844    '''A customized :class:`wxpython.ComboBox` that selects items from a list
845    of choices, but sets a dict (list) entry to the corresponding
846    entry from the input list of values.
847
848    :param wx.Panel parent: the parent to the :class:`~wxpython.ComboBox` (usually a
849      frame or panel)
850    :param dict dct: a dict (or list) to contain the value set
851      for the :class:`~wxpython.ComboBox`.
852    :param item: the dict key (or list index) where ``dct[item]`` will
853      be set to the value selected in the :class:`~wxpython.ComboBox`. Also, dct[item]
854      contains the starting value shown in the widget. If the value
855      does not match an entry in :data:`values`, the first value
856      in :data:`choices` is used as the default, but ``dct[item]`` is
857      not changed.   
858    :param list choices: a list of choices to be displayed to the
859      user such as
860      ::
861     
862      ["default","option 1","option 2",]
863
864      Note that these options will correspond to the entries in
865      :data:`values` (if specified) item by item.
866    :param list values: a list of values that correspond to
867      the options in :data:`choices`, such as
868      ::
869     
870      [0,1,2]
871     
872      The default for :data:`values` is to use the same list as
873      specified for :data:`choices`.
874    :param (other): additional keyword arguments accepted by
875      :class:`~wxpython.ComboBox` can be specified.
876    '''
877    def __init__(self,parent,dct,item,choices,values=None,**kw):
878        if values is None:
879            values = choices
880        if dct[item] in values:
881            i = values.index(dct[item])
882        else:
883            i = 0
884        startval = choices[i]
885        wx.ComboBox.__init__(self,parent,wx.ID_ANY,startval,
886                             choices = choices,
887                             style=wx.CB_DROPDOWN|wx.CB_READONLY,
888                             **kw)
889        self.choices = choices
890        self.values = values
891        self.dct = dct
892        self.item = item
893        self.Bind(wx.EVT_COMBOBOX, self.onSelection)
894    def onSelection(self,event):
895        # respond to a selection by setting the enum value in the CIF dictionary
896        if self.GetValue() in self.choices: # should always be true!
897            self.dct[self.item] = self.values[self.choices.index(self.GetValue())]
898        else:
899            self.dct[self.item] = self.values[0] # unknown
900
901################################################################################
902class G2ChoiceButton(wx.Choice):
903    '''A customized version of a wx.Choice that automatically initializes
904    the control to match a supplied value and saves the choice directly
905    into an array or list. Optionally a function can be called each time a
906    choice is selected. The widget can be used with an array item that is set to
907    to the choice by number (``indLoc[indKey]``) or by string value
908    (``strLoc[strKey]``) or both. The initial value is taken from ``indLoc[indKey]``
909    if not None or ``strLoc[strKey]`` if not None.
910
911    :param wx.Panel parent: name of panel or frame that will be
912      the parent to the widget. Can be None.
913    :param list choiceList: a list or tuple of choices to offer the user.
914    :param dict/list indLoc: a dict or list with the initial value to be
915      placed in the Choice button. If this is None, this is ignored.
916    :param int/str indKey: the dict key or the list index for the value to be
917      edited by the Choice button. If indLoc is not None then this
918      must be specified and the ``indLoc[indKey]`` will be set. If the value
919      for ``indLoc[indKey]`` is not None, it should be an integer in
920      range(len(choiceList)). The Choice button will be initialized to the
921      choice corresponding to the value in this element if not None.
922    :param dict/list strLoc: a dict or list with the string value corresponding to
923      indLoc/indKey. Default (None) means that this is not used.
924    :param int/str strKey: the dict key or the list index for the string value
925      The ``strLoc[strKey]`` element must exist or strLoc must be None (default).
926    :param function onChoice: name of a function to call when the choice is made.
927    '''
928    def __init__(self,parent,choiceList,indLoc=None,indKey=None,strLoc=None,strKey=None,
929                 onChoice=None,**kwargs):
930        wx.Choice.__init__(self,parent,choices=choiceList,id=wx.ID_ANY,**kwargs)
931        self.choiceList = choiceList
932        self.indLoc = indLoc
933        self.indKey = indKey
934        self.strLoc = strLoc
935        self.strKey = strKey
936        self.onChoice = None
937        self.SetSelection(wx.NOT_FOUND)
938        if self.indLoc is not None and self.indLoc.get(self.indKey) is not None:
939            self.SetSelection(self.indLoc[self.indKey])
940            if self.strLoc is not None:
941                self.strLoc[self.strKey] = self.GetStringSelection()
942                log.LogVarChange(self.strLoc,self.strKey)
943        elif self.strLoc is not None and self.strLoc.get(self.strKey) is not None:
944            try:
945                self.SetSelection(choiceList.index(self.strLoc[self.strKey]))
946                if self.indLoc is not None:
947                    self.indLoc[self.indKey] = self.GetSelection()
948                    log.LogVarChange(self.indLoc,self.indKey)
949            except ValueError:
950                pass
951        self.Bind(wx.EVT_CHOICE, self._OnChoice)
952        #if self.strLoc is not None: # make sure strLoc gets initialized
953        #    self._OnChoice(None) # note that onChoice will not be called
954        self.onChoice = onChoice
955    def _OnChoice(self,event):
956        if self.indLoc is not None:
957            self.indLoc[self.indKey] = self.GetSelection()
958            log.LogVarChange(self.indLoc,self.indKey)
959        if self.strLoc is not None:
960            self.strLoc[self.strKey] = self.GetStringSelection()
961            log.LogVarChange(self.strLoc,self.strKey)
962        if self.onChoice:
963            self.onChoice()
964
965############################################################### Custom checkbox that saves values into dict/list as used
966class G2CheckBox(wx.CheckBox):
967    '''A customized version of a CheckBox that automatically initializes
968    the control to a supplied list or dict entry and updates that
969    entry as the widget is used.
970
971    :param wx.Panel parent: name of panel or frame that will be
972      the parent to the widget. Can be None.
973    :param str label: text to put on check button
974    :param dict/list loc: the dict or list with the initial value to be
975      placed in the CheckBox.
976    :param int/str key: the dict key or the list index for the value to be
977      edited by the CheckBox. The ``loc[key]`` element must exist.
978      The CheckBox will be initialized from this value.
979      If the value is anything other that True (or 1), it will be taken as
980      False.
981    :param function OnChange: specifies a function or method that will be
982      called when the CheckBox is changed (Default is None).
983      The called function is supplied with one argument, the calling event.
984    '''
985    def __init__(self,parent,label,loc,key,OnChange=None):
986        wx.CheckBox.__init__(self,parent,id=wx.ID_ANY,label=label)
987        self.loc = loc
988        self.key = key
989        self.OnChange = OnChange
990        self.SetValue(self.loc[self.key]==True)
991        self.Bind(wx.EVT_CHECKBOX, self._OnCheckBox)
992    def _OnCheckBox(self,event):
993        self.loc[self.key] = self.GetValue()
994        log.LogVarChange(self.loc,self.key)
995        if self.OnChange: self.OnChange(event)
996                   
997################################################################################
998#### Commonly used dialogs
999################################################################################
1000def CallScrolledMultiEditor(parent,dictlst,elemlst,prelbl=[],postlbl=[],
1001                 title='Edit items',header='',size=(300,250),
1002                             CopyButton=False, **kw):
1003    '''Shell routine to call a ScrolledMultiEditor dialog. See
1004    :class:`ScrolledMultiEditor` for parameter definitions.
1005
1006    :returns: True if the OK button is pressed; False if the window is closed
1007      with the system menu or the Cancel button.
1008
1009    '''
1010    dlg = ScrolledMultiEditor(parent,dictlst,elemlst,prelbl,postlbl,
1011                              title,header,size,
1012                              CopyButton, **kw)
1013    if dlg.ShowModal() == wx.ID_OK:
1014        dlg.Destroy()
1015        return True
1016    else:
1017        dlg.Destroy()
1018        return False
1019
1020################################################################################
1021class ScrolledMultiEditor(wx.Dialog):
1022    '''Define a window for editing a potentially large number of dict- or
1023    list-contained values with validation for each item. Edited values are
1024    automatically placed in their source location. If invalid entries
1025    are provided, the TextCtrl is turned yellow and the OK button is disabled.
1026
1027    The type for each TextCtrl validation is determined by the
1028    initial value of the entry (int, float or string).
1029    Float values can be entered in the TextCtrl as numbers or also
1030    as algebraic expressions using operators + - / \* () and \*\*,
1031    in addition pi, sind(), cosd(), tand(), and sqrt() can be used,
1032    as well as appreviations s(), sin(), c(), cos(), t(), tan() and sq().
1033
1034    :param wx.Frame parent: name of parent window, or may be None
1035
1036    :param tuple dictlst: a list of dicts or lists containing values to edit
1037
1038    :param tuple elemlst: a list of keys for each item in a dictlst. Must have the
1039      same length as dictlst.
1040
1041    :param wx.Frame parent: name of parent window, or may be None
1042   
1043    :param tuple prelbl: a list of labels placed before the TextCtrl for each
1044      item (optional)
1045   
1046    :param tuple postlbl: a list of labels placed after the TextCtrl for each
1047      item (optional)
1048
1049    :param str title: a title to place in the frame of the dialog
1050
1051    :param str header: text to place at the top of the window. May contain
1052      new line characters.
1053
1054    :param wx.Size size: a size parameter that dictates the
1055      size for the scrolled region of the dialog. The default is
1056      (300,250).
1057
1058    :param bool CopyButton: if True adds a small button that copies the
1059      value for the current row to all fields below (default is False)
1060     
1061    :param list minvals: optional list of minimum values for validation
1062      of float or int values. Ignored if value is None.
1063    :param list maxvals: optional list of maximum values for validation
1064      of float or int values. Ignored if value is None.
1065    :param list sizevals: optional list of wx.Size values for each input
1066      widget. Ignored if value is None.
1067     
1068    :param tuple checkdictlst: an optional list of dicts or lists containing bool
1069      values (similar to dictlst).
1070    :param tuple checkelemlst: an optional list of dicts or lists containing bool
1071      key values (similar to elemlst). Must be used with checkdictlst.
1072    :param string checklabel: a string to use for each checkbutton
1073     
1074    :returns: the wx.Dialog created here. Use method .ShowModal() to display it.
1075   
1076    *Example for use of ScrolledMultiEditor:*
1077
1078    ::
1079
1080        dlg = <pkg>.ScrolledMultiEditor(frame,dictlst,elemlst,prelbl,postlbl,
1081                                        header=header)
1082        if dlg.ShowModal() == wx.ID_OK:
1083             for d,k in zip(dictlst,elemlst):
1084                 print d[k]
1085
1086    *Example definitions for dictlst and elemlst:*
1087
1088    ::
1089     
1090          dictlst = (dict1,list1,dict1,list1)
1091          elemlst = ('a', 1, 2, 3)
1092
1093      This causes items dict1['a'], list1[1], dict1[2] and list1[3] to be edited.
1094   
1095    Note that these items must have int, float or str values assigned to
1096    them. The dialog will force these types to be retained. String values
1097    that are blank are marked as invalid.
1098    '''
1099   
1100    def __init__(self,parent,dictlst,elemlst,prelbl=[],postlbl=[],
1101                 title='Edit items',header='',size=(300,250),
1102                 CopyButton=False,
1103                 minvals=[],maxvals=[],sizevals=[],
1104                 checkdictlst=[], checkelemlst=[], checklabel=""):
1105        if len(dictlst) != len(elemlst):
1106            raise Exception,"ScrolledMultiEditor error: len(dictlst) != len(elemlst) "+str(len(dictlst))+" != "+str(len(elemlst))
1107        if len(checkdictlst) != len(checkelemlst):
1108            raise Exception,"ScrolledMultiEditor error: len(checkdictlst) != len(checkelemlst) "+str(len(checkdictlst))+" != "+str(len(checkelemlst))
1109        wx.Dialog.__init__( # create dialog & sizer
1110            self,parent,wx.ID_ANY,title,
1111            style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)
1112        mainSizer = wx.BoxSizer(wx.VERTICAL)
1113        self.orig = []
1114        self.dictlst = dictlst
1115        self.elemlst = elemlst
1116        self.checkdictlst = checkdictlst
1117        self.checkelemlst = checkelemlst
1118        self.StartCheckValues = [checkdictlst[i][checkelemlst[i]] for i in range(len(checkdictlst))]
1119        self.ButtonIndex = {}
1120        for d,i in zip(dictlst,elemlst):
1121            self.orig.append(d[i])
1122        # add a header if supplied
1123        if header:
1124            subSizer = wx.BoxSizer(wx.HORIZONTAL)
1125            subSizer.Add((-1,-1),1,wx.EXPAND)
1126            subSizer.Add(wx.StaticText(self,wx.ID_ANY,header))
1127            subSizer.Add((-1,-1),1,wx.EXPAND)
1128            mainSizer.Add(subSizer,0,wx.EXPAND,0)
1129        # make OK button now, because we will need it for validation
1130        self.OKbtn = wx.Button(self, wx.ID_OK)
1131        self.OKbtn.SetDefault()
1132        # create scrolled panel and sizer
1133        panel = wxscroll.ScrolledPanel(self, wx.ID_ANY,size=size,
1134            style = wx.TAB_TRAVERSAL|wx.SUNKEN_BORDER)
1135        cols = 4
1136        if CopyButton: cols += 1
1137        subSizer = wx.FlexGridSizer(cols=cols,hgap=2,vgap=2)
1138        self.ValidatedControlsList = [] # make list of TextCtrls
1139        self.CheckControlsList = [] # make list of CheckBoxes
1140        for i,(d,k) in enumerate(zip(dictlst,elemlst)):
1141            if i >= len(prelbl): # label before TextCtrl, or put in a blank
1142                subSizer.Add((-1,-1)) 
1143            else:
1144                subSizer.Add(wx.StaticText(panel,wx.ID_ANY,str(prelbl[i])))
1145            kargs = {}
1146            if i < len(minvals):
1147                if minvals[i] is not None: kargs['min']=minvals[i]
1148            if i < len(maxvals):
1149                if maxvals[i] is not None: kargs['max']=maxvals[i]
1150            if i < len(sizevals):
1151                if sizevals[i]: kargs['size']=sizevals[i]
1152            if CopyButton:
1153                import wx.lib.colourselect as wscs
1154                but = wscs.ColourSelect(label='v', # would like to use u'\u2193' or u'\u25BC' but not in WinXP
1155                                        # is there a way to test?
1156                                        parent=panel,
1157                                        colour=(255,255,200),
1158                                        size=wx.Size(30,23),
1159                                        style=wx.RAISED_BORDER)
1160                but.Bind(wx.EVT_BUTTON, self._OnCopyButton)
1161                but.SetToolTipString('Press to copy adjacent value to all rows below')
1162                self.ButtonIndex[but] = i
1163                subSizer.Add(but)
1164            # create the validated TextCrtl, store it and add it to the sizer
1165            ctrl = ValidatedTxtCtrl(panel,d,k,OKcontrol=self.ControlOKButton,
1166                                    **kargs)
1167            self.ValidatedControlsList.append(ctrl)
1168            subSizer.Add(ctrl)
1169            if i < len(postlbl): # label after TextCtrl, or put in a blank
1170                subSizer.Add(wx.StaticText(panel,wx.ID_ANY,str(postlbl[i])))
1171            else:
1172                subSizer.Add((-1,-1))
1173            if i < len(checkdictlst):
1174                ch = G2CheckBox(panel,checklabel,checkdictlst[i],checkelemlst[i])
1175                self.CheckControlsList.append(ch)
1176                subSizer.Add(ch)                   
1177            else:
1178                subSizer.Add((-1,-1))
1179        # finish up ScrolledPanel
1180        panel.SetSizer(subSizer)
1181        panel.SetAutoLayout(1)
1182        panel.SetupScrolling()
1183        # patch for wx 2.9 on Mac
1184        i,j= wx.__version__.split('.')[0:2]
1185        if int(i)+int(j)/10. > 2.8 and 'wxOSX' in wx.PlatformInfo:
1186            panel.SetMinSize((subSizer.GetSize()[0]+30,panel.GetSize()[1]))       
1187        mainSizer.Add(panel,1, wx.ALL|wx.EXPAND,1)
1188
1189        # Sizer for OK/Close buttons. N.B. on Close changes are discarded
1190        # by restoring the initial values
1191        btnsizer = wx.BoxSizer(wx.HORIZONTAL)
1192        btnsizer.Add(self.OKbtn)
1193        btn = wx.Button(self, wx.ID_CLOSE,"Cancel") 
1194        btn.Bind(wx.EVT_BUTTON,self._onClose)
1195        btnsizer.Add(btn)
1196        mainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER|wx.ALL, 5)
1197        # size out the window. Set it to be enlarged but not made smaller
1198        self.SetSizer(mainSizer)
1199        mainSizer.Fit(self)
1200        self.SetMinSize(self.GetSize())
1201
1202    def _OnCopyButton(self,event):
1203        'Implements the copy down functionality'
1204        but = event.GetEventObject()
1205        n = self.ButtonIndex.get(but)
1206        if n is None: return
1207        for i,(d,k,ctrl) in enumerate(zip(self.dictlst,self.elemlst,self.ValidatedControlsList)):
1208            if i < n: continue
1209            if i == n:
1210                val = d[k]
1211                continue
1212            d[k] = val
1213            ctrl.SetValue(val)
1214        for i in range(len(self.checkdictlst)):
1215            if i < n: continue
1216            self.checkdictlst[i][self.checkelemlst[i]] = self.checkdictlst[n][self.checkelemlst[n]]
1217            self.CheckControlsList[i].SetValue(self.checkdictlst[i][self.checkelemlst[i]])
1218    def _onClose(self,event):
1219        'Used on Cancel: Restore original values & close the window'
1220        for d,i,v in zip(self.dictlst,self.elemlst,self.orig):
1221            d[i] = v
1222        for i in range(len(self.checkdictlst)):
1223            self.checkdictlst[i][self.checkelemlst[i]] = self.StartCheckValues[i]
1224        self.EndModal(wx.ID_CANCEL)
1225       
1226    def ControlOKButton(self,setvalue):
1227        '''Enable or Disable the OK button for the dialog. Note that this is
1228        passed into the ValidatedTxtCtrl for use by validators.
1229
1230        :param bool setvalue: if True, all entries in the dialog are
1231          checked for validity. if False then the OK button is disabled.
1232
1233        '''
1234        if setvalue: # turn button on, do only if all controls show as valid
1235            for ctrl in self.ValidatedControlsList:
1236                if ctrl.invalid:
1237                    self.OKbtn.Disable()
1238                    return
1239            else:
1240                self.OKbtn.Enable()
1241        else:
1242            self.OKbtn.Disable()
1243
1244###############################################  Multichoice Dialog with set all, toggle & filter options
1245class G2MultiChoiceDialog(wx.Dialog):
1246    '''A dialog similar to MultiChoiceDialog except that buttons are
1247    added to set all choices and to toggle all choices.
1248
1249    :param wx.Frame ParentFrame: reference to parent frame
1250    :param str title: heading above list of choices
1251    :param str header: Title to place on window frame
1252    :param list ChoiceList: a list of choices where one will be selected
1253    :param bool toggle: If True (default) the toggle and select all buttons
1254      are displayed
1255    :param bool monoFont: If False (default), use a variable-spaced font;
1256      if True use a equally-spaced font.
1257    :param bool filterBox: If True (default) an input widget is placed on
1258      the window and only entries matching the entered text are shown.
1259    :param kw: optional keyword parameters for the wx.Dialog may
1260      be included such as size [which defaults to `(320,310)`] and
1261      style (which defaults to `wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER|wx.CENTRE| wx.OK | wx.CANCEL`);
1262      note that `wx.OK` and `wx.CANCEL` controls
1263      the presence of the eponymous buttons in the dialog.
1264    :returns: the name of the created dialog 
1265    '''
1266    def __init__(self,parent, title, header, ChoiceList, toggle=True,
1267                 monoFont=False, filterBox=True, **kw):
1268        # process keyword parameters, notably style
1269        options = {'size':(320,310), # default Frame keywords
1270                   'style':wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER|wx.CENTRE| wx.OK | wx.CANCEL,
1271                   }
1272        options.update(kw)
1273        self.ChoiceList = ChoiceList # list of choices (list of str values)
1274        self.Selections = len(self.ChoiceList) * [False,] # selection status for each choice (list of bools)
1275        self.filterlist = range(len(self.ChoiceList)) # list of the choice numbers that have been filtered (list of int indices)
1276        if options['style'] & wx.OK:
1277            useOK = True
1278            options['style'] ^= wx.OK
1279        else:
1280            useOK = False
1281        if options['style'] & wx.CANCEL:
1282            useCANCEL = True
1283            options['style'] ^= wx.CANCEL
1284        else:
1285            useCANCEL = False       
1286        # create the dialog frame
1287        wx.Dialog.__init__(self,parent,wx.ID_ANY,header,**options)
1288        # fill the dialog
1289        Sizer = wx.BoxSizer(wx.VERTICAL)
1290        topSizer = wx.BoxSizer(wx.HORIZONTAL)
1291        topSizer.Add(wx.StaticText(self,wx.ID_ANY,title,size=(-1,35)),
1292            1,wx.ALL|wx.EXPAND|WACV,1)
1293        if filterBox:
1294            self.timer = wx.Timer()
1295            self.timer.Bind(wx.EVT_TIMER,self.Filter)
1296            topSizer.Add(wx.StaticText(self,wx.ID_ANY,'Name \nFilter: '),0,wx.ALL|WACV,1)
1297            self.filterBox = wx.TextCtrl(self, wx.ID_ANY, size=(80,-1),style=wx.TE_PROCESS_ENTER)
1298            self.filterBox.Bind(wx.EVT_TEXT,self.onChar)
1299            self.filterBox.Bind(wx.EVT_TEXT_ENTER,self.Filter)
1300            topSizer.Add(self.filterBox,0,wx.ALL|WACV,0)
1301        Sizer.Add(topSizer,0,wx.ALL|wx.EXPAND,8)
1302        self.settingRange = False
1303        self.rangeFirst = None
1304        self.clb = wx.CheckListBox(self, wx.ID_ANY, (30,30), wx.DefaultSize, ChoiceList)
1305        self.clb.Bind(wx.EVT_CHECKLISTBOX,self.OnCheck)
1306        if monoFont:
1307            font1 = wx.Font(self.clb.GetFont().GetPointSize(),
1308                            wx.MODERN, wx.NORMAL, wx.NORMAL, False)
1309            self.clb.SetFont(font1)
1310        Sizer.Add(self.clb,1,wx.LEFT|wx.RIGHT|wx.EXPAND,10)
1311        Sizer.Add((-1,10))
1312        # set/toggle buttons
1313        if toggle:
1314            tSizer = wx.FlexGridSizer(cols=2,hgap=5,vgap=5)
1315            setBut = wx.Button(self,wx.ID_ANY,'Set All')
1316            setBut.Bind(wx.EVT_BUTTON,self._SetAll)
1317            tSizer.Add(setBut)
1318            togBut = wx.Button(self,wx.ID_ANY,'Toggle All')
1319            togBut.Bind(wx.EVT_BUTTON,self._ToggleAll)
1320            tSizer.Add(togBut)
1321            self.rangeBut = wx.ToggleButton(self,wx.ID_ANY,'Set Range')
1322            self.rangeBut.Bind(wx.EVT_TOGGLEBUTTON,self.SetRange)
1323            tSizer.Add(self.rangeBut)           
1324            self.rangeCapt = wx.StaticText(self,wx.ID_ANY,'')
1325            tSizer.Add(self.rangeCapt)
1326            Sizer.Add(tSizer,0,wx.LEFT,12)
1327        # OK/Cancel buttons
1328        btnsizer = wx.StdDialogButtonSizer()
1329        if useOK:
1330            self.OKbtn = wx.Button(self, wx.ID_OK)
1331            self.OKbtn.SetDefault()
1332            btnsizer.AddButton(self.OKbtn)
1333        if useCANCEL:
1334            btn = wx.Button(self, wx.ID_CANCEL)
1335            btnsizer.AddButton(btn)
1336        btnsizer.Realize()
1337        Sizer.Add((-1,5))
1338        Sizer.Add(btnsizer,0,wx.ALIGN_RIGHT,50)
1339        Sizer.Add((-1,20))
1340        # OK done, let's get outa here
1341        self.SetSizer(Sizer)
1342        self.CenterOnParent()
1343
1344    def SetRange(self,event):
1345        '''Respond to a press of the Set Range button. Set the range flag and
1346        the caption next to the button
1347        '''
1348        self.settingRange = self.rangeBut.GetValue()
1349        if self.settingRange:
1350            self.rangeCapt.SetLabel('Select range start')
1351        else:
1352            self.rangeCapt.SetLabel('')           
1353        self.rangeFirst = None
1354       
1355    def GetSelections(self):
1356        'Returns a list of the indices for the selected choices'
1357        # update self.Selections with settings for displayed items
1358        for i in range(len(self.filterlist)):
1359            self.Selections[self.filterlist[i]] = self.clb.IsChecked(i)
1360        # return all selections, shown or hidden
1361        return [i for i in range(len(self.Selections)) if self.Selections[i]]
1362       
1363    def SetSelections(self,selList):
1364        '''Sets the selection indices in selList as selected. Resets any previous
1365        selections for compatibility with wx.MultiChoiceDialog. Note that
1366        the state for only the filtered items is shown.
1367
1368        :param list selList: indices of items to be selected. These indices
1369          are referenced to the order in self.ChoiceList
1370        '''
1371        self.Selections = len(self.ChoiceList) * [False,] # reset selections
1372        for sel in selList:
1373            self.Selections[sel] = True
1374        self._ShowSelections()
1375
1376    def _ShowSelections(self):
1377        'Show the selection state for displayed items'
1378        self.clb.SetChecked(
1379            [i for i in range(len(self.filterlist)) if self.Selections[self.filterlist[i]]]
1380            ) # Note anything previously checked will be cleared.
1381           
1382    def _SetAll(self,event):
1383        'Set all viewed choices on'
1384        self.clb.SetChecked(range(len(self.filterlist)))
1385       
1386    def _ToggleAll(self,event):
1387        'flip the state of all viewed choices'
1388        for i in range(len(self.filterlist)):
1389            self.clb.Check(i,not self.clb.IsChecked(i))
1390           
1391    def onChar(self,event):
1392        'Respond to keyboard events in the Filter box'
1393        self.OKbtn.Enable(False)
1394        if self.timer.IsRunning():
1395            self.timer.Stop()
1396        self.timer.Start(1000,oneShot=True)
1397        event.Skip()
1398       
1399    def OnCheck(self,event):
1400        '''for CheckListBox events; if Set Range is in use, this sets/clears all
1401        entries in range between start and end according to the value in start.
1402        Repeated clicks on the start change the checkbox state, but do not trigger
1403        the range copy.
1404        The caption next to the button is updated on the first button press.
1405        '''
1406        if self.settingRange:
1407            id = event.GetInt()
1408            if self.rangeFirst is None:
1409                name = self.clb.GetString(id)
1410                self.rangeCapt.SetLabel(name+' to...')
1411                self.rangeFirst = id
1412            elif self.rangeFirst == id:
1413                pass
1414            else:
1415                for i in range(min(self.rangeFirst,id), max(self.rangeFirst,id)+1):
1416                    self.clb.Check(i,self.clb.IsChecked(self.rangeFirst))
1417                self.rangeBut.SetValue(False)
1418                self.rangeCapt.SetLabel('')
1419            return
1420       
1421    def Filter(self,event):
1422        '''Read text from filter control and select entries that match. Called by
1423        Timer after a delay with no input or if Enter is pressed.
1424        '''
1425        if self.timer.IsRunning():
1426            self.timer.Stop()
1427        self.GetSelections() # record current selections
1428        txt = self.filterBox.GetValue()
1429        self.clb.Clear()
1430       
1431        self.Update()
1432        self.filterlist = []
1433        if txt:
1434            txt = txt.lower()
1435            ChoiceList = []
1436            for i,item in enumerate(self.ChoiceList):
1437                if item.lower().find(txt) != -1:
1438                    ChoiceList.append(item)
1439                    self.filterlist.append(i)
1440        else:
1441            self.filterlist = range(len(self.ChoiceList))
1442            ChoiceList = self.ChoiceList
1443        self.clb.AppendItems(ChoiceList)
1444        self._ShowSelections()
1445        self.OKbtn.Enable(True)
1446
1447def SelectEdit1Var(G2frame,array,labelLst,elemKeysLst,dspLst,refFlgElem):
1448    '''Select a variable from a list, then edit it and select histograms
1449    to copy it to.
1450
1451    :param wx.Frame G2frame: main GSAS-II frame
1452    :param dict array: the array (dict or list) where values to be edited are kept
1453    :param list labelLst: labels for each data item
1454    :param list elemKeysLst: a list of lists of keys needed to be applied (see below)
1455      to obtain the value of each parameter
1456    :param list dspLst: list list of digits to be displayed (10,4) is 10 digits
1457      with 4 decimal places. Can be None.
1458    :param list refFlgElem: a list of lists of keys needed to be applied (see below)
1459      to obtain the refine flag for each parameter or None if the parameter
1460      does not have refine flag.
1461
1462    Example::
1463      array = data
1464      labelLst = ['v1','v2']
1465      elemKeysLst = [['v1'], ['v2',0]]
1466      refFlgElem = [None, ['v2',1]]
1467
1468     * The value for v1 will be in data['v1'] and this cannot be refined while,
1469     * The value for v2 will be in data['v2'][0] and its refinement flag is data['v2'][1]
1470    '''
1471    def unkey(dct,keylist):
1472        '''dive into a nested set of dicts/lists applying keys in keylist
1473        consecutively
1474        '''
1475        d = dct
1476        for k in keylist:
1477            d = d[k]
1478        return d
1479
1480    def OnChoice(event):
1481        'Respond when a parameter is selected in the Choice box'
1482        valSizer.DeleteWindows()
1483        lbl = event.GetString()
1484        copyopts['currentsel'] = lbl
1485        i = labelLst.index(lbl)
1486        OKbtn.Enable(True)
1487        ch.SetLabel(lbl)
1488        args = {}
1489        if dspLst[i]:
1490            args = {'nDig':dspLst[i]}
1491        Val = ValidatedTxtCtrl(
1492            dlg,
1493            unkey(array,elemKeysLst[i][:-1]),
1494            elemKeysLst[i][-1],
1495            **args)
1496        copyopts['startvalue'] = unkey(array,elemKeysLst[i])
1497        #unkey(array,elemKeysLst[i][:-1])[elemKeysLst[i][-1]] =
1498        valSizer.Add(Val,0,wx.LEFT,5)
1499        dlg.SendSizeEvent()
1500       
1501    # SelectEdit1Var execution begins here
1502    saveArray = copy.deepcopy(array) # keep original values
1503    TreeItemType = G2frame.PatternTree.GetItemText(G2frame.PickId)
1504    copyopts = {'InTable':False,"startvalue":None,'currentsel':None}       
1505    hst = G2frame.PatternTree.GetItemText(G2frame.PatternId)
1506    histList = G2pdG.GetHistsLikeSelected(G2frame)
1507    if not histList:
1508        G2frame.ErrorDialog('No match','No histograms match '+hst,G2frame.dataFrame)
1509        return
1510    dlg = wx.Dialog(G2frame.dataDisplay,wx.ID_ANY,'Set a parameter value',
1511        style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)
1512    mainSizer = wx.BoxSizer(wx.VERTICAL)
1513    mainSizer.Add((5,5))
1514    subSizer = wx.BoxSizer(wx.HORIZONTAL)
1515    subSizer.Add((-1,-1),1,wx.EXPAND)
1516    subSizer.Add(wx.StaticText(dlg,wx.ID_ANY,'Select a parameter and set a new value'))
1517    subSizer.Add((-1,-1),1,wx.EXPAND)
1518    mainSizer.Add(subSizer,0,wx.EXPAND,0)
1519    mainSizer.Add((0,10))
1520
1521    subSizer = wx.FlexGridSizer(0,2,5,0)
1522    subSizer.Add(wx.StaticText(dlg,wx.ID_ANY,'Parameter: '))
1523    ch = wx.Choice(dlg, wx.ID_ANY, choices = sorted(labelLst))
1524    ch.SetSelection(-1)
1525    ch.Bind(wx.EVT_CHOICE, OnChoice)
1526    subSizer.Add(ch)
1527    subSizer.Add(wx.StaticText(dlg,wx.ID_ANY,'Value: '))
1528    valSizer = wx.BoxSizer(wx.HORIZONTAL)
1529    subSizer.Add(valSizer)
1530    mainSizer.Add(subSizer)
1531
1532    mainSizer.Add((-1,20))
1533    subSizer = wx.BoxSizer(wx.HORIZONTAL)
1534    subSizer.Add(G2CheckBox(dlg, 'Edit in table ', copyopts, 'InTable'))
1535    mainSizer.Add(subSizer)
1536
1537    btnsizer = wx.StdDialogButtonSizer()
1538    OKbtn = wx.Button(dlg, wx.ID_OK,'Continue')
1539    OKbtn.Enable(False)
1540    OKbtn.SetDefault()
1541    OKbtn.Bind(wx.EVT_BUTTON,lambda event: dlg.EndModal(wx.ID_OK))
1542    btnsizer.AddButton(OKbtn)
1543    btn = wx.Button(dlg, wx.ID_CANCEL)
1544    btnsizer.AddButton(btn)
1545    btnsizer.Realize()
1546    mainSizer.Add((-1,5),1,wx.EXPAND,1)
1547    mainSizer.Add(btnsizer,0,wx.ALIGN_CENTER,0)
1548    mainSizer.Add((-1,10))
1549
1550    dlg.SetSizer(mainSizer)
1551    dlg.CenterOnParent()
1552    if dlg.ShowModal() != wx.ID_OK:
1553        array.update(saveArray)
1554        dlg.Destroy()
1555        return
1556    dlg.Destroy()
1557
1558    copyList = []
1559    lbl = copyopts['currentsel']
1560    dlg = G2MultiChoiceDialog(G2frame.dataFrame,'Copy parameter '+lbl+' from\n'+hst,
1561        'Copy parameters', histList)
1562    dlg.CenterOnParent()
1563    try:
1564        if dlg.ShowModal() == wx.ID_OK:
1565            for i in dlg.GetSelections(): 
1566                copyList.append(histList[i])
1567        else:
1568            # reset the parameter since cancel was pressed
1569            array.update(saveArray)
1570            return
1571    finally:
1572        dlg.Destroy()
1573
1574    prelbl = [hst]
1575    i = labelLst.index(lbl)
1576    keyLst = elemKeysLst[i]
1577    refkeys = refFlgElem[i]
1578    dictlst = [unkey(array,keyLst[:-1])]
1579    if refkeys is not None:
1580        refdictlst = [unkey(array,refkeys[:-1])]
1581    else:
1582        refdictlst = None
1583    Id = GetPatternTreeItemId(G2frame,G2frame.root,hst)
1584    hstData = G2frame.PatternTree.GetItemPyData(GetPatternTreeItemId(G2frame,Id,'Instrument Parameters'))[0]
1585    for h in copyList:
1586        Id = GetPatternTreeItemId(G2frame,G2frame.root,h)
1587        instData = G2frame.PatternTree.GetItemPyData(GetPatternTreeItemId(G2frame,Id,'Instrument Parameters'))[0]
1588        if len(hstData) != len(instData) or hstData['Type'][0] != instData['Type'][0]:  #don't mix data types or lam & lam1/lam2 parms!
1589            print h+' not copied - instrument parameters not commensurate'
1590            continue
1591        hData = G2frame.PatternTree.GetItemPyData(GetPatternTreeItemId(G2frame,Id,TreeItemType))
1592        if TreeItemType == 'Instrument Parameters':
1593            hData = hData[0]
1594        #copy the value if it is changed or we will not edit in a table
1595        valNow = unkey(array,keyLst)
1596        if copyopts['startvalue'] != valNow or not copyopts['InTable']:
1597            unkey(hData,keyLst[:-1])[keyLst[-1]] = valNow
1598        prelbl += [h]
1599        dictlst += [unkey(hData,keyLst[:-1])]
1600        if refdictlst is not None:
1601            refdictlst += [unkey(hData,refkeys[:-1])]
1602    if refdictlst is None:
1603        args = {}
1604    else:
1605        args = {'checkdictlst':refdictlst,
1606                'checkelemlst':len(dictlst)*[refkeys[-1]],
1607                'checklabel':'Refine?'}
1608    if copyopts['InTable']:
1609        dlg = ScrolledMultiEditor(
1610            G2frame.dataDisplay,dictlst,
1611            len(dictlst)*[keyLst[-1]],prelbl,
1612            header='Editing parameter '+lbl,
1613            CopyButton=True,**args)
1614        dlg.CenterOnParent()
1615        if dlg.ShowModal() != wx.ID_OK:
1616            array.update(saveArray)
1617        dlg.Destroy()
1618
1619################################################################        Single choice Dialog with filter options
1620class G2SingleChoiceDialog(wx.Dialog):
1621    '''A dialog similar to wx.SingleChoiceDialog except that a filter can be
1622    added.
1623
1624    :param wx.Frame ParentFrame: reference to parent frame
1625    :param str title: heading above list of choices
1626    :param str header: Title to place on window frame
1627    :param list ChoiceList: a list of choices where one will be selected
1628    :param bool monoFont: If False (default), use a variable-spaced font;
1629      if True use a equally-spaced font.
1630    :param bool filterBox: If True (default) an input widget is placed on
1631      the window and only entries matching the entered text are shown.
1632    :param kw: optional keyword parameters for the wx.Dialog may
1633      be included such as size [which defaults to `(320,310)`] and
1634      style (which defaults to ``wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER | wx.CENTRE | wx.OK | wx.CANCEL``);
1635      note that ``wx.OK`` and ``wx.CANCEL`` controls
1636      the presence of the eponymous buttons in the dialog.
1637    :returns: the name of the created dialog
1638    '''
1639    def __init__(self,parent, title, header, ChoiceList, 
1640                 monoFont=False, filterBox=True, **kw):
1641        # process keyword parameters, notably style
1642        options = {'size':(320,310), # default Frame keywords
1643                   'style':wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER|wx.CENTRE| wx.OK | wx.CANCEL,
1644                   }
1645        options.update(kw)
1646        self.ChoiceList = ChoiceList
1647        self.filterlist = range(len(self.ChoiceList))
1648        if options['style'] & wx.OK:
1649            useOK = True
1650            options['style'] ^= wx.OK
1651        else:
1652            useOK = False
1653        if options['style'] & wx.CANCEL:
1654            useCANCEL = True
1655            options['style'] ^= wx.CANCEL
1656        else:
1657            useCANCEL = False       
1658        # create the dialog frame
1659        wx.Dialog.__init__(self,parent,wx.ID_ANY,header,**options)
1660        # fill the dialog
1661        Sizer = wx.BoxSizer(wx.VERTICAL)
1662        topSizer = wx.BoxSizer(wx.HORIZONTAL)
1663        topSizer.Add(
1664            wx.StaticText(self,wx.ID_ANY,title,size=(-1,35)),
1665            1,wx.ALL|wx.EXPAND|WACV,1)
1666        if filterBox:
1667            self.timer = wx.Timer()
1668            self.timer.Bind(wx.EVT_TIMER,self.Filter)
1669            topSizer.Add(wx.StaticText(self,wx.ID_ANY,'Filter: '),0,wx.ALL,1)
1670            self.filterBox = wx.TextCtrl(self, wx.ID_ANY, size=(80,-1),
1671                                         style=wx.TE_PROCESS_ENTER)
1672            self.filterBox.Bind(wx.EVT_CHAR,self.onChar)
1673            self.filterBox.Bind(wx.EVT_TEXT_ENTER,self.Filter)
1674        topSizer.Add(self.filterBox,0,wx.ALL,0)
1675        Sizer.Add(topSizer,0,wx.ALL|wx.EXPAND,8)
1676        self.clb = wx.ListBox(self, wx.ID_ANY, (30,30), wx.DefaultSize, ChoiceList)
1677        self.clb.Bind(wx.EVT_LEFT_DCLICK,self.onDoubleClick)
1678        if monoFont:
1679            font1 = wx.Font(self.clb.GetFont().GetPointSize(),
1680                            wx.MODERN, wx.NORMAL, wx.NORMAL, False)
1681            self.clb.SetFont(font1)
1682        Sizer.Add(self.clb,1,wx.LEFT|wx.RIGHT|wx.EXPAND,10)
1683        Sizer.Add((-1,10))
1684        # OK/Cancel buttons
1685        btnsizer = wx.StdDialogButtonSizer()
1686        if useOK:
1687            self.OKbtn = wx.Button(self, wx.ID_OK)
1688            self.OKbtn.SetDefault()
1689            btnsizer.AddButton(self.OKbtn)
1690        if useCANCEL:
1691            btn = wx.Button(self, wx.ID_CANCEL)
1692            btnsizer.AddButton(btn)
1693        btnsizer.Realize()
1694        Sizer.Add((-1,5))
1695        Sizer.Add(btnsizer,0,wx.ALIGN_RIGHT,50)
1696        Sizer.Add((-1,20))
1697        # OK done, let's get outa here
1698        self.SetSizer(Sizer)
1699    def GetSelection(self):
1700        'Returns the index of the selected choice'
1701        i = self.clb.GetSelection()
1702        if i < 0 or i >= len(self.filterlist):
1703            return wx.NOT_FOUND
1704        return self.filterlist[i]
1705    def onChar(self,event):
1706        self.OKbtn.Enable(False)
1707        if self.timer.IsRunning():
1708            self.timer.Stop()
1709        self.timer.Start(1000,oneShot=True)
1710        event.Skip()
1711    def Filter(self,event):
1712        if self.timer.IsRunning():
1713            self.timer.Stop()
1714        txt = self.filterBox.GetValue()
1715        self.clb.Clear()
1716        self.Update()
1717        self.filterlist = []
1718        if txt:
1719            txt = txt.lower()
1720            ChoiceList = []
1721            for i,item in enumerate(self.ChoiceList):
1722                if item.lower().find(txt) != -1:
1723                    ChoiceList.append(item)
1724                    self.filterlist.append(i)
1725        else:
1726            self.filterlist = range(len(self.ChoiceList))
1727            ChoiceList = self.ChoiceList
1728        self.clb.AppendItems(ChoiceList)
1729        self.OKbtn.Enable(True)
1730    def onDoubleClick(self,event):
1731        self.EndModal(wx.ID_OK)
1732       
1733################################################################################
1734class FlagSetDialog(wx.Dialog):
1735    ''' Creates popup with table of variables to be checked for e.g. refinement flags
1736    '''
1737    def __init__(self,parent,title,colnames,rownames,flags):
1738        wx.Dialog.__init__(self,parent,-1,title,
1739            pos=wx.DefaultPosition,style=wx.DEFAULT_DIALOG_STYLE)
1740        self.panel = wx.Panel(self)         #just a dummy - gets destroyed in Draw!
1741        self.colnames = colnames
1742        self.rownames = rownames
1743        self.flags = flags
1744        self.newflags = copy.copy(flags)
1745        self.Draw()
1746       
1747    def Draw(self):
1748        Indx = {}
1749       
1750        def OnSelection(event):
1751            Obj = event.GetEventObject()
1752            [name,ia] = Indx[Obj.GetId()]
1753            self.newflags[name][ia] = Obj.GetValue()
1754           
1755        self.panel.DestroyChildren()
1756        self.panel.Destroy()
1757        self.panel = wx.Panel(self)
1758        mainSizer = wx.BoxSizer(wx.VERTICAL)
1759        flagSizer = wx.FlexGridSizer(0,len(self.colnames),5,5)
1760        for item in self.colnames:
1761            flagSizer.Add(wx.StaticText(self.panel,label=item),0,WACV)
1762        for ia,atm in enumerate(self.rownames):
1763            flagSizer.Add(wx.StaticText(self.panel,label=atm),0,WACV)
1764            for name in self.colnames[1:]:
1765                if self.flags[name][ia]:
1766                    self.newflags[name][ia] = False     #default is off
1767                    flg = wx.CheckBox(self.panel,-1,label='')
1768                    flg.Bind(wx.EVT_CHECKBOX,OnSelection)
1769                    Indx[flg.GetId()] = [name,ia]
1770                    flagSizer.Add(flg,0,WACV)
1771                else:
1772                    flagSizer.Add(wx.StaticText(self.panel,label='na'),0,WACV)
1773           
1774        mainSizer.Add(flagSizer,0)
1775        OkBtn = wx.Button(self.panel,-1,"Ok")
1776        OkBtn.Bind(wx.EVT_BUTTON, self.OnOk)
1777        CancelBtn = wx.Button(self.panel,-1,'Cancel')
1778        CancelBtn.Bind(wx.EVT_BUTTON, self.OnCancel)
1779        btnSizer = wx.BoxSizer(wx.HORIZONTAL)
1780        btnSizer.Add((20,20),1)
1781        btnSizer.Add(OkBtn)
1782        btnSizer.Add(CancelBtn)
1783        btnSizer.Add((20,20),1)
1784        mainSizer.Add(btnSizer,0,wx.EXPAND|wx.BOTTOM|wx.TOP, 10)
1785        self.panel.SetSizer(mainSizer)
1786        self.panel.Fit()
1787        self.Fit()
1788       
1789    def GetSelection(self):
1790        return self.newflags
1791
1792    def OnOk(self,event):
1793        parent = self.GetParent()
1794        parent.Raise()
1795        self.EndModal(wx.ID_OK)             
1796       
1797    def OnCancel(self,event):
1798        parent = self.GetParent()
1799        parent.Raise()
1800        self.EndModal(wx.ID_CANCEL)
1801
1802###################################################################,#############
1803def G2MessageBox(parent,msg,title='Error'):
1804    '''Simple code to display a error or warning message
1805    '''
1806    dlg = wx.MessageDialog(parent,StripIndents(msg), title, wx.OK)
1807    dlg.ShowModal()
1808    dlg.Destroy()
1809   
1810################################################################################
1811class PickTwoDialog(wx.Dialog):
1812    '''This does not seem to be in use
1813    '''
1814    def __init__(self,parent,title,prompt,names,choices):
1815        wx.Dialog.__init__(self,parent,-1,title, 
1816            pos=wx.DefaultPosition,style=wx.DEFAULT_DIALOG_STYLE)
1817        self.panel = wx.Panel(self)         #just a dummy - gets destroyed in Draw!
1818        self.prompt = prompt
1819        self.choices = choices
1820        self.names = names
1821        self.Draw()
1822
1823    def Draw(self):
1824        Indx = {}
1825       
1826        def OnSelection(event):
1827            Obj = event.GetEventObject()
1828            id = Indx[Obj.GetId()]
1829            self.choices[id] = Obj.GetValue().encode()  #to avoid Unicode versions
1830            self.Draw()
1831           
1832        self.panel.DestroyChildren()
1833        self.panel.Destroy()
1834        self.panel = wx.Panel(self)
1835        mainSizer = wx.BoxSizer(wx.VERTICAL)
1836        mainSizer.Add(wx.StaticText(self.panel,-1,self.prompt),0,wx.ALIGN_CENTER)
1837        for isel,name in enumerate(self.choices):
1838            lineSizer = wx.BoxSizer(wx.HORIZONTAL)
1839            lineSizer.Add(wx.StaticText(self.panel,-1,'Reference atom '+str(isel+1)),0,wx.ALIGN_CENTER)
1840            nameList = self.names[:]
1841            if isel:
1842                if self.choices[0] in nameList:
1843                    nameList.remove(self.choices[0])
1844            choice = wx.ComboBox(self.panel,-1,value=name,choices=nameList,
1845                style=wx.CB_READONLY|wx.CB_DROPDOWN)
1846            Indx[choice.GetId()] = isel
1847            choice.Bind(wx.EVT_COMBOBOX, OnSelection)
1848            lineSizer.Add(choice,0,WACV)
1849            mainSizer.Add(lineSizer)
1850        OkBtn = wx.Button(self.panel,-1,"Ok")
1851        OkBtn.Bind(wx.EVT_BUTTON, self.OnOk)
1852        CancelBtn = wx.Button(self.panel,-1,'Cancel')
1853        CancelBtn.Bind(wx.EVT_BUTTON, self.OnCancel)
1854        btnSizer = wx.BoxSizer(wx.HORIZONTAL)
1855        btnSizer.Add((20,20),1)
1856        btnSizer.Add(OkBtn)
1857        btnSizer.Add(CancelBtn)
1858        btnSizer.Add((20,20),1)
1859        mainSizer.Add(btnSizer,0,wx.EXPAND|wx.BOTTOM|wx.TOP, 10)
1860        self.panel.SetSizer(mainSizer)
1861        self.panel.Fit()
1862        self.Fit()
1863       
1864    def GetSelection(self):
1865        return self.choices
1866
1867    def OnOk(self,event):
1868        parent = self.GetParent()
1869        parent.Raise()
1870        self.EndModal(wx.ID_OK)             
1871       
1872    def OnCancel(self,event):
1873        parent = self.GetParent()
1874        parent.Raise()
1875        self.EndModal(wx.ID_CANCEL)
1876
1877################################################################################
1878class SingleFloatDialog(wx.Dialog):
1879    'Dialog to obtain a single float value from user'
1880    def __init__(self,parent,title,prompt,value,limits=[0.,1.],format='%.5g'):
1881        wx.Dialog.__init__(self,parent,-1,title, 
1882            pos=wx.DefaultPosition,style=wx.DEFAULT_DIALOG_STYLE)
1883        self.panel = wx.Panel(self)         #just a dummy - gets destroyed in Draw!
1884        self.limits = limits
1885        self.value = value
1886        self.prompt = prompt
1887        self.format = format
1888        self.Draw()
1889       
1890    def Draw(self):
1891       
1892        def OnValItem(event):
1893            try:
1894                val = float(valItem.GetValue())
1895                if val < self.limits[0] or val > self.limits[1]:
1896                    raise ValueError
1897            except ValueError:
1898                val = self.value
1899            self.value = val
1900            valItem.SetValue(self.format%(self.value))
1901           
1902        self.panel.Destroy()
1903        self.panel = wx.Panel(self)
1904        mainSizer = wx.BoxSizer(wx.VERTICAL)
1905        mainSizer.Add(wx.StaticText(self.panel,-1,self.prompt),0,wx.ALIGN_CENTER)
1906        valItem = wx.TextCtrl(self.panel,-1,value=self.format%(self.value),style=wx.TE_PROCESS_ENTER)
1907        mainSizer.Add(valItem,0,wx.ALIGN_CENTER)
1908        valItem.Bind(wx.EVT_TEXT_ENTER,OnValItem)
1909        valItem.Bind(wx.EVT_KILL_FOCUS,OnValItem)
1910        OkBtn = wx.Button(self.panel,-1,"Ok")
1911        OkBtn.Bind(wx.EVT_BUTTON, self.OnOk)
1912        CancelBtn = wx.Button(self.panel,-1,'Cancel')
1913        CancelBtn.Bind(wx.EVT_BUTTON, self.OnCancel)
1914        btnSizer = wx.BoxSizer(wx.HORIZONTAL)
1915        btnSizer.Add((20,20),1)
1916        btnSizer.Add(OkBtn)
1917        btnSizer.Add(CancelBtn)
1918        btnSizer.Add((20,20),1)
1919        mainSizer.Add(btnSizer,0,wx.EXPAND|wx.BOTTOM|wx.TOP, 10)
1920        self.panel.SetSizer(mainSizer)
1921        self.panel.Fit()
1922        self.Fit()
1923
1924    def GetValue(self):
1925        return self.value
1926       
1927    def OnOk(self,event):
1928        parent = self.GetParent()
1929        parent.Raise()
1930        self.EndModal(wx.ID_OK)             
1931       
1932    def OnCancel(self,event):
1933        parent = self.GetParent()
1934        parent.Raise()
1935        self.EndModal(wx.ID_CANCEL)
1936
1937################################################################################
1938class SingleStringDialog(wx.Dialog):
1939    '''Dialog to obtain a single string value from user
1940   
1941    :param wx.Frame parent: name of parent frame
1942    :param str title: title string for dialog
1943    :param str prompt: string to tell use what they are inputting
1944    :param str value: default input value, if any
1945    '''
1946    def __init__(self,parent,title,prompt,value='',size=(200,-1)):
1947        wx.Dialog.__init__(self,parent,wx.ID_ANY,title, 
1948                           pos=wx.DefaultPosition,
1949                           style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)
1950        self.value = value
1951        self.prompt = prompt
1952        self.CenterOnParent()
1953        self.panel = wx.Panel(self)
1954        mainSizer = wx.BoxSizer(wx.VERTICAL)
1955        mainSizer.Add(wx.StaticText(self.panel,-1,self.prompt),0,wx.ALIGN_CENTER)
1956        self.valItem = wx.TextCtrl(self.panel,-1,value=self.value,size=size)
1957        mainSizer.Add(self.valItem,0,wx.ALIGN_CENTER)
1958        btnsizer = wx.StdDialogButtonSizer()
1959        OKbtn = wx.Button(self.panel, wx.ID_OK)
1960        OKbtn.SetDefault()
1961        btnsizer.AddButton(OKbtn)
1962        btn = wx.Button(self.panel, wx.ID_CANCEL)
1963        btnsizer.AddButton(btn)
1964        btnsizer.Realize()
1965        mainSizer.Add(btnsizer,0,wx.ALIGN_CENTER)
1966        self.panel.SetSizer(mainSizer)
1967        self.panel.Fit()
1968        self.Fit()
1969
1970    def Show(self):
1971        '''Use this method after creating the dialog to post it
1972        :returns: True if the user pressed OK; False if the User pressed Cancel
1973        '''
1974        if self.ShowModal() == wx.ID_OK:
1975            self.value = self.valItem.GetValue()
1976            return True
1977        else:
1978            return False
1979
1980    def GetValue(self):
1981        '''Use this method to get the value entered by the user
1982        :returns: string entered by user
1983        '''
1984        return self.value
1985
1986################################################################################
1987class MultiStringDialog(wx.Dialog):
1988    '''Dialog to obtain a multi string values from user
1989   
1990    :param wx.Frame parent: name of parent frame
1991    :param str title: title string for dialog
1992    :param str prompts: strings to tell use what they are inputting
1993    :param str values: default input values, if any
1994    '''
1995    def __init__(self,parent,title,prompts,values=[]):      #,size=(200,-1)?
1996       
1997        wx.Dialog.__init__(self,parent,wx.ID_ANY,title, 
1998                           pos=wx.DefaultPosition,
1999                           style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)
2000        self.values = values
2001        self.prompts = prompts
2002        self.CenterOnParent()
2003        self.panel = wx.Panel(self)
2004        mainSizer = wx.BoxSizer(wx.VERTICAL)
2005        promptSizer = wx.FlexGridSizer(0,2,5,5)
2006        self.Indx = {}
2007        for prompt,value in zip(prompts,values):
2008            promptSizer.Add(wx.StaticText(self.panel,-1,prompt),0,WACV)
2009            valItem = wx.TextCtrl(self.panel,-1,value=value,style=wx.TE_PROCESS_ENTER)
2010            self.Indx[valItem.GetId()] = prompt
2011            valItem.Bind(wx.EVT_TEXT,self.newValue)
2012            promptSizer.Add(valItem,0,WACV)
2013        mainSizer.Add(promptSizer,0)
2014        btnsizer = wx.StdDialogButtonSizer()
2015        OKbtn = wx.Button(self.panel, wx.ID_OK)
2016        OKbtn.SetDefault()
2017        btnsizer.AddButton(OKbtn)
2018        btn = wx.Button(self.panel, wx.ID_CANCEL)
2019        btnsizer.AddButton(btn)
2020        btnsizer.Realize()
2021        mainSizer.Add(btnsizer,0,wx.ALIGN_CENTER)
2022        self.panel.SetSizer(mainSizer)
2023        self.panel.Fit()
2024        self.Fit()
2025       
2026    def newValue(self,event):
2027        Obj = event.GetEventObject()
2028        item = self.Indx[Obj.GetId()]
2029        id = self.prompts.index(item)
2030        self.values[id] = Obj.GetValue()
2031
2032    def Show(self):
2033        '''Use this method after creating the dialog to post it
2034        :returns: True if the user pressed OK; False if the User pressed Cancel
2035        '''
2036        if self.ShowModal() == wx.ID_OK:
2037            return True
2038        else:
2039            return False
2040
2041    def GetValues(self):
2042        '''Use this method to get the value entered by the user
2043        :returns: string entered by user
2044        '''
2045        return self.values
2046
2047################################################################################
2048class G2ColumnIDDialog(wx.Dialog):
2049    '''A dialog for matching column data to desired items; some columns may be ignored.
2050   
2051    :param wx.Frame ParentFrame: reference to parent frame
2052    :param str title: heading above list of choices
2053    :param str header: Title to place on window frame
2054    :param list ChoiceList: a list of possible choices for the columns
2055    :param list ColumnData: lists of column data to be matched with ChoiceList
2056    :param bool monoFont: If False (default), use a variable-spaced font;
2057      if True use a equally-spaced font.
2058    :param kw: optional keyword parameters for the wx.Dialog may
2059      be included such as size [which defaults to `(320,310)`] and
2060      style (which defaults to ``wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER | wx.CENTRE | wx.OK | wx.CANCEL``);
2061      note that ``wx.OK`` and ``wx.CANCEL`` controls
2062      the presence of the eponymous buttons in the dialog.
2063    :returns: the name of the created dialog
2064   
2065    '''
2066
2067    def __init__(self,parent, title, header,Comments,ChoiceList, ColumnData,
2068                 monoFont=False, **kw):
2069
2070        def OnOk(sevent):
2071            OK = True
2072            selCols = []
2073            for col in self.sel:
2074                item = col.GetValue()
2075                if item != ' ' and item in selCols:
2076                    OK = False
2077                    break
2078                else:
2079                    selCols.append(item)
2080            parent = self.GetParent()
2081            if not OK:
2082                parent.ErrorDialog('Duplicate',item+' selected more than once')
2083                return
2084            parent.Raise()
2085            self.EndModal(wx.ID_OK)
2086           
2087        def OnModify(event):
2088            Obj = event.GetEventObject()
2089            icol,colData = Indx[Obj.GetId()]
2090            modify = Obj.GetValue()
2091            if not modify:
2092                return
2093            print 'Modify column',icol,' by', modify
2094            for i,item in enumerate(self.ColumnData[icol]):
2095                self.ColumnData[icol][i] = str(eval(item+modify))
2096            colData.SetValue('\n'.join(self.ColumnData[icol]))
2097            Obj.SetValue('')
2098           
2099        # process keyword parameters, notably style
2100        options = {'size':(600,310), # default Frame keywords
2101                   'style':wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER|wx.CENTRE| wx.OK | wx.CANCEL,
2102                   }
2103        options.update(kw)
2104        self.Comments = ''.join(Comments)
2105        self.ChoiceList = ChoiceList
2106        self.ColumnData = ColumnData
2107        nCol = len(ColumnData)
2108        if options['style'] & wx.OK:
2109            useOK = True
2110            options['style'] ^= wx.OK
2111        else:
2112            useOK = False
2113        if options['style'] & wx.CANCEL:
2114            useCANCEL = True
2115            options['style'] ^= wx.CANCEL
2116        else:
2117            useCANCEL = False       
2118        # create the dialog frame
2119        wx.Dialog.__init__(self,parent,wx.ID_ANY,header,**options)
2120        panel = wxscroll.ScrolledPanel(self)
2121        # fill the dialog
2122        Sizer = wx.BoxSizer(wx.VERTICAL)
2123        Sizer.Add((-1,5))
2124        Sizer.Add(wx.StaticText(panel,label=title),0,WACV)
2125        if self.Comments:
2126            Sizer.Add(wx.StaticText(panel,label=' Header lines:'),0,WACV)
2127            Sizer.Add(wx.TextCtrl(panel,value=self.Comments,size=(200,-1),
2128                style=wx.TE_MULTILINE|wx.TE_READONLY|wx.TE_DONTWRAP),0,wx.ALL|wx.EXPAND|WACV,8)
2129        columnsSizer = wx.FlexGridSizer(0,nCol,5,10)
2130        self.sel = []
2131        self.mod = []
2132        Indx = {}
2133        for icol,col in enumerate(self.ColumnData):
2134            colSizer = wx.BoxSizer(wx.VERTICAL)
2135            colSizer.Add(wx.StaticText(panel,label=' Column #%d Select:'%(icol)),0,WACV)
2136            self.sel.append(wx.ComboBox(panel,value=' ',choices=self.ChoiceList,style=wx.CB_READONLY|wx.CB_DROPDOWN))
2137            colSizer.Add(self.sel[-1])
2138            colData = wx.TextCtrl(panel,value='\n'.join(self.ColumnData[icol]),size=(120,-1),
2139                style=wx.TE_MULTILINE|wx.TE_READONLY|wx.TE_DONTWRAP)
2140            colSizer.Add(colData,0,WACV)
2141            colSizer.Add(wx.StaticText(panel,label=' Modify by:'),0,WACV)
2142            mod = wx.TextCtrl(panel,size=(120,-1),value='',style=wx.TE_PROCESS_ENTER)
2143            mod.Bind(wx.EVT_TEXT_ENTER,OnModify)
2144            mod.Bind(wx.EVT_KILL_FOCUS,OnModify)
2145            Indx[mod.GetId()] = [icol,colData]
2146            colSizer.Add(mod,0,WACV)
2147            columnsSizer.Add(colSizer)
2148        Sizer.Add(columnsSizer)
2149        Sizer.Add(wx.StaticText(panel,label=' For modify by, enter arithmetic string eg. "-12345.67". "+","-","*","/","**" all allowed'),0,WACV) 
2150        Sizer.Add((-1,10))
2151        # OK/Cancel buttons
2152        btnsizer = wx.StdDialogButtonSizer()
2153        if useOK:
2154            self.OKbtn = wx.Button(panel, wx.ID_OK)
2155            self.OKbtn.SetDefault()
2156            btnsizer.AddButton(self.OKbtn)
2157            self.OKbtn.Bind(wx.EVT_BUTTON, OnOk)
2158        if useCANCEL:
2159            btn = wx.Button(panel, wx.ID_CANCEL)
2160            btnsizer.AddButton(btn)
2161        btnsizer.Realize()
2162        Sizer.Add((-1,5))
2163        Sizer.Add(btnsizer,0,wx.ALIGN_LEFT,20)
2164        Sizer.Add((-1,5))
2165        # OK done, let's get outa here
2166        panel.SetSizer(Sizer)
2167        panel.SetAutoLayout(1)
2168        panel.SetupScrolling()
2169        Size = [450,375]
2170        panel.SetSize(Size)
2171        Size[0] += 25; Size[1]+= 25
2172        self.SetSize(Size)
2173       
2174    def GetSelection(self):
2175        'Returns the selected sample parm for each column'
2176        selCols = []
2177        for item in self.sel:
2178            selCols.append(item.GetValue())
2179        return selCols,self.ColumnData
2180   
2181################################################################################
2182class G2HistoDataDialog(wx.Dialog):
2183    '''A dialog for editing histogram data globally.
2184   
2185    :param wx.Frame ParentFrame: reference to parent frame
2186    :param str title: heading above list of choices
2187    :param str header: Title to place on window frame
2188    :param list ParmList: a list of names for the columns
2189    :param list ParmFmt: a list of formatting strings for the columns
2190    :param list: HistoList: a list of histogram names
2191    :param list ParmData: a list of lists of data matched to ParmList; one for each item in HistoList
2192    :param bool monoFont: If False (default), use a variable-spaced font;
2193      if True use a equally-spaced font.
2194    :param kw: optional keyword parameters for the wx.Dialog may
2195      be included such as size [which defaults to `(320,310)`] and
2196      style (which defaults to
2197      ``wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER | wx.CENTRE | wx.OK | wx.CANCEL``);
2198      note that ``wx.OK`` and ``wx.CANCEL`` controls the presence of the eponymous buttons in the dialog.
2199    :returns: the modified ParmData
2200   
2201    '''
2202
2203    def __init__(self,parent, title, header,ParmList,ParmFmt,HistoList,ParmData,
2204                 monoFont=False, **kw):
2205
2206        def OnOk(sevent):
2207            parent.Raise()
2208            self.EndModal(wx.ID_OK)
2209           
2210        def OnModify(event):
2211            Obj = event.GetEventObject()
2212            irow,it = Indx[Obj.GetId()]
2213            try:
2214                val = float(Obj.GetValue())
2215            except ValueError:
2216                val = self.ParmData[irow][it]
2217            self.ParmData[irow][it] = val
2218            Obj.SetValue(self.ParmFmt[it]%val)
2219                       
2220        # process keyword parameters, notably style
2221        options = {'size':(600,310), # default Frame keywords
2222                   'style':wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER|wx.CENTRE| wx.OK | wx.CANCEL,
2223                   }
2224        options.update(kw)
2225        self.ParmList = ParmList
2226        self.ParmFmt = ParmFmt
2227        self.HistoList = HistoList
2228        self.ParmData = ParmData
2229        nCol = len(ParmList)
2230        if options['style'] & wx.OK:
2231            useOK = True
2232            options['style'] ^= wx.OK
2233        else:
2234            useOK = False
2235        if options['style'] & wx.CANCEL:
2236            useCANCEL = True
2237            options['style'] ^= wx.CANCEL
2238        else:
2239            useCANCEL = False       
2240        # create the dialog frame
2241        wx.Dialog.__init__(self,parent,wx.ID_ANY,header,**options)
2242        panel = wxscroll.ScrolledPanel(self)
2243        # fill the dialog
2244        Sizer = wx.BoxSizer(wx.VERTICAL)
2245        Sizer.Add((-1,5))
2246        Sizer.Add(wx.StaticText(panel,label=title),0,WACV)
2247        dataSizer = wx.FlexGridSizer(0,nCol+1,0,0)
2248        self.sel = []
2249        self.mod = []
2250        Indx = {}
2251        for item in ['Histogram',]+self.ParmList:
2252            dataSizer.Add(wx.StaticText(panel,-1,label=' %10s '%(item)),0,WACV)
2253        for irow,name in enumerate(self.HistoList):
2254            dataSizer.Add(wx.StaticText(panel,label=name),0,WACV|wx.LEFT|wx.RIGHT,10)
2255            for it,item in enumerate(self.ParmData[irow]):
2256                dat = wx.TextCtrl(panel,-1,value=self.ParmFmt[it]%(item),style=wx.TE_PROCESS_ENTER)
2257                dataSizer.Add(dat,0,WACV)
2258                dat.Bind(wx.EVT_TEXT_ENTER,OnModify)
2259                dat.Bind(wx.EVT_KILL_FOCUS,OnModify)
2260                Indx[dat.GetId()] = [irow,it]
2261        Sizer.Add(dataSizer)
2262        Sizer.Add((-1,10))
2263        # OK/Cancel buttons
2264        btnsizer = wx.StdDialogButtonSizer()
2265        if useOK:
2266            self.OKbtn = wx.Button(panel, wx.ID_OK)
2267            self.OKbtn.SetDefault()
2268            btnsizer.AddButton(self.OKbtn)
2269            self.OKbtn.Bind(wx.EVT_BUTTON, OnOk)
2270        if useCANCEL:
2271            btn = wx.Button(panel, wx.ID_CANCEL)
2272            btnsizer.AddButton(btn)
2273        btnsizer.Realize()
2274        Sizer.Add((-1,5))
2275        Sizer.Add(btnsizer,0,wx.ALIGN_LEFT,20)
2276        Sizer.Add((-1,5))
2277        # OK done, let's get outa here
2278        panel.SetSizer(Sizer)
2279        panel.SetAutoLayout(1)
2280        panel.SetupScrolling()
2281        Size = [450,375]
2282        panel.SetSize(Size)
2283        Size[0] += 25; Size[1]+= 25
2284        self.SetSize(Size)
2285       
2286    def GetData(self):
2287        'Returns the modified ParmData'
2288        return self.ParmData
2289   
2290################################################################################
2291def ItemSelector(ChoiceList, ParentFrame=None,
2292                 title='Select an item',
2293                 size=None, header='Item Selector',
2294                 useCancel=True,multiple=False):
2295    ''' Provide a wx dialog to select a single item or multiple items from list of choices
2296
2297    :param list ChoiceList: a list of choices where one will be selected
2298    :param wx.Frame ParentFrame: Name of parent frame (default None)
2299    :param str title: heading above list of choices (default 'Select an item')
2300    :param wx.Size size: Size for dialog to be created (default None -- size as needed)
2301    :param str header: Title to place on window frame (default 'Item Selector')
2302    :param bool useCancel: If True (default) both the OK and Cancel buttons are offered
2303    :param bool multiple: If True then multiple items can be selected (default False)
2304   
2305    :returns: the selection index or None or a selection list if multiple is true
2306    '''
2307    if multiple:
2308        if useCancel:
2309            dlg = G2MultiChoiceDialog(
2310                ParentFrame,title, header, ChoiceList)
2311        else:
2312            dlg = G2MultiChoiceDialog(
2313                ParentFrame,title, header, ChoiceList,
2314                style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER|wx.OK|wx.CENTRE)
2315    else:
2316        if useCancel:
2317            dlg = wx.SingleChoiceDialog(
2318                ParentFrame,title, header, ChoiceList)
2319        else:
2320            dlg = wx.SingleChoiceDialog(
2321                ParentFrame,title, header,ChoiceList,
2322                style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER|wx.OK|wx.CENTRE)
2323    if size: dlg.SetSize(size)
2324    if dlg.ShowModal() == wx.ID_OK:
2325        if multiple:
2326            dlg.Destroy()
2327            return dlg.GetSelections()
2328        else:
2329            dlg.Destroy()
2330            return dlg.GetSelection()
2331    else:
2332        dlg.Destroy()
2333        return None
2334    dlg.Destroy()
2335
2336######################################################### Column-order selection dialog
2337def GetItemOrder(parent,keylist,vallookup,posdict):
2338    '''Creates a panel where items can be ordered into columns
2339   
2340    :param list keylist: is a list of keys for column assignments
2341    :param dict vallookup: is a dict keyed by names in keylist where each item is a dict.
2342       Each inner dict contains variable names as keys and their associated values
2343    :param dict posdict: is a dict keyed by names in keylist where each item is a dict.
2344       Each inner dict contains column numbers as keys and their associated
2345       variable name as a value. This is used for both input and output.
2346       
2347    '''
2348    dlg = wx.Dialog(parent,style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)
2349    sizer = wx.BoxSizer(wx.VERTICAL)
2350    spanel = OrderBox(dlg,keylist,vallookup,posdict)
2351    spanel.Fit()
2352    sizer.Add(spanel,1,wx.EXPAND)
2353    btnsizer = wx.StdDialogButtonSizer()
2354    btn = wx.Button(dlg, wx.ID_OK)
2355    btn.SetDefault()
2356    btnsizer.AddButton(btn)
2357    #btn = wx.Button(dlg, wx.ID_CANCEL)
2358    #btnsizer.AddButton(btn)
2359    btnsizer.Realize()
2360    sizer.Add(btnsizer, 0, wx.ALIGN_CENTER_VERTICAL|wx.EXPAND|wx.ALL, 5)
2361    dlg.SetSizer(sizer)
2362    sizer.Fit(dlg)
2363    val = dlg.ShowModal()
2364
2365################################################################################
2366class OrderBox(wxscroll.ScrolledPanel):
2367    '''Creates a panel with scrollbars where items can be ordered into columns
2368   
2369    :param list keylist: is a list of keys for column assignments
2370    :param dict vallookup: is a dict keyed by names in keylist where each item is a dict.
2371      Each inner dict contains variable names as keys and their associated values
2372    :param dict posdict: is a dict keyed by names in keylist where each item is a dict.
2373      Each inner dict contains column numbers as keys and their associated
2374      variable name as a value. This is used for both input and output.
2375     
2376    '''
2377    def __init__(self,parent,keylist,vallookup,posdict,*arg,**kw):
2378        self.keylist = keylist
2379        self.vallookup = vallookup
2380        self.posdict = posdict
2381        self.maxcol = 0
2382        for nam in keylist:
2383            posdict = self.posdict[nam]
2384            if posdict.keys():
2385                self.maxcol = max(self.maxcol, max(posdict))
2386        wxscroll.ScrolledPanel.__init__(self,parent,wx.ID_ANY,*arg,**kw)
2387        self.GBsizer = wx.GridBagSizer(4,4)
2388        self.SetBackgroundColour(WHITE)
2389        self.SetSizer(self.GBsizer)
2390        colList = [str(i) for i in range(self.maxcol+2)]
2391        for i in range(self.maxcol+1):
2392            wid = wx.StaticText(self,wx.ID_ANY,str(i),style=wx.ALIGN_CENTER)
2393            wid.SetBackgroundColour(DULL_YELLOW)
2394            wid.SetMinSize((50,-1))
2395            self.GBsizer.Add(wid,(0,i),flag=wx.ALIGN_CENTER|wx.EXPAND)
2396        self.chceDict = {}
2397        for row,nam in enumerate(self.keylist):
2398            posdict = self.posdict[nam]
2399            for col in posdict:
2400                lbl = posdict[col]
2401                pnl = wx.Panel(self,wx.ID_ANY)
2402                pnl.SetBackgroundColour(VERY_LIGHT_GREY)
2403                insize = wx.BoxSizer(wx.VERTICAL)
2404                wid = wx.Choice(pnl,wx.ID_ANY,choices=colList)
2405                insize.Add(wid,0,wx.EXPAND|wx.BOTTOM,3)
2406                wid.SetSelection(col)
2407                self.chceDict[wid] = (row,col)
2408                wid.Bind(wx.EVT_CHOICE,self.OnChoice)
2409                wid = wx.StaticText(pnl,wx.ID_ANY,lbl)
2410                insize.Add(wid,0,flag=wx.EXPAND)
2411                val = G2py3.FormatSigFigs(self.vallookup[nam][lbl],maxdigits=8)
2412                wid = wx.StaticText(pnl,wx.ID_ANY,'('+val+')')
2413                insize.Add(wid,0,flag=wx.EXPAND)
2414                pnl.SetSizer(insize)
2415                self.GBsizer.Add(pnl,(row+1,col),flag=wx.EXPAND)
2416        self.SetAutoLayout(1)
2417        self.SetupScrolling()
2418        self.SetMinSize((
2419            min(700,self.GBsizer.GetSize()[0]),
2420            self.GBsizer.GetSize()[1]+20))
2421    def OnChoice(self,event):
2422        '''Called when a column is assigned to a variable
2423        '''
2424        row,col = self.chceDict[event.EventObject] # which variable was this?
2425        newcol = event.Selection # where will it be moved?
2426        if newcol == col:
2427            return # no change: nothing to do!
2428        prevmaxcol = self.maxcol # save current table size
2429        key = self.keylist[row] # get the key for the current row
2430        lbl = self.posdict[key][col] # selected variable name
2431        lbl1 = self.posdict[key].get(col+1,'') # next variable name, if any
2432        # if a posXXX variable is selected, and the next variable is posXXX, move them together
2433        repeat = 1
2434        if lbl[:3] == 'pos' and lbl1[:3] == 'int' and lbl[3:] == lbl1[3:]:
2435            repeat = 2
2436        for i in range(repeat): # process the posXXX and then the intXXX (or a single variable)
2437            col += i
2438            newcol += i
2439            if newcol in self.posdict[key]:
2440                # find first non-blank after newcol
2441                for mtcol in range(newcol+1,self.maxcol+2):
2442                    if mtcol not in self.posdict[key]: break
2443                l1 = range(mtcol,newcol,-1)+[newcol]
2444                l = range(mtcol-1,newcol-1,-1)+[col]
2445            else:
2446                l1 = [newcol]
2447                l = [col]
2448            # move all of the items, starting from the last column
2449            for newcol,col in zip(l1,l):
2450                #print 'moving',col,'to',newcol
2451                self.posdict[key][newcol] = self.posdict[key][col]
2452                del self.posdict[key][col]
2453                self.maxcol = max(self.maxcol,newcol)
2454                obj = self.GBsizer.FindItemAtPosition((row+1,col))
2455                self.GBsizer.SetItemPosition(obj.GetWindow(),(row+1,newcol))
2456                for wid in obj.GetWindow().Children:
2457                    if wid in self.chceDict:
2458                        self.chceDict[wid] = (row,newcol)
2459                        wid.SetSelection(self.chceDict[wid][1])
2460        # has the table gotten larger? If so we need new column heading(s)
2461        if prevmaxcol != self.maxcol:
2462            for i in range(prevmaxcol+1,self.maxcol+1):
2463                wid = wx.StaticText(self,wx.ID_ANY,str(i),style=wx.ALIGN_CENTER)
2464                wid.SetBackgroundColour(DULL_YELLOW)
2465                wid.SetMinSize((50,-1))
2466                self.GBsizer.Add(wid,(0,i),flag=wx.ALIGN_CENTER|wx.EXPAND)
2467            colList = [str(i) for i in range(self.maxcol+2)]
2468            for wid in self.chceDict:
2469                wid.SetItems(colList)
2470                wid.SetSelection(self.chceDict[wid][1])
2471        self.GBsizer.Layout()
2472        self.FitInside()
2473
2474################################################################################
2475def GetImportFile(G2frame, message, defaultDir="", defaultFile="", style=wx.OPEN,
2476                  *args, **kwargs):
2477    '''Uses a customized dialog that gets files from the appropriate import directory.
2478    Arguments are used the same as in :func:`wx.FileDialog`. Selection of
2479    multiple files is allowed if argument style includes wx.MULTIPLE.
2480
2481    The default initial directory (unless overridden with argument defaultDir)
2482    is found in G2frame.TutorialImportDir, config setting Import_directory or
2483    G2frame.LastImportDir, see :func:`GetImportPath`.
2484
2485    The path of the first file entered is used to set G2frame.LastImportDir
2486    and optionally config setting Import_directory.
2487
2488    :returns: a list of files or an empty list
2489    '''
2490    dlg = wx.FileDialog(G2frame, message, defaultDir, defaultFile, *args,
2491                        style=style, **kwargs)
2492    pth = GetImportPath(G2frame)
2493    if not defaultDir and pth: dlg.SetDirectory(pth)
2494    try:
2495        if dlg.ShowModal() == wx.ID_OK:
2496            if style & wx.MULTIPLE:
2497                filelist = dlg.GetPaths()
2498                if len(filelist) == 0: return []
2499            else:
2500                filelist = [dlg.GetPath(),]
2501            # not sure if we want to do this (why use wx.CHANGE_DIR?)
2502            if style & wx.CHANGE_DIR: # to get Mac/Linux to change directory like windows!
2503                os.chdir(dlg.GetDirectory())
2504        else: # cancel was pressed
2505            return []
2506    finally:
2507        dlg.Destroy()
2508    # save the path of the first file and reset the TutorialImportDir variable
2509    pth = os.path.split(os.path.abspath(filelist[0]))[0]
2510    if GSASIIpath.GetConfigValue('Save_paths'): SaveImportDirectory(pth)
2511    G2frame.LastImportDir = pth
2512    G2frame.TutorialImportDir = None
2513    return filelist
2514
2515def GetImportPath(G2frame):
2516    '''Determines the default location to use for importing files. Tries sequentially
2517    G2frame.TutorialImportDir, config var Import_directory and G2frame.LastImportDir.
2518   
2519    :returns: a string containing the path to be used when reading files or None
2520      if none of the above are specified.
2521    '''
2522    if G2frame.TutorialImportDir:
2523        if os.path.exists(G2frame.TutorialImportDir):
2524            return G2frame.TutorialImportDir
2525        elif GSASIIpath.GetConfigValue('debug'):
2526            print('Tutorial location (TutorialImportDir) not found: '+G2frame.TutorialImportDir)
2527    pth = GSASIIpath.GetConfigValue('Import_directory')
2528    if pth:
2529        pth = os.path.expanduser(pth)
2530        if os.path.exists(pth):
2531            return pth
2532        elif GSASIIpath.GetConfigValue('debug'):
2533            print('Ignoring Config Import_directory value: '+
2534                      GSASIIpath.GetConfigValue('Import_directory'))
2535    if G2frame.LastImportDir:
2536        if os.path.exists(G2frame.LastImportDir):
2537            return G2frame.LastImportDir
2538        elif GSASIIpath.GetConfigValue('debug'):
2539            print('Warning: G2frame.LastImportDir not found = '+G2frame.LastImportDir)
2540    return None
2541
2542def GetExportPath(G2frame):
2543    '''Determines the default location to use for writing files. Tries sequentially
2544    G2frame.LastExportDir and G2frame.LastGPXdir.
2545   
2546    :returns: a string containing the path to be used when writing files or '.'
2547      if none of the above are specified.
2548    '''
2549    if G2frame.LastExportDir:
2550        return G2frame.LastExportDir
2551    elif G2frame.LastGPXdir:
2552        return G2frame.LastGPXdir
2553    else:
2554        return '.'
2555
2556################################################################################
2557#####  Customized Grid Support
2558################################################################################           
2559class GSGrid(wg.Grid):
2560    '''Basic wx.Grid implementation
2561    '''
2562    def __init__(self, parent, name=''):
2563        wg.Grid.__init__(self,parent,-1,name=name)                   
2564        #self.SetSize(parent.GetClientSize())
2565        # above removed to speed drawing of initial grid
2566        # does not appear to be needed
2567           
2568    def Clear(self):
2569        wg.Grid.ClearGrid(self)
2570       
2571    def SetCellReadOnly(self,r,c,readonly=True):
2572        self.SetReadOnly(r,c,isReadOnly=readonly)
2573       
2574    def SetCellStyle(self,r,c,color="white",readonly=True):
2575        self.SetCellBackgroundColour(r,c,color)
2576        self.SetReadOnly(r,c,isReadOnly=readonly)
2577       
2578    def GetSelection(self):
2579        #this is to satisfy structure drawing stuff in G2plt when focus changes
2580        return None
2581
2582    def InstallGridToolTip(self, rowcolhintcallback,
2583                           colLblCallback=None,rowLblCallback=None):
2584        '''code to display a tooltip for each item on a grid
2585        from http://wiki.wxpython.org/wxGrid%20ToolTips (buggy!), expanded to
2586        column and row labels using hints from
2587        https://groups.google.com/forum/#!topic/wxPython-users/bm8OARRVDCs
2588
2589        :param function rowcolhintcallback: a routine that returns a text
2590          string depending on the selected row and column, to be used in
2591          explaining grid entries.
2592        :param function colLblCallback: a routine that returns a text
2593          string depending on the selected column, to be used in
2594          explaining grid columns (if None, the default), column labels
2595          do not get a tooltip.
2596        :param function rowLblCallback: a routine that returns a text
2597          string depending on the selected row, to be used in
2598          explaining grid rows (if None, the default), row labels
2599          do not get a tooltip.
2600        '''
2601        prev_rowcol = [None,None,None]
2602        def OnMouseMotion(event):
2603            # event.GetRow() and event.GetCol() would be nice to have here,
2604            # but as this is a mouse event, not a grid event, they are not
2605            # available and we need to compute them by hand.
2606            x, y = self.CalcUnscrolledPosition(event.GetPosition())
2607            row = self.YToRow(y)
2608            col = self.XToCol(x)
2609            hinttext = ''
2610            win = event.GetEventObject()
2611            if [row,col,win] == prev_rowcol: # no change from last position
2612                event.Skip()
2613                return
2614            if win == self.GetGridWindow() and row >= 0 and col >= 0:
2615                hinttext = rowcolhintcallback(row, col)
2616            elif win == self.GetGridColLabelWindow() and col >= 0:
2617                if colLblCallback: hinttext = colLblCallback(col)
2618            elif win == self.GetGridRowLabelWindow() and row >= 0:
2619                if rowLblCallback: hinttext = rowLblCallback(row)
2620            else: # this should be the upper left corner, which is empty
2621                event.Skip()
2622                return
2623            if hinttext is None: hinttext = ''
2624            win.SetToolTipString(hinttext)
2625            prev_rowcol[:] = [row,col,win]
2626            event.Skip()
2627
2628        wx.EVT_MOTION(self.GetGridWindow(), OnMouseMotion)
2629        if colLblCallback: wx.EVT_MOTION(self.GetGridColLabelWindow(), OnMouseMotion)
2630        if rowLblCallback: wx.EVT_MOTION(self.GetGridRowLabelWindow(), OnMouseMotion)
2631                                                   
2632################################################################################           
2633class Table(wg.PyGridTableBase):
2634    '''Basic data table for use with GSgrid
2635    '''
2636    def __init__(self, data=[], rowLabels=None, colLabels=None, types = None):
2637        wg.PyGridTableBase.__init__(self)
2638        self.colLabels = colLabels
2639        self.rowLabels = rowLabels
2640        self.dataTypes = types
2641        self.data = data
2642       
2643    def AppendRows(self, numRows=1):
2644        self.data.append([])
2645        return True
2646       
2647    def CanGetValueAs(self, row, col, typeName):
2648        if self.dataTypes:
2649            colType = self.dataTypes[col].split(':')[0]
2650            if typeName == colType:
2651                return True
2652            else:
2653                return False
2654        else:
2655            return False
2656
2657    def CanSetValueAs(self, row, col, typeName):
2658        return self.CanGetValueAs(row, col, typeName)
2659
2660    def DeleteRow(self,pos):
2661        data = self.GetData()
2662        self.SetData([])
2663        new = []
2664        for irow,row in enumerate(data):
2665            if irow <> pos:
2666                new.append(row)
2667        self.SetData(new)
2668       
2669    def GetColLabelValue(self, col):
2670        if self.colLabels:
2671            return self.colLabels[col]
2672           
2673    def GetData(self):
2674        data = []
2675        for row in range(self.GetNumberRows()):
2676            data.append(self.GetRowValues(row))
2677        return data
2678       
2679    def GetNumberCols(self):
2680        try:
2681            return len(self.colLabels)
2682        except TypeError:
2683            return None
2684       
2685    def GetNumberRows(self):
2686        return len(self.data)
2687       
2688    def GetRowLabelValue(self, row):
2689        if self.rowLabels:
2690            return self.rowLabels[row]
2691       
2692    def GetColValues(self, col):
2693        data = []
2694        for row in range(self.GetNumberRows()):
2695            data.append(self.GetValue(row, col))
2696        return data
2697       
2698    def GetRowValues(self, row):
2699        data = []
2700        for col in range(self.GetNumberCols()):
2701            data.append(self.GetValue(row, col))
2702        return data
2703       
2704    def GetTypeName(self, row, col):
2705        try:
2706            if self.data[row][col] is None: return None
2707            return self.dataTypes[col]
2708        except (TypeError,IndexError):
2709            return None
2710
2711    def GetValue(self, row, col):
2712        try:
2713            if self.data[row][col] is None: return ""
2714            return self.data[row][col]
2715        except IndexError:
2716            return None
2717           
2718    def InsertRows(self, pos, rows):
2719        for row in range(rows):
2720            self.data.insert(pos,[])
2721            pos += 1
2722       
2723    def IsEmptyCell(self,row,col):
2724        try:
2725            return not self.data[row][col]
2726        except IndexError:
2727            return True
2728       
2729    def OnKeyPress(self, event):
2730        dellist = self.GetSelectedRows()
2731        if event.GetKeyCode() == wx.WXK_DELETE and dellist:
2732            grid = self.GetView()
2733            for i in dellist: grid.DeleteRow(i)
2734               
2735    def SetColLabelValue(self, col, label):
2736        numcols = self.GetNumberCols()
2737        if col > numcols-1:
2738            self.colLabels.append(label)
2739        else:
2740            self.colLabels[col]=label
2741       
2742    def SetData(self,data):
2743        for row in range(len(data)):
2744            self.SetRowValues(row,data[row])
2745               
2746    def SetRowLabelValue(self, row, label):
2747        self.rowLabels[row]=label
2748           
2749    def SetRowValues(self,row,data):
2750        self.data[row] = data
2751           
2752    def SetValue(self, row, col, value):
2753        def innerSetValue(row, col, value):
2754            try:
2755                self.data[row][col] = value
2756            except TypeError:
2757                return
2758            except IndexError: # has this been tested?
2759                #print row,col,value
2760                # add a new row
2761                if row > self.GetNumberRows():
2762                    self.data.append([''] * self.GetNumberCols())
2763                elif col > self.GetNumberCols():
2764                    for row in range(self.GetNumberRows()): # bug fixed here
2765                        self.data[row].append('')
2766                #print self.data
2767                self.data[row][col] = value
2768        innerSetValue(row, col, value)
2769
2770################################################################################
2771class GridFractionEditor(wg.PyGridCellEditor):
2772    '''A grid cell editor class that allows entry of values as fractions as well
2773    as sine and cosine values [as s() and c()]
2774    '''
2775    def __init__(self,grid):
2776        wg.PyGridCellEditor.__init__(self)
2777
2778    def Create(self, parent, id, evtHandler):
2779        self._tc = wx.TextCtrl(parent, id, "")
2780        self._tc.SetInsertionPoint(0)
2781        self.SetControl(self._tc)
2782
2783        if evtHandler:
2784            self._tc.PushEventHandler(evtHandler)
2785
2786        self._tc.Bind(wx.EVT_CHAR, self.OnChar)
2787
2788    def SetSize(self, rect):
2789        self._tc.SetDimensions(rect.x, rect.y, rect.width+2, rect.height+2,
2790                               wx.SIZE_ALLOW_MINUS_ONE)
2791
2792    def BeginEdit(self, row, col, grid):
2793        self.startValue = grid.GetTable().GetValue(row, col)
2794        self._tc.SetValue(str(self.startValue))
2795        self._tc.SetInsertionPointEnd()
2796        self._tc.SetFocus()
2797        self._tc.SetSelection(0, self._tc.GetLastPosition())
2798
2799    def EndEdit(self, row, col, grid, oldVal=None):
2800        changed = False
2801
2802        self.nextval = self.startValue
2803        val = self._tc.GetValue().lower()
2804        if val != self.startValue:
2805            changed = True
2806            neg = False
2807            if '-' in val:
2808                neg = True
2809            if '/' in val and '.' not in val:
2810                val += '.'
2811            elif 's' in val and not 'sind(' in val:
2812                if neg:
2813                    val = '-sind('+val.strip('-s')+')'
2814                else:
2815                    val = 'sind('+val.strip('s')+')'
2816            elif 'c' in val and not 'cosd(' in val:
2817                if neg:
2818                    val = '-cosd('+val.strip('-c')+')'
2819                else:
2820                    val = 'cosd('+val.strip('c')+')'
2821            try:
2822                self.nextval = val = float(eval(val))
2823            except (SyntaxError,NameError,ZeroDivisionError):
2824                val = self.startValue
2825                return None
2826           
2827            if oldVal is None: # this arg appears in 2.9+; before, we should go ahead & change the table
2828                grid.GetTable().SetValue(row, col, val) # update the table
2829            # otherwise self.ApplyEdit gets called
2830
2831        self.startValue = ''
2832        self._tc.SetValue('')
2833        return changed
2834   
2835    def ApplyEdit(self, row, col, grid):
2836        """ Called only in wx >= 2.9
2837        Save the value of the control into the grid if EndEdit() returns as True
2838        """
2839        grid.GetTable().SetValue(row, col, self.nextval) # update the table
2840
2841    def Reset(self):
2842        self._tc.SetValue(self.startValue)
2843        self._tc.SetInsertionPointEnd()
2844
2845    def Clone(self):
2846        return GridFractionEditor(grid)
2847
2848    def StartingKey(self, evt):
2849        self.OnChar(evt)
2850        if evt.GetSkipped():
2851            self._tc.EmulateKeyPress(evt)
2852
2853    def OnChar(self, evt):
2854        key = evt.GetKeyCode()
2855        if key == 15:
2856            return
2857        if key > 255:
2858            evt.Skip()
2859            return
2860        char = chr(key)
2861        if char in '.+-/0123456789cosind()':
2862            self._tc.WriteText(char)
2863        else:
2864            evt.Skip()
2865           
2866################################################################################
2867#####  Customized Notebook
2868################################################################################           
2869class GSNoteBook(wx.aui.AuiNotebook):
2870    '''Notebook used in various locations; implemented with wx.aui extension
2871    '''
2872    def __init__(self, parent, name='',size = None):
2873        wx.aui.AuiNotebook.__init__(self, parent, -1,
2874                                    style=wx.aui.AUI_NB_TOP |
2875                                    wx.aui.AUI_NB_SCROLL_BUTTONS)
2876        if size: self.SetSize(size)
2877        self.parent = parent
2878        self.PageChangeHandler = None
2879       
2880    def PageChangeEvent(self,event):
2881        G2frame = self.parent.G2frame
2882        page = event.GetSelection()
2883        if self.PageChangeHandler:
2884            if log.LogInfo['Logging']:
2885                log.MakeTabLog(
2886                    G2frame.dataFrame.GetTitle(),
2887                    G2frame.dataDisplay.GetPageText(page)
2888                    )
2889            self.PageChangeHandler(event)
2890           
2891    def Bind(self,eventtype,handler,*args,**kwargs):
2892        '''Override the Bind() function so that page change events can be trapped
2893        '''
2894        if eventtype == wx.aui.EVT_AUINOTEBOOK_PAGE_CHANGED:
2895            self.PageChangeHandler = handler
2896            wx.aui.AuiNotebook.Bind(self,eventtype,self.PageChangeEvent)
2897            return
2898        wx.aui.AuiNotebook.Bind(self,eventtype,handler,*args,**kwargs)
2899                                                     
2900    def Clear(self):       
2901        GSNoteBook.DeleteAllPages(self)
2902       
2903    def FindPage(self,name):
2904        numPage = self.GetPageCount()
2905        for page in range(numPage):
2906            if self.GetPageText(page) == name:
2907                return page
2908
2909    def ChangeSelection(self,page):
2910        # in wx.Notebook ChangeSelection is like SetSelection, but it
2911        # does not invoke the event related to pressing the tab button
2912        # I don't see a way to do that in aui.
2913        oldPage = self.GetSelection()
2914        self.SetSelection(page)
2915        return oldPage
2916
2917    # def __getattribute__(self,name):
2918    #     '''This method provides a way to print out a message every time
2919    #     that a method in a class is called -- to see what all the calls
2920    #     might be, or where they might be coming from.
2921    #     Cute trick for debugging!
2922    #     '''
2923    #     attr = object.__getattribute__(self, name)
2924    #     if hasattr(attr, '__call__'):
2925    #         def newfunc(*args, **kwargs):
2926    #             print('GSauiNoteBook calling %s' %attr.__name__)
2927    #             result = attr(*args, **kwargs)
2928    #             return result
2929    #         return newfunc
2930    #     else:
2931    #         return attr
2932           
2933################################################################################
2934#### Help support routines
2935################################################################################
2936class MyHelp(wx.Menu):
2937    '''
2938    A class that creates the contents of a help menu.
2939    The menu will start with two entries:
2940
2941    * 'Help on <helpType>': where helpType is a reference to an HTML page to
2942      be opened
2943    * About: opens an About dialog using OnHelpAbout. N.B. on the Mac this
2944      gets moved to the App menu to be consistent with Apple style.
2945
2946    NOTE: for this to work properly with respect to system menus, the title
2947    for the menu must be &Help, or it will not be processed properly:
2948
2949    ::
2950
2951       menu.Append(menu=MyHelp(self,...),title="&Help")
2952
2953    '''
2954    def __init__(self,frame,helpType=None,helpLbl=None,morehelpitems=[],title=''):
2955        wx.Menu.__init__(self,title)
2956        self.HelpById = {}
2957        self.frame = frame
2958        self.Append(help='', id=wx.ID_ABOUT, kind=wx.ITEM_NORMAL,
2959            text='&About GSAS-II')
2960        frame.Bind(wx.EVT_MENU, self.OnHelpAbout, id=wx.ID_ABOUT)
2961        if GSASIIpath.whichsvn():
2962            helpobj = self.Append(
2963                help='', id=wx.ID_ANY, kind=wx.ITEM_NORMAL,
2964                text='&Check for updates')
2965            frame.Bind(wx.EVT_MENU, self.OnCheckUpdates, helpobj)
2966            helpobj = self.Append(
2967                help='', id=wx.ID_ANY, kind=wx.ITEM_NORMAL,
2968                text='&Regress to an old GSAS-II version')
2969            frame.Bind(wx.EVT_MENU, self.OnSelectVersion, helpobj)
2970        for lbl,indx in morehelpitems:
2971            helpobj = self.Append(text=lbl,
2972                id=wx.ID_ANY, kind=wx.ITEM_NORMAL)
2973            frame.Bind(wx.EVT_MENU, self.OnHelpById, helpobj)
2974            self.HelpById[helpobj.GetId()] = indx
2975        # add a help item only when helpType is specified
2976        if helpType is not None:
2977            self.AppendSeparator()
2978            if helpLbl is None: helpLbl = helpType
2979            helpobj = self.Append(text='Help on '+helpLbl,
2980                                  id=wx.ID_ANY, kind=wx.ITEM_NORMAL)
2981            frame.Bind(wx.EVT_MENU, self.OnHelpById, helpobj)
2982            self.HelpById[helpobj.GetId()] = helpType
2983       
2984    def OnHelpById(self,event):
2985        '''Called when Help on... is pressed in a menu. Brings up
2986        a web page for documentation.
2987        '''
2988        helpType = self.HelpById.get(event.GetId())
2989        if helpType is None:
2990            print 'Error: help lookup failed!',event.GetEventObject()
2991            print 'id=',event.GetId()
2992        elif helpType == 'Tutorials': 
2993            dlg = OpenTutorial(self.frame)
2994            dlg.ShowModal()
2995            dlg.Destroy()
2996            return
2997        else:
2998            ShowHelp(helpType,self.frame)
2999
3000    def OnHelpAbout(self, event):
3001        "Display an 'About GSAS-II' box"
3002        import GSASII
3003        info = wx.AboutDialogInfo()
3004        info.Name = 'GSAS-II'
3005        ver = GSASIIpath.svnGetRev()
3006        if ver: 
3007            info.Version = 'Revision '+str(ver)+' (svn), version '+GSASII.__version__
3008        else:
3009            info.Version = 'Revision '+str(GSASIIpath.GetVersionNumber())+' (.py files), version '+GSASII.__version__
3010        #info.Developers = ['Robert B. Von Dreele','Brian H. Toby']
3011        info.Copyright = ('(c) ' + time.strftime('%Y') +
3012''' Argonne National Laboratory
3013This product includes software developed
3014by the UChicago Argonne, LLC, as
3015Operator of Argonne National Laboratory.''')
3016        info.Description = '''General Structure Analysis System-II (GSAS-II)
3017Robert B. Von Dreele and Brian H. Toby
3018
3019Please cite as:
3020B.H. Toby & R.B. Von Dreele, J. Appl. Cryst. 46, 544-549 (2013) '''
3021
3022        info.WebSite = ("https://subversion.xray.aps.anl.gov/trac/pyGSAS","GSAS-II home page")
3023        wx.AboutBox(info)
3024
3025    def OnCheckUpdates(self,event):
3026        '''Check if the GSAS-II repository has an update for the current source files
3027        and perform that update if requested.
3028        '''
3029        if not GSASIIpath.whichsvn():
3030            dlg = wx.MessageDialog(self.frame,
3031                                   'No Subversion','Cannot update GSAS-II because subversion (svn) was not found.',
3032                                   wx.OK)
3033            dlg.ShowModal()
3034            dlg.Destroy()
3035            return
3036        wx.BeginBusyCursor()
3037        local = GSASIIpath.svnGetRev()
3038        if local is None: 
3039            wx.EndBusyCursor()
3040            dlg = wx.MessageDialog(self.frame,
3041                                   'Unable to run subversion on the GSAS-II current directory. Is GSAS-II installed correctly?',
3042                                   'Subversion error',
3043                                   wx.OK)
3044            dlg.ShowModal()
3045            dlg.Destroy()
3046            return
3047        print 'Installed GSAS-II version: '+local
3048        repos = GSASIIpath.svnGetRev(local=False)
3049        wx.EndBusyCursor()
3050        if repos is None: 
3051            dlg = wx.MessageDialog(self.frame,
3052                                   'Unable to access the GSAS-II server. Is this computer on the internet?',
3053                                   'Server unavailable',
3054                                   wx.OK)
3055            dlg.ShowModal()
3056            dlg.Destroy()
3057            return
3058        print 'GSAS-II version on server: '+repos
3059        if local == repos:
3060            dlg = wx.MessageDialog(self.frame,
3061                                   'GSAS-II is up-to-date. Version '+local+' is already loaded.',
3062                                   'GSAS-II Up-to-date',
3063                                   wx.OK)
3064            dlg.ShowModal()
3065            dlg.Destroy()
3066            return
3067        mods = GSASIIpath.svnFindLocalChanges()
3068        if mods:
3069            dlg = wx.MessageDialog(self.frame,
3070                                   'You have version '+local+
3071                                   ' of GSAS-II installed, but the current version is '+repos+
3072                                   '. However, '+str(len(mods))+
3073                                   ' file(s) on your local computer have been modified.'
3074                                   ' Updating will attempt to merge your local changes with '
3075                                   'the latest GSAS-II version, but if '
3076                                   'conflicts arise, local changes will be '
3077                                   'discarded. It is also possible that the '
3078                                   'local changes my prevent GSAS-II from running. '
3079                                   'Press OK to start an update if this is acceptable:',
3080                                   'Local GSAS-II Mods',
3081                                   wx.OK|wx.CANCEL)
3082            if dlg.ShowModal() != wx.ID_OK:
3083                dlg.Destroy()
3084                return
3085            else:
3086                dlg.Destroy()
3087        else:
3088            dlg = wx.MessageDialog(self.frame,
3089                                   'You have version '+local+
3090                                   ' of GSAS-II installed, but the current version is '+repos+
3091                                   '. Press OK to start an update:',
3092                                   'GSAS-II Updates',
3093                                   wx.OK|wx.CANCEL)
3094            if dlg.ShowModal() != wx.ID_OK:
3095                dlg.Destroy()
3096                return
3097            dlg.Destroy()
3098        print 'start updates'
3099        dlg = wx.MessageDialog(self.frame,
3100                               'Your project will now be saved, GSAS-II will exit and an update '
3101                               'will be performed and GSAS-II will restart. Press Cancel to '
3102                               'abort the update',
3103                               'Start update?',
3104                               wx.OK|wx.CANCEL)
3105        if dlg.ShowModal() != wx.ID_OK:
3106            dlg.Destroy()
3107            return
3108        dlg.Destroy()
3109        self.frame.OnFileSave(event)
3110        GSASIIpath.svnUpdateProcess(projectfile=self.frame.GSASprojectfile)
3111        return
3112
3113    def OnSelectVersion(self,event):
3114        '''Allow the user to select a specific version of GSAS-II
3115        '''
3116        if not GSASIIpath.whichsvn():
3117            dlg = wx.MessageDialog(self,'No Subversion','Cannot update GSAS-II because subversion (svn) '+
3118                                   'was not found.'
3119                                   ,wx.OK)
3120            dlg.ShowModal()
3121            return
3122        local = GSASIIpath.svnGetRev()
3123        if local is None: 
3124            dlg = wx.MessageDialog(self.frame,
3125                                   'Unable to run subversion on the GSAS-II current directory. Is GSAS-II installed correctly?',
3126                                   'Subversion error',
3127                                   wx.OK)
3128            dlg.ShowModal()
3129            return
3130        mods = GSASIIpath.svnFindLocalChanges()
3131        if mods:
3132            dlg = wx.MessageDialog(self.frame,
3133                                   'You have version '+local+
3134                                   ' of GSAS-II installed'
3135                                   '. However, '+str(len(mods))+
3136                                   ' file(s) on your local computer have been modified.'
3137                                   ' Downdating will attempt to merge your local changes with '
3138                                   'the selected GSAS-II version. '
3139                                   'Downdating is not encouraged because '
3140                                   'if merging is not possible, your local changes will be '
3141                                   'discarded. It is also possible that the '
3142                                   'local changes my prevent GSAS-II from running. '
3143                                   'Press OK to continue anyway.',
3144                                   'Local GSAS-II Mods',
3145                                   wx.OK|wx.CANCEL)
3146            if dlg.ShowModal() != wx.ID_OK:
3147                dlg.Destroy()
3148                return
3149            dlg.Destroy()
3150        dlg = downdate(parent=self.frame)
3151        if dlg.ShowModal() == wx.ID_OK:
3152            ver = dlg.getVersion()
3153        else:
3154            dlg.Destroy()
3155            return
3156        dlg.Destroy()
3157        print('start regress to '+str(ver))
3158        GSASIIpath.svnUpdateProcess(
3159            projectfile=self.frame.GSASprojectfile,
3160            version=str(ver)
3161            )
3162        self.frame.OnFileSave(event)
3163        return
3164
3165################################################################################
3166class AddHelp(wx.Menu):
3167    '''For the Mac: creates an entry to the help menu of type
3168    'Help on <helpType>': where helpType is a reference to an HTML page to
3169    be opened.
3170
3171    NOTE: when appending this menu (menu.Append) be sure to set the title to
3172    '&Help' so that wx handles it correctly.
3173    '''
3174    def __init__(self,frame,helpType,helpLbl=None,title=''):
3175        wx.Menu.__init__(self,title)
3176        self.frame = frame
3177        if helpLbl is None: helpLbl = helpType
3178        # add a help item only when helpType is specified
3179        helpobj = self.Append(text='Help on '+helpLbl,
3180                              id=wx.ID_ANY, kind=wx.ITEM_NORMAL)
3181        frame.Bind(wx.EVT_MENU, self.OnHelpById, helpobj)
3182        self.HelpById = helpType
3183       
3184    def OnHelpById(self,event):
3185        '''Called when Help on... is pressed in a menu. Brings up
3186        a web page for documentation.
3187        '''
3188        ShowHelp(self.HelpById,self.frame)
3189
3190################################################################################
3191class HelpButton(wx.Button):
3192    '''Create a help button that displays help information.
3193    The text is displayed in a modal message window.
3194
3195    TODO: it might be nice if it were non-modal: e.g. it stays around until
3196    the parent is deleted or the user closes it, but this did not work for
3197    me.
3198
3199    :param parent: the panel which will be the parent of the button
3200    :param str msg: the help text to be displayed
3201    '''
3202    def __init__(self,parent,msg):
3203        if sys.platform == "darwin": 
3204            wx.Button.__init__(self,parent,wx.ID_HELP)
3205        else:
3206            wx.Button.__init__(self,parent,wx.ID_ANY,'?',style=wx.BU_EXACTFIT)
3207        self.Bind(wx.EVT_BUTTON,self._onPress)
3208        self.msg=StripIndents(msg)
3209        self.parent = parent
3210    def _onClose(self,event):
3211        self.dlg.EndModal(wx.ID_CANCEL)
3212    def _onPress(self,event):
3213        'Respond to a button press by displaying the requested text'
3214        #dlg = wx.MessageDialog(self.parent,self.msg,'Help info',wx.OK)
3215        self.dlg = wx.Dialog(self.parent,wx.ID_ANY,'Help information', 
3216                        style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)
3217        #self.dlg.SetBackgroundColour(wx.WHITE)
3218        mainSizer = wx.BoxSizer(wx.VERTICAL)
3219        txt = wx.StaticText(self.dlg,wx.ID_ANY,self.msg)
3220        mainSizer.Add(txt,1,wx.ALL|wx.EXPAND,10)
3221        txt.SetBackgroundColour(wx.WHITE)
3222
3223        btnsizer = wx.BoxSizer(wx.HORIZONTAL)
3224        btn = wx.Button(self.dlg, wx.ID_CLOSE) 
3225        btn.Bind(wx.EVT_BUTTON,self._onClose)
3226        btnsizer.Add(btn)
3227        mainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER|wx.ALL, 5)
3228        self.dlg.SetSizer(mainSizer)
3229        mainSizer.Fit(self.dlg)
3230        self.dlg.CenterOnParent()
3231        self.dlg.ShowModal()
3232        self.dlg.Destroy()
3233################################################################################
3234class MyHtmlPanel(wx.Panel):
3235    '''Defines a panel to display HTML help information, as an alternative to
3236    displaying help information in a web browser.
3237    '''
3238    def __init__(self, frame, id):
3239        self.frame = frame
3240        wx.Panel.__init__(self, frame, id)
3241        sizer = wx.BoxSizer(wx.VERTICAL)
3242        back = wx.Button(self, -1, "Back")
3243        back.Bind(wx.EVT_BUTTON, self.OnBack)
3244        self.htmlwin = G2HtmlWindow(self, id, size=(750,450))
3245        sizer.Add(self.htmlwin, 1,wx.EXPAND)
3246        sizer.Add(back, 0, wx.ALIGN_LEFT, 0)
3247        self.SetSizer(sizer)
3248        sizer.Fit(frame)       
3249        self.Bind(wx.EVT_SIZE,self.OnHelpSize)
3250    def OnHelpSize(self,event):         #does the job but weirdly!!
3251        anchor = self.htmlwin.GetOpenedAnchor()
3252        if anchor:           
3253            self.htmlwin.ScrollToAnchor(anchor)
3254            wx.CallAfter(self.htmlwin.ScrollToAnchor,anchor)
3255            event.Skip()
3256    def OnBack(self, event):
3257        self.htmlwin.HistoryBack()
3258    def LoadFile(self,file):
3259        pos = file.rfind('#')
3260        if pos != -1:
3261            helpfile = file[:pos]
3262            helpanchor = file[pos+1:]
3263        else:
3264            helpfile = file
3265            helpanchor = None
3266        self.htmlwin.LoadPage(helpfile)
3267        if helpanchor is not None:
3268            self.htmlwin.ScrollToAnchor(helpanchor)
3269            xs,ys = self.htmlwin.GetViewStart()
3270            self.htmlwin.Scroll(xs,ys-1)
3271################################################################################
3272class G2HtmlWindow(wx.html.HtmlWindow):
3273    '''Displays help information in a primitive HTML browser type window
3274    '''
3275    def __init__(self, parent, *args, **kwargs):
3276        self.parent = parent
3277        wx.html.HtmlWindow.__init__(self, parent, *args, **kwargs)
3278    def LoadPage(self, *args, **kwargs):
3279        wx.html.HtmlWindow.LoadPage(self, *args, **kwargs)
3280        self.TitlePage()
3281    def OnLinkClicked(self, *args, **kwargs):
3282        wx.html.HtmlWindow.OnLinkClicked(self, *args, **kwargs)
3283        xs,ys = self.GetViewStart()
3284        self.Scroll(xs,ys-1)
3285        self.TitlePage()
3286    def HistoryBack(self, *args, **kwargs):
3287        wx.html.HtmlWindow.HistoryBack(self, *args, **kwargs)
3288        self.TitlePage()
3289    def TitlePage(self):
3290        self.parent.frame.SetTitle(self.GetOpenedPage() + ' -- ' + 
3291            self.GetOpenedPageTitle())
3292
3293################################################################################
3294def StripIndents(msg):
3295    'Strip indentation from multiline strings'
3296    msg1 = msg.replace('\n ','\n')
3297    while msg != msg1:
3298        msg = msg1
3299        msg1 = msg.replace('\n ','\n')
3300    return msg.replace('\n\t','\n')
3301       
3302################################################################################
3303# configuration routines (for editing config.py)
3304def SaveGPXdirectory(path):
3305    if GSASIIpath.GetConfigValue('Starting_directory') == path: return
3306    vars = GetConfigValsDocs()
3307    try:
3308        vars['Starting_directory'][1] = path
3309        if GSASIIpath.GetConfigValue('debug'): print('Saving GPX path: '+path)
3310        SaveConfigVars(vars)
3311    except KeyError:
3312        pass
3313
3314def SaveImportDirectory(path):
3315    if GSASIIpath.GetConfigValue('Import_directory') == path: return
3316    vars = GetConfigValsDocs()
3317    try:
3318        vars['Import_directory'][1] = path
3319        if GSASIIpath.GetConfigValue('debug'): print('Saving Import path: '+path)
3320        SaveConfigVars(vars)
3321    except KeyError:
3322        pass
3323
3324def GetConfigValsDocs():
3325    '''Reads the module referenced in fname (often <module>.__file__) and
3326    return a dict with names of global variables as keys.
3327    For each global variable, the value contains four items:
3328
3329    :returns: a dict where keys are names defined in module config_example.py
3330      where the value is a list of four items, as follows:
3331
3332         * item 0: the default value
3333         * item 1: the current value
3334         * item 2: the initial value (starts same as item 1)
3335         * item 3: the "docstring" that follows variable definition
3336
3337    '''
3338    import config_example
3339    import ast
3340    fname = os.path.splitext(config_example.__file__)[0]+'.py' # convert .pyc to .py
3341    with open(fname, 'r') as f:
3342        fstr = f.read()
3343    fstr = fstr.replace('\r\n', '\n').replace('\r', '\n')
3344    if not fstr.endswith('\n'):
3345        fstr += '\n'
3346    tree = ast.parse(fstr)
3347    d = {}
3348    key = None
3349    for node in ast.walk(tree):
3350        if isinstance(node,ast.Assign):
3351            key = node.targets[0].id
3352            d[key] = [config_example.__dict__.get(key),
3353                      GSASIIpath.configDict.get(key),
3354                      GSASIIpath.configDict.get(key),'']
3355        elif isinstance(node,ast.Expr) and key:
3356            d[key][3] = node.value.s.strip()
3357        else:
3358            key = None
3359    return d
3360
3361def SaveConfigVars(vars,parent=None):
3362    '''Write the current config variable values to config.py
3363
3364    :params dict vars: a dictionary of variable settings and meanings as
3365      created in :func:`GetConfigValsDocs`.
3366    :param parent: wx.Frame object or None (default) for parent
3367      of error message if no file can be written.
3368    :returns: True if unable to write the file, None otherwise
3369    '''
3370    # try to write to where an old config file is located
3371    try:
3372        import config
3373        savefile = config.__file__
3374    except ImportError: # no config.py file yet
3375        savefile = os.path.join(GSASIIpath.path2GSAS2,'config.py')
3376    # try to open file for write
3377    try:
3378        savefile = os.path.splitext(savefile)[0]+'.py' # convert .pyc to .py
3379        fp = open(savefile,'w')
3380    except IOError:  # can't write there, write in local mods directory
3381        # create a local mods directory, if needed
3382        if not os.path.exists(os.path.expanduser('~/.G2local/')):
3383            print('Creating directory '+os.path.expanduser('~/.G2local/'))
3384            os.mkdir(os.path.expanduser('~/.G2local/'))
3385            sys.path.insert(0,os.path.expanduser('~/.G2local/'))
3386        savefile = os.path.join(os.path.expanduser('~/.G2local/'),'config.py')
3387        try:
3388            fp = open(savefile,'w')
3389        except IOError:
3390            if parent:
3391                G2MessageBox(parent,
3392                             'Error trying to write configuration to '+savefile,
3393                             'Unable to save')
3394            else:
3395                print('Error trying to write configuration to '+savefile)
3396            return True
3397    import datetime
3398    fp.write("'''\n")
3399    fp.write("*config.py: Configuration options*\n----------------------------------\n")
3400    fp.write("This file created in SelectConfigSetting on {:%d %b %Y %H:%M}\n".
3401             format(datetime.datetime.now()))
3402    fp.write("'''\n\n")
3403    fp.write("import os.path\n")
3404    fp.write("import GSASIIpath\n\n")
3405    for var in sorted(vars.keys(),key=lambda s: s.lower()):
3406        if vars[var][1] is None: continue
3407        if vars[var][1] == '': continue
3408        if vars[var][0] == vars[var][1]: continue
3409        try:
3410            float(vars[var][1]) # test for number
3411            fp.write(var + ' = ' + str(vars[var][1])+'\n')
3412        except:
3413            try:
3414                eval(vars[var][1]) # test for an expression
3415                fp.write(var + ' = ' + str(vars[var][1])+'\n')
3416            except: # must be a string
3417                fp.write(var + ' = "' + str(vars[var][1])+'"\n')
3418        if vars[var][3]:
3419            fp.write("'''" + str(vars[var][3]) + "\n'''\n\n")
3420    fp.close()
3421    print('wrote file '+savefile)
3422
3423class SelectConfigSetting(wx.Dialog):
3424    '''Dialog to select configuration variables and set associated values.
3425    '''
3426    def __init__(self,parent=None):
3427        style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER
3428        wx.Dialog.__init__(self, parent, wx.ID_ANY, 'Set Config Variable', style=style)
3429        self.sizer = wx.BoxSizer(wx.VERTICAL)
3430        self.vars = GetConfigValsDocs()
3431       
3432        label = wx.StaticText(
3433            self,  wx.ID_ANY,
3434            'Select a GSAS-II configuration variable to change'
3435            )
3436        self.sizer.Add(label, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
3437        self.choice = {}
3438        btn = G2ChoiceButton(self, sorted(self.vars.keys(),key=lambda s: s.lower()),
3439                                 strLoc=self.choice,strKey=0,
3440                                 onChoice=self.OnSelection)
3441        btn.SetLabel("")
3442        self.sizer.Add(btn)
3443
3444        self.varsizer = wx.BoxSizer(wx.VERTICAL)
3445        self.sizer.Add(self.varsizer,1,wx.ALL|wx.EXPAND,1)
3446       
3447        self.doclbl = wx.StaticBox(self, wx.ID_ANY, "")
3448        self.doclblsizr = wx.StaticBoxSizer(self.doclbl)
3449        self.docinfo = wx.StaticText(self,  wx.ID_ANY, "")
3450        self.doclblsizr.Add(self.docinfo, 0, wx.ALIGN_LEFT|wx.ALL, 5)
3451        self.sizer.Add(self.doclblsizr, 0, wx.ALIGN_LEFT|wx.EXPAND|wx.ALL, 5)
3452        btnsizer = wx.BoxSizer(wx.HORIZONTAL)
3453        self.saveBtn = wx.Button(self,-1,"Save current settings")
3454        btnsizer.Add(self.saveBtn, 0, wx.ALL, 2) 
3455        self.saveBtn.Bind(wx.EVT_BUTTON, self.OnSave)
3456        self.saveBtn.Enable(False)
3457        self.applyBtn = wx.Button(self,-1,"Use current (no save)")
3458        btnsizer.Add(self.applyBtn, 0, wx.ALL, 2) 
3459        self.applyBtn.Bind(wx.EVT_BUTTON, self.OnApplyChanges)
3460        self.applyBtn.Enable(False)
3461       
3462        btn = wx.Button(self,wx.ID_CANCEL)
3463        btnsizer.Add(btn, 0, wx.ALL, 2) 
3464        self.sizer.Add(btnsizer, 0, wx.ALIGN_CENTRE|wx.ALL, 5) 
3465               
3466        self.SetSizer(self.sizer)
3467        self.sizer.Fit(self)
3468        self.CenterOnParent()
3469
3470    def OnChange(self,event=None):
3471        ''' Check if anything been changed. Turn the save button on/off.
3472        '''
3473        for var in self.vars:
3474            if self.vars[var][0] is None and self.vars[var][1] is not None:
3475                # make blank strings into None, if that is the default
3476                if self.vars[var][1].strip() == '': self.vars[var][1] = None
3477            if self.vars[var][1] != self.vars[var][2]:
3478                #print 'changed',var,self.vars[var][:3]
3479                self.saveBtn.Enable(True)
3480                self.applyBtn.Enable(True)
3481                break
3482        else:
3483            self.saveBtn.Enable(False)
3484            self.applyBtn.Enable(False)
3485        try:
3486            self.resetBtn.Enable(True)
3487        except:
3488            pass
3489       
3490    def OnApplyChanges(self,event=None):
3491        'Set config variables to match the current settings'
3492        GSASIIpath.SetConfigValue(self.vars)
3493        self.EndModal(wx.ID_OK)
3494       
3495    def OnSave(self,event):
3496        '''Write the config variables to config.py and then set them
3497        as the current settings
3498        '''
3499        if not SaveConfigVars(self.vars,parent=self):
3500            self.OnApplyChanges() # force a reload of the config settings
3501            self.EndModal(wx.ID_OK)
3502
3503    def OnBoolSelect(self,event):
3504        'Respond to a change in a True/False variable'
3505        rb = event.GetEventObject()
3506        var = self.choice[0]
3507        self.vars[var][1] = (rb.GetSelection() == 0)
3508        self.OnChange()
3509        wx.CallAfter(self.OnSelection)
3510       
3511    def onSelDir(self,event):
3512        'Select a directory from a menu'
3513        dlg = wx.DirDialog(self, "Choose a directory:",style=wx.DD_DEFAULT_STYLE)
3514        if dlg.ShowModal() == wx.ID_OK:
3515            var = self.choice[0]
3516            self.vars[var][1] = dlg.GetPath()
3517            self.strEd.SetValue(self.vars[var][1])
3518            self.OnChange()
3519        dlg.Destroy()
3520       
3521    def OnSelection(self):
3522        'show a selected variable'
3523        self.varsizer.DeleteWindows()
3524        var = self.choice[0]
3525        showdef = True
3526        if var not in self.vars:
3527            raise Exception,"How did this happen?"
3528        if type(self.vars[var][0]) is int:
3529            ed = ValidatedTxtCtrl(self,self.vars[var],1,typeHint=int,OKcontrol=self.OnChange)
3530            self.varsizer.Add(ed, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
3531        elif type(self.vars[var][0]) is float:
3532            ed = ValidatedTxtCtrl(self,self.vars[var],1,typeHint=float,OKcontrol=self.OnChange)
3533            self.varsizer.Add(ed, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
3534        elif type(self.vars[var][0]) is bool:
3535            showdef = False
3536            lbl = "value for "+var
3537            ch = []
3538            for i,v in enumerate((True,False)):
3539                s = str(v)
3540                if v == self.vars[var][0]:
3541                    defopt = i
3542                    s += ' (default)'
3543                ch += [s]
3544            rb = wx.RadioBox(
3545                    self, wx.ID_ANY, lbl, wx.DefaultPosition, wx.DefaultSize,
3546                    ch, 1, wx.RA_SPECIFY_COLS
3547            )
3548            # set initial value
3549            if self.vars[var][1] is None:
3550                rb.SetSelection(defopt)
3551            elif self.vars[var][1]:
3552                rb.SetSelection(0)
3553            else:
3554                rb.SetSelection(1)
3555            rb.Bind(wx.EVT_RADIOBOX,self.OnBoolSelect)
3556            self.varsizer.Add(rb, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
3557        else:
3558            if var.endswith('_directory') or var.endswith('_location'):
3559                btn = wx.Button(self,wx.ID_ANY,'Select from dialog...')
3560                sz = (400,-1)
3561            else:
3562                btn = None
3563                sz = (250,-1)
3564            self.strEd = ValidatedTxtCtrl(self,self.vars[var],1,typeHint=str,OKcontrol=self.OnChange,
3565                                              size=sz)
3566            if self.vars[var][1] is not None:
3567                self.strEd.SetValue(self.vars[var][1])
3568            self.varsizer.Add(self.strEd, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
3569            if btn:
3570                btn.Bind(wx.EVT_BUTTON,self.onSelDir)
3571                self.varsizer.Add(btn, 0, wx.ALIGN_CENTRE|wx.ALL, 5) 
3572        # button for reset to default value
3573        lbl = "Reset to Default"
3574        if showdef: # spell out default when needed
3575            lbl += ' (='+str(self.vars[var][0])+')'
3576            #label = wx.StaticText(self,  wx.ID_ANY, 'Default value = '+str(self.vars[var][0]))
3577            #self.varsizer.Add(label, 0, wx.ALIGN_LEFT|wx.ALL, 5)
3578        self.resetBtn = wx.Button(self,-1,lbl)
3579        self.resetBtn.Bind(wx.EVT_BUTTON, self.OnClear)
3580        if self.vars[var][1] is not None and self.vars[var][1] != '': # show current value, if one
3581            #label = wx.StaticText(self,  wx.ID_ANY, 'Current value = '+str(self.vars[var][1]))
3582            #self.varsizer.Add(label, 0, wx.ALIGN_LEFT|wx.ALL, 5)
3583            self.resetBtn.Enable(True)
3584        else:
3585            self.resetBtn.Enable(False)
3586        self.varsizer.Add(self.resetBtn, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
3587        # show meaning, if defined
3588        self.doclbl.SetLabel("Description of "+str(var)) 
3589        if self.vars[var][3]:
3590            self.docinfo.SetLabel(self.vars[var][3])
3591        else:
3592            self.docinfo.SetLabel("(not documented)")
3593        self.sizer.Fit(self)
3594        self.CenterOnParent()
3595        wx.CallAfter(self.SendSizeEvent)
3596
3597    def OnClear(self, event):
3598        var = self.choice[0]
3599        self.vars[var][1] = self.vars[var][0]
3600        self.OnChange()
3601        wx.CallAfter(self.OnSelection)
3602       
3603################################################################################
3604class downdate(wx.Dialog):
3605    '''Dialog to allow a user to select a version of GSAS-II to install
3606    '''
3607    def __init__(self,parent=None):
3608        style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER
3609        wx.Dialog.__init__(self, parent, wx.ID_ANY, 'Select Version', style=style)
3610        pnl = wx.Panel(self)
3611        sizer = wx.BoxSizer(wx.VERTICAL)
3612        insver = GSASIIpath.svnGetRev(local=True)
3613        curver = int(GSASIIpath.svnGetRev(local=False))
3614        label = wx.StaticText(
3615            pnl,  wx.ID_ANY,
3616            'Select a specific GSAS-II version to install'
3617            )
3618        sizer.Add(label, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
3619        sizer1 = wx.BoxSizer(wx.HORIZONTAL)
3620        sizer1.Add(
3621            wx.StaticText(pnl,  wx.ID_ANY,
3622                          'Currently installed version: '+str(insver)),
3623            0, wx.ALIGN_CENTRE|wx.ALL, 5)
3624        sizer.Add(sizer1)
3625        sizer1 = wx.BoxSizer(wx.HORIZONTAL)
3626        sizer1.Add(
3627            wx.StaticText(pnl,  wx.ID_ANY,
3628                          'Select GSAS-II version to install: '),
3629            0, wx.ALIGN_CENTRE|wx.ALL, 5)
3630        self.spin = wx.SpinCtrl(pnl, wx.ID_ANY,size=(150,-1))
3631        self.spin.SetRange(1, curver)
3632        self.spin.SetValue(curver)
3633        self.Bind(wx.EVT_SPINCTRL, self._onSpin, self.spin)
3634        self.Bind(wx.EVT_KILL_FOCUS, self._onSpin, self.spin)
3635        sizer1.Add(self.spin)
3636        sizer.Add(sizer1)
3637
3638        line = wx.StaticLine(pnl,-1, size=(-1,3), style=wx.LI_HORIZONTAL)
3639        sizer.Add(line, 0, wx.EXPAND|wx.ALIGN_CENTER|wx.ALL, 10)
3640
3641        self.text = wx.StaticText(pnl,  wx.ID_ANY, "")
3642        sizer.Add(self.text, 0, wx.ALIGN_LEFT|wx.EXPAND|wx.ALL, 5)
3643
3644        line = wx.StaticLine(pnl,-1, size=(-1,3), style=wx.LI_HORIZONTAL)
3645        sizer.Add(line, 0, wx.EXPAND|wx.ALIGN_CENTER|wx.ALL, 10)
3646        sizer.Add(
3647            wx.StaticText(
3648                pnl,  wx.ID_ANY,
3649                'If "Install" is pressed, your project will be saved;\n'
3650                'GSAS-II will exit; The specified version will be loaded\n'
3651                'and GSAS-II will restart. Press "Cancel" to abort.'),
3652            0, wx.EXPAND|wx.ALL, 10)
3653        btnsizer = wx.StdDialogButtonSizer()
3654        btn = wx.Button(pnl, wx.ID_OK, "Install")
3655        btn.SetDefault()
3656        btnsizer.AddButton(btn)
3657        btn = wx.Button(pnl, wx.ID_CANCEL)
3658        btnsizer.AddButton(btn)
3659        btnsizer.Realize()
3660        sizer.Add(btnsizer, 0, wx.ALIGN_CENTER|wx.ALL, 5)
3661        pnl.SetSizer(sizer)
3662        sizer.Fit(self)
3663        self.topsizer=sizer
3664        self.CenterOnParent()
3665        self._onSpin(None)
3666
3667    def _onSpin(self,event):
3668        'Called to load info about the selected version in the dialog'
3669        ver = self.spin.GetValue()
3670        d = GSASIIpath.svnGetLog(version=ver)
3671        date = d.get('date','?').split('T')[0]
3672        s = '(Version '+str(ver)+' created '+date
3673        s += ' by '+d.get('author','?')+')'
3674        msg = d.get('msg')
3675        if msg: s += '\n\nComment: '+msg
3676        self.text.SetLabel(s)
3677        self.topsizer.Fit(self)
3678
3679    def getVersion(self):
3680        'Get the version number in the dialog'
3681        return self.spin.GetValue()
3682
3683################################################################################
3684#### Display Help information
3685################################################################################
3686# define some globals
3687htmlPanel = None
3688htmlFrame = None
3689htmlFirstUse = True
3690helpLocDict = {}
3691path2GSAS2 = os.path.dirname(os.path.realpath(__file__)) # save location of this file
3692def ShowHelp(helpType,frame):
3693    '''Called to bring up a web page for documentation.'''
3694    global htmlFirstUse
3695    # look up a definition for help info from dict
3696    helplink = helpLocDict.get(helpType)
3697    if helplink is None:
3698        # no defined link to use, create a default based on key
3699        helplink = 'gsasII.html#'+helpType.replace(' ','_')
3700    helplink = os.path.join(path2GSAS2,'help',helplink)
3701    # determine if a web browser or the internal viewer should be used for help info
3702    if GSASIIpath.GetConfigValue('Help_mode'):
3703        helpMode = GSASIIpath.GetConfigValue('Help_mode')
3704    else:
3705        helpMode = 'browser'
3706    if helpMode == 'internal':
3707        try:
3708            htmlPanel.LoadFile(helplink)
3709            htmlFrame.Raise()
3710        except:
3711            htmlFrame = wx.Frame(frame, -1, size=(610, 510))
3712            htmlFrame.Show(True)
3713            htmlFrame.SetTitle("HTML Window") # N.B. reset later in LoadFile
3714            htmlPanel = MyHtmlPanel(htmlFrame,-1)
3715            htmlPanel.LoadFile(helplink)
3716    else:
3717        pfx = "file://"
3718        if sys.platform.lower().startswith('win'):
3719            pfx = ''
3720        if htmlFirstUse:
3721            webbrowser.open_new(pfx+helplink)
3722            htmlFirstUse = False
3723        else:
3724            webbrowser.open(pfx+helplink, new=0, autoraise=True)
3725
3726def ShowWebPage(URL,frame):
3727    '''Called to show a tutorial web page.
3728    '''
3729    global htmlFirstUse
3730    # determine if a web browser or the internal viewer should be used for help info
3731    if GSASIIpath.GetConfigValue('Help_mode'):
3732        helpMode = GSASIIpath.GetConfigValue('Help_mode')
3733    else:
3734        helpMode = 'browser'
3735    if helpMode == 'internal':
3736        try:
3737            htmlPanel.LoadFile(URL)
3738            htmlFrame.Raise()
3739        except:
3740            htmlFrame = wx.Frame(frame, -1, size=(610, 510))
3741            htmlFrame.Show(True)
3742            htmlFrame.SetTitle("HTML Window") # N.B. reset later in LoadFile
3743            htmlPanel = MyHtmlPanel(htmlFrame,-1)
3744            htmlPanel.LoadFile(URL)
3745    else:
3746        if URL.startswith('http'): 
3747            pfx = ''
3748        elif sys.platform.lower().startswith('win'):
3749            pfx = ''
3750        else:
3751            pfx = "file://"
3752        if htmlFirstUse:
3753            webbrowser.open_new(pfx+URL)
3754            htmlFirstUse = False
3755        else:
3756            webbrowser.open(pfx+URL, new=0, autoraise=True)
3757
3758################################################################################
3759#### Tutorials support
3760################################################################################
3761G2BaseURL = "https://subversion.xray.aps.anl.gov/pyGSAS"
3762# N.B. tutorialCatalog is generated by routine catalog.py, which also generates the appropriate
3763# empty directories (.../MT/* .../trunk/GSASII/* *=[help,Exercises])
3764tutorialCatalog = (
3765    # tutorial dir,      exercise dir,      web page file name,      title for page
3766
3767    ['StartingGSASII', 'StartingGSASII', 'Starting GSAS.htm',
3768        'Starting GSAS-II'],
3769       
3770    ['FitPeaks', 'FitPeaks', 'Fit Peaks.htm',
3771        'Fitting individual peaks & autoindexing'],
3772    ['BkgFit', 'BkgFit', 'FitBkgTut.htm',
3773       'Fitting the Starting Background using Fixed Points'],
3774       
3775    ['CWNeutron', 'CWNeutron', 'Neutron CW Powder Data.htm',
3776        'CW Neutron Powder fit for Yttrium-Iron Garnet'],
3777    ['LabData', 'LabData', 'Laboratory X.htm',
3778        'Fitting laboratory X-ray powder data for fluoroapatite'],
3779    ['CWCombined', 'CWCombined', 'Combined refinement.htm',
3780        'Combined X-ray/CW-neutron refinement of PbSO4'],
3781    ['TOF-CW Joint Refinement', 'TOF-CW Joint Refinement', 'TOF combined XN Rietveld refinement in GSAS.htm',
3782        'Combined X-ray/TOF-neutron Rietveld refinement'],
3783    ['SeqRefine', 'SeqRefine', 'SequentialTutorial.htm',
3784        'Sequential refinement of multiple datasets'],
3785    ['SeqParametric', 'SeqParametric', 'ParametricFitting.htm',
3786        'Parametric Fitting and Pseudo Variables for Sequential Fits'],
3787       
3788    ['CFXraySingleCrystal','CFXraySingleCrystal','CFSingleCrystal.htm',
3789        'Charge Flipping structure solution with Xray single crystal data'],       
3790    ['CFjadarite', 'CFjadarite', 'Charge Flipping in GSAS.htm',
3791        'Charge Flipping structure solution for jadarite'],
3792    ['CFsucrose', 'CFsucrose', 'Charge Flipping - sucrose.htm',
3793        'Charge Flipping structure solution for sucrose'],
3794    ['TOF Charge Flipping', 'TOF Charge Flipping', 'Charge Flipping with TOF single crystal data in GSASII.htm',
3795        'Charge flipping with neutron TOF single crystal data'],
3796    ['MCsimanneal', 'MCsimanneal', 'MCSA in GSAS.htm',
3797        'Monte-Carlo simulated annealing structure'],
3798
3799    ['2DCalibration', '2DCalibration', 'Calibration of an area detector in GSAS.htm',
3800        'Calibration of an area detector'],
3801    ['2DIntegration', '2DIntegration', 'Integration of area detector data in GSAS.htm',
3802        'Integration of area detector data'],
3803    ['TOF Calibration', 'TOF Calibration', 'Calibration of a TOF powder diffractometer.htm',
3804        'Calibration of a Neutron TOF diffractometer'],
3805    ['TOF Single Crystal Refinement', 'TOF Single Crystal Refinement', 'TOF single crystal refinement in GSAS.htm',
3806        'Single crystal refinement from TOF data'],
3807       
3808    ['2DStrain', '2DStrain', 'Strain fitting of 2D data in GSAS-II.htm',
3809        'Strain fitting of 2D data'],
3810    ['2DTexture', '2DTexture', 'Texture analysis of 2D data in GSAS-II.htm',
3811        'Texture analysis of 2D data'],
3812             
3813    ['SAimages', 'SAimages', 'Small Angle Image Processing.htm',
3814        'Image Processing of small angle x-ray data'],
3815    ['SAfit', 'SAfit', 'Fitting Small Angle Scattering Data.htm',
3816        'Fitting small angle x-ray data (alumina powder)'],
3817    ['SAsize', 'SAsize', 'Small Angle Size Distribution.htm',
3818        'Small angle x-ray data size distribution (alumina powder)'],
3819    ['SAseqref', 'SAseqref', 'Sequential Refinement of Small Angle Scattering Data.htm',
3820        'Sequential refinement with small angle scattering data'],
3821   
3822    #['TOF Sequential Single Peak Fit', 'TOF Sequential Single Peak Fit', '', ''],
3823    )
3824if GSASIIpath.GetConfigValue('Tutorial_location'):
3825    tutorialPath = os.path.abspath(GSASIIpath.GetConfigValue('Tutorial_location'))
3826else:
3827    # pick a default directory in a logical place
3828    if sys.platform.lower().startswith('win') and os.path.exists(os.path.abspath(os.path.expanduser('~/My Documents'))):
3829        tutorialPath = os.path.abspath(os.path.expanduser('~/My Documents/G2tutorials'))
3830    else:
3831        tutorialPath = os.path.abspath(os.path.expanduser('~/G2tutorials'))
3832
3833class OpenTutorial(wx.Dialog):
3834    '''Open a tutorial, optionally copying it to the local disk. Always copy
3835    the data files locally.
3836
3837    For now tutorials will always be copied into the source code tree, but it
3838    might be better to have an option to copy them somewhere else, for people
3839    who don't have write access to the GSAS-II source code location.
3840    '''
3841    # TODO: set default input-file open location to the download location
3842    def __init__(self,parent=None):
3843        style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER
3844        wx.Dialog.__init__(self, parent, wx.ID_ANY, 'Open Tutorial', style=style)
3845        self.frame = parent
3846        pnl = wx.Panel(self)
3847        sizer = wx.BoxSizer(wx.VERTICAL)
3848        sizer1 = wx.BoxSizer(wx.HORIZONTAL)       
3849        label = wx.StaticText(
3850            pnl,  wx.ID_ANY,
3851            'Select the tutorial to be run and the mode of access'
3852            )
3853        msg = '''To save download time for GSAS-II tutorials and their
3854        sample data files are being moved out of the standard
3855        distribution. This dialog allows users to load selected
3856        tutorials to their computer.
3857
3858        Tutorials can be viewed over the internet or downloaded
3859        to this computer. The sample data can be downloaded or not,
3860        (but it is not possible to run the tutorial without the
3861        data). If no web access is available, tutorials that were
3862        previously downloaded can be viewed.
3863
3864        By default, files are downloaded into the location used
3865        for the GSAS-II distribution, but this may not be possible
3866        if the software is installed by a administrator. The
3867        download location can be changed using the "Set data
3868        location" or the "Tutorial_location" configuration option
3869        (see config_example.py).
3870        '''
3871        hlp = HelpButton(pnl,msg)
3872        sizer1.Add((-1,-1),1, wx.EXPAND, 0)
3873        sizer1.Add(label, 0, wx.ALIGN_CENTRE|wx.ALL, 0)
3874        sizer1.Add((-1,-1),1, wx.EXPAND, 0)
3875        sizer1.Add(hlp,0,wx.ALIGN_RIGHT|wx.ALL)
3876        sizer.Add(sizer1,0,wx.EXPAND|wx.ALL,0)
3877        sizer.Add((10,10))
3878        self.BrowseMode = 1
3879        choices = [
3880            'make local copy of tutorial and data, then open',
3881            'run from web (copy data locally)',
3882            'browse on web (data not loaded)', 
3883            'open from local tutorial copy',
3884        ]
3885        self.mode = wx.RadioBox(pnl,wx.ID_ANY,'access mode:',
3886                                wx.DefaultPosition, wx.DefaultSize,
3887                                choices, 1, wx.RA_SPECIFY_COLS)
3888        self.mode.SetSelection(self.BrowseMode)
3889        self.mode.Bind(wx.EVT_RADIOBOX, self.OnModeSelect)
3890        sizer.Add(self.mode,0,WACV)
3891        sizer.Add((10,10))
3892        label = wx.StaticText(pnl,  wx.ID_ANY,'Click on tutorial to be opened:')
3893        sizer.Add(label, 0, wx.ALIGN_LEFT|wx.ALL, 2)
3894        self.listbox = wx.ListBox(pnl, wx.ID_ANY, size=(450, 100), style=wx.LB_SINGLE)
3895        self.listbox.Bind(wx.EVT_LISTBOX, self.OnTutorialSelected)
3896        sizer.Add(self.listbox,1,WACV|wx.EXPAND|wx.ALL,1)
3897        sizer.Add((10,10))
3898        sizer1 = wx.BoxSizer(wx.HORIZONTAL)
3899        btn = wx.Button(pnl, wx.ID_ANY, "Set download location")
3900        btn.Bind(wx.EVT_BUTTON, self.SelectDownloadLoc)
3901        sizer1.Add(btn,0,WACV)
3902        self.dataLoc = wx.StaticText(pnl, wx.ID_ANY,tutorialPath)
3903        sizer1.Add(self.dataLoc,0,WACV)
3904        sizer.Add(sizer1)
3905        label = wx.StaticText(
3906            pnl,  wx.ID_ANY,
3907            'Tutorials and Exercise files will be downloaded to:'
3908            )
3909        sizer.Add(label, 0, wx.ALIGN_LEFT|wx.ALL, 1)
3910        self.TutorialLabel = wx.StaticText(pnl,wx.ID_ANY,'')
3911        sizer.Add(self.TutorialLabel, 0, wx.ALIGN_LEFT|wx.EXPAND, 5)
3912        self.ExerciseLabel = wx.StaticText(pnl,wx.ID_ANY,'')
3913        sizer.Add(self.ExerciseLabel, 0, wx.ALIGN_LEFT|wx.EXPAND, 5)
3914        self.ShowTutorialPath()
3915        self.OnModeSelect(None)
3916       
3917        btnsizer = wx.StdDialogButtonSizer()
3918        btn = wx.Button(pnl, wx.ID_CANCEL)
3919        btnsizer.AddButton(btn)
3920        btnsizer.Realize()
3921        sizer.Add(btnsizer, 0, wx.ALIGN_CENTER|wx.ALL, 5)
3922        pnl.SetSizer(sizer)
3923        sizer.Fit(self)
3924        self.topsizer=sizer
3925        self.CenterOnParent()
3926    # def OpenOld(self,event):
3927    #     '''Open old tutorials. This is needed only until we get all the tutorials items moved
3928    #     '''
3929    #     self.EndModal(wx.ID_OK)
3930    #     ShowHelp('Tutorials',self.frame)
3931    def OnModeSelect(self,event):
3932        '''Respond when the mode is changed
3933        '''
3934        self.BrowseMode = self.mode.GetSelection()
3935        if self.BrowseMode == 3:
3936            import glob
3937            filelist = glob.glob(os.path.join(tutorialPath,'help','*','*.htm'))
3938            taillist = [os.path.split(f)[1] for f in filelist]
3939            itemlist = [tut[-1] for tut in tutorialCatalog if tut[2] in taillist]
3940        else:
3941            itemlist = [tut[-1] for tut in tutorialCatalog if tut[-1]]
3942        self.listbox.Clear()
3943        self.listbox.AppendItems(itemlist)
3944    def OnTutorialSelected(self,event):
3945        '''Respond when a tutorial is selected. Load tutorials and data locally,
3946        as needed and then display the page
3947        '''
3948        for tutdir,exedir,htmlname,title in tutorialCatalog:
3949            if title == event.GetString(): break
3950        else:
3951            raise Exception("Match to file not found")
3952        if self.BrowseMode == 0 or self.BrowseMode == 1:
3953            try: 
3954                self.ValidateTutorialDir(tutorialPath,G2BaseURL)
3955            except:
3956                G2MessageBox(self.frame,
3957            '''The selected directory is not valid.
3958           
3959            You must use a directory that you have write access
3960            to. You can reuse a directory previously used for
3961            downloads, but the help and Tutorials subdirectories
3962             must be created by this routine.
3963            ''')
3964                return
3965        #self.dataLoc.SetLabel(tutorialPath)
3966        self.EndModal(wx.ID_OK)
3967        wx.BeginBusyCursor()
3968        if self.BrowseMode == 0:
3969            # xfer data & web page locally, then open web page
3970            self.LoadTutorial(tutdir,tutorialPath,G2BaseURL)
3971            self.LoadExercise(exedir,tutorialPath,G2BaseURL)
3972            URL = os.path.join(tutorialPath,'help',tutdir,htmlname)
3973            self.frame.TutorialImportDir = os.path.join(tutorialPath,'Exercises',exedir)
3974            ShowWebPage(URL,self.frame)
3975        elif self.BrowseMode == 1:
3976            # xfer data locally, open web page remotely
3977            self.LoadExercise(exedir,tutorialPath,G2BaseURL)
3978            URL = os.path.join(G2BaseURL,'Tutorials',tutdir,htmlname)
3979            self.frame.TutorialImportDir = os.path.join(tutorialPath,'Exercises',exedir)
3980            ShowWebPage(URL,self.frame)
3981        elif self.BrowseMode == 2:
3982            # open web page remotely, don't worry about data
3983            URL = os.path.join(G2BaseURL,'Tutorials',tutdir,htmlname)
3984            ShowWebPage(URL,self.frame)
3985        elif self.BrowseMode == 3:
3986            # open web page that has already been transferred
3987            URL = os.path.join(tutorialPath,'help',tutdir,htmlname)
3988            self.frame.TutorialImportDir = os.path.join(tutorialPath,'Exercises',exedir)
3989            ShowWebPage(URL,self.frame)
3990        else:
3991            wx.EndBusyCursor()
3992            raise Exception("How did this happen!")
3993        wx.EndBusyCursor()
3994    def ShowTutorialPath(self):
3995        'Show the help and exercise directory names'
3996        self.TutorialLabel.SetLabel('\t'+
3997                                    os.path.join(tutorialPath,"help") +
3998                                    ' (tutorials)')
3999        self.ExerciseLabel.SetLabel('\t'+
4000                                    os.path.join(tutorialPath,"Exercises") +
4001                                    ' (exercises)')
4002    def ValidateTutorialDir(self,fullpath=tutorialPath,baseURL=G2BaseURL):
4003        '''Load help to new directory or make sure existing directory looks correctly set up
4004        throws an exception if there is a problem.
4005        '''
4006        wx.BeginBusyCursor()
4007        wx.Yield()
4008        if os.path.exists(fullpath):
4009            if os.path.exists(os.path.join(fullpath,"help")):
4010                if not GSASIIpath.svnGetRev(os.path.join(fullpath,"help")):
4011                    print("Problem with "+fullpath+" dir help exists but is not in SVN")
4012                    wx.EndBusyCursor()
4013                    raise Exception
4014            if os.path.exists(os.path.join(fullpath,"Exercises")):
4015                if not GSASIIpath.svnGetRev(os.path.join(fullpath,"Exercises")):
4016                    print("Problem with "+fullpath+" dir Exercises exists but is not in SVN")
4017                    wx.EndBusyCursor()
4018                    raise Exception
4019            if (os.path.exists(os.path.join(fullpath,"help")) and
4020                    os.path.exists(os.path.join(fullpath,"Exercises"))):
4021                if self.BrowseMode != 3:
4022                    print('Checking for directory updates')
4023                    GSASIIpath.svnUpdateDir(os.path.join(fullpath,"help"))
4024                    GSASIIpath.svnUpdateDir(os.path.join(fullpath,"Exercises"))
4025                wx.EndBusyCursor()
4026                return True # both good
4027            elif (os.path.exists(os.path.join(fullpath,"help")) or
4028                    os.path.exists(os.path.join(fullpath,"Exercises"))):
4029                print("Problem: dir "+fullpath+" exists has either help or Exercises, not both")
4030                wx.EndBusyCursor()
4031                raise Exception
4032        if not GSASIIpath.svnInstallDir(baseURL+"/MT",fullpath):
4033            wx.EndBusyCursor()
4034            print("Problem transferring empty directory from web")
4035            raise Exception
4036        wx.EndBusyCursor()
4037        return True
4038
4039    def LoadTutorial(self,tutorialname,fullpath=tutorialPath,baseURL=G2BaseURL):
4040        'Load a Tutorial to the selected location'
4041        if GSASIIpath.svnSwitchDir("help",tutorialname,baseURL+"/Tutorials",fullpath):
4042            return True
4043        print("Problem transferring Tutorial from web")
4044        raise Exception
4045       
4046    def LoadExercise(self,tutorialname,fullpath=tutorialPath,baseURL=G2BaseURL):
4047        'Load Exercise file(s) for a Tutorial to the selected location'
4048        if GSASIIpath.svnSwitchDir("Exercises",tutorialname,baseURL+"/Exercises",fullpath):
4049            return True
4050        print ("Problem transferring Exercise from web")
4051        raise Exception
4052       
4053    def SelectDownloadLoc(self,event):
4054        '''Select a download location,
4055        Cancel resets to the default
4056        '''
4057        global tutorialPath
4058        dlg = wx.DirDialog(self, "Choose a directory for downloads:",
4059                           defaultPath=tutorialPath)#,style=wx.DD_DEFAULT_STYLE)
4060                           #)
4061        try:
4062            if dlg.ShowModal() != wx.ID_OK:
4063                return
4064            pth = dlg.GetPath()
4065        finally:
4066            dlg.Destroy()
4067
4068        if not os.path.exists(pth):
4069            try:
4070                os.makedirs(pth)
4071            except OSError:
4072                msg = 'The selected directory is not valid.\n\t'
4073                msg += pth
4074                msg += '\n\nAn attempt to create the directory failed'
4075                G2MessageBox(self.frame,msg)
4076                return
4077        try:
4078            self.ValidateTutorialDir(pth,G2BaseURL)
4079            tutorialPath = pth
4080        except:
4081            G2MessageBox(self.frame,
4082            '''Error downloading to the selected directory
4083
4084            Are you connected to the internet? If not, you can
4085            only view previously downloaded tutorials (select
4086            "open from local...")
4087           
4088            You must use a directory that you have write access
4089            to. You can reuse a directory previously used for
4090            downloads, but the help and Tutorials subdirectories
4091            must have been created by this routine.
4092            ''')
4093        self.dataLoc.SetLabel(tutorialPath)
4094        self.ShowTutorialPath()
4095        self.OnModeSelect(None)
4096   
4097if __name__ == '__main__':
4098    app = wx.PySimpleApp()
4099    GSASIIpath.InvokeDebugOpts()
4100    frm = wx.Frame(None) # create a frame
4101    frm.Show(True)
4102    #dlg = OpenTutorial(frm)
4103    #if dlg.ShowModal() == wx.ID_OK:
4104    #    print "OK"
4105    #else:
4106    #    print "Cancel"
4107    #dlg.Destroy()
4108    #import sys
4109    #sys.exit()
4110    #======================================================================
4111    # test ScrolledMultiEditor
4112    #======================================================================
4113    # Data1 = {
4114    #      'Order':1,
4115    #      'omega':'string',
4116    #      'chi':2.0,
4117    #      'phi':'',
4118    #      }
4119    # elemlst = sorted(Data1.keys())
4120    # prelbl = sorted(Data1.keys())
4121    # dictlst = len(elemlst)*[Data1,]
4122    #Data2 = [True,False,False,True]
4123    #Checkdictlst = len(Data2)*[Data2,]
4124    #Checkelemlst = range(len(Checkdictlst))
4125    # print 'before',Data1,'\n',Data2
4126    # dlg = ScrolledMultiEditor(
4127    #     frm,dictlst,elemlst,prelbl,
4128    #     checkdictlst=Checkdictlst,checkelemlst=Checkelemlst,
4129    #     checklabel="Refine?",
4130    #     header="test")
4131    # if dlg.ShowModal() == wx.ID_OK:
4132    #     print "OK"
4133    # else:
4134    #     print "Cancel"
4135    # print 'after',Data1,'\n',Data2
4136    # dlg.Destroy()
4137    Data3 = {
4138         'Order':1.0,
4139         'omega':1.1,
4140         'chi':2.0,
4141         'phi':2.3,
4142         'Order1':1.0,
4143         'omega1':1.1,
4144         'chi1':2.0,
4145         'phi1':2.3,
4146         'Order2':1.0,
4147         'omega2':1.1,
4148         'chi2':2.0,
4149         'phi2':2.3,
4150         }
4151    elemlst = sorted(Data3.keys())
4152    dictlst = len(elemlst)*[Data3,]
4153    prelbl = elemlst[:]
4154    prelbl[0]="this is a much longer label to stretch things out"
4155    Data2 = len(elemlst)*[False,]
4156    Data2[1] = Data2[3] = True
4157    Checkdictlst = len(elemlst)*[Data2,]
4158    Checkelemlst = range(len(Checkdictlst))
4159    #print 'before',Data3,'\n',Data2
4160    #print dictlst,"\n",elemlst
4161    #print Checkdictlst,"\n",Checkelemlst
4162    # dlg = ScrolledMultiEditor(
4163    #     frm,dictlst,elemlst,prelbl,
4164    #     checkdictlst=Checkdictlst,checkelemlst=Checkelemlst,
4165    #     checklabel="Refine?",
4166    #     header="test",CopyButton=True)
4167    # if dlg.ShowModal() == wx.ID_OK:
4168    #     print "OK"
4169    # else:
4170    #     print "Cancel"
4171    #print 'after',Data3,'\n',Data2
4172
4173    # Data2 = list(range(100))
4174    # elemlst += range(2,6)
4175    # postlbl += range(2,6)
4176    # dictlst += len(range(2,6))*[Data2,]
4177
4178    # prelbl = range(len(elemlst))
4179    # postlbl[1] = "a very long label for the 2nd item to force a horiz. scrollbar"
4180    # header="""This is a longer\nmultiline and perhaps silly header"""
4181    # dlg = ScrolledMultiEditor(frm,dictlst,elemlst,prelbl,postlbl,
4182    #                           header=header,CopyButton=True)
4183    # print Data1
4184    # if dlg.ShowModal() == wx.ID_OK:
4185    #     for d,k in zip(dictlst,elemlst):
4186    #         print k,d[k]
4187    # dlg.Destroy()
4188    # if CallScrolledMultiEditor(frm,dictlst,elemlst,prelbl,postlbl,
4189    #                            header=header):
4190    #     for d,k in zip(dictlst,elemlst):
4191    #         print k,d[k]
4192
4193    #======================================================================
4194    # test G2MultiChoiceDialog
4195    #======================================================================
4196    choices = []
4197    for i in range(21):
4198        choices.append("option_"+str(i))
4199    dlg = G2MultiChoiceDialog(frm, 'Sequential refinement',
4200                              'Select dataset to include',
4201                              choices)
4202    sel = range(2,11,2)
4203    dlg.SetSelections(sel)
4204    dlg.SetSelections((1,5))
4205    if dlg.ShowModal() == wx.ID_OK:
4206        for sel in dlg.GetSelections():
4207            print sel,choices[sel]
4208   
4209    #======================================================================
4210    # test wx.MultiChoiceDialog
4211    #======================================================================
4212    # dlg = wx.MultiChoiceDialog(frm, 'Sequential refinement',
4213    #                           'Select dataset to include',
4214    #                           choices)
4215    # sel = range(2,11,2)
4216    # dlg.SetSelections(sel)
4217    # dlg.SetSelections((1,5))
4218    # if dlg.ShowModal() == wx.ID_OK:
4219    #     for sel in dlg.GetSelections():
4220    #         print sel,choices[sel]
4221
4222    # pnl = wx.Panel(frm)
4223    # siz = wx.BoxSizer(wx.VERTICAL)
4224
4225    # td = {'Goni':200.,'a':1.,'calc':1./3.,'string':'s'}
4226    # for key in sorted(td):
4227    #     txt = ValidatedTxtCtrl(pnl,td,key)
4228    #     siz.Add(txt)
4229    # pnl.SetSizer(siz)
4230    # siz.Fit(frm)
4231    # app.MainLoop()
4232    # print td
Note: See TracBrowser for help on using the repository browser.