Example #1
0
class CodeBrowser(plugin.Plugin):
    """Adds a CodeBrowser to the view menu"""
    plugin.Implements(iface.MainWindowI)

    def PlugIt(self, parent):
        """Adds the view menu entry and registers the event handler"""
        self._mw = parent
        self._log = wx.GetApp().GetLog()
        if self._mw != None:
            self._log("[codebrowser][info] Installing codebrowser plugin")

            #---- Create File Browser ----#
            self._codebrowser = cbrowser.CodeBrowserTree(self._mw)
            mgr = self._mw.GetFrameManager()
            mgr.AddPane(self._codebrowser,
                        wx.aui.AuiPaneInfo().Name(cbrowser.PANE_NAME).\
                            Caption(_("Editra | CodeBrowser")).\
                            Top().Right().Layer(0).\
                            CloseButton(True).MaximizeButton(True).\
                            BestSize(wx.Size(215, 350)))
            mgr.Update()

    def GetMenuHandlers(self):
        """Pass even handler for menu item to main window for management"""
        return [(cbrowser.ID_CODEBROWSER, self._codebrowser.OnShowBrowser)]

    def GetUIHandlers(self):
        """Pass Ui handlers to main window for management"""
        return [(cbrowser.ID_CODEBROWSER, self._codebrowser.OnUpdateMenu)]
class Calculator(plugin.Plugin):
    """Simple Programmer's Calculator"""
    plugin.Implements(iface.MainWindowI)
    def PlugIt(self, parent):
        """Hook the calculator into the menu and bind the event"""
        util.Log("[calc][info] Installing calculator plugin")

        # Add Menu
        viewm = parent.GetMenuBar().GetMenuByName("view")
        mitem = viewm.InsertAlpha(calc.ID_CALC, _("Calculator"), 
                                  ("Open Calculator"), wx.ITEM_CHECK, 
                                  after=ed_glob.ID_PRE_MARK)

        if calc.CalcFrame.INSTANCE is not None:
            mitem.Check(calc.CalcFrame.INSTANCE.IsShown())

    def GetMenuHandlers(self):
        """Register the calculators menu event handler with the 
        top level window and the app.

        """
        return [(calc.ID_CALC, calc.ShowCalculator)]

    def GetUIHandlers(self):
        """No UpdateUI events are needed to be processed by this plugin
        so return an empty list.

        """
        return [(calc.ID_CALC, calc.UpdateMenu)]
class PyRun(plugin.Plugin):
    """Adds a PyRun to the Shelf"""
    plugin.Implements(iface.ShelfI)
    ID_PYRUN = wx.NewId()
    __name__ = u'PyRun'

    def AllowMultiple(self):
        """PyRun allows multiple instances"""
        return True

    def CreateItem(self, parent):
        """Returns a PyRun Panel"""
        self._log = wx.GetApp().GetLog()
        self._log("[PyRun][info] Creating PyRun instance for Shelf")

        output = outwin.OutputWindow(parent)
        window = wx.GetApp().GetTopWindow()
        if getattr(window, '__name__', ' ') == 'MainWindow':
            ctrl = window.GetNotebook().GetCurrentCtrl()
            if ctrl.GetLangId() == synglob.ID_LANG_PYTHON:
                wx.CallLater(100, output.SetScript, ctrl.GetFileName())
        return output

    def GetId(self):
        return self.ID_PYRUN

    def GetMenuEntry(self, menu):
        return wx.MenuItem(menu, self.ID_PYRUN, self.__name__,
                           _("Executes a python script"))

    def GetName(self):
        return self.__name__
Example #4
0
class FileBrowserPanel(plugin.Plugin):
    """Adds a filebrowser to the view menu"""
    plugin.Implements(iface.MainWindowI)

    def PlugIt(self, parent):
        """Adds the view menu entry and registers the event handler"""
        self._mw = parent
        self._log = wx.GetApp().GetLog()
        if self._mw != None:
            self._log("[filebrowser][info] Installing filebrowser plugin")

            #---- Create File Browser ----#
            # TODO hook in saved filter from profile
            self._filebrowser = browser.BrowserPane(self._mw,
                                                    browser.ID_BROWSERPANE)
            mgr = self._mw.GetFrameManager()
            mgr.AddPane(self._filebrowser,
                        wx.aui.AuiPaneInfo().Name(browser.PANE_NAME).\
                            Caption("File Browser").Left().Layer(1).\
                            CloseButton(True).MaximizeButton(True).\
                            BestSize(wx.Size(215, 350)))
            mgr.Update()

    def GetMenuHandlers(self):
        """Pass even handler for menu item to main window for management"""
        return [(browser.ID_FILEBROWSE, self._filebrowser.OnShowBrowser)]

    def GetUIHandlers(self):
        """Pass Ui handlers to main window for management"""
        return [(browser.ID_FILEBROWSE, self._filebrowser.OnUpdateMenu)]
Example #5
0
class PyShell(plugin.Plugin):
    """Adds a PyShell to the Shelf"""
    plugin.Implements(iface.ShelfI)
    __name__ = u'PyShell'

    def AllowMultiple(self):
        """PyShell allows multiple instances"""
        return True

    def CreateItem(self, parent):
        """Returns a PyShell Panel"""
        util.Log("[PyShell][info] Creating PyShell instance for Shelf")
        return EdPyShellBox(parent)

    def GetBitmap(self):
        """Get the bitmap for representing this control in the ui
        @return: wx.Bitmap

        """
        return wx.ArtProvider.GetBitmap(str(ed_glob.ID_PYSHELL), wx.ART_MENU)

    def GetId(self):
        return ed_glob.ID_PYSHELL

    def GetMenuEntry(self, menu):
        return wx.MenuItem(menu, ed_glob.ID_PYSHELL, self.__name__,
                           _("Open A Python Shell"))

    def GetName(self):
        return self.__name__

    def IsStockable(self):
        return True
Example #6
0
class Hello(plugin.Plugin):
    """Adds Hello World to the View Menu"""
    plugin.Implements(iface.MainWindowI)

    def PlugIt(self, parent):
        """Adds the view menu entry registers the event handler"""
        if parent:
            # This will let you use Editra's loggin system
            self._log = wx.GetApp().GetLog()
            self._log("[hello][info] Installing Hello World")
            vm = parent.GetMenuBar().GetMenuByName("view")
            vm.Append(ID_HELLO, _("Hello World"),
                      _("Open a Hello World Dialog"))
        else:
            self._log("[hello][err] Failed to install hello plugin")

    def GetMenuHandlers(self):
        """This is used to register the menu handler with the app and
        associate the event with the parent window. It needs to return
        a list of ID/Handler pairs for each menu handler that the plugin
        is providing.

        """
        return [(ID_HELLO, SayHello)]

    def GetUIHandlers(self):
        """This is used to register the update ui handler with the app and
        associate the event with the parent window. This plugin doesn't use
        the UpdateUI event so it can just return an empty list.

        """
        return list()
Example #7
0
class Projects(plugin.Plugin):
    """Adds a projects pane to the view menu"""
    plugin.Implements(iface.MainWindowI)

    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()

    def GetMenuHandlers(self):
        """Returns the menu event handlers"""
        return [(ProjectPane.ID_PROJECTS, self._projects.OnShowProjects)]

    def GetMinVersion(self):
        """Get the minimum version of Editra that this plugin supports"""
        return "0.6.48"

    def GetUIHandlers(self):
        """Returns handlers for UpdateUI events"""
        return [(ProjectPane.ID_PROJECTS, self._projects.OnUpdateMenu)]
Example #8
0
class PyShell(plugin.Plugin):
    """Adds a PyShell to the Shelf"""
    plugin.Implements(iface.ShelfI)
    ID_PYSHELL = wx.NewId()
    __name__ = u'PyShell'

    def __SetupFonts(self):
        """Create the font settings for the shell"""
        fonts = {
            'size': 11,
            'lnsize': 10,
            'backcol': '#FFFFFF',
            'calltipbg': '#FFFFB8',
            'calltipfg': '#404040',
        }

        font = Profile_Get(
            'FONT1', 'font',
            wx.Font(11, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL,
                    wx.FONTWEIGHT_NORMAL))
        if font.IsOk() and len(font.GetFaceName()):
            fonts['mono'] = font.GetFaceName()
            fonts['size'] = font.GetPointSize()
            if fonts['size'] < 11:
                fonts['size'] = 11
            fonts['lnsize'] = fonts['size'] - 1

        font = Profile_Get(
            'FONT2', 'font',
            wx.Font(11, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_NORMAL,
                    wx.FONTWEIGHT_NORMAL))
        if font.IsOk() and len(font.GetFaceName()):
            fonts['times'] = font.GetFaceName()
            fonts['helv'] = font.GetFaceName()
            fonts['other'] = font.GetFaceName()

        return fonts

    def AllowMultiple(self):
        """PyShell allows multiple instances"""
        return True

    def CreateItem(self, parent):
        """Returns a PyShell Panel"""
        self._log = wx.GetApp().GetLog()
        self._log("[pyshell][info] Creating PyShell instance for Shelf")
        pyshell = shell.Shell(parent, locals=dict())
        pyshell.setStyles(self.__SetupFonts())
        return pyshell

    def GetId(self):
        return self.ID_PYSHELL

    def GetMenuEntry(self, menu):
        return wx.MenuItem(menu, self.ID_PYSHELL, self.__name__,
                           _("Open A Python Shell"))

    def GetName(self):
        return self.__name__
Example #9
0
class Launch(plugin.Plugin):
    """Script Launcher and output viewer"""
    plugin.Implements(iface.ShelfI)
    ID_LAUNCH = wx.NewId()
    INSTALLED = False
    SHELF = None

    @property
    def __name__(self):
        return u'Launch'

    def AllowMultiple(self):
        """Launch allows multiple instances"""
        return True

    def CreateItem(self, parent):
        """Create a Launch panel"""
        util.Log("[Launch][info] Creating Launch instance for Shelf")
        return launch.LaunchWindow(parent)

    def GetId(self):
        """The unique identifier of this plugin"""
        return self.ID_LAUNCH

    def GetMenuEntry(self, menu):
        """This plugins menu entry"""
        return wx.MenuItem(menu, self.ID_LAUNCH, self.__name__,
                           _("Run script from current buffer"))

    def GetMinVersion(self):
        return "3.15"

    def GetName(self):
        """The name of this plugin"""
        return self.__name__

    def InstallComponents(self, mainw):
        """Install extra menu components
        param mainw: MainWindow Instance

        """
        tmenu = mainw.GetMenuBar().GetMenuByName("tools")
        tmenu.Insert(0, ed_glob.ID_RUN_LAUNCH, _("Run") + \
                     EdMenuBar.keybinder.GetBinding(ed_glob.ID_RUN_LAUNCH),
                     _("Run the file associated with the current buffer in Launch"))
        mainw.AddMenuHandler(ed_glob.ID_RUN_LAUNCH, OnRequestHandler)
        mainw.AddUIHandler(ed_glob.ID_RUN_LAUNCH, OnUpdateMenu)
        tmenu.Insert(1, wx.ID_SEPARATOR)

    def IsInstalled(self):
        """Check whether launch has been installed yet or not
        @note: overridden from Plugin
        @return bool

        """
        return Launch.INSTALLED

    def IsStockable(self):
        return True
Example #10
0
class EnigmaPlugin(plugin.Plugin):
    """Text encoder/decoder context menu plugin"""
    plugin.Implements(iface.MainWindowI)

    def PlugIt(self, parent):
        util.Log("[Enigma][info] PlugIt called")
        # Note: multiple subscriptions are ok it will only be
        #       called once.
        ed_msg.Subscribe(self.OnContextMenu, ed_msg.EDMSG_UI_STC_CONTEXT_MENU)

    def GetMenuHandlers(self):
        """Not needed by this plugin"""
        return list()

    def GetUIHandlers(self):
        """Not needed by this plugin"""
        return list()

    def GetMinVersion(self):
        return u"0.7.00"

    #---- Implementation ----#

    @staticmethod
    def OnContextMenu(msg):
        """EdMsg Handler for customizing the buffers context menu"""
        menumgr = msg.GetData()
        menu = menumgr.GetMenu()
        if menu:
            # Build Submenu
            subMen = wx.Menu()

            b16enc = subMen.Append(ID_BASE16_ENC, _("Base16 Encode"))
            b32enc = subMen.Append(ID_BASE32_ENC, _("Base32 Encode"))
            b64enc = subMen.Append(ID_BASE64_ENC, _("Base64 Encode"))
            b64encUn = subMen.Append(ID_BASE64_ENC_UNIX,
                                     _("Base64 Encode with Unix EOL"))

            subMen.AppendSeparator()

            b16dec = subMen.Append(ID_BASE16_DEC, _("Base16 Decode"))
            b32dec = subMen.Append(ID_BASE32_DEC, _("Base32 Decode"))
            b64dec = subMen.Append(ID_BASE64_DEC, _("Base64 Decode"))

            menu.InsertMenu(0, ID_ENIGMA, u"Enigma", subMen)
            menu.InsertSeparator(1)

            buf = menumgr.GetUserData('buffer')
            if buf:
                # Only enable the menu item if there is a selection in the
                # buffer.
                has_sel = buf.HasSelection()
                for item in (b16enc, b32enc, b64enc, b64encUn, b16dec, b32dec,
                             b64dec):
                    item.Enable(has_sel)
                    menumgr.AddHandler(item.Id, OnEnDe)
class CrystalTheme(plugin.Plugin):
    """Represents the Crystal Icon theme for Editra"""
    plugin.Implements(ed_theme.ThemeI)

    def __LoadBitmapData(self, path):
        """Loads image data into a bitmap, returns None if there is a failure"""
        try:
            data = __loader__.get_data(os.path.join(__path__[0], path))
        except IOError:
            pass
        else:
            bmp = wx.ImageFromStream(cStringIO.StringIO(data),
                                     wx.BITMAP_TYPE_PNG)
            return bmp.ConvertToBitmap()

    def GetName(self):
        return u'Crystal'

    def GetMenuBitmap(self, bmp_id):
        if bmp_id in ed_theme.ART:
            path = MENU_PATH + ed_theme.ART[bmp_id]
            bmp = self.__LoadBitmapData(path)
            if bmp is not None:
                return bmp
        else:
            return self.GetFileBitmap(bmp_id)

        return wx.NullBitmap

    def GetFileBitmap(self, bmp_id):
        bmp = None
        if bmp_id in ed_theme.MIME_ART:
            path = MIME_PATH + ed_theme.MIME_ART[bmp_id]
            bmp = self.__LoadBitmapData(path)
            if bmp is not None:
                return bmp

        if bmp is None and bmp_id in syntax.SyntaxIds():
            # Fail back to plain text bitmap
            bkup = MIME_PATH + ed_theme.MIME_ART[synglob.ID_LANG_TXT]
            bmp = self.__LoadBitmapData(bkup)
            if bmp is not None:
                return bmp

        return wx.NullBitmap

    def GetToolbarBitmap(self, bmp_id):
        if bmp_id in ed_theme.ART:
            path = TOOL_PATH + ed_theme.ART[bmp_id]
            bmp = self.__LoadBitmapData(path)
            if bmp is not None:
                return bmp

        return wx.NullBitmap
Example #12
0
class CssOptimizer(plugin.Plugin):
    """ Optimizes Css Files """
    plugin.Implements(generator.GeneratorI)

    def Generate(self, txt_ctrl):
        """Generate an optimized version of the given css file.
        If the file does note appear to be css it will return the
        input verbatim.

        """
        stc = txt_ctrl
        eol = stc.GetEOLChar()
        if stc.GetLexer() == wx.stc.STC_LEX_CSS or \
           (len(stc.filename) > 3 and stc.filename[-3:] == "css"):
            # Optimize the text
            lines = [stc.GetLine(x) for x in xrange(stc.GetLineCount() + 1)]
            to_pop = list()
            # First Pass compact everything
            for x in xrange(len(lines)):
                line = lines[x].strip()
                if u':' in line:
                    line = line.split(u':')
                    for y in xrange(len(line)):
                        line[y] = line[y].strip()
                    line = u':'.join(line)
                if u"{" in line:
                    line = line.split(u'{')
                    for y in xrange(len(line)):
                        line[y] = line[y].strip()
                    line = u'{'.join(line)
                if len(line) and line[-1] == u'}':
                    line += eol
                lines[x] = line
            # Finally remove all comments
            txt = "".join(lines)
            cmt_pat = re.compile("\/\*[^*]*\*+([^/][^*]*\*+)*\/")
            if re.search(cmt_pat, txt):
                txt = re.sub(cmt_pat, u'', txt)
            ret = ('css', txt)
        else:
            ret = ('txt', stc.GetText())
        return ret

    def GetId(self):
        """Returns the identifing Id of this generator"""
        return ID_CSS_OPTIMIZER

    def GetMenuEntry(self, menu):
        """Returns the MenuItem entry for this generator"""
        mi = wx.MenuItem(menu, ID_CSS_OPTIMIZER,
                         _("Optimize %s") % u"CSS",
                         _("Generate an optimized version of the css"))
        mi.SetBitmap(wx.ArtProvider.GetBitmap(str(ID_LANG_CSS), wx.ART_MENU))
        return mi
Example #13
0
class ProjectsModList(plugin.Plugin):
    """Shelf interface implementation for the Repo Modification List"""
    plugin.Implements(iface.ShelfI)

    @property
    def __name__(self):
        return u'Source Control'

    def AllowMultiple(self):
        """ModList allows multiple instances"""
        return True

    def CreateItem(self, parent):
        """Returns a log viewer panel"""
        modbox = RepoModBox(parent)
        modbox.SetFileOpenerHook(wx.GetApp().MacOpenFile)
        return modbox

    def GetBitmap(self):
        """Get the tab icon
        @return: wx.Bitmap

        """
        return FileIcons.getScUpdateBitmap()

    def GetId(self):
        """Plugin menu identifier ID"""
        return ID_MODLIST

    def GetMenuEntry(self, menu):
        """Get the menu entry for the log viewer
        @param menu: the menu items parent menu

        """
        item = wx.MenuItem(menu, ID_MODLIST, _("Source Control"),
                           _("Open the Projects source control summary list"))
        item.SetBitmap(self.GetBitmap())
        return item

    def GetName(self):
        """Return the name of this control"""
        return self.__name__

    def IsStockable(self):
        """ModList can be saved in the shelf preference stack"""
        return True
Example #14
0
class MacroManager(plugin.Plugin):
    """Manage macros"""
    plugin.Implements([iface.ShelfI])

    def AllowMultiple(self):
        """This method is used to check if multiple instances of this
        item are allowed to be open at one time.
        @return: True/False
        @rtype: boolean

        """
        return False

    def CreateItem(self, parent):
        """This is them method used to open the item in the L{Shelf}
        It should return an object that is a Panel or subclass of a Panel.
        @param parent: The would be parent window of this panel
        @return: wx.Panel

        """

    def GetId(self):
        """Return the id that identifies this item (same as the menuid)
        @return: Item ID
        @rtype: int

        """
        return ID_MACRO_MAN

    def GetMenuEntry(self, menu):
        """Returns the menu entry for the Macro Manager
        @param menu: The menu this entry will be added to
        @return: wx.MenuItem

        """
        return wx.MenuItem(menu, ID_MACRO_MAN, _("Macro Manager"),
                           _("View and Edit Macros"))

    def GetName(self):
        """Return the name of this shelf item. This should be the
        same as the MenuEntry's label.
        @return: name of item
        @rtype: string

        """
        return _(u"Macro Manager")
Example #15
0
class EdLogViewer(plugin.Plugin):
    """Shelf interface implementation for the log viewer"""
    plugin.Implements(iface.ShelfI)

    __name__ = u'Editra Log'

    @staticmethod
    def AllowMultiple():
        """EdLogger allows multiple instances"""
        return True

    @staticmethod
    def CreateItem(parent):
        """Returns a log viewr panel"""
        return LogViewer(parent)

    def GetBitmap(self):
        """Get the log viewers tab icon
        @return: wx.Bitmap

        """
        bmp = wx.ArtProvider.GetBitmap(str(self.GetId()), wx.ART_MENU)
        return bmp

    @staticmethod
    def GetId():
        """Plugin menu identifier ID"""
        return ed_glob.ID_LOGGER

    @staticmethod
    def GetMenuEntry(menu):
        """Get the menu entry for the log viewer
        @param menu: the menu items parent menu

        """
        return wx.MenuItem(menu, ed_glob.ID_LOGGER, _("Editra Log"),
                           _("View Editra's console log"))

    def GetName(self):
        """Return the name of this control"""
        return self.__name__

    @staticmethod
    def IsStockable():
        """EdLogViewer can be saved in the shelf preference stack"""
        return True
Example #16
0
class FileBrowserPanel(plugin.Plugin):
    """Adds a filebrowser to the view menu"""
    plugin.Implements(ed_main.MainWindowI)

    def PlugIt(self, parent):
        """Adds the view menu entry and registers the event handler"""
        self._mw = parent
        self._log = wx.GetApp().GetLog()
        if self._mw != None:
            self._log("[filebrowser] Installing filebrowser plugin")

            #---- Create File Browser ----#
            self._filebrowser = BrowserPane(self._mw, ID_BROWSERPANE)
            mgr = self._mw.GetFrameManager()
            mgr.AddPane(self._filebrowser, wx.aui.AuiPaneInfo().Name(PANE_NAME).\
                            Caption("Editra | File Browser").Left().Layer(1).\
                            CloseButton(True).MaximizeButton(False).\
                            BestSize(wx.Size(215, 350)))

            if Profile_Get('SHOW_FB', 'bool', False):
                mgr.GetPane(PANE_NAME).Show()
            else:
                mgr.GetPane(PANE_NAME).Hide()
            mgr.Update()

            # Event Handlers
            self._mw.Bind(wx.aui.EVT_AUI_PANE_CLOSE, self.OnPaneClose)

    def GetMenuHandlers(self):
        return [(ID_FILEBROWSE, self._filebrowser.OnShowBrowser)]

    def GetUIHandlers(self):
        return list()

    def OnPaneClose(self, evt):
        """Handles when the pane is closed to update the profile"""
        if evt.GetPane().name == PANE_NAME:
            Profile_Set('SHOW_FB', False)
        else:
            evt.Skip()
class TheDailyWtf(plugin.Plugin):
    """Adds Submit to The DailyWtf context menu"""
    plugin.Implements(iface.MainWindowI)

    def PlugIt(self, parent):
        util.Log("[thedailywtf][info] PlugIt called")
        # Note: multiple subscriptions are ok it will only be
        #       called once.
        ed_msg.Subscribe(self.OnContextMenu, ed_msg.EDMSG_UI_STC_CONTEXT_MENU)

    def GetMenuHandlers(self):
        """Not needed by this plugin"""
        return list()

    def GetUIHandlers(self):
        """Not needed by this plugin"""
        return list()

    def GetMinVersion(self):
        return u"0.5.86"

    #---- Implementation ----#

    @staticmethod
    def OnContextMenu(msg):
        """EdMsg Handler for customizing the buffers context menu"""
        menumgr = msg.GetData()
        menu = menumgr.GetMenu()
        if menu:
            menu.AppendSeparator()
            item = menu.Append(ID_TDWTF, _("Submit to TDWTF"))
            item.SetBitmap(WTFICON.GetBitmap())
            buf = menumgr.GetUserData('buffer')
            if buf:
                # Only enable the menu item if there is a selection in the
                # buffer.
                hassel = buf.HasSelection()
                item.Enable(hassel)
            menumgr.AddHandler(ID_TDWTF, OnSubmit)
Example #18
0
class Hello(plugin.Plugin):
    """Adds Hello World to the View Menu"""
    plugin.Implements(ed_main.MainWindowI)

    def PlugIt(self, parent):
        """Adds the view menu entry registers the event handler"""
        mw = parent
        if mw:
            self._log = wx.GetApp().GetLog()
            self._log("[hello] Installing Hello World")
            mb = mw.GetMenuBar()
            hm = mb.GetMenuByName("view")
            hm.Append(ID_HELLO, _("Hello World"),
                      _("Open a Hello World Dialog"))
        else:
            self._log("[hello][err] Failed to install hello plugin")

    def GetMenuHandlers(self):
        return [(ID_HELLO, SayHello)]

    def GetUIHandlers(self):
        return list()
Example #19
0
class Calculator(plugin.Plugin):
    """Simple Programmer's Calculator"""
    plugin.Implements(ed_main.MainWindowI)
    def PlugIt(self, parent):
        """Hook the calculator into the menu and bind the event"""
        self._log = wx.GetApp().GetLog()
        self._log("[calc] Installing calculator plugin")

        # Add Menu
        mb = parent.GetMenuBar()
        vm = mb.GetMenuByName("view")
        mi = vm.InsertAlpha(calc.ID_CALC, _("Calculator"), 
                                 ("Open Calculator"), wx.ITEM_CHECK, 
                                 after=ed_glob.ID_PRE_MARK)

        if calc.CalcFrame.INSTANCE is not None:
            mi.Check(calc.CalcFrame.INSTANCE.IsShown())

    def GetMenuHandlers(self):
        return [(calc.ID_CALC, calc.ShowCalculator)]

    def GetUIHandlers(self):
        return list()
class Terminal(plugin.Plugin):
    """Adds a Terminal to the Shelf"""
    plugin.Implements(iface.ShelfI)
    ID_TERM = wx.NewId()
    __name__ = u'Terminal'

    def AllowMultiple(self):
        """Terminal allows multiple instances"""
        return True

    def CreateItem(self, parent):
        """Returns a Terminal Panel"""
        self._log = wx.GetApp().GetLog()
        self._log("[term][info] Creating Terminal instance for Shelf")
        return terminal.Xterm(parent, wx.ID_ANY)

    def GetId(self):
        return self.ID_TERM

    def GetMenuEntry(self, menu):
        return wx.MenuItem(menu, self.ID_TERM, self.__name__, _("Open A Terminal"))

    def GetName(self):
        return self.__name__
Example #21
0
class Launch(plugin.Plugin):
    """Script Launcher and output viewer"""
    plugin.Implements(iface.ShelfI)
    ID_LAUNCH = wx.NewId()

    @property
    def __name__(self):
        return u'Launch'

    def AllowMultiple(self):
        """Launch allows multiple instances"""
        return True

    def CreateItem(self, parent):
        """Create a Launch panel"""
        self._log = wx.GetApp().GetLog()
        self._log("[Launch][info] Creating Launch instance for Shelf")

        output = launch.LaunchWindow(parent)
        return output

    def GetId(self):
        """The unique identifier of this plugin"""
        return self.ID_LAUNCH

    def GetMenuEntry(self, menu):
        """This plugins menu entry"""
        return wx.MenuItem(menu, self.ID_LAUNCH, self.__name__,
                           _("Run script from current buffer"))

    def GetName(self):
        """The name of this plugin"""
        return self.__name__

    def IsStockable(self):
        return True
Example #22
0
class EdLogViewer(plugin.Plugin):
    """Shelf interface implementation for the log viewer"""
    plugin.Implements(iface.ShelfI)
    ID_LOGGER = wx.NewId()

    @property
    def __name__(self):
        return u'Editra Log'

    def AllowMultiple(self):
        """EdLogger allows multiple instances"""
        return True

    def CreateItem(self, parent):
        """Returns a log viewr panel"""
        return LogViewer(parent)

    def GetId(self):
        """Plugin menu identifier ID"""
        return self.ID_LOGGER

    def GetMenuEntry(self, menu):
        """Get the menu entry for the log viewer
        @param menu: the menu items parent menu

        """
        return wx.MenuItem(menu, self.ID_LOGGER, _("Editra Log"),
                           _("View Editra's console log"))

    def GetName(self):
        """Return the name of this control"""
        return self.__name__

    def IsStockable(self):
        """EdLogViewer can be saved in the shelf preference stack"""
        return True
Example #23
0
class EdFindResults(plugin.Plugin):
    """Shelf interface implementation for the find results"""
    plugin.Implements(iface.ShelfI)
    SUBSCRIBED = False
    RESULT_SCREENS = list()

    def __init__(self, pmgr):
        """Create the FindResults plugin
        @param pmgr: This plugins manager

        """
        if not EdFindResults.SUBSCRIBED:
            ed_msg.Subscribe(EdFindResults.StartResultsScreen,
                             ed_msg.EDMSG_START_SEARCH)
            EdFindResults.SUBSCRIBED = True

#    def __del__(self):
#        if EdFindResults.SUBSCRIBED:
#            print "UNSUBSCRIBE"
#            ed_msg.Unsubscribe(self.StartResultsScreen)

    @property
    def __name__(self):
        return u'Find Results'

    def AllowMultiple(self):
        """Find Results allows multiple instances"""
        return True

    def CreateItem(self, parent):
        """Returns a log viewr panel"""
        screen = SearchResultScreen(parent)
        EdFindResults.RESULT_SCREENS.append(screen)
        return screen

    def GetBitmap(self):
        """Get the find results bitmap
        @return: wx.Bitmap

        """
        bmp = wx.ArtProvider.GetBitmap(str(ed_glob.ID_FIND), wx.ART_MENU)
        return bmp

    def GetId(self):
        """Plugin menu identifier ID"""
        return ed_glob.ID_FIND_RESULTS

    def GetMenuEntry(self, menu):
        """Get the menu entry for the log viewer
        @param menu: the menu items parent menu

        """
        return None

    def GetName(self):
        """Return the name of this control"""
        return self.__name__

    def IsStockable(self):
        """EdLogViewer can be saved in the shelf preference stack"""
        return False

    @classmethod
    def StartResultsScreen(cls, msg):
        """Start a search in an existing window or open a new one
        @param cls: this class
        @param msg: message object

        """
        win = wx.GetApp().GetActiveWindow()

        # Cleanup window list for dead objects
        to_pop = list()
        for idx, item in enumerate(list(EdFindResults.RESULT_SCREENS)):
            if not isinstance(item, SearchResultScreen):
                to_pop.append(idx)

        for idx in reversed(to_pop):
            EdFindResults.RESULT_SCREENS.pop(idx)

        # Try to find an empty existing window to use for the new search
        screen = None
        if win is not None:
            shelf = win.GetShelf()
            s_mw = shelf.GetOwnerWindow()
            shelf_nb = shelf.GetWindow()
            for item in EdFindResults.RESULT_SCREENS:
                if item.GetDisplayedLines() < 3 and \
                   s_mw is win and item.GetParent() is shelf_nb:
                    screen = shelf.RaiseWindow(item)
                    break

            if screen is None:
                shelf.PutItemOnShelf(ed_glob.ID_FIND_RESULTS)
                screen = shelf_nb.GetCurrentPage()

            # Fire off the search job
            data = msg.GetData()
            if len(data) > 1:
                # Doing a file search operation
                screen.StartSearch(data[0], *data[1], **data[2])
            else:
                # Doing a buffer find operation (in memory)
                screen.StartSearch(data[0])
Example #24
0
class LaTeX(plugin.Plugin):
    """Creates a LaTeX document object from the contents of the
    supplied document reference.
    @todo: performance improvements and wordwrap in generated document

    """
    plugin.Implements(GeneratorI)

    def __init__(self, plgmgr):
        """Initializes the LaTeX object
        @param plgmgr: pluginmanger for this object

        """
        plugin.Plugin.__init__(self)

        # Attributes
        self._stc = None
        self._id = ed_glob.ID_TEX_GEN
        self._dstyle = StyleItem()
        self._cmds = dict()

    def CreateCmdName(self, name):
        """Creates and returns a proper cmd name
        @param name: name to construct command from
        @return: latex formated command string

        """
        name = name.replace('_', '')
        tmp = list()
        alpha = "ABCDEFGHIJ"
        for char in name:
            if char.isdigit():
                tmp.append(alpha[int(char)])
            else:
                tmp.append(char)
        return "".join(tmp)

    def GenDoc(self):
        """Generates the document body of the LaTeX document
        @returns: the main body of the reference document marked up with latex

        """
        tex = list()
        tmp = u''
        start = parse_pos = 0
        last_pos = self._stc.GetLineEndPosition(self._stc.GetLineCount())

        # Define the default style
        self.RegisterStyleCmd('default_style', \
                              self._stc.GetItemByName('default_style'))

        # Get Document start point info
        last_id = self._stc.GetStyleAt(parse_pos)
        tmp = self.TransformText(
            self._stc.GetTextRange(parse_pos, parse_pos + 1))
        tag = self._stc.FindTagById(last_id)
        if tag != wx.EmptyString:
            self.RegisterStyleCmd(tag, self._stc.GetItemByName(tag))

        # Optimizations
        stc = self._stc
        GetStyleAt = stc.GetStyleAt
        GetTextRange = stc.GetTextRange
        TransformText = self.TransformText

        # Build LaTeX
        for parse_pos in xrange(last_pos + 1):
            curr_id = GetStyleAt(parse_pos)
            if parse_pos > 1:
                # This is the performance bottleneck, changeing the text
                # collection to when the style changes is much faster as
                # it only needs to be done once per style section instead
                # of once per character. Doing that however causes problems
                # with the style and resulting document formatting.
                tmp = TransformText(GetTextRange((parse_pos - 1), parse_pos))

            if curr_id == 0 and GetStyleAt(parse_pos + 1) == last_id:
                curr_id = last_id

            # If style region has changed close section
            if curr_id != last_id or tmp[-1] == "\n":
                tmp_tex = TransformText(GetTextRange(start, parse_pos))
                #                 tmp_tex = u"".join(tmp)
                if tag == "operator_style" or \
                   (tag == "default_style" and \
                    tmp_tex.isspace() and len(tmp_tex) <= 2):
                    tex.append(tmp_tex)
                else:
                    if "\\\\\n" in tmp_tex:
                        tmp_tex = tmp_tex.replace("\\\\\n", "")
                        tmp2 = "\\%s{%s}\\\\\n"
                    else:
                        tmp2 = "\\%s{%s}"

                    cmd = self.CreateCmdName(tag)
                    if cmd in [None, wx.EmptyString]:
                        cmd = "defaultstyle"
                    tex.append(tmp2 % (cmd, tmp_tex))

                last_id = curr_id
                tag = stc.FindTagById(last_id)
                if tag not in [None, wx.EmptyString]:
                    self.RegisterStyleCmd(tag, stc.GetItemByName(tag))
                tmp = list()
                start = parse_pos

        # Case for unstyled documents
        if tex == wx.EmptyString:
            tex.append(self.TransformText(stc.GetText()))
        return "\\begin{document}\n%s\n\\end{document}" % "".join(tex)

    def Generate(self, stc_doc):
        """Generates the LaTeX document
        @param stc_doc: text control to generate latex from
        @return: the reference document marked up in LaTeX.

        """
        self._stc = stc_doc
        default_si = self._stc.GetItemByName('default_style')
        self._dstyle.SetBack(default_si.GetBack().split(',')[0])
        self._dstyle.SetFore(default_si.GetFore().split(',')[0])
        self._dstyle.SetFace(default_si.GetFace().split(',')[0])
        self._dstyle.SetSize(default_si.GetSize().split(',')[0])
        body = self.GenDoc()
        preamble = self.GenPreamble()
        return ("tex", u"".join([preamble, body]))

    def GenPreamble(self):
        """Generates the Preamble of the document
        @return: the LaTeX document preamble

        """
        # Preamble template
        pre = (
            "%% \iffalse meta-comment\n"
            "%%\n%% Generated by Editra %s\n"
            "%% This is generator is Very Experimental.\n"
            "%% The code should compile in most cases but there may\n"
            "%% be some display issues when rendered.\n"
            "%%\n%%\n\n"
            "\\documentclass[11pt, a4paper]{article}\n"
            "\\usepackage[a4paper, margin=2cm]{geometry}\n"
            "\\usepackage[T1]{fontenc}\n"
            #               "\\usepackage{ucs}\n"
            #               "\\usepackage[utf8]{inputenc}\n"
            "\\usepackage{color}\n"
            "\\usepackage{alltt}\n"
            "\\usepackage{times}\n") % ed_glob.VERSION

        # Set the background color
        pre += ("\\pagecolor[rgb]{%s}\n" % \
                self.HexToRGB(self._dstyle.GetBack()))
        pre += "\\parindent=0in\n\n"

        # Insert all styling commands
        pre += "%% Begin Styling Command Definitions"
        for cmd in self._cmds:
            pre += ("\n" + self._cmds[cmd])
        pre += "\n%% End Styling Command Definitions\n\n"
        return pre

    def GetId(self):
        """Returns the menu identifier for the LaTeX generator
        @return: id of that identifies this generator

        """
        return self._id

    def GetMenuEntry(self, menu):
        """Returns the Menu control for the LaTeX generator
        @param menu: menu to create MenuItem for

        """
        return wx.MenuItem(menu, self._id, _("Generate %s") % u"LaTeX",
                           _("Generate an %s version of the " \
                             "current document") % u"LaTeX")

    def HexToRGB(self, hex_str):
        """Returns a comma separated rgb string representation
        of the input hex string. 1.0 = White, 0.0 = Black.
        @param hex_str: hex string to convert to latex rgb format

        """
        r_hex = hex_str
        if r_hex[0] == u"#":
            r_hex = r_hex[1:]
        ldiff = 6 - len(r_hex)
        r_hex += ldiff * u"0"
        # Convert hex values to integer
        red = round(float(float(int(r_hex[0:2], 16)) / 255), 2)
        green = round(float(float(int(r_hex[2:4], 16)) / 255), 2)
        blue = round(float(float(int(r_hex[4:], 16)) / 255), 2)
        return "%s,%s,%s" % (str(red), str(green), str(blue))

    def RegisterStyleCmd(self, cmd_name, s_item):
        """Registers and generates a command from the
        supplied StyleItem.
        @param cmd_name: name of command
        @param s_item: style item to create command for
        @postcondition: new styling command is created and registered for use

        """
        cmd_name = self.CreateCmdName(cmd_name)

        # If we already made a command for this style return
        if cmd_name in self._cmds:
            return

        # Templates
        uline_tmp = u"\\underline{%s}"
        ital_tmp = u"\\emph{%s}"
        bold_tmp = u"\\textbf{%s}"
        fore_tmp = u"\\textcolor[rgb]{%s}{%s}"
        back_tmp = u"\\colorbox[rgb]{%s}{#1}"
        cmd_tmp = u"\\newcommand{%s}[1]{%s}"

        # Get Style Attributes
        fore = s_item.GetFore()
        if fore == wx.EmptyString:
            fore = self._dstyle.GetFore()
        back = s_item.GetBack()
        if back == wx.EmptyString:
            back = self._dstyle.GetBack()
        face = s_item.GetFace()
        if face == wx.EmptyString:
            face = self._dstyle.GetFace()
        size = s_item.GetSize()
        if size == wx.EmptyString:
            size = self._dstyle.GetSize()

        back = back_tmp % self.HexToRGB(back.split(u',')[0])
        fore = fore_tmp % (self.HexToRGB(fore.split(u',')[0]), back)
        if u"bold" in unicode(s_item):
            fore = bold_tmp % fore
        if u"underline" in unicode(s_item):
            fore = uline_tmp % fore
        if u"italic" in unicode(s_item):
            fore = ital_tmp % fore
        cmd = cmd_tmp % (
            (u"\\" + cmd_name), u"\\texttt{\\ttfamily{%s}}" % fore)
        self._cmds[cmd_name] = cmd

    def TransformText(self, txt):
        """Transforms the given text into LaTeX format, by
        escaping all special characters and sequences.
        @param txt: text to transform
        @return: txt with all special characters transformed

        """
        ch_map = {
            "#": "\\#",
            "$": "\\$",
            "^": "\\^",
            "%": "\\%",
            "&": "\\&",
            "_": "\\_",
            "{": "\\{",
            "}": "\\}",
            "~": "\\~",
            "\\": "$\\backslash$",
            "\n": "\\\\\n",
            "@": "$@$",
            "<": "$<$",
            ">": "$>$",
            "-": "$-$",
            "|": "$|$"
        }
        tmp = list()
        for char in txt:
            tmp.append(ch_map.get(char, char))
        return u''.join(tmp)
Example #25
0
class Rtf(plugin.Plugin):
    """Generates a fully styled RTF document from the given text
    controls contents.
    @todo: add support for bold/italic/underline and multiple fonts

    """
    plugin.Implements(GeneratorI)

    def __init__(self, mgr):
        """Initializes and declares the attribute values for
        this generator.
        @param mgr: plugin manager of this object

        """
        plugin.Plugin.__init__(self)

        # Attributes
        self._stc = None
        self._id = ed_glob.ID_RTF_GEN
        self._colortbl = RtfColorTbl()

    def __str__(self):
        """Returns the RTF object as a string
        @return: rtf object as a string

        """
        return self._GenRtf()

    #---- Protected Member Functions ----#
    def _GenRtf(self):
        """Generates the RTF equivalent of the displayed text in the current
        stc document window.
        @precondition: self._stc must have been set by a call to Generate
        @return: generated rtf marked up text

        """
        # Buffer hasn't been set
        if self._stc is None:
            return u''

        # Optimizations
        stc = self._stc
        def_fore = stc.GetDefaultForeColour(as_hex=True)
        self._colortbl.AddColor(def_fore)
        def_back = stc.GetDefaultBackColour(as_hex=True)
        self._colortbl.AddColor(def_back)
        last_pos = stc.GetLineEndPosition(stc.GetLineCount())
        parse_pos = 0
        last_id = None
        last_fore = None
        last_back = None
        start = end = 0
        tmp_txt = list()
        font_tmp = "\\f0"
        fore_tmp = "\\cf%d"
        back_tmp = "\\cb%d"
        AddColor = self._colortbl.AddColor
        GetColorIndex = self._colortbl.GetColorIndex
        GetStyleAt = stc.GetStyleAt

        # Parse all characters/style bytes in document
        for parse_pos in xrange(last_pos + 1):
            sty_id = GetStyleAt(parse_pos)
            end = parse_pos

            # If style has changed build the previous section
            if sty_id != last_id:
                tag = stc.FindTagById(last_id)
                s_item = stc.GetItemByName(tag)
                AddColor(s_item.GetFore())
                AddColor(s_item.GetBack())
                tplate = font_tmp
                fid = GetColorIndex(s_item.GetFore())
                if fid != last_fore:
                    last_fore = fid
                    tplate = tplate + (fore_tmp % fid)
                bid = GetColorIndex(s_item.GetBack())
                if bid != last_back:
                    last_back = bid
                    tplate = tplate + (back_tmp % bid)
                tmp_txt.append(tplate + " " + \
                               self.TransformText(stc.GetTextRange(start, end)))
                start = end
            last_id = sty_id

        head = "{\\rtf1\\ansi\\deff0{\\fonttbl{\\f0 %s;}}" % \
                stc.GetDefaultFont().GetFaceName()
        return u"%s%s%s}" % (head, self._colortbl, "".join(tmp_txt))

    #---- End Protected Member Functions ----#

    def Generate(self, stc_doc):
        """Implements the GeneratorI's Generator Function by
        returning the RTF equvialent of the given stc_doc
        @param stc_doc: document to generate text from
        @return: document marked up in rtf

        """
        self._stc = stc_doc
        return ('rtf', self._GenRtf())

    def GetId(self):
        """Implements the GeneratorI's GetId function by returning
        the identifier for this generator.
        @return: identifier for this generator

        """
        return self._id

    def GetMenuEntry(self, menu):
        """Implements the GeneratorI's GetMenuEntry function by
        returning the MenuItem to associate with this object.
        @return: menu entry item for this generator

        """
        return wx.MenuItem(menu, self._id, _("Generate %s") % u"RTF",
                           _("Generate a %s version of the " \
                             "current document") % u"RTF")

    def TransformText(self, text):
        """Transforms the given text by converting it to RTF format
        @param text: text to transform
        @return: text with all special characters transformed
        """
        chmap = {
            "\t": "\\tab ",
            "{": "\\{",
            "}": "\\}",
            "\\": "\\\\",
            "\n": "\\par\n",
            "\r": "\\par\n"
        }
        text = text.replace('\r\n', '\n')
        tmp = u''
        for char in text:
            tmp = tmp + chmap.get(char, char)
        return tmp
Example #26
0
class Html(plugin.Plugin):
    """Transforms the text from a given Editra stc to a fully
    styled html page. Inline CSS is generated and inserted into
    the head of the Html to style the text regions by default
    unless requested to generate a separate sheet.

    """
    plugin.Implements(GeneratorI)

    def __init__(self, mgr):
        """Creates the Html object from an Editra stc text control
        @param mgr: This generators plugin manager

        """
        plugin.Plugin.__init__(self)

        # Attributes
        self._id = ed_glob.ID_HTML_GEN
        self.stc = None
        self.head = wx.EmptyString
        self.css = dict()
        self.body = wx.EmptyString

    def __str__(self):
        """Returns the string of html
        @return: string version of html object

        """
        # Assemble the embedded html
        style = "<style type=\"text/css\">\n%s</style>"
        css = wx.EmptyString
        for key in self.css:
            css += str(self.css[key]) + "\n"
        css = css % self.stc.GetFontDictionary()
        style = style % css

        # Insert the css into the head
        head = self.head.replace('</head>', style + "\n</head>")

        # Assemble the body of the html
        html = "<html>\n%s\n%s\n</html>"
        html = html % (head, self.body)
        return html

    def Unicode(self):
        """Returns the html as unicode
        @return: unicode string of html

        """
        return unicode(self.__str__())

    def Generate(self, stc_ctrl):
        """Generates and returns the document
        @param stc_ctrl: text control to get text from

        """
        self.stc = stc_ctrl
        self.head = self.GenerateHead()
        self.body = self.GenerateBody()
        return ("html", self.__str__())

    def GenerateHead(self):
        """Generates the html head block
        @return: html header information
        @rtype: string

        """
        return "<head>\n<title>%s</title>\n" \
               "<meta name=\"Generator\" content=\"Editra/%s\">\n" \
               "<meta http-equiv=\"content-type\" content=\"text/html; " \
               "charset=utf-8\">" \
               "\n</head>" % (ebmlib.GetFileName(self.stc.GetFileName()),
                              ed_glob.VERSION)

    def GenerateBody(self):
        """Generates the body of the html from the stc's content. To do
        this it does a character by character parse of the stc to determine
        style regions and generate css and and styled spans of html in order
        to generate an 'exact' html reqresentation of the stc's window.
        @return: the body section of the html generated from the text control

        """
        html = list()
        parse_pos = 0
        style_start = 0
        style_end = 0
        last_pos = self.stc.GetLineEndPosition(self.stc.GetLineCount()) + 1

        # Get Document start point info
        last_id = self.stc.GetStyleAt(parse_pos)
        tag = self.stc.FindTagById(last_id)
        if tag != wx.EmptyString:
            s_item = StyleItem()
            s_item.SetAttrFromStr(self.stc.GetStyleByName(tag))
            self.css[tag] = CssItem(tag.split('_')[0], s_item)

        # Optimizations
        stc = self.stc
        GetStyleAt = stc.GetStyleAt

        # Build Html
        while parse_pos < last_pos:
            parse_pos += 1
            curr_id = GetStyleAt(parse_pos)
            style_end = parse_pos
            # If style region has changed close section
            if curr_id == 0 and GetStyleAt(parse_pos + 1) == last_id:
                curr_id = last_id

            if curr_id != last_id or parse_pos == last_pos:
                tmp = stc.GetTextRange(style_start, style_end)
                tmp = self.TransformText(tmp)
                if tmp.isspace() or tag in ["default_style", "operator_style"]:
                    html.append(tmp)
                else:
                    tmp2 = "<span class=\"%s\">%s</span>"
                    html.append(tmp2 % (tag.split('_')[0], tmp))

                last_id = curr_id
                style_start = style_end
                tag = stc.FindTagById(last_id)
                if tag not in self.css:
                    s_item = StyleItem()
                    s_item.SetAttrFromStr(stc.GetStyleByName(tag))
                    self.css[tag] = CssItem(tag.split('_')[0], s_item)

        # Case for unstyled documents
        if len(html) == 0:
            s_item = StyleItem()
            s_item.SetAttrFromStr(stc.GetStyleByName('default_style'))
            self.css['default_style'] = CssItem('default', s_item)
            html.append(self.TransformText(stc.GetText()))
        else:
            self.OptimizeCss()

        return "<body class=\"default\">\n<pre>\n%s\n</pre>\n</body>" % \
                                                                   "".join(html)

    def GetId(self):
        """Returns the menu identifier for the HTML generator
        @return: id of this object

        """
        return self._id

    def GetMenuEntry(self, menu):
        """Returns the Menu control for the HTML generator
        @return: menu entry for this generator

        """
        return wx.MenuItem(menu, self._id, _("Generate %s") % u"HTML",
                           _("Generate a %s version of the " \
                             "current document") % u"HTML")

    def OptimizeCss(self):
        """Optimizes the CSS Set
        @postcondition: css is optimized to remove any redundant entries

        """
        # Must have the default style defined
        if 'default_style' not in self.css:
            return

        # Don't style operators. This is to optimize the html size
        if 'operator_style' in self.css:
            self.css.pop('operator_style')

        # All other css elements will inheirit from the default
        default = self.css['default_style']
        for key in self.css:
            if key == 'default_style':
                continue
            if default.GetFont() == self.css[key].GetFont():
                self.css[key].SetFont(wx.EmptyString)
            if default.GetFontSize() == self.css[key].GetFontSize():
                self.css[key].SetFontSize(wx.EmptyString)
            if default.GetBackground() == self.css[key].GetBackground():
                self.css[key].SetBackground(wx.EmptyString)
            if default.GetColor() == self.css[key].GetColor():
                self.css[key].SetColor(wx.EmptyString)
            for item in default.GetDecorators():
                if item in self.css[key].GetDecorators():
                    self.css[key].RemoveDecorator(item)

    def TransformText(self, text):
        """Does character substitution on a string and returns
        the html equivlant of the given string.
        @param text: text to transform
        @return: text with all special characters transformed

        """
        text = text.replace('&', "&amp;")  # Ampersands
        text = text.replace('<', "&lt;")  # Less Than Symbols
        text = text.replace('>', "&gt;")  # Greater Than Symbols
        text = text.replace("\"", "&quot;")
        return text
Example #27
0
class TangoTheme(plugin.Plugin):
    """Represents the Tango Icon theme for Editra"""
    plugin.Implements(ThemeI)

    name = u'Tango'

    def __GetArtPath(self, client, mime=False):
        """Gets the path of the resource directory to get
        the bitmaps from.
        @param client: wx.ART_MENU/wx.ART_TOOLBAR
        @keyword mime: is this a filetype icon lookup
        @return: path of art resource
        @rtype: string

        """
        clients = {
            wx.ART_MENU: u"menu",
            wx.ART_TOOLBAR: u"toolbar",
            wx.ART_OTHER: u"other"
        }

        # Get the path
        if ed_glob.CONFIG['THEME_DIR'] == u'':
            theme = util.ResolvConfigDir(os.path.join(u"pixmaps", u"theme"))
            ed_glob.CONFIG['THEME_DIR'] = theme

        if mime:
            path = os.path.join(ed_glob.CONFIG['THEME_DIR'],
                                Profile_Get('ICONS'), u'mime')
        else:
            path = os.path.join(ed_glob.CONFIG['THEME_DIR'], self.GetName(),
                                clients.get(client, u"menu"))

        path += os.sep
        if os.path.exists(path):
            return path
        else:
            return None

    def GetName(self):
        """Get the name of this theme
        @return: string

        """
        return TangoTheme.name

    def GetMenuBitmap(self, bmp_id):
        """Get a menu bitmap
        @param bmp_id: Id of bitmap to look for

        """
        if bmp_id in ART:
            path = self.__GetArtPath(wx.ART_MENU, mime=False)
            if path is not None:
                path = path + ART[bmp_id]
                if os.path.exists(path):
                    return wx.Bitmap(path, wx.BITMAP_TYPE_PNG)
        else:
            return self.GetFileBitmap(bmp_id)

        return wx.NullBitmap

    def GetFileBitmap(self, bmp_id):
        """Get a mime type bitmap from the theme
        @param bmp_id: Id of filetype bitmap to look up
        @see: L{syntax.synglob}

        """
        path = self.__GetArtPath(wx.ART_MENU, mime=True)
        if path is not None and bmp_id in SYNTAX_IDS:
            if bmp_id in MIME_ART:
                req = path + MIME_ART[bmp_id]
                if os.path.exists(req):
                    return wx.Bitmap(req, wx.BITMAP_TYPE_PNG)

            # Try to fall back to bmp for plain text when above is not found
            bkup = path + MIME_ART[synglob.ID_LANG_TXT]
            if os.path.exists(bkup):
                return wx.Bitmap(bkup, wx.BITMAP_TYPE_PNG)

        return wx.NullBitmap

    def GetOtherBitmap(self, bmp_id):
        """Get a other catagory bitmap.
        @param bmp_id: Id of art resource

        """
        if bmp_id in ART:
            path = self.__GetArtPath(wx.ART_OTHER, mime=False)
            if path is not None:
                path = path + ART[bmp_id]
                if os.path.exists(path):
                    return wx.Bitmap(path, wx.BITMAP_TYPE_PNG)

        return wx.NullBitmap

    def GetToolbarBitmap(self, bmp_id):
        """Get a toolbar bitmap
        @param bmp_id: Id of bitmap to look for
        @return: wx.NullBitmap or a 32x32 bitmap

        """
        if bmp_id in ART:
            #            size = Profile_Get('ICON_SZ', default=(24, 24))
            path = self.__GetArtPath(wx.ART_TOOLBAR, mime=False)
            if path is not None:
                #                tpath = os.path.join(path, '24', ART[bmp_id])
                #                if size[0] == 24 and os.path.exists(tpath):
                #                    path = tpath
                #                else:
                path = path + ART[bmp_id]

                if os.path.exists(path):
                    return wx.Bitmap(path, wx.BITMAP_TYPE_PNG)

        return wx.NullBitmap
Example #28
0
class TangoTheme(plugin.Plugin):
    """Represents the Nuovo Icon theme for Editra"""
    plugin.Implements(ThemeI)

    def __GetArtPath(self, client, mime=False):
        """Gets the path of the resource directory to get
        the bitmaps from.
        @return: path of art resource
        @rtype: string

        """
        clients = {wx.ART_MENU: u"menu", wx.ART_TOOLBAR: u"toolbar"}
        if ed_glob.CONFIG['THEME_DIR'] == u'':
            theme = util.ResolvConfigDir(os.path.join("pixmaps", "theme"))
            ed_glob.CONFIG['THEME_DIR'] = theme

        if mime:
            path = ed_glob.CONFIG['THEME_DIR'] + util.GetPathChar() + \
                   Profile_Get('ICONS') + util.GetPathChar() + \
                   u'mime' + util.GetPathChar()
        else:
            path = ed_glob.CONFIG['THEME_DIR'] + util.GetPathChar() + \
                   Profile_Get('ICONS') + util.GetPathChar() + \
                   clients.get(client, u"menu") + util.GetPathChar()

        if os.path.exists(path):
            return path
        else:
            return None

    def GetName(self):
        return u'Tango'

    def GetMenuBitmap(self, bmp_id):
        if ART.has_key(bmp_id):
            path = self.__GetArtPath(wx.ART_MENU, mime=False)
            if path is not None:
                path = path + ART[bmp_id]
                if os.path.exists(path):
                    return wx.Bitmap(path, wx.BITMAP_TYPE_PNG)
        else:
            return self.GetFileBitmap(bmp_id)

        return wx.NullBitmap

    def GetFileBitmap(self, bmp_id):
        path = self.__GetArtPath(wx.ART_MENU, mime=True)
        if path is not None and bmp_id in SyntaxIds():
            if MIME_ART.has_key(bmp_id):
                req = path + MIME_ART[bmp_id]
                if os.path.exists(req):
                    return wx.Bitmap(req, wx.BITMAP_TYPE_PNG)

            # Try to fall back to bmp for plain text when above is not found
            bkup = path + MIME_ART[synglob.ID_LANG_TXT]
            if os.path.exists(bkup):
                return wx.Bitmap(bkup, wx.BITMAP_TYPE_PNG)

        return wx.NullBitmap

    def GetToolbarBitmap(self, bmp_id):
        if ART.has_key(bmp_id):
            path = self.__GetArtPath(wx.ART_TOOLBAR, mime=False)
            if path is not None:
                path = path + ART[bmp_id]
                if os.path.exists(path):
                    return wx.Bitmap(path, wx.BITMAP_TYPE_PNG)

        return wx.NullBitmap
class CodeTemplater(plugin.Plugin):
    """Adds an interface to add Code Templates"""
    plugin.Implements(iface.MainWindowI)
    templates = {}
    currentlang = synglob.ID_LANG_TXT

    def PlugIt(self, parent):
        """Implements MainWindowI's PlugIt Method"""
        self._log = wx.GetApp().GetLog()
        self._log("[codetemplater][info] Starting codetemplater")

        self.templates = load_templates()

        self.currentlang = synglob.ID_LANG_TXT

        self.templatemenu = submenu = EdMenu()

        popupshortcut = Profile_Get(PROFILE_KEY_POPUP)

        submenu.Append(ID_SHOW_TEMPLATES,
                       _("Show Code Templates") + u'\t' + popupshortcut)
        submenu.AppendSeparator()
        submenu.Append(
            ID_EDIT_TEMPLATES, _("Edit Templates..."),
            _("Open a Dialog to Edit the Templates Currently in Use"))

        toolmenu = parent.GetMenuBar().GetMenuByName("tools")
        toolmenu.AppendSubMenu(submenu, _("Code Templates"),
                               _("Insert Code Templates into Document"))

        Subscribe(self.OnTemplate, EDMSG_UI_STC_USERLIST_SEL)
        Subscribe(self.OnLexerChange, EDMSG_UI_STC_LEXER)
        Subscribe(self.OnPageChange, EDMSG_UI_NB_CHANGED)

        self._log("[codetemplater][info] Finished loading codetemplater")

    def GetMenuHandlers(self):
        return [(ID_EDIT_TEMPLATES, self.OnEdit),
                (ID_SHOW_TEMPLATES, self.OnShow)]

    def GetUIHandlers(self):
        return []

    def OnShow(self, evt):
        if evt.GetId() == ID_SHOW_TEMPLATES:
            lst = self.templates[self.currentlang].keys()

            if len(lst) == 0:
                self._log(
                    "[codetemplater][info] Tried to show template list, but no templates present"
                )
            else:
                lst.sort()
                self._log("[codetemplater][info] Showing template list: " +
                          u','.join(lst))
                cbuff = wx.GetApp().GetCurrentBuffer()
                oldsep = cbuff.AutoCompGetSeparator()
                try:
                    cbuff.AutoCompSetSeparator(ord(u'\n'))
                    cbuff.UserListShow(1, u'\n'.join(lst))
                except wx.PyAssertionError, msg:
                    self._log(
                        "[codetemplater][err] Fail to show user list: %s" %
                        str(msg))
                finally:
                    cbuff.AutoCompSetSeparator(oldsep)
Example #30
0
class EdBookmarks(plugin.Plugin):
    """Shelf interface implementation for the bookmark manager"""
    plugin.Implements(iface.ShelfI)

    __name__ = u'Bookmarks'

    @staticmethod
    def AllowMultiple():
        """EdBookmark only allows one instance"""
        return False

    @staticmethod
    def CreateItem(parent):
        """Returns a bookmark panel"""
        return BookmarkWindow(parent)

    def GetBitmap(self):
        """Get the log viewers tab icon
        @return: wx.Bitmap

        """
        bmp = wx.ArtProvider.GetBitmap(str(ed_glob.ID_ADD_BM), wx.ART_MENU)
        return bmp

    @staticmethod
    def GetId():
        """Plugin menu identifier ID"""
        return ed_glob.ID_BOOKMARK_MGR

    @staticmethod
    def GetMenuEntry(menu):
        """Get the menu entry for the bookmark viewer
        @param menu: the menu items parent menu

        """
        item = wx.MenuItem(menu, ed_glob.ID_BOOKMARK_MGR, _("Bookmarks"),
                           _("View all bookmarks"))
        bmp = wx.ArtProvider.GetBitmap(str(ed_glob.ID_ADD_BM), wx.ART_MENU)
        item.SetBitmap(bmp)
        return item

    def GetName(self):
        """Return the name of this control"""
        return self.__name__

    @staticmethod
    def IsStockable():
        """EdBookmark can be saved in the shelf preference stack"""
        return True

    # Bookmark storage
    _marks = list()

    @classmethod
    def OnStoreBM(cls, msg):
        data = msg.GetData()
        buf = data.get('stc')
        line = data.get('line')
        mark = Bookmark()
        mark.Filename = buf.GetFileName()
        mark.Line = line
        if data.get('added', False):
            if mark not in cls._marks:
                # Store the stc bookmark handle
                mark.Handle = data.get('handle', None)
                # Store an alias for the bookmark
                name = u""
                cline = buf.GetCurrentLine()
                if line == cline:
                    name = buf.GetSelectedText()
                if not name:
                    name = buf.GetLine(line)
                mark.Name = name.strip()
                cls._marks.append(mark)
        else:
            if mark in cls._marks:
                idx = cls._marks.index(mark)
                cls._marks.pop(idx)

    @classmethod
    def GetMarks(cls):
        return cls._marks