-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprogressbar.tcl
More file actions
executable file
·2155 lines (1817 loc) · 79 KB
/
Copy pathprogressbar.tcl
File metadata and controls
executable file
·2155 lines (1817 loc) · 79 KB
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
# Copyright (c) 2025 Nicolas ROBERT.
# Distributed under MIT license. Please see LICENSE for details.
namespace eval zesty {}
oo::class create zesty::Bar {
# Progress bar class with multiple column types, animations,
# and customizable display options. Supports determinate and
# indeterminate progress modes with various spinner styles.
variable _tasks
variable _task_index
variable _all_tasks_completed
variable _term_width
variable _term_height
variable _options
variable _header_configs
variable _column_configs
variable _count_timer_id
variable _time_timer_id
variable _spinner_timer_id
variable _indeterminate_timer_id
variable _custom_timer_id
variable _has_spinner_column
variable _handle
variable _cache_valid
variable _column_widths_cache
variable _isWindows
constructor {args} {
# Initialize progress bar with configurable options.
#
# args - configuration options in key-value pairs:
# -minColumnWidth - minimum column width
# -minBarWidth - minimum progress bar width
# -ellipsisThreshold - threshold for ellipsis display
# -barChar - character for progress bar fill
# -bgBarChar - character for progress bar background
# -leftBarDelimiter - left delimiter for progress bar
# -rightBarDelimiter - right delimiter for progress bar
# -indeterminateBarStyle - animation style for indeterminate mode
# -spinnerFrequency - spinner update frequency in ms
# -indeterminateSpeed - animation speed
# -setColumns - custom column configuration
# -colorBarChar - color for progress bar fill
# -colorBgBarChar - color for progress bar background
# -headers - custom header configuration
# -lineHSeparator - custom header separator configuration
# Initialize variables
set _tasks {}
set _all_tasks_completed 0
set _task_index 0
set _count_timer_id ""
set _time_timer_id ""
set _spinner_timer_id ""
set _indeterminate_timer_id ""
set _custom_timer_id ""
set _handle "null"
set _cache_valid 0
set _column_widths_cache {}
set _header_configs {}
set _column_configs {}
set _isWindows 0
# Default options
zesty::def _options "-headers" -validvalue formatVKVP -type struct -with {
show -validvalue formatVBool -type any -default "false"
set -validvalue formatHSets -type any|none -default ""
}
zesty::def _options "-lineHSeparator" -validvalue formatVKVP -type struct -with {
show -validvalue formatVBool -type any -default "false"
style -validvalue formatStyle -type any|none -default ""
char -validvalue formatLChar -type any -default "─"
}
zesty::def _options "-minColumnWidth" -validvalue formatMCWidth -type num -default 5
zesty::def _options "-minBarWidth" -validvalue formatMBWidth -type num -default 10
zesty::def _options "-ellipsisThreshold" -validvalue {} -type num -default 4
zesty::def _options "-barChar" -validvalue {} -type str -default "━"
zesty::def _options "-bgBarChar" -validvalue {} -type str -default "━"
zesty::def _options "-leftBarDelimiter" -validvalue {} -type str|none -default ""
zesty::def _options "-rightBarDelimiter" -validvalue {} -type str|none -default ""
zesty::def _options "-indeterminateBarStyle" -validvalue formatIBStyle -type str -default "bounce"
zesty::def _options "-spinnerFrequency" -validvalue formatSFreq -type num -default 100
zesty::def _options "-indeterminateSpeed" -validvalue formatIBSpeed -type num -default -2
zesty::def _options "-colorBarChar" -validvalue {} -type str|num|none -default "red"
zesty::def _options "-colorBgBarChar" -validvalue {} -type str|num|none -default "Gray80"
zesty::def _options "-setColumns" -validvalue {} -type any|none -default ""
# Merge options and args
set _options [zesty::merge $_options $args]
# Default column configuration
foreach {index type} {0 zName 1 zCount 2 zBar 3 zPercent 4 zElapsed 5 zRemaining} {
my InitStandardColumn $index $type
}
# If setColumns option is defined, configure columns
if {[dict get $_options setColumns] ne ""} {
my ProcessSetColumns [dict get $_options setColumns]
}
# If setHeaders option is defined, configure headers
if {
[dict get $_options headers show] &&
[dict get $_options headers set] ne ""
} {
my SetHeaders [dict get $_options headers set]
}
# Initialize terminal width + _handle (if Windows)
my Init
set _has_spinner_column [my HasSpinnerColumn]
}
destructor {
# Cleanup progress bar system.
#
# Returns nothing
classvar BARINSTANCE
classvar ALLTASKS
classvar TASK_POSITION
classvar BARDISPLAY
classvar MANAGING_INITIALIZED
classvar INITIAL_CURSOR_POSITION
classvar DISPLAYS_INITIALIZED
if {[info exists BARINSTANCE] && ($BARINSTANCE > 0)} {
incr BARINSTANCE -1
}
if {[info exists ALLTASKS] && ($ALLTASKS > 0)} {
foreach taskId [dict keys $_tasks] {
incr ALLTASKS -1
if {!$ALLTASKS} {break}
}
}
if {[info exists TASK_POSITION]} {
foreach taskId [dict keys $_tasks] {
set TASK_POSITION [dict remove $TASK_POSITION $taskId]
}
}
if {[info exists BARDISPLAY] && ($BARDISPLAY > 0)} {
incr BARDISPLAY -1
}
if {[info exists MANAGING_INITIALIZED] && ($MANAGING_INITIALIZED > 0)} {
set MANAGING_INITIALIZED 0
}
if {[info exists DISPLAYS_INITIALIZED] && $DISPLAYS_INITIALIZED} {
set DISPLAYS_INITIALIZED 0
}
}
method getONSClass {} {
# Returns the name of the internal namespace of the object.
return [info object namespace [self class]]
}
method ConfigureHeader {column_num data} {
# Configures header data for a specific column.
# Throws error if column doesn't exist.
#
# column_num - column number to configure
# data - header configuration dictionary
#
# Returns: nothing.
if {![dict exists $_column_configs $column_num]} {
error "zesty(error): Column: '$column_num' does not exist."
}
dict set _header_configs $column_num $data
return {}
}
method SetHeaders {config} {
# Sets header configuration for multiple columns.
# Throws error if headers not enabled or invalid format.
#
# config - dictionary of column headers in key-value pairs
#
# Returns: nothing.
if {![dict get $_options headers show]} {
error "zesty(error): Headers are not enabled"
}
foreach {key value} $config {
my ConfigureHeader $key $value
}
return {}
}
method GetHeaderText {column_num} {
# Header text configuration for a column.
#
# column_num - column number to get header for
#
# Returns header configuration dict with name, align, and style.
# Uses default headers based on column type if not configured.
if {[dict exists $_header_configs $column_num]} {
return [dict get $_header_configs $column_num]
}
# Default headers according to type
set type [dict get $_column_configs $column_num type]
switch -exact -- $type {
"zName" {return {name "Task" align left style ""}}
"zCount" {return {name "Count" align center style ""}}
"zBar" {return {name "Progress" align center style ""}}
"zPercent" {return {name "%" align center style ""}}
"zElapsed" {return {name "Elapsed" align left style ""}}
"zRemaining" {return {name "ETA" align center style ""}}
"zSpinner" -
"zSeparator" {return {name "" align center style ""}}
default {return [list name [string totitle $type] align left style ""]}
}
}
method DisplayHeader {} {
# Displays the header row with column titles.
# Calculates column widths and formats header text according
# to column configuration. Optionally displays separator line.
#
# Returns nothing
set column_widths [my CalculateColumnWidths]
# Create header line
set header_line ""
foreach {key value} $_column_configs {
set config [dict get $_column_configs $key]
if {[dict exists $config visible] && [dict get $config visible]} {
set width [dict get $column_widths $key]
set data [my GetHeaderText $key]
zesty::validateKeyValuePairs "data" $data
if {![dict exists $data name]} {
error "zesty(error): header configuration\
must contain 'name' key"
}
set header_text [dict get $data name]
if {![dict exists $data align]} {
set align "center"
} else {
set align [dict get $data align]
}
zesty::validValue {} $header_text "formatAlign" $align
# Special case for progress bar
if {[dict get $config type] eq "zBar"} {
set l [dict get $_options leftBarDelimiter]
set r [dict get $_options rightBarDelimiter]
incr width [string length $l$r]
}
# Special case for separators
if {[dict get $config type] eq "zSeparator"} {
set header_text ""
set align "center"
}
set frmtText [my FormatText $header_text $width $align]
if {[dict exists $data style] && ([dict get $data style] ne "")} {
set frmtText [zesty::parseStyleDictToXML $frmtText [dict get $data style]]
}
append header_line $frmtText " "
}
}
# Display header line
zesty::echo $header_line
# Optional separator line
if {[dict get $_options lineHSeparator show]} {
my DisplayHeaderLineSeparator
}
return {}
}
method DisplayHeaderLineSeparator {} {
# Displays horizontal separator line under headers.
# Creates line using configured separator character and style,
# spanning the full width of all visible columns.
#
# Returns nothing
set column_widths [my CalculateColumnWidths]
foreach {key value} $_column_configs {
set config [dict get $_column_configs $key]
if {[dict exists $config visible] && [dict get $config visible]} {
incr width [dict get $column_widths $key]
# Special case for progress bar
if {[dict get $config type] eq "zBar"} {
set l [dict get $_options leftBarDelimiter]
set r [dict get $_options rightBarDelimiter]
incr width [string length $l$r]
}
incr width 1
}
}
incr width -1
set style {}
if {[dict get $_options lineHSeparator style] ne ""} {
set style [dict get $_options lineHSeparator style]
}
set char [dict get $_options lineHSeparator char]
zesty::echo [string repeat $char $width] -style $style
return {}
}
method InitStandardColumn {index type} {
# Initializes standard column configuration based on type.
#
# index - column index number
# type - column type
#
# Returns nothing
switch -exact -- $type {
"zName" {
dict set _column_configs $index visible 1
dict set _column_configs $index width 20
dict set _column_configs $index type $type
dict set _column_configs $index align left
}
"zCount" {
dict set _column_configs $index visible 1
dict set _column_configs $index width 15
dict set _column_configs $index type $type
dict set _column_configs $index align right
}
"zBar" {
dict set _column_configs $index visible 1
dict set _column_configs $index width 30
dict set _column_configs $index type $type
dict set _column_configs $index align left
}
"zPercent" {
dict set _column_configs $index visible 1
dict set _column_configs $index width 6
dict set _column_configs $index type $type
dict set _column_configs $index align right
}
"zElapsed" {
dict set _column_configs $index visible 1
dict set _column_configs $index width 15
dict set _column_configs $index type $type
dict set _column_configs $index align left
}
"zRemaining" {
dict set _column_configs $index visible 1
dict set _column_configs $index width 15
dict set _column_configs $index type $type
dict set _column_configs $index align right
}
"zSeparator" {
dict set _column_configs $index visible 1
dict set _column_configs $index width 1
dict set _column_configs $index type $type
dict set _column_configs $index char "|"
dict set _column_configs $index align center
}
"zSpinner" {
dict set _column_configs $index visible 1
dict set _column_configs $index width 3
dict set _column_configs $index type $type
dict set _column_configs $index align center
dict set _column_configs $index spinnerStyle "dots"
}
default {
# Check if it's a command type
if {[info commands $type] ne ""} {
dict set _column_configs $index visible 1
dict set _column_configs $index width 15
dict set _column_configs $index type $type
dict set _column_configs $index align left
} else {
# Unknown type
error "zesty(error): A command must be associated\
with '$type' column type."
}
}
}
return {}
}
method RenderSpinner {task_id width} {
# Renders animated spinner for a task.
#
# task_id - task identifier
# width - column width for spinner display
#
# Returns formatted spinner text centered in column width.
set spinnerStyle "dots"
# Check if specific style is defined for this column
foreach num [dict keys $_column_configs] {
if {[dict get $_column_configs $num type] eq "zSpinner"} {
if {[dict exists $_column_configs $num spinnerStyle]} {
set spinnerStyle [dict get $_column_configs $num spinnerStyle]
}
break
}
}
# Current position in animation
set pos [dict get $_tasks $task_id anim_spin]
if {![dict exists $::zesty::spinnerstyles $spinnerStyle]} {
zesty::throwError "'$spinnerStyle' not supported."
}
set spinner_chars [dict get $::zesty::spinnerstyles $spinnerStyle]
# Select current character in animation sequence
set char_index [expr {$pos % [llength $spinner_chars]}]
set spinner_char [lindex $spinner_chars $char_index]
# Use zesty::strLength to calculate visual width
set visual_width [zesty::strLength $spinner_char]
# If character's visual width exceeds available width,
# return points.
if {$visual_width > $width} {
return [string repeat "." $width]
}
# Calculate padding taking visual width into account
set total_padding [expr {$width - $visual_width}]
set padding_left [expr {int($total_padding / 2)}]
set padding_right [expr {$total_padding - $padding_left}]
# Create display with centered character
set spinner_text ""
append spinner_text [string repeat " " $padding_left]
append spinner_text [lindex $spinner_chars $char_index]
append spinner_text [string repeat " " $padding_right]
# Using string length here because we want character length
# to ensure our string is exactly $width characters
set actual_length [zesty::strLength $spinner_text]
if {$actual_length > $width} {
# Truncate if too long
set spinner_text [string range $spinner_text 0 $width-1]
} elseif {$actual_length < $width} {
# Add spaces if too short
append spinner_text [string repeat " " [expr {$width - $actual_length}]]
}
return $spinner_text
}
method ProcessSetColumns {columns_list} {
# Processes custom column configuration list.
#
# columns_list - list of column specifications, where each element
# can be either a simple type string or a list for
# separators with custom characters
#
# Returns nothing
set _column_configs {}
# Index for columns
set num_col 0
# Go through list of columns to configure
foreach column $columns_list {
# Check if it's a list or just a type
if {[llength $column] > 1} {
# If it's a list
set first_elem [lindex $column 0]
if {$first_elem ne "zSeparator"} {
error "zesty(error): Column '$num_col' should be a type 'zSeparator'"
}
# Format {zSeparator |} - separator with specified character
set separator_char [lindex $column 1]
# Create separator column
dict set _column_configs $num_col visible 1
dict set _column_configs $num_col width 1
dict set _column_configs $num_col type "zSeparator"
dict set _column_configs $num_col char $separator_char
dict set _column_configs $num_col align center
} else {
# Simple format: just the type (zName, zCount, zBar, etc.)
set column_type $column
# Initialize standard column with specified type
my InitStandardColumn $num_col $column_type
}
incr num_col
}
# Invalidate width cache
set _cache_valid 0
return {}
}
method Init {} {
# Initializes the progress zBar system.
# Sets up terminal detection, handles, display system,
# and increments global instance counter.
#
# Returns nothing
classvar BARINSTANCE
set _isWindows [zesty::isWindows]
if {$_isWindows} {
set _handle [zesty::win32::getStdOutHandle]
}
lassign [zesty::getTerminalSize $_handle] _term_width _term_height
# Ensure display system is initialized
my InitDisplaySystem
incr BARINSTANCE
return {}
}
method configureColumn {numOrType args} {
# Configures properties of an existing column.
# Throws error if column doesn't exist or invalid options provided.
#
# numOrType - column number or type to configure
# args - configuration options in key-value pairs:
# -visible - column visibility (boolean)
# -width - column width (positive integer)
# -type - column type
# -format - custom format specification
# -align - text alignment (left, right, center)
# -spinnerStyle - spinner animation style
# -style - text styling options
#
# Returns nothing.
set num "-"
if {[string is integer -strict $numOrType]} {
set num $numOrType
} else {
# Get column number from type
foreach key [dict keys $_column_configs] {
if {[dict get $_column_configs $key type] eq $numOrType} {
set num $key ; break
}
}
}
if {![dict exists $_column_configs $num]} {
error "zesty(error): Column '$num' does not exist."
}
# Validate args
zesty::validateKeyValuePairs "args" $args
foreach {key value} $args {
switch -exact -- $key {
-visible {
zesty::validValue {} $key "formatVBool" $value
dict set _column_configs $num visible $value
}
-width {
zesty::validValue {} $key "formatMCWidth" $value
dict set _column_configs $num width $value
}
-type {dict set _column_configs $num type $value}
-format {dict set _column_configs $num format $value}
-align {
zesty::validValue {} $key "formatAlign" $value
dict set _column_configs $num align $value
}
-spinnerStyle {
if {![dict exists $::zesty::spinnerstyles $value]} {
error "zesty(error): spinnerStyle must be one of:\
[join [dict keys $::zesty::spinnerstyles] ","]"
}
dict set _column_configs $num spinnerStyle $value
}
-style {
zesty::validValue {} $key "formatStyle" $value
dict set _column_configs $num style $value
}
default {error "zesty(error): Column option '$key' not supported"}
}
}
set _has_spinner_column [my HasSpinnerColumn]
set _cache_valid 0 ;# Invalidate cache
return {}
}
method addColumn {num args} {
# Creates new column with default settings and applies
# provided configuration options.
#
# num - column number (must not already exist)
# args - configuration options (same as configureColumn)
# Must include -type option
#
# Returns nothing.
if {[dict exists $_column_configs $num]} {
error "zesty(error): Column '$num' already exists"
}
dict set _column_configs $num visible 1
dict set _column_configs $num width 20
dict set _column_configs $num align left
my configureColumn $num {*}$args
if {![dict exists $_column_configs $num type]} {
error "zesty(error): Column 'type' must be specified\
with '-type' option"
}
return {}
}
method addTask {args} {
# Adds a new progress task to the display.
#
# args - task configuration options:
# -name - task description/name
# -total - total progress value (default: 100)
# -completed - current progress value (default: 0)
# -mode - progress mode: "determinate" or "indeterminate"
# -animStyle - animation style for indeterminate mode
#
# Returns unique task identifier for future operations.
classvar ALLTASKS
classvar TASK_POSITION
# Create new task ID
incr _task_index ; incr ALLTASKS
set index [self]::$_task_index
set task_id [string cat "task" $index]
set time [clock milliseconds]
# Initialize task
dict set _tasks $task_id description $task_id
dict set _tasks $task_id total 100
dict set _tasks $task_id completed 0
dict set _tasks $task_id start_time $time
dict set _tasks $task_id last_update $time
dict set _tasks $task_id mode "determinate" ;# Default: determinate mode
dict set _tasks $task_id anim_pos 0 ;# Animation position for indeterminate mode
dict set _tasks $task_id anim_spin 0 ;# Animation position for spinner
dict set _tasks $task_id animStyle [dict get $_options indeterminateBarStyle] ;# Animation style
dict set _tasks $task_id timer_running 0 ;# New flag to indicate if timer is running
# Process constructor arguments
foreach {key value} $args {
switch -exact -- $key {
-name {dict set _tasks $task_id description $value}
-total {
zesty::validValue {} $key "formatTTask" $value
dict set _tasks $task_id total $value
}
-completed {
zesty::validValue {} $key "formatCTask" $value
dict set _tasks $task_id completed $value
}
-mode {
zesty::validValue {} $key "formatIBMode" $value
dict set _tasks $task_id mode $value
}
-animStyle {
zesty::validValue {} $key "formatIBStyle" $value
dict set _tasks $task_id animStyle $value
}
default {error "zesty(error): Task option '$key' not supported"}
}
}
dict set TASK_POSITION $task_id [list row $ALLTASKS column 0]
if {$_has_spinner_column || ([dict get $_tasks $task_id mode] eq "indeterminate")} {
# Start automatic update for spinners and indeterminate bars
after 16 [list [self] update $task_id]
}
return $task_id
}
method update {task_id args} {
# Updates task progress and triggers display refresh.
#
# task_id - task identifier to update
# args - update options:
# -total - new total value
# -completed - new completed value
# -advance - increment completed by this amount
# -mode - change progress mode
# -description - update task description
#
# Returns nothing.
if {![dict exists $_tasks $task_id]} {
zesty::throwError "Task ID '$task_id' does not exist."
}
# Save old state to detect if task just completed
set was_completed [expr {
[dict get $_tasks $task_id completed] >= [dict get $_tasks $task_id total]
}]
foreach {key value} $args {
switch -- $key {
-total {
if {[catch {zesty::validValue {} $key "formatTTask" $value} err]} {
zesty::throwError $err
}
dict set _tasks $task_id total $value
}
-completed {
if {[catch {zesty::validValue {} $key "formatCTask" $value} err]} {
zesty::throwError $err
}
dict set _tasks $task_id completed $value
dict set _tasks $task_id mode "determinate"
}
-advance {
if {![string is integer -strict $value]} {
zesty::throwError "'$key' must be an integer"
}
dict set _tasks $task_id completed [expr {
[dict get $_tasks $task_id completed] + $value
}]
}
-mode {
if {[catch {zesty::validValue {} $key "formatIBMode" $value} err]} {
zesty::throwError $err
}
dict set _tasks $task_id mode $value
}
-description {
dict set _tasks $task_id description $value
}
default {
zesty::throwError "Unknown key '$key'"
}
}
}
# Limit 'completed' to 'total'
if {[dict get $_tasks $task_id completed] > [dict get $_tasks $task_id total]} {
dict set _tasks $task_id completed [dict get $_tasks $task_id total]
}
# Update last update time
dict set _tasks $task_id last_update [clock milliseconds]
# Check if task just completed
set is_completed [expr {
[dict get $_tasks $task_id completed] >= [dict get $_tasks $task_id total]
}]
if {$is_completed && !$was_completed} {
# Task just completed, record completion time
dict set _tasks $task_id completion_time [clock milliseconds]
}
my Display
return {}
}
method HasSpinnerColumn {} {
# Checks if any spinner columns are visible.
# Used to determine if spinner update timers needed.
#
# Returns 1 if at least one spinner column exists and is visible,
# 0 otherwise.
foreach num [dict keys $_column_configs] {
if {
[dict get $_column_configs $num type] eq "zSpinner" &&
[dict exists $_column_configs $num visible] &&
[dict get $_column_configs $num visible]
} {
return 1
}
}
return 0
}
method advance {task_id {steps 1}} {
# Advances task progress by specified number of steps.
# Convenience method that calls update with -advance option.
#
# task_id - task identifier to advance
# steps - number of steps to advance (default: 1)
#
# Returns nothing.
if {![dict exists $_tasks $task_id]} {
zesty::throwError "Task ID '$task_id' does not exist."
}
my update $task_id -advance $steps
return {}
}
method percentage {task_id} {
# Calculates completion percentage for a task.
#
# task_id - task identifier
#
# Returns percentage as floating point number (0.0-100.0)
# or '0' if total is '0' or negative.
if {[dict get $_tasks $task_id total] <= 0} {
return 0
}
return [expr {
(100.0 * [dict get $_tasks $task_id completed]) /
double([dict get $_tasks $task_id total])
}]
}
method elapsedTime {task_id} {
# Calculates elapsed time for a task in seconds.
#
# task_id - task identifier
#
# Returns elapsed time as floating point seconds.
if {[dict exists $_tasks $task_id completion_time]} {
return [expr {
([dict get $_tasks $task_id completion_time] -
[dict get $_tasks $task_id start_time]) / 1000.0
}]
} else {
return [expr {
([clock milliseconds] -
[dict get $_tasks $task_id start_time]) / 1000.0
}]
}
}
method remainingTime {task_id} {
# Estimates remaining time for task completion.
#
# task_id - task identifier
#
# Returns estimated remaining time in seconds as floating point,
# or '0.0' if completed, '-1.0' if cannot estimate.
set completed [dict get $_tasks $task_id completed]
set total [dict get $_tasks $task_id total]
if {$completed >= $total} {return 0.0}
set elapsed [my elapsedTime $task_id]
if {$completed <= 0 || $elapsed <= 0} {
return -1.0
}
set rate [expr {$completed / double($elapsed)}]
return [expr {($total - $completed) / double($rate)}]
}
method formatTime {seconds} {
# Formats time duration into readable string.
#
# seconds - time duration in seconds (floating point)
#
# Returns formatted string in HH:MM:SS.mmm format.
if {$seconds < 0} {return "--:--:--.---"}
set seconds_float $seconds
set total_seconds [expr {int($seconds_float)}]
set hours [expr {$total_seconds / 3600}]
set remaining_seconds [expr {$total_seconds % 3600}]
set minutes [expr {$remaining_seconds / 60}]
set secs [expr {$remaining_seconds % 60}]
set milliseconds [expr {int(round(($seconds_float - int($seconds_float)) * 1000))}]
return [format "%d:%02d:%02d.%03d" $hours $minutes $secs $milliseconds]
}
method renderBar {task_id width percent bg_color fg_color} {
# Renders progress bar for a task.
#
# task_id - task identifier
# width - bar width in characters
# percent - completion percentage (0-100)
# bg_color - background color
# fg_color - foreground color
#
# Returns formatted progress bar string with colors applied.
set mode [dict get $_tasks $task_id mode]
if {$mode eq "determinate"} {
# Determinate mode - existing code
set completed_width [expr {int($width * $percent / 100.0)}]
set ld [dict get $_options leftBarDelimiter]
set rd [dict get $_options rightBarDelimiter]
# Create bar
set bar ""
set b [string repeat [dict get $_options barChar] $completed_width]
set bg [string repeat [dict get $_options bgBarChar] [expr {$width - $completed_width}]]
append bar [zesty::parseStyleDictToXML $b [list fg $fg_color]]
append bar [zesty::parseStyleDictToXML $bg [list fg $bg_color]]
return ${ld}${bar}${rd}
} else {
# Indeterminate mode - different animation styles
set anim_style [dict get $_tasks $task_id animStyle]
set pos [dict get $_tasks $task_id anim_pos]
set speed [dict get $_options indeterminateSpeed]
# Call method corresponding to animation style
switch -exact -- $anim_style {
"bounce" {
return [my RenderBounceAnimation $task_id $width $pos $bg_color $fg_color $speed]
}
"pulse" {
return [my RenderPulseAnimation $task_id $width $pos $bg_color $fg_color $speed]
}
"wave" {
return [my RenderWaveAnimation $task_id $width $pos $bg_color $fg_color $speed]
}
default {
zesty::throwError "Unknown animation style: $anim_style"
}
}
}
}
method RenderBounceAnimation {task_id width pos bg_color fg_color speed} {
# Renders bouncing animation for indeterminate progress bar.
#
# task_id - task identifier
# width - bar width
# pos - animation position
# bg_color - background color
# fg_color - foreground color
# speed - animation speed
#
# Returns animated bar with block bouncing left-right.
set block_size [expr {max(int($width / 4), 3)}]
# Slow down animation by dividing position
if {$speed < 0} {
set slow_pos [expr {$pos / abs($speed)}]
} else {
set slow_pos [expr {$pos * $speed}]
}
# Handle oscillating animation
set cycle_length [expr {2 * $width}]
set normalized_pos [expr {int($slow_pos) % $cycle_length}]
if {$normalized_pos < $width} {
set start_pos $normalized_pos
} else {
set start_pos [expr {2 * $width - $normalized_pos - $block_size}]
}
set start_pos [expr {max(0, min($start_pos, $width - $block_size))}]
set ld [dict get $_options leftBarDelimiter]
set rd [dict get $_options rightBarDelimiter]
set result ""