Beispiel #1
0
    def close_bluemindo(self, window, quit=True):
        """This function is called when the Bluemindo's main window is
        closed."""
        # Backup window width, height and position
        if window is not None and window.get_properties('visible')[0]:
            width = window.get_size()[0]
            height = window.get_size()[1]
            x = window.get_position()[0]
            y = window.get_position()[1]

            self.userconf.update_key('Window', 'width', str(width))
            self.userconf.update_key('Window', 'height', str(height))
            self.userconf.update_key('Window', 'x', str(x))
            self.userconf.update_key('Window', 'y', str(y))

        # Delete the socket file and quit GTK
        if quit:
            SOCKET_NAME = '/tmp/bluemindo'
            if exists(SOCKET_NAME):
                remove(SOCKET_NAME)

            pid_filename = join(self.datadir, 'pid')
            if isfile(pid_filename):
                remove(pid_filename)

            current_playing = join(self.datadir, 'current-playing')
            if isfile(current_playing):
                remove(current_playing)

            print('The dolphin has plunge!')
            idle_add(gtk_main_quit)
        # Hide window
        else:
            if window.get_properties('visible')[0]:
                window.hide()
Beispiel #2
0
    def on_new_operation(self, transaction, operation, progress):
        package = self.get_package_from_operation(operation)

        # Don't try and update UI if there is no pacakge (probably a runtime)
        if package:
            idle_add(package.start_spinner)
            idle_add(package.set_status_text, 'Installing')
Beispiel #3
0
 def _validar_configuracion(self, mesa=None, pin=None,
                            con_acta_apertura=False, datos_tag=''):
     """ Recibe el numero de mesa y el pin de la pantalla de configuración y
         verifica que sea correcto.
         Si es *con_acta_apertura* se carga la mesa automaticamente y con
         datos tag carga los datos del presidente
         Si es correcto configura la mesa para dejarla operativa y pasa al
         menú de administración, en otro caso presenta la pantalla
         principal.
     """
     if mesa is not None:
         self._mesa = mesa
         # Le seteo el atributo abierta si la configuracion de la mesa fue
         # con el acta de apertura
         self._configurar_mesa()
         if con_acta_apertura:
             apertura = Apertura.desde_tag(datos_tag)
             self.sesion.apertura = apertura
         self.estado = E_CONFIGURADA
         realizar_apertura = self.config("realizar_apertura")
         self.ret_code = SUBMODULO_DATOS_APERTURA if realizar_apertura \
             else MODULO_MENU
         if self.rampa.tiene_papel:
             self.rampa.expulsar_boleta()
         idle_add(self.quit)
     else:
         self.estado = E_INICIAL
         self._cargar_ui_web()
         self.ventana.show_all()
         self._pantalla_principal()
         self.controlador.msg_mesaypin_incorrecto()
Beispiel #4
0
    def _error(self):
        """Lanza el error tanto en la interfaz visual como en la auditiva."""
        ModuloSufragio._error(self)

        def _locutar_error():
            """Ejecuta el sonido del error."""
            self.controlador.sesion.locutor.shutup()
            frases = [Speech.one("error_almacenado").texto,
                      Speech.one("error_almacenado_2").texto]
            self.sesion.locutor.decir(frases)
        idle_add(_locutar_error)
Beispiel #5
0
    def _on_create_torrent_progress(self, value, num_pieces):
        percent = value / num_pieces

        def update_pbar_with_gobject(percent):
            pbar = self.builder.get_object('progressbar')
            pbar.set_text('%.2f%%' % (percent * 100))
            pbar.set_fraction(percent)
            return False

        if percent >= 0 and percent <= 1.0:
            # Make sure there are no threads race conditions that can
            # crash the UI while updating it.
            idle_add(update_pbar_with_gobject, percent)
        def handle_connection(source, condition):
            """This is the UNIX socket server."""
            datagram = server.recv(1024)
            argv = loads(datagram)
            usercommand = argv[1]

            # PlayPause, Play or Pause
            if usercommand in ('--playpause', '--play', '--pause'):
                idle_add(extensions.load_event, 'OnPlayPressed')

            # Stop
            elif usercommand == '--stop':
                idle_add(extensions.load_event, 'OnStopPressed')

            # Next
            elif usercommand == '--next':
                idle_add(extensions.load_event, 'OnNextPressed')

            # Previous
            elif usercommand == '--previous':
                idle_add(extensions.load_event, 'OnPreviousPressed')

            # Quit Bluemindo
            elif usercommand in ('--quit', '--plunge'):
                functions.close_bluemindo(None)

            # The command isn't handled by any action
            else:
                print ('Received unknown event `%s`!' % usercommand)

            return True
Beispiel #7
0
    def _error(self):
        """Lanza el error tanto en la interfaz visual como en la auditiva."""
        ModuloSufragio._error(self)

        def _locutar_error():
            """Ejecuta el sonido del error."""
            self.controlador.sesion.locutor.shutup()
            frases = [
                Speech.one("error_almacenado").texto,
                Speech.one("error_almacenado_2").texto
            ]
            self.sesion.locutor.decir(frases)

        idle_add(_locutar_error)
Beispiel #8
0
    def salir(self):
        """Sale del modulo o va al menu de capacitacion, segun el contexto."""
        if self.controlador.nombre == MODULO_CAPACITACION:
            if self._mesa_anterior:
                self.sesion.mesa = self._mesa_anterior
            self.rampa.expulsar_boleta()
            self._salir()
        else:
            self._descargar_ui_web()
            self.controlador = ControllerCapac(self)
            self.web_template = "capacitacion"

            def _recargar():
                self._cargar_ui_web()
                self.ventana.show_all()
                self.rampa = RampaCapacitacion(self)

            idle_add(_recargar)
Beispiel #9
0
    def on_operation_done(self, transaction, operation, commit, result):
        package = self.get_package_from_operation(operation)

        # Don't try and update UI if there is no pacakge (probably a runtime)
        if package:
            idle_add(package.stop_spinner)
            idle_add(package.set_status_text, "Flatpak installed")
            idle_add(package.set_installed_status, 'installed')
Beispiel #10
0
    def on_operation_error(self, transaction, operation, error, details):
        package = self.get_package_from_operation(operation)
        error_text = f"Error: {error.message}"

        # Don't try and update UI if there is no pacakge (probably a runtime)
        if package:
            idle_add(package.stop_spinner)
            idle_add(package.set_status_text, "Error installing")
            idle_add(package.set_installed_status, error_text)
 def Previous(self):
     idle_add(extensions.load_event, 'OnPreviousPressed')
 def Next(self):
     idle_add(extensions.load_event, 'OnNextPressed')
Beispiel #13
0
 def apagar(self):
     """ Sale del módulo de inicio y envia la orden de apagado """
     self.ret_code = SHUTDOWN
     idle_add(self.quit)
Beispiel #14
0
 def callback(*args):
   idle_add(func, *args)
Beispiel #15
0
 def callback(*args):
     idle_add(func, *args)
Beispiel #16
0
 def emit(self, *args):
     """"""
     idle_add(GObject.emit, self, *args)
Beispiel #17
0
 def emit(self, *args):
     """"""
     idle_add(GObject.emit, self, *args)
Beispiel #18
0
    def run(self):
        pkg_list = []
        success = []

        for package in self.packages:
            pkg_list.append(package.deb_package)
            idle_add(package.set_status_text, 'Waiting')

        print(f'Removing debs: {pkg_list}')

        # Keep trying to obtain a lock and remove the packages
        while True:
            print('Waiting for package manager lock')
            idle_add(
                self.packages[0].set_status_text,
                'Waiting for the package system lock'
            )
            lock = privileged_object.obtain_lock()
            if lock:
                break
            print('Could not obtain lock, trying again in 5 seconds')
            time.sleep(5)
        
        # Most of the following code is contained within try-except blocks 
        # because we need to be 100% sure that we release the package manager
        # lock at the end of the process, so we cannot allow a failure from the
        # package system to propagate outwards and prevent release of the lock.
        # debugging information can be obtained by running the dbus service from 
        # a root terminal and observing the output. 
        try:
            print('Opening cache')
            privileged_object.open_cache()
        
            for package in self.packages:
                print(f'Removing {package.deb_package}')
                idle_add(package.set_status_text, f'Removing {package.deb_package}')
                removed = privileged_object.remove_package(package.deb_package)
                if removed:
                    print(f'Marked {removed} removed.')
                    success.append(removed)
        except Exception as e:
            print(f'Something went wrong: {e}')
            success = []
        
        try:
            print('Committing changes and closing cache')
            privileged_object.commit_changes()
            privileged_object.close_cache()
        except Exception as e:
            print(f'Something went wrong: {e}')
            success = []

        # Don't exit until the lock is released.
        while True:
            try:
                print('Releasing package manager lock')
                idle_add(
                    self.packages[0].set_status_text,
                    'Releasing Package Manager Lock'
                )
                unlock = privileged_object.release_lock()
                if unlock:
                    break
            except Exception as e:
                print(e)
                continue
                
        # idle_add(self.window.quit_app)
        for package in self.packages:
            if package.deb_package in success:
                idle_add(package.set_removed, True)
        
        idle_add(self.window.show_summary_page)
Beispiel #19
0
    def run(self):
        idle_add(self.packages[0].set_status_text, 'Updating Appstream Data')
        print("Repairing Flatpak installation")
        # Sometimes this appears to cause issues, so we need to do a quick
        # repair first to ensure that the local installation is consistent.
        # See https://github.com/flatpak/flatpak/issues/4095
        subprocess.run(['flatpak', 'repair', '--user'])

        print('Updating Appstream Data')
        # If the appstream data is out of date, it can cause problems installing
        # some applications. So we update it first.
        self.user.update_appstream_full_sync(self.flathub.get_name())

        print('Installing Flatpaks...')
        idle_add(self.packages[0].set_status_text, 'Waiting')

        # We use a transaction to get error details and to install dependencies
        transaction = Flatpak.Transaction.new_for_installation(self.user)
        transaction.connect('new_operation', self.on_new_operation)
        transaction.connect('operation-done', self.on_operation_done)
        transaction.connect('operation-error', self.on_operation_error)

        for package in self.packages:
            print(f'Installing {package.name} flatpak {package.app_id}.')
            remote_ref = self.user.fetch_remote_ref_sync(
                self.flathub.get_name(), Flatpak.RefKind.APP, package.app_id,
                None, 'stable')
            try:
                transaction.add_install(self.flathub.get_name(),
                                        remote_ref.format_ref())
                idle_add(package.set_status_text, 'Waiting')
            except GLib.Error as err:
                idle_add(package.stop_spinner)

                # Package is already installed, inform the user
                if 'is already installed' in err.message:
                    idle_add(package.set_status_text, 'Already Installed')
                    idle_add(package.set_installed_status, 'already installed')

                # Or there was some other error, let the user know
                else:
                    idle_add(package.set_status_text, 'Error installing')
                    idle_add(package.set_installed_status, err.message)

        transaction.run()
        idle_add(self.window.show_apt_page)
 def Quit(self):
     idle_add(functions.close_bluemindo, None)
Beispiel #21
0
 def apagar(self):
     """ Sale del módulo de inicio y envia la orden de apagado """
     self.ret_code = SHUTDOWN
     idle_add(self.quit)
 def Pause(self):
     idle_add(extensions.load_event, 'OnPlayPressed')
Beispiel #23
0
            def do_scan():
                # Freeze user interface
                gldfile = join(self.functions.datadir, 'glade', 'loading.ui')
                win = gtk_builder()
                win.set_translation_domain('bluemindo')
                win.add_from_file(gldfile)
                box_content = win.get_object('box1')

                # Create an interface to help the user waiting for the job
                bluemindo = join(self.functions.datadir, 'image',
                                 'bluemindo.png')
                img = win.get_object('image')
                cover_px = Pixbuf.new_from_file(bluemindo)
                idle_add(img.set_from_pixbuf, cover_px)

                idle_add(
                    win.get_object('label').set_markup,
                    '<span size="x-large"><b>' +
                    _('Reloading music database.') + '</b></span>')

                idle_add(self.widgets[0][2].set_sensitive, False)
                idle_add(self.widgets[0][3].set_sensitive, False)
                idle_add(self.widgets[0][5].set_sensitive, False)
                idle_add(self.widgets[0][6].set_sensitive, False)
                idle_add(self.widgets[0][7].set_sensitive, False)
                idle_add(self.widgets[0][8].set_sensitive, False)

                idle_add(self.widgets[1].get_object('box1').add, box_content)

                lbl = win.get_object('label_info')
                idle_add(lbl.set_text,
                         _('Starting… Prepares to search for new files.'))

                # Update GUI
                box_content.show_all()
                self.widgets[1].get_object('box2').hide()

                # Do the scanning
                pb = win.get_object('progressbar')
                musicdb.scan(lbl, pb)

                # Show original GUI
                idle_add(self.widgets[0][2].set_sensitive, True)
                idle_add(self.widgets[0][3].set_sensitive, True)
                idle_add(box_content.hide)
                idle_add(self.widgets[1].get_object('box2').show_all)
                idle_add(self.create_view)
 def Stop(self):
     idle_add(extensions.load_event, 'OnStopPressed')
Beispiel #25
0
 def song_nearly_ended(self, *args):
     idle_add(self.next_pressed, True)
    def do_scan(self, wdg=None):
        """This function scan the music directory."""
        songs = list()
        songs_filename = list()
        songs_artists = list()
        songs_albums = list()
        nb_song = 0
        fileregxp = re_compile('.+\.(flac|ogg|oga|mp3)$')

        # Walk in the music folder
        folder = self.folder

        song_files = list()
        for (dir_, rep, files) in walk(folder):
            for file_ in files:
                if fileregxp.match(file_):
                    nb_song += 1
                    song_files.append(join(dir_, file_))

        if wdg is not None:
            idle_add(wdg[0].set_text, _('Found %d songs.' % len(song_files)))
            idle_add(wdg[1].set_fraction, 0)

        id_song = 0
        ok_song = 0
        for song in song_files:
            id_song += 1

            try:
                exif = TagLibFile(song)
                if all(k in exif.tags.keys()
                       for k in ('TITLE', 'ARTIST', 'ALBUM', 'TRACKNUMBER')):
                    ok_song += 1
                    filename = song

                    title = exif.tags['TITLE'][0]
                    artist = exif.tags['ARTIST'][0]
                    album = exif.tags['ALBUM'][0]
                    track = exif.tags['TRACKNUMBER'][0]

                    length = exif.length

                    if 'COMMENT' in exif.tags:
                        try:
                            comment = exif.tags['COMMENT'][0]
                        except IndexError:
                            comment = ''
                    else:
                        comment = ''

                    if 'GENRE' in exif.tags:
                        try:
                            genre = exif.tags['GENRE'][0]
                        except IndexError:
                            genre = ''
                    else:
                        genre = ''

                    if 'DATE' in exif.tags:
                        try:
                            year = exif.tags['DATE'][0]
                        except IndexError:
                            year = ''
                    else:
                        year = ''

                    if wdg is not None and id_song % 5:
                        idle_add(wdg[1].set_fraction,
                                 float(id_song) / float(nb_song))
                        idle_add(wdg[0].set_text,
                                 _('Added %d songs.' % id_song))

                    songs_filename.append(filename)
                    songs_artists.append(artist)
                    songs_albums.append(album)

                    songs.append((title, artist, album, comment, genre, year,
                                  track, length, filename))
                else:
                    raise OSError
            except OSError:
                idle_add(print, '[ERROR] Unable to import %s' % song)

        if wdg is not None:
            idle_add(
                wdg[0].set_text,
                _('Metadata retrieved for %d songs. Updating database…' %
                  len(songs)))

        idle_add(
            print,
            '[RELOAD] Imported %d songs from %d founded.' % (ok_song, id_song))

        # Serialize songs
        sqlite = SQLite()
        sqlite.execute('delete from songs')
        sqlite.executemany(
            'insert into songs (title, artist, album, '
            'comment, genre, year, track, length, filename) '
            'values (?, ?, ?, ?, ?, ?, ?, ?, ?)', songs)

        # Update songs
        cursor = sqlite.execute('select * from stats_songs')
        for song in cursor.fetchall():
            filename = song[0]

            if filename not in songs_filename:
                # Delete this songs from statistics
                sqlite.execute('delete from stats_songs where filename=:val',
                               {'val': filename})

        # Update artists
        cursor = sqlite.execute('select * from stats_artists')
        for artist in cursor.fetchall():
            artist = artist[0]

            if artist not in songs_artists:
                # Delete this artist from statistics
                sqlite.execute('delete from stats_artists where artist=:val',
                               {'val': artist})

        # Update albums
        cursor = sqlite.execute('select * from stats_albums')
        for album in cursor.fetchall():
            album = album[0]

            if album not in songs_albums:
                # Delete this album from statistics
                sqlite.execute('delete from stats_albums where album=:val',
                               {'val': album})

        # The job is ended o/
        sqlite.close()