Пример #1
0
    def FormatPluginList(self, data):
        """Formats a list of plugin data served by the server into
        PluginData objects for usage in the list view.
        @return: PluginData of all available plugins
        @rtype: dict

        """
        plugins = data
        p_list = dict()
        if len(plugins) < 2:
            return p_list

        for meta in plugins:
            data = meta.split("\n")

            if len(data) < 4:
                continue

            tmpdat = PluginData()
            for attr in data:
                tmp = attr.split("=")
                if len(tmp) != 2:
                    continue

                set_map = {
                    'author': tmpdat.SetAuthor,
                    'version': tmpdat.SetVersion,
                    'name': tmpdat.SetName,
                    'description': tmpdat.SetDescription,
                    'url': tmpdat.SetUrl
                }
                funct = set_map.get(tmp[0].lower(), None)
                if funct:
                    funct(ed_txt.DecodeString(tmp[1].strip()))

            if tmpdat.GetName() != u'':
                p_list[ed_txt.DecodeString(tmpdat.GetName())] = tmpdat

        # Remove items that have already been installed
        config_pg = self.GetParent().GetPage(CONFIG_PG)
        to_clean = list()
        for pin in p_list:
            cfg_id = config_pg.GetItemIdentifier(pin.lower())
            if cfg_id is not None and cfg_id[1] >= p_list[pin].GetVersion():
                to_clean.append(pin)

        for item in to_clean:
            del p_list[item]

        return p_list
Пример #2
0
    def NavigateToTaskSource(self, itemIndex):
        """
        Navigates to the file and position saved in this item
        @param itemIndex: a int

        """
        if itemIndex < 0 or itemIndex > len(self.itemDataMap):
            self._log("[err] itemIndex out of range!")
            return
        
        key = self.itemIndexMap[itemIndex]
        source = self.itemDataMap[key][-1]
        if not ebmlib.IsUnicode(source):
            source = ed_txt.DecodeString(source)
        line = self.itemDataMap[key][-2]
        try:
            nbook = self.GetParent().GetMainWindow().GetNotebook()
            ctrls = nbook.GetTextControls()
            for ctrl in ctrls:
                if source == ctrl.GetFileName():
                    nbook.SetSelection(nbook.GetPageIndex(ctrl))
                    nbook.GoCurrentPage()
                    ctrl.GotoLine(line-1)
                    break
        except Exception, excp:
            self._log("[err] %s" % excp)
Пример #3
0
def FormatResult(fname, lnum, match):
    """Format the search result string
    @return: string
    @todo: better unicode handling

    """
    fname = ed_txt.DecodeString(fname, sys.getfilesystemencoding())
    if not isinstance(fname, types.UnicodeType):
        fname = _("DECODING ERROR")

    match = ed_txt.DecodeString(match)
    if not isinstance(match, types.UnicodeType):
        match = _("DECODING ERROR")
    else:
        match = u" " + match.lstrip()
    return RESULT_TEMPLATE % dict(fname=fname, lnum=lnum+1, match=match)
Пример #4
0
 def get_unicodevalue(_value):
     if not isinstance(_value, basestring):
         _value = repr(_value)
     _value = ed_txt.DecodeString(_value)
     if not ebmlib.IsUnicode(_value):
         # Give up and do what we can
         _value = unicode(_value, 'latin1', errors='replace')
     return _value
Пример #5
0
    def SaveSessionFile(self, session):
        """Save the current open files to the given session file
        @param session: path to session file
        @return: tuple (error desc, error msg) or None

        """
        try:
            f_handle = open(session, 'wb')
        except (IOError, OSError), msg:
            return (_("Error Saving Session File"), ed_txt.DecodeString(msg))
Пример #6
0
    def FormatResult(self, fname, lnum, match):
        """Format the search result string for find all action that is performed
        on a selection.
        @return: string
        @todo: better unicode handling

        """
        fname = ed_txt.DecodeString(fname, sys.getfilesystemencoding())
        if not isinstance(fname, types.UnicodeType):
            fname = _("DECODING ERROR")

        match = ed_txt.DecodeString(match)
        if not isinstance(match, types.UnicodeType):
            match = _("DECODING ERROR")
        else:
            match = u" " + match.lstrip()

        rstring = u"%(fname)s (%(lnum)d): %(match)s"
        lnum = lnum + self._offset + 1
        return rstring % dict(fname=fname, lnum=lnum, match=match)
Пример #7
0
    def PopulateCtrl(self):
        """Populates the list of plugins and sets the
        values of their states. Any successive calls to
        this function will clear the list and Repopulate it
        with current config values. Returns the number of
        items populated to the list
        @postcondition: list is populated with all plugins that are
                        currently loaded and sets the checkmarks accordingly
        @return: number of items added to list

        """
        p_mgr = wx.GetApp().GetPluginManager()
        if self._list.GetItemCount():
            self._list.DeleteAllItems()

        p_mgr.ReInit()
        config = p_mgr.GetConfig()
        keys = sorted([ed_txt.DecodeString(name) for name in config.keys()],
                      key=unicode.lower)
        uninstalled = Profile_Get('UNINSTALL_PLUGINS', default=list())

        for item in keys:
            val = config[item]
            self._list.Freeze()
            mod = sys.modules.get(item)
            dist = p_mgr.GetPluginDistro(item)
            if dist is not None:
                item = dist.project_name
                version = dist.version
            else:
                version = str(getattr(mod, '__version__', _("Unknown")))

            pdata = PluginData()
            pdata.SetName(item)
            desc = getattr(mod, '__doc__', None)
            if not isinstance(desc, basestring):
                desc = _("No Description Available")
            pdata.SetDescription(desc.strip())
            pdata.SetAuthor(getattr(mod, '__author__', _("Unknown")))
            pdata.SetVersion(version)
            pdata.SetDist(dist)
            pbi = PBPluginItem(self._list, mod, pdata, None)

            pbi.SetChecked(val)
            util.Log("[pluginmgr][info] Adding %s to list" % item)
            self._list.AppendItem(pbi)
            if pbi.GetInstallPath() in uninstalled:
                pbi.Enable(False)
            self._list.Thaw()

        self._list.SendSizeEvent()
        return self._list.GetItemCount()
Пример #8
0
    def PopulateErrors(self):
        """Populates the list of plugins and sets the
        values of their states. Any successive calls to
        this function will clear the list and Repopulate it
        with current config values. Returns the number of
        items populated to the list
        @postcondition: list is populated with all plugins that are
                        currently loaded and sets the checkmarks accordingly
        @return: number of items added to list

        """
        p_mgr = wx.GetApp().GetPluginManager()
        if self._list.GetItemCount():
            self._list.DeleteAllItems()

        p_mgr.ReInit()
        errors = p_mgr.GetIncompatible()
        keys = sorted([ ed_txt.DecodeString(name)
                        for name in errors.keys() ],
                      key=unicode.lower)
        bmp = wx.ArtProvider.GetBitmap(wx.ART_ERROR, wx.ART_TOOLBAR, (32, 32))
        msg = _("This plugin requires a newer version of Editra.")

        for item in keys:
            val = errors[item]
            self._list.Freeze()
            mod = sys.modules.get(val)
            dist = p_mgr.GetPluginDistro(item)
            if dist is not None:
                item = dist.project_name
                version = dist.version
            else:
                version = str(getattr(mod, '__version__', _("Unknown")))

            pin = PluginData()
            pin.SetName(item)
            pin.SetAuthor(getattr(mod, '__author__', _("Unknown")))
            pin.SetVersion(version)
            pin.SetDist(dist)
            pbi = PluginErrorItem(self._list, pin, bmp, item)

            self._list.AppendItem(pbi)
            self._list.Thaw()

        self._list.SendSizeEvent()
        return self._list.GetItemCount()
Пример #9
0
    def PopulateCtrl(self):
        """Populates the list of plugins and sets the
        values of their states. Any successive calls to
        this function will clear the list and Repopulate it
        with current config values. Returns the number of
        items populated to the list
        @postcondition: list is popluated with all plugins that are
                        currently loaded and sets the checkmarks accordingly
        @return: number of items added to list

        """
        p_mgr = wx.GetApp().GetPluginManager()
        if self._list.GetItemCount():
            self._list.DeleteAllItems()

        p_mgr.ReInit()
        config = p_mgr.GetConfig()
        keys = sorted([ed_txt.DecodeString(name) for name in config.keys()],
                      key=unicode.lower)

        for item in keys:
            val = config[item]
            self._list.Freeze()
            mod = sys.modules.get(item)
            dist = p_mgr.GetPluginDistro(item)
            if dist is not None:
                item = dist.project_name
                version = dist.version
            else:
                version = str(getattr(mod, '__version__', _("Unknown")))

            pin = PluginData()
            pin.SetName(item)
            desc = getattr(mod, '__doc__', _("No Description Available"))
            pin.SetDescription(desc.strip())
            pin.SetAuthor(getattr(mod, '__author__', _("Unknown")))
            pin.SetVersion(version)
            pbi = PBPluginItem(self._list, mod, None, item, pin.GetVersion(),
                               pin.GetDescription(), pin.GetAuthor())

            pbi.SetChecked(val)
            self._list.AppendItem(pbi)
            self._list.Thaw()

        self._list.SendSizeEvent()
        return self._list.GetItemCount()
Пример #10
0
    def MacOpenFile(self, filename):
        """Macintosh Specific code for opening files that are associated
        with the editor and double clicked on after the editor is already
        running.
        @param filename: file path string
        @postcondition: if L{MainWindow} is open file will be opened in notebook

        """
        window = self.GetTopWindow()
        if getattr(window, '__name__', '') == "MainWindow":
            try:
                encoding = sys.getfilesystemencoding()
                window.DoOpen(ed_glob.ID_COMMAND_LINE_OPEN,
                              ed_txt.DecodeString(filename, encoding))
                self._log("[app][info] MacOpenFile Fired")
            except Exception, msg:
                self._log("[app][err] Failed to open drop file: %s" % str(msg))
                pass
Пример #11
0
    def DoProcessError(self, code, excdata=None):
        """Handle notifications of when an error occurs in the process
        @param code: an OBP error code
        @keyword excdata: Exception string
        @return: None

        """
        if code == eclib.OPB_ERROR_INVALID_COMMAND:
            self.AppendUpdate(_("The requested command could not be executed.") + u"\n")

        # Log the raw exception data to the log as well
        if excdata is not None:
            try:
                excstr = str(excdata)
                if not ebmlib.IsUnicode(excstr):
                    excstr = ed_txt.DecodeString(excstr)
                util.Log(u"[launch][err] %s" % excdata)
            except UnicodeDecodeError:
                util.Log(u"[launch][err] error decoding log message string")
Пример #12
0
    def OnFind(self, evt, findnext=False):
        """Do an incremental search in the currently buffer
        @param evt: EVT_FIND, EVT_FIND_NEXT
        @keyword findnext: force a find next action

        """
        data = self.GetData()

        # Find next from menu event or called internally by replace
        if findnext or evt.GetEventType() == wx.wxEVT_COMMAND_MENU_SELECTED:

            # Adjust flags
            flags = data.GetFlags()
            if not findnext and evt.GetId() == ed_glob.ID_FIND_PREVIOUS:
                flags |= eclib.AFR_UP

            evt = eclib.FindEvent(eclib.edEVT_FIND_NEXT, flags=flags)
            evt.SetFindString(data.GetFindString())

        stc = self._stc()
        data.SetFindString(evt.GetFindString())

        # Create the search engine
        isdown = not evt.IsUp()
        self._engine.SetQuery(data.GetFindString())
        self._engine.SetFlags(isregex=evt.IsRegEx(),
                              matchcase=evt.IsMatchCase(),
                              wholeword=evt.IsWholeWord(),
                              down=isdown)

        # Check if expression was valid or not
        if self._engine.GetQueryObject() is None:
            fail = ed_txt.DecodeString(self._engine.GetQuery(), 'utf-8')
            wx.MessageBox(_("Invalid expression \"%s\"") % fail,
                          _("Regex Compile Error"),
                          style=wx.OK | wx.CENTER | wx.ICON_ERROR)
            return

        # XXX: may be inefficent to copy whole buffer each time for files
        #      that are large.
        self._engine.SetSearchPool(stc.GetTextRaw())

        # Check if the direction changed
        ldir = self._posinfo['ldir']
        if isdown:
            self._posinfo['ldir'] = 'down'
        else:
            self._posinfo['ldir'] = 'up'

        # Get the search start position
        if evt.GetEventType() == eclib.edEVT_FIND:
            spos = self._posinfo['found']
        else:
            spos = stc.GetCurrentPos()
            if ldir != self._posinfo['ldir']:
                start, end = stc.GetSelection()
                if ldir == 'down':
                    spos = start
                else:
                    spos = end

        # Do the find
        match = self._engine.Find(spos)
        if match is not None:
            start, end = match

            if isdown:
                start = start + spos
                end = end + spos
                stc.SetSelection(start, end)
            else:
                stc.SetSelection(end, start)

            # Ensure caret and the line its in is exposed
            stc.EnsureCaretVisible()
            line = stc.LineFromPosition(start)
            stc.EnsureVisible(line)

            self._posinfo['found'] = start

            ed_msg.PostMessage(ed_msg.EDMSG_UI_SB_TXT, (ed_glob.SB_INFO, u""))
        else:
            # try search from top again
            if isdown:
                match = self._engine.Find(0)
                ed_msg.PostMessage(
                    ed_msg.EDMSG_UI_SB_TXT,
                    (ed_glob.SB_INFO, _("Search wrapped to top")))
            else:
                match = self._engine.Find(-1)
                ed_msg.PostMessage(
                    ed_msg.EDMSG_UI_SB_TXT,
                    (ed_glob.SB_INFO, _("Search wrapped to bottom")))

            if match is not None:
                start, end = match

                self._posinfo['found'] = start

                match = list(match)
                if not isdown:
                    match.reverse()
                stc.SetSelection(match[0], match[1])

                # Ensure caret and the line its in is exposed
                stc.EnsureCaretVisible()
                line = stc.LineFromPosition(match[0])
                stc.EnsureVisible(line)
            else:
                self._posinfo['found'] = -1
                fail = ed_txt.DecodeString(self._engine.GetQuery(), 'utf-8')
                ed_msg.PostMessage(
                    ed_msg.EDMSG_UI_SB_TXT,
                    (ed_glob.SB_INFO, _("\"%s\" was not found") % fail))
Пример #13
0
def Main():
    """Configures and Runs an instance of Editra
    @summary: Parses command line options, loads the user profile, creates
              an instance of Editra and starts the main loop.

    """
    opts, args = ProcessCommandLine()

    # We are ready to run so fire up the config and launch the app
    profile_updated = InitConfig()

    # Put extern subpackage on path so that bundled external dependancies
    # can be found if needed.
    if not hasattr(sys, 'frozen'):
        epath = os.path.join(os.path.dirname(__file__), 'extern')
        if os.path.exists(epath):
            sys.path.append(epath)

    # Create Application
    dev_tool.DEBUGP("[main][app] Initializing application...")
    editra_app = Editra(False)

    # Print ipc server authentication info
    if '--auth' in opts:
        opts.remove('--auth')
        print "port=%d,key=%s" % (ed_ipc.EDPORT,
                                  profiler.Profile_Get('SESSION_KEY'))

    # Check if this is the only instance, if its not exit since
    # any of the opening commands have already been passed to the
    # master instance
    if not editra_app.IsOnlyInstance():
        dev_tool.DEBUGP("[main][info] Second instance exiting...")
        editra_app.Destroy()
        os._exit(0)

    if profile_updated:
        # Make sure window iniliazes to default position
        profiler.Profile_Del('WPOS')
        wx.MessageBox(_("Your profile has been updated to the latest "
                        "version") + u"\n" + \
                      _("Please check the preferences dialog to check "
                        "your preferences"),
                      _("Profile Updated"))

    # Splash a warning if version is not a final version
    if profiler.Profile_Get('APPSPLASH'):
        import edimage
        splash_img = edimage.splashwarn.GetBitmap()
        splash = wx.SplashScreen(splash_img, wx.SPLASH_CENTRE_ON_PARENT | \
                                 wx.SPLASH_NO_TIMEOUT, 0, None, wx.ID_ANY)
        splash.Show()

    if profiler.Profile_Get('SET_WSIZE'):
        wsize = profiler.Profile_Get('WSIZE')
    else:
        wsize = (700, 450)
    frame = ed_main.MainWindow(None, wx.ID_ANY, wsize, ed_glob.PROG_NAME)
    frame.Maximize(profiler.Profile_Get('MAXIMIZED'))
    editra_app.RegisterWindow(repr(frame), frame, True)
    editra_app.SetTopWindow(frame)
    frame.Show(True)

    # Load Session Data
    # But not if there are command line args for files to open
    if profiler.Profile_Get('SAVE_SESSION', 'bool', False) and not len(args):
        frame.GetNotebook().LoadSessionFiles()

    # Unlike wxMac/wxGTK Windows doesn't post an activate event when a window
    # is first shown, so do it manually to make sure all event handlers get
    # pushed.
    if wx.Platform == '__WXMSW__':
        wx.PostEvent(frame, wx.ActivateEvent(wx.wxEVT_ACTIVATE, True))

    if 'splash' in locals():
        splash.Destroy()

    # Do update check, only check if its been more than a day since the last
    # check
    if profiler.Profile_Get('CHECKUPDATE', default=True):
        uthread = updater.UpdateThread(editra_app, ID_UPDATE_CHECK)
        uthread.start()

    for arg in args:
        try:
            arg = os.path.abspath(arg)
            fname = ed_txt.DecodeString(arg, sys.getfilesystemencoding())
            frame.DoOpen(ed_glob.ID_COMMAND_LINE_OPEN, fname)
        except IndexError:
            dev_tool.DEBUGP("[main][err] IndexError on commandline args")

    # 3. Start Applications Main Loop
    dev_tool.DEBUGP("[main][info] Starting MainLoop...")
    editra_app.MainLoop()
    dev_tool.DEBUGP("[main][info] MainLoop finished exiting application")
    os._exit(0)
Пример #14
0
 def testDecodeString(self):
     """Test decoding a string to unicode."""
     test = "test string"
     self.assertTrue(isinstance(test, str), "Not a string")
     uni = ed_txt.DecodeString(test, 'utf-8')
     self.assertTrue(isinstance(uni, types.UnicodeType), "Failed decode")
Пример #15
0
    if 'splash' in locals():
        splash.Destroy()

    # Do update check, only check if its been more than a day since the last
    # check
    tval = sum(time.localtime(time.time())[:3])
    if profiler.Profile_Get('CHECKUPDATE', default=True) and \
       tval - profiler.Profile_Get('LASTCHECK', 'int', default=0) > 1:
        profiler.Profile_Set('LASTCHECK', tval)
        uthread = updater.UpdateThread(editra_app, ID_UPDATE_CHECK)
        uthread.start()

    for arg in args:
        try:
            arg = os.path.abspath(arg)
            fname = ed_txt.DecodeString(arg, sys.getfilesystemencoding())
            frame.DoOpen(ed_glob.ID_COMMAND_LINE_OPEN, fname)
        except IndexError:
            dev_tool.DEBUGP("[main][err] IndexError on commandline args")

    # 3. Start Applications Main Loop
    dev_tool.DEBUGP("[main][info] Starting MainLoop...")
    editra_app.MainLoop()
    dev_tool.DEBUGP("[main][info] MainLoop finished exiting application")
    os._exit(0)


#-----------------------------------------------------------------------------#
if __name__ == '__main__':
    Main()