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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;

namespace Unity.VisualScripting
{
    [FuzzyOption(typeof(IUnit))]
    public class UnitOption<TUnit> : IUnitOption where TUnit : IUnit
    {
        public UnitOption()
        {
            sourceScriptGuids = new HashSet<string>();
        }

        public UnitOption(TUnit unit) : this()
        {
            this.unit = unit;

            FillFromUnit();
        }

        [DoNotSerialize]
        protected bool filled { get; private set; }

        private TUnit _unit;

        protected UnitOptionRow source { get; private set; }

        public TUnit unit
        {
            get
            {
                // Load the node on demand to avoid deserialization overhead
                // Deserializing the entire database takes many seconds,
                // which is the reason why UnitOptionRow and SQLite are used
                // in the first place.

                if (_unit == null)
                {
                    _unit = (TUnit)new SerializationData(source.unit).Deserialize();
                }

                return _unit;
            }
            protected set
            {
                _unit = value;
            }
        }

        IUnit IUnitOption.unit => unit;

        public Type unitType { get; private set; }

        protected IUnitDescriptor descriptor => unit.Descriptor<IUnitDescriptor>();

        // Avoid using the descriptions for each option, because we don't need all fields described until the option is hovered

        protected UnitDescription description => unit.Description<UnitDescription>();

        protected UnitPortDescription PortDescription(IUnitPort port)
        {
            return port.Description<UnitPortDescription>();
        }

        public virtual IUnit InstantiateUnit()
        {
            var instance = unit.CloneViaSerialization();
            instance.Define();
            return instance;
        }

        void IUnitOption.PreconfigureUnit(IUnit unit)
        {
            PreconfigureUnit((TUnit)unit);
        }

        public virtual void PreconfigureUnit(TUnit unit)
        {
        }

        protected virtual void FillFromUnit()
        {
            unit.EnsureDefined();
            unitType = unit.GetType();

            labelHuman = Label(true);
            haystackHuman = Haystack(true);

            labelProgrammer = Label(false);
            haystackProgrammer = Haystack(false);

            category = Category();
            order = Order();
            favoriteKey = FavoriteKey();
            UnityAPI.Async(() => icon = Icon());

            showControlInputsInFooter = ShowControlInputsInFooter();
            showControlOutputsInFooter = ShowControlOutputsInFooter();
            showValueInputsInFooter = ShowValueInputsInFooter();
            showValueOutputsInFooter = ShowValueOutputsInFooter();

            controlInputCount = unit.controlInputs.Count;
            controlOutputCount = unit.controlOutputs.Count;
            valueInputTypes = unit.valueInputs.Select(vi => vi.type).ToHashSet();
            valueOutputTypes = unit.valueOutputs.Select(vo => vo.type).ToHashSet();

            filled = true;
        }

        protected virtual void FillFromData()
        {
            unit.EnsureDefined();
            unitType = unit.GetType();
            UnityAPI.Async(() => icon = Icon());

            showControlInputsInFooter = ShowControlInputsInFooter();
            showControlOutputsInFooter = ShowControlOutputsInFooter();
            showValueInputsInFooter = ShowValueInputsInFooter();
            showValueOutputsInFooter = ShowValueOutputsInFooter();

            filled = true;
        }

        public virtual void Deserialize(UnitOptionRow row)
        {
            source = row;

            if (row.sourceScriptGuids != null)
            {
                sourceScriptGuids = row.sourceScriptGuids.Split(',').ToHashSet();
            }

            unitType = Codebase.DeserializeType(row.unitType);

            category = row.category == null ? null : new UnitCategory(row.category);
            labelHuman = row.labelHuman;
            labelProgrammer = row.labelProgrammer;
            order = row.order;
            haystackHuman = row.haystackHuman;
            haystackProgrammer = row.haystackProgrammer;
            favoriteKey = row.favoriteKey;

            controlInputCount = row.controlInputCount;
            controlOutputCount = row.controlOutputCount;
        }

        public virtual UnitOptionRow Serialize()
        {
            var row = new UnitOptionRow();

            if (sourceScriptGuids.Count == 0)
            {
                // Important to set to null here, because the code relies on
                // null checks, not empty string checks.
                row.sourceScriptGuids = null;
            }
            else
            {
                row.sourceScriptGuids = string.Join(",", sourceScriptGuids.ToArray());
            }

            row.optionType = Codebase.SerializeType(GetType());
            row.unitType = Codebase.SerializeType(unitType);
            row.unit = unit.Serialize().json;

            row.category = category?.fullName;
            row.labelHuman = labelHuman;
            row.labelProgrammer = labelProgrammer;
            row.order = order;
            row.haystackHuman = haystackHuman;
            row.haystackProgrammer = haystackProgrammer;
            row.favoriteKey = favoriteKey;

            row.controlInputCount = controlInputCount;
            row.controlOutputCount = controlOutputCount;
            row.valueInputTypes = valueInputTypes.Select(Codebase.SerializeType).ToSeparatedString("|").NullIfEmpty();
            row.valueOutputTypes = valueOutputTypes.Select(Codebase.SerializeType).ToSeparatedString("|").NullIfEmpty();

            return row;
        }

        public virtual void OnPopulate()
        {
            if (!filled)
            {
                FillFromData();
            }
        }

        public virtual void Prewarm() { }


        #region Configuration

        public object value => this;

        public bool parentOnly => false;

        public virtual string headerLabel => label;

        public virtual bool showHeaderIcon => false;

        public virtual bool favoritable => true;

        #endregion


        #region Properties

        public HashSet<string> sourceScriptGuids { get; protected set; }

        protected string labelHuman { get; set; }

        protected string labelProgrammer { get; set; }

        public string label => BoltCore.Configuration.humanNaming ? labelHuman : labelProgrammer;

        public UnitCategory category { get; private set; }

        public int order { get; private set; }

        public EditorTexture icon { get; private set; }

        protected string haystackHuman { get; set; }

        protected string haystackProgrammer { get; set; }

        public string haystack => BoltCore.Configuration.humanNaming ? haystackHuman : haystackProgrammer;

        public string favoriteKey { get; private set; }

        public virtual string formerHaystack => BoltFlowNameUtility.UnitPreviousTitle(unitType);

        GUIStyle IFuzzyOption.style => Style();

        #endregion


        #region Contextual Filtering

        public int controlInputCount { get; private set; }

        public int controlOutputCount { get; private set; }

        private HashSet<Type> _valueInputTypes;

        private HashSet<Type> _valueOutputTypes;

        // On demand loading for initialization performance (type deserialization is expensive)

        public HashSet<Type> valueInputTypes
        {
            get
            {
                if (_valueInputTypes == null)
                {
                    if (string.IsNullOrEmpty(source.valueInputTypes))
                    {
                        _valueInputTypes = new HashSet<Type>();
                    }
                    else
                    {
                        _valueInputTypes = source.valueInputTypes.Split('|').Select(Codebase.DeserializeType).ToHashSet();
                    }
                }

                return _valueInputTypes;
            }
            private set
            {
                _valueInputTypes = value;
            }
        }

        public HashSet<Type> valueOutputTypes
        {
            get
            {
                if (_valueOutputTypes == null)
                {
                    if (string.IsNullOrEmpty(source.valueOutputTypes))
                    {
                        _valueOutputTypes = new HashSet<Type>();
                    }
                    else
                    {
                        _valueOutputTypes = source.valueOutputTypes.Split('|').Select(Codebase.DeserializeType).ToHashSet();
                    }
                }

                return _valueOutputTypes;
            }
            private set
            {
                _valueOutputTypes = value;
            }
        }

        #endregion


        #region Providers

        protected virtual string Label(bool human)
        {
            return BoltFlowNameUtility.UnitTitle(unitType, false, true);
        }

        protected virtual UnitCategory Category()
        {
            return unitType.GetAttribute<UnitCategory>();
        }

        protected virtual int Order()
        {
            return unitType.GetAttribute<UnitOrderAttribute>()?.order ?? int.MaxValue;
        }

        protected virtual string Haystack(bool human)
        {
            return Label(human);
        }

        protected virtual EditorTexture Icon()
        {
            return descriptor.Icon();
        }

        protected virtual GUIStyle Style()
        {
            return FuzzyWindow.defaultOptionStyle;
        }

        protected virtual string FavoriteKey()
        {
            return unit.GetType().FullName;
        }

        #endregion


        #region Search

        public virtual string SearchResultLabel(string query)
        {
            var label = SearchUtility.HighlightQuery(haystack, query);

            if (category != null)
            {
                label += $" <color=#{ColorPalette.unityForegroundDim.ToHexString()}>(in {category.fullName})</color>";
            }

            return label;
        }

        #endregion


        #region Footer

        private string summary => description.summary;

        public bool hasFooter => !StringUtility.IsNullOrWhiteSpace(summary) || footerPorts.Any();

        protected virtual bool ShowControlInputsInFooter()
        {
            return unitType.GetAttribute<UnitFooterPortsAttribute>()?.ControlInputs ?? false;
        }

        protected virtual bool ShowControlOutputsInFooter()
        {
            return unitType.GetAttribute<UnitFooterPortsAttribute>()?.ControlOutputs ?? false;
        }

        protected virtual bool ShowValueInputsInFooter()
        {
            return unitType.GetAttribute<UnitFooterPortsAttribute>()?.ValueInputs ?? true;
        }

        protected virtual bool ShowValueOutputsInFooter()
        {
            return unitType.GetAttribute<UnitFooterPortsAttribute>()?.ValueOutputs ?? true;
        }

        [DoNotSerialize]
        protected bool showControlInputsInFooter { get; private set; }

        [DoNotSerialize]
        protected bool showControlOutputsInFooter { get; private set; }

        [DoNotSerialize]
        protected bool showValueInputsInFooter { get; private set; }

        [DoNotSerialize]
        protected bool showValueOutputsInFooter { get; private set; }

        private IEnumerable<IUnitPort> footerPorts
        {
            get
            {
                if (showControlInputsInFooter)
                {
                    foreach (var controlInput in unit.controlInputs)
                    {
                        yield return controlInput;
                    }
                }

                if (showControlOutputsInFooter)
                {
                    foreach (var controlOutput in unit.controlOutputs)
                    {
                        yield return controlOutput;
                    }
                }

                if (showValueInputsInFooter)
                {
                    foreach (var valueInput in unit.valueInputs)
                    {
                        yield return valueInput;
                    }
                }

                if (showValueOutputsInFooter)
                {
                    foreach (var valueOutput in unit.valueOutputs)
                    {
                        yield return valueOutput;
                    }
                }
            }
        }

        public float GetFooterHeight(float width)
        {
            var hasSummary = !StringUtility.IsNullOrWhiteSpace(summary);
            var hasIcon = icon != null;
            var hasPorts = footerPorts.Any();

            var height = 0f;

            width -= 2 * FooterStyles.padding;

            height += FooterStyles.padding;

            if (hasSummary)
            {
                if (hasIcon)
                {
                    height += Mathf.Max(FooterStyles.unitIconSize, GetFooterSummaryHeight(width - FooterStyles.unitIconSize - FooterStyles.spaceAfterUnitIcon));
                }
                else
                {
                    height += GetFooterSummaryHeight(width);
                }
            }

            if (hasSummary && hasPorts)
            {
                height += FooterStyles.spaceBetweenDescriptionAndPorts;
            }

            foreach (var port in footerPorts)
            {
                height += GetFooterPortHeight(width, port);
                height += FooterStyles.spaceBetweenPorts;
            }

            if (hasPorts)
            {
                height -= FooterStyles.spaceBetweenPorts;
            }

            height += FooterStyles.padding;

            return height;
        }

        public void OnFooterGUI(Rect position)
        {
            var hasSummary = !StringUtility.IsNullOrWhiteSpace(summary);
            var hasIcon = icon != null;
            var hasPorts = footerPorts.Any();

            var y = position.y;

            y += FooterStyles.padding;

            position.x += FooterStyles.padding;
            position.width -= FooterStyles.padding * 2;

            if (hasSummary)
            {
                if (hasIcon)
                {
                    var iconPosition = new Rect
                        (
                        position.x,
                        y,
                        FooterStyles.unitIconSize,
                        FooterStyles.unitIconSize
                        );

                    var summaryWidth = position.width - iconPosition.width - FooterStyles.spaceAfterUnitIcon;

                    var summaryPosition = new Rect
                        (
                        iconPosition.xMax + FooterStyles.spaceAfterUnitIcon,
                        y,
                        summaryWidth,
                        GetFooterSummaryHeight(summaryWidth)
                        );

                    GUI.DrawTexture(iconPosition, icon?[FooterStyles.unitIconSize]);

                    OnFooterSummaryGUI(summaryPosition);

                    y = Mathf.Max(iconPosition.yMax, summaryPosition.yMax);
                }
                else
                {
                    OnFooterSummaryGUI(position.VerticalSection(ref y, GetFooterSummaryHeight(position.width)));
                }
            }

            if (hasSummary && hasPorts)
            {
                y += FooterStyles.spaceBetweenDescriptionAndPorts;
            }

            foreach (var port in footerPorts)
            {
                OnFooterPortGUI(position.VerticalSection(ref y, GetFooterPortHeight(position.width, port)), port);
                y += FooterStyles.spaceBetweenPorts;
            }

            if (hasPorts)
            {
                y -= FooterStyles.spaceBetweenPorts;
            }

            y += FooterStyles.padding;
        }

        private float GetFooterSummaryHeight(float width)
        {
            return FooterStyles.description.CalcHeight(new GUIContent(summary), width);
        }

        private void OnFooterSummaryGUI(Rect position)
        {
            EditorGUI.LabelField(position, summary, FooterStyles.description);
        }

        private string GetFooterPortLabel(IUnitPort port)
        {
            string type;

            if (port is ValueInput)
            {
                type = ((IUnitValuePort)port).type.DisplayName() + " Input";
            }
            else if (port is ValueOutput)
            {
                type = ((IUnitValuePort)port).type.DisplayName() + " Output";
            }
            else if (port is ControlInput)
            {
                type = "Trigger Input";
            }
            else if (port is ControlOutput)
            {
                type = "Trigger Output";
            }
            else
            {
                throw new NotSupportedException();
            }

            var portDescription = PortDescription(port);

            if (!StringUtility.IsNullOrWhiteSpace(portDescription.summary))
            {
                return $"<b>{portDescription.label}:</b> {portDescription.summary} {LudiqGUIUtility.DimString($"({type})")}";
            }
            else
            {
                return $"<b>{portDescription.label}:</b> {LudiqGUIUtility.DimString($"({type})")}";
            }
        }

        private float GetFooterPortDescriptionHeight(float width, IUnitPort port)
        {
            return FooterStyles.portDescription.CalcHeight(new GUIContent(GetFooterPortLabel(port)), width);
        }

        private void OnFooterPortDescriptionGUI(Rect position, IUnitPort port)
        {
            GUI.Label(position, GetFooterPortLabel(port), FooterStyles.portDescription);
        }

        private float GetFooterPortHeight(float width, IUnitPort port)
        {
            var descriptionWidth = width - FooterStyles.portIconSize - FooterStyles.spaceAfterPortIcon;

            return GetFooterPortDescriptionHeight(descriptionWidth, port);
        }

        private void OnFooterPortGUI(Rect position, IUnitPort port)
        {
            var iconPosition = new Rect
                (
                position.x,
                position.y,
                FooterStyles.portIconSize,
                FooterStyles.portIconSize
                );

            var descriptionWidth = position.width - FooterStyles.portIconSize - FooterStyles.spaceAfterPortIcon;

            var descriptionPosition = new Rect
                (
                iconPosition.xMax + FooterStyles.spaceAfterPortIcon,
                position.y,
                descriptionWidth,
                GetFooterPortDescriptionHeight(descriptionWidth, port)
                );

            var portDescription = PortDescription(port);

            var icon = portDescription.icon?[FooterStyles.portIconSize];

            if (icon != null)
            {
                GUI.DrawTexture(iconPosition, icon);
            }

            OnFooterPortDescriptionGUI(descriptionPosition, port);
        }

        public static class FooterStyles
        {
            static FooterStyles()
            {
                description = new GUIStyle(EditorStyles.label);
                description.padding = new RectOffset(0, 0, 0, 0);
                description.wordWrap = true;
                description.richText = true;

                portDescription = new GUIStyle(EditorStyles.label);
                portDescription.padding = new RectOffset(0, 0, 0, 0);
                portDescription.wordWrap = true;
                portDescription.richText = true;
                portDescription.imagePosition = ImagePosition.TextOnly;
            }

            public static readonly GUIStyle description;
            public static readonly GUIStyle portDescription;
            public static readonly float spaceAfterUnitIcon = 7;
            public static readonly int unitIconSize = IconSize.Medium;
            public static readonly float spaceAfterPortIcon = 6;
            public static readonly int portIconSize = IconSize.Small;
            public static readonly float spaceBetweenDescriptionAndPorts = 8;
            public static readonly float spaceBetweenPorts = 8;
            public static readonly float padding = 8;
        }

        #endregion
    }
}