Пример #1
1
    def _update_timeout(self):
        """Update the duration for self.timeout and self._seconds_timeout

        Sets the period of self.timeout to a value small enough to make the
        slider of self.progressScale move smoothly based on the current song
        duration and progressScale length.  self._seconds_timeout is always set
        to a fixed value, short enough to hide irregularities in GLib event
        timing from the user, for updating the songPlaybackTimeLabel.
        """
        # Don't run until progressScale has been realized
        if self.progressScale.get_realized() == False:
            return

        # Update self.timeout
        width = self.progressScale.get_allocated_width()
        padding = self.progressScale.get_style_context().get_padding(
            Gtk.StateFlags.NORMAL)
        width -= padding.left + padding.right
        duration = self.player.query_duration(Gst.Format.TIME)[1] / 10**9
        timeout_period = min(1000 * duration // width, 1000)

        if self.timeout:
            GLib.source_remove(self.timeout)
        self.timeout = GLib.timeout_add(
            timeout_period, self._update_position_callback)

        # Update self._seconds_timeout
        if not self._seconds_timeout:
            self.seconds_period = 1000
            self._seconds_timeout = GLib.timeout_add(
                self.seconds_period, self._update_seconds_callback)
Пример #2
0
 def remove_pulsing(self):
     """
     Stop pulsing, useful when especially when removing widget
     """
     if self.pulse_id:
         GLib.source_remove(self.pulse_id)
     self.pulse_id = None
Пример #3
0
 def _recalc_width(self, path, text):
     self._texts[path[0]] = text
     if self._timeout is not None:
         GLib.source_remove(self._timeout)
         self._timeout = None
     self._timeout = GLib.idle_add(self._delayed_recalc,
         priority=GLib.PRIORITY_LOW)
    def _stop_and_maybe_start_time_updating(self, interval=2):
        """
        This method is called in every date/time-setting button's callback.
        It removes the timer for updating displayed date/time (do not want to
        change it while user does it manually) and allows us to set new system
        date/time only after $interval seconds long idle on time-setting buttons.
        This is done by the _start_updating_timer that is reset in this method.
        So when there is $interval seconds long idle on date/time-setting
        buttons, self._save_system_time method is invoked. Since it returns
        False, this timer is then removed and only reactivated in this method
        (thus in some date/time-setting button's callback).

        """

        #do not start timers if the spoke is not shown
        if self._update_datetime_timer_id is None:
            self._update_datetime()
            self._save_system_time()
            return

        #stop time updating
        GLib.source_remove(self._update_datetime_timer_id)

        #stop previous $interval seconds timer (see below)
        if self._start_updating_timer_id:
            GLib.source_remove(self._start_updating_timer_id)

        #let the user change date/time and after $interval seconds of inactivity
        #save it as the system time and start updating the displayed date/time
        self._start_updating_timer_id = GLib.timeout_add_seconds(interval,
                                                    self._save_system_time)
Пример #5
0
    def getNextImage(self):
        if self.update_id > 0:
            GLib.source_remove(self.update_id)
            self.update_id = 0

        self.loop_counter = self.slideshow_settings.get_int("delay")
        self.start_mainloop()        
Пример #6
0
 def _set_transaction(self, transaction):
     """Connect the dialog to the given aptdaemon transaction"""
     for sig in self._signals:
         GLib.source_remove(sig)
     self._signals = []
     self.current_trans = transaction
     self._signals.append(transaction.connect_after("status-changed",
                                                 self._on_status_changed))
     self._signals.append(transaction.connect("status-details-changed",
                                                 self._on_status_details_changed))
     self._signals.append(transaction.connect("role-changed",
                                                 self._on_role_changed))
     self._signals.append(transaction.connect("medium-required",
                                                 self._on_medium_required))
     self._signals.append(transaction.connect("config-file-conflict",
                                                 self._on_config_file_conflict))
     self._signals.append(transaction.connect("progress-changed",
                                                  self._on_progress_changed))
     self._signals.append(transaction.connect("progress-details-changed",
                                                  self._on_progress_details_changed))
     self._signals.append(transaction.connect("cancellable-changed",
                                                   self._on_cancellable_changed))
     self._signals.append(transaction.connect("progress-download-changed",
                                                   self._on_download_changed))
     self._signals.append(transaction.connect("terminal-attached-changed",
                                                   self._on_terminal_attached_changed))
     self._on_role_changed(transaction, transaction.role)
     if self._ttyname:
         transaction.set_terminal(self._ttyname)
Пример #7
0
    def show_playlist_notification(self):
        """Show a notification on playlist removal and provide an
        option to undo for 5 seconds.
        """

        # Callback to remove playlists
        def remove_playlist_timeout_cb(self):
            # Remove the playlist
            self.views[3].really_delete = False
            playlist.delete_playlist(self.views[3].pl_todelete)

            # Hide the notification
            self._playlist_notification.set_reveal_child(False)

            # Stop the timeout
            self._playlist_notification_timeout_id = 0

            return GLib.SOURCE_REMOVE

        # If a notification is already visible, remove that playlist
        if self._playlist_notification_timeout_id > 0:
            GLib.source_remove(self._playlist_notification_timeout_id)
            remove_playlist_timeout_cb(self)

        playlist_title = self.views[3].current_playlist.get_title()
        label = _("Playlist {} removed".format(playlist_title))

        self._playlist_notification.label.set_label(label)
        self._playlist_notification.set_reveal_child(True)

        timeout_id = GLib.timeout_add_seconds(5, remove_playlist_timeout_cb,
                                              self)
        self._playlist_notification_timeout_id = timeout_id
Пример #8
0
    def _move(self, up=False):
        text = self._search_entry.get_text()
        if not text:
            return

        if up and self.__selected_search_result == 1:
            return False

        model = self._treeview.get_model()
        selection = self._treeview.get_selection()
        # disable flush timeout while searching
        if self._entry_flush_timeout:
            GLib.source_remove(self._entry_flush_timeout)
            self._entry_flush_timeout = 0
        # search
        start_count = self.__selected_search_result + (-1 if up else 1)
        start_iter = model.get_iter_first()
        found_iter = self.search_iter(selection, start_iter, text, 0,
                                      start_count)
        if found_iter:
            self.__selected_search_result += (-1 if up else 1)
            return True
        else:
            # Return to old iter
            self.search_iter(selection, start_iter, text, 0,
                             self.__selected_search_result)
            return False
        # renew flush timeout
        self._renew_flush_timeout()
        return
Пример #9
0
 def on_playback_track_end(self, event, player, track):
     """
         Stops marker watching
     """
     if self.__timeout_id is not None:
         GLib.source_remove(self.__timeout_id)
         self.__timeout_id = None
Пример #10
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)
Пример #11
0
        def periodic_scroll():
            """Get the tree coords for 0,0 and scroll from there"""
            wx, wy, dist, ref = self.__scroll_args
            x, y = self.convert_widget_to_tree_coords(0, 0)
            x, y = self.convert_bin_window_to_widget_coords(x, y)

            # We reached an end, stop
            if self.__scroll_last == y:
                self.scroll_disable()
                return
            self.__scroll_last = y

            # If we went full speed for a while.. speed up
            # .. every number is made up here
            if self.__scroll_length >= 50 * ref:
                dist *= self.__scroll_length / (ref * 10)
            if self.__scroll_length < 2000 * ref:
                self.__scroll_length += abs(dist)

            try:
                self.scroll_to_point(-1, y + dist)
            except OverflowError:
                pass
            self.set_drag_dest(wx, wy)
            # we have to re-add the timeout.. otherwise they could add up
            # because scroll can last longer than 50ms
            GLib.source_remove(self.__scroll_periodic)
            self.__scroll_periodic = None
            enable_periodic_scroll()
Пример #12
0
 def __disable_timer(self):
     """
         Disables the update timer
     """
     if self.__timer_id is not None:
         GLib.source_remove(self.__timer_id)
         self.__timer_id = None
Пример #13
0
def unwatchAllProcesses():
    """Clear the watched process list."""
    global _forever_pids
    for child_pid in _forever_pids:
        if _forever_pids[child_pid][1]:
            GLib.source_remove(_forever_pids[child_pid][1])
    _forever_pids = {}
Пример #14
0
 def check(self):
     if self.called == self.num_cb:
         GLib.source_remove(self.timer)
         logging.info("callbacks done")
         self.parent.set_adapter_state(self.state)
         self.parent.update_power_state()
         self.parent.request_in_progress = False
Пример #15
0
    def run (self):
        if self.use_callback:
            raise RuntimeError

        if self.show_dialog:
            wait = Gtk.MessageDialog (self.parent,
                                      Gtk.DialogFlags.MODAL |
                                      Gtk.DialogFlags.DESTROY_WITH_PARENT,
                                      Gtk.MessageType.INFO,
                                      Gtk.ButtonsType.CANCEL,
                                      _("Please wait"))
            wait.connect ("delete_event", lambda *args: False)
            wait.connect ("response", self._wait_window_response)
            if self.parent:
                wait.set_transient_for (self.parent)

            wait.set_position (Gtk.WindowPosition.CENTER_ON_PARENT)
            wait.format_secondary_text (_("Gathering information"))
            wait.show_all ()

        self.timeout_source = GLib.timeout_add (50, self._check_thread)
        Gtk.main ()
        GLib.source_remove (self.timeout_source)
        if self.show_dialog:
            wait.destroy ()

        return self.thread.collect_result ()
Пример #16
0
def _sigchld_handler(num=None, frame=None):
    # Check whether anything in the list of processes being watched has
    # exited. We don't want to call waitpid(-1), since that would break
    # anything else using wait/waitpid (like the subprocess module).
    exited_pids = []
    exit_statuses = []

    for child_pid in _forever_pids:
        try:
            pid_result, status = eintr_retry_call(os.waitpid, child_pid, os.WNOHANG)
        except ChildProcessError:
            continue

        if pid_result:
            proc_name = _forever_pids[child_pid][0]
            exited_pids.append(child_pid)

            # Convert the wait-encoded status to the format used by subprocess
            if os.WIFEXITED(status):
                sub_status = os.WEXITSTATUS(status)
            else:
                # subprocess uses negative return codes to indicate signal exit
                sub_status = -os.WTERMSIG(status)

            exit_statuses.append((proc_name, sub_status))

    for child_pid in exited_pids:
        if _forever_pids[child_pid][1]:
            GLib.source_remove(_forever_pids[child_pid][1])
        del _forever_pids[child_pid]

    if exit_statuses:
        _raise_exit_error(exit_statuses)
Пример #17
0
        def do_deactivate(self):
                if self.timeout_update_id != 0:
                        GLib.source_remove(self.timeout_update_id)
                        self.timeout_update_id = 0

                        del self.update_placeholders[:]
                        del self.jump_placeholders[:]

                # Always release the reference to the global snippets
                Library().unref(None)
                self.active_placeholder = None

                self.disconnect_signals(self.view)
                self.disconnect_signals(self.view.get_buffer())

                # Remove all active snippets
                for snippet in list(self.active_snippets):
                        self.deactivate_snippet(snippet, True)

                completion = self.view.get_completion()

                if completion:
                        completion.remove_provider(self.provider)
                        completion.remove_provider(self.defaults_provider)

                if self.language_id != 0:
                        Library().unref(self.language_id)

                SharedData().unregister_controller(self.view, self)
Пример #18
0
    def cleanup(self):
        if self.timeout:
            GLib.source_remove(self.timeout)
        self.parent.bus.remove_signal_receiver(self.on_interfaces_added, "InterfacesAdded",
                                               "org.freedesktop.DBus.ObjectManager")

        del self.service
Пример #19
0
    def cleanup (self):
        if self.sub_id != -1:
            user = cups.getUser ()
            try:
                cups.setUser (self.user)
                c = cups.Connection (host=self.host,
                                     port=self.port,
                                     encryption=self.encryption)
                c.cancelSubscription (self.sub_id)
                debugprint ("Canceled subscription %d" % self.sub_id)
            except:
                pass
            cups.setUser (user)

        if self.bus is not None:
            self.bus.remove_signal_receiver (self.handle_dbus_signal,
                                             path=self.DBUS_PATH,
                                             dbus_interface=self.DBUS_IFACE)

        timers = list(self.connecting_timers.values ())
        for timer in [self.update_timer, self.fetch_jobs_timer]:
            if timer:
                timers.append (timer)
        for timer in timers:
            GLib.source_remove (timer)

        self.emit ('monitor-exited')
Пример #20
0
    def stop (self):
        if self.process is None:
            # Seems that it didn't even start...
            return

        start = time.time()
        if self.process.poll() == None:
            GLib.source_remove(self.process_watch_timeout)
            self.process_watch_timeout = 0

            self.process.terminate()

            while self.process.poll() == None:
                time.sleep(0.1)

                if time.time() > (start + REASONABLE_TIMEOUT):
                    log ("[%s] Failed to terminate, sending kill!" % self.PROCESS_NAME)
                    self.process.kill()
                    self.process.wait()

        log ("[%s] stopped." % self.PROCESS_NAME)

        # Run the loop until the bus name appears, or the process dies.
        self.loop.run ()
        Gio.bus_unwatch_name(self._bus_name_watch_id)

        self.process = None
Пример #21
0
 def _on_progress_scale_event(self, scale, data):
     self._lastState = self.player.get_state(1)[1]
     self.player.set_state(Gst.State.PAUSED)
     if self.timeout:
         GLib.source_remove(self.timeout)
         self.timeout = None
     return False
Пример #22
0
 def new_handle(self, reset):
     if self.actualizador:
         GLib.source_remove(self.actualizador)
         self.actualizador = False
     if reset:
         # FIXME: El intervalo puedes alargarlo si tu maquina es lenta.
         self.actualizador = GLib.timeout_add(1000, self.__handle)
Пример #23
0
 def _remove_timeout(self):
     if self.timeout:
         GLib.source_remove(self.timeout)
         self.timeout = None
     if self._seconds_timeout:
         GLib.source_remove(self._seconds_timeout)
         self._seconds_timeout = None
Пример #24
0
    def cancel(self):
        self.clock.acquire()
        self.cancelled = True
        if self.idle_finish != 0:
            GLib.source_remove(self.idle_finish)

        self.clock.release()
Пример #25
0
 def _on_title_release_event(self, widget, event):
     """
         Show track information popover
         On long press/right click: show current track menu
         @param widget as Gtk.Widget
         @param event as Gdk.Event
     """
     if self._timeout_id is not None:
         GLib.source_remove(self._timeout_id)
         self._timeout_id = None
         if Lp().player.current_track.id == Type.EXTERNALS:
             expopover = ExternalsPopover()
             expopover.set_relative_to(widget)
             expopover.populate()
             expopover.show()
         elif Lp().player.current_track.id is not None:
             if event.button == 1:
                 if Lp().player.current_track.id == Type.RADIOS:
                     if self._pop_tunein is None:
                         self._pop_tunein = TuneinPopover()
                         self._pop_tunein.populate()
                         self._pop_tunein.set_relative_to(widget)
                     self._pop_tunein.show()
                 else:
                     if self._pop_info is None:
                         self._pop_info = InfoPopover()
                         self._pop_info.set_relative_to(widget)
                     self._pop_info.show()
             else:
                 self._show_track_menu()
     return True
Пример #26
0
def on_entry_changed(widget, data):

    def _work():
        new_text = widget.get_text()
        (view, enquirer) = data

        with ExecutionTime("total time"):
            with ExecutionTime("enquire.set_query()"):
                enquirer.set_query(get_query_from_search_entry(new_text),
                    limit=100 * 1000,
                    nonapps_visible=NonAppVisibility.ALWAYS_VISIBLE)

            store = view.tree_view.get_model()
            if store is None:
                return

            with ExecutionTime("store.clear()"):
                store.clear()

            with ExecutionTime("store.set_from_matches()"):
                store.set_from_matches(enquirer.matches)

            with ExecutionTime("model settle (size=%s)" % len(store)):
                do_events()

    if widget.stamp:
        GLib.source_remove(widget.stamp)
    widget.stamp = GLib.timeout_add(250, _work)
Пример #27
0
	def unread(self): # {{{
		if self.event:
			GLib.source_remove(self.event)
			self.event = None
		ret = self._linebuffer
		self._linebuffer = b''
		return ret
Пример #28
0
    def geoname_cb(self, session, message, user_data):
        import syslog
        import json
        from gi.repository import GLib, Soup

        text, model = user_data

        if self.geoname_timeout_id is not None:
            GLib.source_remove(self.geoname_timeout_id)
            self.geoname_timeout_id = None
        self.geoname_add_tzdb(text, model)

        if message.status_code == Soup.KnownStatusCode.CANCELLED:
            # Silently ignore cancellation.
            pass
        elif message.status_code != Soup.KnownStatusCode.OK:
            # Log but otherwise ignore failures.
            syslog.syslog(
                'Geoname lookup for "%s" failed: %d %s' %
                (text, message.status_code, message.reason_phrase))
        else:
            try:
                for result in json.loads(message.response_body.data):
                    model.append([
                        result['name'], result['admin1'], result['country'],
                        result['latitude'], result['longitude']])

                # Only cache positive results.
                self.geoname_cache[text] = model

            except ValueError:
                syslog.syslog(
                    'Server return does not appear to be valid JSON.')

        self.city_entry.get_completion().set_model(model)
Пример #29
0
    def changed(self, entry):
        from gi.repository import Gtk, GObject, GLib, Soup

        text = misc.utf8(self.city_entry.get_text())
        if not text:
            return
        # TODO if the completion widget has a selection, return?  How do we
        # determine this?
        if text in self.geoname_cache:
            model = self.geoname_cache[text]
            self.city_entry.get_completion().set_model(model)
        else:
            model = Gtk.ListStore(GObject.TYPE_STRING, GObject.TYPE_STRING,
                                  GObject.TYPE_STRING, GObject.TYPE_STRING,
                                  GObject.TYPE_STRING)

            if self.geoname_session is None:
                self.geoname_session = Soup.SessionAsync()
            url = _geoname_url % (quote(text), misc.get_release().version)
            message = Soup.Message.new('GET', url)
            message.request_headers.append('User-agent', 'Ubiquity/1.0')
            self.geoname_session.abort()
            if self.geoname_timeout_id is not None:
                GLib.source_remove(self.geoname_timeout_id)
            self.geoname_timeout_id = \
                GLib.timeout_add_seconds(2, self.geoname_timeout,
                                         (text, model))
            self.geoname_session.queue_message(message, self.geoname_cb,
                                               (text, model))
Пример #30
0
    def stop(self):
        if self.timeout:
            GLib.source_remove(self.timeout)
            self.timeout = None

        self.player.set_state(Gst.State.NULL)
        self.emit('playing-changed')
Пример #31
0
 def __source_remove(self):
     if self.__id is not None:
         GLib.source_remove(self.__id)
         self.__id = None
Пример #32
0
 def destroy(self):
     #Gtk.DrawingArea.destroy(self)
     self.close_event()
     if self._idle_draw_id != 0:
         GLib.source_remove(self._idle_draw_id)
Пример #33
0
 def _timer_stop(self):
     if self._timer is not None:
         GLib.source_remove(self._timer)
         self._timer = None
Пример #34
0
 def __scroll(self, widget, event, player):
     self.__lock = True
     if self.__sig is not None:
         GLib.source_remove(self.__sig)
     self.__sig = GLib.timeout_add(100, self.__scroll_timeout, player)
Пример #35
0
 def __entry_changed_cb(self, widget, data=None):
     if self._timeout_sid:
         GLib.source_remove(self._timeout_sid)
     self._timeout_sid = GLib.timeout_add(APPLY_TIMEOUT, self.__timeout_cb)
Пример #36
0
 def clear_timer(self):
     """Remove function from GLib loop and clear reference"""
     if self.timeout_id is not None:
         GLib.source_remove(self.timeout_id)
     self.timeout_id = None
    def update_jobs_list(self):
        def get_notifications(self):
            c = self.authconn
            try:
                notifications = c.getNotifications([self.sub_id],
                                                   [self.sub_seq + 1])
            except AttributeError:
                notifications = c.getNotifications([self.sub_id])

            return notifications

        # Enter the GDK lock.  We need to do this because we were
        # called from a timeout.
        Gdk.threads_enter()

        parent = self.troubleshooter.get_window()
        self.op = TimedOperation(get_notifications, (self, ), parent=parent)
        try:
            notifications = self.op.run()
        except (OperationCanceled, cups.IPPError):
            Gdk.threads_leave()
            return True

        answers = self.troubleshooter.answers
        model = self.treeview.get_model()
        queue = answers['cups_queue']
        test_jobs = self.persistent_answers.get('test_page_job_id', [])
        for event in notifications['events']:
            seq = event['notify-sequence-number']
            try:
                if seq <= self.sub_seq:
                    # Work around a bug in pycups < 1.9.34
                    continue
            except AttributeError:
                pass
            self.sub_seq = seq
            job = event['notify-job-id']

            nse = event['notify-subscribed-event']
            if nse == 'job-created':
                if (job in test_jobs or event['printer-name'] == queue):
                    iter = model.append(None)
                    self.job_to_iter[job] = iter
                    model.set_value(iter, 0, True)
                    model.set_value(iter, 1, job)
                else:
                    continue
            elif not self.job_to_iter.has_key(job):
                continue

            if (job in test_jobs and nse in ["job-stopped", "job-completed"]):
                comp = self.persistent_answers.get('test_page_completions', [])
                comp.append((job, event['notify-text']))
                self.persistent_answers['test_page_completions'] = comp

            self.update_job(job, event)

        # Update again when we're told to. (But we might update sooner if
        # there is a D-Bus signal.)
        GLib.source_remove(self.timer)
        self.timer = GLib.timeout_add_seconds(
            notifications['notify-get-interval'], self.update_jobs_list)
        debugprint("Update again in %ds" %
                   notifications['notify-get-interval'])
        Gdk.threads_leave()
        return False
Пример #38
0
 def _remove_timeout_source(self):
     if self._timeout_id is not None:
         GLib.source_remove(self._timeout_id)
         self._timeout_id = None
Пример #39
0
 def on_tv_changed(column, old, new):
     if new is None and self._timeout is not None:
         GLib.source_remove(self._timeout)
         self._timeout = None
Пример #40
0
 def cancel_timer(self):
     if self._timer:
         GLib.source_remove(self._timer)
         self._timer = None
Пример #41
0
 def _response(self, *args):
     GLib.source_remove(self._timeout_sid)
     Alert._response(self, *args)
Пример #42
0
 def deactivate(self):
     if self.graph_update is not None:
         GLib.source_remove(self.graph_update)
         self.graph_update = None
Пример #43
0
 def _set_repeat(self, delay=None, interval=None):
     if delay is not None and self.__repeat[0] is None:
         self.__tick_id = GLib.timeout_add(10, self._tick_cb)
     elif delay is None and self.__repeat[0] is not None:
         GLib.source_remove(self.__tick_id)
     self.__repeat = (delay, interval)
Пример #44
0
 def search_entry_timeout(self, widget):
     if self.timeout:
         GLib.source_remove(self.timeout)
     self.timeout = GLib.timeout_add(500, self.search_entry_changed, widget)
Пример #45
0
 def _releaseServer(self):
     assert self._entryGroup is None
     if self._retryCreateServerTimer is not None:
         GLib.source_remove(self._retryCreateServerTimer)
         self._retryCreateServerTimer = None
     self._server = None
Пример #46
0
 def _cancel_delayed_start(self):
     if self._delay_id is not None:
         GLib.source_remove(self._delay_id)
         self._delay_id = None
Пример #47
0
 def on_search_games_fire(self, value):
     GLib.source_remove(self.search_timer_id)
     self.search_timer_id = None
     self.search_games(value)
     return False
Пример #48
0
    def reset(self):
        if self._reset_id is not None:
            GLib.source_remove(self._reset_id)
            self._reset_id = None

        self.emit("reset")
    def main(self, args):
        # start a timeout timer in validation process to close application if
        # timeout occurs
        if args.validation:
            self.valid_timeout_id = GLib.timeout_add(35000,
                                                     self.valid_timeout_callback)

        if self.enable_camera_preview:
            #variable to compute preview framerate
            self.loop_count = 1
            self.loop_time = 0
            self.loop_start = 0
            self.total_time = 0
            self.preview_fps = 0

            self.camera_not_started = True
            # initialize VideoFrameCapture object
            cap = VideoFrameCapture(int(args.video_device), float(args.frame_width), float(args.frame_height), float(args.framerate))
            shape = cap.get_frame_size()
            self.camera_not_started = False

            # define shared variables
            self.shared_array_base = Array(ctypes.c_uint8, shape[0] * shape[1] * shape[2])
            self.frame = np.ctypeslib.as_array(self.shared_array_base.get_obj())
            self.frame = self.frame.reshape(shape[0], shape[1], shape[2])
            self.grabbing_fps = Value('f', 0.0)

            # start processes which run in parallel
            self.preview_synchro_event = Event()
            self.preview_process = Process(name='camera_streaming', target=camera_streaming,
                                           args=(cap,
                                                 self.shared_array_base,
                                                 self.preview_synchro_event,
                                                 self.grabbing_fps))
            # launch capture process
            self.preview_process.daemon = True
            self.preview_process.start()
        else:
            # still picture
            # Check if image directory is empty
            rfile = self.getRandomFile(args.image)
            if rfile == '':
                print("ERROR: Image directory " + rfile + "is empty")
                self.destroy()
                os._exit(1)
            else:
                # reset the self.files variable
                self.files = []

        # initialize NeuralNetwork object
        self.nn = NeuralNetwork(args.model_file, args.label_file, float(args.input_mean), float(args.input_std))
        shape = self.nn.get_img_size()

        if self.nn._floating_model:
            Gtk.HeaderBar.set_subtitle(self.headerbar, "float model " + os.path.basename(args.model_file))
        else:
            Gtk.HeaderBar.set_subtitle(self.headerbar, "quant model " + os.path.basename(args.model_file))

        # define shared variables
        self.nn_processing_start = Value(ctypes.c_bool, False)
        self.nn_processing_finished = Value(ctypes.c_bool, False)
        self.nn_img_shared_array = Array(ctypes.c_uint8, shape[0] * shape[1] * shape[2])
        self.nn_img = np.ctypeslib.as_array(self.nn_img_shared_array.get_obj())
        self.nn_img = self.nn_img.reshape(shape[0], shape[1], shape[2])
        self.nn_inference_time = Value('f', 0)
        self.nn_inference_fps = Value('f', 0.0)
        self.nn_result_accuracy = Value('f', 0.0)
        self.nn_result_label = Value('i', 0)

        # start processes which run in parallel
        self.nn_synchro_event = Event()
        self.nn_process = Process(name='nn_processing', target=nn_processing,
                                  args=(self.nn,
                                        self.nn_img_shared_array,
                                        self.nn_processing_start,
                                        self.nn_processing_finished,
                                        self.nn_inference_time,
                                        self.nn_result_accuracy,
                                        self.nn_result_label,
                                        self.nn_synchro_event,
                                        self.nn_inference_fps))
        # launch nn process
        self.nn_process.daemon = True
        self.nn_process.start()

        # wait the nn process to start
        self.nn_synchro_event.wait()

        if self.enable_camera_preview:
            self.preview_synchro_event.wait()

            # define the crop parameters that will be used to crop the input preview frame to
            # the requested NN input image size
            self.y1 = int(0)
            self.y2 = int(self.frame.shape[0])
            self.x1 = int((self.frame.shape[1] - self.frame.shape[0]) / 2)
            self.x2 = int(self.x1 + self.frame.shape[0])

            # set the following variable to True to trig the first NN inference
            self.nn_processing_finished.value = True

            # hidde the progress bar
            GLib.source_remove(self.timeout_id)
            self.progressbar.hide()

            GLib.idle_add(self.camera_preview)
        else:
            # hidde the progress bar
            GLib.source_remove(self.timeout_id)
            self.progressbar.hide()

            if not args.validation:
                self.button = Gtk.Button.new_with_label("Next inference")
                self.vbox.pack_start(self.button, False, False, 15)
                self.button.connect("clicked", self.still_picture)
                self.button.show_all()
            else:
                GLib.idle_add(self.validation_picture)
Пример #50
0
 def _stop_hover_expand_timer(self):
     if self._hover_expand_timer_id is None:
         return
     GLib.source_remove(self._hover_expand_timer_id)
     self._hover_expand_timer_id = None
Пример #51
0
 def alive (self):
     self._lock.acquire()
     if self._holds == 0:
         GLib.source_remove (self._timer)
         self._add_timeout ()
     self._lock.release()
Пример #52
0
 def cancel_countdown(self):
     self.indicator.blink_set_state(BLINK_STOP)
     self.canceled = True
     GLib.source_remove(self.timeoutId)
     self.window.destroy()
Пример #53
0
    def disable_send(self):
        if self.send_id is None:
            return

        GLib.source_remove(self.send_id)
        self.send_id = None
 def __del__(self):
     if self.strength_id > 0:
         GLib.source_remove(self.strength_id)
     self.strength_id = 0
Пример #55
0
 def disable_timeout(self):
     """Deactivate timeout mechanism."""
     if self.timeout_id is None:
         return
     GLib.source_remove(self.timeout_id)
     self.timeout_id = None
Пример #56
0
 def stop(self):
     if self.source_id > 0:
         GLib.source_remove(self.source_id)
         self.source_id = 0
 def handle_dbus_signal(self, *args):
     debugprint("D-Bus signal caught: updating jobs list soon")
     GLib.source_remove(self.timer)
     self.timer = GLib.timeout_add(200, self.update_jobs_list)
Пример #58
0
 def disable_recv(self):
     if self.recv_id is None:
         return
     GLib.source_remove(self.recv_id)
     self.recv_id = None
Пример #59
0
    def on_configure_event(self, window, event: Gdk.EventConfigure):
        if self._configure_timeout_id:
            GLib.source_remove(self._configure_timeout_id)

        self.current_size = window.get_size()
        self.current_position = window.get_position()
Пример #60
0
 def cancel_timeouts(self):
     from gi.repository import GLib
     if self.keyboard_layout_timeout_id:
         GLib.source_remove(self.keyboard_layout_timeout_id)
     if self.keyboard_variant_timeout_id:
         GLib.source_remove(self.keyboard_variant_timeout_id)