Beispiel #1
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
Beispiel #2
0
    def _busMessageCb(self, unused_bus, message):
        if message.type == Gst.MessageType.EOS:
            self.pause()
            self.emit('eos')
        elif message.type == Gst.MessageType.STATE_CHANGED:
            prev, new, pending = message.parse_state_changed()

            if message.src == self._pipeline:
                self.debug("Pipeline change state prev:%r, new:%r, pending:%r" % (prev, new, pending))

                emit_state_change = pending == Gst.State.VOID_PENDING
                if prev == Gst.State.READY and new == Gst.State.PAUSED:
                    # trigger duration-changed
                    try:
                        self.getDuration()
                    except PipelineError:
                        # no sinks??
                        pass
                elif prev == Gst.State.PAUSED and new == Gst.State.PLAYING:
                    self._listenToPosition(True)
                elif prev == Gst.State.PLAYING and new == Gst.State.PAUSED:
                    self._listenToPosition(False)

                if emit_state_change:
                    self.emit('state-change', new)

        elif message.type == Gst.MessageType.ERROR:
            error, detail = message.parse_error()
            self._handleErrorMessage(error, detail, message.src)
        elif message.type == Gst.MessageType.DURATION_CHANGED:
            self.debug("Duration might have changed, querying it")
            GLib.idle_add(self._queryDurationAsync)
        else:
            self.log("%s [%r]" % (message.type, message.src))
 def __init__(self):
     super().__init__({
         application_id: 'org.gnome.Music',
         flags: gio.ApplicationFlags.FLAGS_NONE,
         inactivity_timeout: 12000}
     )
     GLib.set_application_name("Music")
Beispiel #4
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)
Beispiel #5
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)
Beispiel #6
0
 def _get_tracks_files(self):
     """
         Return children uris for uri
         @return [str]
     """
     children = []
     dir_uris = [self._uri+'/tracks/']
     while dir_uris:
         uri = dir_uris.pop(0)
         album_name = uri.replace(self._uri+"/tracks/", "")
         album = GLib.uri_escape_string(album_name,
                                        "",
                                        False)
         d = Gio.File.new_for_uri(self._uri+"/tracks/"+album)
         infos = d.enumerate_children(
             'standard::name,standard::type',
             Gio.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,
             None)
         for info in infos:
             if info.get_file_type() == Gio.FileType.DIRECTORY:
                 dir_uris.append(uri+info.get_name())
             else:
                 track = GLib.uri_escape_string(info.get_name(),
                                                "",
                                                False)
                 children.append("%s/tracks/%s/%s" % (self._uri,
                                                      album,
                                                      track))
     return children
Beispiel #7
0
    def _sync(self, playlists, convert):
        """
            Sync playlists with device as this
            @param playlists as [str]
            @param convert as bool
        """
        try:
            self._in_thread = True
            self._convert = convert
            self._errors = False
            self._errors_count = 0
            self._copied_art_uris = []
            # For progress bar
            self._total = 1
            self._done = 0
            self._fraction = 0.0
            plnames = []

            # New tracks
            for playlist in playlists:
                plnames.append(Lp().playlists.get_name(playlist))
                self._fraction = self._done/self._total
                self._total += len(Lp().playlists.get_tracks(playlist))

            # Old tracks
            try:
                children = self._get_tracks_files()
                self._total += len(children)
            except:
                pass
            GLib.idle_add(self._update_progress)

            # Copy new tracks to device
            if self._syncing:
                self._copy_to_device(playlists)

            # Remove old tracks from device
            if self._syncing:
                self._remove_from_device(playlists)

            # Delete old playlists
            d = Gio.File.new_for_uri(self._uri)
            infos = d.enumerate_children(
                'standard::name',
                Gio.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,
                None)
            for info in infos:
                f = info.get_name()
                if f.endswith(".m3u") and f[:-4] not in plnames:
                    uri = self._uri+'/'+f
                    d = Gio.File.new_for_uri(uri)
                    self._retry(d.delete, (None,))

        except Exception as e:
            print("DeviceManagerWidget::_sync(): %s" % e)
        self._fraction = 1.0
        self._syncing = False
        self._in_thread = False
        if self._errors:
            GLib.idle_add(self._on_errors)
Beispiel #8
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)
Beispiel #9
0
 def populate(self):
     """
         Populate view
     """
     if Lp.player.get_queue():
         self._clear_btn.set_sensitive(True)
     GLib.idle_add(self._add_items, list(Lp.player.get_queue()))
Beispiel #10
0
 def checkFiles( self ):
     for monitored in self.monitoredFiles:
         if monitored.hasChanged():
             if monitored.args:
                 GLib.idle_add( monitored.callback, monitored.args )
             else:
                 GLib.idle_add( monitored.callback )
Beispiel #11
0
def capture_glib_warnings(allow_warnings=False, allow_criticals=False):
    """Temporarily suppress glib warning output and record them.

    The test suite is run with G_DEBUG="fatal-warnings fatal-criticals"
    by default. Setting allow_warnings and allow_criticals will temporarily
    allow warnings or criticals without terminating the test run.
    """

    old_mask = GLib.log_set_always_fatal(GLib.LogLevelFlags(0))

    new_mask = old_mask
    if allow_warnings:
        new_mask &= ~GLib.LogLevelFlags.LEVEL_WARNING
    if allow_criticals:
        new_mask &= ~GLib.LogLevelFlags.LEVEL_CRITICAL

    GLib.log_set_always_fatal(GLib.LogLevelFlags(new_mask))

    GLibWarning = gi._gi._gobject.Warning
    try:
        with warnings.catch_warnings(record=True) as warn:
            warnings.filterwarnings('always', category=GLibWarning)
            yield warn
    finally:
        GLib.log_set_always_fatal(old_mask)
Beispiel #12
0
 def on_motor_position_change(self, motor: Optional[Motor], pos: Optional[float]):
     if motor is None or pos is None:
         logger.debug('Faked motor position changed signal caught by ShutterFrame.')
     else:
         logger.debug(
             'Motor position changed signal caught by ShutterFrame. Motor: {}. Position: {}'.format(motor.name, pos))
         try:
             logger.debug('Stored motor position is {}'.format(motor.where()))
         except KeyError:
             logger.debug('Stored motor position not yet available.')
     try:
         if motor is not None:
             beamstopstate = self.instrument.get_beamstop_state(**{motor.name: pos})
         else:
             beamstopstate = self.instrument.get_beamstop_state()
         logger.debug('beamstopstate: {}'.format(beamstopstate))
     except KeyError:
         # can happen at program initialization, when the motor position has not yet been read.
         logger.debug('No beamstop state yet.')
         GLib.timeout_add(1000, lambda m=motor, p=pos: self.on_motor_position_change(m, p))
         return False
     if beamstopstate == 'in':
         self.builder.get_object('beamstopstate_image').set_from_icon_name('beamstop-in', Gtk.IconSize.BUTTON)
         self.builder.get_object('beamstop_in_button').set_sensitive(False)
         self.builder.get_object('beamstop_out_button').set_sensitive(True)
     elif beamstopstate == 'out':
         self.builder.get_object('beamstopstate_image').set_from_icon_name('beamstop-out', Gtk.IconSize.BUTTON)
         self.builder.get_object('beamstop_in_button').set_sensitive(True)
         self.builder.get_object('beamstop_out_button').set_sensitive(False)
     else:
         self.builder.get_object('beamstopstate_image').set_from_icon_name('beamstop-inconsistent',
                                                                           Gtk.IconSize.BUTTON)
         self.builder.get_object('beamstop_in_button').set_sensitive(True)
         self.builder.get_object('beamstop_out_button').set_sensitive(True)
     return False
Beispiel #13
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)
Beispiel #14
0
 def __init__(self):
     Gtk.Window.__init__(self)
     self.image = None
     GLib.timeout_add(50, self.save_image)
     self.connect("delete-event", self.on_quit)
     # Status
     self.status = Gst.State.NULL
     # Video Area
     self.video_area = Gtk.DrawingArea()
     # Disable Double Buffered
     self.video_area.set_double_buffered(False)
     # playbin
     self.player = Gst.parse_launch("tcpclientsrc host=" + sys.argv[1] +" port=5000 ! gdpdepay ! rtph264depay ! avdec_h264 ! videoconvert ! xvimagesink name=xv")
     bus = self.player.get_bus()
     bus.add_signal_watch()
     bus.enable_sync_message_emission()
     bus.connect("message", self.on_message)
     bus.connect("sync-message::element", self.on_sync_message)
     # DnD
     dnd_list = Gtk.TargetEntry.new("text/uri-list", 0, 0)
     # pack
     vbox = Gtk.Box.new(Gtk.Orientation.VERTICAL, 0) 
     vbox.pack_start(self.video_area, True, True, 0)
     self.add(vbox)
     self.resize(640, 480)
     self.show_all()
     self.player.set_state(Gst.State.PLAYING)
Beispiel #15
0
	def close(self, *a):
		"""
		Closes revealer (with animation), removes it from parent and
		calls destroy()
		"""
		self.set_reveal_child(False)
		GLib.timeout_add(self.get_transition_duration() + 50, self._cb_destroy)
    def enabled(self):
        if not self.running:
            wm = WatchManager()
            self.event_handler = LibraryEvent(app.library)

            # Choose event types to watch for
            # FIXME: watch for IN_CREATE or for some reason folder copies
            # are missed,  --nickb
            FLAGS = ['IN_DELETE', 'IN_CLOSE_WRITE',# 'IN_MODIFY',
                     'IN_MOVED_FROM', 'IN_MOVED_TO', 'IN_CREATE']
            mask = reduce(lambda x, s: x | EventsCodes.ALL_FLAGS[s], FLAGS, 0)

            if self.USE_THREADS:
                print_d("Using threaded notifier")
                self.notifier = ThreadedNotifier(wm, self.event_handler)
                # Daemonize to ensure thread dies on exit
                self.notifier.daemon = True
                self.notifier.start()
            else:
                self.notifier = Notifier(wm, self.event_handler, timeout=100)
                GLib.timeout_add(1000, self.unthreaded_callback)

            for path in get_scan_dirs():
                print_d('Watching directory %s for %s' % (path, FLAGS))
                # See https://github.com/seb-m/pyinotify/wiki/
                # Frequently-Asked-Questions
                wm.add_watch(path, mask, rec=True, auto_add=True)

            self.running = True
Beispiel #17
0
    def run_dbus_service(self, timeout=None, send_usr1=False):
        '''Run D-BUS server.

        If no timeout is given, the server will run forever, otherwise it will
        return after the specified number of seconds.

        If send_usr1 is True, this will send a SIGUSR1 to the parent process
        once the server is ready to take requests.
        '''
        dbus.service.Object.__init__(self, self.bus, '/DeviceDriver')
        self.main_loop = GLib.MainLoop()
        self._timeout = False
        if timeout:
            def _t():
                self.main_loop.quit()
                return True
            GLib.timeout_add(timeout * 1000, _t)

        # send parent process a signal that we are ready now
        if send_usr1:
            os.kill(os.getppid(), signal.SIGUSR1)

        # run until we time out
        while not self._timeout:
            if timeout:
                self._timeout = True
            self.main_loop.run()
Beispiel #18
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 _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)
Beispiel #20
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
Beispiel #21
0
    def _expand_node_by_name(self, search_num, parent, name, rest=None):
        """
            Recursive function to expand all nodes in a hierarchical list of
            names.

            @param search_num: the current search number
            @param parent: the parent node
            @param name: the name of the node to expand
            @param rest: the list of the nodes to expand after this one
        """
        iter = self.model.iter_children(parent)

        while iter:
            if search_num != self._search_num: return
            value = self.model.get_value(iter, 1)
            if not value:
                value = self.model.get_value(iter, 2)
            if value: value = unicode(value, 'utf-8')

            if value == name:
                self.tree.expand_row(self.model.get_path(iter), False)
                parent = iter
                break

            iter = self.model.iter_next(iter)

        if rest:
            item = rest.pop(0)
            GLib.idle_add(self._expand_node_by_name, search_num,
                parent, item, rest)
Beispiel #22
0
 def _configure_cb(self, widget, event):
     """Internal: Update size and prefs when window is adjusted"""
     # Constrain window to fit on its current monitor, if possible.
     screen = event.get_screen()
     mon = screen.get_monitor_at_point(event.x, event.y)
     mon_geom = screen.get_monitor_geometry(mon)
     # Constrain width and height
     w = clamp(int(event.width), self.MIN_WIDTH, self.MAX_WIDTH)
     h = clamp(int(event.height), self.MIN_HEIGHT, self.MAX_HEIGHT)
     # Constrain position
     x, y = event.x, event.y
     if y+h > mon_geom.y + mon_geom.height:
         y = mon_geom.y + mon_geom.height - h
     if x+w > mon_geom.x + mon_geom.width:
         x = mon_geom.x + mon_geom.width - w
     if x < mon_geom.x:
         x = mon_geom.x
     if y < mon_geom.y:
         y = mon_geom.y
     event_size = (event.x, event.y, event.width, event.height)
     ex, ey, ew, eh = [int(c) for c in event_size]
     x, y, w, h = [int(c) for c in (x, y, w, h)]
     if not self._corrected_pos:
         if (x, y) != (ex, ey):
             GLib.idle_add(self.move, x, y)
         if (w, h) != (ew, eh):
             GLib.idle_add(self.resize, w, h)
         self._corrected_pos = True
     # Record size
     self._size = (x, y, w, h)
     self.app.preferences[self._prefs_size_key] = (w, h)
Beispiel #23
0
    def _switch_to_player_view(self):
        self.settings.set_boolean('did-initial-state', True)
        self._on_notify_model_id = self._stack.connect('notify::visible-child', self._on_notify_mode)
        self.connect('destroy', self._notify_mode_disconnect)
        self._key_press_event_id = self.connect('key_press_event', self._on_key_press)

        self.views.append(AlbumsView(self, self.player))
        self.views.append(ArtistsView(self, self.player))
        self.views.append(SongsView(self, self.player))
        self.views.append(PlaylistView(self, self.player))
        self.views.append(SearchView(self, self.player))
        self.views.append(EmptySearchView(self, self.player))

        for i in self.views:
            if i.title:
                self._stack.add_titled(i, i.name, i.title)
            else:
                self._stack.add_named(i, i.name)

        self.toolbar.set_stack(self._stack)
        self.toolbar.searchbar.show()
        self.toolbar.dropdown.show()

        for i in self.views:
            GLib.idle_add(i.populate)
Beispiel #24
0
	def _syncthing_cb_config_error(self, exception, command):
		self.cancel_all()
		if isinstance(exception, GLib.GError):
			if exception.code in (0, 39, 34, 45):	# Connection Refused / Cannot connect to destination
				# It usualy means that daemon is not yet fully started or not running at all.
				epoch = self._epoch
				self.emit("connection-error", Daemon.REFUSED, exception.message, exception)
				if epoch == self._epoch:
					self.timer("config", self._refresh_interval, self._rest_request, "system/config", self._syncthing_cb_config, self._syncthing_cb_config_error)
				return
		elif isinstance(exception, HTTPAuthException):
			self.emit("connection-error", Daemon.NOT_AUTHORIZED, exception.message, exception)
			return
		elif isinstance(exception, HTTPCode):
			# HTTP 404 may acually mean old daemon version
			version = get_header(exception.headers, "X-Syncthing-Version")
			if version != None and not compare_version(version, MIN_VERSION):
				self._epoch += 1
				msg = "daemon is too old"
				self.emit("connection-error", Daemon.OLD_VERSION, msg, Exception(msg))
			else:
				self.emit("connection-error", Daemon.UNKNOWN, exception.message, exception)
			return
		elif isinstance(exception, TLSUnsupportedException):
			self.emit("connection-error", Daemon.TLS_UNSUPPORTED, exception.message, exception)
			return
		elif isinstance(exception, ConnectionRestarted):
			# Happens on Windows. Just try again.
			GLib.idle_add(self._request_config)
			return
		elif isinstance(exception, TLSUnsupportedException):
			self.emit("connection-error", Daemon.TLS_UNSUPPORTED, exception.message, exception)
			return
		self.emit("connection-error", Daemon.UNKNOWN, exception.message, exception)
Beispiel #25
0
	def reconnect(self):
		"""
		Cancel all pending requests, throw away all data and (re)connect.
		Should be called from glib loop
		"""
		self.close()
		GLib.idle_add(self._request_config)
Beispiel #26
0
def tree_append_items(tree, items):
    '''A faster way to append many items to GtkTreeModel at a time.

    When appending many items to a model , app will lose response, which
    is really annoying.
    From:http://faq.pygtk.org/index.py?req=show&file=faq13.043.htp
    @tree a GtkTreeView
    @items a list of items
    '''
    def append_generator(step=100):
        n = 0
        tree.freeze_child_notify()
        for item in items:
            model.append(item)
            n += 1
            if (n % step) == 0:
                tree.thaw_child_notify()
                yield True
                tree.freeze_child_notify()
        # stop idle_add()
        tree.thaw_child_notify()
        yield False

    model = tree.get_model()
    loader = append_generator()
    GLib.idle_add(loader.__next__)
Beispiel #27
0
def main():
    # These imports were moved here because the keysign module
    # can be imported without wanting to run it, e.g. setup.py
    # imports the __version__
    import logging, sys, signal
    
    import gi
    gi.require_version('Gtk', '3.0')
    from gi.repository import GLib, Gtk
    
    from .MainWindow import MainWindow

    logging.basicConfig(stream=sys.stderr,
        level=logging.DEBUG,
        format='%(name)s (%(levelname)s): %(message)s')

    app = MainWindow()

    try:
        GLib.unix_signal_add_full(GLib.PRIORITY_HIGH, signal.SIGINT, lambda *args : app.quit(), None)
    except AttributeError:
        pass

    exit_status = app.run(None)

    return exit_status
Beispiel #28
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
Beispiel #29
0
 def do_show(self):
     """
         Init signals, set color and go party mode if nothing is playing
     """
     self._signal1_id = Lp().player.connect('current-changed',
                                            self.on_current_changed)
     self._signal2_id = Lp().player.connect('status-changed',
                                            self.on_status_changed)
     if Lp().player.current_track.id is None:
         Lp().player.set_party(True)
     else:
         self.on_status_changed(Lp().player)
         self.on_current_changed(Lp().player)
     if self._timeout1 is None:
         self._timeout1 = GLib.timeout_add(1000, self._update_position)
     Gtk.Window.do_show(self)
     now = datetime.now()
     self._datetime.set_label(now.strftime('%a %d %b, %X')[:-3])
     if self._timeout2 is None:
         second = datetime.now().second
         if 60 - second > 0:
             GLib.timeout_add((60-second)*1000, self._update_datetime)
         else:
             self._timeout2 = GLib.timeout_add(60000, self._update_datetime)
     self._update_position()
     self.fullscreen()
     self._next_popover.set_relative_to(self._album_label)
     if Lp().player.next_track.id != Type.RADIOS:
         self._next_popover.show()
Beispiel #30
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)
Beispiel #31
0
 def close(self):
     for source, callback, args, handle in self._sources.values():
         self._close_process_handle(handle)
         GLib.source_remove(source)
     self._sources = {}
     self._handles = {}
Beispiel #32
0
import sys
from threading import Thread

from gi.repository import GLib

from pydbus import SessionBus

done = 0
loop = GLib.MainLoop()


class TestObject(object):
    '''
<node>
	<interface name='net.lew21.pydbus.tests.Iface1'>
		<method name='Method1'>
			<arg type='s' name='response' direction='out'/>
		</method>
	</interface>
	<interface name='net.lew21.pydbus.tests.Iface2'>
		<method name='Method2'>
			<arg type='s' name='response' direction='out'/>
		</method>
	</interface>
</node>
	'''
    def Method1(self):
        global done
        done += 1
        if done == 2:
            loop.quit()
Beispiel #33
0
    def __init__(self):
        """
            Init dialog
        """
        self.__choosers = []
        self.__cover_tid = None
        self.__mix_tid = None
        self.__popover = None

        cs_api_key = Lp().settings.get_value('cs-api-key').get_string()
        default_cs_api_key = Lp().settings.get_default_value(
                                                     'cs-api-key').get_string()
        if (not cs_api_key or
            cs_api_key == default_cs_api_key) and\
                get_network_available() and\
                Lp().notify is not None:
            Lp().notify.send(
                         _("Google Web Services need a custom API key"),
                         _("Lollypop needs this to search artwork and music."))

        builder = Gtk.Builder()
        builder.add_from_resource('/org/gnome/Lollypop/SettingsDialog.ui')
        if Lp().lastfm is None or Lp().lastfm.is_goa:
            builder.get_object('lastfm_grid').hide()
        if Lp().scanner.is_locked():
            builder.get_object('button').set_sensitive(False)
        builder.get_object('button').connect('clicked',
                                             self.__on_reset_clicked,
                                             builder.get_object('progress'))
        artists = Lp().artists.count()
        albums = Lp().albums.count()
        tracks = Lp().tracks.count()
        builder.get_object('artists').set_text(
                        ngettext("%d artist", "%d artists", artists) % artists)
        builder.get_object('albums').set_text(
                            ngettext("%d album", "%d albums", albums) % albums)
        builder.get_object('tracks').set_text(
                            ngettext("%d track", "%d tracks", tracks) % tracks)

        self.__popover_content = builder.get_object('popover')
        duration = builder.get_object('duration')
        duration.set_range(1, 20)
        duration.set_value(Lp().settings.get_value('mix-duration').get_int32())

        self.__settings_dialog = builder.get_object('settings_dialog')
        self.__settings_dialog.set_transient_for(Lp().window)

        if Lp().settings.get_value('disable-csd'):
            self.__settings_dialog.set_title(_("Preferences"))
        else:
            headerbar = builder.get_object('header_bar')
            headerbar.set_title(_("Preferences"))
            self.__settings_dialog.set_titlebar(headerbar)

        switch_scan = builder.get_object('switch_scan')
        switch_scan.set_state(Lp().settings.get_value('auto-update'))

        switch_view = builder.get_object('switch_dark')
        switch_view.set_state(Lp().settings.get_value('dark-ui'))

        switch_background = builder.get_object('switch_background')
        switch_background.set_state(Lp().settings.get_value('background-mode'))

        switch_state = builder.get_object('switch_state')
        switch_state.set_state(Lp().settings.get_value('save-state'))

        switch_mix = builder.get_object('switch_mix')
        switch_mix.set_state(Lp().settings.get_value('mix'))
        helper = TouchHelper(switch_mix, None, None)
        helper.set_long_func(self.__mix_long_func, switch_mix)
        helper.set_short_func(self.__mix_short_func, switch_mix)

        switch_mix_party = builder.get_object('switch_mix_party')
        switch_mix_party.set_state(Lp().settings.get_value('party-mix'))

        switch_librefm = builder.get_object('switch_librefm')
        switch_librefm.set_state(Lp().settings.get_value('use-librefm'))

        switch_artwork_tags = builder.get_object('switch_artwork_tags')
        # Check portal for kid3-cli
        can_set_cover = False
        try:
            bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
            proxy = Gio.DBusProxy.new_sync(bus, Gio.DBusProxyFlags.NONE, None,
                                           'org.gnome.Lollypop.Portal',
                                           '/org/gnome/LollypopPortal',
                                           'org.gnome.Lollypop.Portal', None)
            can_set_cover = proxy.call_sync('CanSetCover', None,
                                            Gio.DBusCallFlags.NO_AUTO_START,
                                            500, None)[0]
        except Exception as e:
            print("You are missing lollypop-portal: "
                  "https://github.com/gnumdk/lollypop-portal", e)
        if not can_set_cover:
            grid = builder.get_object('grid_behaviour')
            h = grid.child_get_property(switch_artwork_tags, 'height')
            w = grid.child_get_property(switch_artwork_tags, 'width')
            l = grid.child_get_property(switch_artwork_tags, 'left-attach')
            t = grid.child_get_property(switch_artwork_tags, 'top-attach')
            switch_artwork_tags.destroy()
            label = Gtk.Label.new(_("You need to install kid3-cli"))
            label.get_style_context().add_class('dim-label')
            label.set_property('halign', Gtk.Align.END)
            label.show()
            grid.attach(label, l, t, w, h)
        else:
            switch_artwork_tags.set_state(
                                      Lp().settings.get_value('save-to-tags'))

        if GLib.find_program_in_path("youtube-dl") is None:
            builder.get_object('charts_grid').hide()
        else:
            switch_charts = builder.get_object('switch_charts')
            switch_charts.set_state(Lp().settings.get_value('show-charts'))

        switch_genres = builder.get_object('switch_genres')
        switch_genres.set_state(Lp().settings.get_value('show-genres'))

        switch_compilations = builder.get_object('switch_compilations')
        switch_compilations.set_state(
            Lp().settings.get_value('show-compilations'))

        switch_artwork = builder.get_object('switch_artwork')
        switch_artwork.set_state(Lp().settings.get_value('artist-artwork'))

        combo_orderby = builder.get_object('combo_orderby')
        combo_orderby.set_active(Lp().settings.get_enum(('orderby')))

        combo_preview = builder.get_object('combo_preview')

        scale_coversize = builder.get_object('scale_coversize')
        scale_coversize.set_range(150, 300)
        scale_coversize.set_value(
                            Lp().settings.get_value('cover-size').get_int32())
        self.__settings_dialog.connect('destroy', self.__edit_settings_close)

        builder.connect_signals(self)

        main_chooser_box = builder.get_object('main_chooser_box')
        self.__chooser_box = builder.get_object('chooser_box')

        self.__set_outputs(combo_preview)

        #
        # Music tab
        #
        dirs = []
        for directory in Lp().settings.get_value('music-uris'):
            dirs.append(directory)

        # Main chooser
        self.__main_chooser = ChooserWidget()
        image = Gtk.Image.new_from_icon_name("list-add-symbolic",
                                             Gtk.IconSize.MENU)
        self.__main_chooser.set_icon(image)
        self.__main_chooser.set_action(self.__add_chooser)
        main_chooser_box.pack_start(self.__main_chooser, False, True, 0)
        if len(dirs) > 0:
            uri = dirs.pop(0)
        else:
            filename = GLib.get_user_special_dir(
                                            GLib.UserDirectory.DIRECTORY_MUSIC)
            if filename:
                uri = GLib.filename_to_uri(filename)
            else:
                uri = ""

        self.__main_chooser.set_dir(uri)

        # Others choosers
        for directory in dirs:
            self.__add_chooser(directory)

        #
        # Google tab
        #
        builder.get_object('cs-entry').set_text(
                            Lp().settings.get_value('cs-api-key').get_string())
        #
        # Last.fm tab
        #
        if Lp().lastfm is not None and Secret is not None:
            self.__test_img = builder.get_object('test_img')
            self.__login = builder.get_object('login')
            self.__password = builder.get_object('password')
            schema = Secret.Schema.new("org.gnome.Lollypop",
                                       Secret.SchemaFlags.NONE,
                                       SecretSchema)
            Secret.password_lookup(schema, SecretAttributes, None,
                                   self.__on_password_lookup)
            builder.get_object('lastfm_grid').set_sensitive(True)
            builder.get_object('lastfm_error').hide()
            self.__login.set_text(
                Lp().settings.get_value('lastfm-login').get_string())
Beispiel #34
0
#!/usr/bin/env python3

from gi.repository import Playerctl, GLib


def on_track_change(player, e):
    if 'xesam:artist' in e.keys() and 'xesam:title' in e.keys():
        print('{artist} - {title}'.format(artist=e['xesam:artist'][0],
                                          title=e['xesam:title']))


# Get player instance
player = Playerctl.Player(player_name='spotify')

# Initial track information
artist = player.get_artist()
title = player.get_title()
print('%s - %s' % (artist, title))

# Listener for track changes
player.on('metadata', on_track_change)

GLib.MainLoop().run()
Beispiel #35
0
 def rename(self, name):
     """
         Rename widget
         @param name as str
     """
     self.__label.set_markup("<b>" + GLib.markup_escape_text(name) + "</b>")
Beispiel #36
0
    def run(self, procedure, run_mode, image, drawable, args, run_data):
        if run_mode == Gimp.RunMode.INTERACTIVE:
            gi.require_version('Gtk', '3.0')
            from gi.repository import Gtk
            gi.require_version('Gdk', '3.0')
            from gi.repository import Gdk

            GimpUi.ui_init("palette-offset.py")

            dialog = GimpUi.Dialog(use_header_bar=True,
                                   title=_("Exercise a goat (Python 3)"),
                                   role="goat-exercise-Python3")

            dialog.add_button("_Cancel", Gtk.ResponseType.CANCEL)
            dialog.add_button("_Source", Gtk.ResponseType.APPLY)
            dialog.add_button("_OK", Gtk.ResponseType.OK)

            geometry = Gdk.Geometry()
            geometry.min_aspect = 0.5
            geometry.max_aspect = 1.0
            dialog.set_geometry_hints(None, geometry, Gdk.WindowHints.ASPECT)

            box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=2)
            dialog.get_content_area().add(box)
            box.show()

            # XXX We use printf-style string for sharing the localized
            # string. You may just use recommended Python format() or
            # any style you like in your plug-ins.
            head_text = ("This plug-in is an exercise in '%s' to "
                         "demo plug-in creation.\nCheck out the last "
                         "version of the source code online by clicking "
                         "the \"Source\" button." % ("Python 3"))
            label = Gtk.Label(label=head_text)
            box.pack_start(label, False, False, 1)
            label.show()

            contents = None
            # Get the file contents Python-style instead of using
            # GLib.file_get_contents() which returns bytes result, and
            # when converting to string, get newlines as text contents.
            # Rather than wasting time to figure this out, use Python
            # core API!
            with open(os.path.realpath(__file__), 'r') as f:
                contents = f.read()

            if contents is not None:
                scrolled = Gtk.ScrolledWindow()
                scrolled.set_vexpand(True)
                box.pack_start(scrolled, True, True, 1)
                scrolled.show()

                view = Gtk.TextView()
                view.set_wrap_mode(Gtk.WrapMode.WORD)
                view.set_editable(False)
                buffer = view.get_buffer()
                buffer.set_text(contents, -1)
                scrolled.add(view)
                view.show()

            while (True):
                response = dialog.run()
                if response == Gtk.ResponseType.OK:
                    dialog.destroy()
                    break
                elif response == Gtk.ResponseType.APPLY:
                    url = "https://gitlab.gnome.org/GNOME/gimp/-/blob/master/plug-ins/goat-exercises/goat-exercise-py3.py"
                    Gio.app_info_launch_default_for_uri(url, None)
                    continue
                else:
                    dialog.destroy()
                    return procedure.new_return_values(
                        Gimp.PDBStatusType.CANCEL, GLib.Error())

        intersect, x, y, width, height = drawable.mask_intersect()
        if intersect:
            Gegl.init(None)

            buffer = drawable.get_buffer()
            shadow_buffer = drawable.get_shadow_buffer()

            graph = Gegl.Node()
            input = graph.create_child("gegl:buffer-source")
            input.set_property("buffer", buffer)
            invert = graph.create_child("gegl:invert")
            output = graph.create_child("gegl:write-buffer")
            output.set_property("buffer", shadow_buffer)
            input.link(invert)
            invert.link(output)
            output.process()

            # This is extremely important in bindings, since we don't
            # unref buffers. If we don't explicitly flush a buffer, we
            # may left hanging forever. This step is usually done
            # during an unref().
            shadow_buffer.flush()

            drawable.merge_shadow(True)
            drawable.update(x, y, width, height)
            Gimp.displays_flush()

        return procedure.new_return_values(Gimp.PDBStatusType.SUCCESS,
                                           GLib.Error())
Beispiel #37
0
 def _new_default_loop(self):
     l = GLibEventLoop(context=GLib.main_context_default(), application=self._application)
     l._policy = self
     return l
Beispiel #38
0
    def __init__(self, options, title="Xpra Session Browser"):
        super().__init__()
        self.exit_code = 0
        self.set_title(title)
        self.set_border_width(20)
        self.set_resizable(True)
        self.set_default_size(800, 220)
        self.set_decorated(True)
        self.set_size_request(800, 220)
        self.set_position(Gtk.WindowPosition.CENTER)
        self.set_wmclass("xpra-sessions-gui", "Xpra-Sessions-GUI")
        add_close_accel(self, self.quit)
        self.connect("delete_event", self.quit)
        icon = get_icon_pixbuf("browse.png")
        if icon:
            self.set_icon(icon)

        hb = Gtk.HeaderBar()
        hb.set_show_close_button(True)
        hb.props.title = "Xpra"
        button = Gtk.Button()
        icon = Gio.ThemedIcon(name="help-about")
        image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
        button.add(image)
        button.set_tooltip_text("About")
        button.connect("clicked", self.show_about)
        hb.add(button)
        hb.show_all()
        self.set_titlebar(hb)

        self.clients = {}
        self.clients_disconnecting = set()
        self.child_reaper = getChildReaper()

        self.vbox = Gtk.VBox(False, 20)
        self.add(self.vbox)

        title_label = Gtk.Label(title)
        title_label.modify_font(Pango.FontDescription("sans 14"))
        title_label.show()
        self.vbox.add(title_label)

        self.warning = Gtk.Label(" ")
        red = color_parse("red")
        self.warning.modify_fg(Gtk.StateType.NORMAL, red)
        self.warning.show()
        self.vbox.add(self.warning)

        self.password_box = Gtk.HBox(False, 10)
        self.password_label = Gtk.Label("Password:"******""
        #log.info("options=%s (%s)", options, type(options))
        self.local_info_cache = {}
        self.dotxpra = DotXpra(options.socket_dir, options.socket_dirs,
                               username)
        self.poll_local_sessions()
        self.populate()
        GLib.timeout_add(5 * 1000, self.update)
        self.vbox.show()
        self.show()
def array_to_variant(array):
    '''Encode :array: as an array of strings or an array of variants.'''
    if all([isinstance(e, str) for e in array]):
        return GLib.Variant('as', array)

    return GLib.Variant('av', [to_variant(e) for e in array if e is not None])
Beispiel #40
0
 def time(self):
     return GLib.get_monotonic_time() / 1000000
Beispiel #41
0
 def populate_games(self, games):
     loader = self._fill_store_generator(games)
     GLib.idle_add(loader.__next__)
def dict_to_variant(dictionary):
    '''Encode :dictionary:' as a variant of type a{sv}.'''
    return GLib.Variant('a{sv}', {
        k: to_variant(v) for k, v in dictionary.items() if v is not None
    })
Beispiel #43
0
    def populate(self, contacts):
        self.create_window()

        self.create_table()
        if not contacts or len(contacts) == 0:
            # Tooltip for merged accounts row
            accounts = helpers.get_notification_icon_tooltip_dict()
            self.spacer_label = ''
            self.fill_table_with_accounts(accounts)
            self.win.add(self.table)
            return

        # primary contact
        prim_contact = gajim.contacts.get_highest_prio_contact_from_contacts(
            contacts)

        puny_jid = helpers.sanitize_filename(prim_contact.jid)
        table_size = 3

        file_ = helpers.get_avatar_path(os.path.join(gajim.AVATAR_PATH,
            puny_jid))
        if file_:
            with open(file_, 'rb') as file_data:
                pix = gtkgui_helpers.get_pixbuf_from_data(file_data.read())
            pix = gtkgui_helpers.get_scaled_pixbuf(pix, 'tooltip')
            self.avatar_image.set_from_pixbuf(pix)
            table_size = 4
        else:
            self.avatar_image.set_from_pixbuf(None)
        vcard_table = Gtk.Grid()
        vcard_table.insert_row(0)
        for i in range(0, table_size):
            vcard_table.insert_column(0)
        vcard_table.set_property('column-spacing', 2)
        vcard_current_row = 1
        properties = []

        name_markup = '<span weight="bold">' + GLib.markup_escape_text(
            prim_contact.get_shown_name()) + '</span>'
        if gajim.config.get('mergeaccounts'):
            name_markup += " <span foreground='%s'>(%s)</span>" % (
                gajim.config.get('tooltip_account_name_color'),
                GLib.markup_escape_text(prim_contact.account.name))

        if self.account and helpers.jid_is_blocked(self.account,
        prim_contact.jid):
            name_markup += _(' [blocked]')
        if self.account and \
        self.account in gajim.interface.minimized_controls and \
        prim_contact.jid in gajim.interface.minimized_controls[self.account]:
            name_markup += _(' [minimized]')
        properties.append((name_markup, None))

        num_resources = 0
        # put contacts in dict, where key is priority
        contacts_dict = {}
        for contact in contacts:
            if contact.resource:
                num_resources += 1
                if contact.priority in contacts_dict:
                    contacts_dict[int(contact.priority)].append(contact)
                else:
                    contacts_dict[int(contact.priority)] = [contact]

        if num_resources > 1:
            properties.append((_('Status: '),       ' '))
            transport = gajim.get_transport_name_from_jid(prim_contact.jid)
            if transport:
                file_path = os.path.join(helpers.get_transport_path(transport),
                    '16x16')
            else:
                iconset = gajim.config.get('iconset')
                if not iconset:
                    iconset = 'dcraven'
                file_path = os.path.join(helpers.get_iconset_path(iconset),
                    '16x16')

            contact_keys = sorted(contacts_dict.keys())
            contact_keys.reverse()
            for priority in contact_keys:
                for acontact in contacts_dict[priority]:
                    status_line = self.get_status_info(acontact.resource,
                        acontact.priority, acontact.show, acontact.status)

                    icon_name = self._get_icon_name_for_tooltip(acontact)
                    self.add_status_row(file_path, icon_name, status_line,
                        acontact.last_status_time)
            properties.append((self.table,  None))

        else: # only one resource
            if contact.show:
                show = helpers.get_uf_show(contact.show)
                if not self.check_last_time and self.account:
                    if contact.show == 'offline':
                        if not contact.last_status_time:
                            gajim.connections[self.account].\
                                request_last_status_time(contact.jid, '')
                        else:
                            self.check_last_time = contact.last_status_time
                    elif contact.resource:
                        gajim.connections[self.account].\
                            request_last_status_time(
                            contact.jid, contact.resource)
                        if contact.last_activity_time:
                            self.check_last_time = contact.last_activity_time
                else:
                    self.check_last_time = None
                if contact.last_status_time:
                    vcard_current_row += 1
                    if contact.show == 'offline':
                        text = ' - ' + _('Last status: %s')
                    else:
                        text = _(' since %s')

                    if time.strftime('%j', time.localtime()) == \
                        time.strftime('%j', contact.last_status_time):
                        # it's today, show only the locale hour representation
                        local_time = time.strftime('%X',
                            contact.last_status_time)
                    else:
                        # time.strftime returns locale encoded string
                        local_time = time.strftime('%c',
                            contact.last_status_time)

                    text = text % local_time
                    show += text
                if self.account and \
                prim_contact.jid in gajim.gc_connected[self.account]:
                    if gajim.gc_connected[self.account][prim_contact.jid]:
                        show = _('Connected')
                    else:
                        show = _('Disconnected')
                show = self.colorize_status(show)

                if contact.status:
                    status = contact.status.strip()
                    if status:
                        # reduce long status
                        # (no more than 300 chars on line and no more than
                        # 5 lines)
                        # status is wrapped
                        status = helpers.reduce_chars_newlines(status, 300, 5)
                        # escape markup entities.
                        status = GLib.markup_escape_text(status)
                        properties.append(('<i>%s</i>' % status, None))
                properties.append((show, None))

        self._append_pep_info(contact, properties)

        properties.append((_('Jabber ID: '), '\u200E' + "<b>%s</b>" % \
            prim_contact.jid))

        # contact has only one ressource
        if num_resources == 1 and contact.resource:
            properties.append((_('Resource: '), GLib.markup_escape_text(
                contact.resource) + ' (' + str(contact.priority) + ')'))

        if self.account and prim_contact.sub and prim_contact.sub != 'both' and\
        prim_contact.jid not in gajim.gc_connected[self.account]:
            # ('both' is the normal sub so we don't show it)
            properties.append(( _('Subscription: '), GLib.markup_escape_text(
                helpers.get_uf_sub(prim_contact.sub))))

        if prim_contact.keyID:
            keyID = None
            if len(prim_contact.keyID) == 8:
                keyID = prim_contact.keyID
            elif len(prim_contact.keyID) == 16:
                keyID = prim_contact.keyID[8:]
            if keyID:
                properties.append((_('OpenPGP: '), GLib.markup_escape_text(
                    keyID)))

        if contact.last_activity_time:
            last_active = datetime(*contact.last_activity_time[:6])
            current = datetime.now()

            diff = current - last_active
            diff = timedelta(diff.days, diff.seconds)

            if last_active.date() == current.date():
                formatted = last_active.strftime("%X")
            else:
                formatted = last_active.strftime("%c")

            # Do not show the "Idle since" and "Idle for" items if there
            # is no meaningful difference between last activity time and
            # current time.
            if diff.days > 0 or diff.seconds > 0:
                cs = "<span foreground='%s'>" % gajim.config.get(
                    'tooltip_idle_color')
                cs += '%s</span>'
                properties.append((str(), None))
                idle_since = cs % _("Idle since %s")
                properties.append((idle_since % formatted, None))
                idle_for = cs % _("Idle for %s")
                properties.append((idle_for % str(diff), None))

        while properties:
            property_ = properties.pop(0)
            vcard_current_row += 1
            label = Gtk.Label()
            if not properties and table_size == 4:
                label.set_vexpand(True)
            label.set_alignment(0, 0)
            if property_[1]:
                label.set_markup(property_[0])
                vcard_table.attach(label, 1, vcard_current_row, 1, 1)
                label = Gtk.Label()
                if not properties and table_size == 4:
                    label.set_vexpand(True)
                label.set_alignment(0, 0)
                label.set_markup(property_[1])
                label.set_line_wrap(True)
                vcard_table.attach(label, 2, vcard_current_row, 1, 1)
            else:
                if isinstance(property_[0], str):
                    label.set_markup(property_[0])
                    label.set_line_wrap(True)
                else:
                    label = property_[0]
                vcard_table.attach(label, 1, vcard_current_row, 2, 1)
        self.avatar_image.set_alignment(0, 0)
        if table_size == 4:
            vcard_table.attach(self.avatar_image, 3, 2, 1, vcard_current_row - 1)

        gajim.plugin_manager.gui_extension_point('roster_tooltip_populate',
            self, contacts, vcard_table)
        self.win.add(vcard_table)
def _dbus_error_to_companion_app_error(error):
    '''Translate the GDBusError from EknServices to a Companion App error.'''
    code = _EKS_ERROR_TO_COMPANION_APP_ERROR[Gio.DBusError.get_remote_error(error)]
    return GLib.Error(error.message,  # pylint: disable=no-member
                      EosCompanionAppService.error_quark(),
                      code)
Beispiel #45
0
 def motion_notify_event(self, widget, event):
     GLib.idle_add(self.hide_tooltip)
Beispiel #46
0
    def populate(self, file_props):
        ft_table = Gtk.Table(2, 1)
        ft_table.set_property('column-spacing', 2)
        current_row = 1
        self.create_window()
        properties = []
        name = file_props.name
        if file_props.type_ == 'r':
            file_name = os.path.split(file_props.file_name)[1]
        else:
            file_name = file_props.name
        properties.append((_('Name: '), GLib.markup_escape_text(file_name)))
        if file_props.type_ == 'r':
            type_ = _('Download')
            actor = _('Sender: ')
            sender = file_props.sender.split('/')[0]
            name = gajim.contacts.get_first_contact_from_jid(
                    file_props.tt_account, sender).get_shown_name()
        else:
            type_ = _('Upload')
            actor = _('Recipient: ')
            receiver = file_props.receiver
            if hasattr(receiver, 'name'):
                name = receiver.get_shown_name()
            else:
                name = receiver.split('/')[0]
        properties.append((_('Type: '), type_))
        properties.append((actor, GLib.markup_escape_text(name)))

        transfered_len = file_props.received_len
        if not transfered_len:
            transfered_len = 0
        properties.append((_('Transferred: '), helpers.convert_bytes(transfered_len)))
        status = ''
        if file_props.started:
            status = _('Not started')
        if file_props.stopped == True:
            status = _('Stopped')
        elif file_props.completed:
            status = _('Completed')
        elif file_props.connected == False:
            if file_props.completed:
                status = _('Completed')
            else:
                if file_props.paused == True:
                    status = _('?transfer status:Paused')
                elif file_props.stalled == True:
                    #stalled is not paused. it is like 'frozen' it stopped alone
                    status = _('Stalled')
                else:
                    status = _('Transferring')
        else:
            status = _('Not started')
        properties.append((_('Status: '), status))
        file_desc = file_props.desc or ''
        properties.append((_('Description: '), GLib.markup_escape_text(
            file_desc)))
        while properties:
            property_ = properties.pop(0)
            current_row += 1
            label = Gtk.Label()
            label.set_alignment(0, 0)
            label.set_markup(property_[0])
            ft_table.attach(label, 1, 2, current_row, current_row + 1,
                    Gtk.AttachOptions.FILL, Gtk.AttachOptions.FILL, 0, 0)
            label = Gtk.Label()
            label.set_alignment(0, 0)
            label.set_line_wrap(True)
            label.set_markup(property_[1])
            ft_table.attach(label, 2, 3, current_row, current_row + 1,
                    Gtk.AttachOptions.EXPAND | Gtk.AttachOptions.FILL, Gtk.AttachOptions.FILL, 0, 0)

        self.win.add(ft_table)
Beispiel #47
0
def load_html(content, base_uri):
    def _load_html():
        BrowserView.instance.load_html(content, base_uri)

    glib.idle_add(_load_html)
Beispiel #48
0
    def populate(self, contact):
        if not contact:
            return
        self.create_window()
        vcard_table = Gtk.Grid()
        vcard_table.insert_row(0)
        vcard_table.insert_row(0)
        vcard_table.insert_row(0)
        vcard_table.insert_column(0)
        vcard_table.set_property('column-spacing', 2)
        vcard_current_row = 1
        properties = []

        nick_markup = '<b>' + GLib.markup_escape_text(contact.get_shown_name())\
            + '</b>'
        properties.append((nick_markup, None))

        if contact.status: # status message
            status = contact.status.strip()
            if status != '':
                # escape markup entities
                status = helpers.reduce_chars_newlines(status, 300, 5)
                status = '<i>' + GLib.markup_escape_text(status) + '</i>'
                properties.append((status, None))

        show = helpers.get_uf_show(contact.show)
        show = self.colorize_status(show)
        properties.append((show, None))

        if contact.jid.strip():
            properties.append((_('Jabber ID: '), '\u200E' + "<b>%s</b>" % \
                contact.jid))

        if hasattr(contact, 'resource') and contact.resource.strip():
            properties.append((_('Resource: '), GLib.markup_escape_text(
                contact.resource)))

        if contact.affiliation != 'none':
            uf_affiliation = helpers.get_uf_affiliation(contact.affiliation)
            uf_affiliation = \
                _('%(owner_or_admin_or_member)s of this group chat') % \
                {'owner_or_admin_or_member': uf_affiliation}
            uf_affiliation = self.colorize_affiliation(uf_affiliation)
            properties.append((uf_affiliation, None))

        # Add avatar
        puny_name = helpers.sanitize_filename(contact.name)
        puny_room = helpers.sanitize_filename(contact.room_jid)
        file_ = helpers.get_avatar_path(os.path.join(gajim.AVATAR_PATH,
            puny_room, puny_name))
        if file_:
            with open(file_, 'rb') as file_data:
                pix = gtkgui_helpers.get_pixbuf_from_data(file_data.read())
            pix = gtkgui_helpers.get_scaled_pixbuf(pix, 'tooltip')
            self.avatar_image.set_from_pixbuf(pix)
        else:
            self.avatar_image.set_from_pixbuf(None)
        while properties:
            property_ = properties.pop(0)
            vcard_current_row += 1
            label = Gtk.Label()
            if not properties:
                label.set_vexpand(True)
            label.set_alignment(0, 0)
            if property_[1]:
                label.set_markup(property_[0])
                vcard_table.attach(label, 1, vcard_current_row, 1, 1)
                label = Gtk.Label()
                if not properties:
                    label.set_vexpand(True)
                label.set_alignment(0, 0)
                label.set_markup(property_[1])
                label.set_line_wrap(True)
                vcard_table.attach(label, 2, vcard_current_row, 1, 1)
            else:
                label.set_markup(property_[0])
                label.set_line_wrap(True)
                vcard_table.attach(label, 1, vcard_current_row, 2, 1)

        self.avatar_image.set_alignment(0, 0)
        vcard_table.attach(self.avatar_image, 3, 2, 1, vcard_current_row - 1)
        gajim.plugin_manager.gui_extension_point('gc_tooltip_populate',
            self, contact, vcard_table)
        self.win.add(vcard_table)
Beispiel #49
0
def toggle_fullscreen():
    def _toggle_fullscreen():
        BrowserView.instance.toggle_fullscreen()

    glib.idle_add(_toggle_fullscreen)
Beispiel #50
0
    def __init__(self):
        ## This allows to translate all py texts (not the glade ones)
        #gettext.textdomain(APP_NAME)
        #gettext.bindtextdomain(APP_NAME, LOCALE_DIR)
        #
        #locale_code, encoding = locale.getdefaultlocale()
        #lang = gettext.translation(APP_NAME, LOCALE_DIR, [locale_code], None, True)
        #lang.install()
        #
        ## With this we can use _("string") to translate
        #gettext.install(APP_NAME, localedir=LOCALE_DIR, codeset=None, names=[locale_code])

        # Check if we have administrative privileges
        if os.getuid() != 0:
            show.fatal_error(
                _('This installer must be run with administrative'
                  ' privileges and cannot continue without them.'))

        setup_logging()

        # Check if we're already running
        tmp_running = "/tmp/.setup-running"
        if os.path.exists(tmp_running):
            show.error(
                _('You cannot run two instances of this installer.\n\n'
                  'If you are sure that another installer is not already running\n'
                  'you can manually delete the file %s\n'
                  'and run this installer again.') % tmp_running)
            sys.exit(1)

        super().__init__()

        # workaround for dconf
        os.system("mkdir -p /root/.cache/dconf")
        os.system("chmod -R 777 /root/.cache")

        logging.info(_("Thus installer version %s"), info.THUS_VERSION)

        current_process = multiprocessing.current_process()
        logging.debug("[%d] %s started", current_process.pid,
                      current_process.name)

        self.settings = config.Settings()

        thus_dir = os.path.join(os.path.dirname(__file__), './')
        if os.path.exists(thus_dir):
            self.settings.set('thus', thus_dir)
        else:
            thus_dir = self.settings.get('thus')

        ui_dir = os.path.join(os.path.dirname(__file__), 'ui/')
        if os.path.exists(ui_dir):
            self.settings.set('ui', ui_dir)
        else:
            ui_dir = self.settings.get('ui')

        data_dir = os.path.join(os.path.dirname(__file__), 'data/')
        if os.path.exists(data_dir):
            self.settings.set('data', data_dir)
        else:
            data_dir = self.settings.get('data')

        if os.path.exists("/sys/firmware/efi"):
            self.settings.set('efi', True)

        self.ui = Gtk.Builder()
        self.ui.add_from_file(ui_dir + "thus.ui")

        self.add(self.ui.get_object("main"))

        self.header = self.ui.get_object("header")

        self.forward_button = self.ui.get_object("forward_button")

        self.logo = self.ui.get_object("logo")

        logo_dir = os.path.join(data_dir, "manjaro-logo-mini.png")

        self.logo.set_from_file(logo_dir)

        self.title = self.ui.get_object("title")

        # To honor our css
        self.title.set_name("header")
        self.logo.set_name("header")

        self.main_box = self.ui.get_object("main_box")
        self.progressbar = self.ui.get_object("progressbar1")

        self.forward_button = self.ui.get_object("forward_button")
        self.exit_button = self.ui.get_object("exit_button")
        self.backwards_button = self.ui.get_object("backwards_button")

        # Create a queue. Will be used to report pacman messages (pac.py)
        # to the main thread (installer_*.py)
        self.callback_queue = multiprocessing.JoinableQueue()

        # Load all pages
        # (each one is a screen, a step in the install process)

        self.pages = dict()

        params = dict()
        params['title'] = self.title
        params['forward_button'] = self.forward_button
        params['backwards_button'] = self.backwards_button
        params['exit_button'] = self.exit_button
        params['callback_queue'] = self.callback_queue
        params['settings'] = self.settings
        params['main_progressbar'] = self.ui.get_object('progressbar1')
        params['alternate_package_list'] = ""
        params['testing'] = cmd_line.testing

        self.pages["language"] = language.Language(params)
        self.pages["location"] = location.Location(params)
        self.pages["check"] = check.Check(params)
        self.pages["keymap"] = keymap.Keymap(params)
        self.pages["timezone"] = timezone.Timezone(params)
        self.pages["installation_ask"] = installation_ask.InstallationAsk(
            params)
        self.pages[
            "installation_automatic"] = installation_automatic.InstallationAutomatic(
                params)
        self.pages[
            "installation_alongside"] = installation_alongside.InstallationAlongside(
                params)
        self.pages[
            "installation_advanced"] = installation_advanced.InstallationAdvanced(
                params)
        self.pages["user_info"] = user_info.UserInfo(params)
        self.pages["slides"] = slides.Slides(params)

        self.connect("delete-event", Gtk.main_quit)
        self.ui.connect_signals(self)

        self.set_title(_('Manjaro Installer'))
        self.set_position(Gtk.WindowPosition.CENTER)
        self.set_resizable(False)
        self.set_size_request(MAIN_WINDOW_WIDTH, MAIN_WINDOW_HEIGHT)

        # Set window icon
        icon_dir = os.path.join(data_dir, 'manjaro-icon.png')

        self.set_icon_from_file(icon_dir)

        # Set the first page to show
        self.current_page = self.pages["language"]

        self.main_box.add(self.current_page)

        # Header style testing

        style_provider = Gtk.CssProvider()

        style_css = os.path.join(data_dir, "css", "gtk-style.css")

        with open(style_css, 'rb') as css:
            css_data = css.read()

        style_provider.load_from_data(css_data)

        Gtk.StyleContext.add_provider_for_screen(
            Gdk.Screen.get_default(), style_provider,
            Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)

        # Show main window
        self.show_all()

        self.current_page.prepare('forwards')

        # Hide backwards button
        self.backwards_button.hide()

        # Hide titlebar but show border decoration
        self.get_window().set_accept_focus(True)
        #self.get_window().set_decorations(Gdk.WMDecoration.BORDER)

        # Hide progress bar as it's value is zero
        self.progressbar.set_fraction(0)
        self.progressbar.hide()
        self.progressbar_step = 1.0 / (len(self.pages) - 2)

        with open(tmp_running, "w") as tmp_file:
            tmp_file.write("Thus %d\n" % 1234)

        GLib.timeout_add(1000,
                         self.pages["slides"].manage_events_from_cb_queue)
Beispiel #51
0
 def on_load_finish(self, webview, webframe):
     # Show the webview if it's not already visible
     if not webview.props.opacity:
         glib.idle_add(webview.set_opacity, 1.0)
Beispiel #52
0
def load_url(url):
    def _load_url():
        BrowserView.instance.load_url(url)

    glib.idle_add(_load_url)
Beispiel #53
0
    def do_size_allocate(self, alloc):
        if self.get_shadow_type() == Gtk.ShadowType.NONE:
            return Gtk.ScrolledWindow.do_size_allocate(self, alloc)

        toplevel = self.get_toplevel()

        try:
            dx, dy = self.translate_coordinates(toplevel, 0, 0)
        except TypeError:
            GLib.idle_add(self.queue_resize)
            return Gtk.ScrolledWindow.do_size_allocate(self, alloc)

        # since 3.15 the gdkwindow moves to dx==-1 with the allocation
        # so ignore anything < 0 (I guess something passes the adjusted alloc
        # to us a second time)
        # https://git.gnome.org/browse/gtk+/commit/?id=fdf367e8689cb
        dx = max(0, dx)
        dy = max(0, dy)

        ctx = self.get_style_context()
        border = ctx.get_border(self.get_state_flags())

        # https://bugzilla.gnome.org/show_bug.cgi?id=694844
        border.left = border.top = border.right = border.bottom = 1

        # XXX: ugly, ugly hack
        # Pretend the main window toolbar is the top of the window.
        # This removes the top border in case the ScrolledWindow
        # is drawn right below the toolbar.
        try:
            top_bar = toplevel.top_bar
            if not isinstance(top_bar, Gtk.Widget):
                raise TypeError
        except (AttributeError, TypeError):
            # In case the window border is at the top, we expect the menubar
            # there, so draw the normal border
            border.top = 0
        else:
            top_ctx = top_bar.get_style_context()
            b = top_ctx.get_border(top_bar.get_state_flags())
            # only if the toolbar has a border we hide our own.
            # seems to work, even tough it doesn't for getting the
            # Notebook/ScrolledWindow border :/
            if b.bottom:
                dy = 0

        # Don't remove the border if the border is drawn inside
        # and the scrollbar on that edge is visible
        bottom = left = right = top = False

        value = GObject.Value()
        value.init(GObject.TYPE_BOOLEAN)
        # default to True: https://bugzilla.gnome.org/show_bug.cgi?id=701058
        value.set_boolean(True)
        ctx.get_style_property("scrollbars-within-bevel", value)
        scroll_within = value.get_boolean()
        value.unset()

        if not scroll_within:
            h, v = self.get_hscrollbar(), self.get_vscrollbar()
            hscroll = vscroll = False
            if h.get_visible():
                req = h.size_request()
                hscroll = bool(req.width + req.height)

            if v.get_visible():
                req = v.size_request()
                vscroll = bool(req.width + req.height)

            placement = self.get_placement()
            if placement == Gtk.CornerType.TOP_LEFT:
                bottom = hscroll
                right = vscroll
            elif placement == Gtk.CornerType.BOTTOM_LEFT:
                right = vscroll
                top = hscroll
            elif placement == Gtk.CornerType.TOP_RIGHT:
                bottom = hscroll
                left = vscroll
            elif placement == Gtk.CornerType.BOTTOM_RIGHT:
                left = vscroll
                top = hscroll

        width, height = toplevel.get_size()
        if alloc.height + dy == height and not bottom:
            alloc.height += border.bottom

        if alloc.width + dx == width and not right:
            alloc.width += border.right

        if dy == 0 and not top:
            alloc.y -= border.top
            alloc.height += border.top

        if dx == 0 and not left:
            alloc.x -= border.left
            alloc.width += border.left

        return Gtk.ScrolledWindow.do_size_allocate(self, alloc)
Beispiel #54
0
def destroy_window():
    def _destroy_window():
        BrowserView.instance.close_window()

    glib.idle_add(_destroy_window)
Beispiel #55
0
 def mount(self):
     logger.info("Mounting volume %s", self.device_file)
     self.udisks_object.get_filesystem().call_mount_sync(GLib.Variant('a{sv}', {}),  # options
                                                         None)                       # cancellable
Beispiel #56
0
 def emit(self, *args):
     GLib.idle_add(GObject.GObject.emit, self, *args)
Beispiel #57
0
#da.add_tick_callback(redraw)
#new_gdk_window()
#gl.connect('render',render.gl_render)
#gl.connect('realize', area_realize)
daxid=da.get_window().get_xid()
r=da.get_allocated_size().allocation
print("%d %d %d %d\n" % (r.x, r.y, r.width, r.height))
dpy=Gdk.Display.get_default().get_xdisplay()
print("python dpy=",dpy," win=",daxid)
#print ([a for a in dir(dpy)])
import scope
scope.get_egl_ctx(dpy,daxid)
import render
import sys
sys.path.append('../../rawcamII')

import rawcam
cam_src = GLib.IOChannel(camera_init())
GLib.io_add_watch(cam_src,GLib.IO_IN,got_camera)
#root=Gdk.get_default_root_window()
#scr=Gdk.Display.get_default_screen()
Gtk.main()
exit()
import cProfile
GLib.timeout_add(30000, Gtk.main_quit, None)
pr = cProfile.Profile()
pr.enable()
Gtk.main()
pr.disable()
pr.print_stats(sort="cumtime")
Beispiel #58
0
PROJECT = "Lutris"
VERSION = "0.4.23"
COPYRIGHT = "(c) 2010-2018 Lutris Gaming Platform"
AUTHORS = [
    "Mathieu Comandon <*****@*****.**>",
    "Pascal Reinhard (Xodetaetl) <*****@*****.**"
]
ARTISTS = ["Ludovic Soulié <*****@*****.**>"]

# Paths
is_snap = 'SNAP' in os.environ and 'SNAP_USER_DATA' in os.environ
if is_snap:
    CONFIG_DIR = os.path.join(os.environ['SNAP_USER_DATA'], 'config')
else:
    CONFIG_DIR = os.path.join(GLib.get_user_config_dir(), 'lutris')
CONFIG_FILE = os.path.join(CONFIG_DIR, "lutris.conf")
if is_snap:
    DATA_DIR = os.path.join(os.environ['SNAP_USER_DATA'], 'data')
else:
    DATA_DIR = os.path.join(GLib.get_user_data_dir(), 'lutris')
RUNNER_DIR = os.path.join(DATA_DIR, "runners")
RUNTIME_DIR = os.path.join(DATA_DIR, "runtime")
if is_snap:
    CACHE_DIR = os.path.join(os.environ['SNAP_USER_DATA'], 'cache')
else:
    CACHE_DIR = os.path.join(GLib.get_user_cache_dir(), 'lutris')
GAME_CONFIG_DIR = os.path.join(CONFIG_DIR, 'games')

TMP_PATH = os.path.join(CACHE_DIR, 'tmp')
BANNER_PATH = os.path.join(DATA_DIR, 'banners')
Beispiel #59
0
 def __do_realize(self, widget):
     GLib.timeout_add(3000, self.__destroy)
Beispiel #60
0
 def lock(self):
     logger.info("Locking volume %s", self.device_file)
     self.udisks_object.get_encrypted().call_lock_sync(GLib.Variant('a{sv}', {}),  # options
                                                       None)                       # cancellable