Exemple #1
0
	def __handle_keyword(self, kwd=None):
		try:
			create_widget = self.__popup_keywords[kwd]['widget_factory']
		except KeyError:
			gmDispatcher.send(signal='statustext', msg=_('No action configured for keyword [%s].') % kwd)
			return False

#		best_pos, best_size = self.__get_best_popup_geom()
		screen_pos = self.ClientToScreen(self.PointFromPosition(self.GetCurrentPos()))
		top_parent = wx.GetTopLevelParent(self)
		best_pos = top_parent.ScreenToClient(screen_pos)
		try:
			popup = create_widget (
				parent = top_parent,
				pos = best_pos,
				size = wx.Size(400, 300),
				style = wx.SUNKEN_BORDER,
				data_sink = self.__popup_keywords[kwd]['widget_data_sink']
			)
		except Exception:
			_log.exception('cannot call [%s] on keyword [%s] to create widget' % (create_widget, kwd))
			gmGuiHelpers.gm_show_error (
				aMessage = _('Cannot invoke [%s] for keyword [%s].') % (create_widget, kwd),
				aTitle = _('showing keyword popup')
			)
			return False

		if not isinstance(popup, wx.Dialog):
			gmDispatcher.send(signal='statustext', msg=_('Action [%s] on keyword [%s] is invalid.') % (create_widget, kwd))
			_log.error('keyword [%s] triggered action [%s]' % (kwd, create_widget))
			_log.error('the result (%s) is not a wx.Dialog subclass instance, however' % str(popup))
			return False

		# display widget
		result = popup.ShowModal()
		if result == wx.ID_OK:
			summary = popup.get_summary()
			wx.CallAfter(self.Embed, summary)
		popup.Destroy()
Exemple #2
0
    def __init__(self,
                 parent,
                 moveCallback=None,
                 cornerCallback=None,
                 spacebarCallback=None,
                 bgcolor="#FFFFFF",
                 ID=-1,
                 zcallback=None):
        self.bg_bmp = wx.Image(imagefile("control_xy.png"),
                               wx.BITMAP_TYPE_PNG).ConvertToBitmap()
        self.keypad_bmp = wx.Image(imagefile("arrow_keys.png"),
                                   wx.BITMAP_TYPE_PNG).ConvertToBitmap()
        self.keypad_idx = -1
        self.quadrant = None
        self.concentric = None
        self.corner = None
        self.moveCallback = moveCallback
        self.cornerCallback = cornerCallback
        self.spacebarCallback = spacebarCallback
        self.zCallback = zcallback
        self.enabled = False
        # Remember the last clicked buttons, so we can repeat when spacebar pressed
        self.lastMove = None
        self.lastCorner = None

        self.bgcolor = wx.Colour()
        self.bgcolor.SetFromName(bgcolor)
        self.bgcolormask = wx.Colour(self.bgcolor.Red(), self.bgcolor.Green(),
                                     self.bgcolor.Blue(), 128)

        BufferedCanvas.__init__(self, parent, ID, size=self.bg_bmp.GetSize())

        # Set up mouse and keyboard event capture
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDown)
        self.Bind(wx.EVT_MOTION, self.OnMotion)
        self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow)
        self.Bind(wx.EVT_KEY_UP, self.OnKey)
        wx.GetTopLevelParent(self).Bind(wx.EVT_CHAR_HOOK, self.OnTopLevelKey)
Exemple #3
0
    def menu(self):
        # Add 'View' menu to the menu bar and define its options.
        # Present y-axis plotting scales as radio buttons.
        # Grey out items that are not currently implemented.
        frame = wx.GetTopLevelParent(self)
        menu = wx.Menu()
        _item = menu.AppendRadioItem(wx.ID_ANY, "Li&near",
                                     "Plot y-axis in linear scale")
        _item.Check(True)
        frame.Bind(wx.EVT_MENU, self.OnLinear, _item)
        _item = menu.AppendRadioItem(wx.ID_ANY, "&Log",
                                     "Plot y-axis in log scale")
        frame.Bind(wx.EVT_MENU, self.OnLog, _item)

        menu.AppendSeparator()

        _item = menu.Append(wx.ID_ANY, "&Residuals",
                            "Show residuals on plot panel")
        frame.Bind(wx.EVT_MENU, self.OnResiduals, _item)
        menu.Enable(id=_item.GetId(), enable=True)

        return menu
Exemple #4
0
    def OnExtractMultiviewPSF(self, event):
        if (len(self.PSFLocs) > 0):
            from PYME.Analysis.PSFEst import extractImages

            psfROISize = [int(s) for s in self.tPSFROI.GetValue().split(',')]
            psfBlur = [float(s) for s in self.tPSFBlur.GetValue().split(',')]

            psfs = []

            for chnum in range(self.image.data.shape[3]):
                alignZ = (chnum > 0) and self.cbAlignZ.GetValue()
                #always align the first channel

                psf, offsets = extractImages.getPSF3D(
                    self.image.data[:, :, :, chnum],
                    self.PSFLocs,
                    psfROISize,
                    psfBlur,
                    centreZ=alignZ,
                    expand_z=self.cbExpandROI.GetValue())

                if self.cbBackgroundCorrect.GetValue():
                    #widefield image - do special background subtraction
                    psf = extractImages.backgroundCorrectPSFWF(psf)

                psfs.append(psf)

            from PYME.DSView.dsviewer import ImageStack, ViewIm3D
            from PYME.IO.MetaDataHandler import NestedClassMDHandler

            mdh = NestedClassMDHandler(self.image.mdh)
            self.write_metadata(mdh, 'Multiview')
            mdh['ImageType'] = 'PSF'

            im = ImageStack(data=psfs, mdh=mdh, titleStub='Extracted PSF')
            im.defaultExt = '*.tif'  #we want to save as PSF by default
            ViewIm3D(im,
                     mode='psf',
                     parent=wx.GetTopLevelParent(self.dsviewer))
Exemple #5
0
 def _bindUserStop(self):
     topParent = wx.GetTopLevelParent(self)
     if "keyboard_events" in self.configuration:
         items = []
         if 'stopTask' in self.configuration['keyboard_events']:
             userStopId = wx.NewId()
             items.append((wx.ACCEL_NORMAL, self.configuration['keyboard_events']['stopTask'], userStopId))
             topParent.Bind(wx.EVT_MENU, self.OnUserStop, id=userStopId)
         if 'scanOnce' in self.configuration['keyboard_events']:
             userScanOnceId = wx.NewId()
             items.append((wx.ACCEL_NORMAL, self.configuration['keyboard_events']['scanOnce'], userScanOnceId))
             topParent.Bind(wx.EVT_MENU, self.OnScanOnce, id=userScanOnceId)
         accel_tbl = wx.AcceleratorTable(items)
         topParent.SetAcceleratorTable(accel_tbl)
         # Map displays
         for mapw in self.giface.GetAllMapDisplays():
             mapw.Bind(wx.EVT_MENU, self.OnUserStop, id=userStopId)
             mapw.SetAcceleratorTable(accel_tbl)
         # Layer Manager
         lm = self.giface.lmgr
         lm.Bind(wx.EVT_MENU, self.OnUserStop, id=userStopId)
         lm.SetAcceleratorTable(accel_tbl)
 def RunSim(self):
     self.CheckConstraints()
 
     sim = Simulation(self)
     app = wx.GetTopLevelParent(self)
     try:
         sim.payload = float(app.Params.PayloadWeightControl.GetValue())
         sim.rvdiam = float(app.Params.RVControl.GetValue())
         sim.missilediam = float(app.Params.DiameterControl.GetValue())
         sim.numstages = int(app.Params.StageChoiceBox.GetSelection()+1)
         for i in range(1,sim.numstages+1):
             sim.fuelmass.append(float(app.Params.StageFuelMassCtrl[i].GetValue()))
             sim.m0.append(float(app.Params.StageDryMassCtrl[i].GetValue())+sim.fuelmass[i])
             sim.fuelfraction.append(float(sim.fuelmass[i]/sim.m0[i]))
             sim.Isp0.append(float(app.Params.StageIspCtrl[i].GetValue()))
             sim.thrust0.append(float(app.Params.StageThrustCtrl[i].GetValue())*9.81) #convert from kgf to N
             sim.dMdt.append(float(sim.thrust0[i]/(sim.Isp0[i]*9.81)))
         trajectory = app.Params.TrajectoryChoiceBox.GetStringSelection()
         if trajectory == "Minimum Energy":
             sim.est_range = float(app.Params.EstRangeControl.GetValue())*1000 #convert to m
         if trajectory == 'Thrust Vector':
             sim.TStartTurn = float(self.EtaTStartTurn.GetValue())
             sim.TEndTurn = float(self.EtaTEndTurn.GetValue())
             sim.TurnAngle = float(self.EtaTurnAngle.GetValue())
         if trajectory == 'Burnout Angle':
             sim.burnout_angle = float(self.BurnoutAngleCtrl.GetValue())
             
     except ValueError:
             dlg = wx.MessageDialog(self,"Please fill in all fields in Parameters panel.","Unable to solve",wx.OK | wx.ICON_INFORMATION)
             dlg.ShowModal()
             dlg.Destroy()
             #advance to params panel
     #run sim
     data = sim.integrate(trajectory)
     answer = float(app.Results.RangeResult.GetValue()) 
     #subtract from ans_est because method works to find zero
     del(sim) #delete last run
     del(data)
     return answer
    def __init__(self, parent, projectName, creationDate, name):
        """
        Default class constructor.
        
        
        **Parameters:**

        * parent: the widget parent;
        * projectName: the name of the project we are working on;
        * creationDate: the date and time the project was created;
        * name: the widget (compiler) name.

        """

        scrolled.ScrolledPanel.__init__(self, parent, name=name)
        self.MainFrame = wx.GetTopLevelParent(self)

        # I need this flag otherwise all the widgets start sending changed
        # events when I first populate the full panel

        self.created = False
        self.tipWindow = None
    def OnCreateMask(self, event=None):
        #lx, ly, hx, hy = self.do.GetSliceSelection()
        import numpy as np
        #from scipy import ndimage
        from PYME.IO.image import ImageStack
        from PYME.DSView import ViewIm3D

        #sp = self.image.data.shape[:3]
        #if len(sp)
        self.mask = np.atleast_3d(np.zeros(self.image.data.shape[:3],
                                           'uint16'))
        #self.vmax = 0
        self.image.labels = self.mask

        im = ImageStack(self.mask, titleStub='Manual labels')
        im.mdh.copyEntriesFrom(self.image.mdh)

        #im.mdh['Processing.CropROI'] = roi

        if self.dsviewer.mode == 'visGUI':
            mode = 'visGUI'
        else:
            mode = 'lite'

        self.labv = ViewIm3D(im,
                             mode=mode,
                             glCanvas=self.dsviewer.glCanvas,
                             parent=wx.GetTopLevelParent(self.dsviewer))

        self.rois = []

        #set scaling to (0,1)
        #for i in range(im.data.shape[3]):
        #    self.dv.do.Gains[i] = 1.0

        for i in range(im.data.shape[3]):
            self.labv.do.Gains[i] = .1
            self.labv.do.cmaps[i] = matplotlib.cm.labeled
    def OnAlignChannels(self, event):
        #try:
        #    names = self.image.mdh.getEntry('ChannelNames')
        #except:
        #    names = ['%d' % d for d in range(self.image.data.shape[3])]
        from PYME.IO.DataSources import AlignDataSource
        from PYME.IO import dataWrap

        if isinstance(self.image.data, dataWrap.ListWrapper):
            nd = [
                AlignDataSource.DataSource(ds)
                for ds in self.image.data.wrapList
            ]
        else:
            nd = [
                AlignDataSource.DataSource(
                    dataWrap.Wrap(self.image.data[:, :, :, i]))
                for i in range(self.image.data.shape[3])
            ]

        mdh = MetaDataHandler.NestedClassMDHandler(self.image.mdh)

        res = View3D(nd,
                     '%s - %s' % (self.image.filename, 'align'),
                     mdh=mdh,
                     parent=wx.GetTopLevelParent(self.dsviewer))

        res.panAlign = ShiftPanel(res)

        pinfo1 = aui.AuiPaneInfo().Name("shiftPanel").Right(
        ).Caption('Alignment').DestroyOnClose(
            True
        ).CloseButton(False).MinimizeButton(True).MinimizeMode(
            aui.AUI_MINIMIZE_CAPT_SMART | aui.AUI_MINIMIZE_POS_RIGHT
        )  #.MinimizeButton(True).MinimizeMode(aui.AUI_MINIMIZE_CAPT_SMART|aui.AUI_MINIMIZE_POS_RIGHT)#.CaptionVisible(False)
        #pinfo2 = aui.AuiPaneInfo().Name("overlayPanel").Right().Caption('Overlays').CloseButton(False).MinimizeButton(True).MinimizeMode(aui.AUI_MINIMIZE_CAPT_SMART|aui.AUI_MINIMIZE_POS_RIGHT)#.CaptionVisible(False)
        res._mgr.AddPane(res.panAlign, pinfo1)
        res._mgr.Update()
    def __init__(self, parent):
        """
        Default class constructor.

        
        **Parameters:**

        * parent: the widget parent.
        """

        wx.Panel.__init__(self, parent)
        self.MainFrame = wx.GetTopLevelParent(self)        

        # Add the fancy list at the bottom
        self.list = BaseListCtrl(self, columnNames=[_("Time        "), _("Compiler Messages")],
                                 name="messages")

        # Create 3 themed bitmap buttons
        dryBmp = self.MainFrame.CreateBitmap("dry")
        compileBmp = self.MainFrame.CreateBitmap("compile")
        killBmp = self.MainFrame.CreateBitmap("kill")

        # This is a bit tailored over py2exe, but it's the only one I know
        self.dryrun = buttons.ThemedGenBitmapTextButton(self, -1, dryBmp, _("Dry Run"), size=(-1, 25))
        self.compile = buttons.ThemedGenBitmapTextButton(self, -1, compileBmp, _("Compile"), size=(-1, 25))
        self.kill = buttons.ThemedGenBitmapTextButton(self, -1, killBmp, _("Kill"), size=(-1, 25))
        # The animation control
        ani = wx.animate.Animation(os.path.normpath(self.MainFrame.installDir +"/images/throbber.gif"))
        self.throb = wx.animate.AnimationCtrl(self, -1, ani)
        self.throb.SetUseWindowBackgroundColour()

        # Store an id for the popup menu
        self.popupId = wx.NewId()

        # Fo the hard work on other methods
        self.SetProperties()        
        self.LayoutItems()
        self.BindEvents()
Exemple #11
0
    def SetDefault(self):
        """
        This sets the :class:`GenButton` to be the default item for
        the panel or dialog box.

        .. note:: Under Windows, only dialog box buttons respond to this function.
           As normal under Windows and Motif, pressing return causes the
           default button to be depressed when the return key is pressed. See
           also :meth:`wx.Window.SetFocus` which sets the keyboard focus for
           windows and text panel items, and
           :meth:`wx.TopLevelWindow.SetDefaultItem`.

        .. note:: Note that under Motif, calling this function immediately after
           creation of a button and before the creation of other buttons will
           cause misalignment of the row of buttons, since default buttons are
           larger. To get around this, call :meth:`wx.SetDefault` after you
           have created a row of buttons: wxPython will then set the size of
           all buttons currently on the panel to the same size.
        """

        tlw = wx.GetTopLevelParent(self)
        if hasattr(tlw, 'SetDefaultItem'):
            tlw.SetDefaultItem(self)
Exemple #12
0
    def get_label_image(self, event=None, mask=False):
        from PYME.IO.image import ImageStack
        from PYME.DSView import ViewIm3D
        lab = np.concatenate([
            np.atleast_3d(self.rasterize(z))
            for z in range(self.do.ds.shape[2])
        ], 2)
        if mask:
            im = ImageStack(lab > 0.5, titleStub='Mask')
        else:
            im = ImageStack(lab, titleStub='Labels')

        im.mdh.copyEntriesFrom(self.dsviewer.image.mdh)

        if self.dsviewer.mode == 'visGUI':
            mode = 'visGUI'
        else:
            mode = 'lite'

        self.lv = ViewIm3D(im,
                           mode=mode,
                           glCanvas=self.dsviewer.glCanvas,
                           parent=wx.GetTopLevelParent(self.dsviewer))
Exemple #13
0
 def CheckConstraints(self):
     app = wx.GetTopLevelParent(self)
     nstage = int(self.StageChoiceBox.GetSelection()+1)
     self.var_string = self.VariableChoice.GetStringSelection()
     if self.var_string == "Fuel Fraction":
         m0 = float(self.StageMassCtrl.GetValue()) #keep stage mass const
         fuelfraction = float(self.FuelFractionCtrl.GetValue())/100
         if fuelfraction > 1:
             print "invalid fuel fraction, setting to maximum"
             fuelfraction = .99*100
             self.FuelFractionCtrl.SetValue("%.2f" % fuelfraction)
         if fuelfraction < 0:
             print "invalid fuel fraction, setting to minimum"
             fuelfraction = .01*100
             self.FuelFractionCtrl.SetValue("%.2f" % fuelfraction)
         m_prop = fuelfraction*m0
         m_struct = m0 - fuelfraction*m0
         self.FuelMassCtrl.SetValue("%.2f" % m_prop)
         self.DryMassCtrl.SetValue("%.2f" % m_struct)
         app.Params.StageFuelMassCtrl[nstage].SetValue("%.2f" % m_prop)
         app.Params.StageDryMassCtrl[nstage].SetValue("%.2f" % m_struct)
     else:
         pass
Exemple #14
0
def GetActiveWindow(event=None):
    """
	"""
    aW = None

    for win in wx.GetTopLevelWindows():
        if getattr(win, 'IsActive', lambda: False)():
            aW = win

    if aW is None:
        try:
            child = wx.Window.FindFocus()
            aW = wx.GetTopLevelParent(child)
        except:
            pass

    if aW is None and event is not None:

        obj = event.GetEventObject()
        #### conditional statement only for windows
        aW = obj.GetInvokingWindow() if isinstance(obj, wx.Menu) else obj

    return aW
Exemple #15
0
    def __init__(self, parent, moveCallback=None, cornerCallback=None, ID=-1):
        self.bg_bmp = wx.Image(imagefile("control_xy.png"),
                               wx.BITMAP_TYPE_PNG).ConvertToBitmap()
        self.keypad_bmp = wx.Image(imagefile("arrow_keys.png"),
                                   wx.BITMAP_TYPE_PNG).ConvertToBitmap()
        self.keypad_idx = -1
        self.quadrant = None
        self.concentric = None
        self.corner = None
        self.moveCallback = moveCallback
        self.cornerCallback = cornerCallback
        self.enabled = False

        BufferedCanvas.__init__(self, parent, ID)
        self.SetSize(self.bg_bmp.GetSize())

        # Set up mouse and keyboard event capture
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDown)
        self.Bind(wx.EVT_MOTION, self.OnMotion)
        self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow)
        self.Bind(wx.EVT_KEY_UP, self.OnKey)
        wx.GetTopLevelParent(self).Bind(wx.EVT_CHAR_HOOK, self.OnTopLevelKey)
Exemple #16
0
    def __init__(self, parent):
        """
        Default class constructor.

        
        **Parameters:**

        * parent: the tree control parent widget.
        """

        CT.CustomTreeCtrl.__init__(
            self,
            parent,
            style=wx.TR_FULL_ROW_HIGHLIGHT | wx.TR_EDIT_LABELS
            | wx.TR_MULTIPLE | wx.TR_HAS_VARIABLE_ROW_HEIGHT)

        # Remember our main frame (GUI2Exe application window)
        self.MainFrame = wx.GetTopLevelParent(self)
        self.popupIds = [wx.NewId() for i in xrange(7)]
        # A flag to monitor if we are in dragging mode or not
        self.isDragging = False
        self.isDying = False

        # Build all the tree control
        self.BuildImageList()
        self.SetProperties()
        self.BindEvents()

        # Add a root: if someone has a fancier name for the root item, let me know :-D
        self.rootItem = self.AddRoot(_("My Projects"), image=0)
        # Make it bigger, so it is clear that it is a root item
        self.SetItemFont(self.rootItem,
                         wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD, False))

        # Store a particular font, we are going to use it later
        self.boldFont = self.GetFont()
        self.boldFont.SetWeight(wx.FONTWEIGHT_BOLD)
    def Render(self):
        """Actually renders the VTK scene on screen.
        """
        RenderAllowed = 1

        if not self.__RenderWhenDisabled:
            #          print "RenderWhwn Disabled false"
            # the user doesn't want us to render when the toplevel frame
            # is disabled - first find the top level parent
            topParent = wx.GetTopLevelParent(self)
            if topParent:
                # if it exists, check whether it's enabled
                # if it's not enabeld, RenderAllowed will be false
                RenderAllowed = topParent.IsEnabled()

#       print "RenderAllowed", RenderAllowed
        if RenderAllowed:
            if self.__handle and self.__handle == self.GetHandle():
                self._Iren.GetRenderWindow().Render()

            elif self.GetHandle() and self.__has_painted:
                # this means the user has reparented us; let's adapt to the
                # new situation by doing the WindowRemap dance
                self._Iren.GetRenderWindow().SetNextWindowInfo(
                    str(self.GetHandle()))

                # make sure the DisplayId is also set correctly
                d = self.GetDisplayId()
                if d:
                    self._Iren.GetRenderWindow().SetDisplayId(d)

                # do the actual remap with the new parent information
                self._Iren.GetRenderWindow().WindowRemap()

                # store the new situation
                self.__handle = self.GetHandle()
                self._Iren.GetRenderWindow().Render()
Exemple #18
0
    def svm_segment(self, event=None):
        from PYME.IO.image import ImageStack
        from PYME.DSView import ViewIm3D
        # import pylab
        import matplotlib.cm
        #sp = self.image.data.shape[:3]
        #if len(sp)
        lab2 = self.cf.classify(self.dsviewer.image.data[:, :, self.do.zp,
                                                         0].squeeze()
                                )  #, self.image.labels[:,:,self.do.zp])
        #self.vmax = 0
        #self.image.labels = self.mask

        im = ImageStack(lab2, titleStub='Segmentation')
        im.mdh.copyEntriesFrom(self.dsviewer.image.mdh)

        #im.mdh['Processing.CropROI'] = roi

        if self.dsviewer.mode == 'visGUI':
            mode = 'visGUI'
        else:
            mode = 'lite'

        self.dv = ViewIm3D(im,
                           mode=mode,
                           glCanvas=self.dsviewer.glCanvas,
                           parent=wx.GetTopLevelParent(self.dsviewer))

        self.rois = []

        #set scaling to (0,10)
        for i in range(im.data.shape[3]):
            self.dv.do.Gains[i] = .1
            self.dv.do.cmaps[i] = matplotlib.cm.labeled

        self.dv.Refresh()
        self.dv.Update()
Exemple #19
0
    def Error(self, message = None, link = None, callback = None):
        """
            This shows the panel with the message provided.
            Has a link in the lower right if a link string and callback are provided.
            If message is None, the panel is hidden.
            If the message is a callable, then the panel is added to the refresh
            timer and message is called every 1 second, expecting a string to be
            returned.
        """

        self.message = message

        #destroy old link if there is one
        self.link=''

        if message:
            # if link and callback are provided, make a ClearLink object
            if link and callback:
                self.linkcb = lambda *a: (wx.GetTopLevelParent(self).Hide(), callback(*a))
                self.link = link
                linksize = wx.Size(GetTextWidth(link,self.linkf),self.linkf.Height)
                self.linkrect = wx.Rect(self.Size.width-linksize.width-self.padding.x,self.Size.height-linksize.height-self.padding.y,*linksize)

            self.Show(True)

            self.MinSize = wx.Size(-1, 5 * max(self.labelf.Height, self.linkf.Height))

            self.GrandParent.DoSizeMagic()
            self.Refresh()
        else:
            self.Show(False)

        #if message is a callable, register with refresh timer
        if callable(message):
            refreshtimer().Register(self)
        else:
            refreshtimer().UnRegister(self)
Exemple #20
0
 def _DoDebugHide( self ):
     
     parent = self.GetParent()
     
     parent_iconized = parent.IsIconized()
     
     # changing show status while parent iconised in Windows leads to grey window syndrome
     windows_and_iconised = HC.PLATFORM_WINDOWS and parent_iconized
     
     possibly_on_hidden_virtual_desktop = not ClientGUITopLevelWindows.MouseIsOnMyDisplay( parent )
     
     going_to_bug_out_at_hide_or_show = windows_and_iconised or possibly_on_hidden_virtual_desktop
     
     new_options = HG.client_controller.new_options
     
     if new_options.GetBoolean( 'hide_message_manager_on_gui_iconise' ):
         
         if parent.IsIconized():
             
             self.Hide()
             
             return
             
         
     
     current_focus_tlp = wx.GetTopLevelParent( wx.Window.FindFocus() )
     
     main_gui_is_active = current_focus_tlp in ( self, parent )
     
     if new_options.GetBoolean( 'hide_message_manager_on_gui_deactive' ):
         
         if not main_gui_is_active:
             
             if not going_to_bug_out_at_hide_or_show:
                 
                 self.Hide()
Exemple #21
0
    def OnSelectSound(self, evt):
        """
		"""
        dlg = wx.FileDialog(wx.GetTopLevelParent(self),
                            _("Choose a sound file"),
                            wildcard=_("WAV files (*.wav)|*.wav"),
                            style=wx.OPEN)

        if dlg.ShowModal() == wx.ID_OK:
            val = dlg.GetPath()
            name = evt.GetEventObject().GetName()
            try:
                ### test the selected sound
                wx.Sound.PlaySound(val, wx.SOUND_SYNC)

                if name == 'success':
                    self.sim_success_wav_path = val
                elif name == 'error':
                    self.sim_error_wav_path = val
                else:
                    pass

            except NotImplementedError, v:
                wx.MessageBox(str(v), _("Exception Message"))
Exemple #22
0
    def AddScene(self, parent):
        ProjectController.scene_count += 1

        scene_name = 'New Scene {}'.format(ProjectController.scene_count)
        node = SceneNode(Scene(scene_name), scene_name, parent)
        tree_parent = self.RecursiveFindByNode(
            self.project_panel.visualization_tree, self.project_panel.visualization_tree.GetRootItem(), parent
        )
        if not tree_parent.IsOk():
            tree_parent = self.project_panel.visualization_tree.GetRootItem()
        tree_item = self.project_panel.visualization_tree.AppendSceneItem(
            tree_parent, node.label, node
        )

        self.project_panel.visualization_tree.Collapse(tree_parent)
        self.project_panel.visualization_tree.EnsureVisible(tree_item)
        self.project_panel.visualization_tree.EditLabel(tree_item)

        edit_ctrl = self.project_panel.visualization_tree.GetEditControl()
        if edit_ctrl is not None:
            edit_ctrl.SetSelection(-1, -1)

        pce = ProjectChangedEvent(node=node, change=ProjectChangedEvent.ADDED_SCENE)
        wx.PostEvent(wx.GetTopLevelParent(self.project_panel), pce)
Exemple #23
0
    def __init__(self, parent, rangesize, startFrame, endFrame,
                 sliderStartFrame, sliderEndFrame):
        wx.Window.__init__(self,
                           parent,
                           size=rangesize,
                           style=wx.SUNKEN_BORDER)

        self._mainDialog = wx.GetTopLevelParent(self)

        self._mouseIn = False

        self.startFrame = startFrame
        self.endFrame = endFrame
        self.sliderStartFrame = sliderStartFrame
        self.sliderEndFrame = sliderEndFrame
        self.frameNum = self.endFrame - self.startFrame + 1

        self.InitBuffer()

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
        self.Bind(wx.EVT_MOTION, self.OnMotion)
Exemple #24
0
    def OnCharHook(self, event):
        if event.KeyCode in (wx.WXK_RETURN, wx.WXK_SPACE):
            for id in (wx.ID_YES, wx.ID_NO, wx.ID_OK):
                wnd = self.m_html.FindWindowById(id)
                if wnd:
                    tlw = wx.GetTopLevelParent(wnd)
                    if tlw.GetDefaultItem() == wnd:
                        wnd.ProcessEvent(
                            wx.CommandEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED,
                                            id))
                        break

        elif event.KeyCode == wx.WXK_ESCAPE:
            if self.m_html.FindWindowById(wx.ID_CANCEL):
                self.m_html.FindWindowById(wx.ID_CANCEL).ProcessEvent(
                    wx.CommandEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED,
                                    wx.ID_CANCEL))
            else:
                if self.IsModal() == False:
                    self.Show(False)
                else:
                    self.EndModal(wx.ID_CANCEL)
        else:
            event.Skip()
Exemple #25
0
    def OnExtractSplitPSF(self, event):
        if (len(self.PSFLocs) > 0):
            from PYME.PSFEst import extractImages
            chnum = self.chChannel.GetSelection()

            psfROISize = [int(s) for s in self.tPSFROI.GetValue().split(',')]
            psfBlur = [float(s) for s in self.tPSFBlur.GetValue().split(',')]
            #print psfROISize

            psfs = []

            for i in range(self.image.data.shape[3]):
                psf = extractImages.getPSF3D(self.image.data[:, :, :, i],
                                             self.PSFLocs, psfROISize, psfBlur)

                if self.chType.GetSelection() == 0:
                    #widefield image - do special background subtraction
                    psf = extractImages.backgroundCorrectPSFWF(psf)

                psfs.append(psf)

            psf = numpy.concatenate(psfs, 0)

            #            from pylab import *
            #            import cPickle
            #            imshow(psf.max(2))

            from PYME.DSView.dsviewer_npy_nb import ImageStack, ViewIm3D

            im = ImageStack(data=psf,
                            mdh=self.image.mdh,
                            titleStub='Extracted PSF')
            im.defaultExt = '*.psf'  #we want to save as PSF by default
            ViewIm3D(im,
                     mode='psf',
                     parent=wx.GetTopLevelParent(self.dsviewer))
Exemple #26
0
	def _on_list_item_activated(self, evt):
		data = self.get_selected_item_data(only_one = True)
		pk_pat_col = self.__get_patient_pk_data_key(data = data)

		if pk_pat_col is None:
			gmDispatcher.send(signal = 'statustext', msg = _('List not known to be patient-related.'))
			return

		pat_data = data[pk_pat_col]
		try:
			pat_pk = int(pat_data)
			pat = gmPerson.cPerson(aPK_obj = pat_pk)
		except (ValueError, TypeError):
			searcher = gmPersonSearch.cPatientSearcher_SQL()
			idents = searcher.get_identities(pat_data)
			if len(idents) == 0:
				gmDispatcher.send(signal = 'statustext', msg = _('No matching patient found.'))
				return
			if len(idents) == 1:
				pat = idents[0]
			else:
				from Gnumed.wxpython import gmPatSearchWidgets
				dlg = gmPatSearchWidgets.cSelectPersonFromListDlg(parent=wx.GetTopLevelParent(self), id=-1)
				dlg.set_persons(persons=idents)
				result = dlg.ShowModal()
				if result == wx.ID_CANCEL:
					dlg.Destroy()
					return
				pat = dlg.get_selected_person()
				dlg.Destroy()
		except ConstructorError:
			gmDispatcher.send(signal = 'statustext', msg = _('No matching patient found.'))
			return

		from Gnumed.wxpython import gmPatSearchWidgets
		gmPatSearchWidgets.set_active_patient(patient = pat)
Exemple #27
0
    def _bindEvents(self, eventList):
        # shouldn't components be subclasses of Scriptable?
        # components would have their own handlers but when
        # looking for a handler match it will search the parents
        # for now just grab handlers from the background

        # the references below would be self.findHandler instead of
        # background.findHandler

        #background = self.GetParent().GetParent()
        background = wx.GetTopLevelParent(self)

        if wx.GetApp()._showDebugMenu:
            bindUnusedEvents = True
        else:
            bindUnusedEvents = False

        # helper variable to simplify test for whether to bind InsteadOfTypeEvents
        # there is a good chance we will need to know
        # which events are bound, if we want to dynamically add or remove
        # events later, so go ahead and keep a reference to the list
        self.boundEvents = {}

        self.eventIdToHandler = {}
        self.wxEventIdMap = {}

        if 0:
            print "\nBINDING...", self.name

        for eventClass in eventList:
            #for eventClass in ButtonEvents:
            # need to figure out a way to avoid the need
            # for this id to class mapping which is used in _dispatch below
            self.wxEventIdMap[eventClass.id] = eventClass
            # command handler overrides normal mouseClick or select handler
            # so dispatch will automatically dispatch to the command handler
            # by looking up the handler this way
            # it also means that if there is a command association with this component
            # then the regular mouseClick or select handler will never be bound, just ignored
            if issubclass(eventClass, event.CommandTypeEvent) and self.command:
                handler = background.findHandler('on_' + self.command +
                                                 '_command')
                if not handler:
                    handler = background.findHandler('on_' + self.name + '_' +
                                                     eventClass.name)
            else:
                handler = background.findHandler('on_' + self.name + '_' +
                                                 eventClass.name)
            if not handler:
                handler = background.findHandler('on_' + eventClass.name)
            if handler or bindUnusedEvents:
                # only bind events that have an event handler
                # in this scenario unused events are never bound
                # which is more efficient, but the Message Watcher needs
                # to be changed
                # alternatively we can bind everything and then in _dispatch
                # if there isn't a match in eventIdToHandler then we know
                # the event isn't used and we can set used to False
                # the complication would be that we probably have to have to
                # always call Skip() which may or may not be a hassle with components

                # this doesn't bind command events
                # they would be of the form on_somename_command
                # or perhaps on_command but I don't think we would want
                # to support that
                # the event binding would be specific to a component
                # since on dispatch command overrides something like mouseClickEvent
                # but the name of the command is not related to the component
                # need to look at whether self.command has a value and then bind
                # with ButtonMouseClickEvent.binding if that isn't already bound
                # then in dispatch have to check again I think

                # need to avoid double binding
                # also binding shouldn't be order-specific
                # so how to avoid binding mouseDrag to _dispatch
                # if mouseMove is already bound or if binding mouseMove
                # not rebinding if mouseDrag is already bound
                # perhaps MouseDragEvent keeps a reference to MouseMoveEvent
                # and that is inserted into boundEvents, then we check boundEvents
                # prior to rebinding?
                if not self.boundEvents.get(eventClass.binding, None):
                    background.Bind(eventClass.binding, self._dispatch, self)
                    self.boundEvents[eventClass.binding] = eventClass.name
                if handler:
                    if 0:
                        print "  binding", self.name, eventClass.name, handler.__name__, eventClass.id
                    # KEA 2004-05-02
                    # change to just using the method directly, Handler class not needed
                    # actually the Handler class isn't needed at all
                    # so if the initial list built to simplify findHandler
                    # just stores a reference to the method that would be fine
                    # as long as the whole system uses that
                    # the only reason we don't just build the list ourselves
                    # in _bindEvents is that every component needs to do findHandler
                    # so it is more efficient to do once when the Scriptable object
                    # is created than to reparse for each component
                    #self.eventIdToHandler[eventClass.id] = handler
                    #self.eventIdToHandler[eventClass.id] = handler.getFunction()
                    self.eventIdToHandler[eventClass.id] = handler

        if 0:
            print "\n  boundEvents:"
            for name in self.boundEvents.values():
                print "   ", name
            print "\n\n"
            print "\n  self.eventIdToHandler:"
            for id in self.eventIdToHandler:
                # KEA 2004-05-02
                # change to just using the method directly, Handler class not needed
                #print "   ", id, self.eventIdToHandler[id]._function
                print "   ", id, self.eventIdToHandler[id]
            print "\n\n"
Exemple #28
0
    def SetDefault(self):
        """ Sets the default button. """

        tlw = wx.GetTopLevelParent(self)
        if hasattr(tlw, 'SetDefaultItem'):
            tlw.SetDefaultItem(self)
    def OnKey(self, event):

        if event.GetEventType() == wx.wxEVT_KEY_UP:
            if event.GetKeyCode() == self.GetModifierKey():
                topLevel = wx.GetTopLevelParent(self)
                closeEvent = wx.CloseEvent(wx.wxEVT_CLOSE_WINDOW, topLevel.GetId())
                closeEvent.SetEventObject(topLevel)
                closeEvent.SetCanVeto(False)

                topLevel.GetEventHandler().ProcessEvent(closeEvent)
                return

            event.Skip()
            return

        keyCode = event.GetKeyCode()

        if keyCode in [wx.WXK_ESCAPE, wx.WXK_RETURN]:
            if keyCode == wx.WXK_ESCAPE:
                self._items.SetSelection(-1)

            topLevel = wx.GetTopLevelParent(self)
            closeEvent = wx.CloseEvent(wx.wxEVT_CLOSE_WINDOW, topLevel.GetId())
            closeEvent.SetEventObject(topLevel)
            closeEvent.SetCanVeto(False)

            topLevel.GetEventHandler().ProcessEvent(closeEvent)
            return

        elif keyCode in [wx.WXK_TAB, self.GetExtraNavigationKey()]:
            if event.ShiftDown():

                self._items.SetSelection(self._items.GetSelection() - 1)
                if self._items.GetSelection() < 0:
                    self._items.SetSelection(self._items.GetItemCount() - 1)

                self.AdvanceToNextSelectableItem(-1)

            else:

                self._items.SetSelection(self._items.GetSelection() + 1)
                if self._items.GetSelection() >= self._items.GetItemCount():
                    self._items.SetSelection(0)

                self.AdvanceToNextSelectableItem(1)

            self.GenerateSelectionEvent()
            self.Refresh()

        elif keyCode in [wx.WXK_DOWN, wx.WXK_NUMPAD_DOWN]:
            self._items.SetSelection(self._items.GetSelection() + 1)
            if self._items.GetSelection() >= self._items.GetItemCount():
                self._items.SetSelection(0)

            self.AdvanceToNextSelectableItem(1)
            self.GenerateSelectionEvent()
            self.Refresh()

        elif keyCode in [wx.WXK_UP, wx.WXK_NUMPAD_UP]:
            self._items.SetSelection(self._items.GetSelection() - 1)
            if self._items.GetSelection() < 0:
                self._items.SetSelection(self._items.GetItemCount() - 1)

            self.AdvanceToNextSelectableItem(-1)
            self.GenerateSelectionEvent()
            self.Refresh()

        elif keyCode in [wx.WXK_HOME, wx.WXK_NUMPAD_HOME]:
            self._items.SetSelection(0)
            self.AdvanceToNextSelectableItem(1)
            self.GenerateSelectionEvent()
            self.Refresh()

        elif keyCode in [wx.WXK_END, wx.WXK_NUMPAD_END]:
            self._items.SetSelection(self._items.GetItemCount() - 1)
            self.AdvanceToNextSelectableItem(-1)
            self.GenerateSelectionEvent()
            self.Refresh()

        elif keyCode in [wx.WXK_LEFT, wx.WXK_NUMPAD_LEFT]:
            item = self._items.GetItem(self._items.GetSelection())

            row = item.GetRowPos()
            newCol = item.GetColPos() - 1
            if newCol < 0:
                newCol = self._items.GetColumnCount() - 1

            # Find the first item from the end whose row matches and whose column is equal or lower
            for i in range(self._items.GetItemCount()-1, -1, -1):
                item2 = self._items.GetItem(i)
                if item2.GetColPos() == newCol and item2.GetRowPos() <= row:
                    self._items.SetSelection(i)
                    break

            self.AdvanceToNextSelectableItem(-1)
            self.GenerateSelectionEvent()
            self.Refresh()

        elif keyCode in [wx.WXK_RIGHT, wx.WXK_NUMPAD_RIGHT]:
            item = self._items.GetItem(self._items.GetSelection())

            row = item.GetRowPos()
            newCol = item.GetColPos() + 1
            if newCol >= self._items.GetColumnCount():
                newCol = 0

            # Find the first item from the end whose row matches and whose column is equal or lower
            for i in range(self._items.GetItemCount()-1, -1, -1):
                item2 = self._items.GetItem(i)
                if item2.GetColPos() == newCol and item2.GetRowPos() <= row:
                    self._items.SetSelection(i)
                    break

            self.AdvanceToNextSelectableItem(1)
            self.GenerateSelectionEvent()
            self.Refresh()

        else:
            event.Skip()
Exemple #30
0
 def OnCloseParent(self, evt):
     p = wx.GetTopLevelParent(self)
     if p:
         p.Close()