< Summary

Class:DCL.Components.UIShape
Assembly:MainScripts
File(s):/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/Components/UI/UIShape.cs
Covered lines:152
Uncovered lines:12
Coverable lines:164
Total lines:504
Line coverage:92.6% (152 of 164)
Covered branches:0
Total branches:0

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity NPath complexity Sequence coverage
Model()0%110100%
GetDataFromJSON(...)0%110100%
UIShape()0%220100%
OnScreenResize(...)0%110100%
GetClassId()0%2100%
GetDebugName()0%220100%
ApplyChanges(...)0%2100%
InstantiateUIGameObject[T](...)0%6.076087.5%
LayoutRefreshWatcher()0%550100%
RefreshAll()0%220100%
MarkLayoutDirty(...)0%3.023087.5%
RefreshDCLLayout(...)0%330100%
RefreshDCLSize(...)0%2.022083.33%
RefreshDCLAlignmentAndPosition(...)0%22092.31%
RefreshDCLLayoutRecursively(...)0%110100%
RefreshDCLLayoutRecursively_Internal(...)0%220100%
FixMaxStretchRecursively()0%330100%
ReparentComponent(...)0%880100%
GetRootParent()0%330100%
ConfigureAlignment(...)0%13130100%
SetComponentDebugName()0%3.143075%
Dispose()0%330100%
OnChildAttached(...)0%110100%
OnChildDetached(...)0%110100%

File(s)

/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/Components/UI/UIShape.cs

#LineLine coverage
 1using DCL.Helpers;
 2using DCL.Models;
 3using System.Collections;
 4using UnityEngine;
 5using UnityEngine.Assertions;
 6using UnityEngine.UI;
 7
 8namespace DCL.Components
 9{
 10    [System.Serializable]
 11    public struct UIValue
 12    {
 13        public enum Unit
 14        {
 15            PERCENT,
 16            PIXELS
 17        }
 18
 19        public float value;
 20        public Unit type;
 21
 22        public void SetPixels(float value)
 23        {
 24            this.type = Unit.PIXELS;
 25            this.value = value;
 26        }
 27
 28        public void SetPercent(float value)
 29        {
 30            this.type = Unit.PERCENT;
 31            this.value = value;
 32        }
 33
 34        public UIValue(float value, Unit unitType = Unit.PIXELS)
 35        {
 36            this.value = value;
 37            this.type = unitType;
 38        }
 39
 40        public float GetScaledValue(float parentSize)
 41        {
 42            if (type == Unit.PIXELS)
 43                return value;
 44
 45            // Prevent division by zero
 46            if (parentSize <= Mathf.Epsilon)
 47                parentSize = 1;
 48
 49            return value / 100 * parentSize;
 50        }
 51    }
 52
 53    public class UIShape<ReferencesContainerType, ModelType> : UIShape
 54        where ReferencesContainerType : UIReferencesContainer
 55        where ModelType : UIShape.Model
 56    {
 57        public const float RAYCAST_ALPHA_THRESHOLD = 0.01f;
 58
 59        public UIShape() { }
 60
 61        new public ModelType model { get { return base.model as ModelType; } set { base.model = value; } }
 62
 63        new public ReferencesContainerType referencesContainer { get { return base.referencesContainer as ReferencesCont
 64
 65        public override ComponentUpdateHandler CreateUpdateHandler() { return new UIShapeUpdateHandler<ReferencesContain
 66
 67        bool raiseOnAttached;
 68        bool firstApplyChangesCall;
 69
 70        /// <summary>
 71        /// This is called by UIShapeUpdateHandler before calling ApplyChanges.
 72        /// </summary>
 73        public void PreApplyChanges(BaseModel newModel)
 74        {
 75            model = (ModelType) newModel;
 76
 77            raiseOnAttached = false;
 78            firstApplyChangesCall = false;
 79
 80            if (referencesContainer == null)
 81            {
 82                referencesContainer = InstantiateUIGameObject<ReferencesContainerType>(referencesContainerPrefabName);
 83
 84                raiseOnAttached = true;
 85                firstApplyChangesCall = true;
 86            }
 87            else if (ReparentComponent(referencesContainer.rectTransform, model.parentComponent))
 88            {
 89                raiseOnAttached = true;
 90            }
 91        }
 92
 93        public override void RaiseOnAppliedChanges()
 94        {
 95            RefreshDCLLayout();
 96
 97#if UNITY_EDITOR
 98            SetComponentDebugName();
 99#endif
 100
 101            // We hide the component visibility when it's created (first applychanges)
 102            // as it has default values and appears in the middle of the screen
 103            if (firstApplyChangesCall)
 104                referencesContainer.canvasGroup.alpha = 0f;
 105            else
 106                referencesContainer.canvasGroup.alpha = model.visible ? model.opacity : 0f;
 107
 108            referencesContainer.canvasGroup.blocksRaycasts = model.visible && model.isPointerBlocker;
 109
 110            base.RaiseOnAppliedChanges();
 111
 112            if (raiseOnAttached && parentUIComponent != null)
 113            {
 114                UIReferencesContainer[] parents = referencesContainer.GetComponentsInParent<UIReferencesContainer>(true)
 115
 116                for (int i = 0; i < parents.Length; i++)
 117                {
 118                    UIReferencesContainer parent = parents[i];
 119                    if (parent.owner != null)
 120                    {
 121                        parent.owner.OnChildAttached(parentUIComponent, this);
 122                    }
 123                }
 124            }
 125        }
 126    }
 127
 128    public class UIShape : BaseDisposable
 129    {
 130        [System.Serializable]
 131        public class Model : BaseModel
 132        {
 133            public string name;
 134            public string parentComponent;
 618135            public bool visible = true;
 618136            public float opacity = 1f;
 618137            public string hAlign = "center";
 618138            public string vAlign = "center";
 618139            public UIValue width = new UIValue(100f);
 618140            public UIValue height = new UIValue(50f);
 618141            public UIValue positionX = new UIValue(0f);
 618142            public UIValue positionY = new UIValue(0f);
 618143            public bool isPointerBlocker = true;
 144            public string onClick;
 145
 52146            public override BaseModel GetDataFromJSON(string json) { return Utils.SafeFromJson<Model>(json); }
 147        }
 148
 146149        public override string componentName => GetDebugName();
 0150        public virtual string referencesContainerPrefabName => "";
 151        public UIReferencesContainer referencesContainer;
 152        public RectTransform childHookRectTransform;
 153
 0154        public bool isLayoutDirty { get; protected set; }
 155        protected System.Action OnLayoutRefresh;
 156
 0157        private BaseVariable<Vector2Int> screenSize => DataStore.i.screen.size;
 158
 0159        public UIShape parentUIComponent { get; protected set; }
 160
 161        private Coroutine layoutRefreshWatcher;
 162
 122163        public UIShape()
 164        {
 122165            screenSize.OnChange += OnScreenResize;
 122166            model = new Model();
 167
 122168            if ( layoutRefreshWatcher == null )
 122169                layoutRefreshWatcher = CoroutineStarter.Start(LayoutRefreshWatcher());
 122170        }
 171
 6172        private void OnScreenResize(Vector2Int current, Vector2Int previous) => RefreshAll();
 173
 0174        public override int GetClassId() { return (int) CLASS_ID.UI_IMAGE_SHAPE; }
 175
 176        public string GetDebugName()
 177        {
 146178            Model model = (Model) this.model;
 179
 146180            if (string.IsNullOrEmpty(model.name))
 181            {
 139182                return GetType().Name;
 183            }
 184            else
 185            {
 7186                return GetType().Name + " - " + model.name;
 187            }
 188        }
 189
 190        public override IEnumerator ApplyChanges(BaseModel newJson)
 191        {
 0192            return null;
 193        }
 194
 195        internal T InstantiateUIGameObject<T>(string prefabPath) where T : UIReferencesContainer
 196        {
 78197            Model model = (Model) this.model;
 198
 78199            GameObject uiGameObject = null;
 200
 78201            bool targetParentExists = !string.IsNullOrEmpty(model.parentComponent) &&
 202                                      scene.disposableComponents.ContainsKey(model.parentComponent);
 203
 78204            if (targetParentExists)
 205            {
 23206                if (scene.disposableComponents.ContainsKey(model.parentComponent))
 207                {
 23208                    parentUIComponent = (scene.disposableComponents[model.parentComponent] as UIShape);
 23209                }
 210                else
 211                {
 0212                    parentUIComponent = scene.GetSharedComponent<UIScreenSpace>();
 213                }
 0214            }
 215            else
 216            {
 55217                parentUIComponent = scene.GetSharedComponent<UIScreenSpace>();
 218            }
 219
 78220            uiGameObject =
 221                Object.Instantiate(
 222                    Resources.Load(prefabPath),
 223                    parentUIComponent != null ? parentUIComponent.childHookRectTransform : null) as GameObject;
 224
 78225            referencesContainer = uiGameObject.GetComponent<T>();
 226
 78227            referencesContainer.rectTransform.SetToMaxStretch();
 228
 78229            childHookRectTransform = referencesContainer.childHookRectTransform;
 230
 78231            referencesContainer.owner = this;
 232
 78233            return referencesContainer as T;
 234        }
 235
 236        IEnumerator LayoutRefreshWatcher()
 237        {
 53238            while (true)
 239            {
 240                // WaitForEndOfFrame doesn't work in batch mode
 4311241                yield return Application.isBatchMode ? null : new WaitForEndOfFrame();
 242
 4189243                if ( !isLayoutDirty )
 244                    continue;
 245
 53246                RefreshAll();
 247            }
 248        }
 249
 250        public virtual void RefreshAll()
 251        {
 252            // We are not using the _Internal here because the method is overridden
 253            // by some UI shapes.
 59254            RefreshDCLLayoutRecursively(refreshSize: true, refreshAlignmentAndPosition: false);
 59255            FixMaxStretchRecursively();
 59256            RefreshDCLLayoutRecursively_Internal(refreshSize: false, refreshAlignmentAndPosition: true);
 59257            isLayoutDirty = false;
 59258            OnLayoutRefresh?.Invoke();
 59259            OnLayoutRefresh = null;
 59260        }
 261
 262        public virtual void MarkLayoutDirty( System.Action OnRefresh = null )
 263        {
 93264            UIShape rootParent = GetRootParent();
 265
 93266            Assert.IsTrue(rootParent != null, "root parent must never be null");
 267
 93268            if (rootParent.referencesContainer == null)
 0269                return;
 270
 93271            rootParent.isLayoutDirty = true;
 272
 93273            if ( OnRefresh != null )
 24274                rootParent.OnLayoutRefresh += OnRefresh;
 93275        }
 276
 277        public void RefreshDCLLayout(bool refreshSize = true, bool refreshAlignmentAndPosition = true)
 278        {
 366279            RectTransform parentRT = referencesContainer.GetComponentInParent<RectTransform>();
 280
 366281            if (refreshSize)
 282            {
 244283                RefreshDCLSize(parentRT);
 284            }
 285
 366286            if (refreshAlignmentAndPosition)
 287            {
 288                // Alignment (Alignment uses size so we should always align AFTER resizing)
 268289                RefreshDCLAlignmentAndPosition(parentRT);
 290            }
 366291        }
 292
 293        protected virtual void RefreshDCLSize(RectTransform parentTransform = null)
 294        {
 228295            if (parentTransform == null)
 0296                parentTransform = referencesContainer.GetComponentInParent<RectTransform>();
 297
 228298            Model model = (Model) this.model;
 299
 228300            referencesContainer.layoutElementRT.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal,
 301                model.width.GetScaledValue(parentTransform.rect.width));
 228302            referencesContainer.layoutElementRT.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical,
 303                model.height.GetScaledValue(parentTransform.rect.height));
 228304        }
 305
 306        public void RefreshDCLAlignmentAndPosition(RectTransform parentTransform = null)
 307        {
 268308            if (parentTransform == null)
 0309                parentTransform = referencesContainer.GetComponentInParent<RectTransform>();
 310
 268311            referencesContainer.layoutElement.ignoreLayout = false;
 268312            ConfigureAlignment(referencesContainer.layoutGroup);
 268313            Utils.ForceRebuildLayoutImmediate(parentTransform);
 268314            referencesContainer.layoutElement.ignoreLayout = true;
 315
 268316            Model model = (Model) this.model;
 317
 318            // Reposition
 268319            Vector3 position = Vector3.zero;
 268320            position.x = model.positionX.GetScaledValue(parentTransform.rect.width);
 268321            position.y = model.positionY.GetScaledValue(parentTransform.rect.height);
 322
 268323            position = Utils.Sanitize(position);
 268324            referencesContainer.layoutElementRT.localPosition += position;
 268325        }
 326
 327        public virtual void RefreshDCLLayoutRecursively(bool refreshSize = true,
 328            bool refreshAlignmentAndPosition = true)
 329        {
 83330            RefreshDCLLayoutRecursively_Internal(refreshSize, refreshAlignmentAndPosition);
 83331        }
 332
 333        public void RefreshDCLLayoutRecursively_Internal(bool refreshSize = true,
 334            bool refreshAlignmentAndPosition = true)
 335        {
 142336            UIShape rootParent = GetRootParent();
 337
 142338            Assert.IsTrue(rootParent != null, "root parent must never be null");
 339
 142340            if (rootParent.referencesContainer == null)
 6341                return;
 342
 136343            Utils.InverseTransformChildTraversal<UIReferencesContainer>(
 344                (x) =>
 345                {
 304346                    if (x.owner != null)
 220347                        x.owner.RefreshDCLLayout(refreshSize, refreshAlignmentAndPosition);
 304348                },
 349                rootParent.referencesContainer.transform);
 136350        }
 351
 352        public void FixMaxStretchRecursively()
 353        {
 59354            UIShape rootParent = GetRootParent();
 355
 59356            Assert.IsTrue(rootParent != null, "root parent must never be null");
 357
 59358            if (rootParent.referencesContainer == null)
 3359                return;
 360
 56361            Utils.InverseTransformChildTraversal<UIReferencesContainer>(
 362                (x) =>
 363                {
 140364                    if (x.owner != null)
 365                    {
 98366                        x.rectTransform.SetToMaxStretch();
 367                    }
 140368                },
 369                rootParent.referencesContainer.transform);
 56370        }
 371
 372        protected bool ReparentComponent(RectTransform targetTransform, string targetParent)
 373        {
 68374            bool targetParentExists = !string.IsNullOrEmpty(targetParent) &&
 375                                      scene.disposableComponents.ContainsKey(targetParent);
 376
 68377            if (targetParentExists && parentUIComponent == scene.disposableComponents[targetParent])
 378            {
 22379                return false;
 380            }
 381
 46382            if (parentUIComponent != null)
 383            {
 46384                UIReferencesContainer[] parents = referencesContainer.GetComponentsInParent<UIReferencesContainer>(true)
 385
 186386                foreach (var parent in parents)
 387                {
 47388                    if (parent.owner != null)
 389                    {
 47390                        parent.owner.OnChildDetached(parentUIComponent, this);
 391                    }
 392                }
 393            }
 394
 46395            if (targetParentExists)
 396            {
 22397                parentUIComponent = scene.disposableComponents[targetParent] as UIShape;
 22398            }
 399            else
 400            {
 24401                parentUIComponent = scene.GetSharedComponent<UIScreenSpace>();
 402            }
 403
 46404            targetTransform.SetParent(parentUIComponent.childHookRectTransform, false);
 46405            return true;
 406        }
 407
 408        public UIShape GetRootParent()
 409        {
 300410            UIShape parent = null;
 411
 300412            if (parentUIComponent != null && !(parentUIComponent is UIScreenSpace))
 413            {
 6414                parent = parentUIComponent.GetRootParent();
 6415            }
 416            else
 417            {
 294418                parent = this;
 419            }
 420
 300421            return parent;
 422        }
 423
 424        protected void ConfigureAlignment(LayoutGroup layout)
 425        {
 268426            Model model = (Model) this.model;
 268427            switch (model.vAlign)
 428            {
 429                case "top":
 7430                    switch (model.hAlign)
 431                    {
 432                        case "left":
 2433                            layout.childAlignment = TextAnchor.UpperLeft;
 2434                            break;
 435                        case "right":
 2436                            layout.childAlignment = TextAnchor.UpperRight;
 2437                            break;
 438                        default:
 3439                            layout.childAlignment = TextAnchor.UpperCenter;
 3440                            break;
 441                    }
 442
 443                    break;
 444                case "bottom":
 26445                    switch (model.hAlign)
 446                    {
 447                        case "left":
 8448                            layout.childAlignment = TextAnchor.LowerLeft;
 8449                            break;
 450                        case "right":
 16451                            layout.childAlignment = TextAnchor.LowerRight;
 16452                            break;
 453                        default:
 2454                            layout.childAlignment = TextAnchor.LowerCenter;
 2455                            break;
 456                    }
 457
 458                    break;
 459                default: // center
 235460                    switch (model.hAlign)
 461                    {
 462                        case "left":
 2463                            layout.childAlignment = TextAnchor.MiddleLeft;
 2464                            break;
 465                        case "right":
 2466                            layout.childAlignment = TextAnchor.MiddleRight;
 2467                            break;
 468                        default:
 231469                            layout.childAlignment = TextAnchor.MiddleCenter;
 470                            break;
 471                    }
 472
 473                    break;
 474            }
 231475        }
 476
 477        protected void SetComponentDebugName()
 478        {
 146479            if (referencesContainer == null || model == null)
 480            {
 0481                return;
 482            }
 483
 146484            referencesContainer.name = componentName;
 146485        }
 486
 487        public override void Dispose()
 488        {
 85489            if (childHookRectTransform)
 52490                Utils.SafeDestroy(childHookRectTransform.gameObject);
 491
 85492            screenSize.OnChange -= OnScreenResize;
 493
 85494            if ( layoutRefreshWatcher != null )
 85495                CoroutineStarter.Stop(layoutRefreshWatcher);
 496
 85497            base.Dispose();
 85498        }
 499
 115500        public virtual void OnChildAttached(UIShape parentComponent, UIShape childComponent) { }
 501
 38502        public virtual void OnChildDetached(UIShape parentComponent, UIShape childComponent) { }
 503    }
 504}