def __init__(self, TYPE): self.l = pyPlexLogger('AvahiLookUp').logger self.l.info('Looking for %s type Avahi shares' % TYPE) self.services = [] self.servers = [] loop = DBusGMainLoop() bus = dbus.SystemBus(mainloop=loop) dbus.set_default_main_loop(loop) self.server = dbus.Interface(bus.get_object(avahi.DBUS_NAME, '/'), 'org.freedesktop.Avahi.Server') sbrowser = dbus.Interface( bus.get_object( avahi.DBUS_NAME, self.server.ServiceBrowserNew(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, TYPE, 'local', dbus.UInt32(0))), avahi.DBUS_INTERFACE_SERVICE_BROWSER) sbrowser.connect_to_signal("ItemNew", self.myhandler) sbrowser.connect_to_signal("AllForNow", self.__handle_all_for_now) self.GObj = gobject.MainLoop() self.GObj.run()
def __init__(self, TYPE): self.l = pyPlexLogger("AvahiLookUp").logger self.l.info("Looking for %s type Avahi shares" % TYPE) self.services = [] self.servers = [] loop = DBusGMainLoop() bus = dbus.SystemBus(mainloop=loop) dbus.set_default_main_loop(loop) self.server = dbus.Interface(bus.get_object(avahi.DBUS_NAME, "/"), "org.freedesktop.Avahi.Server") sbrowser = dbus.Interface( bus.get_object( avahi.DBUS_NAME, self.server.ServiceBrowserNew(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, TYPE, "local", dbus.UInt32(0)), ), avahi.DBUS_INTERFACE_SERVICE_BROWSER, ) sbrowser.connect_to_signal("ItemNew", self.myhandler) sbrowser.connect_to_signal("AllForNow", self.__handle_all_for_now) self.GObj = gobject.MainLoop() self.GObj.run()
def main(): dbus.set_default_main_loop(dbus.mainloop.glib.DBusGMainLoop()) bus = dbus.SessionBus() name = dbus.service.BusName("org.volume.VolumeService",bus) VolumeServiceObject = VolumeService(bus, "/VolumeService") VolumeServiceObject.run() return 0
def main(): dbus.set_default_main_loop(dbus.mainloop.glib.DBusGMainLoop()) bus = dbus.SessionBus() name = dbus.service.BusName("org.volume.VolumeService", bus) VolumeServiceObject = VolumeService(bus, "/VolumeService") VolumeServiceObject.run() return 0
def run(self): # Start the main loop from dbus.mainloop.glib import DBusGMainLoop from gobject import MainLoop self.loop = DBusGMainLoop(set_as_default=True) dbus.set_default_main_loop(self.loop) self.obj = DBusTestObject() self.mainloop = MainLoop() self.mainloop.run()
def calculateBreakTime(self, thread): """ Calculate break time when user gets idle and then display a notification :return: """ loop = gobject.MainLoop() dbus.set_default_main_loop(DBusGMainLoop(set_as_default=True)) bus = dbus.SessionBus() bus.add_signal_receiver(self.screensaverChangedEvent,'ActiveChanged','org.freedesktop.ScreenSaver') loop.run()
def __init__(self, show_notifications=False): self.show_notifications = show_notifications # Sets the new main loop as the default for Bus instances. dbus.set_default_main_loop(DBusGMainLoop()) # Connect listener to the PurpleInterface's ReceivedImMsg signal. self._bus = dbus.SessionBus() self._loop = GObject.MainLoop() obj = self._bus.get_object("im.pidgin.purple.PurpleService", "/im/pidgin/purple/PurpleObject") self._purple = dbus.Interface(obj, "im.pidgin.purple.PurpleInterface") self.setup_receivers()
def __init__(self) : "Reads glade file and sets up instance variables" dbus_loop = DBusGMainLoop() dbus.set_default_main_loop(dbus_loop) bus_name = dbus.service.BusName('com.chat.serverbusname',bus=dbus.SessionBus()) dbus.service.Object.__init__(self, bus_name, "/com/chat/serverobject") builder = gtk.Builder() builder.add_from_file("server.glade") builder.connect_signals(self) self.window = builder.get_object("window") self.textView = builder.get_object("textview")
def _setup_bus(self): dbus.set_default_main_loop(self._loop) if dbus.SystemBus().name_has_owner("org.gnome.ShairportSync"): self.log.debug("shairport-sync dbus service is running on the system bus") self._bus = dbus.SystemBus() return if dbus.SessionBus().name_has_owner("org.gnome.ShairportSync"): self.log.debug("shairport-sync dbus service is running on the session bus") self._bus = dbus.SessionBus() return self.log.error("shairport-sync dbus service is not running") exit(1)
def init(self): self.setHasConfigurationInterface(False) self.setAspectRatioMode(Plasma.Square) # Theme self.theme = Plasma.Svg(self) self.theme.setImagePath("widgets/background") self.theme.setContainsMultipleImages(False) self.setBackgroundHints(Plasma.Applet.DefaultBackground) # DBus loop = DBusQtMainLoop() dbus.set_default_main_loop(loop) self.sessionBus = dbus.SessionBus() i = 0 while i < 10: # ugly hack to wait for service to be available i = i + 1 try: self.imap_res = self.sessionBus.get_object('org.freedesktop.Akonadi.Agent.' + RES, '/') self.imap_res.connect_to_signal("onlineChanged", self.onlineChanged) except dbus.exceptions.DBusException as e: if(e.get_dbus_name() == "org.freedesktop.DBus.Error.ServiceUnknown"): # Service is not yet ready print "Waiting for 'org.freedesktop.Akonadi.Agent.%s/' to become available..." % RES time.sleep(0.2) else: break else: break # Icon self.layout = QGraphicsLinearLayout(Qt.Horizontal, self.applet) self.icon = Plasma.IconWidget() self.icon.mousePressEvent = self.mousePressEvent self.icon.mouseReleaseEvent = self.mouseReleaseEvent if self.isOnline(): self.onlineChanged(True) else: self.onlineChanged(False) self.layout.addItem(self.icon) self.applet.setLayout(self.layout)
def run(): global alreadyran if alreadyran: return d = DBusGMainLoop(set_as_default=True) dbus.set_default_main_loop(d) DBUS_BUSNAME = "org.strenua.Melia" DBUS_IFACE = 'org.strenua.Melia.MeliaIF' DBUS_PATH = '/org/strenua/Melia/MeliaIF' session_bus0 = dbus.SessionBus() busname0 = dbus.service.BusName(DBUS_BUSNAME, bus=session_bus0) eo0 = MeliaObject(object_path=DBUS_PATH, bus_name=busname0) DBUS_BUSNAME = "org.freedesktop.Notifications" DBUS_IFACE = 'org.freedesktop.Notifications' DBUS_PATH = '/org/freedesktop/Notifications' session_bus1 = dbus.SessionBus() busname1 = dbus.service.BusName(DBUS_BUSNAME, bus=session_bus1) eo1 = NotificationObject(object_path=DBUS_PATH, bus_name=busname1) alreadyran = True
def __init__(self): ''' Constructor ''' dbus.set_default_main_loop(DBusGMainLoop(set_as_default=True)) self.nm=networkmanager.NetworkManager() devices=self.nm.GetDevices() self.wireless = None self.ap=None self.success = True witype=networkmanager.device.Device.DeviceType(2) for device in devices: if str(device["DeviceType"])==str(witype): self.wireless=device break if self.wireless == None: print "No Devices Found" self.success = False self.applet=NetworkManagerSettings(SYSTEM_SERVICE)
def __init__(self) : "Reads glade file and sets up instance variables" builder = gtk.Builder() builder.add_from_file("client.glade") builder.connect_signals(self) self.window = builder.get_object("window") self.entry = builder.get_object("entry") self.colorButton = builder.get_object("colorbutton") self.textView = builder.get_object("textview") self.button = builder.get_object("button") try : dbus_loop = DBusGMainLoop() dbus.set_default_main_loop(dbus_loop) self.bus = dbus.SessionBus() self.chat_obj = self.bus.get_object("com.chat.serverbusname", "/com/chat/serverobject") self.chat = dbus.Interface(self.chat_obj, "com.chat.serverinterface") self.chat.connect_to_signal("message_received", self.on_message_received) except dbus.exceptions.DBusException : self.set_server_unavailable()
def connect_dbus(self): try: import dbus from dbus.mainloop.glib import DBusGMainLoop main_loop = DBusGMainLoop(set_as_default=True) dbus.set_default_main_loop(main_loop) except ImportError: log.debug('Error: python-dbus needs to be installed. No ' 'zeroconf support.') return False if self.bus: return True try: self.bus = dbus.SystemBus() self.bus.add_signal_receiver(self.avahi_dbus_connect_cb, 'NameOwnerChanged', 'org.freedesktop.DBus', arg0='org.freedesktop.Avahi') except Exception as e: # System bus is not present self.bus = None log.debug(str(e)) return False else: return True
# ============================================================================= # zeroconf # ============================================================================= _ZC_TYPE = "_remuco._tcp" if linux: import dbus from dbus.mainloop.glib import DBusGMainLoop from dbus.exceptions import DBusException import gobject dbus.set_default_main_loop(DBusGMainLoop()) # Avahi DBus constants (defined here to prevent python-avahi dependency) _DBA_NAME = "org.freedesktop.Avahi" _DBA_INTERFACE_SERVER = _DBA_NAME + ".Server" _DBA_PATH_SERVER = "/" _DBA_INTERFACE_ENTRY_GROUP = _DBA_NAME + ".EntryGroup" _zc_group = None def zc_publish(player, port): """Publish a service for the given player at the given port.""" zc_unpublish() log.debug("publishing zeroconf service")
import os import string import json import dbus from PyQt4.QtGui import * from dbus.mainloop.qt import DBusQtMainLoop from main_window import * app = QApplication(sys.argv) dbus.set_default_main_loop(dbus.mainloop.qt.DBusQtMainLoop()) the_main_window = main_window() the_main_window.show() if False == os.isatty(0): the_line = "" for line in sys.stdin: if string.rfind(line, "PSST:") == 0: the_line = line[len("PSST:"):] if len(the_line) > 0: #last line has to be most current state json.loads(the_line, object_hook=lambda x: from_json(the_main_window, x)) if the_main_window.tab_widget.count() == 0: the_main_window.add_view()
def main(): """ Parse arguments and run either the command-line or the GUI monitor. """ global bus global cmdline_args global cli gettext.install(NAME) parser = argparse.ArgumentParser(description=_('Upstart Event Monitor')) parser.add_argument('-n', '--no-gui', action='store_true', help=_('run in command-line mode')) parser.add_argument('-s', '--separator', help=_('field separator to use for command-line output')) parser.add_argument('-d', '--destination', choices=destinations.keys(), help=_('connect to Upstart via specified D-Bus route')) cmdline_args = parser.parse_args() # allow interrupt signal.signal(signal.SIGINT, signal.SIG_DFL) dbus.set_default_main_loop(dbus.mainloop.glib.DBusGMainLoop()) if not cmdline_args.destination: # If no destination specified, attempt to connect to session # if running under a Session Init, else connect to the system # bus (since this allows even non-priv users to see events). if SESSION_SOCKET: cmdline_args.destination = 'session-socket' else: cmdline_args.destination = 'system-bus' if cmdline_args.destination == 'system-bus': bus = dbus.SystemBus() elif cmdline_args.destination == 'session-bus': bus = dbus.SessionBus() elif cmdline_args.destination == 'system-socket': socket = INIT_SOCKET bus = dbus.connection.Connection(socket) elif cmdline_args.destination == 'session-socket': socket = SESSION_SOCKET bus = dbus.connection.Connection(socket) if cmdline_args.no_gui or not os.environ.get('DISPLAY'): cli = True # dynamically load GUI elements so we can fall back to the # command-line version if we cannot display a GUI if cli == True: # register a D-Bus handler bus.add_signal_receiver(cmdline_event_handler, dbus_interface='com.ubuntu.Upstart0_6', signal_name='EventEmitted') loop = GLib.MainLoop() print('# Upstart Event Monitor (%s)' % _('console mode')) print('#') print('# %s %s' % (_('Connected to'), destinations[cmdline_args.destination])) print('#') print('# %s' % _('Columns: time, event and environment')) print('') loop.run() else: win = UpstartEventsGui() win.connect('delete-event', Gtk.main_quit) win.show_all() Gtk.main()
if args.debug: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) #problems led_layout = LED_LAYOUT.get( args.led_layout) if args.led_layout is not None else None MOONBOARD = MoonBoard(args.driver_type, led_layout) # connect to dbus signal new problem dbml = DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() proxy = bus.get_object('com.moonboard', '/com/moonboard') proxy.connect_to_signal('new_problem', partial(new_problem_cb, MOONBOARD)) loop = GLib.MainLoop() dbus.set_default_main_loop(dbml) # Run the loop try: loop.run() except KeyboardInterrupt: print("keyboard interrupt received") except Exception as e: print("Unexpected exception occurred: '{}'".format(str(e))) finally: loop.quit()
fh.setFormatter(fh_formatter) fh.setLevel(logging.ERROR) log.addHandler(fh) return log log = setup_log() try: from e_dbus import DBusEcoreMainLoop except ImportError: from efl.dbus_mainloop import DBusEcoreMainLoop import dbus ml = DBusEcoreMainLoop() dbus.set_default_main_loop(ml) import dbus.service bus = dbus.SessionBus() dbo = None try: dbo = bus.get_object("net.launchpad.epour", "/net/launchpad/epour") except dbus.exceptions.DBusException: pass if dbo: if sys.argv[1:]: for f in sys.argv[1:]: log.info("Sending %s via dbus" % f) dbo.AddTorrent(f, dbus_interface="net.launchpad.epour") sys.exit()
def register(self): global nmainloop if self.registered: return try: # register the main loop for d-bus events dbus.set_default_main_loop(nmainloop) bus = dbus.SessionBus(mainloop=nmainloop) # bus.add_match_string_non_blocking("eavesdrop=true") # wildcard bus.add_message_filter(self.notifications) except dbus.DBusException as e: raise DRingCtrlDBusError(str(e)) if not bus.name_has_owner(DBUS_DEAMON_OBJECT): raise DRingCtrlDBusError(("Unable to find %s in DBUS." % DBUS_DEAMON_OBJECT) + " Check if dring is running") try: proxy_instance = bus.get_object(DBUS_DEAMON_OBJECT, DBUS_DEAMON_PATH + '/Instance', introspect=False) proxy_callmgr = bus.get_object(DBUS_DEAMON_OBJECT, DBUS_DEAMON_PATH + '/CallManager', introspect=False) proxy_confmgr = bus.get_object(DBUS_DEAMON_OBJECT, DBUS_DEAMON_PATH + '/ConfigurationManager', introspect=False) proxy_videomgr = bus.get_object(DBUS_DEAMON_OBJECT, DBUS_DEAMON_PATH + '/VideoManager', introspect=False) self.instance = dbus.Interface(proxy_instance, DBUS_DEAMON_OBJECT + '.Instance') self.callmanager = dbus.Interface( proxy_callmgr, DBUS_DEAMON_OBJECT + '.CallManager') self.configurationmanager = dbus.Interface( proxy_confmgr, DBUS_DEAMON_OBJECT + '.ConfigurationManager') if proxy_videomgr: self.videomanager = dbus.Interface( proxy_videomgr, DBUS_DEAMON_OBJECT + '.VideoManager') except dbus.DBusException as e: raise DRingCtrlDBusError("Unable to bind to dring DBus API") try: self.instance.Register(os.getpid(), self.name) self.registered = True except dbus.DBusException as e: raise DRingCtrlDeamonError("Client registration failed") try: proxy_callmgr.connect_to_signal('incomingCall', self.onIncomingCall) proxy_callmgr.connect_to_signal('callStateChanged', self.onCallStateChanged) proxy_callmgr.connect_to_signal('conferenceCreated', self.onConferenceCreated) proxy_confmgr.connect_to_signal('accountsChanged', self.onAccountsChanged) proxy_confmgr.connect_to_signal('dataTransferEvent', self.onDataTransferEvent) proxy_confmgr.connect_to_signal('incomingAccountMessage', self.onIncomingAccountMessage) except dbus.DBusException as e: raise DRingCtrlDBusError("Unable to connect to dring DBus signals")
def main(argv): global server_thread print("Starting %s %s..." % (common.app_name, common.app_version)) print(""" __ / \_ __( )_ _( \_ _( )_ (__________________) """) app = QApplication(argv) network.setup() filtering.setup() # Create extension server. server_thread = extension_server.ExtensionServerThread(QCoreApplication.instance()) # Start DBus loop if has_dbus: print("DBus available. Creating main loop...", end=" ") mainloop = DBusQtMainLoop(set_as_default = True) dbus.set_default_main_loop(mainloop) print("done.") else: print("DBus unavailable.") # Create app. app.setApplicationName(common.app_name) app.setApplicationVersion(common.app_version) app.installTranslator(translate.translator) # We want Nimbus to stay open when the last window is closed, # so we set this. app.setQuitOnLastWindowClosed(False) # If D-Bus is present... if has_dbus: print("Creating DBus session bus...", end=" ") try: bus = dbus.SessionBus() except: print("failed.") else: print("done.") try: print("Checking for running instances of %s..." % (common.app_name,), end=" ") proxy = bus.get_object("org.nimbus.%s" % (common.app_name,), "/%s" % common.app_name,) except: dbus_present = False else: dbus_present = True print("done.") # If Nimbus detects the existence of another Nimbus process, it # will send all the requested URLs to the existing process and # exit. if dbus_present: print("An instance of Nimbus is already running. Passing arguments via DBus.") for arg in argv[1:]: proxy.addTab(arg) if len(argv) < 2: proxy.addWindow() return elif has_dbus: print("No prior instances found. Continuing on our merry way.") # Hack together the browser's icon. This needs to be improved. common.app_icon = common.complete_icon("nimbus") app.setWindowIcon(common.app_icon) common.searchEditor = search_manager.SearchEditor() common.downloadManager = DownloadManager(windowTitle=tr("Downloads")) common.downloadManager.resize(QSize(480, 320)) common.downloadManager.loadSession() # Create tray icon. common.trayIcon = SystemTrayIcon() common.trayIcon.newWindowRequested.connect(addWindow) #common.trayIcon.windowReopenRequested.connect(reopenWindow) common.trayIcon.show() # Creates a licensing information dialog. common.licenseDialog = custom_widgets.LicenseDialog() # Create instance of clear history dialog. common.chistorydialog = clear_history_dialog.ClearHistoryDialog() uc = QUrl.fromUserInput(settings.user_css) websettings = QWebSettings.globalSettings() websettings.setUserStyleSheetUrl(uc) websettings.enablePersistentStorage(settings.settings_folder) websettings.setAttribute(websettings.LocalContentCanAccessRemoteUrls, True) websettings.setAttribute(websettings.LocalContentCanAccessFileUrls, True) websettings.setAttribute(websettings.DeveloperExtrasEnabled, True) try: websettings.setAttribute(websettings.ScrollAnimatorEnabled, True) except: pass common.applyWebSettings() # Set up settings dialog. settings.settingsDialog = settings_dialog.SettingsDialog() settings.settingsDialog.setWindowFlags(Qt.Dialog) closeSettingsDialogAction = QAction(settings.settingsDialog) closeSettingsDialogAction.setShortcuts(["Esc", "Ctrl+W"]) closeSettingsDialogAction.triggered.connect(settings.settingsDialog.hide) settings.settingsDialog.addAction(closeSettingsDialogAction) # Set up clippings manager. settings.clippingsManager = settings_dialog.ClippingsPanel() settings.clippingsManager.setWindowFlags(Qt.Dialog) closeClippingsManagerAction = QAction(settings.clippingsManager) closeClippingsManagerAction.setShortcuts(["Esc", "Ctrl+W"]) closeClippingsManagerAction.triggered.connect(settings.clippingsManager.hide) settings.clippingsManager.addAction(closeClippingsManagerAction) # Create DBus server if has_dbus: print("Creating DBus server...", end=" ") server = DBusServer(bus) print("done.") # Load adblock rules. filtering.adblock_filter_loader.start() if not os.path.isdir(settings.extensions_folder): try: print("Copying extensions...", end=" ") shutil.copytree(common.extensions_folder,\ settings.extensions_folder) except: print("failed.") else: print("done.") if not os.path.isfile(settings.startpage): try: print("Copying start page...", end=" ") shutil.copy2(common.startpage, settings.startpage) except: print("failed.") else: print("done.") settings.reload_extensions() settings.reload_userscripts() server_thread.setDirectory(settings.extensions_folder) # Start extension server. server_thread.start() # On quit, save settings. app.aboutToQuit.connect(prepareQuit) # Load settings. data.loadData() # View source dialog. common.viewSourceDialog = ViewSourceDialogTabber() #common.viewSourceDialog.show() # This is a baaad name. common.sessionSaver = QTimer(QCoreApplication.instance()) common.sessionSaver.timeout.connect(saveSession) common.sessionSaver.timeout.connect(data.saveData) if common.portable: common.sessionSaver.start(50000) else: common.sessionSaver.start(30000) common.desktop = QDesktopWidget() changeSettings = False if os.path.isfile(settings.crash_file): print("Crash file detected.", end="") if not has_dbus: print(" With no DBus, %s may already be running." % common.app_name,) multInstances = QMessageBox.question(None, tr("Hm."), tr("It's not good to run multiple instances of %(app_name)s. Is an instance of %(app_name)s already running?") % {"app_name": common.app_name}, QMessageBox.Yes | QMessageBox.No) if multInstances == QMessageBox.Yes: print("%s will now halt." % common.app_name,) return else: print() clearCache = QMessageBox() clearCache.setWindowTitle(tr("Ow.")) clearCache.setText(tr("%(app_name)s seems to have crashed during your last session. Fortunately, your tabs were saved up to 30 seconds beforehand. Would you like to restore them?") % {"app_name": common.app_name}) clearCache.addButton(QPushButton(tr("Yes and change &settings")), QMessageBox.YesRole) clearCache.addButton(QMessageBox.Yes) clearCache.addButton(QMessageBox.No) returnValue = clearCache.exec_() if returnValue == QMessageBox.No: try: os.remove(settings.session_file) except: pass if returnValue == 0: changeSettings = True else: f = open(settings.crash_file, "w") f.write("") f.close() if not "--daemon" in argv and os.path.exists(settings.session_file): print("Loading previous session...", end=" ") if changeSettings: settings.settingsDialog.exec_() loadSession() print("done.") if not "--daemon" in argv and len(argv[1:]) > 0: # Create instance of MainWindow. print("Loading the URLs you requested...", end=" ") if len(browser.windows) > 0: win = browser.windows[-1] else: win = MainWindow(appMode = ("--app" in argv)) # Open URLs from command line. if len(argv[1:]) > 0: for arg in argv[1:]: if "." in arg or ":" in arg: win.addTab(url=arg) if win.tabWidget().count() < 1: win.addTab(url=settings.settings.value("general/Homepage")) # Show window. win.show() print("done.") elif not "--daemon" in argv and len(argv[1:]) == 0 and len(browser.windows) == 0: win = MainWindow(appMode = ("--app" in argv)) win.addTab(url=settings.settings.value("general/Homepage")) win.show() # Load filtering stuff. if not os.path.isdir(filtering.hosts_folder): common.trayIcon.showMessage(tr("Downloading content filters"), ("Ad blocking and host filtering will not work until this completes.")) filtering.update_filters() else: filtering.load_host_rules() # Start app. print("Kon~!") sys.exit(app.exec_())
def set_mainloop(self, loop): """ Set DBus main loop. """ dbus.set_default_main_loop(loop)
def main(argv): global server_thread print("Starting %s %s..." % (common.app_name, common.app_version)) print(""" __ / \_ __( )_ _( \_ _( )_ (__________________) """) app = QApplication(argv) network.setup() filtering.setup() # Create extension server. server_thread = extension_server.ExtensionServerThread( QCoreApplication.instance()) # Start DBus loop if has_dbus: print("DBus available. Creating main loop...", end=" ") mainloop = DBusQtMainLoop(set_as_default=True) dbus.set_default_main_loop(mainloop) print("done.") else: print("DBus unavailable.") # Create app. app.setApplicationName(common.app_name) app.setApplicationVersion(common.app_version) app.installTranslator(translate.translator) # We want Nimbus to stay open when the last window is closed, # so we set this. app.setQuitOnLastWindowClosed(False) # If D-Bus is present... if has_dbus: print("Creating DBus session bus...", end=" ") try: bus = dbus.SessionBus() except: print("failed.") else: print("done.") try: print("Checking for running instances of %s..." % (common.app_name, ), end=" ") proxy = bus.get_object( "org.nimbus.%s" % (common.app_name, ), "/%s" % common.app_name, ) except: dbus_present = False else: dbus_present = True print("done.") # If Nimbus detects the existence of another Nimbus process, it # will send all the requested URLs to the existing process and # exit. if dbus_present: print( "An instance of Nimbus is already running. Passing arguments via DBus." ) for arg in argv[1:]: proxy.addTab(arg) if len(argv) < 2: proxy.addWindow() return elif has_dbus: print("No prior instances found. Continuing on our merry way.") # Hack together the browser's icon. This needs to be improved. common.app_icon = common.complete_icon("nimbus") app.setWindowIcon(common.app_icon) common.searchEditor = search_manager.SearchEditor() common.downloadManager = DownloadManager(windowTitle=tr("Downloads")) common.downloadManager.resize(QSize(480, 320)) common.downloadManager.loadSession() # Create tray icon. common.trayIcon = SystemTrayIcon() common.trayIcon.newWindowRequested.connect(addWindow) #common.trayIcon.windowReopenRequested.connect(reopenWindow) common.trayIcon.show() # Creates a licensing information dialog. common.licenseDialog = custom_widgets.LicenseDialog() # Create instance of clear history dialog. common.chistorydialog = clear_history_dialog.ClearHistoryDialog() uc = QUrl.fromUserInput(settings.user_css) websettings = QWebSettings.globalSettings() websettings.setUserStyleSheetUrl(uc) websettings.enablePersistentStorage(settings.settings_folder) websettings.setAttribute(websettings.LocalContentCanAccessRemoteUrls, True) websettings.setAttribute(websettings.LocalContentCanAccessFileUrls, True) websettings.setAttribute(websettings.DeveloperExtrasEnabled, True) try: websettings.setAttribute(websettings.ScrollAnimatorEnabled, True) except: pass common.applyWebSettings() # Set up settings dialog. settings.settingsDialog = settings_dialog.SettingsDialog() settings.settingsDialog.setWindowFlags(Qt.Dialog) closeSettingsDialogAction = QAction(settings.settingsDialog) closeSettingsDialogAction.setShortcuts(["Esc", "Ctrl+W"]) closeSettingsDialogAction.triggered.connect(settings.settingsDialog.hide) settings.settingsDialog.addAction(closeSettingsDialogAction) # Set up clippings manager. settings.clippingsManager = settings_dialog.ClippingsPanel() settings.clippingsManager.setWindowFlags(Qt.Dialog) closeClippingsManagerAction = QAction(settings.clippingsManager) closeClippingsManagerAction.setShortcuts(["Esc", "Ctrl+W"]) closeClippingsManagerAction.triggered.connect( settings.clippingsManager.hide) settings.clippingsManager.addAction(closeClippingsManagerAction) # Create DBus server if has_dbus: print("Creating DBus server...", end=" ") server = DBusServer(bus) print("done.") # Load adblock rules. filtering.adblock_filter_loader.start() if not os.path.isdir(settings.extensions_folder): try: print("Copying extensions...", end=" ") shutil.copytree(common.extensions_folder,\ settings.extensions_folder) except: print("failed.") else: print("done.") if not os.path.isfile(settings.startpage): try: print("Copying start page...", end=" ") shutil.copy2(common.startpage, settings.startpage) except: print("failed.") else: print("done.") settings.reload_extensions() settings.reload_userscripts() server_thread.setDirectory(settings.extensions_folder) # Start extension server. server_thread.start() # On quit, save settings. app.aboutToQuit.connect(prepareQuit) # Load settings. data.loadData() # View source dialog. common.viewSourceDialog = ViewSourceDialogTabber() #common.viewSourceDialog.show() # This is a baaad name. common.sessionSaver = QTimer(QCoreApplication.instance()) common.sessionSaver.timeout.connect(saveSession) common.sessionSaver.timeout.connect(data.saveData) if common.portable: common.sessionSaver.start(50000) else: common.sessionSaver.start(30000) common.desktop = QDesktopWidget() changeSettings = False if os.path.isfile(settings.crash_file): print("Crash file detected.", end="") if not has_dbus: print( " With no DBus, %s may already be running." % common.app_name, ) multInstances = QMessageBox.question( None, tr("Hm."), tr("It's not good to run multiple instances of %(app_name)s. Is an instance of %(app_name)s already running?" ) % {"app_name": common.app_name}, QMessageBox.Yes | QMessageBox.No) if multInstances == QMessageBox.Yes: print("%s will now halt." % common.app_name, ) return else: print() clearCache = QMessageBox() clearCache.setWindowTitle(tr("Ow.")) clearCache.setText( tr("%(app_name)s seems to have crashed during your last session. Fortunately, your tabs were saved up to 30 seconds beforehand. Would you like to restore them?" ) % {"app_name": common.app_name}) clearCache.addButton(QPushButton(tr("Yes and change &settings")), QMessageBox.YesRole) clearCache.addButton(QMessageBox.Yes) clearCache.addButton(QMessageBox.No) returnValue = clearCache.exec_() if returnValue == QMessageBox.No: try: os.remove(settings.session_file) except: pass if returnValue == 0: changeSettings = True else: f = open(settings.crash_file, "w") f.write("") f.close() if not "--daemon" in argv and os.path.exists(settings.session_file): print("Loading previous session...", end=" ") if changeSettings: settings.settingsDialog.exec_() loadSession() print("done.") if not "--daemon" in argv and len(argv[1:]) > 0: # Create instance of MainWindow. print("Loading the URLs you requested...", end=" ") if len(browser.windows) > 0: win = browser.windows[-1] else: win = MainWindow(appMode=("--app" in argv)) # Open URLs from command line. if len(argv[1:]) > 0: for arg in argv[1:]: if "." in arg or ":" in arg: win.addTab(url=arg) if win.tabWidget().count() < 1: win.addTab(url=settings.settings.value("general/Homepage")) # Show window. win.show() print("done.") elif not "--daemon" in argv and len(argv[1:]) == 0 and len( browser.windows) == 0: win = MainWindow(appMode=("--app" in argv)) win.addTab(url=settings.settings.value("general/Homepage")) win.show() # Load filtering stuff. if not os.path.isdir(filtering.hosts_folder): common.trayIcon.showMessage(tr("Downloading content filters"), ( "Ad blocking and host filtering will not work until this completes." )) filtering.update_filters() else: filtering.load_host_rules() # Start app. print("Kon~!") sys.exit(app.exec_())
#!/usr/bin/python import dbus import asyncio from gi.repository import GObject from dbus.mainloop.glib import DBusGMainLoop from gbulb import glib_events from tphangups import HangupsConnectionManager if __name__ == '__main__': #both dbus and asyncio need an event loop #having two event loops would be mental #this makes them both use the glib event loop via dark and evil black magic #don't touch it asyncio.set_event_loop_policy(glib_events.GLibEventLoopPolicy()) dbus.set_default_main_loop(dbus.mainloop.glib.DBusGMainLoop()) manager = HangupsConnectionManager() loop = asyncio.get_event_loop() loop.run_forever()
def set_mainloop(self, loop): dbus.set_default_main_loop(loop)
import sys import dbus import dbus.service import dbus.mainloop.qt from PyQt4.QtCore import QCoreApplication from PyQt4 import QtCore from pulseaudio.PulseAudio import * from VeromixDbus import * from VeromixEvent import * from Pa2dBus import * if __name__ == '__main__': app=QtCore.QCoreApplication(sys.argv) signal.signal(signal.SIGINT, signal.SIG_DFL) mainloop = dbus.mainloop.qt.DBusQtMainLoop(set_as_default=True) conn = dbus.SessionBus() name = dbus.service.BusName("org.veromix.pulseaudio.qt", conn) dbus.set_default_main_loop(mainloop) pulse = PulseAudio() bus = VeromixDbus(pulse,conn) i = Pa2dBus(bus, pulse) event_processor = VeromixEvent(i) pulse.set_receiver(event_processor) pulse.start_pulsing() app.exec_()
def main(): """ Parse arguments and run either the command-line or the GUI monitor. """ global bus global cmdline_args global cli gettext.install(NAME) parser = argparse.ArgumentParser(description=_('Upstart Event Monitor')) parser.add_argument('-n', '--no-gui', action='store_true', help=_('run in command-line mode')) parser.add_argument( '-s', '--separator', help=_('field separator to use for command-line output')) parser.add_argument('-d', '--destination', choices=destinations.keys(), help=_('connect to Upstart via specified D-Bus route')) cmdline_args = parser.parse_args() # allow interrupt signal.signal(signal.SIGINT, signal.SIG_DFL) dbus.set_default_main_loop(dbus.mainloop.glib.DBusGMainLoop()) if not cmdline_args.destination: # If no destination specified, attempt to connect to session # if running under a Session Init, else connect to the system # bus (since this allows even non-priv users to see events). if SESSION_SOCKET: cmdline_args.destination = 'session-socket' else: cmdline_args.destination = 'system-bus' if cmdline_args.destination == 'system-bus': bus = dbus.SystemBus() elif cmdline_args.destination == 'session-bus': bus = dbus.SessionBus() elif cmdline_args.destination == 'system-socket': socket = INIT_SOCKET bus = dbus.connection.Connection(socket) elif cmdline_args.destination == 'session-socket': socket = SESSION_SOCKET bus = dbus.connection.Connection(socket) if cmdline_args.no_gui or not os.environ.get('DISPLAY'): cli = True # dynamically load GUI elements so we can fall back to the # command-line version if we cannot display a GUI if cli == True: # register a D-Bus handler bus.add_signal_receiver(cmdline_event_handler, dbus_interface='com.ubuntu.Upstart0_6', signal_name='EventEmitted') loop = GLib.MainLoop() print('# Upstart Event Monitor (%s)' % _('console mode')) print('#') print('# %s %s' % (_('Connected to'), destinations[cmdline_args.destination])) print('#') print('# %s' % _('Columns: time, event and environment')) print('') loop.run() else: win = UpstartEventsGui() win.connect('delete-event', Gtk.main_quit) win.show_all() Gtk.main()
# TODO: implementations for mac and win # ============================================================================= # zeroconf # ============================================================================= _ZC_TYPE = "_remuco._tcp" if linux: import dbus from dbus.mainloop.glib import DBusGMainLoop from dbus.exceptions import DBusException import gobject dbus.set_default_main_loop(DBusGMainLoop()) # Avahi DBus constants (defined here to prevent python-avahi dependency) _DBA_NAME = "org.freedesktop.Avahi" _DBA_INTERFACE_SERVER = _DBA_NAME + ".Server" _DBA_PATH_SERVER = "/" _DBA_INTERFACE_ENTRY_GROUP = _DBA_NAME + ".EntryGroup" _zc_group = None def zc_publish(player, port): """Publish a service for the given player at the given port.""" zc_unpublish() log.debug("publishing zeroconf service")
def _setup_dbus(): dbus_loop = dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) # To make threading.Timer work dbus.mainloop.glib.threads_init() dbus_server = SprinklersApi() dbus.set_default_main_loop(dbus_loop)
import dbus import dbus.mainloop.glib from gi.repository import GLib import Charon.Client if len(sys.argv) != 2: print("Usage: test.py [file]") exit(1) GLib.threads_init() dbus.mainloop.glib.threads_init() loop = GLib.MainLoop() dbus.set_default_main_loop(dbus.mainloop.glib.DBusGMainLoop()) request = Charon.Client.Request(sys.argv[1], ["/Metadata/thumbnail.png"]) request.setCallbacks(completed=lambda request: loop.quit()) request.start() loop.run() if request.state == Charon.Client.Request.State.Completed: print("Request Complete") print(request.data) elif request.state == Charon.Client.Request.State.Error: print("Request Error") print(request.errorString) else: