notebook_patch_runners.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. """Patch the immapp and hello_imgui runners for Jupyter notebook.
  2. - Will display a screenshot of the final app state in the notebook output.
  3. - Will use a white theme for the GUI.
  4. - Will make the window autosize by default.
  5. - Will patch hello_imgui.run and immapp.run
  6. """
  7. from typing import Any
  8. def is_in_notebook() -> bool:
  9. try:
  10. import sys
  11. return 'ipykernel' in sys.modules and 'IPython' in sys.modules
  12. except ImportError:
  13. return False
  14. def notebook_do_patch_runners_if_needed() -> None:
  15. if not is_in_notebook():
  16. return
  17. from imgui_bundle import immapp, hello_imgui
  18. from imgui_bundle.immapp.immapp_notebook import _run_app_function_and_display_image_in_notebook
  19. def patch_runner(run_backup: Any) -> Any:
  20. def patched_run(*args: Any, **kwargs: Any) -> None:
  21. # Are we using hello_imgui.RunnerParams, or are we using raw parameters (i.e. a gui_function + other parameters)?
  22. use_gui_function = (len(args) >= 1 and callable(args[0])) or "gui_function" in kwargs
  23. # Set window_size_auto to True if not set, to make the window smaller and reduce the size of the screenshot
  24. if use_gui_function and "window_size" not in kwargs and "window_size_auto" not in kwargs:
  25. kwargs["window_size_auto"] = True
  26. # If using a gui function, patch it so that it uses a white theme
  27. if use_gui_function:
  28. gui_function = args[0] if len(args) >= 1 else kwargs.get("gui_function", None)
  29. if gui_function:
  30. from imgui_bundle.immapp.immapp_notebook import _make_gui_with_light_theme
  31. gui_function_with_light_theme = _make_gui_with_light_theme(gui_function)
  32. if "gui_function" in kwargs:
  33. kwargs["gui_function"] = gui_function_with_light_theme
  34. else:
  35. args = (gui_function_with_light_theme, *args[1:])
  36. if "thumbnail_height" in kwargs:
  37. thumbnail_height = kwargs.pop("thumbnail_height")
  38. else:
  39. thumbnail_height = 0
  40. if "thumbnail_ratio" in kwargs:
  41. thumbnail_ratio = kwargs.pop("thumbnail_ratio")
  42. else:
  43. thumbnail_ratio = 0.0
  44. # define a function that will run the full app, then run this function
  45. # via _run_app_function_and_display_image_in_notebook
  46. def app_function() -> None:
  47. run_backup(*args, **kwargs)
  48. _run_app_function_and_display_image_in_notebook(app_function, thumbnail_height, thumbnail_ratio)
  49. return patched_run
  50. immapp.run_original = immapp.run
  51. immapp.run = patch_runner(immapp.run_original) # noqa
  52. hello_imgui.run_original = hello_imgui.run
  53. hello_imgui.run = patch_runner(hello_imgui.run_original) # noqa