Example #1
0
    def __init__(self, glib_context=None, gtk=False, application=None):

        assert (glib_context is not None) + bool(gtk) + (application
                                                         is not None) <= 1

        self._gtk = gtk
        self._application = application

        if gtk or self._application is not None:
            self._context = GLib.main_context_default()
        else:
            self._context = glib_context if glib_context else GLib.MainContext(
            )

        self._readers = {}
        self._writers = {}
        self._sighandlers = {}
        self._chldhandlers = {}
        self._handlers = set()
        self._ready = collections.deque()
        self._wakeup = None
        self._will_dispatch = False
        self._loop_implem = None
        self._interrupted = False

        super(BaseGLibEventLoop, self).__init__()

        # install a default handler for SIGINT
        # in the default context
        if self._context == GLib.main_context_default():
            assert hasattr(self, "_default_sigint_handler"
                           ), "Must call BaseGLibEventLoop.init_class() first"
            self._default_sigint_handler.attach(self)
Example #2
0
 def pulse(self, owner):
     """Callback to update progress information"""
     if self.transaction.cancelled:
         return False
     self.transaction.progress_details = (self.current_items,
                                          self.total_items,
                                          self.current_bytes,
                                          self.total_bytes,
                                          self.current_cps,
                                          self.elapsed_time)
     percent = (((self.current_bytes + self.current_items) * 100.0) /
                float(self.total_bytes + self.total_items))
     progress = int(self.progress_begin + percent / 100 *
                    (self.progress_end - self.progress_begin))
     # If the progress runs backwards emit an illegal progress value
     # e.g. during cache updates.
     if self.progress > progress:
         self.transaction.progress = 101
     else:
         self.transaction.progress = progress
         self.progress = progress
     # Show all currently downloaded files
     items = []
     for worker in owner.workers:
         if not worker.current_item:
             continue
         self._emit_acquire_item(worker.current_item, worker.total_size,
                                 worker.current_size)
         items.append(worker.current_item)
     self._emit_status_details(items)
     while GLib.main_context_default().pending():
         GLib.main_context_default().iteration()
     return True
    def __init__(self, glib_context=None, gtk=False, application=None):

        assert (glib_context is not None) + bool(gtk) + (application is not None) <= 1

        self._gtk = gtk
        self._application = application

        if gtk or self._application is not None:
            self._context = GLib.main_context_default()
        else:
            self._context = glib_context if glib_context else GLib.MainContext()

        self._closed = False
        self._readers = {}
        self._writers = {}
        self._sighandlers = {}
        self._chldhandlers = {}
        self._handlers = set()
        self._ready   = collections.deque()
        self._wakeup  = None
        self._will_dispatch = False
        self._loop_implem = None
        self._interrupted = False

        super().__init__()

        # install a default handler for SIGINT
        # in the default context
        if self._context == GLib.main_context_default():
            assert hasattr(self, "_default_sigint_handler"), "Must call BaseGLibEventLoop.init_class() first"
            self._default_sigint_handler.attach(self)
Example #4
0
 def pulse(self, owner):
     """Callback to update progress information"""
     if self.transaction.cancelled:
         return False
     self.transaction.progress_details = (
         self.current_items,
         self.total_items,
         self.current_bytes,
         self.total_bytes,
         self.current_cps,
         self.elapsed_time,
     )
     percent = ((self.current_bytes + self.current_items) * 100.0) / float(self.total_bytes + self.total_items)
     progress = int(self.progress_begin + percent / 100 * (self.progress_end - self.progress_begin))
     # If the progress runs backwards emit an illegal progress value
     # e.g. during cache updates.
     if self.progress > progress:
         self.transaction.progress = 101
     else:
         self.transaction.progress = progress
         self.progress = progress
     # Show all currently downloaded files
     items = []
     for worker in owner.workers:
         if not worker.current_item:
             continue
         self._emit_acquire_item(worker.current_item, worker.total_size, worker.current_size)
         items.append(worker.current_item)
     self._emit_status_details(items)
     while GLib.main_context_default().pending():
         GLib.main_context_default().iteration()
     return True
def get_license_key(uid, pkg_name, json_token, server_name):
    """Return the license key and the path for the given package."""
    rootdir = apt_pkg.config["Dir"]
    license_key_helper = os.path.join(
        rootdir, "usr/share/software-center/ubuntu-license-key-helper")
    cmd = [license_key_helper, "--server", server_name, "--pkgname", pkg_name]
    proc = subprocess.Popen(
        cmd,
        stdin=subprocess.PIPE,
        stderr=subprocess.PIPE,
        stdout=subprocess.PIPE,
        preexec_fn=lambda: os.setuid(uid),
        close_fds=True,
        # this will give us str in py3 instead of bytes
        universal_newlines=True)
    # send json token to the process
    proc.stdin.write(json_token + "\n")
    # wait until it finishes
    while proc.poll() is None:
        while GLib.main_context_default().pending():
            GLib.main_context_default().iteration()
            time.sleep(0.05)

    if proc.returncode != 0:
        stderr = proc.stderr.read()
        raise TransactionFailed(ERROR_LICENSE_KEY_DOWNLOAD_FAILED, stderr)

    # get data from stdout
    license_key_path = proc.stdout.readline().strip()
    license_key = proc.stdout.read()

    return license_key, license_key_path
def get_license_key(uid, pkg_name, json_token, server_name):
    """Return the license key and the path for the given package."""
    rootdir = apt_pkg.config["Dir"]
    license_key_helper = os.path.join(rootdir, "usr/share/software-center/ubuntu-license-key-helper")
    cmd = [license_key_helper, "--server", server_name, "--pkgname", pkg_name]
    proc = subprocess.Popen(
        cmd,
        stdin=subprocess.PIPE,
        stderr=subprocess.PIPE,
        stdout=subprocess.PIPE,
        preexec_fn=lambda: os.setuid(uid),
        close_fds=True,
        # this will give us str in py3 instead of bytes
        universal_newlines=True,
    )
    # send json token to the process
    proc.stdin.write(json_token + "\n")
    # wait until it finishes
    while proc.poll() is None:
        while GLib.main_context_default().pending():
            GLib.main_context_default().iteration()
            time.sleep(0.05)

    if proc.returncode != 0:
        stderr = proc.stderr.read()
        raise TransactionFailed(ERROR_LICENSE_KEY_DOWNLOAD_FAILED, stderr)

    # get data from stdout
    license_key_path = proc.stdout.readline().strip()
    license_key = proc.stdout.read()

    return license_key, license_key_path
Example #7
0
    def test_sources(self):
        loop = GLib.MainLoop()

        self.setup_timeout(loop)

        idle = Idle(loop)
        self.assertEqual(idle.get_context(), None)
        idle.attach()
        self.assertEqual(idle.get_context(), GLib.main_context_default())

        self.pos = 0

        m = MySource()
        self.assertEqual(m.get_context(), None)
        m.set_callback(self.my_callback, loop)
        m.attach()
        self.assertEqual(m.get_context(), GLib.main_context_default())

        loop.run()

        m.destroy()
        idle.destroy()

        self.assertGreater(self.pos, 0)
        self.assertGreaterEqual(idle.count, 0)
        self.assertTrue(m.is_destroyed())
        self.assertTrue(idle.is_destroyed())
Example #8
0
    def test_sources(self):
        loop = GLib.MainLoop()

        self.setup_timeout(loop)

        idle = Idle(loop)
        self.assertEqual(idle.get_context(), None)
        idle.attach()
        self.assertEqual(idle.get_context(), GLib.main_context_default())

        self.pos = 0

        m = MySource()
        self.assertEqual(m.get_context(), None)
        m.set_callback(self.my_callback, loop)
        m.attach()
        self.assertEqual(m.get_context(), GLib.main_context_default())

        loop.run()

        m.destroy()
        idle.destroy()

        self.assertGreater(self.pos, 0)
        self.assertGreaterEqual(idle.count, 0)
        self.assertTrue(m.is_destroyed())
        self.assertTrue(idle.is_destroyed())
Example #9
0
def open(uri):
    """Connects to the given URI."""

    def mount_done(location, result, ignored):
        try:
            location.mount_enclosing_volume_finish(result)
        except GLib.GError as exc:
            print(colored("Could not connect: {}".format(exc.args[0]),
                          "red"))
        else:
            print("Connected to {} :-)".format(location.get_uri()))
        connected.set()

    # XXX disconnect first

    connection = Gio.file_new_for_uri(uri)
    if not connection.query_exists():
        connected = Event()
        mount_operation = Gio.MountOperation()
        connection.mount_enclosing_volume(
            Gio.MountMountFlags.NONE, mount_operation, None,
            mount_done, None)
        while not connected.is_set():
            GLib.main_context_default().iteration(False)
    else:
        print("Connected to", uri)

    return connection
Example #10
0
 def show(self):
   """Show this mouse indicator and ignore awaiting fade away request."""
   if self.timeout_timer and self.shown:
     # There is a fade away request, ignore it
     if GLib.main_context_default().find_source_by_id(self.timeout_timer) and not GLib.main_context_default().find_source_by_id(self.timeout_timer).is_destroyed():
       GLib.source_remove(self.timeout_timer)
     self.timeout_timer = None
     # This method only is called when mouse is pressed, so there will be a
     # release and fade_away call, no need to set up another timer.
   super(ShapedWindow, self).show()
Example #11
0
 def wait_for_status(self, desiredstatus, alternative_breakfunc=lambda: False):
     """Wait until the instrument comes into the desired state or alternative_breakfunc() returns True.
     During the wait, this calls the default GObject main loop.
     """
     while not (self.status == desiredstatus or alternative_breakfunc()):
         for i in range(100):
             GLib.main_context_default().iteration(False)
             if not GLib.main_context_default().pending():
                 break
     return not alternative_breakfunc()
Example #12
0
 def wait_for_vacuum(self, pthreshold=1.0, alternative_breakfunc=lambda: False):
     """Wait until the vacuum becomes better than pthreshold or alternative_breakfunc() returns True.
     During the wait, this calls the default GObject main loop.
     """
     while not (self.pressure <= pthreshold or alternative_breakfunc()):
         for i in range(100):
             GLib.main_context_default().iteration(False)
             if not GLib.main_context_default().pending():
                 break
     return (not alternative_breakfunc())
Example #13
0
 def wait_for_idle(self, alternative_breakfunc=lambda: False):
     """Wait until the instrument becomes idle or alternative_breakfunc() returns True.
     During the wait, this calls the default GObject main loop.
     """
     while not (self.is_idle() or alternative_breakfunc()):
         for i in range(100):
             GLib.main_context_default().iteration(False)
             if not GLib.main_context_default().pending():
                 break
     return (not alternative_breakfunc())
Example #14
0
 def media_change(self, medium, drive):
     """Callback for media changes"""
     self.transaction.required_medium = medium, drive
     self.transaction.paused = True
     self.transaction.status = enums.STATUS_WAITING_MEDIUM
     while self.transaction.paused:
         GLib.main_context_default().iteration()
     self.transaction.status = enums.STATUS_DOWNLOADING
     if self.transaction.cancelled:
         return False
     return True
Example #15
0
 def media_change(self, medium, drive):
     """Callback for media changes"""
     self.transaction.required_medium = medium, drive
     self.transaction.paused = True
     self.transaction.status = enums.STATUS_WAITING_MEDIUM
     while self.transaction.paused:
         GLib.main_context_default().iteration()
     self.transaction.status = enums.STATUS_DOWNLOADING
     if self.transaction.cancelled:
         return False
     return True
Example #16
0
    def block_on(self, func, *args, **kwargs):
        done = threading.Event()
        result = [None]

        def cb(data):
            result[0] = func(*args, **kwargs)
            done.set()

        GLib.main_context_default().invoke_full(GLib.PRIORITY_DEFAULT, cb,
                                                None)
        done.wait()
        return result[0]
Example #17
0
 def wait_for_temperature(self, interval, delta=0.01, setpoint=None, alternative_breakfunc=lambda: False):
     """Wait until the vacuum becomes better than pthreshold or alternative_breakfunc() returns True. 
     During the wait, this calls the default GObject main loop.
     """
     if setpoint is None:
         setpoint = self.get_setpoint()
     lastwrong = time.time()
     while not ((time.time() - lastwrong) > interval or alternative_breakfunc()):
         for i in range(100):
             GLib.main_context_default().iteration(False)
             if not GLib.main_context_default().pending():
                 break
         if abs(setpoint - self.get_temperature()) > delta:
             lastwrong = time.time()
     return (not alternative_breakfunc())
Example #18
0
 def __init__(self, **kwargs):
     super(GioConsole, self).__init__(**kwargs)
     self.main_context = GLib.main_context_default()
     self.input_stream = Gio.UnixInputStream.new(self.input_fd, False)
     self._active = False
     self.input_stream.read_bytes_async(
         1, GLib.PRIORITY_HIGH, None, self._read_char, None)
Example #19
0
 def setUp(self):
     self.timeout_seconds = 10  # seconds per test
     self._main_context = GLib.main_context_default()
     self.__timed_out = False
     self.__old_service_file = '/etc/avahi/services/eos-updater.service'
     self.__new_service_file = '/etc/avahi/services/eos-ostree-updater-0.service'
     self.__config_file = '/etc/eos-updater/eos-update-server.conf'
Example #20
0
    def apply_search(self, panel, add_list):
        """
        Add persons to specified panel by self.queue.
        """
        thread_event = Event()
        context = GLib.main_context_default()
        while True:
            item = self.queue.get()

            if item == 'stop':
                self.queue.task_done()
                return

            add_list.append(item.handle)
            task_id = GLib.idle_add(self.do_this, thread_event,
                                    self.add_to_result,
                                    item.handle, panel)
            task = context.find_source_by_id(task_id)
            # wait until person is added to list
            while not thread_event.wait(timeout=0.01):
                if not self.in_search:
                    if task and not task.is_destroyed():
                        GLib.source_remove(task.get_id())
                    self.queue.task_done()
                    return
            thread_event.clear()
            self.queue.task_done()
Example #21
0
    def do_activate(self):
        # only one instance
        if len(self.get_windows()) > 0:
            self.window.present(); # main window to foreground
            return

        # start setup if no login
        if not HubLinuxConfig().hasLogin:
            loop = GLib.MainLoop(GLib.main_context_default())
            assistance = InitialSetupAssistant(loop)
            assistance.show()
            loop.run()

        # setup canceled?
        if HubLinuxConfig().hasLogin:
            self.set_app_menu(self.appMenu)
            self.appWindow = Window(self)

            self.provider = Gtk.CssProvider()
            self.provider.load_from_path(ROOT_DIR + "/data/style.css")
            screen = self.appWindow.get_screen()

            self.appWindow.get_style_context().add_provider_for_screen(screen, self.provider, 1000)

            self.appWindow.show_all()
        else:
            LOG.warning("No login credentials -> Exit")
Example #22
0
 def tearDown(self):
     self.roster.window.destroy()
     # Clean main loop
     from gi.repository import GLib
     mc = GLib.main_context_default()
     while mc.pending():
         mc.iteration()
Example #23
0
    def __zerolistener(self, *args):
        if self.ended:
            return False

        cur_time = time()
        t1 = cur_time + self.getPlayerTime(WHITE)
        t2 = cur_time + self.getPlayerTime(BLACK)
        if t1 <= t2:
            t = t1
            color = WHITE
        else:
            t = t2
            color = BLACK

        s = t - cur_time + 0.01
        if s > 0 and s != self.zero_listener_time:
            if (
                (self.zero_listener_id is not None)
                and (self.zero_listener_source is not None)
                and not self.zero_listener_source.is_destroyed()
            ):
                GLib.source_remove(self.zero_listener_id)
            self.zero_listener_time = s
            self.zero_listener_id = GLib.timeout_add(10, self.__checkzero, color)
            default_context = GLib.main_context_get_thread_default() or GLib.main_context_default()
            if hasattr(default_context, "find_source_by_id"):
                self.zero_listener_source = default_context.find_source_by_id(self.zero_listener_id)
  def __init__(self):
      
      super(UPnPDeviceManager, self).__init__()
      GObject.threads_init()

      GObject.signal_new("device-available", UPnPDeviceManager, 
                         GObject.SIGNAL_RUN_LAST, 
                         GObject.TYPE_BOOLEAN, (GObject.TYPE_PYOBJECT,))

      GObject.signal_new("device-unavailable", UPnPDeviceManager, 
                         GObject.SIGNAL_RUN_LAST, 
                         GObject.TYPE_BOOLEAN, (GObject.TYPE_PYOBJECT,))

      atexit.register(self.cleanup_files)

      self.contexts = []
      self.cps = []
      self.devices = []
      self.sources = []
      self.renderers = []
      self.device_services = {}
      self.introspections = {}
      self.created_files = []

      # Get a default maincontext
      self.main_ctx = GLib.main_context_default() 
        
      # Use the built in GUPnP Network Manager to listen on 
      # all interfaces
      self.ctx_mgr = GUPnP.ContextManager.new(self.main_ctx, 0)
      self.ctx_mgr.connect("context_available", self.new_ctx)

      self.new_ctx(self.ctx_mgr, GUPnP.Context(interface="eth0"))
Example #25
0
    def do_activate(self):
        # only one instance
        if len(self.get_windows()) > 0:
            image = os.path.realpath("./assets/icon.png")
            Notify.init(APP_NAME)
            notification = Notify.Notification.new(
                APP_NAME,
                _('Another instance of %(name)s is running. You can start %(name)s only once.') % {'name': APP_NAME},
                image
            )
            notification.show()
            return

        # start setup if no login
        if not HubLinuxConfig().hasLogin:
            loop = GLib.MainLoop(GLib.main_context_default())
            assistance = InitialSetupAssistant(loop)
            assistance.show()
            loop.run()

        # setup canceled?
        if HubLinuxConfig().hasLogin:
            self.set_app_menu(self.appMenu)
            self.appWindow = Window(self)
            self.appWindow.show_all()
        else:
            LOG.warning("No login credentials -> Exit")
Example #26
0
 def test_get_total_size(self):
     def _on_query_total_size_on_install_done(pkginfo, pkgname, 
                                              download, space):
         self.need_download = download
         self.need_space = space
         loop.quit()
     TEST_PKG = "casper"
     ADDONS_TO_INSTALL = [ "lupin-casper" ]
     ADDONS_TO_REMOVE = []
     loop =  GLib.MainLoop(GLib.main_context_default())
     cache = get_test_pkg_info()
     cache.connect(
         "query-total-size-on-install-done", 
         _on_query_total_size_on_install_done)
     cache.query_total_size_on_install(
         TEST_PKG, ADDONS_TO_INSTALL, ADDONS_TO_REMOVE)
     loop.run()
     # ensure the test eventually stops and does not hang
     GLib.timeout_add_seconds(10, loop.quit)
     # work out the numbers that we at least need to get (this will
     # not include dependencies so it is probably lower)
     need_at_least_download = (
         cache[TEST_PKG].candidate.size + 
         sum([cache[pkg].candidate.size for pkg in ADDONS_TO_INSTALL]))
     need_at_least_installed = (
         cache[TEST_PKG].candidate.installed_size +
         sum([cache[pkg].candidate.installed_size for pkg in ADDONS_TO_INSTALL]))
     self.assertTrue(self.need_download >= need_at_least_download)
     self.assertTrue(self.need_space >= need_at_least_installed)
     del self.need_download
     del self.need_space
Example #27
0
 def setUp(self):
     self.timeout_seconds = 10  # seconds per test
     self._main_context = GLib.main_context_default()
     self.__timed_out = False
     self.__old_service_file = '/etc/avahi/services/eos-updater.service'
     self.__new_service_file = '/etc/avahi/services/eos-ostree-updater-0.service'
     self.__config_file = '/etc/eos-updater/eos-update-server.conf'
Example #28
0
    def __zerolistener(self, *args):
        if self.ended:
            return False

        cur_time = time()
        whites_time = cur_time + self.getPlayerTime(WHITE)
        blacks_time = cur_time + self.getPlayerTime(BLACK)
        if whites_time <= blacks_time:
            the_time = whites_time
            color = WHITE
        else:
            the_time = blacks_time
            color = BLACK

        remaining_time = the_time - cur_time + 0.01
        if remaining_time > 0 and remaining_time != self.zero_listener_time:
            if (self.zero_listener_id is not None) and \
                (self.zero_listener_source is not None) and \
                not self.zero_listener_source.is_destroyed():
                GLib.source_remove(self.zero_listener_id)
            self.zero_listener_time = remaining_time
            self.zero_listener_id = GLib.timeout_add(10, self.__checkzero,
                                                     color)
            default_context = GLib.main_context_get_thread_default(
            ) or GLib.main_context_default()
            if hasattr(default_context, "find_source_by_id"):
                self.zero_listener_source = default_context.find_source_by_id(
                    self.zero_listener_id)
Example #29
0
    def initiate_purchase(self, app, iconname, url=None, html=None):
        """
        initiates the purchase workflow inside the embedded webkit window
        for the item specified
        """
        if not self._ask_for_tos_acceptance_if_needed():
            self.emit("terms-of-service-declined")
            return False

        self.init_view()
        self.app = app
        self.iconname = iconname
        self.wk.webkit.load_html_string(self.LOADING_HTML, "file:///")
        self.wk.show()
        context = GLib.main_context_default()
        while context.pending():
            context.iteration()
        if url:
            self.wk.webkit.load_uri(url)
        elif html:
            self.wk.webkit.load_html_string(html, "file:///")
        else:
            self.wk.webkit.load_html_string(DUMMY_HTML, "file:///")
        # only for debugging
        if os.environ.get("SOFTWARE_CENTER_DEBUG_BUY"):
            GLib.timeout_add_seconds(1, _generate_events, self)
        return True
Example #30
0
    def __init__(self, figure):
        if _debug: print('FigureCanvasGTK3.%s' % fn_name())
        FigureCanvasBase.__init__(self, figure)
        GObject.GObject.__init__(self)

        self._idle_draw_id = 0
        self._need_redraw = True
        self._lastCursor = None

        self.connect('scroll_event', self.scroll_event)
        self.connect('button_press_event', self.button_press_event)
        self.connect('button_release_event', self.button_release_event)
        self.connect('configure_event', self.configure_event)
        self.connect('draw', self.on_draw_event)
        self.connect('key_press_event', self.key_press_event)
        self.connect('key_release_event', self.key_release_event)
        self.connect('motion_notify_event', self.motion_notify_event)
        self.connect('leave_notify_event', self.leave_notify_event)
        self.connect('enter_notify_event', self.enter_notify_event)
        self.connect('size_allocate', self.size_allocate)

        self.set_events(self.__class__.event_mask)

        self.set_double_buffered(True)
        self.set_can_focus(True)
        self._renderer_init()
        self._idle_event_id = GLib.idle_add(self.idle_event)
        default_context = GLib.main_context_get_thread_default(
        ) or GLib.main_context_default()
        self._idle_event_source = default_context.find_source_by_id(
            self._idle_event_id)
Example #31
0
    def getPosition(self, blocks=False):
        """
        Get the current position of the L{Pipeline}.

        @return: The current position or Gst.CLOCK_TIME_NONE
        @rtype: L{long}
        @raise PipelineError: If the position couldn't be obtained.
        """
        maincontext = GLib.main_context_default()
        if blocks and self._recovery_state == self.RecoveryState.NOT_RECOVERING:
            while self._waiting_for_async_done and self._recovery_state == self.RecoveryState.NOT_RECOVERING:
                self.info("Iterating mainloop waiting for the pipeline to be ready to be queried")
                maincontext.iteration(True)

        try:
            res, cur = self._pipeline.query_position(Gst.Format.TIME)
        except Exception as e:
            self.handleException(e)
            raise PipelineError("Couldn't get position")

        if not res:
            raise PipelineError("Position not available")

        self.log("Got position %s", format_ns(cur))
        return cur
Example #32
0
    def initiate_purchase(self, app, iconname, url=None, html=None):
        """
        initiates the purchase workflow inside the embedded webkit window
        for the item specified
        """
        if not self._ask_for_tos_acceptance_if_needed():
            self.emit("terms-of-service-declined")
            return False

        self.init_view()
        self.app = app
        self.iconname = iconname
        self.wk.webkit.load_html_string(self.LOADING_HTML, "file:///")
        self.wk.show()
        context = GLib.main_context_default()
        while context.pending():
            context.iteration()
        if url:
            self.wk.webkit.load_uri(url)
        elif html:
            self.wk.webkit.load_html_string(html, "file:///")
        else:
            self.wk.webkit.load_html_string(DUMMY_HTML, "file:///")
        # only for debugging
        if os.environ.get("SOFTWARE_CENTER_DEBUG_BUY"):
            GLib.timeout_add_seconds(1, _generate_events, self)
        return True
Example #33
0
def update_from_app_install_data(db, cache, datadir=None):
    """ index the desktop files in $datadir/desktop/*.desktop """
    if not datadir:
        datadir = softwarecenter.paths.APP_INSTALL_DESKTOP_PATH
    context = GLib.main_context_default()
    for desktopf in glob(datadir + "/*.desktop") + glob(datadir + "/*.scope"):
        LOG.debug("processing %r", desktopf)
        # process events
        while context.pending():
            context.iteration()
        try:
            if desktopf.endswith('.scope'):
                parser = ScopeConfigParser()
            else:
                parser = DesktopConfigParser()
            parser.read(desktopf)
            parser.index_app_info(db, cache)
        except Exception as e:
            # Print a warning, no error (Debian Bug #568941)
            LOG.debug("error processing: %r %r", desktopf, e)
            warning_text = _(
                "The file: '%s' could not be read correctly. The application "
                "associated with this file will not be included in the "
                "software catalog. Please consider raising a bug report "
                "for this issue with the maintainer of that application")
            LOG.warning(warning_text, desktopf)
    return True
Example #34
0
 def gobject_thread():
     ctx = GLib.main_context_default()
     while not self.qtile.is_stopped():
         try:
             ctx.iteration(True)
         except Exception:
             logger.exception('got exception from gobject')
Example #35
0
    def test_blocking_put_wait(self):

        def gen():
            when = yield
            self.assertAlmostEqual(0.01, when)
            yield 0.01

        loop = gpotato.GLibEventLoop(GLib.main_context_default())
        self.addCleanup(loop.close)

        q = asyncio.Queue(maxsize=1, loop=loop)
        started = asyncio.Event(loop=loop)
        finished = False

        @asyncio.coroutine
        def queue_put():
            nonlocal finished
            started.set()
            yield from q.put(1)
            yield from q.put(2)
            finished = True

        @asyncio.coroutine
        def queue_get():
            loop.call_later(0.01, q.get_nowait)
            queue_put_task = asyncio.Task(queue_put(), loop=loop)
            yield from started.wait()
            self.assertFalse(finished)
            yield from queue_put_task
            self.assertTrue(finished)

        loop.run_until_complete(queue_get())
        self.assertAlmostEqual(0.01, loop.time())
Example #36
0
def update_from_app_install_data(db, cache, datadir=None):
    """ index the desktop files in $datadir/desktop/*.desktop """
    if not datadir:
        datadir = softwarecenter.paths.APP_INSTALL_DESKTOP_PATH
    context = GLib.main_context_default()
    for desktopf in glob(datadir + "/*.desktop") + glob(datadir + "/*.scope"):
        LOG.debug("processing %r", desktopf)
        # process events
        while context.pending():
            context.iteration()
        try:
            if desktopf.endswith('.scope'):
                parser = ScopeConfigParser()
            else:
                parser = DesktopConfigParser()
            parser.read(desktopf)
            parser.index_app_info(db, cache)
        except Exception as e:
            # Print a warning, no error (Debian Bug #568941)
            LOG.debug("error processing: %r %r", desktopf, e)
            warning_text = _(
                "The file: '%s' could not be read correctly. The application "
                "associated with this file will not be included in the "
                "software catalog. Please consider raising a bug report "
                "for this issue with the maintainer of that application")
            LOG.warning(warning_text, desktopf)
    return True
Example #37
0
    def test_get_cancelled(self):

        def gen():
            when = yield
            self.assertAlmostEqual(0.01, when)
            when = yield 0.01
            self.assertAlmostEqual(0.061, when)
            yield 0.05

        loop = gpotato.GLibEventLoop(GLib.main_context_default())
        self.addCleanup(loop.close)

        q = asyncio.Queue(loop=loop)

        @asyncio.coroutine
        def queue_get():
            return (yield from asyncio.wait_for(q.get(), 0.051, loop=loop))

        @asyncio.coroutine
        def test():
            get_task = asyncio.Task(queue_get(), loop=loop)
            yield from asyncio.sleep(0.01, loop=loop)  # let the task start
            q.put_nowait(1)
            return (yield from get_task)

        self.assertEqual(1, loop.run_until_complete(test()))
        self.assertAlmostEqual(0.06, loop.time())
Example #38
0
    def __init__(self, figure):
        if _debug: print('FigureCanvasGTK3.%s' % fn_name())
        FigureCanvasBase.__init__(self, figure)
        GObject.GObject.__init__(self)

        self._idle_draw_id  = 0
        self._need_redraw   = True
        self._lastCursor    = None

        self.connect('scroll_event',         self.scroll_event)
        self.connect('button_press_event',   self.button_press_event)
        self.connect('button_release_event', self.button_release_event)
        self.connect('configure_event',      self.configure_event)
        self.connect('draw',                 self.on_draw_event)
        self.connect('key_press_event',      self.key_press_event)
        self.connect('key_release_event',    self.key_release_event)
        self.connect('motion_notify_event',  self.motion_notify_event)
        self.connect('leave_notify_event',   self.leave_notify_event)
        self.connect('enter_notify_event',   self.enter_notify_event)
        self.connect('size_allocate',        self.size_allocate)

        self.set_events(self.__class__.event_mask)

        self.set_double_buffered(True)
        self.set_can_focus(True)
        self._renderer_init()
        default_context = GLib.main_context_get_thread_default() or GLib.main_context_default()
Example #39
0
    def __init__(self, figure):
        FigureCanvasBase.__init__(self, figure)
        GObject.GObject.__init__(self)

        self._idle_draw_id = 0
        self._lastCursor = None

        self.connect('scroll_event', self.scroll_event)
        self.connect('button_press_event', self.button_press_event)
        self.connect('button_release_event', self.button_release_event)
        self.connect('configure_event', self.configure_event)
        self.connect('draw', self.on_draw_event)
        self.connect('key_press_event', self.key_press_event)
        self.connect('key_release_event', self.key_release_event)
        self.connect('motion_notify_event', self.motion_notify_event)
        self.connect('leave_notify_event', self.leave_notify_event)
        self.connect('enter_notify_event', self.enter_notify_event)
        self.connect('size_allocate', self.size_allocate)

        self.set_events(self.__class__.event_mask)

        self.set_double_buffered(True)
        self.set_can_focus(True)
        self._renderer_init()
        default_context = GLib.main_context_get_thread_default(
        ) or GLib.main_context_default()
Example #40
0
    def __zerolistener(self, *args):
        if self.ended:
            return False

        cur_time = time()
        whites_time = cur_time + self.getPlayerTime(WHITE)
        blacks_time = cur_time + self.getPlayerTime(BLACK)
        if whites_time <= blacks_time:
            the_time = whites_time
            color = WHITE
        else:
            the_time = blacks_time
            color = BLACK

        remaining_time = the_time - cur_time + 0.01
        if remaining_time > 0 and remaining_time != self.zero_listener_time:
            if (self.zero_listener_id is not None) and \
                (self.zero_listener_source is not None) and \
                    not self.zero_listener_source.is_destroyed():
                GLib.source_remove(self.zero_listener_id)
            self.zero_listener_time = remaining_time
            self.zero_listener_id = GLib.timeout_add(10, self.__checkzero,
                                                     color)
            default_context = GLib.main_context_get_thread_default(
            ) or GLib.main_context_default()
            if hasattr(default_context, "find_source_by_id"):
                self.zero_listener_source = default_context.find_source_by_id(
                    self.zero_listener_id)
Example #41
0
 def _perform(self, multi, handles):
     # While we're performing the cURL downloads, we need to periodically
     # process D-Bus events, otherwise we won't be able to cancel downloads
     # or handle other interruptive events.  To do this, we grab the GLib
     # main loop context and then ask it to do an iteration over its events
     # once in a while.  It turns out that even if we're not running a D-Bus
     # main loop (i.e. during the in-process tests) periodically dispatching
     # into GLib doesn't hurt, so just do it unconditionally.
     self.received = 0
     context = GLib.main_context_default()
     while True:
         # Do the progress callback, but only if the current received size
         # is different than the last one.  Don't worry about in which
         # direction it's different.
         received = int(
             sum(c.getinfo(pycurl.SIZE_DOWNLOAD) for c in handles))
         if received != self.received:
             self._do_callback()
             self.received = received
         if not self._do_once(multi, handles):
             break
         multi.select(SELECT_TIMEOUT)
         # Let D-Bus events get dispatched, but only block if downloads are
         # paused.
         while context.iteration(may_block=self._paused):
             pass
         if self._queued_cancel:
             raise Canceled
     # One last callback, unconditionally.
     self.received = int(
         sum(c.getinfo(pycurl.SIZE_DOWNLOAD) for c in handles))
     self._do_callback()
Example #42
0
    def __init__(self,
                 bus_address: str = None,
                 bus_type: BusType = BusType.SESSION):
        if _import_error:
            raise _import_error

        super().__init__(bus_address, bus_type, ProxyObject)
        self._main_context = GLib.main_context_default()
Example #43
0
 def __init__(self):
     super().__init__()
     if isinstance(threading.current_thread(), threading._MainThread):
         self._context = GLib.main_context_default()
     else:
         self._context = GLib.MainContext()
     self.loop = GLib.MainLoop(self._context)
     self.pending_events = set()
Example #44
0
 def _conffile(self, current, new):
     """Callback for a config file conflict"""
     log.warning("Config file prompt: '%s' (%s)" % (current, new))
     self.transaction.config_file_conflict = (current, new)
     self.transaction.paused = True
     self.transaction.status = enums.STATUS_WAITING_CONFIG_FILE_PROMPT
     while self.transaction.paused:
         GLib.main_context_default().iteration()
     log.debug("Sending config file answer: %s", self.transaction.config_file_conflict_resolution)
     if self.transaction.config_file_conflict_resolution == "replace":
         os.write(self.master_fd, b"y\n")
     elif self.transaction.config_file_conflict_resolution == "keep":
         os.write(self.master_fd, b"n\n")
     self.transaction.config_file_conflict_resolution = None
     self.transaction.config_file_conflict = None
     self.transaction.status = enums.STATUS_COMMITTING
     return True
Example #45
0
def wait_main_milli(t):
    _state = {"ready": False}
    c = GLib.main_context_default()
    def _func():
        _state["ready"] = True
    GLib.timeout_add(int(t), _func)
    while not _state["ready"]:
        c.iteration(True)
Example #46
0
 def __worker():
     try:
         res = func(self, *_args)
     except:
         print_except()
         res = error_ret
     ctx = GLib.main_context_default()
     ctx.invoke_full(0, _reply_hdl, res)
Example #47
0
 def _conffile(self, current, new):
     """Callback for a config file conflict"""
     log.warning("Config file prompt: '%s' (%s)" % (current, new))
     self.transaction.config_file_conflict = (current, new)
     self.transaction.paused = True
     self.transaction.status = enums.STATUS_WAITING_CONFIG_FILE_PROMPT
     while self.transaction.paused:
         GLib.main_context_default().iteration()
     log.debug("Sending config file answer: %s",
               self.transaction.config_file_conflict_resolution)
     if self.transaction.config_file_conflict_resolution == "replace":
         os.write(self.master_fd, b"y\n")
     elif self.transaction.config_file_conflict_resolution == "keep":
         os.write(self.master_fd, b"n\n")
     self.transaction.config_file_conflict_resolution = None
     self.transaction.config_file_conflict = None
     self.transaction.status = enums.STATUS_COMMITTING
     return True
    def setUp(self):
        self.loop = GLib.MainLoop(GLib.main_context_default())

        # setup bus
        dbus_service_name = DBUS_BUS_NAME
        proc, dbus_address = start_dbus_daemon()
        bus = dbus.bus.BusConnection(dbus_address)
        # run the checks
        self.bus_name = dbus.service.BusName(dbus_service_name, bus)
Example #49
0
 def show(self):
     """Show this mouse indicator and ignore awaiting fade away request."""
     if self.timeout_timer and self.shown:
         # There is a fade away request, ignore it
         if GLib.main_context_default().find_source_by_id(
                 self.timeout_timer) and not GLib.main_context_default(
                 ).find_source_by_id(self.timeout_timer).is_destroyed():
             GLib.source_remove(self.timeout_timer)
         self.timeout_timer = None
         # This method only is called when mouse is pressed, so there will be a
         # release and fade_away call, no need to set up another timer.
     super(ShapedWindow, self).show()
     # Fix click-through
     pm = gtk.gdk.Pixmap(None, self.get_size()[0], self.get_size()[1], 1)
     pmcr = pm.cairo_create()
     pmcr.rectangle(0, 0, 1, 1)
     pmcr.fill()
     self.input_shape_combine_mask(pm, 0, 0)
    def setUp(self):
        self.loop = GLib.MainLoop(GLib.main_context_default())

        # setup bus
        dbus_service_name = DBUS_BUS_NAME
        proc, dbus_address = start_dbus_daemon()
        bus = dbus.bus.BusConnection(dbus_address)
        # run the checks
        self.bus_name = dbus.service.BusName(dbus_service_name, bus)
Example #51
0
def get_url_title_async(url, readycallback, userdata, context=None):
    """Gets url's title assynchronously
    """

    if context is None:
        context = GLib.main_context_default()

    source = GetURLTitleThreadSource(url, readycallback, userdata)
    #pylint: disable=E1101
    source.attach(context)
Example #52
0
def get_url_title_async(url, readycallback, userdata, context=None):
    """Gets url's title asynchronously
    """

    if context is None:
        context = GLib.main_context_default()

    source = GetURLTitleThreadSource(url, readycallback, userdata)
    #pylint: disable=E1101
    source.attach(context)
Example #53
0
def wait_for_lock(trans, alt_lock=None):
    """Acquire the system lock or the optionally given one. If the lock
    cannot be obtained pause the transaction in the meantime.

    :param trans: the transaction
    :param lock: optional alternative lock
    """
    def watch_lock():
        """Helper to unpause the transaction if the lock can be obtained.

        Keyword arguments:
        trans -- the corresponding transaction
        alt_lock -- alternative lock to the system lock
        """
        try:
            if alt_lock:
                alt_lock.acquire()
            else:
                acquire()
        except LockFailedError:
            return True
        trans.paused = False
        return True

    try:
        if alt_lock:
            alt_lock.acquire()
        else:
            acquire()
    except LockFailedError as error:
        trans.paused = True
        trans.status = enums.STATUS_WAITING_LOCK
        if error.process:
            # TRANSLATORS: %s is the name of a package manager
            msg = trans.gettext("Waiting for %s to exit")
            trans.status_details = msg % error.process
        lock_watch = GLib.timeout_add_seconds(3, watch_lock)
        while trans.paused and not trans.cancelled:
            GLib.main_context_default().iteration()
        GLib.source_remove(lock_watch)
        if trans.cancelled:
            raise TransactionCancelled()
Example #54
0
def wait_for_lock(trans, alt_lock=None):
    """Acquire the system lock or the optionally given one. If the lock
    cannot be obtained pause the transaction in the meantime.

    :param trans: the transaction
    :param lock: optional alternative lock
    """
    def watch_lock():
        """Helper to unpause the transaction if the lock can be obtained.

        Keyword arguments:
        trans -- the corresponding transaction
        alt_lock -- alternative lock to the system lock
        """
        try:
            if alt_lock:
                alt_lock.acquire()
            else:
                acquire()
        except LockFailedError:
            return True
        trans.paused = False
        return True

    try:
        if alt_lock:
            alt_lock.acquire()
        else:
            acquire()
    except LockFailedError as error:
        trans.paused = True
        trans.status = enums.STATUS_WAITING_LOCK
        if error.process:
            # TRANSLATORS: %s is the name of a package manager
            msg = trans.gettext("Waiting for %s to exit")
            trans.status_details = msg % error.process
        lock_watch = GLib.timeout_add_seconds(3, watch_lock)
        while trans.paused and not trans.cancelled:
            GLib.main_context_default().iteration()
        GLib.source_remove(lock_watch)
        if trans.cancelled:
            raise TransactionCancelled()
Example #55
0
 def wait(self, timeout=0):
     """Wait until the corouine is finished or return after timeout seconds.
     This is achieved by running the GTK+ main loop.
     """
     clock = time.clock
     start_time = clock()
     main = GLib.main_context_default()
     while self.is_alive():
         main.iteration(False)
         if timeout and (clock() - start_time >= timeout):
             return
 def ensure_installation_date_and_lazy_history_loading(self, appdetails):
     # we run two tests, the first is to ensure that we get a
     # result from installation_data immediately (at this point the
     # history is not loaded yet) so we expect "None"
     self.assertEqual(appdetails.installation_date, None)
     # then we need to wait until the history is loaded in the idle
     # handler
     context = GLib.main_context_default()
     while context.pending():
         context.iteration()
     # ... and finally we test that its really there
     # FIXME: this will only work if software-center is installed
     self.assertNotEqual(appdetails.installation_date, None)
Example #57
0
 def setUp(self):
     self.loop = GLib.MainLoop(GLib.main_context_default())
     self.error = False
     if "SOFTWARE_CENTER_RECOMMENDER_HOST" in os.environ:
         orig_host = os.environ.get("SOFTWARE_CENTER_RECOMMENDER_HOST")
         self.addCleanup(os.environ.__setitem__,
                         "SOFTWARE_CENTER_RECOMMENDER_HOST", orig_host)
     else:
         self.addCleanup(os.environ.pop, "SOFTWARE_CENTER_RECOMMENDER_HOST")
     server = "https://rec.staging.ubuntu.com"
     os.environ["SOFTWARE_CENTER_RECOMMENDER_HOST"] = server
     # most tests need it
     self.recommender_agent = RecommenderAgent()
     self.recommender_agent.connect("error", self.on_query_error)
Example #58
0
 def __init__(self, use_cache=True):
     LOG.debug("AptHistory.__init__()")
     self.main_context = GLib.main_context_default()
     self.history_file = apt_pkg.config.find_file("Dir::Log::History")
     #Copy monitoring of history file changes from historypane.py
     self.logfile = Gio.File.new_for_path(self.history_file)
     self.monitor = self.logfile.monitor_file(0, None)
     self.monitor.connect("changed", self._on_apt_history_changed)
     self.update_callback = None
     LOG.debug("init history")
     # this takes a long time, run it in the idle handler
     self._transactions = []
     self._history_ready = False
     GLib.idle_add(self._rescan, use_cache)
Example #59
0
	def __init__(self):
		import gi.repository.GLib as glib
		self.IO_ERR = glib.IO_ERR
		self.IO_HUP = glib.IO_HUP
		self.IO_IN = glib.IO_IN
		self.IO_NVAL = glib.IO_NVAL
		self.IO_OUT = glib.IO_OUT
		self.IO_PRI = glib.IO_PRI
		self.iteration = glib.main_context_default().iteration
		self.child_watch_add = glib.child_watch_add
		self.idle_add = glib.idle_add
		self.io_add_watch = glib.io_add_watch
		self.timeout_add = glib.timeout_add
		self.source_remove = glib.source_remove