def OnAddPyExe(self, event):
     """Handle adding new item"""
     config = Profile_Get(PYTOOL_CONFIG, default=dict())
     curpy = config.get(TLC_PYTHON_PATH, u'')
     cdir = ebmlib.GetPathName(curpy)
     cfile = ebmlib.GetFileName(curpy)
     dlg = wx.FileDialog(self, _("Select Python Executable"), cdir, cfile,
                         style=wx.FD_OPEN|wx.FD_CHANGE_DIR|wx.FD_FILE_MUST_EXIST)
     dlg.CenterOnParent()
     result = dlg.ShowModal()
     path = dlg.Path
     dlg.Destroy()
     if result != wx.ID_OK:
         return
     if path and os.path.exists(path):
         allpy = config.get(TLC_ALL_PYTHON_PATHS, [])
         if path not in allpy:
             # Update collection of paths
             allpy.append(path)
             allpy.sort()
             config[TLC_ALL_PYTHON_PATHS] = allpy
             # Update Choice control and current selection
             self._python_path_combo.Items = allpy
             self._python_path_combo.StringSelection = path
             # Update current python to the newly added one
             config[TLC_PYTHON_PATH] = path
             Profile_Set(PYTOOL_CONFIG, config)
    def __init__(self, parent):
        super(LintConfigPanel, self).__init__(parent)

        # Attributes
        config = Profile_Get(PYTOOL_CONFIG, default=dict())
        modebox = wx.StaticBox(self, label=_("Lint Run Mode"))
        self._lintmodesz = wx.StaticBoxSizer(modebox, wx.VERTICAL)
        self._lintautorb = wx.RadioButton(self, label=_("Automatic"), style=wx.RB_GROUP)
        tooltip = _("Automatically rerun on save, document change, and file load")
        self._lintautorb.SetToolTipString(tooltip)
        self._lintmanualrb = wx.RadioButton(self, label=_("Manual"))
        tooltip = _("Only run when requested")
        self._lintmanualrb.SetToolTipString(tooltip)
        mode = config.get(TLC_LINT_AUTORUN, False)
        self._lintautorb.SetValue(mode)
        self._lintmanualrb.SetValue(not mode)

        ## Message configuration
        msgbox = wx.StaticBox(self, label=_("PyLint Checkers"))
        self._msgsz = wx.StaticBoxSizer(msgbox, wx.VERTICAL)
        self._msgtype = wx.Choice(self, choices=_GetPyLintMessageTypes())
        self._msglst = MessageIDList(self, style=wx.LC_REPORT)

        # Setup
        self._msglst.SetConfig(config)
        self._msgtype.SetSelection(0)
        self.UpdateListCtrl()
        self.__DoLayout()

        # Event Handlers
        self.Bind(wx.EVT_CHOICE, self.OnChoice, self._msgtype)
        self.Bind(wx.EVT_RADIOBUTTON, self.OnRunModeCheckBox, self._lintautorb)
        self.Bind(wx.EVT_RADIOBUTTON, self.OnRunModeCheckBox, self._lintmanualrb)
Example #3
0
    def GetStyleSheet(sheet_name=None):
        """Finds the current style sheet and returns its path. The
        Lookup is done by first looking in the users config directory
        and if it is not found there it looks for one on the system
        level and if that fails it returns None.
        @param sheet_name: style sheet to look for
        @return: full path to style sheet

        """
        if sheet_name:
            style = sheet_name
            if sheet_name.split(u'.')[-1] != u"ess":
                style += u".ess"
        elif Profile_Get('SYNTHEME', 'str').split(u'.')[-1] != u"ess":
            style = (Profile_Get('SYNTHEME', 'str') + u".ess").lower()
        else:
            style = Profile_Get('SYNTHEME', 'str').lower()

        # Get Correct Filename if it exists
        for sheet in util.GetResourceFiles(u'styles', False, True, title=False):
            if sheet.lower() == style.lower():
                style = sheet
                break

        user = os.path.join(ed_glob.CONFIG['STYLES_DIR'], style)
        sysp = os.path.join(ed_glob.CONFIG['SYS_STYLES_DIR'], style)
        if os.path.exists(user):
            return user
        elif os.path.exists(sysp):
            return sysp
        else:
            return None
Example #4
0
    def __init__(self, parent):
        eclib.ControlBox.__init__(self, parent)

        # Attributes
        self._log = wx.GetApp().GetLog()
        self._mw = self.__FindMainWindow()
        self._buffer = OutputDisplay(self)
        self._fnames = list()
        self._chFiles = None # Created in __DoLayout
        self._worker = None
        self._busy = False
        self._isready = False
        self._config = dict(file='', lang=0,
                            cfile='', clang=0,
                            last='', lastlang=0,
                            prelang=0, largs='',
                            lcmd='')
        self._prefs = Profile_Get(cfgdlg.LAUNCH_PREFS, default=None)

        # Setup
        self.__DoLayout()
        hstate = Profile_Get(LAUNCH_KEY)
        if hstate is not None:
            handlers.SetState(hstate)
        if self._prefs is None:
            Profile_Set(cfgdlg.LAUNCH_PREFS,
                        dict(autoclear=False,
                             defaultf=self._buffer.GetDefaultForeground().Get(),
                             defaultb=self._buffer.GetDefaultBackground().Get(),
                             errorf=self._buffer.GetErrorForeground().Get(),
                             errorb=self._buffer.GetErrorBackground().Get(),
                             infof=self._buffer.GetInfoForeground().Get(),
                             infob=self._buffer.GetInfoBackground().Get(),
                             warnf=self._buffer.GetWarningForeground().Get(),
                             warnb=self._buffer.GetWarningBackground().Get()))
            self._prefs = Profile_Get(cfgdlg.LAUNCH_PREFS)

        self.UpdateBufferColors()
        cbuffer = self._mw.GetNotebook().GetCurrentCtrl()
        self.SetupControlBar(cbuffer)
        self._config['lang'] = GetLangIdFromMW(self._mw)
        self.UpdateCurrentFiles(self._config['lang'])
        self.SetFile(GetTextBuffer(self._mw).GetFileName())

        # Setup filetype settings
        self.RefreshControlBar()

        # Event Handlers
        self.Bind(wx.EVT_BUTTON, self.OnButton)
        self.Bind(wx.EVT_CHOICE, self.OnChoice)
        ed_msg.Subscribe(self.OnPageChanged, ed_msg.EDMSG_UI_NB_CHANGED)
        ed_msg.Subscribe(self.OnFileOpened, ed_msg.EDMSG_FILE_OPENED)
        ed_msg.Subscribe(self.OnThemeChanged, ed_msg.EDMSG_THEME_CHANGED)
        ed_msg.Subscribe(self.OnLexerChange, ed_msg.EDMSG_UI_STC_LEXER)
        ed_msg.Subscribe(self.OnConfigExit, cfgdlg.EDMSG_LAUNCH_CFG_EXIT)
        ed_msg.Subscribe(self.OnRunMsg, MSG_RUN_LAUNCH)
        ed_msg.Subscribe(self.OnRunLastMsg, MSG_RUN_LAST)
        ed_msg.RegisterCallback(self._CanLaunch, REQUEST_ACTIVE)
        ed_msg.RegisterCallback(self._CanReLaunch, REQUEST_RELAUNCH)
Example #5
0
def GetUserSettings(name):
    """Get the user settings for a given file type
    @param name: file type name

    """
    data = Profile_Get(CONFIG_KEY, default=dict())
    val = data.get(name, tuple())
    return val
Example #6
0
    def __init__(self, parent):
        super(SearchBar, self).__init__(parent)

        # Attributes
        self.SetControl(ed_search.EdSearchCtrl(self, wx.ID_ANY, menulen=5, size=(180, -1)))
        self._sctrl = self.ctrl.GetSearchController()

        # Setup
        f_lbl = wx.StaticText(self, label=_("Find") + u": ")
        t_bmp = wx.ArtProvider.GetBitmap(str(ed_glob.ID_DOWN), wx.ART_MENU)
        next_btn = eclib.PlateButton(self, ID_SEARCH_NEXT, _("Next"), t_bmp, style=eclib.PB_STYLE_NOBG, name="NextBtn")
        self.AddControl(f_lbl, wx.ALIGN_LEFT)
        self.AddControl(self.ctrl, wx.ALIGN_LEFT)
        self.AddControl(next_btn, wx.ALIGN_LEFT)

        t_bmp = wx.ArtProvider.GetBitmap(str(ed_glob.ID_UP), wx.ART_MENU)
        pre_btn = eclib.PlateButton(self, ID_SEARCH_PRE, _("Previous"), t_bmp, style=eclib.PB_STYLE_NOBG, name="PreBtn")
        self.AddControl(pre_btn, wx.ALIGN_LEFT)

        t_bmp = wx.ArtProvider.GetBitmap(str(ed_glob.ID_FIND), wx.ART_MENU)
        fa_btn = eclib.PlateButton(
            self, ID_FIND_ALL, _("Find All"), t_bmp, style=eclib.PB_STYLE_NOBG, name="FindAllBtn"
        )
        self.AddControl(fa_btn)
        fa_btn.Show(False)  # Hide this button by default

        match_case = wx.CheckBox(self, ID_MATCH_CASE, _("Match Case"), name="MatchCase")
        match_case.SetValue(self.ctrl.IsMatchCase())
        self.AddControl(match_case, wx.ALIGN_LEFT)
        match_case.Show(False)  # Hide by default

        ww_cb = wx.CheckBox(self, ID_WHOLE_WORD, _("Whole Word"), name="WholeWord")
        ww_cb.SetValue(self.ctrl.IsWholeWord())
        self.AddControl(ww_cb, wx.ALIGN_LEFT)

        regex_cb = wx.CheckBox(self, ID_REGEX, _("Regular Expression"), name="RegEx")
        regex_cb.SetValue(self.ctrl.IsRegEx())
        self.AddControl(regex_cb, wx.ALIGN_LEFT)

        # HACK: workaround bug in mac control that resets size to
        #       that of the default variant after any text has been
        #       typed in it. Note it reports the best size as the default
        #       variant and causes layout issues. wxBUG
        if wx.Platform == "__WXMAC__":
            self.ctrl.SetSizeHints(180, 16, 180, 16)

        # Event Handlers
        self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
        self.Bind(wx.EVT_BUTTON, self.OnButton)
        self.Bind(wx.EVT_CHECKBOX, self.OnCheck)
        ed_msg.Subscribe(self.OnThemeChange, ed_msg.EDMSG_THEME_CHANGED)
        self._sctrl.RegisterClient(self)

        # Set user customizable layout
        state = Profile_Get("CTRLBAR", default=dict())
        cfg = state.get(self.GetConfigKey(), dict())
        self.SetControlStates(cfg)
Example #7
0
def GetUserSettings(name):
    """Get the user settings for a given file type
    @param name: file type name

    """
    data = Profile_Get("Launch.Config", default=dict())
    for key, val in data.iteritems():
        if key.lower() == name.lower():
            return val
    return tuple()
Example #8
0
 def StoreState(cls):
     """Store the state of this handler"""
     if cls.meta.transient:
         util.Log("[Launch][info] Transient XML handler: settings will not persist")
         # TODO: update XML configuration file?
         return
     data = Profile_Get(CONFIG_KEY, default=dict())
     cdata = data.get(cls.GetName(), None)
     if data != cdata:
         util.Log("[Launch][info] Store config: %s" % cls.GetName())
         data[cls.GetName()] = (cls.meta.default, cls.meta.commands.items())
         Profile_Set(CONFIG_KEY, data)
Example #9
0
    def __init__(self, parent, id_=wx.ID_ANY, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=0, use_dt=True):
        """Initialize the editor view"""
        ed_stc.EditraStc.__init__(self, parent, id_, pos, size, style, use_dt)
        ed_tab.EdTabBase.__init__(self)

        # Attributes
        self._ro_img = False
        self._ignore_del = False
        self._has_dlg = False
        self._lprio = 0     # Idle event priority counter
        self._menu = ContextMenuManager()
        self._spell = STCSpellCheck(self, check_region=self.IsNonCode)
        self._caret_w = 1
        self._focused = True
        spref = Profile_Get('SPELLCHECK', default=dict())
        self._spell_data = dict(choices=list(),
                                word=('', -1, -1),
                                enabled=spref.get('auto', False))

        # Initialize the classes position manager for the first control
        # that is created only.
        if not EdEditorView.DOCMGR.IsInitialized():
            EdEditorView.DOCMGR.InitPositionCache(ed_glob.CONFIG['CACHE_DIR'] + \
                                                  os.sep + u'positions')

        self._spell.clearAll()
        self._spell.setDefaultLanguage(spref.get('dict', 'en_US'))
        self._spell.startIdleProcessing()

        # Context Menu Events
        self.Bind(wx.EVT_CONTEXT_MENU, self.OnContextMenu)

        # Need to relay the menu events from the context menu to the top level
        # window to be handled on gtk. Other platforms don't require this.
        self.Bind(wx.EVT_MENU, self.OnMenuEvent)

        # Hide autocomp/calltips when window looses focus
        # TODO: decide on whether this belongs in base class or not
        self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
        self.Bind(wx.EVT_LEFT_UP, self.OnSetFocus)
        self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy, self)

        # Subscribe for configuration updates
        for opt in ('AUTOBACKUP', 'SYNTHEME', 'SYNTAX', 'BRACKETHL', 'GUIDES',
                    'SHOW_EDGE', 'EDGE', 'CODE_FOLD', 'AUTO_COMP',
                    'AUTO_INDENT', 'HLCARETLINE', 'SPELLCHECK', 'VI_EMU',
                    'VI_NORMAL_DEFAULT', 'USETABS', 'TABWIDTH', 'INDENTWIDTH',
                    'BSUNINDENT', 'EOL_MODE', 'AALIASING', 'SHOW_EOL', 'SHOW_LN',
                    'SHOW_WS', 'WRAP', 'VIEWVERTSPACE'):
            ed_msg.Subscribe(self.OnConfigMsg,
                             ed_msg.EDMSG_PROFILE_CHANGE + (opt,))
Example #10
0
 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)
Example #11
0
 def OnRemovePyExe(self, event):
     """Remove an executable from the configuration"""
     csel = self._python_path_combo.StringSelection
     config = Profile_Get(PYTOOL_CONFIG, default=dict())
     allpy = config.get(TLC_ALL_PYTHON_PATHS, [])
     if csel and csel in allpy:
         allpy.remove(csel)
         config[TLC_ALL_PYTHON_PATHS] = allpy
         self._python_path_combo.Items = allpy
         nsel = u''
         if len(allpy):
             nsel = allpy[0]
             self._python_path_combo.StringSelection = nsel
         config[TLC_PYTHON_PATH] = nsel
Example #12
0
    def __GetCurrentProvider(self):
        """Gets the provider of the current theme resources
        @return: ThemeI object

        """
        theme = Profile_Get("ICONS", "str", u"")
        for prov in self.observers:
            if theme == prov.GetName():
                return prov

        # Case if a theme was deleted while it was the active theme
        if theme.lower() != u"default":
            Profile_Set("ICONS", u"Default")

        return None
Example #13
0
    def __GetCurrentProvider(self):
        """Gets the provider of the current theme resources
        @return: ThemeI object

        """
        theme = Profile_Get('ICONS', 'str', u'')
        for prov in self.observers:
            if theme == prov.GetName():
                return prov

        # Case if a theme was deleted while it was the active theme
        if theme.lower() != u'default':
            Profile_Set('ICONS', u'Default')

        return None
Example #14
0
    def __init__(self, parent):
        ctrlbox.ControlBox.__init__(self, parent)

        # Attributes
        self._mw = self.__FindMainWindow()
        self._buffer = OutputDisplay(self)
        self._fnames = list()
        self._chFiles = None # Created in __DoLayout
        self._worker = None
        self._busy = False
        self._isready = False
        self._config = dict(file='', lang=0,
                            cfile='', clang=0,
                            last='', lastlang=0,
                            prelang=0)
        self._prefs = Profile_Get('Launch.Prefs', default=None)

        # Setup
        self.__DoLayout()
        hstate = Profile_Get(LAUNCH_KEY)
        if hstate is not None:
            handlers.SetState(hstate)
        if self._prefs is None:
            Profile_Set('Launch.Prefs',
                        dict(autoclear=False,
                             defaultf=self._buffer.GetDefaultForeground().Get(),
                             defaultb=self._buffer.GetDefaultBackground().Get(),
                             errorf=self._buffer.GetErrorForeground().Get(),
                             errorb=self._buffer.GetErrorBackground().Get(),
                             infof=self._buffer.GetInfoForeground().Get(),
                             infob=self._buffer.GetInfoBackground().Get(),
                             warnf=self._buffer.GetWarningForeground().Get(),
                             warnb=self._buffer.GetWarningBackground().Get()))
            self._prefs = Profile_Get('Launch.Prefs')

        self.UpdateBufferColors()
        cbuffer = self._mw.GetNotebook().GetCurrentCtrl()
        self.SetupControlBar(cbuffer)

        # Event Handlers
        self.Bind(wx.EVT_BUTTON, self.OnButton)
        self.Bind(wx.EVT_CHOICE, self.OnChoice)
        ed_msg.Subscribe(self.OnPageChanged, ed_msg.EDMSG_UI_NB_CHANGED)
        ed_msg.Subscribe(self.OnFileOpened, ed_msg.EDMSG_FILE_OPENED)
        ed_msg.Subscribe(self.OnThemeChanged, ed_msg.EDMSG_THEME_CHANGED)
        ed_msg.Subscribe(self.OnConfigExit, cfgdlg.EDMSG_LAUNCH_CFG_EXIT)
        ed_msg.Subscribe(self.OnRunMsg, MSG_RUN_LAUNCH)
        ed_msg.RegisterCallback(self._CanLaunch, REQUEST_ACTIVE)
Example #15
0
 def OnUninstallButton(self, evt):
     """Uninstall the plugin"""
     msg = _("Are you sure you want to uninstall %s?\nThis cannot be undone.")
     result = wx.MessageBox(msg % self.GetPluginName(), _("Uninstall Plugin"), wx.OK | wx.CANCEL | wx.ICON_WARNING)
     if result == wx.OK:
         self.Enable(False)
         self._desc.SetLabel(_("This plugin will be uninstalled on next program launch."))
         self._enabled.SetValue(False)
         pname = self._title.GetLabel()
         event = ed_event.NotificationEvent(ed_event.edEVT_NOTIFY, self.GetId(), (pname, False), self)
         wx.PostEvent(self.GetParent(), event)
         plist = Profile_Get("UNINSTALL_PLUGINS", default=list())
         plist.append(self.GetInstallPath())
         Profile_Set("UNINSTALL_PLUGINS", plist)
     else:
         return
Example #16
0
    def __init__(self, parent, id_=wx.ID_ANY, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=0, use_dt=True):
        """Initialize the editor view"""
        ed_stc.EditraStc.__init__(self, parent, id_, pos, size, style, use_dt)
        ed_tab.EdTabBase.__init__(self)

        # Attributes
        self._ignore_del = False
        self._has_dlg = False
        self._lprio = 0     # Idle event priority counter
        self._menu = ContextMenuManager()
        self._spell = STCSpellCheck(self, check_region=self.IsNonCode)
        spref = Profile_Get('SPELLCHECK', default=dict())
        self._spell_data = dict(choices=list(),
                                word=('', -1, -1),
                                enabled=spref.get('auto', False))

        # Initialize the classes position manager for the first control
        # that is created only.
        if not EdEditorView.DOCMGR.IsInitialized():
            EdEditorView.DOCMGR.InitPositionCache(ed_glob.CONFIG['CACHE_DIR'] + \
                                                  os.sep + u'positions')

        self._spell.clearAll()
        self._spell.setDefaultLanguage(spref.get('dict', 'en_US'))
        self._spell.startIdleProcessing()

        # Context Menu Events
        self.Bind(wx.EVT_CONTEXT_MENU, self.OnContextMenu)

        # Need to relay the menu events from the context menu to the top level
        # window to be handled on gtk. Other platforms don't require this.
        self.Bind(wx.EVT_MENU, self.OnMenuEvent)

        # Hide autocomp/calltips when window looses focus
        # TODO: decide on whether this belongs in base class or not
        self.Bind(wx.EVT_KILL_FOCUS, lambda evt: self.HidePopups())
        self.Bind(wx.EVT_LEFT_UP, self.OnSetFocus)

        ed_msg.Subscribe(self.OnConfigMsg,
                         ed_msg.EDMSG_PROFILE_CHANGE + ('SPELLCHECK',))
        ed_msg.Subscribe(self.OnConfigMsg,
                         ed_msg.EDMSG_PROFILE_CHANGE + ('AUTOBACKUP',))
        ed_msg.Subscribe(self.OnConfigMsg,
                         ed_msg.EDMSG_PROFILE_CHANGE + ('SYNTHEME',))
        ed_msg.Subscribe(self.OnConfigMsg,
                         ed_msg.EDMSG_PROFILE_CHANGE + ('SYNTAX',))
Example #17
0
 def OnCheck(self, evt):
     """Handle checkbox events"""
     e_id = evt.GetId()
     e_val = evt.GetEventObject().GetValue()
     cfg = Profile_Get(LAUNCH_PREFS, default=dict())
     if e_id == ID_AUTOCLEAR:
         cfg['autoclear'] = e_val
     else:
         evt.Skip()
Example #18
0
    def __init__(self, parent, id_num):
        """Initialize a notebook with a blank text control in it
        @param parent: parent window of the notebook
        @param id_num: this notebooks id

        """
        FNB.FlatNotebook.__init__(
            self,
            parent,
            id_num,
            style=FNB.FNB_FF2 | FNB.FNB_X_ON_TAB | FNB.FNB_SMART_TABS
            | FNB.FNB_BACKGROUND_GRADIENT | FNB.FNB_DROPDOWN_TABS_LIST
            | FNB.FNB_ALLOW_FOREIGN_DND)

        # Notebook attributes
        self.LOG = wx.GetApp().GetLog()
        self.DocMgr = ed_editv.EdEditorView.DOCMGR
        self._searchctrl = ed_search.SearchController(self,
                                                      self.GetCurrentCtrl)
        self._searchctrl.SetLookinChoices(
            Profile_Get('SEARCH_LOC', default=list()))
        self.pg_num = -1  # Track new pages (aka untitled docs)
        self.control = None
        self.frame = self.GetTopLevelParent()  # MainWindow
        self._index = dict()  # image list index
        self._ses_load = False
        self._menu = None

        # Set Additional Style Parameters
        self.SetNonActiveTabTextColour(wx.Colour(102, 102, 102))
        ed_icon = ed_glob.CONFIG['SYSPIX_DIR'] + u"editra.png"
        self.SetNavigatorIcon(wx.Bitmap(ed_icon, wx.BITMAP_TYPE_PNG))

        # Setup the ImageList and the default image
        imgl = wx.ImageList(16, 16)
        txtbmp = wx.ArtProvider.GetBitmap(str(synglob.ID_LANG_TXT),
                                          wx.ART_MENU)
        self._index[synglob.ID_LANG_TXT] = imgl.Add(txtbmp)
        self.SetImageList(imgl)

        # Notebook Events
        self.Bind(FNB.EVT_FLATNOTEBOOK_PAGE_CHANGING, self.OnPageChanging)
        self.Bind(FNB.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
        self.Bind(FNB.EVT_FLATNOTEBOOK_PAGE_CLOSING, self.OnPageClosing)
        self.Bind(FNB.EVT_FLATNOTEBOOK_PAGE_CLOSED, self.OnPageClosed)
        self.Bind(wx.stc.EVT_STC_MODIFIED, self.OnUpdatePageText)
        self._pages.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
        self.Bind(FNB.EVT_FLATNOTEBOOK_PAGE_CONTEXT_MENU, self.OnTabMenu)
        self.Bind(wx.EVT_MENU, self.OnCopyTabPath, id=ed_glob.ID_COPY_PATH)
        self.Bind(wx.EVT_IDLE, self.OnIdle)

        # Message handlers
        ed_msg.Subscribe(self.OnThemeChanged, ed_msg.EDMSG_THEME_CHANGED)
        ed_msg.Subscribe(self.OnThemeChanged, ed_msg.EDMSG_THEME_NOTEBOOK)

        # Add a blank page
        self.NewPage()
Example #19
0
    def InitPositionCache(self, book_path):
        """Initialize and load the on disk document position cache.
        @param book_path: path to on disk cache

        """
        self._init = True
        self._book = book_path
        if Profile_Get('SAVE_POS'):
            self.LoadBook(book_path)
Example #20
0
 def SaveCurrentSession(self):
     """Save the current session"""
     session = Profile_Get('LAST_SESSION')
     # Compatibility with older session data
     if not isinstance(session, basestring) or not len(session):
         session = os.path.join(ed_glob.CONFIG['SESSION_DIR'], 
                                u"__default.session")
         Profile_Set('LAST_SESSION', session)
     self.SaveSessionFile(session)
Example #21
0
    def __init__(self, auimgr, base):
        """Initializes the perspective manager. The auimgr parameter is
        a reference to the windows AuiManager instance, base is the base
        path to where perspectives should be loaded from and saved to.
        @param auimgr: AuiManager to use
        @param base: path to configuration cache

        """
        object.__init__(self)

        # Attributes
        self._window = auimgr.GetManagedWindow()    # Managed Window
        self._mgr = auimgr                          # Window Manager
        self._ids = list()                          # List of menu ids
        self._base = os.path.join(base, DATA_FILE)  # Path to config
        self._viewset = dict()                      # Set of Views
        self.LoadPerspectives()
        self._menu = ed_menu.EdMenu()               # Control menu
        self._currview = Profile_Get('DEFAULT_VIEW')    # Currently used view

        # Setup Menu
        self._menu.Append(ID_SAVE_PERSPECTIVE, _("Save Current View"),
                    _("Save the current window layout"))
        self._menu.Append(ID_DELETE_PERSPECTIVE, _("Delete Saved View"))
        self._menu.AppendSeparator()
        self._menu.Append(ID_AUTO_PERSPECTIVE, _(AUTO_PERSPECTIVE),
                          _("Automatically save/use window state from last session"),
                          wx.ITEM_CHECK)
        self._menu.AppendSeparator()
        for name in self._viewset:
            self.AddPerspectiveMenuEntry(name)

        # Restore the managed windows previous position preference if available.
        pos = Profile_Get('WPOS', "size_tuple", False)
        if Profile_Get('SET_WPOS') and pos:
            # Ensure window is on screen
            # NOTE: don't default to 0,0 otherwise on osx the frame will be
            #       stuck behind the menubar.
            if pos[0] < 0 or pos[1] < 0:
                pos = (100, 100)
            self._window.SetPosition(pos)

        # Event Handlers
        self._window.Bind(wx.EVT_MENU, self.OnPerspectiveMenu)
Example #22
0
    def Init(self, parent):
        """Mixes the shelf into the parent window
        @param parent: Reference to MainWindow

        """
        # First check if the parent has an instance already
        parent = parent
        mgr = parent.GetFrameManager()
        if mgr.GetPane(Shelf.SHELF_NAME).IsOk():
            return

        shelf = EdShelfBook(parent)
        mgr.AddPane(shelf,
                    wx.aui.AuiPaneInfo().Name(Shelf.SHELF_NAME).\
                            Caption("Shelf").Bottom().Layer(0).\
                            CloseButton(True).MaximizeButton(False).\
                            BestSize(wx.Size(500,250)))

        # Hide the pane and let the perspective manager take care of it
        mgr.GetPane(Shelf.SHELF_NAME).Hide()
        mgr.Update()

        # Create the delegate
        # Parent MUST take ownership and clear the class variable before
        # another call to Init is made.
        delegate = EdShelfDelegate(shelf, self)
        assert Shelf.delegate is None, "Delegate not cleared!"
        Shelf.delegate = delegate

        # Install Shelf menu under View and bind event handlers
        view = parent.GetMenuBar().GetMenuByName("view")
        menu = delegate.GetMenu()
        pos = 0
        for pos in xrange(view.GetMenuItemCount()):
            mitem = view.FindItemByPosition(pos)
            if mitem.GetId() == ed_glob.ID_PERSPECTIVES:
                break

        view.InsertMenu(pos + 1, ed_glob.ID_SHELF, _("Shelf"), menu,
                        _("Put an item on the Shelf"))

        for item in menu.GetMenuItems():
            if item.IsSeparator():
                continue
            parent.Bind(wx.EVT_MENU, delegate.OnGetShelfItem, item)

        if menu.GetMenuItemCount() < 3:
            view.Enable(ed_glob.ID_SHELF, False)

        # Check for any other plugin specific install needs
        for observer in self.observers:
            if not observer.IsInstalled() and \
               hasattr(observer, 'InstallComponents'):
                observer.InstallComponents(parent)

        delegate.StockShelf(Profile_Get('SHELF_ITEMS', 'list', []))
Example #23
0
def init_locale():
    """
    Initialize the Language Settings.
    """
    the_locale = wx.Locale(ed_i18n.GetLangId(Profile_Get('LANG')))
    if the_locale.GetCanonicalName() in ed_i18n.GetAvailLocales():
        lc = ed_glob.CONFIG['LANG_DIR'] + 'defis\\'
        wx.GetApp().GetLog()('----- init_locale ----- %s' % lc)
        gettext.bindtextdomain('defis', lc)
        gettext.textdomain('defis')
Example #24
0
    def __init__(self, parent):
        eclib.OutputBuffer.__init__(self, parent)

        # Attributes
        self._filter = SHOW_ALL_MSG
        self._srcs = list()
        self.SetLineBuffering(2000)

        # Setup
        font = Profile_Get('FONT1', 'font', wx.Font(11, wx.FONTFAMILY_MODERN, 
                                                    wx.FONTSTYLE_NORMAL, 
                                                    wx.FONTWEIGHT_NORMAL))
        self.SetFont(font)
        style = (font.GetFaceName(), font.GetPointSize(), "#FF0000")
        self.StyleSetSpec(LogBuffer.ERROR_STYLE,
                          "face:%s,size:%d,fore:#FFFFFF,back:%s" % style)

        # Subscribe to Editra's Log
        ed_msg.Subscribe(self.UpdateLog, ed_msg.EDMSG_LOG_ALL)
Example #25
0
    def __DoLayout(self):
        """Layout the panel"""
        sizer = wx.BoxSizer(wx.VERTICAL)
        cfg = Profile_Get(handlers.CONFIG_KEY, default=dict())

        # Editor options
        ebox = wx.StaticBox(self, label=_("Editor Options"))
        eboxsz = wx.StaticBoxSizer(ebox, wx.VERTICAL)
        lbl = _("Automatically save current file before running")
        self.savecb = wx.CheckBox(self, label=lbl)
        self.savecb.SetValue(cfg.get('autosave', False))
        lbl = _("Automatically save all open files before running")
        self.saveallcb = wx.CheckBox(self, label=lbl)
        self.saveallcb.SetValue(cfg.get('autosaveall', False))
        eboxsz.Add(self.savecb, 0, wx.ALL, 3)
        eboxsz.Add(self.saveallcb, 0, wx.ALL, 3)
        sizer.Add(eboxsz, 0, wx.EXPAND | wx.ALL, 5)

        self.SetSizer(sizer)
Example #26
0
    def __init__(self, book_path):
        """Creates the position manager object
        @param book_path: path to on disk data file

        """
        object.__init__(self)
        self._book = book_path
        self._records = dict()
        if Profile_Get('SAVE_POS'):
            self.LoadBook(book_path)
    def OnRunModeCheckBox(self, evt):
        evt_obj = evt.GetEventObject()
        config = Profile_Get(PYTOOL_CONFIG, default=dict())
        if evt_obj in (self._lintautorb, self._lintmanualrb):
            config[TLC_LINT_AUTORUN] = self._lintautorb.GetValue()
        else:
            evt.Skip()
            return

        Profile_Set(PYTOOL_CONFIG, config)
Example #28
0
    def __init__(self, parent):
        """Initialize the Shell"""
        shell.Shell.__init__(self, parent, locals=dict())

        # Get the color scheme to use
        style = Profile_Get(PYSHELL_STYLE)
        if style is None:
            style = Profile_Get('SYNTHEME')

        ed_style.StyleMgr.__init__(self, self.GetStyleSheet(style))

        # Attributes
        self.SetStyleBits(5)
        self._shell_style = style
        mgr = syntax.SyntaxMgr(ed_glob.CONFIG['CACHE_DIR'])
        syn_data = mgr.SyntaxData('py')
        synspec = syn_data[syntax.SYNSPEC]
        self.SetLexer(wx.stc.STC_LEX_PYTHON)
        self.SetSyntax(synspec)
Example #29
0
    def __DoLayout(self):
        """Layout the panel"""
        sizer = wx.BoxSizer(wx.VERTICAL)
        cfg = Profile_Get(LAUNCH_PREFS, default=dict())

        # Editor options
        ebox = wx.StaticBox(self, label=_("Editor Options"))
        eboxsz = wx.StaticBoxSizer(ebox, wx.VERTICAL)
        lbl = _("Automatically save current file before running")
        self.savecb = wx.CheckBox(self, label=lbl)
        self.savecb.SetValue(cfg.get('autosave', False))
        lbl = _("Automatically save all open files before running")
        self.saveallcb = wx.CheckBox(self, label=lbl)
        self.saveallcb.SetValue(cfg.get('autosaveall', False))
        eboxsz.Add(self.savecb, 0, wx.ALL, 3)
        eboxsz.Add(self.saveallcb, 0, wx.ALL, 3)
        sizer.Add(eboxsz, 0, wx.EXPAND|wx.ALL, 5)

        self.SetSizer(sizer)
Example #30
0
 def OnUninstallButton(self, evt):
     """Uninstall the plugin"""
     msg = _("Are you sure you want to uninstall %s?\nThis cannot be undone.") 
     result = wx.MessageBox(msg % self.GetPluginName(),
                            _("Uninstall Plugin"),
                            wx.OK|wx.CANCEL|wx.ICON_WARNING)
     if result == wx.OK:
         self.Enable(False)
         self._desc.SetLabel(_("This plugin will be uninstalled on next program launch."))
         self._enabled.SetValue(False)
         pname = self._title.GetLabel()
         event = ed_event.NotificationEvent(ed_event.edEVT_NOTIFY, self.GetId(),
                                            (pname, False), self)
         wx.PostEvent(self.GetParent(), event)
         plist = Profile_Get('UNINSTALL_PLUGINS', default=list())
         plist.append(self.GetInstallPath())
         Profile_Set('UNINSTALL_PLUGINS', plist)
     else:
         return
 def OnCheckBox(self, event):
     """Update checkbox linked configuration options"""
     e_obj = event.GetEventObject()
     config = Profile_Get(PYTOOL_CONFIG, default=dict())
     if e_obj is self._check_on_save_cb:
         config[TLC_COMPILE_ON_SAVE] = e_obj.Value
         Profile_Set(PYTOOL_CONFIG, config)
     elif e_obj is self._load_proj_cb:
         config[TLC_LOAD_LAST_PROJECT] = e_obj.Value
         Profile_Set(PYTOOL_CONFIG, config)
Example #32
0
    def DoPostLoad(self):
        """Perform post file open actions"""
        if Profile_Get('SAVE_POS'):
            pos = self.DocMgr.GetPos(self.control.GetFileName())
            self.control.SetCaretPos(pos)
            self.control.ScrollToColumn(0)

        ed_msg.PostMessage(ed_msg.EDMSG_FILE_OPENED,
                           self.control.GetFileName(),
                           context=self.frame.GetId())
Example #33
0
    def __init__(self, parent):
        """Initializes the toolbar
        @param parent: parent window of this toolbar

        """
        sstyle = wx.TB_HORIZONTAL | wx.NO_BORDER
        if wx.Platform == '__WXGTK__':
            sstyle = sstyle | wx.TB_DOCKABLE
        wx.ToolBar.__init__(self, parent, style=sstyle)

        # Attributes
        self._theme = Profile_Get('ICONS')
        self.SetToolBitmapSize(Profile_Get('ICON_SZ', 'size_tuple'))
        self._PopulateTools()

        # Message Handlers
        ed_msg.Subscribe(self.OnThemeChange, ed_msg.EDMSG_THEME_CHANGED)

        self.Realize()
Example #34
0
 def OnColor(self, evt):
     """Handle color change events"""
     e_id = evt.GetId()
     color = COLOR_MAP.get(e_id, None)
     cfg = Profile_Get(handlers.CONFIG_KEY, default=dict())
     if color is not None:
         cfg[color] = evt.GetValue().Get()
         Profile_Set(handlers.CONFIG_KEY, cfg)
     else:
         evt.Skip()
    def __DoLayout(self):
        sizer = wx.BoxSizer(wx.VERTICAL)

        # Python executable configuration
        config = Profile_Get(PYTOOL_CONFIG, default=dict())
        pythonpath = config.get(TLC_PYTHON_PATH, None)
        if not pythonpath:
            pythonpath = PyStudioUtils.GetDefaultPython()
        all_pythons = config.get(TLC_ALL_PYTHON_PATHS, [])
        if pythonpath:
            pythonpath = os.path.normcase(
                pythonpath
            )  #TODO: this will likely cause problems on non Windows
            config[TLC_PYTHON_PATH] = pythonpath
            if not pythonpath in all_pythons:
                all_pythons.append(pythonpath)
        config[TLC_ALL_PYTHON_PATHS] = all_pythons
        ## Layout Python path selections
        hsizer = wx.BoxSizer(wx.HORIZONTAL)
        self._python_path_combo.Items = all_pythons
        self._python_path_combo.StringSelection = pythonpath
        self._python_path_combo.ToolTip = wx.ToolTip(
            _("Currently active Python"))
        hsizer.Add(wx.StaticText(self, label=_("Python Path:")), 0, wx.ALL, 5)
        hsizer.Add(self._python_path_combo, 1,
                   wx.EXPAND | wx.ALIGN_CENTER_VERTICAL)
        hsizer.Add(self._add_path, 0, wx.ALIGN_CENTER_VERTICAL | wx.LEFT, 5)
        hsizer.Add(self._rm_path, 0, wx.ALIGN_CENTER_VERTICAL | wx.LEFT, 5)
        sizer.Add(hsizer, 0, wx.EXPAND | wx.ALL, 8)
        # Syntax check
        self._check_on_save_cb.ToolTip = wx.ToolTip(
            _("Mark syntax errors in buffer after save"))
        self._check_on_save_cb.SetValue(
            GetConfigValue(TLC_COMPILE_ON_SAVE, True))
        sizer.Add(self._check_on_save_cb, 0, wx.ALL, 5)
        # Project
        self._load_proj_cb.ToolTip = wx.ToolTip(
            _("Automatically reload last project at startup."))
        self._load_proj_cb.SetValue(GetConfigValue(TLC_LOAD_LAST_PROJECT,
                                                   True))
        sizer.Add(self._load_proj_cb, 0, wx.ALL, 5)

        self.SetSizer(sizer)
    def OnIgnoreSysExitCheckBox(self, evt):
        config = Profile_Get(PYTOOL_CONFIG, default=dict())
        if evt.GetEventObject() is self._igsyscb:
            igsys = self._igsyscb.GetValue()
            config[TLC_IGNORE_SYSEXIT] = igsys
        else:
            evt.Skip()
            return

        Profile_Set(PYTOOL_CONFIG, config)
Example #37
0
    def Init(self, parent):
        """Mixes the shelf into the parent window
        @param parent: Reference to MainWindow

        """
        # First check if the parent has an instance already
        self._parent = parent
        mgr = parent.GetFrameManager()
        if mgr.GetPane(Shelf.SHELF_NAME).IsOk():
            return

        self._shelf = FNB.FlatNotebook(parent,
                                       style=FNB.FNB_FF2 |
                                             FNB.FNB_X_ON_TAB |
                                             FNB.FNB_BACKGROUND_GRADIENT |
                                             FNB.FNB_NODRAG |
                                             FNB.FNB_BOTTOM |
                                             FNB.FNB_NO_X_BUTTON)
        self._shelf.SetImageList(self._imglst)
        mgr.AddPane(self._shelf, wx.aui.AuiPaneInfo().Name(Shelf.SHELF_NAME).\
                            Caption("Shelf").Bottom().Layer(0).\
                            CloseButton(True).MaximizeButton(False).\
                            BestSize(wx.Size(500,250)))

        # Hide the pane and let the perspective manager take care of it
        mgr.GetPane(Shelf.SHELF_NAME).Hide()
        mgr.Update()

        # Install Shelf menu under View and bind event handlers
        view = parent.GetMenuBar().GetMenuByName("view")
        menu = self._GetMenu()
        pos = 0
        for pos in xrange(view.GetMenuItemCount()):
            mitem = view.FindItemByPosition(pos)
            if mitem.GetId() == ed_glob.ID_PERSPECTIVES:
                break

        view.InsertMenu(pos + 1, ed_glob.ID_SHELF, _("Shelf"), 
                        menu, _("Put an item on the Shelf"))

        for item in menu.GetMenuItems():
            if item.IsSeparator():
                continue
            parent.Bind(wx.EVT_MENU, self.OnGetShelfItem, item)

        if menu.GetMenuItemCount() < 3:
            view.Enable(ed_glob.ID_SHELF, False)

        # Check for any other plugin specific install needs
        for observer in self.observers:
            if not observer.IsInstalled() and \
               hasattr(observer, 'InstallComponents'):
                observer.InstallComponents(parent)

        self.StockShelf(Profile_Get('SHELF_ITEMS', 'list', []))
    def OnTrapExceptionsCheckBox(self, evt):
        config = Profile_Get(PYTOOL_CONFIG, default=dict())
        if evt.GetEventObject() is self._trapcb:
            trap = self._trapcb.GetValue()
            config[TLC_TRAP_EXCEPTIONS] = trap
            RpdbDebugger().set_trap_unhandled_exceptions(trap)
        else:
            evt.Skip()
            return

        Profile_Set(PYTOOL_CONFIG, config)
Example #39
0
 def OnUpdateTabs(self, msg):
     """Update all tab images depending upon current settings"""
     if not Profile_Get('TABICONS', default=True):
         for page in range(self.GetPageCount()):
             self.SetPageImage(page, -1)
     else:
         # Show the icons
         for pnum in range(self.GetPageCount()):
             page = self.GetPage(pnum)
             imgid = self._name2idx.get(repr(page.__class__), -1)
             self.SetPageImage(pnum, imgid)
Example #40
0
 def OnUpdateTabs(self, msg):
     """Update all tab images depending upon current settings"""
     if not Profile_Get('TABICONS', default=True):
         for page in range(self.GetPageCount()):
             self.SetPageBitmap(page, wx.NullBitmap)
     else:
         # Show the icons
         for pnum in range(self.GetPageCount()):
             page = self.GetPage(pnum)
             bmp = self.BitmapCallbacks.get(repr(page.__class__), lambda:wx.NullBitmap)()
             self.SetPageBitmap(pnum, bmp)
Example #41
0
 def OnCheck(self, event):
     """Update the configuration"""
     e_obj = event.GetEventObject()
     value = e_obj.GetValue()
     cfg = Profile_Get(LAUNCH_PREFS, default=dict())
     if e_obj is self.savecb:
         cfg['autosave'] = value
     elif e_obj is self.saveallcb:
         cfg['autosaveall'] = value
     else:
         event.Skip()
Example #42
0
 def DoOnIdle(self):
     """Check if the file has been modified and prompt a warning"""
     if Profile_Get('CHECKMOD'):
         cfile = self.GetFileName()
         lmod = GetFileModTime(cfile)
         if self.GetModTime() and not lmod and not os.path.exists(cfile):
             wx.CallAfter(self.PromptToReSave, cfile)
         elif self.GetModTime() < lmod:
             wx.CallAfter(self.AskToReload, cfile)
         else:
             pass
    def GetPythonCommand(self):
        """Get the command that is set in the text control or
        the default value if nothing is set.
        @return: python command string

        """
        cmd = self._pbuff.GetValue().strip()
        if not len(cmd):
            return Profile_Get(PYRUN_EXE, 'str', 'python')
        else:
            return cmd
Example #44
0
    def __init__(self,
                 parent,
                 id_=wx.ID_ANY,
                 pos=wx.DefaultPosition,
                 size=wx.DefaultSize,
                 style=0,
                 use_dt=True):
        """Initialize the editor view"""
        ed_stc.EditraStc.__init__(self, parent, id_, pos, size, style, use_dt)
        ed_tab.EdTabBase.__init__(self)

        # Attributes
        self._ignore_del = False
        self._has_dlg = False
        self._mdata = dict(menu=None, handlers=list(), buff=self)
        self._lprio = 0  # Idle event priority counter
        self._spell = STCSpellCheck(self, check_region=self.IsNonCode)
        spref = Profile_Get('SPELLCHECK', default=dict())
        self._spell_data = dict(choices=list(),
                                word=('', -1, -1),
                                enabled=spref.get('auto', False))

        # Initialize the classes position manager for the first control
        # that is created only.
        if not EdEditorView.DOCMGR.IsInitialized():
            EdEditorView.DOCMGR.InitPositionCache(ed_glob.CONFIG['CACHE_DIR'] + \
                                                  os.sep + u'positions')

        self._spell.clearAll()
        self._spell.setDefaultLanguage(spref.get('dict', 'en_US'))
        self._spell.startIdleProcessing()

        # Context Menu Events
        self.Bind(wx.EVT_CONTEXT_MENU, self.OnContextMenu)

        # Need to relay the menu events from the context menu to the top level
        # window to be handled on gtk. Other platforms don't require this.
        self.Bind(wx.EVT_MENU, self.OnMenuEvent)

        ed_msg.Subscribe(self.OnConfigMsg,
                         ed_msg.EDMSG_PROFILE_CHANGE + ('SPELLCHECK', ))
Example #45
0
def load_templates():
    """
    returns a dictionary mapping template names to template objects for the
    requested lexer type
    """
    from collections import defaultdict

    wx.GetApp().GetLog()('[codetemplater][info]getting %s' %
                         PROFILE_KEY_TEMPLATES)
    temps = Profile_Get(PROFILE_KEY_TEMPLATES)

    templd = defaultdict(lambda: dict())
    try:
        if temps is None:
            dct = load_default_templates()
            #default templates have text name keys instead of IDs like the plugin wants

            for k, v in dct.iteritems():
                templd[synglob.GetIdFromDescription(k)] = v
        else:
            #saved templates store the dict instead of objects,
            # and use language names instead of IDs
            logfunct = wx.GetApp().GetLog()
            for langname, ld in temps.iteritems():
                newld = {}
                for tempname, d in ld.iteritems():
                    logfunct('[codetemplater][info]dkeys %s' % d.keys())
                    logfunct('[codetemplater][info]dname %s' % d['name'])
                    logfunct('[codetemplater][info]templ %s' % d['templ'])
                    logfunct('[codetemplater][info]description %s' %
                             d['description'])
                    logfunct('[codetemplater][info]indent %s' % d['indent'])
                    newld[tempname] = CodeTemplate(d['name'], d['templ'],
                                                   d['description'],
                                                   d['indent'])
                templd[synglob.GetIdFromDescription(langname)] = newld

        return templd
    except:
        Profile_Del(PROFILE_KEY_TEMPLATES)
        raise
Example #46
0
 def AddPage(self, page, text=u'', select=True, imgId=-1):
     """Add a page to the notebook"""
     bNewPage = False
     if not len(text):
         self.pg_num += 1
         if self.pg_num != 0:
             text = _("untitled %d") % self.pg_num
         else:
             text = _("untitled")
         bNewPage = True
     page.SetTabLabel(text)
     bmp = wx.NullBitmap
     if Profile_Get('TABICONS'):
         bmp = page.GetTabImage()
     super(EdPages, self).AddPage(page, text, select, bitmap=bmp)
     self.UpdateIndexes()
     if not self._ses_load and not bNewPage:
         # Only auto save session when using default session
         mgr = ed_session.EdSessionMgr()
         if Profile_Get('LAST_SESSION') == mgr.DefaultSession:
             self.SaveCurrentSession()
Example #47
0
    def SaveCurrentSession(self):
        """Save the current session"""
        if self._ses_load:
            return

        session = Profile_Get('LAST_SESSION')
        # Compatibility with older session data
        if not isinstance(session, basestring) or not len(session):
            mgr = ed_session.EdSessionMgr()
            session = mgr.DefaultSession
            Profile_Set('LAST_SESSION', session)
        self.SaveSessionFile(session)
Example #48
0
def load_templates():
    """
    returns a dictionary mapping template names to template objects for the
    requested lexer type
    """
    from collections import defaultdict

    wx.GetApp().GetLog()('[codetemplater][info]getting %s' % PROFILE_KEY_TEMPLATES)
    temps = Profile_Get(PROFILE_KEY_TEMPLATES)

    templd = defaultdict(lambda:dict())
    try:
        if temps is None:
            dct = load_default_templates()
            #default templates have text name keys instead of IDs like the plugin wants

            for k,v in dct.iteritems():
                templd[synglob.GetIdFromDescription(k)] = v
        else:
            #saved templates store the dict instead of objects,
            # and use language names instead of IDs
            logfunct = wx.GetApp().GetLog()
            for langname,ld in temps.iteritems():
                newld = {}
                for tempname,d in ld.iteritems():
                    logfunct('[codetemplater][info]dkeys %s'%d.keys())
                    logfunct('[codetemplater][info]dname %s'%d['name'])
                    logfunct('[codetemplater][info]templ %s'%d['templ'])
                    logfunct('[codetemplater][info]description %s'%d['description'])
                    logfunct('[codetemplater][info]indent %s'%d['indent'])
                    newld[tempname] = CodeTemplate(d['name'],d['templ'],
                                                   d['description'],d['indent'])
                templd[synglob.GetIdFromDescription(langname)] = newld

        return templd
    except:
        Profile_Del(PROFILE_KEY_TEMPLATES)
        raise
Example #49
0
    def __DoLayout(self):
        sizer = wx.BoxSizer(wx.VERTICAL)

        # Python executable configuration
        config = Profile_Get(PYTOOL_CONFIG, default=dict())
        pythonpath = config.get(TLC_PYTHON_PATH, None)
        if not pythonpath:
            pythonpath = PyStudioUtils.GetDefaultPython()
        all_pythons = config.get(TLC_ALL_PYTHON_PATHS, [])
        if pythonpath:
            pythonpath = os.path.normcase(pythonpath) #TODO: this will likely cause problems on non Windows
            config[TLC_PYTHON_PATH] = pythonpath
            if not pythonpath in all_pythons:
                all_pythons.append(pythonpath)        
        config[TLC_ALL_PYTHON_PATHS] = all_pythons
        ## Layout Python path selections
        hsizer = wx.BoxSizer(wx.HORIZONTAL)
        self._python_path_combo.Items = all_pythons
        self._python_path_combo.StringSelection = pythonpath
        self._python_path_combo.ToolTip = wx.ToolTip(_("Currently active Python"))
        hsizer.Add(wx.StaticText(self, label=_("Python Path:")), 0, wx.ALL, 5)
        hsizer.Add(self._python_path_combo, 1, wx.EXPAND|wx.ALIGN_CENTER_VERTICAL)
        hsizer.Add(self._add_path, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT, 5)
        hsizer.Add(self._rm_path, 0, wx.ALIGN_CENTER_VERTICAL|wx.LEFT, 5)
        sizer.Add(hsizer, 0, wx.EXPAND|wx.ALL, 8)
        # Syntax check
        self._check_on_save_cb.ToolTip = wx.ToolTip(_("Mark syntax errors in buffer after save"))
        self._check_on_save_cb.SetValue(GetConfigValue(TLC_COMPILE_ON_SAVE, True))
        sizer.Add(self._check_on_save_cb, 0, wx.ALL, 5)
        # Project
        self._load_proj_cb.ToolTip = wx.ToolTip(_("Automatically reload last project at startup."))
        self._load_proj_cb.SetValue(GetConfigValue(TLC_LOAD_LAST_PROJECT, True))
        sizer.Add(self._load_proj_cb, 0, wx.ALL, 5)
        

        self.SetSizer(sizer)
Example #50
0
    def RemoveUninstalled(self):
        """Remove all uninstalled plugins
        @todo: need error reporting and handling file permissions
        @todo: handle multiple older versions that are installed
        @todo: handle when installed in multiple locations

        """
        plist = Profile_Get('UNINSTALL_PLUGINS', default=list())
        for path in list(plist):
            try:
                if os.path.isdir(path):
                    shutil.rmtree(path)
                else:
                    os.remove(path)
            except OSError:
                # TODO: don't delete from list, so it can be kept to report
                #       removal errors to user.
                if not os.path.exists(path):
                    plist.remove(path)
                continue
            else:
                self.LOG("[pluginmgr][info] Uninstalled: %s" % path)
                plist.remove(path)
        Profile_Set('UNINSTALL_PLUGINS', plist)
    def OnEditorUpdate(self, ispython, filename, force):
        self._onbuttonsupdate(ispython)
        self.combotexts[self.combocurrent_selection] = self.search.GetValue()
        config = Profile_Get(ToolConfig.PYTOOL_CONFIG, default=dict())
        if MessageHandler().PreviousFile:
            emptycombotexts = True
            for key in self.combotexts:
                combotext = self.combotexts[key]
                if combotext:
                    emptycombotexts = False
                    break
            key = "DEBUG_%s" % MessageHandler().PreviousFile
            if emptycombotexts:
                if key in config:
                    del config["DEBUG_%s" % MessageHandler().PreviousFile]
            else:
                debuginfo = (self.combocurrent_selection, self.combotexts)
                config[key] = copy.deepcopy(debuginfo)
                Profile_Set(ToolConfig.PYTOOL_CONFIG, config)

        debuginfo = config.get("DEBUG_%s" % filename, None)
        if debuginfo:
            self.combocurrent_selection, self.combotexts = debuginfo
            self.combo.SetSelection(self.combocurrent_selection)
            self.search.SetValue(self.combotexts[self.combocurrent_selection])
        else:
            self.combocurrent_selection = 0
            self.combotexts = {}
            for i, ignore in enumerate(self.choices):
                self.combotexts[i] = ""
            self.combo.SetSelection(0)
            self.search.SetValue(u"")

        if force or not self._hasrun:
            ctrlbar = self.GetControlBar(wx.TOP)
            ctrlbar.Layout()
Example #52
0
    def __init__(self, parent):
        super(ToolConfigPanel, self).__init__(parent)

        # Attributes
        self._config = Profile_Get(PYTOOL_CONFIG, default=dict())
        pythonpath = self._config.get(TLC_PYTHON_PATH, None)
        if not pythonpath:
            pythonpath = PyToolsUtils.GetDefaultPython()
        self._python_path_pk = wx.FilePickerCtrl(self, path=pythonpath,
                                          style=wx.FLP_USE_TEXTCTRL|\
                                                wx.FLP_CHANGE_DIR|\
                                                wx.FLP_FILE_MUST_EXIST)
        self._python_path_pk.SetPickerCtrlGrowable(True)
        modebox = wx.StaticBox(self, label=_("Pylint Run Mode"))
        self._modesz = wx.StaticBoxSizer(modebox, wx.VERTICAL)
        self._autorb = wx.RadioButton(self, label=_("Automatic"))
        tooltip = _("Automatically rerun on save, document change, and file load")
        self._autorb.SetToolTipString(tooltip)
        self._manualrb = wx.RadioButton(self, label=_("Manual"))
        tooltip = _("Only run when requested")
        self._manualrb.SetToolTipString(tooltip)
        mode = self._config.get(TLC_AUTO_RUN, False)
        self._autorb.SetValue(mode)
        self._manualrb.SetValue(not mode)

        ## Message configuration
        msgbox = wx.StaticBox(self, label=_("Messages"))
        self._msgsz = wx.StaticBoxSizer(msgbox, wx.VERTICAL)
        self._msgtype = wx.Choice(self, choices=_GetPyLintMessageTypes())
        self._msglst = MessageIDList(self, style=wx.LC_REPORT)

        # Setup
        self._msglst.SetConfig(self._config)
        self._msgtype.SetSelection(0)
        self.UpdateListCtrl()

        # Layout
        self.__DoLayout()

        # Event Handlers
        self.Bind(wx.EVT_RADIOBUTTON, self.OnCheckBox, self._autorb)
        self.Bind(wx.EVT_RADIOBUTTON, self.OnCheckBox, self._manualrb)
        self.Bind(wx.EVT_CHOICE, self.OnChoice, self._msgtype)
        self.Bind(wx.EVT_FILEPICKER_CHANGED, self.OnPythonPathChanged, self._python_path_pk)
 def _setdebuggeroptions(self):
     config = Profile_Get(ToolConfig.PYTOOL_CONFIG, default=dict())
     trap = config.get(ToolConfig.TLC_TRAP_EXCEPTIONS, True)
     RpdbDebugger().set_trap_unhandled_exceptions(trap)
     synchronicity = config.get(ToolConfig.TLC_SYNCHRONICITY, True)
     RpdbDebugger().set_synchronicity(synchronicity)
     autofork = config.get(ToolConfig.TLC_AUTO_FORK, True)
     forkmode = config.get(ToolConfig.TLC_FORK_MODE, False)
     RpdbDebugger().set_fork_mode(forkmode, autofork)
     encoding = config.get(ToolConfig.TLC_EXECEVALENCODING, "auto")
     escaping = config.get(ToolConfig.TLC_EXECEVALESCAPING, True)
     RpdbDebugger().set_encoding(encoding, escaping)
     mode = config.get(ToolConfig.TLC_LINT_AUTORUN, False)
     if mode:
         config[ToolConfig.TLC_LINT_AUTORUN] = False
         Profile_Set(ToolConfig.PYTOOL_CONFIG, config)
         self._listCtrl.AppendUpdate(self.disablingpylinttext)
         self._listCtrl.restoreautorun = self.restorepylint_autorun
     else:
         self._listCtrl.restoreautorun = lambda:None
    def __init__(self, parent):
        """Initialize the window"""
        super(VariablesShelfWindow, self).__init__(parent)

        config = Profile_Get(ToolConfig.PYTOOL_CONFIG, default=dict())
        localsfilterexpr = config.get(ToolConfig.TLC_LOCALS_FILTEREXPR, "")
        globalsfilterexpr = config.get(ToolConfig.TLC_GLOBALS_FILTEREXPR, "")
        exceptionsfilterexpr = config.get(ToolConfig.TLC_EXCEPTIONS_FILTEREXPR, "")
        localsfilterlevel = config.get(ToolConfig.TLC_LOCALS_FILTERLEVEL, 0)
        globalsfilterlevel = config.get(ToolConfig.TLC_GLOBALS_FILTERLEVEL, 0)
        exceptionsfilterlevel = config.get(ToolConfig.TLC_EXCEPTIONS_FILTERLEVEL, 0)
        
        # Attributes
        bstyle = eclib.SEGBOOK_STYLE_NO_DIVIDERS|eclib.SEGBOOK_STYLE_LEFT
        self._nb = eclib.SegmentBook(self, style=bstyle)
        self._locals = VariablesList(self._nb, self.LOCALSSTR, localsfilterexpr, localsfilterlevel)
        self._globals = VariablesList(self._nb, self.GLOBALSSTR, globalsfilterexpr, globalsfilterlevel)
        self._exceptions = VariablesList(self._nb, self.EXCEPTIONSSTR, exceptionsfilterexpr, exceptionsfilterlevel)
        
        # Setup
        self._InitImageList()
        self._nb.AddPage(self._locals, _("Locals"), img_id=0)
        self._nb.AddPage(self._globals, _("Globals"), img_id=1)
        self._nb.AddPage(self._exceptions, _("Exceptions"), img_id=2)
        # NOTE: page order must be kept in sync with this map
        self.pmap = { 0 : (ToolConfig.TLC_LOCALS_FILTEREXPR, ToolConfig.TLC_LOCALS_FILTERLEVEL, self._locals),
                 1 : (ToolConfig.TLC_GLOBALS_FILTEREXPR, ToolConfig.TLC_GLOBALS_FILTERLEVEL, self._globals),
                 2 : (ToolConfig.TLC_EXCEPTIONS_FILTEREXPR, ToolConfig.TLC_EXCEPTIONS_FILTERLEVEL, self._exceptions)
               }
        ctrlbar = self.setup(self._nb, self._locals,
                             self._globals, self._exceptions)
        self.refreshbtn = self.AddPlateButton(u"", ed_glob.ID_REFRESH, wx.ALIGN_LEFT)
        self.refreshbtn.ToolTip = wx.ToolTip(_("Refresh Variables"))
        ctrlbar.AddStretchSpacer()
        self.filterlevel = wx.Choice(ctrlbar, wx.ID_ANY,
                                     choices=(_("Off"), _("Medium"), _("Maximum")))
        self.filterlevel.SetSelection(localsfilterlevel)
        text = wx.StaticText(ctrlbar, label=_("Filtering:"))
        ctrlbar.AddControl(text, wx.ALIGN_RIGHT)
        self.search = eclib.CommandEntryBase(ctrlbar, style=wx.TE_PROCESS_ENTER)
        self.search.Enable(True)
        self.search.SetDescriptiveText(u"Enter Regular Expression")
        if localsfilterexpr:
            self.search.SetValue(localsfilterexpr)
        self.search.ShowSearchButton(True)
        self.search.ShowCancelButton(True)
        ctrlbar.AddControl(self.search, wx.ALIGN_RIGHT, 2)
        ctrlbar.AddControl(self.filterlevel, wx.ALIGN_RIGHT)
        if RpdbDebugger().analyzing:
            self.layout(self.STOPANALYZELBL, self.OnAnalyze)
        else:
            self.layout(self.ANALYZELBL, self.OnAnalyze)
        self.taskbtn.SetBitmap(Images.Inspect.Bitmap)

        # Debugger attributes
        RpdbDebugger().clearlocalvariables = self._locals.Clear
        RpdbDebugger().updatelocalvariables = self._locals.update_namespace
        RpdbDebugger().clearglobalvariables = self._globals.Clear
        RpdbDebugger().updateglobalvariables = self._globals.update_namespace
        RpdbDebugger().clearexceptions = self._exceptions.Clear
        RpdbDebugger().updateexceptions = self._exceptions.update_namespace
        RpdbDebugger().updateanalyze = self.UpdateAnalyze
        
        # Event Handlers
        self.Bind(eclib.EVT_SB_PAGE_CHANGED, self.OnPageChanged, self._nb)
        self.Bind(wx.EVT_BUTTON, self.OnRefresh, self.refreshbtn)
        self.Bind(wx.EVT_CHOICE, self.OnSetFilterLevel, self.filterlevel)
        self.Bind(wx.EVT_SEARCHCTRL_SEARCH_BTN, self.OnRefresh, self.search)
        self.Bind(wx.EVT_TEXT_ENTER, self.OnRefresh, self.search)
        self.Bind(wx.EVT_SEARCHCTRL_CANCEL_BTN, self.OnCancelSearch, self.search)

        RpdbDebugger().update_namespace()
Example #55
0
    def __DoLayout(self):
        """Layout the controls"""
        msizer = wx.BoxSizer(wx.VERTICAL)
        sbox = wx.StaticBox(self, label=_("Text Colors"))
        boxsz = wx.StaticBoxSizer(sbox, wx.VERTICAL)

        # Launch Config
        cfg = Profile_Get(handlers.CONFIG_KEY, default=dict())

        # Actions Configuration
        clear_cb = wx.CheckBox(self, ID_AUTOCLEAR, _("Automatically clear output buffer between runs"))
        clear_cb.SetValue(cfg.get("autoclear", False))
        error_cb = wx.CheckBox(self, ID_ERROR_BEEP, _("Audible feedback when errors are detected"))
        error_cb.SetValue(cfg.get("errorbeep", False))
        wrap_cb = wx.CheckBox(self, ID_WRAP_OUTPUT, _("Wrap lines in output buffer"))
        wrap_cb.SetValue(cfg.get("wrapoutput", False))
        buff_sz = wx.BoxSizer(wx.HORIZONTAL)
        buff_sz.Add(wx.StaticText(self, label=_("Line Buffering:")), 0, wx.ALIGN_CENTER_VERTICAL)
        self._bufftxt = intctrl.IntCtrl(self, min=0, max=50000, allow_none=True)
        self._bufftxt.ToolTip = wx.ToolTip(_("0-50000 (0 unlimited)"))
        lbufcfg = max(0, cfg.get("linebuffer", DEFAULT_LINEBUFFER))
        self._bufftxt.Value = unicode(lbufcfg)
        buff_sz.Add(self._bufftxt, 0, wx.ALL, 5)

        # Colors
        colors = dict()
        for btn in COLOR_MAP.iteritems():
            cbtn = eclib.ColorSetter(self, btn[0], color=cfg.get(btn[1], wx.WHITE))
            colors[btn[0]] = cbtn

        flexg = wx.FlexGridSizer(5, 5, 5, 5)
        flexg.AddGrowableCol(1, 1)
        flexg.AddGrowableCol(3, 1)
        flexg.AddMany(
            [  # First Row
                ((5, 5), 0),
                ((5, 5), 1),
                (wx.StaticText(self, label=_("Foreground")), 0, wx.ALIGN_CENTER),
                ((5, 5), 1),
                (wx.StaticText(self, label=_("Background")), 0, wx.ALIGN_CENTER),
                # Second Row
                (wx.StaticText(self, label=_("Plain Text") + u":"), 0, wx.ALIGN_CENTER_VERTICAL),
                ((5, 5), 1),
                (colors[ID_DEF_FORE], 0, wx.EXPAND),
                ((5, 5), 1),
                (colors[ID_DEF_BACK], 0, wx.EXPAND),
                # Third Row
                (wx.StaticText(self, label=_("Error Text") + u":"), 0, wx.ALIGN_CENTER_VERTICAL),
                ((5, 5), 1),
                (colors[ID_ERR_FORE], 0, wx.EXPAND),
                ((5, 5), 1),
                (colors[ID_ERR_BACK], 0, wx.EXPAND),
                # Fourth Row
                (wx.StaticText(self, label=_("Info Text") + u":"), 0, wx.ALIGN_CENTER_VERTICAL),
                ((5, 5), 1),
                (colors[ID_INFO_FORE], 0, wx.EXPAND),
                ((5, 5), 1),
                (colors[ID_INFO_BACK], 0, wx.EXPAND),
                # Fifth Row
                (wx.StaticText(self, label=_("Warning Text") + u":"), 0, wx.ALIGN_CENTER_VERTICAL),
                ((5, 5), 1),
                (colors[ID_WARN_FORE], 0, wx.EXPAND),
                ((5, 5), 1),
                (colors[ID_WARN_BACK], 0, wx.EXPAND),
            ]
        )
        boxsz.Add(flexg, 0, wx.EXPAND)

        # Layout
        msizer.AddMany(
            [
                ((5, 5), 0),
                (wx.StaticText(self, label=("Actions") + u":"), 0),
                ((5, 5), 0),
                (clear_cb, 0),
                ((5, 5), 0),
                (error_cb, 0),
                ((5, 5), 0),
                (wrap_cb, 0),
                ((5, 5), 0),
                (buff_sz, 0),
                ((10, 10), 0),
                (wx.StaticLine(self), 0, wx.EXPAND),
                ((10, 10), 0),
                (boxsz, 1, wx.EXPAND),
            ]
        )
        hsizer = wx.BoxSizer(wx.HORIZONTAL)
        hsizer.AddMany([((5, 5), 0), (msizer, 1, wx.EXPAND), ((5, 5), 0)])
        self.SetSizer(hsizer)
Example #56
0
def GetConfigValue(key):
    """Get a value from the config"""
    config = Profile_Get(PYTOOL_CONFIG, default=dict())
    return config.get(key, None)
Example #57
0
class ToolConfigPanel(wx.Panel):
    """Configuration panel for Python configuration in the
    PluginManager dialog.

    """
    def __init__(self, parent):
        super(ToolConfigPanel, self).__init__(parent)

        # Attributes
        self._config = Profile_Get(PYTOOL_CONFIG, default=dict())
        pythonpath = self._config.get(TLC_PYTHON_PATH, None)
        if not pythonpath:
            pythonpath = PyToolsUtils.GetDefaultPython()
        self._python_path_pk = wx.FilePickerCtrl(self, path=pythonpath,
                                          style=wx.FLP_USE_TEXTCTRL|\
                                                wx.FLP_CHANGE_DIR|\
                                                wx.FLP_FILE_MUST_EXIST)
        self._python_path_pk.SetPickerCtrlGrowable(True)
        modebox = wx.StaticBox(self, label=_("Pylint Run Mode"))
        self._modesz = wx.StaticBoxSizer(modebox, wx.VERTICAL)
        self._autorb = wx.RadioButton(self, label=_("Automatic"))
        tooltip = _("Automatically rerun on save, document change, and file load")
        self._autorb.SetToolTipString(tooltip)
        self._manualrb = wx.RadioButton(self, label=_("Manual"))
        tooltip = _("Only run when requested")
        self._manualrb.SetToolTipString(tooltip)
        mode = self._config.get(TLC_AUTO_RUN, False)
        self._autorb.SetValue(mode)
        self._manualrb.SetValue(not mode)

        ## Message configuration
        msgbox = wx.StaticBox(self, label=_("Messages"))
        self._msgsz = wx.StaticBoxSizer(msgbox, wx.VERTICAL)
        self._msgtype = wx.Choice(self, choices=_GetPyLintMessageTypes())
        self._msglst = MessageIDList(self, style=wx.LC_REPORT)

        # Setup
        self._msglst.SetConfig(self._config)
        self._msgtype.SetSelection(0)
        self.UpdateListCtrl()

        # Layout
        self.__DoLayout()

        # Event Handlers
        self.Bind(wx.EVT_RADIOBUTTON, self.OnCheckBox, self._autorb)
        self.Bind(wx.EVT_RADIOBUTTON, self.OnCheckBox, self._manualrb)
        self.Bind(wx.EVT_CHOICE, self.OnChoice, self._msgtype)
        self.Bind(wx.EVT_FILEPICKER_CHANGED, self.OnPythonPathChanged, self._python_path_pk)

    def __DoLayout(self):
        sizer = wx.BoxSizer(wx.VERTICAL)

        # Python Path
        pathsz = wx.BoxSizer(wx.HORIZONTAL)
        pathsz.Add(wx.StaticText(self, label=_("Python Executable Path:")),
                   0, wx.ALIGN_CENTER_VERTICAL)
        pathsz.Add(self._python_path_pk, 1, wx.EXPAND|wx.LEFT, 5)
        sizer.Add(pathsz, 0, wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, 5)

        # Run mode configuration
        self._modesz.Add(self._autorb, 0, wx.ALL, 5)
        self._modesz.Add(self._manualrb, 0, wx.ALL, 5)
        sizer.Add(self._modesz, 0, wx.ALL|wx.EXPAND, 8)

        # Enable/Disable pylint checkers
        hsizer = wx.BoxSizer(wx.HORIZONTAL)
        typelbl = wx.StaticText(self, label=_("Message Type: "))
        hsizer.AddMany([((5, 5),0), (typelbl, 0, wx.ALIGN_CENTER_VERTICAL),
                        ((5, 5),0),
                        (self._msgtype, 1, wx.ALIGN_CENTER_VERTICAL|wx.EXPAND),
                        ((5, 5),0)])
        self._msgsz.Add(hsizer, 0, wx.EXPAND|wx.ALL, 5)
        self._msgsz.Add(self._msglst, 1, wx.EXPAND|wx.ALL, 5)
        sizer.Add(self._msgsz, 1, wx.EXPAND|wx.ALL, 8)

        self.SetSizer(sizer)

    def OnCheckBox(self, evt):
        evt_obj = evt.GetEventObject()
        if evt_obj in (self._autorb, self._manualrb):
            self._config[TLC_AUTO_RUN] = self._autorb.GetValue()
        else:
            evt.Skip()
            return

        Profile_Set(PYTOOL_CONFIG, self._config)

    def OnChoice(self, evt):
        evt_obj = evt.GetEventObject()
        if evt_obj is self._msgtype:
            self.UpdateListCtrl()
        else:
            evt.Skip()

    def OnPythonPathChanged(self, event):
        """Update the configured pylint path"""
        path = self._python_path_pk.GetPath()
        if path and os.path.exists(path):
            self._config[TLC_PYTHON_PATH] = path
            Profile_Set(PYTOOL_CONFIG, self._config)

    def UpdateListCtrl(self):
        """Update the list control for the selected message type"""
        if self._msglst.GetItemCount() > 0:
            self._msglst.DeleteAllItems()

        sel = self._msgtype.GetSelection()
        funct = { 0 : Conventions,
                  1 : Refactor,
                  2 : Warnings,
                  3 : Errors,
                  4 : Fatal }
        self._msglst.LoadData(funct[sel]())
Example #58
0
class LaunchWindow(ctrlbox.ControlBox):
    """Control window for showing and running scripts"""
    def __init__(self, parent):
        ctrlbox.ControlBox.__init__(self, parent)

        # Attributes
        self._mw = self.__FindMainWindow()
        self._buffer = OutputDisplay(self)
        self._fnames = list()
        self._chFiles = None # Created in __DoLayout
        self._worker = None
        self._busy = False
        self._isready = False
        self._config = dict(file='', lang=0,
                            cfile='', clang=0,
                            last='', lastlang=0,
                            prelang=0, largs='',
                            lcmd='')
        self._prefs = Profile_Get('Launch.Prefs', default=None)

        # Setup
        self.__DoLayout()
        hstate = Profile_Get(LAUNCH_KEY)
        if hstate is not None:
            handlers.SetState(hstate)
        if self._prefs is None:
            Profile_Set('Launch.Prefs',
                        dict(autoclear=False,
                             defaultf=self._buffer.GetDefaultForeground().Get(),
                             defaultb=self._buffer.GetDefaultBackground().Get(),
                             errorf=self._buffer.GetErrorForeground().Get(),
                             errorb=self._buffer.GetErrorBackground().Get(),
                             infof=self._buffer.GetInfoForeground().Get(),
                             infob=self._buffer.GetInfoBackground().Get(),
                             warnf=self._buffer.GetWarningForeground().Get(),
                             warnb=self._buffer.GetWarningBackground().Get()))
            self._prefs = Profile_Get('Launch.Prefs')

        self.UpdateBufferColors()
        cbuffer = self._mw.GetNotebook().GetCurrentCtrl()
        self.SetupControlBar(cbuffer)
        self._config['lang'] = GetLangIdFromMW(self._mw)
        self.UpdateCurrentFiles(self._config['lang'])
        self.SetFile(GetTextBuffer(self._mw).GetFileName())

        # Setup filetype settings
        self.RefreshControlBar()

        # Event Handlers
        self.Bind(wx.EVT_BUTTON, self.OnButton)
        self.Bind(wx.EVT_CHOICE, self.OnChoice)
        ed_msg.Subscribe(self.OnPageChanged, ed_msg.EDMSG_UI_NB_CHANGED)
        ed_msg.Subscribe(self.OnFileOpened, ed_msg.EDMSG_FILE_OPENED)
        ed_msg.Subscribe(self.OnThemeChanged, ed_msg.EDMSG_THEME_CHANGED)
        ed_msg.Subscribe(self.OnLexerChange, ed_msg.EDMSG_UI_STC_LEXER)
        ed_msg.Subscribe(self.OnConfigExit, cfgdlg.EDMSG_LAUNCH_CFG_EXIT)
        ed_msg.Subscribe(self.OnRunMsg, MSG_RUN_LAUNCH)
        ed_msg.Subscribe(self.OnRunLastMsg, MSG_RUN_LAST)
        ed_msg.RegisterCallback(self._CanLaunch, REQUEST_ACTIVE)
        ed_msg.RegisterCallback(self._CanReLaunch, REQUEST_RELAUNCH)

    def __del__(self):
        ed_msg.Unsubscribe(self.OnPageChanged)
        ed_msg.Unsubscribe(self.OnFileOpened)
        ed_msg.Unsubscribe(self.OnThemeChanged)
        ed_msg.Unsubscribe(self.OnLexerChange)
        ed_msg.Unsubscribe(self.OnConfigExit)
        ed_msg.Unsubscribe(self.OnRunMsg)
        ed_msg.Unsubscribe(self.OnRunLastMsg)
        ed_msg.UnRegisterCallback(self._CanLaunch)
        ed_msg.UnRegisterCallback(self._CanReLaunch)
        super(LaunchWindow, self).__del__()

    def __DoLayout(self):
        """Layout the window"""
        #-- Setup ControlBar --#
        ctrlbar = ctrlbox.ControlBar(self, style=ctrlbox.CTRLBAR_STYLE_GRADIENT)
        if wx.Platform == '__WXGTK__':
            ctrlbar.SetWindowStyle(ctrlbox.CTRLBAR_STYLE_DEFAULT)

        # Preferences
        prefbmp = wx.ArtProvider.GetBitmap(str(ed_glob.ID_PREF), wx.ART_MENU)
        pref = platebtn.PlateButton(ctrlbar, ID_SETTINGS, '', prefbmp,
                                    style=platebtn.PB_STYLE_NOBG)
        pref.SetToolTipString(_("Settings"))
        ctrlbar.AddControl(pref, wx.ALIGN_LEFT)

        # Exe
        ctrlbar.AddControl(wx.StaticText(ctrlbar, label=_("exec") + ":"),
                           wx.ALIGN_LEFT)
        exe = wx.Choice(ctrlbar, ID_EXECUTABLE)
        exe.SetToolTipString(_("Program Executable Command"))
        ctrlbar.AddControl(exe, wx.ALIGN_LEFT)

        # Script Label
        ctrlbar.AddControl((5, 5), wx.ALIGN_LEFT)
        self._chFiles = wx.Choice(ctrlbar, choices=[''])
        ctrlbar.AddControl(self._chFiles, wx.ALIGN_LEFT)

        # Args
        ctrlbar.AddControl((5, 5), wx.ALIGN_LEFT)
        ctrlbar.AddControl(wx.StaticText(ctrlbar, label=_("args") + ":"),
                           wx.ALIGN_LEFT)
        args = wx.TextCtrl(ctrlbar, ID_ARGS)
        args.SetToolTipString(_("Script Arguments"))
        ctrlbar.AddControl(args, wx.ALIGN_LEFT)

        # Spacer
        ctrlbar.AddStretchSpacer()
        
        # Run Button
        rbmp = wx.ArtProvider.GetBitmap(str(ed_glob.ID_BIN_FILE), wx.ART_MENU)
        if rbmp.IsNull() or not rbmp.IsOk():
            rbmp = None
        run = platebtn.PlateButton(ctrlbar, ID_RUN, _("Run"), rbmp,
                                   style=platebtn.PB_STYLE_NOBG)
        ctrlbar.AddControl(run, wx.ALIGN_RIGHT)

        # Clear Button
        cbmp = wx.ArtProvider.GetBitmap(str(ed_glob.ID_DELETE), wx.ART_MENU)
        if cbmp.IsNull() or not cbmp.IsOk():
            cbmp = None
        clear = platebtn.PlateButton(ctrlbar, wx.ID_CLEAR, _("Clear"),
                                     cbmp, style=platebtn.PB_STYLE_NOBG)
        ctrlbar.AddControl(clear, wx.ALIGN_RIGHT)
        ctrlbar.SetVMargin(1, 1)
        self.SetControlBar(ctrlbar)

        self.SetWindow(self._buffer)

    def __FindMainWindow(self):
        """Find the mainwindow of this control
        @return: MainWindow or None

        """
        def IsMainWin(win):
            """Check if the given window is a main window"""
            return getattr(tlw, '__name__', '') == 'MainWindow'

        tlw = self.GetTopLevelParent()
        if IsMainWin(tlw):
            return tlw
        elif hasattr(tlw, 'GetParent'):
            tlw = tlw.GetParent()
            if IsMainWin(tlw):
                return tlw

        return None

    def _CanLaunch(self):
        """Method to use with RegisterCallback for getting status"""
        val = self.CanLaunch()
        if not val:
            val = ed_msg.NullValue()
        return val

    def _CanReLaunch(self):
        """Method to use with RegisterCallback for getting status"""
        val = self.CanLaunch()
        if not val or not len(self._config['last']):
            val = ed_msg.NullValue()
        return val

    def CanLaunch(self):
        """Can the launch window run or not
        @return: bool

        """
        parent = self.GetParent()
        return parent.GetParent().IsActive() and self._isready

    def GetFile(self):
        """Get the file that is currently set to be run
        @return: file path

        """
        return self._config['file']

    def GetLastRun(self):
        """Get the last file that was run
        @return: (fname, lang_id)

        """
        return (self._config['last'], self._config['lastlang'])

    def GetMainWindow(self):
        """Get the mainwindow that created this instance
        @return: reference to MainWindow

        """
        return self._mw

    def OnButton(self, evt):
        """Handle events from the buttons on the control bar"""
        e_id = evt.GetId()
        if e_id == ID_SETTINGS:
            app = wx.GetApp()
            win = app.GetWindowInstance(cfgdlg.ConfigDialog)
            if win is None:
                config = cfgdlg.ConfigDialog(self._mw,
                                             ftype=self._config['lang'])
                config.CentreOnParent()
                config.Show()
            else:
                win.Raise()
        elif e_id == ID_RUN:
            # May be run or abort depending on current state
            self.StartStopProcess()
        elif e_id == wx.ID_CLEAR:
            self._buffer.Clear()
        else:
            evt.Skip()

    def OnChoice(self, evt):
        """Handle events from the Choice controls
        @param evt: wx.CommandEvent

        """
        e_id = evt.GetId()
        e_sel = evt.GetSelection()
        if e_id == self._chFiles.GetId():
            fname = self._fnames[e_sel]
            self.SetFile(fname)
            self._chFiles.SetToolTipString(fname)
        elif e_id == ID_EXECUTABLE:
            e_obj = evt.GetEventObject()
            handler = handlers.GetHandlerById(self._config['lang'])
            cmd = e_obj.GetStringSelection()
            e_obj.SetToolTipString(handler.GetCommand(cmd))
        else:
            evt.Skip()

    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())
        self.UpdateBufferColors()

    def OnFileOpened(self, msg):
        """Reset state when a file open message is recieved
        @param msg: Message Object

        """
        # Only update when in the active window
        if not self._mw.IsActive():
            return

        # Update the file choice control
        self._config['lang'] = GetLangIdFromMW(self._mw)
        self.UpdateCurrentFiles(self._config['lang'])

        fname = msg.GetData()
        self.SetFile(fname)

        # Setup filetype settings
        self.RefreshControlBar()

    def OnLexerChange(self, msg):
        """Update the status of the currently associated file
        when a file is saved. Used for updating after a file type has
        changed due to a save action.
        @param msg: Message object

        """
        if not self._mw.IsActive():
            return

        mdata = msg.GetData()
        # For backwards compatibility with older message format
        if mdata is None:
            return

        fname, ftype = msg.GetData()
        if ftype != self._config['lang']:
            self.UpdateCurrentFiles(ftype)
            self.SetControlBarState(fname, ftype)

    def OnPageChanged(self, msg):
        """Update the status of the currently associated file
        when the page changes in the main notebook.
        @param msg: Message object

        """
        # Only update when in the active window
        if not self._mw.IsActive():
            return

        mval = msg.GetData()
        ctrl = mval[0].GetCurrentCtrl()
        self.UpdateCurrentFiles(ctrl.GetLangId())
        if hasattr(ctrl, 'GetFileName'):
            self.SetupControlBar(ctrl)

    def OnRunMsg(self, msg):
        """Run or abort a launch process if this is the current 
        launch window.
        @param msg: MSG_RUN_LAUNCH

        """
        if self.CanLaunch():
            shelf = self._mw.GetShelf()
            shelf.RaiseWindow(self)
            self.StartStopProcess()

    def OnRunLastMsg(self, msg):
        """Re-run the last run program.
        @param msg: MSG_RUN_LAST

        """
        if self.CanLaunch():
            fname, ftype = self.GetLastRun()
            # If there is no last run file return
            if not len(fname):
                return

            shelf = self._mw.GetShelf()
            self.UpdateCurrentFiles(ftype)
            self.SetFile(fname)
            self.RefreshControlBar()
            shelf.RaiseWindow(self)

            if self._prefs.get('autoclear'):
                self._buffer.Clear()

            self.SetProcessRunning(True)

            self.Run(fname, self._config['lcmd'], self._config['largs'], ftype)

    def OnThemeChanged(self, msg):
        """Update icons when the theme has been changed
        @param msg: Message Object

        """
        ctrls = ((ID_SETTINGS, ed_glob.ID_PREF),
                 (wx.ID_CLEAR, ed_glob.ID_DELETE))
        if self._busy:
            ctrls += ((ID_RUN, ed_glob.ID_STOP),)
        else:
            ctrls += ((ID_RUN, ed_glob.ID_BIN_FILE),)

        for ctrl, art in ctrls:
            btn = self.FindWindowById(ctrl)
            bmp = wx.ArtProvider.GetBitmap(str(art), wx.ART_MENU)
            btn.SetBitmap(bmp)
            btn.Refresh()

    def RefreshControlBar(self):
        """Refresh the state of the control bar based on the current config"""
        handler = handlers.GetHandlerById(self._config['lang'])
        cmds = handler.GetAliases()

        # Get the controls
        exe_ch = self.FindWindowById(ID_EXECUTABLE)
        args_txt = self.FindWindowById(ID_ARGS)
        run_btn = self.FindWindowById(ID_RUN)

        # Set control states
        csel = exe_ch.GetStringSelection()
        exe_ch.SetItems(cmds)
        if len(cmds):
            exe_ch.SetToolTipString(handler.GetCommand(cmds[0]))

        util.Log("[Launch][info] Found commands %s" % str(cmds))
        if handler.GetName() != handlers.DEFAULT_HANDLER and len(self.GetFile()):
            for ctrl in (exe_ch, args_txt, run_btn, self._chFiles):
                ctrl.Enable()
            self._isready = True

            if self._config['lang'] == self._config['prelang'] and len(csel):
                exe_ch.SetStringSelection(csel)
            else:
                csel = handler.GetDefault()
                exe_ch.SetStringSelection(csel)

            exe_ch.SetToolTipString(handler.GetCommand(csel))
            self.GetControlBar().Layout()
        else:
            self._isready = False
            for ctrl in (exe_ch, args_txt, run_btn, self._chFiles):
                ctrl.Disable()

    def Run(self, fname, cmd, args, ftype):
        """Run the given file
        @param fname: File path
        @param cmd: Command to run on file
        @param args: Executable arguments
        @param ftype: File type id

        """
        # Find and save the file if it is modified
        nb = self._mw.GetNotebook()
        for ctrl in nb.GetTextControls():
            tname = ctrl.GetFileName()
            if fname == tname:
                if ctrl.GetModify():
                    ctrl.SaveFile(tname)
                    break

        handler = handlers.GetHandlerById(ftype)
        path, fname = os.path.split(fname)
        self._worker = outbuff.ProcessThread(self._buffer,
                                             cmd, fname,
                                             args, path,
                                             handler.GetEnvironment())
        self._worker.start()

    def StartStopProcess(self):
        """Run or abort the context of the current process if possible"""
        if self._prefs.get('autoclear'):
            self._buffer.Clear()

        self.SetProcessRunning(not self._busy)
        if self._busy:
            util.Log("[Launch][info] Starting process")
            handler = handlers.GetHandlerById(self._config['lang'])
            cmd = self.FindWindowById(ID_EXECUTABLE).GetStringSelection()
            self._config['lcmd'] = cmd
            cmd = handler.GetCommand(cmd)
            args = self.FindWindowById(ID_ARGS).GetValue().split()
            self._config['largs'] = args
            self.Run(self._config['file'], cmd, args, self._config['lang'])
        else:
            util.Log("[Launch][info] Aborting process")
            self._worker.Abort()
            self._worker = None

    def SetFile(self, fname):
        """Set the script file that will be run
        @param fname: file path

        """
        # Set currently selected file
        self._config['file'] = fname
        self._chFiles.SetStringSelection(os.path.split(fname)[1])
        self.GetControlBar().Layout()

    def SetLangId(self, langid):
        """Set the language id value(s)
        @param langid: syntax.synglob lang id

        """
        self._config['prelang'] = self._config['lang']
        self._config['lang'] = langid

    def SetProcessRunning(self, running=True):
        """Set the state of the window into either process running mode
        or process not running mode.
        @keyword running: Is a process running or not

        """
        rbtn = self.FindWindowById(ID_RUN)
        self._busy = running
        if running:
            self._config['last'] = self._config['file']
            self._config['lastlang'] = self._config['lang']
            self._config['cfile'] = self._config['file']
            self._config['clang'] = self._config['lang']
            abort = wx.ArtProvider.GetBitmap(str(ed_glob.ID_STOP), wx.ART_MENU)
            if abort.IsNull() or not abort.IsOk():
                abort = wx.ArtProvider.GetBitmap(wx.ART_ERROR,
                                                 wx.ART_MENU, (16, 16))
            rbtn.SetBitmap(abort)
            rbtn.SetLabel(_("Abort"))
        else:
            rbmp = wx.ArtProvider.GetBitmap(str(ed_glob.ID_BIN_FILE), wx.ART_MENU)
            if rbmp.IsNull() or not rbmp.IsOk():
                rbmp = None
            rbtn.SetBitmap(rbmp)
            rbtn.SetLabel(_("Run"))
            # If the buffer was changed while this was running we should
            # update to the new buffer now that it has stopped.
            self.SetFile(self._config['cfile'])
            self.SetLangId(self._config['clang'])
            self.RefreshControlBar()

        self.GetControlBar().Layout()
        rbtn.Refresh()

    def SetupControlBar(self, ctrl):
        """Set the state of the controlbar based data found in the buffer
        passed in.
        @param ctrl: EdStc

        """
        fname = ctrl.GetFileName()
        lang_id = ctrl.GetLangId()
        self.SetControlBarState(fname, lang_id)

    def SetControlBarState(self, fname, lang_id):
        # Don't update the bars status if the buffer is busy
        if self._buffer.IsRunning():
            self._config['cfile'] = fname
            self._config['clang'] = lang_id
        else:
            self.SetFile(fname)
            self.SetLangId(lang_id)

            # Refresh the control bars view
            self.RefreshControlBar()

    def UpdateBufferColors(self):
        """Update the buffers colors"""
        colors = dict()
        for color in ('defaultf', 'defaultb', 'errorf', 'errorb',
                      'infof', 'infob', 'warnf', 'warnb'):
            val = self._prefs.get(color, None)
            if val is not None:
                colors[color] = wx.Color(*val)
            else:
                colors[color] = val

        self._buffer.SetDefaultColor(colors['defaultf'], colors['defaultb'])
        self._buffer.SetErrorColor(colors['errorf'], colors['errorb'])
        self._buffer.SetInfoColor(colors['infof'], colors['infob'])
        self._buffer.SetWarningColor(colors['warnf'], colors['warnb'])

    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)
            if len(self._fnames):
                self._chFiles.SetToolTipString(self._fnames[0])
        except TypeError:
            util.Log("[Launch][err] UpdateCurrent Files: " + str(items))
            self._chFiles.SetItems([''])
Example #59
0
def GetSortOption():
    """Get current sorting option"""
    cfgobj = Profile_Get(CB_PROFILE_KEY, default=dict())
    sortopt = cfgobj.get(CB_SORT_OPTION, CB_ALPHA_SORT)
    return sortopt
Example #60
0
    def __DoLayout(self):
        """Layout the controls"""
        msizer = wx.BoxSizer(wx.VERTICAL)
        sbox = wx.StaticBox(self, label=_("Text Colors"))
        boxsz = wx.StaticBoxSizer(sbox, wx.VERTICAL)

        # Launch Config
        cfg = Profile_Get(LAUNCH_PREFS, default=dict())

        # Actions Configuration
        clear_cb = wx.CheckBox(self, ID_AUTOCLEAR,
                               _("Automatically clear output buffer between runs"))
        clear_cb.SetValue(cfg.get('autoclear', False))
        error_cb = wx.CheckBox(self, ID_ERROR_BEEP,
                               _("Audible feedback when errors are detected"))
        error_cb.SetValue(cfg.get('errorbeep', False))
        wrap_cb = wx.CheckBox(self, ID_WRAP_OUTPUT,
                              _("Wrap lines in output buffer"))
        wrap_cb.SetValue(cfg.get('wrapoutput', False))

        # Colors
        colors = dict()
        for btn in COLOR_MAP.iteritems():
            cbtn = eclib.ColorSetter(self, btn[0], color=cfg.get(btn[1]))
            colors[btn[0]] = cbtn

        flexg = wx.FlexGridSizer(5, 5, 5, 5)
        flexg.AddGrowableCol(1, 1)
        flexg.AddGrowableCol(3, 1)
        flexg.AddMany([# First Row
                       ((5, 5), 0), ((5, 5), 1),
                       (wx.StaticText(self, label=_("Foreground")), 0,
                        wx.ALIGN_CENTER),
                       ((5, 5), 1),
                       (wx.StaticText(self, label=_("Background")), 0,
                        wx.ALIGN_CENTER),
                       # Second Row
                       (wx.StaticText(self, label=_("Plain Text") + u":"), 0,
                        wx.ALIGN_CENTER_VERTICAL),
                       ((5, 5), 1),
                       (colors[ID_DEF_FORE], 0, wx.EXPAND),
                       ((5, 5), 1),
                       (colors[ID_DEF_BACK], 0, wx.EXPAND),
                       # Third Row
                       (wx.StaticText(self, label=_("Error Text") + u":"), 0,
                        wx.ALIGN_CENTER_VERTICAL),
                       ((5, 5), 1),
                       (colors[ID_ERR_FORE], 0, wx.EXPAND),
                       ((5, 5), 1),
                       (colors[ID_ERR_BACK], 0, wx.EXPAND),
                       # Fourth Row
                       (wx.StaticText(self, label=_("Info Text") + u":"), 0,
                        wx.ALIGN_CENTER_VERTICAL),
                       ((5, 5), 1),
                       (colors[ID_INFO_FORE], 0, wx.EXPAND),
                       ((5, 5), 1),
                       (colors[ID_INFO_BACK], 0, wx.EXPAND),
                       # Fifth Row
                       (wx.StaticText(self, label=_("Warning Text") + u":"), 0,
                        wx.ALIGN_CENTER_VERTICAL),
                       ((5, 5), 1),
                       (colors[ID_WARN_FORE], 0, wx.EXPAND),
                       ((5, 5), 1),
                       (colors[ID_WARN_BACK], 0, wx.EXPAND)])
        boxsz.Add(flexg, 0, wx.EXPAND)

        # Layout
        msizer.AddMany([((5, 5), 0),
                        (wx.StaticText(self, label=("Actions") + u":"), 0),
                        ((5, 5), 0), (clear_cb, 0),
                        ((5, 5), 0), (error_cb, 0),
                        ((5, 5), 0), (wrap_cb, 0),
                        ((10, 10), 0), (wx.StaticLine(self), 0, wx.EXPAND),
                        ((10, 10), 0),
                        (boxsz, 1, wx.EXPAND)])
        hsizer = wx.BoxSizer(wx.HORIZONTAL)
        hsizer.AddMany([((5, 5), 0), (msizer, 1, wx.EXPAND), ((5, 5), 0)])
        self.SetSizer(hsizer)