def DoPostLoad(self): """Perform post file open actions""" # Ensure that document buffer is writable after an editable # document is opened in the buffer. doc = self.control.GetDocument() if not doc.IsReadOnly() and not doc.IsRawBytes(): self.control.SetReadOnly(False) # Set last known caret position if the user setting is enabled # and the caret position has not been changed during a threaded # file loading operation. if Profile_Get('SAVE_POS') and self.control.GetCurrentPos() <= 0: 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())
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)
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)
def OpenFileObject(self, fileobj): """Open a new text editor page with the given file object. The file object must be an instance of ed_txt.EdFile. @param fileobj: File Object """ # Create the control with eclib.Freezer(self.TopLevelParent) as _tmp: control = ed_editv.EdEditorView(self) control.Hide() # Load the files data path = fileobj.GetPath() filename = ebmlib.GetFileName(path) control.SetDocument(fileobj) result = control.ReloadFile() # Setup the buffer fileobj.AddModifiedCallback(control.FireModified) # Setup the notebook self.control = control self.control.FindLexer() self.control.EmptyUndoBuffer() self.control.Show() self.AddPage(self.control, filename) self.frame.AddFileToHistory(path) self.SetPageText(self.GetSelection(), filename) self.LOG("[ed_pages][evt] Opened Page: %s" % filename) # Set tab image cpage = self.GetSelection() self.SetPageBitmap(cpage, self.control.GetTabImage()) # Refocus on selected page self.GoCurrentPage() ed_msg.PostMessage(ed_msg.EDMSG_FILE_OPENED, self.control.GetFileName(), context=self.frame.Id) if Profile_Get('WARN_EOL', default=True) and not fileobj.IsRawBytes(): self.control.CheckEOL()
def RunScript(self, fname): """Start the worker thread that runs the python script""" self._abort = False self._buffer.Clear() self._ctrl.SetCurrentFile(fname) self._ctrl.Disable() pyexe = self._ctrl.GetPythonCommand() if len(pyexe): Profile_Set(PYRUN_EXE, pyexe) else: pyexe = Profile_Get(PYRUN_EXE, 'str', 'python') # Start the worker thread self._log("[PyRun][info] Running script with command: %s" % pyexe) self._worker = threading.Thread(target=self._DoRunCmd, args=[fname, pyexe]) self._worker.start() self._ctrl.SetLastRun(fname) self.Layout() wx.CallLater(150, self._buffer.Start, 300)
def _SetupImageList(self): """Setup the image list for the tree""" imglst = wx.ImageList(16, 16) if Profile_Get('ICONS', 'Default') != 'Default': globe = wx.ArtProvider.GetBitmap(str(ed_glob.ID_WEB), wx.ART_MENU) self.icons['globals'] = imglst.Add(globe) else: self.icons['globals'] = imglst.Add(IconFile.GetGlobalBitmap()) self.icons['class'] = imglst.Add(IconFile.GetBricksBitmap()) self.icons['section'] = imglst.Add(IconFile.GetBrickAddBitmap()) self.icons['function'] = imglst.Add(IconFile.GetBrickGoBitmap()) self.icons['method'] = self.icons['function'] self.icons['subroutine'] = self.icons['function'] self.icons['procedure'] = self.icons['function'] self.icons['task'] = imglst.Add(IconFile.GetBrickGo2Bitmap()) self.icons['variable'] = imglst.Add(IconFile.GetBrickBitmap()) self.icons['namespace'] = imglst.Add(IconFile.GetBrickBricksBitmap()) self.SetImageList(imglst) # NOTE: Must save reference to the image list or tree will crash!!! self.il = imglst
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
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', ))
def NewPage(self): """Create a new notebook page with a blank text control @postcondition: a new page with an untitled document is opened """ self.GetTopLevelParent().Freeze() self.pg_num += 1 self.control = ed_stc.EditraStc(self, wx.ID_ANY) self.LOG("[ed_pages][evt] New Page Created ID: %d" % self.control.GetId()) self.AddPage(self.control, u"Untitled - %d" % self.pg_num) self.SetPageImage(self.GetSelection(), str(self.control.GetLangId())) # Set the control up the the preferred default lexer dlexer = Profile_Get('DEFAULT_LEX', 'str', 'Plain Text') ext_reg = syntax.ExtensionRegister() ext_lst = ext_reg.get(dlexer, [ 'txt', ]) self.control.FindLexer(ext_lst[0]) self.GetTopLevelParent().Thaw()
def NewPage(self): """Create a new notebook page with a blank text control @postcondition: a new page with an untitled document is opened """ frame = self.TopLevelParent with eclib.Freezer(frame) as _tmp: self.control = ed_editv.EdEditorView(self) self.LOG("[ed_pages][evt] New Page Created") self.AddPage(self.control) # Set the control up the the preferred default lexer dlexer = Profile_Get('DEFAULT_LEX', 'str', synglob.LANG_TXT) ext_reg = syntax.ExtensionRegister() ext_lst = ext_reg.get(dlexer, ['txt', ]) self.control.FindLexer(ext_lst[0]) self.SetPageBitmap(self.GetSelection(), self.control.GetTabImage()) # Set the modified callback notifier doc = self.control.GetDocument() doc.AddModifiedCallback(self.control.FireModified)
def DocDuplicated(self, path): """Check for if the given path is open elswhere and duplicate the docpointer. @param path: string """ doc = ed_msg.RequestResult(ed_msg.EDREQ_DOCPOINTER, [self, path]) if hasattr(doc, 'GetDocPointer'): self.GetTopLevelParent().Freeze() nbuff = ed_editv.EdEditorView(self, wx.ID_ANY) nbuff.SetDocPointer(doc.GetDocPointer()) doc = doc.GetDocument() nbuff.SetDocument(doc) doc.AddModifiedCallback(nbuff.FireModified) nbuff.FindLexer() nbuff.EmptyUndoBuffer() if Profile_Get('SAVE_POS'): pos = self.DocMgr.GetPos(nbuff.GetFileName()) nbuff.GotoPos(pos) nbuff.ScrollToColumn(0) filename = util.GetFileName(path) self.AddPage(nbuff, filename) self.frame.SetTitle(nbuff.GetTitleString()) self.SetPageText(self.GetSelection(), filename) self.LOG("[ed_pages][evt] Opened Page: %s" % filename) # Set tab image self.SetPageImage(self.GetSelection(), str(nbuff.GetLangId())) # Refocus on selected page self.control = nbuff self.GoCurrentPage() self.GetTopLevelParent().Thaw() ed_msg.PostMessage(ed_msg.EDMSG_FILE_OPENED, nbuff.GetFileName()) return True else: return False
def __init__(self, parent, id_=wx.ID_ANY): super(FtpWindow, self).__init__(parent, id_) # Attributes self._mw = ed_basewin.FindMainWindow(self) self._config = ftpconfig.ConfigData self._config.SetData(Profile_Get(CONFIG_KEY, default=dict())) self._connected = False self._client = ftpclient.FtpClient(self) self._files = list() self._select = None self._open = list() # Open ftpfile objects # Ui controls self._cbar = None # ControlBar self._list = None # FtpList self._sites = None # wx.Choice self.prefbtn = None self._username = None # wx.TextCtrl self._password = None # wx.TextCtrl # Layout self.__DoLayout() self.EnableControls(bool(self._config.GetCount())) self.RefreshControlBar() # Event Handlers self.Bind(wx.EVT_BUTTON, self.OnButton, self.prefbtn) self.Bind(wx.EVT_BUTTON, self.OnButton, self.cbtn) self.Bind(wx.EVT_CHOICE, self.OnChoice, id=ID_SITES) self.Bind(wx.EVT_MENU, self.OnMenu) self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnItemActivated) self.Bind(ftpclient.EVT_FTP_REFRESH, self.OnRefresh) self.Bind(ftpclient.EVT_FTP_DOWNLOAD, self.OnDownload) self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy, self) # Editra Message Handlers ed_msg.Subscribe(self.OnThemeChanged, ed_msg.EDMSG_THEME_CHANGED) ed_msg.Subscribe(self.OnCfgUpdated, ftpconfig.EDMSG_FTPCFG_UPDATED)
def __init__(self, parent): super(StyleEditorBox, self).__init__(parent) # Attributes self._prevTheme = None ctrlbar = self.CreateControlBar(wx.TOP) ss_lst = util.GetResourceFiles(u'styles', get_all=True) ss_lst = [sheet for sheet in ss_lst if not sheet.startswith('.')] self._style_ch = wx.Choice(ctrlbar, ed_glob.ID_PREF_SYNTHEME, choices=sorted(ss_lst)) bmp = wx.ArtProvider.GetBitmap(str(ed_glob.ID_ADD), wx.ART_MENU) self._addbtn = eclib.PlateButton(ctrlbar, label=_("New"), bmp=bmp, style=eclib.PB_STYLE_NOBG) bmp = wx.ArtProvider.GetBitmap(str(ed_glob.ID_REMOVE), wx.ART_MENU) self._delbtn = eclib.PlateButton(ctrlbar, label=_("Remove"), bmp=bmp, style=eclib.PB_STYLE_NOBG) # Setup ss_lbl = wx.StaticText(ctrlbar, label=_("Style Theme") + u": ") ctrlbar.AddControl(ss_lbl, wx.ALIGN_LEFT) self.StyleTheme = Profile_Get('SYNTHEME', 'str') ctrlbar.AddControl(self._style_ch, wx.ALIGN_LEFT) ctrlbar.AddControl(self._addbtn, wx.ALIGN_LEFT) self._addbtn.SetToolTipString(_("Create a new style theme")) ctrlbar.AddControl(self._delbtn, wx.ALIGN_LEFT) self._delbtn.SetToolTipString(_("Remove Style")) self.SetWindow(StyleEditorPanel(self)) # Events self.Bind(wx.EVT_CHOICE, self.OnThemeChoice, self._style_ch) self.Bind(wx.EVT_BUTTON, self.OnButton) self.Bind(wx.EVT_UPDATE_UI, lambda evt: evt.Enable(not self.IsSystemStyleSheet()), self._delbtn)
def SetPageImage(self, pg_num, lang_id): """Sets the page image by querying the ArtProvider based on the language id associated with the type of open document. Any unknown filetypes are associated with the plaintext page image. @param pg_num: page index to set image for @param lang_id: language id of file type to get mime image for """ if not Profile_Get('TABICONS'): return imglst = self.GetImageList() if not self._index.has_key(lang_id): bmp = wx.ArtProvider.GetBitmap(lang_id, wx.ART_MENU) if bmp.IsNull(): self._index.setdefault(lang_id, \ self._index[synglob.ID_LANG_TXT]) else: self._index[lang_id] = imglst.Add(wx.ArtProvider.\ GetBitmap(lang_id, wx.ART_MENU)) FNB.FlatNotebook.SetPageImage(self, pg_num, self._index[lang_id])
def __StyleSheets(self): """Returns a sizer item that contains a choice control with all the available style sheets listed in it. @return: sizer item holding all installed style sheets """ ss_sizer = wx.BoxSizer(wx.HORIZONTAL) ss_lbl = wx.StaticText(self.ctrl_pane, wx.ID_ANY, _("Style Theme") + u": ") ss_lst = util.GetResourceFiles(u'styles', get_all=True) ss_choice = wx.Choice(self.ctrl_pane, ed_glob.ID_PREF_SYNTHEME, choices=sorted(ss_lst)) ss_choice.SetToolTip(wx.ToolTip(_("Base new theme on existing one"))) ss_choice.SetStringSelection(Profile_Get('SYNTHEME', 'str')) ss_new = wx.CheckBox(self.ctrl_pane, wx.ID_NEW, _("New")) ss_new.SetToolTip(wx.ToolTip(_("Start a blank new style"))) ss_sizer.AddMany([((10, 10)), (ss_lbl, 0, wx.ALIGN_CENTER_VERTICAL), ((5, 0)), (ss_choice, 0, wx.ALIGN_CENTER_VERTICAL), ((10, 0)), (ss_new, 0, wx.ALIGN_CENTER_VERTICAL), ((10, 10))]) return ss_sizer
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 __init__(self, parent): """create the tree""" wx.TreeCtrl.__init__(self, parent, style=wx.TR_DEFAULT_STYLE|\ wx.TR_FULL_ROW_HIGHLIGHT|\ wx.TR_EDIT_LABELS|\ wx.TR_SINGLE|\ wx.SIMPLE_BORDER) # Attributes self._editing = (None, None) self._imglst = wx.ImageList(16, 16) self._imgidx = dict(folder=0, site=1) self._root = None # TreeItemId # Setup font = Profile_Get('FONT3', 'font', wx.NORMAL_FONT) self.SetFont(font) self.SetImageList(self._imglst) self.__SetupImageList() self._root = self.AddRoot(_("My Sites")) self.SetItemImage(self._root, self._imgidx['folder'], wx.TreeItemIcon_Normal) self.SetItemImage(self._root, self._imgidx['open'], wx.TreeItemIcon_Expanded) self.SetItemHasChildren(self._root, True) self.Expand(self._root) for site in ConfigData.GetSites(): self.AppendItem(self._root, site, self._imgidx['site']) self.SetMinSize(wx.Size(-1, 150)) # Event Handlers self.Bind(wx.EVT_TREE_BEGIN_LABEL_EDIT, self.OnBeginLabelEdit) self.Bind(wx.EVT_TREE_END_LABEL_EDIT, self.OnEndLabelEdit) # Editra Message Handlers ed_msg.Subscribe(self.OnThemeChanged, ed_msg.EDMSG_THEME_CHANGED) ed_msg.Subscribe(self.OnUpdateFont, ed_msg.EDMSG_DSP_FONT)
def LoadSessionFiles(self): """Load files from saved session data in profile @postcondition: Files saved from previous session are opened. If no files were found then only a single blank page is opened. """ self._ses_load = True files = Profile_Get('LAST_SESSION') # Open the files from the profile if files is not None: for fname in files: if os.path.exists(fname) and os.access(fname, os.R_OK): self.OpenPage(os.path.dirname(fname), os.path.basename(fname)) # Give feedback as files are loaded self.Update() self._ses_load = False if self.GetPageCount() == 0: self.NewPage()
def __init__(self, parent): wx.Notebook.__init__(self, parent) # Make sure config has been intialized prefs = Profile_Get(LAUNCH_PREFS, default=None) if prefs is None: buff = eclib.OutputBuffer(self) buff.Hide() Profile_Set(LAUNCH_PREFS, dict(autoclear=False, defaultf=buff.GetDefaultForeground().Get(), defaultb=buff.GetDefaultBackground().Get(), errorf=buff.GetErrorForeground().Get(), errorb=buff.GetErrorBackground().Get(), infof=buff.GetInfoForeground().Get(), infob=buff.GetInfoBackground().Get(), warnf=buff.GetWarningForeground().Get(), warnb=buff.GetWarningBackground().Get())) buff.Destroy() # Setup self.AddPage(ConfigPanel(self), _("General")) self.AddPage(MiscPanel(self), _("Misc"))
def SetPageImage(self, pg_num, lang_id): """Sets the page image by querying the ArtProvider based on the language id associated with the type of open document. Any unknown filetypes are associated with the plaintext page image. @param pg_num: page index to set image for @param lang_id: language id of file type to get mime image for """ # Only set icons when enabled in preferences if not Profile_Get('TABICONS'): return imglst = self.GetImageList() if lang_id not in self._index: bmp = wx.ArtProvider.GetBitmap(lang_id, wx.ART_MENU) if bmp.IsNull(): self._index.setdefault(lang_id, \ self._index[synglob.ID_LANG_TXT]) else: self._index[lang_id] = imglst.Add(wx.ArtProvider.\ GetBitmap(lang_id, wx.ART_MENU)) super(EdPages, self).SetPageImage(pg_num, self._index[lang_id])
def UpdateAllImages(self): """Reload and Reset all images in the notebook pages and the corresponding imagelist to match those of the current theme @postcondition: all images in control are updated """ if not Profile_Get('TABICONS'): for page in xrange(self.GetPageCount()): FNB.FlatNotebook.SetPageImage(self, page, -1) else: imglst = self.GetImageList() for lang, index in self._index.iteritems(): bmp = wx.ArtProvider.GetBitmap(str(lang), wx.ART_MENU) if bmp.IsNull(): self._index.setdefault(lang, \ self._index[synglob.ID_LANG_TXT]) else: imglst.Replace(index, bmp) for page in xrange(self.GetPageCount()): self.SetPageImage(page, str(self.GetPage(page).GetLangId())) self.Refresh()
def PlugIt(self, parent): """Adds the view menu entry and registers the event handler""" self._mw = parent self._log = wx.GetApp().GetLog() if self._mw != None: self._log("[filebrowser] Installing filebrowser plugin") #---- Create File Browser ----# self._filebrowser = BrowserPane(self._mw, ID_BROWSERPANE) mgr = self._mw.GetFrameManager() mgr.AddPane(self._filebrowser, wx.aui.AuiPaneInfo().Name(PANE_NAME).\ Caption("Editra | File Browser").Left().Layer(1).\ CloseButton(True).MaximizeButton(False).\ BestSize(wx.Size(215, 350))) if Profile_Get('SHOW_FB', 'bool', False): mgr.GetPane(PANE_NAME).Show() else: mgr.GetPane(PANE_NAME).Hide() mgr.Update() # Event Handlers self._mw.Bind(wx.aui.EVT_AUI_PANE_CLOSE, self.OnPaneClose)
def OnButton(self, evt): """Filter add/remove buttons""" bChanged = False if evt.EventObject is self._addb: txt = wx.GetTextFromUser(_("Enter new filter"), _("Add File Filters"), parent=self.TopLevelParent) txt = txt.strip() items = self._filters.GetItems() if txt and txt not in items: self._filters.Append(txt) bChanged = True else: # Remove filters sels = self._filters.GetSelections() for idx in reversed(sels): self._filters.Delete(idx) bChanged = True if bChanged: cfgobj = Profile_Get(FB_PROF_KEY, default=dict()) cfgobj[evt.EventObject.Name] = self._filters.GetItems() Profile_Set(FB_PROF_KEY, cfgobj)
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)
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 __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)) # 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)
def InitWindowAlpha(self): """Initialize the windows alpha setting""" level = max(100, Profile_Get('ALPHA', default=255)) # Only set the transparency if it is not opaque if level != 255: self._window.SetTransparent(level)
def __init__(self, parent): super(LaunchWindow, self).__init__(parent) # Attributes self._log = wx.GetApp().GetLog() self._mw = self.__FindMainWindow() self._buffer = OutputDisplay(self) self._fnames = list() self._lockFile = None # Created in __DoLayout 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() if not handlers.InitCustomHandlers(ed_glob.CONFIG['CACHE_DIR']): util.Log(u"[launch][warn] failed to load launch extensions") 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, errorbeep=False, wrapoutput=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._buffer.SetPrefs(self._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) self.Bind(wx.EVT_CHECKBOX, self.OnCheck) 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)
class StyleMgr(object): """Manages style definitions and provides them on request. Also provides functionality for loading custom style sheets and modifying styles during run time. """ STYLES = dict() # Static cache for loaded style set(s) FONT_PRIMARY = u"primary" FONT_SECONDARY = u"secondary" FONT_SIZE = u"size" FONT_SIZE2 = u"size2" FONT_SIZE3 = u"size3" def __init__(self, custom=wx.EmptyString): """Initializes the Style Manager @keyword custom: path to custom style sheet to use """ super(StyleMgr, self).__init__() # Attributes self.fonts = self.GetFontDictionary() self.style_set = custom self.syntax_set = list() self.LOG = wx.GetApp().GetLog() # Get the Style Set if custom != wx.EmptyString and self.LoadStyleSheet(custom): self.LOG("[ed_style][info] Loaded custom style sheet %s" % custom) elif custom == wx.EmptyString: self.SetStyles('default', DEF_STYLE_DICT) else: self.LOG("[ed_style][err] Failed to import styles from %s" % custom) def BlankStyleDictionary(self): """Returns a dictionary of unset style items based on the tags defined in the current dictionary. @return: dictionary of unset style items using the current tag set as keys. """ sty_dict = dict() for key in DEF_STYLE_DICT.keys(): if key in ('select_style', ): # special styles sty_dict[key] = NullStyleItem() else: sty_dict[key] = StyleItem("#000000", "#FFFFFF", "%(primary)s", "%(size)d") return sty_dict def FindTagById(self, style_id): """Find the style tag that is associated with the given Id. Return value defaults to default_style . @param style_id: id of tag to look for @return: style tag string """ for data in self.syntax_set: if style_id == data[0]: return data[1] return 'default_style' def GetFontDictionary(self, default=True): """Does a system lookup to build a default set of fonts using ten point fonts as the standard size. @keyword default: return the default dictionary of fonts, else return the current running dictionary of fonts if it exists. @return: font dictionary (primary, secondary) + (size, size2) """ if hasattr(self, 'fonts') and not default: return self.fonts font = Profile_Get('FONT1', 'font', None) if font is not None: mfont = font else: mfont = wx.Font(10, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL) Profile_Set('FONT1', mfont, 'font') primary = mfont.GetFaceName() font = Profile_Get('FONT2', 'font', None) if font is None: font = wx.Font(10, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL) Profile_Set('FONT2', font, 'font') secondary = font.GetFaceName() faces = { self.FONT_PRIMARY: primary, self.FONT_SECONDARY: secondary, self.FONT_SIZE: mfont.GetPointSize(), self.FONT_SIZE2: font.GetPointSize(), self.FONT_SIZE3: mfont.GetPointSize() - 2 } return faces def GetDefaultFont(self): """Constructs and returns a wxFont object from the settings of the default_style object. @return: wx.Font object of default style """ if self.HasNamedStyle('default_style'): style_item = self.GetItemByName('default_style') face = style_item.GetFace() if face and face[0] == u"%": face = face % self.fonts size = style_item.GetSize() if isinstance(size, basestring): size = size % self.fonts font = wx.FFont(int(size), wx.MODERN, face=face) else: font = wx.FFont(self.fonts[self.FONT_SIZE], wx.MODERN) return font def GetDefaultForeColour(self, as_hex=False): """Gets the foreground color of the default style and returns a Colour object. Otherwise returns Black if the default style is not found. @keyword as_hex: return a hex string or colour object @return: wx.Colour of default style foreground or hex value """ fore = self.GetItemByName('default_style').GetFore() if not fore: fore = u"#000000" if not as_hex: rgb = eclib.HexToRGB(fore[1:]) fore = wx.Colour(red=rgb[0], green=rgb[1], blue=rgb[2]) return fore def GetCurrentStyleSetName(self): """Get the name of the currently set style @return: string """ return self.style_set def GetDefaultBackColour(self, as_hex=False): """Gets the background color of the default style and returns a Colour object. Otherwise returns white if the default style is not found. @keyword as_hex: return a hex string or colour object @return: wx.Colour of default style background or hex value """ back = self.GetItemByName('default_style').GetBack() if not back: back = u"#FFFFFF" if not as_hex: rgb = eclib.HexToRGB(back[1:]) back = wx.Colour(red=rgb[0], green=rgb[1], blue=rgb[2]) return back def GetItemByName(self, name): """Gets and returns a style item using its name for the search @param name: tag name of style item to get @return: style item (may be empty/null style item) """ scheme = self.GetStyleSet() if name in scheme: item = scheme[name] # Set font value if need be ival = unicode(item) if u"%" in ival: val = ival % self.fonts item = StyleItem() item.SetAttrFromStr(val) return item else: return StyleItem() def GetStyleFont(self, primary=True): """Returns the primary font facename by default @keyword primary: Get Primary(default) or Secondary Font @return face name of current font in use """ if primary: font = wx.FFont(self.fonts[self.FONT_SIZE], wx.DEFAULT, face=self.fonts[self.FONT_PRIMARY]) else: font = wx.FFont(self.fonts[self.FONT_SIZE2], wx.DEFAULT, face=self.fonts[self.FONT_SECONDARY]) return font def GetStyleByName(self, name): """Gets and returns a style string using its name for the search @param name: tag name of style to get @return: style item in string form """ if self.HasNamedStyle(name): stystr = unicode(self.GetItemByName(name)) return stystr.replace("modifiers:", "") else: return u"" def GetStyleSet(self): """Returns the current set of styles or the default set if there is no current set. @return: current style set dictionary """ return StyleMgr.STYLES.get(self.style_set, DEF_STYLE_DICT) @staticmethod 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 else: style = Profile_Get('SYNTHEME', 'str') style = ebmlib.AddFileExtension(style, u'.ess').lower() # Get Correct Filename if it exists for sheet in util.GetResourceFiles(u'styles', trim=False, get_all=True, title=False): if sheet.lower() == style: 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 def GetSyntaxParams(self): """Get the set of syntax parameters @return: list """ return self.syntax_set def HasNamedStyle(self, name): """Checks if a style has been set/loaded or not @param name: tag name of style to look for @return: whether item is in style set or not """ return name in self.GetStyleSet() def LoadStyleSheet(self, style_sheet, force=False): """Loads a custom style sheet and returns True on success @param style_sheet: path to style sheet to load @keyword force: Force re-parse of style sheet, default is to use cached data when available @return: whether style sheet was loaded or not """ if isinstance(style_sheet, basestring) and \ os.path.exists(style_sheet) and \ ((force or style_sheet not in StyleMgr.STYLES) or \ style_sheet != self.style_set): reader = util.GetFileReader(style_sheet) if reader == -1: self.LOG("[ed_style][err] Failed to open style sheet: %s" % style_sheet) return False style_data = None try: style_data = self.ParseStyleData(reader.read()) except Exception, msg: self.LOG("[ed_style][err] Failed to parse style data for %s:" % style_sheet) return False ret_val = self.SetStyles(style_sheet, style_data) reader.close() return ret_val elif style_sheet not in StyleMgr.STYLES: self.LOG("[ed_style][warn] Style sheet %s does not exists" % style_sheet) # Reset to default style if Profile_Get('SYNTHEME') != 'default': Profile_Set('SYNTHEME', 'default') self.SetStyles('default', DEF_STYLE_DICT) return False
def SaveBreakpoints(): """Save currently set breakpoints in the user configuration""" config = Profile_Get(ToolConfig.PYTOOL_CONFIG, default=dict()) config[ToolConfig.TLC_BREAKPOINTS] = copy.deepcopy(RpdbDebugger().breakpoints) Profile_Set(ToolConfig.PYTOOL_CONFIG, config)