Debian Codegraph @

tksheet/other_classes.py

raw symbols SCIP
1 from __future__ import annotations
2
3 import pickle
4 import tkinter as tk
5 from collections import namedtuple
6 from collections.abc import Callable, Hashable, Iterator
7 from functools import partial
8 from typing import Any, Literal
9
10 pickle_obj = partial(pickle.dumps, protocol=pickle.HIGHEST_PROTOCOL)
11
12 FontTuple = namedtuple("FontTuple", "family size style")
13 Box_nt = namedtuple(
14 "Box_nt",
15 "from_r from_c upto_r upto_c",
16 )
17 Box_t = namedtuple(
18 "Box_t",
19 "from_r from_c upto_r upto_c type_",
20 )
21 Box_st = namedtuple("Box_st", "coords type_")
22 Loc = namedtuple("Loc", "row column", defaults=(None, None))
23
24 Highlight = namedtuple(
25 "Highlight",
26 (
27 "bg",
28 "fg",
29 "end", # only used for row options highlights
30 ),
31 defaults=(
32 None,
33 None,
34 False,
35 ),
36 )
37 DrawnItem = namedtuple("DrawnItem", "iid showing")
38 TextCfg = namedtuple("TextCfg", "txt tf font align")
39 DraggedRowColumn = namedtuple("DraggedRowColumn", "dragged to_move")
40
41
42 class SelectionBox:
43 __slots__ = ("fill_iid", "bd_iid", "index", "header", "coords", "type_", "state")
44
45 def __init__(
46 self,
47 fill_iid: int | None = None,
48 bd_iid: int | None = None,
49 index: int | None = None,
50 header: int | None = None,
51 coords: tuple[int, int, int, int] = None,
52 type_: Literal["cells", "rows", "columns"] = "cells",
53 state: Literal["normal", "hidden"] = "normal",
54 ) -> None:
55 self.fill_iid = fill_iid
56 self.bd_iid = bd_iid
57 self.index = index
58 self.header = header
59 self.coords = coords
60 self.type_ = type_
61 self.state = state
62
63
64 Selected = namedtuple(
65 "Selected",
66 (
67 "row",
68 "column",
69 "type_",
70 "box",
71 "iid",
72 "fill_iid",
73 ),
74 defaults=(
75 None,
76 None,
77 None,
78 None,
79 None,
80 None,
81 ),
82 )
83
84
85 def num2alpha(n: int) -> str | None:
86 try:
87 s = ""
88 n += 1
89 while n > 0:
90 n, r = divmod(n - 1, 26)
91 s = chr(65 + r) + s
92 return s
93 except Exception:
94 return None
95
96
97 class SpanRange:
98 def __init__(self, from_: int, upto_: int) -> None:
99 __slots__ = ("from_", "upto_") # noqa: F841
100 self.from_ = from_
101 self.upto_ = upto_
102
103 def __iter__(self) -> Iterator:
104 return iter(range(self.from_, self.upto_))
105
106 def __reversed__(self) -> Iterator:
107 return reversed(range(self.from_, self.upto_))
108
109 def __contains__(self, n: int) -> bool:
110 return n >= self.from_ and n < self.upto_
111
112 def __eq__(self, v: SpanRange) -> bool:
113 return self.from_ == v.from_ and self.upto_ == v.upto_
114
115 def __ne__(self, v: SpanRange) -> bool:
116 return self.from_ != v.from_ or self.upto_ != v.upto_
117
118 def __len__(self) -> int:
119 return self.upto_ - self.from_
120
121
122 class DotDict(dict):
123 def __init__(self, *args, **kwargs) -> None:
124 super().__init__(*args, **kwargs)
125 # Recursively turn nested dicts into DotDicts
126 for key, value in self.items():
127 if type(value) is dict: # noqa: E721
128 self[key] = DotDict(value)
129
130 def __getstate__(self) -> DotDict:
131 return self
132
133 def __setstate__(self, state: DotDict) -> None:
134 self.update(state)
135
136 def __setitem__(self, key: Hashable, item: Any) -> None:
137 if type(item) is dict: # noqa: E721
138 super().__setitem__(key, DotDict(item))
139 else:
140 super().__setitem__(key, item)
141
142 __setattr__ = __setitem__
143 __getattr__ = dict.__getitem__
144 __delattr__ = dict.__delitem__
145
146
147 class EventDataDict(DotDict):
148 """
149 A subclass of DotDict with no changes
150 For better clarity in type hinting
151 """
152
153
154 class Span(dict):
155 def __init__(self, *args, **kwargs) -> None:
156 super().__init__(*args, **kwargs)
157 # Recursively turn nested dicts into DotDicts
158 for key, item in self.items():
159 if key == "data" or key == "value":
160 self["widget"].set_data(self, data=item)
161 elif type(item) is dict: # noqa: E721
162 self[key] = DotDict(item)
163
164 def __getstate__(self) -> Span:
165 return self
166
167 def __setstate__(self, state: Span) -> None:
168 self.update(state)
169
170 def __getitem__(self, key: Hashable) -> Any:
171 if key == "data" or key == "value":
172 return self["widget"].get_data(self)
173 else:
174 return super().__getitem__(key)
175
176 def __setitem__(self, key: Hashable, item: Any) -> None:
177 if key == "data" or key == "value":
178 self["widget"].set_data(self, data=item)
179 elif key == "bg":
180 self["widget"].highlight(self, bg=item)
181 elif key == "fg":
182 self["widget"].highlight(self, fg=item)
183 elif key == "align":
184 self["widget"].align(self, align=item)
185 elif type(item) is dict: # noqa: E721
186 super().__setitem__(key, DotDict(item))
187 else:
188 super().__setitem__(key, item)
189
190 def format(
191 self,
192 formatter_options: dict | None = None,
193 formatter_class: Any = None,
194 redraw: bool = True,
195 **kwargs,
196 ) -> Span:
197 if formatter_options is None:
198 formatter_options = {}
199 return self["widget"].format(
200 self,
201 formatter_options={"formatter": formatter_class, **formatter_options, **kwargs},
202 formatter_class=formatter_class,
203 redraw=redraw,
204 **kwargs,
205 )
206
207 def del_format(self) -> Span:
208 return self["widget"].del_format(self)
209
210 def highlight(
211 self,
212 bg: bool | None | str = False,
213 fg: bool | None | str = False,
214 end: bool | None = None,
215 overwrite: bool = False,
216 redraw: bool = True,
217 ) -> Span:
218 return self["widget"].highlight(
219 self,
220 bg=bg,
221 fg=fg,
222 end=end,
223 overwrite=overwrite,
224 redraw=redraw,
225 )
226
227 def dehighlight(self, redraw: bool = True) -> Span:
228 return self["widget"].dehighlight(self, redraw=redraw)
229
230 del_highlight = dehighlight
231
232 def readonly(self, readonly: bool = True) -> Span:
233 return self["widget"].readonly(self, readonly=readonly)
234
235 def dropdown(
236 self,
237 values: list[Any] | None = None,
238 edit_data: bool = True,
239 set_values: dict[tuple[int, int], Any] | None = None,
240 set_value: Any = None,
241 state: str = "normal",
242 redraw: bool = True,
243 selection_function: Callable | None = None,
244 modified_function: Callable | None = None,
245 search_function: Callable | None = None,
246 validate_input: bool = True,
247 text: None | str = None,
248 ) -> Span:
249 return self["widget"].dropdown(
250 self,
251 values=[] if values is None else values,
252 edit_data=edit_data,
253 set_values={} if set_values is None else set_values,
254 set_value=set_value,
255 state=state,
256 redraw=redraw,
257 selection_function=selection_function,
258 modified_function=modified_function,
259 search_function=search_function,
260 validate_input=validate_input,
261 text=text,
262 )
263
264 def del_dropdown(self) -> Span:
265 return self["widget"].del_dropdown(self)
266
267 def checkbox(
268 self,
269 edit_data: bool = True,
270 checked: bool | None = None,
271 state: str = "normal",
272 redraw: bool = True,
273 check_function: Callable | None = None,
274 text: str = "",
275 ) -> Span:
276 return self["widget"].checkbox(
277 self,
278 edit_data=edit_data,
279 checked=checked,
280 state=state,
281 redraw=redraw,
282 check_function=check_function,
283 text=text,
284 )
285
286 def del_checkbox(self) -> Span:
287 return self["widget"].del_checkbox(self)
288
289 def align(self, align: str | None, redraw: bool = True) -> Span:
290 return self["widget"].align(self, align=align, redraw=redraw)
291
292 def del_align(self, redraw: bool = True) -> Span:
293 return self["widget"].del_align(self, redraw=redraw)
294
295 def clear(self, undo: bool | None = None, redraw: bool = True) -> Span:
296 if undo is not None:
297 self["widget"].clear(self, undo=undo, redraw=redraw)
298 else:
299 self["widget"].clear(self, redraw=redraw)
300 return self
301
302 def tag(self, *tags) -> Span:
303 self["widget"].tag(self, tags=tags)
304 return self
305
306 def untag(self) -> Span:
307 if self.kind == "cell":
308 for r in self.rows:
309 for c in self.columns:
310 self["widget"].untag(cell=(r, c))
311 elif self.kind == "row":
312 self["widget"].untag(rows=self.rows)
313 elif self.kind == "column":
314 self["widget"].untag(columns=self.columns)
315 return self
316
317 def options(
318 self,
319 type_: str | None = None,
320 name: str | None = None,
321 table: bool | None = None,
322 index: bool | None = None,
323 header: bool | None = None,
324 tdisp: bool | None = None,
325 idisp: bool | None = None,
326 hdisp: bool | None = None,
327 transposed: bool | None = None,
328 ndim: int | None = None,
329 convert: Callable | None = None,
330 undo: bool | None = None,
331 emit_event: bool | None = None,
332 widget: Any = None,
333 expand: str | None = None,
334 formatter_options: dict | None = None,
335 **kwargs,
336 ) -> Span:
337 if isinstance(expand, str) and expand.lower() in ("down", "right", "both", "table"):
338 self.expand(expand)
339
340 if isinstance(convert, Callable):
341 self["convert"] = convert
342
343 if isinstance(type_, str):
344 self["type_"] = type_.lower()
345
346 if isinstance(name, str):
347 if isinstance(name, str) and not name:
348 name = f"{num2alpha(self['widget'].named_span_id)}"
349 self["widget"].named_span_id += 1
350 self["name"] = name
351
352 if isinstance(table, bool):
353 self["table"] = table
354 if isinstance(index, bool):
355 self["index"] = index
356 if isinstance(header, bool):
357 self["header"] = header
358 if isinstance(transposed, bool):
359 self["transposed"] = transposed
360 if isinstance(tdisp, bool):
361 self["tdisp"] = tdisp
362 if isinstance(idisp, bool):
363 self["idisp"] = idisp
364 if isinstance(hdisp, bool):
365 self["hdisp"] = hdisp
366 if isinstance(undo, bool):
367 self["undo"] = undo
368 if isinstance(emit_event, bool):
369 self["emit_event"] = emit_event
370
371 if isinstance(ndim, int) and ndim in (0, 1, 2):
372 self["ndim"] = ndim
373
374 if isinstance(formatter_options, dict):
375 self["type_"] = "format"
376 self["kwargs"] = {"formatter": None, **formatter_options}
377
378 elif kwargs:
379 self["kwargs"] = kwargs
380
381 if widget is not None:
382 self["widget"] = widget
383 return self
384
385 def transpose(self) -> Span:
386 self["transposed"] = not self["transposed"]
387 return self
388
389 def expand(self, direction: Literal["both", "table", "down", "right"] = "both") -> Span:
390 if direction == "both" or direction == "table":
391 self["upto_r"], self["upto_c"] = None, None
392 elif direction == "down":
393 self["upto_r"] = None
394 elif direction == "right":
395 self["upto_c"] = None
396 else:
397 raise ValueError(f"Expand argument must be either 'both', 'table', 'down' or 'right'. Not {direction}")
398 return self
399
400 @property
401 def kind(self) -> str:
402 if self["from_r"] is None:
403 return "column"
404 if self["from_c"] is None:
405 return "row"
406 return "cell"
407
408 @property
409 def rows(self) -> SpanRange:
410 rng_from_r = 0 if self["from_r"] is None else self["from_r"]
411 rng_upto_r = self["widget"].total_rows() if self["upto_r"] is None else self["upto_r"]
412 return SpanRange(rng_from_r, rng_upto_r)
413
414 @property
415 def columns(self) -> SpanRange:
416 rng_from_c = 0 if self["from_c"] is None else self["from_c"]
417 rng_upto_c = self["widget"].total_columns() if self["upto_c"] is None else self["upto_c"]
418 return SpanRange(rng_from_c, rng_upto_c)
419
420 @property
421 def coords(self) -> tuple[int, int, int, int]:
422 rows = self.rows
423 cols = self.columns
424 return Box_nt(rows.from_, cols.from_, rows.upto_, cols.upto_)
425
426 def pickle_self(self) -> bytes:
427 x = self["widget"]
428 self["widget"] = None
429 p = pickle_obj(self)
430 self["widget"] = x
431 return p
432
433 __setattr__ = __setitem__
434 __getattr__ = __getitem__
435 __delattr__ = dict.__delitem__
436
437
438 class GeneratedMouseEvent:
439 def __init__(self):
440 self.keycode = "??"
441 self.num = 1
442
443
444 class Node:
445 __slots__ = ("text", "iid", "parent", "children")
446
447 def __init__(
448 self,
449 text: str,
450 iid: str,
451 parent: str = "",
452 children: list[str] | None = None,
453 ) -> None:
454 self.text = text
455 self.iid = iid
456 self.parent = parent
457 self.children = children if children else []
458
459
460 class StorageBase:
461 __slots__ = ("canvas_id", "window", "open")
462
463 def __init__(self) -> None:
464 self.canvas_id = None
465 self.window = None
466 self.open = False
467
468
469 class DropdownStorage(StorageBase):
470 def get_coords(self) -> int | tuple[int, int] | None:
471 """
472 Returns None if not open or window is None
473 """
474 if self.open and self.window is not None:
475 return self.window.get_coords()
476 return None
477
478
479 class EditorStorageBase(StorageBase):
480 def focus(self) -> None:
481 if self.window:
482 self.window.tktext.focus_set()
483
484 def get(self) -> str:
485 if self.window:
486 return self.window.get()
487 return ""
488
489 def set(self, value: str) -> None:
490 if not self.window:
491 return
492 self.window.set_text(value)
493
494 def highlight_from(self, index: tk.Misc, r: int | str, c: int | str) -> None:
495 self.window.tktext.tag_add("sel", index, "end")
496 self.window.tktext.mark_set("insert", f"{r}.{c}")
497
498 def autocomplete(self, value: str | None) -> None:
499 current_val = self.get()
500 if not value or len(current_val) >= len(value) or current_val != value[: len(current_val)]:
501 return
502 cursor_pos = self.tktext.index("insert")
503 line, column = cursor_pos.split(".")
504 index = self.window.tktext.index(f"{line}.{column}")
505 self.tktext.insert(index, value[len(current_val) :])
506 self.highlight_from(index, line, column)
507
508 @property
509 def tktext(self) -> Any:
510 if self.window:
511 return self.window.tktext
512 return self.window
513
514
515 class TextEditorStorage(EditorStorageBase):
516 @property
517 def coords(self) -> tuple[int, int]:
518 return self.window.r, self.window.c
519
520 @property
521 def row(self) -> int:
522 return self.window.r
523
524 @property
525 def column(self) -> int:
526 return self.window.c
527
528
529 class ProgressBar:
530 __slots__ = ("bg", "fg", "name", "percent", "del_when_done")
531
532 def __init__(self, bg: str, fg: str, name: Hashable, percent: int, del_when_done: bool) -> None:
533 self.bg = bg
534 self.fg = fg
535 self.name = name
536 self.percent = percent
537 self.del_when_done = del_when_done
538
539 def __len__(self):
540 return 2
541
542 def __getitem__(self, key: Hashable) -> Any:
543 if key == 0:
544 return self.bg
545 elif key == 1:
546 return self.fg
547 elif key == 2:
548 return self.name
549 elif key == 3:
550 return self.percent
551 elif key == 4:
552 return self.del_when_done
553 else:
554 return self.__getattribute__(key)