gilt 2.1.0

Fast, beautiful terminal formatting for Rust — styles, tables, trees, syntax highlighting, progress bars, markdown.
Documentation
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
//! Main progress tracking orchestrator.

use std::collections::HashMap;
use std::io::{self, Read, Seek, SeekFrom};

use crate::console::{Console, ConsoleOptions, Renderable};
use crate::live::Live;
use crate::progress::columns::{BarColumn, TaskProgressColumn, TextColumn, TimeRemainingColumn};
use crate::progress::task::{current_time_secs, Task, TaskId};
use crate::segment::{Segment, TaskbarState};
use crate::style::Style;
use crate::table::Table;
use crate::text::Text;
use crate::utils::filesize;

// ---------------------------------------------------------------------------
// ProgressColumn trait
// ---------------------------------------------------------------------------

/// Trait for columns that render task information in a progress display.
///
/// Each column is responsible for producing a [`Text`] renderable from
/// a [`Task`] reference.
///
/// The default `render_renderable` method wraps the `Text` returned by
/// [`render`] as a [`RenderableArc`] so columns can participate in the
/// richer renderable pipeline without requiring every implementor to change
/// its return type (least-breaking option — P2 fix, item 3).  Custom columns
/// that need to return non-`Text` renderables can override
/// `render_renderable` directly while keeping `render` as a no-op.
pub trait ProgressColumn: Send + Sync {
    /// Render this column for the given task.
    fn render(&self, task: &Task) -> Text;

    /// Render this column as a [`RenderableArc`] for richer renderable support.
    ///
    /// The default implementation wraps the result of [`render`] in an `Arc`.
    /// Override this to return a custom `Renderable` type (e.g. an image, a
    /// styled widget) without changing the `render` signature.
    fn render_renderable(&self, task: &Task) -> crate::console::RenderableArc {
        use std::sync::Arc;
        Arc::new(self.render(task))
    }

    /// Maximum refresh rate in Hz (refreshes per second), or `None` for
    /// unlimited.
    ///
    /// When `Some(hz)`, the render loop will skip re-rendering this column
    /// if the elapsed time since the last render is less than `1.0 / hz`
    /// seconds — matching rich's `ProgressColumn.max_refresh` parity (P2 fix).
    fn max_refresh(&self) -> Option<f64> {
        None
    }
}

// ---------------------------------------------------------------------------
// DownloadColumn
// ---------------------------------------------------------------------------

/// A column that shows `downloaded/total` as human-readable file sizes.
///
/// By default, sizes are formatted with SI (base-1000) units using
/// [`filesize::decimal`]. Set `binary_units` to `true` to use IEC
/// (base-1024) units via [`filesize::binary`].
#[derive(Debug, Clone)]
pub struct DownloadColumn {
    /// When `true`, format sizes with binary (base-1024) units (KiB, MiB, ...).
    /// When `false` (default), use decimal (base-1000) units (kB, MB, ...).
    pub binary_units: bool,
}

impl DownloadColumn {
    /// Create a new `DownloadColumn` with SI decimal units (default).
    pub fn new() -> Self {
        Self {
            binary_units: false,
        }
    }

    /// Create a new `DownloadColumn` that uses IEC binary units.
    pub fn with_binary_units(mut self, binary: bool) -> Self {
        self.binary_units = binary;
        self
    }

    /// Format a byte count using the configured unit system.
    ///
    /// This uses independent magnitude selection based on `size` alone.
    /// Prefer [`format_size_with_ref`](Self::format_size_with_ref) when
    /// formatting a pair of values (completed/total) to keep units consistent.
    #[allow(dead_code)]
    pub(crate) fn format_size(&self, size: u64) -> String {
        if self.binary_units {
            filesize::binary(size, 1, " ")
        } else {
            filesize::decimal(size, 1, " ")
        }
    }

    /// Format `size` using the same magnitude bracket as `reference`.
    ///
    /// This keeps the unit consistent between the completed and total values
    /// so the display doesn't flip from "kB" to "MB" mid-download.
    pub(crate) fn format_size_with_ref(&self, size: u64, reference: u64) -> String {
        // Determine which suffix/divisor to use from the reference magnitude.
        if self.binary_units {
            // IEC: GiB ≥ 2^30, MiB ≥ 2^20, KiB ≥ 2^10
            if reference >= 1 << 30 {
                format!("{:.1} GiB", size as f64 / (1u64 << 30) as f64)
            } else if reference >= 1 << 20 {
                format!("{:.1} MiB", size as f64 / (1u64 << 20) as f64)
            } else if reference >= 1 << 10 {
                format!("{:.1} KiB", size as f64 / (1u64 << 10) as f64)
            } else {
                format!("{size} B")
            }
        } else {
            // SI: GB ≥ 1e9, MB ≥ 1e6, kB ≥ 1e3
            if reference >= 1_000_000_000 {
                format!("{:.1} GB", size as f64 / 1_000_000_000.0)
            } else if reference >= 1_000_000 {
                format!("{:.1} MB", size as f64 / 1_000_000.0)
            } else if reference >= 1_000 {
                format!("{:.1} kB", size as f64 / 1_000.0)
            } else {
                format!("{size} B")
            }
        }
    }
}

impl Default for DownloadColumn {
    fn default() -> Self {
        Self::new()
    }
}

impl ProgressColumn for DownloadColumn {
    fn render(&self, task: &Task) -> Text {
        // Use the same unit magnitude for both sides of the slash: derive the
        // unit from max(completed, total) so the display is consistent and the
        // unit doesn't flip as the download progresses (rich parity, P2 fix).
        let reference_bytes = match task.total {
            Some(t) => (task.completed as u64).max(t as u64),
            None => task.completed as u64,
        };
        let completed = self.format_size_with_ref(task.completed as u64, reference_bytes);
        let total = match task.total {
            Some(t) => self.format_size_with_ref(t as u64, reference_bytes),
            None => "?".to_string(),
        };
        let style = Style::parse("progress.download");
        Text::new(&format!("{completed}/{total}"), style)
    }
}

// ---------------------------------------------------------------------------
// TransferSpeedColumn
// ---------------------------------------------------------------------------

/// A column that shows the current transfer speed in human-readable form.
///
/// By default, speeds are formatted with SI (base-1000) units using
/// [`filesize::decimal`]. Set `binary_units` to `true` to use IEC
/// (base-1024) units via [`filesize::binary`].
#[derive(Debug, Clone)]
pub struct TransferSpeedColumn {
    /// When `true`, format speeds with binary (base-1024) units (KiB, MiB, ...).
    /// When `false` (default), use decimal (base-1000) units (kB, MB, ...).
    pub binary_units: bool,
}

impl TransferSpeedColumn {
    /// Create a new `TransferSpeedColumn` with SI decimal units (default).
    pub fn new() -> Self {
        Self {
            binary_units: false,
        }
    }

    /// Create a new `TransferSpeedColumn` that uses IEC binary units.
    pub fn with_binary_units(mut self, binary: bool) -> Self {
        self.binary_units = binary;
        self
    }

    /// Format a byte count using the configured unit system.
    pub(crate) fn format_size(&self, size: u64) -> String {
        if self.binary_units {
            filesize::binary(size, 1, " ")
        } else {
            filesize::decimal(size, 1, " ")
        }
    }
}

impl Default for TransferSpeedColumn {
    fn default() -> Self {
        Self::new()
    }
}

impl ProgressColumn for TransferSpeedColumn {
    fn render(&self, task: &Task) -> Text {
        let style = Style::parse("progress.data.speed");
        match task.speed() {
            Some(speed) => {
                let formatted = self.format_size(speed as u64);
                Text::new(&format!("{formatted}/s"), style)
            }
            None => Text::new("?", style),
        }
    }
}

// ---------------------------------------------------------------------------
// RenderableColumn
// ---------------------------------------------------------------------------

/// A column that renders custom content via a user-supplied callback.
///
/// This allows callers to inject arbitrary rendering logic without
/// defining a new struct that implements [`ProgressColumn`].
///
/// # Examples
///
/// ```
/// use gilt::progress::{ProgressColumn, RenderableColumn, Task};
/// use gilt::text::Text;
/// use gilt::style::Style;
///
/// let col = RenderableColumn::new(|task: &Task| {
///     Text::new(&format!("Step {}", task.completed as u64), Style::null())
/// });
/// let task = Task::new(0, "demo", Some(10.0));
/// assert_eq!(col.render(&task).plain(), "Step 0");
/// ```
pub struct RenderableColumn {
    /// Callback that produces a [`Text`] renderable from a [`Task`].
    pub callback: Box<dyn Fn(&Task) -> Text + Send + Sync>,
}

impl RenderableColumn {
    /// Create a new RenderableColumn with the given rendering callback.
    pub fn new<F>(callback: F) -> Self
    where
        F: Fn(&Task) -> Text + Send + Sync + 'static,
    {
        RenderableColumn {
            callback: Box::new(callback),
        }
    }
}

impl ProgressColumn for RenderableColumn {
    fn render(&self, task: &Task) -> Text {
        (self.callback)(task)
    }
}

// ---------------------------------------------------------------------------
// Progress
// ---------------------------------------------------------------------------

/// The main progress tracking orchestrator.
///
/// Manages a collection of [`Task`]s, renders them through configurable
/// [`ProgressColumn`]s, and displays the result via a [`Live`] display.
///
/// # Examples
///
/// ```no_run
/// use gilt::progress::{Progress, BarColumn, TextColumn, TaskProgressColumn, TimeRemainingColumn};
///
/// let mut progress = Progress::new(Progress::default_columns());
/// let task_id = progress.add_task("Downloading...", Some(100.0), true);
/// progress.start();
/// for i in 0..100 {
///     progress.advance(task_id, 1.0);
/// }
/// progress.stop();
/// ```
pub struct Progress {
    /// Columns to render for each task.
    columns: Vec<Box<dyn ProgressColumn>>,
    /// All tracked tasks.
    tasks: Vec<Task>,
    /// Live display for rendering.
    live: Live,
    /// Counter for generating unique task IDs.
    task_id_counter: usize,
    /// Duration in seconds for the speed estimation sliding window.
    speed_estimate_period: f64,
    /// Function to get the current time (injectable for testing).
    get_time: Box<dyn Fn() -> f64 + Send>,
    /// Whether rendering is disabled.
    disable: bool,
    /// Whether the table should expand to fill available width.
    expand: bool,
    /// When `true`, emit OSC 9;4 taskbar progress updates on each refresh.
    ///
    /// Default: `false`. Enable with [`Progress::with_taskbar`].
    taskbar: bool,
    /// Per-column last-render timestamps (indexed by column position).
    ///
    /// Used to implement `max_refresh` rate-limiting: a column with
    /// `max_refresh = Some(hz)` is skipped when the elapsed time since its
    /// last render is less than `1 / hz` seconds.
    column_last_rendered: Vec<f64>,
    /// Per-column × per-task cached Text output for rate-limited columns.
    ///
    /// Index: `[column_idx][task_idx]`. Populated on first render; reused
    /// when the column is within its `max_refresh` interval.
    column_render_cache: Vec<Vec<Text>>,
}

impl Progress {
    /// Create a new Progress with the given columns.
    pub fn new(columns: Vec<Box<dyn ProgressColumn>>) -> Self {
        let n = columns.len();
        Progress {
            columns,
            tasks: Vec::new(),
            live: Live::new(Text::empty())
                .with_auto_refresh(true)
                .with_refresh_per_second(10.0),
            task_id_counter: 0,
            speed_estimate_period: 30.0,
            get_time: Box::new(current_time_secs),
            disable: false,
            expand: false,
            taskbar: false,
            column_last_rendered: vec![0.0; n],
            column_render_cache: vec![Vec::new(); n],
        }
    }

    /// Return the default set of columns:
    /// TextColumn (description), BarColumn, TaskProgressColumn, TimeRemainingColumn.
    pub fn default_columns() -> Vec<Box<dyn ProgressColumn>> {
        vec![
            Box::new(TextColumn::new("{task.description}")),
            Box::new(BarColumn::default()),
            Box::new(TaskProgressColumn::default()),
            Box::new(TimeRemainingColumn::default()),
        ]
    }

    // -- Builder methods ----------------------------------------------------

    /// Set the console for the live display (builder pattern).
    #[must_use]
    pub fn with_console(mut self, console: Console) -> Self {
        self.live = self.live.with_console(console);
        self
    }

    /// Enable or disable auto-refresh (builder pattern).
    #[must_use]
    pub fn with_auto_refresh(mut self, auto_refresh: bool) -> Self {
        self.live = self.live.with_auto_refresh(auto_refresh);
        self
    }

    /// Enable or disable transient mode (builder pattern).
    #[must_use]
    pub fn with_transient(mut self, transient: bool) -> Self {
        self.live = self.live.with_transient(transient);
        self
    }

    /// Set the refresh rate in refreshes per second (builder pattern).
    #[must_use]
    pub fn with_refresh_per_second(mut self, rate: f64) -> Self {
        self.live = self.live.with_refresh_per_second(rate);
        self
    }

    /// Set the speed estimation period in seconds (builder pattern).
    #[must_use]
    pub fn with_speed_estimate_period(mut self, seconds: f64) -> Self {
        self.speed_estimate_period = seconds;
        self
    }

    /// Enable or disable progress display (builder pattern).
    #[must_use]
    pub fn with_disable(mut self, disable: bool) -> Self {
        self.disable = disable;
        self
    }

    /// Enable or disable table expansion (builder pattern).
    #[must_use]
    pub fn with_expand(mut self, expand: bool) -> Self {
        self.expand = expand;
        self
    }

    /// Enable or disable OSC 9;4 taskbar progress updates (builder pattern).
    ///
    /// When enabled, `Progress` emits ConEmu/Windows Terminal taskbar progress
    /// (Normal with overall percent) on each refresh, and removes it on stop.
    /// Default: `false`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use gilt::progress::Progress;
    ///
    /// let mut progress = Progress::new(Progress::default_columns())
    ///     .with_taskbar(true);
    /// progress.start();
    /// progress.add_task("demo", Some(100.0), true);
    /// progress.stop();
    /// ```
    #[must_use]
    pub fn with_taskbar(mut self, enabled: bool) -> Self {
        self.taskbar = enabled;
        self
    }

    /// Set a custom time function for testing (builder pattern).
    #[must_use]
    pub fn with_get_time<F>(mut self, f: F) -> Self
    where
        F: Fn() -> f64 + Send + 'static,
    {
        self.get_time = Box::new(f);
        self
    }

    // -- Task management ----------------------------------------------------

    /// Add a new task and return its ID.
    ///
    /// When `start` is `true` (the default for most callers), `start_time` is
    /// set immediately. When `start` is `false` the task is created in a
    /// not-yet-started state and must be explicitly started with
    /// [`start_task`](Self::start_task).
    pub fn add_task(&mut self, description: &str, total: Option<f64>, start: bool) -> TaskId {
        let id = self.task_id_counter;
        self.task_id_counter += 1;
        let mut task = Task::new(id, description, total);
        if start {
            let now = (self.get_time)();
            task.start_time = Some(now);
        }
        self.tasks.push(task);
        id
    }

    /// Update a task with new values.
    ///
    /// Any parameter set to `None` is left unchanged. Use `advance` to
    /// set a relative increment instead of an absolute `completed` value.
    /// `fields`, when `Some`, is merged into `task.fields` (existing keys
    /// are overwritten; unmentioned keys are preserved).
    ///
    /// Refreshes the live display after the state mutation so the new
    /// values appear without waiting for the next auto-refresh tick.
    #[allow(clippy::too_many_arguments)]
    pub fn update(
        &mut self,
        task_id: TaskId,
        completed: Option<f64>,
        total: Option<f64>,
        advance: Option<f64>,
        description: Option<&str>,
        visible: Option<bool>,
        fields: Option<HashMap<String, String>>,
    ) {
        let now = (self.get_time)();
        let mut changed = false;
        if let Some(task) = self.tasks.iter_mut().find(|t| t.id == task_id) {
            if let Some(desc) = description {
                task.description = desc.to_string();
                changed = true;
            }
            if let Some(t) = total {
                // When the total changes the existing speed samples become
                // meaningless (they measured progress towards a different
                // goal).  Clear both the sliding window and the history.
                if task.total != Some(t) {
                    task.samples.clear();
                    task.progress.clear();
                }
                task.total = Some(t);
                changed = true;
            }
            if let Some(c) = completed {
                task.completed = c;
                changed = true;
            }
            if let Some(a) = advance {
                task.completed += a;
                changed = true;
            }
            if let Some(v) = visible {
                task.visible = v;
                changed = true;
            }
            if let Some(f) = fields {
                task.fields.extend(f);
                changed = true;
            }

            // Record a speed sample only when something actually changed —
            // recording on no-op calls would corrupt the speed estimate.
            if changed && task.started() && !task.finished() {
                task.record_sample(now, self.speed_estimate_period);
            }

            // Check if task just finished.
            if let Some(t) = task.total {
                if task.completed >= t && task.finished_time.is_none() {
                    task.finished_speed = task.speed();
                    task.finished_time = Some(now);
                }
            }
        }
        if changed {
            self.mark_dirty();
        }
    }

    /// Advance a task's completed count by the given amount.
    ///
    /// Triggers a live-display refresh through [`update`](Self::update).
    pub fn advance(&mut self, task_id: TaskId, advance: f64) {
        self.update(task_id, None, None, Some(advance), None, None, None);
    }

    /// Mark a task as started (set start_time to now).
    pub fn start_task(&mut self, task_id: TaskId) {
        let now = (self.get_time)();
        let mut changed = false;
        if let Some(task) = self.tasks.iter_mut().find(|t| t.id == task_id) {
            if task.start_time.is_none() {
                task.start_time = Some(now);
                changed = true;
            }
        }
        if changed {
            self.mark_dirty();
        }
    }

    /// Mark a task as stopped (set stop_time to now).
    pub fn stop_task(&mut self, task_id: TaskId) {
        let now = (self.get_time)();
        let mut changed = false;
        if let Some(task) = self.tasks.iter_mut().find(|t| t.id == task_id) {
            task.stop_time = Some(now);
            changed = true;
        }
        if changed {
            self.mark_dirty();
        }
    }

    /// Remove a task from tracking entirely.
    pub fn remove_task(&mut self, task_id: TaskId) {
        self.tasks.retain(|t| t.id != task_id);
    }

    /// Get a reference to a task by ID.
    pub fn get_task(&self, task_id: TaskId) -> Option<&Task> {
        self.tasks.iter().find(|t| t.id == task_id)
    }

    /// Get a mutable reference to a task by ID.
    pub fn get_task_mut(&mut self, task_id: TaskId) -> Option<&mut Task> {
        self.tasks.iter_mut().find(|t| t.id == task_id)
    }

    /// Return a slice of all tasks.
    pub fn tasks(&self) -> &[Task] {
        &self.tasks
    }

    /// Return the number of finished tasks.
    pub fn finished_count(&self) -> usize {
        self.tasks.iter().filter(|t| t.finished()).count()
    }

    /// Return the number of visible tasks.
    pub fn visible_count(&self) -> usize {
        self.tasks.iter().filter(|t| t.visible).count()
    }

    // -- Task reset & query -------------------------------------------------

    /// Reset a task's progress to zero.
    ///
    /// Restarts timing from now. The task's total and description remain
    /// unchanged.
    pub fn reset(&mut self, task_id: TaskId) {
        let now = (self.get_time)();
        if let Some(task) = self.tasks.iter_mut().find(|t| t.id == task_id) {
            task.completed = 0.0;
            task.start_time = Some(now);
            task.stop_time = None;
            task.finished_time = None;
            task.finished_speed = None;
            task.samples.clear();
        }
    }

    /// Returns true if all visible tasks are finished.
    ///
    /// An empty task list (no visible tasks) returns `true`.
    pub fn all_tasks_finished(&self) -> bool {
        self.tasks
            .iter()
            .filter(|t| t.visible)
            .all(|t| t.finished())
    }

    // -- Console convenience ------------------------------------------------

    /// Print a renderable to the underlying console.
    pub fn print(&self, renderable: &dyn Renderable) {
        self.live.console_mut().print(renderable);
    }

    /// Log a message to the underlying console.
    pub fn log(&self, message: &str) {
        self.live.console_mut().log(message);
    }

    // -- Iterator tracking --------------------------------------------------

    /// Wrap an iterator with automatic progress tracking.
    ///
    /// Creates a task with the given description and optional total,
    /// then returns a [`ProgressTracker`] iterator that advances the
    /// task by 1.0 on each call to `next()`.
    ///
    /// # Examples
    ///
    /// ```
    /// use gilt::progress::Progress;
    ///
    /// let mut progress = Progress::new(Progress::default_columns())
    ///     .with_disable(true);
    /// let items: Vec<i32> = progress.track(0..5, "Counting", Some(5.0)).collect();
    /// assert_eq!(items, vec![0, 1, 2, 3, 4]);
    /// ```
    pub fn track<I>(
        &mut self,
        iter: I,
        description: &str,
        total: Option<f64>,
    ) -> ProgressTracker<'_, I::IntoIter>
    where
        I: IntoIterator,
    {
        let task_id = self.add_task(description, total, true);
        ProgressTracker {
            inner: iter.into_iter(),
            progress: self,
            task_id,
        }
    }

    // -- File helpers -------------------------------------------------------

    /// Open a file for reading with a progress task automatically attached.
    ///
    /// Computes the file's length from its metadata so the bar shows a
    /// known total and ETA. The returned reader, when read, advances the
    /// task; when dropped, the task is left in place (call
    /// [`remove_task`](Self::remove_task) or [`stop_task`](Self::stop_task)
    /// explicitly if you want it gone before [`stop`](Self::stop)).
    ///
    /// The returned `ProgressReader<'_, File>` borrows `self` mutably for
    /// its entire lifetime, so no other `&mut Progress` methods may be called
    /// while the reader is live — the same constraint as [`track`](Self::track).
    ///
    /// # Errors
    ///
    /// Returns [`std::io::Error`] if the file cannot be opened or its length
    /// cannot be determined.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use gilt::progress::Progress;
    ///
    /// let mut progress = Progress::new(Progress::default_columns());
    /// let mut reader = progress.open_file("file.bin", "Reading").unwrap();
    /// // Use `reader` as any `std::io::Read` impl.
    /// ```
    pub fn open_file(
        &mut self,
        path: impl AsRef<std::path::Path>,
        description: &str,
    ) -> io::Result<ProgressReader<'_, std::fs::File>> {
        let file = std::fs::File::open(path)?;
        let len = file.metadata()?.len();
        let task_id = self.add_task(description, Some(len as f64), true);
        // Sound: the callback captures `&mut *self` (a re-borrow) with the
        // explicit `'_` lifetime that ties the returned ProgressReader to
        // this `&mut self` borrow.  The borrow checker therefore prevents any
        // concurrent `&mut Progress` use while the reader is alive.
        Ok(ProgressReader::new(file, move |n| {
            self.advance(task_id, n as f64);
        }))
    }

    /// Wrap an arbitrary `Read + Seek` impl in a progress-tracking reader,
    /// auto-creating a task with the seekable stream length as total.
    ///
    /// Uses `SeekFrom::End(0)` to determine the stream length, then rewinds
    /// to the current beginning before wrapping.
    ///
    /// The returned `ProgressReader<'_, R>` borrows `self` mutably for
    /// its entire lifetime — same constraint as [`open_file`](Self::open_file).
    ///
    /// # Errors
    ///
    /// Returns [`std::io::Error`] if the seek operations fail.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::io::Cursor;
    /// use gilt::progress::Progress;
    ///
    /// let data = b"hello world";
    /// let cursor = Cursor::new(data.to_vec());
    /// let mut progress = Progress::new(Progress::default_columns())
    ///     .with_disable(true);
    /// let _reader = progress.wrap_file(cursor, "Processing").unwrap();
    /// ```
    pub fn wrap_file<R: Read + Seek>(
        &mut self,
        mut reader: R,
        description: &str,
    ) -> io::Result<ProgressReader<'_, R>> {
        let len = reader.seek(SeekFrom::End(0))?;
        reader.seek(SeekFrom::Start(0))?;
        let task_id = self.add_task(description, Some(len as f64), true);
        // Sound: same lifetime-borrow approach as `open_file`.
        Ok(ProgressReader::new(reader, move |n| {
            self.advance(task_id, n as f64);
        }))
    }

    // -- Taskbar helpers ----------------------------------------------------

    /// Compute the overall progress percentage across all visible tasks.
    ///
    /// Returns `None` if no tasks have a known total.  Otherwise returns the
    /// ratio of total completed to total work across all visible tasks,
    /// clamped to 0–100.
    fn overall_percent(&self) -> Option<u8> {
        let (mut total_completed, mut total_work) = (0.0f64, 0.0f64);
        let mut has_total = false;
        for task in &self.tasks {
            if !task.visible {
                continue;
            }
            if let Some(t) = task.total {
                total_work += t;
                total_completed += task.completed.min(t);
                has_total = true;
            }
        }
        if !has_total || total_work <= 0.0 {
            return None;
        }
        let pct = ((total_completed / total_work) * 100.0).clamp(0.0, 100.0) as u8;
        Some(pct)
    }

    /// Emit a taskbar progress update when `taskbar` is enabled.
    fn emit_taskbar_progress(&mut self, state: TaskbarState, percent: u8) {
        if !self.taskbar {
            return;
        }
        self.live.console_mut().set_taskbar_progress(state, percent);
    }

    // -- Display lifecycle --------------------------------------------------

    /// Start the live display.
    pub fn start(&mut self) {
        if self.disable {
            return;
        }
        self.live.start();
    }

    /// Stop the live display.
    ///
    /// When `with_taskbar(true)` was set, emits the Remove taskbar state
    /// before stopping the live display.
    pub fn stop(&mut self) {
        if self.disable {
            return;
        }
        // Emit taskbar Remove before the live display clears.
        self.emit_taskbar_progress(TaskbarState::Remove, 0);
        self.live.stop();
    }

    /// Refresh the live display with current task state and force an
    /// immediate paint.
    ///
    /// State-mutating helpers (`update`, `advance`, `start_task`,
    /// `stop_task`) call an internal `mark_dirty` instead of this —
    /// they rebuild the stored renderable without forcing a paint, so the
    /// auto-refresh thread paints at the configured rate (default 10 Hz).
    /// Tight `advance()` loops therefore generate at most one paint per
    /// refresh-tick interval rather than one per call.
    ///
    /// When `with_taskbar(true)` is set, also emits a Normal taskbar
    /// progress update with the overall completion percentage.
    pub fn refresh(&mut self) {
        if self.disable {
            return;
        }
        let table_text = self.render_tasks_text_limited();
        self.live.update_renderable(table_text, true);
        // Emit taskbar progress update if enabled.
        if self.taskbar {
            let pct = self.overall_percent().unwrap_or(0);
            self.emit_taskbar_progress(TaskbarState::Normal, pct);
        }
    }

    /// Re-render the task table and store it on the live display, but do
    /// **not** trigger an immediate paint. The auto-refresh thread will
    /// pick up the updated renderable on its next tick.
    fn mark_dirty(&mut self) {
        if self.disable {
            return;
        }
        let table_text = self.render_tasks_text_limited();
        // refresh = false: just update s.renderable so the next tick paints
        // the fresh content; do not synchronously call write_segments.
        self.live.update_renderable(table_text, false);
    }

    // -- Test-only helpers -------------------------------------------------

    /// Return the depth of the console live-stack for the internal `Live`.
    ///
    /// After `start()` the depth is 1; after `stop()` it is 0.  Used by
    /// unit tests to verify that `Progress` registers on (and deregisters
    /// from) the console's live-nesting stack via its embedded `Live`.
    #[cfg(test)]
    pub(crate) fn live_stack_depth(&self) -> usize {
        self.live.console().live_depth()
    }

    // -- Rendering ----------------------------------------------------------

    /// Build a text representation of the progress table.
    ///
    /// This renders each visible task through the configured columns,
    /// producing a multi-line text output. The table has one row per
    /// visible task and one table-column per configured ProgressColumn.
    pub fn make_tasks_table(&self) -> Table {
        let headers: Vec<&str> = self.columns.iter().map(|_| "").collect();
        let mut table = Table::grid(&headers);
        table.padding = (0, 1, 0, 0);

        if self.expand {
            table.set_expand(true);
        }

        // Ensure all columns have no_wrap set.
        for col in &mut table.columns {
            col.no_wrap = true;
        }

        // Add a row for each visible task, preserving column styling.
        for task in &self.tasks {
            if !task.visible {
                continue;
            }
            let cells: Vec<Text> = self.columns.iter().map(|col| col.render(task)).collect();
            table.add_row_text(&cells);
        }

        table
    }

    /// Render the tasks table as a single Text for the live display.
    ///
    /// Preserves styled spans from each column render (bar colors, etc.).
    /// This path does not apply `max_refresh` rate-limiting; it is used by
    /// the `Renderable` impl and direct render calls.
    fn render_tasks_text(&self) -> Text {
        let visible_tasks: Vec<&Task> = self.tasks.iter().filter(|t| t.visible).collect();
        if visible_tasks.is_empty() {
            return Text::empty();
        }

        let separator = Text::new(" ", Style::null());
        let mut result = Text::empty();

        for (i, task) in visible_tasks.iter().enumerate() {
            if i > 0 {
                result.append_str("\n", None);
            }
            for (j, col) in self.columns.iter().enumerate() {
                if j > 0 {
                    result.append_text(&separator);
                }
                let rendered = col.render(task);
                result.append_text(&rendered);
            }
        }

        result
    }

    /// Render the tasks table as a single Text, honouring per-column
    /// `max_refresh` rate-limits (P2 fix — rich parity).
    ///
    /// Columns that have a `max_refresh(hz)` limit are skipped when the
    /// elapsed time since their last render is shorter than `1.0 / hz`
    /// seconds.  Skipped columns reuse their last cached [`Text`] output.
    fn render_tasks_text_limited(&mut self) -> Text {
        let visible_tasks: Vec<usize> = self
            .tasks
            .iter()
            .enumerate()
            .filter_map(|(i, t)| if t.visible { Some(i) } else { None })
            .collect();

        if visible_tasks.is_empty() {
            return Text::empty();
        }

        let now = (self.get_time)();
        let ncols = self.columns.len();

        // Ensure the per-column metadata vecs are the right length.
        while self.column_last_rendered.len() < ncols {
            self.column_last_rendered.push(0.0);
        }
        while self.column_render_cache.len() < ncols {
            self.column_render_cache.push(Vec::new());
        }

        // Determine which columns need re-rendering.
        let mut should_render: Vec<bool> = (0..ncols)
            .map(|j| match self.columns[j].max_refresh() {
                Some(hz) if hz > 0.0 => {
                    let min_interval = 1.0 / hz;
                    (now - self.column_last_rendered[j]) >= min_interval
                }
                _ => true,
            })
            .collect();

        // Render all columns that need it, into temporary storage.
        // We collect into a separate Vec to avoid borrow conflicts.
        let rendered: Vec<Option<Vec<Text>>> = (0..ncols)
            .map(|j| {
                if should_render[j] {
                    let texts: Vec<Text> = visible_tasks
                        .iter()
                        .map(|&task_idx| self.columns[j].render(&self.tasks[task_idx]))
                        .collect();
                    Some(texts)
                } else {
                    None
                }
            })
            .collect();

        // Commit fresh renders into the cache and update timestamps.
        for (j, fresh) in rendered.into_iter().enumerate() {
            if let Some(texts) = fresh {
                self.column_last_rendered[j] = now;
                self.column_render_cache[j] = texts;
            } else if self.column_render_cache[j].len() < visible_tasks.len() {
                // Cache is stale (e.g. tasks were added): force a render.
                should_render[j] = true;
                self.column_render_cache[j] = visible_tasks
                    .iter()
                    .map(|&task_idx| self.columns[j].render(&self.tasks[task_idx]))
                    .collect();
                self.column_last_rendered[j] = now;
            }
        }

        let separator = Text::new(" ", Style::null());
        let mut result = Text::empty();

        for (ti, _task_idx) in visible_tasks.iter().enumerate() {
            if ti > 0 {
                result.append_str("\n", None);
            }
            for j in 0..ncols {
                if j > 0 {
                    result.append_text(&separator);
                }
                if let Some(cached) = self.column_render_cache[j].get(ti) {
                    result.append_text(cached);
                }
            }
        }

        result
    }
}

impl Renderable for Progress {
    fn gilt_console(&self, console: &Console, _options: &ConsoleOptions) -> Vec<Segment> {
        let text = self.render_tasks_text();
        text.render_themed(console)
    }
}

// ---------------------------------------------------------------------------
// ProgressTracker
// ---------------------------------------------------------------------------

/// An iterator wrapper that advances a task within a borrowed [`Progress`]
/// on each yielded item.
///
/// Created by [`Progress::track`].
pub struct ProgressTracker<'a, I> {
    inner: I,
    progress: &'a mut Progress,
    task_id: TaskId,
}

impl<'a, I> ProgressTracker<'a, I> {
    /// Return the task ID associated with this tracker.
    pub fn task_id(&self) -> TaskId {
        self.task_id
    }
}

impl<I> Iterator for ProgressTracker<'_, I>
where
    I: Iterator,
{
    type Item = I::Item;

    fn next(&mut self) -> Option<Self::Item> {
        let item = self.inner.next()?;
        self.progress.advance(self.task_id, 1.0);
        Some(item)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

// ---------------------------------------------------------------------------
// TrackIterator
// ---------------------------------------------------------------------------

/// An iterator wrapper that updates a Progress display as items are yielded.
///
/// Created by [`track`] or by manually wrapping an iterator.
pub struct TrackIterator<I> {
    inner: I,
    progress: Progress,
    task_id: TaskId,
    started: bool,
}

impl<I> TrackIterator<I>
where
    I: Iterator,
{
    /// Create a new TrackIterator wrapping the given iterator.
    pub fn new(iter: I, description: &str, total: Option<f64>) -> Self {
        let mut progress = Progress::new(Progress::default_columns()).with_auto_refresh(false);
        let task_id = progress.add_task(description, total, true);
        TrackIterator {
            inner: iter,
            progress,
            task_id,
            started: false,
        }
    }
}

impl<I> Iterator for TrackIterator<I>
where
    I: Iterator,
{
    type Item = I::Item;

    fn next(&mut self) -> Option<Self::Item> {
        if !self.started {
            self.progress.start();
            self.started = true;
        }

        match self.inner.next() {
            Some(item) => {
                self.progress.advance(self.task_id, 1.0);
                self.progress.refresh();
                Some(item)
            }
            None => {
                self.progress.stop();
                None
            }
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

impl<I> Drop for TrackIterator<I> {
    fn drop(&mut self) {
        if self.started {
            self.progress.stop();
        }
    }
}

/// Convenience function to wrap an iterator with a progress display.
///
/// # Examples
///
/// ```no_run
/// use gilt::progress::track;
///
/// for item in track(0..100, "Processing", Some(100.0)) {
///     // work with item
/// }
/// ```
pub fn track<I>(iter: I, description: &str, total: Option<f64>) -> TrackIterator<I::IntoIter>
where
    I: IntoIterator,
{
    TrackIterator::new(iter.into_iter(), description, total)
}

// ---------------------------------------------------------------------------
// ProgressIteratorExt -- `.progress()` adapter for any iterator
// ---------------------------------------------------------------------------

/// Extension trait that adds [`.progress()`](ProgressIteratorExt::progress)
/// to any iterator, wrapping it with a live progress bar.
///
/// The progress bar total is inferred from
/// [`size_hint()`](Iterator::size_hint) when an upper bound is available
/// (e.g. `Vec::iter()`, `Range`). For iterators without a known length the
/// bar runs in indeterminate mode.
///
/// # Examples
///
/// ```no_run
/// use gilt::progress::ProgressIteratorExt;
///
/// // Range -- total inferred from size_hint
/// for i in (0..100).progress("Counting") {
///     // work
/// }
///
/// // Vec -- total inferred from size_hint
/// let items = vec![1, 2, 3, 4, 5];
/// for item in items.iter().progress("Loading") {
///     // work
/// }
/// ```
pub trait ProgressIteratorExt: Iterator + Sized {
    /// Wrap this iterator with a progress bar.
    ///
    /// The progress bar total is inferred from `size_hint()` if an upper
    /// bound is available; otherwise the bar is indeterminate.
    fn progress(self, description: &str) -> ProgressIter<Self>;

    /// Wrap this iterator with a progress bar, explicitly setting the total.
    fn progress_with_total(self, description: &str, total: f64) -> ProgressIter<Self>;
}

impl<I: Iterator> ProgressIteratorExt for I {
    fn progress(self, description: &str) -> ProgressIter<Self> {
        let total = self.size_hint().1.map(|n| n as f64);
        ProgressIter::new(self, description, total)
    }

    fn progress_with_total(self, description: &str, total: f64) -> ProgressIter<Self> {
        ProgressIter::new(self, description, Some(total))
    }
}

/// An iterator adapter that displays a live progress bar while yielding
/// items from an inner iterator.
///
/// Created by [`ProgressIteratorExt::progress`]. Owns its own [`Progress`]
/// display; the progress bar starts on the first call to `next()` and stops
/// automatically when the iterator is exhausted or dropped.
pub struct ProgressIter<I> {
    inner: I,
    progress: Progress,
    task_id: TaskId,
    started: bool,
}

impl<I: Iterator> ProgressIter<I> {
    /// Create a new `ProgressIter` wrapping the given iterator.
    fn new(iter: I, description: &str, total: Option<f64>) -> Self {
        let mut progress = Progress::new(Progress::default_columns()).with_auto_refresh(true);
        let task_id = progress.add_task(description, total, true);
        ProgressIter {
            inner: iter,
            progress,
            task_id,
            started: false,
        }
    }

    /// Return the [`TaskId`] for the underlying progress task.
    pub fn task_id(&self) -> TaskId {
        self.task_id
    }
}

impl<I: Iterator> Iterator for ProgressIter<I> {
    type Item = I::Item;

    fn next(&mut self) -> Option<Self::Item> {
        if !self.started {
            self.progress.start();
            self.started = true;
        }

        match self.inner.next() {
            Some(item) => {
                self.progress.advance(self.task_id, 1.0);
                self.progress.refresh();
                Some(item)
            }
            None => {
                self.progress.stop();
                None
            }
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

impl<I> Drop for ProgressIter<I> {
    fn drop(&mut self) {
        if self.started {
            self.progress.stop();
        }
    }
}

// ---------------------------------------------------------------------------
// ProgressReader
// ---------------------------------------------------------------------------

/// A reader wrapper that calls a callback on each read for progress tracking.
///
/// This wraps any [`Read`] implementor and invokes a user-supplied callback
/// with the number of bytes read on each call to [`read`](Read::read). The
/// callback is typically a closure that calls [`Progress::advance`].
///
/// # Lifetime
///
/// The lifetime parameter `'p` ties this reader to the `Progress` borrow that
/// backs it (when created via [`Progress::open_file`] or
/// [`Progress::wrap_file`]).  For standalone use with a `'static` callback
/// simply omit the lifetime or use `ProgressReader<'static, R>`.
///
/// # Examples
///
/// ```
/// use std::io::Read;
/// use std::sync::atomic::{AtomicUsize, Ordering};
/// use std::sync::Arc;
/// use gilt::progress::ProgressReader;
///
/// let data = vec![0u8; 1024];
/// let bytes_seen = Arc::new(AtomicUsize::new(0));
/// let counter = bytes_seen.clone();
/// let mut reader = ProgressReader::new(
///     data.as_slice(),
///     move |n| { counter.fetch_add(n, Ordering::Relaxed); },
/// );
/// let mut buf = vec![0u8; 256];
/// reader.read(&mut buf).unwrap();
/// assert_eq!(bytes_seen.load(Ordering::Relaxed), 256);
/// ```
pub struct ProgressReader<'p, R> {
    inner: R,
    callback: Box<dyn FnMut(usize) + 'p>,
    total_read: usize,
}

impl<'p, R> ProgressReader<'p, R> {
    /// Wrap a reader with a progress callback.
    ///
    /// The `callback` is invoked after every successful read with the
    /// number of bytes that were read.
    pub fn new(inner: R, callback: impl FnMut(usize) + 'p) -> Self {
        ProgressReader {
            inner,
            callback: Box::new(callback),
            total_read: 0,
        }
    }

    /// Total bytes read so far through this wrapper.
    pub fn total_read(&self) -> usize {
        self.total_read
    }

    /// Consume the wrapper and return the inner reader.
    pub fn into_inner(self) -> R {
        self.inner
    }
}

impl<R: Read> Read for ProgressReader<'_, R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let n = self.inner.read(buf)?;
        self.total_read += n;
        (self.callback)(n);
        Ok(n)
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::console::Console;
    use std::io::{Cursor, Read};

    fn make_progress() -> Progress {
        Progress::new(Progress::default_columns()).with_disable(true)
    }

    // -- open_file tests ----------------------------------------------------

    #[test]
    fn open_file_creates_task_with_file_length() {
        let content = b"hello, progress world!";
        let path = std::env::temp_dir().join("gilt_test_open_file_task.bin");
        std::fs::write(&path, content).unwrap();

        let mut progress = make_progress();
        // Drop the reader immediately after creating it; we only care about
        // the task metadata.  The borrow-based API requires the reader to be
        // dropped before `progress` is accessed again.
        {
            let _reader = progress.open_file(&path, "Reading").unwrap();
        }

        let tasks = progress.tasks();
        assert_eq!(tasks.len(), 1);
        assert_eq!(
            tasks[0].total,
            Some(content.len() as f64),
            "task total should equal file byte length"
        );

        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn open_file_advances_task_on_read() {
        let content = b"advance me please";
        let path = std::env::temp_dir().join("gilt_test_open_file_advance.bin");
        std::fs::write(&path, content).unwrap();

        let mut progress = make_progress();

        // Read all bytes through the progress reader, then drop it so we can
        // inspect `progress` again (the borrow-based API requires this).
        let total_read = {
            let mut reader = progress.open_file(&path, "Reading").unwrap();
            let mut buf = Vec::new();
            reader.read_to_end(&mut buf).unwrap();
            reader.total_read()
        };

        assert_eq!(
            total_read,
            content.len(),
            "ProgressReader.total_read should equal bytes read"
        );
        // The task's completed counter is advanced through the borrow closure.
        let task = &progress.tasks()[0];
        assert_eq!(
            task.completed,
            content.len() as f64,
            "task.completed should equal bytes read"
        );

        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn open_file_returns_error_for_missing_path() {
        let mut progress = make_progress();
        let result = progress.open_file("/nonexistent/path/gilt_test.bin", "Reading");
        assert!(result.is_err(), "should error for nonexistent path");
    }

    // -- wrap_file tests ----------------------------------------------------

    #[test]
    fn wrap_file_uses_seek_to_compute_total() {
        let content = b"seekable data here";
        let cursor = Cursor::new(content.to_vec());

        let mut progress = make_progress();
        // Drop the reader before inspecting `progress`.
        {
            let _reader = progress.wrap_file(cursor, "Processing").unwrap();
        }

        let tasks = progress.tasks();
        assert_eq!(tasks.len(), 1);
        assert_eq!(
            tasks[0].total,
            Some(content.len() as f64),
            "task total should equal cursor length determined via seek"
        );
    }

    #[test]
    fn wrap_file_advances_task_on_read() {
        let content = b"wrap and advance";
        let cursor = Cursor::new(content.to_vec());

        let mut progress = make_progress();
        let read_data: Vec<u8> = {
            let mut reader = progress.wrap_file(cursor, "Processing").unwrap();
            let mut buf = Vec::new();
            reader.read_to_end(&mut buf).unwrap();
            buf
        };

        assert_eq!(read_data.as_slice(), content as &[u8]);
        let task = &progress.tasks()[0];
        assert_eq!(
            task.completed,
            content.len() as f64,
            "task.completed should equal bytes read"
        );
    }

    // -- with_taskbar tests -------------------------------------------------

    /// `Progress::with_taskbar` builder sets the flag and the overall_percent
    /// helper returns the correct proportion when tasks have a known total.
    #[test]
    fn test_progress_overall_percent_basic() {
        let mut p = make_progress();
        let t = p.add_task("demo", Some(100.0), true);
        p.update(t, Some(50.0), None, None, None, None, None);
        let pct = p.overall_percent();
        assert_eq!(pct, Some(50), "50/100 should give 50%");
    }

    #[test]
    fn test_progress_overall_percent_no_total() {
        let mut p = make_progress();
        p.add_task("indeterminate", None, true);
        assert_eq!(
            p.overall_percent(),
            None,
            "task with no total should give None"
        );
    }

    /// `with_taskbar(true)` builder method sets the flag and the Normal state
    /// OSC sequence is produced via the underlying console when the taskbar is
    /// enabled and `refresh()` is called.
    ///
    /// We verify by wiring a recording console and inspecting raw escape bytes.
    #[test]
    fn test_progress_with_taskbar_emits_normal() {
        // Build a recording console so we can inspect what is emitted.
        let recording_console = Console::builder()
            .force_terminal(true)
            .no_color(true)
            .record(true)
            .build();

        let mut p = Progress::new(Progress::default_columns())
            .with_disable(false) // enable rendering
            .with_taskbar(true)
            .with_console(recording_console)
            .with_auto_refresh(false); // manual refresh only

        let t = p.add_task("demo", Some(100.0), true);
        p.update(t, Some(50.0), None, None, None, None, None);
        // refresh() should emit Normal state + 50%.
        p.refresh();

        let output = p.live.console_mut().export_text(false, true);
        assert!(
            output.contains("\x1b]9;4;1;"),
            "taskbar normal state should appear in output; got {:?}",
            output
        );
    }

    // -- Task 6.3: Progress live-stack registration (#27) ------------------

    /// After `progress.start()` the internal live's console must have depth 1;
    /// after `progress.stop()` it must return to 0.
    ///
    /// This is a characterization/regression guard: task 6.2 wired
    /// `Live::start`/`stop` to call `push_live`/`pop_live`, and `Progress`
    /// delegates directly to `self.live.start()`/`self.live.stop()`, so the
    /// depth invariant is satisfied for free from 6.2.  These tests lock in
    /// that contract so any future regression is caught immediately.
    #[test]
    fn progress_live_stack_depth_start_stop() {
        let console = Console::builder()
            .force_terminal(false)
            .no_color(true)
            .build();
        let mut p = Progress::new(Progress::default_columns())
            .with_console(console)
            .with_auto_refresh(false)
            .with_disable(false);

        assert_eq!(p.live_stack_depth(), 0, "depth before start must be 0");

        p.start();
        assert_eq!(
            p.live_stack_depth(),
            1,
            "depth after start must be 1 (push_live fired via Live::start)"
        );

        p.stop();
        assert_eq!(
            p.live_stack_depth(),
            0,
            "depth after stop must be 0 (pop_live fired via Live::stop)"
        );
    }

    /// Two `Progress` instances on *separate* consoles must not interfere:
    /// both can start, advance, and stop without panic or cross-contamination
    /// of live-stack state.
    #[test]
    fn two_progress_separate_consoles_no_interference() {
        let make_p = || {
            Progress::new(Progress::default_columns())
                .with_console(
                    Console::builder()
                        .force_terminal(false)
                        .no_color(true)
                        .build(),
                )
                .with_auto_refresh(false)
                .with_disable(false)
        };

        let mut p1 = make_p();
        let mut p2 = make_p();

        p1.start();
        p2.start();

        let t1 = p1.add_task("task1", Some(10.0), true);
        let t2 = p2.add_task("task2", Some(10.0), true);

        p1.advance(t1, 5.0);
        p2.advance(t2, 3.0);

        // Each console's live-stack must be depth 1 independently.
        assert_eq!(
            p1.live_stack_depth(),
            1,
            "p1 depth should be 1 while running"
        );
        assert_eq!(
            p2.live_stack_depth(),
            1,
            "p2 depth should be 1 while running"
        );

        p1.stop();
        assert_eq!(p1.live_stack_depth(), 0, "p1 depth should be 0 after stop");
        assert_eq!(
            p2.live_stack_depth(),
            1,
            "p2 depth should still be 1 (separate console)"
        );

        p2.stop();
        assert_eq!(p2.live_stack_depth(), 0, "p2 depth should be 0 after stop");
    }

    // -- Item 4: max_refresh rate-limiting -------------------------------------

    /// A column with `max_refresh(Some(1.0))` should return the same cached
    /// Text on subsequent renders within 1-second intervals.
    #[test]
    fn max_refresh_column_is_rate_limited() {
        use std::sync::{Arc, Mutex};

        // A column that counts how many times render() is called.
        struct CountingColumn {
            count: Arc<Mutex<u32>>,
        }
        impl ProgressColumn for CountingColumn {
            fn render(&self, _task: &Task) -> Text {
                let mut c = self.count.lock().unwrap();
                *c += 1;
                Text::new(&format!("render#{c}"), Style::null())
            }
            // Limit to 1 Hz — only re-render after ≥ 1 s has elapsed.
            fn max_refresh(&self) -> Option<f64> {
                Some(1.0)
            }
        }

        let count = Arc::new(Mutex::new(0u32));
        let clock = Arc::new(Mutex::new(0.0_f64));
        let clock_c = clock.clone();

        let col = CountingColumn {
            count: count.clone(),
        };
        // Must NOT disable — mark_dirty is a no-op when disabled,
        // so render_tasks_text_limited would never be called.
        let mut p = Progress::new(vec![Box::new(col)])
            .with_disable(false)
            .with_auto_refresh(false)
            .with_get_time(move || *clock_c.lock().unwrap());

        let id = p.add_task("t", Some(10.0), true);

        // First render at t=0 → must render (cache cold).
        p.advance(id, 1.0); // triggers mark_dirty → render_tasks_text_limited
        let c1 = *count.lock().unwrap();
        assert!(c1 >= 1, "first render must happen");

        // Second call within the 1-Hz interval (t=0.1 → elapsed=0.1 < 1.0).
        *clock.lock().unwrap() = 0.1;
        p.advance(id, 1.0);
        let c2 = *count.lock().unwrap();
        assert_eq!(
            c2, c1,
            "second render within interval must be skipped; count was {c2}"
        );

        // After interval expires (t=2.0 → elapsed ≥ 1.0) a fresh render must happen.
        *clock.lock().unwrap() = 2.0;
        p.advance(id, 1.0);
        let c3 = *count.lock().unwrap();
        assert!(
            c3 > c2,
            "render must happen after interval expires; count was {c3}"
        );
    }

    // -- Item 5: DownloadColumn shared units -----------------------------------

    /// Both sides of the slash must share the same unit magnitude.
    #[test]
    fn download_column_shared_unit() {
        // completed=512 kB, total=1 MB → reference = 1 MB (SI) → both in MB.
        let mut task = Task::new(0, "t", Some(1_000_000.0));
        task.completed = 512_000.0;

        let col = DownloadColumn::new();
        let rendered = col.render(&task).plain().to_string();
        // Both sides must be in MB (no "kB/MB" inconsistency).
        let lower = rendered.to_lowercase();
        assert!(
            !lower.contains("kb"),
            "completed side must not use kB when total is 1 MB; got: {rendered}"
        );
        assert!(
            lower.contains("mb"),
            "both sides should be in MB; got: {rendered}"
        );
    }

    // -- Item 1: add_task start=false ------------------------------------------

    /// `add_task` with `start=false` must NOT set `start_time`.
    #[test]
    fn add_task_start_false_leaves_start_time_unset() {
        let mut p = make_progress();
        let id = p.add_task("deferred", Some(10.0), false);
        let task = p.get_task(id).unwrap();
        assert!(
            task.start_time.is_none(),
            "start_time should be None when start=false"
        );
    }

    /// `add_task` with `start=true` must set `start_time`.
    #[test]
    fn add_task_start_true_sets_start_time() {
        let mut p = make_progress();
        let id = p.add_task("eager", Some(10.0), true);
        let task = p.get_task(id).unwrap();
        assert!(
            task.start_time.is_some(),
            "start_time should be Some when start=true"
        );
    }

    // -- Item 2: update fields merge -------------------------------------------

    /// `update` with `fields=Some(...)` merges new keys into `task.fields`.
    #[test]
    fn update_fields_merges_into_task_fields() {
        let mut p = make_progress();
        let id = p.add_task("fielded", Some(10.0), true);

        let mut f1 = HashMap::new();
        f1.insert("key1".to_string(), "v1".to_string());
        f1.insert("key2".to_string(), "v2".to_string());
        p.update(id, None, None, None, None, None, Some(f1));

        let task = p.get_task(id).unwrap();
        assert_eq!(task.fields.get("key1").map(|s| s.as_str()), Some("v1"));
        assert_eq!(task.fields.get("key2").map(|s| s.as_str()), Some("v2"));

        // Merge again — existing keys overwritten, others preserved.
        let mut f2 = HashMap::new();
        f2.insert("key2".to_string(), "updated".to_string());
        f2.insert("key3".to_string(), "v3".to_string());
        p.update(id, None, None, None, None, None, Some(f2));

        let task = p.get_task(id).unwrap();
        assert_eq!(
            task.fields.get("key1").map(|s| s.as_str()),
            Some("v1"),
            "key1 preserved"
        );
        assert_eq!(
            task.fields.get("key2").map(|s| s.as_str()),
            Some("updated"),
            "key2 overwritten"
        );
        assert_eq!(
            task.fields.get("key3").map(|s| s.as_str()),
            Some("v3"),
            "key3 added"
        );
    }

    /// When `disable = true`, `start` and `stop` are no-ops so the live-stack
    /// depth remains 0 throughout.
    #[test]
    fn progress_disabled_depth_stays_zero() {
        let console = Console::builder()
            .force_terminal(false)
            .no_color(true)
            .build();
        let mut p = Progress::new(Progress::default_columns())
            .with_console(console)
            .with_auto_refresh(false)
            .with_disable(true);

        p.start();
        assert_eq!(p.live_stack_depth(), 0, "disabled: start must not push");

        p.stop();
        assert_eq!(p.live_stack_depth(), 0, "disabled: stop must not pop");
    }
}