class ReproTestDialog(wx.Dialog):
    def __init__(self, parent):
        self.node = parent.node

        wx.Dialog.__init__(self, parent, -1, 'Test Reproducibiltiy')

        self.measure = wx.Button(self, -1, 'Run')
        self.Bind(wx.EVT_BUTTON, self.onMeasureButton, self.measure)

        szbutton = wx.GridBagSizer(5, 5)
        szbutton.Add(self.measure, (0, 0), (1, 1), wx.EXPAND)

        sbsz = wx.GridBagSizer(5, 5)

        label = wx.StaticText(self, -1, 'Label:')
        self.labvalue = Entry(self, -1, chars=20, value='test1')
        sbsz.Add(label, (0, 0), (1, 1))
        sbsz.Add(self.labvalue, (0, 1), (1, 1))

        label = wx.StaticText(self, -1, 'Moves:')
        self.movesvalue = IntEntry(self,
                                   -1,
                                   allownone=False,
                                   chars=5,
                                   value='10')
        sbsz.Add(label, (1, 0), (1, 1))
        sbsz.Add(self.movesvalue, (1, 1), (1, 1))

        label = wx.StaticText(self, -1, 'Distance:')
        self.distvalue = FloatEntry(self,
                                    -1,
                                    allownone=False,
                                    chars=5,
                                    value='1e-5')
        sbsz.Add(label, (2, 0), (1, 1))
        sbsz.Add(self.distvalue, (2, 1), (1, 1))

        label = wx.StaticText(self, -1, 'Angle:')
        self.angvalue = FloatEntry(self, -1, allownone=True, chars=5, value='')
        sbsz.Add(label, (3, 0), (1, 1))
        sbsz.Add(self.angvalue, (3, 1), (1, 1))

        self.sizer = wx.GridBagSizer(5, 5)
        self.sizer.Add(sbsz, (0, 0), (1, 1), wx.EXPAND | wx.ALL, 10)
        self.sizer.Add(self.measure, (1, 0), (1, 1),
                       wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 10)

        self.SetSizerAndFit(self.sizer)

    def onMeasureButton(self, evt):
        self.Close()
        label = self.labvalue.GetValue()
        moves = self.movesvalue.GetValue()
        distance = self.distvalue.GetValue()
        angle = self.angvalue.GetValue()
        threading.Thread(target=self.node.move_away_move_back,
                         args=(label, moves, distance, angle)).start()
class Panel(GridSelectionPanel):
    def setDefaultGridSelection(self):
        self.default_gridlabel = '--New Grid as Below--'

    def addNew(self):
        self.createNewGridEntry((1, 0))

    def enableNew(self, gridlabel):
        # enable entry of new grid
        if gridlabel != self.default_gridlabel:
            self.newgrid.Enable(False)
        else:
            self.newgrid.Enable(True)

    def runNew(self):
        self.onSaveNewGrid(None)

    def createNewGridEntry(self, start_position):
        sb = wx.StaticBox(self, -1, 'New Grid')
        sbsz = wx.StaticBoxSizer(sb, wx.VERTICAL)
        szgrid = wx.GridBagSizer(5, 5)
        label = wx.StaticText(self, -1, 'New Grid Name:')
        szgrid.Add(label, (0, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        self.newgrid = Entry(self, -1)
        szgrid.Add(self.newgrid, (0, 1), (1, 1),
                   wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)

        self.savenewgrid = wx.Button(self, wx.ID_APPLY)

        szgrid.Add(self.savenewgrid, (2, 0), (1, 2), wx.ALIGN_CENTER_VERTICAL)

        szgrid.AddGrowableCol(1)
        sbsz.Add(szgrid, 0, wx.EXPAND | wx.ALL, 5)
        self.szmain.Add(sbsz, start_position, (1, 1),
                        wx.EXPAND | wx.ALL | wx.ALIGN_CENTER_VERTICAL)

    def onNodeInitialized(self):
        super(Panel, self).onNodeInitialized()
        self.Bind(wx.EVT_BUTTON, self.onSaveNewGrid, self.savenewgrid)

    def onSaveNewGrid(self, evt=None):
        choices = self.node.getGridNames()
        newgrid = self.newgrid.Update()
        newgrid = self.newgrid.GetValue()
        if newgrid is None or newgrid == '':
            self.node.onBadEMGridName('No Grid Name')
            return
        elif newgrid in choices:
            self.node.onBadEMGridName('Grid Name Exists')
            return
        else:
            self.node.publishNewEMGrid(newgrid)
        self.refreshGrids()
Beispiel #3
0
class CameraPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, -1)
        sb = wx.StaticBox(self, -1, 'Camera Configuration')
        self.sbsz = wx.StaticBoxSizer(sb, wx.VERTICAL)
        self.size = None
        self.binmethod = 'exact'
        self.geometry = None
        self.binnings = {'x': [1, 2, 3, 4, 6, 8], 'y': [1, 2, 3, 4, 6, 8]}
        self.defaultexptime = 1000.0
        self.defaultsaveframes = False
        self.defaultframetime = 200
        self.defaultalignframes = False
        self.defaultalignfilter = 'None'
        self.defaultuseframes = ''
        self.defaultreadoutdelay = 0
        self.common = {}
        self.setfuncs = {
            'exposure time': self._setExposureTime,
            'save frames': self._setSaveFrames,
            'frame time': self._setFrameTime,
            'align frames': self._setAlignFrames,
            'align filter': self._setAlignFilter,
            'use frames': self._setUseFrames,
            'readout delay': self._setReadoutDelay,
        }
        self.getfuncs = {
            'exposure time': self._getExposureTime,
            'save frames': self._getSaveFrames,
            'frame time': self._getFrameTime,
            'align frames': self._getAlignFrames,
            'align filter': self._getAlignFilter,
            'use frames': self._getUseFrames,
            'readout delay': self._getReadoutDelay,
        }

        # geometry
        self.ccommon = wx.Choice(self, -1, choices=['(None)'])
        self.ccommon.SetSelection(0)
        bcustom = wx.Button(self, -1, 'Custom...')

        std = wx.StaticText(self, -1, 'Dimension:')
        self.stdimension = wx.StaticText(self, -1, '')

        sto = wx.StaticText(self, -1, 'Offset:')
        self.stoffset = wx.StaticText(self, -1, '')

        stb = wx.StaticText(self, -1, 'Binning:')
        self.stbinning = wx.StaticText(self, -1, '')

        self.szmain = wx.GridBagSizer(3, 3)

        sz = wx.GridBagSizer(5, 5)
        sz.Add(self.ccommon, (0, 0), (1, 1),
               wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
        sz.Add(bcustom, (0, 1), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        sz.AddGrowableRow(0)
        sz.AddGrowableCol(0)
        sz.AddGrowableCol(1)
        self.szmain.Add(sz, (0, 0), (1, 2), wx.EXPAND)

        self.szmain.Add(std, (1, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        self.szmain.Add(self.stdimension, (1, 1), (1, 1), wx.ALIGN_CENTER)

        self.szmain.Add(sto, (2, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        self.szmain.Add(self.stoffset, (2, 1), (1, 1), wx.ALIGN_CENTER)

        self.szmain.Add(stb, (3, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        self.szmain.Add(self.stbinning, (3, 1), (1, 1), wx.ALIGN_CENTER)

        # exposure time
        stet = wx.StaticText(self, -1, 'Exposure time:')
        self.feexposuretime = FloatEntry(self, -1, min=0.0, chars=7)
        stms = wx.StaticText(self, -1, 'ms')

        self.szmain.Add(stet, (4, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        sz = wx.GridBagSizer(0, 3)
        sz.Add(self.feexposuretime, (0, 0), (1, 1),
               wx.ALIGN_CENTER_VERTICAL | wx.FIXED_MINSIZE)
        sz.Add(stms, (0, 1), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        self.szmain.Add(sz, (4, 1), (1, 2), wx.ALIGN_CENTER | wx.EXPAND)

        sb = wx.StaticBox(self, -1, 'Camera with Movie Mode')
        ddsb = wx.StaticBoxSizer(sb, wx.VERTICAL)
        ddsz = wx.GridBagSizer(5, 5)
        # save frames
        self.saveframes = wx.CheckBox(self, -1, 'Save frames')
        ddsz.Add(self.saveframes, (0, 0), (1, 2), wx.ALIGN_CENTER | wx.EXPAND)

        # frame time
        stet = wx.StaticText(self, -1, 'Exposure time per Frame:')
        self.frametime = FloatEntry(self, -1, min=0.01, chars=7)
        stms = wx.StaticText(self, -1, 'ms')

        ddsz.Add(stet, (1, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        ftsz = wx.GridBagSizer(0, 3)
        ftsz.Add(self.frametime, (0, 0), (1, 1),
                 wx.ALIGN_CENTER_VERTICAL | wx.FIXED_MINSIZE)
        ftsz.Add(stms, (0, 1), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        ddsz.Add(ftsz, (1, 1), (1, 2), wx.ALIGN_CENTER | wx.EXPAND)
        # use raw frames
        label = wx.StaticText(self, -1, 'Frames to use:')
        self.useframes = Entry(self, -1)
        ddsz.Add(label, (2, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        ddsz.Add(self.useframes, (2, 1), (1, 1), wx.ALIGN_CENTER | wx.EXPAND)

        # readout delay
        strd = wx.StaticText(self, -1, 'Readout delay:')
        self.readoutdelay = IntEntry(self, -1, chars=7)
        stms = wx.StaticText(self, -1, 'ms')
        sz = wx.BoxSizer(wx.HORIZONTAL)
        sz.Add(strd)
        sz.Add(self.readoutdelay)
        sz.Add(stms)
        ddsz.Add(sz, (3, 0), (1, 2), wx.ALIGN_CENTER | wx.EXPAND)

        # align frames box
        sb = wx.StaticBox(self, -1, 'Frame-Aligning Camera Only')
        afsb = wx.StaticBoxSizer(sb, wx.VERTICAL)
        afsz = wx.GridBagSizer(3, 3)
        # align frames
        self.alignframes = wx.CheckBox(self, -1, 'Align frames')
        afsz.Add(self.alignframes, (0, 0), (1, 2), wx.ALIGN_CENTER | wx.EXPAND)

        # align frame filter
        label = wx.StaticText(self, -1, 'c-correlation filter:')
        self.alignfilter = wx.Choice(self, -1, choices=self.getAlignFilters())
        self.alignfilter.SetSelection(0)
        afsz.Add(label, (1, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        afsz.Add(self.alignfilter, (1, 1), (1, 1), wx.ALIGN_CENTER | wx.EXPAND)
        afsb.Add(afsz, 0, wx.EXPAND | wx.ALL, 2)

        ddsz.Add(afsb, (4, 0), (3, 2), wx.ALIGN_CENTER | wx.EXPAND)

        ddsb.Add(ddsz, 0, wx.EXPAND | wx.ALL, 2)
        self.szmain.Add(ddsb, (7, 0), (1, 3), wx.ALIGN_CENTER | wx.EXPAND)

        ddsz.AddGrowableCol(1)
        self.szmain.AddGrowableCol(1)
        self.szmain.AddGrowableCol(2)

        self.sbsz.Add(self.szmain, 0, wx.EXPAND | wx.ALL, 2)

        self.SetSizerAndFit(self.sbsz)

        self.Bind(wx.EVT_CHOICE, self.onCommonChoice, self.ccommon)
        self.Bind(wx.EVT_BUTTON, self.onCustomButton, bcustom)
        self.Bind(EVT_ENTRY, self.onExposureTime, self.feexposuretime)
        self.Bind(wx.EVT_CHECKBOX, self.onSaveFrames, self.saveframes)
        self.Bind(EVT_ENTRY, self.onFrameTime, self.frametime)
        self.Bind(EVT_ENTRY, self.onUseFrames, self.useframes)
        self.Bind(EVT_ENTRY, self.onReadoutDelay, self.readoutdelay)
        self.Bind(EVT_SET_CONFIGURATION, self.onSetConfiguration)

        #self.Enable(False)

    def setGeometryLimits(self, limitdict):
        if limitdict is None:
            self.setSize(None)
        if 'binnings' in limitdict.keys():
            self.binnings['x'] = limitdict['binnings']
            self.binnings['y'] = limitdict['binnings']
        if 'binmethod' in limitdict.keys():
            self.binmethod = limitdict['binmethod']
        if 'size' in limitdict.keys():
            self.setSize(limitdict['size'])
        else:
            self.setSize(None)

    def setSize(self, size):
        if size is None:
            self.size = None
            self.Freeze()
            self.choices, self.common = None, None
            self.ccommon.Clear()
            self.ccommon.Append('(None)')
            self.szmain.Layout()
            #self.Enable(False)
            self.Thaw()
        else:
            self.size = dict(size)
            self.Freeze()
            self.choices, self.common = self.getCenteredGeometries()
            self.ccommon.Clear()
            self.ccommon.AppendItems(self.choices)
            if self.geometry is None or not self.validateGeometry():
                self.ccommon.SetSelection(len(self.choices) - 1)
                self.setGeometry(
                    self.common[self.ccommon.GetStringSelection()])
            else:
                self.setCommonChoice()
            if self.feexposuretime.GetValue() is None:
                self.feexposuretime.SetValue(self.defaultexptime)
            #self.Enable(True)
            self.szmain.Layout()
            self.Thaw()

    def clear(self):
        if self.size is None:
            return
        self.Freeze()
        self.ccommon.SetSelection(len(self.choices) - 1)
        self.setGeometry(self.common[self.ccommon.GetStringSelection()])
        self.feexposuretime.SetValue(self.defaultexptime)
        self.saveframes.SetValue(self.defaultsaveframes)
        self.frametime.SetValue(self.defaultframetime)
        self.alignframes.SetValue(self.defaultalignframes)
        self.alignfilter.SetValue(self.defaultalignfilter)
        self.useframes.SetValue(self.defaultuseframes)
        self.readoutdelay.SetValue(self.defaultreadoutdelay)
        #self.Enable(False)
        self.Thaw()

    def onConfigurationChanged(self):
        evt = ConfigurationChangedEvent(self.getConfiguration(), self)
        self.GetEventHandler().AddPendingEvent(evt)

    def onExposureTime(self, evt):
        self.onConfigurationChanged()

    def onSaveFrames(self, evt):
        self.onConfigurationChanged()

    def onFrameTime(self, evt):
        self.onConfigurationChanged()

    def onUseFrames(self, evt):
        self.onConfigurationChanged()

    def onReadoutDelay(self, evt):
        self.onConfigurationChanged()

    def setCommonChoice(self):
        for key, geometry in self.common.items():
            flag = True
            for i in ['dimension', 'offset', 'binning']:
                if self.geometry[i] != geometry[i]:
                    flag = False
                    break
            if flag:
                self.ccommon.SetStringSelection(key)
                return
        if self.ccommon.FindString('(Custom)') is wx.NOT_FOUND:
            self.ccommon.Insert('(Custom)', 0)
            self.ccommon.SetSelection(0)

    def _getDimension(self):
        return self.geometry['dimension']

    def _setDimension(self, value):
        self.geometry['dimension'] = value
        self.setCommonChoice()

    def _getOffset(self):
        return self.geometry['offset']

    def _setOffset(self, value):
        self.geometry['offset'] = value
        self.setCommonChoice()

    def _getBinning(self):
        return self.geometry['binning']

    def _setBinning(self, value):
        self.geometry['binning'] = value
        self.setCommonChoice()

    def _getExposureTime(self):
        return self.feexposuretime.GetValue()

    def _setExposureTime(self, value):
        self.feexposuretime.SetValue(value)

    def _getSaveFrames(self):
        return self.saveframes.GetValue()

    def _setSaveFrames(self, value):
        value = bool(value)
        self.saveframes.SetValue(value)

    def _getFrameTime(self):
        return self.frametime.GetValue()

    def _setFrameTime(self, value):
        self.frametime.SetValue(value)

    def _getAlignFrames(self):
        return self.alignframes.GetValue()

    def _setAlignFrames(self, value):
        value = bool(value)
        self.alignframes.SetValue(value)

    def getAlignFilters(self):
        return [
            'None', 'Hanning Window (default)', 'Bandpass Filter (default)',
            'Sobel Filter (default)', 'Combined Filter (default)'
        ]

    def _getAlignFilter(self):
        return self.alignfilter.GetStringSelection()

    def _setAlignFilter(self, value):
        if value:
            value = str(value)
        else:
            value = 'None'
        self.alignfilter.SetStringSelection(value)

    def _getUseFrames(self):
        frames_str = self.useframes.GetValue()
        numbers = re.split('\D+', frames_str)
        numbers = filter(None, numbers)
        if numbers:
            numbers = map(int, numbers)
            numbers = tuple(numbers)
        else:
            numbers = ()
        return numbers

    def _setUseFrames(self, value):
        if value:
            value = str(value)
        else:
            value = ''
        self.useframes.SetValue(value)

    def _getReadoutDelay(self):
        return self.readoutdelay.GetValue()

    def _setReadoutDelay(self, value):
        return self.readoutdelay.SetValue(value)

    def onCommonChoice(self, evt):
        key = evt.GetString()
        if key == '(Custom)' or key.startswith('-'):
            return
        if self.setGeometry(self.common[key]):
            self.onConfigurationChanged()
        n = self.ccommon.FindString('(Custom)')
        if n is not wx.NOT_FOUND:
            self.ccommon.Delete(n)

    def onCustomButton(self, evt):
        dialog = CustomDialog(self, self.getGeometry())
        if dialog.ShowModal() == wx.ID_OK:
            if self.setGeometry(dialog.getGeometry()):
                self.onConfigurationChanged()
            self.setCommonChoice()
        dialog.Destroy()

    def getCenteredGeometry(self, dimension, binning):
        offset = {}
        for axis in ['x', 'y']:
            offset[axis] = int((self.size[axis] / binning - dimension) / 2)

        geometry = {
            'dimension': {
                'x': dimension,
                'y': dimension
            },
            'offset': {
                'x': offset['x'],
                'y': offset['y']
            },
            'binning': {
                'x': binning,
                'y': binning
            }
        }
        return geometry

    def getFullGeometry(self, binning):
        if self.binmethod == 'exact' and ((self.size['x'] % binning) or
                                          (self.size['y'] % binning)):
            return None
        dimx = self.size['x'] / binning
        dimy = self.size['y'] / binning
        geometry = {
            'dimension': {
                'x': dimx,
                'y': dimy
            },
            'offset': {
                'x': 0,
                'y': 0
            },
            'binning': {
                'x': binning,
                'y': binning
            }
        }
        return geometry

    def getCenteredGeometries(self):
        geometries = {}
        keys = []
        show_sections = False
        if self.size['x'] != self.size['y']:
            show_sections = True
            keys.append('--- Full ---')
            for binning in self.binnings['x']:
                dimx = self.size['x'] / binning
                dimy = self.size['y'] / binning
                key = '%d x %d bin %d' % (dimx, dimy, binning)
                geo = self.getFullGeometry(binning)
                if geo is not None:
                    geometries[key] = geo
                    keys.append(key)
        if self.binnings['x'] != self.binnings['y']:
            return geometries
        self.minsize = min(self.size['x'], self.size['y'])
        dimensions = [int(self.minsize / float(b)) for b in self.binnings['x']]

        def good(dim):
            return not bool(numpy.modf(dim)[1] - dim)

        def filtergood(input, mask):
            result = []
            for i, inval in enumerate(input):
                if mask[i]:
                    result.append(inval)
            return result

        if self.binmethod == 'exact':
            mask = [good(dim) for dim in dimensions]
        else:
            mask = [True for dim in dimensions]
        dimensions = filtergood(dimensions, mask)

        def minsize(size):
            return size >= self.minsize / max(self.binnings['x'])

        dimensions = filter(minsize, dimensions)
        dimensions = map((lambda x: primefactor.getAllEvenPrimes(x)[-1]),
                         dimensions)
        binnings = filtergood(self.binnings['x'], mask)
        dimensions.reverse()
        if show_sections:
            keys.append('--- Center ---')
        for d in dimensions:
            for b in self.binnings['x']:
                if d * b <= self.minsize:
                    key = '%d x %d bin %d' % (d, d, b)
                    geometries[key] = self.getCenteredGeometry(d, b)
                    keys.append(key)
                else:
                    break
        return keys, geometries

    def validateGeometry(self, geometry=None):
        if geometry is None:
            geometry = self.geometry
        for a in ['x', 'y']:
            try:
                if geometry['dimension'][a] < 1 or geometry['offset'][a] < 0:
                    return False
                if geometry['binning'][a] not in self.binnings[a]:
                    return False
                size = geometry['dimension'][a] + geometry['offset'][a]
                size *= geometry['binning'][a]
                if size > self.size[a]:
                    return False
            except:
                return False
        return True

    def cmpGeometry(self, geometry):
        if self.geometry == geometry:
            return True
        for g in ['dimension', 'offset', 'binning']:
            try:
                for a in ['x', 'y']:
                    if self.geometry[g][a] != geometry[g][a]:
                        return False
            except (KeyError, TypeError):
                return False
        return True

    def setGeometry(self, geometry):
        if self.cmpGeometry(geometry):
            return False

        if self.size is not None and not self.validateGeometry(geometry):
            raise ValueError

        self._setGeometry(geometry)

        return True

    def getGeometry(self):
        return self.geometry

    def getConfiguration(self):
        g = self.getGeometry()
        if g is None:
            return None
        c = copy.deepcopy(g)
        for key, func in self.getfuncs.items():
            c[key] = func()
        return c

    def _setGeometry(self, geometry):
        if self.geometry is None:
            self.geometry = {}
        else:
            self.geometry = copy.deepcopy(self.geometry)
        self.Freeze()
        for g in ['dimension', 'offset', 'binning']:
            if g not in self.geometry:
                self.geometry[g] = {}
            try:
                self.geometry[g].update(dict(geometry[g]))
                if g == 'offset':
                    label = '(%d, %d)'
                else:
                    #label = '%d × %d'
                    label = '%d x %d'
                label = label % (self.geometry[g]['x'], self.geometry[g]['y'])
                getattr(self, 'st' + g).SetLabel(label)
            except:
                pass
        self.szmain.Layout()
        self.Thaw()
        return True

    def _setConfiguration(self, value):
        for key, func in self.setfuncs.items():
            if key in value:
                func(value[key])
        self._setGeometry(value)
        self.setCommonChoice()

    def setConfiguration(self, value):
        for key, func in self.setfuncs.items():
            if key in value:
                func(value[key])
        self.setGeometry(value)
        if self.size is not None:
            self.setCommonChoice()
        #if not self.IsEnabled():
        #       self.Enable(True)

    def onSetConfiguration(self, evt):
        self.setConfiguration(evt.configuration)
class Panel(leginon.gui.wx.GridEntry.GridSelectionPanel):
    #icon = 'robot'
    def setDefaultGridSelection(self):
        self.default_gridlabel = '--Not-specified--'

    def addNew(self):
        self.createNewGridFromPlate((2, 0))
        self.createNewPlateSelector((4, 0))

    def runNew(self):
        self.node.onBadEMGridName('No Grid')

    def createNewGridFromPlate(self, start_position):
        sb = wx.StaticBox(self, -1, 'New Grid Batch')
        sbsz = wx.StaticBoxSizer(sb, wx.VERTICAL)
        szgrid = wx.GridBagSizer(5, 5)
        label = wx.StaticText(self, -1, 'Select a Grid Format (r x c:skips):')
        szgrid.Add(label, (0, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
        self.cgridformat = wx.Choice(self, -1)
        self.cgridformat.Enable(False)
        szgrid.Add(self.cgridformat, (0, 1), (1, 1), wx.ALIGN_CENTER_VERTICAL)

        label = wx.StaticText(self, -1, 'Select a plate in the project')
        szgrid.Add(label, (1, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)

        self.cplate = wx.Choice(self, -1)
        self.cplate.Enable(False)

        szgrid.Add(self.cplate, (1, 1), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        self.savenewgrid = wx.Button(self, wx.ID_APPLY)

        szgrid.Add(self.savenewgrid, (2, 0), (1, 2), wx.ALIGN_CENTER_VERTICAL)

        szgrid.AddGrowableCol(1)
        sbsz.Add(szgrid, 0, wx.EXPAND | wx.ALL, 5)
        self.szmain.Add(sbsz, start_position, (1, 1),
                        wx.EXPAND | wx.ALL | wx.ALIGN_CENTER_VERTICAL)

    def createNewPlateSelector(self, start_position):
        sb = wx.StaticBox(self, -1, 'New Prep Plate')
        sbsz = wx.StaticBoxSizer(sb, wx.VERTICAL)
        szplate = wx.GridBagSizer(5, 5)
        # plate format
        label = wx.StaticText(self, -1, 'Plate Format:')
        szplate.Add(label, (0, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        self.cplateformat = wx.Choice(self, -1)
        self.cplateformat.Enable(False)
        szplate.Add(self.cplateformat, (0, 1), (1, 1),
                    wx.ALIGN_CENTER_VERTICAL)
        # plate name
        label = wx.StaticText(self, -1, 'New Plate Name:')
        szplate.Add(label, (1, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        self.newplate = Entry(self, -1)
        szplate.Add(self.newplate, (1, 1), (1, 1),
                    wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)

        self.savenewplate = wx.Button(self, wx.ID_SAVE)

        szplate.Add(self.savenewplate, (2, 0), (1, 2),
                    wx.ALIGN_CENTER_VERTICAL)

        szplate.AddGrowableCol(1)
        sbsz.Add(szplate, 0, wx.EXPAND | wx.ALL, 5)
        self.szmain.Add(sbsz, start_position, (1, 1),
                        wx.EXPAND | wx.ALL | wx.ALIGN_CENTER_VERTICAL)

    def onNodeInitialized(self):
        super(Panel, self).onNodeInitialized()

        self.Bind(wx.EVT_BUTTON, self.onSaveNewGrids, self.savenewgrid)
        self.Bind(wx.EVT_CHOICE, self.onGridFormatChoice, self.cgridformat)
        self.Bind(wx.EVT_CHOICE, self.onPlateChoice, self.cplate)
        self.Bind(wx.EVT_CHOICE, self.onPlateFormatChoice, self.cplateformat)
        self.Bind(wx.EVT_BUTTON, self.onSaveNewPlate, self.savenewplate)
        self.refreshNewGrids()
        self.refreshPlates()

    def onSaveNewGrids(self, evt=None):
        self.cplate.Update()
        plate = self.cplate.GetStringSelection()
        if plate is None or plate == '':
            self.node.onBadEMGridName('No Plate')
            return
        if plate == '--New Plate as Below--':
            # save the new plate entry and then update the value
            status = self.onSaveNewPlate()
            if status is False:
                return
            plate = self.cplate.GetStringSelection()
        self.cgridformat.Update()
        gformat = self.cgridformat.GetStringSelection()
        if gformat is None or gformat == '':
            self.node.onBadEMGridName('No Grid Format')
            return
        else:
            self.node.publishNewEMGrids(gformat, plate)
        self.refreshGrids()

    def onGridFormatChoice(self, evt=None):
        if evt is None:
            formatlabel = self.cgridformat.GetStringSelection()
        else:
            formatlabel = evt.GetString()
        settings = self.node.getSettings()
        settings['grid format name'] = formatlabel
        self.node.setSettings(settings)
        self.newplate.Enable(False)

    def onPlateFormatChoice(self, evt=None):
        if evt is None:
            formatlabel = self.cplateformat.GetStringSelection()
        else:
            formatlabel = evt.GetString()
        settings = self.node.getSettings()
        settings['plate format name'] = formatlabel
        self.node.setSettings(settings)
        self.newplate.Enable(True)

    def setGridFormatSelection(self, choices):
        if choices:
            self.cgridformat.Clear()
            self.cgridformat.AppendItems(choices)
            if self.node.settings['grid format name']:
                n = self.cgridformat.FindString(
                    self.node.settings['grid format name'])
            else:
                n = wx.NOT_FOUND
            if n == wx.NOT_FOUND:
                self.cgridformat.SetSelection(0)
            else:
                self.cgridformat.SetSelection(n)
            self.cgridformat.Enable(True)
            self.onGridFormatChoice()

    def setPlateFormatSelection(self, choices):
        if choices:
            self.cplateformat.Clear()
            self.cplateformat.AppendItems(choices)
            if self.node.settings['plate format name']:
                n = self.cplateformat.FindString(
                    self.node.settings['plate format name'])
            else:
                n = wx.NOT_FOUND
            if n == wx.NOT_FOUND:
                self.cplateformat.SetSelection(0)
            else:
                self.cplateformat.SetSelection(n)
            self.cplateformat.Enable(True)
            self.onPlateFormatChoice()

    def onSaveNewPlate(self, evt=None):
        choices = self.node.getPlateNames()
        self.newplate.Update()
        newplate = self.newplate.GetValue()
        if newplate is None or newplate == '':
            self.node.onBadPlateName('No Plate Name')
            return False
        elif newplate in choices:
            self.node.onBadPlateName('Plate Name Exists')
            return False
        choices = self.node.getPlateFormats()
        self.cplateformat.Update()
        pformat = self.cplateformat.GetStringSelection()
        if pformat is None or pformat == '':
            self.node.onBadPlateName('No Plate Format')
            return False
        else:
            self.node.publishNewPlate(newplate, pformat)
        self.refreshPlates()

    def onPlateChoice(self, evt=None):
        if evt is None:
            platelabel = self.cplate.GetStringSelection()
        else:
            platelabel = evt.GetString()
        settings = self.node.getSettings()
        settings['plate name'] = platelabel
        self.node.setSettings(settings)
        if platelabel != '--New Plate as Below--':
            self.newplate.Enable(False)
        else:
            self.newplate.Enable(True)

    def setPlateSelection(self, choices):
        if choices:
            self.cplate.Clear()
            self.cplate.AppendItems(choices)
            if self.node.settings['plate name']:
                n = self.cplate.FindString(self.node.settings['plate name'])
            else:
                n = wx.NOT_FOUND
            if n == wx.NOT_FOUND:
                self.cplate.SetSelection(0)
            else:
                self.cplate.SetSelection(n)
            self.cplate.Enable(True)
            self.onPlateChoice()

    def onRefreshGridsButton(self, evt):
        self.refreshGrids()
        self.refreshNewGrids()
        self.refreshPlates()

    def refreshNewGrids(self):
        choices = self.node.getGridFormats()
        self.setGridFormatSelection(choices)

    def refreshPlates(self):
        choices = self.node.getPlateNames()
        choices.insert(0, '--New Plate as Below--')
        self.setPlateSelection(choices)
        choices = self.node.getPlateFormats()
        self.setPlateFormatSelection(choices)
class Panel(leginon.gui.wx.Node.Panel):
    #icon = 'robot'
    def __init__(self, *args, **kwargs):
        leginon.gui.wx.Node.Panel.__init__(self, *args, **kwargs)

        self.toolbar.AddTool(leginon.gui.wx.ToolBar.ID_SETTINGS,
                             'settings',
                             shortHelpString='Start')
        self.toolbar.AddSeparator()
        self.toolbar.AddTool(leginon.gui.wx.ToolBar.ID_PLAY,
                             'play',
                             shortHelpString='Start')
        self.toolbar.AddSeparator()
        self.toolbar.AddTool(leginon.gui.wx.ToolBar.ID_REFRESH,
                             'refresh',
                             shortHelpString='Refresh Grid List')

        self.cgrid = wx.Choice(self, -1)
        self.cgrid.Enable(False)
        szgrid = wx.GridBagSizer(5, 5)
        label = wx.StaticText(self, -1, 'Grids in the project')
        szgrid.Add(label, (0, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        szgrid.Add(self.cgrid, (0, 1), (1, 1), wx.ALIGN_CENTER_VERTICAL)

        label = wx.StaticText(self, -1, 'New Grid Name:')
        szgrid.Add(label, (1, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        self.newgrid = Entry(self, -1)
        szgrid.Add(self.newgrid, (1, 1), (1, 1),
                   wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
        self.savenewgrid = wx.Button(self, wx.ID_APPLY)
        szgrid.Add(self.savenewgrid, (1, 2), (1, 1), wx.ALIGN_CENTER_VERTICAL)

        self.szmain.Add(szgrid, (0, 0), (1, 1), wx.ALIGN_CENTER)
        self.szmain.AddGrowableCol(0)

        self.SetSizer(self.szmain)
        self.SetAutoLayout(True)
        self.SetupScrolling()

    def onNodeInitialized(self):
        self.toolbar.Bind(wx.EVT_TOOL,
                          self.onSettingsTool,
                          id=leginon.gui.wx.ToolBar.ID_SETTINGS)
        self.toolbar.Bind(wx.EVT_TOOL,
                          self.onPlayTool,
                          id=leginon.gui.wx.ToolBar.ID_PLAY)
        self.toolbar.Bind(wx.EVT_TOOL,
                          self.onRefreshGridsButton,
                          id=leginon.gui.wx.ToolBar.ID_REFRESH)

        self.Bind(wx.EVT_CHOICE, self.onGridChoice, self.cgrid)
        self.Bind(wx.EVT_BUTTON, self.onSaveNewGrid, self.savenewgrid)
        self.refreshGrids()

    def onSaveNewGrid(self, evt=None):
        choices = self.node.getGridNames()
        newgrid = self.newgrid.Update()
        newgrid = self.newgrid.GetValue()
        if newgrid is None or newgrid == '':
            self.node.onBadEMGridName('No Grid Name')
            return
        elif newgrid in choices:
            self.node.onBadEMGridName('Grid Name Exists')
            return
        else:
            self.node.publishNewEMGrid(newgrid)
        self.refreshGrids()

    def onGridChoice(self, evt=None):
        if evt is None:
            gridlabel = self.cgrid.GetStringSelection()
        else:
            gridlabel = evt.GetString()
        settings = self.node.getSettings()
        settings['grid name'] = gridlabel
        self.node.setSettings(settings)
        if gridlabel != '--New Grid as Below--':
            self.newgrid.Enable(False)
        else:
            self.newgrid.Enable(True)

    def setGridSelection(self, choices):
        if choices:
            self.cgrid.Clear()
            self.cgrid.AppendItems(choices)
            if self.node.settings['grid name']:
                n = self.cgrid.FindString(self.node.settings['grid name'])
            else:
                n = wx.NOT_FOUND
            if n == wx.NOT_FOUND:
                self.cgrid.SetSelection(0)
            else:
                self.cgrid.SetSelection(n)
            self.cgrid.Enable(True)
            self.onGridChoice()

    def onSettingsTool(self, evt):
        dialog = SettingsDialog(self)
        dialog.ShowModal()
        dialog.Destroy()

    def onPlayTool(self, evt):
        gridlabel = self.cgrid.GetStringSelection()
        if gridlabel == '--New Grid as Below--':
            choices = self.node.getGridNames()
            newgrid = self.newgrid.Update()
            newgrid = self.newgrid.GetValue()
            if newgrid is None or newgrid == '':
                self.node.onBadEMGridName('No Grid Name')
                return
            elif newgrid in choices:
                self.node.onBadEMGridName('Grid Name Exists')
                return
            else:
                self.node.publishNewEMGrid(newgrid)
        self.refreshGrids()
        #self.toolbar.EnableTool(leginon.gui.wx.ToolBar.ID_PLAY, False)
        self.node.submitGrid()

    def onRefreshGridsButton(self, evt):
        self.refreshGrids

    def refreshGrids(self):
        choices = self.node.getGridNames()
        choices.insert(0, '--New Grid as Below--')
        self.setGridSelection(choices)

    def onGridDone(self):
        self.toolbar.EnableTool(leginon.gui.wx.ToolBar.ID_PLAY, True)