sugar package

Subpackages

Submodules

sugar.env module

Calculates file-paths for the Sugar working environment

sugar.env.is_emulator()[source]
sugar.env.get_profile_path(path=None)[source]
sugar.env.get_logs_path(path=None)[source]
sugar.env.get_user_activities_path()[source]
sugar.env.get_user_library_path()[source]

sugar.logger module

Logging service setup.

STABLE.

sugar.logger.get_logs_dir()[source]
sugar.logger.set_level(level)[source]
sugar.logger.cleanup()[source]

Clean up the log directory, moving old logs into a numbered backup directory. We only keep _MAX_BACKUP_DIRS of these backup directories around; the rest are removed.

sugar.logger.start(log_filename=None)[source]
class sugar.logger.TraceRepr(*args: Any, **kwargs: Any)[source]

Bases: Repr

repr1(x, level)[source]
repr_int(x, level)[source]
repr_bool(x, level)[source]
sugar.logger.trace(logger=None, logger_name=None, skip_args=None, skip_kwargs=None, maxsize_list=30, maxsize_dict=30, maxsize_string=300)[source]

sugar.mime module

MIME helpers based on freedesktop specification.

STABLE.

class sugar.mime.ObjectType(type_id, name, icon, mime_types)[source]

Bases: object

__init__(type_id, name, icon, mime_types)[source]
sugar.mime.get_generic_type(type_id)[source]
sugar.mime.get_all_generic_types()[source]
sugar.mime.get_for_file(file_name)[source]
sugar.mime.get_from_file_name(file_name)[source]

DEPRECATED: 0.102 (removed in 4 releases) Use Gio.content_type_guess(file_name, None)[0] instead.

sugar.mime.get_mime_icon(mime_type)[source]
sugar.mime.get_mime_description(mime_type)[source]
sugar.mime.get_mime_parents(mime_type)[source]
sugar.mime.get_primary_extension(mime_type)[source]
sugar.mime.get_extensions_by_mimetype(mime_type)[source]
sugar.mime.choose_most_significant(mime_types)[source]
sugar.mime.split_uri_list(uri_list)[source]

sugar.network module

STABLE.

sugar.network.get_authinfo()[source]
class sugar.network.GlibTCPServer(*args: Any, **kwargs: Any)[source]

Bases: TCPServer

Integrate socket accept into glib mainloop.

allow_reuse_address = True
request_queue_size = 20
__init__(server_address, RequestHandlerClass)[source]
close_request(request)[source]

Called to clean up an individual request.

shutdown_request(request)[source]

Called to shutdown and close an individual request.

class sugar.network.ChunkedGlibHTTPRequestHandler(*args: Any, **kwargs: Any)[source]

Bases: SimpleHTTPRequestHandler

RequestHandler class that integrates with Glib mainloop. It writes the specified file to the client in chunks, returning control to the mainloop between chunks.

CHUNK_SIZE = 4096
__init__(request, client_address, server)[source]
log_request(code='-', size='-')[source]
do_GET()[source]

Serve a GET request.

finish()[source]

Close the sockets when we’re done, not before

send_head()[source]

Common code for GET and HEAD commands.

This sends the response code and MIME headers.

Return value is either a file object (which has to be copied to the outputfile by the caller unless the command was HEAD, and must be closed by the caller under all circumstances), or None, in which case the caller has nothing further to do.

** [dcbw] modified to send Content-disposition filename too

class sugar.network.GlibURLDownloader(*args: Any, **kwargs: Any)[source]

Bases: GObject

Grabs a URL in chunks, returning to the mainloop after each chunk

CHUNK_SIZE = 4096
__init__(url, destdir=None)[source]
start(destfile=None, destfd=None)[source]
cancel()[source]
cleanup(remove=False)[source]

sugar.profile module

User settings/configuration loading.

class sugar.profile.Profile(path)[source]

Bases: object

Local user’s current options/profile information

The profile is also responsible for loading the user’s public and private ssh keys from disk.

pubkey -- public ssh key
privkey_hash -- SHA has of the child's public key
__init__(path)[source]
property pubkey
property privkey_hash
is_valid()[source]
convert_profile()[source]
sugar.profile.get_profile()[source]
sugar.profile.get_nick_name()[source]
sugar.profile.get_color()[source]
sugar.profile.get_pubkey()[source]
sugar.profile.get_save_as()[source]

sugar.util module

Various utility functions

sugar.util.printable_hash(in_hash)[source]

Convert binary hash data into printable characters.

sugar.util.sha_data(data)[source]

sha1 hash some bytes.

sugar.util.unique_id(data='')[source]

Generate a likely-unique ID for whatever purpose

data – suffix appended to working data before hashing

Returns a 40-character string with hexidecimal digits representing an SHA hash of the time, a random digit within a constrained range and the data passed.

Note: these are not crypotographically secure or

globally unique identifiers. While they are likely to be unique-enough, no attempt is made to make perfectly unique values.

sugar.util.is_hex(s)[source]
sugar.util.validate_activity_id(actid)[source]

Validate an activity ID.

sugar.util.set_proc_title(title)[source]

Sets the process title so ps and top show more descriptive names. This does not modify argv[0] and only the first 15 characters will be shown.

title – the title you wish to change the process

title to

Returns True on success. We don’t raise exceptions because if something goes wrong here it is not a big deal as this is intended as a nice thing to have for debugging

class sugar.util.Node(prev, me)[source]

Bases: object

__init__(prev, me)[source]
prev
me
next
class sugar.util.LRU(count, pairs=[])[source]

Bases: object

Implementation of a length-limited O(1) LRU queue. Built for and used by PyPE: http://pype.sourceforge.net Copyright 2003 Josiah Carlson.

__init__(count, pairs=[])[source]
iteritems()[source]
iterkeys()[source]
itervalues()[source]
keys()[source]
sugar.util.timestamp_to_elapsed_string(timestamp, max_levels=2)[source]
class sugar.util.TempFilePath(path=None)[source]

Bases: str

sugar.util.format_size(size)[source]

Module contents

Sugar Toolkit GTK4 Python

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

class sugar.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.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]
class sugar.XoColor(color_string=None)[source]

Bases: object

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

__hash__()[source]

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

__init__(color_string=None)[source]
__ne__(other)[source]

Check if two XoColor objects are not equal.

__repr__()[source]

Detailed string representation of XoColor.

__str__()[source]

String representation of XoColor.

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

get_fill_color()[source]
Returns:

fill color in HTML hex format (#RRGGBB)

Return type:

str

classmethod get_random_color()[source]

Get a random XO color.

Returns:

Random XoColor instance from the standard palette

Return type:

XoColor

get_stroke_color()[source]
Returns:

stroke color in HTML hex format (#RRGGBB)

Return type:

str

to_rgba_tuple(alpha=1.0)[source]

Convert colors to RGBA tuples for use with Cairo/GTK4.

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

to_string()[source]
Returns:

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

Return type:

str

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

Bases: Widget

Basic Sugar icon widget for GTK4.

Displays themed icons with Sugar’s color customization features.

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

__init__(icon_name: str | None = None, file_name: str | None = None, pixel_size: int = 48, **kwargs)[source]
do_measure(orientation: gi.repository.Gtk.Orientation, for_size: int) Tuple[int, int, int, int][source]

GTK4 size request method.

do_snapshot(snapshot: gi.repository.Gtk.Snapshot)[source]

GTK4 drawing method.

get_alpha() float[source]
get_badge_name() str | None[source]
get_badge_size() int[source]

Get size of badge icon in pixels.

get_file_name() str | None[source]
get_fill_color() str | None[source]
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

get_icon_name() str | None[source]
get_pixbuf() gi.repository.GdkPixbuf.Pixbuf | None[source]

Get pixbuf for this icon.

get_pixel_size() int[source]
get_scale() float[source]
get_stroke_color() str | None[source]
get_xo_color() XoColor | None[source]
set_alpha(alpha: float)[source]
set_badge_name(badge_name: str | None)[source]
set_file_name(file_name: str | None)[source]
set_fill_color(color: str | None)[source]
set_icon_name(icon_name: str | None)[source]
set_pixbuf(pixbuf: gi.repository.GdkPixbuf.Pixbuf | None)[source]

Set pixbuf for this icon.

set_pixel_size(size: int)[source]
set_scale(scale: float)[source]
set_stroke_color(color: str | None)[source]
set_xo_color(xo_color: XoColor | None)[source]
class sugar.EventIcon(*args: Any, **kwargs: Any)[source]

Bases: Icon

Icon widget with mouse event handling using GTK4 gestures.

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

__init__(**kwargs)[source]
get_background_color() gi.repository.Gdk.RGBA | None[source]

Get background color.

get_cache() bool[source]

Get cache setting.

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

Set background color.

set_cache(cache: bool)[source]

Set cache setting.

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

Bases: Button

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

In GTK4, 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

__init__(text_label: str | None = None, icon_name: str | None = None, text_maxlen: int = 60, xo_color=None, file_name: str | None = None)[source]
get_accelerator() str | None[source]

Get the current accelerator string.

Returns:

Current accelerator or None

Return type:

str

get_text() str[source]

Get the current text of the menu item.

Returns:

Current text or empty string

Return type:

str

set_accelerator(accelerator: str | None)[source]

Set keyboard accelerator for this menu item.

Parameters:

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

set_text(text: str)[source]

Set the text label of the menu item.

Parameters:

text (str) – New text to display

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

Bases: Separator

A separator for use in menus.

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

__init__()[source]