-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwindow_here.py
More file actions
80 lines (61 loc) · 2.52 KB
/
Copy pathwindow_here.py
File metadata and controls
80 lines (61 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
"""Utilities for working with Kivy window."""
import time
from base64 import b64encode
from pathlib import Path
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
def reset_window_environment() -> BoxLayout:
"""Remove PythonHere app widgets and styles."""
# import Window inside function to avoid early loading of the app config
from kivy.core.window import Window # pylint: disable=import-outside-toplevel
for widget in Window.children:
widget.clear_widgets()
Window.remove_widget(widget)
for filename in Builder.files[1:]:
Builder.unload_file(filename)
root = BoxLayout(orientation="vertical")
Window.add_widget(root)
return root
def unload_app_kv_styles():
"""Unload previously applied KV rules."""
for filename in [f for f in Builder.files if (f or "").isdigit()]:
Builder.unload_file(filename)
def load_kv_string(code: str, clear_style: bool):
"""Insert given rules into the Kivy Language Builder."""
from kivy.core.window import Window # pylint: disable=import-outside-toplevel
app = App.get_running_app()
if clear_style:
unload_app_kv_styles()
# digits-only filename to distinguish from other styles
filename = str(time.time()).replace(".", "")
root = Builder.load_string(code, filename=filename)
if root:
for widget in Window.children:
widget.clear_widgets()
Window.remove_widget(widget)
Window.add_widget(root)
app.root = root
app.update_ssh_server_namespace({"root": root})
def save_screenshot(path: str | Path, widget=None) -> str:
"""Save a widget, or the visible window content, as a PNG."""
from kivy.core.window import Window # pylint: disable=import-outside-toplevel
if widget is None:
if not Window.children:
raise RuntimeError("PythonHere has no visible content to capture")
widget = Window.children[0]
destination = Path(path).expanduser().resolve()
if not destination.parent.is_dir():
raise FileNotFoundError(
f"Screenshot directory does not exist: {destination.parent}"
)
widget.export_to_png(str(destination))
return str(destination)
def encoded_screenshot(widget=None) -> str:
"""Return base64 encoded displayed image."""
path = Path(f"screenshot_{time.time()}.png").resolve()
try:
save_screenshot(path, widget=widget)
return b64encode(path.read_bytes()).decode()
finally:
path.unlink(missing_ok=True)