wz-editor 0.0.1

冒险岛wz素材浏览编辑器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
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
//! WZ 浏览器 / WZ resource browser(bin/wz_editor)
//!
//! 老杨的两条硬要求 / Two hard requirements from LaoYang:
//!   1. 启动**不再**加载任何默认路径的 WZ 文件。旧实现在 `Default::default()` 里写死
//!      `resolve_base("./Data/Base.wz", None).unwrap()` —— 路径不对直接 panic。
//!      现在启动时是空界面,必须手动选文件。
//!   2. 左上角「打开 Base.wz…」按钮呼出**文件选择窗口**,选中 `Base.wz` 后再加载。
//!
//! 顺带精进的浏览器能力 / Browser improvements:
//!   - 加载走后台线程 + 加载中遮罩(Map.wz 几百 MB,解析要几秒,不能卡死界面)
//!   - 左侧树:搜索过滤(命中自动展开)、路径跳转、超大目录截断提示
//!   - 右侧预览:PNG 缩放 / 最近邻贴合像素画 / 复制图片 / 导出 PNG、音效播放、JSON 预览
//!   - 底部状态栏:当前路径、子节点数、加载耗时、错误提示(失败不再 panic,只提示)
//!
//! Run:
//!   cargo run --bin wz_editor

use clipboard_rs::common::{RustImage, RustImageData};
use clipboard_rs::{Clipboard, ClipboardContext};
use eframe::egui;
use egui::collapsing_header::CollapsingState;
use egui::{Color32, Id, Rect, RichText, TextureHandle, Ui};
use font_kit::{family_name::FamilyName, handle::Handle, properties::Properties, source::SystemSource};
use image::DynamicImage;
use image::EncodableLayout;
use rodio::{DeviceSinkBuilder, MixerDeviceSink, Player, play};
use serde_json::{Map, Number, Value};
use std::collections::HashMap;
use std::collections::VecDeque;
use std::fs;
use std::io::Cursor;
use std::path::PathBuf;
use std::sync::mpsc::{Receiver, TryRecvError, channel};
use std::sync::Arc;
use std::thread;
use std::time::{Duration, Instant};
use wz_reader::property::{Vector2D, WzSubProperty, WzValue};
use wz_reader::util::node_util;
use wz_reader::util::resolve_base;
use wz_reader::{WzNodeArc, WzObjectType};

/// JSON 预览最大节点数:防止选中 `Map` 之类的大目录把界面解析卡死。
/// Max nodes rendered into the JSON preview.
const MAX_JSON_NODES: usize = 4000;
/// 图片缓存上限(条)
/// Max number of decoded images kept in memory.
const IMAGE_CACHE_CAP: usize = 48;
/// 单个目录一次最多渲染的子项数(其余用搜索过滤)
/// Max children rendered per directory in one frame.
const MAX_VISIBLE_CHILDREN: usize = 500;
/// 左栏(节点树)默认 / 最小宽度,以及右栏最小宽度(都含边距)
/// Default / minimum width of the tree column, and the minimum width kept for the preview column.
const TREE_WIDTH_DEFAULT: f32 = 320.0;
const TREE_WIDTH_MIN: f32 = 180.0;
const RIGHT_MIN_WIDTH: f32 = 320.0;
/// 两栏之间可拖拽的分隔条宽度
/// Width of the draggable splitter between the two columns.
const SPLITTER_WIDTH: f32 = 6.0;
/// 左栏宽度落盘位置(eframe 的 persistence feature 没开,自己存一个就行)
/// Where the tree width is persisted (eframe's `persistence` feature is off).
const TREE_WIDTH_FILE: &str = "wz_editor_tree_width.txt";

/// 读取上次记住的左栏宽度
/// Load the remembered tree-column width.
fn load_tree_width() -> f32 {
    let path = std::env::temp_dir().join(TREE_WIDTH_FILE);
    let Ok(text) = std::fs::read_to_string(path) else {
        return TREE_WIDTH_DEFAULT;
    };
    text.trim().parse::<f32>().unwrap_or(TREE_WIDTH_DEFAULT)
}

/// 记住左栏宽度(失败无所谓,不影响使用)
/// Remember the tree-column width (failures are harmless).
fn save_tree_width(width: f32) {
    let path = std::env::temp_dir().join(TREE_WIDTH_FILE);
    let _ = std::fs::write(path, format!("{width:.0}"));
}

// ───────────────────────────────── 入口 ─────────────────────────────────

fn main() -> eframe::Result {
    let options = eframe::NativeOptions {
        viewport: egui::ViewportBuilder::default().with_inner_size([1280.0, 800.0]),
        ..Default::default()
    };
    eframe::run_native(
        "WZ 浏览器 / wz_editor",
        options,
        Box::new(|cc| {
            load_system_font(&cc.egui_ctx);
            Ok(Box::<WzEditorApp>::default())
        }),
    )
}

/// 载入系统中文字体(任一候选命中即可;全部失败就保留 egui 默认字体,绝不 panic)。
/// Load a CJK font from the system; fall back to egui's default font on failure.
fn load_system_font(ctx: &egui::Context) {
    const FONT_NAME: &str = "SystemCJK";
    let candidates = [
        "Microsoft YaHei",
        "PingFang SC",
        "SimSun",
        "Noto Sans CJK SC",
    ];

    let mut font_bytes: Option<Vec<u8>> = None;
    for family in candidates {
        let Ok(handle) = SystemSource::new().select_best_match(
            &[FamilyName::Title(family.to_string())],
            &Properties::new(),
        ) else {
            continue;
        };
        match handle {
            Handle::Memory { bytes, .. } => font_bytes = Some(bytes.to_vec()),
            Handle::Path { path, .. } => font_bytes = fs::read(path).ok(),
        }
        if font_bytes.is_some() {
            break;
        }
    }

    let Some(font_bytes) = font_bytes else {
        return;
    };

    let mut fonts = egui::FontDefinitions::empty();
    fonts
        .font_data
        .insert(FONT_NAME.to_owned(), Arc::new(egui::FontData::from_owned(font_bytes)));
    for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] {
        fonts
            .families
            .entry(family)
            .or_default()
            .push(FONT_NAME.to_owned());
    }
    ctx.set_fonts(fonts);
}

// ─────────────────────────── WZ 值 → JSON ───────────────────────────

/// `WzValue` → `serde_json::Value`(wz_reader 的 `json` feature 未开,自己转,够用且可控)。
/// Convert a WZ value to JSON (wz_reader's `json` feature is off, so we do it ourselves).
fn wz_value_to_json(value: &WzValue) -> Value {
    match value {
        WzValue::Null => Value::Null,
        WzValue::Short(value) => Value::from(*value),
        WzValue::Int(value) => Value::from(*value),
        WzValue::Long(value) => Value::from(*value),
        WzValue::Float(value) => number_from_f64(*value as f64),
        WzValue::Double(value) => number_from_f64(*value),
        WzValue::Vector(Vector2D(x, y)) => {
            let mut map = Map::new();
            map.insert("x".to_string(), Value::from(*x));
            map.insert("y".to_string(), Value::from(*y));
            Value::Object(map)
        }
        // `WzString` 需要读 WZ 字节流才能拿到真实字符串
        // `WzString` needs to read from the WZ byte stream.
        WzValue::UOL(value) | WzValue::String(value) => {
            Value::String(value.get_string().unwrap_or_default())
        }
        WzValue::ParsedString(value) => Value::String(value.clone()),
        WzValue::RawData(_) => Value::String("<raw data>".to_string()),
        WzValue::Video(_) => Value::String("<video>".to_string()),
        WzValue::Lua(_) => Value::String("<lua>".to_string()),
    }
}

fn number_from_f64(value: f64) -> Value {
    match Number::from_f64(value) {
        Some(number) => Value::Number(number),
        None => Value::Null,
    }
}

/// 递归把节点及其子树转成 JSON,`budget` 控制最大节点数(超了就截断)。
/// Recursively turn a node subtree into JSON; `budget` caps the work.
fn walk_node_to_json(node_arc: &WzNodeArc, json: &mut Map<String, Value>, budget: &mut usize) {
    if *budget == 0 {
        return;
    }
    *budget -= 1;

    // 惰性节点(如未解析的 .img)先解析,解析失败就当占位符输出
    // Lazily parse unparsed nodes; on failure emit a placeholder.
    if node_util::parse_node(node_arc).is_err() {
        let name = node_arc.read().unwrap().name.as_str().to_string();
        json.insert(name, Value::String("<parse error>".to_string()));
        return;
    }

    let (name, children, object_type) = {
        let node = node_arc.read().unwrap();
        (
            node.name.as_str().to_string(),
            node.children.values().cloned().collect::<Vec<WzNodeArc>>(),
            node.object_type.clone(),
        )
    };

    match object_type {
        WzObjectType::Value(value) => {
            json.insert(name, wz_value_to_json(&value));
        }
        WzObjectType::Property(WzSubProperty::PNG(png)) => {
            json.insert(
                name,
                Value::String(format!(
                    "<png {}x{} {:?}>",
                    png.width,
                    png.height,
                    png.format()
                )),
            );
        }
        WzObjectType::Property(WzSubProperty::Sound(sound)) => {
            json.insert(
                name,
                Value::String(format!("<sound {:?} {}ms>", sound.sound_type, sound.duration)),
            );
        }
        WzObjectType::Property(WzSubProperty::Convex) => {
            json.insert(name, Value::String("<convex>".to_string()));
        }
        _ => {
            if children.is_empty() {
                json.insert(name, Value::Null);
                return;
            }
            let mut child_json = Map::new();
            for child in &children {
                walk_node_to_json(child, &mut child_json, budget);
            }
            json.insert(name, Value::Object(child_json));
        }
    }
}

/// 生成节点子树的 JSON 文本(带节点数上限)。
/// Build the JSON text of a node subtree (capped).
fn node_to_json(node_arc: &WzNodeArc) -> String {
    let mut json = Map::new();
    let mut budget = MAX_JSON_NODES;
    {
        let children: Vec<WzNodeArc> = node_arc.read().unwrap().children.values().cloned().collect();
        for child in &children {
            walk_node_to_json(child, &mut json, &mut budget);
        }
    }
    let mut text = serde_json::to_string_pretty(&Value::Object(json)).unwrap_or_default();
    if budget == 0 {
        text.push_str("\n…(节点过多,已截断)");
    }
    text
}

fn type_of<T>(_: &T) -> String {
    std::any::type_name::<T>().to_string()
}

// ─────────────────────────── 文件选择窗口 ───────────────────────────

/// 目录里的一个条目(目录或文件)
/// One entry (dir or file) inside the picker's current directory.
#[derive(Clone)]
struct PickerEntry {
    path: PathBuf,
    name: String,
    is_dir: bool,
    size: Option<u64>,
}

/// 文件选择窗口的用途:选 WZ 数据文件 / 选一张替换用的图片
/// What the picker is for: pick a WZ data file, or pick a replacement image.
#[derive(Clone, Copy, PartialEq, Eq)]
enum PickerMode {
    /// 选 WZ 数据文件(必须是 Base.wz)
    Wz,
    /// 选一张图片(右键「替换图片」用)
    Image,
}

impl PickerMode {
    fn title(self) -> &'static str {
        match self {
            PickerMode::Wz => "打开 WZ 文件(请选择 Base.wz)",
            PickerMode::Image => "选择替换用的图片",
        }
    }

    /// 该模式下允许显示的文件扩展名
    /// File extensions shown in this mode.
    fn matches_extension(self, extension: &str) -> bool {
        let targets = match self {
            PickerMode::Wz => ["wz"].as_slice(),
            PickerMode::Image => ["png", "jpg", "jpeg", "bmp", "gif", "webp", "tga"].as_slice(),
        };
        targets
            .iter()
            .any(|target| extension.eq_ignore_ascii_case(target))
    }

    fn filter_label(self) -> &'static str {
        match self {
            PickerMode::Wz => "只看 .wz",
            PickerMode::Image => "只看图片",
        }
    }
}

/// 「打开 WZ 文件 / 选择图片」窗口:纯 egui 实现,不引入新的第三方依赖。
/// The file-picker window, built purely with egui (no new dependencies).
struct FilePicker {
    /// 窗口是否打开
    open: bool,
    /// 当前用途(选 WZ 还是选图片)
    mode: PickerMode,
    current_dir: PathBuf,
    path_input: String,
    entries: Vec<PickerEntry>,
    selected: Option<PathBuf>,
    /// 只显示当前模式关心的文件
    only_filtered: bool,
    error: Option<String>,
    need_refresh: bool,
    /// 最近打开过的 Base.wz,作为快捷入口
    last_opened: Option<PathBuf>,
}

impl FilePicker {
    fn new() -> Self {
        let start_dir = detect_start_dir();
        let mut picker = Self {
            open: false,
            mode: PickerMode::Wz,
            current_dir: start_dir.clone(),
            path_input: start_dir.display().to_string(),
            entries: Vec::new(),
            selected: None,
            only_filtered: true,
            error: None,
            need_refresh: true,
            last_opened: None,
        };
        picker.refresh();
        picker
    }

    /// 打开窗口(顺便刷新当前目录)
    /// Open the window (and refresh the listing).
    fn show(&mut self, mode: PickerMode) {
        self.mode = mode;
        self.open = true;
        self.need_refresh = true;
        self.selected = None;
        self.error = None;
    }

    fn enter_dir(&mut self, dir: PathBuf) {
        self.current_dir = dir;
        self.path_input = self.current_dir.display().to_string();
        self.error = None;
        self.refresh();
    }

    /// 重新列出当前目录条目
    /// Re-list the entries of the current directory.
    fn refresh(&mut self) {
        self.entries.clear();
        let Ok(read_dir) = fs::read_dir(&self.current_dir) else {
            self.error = Some(format!("无法读取目录:{}", self.current_dir.display()));
            return;
        };

        for entry in read_dir.flatten() {
            let path = entry.path();
            let Some(name) = path.file_name().map(|value| value.to_string_lossy().to_string()) else {
                continue;
            };
            let is_dir = path.is_dir();
            let wanted = path
                .extension()
                .map(|extension| self.mode.matches_extension(&extension.to_string_lossy()))
                .unwrap_or(false);
            if !is_dir && self.only_filtered && !wanted {
                continue;
            }
            let size = entry.metadata().ok().map(|metadata| metadata.len());
            self.entries.push(PickerEntry {
                path,
                name,
                is_dir,
                size,
            });
        }

        // 目录在前,文件在后,各自按名称排序
        // Directories first, then files; each sorted by name.
        self.entries.sort_by(|left, right| {
            right
                .is_dir
                .cmp(&left.is_dir)
                .then_with(|| left.name.to_lowercase().cmp(&right.name.to_lowercase()))
        });
    }

    /// 绘制窗口;返回用户确认要打开的 `Base.wz` 路径。
    /// Draw the window; returns the confirmed `Base.wz` path, if any.
    fn ui(&mut self, ctx: &egui::Context) -> Option<PathBuf> {
        if !self.open {
            return None;
        }
        if self.need_refresh {
            self.refresh();
            self.need_refresh = false;
        }

        let mut open = self.open;
        let mut confirmed: Option<PathBuf> = None;
        // 窗口内部的关闭请求(确认 / 双击 / 取消)。
        // 不能直接改 self.open:本帧末尾会用 `open`(窗口标题栏 X 的状态)回写覆盖掉。
        // Close requests from inside the window (confirm / double-click / cancel).
        // Can't set self.open directly: it gets overwritten by `open` (title-bar X state) at frame end.
        let mut close_requested = false;

        let mode = self.mode;
        egui::Window::new(mode.title())
            .open(&mut open)
            .collapsible(false)
            .resizable(true)
            .default_size([780.0, 540.0])
            .show(ctx, |ui| {
                // ── 第一行:路径导航 ──
                ui.horizontal(|ui| {
                    if let Some(parent) = self.current_dir.parent().map(|value| value.to_path_buf()) {
                        if ui.button("上一级").clicked() {
                            self.enter_dir(parent);
                        }
                    }
                    if ui.button("刷新").clicked() {
                        self.refresh();
                    }
                    ui.label(mode.filter_label());
                    if ui.checkbox(&mut self.only_filtered, "").changed() {
                        self.refresh();
                    }
                });

                ui.horizontal(|ui| {
                    ui.label("路径");
                    let response = ui.add(
                        egui::TextEdit::singleline(&mut self.path_input).desired_width(f32::INFINITY),
                    );
                    let go = response.lost_focus() && ui.input(|state| state.key_pressed(egui::Key::Enter));
                    if go || ui.button("前往").clicked() {
                        let target = PathBuf::from(self.path_input.trim());
                        if target.is_dir() {
                            self.enter_dir(target);
                        } else {
                            self.error = Some(format!("目录不存在:{}", target.display()));
                        }
                    }
                });

                // ── 快捷入口 ──
                ui.horizontal_wrapped(|ui| {
                    ui.label("快捷");
                    for drive in list_drives() {
                        if ui.button(drive.display().to_string()).clicked() {
                            self.enter_dir(drive);
                        }
                    }
                    if let Some(work_dir) = std::env::current_dir().ok() {
                        if ui.button("工作目录").clicked() {
                            self.enter_dir(work_dir.clone());
                        }
                        let data_dir = work_dir.join(".data");
                        if data_dir.is_dir() && ui.button("项目 .data").clicked() {
                            self.enter_dir(data_dir);
                        }
                    }
                    if let Some(last) = self.last_opened.clone() {
                        if ui.button("上次打开").clicked() {
                            if let Some(parent) = last.parent() {
                                self.enter_dir(parent.to_path_buf());
                                self.selected = Some(last);
                            }
                        }
                    }
                });

                ui.separator();

                // ── 条目列表 ──
                egui::ScrollArea::vertical()
                    .id_salt("wz_picker_list")
                    .show(ui, |ui| {
                        let entries = self.entries.clone();
                        for entry in &entries {
                            let is_selected = self.selected.as_deref() == Some(entry.path.as_path());
                            let size_text = entry
                                .size
                                .map(format_size)
                                .unwrap_or_else(|| "-".to_string());
                            let label = if entry.is_dir {
                                format!("[目录] {}", entry.name)
                            } else if mode == PickerMode::Image {
                                // 图片模式:顺带显示尺寸(只读文件头,不全解码)
                                match image::image_dimensions(&entry.path) {
                                    Ok((width, height)) => {
                                        format!("{}  ({}x{}, {})", entry.name, width, height, size_text)
                                    }
                                    Err(_) => format!("{}  ({})", entry.name, size_text),
                                }
                            } else {
                                format!("{}  ({})", entry.name, size_text)
                            };
                            let mut rich = RichText::new(label);
                            // Base.wz 高亮:只有它能作为根节点加载
                            if !entry.is_dir && entry.name == "Base.wz" {
                                rich = rich.color(Color32::from_rgb(0xc0, 0x30, 0x30)).strong();
                            }
                            let response = ui.selectable_label(is_selected, rich);
                            if response.clicked() {
                                if entry.is_dir {
                                    self.enter_dir(entry.path.clone());
                                } else {
                                    self.error = None;
                                    self.selected = Some(entry.path.clone());
                                }
                            }
                            if response.double_clicked() && !entry.is_dir {
                                self.selected = Some(entry.path.clone());
                                if let Some(path) = self.take_confirmed() {
                                    confirmed = Some(path);
                                    close_requested = true;
                                }
                            }
                        }
                    });

                ui.separator();

                // ── 底部:选中文件名 + 打开/取消 ──
                ui.horizontal(|ui| {
                    ui.label("文件");
                    let file_name = self
                        .selected
                        .as_ref()
                        .map(|path| path.display().to_string())
                        .unwrap_or_else(|| "(未选择)".to_string());
                    ui.add_enabled(
                        false,
                        egui::TextEdit::singleline(&mut file_name.clone()).desired_width(f32::INFINITY),
                    );
                });

                ui.horizontal(|ui| {
                    let enabled = self.selected.is_some();
                    let confirm_label = match mode {
                        PickerMode::Wz => "打开",
                        PickerMode::Image => "替换",
                    };
                    if ui.add_enabled(enabled, egui::Button::new(confirm_label)).clicked() {
                        if let Some(path) = self.take_confirmed() {
                            confirmed = Some(path);
                            // 确认成功(Wz 模式下即选定 Base.wz)→ 关闭选择窗口
                            close_requested = true;
                        }
                    }
                    if ui.button("取消").clicked() {
                        close_requested = true;
                    }
                });

                if let Some(error) = &self.error {
                    ui.colored_label(Color32::from_rgb(0xc0, 0x30, 0x30), error);
                } else if mode == PickerMode::Wz {
                    ui.label(
                        RichText::new("提示:必须选择 Base.wz(其他 .wz 只是数据分片,不能作为根节点)。")
                            .weak(),
                    );
                } else {
                    ui.label(
                        RichText::new("提示:替换只作用于当前会话的浏览/复制/导出,不会写回磁盘上的 WZ 文件。")
                            .weak(),
                    );
                }
            });

        // 标题栏 X(open=false)或窗口内主动关闭,都把窗口收起来
        // Closed either via title-bar X or from inside the window.
        self.open = open && !close_requested;
        confirmed
    }

    /// 校验并取走当前选中的文件
    /// Validate and take the selected file.
    /// - Wz 模式:只有 `Base.wz` 能通过
    /// - Image 模式:必须是能解码的图片
    fn take_confirmed(&mut self) -> Option<PathBuf> {
        let path = self.selected.clone()?;

        if self.mode == PickerMode::Wz {
            let is_base = path
                .file_name()
                .map(|name| name == "Base.wz")
                .unwrap_or(false);
            if !is_base {
                self.error = Some(format!(
                    "必须选择 Base.wz,当前选的是:{}",
                    path.display()
                ));
                return None;
            }
            self.error = None;
            self.last_opened = Some(path.clone());
            return Some(path);
        }

        // 图片模式:先探一下能不能解码(不然选了废图才报错很烦)
        match image::image_dimensions(&path) {
            Ok((width, height)) => {
                self.error = None;
                self.selected = None;
                let _ = (width, height);
                Some(path)
            }
            Err(error) => {
                self.error = Some(format!("不是可用的图片:{error}"));
                None
            }
        }
    }
}

/// 起始目录:优先项目约定的 `.data/`(sdlgms::wz::resolve_base 用的就是 `./.data/Base.wz`)。
/// Start directory: prefer the project's `.data/` folder.
fn detect_start_dir() -> PathBuf {
    let work_dir = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    let data_dir = work_dir.join(".data");
    if data_dir.is_dir() {
        data_dir
    } else {
        work_dir
    }
}

#[cfg(windows)]
fn list_drives() -> Vec<PathBuf> {
    ('C'..='Z')
        .map(|letter| PathBuf::from(format!("{letter}:\\")))
        .filter(|path| path.exists())
        .collect()
}

#[cfg(not(windows))]
fn list_drives() -> Vec<PathBuf> {
    Vec::new()
}

fn format_size(size: u64) -> String {
    const KB: u64 = 1024;
    const MB: u64 = KB * 1024;
    if size >= MB {
        format!("{:.1} MB", size as f64 / MB as f64)
    } else if size >= KB {
        format!("{:.1} KB", size as f64 / KB as f64)
    } else {
        format!("{size} B")
    }
}

// ─────────────────────────────── 左侧树 ───────────────────────────────

/// 左侧 WZ 节点树(选中 / 搜索 / 跳转状态)
/// The WZ node tree on the left (selection / search / jump state).
struct Tree {
    search: String,
    goto_path: String,
    selected: Option<WzNodeArc>,
    selected_path: String,
    error: Option<String>,
    /// 右键菜单触发、待 App 执行的动作
    pending_action: Option<TreeAction>,
    /// 右键「复制节点路径」待拷贝的内容
    pending_copy_path: Option<String>,
    /// 被替换过图片的节点(full path),树上打个 `*` 标记
    marked: std::collections::HashSet<String>,
}

impl Default for Tree {
    fn default() -> Self {
        Self {
            search: String::new(),
            goto_path: String::new(),
            selected: None,
            selected_path: String::new(),
            error: None,
            pending_action: None,
            pending_copy_path: None,
            marked: std::collections::HashSet::new(),
        }
    }
}

impl Tree {
    /// 重置(换 WZ 文件时调用)
    /// Reset (called when another WZ file is loaded).
    fn reset(&mut self) {
        self.selected = None;
        self.selected_path.clear();
        self.search.clear();
        self.error = None;
        self.pending_action = None;
        self.pending_copy_path = None;
        self.marked.clear();
    }

    /// 标记 / 取消标记「已替换图片」的节点
    /// Mark / un-mark a node as "image replaced".
    fn set_marked(&mut self, full_path: String, marked: bool) {
        if marked {
            self.marked.insert(full_path);
        } else {
            self.marked.remove(&full_path);
        }
    }

    /// 取走右键菜单产生的动作(App 执行)
    /// Take the pending right-click action (executed by the App).
    fn take_action(&mut self) -> Option<TreeAction> {
        self.pending_action.take()
    }

    /// 取走待复制的节点路径
    /// Take the pending path to copy.
    fn take_copy_path(&mut self) -> Option<String> {
        self.pending_copy_path.take()
    }

    fn is_selected(&self, node: &WzNodeArc) -> bool {
        self.selected
            .as_ref()
            .map(|selected| Arc::ptr_eq(selected, node))
            .unwrap_or(false)
    }

    fn select(&mut self, node: WzNodeArc) {
        let path = node.read().unwrap().get_path_from_root();
        self.selected_path = path;
        self.selected = Some(node);
    }

    fn try_parse(&mut self, node: &WzNodeArc) {
        if let Err(error) = node_util::parse_node(node) {
            self.error = Some(format!("解析节点失败:{error}"));
        }
    }

    /// 绘制整棵树,返回「选中项是否变化」(变了就停掉正在播放的音效)
    /// Draw the tree; returns whether the selection changed.
    fn ui(&mut self, ui: &mut Ui, root: &WzNodeArc) -> bool {
        ui.horizontal(|ui| {
            ui.label("搜索");
            ui.add(
                egui::TextEdit::singleline(&mut self.search)
                    .hint_text("名称关键字(大小写不敏感)")
                    .desired_width(f32::INFINITY),
            );
            if ui.button("清空").clicked() {
                self.search.clear();
            }
        });

        ui.horizontal(|ui| {
            ui.label("跳转");
            let response = ui.add(
                egui::TextEdit::singleline(&mut self.goto_path)
                    .hint_text("如 Skill/1111.img/skill/11111004")
                    .desired_width(f32::INFINITY),
            );
            let jump = response.lost_focus() && ui.input(|state| state.key_pressed(egui::Key::Enter));
            if jump || ui.button("前往").clicked() {
                self.goto(ui.ctx(), root);
            }
        });

        if let Some(error) = self.error.take() {
            ui.colored_label(Color32::from_rgb(0xc0, 0x30, 0x30), error);
        }

        ui.separator();

        egui::ScrollArea::vertical()
            .id_salt("wz_tree_scroll")
            .show(ui, |ui| self.children_ui(ui, root, 0))
            .inner
    }

    fn children_ui(&mut self, ui: &mut Ui, node: &WzNodeArc, depth: usize) -> bool {
        let mut children: Vec<(String, WzNodeArc)> = {
            let guard = node.read().unwrap();
            guard
                .children
                .iter()
                .map(|(name, child)| (name.as_str().to_string(), child.clone()))
                .collect()
        };
        // 老杨要求:展开后的节点按名称(首字母)排序;数字名按数值大小排(0,1,2…10)
        // LaoYang: sort expanded children by name; numeric names sort by value (0,1,2…10).
        children.sort_by(|(left, _), (right, _)| natural_cmp(left, right));

        let mut changed = false;
        for (index, (name, child)) in children.iter().enumerate() {
            if index >= MAX_VISIBLE_CHILDREN {
                ui.label(
                    RichText::new(format!(
                        "… 还有 {} 项,请用上方搜索过滤",
                        children.len() - MAX_VISIBLE_CHILDREN
                    ))
                    .weak(),
                );
                break;
            }
            changed |= self.node_ui(ui, name, child, depth);
        }
        changed
    }

    fn node_ui(&mut self, ui: &mut Ui, name: &str, node: &WzNodeArc, depth: usize) -> bool {
        let search_active = !self.search.trim().is_empty();
        if search_active && !subtree_matches(node, &self.search.trim().to_lowercase(), 0) {
            return false; // 搜索模式下过滤掉不匹配的分支
        }

        let full_path = node.read().unwrap().get_full_path();
        let node_id = Id::new(full_path.clone());
        let has_children = !node.read().unwrap().children.is_empty();
        let is_image = name.ends_with(".img");
        let mut changed = false;

        // 右键菜单内容取决于节点类型:基本类型→编辑;图片→替换
        // Right-click menu depends on the node kind: primitives → edit; PNG → replace.
        let is_png = matches!(
            &node.read().unwrap().object_type,
            WzObjectType::Property(WzSubProperty::PNG(_))
        );
        let is_value = matches!(&node.read().unwrap().object_type, WzObjectType::Value(_));

        // 被替换过的节点加个 `*` 标记,一眼看出改了哪些
        let display_name = if self.marked.contains(&full_path) {
            format!("{name} *")
        } else {
            name.to_string()
        };

        if has_children || is_image {
            let mut state = CollapsingState::load_with_default_open(ui.ctx(), node_id, false);
            if search_active {
                state.set_open(true); // 命中搜索时自动展开
            }
            let was_open = state.is_open();
            let (_toggle, header, body) = state
                .show_header(ui, |ui| {
                    let response =
                        ui.selectable_label(self.is_selected(node), node_label(&display_name, node));
                    self.context_menu(&response, node, is_png, is_value);
                    response.clicked()
                })
                .body(|ui| self.children_ui(ui, node, depth + 1));

            if header.inner {
                self.select(node.clone());
                self.try_parse(node);
                // 点名称同时展开/折叠,比只点箭头更符合直觉
                if let Some(mut stored) = CollapsingState::load(ui.ctx(), node_id) {
                    stored.set_open(!was_open);
                    stored.store(ui.ctx());
                }
                changed = true;
            }
            changed |= body.map(|inner| inner.inner).unwrap_or(false);
        } else {
            let response =
                ui.selectable_label(self.is_selected(node), node_label(&display_name, node));
            self.context_menu(&response, node, is_png, is_value);
            if response.clicked() {
                self.select(node.clone());
                self.try_parse(node);
                changed = true;
            }
        }

        changed
    }

    /// 节点右键菜单:基本类型「编辑」、图片「替换 / 还原」,外加「复制路径」
    /// Right-click menu: "编辑" for primitives, "替换/还原" for images, plus "复制路径".
    fn context_menu(
        &mut self,
        response: &egui::Response,
        node: &WzNodeArc,
        is_png: bool,
        is_value: bool,
    ) {
        response.context_menu(|ui| {
            let node_name = node.read().unwrap().name.as_str().to_string();
            ui.label(RichText::new(node_name).strong());
            ui.separator();

            if is_value && ui.button("编辑值…").clicked() {
                self.pending_action = Some(TreeAction::EditValue(node.clone()));
            }
            if is_png {
                if ui.button("替换图片…").clicked() {
                    self.pending_action = Some(TreeAction::ReplaceImage(node.clone()));
                }
                if ui.button("还原原图").clicked() {
                    self.pending_action = Some(TreeAction::RevertImage(node.clone()));
                }
            }
            if !is_value && !is_png {
                ui.label(RichText::new("(该节点不可编辑)").weak());
            }
            ui.separator();
            if ui.button("复制节点路径").clicked() {
                self.pending_copy_path = Some(node.read().unwrap().get_path_from_root());
            }
        });
    }

    /// 按路径跳转(自动解析路径上所有节点并展开祖先)
    /// Jump to a path (parses nodes along the way and expands ancestors).
    fn goto(&mut self, ctx: &egui::Context, root: &WzNodeArc) {
        let path = self.goto_path.trim().trim_start_matches('/').to_string();
        if path.is_empty() {
            return;
        }
        let found = { root.read().unwrap().at_path_parsed(&path) };
        match found {
            Ok(node) => {
                self.try_parse(&node);
                let path_from_root = node.read().unwrap().get_path_from_root();
                let root_name = root.read().unwrap().name.as_str().to_string();
                // 展开祖先节点,让目标可见
                let segments: Vec<&str> = path_from_root.split('/').collect();
                for count in 1..segments.len() {
                    let prefix = segments[..count].join("/");
                    let id = Id::new(format!("{root_name}/{prefix}"));
                    if let Some(mut state) = CollapsingState::load(ctx, id) {
                        state.set_open(true);
                        state.store(ctx);
                    }
                }
                self.select(node);
            }
            Err(error) => self.error = Some(format!("跳转失败 {path}:{error}")),
        }
    }
}

/// 节点名着色:一眼看出是目录 / img / 图片 / 音效 / 值
/// Color the node name by type: dir / img / png / sound / value.
fn node_label(name: &str, node: &WzNodeArc) -> RichText {
    let color = match &node.read().unwrap().object_type {
        WzObjectType::Property(WzSubProperty::PNG(_)) => Color32::from_rgb(0x1a, 0x8a, 0x3a),
        WzObjectType::Property(WzSubProperty::Sound(_)) => Color32::from_rgb(0xb0, 0x70, 0x00),
        WzObjectType::Value(_) => Color32::from_rgb(0x60, 0x60, 0x60),
        WzObjectType::Image(_) => Color32::from_rgb(0x1a, 0x50, 0xa0),
        _ => Color32::from_rgb(0x20, 0x20, 0x20),
    };
    RichText::new(name).color(color)
}

/// 子树里是否有名字命中关键字(未解析的节点只比对自己的名字)
/// Does any node in this subtree match the query?
fn subtree_matches(node: &WzNodeArc, query: &str, depth: usize) -> bool {
    if query.is_empty() {
        return true;
    }
    let (name_matched, children) = {
        let guard = node.read().unwrap();
        (
            guard.name.as_str().to_lowercase().contains(query),
            guard.children.values().cloned().collect::<Vec<WzNodeArc>>(),
        )
    };
    if name_matched {
        return true;
    }
    if depth >= 8 || children.is_empty() {
        return false;
    }
    children
        .iter()
        .any(|child| subtree_matches(child, query, depth + 1))
}

// ───────────────────────────── 图片缓存 ─────────────────────────────

struct CachedImage {
    image: DynamicImage,
    texture: TextureHandle,
}

/// 解码后的图片缓存:避免每帧重复解压 PNG
/// Cache of decoded images so we don't re-decode every frame.
#[derive(Default)]
struct ImageCache {
    entries: HashMap<String, CachedImage>,
    order: VecDeque<String>,
}

impl ImageCache {
    fn clear(&mut self) {
        self.entries.clear();
        self.order.clear();
    }

    /// 确保图片已解码并上传为纹理;`nearest` 决定采样方式(放大用最近邻,保留像素画质感)
    /// Decode + upload the image; `nearest` picks the sampling mode.
    fn ensure(&mut self, ctx: &egui::Context, key: &str, image: DynamicImage, nearest: bool) {
        if self.entries.contains_key(key) {
            return;
        }
        let color_image = match &image {
            DynamicImage::ImageRgb8(buffer) => egui::ColorImage::from_rgb(
                [buffer.width() as usize, buffer.height() as usize],
                buffer.as_bytes(),
            ),
            other => {
                let rgba = other.to_rgba8();
                egui::ColorImage::from_rgba_unmultiplied(
                    [rgba.width() as usize, rgba.height() as usize],
                    rgba.as_bytes(),
                )
            }
        };
        let options = if nearest {
            egui::TextureOptions::NEAREST
        } else {
            egui::TextureOptions::LINEAR
        };
        let texture = ctx.load_texture(key, color_image, options);
        self.entries.insert(key.to_string(), CachedImage { image, texture });
        self.order.push_back(key.to_string());
        while self.order.len() > IMAGE_CACHE_CAP {
            if let Some(oldest) = self.order.pop_front() {
                self.entries.remove(&oldest);
            }
        }
    }

    fn get(&self, key: &str) -> Option<&CachedImage> {
        self.entries.get(key)
    }

    /// 丢弃某条缓存(图片被替换/还原后必须调用,否则会显示旧图)
    /// Drop a cache entry (required after replacing/reverting an image).
    fn remove(&mut self, key: &str) {
        self.entries.remove(key);
    }
}

// ─────────────────── 右键编辑 / 替换(覆盖表 + 值编辑器)───────────────────

/// 内存覆盖表。
///
/// WZ 是**只读**格式:`WzValue` 可以直接改(内存里换掉节点的 `object_type` 即可),
/// 但 `WzPng` 必须由 reader + offset 构造,**没法凭空造一个**,所以「替换图片」只能
/// 存在这张表里:影响本会话的浏览 / 复制 / 导出,**不会写回磁盘上的 WZ 文件**。
/// In-memory overrides. WZ is read-only: `WzValue`s can be swapped in place, but a
/// `WzPng` cannot be constructed from scratch, so replaced images live here and only
/// affect this session (viewing / copying / exporting), never the file on disk.
#[derive(Default)]
struct Overrides {
    /// key = 节点的 `get_path_from_root()`
    images: HashMap<String, DynamicImage>,
}

impl Overrides {
    fn set_image(&mut self, path: String, image: DynamicImage) {
        self.images.insert(path, image);
    }

    fn remove_image(&mut self, path: &str) -> bool {
        self.images.remove(path).is_some()
    }

    fn image(&self, path: &str) -> Option<&DynamicImage> {
        self.images.get(path)
    }
}

/// 基本类型(叶子值)编辑器:右键「编辑」弹出的小窗口。
/// The leaf-value editor window (opened via right-click → "编辑").
#[derive(Default)]
struct ValueEditor {
    open: bool,
    /// 目标节点
    node: Option<WzNodeArc>,
    /// 目标节点路径(显示用)
    path: String,
    /// 原始类型(决定怎么解析输入)
    kind: ValueKind,
    /// 输入框内容
    buffer: String,
    error: Option<String>,
}

/// 可编辑的基本类型
/// Editable primitive kinds.
#[derive(Default, Clone, Copy, PartialEq, Eq)]
enum ValueKind {
    #[default]
    Int,
    Short,
    Long,
    Float,
    Double,
    /// `x,y` 形式
    Vector,
    /// 字符串(含 UOL / ParsedString:WzString 依赖 reader,改不了,存成 ParsedString)
    String,
}

impl ValueKind {
    fn label(self) -> &'static str {
        match self {
            ValueKind::Int => "int",
            ValueKind::Short => "short",
            ValueKind::Long => "long",
            ValueKind::Float => "float",
            ValueKind::Double => "double",
            ValueKind::Vector => "vector (x,y)",
            ValueKind::String => "string",
        }
    }

    /// 把输入文本解析成 `WzValue`
    /// Parse the input text into a `WzValue`.
    fn parse(self, text: &str) -> Result<WzValue, String> {
        let text = text.trim();
        match self {
            ValueKind::Int => text
                .parse::<i32>()
                .map(WzValue::Int)
                .map_err(|_| "需要整数(如 115)".to_string()),
            ValueKind::Short => text
                .parse::<i16>()
                .map(WzValue::Short)
                .map_err(|_| "需要 short 整数(-32768~32767)".to_string()),
            ValueKind::Long => text
                .parse::<i64>()
                .map(WzValue::Long)
                .map_err(|_| "需要长整数".to_string()),
            ValueKind::Float => text
                .parse::<f32>()
                .map(WzValue::Float)
                .map_err(|_| "需要浮点数(如 1.5)".to_string()),
            ValueKind::Double => text
                .parse::<f64>()
                .map(WzValue::Double)
                .map_err(|_| "需要浮点数(如 1.5)".to_string()),
            ValueKind::Vector => {
                let (left, right) = text.split_once(',').ok_or("格式必须是 x,y(如 30,23)")?;
                let x = left.trim().parse::<i32>().map_err(|_| "x 不是整数")?;
                let y = right.trim().parse::<i32>().map_err(|_| "y 不是整数")?;
                Ok(WzValue::Vector(Vector2D(x, y)))
            }
            ValueKind::String => Ok(WzValue::ParsedString(text.to_string())),
        }
    }
}

impl ValueEditor {
    /// 打开编辑器:读当前值作为初值
    /// Open the editor, pre-filled with the current value.
    fn open_with(&mut self, node: &WzNodeArc) {
        // 先在锁内把「类型 + 初值」算出来,别在 match 里动 guard(会 borrow 冲突)
        // Resolve kind + initial text inside the lock; never touch `guard` inside the match.
        let (path, outcome) = {
            let guard = node.read().unwrap();
            let path = guard.get_path_from_root();
            let outcome = match &guard.object_type {
                WzObjectType::Value(value) => match value {
                    WzValue::Int(value) => Ok((ValueKind::Int, value.to_string())),
                    WzValue::Short(value) => Ok((ValueKind::Short, value.to_string())),
                    WzValue::Long(value) => Ok((ValueKind::Long, value.to_string())),
                    WzValue::Float(value) => Ok((ValueKind::Float, value.to_string())),
                    WzValue::Double(value) => Ok((ValueKind::Double, value.to_string())),
                    WzValue::Vector(Vector2D(x, y)) => {
                        Ok((ValueKind::Vector, format!("{x},{y}")))
                    }
                    WzValue::String(value) | WzValue::UOL(value) => Ok((
                        ValueKind::String,
                        value.get_string().unwrap_or_default(),
                    )),
                    WzValue::ParsedString(value) => Ok((ValueKind::String, value.clone())),
                    WzValue::Null => Ok((ValueKind::String, String::new())),
                    // RawData / Lua / Video 不是基本类型,不给编辑
                    other => Err(format!("该类型不支持编辑:{other:?}")),
                },
                // 非值节点(属性 / 图片 / 目录)不支持「编辑值」
                _ => Err("只有基本类型(叶子值)可以编辑".to_string()),
            };
            (path, outcome)
        };

        self.path = path;
        match outcome {
            Ok((kind, text)) => {
                self.node = Some(node.clone());
                self.kind = kind;
                self.buffer = text;
                self.error = None;
            }
            Err(message) => {
                self.node = None;
                self.buffer.clear();
                self.error = Some(message);
            }
        }
        self.open = true;
    }

    /// 应用编辑:解析输入 → 直接改内存里节点的 `object_type`
    /// Apply the edit: parse and swap the node's `object_type` in place.
    fn apply(&mut self) -> Result<String, String> {
        let Some(node) = self.node.clone() else {
            return Err("没有可编辑的节点".to_string());
        };
        let value = self.kind.parse(&self.buffer)?;
        {
            let mut guard = node.write().unwrap();
            guard.object_type = WzObjectType::Value(value);
        }
        Ok(self.path.clone())
    }

    /// 绘制编辑窗口;返回是否刚刚提交成功
    /// Draw the editor window; returns true if an edit was just committed.
    fn ui(&mut self, ctx: &egui::Context) -> bool {
        if !self.open {
            return false;
        }
        let mut open = self.open;
        let mut applied = false;

        egui::Window::new("编辑值")
            .open(&mut open)
            .collapsible(false)
            .resizable(false)
            .default_size([420.0, 220.0])
            .show(ctx, |ui| {
                ui.label(RichText::new(&self.path).weak());
                ui.label(format!("类型:{}", self.kind.label()));
                ui.add_space(4.0);
                ui.add(
                    egui::TextEdit::singleline(&mut self.buffer).desired_width(f32::INFINITY),
                );
                if let Some(error) = &self.error {
                    ui.colored_label(Color32::from_rgb(0xc0, 0x30, 0x30), error);
                }
                ui.add_space(8.0);
                ui.horizontal(|ui| {
                    if ui.button("确定").clicked() {
                        match self.apply() {
                            Ok(_) => {
                                self.error = None;
                                applied = true;
                                self.open = false;
                            }
                            Err(error) => self.error = Some(error),
                        }
                    }
                    if ui.button("取消").clicked() {
                        self.open = false;
                    }
                });
                ui.label(
                    RichText::new("提示:改的是内存里的 WZ 树,关掉程序就没了(WZ 是只读格式)。")
                        .weak(),
                );
            });

        self.open = open;
        applied
    }
}

/// 树上的右键动作,交给 App 执行(Tree 自己不改业务状态)
/// Right-click actions produced by the tree, executed by the App.
enum TreeAction {
    /// 编辑基本类型的值
    EditValue(WzNodeArc),
    /// 替换图片
    ReplaceImage(WzNodeArc),
    /// 还原被替换的图片
    RevertImage(WzNodeArc),
}

// ───────────────────────────── 加载状态 ─────────────────────────────

/// 后台加载 WZ:大文件(Map.wz 几百 MB)解析要几秒,不能卡住界面。
/// Background WZ loading: big files take seconds, so keep the UI responsive.
enum LoadState {
    Idle,
    Loading {
        started: Instant,
        receiver: Receiver<Result<WzNodeArc, String>>,
    },
}

impl Default for LoadState {
    fn default() -> Self {
        LoadState::Idle
    }
}

/// 正在播放的音效(设备输出流必须活着,否则没声音)
/// The currently playing sound (the device sink must stay alive).
struct AudioPlayer {
    _device_sink: MixerDeviceSink,
    player: Player,
}

// ─────────────────────────────── 应用 ───────────────────────────────

/// 状态栏消息 / Status bar message.
struct Status {
    text: String,
    is_error: bool,
}

impl Default for Status {
    fn default() -> Self {
        Self {
            text: "就绪:请点左上角「打开 Base.wz…」选择 WZ 文件".to_string(),
            is_error: false,
        }
    }
}

struct WzEditorApp {
    root: Option<WzNodeArc>,
    root_path: Option<PathBuf>,
    load_state: LoadState,
    load_cost: Option<Duration>,
    tree: Tree,
    picker: FilePicker,
    clipboard: Option<ClipboardContext>,
    audio: Option<AudioPlayer>,
    image_cache: ImageCache,
    /// 图片缩放倍率
    zoom: f32,
    /// 当前 JSON / 文本预览内容
    preview_text: String,
    /// `preview_text` 对应的节点路径(避免重复计算)
    preview_path: String,
    /// 左栏(节点树)宽度:自己持有,拖拽分隔条直接改它
    tree_width: f32,
    /// 拖拽中先不落盘,松手才写文件
    tree_width_dirty: bool,
    /// 内存覆盖(替换后的图片)
    overrides: Overrides,
    /// 基本类型编辑器窗口
    value_editor: ValueEditor,
    /// 「替换图片」的目标节点(右键菜单里定下来)
    replace_target: Option<WzNodeArc>,
    status: Status,
}

impl Default for WzEditorApp {
    fn default() -> Self {
        Self {
            // 关键:启动不加载任何 WZ 文件
            // Key point: nothing is loaded at startup.
            root: None,
            root_path: None,
            load_state: LoadState::Idle,
            load_cost: None,
            tree: Tree::default(),
            picker: FilePicker::new(),
            clipboard: ClipboardContext::new().ok(),
            audio: None,
            image_cache: ImageCache::default(),
            zoom: 1.0,
            preview_text: String::new(),
            preview_path: String::new(),
            tree_width: load_tree_width(),
            tree_width_dirty: false,
            overrides: Overrides::default(),
            value_editor: ValueEditor::default(),
            replace_target: None,
            status: Status::default(),
        }
    }
}

impl WzEditorApp {
    /// 手动调整左栏宽度(顶栏按钮用),并立刻记住
    /// Nudge the tree-column width (top-bar buttons) and remember it.
    fn nudge_tree_width(&mut self, delta: f32) {
        self.tree_width = (self.tree_width + delta).max(TREE_WIDTH_MIN);
        save_tree_width(self.tree_width);
        self.set_status(format!("左栏宽度 {:.0}px", self.tree_width), false);
    }
}

impl WzEditorApp {
    fn set_status(&mut self, text: impl Into<String>, is_error: bool) {
        self.status = Status {
            text: text.into(),
            is_error,
        };
    }

    /// 后台加载 Base.wz
    /// Load Base.wz in a background thread.
    fn start_load(&mut self, path: PathBuf) {
        let (sender, receiver) = channel();
        let load_path = path.clone();
        thread::spawn(move || {
            let result = resolve_base(&load_path, None).map_err(|error| format!("{error}"));
            let _ = sender.send(result);
        });
        self.load_state = LoadState::Loading {
            started: Instant::now(),
            receiver,
        };
        self.root = None;
        self.root_path = Some(path.clone());
        self.tree.reset();
        self.image_cache.clear();
        self.audio = None;
        self.set_status(format!("正在加载:{}", path.display()), false);
    }

    /// 取回后台加载结果(在 `logic` 里每帧轮询,不阻塞 UI)
    /// Poll the loading result every frame (non-blocking).
    fn poll_load(&mut self, ctx: &egui::Context) {
        let received = match &self.load_state {
            LoadState::Loading { receiver, .. } => Some(receiver.try_recv()),
            LoadState::Idle => None,
        };

        match received {
            Some(Ok(Ok(root))) => {
                let cost = match &self.load_state {
                    LoadState::Loading { started, .. } => started.elapsed(),
                    LoadState::Idle => Duration::ZERO,
                };
                self.load_cost = Some(cost);
                self.root = Some(root);
                self.load_state = LoadState::Idle;
                self.set_status(
                    format!("加载完成,耗时 {:.2}s", cost.as_secs_f32()),
                    false,
                );
            }
            Some(Ok(Err(message))) => {
                self.load_state = LoadState::Idle;
                self.root = None;
                self.set_status(format!("加载失败:{message}"), true);
            }
            Some(Err(TryRecvError::Empty)) => {
                // 还在加载,保持界面持续重绘(转圈动画要动)
                ctx.request_repaint();
            }
            Some(Err(TryRecvError::Disconnected)) => {
                self.load_state = LoadState::Idle;
                self.set_status("加载失败:后台线程异常退出".to_string(), true);
            }
            None => {}
        }
    }

    fn close_wz(&mut self) {
        self.root = None;
        self.root_path = None;
        self.load_state = LoadState::Idle;
        self.load_cost = None;
        self.tree.reset();
        self.image_cache.clear();
        self.audio = None;
        self.set_status("已关闭,可重新打开 Base.wz".to_string(), false);
    }

    fn copy_text(&mut self, text: String) {
        match &self.clipboard {
            Some(clipboard) => match clipboard.set_text(text) {
                Ok(()) => self.set_status("已复制到剪贴板".to_string(), false),
                Err(error) => self.set_status(format!("复制失败:{error}"), true),
            },
            None => self.set_status("剪贴板不可用".to_string(), true),
        }
    }

    fn copy_image(&mut self, image: DynamicImage) {
        match &self.clipboard {
            Some(clipboard) => match clipboard.set_image(RustImageData::from_dynamic_image(image)) {
                Ok(()) => self.set_status("图片已复制到剪贴板".to_string(), false),
                Err(error) => self.set_status(format!("复制图片失败:{error}"), true),
            },
            None => self.set_status("剪贴板不可用".to_string(), true),
        }
    }

    // ── 顶栏 ──
    fn top_bar(&mut self, ui: &mut Ui) {
        egui::Panel::top("wz_top_bar").show(ui, |ui| {
            ui.horizontal(|ui| {
                // 左上角:呼出文件选择窗口
                if ui.button("打开 Base.wz…").clicked() {
                    self.picker.show(PickerMode::Wz);
                }
                if ui
                    .add_enabled(self.root.is_some(), egui::Button::new("关闭"))
                    .clicked()
                {
                    self.close_wz();
                }
                if let Some(path) = self.root_path.clone() {
                    if ui.button("重新加载").clicked() {
                        self.start_load(path);
                    }
                }
                ui.separator();
                match &self.root_path {
                    Some(path) => {
                        ui.label(RichText::new(path.display().to_string()).weak());
                    }
                    None => {
                        ui.label(RichText::new("未加载 WZ 文件").weak());
                    }
                }

                // 左栏宽度:拖分隔条之外,也提供按钮微调(对触摸板/精确对齐友好)
                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                    ui.label(RichText::new(format!("左栏 {:.0}px", self.tree_width)).weak());
                    if ui.button("加宽 →").clicked() {
                        self.nudge_tree_width(32.0);
                    }
                    if ui.button("← 收窄").clicked() {
                        self.nudge_tree_width(-32.0);
                    }
                    ui.label("左栏宽度");
                });
            });
        });
    }

    // ── 底部状态栏 ──
    fn status_bar(&mut self, ui: &mut Ui) {
        egui::Panel::bottom("wz_status_bar").show(ui, |ui| {
            ui.horizontal(|ui| {
                let color = if self.status.is_error {
                    Color32::from_rgb(0xc0, 0x30, 0x30)
                } else {
                    Color32::from_rgb(0x40, 0x40, 0x40)
                };
                ui.colored_label(color, &self.status.text);
                ui.separator();
                if let Some(cost) = self.load_cost {
                    ui.label(RichText::new(format!("加载耗时 {:.2}s", cost.as_secs_f32())).weak());
                }
                if !self.tree.selected_path.is_empty() {
                    ui.separator();
                    ui.label(RichText::new(format!("当前:{}", self.tree.selected_path)).weak());
                }
            });
        });
    }

    // ── 主体:左树 | 分隔条 | 右预览(宽度自己管,绝不回弹)──
    /// Body: tree column | splitter | preview column.
    ///
    /// 说明:egui 0.36 的 `Panel::left(..).resizable(true)` 拖拽后会回弹(尺寸状态由库内部
    /// 持久化、且拖动中不落盘),这里改成**自己持有宽度 + 自己画分隔条**,拖到哪就是哪。
    /// NOTE: egui 0.36's `Panel::left(..).resizable(true)` snaps back after dragging,
    /// so we own the width and draw our own splitter instead.
    fn body(&mut self, ui: &mut Ui) {
        egui::CentralPanel::default().show(ui, |ui| {
            let available = ui.available_rect_before_wrap();

            // 左栏宽度:夹在 [TREE_WIDTH_MIN, 可用宽度 - RIGHT_MIN_WIDTH]
            let max_width = (available.width() - RIGHT_MIN_WIDTH).max(TREE_WIDTH_MIN);
            self.tree_width = self.tree_width.clamp(TREE_WIDTH_MIN, max_width);

            let left_rect = Rect::from_min_size(
                available.min,
                egui::Vec2::new(self.tree_width, available.height()),
            );
            let splitter_rect = Rect::from_min_size(
                egui::Pos2::new(left_rect.max.x, available.min.y),
                egui::Vec2::new(SPLITTER_WIDTH, available.height()),
            );
            let right_rect = Rect::from_min_size(
                egui::Pos2::new(splitter_rect.max.x, available.min.y),
                egui::Vec2::new(
                    (available.max.x - splitter_rect.max.x).max(0.0),
                    available.height(),
                ),
            );

            // ── 左栏:节点树 ──
            let mut left_ui = ui.new_child(
                egui::UiBuilder::new()
                    .max_rect(left_rect)
                    .layout(egui::Layout::top_down(egui::Align::Min))
                    .id_salt("wz_tree_column"),
            );
            left_ui.set_clip_rect(left_rect);
            // 注意:`ui.style()` 返回的是借用,这里 clone 成自有 Arc,后面右栏还要用
            // `ui.style()` borrows `ui`, so clone the Arc before re-borrowing `ui` mutably.
            let style = ui.style().clone();
            egui::Frame::side_top_panel(&style).show(&mut left_ui, |ui| {
                ui.expand_to_include_rect(ui.max_rect()); // 撑满整列,视觉上就是侧边面板
                self.tree_column(ui);
            });

            // ── 分隔条:拖拽调宽 / 双击复位 ──
            let splitter = ui.interact(
                splitter_rect,
                Id::new("wz_tree_splitter"),
                egui::Sense::click_and_drag(),
            );
            if splitter.dragged() {
                if let Some(pointer) = splitter.interact_pointer_pos() {
                    self.tree_width = (pointer.x - available.min.x).clamp(TREE_WIDTH_MIN, max_width);
                    self.tree_width_dirty = true; // 松手后再落盘,避免拖动中疯狂写文件
                }
            }
            if splitter.drag_stopped() && self.tree_width_dirty {
                self.tree_width_dirty = false;
                save_tree_width(self.tree_width);
            }
            if splitter.double_clicked() {
                self.tree_width = TREE_WIDTH_DEFAULT.clamp(TREE_WIDTH_MIN, max_width);
                save_tree_width(self.tree_width);
            }
            if splitter.hovered() || splitter.dragged() {
                ui.set_cursor_icon(egui::CursorIcon::ResizeHorizontal);
            }
            if splitter.dragged() {
                self.set_status(
                    format!("左栏宽度 {:.0}px(松手生效,双击分隔条复位)", self.tree_width),
                    false,
                );
            }
            let stroke = if splitter.dragged() {
                ui.style().visuals.widgets.active.fg_stroke
            } else if splitter.hovered() {
                ui.style().visuals.widgets.hovered.fg_stroke
            } else {
                ui.style().visuals.widgets.noninteractive.bg_stroke
            };
            ui.painter()
                .vline(splitter_rect.center().x, splitter_rect.y_range(), stroke);

            // ── 右栏:预览 ──
            let mut right_ui = ui.new_child(
                egui::UiBuilder::new()
                    .max_rect(right_rect)
                    .layout(egui::Layout::top_down(egui::Align::Min))
                    .id_salt("wz_preview_column"),
            );
            right_ui.set_clip_rect(right_rect);
            egui::Frame::central_panel(&style).show(&mut right_ui, |ui| {
                ui.expand_to_include_rect(ui.max_rect());
                self.preview_panel(ui);
            });

            // 用掉父 Ui 的剩余空间
            ui.advance_cursor_after_rect(available);
        });
    }

    /// 左栏内容(树本体)+ 右键动作分发
    /// Contents of the tree column, plus right-click action dispatch.
    fn tree_column(&mut self, ui: &mut Ui) {
        let Some(root) = self.root.clone() else {
            ui.label(RichText::new("(尚未加载 WZ)").weak());
            return;
        };
        let selection_changed = self.tree.ui(ui, &root);
        if selection_changed {
            // 换节点就停掉正在播放的音效
            self.audio = None;
            self.preview_path.clear();
        }

        // 右键「复制节点路径」
        if let Some(path) = self.tree.take_copy_path() {
            self.copy_text(path);
        }

        // 右键菜单动作:编辑值 / 替换图片 / 还原原图
        match self.tree.take_action() {
            Some(TreeAction::EditValue(node)) => {
                self.value_editor.open_with(&node);
                self.tree.select(node);
            }
            Some(TreeAction::ReplaceImage(node)) => {
                let path = node.read().unwrap().get_path_from_root();
                self.replace_target = Some(node.clone());
                self.tree.select(node);
                self.picker.show(PickerMode::Image);
                self.set_status(format!("选择一张图片替换:{path}"), false);
            }
            Some(TreeAction::RevertImage(node)) => {
                let path = node.read().unwrap().get_path_from_root();
                if self.overrides.remove_image(&path) {
                    self.invalidate_image_cache(&path);
                    self.tree.set_marked(node.read().unwrap().get_full_path(), false);
                    self.set_status(format!("已还原原图:{path}"), false);
                } else {
                    self.set_status("这个节点没有被替换过,无需还原".to_string(), false);
                }
            }
            None => {}
        }
    }

    /// 丢掉某个节点的图片缓存(替换 / 还原后必调)
    /// Drop cached images for a node (must be called after replace/revert).
    fn invalidate_image_cache(&mut self, path: &str) {
        self.image_cache.remove(&format!("{path}|nearest"));
        self.image_cache.remove(&format!("{path}|linear"));
    }

    /// 用选中的图片替换目标节点(只改内存,不写回 WZ)
    /// Replace the target node's image with the picked file (in-memory only).
    fn apply_image_replacement(&mut self, file: PathBuf) {
        let Some(node) = self.replace_target.take() else {
            self.set_status("没有待替换的节点".to_string(), true);
            return;
        };
        let path = node.read().unwrap().get_path_from_root();
        match image::open(&file) {
            Ok(image) => {
                let size = (image.width(), image.height());
                self.invalidate_image_cache(&path); // 丢掉旧图缓存,否则还显示原图
                self.tree.set_marked(node.read().unwrap().get_full_path(), true);
                self.overrides.set_image(path.clone(), image);
                self.set_status(
                    format!(
                        "已替换 {}:来自 {}({}x{})—— 仅本会话生效,不写回 WZ",
                        path,
                        file.display(),
                        size.0,
                        size.1
                    ),
                    false,
                );
                self.preview_path.clear();
            }
            Err(error) => self.set_status(format!("读取图片失败:{error}"), true),
        }
    }

    // ── 右侧预览 ──
    fn preview_panel(&mut self, ui: &mut Ui) {
        if self.root.is_none() {
            ui.centered_and_justified(|ui| {
                ui.vertical_centered(|ui| {
                    ui.label(RichText::new("尚未加载 WZ 文件").strong());
                    ui.add_space(8.0);
                    ui.label("点击左上角「打开 Base.wz…」,在弹出的窗口里选择 Base.wz");
                    ui.add_space(12.0);
                    if ui.button("打开 Base.wz…").clicked() {
                        self.picker.show(PickerMode::Wz);
                    }
                });
            });
            return;
        }

        let Some(selected) = self.tree.selected.clone() else {
            ui.centered_and_justified(|ui| {
                ui.label(RichText::new("从左侧选择一个节点").weak());
            });
            return;
        };

        let path_from_root = self.tree.selected_path.clone();
        let (child_count, object_type) = {
            let node = selected.read().unwrap();
            (node.children.len(), node.object_type.clone())
        };

        // ── 头部:路径 + 常用操作 ──
        ui.horizontal(|ui| {
            ui.label(RichText::new(&path_from_root).strong());
        });
        ui.horizontal(|ui| {
            if ui.button("复制路径").clicked() {
                let path = path_from_root.clone();
                self.copy_text(path);
            }
            if ui.button("复制名称").clicked() {
                let name = selected.read().unwrap().name.as_str().to_string();
                self.copy_text(name);
            }
            ui.separator();
            ui.label(RichText::new(format!("子节点 {child_count}")).weak());
            ui.label(RichText::new(object_type_name(&object_type)).weak());
        });
        ui.separator();

        match object_type {
            WzObjectType::Property(WzSubProperty::PNG(png)) => {
                // 先看有没有被右键「替换」过(覆盖表优先)
                // Replacements (right-click → 替换) take priority.
                if let Some(image) = self.overrides.image(&path_from_root).cloned() {
                    ui.horizontal(|ui| {
                        ui.colored_label(
                            Color32::from_rgb(0x1a, 0x8a, 0x3a),
                            format!(
                                "已替换(本会话):{} x {} —— 原图 {} x {} {:?}",
                                image.width(),
                                image.height(),
                                png.width,
                                png.height,
                                png.format()
                            ),
                        );
                    });
                    self.show_image(ui, image, &path_from_root);
                } else {
                    self.png_preview(ui, &selected, &png, &path_from_root);
                }
            }
            WzObjectType::Property(WzSubProperty::Sound(sound)) => {
                ui.label(format!(
                    "音效:{:?},时长 {:?}",
                    sound.sound_type,
                    Duration::from_millis(sound.duration as u64)
                ));
                if ui.button("播放").clicked() {
                    // rodio 0.22:`play` 内部自己解码,传原始字节即可
                    // rodio 0.22: `play` decodes internally, feed it raw bytes.
                    let buffer = sound.get_buffer();
                    match DeviceSinkBuilder::open_default_sink() {
                        Ok(device_sink) => {
                            match play(device_sink.mixer(), Cursor::new(buffer)) {
                                Ok(player) => {
                                    self.audio = Some(AudioPlayer {
                                        _device_sink: device_sink,
                                        player,
                                    });
                                    self.set_status("播放中".to_string(), false);
                                }
                                Err(error) => self.set_status(format!("播放失败:{error}"), true),
                            }
                        }
                        Err(error) => self.set_status(format!("音频设备不可用:{error}"), true),
                    }
                }
                if ui.button("停止").clicked() {
                    if let Some(audio) = &self.audio {
                        audio.player.stop();
                    }
                    self.audio = None;
                }
            }
            WzObjectType::Property(WzSubProperty::Convex) => {
                ui.label("Convex(凸多边形数据)");
            }
            WzObjectType::Property(WzSubProperty::Property) => {
                self.json_preview(ui, &selected, &path_from_root);
            }
            WzObjectType::Value(value) => {
                self.value_preview(ui, &value, &selected, &path_from_root);
            }
            WzObjectType::File(_) | WzObjectType::MsFile(_) => {
                ui.label("WZ 文件根节点");
            }
            WzObjectType::Image(_) | WzObjectType::MsImage(_) => {
                self.json_preview(ui, &selected, &path_from_root);
            }
            WzObjectType::Directory(_) => {
                self.json_preview(ui, &selected, &path_from_root);
            }
        }
    }

    /// PNG 预览:缩放、复制、导出
    /// PNG preview: zoom, copy, export.
    fn png_preview(
        &mut self,
        ui: &mut Ui,
        node: &WzNodeArc,
        png: &wz_reader::property::WzPng,
        path: &str,
    ) {
        let format = png.format();
        ui.horizontal(|ui| {
            ui.label(format!(
                "图片 {} x {},格式 {:?}",
                png.width, png.height, format
            ));
        });

        // 先解码(可能失败),失败只提示,不 panic
        match png.extract_png() {
            Ok(image) => self.show_image(ui, image, path),
            Err(error) => {
                ui.colored_label(
                    Color32::from_rgb(0xc0, 0x30, 0x30),
                    format!("图片解码失败:{error:?}"),
                );
            }
        }
        let _ = node;
    }

    /// 显示一张图片:缩放 / 复制 / 导出(原图和替换图走同一条路)
    /// Show an image with zoom / copy / export (used for both originals and replacements).
    fn show_image(&mut self, ui: &mut Ui, image: DynamicImage, path: &str) {
        let nearest = self.zoom >= 1.0;
        let cache_key = if nearest {
            format!("{path}|nearest")
        } else {
            format!("{path}|linear")
        };
        ui.horizontal(|ui| {
            ui.label("缩放");
            ui.add(egui::Slider::new(&mut self.zoom, 0.25..=8.0).suffix("x"));
            if ui.button("重置").clicked() {
                self.zoom = 1.0;
            }
        });
        self.image_cache
            .ensure(ui.ctx(), &cache_key, image, nearest);
        // 先把缓存里的纹理和图片取成局部变量,避免借用冲突
        // Grab owned copies from the cache to avoid borrow conflicts.
        let Some((texture, cached_image)) = self
            .image_cache
            .get(&cache_key)
            .map(|cached| (cached.texture.clone(), cached.image.clone()))
        else {
            return;
        };
        ui.add(
            egui::Image::new(&texture)
                .fit_to_original_size(self.zoom)
                .bg_fill(Color32::from_gray(235)),
        );
        ui.horizontal(|ui| {
            if ui.button("复制图片").clicked() {
                let image = cached_image.clone();
                self.copy_image(image);
            }
            if ui.button("导出 PNG").clicked() {
                let file_name = std::env::temp_dir()
                    .join(format!("wz_editor_{}.png", path.replace('/', "_")));
                match cached_image.clone().into_rgba8().save(&file_name) {
                    Ok(()) => self.set_status(format!("已导出:{}", file_name.display()), false),
                    Err(error) => self.set_status(format!("导出失败:{error}"), true),
                }
            }
        });
    }

    /// JSON 预览(属性 / 图片节点 / 目录)
    /// JSON preview for property / image / directory nodes.
    fn json_preview(&mut self, ui: &mut Ui, node: &WzNodeArc, path: &str) {
        if self.preview_path != path {
            self.preview_text = node_to_json(node);
            self.preview_path = path.to_string();
        }
        ui.horizontal(|ui| {
            if ui.button("复制 JSON").clicked() {
                let text = self.preview_text.clone();
                self.copy_text(text);
            }
            ui.label(RichText::new(format!("{} 字节", self.preview_text.len())).weak());
        });
        egui::ScrollArea::both()
            .id_salt("wz_json_preview")
            .show(ui, |ui| {
                ui.add(
                    egui::TextEdit::multiline(&mut self.preview_text)
                        .font(egui::TextStyle::Monospace)
                        .desired_width(f32::INFINITY),
                );
            });
    }

    /// 叶子值预览(顺带支持 UOL 跳转)
    /// Leaf value preview (with UOL jump support).
    fn value_preview(&mut self, ui: &mut Ui, value: &WzValue, node: &WzNodeArc, path: &str) {
        match value {
            WzValue::String(string) | WzValue::UOL(string) => {
                let text = string.get_string().unwrap_or_default();
                ui.label(format!("{text:?}"));
                if matches!(value, WzValue::UOL(_)) {
                    ui.label(RichText::new("UOL:指向另一个节点的链接").weak());
                    if ui.button("跳转到目标").clicked() {
                        let target = node_util::get_resolved_uol_path(path, &text);
                        self.tree.goto_path = target;
                        if let Some(root) = self.root.clone() {
                            self.tree.goto(ui.ctx(), &root);
                        }
                    }
                }
            }
            WzValue::Vector(vector) => {
                ui.label(format!("{vector:?}"));
            }
            WzValue::Null => {
                ui.label("null");
            }
            other => {
                ui.label(format!("{other:?}  ({})", type_of(other)));
            }
        }
        let _ = node;
    }

    /// 加载中遮罩
    /// Loading overlay.
    fn loading_overlay(&self, ctx: &egui::Context) {
        if !matches!(self.load_state, LoadState::Loading { .. }) {
            return;
        }
        egui::Window::new("加载中")
            .collapsible(false)
            .resizable(false)
            .anchor(egui::Align2::CENTER_CENTER, egui::Vec2::ZERO)
            .show(ctx, |ui| {
                ui.horizontal(|ui| {
                    ui.spinner();
                    ui.label("正在解析 WZ,请稍候…");
                });
            });
    }
}

fn object_type_name(object_type: &WzObjectType) -> String {
    match object_type {
        WzObjectType::File(_) => "文件",
        WzObjectType::MsFile(_) => "MS 文件",
        WzObjectType::Image(_) => "图片节点(.img)",
        WzObjectType::MsImage(_) => "MS 图片节点",
        WzObjectType::Directory(_) => "目录",
        WzObjectType::Property(WzSubProperty::PNG(_)) => "PNG",
        WzObjectType::Property(WzSubProperty::Sound(_)) => "音效",
        WzObjectType::Property(WzSubProperty::Convex) => "Convex",
        WzObjectType::Property(WzSubProperty::Property) => "属性",
        WzObjectType::Value(_) => "值",
    }
    .to_string()
}

impl eframe::App for WzEditorApp {
    /// 每帧在 UI 之前调用:取后台加载结果(不绘制任何东西)
    /// Called before each UI pass: poll the background loader.
    fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
        self.poll_load(ctx);
    }

    fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
        // Ctrl/Cmd + O 打开选择窗口
        let shortcut = ui
            .ctx()
            .input_mut(|state| state.consume_key(egui::Modifiers::COMMAND, egui::Key::O));
        if shortcut {
            self.picker.show(PickerMode::Wz);
        }

        self.top_bar(ui);
        self.status_bar(ui);
        self.body(ui); // 左树 + 分隔条 + 右预览(宽度由 self.tree_width 掌控)

        // 面板之后弹窗口(egui 约定)
        let picker_mode = self.picker.mode;
        if let Some(path) = self.picker.ui(ui.ctx()) {
            match picker_mode {
                PickerMode::Wz => self.start_load(path),
                PickerMode::Image => self.apply_image_replacement(path),
            }
        }
        // 基本类型编辑窗口
        if self.value_editor.ui(ui.ctx()) {
            self.preview_path.clear(); // 值改了,JSON 缓存作废重算
            self.set_status("已修改该节点的值(仅内存)".to_string(), false);
        }
        self.loading_overlay(ui.ctx());
    }
}

/// 「自然排序」比较:把名字切成「数字块 / 非数字块」逐段比较。
/// 这样 `0,1,2,10` 不会排成 `0,1,10,2`,`a1, a2, a10` 同理。
/// Natural ordering: split names into digit / non-digit chunks and compare chunk by chunk,
/// so `0,1,2,10` doesn't become `0,1,10,2`.
fn natural_cmp(left: &str, right: &str) -> std::cmp::Ordering {
    use std::cmp::Ordering;

    let left_chars: Vec<char> = left.chars().collect();
    let right_chars: Vec<char> = right.chars().collect();
    let mut left_index = 0usize;
    let mut right_index = 0usize;

    while left_index < left_chars.len() && right_index < right_chars.len() {
        let left_is_digit = left_chars[left_index].is_ascii_digit();
        let right_is_digit = right_chars[right_index].is_ascii_digit();

        if left_is_digit && right_is_digit {
            // 数字块:按数值比(跳过前导 0)
            let left_start = left_index;
            let right_start = right_index;
            while left_index < left_chars.len() && left_chars[left_index].is_ascii_digit() {
                left_index += 1;
            }
            while right_index < right_chars.len() && right_chars[right_index].is_ascii_digit() {
                right_index += 1;
            }
            let left_number: u128 = left[left_start..left_index].parse().unwrap_or(u128::MAX);
            let right_number: u128 = right[right_start..right_index].parse().unwrap_or(u128::MAX);
            match left_number.cmp(&right_number) {
                Ordering::Equal => {}
                ordering => return ordering,
            }
        } else {
            // 非数字块:按字符比(大小写不敏感,保证 a/A/b 稳定)
            let left_char = left_chars[left_index].to_ascii_lowercase();
            let right_char = right_chars[right_index].to_ascii_lowercase();
            match left_char.cmp(&right_char) {
                Ordering::Equal => {
                    left_index += 1;
                    right_index += 1;
                }
                ordering => return ordering,
            }
        }
    }

    left_chars.len().cmp(&right_chars.len())
}