Top Banner
Application development for the OLPC laptop Program an activity for the XO-1 using Python Skill Level: Intermediate M. Tim Jones ([email protected]) Consultant Engineer Emulex Corp. 18 Dec 2007 The XO laptop (of the One-Laptop-Per-Child initiative) is an inexpensive laptop project intended to help educate children around the world. The laptop includes many innovations, such as a novel, inexpensive, and durable hardware design and the use of GNU/Linux® as the underlying operating system. The XO also includes an application environment written in Python with a human interface called Sugar, accessible to everyone (including kids). Explore the Sugar APIs and learn how to develop and debug a graphical activity in Sugar using Python. Section 1. Before you start This tutorial describes an emulation of the One Child Per Laptop (OLPC) XO laptop using QEMU. This means that you'll emulate a complete XO laptop on a PC (running a Linux® or Microsoft® Windows® operating system) for the purposes of developing a Python activity —that is, a program in the OLPC Sugar interface, which is based on the Python programming language. At the heart of the XO laptop, like most of the cool devices out there, is the Linux operating system. About this tutorial This tutorial shows how to develop Python activities for the XO laptop. From this perspective, you learn about Sugar (the XO user interface, or UI) and the details Application development for the OLPC laptop © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 1 of 25
25

Application development for the OLPC laptop - IBM · PDF fileApplication development for the OLPC laptop Program an activity for the XO-1 using Python Skill Level: Intermediate M.

Mar 13, 2018

Download

Documents

LyMinh
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Application development for the OLPC laptop - IBM · PDF fileApplication development for the OLPC laptop Program an activity for the XO-1 using Python Skill Level: Intermediate M.

Application development for the OLPC laptopProgram an activity for the XO-1 using Python

Skill Level: Intermediate

M. Tim Jones ([email protected])Consultant EngineerEmulex Corp.

18 Dec 2007

The XO laptop (of the One-Laptop-Per-Child initiative) is an inexpensive laptopproject intended to help educate children around the world. The laptop includes manyinnovations, such as a novel, inexpensive, and durable hardware design and the useof GNU/Linux® as the underlying operating system. The XO also includes anapplication environment written in Python with a human interface called Sugar,accessible to everyone (including kids). Explore the Sugar APIs and learn how todevelop and debug a graphical activity in Sugar using Python.

Section 1. Before you start

This tutorial describes an emulation of the One Child Per Laptop (OLPC) XO laptopusing QEMU. This means that you'll emulate a complete XO laptop on a PC (runninga Linux® or Microsoft® Windows® operating system) for the purposes of developinga Python activity —that is, a program in the OLPC Sugar interface, which is basedon the Python programming language. At the heart of the XO laptop, like most of thecool devices out there, is the Linux operating system.

About this tutorial

This tutorial shows how to develop Python activities for the XO laptop. From thisperspective, you learn about Sugar (the XO user interface, or UI) and the details

Application development for the OLPC laptop© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 1 of 25

Page 2: Application development for the OLPC laptop - IBM · PDF fileApplication development for the OLPC laptop Program an activity for the XO-1 using Python Skill Level: Intermediate M.

behind activity development. You also learn about Python programming, Sugarapplication program interfaces (APIs) for Python, and platform emulation withQEMU.

Objectives

In this tutorial, you learn about the XO laptop and how to write a Python activityusing the Sugar UI. Along the way, you learn more about the XO laptop, itsarchitecture, internals, and use.

Prerequisites

This tutorial is written for Linux developers who want to learn more about the XOlaptop and the Sugar UI. It assumes a familiarity with the Linux shell and a basicunderstanding of the Python language.

System requirements

This tutorial provides a hands-on approach to learning about the XO laptop andSugar activities. It assumes a Linux computer with at least 1.1GB of free space.

Section 2. OLPC and the XO laptop

For those new to the XO laptop and the OLPC, this section gives a brief overview.

What's all this, then?

The XO-1 is a laptop computer designed to be inexpensively manufactured anddistributed to children in developing countries around the world. The goal of thislaptop is to bring technology and access to information to children who wouldotherwise not have this ability. The laptop includes wireless networking, allowingchildren to collaborate locally with each other on projects.

The laptop was first proposed by faculty at the Massachusetts Institute ofTechnology (MIT) Media Lab under the non-profit organization, One Laptop PerChild. The organization includes such luminaries as Nicholas Negroponte and, in theearly days, Seymour Papert (a pioneer in the field of artificial intelligence), whose

developerWorks® ibm.com/developerWorks

Application development for the OLPC laptopPage 2 of 25 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 3: Application development for the OLPC laptop - IBM · PDF fileApplication development for the OLPC laptop Program an activity for the XO-1 using Python Skill Level: Intermediate M.

ideas and research are instrumental to the project.

The project has not been without criticism. As a technology, the laptop is novel, butsome wonder whether the money spent on the laptop in some developing countrieswould be better spent elsewhere. For example, some of the target countries for theXO-1 lack the basic elements of education (such as schools or libraries). SeeResources for more details.

The XO-1 laptop

The design of the XO-1 laptop is interesting, because it includes two competingrequirements. First, the XO-1 laptop must be inexpensive (selling for USD140) butalso feature rich. The design includes a 433MHz AMD Geode processor, 128MB ofRAM, 1GB of NAND flash (instead of a hard disk), a 7 1/2-inch dual-mode LCD,wireless networking, and even a video camera. The laptop is also designed to beoperated in non-traditional environments and is therefore very durable and rugged(see Figure 1).

Figure 1. The XO-1 laptop

Wireless networking is based on an 802.11b/g and 802.11s chip, which supportsboth standard networking and mesh networking. This allows laptops toautonomously route packets between themselves in a peer-to-peer network (withoutthe need for a separate router). The mesh networking works even if the CPU ispowered off.

Software

While the ideas behind the XO-1 laptop are intriguing, and its physical and hardwaredesign make it novel, what's most interesting is the software. The XO-1 laptop ispowered by GNU/Linux (a minimal version based on the Fedora project). The basicinput/output system (BIOS) is the Open Firmware, which is written in a variant ofForth. The graphical user interface (GUI), called Sugar, is based on the X windowing

ibm.com/developerWorks developerWorks®

Application development for the OLPC laptop© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 3 of 25

Page 4: Application development for the OLPC laptop - IBM · PDF fileApplication development for the OLPC laptop Program an activity for the XO-1 using Python Skill Level: Intermediate M.

system and written in Python. This is by far the most interesting element, because itmakes the XO-1 an immediate development environment. (Python is an interpretedlanguage.) No compilers are necessary, and anyone can develop Sugar activities(that is, applications in the Sugar GUI). In other words, all software on the XO-1laptop is open source and therefore free and modifiable.

This use of Python is interesting, because as the core of the XO-1 laptop, it exposesPython to millions of children around the world. Python was created as a language tolearn programming, so it was an ideal decision and has the potential to create a newpopulation of Python enthusiasts.

Section 3. XO laptop emulation

This section gives instructions for downloading and installing the QEMU platformemulator and the XO-1 laptop image.

Introduction to QEMU

QEMU is a platform virtualization application that allows you to emulate an entirecomputer (processors and associated peripherals) for purposes of virtualizinganother operating system on it. With this, you can emulate Linux on Windows,Windows on Linux, or any other operating system on another operating system thatruns QEMU. You can even emulate an operating system for a different architecturethan the host. For example, you can emulate an Arm Linux system on an x86 host.

A system emulation is made up of the platform emulator (QEMU), an optionalaccelerator (KQEMU), and a root image (a file in the host operating system) thatcontains both the kernel and the root file system. For more details on QEMU and itsinternal operation, see Resources.

Download and install QEMU

Installing QEMU and the accelerator is as simple as you would expect withGNU/Linux. Listing 1 provides the QEMU download, build, and installationinstructions.

Listing 1. Downloading, building, and installing QEMU

$ wget

developerWorks® ibm.com/developerWorks

Application development for the OLPC laptopPage 4 of 25 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 5: Application development for the OLPC laptop - IBM · PDF fileApplication development for the OLPC laptop Program an activity for the XO-1 using Python Skill Level: Intermediate M.

http://fabrice.bellard.free.fr/qemu/qemu-0.9.0.tar.gz$ tar xfvz qemu-0.9.0.tar.gz$ cd qemu-0.9.0$ ./configure$ make$ make install$

The QEMU accelerator is an optional step, but I recommend it because it results ingreater performance. Listing 2 gives the QEMU accelerator download, build, andinstallation instructions.

Listing 2. Downloading, building, and installing the QEMU accelerator

$ wgethttp://fabrice.bellard.free.fr/qemu/kqemu-1.3.0pre11.tar.gz$ tar xvfz kqemu-1.3.0pre11.tar.gz$ cd kqemu-1.3.0pre11$ ./configure$ make$ make install$ insmod kqemu.ko

Note: At the end of Listing 2, the QEMU accelerator kernel module is installed.

Get the XO kernel and file system images

The final step in preparation is to download and prepare the QEMU image for theXO-1 laptop. Listing 3 shows how to retrieve this image and extract it prior to use.The image is quite large (183MB), so the download time can be long. Also, thedownloaded image expands to almost 1GB in size, so make sure that you havesufficient space available.

Listing 3. Download and extract the OLPC image

$ wgethttp://olpc.download.redhat.com/olpc/streams/development/LATEST-STABLE-BUILD/devel_ext3/olpc-redhat-stream-development-devel_ext3.img.bz2$ bunzip2olpc-redhat-stream-development-devel_ext3.img.bz2

Start the XO-1 laptop

With the OLPC image downloaded and extracted, it's time for a test run. Start QEMUwith two options that specify the amount of memory to make available (256MB) andthe hard disk to use for the emulation (the image you downloaded above):

ibm.com/developerWorks developerWorks®

Application development for the OLPC laptop© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 5 of 25

Page 6: Application development for the OLPC laptop - IBM · PDF fileApplication development for the OLPC laptop Program an activity for the XO-1 using Python Skill Level: Intermediate M.

$ qemu -m 256 -hdaolpc-redhat-stream-development-devel_ext3.img

You should then see the standard Linux boot from GNU GRUB (GRand Unified Bootloader). At the end is the startup window, which requests that you provide a username (see Figure 2). After you provide a name, you can optionally change the colorscheme. In the end, you'll end up with the home screen for the XO-1 laptop, whichyou explore in the next section.

Figure 2. First-time login for the XO-1 laptop

If you'd like to leave QEMU and return the mouse context to your host operatingsystem, press Ctrl-Alt. To return to the XO-1, click within the Sugar frame, and themouse context returns to QEMU.

Section 4. Navigating Sugar

developerWorks® ibm.com/developerWorks

Application development for the OLPC laptopPage 6 of 25 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 7: Application development for the OLPC laptop - IBM · PDF fileApplication development for the OLPC laptop Program an activity for the XO-1 using Python Skill Level: Intermediate M.

Now that you're logged in and ready to start, explore the OLPC Sugar UI.

Home mode and the frame

The main window in Sugar is called Home mode (see Figure 3). This window isbasically the desktop and tells you about your environment, activities, and so on. Inthe center of the window is the XO icon, which represents you and your laptop. Ifother users were visible to you wirelessly, you would see them, as well. To shutdown the laptop, place the mouse cursor over the X icon, then click the shutdownoption.

Figure 3. Home mode for the XO-1 laptop

The ring around your laptop shows you the activities that are currently running. Youcan click any icon here to return to a running activity. To return to Home mode, movethe mouse to a corner of the window. Doing so returns the frame to view. Notice thefour circle "zoom" icons at the top left of the frame: The last represents the mostrecently accessed activities. Clicking this icon takes you back to that activity (whichoccupies the entire window). The second-to-last icon (the icon with a single dot inthe center) represents the Home window. Clicking this icon takes you back to Home

ibm.com/developerWorks developerWorks®

Application development for the OLPC laptop© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 7 of 25

Page 8: Application development for the OLPC laptop - IBM · PDF fileApplication development for the OLPC laptop Program an activity for the XO-1 using Python Skill Level: Intermediate M.

mode. The next icon (the icon with three dots) shows you the groups, which are localfriends and the activities that they're running. Finally, the first icon (the icon withmany dots) represents the entire neighborhood. This icon shows all users and theactivities they're sharing.

Start an activity

At the bottom of the frame is the collection of activities that you can run. An activity isan application; as you saw in Figure 3, the XO-1 laptop supports several activities.Sugar comes equipped with a Web browser, a calculator, a paint program, a newsreader, and other programs that you can share with other users to collaborate onprojects. To start an activity, click that activity's icon in the lower part of the frame. InFigure 4, I've started the Write activity and added some text.

Figure 4. A running activity in Sugar

Control keys

Using the mouse to navigate is simple enough, but Sugar allows control keys for

developerWorks® ibm.com/developerWorks

Application development for the OLPC laptopPage 8 of 25 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 9: Application development for the OLPC laptop - IBM · PDF fileApplication development for the OLPC laptop Program an activity for the XO-1 using Python Skill Level: Intermediate M.

faster transitions between applications and modes. Table 1 lists several importantcontrol sequences that you can use to easily switch between modes.

Table 1. Control sequences for switching between modesControl key Action

F1 Switch to neighborhood view

F2 Switch to group view

F3 Switch to home mode

F4 Switch to the last activity

Developer console

Because Sugar is built on the Linux operating system, development work requiresaccess to a shell. You can access the shell by pressing Alt-=, which brings up a loginprompt. From here, type root to call up a friendly Bash prompt. You can alsoaccess a shell through the developer's console, shown in Figure 5. This consoleincludes five tabs for accessing a resource panel, a log viewer, a presence panel (forwireless attached XO-1 laptops), and a terminal (Bash shell), respectively.

Figure 5. The developer console

ibm.com/developerWorks developerWorks®

Application development for the OLPC laptop© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 9 of 25

Page 10: Application development for the OLPC laptop - IBM · PDF fileApplication development for the OLPC laptop Program an activity for the XO-1 using Python Skill Level: Intermediate M.

Whenever you want to return to Sugar, press Ctrl-Alt-F3. The shell remains active,so you can conveniently switch back and forth between Sugar and Bash.

Other shortcuts include Alt-F to toggle the frame (that is, the border around thewindow) on and off. You can exit the current activity by pressing Alt-C and terminatethe Sugar GUI by pressing Ctrl-Alt-Backspace.

Extend the XO laptop

Downloading a file system image for the XO-1 laptop means that you get a kerneland root file system in one. The file system contains all the necessary applicationsand OLPC components to power the XO-1 laptop. But this doesn't mean that youcan't extend the software. One of the resident packages in the file system, YUM(Yellow-dog Updated, Modified), is a package-management system that simplifiesthe downloading, installation, and configuration of software packages.

With YUM, you can download and install new packages as well as update allexisting packages on a system. For example, Listing 4 shows how to updatepackages that have changed since the last update.

developerWorks® ibm.com/developerWorks

Application development for the OLPC laptopPage 10 of 25 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 11: Application development for the OLPC laptop - IBM · PDF fileApplication development for the OLPC laptop Program an activity for the XO-1 using Python Skill Level: Intermediate M.

Listing 4. Using YUM to install new updates

-bash-3.2# yum -y updateLoading "installonlyn" pluginSetting up Update Processolpc_development 100%|==========================| 1.1 kB 00:00primary.xml.gz 100%|==========================| 2.9 MB 00:17olpc_devel:###################################################11448/11448olpc_devel_kernel_repo 100%|==========================| 951 B 00:00olpc_devel:################################################### 23/23No Packages marked for Update/Obsoletion-bash-3.2#

Section 5. Working with Python

This section briefly introduces Python programming. If you're already familiar withPython, you can skip this section and go to a review of the Sugar APIs.

What is Python?

It's not surprising that Python was chosen as the core of the XO-1 laptop. Mostimportantly, Python is an open source language, which means that you can see thesource, modify it, and improve it. Python is a very clean language that is simple andincludes a large library of APIs to simplify the task of programming complexapplications.

Python is also an interpreted language, which means that it's easy to prototypeactivities without the step of compilation. You can compile Python for speed, or youcan use libraries programmed in lower-level languages for greater performance.

While Python was originally developed as a new language to help users learnprogramming (the BASIC of today), its simplicity and power are appreciated bybeginning and advanced developers alike.

Python by (short) example

Listing 5 provides a simple Python program that introduces the language and its use.The Python program begins by opening a file (the name of the program itself) for

ibm.com/developerWorks developerWorks®

Application development for the OLPC laptop© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 11 of 25

Page 12: Application development for the OLPC laptop - IBM · PDF fileApplication development for the OLPC laptop Program an activity for the XO-1 using Python Skill Level: Intermediate M.

reading. The handle to this open file is stored in the infile variable (whose type isdetermined as it's assigned). Next, a simple for loop is started using an iterator.(Note the use of the in keyword, which creates an iterator.) This for loop simplysays, "for each line in the file, do."

The internals of the loop are shown indented (which is Python's way of establishinga block). The block for this for loop is to emit the line that was just read. The printstatement emits the information shown, and the trailing comma (,) indicates that youdon't want an \n character emitted at the end (because it's already contained in theline string).

Listing 5. File input and iteration

infile = file('pythprog.py', 'r')for line in infile:

print 'Read: ', line,

Iterators are an important part of Python and one of the main reasons the languageis so simple and readable.

Python programming paradigms

In addition to being simple, Python as a multi-paradigm language supports varyingstyles of application development. Here are a few examples to help you explorewhat is meant by multi-paradigm.

Imperative programming

Python supports imperative programming, which focuses on sequences ofstatements to be performed. An imperative program is shown in Listing 6. In thisexample, you create a function (with the def, or define, statement). Afterwards, youcall this new function with the filename argument.

Listing 6. A simple imperative program

def print_file(filename):infile = file(filename, 'r')for line in infile:

print 'Read: ', line,

print_file("pythprog.py")

Object-oriented programming

You can also program in the object-oriented paradigm, which focuses on classesand methods that operate on data within the instance of the class. As shown in

developerWorks® ibm.com/developerWorks

Application development for the OLPC laptopPage 12 of 25 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 13: Application development for the OLPC laptop - IBM · PDF fileApplication development for the OLPC laptop Program an activity for the XO-1 using Python Skill Level: Intermediate M.

Listing 7, the class contains two methods. The first method is __init__(), which isthe constructor for the class. The second method is the one that performs the print ofthe file. Use of this class and calling the method is shown following definition of theclass.

Listing 7. A simple object-oriented program

class PrintFile():

def __init__(self, filename):self.filename = filename

def printit(self):infile = file(self.filename, 'r')for line in infile:

print 'Read: ', line,

myPF = PrintFile("pythprog.py")myPF.printit()

Functional programming and mixed-paradigm programming

Python also supports functional programming and mixed-paradigm programming,which allow you to, for example, use functional language concepts within anobject-oriented application.

Section 6. The Sugar interface

This section introduces you to the architecture of Sugar and the elements necessaryfor building a graphical activity in Sugar.

Sugar architecture

Sugar is a collection of core libraries and widgets that implement the GUI and itsinterfaces for activity development. Figure 6 shows a partial view of the Sugararchitecture.

Figure 6. Partial view of the Sugar architecture

ibm.com/developerWorks developerWorks®

Application development for the OLPC laptop© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 13 of 25

Page 14: Application development for the OLPC laptop - IBM · PDF fileApplication development for the OLPC laptop Program an activity for the XO-1 using Python Skill Level: Intermediate M.

As you can see from Figure 6, the architecture consists of the following elements:

• Activity class: At the base (for an activity) is the Activity class.(This class is discussed in detail in the next section, Structure of a newactivity). This class is the basic interface of an activity in Sugar.

• Clipboard: The clipboard provides an interface to the clipboard service (asimplified API over the dbus) for adding, retrieving, or removing objectsfrom the clipboard.

• Logger: The logger module provides your activity with an interface foremitting log (text) information as well as setting filtering options.

• Datastore: The datastore package allows your activity to store andretrieve information in a simple and convenient way for current executionof an activity.

• Env: Module env provides a collection of file path functions for the Sugarenvironment.

• Graphics: The graphics package provides an assortment of classes forgraphics and their controls.

• Presence: The presence package provides the means of collaborating onactivities with other laptops. It extends several services for native networkpresence and information sharing.

• Profile class: Finally, the profile class provides a way to storeuser-specific options and settings.

Activity class

developerWorks® ibm.com/developerWorks

Application development for the OLPC laptopPage 14 of 25 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 15: Application development for the OLPC laptop - IBM · PDF fileApplication development for the OLPC laptop Program an activity for the XO-1 using Python Skill Level: Intermediate M.

The Activity class is the base class for all user-developed activities (a subclass ofGtkWindows) and is the way that your activity hooks into Sugar. The Activityclass provides the means for Sugar to launch your activity when requested from amouse event.

In addition to providing a way to invoke the activity from the Sugar desktop, theactivity classes provide several other useful capabilities. For example, the activitycan request to be shared, making it available for collaboration with other users onthe network. The method share identifies whether the activity should be publiclyvisible or shared by invitation only. The Activity inherits literally hundreds ofmethods from other classes such as Window Container, Widget, Object, andGInterface.

PyGTK

The Sugar UI is based on the Python GIMP Toolkit (PyGTK). GTK is a multi-platformAPI that includes a comprehensive set of libraries for developing graphicalapplications.

PyGTK is the Python interface to the GTK+ toolkit and is based on three libraries:

• GLib: GLib is the low-level library and forms the core of GTK+. It providesinterfaces for run time functionality (such as threads, dynamic loading,and the object system).

• Pango: The Pango library consists of APIs for text layout and rendering.

• ATK: The ATK library defines a set of interfaces for accessibility(including tools such as magnifiers, screen readers, and support foralternative input devices).

In the next section, you use PyGTK, events, and callbacks to develop a simplegraphical activity.

Section 7. Structure of a new activity

In this section, you develop a new activity and explore the process of integrating withSugar.

Basic architecture

ibm.com/developerWorks developerWorks®

Application development for the OLPC laptop© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 15 of 25

Page 16: Application development for the OLPC laptop - IBM · PDF fileApplication development for the OLPC laptop Program an activity for the XO-1 using Python Skill Level: Intermediate M.

Developing a Sugar activity (based on PyGTK) requires a slightly different paradigmthan you may be used to. PyGTK is an event-driven toolkit, which means that youinstall callbacks for events of interest, and then control is released to Sugar.

Events, such as mouse movement, a button press, loss or gain of focus in a window,or the click of a mouse button, occur within the window. When these events occur, asignal is emitted by the "widget" that they affect. For example, the mouse click mayoccur within a window, or the click could have been performed on a button. Thewidgets associated with these two events are different, and they may result indifferent actions. For this reason, each widget can support its own set of callbacksfor the variety of events that it supports.

For each widget for which you want to support some kind of feedback, you create acallback function, and then tie the callback to the event for the widget. This processforms the basis for control in a graphical activity.

In this activity, you draw a colored rectangle, and then draw a smaller coloredrectangle at each point in the window at which the user presses the left mousebutton.

The __init__ method

Let's start with a discussion of the constructor for your activity (in addition to thebasic class definition). Listing 8 provides the class and __init__ method(). (Icover the callbacks shortly.) First, you must import the modules that you use in thisactivity. Next, declare your class, which uses as its base class the Activity class.Recall that the Activity class serves as your hook into the Sugar infrastructure.

Listing 8. The class and __init__ constructor method (ExampleActivity.py).

import pygtkpygtk.require('2.0')import gtk, sys, random, time

from sugar.activity import activity

class ExampleActivity(activity.Activity):

def __init__(self, handle):activity.Activity.__init__(self, handle)

self.set_title("Simple GraphicalActivity")

# Show the toolbox elementstoolbox = activity.ActivityToolbox(self)self.set_toolbox(toolbox)toolbox.show()

# Register the event callbacksself.connect("expose_event",

self.area_expose_cb)

developerWorks® ibm.com/developerWorks

Application development for the OLPC laptopPage 16 of 25 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 17: Application development for the OLPC laptop - IBM · PDF fileApplication development for the OLPC laptop Program an activity for the XO-1 using Python Skill Level: Intermediate M.

self.connect("key_press_event",self.keypress_cb)

self.connect("button_press_event",self.button_press_cb)

self.show()

# Seed the random number generatorrandom.seed(time.time())

self.area = self.windowself.gc = self.area.new_gc()

# Allocate a color dictionaryself.colors = {}self.colormap = self.gc.get_colormap()self.colors[0] =

self.colormap.alloc_color('green')self.colors[1] =

self.colormap.alloc_color('blue')self.colors[2] =

self.colormap.alloc_color('black')self.colors[3] =

self.colormap.alloc_color('red')

# Register for eventsself.area.set_events(

gtk.gdk.EXPOSURE_MASK |gtk.gdk.KEY_PRESS_MASK |gtk.gdk.LEAVE_NOTIFY_MASK |gtk.gdk.BUTTON_PRESS_MASK )

The __init__() method is the constructor and is called as an instance is createdfor this class (that is, when the Sugar user clicks its icon). It begins by calling theactivity constructor (to allow it to do its initialization). Next, you provide a simple title.A toolbox is created, which appears at the top of the window when the activity hasbegun. This toolbox provides an exit button and other tools.

Next, register your callbacks for the events that you're interested in. Another way tothink about this is that you're creating signal handlers for the signals of interest(much like X). As shown, the connect() method ties a particular event to acallback. The expose_event can occur for numerous reasons (such as the windowbeing exposed), but the result should be a redraw of the window. Thekey_press_event indicates that a key was pressed on the keyboard while thewindow was in focus. Finally, the button_press_event indicates that a mousebutton was pressed in the window. Each event is associated with its own callback.

Notice the random number generator with a call to the seed() method of therandom module. You save the window in an instance variable called area, and thena new graphics context is created with a call to new_gc().

The next step is to create a color dictionary (colors). A dictionary is a hash inPython that allows you to create an array to associate values with other values. Youuse it here as an array, but the index could have just as well been another type.

Finally, you enable receipt of events with a call to set_events(). This method

ibm.com/developerWorks developerWorks®

Application development for the OLPC laptop© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 17 of 25

Page 18: Application development for the OLPC laptop - IBM · PDF fileApplication development for the OLPC laptop Program an activity for the XO-1 using Python Skill Level: Intermediate M.

represents a bitmask and tells PyGTK to send those signals when they occur in yourcontext.

Event callbacks

The callbacks (and the method you use to draw in the window) are shown in Listing9.

Listing 9. The event callbacks and draw_box method (ExampleActivity.py part2)

def draw_box(self, x, y):self.gc.set_foreground(

self.colors[random.randint(1,3)] )self.area.draw_rectangle(self.gc, True, x,

y, 50, 50)

def area_expose_cb(self, area, event):self.gc_set_foreground(self.colors[0])self.area.draw_rectangle(self.gc, True,

200, 200, 400, 400)

return True

def keypress_cb(self, widget, event):sys.exit()

def button_press_cb(self, widget, event):if event.button == 1:

self.draw_box(event.x, event.y)

return True

The first callback, draw_box, is used to draw a new box (upon user request). Themethod takes self (representing the instance of this class), and then the x and ypositions to draw. The foreground color is set with a random color from the dictionary(with the key of the dictionary being provided as a random index). Thedraw_rectangle() method is used to draw a filled rectangle, providing thegraphics context, location, and size.

The area_expose_cb callback is used to redraw the window. This callback occursif the window is exposed (focus returns to it, for example). The foreground color isset (using the first index of the color dictionary, so the color green is used), and thena large rectangle is drawn.

The keypress_cb callback is called when a key is pressed in the current window.For this event, simply exit the activity.

Finally, the button_press_cb callback is called when a mouse button is pressedin the window. The callback checks to see whether the left button was pressed; if itwas, it calls the draw_box() method to draw a new box at the current location of

developerWorks® ibm.com/developerWorks

Application development for the OLPC laptopPage 18 of 25 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 19: Application development for the OLPC laptop - IBM · PDF fileApplication development for the OLPC laptop Program an activity for the XO-1 using Python Skill Level: Intermediate M.

the cursor in the window.

Section 8. Installing a new activity

This section explores how to integrate a Sugar activity into the desktop. It integratesthe simple graphical activity you developed in the last section into Sugar forexecution from home mode.

Getting to the shell

The first step is to get to the Linux shell, which is easily accomplished from homemode by pressing Alt-Ctrl-F1. Log in as root, which requires no password. Fromhere, change to the olpc user, as shown in Listing 10.

Listing 10. Getting to the shell for user olpc

-bash-3.2# su - olpc[olpc@xo-12-34-56 ~]$ pwd/home/olpc[olpc@xo-12-34-56 ~]$

At this point, you're in the /home/olpc directory, which is right where you want to be.Create a new directory here (call it ExampleActivity), and change the directory to it:

[olpc@xo-12-34-56 ~]$ mkdir ExampleActivity[olpc@xo-12-34-56 ~]$ cd ExampleActivity[olpc@xo-12-34-56 ExampleActivity]$

The activity directory

In this directory (/home/olpc/ExampleActivity), place (that is, type in) the source filecalled ExampleActivity.py (the concatenation of Listing 8 and Listing 9). You'll alsowant the file shown in Listing 11 in the same directory. This is a special file for Sugarthat bundles the activity for use.

Listing 11. setup.py

#!/usr/bin/env pythonfrom sugar.activity import bundlebuilderif __name__ == "__main__":

ibm.com/developerWorks developerWorks®

Application development for the OLPC laptop© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 19 of 25

Page 20: Application development for the OLPC laptop - IBM · PDF fileApplication development for the OLPC laptop Program an activity for the XO-1 using Python Skill Level: Intermediate M.

bundlebuilder.start("ExampleActivity")

When this file is created, ensure that it's executable. To do so, type:

[olpc@xo-12-34-56 ExampleActivity]$ chmod +x setup.py[olpc@xo-12-34-56 ExampleActivity]$

Create the support files

Just a few more support files, and you're done. In the ExampleActivity subdirectory,create a new directory called activity, and then change directory into it:

[olpc@xo-12-34-56 ExampleActivity]$ mkdir activity[olpc@xo-12-34-56 ExampleActivity]$ cd activity[olpc@xo-12-34-56 activity]$

Two additional support files are needed here, representing the icon to use for theactivity in Sugar, and an information file to represent the activity, respectively. Theicon file (a Scalable Vector Graphics [SVG] file) is provided in Listing 12, and theinformation file is shown in Listing 13.

Listing 12. The SVG icon file for the activity (ExampleActivity.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 "#000000">

]><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>

Listing 13. The activity information file (activity.info)

[Activity]name = ExampleActivityservice_name = org.laptop.ExampleActivityclass = ExampleActivity.ExampleActivityicon = ExampleActivityactivity_version = 1show_launcher = yes

Finally, go back up to the /home/olpc/ExampleActivity directory, and then create afile called MANIFEST, which will contain a single line:

developerWorks® ibm.com/developerWorks

Application development for the OLPC laptopPage 20 of 25 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 21: Application development for the OLPC laptop - IBM · PDF fileApplication development for the OLPC laptop Program an activity for the XO-1 using Python Skill Level: Intermediate M.

ExampleActivity.py

This file represents the source files that make up the package. The directorystructure should now appear with the files defined in Listing 14.

Listing 14. Structure and files of the ExampleActivity package

/home/olpc/ExampleActivity//home/olpc/ExampleActivity/ExampleActivity.py/home/olpc/ExampleActivity/MANIFEST/home/olpc/ExampleActivity/setup.py/home/olpc/ExampleActivity/activity//home/olpc/ExampleActivity/activity/ExampleActivity.svg/home/olpc/ExampleActivity/activity/activity.info

Install the new bundle

Before you start the installation, be aware that you may have to provide the symbolSUGAR_PATH. If you type echo $SUGAR_PATH and a blank line results, type thefollowing:

[olpc@xo-12-34-56 ExampleActivity]$ exportSUGAR_PATH=/share/sugar[olpc@xo-12-34-56 ExampleActivity]$

Now, use the cd command in the root directory of your package (that is, cd/home/olpc/ExampleActivity), and then type:

[olpc@xo-12-34-56 ExampleActivity]$ python setup.py dev

Doing so creates a symbolic link from the Activities subdirectory (in /home/olpc) toyour package directory. You can now test your new activity from Sugar.

Test the activity

To test the activity, first return to Sugar's home mode. To do this, press Ctrl-Alt-F3.Next, restart Sugar to make the activity visible. To restart Sugar, pressCtrl-Alt-Backspace. The terminal window reappears for a few seconds, and Sugarrestarts. In the frame at the bottom of home mode, a new icon appears (as an emptybox). Place your mouse cursor over this icon to display the activity name(ExampleActivity). Click the icon, and the new activity appears (consuming the entirescreen). After left-clicking a few times in the green square, the window shown in

ibm.com/developerWorks developerWorks®

Application development for the OLPC laptop© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 21 of 25

Page 22: Application development for the OLPC laptop - IBM · PDF fileApplication development for the OLPC laptop Program an activity for the XO-1 using Python Skill Level: Intermediate M.

Figure 7 appears.

Figure 7. The finished simple activity

Distribute your bundle

If you wanted to distribute your activity for others to use, an additional step isrequired. In the ExampleActivity subdirectory, type the following command to createa bundle (which contains all the necessary files for the activity):

[olpc@xo-12-34-56 ExampleActivity]$ python setup.py dist

The result is a file called ExampleActivity-1.xo, which can be distributed to others.Other users can migrate this file to their laptops and install it using thesugar-install-bundle command. For example:

[olpc@xo-12-34-56 ExampleActivity]$ sugar-install-bundleExampleActivity-1.xo

developerWorks® ibm.com/developerWorks

Application development for the OLPC laptopPage 22 of 25 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 23: Application development for the OLPC laptop - IBM · PDF fileApplication development for the OLPC laptop Program an activity for the XO-1 using Python Skill Level: Intermediate M.

Section 9. Summary

The XO-1 laptop has entered mass production, so the product is now a reality. At thetime of this writing, the OLPC foundation offered XO-1 laptops for sale at USD399(which purchased two laptops: one for yourself and one for a child in a developingnation). The Linux kernel and user-space software continue development and haveevolved nicely over the past six months. The software framework is very stable, andthe APIs solid enough for developers not closely related to the project.

You'll also find a large number of applications developed for Sugar, includingdevelopment tools (see Resources for more detail). Bindings for languages otherthan Python have appeared as well, so soon you'll be able to develop applications inJavaScript and other languages. It will be interesting to see what evolves from theXO-1 laptop after it gets into the hands of the children of the world. It could be aprogramming revolution, with Linux and Python leading the way.

ibm.com/developerWorks developerWorks®

Application development for the OLPC laptop© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 23 of 25

Page 24: Application development for the OLPC laptop - IBM · PDF fileApplication development for the OLPC laptop Program an activity for the XO-1 using Python Skill Level: Intermediate M.

Resources

Learn

• In Tim's article "Sugar, the XO laptop, and One Laptop per Child"(developerWorks, Apr 2007), take a tour of Sugar, the XO laptop's novel userinterface.

• In this developerWorks interview with OLPC visionary Walter Bender(developerWorks, Apr 2007), hear about the OLPC vision, challenges faced,and progress to date.

• The official OLPC Web site introduces the philosophy and vision of the OLPCproject and explores how the laptop will benefit children around the world.

• Wikipedia has a great introduction to the XO-1 laptop, it's history, design,software, and features. The laptop is novel, but some critics wonder whether themoney spent on the laptop in some developing countries would be better spentelsewhere.

• This Sugar activity tutorial has introduced many developers to developing withSugar.

• The Open Firmware standard (described by the IEEE) is the basis for the XO-1BIOS. In the spirit of open source firmware, even the XO's BIOS is open source.

• Python is a great language for beginners and experienced programmers alike.It's a multi-paradigm language that can be used in interpretive or compiledforms. Its official Web site provides a wealth of information, includingdocumentation and many tutorials.

• In "System emulation with QEMU" (developerWorks, September 2007), learnabout QEMU and its use as a platform emulator. This article introduces you tovirtualization, then discusses the internals of QEMU and its use. For more detailon virtualization and the range of Linux solutions, check out "Virtual Linux"(developerWorks, December 2006).

• A list of activities and projects for the XO-1 is on the laptop.org site. In the earlydays, the list was sparse, but today you'll find a large number of activitiesranging from educational activities, audio and video players, media-creationtools, programming tools, and necessary network applications (such asbrowsers, feed-readers, and mail programs). You'll even find a variety ofgames. (Python is a great language for game development.)

• Sugar is based on the Python GTK (PyGTK), which is a GUI toolkit with Pythonbindings. PyGTK is multi-platform and was a great choice for the XO-1. At thePyGTK Web site, you'll find a wealth of information, including several tutorials.The Sugar APIs are large and extensive, as shown in the OLPC Sugar UserInterface list.

developerWorks® ibm.com/developerWorks

Application development for the OLPC laptopPage 24 of 25 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 25: Application development for the OLPC laptop - IBM · PDF fileApplication development for the OLPC laptop Program an activity for the XO-1 using Python Skill Level: Intermediate M.

• In the developerWorks Linux zone, find more resources for Linux developers,and scan our most popular articles and tutorials.

• See all Linux tips and Linux tutorials on developerWorks.

• Stay current with developerWorks technical events and Webcasts.

Get products and technologies

• The OLPC organization is running a limited-time "Give One Get One" program.For a donation of a set amount, the organization will send one XO laptop to achild in a developing nation and one to you.

• Order the SEK for Linux, a two-DVD set containing the latest IBM trial softwarefor Linux from DB2®, Lotus®, Rational®, Tivoli®, and WebSphere®.

• With IBM trial software, available for download directly from developerWorks,build your next development project on Linux.

Discuss

• Get involved in the developerWorks community through blogs, forums,podcasts, and community topics in our new developerWorks spaces.

About the author

M. Tim JonesM. Tim Jones is an embedded software engineer and the author of GNU/LinuxApplication Programming, AI Application Programming (now in its second edition),and BSD Sockets Programming from a Multilanguage Perspective. His engineeringbackground ranges from the development of kernels for geosynchronous spacecraftto embedded systems architecture and networking protocols development. Tim is aConsultant Engineer for Emulex Corp. in Longmont, Colorado.

Trademarks

Linux is a registered trademark of Linus Torvalds in the United States, othercountries, or both.Microsoft and Windows are trademarks of Microsoft Corporation in the United States,other countries, or both.Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc., in theUnited States, other countries, or both.

ibm.com/developerWorks developerWorks®

Application development for the OLPC laptop© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 25 of 25