def test_ignorable_classes(self): self._create('foo.py', 'class Foo(object): pass') sut = PluginLoader() sut.load_directory(self.plugin_dir, onlyif=lambda x, y: False) self.assertEqual({}, sut.plugins)
class PluginRegistry(object): """ """ def __init__(self, deviceRegistry): """ """ self.__deviceRegistry = deviceRegistry self.__logger = logging.getLogger("PluginRegistry") self.__pluginsloader = PluginLoader() self.__plugins = [] def __isPlugin(self, name, clazz): #print ("Checking %s (%s)" % (name, clazz)) return isclass(clazz) and issubclass(clazz, Plugin) and clazz != Plugin def getPlugins(self): return self.__plugins def initialize(self, directory): self.__pluginsloader.load_directory(directory, onlyif=self.__isPlugin, context={'deviceRegistry': self.__deviceRegistry}) for name, plugin in self.__pluginsloader.plugins.iteritems(): self.__logger.debug("Loading plugin: %s" % name) inst = plugin() inst.setDeviceRegistry(self.__deviceRegistry) self.__plugins.append(inst)
def test_load_simple_file(self): self._create('foo.py', 'class Foo(object): pass') sut = PluginLoader() sut.load_directory(self.plugin_dir) self.assertEqual(['Foo'], list(sut.plugins.keys()))
def test_containing_directories(self): self._create_dir('foo') sut = PluginLoader() sut.load_directory(self.plugin_dir) self.assertEqual({}, sut.plugins)
def test_link_recursive(self): os.symlink(self.plugin_dir, os.path.join(self.plugin_dir, 'foo')) sut = PluginLoader() sut.load_directory(self.plugin_dir, recursive=True) self.assertEqual({}, sut.plugins)
def test_ignorable_classes(self): self._write_file('class Foo(object): pass') self.plugin_file.flush() sut = PluginLoader() sut.load_file(self.plugin_file.name, onlyif=lambda x, y, z: False) self.assertEquals({}, sut.plugins)
def test_not_ignorable_classes(self): self._write_file('class Foo(object): pass') self.plugin_file.flush() sut = PluginLoader() sut.load_file(self.plugin_file.name, onlyif=lambda x, y, z: True) self.assertEquals('Foo', sut.plugins['Foo']().__class__.__name__)
def test_binary_files_are_ignored(self): self.plugin_file.write(b'\0\1\2\3\4\5\6\7') self.plugin_file.flush() sut = PluginLoader() sut.load_file(self.plugin_file.name) self.assertEqual([], list(sut.plugins.keys()))
def test_recursive_mode_off(self): self._create_dir('foo') self._create('bar.py', 'class Bazz(object): pass', 'foo') sut = PluginLoader() sut.load_directory(self.plugin_dir, recursive=False) self.assertEqual({}, sut.plugins)
def test_ignorable_classes_with_variable_false(self): self._write_file('class Foo(object): pass') self.plugin_file.flush() sut = PluginLoader() sut.load_file(self.plugin_file.name, onlyif=False) self.assertEqual([], list(sut.plugins.keys()))
def test_recursive_mode(self): self._create_dir('foo') self._create('bar.py', 'class Bazz(object): pass', 'foo') sut = PluginLoader() sut.load_directory(self.plugin_dir, recursive=True) self.assertEqual(['Bazz'], list(sut.plugins.keys()))
def _load_plugins(self): plugin_path = os.path.join( os.path.dirname(__file__), 'plugins', ) plugin_mgr = PluginLoader() plugin_mgr.load_directory(plugin_path, onlyif=self._check_plugin) self.plugins = [c() for n, c in plugin_mgr.plugins.items()]
def test_ignorable_classes_with_variable_true(self): self._write_file('class Foo(object): pass') self.plugin_file.flush() sut = PluginLoader() sut.load_file(self.plugin_file.name, onlyif=True) self.assertEqual(sorted(['__builtins__', 'Foo']), sorted(list(sut.plugins.keys())))
def test_base_case(self): self._write_file('class Foo(object): pass') self.plugin_file.flush() sut = PluginLoader() sut.load_file(self.plugin_file.name) self.assertEquals(['Foo'], list(sut.plugins.keys())) self.assertIsInstance(sut.plugins['Foo'], object) self.assertEquals('Foo', sut.plugins['Foo']().__class__.__name__)
def test_parameters_for_constructor(self): self._write_file('class Foo(object):\n' ' def __init__(self, a):\n' ' self.a = a') self.plugin_file.flush() sut = PluginLoader() sut.load_file(self.plugin_file.name) plugin = sut.plugins['Foo'](5) self.assertEqual(5, plugin.a)
def test_use_context(self): class Pattern(object): pass self._create('foo.py', 'class Foo(Bar): pass') sut = PluginLoader() sut.load_directory(self.plugin_dir, context={'Bar': Pattern}) self.assertEqual(sorted(['Foo', 'Bar']), sorted(list(sut.plugins.keys())))
def test_adding_context(self): class Pattern(object): pass self.plugin_file.write(b'class Foo(Bar): pass') self.plugin_file.flush() sut = PluginLoader() sut.load_file(self.plugin_file.name, context={'Bar': Pattern}) self.assertEqual(sorted(['Foo', 'Bar']), sorted(list(sut.plugins.keys())))
def test_parameters_for_constructor(self): self._write_file( 'class Foo(object):\n' ' def __init__(self, a):\n' ' self.a = a' ) self.plugin_file.flush() sut = PluginLoader() sut.load_file(self.plugin_file.name) plugin = sut.plugins['Foo'](5) self.assertEqual(5, plugin.a)
def test_two_plugins_in_a_file(self): self._write_file('class Foo(object):\n' ' pass\n' 'class Bar(object):\n' ' pass\n') self.plugin_file.flush() sut = PluginLoader() sut.load_file(self.plugin_file.name) self.assertEqual(sorted(['Foo', 'Bar']), sorted(list(sut.plugins.keys()))) self.assertEqual('Foo', sut.plugins['Foo']().__class__.__name__) self.assertEqual('Bar', sut.plugins['Bar']().__class__.__name__)
def __init__(self, deviceRegistry): """ """ self.__deviceRegistry = deviceRegistry self.__logger = logging.getLogger("PluginRegistry") self.__pluginsloader = PluginLoader() self.__plugins = []
def test_two_plugins_in_a_file(self): self._write_file( 'class Foo(object):\n' ' pass\n' 'class Bar(object):\n' ' pass\n' ) self.plugin_file.flush() sut = PluginLoader() sut.load_file(self.plugin_file.name) self.assertEqual(sorted(['Foo', 'Bar']), sorted(list(sut.plugins.keys()))) self.assertEqual('Foo', sut.plugins['Foo']().__class__.__name__) self.assertEqual('Bar', sut.plugins['Bar']().__class__.__name__)
def OnInit(self): self.settings = RideSettings() librarydatabase.initialize_database() self.preferences = Preferences(self.settings) self.namespace = Namespace(self.settings) self._controller = ChiefController(self.namespace, self.settings) self.frame = RideFrame(self, self._controller) self._editor_provider = EditorProvider() self._plugin_loader = PluginLoader(self, self._get_plugin_dirs(), context.get_core_plugins()) self._plugin_loader.enable_plugins() self.editor = self._get_editor() self.editor.show() self._load_data() self.frame.tree.populate(self.model) self.frame.tree.set_editor(self.editor) self._publish_system_info() if self._updatecheck: UpdateNotifierController( self.settings).notify_update_if_needed(UpdateDialog) wx.CallLater(200, ReleaseNotes(self).bring_to_front) return True
def __init__(self, parent=None): """ init UI """ QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.actionSaveSession.setEnabled(False) self.distributed_objects = DistributedObjects() self.debug_controller = self.distributed_objects.debug_controller self.settings = self.debug_controller.settings self.signalproxy = self.distributed_objects.signal_proxy self.pluginloader = PluginLoader(self.distributed_objects) #init RecentFileHandler nrRecentFiles = 5 self.initRecentFileHandler(nrRecentFiles) QObject.connect(self.debug_controller, SIGNAL('executableOpened'), self.showExecutableName) # signal proxy QObject.connect(self.signalproxy, SIGNAL('inferiorIsRunning(PyQt_PyObject)'), self.targetStartedRunning, Qt.QueuedConnection) QObject.connect(self.signalproxy, SIGNAL('inferiorHasStopped(PyQt_PyObject)'), self.targetStopped, Qt.QueuedConnection) QObject.connect(self.signalproxy, SIGNAL('inferiorHasExited(PyQt_PyObject)'), self.targetExited, Qt.QueuedConnection) QObject.connect(self.signalproxy, SIGNAL('addDockWidget(PyQt_PyObject, QDockWidget, PyQt_PyObject)'), self.addPluginDockWidget) QObject.connect(self.signalproxy, SIGNAL('removeDockWidget(QDockWidget)'), self.removeDockWidget) QObject.connect(self.pluginloader, SIGNAL('insertPluginAction(PyQt_PyObject)'), self.addPluginAction) QObject.connect(self.ui.actionSavePlugins, SIGNAL('activated()'), self.showSavePluginsDialog) QObject.connect(self.ui.actionLoadPlugins, SIGNAL('activated()'), self.showLoadPluginsDialog) # Add editor to main window. self.ui.gridLayout.addWidget(self.distributed_objects.editor_controller.editor_view, 0, 0, 1, 1) self.pluginloader.addAvailablePlugins() # Tell everyone to insert their dock widgets into the main window self.distributed_objects.signal_proxy.insertDockWidgets() # get filelist dockwidget self.filelist_dockwidget = self.findChild(QDockWidget, "FileListView"); QObject.connect(self.debug_controller, SIGNAL('executableOpened'), self.filelist_dockwidget.raise_) self.setWindowFilePath("<none>") self.setupUi() self.createInitialWindowPlacement() self.readSettings()
def __init__(self, config, logger): super(TelegramBot, self).__init__(config.get('telegrambot', 'token')) self.logger = logger self.restricted = config.getboolean('telegrambot', 'restrict_contacts') self.allowedusers = config.get('telegrambot', 'allowed_contacts').split(',') self.callbackusers = config.get('telegrambot', 'callback_contacts').split(',') self.botinfo = self.getMe() self.logger.info('Bot "' + self.botinfo['first_name'] + '" initialized. Bot id: ' + str(self.botinfo['id'])) self.logger.info("Listening...") self.useplugins = config.getboolean('telegrambot', 'loadplugins') if (self.useplugins): pluginloader = PluginLoader(self.logger) self.plugins = pluginloader.loadPlugins(self.callback) self.logger.info("Plugins are loaded") for k, v in self.plugins.iteritems(): if (k.startswith('/')): self.commands[k] = v.getdescription(k) self.plugins['/help'] = HelpPlugin(self.commands) self.logger.info("Help is: " + str(self.commands))
def OnInit(self): self.namespace = Namespace() self._controller = ChiefController(self.namespace) self.frame = RideFrame(self, self._controller) self._editor_provider = EditorProvider() self._plugin_loader = PluginLoader(self, self._get_plugin_dirs(), context.get_core_plugins()) self._plugin_loader.enable_plugins() self.editor = self._get_editor() self.editor.show() self._load_data() self.frame.tree.populate(self.model) self.frame.tree.set_editor(self.editor) self._publish_system_info() wx.CallLater(200, self._get_release_notes().bring_to_front) return True
def OnInit(self): self.settings = RideSettings() self.preferences = Preferences(self.settings) self.namespace = Namespace(self.settings) self._controller = ChiefController(self.namespace, self.settings) self.frame = RideFrame(self, self._controller) self._editor_provider = EditorProvider() self._plugin_loader = PluginLoader(self, self._get_plugin_dirs(), context.get_core_plugins()) self._plugin_loader.enable_plugins() self.editor = self._get_editor() self.editor.show() self._load_data() self.frame.tree.populate(self.model) self.frame.tree.set_editor(self.editor) self._publish_system_info() if self._updatecheck: UpdateNotifierController(self.settings).notify_update_if_needed(UpdateDialog) wx.CallLater(200, ReleaseNotes(self).bring_to_front) return True
class RIDE(wx.App): def __init__(self, path=None): self._initial_path = path context.APP = self wx.App.__init__(self, redirect=False) def OnInit(self): self.namespace = Namespace() self._controller = ChiefController(self.namespace) self.frame = RideFrame(self, self._controller) self._editor_provider = EditorProvider() self._plugin_loader = PluginLoader(self, self._get_plugin_dirs(), context.get_core_plugins()) self._plugin_loader.enable_plugins() self.editor = self._get_editor() self.editor.show() self._load_data() self.frame.tree.populate(self.model) self.frame.tree.set_editor(self.editor) self._publish_system_info() wx.CallLater(200, self._get_release_notes().bring_to_front) return True def _publish_system_info(self): RideLogMessage(context.SYSTEM_INFO).publish() @property def model(self): return self._controller def _get_plugin_dirs(self): return [context.SETTINGS.get_path('plugins'), os.path.join(context.SETTINGS['install root'], 'site-plugins'), contrib.CONTRIB_PATH] def _get_editor(self): from robotide.editor import EditorPlugin for pl in self._plugin_loader.plugins: if isinstance(pl._plugin, EditorPlugin): return pl._plugin def _get_release_notes(self): from .releasenotes import ReleaseNotesPlugin for pl in self._plugin_loader.plugins: if isinstance(pl._plugin, ReleaseNotesPlugin): return pl._plugin def _load_data(self): if self._initial_path: with self.active_event_loop(): observer = LoadProgressObserver(self.frame) self._controller.load_data(self._initial_path, observer) def get_plugins(self): return self._plugin_loader.plugins def register_editor(self, object_class, editor_class, activate): self._editor_provider.register_editor(object_class, editor_class, activate) def unregister_editor(self, object_class, editor_class): self._editor_provider.unregister_editor(object_class, editor_class) def activate_editor(self, object_class, editor_class): self._editor_provider.set_active_editor(object_class, editor_class) def get_editors(self, object_class): return self._editor_provider.get_editors(object_class) def get_editor(self, object_class): return self._editor_provider.get_editor(object_class) @contextmanager def active_event_loop(self): # With wxPython 2.9.1, ProgressBar.Pulse breaks if there's no active # event loop. # See http://code.google.com/p/robotframework-ride/issues/detail?id=798 loop = wx.EventLoop() wx.EventLoop.SetActive(loop) yield del loop
class RIDE(wx.App): def __init__(self, path=None, updatecheck=True): self._initial_path = path self._updatecheck = updatecheck context.APP = self wx.App.__init__(self, redirect=False) def OnInit(self): self.settings = RideSettings() librarydatabase.initialize_database() self.preferences = Preferences(self.settings) self.namespace = Namespace(self.settings) self._controller = ChiefController(self.namespace, self.settings) self.frame = RideFrame(self, self._controller) self._editor_provider = EditorProvider() self._plugin_loader = PluginLoader(self, self._get_plugin_dirs(), context.get_core_plugins()) self._plugin_loader.enable_plugins() self.editor = self._get_editor() self.editor.show() self._load_data() self.frame.tree.populate(self.model) self.frame.tree.set_editor(self.editor) self._publish_system_info() if self._updatecheck: UpdateNotifierController( self.settings).notify_update_if_needed(UpdateDialog) wx.CallLater(200, ReleaseNotes(self).bring_to_front) return True def _publish_system_info(self): RideLogMessage(context.SYSTEM_INFO).publish() @property def model(self): return self._controller def _get_plugin_dirs(self): return [ self.settings.get_path('plugins'), os.path.join(self.settings['install root'], 'site-plugins'), contrib.CONTRIB_PATH ] def _get_editor(self): from robotide.editor import EditorPlugin for pl in self._plugin_loader.plugins: if isinstance(pl._plugin, EditorPlugin): return pl._plugin def _load_data(self): path = self._initial_path or self._get_latest_path() if path: with self.active_event_loop(): observer = LoadProgressObserver(self.frame) self._controller.load_data(path, observer) def _get_latest_path(self): recent = self._get_recentfiles_plugin() if not recent or not recent.recent_files: return None return recent.recent_files[0] def _get_recentfiles_plugin(self): from robotide.recentfiles import RecentFilesPlugin for pl in self.get_plugins(): if isinstance(pl._plugin, RecentFilesPlugin): return pl._plugin def get_plugins(self): return self._plugin_loader.plugins def register_preference_panel(self, panel_class): '''Add the given panel class to the list of known preference panels''' self.preferences.add(panel_class) def unregister_preference_panel(self, panel_class): '''Remove the given panel class from the list of known preference panels''' self.preferences.remove(panel_class) def register_editor(self, object_class, editor_class, activate): self._editor_provider.register_editor(object_class, editor_class, activate) def unregister_editor(self, object_class, editor_class): self._editor_provider.unregister_editor(object_class, editor_class) def activate_editor(self, object_class, editor_class): self._editor_provider.set_active_editor(object_class, editor_class) def get_editors(self, object_class): return self._editor_provider.get_editors(object_class) def get_editor(self, object_class): return self._editor_provider.get_editor(object_class) @contextmanager def active_event_loop(self): # With wxPython 2.9.1, ProgressBar.Pulse breaks if there's no active # event loop. # See http://code.google.com/p/robotframework-ride/issues/detail?id=798 loop = wx.EventLoop() wx.EventLoop.SetActive(loop) yield del loop
class MainWindow(QMainWindow): def setupUi(self): self.__initActions() self.ui.statusLabel = QLabel() self.ui.statusLabel.setText("Not running") self.ui.statusbar.addPermanentWidget(self.ui.statusLabel) self.ui.statusIcon = QLabel() self.ui.statusIcon.setPixmap(QPixmap(":/icons/images/inferior_not_running.png")) self.ui.statusbar.addPermanentWidget(self.ui.statusIcon) #def setupGraph(self): #self.scene = QGraphicsScene() #self.c2 = Composite() #self.c1 = Composite() #self.c1.addItem(LeafEntry("exp1", "val11")) #self.c1.addItem(LeafEntry("exp2 long", "val22")) #self.c2.addItem(LeafEntry("exp2 even longer", "val22")) #self.c2.addItem(CompositeEntry("subcomp", self.c1)) #self.c2.setFlags(QGraphicsItem.ItemIsSelectable | QGraphicsItem.ItemIsMovable) #self.scene.addItem(self.c2) def __initActions(self): self.act = Actions(self) # debug actions self.ui.menuDebug.addAction(self.act.actions[Actions.Run]) self.ui.menuDebug.addAction(self.act.actions[Actions.Continue]) self.ui.menuDebug.addAction(self.act.actions[Actions.Interrupt]) self.ui.menuDebug.addAction(self.act.actions[Actions.Next]) self.ui.menuDebug.addAction(self.act.actions[Actions.Step]) self.ui.menuDebug.addAction(self.act.actions[Actions.Finish]) self.ui.menuDebug.addAction(self.act.actions[Actions.RunToCursor]) # file actions self.ui.menuFile.insertAction(self.ui.actionSaveSession, self.act.actions[Actions.Open]) self.ui.menuFile.addAction(self.act.actions[Actions.SaveFile]) self.ui.menuFile.addAction(self.act.actions[Actions.Exit]) # add them to menubar and also menuView to respect order self.ui.menubar.addAction(self.ui.menuFile.menuAction()) self.ui.menubar.addAction(self.ui.menuView.menuAction()) self.ui.menubar.addAction(self.ui.menuDebug.menuAction()) self.ui.menubar.addAction(self.ui.menuHelp.menuAction()) # now make toolbar actions self.ui.Main.addAction(self.act.actions[Actions.Open]) self.ui.Main.addAction(self.act.actions[Actions.SaveFile]) self.ui.Main.addSeparator() self.ui.Main.addAction(self.act.actions[Actions.Run]) self.ui.Main.addAction(self.act.actions[Actions.Continue]) self.ui.Main.addAction(self.act.actions[Actions.Interrupt]) self.ui.Main.addAction(self.act.actions[Actions.Next]) self.ui.Main.addAction(self.act.actions[Actions.Step]) self.ui.Main.addAction(self.act.actions[Actions.Finish]) self.ui.Main.addAction(self.act.actions[Actions.RunToCursor]) self.ui.Main.addSeparator() self.ui.Main.addAction(self.act.actions[Actions.Exit]) # connect actions self.__connectActions() def __connectActions(self): # file menu self.connect(self.act.actions[Actions.Open], SIGNAL('activated()'), self.showOpenExecutableDialog) self.connect(self.act.actions[Actions.Exit], SIGNAL('activated()'), self.close) self.connect(self.act.actions[Actions.SaveFile], SIGNAL('activated()'), self.signalproxy.emitSaveCurrentFile) # debug menu self.connect(self.act.actions[Actions.Run], SIGNAL('activated()'), self.debug_controller.run) self.connect(self.act.actions[Actions.Next], SIGNAL('activated()'), self.debug_controller.next_) self.connect(self.act.actions[Actions.Step], SIGNAL('activated()'), self.debug_controller.step) self.connect(self.act.actions[Actions.Continue], SIGNAL('activated()'), self.debug_controller.cont) self.connect(self.act.actions[Actions.Interrupt], SIGNAL('activated()'), self.debug_controller.interrupt) self.connect(self.act.actions[Actions.Finish], SIGNAL('activated()'), self.debug_controller.finish) self.connect(self.act.actions[Actions.RunToCursor], SIGNAL('activated()'), self.debug_controller.inferiorUntil) QObject.connect(self.ui.actionRestoreSession, SIGNAL('activated()'), self.distributed_objects.session_manager.showRestoreSessionDialog) QObject.connect(self.ui.actionSaveSession, SIGNAL('activated()'), self.distributed_objects.session_manager.showSaveSessionDialog) def __init__(self, parent=None): """ init UI """ QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.actionSaveSession.setEnabled(False) self.distributed_objects = DistributedObjects() self.debug_controller = self.distributed_objects.debug_controller self.settings = self.debug_controller.settings self.signalproxy = self.distributed_objects.signal_proxy self.pluginloader = PluginLoader(self.distributed_objects) #init RecentFileHandler nrRecentFiles = 5 self.initRecentFileHandler(nrRecentFiles) QObject.connect(self.debug_controller, SIGNAL('executableOpened'), self.showExecutableName) # signal proxy QObject.connect(self.signalproxy, SIGNAL('inferiorIsRunning(PyQt_PyObject)'), self.targetStartedRunning, Qt.QueuedConnection) QObject.connect(self.signalproxy, SIGNAL('inferiorHasStopped(PyQt_PyObject)'), self.targetStopped, Qt.QueuedConnection) QObject.connect(self.signalproxy, SIGNAL('inferiorHasExited(PyQt_PyObject)'), self.targetExited, Qt.QueuedConnection) QObject.connect(self.signalproxy, SIGNAL('addDockWidget(PyQt_PyObject, QDockWidget, PyQt_PyObject)'), self.addPluginDockWidget) QObject.connect(self.signalproxy, SIGNAL('removeDockWidget(QDockWidget)'), self.removeDockWidget) QObject.connect(self.pluginloader, SIGNAL('insertPluginAction(PyQt_PyObject)'), self.addPluginAction) QObject.connect(self.ui.actionSavePlugins, SIGNAL('activated()'), self.showSavePluginsDialog) QObject.connect(self.ui.actionLoadPlugins, SIGNAL('activated()'), self.showLoadPluginsDialog) # Add editor to main window. self.ui.gridLayout.addWidget(self.distributed_objects.editor_controller.editor_view, 0, 0, 1, 1) self.pluginloader.addAvailablePlugins() # Tell everyone to insert their dock widgets into the main window self.distributed_objects.signal_proxy.insertDockWidgets() # get filelist dockwidget self.filelist_dockwidget = self.findChild(QDockWidget, "FileListView"); QObject.connect(self.debug_controller, SIGNAL('executableOpened'), self.filelist_dockwidget.raise_) self.setWindowFilePath("<none>") self.setupUi() self.createInitialWindowPlacement() self.readSettings() def addPluginDockWidget(self, area, widget, addToggleViewAction): self.addDockWidget(area, widget) if addToggleViewAction == True: self.ui.menuShow_View.addAction(widget.toggleViewAction()) def addPluginAction(self, Action): """ show plugin as menu entry """ self.ui.menuPlugins.addAction(Action) def createInitialWindowPlacement(self): """ Saves the window and widget placement after first start of program. """ #check if settings do not exist initExists = self.settings.contains("InitialWindowPlacement/geometry") if initExists == False: self.breakpointWidget = self.findChild(QDockWidget, "BreakpointView") self.fileListWidget = self.findChild(QDockWidget, "FileListView") self.dataGraphWidget = self.findChild(QDockWidget, "DataGraphView") self.watchWidget = self.findChild(QDockWidget, "WatchView") self.localsWidget = self.findChild(QDockWidget, "LocalsView") self.stackWidget = self.findChild(QDockWidget, "StackView") self.tracepointWidget = self.findChild(QDockWidget, "TracepointView") self.gdbIoWidget = self.findChild(QDockWidget, "GdbIoView") self.pyIoWidget = self.findChild(QDockWidget, "PyIoView") self.inferiorIoWidget = self.findChild(QDockWidget, "InferiorIoView") #tabify widgets to initial state and save settings self.tabifyDockWidget(self.fileListWidget, self.dataGraphWidget) self.tabifyDockWidget(self.watchWidget, self.localsWidget) self.tabifyDockWidget(self.localsWidget, self.stackWidget) self.tabifyDockWidget(self.stackWidget, self.breakpointWidget) self.tabifyDockWidget(self.breakpointWidget, self.tracepointWidget) self.tabifyDockWidget(self.gdbIoWidget, self.pyIoWidget) self.tabifyDockWidget(self.pyIoWidget, self.inferiorIoWidget) self.settings.setValue("InitialWindowPlacement/geometry", self.saveGeometry()) self.settings.setValue("InitialWindowPlacement/windowState", self.saveState()) def initRecentFileHandler(self, nrRecentFiles): """ Create menu entries for recently used files and connect them to the RecentFileHandler """ # create menu entries and connect the actions to the debug controller recentFileActions = [0]*nrRecentFiles for i in range(nrRecentFiles): recentFileActions[i] = OpenRecentFileAction(self) recentFileActions[i].setVisible(False) self.ui.menuRecentlyUsedFiles.addAction(recentFileActions[i]) QObject.connect(recentFileActions[i], SIGNAL('executableOpened'), self.distributed_objects.debug_controller.openExecutable) self.RecentFileHandler = RecentFileHandler(recentFileActions, nrRecentFiles, self.distributed_objects) QObject.connect(self.debug_controller, SIGNAL('executableOpened'), self.RecentFileHandler.addToRecentFiles) def restoreInitialWindowPlacement(self): """ Restores the window placement created by createInitialWindowPlacement(). """ self.restoreGeometry(self.settings.value("InitialWindowPlacement/geometry").toByteArray()) self.restoreState(self.settings.value("InitialWindowPlacement/windowState").toByteArray()) def showOpenExecutableDialog(self): filename = str(QFileDialog.getOpenFileName(self, "Open Executable")) if (filename != ""): self.debug_controller.openExecutable(filename) def showLoadPluginsDialog(self): dialog = QFileDialog() dialog.setNameFilter("*.xml") filename = str(dialog.getOpenFileName(self, "Load plugin configuration")) if (filename != ""): self.pluginloader.getActivePlugins(filename) def showSavePluginsDialog(self): dialog = QFileDialog() dialog.setNameFilter("*.xml") filename = str(dialog.getSaveFileName(self, "Save plugin configuration")) if (filename != ""): self.pluginloader.savePluginInfo(filename) def showExecutableName(self, filename): self.ui.actionSaveSession.setEnabled(True) #enable saving session self.setWindowFilePath(filename) def targetStartedRunning(self): self.ui.statusLabel.setText("Running") self.ui.statusIcon.setPixmap(QPixmap(":/icons/images/inferior_running.png")); def targetStopped(self, rec): self.ui.statusLabel.setText("Stopped") self.ui.statusIcon.setPixmap(QPixmap(":/icons/images/inferior_stopped.png")); def targetExited(self): self.ui.statusLabel.setText("Not running") self.ui.statusIcon.setPixmap(QPixmap(":/icons/images/inferior_not_running.png")); def closeEvent(self, event): if self.distributed_objects.editor_controller.closeOpenedFiles() == False: event.ignore() #closing source files may be canceled by user else: self.settings.setValue("geometry", self.saveGeometry()) self.settings.setValue("windowState", self.saveState()) QMainWindow.closeEvent(self, event) self.pluginloader.savePluginInfo() def readSettings(self): self.restoreGeometry(self.settings.value("geometry").toByteArray()) self.restoreState(self.settings.value("windowState").toByteArray()) def addWatch(self, word): word = str(word) print word
def main(argv): polling_interval = config.getint("EvoHome", "pollingInterval") debug_logging = False try: opts, args = getopt.getopt(argv, "hdi:", ["help", "interval", "debug="]) except getopt.GetoptError: print 'evohome-logger.py -h for help' sys.exit(2) for opt, arg in opts: if opt in ('-h', '--help'): print 'evohome-logger, version 0.1' print '' print 'usage: evohome-logger.py [-h|--help] [-d|--debug <true|false>] [-i|--interval <interval>]' print '' print ' h|help : display this help page' print ' d|debug : turn on debug logging, regardless of the config.ini setting' print ' i|interval <interval> : Log temperatures every <polling interval> seconds, overriding the config.ini value' print ' If 0 is specified then temperatures are logged only once and the program exits' print '' sys.exit() elif opt in ('-i', '--interval'): if arg.isdigit(): polling_interval = int(arg) elif opt in ('-d', '--debug'): debug_logging = True if debug_logging or is_debugging_enabled('DEFAULT'): logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) global logger logger = logging.getLogger('evohome-logger::') if polling_interval == 0: logger.debug('One-off run') else: logger.debug('Polling every %s seconds', polling_interval) logger.info("==Started==") global plugins sections = filter(lambda a: a.lower() != 'DEFAULT', config.sections()) plugins = PluginLoader(sections) continue_polling = True try: while continue_polling: timestamp = datetime.utcnow() timestamp = timestamp.replace(microsecond=0) temperatures = get_temperatures() if temperatures: text_temperatures = '%s: ' % datetime.utcnow().strftime( '%Y-%m-%d %H:%M:%S') for t in temperatures: text_temperatures += "%s (%s A" % (t.zone, t.actual) if t.target is not None: text_temperatures += ", %s T" % t.target text_temperatures += ') ' logger.info(text_temperatures) for i in plugins.outputs: plugin = plugins.get(i) logger.debug('Writing temperatures to %s', plugin.plugin_name) try: plugin.write(timestamp, temperatures) except Exception, e: logger.error('Error trying to write to %s: %s', plugin.plugin_name, str(e)) if polling_interval == 0: continue_polling = False else: logger.info("Going to sleep for %s minutes", (polling_interval / 60)) time.sleep(polling_interval) except Exception, e: logger.error('An error occurred, trying again in 15 seconds: %s', str(e)) time.sleep(15)
def test_load_empty_file(self): sut = PluginLoader() sut.load_file(self.plugin_file.name) self.assertEquals({}, sut.plugins)
def test_empty_directory(self): sut = PluginLoader() sut.load_directory(self.plugin_dir) self.assertEqual({}, sut.plugins)
class RIDE(wx.App): def __init__(self, path=None, updatecheck=True): self._initial_path = path self._updatecheck = updatecheck context.APP = self wx.App.__init__(self, redirect=False) def OnInit(self): self.settings = RideSettings() librarydatabase.initialize_database() self.preferences = Preferences(self.settings) self.namespace = Namespace(self.settings) self._controller = Project(self.namespace, self.settings) self.frame = RideFrame(self, self._controller) self._editor_provider = EditorProvider() self._plugin_loader = PluginLoader(self, self._get_plugin_dirs(), context.get_core_plugins()) self._plugin_loader.enable_plugins() self.editor = self._get_editor() self.editor.show() self._load_data() self.frame.tree.populate(self.model) self.frame.tree.set_editor(self.editor) self._publish_system_info() if self._updatecheck: UpdateNotifierController(self.settings).notify_update_if_needed(UpdateDialog) wx.CallLater(200, ReleaseNotes(self).bring_to_front) return True def _publish_system_info(self): RideLogMessage(context.SYSTEM_INFO).publish() @property def model(self): return self._controller def _get_plugin_dirs(self): return [self.settings.get_path('plugins'), os.path.join(self.settings['install root'], 'site-plugins'), contrib.CONTRIB_PATH] def _get_editor(self): from robotide.editor import EditorPlugin for pl in self._plugin_loader.plugins: if isinstance(pl._plugin, EditorPlugin): return pl._plugin def _load_data(self): path = self._initial_path or self._get_latest_path() if path: with self.active_event_loop(): observer = LoadProgressObserver(self.frame) self._controller.load_data(path, observer) def _get_latest_path(self): recent = self._get_recentfiles_plugin() if not recent or not recent.recent_files: return None return recent.recent_files[0] def _get_recentfiles_plugin(self): from robotide.recentfiles import RecentFilesPlugin for pl in self.get_plugins(): if isinstance(pl._plugin, RecentFilesPlugin): return pl._plugin def get_plugins(self): return self._plugin_loader.plugins def register_preference_panel(self, panel_class): '''Add the given panel class to the list of known preference panels''' self.preferences.add(panel_class) def unregister_preference_panel(self, panel_class): '''Remove the given panel class from the list of known preference panels''' self.preferences.remove(panel_class) def register_editor(self, object_class, editor_class, activate): self._editor_provider.register_editor(object_class, editor_class, activate) def unregister_editor(self, object_class, editor_class): self._editor_provider.unregister_editor(object_class, editor_class) def activate_editor(self, object_class, editor_class): self._editor_provider.set_active_editor(object_class, editor_class) def get_editors(self, object_class): return self._editor_provider.get_editors(object_class) def get_editor(self, object_class): return self._editor_provider.get_editor(object_class) @contextmanager def active_event_loop(self): # With wxPython 2.9.1, ProgressBar.Pulse breaks if there's no active # event loop. # See http://code.google.com/p/robotframework-ride/issues/detail?id=798 loop = wx.EventLoop() wx.EventLoop.SetActive(loop) yield del loop
def main(argv): polling_interval = config.getint("EvoHome", "pollingInterval") debug_logging = False try: opts, args = getopt.getopt(argv, "hdi:", ["help","interval", "debug="]) except getopt.GetoptError: print 'evohome-logger.py -h for help' sys.exit(2) for opt, arg in opts: if opt in ('-h', '--help'): print 'evohome-logger, version 0.1' print '' print 'usage: evohome-logger.py [-h|--help] [-d|--debug <true|false>] [-i|--interval <interval>]' print '' print ' h|help : display this help page' print ' d|debug : turn on debug logging, regardless of the config.ini setting' print ' i|interval <interval> : Log temperatures every <polling interval> seconds, overriding the config.ini value' print ' If 0 is specified then temperatures are logged only once and the program exits' print '' sys.exit() elif opt in ('-i', '--interval'): if arg.isdigit(): polling_interval = int(arg) elif opt in ('-d', '--debug'): debug_logging = True if debug_logging or is_debugging_enabled('DEFAULT'): logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) global logger logger = logging.getLogger('evohome-logger::') if polling_interval == 0: logger.debug('One-off run') else: logger.debug('Polling every %s seconds', polling_interval) logger.info("==Started==") global plugins sections = filter(lambda a: a.lower() != 'DEFAULT', config.sections()) plugins = PluginLoader(sections) continue_polling = True try: while continue_polling: timestamp = datetime.utcnow() timestamp = timestamp.replace(microsecond=0) temperatures = get_temperatures() if temperatures: text_temperatures = '%s: ' % datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S') for t in temperatures: text_temperatures += "%s (%s A" % (t.zone, t.actual) if t.target is not None: text_temperatures += ", %s T" % t.target text_temperatures += ') ' logger.info(text_temperatures) for i in plugins.outputs: plugin = plugins.get(i) logger.debug('Writing temperatures to %s', plugin.plugin_name) try: plugin.write(timestamp, temperatures) except Exception, e: logger.error('Error trying to write to %s: %s', plugin.plugin_name, str(e)) if polling_interval == 0: continue_polling = False else: logger.info("Going to sleep for %s minutes", (polling_interval/60)) time.sleep(polling_interval) except Exception, e: logger.error('An error occurred, trying again in 15 seconds: %s', str(e)) time.sleep(15)
"--offline-mode", dest="offlineMode", action="store_true", default=False, help="run in offline mode i.e don't attempt to auth via minecraft.net") parser.add_option( "-c", "--disable-console-colours", dest="disableAnsiColours", action="store_true", default=False, help="print minecraft chat colours as their equivalent ansi colours") # pluginLoader pluginLoader = PluginLoader("plugins") pluginLoader.loadPlugins(parser) (options, args) = parser.parse_args() pluginLoader.notifyOptions(options) if (options.username != ""): user = options.username else: user = raw_input("Enter your username: "******""): passwd = options.password elif (not options.offlineMode): passwd = getpass.getpass("Enter your password: ")
async def main(): # TODO: this really needs to be replaced # probably using https://docs.python.org/3.8/library/functools.html#functools.partial global client global plugin_loader # Read config file config = Config("config.yaml") # Configure the database store = Storage(config.database_filepath) # Configuration options for the AsyncClient client_config = AsyncClientConfig( max_limit_exceeded=0, max_timeouts=0, store_sync_tokens=True, encryption_enabled=config.enable_encryption, ) # Initialize the matrix client client = AsyncClient( config.homeserver_url, config.user_id, device_id=config.device_id, store_path=config.store_filepath, config=client_config, ) # instantiate the pluginLoader plugin_loader = PluginLoader() # Set up event callbacks callbacks = Callbacks(client, store, config, plugin_loader) client.add_event_callback(callbacks.message, (RoomMessageText, )) client.add_event_callback(callbacks.invite, (InviteEvent, )) client.add_event_callback(callbacks.event_unknown, (UnknownEvent, )) client.add_response_callback(run_plugins) # Keep trying to reconnect on failure (with some time in-between) error_retries: int = 0 while True: try: # Try to login with the configured username/password try: login_response = await client.login( password=config.user_password, device_name=config.device_name, ) # Check if login failed if type(login_response) == LoginError: logger.error( f"Failed to login: {login_response.message}, retrying in 15s... ({error_retries})" ) # try logging in a few times to work around temporary login errors during homeserver restarts if error_retries < 3: error_retries += 1 await sleep(15) continue else: return False else: error_retries = 0 except LocalProtocolError as e: # There's an edge case here where the user enables encryption but hasn't installed # the correct C dependencies. In that case, a LocalProtocolError is raised on login. # Warn the user if these conditions are met. if config.enable_encryption: logger.fatal( "Failed to login and encryption is enabled. Have you installed the correct dependencies? " "https://github.com/poljar/matrix-nio#installation") return False else: # We don't know why this was raised. Throw it at the user logger.fatal(f"Error logging in: {e}") # Login succeeded! # Sync encryption keys with the server # Required for participating in encrypted rooms if client.should_upload_keys: await client.keys_upload() logger.info(f"Logged in as {config.user_id}") await client.sync_forever(timeout=30000, full_state=True) except (ClientConnectionError, ServerDisconnectedError, AttributeError, asyncio.TimeoutError) as err: logger.debug(err) logger.warning( f"Unable to connect to homeserver, retrying in 15s...") # Sleep so we don't bombard the server with login requests await sleep(15) finally: # Make sure to close the client connection on disconnect await client.close()
parser.add_option("-p", "--password", dest="password", default="", help="password to log in with") parser.add_option("-s", "--server", dest="server", default="", help="server to connect to") parser.add_option("-x", "--offline-mode", dest="offlineMode", action="store_true", default=False, help="run in offline mode i.e don't attempt to auth via minecraft.net") parser.add_option("-c", "--disable-console-colours", dest="disableAnsiColours", action="store_true", default=False, help="print minecraft chat colours as their equivalent ansi colours") # pluginLoader pluginLoader = PluginLoader("plugins") pluginLoader.loadPlugins(parser) (options, args) = parser.parse_args() pluginLoader.notifyOptions(options) if (options.username != ""): user = options.username else: user = raw_input("Enter your username: "******""): passwd = options.password elif (not options.offlineMode): passwd = getpass.getpass("Enter your password: ")