sugar3.activity.activity module

Activity

A definitive reference for what a Sugar Python activity must do to participate in the Sugar desktop.

Note

This API is STABLE.

The Activity class is used to derive all Sugar Python activities. This is where your activity starts.

Derive from the class

from sugar3.activity.activity import Activity

class MyActivity(Activity):
    def __init__(self, handle):
        Activity.__init__(self, handle)

An activity must implement a new class derived from Activity.

Name the new class MyActivity, where My is the name of your activity. Use bundle metadata to tell Sugar to instantiate this class. See bundle for bundle metadata.

Create a ToolbarBox

In your __init__() method create a ToolbarBox, with an ActivityToolbarButton, a StopButton, and then call set_toolbar_box().

from sugar3.activity.activity import Activity
from sugar3.graphics.toolbarbox import ToolbarBox
from sugar3.activity.widgets import ActivityToolbarButton
from sugar3.activity.widgets import StopButton

class MyActivity(Activity):
    def __init__(self, handle):
        Activity.__init__(self, handle)

        toolbar_box = ToolbarBox()
        activity_button = ActivityToolbarButton(self)
        toolbar_box.toolbar.insert(activity_button, 0)
        activity_button.show()

        separator = Gtk.SeparatorToolItem(draw=False)
        separator.set_expand(True)
        toolbar_box.toolbar.insert(separator, -1)
        separator.show()

        stop_button = StopButton(self)
        toolbar_box.toolbar.insert(stop_button, -1)
        stop_button.show()

        self.set_toolbar_box(toolbar_box)
        toolbar_box.show()

Journal methods

In your activity class, code read_file() and write_file() methods.

Most activities create and resume journal objects. For example, the Write activity saves the document as a journal object, and reads it from the journal object when resumed.

read_file() and write_file() will be called by the toolkit to tell your activity that it must load or save the data the user is working on.

Activity toolbars

Add any activity toolbars before the last separator in the ToolbarBox, so that the StopButton is aligned to the right.

There are a number of standard Toolbars.

You may need the EditToolbar. This has copy and paste buttons. You may derive your own class from EditToolbar:

from sugar3.activity.widgets import EditToolbar

class MyEditToolbar(EditToolbar):
    ...

See EditToolbar for the methods you should implement in your class.

You may need some activity specific buttons and options which you can create as toolbars by deriving a class from Gtk.Toolbar:

class MySpecialToolbar(Gtk.Toolbar):
    ...

Sharing

An activity can be shared across the network with other users. Near the end of your __init__(), test if the activity is shared, and connect to signals to detect sharing.

if self.shared_activity:
    # we are joining the activity
    self.connect('joined', self._joined_cb)
    if self.get_shared():
        # we have already joined
        self._joined_cb()
else:
    # we are creating the activity
    self.connect('shared', self._shared_cb)

Add methods to handle the signals.

Read through the methods of the Activity class below, to learn more about how to make an activity work.

Hint: A good and simple activity to learn from is the Read activity. You may copy it and use it as a template.

class sugar3.activity.activity.Activity(handle, create_jobject=True)

Bases: sugar3.graphics.window.Window, gi.overrides.Gtk.Container

Initialise an Activity.

Parameters
  • handle (ActivityHandle) – instance providing the activity id and access to the presence service which may provide sharing for this application

  • create_jobject (boolean) – DEPRECATED: define if it should create a journal object if we are not resuming. The parameter is ignored, and always will be created a object in the Journal.

Signals:
  • shared - the activity has been shared on a network in

    order that other users may join,

  • joined - the activity has joined with other instances of

    the activity to create a shared network activity.

Side effects:

  • sets the gdk screen DPI setting (resolution) to the Sugar screen resolution.

  • connects our “destroy” message to our _destroy_cb method.

  • creates a base Gtk.Window within this window.

  • creates an ActivityService (self._bus) servicing this application.

When your activity implements __init__(), it must call the Activity class __init__() before any Activity specific code.

active

Whether an activity is active.

add_stop_button(button)

Register an extra stop button. Normally not required. Use only when an activity has more than the default stop button.

Parameters

button (Gtk.Button) – a stop button

busy()

Show that the activity is busy. If used, must be called once before a lengthy operation, and unbusy() must be called after the operation completes.

self.busy()
self.long_operation()
self.unbusy()
can_close()

Return whether close() is permitted.

An activity may override this function to code extra checks before closing.

Returns

whether close() is permitted by activity, default True.

Return type

bool

property canvas

The Gtk.Widget used as canvas, or work area of your activity. A common canvas is Gtk.ScrolledWindow.

close(skip_save=False)

Save to the journal and stop the activity.

Activities should not override this method, but should implement write_file() to do any state saving instead. If the activity wants to control wether it can close, it should override can_close().

Parameters

skip_save (bool) – avoid last-chance save; but does not prevent a journal object, as an object is created when the activity starts. Use this when an activity calls save() just prior to close().

copy()

Make a copy of the journal object.

Activities may use this to ‘Keep in Journal’ the current state of the activity. A new journal object will be created for the running activity.

Activities should not override this method. Instead, like save() do any copy work that needs to be done in write_file().

do_get_property(pspec)
do_set_property(pspec, value)
get_active()

Get whether the activity is active. An activity may be made inactive by the shell as a result of another activity being active. An active activity accumulates usage metrics.

Returns

if the activity is active.

Return type

boolean

get_activity_root()

Deprecated. This part of the API has been moved out of this class to the module itself

get_bundle_id()
Returns

the bundle_id from the activity.info file

Return type

int

get_canvas()

Get the canvas.

Returns

the widget used as canvas

Return type

Gtk.Widget

get_document_path(async_cb, async_err_cb)

Not implemented.

get_id()

Get the activity id, a likely-unique identifier for the instance of an activity, randomly assigned when a new instance is started, or read from the journal object metadata when a saved instance is resumed.

Returns

the activity id

Return type

str

See also create_activity_id() and unique_id().

get_max_participants()

Get the maximum number of users that can share a instance of this activity. Should be configured in the activity.info file. When not configured, it will be zero.

Returns

the maximum number of participants

Return type

int

See also get_max_participants() in ActivityBundle.

get_metadata()

Get the journal object metadata.

Returns

the journal object metadata, or None if there is no object.

Return type

dict

Activities can set metadata in write_file() using:

self.metadata['MyKey'] = 'Something'

and retrieve metadata in read_file() using:

self.metadata.get('MyKey', 'aDefaultValue')

Make sure your activity works properly if one or more of the metadata items is missing. Never assume they will all be present.

get_preview()

Get a preview image from the canvas, for use as metadata for the journal object. This should be what the user is seeing at the time.

Returns

image data in PNG format

Return type

bytes

Activities may override this method, and return a string with image data in PNG format with a width and height of PREVIEW_SIZE pixels.

The method creates a Cairo surface similar to that of the Gdk.Window of the canvas() widget, draws on it, then resizes to a surface with the preview size.

get_shared()

Get whether the activity is shared.

Returns

the activity is shared.

Return type

bool

get_shared_activity()

Get the shared activity of type sugar3.presence.activity.Activity, or None if the activity is not shared, or is shared and not yet joined.

Returns

instance of

the shared activity or None

Return type

sugar3.presence.activity.Activity

handle_view_source()

An activity may override this method to show aditional information in the View Source window. Examples can be seen in Browse and TurtleArt.

Raises

NotImplementedError

iconify(self)
invite(account_path, contact_id)

Invite a buddy to join this activity.

Parameters
  • account_path

  • contact_id

Side Effects:

Calls share() to privately share the activity if it wasn’t shared before.

max_participants

Get the maximum number of users that can share a instance of this activity. Should be configured in the activity.info file. When not configured, it will be zero.

Returns

the maximum number of participants

Return type

int

See also get_max_participants() in ActivityBundle.

property metadata

Get the journal object metadata.

Returns

the journal object metadata, or None if there is no object.

Return type

dict

Activities can set metadata in write_file() using:

self.metadata['MyKey'] = 'Something'

and retrieve metadata in read_file() using:

self.metadata.get('MyKey', 'aDefaultValue')

Make sure your activity works properly if one or more of the metadata items is missing. Never assume they will all be present.

notify_user(summary, body)

Display a notification with the given summary and body. The notification will go under the activities icon in the frame.

read_file(file_path)

Subclasses implement this method if they support resuming objects from the journal. ‘file_path’ is the file to read from.

You should immediately open the file from the file_path, because the file_name will be deleted immediately after returning from read_file().

Once the file has been opened, you do not have to read it immediately: After you have opened it, the file will only be really gone when you close it.

Although not required, this is also a good time to read all meta-data: the file itself cannot be changed externally, but the title, description and other metadata[‘tags’] may change. So if it is important for you to notice changes, this is the time to record the originals.

Parameters

file_path (str) – the file path to read

run_main_loop()
save()

Save to the journal.

This may be called by the close() method.

Activities should not override this method. This method is part of the public API of an activity, and should behave in standard ways. Use your own implementation of write_file() to save your activity specific data.

set_active(active)

Set whether the activity is active. An activity may declare itself active or inactive, as can the shell. An active activity accumulates usage metrics.

Parameters

active (boolean) – if the activity is active.

set_canvas(canvas)

Set the canvas.

Parameters

canvas (Gtk.Widget) – the widget used as canvas

set_max_participants(participants)

Set the maximum number of users that can share a instance of this activity. An activity may use this method instead of or as well as configuring the activity.info file. When both are used, this method takes precedence over the activity.info file.

Parameters

participants (int) – the maximum number of participants

share(private=False)

Request that the activity be shared on the network.

Parameters

private (bool) – True to share by invitation only, False to advertise as shared to everyone.

Once the activity is shared, its privacy can be changed by setting the private property of the sugar3.presence.activity.Activity class.

unbusy()

Show that the activity is not busy. An equal number of calls to unbusy() are required to balance the calls to busy().

Returns

a count of further calls to unbusy() expected

Return type

int

write_file(file_path)

Subclasses implement this method if they support saving data to objects in the journal. ‘file_path’ is the file to write to.

If the user did make changes, you should create the file_path and save all document data to it.

Additionally, you should also write any metadata needed to resume your activity. For example, the Read activity saves the current page and zoom level, so it can display the page.

Note: Currently, the file_path WILL be different from the one you received in read_file(). Even if you kept the file_path from read_file() open until now, you must still write the entire file to this file_path.

Parameters

file_path (str) – complete path of the file to write

sugar3.activity.activity.PREVIEW_SIZE = (300, 225)

Size of a preview image for journal object metadata.

sugar3.activity.activity.get_activity_root()
Returns

a path for saving Activity specific preferences, etc.

Return type

str

Returns a path to the location in the filesystem where the activity can store activity related data that doesn’t pertain to the current execution of the activity and thus cannot go into the DataStore.

Currently, this will return something like ~/.sugar/default/MyActivityName/

Activities should ONLY save settings, user preferences and other data which isn’t specific to a journal item here. If (meta-)data is in anyway specific to a journal entry, it MUST be stored in the DataStore.

sugar3.activity.activity.get_bundle(bundle_id='', object_id='')

Get the bundle id of an activity that can open a journal object.

Parameters
  • bundle_id (str) – activity bundle id, optional

  • object_id (object) – journal object

sugar3.activity.activity.get_bundle_name()
Returns

the bundle name for the current process’ bundle

Return type

str

sugar3.activity.activity.get_bundle_path()
Returns

the bundle path for the current process’ bundle

Return type

str

sugar3.activity.activity.launch_bundle(bundle_id='', object_id='')

Launch an activity for a journal object, or an activity.

Parameters
  • bundle_id (str) – activity bundle id, optional

  • object_id (object) – journal object

sugar3.activity.activity.show_object_in_journal(object_id)

Raise the journal activity and show a journal object.

Parameters

object_id (object) – journal object