def showExportFormats(self): PluginManager.instance().loadPlugins() qWarning(self.tr("Export formats:")) formats = PluginManager.objects() for format in formats: if format.hasCapabilities(MapFormat.Write): qWarning(" " + format.nameFilter()) self.quit = True
def main(): manager = PluginManager() manager.setPluginPaths(["plugins"]) manager.loadPlugins() app = QApplication(sys.argv) dialog = PluginDialog(manager) dialog.show() app.exec_()
class Client(object): def __init__(self): self.pluginmanager = PluginManager() self.pluginmanager.loadPlugins() @classmethod def loadFont(cls): """加载外部字体""" path = os.path.join(Settings().dataDir, "fonts") for font in os.listdir(path): QFontDatabase.addApplicationFont(os.path.join(path, font))
def __init__(self, capabilities, initialFilter): self.mFilter = initialFilter self.mFormats = QList() self.mFormatByNameFilter = QMap() def t(self, format): if (format.hasCapabilities(capabilities)): nameFilter = format.nameFilter() self.mFilter += ";;" self.mFilter += nameFilter self.mFormats.append(format) self.mFormatByNameFilter.insert(nameFilter, format) PluginManager.each(self, t)
class Collector: """ Main command line interface """ def __init__(self): """ Initialize the plugin manager """ self.__pluginmanager = PluginManager() def parse_input(self): """ Validates user input and delegates to the plugin manager """ if len(sys.argv) > 1: print "The following plugins are available:\n" self.__pluginmanager.help_all() else: # Call the command in the given plugin with the # remaining arguments return self.__pluginmanager.call()
def __init__(self, configdir, file_to_open=None): super().__init__(['kalpana']) self.objects = create_objects(configdir) self.objects['mainwindow'].create_ui(self.objects['chaptersidebar'], self.objects['textarea'], self.objects['terminal']) # Plugins self.pluginmanager = PluginManager(self.objects.copy()) self.objects['terminal'].update_commands(self.pluginmanager.plugin_commands) # Signals connect_others_signals(*self.objects.values()) self.connect_own_signals() # Hotkeys set_key_shortcuts(self.objects['mainwindow'], self.objects['textarea'], self.objects['terminal'], self.pluginmanager.get_compiled_hotkeys()) self.init_hotkeys() # Load settings and get it oooon self.objects['settingsmanager'].load_settings() self.install_event_filter() # Try to open a file and die if it doesn't work, or make a new file if file_to_open: if not self.objects['textarea'].open_file(file_to_open): self.close() else: self.objects['textarea'].set_filename(new=True) # FIN self.objects['mainwindow'].show()
def __init__(self, pluginManager=None, localBrowsingMode=True): """localBrowsingMode: not implemented yet""" self.localBrowsingMode = localBrowsingMode self.pluginManager = pluginManager if self.pluginManager is None: from pluginmanager import PluginManager self.pluginManager = PluginManager() self.data = {} self.timestamp = datetime.datetime.today().strftime("%Y%m%d%H%M%S") self.templatePath = None self.htmlfilename = None self.path_root = None self.htmlfiletitle = None self.title = None self.exportMode = ExportSettings.PLAIN_SIMPLE self._controls = None self.coordsInWGS84 = False self.canvas = None self.mapSettings = None self.baseExtent = None self.crs = None # cache self._mapTo3d = None self._quadtree = None self._templateConfig = None
def load(fileName, mapFormat = None): error = '' tmxMapFormat = TmxMapFormat() if (not mapFormat and not tmxMapFormat.supportsFile(fileName)): # Try to find a plugin that implements support for this format formats = PluginManager.objects() for format in formats: if (format.supportsFile(fileName)): mapFormat = format break map = None errorString = '' if mapFormat: map = mapFormat.read(fileName) errorString = mapFormat.errorString() else: map = tmxMapFormat.read(fileName) errorString = tmxMapFormat.errorString() if (not map): error = errorString return None, error mapDocument = MapDocument(map, fileName) if mapFormat: mapDocument.setReaderFormat(mapFormat) if mapFormat.hasCapabilities(MapFormat.Write): mapDocument.setWriterFormat(mapFormat) return mapDocument, error
def __init__(self, configdir, file_to_open=None, silentmode=False): super().__init__(['kalpana']) self.objects = create_objects(configdir) self.objects['mainwindow'].create_ui(self.objects['chaptersidebar'], self.objects['textarea'], self.objects['terminal']) # Plugins self.pluginmanager = PluginManager(self.objects.copy(), silentmode) self.objects['terminal'].update_commands(self.pluginmanager.plugin_commands) # Signals connect_others_signals(*self.objects.values()) self.connect_own_signals() # Hotkeys set_key_shortcuts(self.objects['mainwindow'], self.objects['textarea'], self.objects['terminal'], self.pluginmanager.get_compiled_hotkeys()) self.init_hotkeys() # Load settings and get it oooon self.objects['settingsmanager'].load_settings() self.install_event_filter() # Try to open a file and die if it doesn't work, or make a new file if file_to_open: if os.path.exists(file_to_open): if not self.objects['textarea'].open_file(file_to_open): print('Bad encoding! Use utf-8 or latin1.') self.close() else: # If the path doesn't exist, open a new file with the name self.objects['textarea'].document().setModified(True) self.objects['textarea'].set_filename(file_to_open) else: self.objects['textarea'].set_filename(new=True) self.objects['textarea'].document().setModified(True) # FIN self.objects['mainwindow'].show()
class DAgentPluginManager(object): def __init__(self, plugindir, logger): self.logger = WrapLogger(logger) self.pluginmanager = PluginManager(plugindir, self.logger) self.pluginmanager.loadPlugins(IMapiDAgentPlugin) def PostConverting(self, session, addrbook, store, folder, message): return self.pluginmanager.processPluginFunction( 'PostConverting', session, addrbook, store, folder, message) def PreDelivery(self, session, addrbook, store, folder, message): return self.pluginmanager.processPluginFunction( 'PreDelivery', session, addrbook, store, folder, message) def PostDelivery(self, session, addrbook, store, folder, message): return self.pluginmanager.processPluginFunction( 'PostDelivery', session, addrbook, store, folder, message) def PreRuleProcess(self, session, addrbook, store, rulestable): return self.pluginmanager.processPluginFunction( 'PreRuleProcess', session, addrbook, store, rulestable) def SendNewMailNotify(self, session, addrbook, store, folder, message): return self.pluginmanager.processPluginFunction( 'SendNewMailNotify', session, addrbook, store, folder, message)
def __init__ (self, view, viewcontrol, type): Control.__init__ (self, view) self.vc = viewcontrol self.pm = PluginManager.getInstance() if type in [WizardPlugin.T_INPUT, WizardPlugin.T_OUTPUT]: self.type = type # TODO Parameter else: raise Exception("Invalid PluginType")
def init(self): self.setHasConfigurationInterface(False) self.setAspectRatioMode(Plasma.Square) self.theme = Plasma.Svg(self) self.setBackgroundHints(Plasma.Applet.DefaultBackground) self.layout = QGraphicsLinearLayout(Qt.Vertical, self.applet) self.getLogin() self.setHasConfigurationInterface(True) self.label = Plasma.Label(self.applet) self.label.setText(i18n("Welcome to the Multimobilewidget")) nrlabel = Plasma.Label(self.applet) nrlabel.setText(i18n("Phonenr(s)")) self.messagelabel = Plasma.Label(self.applet) self.messagelabel.setText(i18n("Message - 0 signs used")) self.nrfield = Plasma.LineEdit() self.messageText = Plasma.TextEdit(self.applet) self.messageText.nativeWidget() sendButton = Plasma.PushButton(self.applet) sendButton.setText(i18n("Send the SMS!")) sendButton.resize(20, 40) configButton = Plasma.PushButton(self.applet) configButton.setText("Config") configButton.resize(20, 40) self.layout.addItem(self.label) self.layout.addItem(nrlabel) self.layout.addItem(self.nrfield) self.layout.addItem(self.messagelabel) self.layout.addItem(self.messageText) self.layout.addItem(sendButton) self.layout.addItem(configButton) self.applet.setLayout(self.layout) self.connect(sendButton, SIGNAL("clicked()"), self.onSendClick) self.connect(configButton, SIGNAL("clicked()"), self.onConfigClick) self.connect(self.messageText, SIGNAL("textChanged()"), self.onTextChanged) fullPath = str(self.package().path()) self.providerPluginManager = PluginManager("multimobilewidget/contents/code/providerplugins/","", providerplugins.Provider.Provider) self.providerpluginlist = self.providerPluginManager.getPluginClassList() for provider in self.providerpluginlist: self.ui.providerList.addItem(provider.getObjectname()) print provider.getObjectname() self.ui.providerList.setCurrentRow(0) self.adressplugins = PluginManager("multimobilewidget/contents/code/adressplugins/","", adressplugins.AdressPlugin.AdressPlugin) self.adresspluginlist = self.adressplugins.getPluginClassList() self.adressList = list()
class CLI: """ Main command line interface. """ def __init__(self): """ Initialize the plugin manager. """ self.__pluginmanager = PluginManager() def parse_input(self): """ Validates user input and delegates execution to the plugin manager. """ if len(sys.argv) < 2: print "Usage: kahuna <plugin> <command> [<options>]" print "The following plugins are available:\n" self.__pluginmanager.help_all() elif len(sys.argv) == 2: print "Usage: kahuna <plugin> <command> [<options>]" # Call the given pugin without command to print the help of the plugin return self.__pluginmanager.call(sys.argv[1], None, None) else: # Call the command in the given plugin with the remaining of the arguments return self.__pluginmanager.call(sys.argv[1], sys.argv[2], sys.argv[3:])
def __init__(self, bus_name, options, object_path="/org/wicd/daemon"): ''' Creates a new WicdDaemon object. ''' dbus.service.Object.__init__(self, bus_name=bus_name, object_path=object_path) self.options = options self.interface_manager = InterfaceManager(self.StatusChange) self.plugin_manager = PluginManager(self) if not options.no_load_configuration: self.LoadConfiguration() self.plugin_manager.action('start')
def start(): #repeater() #加载所有插件 PluginManager.LoadAllPlugin() headers = redis_handle.iteritems() #TODO 多线程 #遍历所有插件 for SingleModel in __ALLMODEL__: plugins = SingleModel.GetPluginObject() for item in plugins: #调用接口 item.start(headers)
class CLI: """ Main command line interface """ def __init__(self): """ Initialize the plugin manager """ self.__pluginmanager = PluginManager() def parse_input(self): """ Validates user input and delegates to the plugin manager """ if len(sys.argv) < 2: print "Usage: kahuna <plugin> <command> [<options>]" print "The following plugins are available:\n" self.__pluginmanager.help_all() elif len(sys.argv) == 2: print "Usage: kahuna <plugin> <command> [<options>]" # Call the given plugin without command to print # the help of the plugin return self.__pluginmanager.call(sys.argv[1], None, None) else: # Call the command in the given plugin with the # remaining of the arguments return self.__pluginmanager.call(sys.argv[1], sys.argv[2], sys.argv[3:])
class Coffesploit(object): """Main Class""" def __init__(self, basepath): self.target = Target() self.tool = None self.pluginmanager = PluginManager() self.helper = Help() self.basepath = basepath def set_target(self,rhost=None,url=None): if url is not None: self.target.seturl(url) if rhost is not None: self.target.setrhost(rhost) def set(self, arg1, arg2): self.pluginmanager.current_plugin.set_arg(arg1,arg2) def show(self,arg): if arg == "target": print "ip:",self.target.getrhost(),"url:",self.target.geturl() if arg == "status": if self.pluginmanager.current_plugin is not None: self.pluginmanager.plugin_status() if arg == "version": print "Currnt Version:",self.version() def use(self,arg): self.pluginmanager.load_plugin(arg) def run(self): self.pluginmanager.plugin_run() self.pluginmanager.plugin_result() def main_help (self): return self.helper.main_help() def main_list (self): return self.pluginmanager.importer.get_plugins_list() def help(self,arg): """show help info of t""" if arg == "target": self.helper.help_set_tartget() if arg == "show": self.helper.help_show() if arg == "use": self.helper.help_use() def exit(self): exit(0) def version(self): return __Version__
def __init__(self, parent=None): super().__init__(parent) self.setObjectName("ConsoleDock") self.setWindowTitle(self.tr("Debug Console")) widget = QWidget(self) layout = QVBoxLayout(widget) layout.setContentsMargins(5, 5, 5, 5) self.plainTextEdit = QPlainTextEdit() self.plainTextEdit.setReadOnly(True) self.plainTextEdit.setStyleSheet( QString("QAbstractScrollArea {" " background-color: black;" " color:green;" "}")) layout.addWidget(self.plainTextEdit) for output in PluginManager.objects(LoggingInterface): self.registerOutput(output) PluginManager.instance().objectAdded.connect(self.onObjectAdded) self.setWidget(widget)
def __init__(self, parent = None): super().__init__(parent) self.setObjectName("ConsoleDock") self.setWindowTitle(self.tr("Debug Console")) widget = QWidget(self) layout = QVBoxLayout(widget) layout.setContentsMargins(5, 5, 5, 5) self.plainTextEdit = QPlainTextEdit() self.plainTextEdit.setReadOnly(True) self.plainTextEdit.setStyleSheet(QString( "QAbstractScrollArea {" " background-color: black;" " color:green;" "}" )) layout.addWidget(self.plainTextEdit) for output in PluginManager.objects(LoggingInterface): self.registerOutput(output) PluginManager.instance().objectAdded.connect(self.onObjectAdded) self.setWidget(widget)
def __init__(self, mainWindow, parent = None): super().__init__(parent) self.mMainWindow = mainWindow self.setRootIsDecorated(False) self.setHeaderHidden(True) self.setItemsExpandable(False) self.setUniformRowHeights(True) self.setDragEnabled(True) self.setDefaultDropAction(Qt.MoveAction) prefs = preferences.Preferences.instance() prefs.mapsDirectoryChanged.connect(self.onMapsDirectoryChanged) mapsDir = QDir(prefs.mapsDirectory()) if (not mapsDir.exists()): mapsDir.setPath(QDir.currentPath()) self.mFSModel = FileSystemModel(self) self.mFSModel.setRootPath(mapsDir.absolutePath()) nameFilters = QStringList("*.tmx") # The file system model name filters are plain, whereas the plugins expose # a filter as part of the file description filterFinder = QRegExp("\\((\\*\\.[^\\)\\s]*)") for format in PluginManager.objects(MapFormat): if not (format.capabilities() & MapFormat.Read): continue filter = format.nameFilter() if (filterFinder.indexIn(filter) != -1): nameFilters.append(filterFinder.cap(1)) self.mFSModel.setFilter(QDir.AllDirs | QDir.Files | QDir.NoDot) self.mFSModel.setNameFilters(nameFilters) self.mFSModel.setNameFilterDisables(False) # hide filtered files self.setModel(self.mFSModel) headerView = self.header() headerView.hideSection(1) # Size column headerView.hideSection(2) headerView.hideSection(3) self.setRootIndex(self.mFSModel.index(mapsDir.absolutePath())) self.header().setStretchLastSection(False) self.header().setSectionResizeMode(0, QHeaderView.Stretch) self.activated.connect(self.onActivated) self.mMainWindow = None self.mFSModel = None
def updatePluginDependencies(self): for spec in PluginManager.getInstance().loadQueue(): disableIndirectly = False if spec.name() in self.whitelist: continue for depSpec in spec.dependencySpecs(): if not depSpec.isEnabled() or depSpec.isDisabledIndirectly(): disableIndirectly = True break childItem = self.specToItem[spec] childItem.setDisabled(disableIndirectly) if disableIndirectly == spec.isDisabledIndirectly(): continue spec.setDisabledIndirectly(disableIndirectly) if childItem.parent() and not childItem.parent().isExpanded(): childItem.parent().setExpanded(True)
def run(self): from vectorobject import ObjectTypeManager from pluginmanager import PluginManager from qgis2threejsdialog import Qgis2threejsDialog if self.objectTypeManager is None: self.objectTypeManager = ObjectTypeManager() if self.pluginManager is None: self.pluginManager = PluginManager() # restore export settings proj_path = QgsProject.instance().fileName() settingsFilePath = proj_path + ".qto3settings" if proj_path else None if not self.exportSettings or settingsFilePath != self.settingsFilePath: if settingsFilePath and os.path.exists(settingsFilePath): self.loadExportSettings(settingsFilePath) logMessage(u"Restored export settings of this project: {0}".format( os.path.basename(proj_path))) # QgsProject.instance().title() dialog = Qgis2threejsDialog( self.iface, self.objectTypeManager, self.pluginManager, self.exportSettings, self.lastTreeItemData) # show dialog dialog.show() ret = dialog.exec_() self.exportSettings = dialog.settings(True) item = dialog.ui.treeWidget.currentItem() self.lastTreeItemData = item.data(0, Qt.UserRole) if item else None # if export succeeded, save export settings in the directory that # project file exists if ret and settingsFilePath: self.saveExportSettings(settingsFilePath) self.settingsFilePath = settingsFilePath
def initialize(self, arguments): self.initializeCalled = False obj = QObject(self) obj.setObjectName("MyPlugin1") self.addAutoReleaseObject(obj) found2 = False found3 = False for otherPluginObj in PluginManager.getInstance().allObjects(): if otherPluginObj.objectName() == "MyPlugin2": found2 = True elif otherPluginObj.objectName() == "MyPlugin3": found3 = True if found2 and found3: return True, "No error" errorString = "object(s) missing from plugin(s):" if not found2: errorString += "plugin2" if not found3: errorString += "plugin3" return False, errorString
def run(self): if self.options.listchats: self._list_chats() return self.__connect_signals() self.plugin_manager = PluginManager(PLUGINS_CONFIG) for event in SKYPE_EVENTS: self.skype.RegisterEventHandler( event, self.plugin_manager.on_event(event)) log.info("*** Entering main loop. Press CTRL+C to quit ***") while self._attached_to_skype(): for plugin in self.plugin_manager.plugins: messages = plugin.flush_output() for message in messages: try: message.send(self.skype) except PluginOutputError, e: log.error("Unable to send message %s by plugin %s: %s", plugin, message.text, e) time.sleep(self.options.sleep_time)
def main(): args = parser.parse_args() # Initialize the plugin manager by giving it the plugin directory path. # Then import all the plugins in the directory. You can also import individual plugins. plugin_manager = PluginManager(plugin_folder=args.plugin_dir) plugin_manager.import_all_plugins() # Plugin manager imports all plugins in the plugin at runtime. # The user then tells it which plugin to use based off of the file name of the plugin. for name, info in plugin_manager.get_available_plugins().items(): plugin_module = plugin_manager.get_imported_plugin_module(name) class_ = getattr(plugin_module, "Plugin") current_plugin = class_() # Do a quick check to make sure the plugin exists and if it does execute it. if current_plugin: current_plugin.execute()
def readTileset(fileName): error = '' # Try the first registered tileset format that claims to support the file for format in PluginManager.objects(TilesetFormat): if format.supportsFile(fileName): tileset = format.read(fileName) if (error): if (not tileset): error = format.errorString() else: error = '' return tileset, error # Fall back to default reader (TSX format) reader = mapreader.MapReader() tileset = reader.readTileset(fileName) if (error): if (not tileset): error = reader.errorString() else: error = '' return tileset, error
def __init__(self, plugindir, logger): self.logger = WrapLogger(logger) self.pluginmanager = PluginManager(plugindir, self.logger) self.pluginmanager.loadPlugins(IMapiSpoolerPlugin)
def __init__(self, basepath): self.target = Target() self.tool = None self.pluginmanager = PluginManager() self.helper = Help() self.basepath = basepath
def removeObject(object): PluginManager.removeObject(object)
class GtkUI(object): def __init__(self, args): self.daemon_bps = (0, 0, 0) # Setup signals try: import gnome.ui import gnome #Suppress: Warning: Attempt to add property GnomeProgram::*** after class was initialised original_filters = warnings.filters[:] warnings.simplefilter("ignore") try: self.gnome_prog = gnome.init("Deluge", deluge.common.get_version()) finally: warnings.filters = original_filters self.gnome_client = gnome.ui.master_client() def on_die(*args): reactor.stop() self.gnome_client.connect("die", on_die) log.debug("GNOME session 'die' handler registered!") except Exception, e: log.warning( "Unable to register a 'die' handler with the GNOME session manager: %s", e) if deluge.common.windows_check(): from win32api import SetConsoleCtrlHandler from win32con import CTRL_CLOSE_EVENT from win32con import CTRL_SHUTDOWN_EVENT def win_handler(ctrl_type): log.debug("ctrl_type: %s", ctrl_type) if ctrl_type in (CTRL_CLOSE_EVENT, CTRL_SHUTDOWN_EVENT): reactor.stop() return 1 SetConsoleCtrlHandler(win_handler) if deluge.common.osx_check() and Gdk.WINDOWING == "quartz": import gtkosx_application self.osxapp = gtkosx_application.gtkosx_application_get() def on_die(*args): reactor.stop() self.osxapp.connect("NSApplicationWillTerminate", on_die) # Set process name again to fix gtk issue setproctitle(getproctitle()) # Attempt to register a magnet URI handler with gconf, but do not overwrite # if already set by another program. common.associate_magnet_links(False) # Make sure gtkui.conf has at least the defaults set self.config = deluge.configmanager.ConfigManager( "gtkui.conf", DEFAULT_PREFS) # We need to check on exit if it was started in classic mode to ensure we # shutdown the daemon. self.started_in_classic = self.config["classic_mode"] # Start the IPC Interface before anything else.. Just in case we are # already running. self.queuedtorrents = QueuedTorrents() self.ipcinterface = IPCInterface(args) # Initialize gdk threading Gdk.threads_init() GObject.threads_init() # We make sure that the UI components start once we get a core URI client.set_disconnect_callback(self.__on_disconnect) self.trackericons = TrackerIcons() self.sessionproxy = SessionProxy() # Initialize various components of the gtkui self.mainwindow = MainWindow() self.menubar = MenuBar() self.toolbar = ToolBar() self.torrentview = TorrentView() self.torrentdetails = TorrentDetails() self.sidebar = SideBar() self.filtertreeview = FilterTreeView() self.preferences = Preferences() self.systemtray = SystemTray() self.statusbar = StatusBar() self.addtorrentdialog = AddTorrentDialog() if deluge.common.osx_check() and Gdk.WINDOWING == "quartz": def nsapp_open_file(osxapp, filename): # Will be raised at app launch (python opening main script) if filename.endswith('Deluge-bin'): return True from deluge.ui.gtkui.ipcinterface import process_args process_args([filename]) self.osxapp.connect("NSApplicationOpenFile", nsapp_open_file) from menubar_osx import menubar_osx menubar_osx(self, self.osxapp) self.osxapp.ready() # Initalize the plugins self.plugins = PluginManager() # Show the connection manager self.connectionmanager = ConnectionManager() from twisted.internet.task import LoopingCall rpc_stats = LoopingCall(self.print_rpc_stats) rpc_stats.start(10) reactor.callWhenRunning(self._on_reactor_start) # Start the gtk main loop Gdk.threads_enter() reactor.run() self.shutdown() Gdk.threads_leave()
#! usr/bin/python #coding=utf-8 import sys from pluginmanager import PluginManager from pluginmanager import __ALLMODEL__ if __name__ == '__main__': #加载所有插件 PluginManager.LoadAllPlugin() #遍历所有接入点下的所有插件 for SingleModel in __ALLMODEL__: plugins = SingleModel.GetPluginObject() for item in plugins: #调用接入点的公共接口 item.Start()
def __init__(self): self.pluginmanager = PluginManager() self.pluginmanager.loadPlugins()
class TestPluginManager(unittest.TestCase): def setUp(self): self.instance = InstanceClass() self.plugin_manager = PluginManager() self.plugin_manager.add_plugins(self.instance) def test_add_instances(self): self.plugin_manager.unique_instances = False instance = InstanceClass() self.plugin_manager.add_plugins(instance) instances = self.plugin_manager.get_plugins() self.assertIn(instance, instances) self.plugin_manager.add_plugins(InstanceClass()) instances = self.plugin_manager.get_plugins() self.assertTrue(len(instances) > 2) uniq = self.plugin_manager._unique_class(InstanceClass) self.assertFalse(uniq) def test_register_class(self): class TestClass: pass self.assertFalse(issubclass(TestClass, IPlugin)) self.plugin_manager.register_classes(TestClass) self.assertTrue(issubclass(TestClass, IPlugin)) def test_class_in_blacklist(self): self.plugin_manager.set_plugins([]) self.plugin_manager.add_blacklisted_plugins(InstanceClass) self.plugin_manager._handle_object_instance(self.instance) plugins = self.plugin_manager.get_plugins() self.assertEqual(plugins, []) def test_blacklist_plugins(self): self.plugin_manager.add_blacklisted_plugins(InstanceClass) blacklisted = self.plugin_manager.get_blacklisted_plugins() self.assertIn(InstanceClass, blacklisted) def test_handle_classs_instance(self): self.plugin_manager.instantiate_classes = False is_none = self.plugin_manager._handle_class_instance(5) self.assertIsNone(is_none) def test_class_instance_not_unique(self): self.plugin_manager.unique_instances = False num_plugins = len(self.plugin_manager.plugins) self.plugin_manager._handle_class_instance(InstanceClass) self.assertTrue(len(self.plugin_manager.plugins) > num_plugins) def test_class_instance_unique(self): num_plugins = len(self.plugin_manager.plugins) self.plugin_manager.unique_instances = True self.plugin_manager._handle_class_instance(InstanceClass) self.assertTrue(len(self.plugin_manager.plugins) == num_plugins) def test_get_plugins(self): self.plugin_manager.unique_instances = False instance_2 = InstanceClass() instance_2.name = 'red' self.plugin_manager.add_plugins(instance_2) filtered_plugins = self.plugin_manager.get_plugins(_test_filter) self.assertNotIn(self.instance, filtered_plugins) self.assertIn(instance_2, filtered_plugins) def test_set_plugins(self): instance_2 = InstanceClass() self.plugin_manager.set_plugins(instance_2) plugins = self.plugin_manager.get_plugins() self.assertIn(instance_2, plugins) self.assertNotIn(self.instance, plugins) def test_remove_plugin(self): self.plugin_manager.remove_plugins(self.instance) plugins = self.plugin_manager.get_plugins() self.assertNotIn(self.instance, plugins) def test_remove_instance(self): self.plugin_manager.remove_instance(self.instance) plugins = self.plugin_manager.get_plugins() self.assertNotIn(self.instance, plugins) def test_get_instances(self): self.plugin_manager.unique_instances = False instance_2 = InstanceClass() instance_2.name = 'red' self.plugin_manager.add_plugins((instance_2, 5.0)) instances = self.plugin_manager.get_instances((IPlugin, InstanceClass)) self.assertIn(instance_2, instances) self.assertIn(self.instance, instances) self.assertNotIn(5.0, instances) filtered_instances = self.plugin_manager.get_instances(_test_filter) self.assertIn(instance_2, filtered_instances) self.assertNotIn(self.instance, filtered_instances) self.assertNotIn(5.0, filtered_instances) all_instances = self.plugin_manager.get_instances(None) self.assertIn(self.instance, all_instances) self.assertIn(instance_2, all_instances) self.assertIn(5.0, all_instances) def test_activate_instances(self): self.plugin_manager.activate_plugins() instances = self.plugin_manager.get_plugins() self.assertTrue(instances[0].active) def test_deactive_instances(self): instance = InstanceClass(True) self.plugin_manager.add_plugins(instance) self.plugin_manager.deactivate_plugins() instances = self.plugin_manager.get_plugins() for instance in instances: self.assertFalse(instance.active)
def __init__(self): """ Initialize the plugin manager """ self.__pluginmanager = PluginManager()
def show_plugin_manager(self): plugin_manager = PluginManager(self.data_singleton) plugin_manager.exec_()
class GtkUI(object): def __init__(self, args): self.daemon_bps = (0, 0, 0) # Setup signals try: import gnome.ui import gnome self.gnome_prog = gnome.init("Deluge", deluge.common.get_version()) self.gnome_client = gnome.ui.master_client() def on_die(*args): reactor.stop() self.gnome_client.connect("die", on_die) log.debug("GNOME session 'die' handler registered!") except Exception, e: log.warning( "Unable to register a 'die' handler with the GNOME session manager: %s", e) if deluge.common.windows_check(): from win32api import SetConsoleCtrlHandler from win32con import CTRL_CLOSE_EVENT from win32con import CTRL_SHUTDOWN_EVENT def win_handler(ctrl_type): log.debug("ctrl_type: %s", ctrl_type) if ctrl_type in (CTRL_CLOSE_EVENT, CTRL_SHUTDOWN_EVENT): reactor.stop() return 1 SetConsoleCtrlHandler(win_handler) # Attempt to register a magnet URI handler with gconf, but do not overwrite # if already set by another program. common.associate_magnet_links(False) # Make sure gtkui.conf has at least the defaults set self.config = deluge.configmanager.ConfigManager( "gtkui.conf", DEFAULT_PREFS) # We need to check on exit if it was started in classic mode to ensure we # shutdown the daemon. self.started_in_classic = self.config["classic_mode"] # Start the IPC Interface before anything else.. Just in case we are # already running. self.queuedtorrents = QueuedTorrents() self.ipcinterface = IPCInterface(args) # Initialize gdk threading gtk.gdk.threads_init() # We make sure that the UI components start once we get a core URI client.set_disconnect_callback(self.__on_disconnect) self.trackericons = TrackerIcons() self.sessionproxy = SessionProxy() # Initialize various components of the gtkui self.mainwindow = MainWindow() self.menubar = MenuBar() self.toolbar = ToolBar() self.torrentview = TorrentView() self.torrentdetails = TorrentDetails() self.sidebar = SideBar() self.filtertreeview = FilterTreeView() self.preferences = Preferences() self.systemtray = SystemTray() self.statusbar = StatusBar() self.addtorrentdialog = AddTorrentDialog() # Initalize the plugins self.plugins = PluginManager() # Late import because of setting up translations from connectionmanager import ConnectionManager # Show the connection manager self.connectionmanager = ConnectionManager() from twisted.internet.task import LoopingCall rpc_stats = LoopingCall(self.print_rpc_stats) rpc_stats.start(10) reactor.callWhenRunning(self._on_reactor_start) # Initialize gdk threading gtk.gdk.threads_enter() reactor.run() self.shutdown() gtk.gdk.threads_leave()
def __init__(self, type, fb): PluginManager.__init__(self, type, fb)
def __init__(self, token): super(Telegooby, self).__init__(token) for path in (Settings.cache_directory, Settings.logs_directory): path.mkdir(parents=True, exist_ok=True) self._plugin_manager = PluginManager(self)
class Gooby(object): def __init__(self, options): self.options = options self.plugin_manager = None log.info("Gooby %s", gooby_version) log.debug("Options: %s", self.options) skype_options = {} if any(sys.platform.startswith(p) for p in ("linux", "darwin")): skype_options.update({"Transport": "x11"}) self.skype = Skype4Py.Skype(**skype_options) setattr(self.skype, "FriendlyName", "Gooby") self.skype.Client.Start(Minimized=True, Nosplash=True) self.skype.Attach(Protocol=8) for path in (options.cache_dir, options.logs_dir): if not os.path.exists(path): os.mkdir(path) log.info("Cache: %s", os.path.abspath(options.cache_dir)) log.info("Logs: %s", os.path.abspath(options.logs_dir)) def __connect_signals(self): dispatcher.connect(self._plugins, signals.REQUEST_PLUGINS, False) dispatcher.connect(self._usage, signals.REQUEST_USAGE, False) dispatcher.connect(self._chats, signals.REQUEST_CHATS, False) def _chats(self): """Signal receiver.""" for chat in chain(self.skype.RecentChats, self.skype.BookmarkedChats): yield chat.Name def _usage(self, target, *args, **kwargs): """Signal receiver.""" for plugin in self.plugin_manager.plugins: usage = plugin.usage if plugin.__class__.__name__.lower() == target.lower(): return [usage(*args, **kwargs)] return None def _plugins(self): """Signal receiver.""" plugins = list() for plugin in self.plugin_manager.plugins: plugins.append(plugin.__class__.__name__) return plugins def _list_chats(self): log.info("Recent chats:") for i, chat in enumerate(self.skype.RecentChats): log.info("%3d) %s", i + 1, chat.Name) log.info("Bookmarked chats:") for i, chat in enumerate(self.skype.BookmarkedChats): log.info("%3d) %s", i + 1, chat.Name) def _attached_to_skype(self): return self.skype.AttachmentStatus == Skype4Py.enums.apiAttachSuccess def run(self): if self.options.listchats: self._list_chats() return self.__connect_signals() self.plugin_manager = PluginManager(PLUGINS_CONFIG) for event in SKYPE_EVENTS: self.skype.RegisterEventHandler( event, self.plugin_manager.on_event(event)) log.info("*** Entering main loop. Press CTRL+C to quit ***") while self._attached_to_skype(): for plugin in self.plugin_manager.plugins: messages = plugin.flush_output() for message in messages: try: message.send(self.skype) except PluginOutputError, e: log.error("Unable to send message %s by plugin %s: %s", plugin, message.text, e) time.sleep(self.options.sleep_time)
from pluginmanager import PluginManager if len(sys.argv) == 3: port = int(sys.argv[1]) plugin_path = sys.argv[2] else: raise Exception("Usage: %s path_to_plugin_dir"%sys.argv[0]) def debug( message ): print message tm = TaskManager() pm = PluginManager() pm.load_plugins(plugin_path) class PluginTCPHandler(SocketServer.StreamRequestHandler): def handle(self): processor_dict = {"start": self.command_start, "status": self.command_status} data = self.rfile.readline() debug(">"+data) try: command = json.loads(data) command_name = command.get("command", "") command_callable = processor_dict.get(command_name, self.command_not_found)
class RemoteData(object): """Get data from remote data source .. warning:: Only one plugin at time """ def __init__(self, plugdir): self.pm = PluginManager() if len(plugdir) > 0: self.pm.setPluginsDir(plugdir) self.__loadPluginId = None self.__plugin = None def pluginsMetadata(self): """Get metadata for all plugins """ return (self.pm.pluginsMetadata()) def loadPlugin(self, plugid): """Load plugin by his id :param plugid: id string for the plugin :type plugid: str """ self.pm.unloadAll() self.pm.loadPlugin(plugid) self.__loadPluginId = plugid # self.__plugin = self.pm.loadedPlugins()[0] self.__plugin = self.pm.loadedPlugin(plugid) def loadedPlugins(self): """Get metadata for all plugins :returns: List of loaded plugins :rtype: IPlugin """ return self.pm.loadedPlugins() def planes(self): """Get data for table planes in MoSiVo database :returns: List Planes table data :rtype: list """ return self.__plugin.planes() def rodalesd(self): """Get data for table planes in MoSiVo database :returns: List Planes table data :rtype: list """ return self.__plugin.rodalesd() def ubicacionrodalesd(self): """Get data for table planes in MoSiVo database :returns: List Planes table data :rtype: list """ return self.__plugin.ubicacionrodalesd() def gruposuelorodald(self): """Get data for table planes in MoSiVo database :returns: List Planes table data :rtype: list """ return self.__plugin.gruposuelorodald() def raleorodalesd(self): """Get data for table planes in MoSiVo database :returns: List Planes table data :rtype: list """ return self.__plugin.raleorodalesd() def turnorodalesd(self): """Get data for table planes in MoSiVo database :returns: List Planes table data :rtype: list """ return self.__plugin.turnorodalesd() def rodalesp(self): """Get data for table planes in MoSiVo database :returns: List Planes table data :rtype: list """ return self.__plugin.rodalesp() def ubicacionrodalesp(self): """Get data for table planes in MoSiVo database :returns: List Planes table data :rtype: list """ return self.__plugin.ubicacionrodalesp() def gruposuelorodalp(self): """Get data for table planes in MoSiVo database :returns: List Planes table data :rtype: list """ return self.__plugin.gruposuelorodalp() def raleorodalesp(self): """Get data for table planes in MoSiVo database :returns: List Planes table data :rtype: list """ return self.__plugin.raleorodalesp() def turnorodalesp(self): """Get data for table planes in MoSiVo database :returns: List Planes table data :rtype: list """ return self.__plugin.turnorodalesp() def unloadPlugin(self): """Unload loaded plugin """ self.pm.unloadPlugin(self.__loadPluginId) self.__loadPluginId = None self.__plugin = None
class ExportSettings: # export mode PLAIN_SIMPLE = 0 PLAIN_MULTI_RES = 1 SPHERE = 2 def __init__(self, pluginManager=None, localBrowsingMode=True): """localBrowsingMode: not implemented yet""" self.localBrowsingMode = localBrowsingMode self.pluginManager = pluginManager if self.pluginManager is None: from pluginmanager import PluginManager self.pluginManager = PluginManager() self.data = {} self.timestamp = datetime.datetime.today().strftime("%Y%m%d%H%M%S") self.templatePath = None self.htmlfilename = None self.path_root = None self.htmlfiletitle = None self.title = None self.exportMode = ExportSettings.PLAIN_SIMPLE self._controls = None self.coordsInWGS84 = False self.canvas = None self.mapSettings = None self.baseExtent = None self.crs = None # cache self._mapTo3d = None self._quadtree = None self._templateConfig = None @property def controls(self): if self._controls: return self._controls return QSettings().value("/Qgis2threejs/lastControls", def_vals.controls, type=unicode) @controls.setter def controls(self, value): self._controls = value def loadSettings(self, settings): self.data = settings self._mapTo3d = None # output html file path self.setOutputFilename(settings.get("OutputFilename")) # template self.setTemplatePath(settings.get("Template", def_vals.template)) # world world = settings.get(ObjectTreeItem.ITEM_WORLD, {}) self.coordsInWGS84 = world.get("radioButton_WGS84", False) # controls name self._controls = settings.get(ObjectTreeItem.ITEM_CONTROLS, {}).get("comboBox_Controls") # export mode demProperties = settings.get(ObjectTreeItem.ITEM_DEM, {}) if self.templateConfig().get("type") == "sphere": self.exportMode = ExportSettings.SPHERE elif demProperties.get("radioButton_Advanced", False): self.exportMode = ExportSettings.PLAIN_MULTI_RES else: self.exportMode = ExportSettings.PLAIN_SIMPLE def loadSettingsFromFile(self, filepath): """load settings from JSON file""" import json with open(filepath) as f: settings = json.load(f) self.loadSettings(settings) def setTemplatePath(self, filepath): """filepath: relative path from html_templates directory or absolute path to a template html file""" self.templatePath = filepath self._templateConfig = None def setOutputFilename(self, filepath=None): if not filepath: filepath = tools.temporaryOutputDir( ) + "/%s.html" % self.timestamp # temporary file self.htmlfilename = filepath self.path_root = os.path.splitext(filepath)[0] self.htmlfiletitle = os.path.basename(self.path_root) self.title = self.htmlfiletitle def setMapCanvas(self, canvas): self.setMapSettings(canvas.mapSettings( ) if QGis.QGIS_VERSION_INT >= 20300 else canvas.mapRenderer()) self.canvas = canvas def setMapSettings(self, settings): """settings: QgsMapSettings (QGIS >= 2.3) or QgsMapRenderer""" self.canvas = None self.mapSettings = settings self.baseExtent = RotatedRect.fromMapSettings(settings) self.crs = settings.destinationCrs() def demProvider(self): layerId = self.data.get(ObjectTreeItem.ITEM_DEM, {}).get("comboBox_DEMLayer", 0) return self.demProviderByLayerId(layerId) def mapTo3d(self): if self._mapTo3d: return self._mapTo3d if self.mapSettings is None: return None world = self.data.get(ObjectTreeItem.ITEM_WORLD, {}) baseSize = world.get("lineEdit_BaseSize", def_vals.baseSize) verticalExaggeration = world.get("lineEdit_zFactor", def_vals.zExaggeration) verticalShift = world.get("lineEdit_zShift", def_vals.zShift) self._mapTo3d = MapTo3D(self.mapSettings, float(baseSize), float(verticalExaggeration), float(verticalShift)) return self._mapTo3d def quadtree(self): if self._quadtree: self._quadtree if self.baseExtent is None: return properties = self.data.get(ObjectTreeItem.ITEM_DEM, {}) self._quadtree = createQuadTree(self.baseExtent, properties) return self._quadtree def templateConfig(self): if self._templateConfig: return self._templateConfig if not self.templatePath: self.setTemplatePath(def_vals.template) self._templateConfig = tools.getTemplateConfig(self.templatePath) return self._templateConfig def wgs84Center(self): if self.crs and self.baseExtent: wgs84 = QgsCoordinateReferenceSystem(4326) transform = QgsCoordinateTransform(self.crs, wgs84) return transform.transform(self.baseExtent.center()) return None def get(self, key, default=None): return self.data.get(key, default) def checkValidity(self): """check validity of export settings. return error message as unicode. return None if valid.""" if self.exportMode == ExportSettings.PLAIN_MULTI_RES and self.quadtree( ) is None: return u"Focus point/area is not selected." return None def demProviderByLayerId(self, id): if not id: return FlatDEMProvider() if id.startswith("plugin:"): provider = self.pluginManager.findDEMProvider(id[7:]) if provider: return provider(str(self.crs.toWkt())) logMessage('Plugin "{0}" not found'.format(id)) return FlatDEMProvider() else: layer = QgsMapLayerRegistry.instance().mapLayer(id) return GDALDEMProvider( layer.source(), str(self.crs.toWkt()), source_wkt=str( layer.crs().toWkt())) # use CRS set to the layer in QGIS
def addObject(object): PluginManager.addObject(object)
def main(argv): a = TiledApplication(argv) a.setOrganizationDomain("mapeditor.org") a.setApplicationName("Tiled") a.setApplicationVersion("0.14.2") if sys.platform == 'darwin': a.setAttribute(Qt.AA_DontShowIconsInMenus) # Enable support for highres images (added in Qt 5.1, but off by default) a.setAttribute(Qt.AA_UseHighDpiPixmaps) if sys.platform != 'win32': baseName = QApplication.style().objectName() if (baseName == "windows"): # Avoid Windows 95 style at all cost if (QStyleFactory.keys().contains("Fusion")): baseName = "fusion" # Qt5 else: # Qt4 # e.g. if we are running on a KDE4 desktop desktopEnvironment = qgetenv("DESKTOP_SESSION") if (desktopEnvironment == "kde"): baseName = "plastique" else: baseName = "cleanlooks" a.setStyle(QStyleFactory.create(baseName)) languageManager = LanguageManager.instance() languageManager.installTranslators() commandLine = CommandLineHandler() if (not commandLine.parse(QCoreApplication.arguments())): return 0 if (commandLine.quit): return 0 if (commandLine.disableOpenGL): preferences.Preferences.instance().setUseOpenGL(False) PluginManager.instance().loadPlugins() if (commandLine.exportMap): # Get the path to the source file and target file if (commandLine.filesToOpen().length() < 2): qWarning( QCoreApplication.translate( "Command line", "Export syntax is --export-map [format] ")) return 1 index = 0 if commandLine.filesToOpen().length() > 2: filter = commandLine.filesToOpen().at(index) index += 1 else: filter = None sourceFile = commandLine.filesToOpen().at(index) index += 1 targetFile = commandLine.filesToOpen().at(index) index += 1 chosenFormat = None formats = PluginManager.objects() if filter: # Find the map format supporting the given filter for format in formats: if not format.hasCapabilities(MapFormat.Write): continue if format.nameFilter().lower() == filter.lower(): chosenFormat = format break if not chosenFormat: qWarning( QCoreApplication.translate( "Command line", "Format not recognized (see --export-formats)")) return 1 else: # Find the map format based on target file extension suffix = QFileInfo(targetFile).completeSuffix() for format in formats: if not format.hasCapabilities(MapFormat.Write): continue if suffix.lower() in format.nameFilter().lower(): if chosenFormat: qWarning( QCoreApplication.translate( "Command line", "Non-unique file extension. Can't determine correct export format." )) return 1 chosenFormat = format if not chosenFormat: qWarning( QCoreApplication.translate( "Command line", "No exporter found for target file.")) return 1 # Load the source file reader = MapReader() map = reader.readMap(sourceFile) if (not map): qWarning( QCoreApplication.translate("Command line", "Failed to load source map.")) return 1 # Write out the file success = chosenFormat.write(map.data(), targetFile) if (not success): qWarning( QCoreApplication.translate( "Command line", "Failed to export map to target file.")) return 1 return 0 w = MainWindow() w.show() a.fileOpenRequest.connect(w.openFile) if (not commandLine.filesToOpen().isEmpty()): for fileName in commandLine.filesToOpen(): w.openFile(fileName) elif preferences.Preferences.instance().openLastFilesOnStartup(): w.openLastFiles() return a.exec()
def load_plugins_from_cfg(gctx): pluginmanager = PluginManager(gctx) gctx['pluginmanager'] = pluginmanager pluginmanager.load_plugins() gctx['hdl'] += [Handler(handle, callback) for handle, callback in pluginmanager.get_handlers()]
class Multimobilewidget(plasmascript.Applet): def __init__(self, parent, args=None): plasmascript.Applet.__init__(self, parent) def init(self): self.setHasConfigurationInterface(False) self.setAspectRatioMode(Plasma.Square) self.theme = Plasma.Svg(self) self.setBackgroundHints(Plasma.Applet.DefaultBackground) self.layout = QGraphicsLinearLayout(Qt.Vertical, self.applet) self.getLogin() self.setHasConfigurationInterface(True) self.label = Plasma.Label(self.applet) self.label.setText(i18n("Welcome to the Multimobilewidget")) nrlabel = Plasma.Label(self.applet) nrlabel.setText(i18n("Phonenr(s)")) self.messagelabel = Plasma.Label(self.applet) self.messagelabel.setText(i18n("Message - 0 signs used")) self.nrfield = Plasma.LineEdit() self.messageText = Plasma.TextEdit(self.applet) self.messageText.nativeWidget() sendButton = Plasma.PushButton(self.applet) sendButton.setText(i18n("Send the SMS!")) sendButton.resize(20, 40) configButton = Plasma.PushButton(self.applet) configButton.setText("Config") configButton.resize(20, 40) self.layout.addItem(self.label) self.layout.addItem(nrlabel) self.layout.addItem(self.nrfield) self.layout.addItem(self.messagelabel) self.layout.addItem(self.messageText) self.layout.addItem(sendButton) self.layout.addItem(configButton) self.applet.setLayout(self.layout) self.connect(sendButton, SIGNAL("clicked()"), self.onSendClick) self.connect(configButton, SIGNAL("clicked()"), self.onConfigClick) self.connect(self.messageText, SIGNAL("textChanged()"), self.onTextChanged) fullPath = str(self.package().path()) self.providerPluginManager = PluginManager("multimobilewidget/contents/code/providerplugins/","", providerplugins.Provider.Provider) self.providerpluginlist = self.providerPluginManager.getPluginClassList() for provider in self.providerpluginlist: self.ui.providerList.addItem(provider.getObjectname()) print provider.getObjectname() self.ui.providerList.setCurrentRow(0) self.adressplugins = PluginManager("multimobilewidget/contents/code/adressplugins/","", adressplugins.AdressPlugin.AdressPlugin) self.adresspluginlist = self.adressplugins.getPluginClassList() self.adressList = list() def onConfigClick(self): from config import config self.startAssistant = config(self.providerPluginManager, self.adressplugins) self.startAssistant.show() self.connect(self.startAssistant, SIGNAL("finished(int)"), self.getLogin) def connectToAkonadi(self): self.akonadiEngine = Plasma.DataEngine() self.akonadiEngine.setName("akonadi") def onSendClick(self): for provider in self.providerpluginlist: if(provider.getObjectname() == self.ui.providerList.selectedItems()[0].text()): sms = provider if self.ui.smstext.toPlainText() != "": if self.ui.phonenr.text() != "": self.getLogin() try: sms.setConfig(self.config) except Exception: self.onConfigClick() return sms.clearNrs() for nr in re.findall("(\+\d*)", self.ui.phonenr.text()): sms.addNr(nr) sms.setText(self.ui.smstext.toPlainText()) savenr = self.ui.phonenr.text() try: sms.execute() # self.notification.setText(i18n("Wurde erfolgreich an <i>%1</i> geschickt!").arg(savenr )) # self.notification.setTitle("Erfolg!") # self.notification.sendEvent() KMessageBox.information(None, i18n("SMS sendet successfully to " + savenr + ". Service: "+sms.getProvidername()), i18n("Success!")) except Exception, error: KMessageBox.error(None, i18n(error.message), i18n("Sendproblems")) self.ui.phonenr.clear() self.ui.smstext.clear() else: KMessageBox.error(None, i18n("Please fill in a phonenr"), i18n("Please fill in a phonenr")) else:
def setUp(self): self.instance = InstanceClass() self.plugin_manager = PluginManager() self.plugin_manager.add_plugins(self.instance)
def __init__(self, plugindir): self.logger = WrapLogger() self.pluginmanager = PluginManager(plugindir, self.logger) self.pluginmanager.loadPlugins(IMapiDAgentPlugin)
class Kalpana(QtGui.QApplication): read_plugin_config = pyqtSignal() write_plugin_config = pyqtSignal() print_ = pyqtSignal(str) error = pyqtSignal(str) def __init__(self, configdir, file_to_open=None): super().__init__(['kalpana']) self.objects = create_objects(configdir) self.objects['mainwindow'].create_ui(self.objects['chaptersidebar'], self.objects['textarea'], self.objects['terminal']) # Plugins self.pluginmanager = PluginManager(self.objects.copy()) self.objects['terminal'].update_commands(self.pluginmanager.plugin_commands) # Signals connect_others_signals(*self.objects.values()) self.connect_own_signals() # Hotkeys set_key_shortcuts(self.objects['mainwindow'], self.objects['textarea'], self.objects['terminal'], self.pluginmanager.get_compiled_hotkeys()) self.init_hotkeys() # Load settings and get it oooon self.objects['settingsmanager'].load_settings() self.install_event_filter() # Try to open a file and die if it doesn't work, or make a new file if file_to_open: if not self.objects['textarea'].open_file(file_to_open): self.close() else: self.objects['textarea'].set_filename(new=True) # FIN self.objects['mainwindow'].show() def install_event_filter(self): # Event filter class AppEventFilter(QtCore.QObject): activation_event = pyqtSignal() def eventFilter(self, object, event): if event.type() == QtCore.QEvent.ApplicationActivate: self.activation_event.emit() return False self.event_filter = AppEventFilter() def refresh_config(): self.objects['settingsmanager'].load_settings(refresh_only=True) self.event_filter.activation_event.connect(refresh_config) self.installEventFilter(self.event_filter) def connect_own_signals(self): self.objects['settingsmanager'].set_stylesheet.connect(self.setStyleSheet) self.objects['terminal'].list_plugins.connect(self.list_plugins) def list_plugins(self, _): plugins = self.pluginmanager.plugins self.objects['terminal'].print_(', '.join(name for name, p in plugins)) # === Configurable hotkeys ========================================= def init_hotkeys(self): l = (('terminal', self.objects['terminal'].toggle, self.set_terminal_hotkey), ('chapter sidebar', self.objects['chaptersidebar'].toggle, self.set_chaptersidebar_hotkey)) self.hotkeys = {name: QtGui.QShortcut(QtGui.QKeySequence(''), self.objects['mainwindow'], callback) for name, callback, _ in l} for n, _, callback in l: self.objects['settingsmanager'].register_setting(n + ' hotkey', callback) def set_terminal_hotkey(self, newkey): self.set_hotkey('terminal', newkey) def set_chaptersidebar_hotkey(self, newkey): self.set_hotkey('chapter sidebar', newkey) def set_hotkey(self, hotkey, newkey): self.hotkeys[hotkey].setKey(QtGui.QKeySequence(newkey))
class WicdDaemon(dbus.service.Object): def __init__(self, bus_name, options, object_path="/org/wicd/daemon"): ''' Creates a new WicdDaemon object. ''' dbus.service.Object.__init__(self, bus_name=bus_name, object_path=object_path) self.options = options self.interface_manager = InterfaceManager(self.StatusChange, self.StateChange) self.plugin_manager = PluginManager(self) import wglobals wglobals.daemon = self wglobals.plugin_manager = self.plugin_manager if not options.no_load_configuration: self.LoadConfiguration() self.plugin_manager.action('start') @dbus.service.method('org.wicd.daemon') def GetVersion(self): """ Returns the version number. """ version = 'VeryPluggableBackends SVN' return version @dbus.service.method('org.wicd.daemon.interface') def ListInterfaces(self): ''' Returns the names of all the interfaces. ''' data = self.interface_manager.get_all_names() if data in [(), [], {}]: data = ('',) return data @dbus.service.method('org.wicd.daemon.interface') def CreateInterface(self, type, name): self.interface_manager.create(type, name) def _has_data(self, data_tuple): ''' Used to convert tuples sent over DBus to real tuples. ''' if data_tuple in [('dbusdoesntallowemptytuples',), None, ()]: return None else: return data_tuple @dbus.service.method('org.wicd.daemon.interface') def GetInterfaceData(self, interface_name, method_name, data): ''' Gets the specified data from the specified interface. ''' data = self.interface_action(interface_name, method_name, data, 'get_') if data in [(), [], {}]: data = ('dbusdoesntallowemptytuples',) logging.debug( 'returning %s', data ) return data @dbus.service.method('org.wicd.daemon.interface') def SetInterfaceData(self, interface_name, method_name, data): ''' Sets the specified data on the specified interface. ''' self.interface_action(interface_name, method_name, data, 'set_') @dbus.service.method('org.wicd.daemon.interface') def DoInterfaceAction(self, interface_name, method_name, data): ''' Runs the specified command on the specified interface. ''' self.interface_action(interface_name, method_name, data, 'do_') def interface_action(self, interface_name, method_name, data, prefix=''): ''' Runs a specified action on a specified method that starts with prefix. ''' if not self.interface_manager.exists(interface_name): raise WicdError('Specified interface does not exist') interface = self.interface_manager.get(interface_name) if not hasattr(interface, (prefix + method_name)): raise WicdError('%s: method does not exist' % (prefix + method_name)) self.plugin_manager.action('starting_action', (interface_name, (prefix + method_name), self._has_data(data))) method = getattr(interface, prefix + method_name) logging.debug( '%s interface action calling %s' % (prefix[:-1], method) ) return_data = None if self._has_data(data): return_data = method(*data) else: return_data = method() self.plugin_manager.action('finished_action', (interface_name, (prefix + method_name), self._has_data(data), return_data)) return return_data @dbus.service.method('org.wicd.daemon') def SaveConfiguration(self): ''' Saves the state of the daemon. ''' logging.debug( 'saving configuration...' ) self.interface_manager.save() @dbus.service.method('org.wicd.daemon') def LoadConfiguration(self): ''' Loads the saved state of the daemon. ''' logging.debug( 'loading configuration...' ) self.interface_manager.load() @dbus.service.signal('org.wicd.daemon') def StatusChange(self, interface_name, previous_status, status): logging.debug( '%s: status changed from %s to %s', interface_name, previous_status, status) self.plugin_manager.action('signal_%s' % status, (previous_status, interface_name)) self.plugin_manager.action('signal_%s_from_%s' % (status, previous_status), (interface_name, )) @dbus.service.signal('org.wicd.daemon') def StateChange(self, interface_name, state): logging.debug( '%s: status changed to %s', interface_name, state) self.plugin_manager.action('state_%s' % state, (interface_name, )) @dbus.service.signal('org.wicd.daemon') def Closing(self): logging.debug('Daemon shutting down...') self.plugin_manager.action('closing')
def __init__(self, plugdir): self.pm = PluginManager() if len(plugdir) > 0: self.pm.setPluginsDir(plugdir) self.__loadPluginId = None self.__plugin = None
class ModRef: ''' helper class to store references to the global modules ''' def __init__(self): self.server = None self.message_handler = None def _(s): return s logger = schnipsllogger.getLogger(__name__) DirectoryMapper( os.path.abspath(os.path.dirname(__file__)), { 'backup': 'volumes/backup', 'runtime': 'volumes/runtime', 'tmpfs': 'volumes/tmpfs', 'videos': 'volumes/videos', }) modref = ModRef() # create object to store all module instances modref.message_handler = MessageHandler(modref) modref.server = Webserver(modref) plugin_manager = PluginManager(modref, 'plugins') modref.server.run() while (True): time.sleep(1)
def main(argv): a = TiledApplication(argv) a.setOrganizationDomain("mapeditor.org") a.setApplicationName("Tiled") a.setApplicationVersion("0.14.2") if sys.platform == 'darwin': a.setAttribute(Qt.AA_DontShowIconsInMenus) # Enable support for highres images (added in Qt 5.1, but off by default) a.setAttribute(Qt.AA_UseHighDpiPixmaps) if sys.platform != 'win32': baseName = QApplication.style().objectName() if (baseName == "windows"): # Avoid Windows 95 style at all cost if (QStyleFactory.keys().contains("Fusion")): baseName = "fusion" # Qt5 else: # Qt4 # e.g. if we are running on a KDE4 desktop desktopEnvironment = qgetenv("DESKTOP_SESSION") if (desktopEnvironment == "kde"): baseName = "plastique" else: baseName = "cleanlooks" a.setStyle(QStyleFactory.create(baseName)) languageManager = LanguageManager.instance() languageManager.installTranslators() commandLine = CommandLineHandler() if (not commandLine.parse(QCoreApplication.arguments())): return 0 if (commandLine.quit): return 0 if (commandLine.disableOpenGL): preferences.Preferences.instance().setUseOpenGL(False) PluginManager.instance().loadPlugins() if (commandLine.exportMap): # Get the path to the source file and target file if (commandLine.filesToOpen().length() < 2): qWarning(QCoreApplication.translate("Command line", "Export syntax is --export-map [format] ")) return 1 index = 0 if commandLine.filesToOpen().length() > 2: filter = commandLine.filesToOpen().at(index) index += 1 else: filter = None sourceFile = commandLine.filesToOpen().at(index) index += 1 targetFile = commandLine.filesToOpen().at(index) index += 1 chosenFormat = None formats = PluginManager.objects() if filter: # Find the map format supporting the given filter for format in formats: if not format.hasCapabilities(MapFormat.Write): continue if format.nameFilter().lower()==filter.lower(): chosenFormat = format break if not chosenFormat: qWarning(QCoreApplication.translate("Command line", "Format not recognized (see --export-formats)")) return 1 else: # Find the map format based on target file extension suffix = QFileInfo(targetFile).completeSuffix() for format in formats: if not format.hasCapabilities(MapFormat.Write): continue if suffix.lower() in format.nameFilter().lower(): if chosenFormat: qWarning(QCoreApplication.translate("Command line", "Non-unique file extension. Can't determine correct export format.")) return 1 chosenFormat = format if not chosenFormat: qWarning(QCoreApplication.translate("Command line", "No exporter found for target file.")) return 1 # Load the source file reader = MapReader() map = reader.readMap(sourceFile) if (not map): qWarning(QCoreApplication.translate("Command line", "Failed to load source map.")) return 1 # Write out the file success = chosenFormat.write(map.data(), targetFile) if (not success): qWarning(QCoreApplication.translate("Command line", "Failed to export map to target file.")) return 1 return 0 w = MainWindow() w.show() a.fileOpenRequest.connect(w.openFile) if (not commandLine.filesToOpen().isEmpty()): for fileName in commandLine.filesToOpen(): w.openFile(fileName) elif preferences.Preferences.instance().openLastFilesOnStartup(): w.openLastFiles() return a.exec()