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
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
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT
//! GanttWidget for timeline task planning.
use crate::compat::HashMap;
use crate::core::{Color, HorizontalAlignment, Point, Rect};
use crate::event::{Event, EventHandler};
use crate::render::RenderContext;
use crate::signal::Signal1;
use crate::widget::capability::coercion::expect_i64;
use crate::widget::capability::properties_trait::{base_property_get, base_property_set};
use crate::widget::capability::types::{CapabilityAccessError, CapabilityValue};
use crate::widget::capability::WidgetProperties;
use crate::widget::metrics::{dimensions, effective_font};
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};
use crate::{impl_widget_property_hooks, property_names_of};
/// How far past the predecessor's right edge a dependency elbow turns: a short stub, so a link is
/// visibly an elbow and not a straight diagonal when the two bars are close on the axis.
const LINK_STUB: i32 = 4;
/// The half-width of a dependency arrow head, in pixels.
const LINK_HEAD: i32 = 4;
/// The width of a bar's start/end resize handle, in pixels.
const RESIZE_HANDLE: i32 = 5;
/// The height of the strip along a bar's bottom edge that drags its progress.
const PROGRESS_STRIP: i32 = 7;
/// What a drag on a task row is editing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum GanttDragKind {
/// The whole bar (or milestone) moves.
Move,
/// The start edge moves; the end is pinned.
ResizeStart,
/// The end edge moves; the start is pinned.
ResizeEnd,
/// The completion percentage follows the pointer.
Progress,
}
/// A drag in progress.
struct GanttDrag {
/// The task's index at press time.
task: usize,
/// The axis value the press landed on.
///
/// Keeping the press **date** rather than the press pixel is what makes edge auto-scroll
/// work: when the viewport moves, the pointer's date changes and the bar follows it, while a
/// stored pixel would keep pointing at the old date.
origin_value: i64,
/// The task's start at press time.
start: i64,
/// The task's end at press time.
end: i64,
/// Which part of the bar is being edited.
kind: GanttDragKind,
}
/// One gantt task bar.
///
/// Describes a single bar on the timeline. The widget treats `start` and `end`
/// as opaque integers on a linear axis — no calendar or timezone interpretation
/// is applied, so the unit (days since epoch, milliseconds, sprint numbers, ...)
/// is whatever the caller decides. Only their ordering and difference matter for
/// drawing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GanttTask {
/// Stable identifier. Not shown to the user; it is how a caller correlates a
/// selected task with its own data.
pub id: String,
/// Caption drawn on or beside the bar.
pub label: String,
/// Start position on the task axis.
pub start: i64,
/// End position on the task axis. Must be at least `start`; a reversed range
/// yields a zero- or negative-width bar rather than an error.
pub end: i64,
/// Completion percentage, `0 ..= 100`. Values above 100 are not clamped by
/// the type, so a caller is responsible for the range; drawing a value over
/// 100 would overflow the bar.
pub progress: u8,
/// The tasks this one waits on, by [`id`](Self::id).
///
/// A dependency is a **relationship between two bars**, and a gantt without it is a bar chart
/// with a time axis. The widget resolves these against the whole task list and draws an elbow
/// from each predecessor's right edge to this task's left edge; an id that names no task is
/// skipped rather than reported, because a caller editing a schedule will transiently hold
/// dangling ids and a chart is not the place to complain about it. Empty means "no
/// predecessors", which is the common case and what every task built through
/// [`GanttTask::new`] gets.
pub depends_on: Vec<String>,
/// Typed dependencies, carrying the relationship kind.
///
/// `depends_on` is the finish-to-start spelling kept for callers that predate the typed
/// form; both are resolved when the elbows are drawn.
pub dependencies: Vec<GanttDependency>,
/// Whether this row is a **milestone** rather than a bar.
///
/// A milestone is a single instant, so it is drawn as a diamond at [`start`](Self::start) rather
/// than a bar spanning a range — the one shape in a gantt that carries meaning no bar can, and
/// the reason a zero-length task has to be expressible at all. [`GanttTask::new`] widens a
/// reversed range to `start + 1` so an ordinary bar is never zero-length; a milestone opts out
/// of that by asking for it explicitly.
pub milestone: bool,
}
impl GanttTask {
/// Creates task.
pub fn new(
id: impl Into<String>,
label: impl Into<String>,
start: i64,
end: i64,
progress: u8,
) -> Self {
let s = start;
let e = end.max(s + 1);
Self {
id: id.into(),
label: label.into(),
start: s,
end: e,
progress: progress.min(100),
depends_on: Vec::new(),
dependencies: Vec::new(),
milestone: false,
}
}
/// Creates a **milestone**: a single instant drawn as a diamond, not a bar.
///
/// `end` is set equal to `start` rather than widened, because a milestone *is* an instant —
/// that is the whole distinction from a bar, and widening it would erase it.
pub fn milestone(id: impl Into<String>, label: impl Into<String>, at: i64) -> Self {
Self {
id: id.into(),
label: label.into(),
start: at,
end: at,
progress: 0,
depends_on: Vec::new(),
dependencies: Vec::new(),
milestone: true,
}
}
/// Declares that this task waits on `predecessors`, by id.
///
/// A builder rather than a constructor argument: most tasks have no dependencies, and a
/// five-argument constructor that made every caller write `vec![]` for the common case would
/// have been the wrong default.
pub fn depends_on(mut self, predecessors: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.depends_on = predecessors.into_iter().map(Into::into).collect();
self
}
/// Declares a typed dependency on `id`.
pub fn with_dependency(mut self, id: impl Into<String>, kind: DependencyKind) -> Self {
self.dependencies.push(GanttDependency { id: id.into(), kind });
self
}
}
/// How one task waits on another.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DependencyKind {
/// The successor starts when the predecessor finishes; the default elbow.
#[default]
FinishToStart,
/// Both start together, so the elbow leaves the predecessor's left edge.
StartToStart,
/// Both finish together, so the elbow enters the successor's right edge.
FinishToFinish,
}
use core::cell::RefCell;
/// The distance from an edge at which a drag starts advancing the viewport.
const DRAG_EDGE_BAND: i32 = 24;
/// One typed dependency edge.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GanttDependency {
/// The predecessor's task id.
pub id: String,
/// The relationship kind.
pub kind: DependencyKind,
}
/// Basic gantt widget with selectable task rows and zoomable viewport.
pub struct GanttWidget {
base: BaseWidget,
tasks: Vec<GanttTask>,
selected_index: Option<usize>,
viewport_start: i64,
viewport_end: i64,
row_height: u32,
/// The axis position to mark as "now", if any.
///
/// A gantt is read against the present: the whole question it answers is "where are we against
/// the plan", and the answer is invisible without this line. `Option` because the axis unit is
/// the caller's (days since epoch, sprint numbers, …) — the widget cannot invent "now" on an
/// axis it cannot interpret, so it draws the line only when told where now is.
today: Option<i64>,
/// Rows scrolled out of view at the top.
scroll_offset: usize,
/// Whether the time axis header is drawn.
show_time_axis: bool,
/// The number of ticks on that axis.
time_axis_ticks: u32,
/// Whether the critical path is highlighted.
show_critical_path: bool,
/// Whether the caller-supplied "now" line is drawn.
show_today: bool,
/// Task id to index, so a dependency is resolved in constant time.
id_index: HashMap<String, usize>,
/// The critical-path indices for the current tasks and edges, or `None` when stale.
///
/// The path is a topology walk; a still frame ran it again for the same schedule.
critical_cache: RefCell<Option<Vec<usize>>>,
/// The task row under the pointer, when no drag is in progress.
hovered_task: Option<usize>,
/// The pointer position that produced [`Self::hovered_task`], for the read-out anchor.
hover_position: Point,
/// Whether the hover read-out bubble is painted.
show_hover_readout: bool,
/// A drag in progress.
drag: Option<GanttDrag>,
/// The date axis painted in the header. Its range always mirrors the viewport.
axis: TimelineAxis,
/// The editable list of dependency edges.
dependency_editor: DependencyEditor,
/// Whether the dependency editor is painted over the right edge of the plot.
show_dependency_editor: bool,
/// Emitted when a task selected. Payload is task id.
pub task_selected: Signal1<String>,
/// Emitted when a task's dates change through a drag. Payload is task id.
pub task_rescheduled: Signal1<String>,
/// Emitted when a resize (or progress) drag starts. Payload is task id.
pub task_resize_started: Signal1<String>,
/// Emitted when a resize (or progress) drag ends. Payload is task id.
pub task_resize_finished: Signal1<String>,
/// Emitted when the visible axis range changes.
pub viewport_changed: Signal1<(i64, i64)>,
/// Emitted when a dependency edge is added through this widget.
pub dependency_added: Signal1<Dependency>,
/// Emitted when a dependency edge is removed through this widget.
pub dependency_removed: Signal1<Dependency>,
/// Emitted with the edge a press selected in the mounted editor.
pub link_selected: Signal1<Dependency>,
/// Emitted when the task under the pointer changes, with its index (or `None` on exit).
pub task_hovered: Signal1<Option<usize>>,
}
impl GanttWidget {
/// Creates empty gantt.
pub fn new(geometry: Rect) -> Self {
Self {
base: BaseWidget::new(WidgetKind::Chart, geometry, "GanttWidget"),
tasks: Vec::new(),
selected_index: None,
viewport_start: 0,
viewport_end: 100,
row_height: 24,
// No "now" until the caller says where it is: the axis unit is theirs.
today: None,
scroll_offset: 0,
show_time_axis: false,
time_axis_ticks: 4,
show_critical_path: false,
show_today: true,
id_index: HashMap::new(),
critical_cache: RefCell::new(None),
hovered_task: None,
hover_position: Point::new(0, 0),
show_hover_readout: true,
drag: None,
axis: TimelineAxis::new(Rect::new(0, 0, 0, 0)),
dependency_editor: DependencyEditor::new(Rect::new(0, 0, 0, 0)),
show_dependency_editor: false,
task_selected: Signal1::new(),
task_rescheduled: Signal1::new(),
task_resize_started: Signal1::new(),
task_resize_finished: Signal1::new(),
viewport_changed: Signal1::new(),
dependency_added: Signal1::new(),
dependency_removed: Signal1::new(),
link_selected: Signal1::new(),
task_hovered: Signal1::new(),
}
}
/// The date axis painted in the header.
pub fn timeline_axis(&self) -> &TimelineAxis {
&self.axis
}
/// The date axis, for a host that changes its format or tick density.
pub fn timeline_axis_mut(&mut self) -> &mut TimelineAxis {
&mut self.axis
}
/// The editable dependency list.
pub fn dependency_editor(&self) -> &DependencyEditor {
&self.dependency_editor
}
/// The editable dependency list, for a host that wants its own selection policy.
pub fn dependency_editor_mut(&mut self) -> &mut DependencyEditor {
&mut self.dependency_editor
}
/// Whether the dependency editor is painted.
pub fn show_dependency_editor(&self) -> bool {
self.show_dependency_editor
}
/// Shows or hides the dependency editor.
pub fn set_show_dependency_editor(&mut self, show: bool) {
if self.show_dependency_editor == show {
return;
}
self.show_dependency_editor = show;
self.base.request_layout();
self.base.request_redraw();
}
/// Adds an edge and re-emits `dependency_added`.
///
/// Returns `false` for a self-edge or a duplicate, matching the editor's own rule: an edge that
/// would be discarded must not leave the widget reporting an addition it did not make.
pub fn add_dependency(
&mut self,
predecessor: impl Into<String>,
successor: impl Into<String>,
) -> bool {
let dependency = Dependency::new(predecessor, successor);
if !self.dependency_editor.add_dependency(dependency.clone()) {
return false;
}
self.invalidate_critical_path();
self.dependency_added.emit(dependency);
self.base.request_redraw();
true
}
/// Removes the first matching edge and re-emits `dependency_removed`.
pub fn remove_dependency(
&mut self,
predecessor: impl Into<String>,
successor: impl Into<String>,
) -> bool {
let dependency = Dependency::new(predecessor, successor);
if !self.dependency_editor.remove_dependency(&dependency) {
return false;
}
self.invalidate_critical_path();
self.dependency_removed.emit(dependency);
self.base.request_redraw();
true
}
/// Replaces the editable edge list without re-emitting additions.
pub fn set_dependencies(&mut self, dependencies: Vec<Dependency>) {
self.dependency_editor.set_dependencies(dependencies);
self.invalidate_critical_path();
self.base.request_redraw();
}
/// Rebuilds the editor's edges from the tasks' two dependency spellings.
///
/// Both `depends_on` and `dependencies` contribute, matching the arrow paint and the critical
/// path, so the editor lists the same schedule the chart draws.
pub fn sync_dependencies_from_tasks(&mut self) {
let mut edges: Vec<Dependency> = Vec::new();
for task in &self.tasks {
for predecessor in &task.depends_on {
edges.push(Dependency::new(predecessor.clone(), task.id.clone()));
}
for dependency in &task.dependencies {
// The typed edge's relationship kind travels with it: the editor used to receive
// the ids only, so a start-to-start link was re-read as finish-to-start.
edges.push(Dependency::with_kind(
dependency.id.clone(),
task.id.clone(),
dependency.kind,
));
}
}
self.dependency_editor.set_dependencies(edges);
self.invalidate_critical_path();
self.base.request_redraw();
}
/// Rebuilds each task's typed dependency list from the mounted editor.
///
/// This is the other direction of [`Self::sync_dependencies_from_tasks`]. Together they make
/// the editor's relationship kinds survive a round trip instead of being lost at one end.
pub fn sync_tasks_from_dependencies(&mut self) {
for task in &mut self.tasks {
task.dependencies.clear();
}
let edges = self.dependency_editor.dependencies().to_vec();
for edge in edges {
if let Some(index) = self.id_index.get(&edge.successor).copied() {
if let Some(task) = self.tasks.get_mut(index) {
task.dependencies
.push(GanttDependency { id: edge.predecessor, kind: edge.kind });
}
}
}
self.invalidate_critical_path();
self.base.request_redraw();
}
/// Marks the cached critical path stale.
fn invalidate_critical_path(&mut self) {
*self.critical_cache.borrow_mut() = None;
}
/// The dependency row under `pos`, when the mounted editor is showing.
pub fn dependency_at(&self, pos: Point) -> Option<Dependency> {
if !self.show_dependency_editor {
return None;
}
let index = self.dependency_editor.hit_link(pos)?;
self.dependency_editor.dependencies().get(index).cloned()
}
/// The rectangle the date axis occupies, widened so its own track matches the task track.
///
/// `TimelineAxis` pads its track by its own constant; growing its box by the same amount on
/// both sides makes `date_to_pixel` and `pixel_to_date` agree with the bars' `project_x`.
fn axis_rect(&self) -> Rect {
let rect = self.geometry();
let (track_x, track_w) = self.track_geometry();
const AXIS_PADDING: i32 = 8;
Rect::new(
track_x - AXIS_PADDING,
rect.y,
track_w + 2 * AXIS_PADDING as u32,
self.axis_height().max(1) as u32,
)
}
/// The rectangle the dependency editor occupies, when it is shown.
fn dependency_editor_rect(&self) -> Rect {
let rect = self.geometry();
let width = 220.min(rect.width);
Rect::new(
rect.x + rect.width as i32 - width as i32,
rect.y + self.axis_height(),
width,
rect.height.saturating_sub(self.axis_height().max(0) as u32),
)
}
/// Places the axis and editor and keeps the axis range on the viewport.
fn layout_companions(&mut self) {
let axis_rect = self.axis_rect();
if self.axis.base().geometry() != axis_rect {
self.axis.base_mut().set_geometry(axis_rect);
}
self.axis.set_range(self.viewport_start, self.viewport_end);
self.axis.set_tick_density(self.time_axis_ticks);
if self.show_dependency_editor {
let editor_rect = self.dependency_editor_rect();
if self.dependency_editor.base().geometry() != editor_rect {
self.dependency_editor.base_mut().set_geometry(editor_rect);
}
}
}
/// Shows or hides the time axis header.
///
/// The header is opt-in because it shifts the lanes down by its own height; a schedule that
/// sits in a fixed-height card keeps its previous pixel layout until it asks for the axis.
pub fn set_show_time_axis(&mut self, show: bool) {
if self.show_time_axis == show {
return;
}
self.show_time_axis = show;
self.base.request_layout();
self.base.request_redraw();
}
/// Returns whether the time axis header is shown.
pub fn show_time_axis(&self) -> bool {
self.show_time_axis
}
/// Sets the number of time-axis ticks.
pub fn set_time_axis_ticks(&mut self, ticks: u32) {
let ticks = ticks.clamp(2, 12);
if self.time_axis_ticks == ticks {
return;
}
self.time_axis_ticks = ticks;
self.base.request_redraw();
}
/// Returns the number of time-axis ticks.
pub fn time_axis_ticks(&self) -> u32 {
self.time_axis_ticks
}
/// Sets the row height in pixels (floored at 8).
pub fn set_row_height(&mut self, row_height: u32) {
let row_height = row_height.max(8);
if self.row_height == row_height {
return;
}
self.row_height = row_height;
self.base.request_layout();
self.base.request_redraw();
}
/// Returns the row height in pixels.
pub fn row_height(&self) -> u32 {
self.row_height
}
/// Whether the critical path is highlighted.
pub fn show_critical_path(&self) -> bool {
self.show_critical_path
}
/// Enables highlighting of the longest dependency chain.
pub fn set_show_critical_path(&mut self, show: bool) {
if self.show_critical_path == show {
return;
}
self.show_critical_path = show;
self.base.request_redraw();
}
/// Whether the "now" line is drawn when a position is set.
pub fn show_today(&self) -> bool {
self.show_today
}
/// Shows or hides the "now" line without discarding its position.
pub fn set_show_today(&mut self, show: bool) {
if self.show_today == show {
return;
}
self.show_today = show;
self.base.request_redraw();
}
/// The task ids on the longest dependency chain, in schedule order.
///
/// A schedule's critical path is the chain of dependent tasks with the largest total duration:
/// every day it slips, the whole project slips by one. The chain is computed over the typed and
/// untyped dependency lists together, so both spellings contribute. Cyclic dependencies have no
/// longest chain; the nodes reachable from a cycle are omitted rather than reported as critical,
/// because a cycle is a caller error and inventing a path through it would hide that.
pub fn critical_path(&self) -> Vec<String> {
self.critical_path_indices()
.into_iter()
.filter_map(|index| self.tasks.get(index).map(|task| task.id.clone()))
.collect()
}
/// The task indices on the critical path.
///
/// The answer is a pure function of the tasks and their edges, so it is computed once and
/// cached until one of those changes; a still frame used to re-run the topology walk.
fn critical_path_indices(&self) -> Vec<usize> {
if let Some(cached) = self.critical_cache.borrow().as_ref() {
return cached.clone();
}
let computed = self.compute_critical_path();
*self.critical_cache.borrow_mut() = Some(computed.clone());
computed
}
/// Computes the critical path from scratch.
fn compute_critical_path(&self) -> Vec<usize> {
let count = self.tasks.len();
if count == 0 {
return Vec::new();
}
let duration = |index: usize| -> i64 {
self.tasks.get(index).map_or(0, |task| (task.end - task.start).max(0))
};
// Kahn's topological order. `edges[pred]` lists the successors that wait on it.
let mut edges: Vec<Vec<usize>> = vec![Vec::new(); count];
let mut indegree = vec![0usize; count];
for (successor, indegree_slot) in indegree.iter_mut().enumerate() {
for predecessor in self.predecessor_indices(successor) {
edges[predecessor].push(successor);
*indegree_slot += 1;
}
}
let mut queue: Vec<usize> = (0..count).filter(|index| indegree[*index] == 0).collect();
let mut order = Vec::with_capacity(count);
let mut cursor = 0usize;
while cursor < queue.len() {
let node = queue[cursor];
cursor += 1;
order.push(node);
for successor in &edges[node] {
indegree[*successor] -= 1;
if indegree[*successor] == 0 {
queue.push(*successor);
}
}
}
// `finish[i]` is the longest chain that **ends** at `i`; `previous[i]` is the predecessor
// that chain came through, which is what makes the answer a path rather than a number.
let mut finish = vec![0i64; count];
let mut previous: Vec<Option<usize>> = vec![None; count];
let mut ordered = vec![false; count];
for node in order {
ordered[node] = true;
let candidate = finish[node] + duration(node);
for successor in &edges[node] {
if candidate > finish[*successor] {
finish[*successor] = candidate;
previous[*successor] = Some(node);
}
}
}
// Only nodes that reached a topological position can be on a chain. A node inside a cycle
// never did, and reporting it as "critical" would invent a path through a schedule error.
let Some(end) = (0..count)
.filter(|index| ordered[*index])
.max_by_key(|index| finish[*index] + duration(*index))
else {
return Vec::new();
};
if finish[end] == 0 && previous[end].is_none() && duration(end) == 0 {
// Every task is a zero-length isolated node: there is no chain to mark, and naming an
// arbitrary one would be a claim the data does not support.
return Vec::new();
}
let mut path = Vec::new();
let mut node = Some(end);
while let Some(index) = node {
path.push(index);
node = previous[index];
}
path.reverse();
path
}
/// The indices of `index`'s predecessors, from both dependency spellings.
fn predecessor_indices(&self, index: usize) -> Vec<usize> {
let Some(task) = self.tasks.get(index) else {
return Vec::new();
};
let mut out: Vec<usize> = Vec::new();
let ids =
task.depends_on.iter().chain(task.dependencies.iter().map(|dependency| &dependency.id));
for id in ids {
if let Some(found) = self.id_index.get(id).copied() {
if found != index && !out.contains(&found) {
out.push(found);
}
}
}
out
}
/// The header height the time axis reserves.
fn axis_height(&self) -> i32 {
if self.show_time_axis {
18
} else {
0
}
}
/// The lane rectangle for a task row.
fn lane_rect(&self, visible_row: usize) -> Rect {
let rect = self.geometry();
Rect::new(
rect.x,
rect.y + self.axis_height() + visible_row as i32 * self.row_height as i32,
rect.width,
self.row_height,
)
}
/// How many task lanes fit under the axis.
fn visible_row_count(&self) -> usize {
let height = self.geometry().height.saturating_sub(self.axis_height().max(0) as u32);
(height / self.row_height.max(1)) as usize
}
/// Returns how many rows are scrolled out of view.
pub fn scroll_offset(&self) -> usize {
self.scroll_offset
}
/// Scrolls the task lanes by `delta`.
pub fn scroll_by(&mut self, delta: isize) {
let max = self.tasks.len().saturating_sub(self.visible_row_count());
let next = (self.scroll_offset as isize + delta).clamp(0, max as isize) as usize;
if self.scroll_offset == next {
return;
}
self.scroll_offset = next;
self.base.request_redraw();
}
/// Whether the hover read-out bubble is painted.
pub fn show_hover_readout(&self) -> bool {
self.show_hover_readout
}
/// Shows or hides the hover read-out bubble.
pub fn set_show_hover_readout(&mut self, show: bool) {
if self.show_hover_readout == show {
return;
}
self.show_hover_readout = show;
self.base.request_redraw();
}
/// Advances the viewport while a dragged bar is held near an edge.
///
/// The time axis moves by a twentieth of its own span per pointer move, which is slow enough
/// to aim and fast enough to cross a long schedule; the row bands move one row. Both go
/// through the same clamped entry points the wheel and the keyboard use.
fn autoscroll_drag(&mut self, pos: Point) {
if self.drag.is_none() {
return;
}
let rect = self.geometry();
if rect.width == 0 || rect.height == 0 {
return;
}
let band = DRAG_EDGE_BAND;
let step = ((self.viewport_end - self.viewport_start).max(1) / 20).max(1);
if pos.x < rect.x + band {
let start = (self.viewport_start - step).max(0);
self.set_viewport(start, start + step + (self.viewport_end - self.viewport_start));
} else if pos.x > rect.x + rect.width as i32 - band {
self.set_viewport(self.viewport_start + step, self.viewport_end + step);
}
if pos.y < rect.y + band {
self.scroll_by(-1);
} else if pos.y > rect.y + rect.height as i32 - band {
self.scroll_by(1);
}
}
/// Maps a pointer x to an axis position.
///
/// The mounted [`TimelineAxis`] owns the mapping, so a drag cannot disagree with the labels
/// above it; [`Self::layout_companions`] keeps the axis range on the viewport.
fn axis_value_at(&self, x: i32) -> i64 {
self.axis.pixel_to_date(x)
}
/// The time track's left edge and width.
///
/// One derivation shared by the press hit test and the progress drag: the two used to respell
/// `CHART_LABEL_GUTTER`/`CHART_TRACK_MARGIN` and could drift apart.
fn track_geometry(&self) -> (i32, u32) {
let rect = self.geometry();
(
rect.x + dimensions::CHART_LABEL_GUTTER,
rect.width
.saturating_sub(
dimensions::CHART_LABEL_GUTTER as u32 + dimensions::CHART_TRACK_MARGIN as u32,
)
.max(1),
)
}
/// Sets `index`'s progress from the pointer's x over the bar `start..end`.
///
/// Shared by the press and the move so that a press inside the progress strip immediately
/// applies the value the user pointed at, instead of waiting for a move that may never come (a
/// click alone used to leave the old percentage in place).
fn set_progress_from_pointer(&mut self, index: usize, start: i64, end: i64, x: i32) {
let (track_x, track_w) = self.track_geometry();
let x0 = self.project_x(start, track_x, track_w);
let x1 = self.project_x(end, track_x, track_w).max(x0 + 2);
let ratio = ((x - x0) as f32 / (x1 - x0) as f32).clamp(0.0, 1.0);
if let Some(task) = self.tasks.get_mut(index) {
let progress = (ratio * 100.0).round() as u8;
if task.progress != progress {
task.progress = progress;
self.base.request_redraw();
}
}
}
/// Commits the drag in progress and reports what it changed.
fn finish_drag(&mut self) {
let Some(drag) = self.drag.take() else {
return;
};
let Some(task) = self.tasks.get(drag.task) else {
self.base.request_redraw();
return;
};
// The task's fields are read before the cache is invalidated: holding the borrow across a
// `&mut self` call is what a cache write is.
let (start, end, id) = (task.start, task.end, task.id.clone());
self.invalidate_critical_path();
if start != drag.start || end != drag.end {
self.task_rescheduled.emit(id.clone());
}
if drag.kind != GanttDragKind::Move {
self.task_resize_finished.emit(id);
}
self.base.request_redraw();
}
/// Sets tasks.
pub fn set_tasks(&mut self, tasks: Vec<GanttTask>) {
self.tasks = tasks;
self.invalidate_critical_path();
// The map is rebuilt with the list rather than maintained per lookup: a dependency arrow
// resolves its predecessor through it, and `tasks.iter().position` per arrow made one paint
// O(tasks × links). A duplicate id keeps the first row, matching the first-match rule the
// arrow drawing had before the map existed.
self.id_index.clear();
for (index, task) in self.tasks.iter().enumerate() {
self.id_index.entry(task.id.clone()).or_insert(index);
}
self.selected_index = None;
self.recompute_viewport();
self.base.request_layout();
self.base.request_redraw();
}
/// Returns tasks.
pub fn tasks(&self) -> &[GanttTask] {
&self.tasks
}
/// Returns viewport range.
pub fn viewport(&self) -> (i64, i64) {
(self.viewport_start, self.viewport_end)
}
/// Sets viewport range.
pub fn set_viewport(&mut self, start: i64, end: i64) {
let end = end.max(start + 1);
if self.viewport_start == start && self.viewport_end == end {
return;
}
self.viewport_start = start;
self.viewport_end = end;
// The mounted axis is a view of the same range, so a zoom or a scroll has to reach it
// without waiting for the next paint: the axis is readable state, not just a drawing.
self.axis.set_range(start, end);
// The range is what the axis header and every bar are projected through, so a zoom or a
// scroll changes the picture. It used to change silently, which left a host unable to keep a
// linked chart (the finance panes, a second gantt) in step.
self.viewport_changed.emit((start, end));
self.base.request_redraw();
}
/// Zooms around center.
pub fn zoom(&mut self, factor: f32) {
if factor <= 0.0 {
return;
}
let span = (self.viewport_end - self.viewport_start).max(1) as f32;
let center = (self.viewport_start + self.viewport_end) as f32 / 2.0;
let half = (span / factor / 2.0).max(1.0);
self.set_viewport((center - half).floor() as i64, (center + half).ceil() as i64);
}
/// Select task by index.
pub fn select_index(&mut self, index: usize) -> bool {
if index >= self.tasks.len() {
return false;
}
self.selected_index = Some(index);
if let Some(task) = self.tasks.get(index) {
self.task_selected.emit(task.id.clone());
}
self.base.request_redraw();
true
}
/// Returns selected task id.
pub fn selected_id(&self) -> Option<&str> {
let index = self.selected_index?;
self.tasks.get(index).map(|task| task.id.as_str())
}
/// Returns the axis position marked as "now", if the caller set one.
pub fn today(&self) -> Option<i64> {
self.today
}
/// Marks `position` on the axis as "now".
///
/// Pass `None` to remove the marker. The line is drawn over the bars at full plot height, which
/// is what makes it readable against a busy schedule; before this it did not exist and the only
/// way a reader could locate "now" was to compare today's date against the axis by eye.
pub fn set_today(&mut self, position: Option<i64>) {
if self.today == position {
return;
}
self.today = position;
self.base.request_redraw();
}
fn recompute_viewport(&mut self) {
let (start, end) = if self.tasks.is_empty() {
(0, 100)
} else {
let mut min_start = i64::MAX;
let mut max_end = i64::MIN;
for task in &self.tasks {
min_start = min_start.min(task.start);
max_end = max_end.max(task.end);
}
(min_start, max_end.max(min_start + 1))
};
self.viewport_start = start;
self.viewport_end = end;
self.axis.set_range(start, end);
self.viewport_changed.emit((start, end));
}
fn row_at(&self, pos: Point) -> Option<usize> {
let rect = self.geometry();
if pos.x < rect.x
|| pos.x >= rect.x + rect.width as i32
|| pos.y < rect.y
|| pos.y >= rect.y + rect.height as i32
{
return None;
}
let idx = ((pos.y - rect.y - self.axis_height()) / self.row_height as i32) as usize
+ self.scroll_offset;
(idx < self.tasks.len()
&& pos.y >= rect.y + self.axis_height()
&& ((pos.y - rect.y - self.axis_height()) / self.row_height as i32)
< self.visible_row_count() as i32)
.then_some(idx)
}
fn project_x(&self, value: i64, track_x: i32, track_w: u32) -> i32 {
let start = self.viewport_start;
let end = self.viewport_end.max(start + 1);
let span = (end - start) as f32;
let ratio = ((value - start) as f32 / span).clamp(0.0, 1.0);
track_x + (ratio * track_w as f32) as i32
}
}
impl Widget for GanttWidget {
fn base(&self) -> &BaseWidget {
&self.base
}
fn set_state_theme_hook(&mut self) {
crate::style::reapply_active_theme_state(self);
}
fn base_mut(&mut self) -> &mut BaseWidget {
&mut self.base
}
/// Paints itself, so it can be mounted into a native window.
fn as_draw_mut(&mut self) -> Option<&mut dyn crate::widget::Draw> {
Some(self)
}
fn size_hint(&self) -> crate::core::Size {
crate::core::Size::new(dimensions::GANTT_DEFAULT_WIDTH, dimensions::GANTT_DEFAULT_HEIGHT)
}
impl_widget_property_hooks!();
/// Resolves a published event name to the control's own signal.
///
/// # Why this is explicit per control
///
/// `connect_event` validates a name against the capability table and registers a hub slot; only
/// `event_signal_dyn` joins that name to the signal the control actually emits. Without it a name
/// is valid and inert, which is the silent failure `tools/check_event_signal_dyn.sh` exists to
/// make impossible. The arm set is checked against the capability's published names, so this
/// list cannot drift from what the control advertises.
fn event_signal_dyn(&self, name: &str) -> Option<crate::signal::EventSignalRef> {
use crate::signal::EventSignalRef;
#[allow(unused_imports)]
use crate::widget::capability::CapabilityValue;
match name {
"task_selected" => {
Some(EventSignalRef::mapped("task_selected", &self.task_selected, |v| {
CapabilityValue::String(v.clone())
}))
}
"task_rescheduled" => {
Some(EventSignalRef::mapped("task_rescheduled", &self.task_rescheduled, |v| {
crate::widget::capability::CapabilityValue::String(v.clone())
}))
}
"task_resize_started" => Some(EventSignalRef::mapped(
"task_resize_started",
&self.task_resize_started,
|v| CapabilityValue::String(v.clone()),
)),
"task_resize_finished" => Some(EventSignalRef::mapped(
"task_resize_finished",
&self.task_resize_finished,
|v| CapabilityValue::String(v.clone()),
)),
"viewport_changed" => {
Some(EventSignalRef::mapped("viewport_changed", &self.viewport_changed, |v| {
CapabilityValue::Tuple(alloc::vec![
CapabilityValue::Int(v.0),
CapabilityValue::Int(v.1),
])
}))
}
"dependency_added" => {
Some(EventSignalRef::mapped("dependency_added", &self.dependency_added, |edge| {
CapabilityValue::Tuple(alloc::vec![
CapabilityValue::String(edge.predecessor.clone()),
CapabilityValue::String(edge.successor.clone()),
])
}))
}
"dependency_removed" => Some(EventSignalRef::mapped(
"dependency_removed",
&self.dependency_removed,
|edge| {
CapabilityValue::Tuple(alloc::vec![
CapabilityValue::String(edge.predecessor.clone()),
CapabilityValue::String(edge.successor.clone()),
])
},
)),
"link_selected" => {
Some(EventSignalRef::mapped("link_selected", &self.link_selected, |edge| {
CapabilityValue::Tuple(alloc::vec![
CapabilityValue::String(edge.predecessor.clone()),
CapabilityValue::String(edge.successor.clone()),
])
}))
}
"task_hovered" => {
Some(EventSignalRef::mapped("task_hovered", &self.task_hovered, |v| match v {
Some(index) => CapabilityValue::UInt(*index as u64),
None => CapabilityValue::Null,
}))
}
_ => None,
}
}
}
/// `GanttWidget`'s property contract.
///
/// Read/write semantics are carried over unchanged from the centralised
/// `access_read_other.in.rs` / `access_write_other.in.rs` dispatch, so callers see
/// the same coercions and the same errors as before. `GanttWidget` reports
/// `WidgetKind::Chart`, shared with `ChartWidget` and `TimelineWidget`;
/// dispatching on the concrete type here is what keeps the three contracts
/// separate.
impl WidgetProperties for GanttWidget {
fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
match name {
"task_count" => Ok(CapabilityValue::UInt(self.tasks().len() as u64)),
"selected_id" => match self.selected_id() {
Some(id) => Ok(CapabilityValue::String(id.to_string())),
None => Ok(CapabilityValue::Null),
},
"viewport_start" => Ok(CapabilityValue::Int(self.viewport().0)),
"viewport_end" => Ok(CapabilityValue::Int(self.viewport().1)),
"row_height" => Ok(CapabilityValue::UInt(self.row_height() as u64)),
"show_critical_path" => Ok(CapabilityValue::Bool(self.show_critical_path())),
"show_today" => Ok(CapabilityValue::Bool(self.show_today())),
_ => base_property_get(self, name),
}
}
fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
match name {
"viewport_start" => {
let start = expect_i64(value)?;
let (_, end) = self.viewport();
self.set_viewport(start, end);
Ok(())
}
"viewport_end" => {
let end = expect_i64(value)?;
let (start, _) = self.viewport();
self.set_viewport(start, end);
Ok(())
}
"row_height" => {
let height = match value {
CapabilityValue::UInt(height) => {
u32::try_from(height).map_err(|_| CapabilityAccessError::TypeMismatch)?
}
_ => return Err(CapabilityAccessError::TypeMismatch),
};
self.set_row_height(height);
Ok(())
}
"show_critical_path" => {
self.set_show_critical_path(crate::widget::capability::coercion::expect_bool(
value,
)?);
Ok(())
}
"show_today" => {
self.set_show_today(crate::widget::capability::coercion::expect_bool(value)?);
Ok(())
}
// Derived counts and the selection identity are computed from the task
// list, so they are refused as read-only rather than reported as names
// this control does not know.
"task_count" | "selected_id" => Err(CapabilityAccessError::ReadOnlyProperty),
_ => base_property_set(self, name, value),
}
}
fn property_names(&self) -> &'static [&'static str] {
property_names_of![
"task_count",
"selected_id",
"viewport_start",
"viewport_end",
"row_height",
"show_critical_path",
"show_today",
BASE_PROPERTY_NAMES
]
}
/// Runs one of the commands `gantt_widget` publishes.
///
/// `zoom` is payload-free here: a bare invocation zooms in around the
/// centre, which is the direction the affordance always offers, so the
/// widget's real `zoom` receives a fixed factor. `set_tasks`, `set_viewport`
/// and `select_task` need the tasks, the bounds and the index respectively.
fn command(&mut self, name: &str) -> Result<(), CapabilityAccessError> {
match name {
"zoom" => {
self.zoom(1.25);
Ok(())
}
"set_tasks" | "set_viewport" | "select_task" => Err(CapabilityAccessError::OutOfRange),
_ => Err(CapabilityAccessError::UnknownCommand),
}
}
}
impl EventHandler for GanttWidget {
fn handle_event(&mut self, event: &Event) {
self.base.handle_event(event);
if !self.base.is_enabled() {
return;
}
// The axis and editor live inside this widget's rectangle, so their geometry and the
// axis range are refreshed before any press is resolved against them.
self.layout_companions();
match event {
Event::MousePress { pos, button: 1, .. }
if self.show_dependency_editor
&& self.dependency_editor_rect().contains_point(*pos) =>
{
// The editor owns its rows: a press selects the edge under the pointer and the
// widget re-emits it, so a host connects to the chart rather than to a child it
// never mounted itself.
self.dependency_editor.handle_event(event);
if let Some(dependency) = self.dependency_at(*pos) {
self.link_selected.emit(dependency);
}
self.base.request_redraw();
}
Event::MousePress { pos, button: 1, .. } => {
let Some(index) = self.row_at(*pos) else {
return;
};
let _ = self.select_index(index);
let Some(task) = self.tasks.get(index) else {
return;
};
let (start, end, milestone, id) =
(task.start, task.end, task.milestone, task.id.clone());
let (track_x, track_w) = self.track_geometry();
let x0 = self.project_x(start, track_x, track_w);
let x1 = self.project_x(end, track_x, track_w).max(x0 + 2);
let lane_y = self.lane_rect(index - self.scroll_offset).y;
let bar_top = lane_y + 5;
let bar_bottom = lane_y + self.row_height as i32 - 5;
let kind = if milestone {
// A milestone is a diamond, not a bar, so only the diamond itself is grabbable.
// It used to be undraggable at all, which left the one point-shaped mark on the
// chart as the only thing a user could not move.
let half = (self.row_height.saturating_sub(10) / 2) as i32;
if (pos.x - x0).abs() > half + 2 {
return;
}
GanttDragKind::Move
} else {
if pos.x < x0 || pos.x > x1 || pos.y < bar_top || pos.y > bar_bottom {
return;
}
// The edges resize, the bottom strip sets progress, and the rest moves the bar.
// Before this the whole bar moved regardless of where it was grabbed, so a
// schedule could not be adjusted without editing the task list.
if pos.x <= x0 + RESIZE_HANDLE {
GanttDragKind::ResizeStart
} else if pos.x >= x1 - RESIZE_HANDLE {
GanttDragKind::ResizeEnd
} else if pos.y >= bar_bottom - PROGRESS_STRIP {
GanttDragKind::Progress
} else {
GanttDragKind::Move
}
};
self.drag = Some(GanttDrag {
task: index,
origin_value: self.axis_value_at(pos.x),
start,
end,
kind,
});
if kind == GanttDragKind::Progress {
self.set_progress_from_pointer(index, start, end, pos.x);
}
if kind != GanttDragKind::Move {
self.task_resize_started.emit(id);
}
}
Event::MouseMove { pos } => {
if self.drag.is_none() {
// Hover is tracked only while nothing is being dragged: during a drag the
// pointer belongs to the bar, not to a read-out target.
let hovered = self.row_at(*pos);
self.hover_position = *pos;
if hovered != self.hovered_task {
self.hovered_task = hovered;
self.task_hovered.emit(hovered);
self.base.request_redraw();
}
return;
}
// Edge auto-scroll runs first, so the drag's target date is computed against the
// viewport the scroll just produced. Without it a bar could only be dropped into
// the slice of time already on screen.
self.autoscroll_drag(*pos);
self.layout_companions();
let Some(drag) = self.drag.as_ref() else {
return;
};
let (index, origin_value, start, end, kind) =
(drag.task, drag.origin_value, drag.start, drag.end, drag.kind);
if index >= self.tasks.len() {
return;
}
// The delta is converted through the axis rather than a pixels-per-unit
// constant, so the bar tracks the pointer at any zoom level. Both endpoints are
// recomputed from the **press** value, so a drag that reverses direction across the
// origin lands where the pointer is rather than drifting by the distance travelled.
let shift = self.axis_value_at(pos.x) - origin_value;
if kind == GanttDragKind::Progress {
self.set_progress_from_pointer(index, start, end, pos.x);
return;
}
if shift == 0 {
return;
}
let Some(task) = self.tasks.get_mut(index) else {
return;
};
match kind {
GanttDragKind::Move => {
if start + shift >= 0 {
task.start = start + shift;
task.end = end + shift;
}
}
// A resize keeps the opposite edge pinned and never crosses it: a reversed
// range would paint a negative-width bar, which reads as a rendering fault.
GanttDragKind::ResizeStart => {
task.start = (start + shift).clamp(0, end - 1);
task.end = end;
}
GanttDragKind::ResizeEnd => {
task.start = start;
task.end = (end + shift).max(start + 1);
}
GanttDragKind::Progress => unreachable!("progress returned above"),
}
self.invalidate_critical_path();
self.base.request_redraw();
}
Event::MouseRelease { button: 1, .. } => self.finish_drag(),
// A drag that loses the pointer must not leave a bar following a pointer that is no
// longer there; the gesture is committed at its last position.
Event::MouseLeave { .. } => {
if self.hovered_task.take().is_some() {
self.task_hovered.emit(None);
}
self.finish_drag();
}
Event::Wheel { delta, modifiers } => {
let modifiers = crate::shortcut::Modifiers::from_event_bits(*modifiers);
if modifiers.contains(crate::shortcut::Modifiers::SHIFT) {
if delta.y != 0 {
self.scroll_by(if delta.y > 0 { 1 } else { -1 });
}
} else if delta.y < 0 {
self.zoom(1.2);
} else if delta.y > 0 {
self.zoom(0.8);
}
}
Event::KeyPress { key, .. } => match *key {
38 => {
let index = self.selected_index.map_or(0, |index| index.saturating_sub(1));
let _ = self.select_index(index);
}
40 => {
if !self.tasks.is_empty() {
let index = self
.selected_index
.map_or(0, |index| (index + 1).min(self.tasks.len() - 1));
let _ = self.select_index(index);
}
}
33 => self.scroll_by(-(self.visible_row_count().max(1) as isize)),
34 => self.scroll_by(self.visible_row_count().max(1) as isize),
_ => {}
},
_ => { /* Other events are not relevant */ }
}
}
}
impl Draw for GanttWidget {
fn draw(&mut self, context: &mut RenderContext) {
let rect = self.geometry();
// The axis and editor are children of this widget: their geometry and the axis' range are
// resolved before any colour borrow is taken.
self.layout_companions();
// Chrome colours resolve explicit style first, then the theme's resolved
// style for this control, and only then a literal. The theme step is what
// makes an appearance switch visible; previously every colour below was a
// hardcoded literal, so light and dark rendered identically.
//
// `resolved_theme_style` takes and releases the global manager's lock
// internally, so no guard is held across the draw (the mutex is not
// re-entrant).
let style = self.base.style();
let theme = crate::style::resolved_theme_style_shared("gantt_widget");
// `gantt_widget` is not a control kind in the role table, so it classifies as
// `Surface`, whose background is `theme.colors.background` — byte-identical
// to the window behind it. The chart's own fill is therefore a step toward
// the foreground, so it reads as a surface of its own.
let resolved = style
.background_color
.or_else(|| theme.as_ref().and_then(|t| t.background_color))
.unwrap_or(Color::rgb(251, 252, 254));
let border = style
.border_color
.or_else(|| theme.as_ref().and_then(|t| t.border_color))
.unwrap_or_else(|| crate::core::Color::border_of(resolved));
let text_color = style
.text_color
.or_else(|| theme.as_ref().and_then(|t| t.text_color))
.unwrap_or(Color::rgb(0, 0, 0));
let background = resolved.blend(&text_color, 0.08);
// A selected lane is a chrome state of the chart, so it is derived from the
// resolved pair rather than a literal tint.
let selected_lane = background.blend(&text_color, 0.14);
// Task bars are data marks drawn in the accent colour, which is what makes
// them a chart rather than chrome.
let bar_color = crate::style::resolved_theme_style_shared("slider")
.and_then(|accent| accent.background_color)
.unwrap_or_else(|| background.blend(&text_color, 0.55));
let progress_color = bar_color.blend(&text_color, 0.18);
// The row separator is secondary chrome, derived from the same pair.
let separator = background.blend(&text_color, 0.12);
// The "now" line is a **semantic** mark, not chrome: it answers the question the chart exists
// to answer, so it takes the theme's error role -- the one colour in the palette that is
// universally read as "pay attention to this instant". It read the `badge` style's text
// colour instead, and `badge` is not a role, so the mark was painted in ordinary ink.
let today_color = crate::style::semantic_color(crate::style::SemanticColor::Error)
.unwrap_or_else(|| background.blend(&text_color, 0.85));
// Dependencies are structure, not data: a line that connected bars in the accent colour would
// compete with the bars themselves.
let link_color = background.blend(&text_color, 0.45);
// The critical path is a *state* of the schedule ("this chain decides the finish date"), so
// it takes a semantic role rather than a fourth literal.
let critical_color = crate::style::semantic_color(crate::style::SemanticColor::Warning)
.map(|token| token.blend(&background, 0.25))
.unwrap_or_else(|| bar_color.blend(&progress_color, 0.5));
let critical_flags: Vec<bool> = {
let mut flags = vec![false; self.tasks.len()];
if self.show_critical_path {
for index in self.critical_path_indices() {
if let Some(flag) = flags.get_mut(index) {
*flag = true;
}
}
}
flags
};
context.face_with_gradient(
rect,
background,
self.style().background_gradient.as_ref(),
self.style().surface.unwrap_or_default(),
self.style().border_radius.unwrap_or(0),
Color::BLACK,
);
crate::widget::draw::stroke_surface_border(
context,
rect,
self.style().border_radius.unwrap_or(0),
border,
1,
);
// The label column and the track share one derivation: `CHART_LABEL_GUTTER` is the room
// reserved for task names, and the track begins at its trailing edge and ends a
// `CHART_TRACK_MARGIN` short of the control's right edge. The pair this replaces —
// `rect.x + 150` for the track and `rect.width - 160` for its length — encoded the same
// fact twice with two different numbers, so the track began 10 px past the gutter its
// labels were measured against.
let track_x = rect.x + dimensions::CHART_LABEL_GUTTER;
let track_w = rect.width.saturating_sub(
dimensions::CHART_LABEL_GUTTER as u32 + dimensions::CHART_TRACK_MARGIN as u32,
);
// ── Time axis header ──
//
// Opt-in because it shifts the lanes down. The mounted [`TimelineAxis`] paints the ticks
// and formats the labels; its range is synced to the viewport by `layout_companions`.
if self.show_time_axis {
self.axis.draw(context);
}
let first_visible = self.scroll_offset;
let visible_rows = self.visible_row_count();
for visible_row in 0..visible_rows {
let index = first_visible + visible_row;
let Some(task) = self.tasks.get(index) else {
break;
};
let y = self.lane_rect(visible_row).y;
if y + self.row_height as i32 > rect.y + rect.height as i32 {
break;
}
if self.selected_index == Some(index) {
context.fill_rect(Rect::new(rect.x, y, rect.width, self.row_height), selected_lane);
}
// The lane label is centred in its lane. The raw midpoint put the glyph box's
// *top* edge on the lane's middle line, half a line low; the fix is the shared
// *line-box* primitive, not a wider band — `draw_text_fitted` centres only the
// horizontal axis and leaves `y` at the band's top edge, so handing it a
// `row_height`-tall band pinned every task name to the top of its lane again.
// `draw_text_line` is the entry point that centres on both axes.
let label_band =
Rect::new(rect.x, y, track_x.saturating_sub(rect.x) as u32, self.row_height);
context.draw_text_line_cow(
label_band,
&task.label,
effective_font(style),
text_color,
HorizontalAlignment::Left,
);
let x0 = self.project_x(task.start, track_x, track_w);
// ── A milestone is a diamond, not a bar ──
//
// It marks an instant, and an instant has no width, so drawing it as a bar would state
// something false about the schedule. The half-size is half the lane's bar height, which
// is what makes it read as the same weight as its neighbours' bars.
if task.milestone {
let bar_h = self.row_height.saturating_sub(10);
let half = (bar_h / 2) as i32;
let cy = y + 5 + half;
// A fixed-size array on the stack: the diamond always has four corners, so the
// per-milestone `vec!` allocated a list whose length could never vary.
let points = [
Point::new(x0, cy - half),
Point::new(x0 + half, cy),
Point::new(x0, cy + half),
Point::new(x0 - half, cy),
];
let fill = if critical_flags.get(index).copied().unwrap_or(false) {
critical_color
} else {
bar_color
};
context.execute_command(crate::render::RenderCommand::DrawPath {
points: points.into(),
closed: true,
color: fill,
filled: true,
width: 1,
});
context.draw_line(
Point::new(rect.x, y + self.row_height as i32),
Point::new(rect.x + rect.width as i32, y + self.row_height as i32),
separator,
);
continue;
}
let x1 = self.project_x(task.end, track_x, track_w).max(x0 + 2);
let bar_h = self.row_height.saturating_sub(10);
let bar_rect = Rect::new(x0, y + 5, (x1 - x0) as u32, bar_h);
let fill = if critical_flags.get(index).copied().unwrap_or(false) {
critical_color
} else {
bar_color
};
let progress_fill = fill.blend(&text_color, 0.18);
context.fill_rect(bar_rect, fill);
let progress_w =
((bar_rect.width as f32) * (task.progress as f32 / 100.0)).round() as u32;
if progress_w > 0 {
context.fill_rect(
Rect::new(bar_rect.x, bar_rect.y, progress_w, bar_rect.height),
progress_fill,
);
}
context.draw_line(
Point::new(rect.x, y + self.row_height as i32),
Point::new(rect.x + rect.width as i32, y + self.row_height as i32),
separator,
);
}
// ── Dependency arrows ──
//
// Drawn **after** every bar, so a successor's bar cannot cover the elbow that explains it.
// The shape is the conventional one: out of the predecessor's right edge, a half-gap to the
// right or left, then into the successor's left edge -- two segments and an arrow head, which
// is the minimum that still says "this one waits for that one" rather than "these two happen
// to be near each other".
for visible_row in 0..visible_rows {
let index = first_visible + visible_row;
let Some(task) = self.tasks.get(index) else {
break;
};
let y = self.lane_rect(visible_row).y;
if y + self.row_height as i32 > rect.y + rect.height as i32 {
break;
}
let predecessors = task
.depends_on
.iter()
.map(|id| (id.as_str(), DependencyKind::FinishToStart))
.chain(
task.dependencies
.iter()
.map(|dependency| (dependency.id.as_str(), dependency.kind)),
);
for (predecessor_id, kind) in predecessors {
// Constant-time id resolution. The per-arrow `tasks.iter().position` made one paint
// quadratic in the schedule's size; the map is built and maintained by `set_tasks`.
let Some(pred_index) = self.id_index.get(predecessor_id).copied() else {
// A dangling id is skipped rather than reported: a caller editing a schedule
// transiently holds them, and a chart is not the place to complain.
continue;
};
let Some(pred) = self.tasks.get(pred_index) else {
continue;
};
// A predecessor scrolled out of view still has a known **axis** position — only its
// lane is off screen. The elbow is clipped to the visible band instead of dropped,
// which is what keeps a dependency visible when the task it comes from is above or
// below the viewport. Dropping it made the link silently disappear on scroll.
let pred_visible_row = pred_index as i64 - first_visible as i64;
let pred_offset = pred_visible_row
.clamp(-(self.tasks.len() as i64), self.tasks.len() as i64)
as i32;
let pred_y = rect.y
+ self.axis_height()
+ pred_offset.saturating_mul(self.row_height as i32);
// The three relationship kinds differ in which edges the elbow joins: a
// finish-to-start link leaves the predecessor's end and enters the successor's
// start, start-to-start joins the two left edges, finish-to-finish the two right
// edges. Routing each with its own pair of edges is what makes the arrow state the
// relationship instead of only the dependency.
let (from_x, to_x) = match kind {
DependencyKind::FinishToStart => (
self.project_x(pred.end.max(pred.start + 1), track_x, track_w),
self.project_x(task.start, track_x, track_w),
),
DependencyKind::StartToStart => (
self.project_x(pred.start, track_x, track_w),
self.project_x(task.start, track_x, track_w),
),
DependencyKind::FinishToFinish => (
self.project_x(pred.end.max(pred.start + 1), track_x, track_w),
self.project_x(task.end.max(task.start + 1), track_x, track_w),
),
};
let from_y = (pred_y + self.row_height as i32 / 2)
.clamp(rect.y, rect.y + rect.height as i32 - 1);
let to_y = y + self.row_height as i32 / 2;
// The elbow's vertical segment sits a short step past the predecessor's right edge,
// so a forward link and a backward one both read as an elbow rather than as a
// straight diagonal. One expression, not a branch on the direction: the step is the
// same either way, and the branch would have been two spellings of one value.
let mid_x = from_x + LINK_STUB;
context.draw_line(
Point::new(from_x, from_y),
Point::new(mid_x, from_y),
link_color,
);
context.draw_line(Point::new(mid_x, from_y), Point::new(mid_x, to_y), link_color);
context.draw_line(Point::new(mid_x, to_y), Point::new(to_x, to_y), link_color);
// The head: a small solid triangle at the successor's left edge, pointing right.
let head = LINK_HEAD;
// A stack array: the arrow head's three points are a constant of the drawing, not a
// per-arrow list.
let arrow_head = [
Point::new(to_x, to_y),
Point::new(to_x - head, to_y - head / 2),
Point::new(to_x - head, to_y + head / 2),
];
context.execute_command(crate::render::RenderCommand::DrawPath {
points: arrow_head.into(),
closed: true,
color: link_color,
filled: true,
width: 1,
});
}
}
// ── The "now" line ──
//
// Last, so nothing hides it: it is the one mark on the chart that is *about* the reader.
// Painted only when it falls inside the viewport, because `project_x` extrapolates linearly
// and would otherwise draw a confident line at a position off the plot.
if let Some(today) = self.today {
if self.show_today && (self.viewport_start..=self.viewport_end).contains(&today) {
let x = self.project_x(today, track_x, track_w);
let top = rect.y;
let bottom = rect.y + rect.height as i32;
context.draw_line(Point::new(x, top), Point::new(x, bottom), today_color);
// A one-pixel line at the bottom edge is how a "now" mark is told apart from a
// separator at a glance when the two coincide.
context.draw_line(
Point::new(x.saturating_sub(2), bottom),
Point::new(x + 2, bottom),
today_color,
);
}
}
// The dependency editor is an editing surface, so it is painted over the schedule rather
// than beside it: hiding the bars would make the relationship it edits unverifiable.
if self.show_dependency_editor {
self.dependency_editor.draw(context);
}
// ── Hover read-out ──
//
// The label is what the clip at the row's left edge hides when a name is long, and the
// dates are what a bar's width only approximates; the bubble states both. It is painted
// last so an editor next to it cannot cover it.
if self.show_hover_readout {
if let Some(index) = self.hovered_task {
if let Some(task) = self.tasks.get(index) {
let text = format!("{} {} \u{2192} {}", task.label, task.start, task.end);
let font = effective_font(style);
let metrics = context.measure_text(&text, font);
let width = metrics.width as i32 + 10;
let height = metrics.height.max(1) as i32 + 8;
let x = (self.hover_position.x + 12)
.min(rect.x + rect.width as i32 - width)
.max(rect.x);
let y = (self.hover_position.y + 12)
.min(rect.y + rect.height as i32 - height)
.max(rect.y);
let bubble = Rect::new(x, y, width.max(1) as u32, height.max(1) as u32);
context.fill_rect(bubble, background);
context.draw_rect(bubble, border);
context.draw_text_line(
bubble,
&text,
font,
text_color,
HorizontalAlignment::Left,
);
}
}
}
}
}
// The two companions live in a sibling file so this one stays under the
// 2000-line production limit (principle #9). Re-exporting keeps their public
// path unchanged: `gantt_widget::TimelineAxis` and friends still resolve.
#[path = "gantt_companions.rs"]
mod companions;
pub use companions::{
DateFormat, Dependency, DependencyEditor, TimelineAxis, AXIS_MAX_ZOOM, AXIS_MIN_ZOOM,
};
#[cfg(test)]
mod tests {
use super::*;
use std::sync::{Arc, Mutex};
fn sample_tasks() -> Vec<GanttTask> {
vec![
GanttTask::new("t1", "Design", 0, 10, 100),
GanttTask::new("t2", "Build", 8, 22, 60),
GanttTask::new("t3", "Verify", 20, 30, 20),
]
}
#[test]
fn set_tasks_recomputes_viewport() {
let mut gantt = GanttWidget::new(Rect::new(0, 0, 700, 180));
gantt.set_tasks(sample_tasks());
assert_eq!(gantt.viewport(), (0, 30));
assert_eq!(gantt.tasks().len(), 3);
}
#[test]
fn selecting_task_emits_signal() {
let mut gantt = GanttWidget::new(Rect::new(0, 0, 700, 180));
gantt.set_tasks(sample_tasks());
let selected = Arc::new(Mutex::new(Vec::<String>::new()));
let sink = selected.clone();
gantt.task_selected.connect(move |id| {
if let Ok(mut guard) = sink.lock() {
guard.push(id.as_ref().clone());
}
});
assert!(gantt.select_index(1));
assert_eq!(gantt.selected_id(), Some("t2"));
let got = selected.lock().ok().map(|guard| guard.clone()).unwrap_or_default();
assert_eq!(got, vec!["t2".to_string()]);
}
#[test]
fn wheel_zoom_changes_viewport_span() {
let mut gantt = GanttWidget::new(Rect::new(0, 0, 700, 180));
gantt.set_tasks(sample_tasks());
let before = gantt.viewport();
gantt.handle_event(&Event::wheel(0, -120, 0));
let after_in = gantt.viewport();
assert!((after_in.1 - after_in.0) < (before.1 - before.0));
gantt.handle_event(&Event::wheel(0, 120, 0));
let after_out = gantt.viewport();
assert!((after_out.1 - after_out.0) >= (after_in.1 - after_in.0));
}
#[test]
fn new_creates_default_state() {
let gantt = GanttWidget::new(Rect::new(0, 0, 800, 600));
assert!(gantt.tasks().is_empty());
assert_eq!(gantt.selected_id(), None);
assert_eq!(gantt.viewport(), (0, 100));
}
#[test]
fn task_creation_validates_end_gt_start() {
let task = GanttTask::new("t1", "Task", 10, 5, 50);
assert!(task.end > task.start);
assert_eq!(task.start, 10);
assert_eq!(task.end, 11); // end clamped to start + 1
}
#[test]
fn progress_clamp_upper_bound() {
let task = GanttTask::new("t1", "Task", 0, 10, 200);
assert_eq!(task.progress, 100);
}
#[test]
fn progress_clamp_lower_bound() {
// Progress is u8, so 0 is the minimum. Just check behavior.
let task = GanttTask::new("t1", "Task", 0, 10, 0);
assert_eq!(task.progress, 0);
}
#[test]
fn select_index_out_of_bounds_returns_false() {
let mut gantt = GanttWidget::new(Rect::new(0, 0, 800, 600));
gantt.set_tasks(sample_tasks());
assert!(!gantt.select_index(10));
assert_eq!(gantt.selected_id(), None);
}
#[test]
fn select_index_duplicate_guard() {
let mut gantt = GanttWidget::new(Rect::new(0, 0, 800, 600));
gantt.set_tasks(sample_tasks());
assert!(gantt.select_index(0));
assert_eq!(gantt.selected_id(), Some("t1"));
let emitted = Arc::new(Mutex::new(Vec::<String>::new()));
let sink = emitted.clone();
gantt.task_selected.connect(move |id| {
if let Ok(mut guard) = sink.lock() {
guard.push(id.as_ref().clone());
}
});
gantt.select_index(0);
let got = emitted.lock().ok().map(|g| g.clone()).unwrap_or_default();
assert_eq!(got.len(), 1); // note: select_index always emits even if same
// This is the existing behavior - select_index does not guard
}
#[test]
fn set_viewport_updates_range() {
let mut gantt = GanttWidget::new(Rect::new(0, 0, 800, 600));
gantt.set_viewport(50, 150);
assert_eq!(gantt.viewport(), (50, 150));
}
#[test]
fn set_viewport_maintains_min_span() {
let mut gantt = GanttWidget::new(Rect::new(0, 0, 800, 600));
gantt.set_viewport(10, 10);
assert_eq!(gantt.viewport(), (10, 11));
}
#[test]
fn empty_tasks_returns_default_viewport() {
let mut gantt = GanttWidget::new(Rect::new(0, 0, 800, 600));
gantt.set_tasks(vec![]);
assert!(gantt.tasks().is_empty());
assert_eq!(gantt.selected_id(), None);
assert_eq!(gantt.viewport(), (0, 100));
}
#[test]
fn zoom_with_zero_factor_does_nothing() {
let mut gantt = GanttWidget::new(Rect::new(0, 0, 800, 600));
gantt.set_tasks(sample_tasks());
let before = gantt.viewport();
gantt.zoom(0.0);
assert_eq!(gantt.viewport(), before);
}
/// A milestone is an instant, so it is a diamond and not a bar.
///
/// # The defect this pins
///
/// The widget could only express a **range**: every `GanttTask` was a bar and
/// [`GanttTask::new`] widened a reversed range to `start + 1`. A schedule's milestones -- the
/// sign-off, the release, the review -- are single instants, so the only way to draw one was a
/// one-unit-wide bar, which states that the milestone took a unit of time. The assertion is on
/// the **pixels**: a diamond and a bar of the same centre must not produce the same document,
/// and the milestone's ink must be *narrower* than a bar spanning the same row would be.
#[test]
fn a_milestone_is_a_diamond_rather_than_a_bar() {
use crate::widget::svg::render_to_svg;
let _theme_guard = crate::style::theme_test_guard();
let milestone = GanttTask::milestone("m1", "Sign-off", 10);
assert!(milestone.milestone, "the constructor marks it");
assert_eq!(
milestone.start, milestone.end,
"a milestone is an instant, so its range has no width"
);
// The same instant drawn as an ordinary bar, for comparison.
let as_bar = GanttTask::new("b1", "Sign-off", 10, 10, 0);
assert!(as_bar.end > as_bar.start, "a bar always spans something");
let mut diamond = GanttWidget::new(Rect::new(0, 0, 400, 60));
diamond.set_tasks(vec![milestone]);
let diamond_svg = render_to_svg(&mut diamond);
let mut bar = GanttWidget::new(Rect::new(0, 0, 400, 60));
bar.set_tasks(vec![as_bar]);
let bar_svg = render_to_svg(&mut bar);
assert_ne!(diamond_svg, bar_svg, "a milestone must not be drawn as a bar");
// The diamond is a `<path>` and a bar is a `<rect>`. That difference is asserted directly,
// because `assert_ne!` alone is satisfied by *anything* differing -- including a milestone
// that paints no shape at all. It was checked: knocking out the `DrawPath` above left this
// test green until these two lines existed.
assert!(
diamond_svg.contains("<path"),
"the milestone is drawn as a closed diamond: {diamond_svg}"
);
assert!(
crate::widget::svg::first_shape_bounds(&bar_svg).is_none(),
"an ordinary bar is a rectangle, not a path: {bar_svg}"
);
// And the diamond is centred on the milestone's instant rather than on the bar's left edge.
// Both shapes are compared through the **same** projection, so the assertion is about the
// shape's placement and not about two independently-scraped coordinates: a bar and a diamond
// for the same instant must share a centre.
let (diamond_left, _, diamond_right, _) =
crate::widget::svg::first_shape_bounds(&diamond_svg).expect("the diamond's bounds");
let diamond_centre = (diamond_left + diamond_right) / 2;
let (bar_left, bar_right) = bar_horizontal_span(&bar_svg);
// The diamond is centred on the instant, and the bar *starts* at it: `project_x` maps the
// instant to one x, the diamond straddles it and the bar begins there and runs right. So the
// two are compared as centre-vs-left-edge -- asserting centre-vs-centre would have been
// asserting that a bar is symmetric about its start, which it is not.
assert!(
(diamond_centre - bar_left).abs() <= 2,
"the diamond is centred on the instant and the bar starts at it: \
diamond={diamond_left}..{diamond_right} centre={diamond_centre} bar starts {bar_left}"
);
assert!(
bar_right > bar_left,
"the bar spans forward from the instant: bar={bar_left}..{bar_right}"
);
}
/// The horizontal span of the task **bar**: the shortest plain rectangle in the document.
///
/// The control fills its whole box with a background first, so "the first plain rect" is the
/// control, not the bar -- which is why this picks the narrowest one instead. That is a property
/// of a gantt with one row and one short task, and the assertion above reports both spans so a
/// future geometry change is diagnosable rather than mysterious.
fn bar_horizontal_span(svg: &str) -> (i32, i32) {
svg.split("<rect ")
.filter(|chunk| !chunk.contains("rx=\"") && chunk.contains("width=\""))
.filter_map(|chunk| {
let x = chunk.split("x=\"").nth(1)?.split('"').next()?.parse::<i32>().ok()?;
let w = chunk.split("width=\"").nth(1)?.split('"').next()?.parse::<i32>().ok()?;
Some((x, x + w, w))
})
.min_by_key(|(_, _, w)| *w)
.map(|(x, x2, _)| (x, x2))
.unwrap_or((0, 0))
}
/// The "now" line appears only when the caller says where now is, and only inside the viewport.
///
/// # The defect this pins
///
/// There was no "now" mark at all. A gantt is read against the present -- the question it
/// answers is where the plan stands against today -- so without this the reader has to compare
/// the axis against the wall clock by eye. The assertion is on the painted document, and it
/// checks all three states, because "drawn" and "not drawn" are the whole feature: off the
/// viewport must be silent, on the viewport must lay ink, and the ink must differ from the
/// no-marker case.
#[test]
fn the_now_line_is_drawn_only_where_it_belongs() {
use crate::widget::svg::render_to_svg;
let _theme_guard = crate::style::theme_test_guard();
let tasks = || vec![GanttTask::new("t1", "Design", 0, 10, 100)];
let mut unset = GanttWidget::new(Rect::new(0, 0, 400, 60));
unset.set_tasks(tasks());
assert_eq!(unset.today(), None, "nothing is marked until the caller says so");
let unset_svg = render_to_svg(&mut unset);
let mut marked = GanttWidget::new(Rect::new(0, 0, 400, 60));
marked.set_tasks(tasks());
marked.set_today(Some(5));
assert_eq!(marked.today(), Some(5), "and it reports what was set");
let marked_svg = render_to_svg(&mut marked);
assert_ne!(
marked_svg, unset_svg,
"a marked \"now\" must lay ink, or the marker is not drawn at all"
);
// Outside the viewport it must be silent: `project_x` extrapolates, so an unguarded line
// would be drawn confidently at a position the axis does not span.
let mut outside = GanttWidget::new(Rect::new(0, 0, 400, 60));
outside.set_tasks(tasks());
outside.set_today(Some(9_999));
let outside_svg = render_to_svg(&mut outside);
assert_eq!(
outside_svg, unset_svg,
"a \"now\" outside the viewport must paint nothing extra"
);
}
/// A dependency is a link between two bars, resolved by id and drawn as an elbow.
///
/// # The defect this pins
///
/// `GanttTask` had four fields and none of them related two tasks, so the widget drew a set of
/// bars with no structure between them -- a bar chart with a time axis. The assertion is that the
/// elbowing ink is *added* by the declaration (a dependency-free schedule paints less) and that a
/// **dangling id is skipped rather than drawn**: a caller editing a schedule transiently holds
/// ids that name nothing, and a link to nowhere would be a line with no bar at either end.
#[test]
fn a_dependency_draws_an_elbow_and_a_dangling_one_is_skipped() {
use crate::widget::svg::render_to_svg;
let _theme_guard = crate::style::theme_test_guard();
let linked = || {
vec![
GanttTask::new("a", "Design", 0, 10, 100),
GanttTask::new("b", "Build", 14, 24, 0).depends_on(["a"]),
]
};
let unlinked = || {
vec![GanttTask::new("a", "Design", 0, 10, 100), GanttTask::new("b", "Build", 14, 24, 0)]
};
let mut with = GanttWidget::new(Rect::new(0, 0, 400, 80));
with.set_tasks(linked());
let with_svg = render_to_svg(&mut with);
let mut without = GanttWidget::new(Rect::new(0, 0, 400, 80));
without.set_tasks(unlinked());
let without_svg = render_to_svg(&mut without);
assert_ne!(
with_svg, without_svg,
"declaring a dependency must change the picture, or it is stored and never read"
);
// A dependency naming a task that does not exist is skipped: a transient edit state must not
// paint a line to nowhere, and it must not panic.
let mut dangling = GanttWidget::new(Rect::new(0, 0, 400, 80));
dangling.set_tasks(vec![GanttTask::new("b", "Build", 14, 24, 0).depends_on(["missing"])]);
let dangling_svg = render_to_svg(&mut dangling);
let mut bare = GanttWidget::new(Rect::new(0, 0, 400, 80));
bare.set_tasks(vec![GanttTask::new("b", "Build", 14, 24, 0)]);
let bare_svg = render_to_svg(&mut bare);
assert_eq!(
dangling_svg, bare_svg,
"a dependency that names no task must paint nothing rather than a line to nowhere"
);
}
#[test]
fn critical_path_is_the_longest_duration_chain() {
let mut gantt = GanttWidget::new(Rect::new(0, 0, 700, 180));
gantt.set_tasks(vec![
// 0..10 (10 units) → 10..40 (30) → 40..45 (5): total 45.
GanttTask::new("a", "Design", 0, 10, 100),
GanttTask::new("b", "Build", 10, 40, 0).depends_on(["a"]),
GanttTask::new("c", "Ship", 40, 45, 0).depends_on(["b"]),
// A short side branch: 2 units, not critical.
GanttTask::new("x", "Side", 0, 2, 0),
]);
assert_eq!(gantt.critical_path(), vec!["a".to_string(), "b".to_string(), "c".to_string()]);
// The property is what turns the highlight on; reading it is the switch's own state.
gantt.set("show_critical_path", CapabilityValue::Bool(true)).expect("bool accepted");
assert!(gantt.show_critical_path());
}
#[test]
fn critical_path_names_nothing_when_every_task_is_zero_length_and_isolated() {
let mut gantt = GanttWidget::new(Rect::new(0, 0, 700, 180));
gantt.set_tasks(vec![GanttTask::milestone("m", "Start", 5)]);
assert!(
gantt.critical_path().is_empty(),
"one instant is not a chain, and naming it would be an invented claim"
);
}
#[test]
fn a_dependency_cycle_has_no_critical_path() {
let mut gantt = GanttWidget::new(Rect::new(0, 0, 700, 180));
gantt.set_tasks(vec![
GanttTask::new("a", "A", 0, 10, 0).depends_on(["b"]),
GanttTask::new("b", "B", 10, 20, 0).depends_on(["a"]),
]);
assert!(
gantt.critical_path().is_empty(),
"a cycle has no longest chain; reporting one would hide the caller's error"
);
}
#[test]
fn viewport_changed_fires_on_zoom_and_on_task_replacement() {
let mut gantt = GanttWidget::new(Rect::new(0, 0, 700, 180));
gantt.set_tasks(sample_tasks());
let ranges = Arc::new(Mutex::new(Vec::<(i64, i64)>::new()));
let sink = ranges.clone();
gantt.viewport_changed.connect(move |range| {
if let Ok(mut guard) = sink.lock() {
guard.push(*range);
}
});
gantt.handle_event(&Event::wheel(0, -120, 0));
gantt.set_tasks(sample_tasks());
let got = ranges.lock().ok().map(|guard| guard.clone()).unwrap_or_default();
assert!(got.len() >= 2, "both changes must be reported, got {got:?}");
assert!(got[0].1 - got[0].0 < 30, "the zoom must shrink the range: {:?}", got[0]);
}
#[test]
fn dragging_a_bars_right_edge_resizes_and_reports_start_and_finish() {
let mut gantt = GanttWidget::new(Rect::new(0, 0, 700, 180));
gantt.set_tasks(sample_tasks());
let started = Arc::new(Mutex::new(Vec::<String>::new()));
let finished = Arc::new(Mutex::new(Vec::<String>::new()));
let start_sink = started.clone();
let finish_sink = finished.clone();
gantt.task_resize_started.connect(move |id| {
if let Ok(mut guard) = start_sink.lock() {
guard.push(id.as_ref().clone());
}
});
gantt.task_resize_finished.connect(move |id| {
if let Ok(mut guard) = finish_sink.lock() {
guard.push(id.as_ref().clone());
}
});
let (track_x, track_w) = gantt.track_geometry();
let task = &gantt.tasks()[0];
let x1 = gantt.project_x(task.end, track_x, track_w);
let y = gantt.lane_rect(0).y + 10;
gantt.handle_event(&Event::mouse_press(x1 - 1, y, 1));
gantt.handle_event(&Event::mouse_move(x1 + 20, y));
gantt.handle_event(&Event::mouse_release(x1 + 20, y, 1));
assert!(
gantt.tasks()[0].end > 10,
"the end edge must move: end is {}",
gantt.tasks()[0].end
);
assert_eq!(gantt.tasks()[0].start, 0, "resizing the end pins the start");
assert_eq!(
started.lock().ok().map(|guard| guard.clone()).unwrap_or_default(),
vec!["t1".to_string()]
);
assert_eq!(
finished.lock().ok().map(|guard| guard.clone()).unwrap_or_default(),
vec!["t1".to_string()]
);
}
#[test]
fn dragging_the_progress_strip_changes_progress_without_moving_the_bar() {
let mut gantt = GanttWidget::new(Rect::new(0, 0, 700, 180));
gantt.set_tasks(sample_tasks());
let (track_x, track_w) = gantt.track_geometry();
let (start, end) = {
let task = &gantt.tasks()[0];
(task.start, task.end)
};
let x0 = gantt.project_x(start, track_x, track_w);
let x1 = gantt.project_x(end, track_x, track_w);
let lane_y = gantt.lane_rect(0).y;
let bar_bottom = lane_y + gantt.row_height() as i32 - 6;
// Halfway across the bottom strip: the bar's 100 % becomes 50 %.
let mid = x0 + (x1 - x0) / 2;
gantt.handle_event(&Event::mouse_press(mid, bar_bottom, 1));
gantt.handle_event(&Event::mouse_release(mid, bar_bottom, 1));
let task = &gantt.tasks()[0];
assert_eq!((task.start, task.end), (start, end), "progress must not move the bar");
assert!((task.progress as i32 - 50).abs() <= 1, "progress was {}", task.progress);
}
#[test]
fn dependency_lookup_is_indexed_and_survives_task_replacement() {
let mut gantt = GanttWidget::new(Rect::new(0, 0, 700, 180));
gantt.set_tasks(sample_tasks());
assert_eq!(gantt.id_index.get("t3").copied(), Some(2));
gantt.set_tasks(vec![GanttTask::new("only", "Only", 0, 5, 0)]);
assert_eq!(gantt.id_index.get("t3"), None);
assert_eq!(gantt.id_index.get("only").copied(), Some(0));
}
// ── COMP-14: gantt companions ──────────────────────────────────────────
#[test]
fn axis_pixel_and_date_round_trip() {
let axis = TimelineAxis::new(Rect::new(0, 0, 320, 24));
for date in [0, 25, 50, 75, 100] {
let x = axis.date_to_pixel(date);
assert_eq!(axis.pixel_to_date(x), date, "date {date} round-trips through x={x}");
}
// A pixel round-trip is limited by the axis resolution: one pixel can stand
// for more than one unit, so the value may move by at most one pixel.
for x in [8, 84, 160, 236, 312] {
let date = axis.pixel_to_date(x);
assert!((axis.date_to_pixel(date) - x).abs() <= 1, "x={x} drifted");
}
// Outside the track clamps to the ends.
assert_eq!(axis.pixel_to_date(-100), 0);
assert_eq!(axis.pixel_to_date(10_000), 100);
}
#[test]
fn axis_zoom_changes_the_range_and_reports_it() {
let mut axis = TimelineAxis::new(Rect::new(0, 0, 320, 24));
let ranges = Arc::new(Mutex::new(Vec::<(i64, i64)>::new()));
let sink = ranges.clone();
axis.scale_changed.connect(move |range| {
if let Ok(mut guard) = sink.lock() {
guard.push(*range);
}
});
assert!(axis.set_zoom_level(2.0));
assert_eq!(axis.range(), (25, 75));
assert!((axis.zoom_level() - 2.0).abs() < f32::EPSILON);
assert!(!axis.set_zoom_level(2.0), "an unchanged level is a no-op");
assert!(!axis.set_zoom_level(f32::NAN), "non-finite levels are refused");
assert!(axis.set_zoom_level(0.0));
assert!((axis.zoom_level() - AXIS_MIN_ZOOM).abs() < f32::EPSILON);
assert_eq!(axis.range(), (-150, 250));
assert!(axis.set_zoom_level(1000.0));
assert!((axis.zoom_level() - AXIS_MAX_ZOOM).abs() < f32::EPSILON);
// `set_range` is the explicit path and returns to 1:1.
axis.set_range(10, 20);
assert_eq!(axis.range(), (10, 20));
assert!((axis.zoom_level() - 1.0).abs() < f32::EPSILON);
let got = ranges.lock().ok().map(|guard| guard.clone()).unwrap_or_default();
assert_eq!(
got,
vec![(25, 75), (-150, 250), (49, 51), (10, 20)],
"each committed change reports its range once"
);
}
#[test]
fn axis_formats_numeric_and_iso_labels() {
let mut axis = TimelineAxis::new(Rect::new(0, 0, 320, 24));
assert_eq!(axis.format_tick(42), "42");
assert_eq!(axis.date_format(), DateFormat::Numeric);
axis.set_date_format(DateFormat::IsoDate);
assert_eq!(axis.format_tick(0), "1970-01-01");
assert_eq!(axis.format_tick(31), "1970-02-01");
assert_eq!(axis.format_tick(-1), "1969-12-31");
axis.set("date_format", CapabilityValue::String("numeric".into()))
.expect("numeric is a published token");
assert_eq!(axis.date_format(), DateFormat::Numeric);
assert!(axis.set("date_format", CapabilityValue::String("strftime".into())).is_err());
}
#[test]
fn axis_ticks_cover_the_range_with_the_requested_density() {
let mut axis = TimelineAxis::new(Rect::new(0, 0, 320, 24));
axis.set_tick_density(4);
let ticks = axis.ticks();
assert_eq!(ticks.len(), 5);
assert_eq!(ticks.first().map(|(value, _)| *value), Some(0));
assert_eq!(ticks.last().map(|(value, _)| *value), Some(100));
assert!(ticks.windows(2).all(|pair| pair[0].1 < pair[1].1), "left to right");
// A span smaller than the density collapses duplicate ticks instead of
// painting several labels on one pixel.
axis.set_range(0, 2);
axis.set_tick_density(8);
assert!(axis.ticks().len() <= 3);
}
#[test]
fn axis_properties_round_trip() {
let mut axis = TimelineAxis::new(Rect::new(0, 0, 320, 24));
axis.set("tick_density", CapabilityValue::UInt(3)).expect("density");
axis.set("range_end", CapabilityValue::Int(60)).expect("range end");
assert_eq!(axis.range(), (0, 60));
assert_eq!(axis.get("tick_density").unwrap(), CapabilityValue::UInt(3));
assert_eq!(axis.get("range_end").unwrap(), CapabilityValue::Int(60));
assert!(axis.set("range", CapabilityValue::Int(1)).is_err());
axis.set("zoom_level", CapabilityValue::Float(2.0)).expect("zoom");
assert_eq!(axis.range(), (15, 45));
assert!((axis.zoom_level() - 2.0).abs() < f32::EPSILON);
}
#[test]
fn dependency_editor_adds_rejects_and_removes() {
let mut editor = DependencyEditor::new(Rect::new(0, 0, 260, 160));
let added = Arc::new(Mutex::new(Vec::<Dependency>::new()));
let sink = added.clone();
editor.dependency_added.connect(move |dependency| {
if let Ok(mut guard) = sink.lock() {
guard.push(dependency.as_ref().clone());
}
});
let removed = Arc::new(Mutex::new(Vec::<Dependency>::new()));
let sink = removed.clone();
editor.dependency_removed.connect(move |dependency| {
if let Ok(mut guard) = sink.lock() {
guard.push(dependency.as_ref().clone());
}
});
assert!(editor.add_dependency(Dependency::new("a", "b")));
assert!(editor.add_dependency(Dependency::new("b", "c")));
assert!(!editor.add_dependency(Dependency::new("b", "c")), "duplicates are refused");
assert!(!editor.add_dependency(Dependency::new("a", "a")), "self-edges are refused");
assert_eq!(editor.dependencies().len(), 2);
assert!(editor.remove_dependency(&Dependency::new("a", "b")));
assert!(!editor.remove_dependency(&Dependency::new("a", "b")));
assert_eq!(editor.dependencies().to_vec(), vec![Dependency::new("b", "c")]);
let added = added.lock().ok().map(|guard| guard.clone()).unwrap_or_default();
assert_eq!(added, vec![Dependency::new("a", "b"), Dependency::new("b", "c")]);
let removed = removed.lock().ok().map(|guard| guard.clone()).unwrap_or_default();
assert_eq!(removed, vec![Dependency::new("a", "b")]);
}
#[test]
fn dependency_editor_set_dependencies_sanitises_the_list() {
let mut editor = DependencyEditor::new(Rect::new(0, 0, 260, 160));
editor.set_dependencies(vec![
Dependency::new("a", "b"),
Dependency::new("a", "b"),
Dependency::new("c", "c"),
Dependency::new("b", "c"),
]);
assert_eq!(
editor.dependencies().to_vec(),
vec![Dependency::new("a", "b"), Dependency::new("b", "c")]
);
}
#[test]
fn dependency_editor_hit_tests_rows_and_reports_selection() {
let mut editor = DependencyEditor::new(Rect::new(0, 0, 260, 160));
assert!(editor.add_dependency(Dependency::new("a", "b")));
assert!(editor.add_dependency(Dependency::new("b", "c")));
let (start, end) = editor.link_geometry(0).expect("row 0 is visible");
let midpoint = Point::new((start.x + end.x) / 2, start.y);
assert_eq!(editor.hit_link(midpoint), Some(0));
let second = editor.link_geometry(1).expect("row 1 is visible");
assert_eq!(editor.hit_link(Point::new(second.0.x, second.0.y)), Some(1));
assert_eq!(editor.hit_link(Point::new(5, 5)), None);
assert_eq!(editor.link_geometry(2), None);
let selected = Arc::new(Mutex::new(Vec::<Dependency>::new()));
let sink = selected.clone();
editor.link_selected.connect(move |dependency| {
if let Ok(mut guard) = sink.lock() {
guard.push(dependency.as_ref().clone());
}
});
editor.handle_event(&Event::mouse_press(midpoint.x, midpoint.y, 1));
assert_eq!(
selected.lock().ok().map(|guard| guard.clone()).unwrap_or_default(),
vec![Dependency::new("a", "b")]
);
editor.set_editable(false);
editor.handle_event(&Event::mouse_press(midpoint.x, midpoint.y, 1));
assert_eq!(
selected.lock().ok().map(|guard| guard.clone()).unwrap_or_default().len(),
1,
"a read-only editor does not select"
);
}
#[test]
fn dependency_editor_properties_round_trip() {
let mut editor = DependencyEditor::new(Rect::new(0, 0, 260, 160));
assert_eq!(editor.get("editable").unwrap(), CapabilityValue::Bool(true));
editor.set("editable", CapabilityValue::Bool(false)).expect("editable");
assert!(!editor.editable());
assert!(editor.set("dependencies", CapabilityValue::UInt(0)).is_err());
assert_eq!(editor.get("dependencies").unwrap(), CapabilityValue::UInt(0));
}
/// The mounted axis is a view of the viewport: painting it leaves both on the same range.
#[test]
fn the_mounted_axis_follows_the_viewport() {
use crate::render::{PaintBackend, SoftwarePaintBackend};
let mut gantt = GanttWidget::new(Rect::new(0, 0, 700, 180));
gantt.set_show_time_axis(true);
gantt.set_tasks(sample_tasks());
let mut backend = SoftwarePaintBackend::new(crate::core::Size::new(700, 180), 1.0);
backend.begin_frame(Color::WHITE);
{
let mut context = RenderContext::new(&mut backend);
gantt.draw(&mut context);
}
backend.end_frame();
assert_eq!(gantt.timeline_axis().range(), gantt.viewport());
gantt.set_viewport(5, 25);
assert_eq!(gantt.timeline_axis().range(), gantt.viewport(), "a zoom is reflected");
}
/// Dependency editing lives on the chart: additions/removals and a press are re-emitted by the
/// widget, not only by the child editor a caller never mounted itself.
#[test]
fn dependency_edits_and_selection_reach_the_chart() {
let mut gantt = GanttWidget::new(Rect::new(0, 0, 700, 240));
let added = Arc::new(Mutex::new(Vec::<Dependency>::new()));
let removed = Arc::new(Mutex::new(Vec::<Dependency>::new()));
let selected = Arc::new(Mutex::new(Vec::<Dependency>::new()));
let sink = added.clone();
gantt.dependency_added.connect(move |edge| {
if let Ok(mut guard) = sink.lock() {
guard.push((*edge).clone());
}
});
let sink = removed.clone();
gantt.dependency_removed.connect(move |edge| {
if let Ok(mut guard) = sink.lock() {
guard.push((*edge).clone());
}
});
let sink = selected.clone();
gantt.link_selected.connect(move |edge| {
if let Ok(mut guard) = sink.lock() {
guard.push((*edge).clone());
}
});
assert!(gantt.add_dependency("a", "b"));
assert!(!gantt.add_dependency("a", "b"), "a duplicate is refused by the editor");
assert_eq!(
added.lock().ok().map(|guard| guard.clone()).unwrap_or_default(),
vec![Dependency::new("a", "b")]
);
gantt.set_show_dependency_editor(true);
// The editor is 220 px wide on the right; row 0 begins below its caption.
gantt.handle_event(&Event::mouse_press(520, 30, 1));
assert_eq!(
selected.lock().ok().map(|guard| guard.clone()).unwrap_or_default(),
vec![Dependency::new("a", "b")]
);
assert!(gantt.remove_dependency("a", "b"));
assert!(!gantt.remove_dependency("a", "b"));
assert_eq!(
removed.lock().ok().map(|guard| guard.clone()).unwrap_or_default(),
vec![Dependency::new("a", "b")]
);
}
/// The editor's edge list can be rebuilt from the tasks' two dependency spellings.
#[test]
fn dependencies_sync_from_tasks() {
let mut gantt = GanttWidget::new(Rect::new(0, 0, 700, 180));
gantt.set_tasks(vec![
GanttTask::new("t1", "Design", 0, 5, 0),
GanttTask::new("t2", "Build", 5, 10, 0).depends_on(["t1"]),
]);
gantt.sync_dependencies_from_tasks();
assert_eq!(gantt.dependency_editor().dependencies(), &[Dependency::new("t1", "t2")]);
}
}
#[cfg(test)]
mod issue_2_8_tests {
use super::*;
fn two_tasks() -> Vec<GanttTask> {
let mut second = GanttTask::new("b", "Build", 5, 9, 0);
second
.dependencies
.push(GanttDependency { id: "a".to_string(), kind: DependencyKind::StartToStart });
vec![GanttTask::new("a", "Design", 0, 5, 0), second]
}
/// SP-15: the typed relationship survives a trip through the editor and back.
#[test]
fn dependency_kinds_survive_both_sync_directions() {
let mut gantt = GanttWidget::new(Rect::new(0, 0, 600, 300));
gantt.set_tasks(two_tasks());
gantt.sync_dependencies_from_tasks();
assert_eq!(gantt.dependency_editor().dependencies()[0].kind, DependencyKind::StartToStart);
gantt.dependency_editor_mut().set_dependencies(vec![Dependency::with_kind(
"a",
"b",
DependencyKind::FinishToFinish,
)]);
gantt.sync_tasks_from_dependencies();
assert_eq!(gantt.tasks()[1].dependencies[0].kind, DependencyKind::FinishToFinish);
}
/// SP-P21: the critical path is cached but follows a task replacement.
#[test]
fn the_critical_path_cache_follows_task_replacement() {
let mut gantt = GanttWidget::new(Rect::new(0, 0, 600, 300));
gantt.set_tasks(two_tasks());
assert_eq!(gantt.critical_path(), vec!["a".to_string(), "b".to_string()]);
gantt.set_tasks(vec![
GanttTask::new("a", "Design", 0, 2, 0),
GanttTask::new("b", "Build", 2, 20, 0),
]);
// Without the edge, `b` is the longest single chain.
assert_eq!(gantt.critical_path(), vec!["b".to_string()]);
gantt.set_tasks(vec![GanttTask::new("solo", "Solo", 0, 1, 0)]);
assert_eq!(gantt.critical_path(), vec!["solo".to_string()]);
}
}