sugar4

A modern GTK4 port of the Sugar Toolkit for Python activities.

This package provides the core functionality needed to create Sugar activities using GTK4, maintaining compatibility with Sugar’s educational framework while leveraging modern GTK4 features.

Modules:

activity: Core activity classes and functionality graphics: Visual components, styling, and UI widgets bundle: Activity bundle management

Submodules

Classes

Activity

Initialise an Activity.

SimpleActivity

A simple activity implementation for quick prototyping.

EventIcon

Icon widget with mouse event handling using gesture controllers.

Icon

Basic Sugar icon widget.

MenuItem

A Sugar-style menu item with icon and text support.

MenuSeparator

A separator for use in menus.

XoColor

Defines color for XO

Package Contents

class sugar4.Activity(handle, create_jobject=True, application=None)[source]

Bases: sugar4.graphics.window.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.

__gtype_name__ = 'SugarActivity'
__gsignals__
shared_activity = None
sugar_accel_group = None
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.

show()[source]

Show the activity window.

In GTK4, ApplicationWindow uses present() instead of show(). This method provides compatibility with the activityinstance API.

run_main_loop()[source]

Run the main loop for the activity.

Note: In modern applications, this is typically handled by the application framework, but we keep this for compatibility with legacy code.

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

max_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

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

abstractmethod 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

abstractmethod 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 sugar4.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:

sugar4.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.

abstractmethod 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 sugar4.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.

metadata
abstractmethod 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 sugar4.SimpleActivity(handle=None, application=None)[source]

Bases: Activity

A simple activity implementation for quick prototyping.

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

class sugar4.EventIcon(**kwargs)[source]

Bases: Icon

Icon widget with mouse event handling using gesture controllers.

Provides click, press, and release events through modern gesture handling for better touch and accessibility support.

Signals:

clicked: Emitted when icon is clicked pressed: Emitted when icon is pressed released: Emitted when icon is released activate: Emitted when icon is activated

__gtype_name__ = 'SugarEventIcon'
__gsignals__
get_background_color() gi.repository.Gdk.RGBA | None[source]

Get background color.

set_background_color(color: gi.repository.Gdk.RGBA | None)[source]

Set background color.

get_cache() bool[source]

Get cache setting.

set_cache(cache: bool)[source]

Set cache setting.

background_color
cache
class sugar4.Icon(icon_name: str | None = None, file_name: str | None = None, pixel_size: int = STANDARD_ICON_SIZE, **kwargs)[source]

Bases: gi.repository.Gtk.Widget

Basic Sugar icon widget.

Displays themed icons with Sugar’s color customization features. Uses modern snapshot-based rendering for improved performance.

Properties:

icon_name (str): Icon name from theme file_name (str): Path to icon file pixel_size (int): Size in pixels fill_color (str): Fill color as hex string stroke_color (str): Stroke color as hex string xo_color (XoColor): Sugar color pair badge_name (str): Badge icon name alpha (float): Icon transparency (0.0-1.0) scale (float): Icon scale factor sensitive (bool): Whether icon appears sensitive

__gtype_name__ = 'SugarIcon'
do_snapshot(snapshot: gi.repository.Gtk.Snapshot)[source]

Render icon using snapshot-based drawing.

do_measure(orientation: gi.repository.Gtk.Orientation, for_size: int) Tuple[int, int, int, int][source]

Calculate widget size requirements.

get_icon_name() str | None[source]
set_icon_name(icon_name: str | None)[source]
get_file_name() str | None[source]
set_file_name(file_name: str | None)[source]
get_pixel_size() int[source]
set_pixel_size(size: int)[source]
get_fill_color() str | None[source]
set_fill_color(color: str | None)[source]
get_stroke_color() str | None[source]
set_stroke_color(color: str | None)[source]
get_xo_color() sugar4.graphics.xocolor.XoColor | None[source]
set_xo_color(xo_color: sugar4.graphics.xocolor.XoColor | None)[source]
get_badge_name() str | None[source]
set_badge_name(badge_name: str | None)[source]
get_alpha() float[source]
set_alpha(alpha: float)[source]
get_scale() float[source]
set_scale(scale: float)[source]
get_badge_size() int[source]

Get size of badge icon in pixels.

icon_name
file_name
pixel_size
fill_color
stroke_color
xo_color
badge_name
alpha
scale
get_pixbuf() gi.repository.GdkPixbuf.Pixbuf | None[source]

Get pixbuf for this icon.

set_pixbuf(pixbuf: gi.repository.GdkPixbuf.Pixbuf | None)[source]

Set pixbuf for this icon.

get_gtk_image() gi.repository.Gtk.Image[source]

Create a Gtk.Image from this icon for compatibility.

Returns:

Image widget with icon content

Return type:

Gtk.Image

class sugar4.MenuItem(text_label: str | None = None, icon_name: str | None = None, text_maxlen: int = style.MENU_WIDTH_CHARS, xo_color=None, file_name: str | None = None)[source]

Bases: gi.repository.Gtk.Button

A Sugar-style menu item with icon and text support.

This replaces the deprecated ImageMenuItem with a Button that can be used in menus and popover menus.

Parameters:
  • text_label (str) – Text to display on the menu item

  • icon_name (str) – Name of icon to display

  • text_maxlen (int) – Maximum text length before ellipsizing

  • xo_color – XO color scheme for the icon

  • file_name (str) – Path to icon file

__gtype_name__ = 'SugarMenuItem'
set_accelerator(accelerator: str | None)[source]

Set keyboard accelerator for this menu item.

Parameters:

accelerator (str) – Accelerator string (e.g., ‘<Ctrl>s’)

get_accelerator() str | None[source]

Get the current accelerator string.

Returns:

Current accelerator or None

Return type:

str

set_text(text: str)[source]

Set the text label of the menu item.

Parameters:

text (str) – New text to display

get_text() str[source]

Get the current text of the menu item.

Returns:

Current text or empty string

Return type:

str

accelerator
class sugar4.MenuSeparator[source]

Bases: gi.repository.Gtk.Separator

A separator for use in menus.

Simple wrapper around Gtk.Separator with menu-appropriate styling.

class sugar4.XoColor(color_string=None)[source]

Defines color for XO

This class represents a pair of colors (stroke and fill) that can be used throughout Sugar activities. Colors can be parsed from strings, loaded from user settings, or chosen randomly.

Parameters:

color_string (str, optional) – Color specification in one of these formats: - “stroke_hex,fill_hex” (e.g., “#FF0000,#00FF00”) - “white” for white theme - “insensitive” for disabled/grayed theme - None to use user’s color from settings or random if not available

Examples

>>> #from string
>>> color = XoColor("#FF0000,#00FF00")
>>> print(color.get_stroke_color())  # "#FF0000"
>>> print(color.get_fill_color())    # "#00FF00"
>>> # create user's color (or random if not set)
>>> color = XoColor()
>>> # themed colors
>>> white_color = XoColor("white")
>>> disabled_color = XoColor("insensitive")
__eq__(other)[source]

Check if two XoColor objects are equal.

Parameters:

other (object) – Another XoColor object to compare

Returns:

True if both stroke and fill colors match

Return type:

bool

__ne__(other)[source]

Check if two XoColor objects are not equal.

__hash__()[source]

Make XoColor hashable for use in sets and as dict keys.

__str__()[source]

String representation of XoColor.

__repr__()[source]

Detailed string representation of XoColor.

get_stroke_color()[source]
Returns:

stroke color in HTML hex format (#RRGGBB)

Return type:

str

get_fill_color()[source]
Returns:

fill color in HTML hex format (#RRGGBB)

Return type:

str

to_string()[source]
Returns:

formatted string in the format “#STROKEHEX,#FILLHEX”

Return type:

str

classmethod from_string(color_string)[source]

Create XoColor from string representation.

Parameters:

color_string (str) – Color string to parse

Returns:

New XoColor instance

Return type:

XoColor

Raises:

ValueError – If color_string cannot be parsed

classmethod get_random_color()[source]

Get a random XO color.

Returns:

Random XoColor instance from the standard palette

Return type:

XoColor

to_rgba_tuple(alpha=1.0)[source]

Convert colors to RGBA tuples for use with Cairo and modern graphics.

Parameters:

alpha (float) – Alpha value (0.0 - 1.0)

Returns:

((r, g, b, a), (r, g, b, a)) for stroke and fill colors

Return type:

tuple