sugar4.graphics package
Submodules
sugar4.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 sugar4.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 sugar4.graphics.alert.Alert(*args: Any, **kwargs: Any)[source]
Bases:
BoxAlerts 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 anActivityvia 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.Entrysignal 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 sugar4.graphics.alert.ConfirmationAlert(*args: Any, **kwargs: Any)[source]
Bases:
AlertAn alert with two buttons; Ok and Cancel.
When a button is clicked, the
ConfirmationAlertwill 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 sugar4.graphics.alert.ErrorAlert(*args: Any, **kwargs: Any)[source]
Bases:
AlertAn alert with one button; Ok.
When the button is clicked, the
ErrorAlertwill emit a response signal with a response identifierGtk.ResponseType.OK.- Parameters:
**kwargs – parameters for
Alert
- class sugar4.graphics.alert.TimeoutAlert(*args: Any, **kwargs: Any)[source]
Bases:
_TimeoutAlertA timed alert with two buttons; Continue and Cancel. The Continue button contains a countdown of seconds remaining.
When a button is clicked, the
TimeoutAlertwill 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
TimeoutAlertwill emit a response signal with a response identifier of -1.
- class sugar4.graphics.alert.NotifyAlert(*args: Any, **kwargs: Any)[source]
Bases:
_TimeoutAlertA timed alert with one button; Ok. The button contains a countdown of seconds remaining.
When the button is clicked, the
NotifyAlertwill emit a response signal with a response identifierGtk.ResponseType.OK.If the countdown reaches zero before the button is clicked, the
NotifyAlertwill emit a response signal with a response identifier of -1.
sugar4.graphics.animator module
Animator
The animator module provides a simple framework to create animations.
Example
Animate the size of a window:
from gi.repository import Gtk
from sugar4.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 sugar4.graphics.animator.Animator(*args: Any, **kwargs: Any)[source]
Bases:
GObjectThe 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 (
sugar4.graphics.animator.Animation) – the animation instance to add
- class sugar4.graphics.animator.Animation(start, end)[source]
Bases:
objectThe 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 sugar4.graphics.animator.FadeAnimation(widget, start_opacity=0.0, end_opacity=1.0)[source]
Bases:
AnimationA 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 sugar4.graphics.animator.ScaleAnimation(widget, start_scale=0.0, end_scale=1.0)[source]
Bases:
AnimationA 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 sugar4.graphics.animator.MoveAnimation(widget, start_pos, end_pos)[source]
Bases:
AnimationA 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)
sugar4.graphics.icon module
Icons
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.
This module provides modern icon widgets using native gesture handling and snapshot-based rendering for improved performance and accessibility.
- Classes:
Icon: Basic icon widget for displaying themed icons EventIcon: Icon with mouse event handling using gesture controllers 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 sugar4.graphics.icon.Icon(*args: Any, **kwargs: Any)[source]
Bases:
WidgetBasic Sugar icon widget.
Displays themed icons with Sugar’s color customization features. Uses modern snapshot-based rendering for improved performance.
- Properties:
icon_name (str): Icon name from theme file_name (str): Path to icon file pixel_size (int): Size in pixels fill_color (str): Fill color as hex string stroke_color (str): Stroke color as hex string xo_color (XoColor): Sugar color pair badge_name (str): Badge icon name alpha (float): Icon transparency (0.0-1.0) scale (float): Icon scale factor sensitive (bool): Whether icon appears sensitive
- __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]
Render icon using snapshot-based drawing.
- class sugar4.graphics.icon.EventIcon(*args: Any, **kwargs: Any)[source]
Bases:
IconIcon widget with mouse event handling using gesture controllers.
Provides click, press, and release events through modern gesture handling for better touch and accessibility support.
- Signals:
clicked: Emitted when icon is clicked pressed: Emitted when icon is pressed released: Emitted when icon is released activate: Emitted when icon is activated
- class sugar4.graphics.icon.CanvasIcon(*args: Any, **kwargs: Any)[source]
Bases:
EventIconAn EventIcon with active and prelight states, and a styleable background.
This icon responds to mouse hover and press states with visual feedback.
- class sugar4.graphics.icon.CellRendererIcon[source]
Bases:
objectIcon renderer for use in list/tree views.
Modern implementations use different approaches for cell rendering. This provides compatibility for legacy code that may need adaptation.
Note: Consider using modern list/tree widget patterns instead.
- sugar4.graphics.icon.get_icon_file_name(icon_name: str) str | None[source]
Resolve icon name to file path using icon theme.
Uses the system icon theme to find the appropriate icon file for the given icon name.
- Parameters:
icon_name – Name of icon to resolve
- Returns:
Path to icon file or None if not found
- sugar4.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
- sugar4.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
sugar4.graphics.objectchooser module
STABLE.
- sugar4.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 sugar4.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 sugar4.graphics.objectchooser.ObjectChooser(parent=None, what_filter=None, filter_type=None, show_preview=False)[source]
Bases:
objectUI 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
sugar4.mimeused 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.
sugar4.graphics.palette module
- class sugar4.graphics.palette.Palette(*args: Any, **kwargs: Any)[source]
Bases:
PaletteWindowFloating 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.
sugar4.graphics.palettegroup module
sugar4.graphics.palettewindow module
- class sugar4.graphics.palettewindow.MouseSpeedDetector(*args: Any, **kwargs: Any)[source]
Bases:
GObjectDetects mouse movement speed for palette activation.
- class sugar4.graphics.palettewindow.PaletteWindow(*args: Any, **kwargs: Any)[source]
Bases:
GObjectBase class for palette windows.
- class sugar4.graphics.palettewindow.Invoker(*args: Any, **kwargs: Any)[source]
Bases:
GObjectBase class for palette invokers.
- 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 sugar4.graphics.palettewindow.WidgetInvoker(*args: Any, **kwargs: Any)[source]
Bases:
InvokerInvoker for general widgets.
- class sugar4.graphics.palettewindow.CursorInvoker(*args: Any, **kwargs: Any)[source]
Bases:
InvokerInvoker that tracks cursor position.
- class sugar4.graphics.palettewindow.ToolInvoker(*args: Any, **kwargs: Any)[source]
Bases:
WidgetInvokerA 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
sugar4.graphics.toolbutton.toolbuttonand 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
sugar4.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 implementation 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 sugar4.graphics.radiopalette import RadioToolsButton, RadioPalette
from sugar4.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 sugar4.graphics.radiopalette.RadioMenuButton(*args: Any, **kwargs: Any)[source]
Bases:
ToolButtonA toolbar button that shows a radio palette when clicked.
- class sugar4.graphics.radiopalette.RadioToolsButton(*args: Any, **kwargs: Any)[source]
Bases:
RadioMenuButton
- class sugar4.graphics.radiopalette.RadioPalette(*args: Any, **kwargs: Any)[source]
Bases:
PaletteA 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
sugar4.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 sugar4.graphics.style.Font(desc: str)[source]
Bases:
objectA 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 sugar4.graphics.style.Color(color: str, alpha: float = 1.0)[source]
Bases:
objectA Color object defines a specific color with RGBA values.
This 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.
- sugar4.graphics.style.zoom(units: float) int[source]
Returns size of units pixels at current zoom level.
- sugar4.graphics.style.apply_css_to_widget(widget, css: str) None[source]
Apply CSS styling to a widget.
- Parameters:
widget – Widget to style
css (str) – CSS string to apply
- sugar4.graphics.style.GRID_CELL_SIZE = 75[source]
allow elements to tile neatly within boundaries of a grid http://wiki.sugarlabs.org/go/Human_Interface_Guidelines#The_Grid_System
- sugar4.graphics.style.XLARGE_ICON_SIZE = 151[source]
larger than large, used in activity pulsing launcher icon
- sugar4.graphics.style.FONT_SIZE = 10
User’s preferred font size
- sugar4.graphics.style.FONT_FACE = 'Sans Serif'
User’s preferred font face
- sugar4.graphics.style.COLOR_TRANSPARENT = Color('#ffffff', alpha=0.0)[source]
Fully transparent color
- sugar4.graphics.style.COLOR_PANEL_GREY = Color('#c0c0c0', alpha=1.0)[source]
Default background color of a window
- sugar4.graphics.style.COLOR_SELECTION_GREY = Color('#a6a6a6', alpha=1.0)[source]
Background color of selected entry
- sugar4.graphics.style.COLOR_INACTIVE_FILL = Color('#9d9fa1', alpha=1.0)[source]
Fill colour of an inactive button
- sugar4.graphics.style.COLOR_INACTIVE_STROKE = Color('#757575', alpha=1.0)[source]
Stroke colour of an inactive button
- sugar4.graphics.style.COLOR_TEXT_FIELD_GREY = Color('#e5e5e5', alpha=1.0)[source]
Background color of entry
- sugar4.graphics.style.COLOR_HIGHLIGHT = Color('#e7e7e7', alpha=1.0)[source]
Color of highlighted text
- sugar4.graphics.style.PALETTE_CURSOR_DISTANCE = 10[source]
Cursor invoked palettes will be placed this far from the cursor
sugar4.graphics.toolbarbox module
ToolbarBox
The ToolbarBox provides a horizontal toolbar container for Sugar activities, supporting both regular toolbar buttons and expandable toolbar sections.
- class sugar4.graphics.toolbarbox.ToolbarButton(*args: Any, **kwargs: Any)[source]
Bases:
ToolButtonA 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.
sugar4.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 sugar4.graphics.toolbox.Toolbox(*args: Any, **kwargs: Any)[source]
Bases:
BoxClass 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:
sugar4.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 sugar4.graphics.combobox.ComboBox(*args: Any, **kwargs: Any)[source]
Bases:
ComboBoxThis 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.
sugar4.graphics.toolcombobox module
STABLE.
sugar4.graphics.window module
Window Management
Window management for Sugar 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 sugar4.graphics.window.UnfullscreenButton(*args: Any, **kwargs: Any)[source]
Bases:
WindowA ready-made “Unfullscreen” button.
Used by
Windowto exit fullscreen mode using modern window management.
- class sugar4.graphics.window.Window(*args: Any, **kwargs: Any)[source]
Bases:
ApplicationWindowA Sugar activity window.
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:
sugar4.graphics.xocolor module
XoColor
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.
Modern implementation with improved color handling and CSS support.
- class sugar4.graphics.xocolor.XoColor(color_string=None)[source]
Bases:
objectDefines 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 activities.
- class sugar4.graphics.XoColor(color_string=None)[source]
Bases:
objectDefines 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 sugar4.graphics.Icon(*args: Any, **kwargs: Any)[source]
Bases:
WidgetBasic Sugar icon widget.
Displays themed icons with Sugar’s color customization features. Uses modern snapshot-based rendering for improved performance.
- Properties:
icon_name (str): Icon name from theme file_name (str): Path to icon file pixel_size (int): Size in pixels fill_color (str): Fill color as hex string stroke_color (str): Stroke color as hex string xo_color (XoColor): Sugar color pair badge_name (str): Badge icon name alpha (float): Icon transparency (0.0-1.0) scale (float): Icon scale factor sensitive (bool): Whether icon appears sensitive
- __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]
Calculate widget size requirements.
- do_snapshot(snapshot: gi.repository.Gtk.Snapshot)[source]
Render icon using snapshot-based drawing.
- class sugar4.graphics.EventIcon(*args: Any, **kwargs: Any)[source]
Bases:
IconIcon widget with mouse event handling using gesture controllers.
Provides click, press, and release events through modern gesture handling for better touch and accessibility support.
- Signals:
clicked: Emitted when icon is clicked pressed: Emitted when icon is pressed released: Emitted when icon is released activate: Emitted when icon is activated
- class sugar4.graphics.CanvasIcon(*args: Any, **kwargs: Any)[source]
Bases:
EventIconAn EventIcon with active and prelight states, and a styleable background.
This icon responds to mouse hover and press states with visual feedback.
- class sugar4.graphics.CellRendererIcon[source]
Bases:
objectIcon renderer for use in list/tree views.
Modern implementations use different approaches for cell rendering. This provides compatibility for legacy code that may need adaptation.
Note: Consider using modern list/tree widget patterns instead.
- sugar4.graphics.get_icon_file_name(icon_name: str) str | None[source]
Resolve icon name to file path using icon theme.
Uses the system icon theme to find the appropriate icon file for the given icon name.
- Parameters:
icon_name – Name of icon to resolve
- Returns:
Path to icon file or None if not found
- sugar4.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
- sugar4.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