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()
andremove_alert()
to add and remove an alert. These methods are inherited by anActivity
via superclassWindow
.The alert is placed between the canvas and the toolbox, or above the canvas in fullscreen mode.
- Parameters:
- 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:
- 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:
- Returns:
the button added to the alert
- Return type:
- 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 beGtk.ResponseType.OK
. For the Cancel button,Gtk.ResponseType.CANCEL
.- Parameters:
**kwargs – parameters for
Alert
- 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 identifierGtk.ResponseType.OK
.- Parameters:
**kwargs – parameters for
Alert
- 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 beGtk.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.
- 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 identifierGtk.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.
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.
- add(animation)[source]
Add an animation to this animator.
- Parameters:
animation (
sugar.graphics.animator.Animation
) – the animation instance to add
- 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:
# 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)
- 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.
- 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)
- 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
- 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)
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]
- 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
- 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.
- 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.
- 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.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:
- 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 ObjectChooserwhat_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 chooserfilter_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)
- run()[source]
Runs the object chooser and displays it.
- Returns:
Gtk.ResponseType constant, the response received from displaying 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.
- popdown(immediate=False, state=None)[source]
Hide the palette.
- Parameters:
immediate (bool) – if True, hide instantly. If False, use animation.
state – deprecated parameter, ignored.
sugar.graphics.palettegroup module
sugar.graphics.palettewindow module
- class sugar.graphics.palettewindow.MouseSpeedDetector(*args: Any, **kwargs: Any)[source]
Bases:
GObject
Detects mouse movement speed for palette activation.
- class sugar.graphics.palettewindow.PaletteWindow(*args: Any, **kwargs: Any)[source]
Bases:
GObject
Base class for palette windows.
- 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)]
- get_position_for_alignment(alignment, palette_dim)[source]
Get position for specific alignment if it fits on screen.
- 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
- class sugar.graphics.palettewindow.WidgetInvoker(*args: Any, **kwargs: Any)[source]
Bases:
Invoker
Invoker for general widgets.
- class sugar.graphics.palettewindow.CursorInvoker(*args: Any, **kwargs: Any)[source]
Bases:
Invoker
Invoker that tracks cursor position.
- 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
- 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
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.
- class sugar.graphics.radiopalette.RadioToolsButton(*args: Any, **kwargs: Any)[source]
Bases:
RadioMenuButton
- class sugar.graphics.radiopalette.RadioPalette(*args: Any, **kwargs: Any)[source]
Bases:
Palette
A palette containing radio button options.
- 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
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
- 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:
- get_rgba() Tuple[float, float, float, float] [source]
Returns 4-tuple of red, green, blue, and alpha levels in range 0-1.
- 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.
- sugar.graphics.style.zoom(units: float) int [source]
Returns size of units pixels at current zoom level.
- 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.
- property toolbar_box
- 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.
- property toolbar
- property expanded_button
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.
- 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:
- get_toolbar_count() int [source]
Returns the number of toolbars in this toolbox.
- Returns:
Number of toolbars
- Return type:
- 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:
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.- 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.
sugar.graphics.toolcombobox module
STABLE.
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.
- 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
- 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:
- 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
- set_toolbar_box(toolbar_box)[source]
Set toolbar box widget.
- Parameters:
toolbar_box (Gtk.Widget) – the toolbar box to set
- set_tray(tray, position=gi.repository.Gtk.PositionType.BOTTOM)[source]
Set the tray.
- Parameters:
tray (Gtk.Widget) – the tray to set
position (Gtk.PositionType) – the edge to set the tray at
- 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:
- property canvas
Get canvas widget.
- Returns:
the canvas
- Return type:
- property toolbar_box
Get toolbar box widget.
- Returns:
the current toolbar box
- Return type:
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")
- 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:
- Raises:
ValueError – If color_string cannot be parsed
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")
- 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:
- 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:
- 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.
- 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
- 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.
- 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.
- 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