GNU/Linux >> Linux Esercitazione >  >> Ubuntu

Ubuntu 16.04:come aggiungere/rimuovere app bloccate su Unity Launcher tramite terminale?

quindi ho cercato in rete sul mio argomento ma non ho trovato nessuna risposta.

È possibile? Se si, mi può dire per favore? Grazie 🙂

Risposta accettata:

Contenuti:

  1. Teoria generale del funzionamento del Launcher
  2. Possibili modi per rimuovere e aggiungere a Unity Launcher
  3. utilità launcherctl.py

1. Teoria generale del funzionamento del lanciatore

Il launcher di Unity è essenzialmente un elenco di .desktop File. Sono essenzialmente scorciatoie che consentono di avviare applicazioni e di eseguire azioni personalizzate. In genere vengono archiviati in /usr/share/applications , ma può anche trovarsi in ~/.local/share/applications e in qualsiasi altra parte del sistema. Per il caso generale, consiglio di archiviare tali file in /usr/share/applications per tutti gli utenti o ~/.local/share/applications per ogni singolo utente.

Il Dconf il database delle impostazioni consente di archiviare l'elenco di tali app per Unity Launcher e può essere visualizzato e modificato con gsettings utilità. Ad esempio:

$ gsettings get  com.canonical.Unity.Launcher favorites
['application://wps-office-et.desktop', 'application://wps-office-wpp.desktop', 'application://wps-office-wps.desktop', 'unity://running-apps', 'unity://devices']
$ gsettings set  com.canonical.Unity.Launcher favorites  "['wechat.desktop']"                                                         
$ gsettings get  com.canonical.Unity.Launcher favorites                                                                               
['application://wechat.desktop', 'unity://running-apps', 'unity://devices']

Come puoi vedere tutto il .desktop i file hanno application:// prefisso su di essi, tuttavia non è richiesto quando si imposta l'elenco di avvio. Gli articoli con unity:// prefissi non sono modificabili e non possono essere rimossi.

Le gsettings get com.canonical.Unity.Launcher favorites e gsettings set com.canonical.Unity.Launcher favorites i comandi possono essere usati per creare funzioni nel tuo ~/.bashrc , ad esempio:

get_launcher()
{
    gsettings get  com.canonical.Unity.Launcher favorites
}

set_launcher()
{
    # call this as set_launcher "['file1.desktop','file2.desktop']"
    gsettings set  com.canonical.Unity.Launcher favorites "$1"
}

Esempio:

$ set_launcher "['firefox.desktop','gnome-terminal.desktop']"                                                                         
$ get_launcher                                                                                                                        
['application://firefox.desktop', 'application://gnome-terminal.desktop', 'unity://running-apps', 'unity://devices']

2. Possibili modi per rimuovere e aggiungere Unity Launcher

L'esempio più semplice è già stato mostrato:tramite gsettings utilità. La rimozione e l'aggiunta di elementi specifici richiede l'analisi delle gsettings produzione. Questo può essere fatto tramite sed o awk utility e con fatica anche in bash . Tuttavia, trovo che Python consenta l'approccio più semplice e il "percorso di minor resistenza". Pertanto, gli esempi forniti qui utilizzano gsettings insieme a Python.

Ecco un caso di rimozione:

$ gsettings get com.canonical.Unity.Launcher favorites|                                                                               
> python -c 'import ast,sys; x =[]; x = [i for l in sys.stdin for i in ast.literal_eval(l)]; 
> x.pop(x.index("application://"+sys.argv[1])); print x' firefox.desktop
['application://gnome-terminal.desktop', 'unity://running-apps', 'unity://devices']

Cosa sta succedendo qui ? Passiamo l'output di gsettings get tramite pipe a Python. Python quindi legge il flusso di input standard e utilizza ast library valuta la rappresentazione testuale dell'elenco e lo converte in un elenco effettivo che Python può riconoscere. Questo semplifica enormemente il lavoro:se fosse stato awk o sed avremmo dovuto occuparci della rimozione e dell'aggiunta di singoli caratteri. Infine, rimuoviamo (pop) il secondo argomento della riga di comando (indicato da sys.argv[1] ) trovando il suo indice nell'elenco. Ora abbiamo un nuovo elenco, che può essere passato ulteriormente tramite pipe a gsettings set

Il comando completo è quindi questo:

$ gsettings get com.canonical.Unity.Launcher favorites|
> python -c 'import ast,sys; x =[]; x = [i for l in sys.stdin for i in ast.literal_eval(l)]; 
> x.pop(x.index("application://"+sys.argv[1])); print "\""+repr(x)+"\""' firefox.desktop |
> xargs -I {} gsettings set  com.canonical.Unity.Launcher favorites {}

Che può essere ben inserito in un ~/.bashrc funziona così:

remove_launcher_item()
{
  gsettings get com.canonical.Unity.Launcher favorites|
  python -c 'import ast,sys; x =[]; x = [i for l in sys.stdin for i in ast.literal_eval(l)];\
  x.pop(x.index("application://"+sys.argv[1])); print "\""+repr(x)+"\""' "$1" |
  xargs -I {} gsettings set  com.canonical.Unity.Launcher favorites {}
}

Alcune cose da notare qui sono che dobbiamo stampare di nuovo la rappresentazione "stringa" dell'elenco racchiusa tra virgolette e passarla tramite xargs . L'idea con l'aggiunta è simile, tranne al posto di pop usiamo append funzione:

append_launcher_item()
{
  gsettings get com.canonical.Unity.Launcher favorites|
  python -c 'import ast,sys; x =[]; x = [i for l in sys.stdin for i in ast.literal_eval(l)];\
  x.append("application://"+sys.argv[1]); print "\""+repr(x)+"\""' "$1" |
  xargs -I {} gsettings set  com.canonical.Unity.Launcher favorites {}

}

Esempio di esecuzione:

$ get_launcher                                                                                                                        
['unity://running-apps', 'unity://devices', 'application://firefox.desktop']
$ append_launcher_item gnome-terminal.desktop                                                                                         
$ get_launcher                                                                                                                        
['unity://running-apps', 'unity://devices', 'application://firefox.desktop', 'application://gnome-terminal.desktop']
$ 

Queste funzioni non devono necessariamente far parte di ~/.bashrc . Puoi anche inserirli in uno script

3. utility launcherctl.py

Nel tempo, ho ricercato e creato una serie di funzioni in Python che possono effettivamente fare lo stesso di gsettings utilità. Unendo la potenza di Python a queste funzioni, ho creato launcherctl.py utilità.

Correlati:driver per Intel HD installato, ma i giochi si lamentano ancora che il 3D non è supportato?

Questo è un lavoro in corso e sarà ampliato per includere più funzioni in futuro. Per questa domanda specifica, lascerò il codice sorgente come appare nella prima versione. Ulteriori versioni e miglioramenti possono essere trovati su GitHub.

Quali sono i vantaggi di questo script rispetto alle funzioni bash?
1. Questa è un'utilità “centralizzata” con uno scopo specifico. Non è necessario disporre di script/funzioni separati per ciascuna azione.
2. Opzioni della riga di comando semplici da usare e minimaliste
3. Se utilizzato insieme ad altre utilità, fornisce un codice più leggibile .

Utilizzo :

Come mostrato da -h opzione della riga di comando:

$ ./launcherctl.py -h                                                                                                                 
usage: launcherctl.py [-h] [-f FILE] [-a] [-r] [-l] [-c]

Copyright 2016. Sergiy Kolodyazhnyy.
    This command line utility allows appending and removing items
    from Unity launcher, as well as listing and clearing the
    Launcher items.

    --file option is required for --append and --remove 


optional arguments:
  -h, --help            show this help message and exit
  -f FILE, --file FILE
  -a, --append
  -r, --remove
  -l, --list
  -c, --clear

L'utilizzo della riga di comando è semplice.

In allegato:

$ ./launcherctl.py -a -f wechat.desktop

Rimozione:

$ ./launcherctl.py -r -f wechat.desktop

Cancellazione completa del programma di avvio:

$ ./launcherctl.py -c 

Elementi dell'elenco sul programma di avvio:

$ ./launcherctl.py -l                                                                                                                 
chromium-browser.desktop
firefox.desktop
opera.desktop
vivaldi-beta.desktop

Come accennato in precedenza, può essere utilizzato con altri comandi. Ad esempio, aggiungendo da file:

$ cat new_list.txt                                                                                                                    
firefox.desktop
wechat.desktop
gnome-terminal.desktop    
$ cat new_list.txt | xargs -L 1 launcherctl.py -a -f

Lo stesso può essere utilizzato con la rimozione di elementi forniti da un file di testo

Rimozione di un terzo elemento dal dash pulsante:

$ launcherctl.py  -l | awk 'NR==3' | xargs -L 1 launcherctl.py -r -f  

Ottenimento del codice sorgente e installazione

Modo manuale:

  1. Crea una directory ~/bin .
  2. Salva il codice sorgente dal basso nel file ~/bin/launcherctl.py
  3. Se sei bash utente, puoi procurarti ~/.profile oppure disconnettersi ed effettuare il login. Il ~/bin la directory verrà aggiunta al tuo $PATH variabile automaticamente. Per coloro che non usano bash , aggiungi ~/bin al tuo $PATH variabile all'interno del file di configurazione della shell, in questo modo:PATH="$PATH:$HOME/bin

Come ho già detto, le ultime modifiche al codice vanno nel repository GitHub. Se hai git installato, i passaggi sono più semplici:

  1. git clone https://github.com/SergKolo/sergrep.git ~/bin/sergrep
  2. echo "PATH=$PATH:$HOME/bin/sergrep" >> ~/.bashrc
  3. source ~/.bashrc . Dopo questo passaggio, puoi chiamare launcherctl.py come qualsiasi altro comando. Ottenere gli aggiornamenti è semplice come cd ~/bin/sergrep;git pull

Ottenere codice da GitHub senza git :

  1. cd /tmp
  2. wget https://github.com/SergKolo/sergrep/archive/master.zip
  3. unzip master.zip
  4. Se non hai ~/bin , fallo con mkdir ~/bin
  5. mv sergrep-master/launcherctl.py ~/bin/launcherctl.py

In tutti i casi si applicano le stesse regole:lo script deve risiedere in una directory aggiunta a PATH variabile e deve avere i permessi eseguibili impostati con chmod +x launcherctl.py

Codice sorgente originale :

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

#
# Author: Serg Kolo , contact: [email protected]
# Date: Sept 24, 2016
# Purpose: command-line utility for controling the launcher
#          settings
# Tested on: Ubuntu 16.04 LTS
#
#
# Licensed under The MIT License (MIT).
# See included LICENSE file or the notice below.
#
# Copyright © 2016 Sergiy Kolodyazhnyy
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

import gi
from gi.repository import Gio
import argparse
import sys

def gsettings_get(schema, path, key):
    """Get value of gsettings schema"""
    if path is None:
        gsettings = Gio.Settings.new(schema)
    else:
        gsettings = Gio.Settings.new_with_path(schema, path)
    return gsettings.get_value(key)

def gsettings_set(schema, path, key, value):
    """Set value of gsettings schema"""
    if path is None:
        gsettings = Gio.Settings.new(schema)
    else:
        gsettings = Gio.Settings.new_with_path(schema, path)
    if isinstance(value,list ):
        return gsettings.set_strv(key, value)
    if isinstance(value,int):
        return gsettings.set_int(key, value)

def puts_error(string):
    sys.stderr.write(string+"\n")
    sys.exit(1)

def list_items():
    """ lists all applications pinned to launcher """
    schema = 'com.canonical.Unity.Launcher'
    path = None
    key = 'favorites'
    items = list(gsettings_get(schema,path,key))
    for item in items:
        if 'application://' in item:
            print(item.replace("application://","").lstrip())

def append_item(item):
    """ appends specific item to launcher """
    schema = 'com.canonical.Unity.Launcher'
    path = None
    key = 'favorites'
    items = list(gsettings_get(schema,path,key))

    if not item.endswith(".desktop"):
        puts_error( ">>> Bad file.Must have .desktop extension!!!")

    items.append('application://' + item)
    gsettings_set(schema,path,key,items)

def remove_item(item):
    """ removes specific item from launcher """
    schema = 'com.canonical.Unity.Launcher'
    path = None
    key = 'favorites'
    items = list(gsettings_get(schema,path,key))

    if not item.endswith(".desktop"):
       puts_error(">>> Bad file. Must have .desktop extension!!!")
    items.pop(items.index('application://'+item))
    gsettings_set(schema,path,key,items)

def clear_all():
    """ clears the launcher completely """
    schema = 'com.canonical.Unity.Launcher'
    path = None
    key = 'favorites'

    gsettings_set(schema,path,key,[])

def parse_args():
    """parse command line arguments"""

    info="""Copyright 2016. Sergiy Kolodyazhnyy.
    This command line utility allows appending and removing items
    from Unity launcher, as well as listing and clearing the
    Launcher items.

    --file option is required for --append and --remove 
    """
    arg_parser = argparse.ArgumentParser(
                 description=info,
                 formatter_class=argparse.RawTextHelpFormatter)
    arg_parser.add_argument('-f','--file',action='store',
                            type=str,required=False)
    arg_parser.add_argument('-a','--append',
                            action='store_true',required=False)

    arg_parser.add_argument('-r','--remove',
                            action='store_true',required=False)
    arg_parser.add_argument('-l','--list',
                            action='store_true',required=False)

    arg_parser.add_argument('-c','--clear',
                            action='store_true',required=False)
    return arg_parser.parse_args()

def main():
    """ Defines program entry point """
    args = parse_args()

    if args.list:
       list_items()
       sys.exit(0)

    if args.append:
       if not args.file:
          puts_error(">>>Specify .desktop file with --file option")

       append_item(args.file)
       sys.exit(0)

    if args.remove:
       if not args.file:
          puts_error(">>>Specify .desktop file with --file option")

       remove_item(args.file)
       sys.exit(0)

    if args.clear:
       clear_all()
       sys.exit(0)

    sys.exit(0)

if __name__ == '__main__':
    main()

Note aggiuntive:

  • in passato ho creato una risposta che permette di impostare l'elenco dei lanciatori da file:https://askubuntu.com/a/761021/295286
  • Ho anche creato un indicatore Unity per passare da più elenchi. Vedi le istruzioni qui:http://www.omgubuntu.co.uk/2016/09/launcher-list-indicator-update-ppa-workspaces
Correlati:nessun suono in Ubuntu 13.04, solo Dumthe dispositivo di output elencato?
Ubuntu
  1. Come rimuovere Amazon Dash Launcher su Ubuntu 20.04 Focal Fossa Linux

  2. Come aprire il terminale in Ubuntu 22.04

  3. Come aggiungere un file di scambio su Ubuntu

  4. Come aggiungere una stampante in Ubuntu 11.10 | Aggiungi stampante in Ubuntu

  5. Come installare l'emulatore di terminale Alacritty tramite PPA in Ubuntu 20.04

Come aggiungere e rimuovere segnalibri in Ubuntu [Suggerimento per principianti]

Come aggiungere o rimuovere l'applicazione di avvio in Ubuntu

Ubuntu Come impostare un IP statico tramite terminale e GUI

Come installare Teamviewer su Ubuntu 20.04 tramite Terminale

Come rimuovere completamente le app di Google Chrome (ad es. Postman) su Ubuntu 18.04?

Come aggiungere e rimuovere app dopo la creazione su Liveusb?