Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
40 changes: 26 additions & 14 deletions ClientBuilder.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ async def build(self) -> Dict[str, Any]:
legacy_builder = LegacyKvuiClientBuilder(
self.ctx,
self._init_data.get("ui"),
self._init_data.get("world_ui"),
)
legacy_result = await legacy_builder.build()

Expand Down Expand Up @@ -147,12 +148,16 @@ class LegacyKvuiClientBuilder(ClientBuilder):
from needing to know whether a world uses an explicit build_gui hook or
the old make_gui()/build() compatibility shape. Both run when both are
present: a context inheriting TrackerGameContext gets build_gui from the
tracker while its own make_gui() subclass still owns the game tab.
tracker while its own make_gui() subclass still owns the game tab. A
manager the world's own run_gui made (``world_ui``) is built in place of
its make_gui() class.
"""

def __init__(self, ctx: 'CommonContext', app: Optional['FrontendProtocol'] = None):
def __init__(self, ctx: 'CommonContext', app: Optional['FrontendProtocol'] = None,
world_ui: Any = None):
super().__init__(ctx=ctx)
self.app = app
self.world_ui = world_ui
self.manager = None

async def build(self) -> Dict[str, Any]:
Expand All @@ -173,19 +178,20 @@ async def build(self) -> Dict[str, Any]:
logger.exception("Post-takeover build_gui hook failed")

try:
manager_cls = self._legacy_manager_class(app)
instance = self._world_made_manager(app)
manager_cls = type(instance) if instance is not None else self._legacy_manager_class(app)
if manager_cls is None:
return result

build_legacy_kvui = getattr(app, "build_legacy_kvui", None)
if build_legacy_kvui is not None:
self.manager = build_legacy_kvui(self.ctx, manager_cls)
self.manager = build_legacy_kvui(self.ctx, instance if instance is not None else manager_cls)
else:
build_for_live_app = getattr(manager_cls, "build_for_live_app", None)
if build_for_live_app is not None:
self.manager = build_for_live_app(self.ctx, app)
self.manager = build_for_live_app(self.ctx, app, manager=instance)
else:
self.manager = manager_cls(self.ctx)
self.manager = instance if instance is not None else manager_cls(self.ctx)
self.manager.build()

result["builders"].append("legacy_kvui")
Expand All @@ -209,33 +215,39 @@ def _build_explicit_gui(self, app: 'FrontendProtocol') -> bool:
self.ctx._state = previous_state
return True

def _world_made_manager(self, app: 'FrontendProtocol') -> Any:
world_ui = self.world_ui
if world_ui is None or world_ui is app or not self._is_legacy_manager_class(type(world_ui), app):
return None
return world_ui

def _legacy_manager_class(self, app: 'FrontendProtocol') -> Optional[type]:
try:
manager_cls = self.ctx.make_gui()
except Exception:
logger.exception("Failed to resolve legacy kvui manager")
return None

if not isinstance(manager_cls, type):
if not isinstance(manager_cls, type) or not self._is_legacy_manager_class(manager_cls, app):
return None
return manager_cls

@staticmethod
def _is_legacy_manager_class(manager_cls: type, app: 'FrontendProtocol') -> bool:
frontend_cls = resolve_frontend_class()
if manager_cls is frontend_cls or manager_cls is type(app):
return None
return False

# upstream make_gui()/build() shape: a subclass of the live frontend class
if issubclass(manager_cls, frontend_cls) or hasattr(manager_cls, "build_for_live_app"):
return manager_cls
return True

try:
from kvui import GameManager
except Exception:
return None

if issubclass(manager_cls, GameManager):
return manager_cls
return False

return None
return issubclass(manager_cls, GameManager)

async def cleanup(self) -> None:
self._is_running = False
Expand Down
5 changes: 4 additions & 1 deletion CommonClient.py
Original file line number Diff line number Diff line change
Expand Up @@ -777,14 +777,17 @@ async def _takeover_existing_ui(self) -> None:
try:
self.exit_event = existing_ctx.exit_event

# the manager a world's own run_gui made, about to be replaced by the live app
world_ui = self.ui
if hasattr(existing_ctx, 'ui'):
self.ui = existing_ctx.ui
if hasattr(existing_ctx, 'ui_task'):
self.ui_task = existing_ctx.ui_task

game_client = GameClient(self, {
"ui_task": self.ui_task,
"ui": self.ui
"ui": self.ui,
"world_ui": world_ui,
})

app.ctx = self
Expand Down
16 changes: 13 additions & 3 deletions kvui.py
Original file line number Diff line number Diff line change
Expand Up @@ -267,13 +267,16 @@ def attach_live_app(self, app: App) -> None:
self._running_app = app

@classmethod
def build_for_live_app(cls, ctx, app: App):
def build_for_live_app(cls, ctx, app: App, manager: "GameManager | None" = None):
"""Build a manager against the running frontend the way kivy's App.run
would, build() then on_start(). `manager` is one a world's run_gui made."""
from ClientState import ClientState

previous_state = getattr(ctx, "_state", None)
ctx._state = ClientState.LEGACY_KVUI
try:
manager = cls(ctx)
if manager is None:
manager = cls(ctx)
manager.attach_live_app(app)

root_layout = getattr(app, "root_layout", None) or app.root
Expand All @@ -295,6 +298,10 @@ def build_for_live_app(cls, ctx, app: App):
# Subclasses declare the window title; the live app owns the property.
if manager.base_title:
app.base_title = manager.base_title
try:
manager.on_start()
except Exception:
logging.getLogger("kvui").exception("Legacy client on_start failed")
return manager
finally:
if previous_state is not None:
Expand All @@ -303,6 +310,9 @@ def build_for_live_app(cls, ctx, app: App):
def build_config(self, config) -> None:
"""Target for subclasses' super().build_config(config); super() bypasses __getattr__."""

def on_start(self) -> None:
"""Target for subclasses' super().on_start(); the live app started long before."""

def _load_legacy_config(self) -> None:
"""kivy App.load_config for a world's build_config/get_application_config
overrides. Without one, `config` forwards to the live app's Kivy Config."""
Expand Down Expand Up @@ -340,7 +350,7 @@ async def async_run(self):
''' Changing this 'run' to instead do the client takeover loop '''
if self.ctx._can_takeover_existing_ui():
await self.ctx._takeover_existing_ui()
# Managers built in a world's run_gui never pass build_for_live_app.
# The takeover builds this manager; a failed build still titles the live app.
if self.base_title:
self.ctx.ui.base_title = self.base_title
else:
Expand Down
151 changes: 151 additions & 0 deletions test/general/test_client_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,7 @@ def _gui_game_manager() -> type:
namespace = {
"os": os, "logging": logging, "App": type("App", (), {}),
"KivyJSONtoTextParser": object, "MDNavigationItemBase": object, "Widget": object,
"MDBoxLayout": lambda **kwargs: SimpleNamespace(**kwargs),
}
exec(compile(ast.Module(body=[class_def], type_ignores=[]), "kvui.py", "exec"), namespace)
return namespace["GameManager"]
Expand Down Expand Up @@ -275,6 +276,91 @@ def test_without_override_config_forwards_to_live_app(self) -> None:
self.assertNotIn("config", vars(manager))


# --------------------------------------------------------------------------- #
# The live app's on_start ran before any world manager existed, so
# build_for_live_app runs a manager's own on_start after its build, as kivy's
# App.run would (sc2 resizes the window and adds a log handler there). The
# default never forwards to the live app's on_start.
# --------------------------------------------------------------------------- #

class TestKvuiBuildForLiveApp(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
cls.GameManager = _gui_game_manager()

def setUp(self) -> None:
patcher = mock.patch.dict(sys.modules, {"kivy.config": SimpleNamespace(ConfigParser=_KivyConfigParser)})
patcher.start()
self.addCleanup(patcher.stop)
self.live_started = []
self.app = SimpleNamespace(
root_layout="root", screen_manager="screens", main_layout="grid",
base_title="MultiworldGG", on_start=lambda: self.live_started.append(True),
)
self.ctx = SimpleNamespace(_state="GAME")

def test_on_start_override_runs_once_after_build(self) -> None:
app = self.app
events = []

class Manager(self.GameManager):
base_title = "World Client"

def build(self):
events.append("build")

def on_start(self):
super().on_start()
events.append(("on_start", app._legacy_kvui_manager is self, app.base_title))

Manager.build_for_live_app(self.ctx, app)
self.assertEqual(events, ["build", ("on_start", True, "World Client")])
self.assertEqual(self.live_started, [])

def test_without_override_the_live_on_start_is_not_rerun(self) -> None:
class Manager(self.GameManager):
def build(self):
pass

with self.assertNoLogs("kvui", level="ERROR"):
manager = Manager.build_for_live_app(self.ctx, self.app)
self.assertIs(self.app._legacy_kvui_manager, manager)
self.assertEqual(self.live_started, [])

def test_failing_on_start_is_logged_and_the_build_kept(self) -> None:
class Manager(self.GameManager):
def build(self):
pass

def on_start(self):
raise AttributeError("log_panels")

with self.assertLogs("kvui", level="ERROR"):
manager = Manager.build_for_live_app(self.ctx, self.app)
self.assertIs(self.app._legacy_kvui_manager, manager)
self.assertEqual(self.ctx._state, "GAME")

def test_run_gui_manager_is_built_in_place(self) -> None:
class Manager(self.GameManager):
made = 0
started = 0

def __init__(self, ctx):
super().__init__(ctx)
type(self).made += 1

def build(self):
pass

def on_start(self):
type(self).started += 1

made = Manager(self.ctx)
self.assertIs(Manager.build_for_live_app(self.ctx, self.app, manager=made), made)
self.assertEqual((Manager.made, Manager.started), (1, 1))
self.assertIs(made._running_app, self.app)


# --------------------------------------------------------------------------- #
# Takeover path: LegacyKvuiClientBuilder resolves the per-world UI class from
# ctx.make_gui(). Upstream world clients (e.g. SMS) return a subclass of the
Expand Down Expand Up @@ -401,6 +487,71 @@ def broken(app):
self.assertEqual(result, {"builders": ["legacy_kvui"], "manager": Wrapper})


# --------------------------------------------------------------------------- #
# Worlds that override run_gui (factorio, kh2, sc2, tboir, ...) make their
# manager there and run its async_run, which takes over the live app. The
# takeover replaces ctx.ui with the live app, so it hands the world's manager
# to the builder, which builds that instance instead of the make_gui() class.
# --------------------------------------------------------------------------- #

class TestWorldMadeManager(unittest.TestCase):
def _build(self, world_ui, make_gui_cls=_Frontend):
app = _Frontend()
ctx = _Ctx(make_gui_cls)
builder = ClientBuilder.LegacyKvuiClientBuilder(ctx, app, world_ui)
with _patched_frontend():
result = asyncio.run(builder.build())
return app, result

def test_run_gui_game_manager_is_built(self) -> None:
made = type("Manager", (_GameManager,), {})()
app, result = self._build(made)
self.assertEqual(app.built, [made])
self.assertEqual(result, {"builders": ["legacy_kvui"], "manager": made})

def test_run_gui_frontend_subclass_wins_over_make_gui(self) -> None:
"""tboir's run_gui instantiates its make_gui() subclass, and each make_gui()
call mints a fresh class; only the world's own instance may build."""
def make_gui():
return type("Wrapper", (_Frontend,), {})

made = make_gui()()
app, _ = self._build(made, make_gui())
self.assertEqual(app.built, [made])

def test_world_ui_that_is_not_a_manager_falls_back_to_make_gui(self) -> None:
class Wrapper(_Frontend):
pass

for world_ui in (None, object(), _Frontend()):
with self.subTest(world_ui=world_ui):
app, _ = self._build(world_ui, Wrapper)
self.assertEqual(app.built, [Wrapper])

def test_takeover_hands_the_world_manager_to_the_build(self) -> None:
made = object()
live = SimpleNamespace(ctx=SimpleNamespace(
exit_event="exit", ui="live app", ui_task="live task", _is_transitioning=False))
seen = {}

class FakeGameClient:
def __init__(self, ctx, init_data):
seen.update(init_data)

async def build(self):
pass

ctx = SimpleNamespace(
ui=made, ui_task="world task", _ready_callback=lambda: None,
_error_callback=lambda: None, takeover_complete=asyncio.Event(),
)
with mock.patch("frontend_protocol.resolve_frontend_class", lambda: SimpleNamespace(_active_instance=live)), \
mock.patch.object(ClientBuilder, "GameClient", FakeGameClient):
asyncio.run(CommonClient.CommonContext._takeover_existing_ui(ctx))
self.assertIs(seen["world_ui"], made)
self.assertEqual((seen["ui"], ctx.ui, ctx.ui_task), ("live app", "live app", "live task"))


# --------------------------------------------------------------------------- #
# BizHawk attaches like SNI and the text client: launch() awaits the takeover
# itself and titles the live app afterwards. A make_gui() override or a
Expand Down
Loading