summaryrefslogtreecommitdiff
path: root/Plugins/MonoGame.Extended/source/MonoGame.Extended.Gui/Serialization/ControlJsonConverter.cs
blob: a9c71f823511b8dfa56cff0b53d557bcf17ecc91 (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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
using MonoGame.Extended.Gui.Controls;

namespace MonoGame.Extended.Gui.Serialization
{
    public class ControlJsonConverter : JsonConverter<Control>
    {
        private readonly IGuiSkinService _guiSkinService;
        private readonly ControlStyleJsonConverter _styleConverter;
        private const string _styleProperty = "Style";

        public ControlJsonConverter(IGuiSkinService guiSkinService, params Type[] customControlTypes)
        {
            _guiSkinService = guiSkinService;
            _styleConverter = new ControlStyleJsonConverter(customControlTypes);
        }

        /// <inheritdoc />
        public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(Control);

        /// <inheritdoc />
        public override Control Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            var style = _styleConverter.Read(ref reader, typeToConvert, options);
            var template = GetControlTemplate(style);
            var skin = _guiSkinService.Skin;
            var control = skin.Create(style.TargetType, template);

            var itemsControl = control as ItemsControl;
            if (itemsControl != null)
            {
                object childControls;

                if (style.TryGetValue(nameof(ItemsControl.Items), out childControls))
                {
                    var controlCollection = childControls as ControlCollection;

                    if (controlCollection != null)
                    {
                        foreach (var child in controlCollection)
                            itemsControl.Items.Add(child);
                    }
                }
            }

            style.Apply(control);
            return control;
        }

        /// <inheritdoc />
        public override void Write(Utf8JsonWriter writer, Control value, JsonSerializerOptions options) { }



        private static string GetControlTemplate(ControlStyle style)
        {
            object template;

            if (style.TryGetValue(_styleProperty, out template))
                return template as string;

            return null;
        }
    }
}