Ui builder

  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
use "collections"

type WidgetFactory is {(WidgetParent tag): Widget tag} val

class ref UIBuilder
  let _compositor: Compositor tag
  let _input_actor: InputActor tag
  let _registry: Map[String, WidgetFactory]
  let _widgets_by_id: Map[String, Widget tag]

  new create(compositor: Compositor tag, input_actor: InputActor tag) =>
    _compositor = compositor
    _input_actor = input_actor
    _registry = Map[String, WidgetFactory]
    _widgets_by_id = Map[String, Widget tag]
    _register_defaults()

  fun ref _register_defaults() =>
    _registry("vbox") = {(p: WidgetParent tag): Widget tag => VBox(p)} val
    _registry("hbox") = {(p: WidgetParent tag): Widget tag => HBox(p)} val
    _registry("frame") = {(p: WidgetParent tag): Widget tag => Frame(p)} val
    _registry("label") = {(p: WidgetParent tag): Widget tag => Label(p)} val
    _registry("textbox") = {(p: WidgetParent tag): Widget tag => TextBox(p)} val
    _registry("hline") = {(p: WidgetParent tag): Widget tag => HLine(p)} val
    _registry("vline") = {(p: WidgetParent tag): Widget tag => VLine(p)} val
    _registry("canvas") = {(p: WidgetParent tag): Widget tag => Canvas(p)} val
    _registry("stack") = {(p: WidgetParent tag): Widget tag => Stack(p)} val
    _registry("tabbar") = {(p: WidgetParent tag): Widget tag =>
      TabBar(p, {(s: String val) => None} val)
    } val

  fun ref register(type_name: String, factory: WidgetFactory) =>
    _registry(type_name) = factory

  fun get_widget(id: String): (Widget tag | None) =>
    try _widgets_by_id(id)? else None end

  fun ref build(dsl: String): (Widget tag | BuilderError) =>
    let stripped = _strip_block_comments(dsl)
    let lines: Array[String] val = stripped.split_by("\n")

    // Parse all lines
    let parsed: Array[(USize, ParsedLine)] = Array[(USize, ParsedLine)]
    var line_num: USize = 1
    for line in lines.values() do
      let cleaned = UIParser.strip_comments(line)
      match UIParser.tokenize_line(cleaned, line_num)
      | let pl: ParsedLine =>
        if pl.tokens.size() > 0 then
          parsed.push((line_num, pl))
        end
      | let err: BuilderError =>
        return err
      end
      line_num = line_num + 1
    end

    if parsed.size() == 0 then
      return BuilderError(0, "empty DSL: no widgets defined")
    end

    // Stack: (indent, widget, type_name)
    let stack: Array[(USize, Widget tag, String)] = Array[(USize, Widget tag, String)]

    // Pending pack context: (indent, is_pack_start, width, height, PackOption)
    var pending_pack: ((USize, Bool, USize, USize, PackOption) | None) = None

    // Pending add context: (indent, child_name, optional tab label)
    var pending_add: ((USize, String val, (String val | None)) | None) = None

    var root: (Widget tag | None) = None

    // Track stacks needing tab wrapping: (stack_widget, position, tab_entries)
    let stacks_needing_tabs:
      Array[(Stack tag, String val, Array[(String val, String val)])]
      = Array[(Stack tag, String val, Array[(String val, String val)])]

    for entry in parsed.values() do
      (let ln, let pl) = entry
      let indent = pl.indent
      let tokens = pl.tokens
      // Pop stack entries with indent >= current indent
      while stack.size() > 0 do
        try
          (let si, _, _) = stack(stack.size() - 1)?
          if si >= indent then
            stack.pop()?
          else
            break
          end
        else
          break
        end
      end

      // Look at first token
      let first_token = try tokens(0)? else continue end

      match first_token.kind
      | TokPackStart | TokPackEnd =>
        let is_start = match first_token.kind
        | TokPackStart => true
        else false
        end

        // Extract size and mode from remaining tokens
        var pack_w: USize = 0
        var pack_h: USize = 0
        var pack_mode: PackMode = PackFixed

        for ti in Range(1, tokens.size()) do
          try
            let tok = tokens(ti)?
            match tok.kind
            | TokSize =>
              match UIParser.parse_size(tok.value, ln)
              | (let pw: USize, let ph: USize) =>
                pack_w = pw
                pack_h = ph
              | let err: BuilderError =>
                return err
              end
            | TokMode =>
              match ModeLookup(tok.value)
              | let m: PackMode => pack_mode = m
              | None =>
                return BuilderError(ln, "unknown pack mode: " + tok.value)
              end
            end
          end
        end

        let pack_opt = PackOption(pack_mode)
        pending_pack = (indent, is_start, pack_w, pack_h, pack_opt)

      | TokAdd =>
        // Extract child name from remaining tokens
        var add_name: (String val | None) = None
        var add_tab: (String val | None) = None

        for ti in Range(1, tokens.size()) do
          try
            let tok = tokens(ti)?
            match tok.kind
            | TokQuotedString =>
              add_name = tok.value
            | TokKeyValue =>
              if tok.key == "tab" then
                add_tab = tok.value
              end
            end
          end
        end

        match add_name
        | let name: String val =>
          pending_add = (indent, name, add_tab)
        | None =>
          return BuilderError(ln, "add directive requires a quoted name")
        end

      | TokWord =>
        let type_name = first_token.value

        // Determine parent
        let parent: WidgetParent tag = if stack.size() > 0 then
          try
            (_, let pw, _) = stack(stack.size() - 1)?
            match pw
            | let wp: WidgetParent tag => wp
            else
              _compositor
            end
          else
            _compositor
          end
        else
          _compositor
        end

        // Look up factory
        let factory = try
          _registry(type_name)?
        else
          return BuilderError(ln, "unknown widget type: " + type_name)
        end

        // Create widget
        let widget: Widget tag = factory(parent)

        // Process remaining tokens
        var primary_text: (String | None) = None
        var widget_id: (String | None) = None
        var focusable: Bool = false

        for ti in Range(1, tokens.size()) do
          try
            let tok = tokens(ti)?
            match tok.kind
            | TokId =>
              widget_id = tok.value
            | TokQuotedString =>
              primary_text = tok.value
            | TokKeyValue =>
              match _apply_property(widget, type_name, tok.key, tok.value, ln)
              | let err: BuilderError => return err
              end
            | TokWord =>
              if tok.value == "focusable" then
                focusable = true
              else
                return BuilderError(ln,
                  "unexpected token: " + tok.value)
              end
            end
          end
        end

        // Track stacks with tabs= for post-parse wrapping
        if type_name == "stack" then
          for ti in Range(1, tokens.size()) do
            try
              let tok = tokens(ti)?
              if (tok.kind is TokKeyValue) and (tok.key == "tabs") then
                match tok.value
                | "north" | "south" | "east" | "west" =>
                  match widget
                  | let sw: Stack tag =>
                    stacks_needing_tabs.push((sw, tok.value,
                      Array[(String val, String val)]))
                  end
                else
                  return BuilderError(ln, "invalid tabs position: " + tok.value)
                end
              end
            end
          end
        end

        // Apply primary text
        match primary_text
        | let text: String =>
          match type_name
          | "label" =>
            match widget
            | let l: Label tag => l.set_text(text)
            end
          | "frame" =>
            match widget
            | let f: Frame tag => f.set_title(text)
            end
          | "textbox" =>
            match widget
            | let tb: TextBox tag => tb.set_text(text)
            end
          end
        end

        // Store by #id
        match widget_id
        | let id: String =>
          _widgets_by_id(id) = widget
        end

        // Wire to parent
        match pending_pack
        | (let pi: USize, let is_start: Bool, let pw: USize, let ph: USize,
           let po: PackOption) =>
          if stack.size() > 0 then
            try
              (_, let parent_widget, _) = stack(stack.size() - 1)?
              if is_start then
                match parent_widget
                | let vb: VBox tag => vb.pack_start(widget, pw, ph, po)
                | let hb: HBox tag => hb.pack_start(widget, pw, ph, po)
                end
              else
                match parent_widget
                | let vb: VBox tag => vb.pack_end(widget, pw, ph, po)
                | let hb: HBox tag => hb.pack_end(widget, pw, ph, po)
                end
              end
            end
          end
          pending_pack = None
        else
          match pending_add
          | (let ai: USize, let add_name: String val,
             let add_tab: (String val | None)) =>
            if stack.size() > 0 then
              try
                (_, let parent_widget, let parent_type) = stack(stack.size() - 1)?
                if parent_type == "stack" then
                  match parent_widget
                  | let s: Stack tag =>
                    s.add_child(add_name, widget)
                    s.set_input_actor(_input_actor)
                    // Track tab entry for stacks with tabs=
                    for tab_info in stacks_needing_tabs.values() do
                      (let tracked_stack, _, let tab_entries) = tab_info
                      if (tracked_stack is s) then
                        let label = match add_tab
                        | let l: String val => l
                        else add_name
                        end
                        tab_entries.push((add_name, label))
                      end
                    end
                  end
                end
              end
            end
            _widgets_by_id(add_name) = widget
            pending_add = None
          else
            if stack.size() > 0 then
              try
                (_, let parent_widget, let parent_type) = stack(stack.size() - 1)?
                if parent_type == "frame" then
                  match parent_widget
                  | let f: Frame tag => f.set_child(widget)
                  end
                end
              end
            end
          end
        end

        // Track root
        match root
        | None => root = widget
        end

        // Push onto stack
        stack.push((indent, widget, type_name))

        // Register focusable (with stack scope if inside a stack child).
        // Must happen after push so the parse stack has the scope entry.
        // Routes through Stack so register_focusable and disable_scope
        // are causally ordered on the InputActor.
        if focusable then
          match _find_stack_and_scope(stack)
          | (let s: Stack tag, let scope: Widget tag) =>
            s._register_focusable(widget, scope)
          else
            _input_actor.register_focusable(widget)
          end
        end
      end
    end

    // Post-parse: wrap stacks that have tabs= with container + TabBar
    for tab_info in stacks_needing_tabs.values() do
      (let sw, let position, let tab_entries) = tab_info
      if tab_entries.size() == 0 then continue end

      let is_vertical_layout =
        (position == "north") or (position == "south")
      let tab_orient: TabOrientation =
        if is_vertical_layout then TabHorizontal else TabVertical end

      let callback = {(key: String val)(sw) => sw.show(key)} val

      if is_vertical_layout then
        let wrapper = VBox(_compositor)
        let tab_bar = TabBar(wrapper, callback, tab_orient)
        for te in tab_entries.values() do
          (let key, let label) = te
          tab_bar.add_tab(key, label)
        end
        _input_actor.register_focusable(tab_bar)

        match position
        | "north" =>
          wrapper.pack_start(tab_bar, 0, 1, PackOption(PackFixed))
          wrapper.pack_start(sw, 0, 0, PackOption(PackFill))
        | "south" =>
          wrapper.pack_start(sw, 0, 0, PackOption(PackFill))
          wrapper.pack_end(tab_bar, 0, 1, PackOption(PackFixed))
        end

        match root
        | let r: Widget tag if r is sw => root = wrapper
        end
      else
        let wrapper = HBox(_compositor)
        let tab_bar = TabBar(wrapper, callback, tab_orient)
        for te in tab_entries.values() do
          (let key, let label) = te
          tab_bar.add_tab(key, label)
        end
        _input_actor.register_focusable(tab_bar)

        match position
        | "west" =>
          wrapper.pack_start(tab_bar, 12, 0, PackOption(PackFixed))
          wrapper.pack_start(sw, 0, 0, PackOption(PackFill))
        | "east" =>
          wrapper.pack_start(sw, 0, 0, PackOption(PackFill))
          wrapper.pack_end(tab_bar, 12, 0, PackOption(PackFixed))
        end

        match root
        | let r: Widget tag if r is sw => root = wrapper
        end
      end
    end

    // Register root for resize and return
    match root
    | let r: Widget tag =>
      _input_actor.register_widget(r)
      r
    else
      BuilderError(0, "empty DSL: no widgets defined")
    end

  fun ref _apply_property(
    widget: Widget tag,
    type_name: String,
    key: String,
    value: String,
    line_num: USize)
    : (None | BuilderError)
  =>
    // Universal: debug-bg
    if key == "debug-bg" then
      match ColorLookup(value)
      | let c: Color => widget.set_debug_bg(c)
        return None
      | None =>
        return BuilderError(line_num, "unknown color: " + value)
      end
    end

    match type_name
    | "label" =>
      match key
      | "fg" =>
        match ColorLookup(value)
        | let c: Color =>
          match widget
          | let l: Label tag => l.set_color(c)
          end
        | None =>
          return BuilderError(line_num, "unknown color: " + value)
        end
      | "bg" =>
        match ColorLookup(value)
        | let c: Color =>
          match widget
          | let l: Label tag => l.set_color(White, c)
          end
        | None =>
          return BuilderError(line_num, "unknown color: " + value)
        end
      | "align" =>
        match AlignLookup(value)
        | let a: Alignment =>
          match widget
          | let l: Label tag => l.set_align(a)
          end
        | None =>
          return BuilderError(line_num, "unknown alignment: " + value)
        end
      else
        return BuilderError(line_num,
          "unknown property '" + key + "' for " + type_name)
      end
    | "frame" =>
      match key
      | "border-color" =>
        match ColorLookup(value)
        | let c: Color =>
          match widget
          | let f: Frame tag => f.set_border_color(c)
          end
        | None =>
          return BuilderError(line_num, "unknown color: " + value)
        end
      else
        return BuilderError(line_num,
          "unknown property '" + key + "' for " + type_name)
      end
    | "hbox" | "vbox" =>
      match key
      | "align" =>
        match AlignLookup(value)
        | let a: Alignment =>
          match type_name
          | "hbox" =>
            match widget
            | let hb: HBox tag => hb.set_align(a)
            end
          | "vbox" =>
            match widget
            | let vb: VBox tag => vb.set_align(a)
            end
          end
        | None =>
          return BuilderError(line_num, "unknown alignment: " + value)
        end
      else
        return BuilderError(line_num,
          "unknown property '" + key + "' for " + type_name)
      end
    | "hline" | "vline" =>
      match key
      | "color" =>
        match ColorLookup(value)
        | let c: Color =>
          match type_name
          | "hline" =>
            match widget
            | let hl: HLine tag => hl.set_color(c)
            end
          | "vline" =>
            match widget
            | let vl: VLine tag => vl.set_color(c)
            end
          end
        | None =>
          return BuilderError(line_num, "unknown color: " + value)
        end
      else
        return BuilderError(line_num,
          "unknown property '" + key + "' for " + type_name)
      end
    | "textbox" =>
      match key
      | "fg" =>
        match ColorLookup(value)
        | let c: Color =>
          match widget
          | let tb: TextBox tag => tb.set_color(c)
          end
        | None =>
          return BuilderError(line_num, "unknown color: " + value)
        end
      | "bg" =>
        match ColorLookup(value)
        | let c: Color =>
          match widget
          | let tb: TextBox tag => tb.set_color(White, c)
          end
        | None =>
          return BuilderError(line_num, "unknown color: " + value)
        end
      | "wrap" =>
        match widget
        | let tb: TextBox tag => tb.set_wrap(value == "true")
        end
      else
        return BuilderError(line_num,
          "unknown property '" + key + "' for " + type_name)
      end
    | "stack" =>
      match key
      | "tabs" => None  // Validated and applied in build() inline
      else
        return BuilderError(line_num,
          "unknown property '" + key + "' for " + type_name)
      end
    | "tabbar" =>
      match key
      | "orientation" => None  // Set at construction
      else
        return BuilderError(line_num,
          "unknown property '" + key + "' for " + type_name)
      end
    else
      return BuilderError(line_num,
        "unknown property '" + key + "' for " + type_name)
    end
    None

  fun _find_stack_and_scope(
    stack: Array[(USize, Widget tag, String)])
    : ((Stack tag, Widget tag) | None)
  =>
    """
    Walk the parse stack looking for a "stack" entry. Returns the Stack and
    its direct child (the focus scope widget). The child is the entry
    immediately after the stack in the parse stack.
    """
    var i: USize = 0
    while i < stack.size() do
      try
        (_, let stack_widget, let tn) = stack(i)?
        if tn == "stack" then
          try
            (_, let child_widget, _) = stack(i + 1)?
            match (stack_widget, child_widget)
            | (let s: Stack tag, let c: Widget tag) =>
              return (s, c)
            end
          end
        end
      end
      i = i + 1
    end
    None

  fun _strip_block_comments(input: String): String =>
    recover val
      let result = String(input.size())
      var in_block: Bool = false
      var i: USize = 0
      while i < input.size() do
        try
          if in_block then
            if (input(i)? == '*') and ((i + 1) < input.size())
              and (input(i + 1)? == '/')
            then
              in_block = false
              i = i + 2
              continue
            end
            // Preserve newlines for line counting
            if input(i)? == '\n' then
              result.push('\n')
            end
            i = i + 1
          else
            if (input(i)? == '/') and ((i + 1) < input.size())
              and (input(i + 1)? == '*')
            then
              in_block = true
              i = i + 2
              continue
            end
            result.push(input(i)?)
            i = i + 1
          end
        else
          break
        end
      end
      result
    end