Activity tutorial: Difference between revisions

From OLPC
Jump to navigation Jump to search
(remove Category:Activities -- this is not an activity!)
No edit summary
Line 1: Line 1:
El tutorial explica paso a paso como crear el [http://divieira.googlepages.com/HelloWorld-1.xo Paquete de la actividad Hola Mundo].
{{Translations}}
{{Developers}}
<< [[Tutorials]]


Se asume que ya ha [[:Category:Installing Sugar|instalado el entorno de desarrollo Azúcar]].
This tutorial explains step by step how to create the Hello World Activity bundle. You can [http://divieira.googlepages.com/HelloWorld-1.xo download a completed .xo package], though the package will not exactly match the below contents.


Crear la estructura de directorios del paquete:
This tutorial assumes you have read the [[Developers|Developer's Manual]], have [[Developers/Setup|installed a Sugar development environment]] and wish to use the [[Developers/Setup#Python/PyGTK|PyGTK]] development approach (the standard approach to developing activities for the OLPC).


mkdir HolaMundo.activity
== Getting started ==
mkdir HolaMundo.activity/activity
*Create the bundle directory structure:


Escribir el archivo activity.info, para describir el paquete en el sub-directorio de la actividad (por ejemplo, HolaMundo.activity/activity/activity.info). Las especificaciones de los [[Activity Bundles|Paquetes de Actividad]] explican en detalle el significado de cada campo.
mkdir -p HelloWorldActivity.activity/activity

*Write the <tt>activity.info</tt> file, to describe your bundle in the activity sub-directory (e.g. <tt>HelloWorldActivity.activity/activity/activity.info</tt>). The [[Activity Bundles]] specification explain in detail the meaning of each field.
**Note: in a joyride-1525 build, sugar could not locate the icon when I tried this unless I removed the '.svg' extension from the 'icon = activity-helloworld.svg' line.


{{ Box File | activity.info | 2=<pre>
{{ Box File | activity.info | 2=<pre>
[Activity]
[Activity]
name = HelloWorld
name = HolaMundo
bundle_id = org.laptop.HelloWorldActivity
service_name = com.ywwg.HelloWorldActivity
class = HelloWorldActivity.HelloWorldActivity
class = ActividadHolaMundo.ActividadHolaMundo
icon = activity-helloworld
icon = actividad-holamundo
activity_version = 1
activity_version = 1
host_version = 1
show_launcher = yes
show_launcher = yes
</pre>
</pre>
}}
}}


Diseñe un icono para su actividad, de acuerdo con el [[Sugar_Icon_Format|formato del icono]] y colóquelo en el sub-directorio "activity". El nombre del archivo debe coincidir con el nombre especificado en el archivo .info (por ejemplo, actividad-holamundo.svg)
*Design an icon for your activity by following the instructions on [[Making_Sugar_Icons | making icons for Sugar]] and place it in the activity sub-directory. The file name should match the icon file name specified in the info file (e.g. <tt>activity-helloworld.svg</tt>). The contents of the SVG file will look something like:


{{ Box File | activity-helloworld.svg | 2=<pre>
{{ Box File | actividad-holamundo.svg | 2=<pre>
<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" [
<!ENTITY fill_color "#FFFFFF">
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" [
<!ENTITY stroke_color "#666666">
<!ENTITY stroke_color "#FF0000">
]>
<!ENTITY fill_color "#FFFFFF">
<svg xmlns="http://www.w3.org/2000/svg" width="50" height="50">
]>
<rect x="1" y="1" width="48" height="48" style="fill:&fill_color;;stroke:&stroke_color;;stroke-width:2"/>
<svg xmlns="http://www.w3.org/2000/svg" width="55" height="55">
</svg>
<rect x="5" y="5" width="45" height="45"
style="fill:&fill_color;;stroke:&stroke_color;;stroke-width:3.5"/>
</svg>
</pre>
</pre>
}}
}}


*Write the <tt>setup.py</tt> script in the top level directory (e.g. <tt>HelloWorldActivity.activity/setup.py</tt>), which in most cases will look like this:
Escribir el script setup.py en el directorio de nivel superior (por ejemplo, HolaMundo.activity/setup.py), que en la mayoría de los casos se verá asi:


{{ Box File | setup.py | 2=<pre>
{{ Box File | setup.py | 2=<pre>
#!/usr/bin/env python
#!/usr/bin/python
from sugar.activity import bundlebuilder
from sugar.activity import bundlebuilder
bundlebuilder.start()
bundlebuilder.start()
Line 52: Line 44:
}}
}}


Codifique su actividad. El nombre que ha especificado en el archivo .info como "class" es el nombre de la clase que ejecuta el código. Para el archivo anterior activity.info, especificamos un modulo de alto nivel ActividadHolaMundo.ActividadHolaMundo (por favor, tenga en cuenta que el uso de mayúsculas en los nombres de módulos en Python es un estilo pobre, siéntase libre de utilizar el nombre de una actividad con mas estilo de nombres estándar).
A more advanced version, which supports building activity bundles without Sugar installed, looks like this:


{{ Box File | setup.py | 2=<pre>
{{ Box File | ActividadHolaMundo.py | 2=<pre>
from sugar.activity import activity
#!/usr/bin/env python
import logging
try:
from sugar.activity import bundlebuilder
bundlebuilder.start()
except ImportError:
import os
os.system("find ./ | sed 's,^./,HelloWorldActivity.activity/,g' > MANIFEST")
os.system('rm HelloWorldActivity.xo')
os.chdir('..')
os.system('zip -r HelloWorldActivity.xo HelloWorldActivity.activity')
os.system('mv HelloWorldActivity.xo ./HelloWorldActivity.activity')
os.chdir('HelloWorldActivity.activity')
</pre>
}}


import sys, os
*Code your activity in Python. The name you specified in the <tt>.info</tt> file as "<tt>class</tt>" is the name of the class which runs your code. For the <tt>activity.info</tt> file above, we specify a top-level module named <tt>HelloWorldActivity.HelloWorldActivity</tt> (please note that the use of uppercase names in module names is considered poor [[Python Style Guide|Python style]], feel free to use an activity name with more standard style names).
import gtk
{{ Box File | HelloWorldActivity.py | 2=<pre>
from sugar.activity import activity
import logging
import sys, os
import gtk
class HelloWorldActivity(activity.Activity):
def hello(self, widget, data=None):
logging.info('Hello World')
def __init__(self, handle):
print "running activity init", handle
activity.Activity.__init__(self, handle)
print "activity running"
# Creates the Toolbox. It contains the Activity Toolbar, which is the
# bar that appears on every Sugar window and contains essential
# functionalities, such as the 'Collaborate' and 'Close' buttons.
toolbox = activity.ActivityToolbox(self)
self.set_toolbox(toolbox)
toolbox.show()
# Creates a new button with the label "Hello World".
self.button = gtk.Button("Hello World")
# When the button receives the "clicked" signal, it will call the
# function hello() passing it None as its argument. The hello()
# function is defined above.
self.button.connect("clicked", self.hello, None)
# Set the button to be our canvas. The canvas is the main section of
# every Sugar Window. It fills all the area below the toolbox.
self.set_canvas(self.button)
# The final step is to display this newly created widget.
self.button.show()
print "AT END OF THE CLASS"
</pre>
}}


class ActividadHolaMundo(activity.Activity):
The above file is called <tt>HelloWorldActivity.py</tt>
def hola(self, widget, data=None):
logging.info('Hola Mundo')


def __init__(self, handle):
*Create a <tt>MANIFEST</tt> (e.g. <tt>HelloWorldActivity.activity/MANIFEST</tt>), containing the list of the files (relative to the directory that the MANIFEST is in) to include in the package. (Note: Be sure '''not''' to leave blank lines at the end of the file.) This script does that in linux (run it from within the HellowWorldActivity.activity directory):
print "ejecutando actividad init", handle
cd HelloWorldActivity.activity
activity.Activity.__init__(self, handle)
find . -type f | sed 's,^./,,g' > MANIFEST
print "ejecutando actividad"


self.set_title('Hola Mundo')
*Your directory structure should now look like this:
HelloWorldActivity.activity/
HelloWorldActivity.activity/setup.py
HelloWorldActivity.activity/activity
HelloWorldActivity.activity/activity/activity.info
HelloWorldActivity.activity/activity/activity-helloworld.svg
HelloWorldActivity.activity/HelloWorldActivity.py
HelloWorldActivity.activity/MANIFEST


# Crea la caja de Herramientas.Que contiene la Barra de Herramientas de la
*Make sure that all your python files have the required permissions to be used.
# Actividad, que es la barra que aparece en cada ventana del Azucar y contiene
chmod a+x setup.py
# funcionalidades esenciales, como los botones 'Compartir con:' y 'Parar'.
chmod a+x HelloWorldActivity.py
toolbox = activity.ActivityToolbox(self)
self.set_toolbox(toolbox)
toolbox.show()


# Crea un nuevo boton con la etiqueta "Hola Mundo".
*Setup your bundle for development (must be user olpc when you do this) to become user olpc, type: su - olpc
self.button = gtk.Button("Hola Mundo")
# Cuando el boton recibe la seNal de "clicked", llamara a la funcion hola()
# pasando a "None" como argumento. La funcion hola() es definida en
# lineas mas arriba.
self.button.connect("clicked", self.hola, None)
# Ajuste el boton para ser nuestro lienzo. El lienzo es la seccion principal
# de toda Ventana Azucar. Se llena toda el area debajo
# de la caja de herramientas.
self.set_canvas(self.button)
# El paso final es mostrar esta nueva creacion de widgets.
self.button.show()
print "AL FINAL DE LA CLASE"
</pre>
}}


Crear un MANIFEST (por ejemplo, HolaMundo.activity/MANIFEST), que contiene la lista de los archivos a incluir en el paquete. (Nota: Asegúrese de '''no''' dejar líneas en blanco al final del archivo.)
If you are prompted for a password, trying using: su


{{ Box File | | 2=<pre>
python setup.py dev
ActividadHolaMundo.py

</pre>
This just creates a symlink to your activity folder in <tt>~/Activities</tt>, so that Sugar can find your activity.
}}

*Restart Sugar using Ctrl-Alt-Erase and your activity will appear in the interface!

*Run your activity, and if there are errors use the [[Log]] viewer activity to see what went wrong.

== Running ==
If you now run sugar the activity icon should be visible on the frame. (You have to restart sugar to get it to pick up the change if you just installed it. Hit <tt>ctrl-alt-erase</tt>.)

You can also edit the code in your bundle directory directly. Note that the first time your Activity is launched, it leaves a process around even if you close the window, so you must kill the <tt>sugar-activity-factory</tt> to get it to reload when you click again.

== Distribution ==
Create a <tt>.xo</tt> package to distribute your bundle. (An <tt>.xo</tt> file is essentially a zip file built from the MANIFEST with some extra metadata, like a JAR file. It also has some localization ability, and in the future we expect to be able to sign these too.) The bundle name is automatically generated from the '<tt>name</tt>' and '<tt>activity_version</tt>' values found in the <tt>activity.info</tt> file, separated by a dash, with a <tt>.xo</tt> extension.

./setup.py dist_xo

To install the xo on a laptop you can use the installer script.

sugar-install-bundle HelloWorld-1.xo

== Trouble Shooting ==


La estructura del directorio ahora debe verse como:
You can find application logs in /home/olpc/.sugar/default/logs. If the sample fails to compile, sugar will show you the icon in the circle but remain forever at the "Starting..." tag when you hover your mouse over it. You'll have to restart sugar with &lt;ctrl-alt-erase&gt; in order to remove the icon. You can find the cause of your trouble in the the log named for the "service-name" in your activity.info file, in this case "org.laptop.HelloWorldActivity".
HolaMundo.activity/
HolaMundo.activity/setup.py
HolaMundo.activity/activity
HolaMundo.activity/activity/activity.info
HolaMundo.activity/activity/actividad-holamundo.svg
HolaMundo.activity/ActividadHolaMundo.py
HolaMundo.activity/MANIFEST


Instale su paquete para el desarrollo
== See also ==
./setup.py dev


(Esto crea un enlace simbólico en ~/Activities).
* [[Activity bundles]]
* [[Hacking Sugar]]
* [[Localization]] -- you will need to localize your activity to make it accessible to users of the OLPC
* [[Game development HOWTO]]
* [[Textedit Activity]] - simple text editor to support development and testing on the Xo


Si ahora ejecuta el Azúcar, el icono de la actividad debe ser visible en el marco. (Hay que reiniciar el Azúcar para ver el cambio. Pulsa Ctrl-Alt-borrar.)


[[Category:Sugar]]
[[category:groups]]
[[Category:HowTo]]
[[category:peru]]
[[Category:Developers]]

Revision as of 01:10, 14 February 2009

El tutorial explica paso a paso como crear el Paquete de la actividad Hola Mundo.

Se asume que ya ha instalado el entorno de desarrollo Azúcar.

Crear la estructura de directorios del paquete:

mkdir HolaMundo.activity
mkdir HolaMundo.activity/activity

Escribir el archivo activity.info, para describir el paquete en el sub-directorio de la actividad (por ejemplo, HolaMundo.activity/activity/activity.info). Las especificaciones de los Paquetes de Actividad explican en detalle el significado de cada campo.

 File: activity.info
 [Activity]
 name = HolaMundo
 service_name = com.ywwg.HelloWorldActivity
 class = ActividadHolaMundo.ActividadHolaMundo
 icon = actividad-holamundo
 activity_version = 1
 show_launcher = yes

Diseñe un icono para su actividad, de acuerdo con el formato del icono y colóquelo en el sub-directorio "activity". El nombre del archivo debe coincidir con el nombre especificado en el archivo .info (por ejemplo, actividad-holamundo.svg)

 File: actividad-holamundo.svg
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" [
        <!ENTITY fill_color "#FFFFFF">
        <!ENTITY stroke_color "#FF0000">
]>
<svg xmlns="http://www.w3.org/2000/svg" width="50" height="50">
<rect x="1" y="1" width="48" height="48" style="fill:&fill_color;;stroke:&stroke_color;;stroke-width:2"/>
</svg>

Escribir el script setup.py en el directorio de nivel superior (por ejemplo, HolaMundo.activity/setup.py), que en la mayoría de los casos se verá asi:

 File: setup.py
 #!/usr/bin/python
 from sugar.activity import bundlebuilder
 bundlebuilder.start()

Codifique su actividad. El nombre que ha especificado en el archivo .info como "class" es el nombre de la clase que ejecuta el código. Para el archivo anterior activity.info, especificamos un modulo de alto nivel ActividadHolaMundo.ActividadHolaMundo (por favor, tenga en cuenta que el uso de mayúsculas en los nombres de módulos en Python es un estilo pobre, siéntase libre de utilizar el nombre de una actividad con mas estilo de nombres estándar).

 File: ActividadHolaMundo.py
from sugar.activity import activity
import logging

import sys, os
import gtk

class ActividadHolaMundo(activity.Activity):
    def hola(self, widget, data=None):
        logging.info('Hola Mundo')

    def __init__(self, handle):
        print "ejecutando actividad init", handle
        activity.Activity.__init__(self, handle)
        print "ejecutando actividad"

        self.set_title('Hola Mundo')

        # Crea la caja de Herramientas.Que contiene la Barra de Herramientas de la 
        # Actividad, que es la barra que aparece en cada ventana del Azucar y contiene
        # funcionalidades esenciales, como los botones 'Compartir con:' y 'Parar'.
        toolbox = activity.ActivityToolbox(self)
        self.set_toolbox(toolbox)
        toolbox.show()

        # Crea un nuevo boton con la etiqueta "Hola Mundo".
        self.button = gtk.Button("Hola Mundo")
    
        # Cuando el boton recibe la seNal de "clicked", llamara a la funcion hola()
        # pasando a "None" como argumento. La funcion hola() es definida en
        # lineas mas arriba.
        self.button.connect("clicked", self.hola, None)
    
        # Ajuste el boton para ser nuestro lienzo. El lienzo es la seccion principal 
        # de toda Ventana Azucar. Se llena toda el area debajo 
        # de la caja de herramientas.
        self.set_canvas(self.button)
    
        # El paso final es mostrar esta nueva creacion de widgets.
        self.button.show()
    
        print "AL FINAL DE LA CLASE"

Crear un MANIFEST (por ejemplo, HolaMundo.activity/MANIFEST), que contiene la lista de los archivos a incluir en el paquete. (Nota: Asegúrese de no dejar líneas en blanco al final del archivo.)

 File:
 ActividadHolaMundo.py

La estructura del directorio ahora debe verse como:

HolaMundo.activity/
HolaMundo.activity/setup.py
HolaMundo.activity/activity
HolaMundo.activity/activity/activity.info
HolaMundo.activity/activity/actividad-holamundo.svg
HolaMundo.activity/ActividadHolaMundo.py
HolaMundo.activity/MANIFEST

Instale su paquete para el desarrollo

./setup.py dev

(Esto crea un enlace simbólico en ~/Activities).

Si ahora ejecuta el Azúcar, el icono de la actividad debe ser visible en el marco. (Hay que reiniciar el Azúcar para ver el cambio. Pulsa Ctrl-Alt-borrar.)