File: functions.py

package info (click to toggle)
python-tksheet 7.4.16%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,560 kB
  • sloc: python: 25,406; sh: 27; makefile: 2
file content (1757 lines) | stat: -rw-r--r-- 51,280 bytes parent folder | download
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
from __future__ import annotations

import csv
import io
import pickle
import re
import tkinter as tk
from bisect import bisect_left
from collections import deque
from collections.abc import Callable, Generator, Hashable, Iterable, Iterator, Sequence
from difflib import SequenceMatcher
from itertools import chain, islice, repeat
from typing import Any, Literal

from .colors import color_map
from .constants import align_value_error, symbols_set
from .formatters import to_bool
from .other_classes import DotDict, EventDataDict, Highlight, Loc, Span

unpickle_obj = pickle.loads
lines_re = re.compile(r"[^\n]+")
ORD_A = ord("A")


def wrap_text(
    text: str,
    max_width: int,
    max_lines: int,
    char_width_fn: Callable,
    widths: dict[str, int],
    wrap: Literal["", "c", "w"] = "",
    start_line: int = 0,
) -> Generator[str]:
    total_lines = 0
    line_width = 0
    if wrap == "c":
        current_line = []
        for match in lines_re.finditer(text):
            for char in match.group():
                try:
                    char_width = widths[char]
                except KeyError:
                    char_width = char_width_fn(char)

                # adding char to line would result in wrap
                if line_width + char_width >= max_width:
                    if total_lines >= start_line:
                        yield "".join(current_line)

                    total_lines += 1
                    if total_lines >= max_lines:
                        return
                    current_line = []
                    line_width = 0

                    if char_width <= max_width:
                        current_line.append(char)
                        line_width = char_width
                # adding char to line is okay
                else:
                    current_line.append(char)
                    line_width += char_width

            if total_lines >= start_line:
                yield "".join(current_line)

            total_lines += 1
            if total_lines >= max_lines:
                return
            current_line = []  # Reset for next line
            line_width = 0

    elif wrap == "w":
        try:
            space_width = widths[" "]
        except KeyError:
            space_width = char_width_fn(" ")
        current_line = []

        for match in lines_re.finditer(text):
            for i, word in enumerate(match.group().split()):
                # if we're going to next word and
                # if a space fits on the end of the current line we add one
                if i and line_width + space_width < max_width:
                    current_line.append(" ")
                    line_width += space_width

                # check if word will fit
                word_width = 0
                word_char_widths = []
                for char in word:
                    try:
                        char_width = widths[char]
                    except KeyError:
                        char_width = char_width_fn(char)
                    word_char_widths.append(char_width)
                    word_width += char_width

                # we only wrap by character if the whole word alone wont fit max width
                # word won't fit at all we resort to char wrapping it
                if word_width >= max_width:
                    # yield current line before char wrapping word
                    if current_line:
                        if total_lines >= start_line:
                            yield "".join(current_line)

                        total_lines += 1
                        if total_lines >= max_lines:
                            return
                        current_line = []
                        line_width = 0

                    for char, w in zip(word, word_char_widths):
                        # adding char to line would result in wrap
                        if line_width + w >= max_width:
                            if total_lines >= start_line:
                                yield "".join(current_line)

                            total_lines += 1
                            if total_lines >= max_lines:
                                return
                            current_line = []
                            line_width = 0

                            if w <= max_width:
                                current_line.append(char)
                                line_width = w
                        # adding char to line is okay
                        else:
                            current_line.append(char)
                            line_width += w

                # word won't fit on current line but will fit on a newline
                elif line_width + word_width >= max_width:
                    if total_lines >= start_line:
                        yield "".join(current_line)

                    total_lines += 1
                    if total_lines >= max_lines:
                        return
                    current_line = [word]
                    line_width = word_width

                # word will fit we put it on the current line
                else:
                    current_line.append(word)
                    line_width += word_width

            if total_lines >= start_line:
                yield "".join(current_line)

            total_lines += 1
            if total_lines >= max_lines:
                return

            current_line = []  # Reset for next line
            line_width = 0

    else:
        for match in lines_re.finditer(text):
            line_width = 0
            current_line = []
            for char in match.group():
                try:
                    char_width = widths[char]
                except KeyError:
                    char_width = char_width_fn(char)
                line_width += char_width
                if line_width >= max_width:
                    break
                current_line.append(char)

            if total_lines >= start_line:
                yield "".join(current_line)

            # Count the line whether it's empty or not
            total_lines += 1
            if total_lines >= max_lines:
                return


def get_csv_str_dialect(s: str, delimiters: str) -> csv.Dialect:
    if len(s) > 6000:
        try:
            _upto = next(
                match.start() + 1 for i, match in enumerate(re.finditer("\n", s), 1) if i == 300 or match.start() > 6000
            )
        except Exception:
            _upto = len(s)
    else:
        _upto = len(s)
    try:
        return csv.Sniffer().sniff(s[:_upto] if len(s) > 6000 else s, delimiters=delimiters)
    except Exception:
        return csv.excel_tab


def get_data_from_clipboard(
    widget: tk.Misc,
    delimiters: str,
    lineterminator: str = "\n",
) -> list[list[str]]:
    data = widget.clipboard_get()
    dialect = get_csv_str_dialect(data, delimiters=delimiters)
    if dialect.delimiter in data or lineterminator in data:
        return list(csv.reader(io.StringIO(data), dialect=dialect, skipinitialspace=True))
    return [[data]]


def recursive_bind(widget: tk.Misc, event: str, callback: Callable) -> None:
    widget.bind(event, callback)
    for child in widget.winfo_children():
        recursive_bind(child, event, callback)


def recursive_unbind(widget: tk.Misc, event: str) -> None:
    widget.unbind(event)
    for child in widget.winfo_children():
        recursive_unbind(child, event)


def tksheet_type_error(kwarg: str, valid_types: list[str], not_type: Any) -> str:
    valid_types = ", ".join(f"{type_}" for type_ in valid_types)
    return f"Argument '{kwarg}' must be one of the following types: {valid_types}, not {type(not_type)}."


def new_tk_event(keysym: str) -> tk.Event:
    event = tk.Event()
    event.keysym = keysym
    return event


def event_has_char_key(event: Any) -> bool:
    return (
        event and hasattr(event, "char") and (event.char.isalpha() or event.char.isdigit() or event.char in symbols_set)
    )


def event_opens_dropdown_or_checkbox(event=None) -> bool:
    if event is None:
        return False
    elif event == "rc":
        return True
    return (
        (hasattr(event, "keysym") and event.keysym in {"Return", "F2", "BackSpace"})
        or (
            hasattr(event, "keycode") and event.keycode == "??" and hasattr(event, "num") and event.num == 1
        )  # mouseclick
    )


def dropdown_search_function(search_for: str, data: Iterable[Any]) -> None | int:
    search_for = search_for.lower()
    search_len = len(search_for)
    if not search_len:
        return next((i for i, v in enumerate(data) if not str(v)), None)

    matcher = SequenceMatcher(None, search_for, "", autojunk=False)

    match_rn = None
    match_st = float("inf")
    match_len_diff = float("inf")

    fallback_rn = None
    fallback_match_length = 0
    fallback_st = float("inf")

    for rn, value in enumerate(data):
        value = str(value).lower()
        if not value:
            continue
        st = value.find(search_for)
        if st != -1:
            len_diff = len(value) - search_len
            if st < match_st or (st == match_st and len_diff < match_len_diff):
                match_rn = rn
                match_st = st
                match_len_diff = len_diff

        elif match_rn is None:
            matcher.set_seq2(value)
            match = matcher.find_longest_match(0, search_len, 0, len(value))
            match_length = match.size
            start = match.b if match_length > 0 else -1
            if match_length > fallback_match_length or (match_length == fallback_match_length and start < fallback_st):
                fallback_rn = rn
                fallback_match_length = match_length
                fallback_st = start

    return match_rn if match_rn is not None else fallback_rn


def float_to_int(f: int | float) -> int | float:
    if f == float("inf"):
        return f
    return int(f)


def event_dict(
    name: str = None,
    sheet: Any = None,
    widget: tk.Canvas | None = None,
    boxes: None | dict | tuple = None,
    cells_table: None | dict = None,
    cells_header: None | dict = None,
    cells_index: None | dict = None,
    selected: None | tuple = None,
    data: Any = None,
    key: None | str = None,
    value: Any = None,
    loc: None | int | tuple[int] = None,
    row: None | int = None,
    column: None | int = None,
    resized_rows: None | dict = None,
    resized_columns: None | dict = None,
    # resized_index: None, dict] = None,
    # resized_header: None, dict] = None,
    being_selected: None | tuple = None,
    named_spans: None | dict = None,
    sheet_state: None | dict = None,
    treeview: None | dict = None,
    **kwargs,
) -> EventDataDict:
    return EventDataDict(
        eventname="" if name is None else name,
        sheetname="!sheet" if sheet is None else sheet,
        cells=DotDict(
            table=DotDict() if cells_table is None else cells_table,
            header=DotDict() if cells_header is None else cells_header,
            index=DotDict() if cells_index is None else cells_index,
        ),
        moved=DotDict(
            rows=DotDict(),
            columns=DotDict(),
        ),
        added=DotDict(
            rows=DotDict(),
            columns=DotDict(),
        ),
        deleted=DotDict(
            rows=DotDict(),
            columns=DotDict(),
            header=DotDict(),
            index=DotDict(),
            column_widths=DotDict(),
            row_heights=DotDict(),
        ),
        named_spans=DotDict() if named_spans is None else named_spans,
        options=DotDict(),
        selection_boxes={} if boxes is None else boxes,
        selected=() if selected is None else selected,
        being_selected=() if being_selected is None else being_selected,
        data={} if data is None else data,
        key="" if key is None else key,
        value=None if value is None else value,
        loc=() if loc is None else loc,
        row=row,
        column=column,
        resized=DotDict(
            rows=DotDict() if resized_rows is None else resized_rows,
            columns=DotDict() if resized_columns is None else resized_columns,
            # "header": DotDict() if resized_header is None else resized_header,
            # "index": DotDict() if resized_index is None else resized_index,
        ),
        widget=widget,
        sheet_state=DotDict() if sheet_state is None else sheet_state,
        treeview=DotDict(
            nodes={},
            renamed={},
            text={},
        )
        if treeview is None
        else treeview,
    )


def change_eventname(event_dict: EventDataDict, newname: str) -> EventDataDict:
    return EventDataDict({**event_dict, **{"eventname": newname}})


def stored_event_dict(d: DotDict) -> DotDict:
    return DotDict(name=d["eventname"], data=DotDict(kv for kv in d.items() if kv[0] != "widget"))


def len_to_idx(n: int) -> int:
    if n < 1:
        return 0
    else:
        return n - 1


def b_index(sorted_seq: Sequence[int], num_to_index: int) -> int:
    """
    Designed to be a faster way of finding the index of an int
    in a sorted list of ints than list.index()
    """
    if (idx := bisect_left(sorted_seq, num_to_index)) == len(sorted_seq) or sorted_seq[idx] != num_to_index:
        raise ValueError(f"{num_to_index} is not in Sequence")
    else:
        return idx


def try_b_index(sorted_seq: Sequence[int], num_to_index: int) -> int | None:
    if (idx := bisect_left(sorted_seq, num_to_index)) == len(sorted_seq) or sorted_seq[idx] != num_to_index:
        return None
    else:
        return idx


def bisect_in(sorted_seq: Sequence[int], num: int) -> bool:
    """
    Faster than 'num in sorted_seq'
    """
    try:
        return sorted_seq[bisect_left(sorted_seq, num)] == num
    except Exception:
        return False


def push_n(num: int, sorted_seq: Sequence[int]) -> int:
    if num < sorted_seq[0]:
        return num
    else:
        hi = len(sorted_seq)
        lo = 0
        while lo < hi:
            mid = (lo + hi) // 2
            if sorted_seq[mid] < num + mid + 1:
                lo = mid + 1
            else:
                hi = mid
        return num + lo


def get_menu_kwargs(ops: DotDict[str, Any]) -> DotDict[str, Any]:
    return DotDict(
        {
            "font": ops.table_font,
            "foreground": ops.popup_menu_fg,
            "background": ops.popup_menu_bg,
            "activebackground": ops.popup_menu_highlight_bg,
            "activeforeground": ops.popup_menu_highlight_fg,
        }
    )


def get_bg_fg(ops: DotDict[str, Any]) -> dict[str, str]:
    return {
        "bg": ops.table_editor_bg,
        "fg": ops.table_editor_fg,
        "select_bg": ops.table_editor_select_bg,
        "select_fg": ops.table_editor_select_fg,
    }


def get_dropdown_kwargs(
    values: list[Any] | None = None,
    set_value: Any = None,
    state: str = "normal",
    redraw: bool = True,
    selection_function: Callable | None = None,
    modified_function: Callable | None = None,
    search_function: Callable = dropdown_search_function,
    validate_input: bool = True,
    text: None | str = None,
) -> dict:
    return {
        "values": [] if values is None else values,
        "set_value": set_value,
        "state": state,
        "redraw": redraw,
        "selection_function": selection_function,
        "modified_function": modified_function,
        "search_function": search_function,
        "validate_input": validate_input,
        "text": text,
    }


def get_dropdown_dict(**kwargs) -> dict:
    return {
        "values": kwargs["values"],
        "select_function": kwargs["selection_function"],
        "modified_function": kwargs["modified_function"],
        "search_function": kwargs["search_function"],
        "validate_input": kwargs["validate_input"],
        "text": kwargs["text"],
        "state": kwargs["state"],
    }


def get_checkbox_kwargs(
    checked: bool = False,
    state: str = "normal",
    redraw: bool = True,
    check_function: Callable | None = None,
    text: str = "",
) -> dict:
    return {
        "checked": checked,
        "state": state,
        "redraw": redraw,
        "check_function": check_function,
        "text": text,
    }


def get_checkbox_dict(**kwargs) -> dict:
    return {
        "check_function": kwargs["check_function"],
        "state": kwargs["state"],
        "text": kwargs["text"],
    }


def is_iterable(o: Any) -> bool:
    if isinstance(o, str):
        return False
    try:
        iter(o)
        return True
    except Exception:
        return False


def int_x_iter(i: Iterator[int] | int) -> Iterator[int]:
    if isinstance(i, int):
        return (i,)
    return i


def int_x_tuple(i: Iterator[int] | int) -> tuple[int]:
    if isinstance(i, int):
        return (i,)
    return tuple(i)


def unpack(t: tuple[Any] | tuple[Iterator[Any]]) -> tuple[Any]:
    if not len(t):
        return t
    if is_iterable(t[0]) and len(t) == 1:
        return t[0]
    return t


def is_type_int(o: Any) -> bool:
    return isinstance(o, int) and not isinstance(o, bool)


def force_bool(o: Any) -> bool:
    try:
        return to_bool(o)
    except Exception:
        return False


def alpha2idx(a: str) -> int | None:
    try:
        n = 0
        for c in a.upper():
            n = n * 26 + ord(c) - ORD_A + 1
        return n - 1
    except Exception:
        return None


def alpha2num(a: str) -> int | None:
    n = alpha2idx(a)
    return n if n is None else n + 1


def num2alpha(n: int) -> str | None:
    try:
        s = ""
        n += 1
        while n > 0:
            n, r = divmod(n - 1, 26)
            s = chr(65 + r) + s
        return s
    except Exception:
        return None


def idx_param_to_int(idx: str | int | None) -> int | None:
    if idx is None or isinstance(idx, int):
        return idx
    return alpha2idx(idx)


def get_n2a(n: int = 0, _type: Literal["letters", "numbers", "both"] | None = "numbers") -> str:
    if _type == "letters":
        return num2alpha(n)
    elif _type == "numbers":
        return f"{n + 1}"
    elif _type == "both":
        return f"{num2alpha(n)} {n + 1}"
    elif _type is None:
        return ""


def get_index_of_gap_in_sorted_integer_seq_forward(
    seq: list[int],
    start: int = 0,
) -> int | None:
    prevn = seq[start]
    for idx, n in enumerate(islice(seq, start + 1, None), start + 1):
        if n != prevn + 1:
            return idx
        prevn = n
    return None


def get_index_of_gap_in_sorted_integer_seq_reverse(
    seq: list[int],
    start: int = 0,
) -> int | None:
    prevn = seq[start]
    for idx, n in zip(range(start, -1, -1), reversed(seq[:start])):
        if n != prevn - 1:
            return idx
        prevn = n
    return None


def get_seq_without_gaps_at_index(
    seq: list[int],
    position: int,
    get_st_end: bool = False,
) -> tuple[int, int] | list[int]:
    start_idx = bisect_left(seq, position)
    forward_gap = get_index_of_gap_in_sorted_integer_seq_forward(seq, start_idx)
    reverse_gap = get_index_of_gap_in_sorted_integer_seq_reverse(seq, start_idx)
    if forward_gap is not None:
        seq = seq[:forward_gap]
    if reverse_gap is not None:
        seq = seq[reverse_gap:]
    if get_st_end:
        return seq[0], seq[-1]
    return seq


def consecutive_chunks(seq: list[int]) -> Generator[list[int]]:
    start = 0
    for index, value in enumerate(seq, 1):
        try:
            if seq[index] > value + 1:
                yield seq[start : (start := index)]
        except Exception:
            yield seq[start : len(seq)]


def consecutive_ranges(seq: Sequence[int]) -> Generator[tuple[int, int]]:
    seq_iter = iter(seq)
    try:
        start = next(seq_iter)
    except StopIteration:
        return
    prev = start
    for curr in seq_iter:
        if curr > prev + 1:
            yield start, prev + 1
            start = curr
        prev = curr
    yield start, prev + 1


def is_contiguous(iterable: Iterable[int]) -> bool:
    itr = iter(iterable)
    prev = next(itr)
    return all(i == (prev := prev + 1) for i in itr)


def box_is_single_cell(
    r1: int,
    c1: int,
    r2: int,
    c2: int,
) -> bool:
    return r2 - r1 == 1 and c2 - c1 == 1


def color_tup(color: str) -> tuple[int, int, int]:
    res = color if color.startswith("#") else color_map[color]
    return int(res[1:3], 16), int(res[3:5], 16), int(res[5:], 16)


def cell_down_within_box(
    r: int,
    c: int,
    r1: int,
    c1: int,
    r2: int,
    c2: int,
    numrows: int,
    numcols: int,
) -> tuple[int, int]:
    moved = False
    new_r = r
    new_c = c
    if r + 1 == r2:
        new_r = r1
    elif numrows > 1:
        new_r = r + 1
        moved = True
    if not moved:
        if c + 1 == c2:
            new_c = c1
        elif numcols > 1:
            new_c = c + 1
    return new_r, new_c


def cell_right_within_box(
    r: int,
    c: int,
    r1: int,
    c1: int,
    r2: int,
    c2: int,
    numrows: int,
    numcols: int,
) -> tuple[int, int]:
    moved = False
    new_r = r
    new_c = c
    if c + 1 == c2:
        new_c = c1
    elif numcols > 1:
        new_c = c + 1
        moved = True
    if not moved:
        if r + 1 == r2:
            new_r = r1
        elif numrows > 1:
            new_r = r + 1
    return new_r, new_c


def get_last(
    it: Iterator[Any],
) -> Any:
    if hasattr(it, "__reversed__"):
        try:
            return next(reversed(it))
        except Exception:
            return None
    else:
        try:
            return deque(it, maxlen=1)[0]
        except Exception:
            return None


def index_exists(seq: Sequence[Any], index: int) -> bool:
    try:
        seq[index]
        return True
    except Exception:
        return False


def add_to_displayed(displayed: list[int], to_add: Iterable[int]) -> list[int]:
    # assumes to_add is sorted
    for i in to_add:
        ins = bisect_left(displayed, i)
        displayed[ins:] = [i] + [e + 1 for e in islice(displayed, ins, None)]
    return displayed


def move_elements_by_mapping(
    seq: list[Any],
    new_idxs: dict[int, int],
    old_idxs: dict[int, int] | None = None,
) -> list[Any]:
    # move elements of a list around
    # displacing other elements based on mapping
    # new_idxs = {old index: new index, ...}
    # old_idxs = {new index: old index, ...}
    if old_idxs is None:
        old_idxs = dict(zip(new_idxs.values(), new_idxs))
    remaining_values = (e for i, e in enumerate(seq) if i not in new_idxs)
    return [seq[old_idxs[i]] if i in old_idxs else next(remaining_values) for i in range(len(seq))]


def move_elements_by_mapping_gen(
    seq: list[Any],
    new_idxs: dict[int, int],
    old_idxs: dict[int, int] | None = None,
) -> Generator[Any]:
    if old_idxs is None:
        old_idxs = dict(zip(new_idxs.values(), new_idxs))
    remaining_values = (e for i, e in enumerate(seq) if i not in new_idxs)
    return (seq[old_idxs[i]] if i in old_idxs else next(remaining_values) for i in range(len(seq)))


def move_fast(seq: list[Any], new_idxs: dict[int, int], old_idxs: dict[int, int]) -> list[Any]:
    remaining_values = (e for i, e in enumerate(seq) if i not in new_idxs)
    return [seq[old_idxs[i]] if i in old_idxs else next(remaining_values) for i in range(len(seq))]


def move_elements_to(
    seq: list[Any],
    move_to: int,
    to_move: list[int],
) -> list[Any]:
    return move_elements_by_mapping(
        seq,
        *get_new_indexes(
            move_to,
            to_move,
            get_inverse=True,
        ),
    )


def get_new_indexes(
    move_to: int,
    to_move: Iterable[int],
    get_inverse: bool = False,
) -> tuple[dict[int, int]] | dict[int, int]:
    """
    move_to: A positive int, could possibly be the same as an element of to_move
    to_move: An iterable of ints, could be a dict, could be in any order
    returns {old idx: new idx, ...}
    """
    offset = sum(1 for i in to_move if i < move_to)
    correct_move_to = move_to - offset
    if not get_inverse:
        return {elem: correct_move_to + i for i, elem in enumerate(to_move)}
    else:
        new_idxs = {}
        old_idxs = {}
        for i, elem in enumerate(to_move):
            value = correct_move_to + i
            new_idxs[elem] = value
            old_idxs[value] = elem
        return new_idxs, old_idxs


def insert_items(
    seq: list[Any],
    to_insert: dict[int, Any],
    seq_len_func: Callable | None = None,
) -> list[Any]:
    """
    seq: list[Any]
    to_insert: keys are ints sorted, representing list indexes to insert items.
               Values are any, e.g. {0: 200, 1: 200}
    """
    if to_insert:
        if seq_len_func and next(reversed(to_insert)) >= len(seq) + len(to_insert):
            seq_len_func(next(reversed(to_insert)) - len(to_insert))
        for idx, v in to_insert.items():
            seq[idx:idx] = [v]
    return seq


def del_placeholder_dict_key(
    d: dict[Hashable, Any],
    k: Hashable,
    v: Any,
    p: tuple = (),
) -> dict[Hashable, Any]:
    if p in d:
        del d[p]
    d[k] = v
    return d


def data_to_displayed_idxs(
    to_convert: list[int],
    displayed: list[int],
) -> list[int]:
    return [i for i, e in enumerate(displayed) if bisect_in(to_convert, e)]


def displayed_to_data_idxs(
    to_convert: list[int],
    displayed: list[int],
) -> list[int]:
    return [displayed[e] for e in to_convert]


def rounded_box_coords(
    x1: float,
    y1: float,
    x2: float,
    y2: float,
    radius: int = 5,
) -> tuple[float]:
    if y2 - y1 < 2 or x2 - x1 < 2:
        return x1, y1, x2, y1, x2, y2, x1, y2
    return (
        x1 + radius,
        y1,
        x1 + radius,
        y1,
        x2 - radius,
        y1,
        x2 - radius,
        y1,
        x2,
        y1,
        x2,
        y1 + radius,
        x2,
        y1 + radius,
        x2,
        y2 - radius,
        x2,
        y2 - radius,
        x2,
        y2,
        x2 - radius,
        y2,
        x2 - radius,
        y2,
        x1 + radius,
        y2,
        x1 + radius,
        y2,
        x1,
        y2,
        x1,
        y2 - radius,
        x1,
        y2 - radius,
        x1,
        y1 + radius,
        x1,
        y1 + radius,
        x1,
        y1,
    )


def diff_gen(seq: list[float]) -> Generator[int]:
    it = iter(seq)
    a = next(it)
    for b in it:
        yield int(b - a)
        a = b


def gen_coords(
    start_row: int,
    start_col: int,
    end_row: int,
    end_col: int,
    reverse: bool = False,
) -> Generator[tuple[int, int]]:
    if reverse:
        for r in reversed(range(start_row, end_row)):
            for c in reversed(range(start_col, end_col)):
                yield (r, c)
    else:
        for r in range(start_row, end_row):
            for c in range(start_col, end_col):
                yield (r, c)


def box_gen_coords(
    from_r: int,
    from_c: int,
    upto_r: int,
    upto_c: int,
    start_r: int,
    start_c: int,
    reverse: bool,
    all_rows_displayed: bool = True,
    all_cols_displayed: bool = True,
    displayed_cols: list[int] | None = None,
    displayed_rows: list[int] | None = None,
    no_wrap: bool = False,
) -> Generator[tuple[int, int]]:
    # Initialize empty lists if None
    if displayed_rows is None:
        displayed_rows = []
    if displayed_cols is None:
        displayed_cols = []

    # Adjust row indices based on displayed_rows
    if not all_rows_displayed:
        from_r = displayed_rows[from_r]
        upto_r = displayed_rows[upto_r - 1] + 1
        start_r = displayed_rows[start_r]
    # Adjust column indices based on displayed_cols (fixing original bug)
    if not all_cols_displayed:
        from_c = displayed_cols[from_c]
        upto_c = displayed_cols[upto_c - 1] + 1
        start_c = displayed_cols[start_c]

    if not reverse:
        # Forward direction
        # Part 1: From (start_r, start_c) to the end of the box
        for c in range(start_c, upto_c):
            yield (start_r, c)
        for r in range(start_r + 1, upto_r):
            for c in range(from_c, upto_c):
                yield (r, c)
        if not no_wrap:
            # Part 2: Wrap around from beginning to just before (start_r, start_c)
            for r in range(from_r, start_r):
                for c in range(from_c, upto_c):
                    yield (r, c)
            if start_c > from_c:  # Only if there are columns before start_c
                for c in range(from_c, start_c):
                    yield (start_r, c)
    else:
        # Reverse direction
        # Part 1: From (start_r, start_c) backwards to the start of the box
        for c in range(start_c, from_c - 1, -1):
            yield (start_r, c)
        for r in range(start_r - 1, from_r - 1, -1):
            for c in range(upto_c - 1, from_c - 1, -1):
                yield (r, c)
        if not no_wrap:
            # Part 2: Wrap around from end to just after (start_r, start_c)
            for r in range(upto_r - 1, start_r, -1):
                for c in range(upto_c - 1, from_c - 1, -1):
                    yield (r, c)
            if start_c < upto_c - 1:  # Only if there are columns after start_c
                for c in range(upto_c - 1, start_c, -1):
                    yield (start_r, c)


def next_cell(
    start_row: int,
    start_col: int,
    end_row: int,
    end_col: int,
    row: int,
    col: int,
    reverse: bool = False,
) -> tuple[int, int]:
    if reverse:
        col -= 1
        if col < start_col:
            col = end_col - 1
            row -= 1
            if row < start_row:
                row = end_row - 1
    else:
        col += 1
        if col == end_col:
            col = start_col
            row += 1
            if row == end_row:
                row = start_row
    return row, col


def is_last_cell(
    start_row: int,
    start_col: int,
    end_row: int,
    end_col: int,
    row: int,
    col: int,
    reverse: bool = False,
) -> bool:
    if reverse:
        return row == start_row and col == start_col
    return row == end_row - 1 and col == end_col - 1


def zip_fill_2nd_value(x: Iterator[Any], o: Any) -> Generator[Any, Any]:
    return zip(x, repeat(o))


def str_to_int(s: str) -> int | None:
    if s.startswith(("-", "+")):
        if s[1:].isdigit():
            return int(s)
        return None
    elif not s.startswith(("-", "+")):
        if s.isdigit():
            return int(s)
        return None


def gen_formatted(
    options: dict,
    formatter: Any = None,
) -> Generator[tuple[int, int]] | Generator[int]:
    if formatter is None:
        return (k for k, dct in options.items() if "format" in dct)
    return (k for k, dct in options.items() if "format" in dct and dct["format"]["formatter"] == formatter)


def options_with_key(
    options: dict,
    key: str,
) -> Generator[tuple[int, int]] | Generator[int]:
    return (k for k, dct in options.items() if key in dct)


def try_binding(
    binding: None | Callable,
    event: dict,
    new_name: None | str = None,
) -> bool:
    if binding:
        try:
            if new_name is None:
                binding(event)
            else:
                binding(change_eventname(event, new_name))
        except Exception:
            return False
    return True


def span_dict(
    from_r: int | None = None,
    from_c: int | None = None,
    upto_r: int | None = None,
    upto_c: int | None = None,
    type_: str | None = None,
    name: str | None = None,
    kwargs: dict | None = None,
    table: bool = True,
    header: bool = False,
    index: bool = False,
    tdisp: bool = False,
    idisp: bool = True,
    hdisp: bool = True,
    transposed: bool = False,
    ndim: int | None = None,
    convert: Callable | None = None,
    undo: bool = False,
    emit_event: bool = False,
    widget: Any = None,
) -> Span:
    d: Span = Span(
        from_r=from_r,
        from_c=from_c,
        upto_r=upto_r,
        upto_c=upto_c,
        type_="" if type_ is None else type_,
        name="" if name is None else name,
        kwargs={} if kwargs is None else kwargs,
        table=table,
        index=index,
        header=header,
        tdisp=tdisp,
        idisp=idisp,
        hdisp=hdisp,
        transposed=transposed,
        ndim=ndim,
        convert=convert,
        undo=undo,
        emit_event=emit_event,
        widget=widget,
    )
    return d


def coords_to_span(
    widget: Any,
    from_r: int | None = None,
    from_c: int | None = None,
    upto_r: int | None = None,
    upto_c: int | None = None,
) -> Span:
    if not isinstance(from_r, int) and from_r is not None:
        from_r = None
    if not isinstance(from_c, int) and from_c is not None:
        from_c = None
    if not isinstance(upto_r, int) and upto_r is not None:
        upto_r = None
    if not isinstance(upto_c, int) and upto_c is not None:
        upto_c = None
    if from_r is None and from_c is None:
        from_r = 0
    return span_dict(
        from_r=from_r,
        from_c=from_c,
        upto_r=upto_r,
        upto_c=upto_c,
        widget=widget,
    )


PATTERN_ROW = re.compile(r"^(\d+)$")  # "1"
PATTERN_COL = re.compile(r"^([A-Z]+)$")  # "A"
PATTERN_CELL = re.compile(r"^([A-Z]+)(\d+)$")  # "A1"
PATTERN_RANGE = re.compile(r"^([A-Z]+)(\d+):([A-Z]+)(\d+)$")  # "A1:B2"
PATTERN_ROW_RANGE = re.compile(r"^(\d+):(\d+)$")  # "1:2"
PATTERN_ROW_START = re.compile(r"^(\d+):$")  # "2:"
PATTERN_ROW_END = re.compile(r"^:(\d+)$")  # ":2"
PATTERN_COL_RANGE = re.compile(r"^([A-Z]+):([A-Z]+)$")  # "A:B"
PATTERN_COL_START = re.compile(r"^([A-Z]+):$")  # "A:"
PATTERN_COL_END = re.compile(r"^:([A-Z]+)$")  # ":B"
PATTERN_CELL_START = re.compile(r"^([A-Z]+)(\d+):$")  # "A1:"
PATTERN_CELL_END = re.compile(r"^:([A-Z]+)(\d+)$")  # ":B1"
PATTERN_CELL_COL = re.compile(r"^([A-Z]+)(\d+):([A-Z]+)$")  # "A1:B"
PATTERN_CELL_ROW = re.compile(r"^([A-Z]+)(\d+):(\d+)$")  # "A1:2"
PATTERN_ALL = re.compile(r"^:$")  # ":"


def span_a2i(a: str) -> int | None:
    n = 0
    for c in a:
        n = n * 26 + ord(c) - ORD_A + 1
    return n - 1


def span_a2n(a: str) -> int | None:
    n = 0
    for c in a:
        n = n * 26 + ord(c) - ORD_A + 1
    return n


def key_to_span(
    key: (
        str
        | int
        | slice
        | Sequence[int | None, int | None]
        | Sequence[int | None, int | None, int | None, int | None]
        | Sequence[Sequence[int | None, int | None], Sequence[int | None, int | None]]
    ),
    spans: dict[str, Span],
    widget: Any = None,
) -> Span:
    """
    Convert various input types to a Span object representing a 2D range.

    Args:
        key: The input to convert (str, int, slice, sequence, or None).
        spans: A dictionary of named spans (e.g., {"<name>": Span(...)}).
        widget: Optional widget context for span creation.

    Returns:
        A Span object or an error message string if the key is invalid.
    """
    # Handle Span object directly
    if isinstance(key, Span):
        return key

    # Handle None as full span
    elif key is None:
        return coords_to_span(widget=widget, from_r=None, from_c=None, upto_r=None, upto_c=None)

    # Validate input type
    elif not isinstance(key, (str, int, slice, list, tuple)):
        return f"Key type must be either str, int, list, tuple or slice, not '{type(key).__name__}'."

    try:
        # Integer key: whole row
        if isinstance(key, int):
            return span_dict(
                from_r=key,
                from_c=None,
                upto_r=key + 1,
                upto_c=None,
                widget=widget,
            )

        # Slice key: row range
        elif isinstance(key, slice):
            start = 0 if key.start is None else key.start
            return span_dict(
                from_r=start,
                from_c=None,
                upto_r=key.stop,
                upto_c=None,
                widget=widget,
            )

        # Sequence key: various span formats
        elif isinstance(key, (list, tuple)):
            if (
                len(key) == 2
                and (isinstance(key[0], int) or key[0] is None)
                and (isinstance(key[1], int) or key[1] is None)
            ):
                # Single cell or partial span: (row, col)
                r_int = isinstance(key[0], int)
                c_int = isinstance(key[1], int)
                return span_dict(
                    from_r=key[0] if r_int else 0,
                    from_c=key[1] if c_int else 0,
                    upto_r=key[0] + 1 if r_int else None,
                    upto_c=key[1] + 1 if c_int else None,
                    widget=widget,
                )
            elif len(key) == 4:
                # Full span coordinates: (from_r, from_c, upto_r, upto_c)
                return coords_to_span(
                    widget=widget,
                    from_r=key[0],
                    from_c=key[1],
                    upto_r=key[2],
                    upto_c=key[3],
                )
            elif len(key) == 2 and all(isinstance(k, (list, tuple)) for k in key):
                # Start and end points: ((from_r, from_c), (upto_r, upto_c))
                return coords_to_span(
                    widget=widget,
                    from_r=key[0][0],
                    from_c=key[0][1],
                    upto_r=key[1][0],
                    upto_c=key[1][1],
                )

        # String key: parse various span formats
        elif isinstance(key, str):
            if not key:
                # Empty string treated as full span
                return span_dict(
                    from_r=0,
                    from_c=None,
                    upto_r=None,
                    upto_c=None,
                    widget=widget,
                )
            elif key.startswith("<") and key.endswith(">"):
                name = key[1:-1]
                return spans.get(name, f"'{name}' not in named spans.")

            key = key.upper()  # Case-insensitive parsing

            # Match string against precompiled patterns
            if m := PATTERN_ROW.match(key):
                return span_dict(
                    from_r=int(m[1]) - 1,
                    from_c=None,
                    upto_r=int(m[1]),
                    upto_c=None,
                    widget=widget,
                )
            elif m := PATTERN_COL.match(key):
                return span_dict(
                    from_r=None,
                    from_c=span_a2i(m[1]),
                    upto_r=None,
                    upto_c=span_a2n(m[1]),
                    widget=widget,
                )
            elif m := PATTERN_CELL.match(key):
                c = span_a2i(m[1])
                r = int(m[2]) - 1
                return span_dict(
                    from_r=r,
                    from_c=c,
                    upto_r=r + 1,
                    upto_c=c + 1,
                    widget=widget,
                )
            elif m := PATTERN_RANGE.match(key):
                return span_dict(
                    from_r=int(m[2]) - 1,
                    from_c=span_a2i(m[1]),
                    upto_r=int(m[4]),
                    upto_c=span_a2n(m[3]),
                    widget=widget,
                )
            elif m := PATTERN_ROW_RANGE.match(key):
                return span_dict(
                    from_r=int(m[1]) - 1,
                    from_c=None,
                    upto_r=int(m[2]),
                    upto_c=None,
                    widget=widget,
                )
            elif m := PATTERN_ROW_START.match(key):
                return span_dict(
                    from_r=int(m[1]) - 1,
                    from_c=None,
                    upto_r=None,
                    upto_c=None,
                    widget=widget,
                )
            elif m := PATTERN_ROW_END.match(key):
                return span_dict(
                    from_r=0,
                    from_c=None,
                    upto_r=int(m[1]),
                    upto_c=None,
                    widget=widget,
                )
            elif m := PATTERN_COL_RANGE.match(key):
                return span_dict(
                    from_r=None,
                    from_c=span_a2i(m[1]),
                    upto_r=None,
                    upto_c=span_a2n(m[2]),
                    widget=widget,
                )
            elif m := PATTERN_COL_START.match(key):
                return span_dict(
                    from_r=None,
                    from_c=span_a2i(m[1]),
                    upto_r=None,
                    upto_c=None,
                    widget=widget,
                )
            elif m := PATTERN_COL_END.match(key):
                return span_dict(
                    from_r=None,
                    from_c=0,
                    upto_r=None,
                    upto_c=span_a2n(m[1]),
                    widget=widget,
                )
            elif m := PATTERN_CELL_START.match(key):
                return span_dict(
                    from_r=int(m[2]) - 1,
                    from_c=span_a2i(m[1]),
                    upto_r=None,
                    upto_c=None,
                    widget=widget,
                )
            elif m := PATTERN_CELL_END.match(key):
                return span_dict(
                    from_r=0,
                    from_c=0,
                    upto_r=int(m[2]),
                    upto_c=span_a2n(m[1]),
                    widget=widget,
                )
            elif m := PATTERN_CELL_COL.match(key):
                return span_dict(
                    from_r=int(m[2]) - 1,
                    from_c=span_a2i(m[1]),
                    upto_r=None,
                    upto_c=span_a2n(m[3]),
                    widget=widget,
                )
            elif m := PATTERN_CELL_ROW.match(key):
                return span_dict(
                    from_r=int(m[2]) - 1,
                    from_c=span_a2i(m[1]),
                    upto_r=int(m[3]),
                    upto_c=None,
                    widget=widget,
                )
            elif PATTERN_ALL.match(key):
                return span_dict(
                    from_r=0,
                    from_c=None,
                    upto_r=None,
                    upto_c=None,
                    widget=widget,
                )
            else:
                return f"'{key}' could not be converted to span."

    except ValueError as error:
        return f"Error, '{key}' could not be converted to span: {error}"


def span_is_cell(span: Span) -> bool:
    return (
        isinstance(span["from_r"], int)
        and isinstance(span["from_c"], int)
        and isinstance(span["upto_r"], int)
        and isinstance(span["upto_c"], int)
        and span["upto_r"] - span["from_r"] == 1
        and span["upto_c"] - span["from_c"] == 1
    )


def span_to_cell(span: Span) -> tuple[int, int]:
    # assumed that span arg has been tested by 'span_is_cell()'
    return (span["from_r"], span["from_c"])


def span_ranges(
    span: Span,
    totalrows: int | Callable,
    totalcols: int | Callable,
) -> tuple[Generator[int], Generator[int]]:
    rng_from_r = 0 if span.from_r is None else span.from_r
    rng_from_c = 0 if span.from_c is None else span.from_c
    rng_upto_r = (totalrows() if isinstance(totalrows, Callable) else totalrows) if span.upto_r is None else span.upto_r
    rng_upto_c = (totalcols() if isinstance(totalcols, Callable) else totalcols) if span.upto_c is None else span.upto_c
    return range(rng_from_r, rng_upto_r), range(rng_from_c, rng_upto_c)


def span_froms(
    span: Span,
) -> tuple[int, int]:
    from_r = 0 if span.from_r is None else span.from_r
    from_c = 0 if span.from_c is None else span.from_c
    return from_r, from_c


def del_named_span_options(options: dict, itr: Iterator[Hashable], type_: str) -> None:
    for k in itr:
        if k in options and type_ in options[k]:
            del options[k][type_]


def del_named_span_options_nested(
    options: dict, itr1: Iterator[Hashable], itr2: Iterator[Hashable], type_: str
) -> None:
    for k1 in itr1:
        for k2 in itr2:
            k = (k1, k2)
            if k in options and type_ in options[k]:
                del options[k][type_]


def add_highlight(
    options: dict,
    key: int | tuple[int, int],
    bg: bool | None | str = False,
    fg: bool | None | str = False,
    end: bool | None = None,
    overwrite: bool = True,
) -> dict:
    if key not in options:
        options[key] = {}
    if overwrite or "highlight" not in options[key]:
        options[key]["highlight"] = Highlight(
            bg=None if bg is False else bg,
            fg=None if fg is False else fg,
            end=False if end is None else end,
        )
    else:
        options[key]["highlight"] = Highlight(
            bg=options[key]["highlight"].bg if bg is False else bg,
            fg=options[key]["highlight"].fg if fg is False else fg,
            end=options[key]["highlight"].end if end is None else end,
        )
    return options


def set_readonly(
    options: dict,
    key: int | tuple[int, int],
    readonly: bool = True,
) -> dict:
    if readonly:
        if key not in options:
            options[key] = {}
        options[key]["readonly"] = True
    else:
        if key in options and "readonly" in options[key]:
            del options[key]["readonly"]
    return options


def convert_align(align: str | None) -> str | None:
    if isinstance(align, str):
        a = align.lower()
        if a == "global":
            return None
        elif a in ("c", "center", "centre", "n"):
            return "n"
        elif a in ("w", "west", "left", "nw"):
            return "nw"
        elif a in ("e", "east", "right", "ne"):
            return "ne"
    elif align is None:
        return None
    raise ValueError(align_value_error)


def set_align(
    options: dict,
    key: int | tuple[int, int],
    align: str | None = None,
) -> dict:
    if align:
        if key not in options:
            options[key] = {}
        options[key]["align"] = align
    else:
        if key in options and "align" in options[key]:
            del options[key]["align"]


def del_from_options(
    options: dict,
    key: str,
    coords: int | Iterator[int | tuple[int, int]] | None = None,
) -> dict:
    if isinstance(coords, int):
        if coords in options and key in options[coords]:
            del options[coords]
    elif is_iterable(coords):
        for coord in coords:
            if coord in options and key in options[coord]:
                del options[coord]
    else:
        for d in options.values():
            if key in d:
                del d[key]


def add_to_options(
    options: dict,
    coords: int | tuple[int, int],
    key: str,
    value: Any,
) -> dict:
    if coords not in options:
        options[coords] = {}
    options[coords][key] = value


def fix_format_kwargs(kwargs: dict) -> dict:
    if kwargs["formatter"] is None:
        if kwargs["nullable"]:
            if isinstance(kwargs["datatypes"], (list, tuple)):
                kwargs["datatypes"] = tuple(kwargs["datatypes"]) + (type(None),)
            else:
                kwargs["datatypes"] = (kwargs["datatypes"], type(None))
        elif (isinstance(kwargs["datatypes"], (list, tuple)) and type(None) in kwargs["datatypes"]) or kwargs[
            "datatypes"
        ] is type(None):
            raise TypeError("Non-nullable cells cannot have NoneType as a datatype.")
    if not isinstance(kwargs["invalid_value"], str):
        kwargs["invalid_value"] = f"{kwargs['invalid_value']}"
    return kwargs


def span_idxs_post_move(
    new_idxs: dict[int, int],
    full_new_idxs: dict[int, int],
    total: int,
    span: Span,
    axis: str,  # 'r' or 'c'
) -> tuple[int | None]:
    """
    Calculates the position of a span after moving rows/columns
    """
    if isinstance(span[f"upto_{axis}"], int):
        oldfrom, oldupto = int(span[f"from_{axis}"]), int(span[f"upto_{axis}"]) - 1
        newfrom = full_new_idxs[oldfrom]
        newupto = full_new_idxs[oldupto]
        if newfrom > newupto:
            newfrom, newupto = newupto, newfrom
        newupto += 1
        oldupto_colrange = int(span[f"upto_{axis}"])
        newupto_colrange = newupto
    else:
        oldfrom = int(span[f"from_{axis}"])
        newfrom = 0 if not oldfrom else full_new_idxs[oldfrom]
        newupto = None
        oldupto_colrange = total
        newupto_colrange = oldupto_colrange
    return oldupto_colrange, newupto_colrange, newfrom, newupto


def mod_span(
    to_set_to: Span,
    to_set_from: Span,
    from_r: int | None = None,
    from_c: int | None = None,
    upto_r: int | None = None,
    upto_c: int | None = None,
) -> Span:
    to_set_to.kwargs = to_set_from.kwargs
    to_set_to.type_ = to_set_from.type_
    to_set_to.table = to_set_from.table
    to_set_to.index = to_set_from.index
    to_set_to.header = to_set_from.header
    to_set_to.from_r = from_r
    to_set_to.from_c = from_c
    to_set_to.upto_r = upto_r
    to_set_to.upto_c = upto_c
    return to_set_to


def mod_span_widget(span: Span, widget: Any) -> Span:
    span.widget = widget
    return span


def mod_event_val(
    event_data: EventDataDict,
    val: Any,
    loc: Loc | None = None,
    row: int | None = None,
    column: int | None = None,
) -> EventDataDict:
    event_data.value = val
    if isinstance(loc, tuple):
        event_data.loc = Loc(*loc)
        event_data.row = loc[0]
        event_data.column = loc[1]

    elif isinstance(row, int):
        event_data.loc = Loc(row=row)
        event_data.row = row

    elif isinstance(column, int):
        event_data.loc = Loc(column=column)
        event_data.column = column

    return event_data


def pop_positions(
    itr: Callable,
    to_pop: dict[int, int],  # displayed index: data index
    save_to: dict[int, int],
) -> Iterator[int]:
    for i, pos in enumerate(itr()):
        if i in to_pop:
            save_to[to_pop[i]] = pos
        else:
            yield pos


def get_horizontal_gridline_points(
    left: float,
    stop: float,
    positions: list[float],
    start: int,
    end: int,
) -> list[int | float]:
    return list(
        chain.from_iterable(
            (
                left - 1,
                positions[r],
                stop,
                positions[r],
                left - 1,
                positions[r],
                left - 1,
                positions[r + 1] if len(positions) - 1 > r else positions[r],
            )
            for r in range(start, end)
        )
    )


def get_vertical_gridline_points(
    top: float,
    stop: float,
    positions: list[float],
    start: int,
    end: int,
) -> list[float]:
    return list(
        chain.from_iterable(
            (
                positions[c],
                top - 1,
                positions[c],
                stop,
                positions[c],
                top - 1,
                positions[c + 1] if len(positions) - 1 > c else positions[c],
                top - 1,
            )
            for c in range(start, end)
        )
    )