def UpdateLineBuffCfg(self):
     """Update the line buffer configuration"""
     util.Log("[Launch][info] LineBuffer config updated")
     val = self._bufftxt.GetValue()
     if self._bufftxt.IsInBounds(val):
         cfg = Profile_Get(handlers.CONFIG_KEY, default=dict())
         cval = cfg.get('linebuffer', DEFAULT_LINEBUFFER)
         ival = int(val)
         if ival == 0:
             ival = -1
         if ival != cval:
             cfg['linebuffer'] = ival
             Profile_Set(handlers.CONFIG_KEY, cfg)
Exemple #2
0
    def OpenFiles(files):
        """Open the list of files in Editra for editing
        @param files: list of file names

        """
        to_open = list()
        for fname in files:
            try:
                res = os.stat(fname)[0]
                if stat.S_ISREG(res) or stat.S_ISDIR(res):
                    to_open.append(fname)
            except (IOError, OSError), msg:
                util.Log("[filebrowser][err] %s" % str(msg))
Exemple #3
0
 def _GetPluginListData(self, url=PLUGIN_REPO):
     """Gets the list of plugins and their related meta data
     as a string and returns it.
     @return: list of data of available plugins from website
     
     """
     text = u''
     try:
         h_file = urllib.urlopen(url)
         text = h_file.read()
         h_file.close()
     except (IOError, OSError), msg:
         util.Log("[plugdlg][err] %s" % str(msg))
Exemple #4
0
def InitCustomHandlers(path):
    """Init the custom handlers defined in the launch.xml file
    @param path: path to directory to find the launch xml in
    @return: bool

    """
    loaded = False
    path = os.path.join(path, u'launch.xml')
    if os.path.exists(path):
        lxml = launchxml.LaunchXml()
        lxml.SetPath(path)
        loaded = False
        try:
            loaded = lxml.LoadFromDisk()
        except AssertionError, msg:
            # XML Parsing error
            util.Log("[Launch][err] Failed to load custom Handlers")
            util.Log("[Launch][err] XML Parsing Error: %s" % msg)

        if loaded:
            for hndlr in lxml.GetHandlers().values():
                HANDLERS[hndlr.GetLangId()] = XmlHandlerDelegate(hndlr)
    def GetCompleter(self, buff):
        """Get the completer for the specified file type id
        @param buff: EditraStc instance

        """
        ftypeid = buff.GetLangId()
        for observer in self.observers:
            try:
                if observer.GetFileTypeId() == ftypeid:
                    return observer.GetCompleter(buff)
            except Exception, msg:
                util.Log("[ed_basestc][err] GetCompleter Extension: %s" %
                         str(msg))
Exemple #6
0
 def OnShowProjectWindow(self, evt):
     """Show the project window in the current MainWindow."""
     if evt.Id == PyProject.ID_PYPROJECT:
         mainw = wx.GetApp().GetActiveWindow()
         if mainw and isinstance(mainw, ed_main.MainWindow):
             pane = mainw.PanelMgr.GetPane(ProjectManager.PANE_NAME)
             if pane.IsShown():
                 pane.Hide()
             else:
                 pane.Show()
             mainw.PanelMgr.Update()
     else:
         util.Log("[PyStudio][warn] Can't show PyProject panel")
Exemple #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())

        with eclib.Freezer(self._list) as _tmp:
            for item in keys:
                val = config[item]
                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.SendSizeEvent()
        return self._list.GetItemCount()
Exemple #8
0
    def PlugIt(self, parent):
        """Adds the view menu entry and registers the event handler"""
        mainw = parent
        if mainw != None:
            util.Log("[projects][info] Installing projects plugin")

            self._projects = ProjectPane(mainw)
            mgr = mainw.GetFrameManager()
            mgr.AddPane(self._projects, wx.aui.AuiPaneInfo().Name(PANE_NAME).\
                        Caption(_("Projects")).Left().Layer(1).\
                        CloseButton(True).MaximizeButton(False).\
                        BestSize(wx.Size(215, 350)))

            mgr.Update()
Exemple #9
0
    def SavePerspectives(self):
        """Writes the perspectives out to disk. Returns
        True if all data was written and False if there
        was an error.
        @return: whether save was successfull
        @rtype: bool

        """
        writer = util.GetFileWriter(self._base)
        if writer == -1:
            util.Log("[perspective][err] Failed to save %s" % self._base)
            return False

        try:
            self._viewset[LAST_KEY] = self._currview
            for perspect in self._viewset:
                writer.write(u"%s=%s\n" % (perspect, self._viewset[perspect]))
            del self._viewset[LAST_KEY]
        except (IOError, OSError):
            util.Log("[perspective][err] Write error: %s" % self._base)
            return False
        else:
            return True
Exemple #10
0
def OnEnDe(buff, evt):
    """Handle context menu events"""
    try:
        if evt.Id in _DECODERS:
            util.Log("[Enigma] Enigma Decode")
            decoder = emachine.EnigmaMachine.FactoryCreate(
                _DECODERS.get(evt.Id))
            txt = decoder.decode(buff.GetSelectedText())
            buff.ReplaceSelection(txt)
        elif evt.Id in _ENCODERS:
            util.Log("[Enigma] Enigma Encode")
            encoder = emachine.EnigmaMachine.FactoryCreate(
                _ENCODERS.get(evt.Id))
            txt = encoder.encode(buff.GetSelectedText())
            if evt.Id == ID_BASE64_ENC_UNIX:
                # Add line feeds every 64 chars
                tmp = [txt[i:i + 64] for i in range(0, len(txt), 64)]
                txt = "\n".join(tmp)
            buff.ReplaceSelection(txt)
        else:
            evt.Skip()
    except Exception, msg:
        util.Log("[Enigma][err] % s" % msg)
Exemple #11
0
 def _UpdateCatcher(self, delayedResult):
     """Catches the results from the download worker threads"""
     try:
         frame = self.GetGrandParent()
         result = delayedResult.get()
         if len(result):
             self._p_list = self.FormatPluginList(result)
             self.PopulateList()
             frame.SetStatusText(_("Select plugins to download"), 0)
     except wx.PyDeadObjectError:
         return
     except Exception, msg:
         util.Log("[plugdlg][err] Download failed " + str(msg))
         frame.SetStatusText(_("Unable to retrieve plugin list"), 0)
Exemple #12
0
    def LoadKeyProfile(self, pname):
        """Load a key profile into the binder
        @param pname: name of key profile to load

        """
        if pname is None:
            ppath = None
        else:
            ppath = self.GetProfilePath(pname)

        keydict = dict()
        if ppath is not None and os.path.exists(ppath):
            reader = util.GetFileReader(ppath)
            if reader != -1:
                util.Log("[keybinder][info] Loading KeyProfile: %s" % ppath)
                for line in reader:
                    parts = line.split('=', 1)
                    if len(parts) == 2:
                        item_id = _GetValueFromStr(parts[0])
                        if item_id is not None:
                            keydict[item_id] = [ part.strip()
                                                 for part in parts[1].split('+')
                                                 if len(part.strip()) ]
                            if parts[1].strip().endswith('++'):
                                keydict[item_id].append('+')
                reader.close()
                KeyBinder.keyprofile = keydict
                KeyBinder.cprofile = pname
                return
            else:
                util.Log("[keybinder][err] Couldn't read %s" % ppath)
        elif pname is not None:
            # Fallback to default keybindings
            util.Log("[keybinder][err] Failed to load bindings from %s" % pname)

        util.Log("[keybinder][info] Loading Default Keybindings")
        KeyBinder.LoadDefaults()
Exemple #13
0
def UpgradeOldInstall():
    """Upgrade an old installation and transfer all files if they exist
    @note: FOR INTERNAL USE ONLY
    @return: bool (True if success, False if failure)

    """
    old_cdir = u"%s%s.%s%s" % (wx.GetHomeDir(), os.sep, ed_glob.PROG_NAME,
                               os.sep)
    base = ed_glob.CONFIG['CONFIG_BASE']
    if base is None:
        base = wx.StandardPaths.Get().GetUserDataDir() + os.sep

    err = 0
    if os.path.exists(old_cdir) and \
       base.lower().rstrip(os.sep) != old_cdir.lower().rstrip(os.sep):
        for item in os.listdir(old_cdir):
            print item
            try:
                dest = os.path.join(base, item)
                item = os.path.join(old_cdir, item)
                if os.path.exists(dest):
                    if os.path.isdir(dest):
                        shutil.rmtree(dest, True)
                    else:
                        os.remove(dest)

                shutil.move(item, dest)
            except Exception, msg:
                util.Log("[Upgrade][err] %s" % msg)
                err += 1
                continue

        os.rmdir(old_cdir)

        # Load the copied over profile
        pstr = profiler.GetProfileStr()
        prof = os.path.basename(pstr)
        pstr = os.path.join(base, u"profiles", prof)
        if os.path.exists(pstr):
            profiler.Profile().Load(pstr)
            profiler.Profile().Update()
            profiler.UpdateProfileLoader()

        if not err:
            wx.MessageBox(_("Your profile has been updated to the latest "
                "version") + u"\n" + \
              _("Please check the preferences dialog to check "
                "your preferences"),
              _("Profile Updated"))
Exemple #14
0
    def _DownloadPlugin(self, *args):
        """Downloads the plugin at the given url.
        @note: *args is really a string that has been exploded
        @return: name, completed, egg data
        @rtype: tuple

        """
        url = "".join(args)
        egg = None
        try:
            h_file = urllib.urlopen(url)
            egg = h_file.read()
            h_file.close()
        except (IOError, OSError), msg:
            util.Log("[plugdlg][err] %s" % str(msg))
Exemple #15
0
    def InstallMenu(self, menu):
        """Appends the menu of available Generators onto
        the given menu.
        @param menu: menu to install entries into
        @type menu: wx.Menu

        """
        menu_items = list()
        for observer in self.observers:
            try:
                menu_i = observer.GetMenuEntry(menu)
                if menu_i:
                    menu_items.append((menu_i.GetItemLabel(), menu_i))
            except Exception, msg:
                util.Log("[generator][err] %s" % str(msg))
Exemple #16
0
    def OnConfigChange(self, msg):
        """Update current state when the configuration has been changed
        @param msg: Message Object

        """
        util.Log("[Launch][info] Saving config to profile")
        self.RefreshControlBar()
        # Update wordwrapping
        mode = wx.stc.STC_WRAP_NONE
        if self.Preferences.get('wrapoutput', False):
            mode = wx.stc.STC_WRAP_WORD # should we do wrap char?
        wrapmode = self._buffer.GetWrapMode()
        if wrapmode != mode:
            self._buffer.SetWrapMode(mode)
        self.UpdateBufferColors()
    def GetCurrentVersionStr(self):
        """Parses the project website front page for the most
        recent version of the program.
        @requires: network connection
        @return: verision number of latest available program

        """
        page = self.GetPageText(ed_glob.HOME_PAGE + "/version.php?check=True")
        found = re.findall(RE_VERSION, page)
        if len(found):
            return found[0]  # Should be the first/only match found
        else:
            util.Log("[updater][warn] UpdateService.GetCurrentVersionStr "
                     "Failed to get version info.")
            return _("Unable to retrieve version info")
Exemple #18
0
    def SaveStyleSheet(self, sheetname=None):
        """Save the changes to the currently selected StyleSheet
        @return: bool

        """
        # Ensure user styles directory exists to save style sheet to
        if ed_glob.CONFIG['STYLES_DIR'] == ed_glob.CONFIG['SYS_STYLES_DIR']:
            path = util.GetUserConfigBase()
            user_config = os.path.join(path, 'styles')
            if not os.path.exists(user_config):
                try:
                    os.mkdir(user_config)
                except (OSError, IOError), msg:
                    util.Log("[style_editor][err] %s" % msg)
                else:
                    ed_glob.CONFIG['STYLES_DIR'] = user_config
Exemple #19
0
    def WriteBook(self):
        """Writes the collection of files=pos to the config file
        @postcondition: in memory doc data is written out to disk

        """
        writer = util.GetFileWriter(self.GetBook(), sys.getfilesystemencoding())
        if writer != -1:
            try:
                for key, val in self._records.iteritems():
                    try:
                        writer.write(u"%s=%d\n" % (key, val))
                    except UnicodeDecodeError:
                        continue
                writer.close()
            except IOError, msg:
                util.Log("[docpositionmgr][err] %s" % str(msg))
Exemple #20
0
    def SaveSession(self, name, paths):
        """Save the given list of files as a session with the given name
        @param name: session name
        @param paths: list of file paths
        @return: bool

        """
        session = self.PathFromSessionName(name)
        bOk = False
        with open(session, 'wb') as f_handle:
            try:
                # TODO multi window support
                sdata = dict(win1=paths)
                cPickle.dump(sdata, f_handle)
                bOk = True
            except Exception, msg:
                util.Log("[ed_session][err] Failed to SaveSessionFile: %s" % msg)
Exemple #21
0
    def GetEventHandlers(self, ui_evt=False):
        """Get Event handlers and Id's from all observers
        @keyword ui_evt: Get Update Ui handlers (default get menu handlers)
        @return: list [(ID_FOO, foo.OnFoo), (ID_BAR, bar.OnBar)]

        """
        handlers = list()
        for observer in self.observers:
            try:
                if ui_evt:
                    items = observer.GetUIHandlers()
                else:
                    items = observer.GetMenuHandlers()
            except Exception, msg:
                util.Log("[ed_main][err] MainWindoAddOn.GetEventHandlers: %s" % str(msg))
                continue
            handlers.extend(items)
Exemple #22
0
 def GenerateText(self, e_id, txt_ctrl):
     """Generates the new document text based on the given
     generator id and contents of the given ED_STC text control.
     @param e_id: event id originating from menu entry
     @param txt_ctrl: reference document to generate from
     @type txt_ctrl: EditraStc
     @return: the generated text
     @rtype: string
     
     """
     gentext = None
     start = time.time()
     for observer in self.observers:
         if observer.GetId() == e_id:
             gentext = observer.Generate(txt_ctrl)
     util.Log("[generator][info] Generation time %f" % (time.time() - start))
     return gentext
Exemple #23
0
    def OnConfigExit(self, msg):
        """Update current state when the config dialog has been closed
        @param msg: Message Object

        """
        util.Log("[Launch][info] Saving config to profile")
        self.RefreshControlBar()
        Profile_Set(
            LAUNCH_KEY,
            handlers.GetState())  # TODO is this necessary see other handler
        # Update wordwrapping
        mode = wx.stc.STC_WRAP_NONE
        if self._prefs.get('wrapoutput', False):
            mode = wx.stc.STC_WRAP_WORD  # should we do wrap char?
        wrapmode = self._buffer.GetWrapMode()
        if wrapmode != mode:
            self._buffer.SetWrapMode(mode)
        self.UpdateBufferColors()
Exemple #24
0
    def SetBinding(cls, item_id, keys):
        """Set the keybinding of a menu id
        @param item_id: item to set
        @param keys: string or list of key strings

        """
        if cls.cprofile is None:
            util.Log("[keybinder][warn] No keyprofile has been loaded yet")
        else:
            if isinstance(keys, basestring):
                keys = [key.strip() for key in keys.split('+')]

            if len(keys):
                cls.keyprofile[item_id] = keys
            elif cls.keyprofile.has_key(item_id):
                del cls.keyprofile[item_id]
            else:
                pass
    def GenerateText(self, e_id, txt_ctrl):
        """Generates the new document text based on the given
        generator id and contents of the given ED_STC text control.
        @param e_id: event id originating from menu entry
        @param txt_ctrl: EditraStc
        @return: the generated text

        """
        gentext = None
        start = time.time()
        # Find the correct generator and run its generate method on the
        # given text control.
        for observer in self.observers:
            if observer.GetId() == e_id:
                gentext = observer.Generate(txt_ctrl)
                util.Log("[generator][info] Generation time %f" %
                         (time.time() - start))
        return gentext
Exemple #26
0
    def UpdateCurrentFiles(self, lang_id):
        """Update the current set of open files that are of the same
        type.
        @param lang_id: Editra filetype id
        @postcondition: all open files that are of the same type are set
                        and stored in the file choice control.

        """
        self._fnames = list()
        for txt_ctrl in self._mw.GetNotebook().GetTextControls():
            if lang_id == txt_ctrl.GetLangId():
                self._fnames.append(txt_ctrl.GetFileName())

        items = [os.path.basename(fname) for fname in self._fnames]
        try:
            self._chFiles.SetItems(items)
        except TypeError:
            util.Log("[Launch][err] UpdateCurrent Files: " + str(items))
            self._chFiles.SetItems([''])
    def SetBreakpoint(filepath, lineno, exprstr, enabled):
        """Set a breakpoint in the given file
        @param filepath: normalized file path
        @param lineno: buffer display line number

        """
        if not os.path.isfile(filepath):
            return
        if filepath in RpdbDebugger().breakpoints:
            linenos = RpdbDebugger().breakpoints[filepath]
        else:
            linenos = {}
            RpdbDebugger().breakpoints[filepath] = linenos
        linenos[lineno] = (enabled, exprstr)
        util.Log("[DbgBp][info] SetBreakpoint %s, %d, %s, %s" % \
                 (filepath, lineno, enabled, exprstr))
        if enabled:
            RpdbDebugger().set_breakpoint(filepath, lineno, exprstr)
        BreakpointController.SaveBreakpoints()
        BreakpointController.SetEditorBreakpoint(filepath, lineno, enabled, False)
        return lineno
    def attach(self, processcreator):
        if not processcreator:
            return
        self.processcreator = processcreator
        pid = str(processcreator.GetPID())
        tries = 0
        ex = None

        while tries != 5:
            sleep(1)
            util.Log("[PyDbg][info] Trying to Attach")
            ex = None
            try:
                if self.abortattach:
                    self.do_abort()
                    break
                self.sessionmanager.attach(pid, encoding=rpdb2.detect_locale())
                self.attached = True
                break
            except Exception, ex:
                tries = tries + 1
    def OnFrameSelected(self, evt):
        index = evt.GetIndex()
        if self.previndex == index:
            return
        filename = self.GetItem(index, StackFrameList.COL_FILE).GetText()
        if index > self.GetItemCount() - 4:
            if filename and os.path.basename(filename) == "rpdb2.py":
                return
        self.previndex = index
        RpdbDebugger().set_frameindex(index)

        if not filename:
            return
        editor = PyStudioUtils.GetEditorOrOpenFile(self._mainw, filename)
        if editor:
            try:
                lineno = int(
                    self.GetItem(index, StackFrameList.COL_LINE).GetText())
                editor.GotoLine(lineno - 1)
            except ValueError:
                util.Log("[PyStudio][err] StackFrame: failed to jump to file")
Exemple #30
0
    def GetEditorForFile(mainw, fname):
        """Return the EdEditorView that's managing the file, if available
        @param fname: File name to open
        @param mainw: MainWindow instance to open the file in
        @return: Text control managing the file
        @rtype: ed_editv.EdEditorView

        """
        if mainw and hasattr(mainw, 'GetNotebook'):
            nb = mainw.GetNotebook()
            filepath = os.path.normcase(fname)
            if nb:
                for page in nb.GetTextControls():
                    tabfile = os.path.normcase(page.GetFileName())
                    if tabfile == filepath:
                        return page
        else:
            util.Log("[PyStudio][warn] invalid object in GetEditorForFile %s" %
                     repr(mainw))

        return None