sugar.graphics package

Submodules

sugar.graphics.alert module

Alerts appear in an activity below the toolbox and above the canvas.

Alert and the derived TimeoutAlert, ConfirmationAlert, ErrorAlert, and NotifyAlert, each have a title, a message and optional buttons.

Alert will emit a response signal when a button is clicked.

The TimeoutAlert and NotifyAlert display a countdown and will emit a response signal when a timeout occurs.

Example

Create a simple alert message.

from sugar.graphics.alert import Alert

# Create a new simple alert
alert = Alert()

# Set the title and text body of the alert
alert.props.title = _('Title of Alert Goes Here')
alert.props.msg = _('Text message of alert goes here')

# Add the alert to the activity
self.add_alert(alert)
alert.show()

STABLE.

class sugar.graphics.alert.Alert(*args: Any, **kwargs: Any)[source]

Bases: Box

Alerts are inside the activity window instead of being a separate popup window. They do not hide the canvas.

Use add_alert() and remove_alert() to add and remove an alert. These methods are inherited by an Activity via superclass Window.

The alert is placed between the canvas and the toolbox, or above the canvas in fullscreen mode.

Parameters:
  • title (str) – the title of the alert

  • message (str) – the message of the alert

  • icon (str) – the icon that appears at the far left

__init__(**kwargs)[source]
do_set_property(pspec, value)[source]

Set alert property, GObject internal method. Use the alert.props object, eg:

alert.props.title = 'Are you happy?'
do_get_property(pspec)[source]

Get alert property, GObject internal method. Use the alert.props object, eg:

title = alert.props.title
add_entry()[source]

Create an entry and add it to the alert.

The entry is placed after the title and before the buttons.

Caller is responsible for capturing the entry text in the response signal handler or a Gtk.Entry signal handler.

Returns:

the entry added to the alert

Return type:

Gtk.Entry

add_button(response_id, label, icon=None, position=-1)[source]

Create a button and add it to the alert.

The button is added to the end of the alert.

When the button is clicked, the response signal will be emitted, along with a response identifier.

Parameters:
  • response_id (int) – the response identifier, a Gtk.ResponseType constant or any positive integer,

  • label (str) – a label for the button

  • icon (Icon or Gtk.Image, optional) – an icon for the button

  • position (int, optional) – the position of the button in the box of buttons,

Returns:

the button added to the alert

Return type:

Gtk.Button

remove_button(response_id)[source]

Remove a button from the alert.

The button is selected for removal using the response identifier that was passed to add_button().

Parameters:

response_id (int) – the response identifier

Returns:

None

class sugar.graphics.alert.ConfirmationAlert(*args: Any, **kwargs: Any)[source]

Bases: Alert

An alert with two buttons; Ok and Cancel.

When a button is clicked, the ConfirmationAlert will emit a response signal with a response identifier. For the Ok button, the response identifier will be Gtk.ResponseType.OK. For the Cancel button, Gtk.ResponseType.CANCEL.

Parameters:

**kwargs – parameters for Alert

__init__(**kwargs)[source]
class sugar.graphics.alert.ErrorAlert(*args: Any, **kwargs: Any)[source]

Bases: Alert

An alert with one button; Ok.

When the button is clicked, the ErrorAlert will emit a response signal with a response identifier Gtk.ResponseType.OK.

Parameters:

**kwargs – parameters for Alert

__init__(**kwargs)[source]
class sugar.graphics.alert.TimeoutAlert(*args: Any, **kwargs: Any)[source]

Bases: _TimeoutAlert

A timed alert with two buttons; Continue and Cancel. The Continue button contains a countdown of seconds remaining.

When a button is clicked, the TimeoutAlert will emit a response signal with a response identifier. For the Continue button, the response identifier will be Gtk.ResponseType.OK. For the Cancel button, Gtk.ResponseType.CANCEL.

If the countdown reaches zero before a button is clicked, the TimeoutAlert will emit a response signal with a response identifier of -1.

Parameters:
  • timeout (int, optional) – time in seconds, default 5

  • **kwargs – parameters for Alert

__init__(timeout=5, **kwargs)[source]
class sugar.graphics.alert.NotifyAlert(*args: Any, **kwargs: Any)[source]

Bases: _TimeoutAlert

A timed alert with one button; Ok. The button contains a countdown of seconds remaining.

When the button is clicked, the NotifyAlert will emit a response signal with a response identifier Gtk.ResponseType.OK.

If the countdown reaches zero before the button is clicked, the NotifyAlert will emit a response signal with a response identifier of -1.

Parameters:
  • timeout (int, optional) – time in seconds, default 5

  • **kwargs – parameters for Alert

__init__(timeout=5, **kwargs)[source]

sugar.graphics.animator module

Animator

The animator module provides a simple framework to create animations in GTK4.

Example

Animate the size of a window:

from gi.repository import Gtk
from sugar.graphics.animator import Animator, Animation

# Construct a window to animate
w = Gtk.Window()
w.connect('destroy', lambda w: app.quit())

# Start the animation when the window is shown
w.connect('realize', lambda self: animator.start())
w.present()

# Construct a 5 second animator
animator = Animator(5, widget=w)

# Create an animation subclass to animate the widget
class SizeAnimation(Animation):
    def __init__(self):
        # Tell the animation to give us values between 20 and
        # 420 during the animation
        Animation.__init__(self, 20, 420)

    def next_frame(self, frame):
        size = int(frame)
        w.set_default_size(size, size)

# Add the animation to the animator
animation = SizeAnimation()
animator.add(animation)

# The animation runs inside a GLib main loop
app.run()

STABLE.

class sugar.graphics.animator.Animator(*args: Any, **kwargs: Any)[source]

Bases: GObject

The animator class manages the timing for calling the animations.

The animations can be added using the add function and then started with the start function. If multiple animations are added, then they will be played back at the same time and rate as each other.

The completed signal is emitted upon the completion of the animation and also when the stop function is called.

Parameters:
  • duration (float) – the duration of the animation in seconds

  • fps (int, optional) – the number of animation callbacks to make per second (frames per second). This is used as fallback when frame clock is not available.

  • easing (int) – the desired easing mode, either EASE_OUT_EXPO or EASE_IN_EXPO

  • widget (Gtk.Widget) – one of the widgets that the animation is acting on. If supplied, the animation will run on the frame clock of the widget for smoother animation.

Note

When creating an animation, take into account the limited cpu power on some devices, such as the XO. Setting the fps too high can use significant cpu usage.

__init__(duration, fps=20, easing=0, widget=None)[source]
add(animation)[source]

Add an animation to this animator.

Parameters:

animation (sugar.graphics.animator.Animation) – the animation instance to add

remove_all()[source]

Remove all animations and stop this animator.

start()[source]

Start the animation running. This will stop and restart the animation if the animation is currently running.

stop()[source]

Stop the animation and emit the completed signal.

class sugar.graphics.animator.Animation(start, end)[source]

Bases: object

The animation class is a base class for creating an animation. It should be subclassed. Subclasses should specify a next_frame function to set the required properties based on the animation progress. The range of the frame value passed to the next_frame function is defined by the start and end values.

Parameters:
  • start (float) – the first frame value for the next_frame method

  • end (float) – the last frame value for the next_frame method

# Create an animation subclass
class MyAnimation(Animation):
    def __init__(self, thing):
        # Tell the animation to give us values between 0.0 and
        # 1.0 during the animation
        Animation.__init__(self, 0.0, 1.0)
        self._thing = thing

    def next_frame(self, frame):
        # Use the `frame` value to set properties
        self._thing.set_green_value(frame)
__init__(start, end)[source]
do_frame(t, duration, easing)[source]

This method is called by the animator class every frame. This method calculates the frame value to then call next_frame.

Parameters:
  • t (float) – the current time elapsed of the animation in seconds

  • duration (float) – the length of the animation in seconds

  • easing (int) – the easing mode passed to the animator

next_frame(frame)[source]

This method is called every frame and should be overridden by subclasses.

Parameters:

frame (float) – a value between start and end representing the current progress in the animation

do_stop()[source]

This method is called whenever the animation is stopped, either due to the animation ending or being stopped by the animation. next_frame will not be called after do_stop, unless the animation is restarted.

Added in version 0.109.0.3.

This should be used in subclasses if they bind any signals. Eg. if they bind the draw signal for a widget:

class SignalAnimation(Animation):

    def __init__(self, widget):
        Animation.__init__(self, 0, 1)
        self._draw_hid = None
        self._widget = widget

    def next_frame(self, frame):
        self._frame = frame
        if self._draw_hid is None:
            self._draw_hid = self._widget.connect_after(
                'draw', self.__draw_cb)
        self._widget.queue_draw()

    def __draw_cb(self, widget, cr):
        cr.save()
        # Do the draw
        cr.restore()

    def do_stop(self):
        self._widget.disconnect(self._draw_hid)
        self._widget.queue_draw()
class sugar.graphics.animator.FadeAnimation(widget, start_opacity=0.0, end_opacity=1.0)[source]

Bases: Animation

A convenience animation class for fading widgets in/out.

Parameters:
  • widget (Gtk.Widget) – The widget to animate

  • start_opacity (float) – Starting opacity (0.0 to 1.0)

  • end_opacity (float) – Ending opacity (0.0 to 1.0)

__init__(widget, start_opacity=0.0, end_opacity=1.0)[source]
next_frame(frame)[source]

Update widget opacity.

class sugar.graphics.animator.ScaleAnimation(widget, start_scale=0.0, end_scale=1.0)[source]

Bases: Animation

A convenience animation class for scaling widgets.

Parameters:
  • widget (Gtk.Widget) – The widget to animate

  • start_scale (float) – Starting scale factor

  • end_scale (float) – Ending scale factor

__init__(widget, start_scale=0.0, end_scale=1.0)[source]
next_frame(frame)[source]

Update widget scale.

class sugar.graphics.animator.MoveAnimation(widget, start_pos, end_pos)[source]

Bases: Animation

A convenience animation class for moving widgets.

Parameters:
  • widget (Gtk.Widget) – The widget to animate

  • start_pos (tuple) – Starting position (x, y)

  • end_pos (tuple) – Ending position (x, y)

__init__(widget, start_pos, end_pos)[source]
next_frame(frame)[source]

Update widget position.

class sugar.graphics.animator.ColorAnimation(start_color, end_color, callback)[source]

Bases: Animation

A convenience animation class for animating colors.

Parameters:
  • start_color (tuple) – Starting RGBA color (r, g, b, a)

  • end_color (tuple) – Ending RGBA color (r, g, b, a)

  • callback (function) – Function to call with interpolated color

__init__(start_color, end_color, callback)[source]
next_frame(frame)[source]

Interpolate color and call callback.

sugar.graphics.icon module

Icons - GTK4

Icons are small pictures that are used to decorate components. In Sugar, icons are SVG files that are re-coloured with a fill and a stroke colour. Typically, icons representing the system use a greyscale color palette, whereas icons representing people take on their selected XoColors.

Classes:

Icon: Basic icon widget for displaying themed icons EventIcon: Icon with mouse event handling (GTK4 GestureClick) CanvasIcon: EventIcon with active/prelight states and styleable background CellRendererIcon: Icon renderer for use in tree/list views get_icon_file_name: Utility function to resolve icon paths get_surface: Utility function to get cairo surfaces for icons get_icon_state: Utility function to get state-based icon names

class sugar.graphics.icon.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_snapshot(snapshot: gi.repository.Gtk.Snapshot)[source]

GTK4 drawing method.

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

GTK4 size request method.

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() XoColor | None[source]
set_xo_color(xo_color: 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.

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 sugar.graphics.icon.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.

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.

class sugar.graphics.icon.CanvasIcon(*args: Any, **kwargs: Any)[source]

Bases: EventIcon

An EventIcon with active and prelight states, and a styleable background.

This icon responds to mouse hover and press states with visual feedback.

__init__(**kwargs)[source]
do_snapshot(snapshot)[source]

Override to render background based on state.

class sugar.graphics.icon.CellRendererIcon[source]

Bases: object

Icon renderer for use in list/tree views.

Note: GTK4 uses a different approach for cell rendering. This is provided for compatibility but may need adaptation.

__init__()[source]
set_icon_name(icon_name: str)[source]
set_file_name(file_name: str)[source]
set_xo_color(xo_color: XoColor)[source]
set_fill_color(color: str)[source]
set_stroke_color(color: str)[source]
set_size(size: int)[source]
get_surface(sensitive: bool = True) cairo.ImageSurface | None[source]

Get rendered surface.

sugar.graphics.icon.get_icon_file_name(icon_name: str) str | None[source]

Resolve icon name to file path using GTK4 icon theme.

Parameters:

icon_name – Name of icon to resolve

Returns:

Path to icon file or None if not found

sugar.graphics.icon.get_icon_state(base_name: str, perc: float, step: int = 5) str | None[source]

Get the closest icon name for a given state in percent.

Parameters:
  • base_name – Base icon name (e.g., ‘network-wireless’)

  • perc – Desired percentage between 0 and 100

  • step – Step increment to find possible icons

Returns:

Icon name that represents given state, or None if not found

sugar.graphics.icon.get_surface(icon_name: str | None = None, file_name: str | None = None, fill_color: str | None = None, stroke_color: str | None = None, pixel_size: int = 48, **kwargs) cairo.ImageSurface | None[source]

Get cairo surface for an icon with specified properties.

Parameters:
  • icon_name – Icon name from theme

  • file_name – Path to icon file

  • fill_color – Fill color as hex string

  • stroke_color – Stroke color as hex string

  • pixel_size – Size in pixels

  • **kwargs – Additional properties

Returns:

Cairo surface or None if icon not found

sugar.graphics.menuitem module

class sugar.graphics.menuitem.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]
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

class sugar.graphics.menuitem.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]

sugar.graphics.objectchooser module

STABLE.

sugar.graphics.objectchooser.get_preview_pixbuf(preview_data, width=-1, height=-1)[source]

Retrieve a pixbuf with the content of the preview field

Parameters:

preview_data (bytes) – preview data from the metadata dictionary. Can’t be None. Returned from the sugar.datastore.datastore.DSObject.get_metadata() method.

Keyword Arguments:
  • width (int) – the pixbuf width, if is not set,

  • used (the default height will be)

  • height (int) – the pixbuf height, if is not set,

  • used

Returns:

the generated Pixbuf None: if it could not be created

Return type:

GdkPixbuf.Pixbuf

Example

pixbuf = get_preview_pixbuf(metadata.get(‘preview’, ‘’)) has_preview = pixbuf is not None

if has_preview:

im = Gtk.Image() im.set_from_pixbuf(pixbuf) box.append(im) im.show()

class sugar.graphics.objectchooser.ObjectChooser(parent=None, what_filter=None, filter_type=None, show_preview=False)[source]

Bases: object

UI interface for object choosers.

Object choosers can be used by activities to allow the user to select objects from the file system or from some other similar source.

Keyword Arguments:
  • parent (Gtk.Widget) – the widget calling ObjectChooser

  • what_filter (str) – an activity bundle_id or a generic mime type as defined in sugar.mime used to determine which objects will be presented in the object chooser

  • filter_type (str) –

    should be one of [None, FILTER_TYPE_GENERIC_MIME, FILTER_TYPE_ACTIVITY, FILTER_TYPE_MIME_BY_ACTIVITY]

    If filter_type is None, the default behavior of the what_filter is applied (for backward compatibility), this option is DEPRECATED.

    If filter_type is FILTER_TYPE_GENERIC_MIME, the what_filter should be a generic mime type defined in mime.py; the object chooser will filter based in the ‘mime_type’ metadata field.

    If filter_type is FILTER_TYPE_ACTIVITY, the what_filter should by an activity bundle_id; the object chooser will filter based in the ‘activity’ metadata field.

    If filter_type is FILTER_TYPE_MIME_BY_ACTIVITY, the what_filter should be an activity bundle_id; the object chooser will filter based on the ‘mime_type’ metadata field and the mime types defined by the activity in the activity.info file.

  • show_preview (bool) – if True will show the preview image associated with the object in the Journal. This option is only available if filter_type is selected.

Examples

chooser = ObjectChooser(self._activity, what_filter=’Image’)

chooser = ObjectChooser(parent=self,

what_filter=self.get_bundle_id(), filter_type=FILTER_TYPE_ACTIVITY)

__init__(parent=None, what_filter=None, filter_type=None, show_preview=False)[source]
run()[source]

Runs the object chooser and displays it.

Returns:

Gtk.ResponseType constant, the response received from displaying the object chooser.

get_selected_object()[source]

Gets the object selected using the object chooser.

Returns:

the object selected

Return type:

object

destroy()[source]

Destroys and cleans up (disposes) the object chooser.

sugar.graphics.palette module

class sugar.graphics.palette.Palette(*args: Any, **kwargs: Any)[source]

Bases: PaletteWindow

Floating palette implementation.

This class dynamically switches between one of two encapsulated child widget types: a _PaletteWindowWidget or a _PaletteMenuWidget.

The window widget, created by default, acts as the container for any type of widget the user may wish to add. It can optionally display primary text, secondary text, and an icon at the top of the palette.

If the user attempts to access the ‘menu’ property, the window widget is destroyed and the palette is dynamically switched to use a menu widget. This maintains the same look and feel as a normal palette, allowing submenus and so on.

__init__(label=None, accel_path=None, text_maxlen=60, **kwargs)[source]
get_full_size_request()[source]

Get the full size request for the palette.

popup(immediate=False)[source]

Show the palette.

popdown(immediate=False, state=None)[source]

Hide the palette.

Parameters:
  • immediate (bool) – if True, hide instantly. If False, use animation.

  • state – deprecated parameter, ignored.

on_enter()[source]
set_primary_text(label, accel_path=None)[source]
get_primary_text()[source]
set_secondary_text(label)[source]
get_secondary_text()[source]
set_icon(icon)[source]
get_icon()[source]
set_icon_visible(visible)[source]
get_icon_visible()[source]
set_content(widget)[source]

Set the main content widget for the palette window.

get_label_width()[source]
get_menu()[source]
class sugar.graphics.palette.PaletteActionBar(*args: Any, **kwargs: Any)[source]

Bases: Box

__init__()[source]
add_action(label, icon_name=None)[source]

sugar.graphics.palettegroup module

sugar.graphics.palettegroup.get_group(group_id)[source]
sugar.graphics.palettegroup.popdown_all()[source]
class sugar.graphics.palettegroup.Group(*args: Any, **kwargs: Any)[source]

Bases: GObject

__init__()[source]
is_up()[source]
get_state()[source]
add(palette)[source]
remove(palette)[source]
popdown()[source]

sugar.graphics.palettemenu module

PaletteMenu

The palettemenu module is the main port of call for making palettes in GTK4. It covers creating menu items, separators and placing them in a box.

This GTK4 port modernizes the palette menu system while maintaining compatibility with Sugar’s palette interface patterns.

Example

Create a palette menu with 2 items with a separator in the middle.

from gi.repository import Gtk
from gettext import gettext as _

from sugar.graphics.palette import Palette
from sugar.graphics.palettemenu import PaletteMenuBox
from sugar.graphics.palettemenu import PaletteMenuItem
from sugar.graphics.palettemenu import PaletteMenuItemSeparator


class ItemPalette(Palette):
    def __init__(self):
        Palette.__init__(
            self, primary_text='List Item')
        box = PaletteMenuBox()
        self.set_content(box)

        menu_item = PaletteMenuItem(
            _('Edit'), icon_name='toolbar-edit')
        menu_item.connect('activate', self.__edit_cb)
        box.append_item(menu_item)

        sep = PaletteMenuItemSeparator()
        box.append_item(sep)

        menu_item = PaletteMenuItem(
            _('Delete'), icon_name='edit-delete')
        box.append_item(menu_item)

    def __edit_cb(self, menu_item):
        print('Edit...')

# Usually the Palette instance is returned in a create_palette function
p = ItemPalette()
p.popup()

Add a palettebox to a toolbutton:

image = ToolButton('insert-picture')
image.set_tooltip(_('Insert Image'))
toolbar_box.toolbar.insert(image, -1)

palette = image.get_palette()
box = PaletteMenuBox()
palette.set_content(box)

menu_item = PaletteMenuItem(_('Floating'))
menu_item.connect('activate', self.__image_cb, True)
box.append_item(menu_item)
class sugar.graphics.palettemenu.PaletteMenuBox(*args: Any, **kwargs: Any)[source]

Bases: Box

The PaletteMenuBox is a box that is useful for making palettes.

It supports adding sugar.graphics.palettemenu.PaletteMenuItem, sugar.graphics.palettemenu.PaletteMenuItemSeparator and it automatically adds padding to other widgets.

__init__()[source]
append_item(item_or_widget, horizontal_padding=None, vertical_padding=None)[source]

Add a menu item, separator or other widget to the end of the palette (similar to Gtk.Box.append).

If an item is appended (a sugar.graphics.palettemenu.PaletteMenuItem or a sugar.graphics.palettemenu.PaletteMenuItemSeparator) no padding will be added, as that is handled by the item. If a widget is appended (Gtk.Widget subclass) padding will be added.

Parameters:
Returns:

None

class sugar.graphics.palettemenu.PaletteMenuItemSeparator(*args: Any, **kwargs: Any)[source]

Bases: Separator

Horizontal separator to put in a palette.

__init__()[source]
class sugar.graphics.palettemenu.PaletteMenuItem(*args: Any, **kwargs: Any)[source]

Bases: Button

A palette menu item is a line of text, and optionally an icon, that the user can activate.

The activate signal is usually emitted when the item is clicked. It has no arguments. When a menu item is activated, the palette is also closed.

This GTK4 port replaces EventBox with Button for better accessibility and modern interaction patterns.

Parameters:
  • text_label (str) – a text to display in the menu

  • icon_name (str) – the name of a sugar icon to be displayed. Takes precedence over file_name

  • text_maxlen (int) – the desired maximum width of the label, in characters. By default set to 60 chars

  • xo_color (sugar.graphics.XoColor) – the color to be applied to the icon

  • file_name (str) – the path to a svg file used as icon

  • accelerator (str) – a text used to display the keyboard shortcut associated to the menu

__init__(text_label=None, icon_name=None, text_maxlen=60, xo_color=None, file_name=None, accelerator=None)[source]
set_label(text_label)[source]

Set the text label of the menu item.

Parameters:

text_label (str) – New text to display

get_label()[source]

Get the current text of the menu item.

Returns:

Current text or empty string

Return type:

str

set_image(icon)[source]

Set the icon of the menu item.

Parameters:

icon (Icon) – Icon widget to display

set_accelerator(text)[source]

Set the accelerator text for the menu item.

Parameters:

text (str) – Accelerator text to display (e.g., “Ctrl+S”)

set_sensitive(sensitive)[source]

Set the sensitivity of the menu item.

Parameters:

sensitive (bool) – Whether the item should be sensitive

sugar.graphics.palettemenu.create_menu_item(text, icon_name=None, callback=None, accelerator=None)[source]

Create a basic menu item with common parameters.

Parameters:
  • text (str) – Menu item text

  • icon_name (str) – Optional icon name

  • callback (function) – Optional callback function

  • accelerator (str) – Optional accelerator text

Returns:

The created menu item

Return type:

PaletteMenuItem

sugar.graphics.palettemenu.create_separator()[source]

Create a menu separator.

Returns:

The created separator

Return type:

PaletteMenuItemSeparator

sugar.graphics.palettemenu.create_submenu_item(text, submenu_items, icon_name=None)[source]

Create a menu item that expands to show submenu items.

Parameters:
  • text (str) – Menu item text

  • submenu_items (list) – List of submenu items

  • icon_name (str) – Optional icon name

Returns:

The created submenu item

Return type:

PaletteMenuItem

class sugar.graphics.palettemenu.PaletteMenuGroup(name=None)[source]

Bases: object

A group of related menu items that can be managed together.

__init__(name=None)[source]
add_item(item)[source]

Add an item to this group.

set_sensitive(sensitive)[source]

Set sensitivity of all items in the group.

set_visible(visible)[source]

Set visibility of all items in the group.

class sugar.graphics.palettemenu.PaletteMenuBuilder[source]

Bases: object

Builder class for creating complex palette menus.

__init__()[source]
add_item(text, icon_name=None, callback=None, accelerator=None, group=None)[source]

Add a menu item to the builder.

add_separator()[source]

Add a separator to the builder.

get_menu_box()[source]

Get the constructed menu box.

get_group(name)[source]

Get a menu group by name.

sugar.graphics.palettewindow module

class sugar.graphics.palettewindow.MouseSpeedDetector(*args: Any, **kwargs: Any)[source]

Bases: GObject

Detects mouse movement speed for palette activation.

__init__(delay, thresh)[source]

Create MouseSpeedDetector object.

Parameters:
  • delay – delay in msec

  • thresh – threshold in pixels (per tick of ‘delay’ msec)

start()[source]

Start detecting mouse speed.

stop()[source]

Stop detecting mouse speed.

class sugar.graphics.palettewindow.PaletteWindow(*args: Any, **kwargs: Any)[source]

Bases: GObject

Base class for palette windows.

__init__(**kwargs)[source]
destroy()[source]
set_invoker(invoker)[source]
get_invoker()[source]
set_content(widget)[source]

Set the main content widget for the palette window.

is_up()[source]
set_group_id(group_id)[source]
get_group_id()[source]

Get the current group ID.

update_position()[source]

Update the position of the palette.

get_full_size_request()[source]

Get the full size request for the palette.

popup(immediate=False)[source]

Show the palette.

popdown(immediate=False)[source]

Hide the palette.

on_invoker_enter()[source]
on_invoker_leave()[source]
on_enter()[source]
on_leave()[source]
get_rect()[source]
class sugar.graphics.palettewindow.Invoker(*args: Any, **kwargs: Any)[source]

Bases: GObject

Base class for palette invokers.

ANCHORED = 0
AT_CURSOR = 1
BOTTOM = [(0.0, 0.0, 0.0, 1.0), (-1.0, 0.0, 1.0, 1.0)]
RIGHT = [(0.0, 0.0, 1.0, 0.0), (0.0, -1.0, 1.0, 1.0)]
TOP = [(0.0, -1.0, 0.0, 0.0), (-1.0, -1.0, 1.0, 0.0)]
LEFT = [(-1.0, 0.0, 0.0, 0.0), (-1.0, -1.0, 0.0, 1.0)]
__init__()[source]
attach(parent)[source]
detach()[source]
get_position_for_alignment(alignment, palette_dim)[source]

Get position for specific alignment if it fits on screen.

get_position(palette_dim)[source]
get_alignment(palette_dim)[source]
has_rectangle_gap()[source]
draw_rectangle(event, palette)[source]
notify_popup()[source]
notify_popdown()[source]
notify_mouse_enter()[source]
notify_mouse_leave()[source]
notify_right_click(x=None, y=None)[source]

Notify the palette invoker of a right click and expand the palette as required. The x and y args should be that of where the event happened, relative to the root of the screen.

Args
x (float): the x coord of the event relative to the root

of the screen, eg. Gdk.EventTouch.x_root

y (float): the y coord of the event relative to the root

of the screen, eg. Gdk.EventTouch.y_root

notify_toggle_state()[source]
get_palette()[source]
set_palette(palette)[source]
get_cache_palette()[source]
set_cache_palette(cache_palette)[source]
get_toggle_palette()[source]
set_toggle_palette(toggle_palette)[source]
get_lock_palette()[source]
set_lock_palette(lock_palette)[source]
primary_text_clicked()[source]
get_rect()[source]

Get the rectangle for this invoker - implemented by subclasses.

get_toplevel()[source]

Get the toplevel window - implemented by subclasses.

class sugar.graphics.palettewindow.WidgetInvoker(*args: Any, **kwargs: Any)[source]

Bases: Invoker

Invoker for general widgets.

__init__(parent=None, widget=None)[source]
attach_widget(parent, widget=None)[source]
detach()[source]
get_rect()[source]

Get the rectangle for this invoker - implemented by subclasses.

has_rectangle_gap()[source]
draw_rectangle(cr, palette)[source]
get_widget()[source]
set_widget(widget)[source]
get_toplevel()[source]

Get the toplevel window - implemented by subclasses.

notify_popup()[source]
notify_popdown()[source]
class sugar.graphics.palettewindow.CursorInvoker(*args: Any, **kwargs: Any)[source]

Bases: Invoker

Invoker that tracks cursor position.

__init__(parent=None)[source]
attach(parent)[source]
detach()[source]

Detach from the parent.

get_rect()[source]

Get the rectangle for this invoker - implemented by subclasses.

get_toplevel()[source]

Get the toplevel window - implemented by subclasses.

class sugar.graphics.palettewindow.ToolInvoker(*args: Any, **kwargs: Any)[source]

Bases: WidgetInvoker

A palette invoker for toolbar buttons and other items. this invoker will properly align the palette so that is perpendicular to the toolbar (a horizontal toolbar will spawn a palette going downwards). it also draws the highlights specific to a toolitem.

for sugar.graphics.toolbutton.toolbutton and subclasses, you should not use the toolinvoker directly. instead, just subclass the tool button and override the create_palette function.

Parameters:

parent (gtk.widget) – toolitem to connect invoker to

__init__(parent=None)[source]
attach_tool(widget)[source]

Attach a toolitem to the invoker. Same behaviour as passing the parent argument to the constructor.

Parameters:

widget (Gtk.Widget) – toolitem to connect invoker to

primary_text_clicked()[source]
notify_popup()[source]
notify_popdown()[source]
class sugar.graphics.palettewindow.TreeViewInvoker(*args: Any, **kwargs: Any)[source]

Bases: Invoker

Invoker for TreeView cells.

__init__()[source]
attach_treeview(tree_view)[source]
detach()[source]
get_rect()[source]

Get the rectangle for this invoker - implemented by subclasses.

get_toplevel()[source]

Get the toplevel window - implemented by subclasses.

notify_popdown()[source]

sugar.graphics.radiopalette module

RadioPalette

Radio palette provides a way to create radio button groups within palettes, allowing users to select one option from multiple choices.

This GTK4 port modernizes the radio palette system while maintaining compatibility with Sugar’s palette interface patterns.

Example

Create a radio palette with multiple tool options.

from gi.repository import Gtk
from sugar.graphics.radiopalette import RadioToolsButton, RadioPalette
from sugar.graphics.toolbutton import ToolButton

# Create the main radio button
radio_button = RadioToolsButton(
    icon_name='tool-brush',
    tooltip='Drawing Tools'
)

# Create the palette
palette = RadioPalette(primary_text='Drawing Tools')
radio_button.set_palette(palette)

# Add tool options
brush_btn = ToolButton(icon_name='tool-brush')
palette.append(brush_btn, 'Brush')

pen_btn = ToolButton(icon_name='tool-pen')
palette.append(pen_btn, 'Pen')
class sugar.graphics.radiopalette.RadioMenuButton(*args: Any, **kwargs: Any)[source]

Bases: ToolButton

A toolbar button that shows a radio palette when clicked.

__init__(**kwargs)[source]
get_selected_button()[source]
set_selected_button(button)[source]
class sugar.graphics.radiopalette.RadioToolsButton(*args: Any, **kwargs: Any)[source]

Bases: RadioMenuButton

__init__(**kwargs)[source]
do_clicked()[source]
class sugar.graphics.radiopalette.RadioPalette(*args: Any, **kwargs: Any)[source]

Bases: Palette

A palette containing radio button options.

__init__(**kwargs)[source]
append(button, label)[source]

Add a button option to the radio palette.

Parameters:
  • button – The ToolButton to add to the radio group

  • label – The label text for this option

update_button()[source]
popdown(immediate=True)[source]

Hide the palette.

Parameters:
  • immediate (bool) – if True, hide instantly. If False, use animation.

  • state – deprecated parameter, ignored.

popup(immediate=True)[source]

Show the palette.

get_buttons()[source]
get_selected_button()[source]

sugar.graphics.radiotoolbutton module

RadioToolButton

Provides a RadioToolButton class, similar to a “push” button. A group of RadioToolButtons can be set, so that only one can be selected at a time. When a button is clicked, it depresses and is shaded darker.

It is also possible to set a tooltip to be dispalyed when the user scrolls over it with their cursor as well as an accelerator keyboard shortcut.

class sugar.graphics.radiotoolbutton.RadioToolButton(*args: Any, **kwargs: Any)[source]

Bases: ToolButton

A toolbar button that acts as a radio button.

Radio tool buttons work in groups where only one button can be active at a time. When one button is activated, all others in the group are automatically deactivated.

__init__(group=None, **kwargs)[source]

Initialize the radio tool button.

Parameters:
  • group – Another RadioToolButton to group with, or None for new group

  • **kwargs – Additional arguments passed to ToolButton

get_group()[source]

Get the list of buttons in this radio group.

set_group(group_member)[source]

Set the radio group by specifying another member.

Parameters:

group_member – Another RadioToolButton to join groups with

get_active()[source]

Get whether this button is active.

set_active(active)[source]

Set the active state of this button.

Parameters:

active – True to activate, False to deactivate

sugar.graphics.style module

Style

The style module defines constants for spacing and sizing, as well as classes for Colors and Fonts. Text rendering is handled by Pango and colors are inputted by their HTML code (e.g. #FFFFFF)

All the constants are expressed in pixels. They are defined for the XO screen and are usually adapted to different resolution by applying a zoom factor.

class sugar.graphics.style.Font(desc: str)[source]

Bases: object

A font defines the style of how the text should be rendered.

This implementation provides integration with Pango font descriptions and CSS styling.

Parameters:

desc (str) – A description of the Font object in Pango format

__init__(desc: str)[source]
__str__() str[source]

Returns description of font.

get_pango_desc()[source]

Returns Pango description of font. Cached for performance.

get_css_string() str[source]

Returns a CSS font specification string for GTK4 styling.

class sugar.graphics.style.Color(color: str, alpha: float = 1.0)[source]

Bases: object

A Color object defines a specific color with RGBA values.

This GTK4 implementation provides integration with modern color handling and CSS styling.

Parameters:
  • color (str) – String in the form #FFFFFF representing the color

  • alpha (float) – Transparency of color (0.0 to 1.0)

__init__(color: str, alpha: float = 1.0)[source]
get_rgba() Tuple[float, float, float, float][source]

Returns 4-tuple of red, green, blue, and alpha levels in range 0-1.

get_int() int[source]

Returns color encoded as an int, in the form rgba.

get_gdk_rgba()[source]

Returns GDK RGBA color object for GTK4. This replaces the deprecated get_gdk_color method.

get_gdk_color()[source]

Returns GDK standard color (deprecated in GTK4). Maintained for compatibility.

get_html() str[source]

Returns string in the standard HTML color format (#FFFFFF).

get_css_rgba() str[source]

Returns CSS rgba() string for GTK4 styling.

get_svg() str[source]

Returns HTML formatted color, unless the color is completely transparent, in which case returns “none”.

with_alpha(alpha: float) Color[source]

Returns a new Color with the specified alpha value.

sugar.graphics.style.zoom(units: float) int[source]

Returns size of units pixels at current zoom level.

Parameters:

units (int or float) – Size of item at full size

sugar.graphics.style.apply_css_to_widget(widget, css: str) None[source]

Apply CSS styling to a GTK4 widget.

Parameters:
  • widget – GTK4 widget to style

  • css (str) – CSS string to apply

sugar.graphics.style.ZOOM_FACTOR = 1.0

Scale factor, as float (eg. 0.72, 1.0)

sugar.graphics.style.DEFAULT_SPACING = 15

Spacing is placed in-between elements

sugar.graphics.style.DEFAULT_PADDING = 6

Padding is placed around an element

sugar.graphics.style.GRID_CELL_SIZE = 75

allow elements to tile neatly within boundaries of a grid http://wiki.sugarlabs.org/go/Human_Interface_Guidelines#The_Grid_System

sugar.graphics.style.LINE_WIDTH = 2

Thickness of a separator line

sugar.graphics.style.STANDARD_ICON_SIZE = 55

icon that fits within a grid cell

sugar.graphics.style.SMALL_ICON_SIZE = 33

small icon, used in palette menu items

sugar.graphics.style.MEDIUM_ICON_SIZE = 82

larger than standard

sugar.graphics.style.LARGE_ICON_SIZE = 110

larger than medium, used in journal empty view

sugar.graphics.style.XLARGE_ICON_SIZE = 151

larger than large, used in activity pulsing launcher icon

sugar.graphics.style.FONT_SIZE = 10

User’s preferred font size

sugar.graphics.style.FONT_FACE = 'Sans Serif'

User’s preferred font face

sugar.graphics.style.FONT_NORMAL = Font('Sans Serif 10.000000')

Normal font

sugar.graphics.style.FONT_BOLD = Font('Sans Serif bold 10.000000')

Bold font

sugar.graphics.style.FONT_NORMAL_H = 24

Height in pixels of normal font

sugar.graphics.style.FONT_BOLD_H = 24

Height in pixels of bold font

sugar.graphics.style.FONT_ITALIC = Font('Sans Serif italic 10')

Italic font

sugar.graphics.style.COLOR_BLACK = Color('#000000', alpha=1.0)

Black

sugar.graphics.style.COLOR_WHITE = Color('#ffffff', alpha=1.0)

White

sugar.graphics.style.COLOR_TRANSPARENT = Color('#ffffff', alpha=0.0)

Fully transparent color

sugar.graphics.style.COLOR_PANEL_GREY = Color('#c0c0c0', alpha=1.0)

Default background color of a window

sugar.graphics.style.COLOR_SELECTION_GREY = Color('#a6a6a6', alpha=1.0)

Background color of selected entry

sugar.graphics.style.COLOR_TOOLBAR_GREY = Color('#282828', alpha=1.0)

Color of toolbars

sugar.graphics.style.COLOR_BUTTON_GREY = Color('#808080', alpha=1.0)

Color of buttons

sugar.graphics.style.COLOR_INACTIVE_FILL = Color('#9d9fa1', alpha=1.0)

Fill colour of an inactive button

sugar.graphics.style.COLOR_INACTIVE_STROKE = Color('#757575', alpha=1.0)

Stroke colour of an inactive button

sugar.graphics.style.COLOR_TEXT_FIELD_GREY = Color('#e5e5e5', alpha=1.0)

Background color of entry

sugar.graphics.style.COLOR_HIGHLIGHT = Color('#e7e7e7', alpha=1.0)

Color of highlighted text

sugar.graphics.style.COLOR_PRIMARY = Color('#0066cc', alpha=1.0)

Primary accent color

sugar.graphics.style.COLOR_SUCCESS = Color('#00aa00', alpha=1.0)

Success state color

sugar.graphics.style.COLOR_WARNING = Color('#ff8800', alpha=1.0)

Warning state color

sugar.graphics.style.COLOR_ERROR = Color('#cc0000', alpha=1.0)

Error state color

sugar.graphics.style.PALETTE_CURSOR_DISTANCE = 10

Cursor invoked palettes will be placed this far from the cursor

sugar.graphics.style.TOOLBAR_ARROW_SIZE = 24

Size of arrow displayed under toolbar buttons

sugar.graphics.style.MENU_WIDTH_CHARS = 60

Max width of text in a palette menu, in chars

sugar.graphics.style.BORDER_RADIUS = 8

Default border radius for rounded corners

sugar.graphics.style.SHADOW_BLUR = 4

Default shadow blur radius

sugar.graphics.style.TRANSITION_DURATION = 200

Default transition duration in milliseconds

sugar.graphics.toolbarbox module

ToolbarBox

The ToolbarBox provides a horizontal toolbar container for Sugar activities, supporting both regular toolbar buttons and expandable toolbar sections.

class sugar.graphics.toolbarbox.ToolbarButton(*args: Any, **kwargs: Any)[source]

Bases: ToolButton

A toolbar button that can expand to show a toolbar page inline.

This is the main difference from regular ToolButton - it can show an entire toolbar page when clicked, similar to a collapsible section.

__init__(page=None, **kwargs)[source]
get_toolbar_box()[source]
property toolbar_box
get_page()[source]
set_page(page)[source]
is_in_palette()[source]
is_expanded()[source]
popdown()[source]
set_expanded(expanded)[source]
do_snapshot(snapshot)[source]

GTK4 drawing implementation with arrow indicator.

class sugar.graphics.toolbarbox.ToolbarBox(*args: Any, **kwargs: Any)[source]

Bases: Box

A container for toolbars that provides expandable toolbar sections.

The ToolbarBox contains a main horizontal toolbar and can show expanded toolbar pages below it when ToolbarButtons are activated.

__init__(padding=75)[source]
get_toolbar()[source]
property toolbar
get_expanded_button()[source]
set_expanded_button(button)[source]
property expanded_button
get_padding()[source]
set_padding(pad)[source]

sugar.graphics.toolbox module

Toolbox

A toolbox holds a group of toolbars in a list. One toolbar is displayed at a time. Toolbars are assigned an index and can be accessed using this index. Indices are generated in the order the toolbars are added.

class sugar.graphics.toolbox.Toolbox(*args: Any, **kwargs: Any)[source]

Bases: Box

Class to represent the toolbox of an activity. Groups a number of toolbars vertically, which can be accessed using their indices. The current toolbar is the only one displayed.

Emits current-toolbar-changed signal when the current toolbar is changed. This signal takes the current page index as an argument.

__init__()[source]
add_toolbar(name: str, toolbar: gi.repository.Gtk.Widget)[source]

Adds a toolbar to this toolbox. Toolbar will be added to the end of this toolbox, and its index will be 1 greater than the previously added index (index will be 0 if it is the first toolbar added).

Parameters:
  • name (str) – name of toolbar to be added

  • toolbar (Gtk.Widget) – Widget to be appended to this toolbox

remove_toolbar(index: int)[source]

Removes toolbar at the index specified.

Parameters:

index (int) – index of the toolbar to be removed

set_current_toolbar(index: int)[source]

Sets the current toolbar to that of the index specified and displays it.

Parameters:

index (int) – index of toolbar to be set as current toolbar

get_current_toolbar() int[source]

Returns current toolbar index.

Returns:

Index of current toolbar

Return type:

int

get_toolbar_count() int[source]

Returns the number of toolbars in this toolbox.

Returns:

Number of toolbars

Return type:

int

get_toolbar_at(index: int) gi.repository.Gtk.Widget | None[source]

Get the toolbar widget at the specified index.

Parameters:

index (int) – Index of toolbar to retrieve

Returns:

Toolbar widget or None if index is invalid

Return type:

Gtk.Widget

set_toolbar_label(index: int, label: str)[source]

Set the label text for a toolbar tab.

Parameters:
  • index (int) – Index of toolbar

  • label (str) – New label text

get_toolbar_label(index: int) str | None[source]

Get the label text for a toolbar tab.

Parameters:

index (int) – Index of toolbar

Returns:

Label text or None if index is invalid

Return type:

str

property current_toolbar: int

Returns current toolbar index.

Returns:

Index of current toolbar

Return type:

int

sugar.graphics.combobox module

The combobox module provides a combo box; a button like widget which creates a list popup when clicked. It’s best used outside of a toolbar when the user needs to choose from a short list of items.

Example:

class sugar.graphics.combobox.ComboBox(*args: Any, **kwargs: Any)[source]

Bases: ComboBox

This class provides a simple wrapper based on the Gtk.ComboBox. This lets you make a list of items, with a value, label and optionally an icon.

__init__()[source]
get_value()[source]

The value of the currently selected item; the same as the value argument that was passed to the append_item func.

Returns:

object, value of selected item

append_item(value, text, icon_name=None, file_name=None)[source]

This function adds another item to the bottom of the combo box list.

If either icon_name or file_name are supplied and icon column will be added to the combo box list.

Parameters:
  • value (object) – the value that will be returned by get_value, when this item is selected

  • text (str) – the user visible label for the item

  • icon_name (str) – the name of the icon in the theme to use for this item, optional and conflicting with file_name

  • file_name (str) – the path to a sugar (svg) icon to use for this item, optional and conflicting with icon_name

append_separator()[source]

Add a separator to the bottom of the combo box list. The separator can not be selected.

get_active_item()[source]

Get the row of data for the currently selected item.

Returns:

row of data in the format:

[value, text, pixbuf, is_separator]

remove_all()[source]

Remove all list items from the combo box.

sugar.graphics.toolcombobox module

STABLE.

class sugar.graphics.toolcombobox.ToolComboBox(*args: Any, **kwargs: Any)[source]

Bases: Box

__init__(combo=None, label_text='', **kwargs)[source]
do_set_property(pspec, value)[source]
set_label_text(text)[source]

Set the label text.

get_label_text()[source]

Get the label text.

sugar.graphics.toggletoolbutton module

STABLE.

class sugar.graphics.toggletoolbutton.ToggleToolButton(*args: Any, **kwargs: Any)[source]

Bases: ToggleButton

UI for toggletoolbutton. A ToggleToolButton is a toggle button widget that can be used in toolbars, having an icon, a tooltip palette, and an accelerator. Use ToggleToolButton() to create a new ToggleToolButton.

Parameters:
  • accelerator (string) – keyboard shortcut to be used to

  • button. (hovers over toggle)

  • here (Find about format)

  • https – //docs.gtk.org/gtk4/func.accelerator_parse.html

  • tooltip (string) – tooltip to be displayed when user

  • button.

Keyword Arguments:

icon_name (string) – name of themed icon which is to be used.

__init__(icon_name=None)[source]
set_icon_name(icon_name)[source]

Sets the icon for the tool button from a named themed icon. If it is none then no icon will be shown.

Parameters:
  • icon_name (string) – The name for a themed icon.

  • too. (It can be set as 'None')

Example

set_icon_name(‘view-radial’)

get_icon_name()[source]

The get_icon_name() method returns the value of the icon_name property that contains the name of a themed icon or None.

create_palette()[source]
get_palette()[source]
set_palette(palette)[source]
get_palette_invoker()[source]
set_palette_invoker(palette_invoker)[source]
set_tooltip(text)[source]

Sets the tooltip of the toogle tool button. Displays when user hovers over the button with cursor.

Parameters:

tooltip (string) – tooltip to be added to the button

set_accelerator(accelerator)[source]

Sets keyboard shortcut that activates this button.

Parameters:
  • accelerator (string) – accelerator to be set. Should be in

  • <modifier>Letter (form)

  • here (Find about format)

  • https – //docs.gtk.org/gtk4/func.accelerator_parse.html

Example

set_accelerator(self, ‘accel’)

get_accelerator()[source]

Returns above accelerator string.

do_snapshot(snapshot)[source]

Implementation method for drawing the toggle tool button (GTK4)

do_clicked()[source]

Implementation method for hiding the tooltip when the toggle button is clicked

sugar.graphics.toolbutton module

ToolButton

The toolbutton module provides the ToolButton class, which is a Gtk.Button styled as a toolbar button with icon and tooltip for Sugar.

Example

Add a tool button to a window:

from gi.repository import Gtk
from sugar.graphics.toolbutton import ToolButton

def __clicked_cb(button):
    print("tool button was clicked")

app = Gtk.Application()

def on_activate(app):
    w = Gtk.ApplicationWindow(application=app)
    b = ToolButton(icon_name='dialog-ok', tooltip='a tooltip')
    b.connect('clicked', __clicked_cb)
    w.set_child(b)
    w.present()

app.connect('activate', on_activate)
app.run()

STABLE.

sugar.graphics.toolbutton.setup_accelerator(tool_button)[source]
class sugar.graphics.toolbutton.ToolButton(*args: Any, **kwargs: Any)[source]

Bases: Button

The ToolButton class manages a Gtk.Button styled as a toolbar button for Sugar.

In GTK4, this replaces Gtk.ToolButton which was deprecated. The button is styled to look and behave like a traditional toolbar button.

Parameters:
  • icon_name (str, optional) – name of themed icon.

  • accelerator (str, optional) – keyboard shortcut to activate this button.

  • tooltip (str, optional) – tooltip displayed on hover.

  • hide_tooltip_on_click (bool, optional) – Whether tooltip is hidden on click.

__init__(icon_name=None, **kwargs)[source]
set_tooltip(tooltip: str | None)[source]

Set the tooltip.

Parameters:

tooltip (string) – tooltip to be set.

get_tooltip() str | None[source]
get_hide_tooltip_on_click() bool[source]

Return True if the tooltip is hidden when a user clicks on the button, otherwise return False.

set_hide_tooltip_on_click(hide_tooltip_on_click: bool)[source]

Set whether or not the tooltip is hidden when a user clicks on the button.

Parameters:
  • hide_tooltip_on_click (bool) – True if the tooltip is

  • click (hidden on)

  • otherwise. (and False)

set_accelerator(accelerator: str | None)[source]

Set accelerator that activates the button.

Parameters:

accelerator (string) – accelerator to be set.

get_accelerator() str | None[source]

Return accelerator that activates the button.

set_icon_name(icon_name: str | None)[source]
get_icon_name() str | None[source]

Get the icon name.

Returns:

The icon name or None if no icon is set.

set_icon_widget(icon_widget: gi.repository.Gtk.Widget | None)[source]

Set a custom icon widget.

Parameters:

icon_widget – widget to use as icon.

get_icon_widget() gi.repository.Gtk.Widget | None[source]
set_label(label: str | None)[source]
get_label() str | None[source]
create_palette() Palette | None[source]
get_palette() Palette | None[source]

Get the current palette.

set_palette(palette: Palette | None)[source]
get_palette_invoker() ToolInvoker | None[source]
set_palette_invoker(palette_invoker: ToolInvoker | None)[source]
do_snapshot(snapshot)[source]

GTK4 drawing implementation.

set_active(active: bool)[source]
get_active() bool[source]

Get the active state of the button.

sugar.graphics.window module

Window - GTK4 Port

Window management for Sugar GTK4 activities.

Provides window classes for managing Sugar activity windows with fullscreen support, toolbar management, and tray integration.

Classes:

UnfullscreenButton: Button to exit fullscreen mode Window: Main activity window container

class sugar.graphics.window.UnfullscreenButton(*args: Any, **kwargs: Any)[source]

Bases: Window

A ready-made “Unfullscreen” button for GTK4.

Used by Window to exit fullscreen mode. Ported to use GTK4 APIs.

__init__()[source]
connect_button_clicked(callback)[source]

Connect a callback to button click.

class sugar.graphics.window.Window(*args: Any, **kwargs: Any)[source]

Bases: ApplicationWindow

A Sugar activity window for GTK4.

Used as a container to display things that happen in an activity. A window contains a canvas widget, and may contain toolbar and tray widgets.

The window layout is:
  • toolbar (optional)

  • alerts (as overlays)

  • canvas (main content)

  • tray (optional)

Window supports fullscreen mode where toolbar and tray are hidden.

Key bindings:
  • Escape: exit fullscreen mode

  • Alt+Space: toggle tray visibility

__init__(**kwargs)[source]
reveal()[source]

Make window active.

Brings the window to the top and makes it active, even after invoking on response to non-GTK events.

is_fullscreen()[source]

Check if the window is fullscreen.

Returns:

window is fullscreen

Return type:

bool

fullscreen()[source]

Make the window fullscreen.

The toolbar and tray will be hidden, and the UnfullscreenButton will be shown for a short time.

unfullscreen()[source]

Restore the window to non-fullscreen mode.

The UnfullscreenButton will be hidden, and the toolbar and tray will be shown.

set_canvas(canvas)[source]

Set canvas widget.

Parameters:

canvas (Gtk.Widget) – the canvas to set

get_canvas()[source]

Get canvas widget.

Returns:

the canvas

Return type:

Gtk.Widget

set_toolbar_box(toolbar_box)[source]

Set toolbar box widget.

Parameters:

toolbar_box (Gtk.Widget) – the toolbar box to set

get_toolbar_box()[source]

Get toolbar box widget.

Returns:

the current toolbar box

Return type:

Gtk.Widget

set_tray(tray, position=gi.repository.Gtk.PositionType.BOTTOM)[source]

Set the tray.

Parameters:
add_alert(alert)[source]

Add an alert to the window as an overlay.

Parameters:

alert (Gtk.Widget) – the alert to add

remove_alert(alert)[source]

Remove an alert from the window.

Parameters:

alert (Gtk.Widget) – the alert to remove

set_enable_fullscreen_mode(enable)[source]

Set enable fullscreen mode.

Parameters:

enable (bool) – enable fullscreen mode

get_enable_fullscreen_mode()[source]

Get enable fullscreen mode.

Returns:

enable fullscreen mode

Return type:

bool

property canvas

Get canvas widget.

Returns:

the canvas

Return type:

Gtk.Widget

property toolbar_box

Get toolbar box widget.

Returns:

the current toolbar box

Return type:

Gtk.Widget

sugar.graphics.xocolor module

XoColor - GTK4 Port

This class represents all of the colors that the XO can take on. Each pair of colors represents the fill color and the stroke color.

Ported to GTK4 from sugar3.graphics.xocolor

class sugar.graphics.xocolor.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")
__init__(color_string=None)[source]
__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/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

Module contents

Graphics Module

Visual components, styling, and UI widgets for Sugar GTK4 activities.

class sugar.graphics.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.graphics.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.graphics.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.graphics.CanvasIcon(*args: Any, **kwargs: Any)[source]

Bases: EventIcon

An EventIcon with active and prelight states, and a styleable background.

This icon responds to mouse hover and press states with visual feedback.

__init__(**kwargs)[source]
do_snapshot(snapshot)[source]

Override to render background based on state.

class sugar.graphics.CellRendererIcon[source]

Bases: object

Icon renderer for use in list/tree views.

Note: GTK4 uses a different approach for cell rendering. This is provided for compatibility but may need adaptation.

__init__()[source]
get_surface(sensitive: bool = True) cairo.ImageSurface | None[source]

Get rendered surface.

set_file_name(file_name: str)[source]
set_fill_color(color: str)[source]
set_icon_name(icon_name: str)[source]
set_size(size: int)[source]
set_stroke_color(color: str)[source]
set_xo_color(xo_color: XoColor)[source]
sugar.graphics.get_icon_file_name(icon_name: str) str | None[source]

Resolve icon name to file path using GTK4 icon theme.

Parameters:

icon_name – Name of icon to resolve

Returns:

Path to icon file or None if not found

sugar.graphics.get_surface(icon_name: str | None = None, file_name: str | None = None, fill_color: str | None = None, stroke_color: str | None = None, pixel_size: int = 48, **kwargs) cairo.ImageSurface | None[source]

Get cairo surface for an icon with specified properties.

Parameters:
  • icon_name – Icon name from theme

  • file_name – Path to icon file

  • fill_color – Fill color as hex string

  • stroke_color – Stroke color as hex string

  • pixel_size – Size in pixels

  • **kwargs – Additional properties

Returns:

Cairo surface or None if icon not found

sugar.graphics.get_icon_state(base_name: str, perc: float, step: int = 5) str | None[source]

Get the closest icon name for a given state in percent.

Parameters:
  • base_name – Base icon name (e.g., ‘network-wireless’)

  • perc – Desired percentage between 0 and 100

  • step – Step increment to find possible icons

Returns:

Icon name that represents given state, or None if not found