吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 6257|回复: 60
上一主题 下一主题
收起左侧

[Windows] 鼠标或键盘可自定义可同时多按键连点工具(附软件及py源码)

    [复制链接]
跳转到指定楼层
楼主
zwjtr93 发表于 2025-4-10 03:25 回帖奖励
就是个连点工具,功能如图所示,本人系统win11其他系统未做测试,自己玩的游戏可以识别未做太多识别测试,热键的部分组合键识别会有问题未再做修复,其余功能正常。

下载地址:
https://wwlo.lanzouo.com/i95fC2t4t0kf
密码:2duq

楼下分享python源码

免费评分

参与人数 26吾爱币 +27 热心值 +22 收起 理由
米迦尔 + 1 + 1 谢谢@Thanks!
zyhaijun + 1 + 1 鼓励转贴优秀软件安全工具和文档!
曲径通幽处 + 1 + 1 用心讨论,共获提升!
ablepolet + 1 + 1 我很赞同!
cioceo + 1 谢谢@Thanks!
那时还年轻 + 1 + 1 我很赞同!
yuhao724 + 1 我很赞同!
ot1686 + 1 + 1 谢谢@Thanks!
天川 + 1 + 1 用心讨论,共获提升!
lbj528811 + 1 谢谢@Thanks!
aa20221101 + 1 + 1 热心回复!
scirain + 1 + 1 谢谢@Thanks!
jan2204 + 1 + 1 鼓励转贴优秀软件安全工具和文档!
qq350232900 + 1 + 1 无法启动此程序,因为计算机中丢失api-ms-core-path-|1-1-0.dll
qsj521521 + 1 + 1 谢谢@Thanks!
zybesn + 1 + 1 热心回复!
wyangdh + 1 + 1 谢谢@Thanks!
平凡之家 + 2 + 1 谢谢@Thanks!
jyj0912 + 1 谢谢@Thanks!
抱薪风雪雾 + 1 + 1 谢谢@Thanks!
Mandrake + 1 + 1 谢谢@Thanks!
winner2014 + 1 + 1 我很赞同!
cjwq1224 + 1 + 1 谢谢@Thanks!
helh0275 + 1 + 1 感谢发布原创作品,吾爱破解论坛因你更精彩!
superboy8286 + 1 + 1 谢谢@Thanks!
IcePlume + 1 + 1 我很赞同!

查看全部评分

本帖被以下淘专辑推荐:

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

推荐
yemuzhixue 发表于 2025-4-10 08:33
先点赞收藏,学习一下,以后一定可以使用。
推荐
 楼主| zwjtr93 发表于 2025-4-10 03:26 |楼主
本帖最后由 zwjtr93 于 2025-4-10 03:28 编辑

源码(因为有源码也就随便玩玩弄的软件不会再更新修复):
[Python] 纯文本查看 复制代码
0001
0002
0003
0004
0005
0006
0007
0008
0009
0010
0011
0012
0013
0014
0015
0016
0017
0018
0019
0020
0021
0022
0023
0024
0025
0026
0027
0028
0029
0030
0031
0032
0033
0034
0035
0036
0037
0038
0039
0040
0041
0042
0043
0044
0045
0046
0047
0048
0049
0050
0051
0052
0053
0054
0055
0056
0057
0058
0059
0060
0061
0062
0063
0064
0065
0066
0067
0068
0069
0070
0071
0072
0073
0074
0075
0076
0077
0078
0079
0080
0081
0082
0083
0084
0085
0086
0087
0088
0089
0090
0091
0092
0093
0094
0095
0096
0097
0098
0099
0100
0101
0102
0103
0104
0105
0106
0107
0108
0109
0110
0111
0112
0113
0114
0115
0116
0117
0118
0119
0120
0121
0122
0123
0124
0125
0126
0127
0128
0129
0130
0131
0132
0133
0134
0135
0136
0137
0138
0139
0140
0141
0142
0143
0144
0145
0146
0147
0148
0149
0150
0151
0152
0153
0154
0155
0156
0157
0158
0159
0160
0161
0162
0163
0164
0165
0166
0167
0168
0169
0170
0171
0172
0173
0174
0175
0176
0177
0178
0179
0180
0181
0182
0183
0184
0185
0186
0187
0188
0189
0190
0191
0192
0193
0194
0195
0196
0197
0198
0199
0200
0201
0202
0203
0204
0205
0206
0207
0208
0209
0210
0211
0212
0213
0214
0215
0216
0217
0218
0219
0220
0221
0222
0223
0224
0225
0226
0227
0228
0229
0230
0231
0232
0233
0234
0235
0236
0237
0238
0239
0240
0241
0242
0243
0244
0245
0246
0247
0248
0249
0250
0251
0252
0253
0254
0255
0256
0257
0258
0259
0260
0261
0262
0263
0264
0265
0266
0267
0268
0269
0270
0271
0272
0273
0274
0275
0276
0277
0278
0279
0280
0281
0282
0283
0284
0285
0286
0287
0288
0289
0290
0291
0292
0293
0294
0295
0296
0297
0298
0299
0300
0301
0302
0303
0304
0305
0306
0307
0308
0309
0310
0311
0312
0313
0314
0315
0316
0317
0318
0319
0320
0321
0322
0323
0324
0325
0326
0327
0328
0329
0330
0331
0332
0333
0334
0335
0336
0337
0338
0339
0340
0341
0342
0343
0344
0345
0346
0347
0348
0349
0350
0351
0352
0353
0354
0355
0356
0357
0358
0359
0360
0361
0362
0363
0364
0365
0366
0367
0368
0369
0370
0371
0372
0373
0374
0375
0376
0377
0378
0379
0380
0381
0382
0383
0384
0385
0386
0387
0388
0389
0390
0391
0392
0393
0394
0395
0396
0397
0398
0399
0400
0401
0402
0403
0404
0405
0406
0407
0408
0409
0410
0411
0412
0413
0414
0415
0416
0417
0418
0419
0420
0421
0422
0423
0424
0425
0426
0427
0428
0429
0430
0431
0432
0433
0434
0435
0436
0437
0438
0439
0440
0441
0442
0443
0444
0445
0446
0447
0448
0449
0450
0451
0452
0453
0454
0455
0456
0457
0458
0459
0460
0461
0462
0463
0464
0465
0466
0467
0468
0469
0470
0471
0472
0473
0474
0475
0476
0477
0478
0479
0480
0481
0482
0483
0484
0485
0486
0487
0488
0489
0490
0491
0492
0493
0494
0495
0496
0497
0498
0499
0500
0501
0502
0503
0504
0505
0506
0507
0508
0509
0510
0511
0512
0513
0514
0515
0516
0517
0518
0519
0520
0521
0522
0523
0524
0525
0526
0527
0528
0529
0530
0531
0532
0533
0534
0535
0536
0537
0538
0539
0540
0541
0542
0543
0544
0545
0546
0547
0548
0549
0550
0551
0552
0553
0554
0555
0556
0557
0558
0559
0560
0561
0562
0563
0564
0565
0566
0567
0568
0569
0570
0571
0572
0573
0574
0575
0576
0577
0578
0579
0580
0581
0582
0583
0584
0585
0586
0587
0588
0589
0590
0591
0592
0593
0594
0595
0596
0597
0598
0599
0600
0601
0602
0603
0604
0605
0606
0607
0608
0609
0610
0611
0612
0613
0614
0615
0616
0617
0618
0619
0620
0621
0622
0623
0624
0625
0626
0627
0628
0629
0630
0631
0632
0633
0634
0635
0636
0637
0638
0639
0640
0641
0642
0643
0644
0645
0646
0647
0648
0649
0650
0651
0652
0653
0654
0655
0656
0657
0658
0659
0660
0661
0662
0663
0664
0665
0666
0667
0668
0669
0670
0671
0672
0673
0674
0675
0676
0677
0678
0679
0680
0681
0682
0683
0684
0685
0686
0687
0688
0689
0690
0691
0692
0693
0694
0695
0696
0697
0698
0699
0700
0701
0702
0703
0704
0705
0706
0707
0708
0709
0710
0711
0712
0713
0714
0715
0716
0717
0718
0719
0720
0721
0722
0723
0724
0725
0726
0727
0728
0729
0730
0731
0732
0733
0734
0735
0736
0737
0738
0739
0740
0741
0742
0743
0744
0745
0746
0747
0748
0749
0750
0751
0752
0753
0754
0755
0756
0757
0758
0759
0760
0761
0762
0763
0764
0765
0766
0767
0768
0769
0770
0771
0772
0773
0774
0775
0776
0777
0778
0779
0780
0781
0782
0783
0784
0785
0786
0787
0788
0789
0790
0791
0792
0793
0794
0795
0796
0797
0798
0799
0800
0801
0802
0803
0804
0805
0806
0807
0808
0809
0810
0811
0812
0813
0814
0815
0816
0817
0818
0819
0820
0821
0822
0823
0824
0825
0826
0827
0828
0829
0830
0831
0832
0833
0834
0835
0836
0837
0838
0839
0840
0841
0842
0843
0844
0845
0846
0847
0848
0849
0850
0851
0852
0853
0854
0855
0856
0857
0858
0859
0860
0861
0862
0863
0864
0865
0866
0867
0868
0869
0870
0871
0872
0873
0874
0875
0876
0877
0878
0879
0880
0881
0882
0883
0884
0885
0886
0887
0888
0889
0890
0891
0892
0893
0894
0895
0896
0897
0898
0899
0900
0901
0902
0903
0904
0905
0906
0907
0908
0909
0910
0911
0912
0913
0914
0915
0916
0917
0918
0919
0920
0921
0922
0923
0924
0925
0926
0927
0928
0929
0930
0931
0932
0933
0934
0935
0936
0937
0938
0939
0940
0941
0942
0943
0944
0945
0946
0947
0948
0949
0950
0951
0952
0953
0954
0955
0956
0957
0958
0959
0960
0961
0962
0963
0964
0965
0966
0967
0968
0969
0970
0971
0972
0973
0974
0975
0976
0977
0978
0979
0980
0981
0982
0983
0984
0985
0986
0987
0988
0989
0990
0991
0992
0993
0994
0995
0996
0997
0998
0999
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
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
import tkinter as tk
from tkinter import ttk, messagebox, Toplevel
import time
import threading
import sys
import os
import platform
from typing import Optional, List, Set, Callable, Any, Tuple, Union, Dict
import traceback
import json
from pathlib import Path
 
# --- Type Hinting Setup (Forward References) ---
# Attempt to define types early for hinting, handle ImportError later
try:
    from pynput.keyboard import Key, KeyCode
    from pynput.mouse import Button
    PynputKeyType = Union[Key, KeyCode, Button]
    # Optional imports for tray
    try:
        import pystray
        from PIL import Image, ImageDraw
    except ImportError:
        pystray = None
        Image, ImageDraw = None, None
except ImportError:
    # Define dummy types if pynput not installed yet
    class Key: pass
    class KeyCode: pass
    class Button: pass
    pystray = None # Ensure these are None if pynput fails
    Image, ImageDraw = None, None
    PynputKeyType = Union[Any]
 
# --- Global Controllers Placeholder ---
# Initialized in main block after successful import
mouse_controller: Optional['MouseController'] = None
keyboard_controller: Optional['KeyboardController'] = None
 
# --- Constants ---
DEFAULT_AUTOMATION_KEYS = 6
MAX_AUTOMATION_KEYS = 50
APP_NAME = "AdvancedAutoClicker" # Used for config directory
CONFIG_FILENAME = "config.json"
 
# --- Configuration Path Helper Functions ---
def get_config_dir() -> Path:
    """Gets the platform-specific configuration directory."""
    system = platform.system()
    app_name_safe = APP_NAME.replace(" ", "_")
    try:
        if system == "Windows":
            path_str = os.getenv('APPDATA') or os.getenv('LOCALAPPDATA') or os.path.expanduser('~')
            base_path = Path(path_str)
            if path_str == os.path.expanduser('~'): # Fallback case
                 app_name_safe = "." + app_name_safe
        elif system == "Darwin": # macOS
            base_path = Path.home() / "Library" / "Application Support"
        else: # Linux and other Unix-like (XDG)
            xdg_config_home = os.getenv('XDG_CONFIG_HOME')
            base_path = Path(xdg_config_home) if xdg_config_home else Path.home() / ".config"
        config_dir = base_path / app_name_safe
        return config_dir
    except Exception as e:
        print(f"Error determining config directory, falling back to current: {e}")
        return Path(".") / f".{app_name_safe}_config" # Fallback
 
def get_config_path() -> Path:
    """Gets the full path to the configuration file, ensuring directory exists."""
    config_dir = get_config_dir()
    try:
        config_dir.mkdir(parents=True, exist_ok=True)
    except OSError as e:
        print(f"Warning: Could not create config directory '{config_dir}': {e}")
        return Path(CONFIG_FILENAME) # Fallback
    except Exception as e:
       print(f"Unexpected error creating config directory '{config_dir}': {e}")
       return Path(CONFIG_FILENAME)
    return config_dir / CONFIG_FILENAME
 
# --- Application Class ---
class AutoClickerApp:
    """
    Main application class for the Advanced Auto-Clicker.
    Version 2.6.2: Added minimize-to-tray on start, restore on stop. Compacted UI.
    """
 
    def __init__(self, root: tk.Tk):
        self.root = root
        self.system_name = platform.system() # Store system name ONCE as instance attribute
        self.root.title(f"高级连点器 v2.6.2 - 开源免费")
        self.root.resizable(True, True)
 
        # Ensure pynput controllers are initialized (handled in main block)
        global mouse_controller, keyboard_controller
        if mouse_controller is None or keyboard_controller is None:
            messagebox.showerror("初始化错误", "输入控制器未能正确初始化。", parent=self.root)
            self.root.after(50, self.root.destroy)
            raise RuntimeError("Input controllers not initialized")
 
        # --- State Variables (Defaults are fallbacks) ---
        self.click_interval = tk.DoubleVar(value=0.01)
        self.status_text = tk.StringVar(value="状态: 初始化中...")
        self.is_capturing = False
        self._shutting_down = False
        # NEW: Flag to track if window was hidden by automation start
        self.window_hidden_by_automation = False
 
        # Mouse State
        self.selected_click_type = tk.StringVar(value="left")
        self.mouse_hotkey_str = tk.StringVar(value="Key.f8")
        self.parsed_mouse_hotkey: Optional[Set[PynputKeyType]] = set()
        self.is_running_mouse = False
        self.mouse_click_thread: Optional[threading.Thread] = None
        self.mouse_stop_event = threading.Event()
        self.mouse_duration = tk.DoubleVar(value=0.0)
        self.mouse_duration_after_id: Optional[str] = None
 
        # Keyboard State (Dynamic Rows)
        self.keyboard_target_keys: List[tk.StringVar] = []
        self.keyboard_target_delays: List[tk.DoubleVar] = []
        self.valid_target_key_objects: List[Tuple[PynputKeyType, float]] = [] # Validated keys
        self.keyboard_hotkey_str = tk.StringVar(value="Key.f7")
        self.parsed_keyboard_hotkey: Optional[Set[PynputKeyType]] = set()
        self.keyboard_mode = tk.StringVar(value="sequential")
        self.keyboard_cycle_delay = tk.DoubleVar(value=0.1)
        self.is_running_keyboard = False
        self.keyboard_thread: Optional[threading.Thread] = None
        self.keyboard_stop_event = threading.Event()
        self.keyboard_duration = tk.DoubleVar(value=0.0)
        self.keyboard_duration_after_id: Optional[str] = None
        self.current_key_row_count = 0
 
        # Hotkey Listener State
        self.hotkey_listener_thread: Optional[threading.Thread] = None
        self.hotkey_stop_event = threading.Event()
        self.current_pressed_keys: Set[PynputKeyType] = set()
        self._listener_keyboard_instance: Optional['KeyboardListener'] = None
        self._listener_mouse_instance: Optional['MouseListener'] = None
 
        # System Tray State
        self.tray_icon: Optional['pystray.Icon'] = None
        self.tray_thread: Optional[threading.Thread] = None
 
        # --- Widget References (Initialized to None) ---
        # (These provide access to UI elements)
        self.status_label = None
        self.interval_entry = None
        self.click_type_radios = []
        self.mouse_hotkey_entry = None
        self.mouse_hotkey_capture_button = None
        self.mouse_hotkey_apply_button = None
        self.mouse_side_button_x1 = None
        self.mouse_side_button_x2 = None
        self.mouse_duration_entry = None
        self.mouse_duration_label = None
        self.mouse_duration_unit_label = None
        self.mouse_start_button = None
        self.mouse_stop_button = None
        self.keyboard_hotkey_entry = None
        self.keyboard_hotkey_capture_button = None
        self.keyboard_hotkey_apply_button = None
        self.keyboard_side_button_x1 = None
        self.keyboard_side_button_x2 = None
        self.key_row_frames = []
        self.key_entries = []
        self.key_capture_buttons = []
        self.key_apply_buttons = []
        self.key_delay_entries = []
        self.key_delay_labels = []
        self.keyboard_mode_radios = []
        self.cycle_delay_label = None
        self.cycle_delay_entry = None
        self.cycle_delay_unit_label = None
        self.keyboard_duration_entry = None
        self.keyboard_duration_label = None
        self.keyboard_duration_unit_label = None
        self.keyboard_start_button = None
        self.keyboard_stop_button = None
        self.keys_canvas = None
        self.scrollable_frame = None
        self.key_list_frame = None
        self.add_key_button = None
        self.remove_key_button = None
 
        # --- Initialization Steps ---
        self.setup_gui() # Create widgets first
        self.load_config() # Load settings, potentially populate rows
        self._parse_initial_hotkeys() # Parse hotkeys based on loaded/default strings
        self.setup_tray() # Setup tray icon if possible
        self.root.protocol("WM_DELETE_WINDOW", self.on_close_requested) # Set close behaviour
        self.root.after(200, self.start_hotkey_listener) # Start listening for hotkeys
        self.root.after(50, self.update_ui_state) # Set initial UI element states
        if self.status_text.get() == "状态: 初始化中...":
             self.status_text.set("状态: 已停止") # Final default status
 
 
    def _parse_initial_hotkeys(self):
        """Parses hotkeys from string vars after config load."""
        if 'Key' not in globals(): # Check if pynput types are available
            print("Warning: Pynput classes not loaded, cannot parse initial hotkeys.")
            self.parsed_mouse_hotkey = set()
            self.parsed_keyboard_hotkey = set()
            return
 
        try:
            self.parsed_mouse_hotkey = self.parse_hotkey_str(self.mouse_hotkey_str.get())
        except (ValueError, RuntimeError) as e:
            print(f"Warning: Invalid initial mouse hotkey '{self.mouse_hotkey_str.get()}': {e}")
            self.mouse_hotkey_str.set("") # Clear invalid value from UI
            self.parsed_mouse_hotkey = set()
 
        try:
            self.parsed_keyboard_hotkey = self.parse_hotkey_str(self.keyboard_hotkey_str.get())
        except (ValueError, RuntimeError) as e:
            print(f"Warning: Invalid initial keyboard hotkey '{self.keyboard_hotkey_str.get()}': {e}")
            self.keyboard_hotkey_str.set("") # Clear invalid value from UI
            self.parsed_keyboard_hotkey = set()
 
 
    # --- GUI Setup Methods ---
    def setup_gui(self):
        """Sets up the main GUI structure (notebook, tabs, status bar)."""
        # Reduced main frame padding
        main_frame = ttk.Frame(self.root, padding="5")
        main_frame.grid(row=0, column=0, sticky="nsew") # Use nsew
        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)
 
        notebook = ttk.Notebook(main_frame)
        # Reduced notebook padding
        notebook.grid(row=0, column=0, sticky="nsew", pady=3)
        main_frame.columnconfigure(0, weight=1)
        main_frame.rowconfigure(0, weight=1)
 
        # Reduced tab padding
        mouse_tab = ttk.Frame(notebook, padding="5")
        keyboard_tab = ttk.Frame(notebook, padding="5")
 
        # Configure tab resizing weights
        mouse_tab.columnconfigure(1, weight=1)
        keyboard_tab.columnconfigure(0, weight=1)
        keyboard_tab.rowconfigure(1, weight=1) # Key list area vertical expand
 
        notebook.add(mouse_tab, text='鼠标连点')
        notebook.add(keyboard_tab, text='键盘自动化')
 
        # Reduced minsize for compactness
        self.root.minsize(400, 300)
 
        # Populate tabs with widgets (structure only for keyboard)
        self.setup_mouse_tab(mouse_tab)
        self.setup_keyboard_tab(keyboard_tab)
 
        # Setup Status Bar
        self.status_label = ttk.Label(main_frame, textvariable=self.status_text, relief=tk.SUNKEN, anchor=tk.W)
        # Reduced status bar padding
        self.status_label.grid(row=1, column=0, sticky="ew", pady=(3, 0))
 
 
    def setup_mouse_tab(self, tab: ttk.Frame):
        """Sets up the widgets for the Mouse Clicker tab."""
        # Row 0: Settings
        settings_frame = ttk.Frame(tab)
        # Reduced settings frame padding
        settings_frame.grid(row=0, column=0, columnspan=2, sticky="ew", pady=3)
        settings_frame.columnconfigure(1, weight=1)
 
        # Reduced LabelFrame padding
        interval_frame = ttk.LabelFrame(settings_frame, text="鼠标连点设置", padding="3")
        interval_frame.pack(side=tk.LEFT, padx=(0, 3), fill=tk.X, expand=True)
        # Reduced internal padding
        ttk.Label(interval_frame, text="间隔:").grid(row=0, column=0, sticky=tk.W, padx=1)
        vcmd_interval = (self.root.register(self.validate_interval), '%P')
        self.interval_entry = ttk.Entry(interval_frame, textvariable=self.click_interval, width=5, validate="key", validatecommand=vcmd_interval)
        self.interval_entry.grid(row=0, column=1, sticky=tk.W, padx=1)
        ttk.Label(interval_frame, text="秒 (≥0.01)").grid(row=0, column=2, sticky=tk.W, padx=1)
 
        # Reduced LabelFrame padding
        click_type_frame = ttk.LabelFrame(settings_frame, text="类型", padding="3")
        click_type_frame.pack(side=tk.LEFT, padx=(3, 0), fill=tk.X, expand=True)
        self.click_type_radios = []
        types = [("左键", "left"), ("中键", "middle"), ("右键", "right")]
        for txt, val in types:
            rb = ttk.Radiobutton(click_type_frame, text=txt, variable=self.selected_click_type, value=val)
            # Reduced radio button padding
            rb.pack(side=tk.LEFT, padx=2)
            self.click_type_radios.append(rb)
 
        # Row 1: Hotkey
        # Reduced LabelFrame padding
        m_hotkey_frame = ttk.LabelFrame(tab, text="鼠标连点 启动/停止 热键(支持组合键但部分无法识别,连点功能未做游戏界面内通用测试,请自行尝试,间隔较短时热键停止可能反应不灵敏并不是失效可重试)", padding="5")
        # Reduced grid padding
        m_hotkey_frame.grid(row=1, column=0, columnspan=2, sticky="ew", pady=3)
        m_hotkey_frame.columnconfigure(1, weight=1)
 
        # Reduced internal padding
        ttk.Label(m_hotkey_frame, text="热键:").grid(row=0, column=0, sticky=tk.W, padx=3, pady=1)
        self.mouse_hotkey_entry = ttk.Entry(m_hotkey_frame, textvariable=self.mouse_hotkey_str, width=20)
        self.mouse_hotkey_entry.grid(row=0, column=1, sticky="ew", padx=3, pady=1)
        btn_frame_hk = ttk.Frame(m_hotkey_frame)
        btn_frame_hk.grid(row=0, column=2, sticky=tk.E, padx=3, pady=1)
        self.mouse_hotkey_capture_button = ttk.Button(btn_frame_hk, text="采集", command=lambda: self.open_capture_dialog('mouse'), width=5)
        self.mouse_hotkey_capture_button.pack(side=tk.LEFT, padx=(0, 2))
        self.mouse_hotkey_apply_button = ttk.Button(btn_frame_hk, text="应用", command=lambda: self.apply_hotkey('mouse'), width=5)
        self.mouse_hotkey_apply_button.pack(side=tk.LEFT)
 
        # Side Button shortcuts
        side_btn_frame = ttk.Frame(m_hotkey_frame)
        # Reduced grid padding
        side_btn_frame.grid(row=1, column=0, columnspan=3, sticky=tk.W, pady=(3, 0))
        # Reduced internal padding
        ttk.Label(side_btn_frame, text="快捷应用鼠标侧键:").pack(side=tk.LEFT, padx=3)
        if 'Button' in globals() and hasattr(Button, 'x1'):
            self.mouse_side_button_x1 = ttk.Button(side_btn_frame, text="侧键1", command=lambda: self.apply_specific_hotkey('mouse', Button.x1))
            self.mouse_side_button_x1.pack(side=tk.LEFT, padx=(0, 2))
            self.mouse_side_button_x2 = ttk.Button(side_btn_frame, text="侧键2", command=lambda: self.apply_specific_hotkey('mouse', Button.x2))
            self.mouse_side_button_x2.pack(side=tk.LEFT)
        else:
            print("Warning: pynput.mouse.Button not available for side button widgets.")
 
        # Reduced padding
        ttk.Label(m_hotkey_frame, text="格式: 'a', Key.f8, Button.x1, Key.ctrl_l + 'c' (建议用单一按键,部分组合键无法正常采集和识别。不会输入的点击采集键盘后按下需要的热键)", font=("", 8)).grid(row=2, column=0, columnspan=3, sticky=tk.W, padx=3, pady=(1, 0))
 
        # Row 2: Duration & Controls
        bottom_frame = ttk.Frame(tab)
        # Reduced grid padding
        bottom_frame.grid(row=2, column=0, columnspan=2, sticky="ew", pady=3)
        bottom_frame.columnconfigure(0, weight=1)
 
        # Reduced LabelFrame padding
        m_duration_frame = ttk.LabelFrame(bottom_frame, text="持续时间", padding="3")
        m_duration_frame.pack(side=tk.LEFT, padx=(0, 3), fill=tk.X, expand=True)
        self.mouse_duration_label = ttk.Label(m_duration_frame, text="持续:")
        # Reduced internal padding
        self.mouse_duration_label.grid(row=0, column=0, sticky=tk.W, padx=1)
        vcmd_pos_float = (self.root.register(self.validate_positive_float), '%P')
        self.mouse_duration_entry = ttk.Entry(m_duration_frame, textvariable=self.mouse_duration, width=5, validate="key", validatecommand=vcmd_pos_float)
        self.mouse_duration_entry.grid(row=0, column=1, sticky=tk.W, padx=1)
        self.mouse_duration_unit_label = ttk.Label(m_duration_frame, text="秒 (0=无限)")
        self.mouse_duration_unit_label.grid(row=0, column=2, sticky=tk.W, padx=1)
 
        # Reduced padding
        m_control_frame = ttk.Frame(bottom_frame, padding="3 0 0 0")
        m_control_frame.pack(side=tk.LEFT, padx=(3, 0))
        self.mouse_start_button = ttk.Button(m_control_frame, text="启动", command=self.toggle_clicking)
        self.mouse_start_button.pack(side=tk.LEFT, padx=(0, 3))
        self.mouse_stop_button = ttk.Button(m_control_frame, text="停止", command=self.stop_clicking, state=tk.DISABLED)
        self.mouse_stop_button.pack(side=tk.LEFT)
 
    def setup_keyboard_tab(self, tab: ttk.Frame):
        """Sets up the widgets for the Keyboard Automation tab.
            Creates the structure including the scrollable area for dynamic rows.
            Actual row population is handled by load_config.
        """
        # Row 0: Hotkey Settings
        # Reduced LabelFrame padding
        k_hotkey_frame = ttk.LabelFrame(tab, text="键盘自动化 启动/停止 热键(支持组合键但部分无法识别,连点功能未做游戏界面内通用测试,请自行尝试,间隔较短时热键停止可能反应不灵敏并不是失效可重试)", padding="5")
        # Reduced grid padding
        k_hotkey_frame.grid(row=0, column=0, sticky="ew", pady=3)
        k_hotkey_frame.columnconfigure(1, weight=1) # Let entry expand
 
        # Reduced internal padding
        ttk.Label(k_hotkey_frame, text="热键:").grid(row=0, column=0, sticky=tk.W, padx=3, pady=1)
        self.keyboard_hotkey_entry = ttk.Entry(k_hotkey_frame, textvariable=self.keyboard_hotkey_str, width=20)
        self.keyboard_hotkey_entry.grid(row=0, column=1, sticky="ew", padx=3, pady=1)
        k_btn_frame_hk = ttk.Frame(k_hotkey_frame)
        k_btn_frame_hk.grid(row=0, column=2, sticky=tk.E, padx=3, pady=1)
        self.keyboard_hotkey_capture_button = ttk.Button(k_btn_frame_hk, text="采集", command=lambda: self.open_capture_dialog('keyboard'), width=5)
        self.keyboard_hotkey_capture_button.pack(side=tk.LEFT, padx=(0, 2))
        self.keyboard_hotkey_apply_button = ttk.Button(k_btn_frame_hk, text="应用", command=lambda: self.apply_hotkey('keyboard'), width=5)
        self.keyboard_hotkey_apply_button.pack(side=tk.LEFT)
 
        # Side Button shortcuts
        k_side_btn_frame = ttk.Frame(k_hotkey_frame)
        # Reduced grid padding
        k_side_btn_frame.grid(row=1, column=0, columnspan=3, sticky=tk.W, pady=(3, 0))
        # Reduced internal padding
        ttk.Label(k_side_btn_frame, text="快捷应用侧键:").pack(side=tk.LEFT, padx=3)
        if 'Button' in globals() and hasattr(Button, 'x1'): # Check robustly
            self.keyboard_side_button_x1 = ttk.Button(k_side_btn_frame, text="侧键1", command=lambda: self.apply_specific_hotkey('keyboard', Button.x1))
            self.keyboard_side_button_x1.pack(side=tk.LEFT, padx=(0, 2))
            self.keyboard_side_button_x2 = ttk.Button(k_side_btn_frame, text="侧键2", command=lambda: self.apply_specific_hotkey('keyboard', Button.x2))
            self.keyboard_side_button_x2.pack(side=tk.LEFT)
        else: print("Warning: Mouse side buttons (X1/X2) not available for keyboard hotkey.")
 
        # Reduced padding
        ttk.Label(k_hotkey_frame, text="格式: 'a', Key.f8, Button.x1, Key.ctrl_l + 'c' (建议用单一按键,部分组合键无法正常采集和识别。不会输入的点击采集键盘后按下需要的热键)", font=("", 8)).grid(row=2, column=0, columnspan=3, sticky=tk.W, padx=3, pady=(1, 0))
 
        # --- Row 1: Scrollable Target Keys List ---
        # Reduced LabelFrame padding
        self.key_list_frame = ttk.LabelFrame(tab, text="自动化按键列表 (可增减)", padding="5")
        # Reduced grid padding
        self.key_list_frame.grid(row=1, column=0, sticky="nsew", pady=3) # Use nsew
        # Configure resizing for this frame within the tab
        self.key_list_frame.rowconfigure(1, weight=1) # Canvas expands vertically
        self.key_list_frame.columnconfigure(0, weight=1) # Canvas expands horizontally
 
        # Info label above list
        info_frame = ttk.Frame(self.key_list_frame)
        # Reduced padding
        info_frame.grid(row=0, column=0, columnspan=2, sticky="ew", pady=(0, 3))
        # Reduced padding
        ttk.Label(info_frame, text="添加要按下(循环/依次)的 单个 键盘/鼠标 按键:", font=("", 9)).pack(side=tk.LEFT, padx=3)
        # Numpad warning removed
        # Reduced padding
        ttk.Label(info_frame, text="格式: 'a', Key.enter, Button.left, Key.numpad1 (不支持组合键,num打开后小数字键盘无法识别)", font=("", 8)).pack(side=tk.LEFT, padx=3)
 
        # Canvas and Scrollbar Setup
        self.keys_canvas = tk.Canvas(self.key_list_frame, borderwidth=0, highlightthickness=0)
        keys_scrollbar = ttk.Scrollbar(self.key_list_frame, orient="vertical", command=self.keys_canvas.yview)
        self.scrollable_frame = ttk.Frame(self.keys_canvas) # Holds the actual key rows
 
        # Configure canvas scrolling
        self.scrollable_frame.bind("<Configure>", lambda e: self.update_canvas_scrollregion())
        self.scrollable_frame.columnconfigure(0, weight=1) # Allow rows to expand width
        canvas_window = self.keys_canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw", tags="frame")
 
        def _configure_frame_width(event):
            """Ensures the frame inside the canvas tracks the canvas width."""
            if self.keys_canvas and self.scrollable_frame:
                self.keys_canvas.itemconfig(canvas_window, width=event.width)
 
        self.keys_canvas.bind("<Configure>", _configure_frame_width, add='+')
        self.keys_canvas.configure(yscrollcommand=keys_scrollbar.set)
 
        # Place canvas and scrollbar
        self.keys_canvas.grid(row=1, column=0, sticky="nsew")
        keys_scrollbar.grid(row=1, column=1, sticky="ns")
 
        # --- Mousewheel Binding Logic (Uses self.system_name) ---
        # Define the scroll handler nested here to capture 'self'
        def _on_mousewheel(event):
            if not self.keys_canvas: return
            delta = 0
            local_system = self.system_name # Use instance attribute
            try:
                if local_system == "Linux":
                    if event.num == 4: delta = -1
                    elif event.num == 5: delta = 1
                elif local_system == "Windows":
                    delta_val = getattr(event, 'delta', 0)
                    delta = -1 if delta_val > 0 else (1 if delta_val < 0 else 0)
                elif local_system == "Darwin": # macOS
                    delta_val = getattr(event, 'delta', 0)
                    delta = -int(delta_val) if delta_val != 0 else 0
                else: # Fallback
                    if hasattr(event, 'delta') and event.delta != 0:
                        delta = -1 if event.delta > 0 else 1
            except AttributeError as e: print(f"Scroll event missing attrs: {e}"); delta = 0
            except Exception as e: print(f"Error processing scroll delta: {e}"); delta = 0
 
            if delta != 0:
                try:
                    self.keys_canvas.yview_scroll(int(delta * 1), "units")
                except tk.TclError: pass # Ignore scroll errors if canvas is busy/destroyed
 
        # Recursive binding function also nested or made instance method
        def bind_recursive_scroll(widget):
            """Binds mouse wheel scrolling recursively to widget and children."""
            if self.system_name == "Linux": # Use instance attribute
                widget.bind("<Button-4>", _on_mousewheel, add='+')
                widget.bind("<Button-5>", _on_mousewheel, add='+')
            else:
                widget.bind("<MouseWheel>", _on_mousewheel, add='+')
            # Ensure focus can be set for scrolling when mouse enters
            widget.bind("<Enter>", lambda e, w=widget: w.focus_set(), add='+')
            for child in widget.winfo_children():
                bind_recursive_scroll(child)
 
        # Bind initially to canvas and the frame inside it
        widgets_to_bind_scroll = [self.keys_canvas, self.scrollable_frame]
        for widget in widgets_to_bind_scroll:
            if widget: # Ensure widget exists
                bind_recursive_scroll(widget)
 
        # Schedule a re-bind after a delay. This helps catch dynamically added rows
        # when add_key_row is called later (e.g., by load_config or user action).
        self.root.after(500, lambda: bind_recursive_scroll(self.scrollable_frame) if self.scrollable_frame else None)
 
        # --- Row 2: Add/Remove Buttons ---
        key_control_frame = ttk.Frame(self.key_list_frame)
        # Reduced grid padding
        key_control_frame.grid(row=2, column=0, columnspan=2, sticky="ew", pady=(3, 0))
        self.add_key_button = ttk.Button(key_control_frame, text="增加按键 (+)", command=self.add_key_row)
        # Reduced pack padding
        self.add_key_button.pack(side=tk.LEFT, padx=3)
        self.remove_key_button = ttk.Button(key_control_frame, text="移除末尾按键 (-)", command=self.remove_key_row)
        # Reduced pack padding
        self.remove_key_button.pack(side=tk.LEFT, padx=3)
        # Button states set by update_ui_state after load_config
 
        # --- Row 3: Keyboard Mode and Cycle Delay ---
        # Reduced LabelFrame padding
        mode_frame = ttk.LabelFrame(tab, text="执行方式 & 循环延迟", padding="5")
        # Reduced grid padding
        mode_frame.grid(row=2, column=0, sticky="ew", pady=3)
        mode_frame.columnconfigure(1, weight=0) # Keep columns fixed size unless needed
 
        # Mode radios
        self.keyboard_mode_radios = []
        modes = [("依次按下", "sequential"), ("同时按下", "simultaneous")]
        for i, (txt, val) in enumerate(modes):
            rb = ttk.Radiobutton(mode_frame, text=txt, variable=self.keyboard_mode, value=val, command=self.update_ui_state)
            # Reduced grid padding
            rb.grid(row=0, column=i, sticky=tk.W, padx=3, pady=1)
            self.keyboard_mode_radios.append(rb)
        # Optional info label for simultaneous mode
        # Reduced grid padding
        ttk.Label(mode_frame, text="(同时按下: 如果设置间隔极短而且按键较多可能卡死或者导致无法识别到停止热键)", font=("", 8)).grid(row=0, column=len(modes), sticky=tk.W, padx=5)
 
 
        # Cycle delay
        self.cycle_delay_label = ttk.Label(mode_frame, text="循环间隔:")
        # Reduced grid padding
        self.cycle_delay_label.grid(row=1, column=0, sticky=tk.W, padx=3, pady=3)
        vcmd_delay = (self.root.register(self.validate_positive_float), '%P')
        self.cycle_delay_entry = ttk.Entry(mode_frame, textvariable=self.keyboard_cycle_delay, width=5, validate="key", validatecommand=vcmd_delay)
        # Reduced grid padding
        self.cycle_delay_entry.grid(row=1, column=1, sticky=tk.W, padx=3, pady=3)
        self.cycle_delay_unit_label = ttk.Label(mode_frame, text="秒 (≥0)")
        # Reduced grid padding
        self.cycle_delay_unit_label.grid(row=1, column=2, sticky=tk.W, padx=3, pady=3, columnspan=len(modes)-1) # Span remaining columns
 
        # --- Row 4: Duration & Controls ---
        bottom_frame_kb = ttk.Frame(tab)
        # Reduced grid padding
        bottom_frame_kb.grid(row=3, column=0, sticky="ew", pady=3)
        bottom_frame_kb.columnconfigure(0, weight=1)
 
        # Reduced LabelFrame padding
        k_duration_frame = ttk.LabelFrame(bottom_frame_kb, text="持续时间", padding="3")
        k_duration_frame.pack(side=tk.LEFT, padx=(0, 3), fill=tk.X, expand=True)
        self.keyboard_duration_label = ttk.Label(k_duration_frame, text="持续:")
        # Reduced internal padding
        self.keyboard_duration_label.grid(row=0, column=0, sticky=tk.W, padx=1)
        vcmd_pos_float_kb = (self.root.register(self.validate_positive_float), '%P')
        self.keyboard_duration_entry = ttk.Entry(k_duration_frame, textvariable=self.keyboard_duration, width=5, validate="key", validatecommand=vcmd_pos_float_kb)
        self.keyboard_duration_entry.grid(row=0, column=1, sticky=tk.W, padx=1)
        self.keyboard_duration_unit_label = ttk.Label(k_duration_frame, text="秒 (0=无限)")
        self.keyboard_duration_unit_label.grid(row=0, column=2, sticky=tk.W, padx=1)
 
        # Reduced padding
        k_control_frame = ttk.Frame(bottom_frame_kb, padding="3 0 0 0")
        k_control_frame.pack(side=tk.LEFT, padx=(3, 0))
        self.keyboard_start_button = ttk.Button(k_control_frame, text="启动", command=self.toggle_keyboard_automation)
        self.keyboard_start_button.pack(side=tk.LEFT, padx=(0, 3))
        self.keyboard_stop_button = ttk.Button(k_control_frame, text="停止", command=self.stop_keyboard_automation, state=tk.DISABLED)
        self.keyboard_stop_button.pack(side=tk.LEFT)
 
 
    # --- Dynamic Key Row Handling ---
    def _clear_key_rows(self):
        """Removes all dynamic key rows and clears associated data lists."""
        print("Clearing dynamic key rows...")
        if not self.scrollable_frame or not hasattr(self, 'key_row_frames'):
            return
 
        # Destroy widgets safely
        widgets_to_destroy = list(self.key_row_frames)
        for frame in widgets_to_destroy:
            if frame and frame.winfo_exists():
                try: frame.destroy()
                except tk.TclError: pass
                except Exception as e: print(f"Unexpected error destroying frame: {e}")
 
        # Clear data lists
        self.key_row_frames.clear()
        self.keyboard_target_keys.clear()
        self.keyboard_target_delays.clear()
        self.key_entries.clear()
        self.key_capture_buttons.clear()
        self.key_apply_buttons.clear()
        self.key_delay_entries.clear()
        self.key_delay_labels.clear()
        self.current_key_row_count = 0
        self.valid_target_key_objects = []
 
        # Update UI after clearing
        self.update_add_remove_button_state()
        self.root.after(20, self.update_canvas_scrollregion)
 
 
    def add_key_row(self, key_value: str = "", delay_value: float = 0.0, update_scroll: bool = True):
        """Adds a new row for keyboard automation key entry, optionally setting initial values."""
        if self.current_key_row_count >= MAX_AUTOMATION_KEYS:
            messagebox.showwarning("达到上限", f"最多只能添加 {MAX_AUTOMATION_KEYS} 个自动化按键。", parent=self.root)
            return
 
        index = self.current_key_row_count
        if not self.scrollable_frame:
            print("Error: scrollable_frame not initialized, cannot add key row.")
            return
 
        # Create the frame for the row inside the scrollable area
        row_frame = ttk.Frame(self.scrollable_frame)
        # Reduced grid padding
        row_frame.grid(row=index, column=0, sticky="ew", pady=1, padx=1)
        row_frame.columnconfigure(1, weight=1) # Key entry expands
 
        # Variables for this row
        key_var = tk.StringVar(value=key_value)
        delay_var = tk.DoubleVar(value=delay_value)
        self.keyboard_target_keys.append(key_var)
        self.keyboard_target_delays.append(delay_var)
 
        # Widgets for this row
        # Reduced internal padding
        ttk.Label(row_frame, text=f"按键 {index + 1}:", width=7).grid(row=0, column=0, padx=(3,0), sticky=tk.W)
 
        entry = ttk.Entry(row_frame, textvariable=key_var, width=15)
        # Reduced internal padding
        entry.grid(row=0, column=1, padx=3, sticky="ew")
        self.key_entries.append(entry)
 
        btn_sub_frame = ttk.Frame(row_frame)
        # Reduced internal padding
        btn_sub_frame.grid(row=0, column=2, padx=0, sticky=tk.W)
 
        # Use lambda with default idx=index to capture correct index for callbacks
        capture_btn = ttk.Button(btn_sub_frame, text="采集", width=5, command=lambda idx=index: self.open_capture_dialog('target_key', index=idx))
        capture_btn.pack(side=tk.LEFT, padx=(0, 2))
        self.key_capture_buttons.append(capture_btn)
 
        apply_btn = ttk.Button(btn_sub_frame, text="应用", width=5, command=lambda idx=index: self._apply_target_key(idx))
        apply_btn.pack(side=tk.LEFT)
        self.key_apply_buttons.append(apply_btn)
 
        # Post-Key Delay Entry and Label
        vcmd_pos_float = (self.root.register(self.validate_positive_float), '%P')
        delay_entry = ttk.Entry(row_frame, textvariable=delay_var, width=4, validate="key", validatecommand=vcmd_pos_float)
        # Reduced internal padding
        delay_entry.grid(row=0, column=3, padx=(5, 0), sticky=tk.W)
        self.key_delay_entries.append(delay_entry)
 
        delay_label = ttk.Label(row_frame, text="秒后置")
        # Reduced internal padding
        delay_label.grid(row=0, column=4, padx=(1, 3), sticky=tk.W)
        self.key_delay_labels.append(delay_label)
 
        # Store references and increment count
        self.key_row_frames.append(row_frame)
        self.current_key_row_count += 1
 
        # Update UI states
        self.update_add_remove_button_state()
        self.update_ui_state() # Ensures delay widgets enabled/disabled correctly
 
        # Update scroll region and scroll down if requested
        if update_scroll and self.keys_canvas:
            self.keys_canvas.after(20, self.update_canvas_scrollregion)
            self.keys_canvas.after(60, lambda: self.keys_canvas.yview_moveto(1.0) if self.keys_canvas else None)
 
        # NOTE: The direct binding of mousewheel events to the new row_frame
        # that previously caused the NameError HAS BEEN REMOVED here.
        # We rely on the scheduled recursive rebind in setup_keyboard_tab
        # to handle scrolling for newly added rows.
 
 
    def remove_key_row(self):
        """Removes the last keyboard automation key entry row."""
        if self.current_key_row_count <= 0: return
        if not self.scrollable_frame: return
 
        index_to_remove = self.current_key_row_count - 1
 
        # Consistency check before list access
        if index_to_remove >= len(self.key_row_frames):
            print(f"Error: Row index {index_to_remove} out of sync. Adjusting.")
            self.current_key_row_count = len(self.key_row_frames)
            if self.current_key_row_count <= 0: return
            index_to_remove = self.current_key_row_count - 1
 
        # Destroy row frame widgets
        try:
            if index_to_remove < len(self.key_row_frames) and self.key_row_frames[index_to_remove].winfo_exists():
                self.key_row_frames[index_to_remove].destroy()
        except Exception as e:
            print(f"Warning: Error destroying key row frame {index_to_remove}: {e}")
 
        # Safely pop data from lists using the index
        def safe_pop(lst, index, name):
            if index < len(lst): return lst.pop(index)
            print(f"Error: Index {index} out of bounds for '{name}' during pop.")
            return None
 
        safe_pop(self.key_row_frames, index_to_remove, "frames")
        safe_pop(self.keyboard_target_keys, index_to_remove, "keys")
        safe_pop(self.keyboard_target_delays, index_to_remove, "delays")
        safe_pop(self.key_entries, index_to_remove, "entries")
        safe_pop(self.key_capture_buttons, index_to_remove, "cap_btns")
        safe_pop(self.key_apply_buttons, index_to_remove, "app_btns")
        safe_pop(self.key_delay_entries, index_to_remove, "delay_entries")
        safe_pop(self.key_delay_labels, index_to_remove, "delay_labels")
 
        self.current_key_row_count -= 1
        if self.current_key_row_count < 0: self.current_key_row_count = 0 # Ensure non-negative
 
        # Update UI states
        self.update_add_remove_button_state()
        self.update_ui_state()
        if self.keys_canvas:
            self.keys_canvas.after(20, self.update_canvas_scrollregion)
 
# --- UI Update Helpers ---
    def update_canvas_scrollregion(self):
        """Updates the scrollregion of the keys_canvas."""
        if self.keys_canvas and self.scrollable_frame and self.keys_canvas.winfo_exists() and self.scrollable_frame.winfo_exists():
            try:
                self.scrollable_frame.update_idletasks()
                self.keys_canvas.update_idletasks()
                bbox = self.keys_canvas.bbox("all")
                # Use scrollable_frame's required height for accurate region
                required_height = self.scrollable_frame.winfo_reqheight()
                required_width = self.scrollable_frame.winfo_reqwidth() # Or canvas width if frame should fill
                canvas_width = self.keys_canvas.winfo_width()
 
                # Set scroll region based on the frame's content size
                scroll_bbox = (0, 0, max(required_width, canvas_width), required_height)
 
                if required_height > 1 or required_width > 1 : # Check if there's content
                    self.keys_canvas.configure(scrollregion=scroll_bbox)
                else:
                    self.keys_canvas.configure(scrollregion=(0,0,1,1)) # Minimal region if empty
 
            except tk.TclError: pass # Ignore errors during rapid updates/destruction
            except Exception as e: print(f"Unexpected error updating scrollregion: {e}")
 
 
    def update_add_remove_button_state(self):
        """Enables/disables the add/remove key buttons based on count and state."""
        is_busy = self.is_running_mouse or self.is_running_keyboard or self.is_capturing
        base_state = tk.DISABLED if is_busy else tk.NORMAL
 
        def safe_config(widget: Optional[ttk.Button], state: str):
            if widget and widget.winfo_exists():
                try: widget.config(state=state)
                except tk.TclError: pass
                except Exception as e: print(f"Error configuring button state: {e}")
 
        add_state = tk.DISABLED if base_state == tk.DISABLED or self.current_key_row_count >= MAX_AUTOMATION_KEYS else tk.NORMAL
        safe_config(self.add_key_button, add_state)
 
        remove_state = tk.DISABLED if base_state == tk.DISABLED or self.current_key_row_count <= 0 else tk.NORMAL
        safe_config(self.remove_key_button, remove_state)
 
 
    def update_ui_state(self):
        """Central method to enable/disable UI elements based on application state."""
        is_mouse_running = self.is_running_mouse
        is_keyboard_running = self.is_running_keyboard
        is_either_running = is_mouse_running or is_keyboard_running
        is_capturing_active = self.is_capturing
 
        general_state = tk.DISABLED if (is_either_running or is_capturing_active) else tk.NORMAL
        start_button_state = tk.DISABLED if is_either_running or is_capturing_active else tk.NORMAL
        # Entries usually use 'readonly' instead of 'disabled' for better appearance/copying
        entry_state = 'readonly' if general_state == tk.DISABLED else tk.NORMAL
 
        def safe_config_state(widget: Optional[tk.Widget], state: str):
            """Helper to configure widget state safely."""
            if widget and widget.winfo_exists():
                try:
                    # Use 'readonly' for Entry widgets when disabling
                    effective_state = state
                    if isinstance(widget, (ttk.Entry, tk.Entry)) and state == tk.DISABLED:
                        effective_state = 'readonly'
                    widget.config(state=effective_state)
                except tk.TclError: pass
                except Exception as e: print(f"Error in safe_config_state for {widget}: {e}")
 
        # --- Update Mouse Tab ---
        safe_config_state(self.interval_entry, entry_state)
        for radio in self.click_type_radios: safe_config_state(radio, general_state)
        safe_config_state(self.mouse_hotkey_entry, entry_state)
        safe_config_state(self.mouse_hotkey_capture_button, general_state)
        safe_config_state(self.mouse_hotkey_apply_button, general_state)
        safe_config_state(self.mouse_side_button_x1, general_state)
        safe_config_state(self.mouse_side_button_x2, general_state)
        safe_config_state(self.mouse_duration_label, general_state)
        safe_config_state(self.mouse_duration_entry, entry_state)
        safe_config_state(self.mouse_duration_unit_label, general_state)
        safe_config_state(self.mouse_start_button, start_button_state if not is_mouse_running else tk.DISABLED)
        safe_config_state(self.mouse_stop_button, tk.NORMAL if is_mouse_running else tk.DISABLED)
 
        # --- Update Keyboard Tab ---
        safe_config_state(self.keyboard_hotkey_entry, entry_state)
        safe_config_state(self.keyboard_hotkey_capture_button, general_state)
        safe_config_state(self.keyboard_hotkey_apply_button, general_state)
        safe_config_state(self.keyboard_side_button_x1, general_state)
        safe_config_state(self.keyboard_side_button_x2, general_state)
 
        # Dynamic Key Rows Widgets
        for entry in self.key_entries: safe_config_state(entry, entry_state)
        for btn in self.key_capture_buttons: safe_config_state(btn, general_state)
        for btn in self.key_apply_buttons: safe_config_state(btn, general_state)
 
        # Mode & Cycle Delay
        for radio in self.keyboard_mode_radios: safe_config_state(radio, general_state)
        safe_config_state(self.cycle_delay_label, general_state)
        safe_config_state(self.cycle_delay_entry, entry_state)
        safe_config_state(self.cycle_delay_unit_label, general_state)
 
        # Dynamic Post-Key Delay Widgets (State depends on mode AND general state)
        is_sequential = self.keyboard_mode.get() == 'sequential'
        post_delay_state = tk.NORMAL if (general_state == tk.NORMAL and is_sequential) else tk.DISABLED
        post_delay_entry_state = 'readonly' if post_delay_state == tk.DISABLED else tk.NORMAL
 
        for entry in self.key_delay_entries: safe_config_state(entry, post_delay_entry_state)
        for label in self.key_delay_labels: safe_config_state(label, post_delay_state)
 
        # Add/Remove Buttons (Handled by its own update function)
        self.update_add_remove_button_state()
 
        # Duration & Controls
        safe_config_state(self.keyboard_duration_label, general_state)
        safe_config_state(self.keyboard_duration_entry, entry_state)
        safe_config_state(self.keyboard_duration_unit_label, general_state)
        safe_config_state(self.keyboard_start_button, start_button_state if not is_keyboard_running else tk.DISABLED)
        safe_config_state(self.keyboard_stop_button, tk.NORMAL if is_keyboard_running else tk.DISABLED)
 
        # --- Update Status Bar ---
        status_msg = "状态: 已停止"
        if is_mouse_running: status_msg = "状态: 鼠标连点运行中..."
        elif is_keyboard_running: status_msg = "状态: 键盘自动化运行中..."
        elif is_capturing_active: status_msg = "状态: 正在采集输入..."
 
        if self.status_label and self.status_label.winfo_exists():
            try:
                if self.status_text.get() != status_msg:
                    self.status_text.set(status_msg)
            except tk.TclError: pass
            except Exception as e: print(f"Error setting status text: {e}")
 
 
    # --- Input Validation (Tkinter %P validation commands) ---
    def validate_interval(self, P: str) -> bool:
        """Validation rule for interval entry (>= 0.01). Allows intermediate typing."""
        if P == "" or P == "." or P == "-": return True
        # Allow typing "0.0" prefix for 0.01
        if P.startswith("0.") and len(P) <= 3 : return True
        if P.startswith("-"): # Allow typing negative floats temporarily
            if P == "-." or P == "-": return True
            try: float(P); return True
            except ValueError: return False
        try: # Check if it's a valid float
            float(P); return True
        except ValueError: return False
 
    def validate_positive_float(self, P: str) -> bool:
        """Validation rule for non-negative float entry (>= 0). Allows intermediate typing."""
        if P == "" or P == "." or P == "-": return True
        if P == "0.": return True
        if P.startswith("-"): # Allow typing negative floats temporarily
            if P == "-." or P == "-": return True
            try: float(P); return True
            except ValueError: return False
        try: # Check if it's a valid float
            float(P); return True
        except ValueError: return False
 
 
    # --- Mouse Clicking Logic ---
    def toggle_clicking(self):
        """Toggles the mouse clicking state, performs validation before starting."""
        if self.is_running_keyboard:
            messagebox.showwarning("操作冲突", "请先停止键盘自动化。", parent=self.root)
            return
        if self.is_running_mouse:
            self.stop_clicking()
        else:
            # Perform strict validation just before starting
            if self._validate_interval_value() and self._validate_duration_value('mouse'):
                self.start_clicking()
 
    def _validate_interval_value(self) -> bool:
        """Strict validation of click interval (>= 0.01) before starting."""
        entry_widget = self.interval_entry
        error_bg, default_bg = '#FFCCCC', 'SystemWindow'
        try:
            interval = self.click_interval.get()
            if interval < 0.01:
                messagebox.showerror("输入错误", "鼠标间隔时间不能低于 0.01 秒。", parent=self.root)
                if entry_widget and entry_widget.winfo_exists(): entry_widget.config(background=error_bg)
                return False
            if entry_widget and entry_widget.winfo_exists(): entry_widget.config(background=default_bg)
            return True
        except (tk.TclError, ValueError): # Catch get() errors or invalid float conversions
            messagebox.showerror("输入错误", "鼠标间隔时间必须是有效的数字 (≥ 0.01)。", parent=self.root)
            if entry_widget and entry_widget.winfo_exists(): entry_widget.config(background=error_bg)
            return False
        except Exception as e:
            messagebox.showerror("验证错误", f"验证鼠标间隔时出错: {e}", parent=self.root)
            if entry_widget and entry_widget.winfo_exists(): entry_widget.config(background=error_bg)
            return False
 
    def _validate_duration_value(self, op_type: str) -> bool:
        """Strict validation of duration value (>= 0) before starting."""
        duration_var = self.mouse_duration if op_type == 'mouse' else self.keyboard_duration
        entry_widget = self.mouse_duration_entry if op_type == 'mouse' else self.keyboard_duration_entry
        error_bg, default_bg = '#FFCCCC', 'SystemWindow'
        try:
            duration = duration_var.get()
            if duration < 0.0:
                messagebox.showerror("输入错误", "持续时间不能为负数。", parent=self.root)
                if entry_widget and entry_widget.winfo_exists(): entry_widget.config(background=error_bg)
                return False
            if entry_widget and entry_widget.winfo_exists(): entry_widget.config(background=default_bg)
            return True
        except (tk.TclError, ValueError):
            messagebox.showerror("输入错误", "持续时间必须是有效的非负数字。", parent=self.root)
            if entry_widget and entry_widget.winfo_exists(): entry_widget.config(background=error_bg)
            return False
        except Exception as e:
            messagebox.showerror("验证错误", f"验证持续时间时出错: {e}", parent=self.root)
            if entry_widget and entry_widget.winfo_exists(): entry_widget.config(background=error_bg)
            return False
 
    def start_clicking(self):
        """Starts the mouse clicking thread and hides window if tray available."""
        if self.is_running_mouse or self.is_running_keyboard: return
        global mouse_controller
        if mouse_controller is None:
            messagebox.showerror("错误", "鼠标控制器未初始化。", parent=self.root)
            return
 
        # Final duration value check (safety)
        duration = self.mouse_duration.get() # Assumes validation already passed
 
        print("Starting mouse clicking...")
        self.is_running_mouse = True
        self.mouse_stop_event.clear()
 
        # --- NEW: Minimize to Tray Logic ---
        self.window_hidden_by_automation = False # Reset flag
        if self.tray_icon and self.tray_thread and self.tray_thread.is_alive():
            print("Mouse clicking started, hiding window to tray.")
            self.hide_window()
            self.window_hidden_by_automation = True # Set flag *only* if hidden
        # --- End Minimize Logic ---
 
        # Cancel any previous duration timer safely
        if self.mouse_duration_after_id:
            try: self.root.after_cancel(self.mouse_duration_after_id)
            except (ValueError, tk.TclError): pass
            self.mouse_duration_after_id = None
        # Schedule stop if duration is set
        if duration > 0:
            ms = int(duration * 1000)
            print(f"Scheduling mouse stop in {duration}s.")
            self.mouse_duration_after_id = self.root.after(ms, self.stop_clicking)
 
        self.update_ui_state() # Update UI immediately *before* starting thread
        self.mouse_click_thread = threading.Thread(target=self.click_worker, daemon=True, name="MouseClickThread")
        self.mouse_click_thread.start()
 
    def stop_clicking(self):
        """Stops the mouse clicking thread, restores window if needed, and updates UI."""
        if not self.is_running_mouse: return
        print("Stopping mouse clicking...")
        self.is_running_mouse = False
 
        if self.mouse_duration_after_id:
            try: self.root.after_cancel(self.mouse_duration_after_id)
            except (ValueError, tk.TclError): pass
            self.mouse_duration_after_id = None
 
        self.mouse_stop_event.set() # Signal the worker
 
        if self.mouse_click_thread is not None:
            self.mouse_click_thread.join(timeout=0.5)
            if self.mouse_click_thread.is_alive(): print("Warning: Mouse click thread join timed out.")
        self.mouse_click_thread = None
 
        # --- NEW: Restore Window Logic ---
        should_restore = self.window_hidden_by_automation
        self.window_hidden_by_automation = False # Reset flag immediately after checking
 
        def final_stop_actions_mouse():
            # This runs via root.after, ensuring it's in the main thread
            if self.root.winfo_exists():
                if should_restore:
                    print("Mouse clicking stopped, restoring window.")
                    self.show_window() # Restore if it was hidden by automation start
                self.update_ui_state() # Update UI state *after* potential restore
 
        try:
            if self.root.winfo_exists():
                # Schedule the final actions slightly deferred
                self.root.after(10, final_stop_actions_mouse)
        except tk.TclError: pass # Ignore if root destroyed during shutdown
        except Exception as e: print(f"Error scheduling final mouse stop actions: {e}")
        # --- End Restore Logic ---
 
 
    def click_worker(self):
        """Worker thread for mouse clicking."""
        global mouse_controller, Button
        if mouse_controller is None or 'Button' not in globals() or not hasattr(Button, 'left'):
            print("Error (click_worker): Mouse controller or Button class unavailable.")
            try:
                if self.root.winfo_exists(): self.root.after(0, self.stop_clicking)
            except tk.TclError: pass
            self.is_running_mouse = False
            return
 
        try:
            interval = self.click_interval.get()
            click_type_str = self.selected_click_type.get()
            button_to_click = getattr(Button, click_type_str, None) # Get Button enum member
 
            if button_to_click is None: raise ValueError(f"Invalid click type: {click_type_str}")
            if interval < 0.01: raise ValueError("Interval too low")
 
            print(f"Mouse Click worker started: Type={click_type_str}, Interval={interval:.4f}s")
            while not self.mouse_stop_event.is_set():
                loop_start_time = time.perf_counter()
                try:
                    mouse_controller.click(button_to_click, 1)
                except Exception as click_err:
                    print(f"Error during mouse click: {click_err}")
                    # Consider breaking or just continue: continue for now
                    pass
 
                elapsed = time.perf_counter() - loop_start_time
                sleep_time = interval - elapsed
                if sleep_time > 0:
                    # Wait for the remaining interval, but check stop event frequently
                    granularity = 0.005 # Check stop event every 5ms during sleep
                    end_time = time.perf_counter() + sleep_time
                    while time.perf_counter() < end_time:
                         if self.mouse_stop_event.wait(timeout=min(granularity, end_time - time.perf_counter())):
                              break # Exit inner loop if stopped
                    if self.mouse_stop_event.is_set(): break # Exit outer loop if stopped
 
 
            print("Mouse Click worker finished.")
        except (tk.TclError, ValueError, AttributeError, RuntimeError) as e:
            print(f"Error in mouse worker setup or value: {e}. Stopping.")
            try:
                if self.root.winfo_exists(): self.root.after(0, self.stop_clicking)
            except tk.TclError: pass
        except Exception as e:
            print(f"Unexpected error in click_worker: {e}"); traceback.print_exc()
            try:
                if self.root.winfo_exists(): self.root.after(0, self.stop_clicking)
            except tk.TclError: pass
        finally:
            self.is_running_mouse = False # Ensure flag reset
 
# --- Keyboard Automation Logic ---
    def toggle_keyboard_automation(self):
        """Toggles the keyboard automation state, performs validation before starting."""
        if self.is_running_mouse:
            messagebox.showwarning("操作冲突", "请先停止鼠标连点。", parent=self.root)
            return
        if self.is_running_keyboard:
            self.stop_keyboard_automation()
        else:
            # Perform all validations before starting
            if (self._validate_keyboard_cycle_delay() and
                self._validate_duration_value('keyboard') and
                self._validate_keyboard_targets()): # Target validation includes delay checks
                self.start_keyboard_automation()
 
    def _validate_keyboard_cycle_delay(self) -> bool:
        """Validates the keyboard cycle delay (>= 0) before starting."""
        entry_widget = self.cycle_delay_entry
        error_bg, default_bg = '#FFCCCC', 'SystemWindow'
        try:
            delay = self.keyboard_cycle_delay.get()
            if delay < 0.0: raise ValueError("Negative delay")
            if entry_widget and entry_widget.winfo_exists(): entry_widget.config(background=default_bg)
            return True
        except (tk.TclError, ValueError):
            messagebox.showerror("输入错误", "键盘自动化循环间隔必须是有效的非负数字。", parent=self.root)
            if entry_widget and entry_widget.winfo_exists(): entry_widget.config(background=error_bg)
            return False
        except Exception as e:
            messagebox.showerror("验证错误", f"验证键盘循环间隔时出错: {e}", parent=self.root)
            if entry_widget and entry_widget.winfo_exists(): entry_widget.config(background=error_bg)
            return False
 
    def _apply_target_key(self, index: int):
        """Validates manually entered target key & delay for a specific row. Updates UI BG color."""
        # Basic index check
        if index >= self.current_key_row_count or index < 0: return
 
        key_var = self.keyboard_target_keys[index]
        delay_var = self.keyboard_target_delays[index]
        key_entry = self.key_entries[index]
        delay_entry = self.key_delay_entries[index]
        is_seq = self.keyboard_mode.get() == 'sequential'
        error_bg, default_bg = '#FFCCCC', 'SystemWindow'
 
        key_ok, delay_ok = True, True
        parsed_key = None
        key_str = key_var.get().strip()
 
        # Validate Delay
        try:
            if delay_var.get() < 0.0: raise ValueError("Negative")
            if delay_entry.winfo_exists(): delay_entry.config(background=default_bg)
        except (tk.TclError, ValueError):
            delay_ok = False
            if key_str and is_seq and delay_entry.winfo_exists(): delay_entry.config(background=error_bg)
            elif delay_entry.winfo_exists(): delay_entry.config(background=default_bg) # Reset if not seq error
 
        # Validate Key (if not empty)
        if not key_str:
            if key_entry.winfo_exists(): key_entry.config(background=default_bg)
            # Reset delay bg if key is cleared
            if not delay_ok and delay_entry.winfo_exists(): delay_entry.config(background=default_bg)
        else:
            try:
                parsed_set = self.parse_hotkey_str(key_str)
                if len(parsed_set) != 1: raise ValueError("目标必须是单个按键/按钮")
                parsed_key = list(parsed_set)[0]
                if key_entry.winfo_exists(): key_entry.config(background=default_bg)
            except (ValueError, RuntimeError) as e:
                key_ok = False
                messagebox.showerror("格式错误", f"按键 {index + 1} ('{key_str}') 格式无效:\n{e}", parent=self.root)
                if key_entry.winfo_exists(): key_entry.config(background=error_bg)
            except Exception as e:
                 key_ok = False; print(f"Unexpected parse error: {e}")
                 if key_entry.winfo_exists(): key_entry.config(background=error_bg)
 
        # Update UI / Feedback
        if key_ok and delay_ok and parsed_key:
            try: # Format key back to entry for consistency
                key_var.set(self.format_pynput_key(parsed_key))
                print(f"Target key {index + 1} format applied.")
            except Exception: pass # Ignore formatting errors here
        elif key_ok and not key_str:
             print(f"Target key {index + 1} cleared.")
 
 
    def _validate_keyboard_targets(self) -> bool:
        """Checks ALL target key rows for validity before starting automation. Updates UI & internal list."""
        self.valid_target_key_objects = []
        has_valid_key = False
        all_rows_ok = True
        first_error = ""
        is_seq = self.keyboard_mode.get() == 'sequential'
        error_bg, default_bg = '#FFCCCC', 'SystemWindow'
 
        print("Validating keyboard targets...")
        for i in range(self.current_key_row_count):
            key_str = self.keyboard_target_keys[i].get().strip()
            key_entry = self.key_entries[i]
            delay_entry = self.key_delay_entries[i]
            key_ok, delay_ok = True, True
            parsed_key = None
            row_error = ""
 
            # Validate Delay
            try:
                if self.keyboard_target_delays[i].get() < 0.0: raise ValueError("Negative")
                if delay_entry.winfo_exists(): delay_entry.config(background=default_bg)
            except (tk.TclError, ValueError):
                delay_ok = False
                if key_str and is_seq: # Only error if key present & seq mode
                    row_error = f"按键 {i + 1}: 后置延迟无效"; all_rows_ok = False
                    if delay_entry.winfo_exists(): delay_entry.config(background=error_bg)
                elif delay_entry.winfo_exists(): delay_entry.config(background=default_bg) # Reset bg
 
            # Validate Key
            if not key_str:
                if key_entry.winfo_exists(): key_entry.config(background=default_bg)
                if not delay_ok and delay_entry.winfo_exists(): delay_entry.config(background=default_bg) # Reset delay if key empty
            else:
                try:
                    parsed_set = self.parse_hotkey_str(key_str)
                    if len(parsed_set) != 1: raise ValueError("目标必须是单个按键/按钮")
                    parsed_key = list(parsed_set)[0]
                    has_valid_key = True
                    if key_entry.winfo_exists(): key_entry.config(background=default_bg)
                except (ValueError, RuntimeError) as e:
                    key_ok = False; all_rows_ok = False; row_error = f"按键 {i + 1} ('{key_str}') 格式错误: {e}"
                    if key_entry.winfo_exists(): key_entry.config(background=error_bg)
                    if not delay_ok and is_seq and delay_entry.winfo_exists(): delay_entry.config(background=error_bg) # Mark delay red too if key bad & seq
                except Exception as e:
                    key_ok = False; all_rows_ok = False; row_error = f"按键 {i + 1} 解析错误: {e}"
                    if key_entry.winfo_exists(): key_entry.config(background=error_bg)
 
            if row_error and not first_error: first_error = row_error
 
            # Add to list if valid for execution
            if parsed_key and key_ok and (delay_ok or not is_seq):
                 self.valid_target_key_objects.append((parsed_key, self.keyboard_target_delays[i].get()))
 
        # Final checks
        if not all_rows_ok:
            msg = first_error or "自动化按键列表中存在无效设置"
            messagebox.showerror("验证错误", f"{msg} (已标红)。\n请修正后重试。", parent=self.root)
            return False
        if not has_valid_key:
            messagebox.showerror("错误", "请至少设置并应用一个有效的键盘自动化目标按键。", parent=self.root)
            return False
 
        print(f"Keyboard target validation passed. {len(self.valid_target_key_objects)} valid keys found.")
        return True
 
 
    def start_keyboard_automation(self):
        """Starts the keyboard automation thread and hides window if tray available."""
        if self.is_running_keyboard or self.is_running_mouse: return
        global keyboard_controller, mouse_controller
        if keyboard_controller is None or mouse_controller is None:
            messagebox.showerror("错误", "输入控制器未初始化。", parent=self.root)
            return
 
        # Final duration check (safety)
        duration = self.keyboard_duration.get() # Assumes validation passed
 
        if not self.valid_target_key_objects: # Should be caught by toggle logic
            messagebox.showerror("错误", "没有有效的自动化按键可执行。", parent=self.root)
            return
 
        print("Starting keyboard automation...")
        self.is_running_keyboard = True
        self.keyboard_stop_event.clear()
 
        # --- NEW: Minimize to Tray Logic ---
        self.window_hidden_by_automation = False # Reset flag
        if self.tray_icon and self.tray_thread and self.tray_thread.is_alive():
            print("Keyboard automation started, hiding window to tray.")
            self.hide_window()
            self.window_hidden_by_automation = True # Set flag *only* if hidden
        # --- End Minimize Logic ---
 
        if self.keyboard_duration_after_id:
            try: self.root.after_cancel(self.keyboard_duration_after_id)
            except (ValueError, tk.TclError): pass
            self.keyboard_duration_after_id = None
        if duration > 0:
            ms = int(duration * 1000)
            print(f"Scheduling keyboard stop in {duration}s.")
            self.keyboard_duration_after_id = self.root.after(ms, self.stop_keyboard_automation)
 
        self.update_ui_state() # Update UI immediately *before* starting thread
        self.keyboard_thread = threading.Thread(target=self.keyboard_worker, daemon=True, name="KeyboardAutomateThread")
        self.keyboard_thread.start()
 
    def stop_keyboard_automation(self):
        """Stops the keyboard automation thread, restores window if needed, and updates UI."""
        if not self.is_running_keyboard: return
        print("Stopping keyboard automation...")
        self.is_running_keyboard = False
 
        if self.keyboard_duration_after_id:
            try: self.root.after_cancel(self.keyboard_duration_after_id)
            except (ValueError, tk.TclError): pass
            self.keyboard_duration_after_id = None
 
        self.keyboard_stop_event.set() # Signal the worker
 
        if self.keyboard_thread is not None:
            self.keyboard_thread.join(timeout=0.6)
            if self.keyboard_thread.is_alive(): print("Warning: Keyboard automation thread join timed out.")
        self.keyboard_thread = None
 
        # --- NEW: Restore Window Logic ---
        should_restore = self.window_hidden_by_automation
        self.window_hidden_by_automation = False # Reset flag immediately after checking
 
        def final_stop_actions_keyboard():
            # This runs via root.after, ensuring it's in the main thread
            if self.root.winfo_exists():
                if should_restore:
                    print("Keyboard automation stopped, restoring window.")
                    self.show_window() # Restore if it was hidden by automation start
                self.update_ui_state() # Update UI state *after* potential restore
 
        try:
            if self.root.winfo_exists():
                 # Schedule the final actions slightly deferred
                self.root.after(10, final_stop_actions_keyboard)
        except tk.TclError: pass # Ignore if root destroyed during shutdown
        except Exception as e: print(f"Error scheduling final keyboard stop actions: {e}")
        # --- End Restore Logic ---
 
 
    def keyboard_worker(self):
        """Worker thread for keyboard automation (Sequential and Simultaneous modes)."""
        global keyboard_controller, mouse_controller, Button, Key, KeyCode
        req_globals = ['keyboard_controller', 'mouse_controller', 'Button', 'Key', 'KeyCode']
        if not all(c in globals() and globals()[c] is not None for c in req_globals):
            print("Error (keyboard_worker): Input controllers/pynput classes unavailable.")
            try:
                if self.root.winfo_exists(): self.root.after(0, self.stop_keyboard_automation)
            except tk.TclError: pass
            self.is_running_keyboard = False
            return
 
        try:
            cycle_interval = self.keyboard_cycle_delay.get()
            mode = self.keyboard_mode.get()
            # Use the validated list prepared by _validate_keyboard_targets
            target_keys_with_delays = list(self.valid_target_key_objects) # Use a copy
 
            if not target_keys_with_delays: raise ValueError("Worker started with no valid keys.")
            if cycle_interval < 0.0: raise ValueError("Negative cycle interval.")
            if mode not in ['sequential', 'simultaneous']: raise ValueError(f"Invalid mode: {mode}")
 
            print(f"Keyboard worker started: Mode={mode}, Interval={cycle_interval:.4f}s")
 
            while not self.keyboard_stop_event.is_set():
                cycle_start_time = time.perf_counter()
 
                if mode == 'simultaneous':
                    pressed_keys_sim = []
                    try:
                        for key, _ in target_keys_with_delays:
                            if self.keyboard_stop_event.is_set(): break
                            if key is None: continue
                            if isinstance(key, (Key, KeyCode)): keyboard_controller.press(key)
                            elif isinstance(key, Button): mouse_controller.press(key)
                            pressed_keys_sim.append(key) # Track pressed keys
                        if self.keyboard_stop_event.is_set(): break
                        if self.keyboard_stop_event.wait(0.02): break # Short pause
                        for key in reversed(pressed_keys_sim): # Release in reverse
                            if isinstance(key, (Key, KeyCode)): keyboard_controller.release(key)
                            elif isinstance(key, Button): mouse_controller.release(key)
                    except Exception as sim_err:
                        print(f"Error during simultaneous press/release: {sim_err}")
                        # Attempt to release any stuck keys
                        for key in reversed(pressed_keys_sim):
                            try:
                                if isinstance(key, (Key, KeyCode)): keyboard_controller.release(key)
                                elif isinstance(key, Button): mouse_controller.release(key)
                            except Exception: pass # Ignore release errors during cleanup
                        self.keyboard_stop_event.set(); break # Stop on error
 
                elif mode == 'sequential':
                    for i, (key, specific_delay) in enumerate(target_keys_with_delays):
                        if self.keyboard_stop_event.is_set(): break
                        if key is None: continue
 
                        action_start_time = time.perf_counter()
                        try: # Perform tap or click
                            if isinstance(key, (Key, KeyCode)): keyboard_controller.tap(key)
                            elif isinstance(key, Button): mouse_controller.click(key, 1)
                        except Exception as seq_err:
                            print(f"Error during sequential action (key: {key}): {seq_err}")
                            self.keyboard_stop_event.set(); break # Stop on error
                        if self.keyboard_stop_event.is_set(): break
 
                        # Wait for Post-Key Delay (specific_delay)
                        if specific_delay > 0:
                            action_elapsed = time.perf_counter() - action_start_time
                            actual_sleep = specific_delay - action_elapsed
                            if actual_sleep > 0:
                                # Wait, but check stop event frequently
                                granularity = 0.005
                                end_time = time.perf_counter() + actual_sleep
                                while time.perf_counter() < end_time:
                                    if self.keyboard_stop_event.wait(timeout=min(granularity, end_time - time.perf_counter())):
                                        break # Exit inner wait loop
                                if self.keyboard_stop_event.is_set(): break # Exit outer for loop
                        if self.keyboard_stop_event.is_set(): break # Check after delay too
                    if self.keyboard_stop_event.is_set(): break # Exit outer loop if inner loop broke
 
                # --- End of Cycle ---
                if self.keyboard_stop_event.is_set(): break
 
                # Wait for Cycle Interval
                cycle_elapsed = time.perf_counter() - cycle_start_time
                sleep_time = cycle_interval - cycle_elapsed
                if sleep_time > 0:
                    # Wait, but check stop event frequently
                    granularity = 0.005
                    end_time = time.perf_counter() + sleep_time
                    while time.perf_counter() < end_time:
                        if self.keyboard_stop_event.wait(timeout=min(granularity, end_time - time.perf_counter())):
                            break
                    if self.keyboard_stop_event.is_set(): break
 
 
            print("Keyboard worker finished.")
        except (tk.TclError, ValueError, RuntimeError) as e:
            print(f"Error in keyboard worker setup/value: {e}. Stopping.")
            try:
                if self.root.winfo_exists(): self.root.after(0, self.stop_keyboard_automation)
            except tk.TclError: pass
        except Exception as e:
            print(f"Unexpected error in keyboard_worker: {e}"); traceback.print_exc()
            try:
                if self.root.winfo_exists(): self.root.after(0, self.stop_keyboard_automation)
            except tk.TclError: pass
        finally:
            self.is_running_keyboard = False # Ensure flag reset
 
 
    # --- Key/Hotkey Parsing and Formatting Utilities ---
    def format_pynput_key(self, key: Optional[PynputKeyType]) -> str:
        """Formats a pynput key/button object into a user-readable string."""
        if key is None: return ""
        global Key, KeyCode, Button
        if 'Key' not in globals(): return str(key) # Fallback
 
        try:
            if isinstance(key, KeyCode):
                char = getattr(key, 'char', None)
                if char: # Handle characters, including quotes
                    if char == "'": return "\"'\""
                    if char == '"': return "'\"'"
                    if len(char) == 1 and char.isprintable() and char not in "+'\"": return f"'{char}'"
                vk = getattr(key, 'vk', None) # Fallback for non-printable or complex KeyCode
                return f"VK({vk})" if vk else str(key)
            elif isinstance(key, Key): return f"Key.{key.name}" # e.g., Key.f8, Key.ctrl_l
            elif isinstance(key, Button): return f"Button.{key.name}" # e.g., Button.left
            else: return str(key) # Fallback
        except Exception as e: print(f"Error formatting key {key}: {e}"); return str(key)
 
    def parse_hotkey_str(self, hotkey_string: str) -> Set[PynputKeyType]:
        """Parses a user string into a set of pynput key/button objects. Raises ValueError on errors."""
        global Key, KeyCode, Button
        if 'Key' not in globals(): raise RuntimeError("Pynput classes unavailable for parsing.")
        if not isinstance(hotkey_string, str): raise ValueError("Input must be string")
 
        hotkey_string = hotkey_string.strip()
        if not hotkey_string: return set() # Empty string means no hotkey
 
        keys: Set[PynputKeyType] = set()
        processed_string = '+'.join(part.strip() for part in hotkey_string.split('+'))
        parts = [p for p in processed_string.split('+') if p] # Remove empty parts
        if not parts: raise ValueError("Invalid format (empty parts)")
 
        for part in parts:
            part_lower = part.lower()
            found = False
            # Try Button.xxx
            if part_lower.startswith('button.'):
                name = part.split('.')[-1].lower()
                match = next((m for n, m in Button.__members__.items() if n.lower() == name), None)
                if match: keys.add(match); found = True
                else: raise ValueError(f"Unknown mouse button: '{part}'")
            # Try Key.xxx
            elif part_lower.startswith('key.'):
                name = part.split('.')[-1].lower()
                match = next((m for n, m in Key.__members__.items() if n.lower() == name), None)
                if match: keys.add(match); found = True
                else: raise ValueError(f"Unknown special key: '{part}'")
            # Try quoted char 'x' or "x"
            elif len(part) >= 2 and part[0] == part[-1] and part[0] in ("'", '"'):
                inner = part[1:-1]
                if len(inner) == 1:
                    try: keys.add(KeyCode.from_char(inner)); found = True
                    except (ValueError, TypeError) as e: raise ValueError(f"Cannot parse char '{inner}': {e}")
                elif part == "\"'\"": keys.add(KeyCode.from_char("'")); found = True
                elif part == "'\"'": keys.add(KeyCode.from_char('"')); found = True
                else: raise ValueError(f"Quoted content must be single char: '{part}'")
            # Try single char
            elif len(part) == 1:
                if part == '+': raise ValueError("Use Key.add for '+' key")
                try: keys.add(KeyCode.from_char(part)); found = True
                except (ValueError, TypeError) as e: raise ValueError(f"Cannot parse char '{part}': {e}")
 
            if not found:
                 # Improve specific errors
                 if part_lower in ['ctrl','alt','shift','cmd','win','command','option']: raise ValueError(f"Use Key.{part_lower}_l/r for modifiers")
                 raise ValueError(f"Cannot parse hotkey part: '{part}'")
 
        if not keys: raise ValueError("No valid keys parsed") # Should not happen if parts existed
        return keys
 
    def format_hotkey_set(self, hotkey_set: Optional[Set[PynputKeyType]]) -> str:
        """Formats a set of pynput keys into a sorted, readable string."""
        if not hotkey_set: return ""
        keys_list = list(hotkey_set)
 
        def sort_key(k: PynputKeyType) -> Tuple[int, str]:
            """Sorts keys: Modifiers > Mouse > Numpad/Ops > Special > Chars."""
            sort_order = 9; name = str(k).lower()
            if isinstance(k, Key):
                n = k.name.lower(); base = n.replace('_l', '').replace('_r', '')
                name = n # Use specific name for sorting
                if base in ['ctrl','shift','alt','cmd','win','option']: sort_order = 0
                elif n.startswith("numpad") or n in ["add","subtract","multiply","divide","decimal","separator"]: sort_order = 2
                elif n.startswith("f") and n[1:].isdigit(): sort_order = 3
                else: sort_order = 4
            elif isinstance(k, Button): name = k.name.lower(); sort_order = 1
            elif isinstance(k, KeyCode):
                char = getattr(k, 'char', None)
                if char and len(char)==1 and char.isprintable(): name = char.lower(); sort_order = 5
                else: vk = getattr(k, 'vk', None); name = f"vk_{vk}" if vk else name; sort_order = 4
            return (sort_order, name)
 
        try:
            sorted_keys = sorted(keys_list, key=sort_key)
            return " + ".join([self.format_pynput_key(k) for k in sorted_keys])
        except Exception as e:
            print(f"Error formatting hotkey set {hotkey_set}: {e}")
            return " + ".join([self.format_pynput_key(k) for k in keys_list]) # Fallback
 
    def _get_canonical_key(self, key: Optional[PynputKeyType]) -> Optional[PynputKeyType]:
        """Returns canonical key for matching (e.g., maps ctrl_l/r to generic ctrl)."""
        if key is None: return None
        global Key, KeyCode, Button
        if 'Key' not in globals(): return key # Pynput not loaded
 
        # Map side-specific modifiers to generic ones if generic exists in enum
        if isinstance(key, Key):
            name = key.name.lower()
            if name in ('ctrl_l', 'ctrl_r'): return getattr(Key, 'ctrl', key)
            if name in ('shift_l', 'shift_r'): return getattr(Key, 'shift', key)
            if name in ('alt_l', 'alt_r', 'alt_gr'): return getattr(Key, 'alt', key)
            if name in ('cmd_l', 'cmd_r', 'win_l', 'win_r'): return getattr(Key, 'cmd', key) # Use generic 'cmd'
        return key # Return original if no mapping
 
 
    # --- Apply Hotkey Logic ---
    def apply_hotkey(self, hotkey_type: str):
        """Parses hotkey string, validates for conflicts, updates state, restarts listener."""
        if hotkey_type not in ('mouse', 'keyboard'): return
        hotkey_var = self.mouse_hotkey_str if hotkey_type == 'mouse' else self.keyboard_hotkey_str
        entry_widget = self.mouse_hotkey_entry if hotkey_type == 'mouse' else self.keyboard_hotkey_entry
        error_bg, default_bg = '#FFCCCC', 'SystemWindow'
        new_hotkey_str = hotkey_var.get().strip()
 
        current_parsed = self.parsed_mouse_hotkey if hotkey_type == 'mouse' else self.parsed_keyboard_hotkey
        other_parsed = self.parsed_keyboard_hotkey if hotkey_type == 'mouse' else self.parsed_mouse_hotkey
        other_type_str = "键盘自动化" if hotkey_type == 'mouse' else "鼠标连点"
        parsed_set: Set[PynputKeyType] = set()
 
        try:
            parsed_set = self.parse_hotkey_str(new_hotkey_str) # Parse
 
            # Conflict Check (using canonical keys)
            new_canon = {self._get_canonical_key(k) for k in parsed_set if k}
            other_canon = {self._get_canonical_key(k) for k in (other_parsed or set()) if k} # Handle None case
            if new_canon and other_canon and new_canon == other_canon:
                conflict_str = self.format_hotkey_set(parsed_set)
                messagebox.showerror("热键冲突", f"热键 '{conflict_str}' 已被 '{other_type_str}' 使用。", parent=self.root)
                hotkey_var.set(self.format_hotkey_set(current_parsed)) # Revert
                if entry_widget and entry_widget.winfo_exists(): entry_widget.config(background=error_bg)
                return
 
            # Apply valid hotkey
            formatted_str = self.format_hotkey_set(parsed_set)
            hotkey_var.set(formatted_str) # Update UI entry
            if entry_widget and entry_widget.winfo_exists(): entry_widget.config(background=default_bg)
 
            # Stop listener, update internal state, restart listener
            print("Stopping listener to apply hotkey...")
            self.stop_hotkey_listener(wait=True)
            applied_str = formatted_str or '无'
            if hotkey_type == 'mouse': self.parsed_mouse_hotkey = parsed_set; print(f"Mouse Hotkey: {applied_str}")
            else: self.parsed_keyboard_hotkey = parsed_set; print(f"Keyboard Hotkey: {applied_str}")
            print("Restarting listener...")
            # Use slightly longer delay to ensure listener is fully stopped
            self.root.after(150, self.start_hotkey_listener)
 
        except (ValueError, RuntimeError) as e: # Handle parsing errors
            messagebox.showerror("热键格式错误", f"无法应用热键 '{new_hotkey_str}':\n{e}", parent=self.root)
            hotkey_var.set(self.format_hotkey_set(current_parsed)) # Revert
            if entry_widget and entry_widget.winfo_exists(): entry_widget.config(background=error_bg)
            # Ensure listener restarts even after error
            self.root.after(150, self.start_hotkey_listener)
        except Exception as e: # Handle other errors
            messagebox.showerror("应用错误", f"应用热键时发生错误: {e}", parent=self.root); traceback.print_exc()
            hotkey_var.set(self.format_hotkey_set(current_parsed)); # Revert
            if entry_widget and entry_widget.winfo_exists(): entry_widget.config(background=error_bg)
            self.root.after(150, self.start_hotkey_listener)
 
 
    def apply_specific_hotkey(self, hotkey_type: str, key_object: PynputKeyType):
        """Applies a specific pynput key object (e.g., side button) as a hotkey."""
        if key_object is None: return
        try:
            hotkey_str = self.format_pynput_key(key_object)
            hotkey_var = self.mouse_hotkey_str if hotkey_type == 'mouse' else self.keyboard_hotkey_str
            hotkey_var.set(hotkey_str) # Update UI
            self.apply_hotkey(hotkey_type) # Use main logic
        except Exception as e:
            messagebox.showerror("应用错误", f"应用侧键 ({key_object}) 时出错: {e}", parent=self.root); traceback.print_exc()
 
 
    # --- Unified Hotkey Listener Logic ---
    def start_hotkey_listener(self):
        """Starts the single global hotkey listener thread if any hotkeys are set."""
        global KeyboardListener, MouseListener
        if 'KeyboardListener' not in globals() or 'MouseListener' not in globals():
            print("Error: Pynput listeners unavailable."); return
 
        has_mouse_hk = bool(self.parsed_mouse_hotkey)
        has_keyboard_hk = bool(self.parsed_keyboard_hotkey)
        if not (has_mouse_hk or has_keyboard_hk):
            print("Listener not started: No hotkeys configured.")
            if self.hotkey_listener_thread and self.hotkey_listener_thread.is_alive():
                 self.stop_hotkey_listener(wait=False) # Stop if running without need
            return
 
        if self.hotkey_listener_thread is not None and self.hotkey_listener_thread.is_alive():
            print("Listener already running."); return
 
        print("Starting global hotkey listener thread...")
        self.hotkey_stop_event.clear()
        self.current_pressed_keys = set()
        self._listener_keyboard_instance = None # Clear old references
        self._listener_mouse_instance = None
        self.hotkey_listener_thread = threading.Thread(target=self.hotkey_listener_worker, daemon=True, name="HotkeyListenerThread")
        self.hotkey_listener_thread.start()
 
 
    def stop_hotkey_listener(self, wait: bool = False):
        """Stops the global hotkey listener thread and its pynput listeners."""
        if not (self.hotkey_listener_thread and self.hotkey_listener_thread.is_alive()):
            # Already stopped or never started
            self.hotkey_listener_thread = None; self._listener_keyboard_instance = None; self._listener_mouse_instance = None
            return
 
        print("Stopping global hotkey listener...")
        self.hotkey_stop_event.set() # Signal worker thread
 
        # Stop underlying listeners from main thread (safer)
        kb_listener = self._listener_keyboard_instance
        m_listener = self._listener_mouse_instance
 
        # Clear references immediately
        self._listener_keyboard_instance = None
        self._listener_mouse_instance = None
 
        # Use pynput's built-in stop mechanism if possible (handles thread safety)
        if kb_listener and hasattr(kb_listener, 'stop'):
            try:
                # pynput stop() is thread-safe and should be preferred
                kb_listener.stop()
                print(" pynput KB listener stop requested.")
            except Exception as e: print(f" Minor error requesting KB listener stop: {e}")
        if m_listener and hasattr(m_listener, 'stop'):
            try:
                m_listener.stop()
                print(" pynput Mouse listener stop requested.")
            except Exception as e: print(f" Minor error requesting Mouse listener stop: {e}")
 
 
        # Wait for thread exit if requested
        if wait:
            join_timeout = 1.0
            if self.hotkey_listener_thread: # Check if thread still exists
                self.hotkey_listener_thread.join(timeout=join_timeout)
                if self.hotkey_listener_thread.is_alive(): print(" Warning: Listener thread join timed out.")
                else: print(" Listener thread joined.")
            else: print(" Listener thread already cleared.")
 
 
        self.hotkey_listener_thread = None # Clear thread ref after join attempt
        self.current_pressed_keys = set()
        print("Listener cleanup sequence finished.")
 
 
    def hotkey_listener_worker(self):
        """Worker thread running pynput listeners to detect hotkeys."""
        global KeyboardListener, MouseListener
        if 'KeyboardListener' not in globals(): print("Error(worker): Pynput unavailable."); return
 
        listener_keyboard: Optional['KeyboardListener'] = None
        listener_mouse: Optional['MouseListener'] = None
        self.current_pressed_keys = set() # Reset state for this run
 
        try:
            def on_press(key_raw):
                if self.hotkey_stop_event.is_set() or key_raw is None: return
                key = self._get_canonical_key(key_raw)
                if key:
                    # Add key and immediately check for match
                    is_new = key not in self.current_pressed_keys
                    if is_new:
                        self.current_pressed_keys.add(key)
                        check_hotkey_match()
 
            def on_release(key_raw):
                if self.hotkey_stop_event.is_set() or key_raw is None: return
                key = self._get_canonical_key(key_raw)
                if key:
                    # Remove key after processing potential release match (though usually match on press)
                    self.current_pressed_keys.discard(key)
 
            def on_click(x, y, button_raw, pressed):
                if self.hotkey_stop_event.is_set() or button_raw is None: return
                button = self._get_canonical_key(button_raw) # Should be identity for buttons
                if button and pressed:
                     is_new = button not in self.current_pressed_keys
                     if is_new:
                        self.current_pressed_keys.add(button)
                        check_hotkey_match()
                elif button:
                    self.current_pressed_keys.discard(button)
 
            def check_hotkey_match():
                # Use instance attributes directly, assuming they are thread-safe enough for reads
                target_mouse_set = self.parsed_mouse_hotkey or set()
                target_kb_set = self.parsed_keyboard_hotkey or set()
                if not target_mouse_set and not target_kb_set: return
 
                # Get canonical versions for comparison
                pressed_canon = {k for k in self.current_pressed_keys if k}
                mouse_target_canon = {self._get_canonical_key(k) for k in target_mouse_set if k}
                key_target_canon = {self._get_canonical_key(k) for k in target_kb_set if k}
 
                matched = False
                action_to_run = None
 
                if mouse_target_canon and pressed_canon == mouse_target_canon:
                    print(f"Mouse Hotkey triggered!")
                    action_to_run = self.toggle_clicking
                    matched = True
                elif key_target_canon and pressed_canon == key_target_canon:
                    print(f"Keyboard Hotkey triggered!")
                    action_to_run = self.toggle_keyboard_automation
                    matched = True
 
                if matched and action_to_run:
                    try:
                        # Schedule action in main thread
                        if self.root.winfo_exists():
                             self.root.after(0, action_to_run)
                             # Optional: Short sleep in listener to prevent rapid re-trigger
                             time.sleep(0.3)
                    except tk.TclError:
                        self.hotkey_stop_event.set() # Stop listener if root gone
                    except Exception as e:
                        print(f"Error scheduling hotkey action: {e}")
 
 
            # Setup and run listeners
            # Use 'with' statement for cleaner listener management if pynput version supports it well
            # Otherwise, manual start/join
            print("Hotkey listener worker creating listeners.")
            listener_keyboard = KeyboardListener(on_press=on_press, on_release=on_release, suppress=False)
            listener_mouse = MouseListener(on_click=on_click, suppress=False)
 
            # Store references for external stop
            self._listener_keyboard_instance = listener_keyboard
            self._listener_mouse_instance = listener_mouse
 
            listener_keyboard.start()
            listener_mouse.start()
            print("Hotkey listener worker running and waiting.")
 
            # Keep worker alive by joining the listeners (they block until stopped)
            # Check stop event periodically in case listeners fail to start/stop cleanly
            while not self.hotkey_stop_event.is_set():
                 time.sleep(0.5) # Main check loop
 
            print("Hotkey listener worker stop signal received.")
 
 
        except Exception as e: print(f"Fatal error in hotkey worker: {e}"); traceback.print_exc()
        finally: # Cleanup listeners within the worker
            print("Hotkey listener worker cleanup...")
            # Stop listeners if they haven't been stopped externally already
            kb_listener_local = self._listener_keyboard_instance # Use local ref
            m_listener_local = self._listener_mouse_instance
 
            if kb_listener_local and hasattr(kb_listener_local, 'stop') and kb_listener_local.is_alive():
                try: kb_listener_local.stop()
                except Exception: pass
            if m_listener_local and hasattr(m_listener_local, 'stop') and m_listener_local.is_alive():
                try: m_listener_local.stop()
                except Exception: pass
            print("Hotkey listener worker finished cleanup.")
 
 
    # --- Key/Hotkey Capture Dialog ---
    def open_capture_dialog(self, capture_type: str, index: Optional[int] = None):
        """Opens the modal dialog to capture keys/hotkeys."""
        if self.is_running_mouse or self.is_running_keyboard:
            messagebox.showwarning("操作繁忙", "请先停止运行中的任务再采集。", parent=self.root); return
        if self.is_capturing:
            messagebox.showwarning("操作繁忙", "请先完成当前的采集操作。", parent=self.root); return
        if capture_type == 'target_key' and (index is None or index < 0 or index >= self.current_key_row_count):
            messagebox.showerror("内部错误", f"无效的目标按键索引: {index}", parent=self.root); return
 
        self.is_capturing = True; self.update_ui_state()
        captured_value: Optional[str] = None
        try:
            print("Temporarily stopping global listener for capture...")
            self.stop_hotkey_listener(wait=True) # Stop main listener
            dialog = HotkeyCaptureDialog(self.root, self, capture_type, index) # Create dialog
            captured_value = dialog.show() # Show modal dialog, blocks here
        except Exception as e: print(f"Error opening capture dialog: {e}"); traceback.print_exc()
        finally: # Always executed
            self.is_capturing = False
            # Ensure UI update happens even if dialog failed
            if self.root.winfo_exists(): self.root.after(10, self.update_ui_state)
            print("Restarting global listener after capture attempt...")
            # Ensure listener restarts even after dialog error
            if self.root.winfo_exists(): self.root.after(150, self.start_hotkey_listener) # Restart main listener
 
        # Apply captured value if successful
        if captured_value is not None:
            print(f"Capture successful: Type={capture_type}, Val='{captured_value}'")
            if capture_type == 'mouse': self.mouse_hotkey_str.set(captured_value); self.apply_hotkey('mouse')
            elif capture_type == 'keyboard': self.keyboard_hotkey_str.set(captured_value); self.apply_hotkey('keyboard')
            elif capture_type == 'target_key' and index is not None:
                if index < len(self.keyboard_target_keys):
                    self.keyboard_target_keys[index].set(captured_value); self._apply_target_key(index)
                else: print(f"Error: Index {index} invalid after capture.")
        else: print(f"Capture cancelled or failed.")
 
 
    # --- System Tray Logic ---
    def create_image(self, width: int, height: int, color1: str, color2: str) -> Optional['Image.Image']:
        """Creates a simple image for the tray icon."""
        global Image, ImageDraw
        if 'Image' not in globals() or Image is None:
             print("Error: Pillow (PIL) unavailable for tray image."); return None
        try:
            im = Image.new('RGB', (width, height), color1)
            dc = ImageDraw.Draw(im)
            dc.rectangle((width // 2, 0, width, height // 2), fill=color2)
            dc.rectangle((0, height // 2, width // 2, height), fill=color2)
            return im
        except Exception as e: print(f"Error creating tray image: {e}"); return None
 
    def setup_tray(self):
        """Sets up the system tray icon and starts its thread."""
        global pystray
        if 'pystray' not in globals() or pystray is None:
             print("Info: pystray unavailable, tray disabled."); return
        try:
            image = self.create_image(64, 64, '#1E90FF', '#ADD8E6') # Blue colors
            if image is None: raise RuntimeError("Icon image creation failed.")
            menu = (pystray.MenuItem('显示窗口', self.show_window, default=True),
                    pystray.MenuItem('退出程序', self.quit_app))
            self.tray_icon = pystray.Icon(f"{APP_NAME}_Tray", image, f"高级连点器 V2.6.2", menu)
            self.tray_thread = threading.Thread(target=self.run_tray, daemon=True, name="PystrayThread")
            self.tray_thread.start()
            print("Tray icon setup complete.")
        except Exception as e: print(f"Error setting up tray: {e}"); self.tray_icon = None; self.tray_thread = None
 
    def run_tray(self):
        """Runs the pystray icon loop (target for tray_thread)."""
        if self.tray_icon:
            try:
                print("Pystray run loop starting.")
                self.tray_icon.run() # Blocks here until stop()
            except Exception as e: print(f"Error in tray loop: {e}")
            finally:
                print("Pystray run loop finished.") # Ensure this prints on exit
 
    def hide_window(self):
        """Hides the main application window."""
        if self.root and self.root.winfo_exists():
            try: self.root.withdraw(); print("Window hidden.")
            except tk.TclError as e: print(f"Error hiding window: {e}")
 
    def show_window(self, icon=None, item=None): # Args needed for pystray callback
        """Schedules showing the main window via the main Tkinter thread."""
        if self.root and self.root.winfo_exists():
             # Use after(0) for immediate scheduling in the main thread event loop
            self.root.after(0, self._show_window_task)
 
    def _show_window_task(self):
        """Actual window showing logic, executed in the main Tkinter thread."""
        if self.root and self.root.winfo_exists():
            try:
                self.root.deiconify(); # Make window visible
                # The following might be needed depending on OS/WM behavior
                self.root.lift(); # Raise above other windows
                self.root.focus_force() # Try to grab focus
 
                # Bring to front temporarily then release topmost status
                # This helps ensure visibility but respects user's request not to *stay* topmost
                self.root.attributes('-topmost', True)
                self.root.after(200, lambda: self.safe_set_topmost(False))
 
                print("Window shown via _show_window_task.")
            except tk.TclError as e: print(f"Error in _show_window_task: {e}")
 
    def safe_set_topmost(self, value: bool):
        """Safely sets the topmost attribute."""
        try:
            if self.root and self.root.winfo_exists(): self.root.attributes('-topmost', value)
        except tk.TclError: pass
 
 
    # --- Close Button Handler ---
    def on_close_requested(self):
        """Handles the WM_DELETE_WINDOW event (clicking the 'X' button)."""
        if self._shutting_down: return
        tray_ok = self.tray_icon and self.tray_thread and self.tray_thread.is_alive()
        if tray_ok:
            result = messagebox.askyesnocancel("操作确认", "最小化到系统托盘还是直接退出程序?\n\n  [是] = 最小化\n  [否] = 退出\n[取消] = 返回", icon='question', parent=self.root)
            if result is True: self.hide_window() # Yes = Minimize
            elif result is False: self.quit_app() # No = Exit
            # else: Cancel = Do nothing
        else: # Tray not available
            if messagebox.askokcancel("退出确认", "系统托盘不可用。\n确定要退出程序吗?", icon='warning', parent=self.root):
                 self.quit_app() # OK = Exit
             # else: Cancel = Do nothing
 
 
    # --- Configuration Saving and Loading ---
    def load_config(self):
        """Loads configuration from the JSON file."""
        config_path = get_config_path()
        print(f"Loading config from: {config_path}")
        if not config_path.exists():
            print("Config file not found. Using defaults.")
            self.status_text.set("状态: 已停止 | 使用默认")
            # Add default empty rows if none exist
            if self.current_key_row_count == 0:
                for _ in range(DEFAULT_AUTOMATION_KEYS): self.add_key_row(update_scroll=False)
                if self.keys_canvas: self.keys_canvas.after(50, self.update_canvas_scrollregion)
            return
 
        try:
            with open(config_path, 'r', encoding='utf-8') as f: config_data = json.load(f)
            print("Config loaded.")
 
            # Apply Mouse settings safely
            mouse_cfg = config_data.get("mouse", {})
            self.click_interval.set(mouse_cfg.get("interval", 0.01))
            self.selected_click_type.set(mouse_cfg.get("click_type", "left"))
            self.mouse_hotkey_str.set(mouse_cfg.get("hotkey", "Key.f8"))
            self.mouse_duration.set(mouse_cfg.get("duration", 0.0))
 
            # Apply Keyboard settings safely
            kb_cfg = config_data.get("keyboard", {})
            self.keyboard_hotkey_str.set(kb_cfg.get("hotkey", "Key.f7"))
            self.keyboard_mode.set(kb_cfg.get("mode", "sequential"))
            self.keyboard_cycle_delay.set(kb_cfg.get("cycle_delay", 0.1))
            self.keyboard_duration.set(kb_cfg.get("duration", 0.0))
 
            # Load dynamic rows
            loaded_keys = kb_cfg.get("target_keys", [])
            loaded_delays = kb_cfg.get("target_delays", [])
            num_to_load = min(len(loaded_keys), len(loaded_delays), MAX_AUTOMATION_KEYS)
 
            self._clear_key_rows() # Clear existing before loading
            print(f"Loading {num_to_load} key rows from config...")
            for i in range(num_to_load):
                key_str = str(loaded_keys[i]) if loaded_keys[i] is not None else ""
                delay_val = 0.0
                try: delay_val = float(loaded_delays[i]) if loaded_delays[i] is not None else 0.0
                except (ValueError, TypeError): pass
                self.add_key_row(key_value=key_str, delay_value=max(0.0, delay_val), update_scroll=False)
 
            # Optionally add empty rows if loaded count is less than default
            # rows_to_add = DEFAULT_AUTOMATION_KEYS - num_to_load
            # if rows_to_add > 0:
            #    for _ in range(rows_to_add): self.add_key_row(update_scroll=False)
 
            if self.keys_canvas: self.keys_canvas.after(50, self.update_canvas_scrollregion)
            self.status_text.set("状态: 已停止 | 配置已加载")
 
        except FileNotFoundError: print("Config file disappeared.") # Should be caught above
        except json.JSONDecodeError as e: print(f"Error decoding config: {e}"); messagebox.showerror("配置错误", f"配置文件格式错误: {e}", parent=self.root)
        except Exception as e: print(f"Error loading config: {e}"); traceback.print_exc(); messagebox.showerror("配置错误", f"加载配置时出错: {e}", parent=self.root)
 
 
    def save_config(self):
        """Saves the current configuration to the JSON file."""
        config_path = get_config_path()
        print(f"Saving config to: {config_path}")
        try: config_path.parent.mkdir(parents=True, exist_ok=True)
        except Exception as e: print(f"Error ensuring config dir exists: {e}"); return
 
        config_data = {
            "app_version": "2.6.2", # Update version in saved config
            "mouse": { "interval": self.click_interval.get(), "click_type": self.selected_click_type.get(), "hotkey": self.mouse_hotkey_str.get(), "duration": self.mouse_duration.get() },
            "keyboard": { "hotkey": self.keyboard_hotkey_str.get(), "mode": self.keyboard_mode.get(), "cycle_delay": self.keyboard_cycle_delay.get(), "duration": self.keyboard_duration.get(),
                         "target_keys": [var.get() for var in self.keyboard_target_keys], "target_delays": [var.get() for var in self.keyboard_target_delays] }
        }
        try:
            with open(config_path, 'w', encoding='utf-8') as f: json.dump(config_data, f, indent=4, ensure_ascii=False)
            print("Config saved successfully.")
        except Exception as e: print(f"Error saving config: {e}"); traceback.print_exc(); messagebox.showerror("保存错误", f"无法保存配置: {e}", parent=self.root)
 
 
    # --- Application Exit ---
    def quit_app(self, icon=None, item=None): # Args needed for pystray callback
        """Stops processes, saves config, and exits cleanly."""
        if self._shutting_down: return
        print("Quit requested. Shutting down..."); self._shutting_down = True
 
        # Stop ongoing operations
        if self.is_running_mouse: self.stop_clicking()
        if self.is_running_keyboard: self.stop_keyboard_automation()
 
        # Stop listener gracefully
        self.stop_hotkey_listener(wait=True)
 
        # Stop tray icon thread
        if self.tray_icon and hasattr(self.tray_icon, 'stop'):
            try: self.tray_icon.stop()
            except Exception as e: print(f"Minor error stopping tray icon: {e}")
        if self.tray_thread and self.tray_thread.is_alive():
             print("Waiting for tray thread to exit...")
             self.tray_thread.join(timeout=1.0)
             if self.tray_thread.is_alive(): print(" Warning: Tray thread join timed out.")
             else: print(" Tray thread exited.")
 
        # Save config before destroying window
        self.save_config()
 
        # Destroy GUI window
        if self.root and self.root.winfo_exists():
            try: self.root.destroy()
            except tk.TclError: pass
            except Exception as e: print(f"Error destroying root: {e}")
        print("Shutdown sequence finished.")
        # Force exit if shutdown hangs (rarely needed with proper thread joining)
        # sys.exit(0) # Usually not needed if all daemon threads exit
 
# --- End of AutoClickerApp Class ---
 
 
# --- Hotkey Capture Dialog Class ---
class HotkeyCaptureDialog(Toplevel):
    """Modal dialog for capturing keys/hotkeys using temporary listeners."""
    def __init__(self, parent: tk.Tk, parent_app_ref: AutoClickerApp, capture_type: str, index: Optional[int] = None):
        super().__init__(parent)
        self.transient(parent)
        self.parent_app = parent_app_ref
        self.capture_type = capture_type
        self.listener_kb: Optional['KeyboardListener'] = None
        self.listener_mouse: Optional['MouseListener'] = None
        self.captured_raw_keys: Set[PynputKeyType] = set()
        self.result: Optional[str] = None
        self.confirmed = False
        self._stop_event = threading.Event() # Added for safer listener stop
 
        global KeyboardListener, MouseListener # Assumes these were imported successfully
        if 'KeyboardListener' not in globals(): raise RuntimeError("Pynput unavailable for capture")
 
        title = "采集热键"; info = "请按下并松开要设置的键盘/组合键..."
        self.allow_combinations = True; self.listen_mouse = True
        if capture_type == 'target_key':
            title = f"采集目标按键 {index + 1}" if index is not None else "采集目标按键"
            info = "请按下并松开 单个 键盘按键或鼠标按钮..."
            self.allow_combinations = False
 
        self.title(title); self.geometry("380x150"); self.resizable(False, False) # Slightly smaller height
        self.protocol("WM_DELETE_WINDOW", self.cancel); self.grab_set()
 
        # Widgets (Reduced padding)
        main_frame = ttk.Frame(self, padding=5); main_frame.pack(expand=True, fill=tk.BOTH)
        ttk.Label(main_frame, text=info, justify=tk.CENTER, wraplength=360).pack(pady=(3, 5))
        self.status_var = tk.StringVar(value="请按键..."); self.status_label = ttk.Label(main_frame, textvariable=self.status_var, justify=tk.CENTER, font=("", 10, "bold"), foreground="blue")
        self.status_label.pack(pady=3)
        ttk.Button(main_frame, text="取消", command=self.cancel).pack(pady=(5, 3))
 
        self._start_listeners(); self.focus_force(); self._center_dialog()
 
    def _center_dialog(self):
        """Centers the dialog relative to the parent window."""
        try:
            self.update_idletasks()
            parent = self.master
            if not parent: return
            parent_x, parent_y = parent.winfo_rootx(), parent.winfo_rooty()
            parent_w, parent_h = parent.winfo_width(), parent.winfo_height()
            dialog_w, dialog_h = self.winfo_width(), self.winfo_height()
            x = parent_x + (parent_w - dialog_w) // 2
            y = parent_y + (parent_h - dialog_h) // 2
            self.geometry(f"+{x}+{y}")
        except Exception as e: print(f"Could not center dialog: {e}")
 
    def _start_listeners(self):
        """Starts local listeners for this dialog."""
        global KeyboardListener, MouseListener
        self._stop_event.clear()
        try:
            # Pass stop event for cleaner shutdown
            self.listener_kb = KeyboardListener(
                on_press=self.on_press, on_release=self.on_release,
                suppress=False, stop_event=self._stop_event
            )
            self.listener_kb.start()
            if self.listen_mouse:
                self.listener_mouse = MouseListener(
                    on_click=self.on_click, suppress=False,
                    stop_event=self._stop_event
                )
                self.listener_mouse.start()
        except TypeError: # Handle older pynput versions without stop_event
             print("Warning: Using pynput version without stop_event. Capture stop might be less reliable.")
             self.listener_kb = KeyboardListener(on_press=self.on_press, on_release=self.on_release, suppress=False)
             self.listener_kb.start()
             if self.listen_mouse:
                 self.listener_mouse = MouseListener(on_click=self.on_click, suppress=False)
                 self.listener_mouse.start()
        except Exception as e: print(f"Error starting capture listeners: {e}"); self.cancel() # Cancel if fail
 
    def _update_status(self, text: str, color: str = "blue"):
        """Safely schedules status label update."""
        if hasattr(self, 'status_var') and self.winfo_exists():
            try: self.parent_app.root.after(0, lambda: self._do_update(text, color) if self.winfo_exists() else None)
            except tk.TclError: pass
 
    def _do_update(self, text, color):
        """Actual status update in main thread."""
        if self.winfo_exists() and self.status_label and self.status_label.winfo_exists():
            try: self.status_var.set(text); self.status_label.config(foreground=color)
            except tk.TclError: pass
 
    def on_press(self, key_raw):
        if self.confirmed or self._stop_event.is_set() or key_raw is None: return
        if not self.allow_combinations: self.captured_raw_keys.clear()
        self.captured_raw_keys.add(key_raw)
        self._update_status(f"已按下: {self.parent_app.format_hotkey_set(self.captured_raw_keys)}")
 
    def on_release(self, key_raw):
        if self.confirmed or self._stop_event.is_set() or key_raw is None or key_raw not in self.captured_raw_keys: return
        # Check for validity *before* confirming
        is_valid = True
        if not self.allow_combinations and len(self.captured_raw_keys) > 1:
             self._update_status("错误: 只能采集单个按键!", color="red"); self.captured_raw_keys.clear(); is_valid = False
        elif not self.captured_raw_keys: # Should not happen if key_raw was in set
             self._update_status("未采集到按键", color="red"); is_valid = False
 
        if is_valid:
            try:
                self.result = self.parent_app.format_hotkey_set(self.captured_raw_keys)
                self._update_status(f"已捕获: {self.result}", color="green")
                # Schedule confirmation slightly later to allow UI update
                self.after(50, self.confirm)
            except Exception as e:
                self._update_status(f"格式化错误: {e}", color="red"); self.captured_raw_keys.clear()
 
 
    def on_click(self, x, y, button_raw, pressed):
        if self.confirmed or self._stop_event.is_set() or not self.listen_mouse or button_raw is None: return
        if pressed:
            if not self.allow_combinations: self.captured_raw_keys.clear()
            self.captured_raw_keys.add(button_raw)
            self._update_status(f"已按下: {self.parent_app.format_hotkey_set(self.captured_raw_keys)}")
        elif button_raw in self.captured_raw_keys: # On release
             # Check for validity *before* confirming
             is_valid = True
             if not self.allow_combinations and len(self.captured_raw_keys) > 1:
                  self._update_status("错误: 只能采集单个按钮!", color="red"); self.captured_raw_keys.clear(); is_valid = False
             elif not self.captured_raw_keys:
                  self._update_status("未采集到按键", color="red"); is_valid = False
 
             if is_valid:
                 try:
                     self.result = self.parent_app.format_hotkey_set(self.captured_raw_keys)
                     self._update_status(f"已捕获: {self.result}", color="green")
                     self.after(50, self.confirm)
                 except Exception as e:
                     self._update_status(f"格式化错误: {e}", color="red"); self.captured_raw_keys.clear()
 
    def confirm(self):
        if self.confirmed: return; self.confirmed = True
        self._stop_listeners(); self.destroy()
 
    def cancel(self):
        if self.confirmed: return; self.confirmed = True
        self.result = None; self._stop_listeners(); self.destroy()
 
    def _stop_listeners(self):
        """Stops the local pynput listeners safely."""
        if self._stop_event.is_set(): return # Already stopping/stopped
        print("Stopping local capture listeners...")
        self._stop_event.set() # Signal listeners using stop_event
 
        kb_listener = self.listener_kb
        m_listener = self.listener_mouse
        self.listener_kb = None # Clear references
        self.listener_mouse = None
 
        # Attempt direct stop as fallback or if stop_event not supported
        if kb_listener and hasattr(kb_listener, 'stop'):
             try: kb_listener.stop()
             except Exception as e: print(f"  Error stopping capture KB listener: {e}")
        if m_listener and hasattr(m_listener, 'stop'):
             try: m_listener.stop()
             except Exception as e: print(f"  Error stopping capture Mouse listener: {e}")
 
        # No join needed here, dialog destruction handles thread cleanup implicitly if daemonic
        print("Local capture listeners stop requested.")
 
    def show(self) -> Optional[str]:
        self.wait_window(self); return self.result
 
 
# --- Main Execution Block ---
if __name__ == "__main__":
    main_root: Optional[tk.Tk] = None
    app: Optional[AutoClickerApp] = None
    missing_lib = ""
 
    try: # Import and initialize mandatory components
        print("Importing pynput...")
        from pynput import mouse, keyboard
        # Explicitly import required classes for clarity
        from pynput.mouse import Button as PynputMouseButton
        from pynput.mouse import Controller as MouseController
        from pynput.mouse import Listener as MouseListener
        from pynput.keyboard import Key as PynputKey
        from pynput.keyboard import KeyCode as PynputKeyCode
        from pynput.keyboard import Controller as KeyboardController
        from pynput.keyboard import Listener as KeyboardListener
 
        Button, Key, KeyCode = PynputMouseButton, PynputKey, PynputKeyCode # Make available globally
        PynputKeyType = Union[Key, KeyCode, Button] # Redefine type hint
 
        print("Importing optional: pystray, Pillow...")
        try: import pystray; from PIL import Image, ImageDraw
        except ImportError as opt_err:
            missing_lib = str(opt_err).split(" ")[-1].strip("'")
            print(f"Warning: Optional '{missing_lib}' not found. Tray features disabled.")
            if 'pystray' in missing_lib: pystray = None
            if 'PIL' in missing_lib or 'Image' in missing_lib: Image, ImageDraw = None, None
 
        print("Initializing controllers..."); mouse_controller = MouseController(); keyboard_controller = KeyboardController(); print("Controllers OK.")
 
    except ImportError as core_err: # Handle missing pynput
        missing_lib = str(core_err).split(" ")[-1].strip("'"); install_cmd = f"pip install {missing_lib}"
        print(f"错误: 核心库 {missing_lib} 未安装。\n请运行: {install_cmd}", file=sys.stderr)
        try: temp_root = tk.Tk(); temp_root.withdraw(); messagebox.showerror("依赖错误", f"缺少核心库 '{missing_lib}'.\n请安装: {install_cmd}"); temp_root.destroy()
        except Exception: pass; sys.exit(1)
    except Exception as init_err: # Handle other init errors
        print(f"启动错误: {init_err}", file=sys.stderr); traceback.print_exc(file=sys.stderr)
        try: temp_root = tk.Tk(); temp_root.withdraw(); messagebox.showerror("启动错误", f"程序启动失败:\n{init_err}"); temp_root.destroy()
        except Exception: pass; sys.exit(1)
 
    # Run the Application if imports/init succeeded
    try:
        main_root = tk.Tk()
        # Apply theme
        try:
            style = ttk.Style(); themes = style.theme_names(); pref = ['vista','clam','alt','default']
            if platform.system() == "Windows": pref.insert(0,'xpnative') # Try xpnative/vista on Win
            if platform.system() == "Darwin": pref.insert(0,'aqua')
            theme = next((t for t in pref if t in themes), style.theme_use())
            if theme: style.theme_use(theme); print(f"Using theme: {theme}")
        except Exception as e_style: print(f"Theme error: {e_style}")
 
        app = AutoClickerApp(main_root) # Create application instance
        print("Starting main loop...")
        main_root.mainloop() # Start GUI event loop
        print("Main loop finished.")
 
    except KeyboardInterrupt:
         print("\nCtrl+C pressed. Exiting...");
         if app: app.quit_app()
         else: sys.exit(1)
    except Exception as main_e: # Catch runtime errors
        print(f"\n--- 主程序运行时发生错误 ---", file=sys.stderr); print(f"{type(main_e).__name__}: {main_e}", file=sys.stderr); traceback.print_exc(file=sys.stderr)
        print("--- 尝试关闭 ---", file=sys.stderr)
        try:
            if app: app.quit_app()
            else: os._exit(1) # Force exit if app instance not created
        except Exception: os._exit(1) # Force exit on shutdown error
    finally: print("应用程序退出。")
4#
jjyybou 发表于 2025-4-10 06:22
5#
IcePlume 发表于 2025-4-10 06:43
本来还想读读代码,一看有两千多行直接放弃
6#
LOUI55 发表于 2025-4-10 07:23

以后可能有用,收藏起来
7#
cjwq1224 发表于 2025-4-10 08:03
感谢分享,点击方便多了
8#
aigaboy 发表于 2025-4-10 08:19
留存,真能用上的时候可就相当的省时省力了
9#
Lcp1027 发表于 2025-4-10 08:29
感谢精彩的分享
10#
Airiair 发表于 2025-4-10 08:33
请问下有识图功能吗
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2025-8-12 08:37

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表