sugar.activity package

Submodules

sugar.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 sugar.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 sugar.activity.activity import Activity
from sugar.graphics.toolbarbox import ToolbarBox
from sugar.activity.widgets import ActivityToolbarButton
from sugar.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.append(activity_button)

        separator = Gtk.Box()
        separator.set_hexpand(True)
        toolbar_box.toolbar.append(separator)

        stop_button = StopButton(self)
        toolbar_box.toolbar.append(stop_button)

        self.set_toolbar_box(toolbar_box)

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 sugar.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.Box:

class MySpecialToolbar(Gtk.Box):
    ...

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.

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

Size of a preview image for journal object metadata.

class sugar.activity.activity.Activity(*args: Any, **kwargs: Any)[source]

Bases: Window

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.

  • closing - the activity is about to close

Side effects:

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

  • connects our “close-request” signal to our close handling.

  • creates a base Gtk.ApplicationWindow within this window.

  • creates activity service handling for this application.

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

__init__(handle, create_jobject=True, application=None)[source]
add_stop_button(button)[source]

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

iconify()[source]

Iconify the activity window.

run_main_loop()[source]

Run the main loop for the activity.

Note: In GTK4, this is typically handled by the application, but we keep this for compatibility.

get_active()[source]

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

set_active(active)[source]

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.

active

Whether an activity is active.

get_max_participants()[source]

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.

set_max_participants(participants)[source]

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

get_id()[source]

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_bundle_id()[source]
Returns:

the bundle_id from the activity.info file

Return type:

str

get_canvas()[source]

Get the canvas.

Returns:

the widget used as canvas

Return type:

Gtk.Widget

set_canvas(canvas)[source]

Set the canvas.

Parameters:

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

property canvas

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

get_activity_root()[source]

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

read_file(file_path)[source]

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

write_file(file_path)[source]

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

notify_user(summary, body)[source]

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

Note: In GTK4/Flatpak, this uses the portal notification system.

get_preview()[source]

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 for the canvas widget, draws on it, then resizes to a surface with the preview size.

save()[source]

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.

copy()[source]

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().

get_shared_activity()[source]

Get the shared activity of type sugar.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:

sugar.presence.activity.Activity

get_shared()[source]

Get whether the activity is shared.

Returns:

the activity is shared.

Return type:

bool

invite(account_path, contact_id)[source]

Invite a buddy to join this activity.

Parameters:
  • account_path – account path

  • contact_id – contact ID

Side Effects:

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

share(private=False)[source]

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 sugar.presence.activity.Activity class.

can_close()[source]

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

close(skip_save=False)[source]

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 whether 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().

get_metadata()[source]

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.

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.

handle_view_source()[source]

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

Raises:

NotImplementedError

get_document_path(async_cb, async_err_cb)[source]

Not implemented.

busy()[source]

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()
unbusy()[source]

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

class sugar.activity.activity.SimpleActivity(*args: Any, **kwargs: Any)[source]

Bases: Activity

A simple activity implementation for quick prototyping.

This provides a basic activity with a toolbar and content area.

__init__(handle=None, application=None)[source]
sugar.activity.activity.get_bundle_name()[source]
Returns:

the bundle name for the current process’ bundle

Return type:

str

sugar.activity.activity.get_bundle_path()[source]
Returns:

the bundle path for the current process’ bundle

Return type:

str

sugar.activity.activity.get_activity_root()[source]
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.

sugar.activity.activity.show_object_in_journal(object_id)[source]

Raise the journal activity and show a journal object.

Parameters:

object_id (object) – journal object

Note: In GTK4/Flatpak environment, this functionality will need to be implemented using the document portal.

sugar.activity.activity.launch_bundle(bundle_id='', object_id='')[source]

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

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

  • object_id (object) – journal object

sugar.activity.activity.get_bundle(bundle_id='', object_id='')[source]

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

sugar.activity.activityhandle module

Provides a class for storing activity metadata such as activity id’s, journal object id’s. The ActivityHandle class for managing activity instances and their metadata.

class sugar.activity.activityhandle.ActivityHandle(activity_id=None, object_id=None, uri=None, invited=False)[source]

Bases: object

Data structure storing simple activity metadata

Parameters:
  • activity_id (string) – unique id for the activity to be

  • created

  • object_id (string) – identity of the journal object

  • activity. (associated with the)

  • journal (When you resume an activity from the)

  • optional (the object_id will be passed in. It is)

  • an (since new activities does not have)

  • object. (associated)

  • uri (string) – URI associated with the activity. Used when

  • the (opening an external file or resource in)

  • activity

  • object (rather than a journal)

  • for ((downloads stored on the file system)

  • pages) (example or web)

  • invited (bool) – True if the activity is being

  • network (launched for handling an invite from the)

__init__(activity_id=None, object_id=None, uri=None, invited=False)[source]
get_dict()[source]

Get a dictionary representation of the handle. :returns: Dictionary containing handle data :rtype: dict

classmethod create_from_dict(handle_dict)[source]

Create an ActivityHandle from a dictionary. :param handle_dict: Dictionary containing handle data :type handle_dict: dict

Returns:

New handle instance

Return type:

ActivityHandle

__repr__()[source]

String representation of the handle.

sugar.activity.widgets module

class sugar.activity.widgets.ActivityButton(*args: Any, **kwargs: Any)[source]

Bases: ToolButton

Button representing an activity with its icon and metadata.

__init__(activity, **kwargs)[source]
class sugar.activity.widgets.ActivityToolbarButton(*args: Any, **kwargs: Any)[source]

Bases: ToolbarButton

Toolbar button that contains an activity toolbar.

__init__(activity, **kwargs)[source]
class sugar.activity.widgets.StopButton(*args: Any, **kwargs: Any)[source]

Bases: ToolButton

Button to stop/close an activity.

__init__(activity, icon_name='activity-stop', **kwargs)[source]
class sugar.activity.widgets.UndoButton(*args: Any, **kwargs: Any)[source]

Bases: ToolButton

Standard undo button.

__init__(**kwargs)[source]
class sugar.activity.widgets.RedoButton(*args: Any, **kwargs: Any)[source]

Bases: ToolButton

Standard redo button.

__init__(**kwargs)[source]
class sugar.activity.widgets.CopyButton(*args: Any, **kwargs: Any)[source]

Bases: ToolButton

Standard copy button.

__init__(**kwargs)[source]
class sugar.activity.widgets.PasteButton(*args: Any, **kwargs: Any)[source]

Bases: ToolButton

Standard paste button.

__init__(**kwargs)[source]
class sugar.activity.widgets.ShareButton(*args: Any, **kwargs: Any)[source]

Bases: RadioMenuButton

Button for sharing activities with neighborhood.

__init__(activity, **kwargs)[source]
class sugar.activity.widgets.TitleEntry(*args: Any, **kwargs: Any)[source]

Bases: Box

Entry widget for editing activity title.

__init__(activity, **kwargs)[source]
save_title(activity)[source]
class sugar.activity.widgets.DescriptionItem(*args: Any, **kwargs: Any)[source]

Bases: ToolButton

Button for editing activity description.

__init__(activity, icon=None, **kwargs)[source]
set_expanded(expanded)[source]
get_toolbar_box()[source]
property toolbar_box
class sugar.activity.widgets.ActivityToolbar(*args: Any, **kwargs: Any)[source]

Bases: Box

The Activity toolbar with the Journal entry title and sharing button.

__init__(activity, orientation_left=False)[source]
class sugar.activity.widgets.EditToolbar(*args: Any, **kwargs: Any)[source]

Bases: Box

Provides the standard edit toolbar for Activities.

Members:

undo – the undo button redo – the redo button copy – the copy button paste – the paste button separator – A separator between undo/redo and copy/paste

This class only provides the ‘edit’ buttons in a standard layout, your activity will need to either hide buttons which make no sense for your Activity, or you need to connect the button events to your own callbacks:

## Example from Read.activity: # Create the edit toolbar: self._edit_toolbar = EditToolbar() # Hide undo and redo, they’re not needed self._edit_toolbar.undo.props.visible = False self._edit_toolbar.redo.props.visible = False # Hide the separator too: self._edit_toolbar.separator.props.visible = False

# As long as nothing is selected, copy needs to be insensitive: self._edit_toolbar.copy.set_sensitive(False) # When the user clicks the button, call _edit_toolbar_copy_cb() self._edit_toolbar.copy.connect(‘clicked’, self._edit_toolbar_copy_cb)

# Add the edit toolbar: toolbox.add_toolbar(_(‘Edit’), self._edit_toolbar) # And make it visible: self._edit_toolbar.show()

__init__()[source]

Module contents

Activity Module

Core activity classes and functionality for Sugar GTK4 activities.

class sugar.activity.Activity(*args: Any, **kwargs: Any)[source]

Bases: Window

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.

  • closing - the activity is about to close

Side effects:

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

  • connects our “close-request” signal to our close handling.

  • creates a base Gtk.ApplicationWindow within this window.

  • creates activity service handling for this application.

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

__init__(handle, create_jobject=True, application=None)[source]
add_stop_button(button)[source]

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()[source]

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()[source]

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

Get the canvas.

Returns:

the widget used as canvas

Return type:

Gtk.Widget

close(skip_save=False)[source]

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 whether 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()[source]

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().

get_active()[source]

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()[source]

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

get_bundle_id()[source]
Returns:

the bundle_id from the activity.info file

Return type:

str

get_canvas()[source]

Get the canvas.

Returns:

the widget used as canvas

Return type:

Gtk.Widget

get_document_path(async_cb, async_err_cb)[source]

Not implemented.

get_id()[source]

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()[source]

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()[source]

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()[source]

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 for the canvas widget, draws on it, then resizes to a surface with the preview size.

get_shared()[source]

Get whether the activity is shared.

Returns:

the activity is shared.

Return type:

bool

get_shared_activity()[source]

Get the shared activity of type sugar.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:

sugar.presence.activity.Activity

handle_view_source()[source]

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

Raises:

NotImplementedError

iconify()[source]

Iconify the activity window.

invite(account_path, contact_id)[source]

Invite a buddy to join this activity.

Parameters:
  • account_path – account path

  • contact_id – contact ID

Side Effects:

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

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)[source]

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

Note: In GTK4/Flatpak, this uses the portal notification system.

read_file(file_path)[source]

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()[source]

Run the main loop for the activity.

Note: In GTK4, this is typically handled by the application, but we keep this for compatibility.

save()[source]

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)[source]

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)[source]

Set the canvas.

Parameters:

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

set_max_participants(participants)[source]

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)[source]

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 sugar.presence.activity.Activity class.

unbusy()[source]

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)[source]

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

class sugar.activity.SimpleActivity(*args: Any, **kwargs: Any)[source]

Bases: Activity

A simple activity implementation for quick prototyping.

This provides a basic activity with a toolbar and content area.

__init__(handle=None, application=None)[source]