Exemplo n.º 1
0
def wx_cursor(c):
    if PY3:
        return wx.Cursor(c)
    else:
        return wx.StockCursor(c)
Exemplo n.º 2
0
 def OnEnterWindow(self, event):
     obj = event.GetEventObject()
     obj.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
     event.Skip()
Exemplo n.º 3
0
 def hideCursor(self, event=None):
     if self.cursorVisible:
         self.SetCursor(wx.StockCursor(wx.CURSOR_BLANK))
         self.editCtrl.SetCursor(wx.StockCursor(wx.CURSOR_BLANK))
         self.cursorVisible = False
Exemplo n.º 4
0
def stock_cursor(cursor_id):
    return wx.StockCursor(cursor_id)
Exemplo n.º 5
0
 def onMouseMove(self, evt):
     x, y = evt.GetPosition()
     if self.inHotSpot(x, y) is not None:
         self.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
     else:
         self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
Exemplo n.º 6
0
	def OnLeave(self,evt):
		self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
		self.entered = False
Exemplo n.º 7
0
    def _report_mouse_state(self, evt): # wx gives x,y relative to upper left corner
        x, y = evt.GetPosition()
        if self._lastx is None:
            self._lastx = x
            self._lasty = y

        zooming = self._mt.isZooming(evt, self.userzoom, self.userspin)
        spinning = self._mt.isSpinning(evt, self.userzoom, self.userspin, zooming)
        lock = self._mt.checkLock(spinning, zooming)
        
        if lock and not self._captured:
            if 'phoenix' in _wx.PlatformInfo:
                self.win.SetCursor(_wx.Cursor(_wx.CURSOR_BLANK)) # Phoenix
            else:
                self.win.SetCursor(_wx.StockCursor(_wx.CURSOR_BLANK)) # Classic
            if self.standard:
                self._cursorx, self._cursory = (x, y)
            else:
                # cursor is based on (0,0) of the window; our (x,y) is based on (0,0) of the 3D display
                self._cursorx, self._cursory = (int(self._x)+x, int(self._y)+y)
            self._canvas.CaptureMouse()
            self._captured = True
        elif self._captured and not (spinning or zooming):
            self.win.WarpPointer(self._cursorx, self._cursory)
            self._lastx = x = self._cursorx
            self._lasty = y = self._cursory
            if 'phoenix' in _wx.PlatformInfo:
                self.win.SetCursor(_wx.Cursor(_wx.CURSOR_ARROW)) # Phoenix
            else:
                self.win.SetCursor(_wx.StockCursor(_wx.CURSOR_ARROW)) # Classic
            self._canvas.ReleaseMouse()          
            self._captured = False
        
        
        #
        # So... we're going to report left/right/middle
        #

        left = self._mt.leftIsDown and not spinning and not zooming
        right = spinning or self._mt.rightIsDown
        middle = zooming or self._mt.middleIsDown
        shift = evt.ShiftDown()
        ctrl = evt.ControlDown()
        alt = evt.AltDown()
        cmd = evt.CmdDown()
                
        if _plat == 'Macintosh' and ctrl and cmd:
            #
            # Weird... if the user holds the cmd key, evt.ControlDown() returns True even if it's a lie.
            # So... we don't know if it's *really* down or not. ;-(
            #
            ctrl = False
        
#         labels = [s.strip() for s in "x, y, left, middle, right, shift, ctrl, alt, cmd, spin, zoom, lock, cap".split(',')]
#         vals = (x, y, left, middle, right, shift, ctrl, alt, cmd, spinning, zooming, lock, self._captured)
#         fmts = ["%9s"]*len(vals)
#         for l,f in zip(labels,fmts):
#             print(f % l, end='')
#         print()
#         for v,f in zip(vals,fmts):
#             print(f % `v`, end='')
#         print()
##        if trigger == 'leftdown' and not self._rightdown:
##            if ctrl:
##                right = 1
##                left = 0
##            elif alt:
##                middle = 1
##                left = 0

#        if (spinning or zooming) and (x == self._lastx) and (y == self._lasty): return
        
        self.report_mouse_state([left, right, middle],
                self._lastx, self._lasty, x, y,
                [shift, ctrl, alt, cmd])
        # For some reason, handling spin/zoom in terms of movements away
        # from a fixed cursor position fails on the Mac. As you drag the
        # mouse, repeated move mouse events mostly give the fixed cursor position.
        # Hence, for now, dragging off-screen stops spin/zoom on the Mac.
        # Similar problems on Ubuntu 12.04, plus wx.CURSOR_BLANK not available on Linux.
        if (spinning or zooming) and (_plat != 'Macintosh'): # reset mouse to original location
            self.win.WarpPointer(self._cursorx, self._cursory)
            if self.standard:
                self._lastx = self._cursorx
                self._lasty = self._cursory
            else:
                # cursor is based on (0,0) of the window; our (x,y) is based on (0,0) of the 3D display
                self._lastx = self._cursorx - int(self._x)
                self._lasty = self._cursory - int(self._y)
        else: 
            self._lastx = x
            self._lasty = y
Exemplo n.º 8
0
 def HideCursor(self):
     """Hides the cursor."""
     c = wx.StockCursor(wx.CURSOR_BLANK)
     self.SetCursor(c)
Exemplo n.º 9
0
 def ShowCursor(self):
     """Shows the cursor."""
     rw = self._Iren.GetRenderWindow()
     cur = self._cursor_map[rw.GetCurrentCursor()]
     c = wx.StockCursor(cur)
     self.SetCursor(c)
Exemplo n.º 10
0
    def ProvideSettingsValidationResults(event):
        # pylint: disable=too-many-branches
        # pylint: disable=too-many-statements
        # Needs refactoring.
        """
        Only called after settings dialog has been shown.
        Not called if settings validation was triggered by
        a background task.
        """
        if event.GetEventId() != EVT_PROVIDE_SETTINGS_VALIDATION_RESULTS:
            event.Skip()
            return
        settingsValidation = event.settingsModel.GetValidation()
        if settingsValidation.Aborted():
            wx.CallAfter(EndBusyCursorIfRequired, event)
            if wx.version().startswith("3.0.3.dev"):
                arrowCursor = wx.Cursor(wx.CURSOR_ARROW)
            else:
                arrowCursor = wx.StockCursor(wx.CURSOR_ARROW)
            event.settingsDialog.dialogPanel.SetCursor(arrowCursor)
            event.settingsModel.RollBack()
            return
        if settingsValidation is not None and \
                not settingsValidation.IsValid():
            wx.GetApp().GetMainFrame().SetStatusMessage("")
            message = settingsValidation.GetMessage()
            logger.error(message)

            if settingsValidation.GetSuggestion():
                currentValue = ""
                if settingsValidation.GetField() == "instrument_name":
                    currentValue = event.settingsDialog.GetInstrumentName()
                elif settingsValidation.GetField() == "facility_name":
                    currentValue = event.settingsDialog.GetFacilityName()
                elif settingsValidation.GetField() == "mytardis_url":
                    currentValue = event.settingsDialog.GetMyTardisUrl()
                message = message.strip()
                if currentValue != "":
                    message += "\n\nMyData suggests that you replace \"%s\" " \
                        % currentValue
                    message += "with \"%s\"." \
                        % settingsValidation.GetSuggestion()
                else:
                    message += "\n\nMyData suggests that you use \"%s\"." \
                        % settingsValidation.GetSuggestion()
                dlg = wx.MessageDialog(None, message, "MyData",
                                       wx.OK | wx.CANCEL | wx.ICON_ERROR)
                okToUseSuggestion = dlg.ShowModal()
                if okToUseSuggestion == wx.ID_OK:
                    if settingsValidation.GetField() == "instrument_name":
                        event.settingsDialog\
                            .SetInstrumentName(settingsValidation
                                               .GetSuggestion())
                    elif settingsValidation.GetField() == "facility_name":
                        event.settingsDialog.SetFacilityName(
                            settingsValidation.GetSuggestion())
                    elif settingsValidation.GetField() == "mytardis_url":
                        event.settingsDialog.SetMyTardisUrl(
                            settingsValidation.GetSuggestion())
            else:
                dlg = wx.MessageDialog(None, message, "MyData",
                                       wx.OK | wx.ICON_ERROR)
                dlg.ShowModal()
            if settingsValidation.GetField() == "instrument_name":
                event.settingsDialog.instrumentNameField.SetFocus()
                event.settingsDialog.instrumentNameField.SelectAll()
            elif settingsValidation.GetField() == "facility_name":
                event.settingsDialog.facilityNameField.SetFocus()
                event.settingsDialog.facilityNameField.SelectAll()
            elif settingsValidation.GetField() == "data_directory":
                event.settingsDialog.dataDirectoryField.SetFocus()
                event.settingsDialog.dataDirectoryField.SelectAll()
            elif settingsValidation.GetField() == "mytardis_url":
                event.settingsDialog.myTardisUrlField.SetFocus()
                event.settingsDialog.myTardisUrlField.SelectAll()
            elif settingsValidation.GetField() == "contact_name":
                event.settingsDialog.contactNameField.SetFocus()
                event.settingsDialog.contactNameField.SelectAll()
            elif settingsValidation.GetField() == "contact_email":
                event.settingsDialog.contactEmailField.SetFocus()
                event.settingsDialog.contactEmailField.SelectAll()
            elif settingsValidation.GetField() == "username":
                event.settingsDialog.usernameField.SetFocus()
                event.settingsDialog.usernameField.SelectAll()
            elif settingsValidation.GetField() == "api_key":
                event.settingsDialog.apiKeyField.SetFocus()
                event.settingsDialog.apiKeyField.SelectAll()
            elif settingsValidation.GetField() == "scheduled_time":
                event.settingsDialog.timeCtrl.SetFocus()
            elif settingsValidation.GetField() == "includes_file":
                event.settingsDialog.includesFileField.SetFocus()
                event.settingsDialog.includesFileField.SelectAll()
            elif settingsValidation.GetField() == "excludes_file":
                event.settingsDialog.excludesFileField.SetFocus()
                event.settingsDialog.excludesFileField.SelectAll()
            logger.debug("Settings were not valid, so Settings dialog "
                         "should remain visible.")
            if wx.version().startswith("3.0.3.dev"):
                arrowCursor = wx.Cursor(wx.CURSOR_ARROW)
            else:
                arrowCursor = wx.StockCursor(wx.CURSOR_ARROW)
            event.settingsDialog.dialogPanel.SetCursor(arrowCursor)
            event.settingsModel.RollBack()
            return

        if event.settingsModel.IgnoreOldDatasets():
            intervalIfUsed = " (created within the past %d %s)" \
                % (event.settingsModel.GetIgnoreOldDatasetIntervalNumber(),
                   event.settingsModel.GetIgnoreOldDatasetIntervalUnit())
        else:
            intervalIfUsed = ""
        numDatasets = settingsValidation.GetDatasetCount()
        if numDatasets != -1:
            message = "Assuming a folder structure of '%s', " \
                "there %s %d %s in \"%s\"%s.\n\n" \
                "Do you want to continue?" \
                % (event.settingsModel.GetFolderStructure(),
                   "are" if numDatasets != 1 else "is",
                   settingsValidation.GetDatasetCount(),
                   "datasets" if numDatasets != 1 else "dataset",
                   event.settingsDialog.GetDataDirectory(),
                   intervalIfUsed)
            confirmationDialog = \
                wx.MessageDialog(None, message, "MyData",
                                 wx.YES | wx.NO | wx.ICON_QUESTION)
            okToContinue = confirmationDialog.ShowModal()
            if okToContinue != wx.ID_YES:
                return

        logger.debug("Settings were valid, so we'll save the settings "
                     "to disk and close the Settings dialog.")
        # pylint: disable=bare-except
        try:
            # Now is a good time to define the MyData instances's uploader
            # model object, which will generate a UUID if necessary.
            # The UUID will be saved to disk along with the settings from
            # the settings dialog.
            uploaderModel = UploaderModel(event.settingsModel)
            event.settingsModel.SetUploaderModel(uploaderModel)

            # Use the config path determined by appdirs, not the one
            # determined by a user dragging and dropping a config
            # file onto MyData's Settings dialog:
            app = wx.GetApp()
            if hasattr(app, "GetConfigPath"):
                configPath = app.GetConfigPath()
            else:
                configPath = None
            event.settingsModel.SaveFieldsFromDialog(event.settingsDialog,
                                                     configPath=configPath,
                                                     saveToDisk=True)
            event.settingsDialog.EndModal(wx.ID_OK)
            event.settingsDialog.Show(False)
            logger.debug("Closed Settings dialog.")

            if event.settingsModel.GetScheduleType() == "Manually":
                message = \
                     "MyData's schedule type is currently " \
                     "set to 'manual', so you will need to click " \
                     "the Upload toolbar icon or the Sync Now " \
                     "menu item to begin the data scans and uploads."
                title = "Manual Schedule"
                dlg = wx.MessageDialog(None, message, title,
                                       wx.OK | wx.ICON_WARNING)
                dlg.ShowModal()
        except:
            logger.error(traceback.format_exc())
Exemplo n.º 11
0
 def OnLeftDown(self, event):
     self.xDragLast = event.GetX()
     self.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
     event.Skip()
Exemplo n.º 12
0
        def Validate(settingsModel):
            """
            Performs settings validation in separate thread.
            """
            logger.debug("Starting run() method for thread %s" %
                         threading.current_thread().name)
            try:
                wx.CallAfter(BeginBusyCursorIfRequired)
                if sys.platform.startswith("win"):
                    # BeginBusyCursor should update the cursor everywhere,
                    # but it doesn't always work on Windows.
                    if wx.version().startswith("3.0.3.dev"):
                        busyCursor = wx.Cursor(wx.CURSOR_WAIT)
                    else:
                        busyCursor = wx.StockCursor(wx.CURSOR_WAIT)
                    wx.CallAfter(event.settingsDialog.dialogPanel.SetCursor,
                                 busyCursor)
                wx.CallAfter(event.settingsDialog.okButton.Disable)
                wx.CallAfter(event.settingsDialog.lockOrUnlockButton.Disable)

                app = wx.GetApp()
                if hasattr(app, "GetLastConnectivityCheckTime"):
                    intervalSinceLastCheck = datetime.now() - \
                        app.GetLastConnectivityCheckTime()
                    checkInterval = \
                        event.settingsModel.GetConnectivityCheckInterval()
                    if intervalSinceLastCheck.total_seconds() >= checkInterval \
                            or not app.GetLastConnectivityCheckSuccess():
                        settingsDialogValidationEvent = \
                            MyDataEvent(EVT_SETTINGS_DIALOG_VALIDATION,
                                        settingsDialog=event.settingsDialog,
                                        settingsModel=settingsModel,
                                        okEvent=event)
                        checkConnectivityEvent = \
                            MyDataEvent(EVT_CHECK_CONNECTIVITY,
                                        settingsDialog=event.settingsDialog,
                                        settingsModel=settingsModel,
                                        nextEvent=settingsDialogValidationEvent)
                        wx.PostEvent(app.GetMainFrame(),
                                     checkConnectivityEvent)
                        return
                try:
                    event.settingsModel.SaveFieldsFromDialog(
                        event.settingsDialog, saveToDisk=False)
                except:  # pylint: disable=bare-except
                    logger.error(traceback.format_exc())

                def SetStatusMessage(message):
                    """
                    Updates status bar.
                    """
                    wx.CallAfter(wx.GetApp().GetMainFrame().SetStatusMessage,
                                 message)

                settingsModel.Validate(SetStatusMessage)
                wx.CallAfter(EndBusyCursorIfRequired, event)
                if settingsModel.IsIncompatibleMyTardisVersion():
                    wx.CallAfter(event.settingsDialog.okButton.Enable)
                    wx.CallAfter(
                        event.settingsDialog.lockOrUnlockButton.Enable)
                    return
                provideValidationResultsEvent = MyDataEvent(
                    EVT_PROVIDE_SETTINGS_VALIDATION_RESULTS,
                    settingsDialog=event.settingsDialog,
                    settingsModel=event.settingsModel)
                if hasattr(app, "GetMainFrame"):
                    wx.PostEvent(app.GetMainFrame(),
                                 provideValidationResultsEvent)
            except IncompatibleMyTardisVersion as err:
                wx.CallAfter(EndBusyCursorIfRequired, event)

                def ShowDialog(message):
                    """
                    Show error dialog in main thread.
                    """
                    logger.error(message)
                    # pylint: disable=no-member
                    # Otherwise pylint complains about PyAssertionError.
                    # pylint: disable=protected-access
                    try:
                        wx.EndBusyCursor()
                        if wx.version().startswith("3.0.3.dev"):
                            arrowCursor = wx.Cursor(wx.CURSOR_ARROW)
                        else:
                            arrowCursor = wx.StockCursor(wx.CURSOR_ARROW)
                        event.settingsDialog.dialogPanel.SetCursor(arrowCursor)
                    except wx._core.PyAssertionError, err:
                        if "no matching wxBeginBusyCursor()" \
                                not in str(err):
                            logger.error(str(err))
                            raise
                    dlg = wx.MessageDialog(None, message, "MyData",
                                           wx.OK | wx.ICON_ERROR)
                    dlg.ShowModal()

                message = str(err)
                wx.CallAfter(ShowDialog, message)
Exemplo n.º 13
0
 def OnLeftDown(self, evt):
     self.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
     self.CaptureMouse()
     self.offsetFrom = evt.GetPosition()
     evt.Skip()
Exemplo n.º 14
0
 def create_crosshair(self, event):
     self.SetCursor(wx.StockCursor(wx.CURSOR_CROSS))
Exemplo n.º 15
0
	def OnLeave(self,evt):
		self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
Exemplo n.º 16
0
def set_wait_cursor(parent):
    parent.SetCursor(wx.StockCursor(wx.CURSOR_WAIT))
Exemplo n.º 17
0
	def OnEnter(self,evt):
		if self.side == MV_HOR:
			self.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
		else:
			self.SetCursor(wx.StockCursor(wx.CURSOR_POINT_LEFT))
Exemplo n.º 18
0
def set_default_cursor(parent):
    parent.SetCursor(wx.StockCursor(wx.CURSOR_DEFAULT))
Exemplo n.º 19
0
	def OnEnter(self,evt):
		self.SetCursor(wx.StockCursor(wx.CURSOR_BULLSEYE))
		self.entered = True
Exemplo n.º 20
0
    def CreateFilterInfoDialog(self, resetargsbutton=True):
        dlg = wx.Dialog(self, wx.ID_ANY, _('Edit function information'))
        staticText0 = wx.StaticText(dlg, wx.ID_ANY, _('Name:'))
        textCtrl0 = wx.TextCtrl(dlg, wx.ID_ANY, size=(200, -1))
        staticText1 = wx.StaticText(dlg, wx.ID_ANY, _('Type:'))
        choices = [
            _('core filter'),
            _('clip property'),
            _('plugin'),
            _('user function'),
            _('script function')
        ]
        choiceBox1 = wx.Choice(dlg, wx.ID_ANY, choices=choices)
        staticText2 = wx.StaticText(dlg, wx.ID_ANY, _('Arguments:'))
        staticText2_4 = wx.StaticText(dlg, wx.ID_ANY, _('define sliders'))
        staticText2_5 = wx.StaticText(dlg, wx.ID_ANY, _('reset to default'))
        for eachCtrl in (staticText2_4, staticText2_5):
            font = eachCtrl.GetFont()
            font.SetUnderlined(True)
            eachCtrl.SetFont(font)
            eachCtrl.SetForegroundColour(wx.Colour(0, 0, 255))
            eachCtrl.SetCursor(wx.StockCursor(wx.CURSOR_HAND))

        def OnArgsEditSliders(event):
            name = textCtrl0.GetValue()
            dlg2 = AvsFilterAutoSliderInfo(dlg,
                                           self.GetParent(),
                                           name,
                                           textCtrl2.GetValue(),
                                           title=_('Slider information'))
            ID = dlg2.ShowModal()
            if ID == wx.ID_OK:
                textCtrl2.SetValue(dlg2.GetNewFilterInfo())
            dlg2.Destroy()

        staticText2_4.Bind(wx.EVT_LEFT_DOWN, OnArgsEditSliders)

        def OnClickSetToDefault(event):
            textCtrl0.SetValue(dlg.defaultName)
            textCtrl2.SetValue(dlg.defaultArgs)

        staticText2_5.Bind(wx.EVT_LEFT_DOWN, OnClickSetToDefault)
        textCtrl2 = wxp.TextCtrl(dlg,
                                 wx.ID_ANY,
                                 size=(200, 200),
                                 style=wx.TE_MULTILINE | wx.HSCROLL)

        def OnArgsChange(event):
            if checkBox3.IsChecked():
                name = textCtrl0.GetValue()  #dlg.defaultName
                args = textCtrl2.GetValue()
                textCtrl3.SetValue(self.CreateDefaultPreset(name, args))

        textCtrl0.Bind(wx.EVT_TEXT, OnArgsChange)
        textCtrl2.Bind(wx.EVT_TEXT, OnArgsChange)
        #~ textCtrl2.Bind(wx.EVT_LEFT_DCLICK, OnArgsEditSliders)
        staticText3 = wx.StaticText(dlg, wx.ID_ANY, _('Preset:'))
        checkBox3 = wx.CheckBox(dlg, wx.ID_ANY, _('Auto-generate'))

        def OnCheck(event):
            if checkBox3.IsChecked():
                textCtrl3.SetEditable(False)
                colour = self.GetBackgroundColour()
                textCtrl3.SetBackgroundColour(colour)
                OnArgsChange(None)
            else:
                textCtrl3.SetEditable(True)
                textCtrl3.SetBackgroundColour(wx.WHITE)

        checkBox3.Bind(wx.EVT_CHECKBOX, OnCheck)
        textCtrl3 = wxp.TextCtrl(dlg,
                                 wx.ID_ANY,
                                 size=(-1, 50),
                                 style=wx.TE_MULTILINE | wx.HSCROLL)
        # Standard buttons
        okay = wx.Button(dlg, wx.ID_OK, _('OK'))

        def OnFilterInfoDialogButtonOK(event):
            newName = textCtrl0.GetValue()
            enteredName = dlg.enteredName
            if enteredName is None:
                lowername = newName.lower()
                if lowername in self.overrideDict or lowername in self.filterDict:
                    wx.MessageBox(_('Filter name already exists!'),
                                  _('Error'),
                                  style=wx.OK | wx.ICON_ERROR)
                    textCtrl0.SetFocus()
                    return
                if not newName or newName[0].isdigit() or re.findall(
                        '\W', newName):
                    wx.MessageBox(_('Invalid filter name!'),
                                  _('Error'),
                                  style=wx.OK | wx.ICON_ERROR)
                    textCtrl0.SetFocus()
                    return
            elif newName.lower() != enteredName.lower():
                wx.MessageBox(_('Renaming not allowed!'),
                              _('Error'),
                              style=wx.OK | wx.ICON_ERROR)
                textCtrl0.SetFocus()
                return
            if dlg.typeBox.GetCurrentSelection() == 2 and newName.count(
                    '_') == 0:
                wx.MessageBox(_(
                    'You must use dllname_function naming format for plugins!'
                ),
                              _('Error'),
                              style=wx.OK | wx.ICON_ERROR)
                textCtrl0.SetFocus()
                return
            event.Skip()

        dlg.Bind(wx.EVT_BUTTON, OnFilterInfoDialogButtonOK, okay)
        cancel = wx.Button(dlg, wx.ID_CANCEL, _('Cancel'))
        btns = wx.StdDialogButtonSizer()
        btns.AddButton(okay)
        btns.AddButton(cancel)
        btns.Realize()
        # Size the elements
        sizer01 = wx.FlexGridSizer(cols=4, hgap=5, vgap=5)
        sizer01.Add(staticText0, 0, wx.ALIGN_CENTER_VERTICAL)
        sizer01.Add(textCtrl0, 0, wx.EXPAND | wx.RIGHT, 10)
        sizer01.Add(staticText1, 0, wx.ALIGN_CENTER_VERTICAL)
        sizer01.Add(choiceBox1, 0, wx.EXPAND)
        sizer2 = wx.BoxSizer(wx.HORIZONTAL)
        sizer2.Add(staticText2, 0, wx.ALL, 0)
        sizer2.Add((-1, -1), 1, wx.EXPAND | wx.ALL, 0)
        sizer2.Add(staticText2_5, 0, wx.RIGHT, 10)
        sizer2.Add(staticText2_4, 0, wx.LEFT | wx.RIGHT, 10)
        sizer3 = wx.BoxSizer(wx.HORIZONTAL)
        sizer3.Add(staticText3, 0, wx.ALL, 0)
        sizer3.Add((-1, -1), 1, wx.EXPAND | wx.ALL, 0)
        sizer3.Add(checkBox3, 0, wx.RIGHT, 10)
        dlgSizer = wx.BoxSizer(wx.VERTICAL)
        dlgSizer.Add((-1, 5), 0, wx.EXPAND | wx.ALL, 0)
        dlgSizer.Add(sizer01, 0, wx.EXPAND | wx.ALL, 5)
        dlgSizer.Add(wx.StaticLine(dlg, style=wx.HORIZONTAL), 0,
                     wx.EXPAND | wx.TOP | wx.BOTTOM, 5)
        #~ dlgSizer.Add(staticText2, 0, wx.EXPAND|wx.TOP|wx.LEFT, 5)
        dlgSizer.Add(sizer2, 0, wx.EXPAND | wx.TOP | wx.LEFT, 5)
        dlgSizer.Add(textCtrl2, 1, wx.EXPAND | wx.ALL, 5)
        #~ dlgSizer.Add(staticText3, 0, wx.TOP|wx.LEFT, 5)
        dlgSizer.Add(sizer3, 0, wx.EXPAND | wx.TOP | wx.LEFT, 5)
        dlgSizer.Add(textCtrl3, 0, wx.EXPAND | wx.ALL, 5)
        dlgSizer.Add(btns, 0, wx.EXPAND | wx.ALL, 5)
        dlg.SetSizer(dlgSizer)
        if not resetargsbutton:
            staticText2_5.Hide()

        def SetAutopreset(on=True):
            if on:
                checkBox3.SetValue(True)
                textCtrl3.SetEditable(False)
                colour = self.GetBackgroundColour()
                textCtrl3.SetBackgroundColour(colour)
            else:
                checkBox3.SetValue(False)
                textCtrl3.SetEditable(True)
                textCtrl3.SetBackgroundColour(wx.WHITE)

        dlg.SetAutopreset = SetAutopreset
        dlg.Fit()
        dlgSizer.Layout()
        # Bind variables
        dlg.nameBox = textCtrl0
        dlg.typeBox = choiceBox1
        dlg.argsBox = textCtrl2
        dlg.presetBox = textCtrl3
        dlg.resetCtrl = staticText2_5
        dlg.autopresetCheckbox = checkBox3
        dlg.cancelButton = cancel
        dlg.defaultArgs = ''
        dlg.defaultName = ''
        dlg.enteredName = ''
        self.FilterInfoDialog = dlg
Exemplo n.º 21
0
    def angle_from_mouse(self, workspace, pixel_data):
        '''Run a UI that gets an angle from the user'''
        import wx

        if self.how_often == IO_ONCE:
            d = self.get_dictionary(workspace.image_set_list)
            if d.has_key(D_ANGLE):
                return d[D_ANGLE]

        if pixel_data.ndim == 2:
            # make a color matrix for consistency
            pixel_data = np.dstack((pixel_data, pixel_data, pixel_data))
        pd_min = np.min(pixel_data)
        pd_max = np.max(pixel_data)
        if pd_min == pd_max:
            pixel_data[:, :, :] = 0
        else:
            pixel_data = ((pixel_data - pd_min) * 255.0 / (pd_max - pd_min))
        #
        # Make a 100 x 100 image so it's manageable
        #
        isize = 200
        i, j, k = np.mgrid[0:isize, 0:int(isize * pixel_data.shape[1] /
                                          pixel_data.shape[0]),
                           0:3].astype(float)
        i *= float(pixel_data.shape[0]) / float(isize)
        j *= float(pixel_data.shape[0]) / float(isize)
        pixel_data = scind.map_coordinates(pixel_data, (i, j, k))
        #
        # Make a dialog box that contains the image
        #
        dialog = wx.Dialog(workspace.frame, title="Rotate image")
        sizer = wx.BoxSizer(wx.VERTICAL)
        dialog.SetSizer(sizer)
        sizer.Add(
            wx.StaticText(dialog,
                          label="Drag image to rotate, hit OK to continue"), 0,
            wx.ALIGN_CENTER_HORIZONTAL)
        canvas = wx.StaticBitmap(dialog)
        canvas.SetDoubleBuffered(True)
        canvas.BackgroundColour = wx.Colour(0, 0, 0, wx.ALPHA_TRANSPARENT)
        sizer.Add(
            canvas, 0,
            wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5)
        angle = [0]
        angle_text = wx.StaticText(dialog, label="Angle: %d" % angle[0])
        sizer.Add(angle_text, 0, wx.ALIGN_CENTER_HORIZONTAL)

        def imshow():
            angle_text.Label = "Angle: %d" % int(angle[0])
            angle_text.Refresh()
            my_angle = -angle[0] * np.pi / 180.0
            transform = np.array([[np.cos(my_angle), -np.sin(my_angle)],
                                  [np.sin(my_angle),
                                   np.cos(my_angle)]])
            # Make it rotate about the center
            offset = affine_offset(pixel_data.shape, transform)
            x = np.dstack((scind.affine_transform(pixel_data[:, :, 0],
                                                  transform,
                                                  offset,
                                                  order=0),
                           scind.affine_transform(pixel_data[:, :, 1],
                                                  transform,
                                                  offset,
                                                  order=0),
                           scind.affine_transform(pixel_data[:, :, 2],
                                                  transform,
                                                  offset,
                                                  order=0)))
            buff = x.astype(np.uint8).tostring()
            bitmap = wx.BitmapFromBuffer(x.shape[1], x.shape[0], buff)
            canvas.SetBitmap(bitmap)

        imshow()
        #
        # Install handlers for mouse down, mouse move and mouse up
        #
        dragging = [False]
        initial_angle = [0]
        hand_cursor = wx.StockCursor(wx.CURSOR_HAND)
        arrow_cursor = wx.StockCursor(wx.CURSOR_ARROW)

        def get_angle(event):
            center = np.array(canvas.Size) / 2
            point = np.array(event.GetPositionTuple())
            offset = point - center
            return -np.arctan2(offset[1], offset[0]) * 180.0 / np.pi

        def on_mouse_down(event):
            canvas.Cursor = hand_cursor
            dragging[0] = True
            initial_angle[0] = get_angle(event) - angle[0]
            canvas.CaptureMouse()

        wx.EVT_LEFT_DOWN(canvas, on_mouse_down)

        def on_mouse_up(event):
            if dragging[0]:
                canvas.ReleaseMouse()
                dragging[0] = False
                canvas.Cursor = arrow_cursor

        wx.EVT_LEFT_UP(canvas, on_mouse_up)

        def on_mouse_lost(event):
            dragging[0] = False
            canvas.Cursor = arrow_cursor

        wx.EVT_MOUSE_CAPTURE_LOST(canvas, on_mouse_lost)

        def on_mouse_move(event):
            if dragging[0]:
                angle[0] = get_angle(event) - initial_angle[0]
                imshow()
                canvas.Refresh(eraseBackground=False)

        wx.EVT_MOTION(canvas, on_mouse_move)
        #
        # Put the OK and Cancel buttons on the bottom
        #
        btnsizer = wx.StdDialogButtonSizer()

        btn = wx.Button(dialog, wx.ID_OK)
        btn.SetDefault()
        btnsizer.AddButton(btn)

        btn = wx.Button(dialog, wx.ID_CANCEL)
        btnsizer.AddButton(btn)
        btnsizer.Realize()

        sizer.Add(btnsizer, 0, wx.ALIGN_CENTER_HORIZONTAL | wx.ALL, 5)
        dialog.Fit()
        result = dialog.ShowModal()
        dialog.Destroy()
        if result == wx.ID_OK:
            return angle[0]
        raise ValueError("Canceled by user in FlipAndRotate")
Exemplo n.º 22
0
    def OnMotion(self, evt):
        # Ignore mouse movement if we're not dragging.
        if not self.dragShape or not evt.Dragging() or not evt.LeftIsDown():
            return

        # if we have a shape, but haven't started dragging yet
        if self.dragShape and not self.dragImage:

            # only start the drag after having moved a couple pixels
            tolerance = 2
            pt = evt.GetPosition()
            dx = abs(pt.x - self.dragStartPos.x)
            dy = abs(pt.y - self.dragStartPos.y)
            if dx <= tolerance and dy <= tolerance:
                return

            # refresh the area of the window where the shape was so it
            # will get erased.
            self.dragShape.shown = False
            self.RefreshRect(self.dragShape.GetRect(), True)
            self.Update()

            if self.dragShape.text:
                self.dragImage = wx.DragString(self.dragShape.text,
                                              wx.StockCursor(wx.CURSOR_HAND))
            else:
                self.dragImage = wx.DragImage(self.dragShape.bmp,
                                             wx.StockCursor(wx.CURSOR_HAND))

            hotspot = self.dragStartPos - self.dragShape.pos
            self.dragImage.BeginDrag(hotspot, self, self.dragShape.fullscreen)

            self.dragImage.Move(pt)
            self.dragImage.Show()


        # if we have shape and image then move it, posibly highlighting another shape.
        elif self.dragShape and self.dragImage:
            onShape = self.FindShape(evt.GetPosition())
            unhiliteOld = False
            hiliteNew = False

            # figure out what to hilite and what to unhilite
            if self.hiliteShape:
                if onShape is None or self.hiliteShape is not onShape:
                    unhiliteOld = True

            if onShape and onShape is not self.hiliteShape and onShape.shown:
                hiliteNew = True

            # if needed, hide the drag image so we can update the window
            if unhiliteOld or hiliteNew:
                self.dragImage.Hide()

            if unhiliteOld:
                dc = wx.ClientDC(self)
                self.hiliteShape.Draw(dc)
                self.hiliteShape = None

            if hiliteNew:
                dc = wx.ClientDC(self)
                self.hiliteShape = onShape
                self.hiliteShape.Draw(dc, wx.INVERT)

            # now move it and show it again if needed
            self.dragImage.Move(evt.GetPosition())
            if unhiliteOld or hiliteNew:
                self.dragImage.Show()
Exemplo n.º 23
0
 def SetDefaultCursor(self, pusub_evt):
     self.interactor.SetCursor(wx.StockCursor(wx.CURSOR_DEFAULT))
Exemplo n.º 24
0
    def __init__(self, parent, ID):
        wx.ScrolledWindow.__init__(self, parent, ID)
        self.shapes = []
        self.dragImage = None
        self.dragShape = None
        self.hiliteShape = None
        self.labelID = 0

        self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))

        # Make a shape from an image and mask.  This one will demo
        # dragging outside the window
        xPos = 50
        for i in range(4):
            bmp = wx.Bitmap(str(i+1) + '.png')
            shape = DragShape(bmp)
            shape.SetLabel(str(i+1) + '.png')
            shape.pos = (xPos, 5)
            shape.fullscreen = True #makes image dragable outside the window also
            self.shapes.append(shape)
            xPos = xPos + 30

        
        # Make a shape from some text
##        xPos = 250
##        originalSeq = [1,2,3,4,5]
##        temp = originalSeq
##        random.shuffle(temp)
##        print temp
##        for i in temp:
##            text = str(i)
##            bg_colour = wx.Colour(57, 115, 57)  # matches the bg image
##            font = wx.Font(80, wx.ROMAN, wx.NORMAL, wx.BOLD)
##            textExtent = self.GetFullTextExtent(text, font)
##
##            # create a bitmap the same size as our text
##            bmp = wx.EmptyBitmap(textExtent[0], textExtent[1])
##
##            # 'draw' the text onto the bitmap
##            dc = wx.MemoryDC()
##            dc.SelectObject(bmp)
##            dc.SetBackground(wx.Brush(bg_colour, wx.SOLID))
##            dc.Clear()
##            dc.SetTextForeground(wx.BLACK)
##            dc.SetFont(font)
##            dc.DrawText(text, 0, 0)
##            dc.SelectObject(wx.NullBitmap)
##            mask = wx.Mask(bmp, bg_colour)
##            bmp.SetMask(mask)
##            shape = DragShape(bmp)
##            shape.SetLabel(self.labelID)
##            shape.pos = (xPos, 450)
##    ##        shape.text = "1" ##required only if shape of text to be changed during dragging
##            self.shapes.append(shape)
##            xPos = xPos + 90
##            self.labelID = self.labelID + 1


        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
        self.Bind(wx.EVT_MOTION, self.OnMotion)
        self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow)
Exemplo n.º 25
0
 def set_cursor(self):
     # http://www.wxpython.org/docs/api/wx.Cursor-class.html
     if self._canvas is not None:
         self._canvas.SetCursor(wx.StockCursor(wx.CURSOR_RIGHT_ARROW))
Exemplo n.º 26
0
    def __init__(self, parent, id=wx.ID_ANY, label='', pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=wx.NO_BORDER, *args, **kwargs):
        CONTROL.__init__(self, parent, id, pos, size, style, *args, **kwargs)

        self.parent = parent
        self.label = label

        self.bmp_normal = None
        self.bmp_hover = None
        self.bmp_focus = None
        self.bmp_mouse_down = None

        self.foreground_color_normal = '#000000'
        self.foreground_color_hover = None
        self.foreground_color_focus = None
        self.foreground_color_mouse_down = None

        # txt_shadow = (x, y, colour)
        self.txt_shadow_normal = None
        self.txt_shadow_hover = None
        self.txt_shadow_focus = None
        self.txt_shadow_mouse_down = None

        font = wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.NORMAL)
        self.font_normal = font
        self.font_hover = None
        self.font_focus = None
        self.font_mouse_down = None

        # border = (px, colour, radius)
        self.border = (1, '#333333', 0)
        self.border_hover = None
        self.border_focus = None
        self.border_mouse_down = None

        # padding = (top, right, bottom, left)
        self.padding = (0, 0, 0, 0)

        self.bg_type = 'color'
        parent_bg = self.parent.GetBackgroundColour()
        self.bg_color_normal = parent_bg
        self.bg_color_hover = None
        self.bg_color_focus = None
        self.bg_color_mouse_down = None

        if 'phoenix' in wx.PlatformInfo:
            self.cursor = wx.Cursor(wx.CURSOR_ARROW)
        else:
            self.cursor = wx.StockCursor(wx.CURSOR_ARROW)

        self.center = False
        self.size = None

        self.mouse_in = False
        self.mouse_down = False
        self.focus = False

        self.Bind(wx.EVT_SET_FOCUS, self._on_set_focus)
        self.Bind(wx.EVT_KILL_FOCUS, self._on_kill_focus)
        self.Bind(wx.EVT_LEAVE_WINDOW, self._on_mouse_leave)
        self.Bind(wx.EVT_ENTER_WINDOW, self._on_mouse_enter)
        self.Bind(wx.EVT_LEFT_DOWN, self._on_mouse_down)
        self.Bind(wx.EVT_LEFT_UP, self._on_mouse_up)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self._on_erase_background)
        self.Bind(wx.EVT_PAINT, self._on_paint)
Exemplo n.º 27
0
 def OnLeaveWindow(self, event):
     obj = event.GetEventObject()
     obj.SetCursor(wx.StockCursor(wx.CURSOR_DEFAULT))
     event.Skip()
Exemplo n.º 28
0
    def __init__(self, parent, giface, Map):
        self.parent = parent
        self.Map = Map
        self._giface = giface

        # Emitted when someone registers as mouse event handler
        self.mouseHandlerRegistered = Signal(
            'MapWindow.mouseHandlerRegistered')
        # Emitted when mouse event handler is unregistered
        self.mouseHandlerUnregistered = Signal(
            'MapWindow.mouseHandlerUnregistered')
        # emitted after double click in pointer mode on legend, text, scalebar
        self.overlayActivated = Signal('MapWindow.overlayActivated')
        # emitted when overlay should be hidden
        self.overlayHidden = Signal('MapWindow.overlayHidden')

        # mouse attributes -- position on the screen, begin and end of
        # dragging, and type of drawing
        self.mouse = {
            'begin': [0, 0],  # screen coordinates
            'end': [0, 0],
            'use': "pointer",
            'box': "point"
        }
        # last east, north coordinates, changes on mouse motion
        self.lastEN = None

        # stores overridden cursor
        self._overriddenCursor = None

        # dictionary where event types are stored as keys and lists of
        # handlers for these types as values
        self.handlersContainer = {
            wx.EVT_LEFT_DOWN: [],
            wx.EVT_LEFT_UP: [],
            wx.EVT_LEFT_DCLICK: [],
            wx.EVT_MIDDLE_DOWN: [],
            wx.EVT_MIDDLE_UP: [],
            wx.EVT_MIDDLE_DCLICK: [],
            wx.EVT_RIGHT_DOWN: [],
            wx.EVT_RIGHT_UP: [],
            wx.EVT_RIGHT_DCLICK: [],
            wx.EVT_MOTION: [],
            wx.EVT_ENTER_WINDOW: [],
            wx.EVT_LEAVE_WINDOW: [],
            wx.EVT_MOUSEWHEEL: [],
            wx.EVT_MOUSE_EVENTS: []
        }

        # available cursors
        self._cursors = {
            "default": wx.StockCursor(wx.CURSOR_ARROW),
            "cross": wx.StockCursor(wx.CURSOR_CROSS),
            "hand": wx.StockCursor(wx.CURSOR_HAND),
            "pencil": wx.StockCursor(wx.CURSOR_PENCIL),
            "sizenwse": wx.StockCursor(wx.CURSOR_SIZENWSE)
        }

        # default cursor for window is arrow (at least we rely on it here)
        # but we need to define attribute here
        # cannot call SetNamedCursor since it expects the instance
        # to be a wx window, so setting only the attribute
        self._cursor = 'default'

        wx.CallAfter(self.InitBinding)
Exemplo n.º 29
0
 def showCursor(self, event=None):
     if not self.cursorVisible:
         self.SetCursor(wx.StockCursor(wx.CURSOR_DEFAULT))
         self.editCtrl.SetCursor(wx.StockCursor(wx.CURSOR_IBEAM))
         self.cursorVisible = True
Exemplo n.º 30
0
def StartGame(gameroot, project, progress):

    global PROGRESS

    PROGRESS = progress
    PROGRESS_COUNTER = 0

    valid = (".py", ".cs")

    pdict = {}

    messageService = wx.GetApp().GetService(MessageService.MessageService)
    messageService.ShowWindow()

    view = messageService.GetView()
    if view:
        wx.GetApp().GetTopWindow().SetCursor(wx.StockCursor(wx.CURSOR_WAIT))
        view.ClearLines()
        view.AddLines("Starting new game\n\n")

    STUFF = list(dirwalk('./starter.mmo'))

    assert 'starter.mmo' not in gameroot
    assert 'minions.of.mirth' not in gameroot
    #assert not os.path.exists(gameroot)

    pfiles = []
    for src in STUFF:
        dst = src.replace("starter.mmo", gameroot)

        try:
            os.makedirs(os.path.dirname(dst))
        except OSError:
            pass  # dir exists, ignore error
        if view:
            view.AddLines("copying %s\n" % src)
        shutil.copyfile(src, dst)

        PROGRESS.Update(PROGRESS_COUNTER, dst)
        PROGRESS_COUNTER += .25
        PROGRESS_COUNTER %= 100

        pfiles.append(dst)

    f = file("%s/packaging/content.py" % gameroot, "r")
    s = f.read()
    f.close()
    s = s.replace("starter.mmo", gameroot)

    f = file("%s/packaging/content.py" % gameroot, "w")
    f.write(s)
    f.close()

    project.AddFiles(["serverconfig/server.cfg"], "config")

    AddCoreModules(project)

    for dst in pfiles:
        dst = dst[2:]
        fname, ext = os.path.splitext(dst)
        if ext.lower() not in valid:
            continue

        base = os.path.dirname(dst)

        if not pdict.has_key(base):
            pdict[base] = []

        pdict[base].append(dst)

    pview = project.GetFirstView()

    if pview:
        pview._treeCtrl.Freeze()

    bases = pdict.keys()
    bases.sort()

    for base in bases:
        files = pdict[base]
        files.sort()
        project.AddFiles(files, base)
        PROGRESS.Update(PROGRESS_COUNTER, base)
        PROGRESS_COUNTER += 1
        PROGRESS_COUNTER %= 100

    if pview:
        try:
            pview._treeCtrl.CollapseAll()
        except:
            pass

        pview._treeCtrl.Thaw()

    SaveConfig(project)

    project.OnSaveDocument(project.GetFilename())

    if view:
        view.AddLines("\n\nNew game started.\n")
        wx.GetApp().GetTopWindow().SetCursor(wx.StockCursor(wx.CURSOR_DEFAULT))