summaryrefslogtreecommitdiff
path: root/Scripts/Terminal/OutputArea.cs
blob: e5f7535a7dfb789ff4abdbaf81189f3df32e1d92 (plain)
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
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Godot;
using Godot.Collections;

namespace Texty.Scripts.Terminal;

public partial class OutputArea : ScrollContainer
{
    [Export(PropertyHint.File, "*.tscn")] public PackedScene OutputBlockScene;
    public Array<string> TextBlocks => new(BlockNodes.ToList().Select(block => block.Content));

    private VBoxContainer LineContainer => GetNodeOrNull<VBoxContainer>($"%{nameof(LineContainer)}");

    private IEnumerable<OutputBlock> BlockNodes =>
        GD.Range(LineContainer?.GetChildCount() ?? 0)
            .Select(index => LineContainer.GetChild(index))
            .Cast<OutputBlock>();

    public override void _Ready()
    {
        Debug.Assert(OutputBlockScene != null, "OutputBlockScene has not been configured!");
        Debug.Assert(OutputBlockScene.CanInstantiate(), "OutputBlockScene can not be instanced!");
        Clear();
    }

    public void Clear()
    {
        BlockNodes.ToList().ForEach(block =>
        {
            LineContainer.RemoveChild(block);
            block.QueueFree();
        });
    }

    public void Push(string text)
    {
        if (string.IsNullOrEmpty(text)) return;
        var block = OutputBlockScene.Instantiate<OutputBlock>();
        block.Content = text;
        LineContainer.AddChild(block);
    }
}