source: trunk/GSASIIctrls.py @ 1657

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

migrate help from G2grid; set instparms in Powder imports; seach for imports in data path; start on tutorial migration

  • Property svn:eol-style set to native
File size: 82.5 KB
Line 
1# -*- coding: utf-8 -*-
2#GSASIIctrls - Custom GSAS-II GUI controls
3########### SVN repository information ###################
4# $Date: $
5# $Author: $
6# $Revision: $
7# $URL: $
8# $Id: $
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 wx
20# import wx.grid as wg
21# import wx.wizard as wz
22# import wx.aui
23import wx.lib.scrolledpanel as wxscroll
24import time
25import copy
26# import cPickle
27import sys
28import os
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: 1614 $")
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        log.LogInfo['Tree'] = self
78
79    def _getTreeItemsList(self,item):
80        '''Get the full tree hierarchy from a reference to a tree item.
81        Note that this effectively hard-codes phase and histogram names in the
82        returned list. We may want to make these names relative in the future.
83        '''
84        textlist = [self.GetItemText(item)]
85        parent = self.GetItemParent(item)
86        while parent:
87            if parent == self.root: break
88            textlist.insert(0,self.GetItemText(parent))
89            parent = self.GetItemParent(parent)
90        return textlist
91
92    def onSelectionChanged(self,event):
93        '''Log each press on a tree item here.
94        '''
95        if self.SelectionChanged:
96            textlist = self._getTreeItemsList(event.GetItem())
97            if log.LogInfo['Logging'] and event.GetItem() != self.root:
98                textlist[0] = self.GetRelativeHistNum(textlist[0])
99                if textlist[0] == "Phases" and len(textlist) > 1:
100                    textlist[1] = self.GetRelativePhaseNum(textlist[1])
101                log.MakeTreeLog(textlist)
102            self.SelectionChanged(event)
103
104    def Bind(self,eventtype,handler,*args,**kwargs):
105        '''Override the Bind() function so that page change events can be trapped
106        '''
107        if eventtype == wx.EVT_TREE_SEL_CHANGED:
108            self.SelectionChanged = handler
109            wx.TreeCtrl.Bind(self,eventtype,self.onSelectionChanged)
110            return
111        wx.TreeCtrl.Bind(self,eventtype,handler,*args,**kwargs)
112
113    # commented out, disables Logging
114    # def GetItemPyData(self,*args,**kwargs):
115    #    '''Override the standard method to wrap the contents
116    #    so that the source can be logged when changed
117    #    '''
118    #    data = super(self.__class__,self).GetItemPyData(*args,**kwargs)
119    #    textlist = self._getTreeItemsList(args[0])
120    #    if type(data) is dict:
121    #        return log.dictLogged(data,textlist)
122    #    if type(data) is list:
123    #        return log.listLogged(data,textlist)
124    #    if type(data) is tuple: #N.B. tuples get converted to lists
125    #        return log.listLogged(list(data),textlist)
126    #    return data
127
128    def GetRelativeHistNum(self,histname):
129        '''Returns list with a histogram type and a relative number for that
130        histogram, or the original string if not a histogram
131        '''
132        histtype = histname.split()[0]
133        if histtype != histtype.upper(): # histograms (only) have a keyword all in caps
134            return histname
135        item, cookie = self.GetFirstChild(self.root)
136        i = 0
137        while item:
138            itemtext = self.GetItemText(item)
139            if itemtext == histname:
140                return histtype,i
141            elif itemtext.split()[0] == histtype:
142                i += 1
143            item, cookie = self.GetNextChild(self.root, cookie)
144        else:
145            raise Exception("Histogram not found: "+histname)
146
147    def ConvertRelativeHistNum(self,histtype,histnum):
148        '''Converts a histogram type and relative histogram number to a
149        histogram name in the current project
150        '''
151        item, cookie = self.GetFirstChild(self.root)
152        i = 0
153        while item:
154            itemtext = self.GetItemText(item)
155            if itemtext.split()[0] == histtype:
156                if i == histnum: return itemtext
157                i += 1
158            item, cookie = self.GetNextChild(self.root, cookie)
159        else:
160            raise Exception("Histogram #'+str(histnum)+' of type "+histtype+' not found')
161       
162    def GetRelativePhaseNum(self,phasename):
163        '''Returns a phase number if the string matches a phase name
164        or else returns the original string
165        '''
166        item, cookie = self.GetFirstChild(self.root)
167        while item:
168            itemtext = self.GetItemText(item)
169            if itemtext == "Phases":
170                parent = item
171                item, cookie = self.GetFirstChild(parent)
172                i = 0
173                while item:
174                    itemtext = self.GetItemText(item)
175                    if itemtext == phasename:
176                        return i
177                    item, cookie = self.GetNextChild(parent, cookie)
178                    i += 1
179                else:
180                    return phasename # not a phase name
181            item, cookie = self.GetNextChild(self.root, cookie)
182        else:
183            raise Exception("No phases found ")
184
185    def ConvertRelativePhaseNum(self,phasenum):
186        '''Converts relative phase number to a phase name in
187        the current project
188        '''
189        item, cookie = self.GetFirstChild(self.root)
190        while item:
191            itemtext = self.GetItemText(item)
192            if itemtext == "Phases":
193                parent = item
194                item, cookie = self.GetFirstChild(parent)
195                i = 0
196                while item:
197                    if i == phasenum:
198                        return self.GetItemText(item)
199                    item, cookie = self.GetNextChild(parent, cookie)
200                    i += 1
201                else:
202                    raise Exception("Phase "+str(phasenum)+" not found")
203            item, cookie = self.GetNextChild(self.root, cookie)
204        else:
205            raise Exception("No phases found ")
206
207################################################################################
208#### TextCtrl that stores input as entered with optional validation
209################################################################################
210class ValidatedTxtCtrl(wx.TextCtrl):
211    '''Create a TextCtrl widget that uses a validator to prevent the
212    entry of inappropriate characters and changes color to highlight
213    when invalid input is supplied. As valid values are typed,
214    they are placed into the dict or list where the initial value
215    came from. The type of the initial value must be int,
216    float or str or None (see :obj:`key` and :obj:`typeHint`);
217    this type (or the one in :obj:`typeHint`) is preserved.
218
219    Float values can be entered in the TextCtrl as numbers or also
220    as algebraic expressions using operators + - / \* () and \*\*,
221    in addition pi, sind(), cosd(), tand(), and sqrt() can be used,
222    as well as appreviations s, sin, c, cos, t, tan and sq.
223
224    :param wx.Panel parent: name of panel or frame that will be
225      the parent to the TextCtrl. Can be None.
226
227    :param dict/list loc: the dict or list with the initial value to be
228      placed in the TextCtrl.
229
230    :param int/str key: the dict key or the list index for the value to be
231      edited by the TextCtrl. The ``loc[key]`` element must exist, but may
232      have value None. If None, the type for the element is taken from
233      :obj:`typeHint` and the value for the control is set initially
234      blank (and thus invalid.) This is a way to specify a field without a
235      default value: a user must set a valid value.
236      If the value is not None, it must have a base
237      type of int, float, str or unicode; the TextCrtl will be initialized
238      from this value.
239     
240    :param list nDig: number of digits & places ([nDig,nPlc]) after decimal to use
241      for display of float. Alternately, None can be specified which causes
242      numbers to be displayed with approximately 5 significant figures
243      (Default=None).
244
245    :param bool notBlank: if True (default) blank values are invalid
246      for str inputs.
247     
248    :param number min: minimum allowed valid value. If None (default) the
249      lower limit is unbounded.
250
251    :param number max: maximum allowed valid value. If None (default) the
252      upper limit is unbounded
253
254    :param function OKcontrol: specifies a function or method that will be
255      called when the input is validated. The called function is supplied
256      with one argument which is False if the TextCtrl contains an invalid
257      value and True if the value is valid.
258      Note that this function should check all values
259      in the dialog when True, since other entries might be invalid.
260      The default for this is None, which indicates no function should
261      be called.
262
263    :param function OnLeave: specifies a function or method that will be
264      called when the focus for the control is lost.
265      The called function is supplied with (at present) three keyword arguments:
266
267         * invalid: (*bool*) True if the value for the TextCtrl is invalid
268         * value:   (*int/float/str*)  the value contained in the TextCtrl
269         * tc:      (*wx.TextCtrl*)  the TextCtrl name
270
271      The number of keyword arguments may be increased in the future should needs arise,
272      so it is best to code these functions with a \*\*kwargs argument so they will
273      continue to run without errors
274
275      The default for OnLeave is None, which indicates no function should
276      be called.
277
278    :param type typeHint: the value of typeHint is overrides the initial value
279      for the dict/list element ``loc[key]``, if set to
280      int or float, which specifies the type for input to the TextCtrl.
281      Defaults as None, which is ignored.
282
283    :param bool CIFinput: for str input, indicates that only printable
284      ASCII characters may be entered into the TextCtrl. Forces output
285      to be ASCII rather than Unicode. For float and int input, allows
286      use of a single '?' or '.' character as valid input.
287
288    :param dict OnLeaveArgs: a dict with keyword args that are passed to
289      the :attr:`OnLeave` function. Defaults to ``{}``
290
291    :param (other): other optional keyword parameters for the
292      wx.TextCtrl widget such as size or style may be specified.
293
294    '''
295    def __init__(self,parent,loc,key,nDig=None,notBlank=True,min=None,max=None,
296                 OKcontrol=None,OnLeave=None,typeHint=None,
297                 CIFinput=False, OnLeaveArgs={}, **kw):
298        # save passed values needed outside __init__
299        self.result = loc
300        self.key = key
301        self.nDig = nDig
302        self.OKcontrol=OKcontrol
303        self.OnLeave = OnLeave
304        self.OnLeaveArgs = OnLeaveArgs
305        self.CIFinput = CIFinput
306        self.type = str
307        # initialization
308        self.invalid = False   # indicates if the control has invalid contents
309        self.evaluated = False # set to True when the validator recognizes an expression
310        val = loc[key]
311        if isinstance(val,int) or typeHint is int:
312            self.type = int
313            wx.TextCtrl.__init__(
314                self,parent,wx.ID_ANY,
315                validator=NumberValidator(int,result=loc,key=key,
316                                          min=min,max=max,
317                                          OKcontrol=OKcontrol,
318                                          CIFinput=CIFinput),
319                **kw)
320            if val is not None:
321                self._setValue(val)
322            else: # no default is invalid for a number
323                self.invalid = True
324                self._IndicateValidity()
325
326        elif isinstance(val,float) or typeHint is float:
327            self.type = float
328            wx.TextCtrl.__init__(
329                self,parent,wx.ID_ANY,
330                validator=NumberValidator(float,result=loc,key=key,
331                                          min=min,max=max,
332                                          OKcontrol=OKcontrol,
333                                          CIFinput=CIFinput),
334                **kw)
335            if val is not None:
336                self._setValue(val)
337            else:
338                self.invalid = True
339                self._IndicateValidity()
340
341        elif isinstance(val,str) or isinstance(val,unicode):
342            if self.CIFinput:
343                wx.TextCtrl.__init__(
344                    self,parent,wx.ID_ANY,val,
345                    validator=ASCIIValidator(result=loc,key=key),
346                    **kw)
347            else:
348                wx.TextCtrl.__init__(self,parent,wx.ID_ANY,val,**kw)
349            if notBlank:
350                self.Bind(wx.EVT_CHAR,self._onStringKey)
351                self.ShowStringValidity() # test if valid input
352            else:
353                self.invalid = False
354                self.Bind(wx.EVT_CHAR,self._GetStringValue)
355        elif val is None:
356            raise Exception,("ValidatedTxtCtrl error: value of "+str(key)+
357                             " element is None and typeHint not defined as int or float")
358        else:
359            raise Exception,("ValidatedTxtCtrl error: Unknown element ("+str(key)+
360                             ") type: "+str(type(val)))
361        # When the mouse is moved away or the widget loses focus,
362        # display the last saved value, if an expression
363        #self.Bind(wx.EVT_LEAVE_WINDOW, self._onLeaveWindow)
364        self.Bind(wx.EVT_TEXT_ENTER, self._onLoseFocus)
365        self.Bind(wx.EVT_KILL_FOCUS, self._onLoseFocus)
366        # patch for wx 2.9 on Mac
367        i,j= wx.__version__.split('.')[0:2]
368        if int(i)+int(j)/10. > 2.8 and 'wxOSX' in wx.PlatformInfo:
369            self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
370
371    def SetValue(self,val):
372        if self.result is not None: # note that this bypasses formatting
373            self.result[self.key] = val
374            log.LogVarChange(self.result,self.key)
375        self._setValue(val)
376
377    def _setValue(self,val):
378        self.invalid = False
379        if self.type is int:
380            try:
381                if int(val) != val:
382                    self.invalid = True
383                else:
384                    val = int(val)
385            except:
386                if self.CIFinput and (val == '?' or val == '.'):
387                    pass
388                else:
389                    self.invalid = True
390            wx.TextCtrl.SetValue(self,str(val))
391        elif self.type is float:
392            try:
393                val = float(val) # convert strings, if needed
394            except:
395                if self.CIFinput and (val == '?' or val == '.'):
396                    pass
397                else:
398                    self.invalid = True
399            if self.nDig:
400                wx.TextCtrl.SetValue(self,str(G2py3.FormatValue(val,self.nDig)))
401            else:
402                wx.TextCtrl.SetValue(self,str(G2py3.FormatSigFigs(val)).rstrip('0'))
403        else:
404            wx.TextCtrl.SetValue(self,str(val))
405            self.ShowStringValidity() # test if valid input
406            return
407       
408        self._IndicateValidity()
409        if self.OKcontrol:
410            self.OKcontrol(not self.invalid)
411
412    def OnKeyDown(self,event):
413        'Special callback for wx 2.9+ on Mac where backspace is not processed by validator'
414        key = event.GetKeyCode()
415        if key in [wx.WXK_BACK, wx.WXK_DELETE]:
416            if self.Validator: wx.CallAfter(self.Validator.TestValid,self)
417        if key == wx.WXK_RETURN:
418            self._onLoseFocus(None)
419        event.Skip()
420                   
421    def _onStringKey(self,event):
422        event.Skip()
423        if self.invalid: # check for validity after processing the keystroke
424            wx.CallAfter(self.ShowStringValidity,True) # was invalid
425        else:
426            wx.CallAfter(self.ShowStringValidity,False) # was valid
427
428    def _IndicateValidity(self):
429        'Set the control colors to show invalid input'
430        if self.invalid:
431            self.SetForegroundColour("red")
432            self.SetBackgroundColour("yellow")
433            self.SetFocus()
434            self.Refresh()
435        else: # valid input
436            self.SetBackgroundColour(
437                wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW))
438            self.SetForegroundColour("black")
439            self.Refresh()
440
441    def ShowStringValidity(self,previousInvalid=True):
442        '''Check if input is valid. Anytime the input is
443        invalid, call self.OKcontrol (if defined) because it is fast.
444        If valid, check for any other invalid entries only when
445        changing from invalid to valid, since that is slower.
446       
447        :param bool previousInvalid: True if the TextCtrl contents were
448          invalid prior to the current change.
449         
450        '''
451        val = self.GetValue().strip()
452        self.invalid = not val
453        self._IndicateValidity()
454        if self.invalid:
455            if self.OKcontrol:
456                self.OKcontrol(False)
457        elif self.OKcontrol and previousInvalid:
458            self.OKcontrol(True)
459        # always store the result
460        if self.CIFinput: # for CIF make results ASCII
461            self.result[self.key] = val.encode('ascii','replace') 
462        else:
463            self.result[self.key] = val
464        log.LogVarChange(self.result,self.key)
465
466    def _GetStringValue(self,event):
467        '''Get string input and store.
468        '''
469        event.Skip() # process keystroke
470        wx.CallAfter(self._SaveStringValue)
471       
472    def _SaveStringValue(self):
473        val = self.GetValue().strip()
474        # always store the result
475        if self.CIFinput: # for CIF make results ASCII
476            self.result[self.key] = val.encode('ascii','replace') 
477        else:
478            self.result[self.key] = val
479        log.LogVarChange(self.result,self.key)
480
481    def _onLoseFocus(self,event):
482        if self.evaluated:
483            self.EvaluateExpression()
484        elif self.result is not None: # show formatted result, as Bob wants
485            self._setValue(self.result[self.key])
486        if self.OnLeave: self.OnLeave(invalid=self.invalid,
487                                      value=self.result[self.key],
488                                      tc=self,
489                                      **self.OnLeaveArgs)
490        if event: event.Skip()
491
492    def EvaluateExpression(self):
493        '''Show the computed value when an expression is entered to the TextCtrl
494        Make sure that the number fits by truncating decimal places and switching
495        to scientific notation, as needed.
496        Called on loss of focus, enter, etc..
497        '''
498        if self.invalid: return # don't substitute for an invalid expression
499        if not self.evaluated: return # true when an expression is evaluated
500        if self.result is not None: # retrieve the stored result
501            self._setValue(self.result[self.key])
502        self.evaluated = False # expression has been recast as value, reset flag
503       
504class NumberValidator(wx.PyValidator):
505    '''A validator to be used with a TextCtrl to prevent
506    entering characters other than digits, signs, and for float
507    input, a period and exponents.
508   
509    The value is checked for validity after every keystroke
510      If an invalid number is entered, the box is highlighted.
511      If the number is valid, it is saved in result[key]
512
513    :param type typ: the base data type. Must be int or float.
514
515    :param bool positiveonly: If True, negative integers are not allowed
516      (default False). This prevents the + or - keys from being pressed.
517      Used with typ=int; ignored for typ=float.
518
519    :param number min: Minimum allowed value. If None (default) the
520      lower limit is unbounded
521
522    :param number max: Maximum allowed value. If None (default) the
523      upper limit is unbounded
524     
525    :param dict/list result: List or dict where value should be placed when valid
526
527    :param any key: key to use for result (int for list)
528
529    :param function OKcontrol: function or class method to control
530      an OK button for a window.
531      Ignored if None (default)
532
533    :param bool CIFinput: allows use of a single '?' or '.' character
534      as valid input.
535     
536    '''
537    def __init__(self, typ, positiveonly=False, min=None, max=None,
538                 result=None, key=None, OKcontrol=None, CIFinput=False):
539        'Create the validator'
540        wx.PyValidator.__init__(self)
541        # save passed parameters
542        self.typ = typ
543        self.positiveonly = positiveonly
544        self.min = min
545        self.max = max
546        self.result = result
547        self.key = key
548        self.OKcontrol = OKcontrol
549        self.CIFinput = CIFinput
550        # set allowed keys by data type
551        self.Bind(wx.EVT_CHAR, self.OnChar)
552        if self.typ == int and self.positiveonly:
553            self.validchars = '0123456789'
554        elif self.typ == int:
555            self.validchars = '0123456789+-'
556        elif self.typ == float:
557            # allow for above and sind, cosd, sqrt, tand, pi, and abbreviations
558            # also addition, subtraction, division, multiplication, exponentiation
559            self.validchars = '0123456789.-+eE/cosindcqrtap()*'
560        else:
561            self.validchars = None
562            return
563        if self.CIFinput:
564            self.validchars += '?.'
565    def Clone(self):
566        'Create a copy of the validator, a strange, but required component'
567        return NumberValidator(typ=self.typ, 
568                               positiveonly=self.positiveonly,
569                               min=self.min, max=self.max,
570                               result=self.result, key=self.key,
571                               OKcontrol=self.OKcontrol,
572                               CIFinput=self.CIFinput)
573    def TransferToWindow(self):
574        'Needed by validator, strange, but required component'
575        return True # Prevent wxDialog from complaining.
576    def TransferFromWindow(self):
577        'Needed by validator, strange, but required component'
578        return True # Prevent wxDialog from complaining.
579    def TestValid(self,tc):
580        '''Check if the value is valid by casting the input string
581        into the current type.
582
583        Set the invalid variable in the TextCtrl object accordingly.
584
585        If the value is valid, save it in the dict/list where
586        the initial value was stored, if appropriate.
587
588        :param wx.TextCtrl tc: A reference to the TextCtrl that the validator
589          is associated with.
590        '''
591        tc.invalid = False # assume valid
592        if self.CIFinput:
593            val = tc.GetValue().strip()
594            if val == '?' or val == '.':
595                self.result[self.key] = val
596                log.LogVarChange(self.result,self.key)
597                return
598        try:
599            val = self.typ(tc.GetValue())
600        except (ValueError, SyntaxError) as e:
601            if self.typ is float: # for float values, see if an expression can be evaluated
602                val = G2py3.FormulaEval(tc.GetValue())
603                if val is None:
604                    tc.invalid = True
605                    return
606                else:
607                    tc.evaluated = True
608            else: 
609                tc.invalid = True
610                return
611        # if self.max != None and self.typ == int:
612        #     if val > self.max:
613        #         tc.invalid = True
614        # if self.min != None and self.typ == int:
615        #     if val < self.min:
616        #         tc.invalid = True  # invalid
617        if self.max != None:
618            if val > self.max:
619                tc.invalid = True
620        if self.min != None:
621            if val < self.min:
622                tc.invalid = True  # invalid
623        if self.key is not None and self.result is not None and not tc.invalid:
624            self.result[self.key] = val
625            log.LogVarChange(self.result,self.key)
626
627    def ShowValidity(self,tc):
628        '''Set the control colors to show invalid input
629
630        :param wx.TextCtrl tc: A reference to the TextCtrl that the validator
631          is associated with.
632
633        '''
634        if tc.invalid:
635            tc.SetForegroundColour("red")
636            tc.SetBackgroundColour("yellow")
637            tc.SetFocus()
638            tc.Refresh()
639            return False
640        else: # valid input
641            tc.SetBackgroundColour(
642                wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW))
643            tc.SetForegroundColour("black")
644            tc.Refresh()
645            return True
646
647    def CheckInput(self,previousInvalid):
648        '''called to test every change to the TextCtrl for validity and
649        to change the appearance of the TextCtrl
650
651        Anytime the input is invalid, call self.OKcontrol
652        (if defined) because it is fast.
653        If valid, check for any other invalid entries only when
654        changing from invalid to valid, since that is slower.
655
656        :param bool previousInvalid: True if the TextCtrl contents were
657          invalid prior to the current change.
658        '''
659        tc = self.GetWindow()
660        self.TestValid(tc)
661        self.ShowValidity(tc)
662        # if invalid
663        if tc.invalid and self.OKcontrol:
664            self.OKcontrol(False)
665        if not tc.invalid and self.OKcontrol and previousInvalid:
666            self.OKcontrol(True)
667
668    def OnChar(self, event):
669        '''Called each type a key is pressed
670        ignores keys that are not allowed for int and float types
671        '''
672        key = event.GetKeyCode()
673        tc = self.GetWindow()
674        if key == wx.WXK_RETURN:
675            if tc.invalid:
676                self.CheckInput(True) 
677            else:
678                self.CheckInput(False) 
679            return
680        if key < wx.WXK_SPACE or key == wx.WXK_DELETE or key > 255: # control characters get processed
681            event.Skip()
682            if tc.invalid:
683                wx.CallAfter(self.CheckInput,True) 
684            else:
685                wx.CallAfter(self.CheckInput,False) 
686            return
687        elif chr(key) in self.validchars: # valid char pressed?
688            event.Skip()
689            if tc.invalid:
690                wx.CallAfter(self.CheckInput,True) 
691            else:
692                wx.CallAfter(self.CheckInput,False) 
693            return
694        if not wx.Validator_IsSilent(): wx.Bell()
695        return  # Returning without calling event.Skip, which eats the keystroke
696
697class ASCIIValidator(wx.PyValidator):
698    '''A validator to be used with a TextCtrl to prevent
699    entering characters other than ASCII characters.
700   
701    The value is checked for validity after every keystroke
702      If an invalid number is entered, the box is highlighted.
703      If the number is valid, it is saved in result[key]
704
705    :param dict/list result: List or dict where value should be placed when valid
706
707    :param any key: key to use for result (int for list)
708
709    '''
710    def __init__(self, result=None, key=None):
711        'Create the validator'
712        import string
713        wx.PyValidator.__init__(self)
714        # save passed parameters
715        self.result = result
716        self.key = key
717        self.validchars = string.ascii_letters + string.digits + string.punctuation + string.whitespace
718        self.Bind(wx.EVT_CHAR, self.OnChar)
719    def Clone(self):
720        'Create a copy of the validator, a strange, but required component'
721        return ASCIIValidator(result=self.result, key=self.key)
722        tc = self.GetWindow()
723        tc.invalid = False # make sure the validity flag is defined in parent
724    def TransferToWindow(self):
725        'Needed by validator, strange, but required component'
726        return True # Prevent wxDialog from complaining.
727    def TransferFromWindow(self):
728        'Needed by validator, strange, but required component'
729        return True # Prevent wxDialog from complaining.
730    def TestValid(self,tc):
731        '''Check if the value is valid by casting the input string
732        into ASCII.
733
734        Save it in the dict/list where the initial value was stored
735
736        :param wx.TextCtrl tc: A reference to the TextCtrl that the validator
737          is associated with.
738        '''
739        self.result[self.key] = tc.GetValue().encode('ascii','replace')
740        log.LogVarChange(self.result,self.key)
741
742    def OnChar(self, event):
743        '''Called each type a key is pressed
744        ignores keys that are not allowed for int and float types
745        '''
746        key = event.GetKeyCode()
747        tc = self.GetWindow()
748        if key == wx.WXK_RETURN:
749            self.TestValid(tc)
750            return
751        if key < wx.WXK_SPACE or key == wx.WXK_DELETE or key > 255: # control characters get processed
752            event.Skip()
753            self.TestValid(tc)
754            return
755        elif chr(key) in self.validchars: # valid char pressed?
756            event.Skip()
757            self.TestValid(tc)
758            return
759        if not wx.Validator_IsSilent():
760            wx.Bell()
761        return  # Returning without calling event.Skip, which eats the keystroke
762
763################################################################################
764#### Edit a large number of values
765################################################################################
766def CallScrolledMultiEditor(parent,dictlst,elemlst,prelbl=[],postlbl=[],
767                 title='Edit items',header='',size=(300,250),
768                             CopyButton=False, **kw):
769    '''Shell routine to call a ScrolledMultiEditor dialog. See
770    :class:`ScrolledMultiEditor` for parameter definitions.
771
772    :returns: True if the OK button is pressed; False if the window is closed
773      with the system menu or the Cancel button.
774
775    '''
776    dlg = ScrolledMultiEditor(parent,dictlst,elemlst,prelbl,postlbl,
777                              title,header,size,
778                              CopyButton, **kw)
779    if dlg.ShowModal() == wx.ID_OK:
780        dlg.Destroy()
781        return True
782    else:
783        dlg.Destroy()
784        return False
785
786class ScrolledMultiEditor(wx.Dialog):
787    '''Define a window for editing a potentially large number of dict- or
788    list-contained values with validation for each item. Edited values are
789    automatically placed in their source location. If invalid entries
790    are provided, the TextCtrl is turned yellow and the OK button is disabled.
791
792    The type for each TextCtrl validation is determined by the
793    initial value of the entry (int, float or string).
794    Float values can be entered in the TextCtrl as numbers or also
795    as algebraic expressions using operators + - / \* () and \*\*,
796    in addition pi, sind(), cosd(), tand(), and sqrt() can be used,
797    as well as appreviations s(), sin(), c(), cos(), t(), tan() and sq().
798
799    :param wx.Frame parent: name of parent window, or may be None
800
801    :param tuple dictlst: a list of dicts or lists containing values to edit
802
803    :param tuple elemlst: a list of keys for each item in a dictlst. Must have the
804      same length as dictlst.
805
806    :param wx.Frame parent: name of parent window, or may be None
807   
808    :param tuple prelbl: a list of labels placed before the TextCtrl for each
809      item (optional)
810   
811    :param tuple postlbl: a list of labels placed after the TextCtrl for each
812      item (optional)
813
814    :param str title: a title to place in the frame of the dialog
815
816    :param str header: text to place at the top of the window. May contain
817      new line characters.
818
819    :param wx.Size size: a size parameter that dictates the
820      size for the scrolled region of the dialog. The default is
821      (300,250).
822
823    :param bool CopyButton: if True adds a small button that copies the
824      value for the current row to all fields below (default is False)
825     
826    :param list minvals: optional list of minimum values for validation
827      of float or int values. Ignored if value is None.
828    :param list maxvals: optional list of maximum values for validation
829      of float or int values. Ignored if value is None.
830    :param list sizevals: optional list of wx.Size values for each input
831      widget. Ignored if value is None.
832     
833    :param tuple checkdictlst: an optional list of dicts or lists containing bool
834      values (similar to dictlst).
835    :param tuple checkelemlst: an optional list of dicts or lists containing bool
836      key values (similar to elemlst). Must be used with checkdictlst.
837    :param string checklabel: a string to use for each checkbutton
838     
839    :returns: the wx.Dialog created here. Use method .ShowModal() to display it.
840   
841    *Example for use of ScrolledMultiEditor:*
842
843    ::
844
845        dlg = <pkg>.ScrolledMultiEditor(frame,dictlst,elemlst,prelbl,postlbl,
846                                        header=header)
847        if dlg.ShowModal() == wx.ID_OK:
848             for d,k in zip(dictlst,elemlst):
849                 print d[k]
850
851    *Example definitions for dictlst and elemlst:*
852
853    ::
854     
855          dictlst = (dict1,list1,dict1,list1)
856          elemlst = ('a', 1, 2, 3)
857
858      This causes items dict1['a'], list1[1], dict1[2] and list1[3] to be edited.
859   
860    Note that these items must have int, float or str values assigned to
861    them. The dialog will force these types to be retained. String values
862    that are blank are marked as invalid.
863    '''
864   
865    def __init__(self,parent,dictlst,elemlst,prelbl=[],postlbl=[],
866                 title='Edit items',header='',size=(300,250),
867                 CopyButton=False,
868                 minvals=[],maxvals=[],sizevals=[],
869                 checkdictlst=[], checkelemlst=[], checklabel=""):
870        if len(dictlst) != len(elemlst):
871            raise Exception,"ScrolledMultiEditor error: len(dictlst) != len(elemlst) "+str(len(dictlst))+" != "+str(len(elemlst))
872        if len(checkdictlst) != len(checkelemlst):
873            raise Exception,"ScrolledMultiEditor error: len(checkdictlst) != len(checkelemlst) "+str(len(checkdictlst))+" != "+str(len(checkelemlst))
874        wx.Dialog.__init__( # create dialog & sizer
875            self,parent,wx.ID_ANY,title,
876            style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)
877        mainSizer = wx.BoxSizer(wx.VERTICAL)
878        self.orig = []
879        self.dictlst = dictlst
880        self.elemlst = elemlst
881        self.checkdictlst = checkdictlst
882        self.checkelemlst = checkelemlst
883        self.StartCheckValues = [checkdictlst[i][checkelemlst[i]] for i in range(len(checkdictlst))]
884        self.ButtonIndex = {}
885        for d,i in zip(dictlst,elemlst):
886            self.orig.append(d[i])
887        # add a header if supplied
888        if header:
889            subSizer = wx.BoxSizer(wx.HORIZONTAL)
890            subSizer.Add((-1,-1),1,wx.EXPAND)
891            subSizer.Add(wx.StaticText(self,wx.ID_ANY,header))
892            subSizer.Add((-1,-1),1,wx.EXPAND)
893            mainSizer.Add(subSizer,0,wx.EXPAND,0)
894        # make OK button now, because we will need it for validation
895        self.OKbtn = wx.Button(self, wx.ID_OK)
896        self.OKbtn.SetDefault()
897        # create scrolled panel and sizer
898        panel = wxscroll.ScrolledPanel(self, wx.ID_ANY,size=size,
899            style = wx.TAB_TRAVERSAL|wx.SUNKEN_BORDER)
900        cols = 4
901        if CopyButton: cols += 1
902        subSizer = wx.FlexGridSizer(cols=cols,hgap=2,vgap=2)
903        self.ValidatedControlsList = [] # make list of TextCtrls
904        self.CheckControlsList = [] # make list of CheckBoxes
905        for i,(d,k) in enumerate(zip(dictlst,elemlst)):
906            if i >= len(prelbl): # label before TextCtrl, or put in a blank
907                subSizer.Add((-1,-1)) 
908            else:
909                subSizer.Add(wx.StaticText(panel,wx.ID_ANY,str(prelbl[i])))
910            kargs = {}
911            if i < len(minvals):
912                if minvals[i] is not None: kargs['min']=minvals[i]
913            if i < len(maxvals):
914                if maxvals[i] is not None: kargs['max']=maxvals[i]
915            if i < len(sizevals):
916                if sizevals[i]: kargs['size']=sizevals[i]
917            if CopyButton:
918                import wx.lib.colourselect as wscs
919                but = wscs.ColourSelect(label='v', # would like to use u'\u2193' or u'\u25BC' but not in WinXP
920                                        # is there a way to test?
921                                        parent=panel,
922                                        colour=(255,255,200),
923                                        size=wx.Size(30,23),
924                                        style=wx.RAISED_BORDER)
925                but.Bind(wx.EVT_BUTTON, self._OnCopyButton)
926                but.SetToolTipString('Press to copy adjacent value to all rows below')
927                self.ButtonIndex[but] = i
928                subSizer.Add(but)
929            # create the validated TextCrtl, store it and add it to the sizer
930            ctrl = ValidatedTxtCtrl(panel,d,k,OKcontrol=self.ControlOKButton,
931                                    **kargs)
932            self.ValidatedControlsList.append(ctrl)
933            subSizer.Add(ctrl)
934            if i < len(postlbl): # label after TextCtrl, or put in a blank
935                subSizer.Add(wx.StaticText(panel,wx.ID_ANY,str(postlbl[i])))
936            else:
937                subSizer.Add((-1,-1))
938            if i < len(checkdictlst):
939                ch = G2CheckBox(panel,checklabel,checkdictlst[i],checkelemlst[i])
940                self.CheckControlsList.append(ch)
941                subSizer.Add(ch)                   
942            else:
943                subSizer.Add((-1,-1))
944        # finish up ScrolledPanel
945        panel.SetSizer(subSizer)
946        panel.SetAutoLayout(1)
947        panel.SetupScrolling()
948        # patch for wx 2.9 on Mac
949        i,j= wx.__version__.split('.')[0:2]
950        if int(i)+int(j)/10. > 2.8 and 'wxOSX' in wx.PlatformInfo:
951            panel.SetMinSize((subSizer.GetSize()[0]+30,panel.GetSize()[1]))       
952        mainSizer.Add(panel,1, wx.ALL|wx.EXPAND,1)
953
954        # Sizer for OK/Close buttons. N.B. on Close changes are discarded
955        # by restoring the initial values
956        btnsizer = wx.BoxSizer(wx.HORIZONTAL)
957        btnsizer.Add(self.OKbtn)
958        btn = wx.Button(self, wx.ID_CLOSE,"Cancel") 
959        btn.Bind(wx.EVT_BUTTON,self._onClose)
960        btnsizer.Add(btn)
961        mainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER|wx.ALL, 5)
962        # size out the window. Set it to be enlarged but not made smaller
963        self.SetSizer(mainSizer)
964        mainSizer.Fit(self)
965        self.SetMinSize(self.GetSize())
966
967    def _OnCopyButton(self,event):
968        'Implements the copy down functionality'
969        but = event.GetEventObject()
970        n = self.ButtonIndex.get(but)
971        if n is None: return
972        for i,(d,k,ctrl) in enumerate(zip(self.dictlst,self.elemlst,self.ValidatedControlsList)):
973            if i < n: continue
974            if i == n:
975                val = d[k]
976                continue
977            d[k] = val
978            ctrl.SetValue(val)
979        for i in range(len(self.checkdictlst)):
980            if i < n: continue
981            self.checkdictlst[i][self.checkelemlst[i]] = self.checkdictlst[n][self.checkelemlst[n]]
982            self.CheckControlsList[i].SetValue(self.checkdictlst[i][self.checkelemlst[i]])
983    def _onClose(self,event):
984        'Used on Cancel: Restore original values & close the window'
985        for d,i,v in zip(self.dictlst,self.elemlst,self.orig):
986            d[i] = v
987        for i in range(len(self.checkdictlst)):
988            self.checkdictlst[i][self.checkelemlst[i]] = self.StartCheckValues[i]
989        self.EndModal(wx.ID_CANCEL)
990       
991    def ControlOKButton(self,setvalue):
992        '''Enable or Disable the OK button for the dialog. Note that this is
993        passed into the ValidatedTxtCtrl for use by validators.
994
995        :param bool setvalue: if True, all entries in the dialog are
996          checked for validity. if False then the OK button is disabled.
997
998        '''
999        if setvalue: # turn button on, do only if all controls show as valid
1000            for ctrl in self.ValidatedControlsList:
1001                if ctrl.invalid:
1002                    self.OKbtn.Disable()
1003                    return
1004            else:
1005                self.OKbtn.Enable()
1006        else:
1007            self.OKbtn.Disable()
1008
1009################################################################################
1010####
1011################################################################################
1012def SelectEdit1Var(G2frame,array,labelLst,elemKeysLst,dspLst,refFlgElem):
1013    '''Select a variable from a list, then edit it and select histograms
1014    to copy it to.
1015
1016    :param wx.Frame G2frame: main GSAS-II frame
1017    :param dict array: the array (dict or list) where values to be edited are kept
1018    :param list labelLst: labels for each data item
1019    :param list elemKeysLst: a list of lists of keys needed to be applied (see below)
1020      to obtain the value of each parameter
1021    :param list dspLst: list list of digits to be displayed (10,4) is 10 digits
1022      with 4 decimal places. Can be None.
1023    :param list refFlgElem: a list of lists of keys needed to be applied (see below)
1024      to obtain the refine flag for each parameter or None if the parameter
1025      does not have refine flag.
1026
1027    Example::
1028      array = data
1029      labelLst = ['v1','v2']
1030      elemKeysLst = [['v1'], ['v2',0]]
1031      refFlgElem = [None, ['v2',1]]
1032
1033     * The value for v1 will be in data['v1'] and this cannot be refined while,
1034     * The value for v2 will be in data['v2'][0] and its refinement flag is data['v2'][1]
1035    '''
1036    def unkey(dct,keylist):
1037        '''dive into a nested set of dicts/lists applying keys in keylist
1038        consecutively
1039        '''
1040        d = dct
1041        for k in keylist:
1042            d = d[k]
1043        return d
1044
1045    def OnChoice(event):
1046        'Respond when a parameter is selected in the Choice box'
1047        valSizer.DeleteWindows()
1048        lbl = event.GetString()
1049        copyopts['currentsel'] = lbl
1050        i = labelLst.index(lbl)
1051        OKbtn.Enable(True)
1052        ch.SetLabel(lbl)
1053        args = {}
1054        if dspLst[i]:
1055            args = {'nDig':dspLst[i]}
1056        Val = ValidatedTxtCtrl(
1057            dlg,
1058            unkey(array,elemKeysLst[i][:-1]),
1059            elemKeysLst[i][-1],
1060            **args)
1061        copyopts['startvalue'] = unkey(array,elemKeysLst[i])
1062        #unkey(array,elemKeysLst[i][:-1])[elemKeysLst[i][-1]] =
1063        valSizer.Add(Val,0,wx.LEFT,5)
1064        dlg.SendSizeEvent()
1065       
1066    # SelectEdit1Var execution begins here
1067    saveArray = copy.deepcopy(array) # keep original values
1068    TreeItemType = G2frame.PatternTree.GetItemText(G2frame.PickId)
1069    copyopts = {'InTable':False,"startvalue":None,'currentsel':None}       
1070    hst = G2frame.PatternTree.GetItemText(G2frame.PatternId)
1071    histList = G2pdG.GetHistsLikeSelected(G2frame)
1072    if not histList:
1073        G2frame.ErrorDialog('No match','No histograms match '+hst,G2frame.dataFrame)
1074        return
1075    dlg = wx.Dialog(G2frame.dataDisplay,wx.ID_ANY,'Set a parameter value',
1076        style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)
1077    mainSizer = wx.BoxSizer(wx.VERTICAL)
1078    mainSizer.Add((5,5))
1079    subSizer = wx.BoxSizer(wx.HORIZONTAL)
1080    subSizer.Add((-1,-1),1,wx.EXPAND)
1081    subSizer.Add(wx.StaticText(dlg,wx.ID_ANY,'Select a parameter and set a new value'))
1082    subSizer.Add((-1,-1),1,wx.EXPAND)
1083    mainSizer.Add(subSizer,0,wx.EXPAND,0)
1084    mainSizer.Add((0,10))
1085
1086    subSizer = wx.FlexGridSizer(0,2,5,0)
1087    subSizer.Add(wx.StaticText(dlg,wx.ID_ANY,'Parameter: '))
1088    ch = wx.Choice(dlg, wx.ID_ANY, choices = sorted(labelLst))
1089    ch.SetSelection(-1)
1090    ch.Bind(wx.EVT_CHOICE, OnChoice)
1091    subSizer.Add(ch)
1092    subSizer.Add(wx.StaticText(dlg,wx.ID_ANY,'Value: '))
1093    valSizer = wx.BoxSizer(wx.HORIZONTAL)
1094    subSizer.Add(valSizer)
1095    mainSizer.Add(subSizer)
1096
1097    mainSizer.Add((-1,20))
1098    subSizer = wx.BoxSizer(wx.HORIZONTAL)
1099    subSizer.Add(G2CheckBox(dlg, 'Edit in table ', copyopts, 'InTable'))
1100    mainSizer.Add(subSizer)
1101
1102    btnsizer = wx.StdDialogButtonSizer()
1103    OKbtn = wx.Button(dlg, wx.ID_OK,'Continue')
1104    OKbtn.Enable(False)
1105    OKbtn.SetDefault()
1106    OKbtn.Bind(wx.EVT_BUTTON,lambda event: dlg.EndModal(wx.ID_OK))
1107    btnsizer.AddButton(OKbtn)
1108    btn = wx.Button(dlg, wx.ID_CANCEL)
1109    btnsizer.AddButton(btn)
1110    btnsizer.Realize()
1111    mainSizer.Add((-1,5),1,wx.EXPAND,1)
1112    mainSizer.Add(btnsizer,0,wx.ALIGN_CENTER,0)
1113    mainSizer.Add((-1,10))
1114
1115    dlg.SetSizer(mainSizer)
1116    dlg.CenterOnParent()
1117    if dlg.ShowModal() != wx.ID_OK:
1118        array.update(saveArray)
1119        dlg.Destroy()
1120        return
1121    dlg.Destroy()
1122
1123    copyList = []
1124    lbl = copyopts['currentsel']
1125    dlg = G2MultiChoiceDialog(
1126        G2frame.dataFrame, 
1127        'Copy parameter '+lbl+' from\n'+hst,
1128        'Copy parameters', histList)
1129    dlg.CenterOnParent()
1130    try:
1131        if dlg.ShowModal() == wx.ID_OK:
1132            for i in dlg.GetSelections(): 
1133                copyList.append(histList[i])
1134        else:
1135            # reset the parameter since cancel was pressed
1136            array.update(saveArray)
1137            return
1138    finally:
1139        dlg.Destroy()
1140
1141    prelbl = [hst]
1142    i = labelLst.index(lbl)
1143    keyLst = elemKeysLst[i]
1144    refkeys = refFlgElem[i]
1145    dictlst = [unkey(array,keyLst[:-1])]
1146    if refkeys is not None:
1147        refdictlst = [unkey(array,refkeys[:-1])]
1148    else:
1149        refdictlst = None
1150    Id = GetPatternTreeItemId(G2frame,G2frame.root,hst)
1151    hstData = G2frame.PatternTree.GetItemPyData(GetPatternTreeItemId(G2frame,Id,'Instrument Parameters'))[0]
1152    for h in copyList:
1153        Id = GetPatternTreeItemId(G2frame,G2frame.root,h)
1154        instData = G2frame.PatternTree.GetItemPyData(GetPatternTreeItemId(G2frame,Id,'Instrument Parameters'))[0]
1155        if len(hstData) != len(instData) or hstData['Type'][0] != instData['Type'][0]:  #don't mix data types or lam & lam1/lam2 parms!
1156            print h+' not copied - instrument parameters not commensurate'
1157            continue
1158        hData = G2frame.PatternTree.GetItemPyData(GetPatternTreeItemId(G2frame,Id,TreeItemType))
1159        if TreeItemType == 'Instrument Parameters':
1160            hData = hData[0]
1161        #copy the value if it is changed or we will not edit in a table
1162        valNow = unkey(array,keyLst)
1163        if copyopts['startvalue'] != valNow or not copyopts['InTable']:
1164            unkey(hData,keyLst[:-1])[keyLst[-1]] = valNow
1165        prelbl += [h]
1166        dictlst += [unkey(hData,keyLst[:-1])]
1167        if refdictlst is not None:
1168            refdictlst += [unkey(hData,refkeys[:-1])]
1169    if refdictlst is None:
1170        args = {}
1171    else:
1172        args = {'checkdictlst':refdictlst,
1173                'checkelemlst':len(dictlst)*[refkeys[-1]],
1174                'checklabel':'Refine?'}
1175    if copyopts['InTable']:
1176        dlg = ScrolledMultiEditor(
1177            G2frame.dataDisplay,dictlst,
1178            len(dictlst)*[keyLst[-1]],prelbl,
1179            header='Editing parameter '+lbl,
1180            CopyButton=True,**args)
1181        dlg.CenterOnParent()
1182        if dlg.ShowModal() != wx.ID_OK:
1183            array.update(saveArray)
1184        dlg.Destroy()
1185
1186################################################################################
1187#### Custom checkbox that saves values into dict/list as used
1188################################################################################
1189class G2CheckBox(wx.CheckBox):
1190    '''A customized version of a CheckBox that automatically initializes
1191    the control to a supplied list or dict entry and updates that
1192    entry as the widget is used.
1193
1194    :param wx.Panel parent: name of panel or frame that will be
1195      the parent to the widget. Can be None.
1196    :param str label: text to put on check button
1197    :param dict/list loc: the dict or list with the initial value to be
1198      placed in the CheckBox.
1199    :param int/str key: the dict key or the list index for the value to be
1200      edited by the CheckBox. The ``loc[key]`` element must exist.
1201      The CheckBox will be initialized from this value.
1202      If the value is anything other that True (or 1), it will be taken as
1203      False.
1204    '''
1205    def __init__(self,parent,label,loc,key):
1206        wx.CheckBox.__init__(self,parent,id=wx.ID_ANY,label=label)
1207        self.loc = loc
1208        self.key = key
1209        self.SetValue(self.loc[self.key]==True)
1210        self.Bind(wx.EVT_CHECKBOX, self._OnCheckBox)
1211    def _OnCheckBox(self,event):
1212        self.loc[self.key] = self.GetValue()
1213        log.LogVarChange(self.loc,self.key)
1214
1215################################################################################
1216####
1217################################################################################
1218class PickTwoDialog(wx.Dialog):
1219    '''This does not seem to be in use
1220    '''
1221    def __init__(self,parent,title,prompt,names,choices):
1222        wx.Dialog.__init__(self,parent,-1,title, 
1223            pos=wx.DefaultPosition,style=wx.DEFAULT_DIALOG_STYLE)
1224        self.panel = wx.Panel(self)         #just a dummy - gets destroyed in Draw!
1225        self.prompt = prompt
1226        self.choices = choices
1227        self.names = names
1228        self.Draw()
1229
1230    def Draw(self):
1231        Indx = {}
1232       
1233        def OnSelection(event):
1234            Obj = event.GetEventObject()
1235            id = Indx[Obj.GetId()]
1236            self.choices[id] = Obj.GetValue().encode()  #to avoid Unicode versions
1237            self.Draw()
1238           
1239        self.panel.DestroyChildren()
1240        self.panel.Destroy()
1241        self.panel = wx.Panel(self)
1242        mainSizer = wx.BoxSizer(wx.VERTICAL)
1243        mainSizer.Add(wx.StaticText(self.panel,-1,self.prompt),0,wx.ALIGN_CENTER)
1244        for isel,name in enumerate(self.choices):
1245            lineSizer = wx.BoxSizer(wx.HORIZONTAL)
1246            lineSizer.Add(wx.StaticText(self.panel,-1,'Reference atom '+str(isel+1)),0,wx.ALIGN_CENTER)
1247            nameList = self.names[:]
1248            if isel:
1249                if self.choices[0] in nameList:
1250                    nameList.remove(self.choices[0])
1251            choice = wx.ComboBox(self.panel,-1,value=name,choices=nameList,
1252                style=wx.CB_READONLY|wx.CB_DROPDOWN)
1253            Indx[choice.GetId()] = isel
1254            choice.Bind(wx.EVT_COMBOBOX, OnSelection)
1255            lineSizer.Add(choice,0,WACV)
1256            mainSizer.Add(lineSizer)
1257        OkBtn = wx.Button(self.panel,-1,"Ok")
1258        OkBtn.Bind(wx.EVT_BUTTON, self.OnOk)
1259        CancelBtn = wx.Button(self.panel,-1,'Cancel')
1260        CancelBtn.Bind(wx.EVT_BUTTON, self.OnCancel)
1261        btnSizer = wx.BoxSizer(wx.HORIZONTAL)
1262        btnSizer.Add((20,20),1)
1263        btnSizer.Add(OkBtn)
1264        btnSizer.Add(CancelBtn)
1265        btnSizer.Add((20,20),1)
1266        mainSizer.Add(btnSizer,0,wx.EXPAND|wx.BOTTOM|wx.TOP, 10)
1267        self.panel.SetSizer(mainSizer)
1268        self.panel.Fit()
1269        self.Fit()
1270       
1271    def GetSelection(self):
1272        return self.choices
1273
1274    def OnOk(self,event):
1275        parent = self.GetParent()
1276        parent.Raise()
1277        self.EndModal(wx.ID_OK)             
1278       
1279    def OnCancel(self,event):
1280        parent = self.GetParent()
1281        parent.Raise()
1282        self.EndModal(wx.ID_CANCEL)
1283
1284################################################################################
1285#### Column-order selection
1286################################################################################
1287
1288def GetItemOrder(parent,keylist,vallookup,posdict):
1289    '''Creates a panel where items can be ordered into columns
1290    :param list keylist: is a list of keys for column assignments
1291    :param dict vallookup: is a dict keyed by names in keylist where each item is a dict.
1292       Each inner dict contains variable names as keys and their associated values
1293    :param dict posdict: is a dict keyed by names in keylist where each item is a dict.
1294       Each inner dict contains column numbers as keys and their associated
1295       variable name as a value. This is used for both input and output.
1296    '''
1297    dlg = wx.Dialog(parent,style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)
1298    sizer = wx.BoxSizer(wx.VERTICAL)
1299    spanel = OrderBox(dlg,keylist,vallookup,posdict)
1300    spanel.Fit()
1301    sizer.Add(spanel,1,wx.EXPAND)
1302    btnsizer = wx.StdDialogButtonSizer()
1303    btn = wx.Button(dlg, wx.ID_OK)
1304    btn.SetDefault()
1305    btnsizer.AddButton(btn)
1306    #btn = wx.Button(dlg, wx.ID_CANCEL)
1307    #btnsizer.AddButton(btn)
1308    btnsizer.Realize()
1309    sizer.Add(btnsizer, 0, wx.ALIGN_CENTER_VERTICAL|wx.EXPAND|wx.ALL, 5)
1310    dlg.SetSizer(sizer)
1311    sizer.Fit(dlg)
1312    val = dlg.ShowModal()
1313
1314################################################################################
1315####
1316################################################################################
1317class OrderBox(wxscroll.ScrolledPanel):
1318    '''Creates a panel with scrollbars where items can be ordered into columns
1319    :param list keylist: is a list of keys for column assignments
1320    :param dict vallookup: is a dict keyed by names in keylist where each item is a dict.
1321      Each inner dict contains variable names as keys and their associated values
1322    :param dict posdict: is a dict keyed by names in keylist where each item is a dict.
1323      Each inner dict contains column numbers as keys and their associated
1324      variable name as a value. This is used for both input and output.
1325    '''
1326    def __init__(self,parent,keylist,vallookup,posdict,*arg,**kw):
1327        self.keylist = keylist
1328        self.vallookup = vallookup
1329        self.posdict = posdict
1330        self.maxcol = 0
1331        for nam in keylist:
1332            posdict = self.posdict[nam]
1333            if posdict.keys():
1334                self.maxcol = max(self.maxcol, max(posdict))
1335        wxscroll.ScrolledPanel.__init__(self,parent,wx.ID_ANY,*arg,**kw)
1336        self.GBsizer = wx.GridBagSizer(4,4)
1337        self.SetBackgroundColour(WHITE)
1338        self.SetSizer(self.GBsizer)
1339        colList = [str(i) for i in range(self.maxcol+2)]
1340        for i in range(self.maxcol+1):
1341            wid = wx.StaticText(self,wx.ID_ANY,str(i),style=wx.ALIGN_CENTER)
1342            wid.SetBackgroundColour(DULL_YELLOW)
1343            wid.SetMinSize((50,-1))
1344            self.GBsizer.Add(wid,(0,i),flag=wx.ALIGN_CENTER|wx.EXPAND)
1345        self.chceDict = {}
1346        for row,nam in enumerate(self.keylist):
1347            posdict = self.posdict[nam]
1348            for col in posdict:
1349                lbl = posdict[col]
1350                pnl = wx.Panel(self,wx.ID_ANY)
1351                pnl.SetBackgroundColour(VERY_LIGHT_GREY)
1352                insize = wx.BoxSizer(wx.VERTICAL)
1353                wid = wx.Choice(pnl,wx.ID_ANY,choices=colList)
1354                insize.Add(wid,0,wx.EXPAND|wx.BOTTOM,3)
1355                wid.SetSelection(col)
1356                self.chceDict[wid] = (row,col)
1357                wid.Bind(wx.EVT_CHOICE,self.OnChoice)
1358                wid = wx.StaticText(pnl,wx.ID_ANY,lbl)
1359                insize.Add(wid,0,flag=wx.EXPAND)
1360                val = G2py3.FormatSigFigs(self.vallookup[nam][lbl],maxdigits=8)
1361                wid = wx.StaticText(pnl,wx.ID_ANY,'('+val+')')
1362                insize.Add(wid,0,flag=wx.EXPAND)
1363                pnl.SetSizer(insize)
1364                self.GBsizer.Add(pnl,(row+1,col),flag=wx.EXPAND)
1365        self.SetAutoLayout(1)
1366        self.SetupScrolling()
1367        self.SetMinSize((
1368            min(700,self.GBsizer.GetSize()[0]),
1369            self.GBsizer.GetSize()[1]+20))
1370    def OnChoice(self,event):
1371        '''Called when a column is assigned to a variable
1372        '''
1373        row,col = self.chceDict[event.EventObject] # which variable was this?
1374        newcol = event.Selection # where will it be moved?
1375        if newcol == col:
1376            return # no change: nothing to do!
1377        prevmaxcol = self.maxcol # save current table size
1378        key = self.keylist[row] # get the key for the current row
1379        lbl = self.posdict[key][col] # selected variable name
1380        lbl1 = self.posdict[key].get(col+1,'') # next variable name, if any
1381        # if a posXXX variable is selected, and the next variable is posXXX, move them together
1382        repeat = 1
1383        if lbl[:3] == 'pos' and lbl1[:3] == 'int' and lbl[3:] == lbl1[3:]:
1384            repeat = 2
1385        for i in range(repeat): # process the posXXX and then the intXXX (or a single variable)
1386            col += i
1387            newcol += i
1388            if newcol in self.posdict[key]:
1389                # find first non-blank after newcol
1390                for mtcol in range(newcol+1,self.maxcol+2):
1391                    if mtcol not in self.posdict[key]: break
1392                l1 = range(mtcol,newcol,-1)+[newcol]
1393                l = range(mtcol-1,newcol-1,-1)+[col]
1394            else:
1395                l1 = [newcol]
1396                l = [col]
1397            # move all of the items, starting from the last column
1398            for newcol,col in zip(l1,l):
1399                #print 'moving',col,'to',newcol
1400                self.posdict[key][newcol] = self.posdict[key][col]
1401                del self.posdict[key][col]
1402                self.maxcol = max(self.maxcol,newcol)
1403                obj = self.GBsizer.FindItemAtPosition((row+1,col))
1404                self.GBsizer.SetItemPosition(obj.GetWindow(),(row+1,newcol))
1405                for wid in obj.GetWindow().Children:
1406                    if wid in self.chceDict:
1407                        self.chceDict[wid] = (row,newcol)
1408                        wid.SetSelection(self.chceDict[wid][1])
1409        # has the table gotten larger? If so we need new column heading(s)
1410        if prevmaxcol != self.maxcol:
1411            for i in range(prevmaxcol+1,self.maxcol+1):
1412                wid = wx.StaticText(self,wx.ID_ANY,str(i),style=wx.ALIGN_CENTER)
1413                wid.SetBackgroundColour(DULL_YELLOW)
1414                wid.SetMinSize((50,-1))
1415                self.GBsizer.Add(wid,(0,i),flag=wx.ALIGN_CENTER|wx.EXPAND)
1416            colList = [str(i) for i in range(self.maxcol+2)]
1417            for wid in self.chceDict:
1418                wid.SetItems(colList)
1419                wid.SetSelection(self.chceDict[wid][1])
1420        self.GBsizer.Layout()
1421        self.FitInside()
1422
1423################################################################################
1424#### Help support routines
1425################################################################################
1426################################################################################
1427class MyHelp(wx.Menu):
1428    '''
1429    A class that creates the contents of a help menu.
1430    The menu will start with two entries:
1431
1432    * 'Help on <helpType>': where helpType is a reference to an HTML page to
1433      be opened
1434    * About: opens an About dialog using OnHelpAbout. N.B. on the Mac this
1435      gets moved to the App menu to be consistent with Apple style.
1436
1437    NOTE: for this to work properly with respect to system menus, the title
1438    for the menu must be &Help, or it will not be processed properly:
1439
1440    ::
1441
1442       menu.Append(menu=MyHelp(self,...),title="&Help")
1443
1444    '''
1445    def __init__(self,frame,helpType=None,helpLbl=None,morehelpitems=[],title=''):
1446        wx.Menu.__init__(self,title)
1447        self.HelpById = {}
1448        self.frame = frame
1449        self.Append(help='', id=wx.ID_ABOUT, kind=wx.ITEM_NORMAL,
1450            text='&About GSAS-II')
1451        frame.Bind(wx.EVT_MENU, self.OnHelpAbout, id=wx.ID_ABOUT)
1452        if GSASIIpath.whichsvn():
1453            helpobj = self.Append(
1454                help='', id=wx.ID_ANY, kind=wx.ITEM_NORMAL,
1455                text='&Check for updates')
1456            frame.Bind(wx.EVT_MENU, self.OnCheckUpdates, helpobj)
1457            helpobj = self.Append(
1458                help='', id=wx.ID_ANY, kind=wx.ITEM_NORMAL,
1459                text='&Regress to an old GSAS-II version')
1460            frame.Bind(wx.EVT_MENU, self.OnSelectVersion, helpobj)
1461        for lbl,indx in morehelpitems:
1462            helpobj = self.Append(text=lbl,
1463                id=wx.ID_ANY, kind=wx.ITEM_NORMAL)
1464            frame.Bind(wx.EVT_MENU, self.OnHelpById, helpobj)
1465            self.HelpById[helpobj.GetId()] = indx
1466        # add a help item only when helpType is specified
1467        if helpType is not None:
1468            self.AppendSeparator()
1469            if helpLbl is None: helpLbl = helpType
1470            helpobj = self.Append(text='Help on '+helpLbl,
1471                                  id=wx.ID_ANY, kind=wx.ITEM_NORMAL)
1472            frame.Bind(wx.EVT_MENU, self.OnHelpById, helpobj)
1473            self.HelpById[helpobj.GetId()] = helpType
1474       
1475    def OnHelpById(self,event):
1476        '''Called when Help on... is pressed in a menu. Brings up
1477        a web page for documentation.
1478        '''
1479        helpType = self.HelpById.get(event.GetId())
1480        if helpType is None:
1481            print 'Error: help lookup failed!',event.GetEventObject()
1482            print 'id=',event.GetId()
1483        else:
1484            if helpType == 'Tutorials':
1485                self.frame.Tutorials = True 
1486            ShowHelp(helpType,self.frame)
1487
1488    def OnHelpAbout(self, event):
1489        "Display an 'About GSAS-II' box"
1490        import GSASII
1491        info = wx.AboutDialogInfo()
1492        info.Name = 'GSAS-II'
1493        ver = GSASIIpath.svnGetRev()
1494        if ver: 
1495            info.Version = 'Revision '+str(ver)+' (svn), version '+GSASII.__version__
1496        else:
1497            info.Version = 'Revision '+str(GSASIIpath.GetVersionNumber())+' (.py files), version '+GSASII.__version__
1498        #info.Developers = ['Robert B. Von Dreele','Brian H. Toby']
1499        info.Copyright = ('(c) ' + time.strftime('%Y') +
1500''' Argonne National Laboratory
1501This product includes software developed
1502by the UChicago Argonne, LLC, as
1503Operator of Argonne National Laboratory.''')
1504        info.Description = '''General Structure Analysis System-II (GSAS-II)
1505Robert B. Von Dreele and Brian H. Toby
1506
1507Please cite as:
1508B.H. Toby & R.B. Von Dreele, J. Appl. Cryst. 46, 544-549 (2013) '''
1509
1510        info.WebSite = ("https://subversion.xray.aps.anl.gov/trac/pyGSAS","GSAS-II home page")
1511        wx.AboutBox(info)
1512
1513    def OnCheckUpdates(self,event):
1514        '''Check if the GSAS-II repository has an update for the current source files
1515        and perform that update if requested.
1516        '''
1517        if not GSASIIpath.whichsvn():
1518            dlg = wx.MessageDialog(self.frame,
1519                                   'No Subversion','Cannot update GSAS-II because subversion (svn) was not found.',
1520                                   wx.OK)
1521            dlg.ShowModal()
1522            dlg.Destroy()
1523            return
1524        wx.BeginBusyCursor()
1525        local = GSASIIpath.svnGetRev()
1526        if local is None: 
1527            wx.EndBusyCursor()
1528            dlg = wx.MessageDialog(self.frame,
1529                                   'Unable to run subversion on the GSAS-II current directory. Is GSAS-II installed correctly?',
1530                                   'Subversion error',
1531                                   wx.OK)
1532            dlg.ShowModal()
1533            dlg.Destroy()
1534            return
1535        print 'Installed GSAS-II version: '+local
1536        repos = GSASIIpath.svnGetRev(local=False)
1537        wx.EndBusyCursor()
1538        if repos is None: 
1539            dlg = wx.MessageDialog(self.frame,
1540                                   'Unable to access the GSAS-II server. Is this computer on the internet?',
1541                                   'Server unavailable',
1542                                   wx.OK)
1543            dlg.ShowModal()
1544            dlg.Destroy()
1545            return
1546        print 'GSAS-II version on server: '+repos
1547        if local == repos:
1548            dlg = wx.MessageDialog(self.frame,
1549                                   'GSAS-II is up-to-date. Version '+local+' is already loaded.',
1550                                   'GSAS-II Up-to-date',
1551                                   wx.OK)
1552            dlg.ShowModal()
1553            dlg.Destroy()
1554            return
1555        mods = GSASIIpath.svnFindLocalChanges()
1556        if mods:
1557            dlg = wx.MessageDialog(self.frame,
1558                                   'You have version '+local+
1559                                   ' of GSAS-II installed, but the current version is '+repos+
1560                                   '. However, '+str(len(mods))+
1561                                   ' file(s) on your local computer have been modified.'
1562                                   ' Updating will attempt to merge your local changes with '
1563                                   'the latest GSAS-II version, but if '
1564                                   'conflicts arise, local changes will be '
1565                                   'discarded. It is also possible that the '
1566                                   'local changes my prevent GSAS-II from running. '
1567                                   'Press OK to start an update if this is acceptable:',
1568                                   'Local GSAS-II Mods',
1569                                   wx.OK|wx.CANCEL)
1570            if dlg.ShowModal() != wx.ID_OK:
1571                dlg.Destroy()
1572                return
1573            else:
1574                dlg.Destroy()
1575        else:
1576            dlg = wx.MessageDialog(self.frame,
1577                                   'You have version '+local+
1578                                   ' of GSAS-II installed, but the current version is '+repos+
1579                                   '. Press OK to start an update:',
1580                                   'GSAS-II Updates',
1581                                   wx.OK|wx.CANCEL)
1582            if dlg.ShowModal() != wx.ID_OK:
1583                dlg.Destroy()
1584                return
1585            dlg.Destroy()
1586        print 'start updates'
1587        dlg = wx.MessageDialog(self.frame,
1588                               'Your project will now be saved, GSAS-II will exit and an update '
1589                               'will be performed and GSAS-II will restart. Press Cancel to '
1590                               'abort the update',
1591                               'Start update?',
1592                               wx.OK|wx.CANCEL)
1593        if dlg.ShowModal() != wx.ID_OK:
1594            dlg.Destroy()
1595            return
1596        dlg.Destroy()
1597        self.frame.OnFileSave(event)
1598        GSASIIpath.svnUpdateProcess(projectfile=self.frame.GSASprojectfile)
1599        return
1600
1601    def OnSelectVersion(self,event):
1602        '''Allow the user to select a specific version of GSAS-II
1603        '''
1604        if not GSASIIpath.whichsvn():
1605            dlg = wx.MessageDialog(self,'No Subversion','Cannot update GSAS-II because subversion (svn) '+
1606                                   'was not found.'
1607                                   ,wx.OK)
1608            dlg.ShowModal()
1609            return
1610        local = GSASIIpath.svnGetRev()
1611        if local is None: 
1612            dlg = wx.MessageDialog(self.frame,
1613                                   'Unable to run subversion on the GSAS-II current directory. Is GSAS-II installed correctly?',
1614                                   'Subversion error',
1615                                   wx.OK)
1616            dlg.ShowModal()
1617            return
1618        mods = GSASIIpath.svnFindLocalChanges()
1619        if mods:
1620            dlg = wx.MessageDialog(self.frame,
1621                                   'You have version '+local+
1622                                   ' of GSAS-II installed'
1623                                   '. However, '+str(len(mods))+
1624                                   ' file(s) on your local computer have been modified.'
1625                                   ' Downdating will attempt to merge your local changes with '
1626                                   'the selected GSAS-II version. '
1627                                   'Downdating is not encouraged because '
1628                                   'if merging is not possible, your local changes will be '
1629                                   'discarded. It is also possible that the '
1630                                   'local changes my prevent GSAS-II from running. '
1631                                   'Press OK to continue anyway.',
1632                                   'Local GSAS-II Mods',
1633                                   wx.OK|wx.CANCEL)
1634            if dlg.ShowModal() != wx.ID_OK:
1635                dlg.Destroy()
1636                return
1637            dlg.Destroy()
1638        dlg = downdate(parent=self.frame)
1639        if dlg.ShowModal() == wx.ID_OK:
1640            ver = dlg.getVersion()
1641        else:
1642            dlg.Destroy()
1643            return
1644        dlg.Destroy()
1645        print('start regress to '+str(ver))
1646        GSASIIpath.svnUpdateProcess(
1647            projectfile=self.frame.GSASprojectfile,
1648            version=str(ver)
1649            )
1650        self.frame.OnFileSave(event)
1651        return
1652
1653################################################################################
1654class AddHelp(wx.Menu):
1655    '''For the Mac: creates an entry to the help menu of type
1656    'Help on <helpType>': where helpType is a reference to an HTML page to
1657    be opened.
1658
1659    NOTE: when appending this menu (menu.Append) be sure to set the title to
1660    '&Help' so that wx handles it correctly.
1661    '''
1662    def __init__(self,frame,helpType,helpLbl=None,title=''):
1663        wx.Menu.__init__(self,title)
1664        self.frame = frame
1665        if helpLbl is None: helpLbl = helpType
1666        # add a help item only when helpType is specified
1667        helpobj = self.Append(text='Help on '+helpLbl,
1668                              id=wx.ID_ANY, kind=wx.ITEM_NORMAL)
1669        frame.Bind(wx.EVT_MENU, self.OnHelpById, helpobj)
1670        self.HelpById = helpType
1671       
1672    def OnHelpById(self,event):
1673        '''Called when Help on... is pressed in a menu. Brings up
1674        a web page for documentation.
1675        '''
1676        ShowHelp(self.HelpById,self.frame)
1677
1678################################################################################
1679class HelpButton(wx.Button):
1680    '''Create a help button that displays help information.
1681    The text is displayed in a modal message window.
1682
1683    TODO: it might be nice if it were non-modal: e.g. it stays around until
1684    the parent is deleted or the user closes it, but this did not work for
1685    me.
1686
1687    :param parent: the panel which will be the parent of the button
1688    :param str msg: the help text to be displayed
1689    '''
1690    def __init__(self,parent,msg):
1691        if sys.platform == "darwin": 
1692            wx.Button.__init__(self,parent,wx.ID_HELP)
1693        else:
1694            wx.Button.__init__(self,parent,wx.ID_ANY,'?',style=wx.BU_EXACTFIT)
1695        self.Bind(wx.EVT_BUTTON,self._onPress)
1696        self.msg=msg
1697        self.parent = parent
1698    def _onClose(self,event):
1699        self.dlg.EndModal(wx.ID_CANCEL)
1700    def _onPress(self,event):
1701        'Respond to a button press by displaying the requested text'
1702        #dlg = wx.MessageDialog(self.parent,self.msg,'Help info',wx.OK)
1703        self.dlg = wx.Dialog(self.parent,wx.ID_ANY,'Help information', 
1704                        style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)
1705        #self.dlg.SetBackgroundColour(wx.WHITE)
1706        mainSizer = wx.BoxSizer(wx.VERTICAL)
1707        txt = wx.StaticText(self.dlg,wx.ID_ANY,self.msg)
1708        mainSizer.Add(txt,1,wx.ALL|wx.EXPAND,10)
1709        txt.SetBackgroundColour(wx.WHITE)
1710
1711        btnsizer = wx.BoxSizer(wx.HORIZONTAL)
1712        btn = wx.Button(self.dlg, wx.ID_CLOSE) 
1713        btn.Bind(wx.EVT_BUTTON,self._onClose)
1714        btnsizer.Add(btn)
1715        mainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER|wx.ALL, 5)
1716        self.dlg.SetSizer(mainSizer)
1717        mainSizer.Fit(self.dlg)
1718        self.dlg.ShowModal()
1719        self.dlg.Destroy()
1720################################################################################
1721class MyHtmlPanel(wx.Panel):
1722    '''Defines a panel to display HTML help information, as an alternative to
1723    displaying help information in a web browser.
1724    '''
1725    def __init__(self, frame, id):
1726        self.frame = frame
1727        wx.Panel.__init__(self, frame, id)
1728        sizer = wx.BoxSizer(wx.VERTICAL)
1729        back = wx.Button(self, -1, "Back")
1730        back.Bind(wx.EVT_BUTTON, self.OnBack)
1731        self.htmlwin = G2HtmlWindow(self, id, size=(750,450))
1732        sizer.Add(self.htmlwin, 1,wx.EXPAND)
1733        sizer.Add(back, 0, wx.ALIGN_LEFT, 0)
1734        self.SetSizer(sizer)
1735        sizer.Fit(frame)       
1736        self.Bind(wx.EVT_SIZE,self.OnHelpSize)
1737    def OnHelpSize(self,event):         #does the job but weirdly!!
1738        anchor = self.htmlwin.GetOpenedAnchor()
1739        if anchor:           
1740            self.htmlwin.ScrollToAnchor(anchor)
1741            wx.CallAfter(self.htmlwin.ScrollToAnchor,anchor)
1742            event.Skip()
1743    def OnBack(self, event):
1744        self.htmlwin.HistoryBack()
1745    def LoadFile(self,file):
1746        pos = file.rfind('#')
1747        if pos != -1:
1748            helpfile = file[:pos]
1749            helpanchor = file[pos+1:]
1750        else:
1751            helpfile = file
1752            helpanchor = None
1753        self.htmlwin.LoadPage(helpfile)
1754        if helpanchor is not None:
1755            self.htmlwin.ScrollToAnchor(helpanchor)
1756            xs,ys = self.htmlwin.GetViewStart()
1757            self.htmlwin.Scroll(xs,ys-1)
1758
1759class G2HtmlWindow(wx.html.HtmlWindow):
1760    '''Displays help information in a primitive HTML browser type window
1761    '''
1762    def __init__(self, parent, *args, **kwargs):
1763        self.parent = parent
1764        wx.html.HtmlWindow.__init__(self, parent, *args, **kwargs)
1765    def LoadPage(self, *args, **kwargs):
1766        wx.html.HtmlWindow.LoadPage(self, *args, **kwargs)
1767        self.TitlePage()
1768    def OnLinkClicked(self, *args, **kwargs):
1769        wx.html.HtmlWindow.OnLinkClicked(self, *args, **kwargs)
1770        xs,ys = self.GetViewStart()
1771        self.Scroll(xs,ys-1)
1772        self.TitlePage()
1773    def HistoryBack(self, *args, **kwargs):
1774        wx.html.HtmlWindow.HistoryBack(self, *args, **kwargs)
1775        self.TitlePage()
1776    def TitlePage(self):
1777        self.parent.frame.SetTitle(self.GetOpenedPage() + ' -- ' + 
1778            self.GetOpenedPageTitle())
1779################################################################################
1780class downdate(wx.Dialog):
1781    '''Dialog to allow a user to select a version of GSAS-II to install
1782    '''
1783    def __init__(self,parent=None):
1784        style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER
1785        wx.Dialog.__init__(self, parent, wx.ID_ANY, 'Select Version', style=style)
1786        pnl = wx.Panel(self)
1787        sizer = wx.BoxSizer(wx.VERTICAL)
1788        insver = GSASIIpath.svnGetRev(local=True)
1789        curver = int(GSASIIpath.svnGetRev(local=False))
1790        label = wx.StaticText(
1791            pnl,  wx.ID_ANY,
1792            'Select a specific GSAS-II version to install'
1793            )
1794        sizer.Add(label, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
1795        sizer1 = wx.BoxSizer(wx.HORIZONTAL)
1796        sizer1.Add(
1797            wx.StaticText(pnl,  wx.ID_ANY,
1798                          'Currently installed version: '+str(insver)),
1799            0, wx.ALIGN_CENTRE|wx.ALL, 5)
1800        sizer.Add(sizer1)
1801        sizer1 = wx.BoxSizer(wx.HORIZONTAL)
1802        sizer1.Add(
1803            wx.StaticText(pnl,  wx.ID_ANY,
1804                          'Select GSAS-II version to install: '),
1805            0, wx.ALIGN_CENTRE|wx.ALL, 5)
1806        self.spin = wx.SpinCtrl(pnl, wx.ID_ANY,size=(150,-1))
1807        self.spin.SetRange(1, curver)
1808        self.spin.SetValue(curver)
1809        self.Bind(wx.EVT_SPINCTRL, self._onSpin, self.spin)
1810        self.Bind(wx.EVT_KILL_FOCUS, self._onSpin, self.spin)
1811        sizer1.Add(self.spin)
1812        sizer.Add(sizer1)
1813
1814        line = wx.StaticLine(pnl,-1, size=(-1,3), style=wx.LI_HORIZONTAL)
1815        sizer.Add(line, 0, wx.EXPAND|wx.ALIGN_CENTER|wx.ALL, 10)
1816
1817        self.text = wx.StaticText(pnl,  wx.ID_ANY, "")
1818        sizer.Add(self.text, 0, wx.ALIGN_LEFT|wx.EXPAND|wx.ALL, 5)
1819
1820        line = wx.StaticLine(pnl,-1, size=(-1,3), style=wx.LI_HORIZONTAL)
1821        sizer.Add(line, 0, wx.EXPAND|wx.ALIGN_CENTER|wx.ALL, 10)
1822        sizer.Add(
1823            wx.StaticText(
1824                pnl,  wx.ID_ANY,
1825                'If "Install" is pressed, your project will be saved;\n'
1826                'GSAS-II will exit; The specified version will be loaded\n'
1827                'and GSAS-II will restart. Press "Cancel" to abort.'),
1828            0, wx.EXPAND|wx.ALL, 10)
1829        btnsizer = wx.StdDialogButtonSizer()
1830        btn = wx.Button(pnl, wx.ID_OK, "Install")
1831        btn.SetDefault()
1832        btnsizer.AddButton(btn)
1833        btn = wx.Button(pnl, wx.ID_CANCEL)
1834        btnsizer.AddButton(btn)
1835        btnsizer.Realize()
1836        sizer.Add(btnsizer, 0, wx.ALIGN_CENTER|wx.ALL, 5)
1837        pnl.SetSizer(sizer)
1838        sizer.Fit(self)
1839        self.topsizer=sizer
1840        self.CenterOnParent()
1841        self._onSpin(None)
1842
1843    def _onSpin(self,event):
1844        'Called to load info about the selected version in the dialog'
1845        ver = self.spin.GetValue()
1846        d = GSASIIpath.svnGetLog(version=ver)
1847        date = d.get('date','?').split('T')[0]
1848        s = '(Version '+str(ver)+' created '+date
1849        s += ' by '+d.get('author','?')+')'
1850        msg = d.get('msg')
1851        if msg: s += '\n\nComment: '+msg
1852        self.text.SetLabel(s)
1853        self.topsizer.Fit(self)
1854
1855    def getVersion(self):
1856        'Get the version number in the dialog'
1857        return self.spin.GetValue()
1858################################################################################
1859#### Display Help information
1860################################################################################
1861# define some globals
1862htmlPanel = None
1863htmlFrame = None
1864htmlFirstUse = True
1865helpLocDict = {}
1866path2GSAS2 = os.path.dirname(os.path.realpath(__file__)) # save location of this file
1867def ShowHelp(helpType,frame):
1868    '''Called to bring up a web page for documentation.'''
1869    global htmlFirstUse
1870    # look up a definition for help info from dict
1871    helplink = helpLocDict.get(helpType)
1872    if helplink is None:
1873        # no defined link to use, create a default based on key
1874        helplink = 'gsasII.html#'+helpType.replace(' ','_')
1875    helplink = os.path.join(path2GSAS2,'help',helplink)
1876    # determine if a web browser or the internal viewer should be used for help info
1877    if GSASIIpath.GetConfigValue('Help_mode'):
1878        helpMode = GSASIIpath.GetConfigValue('Help_mode')
1879    else:
1880        helpMode = 'browser'
1881    if helpMode == 'internal':
1882        try:
1883            htmlPanel.LoadFile(helplink)
1884            htmlFrame.Raise()
1885        except:
1886            htmlFrame = wx.Frame(frame, -1, size=(610, 510))
1887            htmlFrame.Show(True)
1888            htmlFrame.SetTitle("HTML Window") # N.B. reset later in LoadFile
1889            htmlPanel = MyHtmlPanel(htmlFrame,-1)
1890            htmlPanel.LoadFile(helplink)
1891    else:
1892        pfx = "file://"
1893        if sys.platform.lower().startswith('win'):
1894            pfx = ''
1895        if htmlFirstUse:
1896            webbrowser.open_new(pfx+helplink)
1897            htmlFirstUse = False
1898        else:
1899            webbrowser.open(pfx+helplink, new=0, autoraise=True)
1900################################################################################
1901#### Tutorials selector
1902################################################################################
1903               
1904if __name__ == '__main__':
1905    app = wx.PySimpleApp()
1906    frm = wx.Frame(None) # create a frame
1907    frm.Show(True)
1908
1909    #======================================================================
1910    # test ScrolledMultiEditor
1911    #======================================================================
1912    # Data1 = {
1913    #      'Order':1,
1914    #      'omega':'string',
1915    #      'chi':2.0,
1916    #      'phi':'',
1917    #      }
1918    # elemlst = sorted(Data1.keys())
1919    # prelbl = sorted(Data1.keys())
1920    # dictlst = len(elemlst)*[Data1,]
1921    #Data2 = [True,False,False,True]
1922    #Checkdictlst = len(Data2)*[Data2,]
1923    #Checkelemlst = range(len(Checkdictlst))
1924    # print 'before',Data1,'\n',Data2
1925    # dlg = ScrolledMultiEditor(
1926    #     frm,dictlst,elemlst,prelbl,
1927    #     checkdictlst=Checkdictlst,checkelemlst=Checkelemlst,
1928    #     checklabel="Refine?",
1929    #     header="test")
1930    # if dlg.ShowModal() == wx.ID_OK:
1931    #     print "OK"
1932    # else:
1933    #     print "Cancel"
1934    # print 'after',Data1,'\n',Data2
1935    # dlg.Destroy()
1936    Data3 = {
1937         'Order':1.0,
1938         'omega':1.1,
1939         'chi':2.0,
1940         'phi':2.3,
1941         'Order1':1.0,
1942         'omega1':1.1,
1943         'chi1':2.0,
1944         'phi1':2.3,
1945         'Order2':1.0,
1946         'omega2':1.1,
1947         'chi2':2.0,
1948         'phi2':2.3,
1949         }
1950    elemlst = sorted(Data3.keys())
1951    dictlst = len(elemlst)*[Data3,]
1952    prelbl = elemlst[:]
1953    prelbl[0]="this is a much longer label to stretch things out"
1954    Data2 = len(elemlst)*[False,]
1955    Data2[1] = Data2[3] = True
1956    Checkdictlst = len(elemlst)*[Data2,]
1957    Checkelemlst = range(len(Checkdictlst))
1958    #print 'before',Data3,'\n',Data2
1959    #print dictlst,"\n",elemlst
1960    #print Checkdictlst,"\n",Checkelemlst
1961    dlg = ScrolledMultiEditor(
1962        frm,dictlst,elemlst,prelbl,
1963        checkdictlst=Checkdictlst,checkelemlst=Checkelemlst,
1964        checklabel="Refine?",
1965        header="test",CopyButton=True)
1966    if dlg.ShowModal() == wx.ID_OK:
1967        print "OK"
1968    else:
1969        print "Cancel"
1970    #print 'after',Data3,'\n',Data2
1971
1972    # Data2 = list(range(100))
1973    # elemlst += range(2,6)
1974    # postlbl += range(2,6)
1975    # dictlst += len(range(2,6))*[Data2,]
1976
1977    # prelbl = range(len(elemlst))
1978    # postlbl[1] = "a very long label for the 2nd item to force a horiz. scrollbar"
1979    # header="""This is a longer\nmultiline and perhaps silly header"""
1980    # dlg = ScrolledMultiEditor(frm,dictlst,elemlst,prelbl,postlbl,
1981    #                           header=header,CopyButton=True)
1982    # print Data1
1983    # if dlg.ShowModal() == wx.ID_OK:
1984    #     for d,k in zip(dictlst,elemlst):
1985    #         print k,d[k]
1986    # dlg.Destroy()
1987    # if CallScrolledMultiEditor(frm,dictlst,elemlst,prelbl,postlbl,
1988    #                            header=header):
1989    #     for d,k in zip(dictlst,elemlst):
1990    #         print k,d[k]
1991
1992    #======================================================================
1993    # test G2MultiChoiceDialog
1994    #======================================================================
1995    # choices = []
1996    # for i in range(21):
1997    #     choices.append("option_"+str(i))
1998    # dlg = G2MultiChoiceDialog(frm, 'Sequential refinement',
1999    #                           'Select dataset to include',
2000    #                           choices)
2001    # sel = range(2,11,2)
2002    # dlg.SetSelections(sel)
2003    # dlg.SetSelections((1,5))
2004    # if dlg.ShowModal() == wx.ID_OK:
2005    #     for sel in dlg.GetSelections():
2006    #         print sel,choices[sel]
2007   
2008    #======================================================================
2009    # test wx.MultiChoiceDialog
2010    #======================================================================
2011    # dlg = wx.MultiChoiceDialog(frm, 'Sequential refinement',
2012    #                           'Select dataset to include',
2013    #                           choices)
2014    # sel = range(2,11,2)
2015    # dlg.SetSelections(sel)
2016    # dlg.SetSelections((1,5))
2017    # if dlg.ShowModal() == wx.ID_OK:
2018    #     for sel in dlg.GetSelections():
2019    #         print sel,choices[sel]
2020
2021    pnl = wx.Panel(frm)
2022    siz = wx.BoxSizer(wx.VERTICAL)
2023
2024    td = {'Goni':200.,'a':1.,'calc':1./3.,'string':'s'}
2025    for key in sorted(td):
2026        txt = ValidatedTxtCtrl(pnl,td,key)
2027        siz.Add(txt)
2028    pnl.SetSizer(siz)
2029    siz.Fit(frm)
2030    app.MainLoop()
2031    print td
Note: See TracBrowser for help on using the repository browser.