Skip to content

DrawingAction

For many if not most applications, the interface documented for Canvas is sufficient. However, it is also possible to directly manipulate a Canvas's stored instructions, thereby modifying the results in a non-linear fashion.

Usage

Each drawing operation that has been performed on a Canvas is represented by an object of class DrawingAction. Each drawing method has a corresponding DrawingAction subclass of the same name, except in CamelCase. For example, the line_to() method creates a LineTo object, and LineTo is a subclass of DrawingAction.

The current state of the drawing context is represented by a state object. All states are subclasses of the abstract BaseState; the simplest is State. Initially, a canvas has only one state; this initial state is always accessible via the canvas's root_state attribute.

Each state stores a list of its associated drawing actions.

import toga

canvas = toga.Canvas()

print(canvas.root_state)
# State()
print(canvas.root_state.drawing_actions)
# []

canvas.rect(0, 0, 10, 10)
canvas.stroke()

print(canvas.root_state.drawing_actions)
# [Rect(x=0, y=0, width=10, height=10),
#  Stroke(stroke_style=None, line_width=None, line_dash=None)]

When you save and then restore the state of the drawing context using a context manager (e.g., state(), stroke(), or fill()), a new state object is created and inserted into the currently active state's drawing_actions. This is possible because BaseState is itself a subclass of DrawingAction.

Continuing from the previous example:

with canvas.state():
    canvas.line_width = 10
    canvas.line_dash = [1, 2]

canvas.fill()

print(canvas.root_state.drawing_actions)
# [Rect(x=0, y=0, width=10, height=10),
#  Stroke(stroke_style=None, line_width=None, line_dash=None),
#  State(),
#  Fill(fill_rule=FillRule.NONZERO, fill_style=None)]

The actions corresponding to setting line width and line dash are contained inside the State(), like so:

root_state ─┬─ Rect
            ├─ Stroke
            ├─ State ──┬─ SetLineWidth
            └─ Fill    └─ SetLineDash

Note that the the Fill isn't inside the State, because its method was called after the context manager exited.

Accessing specific drawing actions

A state's drawing actions are a list, and can be accessed using list syntax. For example, if you wanted to access the Fill object in the previous example, you could use:

fill = canvas.root_state.drawing_actions[3]

However, this is not very practical, especially if the action of interest is nested within several states. A better way is to leverage the fact that each drawing method returns its drawing action. The line calling the fill method could be modified to:

fill = canvas.fill()

And now fill is a direct reference to the Fill object. This Fill object can then be modified as required.

The same is true even when a method is being used as a context manager, using with ... as ... syntax. For instance, the following code would bind fill, stroke, and move_to to the Fill, Stroke, and MoveTo drawing actions created by the methods called:

with canvas.fill() as fill:
    with canvas.stroke() as stroke:
        move_to = canvas.move_to(0, 0)

Modifying attributes of drawing actions

DrawingAction objects also have attributes corresponding to the equivalent method's parameters. If you modify these attributes, it will retroactively alter what is drawn on the canvas. For example, consider the following code and its output:

import toga

canvas = toga.Canvas(width=200, height=200)
with canvas.stroke() as stroke:
    canvas.move_to(50, 50)
    first_line = canvas.line_to(150, 50)
    canvas.line_to(50, 150)

Initial output

An initial set of strokes on a canvas.

Since we've saved references, we can alter the parameters of the stroke and the first line segment. After altering attributes like this, the canvas's redraw() method must be called to ensure the results are rendered on screen.

stroke.line_width = 20
first_line.y = 150

canvas.redraw()

After editing

An updated stroke path and width, after calling redraw() on the canvas.

The line has gotten wider, and the second point has moved down to a y coordinate of 150, which alters the orientation of both line segments.

Creating and adding new drawing actions

DrawingAction objects can also be created directly, and the list of DrawingAction objects on a state can be manually altered. As with altering attributes, and direct modification of the lists of drawing actions should be followed by a call to the canvas's redraw method.

An extra point could be added to the above path like so:

from toga.widgets.canvas import LineTo

new_point = LineTo(150, 50)
stroke.drawing_actions.insert(1, new_point)

canvas.redraw()

After adding a new drawing action

An updated stroke with an additional line segment, after calling redraw() on the canvas.

This example uses insert, but drawing_actions is a list, with all of a list's normal methods, including append, remove, and extend. Remember to call redraw after any such alterations.

Reference

Bases: ABC

A Canvas drawing operation.

Every canvas drawing method creates a DrawingAction, adds it to the currently active state, and returns it. Each argument passed to the method becomes a property of the DrawingAction, which can be modified as shown in Modifying attributes of Drawing actions.

A DrawingAction can also be created manually. Their constructors take the same arguments as the corresponding Canvas drawing method, and their classes have the same names, but capitalized.

Source code in core/src/toga/widgets/canvas/drawingaction.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
class DrawingAction(ABC):
    """A [`Canvas`][toga.Canvas] drawing operation.

    Every canvas drawing method creates a `DrawingAction`, adds it to the currently
    active state, and returns it. Each argument passed to the method becomes a property
    of the `DrawingAction`, which can be modified as shown in
    [Modifying attributes of Drawing actions][].

    A `DrawingAction` can also be
    [created manually][creating-and-adding-new-drawing-actions]. Their constructors take
    the same arguments as the corresponding [`Canvas`][toga.Canvas] drawing method, and
    their classes have the same names, but capitalized.
    """

    def __repr__(self) -> str:
        if is_dataclass(self):
            str_fields = []
            for field in fields(self):
                match value := getattr(self, field.name):
                    case float():
                        str_value = f"{value:.3f}"
                    case Enum():
                        str_value = str(value)
                    case _:
                        str_value = repr(value)
                str_fields.append(f"{field.name}={str_value}")

            parenthetical = ", ".join(str_fields)

        else:
            parenthetical = ""

        return f"{type(self).__name__}({parenthetical})"

    @abstractmethod
    def _draw(self, context: Any) -> None:
        """Called by parent state to execute this drawing action."""

    def __contains__(self, other: DrawingAction):
        return hasattr(self, "drawing_actions") and any(
            action is other or other in action for action in self.drawing_actions
        )

Bases: DrawingAction, DrawingActionDispatch, ABC

A base class for all drawing actions that can function as state-saving context managers.

Source code in core/src/toga/widgets/canvas/state.py
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
class BaseState(DrawingAction, DrawingActionDispatch, ABC):
    """A base class for all drawing actions that can function as state-saving context
    managers.
    """

    drawing_actions: list[DrawingAction]
    """The list of all drawing actions contained by this state.

    If you add or remove drawing actions to this list, you'll need to call
    [`Canvas.redraw()`][toga.Canvas.redraw] for the changes to be rendered.
    """

    def __init__(self):
        self.drawing_actions = []
        self._can_be_entered = True

    @abstractmethod
    def _draw(self, context: Any) -> None: ...

    @property
    def _action_target(self):
        # State itself holds its drawing actions.
        return self

    @property
    def _active_state(self):
        """Return the currently active state, either this or a sub-state."""
        if self.drawing_actions:
            # If a sub-state is active, it must be the last action in the list;
            # subsequent actions would be added to that sub-state (or a sub-state of
            # it).
            last = self.drawing_actions[-1]
            if getattr(last, "_is_open", False):
                return last._active_state

        return self

    def __enter__(self):
        if not self._can_be_entered:
            raise RuntimeError(
                "A Canvas context manager can only be entered once, and only before "
                "any subsequent drawing actions are added."
            )

        self._is_open = True
        self._can_be_entered = False
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self._is_open = False
        # Don't suppress any exceptions
        return False

    ##########################################################################
    # 2026-04: Backwards compatibility for <= 0.5.3
    ##########################################################################

    # These preserve the old signature, and warn about the new one.

    def fill(
        self,
        color: ColorT | None | object = NOT_PROVIDED,
        fill_rule: FillRule = FillRule.NONZERO,
    ) -> AbstractContextManager[Fill]:
        fill = Fill(fill_rule=fill_rule, fill_style=color)
        self._add_to_target(fill)
        warnings.warn(
            (
                "Calling drawing methods on a state is deprecated. To add actions "
                "to the currently active state, call drawing methods on the canvas. "
                "Additionally, the Canvas.fill() method's color parameter can only be "
                "provided via keyword. fill_rule is the only argument it accepts "
                "positionally."
            ),
            DeprecationWarning,
            stacklevel=2,
        )
        self._redraw_without_warning()
        return fill

    def stroke(
        self,
        color: ColorT | None | NOT_PROVIDED = NOT_PROVIDED,
        line_width: float | None = None,
        line_dash: list[float] | None = None,
    ) -> AbstractContextManager[Stroke]:
        stroke = Stroke(stroke_style=color, line_width=line_width, line_dash=line_dash)
        self._add_to_target(stroke)
        warnings.warn(
            (
                "Calling drawing methods on a state is deprecated. To add actions "
                "to the currently active state, call drawing methods on the canvas. "
                "Additionally, the Canvas.stroke() method's arguments can only be "
                "provided as keywords. It does not accept any positional arguments."
            ),
            DeprecationWarning,
            stacklevel=2,
        )
        self._redraw_without_warning()
        return stroke

    ###########################################################################
    # 2026-02: Backwards compatibility for Toga <= 0.5.3
    ###########################################################################

    def __len__(self) -> int:
        self._warn_list_methods()
        return len(self.drawing_actions)

    def __getitem__(self, index: int) -> DrawingAction:
        self._warn_list_methods()
        return self.drawing_actions[index]

    def append(self, obj: DrawingAction) -> None:
        self._warn_list_methods()
        self.drawing_actions.append(obj)
        self._redraw_without_warning()

    def insert(self, index: int, obj: DrawingAction) -> None:
        self._warn_list_methods()
        self.drawing_actions.insert(index, obj)
        self._redraw_without_warning()

    def remove(self, obj: DrawingAction) -> None:
        self._warn_list_methods()
        self.drawing_actions.remove(obj)
        self._redraw_without_warning()

    def clear(self) -> None:
        self._warn_list_methods()
        self.drawing_actions.clear()
        self._redraw_without_warning()

    @property
    def canvas(self) -> Canvas:
        warnings.warn(
            "States no longer hold a reference to their canvas.",
            DeprecationWarning,
            stacklevel=2,
        )

        from .canvas import Canvas

        # Get the first that matches.
        for canvas in Canvas._instances:
            if self is canvas.root_state or self in canvas.root_state:
                return canvas

        return None

    def redraw(self) -> None:
        warnings.warn(
            (
                f"{type(self).__name__}.redraw() is deprecated. Call the canvas's "
                "redraw() method instead."
            ),
            DeprecationWarning,
            stacklevel=2,
        )

        from .canvas import Canvas

        # Redraw any canvases that contain self; could be multiple.
        for canvas in Canvas._instances:
            if self is canvas.root_state or self in canvas.root_state:
                canvas.redraw()

    def _warn_list_methods(self) -> None:
        warnings.warn(
            (
                "A state's list-like methods (append, insert, remove, and clear), as "
                "well as implementing len() and indexing, are deprecated. Manipulate "
                "its drawing_actions directly, and then call redraw() on the canvas."
            ),
            DeprecationWarning,
            stacklevel=3,
        )

drawing_actions = [] instance-attribute

The list of all drawing actions contained by this state.

If you add or remove drawing actions to this list, you'll need to call Canvas.redraw() for the changes to be rendered.

Bases: DrawingAction

The DrawingAction representing assigning to the fill_style context attribute.

Source code in core/src/toga/widgets/canvas/drawingaction.py
147
148
149
150
151
152
153
154
155
156
@dataclass(repr=False)
class SetFillStyle(DrawingAction):
    """The [`DrawingAction`][toga.widgets.canvas.DrawingAction] representing assigning
    to the [fill_style][toga.Canvas.fill_style] context attribute.
    """

    fill_style: ColorT = color_property()

    def _draw(self, context: Any) -> None:
        context.set_fill_style(self.fill_style)

Bases: DrawingAction

The DrawingAction representing assigning to the stroke_style context attribute.

Source code in core/src/toga/widgets/canvas/drawingaction.py
159
160
161
162
163
164
165
166
167
168
@dataclass(repr=False)
class SetStrokeStyle(DrawingAction):
    """The [`DrawingAction`][toga.widgets.canvas.DrawingAction] representing assigning
    to the [stroke_style][toga.Canvas.stroke_style] context attribute.
    """

    stroke_style: ColorT = color_property()

    def _draw(self, context: Any) -> None:
        context.set_stroke_style(self.stroke_style)

Bases: DrawingAction

The DrawingAction representing assigning to the line_width context attribute.

Source code in core/src/toga/widgets/canvas/drawingaction.py
183
184
185
186
187
188
189
190
191
192
@dataclass(repr=False)
class SetLineWidth(DrawingAction):
    """The [`DrawingAction`][toga.widgets.canvas.DrawingAction] representing assigning
    to the [line_width][toga.Canvas.line_width] context attribute.
    """

    line_width: float

    def _draw(self, context: Any) -> None:
        context.set_line_width(self.line_width)

Bases: DrawingAction

The DrawingAction representing assigning to the line_dash context attribute.

Source code in core/src/toga/widgets/canvas/drawingaction.py
171
172
173
174
175
176
177
178
179
180
@dataclass(repr=False)
class SetLineDash(DrawingAction):
    """The [`DrawingAction`][toga.widgets.canvas.DrawingAction] representing assigning
    to the [line_dash][toga.Canvas.line_dash] context attribute.
    """

    line_dash: list[float]

    def _draw(self, context: Any) -> None:
        context.set_line_dash(self.line_dash)

Bases: DrawingAction

The DrawingAction representing the save() method.

Source code in core/src/toga/widgets/canvas/drawingaction.py
124
125
126
127
128
129
130
class Save(DrawingAction):
    """The [`DrawingAction`][toga.widgets.canvas.DrawingAction] representing the
    [save()][toga.Canvas.save] method.
    """

    def _draw(self, context: Any) -> None:
        context.save()

Bases: DrawingAction

The DrawingAction representing the restore() method.

Source code in core/src/toga/widgets/canvas/drawingaction.py
133
134
135
136
137
138
139
class Restore(DrawingAction):
    """The [`DrawingAction`][toga.widgets.canvas.DrawingAction] representing the
    [restore()][toga.Canvas.restore] method.
    """

    def _draw(self, context: Any) -> None:
        context.restore()

Bases: BaseState

The DrawingAction representing the stateh() method. Functions as a context manager.

Source code in core/src/toga/widgets/canvas/state.py
866
867
868
869
870
871
872
873
874
875
876
877
878
879
@dataclass(repr=False)
class State(BaseState):
    """The [DrawingAction][toga.widgets.canvas.DrawingAction] representing the
    [stateh()][toga.Canvas.state] method. Functions as a context manager.
    """

    def __post_init__(self):
        super().__init__()

    def _draw(self, context: Any) -> None:
        context.save()
        for action in self.drawing_actions:
            action._draw(context)
        context.restore()

Bases: DrawingAction

The DrawingAction representing the begin_path() method.

Source code in core/src/toga/widgets/canvas/drawingaction.py
200
201
202
203
204
205
206
class BeginPath(DrawingAction):
    """The [`DrawingAction`][toga.widgets.canvas.DrawingAction] representing the
    [begin_path()][toga.Canvas.begin_path] method.
    """

    def _draw(self, context: Any) -> None:
        context.begin_path()

Bases: BaseState

The DrawingAction representing the close_path() method. Can function as a context manager.

Source code in core/src/toga/widgets/canvas/state.py
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
@dataclass(repr=False)
class ClosePath(BaseState):
    """The [DrawingAction][toga.widgets.canvas.DrawingAction] representing the
    [close_path()][toga.Canvas.close_path] method. Can function as a context manager.
    """

    def __post_init__(self):
        super().__init__()

    # Backwards compatibility for Toga <= 0.5.4
    # See DrawingActionDispatch.ClosedPath for explanation
    def __enter__(self):
        super().__enter__()

        if hasattr(self, "x") and hasattr(self, "y"):
            self.drawing_actions.append(MoveTo(self.x, self.y))

        return self

    # End backwards compatibility

    def _draw(self, context: Any) -> None:
        if not (hasattr(self, "_is_open") or self.drawing_actions):
            # Wasn't used as a context manager, nor had drawing actions manually added

            # 4-2026: Backwards compatibility for Toga <= 0.5.4
            # See DrawingActionDispatch.ClosedPath for explanation
            if hasattr(self, "x") and hasattr(self, "y"):
                context.move_to(self.x, self.y)
            # End backwards compatibility

            context.close_path()
            return

        context.save()
        context.begin_path()

        for action in self.drawing_actions:
            action._draw(context)

        context.close_path()
        context.restore()

Bases: DrawingAction

The DrawingAction representing the move_to() method.

Source code in core/src/toga/widgets/canvas/drawingaction.py
209
210
211
212
213
214
215
216
217
218
219
@dataclass(repr=False)
class MoveTo(DrawingAction):
    """The [`DrawingAction`][toga.widgets.canvas.DrawingAction] representing the
    [move_to()][toga.Canvas.move_to] method.
    """

    x: float
    y: float

    def _draw(self, context: Any) -> None:
        context.move_to(self.x, self.y)

Bases: DrawingAction

The DrawingAction representing the line_to() method.

Source code in core/src/toga/widgets/canvas/drawingaction.py
222
223
224
225
226
227
228
229
230
231
232
@dataclass(repr=False)
class LineTo(DrawingAction):
    """The [`DrawingAction`][toga.widgets.canvas.DrawingAction] representing the
    [line_to()][toga.Canvas.line_to] method.
    """

    x: float
    y: float

    def _draw(self, context: Any) -> None:
        context.line_to(self.x, self.y)

Bases: DrawingAction

The DrawingAction representing the bezier_curve_to() method.

Source code in core/src/toga/widgets/canvas/drawingaction.py
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
@dataclass(repr=False)
class BezierCurveTo(DrawingAction):
    """The [`DrawingAction`][toga.widgets.canvas.DrawingAction] representing the
    [bezier_curve_to()][toga.Canvas.bezier_curve_to] method.
    """

    cp1x: float
    cp1y: float
    cp2x: float
    cp2y: float
    x: float
    y: float

    def _draw(self, context: Any) -> None:
        context.bezier_curve_to(
            self.cp1x, self.cp1y, self.cp2x, self.cp2y, self.x, self.y
        )

Bases: DrawingAction

The DrawingAction representing the quadratic_curve_to() method.

Source code in core/src/toga/widgets/canvas/drawingaction.py
254
255
256
257
258
259
260
261
262
263
264
265
266
@dataclass(repr=False)
class QuadraticCurveTo(DrawingAction):
    """The [`DrawingAction`][toga.widgets.canvas.DrawingAction] representing the
    [quadratic_curve_to()][toga.Canvas.quadratic_curve_to] method.
    """

    cpx: float
    cpy: float
    x: float
    y: float

    def _draw(self, context: Any) -> None:
        context.quadratic_curve_to(self.cpx, self.cpy, self.x, self.y)

Bases: DrawingAction

The DrawingAction representing the arc() method.

Source code in core/src/toga/widgets/canvas/drawingaction.py
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
@dataclass(repr=False)
class Arc(DrawingAction):
    """The [`DrawingAction`][toga.widgets.canvas.DrawingAction] representing the
    [arc()][toga.Canvas.arc] method.
    """

    x: float
    y: float
    radius: float
    startangle: float = 0.0
    endangle: float = 2 * pi
    counterclockwise: bool | None = None
    anticlockwise: InitVar[bool | None] = None  # DEPRECATED

    ######################################################################
    # 03-2025: Backwards compatibility for Toga <= 0.5.1
    ######################################################################

    def __post_init__(self, anticlockwise):
        self.counterclockwise = _determine_counterclockwise(
            anticlockwise, self.counterclockwise
        )

    ######################################################################
    # End backwards compatibility
    ######################################################################

    def _draw(self, context: Any) -> None:
        context.arc(
            self.x,
            self.y,
            self.radius,
            self.startangle,
            self.endangle,
            self.counterclockwise,
        )

Bases: DrawingAction

The DrawingAction representing the ellipse() method.

Source code in core/src/toga/widgets/canvas/drawingaction.py
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
@dataclass(repr=False)
class Ellipse(DrawingAction):
    """The [`DrawingAction`][toga.widgets.canvas.DrawingAction] representing the
    [ellipse()][toga.Canvas.ellipse] method.
    """

    x: float
    y: float
    radiusx: float
    radiusy: float
    rotation: float = 0.0
    startangle: float = 0.0
    endangle: float = 2 * pi
    counterclockwise: bool | None = None
    anticlockwise: InitVar[bool | None] = None  # DEPRECATED

    ######################################################################
    # 03-2025: Backwards compatibility for Toga <= 0.5.1
    ######################################################################

    def __post_init__(self, anticlockwise):
        self.counterclockwise = _determine_counterclockwise(
            anticlockwise,
            self.counterclockwise,
        )

    ######################################################################
    # End backwards compatibility
    ######################################################################

    def _draw(self, context: Any) -> None:
        context.ellipse(
            self.x,
            self.y,
            self.radiusx,
            self.radiusy,
            self.rotation,
            self.startangle,
            self.endangle,
            self.counterclockwise,
        )

Bases: DrawingAction

The DrawingAction representing the rect() method.

Source code in core/src/toga/widgets/canvas/drawingaction.py
350
351
352
353
354
355
356
357
358
359
360
361
362
@dataclass(repr=False)
class Rect(DrawingAction):
    """The [`DrawingAction`][toga.widgets.canvas.DrawingAction] representing the
    [rect()][toga.Canvas.rect] method.
    """

    x: float
    y: float
    width: float
    height: float

    def _draw(self, context: Any) -> None:
        context.rect(self.x, self.y, self.width, self.height)

Bases: BaseState

The DrawingAction representing the fill() method. Can function as a context manager.

Source code in core/src/toga/widgets/canvas/state.py
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
@dataclass(repr=False)
class Fill(BaseState):
    """The [DrawingAction][toga.widgets.canvas.DrawingAction] representing the
    [fill()][toga.Canvas.fill] method. Can function as a context manager.
    """

    # This will need to change to a pair of positional arguments in order to accommodate
    # (path), (fill_rule), or (path, fill_rule) usage as in JavaScript.
    fill_rule: FillRule = FillRule.NONZERO
    _: KW_ONLY
    fill_style: ColorT | None | object = color_property()
    color: InitVar[ColorT | None | object] = color_property()

    def __post_init__(self, color):
        super().__init__()
        self.fill_style = _assign_style(self, "fill", color)

    def _draw(self, context: Any) -> None:
        context.save()
        if self.fill_style is not None:
            context.set_fill_style(self.fill_style)

        if hasattr(self, "_is_open") or self.drawing_actions:
            # Was used as a context manager (or had drawing actions manually added)
            context.in_fill = True  # 4-2026: Backwards compatibility for Toga <= 0.5.3
            context.begin_path()

            for action in self.drawing_actions:
                action._draw(context)

            context.in_fill = False  # 4-2026: Backwards compatibility for Toga <= 0.5.3

        context.fill(self.fill_rule)
        context.restore()

Bases: BaseState

The DrawingAction representing the stroke() method. Can function as a context manager.

Source code in core/src/toga/widgets/canvas/state.py
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
@dataclass(repr=False)
class Stroke(BaseState):
    """The [DrawingAction][toga.widgets.canvas.DrawingAction] representing the
    [stroke()][toga.Canvas.stroke] method. Can function as a context manager.
    """

    # Path parameter (positional/keyword) will go here.
    _: KW_ONLY
    stroke_style: ColorT | None | object = color_property()
    color: InitVar[ColorT | None | object] = color_property()
    line_width: float | None = None
    line_dash: list[float] | None = None

    def __post_init__(self, color):
        super().__init__()
        self.stroke_style = _assign_style(self, "stroke", color)

    def _draw(self, context: Any) -> None:
        context.save()
        if self.stroke_style is not None:
            context.set_stroke_style(self.stroke_style)
        if self.line_width is not None:
            context.set_line_width(self.line_width)
        if self.line_dash is not None:
            context.set_line_dash(self.line_dash)

        if hasattr(self, "_is_open") or self.drawing_actions:
            # Was used as a context manager (or had drawing actions manually added)
            context.in_stroke = True  # Backwards compatibility for Toga <= 0.5.3
            context.begin_path()

            for action in self.drawing_actions:
                action._draw(context)

            context.in_stroke = False  # Backwards compatibility for Toga <= 0.5.3

        context.stroke()
        context.restore()

Bases: DrawingAction

The DrawingAction representing the write_text() method.

Source code in core/src/toga/widgets/canvas/drawingaction.py
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
@dataclass(repr=False)
class WriteText(DrawingAction):
    """The [`DrawingAction`][toga.widgets.canvas.DrawingAction] representing the
    [write_text()][toga.Canvas.write_text] method.
    """

    text: str
    x: float = 0.0
    y: float = 0.0
    font: Font | None = None
    baseline: Baseline = Baseline.ALPHABETIC
    line_height: float | None = None

    def _draw(self, context: Any) -> None:
        context.write_text(
            str(self.text),
            self.x,
            self.y,
            (
                self.font._impl
                if self.font is not None
                else Font(family=SYSTEM, size=SYSTEM_DEFAULT_FONT_SIZE)._impl
            ),
            self.baseline,
            self.line_height,
        )

Bases: DrawingAction

The DrawingAction representing the draw_image() method.

Source code in core/src/toga/widgets/canvas/drawingaction.py
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
@dataclass(repr=False)
class DrawImage(DrawingAction):
    """The [`DrawingAction`][toga.widgets.canvas.DrawingAction] representing the
    [draw_image()][toga.Canvas.draw_image] method.
    """

    image: Image
    x: float = 0.0
    y: float = 0.0
    width: float | None = None
    height: float | None = None

    def _draw(self, context: Any) -> None:
        context.draw_image(
            self.image,
            self.x,
            self.y,
            self.width if self.width is not None else self.image.width,
            self.height if self.height is not None else self.image.height,
        )

Bases: DrawingAction

The DrawingAction representing the rotate() method.

Source code in core/src/toga/widgets/canvas/drawingaction.py
446
447
448
449
450
451
452
453
454
455
@dataclass(repr=False)
class Rotate(DrawingAction):
    """The [`DrawingAction`][toga.widgets.canvas.DrawingAction] representing the
    [rotate()][toga.Canvas.rotate] method.
    """

    radians: float

    def _draw(self, context: Any) -> None:
        context.rotate(self.radians)

Bases: DrawingAction

The DrawingAction representing the scale() method.

Source code in core/src/toga/widgets/canvas/drawingaction.py
458
459
460
461
462
463
464
465
466
467
468
@dataclass(repr=False)
class Scale(DrawingAction):
    """The [`DrawingAction`][toga.widgets.canvas.DrawingAction] representing the
    [scale()][toga.Canvas.scale] method.
    """

    sx: float
    sy: float

    def _draw(self, context: Any) -> None:
        context.scale(self.sx, self.sy)

Bases: DrawingAction

The DrawingAction representing the translate() method.

Source code in core/src/toga/widgets/canvas/drawingaction.py
471
472
473
474
475
476
477
478
479
480
481
@dataclass(repr=False)
class Translate(DrawingAction):
    """The [`DrawingAction`][toga.widgets.canvas.DrawingAction] representing the
    [translate()][toga.Canvas.translate] method.
    """

    tx: float
    ty: float

    def _draw(self, context: Any) -> None:
        context.translate(self.tx, self.ty)

Bases: DrawingAction

The DrawingAction representing the reset_transform() method.

Source code in core/src/toga/widgets/canvas/drawingaction.py
484
485
486
487
488
489
490
class ResetTransform(DrawingAction):
    """The [`DrawingAction`][toga.widgets.canvas.DrawingAction] representing the
    [reset_transform()][toga.Canvas.reset_transform] method.
    """

    def _draw(self, context: Any) -> None:
        context.reset_transform()