así que busqué en la red sobre mi tema pero no encontré ninguna respuesta.
¿Es posible? Si es así, ¿puede por favor decirme? Gracias 🙂
Respuesta aceptada:
Contenido:
- Teoría general del funcionamiento del lanzador
- Formas posibles de eliminar y agregar al iniciador de Unity
- utilidad launcherctl.py
1. Teoría general del funcionamiento del lanzador
El lanzador de Unity es esencialmente una lista de .desktop
archivos Son esencialmente accesos directos que permiten iniciar aplicaciones y realizar acciones personalizadas. Por lo general, se almacenan en /usr/share/applications
, pero también se puede ubicar en ~/.local/share/applications
y en cualquier otro lugar del sistema. Para el caso general, recomiendo almacenar dichos archivos en /usr/share/applications
para todos los usuarios o ~/.local/share/applications
para cada usuario individual.
El Dconf
La base de datos de configuración permite almacenar una lista de dichas aplicaciones para el iniciador de Unity y se puede ver y modificar con gsettings
utilidad. Por ejemplo:
$ 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']
Como puedes ver todo el .desktop
los archivos tienen application://
prefijo en ellos, sin embargo, no es necesario al configurar la lista de inicio. Los elementos con unity://
prefijo no se pueden modificar y no se pueden eliminar.
Los gsettings get com.canonical.Unity.Launcher favorites
y gsettings set com.canonical.Unity.Launcher favorites
los comandos se pueden usar para crear funciones en su ~/.bashrc
, por ejemplo:
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"
}
Ejemplo:
$ set_launcher "['firefox.desktop','gnome-terminal.desktop']"
$ get_launcher
['application://firefox.desktop', 'application://gnome-terminal.desktop', 'unity://running-apps', 'unity://devices']
2. Posibles formas de eliminar y agregar a Unity Launcher
El ejemplo más simple ya se ha mostrado:a través de gsettings
utilidad. Eliminar y agregar un elemento específico requiere analizar gsettings
producción. Esto se puede hacer a través de sed
o awk
utilidades, y con esfuerzo incluso en bash
. Sin embargo, encuentro que python permite el enfoque más fácil y el "camino de menor resistencia". Por lo tanto, los ejemplos proporcionados aquí usan gsettings
conjuntamente con python.
Aquí hay un caso de eliminación:
$ 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']
Que está sucediendo aquí ? Pasamos la salida de gsettings get
vía tubería a python. Python luego lee el flujo de entrada estándar y usa ast
biblioteca evalúa la representación de texto de la lista y la convierte en una lista real que Python puede reconocer. Esto simplifica enormemente el trabajo:si esto fuera awk o sed, tendríamos que lidiar con la eliminación y adición de caracteres individuales. Finalmente, eliminamos (pop) el segundo argumento de la línea de comandos (indicado por sys.argv[1]
) encontrando su índice en la lista. Ahora tenemos una nueva lista, que se puede pasar más a través de una canalización a gsettings set
El comando completo es entonces este:
$ 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 {}
Que se puede poner muy bien en un ~/.bashrc
funcionar así:
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 {}
}
Algunas cosas a tener en cuenta aquí es que necesitamos imprimir nuevamente la representación de "cadena" de la lista entre comillas y pasarla a través de xargs
. La idea de agregar es similar, excepto que en lugar de pop
usamos append
función:
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 {}
}
Ejecución de muestra:
$ 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']
$
Estas funciones no necesariamente tienen que ser parte de ~/.bashrc
. También puede colocarlos en un script
3. utilidad launcherctl.py
Con el tiempo, investigué y construí un conjunto de funciones en python que pueden hacer lo mismo que gsettings
. utilidad. Combinando el poder de python con esas funciones, he creado launcherctl.py
utilidad.
Este es un trabajo en progreso y se ampliará para incluir más funciones en el futuro. Para esta pregunta específica, dejaré el código fuente tal como aparece en la primera versión. Se pueden encontrar más versiones y mejoras en GitHub.
¿Cuáles son las ventajas de este script en comparación con las funciones bash?
1. Esta es una utilidad "centralizada" con un propósito específico. No es necesario tener un script/función independiente para cada acción.
2. Opciones de línea de comandos minimalistas y fáciles de usar
3. Cuando se usa junto con otras utilidades, proporciona un código más legible .
Uso :
Como lo muestra el -h
opción de línea de 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
El uso de la línea de comandos es simple.
Anexando:
$ ./launcherctl.py -a -f wechat.desktop
Eliminación:
$ ./launcherctl.py -r -f wechat.desktop
Limpiando lanzador completamente:
$ ./launcherctl.py -c
Listado de elementos en el lanzador:
$ ./launcherctl.py -l
chromium-browser.desktop
firefox.desktop
opera.desktop
vivaldi-beta.desktop
Como se mencionó anteriormente, se puede usar con otros comandos. Por ejemplo, agregando desde el archivo:
$ cat new_list.txt
firefox.desktop
wechat.desktop
gnome-terminal.desktop
$ cat new_list.txt | xargs -L 1 launcherctl.py -a -f
Lo mismo se puede usar con la eliminación de elementos dados de un archivo de texto
Eliminar un tercer elemento del dash
botón:
$ launcherctl.py -l | awk 'NR==3' | xargs -L 1 launcherctl.py -r -f
Obtención del código fuente e instalación
Modo manual:
- Cree un directorio
~/bin
. - Guarde el código fuente de abajo en el archivo
~/bin/launcherctl.py
- Si eres
bash
usuario, puede obtener~/.profile
o cerrar sesión e iniciar sesión. El~/bin
el directorio se agregará a su$PATH
variable automáticamente. Para aquellos que no usanbash
, agregue~/bin
a tu$PATH
variable dentro de su archivo de configuración de shell, así:PATH="$PATH:$HOME/bin
Como mencioné, los últimos cambios en el código van al repositorio de GitHub. Si tienes git
instalado, los pasos son más simples:
git clone https://github.com/SergKolo/sergrep.git ~/bin/sergrep
echo "PATH=$PATH:$HOME/bin/sergrep" >> ~/.bashrc
source ~/.bashrc
. Después de este paso, puede llamar alauncherctl.py
como cualquier otro comando. Obtener actualizaciones es tan simple comocd ~/bin/sergrep;git pull
Obtener código de GitHub sin git
:
cd /tmp
wget https://github.com/SergKolo/sergrep/archive/master.zip
unzip master.zip
- Si no tiene
~/bin
, hazlo conmkdir ~/bin
mv sergrep-master/launcherctl.py ~/bin/launcherctl.py
En todos los casos, se aplican las mismas reglas:el script debe residir en un directorio que se agrega a PATH
variable y debe tener permisos ejecutables configurados con chmod +x launcherctl.py
Código fuente original :
#!/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()
Notas adicionales:
- en el pasado creé una respuesta que permite configurar la lista de inicio desde el archivo:https://askubuntu.com/a/761021/295286
- También creé un indicador de Unity para cambiar entre varias listas. Consulte las instrucciones aquí:http://www.omgubuntu.co.uk/2016/09/launcher-list-indicator-update-ppa-workspaces