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 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, 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, ))
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,))
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', ))
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 __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',))
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
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
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)
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 __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 __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)
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)
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)
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)
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
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
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)
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 _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): 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 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()
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
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)
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]())
def GetConfigValue(key): """Get a value from the config""" config = Profile_Get(PYTOOL_CONFIG, default=dict()) return config.get(key, None)
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 __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()
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()
def __init__(self, parent): super(DebugConfigPanel, self).__init__(parent) # Attributes config = Profile_Get(PYTOOL_CONFIG, default=dict()) self._trapcb = wx.CheckBox(self, label=_("Trap Unhandled Exceptions")) trap = config.get(TLC_TRAP_EXCEPTIONS, True) self._trapcb.SetValue(trap) config[TLC_TRAP_EXCEPTIONS] = trap RpdbDebugger().set_trap_unhandled_exceptions(trap) self._igsyscb = wx.CheckBox(self, label=_("Ignore SystemExit Exception")) igsys = config.get(TLC_IGNORE_SYSEXIT, True) self._igsyscb.SetValue(igsys) config[TLC_IGNORE_SYSEXIT] = igsys self._synccb = wx.CheckBox(self, label=_("Allow Synchronicity")) synchronicity = config.get(TLC_SYNCHRONICITY, True) self._synccb.SetValue(synchronicity) RpdbDebugger().set_synchronicity(synchronicity) config[TLC_SYNCHRONICITY] = synchronicity self._forkcb = wx.CheckBox(self, label=_("Pause before fork")) autofork = config.get(TLC_AUTO_FORK, True) self._forkcb.SetValue(not autofork) config[TLC_AUTO_FORK] = autofork self._forkchildcb = wx.CheckBox(self, label=_("Fork into Child")) forkmode = config.get(TLC_FORK_MODE, False) self._forkchildcb.SetValue(forkmode) config[TLC_FORK_MODE] = forkmode RpdbDebugger().set_fork_mode(forkmode, autofork) self._enclbl = wx.StaticText(self, label=_("Source Encoding:")) encodings = eclib.GetAllEncodings() encodings.insert(0, "auto") self._encch = wx.Choice(self, wx.ID_ANY, choices=encodings) self._encch.SetToolTipString(_("Source Encoding for Execute/Evaluate")) encoding = config.get(TLC_EXECEVALENCODING, "auto") self._encch.SetStringSelection(encoding) config[TLC_EXECEVALENCODING] = encoding self._esccb = wx.CheckBox( self, label=_("Escape Non-Ascii Characters for Execute/Evaluate")) escaping = config.get(TLC_EXECEVALESCAPING, True) self._esccb.SetValue(escaping) config[TLC_EXECEVALESCAPING] = escaping RpdbDebugger().set_encoding(encoding, escaping) Profile_Set(PYTOOL_CONFIG, config) # Layout self.__DoLayout() # Event Handlers self.Bind(wx.EVT_CHECKBOX, self.OnTrapExceptionsCheckBox, self._trapcb) self.Bind(wx.EVT_CHECKBOX, self.OnIgnoreSysExitCheckBox, self._igsyscb) self.Bind(wx.EVT_CHECKBOX, self.OnSynchronicityCheckBox, self._synccb) self.Bind(wx.EVT_CHECKBOX, self.OnForkCheckBox, self._forkcb) self.Bind(wx.EVT_RADIOBUTTON, self.OnForkCheckBox, self._forkchildcb) self.Bind(wx.EVT_CHOICE, self.OnEncoding, self._encch) self.Bind(wx.EVT_CHECKBOX, self.OnEscapingCheckBox, self._esccb)
def GetFBOption(opt, default=None): """Get FileBrowser option from the configuration""" cfgobj = Profile_Get(FB_PROF_KEY, default=dict()) return cfgobj.get(opt, default)
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([''])
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
def __init__(self, parent): super(DebugConfigPanel, self).__init__(parent) # Attributes config = Profile_Get(PYTOOL_CONFIG, default=dict()) self._trapcb = wx.CheckBox(self, label=_("Trap Unhandled Exceptions")) trap = config.get(TLC_TRAP_EXCEPTIONS, True) self._trapcb.SetValue(trap) config[TLC_TRAP_EXCEPTIONS] = trap RpdbDebugger().set_trap_unhandled_exceptions(trap) self._igsyscb = wx.CheckBox(self, label=_("Ignore SystemExit Exception")) igsys = config.get(TLC_IGNORE_SYSEXIT, True) self._igsyscb.SetValue(igsys) config[TLC_IGNORE_SYSEXIT] = igsys self._synccb = wx.CheckBox(self, label=_("Allow Synchronicity")) synchronicity = config.get(TLC_SYNCHRONICITY, True) self._synccb.SetValue(synchronicity) RpdbDebugger().set_synchronicity(synchronicity) config[TLC_SYNCHRONICITY] = synchronicity self._forkcb = wx.CheckBox(self, label=_("Pause before fork")) autofork = config.get(TLC_AUTO_FORK, True) self._forkcb.SetValue(not autofork) config[TLC_AUTO_FORK] = autofork self._forkchildcb = wx.CheckBox(self, label=_("Fork into Child")) forkmode = config.get(TLC_FORK_MODE, False) self._forkchildcb.SetValue(forkmode) config[TLC_FORK_MODE] = forkmode RpdbDebugger().set_fork_mode(forkmode, autofork) self._enclbl = wx.StaticText(self, label=_("Source Encoding:")) encodings = eclib.GetAllEncodings() encodings.insert(0, "auto") self._encch = wx.Choice(self, wx.ID_ANY, choices=encodings) self._encch.SetToolTipString(_("Source Encoding for Execute/Evaluate")) encoding = config.get(TLC_EXECEVALENCODING, "auto") self._encch.SetStringSelection(encoding) config[TLC_EXECEVALENCODING] = encoding self._esccb = wx.CheckBox(self, label=_("Escape Non-Ascii Characters for Execute/Evaluate")) escaping = config.get(TLC_EXECEVALESCAPING, True) self._esccb.SetValue(escaping) config[TLC_EXECEVALESCAPING] = escaping RpdbDebugger().set_encoding(encoding, escaping) Profile_Set(PYTOOL_CONFIG, config) # Layout self.__DoLayout() # Event Handlers self.Bind(wx.EVT_CHECKBOX, self.OnTrapExceptionsCheckBox, self._trapcb) self.Bind(wx.EVT_CHECKBOX, self.OnIgnoreSysExitCheckBox, self._igsyscb) self.Bind(wx.EVT_CHECKBOX, self.OnSynchronicityCheckBox, self._synccb) self.Bind(wx.EVT_CHECKBOX, self.OnForkCheckBox, self._forkcb) self.Bind(wx.EVT_RADIOBUTTON, self.OnForkCheckBox, self._forkchildcb) self.Bind(wx.EVT_CHOICE, self.OnEncoding, self._encch) self.Bind(wx.EVT_CHECKBOX, self.OnEscapingCheckBox, self._esccb)
def GetConfigValue(key): """Get a value from the config""" config = Profile_Get(PYTOOL_CONFIG, default=dict()) return config.get(key, None)
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)
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]())
class LaunchWindow(eclib.ControlBox): """Control window for showing and running scripts""" 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) 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 = eclib.ControlBar(self, style=eclib.CTRLBAR_STYLE_GRADIENT) if wx.Platform == '__WXGTK__': ctrlbar.SetWindowStyle(eclib.CTRLBAR_STYLE_DEFAULT) # Preferences prefbmp = wx.ArtProvider.GetBitmap(str(ed_glob.ID_PREF), wx.ART_MENU) pref = eclib.PlateButton(ctrlbar, ID_SETTINGS, '', prefbmp, style=eclib.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._lockFile = wx.CheckBox(ctrlbar, wx.ID_ANY) self._lockFile.SetToolTipString(_("Lock File")) ctrlbar.AddControl(self._lockFile, wx.ALIGN_LEFT) self._chFiles = wx.Choice(ctrlbar, wx.ID_ANY) #, 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, size=(100, -1)) args.SetToolTipString(_("Arguments")) ctrlbar.AddControl(args, wx.ALIGN_LEFT, 1) # 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 = eclib.PlateButton(ctrlbar, ID_RUN, _("Run"), rbmp, style=eclib.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 = eclib.PlateButton(ctrlbar, wx.ID_CLEAR, _("Clear"), cbmp, style=eclib.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) 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 OnCheck(self, evt): """CheckBox for Lock File was clicked""" e_obj = evt.GetEventObject() if e_obj is self._lockFile: if self._lockFile.IsChecked(): self._chFiles.Disable() else: self._chFiles.Enable() cbuff = GetTextBuffer(self._mw) if isinstance(cbuff, ed_basestc.EditraBaseStc): self.UpdateCurrentFiles(cbuff.GetLangId()) self.SetupControlBar(cbuff) 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()) # TODO is this necessary see other handler # Update wordwrapping mode = wx.stc.STC_WRAP_NONE if self._prefs.get('wrapoutput', False): mode = wx.stc.STC_WRAP_WORD # should we do wrap char? wrapmode = self._buffer.GetWrapMode() if wrapmode != mode: self._buffer.SetWrapMode(mode) self.UpdateBufferColors() @ed_msg.mwcontext def OnFileOpened(self, msg): """Reset state when a file open message is received @param msg: Message Object """ if self._lockFile.IsChecked(): return # Mode is locked ignore update # 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() @ed_msg.mwcontext 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 """ self._log("[launch][info] Lexer changed handler - context %d" % self._mw.GetId()) if self._lockFile.IsChecked(): return # Mode is locked ignore update mdata = msg.GetData() # For backwards compatibility with older message format if mdata is None: return fname, ftype = msg.GetData() # Update regardless of whether lexer has changed or not as the buffer # may have the lexer set before the file was saved to disk. if fname: #if ftype != self._config['lang']: self.UpdateCurrentFiles(ftype) self.SetControlBarState(fname, ftype) @ed_msg.mwcontext def OnPageChanged(self, msg): """Update the status of the currently associated file when the page changes in the main notebook. @param msg: Message object """ # The current mode is locked if self._lockFile.IsChecked(): return mval = msg.GetData() ctrl = mval[0].GetCurrentCtrl() if isinstance(ctrl, ed_basestc.EditraBaseStc): self.UpdateCurrentFiles(ctrl.GetLangId()) self.SetupControlBar(ctrl) else: self._log("[launch][info] Non STC object in notebook") return # Doesn't implement EdStc interface 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) 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, self._lockFile): ctrl.Enable() self._isready = True if self._lockFile.IsChecked(): self._chFiles.Enable(False) 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, self._lockFile): ctrl.Disable() self._chFiles.Clear() 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) if wx.Platform == '__WXMSW__': fname = u"\"" + fname + u"\"" else: fname = fname.replace(u' ', u'\\ ') self._worker = eclib.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: if not self._lockFile.IsChecked(): 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.Colour(*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: if len(u''.join(items)): 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([''])
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._slbl = 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) 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) def __del__(self): ed_msg.Unsubscribe(self.OnPageChanged) ed_msg.Unsubscribe(self.OnThemeChanged) ed_msg.Unsubscribe(self.OnConfigExit) ed_msg.Unsubscribe(self.OnRunMsg) ed_msg.UnRegisterCallback(self.CanLaunch) super(LaunchWindow).__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._slbl = wx.StaticText(ctrlbar, label="") ctrlbar.AddControl(self._slbl, 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 CanLaunch(self): """Can the launch window run or not @return: bool """ parent = self.GetParent() return parent.GetCurrentPage() == self and \ 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 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 fname = msg.GetData() self.SetFile(fname) # Setup filetype settings self._config['lang'] = GetLangIdFromMW(self._mw) self.RefreshControlBar() 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() 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(): self.StartStopProcess() 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) util.Log("[Launch][info] Found commands %s" % str(cmds)) if handler.GetName() != handlers.DEFAULT_HANDLER and len( self.GetFile()): exe_ch.Enable() args_txt.Enable() run_btn.Enable() self._isready = True if self._config['lang'] == self._config['prelang'] and len(csel): exe_ch.SetStringSelection(csel) else: exe_ch.SetStringSelection(handler.GetDefault()) self.GetControlBar().Layout() else: self._isready = False run_btn.Disable() args_txt.Disable() exe_ch.Disable() 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() cmd = handler.GetCommand(cmd) path, fname = os.path.split(self._config['file']) args = self.FindWindowById(ID_ARGS).GetValue().split() self._worker = outbuff.ProcessThread(self._buffer, cmd, fname, args, path, handler.GetEnvironment()) self._worker.start() 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 """ self._config['file'] = fname sname = os.path.split(fname)[1] self._slbl.SetLabel(_("file") + ": " + sname) 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() # 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 __init__(self, parent): CommandBarBase.__init__(self, 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_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)
def GetFBOption(opt, default=None): """Get FileBrowser option from the configuration""" cfgobj = Profile_Get(FB_PROF_KEY, default=dict()) return cfgobj.get(opt, default)