Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Deprecate style.copy(applicator); rework style/applicator setting mechanism #224

Merged
merged 20 commits into from
Nov 4, 2024
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changes/224.misc.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
An applicator, once assigned to a node, now receives a reference to its node (as self.node).
1 change: 1 addition & 0 deletions changes/224.removal.1.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Supplying an applicator to BaseStyle.copy() has been deprecated. If you need to manually assign an applicator to a style, do it separately, after the copy. (In normal usage, though, assigning an applicator to a style is handled automatically when styles and/or applicators are assigned to nodes.)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure the "normal usage" comment here is correct... or at least, it's open to a misleading intepretation. I think the interesting feature here is more that "when a new style is assigned to a node, any existing applicator on the node will be use for the new style" - which is more of a bug fix (see beeware/toga#2305), and independent of "applicator argument to copy deprecated". My inclination is to drop the "normal usage" comment here, and add a separate bug fix entry for being able to assign a new complete style to a node (which will also inherit any previous node applicator)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm, fair enough. I was just thinking in terms of Toga specifically, I think — and a Toga user should probably never encounter this anyway. And thank you for linking that issue! Didn't realize it was already being tracked.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed the parenthetical, added separate bugfix changenote, and edited that issue into the initial comment for the PR.

Copy link
Contributor Author

@HalfWhitt HalfWhitt Nov 4, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, right. Had momentary amnesia about what you said about whether or not to mark this as fixing it. I think it makes sense... Toga only requires Travertino of at least 0.3.0, right? So as soon as this is included in a released version, it's available to current version of Toga. With the caveat that current installations aren't going to be magically auto-updated, of course...

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suppose it boils down to a sort of false positive question. Once Travertino 0.3.1 or 0.4.0 or whatever is released with this patch, it is entirely possible to have an installation of Toga 0.4.8 in which the bug is fixed / feature is added. And any new installation of it presumably will, unless the user specifically pins Travertino 0.3.0 as part of the install.

But it won't be guaranteed to be fixed on existing installations, unless the user updates Travertino, or until they update to the next version of Toga, which can require the newer version of Travertino.

I'm still inclined to think this counts, but as someone without much experience in project management conventions, it's not a hill I'd argue on if you disagree.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree with your analysis - this PR will fix both bugs in Toga... but in a way that causes warnings in Toga. The catch will be how we release this in a way that minimises disruption to users. If existing Toga users are going to get a thousand warnings when they upgrade Travertino, we may need to do a near parallel release to make sure there's a clear way to avoid the warning.

Copy link
Contributor Author

@HalfWhitt HalfWhitt Nov 5, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that sounds like the way to go.

  1. Finish Added composite property (and some nearby cleanups) #222
  2. Finish Updated Pack properties to use new Travertino dataclass-based API toga#2443 (which can include Pack.font) and Restructure widget initialization toga#2937, but don't merge them yet
  3. Release a new version of Travertino
  4. Merge the PRs and release a new version of Toga
  5. ???
  6. Profit!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's definitely one approach; the downside being that it will be difficult to avoid some users getting the warnings from Travertino.

The other possible approach would be something like:

  1. Land Restructure widget initialization toga#2937 in a way that it works with both Travertino releases.
  2. Cut a Toga release
  3. Complete the work on Added composite property (and some nearby cleanups) #222
  4. Cut a Travertino release
  5. Complete the work on Updated Pack properties to use new Travertino dataclass-based API toga#2443
  6. Cut a second Toga release

That all hinges on (1) being possible; but if it is, this approach would give a little breathing room between the Toga release and the Travertino release, so the chances of people getting stuck in the middle zone is lessened. It also gives a little more space for (3) and (5) to be completed - and ironically, the longer they take to implement, the less the impact of the Travertino change will be.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, that makes sense! I had assumed # 1 would be ungainly, but I tried it out just now and what do you know, it's totally doable.

1 change: 1 addition & 0 deletions changes/224.removal.2.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
The mechanisms for assigning styles and applicators to nodes, and applying styles, have been reworked. A node will now attempt to apply its style as soon as it is assigned an applicator; this means you should wait to do so until a node is sufficiently initialized to apply its style. To accomodate uses that currently do not follow this order, any exceptions resulting from a failed style application are caught, and a runtime warning is issued. In a future version, this will be an exception. (Assiging a new style will also trigger a reapply, as long as the applicator is already present.)
HalfWhitt marked this conversation as resolved.
Show resolved Hide resolved
27 changes: 26 additions & 1 deletion src/travertino/declaration.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,22 @@ def _applicator(self):
def _applicator(self, value):
self._assigned_applicator = value

if value is not None:
try:
self.reapply()
# This is backwards compatibility for Toga, which (at least as of
# 0.4.8), assigns style and applicator before the widget's
# implementation is available.
except Exception:
warn(
"Failed to apply style when assigning applicator, or when "
"assigning a new style once applicator is present. Node should be "
"sufficiently initialized to apply its style before it is assigned "
"an applicator. This will be an exception in a future version.",
RuntimeWarning,
stacklevel=2,
)

######################################################################
# Interface that style declarations must define
######################################################################
Expand Down Expand Up @@ -326,8 +342,17 @@ def update(self, **styles):
def copy(self, applicator=None):
"Create a duplicate of this style declaration."
dup = self.__class__()
dup._applicator = applicator
dup.update(**self)

if applicator is not None:
warn(
"Providing an applicator to BaseStyle.copy() is deprecated. Set "
"applicator afterward on the returned copy.",
DeprecationWarning,
stacklevel=2,
)
dup._applicator = applicator

return dup

def __getitem__(self, name):
Expand Down
42 changes: 39 additions & 3 deletions src/travertino/node.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
class Node:
def __init__(self, style, applicator=None, children=None):
# Explicitly set the internal attribute first, since the setter for style will
# access the applicator property.
self._applicator = None

self.style = style
self.applicator = applicator
self.style = style.copy(applicator)
self.intrinsic = self.style.IntrinsicSize()
self.layout = self.style.Box(self)

self._parent = None
self._root = None
Expand All @@ -14,6 +16,40 @@ def __init__(self, style, applicator=None, children=None):
for child in children:
self.add(child)

@property
def style(self):
"""The node's style.

Assigning a style triggers an application of that style if an applicator has
already been assigned.
"""
return self._style

@style.setter
def style(self, style):
self._style = style.copy()
self.intrinsic = self.style.IntrinsicSize()
self.layout = self.style.Box(self)

if self.applicator:
self.style._applicator = self.applicator

@property
def applicator(self):
"""This node's applicator, which handles applying the style.

Assigning an applicator triggers an application of the node's style.
"""
return self._applicator

@applicator.setter
def applicator(self, applicator):
self._applicator = applicator
self.style._applicator = applicator

if applicator:
applicator.node = self

@property
def root(self):
"""The root of the tree containing this node.
Expand Down
28 changes: 2 additions & 26 deletions tests/test_choices.py
Original file line number Diff line number Diff line change
@@ -1,38 +1,14 @@
from __future__ import annotations

import sys
from dataclasses import dataclass
from unittest.mock import Mock
from warnings import catch_warnings, filterwarnings

import pytest

from tests.utils import mock_attr, prep_style_class
from travertino.colors import NAMED_COLOR, rgb
from travertino.constants import GOLDENROD, NONE, REBECCAPURPLE, TOP
from travertino.declaration import BaseStyle, Choices, validated_property

if sys.version_info < (3, 10):
_DATACLASS_KWARGS = {"init": False}
else:
_DATACLASS_KWARGS = {"kw_only": True}


def prep_style_class(cls):
"""Decorator to apply dataclass and mock a style class's apply method."""
return mock_apply(dataclass(**_DATACLASS_KWARGS)(cls))


def mock_apply(cls):
"""Only mock apply, without applying dataclass."""
orig_init = cls.__init__

def __init__(self, *args, **kwargs):
self.apply = Mock()
orig_init(self, *args, **kwargs)

cls.__init__ = __init__
return cls


@prep_style_class
class Style(BaseStyle):
Expand All @@ -56,7 +32,7 @@ class Style(BaseStyle):
with catch_warnings():
filterwarnings("ignore", category=DeprecationWarning)

@mock_apply
@mock_attr("apply")
class DeprecatedStyle(BaseStyle):
pass

Expand Down
19 changes: 17 additions & 2 deletions tests/test_declaration.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

import pytest

from tests.test_choices import mock_apply, prep_style_class
from tests.utils import mock_attr, prep_style_class
from travertino.declaration import (
BaseStyle,
Choices,
Expand Down Expand Up @@ -51,7 +51,7 @@ class Style(BaseStyle):
with catch_warnings():
filterwarnings("ignore", category=DeprecationWarning)

@mock_apply
@mock_attr("apply")
class DeprecatedStyle(BaseStyle):
pass

Expand Down Expand Up @@ -90,6 +90,12 @@ class Sibling(BaseStyle):
pass


@prep_style_class
@mock_attr("reapply")
class MockedReapplyStyle(BaseStyle):
pass


def test_invalid_style():
with pytest.raises(ValueError):
# Define an invalid initial value on a validated property
Expand Down Expand Up @@ -120,6 +126,15 @@ def test_create_and_copy(StyleClass):
assert dup.implicit == VALUE3


def test_deprecated_copy():
style = MockedReapplyStyle()

with pytest.warns(DeprecationWarning):
style_copy = style.copy(applicator=object())

style_copy.reapply.assert_called_once()


@pytest.mark.parametrize("StyleClass", [Style, DeprecatedStyle])
def test_reapply(StyleClass):
style = StyleClass(explicit_const=VALUE2, implicit=VALUE3)
Expand Down
154 changes: 153 additions & 1 deletion tests/test_node.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,36 @@
from unittest.mock import Mock

import pytest

from travertino.declaration import BaseStyle
from tests.utils import mock_attr, prep_style_class
from travertino.declaration import BaseStyle, Choices, validated_property
from travertino.layout import BaseBox, Viewport
from travertino.node import Node
from travertino.size import BaseIntrinsicSize


@prep_style_class
@mock_attr("reapply")
class Style(BaseStyle):
int_prop: int = validated_property(Choices(integer=True))

class IntrinsicSize(BaseIntrinsicSize):
pass

class Box(BaseBox):
pass

def layout(self, root, viewport):
# A simple layout scheme that allocates twice the viewport size.
root.layout.content_width = viewport.width * 2
root.layout.content_height = viewport.height * 2


@prep_style_class
class BrokenStyle(BaseStyle):
def reapply(self):
raise Exception
HalfWhitt marked this conversation as resolved.
Show resolved Hide resolved

class IntrinsicSize(BaseIntrinsicSize):
pass

Expand Down Expand Up @@ -219,3 +243,131 @@ def test_clear():
assert child.root == child

assert node.children == []


def test_create_with_no_applicator():
style = Style(int_prop=5)
node = Node(style=style)

# Style copies on assignment.
assert isinstance(node.style, Style)
assert node.style == style
assert node.style is not style

# Since no applicator has been assigned, style wasn't applied.
node.style.reapply.assert_not_called()


def test_create_with_applicator():
style = Style(int_prop=5)
applicator = Mock()
node = Node(style=style, applicator=applicator)

# Style copies on assignment.
assert isinstance(node.style, Style)
assert node.style == style
assert node.style is not style

# Applicator assignment does *not* copy.
assert node.applicator is applicator
# Applicator gets a reference back to its node and to the style.
assert applicator.node is node
assert node.style._applicator is applicator

# Assigning a non-None applicator should always apply style.
node.style.reapply.assert_called_once()


@pytest.mark.parametrize(
"node",
[
Node(style=Style()),
Node(style=Style(), applicator=Mock()),
],
)
def test_assign_applicator(node):
node.style.reapply.reset_mock()

applicator = Mock()
node.applicator = applicator

# Applicator assignment does *not* copy.
assert node.applicator is applicator
# Applicator gets a reference back to its node and to the style.
assert applicator.node is node
assert node.style._applicator is applicator

# Assigning a non-None applicator should always apply style.
node.style.reapply.assert_called_once()


@pytest.mark.parametrize(
"node",
[
Node(style=Style()),
Node(style=Style(), applicator=Mock()),
],
)
def test_assign_applicator_none(node):
node.style.reapply.reset_mock()

node.applicator = None
assert node.applicator is None

# Should be updated on style as well
assert node.style._applicator is None
# Assigning None to applicator does not trigger reapply.
node.style.reapply.assert_not_called()


def test_assign_style_with_applicator():
style_1 = Style(int_prop=5)
node = Node(style=style_1, applicator=Mock())

node.style.reapply.reset_mock()
style_2 = Style(int_prop=10)
node.style = style_2

# Style copies on assignment.
assert isinstance(node.style, Style)
assert node.style == style_2
assert node.style is not style_2

assert node.style != style_1

# Since an applicator has already been assigned, assigning style applies the style.
node.style.reapply.assert_called_once()


def test_assign_style_with_no_applicator():
style_1 = Style(int_prop=5)
node = Node(style=style_1)

node.style.reapply.reset_mock()
style_2 = Style(int_prop=10)
node.style = style_2

# Style copies on assignment.
assert isinstance(node.style, Style)
assert node.style == style_2
assert node.style is not style_2

assert node.style != style_1

# Since no applicator was present, style should not be applied.
node.style.reapply.assert_not_called()


def test_apply_before_node_is_ready():
style = BrokenStyle()
applicator = Mock()

with pytest.warns(RuntimeWarning):
node = Node(style=style)
node.applicator = applicator

with pytest.warns(RuntimeWarning):
node.style = BrokenStyle()

with pytest.warns(RuntimeWarning):
Node(style=style, applicator=applicator)
29 changes: 29 additions & 0 deletions tests/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import sys
from dataclasses import dataclass
from unittest.mock import Mock

if sys.version_info < (3, 10):
_DATACLASS_KWARGS = {"init": False}
else:
_DATACLASS_KWARGS = {"kw_only": True}


def prep_style_class(cls):
"""Decorator to apply dataclass and mock apply."""
return mock_attr("apply")(dataclass(**_DATACLASS_KWARGS)(cls))


def mock_attr(attr):
"""Mock an arbitrary attribute of a class."""

def returned_decorator(cls):
orig_init = cls.__init__

def __init__(self, *args, **kwargs):
setattr(self, attr, Mock())
orig_init(self, *args, **kwargs)

cls.__init__ = __init__
return cls

return returned_decorator