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

namespace Unity.VisualScripting
{
    public abstract class StateWidget<TState> : NodeWidget<StateCanvas, TState>, IStateWidget
        where TState : class, IState
    {
        protected StateWidget(StateCanvas canvas, TState state) : base(canvas, state)
        {
            minResizeSize = new Vector2(State.DefaultWidth, 0);
        }

        public virtual bool canForceEnter => true;

        public virtual bool canForceExit => true;

        public virtual bool canToggleStart => true;


        #region Model

        protected TState state => element;

        protected IStateDebugData stateDebugData => GetDebugData<IStateDebugData>();

        protected State.Data stateData => reference.hasData ? reference.GetElementData<State.Data>(state) : null;

        IState IStateWidget.state => state;

        protected StateDescription description { get; private set; }

        protected StateAnalysis analysis => state.Analysis<StateAnalysis>(context);

        protected override void CacheDescription()
        {
            description = state.Description<StateDescription>();

            title = description.title;
            summary = description.summary;

            titleContent.text = " " + title;
            titleContent.image = description.icon?[IconSize.Small];
            summaryContent.text = summary;

            Reposition();
        }

        #endregion


        #region Lifecycle

        public override void BeforeFrame()
        {
            base.BeforeFrame();

            if (currentContentOuterHeight != targetContentOuterHeight)
            {
                Reposition();
            }
        }

        public override void HandleInput()
        {
            if (e.IsMouseDrag(MouseButton.Left) &&
                e.ctrlOrCmd &&
                !canvas.isCreatingTransition)
            {
                if (state.canBeSource)
                {
                    canvas.StartTransition(state);
                }
                else
                {
                    Debug.LogWarning("Cannot create a transition from this state.\n");
                }

                e.Use();
            }
            else if (e.IsMouseDrag(MouseButton.Left) && canvas.isCreatingTransition)
            {
                e.Use();
            }
            else if (e.IsMouseUp(MouseButton.Left) && canvas.isCreatingTransition)
            {
                var source = canvas.transitionSource;
                var destination = (canvas.hoveredWidget as IStateWidget)?.state;

                if (destination == null)
                {
                    canvas.CompleteTransitionToNewState();
                }
                else if (destination == source)
                {
                    canvas.CancelTransition();
                }
                else if (destination.canBeDestination)
                {
                    canvas.EndTransition(destination);
                }
                else
                {
                    Debug.LogWarning("Cannot create a transition to this state.\n");
                    canvas.CancelTransition();
                }

                e.Use();
            }

            base.HandleInput();
        }

        #endregion


        #region Contents

        protected virtual string title { get; set; }

        protected virtual string summary { get; set; }

        private GUIContent titleContent { get; } = new GUIContent();

        private GUIContent summaryContent { get; } = new GUIContent();

        #endregion


        #region Positioning

        public override IEnumerable<IWidget> positionDependers => state.transitions.Select(transition => (IWidget)canvas.Widget(transition));

        public Rect titlePosition { get; private set; }

        public Rect summaryPosition { get; private set; }

        public Rect contentOuterPosition { get; private set; }

        public Rect contentBackgroundPosition { get; private set; }

        public Rect contentInnerPosition { get; private set; }

        private float targetContentOuterHeight;

        private float currentContentOuterHeight;

        private bool revealInitialized;

        private Rect _position;

        public override Rect position
        {
            get { return _position; }
            set
            {
                state.position = value.position;
                state.width = value.width;
            }
        }

        public override void CachePosition()
        {
            var edgeOrigin = state.position;
            var edgeX = edgeOrigin.x;
            var edgeY = edgeOrigin.y;
            var edgeWidth = state.width;
            var innerOrigin = EdgeToInnerPosition(new Rect(edgeOrigin, Vector2.zero)).position;
            var innerX = innerOrigin.x;
            var innerY = innerOrigin.y;
            var innerWidth = EdgeToInnerPosition(new Rect(0, 0, edgeWidth, 0)).width;
            var innerHeight = 0f;

            var y = innerY;

            if (showTitle)
            {
                using (LudiqGUIUtility.iconSize.Override(IconSize.Small))
                {
                    titlePosition = new Rect
                        (
                        innerX,
                        y,
                        innerWidth,
                        Styles.title.CalcHeight(titleContent, innerWidth)
                        );

                    y += titlePosition.height;
                    innerHeight += titlePosition.height;
                }
            }

            if (showTitle && showSummary)
            {
                y += Styles.spaceBetweenTitleAndSummary;
                innerHeight += Styles.spaceBetweenTitleAndSummary;
            }

            if (showSummary)
            {
                summaryPosition = new Rect
                    (
                    innerX,
                    y,
                    innerWidth,
                    Styles.summary.CalcHeight(summaryContent, innerWidth)
                    );

                y += summaryPosition.height;
                innerHeight += summaryPosition.height;
            }

            if (showContent)
            {
                var contentInnerWidth = edgeWidth - Styles.contentBackground.padding.left - Styles.contentBackground.padding.right;

                targetContentOuterHeight = revealContent ? (Styles.spaceBeforeContent + Styles.contentBackground.padding.top + GetContentHeight(contentInnerWidth) + Styles.contentBackground.padding.bottom) : 0;

                if (!revealInitialized)
                {
                    currentContentOuterHeight = targetContentOuterHeight;
                    revealInitialized = true;
                }

                currentContentOuterHeight = Mathf.Lerp(currentContentOuterHeight, targetContentOuterHeight, canvas.repaintDeltaTime * Styles.contentRevealSpeed);

                if (Mathf.Abs(targetContentOuterHeight - currentContentOuterHeight) < 1)
                {
                    currentContentOuterHeight = targetContentOuterHeight;
                }

                contentOuterPosition = new Rect
                    (
                    edgeX,
                    y,
                    edgeWidth,
                    currentContentOuterHeight
                    );

                contentBackgroundPosition = new Rect
                    (
                    0,
                    Styles.spaceBeforeContent,
                    edgeWidth,
                    currentContentOuterHeight - Styles.spaceBeforeContent
                    );

                contentInnerPosition = new Rect
                    (
                    Styles.contentBackground.padding.left,
                    Styles.spaceBeforeContent + Styles.contentBackground.padding.top,
                    contentInnerWidth,
                    contentBackgroundPosition.height - Styles.contentBackground.padding.top
                    );

                y += contentOuterPosition.height;
                innerHeight += contentOuterPosition.height;
            }

            var edgeHeight = InnerToEdgePosition(new Rect(0, 0, 0, innerHeight)).height;

            _position = new Rect
                (
                edgeX,
                edgeY,
                edgeWidth,
                edgeHeight
                );
        }

        protected virtual float GetContentHeight(float width) => 0;

        #endregion


        #region Drawing

        protected virtual bool showTitle => true;

        protected virtual bool showSummary => !StringUtility.IsNullOrWhiteSpace(summary);

        protected virtual bool showContent => false;

        protected virtual NodeColorMix baseColor => NodeColor.Gray;

        protected override NodeColorMix color
        {
            get
            {
                if (stateDebugData.runtimeException != null)
                {
                    return NodeColor.Red;
                }

                var color = baseColor;

                if (state.isStart)
                {
                    color = NodeColor.Green;
                }

                if (stateData?.isActive ?? false)
                {
                    color = NodeColor.Blue;
                }
                else if (EditorApplication.isPaused)
                {
                    if (EditorTimeBinding.frame == stateDebugData.lastEnterFrame)
                    {
                        color = NodeColor.Blue;
                    }
                }
                else
                {
                    color.blue = Mathf.Lerp(1, 0, (EditorTimeBinding.time - stateDebugData.lastExitTime) / Styles.enterFadeDuration);
                }

                return color;
            }
        }

        protected override NodeShape shape => NodeShape.Square;

        private bool revealContent
        {
            get
            {
                switch (BoltState.Configuration.statesReveal)
                {
                    case StateRevealCondition.Always:

                        return true;
                    case StateRevealCondition.Never:

                        return false;
                    case StateRevealCondition.OnHover:

                        return isMouseOver;
                    case StateRevealCondition.OnHoverWithAlt:

                        return isMouseOver && e.alt;
                    case StateRevealCondition.WhenSelected:

                        return selection.Contains(state);
                    case StateRevealCondition.OnHoverOrSelected:

                        return isMouseOver || selection.Contains(state);
                    case StateRevealCondition.OnHoverWithAltOrSelected:

                        return isMouseOver && e.alt || selection.Contains(state);
                    default:

                        throw new UnexpectedEnumValueException<StateRevealCondition>(BoltState.Configuration.statesReveal);
                }
            }
        }

        private bool revealedContent;

        private void CheckReveal()
        {
            var revealContent = this.revealContent;

            if (revealContent != revealedContent)
            {
                Reposition();
            }

            revealedContent = revealContent;
        }

        protected override bool dim
        {
            get
            {
                var dim = BoltCore.Configuration.dimInactiveNodes && !analysis.isEntered;

                if (isMouseOver || isSelected)
                {
                    dim = false;
                }

                return dim;
            }
        }

        public override void DrawForeground()
        {
            BeginDim();

            base.DrawForeground();

            if (showTitle)
            {
                DrawTitle();
            }

            if (showSummary)
            {
                DrawSummary();
            }

            if (showContent)
            {
                DrawContentWrapped();
            }

            EndDim();

            CheckReveal();
        }

        private void DrawTitle()
        {
            using (LudiqGUIUtility.iconSize.Override(IconSize.Small))
            {
                GUI.Label(titlePosition, titleContent, invertForeground ? Styles.titleInverted : Styles.title);
            }
        }

        private void DrawSummary()
        {
            GUI.Label(summaryPosition, summaryContent, invertForeground ? Styles.summaryInverted : Styles.summary);
        }

        private void DrawContentWrapped()
        {
            GUI.BeginClip(contentOuterPosition);

            DrawContentBackground();

            DrawContent();

            GUI.EndClip();
        }

        protected virtual void DrawContentBackground()
        {
            if (e.IsRepaint)
            {
                Styles.contentBackground.Draw(contentBackgroundPosition, false, false, false, false);
            }
        }

        protected virtual void DrawContent() { }

        #endregion


        #region Selecting

        public override bool canSelect => true;

        #endregion


        #region Dragging

        protected override bool snapToGrid => BoltCore.Configuration.snapToGrid;

        public override bool canDrag => true;

        public override void ExpandDragGroup(HashSet<IGraphElement> dragGroup)
        {
            if (BoltCore.Configuration.carryChildren)
            {
                foreach (var transition in state.outgoingTransitions)
                {
                    if (dragGroup.Contains(transition.destination))
                    {
                        continue;
                    }

                    dragGroup.Add(transition.destination);

                    canvas.Widget(transition.destination).ExpandDragGroup(dragGroup);
                }
            }
        }

        #endregion


        #region Deleting

        public override bool canDelete => true;

        #endregion


        #region Resizing

        public override bool canResizeHorizontal => true;

        #endregion


        #region Clipboard

        public override void ExpandCopyGroup(HashSet<IGraphElement> copyGroup)
        {
            copyGroup.UnionWith(state.transitions.Cast<IGraphElement>());
        }

        #endregion


        #region Actions

        protected override IEnumerable<DropdownOption> contextOptions
        {
            get
            {
                if (Application.isPlaying && reference.hasData)
                {
                    if (canForceEnter)
                    {
                        yield return new DropdownOption((Action)ForceEnter, "Force Enter");
                    }

                    if (canForceExit)
                    {
                        yield return new DropdownOption((Action)ForceExit, "Force Exit");
                    }
                }

                if (canToggleStart)
                {
                    yield return new DropdownOption((Action)ToggleStart, "Toggle Start");
                }

                if (state.canBeSource)
                {
                    yield return new DropdownOption((Action)MakeTransition, "Make Transition");
                }

                if (state.canBeSource && state.canBeDestination)
                {
                    yield return new DropdownOption((Action)MakeSelfTransition, "Make Self Transition");
                }

                foreach (var baseOption in base.contextOptions)
                {
                    yield return baseOption;
                }
            }
        }

        private void ForceEnter()
        {
            using (var flow = Flow.New(reference))
            {
                state.OnEnter(flow, StateEnterReason.Forced);
            }
        }

        private void ForceExit()
        {
            using (var flow = Flow.New(reference))
            {
                state.OnExit(flow, StateExitReason.Forced);
            }
        }

        protected void MakeTransition()
        {
            canvas.StartTransition(state);
        }

        protected void MakeSelfTransition()
        {
            canvas.StartTransition(state);
            canvas.EndTransition(state);
        }

        protected void ToggleStart()
        {
            UndoUtility.RecordEditedObject("Toggle State Start");

            state.isStart = !state.isStart;
        }

        #endregion


        public static class Styles
        {
            static Styles()
            {
                title = new GUIStyle(BoltCore.Styles.nodeLabel);
                title.fontSize = 12;
                title.alignment = TextAnchor.MiddleCenter;
                title.wordWrap = true;

                summary = new GUIStyle(BoltCore.Styles.nodeLabel);
                summary.fontSize = 10;
                summary.alignment = TextAnchor.MiddleCenter;
                summary.wordWrap = true;

                titleInverted = new GUIStyle(title);
                titleInverted.normal.textColor = ColorPalette.unityBackgroundDark;

                summaryInverted = new GUIStyle(summary);
                summaryInverted.normal.textColor = ColorPalette.unityBackgroundDark;

                contentBackground = new GUIStyle("In BigTitle");
                contentBackground.padding = new RectOffset(0, 0, 4, 4);
            }

            public static readonly GUIStyle title;

            public static readonly GUIStyle summary;

            public static readonly GUIStyle titleInverted;

            public static readonly GUIStyle summaryInverted;

            public static readonly GUIStyle contentBackground;

            public static readonly float spaceBeforeContent = 5;

            public static readonly float spaceBetweenTitleAndSummary = 0;

            public static readonly float enterFadeDuration = 0.5f;

            public static readonly float contentRevealSpeed = 15;
        }
    }
}