< Summary

Class:DCL.Components.UIShape[ReferencesContainerType,ModelType]
Assembly:MainScripts
File(s):/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/Components/UI/UIShape.cs
Covered lines:28
Uncovered lines:1
Coverable lines:29
Total lines:455
Line coverage:96.5% (28 of 29)
Covered branches:0
Total branches:0

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity NPath complexity Sequence coverage
UIShape()0%110100%
CreateUpdateHandler()0%110100%
PreApplyChanges(...)0%330100%
RaiseOnAppliedChanges()0%10100100%

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    {
 15457        public UIShape() { }
 58
 459        new public ModelType model { get { return base.model as ModelType; } set { base.model = value; } }
 60
 061        new public ReferencesContainerType referencesContainer { get { return base.referencesContainer as ReferencesCont
 62
 7763        public override ComponentUpdateHandler CreateUpdateHandler() { return new UIShapeUpdateHandler<ReferencesContain
 64
 65        bool raiseOnAttached;
 66        bool firstApplyChangesCall;
 67
 68        /// <summary>
 69        /// This is called by UIShapeUpdateHandler before calling ApplyChanges.
 70        /// </summary>
 71        public void PreApplyChanges(BaseModel newModel)
 72        {
 14573            model = (ModelType) newModel;
 74
 14575            raiseOnAttached = false;
 14576            firstApplyChangesCall = false;
 77
 14578            if (referencesContainer == null)
 79            {
 7780                referencesContainer = InstantiateUIGameObject<ReferencesContainerType>(referencesContainerPrefabName);
 81
 7782                raiseOnAttached = true;
 7783                firstApplyChangesCall = true;
 7784            }
 6885            else if (ReparentComponent(referencesContainer.rectTransform, model.parentComponent))
 86            {
 4687                raiseOnAttached = true;
 88            }
 6889        }
 90
 91        public override void RaiseOnAppliedChanges()
 92        {
 14593            RefreshDCLLayout();
 94
 95#if UNITY_EDITOR
 14596            SetComponentDebugName();
 97#endif
 98
 99            // We hide the component visibility when it's created (first applychanges)
 100            // as it has default values and appears in the middle of the screen
 145101            if (firstApplyChangesCall)
 77102                referencesContainer.canvasGroup.alpha = 0f;
 103            else
 68104                referencesContainer.canvasGroup.alpha = model.visible ? model.opacity : 0f;
 105
 145106            referencesContainer.canvasGroup.blocksRaycasts = model.visible && model.isPointerBlocker;
 107
 145108            base.RaiseOnAppliedChanges();
 109
 145110            if (raiseOnAttached && parentUIComponent != null)
 111            {
 123112                UIReferencesContainer[] parents = referencesContainer.GetComponentsInParent<UIReferencesContainer>(true)
 113
 570114                for (int i = 0; i < parents.Length; i++)
 115                {
 162116                    UIReferencesContainer parent = parents[i];
 162117                    if (parent.owner != null)
 118                    {
 159119                        parent.owner.OnChildAttached(parentUIComponent, this);
 120                    }
 121                }
 122            }
 145123        }
 124    }
 125
 126    public class UIShape : BaseDisposable
 127    {
 128        [System.Serializable]
 129        public class Model : BaseModel
 130        {
 131            public string name;
 132            public string parentComponent;
 133            public bool visible = true;
 134            public float opacity = 1f;
 135            public string hAlign = "center";
 136            public string vAlign = "center";
 137            public UIValue width = new UIValue(100f);
 138            public UIValue height = new UIValue(50f);
 139            public UIValue positionX = new UIValue(0f);
 140            public UIValue positionY = new UIValue(0f);
 141            public bool isPointerBlocker = true;
 142            public string onClick;
 143
 144            public override BaseModel GetDataFromJSON(string json) { return Utils.SafeFromJson<Model>(json); }
 145        }
 146
 147        public override string componentName => GetDebugName();
 148        public virtual string referencesContainerPrefabName => "";
 149        public UIReferencesContainer referencesContainer;
 150        public RectTransform childHookRectTransform;
 151
 152        private BaseVariable<Vector2Int> screenSize => DataStore.i.screen.size;
 153
 154        public UIShape parentUIComponent { get; protected set; }
 155
 156        public UIShape()
 157        {
 158            screenSize.OnChange += OnScreenResize;
 159            model = new Model();
 160        }
 161
 162        private void OnScreenResize(Vector2Int current, Vector2Int previous) => RefreshAll();
 163
 164        public override int GetClassId() { return (int) CLASS_ID.UI_IMAGE_SHAPE; }
 165
 166        public string GetDebugName()
 167        {
 168            Model model = (Model) this.model;
 169            if (string.IsNullOrEmpty(model.name))
 170            {
 171                return GetType().Name;
 172            }
 173            else
 174            {
 175                return GetType().Name + " - " + model.name;
 176            }
 177        }
 178
 179        public override IEnumerator ApplyChanges(BaseModel newJson) { return null; }
 180
 181        internal T InstantiateUIGameObject<T>(string prefabPath) where T : UIReferencesContainer
 182        {
 183            Model model = (Model) this.model;
 184            GameObject uiGameObject = null;
 185            bool targetParentExists = !string.IsNullOrEmpty(model.parentComponent) &&
 186                                      scene.disposableComponents.ContainsKey(model.parentComponent);
 187
 188            if (targetParentExists)
 189            {
 190                if (scene.disposableComponents.ContainsKey(model.parentComponent))
 191                {
 192                    parentUIComponent = (scene.disposableComponents[model.parentComponent] as UIShape);
 193                }
 194                else
 195                {
 196                    parentUIComponent = scene.GetSharedComponent<UIScreenSpace>();
 197                }
 198            }
 199            else
 200            {
 201                parentUIComponent = scene.GetSharedComponent<UIScreenSpace>();
 202            }
 203
 204            uiGameObject =
 205                UnityEngine.Object.Instantiate(
 206                    Resources.Load(prefabPath),
 207                    parentUIComponent != null ? parentUIComponent.childHookRectTransform : null) as GameObject;
 208            referencesContainer = uiGameObject.GetComponent<T>();
 209
 210            referencesContainer.rectTransform.SetToMaxStretch();
 211
 212            childHookRectTransform = referencesContainer.childHookRectTransform;
 213
 214            referencesContainer.owner = this;
 215
 216            return referencesContainer as T;
 217        }
 218
 219        public virtual void RefreshAll()
 220        {
 221            RefreshDCLLayoutRecursively(refreshSize: true, refreshAlignmentAndPosition: false);
 222            FixMaxStretchRecursively();
 223            RefreshDCLLayoutRecursively_Internal(refreshSize: false, refreshAlignmentAndPosition: true);
 224        }
 225
 226        public void RefreshDCLLayout(bool refreshSize = true, bool refreshAlignmentAndPosition = true)
 227        {
 228            RectTransform parentRT = referencesContainer.GetComponentInParent<RectTransform>();
 229
 230            if (refreshSize)
 231            {
 232                RefreshDCLSize(parentRT);
 233            }
 234
 235            if (refreshAlignmentAndPosition)
 236            {
 237                // Alignment (Alignment uses size so we should always align AFTER resizing)
 238                RefreshDCLAlignmentAndPosition(parentRT);
 239            }
 240        }
 241
 242        protected virtual void RefreshDCLSize(RectTransform parentTransform = null)
 243        {
 244            if (parentTransform == null)
 245            {
 246                parentTransform = referencesContainer.GetComponentInParent<RectTransform>();
 247            }
 248
 249            Model model = (Model) this.model;
 250
 251            referencesContainer.layoutElementRT.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal,
 252                model.width.GetScaledValue(parentTransform.rect.width));
 253            referencesContainer.layoutElementRT.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical,
 254                model.height.GetScaledValue(parentTransform.rect.height));
 255        }
 256
 257        public void RefreshDCLAlignmentAndPosition(RectTransform parentTransform = null)
 258        {
 259            if (parentTransform == null)
 260            {
 261                parentTransform = referencesContainer.GetComponentInParent<RectTransform>();
 262            }
 263
 264            referencesContainer.layoutElement.ignoreLayout = false;
 265            ConfigureAlignment(referencesContainer.layoutGroup);
 266            Utils.ForceRebuildLayoutImmediate(parentTransform);
 267            referencesContainer.layoutElement.ignoreLayout = true;
 268
 269            Model model = (Model) this.model;
 270            // Reposition
 271            Vector3 position = Vector3.zero;
 272            position.x = model.positionX.GetScaledValue(parentTransform.rect.width);
 273            position.y = model.positionY.GetScaledValue(parentTransform.rect.height);
 274
 275            position = Utils.Sanitize(position);
 276            referencesContainer.layoutElementRT.localPosition += position;
 277        }
 278
 279        public virtual void RefreshDCLLayoutRecursively(bool refreshSize = true,
 280            bool refreshAlignmentAndPosition = true)
 281        {
 282            RefreshDCLLayoutRecursively_Internal(refreshSize, refreshAlignmentAndPosition);
 283        }
 284
 285        public void RefreshDCLLayoutRecursively_Internal(bool refreshSize = true,
 286            bool refreshAlignmentAndPosition = true)
 287        {
 288            UIShape rootParent = GetRootParent();
 289
 290            Assert.IsTrue(rootParent != null, "root parent must never be null");
 291
 292            if (rootParent.referencesContainer == null)
 293                return;
 294
 295            Utils.InverseTransformChildTraversal<UIReferencesContainer>(
 296                (x) =>
 297                {
 298                    if (x.owner != null)
 299                    {
 300                        x.owner.RefreshDCLLayout(refreshSize, refreshAlignmentAndPosition);
 301                    }
 302                },
 303                rootParent.referencesContainer.transform);
 304        }
 305
 306        public void FixMaxStretchRecursively()
 307        {
 308            UIShape rootParent = GetRootParent();
 309
 310            Assert.IsTrue(rootParent != null, "root parent must never be null");
 311
 312            if (rootParent.referencesContainer == null)
 313                return;
 314
 315            Utils.InverseTransformChildTraversal<UIReferencesContainer>(
 316                (x) =>
 317                {
 318                    if (x.owner != null)
 319                    {
 320                        x.rectTransform.SetToMaxStretch();
 321                    }
 322                },
 323                rootParent.referencesContainer.transform);
 324        }
 325
 326        protected bool ReparentComponent(RectTransform targetTransform, string targetParent)
 327        {
 328            bool targetParentExists = !string.IsNullOrEmpty(targetParent) &&
 329                                      scene.disposableComponents.ContainsKey(targetParent);
 330
 331            if (targetParentExists && parentUIComponent == scene.disposableComponents[targetParent])
 332            {
 333                return false;
 334            }
 335
 336            if (parentUIComponent != null)
 337            {
 338                UIReferencesContainer[] parents = referencesContainer.GetComponentsInParent<UIReferencesContainer>(true)
 339
 340                foreach (var parent in parents)
 341                {
 342                    if (parent.owner != null)
 343                    {
 344                        parent.owner.OnChildDetached(parentUIComponent, this);
 345                    }
 346                }
 347            }
 348
 349            if (targetParentExists)
 350            {
 351                parentUIComponent = scene.disposableComponents[targetParent] as UIShape;
 352            }
 353            else
 354            {
 355                parentUIComponent = scene.GetSharedComponent<UIScreenSpace>();
 356            }
 357
 358            targetTransform.SetParent(parentUIComponent.childHookRectTransform, false);
 359            return true;
 360        }
 361
 362        public UIShape GetRootParent()
 363        {
 364            UIShape parent = null;
 365
 366            if (parentUIComponent != null && !(parentUIComponent is UIScreenSpace))
 367            {
 368                parent = parentUIComponent.GetRootParent();
 369            }
 370            else
 371            {
 372                parent = this;
 373            }
 374
 375            return parent;
 376        }
 377
 378        protected void ConfigureAlignment(LayoutGroup layout)
 379        {
 380            Model model = (Model) this.model;
 381            switch (model.vAlign)
 382            {
 383                case "top":
 384                    switch (model.hAlign)
 385                    {
 386                        case "left":
 387                            layout.childAlignment = TextAnchor.UpperLeft;
 388                            break;
 389                        case "right":
 390                            layout.childAlignment = TextAnchor.UpperRight;
 391                            break;
 392                        default:
 393                            layout.childAlignment = TextAnchor.UpperCenter;
 394                            break;
 395                    }
 396
 397                    break;
 398                case "bottom":
 399                    switch (model.hAlign)
 400                    {
 401                        case "left":
 402                            layout.childAlignment = TextAnchor.LowerLeft;
 403                            break;
 404                        case "right":
 405                            layout.childAlignment = TextAnchor.LowerRight;
 406                            break;
 407                        default:
 408                            layout.childAlignment = TextAnchor.LowerCenter;
 409                            break;
 410                    }
 411
 412                    break;
 413                default: // center
 414                    switch (model.hAlign)
 415                    {
 416                        case "left":
 417                            layout.childAlignment = TextAnchor.MiddleLeft;
 418                            break;
 419                        case "right":
 420                            layout.childAlignment = TextAnchor.MiddleRight;
 421                            break;
 422                        default:
 423                            layout.childAlignment = TextAnchor.MiddleCenter;
 424                            break;
 425                    }
 426
 427                    break;
 428            }
 429        }
 430
 431        protected void SetComponentDebugName()
 432        {
 433            if (referencesContainer == null || model == null)
 434            {
 435                return;
 436            }
 437
 438            referencesContainer.name = componentName;
 439        }
 440
 441        public override void Dispose()
 442        {
 443            if (childHookRectTransform)
 444                Utils.SafeDestroy(childHookRectTransform.gameObject);
 445
 446            screenSize.OnChange -= OnScreenResize;
 447
 448            base.Dispose();
 449        }
 450
 451        public virtual void OnChildAttached(UIShape parentComponent, UIShape childComponent) { }
 452
 453        public virtual void OnChildDetached(UIShape parentComponent, UIShape childComponent) { }
 454    }
 455}