Python gi.repository.GObject.threads_init() Examples

The following are 30 code examples of gi.repository.GObject.threads_init(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module gi.repository.GObject , or try the search function .
Example #1
Source File: bt-audio.py    From bt-audio with GNU General Public License v3.0 7 votes vote down vote up
def main():

    global args
    args = argparser.parse_args()

    bluez = Bluez()

    adapt = bluez.getAdapter(args.adapter)

    if not adapt:
        print("Adapter " + args.adapter + " not found")
        return

    adapt.powerSet(True)
    adapt.discoverableSet(True)
    adapt.mediaEndpointRegisterSBC()
    if args.aac_enabled:
        adapt.mediaEndpointRegisterAAC()


    Gst.init(None)
    GObject.threads_init()
    mainloop = GObject.MainLoop()
    mainloop.run()
    return 
Example #2
Source File: kaldi.py    From Dragonfire with MIT License 6 votes vote down vote up
def __init__(self):
        # logging.basicConfig(level=logging.INFO)

        # voxforge/tri2b_mmi_b0.05 model:
        decoder_conf = {
            "model": ENGLISH_MODEL_PATH + "final.mdl",
            "lda-mat": ENGLISH_MODEL_PATH + "final.mat",
            "word-syms": ENGLISH_MODEL_PATH + "words.txt",
            "fst": ENGLISH_MODEL_PATH + "HCLG.fst",
            "silence-phones": "6"
        }
        self.decoder_pipeline = DecoderPipeline({"decoder": decoder_conf})
        self.__class__.words = []
        self.__class__.finished = False

        self.decoder_pipeline.set_word_handler(self.word_getter)
        self.decoder_pipeline.set_eos_handler(self.set_finished, self.finished)

        GObject.threads_init()
        self.loop = GObject.MainLoop()
        self.gi_thread = Thread(target=self.loop.run, args=())
        self.gi_thread.start() 
Example #3
Source File: browser_cef.py    From rednotebook with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self):
            super().__init__()
            self._browser = None
            self._win32_handle = None
            self._initial_html = ""

            sys.excepthook = cef.ExceptHook  # To shutdown CEF processes on error.
            cef.Initialize(settings={"context_menu": {"enabled": False}})

            GObject.threads_init()
            GObject.timeout_add(10, self.on_timer)

            self.connect("configure-event", self.on_configure)
            self.connect("size-allocate", self.on_size_allocate)
            self.connect("focus-in-event", self.on_focus_in)
            self.connect("realize", self.on_realize) 
Example #4
Source File: main.py    From python-eduvpn-client with GNU General Public License v3.0 6 votes vote down vote up
def init(lets_connect):  # type: (bool) -> EduVpnApp
    (level, secure_internet_uri, institute_access_uri, verify_key, lets_connect_arg) = parse_args()
    lets_connect = lets_connect or lets_connect_arg
    if geteuid() == 0:
        logger.error(u"Running eduVPN client as root is not supported (yet)")
        exit(1)
    GObject.threads_init()

    if have_dbus():
        import dbus.mainloop.glib
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

    # import this later so the logging is properly configured
    from eduvpn.ui import EduVpnApp

    edu_vpn_app = EduVpnApp(secure_internet_uri=secure_internet_uri,
                            institute_access_uri=institute_access_uri,
                            verify_key=verify_key, lets_connect=lets_connect)
    edu_vpn_app.run()
    return edu_vpn_app 
Example #5
Source File: peripheral.py    From python-bluezero with MIT License 6 votes vote down vote up
def __init__(self, device_id=None):
        """Default initialiser.

        1. Initialises the program loop using ``GObject``.
        2. Registers the Application on the D-Bus.
        3. Initialises the list of services offered by the application.

        """
        # Initialise the loop that the application runs in
        GObject.threads_init()
        dbus.mainloop.glib.threads_init()
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        self.mainloop = GObject.MainLoop()

        # Initialise the D-Bus path and register it
        self.bus = dbus.SystemBus()
        self.path = '/ukBaz/bluezero/application{}'.format(id(self))
        self.bus_name = dbus.service.BusName('ukBaz.bluezero', self.bus)
        dbus.service.Object.__init__(self, self.bus_name, self.path)

        # Initialise services within the application
        self.services = []

        self.dongle = adapter.Adapter(device_id) 
Example #6
Source File: notificationmanager.py    From deskcon-desktop with GNU General Public License v3.0 5 votes vote down vote up
def run(self):
        GObject.threads_init()
        self.nnotification.show()
        Gtk.main() 
Example #7
Source File: ctl.py    From kano-settings with GNU General Public License v2.0 5 votes vote down vote up
def launch_wifi_gui(socket_id=None, no_confirm_ether=False):
    from gi.repository import GObject
    from kano_wifi_gui.wifi_window import create_wifi_gui

    GObject.threads_init()

    is_plug = socket_id is not None
    create_wifi_gui(is_plug, socket_id, no_confirm_ether)

    return 0 
Example #8
Source File: gstfunctions.py    From tapas with GNU General Public License v2.0 5 votes vote down vote up
def gst_init():
    from twisted.internet import gireactor as reactor
    reactor.install()
    import gi
    gi.require_version('Gst', '1.0')
    from gi.repository import GObject, Gst
    GObject.threads_init()
    Gst.init(None) 
Example #9
Source File: main.py    From ebook-viewer with GNU General Public License v3.0 5 votes vote down vote up
def do_activate(self):
        GObject.threads_init()
        gettext.install('easy-ebook-viewer', '/usr/share/easy-ebook-viewer/locale')
        # We only allow a single window and raise any existing ones
        if not self.window:
            # Windows are associated with the application
            # when the last one is closed the application shuts down
            self.window = MainWindow(file_path=self.file_path)
            self.window.connect("delete-event", self.on_quit)
            self.window.set_wmclass("easy-ebook-viewer", "easy-ebook-viewer")
        self.window.show_all()
        if not self.window.book_loaded:
            self.window.header_bar_component.hide_jumping_navigation()
        Gtk.main() 
Example #10
Source File: audiotsmgtk.py    From audiotsm with MIT License 5 votes vote down vote up
def main():
    """Run audiotsmgtk."""
    if len(sys.argv) <= 1:
        print('usage: audiotsmgtk.py <filename>')
        return

    window = MainWindow()
    window.open_file(sys.argv[1])

    window.show_all()

    GObject.threads_init()
    Gtk.main() 
Example #11
Source File: notificationmanager.py    From deskcon-desktop with GNU General Public License v3.0 5 votes vote down vote up
def run(self):
        GObject.threads_init()
        self.file_notification.show()

        timeout_thread = threading.Thread(target=self.input_timeout, args=())
        timeout_thread.daemon = True
        timeout_thread.start()

        Gtk.main()
        return self.accepted 
Example #12
Source File: support.py    From Tickeys-linux with MIT License 5 votes vote down vote up
def install_gobject_iteration():
    '''Import and install gobject context iteration inside our event loop.
    This is used as soon as gobject is used (like gstreamer).
    '''

    from kivy.clock import Clock

    try:
        from gi.repository import GObject as gobject
    except ImportError:
        import gobject

    if hasattr(gobject, '_gobject_already_installed'):
        # already installed, don't do it twice.
        return

    gobject._gobject_already_installed = True

    # get gobject mainloop / context
    loop = gobject.MainLoop()
    gobject.threads_init()
    context = loop.get_context()

    # schedule the iteration each frame
    def _gobject_iteration(*largs):
        # XXX we need to loop over context here, otherwise, we might have a lag
        loop = 0
        while context.pending() and loop < 10:
            context.iteration(False)
            loop += 1
    Clock.schedule_interval(_gobject_iteration, 0)


# -----------------------------------------------------------------------------
# Android support
# ----------------------------------------------------------------------------- 
Example #13
Source File: support.py    From Tickeys-linux with MIT License 5 votes vote down vote up
def install_gobject_iteration():
    '''Import and install gobject context iteration inside our event loop.
    This is used as soon as gobject is used (like gstreamer).
    '''

    from kivy.clock import Clock

    try:
        from gi.repository import GObject as gobject
    except ImportError:
        import gobject

    if hasattr(gobject, '_gobject_already_installed'):
        # already installed, don't do it twice.
        return

    gobject._gobject_already_installed = True

    # get gobject mainloop / context
    loop = gobject.MainLoop()
    gobject.threads_init()
    context = loop.get_context()

    # schedule the iteration each frame
    def _gobject_iteration(*largs):
        # XXX we need to loop over context here, otherwise, we might have a lag
        loop = 0
        while context.pending() and loop < 10:
            context.iteration(False)
            loop += 1
    Clock.schedule_interval(_gobject_iteration, 0)


# -----------------------------------------------------------------------------
# Android support
# ----------------------------------------------------------------------------- 
Example #14
Source File: hmi.py    From virtuaplant with MIT License 5 votes vote down vote up
def main():
    GObject.threads_init()
    win = HMIWindow(PLC_SERVER_IP, PLC_SERVER_PORT)

    win.connect("delete-event", Gtk.main_quit)
    win.connect("destroy", Gtk.main_quit)

    win.show_all()
    Gtk.main() 
Example #15
Source File: main.py    From Dindo-Bot with MIT License 5 votes vote down vote up
def __init__(self, title=__program_name__):
		GObject.threads_init() # allow threads to update GUI
		Gtk.Window.__init__(self, title=title)
		logger.add_separator()
		# Initialise class attributes
		self.game_window = None
		self.game_window_location = None
		self.bot_path = None
		self.bot_thread = None
		self.args = tools.get_cmd_args()
		# Get settings
		self.settings = settings.load()
		# Header Bar
		self.create_header_bar(title)
		# Tabs
		self.create_tabs()
		# Window
		self.set_icon_from_file(tools.get_full_path('icons/logo.png'))
		#self.set_size_request(350, 700)
		self.set_default_size(350, 700)
		self.set_resizable(False)
		self.connect('key-press-event', self.on_key_press)
		#self.connect('configure-event', self.on_resize_or_move)
		#self.connect('window-state-event', self.on_minimize)
		self.connect('destroy', Gtk.main_quit)
		self.show_all()
		self.unbind_button.hide()
		if not self.settings['Debug']['Enabled']:
			self.debug_page.hide()
		if not self.settings['State']['EnablePodBar']:
			self.podbar_box.hide()
		if not self.settings['State']['EnableMiniMap']:
			self.minimap_box.hide() 
Example #16
Source File: run.py    From battery-monitor with GNU General Public License v3.0 5 votes vote down vote up
def main() -> None:
    # checking Test Mode enabled or not
    try:
        if sys.argv[1] == '--test':
            TEST_MODE = True
        else:
            TEST_MODE = False
    except IndexError:
        TEST_MODE = False

    # initiaing app indicator
    indicator = AppIndicator(TEST_MODE)
    GObject.threads_init()
    Gtk.main() 
Example #17
Source File: __init__.py    From AstroBox with GNU Affero General Public License v3.0 5 votes vote down vote up
def startPipelineProcess(device, size, rotation, source, encoding, onListeningEvent, errorState, procPipe, debugLevel=0):
	from gi.repository import GObject

	GObject.threads_init()
	mainLoop = GObject.MainLoop()

	logger = logging.getLogger(__name__ + ':processLoop')
	interface = None

	def onFatalError(details):
		if interface:
			interface.sendResponse(0, {'error': 'fatal_error', 'details': details})
		else:
			#There was a fatal error during the creation of the pipeline, interface has not even been created
			logger.error('Fatal error creating pipeline: %s' % details)
			raise SystemExit(-1)

	try:
		pipeline = pipelineFactory(device, size, rotation, source, encoding, onFatalError, mainLoop, debugLevel)
	except InvalidGStreamerPipelineException as e:
		logger.error(e)
		raise SystemExit(-1)

	interface = processInterface(pipeline, procPipe, mainLoop, onListeningEvent)

	try:
		interface.start()
		logger.debug('Pipeline process started')
		mainLoop.run()

	except KeyboardInterrupt, SystemExit:
		mainLoop.quit() 
Example #18
Source File: pomodoro_indicator.py    From pomodoro-indicator with GNU General Public License v3.0 5 votes vote down vote up
def main():
    if dbus.SessionBus().request_name(
        'es.atareao.PomodoroIndicator') !=\
            dbus.bus.REQUEST_NAME_REPLY_PRIMARY_OWNER:
        print("application already running")
        exit(0)
    GObject.threads_init()
    Gst.init(None)
    Gst.init_check(None)
    Notify.init('pomodoro-indicator')
    Pomodoro_Indicator()
    Gtk.main() 
Example #19
Source File: provider.py    From Adafruit_Python_BluefruitLE with MIT License 5 votes vote down vote up
def initialize(self):
        """Initialize bluez DBus communication.  Must be called before any other
        calls are made!
        """
        # Ensure GLib's threading is initialized to support python threads, and
        # make a default mainloop that all DBus objects will inherit.  These
        # commands MUST execute before any other DBus commands!
        GObject.threads_init()
        dbus.mainloop.glib.threads_init()
        # Set the default main loop, this also MUST happen before other DBus calls.
        self._mainloop = dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        # Get the main DBus system bus and root bluez object.
        self._bus = dbus.SystemBus()
        self._bluez = dbus.Interface(self._bus.get_object('org.bluez', '/'),
                                     'org.freedesktop.DBus.ObjectManager') 
Example #20
Source File: __main__.py    From pyWinUSB with MIT License 5 votes vote down vote up
def main():
    if not check_root_access():
        sys.exit("\nOnly root can run this script :(\n")

    win = AppWindow()
    win.show_all()

    Gdk.threads_enter()
    GObject.threads_init()
    Gtk.main()
    Gdk.threads_leave() 
Example #21
Source File: dbusservice.py    From deskcon-desktop with GNU General Public License v3.0 5 votes vote down vote up
def run(self):
        DBusGMainLoop(set_as_default=True)        
        GObject.threads_init()
        dbus.mainloop.glib.threads_init()
        self.dbusservice = self.DbusService(self.connector)        
        Gtk.main() 
Example #22
Source File: setupdevice.py    From deskcon-desktop with GNU General Public License v3.0 5 votes vote down vote up
def main(args):
    GObject.threads_init()
    win = EntryWindow()
    Gtk.main() 
Example #23
Source File: sms.py    From deskcon-desktop with GNU General Public License v3.0 5 votes vote down vote up
def main(args):
    GObject.threads_init()
    ip = args[1]
    port = args[2]
    if (len(args) == 4):       
        number = args[3]
    else:
        number = ""

    win = EntryWindow(ip, port, number)
    Gtk.main() 
Example #24
Source File: windows.py    From deskcon-desktop with GNU General Public License v3.0 5 votes vote down vote up
def start(self):        
        self.connect("destroy", Gtk.main_quit)
        self.set_position(Gtk.WindowPosition.CENTER)
        self.show_all()
        GObject.threads_init()
        Gtk.main()
        return self.accepted 
Example #25
Source File: filechooser.py    From deskcon-desktop with GNU General Public License v3.0 5 votes vote down vote up
def main(args):
    GObject.threads_init()
    ip = args[1]
    port = args[2]
    win = FileChooserWindow()
    win.run(ip, port) 
Example #26
Source File: fingerprints.py    From deskcon-desktop with GNU General Public License v3.0 5 votes vote down vote up
def start(self):        
        self.connect("destroy", Gtk.main_quit)
        self.set_position(Gtk.WindowPosition.CENTER)
        self.show_all()
        GObject.threads_init()
        Gtk.main()
        return self.accepted 
Example #27
Source File: notificationmanager.py    From deskcon-desktop with GNU General Public License v3.0 5 votes vote down vote up
def run(self):
        GObject.threads_init()
        self.sms_notification.show()
        Gtk.main() 
Example #28
Source File: notificationmanager.py    From deskcon-desktop with GNU General Public License v3.0 5 votes vote down vote up
def input_timeout(self):
        GObject.threads_init()
        timeout = FILE_TIMEOUT
        while self.waiting_for_user_input:
            time.sleep(1)
            timeout = timeout - 1
            if timeout == 0:
                self.file_notification.close()
                self.waiting_for_user_input = False
                buildNotification("File", "Filetranfser was canceled after 60 seconds")
                Gtk.main_quit()
                break 
Example #29
Source File: __init__.py    From zim-desktop-wiki with GNU General Public License v2.0 4 votes vote down vote up
def _run_main_loop(self, cmd):
		# Run for the 1st gtk command in a primary process,
		# but can still be standalone process
		from gi.repository import Gtk
		from gi.repository import GObject

		#######################################################################
		# WARNING: commented out "GObject.threads_init()" because it leads to
		# various segfaults on linux. See github issue #7
		# However without this init, gobject does not properly release the
		# python GIL during C calls, so threads may block while main loop is
		# waiting. Thus threads become very slow and unpredictable unless we
		# actively monitor them from the mainloop, causing python to run
		# frequently. So be very carefull relying on threads.
		# Re-evaluate when we are above PyGObject 3.10.2 - threading should
		# wotk bettter there even without this statement. (But even then,
		# no Gtk calls from threads, just "GObject.idle_add()". )
		# Kept for windows, because we need thread to run ipc listener, and no
		# crashes observed there.
		if os.name == 'nt':
			GObject.threads_init()
		#######################################################################

		from zim.gui.widgets import gtk_window_set_default_icon
		gtk_window_set_default_icon()

		zim.errors.set_use_gtk(True)
		self._setup_signal_handling()

		if self._standalone:
			logger.debug('Starting standalone process')
		else:
			logger.debug('Starting primary process')
			self._daemonize()
			if not _ipc_start_listening(self._handle_incoming):
				logger.warn('Failure to setup socket, falling back to "--standalone" mode')
				self._standalone = True

		w = cmd.run()
		if w is not None:
			self.add_window(w)

		while self._windows:
			Gtk.main()

			for toplevel in list(self._windows):
				try:
					toplevel.destroy()
				except:
					logger.exception('Exception while destroying window')
					self.remove_window(toplevel) # force removal

			# start main again if toplevels remaining ..

		# exit immediatly if no toplevel created 
Example #30
Source File: gst-player.py    From streamlink with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def main():
    if len(sys.argv) < 3:
        exit("Usage: {0} <url> <quality>".format(sys.argv[0]))

    # Initialize and check GStreamer version
    gi.require_version("Gst", "1.0")
    gobject.threads_init()
    gst.init(None)

    # Collect arguments
    url = sys.argv[1]
    quality = sys.argv[2]

    # Create the Streamlink session
    streamlink = Streamlink()

    # Enable logging
    streamlink.set_loglevel("info")
    streamlink.set_logoutput(sys.stdout)

    # Attempt to fetch streams
    try:
        streams = streamlink.streams(url)
    except NoPluginError:
        exit("Streamlink is unable to handle the URL '{0}'".format(url))
    except PluginError as err:
        exit("Plugin error: {0}".format(err))

    if not streams:
        exit("No streams found on URL '{0}'".format(url))

    # Look for specified stream
    if quality not in streams:
        exit("Unable to find '{0}' stream on URL '{1}'".format(quality, url))

    # We found the stream
    stream = streams[quality]

    # Create the player and start playback
    player = StreamlinkPlayer()

    # Blocks until playback is done
    player.play(stream)