예제 #1
0
 def set_values(self):
     try:
         self.open_save_path.SetValue(self.preferences.open_save_path)
         self.codegen_path.SetValue(self.preferences.codegen_path)
         self.use_dialog_units.SetValue(self.preferences.use_dialog_units)
         self.number_history.SetValue(self.preferences.number_history)
         self.show_progress.SetValue(self.preferences.show_progress)
         self.wxg_backup.SetValue(self.preferences.wxg_backup)
         self.codegen_backup.SetValue(self.preferences.codegen_backup)
         self.default_border.SetValue(self.preferences.default_border)
         self.default_border_size.SetValue(
             self.preferences.default_border_size)
         if self.preferences.backup_suffix == '.bak':
             self.backup_suffix.SetSelection(1)
         self.remember_geometry.SetValue(self.preferences.remember_geometry)
         self.local_widget_path.SetValue(self.preferences.local_widget_path)
         self.show_sizer_handle.SetValue(self.preferences.show_sizer_handle)
         self.allow_duplicate_names.SetValue(
             self.preferences.allow_duplicate_names)
         self.autosave.SetValue(self.preferences.autosave)
         self.autosave_delay.SetValue(self.preferences.autosave_delay)
         self.show_completion.SetValue(self.preferences.show_completion)
         self.write_timestamp.SetValue(self.preferences.write_timestamp)
         self.write_generated_from.SetValue(
             self.preferences.write_generated_from)
         self._fix_spin_ctrls()
     except Exception as inst:
         bugdialog.Show(_('Read Configuration'), inst)
예제 #2
0
    def import_xrc(self, infilename=None):
        import xrc2wxg

        if not self.ask_save():
            return

        if not infilename:
            infilename = wx.FileSelector(_("Import file"),
                                         wildcard="XRC files (*.xrc)"
                                         "|*.xrc|All files|*",
                                         flags=wx.FD_OPEN
                                         | wx.FD_FILE_MUST_EXIST,
                                         default_path=self.cur_dir)
        if infilename:
            ibuffer = []
            try:
                xrc2wxg.convert(infilename, ibuffer)

                # Convert UTF-8 returned by xrc2wxg.convert() to Unicode
                tmp = b"".join(ibuffer).decode('UTF-8')
                ibuffer = ['%s\n' % line for line in tmp.split('\n')]

                self._open_app(ibuffer)
                common.app_tree.app.saved = False
            except Exception as inst:
                fn = os.path.basename(infilename).encode('ascii', 'replace')
                bugdialog.Show(_('Import File "%s"') % fn, inst)
예제 #3
0
 def set_encoding(self, value):
     try:
         unicode('a', value)
     except LookupError as inst:
         bugdialog.Show(_('Set Encoding'), inst)
         self.encoding_prop.set_value(self.encoding)
     else:
         self.encoding = value
    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'))
예제 #5
0
    def set_values(self):
        try:
            self.open_save_path.SetValue(self.preferences.open_save_path)
            self.codegen_path.SetValue(self.preferences.codegen_path)
            self.allow_custom_widgets.SetValue(
                self.preferences.allow_custom_widgets)
            self.use_dialog_units.SetValue(self.preferences.use_dialog_units)
            self.number_history.SetValue(self.preferences.number_history)
            if hasattr(self, "font_scale_tree"):
                self.font_scale_tree.SetValue(self.preferences.font_scale_tree)
            self.show_progress.SetValue(self.preferences.show_progress)
            self.wxg_backup.SetValue(self.preferences.wxg_backup)
            self.codegen_backup.SetValue(self.preferences.codegen_backup)
            self.default_border.SetValue(self.preferences.default_border)
            self.default_border_size.SetValue(
                self.preferences.default_border_size)
            if self.preferences.backup_suffix == '.bak':
                self.backup_suffix.SetSelection(1)
            self.remember_geometry.SetValue(self.preferences.remember_geometry)
            self.local_widget_path.SetValue(self.preferences.local_widget_path)
            self.show_sizer_handle.SetValue(self.preferences.show_sizer_handle)
            self.show_palette_icons.SetValue(
                self.preferences.show_palette_icons)
            self.show_palette_labels.SetValue(
                self.preferences.show_palette_labels)
            self.show_gridproperty_editors.SetValue(
                self.preferences.show_gridproperty_editors)
            self.use_checkboxes_workaround.SetValue(
                self.preferences.use_checkboxes_workaround)
            self.no_checkbox_label_colours.SetValue(
                self.preferences.no_checkbox_label_colours)

            self.allow_duplicate_names.SetValue(
                self.preferences.allow_duplicate_names)
            self.autosave.SetValue(self.preferences.autosave)
            self.autosave_delay.SetValue(self.preferences.autosave_delay)
            self.show_completion.SetValue(self.preferences.show_completion)
            self.write_timestamp.SetValue(self.preferences.write_timestamp)
            self.write_generated_from.SetValue(
                self.preferences.write_generated_from)
            self._fix_spin_ctrls()
        except Exception as inst:
            bugdialog.Show(_('Read Configuration'), inst)
예제 #6
0
 def _save_app(self, filename):
     try:
         obuffer = compat.StringIO()
         common.app_tree.write(obuffer)
         common.save_file(filename, obuffer.getvalue(), 'wxg')
     except EnvironmentError as inst:
         common.app_tree.app.saved = False
         bugdialog.ShowEnvironmentError(_('Saving this project failed'),
                                        inst)
     except Exception as inst:
         common.app_tree.app.saved = False
         fn = os.path.basename(filename).encode('ascii', 'replace')
         bugdialog.Show(_('Save File "%s"') % fn, inst)
     else:
         common.app_tree.app.saved = True
         common.remove_autosaved()
         if config.preferences.autosave and self.autosave_timer is not None:
             self.autosave_timer.Start()
         self.user_message(_("Saved %s") % os.path.basename(filename))
예제 #7
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
예제 #8
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'))
예제 #9
0
    def preview(self, widget, out_name=None):
        """Generate and instantiate preview widget.
        None will be returned in case of errors. The error details are written to the application log file."""
        if out_name is None:
            import warnings
            warnings.filterwarnings("ignore", "tempnam", RuntimeWarning,
                                    "application")
            try:
                out_name = os.tempnam(None, 'wxg') + '.py'
            except AttributeError:  # XXX use a different name; e.g. the project file name with "_temp"
                out_name = "C:\\Users\\Dietmar\\wxg_tmp.py"
        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)

        self.real_output_path = self.output_path
        self.properties["output_path"].set(out_name)
        real_multiple_files = self.multiple_files
        real_language = self.language
        real_use_gettext = self.use_gettext
        self.properties["use_gettext"].set(False)
        self.properties["language"].set('python')
        self.properties["multiple_files"].set(False)
        overwrite = self.overwrite
        self.properties["overwrite"].set(False)

        frame = None
        try:
            self.generate_code(preview=True)
            # import generated preview module dynamically
            preview_path = os.path.dirname(self.output_path)
            preview_module_name = os.path.basename(self.output_path)
            preview_module_name = os.path.splitext(preview_module_name)[0]
            preview_module = plugins.import_module(preview_path,
                                                   preview_module_name)
            if not preview_module:
                wx.MessageBox(
                    _('Can not import the preview module from file \n"%s".\n'
                      'The details are written to the log file.\nIf you think this is a wxGlade bug, please '
                      'report it.') % self.output_path, _('Error'),
                    wx.OK | wx.CENTRE | wx.ICON_EXCLAMATION)
                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:
                wx.MessageBox(
                    _('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, _('Error'),
                    wx.OK | wx.CENTRE | wx.ICON_EXCLAMATION)
                return None

            if issubclass(preview_class, wx.MDIChildFrame):
                frame = wx.MDIParentFrame(None, -1, '')
                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)
                elif issubclass(preview_class, wx.ToolBar):
                    toolbar = preview_class(frame, -1)
                    frame.SetToolBar(toolbar)
                else:
                    panel = preview_class(frame, -1)
                frame.Fit()
            else:
                frame = preview_class(None, -1, '')

            def on_close(event):
                frame.Destroy()
                widget.preview_widget = None
                widget.properties["preview"].set_label(_('Preview'))

            wx.EVT_CLOSE(frame, on_close)
            frame.SetTitle(_('<Preview> - %s') % frame.GetTitle())
            # raise the frame
            frame.CenterOnScreen()
            frame.Show()
            # remove the temporary file (and the .pyc/.pyo ones too)
            for ext in ('', 'c', 'o', '~'):
                name = self.output_path + ext
                if os.path.isfile(name):
                    os.unlink(name)
        except Exception as inst:
            widget.preview_widget = None
            widget.properties["preview"].set_label(_('Preview'))
            bugdialog.Show(_("Generate Preview"), inst)

        # restore app state
        widget.properties["class"].set(widget_class_name)
        self.properties["output_path"].set(self.real_output_path)
        del self.real_output_path
        self.properties["multiple_files"].set(real_multiple_files)
        self.properties["language"].set(real_language)
        self.properties["use_gettext"].set(real_use_gettext)
        self.properties["overwrite"].set(overwrite)
        return frame
예제 #10
0
    def generate_code(self, *args, **kwds):
        preview = kwds.get('preview', False)
        if not self.output_path:
            return wx.MessageBox(
                _("You must specify an output file\nbefore generating any code"
                  ), _("Error"), wx.OK | wx.CENTRE | wx.ICON_EXCLAMATION,
                self.notebook)
        name_p = self.properties["name"]
        class_p = self.properties["class"]
        if not preview and (name_p.is_active()
                            or class_p.is_active()) and not self.top_window:
            return wx.MessageBox(
                _("Please select a top window for the application"),
                _("Error"), wx.OK | wx.CENTRE | wx.ICON_EXCLAMATION,
                self.notebook)

        # temporary buffer for XML
        tmp_xml = misc.UnicodeStringIO('utf-8')

        from xml_parse import CodeWriter
        try:
            # generate the code from the xml buffer
            language = self.language

            # save and overwrite some code generation settings; to be restored below
            if preview and language == 'python':
                overwrite_save = self.overwrite
                self.properties["overwrite"].set(True)

            class_names = common.app_tree.write(tmp_xml)

            out_path = os.path.expanduser(self.output_path.strip())
            if not os.path.isabs(out_path) and self.filename:
                out_path = os.path.join(os.path.dirname(self.filename),
                                        out_path)
                out_path = os.path.normpath(out_path)
            else:
                out_path = None

            CodeWriter(common.code_writers[language],
                       tmp_xml.getvalue(),
                       True,
                       preview=preview,
                       out_path=out_path,
                       class_names=class_names)

            # restore saved settings
            if preview and language == 'python':
                self.properties["overwrite"].set(overwrite_save)

        except errors.WxgBaseException as inst:
            wx.MessageBox(
                _("Error generating code:\n%s") % inst, _("Error"),
                wx.OK | wx.CENTRE | wx.ICON_ERROR)
        except EnvironmentError as inst:
            bugdialog.ShowEnvironmentError(
                _('An IO/OS related error is occurred:'), inst)
            bugdialog.Show(_('Generate Code'), inst)
        else:
            if not preview:
                if config.preferences.show_completion:
                    # Show informational dialog
                    wx.MessageBox(_("Code generation completed successfully"),
                                  _("Information"),
                                  wx.OK | wx.CENTRE | wx.ICON_INFORMATION)
                else:
                    # Show message in application status bar
                    app = wx.GetApp()
                    frame = app.GetTopWindow()
                    frame.user_message(_('Code generated'))
예제 #11
0
    def preview(self, widget, out_name=None):
        """\
        Generate and instantiate preview widget.

        None will be returned in case of errors. The error details are
        written to the application log file.
        """
        if out_name is None:
            import warnings
            warnings.filterwarnings("ignore", "tempnam", RuntimeWarning,
                                    "application")
            out_name = os.tempnam(None, 'wxg') + '.py'
        widget_class_name = widget.klass

        # make a valid name for the class (this can be invalid for
        # some sensible reasons...)
        widget.klass = widget.klass[widget.klass.rfind('.') + 1:]
        widget.klass = 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.klass = '_%d_%s' % \
                       (random.randrange(10 ** 8, 10 ** 9), widget.klass)

        self.real_output_path = self.output_path
        self.output_path = out_name
        real_multiple_files = self.multiple_files
        real_language = self.language
        real_use_gettext = self.use_gettext
        self.use_gettext = False
        self.language = 'python'
        self.multiple_files = 0
        overwrite = self.overwrite
        self.overwrite = 0

        frame = None
        try:
            self.generate_code(preview=True)
            # import generated preview module dynamically
            preview_path = os.path.dirname(self.output_path)
            preview_module_name = os.path.basename(self.output_path)
            preview_module_name = os.path.splitext(preview_module_name)[0]
            preview_module = plugins.import_module(preview_path,
                                                   preview_module_name)
            if not preview_module:
                wx.MessageBox(
                    _('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, _('Error'),
                    wx.OK | wx.CENTRE | wx.ICON_EXCLAMATION)
                return None

            preview_class = getattr(preview_module, widget.klass)

            if not preview_class:
                wx.MessageBox(
                    _('No preview class "%s" found.\n'
                      'The details are written to the log file.\n'
                      'If you think this is a wxGlade bug, please '
                      'report it.') % widget.klass, _('Error'),
                    wx.OK | wx.CENTRE | wx.ICON_EXCLAMATION)
                return None

            if issubclass(preview_class, wx.MDIChildFrame):
                frame = wx.MDIParentFrame(None, -1, '')
                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)
                      or issubclass(preview_class, 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)
                elif issubclass(preview_class, wx.ToolBar):
                    toolbar = preview_class(frame, -1)
                    frame.SetToolBar(toolbar)
                else:
                    panel = preview_class(frame, -1)
                frame.Fit()
            else:
                frame = preview_class(None, -1, '')

            def on_close(event):
                frame.Destroy()
                widget.preview_widget = None
                widget.preview_button.SetLabel(_('Preview'))

            wx.EVT_CLOSE(frame, on_close)
            frame.SetTitle(_('<Preview> - %s') % frame.GetTitle())
            # raise the frame
            frame.CenterOnScreen()
            frame.Show()
            # remove the temporary file (and the .pyc/.pyo ones too)
            for ext in '', 'c', 'o', '~':
                name = self.output_path + ext
                if os.path.isfile(name):
                    os.unlink(name)
        except Exception, inst:
            widget.preview_widget = None
            widget.preview_button.SetLabel(_('Preview'))
            bugdialog.Show(_("Generate Preview"), inst)
예제 #12
0
                       preview=preview,
                       out_path=out_path,
                       class_names=class_names)

            # restore saved settings
            if preview and codewriter == 'python':
                self.overwrite = overwrite_save

        except (errors.WxgBaseException, IOError, OSError), inst:
            wx.MessageBox(
                _("Error generating code:\n%s") % inst,
                _("Error"),
                wx.OK | wx.CENTRE | wx.ICON_ERROR,
            )
        except Exception, inst:
            bugdialog.Show(_('Generate Code'), inst)
        else:
            if not preview:
                if config.preferences.show_completion:
                    # Show informational dialog
                    wx.MessageBox(
                        _("Code generation completed successfully"),
                        _("Information"),
                        wx.OK | wx.CENTRE | wx.ICON_INFORMATION,
                    )
                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
예제 #14
0
    def _open_app(self,
                  filename,
                  use_progress_dialog=True,
                  add_to_history=True):
        "Load a new wxGlade project"

        error_msg = None
        infile = None

        start = time.clock()

        common.app_tree.clear()
        common.app_tree.app.init()
        common.app_tree.auto_expand = False  # disable auto-expansion of nodes

        try:
            try:
                self._logger.info(_('Read wxGlade project from file "%s"'),
                                  filename)

                if not isinstance(filename, list):
                    common.app_tree.app.filename = filename
                    # decoding will done automatically by SAX XML library
                    if compat.PYTHON2:
                        infile = open(filename)
                    else:
                        infile = open(filename, "r", encoding="UTF8")
                else:
                    common.app_tree.app.filename = None

                if use_progress_dialog and config.preferences.show_progress:
                    p = ProgressXmlWidgetBuilder(input_file=infile)
                else:
                    p = XmlWidgetBuilder()

                if infile is not None:
                    p.parse(infile)
                else:
                    p.parse_string(filename)
                    filename = None
            except (EnvironmentError, SAXParseException,
                    XmlParsingError) as msg:
                if config.debugging: raise
                if infile is not None:
                    error_msg = _("Error loading file %s: %s") % (
                        misc.wxstr(filename), misc.wxstr(msg))
                else:
                    error_msg = _("Error loading from a file-like object: %s"
                                  ) % misc.wxstr(msg)
            except Exception as inst:
                if config.debugging: raise
                if filename:
                    fn = os.path.basename(filename).encode('ascii', 'replace')
                    msg = _('loading file "%s"') % fn
                else:
                    msg = _('loading from a file-like object')
                bugdialog.Show(msg, inst)
        finally:
            if infile and filename:
                infile.close()

            if error_msg:
                common.app_tree.clear()
                common.app_tree.app.new()
                common.app_tree.app.saved = True
                common.app_tree.auto_expand = True  # re-enable auto-expansion of nodes

                wx.MessageBox(error_msg, _('Error'),
                              wx.OK | wx.CENTRE | wx.ICON_ERROR)

                return False

        misc.set_focused_widget(common.app_tree.root.widget, force=True)

        common.app_tree.auto_expand = True  # re-enable auto-expansion of nodes

        common.app_tree.expand()
        if common.app_tree.app.is_template:
            self._logger.info(_("Template loaded"))
            common.app_tree.app.template_data = template.Template(filename)
            common.app_tree.app.filename = None

        end = time.clock()
        self._logger.info(_('Loading time: %.5f'), end - start)

        common.app_tree.app.saved = True
        common.property_panel.Raise()

        if hasattr(self, 'file_history') and filename is not None and add_to_history and \
           (not common.app_tree.app.is_template):
            self.file_history.AddFileToHistory(misc.wxstr(filename))

        if config.preferences.autosave and self.autosave_timer is not None:
            self.autosave_timer.Start()

        duration = end - start
        if filename:
            self.user_message(
                _("Loaded %s in %.2f seconds") %
                (misc.wxstr(os.path.basename(filename)), duration))
        else:
            self.user_message(_("Loaded in %.2f seconds") % duration)

        return True
예제 #15
0
    def _open_app(self,
                  filename_or_filelike,
                  use_progress_dialog=True,
                  add_to_history=True):
        """\
        Load a new wxGlade project

        @param filename_or_filelike: Source filename or file-like object
        @type filename_or_filelike: file | StringIO

        @param use_progress_dialog: Show progress bar during loading WXG file
        @type use_progress_dialog: bool

        @param add_to_history: Add file to open to file history
        @type add_to_history: bool

        @return: True on Success
        @rtype: bool
        """
        if isinstance(filename_or_filelike, compat.StringIO):
            assert isinstance(filename_or_filelike.getvalue(), unicode)
        else:
            assert isinstance(filename_or_filelike, compat.basestring)

        error_msg = None
        filename = None
        infile = None
        old_dir = os.getcwd()

        if isinstance(filename_or_filelike, compat.basestring):
            common.app_tree.app.filename = filename_or_filelike
            filename = filename_or_filelike
        else:
            common.app_tree.filename = None

        start = time.clock()
        common.app_tree.clear()

        # disable auto-expansion of nodes
        common.app_tree.auto_expand = False

        try:
            try:
                if isinstance(filename_or_filelike, compat.StringIO):
                    # convert filename_or_filelike to UTF-8 and write back as lines, because
                    # ProgressXmlWidgetBuilder uses lines to calculate and show the position
                    tmp = filename_or_filelike.getvalue()
                    tmp = tmp.encode('UTF-8')
                    infile = compat.StringIO()
                    for line in tmp.split('\n'):
                        infile.write('%s\n' % line)
                    infile.seek(0)
                    self._logger.info(
                        _('Read wxGlade project from file-like object'))

                else:
                    self._logger.info(_('Read wxGlade project from file "%s"'),
                                      filename)
                    os.chdir(os.path.dirname(filename))
                    # decoding will done automatically by SAX XML library
                    if compat.PYTHON2:
                        infile = open(filename)
                    else:
                        infile = open(filename, "r", encoding="UTF8")

                if use_progress_dialog and config.preferences.show_progress:
                    p = ProgressXmlWidgetBuilder(input_file=infile)
                else:
                    p = XmlWidgetBuilder()

                p.parse(infile)
            except (EnvironmentError, SAXParseException,
                    XmlParsingError) as msg:
                if 'WINGDB_ACTIVE' in os.environ: raise
                if filename:
                    error_msg = _("Error loading file %s: %s") % (
                        misc.wxstr(filename), misc.wxstr(msg))
                else:
                    error_msg = _("Error loading from a file-like object: %s"
                                  ) % misc.wxstr(msg)
            except Exception as inst:
                if 'WINGDB_ACTIVE' in os.environ: raise
                if filename:
                    fn = os.path.basename(filename).encode('ascii', 'replace')
                    msg = _('loading file "%s"') % fn
                else:
                    msg = _('loading from a file-like object')
                bugdialog.Show(msg, inst)
        finally:
            if infile and filename:
                infile.close()

            if error_msg:
                common.app_tree.clear()
                common.app_tree.app.saved = True
                common.app_tree.auto_expand = True  # re-enable auto-expansion of nodes

                os.chdir(old_dir)

                wx.MessageBox(error_msg, _('Error'),
                              wx.OK | wx.CENTRE | wx.ICON_ERROR)

                return False

        misc.set_focused_widget(common.app_tree.root.widget)

        common.app_tree.auto_expand = True  # re-enable auto-expansion of nodes

        common.app_tree.expand()
        if common.app_tree.app.is_template:
            self._logger.info(_("Template loaded"))
            common.app_tree.app.template_data = template.Template(filename)
            common.app_tree.app.filename = None

        end = time.clock()
        self._logger.info(_('Loading time: %.5f'), end - start)

        common.app_tree.app.saved = True
        common.property_panel.Raise()

        if hasattr(self, 'file_history') and filename is not None and add_to_history and \
           (not common.app_tree.app.is_template):
            self.file_history.AddFileToHistory(misc.wxstr(filename))

        if config.preferences.autosave and self.autosave_timer is not None:
            self.autosave_timer.Start()

        duration = end - start
        if filename:
            self.user_message(
                _("Loaded %s in %.2f seconds") %
                (misc.wxstr(os.path.basename(filename)), duration))
        else:
            self.user_message(_("Loaded in %.2f seconds") % duration)

        return True