예제 #1
0
    def __init__(self, x, y, degree=3, w=None):
        try:
            from geomdl import NURBS, utilities
            self.utilities = utilities
        except ImportError:
            error_message('The module `geomdl` is not installed, but it is required for NURBS!')

        self._x = x
        self._y = y
        self._n = len(x)

        if(w is None):
            w = np.ones(x.shape)
        self._w = w

        # Create the curve
        curve = NURBS.Curve()
        curve.degree = degree
        self._degree = degree

        cpoints = np.zeros((self._n,2))
        cpoints[:,0] = x
        cpoints[:,1] = y
        self._cpoints = cpoints

        curve.ctrlpts = cpoints
        curve.knotvector = utilities.generate_knot_vector(degree, len(cpoints))
        curve.weights = w
        self._curve = curve
예제 #2
0
 def _get_preview_filename(self):
     import warnings
     warnings.filterwarnings("ignore", "tempnam", RuntimeWarning,
                             "application")
     if compat.PYTHON2:
         out_name = os.tempnam(None, 'wxg') + '.py'
     else:
         # create a temporary file at either the output path or the project path
         error = None
         if not self.filename:
             error = "Save project first; a temporary file will be created in the same directory."
         else:
             dirname, basename = os.path.split(self.filename)
             basename, extension = os.path.splitext(basename)
             basename = basename.replace(".", "_")
             if not os.path.exists(dirname):
                 error = "Directory '%s' not found" % dirname
             elif not os.path.isdir(dirname):
                 error = "'%s' is not a directory" % dirname
         if error:
             misc.error_message(error)
             return None
         while True:
             out_name = os.path.join(
                 dirname,
                 "_%s_%d.py" % (basename, random.randrange(10**8, 10**9)))
             if not os.path.exists(out_name): break
     return out_name
    def generate_code(self, preview=False, out_path=None, widget=None):
        if config.use_gui:
            common.property_panel.flush()
        else:
            np.flush_current_property()
        if out_path is None:
            out_path = os.path.expanduser(self.output_path.strip())
            if not os.path.isabs(out_path) and (out_path and self.filename):
                out_path = os.path.join(os.path.dirname(self.filename),
                                        out_path)
                out_path = os.path.normpath(out_path)

        if not out_path:
            msg = "You must specify an output file before generating any code."
            if not self.filename:
                msg += "\nFor relative file names, the project needs to be saved first."
            return misc.error_message(msg)

        name_p = self.properties["name"]
        class_p = self.properties["class"]
        if self.language != "XRC":
            if not preview and (name_p.is_active() or
                                class_p.is_active()) and not self.top_window:
                return misc.error_message(
                    "Please select a top window for the application or deactivate "
                    "the Name and Class properties for Application.\n"
                    "In that case, only code for the windows will be generated, not for the "
                    "application.")

        if preview:
            writer = common.code_writers["python"].copy()
        else:
            writer = common.code_writers[self.language]  #.copy()

        try:
            writer.new_project(self, out_path, preview)
            writer.generate_code(self.node, widget)
            writer.finalize()
        except errors.WxgBaseException as inst:
            misc.error_message(_("Error generating code:\n%s") % inst)
            return
        except EnvironmentError as inst:
            bugdialog.ShowEnvironmentError(
                _('An IO/OS related error is occurred:'), inst)
            bugdialog.Show(_('Generate Code'), inst)
            return
        finally:
            writer.clean_up(self.node)

        if preview or not config.use_gui: return
        if config.preferences.show_completion:
            # Show informational dialog
            misc.info_message("Code generation completed successfully")
        else:
            # Show message in application status bar
            app = wx.GetApp()
            frame = app.GetTopWindow()
            frame.user_message(_('Code generated'))
예제 #4
0
def paste(widget):
    """Copies a widget (and all its children) from the clipboard to the given
    destination (parent, sizer and position inside the sizer). Returns True on success."""
    error = None
    if not wx.TheClipboard.Open():
        misc.error_message("Clipboard can't be opened.")
        return False

    try:
        data_object = None
        for fmt in [widget_data_format, sizer_data_format, window_data_format]:
            if wx.TheClipboard.IsSupported(fmt):
                data_object = wx.CustomDataObject(fmt)
                break
        if data_object is None:
            misc.info_message(
                "The clipboard doesn't contain wxGlade widget data.")
            return False
        if not wx.TheClipboard.GetData(data_object):
            misc.error_message("Data can't be copied from clipboard.")
            return False
    finally:
        wx.TheClipboard.Close()
    format_name = data_object.GetFormat().GetId().split(".")[
        1]  # e.g. 'wxglade.widget' -> 'widget'
    compatible, message = widget.check_compatibility(None, format_name)
    if not compatible:
        wx.Bell()
        if message:
            misc.error_message(message)
        return False
    if not widget.clipboard_paste(data_object.GetData()):
        misc.error_message("Paste failed")
예제 #5
0
파일: tree.py 프로젝트: pywangyu/wxGlade
    def on_left_click(self, event):
        if not common.adding_widget: return event.Skip()
        editor = self.find_editor_by_pos( *event.GetPosition() )
        if not editor: return event.Skip()

        compatible, message = editor.check_drop_compatibility()
        if not compatible:
            event.Skip()
            misc.error_message(message)
            return

        common.adding_window = event.GetEventObject().GetTopLevelParent()
        if editor.IS_SLOT:
            editor.on_drop_widget(event)
        elif common.adding_sizer or True:
            editor.drop_sizer()
        common.adding_window = None
예제 #6
0
    def on_left_click(self, event):
        if not common.adding_widget: return event.Skip()
        node = self._find_node_by_pos(*event.GetPosition())
        if not node: return event.Skip()

        item = node.widget
        compatible, message = item.check_drop_compatibility()
        if not compatible:
            event.Skip()
            misc.error_message(message)
            return

        common.adding_window = event.GetEventObject().GetTopLevelParent()
        if isinstance(item, edit_sizers.SizerSlot):
            item.on_drop_widget(event)
        elif common.adding_sizer:
            item.drop_sizer()
        common.adding_window = None
예제 #7
0
    def on_drop_files(self, x, y, filenames):
        if len(filenames) > 1:
            misc.error_message(_("Please only drop one file at a time"))
            return False
        # find the control and then the property
        screen_xy = self.ClientToScreen((x, y))
        ctrl = wx.FindWindowAtPoint(screen_xy)
        if not ctrl: return False

        for p_name in self.current_widget.PROPERTIES:
            if p_name[0].isupper(): continue
            prop = self.current_widget.properties.get(p_name)
            if not prop or not hasattr(prop, "on_drop_file"): continue
            if (hasattr(prop, "label_ctrl")
                    and prop.label_ctrl.ScreenRect.Contains(screen_xy)
                    and prop.label_ctrl.IsShownOnScreen()
                ) or prop.has_control(ctrl):
                return prop.on_drop_file(filenames[0])
        return False
예제 #8
0
    def preview(self, widget, position=None):
        """Generate and instantiate preview widget.
        None will be returned in case of errors. The error details are written to the application log file."""

        preview_filename = self._get_preview_filename()
        if preview_filename is None: return

        if wx.Platform == "__WXMAC__" and not compat.PYTHON2:
            # workaround for Mac OS testing: sometimes the caches need to be invalidated
            import importlib
            importlib.invalidate_caches()

        # make a valid name for the class (this can be invalid for some sensible reasons...)
        preview_classname = widget.WX_CLASS.split('.')[-1].split(':')[-1]
        # randomize the class name to make preview work when there are multiple classes with the same name (e.g. XRC)
        preview_classname = '_%d_%s' % (random.randrange(10**8, 10**
                                                         9), preview_classname)
        widget.properties["class"].set_temp(preview_classname)

        frame = None
        try:
            self.generate_code(True, preview_filename, widget)
            # import generated preview module dynamically
            preview_path = os.path.dirname(preview_filename)
            preview_module_name = os.path.basename(preview_filename)
            preview_module_name = os.path.splitext(preview_module_name)[0]
            preview_module = plugins.import_module(preview_path,
                                                   preview_module_name)
            if not preview_module:
                misc.error_message(
                    _('Can not import the preview module from file \n"%s".\n'
                      'The details are written to the log file.\n'
                      'If you think this is a wxGlade bug, please report it.')
                    % self.output_path)
                return None

            try:
                preview_class = getattr(preview_module,
                                        preview_classname)  # .klass)
            except AttributeError:
                # module loaded previously -> do a re-load XXX this is required for Python 3; check alternatives
                if sys.version_info.major < 3:
                    preview_module = reload(preview_module)
                else:
                    import importlib
                    preview_module = importlib.reload(preview_module)
                preview_class = getattr(preview_module, preview_classname)

            if not preview_class:
                misc.error_message(
                    _('No preview class "%s" found.\nThe details are written to the log file.\n'
                      'If you think this is a wxGlade bug, please report it.')
                    % widget.klass)
                return None

            if issubclass(preview_class, wx.MDIChildFrame):
                frame = wx.MDIParentFrame(None, -1, '')
                frame.SetMenuBar(wx.MenuBar())  # avoid assertion error
                child = preview_class(frame, -1, '')
                child.SetTitle('<Preview> - ' + child.GetTitle())
                w, h = child.GetSize()
                frame.SetClientSize((w + 20, h + 20))
            elif not issubclass(preview_class, (wx.Frame, wx.Dialog)):
                # the toplevel class isn't really toplevel, add a frame...
                frame = wx.Frame(None, -1, widget.klass)
                if issubclass(preview_class, wx.MenuBar):
                    menubar = preview_class()
                    frame.SetMenuBar(menubar)
                    panel = wx.Panel(frame)
                elif issubclass(preview_class, wx.ToolBar):
                    toolbar = preview_class(frame, -1)
                    frame.SetToolBar(toolbar)
                    panel = wx.Panel(frame)
                    frame.SetMinSize(toolbar.GetBestSize())
                    frame.Fit()
                else:
                    panel = preview_class(frame, -1)
                    frame.Fit()
            else:
                frame = preview_class(None, -1, '')

            def on_close(event):
                frame.Unbind(wx.EVT_CHAR_HOOK)
                compat.DestroyLater(frame)
                widget.preview_widget = None
                widget.properties["preview"].set_label(_('Show Preview'))

            frame.Bind(wx.EVT_CLOSE, on_close)
            frame.SetTitle(_('<Preview> - %s') % frame.GetTitle())
            # raise the frame
            if position:
                frame.SetPosition(position)
            else:
                frame.CenterOnScreen()
                if widget.widget:
                    # avoid Design and Preview window at the same position
                    pos = widget.widget.GetPosition()
                    if frame.GetPosition() == pos:
                        frame.SetPosition((pos[0] + 200, pos[1] + 100))
            frame.Show()
            # install handler for key down events
            frame.Bind(wx.EVT_CHAR_HOOK, self.on_char_hook)

            # remove the temporary file
            if not config.debugging:
                name = os.path.join(preview_path, preview_module_name + ".py")
                if os.path.isfile(name): os.unlink(name)
        except Exception as inst:
            if config.debugging or config.testing: raise
            widget.preview_widget = None
            widget.properties["preview"].set_label(_('Show Preview'))
            bugdialog.Show(_("Generate Preview"), inst)

        return frame
예제 #9
0
    def generate_code(self, preview=False, out_path=None, widget=None):
        np.flush_current_property()
        if out_path is None:
            out_path = os.path.expanduser(self.output_path.strip())
            if not out_path and self.multiple_files: out_path = "."
            if not os.path.isabs(out_path) and (out_path and self.filename):
                out_path = os.path.join(os.path.dirname(self.filename),
                                        out_path)
                out_path = os.path.normpath(out_path)

        if not out_path:
            msg = "You must specify an output file before generating any code."
            if not self.filename:
                msg += "\nFor relative file names, the project needs to be saved first."
            return misc.error_message(msg)

        name_p = self.properties["name"]
        class_p = self.properties["class"]
        if self.language != "XRC":
            if not preview and (name_p.is_active() or
                                class_p.is_active()) and not self.top_window:
                return misc.error_message(
                    "Please select a top window for the application or deactivate "
                    "the Name and Class properties for Application.\n"
                    "In that case, only code for the windows will be generated, not for the "
                    "application.")

        if preview:
            writer = common.code_writers["preview"]
        else:
            writer = common.code_writers[self.language]

        error = writer.new_project(self, out_path, preview)
        if error:
            # prerequisites were checked and there is a problem
            misc.error_message(_("Error generating code:\n%s") % error)
            return

        try:
            writer.generate_code(self, widget)
            writer.finalize()
        except EnvironmentError as inst:
            bugdialog.ShowEnvironmentError(
                _('An IO related error has occurred:'), inst)
            return
        except UnicodeEncodeError as inst:
            msg = _("Could not convert generated source code to encoding %s.\n"
                    '(characters "%s")')
            chars = inst.object[inst.start:
                                inst.end]  # .encode('unicode-escape')
            msg = msg % (self.encoding, chars)
            misc.error_message(msg)
            return
        except Exception as inst:
            # unexpected / internal error
            if config.testing or config.debugging: raise
            bugdialog.Show(_('Generate Code'), inst)
            return
        finally:
            writer.clean_up(widget or self)

        if preview or not config.use_gui: return
        if config.preferences.show_completion:
            # Show informational dialog
            misc.info_message("Code generation completed successfully")
        else:
            # Show message in application status bar
            app = wx.GetApp()
            frame = app.GetTopWindow()
            frame.user_message(_('Code generated'))
    def preview(self, widget, position=None):
        """Generate and instantiate preview widget.
        None will be returned in case of errors. The error details are written to the application log file."""
        # some checks
        #if compat.IS_PHOENIX:
        #found = common.app_tree.find_widgets_by_classnames(widget.node, "EditPropertyGridManager")
        #if found:
        #error = ("Preview with PropertyGridManager controls is currently deactivated as it causes crashes "
        #"with wxPython Phoenix")
        #wx.MessageBox( error, _('Error'), wx.OK | wx.CENTRE | wx.ICON_EXCLAMATION )
        #return
        # XXX check other things as well, e.g. different bitmap sizes for BitmapButton

        preview_filename = self._get_preview_filename()
        if preview_filename is None: return
        widget_class_name = widget.klass

        # make a valid name for the class (this can be invalid for some sensible reasons...)
        widget_class = widget.klass[widget.klass.rfind('.') + 1:]
        widget_class = widget.klass[widget.klass.rfind(':') + 1:]
        # ALB 2003-11-08: always randomize the class name: this is to make preview work even when there are multiple
        # classes with the same name (which makes sense for XRC output...)
        widget_class = '_%d_%s' % (random.randrange(10**8, 10**
                                                    9), widget_class)
        widget.properties["class"].set(widget_class)

        if wx.Platform == "__WXMAC__" and not compat.PYTHON2:
            # workaround for Mac OS testing: sometimes the caches need to be invalidated
            import importlib
            importlib.invalidate_caches()

        frame = None
        try:
            self.generate_code(True, preview_filename, widget)
            # import generated preview module dynamically
            preview_path = os.path.dirname(preview_filename)
            preview_module_name = os.path.basename(preview_filename)
            preview_module_name = os.path.splitext(preview_module_name)[0]
            preview_module = plugins.import_module(preview_path,
                                                   preview_module_name)
            if not preview_module:
                misc.error_message(
                    _('Can not import the preview module from file \n"%s".\n'
                      'The details are written to the log file.\n'
                      'If you think this is a wxGlade bug, please report it.')
                    % self.output_path)
                return None

            try:
                preview_class = getattr(preview_module, widget.klass)
            except AttributeError:
                # module loade previously -> do a re-load XXX this is required for Python 3; check alternatives
                import importlib
                preview_module = importlib.reload(preview_module)
                preview_class = getattr(preview_module, widget.klass)

            if not preview_class:
                misc.error_message(
                    _('No preview class "%s" found.\nThe details are written to the log file.\n'
                      'If you think this is a wxGlade bug, please report it.')
                    % widget.klass)
                return None

            if issubclass(preview_class, wx.MDIChildFrame):
                frame = wx.MDIParentFrame(None, -1, '')
                frame.SetMenuBar(wx.MenuBar())  # avoid assertion error
                child = preview_class(frame, -1, '')
                child.SetTitle('<Preview> - ' + child.GetTitle())
                w, h = child.GetSize()
                frame.SetClientSize((w + 20, h + 20))
            elif not issubclass(preview_class, (wx.Frame, wx.Dialog)):
                # the toplevel class isn't really toplevel, add a frame...
                frame = wx.Frame(None, -1, widget_class_name)
                if issubclass(preview_class, wx.MenuBar):
                    menubar = preview_class()
                    frame.SetMenuBar(menubar)
                    panel = wx.Panel(frame)
                elif issubclass(preview_class, wx.ToolBar):
                    toolbar = preview_class(frame, -1)
                    frame.SetToolBar(toolbar)
                    panel = wx.Panel(frame)
                    frame.SetMinSize(toolbar.GetBestSize())
                    frame.Fit()
                else:
                    panel = preview_class(frame, -1)
                    frame.Fit()
            else:
                frame = preview_class(None, -1, '')

            def on_close(event):
                frame.Unbind(wx.EVT_CHAR_HOOK)
                compat.DestroyLater(frame)
                widget.preview_widget = None
                widget.properties["preview"].set_label(_('Show Preview'))

            frame.Bind(wx.EVT_CLOSE, on_close)
            frame.SetTitle(_('<Preview> - %s') % frame.GetTitle())
            # raise the frame
            if position:
                frame.SetPosition(position)
            else:
                frame.CenterOnScreen()
                if widget.widget:
                    # avoid Design and Preview window at the same position
                    pos = widget.widget.GetPosition()
                    if frame.GetPosition() == pos:
                        frame.SetPosition((pos[0] + 200, pos[1] + 100))
            frame.Show()
            # install handler for key down events
            frame.Bind(wx.EVT_CHAR_HOOK, self.on_char_hook)

            # remove the temporary file
            if not config.debugging:
                name = os.path.join(preview_path, preview_module_name + ".py")
                if os.path.isfile(name): os.unlink(name)
        except Exception as inst:
            if config.debugging or config.testing: raise
            widget.preview_widget = None
            widget.properties["preview"].set_label(_('Show Preview'))
            bugdialog.Show(_("Generate Preview"), inst)
        # XXX restore app state
        widget.properties["class"].set(widget_class_name)
        return frame