¿Cómo crear un lanzador de la unidad que supervise los archivos?


11

Me gustaría crear un lanzador que haga lo mismo que el ícono de la papelera, donde se muestran diferentes listas rápidas dependiendo de si hay elementos en la papelera.

Me gustaría algo como: si la carpeta Aexiste, mostrar A,B,Cen la lista rápida, si la carpeta Ano existe, mostrar D,E,Fen la lista rápida.


3
He investigado esto antes, y probablemente tenga que hacerse a través del protocolo de Notificación de inicio . Y al establecer StartupNotify en true en el archivo .desktop. Pero no estoy seguro de allí.
Paul van Schayck

1
Echa un vistazo: wiki.ubuntu.com/Unity/LauncherAPI Tiene ejemplos de listas rápidas dinámicas
S Prasanth

Respuestas:


3

Los siguientes trabajos:

  1. Cree 2 archivos: mylauncher.desktop y mylauncher.py con el contenido que se muestra a continuación.
  2. Convierta mylauncher.desktop en un ejecutable.
  3. Agregue mylauncher.desktop al lanzador de unity.
  4. Edite nombres de carpetas y ubicaciones de carpetas en mylauncher.py según sea necesario.
  5. Ejecutar python mylauncher.pyen segundo plano. Tendrá que agregar esto a uno de sus scripts de inicio.

Fuente: https://wiki.ubuntu.com/Unity/LauncherAPI


Contenido de mylauncher.desktop:

[Desktop Entry]
Name=My Launcher
Comment=A,B,C if A else D,E,F
Exec=nautilus %U
Icon=nautilus
Terminal=false
StartupNotify=true
Type=Application
OnlyShowIn=GNOME;Unity;
Actions=;

Contenido de mylauncher.py:

updateinterval = 1 #Update interval in seconds. Set it to a +ve integer.
#In Foldernames and Folderlocations, spaces shouldn't be preceded by \.
Foldernames = ["A", "B", "C", "D", "E", "F"]
Folderlocations = ["/home/prasanth/A", "/home/prasanth/B", "/home/prasanth/C", "/home/prasanth/D", "/home/prasanth/E", "/home/prasanth/F"]
#####################################

from gi.repository import Unity, Gio, GObject, Dbusmenu
import os, subprocess

def nautilusopen(junk1, junk2, location): #Function that opens `location` in nautilus. Equivalent to `nautilus location` in bash.
    subprocess.Popen(['nautilus', "%s" % location])

launcher = Unity.LauncherEntry.get_for_desktop_id("mylauncher.desktop") #You won't have to modify this, except if you rename `mylauncher.desktop`

#Code block A: This code block builds 6 quicklist entries, 3 for when A is found and 3 for when it isn't
QLentries = [Dbusmenu.Menuitem.new() for i in Foldernames]
for i in xrange(6):
    QLentries[i].property_set(Dbusmenu.MENUITEM_PROP_LABEL, "Goto %s" % Foldernames[i])
    QLentries[i].connect("item-activated", nautilusopen, Folderlocations[i])
    QLentries[i].property_set_bool(Dbusmenu.MENUITEM_PROP_VISIBLE, True)
################

#Code block B: This code block creates 2 quicklists 1 for when A is found and 1 for when it isn't. Then it adds the first 3 quicklist entries to QLifA and the next 3 to QLifnotA
QLifA = Dbusmenu.Menuitem.new() #Quicklist if A is found
QLifnotA = Dbusmenu.Menuitem.new() #Quicklist if A is not found.
for i in xrange(3):
    QLifA.child_append(QLentries[i])
for i in xrange(3, 6):
    QLifnotA.child_append(QLentries[i])
################

#The rest of the code simply monitors the file system for A's existence and switches appropriately between QLifA and QLifnotA
prevState = None
def updateql():
    global prevState
    currentState = 'A' if os.path.exists(Folderlocations[0]) else 'notA' #currentState is 'A' if Folderlocations[0] (which is /home/prasanth/A) exists, 'notA' otherwise
    if currentState != prevState:
        if currentState == 'A':
            launcher.set_property("quicklist", QLifA)
        else:
            launcher.set_property("quicklist", QLifnotA)
        prevState = currentState
    return True

#GObject.timeout_add_seconds(updateinterval, updateql)
#mainloop = GObject.MainLoop()
#mainloop.run()

#If the 3-line commented block above worked as expected, the remainder of this script would be unnecessary. Unfortunately, it doesn't.
import signal
def alarmhandler(signum, frame):
    raise Exception('Alarm has rung')
signal.signal(signal.SIGALRM, alarmhandler)

mainloop = GObject.MainLoop()

while True:
    try:
        updateql()
        signal.alarm(updateinterval)
        mainloop.run()
    except KeyboardInterrupt:
        continue

EDITAR: Use lo siguiente como mylauncher.py para el propósito mencionado en los comentarios. La modificación para satisfacer sus necesidades debe ser sencilla y en caso de que no se mencione en los comentarios.

from gi.repository import Unity, Gio, GObject, Dbusmenu
import os, subprocess

updateinterval = 1 #Update interval in seconds. Set it to a +ve integer.

#Quicklist entries if already mounted:
ifMountedEntry1text = """Unmount A""" #Text shown in the quicklist menu for this entry.
ifMountedEntry1command = """unmount A""" #Bash command to execute when entry 1 is clicked. Doubt if `unmount A` will work. Modify appropriately.

ifMountedEntry2text = """Open A""" #Maybe you'll want to open A directly from the launcher. Included just so you get a hang of how this works.
ifMountedEntry2command = """nautilus A"""
#Extend as required.

#Quicklist entries if not already mounted:
ifnotMountedEntry1text = """Mount A"""
ifnotMountedEntry1command = """mount A""" #Again modify `mount A` appropriately.
#Extend as required.

#My old file monitoring should work. But in case you want to change the criteria for modifying quicklists, it is better to do the following:
filemonitoringcommand = """if [ -d /folder/to/monitor/ ]; then echo True; else echo False; fi;""" #<Bash command>/<location to script> which prints 'True' if A is mounted, 'False' otherwise.
#####################

def systemcall(junk1, junk2, command):
    os.system(command)

launcher = Unity.LauncherEntry.get_for_desktop_id("mylauncher.desktop") #You won't have to modify this, except if you rename `mylauncher.desktop`

#Quicklist if already mounted:
QLifMounted = Dbusmenu.Menuitem.new()

ifMountedEntry1 = Dbusmenu.Menuitem.new()
ifMountedEntry1.property_set(Dbusmenu.MENUITEM_PROP_LABEL, ifMountedEntry1text) #Sets the text shown in the quicklist menu for this entry.
ifMountedEntry1.connect("item-activated", systemcall, ifMountedEntry1command) #Sets the corresponding bash command.
ifMountedEntry1.property_set_bool(Dbusmenu.MENUITEM_PROP_VISIBLE, True)
QLifMounted.child_append(ifMountedEntry1) #Adds the first entry to the quicklist

ifMountedEntry2 = Dbusmenu.Menuitem.new()
ifMountedEntry2.property_set(Dbusmenu.MENUITEM_PROP_LABEL, ifMountedEntry2text)
ifMountedEntry2.connect("item-activated", systemcall, ifMountedEntry2command)
ifMountedEntry2.property_set_bool(Dbusmenu.MENUITEM_PROP_VISIBLE, True)
QLifMounted.child_append(ifMountedEntry2)
#Extend as required.

#Quicklist if not already mounted:
QLifnotMounted = Dbusmenu.Menuitem.new()

ifnotMountedEntry1 = Dbusmenu.Menuitem.new()
ifnotMountedEntry1.property_set(Dbusmenu.MENUITEM_PROP_LABEL, ifnotMountedEntry1text)
ifnotMountedEntry1.connect("item-activated", systemcall, ifnotMountedEntry1command)
ifnotMountedEntry1.property_set_bool(Dbusmenu.MENUITEM_PROP_VISIBLE, True)
QLifnotMounted.child_append(ifnotMountedEntry1)
#Extend as required.

#The rest of the code uses `filemonitoringcommand` to monitor the filesystem and dynamically modifies (or rather switches between) quicklists.
prevState = None
def updateql():
    global prevState
    currentState = 'True' in os.popen(filemonitoringcommand).read()
    if currentState != prevState:
        if currentState == True:
            launcher.set_property("quicklist", QLifMounted) #If already mounted, sets QLifMounted as the quicklist.
        else:
            launcher.set_property("quicklist", QLifnotMounted) #Otherwise sets QLifnotMounted as the quicklist.
        prevState = currentState
    return True

#GObject.timeout_add_seconds(updateinterval, updateql)
#mainloop = GObject.MainLoop()
#mainloop.run()

#If the 3-line commented block above worked as expected, the remainder of this script would be unnecessary. Unfortunately, it doesn't.
import signal
def alarmhandler(signum, frame):
    raise Exception('Alarm has rung')
signal.signal(signal.SIGALRM, alarmhandler)

mainloop = GObject.MainLoop()

while True:
    try:
        updateql()
        signal.alarm(updateinterval)
        mainloop.run()
    except KeyboardInterrupt:
        continue

He intentado esto pero no me funciona. La lista rápida no cambia. Estoy usando ubuntu 12.10 de 64 bits.
Rey Leonard Amorato

Estoy usando 12.04 32 bit. La secuencia de comandos de Python se debe ejecutar DESPUÉS de agregar el icono del iniciador al iniciador.
S Prasanth

Haga lo siguiente.1) Coloque mylauncher.desktop en ~ / .local / share / aplicaciones 2) Presione la súper tecla y busque 'My Launcher'. 3) Arrastre el icono del iniciador que aparece en el iniciador de la unidad. 4) Ejecute el script python. Esto debería funcionar.
S Prasanth

@ReyLeonardAmorato Tengo curiosidad. ¿Funcionó?
S Prasanth

Hola. Lo siento, no pude encontrar el tiempo para estar en línea últimamente, pero su último método funcionó para mí. Sin embargo, lo que quería es ligeramente diferente de lo que hace el guión. Me gustaría monitorear la ubicación de una carpeta (el script ya lo hace) y si la carpeta 'A' existe, muestre 'desmontar' en la lista rápida. Mostrar 'montar' de lo contrario. No tengo conocimiento de las secuencias de comandos de Python, así que no tengo idea de cómo modificar la secuencia de comandos que ha proporcionado. Sería genial si pudieras ayudar con esta parte final.
Rey Leonard Amorato
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.