< 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:154
Uncovered lines:12
Coverable lines:166
Total lines:508
Line coverage:92.7% (154 of 166)
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%7.237083.33%
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
 178157        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
 2172        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
 0190        public override IEnumerator ApplyChanges(BaseModel newJson) { return null; }
 191
 192        internal T InstantiateUIGameObject<T>(string prefabPath) where T : UIReferencesContainer
 193        {
 78194            Model model = (Model) this.model;
 195
 78196            GameObject uiGameObject = null;
 197
 78198            bool targetParentExists = !string.IsNullOrEmpty(model.parentComponent) &&
 199                                      scene.disposableComponents.ContainsKey(model.parentComponent);
 200
 78201            if (targetParentExists)
 202            {
 23203                if (scene.disposableComponents.ContainsKey(model.parentComponent))
 204                {
 23205                    parentUIComponent = (scene.disposableComponents[model.parentComponent] as UIShape);
 23206                }
 207                else
 208                {
 0209                    parentUIComponent = scene.GetSharedComponent<UIScreenSpace>();
 210                }
 0211            }
 212            else
 213            {
 55214                parentUIComponent = scene.GetSharedComponent<UIScreenSpace>();
 215            }
 216
 78217            uiGameObject =
 218                Object.Instantiate(
 219                    Resources.Load(prefabPath),
 220                    parentUIComponent != null ? parentUIComponent.childHookRectTransform : null) as GameObject;
 221
 78222            referencesContainer = uiGameObject.GetComponent<T>();
 223
 78224            referencesContainer.rectTransform.SetToMaxStretch();
 225
 78226            childHookRectTransform = referencesContainer.childHookRectTransform;
 227
 78228            referencesContainer.owner = this;
 229
 78230            return referencesContainer as T;
 231        }
 232
 233        IEnumerator LayoutRefreshWatcher()
 234        {
 53235            while (true)
 236            {
 237                // WaitForEndOfFrame doesn't work in batch mode
 2180238                yield return Application.isBatchMode ? null : new WaitForEndOfFrame();
 239
 2058240                if ( !isLayoutDirty )
 241                    continue;
 242
 243                // When running tests this is empty.
 53244                if (!string.IsNullOrEmpty(CommonScriptableObjects.sceneID))
 245                {
 0246                    if (CommonScriptableObjects.sceneID.Get() != scene.sceneData.id)
 247                        continue;
 248                }
 249
 53250                RefreshAll();
 251            }
 252        }
 253
 254        public virtual void RefreshAll()
 255        {
 256            // We are not using the _Internal here because the method is overridden
 257            // by some UI shapes.
 55258            RefreshDCLLayoutRecursively(refreshSize: true, refreshAlignmentAndPosition: false);
 55259            FixMaxStretchRecursively();
 55260            RefreshDCLLayoutRecursively_Internal(refreshSize: false, refreshAlignmentAndPosition: true);
 55261            isLayoutDirty = false;
 55262            OnLayoutRefresh?.Invoke();
 55263            OnLayoutRefresh = null;
 55264        }
 265
 266        public virtual void MarkLayoutDirty( System.Action OnRefresh = null )
 267        {
 93268            UIShape rootParent = GetRootParent();
 269
 93270            Assert.IsTrue(rootParent != null, "root parent must never be null");
 271
 93272            if (rootParent.referencesContainer == null)
 0273                return;
 274
 93275            rootParent.isLayoutDirty = true;
 276
 93277            if ( OnRefresh != null )
 24278                rootParent.OnLayoutRefresh += OnRefresh;
 93279        }
 280
 281        public void RefreshDCLLayout(bool refreshSize = true, bool refreshAlignmentAndPosition = true)
 282        {
 362283            RectTransform parentRT = referencesContainer.GetComponentInParent<RectTransform>();
 284
 362285            if (refreshSize)
 286            {
 242287                RefreshDCLSize(parentRT);
 288            }
 289
 362290            if (refreshAlignmentAndPosition)
 291            {
 292                // Alignment (Alignment uses size so we should always align AFTER resizing)
 266293                RefreshDCLAlignmentAndPosition(parentRT);
 294            }
 362295        }
 296
 297        protected virtual void RefreshDCLSize(RectTransform parentTransform = null)
 298        {
 226299            if (parentTransform == null)
 0300                parentTransform = referencesContainer.GetComponentInParent<RectTransform>();
 301
 226302            Model model = (Model) this.model;
 303
 226304            referencesContainer.layoutElementRT.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal,
 305                model.width.GetScaledValue(parentTransform.rect.width));
 226306            referencesContainer.layoutElementRT.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical,
 307                model.height.GetScaledValue(parentTransform.rect.height));
 226308        }
 309
 310        public void RefreshDCLAlignmentAndPosition(RectTransform parentTransform = null)
 311        {
 266312            if (parentTransform == null)
 0313                parentTransform = referencesContainer.GetComponentInParent<RectTransform>();
 314
 266315            referencesContainer.layoutElement.ignoreLayout = false;
 266316            ConfigureAlignment(referencesContainer.layoutGroup);
 266317            Utils.ForceRebuildLayoutImmediate(parentTransform);
 266318            referencesContainer.layoutElement.ignoreLayout = true;
 319
 266320            Model model = (Model) this.model;
 321
 322            // Reposition
 266323            Vector3 position = Vector3.zero;
 266324            position.x = model.positionX.GetScaledValue(parentTransform.rect.width);
 266325            position.y = model.positionY.GetScaledValue(parentTransform.rect.height);
 326
 266327            position = Utils.Sanitize(position);
 266328            referencesContainer.layoutElementRT.localPosition += position;
 266329        }
 330
 331        public virtual void RefreshDCLLayoutRecursively(bool refreshSize = true,
 332            bool refreshAlignmentAndPosition = true)
 333        {
 79334            RefreshDCLLayoutRecursively_Internal(refreshSize, refreshAlignmentAndPosition);
 79335        }
 336
 337        public void RefreshDCLLayoutRecursively_Internal(bool refreshSize = true,
 338            bool refreshAlignmentAndPosition = true)
 339        {
 134340            UIShape rootParent = GetRootParent();
 341
 134342            Assert.IsTrue(rootParent != null, "root parent must never be null");
 343
 134344            if (rootParent.referencesContainer == null)
 2345                return;
 346
 132347            Utils.InverseTransformChildTraversal<UIReferencesContainer>(
 348                (x) =>
 349                {
 300350                    if (x.owner != null)
 216351                        x.owner.RefreshDCLLayout(refreshSize, refreshAlignmentAndPosition);
 300352                },
 353                rootParent.referencesContainer.transform);
 132354        }
 355
 356        public void FixMaxStretchRecursively()
 357        {
 55358            UIShape rootParent = GetRootParent();
 359
 55360            Assert.IsTrue(rootParent != null, "root parent must never be null");
 361
 55362            if (rootParent.referencesContainer == null)
 1363                return;
 364
 54365            Utils.InverseTransformChildTraversal<UIReferencesContainer>(
 366                (x) =>
 367                {
 138368                    if (x.owner != null)
 369                    {
 96370                        x.rectTransform.SetToMaxStretch();
 371                    }
 138372                },
 373                rootParent.referencesContainer.transform);
 54374        }
 375
 376        protected bool ReparentComponent(RectTransform targetTransform, string targetParent)
 377        {
 68378            bool targetParentExists = !string.IsNullOrEmpty(targetParent) &&
 379                                      scene.disposableComponents.ContainsKey(targetParent);
 380
 68381            if (targetParentExists && parentUIComponent == scene.disposableComponents[targetParent])
 382            {
 22383                return false;
 384            }
 385
 46386            if (parentUIComponent != null)
 387            {
 46388                UIReferencesContainer[] parents = referencesContainer.GetComponentsInParent<UIReferencesContainer>(true)
 389
 186390                foreach (var parent in parents)
 391                {
 47392                    if (parent.owner != null)
 393                    {
 47394                        parent.owner.OnChildDetached(parentUIComponent, this);
 395                    }
 396                }
 397            }
 398
 46399            if (targetParentExists)
 400            {
 22401                parentUIComponent = scene.disposableComponents[targetParent] as UIShape;
 22402            }
 403            else
 404            {
 24405                parentUIComponent = scene.GetSharedComponent<UIScreenSpace>();
 406            }
 407
 46408            targetTransform.SetParent(parentUIComponent.childHookRectTransform, false);
 46409            return true;
 410        }
 411
 412        public UIShape GetRootParent()
 413        {
 288414            UIShape parent = null;
 415
 288416            if (parentUIComponent != null && !(parentUIComponent is UIScreenSpace))
 417            {
 6418                parent = parentUIComponent.GetRootParent();
 6419            }
 420            else
 421            {
 282422                parent = this;
 423            }
 424
 288425            return parent;
 426        }
 427
 428        protected void ConfigureAlignment(LayoutGroup layout)
 429        {
 266430            Model model = (Model) this.model;
 266431            switch (model.vAlign)
 432            {
 433                case "top":
 7434                    switch (model.hAlign)
 435                    {
 436                        case "left":
 2437                            layout.childAlignment = TextAnchor.UpperLeft;
 2438                            break;
 439                        case "right":
 2440                            layout.childAlignment = TextAnchor.UpperRight;
 2441                            break;
 442                        default:
 3443                            layout.childAlignment = TextAnchor.UpperCenter;
 3444                            break;
 445                    }
 446
 447                    break;
 448                case "bottom":
 26449                    switch (model.hAlign)
 450                    {
 451                        case "left":
 8452                            layout.childAlignment = TextAnchor.LowerLeft;
 8453                            break;
 454                        case "right":
 16455                            layout.childAlignment = TextAnchor.LowerRight;
 16456                            break;
 457                        default:
 2458                            layout.childAlignment = TextAnchor.LowerCenter;
 2459                            break;
 460                    }
 461
 462                    break;
 463                default: // center
 233464                    switch (model.hAlign)
 465                    {
 466                        case "left":
 2467                            layout.childAlignment = TextAnchor.MiddleLeft;
 2468                            break;
 469                        case "right":
 2470                            layout.childAlignment = TextAnchor.MiddleRight;
 2471                            break;
 472                        default:
 229473                            layout.childAlignment = TextAnchor.MiddleCenter;
 474                            break;
 475                    }
 476
 477                    break;
 478            }
 229479        }
 480
 481        protected void SetComponentDebugName()
 482        {
 146483            if (referencesContainer == null || model == null)
 484            {
 0485                return;
 486            }
 487
 146488            referencesContainer.name = componentName;
 146489        }
 490
 491        public override void Dispose()
 492        {
 56493            if (childHookRectTransform)
 23494                Utils.SafeDestroy(childHookRectTransform.gameObject);
 495
 56496            screenSize.OnChange -= OnScreenResize;
 497
 56498            if ( layoutRefreshWatcher != null )
 56499                CoroutineStarter.Stop(layoutRefreshWatcher);
 500
 56501            base.Dispose();
 56502        }
 503
 115504        public virtual void OnChildAttached(UIShape parentComponent, UIShape childComponent) { }
 505
 38506        public virtual void OnChildDetached(UIShape parentComponent, UIShape childComponent) { }
 507    }
 508}