-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathutils.py
More file actions
318 lines (247 loc) · 7.75 KB
/
utils.py
File metadata and controls
318 lines (247 loc) · 7.75 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
"""TkEasyGUI utilities functions."""
import json
import os
import platform
import sys
from enum import Enum
from tkinter import font as tkinter_font
from tkinter import ttk
from typing import Any, Literal, Union
import pyperclip # type: ignore
from PIL import Image as PILImage
from PIL import ImageGrab
from . import version as tkeasygui_version
# Import window management functions from widgets_window
from .widgets_window import (
get_root_window,
set_theme,
)
# define TypeAlias
TextAlign = Literal["left", "right", "center"]
TextVAlign = Literal["top", "bottom", "center"]
FontType = Union[tuple[str, int], tuple[str, int, str]]
PointType = Union[tuple[int, int], tuple[float, float]]
EventMode = Literal["user", "system"]
OrientationType = Literal["v", "h", "vertical", "horizontal"]
ProgressbarMode = Literal["determinate", "indeterminate"]
ListboxSelectMode = Literal["multiple", "browse", "extended", "single"]
PadType = Union[int, tuple[int, int], tuple[tuple[int, int], tuple[int, int]]]
ReliefType = Literal["flat", "groove", "raised", "ridge", "solid", "sunken"]
KeyType = Union[str, int]
ColorFormatType = Literal["html", "rgb", "tuple"]
CursorType = Literal[
"arrow",
"circle",
"cross",
"dotbox",
"exchange",
"fleur",
"hand1",
"hand2",
"heart",
"man",
"mouse",
"pirate",
"plus",
"shuttle",
"sizing",
"spider",
"spraycan",
"star",
"target",
"tcross",
"trek",
"watch",
"xterm",
"ibeam",
"wait",
"size",
"size_all",
"size_nw_se",
"size_ne_sw",
"size_we",
"size_ns",
]
ElementJustifcation = Literal["left", "center", "right", "c", "r"]
PopupGetFormItemType = Union[
str,
tuple[str, Any],
tuple[str, Any, str],
]
FileTypeList = list[tuple[str, str]]
class TkEasyError(Exception):
"""TkEasyError Exception class."""
def __init__(self, message="TkEasyError"):
"""Create a TkEasyError exception."""
self.message = message
super().__init__(self.message)
class ImageResizeType(Enum):
"""Image resize type."""
NO_RESIZE = "no_resize"
FIT_HEIGHT = "fit_height"
FIT_WIDTH = "fit_width"
FIT_BOTH = "fit_both"
IGNORE_ASPECT_RATIO = "ignore_aspect_ratio"
CROP_TO_SQUARE = "crop_to_square"
# -------------------------------------------------------------------
# clipboard
# -------------------------------------------------------------------
def set_clipboard(text):
"""Copy text to clipboard"""
pyperclip.copy(text)
def get_clipboard():
"""Get text from clipboard"""
return pyperclip.paste()
def copy_to_clipboard(text):
"""Copy text to clipboard"""
set_clipboard(text)
def paste_from_clipboard():
"""Get text from clipboard"""
return get_clipboard()
# ------------------------------------------------------------------------------
# platform utility
# ------------------------------------------------------------------------------
def get_platform() -> str:
"""Get platform"""
return platform.system()
def is_mac() -> bool:
"""Platform : is mac?"""
return get_platform() == "Darwin"
def is_win() -> bool:
"""Platform : is Windows?"""
return get_platform() == "Windows"
def screenshot() -> PILImage.Image:
"""Take a screenshot."""
screen_image = ImageGrab.grab()
return screen_image
def get_screen_size() -> tuple[int, int]:
"""Get screen size."""
root = get_root_window()
width = root.winfo_screenwidth()
height = root.winfo_screenheight()
return width, height
def get_screen_dpi() -> int:
"""Get screen DPI."""
root = get_root_window()
dpi = root.winfo_fpixels("1i")
return int(dpi)
def get_scaling() -> float:
"""Get scaling factor."""
root = get_root_window()
scaling = root.tk.call("tk", "scaling")
return float(scaling)
# ------------------------------------------------------------------------------
# text file utility
# ------------------------------------------------------------------------------
def load_text_file(
filename: str, encoding: str = "utf-8", default_value: str = ""
) -> str:
"""Load text file."""
if os.path.exists(filename):
with open(filename, "r", encoding=encoding) as f:
text = f.read()
return text
return default_value
def save_text_file(filename: str, text: str, encoding: str = "utf-8") -> None:
"""Save text file."""
with open(filename, "w", encoding=encoding) as f:
f.write(text)
def append_text_file(filename: str, text: str, encoding: str = "utf-8") -> None:
"""Append text file."""
with open(filename, "a", encoding=encoding) as f:
f.write(text)
def load_json_file(filename: str, default_value: Any = None) -> Any:
"""Load JSON file."""
if os.path.exists(filename) is False:
with open(filename, "r", encoding="utf-8") as f:
data = json.load(f)
return data
return default_value
def save_json_file(filename: str, data: Any) -> None:
"""Save JSON file."""
with open(filename, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=4)
# -------------------------------------------------------------------
# other utilities
# -------------------------------------------------------------------
def str_to_float(value: str, default_value: float = 0) -> float:
"""Convert string to float."""
try:
return float(value)
except ValueError:
return default_value
# ------------------------------------------------------------------------------
# theme
# ------------------------------------------------------------------------------
_tkeasygui_info: dict[str, Any] = {}
def get_themes() -> tuple[str, ...]:
"""
Get theme list
```py
print(get_themes())
```
"""
win = get_root_window()
win.withdraw()
return ttk.Style().theme_names()
def get_tnemes() -> tuple[str, ...]:
"""Alias of get_themes (kept for backward compatibility)."""
return get_themes()
def theme(name: str) -> None:
"""Set theme (alias of set_theme)"""
set_theme(name)
def get_current_theme() -> str:
"""Get current theme"""
return _tkeasygui_info.get("theme", "")
def set_default_theme() -> None:
"""
Set default theme
```py
print(get_themes())
```
"""
if is_mac():
# ('aqua', 'clam', 'alt', 'default', 'classic')
set_theme("aqua")
elif is_win():
# ('winnative', 'clam', 'alt', 'default', 'classic', 'vista', 'xpnative')
set_theme("vista")
else:
set_theme("clam")
def convert_color_rgb16(color_name: str) -> tuple[int, int, int]:
"""Convert color to RGB, return (r, g, b) tuple. range=0-65535"""
root = get_root_window()
return root.winfo_rgb(color_name)
def convert_color_html(color_name: str) -> str:
"""Convert RGB color(16bit tuple) to HTML color name."""
r, g, b = convert_color_rgb16(color_name)
return f"#{r//256:02x}{g//256:02x}{b//256:02x}"
def get_tk_version() -> str:
"""Get tk version"""
root = get_root_window()
tkversion = root.tk.call("info", "patchlevel")
return tkversion
def get_tcl_version() -> str:
"""Get tcl version"""
root = get_root_window()
tclversion = root.tk.call("info", "tclversion")
return tclversion
def get_font_list() -> list[str]:
"""Get font list"""
root = get_root_window()
root.withdraw()
return list(tkinter_font.families())
def get_system_info():
"""Get system info"""
# node={platform.node()}
py_ver = sys.version.replace("\n", "")
return f"""
tkeasygui={tkeasygui_version.__version__}
python={py_ver}
tcl_tk={get_tk_version()}
os={platform.system()}
os_version={platform.version()}
os_release={platform.release()}
architecture={platform.architecture()}
processor={platform.processor()}
""".strip()