Example #1
0
    def _add_tracks(self, tracks, widget, disc_number, i):
        """
            Add tracks for to tracks widget
            @param tracks as [int]
            @param widget as TracksWidget
            @param disc number as int
            @param i as int
        """
        if self._stop:
            self._stop = False
            return
        if not tracks:
            if widget == self._tracks_right:
                self.emit('populated')
            else:
                self._locked_widget_right = False
            return

        track = tracks.pop(0)
        if not Lp().settings.get_value('show-tag-tracknumber'):
            track_number = i
        else:
            track_number = track.number

        row = TrackRow(track.id, track_number)
        row.show()
        widget[disc_number].add(row)
        GLib.idle_add(self._add_tracks, tracks, widget, disc_number, i + 1)
Example #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))
Example #3
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()))
Example #4
0
    def do_login(self, user_name):
        """Login using autologin"""
        if not self.server_ready:
            raise tailsgreeter.errors.GdmServerNotReady

        GLib.idle_add(
            lambda: self.__greeter_client.call_begin_auto_login(user_name))
Example #5
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)
Example #6
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 )
 def fetch_poll(self, fp, async_result):
     try:
         success, data, etag = fp.load_contents_finish(async_result)
     except:
         print "request failed: error"
         GLib.timeout_add_seconds(10, self.start_poll)
         self.ind.set_icon_full("syncthing-client-error", "Couldn't connect to syncthing")
         return
     if success:
         try:
             queue = json.loads(data)
         except ValueError:
             print "request failed to parse json: error"
             GLib.timeout_add_seconds(10, self.start_poll)
             self.ind.set_icon_full("syncthing-client-error", "Couldn't connect to syncthing")
         for qitem in queue:
             self.process_event(qitem)
     else:
         print "request failed"
     if self.downloading_files or self.uploading_files:
         self.ind.set_icon_full("syncthing-client-updating", 
             "Updating %s files" % (
                 len(self.downloading_files) + len(self.uploading_files)))
     else:
         self.ind.set_icon_full("syncthing-client-idle", "Up to date")
     GLib.idle_add(self.start_poll)
Example #8
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)
Example #9
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)
Example #10
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)
Example #11
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)
Example #12
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__)
Example #13
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)
Example #14
0
File: gui.py Project: Kismon/kismon
	def networks_queue_progress(self):
		if self.progress_bar_win is not None:
			return
		
		self.progress_bar_max = float(len(self.networks.notify_add_queue))
		if self.networks.queue_task:
			self.progress_bar = Gtk.ProgressBar()
			self.progress_bar.set_text("0.0%%, %s networks left" % len(self.networks.notify_add_queue))
			self.progress_bar.set_show_text(True)
			self.progress_bar.set_fraction(0)
			
			self.progress_bar_win = Gtk.Window()
			self.progress_bar_win.set_title("Adding networks")
			self.progress_bar_win.set_position(Gtk.WindowPosition.CENTER)
			self.progress_bar_win.set_default_size(300, 30)
			self.progress_bar_win.set_modal(True)
			self.progress_bar_win.set_transient_for(self.gtkwin)
			self.progress_bar_win.add(self.progress_bar)
			self.progress_bar_win.show_all()
			def on_delete_event(widget, event):
				return True
			self.progress_bar_win.connect("delete-event",on_delete_event)
			self.progress_bar_win.connect("destroy", self.on_destroy_progress_bar_win)
			
			GLib.idle_add(self.networks_queue_progress_update)
Example #15
0
    def monitor_changed(self, monitor, file_a, file_b, event_type):
        # Don't update anything as we will do
        # a full update when we have focus again
        if not self.has_focus:
            return

        # Only monitor for changes as the file browser
        # will emit signals for the other event types
        if event_type != Gio.FileMonitorEvent.CHANGED:
            return

        for f in (file_a, file_b):
            if f is None:
                continue

            # Must let the view activatable know
            # that its location's contents have changed
            view_activatable = self.get_view_activatable_by_location(f)
            if view_activatable is not None:
                # Must reload the location's contents, not just rediff
                GLib.idle_add(view_activatable.update_location)

                # Still need to update the git status
                # as the file could now be in .gitignore

            if f in self.file_nodes:
                repo = self.get_repository(f)
                if repo is not None:
                    self.git_status_thread.push(repo, f)
Example #16
0
    def __mover_videos(self, widget):
        """
        Pasa todos los videos de una lista a otra.
        """

        self.set_sensitive(False)
        self.get_toplevel().toolbar_busqueda.set_sensitive(False)

        map(self.__cancel_toolbars, self.toolbars_flotantes)

        if widget == self.toolbar_videos_izquierda:
            origen = self.encontrados
            destino = self.descargar
            text = TipDescargas

        elif widget == self.toolbar_videos_derecha:
            origen = self.descargar
            destino = self.encontrados
            text = TipEncontrados

        elementos = origen.get_children()

        GLib.idle_add(
            self.__ejecutar_mover_videos,
            origen,
            destino,
            text,
            elementos)
Example #17
0
    def _populate(self):
        """
            Same as _populate()
            Horrible code limited to two engines,
            need rework if adding one more
            @thread safe
        """
        url = None
        image_url = None
        content = None
        if self._wikipedia and self.Wikipedia is not None:
            self._wikipedia = False
            (url, image_url, content) = self.Wikipedia().get_artist_infos(
                self._artist)
        if url is None and Lp.lastfm is not None:
            self._wikipedia = True
            (url, image_url, content) = Lp.lastfm.get_artist_infos(
                                            self._artist)

        stream = None
        try:
            if image_url is not None:
                f = Gio.File.new_for_uri(image_url)
                (status, data, tag) = f.load_contents()
                if status:
                    stream = Gio.MemoryInputStream.new_from_data(data,
                                                                 None)
        except Exception as e:
            print("PopArtistInfos::_populate: %s" % e)

        GLib.idle_add(self._set_content, content, url, stream)
Example #18
0
 def _delete_cb(self, widget):
     """Properties dialog delete callback"""
     self._dialog.hide()
     name = brushmanager.translate_group_name(self._group)
     msg = C_(
         "brush group delete",
         u"Really delete group \u201C{group_name}\u201D?",
     ).format(
         group_name = name,
     )
     bm = self._app.brushmanager
     if not dialogs.confirm(self, msg):
         return
     bm.delete_group(self._group)
     if self._group not in bm.groups:
         GLib.idle_add(
             self._remove_panel_idle_cb,
             self.__gtype_name__, (self._group,),
         )
         return
     # Special groups like "Deleted" cannot be deleted,
     # but the error message is very confusing in that case...
     msg = C_(
         "brush group delete",
         u"Could not delete group \u201C{group_name}\u201D.\n"
         u"Some special groups cannot be deleted.",
     ).format(
         group_name = name,
     )
     dialogs.error(self, msg)
Example #19
0
 def _update_charts_setting(self, widget, state):
     """
         Update show charts setting
         @param widget as Gtk.Switch
         @param state as bool
     """
     if Lp().settings.get_value('network-access'):
         GLib.idle_add(Lp().window.add_remove_from,
                       (Type.CHARTS, _("The charts"), ""),
                       True,
                       state)
     if state:
         if Lp().charts is None:
             from lollypop.charts import Charts
             Lp().charts = Charts()
         if get_network_available():
             Lp().charts.start()
         elif Lp().notify is not None:
             Lp().notify.send(_("The charts"),
                              _("Network access disabled"))
     else:
         Lp().charts.stop()
         Lp().scanner.clean_charts()
     Lp().settings.set_value('show-charts',
                             GLib.Variant('b', state))
Example #20
0
    def __procesar_y_guardar(self):
        if self.archivo:
            if os.path.exists(self.archivo):
                if not os.access(self.archivo, os.W_OK):
                    print "No tienes permiso para guardar:", self.archivo
                    return False
        _buffer = self.get_buffer()
        inicio, fin = _buffer.get_bounds()
        texto = _buffer.get_text(inicio, fin, 0)

        # Para devolver el scroll a donde estaba.
        textmark = _buffer.get_insert()
        textiter = _buffer.get_iter_at_mark(textmark)
        _id = textiter.get_line()

        # FIXME: Falta que  al guardar archivos py establezca tipo y
        # codificación de los archivos.
        texto = self.__limpiar_codigo(texto)
        archivo = open(self.archivo, "w")
        archivo.write(texto)
        archivo.close()
        self.set_archivo(self.archivo)

        # Devolver el scroll a donde estaba.
        linea_iter = self.get_buffer().get_iter_at_line(_id)
        GLib.idle_add(self.scroll_to_iter, linea_iter, 0.1, 1, 1, 0.1)
Example #21
0
 def _on_changes_pending(self, data=None):
     if (self._init
             and not self.header_bar._selectionMode):
         self.model.clear()
         self._offset = 0
         GLib.idle_add(self.populate)
         grilo.changes_pending['Songs'] = False
Example #22
0
 def _play_search(self, object_id=None, is_track=True):
     """
         Play tracks based on search
         @param started object id as int
         @param is track as bool
     """
     sql = Lp.db.get_cursor()
     tracks = []
     track_id = None
     for child in self._view.get_children():
         if child.is_track:
             tracks.append(Track(child.id))
         else:
             album_tracks = Lp.albums.get_tracks(child.id, None, sql)
             if not is_track and child.id == object_id and album_tracks:
                 track_id = album_tracks[0]
             for tid in album_tracks:
                 tracks.append(Track(tid))
     if tracks:
         GLib.idle_add(Lp.player.set_party, False)
         if object_id is not None and is_track:
             track_id = object_id
         elif track_id is None:
             track_id = tracks[0].id
         GLib.idle_add(self._set_user_playlist, tracks, track_id)
     sql.close()
Example #23
0
 def _clear(self, results):
     """
         Remove row not existing in view, thread safe
     """
     for child in self._view.get_children():
         if not results or not child.exists(results):
             GLib.idle_add(child.destroy)
Example #24
0
 def _move_down_group(self, groupindex):
     """
     move down pressed on the group
     If on a family group, allow to reorder the order of families
     as connected to this person.
     """
     ref = self.get_selected()
     if not ref or ref[1]:
         return
     if ref[0] == 0:
         #person events, cannot move down
         return
     if ref[0] == len(self._groups)-1:
         #cannot move down, already last family
         return
     #change family list and rebuild the tabpage
     index = ref[0] -1
     flist = self.obj.get_family_handle_list()
     handle = flist.pop(index)
     flist.insert(index+1, handle)
     self.changed = True
     self.rebuild()
     # select the row
     # New index is index+1 but for path, add another 1 for person events.
     path = (index + 2,)
     self.tree.get_selection().select_path(path)
     GLib.idle_add(self.tree.scroll_to_cell, path)
Example #25
0
 def append_safe(self, box, timeout=None):
     """
     Thread-safe version of append().
     """
     def _append():
         self.append(box, timeout=timeout)
     GLib.idle_add(_append)
Example #26
0
    def _really_do_filtering(self):
        sql = Lp.db.get_cursor()
        results = []
        albums = []

        searched = self._text_entry.get_text()

        tracks_non_aartist = []

        # Get all albums for all artists and non aartist tracks
        for artist_id in Lp.artists.search(searched, sql):
            for album_id in Lp.albums.get_ids(artist_id, None, sql):
                if (album_id, artist_id) not in albums:
                    albums.append((album_id, artist_id))
            for track_id, track_name in Lp.tracks.get_as_non_aartist(artist_id,
                                                                     sql):
                tracks_non_aartist.append((track_id, track_name))

        albums += Lp.albums.search(searched, sql)

        for album_id, artist_id in albums:
            search_obj = SearchObject()
            search_obj.artist = Lp.artists.get_name(artist_id, sql)
            search_obj.title = Lp.albums.get_name(album_id, sql)
            search_obj.count = Lp.albums.get_count(album_id, None, sql)
            search_obj.id = album_id
            search_obj.album_id = album_id
            results.append(search_obj)

        for track_id, track_name in Lp.tracks.search(searched, sql) +\
                tracks_non_aartist:
            search_obj = SearchObject()
            search_obj.title = track_name
            search_obj.id = track_id
            search_obj.album_id = Lp.tracks.get_album_id(track_id, sql)
            search_obj.is_track = True

            album_artist_id = Lp.albums.get_artist_id(search_obj.album_id,
                                                      sql)
            artist_name = ""
            if album_artist_id != Type.COMPILATIONS:
                artist_name = Lp.albums.get_artist_name(
                    search_obj.album_id, sql) + ", "
            for artist_id in Lp.tracks.get_artist_ids(track_id, sql):
                if artist_id != album_artist_id:
                    artist_name += translate_artist_name(
                        Lp.artists.get_name(artist_id, sql)) + ", "

            search_obj.artist = artist_name[:-2]

            results.append(search_obj)

        if not self._stop_thread:
            self._clear(results)
            GLib.idle_add(self._add_rows, results)
        else:
            self._in_thread = False
            self._stop_thread = False

        sql.close()
Example #27
0
    def on_transport(self, beacon):
        self.change_status(Garmin.Status.CONNECTED)

        while True:
            if self.timeout_source:
                self.timeout_source = None
                return

            while self.funcs:
                f, cb, args = self.funcs.pop(0)
                ret = f(self, *args)
                # run in ui thread
                GLib.idle_add(lambda: cb(ret))

            # we've run out of things to do for now. set a timer so we don't
            # disconnect immediately.

            # use a new context as we don't want to get mixed up with the
            # other mainloop currently running
            context = GLib.MainContext()
            self.loop = GLib.MainLoop(context)
            def timeout_cb(data=None):
                self.loop.quit()
                self.loop = None
            self.timeout_source = GLib.timeout_source_new_seconds(5)
            self.timeout_source.set_callback(timeout_cb)
            self.timeout_source.attach(context)
            self.loop.run()
Example #28
0
 def _add_rows(self, results):
     """
         Add a rows recursively
         @param results as array of SearchObject
     """
     if results:
         result = results.pop(0)
         if not self._exists(result):
             search_row = SearchRow(self._parent)
             if result.count != -1:
                 result.title += " (%s)" % result.count
             search_row.set_text(result.artist, result.title)
             search_row.set_cover(Lp.art.get_album(result.album_id,
                                  ArtSize.MEDIUM*self.get_scale_factor()))
             search_row.id = result.id
             search_row.is_track = result.is_track
             self._view.add(search_row)
         if self._stop_thread:
             self._in_thread = False
             self._stop_thread = False
         else:
             GLib.idle_add(self._add_rows, results)
     else:
         self._in_thread = False
         self._stop_thread = False
Example #29
0
	def cb_process_exit(self, process, *a):
		""" Called after daemon binary outputs version and exits """
		from syncthing_gtk.app import MIN_ST_VERSION
		bin_path = process.get_commandline()[0]
		if compare_version(self.version_string, MIN_ST_VERSION):
			# Daemon binary exists, is executable and meets
			# version requirements. That's good, btw.
			self.parent.config["syncthing_binary"] = bin_path
			if not can_upgrade_binary(bin_path):
				# Don't try enable auto-update if binary is in
				# non-writable location (auto-update is enabled
				# by default on Windows only)
				self.parent.config["st_autoupdate"] = False
			self.parent.set_page_complete(self, True)
			self.label.set_markup(
					_("<b>Syncthing daemon binary found.</b>") +
					"\n\n" +
					_("Binary path:") + " " + bin_path + "\n" +
					_("Version:") + " " + self.version_string
				)
		else:
			# Found daemon binary too old to be ussable.
			# Just ignore it and try to find better one.
			log.info("Binary in %s is too old", bin_path)
			self.ignored_version = self.version_string
			GLib.idle_add(self.search)
Example #30
0
 def _on_bus_eos(self, bus, message):
     if self.nextTrack:
         GLib.idle_add(self._on_glib_idle)
     elif (self.repeat == RepeatType.NONE):
         self.stop()
         self.playBtn.set_image(self._playImage)
         self.progressScale.set_value(0)
         self.progressScale.set_sensitive(False)
         if self.playlist is not None:
             currentTrack = self.playlist.get_path(self.playlist.get_iter_first())
             if currentTrack:
                 self.currentTrack = Gtk.TreeRowReference.new(self.playlist, currentTrack)
                 self.currentTrackUri = self.playlist.get_value(
                     self.playlist.get_iter(self.currentTrack.get_path()), 5).get_url()
             else:
                 self.currentTrack = None
             self.load(self.get_current_media())
         self.emit('playback-status-changed')
     else:
         # Stop playback
         self.stop()
         self.playBtn.set_image(self._playImage)
         self.progressScale.set_value(0)
         self.progressScale.set_sensitive(False)
         self.emit('playback-status-changed')
Example #31
0
 async def on_socket_raw_receive(self, *args, **kwargs):
     GLib.idle_add(self.forward_event, "on_socket_raw_receive", *args,
                   **kwargs)
Example #32
0
 def _startThumbnailingWhenIdle(self):
     self.debug('Waiting for UI to become idle for: %s',
                filename_from_uri(self.uri))
     GLib.idle_add(self._startThumbnailing, priority=GLib.PRIORITY_LOW)
Example #33
0
    def do_post_message(self, message):
        if message.type == Gst.MessageType.ELEMENT and \
                message.src == self.gdkpixbufsink:
            GLib.idle_add(self.__addThumbnail, message)

        return Gst.Bin.do_post_message(self, message)
Example #34
0
 def _request_slot(self, file):
     GLib.idle_add(self.raise_progress_event, 'request', file)
     iq = self._build_request(file)
     log.info("Sending request for slot")
     self._con.connection.SendAndCallForResponse(iq, self._received_slot,
                                                 {'file': file})
Example #35
0
 async def on_raw_message_delete(self, *args, **kwargs):
     GLib.idle_add(self.forward_event, "on_raw_message_delete", *args,
                   **kwargs)
Example #36
0
 async def on_typing(self, *args, **kwargs):
     GLib.idle_add(self.forward_event, "on_typing", *args, **kwargs)
Example #37
0
 async def on_socket_raw_send(self, *args, **kwargs):
     GLib.idle_add(self.forward_event, "on_socket_raw_send", *args,
                   **kwargs)
Example #38
0
 async def on_shard_resumed(self, *args, **kwargs):
     GLib.idle_add(self.forward_event, "on_shard_resumed", *args, **kwargs)
Example #39
0
 async def on_shard_disconnect(self, *args, **kwargs):
     GLib.idle_add(self.forward_event, "on_shard_disconnect", *args,
                   **kwargs)
Example #40
0
 async def on_error(self, event, *args, **kwargs):
     GLib.idle_add(self.forward_event, "on_error", *args, **kwargs)
Example #41
0
 async def on_group_remove(self, *args, **kwargs):
     GLib.idle_add(self.forward_event, "on_group_remove", *args, **kwargs)
Example #42
0
 async def on_ready(self, *args, **kwargs):
     GLib.idle_add(self.forward_event, "on_ready", *args, **kwargs)
Example #43
0
 async def on_invite_delete(self, *args, **kwargs):
     GLib.idle_add(self.forward_event, "on_invite_delete", *args, **kwargs)
Example #44
0
 async def on_relationship_update(self, *args, **kwargs):
     GLib.idle_add(self.forward_event, "on_relationship_update", *args,
                   **kwargs)
Example #45
0
 async def on_voice_state_update(self, *args, **kwargs):
     GLib.idle_add(self.forward_event, "on_voice_state_update", *args,
                   **kwargs)
Example #46
0
 async def on_group_join(self, *args, **kwargs):
     GLib.idle_add(self.forward_event, "on_group_join", *args, **kwargs)
Example #47
0
 async def on_guild_emojis_update(self, *args, **kwargs):
     GLib.idle_add(self.forward_event, "on_guild_emojis_update", *args,
                   **kwargs)
Example #48
0
 async def on_member_unban(self, *args, **kwargs):
     GLib.idle_add(self.forward_event, "on_member_unban", *args, **kwargs)
Example #49
0
 async def on_user_update(self, *args, **kwargs):
     GLib.idle_add(self.forward_event, "on_user_update", *args, **kwargs)
Example #50
0
 async def on_guild_unavailable(self, *args, **kwargs):
     GLib.idle_add(self.forward_event, "on_guild_unavailable", *args,
                   **kwargs)
Example #51
0
 async def on_private_channel_pins_update(self, *args, **kwargs):
     GLib.idle_add(self.forward_event, "on_private_channel_pins_update",
                   *args, **kwargs)
Example #52
0
 async def on_guild_role_create(self, *args, **kwargs):
     GLib.idle_add(self.forward_event, "on_guild_role_create", *args,
                   **kwargs)
Example #53
0
 async def on_raw_reaction_remove(self, *args, **kwargs):
     GLib.idle_add(self.forward_event, "on_raw_reaction_remove", *args,
                   **kwargs)
Example #54
0
 async def on_guild_channel_delete(self, *args, **kwargs):
     GLib.idle_add(self.forward_event, "on_guild_channel_delete", *args,
                   **kwargs)
Example #55
0
    def __init__(self, filenames, state_dirs, version, fullscreen=False):
        """Construct, but do not run.

        :param list filenames: The list of files to load (unicode required)
        :param StateDirs state_dirs: static special paths.
        :param unicode version: Version string for the about dialog.
        :param bool fullscreen: Go fullscreen after starting.

        Only the first filename listed will be loaded. If no files are
        listed, the autosave recovery dialog may be shown when the
        application starts up.

        """
        assert Application._INSTANCE is None
        super(Application, self).__init__()
        Application._INSTANCE = self

        self.state_dirs = state_dirs  #: Static special paths: see StateDirs

        self.version = version  #: version string for the app.

        # Create the user's config directory and any needed R/W data
        # storage areas.
        for basedir in [state_dirs.user_config, state_dirs.user_data]:
            if not os.path.isdir(basedir):
                os.makedirs(basedir)
                logger.info('Created basedir %r', basedir)
        for datasubdir in [u'backgrounds', u'brushes', u'scratchpads']:
            datadir = os.path.join(state_dirs.user_data, datasubdir)
            if not os.path.isdir(datadir):
                os.mkdir(datadir)
                logger.info('Created data subdir %r', datadir)

        _init_icons(state_dirs.app_icons)

        # Core actions and menu structure
        resources_xml = join(self.datapath, "gui", "resources.xml")
        self.builder = Gtk.Builder()
        self.builder.set_translation_domain("mypaint")
        self.builder.add_from_file(resources_xml)

        self.ui_manager = self.builder.get_object("app_ui_manager")
        signal_callback_objs = [self]

        Gdk.set_program_class('MyPaint')

        self.pixmaps = PixbufDirectory(join(state_dirs.app_data, u'pixmaps'))
        self.cursor_color_picker = Gdk.Cursor.new_from_pixbuf(
            Gdk.Display.get_default(),
            self.pixmaps.cursor_color_picker,
            3,
            15,
        )
        self.cursors = gui.cursor.CustomCursorMaker(self)

        # unmanaged main brush; always the same instance (we can attach settings_observers)
        # this brush is where temporary changes (color, size...) happen
        self.brush = brush.BrushInfo()
        self.brush.load_defaults()

        # Global pressure mapping function, ignored unless set
        self.pressure_mapping = None

        self.preferences = {}
        self.load_settings()

        # Keyboard manager
        self.kbm = keyboard.KeyboardManager(self)

        # File I/O
        self.filehandler = filehandling.FileHandler(self)

        # Picking grabs
        self.context_grab = gui.picker.ContextPickingGrabPresenter()
        self.context_grab.app = self
        self.color_grab = gui.picker.ColorPickingGrabPresenter()
        self.color_grab.app = self

        # Load the main interface
        mypaint_main_xml = join(self.datapath, "gui", "mypaint.glade")
        self.builder.add_from_file(mypaint_main_xml)

        # Main drawing window
        self.drawWindow = self.builder.get_object("drawwindow")
        signal_callback_objs.append(self.drawWindow)

        # Workspace widget. Manages layout of toolwindows, and autohide in
        # fullscreen.
        workspace = self.builder.get_object("app_workspace")
        workspace.build_from_layout(self.preferences["workspace.layout"])
        workspace.floating_window_created += self._floating_window_created_cb
        fs_autohide_action = self.builder.get_object("FullscreenAutohide")
        fs_autohide_action.set_active(workspace.autohide_enabled)
        self.workspace = workspace

        # Working document: viewer widget
        app_canvas = self.builder.get_object("app_canvas")

        # Working document: model and controller
        model = lib.document.Document(self.brush)
        self.doc = document.Document(self, app_canvas, model)
        app_canvas.set_model(model)

        signal_callback_objs.append(self.doc)
        signal_callback_objs.append(self.doc.modes)

        self.scratchpad_filename = ""
        scratchpad_model = lib.document.Document(self.brush,
                                                 painting_only=True)
        scratchpad_tdw = tileddrawwidget.TiledDrawWidget()
        scratchpad_tdw.set_model(scratchpad_model)
        self.scratchpad_doc = document.Document(self, scratchpad_tdw,
                                                scratchpad_model)
        self.brushmanager = brushmanager.BrushManager(
            join(self.state_dirs.app_data, 'brushes'),
            join(self.state_dirs.user_data, 'brushes'),
            self,
        )
        signal_callback_objs.append(self.filehandler)
        self.brushmodifier = brushmodifier.BrushModifier(self)
        signal_callback_objs.append(self.brushmodifier)
        self.line_mode_settings = linemode.LineModeSettings(self)

        # Button press mapping
        self.button_mapping = ButtonMapping()

        # Monitors pluggings and uses of input device, configures them,
        # and switches between device-specific brushes.
        self.device_monitor = gui.device.Monitor(self)

        if not self.preferences.get("scratchpad.last_opened_scratchpad", None):
            self.preferences[
                "scratchpad.last_opened_scratchpad"] = self.filehandler.get_scratchpad_autosave(
                )
        self.scratchpad_filename = self.preferences[
            "scratchpad.last_opened_scratchpad"]

        self.brush_color_manager = BrushColorManager(self)
        self.brush_color_manager.set_picker_cursor(self.cursor_color_picker)
        self.brush_color_manager.set_data_path(self.datapath)

        #: Mapping of setting cname to a GtkAdjustment which controls the base
        #: value of that setting for the app's current brush.
        self.brush_adjustment = {}
        self.init_brush_adjustments()

        # Connect signals defined in resources.xml
        callback_finder = CallbackFinder(signal_callback_objs)
        self.builder.connect_signals(callback_finder)

        self.kbm.start_listening()
        self.filehandler.doc = self.doc
        self.filehandler.filename = None
        Gtk.AccelMap.load(join(self.user_confpath, 'accelmap.conf'))

        # Load the default background image
        self.doc.reset_background()

        # Non-dockable subwindows
        # Loading is deferred as late as possible
        self._subwindow_classes = {
            # action-name: action-class
            "BackgroundWindow": backgroundwindow.BackgroundWindow,
            "BrushEditorWindow": brusheditor.BrushEditorWindow,
            "PreferencesWindow": preferenceswindow.PreferencesWindow,
            "InputTestWindow": inputtestwindow.InputTestWindow,
            "BrushIconEditorWindow": brushiconeditor.BrushIconEditorWindow,
        }
        self._subwindows = {}

        # Statusbar init
        statusbar = self.builder.get_object("app_statusbar")
        self.statusbar = statusbar
        context_id = statusbar.get_context_id("transient-message")
        self._transient_msg_context_id = context_id
        self._transient_msg_remove_timeout_id = None

        # Profiling & debug stuff
        self.profiler = gui.profiling.Profiler()

        # Show main UI.
        self.drawWindow.show_all()
        GLib.idle_add(self._at_application_start, filenames, fullscreen)
Example #56
0
 async def on_raw_reaction_clear_emoji(self, *args, **kwargs):
     GLib.idle_add(self.forward_event, "on_raw_reaction_clear_emoji", *args,
                   **kwargs)
Example #57
0
 def _on_changes_pending(self, data=None):
     if (self._init and not self._header_bar.selection_mode):
         self._offset = 0
         GLib.idle_add(self.populate)
         grilo.changes_pending['Albums'] = False
Example #58
0
 async def on_message_edit(self, *args, **kwargs):
     GLib.idle_add(self.forward_event, "on_message_edit", *args, **kwargs)
Example #59
0
 def game_changed(cls, model, ply):
     GLib.idle_add(cls.fen_changed)
Example #60
0
    def __init__(self, builder: Gtk.Builder, window: Gtk.Window,
                 settings: SkyTempleSettingsStore):
        self.builder = builder
        self._window = window
        self.__class__._instance = self

        self.settings = settings
        self.recent_files = self.settings.get_recent_files()

        self._load_support_images()

        # Created on demand
        self._loading_dialog: Gtk.Dialog
        self._main_item_list: Gtk.TreeView
        self._main_item_filter: Gtk.TreeModel
        self._last_selected_view_model: Optional[Gtk.TreeModel] = None
        self._last_selected_view_iter: Optional[Gtk.TreeIter] = None

        self._recent_files_store: Gtk.ListStore = self.builder.get_object(
            'recent_files_store')
        self._item_store: Gtk.TreeStore = builder.get_object('item_store')
        self._editor_stack: Gtk.Stack = builder.get_object('editor_stack')

        builder.connect_signals(self)
        window.connect("destroy", self.on_destroy)

        self._search_text: Optional[str] = None
        self._current_view_module: Optional[AbstractModule] = None
        self._current_view_controller: Optional[AbstractController] = None
        self._current_view_controller_class: Optional[
            Type[AbstractController]] = None
        self._current_view_item_id: Optional[int] = None
        self._resize_timeout_id: Optional[int] = None
        self._loaded_map_bg_module: Optional['MapBgModule'] = None
        self._current_breadcrumbs: List[str] = []
        self._after_save_action = None
        self.csd_enabled = self.settings.csd_enabled()

        if not sys.platform.startswith('darwin'):
            # Don't load the window position on macOS to prevent
            # the window from getting stuck on a disconnected screen
            self._load_position_and_size()

        self._configure_csd()
        self._load_icon()
        self._load_recent_files()
        self._connect_item_views()
        self._configure_error_view()
        self._check_for_updates()
        self._check_for_banner()
        self._check_for_native()

        self._debugger_manager = DebuggerManager()

        self.tilequant_controller = TilequantController(
            self._window, self.builder)
        self.settings_controller = SettingsController(self._window,
                                                      self.builder,
                                                      self.settings)

        GLib.idle_add(lambda: self._ask_for_sentry())