Ejemplo n.º 1
0
def get_ibus_bus():
    """Get the ibus bus object, possibly starting the ibus daemon if it's
    not already running.

    :raises: **RuntimeError** in the case of ibus-daemon being unavailable.

    """
    bus = IBus.Bus()
    if bus.is_connected():
        return bus

    main_loop = GLib.MainLoop()

    timeout = 5
    GLib.timeout_add_seconds(timeout, lambda *args: main_loop.quit())
    bus.connect("connected", lambda *args: main_loop.quit())

    os.spawnlp(os.P_NOWAIT, "ibus-daemon", "ibus-daemon", "--xim")

    main_loop.run()

    if not bus.is_connected():
        raise RuntimeError(
            "Could not start ibus-daemon after %d seconds." % (timeout))
    return bus
Ejemplo n.º 2
0
    def _updatePositionCb(self, unused_pipeline, position):
        """Updates the progress bar and triggers the update of the file size.

        This one occurs every time the pipeline emits a position changed signal,
        which is *very* often.
        """
        self.current_position = position
        if not self.progress or not position:
            return

        length = self.project.ges_timeline.props.duration
        fraction = float(min(position, length)) / float(length)
        self.progress.updatePosition(fraction)

        # In order to have enough averaging, only display the ETA after 5s
        timediff = time.time() - self._time_started
        if not self._timeEstimateTimer:
            if timediff < 6:
                self.progress.progressbar.set_text(_("Estimating..."))
            else:
                self._timeEstimateTimer = GLib.timeout_add_seconds(
                    3, self._updateTimeEstimateCb)

        # Filesize is trickier and needs more time to be meaningful.
        if not self._filesizeEstimateTimer and (fraction > 0.33 or timediff > 180):
            self._filesizeEstimateTimer = GLib.timeout_add_seconds(
                5, self._updateFilesizeEstimateCb)
Ejemplo n.º 3
0
    def testAssetAddingRemovingAdding(self):
        def loaded(project, timeline, mainloop, result, uris):
            result[0] = True
            project.addUris(uris)

        def added(project, mainloop, result, uris):
            result[1] = True
            assets = project.list_assets(GES.UriClip)
            asset = assets[0]
            project.remove_asset(asset)
            GLib.idle_add(readd, mainloop, result, uris)

        def readd(mainloop, result, uris):
            project.addUris(uris)
            result[2] = True
            mainloop.quit()

        def quit(mainloop):
            mainloop.quit()

        # Create a blank project and save it.
        project = Project("noname")
        result = [False, False, False]
        uris = ["file://%s/samples/tears of steel.webm" % os.path.dirname(os.path.abspath(__file__))]
        project.connect("loaded", loaded, self.mainloop, result, uris)
        project.connect("done-importing", added, self.mainloop, result, uris)

        self.assertTrue(project.createTimeline())
        GLib.timeout_add_seconds(5, quit, self.mainloop)
        self.mainloop.run()
        self.assertTrue(result[0], "Project creation failed to trigger signal: loaded")
        self.assertTrue(result[1], "Asset add failed to trigger signal: done-importing")
        self.assertTrue(result[2], "Asset re-adding failed")
Ejemplo n.º 4
0
def simple():
  Gst.init(None)
  GES.init()

  timeline = GES.Timeline.new_audio_video()
  
  layer = GES.Layer()
  
  timeline.add_layer(layer)

  asset = GES.UriClipAsset.request_sync(videoFile)
  
  imageasset = GES.UriClipAsset.request_sync(imageFile)

  layer.add_asset(imageasset, 0 * Gst.SECOND, 0, 1 * Gst.SECOND, GES.TrackType.UNKNOWN)
  layer.add_asset(asset, 0 * Gst.SECOND, 0, 10 * Gst.SECOND, GES.TrackType.UNKNOWN)
  
  timeline.commit()

  pipeline = GES.Pipeline()
  pipeline.add_timeline(timeline)
  pipeline.set_state(Gst.State.PLAYING)

  mainLoop = GLib.MainLoop.new(None, False)
  GLib.timeout_add_seconds(10, quit, mainLoop)
  GLib.MainLoop().run()
Ejemplo n.º 5
0
    def test_kerneloops_nodetails(self, *args):
        '''Kernel oops report without showing details'''

        def cont(*args):
            if not self.app.w('continue_button').get_visible():
                return True
            self.app.w('continue_button').clicked()
            return False

        # remove the crash from setUp() and create a kernel oops
        os.remove(self.app.report_file)
        kernel_oops = subprocess.Popen([kernel_oops_path], stdin=subprocess.PIPE)
        kernel_oops.communicate(b'Plasma conduit phase misalignment')
        self.assertEqual(kernel_oops.returncode, 0)

        GLib.timeout_add_seconds(1, cont)
        self.app.run_crashes()

        # we should have reported one crash
        self.assertEqual(self.app.crashdb.latest_id(), 0)
        r = self.app.crashdb.download(0)
        self.assertEqual(r['ProblemType'], 'KernelOops')
        self.assertEqual(r['OopsText'], 'Plasma conduit phase misalignment')

        # data was collected
        self.assertTrue('linux' in r['Package'])
        self.assertTrue('Dependencies' in r)
        self.assertTrue('Plasma conduit' in r['Title'])

        # URL was opened
        self.assertEqual(self.app.open_url.call_count, 1)
Ejemplo n.º 6
0
    def test_add_license_key_backend(self):
        self._finished = False
        # add repo
        deb_line = "deb https://mvo:[email protected]/canonical-isd-hackers/internal-qa/ubuntu oneiric main"
        signing_key_id = "F5410BE0"
        app = Application("Test app1", self.PKGNAME)
        # install only when runnig as root, as we require polkit promtps
        # otherwise
        # FIXME: provide InstallBackendSimulate()
        if os.getuid() == 0:
            backend = get_install_backend()
            backend.ui = Mock()
            backend.connect("transaction-finished",
                            self._on_transaction_finished)
            # simulate repos becomes available for the public 20 s later
            GLib.timeout_add_seconds(20, self._add_pw_to_commercial_repo)
            # run it
            backend.add_repo_add_key_and_install_app(deb_line,
                                                     signing_key_id,
                                                     app,
                                                     "icon",
                                                     self.LICENSE_KEY)
            # wait until the pkg is installed
            while not self._finished:
                do_events_with_sleep()

        if os.getuid() == 0:
            self.assertTrue(os.path.exists(self.LICENSE_KEY_PATH))
            self.assertEqual(open(self.LICENSE_KEY_PATH).read(), self.LICENSE_KEY)
Ejemplo n.º 7
0
    def _startThumbnailing(self):
        if not self.pipeline:
            # Can happen if stopGeneration is called because the clip has been
            # removed from the timeline after the PreviewGeneratorManager
            # started this job.
            return

        self.debug(
            'Now generating thumbnails for: %s', path_from_uri(self.uri))
        query_success, duration = self.pipeline.query_duration(Gst.Format.TIME)
        if not query_success or duration == -1:
            self.debug("Could not determine duration of: %s", self.uri)
            duration = self.ges_elem.props.duration

        self.queue = list(range(0, duration, self.thumb_period))

        self._checkCPU()

        # Save periodically to avoid the common situation where the user exits
        # the app before a long clip has been fully thumbnailed.
        # Spread timeouts between 30-80 secs to avoid concurrent disk writes.
        random_time = random.randrange(30, 80)
        GLib.timeout_add_seconds(random_time, self._autosave)

        # Remove the GSource
        return False
Ejemplo n.º 8
0
	def start(self):
		os.environ["STNORESTART"] = "1"	# see syncthing --help
		os.environ["STNOUPGRADE"] = "1"	# hopefully implemented later
		try:
			self._cancel = Gio.Cancellable()
			if IS_WINDOWS:
				# Windows
				sinfo = STARTUPINFO()
				sinfo.dwFlags = STARTF_USESHOWWINDOW
				sinfo.wShowWindow = 0
				self._proc = Popen(self.commandline,
							stdin=PIPE, stdout=PIPE, stderr=PIPE,
							startupinfo=sinfo)
				self._stdout = WinPopenReader(self._proc)
				self._check = GLib.timeout_add_seconds(1, self._cb_check_alive)
			elif HAS_SUBPROCESS:
				# New Gio
				flags = Gio.SubprocessFlags.STDOUT_PIPE | Gio.SubprocessFlags.STDERR_MERGE
				self._proc = Gio.Subprocess.new(self.commandline, flags)
				self._proc.wait_check_async(None, self._cb_finished)
				self._stdout = self._proc.get_stdout_pipe()
			else:
				# Gio < 3.12 - Gio.Subprocess is missing :(
				self._proc = Popen(self.commandline, stdout=PIPE)
				self._stdout = Gio.UnixInputStream.new(self._proc.stdout.fileno(), False)
				self._check = GLib.timeout_add_seconds(1, self._cb_check_alive)
		except Exception, e:
			# Startup failed
			self.emit("failed", e)
			return
Ejemplo n.º 9
0
 def _add_modify_watcher(self, widgetName):
     # If the payload fetching thread is still running, the user can't go to
     # modify the software selection screen.  Thus, we have to set the button
     # insensitive and wait until software selection is ready to go.
     modify_widget = self.builder.get_object(widgetName)
     if not self._software_is_ready():
         GLib.timeout_add_seconds(1, self._check_for_storage_thread, modify_widget)
Ejemplo n.º 10
0
    def __init__ (self, run_selector = True):
        """run_selector means that we start our regular game.

        For testing purposes, it will be convenient to hand a
        run_selector=False to this method to avoid running the dialog
        and allow a tester to set up a game programmatically.
        """
        self.settings = Gio.Settings(schema="org.gnome.gnome-sudoku")
        self.setup_gui()
        self.timer = timer.ActiveTimer(self.w)
        self.gsd.set_timer(self.timer)
        self.won = False
        # add the accelerator group to our toplevel window
        self.worker_connections = []
        self.is_fullscreen = False

        # setup sudoku maker...
        self.sudoku_maker = sudoku_maker.SudokuMaker()
        self.sudoku_tracker = saver.SudokuTracker()
        # generate puzzles while our use is working...
        self.show()
        if run_selector:
            self.do_stop()
            if self.select_game():
                # If this return True, the user closed...
                self.quit = True
            else:
                self.quit = False

        # Generate puzzles in background...
        GLib.timeout_add_seconds(1, lambda *args: self.start_worker_thread() and True)
Ejemplo n.º 11
0
    def poll(self, engine, ibus_input):
        if len(ibus_input) <= 0:
            return None

        self.result = ''
        self._preedit = ''
        self._context.focus_in()
        self._context.set_engine(engine)

        # Timeout in case of the engine not being installed
        self._abort = False
        timeout = threading.Timer(4.0, self.__abort)
        timeout.start()
        while self._context.get_engine() is None:
            if self._abort is True:
                print "Error! Could not set the engine correctly."
                return None
            continue
        timeout.cancel()

        for c in ibus_input:
            self._context.process_key_event(ord(c), 0, 0)

        self._context.set_engine('')
        self._context.focus_out()

        GLib.timeout_add_seconds(5, lambda *args: self._glibloop.quit())
        self._glibloop.run()

        return unicode(self.result, "UTF-8")
Ejemplo n.º 12
0
    def testLoadedCallback(self):
        def loaded(project, timeline, mainloop, result):
            result[0] = True
            mainloop.quit()

        def quit(mainloop):
            mainloop.quit()

        # Create a blank project and save it.
        project = _createRealProject(name="noname")
        result = [False]
        project.connect("loaded", loaded, self.mainloop, result)

        self.assertTrue(project.createTimeline())
        GLib.timeout_add_seconds(5, quit, self.mainloop)
        self.mainloop.run()
        self.assertTrue(
            result[0], "Blank project creation failed to trigger signal: loaded")

        # Load the blank project and make sure "loaded" is triggered.
        unused, xges_path = tempfile.mkstemp()
        uri = "file://%s" % xges_path
        try:
            project.save(project.timeline, uri, None, overwrite=True)

            project2 = _createRealProject()
            self.assertTrue(project2.createTimeline())
            result = [False]
            project2.connect("loaded", loaded, self.mainloop, result)
            GLib.timeout_add_seconds(5, quit, self.mainloop)
            self.mainloop.run()
            self.assertTrue(
                result[0], "Blank project loading failed to trigger signal: loaded")
        finally:
            os.remove(xges_path)
Ejemplo n.º 13
0
    def _updatePositionCb(self, pipeline, position):
        """
        Unlike other progression indicator callbacks, this one occurs every time
        the pipeline emits a position changed signal, which is *very* often.
        This should only be used for a smooth progressbar/percentage, not text.
        """
        self.current_position = position
        if not self.progress or not position:
            return

        length = self.app.current_project.timeline.props.duration
        fraction = float(min(position, length)) / float(length)
        self.progress.updatePosition(fraction)

        # In order to have enough averaging, only display the ETA after 5s
        timediff = time.time() - self._time_started
        if not self._timeEstimateTimer:
            if timediff < 6:
                self.progress.progressbar.set_text(_("Estimating..."))
            else:
                self._timeEstimateTimer = GLib.timeout_add_seconds(3, self._updateTimeEstimateCb)

        # Filesize is trickier and needs more time to be meaningful:
        if not self._filesizeEstimateTimer and (fraction > 0.33 or timediff > 180):
            self._filesizeEstimateTimer = GLib.timeout_add_seconds(5, self._updateFilesizeEstimateCb)
Ejemplo n.º 14
0
    def do_activate(self):
        try:
            from gi.repository import AppIndicator3 as appindicator
        except ImportError:
            logger.exception(ImportError)
            return

        if hasattr(self, 'ind'):
            self.ind.set_status(appindicator.IndicatorStatus.ACTIVE)
            self.timer_id = GLib.timeout_add_seconds(5, self.update)
            return

        self.date = datetime.date.today()
        self.app = self.object

        self.settings = Gio.Settings.new('org.gahshomar.Gahshomar')
        self.date_format = str(self.settings.get_value('persian-date-format'))
        self.date_format = self.date_format.replace("'", "")

        self.ind = appindicator.Indicator.new(
            "GahShomar-indicator",
            'org.gahshomar.Gahshomar-no-icon',
            appindicator.IndicatorCategory.APPLICATION_STATUS)
        self.ind.set_status(appindicator.IndicatorStatus.ACTIVE)

        self.menu_setup()
        self.update()

        self.timer_id = GLib.timeout_add_seconds(5, self.update)
 def fetch_poll(self, fp, async_result):
     try:
         success, data, etag = fp.load_contents_finish(async_result)
     except:
         print "request failed: error"
         GLib.timeout_add_seconds(10, self.start_poll)
         self.ind.set_icon_full("syncthing-client-error", "Couldn't connect to syncthing")
         return
     if success:
         try:
             queue = json.loads(data)
         except ValueError:
             print "request failed to parse json: error"
             GLib.timeout_add_seconds(10, self.start_poll)
             self.ind.set_icon_full("syncthing-client-error", "Couldn't connect to syncthing")
         for qitem in queue:
             self.process_event(qitem)
     else:
         print "request failed"
     if self.downloading_files or self.uploading_files:
         self.ind.set_icon_full("syncthing-client-updating", 
             "Updating %s files" % (
                 len(self.downloading_files) + len(self.uploading_files)))
     else:
         self.ind.set_icon_full("syncthing-client-idle", "Up to date")
     GLib.idle_add(self.start_poll)
Ejemplo n.º 16
0
    def _startThumbnailing(self):
        if not self.pipeline:
            # Can happen if stopGeneration is called because the clip has been
            # removed from the timeline after the PreviewGeneratorManager
            # started this job.
            return

        # self.props.width_request = self.nsToPixel(self.ges_elem.get_asset().get_filesource_asset().props.duration)
        # self.props.width = self.nsToPixel(self.ges_elem.get_asset().get_filesource_asset().props.duration)

        self.debug(
            'Now generating thumbnails for: %s', filename_from_uri(self.uri))
        query_success, duration = self.pipeline.query_duration(Gst.Format.TIME)
        if not query_success or duration == -1:
            self.debug("Could not determine duration of: %s", self.uri)
            duration = self.ges_elem.props.duration

        self.queue = list(range(0, duration, self.thumb_period))

        self._checkCPU()

        if self.ges_elem.props.in_point != 0:
            adj = self.get_hadjustment()
            adj.props.page_size = 1.0
            adj.props.value = Zoomable.nsToPixel(self.ges_elem.props.in_point)

        # self._addVisibleThumbnails()
        # Save periodically to avoid the common situation where the user exits
        # the app before a long clip has been fully thumbnailed.
        # Spread timeouts between 30-80 secs to avoid concurrent disk writes.
        random_time = random.randrange(30, 80)
        GLib.timeout_add_seconds(random_time, self._autosave)

        # Remove the GSource
        return False
Ejemplo n.º 17
0
def start(discoverer):
    atexit.register(SubProcess.finishAllSubprocesses)
    pgnfile, gameno = queryGameno(sys.argv[1])
    analyzer = queryAnalyzer(discoverer.getAnalyzers())
    secs = queryTime()
    name1, name2 = pgnfile.get_player_names(gameno)
    print("%s will now analyze the game between %s and %s with %d seconds per move." % \
            (discoverer.getName(analyzer), name1, name2, secs))
    print()
    
    global game, values
    values = {}
    game = GameModel()
    game.setPlayers([DummyPlayer(), DummyPlayer()])
    analyzer = discoverer.initAnalyzerEngine(analyzer, ANALYZING, game.variant)
    analyzer.connect('analyze', onAnalyze)
    game.spectators[HINT] = analyzer
    game.loadAndStart(sys.argv[1], pgn, gameno, -1)
    
    def cb():
        if game.ply == game.lowply:
            on_finish()
            return False
        check_blund()
        return True
    GLib.timeout_add_seconds(secs, cb)
Ejemplo n.º 18
0
 def disconnect_from_controller(self, status=True, reconnect=False):
     try:
         self._pre_disconnect(status)
     except:
         pass
     logger.debug("Disconnecting.")
     self._stop_logger()
     with self._socketlock:
         self._collector.kill.set()
         try:
             self._collector.join()
         except RuntimeError:
             pass
         if not self.connected():
             return
         try:
             self._socket.close()
         except socket.error:
             pass
         finally:
             self._socket = None
     self._invalidate_instrumentproperties()
     self.status = InstrumentStatus.Disconnected
     self.emit("disconnect-equipment", status)
     if reconnect:
         GLib.timeout_add_seconds(
             self.reconnect_interval, self.reconnect_to_controller_after_error, self.reconnect_attempts_number
         )
Ejemplo n.º 19
0
    def destroy (self):
        debugprint ("DESTROY: %s" % self)
        for binding in self.bindings:
            delattr (self, binding)

        if self.thread.isAlive ():
            GLib.timeout_add_seconds (1, self._reap_thread)
Ejemplo n.º 20
0
    def test_on_preview_port_added(self):
        """Create a Controller object, call add a source method and
        check that the callback fires
        """
        serv = Server(path=PATH, video_port=3000)
        try:
            serv.run()

            controller = Controller()
            controller.establish_connection()

            test_cb = Mock(side_effect=lambda mode, serve, type:
                           self.quit_mainloop_after(2))
            controller.on_preview_port_added(test_cb)

            sources = TestSources(video_port=3000)
            sources.new_test_video()
            sources.new_test_video()

            GLib.timeout_add_seconds(5, self.quit_mainloop)
            self.run_mainloop()

            print(test_cb.call_args_list)
            test_cb.assert_any_call(3003, 1, 7)
            test_cb.assert_any_call(3004, 1, 8)
            assert test_cb.call_count == 2

            serv.terminate(1)
        finally:
            serv.terminate_and_output_status(cov=True)
Ejemplo n.º 21
0
 def on_preferences_changed(self, settings, key, data=None):
     if key == "refresh-interval":
         self.change_timeout = True
         self.interval = settings.get_int(key)
         GLib.timeout_add_seconds(self.interval*60, self.timeout_set)
     else:
         self.preferences_changed = True
def main():
    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

    random.seed()

    bus = dbus.SessionBus()

    global manager, settings, agent_manager
    manager = NetworkManager(bus, "/org/freedesktop/NetworkManager")
    settings = Settings(bus, "/org/freedesktop/NetworkManager/Settings")
    agent_manager = AgentManager(bus, "/org/freedesktop/NetworkManager/AgentManager")

    if not bus.request_name("org.freedesktop.NetworkManager"):
        sys.exit(1)

    # Watch stdin; if it closes, assume our parent has crashed, and exit
    io = GLib.IOChannel(0)
    io.add_watch(GLib.IOCondition.HUP, stdin_cb)

    # also quit after inactivity to ensure we don't stick around if the above fails somehow
    GLib.timeout_add_seconds(20, quit_cb, None)

    try:
        mainloop.run()
    except Exception as e:
        pass

    sys.exit(0)
Ejemplo n.º 23
0
 def __init__(self):
     self.browsers = []
     
     Gtk.Window.__init__(self, title="Hello World")
     
     self.set_default_size(400, 400)
     
     self.connect("key_press_event", self.key_dispatch)
     self.connect("realize", self.on_realized)
     # self.connect("motion-notify-event", self.hide_cursor)
     
     self.notebook = Gtk.Notebook()
     self.notebook.set_show_border(False)
     self.notebook.set_show_tabs(False)
     self.notebook.set_scrollable(False)
     self.notebook.popup_disable()
     
     self.add(self.notebook)
     
     self.add_browser(self.relative_file_uri("index.html"))
     self.add_browser(self.relative_file_uri("cube.jpg"))
     self.add_browser(self.relative_file_uri("full_of_fish.png"))
     self.add_browser("http://www.google.com")
     self.add_browser("http://www.flickr.com/photos/tags/ocean/show/")
     
     GLib.timeout_add_seconds(5, self.next_timeout)
Ejemplo n.º 24
0
    def __init__(self):
        init_localization()
        self.caja_items = {}
        self.file_states = {}
        self.shared = set()

        self.read_buffer = None
        self.write_buffer = []
        self.writing = False
        self.sock = None
        self.last_prefs_mtime = 0
        self.last_shared_mtime = 0
        self.cloud_folder_uri = ""
 
        self.recv_msg = Message()
        self.file_status_msg = \
            Message(type=MessageType.FILE_STATUS,
                    fileStatus=FileStatusMessage(
                        type=FileStatusType.REQUEST,
                        status=FileStatus()))

        self.config = ConfigParser.ConfigParser()
        self.config.read(PREFS_PATH)

        try:
            import platform
            if platform.dist()[0].lower() == 'ubuntu':
                FILE_STATE_TO_EMBLEM[FileState.SYNCING] = \
                    'emblem-synchronizing-symbolic'
        except (ImportError, IndexError):
            pass

        self.update_config()
        GLib.timeout_add_seconds(30, self.update_config,
                                 priority=GLib.PRIORITY_LOW)
Ejemplo n.º 25
0
    def _startThumbnailing(self):
        self.debug('Now generating thumbnails for "%s"' % filename_from_uri(self.uri))
        self.queue = []
        query_success, duration = self.pipeline.query_duration(Gst.Format.TIME)
        if not query_success or duration == -1:
            self.debug("Could not determine duration of %s" % self.uri)
            duration = self.duration
        else:
            self.duration = duration

        current_time = 0
        while current_time < duration:
            self.queue.append(current_time)
            current_time += self.thumb_period

        self._checkCPU()

        self._addVisibleThumbnails()
        # Save periodically to avoid the common situation where the user exits
        # the app before a long clip has been fully thumbnailed.
        # Spread timeouts between 30-80 secs to avoid concurrent disk writes.
        random_time = randrange(30, 80)
        GLib.timeout_add_seconds(random_time, self._autosave)

        # Remove the GSource
        return False
Ejemplo n.º 26
0
    def test_crash_noaccept(self, *args):
        '''Crash report with non-accepting crash DB'''

        self.visible_progress = None

        def cont(*args):
            if not self.app.w('continue_button').get_visible():
                return True
            self.app.w('continue_button').clicked()
            GLib.timeout_add(200, check_progress)
            return False

        def check_progress(*args):
            self.visible_progress = self.app.w(
                'window_information_collection').get_property('visible')
            return False

        GLib.timeout_add_seconds(1, cont)
        self.app.crashdb.options['problem_types'] = ['bug']
        self.app.run_crash(self.app.report_file)

        # we should not have reported the crash
        self.assertEqual(self.app.crashdb.latest_id(), -1)
        self.assertEqual(self.app.open_url.call_count, 0)

        # no progress dialog for non-accepting DB
        self.assertNotEqual(self.visible_progress, True)

        # data was collected for whoopsie
        r = self.app.report
        self.assertEqual(r['ProblemType'], 'Crash')
        self.assertEqual(r['ExecutablePath'], '/bin/bash')
        self.assertTrue(r['Package'].startswith('bash '))
        self.assertTrue('libc' in r['Dependencies'])
        self.assertTrue('Stacktrace' in r)
Ejemplo n.º 27
0
  def refresh(self, *args):

    if self.refresh_timer_id:
      GLib.source_remove(self.refresh_timer_id)

    refresh_interval = gsettings.get_int("interval")

    if not self.maintRunning and not self.refreshRunning:
      logger.debug("Refresh interval is set to %s", refresh_interval)
      operations = []
    
      for o in self.collector.get_operations():
        interval = FEATURES[o[1]].get("interval", 1)
        if self.refresh_count % interval == 0:
          operations.append(o)
    
      if operations:
        logger.debug("** Starting Refresh - %s **", mx.DateTime.now())
        self.LoadingStarted()
        self.perform_async_operation(operations)


      self.refresh_timer_id = GLib.timeout_add_seconds(int(60 * refresh_interval), self.refresh)
    else:
      self.refresh_timer_id = GLib.timeout_add_seconds(int(30), self.refresh)

    if not self.maintDone:
      self.maint_timer_id = GLib.timeout_add_seconds(60, self.do_maintenance)

    return False
Ejemplo n.º 28
0
 def check(self):
     try:
         feed = requests.get(url).text
         feed = feed[5:-1]
         feed = json.loads(feed)
     except Exception as e:
         sys.stderr.write("Error: " + str(e) + "\n")
         feed = []
     for i in feed:
         i = i['data']
         try:
             id = i['id']
         except Exception as e:
             sys.stderr.write("Error: " + str(e) + "\n")
             id = 0
         if id > self.lastid:
             self.lastid = id
             titre = i['titre_court']
             link = "http://www.lemonde.fr" + i['link']
             if not titre.endswith('?'): titre += "."
             self.notification = Notify.Notification.new("Le Monde", titre, "dialog-information")
             self.notification.add_action("default", "Voir l'article...", self.notification_cb, link)
             try:
                 self.notification.show()
             except Exception as e: # the show can timeout
                 sys.stderr.write("Error: " + str(e) + "\n")
     GLib.timeout_add_seconds(60, self.check)
Ejemplo n.º 29
0
	def __init__(self, *args, **kwargs):
		super(CampaignViewDashboardTab, self).__init__(*args, **kwargs)
		self.graphs = []
		"""The :py:class:`.CampaignGraph` classes represented on the dash board."""

		dash_ports = {
			# dashboard position, (width, height)
			'top_left': (380, 200),
			'top_right': (380, 200),
			'bottom': (760, 200)
		}
		for dash_port, details in dash_ports.items():
			graph_name = self.config['dashboard.' + dash_port]
			cls = graphs.get_graph(graph_name)
			if not cls:
				self.logger.warning('could not get graph: ' + graph_name)
				logo_file_path = find.find_data_file('king-phisher-icon.svg')
				if logo_file_path:
					image = Gtk.Image.new_from_pixbuf(GdkPixbuf.Pixbuf.new_from_file_at_size(logo_file_path, 128, 128))
					image.show()
					self.gobjects['scrolledwindow_' + dash_port].add(image)
				continue
			graph_inst = cls(self.application, details, getattr(self, self.top_gobject).get_style_context())
			self.gobjects['scrolledwindow_' + dash_port].add(graph_inst.canvas)
			self.gobjects['box_' + dash_port].pack_end(graph_inst.navigation_toolbar, False, False, 0)
			self.graphs.append(graph_inst)
		self.logger.debug("dashboard refresh frequency set to {0} seconds".format(self.refresh_frequency))
		GLib.timeout_add_seconds(self.refresh_frequency, self.loader_idle_routine)
Ejemplo n.º 30
0
    def __init__(self, argv, finish_callback, timeout_s, stdin=None, env=None):
        self.stdout = []
        self.stderr = []
        self.stdin = []
        self.timeout = False
        self.killed = False
        self.finished = False
        self.finish_callback = finish_callback

        # FIXME: No byte string support
        self.output_debug("AsyncCommand:", argv)

        flags = (GLib.SPAWN_SEARCH_PATH | GLib.SPAWN_DO_NOT_REAP_CHILD)
        kwargs = {}
        if env is not None:
            kwargs['envp'] = env
        pid, stdin_fd, stdout_fd, stderr_fd = \
             GLib.spawn_async(argv, standard_output=True, standard_input=True,
                              standard_error=True, flags=flags, **kwargs)

        if stdin:
            self.stdin[:] = self._split_string(stdin, self.max_input_buf)
            in_io_flags = GLib.IO_OUT | GLib.IO_ERR | GLib.IO_HUP | GLib.IO_NVAL
            GLib.io_add_watch(stdin_fd, in_io_flags, self._in_io_callback,
                              self.stdin)
        else:
            os.close(stdin_fd)

        io_flags = GLib.IO_IN | GLib.IO_ERR | GLib.IO_HUP | GLib.IO_NVAL
        GLib.io_add_watch(stdout_fd, io_flags, self._io_callback, self.stdout)
        GLib.io_add_watch(stderr_fd, io_flags, self._io_callback, self.stderr)
        self.pid = pid
        GLib.child_watch_add(pid, self._child_callback)
        if timeout_s is not None:
            GLib.timeout_add_seconds(timeout_s, self._timeout_callback)
Ejemplo n.º 31
0
def run(window):
    screen = window.get_screen()
    no_of_monitors = screen.get_n_monitors()
    # return without running if more than one monitor connected (say projector)
    if no_of_monitors > 1: return
    # Run the application.
    window.show()
    window.activate_by_default()
    # initial set 1 sec time delay to start counter/timer
    GLib.timeout_add_seconds(1, window.timer)
    # hide gui after 22 seconds
    GLib.timeout_add_seconds(22, hideWindows, window)
    GLib.timeout_add_seconds(23, Gtk.main_quit)
    Gtk.main()
Ejemplo n.º 32
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()
Ejemplo n.º 33
0
    def __init__(self,
                 notifications_popup,
                 coremodel,
                 type_,
                 playlist,
                 position=None,
                 coresong=None):
        """Creates a playlist deletion notification popup (song or playlist)

        :param GtkRevealer: notifications_popup: the popup object
        :param CoreModel: core model
        :param type_: NotificationType (song or playlist)
        :param Playlist playlist: playlist
        :param int position: position of the object to delete
        :param object coresong: CoreSong for song deletion
        """
        super().__init__(column_spacing=18)
        self._notifications_popup = notifications_popup
        self._coremodel = coremodel
        self.type_ = type_
        self._playlist = playlist
        self._position = position
        self._coresong = coresong

        message = self._create_notification_message()
        self._label = Gtk.Label(label=message,
                                halign=Gtk.Align.START,
                                hexpand=True)
        self.add(self._label)

        undo_button = Gtk.Button.new_with_mnemonic(_("_Undo"))
        undo_button.connect("clicked", self._undo_deletion)
        self.add(undo_button)
        self.show_all()

        if self.type_ == PlaylistNotification.Type.PLAYLIST:
            self._coremodel.stage_playlist_deletion(self._playlist)
        else:
            playlist.stage_song_deletion(self._coresong, position)

        self._timeout_id = GLib.timeout_add_seconds(5, self._finish_deletion)
        self._notifications_popup.add_notification(self)
Ejemplo n.º 34
0
    def __init__(self, notifications_popup, type_, message, media_id):
        super().__init__(column_spacing=18)
        self._notifications_popup = notifications_popup
        self.type_ = type_
        self.media_id = media_id

        self._label = Gtk.Label(
            label=message, halign=Gtk.Align.START, hexpand=True)
        self.add(self._label)

        undo_button = Gtk.Button.new_with_mnemonic(_("_Undo"))
        undo_button.connect("clicked", self._undo_clicked)
        self.add(undo_button)
        self.show_all()

        self._timeout_id = GLib.timeout_add_seconds(
            5, self._notifications_popup.remove_notification, self,
            'finish-deletion')

        self._notifications_popup.add_notification(self)
Ejemplo n.º 35
0
    def _on_copy(self, *__):
        """
            Copy button clicked signal handler.
            Copies the OTP pin to the clipboard
        """
        self.copy_btn_stack.set_visible_child_name("ok_image")
        self._account.copy_pin()
        self.emit(
            "pin-copied",
            _("The PIN of {} was copied to the clipboard").format(
                self.account.username))

        def btn_clicked_timeout_callback(*_):
            self.copy_btn_stack.set_visible_child_name("copy_image")
            if self._timeout_id > 0:
                GLib.Source.remove(self._timeout_id)
                self._timeout_id = 0

        self._timeout_id = GLib.timeout_add_seconds(
            2, btn_clicked_timeout_callback, None)
Ejemplo n.º 36
0
    def list_devices(self, wait_to_appear=0, max_wait=15):
        if not wait_to_appear:
            return list(self._devices.values())

        self._wait_timed_out = False

        def wait_timeout_cb():
            self._wait_timed_out = True
            return False

        timeout = GLib.timeout_add_seconds(max_wait, wait_timeout_cb)
        context = mainloop.get_context()
        while len(self._devices) < wait_to_appear:
            context.iteration(may_block=True)
            if self._wait_timed_out:
                raise TimeoutError('IWD has no associated devices')

        GLib.source_remove(timeout)

        return list(self._devices.values())
Ejemplo n.º 37
0
    def start(self):
        Helper.start(self)

        self.status_match = self.bus.add_signal_receiver(
            self._minerfs_status_cb,
            signal_name="Progress",
            path=cfg.MINERFS_OBJ_PATH,
            dbus_interface=cfg.MINER_IFACE)

        # It should step out of this loop after progress changes to "Idle"
        self.timeout_id = GLib.timeout_add_seconds(REASONABLE_TIMEOUT,
                                                   self._timeout_on_idle_cb)
        self.loop.run()
        if self.timeout_id is not None:
            GLib.source_remove(self.timeout_id)

        bus_object = self.bus.get_object(cfg.MINERFS_BUSNAME,
                                         cfg.MINERFS_OBJ_PATH)
        self.miner_fs = dbus.Interface(bus_object,
                                       dbus_interface=cfg.MINER_IFACE)
Ejemplo n.º 38
0
    def _handle_file_event(self, _file_monitor, file, _other_file, event_type):
        if event_type not in (Gio.FileMonitorEvent.CREATED,
                              Gio.FileMonitorEvent.MOVED_IN):
            return

        path = file.get_path()
        logger.debug('Got file event file=%s, type=%s', path, event_type)

        try:
            with open(path) as inputfile:
                message = email.message_from_file(inputfile,
                                                  policy=email.policy.SMTP)
                self._queue.append(message)
        except FileNotFoundError:
            logger.error('Message file not found: %s', path)
            return

        if self._timer is not None:
            GLib.source_remove(self._timer)
        self._timer = GLib.timeout_add_seconds(60.0, self._handle_messages)
Ejemplo n.º 39
0
    def set_is_visible(self, visible):
        if visible != self._fully_obscured:
            return

        logging.debug('canvas_visibility_notify_event_cb %r', visible)
        if visible:
            self._fully_obscured = False
            if self._dirty:
                self.refresh()
            if self._update_dates_timer is None:
                logging.debug('Adding date updating timer')
                self._update_dates_timer = \
                    GLib.timeout_add_seconds(UPDATE_INTERVAL,
                                             self.__update_dates_timer_cb)
        else:
            self._fully_obscured = True
            if self._update_dates_timer is not None:
                logging.debug('Remove date updating timer')
                GLib.source_remove(self._update_dates_timer)
                self._update_dates_timer = None
Ejemplo n.º 40
0
    def __run_steps(self):
        self._retcode = 1

        for step in steps.get_steps():
            assert (not step.is_disabled())

            if not step.view_data:
                step.view_data = StepView(None, step)
            view = step.view_data

            if self._args.progress:
                self._progress_bar = ProgressBar(step.name)
                timer = GLib.timeout_add_seconds(1, self._on_timeout, step)

            view.run(self._args)

            if not step.is_done():
                return

        self._retcode = 0
Ejemplo n.º 41
0
	def do_selected(self):
		if not self.__activated:
			shell = self.props.shell
			self.__db = shell.props.db
			self.__entry_type = self.props.entry_type

			if not magnatune_in_progress_dir.query_exists(None):
				magnatune_in_progress_path = magnatune_in_progress_dir.get_path()
				os.mkdir(magnatune_in_progress_path, 0o700)

			if not magnatune_cache_dir.query_exists(None):
				magnatune_cache_path = magnatune_cache_dir.get_path()
				os.mkdir(magnatune_cache_path, 0o700)

			self.__activated = True
			self.__show_loading_screen(True)

			# start our catalogue updates
			self.__update_id = GLib.timeout_add_seconds(6 * 60 * 60, self.__update_catalogue)
			self.__update_catalogue()
Ejemplo n.º 42
0
        def watch(self, id, path):
            """ Sets recursive watching on specified directory """
            if self.notifier is None:
                self.wm = pyinotify.WatchManager()
                self.notifier = pyinotify.Notifier(
                    self.wm, timeout=10, default_proc_fun=self._process)
                self.glibsrc = GLib.timeout_add_seconds(
                    5, self._process_events)

            added = self.wm.add_watch(
                path.encode("utf-8"),
                pyinotify.IN_CLOSE_WRITE | pyinotify.IN_MOVED_TO
                | pyinotify.IN_MOVED_FROM | pyinotify.IN_DELETE
                | pyinotify.IN_CREATE,
                rec=True,
                quiet=False)
            if path in added:
                # Should be always
                self.wds[path] = added[path]
            log.verbose("Watching %s", path)
Ejemplo n.º 43
0
    def fullscreen(self):
        palettegroup.popdown_all()
        if self._toolbar_box is not None:
            self._toolbar_box.hide()
        if self.tray is not None:
            self.tray.hide()

        self._is_fullscreen = True

        if self.props.enable_fullscreen_mode:
            self._unfullscreen_button.show()

            if self._unfullscreen_button_timeout_id is not None:
                GObject.source_remove(self._unfullscreen_button_timeout_id)
                self._unfullscreen_button_timeout_id = None

            self._unfullscreen_button_timeout_id = \
                GLib.timeout_add_seconds(
                    _UNFULLSCREEN_BUTTON_VISIBILITY_TIMEOUT,
                    self.__unfullscreen_button_timeout_cb)
Ejemplo n.º 44
0
    def _start_timer(self, change=True):
        frame = self.photoframe
        is_mouse_over = frame.check_mouse_on_frame() and change != 'force'

        if change and not is_mouse_over and not frame.has_trash_dialog():
            self.recursion_depth = 0
            updated = self._change_photo()
        else:
            updated = False

        if updated is False:
            interval = 3
            # print "skip!"
        elif frame.is_fullscreen() or frame.is_screensaver():
            interval = SETTINGS.get_int('interval-fullscreen')
        else:
            interval = SETTINGS.get_int('interval')

        self._timer = GLib.timeout_add_seconds(interval, self._start_timer)
        return False
Ejemplo n.º 45
0
    def _act_on_changed_bookmarks(
            self, old_bookmarks: Dict[str, BookmarkData]) -> None:

        new_bookmarks = self._convert_to_set(self._bookmarks)
        old_bookmarks = self._convert_to_set(old_bookmarks)
        changed = new_bookmarks - old_bookmarks
        if not changed:
            return

        join = [jid for jid, autojoin in changed if autojoin]
        bookmarks = []
        for jid in join:
            self._log.info('Schedule autojoin in 10s for: %s', jid)
            bookmarks.append(self._bookmarks.get(jid))
        # If another client creates a MUC, the MUC is locked until the
        # configuration is finished. Give the user some time to finish
        # the configuration.
        timeout_id = GLib.timeout_add_seconds(10, self._join_with_timeout,
                                              bookmarks)
        self._join_timeouts.append(timeout_id)
    def _delete_event_cb(self, window, event):
        # If nothing is running, just close it down
        if (
            not self._active_engine.props.running
            and not self._queue_manager.get_property("running")
        ):
            return False

        # else, pop up a dialog asking for confirmation
        dialog = Gtk.MessageDialog(
            buttons=Gtk.ButtonsType.OK_CANCEL,
            message_type=Gtk.MessageType.QUESTION,
            text="The monitor engine is still running!",
            secondary_text="Are you sure you want to close this window?",
            transient_for=self,
            modal=True,
            destroy_with_parent=True,
        )

        source_id = GLib.timeout_add_seconds(
            1, self._delete_event_dialog_timeout, dialog
        )
        rv = dialog.run()
        dialog.destroy()
        GLib.source_remove(source_id)

        if rv in (Gtk.ResponseType.CANCEL, Gtk.ResponseType.DELETE_EVENT):
            return True
        elif rv in (Gtk.ResponseType.OK, Gtk.ResponseType.CLOSE):
            if (
                self._active_engine.props.running
                and self._queue_manager.get_property("running")
            ):
                # hookup signal to active_engine running property
                self._queue_manager.connect(
                    "notify::running", self._delete_event_killer
                )
                # stop it manually
                self._active_engine.stop()
                return True
            return False
Ejemplo n.º 47
0
    def _save_system_time(self):
        """
        Returning False from this method removes the timer that would
        otherwise call it again and again.

        """

        if not flags.can_touch_runtime_system("save system time"):
            return False

        month = self._get_combo_selection(self._monthCombo)[0]
        if not month:
            return False

        year = self._get_combo_selection(self._yearCombo)[0]
        if not year:
            return False

        hours = int(self._hoursLabel.get_text())
        if not self._radioButton24h.get_active():
            hours = self._to_24h(hours, self._amPmLabel.get_text())

        minutes = int(self._minutesLabel.get_text())

        day = self._get_combo_selection(self._dayCombo)[0]
        #day may be None if there is no such in the selected year and month
        if day:
            isys.set_system_date_time(year,
                                      month,
                                      day,
                                      hours,
                                      minutes,
                                      tz=self._tz)

        #start the timer only when the spoke is shown
        if self._update_datetime_timer_id is not None:
            self._update_datetime_timer_id = GLib.timeout_add_seconds(
                1, self._update_datetime)

        #run only once (after first 2 seconds of inactivity)
        return False
Ejemplo n.º 48
0
 def set_backup_timer(self):
     """
     Set the backup timer.
     """
     interval = config.get('database.autobackup')
     if self.backup_timer is not None:
         GLib.source_remove(self.backup_timer)
         self.backup_timer = None
     if interval == 1:
         minutes = 15
     elif interval == 2:
         minutes = 30
     elif interval == 3:
         minutes = 60
     elif interval == 4:
         minutes = 720
     elif interval == 5:
         minutes = 1440
     if interval > 0:
         self.backup_timer = GLib.timeout_add_seconds(
             minutes * 60, self.__emit_autobackup)
Ejemplo n.º 49
0
    def bind_subprocess(self, proc):
        unblock_fd(proc.stdout)
        watch_id_stdout = GLib.io_add_watch(
            channel=proc.stdout,
            priority_=GLib.IO_IN | GLib.IO_PRI | GLib.IO_ERR | GLib.IO_HUP,
            condition=self.buffer_update,
            # func      = lambda *a: print("func") # when the condition is satisfied
            # user_data = # user data to pass to func
        )
        unblock_fd(proc.stderr)
        watch_id_stderr = GLib.io_add_watch(
            channel=proc.stderr,
            priority_=GLib.IO_IN | GLib.IO_PRI | GLib.IO_ERR | GLib.IO_HUP,
            condition=self.buffer_update,
            # func      = lambda *a: print("func") # when the condition is satisfied
            # user_data = # user data to pass to func
        )
        watch_id_timeout = GLib.timeout_add_seconds(1, self.buffer_update)

        self.IO_WATCH_ID = (watch_id_stdout, watch_id_stderr, watch_id_timeout)
        return self.IO_WATCH_ID
Ejemplo n.º 50
0
 def add_inhibitor(self, inhibitor_id: int, caller: dbus.String,
                   reason: dbus.String, caller_process: psutil.Process):
     assert inhibitor_id not in self.inhibitors, "Already working on that inhibitor"
     inhibitor = {
         'caller': caller,
         'reason': reason,
         'caller_process': caller_process
     }
     self.inhibitors.update({inhibitor_id: inhibitor})
     print(
         f'Inhibitor requested by "{inhibitor["caller"]}" ({inhibitor["caller_process"].name()})',
         f'for reason "{inhibitor["reason"]}".',
         f'Given ID {inhibitor_id}',
         file=sys.stderr,
         flush=True)
     if self.timeout_source_id is None:
         # AIUI the minimum xscreensaver timeout is 60s, so poke it every 50s.
         # NOTE: This is exactly what xdg-screensaver does
         # UPDATE: Changed to 30 seconds because there was some (very rare) circumstances were it skipped 1 poke
         self.timeout_source_id = GLib.timeout_add_seconds(
             30, self._inhibitor_func)
Ejemplo n.º 51
0
    def start(self):
        # resume
        if self._paused:
            self._should_resume = True
            return

        # start
        if self._running:
            raise AlreadyRunning(
                "The download manager is already running. It needs to be stopped before it may be restarted"
            )

        # hook up to each of the urls' finished signal
        for url in self._appwindow._model:
            url.connect("notify::finished", self._url_finished_cb)

        self._running = True
        self._timeout_id = GLib.timeout_add_seconds(
            1, self._model_timeout_cb, priority=GLib.PRIORITY_DEFAULT
        )
        self.notify("running")
Ejemplo n.º 52
0
    def _on_source_added(self, registry, source):
        def _trigger_art_update():
            self._thumbnail_sources_timeout = None
            if len(self._thumbnail_sources) > 0:
                self.props.cover_sources = True

            return GLib.SOURCE_REMOVE

        if ("net:plaintext" in source.get_tags()
                or source.props.source_id in self._blocklist):
            try:
                registry.unregister_source(source)
            except GLib.GError:
                self._log.warning("Failed to unregister {}".format(
                    source.props.source_id))
            return

        if Grl.METADATA_KEY_THUMBNAIL in source.supported_keys():
            self._thumbnail_sources.append(source)
            if not self._thumbnail_sources_timeout:
                # Aggregate sources being added, for example when the
                # network comes online.
                self._thumbnail_sources_timeout = GLib.timeout_add_seconds(
                    5, _trigger_art_update)

        if (source.props.source_id == "grl-tracker3-source"
                and self._tracker_wrapper.location_filter() is not None):
            new_wrapper = GrlTrackerWrapper(source, self._application,
                                            self._tracker_wrapper)
            self._wrappers[source.props.source_id] = new_wrapper
            self._log.debug("Adding wrapper {}".format(new_wrapper))
        elif (source.props.source_id not in self._search_wrappers.keys()
              and source.props.source_id not in self._wrappers.keys()
              and source.props.source_id != "grl-tracker3-source"
              and source.get_supported_media() & Grl.MediaType.AUDIO
              and source.supported_operations() & Grl.SupportedOps.SEARCH
              and "net:internet" not in source.props.source_tags):
            self._search_wrappers[source.props.source_id] = GrlSearchWrapper(
                source, self._application)
            self._log.debug("Adding search source {}".format(source))
Ejemplo n.º 53
0
    def _update_state(self, state, old_state, reason):
        gsm_state = None

        if state is network.NM_DEVICE_STATE_ACTIVATED:
            gsm_state = _GSM_STATE_CONNECTED
            connection = network.find_gsm_connection()
            if connection is not None:
                self._connection_timestamp = time.time() - \
                    connection.get_settings('connection')['timestamp']
                self._connection_time_handler = GLib.timeout_add_seconds(
                    1, self.__connection_timecount_cb)
                self._palette.update_connection_time()
                self._palette.update_stats(0, 0)
                if self._palette is not None:
                    self._palette.connection_info_box.show()

        elif state is network.NM_DEVICE_STATE_DISCONNECTED:
            gsm_state = _GSM_STATE_DISCONNECTED
            self._connection_timestamp = 0
            if self._connection_time_handler is not None:
                GLib.source_remove(self._connection_time_handler)
            if self._palette is not None:
                self._palette.connection_info_box.hide()

        elif state in [
                network.NM_DEVICE_STATE_UNMANAGED,
                network.NM_DEVICE_STATE_UNAVAILABLE,
                network.NM_DEVICE_STATE_UNKNOWN
        ]:
            gsm_state = _GSM_STATE_NOT_READY

        elif (state >= network.NM_DEVICE_STATE_PREPARE) and \
             (state < network.NM_DEVICE_STATE_ACTIVATED):
            gsm_state = _GSM_STATE_CONNECTING

        elif state == network.NM_DEVICE_STATE_FAILED:
            gsm_state = _GSM_STATE_FAILED

        if self._palette is not None:
            self._palette.update_state(gsm_state, reason)
Ejemplo n.º 54
0
    def __init__(self):
        gtk.Window.__init__(self)

        self.__device_uids = set([])
        self.__last_backup_dir = None

        self.set_title('RkFlashKit')
        self.set_icon(self.render_icon('rkflashkit', gtk.IconSize.MENU))
        self.connect('delete_event', self.__on_delete_window)
        self.set_default_size(DEFAULT_WINDOW_WIDTH, 650)

        hpaned = gtk.HPaned()
        hpaned.set_position(400)
        self.add(hpaned)
        self.__create_ui(hpaned)

        self.__timer_id = glib.timeout_add_seconds(3, self.__check_devices)

        # Check devices
        self.__check_devices()

        self.show_all()
Ejemplo n.º 55
0
    def send_to_clipboard(self, text: str, message: str = "") -> None:
        if not message:
            message = _("Copied")

        self.start_database_lock_timer()

        if self.clipboard_timer_handler:
            GLib.source_remove(self.clipboard_timer_handler)
            self.clipboard_timer_handler = None

        self.clipboard.set(text)

        self.window.send_notification(message)

        clear_clipboard_time = gsecrets.config_manager.get_clear_clipboard()

        def callback():
            self.clipboard_timer_handler = None
            self.clipboard.set_content(None)

        self.clipboard_timer_handler = GLib.timeout_add_seconds(
            clear_clipboard_time, callback)
Ejemplo n.º 56
0
    def notify_launch(self, activity_id, service_name):
        registry = get_registry()
        activity_info = registry.get_bundle(service_name)
        if not activity_info:
            raise ValueError("Activity service name '%s'"
                             " was not found in the bundle registry." %
                             service_name)
        color = self._shared_activities.get(activity_id, None)
        home_activity = Activity(activity_info, activity_id, color)
        self._add_activity(home_activity)

        self._set_active_activity(home_activity)

        self.emit('launch-started', home_activity)

        if activity_id in self._launch_timers:
            GLib.source_remove(self._launch_timers[activity_id])
            del self._launch_timers[activity_id]

        timer = GLib.timeout_add_seconds(90, self._check_activity_launched,
                                         activity_id)
        self._launch_timers[activity_id] = timer
Ejemplo n.º 57
0
    def _wait_for_object_condition(obj, condition_str, max_wait=50):
        class TimeoutData:
            _wait_timed_out = False

        data = TimeoutData()

        def wait_timeout_cb(data):
            data._wait_timed_out = True
            return False

        try:
            timeout = GLib.timeout_add_seconds(max_wait, wait_timeout_cb, data)
            context = ctx.mainloop.get_context()
            while not eval(condition_str):
                context.iteration(may_block=True)
                if data._wait_timed_out and ctx.args.gdb == None:
                    raise TimeoutError('[' + condition_str + ']'\
                                       ' condition was not met in '\
                                       + str(max_wait) + ' sec')
        finally:
            if not data._wait_timed_out:
                GLib.source_remove(timeout)
Ejemplo n.º 58
0
    def reload_layout(self, force_update=False):
        """
        Checks if the X keyboard layout has changed and
        (re)loads Onboards layout accordingly.
        """
        keyboard_state = (None, None)

        vk = self.get_vk()
        if vk:
            try:
                vk.reload()  # reload keyboard names
                keyboard_state = (vk.get_layout_symbols(),
                                  vk.get_current_group_name())
            except osk.error:
                self.reset_vk()
                force_update = True
                _logger.warning("Keyboard layout changed, but retrieving "
                                "keyboard information failed")

        if self.keyboard_state != keyboard_state or force_update:
            self.keyboard_state = keyboard_state

            layout_filename = config.layout_filename
            color_scheme_filename = config.theme_settings.color_scheme_filename

            try:
                self.load_layout(layout_filename, color_scheme_filename)
            except LayoutFileError as ex:
                _logger.error("Layout error: " + unicode_str(ex) +
                              ". Falling back to default layout.")

                # last ditch effort to load the default layout
                self.load_layout(config.get_fallback_layout_filename(),
                                 color_scheme_filename)

        # if there is no X keyboard, poll until it appears (if ever)
        if not vk and not self.vk_timer:
            self.vk_timer = GLib.timeout_add_seconds(1, self.cb_vk_timer)
Ejemplo n.º 59
0
    def __enter__(self):
        log.info("Awaiting deletion of resource id %s", self.resource_id)

        query_check = ' '.join([
            'SELECT ?urn tracker:id(?urn) ',
            f'FROM NAMED <{self.graph}> ',
            ' WHERE { ',
            '   ?urn a rdfs:Resource ; ',
            '   . FILTER (tracker:id(?urn) = ~id) '
            '}'
        ])
        stmt_check = self.conn.query_statement(query_check, None)
        stmt_check.bind_int('id', self.resource_id)
        cursor = stmt_check.execute(None)
        if not cursor.next():
            raise AwaitException(
                "Resource with id %i isn't present in the store.", self.resource_id)

        def match_cb(notifier, service, graph, events):
            for event in events:
                if event.get_event_type() == Tracker.NotifierEventType.DELETE:
                    log.debug("Received %s event for id %s", event.get_event_type(), event.get_id())
                    if event.get_id() == self.resource_id:
                        log.debug("Matched expected id %s", self.resource_id)
                        self.matched = True
                        self.loop.quit()
                else:
                    log.debug("Received %s event for id %s", event.get_event_type(), event.get_id())

        def timeout_cb():
            log.info("Timeout fired after %s seconds", self.timeout)
            raise AwaitTimeoutException(
                f"Timeout ({self.timeout}s) awaiting removal of resource {self.resource_id} ")

        self.signal_id = self.notifier.connect('events', match_cb)
        self.timeout_id = GLib.timeout_add_seconds(self.timeout, timeout_cb)

        return None
Ejemplo n.º 60
0
    def await_method_call(self, method_name, timeout_seconds=20):
        """Quit the main loop when the D-Bus method @method_name is called.
        Timeout after waiting for 'timeout_seconds'. Use like this:
            self.await_method_call('MyMethod')
            # now MyMethod has been called
        """
        self._quit_on_method = method_name
        self._timed_out = False

        def _timeout():
            self._timed_out = True
            self.mainloop.quit()
            return False

        timeout_id = GLib.timeout_add_seconds(timeout_seconds, _timeout)
        self.mainloop.run()
        if self._timed_out:
            self.fail(
                f"Test timed out after waiting {timeout_seconds} seconds for D-Bus method call."
            )
        else:
            GLib.Source.remove(timeout_id)
            return self.interface_mock.GetCalls()