Exemplo n.º 1
0
    def import_xrc(self, event):
        import xrc2wxg

        if not self.ask_save():
            return

        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 = compat.StringIO()
            try:
                xrc2wxg.convert(infilename, ibuffer)

                # Convert UTF-8 returned by xrc2wxg.convert() to Unicode
                tmp = ibuffer.getvalue().decode('UTF-8')
                ibuffer = compat.StringIO()
                [ibuffer.write('%s\n' % line) for line in tmp.split('\n')]
                ibuffer.seek(0)

                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)
Exemplo n.º 2
0
    def _save_file(self, filename, content, which='wxg'):
        """\
        Test specific implementation of L{common.save_file()} to get the
        result of the code generation without file creation.

        The file content is stored in a StringIO instance. It's
        accessible at L{self.vFiles} using the filename as key.

        @note: The signature is as same as L{wxglade.common.save_file()} but
               the functionality differs.

        @param filename: Name of the file to create
        @param content:  String to store into 'filename'
        @param which:    Kind of backup: 'wxg' or 'codegen'
        """
        self.failIf(filename in self.vFiles,
                    "Virtual file %s already exists" % filename)
        self.failUnless(filename, "No filename given")
        if self.non_accessible_files and \
           filename.startswith(self.non_accessible_files):
            raise IOError(errno.EACCES, os.strerror(errno.EACCES), filename)
        else:
            outfile = compat.StringIO()
            outfile.write(content)
            self.vFiles[filename] = outfile
Exemplo n.º 3
0
    def write(self, outfile, tabs, class_names=None):
        "Writes the xml code for the widget to the given output file"
        # XXX move this to the widget
        import edit_sizers
        fwrite = outfile.write
        assert self.widget is not None

        # write object tag, including class, name, base
        classname = getattr(self.widget, '_classname',
                            self.widget.__class__.__name__)
        # to disable custom class code generation (for panels...)
        if getattr(self.widget, 'no_custom_class', False):
            no_custom = u' no_custom_class="1"'
        else:
            no_custom = ""
        outer_tabs = u'    ' * tabs
        fwrite(u'%s<object %s %s %s%s>\n' %
               (outer_tabs,
                common.format_xml_attrs(**{'class': self.widget.klass}),
                common.format_xml_attrs(name=self.widget.name),
                common.format_xml_attrs(base=classname), no_custom))

        # write properties, but without name and class
        # XXX be 100% compatible to 0.7.2, where option is written into the object; remove later
        properties = self.widget.get_properties(
            without=set(edit_sizers.SizerBase.MANAGED_PROPERTIES))
        #properties = self.widget.get_properties(without=set(["pos","flag","border"]))
        for prop in properties:
            prop.write(outfile, tabs + 1)

        if class_names is not None and self.widget.__class__.__name__ != 'CustomWidget':
            class_names.add(self.widget.klass)

        if isinstance(self.widget, edit_sizers.SizerBase):
            for child in self.children or []:
                if not isinstance(child,
                                  SlotNode):  # hasattr(child, 'widget'):
                    inner_xml = compat.StringIO()

                    for name in edit_sizers.SizerBase.MANAGED_PROPERTIES:
                        name = child.widget.properties[name]
                        if name is not None:
                            name.write(inner_xml, tabs + 2)

                    child.write(inner_xml, tabs + 2, class_names)
                    stmt = common.format_xml_tag(u'object',
                                                 inner_xml.getvalue(),
                                                 tabs + 1,
                                                 is_xml=True,
                                                 **{'class': 'sizeritem'})
                    fwrite(stmt)
                else:
                    child.write(outfile, tabs + 1)
        elif self.children is not None:
            for child in self.children:
                child.write(outfile, tabs + 1, class_names)
        fwrite(u'%s</object>\n' % outer_tabs)
Exemplo n.º 4
0
 def parse(self, source):
     # Permanent workaround for Python bug "Sax parser crashes if given
     # unicode file name" (http://bugs.python.org/issue11159).
     #
     # This bug causes a UnicodeEncodeError if the SAX XML parser wants to store an unicode filename internally.
     #
     # That's not a general file handling issue because the parameter source is an open file already.
     source = compat.StringIO(source.read())
     self.parser.parse(source)
     source.close()
Exemplo n.º 5
0
    def init_lang(self, app_attrs):
        # for now we handle only single-file code generation
        if self.multiple_files:
            raise errors.WxgXRCMultipleFilesNotSupported()

        # overwrite existing sources always
        self._overwrite = True

        self.output_file_name = app_attrs['path']
        self.out_file = compat.StringIO()
        self.out_file.write('\n<resource version="2.3.0.1">\n')
        self.curr_tab = 1
        self.xrc_objects = OrderedDict()
Exemplo n.º 6
0
    def _open_wxg_file(self, content=None, filename=None):
        """\
        Open a wxGlade project

        @param content: Content
        @type content:  Unicode | StringIO | None

        @param filename: File name
        @type filename:  str
        """
        self.failUnless(content or filename)
        self.failUnless(
            isinstance(content, (compat.unicode, compat.StringIO))
            or content is None)
        if isinstance(content, compat.StringIO):
            self.failUnless(isinstance(content.getvalue(), compat.unicode))

        if filename:
            content = compat.StringIO(self._load_file(filename))
        elif isinstance(content, compat.StringIO):
            self.failUnless(isinstance(content.getvalue(), compat.unicode))
        else:
            content = compat.StringIO(content)

        self.frame._open_app(filename_or_filelike=content,
                             use_progress_dialog=False,
                             add_to_history=False)
        tree = common.app_tree
        root = tree.GetRootItem()
        first, cookie = tree.GetFirstChild(root)
        if first.IsOk():
            tree.expand()
            self._process_wx_events()
            tree.SelectItem(first)
            self._process_wx_events()
            node = tree.GetPyData(first)
            tree.show_toplevel(node)
        self._process_wx_events()
Exemplo n.º 7
0
    def setUp(self):
        # redirect stdout
        self.orig_stdout = sys.stdout
        sys.stdout = compat.StringIO()

        # initialise base class
        WXGladeBaseTest.setUp(self)

        # inject mock object for wxMessageBox
        wx.MessageBox = self.mockMessageBox
        self._messageBox = []

        # show dialog "Code generation completed successfully"
        config.preferences.show_completion = True
Exemplo n.º 8
0
    def write(self, outfile=None, tabs=0):
        """Writes the xml equivalent of this tree to the given output file.
        This function writes unicode to the outfile."""
        # XXX move this to application.Application
        if outfile is None:
            outfile = sys.stdout
        outfile.write(u'<?xml version="1.0"?>\n'
                      u'<!-- generated by wxGlade %s on %s -->\n\n' %
                      (config.version, time.asctime()))
        outpath = os.path.normpath(
            os.path.expanduser(self.app.output_path.strip()))

        attrs = [
            "name", "class", "language", "top_window", "encoding",
            "use_gettext", "overwrite", "for_version", "is_template",
            "indent_amount"
        ]

        attrs = dict((prop, self.app.properties[prop].get_str_value())
                     for prop in attrs)
        attrs["option"] = self.app.properties["multiple_files"].get_str_value()
        attrs["indent_symbol"] = self.app.properties[
            "indent_mode"].get_str_value()
        attrs["path"] = outpath
        attrs['use_new_namespace'] = 1
        # add a . to the file extensions
        attrs["source_extension"] = '.' + self.app.properties[
            "source_extension"].get_str_value()
        attrs["header_extension"] = '.' + self.app.properties[
            "header_extension"].get_str_value()

        inner_xml = compat.StringIO()

        if self.app.is_template and getattr(self.app, 'template_data', None):
            self.app.template_data.write(inner_xml, tabs + 1)

        class_names = set()
        if self.root.children is not None:
            for c in self.root.children:
                c.write(inner_xml, tabs + 1, class_names)

        stmt = common.format_xml_tag(u'application',
                                     inner_xml.getvalue(),
                                     is_xml=True,
                                     **attrs)
        outfile.write(stmt)

        return class_names
Exemplo n.º 9
0
        def write(self, outfile, tabs, top=False):
            inner_xml = u''
            if not top and not self.children:
                if self.label:
                    inner_xml += format_xml_tag(
                        u'label', self.label, tabs + 1)
                if self.id:
                    inner_xml += format_xml_tag(u'id', self.id, tabs+1)
                if self.name:
                    inner_xml += format_xml_tag(u'name', self.name, tabs+1)
                if self.help_str:
                    inner_xml += format_xml_tag(u'help_str', self.help_str, tabs+1)
                try:
                    checkable = int(self.checkable)
                except ValueError:
                    checkable = 0
                if checkable:
                    inner_xml += format_xml_tag(
                        u'checkable', checkable, tabs + 1)

                try:
                    radio = int(self.radio)
                except ValueError:
                    radio = 0
                if radio:
                    inner_xml += format_xml_tag(u'radio', radio, tabs+1)

                if self.handler:
                    inner_xml += format_xml_tag(u'handler', self.handler, tabs+1)
                stmt = format_xml_tag(u'item', inner_xml, tabs, is_xml=True)
            else:
                attrs = {'name': self.name}
                if self.id:
                    attrs[u'itemid'] = self.id
                if self.handler:
                    attrs[u'handler'] = self.handler
                attrs[u'label'] = self.label
                value = compat.StringIO()
                for c in self.children:
                    c.write(value, tabs + 1)
                inner_xml = value.getvalue()
                stmt = format_xml_tag( u'menu', inner_xml, tabs, is_xml=True, **attrs )

            outfile.write(stmt)
Exemplo n.º 10
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))
Exemplo n.º 11
0
    def test_missing_application_attributes(self):
        """\
        Test load wxg file w/ missing <application> attributes and generate
        code
        """
        fullpath = os.path.join(self.caseDirectory, 'app_wo_attrs_gui.xrc')
        obuffer = compat.StringIO()

        xrc2wxg.convert(fullpath, obuffer)

        generated = obuffer.getvalue().decode('UTF-8')
        expected = self._load_file('app_wo_attrs_gui.wxg')

        self._compare(expected, generated, "wxg")

        self._messageBox = None
        self._open_wxg_file(generated)
        self.failIf(
            self._messageBox,
            'Loading test wxg file caused an error message: %s' %
            self._messageBox)
Exemplo n.º 12
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
Exemplo n.º 13
0
 def write(self, outfile, tabs):
     inner_xml = compat.StringIO()
     for tool in self.get():
         tool.write(inner_xml, tabs+1)
     stmt = common.format_xml_tag( u'tools', inner_xml.getvalue(), tabs, is_xml=True) 
     outfile.write(stmt)