En esta recetilla cuento los pasos que he seguido para crear un pequeño plugin para Freevo, con el que poder lanzar el juego Stepmania. Como tengo la intención de incorporar más juegos al menú de Freevo, he intentado no hacer el plugin demasiado específico.

Lo básico

Es bastante sencillo crear un plugin. Veamos los elementos mínimos. Si atendemos a la documentación oficial un plugin es una subclase que hereda de PluginInterface y que debe tener al menos dos funciones.

  • actions: que devuelve una lista de las posibles acciones del plugin (o una lista vacía)

    def actions(self,item):
    if SOMECONDITION:
    return [ (self.COMMAND,‘Name of menu entry’)]
    return []
  • Uno o varios comandos que deben estar disponibles.

    def COMMAND:
    item = self.item
    os.system(‘command’)
    menuw.delete_menu(arg, menuw)

Aunque se supone que eso es lo básico que hay que saber, resulta que siguiendo estos sencillos pasos no he sido capaz de hacer funcionar mi plugin correctamente. Así que como siempre que ocurre esto el procedimiento a seguir es:

  • Busca un plugin que funcione,
  • destrípalo
  • y adáptalo a tus necesidades.

Plugin Stepmania

A continuación un paseo comentado por mi sencillo plugin para lanzar Stepmania.

En primer lugar una cabecera con las inclusiones de rigor.


#python modules
import os, time, stat, re, copy

#freevo modules
import config, menu, rc, plugin, skin, osd, util
from gui.PopupBox import PopupBox
from item import Item

Después accedo a los objetos skin y osd

#get the singletons so we get skin info and access the osd
skin = skin.get_singleton()
osd = osd.get_singleton()

skin.register(‘Stepmania’, (‘screen’, ‘title’, ‘info’, ‘plugin’))

Realmente solo se necesita el objeto skin, pero bueno.

Clase PluginInterface

class PluginInterface(plugin.MainMenuPlugin):
    """
    A plugin to launch Stepmania Game
    To activate, put the following lines in local_conf.py:

    plugin.activate('stepmania', level=45)
    """
    # make an init func that creates the cache dir if it don't exist
    def __init__(self):
        plugin.MainMenuPlugin.__init__(self)


    def items(self, parent):
        return [ GameMainMenuItem(parent) ]

Como puede verse, en el constructor se invoca el constructor de la clase madre MainMenuPlugin. Existen otros tipos de plugins. Este plugin podría ser del tipo ItemPlugin para incorporarse como una acción más dentro de la categoría video, image o tv.

También puede verse que en vez de implementar una función actions creo una función items. Mi interpretación es que al crearse el plugin de tipo MainMenuPlugin, se obtiene una lista de items disponibles. Cada item retornado es una clase que sí que debe implementar los métodos actions y los comandos asociados.

En mi caso, la función items solo devuelve un elemento, que se corresponde con la clase GameMainMenuItem.

Clase GameMainMenuItem

class GameMainMenuItem(Item):

    def __init__(self, parent):
        Item.__init__(self, parent, skin_type='Stepmania')
        self.name = _('Stepmania')

    def actions(self):
        """
        return a list of actions for this item
        """
        items = [ ( self.launch_game , _('Stepmania' )) ]
        return items

    def launch_game(self, arg=None, menuw=None):
        popup_string=_("Starting Stepmania...")
        pop = PopupBox(text=popup_string)
        pop.show()
        os.system('stepmania')
        pop.destroy()
        menuw.delete_menu(arg, menuw)
        menuw.refresh()

En su constructor se invoca el constructor del elemento en el menú principal de Freevo.

La lista de acciones solo devuelve una única acción que se corresponde con el método launch_game.

El método launch_game se limita a mostrar un popup y lanzar el comando del juego. A la vuelta del juego se destruye el popup y se refresca el menú.

Todo junto

A continuación todo el código del plugin para quien lo quiera utilizar:

#python modules
import os, time, stat, re, copy

#freevo modules
import config, menu, rc, plugin, skin, osd, util
from gui.PopupBox import PopupBox
from item import Item

#get the singletons so we get skin info and access the osd
skin = skin.get_singleton()
osd  = osd.get_singleton()

skin.register('Stepmania', ('screen', 'title', 'info', 'plugin'))

class PluginInterface(plugin.MainMenuPlugin):
    """
    A plugin to launch Stepmania Game

    To activate, put the following lines in local_conf.py:

    plugin.activate('stepmania', level=45)

    """
    # make an init func that creates the cache dir if it don't exist
    def __init__(self):
        plugin.MainMenuPlugin.__init__(self)


    def items(self, parent):
        return [ GameMainMenuItem(parent) ]


class GameMainMenuItem(Item):

    def __init__(self, parent):
        Item.__init__(self, parent, skin_type='Stepmania')
        self.name = _('Stepmania')

    def actions(self):
        """
        return a list of actions for this item
        """
        items = [ ( self.launch_game , _('Stepmania' )) ]
        return items

    def launch_game(self, arg=None, menuw=None):
        popup_string=_("Starting Stepmania...")
        pop = PopupBox(text=popup_string)
        pop.show()
        os.system('stepmania')
        pop.destroy()
        menuw.delete_menu(arg, menuw)
        menuw.refresh()

Tan solo hay que guardar el contenido con el nombre stepmania.py y copiarlo en el directorio /usr/share/python-support/python-freevo/freevo/plugins. Y ejecutar el comando.

# update-python-modules -i /usr/share/python-support/python-freevo

Para invocarlo, tal y como se explica en los comentarios del código, hay que incluir lo siguiente en el fichero /etc/freevo/local_conf.py

plugin.activate('stepmania', level=45)

Referencias



blog comments powered by Disqus