| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import csv |
| 4 |
import io |
| 5 |
import pickle |
| 6 |
import re |
| 7 |
import tkinter as tk |
| 8 |
from bisect import bisect_left |
| 9 |
from collections import deque |
| 10 |
from collections.abc import Callable, Generator, Hashable, Iterable, Iterator, Sequence |
| 11 |
from difflib import SequenceMatcher |
| 12 |
from itertools import chain, islice, repeat |
| 13 |
from typing import Any, Literal |
| 14 |
|
| 15 |
from .colors import color_map |
| 16 |
from .constants import align_value_error, symbols_set |
| 17 |
from .formatters import to_bool |
| 18 |
from .other_classes import DotDict, EventDataDict, Highlight, Loc, Span |
| 19 |
|
| 20 |
unpickle_obj = pickle.loads |
| 21 |
lines_re = re.compile(r"[^\n]+") |
| 22 |
ORD_A = ord("A") |
| 23 |
|
| 24 |
|
| 25 |
def wrap_text( |
| 26 |
text: str, |
| 27 |
max_width: int, |
| 28 |
max_lines: int, |
| 29 |
char_width_fn: Callable, |
| 30 |
widths: dict[str, int], |
| 31 |
wrap: Literal["", "c", "w"] = "", |
| 32 |
start_line: int = 0, |
| 33 |
) -> Generator[str]: |
| 34 |
total_lines = 0 |
| 35 |
line_width = 0 |
| 36 |
if wrap == "c": |
| 37 |
current_line = [] |
| 38 |
for match in lines_re.finditer(text): |
| 39 |
for char in match.group(): |
| 40 |
try: |
| 41 |
char_width = widths[char] |
| 42 |
except KeyError: |
| 43 |
char_width = char_width_fn(char) |
| 44 |
|
| 45 |
|
| 46 |
if line_width + char_width >= max_width: |
| 47 |
if total_lines >= start_line: |
| 48 |
yield "".join(current_line) |
| 49 |
|
| 50 |
total_lines += 1 |
| 51 |
if total_lines >= max_lines: |
| 52 |
return |
| 53 |
current_line = [] |
| 54 |
line_width = 0 |
| 55 |
|
| 56 |
if char_width <= max_width: |
| 57 |
current_line.append(char) |
| 58 |
line_width = char_width |
| 59 |
|
| 60 |
else: |
| 61 |
current_line.append(char) |
| 62 |
line_width += char_width |
| 63 |
|
| 64 |
if total_lines >= start_line: |
| 65 |
yield "".join(current_line) |
| 66 |
|
| 67 |
total_lines += 1 |
| 68 |
if total_lines >= max_lines: |
| 69 |
return |
| 70 |
current_line = [] |
| 71 |
line_width = 0 |
| 72 |
|
| 73 |
elif wrap == "w": |
| 74 |
try: |
| 75 |
space_width = widths[" "] |
| 76 |
except KeyError: |
| 77 |
space_width = char_width_fn(" ") |
| 78 |
current_line = [] |
| 79 |
|
| 80 |
for match in lines_re.finditer(text): |
| 81 |
for i, word in enumerate(match.group().split()): |
| 82 |
|
| 83 |
|
| 84 |
if i and line_width + space_width < max_width: |
| 85 |
current_line.append(" ") |
| 86 |
line_width += space_width |
| 87 |
|
| 88 |
|
| 89 |
word_width = 0 |
| 90 |
word_char_widths = [] |
| 91 |
for char in word: |
| 92 |
try: |
| 93 |
char_width = widths[char] |
| 94 |
except KeyError: |
| 95 |
char_width = char_width_fn(char) |
| 96 |
word_char_widths.append(char_width) |
| 97 |
word_width += char_width |
| 98 |
|
| 99 |
|
| 100 |
|
| 101 |
if word_width >= max_width: |
| 102 |
|
| 103 |
if current_line: |
| 104 |
if total_lines >= start_line: |
| 105 |
yield "".join(current_line) |
| 106 |
|
| 107 |
total_lines += 1 |
| 108 |
if total_lines >= max_lines: |
| 109 |
return |
| 110 |
current_line = [] |
| 111 |
line_width = 0 |
| 112 |
|
| 113 |
for char, w in zip(word, word_char_widths): |
| 114 |
|
| 115 |
if line_width + w >= max_width: |
| 116 |
if total_lines >= start_line: |
| 117 |
yield "".join(current_line) |
| 118 |
|
| 119 |
total_lines += 1 |
| 120 |
if total_lines >= max_lines: |
| 121 |
return |
| 122 |
current_line = [] |
| 123 |
line_width = 0 |
| 124 |
|
| 125 |
if w <= max_width: |
| 126 |
current_line.append(char) |
| 127 |
line_width = w |
| 128 |
|
| 129 |
else: |
| 130 |
current_line.append(char) |
| 131 |
line_width += w |
| 132 |
|
| 133 |
|
| 134 |
elif line_width + word_width >= max_width: |
| 135 |
if total_lines >= start_line: |
| 136 |
yield "".join(current_line) |
| 137 |
|
| 138 |
total_lines += 1 |
| 139 |
if total_lines >= max_lines: |
| 140 |
return |
| 141 |
current_line = [word] |
| 142 |
line_width = word_width |
| 143 |
|
| 144 |
|
| 145 |
else: |
| 146 |
current_line.append(word) |
| 147 |
line_width += word_width |
| 148 |
|
| 149 |
if total_lines >= start_line: |
| 150 |
yield "".join(current_line) |
| 151 |
|
| 152 |
total_lines += 1 |
| 153 |
if total_lines >= max_lines: |
| 154 |
return |
| 155 |
|
| 156 |
current_line = [] |
| 157 |
line_width = 0 |
| 158 |
|
| 159 |
else: |
| 160 |
for match in lines_re.finditer(text): |
| 161 |
line_width = 0 |
| 162 |
current_line = [] |
| 163 |
for char in match.group(): |
| 164 |
try: |
| 165 |
char_width = widths[char] |
| 166 |
except KeyError: |
| 167 |
char_width = char_width_fn(char) |
| 168 |
line_width += char_width |
| 169 |
if line_width >= max_width: |
| 170 |
break |
| 171 |
current_line.append(char) |
| 172 |
|
| 173 |
if total_lines >= start_line: |
| 174 |
yield "".join(current_line) |
| 175 |
|
| 176 |
|
| 177 |
total_lines += 1 |
| 178 |
if total_lines >= max_lines: |
| 179 |
return |
| 180 |
|
| 181 |
|
| 182 |
def get_csv_str_dialect(s: str, delimiters: str) -> csv.Dialect: |
| 183 |
if len(s) > 6000: |
| 184 |
try: |
| 185 |
_upto = next( |
| 186 |
match.start() + 1 for i, match in enumerate(re.finditer("\n", s), 1) if i == 300 or match.start() > 6000 |
| 187 |
) |
| 188 |
except Exception: |
| 189 |
_upto = len(s) |
| 190 |
else: |
| 191 |
_upto = len(s) |
| 192 |
try: |
| 193 |
return csv.Sniffer().sniff(s[:_upto] if len(s) > 6000 else s, delimiters=delimiters) |
| 194 |
except Exception: |
| 195 |
return csv.excel_tab |
| 196 |
|
| 197 |
|
| 198 |
def get_data_from_clipboard( |
| 199 |
widget: tk.Misc, |
| 200 |
delimiters: str, |
| 201 |
lineterminator: str = "\n", |
| 202 |
) -> list[list[str]]: |
| 203 |
data = widget.clipboard_get() |
| 204 |
dialect = get_csv_str_dialect(data, delimiters=delimiters) |
| 205 |
if dialect.delimiter in data or lineterminator in data: |
| 206 |
return list(csv.reader(io.StringIO(data), dialect=dialect, skipinitialspace=True)) |
| 207 |
return [[data]] |
| 208 |
|
| 209 |
|
| 210 |
def recursive_bind(widget: tk.Misc, event: str, callback: Callable) -> None: |
| 211 |
widget.bind(event, callback) |
| 212 |
for child in widget.winfo_children(): |
| 213 |
recursive_bind(child, event, callback) |
| 214 |
|
| 215 |
|
| 216 |
def recursive_unbind(widget: tk.Misc, event: str) -> None: |
| 217 |
widget.unbind(event) |
| 218 |
for child in widget.winfo_children(): |
| 219 |
recursive_unbind(child, event) |
| 220 |
|
| 221 |
|
| 222 |
def tksheet_type_error(kwarg: str, valid_types: list[str], not_type: Any) -> str: |
| 223 |
valid_types = ", ".join(f"{type_}" for type_ in valid_types) |
| 224 |
return f"Argument '{kwarg}' must be one of the following types: {valid_types}, not {type(not_type)}." |
| 225 |
|
| 226 |
|
| 227 |
def new_tk_event(keysym: str) -> tk.Event: |
| 228 |
event = tk.Event() |
| 229 |
event.keysym = keysym |
| 230 |
return event |
| 231 |
|
| 232 |
|
| 233 |
def event_has_char_key(event: Any) -> bool: |
| 234 |
return ( |
| 235 |
event and hasattr(event, "char") and (event.char.isalpha() or event.char.isdigit() or event.char in symbols_set) |
| 236 |
) |
| 237 |
|
| 238 |
|
| 239 |
def event_opens_dropdown_or_checkbox(event=None) -> bool: |
| 240 |
if event is None: |
| 241 |
return False |
| 242 |
elif event == "rc": |
| 243 |
return True |
| 244 |
return ( |
| 245 |
(hasattr(event, "keysym") and event.keysym in {"Return", "F2", "BackSpace"}) |
| 246 |
or ( |
| 247 |
hasattr(event, "keycode") and event.keycode == "??" and hasattr(event, "num") and event.num == 1 |
| 248 |
) |
| 249 |
) |
| 250 |
|
| 251 |
|
| 252 |
def dropdown_search_function(search_for: str, data: Iterable[Any]) -> None | int: |
| 253 |
search_for = search_for.lower() |
| 254 |
search_len = len(search_for) |
| 255 |
if not search_len: |
| 256 |
return next((i for i, v in enumerate(data) if not str(v)), None) |
| 257 |
|
| 258 |
matcher = SequenceMatcher(None, search_for, "", autojunk=False) |
| 259 |
|
| 260 |
match_rn = None |
| 261 |
match_st = float("inf") |
| 262 |
match_len_diff = float("inf") |
| 263 |
|
| 264 |
fallback_rn = None |
| 265 |
fallback_match_length = 0 |
| 266 |
fallback_st = float("inf") |
| 267 |
|
| 268 |
for rn, value in enumerate(data): |
| 269 |
value = str(value).lower() |
| 270 |
if not value: |
| 271 |
continue |
| 272 |
st = value.find(search_for) |
| 273 |
if st != -1: |
| 274 |
len_diff = len(value) - search_len |
| 275 |
if st < match_st or (st == match_st and len_diff < match_len_diff): |
| 276 |
match_rn = rn |
| 277 |
match_st = st |
| 278 |
match_len_diff = len_diff |
| 279 |
|
| 280 |
elif match_rn is None: |
| 281 |
matcher.set_seq2(value) |
| 282 |
match = matcher.find_longest_match(0, search_len, 0, len(value)) |
| 283 |
match_length = match.size |
| 284 |
start = match.b if match_length > 0 else -1 |
| 285 |
if match_length > fallback_match_length or (match_length == fallback_match_length and start < fallback_st): |
| 286 |
fallback_rn = rn |
| 287 |
fallback_match_length = match_length |
| 288 |
fallback_st = start |
| 289 |
|
| 290 |
return match_rn if match_rn is not None else fallback_rn |
| 291 |
|
| 292 |
|
| 293 |
def float_to_int(f: int | float) -> int | float: |
| 294 |
if f == float("inf"): |
| 295 |
return f |
| 296 |
return int(f) |
| 297 |
|
| 298 |
|
| 299 |
def event_dict( |
| 300 |
name: str = None, |
| 301 |
sheet: Any = None, |
| 302 |
widget: tk.Canvas | None = None, |
| 303 |
boxes: None | dict | tuple = None, |
| 304 |
cells_table: None | dict = None, |
| 305 |
cells_header: None | dict = None, |
| 306 |
cells_index: None | dict = None, |
| 307 |
selected: None | tuple = None, |
| 308 |
data: Any = None, |
| 309 |
key: None | str = None, |
| 310 |
value: Any = None, |
| 311 |
loc: None | int | tuple[int] = None, |
| 312 |
row: None | int = None, |
| 313 |
column: None | int = None, |
| 314 |
resized_rows: None | dict = None, |
| 315 |
resized_columns: None | dict = None, |
| 316 |
|
| 317 |
|
| 318 |
being_selected: None | tuple = None, |
| 319 |
named_spans: None | dict = None, |
| 320 |
sheet_state: None | dict = None, |
| 321 |
treeview: None | dict = None, |
| 322 |
**kwargs, |
| 323 |
) -> EventDataDict: |
| 324 |
return EventDataDict( |
| 325 |
eventname="" if name is None else name, |
| 326 |
sheetname="!sheet" if sheet is None else sheet, |
| 327 |
cells=DotDict( |
| 328 |
table=DotDict() if cells_table is None else cells_table, |
| 329 |
header=DotDict() if cells_header is None else cells_header, |
| 330 |
index=DotDict() if cells_index is None else cells_index, |
| 331 |
), |
| 332 |
moved=DotDict( |
| 333 |
rows=DotDict(), |
| 334 |
columns=DotDict(), |
| 335 |
), |
| 336 |
added=DotDict( |
| 337 |
rows=DotDict(), |
| 338 |
columns=DotDict(), |
| 339 |
), |
| 340 |
deleted=DotDict( |
| 341 |
rows=DotDict(), |
| 342 |
columns=DotDict(), |
| 343 |
header=DotDict(), |
| 344 |
index=DotDict(), |
| 345 |
column_widths=DotDict(), |
| 346 |
row_heights=DotDict(), |
| 347 |
), |
| 348 |
named_spans=DotDict() if named_spans is None else named_spans, |
| 349 |
options=DotDict(), |
| 350 |
selection_boxes={} if boxes is None else boxes, |
| 351 |
selected=() if selected is None else selected, |
| 352 |
being_selected=() if being_selected is None else being_selected, |
| 353 |
data={} if data is None else data, |
| 354 |
key="" if key is None else key, |
| 355 |
value=None if value is None else value, |
| 356 |
loc=() if loc is None else loc, |
| 357 |
row=row, |
| 358 |
column=column, |
| 359 |
resized=DotDict( |
| 360 |
rows=DotDict() if resized_rows is None else resized_rows, |
| 361 |
columns=DotDict() if resized_columns is None else resized_columns, |
| 362 |
|
| 363 |
|
| 364 |
), |
| 365 |
widget=widget, |
| 366 |
sheet_state=DotDict() if sheet_state is None else sheet_state, |
| 367 |
treeview=DotDict( |
| 368 |
nodes={}, |
| 369 |
renamed={}, |
| 370 |
text={}, |
| 371 |
) |
| 372 |
if treeview is None |
| 373 |
else treeview, |
| 374 |
) |
| 375 |
|
| 376 |
|
| 377 |
def change_eventname(event_dict: EventDataDict, newname: str) -> EventDataDict: |
| 378 |
return EventDataDict({**event_dict, **{"eventname": newname}}) |
| 379 |
|
| 380 |
|
| 381 |
def stored_event_dict(d: DotDict) -> DotDict: |
| 382 |
return DotDict(name=d["eventname"], data=DotDict(kv for kv in d.items() if kv[0] != "widget")) |
| 383 |
|
| 384 |
|
| 385 |
def len_to_idx(n: int) -> int: |
| 386 |
if n < 1: |
| 387 |
return 0 |
| 388 |
else: |
| 389 |
return n - 1 |
| 390 |
|
| 391 |
|
| 392 |
def b_index(sorted_seq: Sequence[int], num_to_index: int) -> int: |
| 393 |
""" |
| 394 |
Designed to be a faster way of finding the index of an int |
| 395 |
in a sorted list of ints than list.index() |
| 396 |
""" |
| 397 |
if (idx := bisect_left(sorted_seq, num_to_index)) == len(sorted_seq) or sorted_seq[idx] != num_to_index: |
| 398 |
raise ValueError(f"{num_to_index} is not in Sequence") |
| 399 |
else: |
| 400 |
return idx |
| 401 |
|
| 402 |
|
| 403 |
def try_b_index(sorted_seq: Sequence[int], num_to_index: int) -> int | None: |
| 404 |
if (idx := bisect_left(sorted_seq, num_to_index)) == len(sorted_seq) or sorted_seq[idx] != num_to_index: |
| 405 |
return None |
| 406 |
else: |
| 407 |
return idx |
| 408 |
|
| 409 |
|
| 410 |
def bisect_in(sorted_seq: Sequence[int], num: int) -> bool: |
| 411 |
""" |
| 412 |
Faster than 'num in sorted_seq' |
| 413 |
""" |
| 414 |
try: |
| 415 |
return sorted_seq[bisect_left(sorted_seq, num)] == num |
| 416 |
except Exception: |
| 417 |
return False |
| 418 |
|
| 419 |
|
| 420 |
def push_n(num: int, sorted_seq: Sequence[int]) -> int: |
| 421 |
if num < sorted_seq[0]: |
| 422 |
return num |
| 423 |
else: |
| 424 |
hi = len(sorted_seq) |
| 425 |
lo = 0 |
| 426 |
while lo < hi: |
| 427 |
mid = (lo + hi) // 2 |
| 428 |
if sorted_seq[mid] < num + mid + 1: |
| 429 |
lo = mid + 1 |
| 430 |
else: |
| 431 |
hi = mid |
| 432 |
return num + lo |
| 433 |
|
| 434 |
|
| 435 |
def get_menu_kwargs(ops: DotDict[str, Any]) -> DotDict[str, Any]: |
| 436 |
return DotDict( |
| 437 |
{ |
| 438 |
"font": ops.table_font, |
| 439 |
"foreground": ops.popup_menu_fg, |
| 440 |
"background": ops.popup_menu_bg, |
| 441 |
"activebackground": ops.popup_menu_highlight_bg, |
| 442 |
"activeforeground": ops.popup_menu_highlight_fg, |
| 443 |
} |
| 444 |
) |
| 445 |
|
| 446 |
|
| 447 |
def get_bg_fg(ops: DotDict[str, Any]) -> dict[str, str]: |
| 448 |
return { |
| 449 |
"bg": ops.table_editor_bg, |
| 450 |
"fg": ops.table_editor_fg, |
| 451 |
"select_bg": ops.table_editor_select_bg, |
| 452 |
"select_fg": ops.table_editor_select_fg, |
| 453 |
} |
| 454 |
|
| 455 |
|
| 456 |
def get_dropdown_kwargs( |
| 457 |
values: list[Any] | None = None, |
| 458 |
set_value: Any = None, |
| 459 |
state: str = "normal", |
| 460 |
redraw: bool = True, |
| 461 |
selection_function: Callable | None = None, |
| 462 |
modified_function: Callable | None = None, |
| 463 |
search_function: Callable = dropdown_search_function, |
| 464 |
validate_input: bool = True, |
| 465 |
text: None | str = None, |
| 466 |
) -> dict: |
| 467 |
return { |
| 468 |
"values": [] if values is None else values, |
| 469 |
"set_value": set_value, |
| 470 |
"state": state, |
| 471 |
"redraw": redraw, |
| 472 |
"selection_function": selection_function, |
| 473 |
"modified_function": modified_function, |
| 474 |
"search_function": search_function, |
| 475 |
"validate_input": validate_input, |
| 476 |
"text": text, |
| 477 |
} |
| 478 |
|
| 479 |
|
| 480 |
def get_dropdown_dict(**kwargs) -> dict: |
| 481 |
return { |
| 482 |
"values": kwargs["values"], |
| 483 |
"select_function": kwargs["selection_function"], |
| 484 |
"modified_function": kwargs["modified_function"], |
| 485 |
"search_function": kwargs["search_function"], |
| 486 |
"validate_input": kwargs["validate_input"], |
| 487 |
"text": kwargs["text"], |
| 488 |
"state": kwargs["state"], |
| 489 |
} |
| 490 |
|
| 491 |
|
| 492 |
def get_checkbox_kwargs( |
| 493 |
checked: bool = False, |
| 494 |
state: str = "normal", |
| 495 |
redraw: bool = True, |
| 496 |
check_function: Callable | None = None, |
| 497 |
text: str = "", |
| 498 |
) -> dict: |
| 499 |
return { |
| 500 |
"checked": checked, |
| 501 |
"state": state, |
| 502 |
"redraw": redraw, |
| 503 |
"check_function": check_function, |
| 504 |
"text": text, |
| 505 |
} |
| 506 |
|
| 507 |
|
| 508 |
def get_checkbox_dict(**kwargs) -> dict: |
| 509 |
return { |
| 510 |
"check_function": kwargs["check_function"], |
| 511 |
"state": kwargs["state"], |
| 512 |
"text": kwargs["text"], |
| 513 |
} |
| 514 |
|
| 515 |
|
| 516 |
def is_iterable(o: Any) -> bool: |
| 517 |
if isinstance(o, str): |
| 518 |
return False |
| 519 |
try: |
| 520 |
iter(o) |
| 521 |
return True |
| 522 |
except Exception: |
| 523 |
return False |
| 524 |
|
| 525 |
|
| 526 |
def int_x_iter(i: Iterator[int] | int) -> Iterator[int]: |
| 527 |
if isinstance(i, int): |
| 528 |
return (i,) |
| 529 |
return i |
| 530 |
|
| 531 |
|
| 532 |
def int_x_tuple(i: Iterator[int] | int) -> tuple[int]: |
| 533 |
if isinstance(i, int): |
| 534 |
return (i,) |
| 535 |
return tuple(i) |
| 536 |
|
| 537 |
|
| 538 |
def unpack(t: tuple[Any] | tuple[Iterator[Any]]) -> tuple[Any]: |
| 539 |
if not len(t): |
| 540 |
return t |
| 541 |
if is_iterable(t[0]) and len(t) == 1: |
| 542 |
return t[0] |
| 543 |
return t |
| 544 |
|
| 545 |
|
| 546 |
def is_type_int(o: Any) -> bool: |
| 547 |
return isinstance(o, int) and not isinstance(o, bool) |
| 548 |
|
| 549 |
|
| 550 |
def force_bool(o: Any) -> bool: |
| 551 |
try: |
| 552 |
return to_bool(o) |
| 553 |
except Exception: |
| 554 |
return False |
| 555 |
|
| 556 |
|
| 557 |
def alpha2idx(a: str) -> int | None: |
| 558 |
try: |
| 559 |
n = 0 |
| 560 |
for c in a.upper(): |
| 561 |
n = n * 26 + ord(c) - ORD_A + 1 |
| 562 |
return n - 1 |
| 563 |
except Exception: |
| 564 |
return None |
| 565 |
|
| 566 |
|
| 567 |
def alpha2num(a: str) -> int | None: |
| 568 |
n = alpha2idx(a) |
| 569 |
return n if n is None else n + 1 |
| 570 |
|
| 571 |
|
| 572 |
def num2alpha(n: int) -> str | None: |
| 573 |
try: |
| 574 |
s = "" |
| 575 |
n += 1 |
| 576 |
while n > 0: |
| 577 |
n, r = divmod(n - 1, 26) |
| 578 |
s = chr(65 + r) + s |
| 579 |
return s |
| 580 |
except Exception: |
| 581 |
return None |
| 582 |
|
| 583 |
|
| 584 |
def idx_param_to_int(idx: str | int | None) -> int | None: |
| 585 |
if idx is None or isinstance(idx, int): |
| 586 |
return idx |
| 587 |
return alpha2idx(idx) |
| 588 |
|
| 589 |
|
| 590 |
def get_n2a(n: int = 0, _type: Literal["letters", "numbers", "both"] | None = "numbers") -> str: |
| 591 |
if _type == "letters": |
| 592 |
return num2alpha(n) |
| 593 |
elif _type == "numbers": |
| 594 |
return f"{n + 1}" |
| 595 |
elif _type == "both": |
| 596 |
return f"{num2alpha(n)} {n + 1}" |
| 597 |
elif _type is None: |
| 598 |
return "" |
| 599 |
|
| 600 |
|
| 601 |
def get_index_of_gap_in_sorted_integer_seq_forward( |
| 602 |
seq: list[int], |
| 603 |
start: int = 0, |
| 604 |
) -> int | None: |
| 605 |
prevn = seq[start] |
| 606 |
for idx, n in enumerate(islice(seq, start + 1, None), start + 1): |
| 607 |
if n != prevn + 1: |
| 608 |
return idx |
| 609 |
prevn = n |
| 610 |
return None |
| 611 |
|
| 612 |
|
| 613 |
def get_index_of_gap_in_sorted_integer_seq_reverse( |
| 614 |
seq: list[int], |
| 615 |
start: int = 0, |
| 616 |
) -> int | None: |
| 617 |
prevn = seq[start] |
| 618 |
for idx, n in zip(range(start, -1, -1), reversed(seq[:start])): |
| 619 |
if n != prevn - 1: |
| 620 |
return idx |
| 621 |
prevn = n |
| 622 |
return None |
| 623 |
|
| 624 |
|
| 625 |
def get_seq_without_gaps_at_index( |
| 626 |
seq: list[int], |
| 627 |
position: int, |
| 628 |
get_st_end: bool = False, |
| 629 |
) -> tuple[int, int] | list[int]: |
| 630 |
start_idx = bisect_left(seq, position) |
| 631 |
forward_gap = get_index_of_gap_in_sorted_integer_seq_forward(seq, start_idx) |
| 632 |
reverse_gap = get_index_of_gap_in_sorted_integer_seq_reverse(seq, start_idx) |
| 633 |
if forward_gap is not None: |
| 634 |
seq = seq[:forward_gap] |
| 635 |
if reverse_gap is not None: |
| 636 |
seq = seq[reverse_gap:] |
| 637 |
if get_st_end: |
| 638 |
return seq[0], seq[-1] |
| 639 |
return seq |
| 640 |
|
| 641 |
|
| 642 |
def consecutive_chunks(seq: list[int]) -> Generator[list[int]]: |
| 643 |
start = 0 |
| 644 |
for index, value in enumerate(seq, 1): |
| 645 |
try: |
| 646 |
if seq[index] > value + 1: |
| 647 |
yield seq[start : (start := index)] |
| 648 |
except Exception: |
| 649 |
yield seq[start : len(seq)] |
| 650 |
|
| 651 |
|
| 652 |
def consecutive_ranges(seq: Sequence[int]) -> Generator[tuple[int, int]]: |
| 653 |
seq_iter = iter(seq) |
| 654 |
try: |
| 655 |
start = next(seq_iter) |
| 656 |
except StopIteration: |
| 657 |
return |
| 658 |
prev = start |
| 659 |
for curr in seq_iter: |
| 660 |
if curr > prev + 1: |
| 661 |
yield start, prev + 1 |
| 662 |
start = curr |
| 663 |
prev = curr |
| 664 |
yield start, prev + 1 |
| 665 |
|
| 666 |
|
| 667 |
def is_contiguous(iterable: Iterable[int]) -> bool: |
| 668 |
itr = iter(iterable) |
| 669 |
prev = next(itr) |
| 670 |
return all(i == (prev := prev + 1) for i in itr) |
| 671 |
|
| 672 |
|
| 673 |
def box_is_single_cell( |
| 674 |
r1: int, |
| 675 |
c1: int, |
| 676 |
r2: int, |
| 677 |
c2: int, |
| 678 |
) -> bool: |
| 679 |
return r2 - r1 == 1 and c2 - c1 == 1 |
| 680 |
|
| 681 |
|
| 682 |
def color_tup(color: str) -> tuple[int, int, int]: |
| 683 |
res = color if color.startswith("#") else color_map[color] |
| 684 |
return int(res[1:3], 16), int(res[3:5], 16), int(res[5:], 16) |
| 685 |
|
| 686 |
|
| 687 |
def cell_down_within_box( |
| 688 |
r: int, |
| 689 |
c: int, |
| 690 |
r1: int, |
| 691 |
c1: int, |
| 692 |
r2: int, |
| 693 |
c2: int, |
| 694 |
numrows: int, |
| 695 |
numcols: int, |
| 696 |
) -> tuple[int, int]: |
| 697 |
moved = False |
| 698 |
new_r = r |
| 699 |
new_c = c |
| 700 |
if r + 1 == r2: |
| 701 |
new_r = r1 |
| 702 |
elif numrows > 1: |
| 703 |
new_r = r + 1 |
| 704 |
moved = True |
| 705 |
if not moved: |
| 706 |
if c + 1 == c2: |
| 707 |
new_c = c1 |
| 708 |
elif numcols > 1: |
| 709 |
new_c = c + 1 |
| 710 |
return new_r, new_c |
| 711 |
|
| 712 |
|
| 713 |
def cell_right_within_box( |
| 714 |
r: int, |
| 715 |
c: int, |
| 716 |
r1: int, |
| 717 |
c1: int, |
| 718 |
r2: int, |
| 719 |
c2: int, |
| 720 |
numrows: int, |
| 721 |
numcols: int, |
| 722 |
) -> tuple[int, int]: |
| 723 |
moved = False |
| 724 |
new_r = r |
| 725 |
new_c = c |
| 726 |
if c + 1 == c2: |
| 727 |
new_c = c1 |
| 728 |
elif numcols > 1: |
| 729 |
new_c = c + 1 |
| 730 |
moved = True |
| 731 |
if not moved: |
| 732 |
if r + 1 == r2: |
| 733 |
new_r = r1 |
| 734 |
elif numrows > 1: |
| 735 |
new_r = r + 1 |
| 736 |
return new_r, new_c |
| 737 |
|
| 738 |
|
| 739 |
def get_last( |
| 740 |
it: Iterator[Any], |
| 741 |
) -> Any: |
| 742 |
if hasattr(it, "__reversed__"): |
| 743 |
try: |
| 744 |
return next(reversed(it)) |
| 745 |
except Exception: |
| 746 |
return None |
| 747 |
else: |
| 748 |
try: |
| 749 |
return deque(it, maxlen=1)[0] |
| 750 |
except Exception: |
| 751 |
return None |
| 752 |
|
| 753 |
|
| 754 |
def index_exists(seq: Sequence[Any], index: int) -> bool: |
| 755 |
try: |
| 756 |
seq[index] |
| 757 |
return True |
| 758 |
except Exception: |
| 759 |
return False |
| 760 |
|
| 761 |
|
| 762 |
def add_to_displayed(displayed: list[int], to_add: Iterable[int]) -> list[int]: |
| 763 |
|
| 764 |
for i in to_add: |
| 765 |
ins = bisect_left(displayed, i) |
| 766 |
displayed[ins:] = [i] + [e + 1 for e in islice(displayed, ins, None)] |
| 767 |
return displayed |
| 768 |
|
| 769 |
|
| 770 |
def move_elements_by_mapping( |
| 771 |
seq: list[Any], |
| 772 |
new_idxs: dict[int, int], |
| 773 |
old_idxs: dict[int, int] | None = None, |
| 774 |
) -> list[Any]: |
| 775 |
|
| 776 |
|
| 777 |
|
| 778 |
|
| 779 |
if old_idxs is None: |
| 780 |
old_idxs = dict(zip(new_idxs.values(), new_idxs)) |
| 781 |
remaining_values = (e for i, e in enumerate(seq) if i not in new_idxs) |
| 782 |
return [seq[old_idxs[i]] if i in old_idxs else next(remaining_values) for i in range(len(seq))] |
| 783 |
|
| 784 |
|
| 785 |
def move_elements_by_mapping_gen( |
| 786 |
seq: list[Any], |
| 787 |
new_idxs: dict[int, int], |
| 788 |
old_idxs: dict[int, int] | None = None, |
| 789 |
) -> Generator[Any]: |
| 790 |
if old_idxs is None: |
| 791 |
old_idxs = dict(zip(new_idxs.values(), new_idxs)) |
| 792 |
remaining_values = (e for i, e in enumerate(seq) if i not in new_idxs) |
| 793 |
return (seq[old_idxs[i]] if i in old_idxs else next(remaining_values) for i in range(len(seq))) |
| 794 |
|
| 795 |
|
| 796 |
def move_fast(seq: list[Any], new_idxs: dict[int, int], old_idxs: dict[int, int]) -> list[Any]: |
| 797 |
remaining_values = (e for i, e in enumerate(seq) if i not in new_idxs) |
| 798 |
return [seq[old_idxs[i]] if i in old_idxs else next(remaining_values) for i in range(len(seq))] |
| 799 |
|
| 800 |
|
| 801 |
def move_elements_to( |
| 802 |
seq: list[Any], |
| 803 |
move_to: int, |
| 804 |
to_move: list[int], |
| 805 |
) -> list[Any]: |
| 806 |
return move_elements_by_mapping( |
| 807 |
seq, |
| 808 |
*get_new_indexes( |
| 809 |
move_to, |
| 810 |
to_move, |
| 811 |
get_inverse=True, |
| 812 |
), |
| 813 |
) |
| 814 |
|
| 815 |
|
| 816 |
def get_new_indexes( |
| 817 |
move_to: int, |
| 818 |
to_move: Iterable[int], |
| 819 |
get_inverse: bool = False, |
| 820 |
) -> tuple[dict[int, int]] | dict[int, int]: |
| 821 |
""" |
| 822 |
move_to: A positive int, could possibly be the same as an element of to_move |
| 823 |
to_move: An iterable of ints, could be a dict, could be in any order |
| 824 |
returns {old idx: new idx, ...} |
| 825 |
""" |
| 826 |
offset = sum(1 for i in to_move if i < move_to) |
| 827 |
correct_move_to = move_to - offset |
| 828 |
if not get_inverse: |
| 829 |
return {elem: correct_move_to + i for i, elem in enumerate(to_move)} |
| 830 |
else: |
| 831 |
new_idxs = {} |
| 832 |
old_idxs = {} |
| 833 |
for i, elem in enumerate(to_move): |
| 834 |
value = correct_move_to + i |
| 835 |
new_idxs[elem] = value |
| 836 |
old_idxs[value] = elem |
| 837 |
return new_idxs, old_idxs |
| 838 |
|
| 839 |
|
| 840 |
def insert_items( |
| 841 |
seq: list[Any], |
| 842 |
to_insert: dict[int, Any], |
| 843 |
seq_len_func: Callable | None = None, |
| 844 |
) -> list[Any]: |
| 845 |
""" |
| 846 |
seq: list[Any] |
| 847 |
to_insert: keys are ints sorted, representing list indexes to insert items. |
| 848 |
Values are any, e.g. {0: 200, 1: 200} |
| 849 |
""" |
| 850 |
if to_insert: |
| 851 |
if seq_len_func and next(reversed(to_insert)) >= len(seq) + len(to_insert): |
| 852 |
seq_len_func(next(reversed(to_insert)) - len(to_insert)) |
| 853 |
for idx, v in to_insert.items(): |
| 854 |
seq[idx:idx] = [v] |
| 855 |
return seq |
| 856 |
|
| 857 |
|
| 858 |
def del_placeholder_dict_key( |
| 859 |
d: dict[Hashable, Any], |
| 860 |
k: Hashable, |
| 861 |
v: Any, |
| 862 |
p: tuple = (), |
| 863 |
) -> dict[Hashable, Any]: |
| 864 |
if p in d: |
| 865 |
del d[p] |
| 866 |
d[k] = v |
| 867 |
return d |
| 868 |
|
| 869 |
|
| 870 |
def data_to_displayed_idxs( |
| 871 |
to_convert: list[int], |
| 872 |
displayed: list[int], |
| 873 |
) -> list[int]: |
| 874 |
return [i for i, e in enumerate(displayed) if bisect_in(to_convert, e)] |
| 875 |
|
| 876 |
|
| 877 |
def displayed_to_data_idxs( |
| 878 |
to_convert: list[int], |
| 879 |
displayed: list[int], |
| 880 |
) -> list[int]: |
| 881 |
return [displayed[e] for e in to_convert] |
| 882 |
|
| 883 |
|
| 884 |
def rounded_box_coords( |
| 885 |
x1: float, |
| 886 |
y1: float, |
| 887 |
x2: float, |
| 888 |
y2: float, |
| 889 |
radius: int = 5, |
| 890 |
) -> tuple[float]: |
| 891 |
if y2 - y1 < 2 or x2 - x1 < 2: |
| 892 |
return x1, y1, x2, y1, x2, y2, x1, y2 |
| 893 |
return ( |
| 894 |
x1 + radius, |
| 895 |
y1, |
| 896 |
x1 + radius, |
| 897 |
y1, |
| 898 |
x2 - radius, |
| 899 |
y1, |
| 900 |
x2 - radius, |
| 901 |
y1, |
| 902 |
x2, |
| 903 |
y1, |
| 904 |
x2, |
| 905 |
y1 + radius, |
| 906 |
x2, |
| 907 |
y1 + radius, |
| 908 |
x2, |
| 909 |
y2 - radius, |
| 910 |
x2, |
| 911 |
y2 - radius, |
| 912 |
x2, |
| 913 |
y2, |
| 914 |
x2 - radius, |
| 915 |
y2, |
| 916 |
x2 - radius, |
| 917 |
y2, |
| 918 |
x1 + radius, |
| 919 |
y2, |
| 920 |
x1 + radius, |
| 921 |
y2, |
| 922 |
x1, |
| 923 |
y2, |
| 924 |
x1, |
| 925 |
y2 - radius, |
| 926 |
x1, |
| 927 |
y2 - radius, |
| 928 |
x1, |
| 929 |
y1 + radius, |
| 930 |
x1, |
| 931 |
y1 + radius, |
| 932 |
x1, |
| 933 |
y1, |
| 934 |
) |
| 935 |
|
| 936 |
|
| 937 |
def diff_gen(seq: list[float]) -> Generator[int]: |
| 938 |
it = iter(seq) |
| 939 |
a = next(it) |
| 940 |
for b in it: |
| 941 |
yield int(b - a) |
| 942 |
a = b |
| 943 |
|
| 944 |
|
| 945 |
def gen_coords( |
| 946 |
start_row: int, |
| 947 |
start_col: int, |
| 948 |
end_row: int, |
| 949 |
end_col: int, |
| 950 |
reverse: bool = False, |
| 951 |
) -> Generator[tuple[int, int]]: |
| 952 |
if reverse: |
| 953 |
for r in reversed(range(start_row, end_row)): |
| 954 |
for c in reversed(range(start_col, end_col)): |
| 955 |
yield (r, c) |
| 956 |
else: |
| 957 |
for r in range(start_row, end_row): |
| 958 |
for c in range(start_col, end_col): |
| 959 |
yield (r, c) |
| 960 |
|
| 961 |
|
| 962 |
def box_gen_coords( |
| 963 |
from_r: int, |
| 964 |
from_c: int, |
| 965 |
upto_r: int, |
| 966 |
upto_c: int, |
| 967 |
start_r: int, |
| 968 |
start_c: int, |
| 969 |
reverse: bool, |
| 970 |
all_rows_displayed: bool = True, |
| 971 |
all_cols_displayed: bool = True, |
| 972 |
displayed_cols: list[int] | None = None, |
| 973 |
displayed_rows: list[int] | None = None, |
| 974 |
no_wrap: bool = False, |
| 975 |
) -> Generator[tuple[int, int]]: |
| 976 |
|
| 977 |
if displayed_rows is None: |
| 978 |
displayed_rows = [] |
| 979 |
if displayed_cols is None: |
| 980 |
displayed_cols = [] |
| 981 |
|
| 982 |
|
| 983 |
if not all_rows_displayed: |
| 984 |
from_r = displayed_rows[from_r] |
| 985 |
upto_r = displayed_rows[upto_r - 1] + 1 |
| 986 |
start_r = displayed_rows[start_r] |
| 987 |
|
| 988 |
if not all_cols_displayed: |
| 989 |
from_c = displayed_cols[from_c] |
| 990 |
upto_c = displayed_cols[upto_c - 1] + 1 |
| 991 |
start_c = displayed_cols[start_c] |
| 992 |
|
| 993 |
if not reverse: |
| 994 |
|
| 995 |
|
| 996 |
for c in range(start_c, upto_c): |
| 997 |
yield (start_r, c) |
| 998 |
for r in range(start_r + 1, upto_r): |
| 999 |
for c in range(from_c, upto_c): |
| 1000 |
yield (r, c) |
| 1001 |
if not no_wrap: |
| 1002 |
|
| 1003 |
for r in range(from_r, start_r): |
| 1004 |
for c in range(from_c, upto_c): |
| 1005 |
yield (r, c) |
| 1006 |
if start_c > from_c: |
| 1007 |
for c in range(from_c, start_c): |
| 1008 |
yield (start_r, c) |
| 1009 |
else: |
| 1010 |
|
| 1011 |
|
| 1012 |
for c in range(start_c, from_c - 1, -1): |
| 1013 |
yield (start_r, c) |
| 1014 |
for r in range(start_r - 1, from_r - 1, -1): |
| 1015 |
for c in range(upto_c - 1, from_c - 1, -1): |
| 1016 |
yield (r, c) |
| 1017 |
if not no_wrap: |
| 1018 |
|
| 1019 |
for r in range(upto_r - 1, start_r, -1): |
| 1020 |
for c in range(upto_c - 1, from_c - 1, -1): |
| 1021 |
yield (r, c) |
| 1022 |
if start_c < upto_c - 1: |
| 1023 |
for c in range(upto_c - 1, start_c, -1): |
| 1024 |
yield (start_r, c) |
| 1025 |
|
| 1026 |
|
| 1027 |
def next_cell( |
| 1028 |
start_row: int, |
| 1029 |
start_col: int, |
| 1030 |
end_row: int, |
| 1031 |
end_col: int, |
| 1032 |
row: int, |
| 1033 |
col: int, |
| 1034 |
reverse: bool = False, |
| 1035 |
) -> tuple[int, int]: |
| 1036 |
if reverse: |
| 1037 |
col -= 1 |
| 1038 |
if col < start_col: |
| 1039 |
col = end_col - 1 |
| 1040 |
row -= 1 |
| 1041 |
if row < start_row: |
| 1042 |
row = end_row - 1 |
| 1043 |
else: |
| 1044 |
col += 1 |
| 1045 |
if col == end_col: |
| 1046 |
col = start_col |
| 1047 |
row += 1 |
| 1048 |
if row == end_row: |
| 1049 |
row = start_row |
| 1050 |
return row, col |
| 1051 |
|
| 1052 |
|
| 1053 |
def is_last_cell( |
| 1054 |
start_row: int, |
| 1055 |
start_col: int, |
| 1056 |
end_row: int, |
| 1057 |
end_col: int, |
| 1058 |
row: int, |
| 1059 |
col: int, |
| 1060 |
reverse: bool = False, |
| 1061 |
) -> bool: |
| 1062 |
if reverse: |
| 1063 |
return row == start_row and col == start_col |
| 1064 |
return row == end_row - 1 and col == end_col - 1 |
| 1065 |
|
| 1066 |
|
| 1067 |
def zip_fill_2nd_value(x: Iterator[Any], o: Any) -> Generator[Any, Any]: |
| 1068 |
return zip(x, repeat(o)) |
| 1069 |
|
| 1070 |
|
| 1071 |
def str_to_int(s: str) -> int | None: |
| 1072 |
if s.startswith(("-", "+")): |
| 1073 |
if s[1:].isdigit(): |
| 1074 |
return int(s) |
| 1075 |
return None |
| 1076 |
elif not s.startswith(("-", "+")): |
| 1077 |
if s.isdigit(): |
| 1078 |
return int(s) |
| 1079 |
return None |
| 1080 |
|
| 1081 |
|
| 1082 |
def gen_formatted( |
| 1083 |
options: dict, |
| 1084 |
formatter: Any = None, |
| 1085 |
) -> Generator[tuple[int, int]] | Generator[int]: |
| 1086 |
if formatter is None: |
| 1087 |
return (k for k, dct in options.items() if "format" in dct) |
| 1088 |
return (k for k, dct in options.items() if "format" in dct and dct["format"]["formatter"] == formatter) |
| 1089 |
|
| 1090 |
|
| 1091 |
def options_with_key( |
| 1092 |
options: dict, |
| 1093 |
key: str, |
| 1094 |
) -> Generator[tuple[int, int]] | Generator[int]: |
| 1095 |
return (k for k, dct in options.items() if key in dct) |
| 1096 |
|
| 1097 |
|
| 1098 |
def try_binding( |
| 1099 |
binding: None | Callable, |
| 1100 |
event: dict, |
| 1101 |
new_name: None | str = None, |
| 1102 |
) -> bool: |
| 1103 |
if binding: |
| 1104 |
try: |
| 1105 |
if new_name is None: |
| 1106 |
binding(event) |
| 1107 |
else: |
| 1108 |
binding(change_eventname(event, new_name)) |
| 1109 |
except Exception: |
| 1110 |
return False |
| 1111 |
return True |
| 1112 |
|
| 1113 |
|
| 1114 |
def span_dict( |
| 1115 |
from_r: int | None = None, |
| 1116 |
from_c: int | None = None, |
| 1117 |
upto_r: int | None = None, |
| 1118 |
upto_c: int | None = None, |
| 1119 |
type_: str | None = None, |
| 1120 |
name: str | None = None, |
| 1121 |
kwargs: dict | None = None, |
| 1122 |
table: bool = True, |
| 1123 |
header: bool = False, |
| 1124 |
index: bool = False, |
| 1125 |
tdisp: bool = False, |
| 1126 |
idisp: bool = True, |
| 1127 |
hdisp: bool = True, |
| 1128 |
transposed: bool = False, |
| 1129 |
ndim: int | None = None, |
| 1130 |
convert: Callable | None = None, |
| 1131 |
undo: bool = False, |
| 1132 |
emit_event: bool = False, |
| 1133 |
widget: Any = None, |
| 1134 |
) -> Span: |
| 1135 |
d: Span = Span( |
| 1136 |
from_r=from_r, |
| 1137 |
from_c=from_c, |
| 1138 |
upto_r=upto_r, |
| 1139 |
upto_c=upto_c, |
| 1140 |
type_="" if type_ is None else type_, |
| 1141 |
name="" if name is None else name, |
| 1142 |
kwargs={} if kwargs is None else kwargs, |
| 1143 |
table=table, |
| 1144 |
index=index, |
| 1145 |
header=header, |
| 1146 |
tdisp=tdisp, |
| 1147 |
idisp=idisp, |
| 1148 |
hdisp=hdisp, |
| 1149 |
transposed=transposed, |
| 1150 |
ndim=ndim, |
| 1151 |
convert=convert, |
| 1152 |
undo=undo, |
| 1153 |
emit_event=emit_event, |
| 1154 |
widget=widget, |
| 1155 |
) |
| 1156 |
return d |
| 1157 |
|
| 1158 |
|
| 1159 |
def coords_to_span( |
| 1160 |
widget: Any, |
| 1161 |
from_r: int | None = None, |
| 1162 |
from_c: int | None = None, |
| 1163 |
upto_r: int | None = None, |
| 1164 |
upto_c: int | None = None, |
| 1165 |
) -> Span: |
| 1166 |
if not isinstance(from_r, int) and from_r is not None: |
| 1167 |
from_r = None |
| 1168 |
if not isinstance(from_c, int) and from_c is not None: |
| 1169 |
from_c = None |
| 1170 |
if not isinstance(upto_r, int) and upto_r is not None: |
| 1171 |
upto_r = None |
| 1172 |
if not isinstance(upto_c, int) and upto_c is not None: |
| 1173 |
upto_c = None |
| 1174 |
if from_r is None and from_c is None: |
| 1175 |
from_r = 0 |
| 1176 |
return span_dict( |
| 1177 |
from_r=from_r, |
| 1178 |
from_c=from_c, |
| 1179 |
upto_r=upto_r, |
| 1180 |
upto_c=upto_c, |
| 1181 |
widget=widget, |
| 1182 |
) |
| 1183 |
|
| 1184 |
|
| 1185 |
PATTERN_ROW = re.compile(r"^(\d+)$") |
| 1186 |
PATTERN_COL = re.compile(r"^([A-Z]+)$") |
| 1187 |
PATTERN_CELL = re.compile(r"^([A-Z]+)(\d+)$") |
| 1188 |
PATTERN_RANGE = re.compile(r"^([A-Z]+)(\d+):([A-Z]+)(\d+)$") |
| 1189 |
PATTERN_ROW_RANGE = re.compile(r"^(\d+):(\d+)$") |
| 1190 |
PATTERN_ROW_START = re.compile(r"^(\d+):$") |
| 1191 |
PATTERN_ROW_END = re.compile(r"^:(\d+)$") |
| 1192 |
PATTERN_COL_RANGE = re.compile(r"^([A-Z]+):([A-Z]+)$") |
| 1193 |
PATTERN_COL_START = re.compile(r"^([A-Z]+):$") |
| 1194 |
PATTERN_COL_END = re.compile(r"^:([A-Z]+)$") |
| 1195 |
PATTERN_CELL_START = re.compile(r"^([A-Z]+)(\d+):$") |
| 1196 |
PATTERN_CELL_END = re.compile(r"^:([A-Z]+)(\d+)$") |
| 1197 |
PATTERN_CELL_COL = re.compile(r"^([A-Z]+)(\d+):([A-Z]+)$") |
| 1198 |
PATTERN_CELL_ROW = re.compile(r"^([A-Z]+)(\d+):(\d+)$") |
| 1199 |
PATTERN_ALL = re.compile(r"^:$") |
| 1200 |
|
| 1201 |
|
| 1202 |
def span_a2i(a: str) -> int | None: |
| 1203 |
n = 0 |
| 1204 |
for c in a: |
| 1205 |
n = n * 26 + ord(c) - ORD_A + 1 |
| 1206 |
return n - 1 |
| 1207 |
|
| 1208 |
|
| 1209 |
def span_a2n(a: str) -> int | None: |
| 1210 |
n = 0 |
| 1211 |
for c in a: |
| 1212 |
n = n * 26 + ord(c) - ORD_A + 1 |
| 1213 |
return n |
| 1214 |
|
| 1215 |
|
| 1216 |
def key_to_span( |
| 1217 |
key: ( |
| 1218 |
str |
| 1219 |
| int |
| 1220 |
| slice |
| 1221 |
| Sequence[int | None, int | None] |
| 1222 |
| Sequence[int | None, int | None, int | None, int | None] |
| 1223 |
| Sequence[Sequence[int | None, int | None], Sequence[int | None, int | None]] |
| 1224 |
), |
| 1225 |
spans: dict[str, Span], |
| 1226 |
widget: Any = None, |
| 1227 |
) -> Span: |
| 1228 |
""" |
| 1229 |
Convert various input types to a Span object representing a 2D range. |
| 1230 |
|
| 1231 |
Args: |
| 1232 |
key: The input to convert (str, int, slice, sequence, or None). |
| 1233 |
spans: A dictionary of named spans (e.g., {"<name>": Span(...)}). |
| 1234 |
widget: Optional widget context for span creation. |
| 1235 |
|
| 1236 |
Returns: |
| 1237 |
A Span object or an error message string if the key is invalid. |
| 1238 |
""" |
| 1239 |
|
| 1240 |
if isinstance(key, Span): |
| 1241 |
return key |
| 1242 |
|
| 1243 |
|
| 1244 |
elif key is None: |
| 1245 |
return coords_to_span(widget=widget, from_r=None, from_c=None, upto_r=None, upto_c=None) |
| 1246 |
|
| 1247 |
|
| 1248 |
elif not isinstance(key, (str, int, slice, list, tuple)): |
| 1249 |
return f"Key type must be either str, int, list, tuple or slice, not '{type(key).__name__}'." |
| 1250 |
|
| 1251 |
try: |
| 1252 |
|
| 1253 |
if isinstance(key, int): |
| 1254 |
return span_dict( |
| 1255 |
from_r=key, |
| 1256 |
from_c=None, |
| 1257 |
upto_r=key + 1, |
| 1258 |
upto_c=None, |
| 1259 |
widget=widget, |
| 1260 |
) |
| 1261 |
|
| 1262 |
|
| 1263 |
elif isinstance(key, slice): |
| 1264 |
start = 0 if key.start is None else key.start |
| 1265 |
return span_dict( |
| 1266 |
from_r=start, |
| 1267 |
from_c=None, |
| 1268 |
upto_r=key.stop, |
| 1269 |
upto_c=None, |
| 1270 |
widget=widget, |
| 1271 |
) |
| 1272 |
|
| 1273 |
|
| 1274 |
elif isinstance(key, (list, tuple)): |
| 1275 |
if ( |
| 1276 |
len(key) == 2 |
| 1277 |
and (isinstance(key[0], int) or key[0] is None) |
| 1278 |
and (isinstance(key[1], int) or key[1] is None) |
| 1279 |
): |
| 1280 |
|
| 1281 |
r_int = isinstance(key[0], int) |
| 1282 |
c_int = isinstance(key[1], int) |
| 1283 |
return span_dict( |
| 1284 |
from_r=key[0] if r_int else 0, |
| 1285 |
from_c=key[1] if c_int else 0, |
| 1286 |
upto_r=key[0] + 1 if r_int else None, |
| 1287 |
upto_c=key[1] + 1 if c_int else None, |
| 1288 |
widget=widget, |
| 1289 |
) |
| 1290 |
elif len(key) == 4: |
| 1291 |
|
| 1292 |
return coords_to_span( |
| 1293 |
widget=widget, |
| 1294 |
from_r=key[0], |
| 1295 |
from_c=key[1], |
| 1296 |
upto_r=key[2], |
| 1297 |
upto_c=key[3], |
| 1298 |
) |
| 1299 |
elif len(key) == 2 and all(isinstance(k, (list, tuple)) for k in key): |
| 1300 |
|
| 1301 |
return coords_to_span( |
| 1302 |
widget=widget, |
| 1303 |
from_r=key[0][0], |
| 1304 |
from_c=key[0][1], |
| 1305 |
upto_r=key[1][0], |
| 1306 |
upto_c=key[1][1], |
| 1307 |
) |
| 1308 |
|
| 1309 |
|
| 1310 |
elif isinstance(key, str): |
| 1311 |
if not key: |
| 1312 |
|
| 1313 |
return span_dict( |
| 1314 |
from_r=0, |
| 1315 |
from_c=None, |
| 1316 |
upto_r=None, |
| 1317 |
upto_c=None, |
| 1318 |
widget=widget, |
| 1319 |
) |
| 1320 |
elif key.startswith("<") and key.endswith(">"): |
| 1321 |
name = key[1:-1] |
| 1322 |
return spans.get(name, f"'{name}' not in named spans.") |
| 1323 |
|
| 1324 |
key = key.upper() |
| 1325 |
|
| 1326 |
|
| 1327 |
if m := PATTERN_ROW.match(key): |
| 1328 |
return span_dict( |
| 1329 |
from_r=int(m[1]) - 1, |
| 1330 |
from_c=None, |
| 1331 |
upto_r=int(m[1]), |
| 1332 |
upto_c=None, |
| 1333 |
widget=widget, |
| 1334 |
) |
| 1335 |
elif m := PATTERN_COL.match(key): |
| 1336 |
return span_dict( |
| 1337 |
from_r=None, |
| 1338 |
from_c=span_a2i(m[1]), |
| 1339 |
upto_r=None, |
| 1340 |
upto_c=span_a2n(m[1]), |
| 1341 |
widget=widget, |
| 1342 |
) |
| 1343 |
elif m := PATTERN_CELL.match(key): |
| 1344 |
c = span_a2i(m[1]) |
| 1345 |
r = int(m[2]) - 1 |
| 1346 |
return span_dict( |
| 1347 |
from_r=r, |
| 1348 |
from_c=c, |
| 1349 |
upto_r=r + 1, |
| 1350 |
upto_c=c + 1, |
| 1351 |
widget=widget, |
| 1352 |
) |
| 1353 |
elif m := PATTERN_RANGE.match(key): |
| 1354 |
return span_dict( |
| 1355 |
from_r=int(m[2]) - 1, |
| 1356 |
from_c=span_a2i(m[1]), |
| 1357 |
upto_r=int(m[4]), |
| 1358 |
upto_c=span_a2n(m[3]), |
| 1359 |
widget=widget, |
| 1360 |
) |
| 1361 |
elif m := PATTERN_ROW_RANGE.match(key): |
| 1362 |
return span_dict( |
| 1363 |
from_r=int(m[1]) - 1, |
| 1364 |
from_c=None, |
| 1365 |
upto_r=int(m[2]), |
| 1366 |
upto_c=None, |
| 1367 |
widget=widget, |
| 1368 |
) |
| 1369 |
elif m := PATTERN_ROW_START.match(key): |
| 1370 |
return span_dict( |
| 1371 |
from_r=int(m[1]) - 1, |
| 1372 |
from_c=None, |
| 1373 |
upto_r=None, |
| 1374 |
upto_c=None, |
| 1375 |
widget=widget, |
| 1376 |
) |
| 1377 |
elif m := PATTERN_ROW_END.match(key): |
| 1378 |
return span_dict( |
| 1379 |
from_r=0, |
| 1380 |
from_c=None, |
| 1381 |
upto_r=int(m[1]), |
| 1382 |
upto_c=None, |
| 1383 |
widget=widget, |
| 1384 |
) |
| 1385 |
elif m := PATTERN_COL_RANGE.match(key): |
| 1386 |
return span_dict( |
| 1387 |
from_r=None, |
| 1388 |
from_c=span_a2i(m[1]), |
| 1389 |
upto_r=None, |
| 1390 |
upto_c=span_a2n(m[2]), |
| 1391 |
widget=widget, |
| 1392 |
) |
| 1393 |
elif m := PATTERN_COL_START.match(key): |
| 1394 |
return span_dict( |
| 1395 |
from_r=None, |
| 1396 |
from_c=span_a2i(m[1]), |
| 1397 |
upto_r=None, |
| 1398 |
upto_c=None, |
| 1399 |
widget=widget, |
| 1400 |
) |
| 1401 |
elif m := PATTERN_COL_END.match(key): |
| 1402 |
return span_dict( |
| 1403 |
from_r=None, |
| 1404 |
from_c=0, |
| 1405 |
upto_r=None, |
| 1406 |
upto_c=span_a2n(m[1]), |
| 1407 |
widget=widget, |
| 1408 |
) |
| 1409 |
elif m := PATTERN_CELL_START.match(key): |
| 1410 |
return span_dict( |
| 1411 |
from_r=int(m[2]) - 1, |
| 1412 |
from_c=span_a2i(m[1]), |
| 1413 |
upto_r=None, |
| 1414 |
upto_c=None, |
| 1415 |
widget=widget, |
| 1416 |
) |
| 1417 |
elif m := PATTERN_CELL_END.match(key): |
| 1418 |
return span_dict( |
| 1419 |
from_r=0, |
| 1420 |
from_c=0, |
| 1421 |
upto_r=int(m[2]), |
| 1422 |
upto_c=span_a2n(m[1]), |
| 1423 |
widget=widget, |
| 1424 |
) |
| 1425 |
elif m := PATTERN_CELL_COL.match(key): |
| 1426 |
return span_dict( |
| 1427 |
from_r=int(m[2]) - 1, |
| 1428 |
from_c=span_a2i(m[1]), |
| 1429 |
upto_r=None, |
| 1430 |
upto_c=span_a2n(m[3]), |
| 1431 |
widget=widget, |
| 1432 |
) |
| 1433 |
elif m := PATTERN_CELL_ROW.match(key): |
| 1434 |
return span_dict( |
| 1435 |
from_r=int(m[2]) - 1, |
| 1436 |
from_c=span_a2i(m[1]), |
| 1437 |
upto_r=int(m[3]), |
| 1438 |
upto_c=None, |
| 1439 |
widget=widget, |
| 1440 |
) |
| 1441 |
elif PATTERN_ALL.match(key): |
| 1442 |
return span_dict( |
| 1443 |
from_r=0, |
| 1444 |
from_c=None, |
| 1445 |
upto_r=None, |
| 1446 |
upto_c=None, |
| 1447 |
widget=widget, |
| 1448 |
) |
| 1449 |
else: |
| 1450 |
return f"'{key}' could not be converted to span." |
| 1451 |
|
| 1452 |
except ValueError as error: |
| 1453 |
return f"Error, '{key}' could not be converted to span: {error}" |
| 1454 |
|
| 1455 |
|
| 1456 |
def span_is_cell(span: Span) -> bool: |
| 1457 |
return ( |
| 1458 |
isinstance(span["from_r"], int) |
| 1459 |
and isinstance(span["from_c"], int) |
| 1460 |
and isinstance(span["upto_r"], int) |
| 1461 |
and isinstance(span["upto_c"], int) |
| 1462 |
and span["upto_r"] - span["from_r"] == 1 |
| 1463 |
and span["upto_c"] - span["from_c"] == 1 |
| 1464 |
) |
| 1465 |
|
| 1466 |
|
| 1467 |
def span_to_cell(span: Span) -> tuple[int, int]: |
| 1468 |
|
| 1469 |
return (span["from_r"], span["from_c"]) |
| 1470 |
|
| 1471 |
|
| 1472 |
def span_ranges( |
| 1473 |
span: Span, |
| 1474 |
totalrows: int | Callable, |
| 1475 |
totalcols: int | Callable, |
| 1476 |
) -> tuple[Generator[int], Generator[int]]: |
| 1477 |
rng_from_r = 0 if span.from_r is None else span.from_r |
| 1478 |
rng_from_c = 0 if span.from_c is None else span.from_c |
| 1479 |
rng_upto_r = (totalrows() if isinstance(totalrows, Callable) else totalrows) if span.upto_r is None else span.upto_r |
| 1480 |
rng_upto_c = (totalcols() if isinstance(totalcols, Callable) else totalcols) if span.upto_c is None else span.upto_c |
| 1481 |
return range(rng_from_r, rng_upto_r), range(rng_from_c, rng_upto_c) |
| 1482 |
|
| 1483 |
|
| 1484 |
def span_froms( |
| 1485 |
span: Span, |
| 1486 |
) -> tuple[int, int]: |
| 1487 |
from_r = 0 if span.from_r is None else span.from_r |
| 1488 |
from_c = 0 if span.from_c is None else span.from_c |
| 1489 |
return from_r, from_c |
| 1490 |
|
| 1491 |
|
| 1492 |
def del_named_span_options(options: dict, itr: Iterator[Hashable], type_: str) -> None: |
| 1493 |
for k in itr: |
| 1494 |
if k in options and type_ in options[k]: |
| 1495 |
del options[k][type_] |
| 1496 |
|
| 1497 |
|
| 1498 |
def del_named_span_options_nested( |
| 1499 |
options: dict, itr1: Iterator[Hashable], itr2: Iterator[Hashable], type_: str |
| 1500 |
) -> None: |
| 1501 |
for k1 in itr1: |
| 1502 |
for k2 in itr2: |
| 1503 |
k = (k1, k2) |
| 1504 |
if k in options and type_ in options[k]: |
| 1505 |
del options[k][type_] |
| 1506 |
|
| 1507 |
|
| 1508 |
def add_highlight( |
| 1509 |
options: dict, |
| 1510 |
key: int | tuple[int, int], |
| 1511 |
bg: bool | None | str = False, |
| 1512 |
fg: bool | None | str = False, |
| 1513 |
end: bool | None = None, |
| 1514 |
overwrite: bool = True, |
| 1515 |
) -> dict: |
| 1516 |
if key not in options: |
| 1517 |
options[key] = {} |
| 1518 |
if overwrite or "highlight" not in options[key]: |
| 1519 |
options[key]["highlight"] = Highlight( |
| 1520 |
bg=None if bg is False else bg, |
| 1521 |
fg=None if fg is False else fg, |
| 1522 |
end=False if end is None else end, |
| 1523 |
) |
| 1524 |
else: |
| 1525 |
options[key]["highlight"] = Highlight( |
| 1526 |
bg=options[key]["highlight"].bg if bg is False else bg, |
| 1527 |
fg=options[key]["highlight"].fg if fg is False else fg, |
| 1528 |
end=options[key]["highlight"].end if end is None else end, |
| 1529 |
) |
| 1530 |
return options |
| 1531 |
|
| 1532 |
|
| 1533 |
def set_readonly( |
| 1534 |
options: dict, |
| 1535 |
key: int | tuple[int, int], |
| 1536 |
readonly: bool = True, |
| 1537 |
) -> dict: |
| 1538 |
if readonly: |
| 1539 |
if key not in options: |
| 1540 |
options[key] = {} |
| 1541 |
options[key]["readonly"] = True |
| 1542 |
else: |
| 1543 |
if key in options and "readonly" in options[key]: |
| 1544 |
del options[key]["readonly"] |
| 1545 |
return options |
| 1546 |
|
| 1547 |
|
| 1548 |
def convert_align(align: str | None) -> str | None: |
| 1549 |
if isinstance(align, str): |
| 1550 |
a = align.lower() |
| 1551 |
if a == "global": |
| 1552 |
return None |
| 1553 |
elif a in ("c", "center", "centre", "n"): |
| 1554 |
return "n" |
| 1555 |
elif a in ("w", "west", "left", "nw"): |
| 1556 |
return "nw" |
| 1557 |
elif a in ("e", "east", "right", "ne"): |
| 1558 |
return "ne" |
| 1559 |
elif align is None: |
| 1560 |
return None |
| 1561 |
raise ValueError(align_value_error) |
| 1562 |
|
| 1563 |
|
| 1564 |
def set_align( |
| 1565 |
options: dict, |
| 1566 |
key: int | tuple[int, int], |
| 1567 |
align: str | None = None, |
| 1568 |
) -> dict: |
| 1569 |
if align: |
| 1570 |
if key not in options: |
| 1571 |
options[key] = {} |
| 1572 |
options[key]["align"] = align |
| 1573 |
else: |
| 1574 |
if key in options and "align" in options[key]: |
| 1575 |
del options[key]["align"] |
| 1576 |
|
| 1577 |
|
| 1578 |
def del_from_options( |
| 1579 |
options: dict, |
| 1580 |
key: str, |
| 1581 |
coords: int | Iterator[int | tuple[int, int]] | None = None, |
| 1582 |
) -> dict: |
| 1583 |
if isinstance(coords, int): |
| 1584 |
if coords in options and key in options[coords]: |
| 1585 |
del options[coords] |
| 1586 |
elif is_iterable(coords): |
| 1587 |
for coord in coords: |
| 1588 |
if coord in options and key in options[coord]: |
| 1589 |
del options[coord] |
| 1590 |
else: |
| 1591 |
for d in options.values(): |
| 1592 |
if key in d: |
| 1593 |
del d[key] |
| 1594 |
|
| 1595 |
|
| 1596 |
def add_to_options( |
| 1597 |
options: dict, |
| 1598 |
coords: int | tuple[int, int], |
| 1599 |
key: str, |
| 1600 |
value: Any, |
| 1601 |
) -> dict: |
| 1602 |
if coords not in options: |
| 1603 |
options[coords] = {} |
| 1604 |
options[coords][key] = value |
| 1605 |
|
| 1606 |
|
| 1607 |
def fix_format_kwargs(kwargs: dict) -> dict: |
| 1608 |
if kwargs["formatter"] is None: |
| 1609 |
if kwargs["nullable"]: |
| 1610 |
if isinstance(kwargs["datatypes"], (list, tuple)): |
| 1611 |
kwargs["datatypes"] = tuple(kwargs["datatypes"]) + (type(None),) |
| 1612 |
else: |
| 1613 |
kwargs["datatypes"] = (kwargs["datatypes"], type(None)) |
| 1614 |
elif (isinstance(kwargs["datatypes"], (list, tuple)) and type(None) in kwargs["datatypes"]) or kwargs[ |
| 1615 |
"datatypes" |
| 1616 |
] is type(None): |
| 1617 |
raise TypeError("Non-nullable cells cannot have NoneType as a datatype.") |
| 1618 |
if not isinstance(kwargs["invalid_value"], str): |
| 1619 |
kwargs["invalid_value"] = f"{kwargs['invalid_value']}" |
| 1620 |
return kwargs |
| 1621 |
|
| 1622 |
|
| 1623 |
def span_idxs_post_move( |
| 1624 |
new_idxs: dict[int, int], |
| 1625 |
full_new_idxs: dict[int, int], |
| 1626 |
total: int, |
| 1627 |
span: Span, |
| 1628 |
axis: str, |
| 1629 |
) -> tuple[int | None]: |
| 1630 |
""" |
| 1631 |
Calculates the position of a span after moving rows/columns |
| 1632 |
""" |
| 1633 |
if isinstance(span[f"upto_{axis}"], int): |
| 1634 |
oldfrom, oldupto = int(span[f"from_{axis}"]), int(span[f"upto_{axis}"]) - 1 |
| 1635 |
newfrom = full_new_idxs[oldfrom] |
| 1636 |
newupto = full_new_idxs[oldupto] |
| 1637 |
if newfrom > newupto: |
| 1638 |
newfrom, newupto = newupto, newfrom |
| 1639 |
newupto += 1 |
| 1640 |
oldupto_colrange = int(span[f"upto_{axis}"]) |
| 1641 |
newupto_colrange = newupto |
| 1642 |
else: |
| 1643 |
oldfrom = int(span[f"from_{axis}"]) |
| 1644 |
newfrom = 0 if not oldfrom else full_new_idxs[oldfrom] |
| 1645 |
newupto = None |
| 1646 |
oldupto_colrange = total |
| 1647 |
newupto_colrange = oldupto_colrange |
| 1648 |
return oldupto_colrange, newupto_colrange, newfrom, newupto |
| 1649 |
|
| 1650 |
|
| 1651 |
def mod_span( |
| 1652 |
to_set_to: Span, |
| 1653 |
to_set_from: Span, |
| 1654 |
from_r: int | None = None, |
| 1655 |
from_c: int | None = None, |
| 1656 |
upto_r: int | None = None, |
| 1657 |
upto_c: int | None = None, |
| 1658 |
) -> Span: |
| 1659 |
to_set_to.kwargs = to_set_from.kwargs |
| 1660 |
to_set_to.type_ = to_set_from.type_ |
| 1661 |
to_set_to.table = to_set_from.table |
| 1662 |
to_set_to.index = to_set_from.index |
| 1663 |
to_set_to.header = to_set_from.header |
| 1664 |
to_set_to.from_r = from_r |
| 1665 |
to_set_to.from_c = from_c |
| 1666 |
to_set_to.upto_r = upto_r |
| 1667 |
to_set_to.upto_c = upto_c |
| 1668 |
return to_set_to |
| 1669 |
|
| 1670 |
|
| 1671 |
def mod_span_widget(span: Span, widget: Any) -> Span: |
| 1672 |
span.widget = widget |
| 1673 |
return span |
| 1674 |
|
| 1675 |
|
| 1676 |
def mod_event_val( |
| 1677 |
event_data: EventDataDict, |
| 1678 |
val: Any, |
| 1679 |
loc: Loc | None = None, |
| 1680 |
row: int | None = None, |
| 1681 |
column: int | None = None, |
| 1682 |
) -> EventDataDict: |
| 1683 |
event_data.value = val |
| 1684 |
if isinstance(loc, tuple): |
| 1685 |
event_data.loc = Loc(*loc) |
| 1686 |
event_data.row = loc[0] |
| 1687 |
event_data.column = loc[1] |
| 1688 |
|
| 1689 |
elif isinstance(row, int): |
| 1690 |
event_data.loc = Loc(row=row) |
| 1691 |
event_data.row = row |
| 1692 |
|
| 1693 |
elif isinstance(column, int): |
| 1694 |
event_data.loc = Loc(column=column) |
| 1695 |
event_data.column = column |
| 1696 |
|
| 1697 |
return event_data |
| 1698 |
|
| 1699 |
|
| 1700 |
def pop_positions( |
| 1701 |
itr: Callable, |
| 1702 |
to_pop: dict[int, int], |
| 1703 |
save_to: dict[int, int], |
| 1704 |
) -> Iterator[int]: |
| 1705 |
for i, pos in enumerate(itr()): |
| 1706 |
if i in to_pop: |
| 1707 |
save_to[to_pop[i]] = pos |
| 1708 |
else: |
| 1709 |
yield pos |
| 1710 |
|
| 1711 |
|
| 1712 |
def get_horizontal_gridline_points( |
| 1713 |
left: float, |
| 1714 |
stop: float, |
| 1715 |
positions: list[float], |
| 1716 |
start: int, |
| 1717 |
end: int, |
| 1718 |
) -> list[int | float]: |
| 1719 |
return list( |
| 1720 |
chain.from_iterable( |
| 1721 |
( |
| 1722 |
left - 1, |
| 1723 |
positions[r], |
| 1724 |
stop, |
| 1725 |
positions[r], |
| 1726 |
left - 1, |
| 1727 |
positions[r], |
| 1728 |
left - 1, |
| 1729 |
positions[r + 1] if len(positions) - 1 > r else positions[r], |
| 1730 |
) |
| 1731 |
for r in range(start, end) |
| 1732 |
) |
| 1733 |
) |
| 1734 |
|
| 1735 |
|
| 1736 |
def get_vertical_gridline_points( |
| 1737 |
top: float, |
| 1738 |
stop: float, |
| 1739 |
positions: list[float], |
| 1740 |
start: int, |
| 1741 |
end: int, |
| 1742 |
) -> list[float]: |
| 1743 |
return list( |
| 1744 |
chain.from_iterable( |
| 1745 |
( |
| 1746 |
positions[c], |
| 1747 |
top - 1, |
| 1748 |
positions[c], |
| 1749 |
stop, |
| 1750 |
positions[c], |
| 1751 |
top - 1, |
| 1752 |
positions[c + 1] if len(positions) - 1 > c else positions[c], |
| 1753 |
top - 1, |
| 1754 |
) |
| 1755 |
for c in range(start, end) |
| 1756 |
) |
| 1757 |
) |