Skip to content

Commit 2cace75

Browse files
committed
3.8 support GUI
1 parent 9023afa commit 2cace75

File tree

3 files changed

+44
-33
lines changed

3 files changed

+44
-33
lines changed

src/daf/logging/sql.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -800,7 +800,7 @@ async def _save_log(self,
800800
else:
801801
raise RuntimeError(f"Unable to save log within {SQL_MAX_SAVE_ATTEMPTS} tries")
802802

803-
async def _get_guild(self, id_: int, session: AsyncSession | Session):
803+
async def _get_guild(self, id_: int, session: Union[AsyncSession, Session]):
804804
guilduser: GuildUSER = self.guild_user_cache.get(id_)
805805
if guilduser is not None:
806806
return guilduser

src/daf_gui/convert.py

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import get_type_hints, Iterable, Any, Union
1+
from typing import get_type_hints, Iterable, Any, Union, List
22
from contextlib import suppress
33
from enum import Enum
44

@@ -59,19 +59,27 @@ def UserDataFunction(fnc: str):
5959
},
6060
dt.datetime: {
6161
"year": int,
62-
"month": int | None,
63-
"day": int | None,
62+
"month": Union[int, None],
63+
"day": Union[int, None],
6464
"hour": int,
6565
"minute": int,
6666
"second": int,
6767
"microsecond": int,
68-
"tzinfo": dt.tzinfo | None,
68+
"tzinfo": Union[dt.tzinfo, None],
6969
"fold": int
7070
},
7171
discord.Embed: {
72+
"colour": Union[int, discord.Colour],
73+
"color": Union[int, discord.Colour],
7274
"title": str,
75+
"type": discord.embeds.EmbedType,
7376
"url": str,
74-
"description": str
77+
"description": str,
78+
"timestamp": dt.datetime,
79+
"fields": List[discord.EmbedField]
80+
},
81+
discord.EmbedField: {
82+
"name": str, "value": str, "inline": bool
7583
},
7684
daf.TextMESSAGE: {
7785
"data": Union[Iterable[Union[str, discord.Embed, daf.FILE]], str, discord.Embed, daf.FILE, UserDataFunction]
@@ -131,7 +139,7 @@ def __repr__(self) -> str:
131139
return _ret
132140

133141

134-
def convert_objects_to_script(object: ObjectInfo | list | tuple | set | str):
142+
def convert_objects_to_script(object: Union[ObjectInfo, list, tuple, set, str]):
135143
object_data = []
136144
import_data = []
137145
other_data = []
@@ -145,7 +153,7 @@ def convert_objects_to_script(object: ObjectInfo | list | tuple | set | str):
145153
object_str = f"{object.class_.__name__}(\n "
146154
attr_str = ""
147155
for attr, value in object.data.items():
148-
if isinstance(value, ObjectInfo | list | tuple | set):
156+
if isinstance(value, (ObjectInfo, list, tuple, set)):
149157
value, import_data_, other_str = convert_objects_to_script(value)
150158
import_data.extend(import_data_)
151159
if other_str != "":
@@ -165,7 +173,7 @@ def convert_objects_to_script(object: ObjectInfo | list | tuple | set | str):
165173
object_str += " ".join(attr_str.splitlines(True)) + ")"
166174
object_data.append(object_str)
167175

168-
elif isinstance(object, list | tuple | set):
176+
elif isinstance(object, (list, tuple, set)):
169177
_list_data = "[\n"
170178
for element in object:
171179
object_str, import_data_, other_str = convert_objects_to_script(element)
@@ -267,7 +275,7 @@ def convert_to_json(d: ObjectInfo):
267275
return {"type": f"{d.class_.__module__}.{d.class_.__name__}", "data": data_conv}
268276

269277

270-
def convert_from_json(d: dict | list[dict] | Any) -> ObjectInfo:
278+
def convert_from_json(d: Union[dict, List[dict], Any]) -> ObjectInfo:
271279
if isinstance(d, list):
272280
result = []
273281
for item in d:

src/daf_gui/widgets.py

Lines changed: 26 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
from __future__ import annotations
2-
from typing import get_args, get_origin, get_type_hints, Iterable, Union, Literal, Any
1+
from typing import get_args, get_origin, Iterable, Union, Literal, Any
32
from collections.abc import Iterable as ABCIterable
43
from contextlib import suppress
54
from enum import Enum
@@ -20,7 +19,6 @@
2019

2120

2221
import webbrowser
23-
import types
2422
import datetime as dt
2523
import inspect
2624

@@ -67,7 +65,7 @@ def _callback(*args):
6765
return
6866

6967
rgb, hsl, hex_ = _
70-
color = int(hex_.removeprefix("#"), base=16)
68+
color = int(hex_.lstrip("#"), base=16)
7169
if color not in widget["values"]:
7270
widget.insert(tk.END, color)
7371

@@ -125,7 +123,7 @@ def _callback(*args):
125123

126124
class Text(tk.Text):
127125
def get(self) -> str:
128-
return super().get("1.0", tk.END).removesuffix("\n")
126+
return super().get("1.0", tk.END).strip()
129127

130128

131129
class ComboBoxText(ttk.Frame):
@@ -148,7 +146,7 @@ def get(self, original = True, *args, **kwargs) -> list:
148146

149147
return super().get(*args, **kwargs)
150148

151-
def insert(self, index: str | int, *elements: str | float) -> None:
149+
def insert(self, index: Union[str, int], *elements: Union[str, float]) -> None:
152150
_ret = super().insert(index, *elements)
153151
self._original_items.extend(elements)
154152
return _ret
@@ -216,7 +214,7 @@ def listbox_copy_selected(self):
216214
listbox = self.listbox
217215
selection = self.listbox.curselection()
218216
if len(selection):
219-
object_: ObjectInfo | Any = listbox.get()[selection[0]]
217+
object_: Union[ObjectInfo, Any] = listbox.get()[selection[0]]
220218
listbox.insert(tk.END, object_)
221219
else:
222220
tkdiag.Messagebox.show_error("Select atleast one item!", "Empty list!", parent=self)
@@ -239,7 +237,7 @@ def delete(self, index: int) -> None:
239237
super().delete(index)
240238
self["values"] = self["values"] # Update the text list, NOT a code mistake
241239

242-
def insert(self, index: int | str, element: Any) -> None:
240+
def insert(self, index: Union[int, str], element: Any) -> None:
243241
if index == tk.END:
244242
self._original_items.append(element)
245243
index = len(self._original_items)
@@ -347,7 +345,7 @@ class NewObjectFrame(ttk.Frame):
347345
def __init__(
348346
self,
349347
class_,
350-
return_widget: ComboBoxObjects | ListBoxScrolled,
348+
return_widget: Union[ComboBoxObjects, ListBoxScrolled],
351349
parent = None,
352350
old: ObjectInfo = None,
353351
check_parameters = True,
@@ -381,16 +379,12 @@ def init_main_frame(self, class_) -> bool:
381379
frame_main.pack(expand=True, fill=tk.BOTH)
382380
self.frame_main = frame_main
383381

384-
# Additional annotations defined in daf to support more types
385-
try:
382+
annotations = {}
383+
with suppress(AttributeError):
386384
if inspect.isclass(class_):
387-
annot_object = class_.__init__
385+
annotations = class_.__init__.__annotations__
388386
else:
389-
annot_object = class_
390-
391-
annotations = get_type_hints(annot_object, include_extras=True)
392-
except (NameError, TypeError):
393-
annotations = {}
387+
annotations = class_.__annotations__
394388

395389
additional_annotations = ADDITIONAL_ANNOTATIONS.get(class_)
396390
if additional_annotations is not None:
@@ -402,7 +396,7 @@ def init_main_frame(self, class_) -> bool:
402396
self.init_int_float(class_)
403397
elif get_origin(class_) in {list, Iterable, ABCIterable, tuple}:
404398
self.init_iterable(class_)
405-
elif annotations or additional_annotations is not None:
399+
elif annotations:
406400
self.init_structured(annotations)
407401
else:
408402
tkdiag.Messagebox.show_error("This object cannot be edited.", "Load error", parent=self.origin_window)
@@ -418,7 +412,7 @@ def init_toolbar_frame(self, class_):
418412
help_url = HELP_URLS.get(package)
419413
if help_url is not None:
420414
def cmd():
421-
webbrowser.open(help_url.format(class_.__name__))
415+
webbrowser.open(help_url.format(self.get_cls_name(class_)))
422416

423417
ttk.Button(frame_toolbar, text="Help", command=cmd).pack(side="left")
424418

@@ -470,7 +464,7 @@ def init_structured(self, annotations: dict):
470464

471465
if self.allow_save:
472466
menu.add_radiobutton(
473-
label=f"New {entry_type.__name__}",
467+
label=f"New {self.get_cls_name(entry_type)}",
474468
command=self.new_object_window(entry_type, combo)
475469
)
476470

@@ -496,7 +490,7 @@ def init_iterable(self, class_):
496490
args = get_args(args[0])
497491

498492
for arg in args:
499-
menu.add_radiobutton(label=arg.__name__, command=self.new_object_window(arg, w))
493+
menu.add_radiobutton(label=self.get_cls_name(arg), command=self.new_object_window(arg, w))
500494

501495
self._map[None] = (w, list)
502496

@@ -510,13 +504,22 @@ def init_str(self):
510504
w.pack(fill=tk.BOTH, expand=True)
511505
self._map[None] = (w, str)
512506

507+
@staticmethod
508+
def get_cls_name(cls):
509+
if hasattr(cls, "_name"):
510+
return cls._name
511+
if hasattr(cls, "__name__"):
512+
return cls.__name__
513+
else:
514+
return cls
515+
513516
@classmethod
514517
def set_origin_window(cls, window: ObjectEditWindow):
515518
cls.origin_window = window
516519

517520
@classmethod
518521
def convert_types(cls, types_in):
519-
while get_origin(types_in) in {Union, types.UnionType}:
522+
while get_origin(types_in) is Union:
520523
types_in = get_args(types_in)
521524

522525
if not isinstance(types_in, list):
@@ -534,7 +537,7 @@ def convert_types(cls, types_in):
534537
return types_in + subtypes
535538

536539
def update_window_title(self):
537-
self.origin_window.title(f"{'New' if self.old_object_info is None else 'Edit'} {self.class_.__name__} object")
540+
self.origin_window.title(f"{'New' if self.old_object_info is None else 'Edit'} {self.get_cls_name(self.class_)} object")
538541

539542
def close_frame(self):
540543
if self.allow_save:

0 commit comments

Comments
 (0)