|
root / src / ui.reef
ui.reef Reef 986 lines 34.7 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
/******************************************************************************
                __               ____                __
               / /   ___  ____ _/ __/_____________ _/ /__
              / /   / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
             / /___/  __/ /_/ / __(__  ) /__/ /_/ / /  __/
            /_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/

    (C)opyright 2025-2026, Leafscale, LLC -  https://www.leafscale.com

    Project: zyginit
   Filename: ui.reef
    Authors: Chris Tusa <chris.tusa@leafscale.com>
    License: <see LICENSE file included with this source code>
Description: Unified visual rendering: palette, glyphs, sigil, rolling tape, progress bar, spinner, final cards.
     
******************************************************************************/

module ui

import core.str as str
import sys.env as env
import sys.process as process
import time.time as time
import version

export
    fn MODE_PLAIN(): int
    fn MODE_RICH_ASCII(): int
    fn MODE_RICH_16(): int
    fn MODE_RICH_TRUE(): int
    proc ui_init(rich_mode: int)
    fn ui_mode(): int
    fn ui_runlevel(): string
    fn ui_demo(scenario: string): int
    fn detect_rich_mode(): int
    fn detect_rich_mode_for_main(): int
    fn paint(token: string, text: string): string
    fn glyph_ok(): string
    fn glyph_fail(): string
    fn glyph_pending(): string
    fn glyph_starting(): string
    fn sigil(): string
    proc ui_boot_start(num_svc: int, num_tiers: int, runlevel: string)
    proc ui_tier_start(tier: int)
    proc ui_tier_done(tier: int)
    proc ui_event_started(name: string, dur_ms: int)
    proc ui_event_failed(name: string, exit_code: int, dur_ms: int)
    proc ui_event_starting(name: string)
    proc ui_event_stopping(name: string)
    proc ui_tick()
    fn ui_spinner_frame(reverse: bool): string
    fn fmt_progress_bar(done: int, total: int): string
    type BootStats
    proc ui_boot_complete(stats: BootStats)
    proc ui_shutdown_start(reason: string)
    proc ui_event_stopped(name: string, dur_ms: int)
    proc ui_shutdown_complete(reason: string, elapsed_ms: int)
    fn pad_right(s: string, n: int): string
    fn make_divider(): string
    proc ui_set_mode(m: int)
    fn zyginit_monotonic_ms(): int
end export

type BootStats = struct
    elapsed_ms: int
    online: int
    failed: int
    slowest: [string]
    slowest_count: int
end BootStats

// Render modes. Decided once at startup by ui_init().
fn MODE_PLAIN(): int        return 0   end MODE_PLAIN
fn MODE_RICH_ASCII(): int   return 1   end MODE_RICH_ASCII
fn MODE_RICH_16(): int      return 2   end MODE_RICH_16
fn MODE_RICH_TRUE(): int    return 3   end MODE_RICH_TRUE

mut g_mode: int = 0
mut g_failed: bool = false   // set if write() to /dev/console errors

// Declared here (before TAPE_HEIGHT) so the C prototype is emitted before
// its first use; also appears grouped with the other tape externs below.
extern "C" fn zyginit_tape_slots(): int
fn TAPE_HEIGHT(): int return zyginit_tape_slots() end TAPE_HEIGHT

mut g_phase: string = ""
mut g_runlevel: string = ""
mut g_num_svc: int = 0
mut g_num_tiers: int = 0
mut g_cur_tier: int = 0
mut g_done: int = 0
mut g_failed_count: int = 0
mut g_failed_first: string = ""
mut g_failed_first_exit: int = 0
mut g_boot_start_ms: int = 0
mut g_shutdown_reason: string = ""

// Spinner state
mut g_tick: int = 0
mut g_starting_name: string = ""
mut g_stopping_name: string = ""

// Tape state counters. The backing arrays live in helpers.c (C static buffers)
// to avoid Reef's module-level new[] limitation (Reef emits GCC statement-expr
// initializers which are invalid as C static initializers).
mut g_tape_head: int = 0
mut g_tape_count: int = 0

extern "C" fn zyginit_isatty(fd: int): int
extern "C" fn zyginit_esc_str(): string
extern "C" fn zyginit_monotonic_ms(): int
extern "C" fn zyginit_tape_slots(): int
extern "C" proc zyginit_tape_clear()
extern "C" proc zyginit_tape_set(slot: int, elapsed: int, glyph: string, name: string, note: string)
extern "C" fn zyginit_tape_get_elapsed(slot: int): int
extern "C" fn zyginit_tape_get_glyph(slot: int): string
extern "C" fn zyginit_tape_get_name(slot: int): string
extern "C" fn zyginit_tape_get_note(slot: int): string

fn N_FRAMES(): int return 4 end N_FRAMES

// Return the current spinner frame character.
// Forward (starting): cycles / - \ |  with increasing g_tick
// Reverse (stopping): cycles | \ - /  with increasing g_tick (unwinds)
fn ui_spinner_frame(reverse: bool): string
    let i = g_tick % N_FRAMES()
    if reverse
        let r = (N_FRAMES() - 1) - i
        if r == 0  return "/"  end if
        if r == 1  return "-"  end if
        if r == 2  return "\\"  end if
        return "|"
    end if
    if i == 0  return "/"  end if
    if i == 1  return "-"  end if
    if i == 2  return "\\"  end if
    return "|"
end ui_spinner_frame

// Pure terminal capability detector (no PID check, no isatty check).
// Inspects only env vars and TERM. Use this from --ui-demo and snapshot tests.
// Production callers (main.reef boot path) should use
// detect_rich_mode_for_main() — it adds the PID-1 and isatty guards.
fn detect_rich_mode(): int
    if env.has_env("ZYGINIT_NO_UI")     return MODE_PLAIN()      end if
    if env.has_env("NO_COLOR")          return MODE_PLAIN()      end if
    let term = env.get_env_or("TERM", "")
    if term == "dumb"                   return MODE_PLAIN()      end if
    if env.has_env("ZYGINIT_ASCII")     return MODE_RICH_ASCII() end if
    if term == "sun"                    return MODE_RICH_16()    end if
    if term == "vt100"                  return MODE_RICH_16()    end if
    if term == "vt220"                  return MODE_RICH_16()    end if
    if term == "sun-color"              return MODE_RICH_TRUE()  end if
    if str.index_of(term, "256color") >= 0
        return MODE_RICH_TRUE()
    end if
    // Hammerhead UEFI framebuffer: kernel doesn't set TERM but tem
    // supports full ANSI/CSI/truecolor. Default to truecolor when
    // we have no TERM hint.
    if str.length(term) == 0            return MODE_RICH_TRUE()  end if
    // Anything else: safe 16-color baseline.
    return MODE_RICH_16()
end detect_rich_mode

// PID-1-aware, tty-aware wrapper around detect_rich_mode.
// Adds: non-PID-1 instances always emit plain; non-tty stdout always emits plain.
// Call this from main.reef boot path; call detect_rich_mode() for tests/demo.
fn detect_rich_mode_for_main(): int
    // Hard overrides
    if env.has_env("ZYGINIT_NO_UI")  return MODE_PLAIN()  end if
    if env.has_env("NO_COLOR")       return MODE_PLAIN()  end if
    // Production gates
    if process.getpid() != 1         return MODE_PLAIN()  end if
    if zyginit_isatty(1) == 0        return MODE_PLAIN()  end if
    // TERM-driven mode
    let term = env.get_env_or("TERM", "")
    if term == "dumb"                return MODE_PLAIN()      end if
    if env.has_env("ZYGINIT_ASCII")  return MODE_RICH_ASCII() end if
    if term == "sun"                 return MODE_RICH_16()    end if
    if term == "vt100"               return MODE_RICH_16()    end if
    if term == "vt220"               return MODE_RICH_16()    end if
    if term == "sun-color"           return MODE_RICH_TRUE()  end if
    if str.index_of(term, "256color") >= 0
        return MODE_RICH_TRUE()
    end if
    // Hammerhead UEFI framebuffer: kernel doesn't set TERM but tem
    // supports full ANSI/CSI/truecolor. Default to truecolor when we
    // have a tty but no TERM hint.
    if str.length(term) == 0         return MODE_RICH_TRUE()  end if
    // Anything else: safe 16-color baseline.
    return MODE_RICH_16()
end detect_rich_mode_for_main

// SGR escape sequences. ESC char via C helper (Reef lexer has no \x escapes).
// esc_reset returns the SGR reset sequence "\e[0m".
fn esc_reset(): string
    return str.concat(zyginit_esc_str(), "[0m")
end esc_reset

// 16-color foreground codes.
fn sgr_steel(): string  return str.concat(zyginit_esc_str(), "[37m")   end sgr_steel
fn sgr_teal(): string   return str.concat(zyginit_esc_str(), "[36m")   end sgr_teal
fn sgr_ok(): string     return str.concat(zyginit_esc_str(), "[32m")   end sgr_ok
fn sgr_warn(): string   return str.concat(zyginit_esc_str(), "[33m")   end sgr_warn
fn sgr_fail(): string   return str.concat(zyginit_esc_str(), "[31m")   end sgr_fail
fn sgr_mute(): string   return str.concat(zyginit_esc_str(), "[2m")    end sgr_mute

// Truecolor foreground codes.
fn sgr_steel_true(): string return str.concat(zyginit_esc_str(), "[38;2;110;123;139m")  end sgr_steel_true
fn sgr_teal_true(): string  return str.concat(zyginit_esc_str(), "[38;2;0;106;111m")    end sgr_teal_true
fn sgr_ok_true(): string    return str.concat(zyginit_esc_str(), "[38;2;46;139;87m")    end sgr_ok_true
fn sgr_warn_true(): string  return str.concat(zyginit_esc_str(), "[38;2;255;191;0m")    end sgr_warn_true
fn sgr_fail_true(): string  return str.concat(zyginit_esc_str(), "[38;2;200;32;31m")    end sgr_fail_true

// Wrap text in the given palette token, honoring g_mode.
fn paint(token: string, text: string): string
    if g_mode == MODE_PLAIN()  return text  end if
    mut on = ""
    if g_mode == MODE_RICH_TRUE()
        if token == "frame"       on = sgr_steel_true()
        elif token == "accent"    on = sgr_teal_true()
        elif token == "ok"        on = sgr_ok_true()
        elif token == "warn"      on = sgr_warn_true()
        elif token == "fail"      on = sgr_fail_true()
        elif token == "mute"      on = sgr_mute()
        end if
    else
        if token == "frame"       on = sgr_steel()
        elif token == "accent"    on = sgr_teal()
        elif token == "ok"        on = sgr_ok()
        elif token == "warn"      on = sgr_warn()
        elif token == "fail"      on = sgr_fail()
        elif token == "mute"      on = sgr_mute()
        end if
    end if
    return str.concat(str.concat(on, text), esc_reset())
end paint

// Glyphs. Selected by g_mode.
fn glyph_ok(): string
    if g_mode == MODE_RICH_ASCII() return "#"   end if
    if g_mode == MODE_PLAIN()      return "ok"  end if
    return "●"
end glyph_ok

fn glyph_fail(): string
    if g_mode == MODE_RICH_ASCII() return "X"    end if
    if g_mode == MODE_PLAIN()      return "fail" end if
    return "✕"
end glyph_fail

fn glyph_pending(): string
    if g_mode == MODE_RICH_ASCII() return "."       end if
    if g_mode == MODE_PLAIN()      return "pending" end if
    return "·"
end glyph_pending

fn glyph_starting(): string
    if g_mode == MODE_RICH_ASCII() return "o"        end if
    if g_mode == MODE_PLAIN()      return "starting" end if
    return "◉"
end glyph_starting

// Sigil: "[Z]" colored c.accent in rich modes.
fn sigil(): string
    return paint("accent", "[Z]")
end sigil

// Plain-mode line: "  <elapsed-s>  <level>  <event>     <name>  [k=v ...]"
fn fmt_plain_event(elapsed_ms: int, level: string, event: string,
                   name: string, kv: string): string
    let secs = int_to_str(elapsed_ms / 1000)
    // centiseconds: truncate the within-second remainder to 0-99 (2 digits)
    let frac = int_to_str((elapsed_ms % 1000) / 10)
    mut pad = ""
    if str.length(frac) < 2  pad = "0"  end if
    mut line = str.concat("  ", secs)
    line = str.concat(line, ".")
    line = str.concat(line, pad)
    line = str.concat(line, frac)
    line = str.concat(line, "  ")
    line = str.concat(line, level)
    line = str.concat(line, "  ")
    line = str.concat(line, event)
    line = str.concat(line, "  ")
    line = str.concat(line, name)
    if str.length(kv) > 0
        line = str.concat(line, "  ")
        line = str.concat(line, kv)
    end if
    return line
end fmt_plain_event

proc tape_push(elapsed_ms: int, glyph: string, name: string, note: string)
    let slot = g_tape_head % TAPE_HEIGHT()
    zyginit_tape_set(slot, elapsed_ms, glyph, name, note)
    g_tape_head = g_tape_head + 1
    if g_tape_count < TAPE_HEIGHT()
        g_tape_count = g_tape_count + 1
    end if
end tape_push

fn fmt_tape_row(row_elapsed_ms: int, row_glyph: string, row_name: string, row_note: string): string
    let secs = row_elapsed_ms / 1000
    let frac = (row_elapsed_ms % 1000) / 10
    mut sf = int_to_str(frac)
    if str.length(sf) < 2  sf = str.concat("0", sf)  end if
    let elapsed = str.concat(str.concat(int_to_str(secs), "."), sf)
    mut pad = ""
    let pad_n = 6 - str.length(elapsed)
    mut i = 0
    while i < pad_n
        pad = str.concat(pad, " ")
        i = i + 1
    end while
    mut row = str.concat(pad, elapsed)
    row = str.concat(row, "  ")
    row = str.concat(row, row_glyph)
    row = str.concat(row, "  ")
    row = str.concat(row, row_name)
    if str.length(row_note) > 0
        row = str.concat(row, "  ")
        row = str.concat(row, paint("mute", str.concat(str.concat("(", row_note), ")")))
    end if
    return row
end fmt_tape_row

fn make_divider(): string
    mut div = ""
    mut k = 0
    while k < 62
        div = str.concat(div, "─")
        k = k + 1
    end while
    return div
end make_divider

fn fmt_header(elapsed_ms: int): string
    let secs = elapsed_ms / 1000
    let frac = (elapsed_ms % 1000) / 100
    let elapsed = str.concat(str.concat(int_to_str(secs), "."), str.concat(int_to_str(frac), "s"))
    let phase_label = g_runlevel
    mut out = str.concat("  ", sigil())
    out = str.concat(out, str.concat(" zyginit ", str.concat(version.VERSION(), " · ")))
    out = str.concat(out, paint("frame", phase_label))
    out = str.concat(out, "   ")
    out = str.concat(out, paint("accent", str.concat("elapsed ", elapsed)))
    out = str.concat(out, "\n  ")
    out = str.concat(out, paint("frame",
        str.concat(str.concat(int_to_str(g_num_svc), " services · tier "),
        str.concat(str.concat(int_to_str(g_cur_tier), " · "),
        str.concat(str.concat(int_to_str(g_done), " done · "),
        str.concat(int_to_str(g_failed_count), " failed"))))))
    out = str.concat(out, "\n  ")
    if g_failed_count == 0
        out = str.concat(out, paint("mute", "failed: none"))
    elif g_failed_count == 1
        out = str.concat(out, paint("fail",
            str.concat(str.concat("failed: ", g_failed_first),
            str.concat("  exit=", int_to_str(g_failed_first_exit)))))
    else
        out = str.concat(out, paint("fail",
            str.concat(str.concat("failed: ", int_to_str(g_failed_count)),
            " services")))
    end if
    out = str.concat(out, "\n  ")
    out = str.concat(out, paint("accent", make_divider()))
    return out
end fmt_header

fn PROGRESS_WIDTH(): int return 36 end PROGRESS_WIDTH

fn fmt_progress_bar(done: int, total: int): string
    if g_mode == MODE_PLAIN()  return ""  end if
    let width = PROGRESS_WIDTH()
    mut filled = 0
    if total > 0
        filled = (done * width) / total
    end if
    if filled > width  filled = width  end if
    mut pct = 0
    if total > 0
        pct = (done * 100) / total
    end if
    mut bar = ""
    if g_mode == MODE_RICH_ASCII()
        let inner = width - 2
        let inner_filled = (filled * inner) / width
        bar = str.concat(bar, "[")
        mut i = 0
        while i < inner
            if i < inner_filled
                bar = str.concat(bar, "#")
            else
                bar = str.concat(bar, " ")
            end if
            i = i + 1
        end while
        bar = str.concat(bar, "]")
    else
        mut i = 0
        while i < width
            if i < filled
                bar = str.concat(bar, paint("accent", "█"))
            else
                bar = str.concat(bar, paint("mute", "░"))
            end if
            i = i + 1
        end while
    end if
    mut label = ""
    if g_phase == "shutdown"  label = " down"  end if
    return str.concat(
        str.concat("  ", bar),
        str.concat(
            str.concat(str.concat("  ", int_to_str(done)),
                       str.concat("/", int_to_str(total))),
            str.concat(label, str.concat("  ", str.concat(int_to_str(pct), "%")))))
end fmt_progress_bar

// Render a single tape row, overriding the stored glyph with the current
// spinner frame when the row belongs to the active starting/stopping service.
fn fmt_tape_row_at(slot: int): string
    let elapsed_ms = zyginit_tape_get_elapsed(slot)
    let name = zyginit_tape_get_name(slot)
    let note = zyginit_tape_get_note(slot)
    let stored_glyph = zyginit_tape_get_glyph(slot)
    mut glyph = stored_glyph
    if str.length(g_starting_name) > 0 and name == g_starting_name
        glyph = paint("warn", ui_spinner_frame(false))
    end if
    if str.length(g_stopping_name) > 0 and name == g_stopping_name
        glyph = paint("warn", ui_spinner_frame(true))
    end if
    return fmt_tape_row(elapsed_ms, glyph, name, note)
end fmt_tape_row_at

fn render_boot_screen(elapsed_ms: int): string
    if g_mode == MODE_PLAIN()
        return ""
    end if
    mut out = str.concat(fmt_header(elapsed_ms), "\n")
    let start = g_tape_head - g_tape_count
    mut i = 0
    while i < TAPE_HEIGHT()
        if i < g_tape_count
            let slot = (start + i) % TAPE_HEIGHT()
            out = str.concat(out, fmt_tape_row_at(slot))
        end if
        out = str.concat(out, "\n")
        i = i + 1
    end while
    out = str.concat(out, str.concat("  ", paint("accent", make_divider())))
    out = str.concat(out, "\n")
    out = str.concat(out, fmt_progress_bar(g_done, g_num_svc))
    out = str.concat(out, "\n")
    return out
end render_boot_screen

// Advance the tick counter and, if in rich mode with an active spinner, redraw.
proc ui_tick()
    g_tick = g_tick + 1
    if g_mode == MODE_PLAIN()  return  end if
    if str.length(g_starting_name) == 0 and str.length(g_stopping_name) == 0
        return
    end if
    let elapsed = zyginit_monotonic_ms() - g_boot_start_ms
    print(str.concat(str.concat(zyginit_esc_str(), "[2J"),
          str.concat(zyginit_esc_str(), "[H")))
    print(render_boot_screen(elapsed))
end ui_tick

// Rich-mode-only redraw. Plain mode emits its own line before calling this.
proc emit_redraw(elapsed_ms: int)
    if g_mode == MODE_PLAIN()  return  end if
    print(str.concat(str.concat(zyginit_esc_str(), "[2J"),
          str.concat(zyginit_esc_str(), "[H")))
    print(render_boot_screen(elapsed_ms))
end emit_redraw

proc ui_boot_start(num_svc: int, num_tiers: int, runlevel: string)
    g_phase = "boot"
    g_runlevel = runlevel
    g_num_svc = num_svc
    g_num_tiers = num_tiers
    g_cur_tier = 0
    g_done = 0
    g_failed_count = 0
    g_failed_first = ""
    g_failed_first_exit = 0
    g_tape_head = 0
    g_tape_count = 0
    zyginit_tape_clear()
    g_boot_start_ms = zyginit_monotonic_ms()
end ui_boot_start

proc ui_tier_start(tier: int)
    g_cur_tier = tier
end ui_tier_start

proc ui_tier_done(tier: int)
    // header repaints happen via emit_redraw on next event/tick
end ui_tier_done

// dur_ms: service's own runtime (from supervisor). Reserved for future
// use (Task 6 spinner display); the tape currently shows wall-clock
// elapsed since boot, not per-service duration.
proc ui_event_started(name: string, dur_ms: int)
    g_starting_name = ""
    g_stopping_name = ""
    let elapsed = zyginit_monotonic_ms() - g_boot_start_ms
    g_done = g_done + 1
    tape_push(elapsed, paint("ok", glyph_ok()), name, "")
    if g_mode == MODE_PLAIN()
        println(fmt_plain_event(elapsed, "info", "started", name, ""))
    else
        emit_redraw(elapsed)
    end if
end ui_event_started

// dur_ms: service's own runtime (from supervisor). Reserved for future
// use (Task 6 spinner display); the tape currently shows wall-clock
// elapsed since boot, not per-service duration.
proc ui_event_failed(name: string, exit_code: int, dur_ms: int)
    g_starting_name = ""
    g_stopping_name = ""
    let elapsed = zyginit_monotonic_ms() - g_boot_start_ms
    g_done = g_done + 1
    g_failed_count = g_failed_count + 1
    if g_failed_count == 1
        g_failed_first = name
        g_failed_first_exit = exit_code
    end if
    let exit_kv = str.concat("exit=", int_to_str(exit_code))
    tape_push(elapsed, paint("fail", glyph_fail()), name, exit_kv)
    if g_mode == MODE_PLAIN()
        println(fmt_plain_event(elapsed, "err", "failed", name, exit_kv))
    else
        emit_redraw(elapsed)
    end if
end ui_event_failed

// Called when a service is transitioning to started (spinner visible).
proc ui_event_starting(name: string)
    g_starting_name = name
    let elapsed = zyginit_monotonic_ms() - g_boot_start_ms
    tape_push(elapsed, paint("warn", ui_spinner_frame(false)), name, "starting")
    if g_mode == MODE_PLAIN()
        println(fmt_plain_event(elapsed, "info", "starting", name, ""))
    else
        emit_redraw(elapsed)
    end if
end ui_event_starting

// Called when a service is transitioning to stopped (reverse spinner visible).
proc ui_event_stopping(name: string)
    g_stopping_name = name
    let elapsed = zyginit_monotonic_ms() - g_boot_start_ms
    tape_push(elapsed, paint("warn", ui_spinner_frame(true)), name, "stopping")
    if g_mode == MODE_PLAIN()
        println(fmt_plain_event(elapsed, "info", "stopping", name, ""))
    else
        emit_redraw(elapsed)
    end if
end ui_event_stopping

proc ui_init(rich_mode: int)
    g_mode = rich_mode
    g_failed = false
end ui_init

fn ui_mode(): int
    return g_mode
end ui_mode

fn ui_runlevel(): string
    return g_runlevel
end ui_runlevel

proc ui_set_mode(m: int)
    g_mode = m
end ui_set_mode

proc ui_boot_complete(stats: BootStats)
    if g_mode == MODE_PLAIN()
        println(fmt_plain_event(stats.elapsed_ms, "info", "boot_complete",
                "summary", str.concat(str.concat("online=", int_to_str(stats.online)),
                                      str.concat(" failed=", int_to_str(stats.failed)))))
        return
    end if
    // Clear screen, paint final card.
    print(str.concat(str.concat(zyginit_esc_str(), "[2J"),
          str.concat(zyginit_esc_str(), "[H")))
    let secs = stats.elapsed_ms / 1000
    let frac = (stats.elapsed_ms % 1000) / 100
    let elapsed = str.concat(str.concat(int_to_str(secs), "."),
                             str.concat(int_to_str(frac), "s"))
    let summary_count = int_to_str(stats.online + stats.failed)
    mut out = str.concat("  ", sigil())
    out = str.concat(out, str.concat(" zyginit ", str.concat(version.VERSION(), " · ")))
    out = str.concat(out, paint("frame", g_runlevel))
    out = str.concat(out, "   ")
    out = str.concat(out, paint("accent", str.concat("boot ", elapsed)))
    out = str.concat(out, "\n")
    out = str.concat(out, "  ")
    out = str.concat(out, paint("frame",
        str.concat(str.concat(summary_count, " services — "),
        str.concat(str.concat(int_to_str(stats.online), " online, "),
        str.concat(int_to_str(stats.failed), " failed")))))
    out = str.concat(out, "\n\n")
    if stats.failed == 0
        out = str.concat(out, "  ")
        out = str.concat(out, paint("ok", "all services online"))
        out = str.concat(out, "\n")
    elif stats.failed == 1
        out = str.concat(out, "  ")
        out = str.concat(out, paint("fail",
            str.concat(str.concat("failed: ", g_failed_first),
            str.concat("  exit=", int_to_str(g_failed_first_exit)))))
        out = str.concat(out, "\n")
        out = str.concat(out, "      ")
        out = str.concat(out, paint("accent",
            str.concat("→ zygctl log ", g_failed_first)))
        out = str.concat(out, paint("mute", "    to see why"))
        out = str.concat(out, "\n")
    else
        out = str.concat(out, "  ")
        out = str.concat(out, paint("fail",
            str.concat(str.concat("failed: ", int_to_str(stats.failed)), " services")))
        out = str.concat(out, "\n")
        out = str.concat(out, "      ")
        out = str.concat(out, paint("accent", "→ zygctl status"))
        out = str.concat(out, paint("mute", "    to see them"))
        out = str.concat(out, "\n")
    end if
    out = str.concat(out, "  ")
    out = str.concat(out, paint("accent", make_divider()))
    out = str.concat(out, "\n")
    // Slowest line
    let slow_n = stats.slowest_count
    if slow_n > 0
        mut slow = "slowest:"
        mut i = 0
        mut max = slow_n
        if max > 3
            max = 3
        end if
        while i < max
            slow = str.concat(slow, "  ")
            slow = str.concat(slow, stats.slowest[i])
            i = i + 1
        end while
        out = str.concat(out, "  ")
        out = str.concat(out, paint("frame", slow))
        out = str.concat(out, "\n")
    end if
    print(out)
end ui_boot_complete

proc ui_shutdown_start(reason: string)
    g_phase = "shutdown"
    g_shutdown_reason = reason
    g_runlevel = str.concat("stopping for ", reason)
    g_done = 0
    g_failed_count = 0
    g_failed_first = ""
    g_failed_first_exit = 0
    g_tape_head = 0
    g_tape_count = 0
    g_boot_start_ms = zyginit_monotonic_ms()
end ui_shutdown_start

proc ui_event_stopped(name: string, dur_ms: int)
    g_stopping_name = ""
    g_starting_name = ""
    let elapsed = zyginit_monotonic_ms() - g_boot_start_ms
    g_done = g_done + 1
    tape_push(elapsed, paint("mute", glyph_pending()), name, "")
    if g_mode == MODE_PLAIN()
        println(fmt_plain_event(elapsed, "info", "stopped", name, ""))
    else
        emit_redraw(elapsed)
    end if
end ui_event_stopped

proc ui_shutdown_complete(reason: string, elapsed_ms: int)
    if g_mode == MODE_PLAIN()
        println(fmt_plain_event(elapsed_ms, "info", "shutdown_complete",
                reason, str.concat("down=", int_to_str(g_done))))
        return
    end if
    print(str.concat(str.concat(zyginit_esc_str(), "[2J"),
          str.concat(zyginit_esc_str(), "[H")))
    let secs = elapsed_ms / 1000
    let frac = (elapsed_ms % 1000) / 100
    let elapsed = str.concat(str.concat(int_to_str(secs), "."),
                             str.concat(int_to_str(frac), "s"))
    mut out = str.concat("  ", sigil())
    out = str.concat(out, str.concat(" zyginit ", str.concat(version.VERSION(), " · ")))
    out = str.concat(out, paint("frame", str.concat(reason, " complete")))
    out = str.concat(out, "   ")
    out = str.concat(out, paint("accent", str.concat(str.concat(reason, " "), elapsed)))
    out = str.concat(out, "\n  ")
    mut stat_str = "stopped cleanly"
    if g_failed_count > 0
        stat_str = str.concat(str.concat("stopped (", int_to_str(g_failed_count)), " force-killed)")
    end if
    out = str.concat(out, paint("frame",
        str.concat(str.concat(int_to_str(g_num_svc), " services "), stat_str)))
    out = str.concat(out, "\n  ")
    out = str.concat(out, paint("accent", make_divider()))
    out = str.concat(out, "\n  ")
    out = str.concat(out, paint("mute", "invoking uadmin(A_SHUTDOWN, AD_BOOT)"))
    out = str.concat(out, "\n")
    print(out)
end ui_shutdown_complete

// Scenario dispatcher for --ui-demo. Called from main.reef.
// Returns 0 on success, 1 if the scenario name is unknown.
fn ui_demo(scenario: string): int
    if scenario == "skeleton"
        println("ui.reef skeleton ok, mode=" + int_to_str(g_mode))
        return 0
    end if
    if scenario == "plain_boot"
        println(fmt_plain_event(40, "info", "started", "root-fs", ""))
        println(fmt_plain_event(120, "info", "started", "crypto", "dur_ms=80"))
        println(fmt_plain_event(310, "info", "started", "devfs", "dur_ms=190"))
        println(fmt_plain_event(5020, "err",  "failed",  "network", "exit=1 dur_ms=4023"))
        return 0
    end if
    if str.index_of(scenario, "detect_") == 0
        g_mode = detect_rich_mode()
        println("mode=" + int_to_str(g_mode))
        return 0
    end if
    if scenario == "palette_true" or scenario == "palette_16"
        g_mode = detect_rich_mode()
        println(paint("frame",  "frame text"))
        println(paint("accent", "accent text"))
        println(paint("ok",     "ok text"))
        println(paint("warn",   "warn text"))
        println(paint("fail",   "fail text"))
        println(paint("mute",   "mute text"))
        return 0
    end if
    if scenario == "glyphs_unicode" or scenario == "glyphs_ascii"
        g_mode = detect_rich_mode()
        println(glyph_ok() + " " + glyph_starting() + " " +
                glyph_fail() + " " + glyph_pending())
        return 0
    end if
    if scenario == "sigil_rich"
        g_mode = detect_rich_mode()
        println(sigil() + " zyginit " + version.VERSION())
        return 0
    end if
    if scenario == "boot_tape_rich" or scenario == "boot_tape_ascii" or scenario == "boot_tape_plain"
        g_mode = detect_rich_mode()
        ui_boot_start(17, 8, "multi-user")
        g_boot_start_ms = 0
        let names = new [string](9)
        names[0] = "root-fs"
        names[1] = "crypto"
        names[2] = "devfs"
        names[3] = "swap"
        names[4] = "filesystem"
        names[5] = "identity"
        names[6] = "sysconfig"
        names[7] = "dlmgmtd"
        names[8] = "network"
        let elapsed_seq = new [int](9)
        elapsed_seq[0] = 40
        elapsed_seq[1] = 160
        elapsed_seq[2] = 310
        elapsed_seq[3] = 490
        elapsed_seq[4] = 1040
        elapsed_seq[5] = 1080
        elapsed_seq[6] = 1360
        elapsed_seq[7] = 1550
        elapsed_seq[8] = 5020
        mut i = 0
        while i < 8
            g_done = g_done + 1
            tape_push(elapsed_seq[i], paint("ok", glyph_ok()), names[i], "")
            i = i + 1
        end while
        g_failed_count = 1
        g_failed_first = "network"
        g_failed_first_exit = 1
        g_cur_tier = 5
        g_done = g_done + 1
        tape_push(5020, paint("fail", glyph_fail()), "network", "exit=1")
        if g_mode == MODE_PLAIN()
            let lvls = new [string](9)
            let evs = new [string](9)
            let kvs = new [string](9)
            mut j = 0
            while j < 8
                lvls[j] = "info"
                evs[j] = "started"
                kvs[j] = ""
                j = j + 1
            end while
            lvls[8] = "err"
            evs[8] = "failed"
            kvs[8] = "exit=1"
            mut k = 0
            while k < 9
                println(fmt_plain_event(elapsed_seq[k], lvls[k], evs[k], names[k], kvs[k]))
                k = k + 1
            end while
        else
            print(render_boot_screen(5020))
        end if
        return 0
    end if
    if scenario == "progress_rich" or scenario == "progress_ascii"
        g_mode = detect_rich_mode()
        ui_boot_start(17, 8, "multi-user")
        g_done = 12
        g_failed_count = 1
        print(fmt_progress_bar(g_done, g_num_svc))
        return 0
    end if
    if scenario == "progress_full"
        g_mode = detect_rich_mode()
        ui_boot_start(17, 8, "multi-user")
        g_done = 17
        print(fmt_progress_bar(g_done, g_num_svc))
        return 0
    end if
    if scenario == "spinner_forward"
        g_mode = detect_rich_mode()
        mut i = 0
        while i < 8
            g_tick = i
            print(ui_spinner_frame(false))
            i = i + 1
        end while
        println("")
        return 0
    end if
    if scenario == "spinner_reverse"
        g_mode = detect_rich_mode()
        mut i = 0
        while i < 8
            g_tick = i
            print(ui_spinner_frame(true))
            i = i + 1
        end while
        println("")
        return 0
    end if
    if scenario == "spinner_in_tape"
        g_mode = detect_rich_mode()
        ui_boot_start(17, 8, "multi-user")
        g_boot_start_ms = 0
        tape_push(40, paint("ok", glyph_ok()), "root-fs", "")
        tape_push(160, paint("ok", glyph_ok()), "crypto", "")
        tape_push(310, paint("ok", glyph_ok()), "devfs", "")
        g_done = 3
        // Manually set up the spinner state — bypass ui_event_starting to
        // avoid a host-dependent monotonic_ms() reading in the demo.
        g_starting_name = "network"
        g_tick = 0
        tape_push(2100, paint("warn", ui_spinner_frame(false)), "network", "starting")
        // Now bump tick so the live re-render shows frame index 2.
        g_tick = 2
        print(str.concat(str.concat(zyginit_esc_str(), "[2J"),
              str.concat(zyginit_esc_str(), "[H")))
        print(render_boot_screen(2100))
        return 0
    end if
    if scenario == "final_card_ok"
        g_mode = detect_rich_mode()
        ui_boot_start(17, 8, "multi-user")
        let slow = new [string](3)
        slow[0] = "dlmgmtd 1.2s"
        slow[1] = "filesystem 0.55s"
        slow[2] = "sshd 0.37s"
        let stats = BootStats{
            elapsed_ms: 8300,
            online: 17,
            failed: 0,
            slowest: slow,
            slowest_count: 3
        }
        ui_boot_complete(stats)
        return 0
    end if
    if scenario == "final_card_failed"
        g_mode = detect_rich_mode()
        ui_boot_start(17, 8, "multi-user")
        g_failed_first = "network"
        g_failed_first_exit = 1
        let slow = new [string](3)
        slow[0] = "network 5.02s"
        slow[1] = "filesystem 0.55s"
        slow[2] = "sshd 0.37s"
        let stats = BootStats{
            elapsed_ms: 8300,
            online: 16,
            failed: 1,
            slowest: slow,
            slowest_count: 3
        }
        ui_boot_complete(stats)
        return 0
    end if
    if scenario == "shutdown_mirror"
        g_mode = detect_rich_mode()
        ui_boot_start(17, 8, "multi-user")
        ui_shutdown_start("reboot")
        g_boot_start_ms = 0
        tape_push(40,  paint("mute", glyph_pending()), "sshd", "")
        tape_push(160, paint("mute", glyph_pending()), "console-login", "")
        tape_push(310, paint("mute", glyph_pending()), "cron", "")
        g_stopping_name = "syslogd"
        g_tick = 0
        tape_push(480, paint("warn", ui_spinner_frame(true)), "syslogd", "stopping")
        g_tick = 3
        g_done = 4
        g_cur_tier = 6
        print(str.concat(str.concat(zyginit_esc_str(), "[2J"),
              str.concat(zyginit_esc_str(), "[H")))
        print(render_boot_screen(480))
        return 0
    end if
    if scenario == "shutdown_final"
        g_mode = detect_rich_mode()
        ui_boot_start(17, 8, "multi-user")
        ui_shutdown_start("reboot")
        g_num_svc = 17
        g_done = 17
        ui_shutdown_complete("reboot", 2100)
        return 0
    end if
    println("ui.reef: unknown demo scenario: " + scenario)
    return 1
end ui_demo

fn int_to_str(n: int): string
    if n == 0
        return "0"
    end if

    mut value = n
    if n < 0
        value = 0 - n
    end if

    mut result = ""
    while value > 0
        let digit = value % 10
        result = str.concat(str.substring("0123456789", digit, 1), result)
        value = value / 10
    end while

    if n < 0
        result = str.concat("-", result)
    end if

    return result
end int_to_str

// ============================================================================
// Status/list rendering (used by socket command handlers)
// ============================================================================

fn pad_right(s: string, n: int): string
    let extra = n - str.length(s)
    if extra <= 0
        return s
    end if
    mut out = s
    mut i = 0
    while i < extra
        out = str.concat(out, " ")
        i = i + 1
    end while
    return out
end pad_right

end module