< Summary

Class:DCL.Components.UIValue
Assembly:MainScripts
File(s):/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/Components/UI/UIShape.cs
Covered lines:4
Uncovered lines:10
Coverable lines:14
Total lines:504
Line coverage:28.5% (4 of 14)
Covered branches:0
Total branches:0

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity NPath complexity Sequence coverage
SetPixels(...)0%2100%
SetPercent(...)0%2100%
UIValue(...)0%2100%
GetScaledValue(...)0%3.073080%

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        {
 024            this.type = Unit.PIXELS;
 025            this.value = value;
 026        }
 27
 28        public void SetPercent(float value)
 29        {
 030            this.type = Unit.PERCENT;
 031            this.value = value;
 032        }
 33
 34        public UIValue(float value, Unit unitType = Unit.PIXELS)
 35        {
 036            this.value = value;
 037            this.type = unitType;
 038        }
 39
 40        public float GetScaledValue(float parentSize)
 41        {
 102042            if (type == Unit.PIXELS)
 91943                return value;
 44
 45            // Prevent division by zero
 10146            if (parentSize <= Mathf.Epsilon)
 047                parentSize = 1;
 48
 10149            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;
 135            public bool visible = true;
 136            public float opacity = 1f;
 137            public string hAlign = "center";
 138            public string vAlign = "center";
 139            public UIValue width = new UIValue(100f);
 140            public UIValue height = new UIValue(50f);
 141            public UIValue positionX = new UIValue(0f);
 142            public UIValue positionY = new UIValue(0f);
 143            public bool isPointerBlocker = true;
 144            public string onClick;
 145
 146            public override BaseModel GetDataFromJSON(string json) { return Utils.SafeFromJson<Model>(json); }
 147        }
 148
 149        public override string componentName => GetDebugName();
 150        public virtual string referencesContainerPrefabName => "";
 151        public UIReferencesContainer referencesContainer;
 152        public RectTransform childHookRectTransform;
 153
 154        public bool isLayoutDirty { get; protected set; }
 155        protected System.Action OnLayoutRefresh;
 156
 157        private BaseVariable<Vector2Int> screenSize => DataStore.i.screen.size;
 158
 159        public UIShape parentUIComponent { get; protected set; }
 160
 161        private Coroutine layoutRefreshWatcher;
 162
 163        public UIShape()
 164        {
 165            screenSize.OnChange += OnScreenResize;
 166            model = new Model();
 167
 168            if ( layoutRefreshWatcher == null )
 169                layoutRefreshWatcher = CoroutineStarter.Start(LayoutRefreshWatcher());
 170        }
 171
 172        private void OnScreenResize(Vector2Int current, Vector2Int previous) => RefreshAll();
 173
 174        public override int GetClassId() { return (int) CLASS_ID.UI_IMAGE_SHAPE; }
 175
 176        public string GetDebugName()
 177        {
 178            Model model = (Model) this.model;
 179
 180            if (string.IsNullOrEmpty(model.name))
 181            {
 182                return GetType().Name;
 183            }
 184            else
 185            {
 186                return GetType().Name + " - " + model.name;
 187            }
 188        }
 189
 190        public override IEnumerator ApplyChanges(BaseModel newJson)
 191        {
 192            return null;
 193        }
 194
 195        internal T InstantiateUIGameObject<T>(string prefabPath) where T : UIReferencesContainer
 196        {
 197            Model model = (Model) this.model;
 198
 199            GameObject uiGameObject = null;
 200
 201            bool targetParentExists = !string.IsNullOrEmpty(model.parentComponent) &&
 202                                      scene.disposableComponents.ContainsKey(model.parentComponent);
 203
 204            if (targetParentExists)
 205            {
 206                if (scene.disposableComponents.ContainsKey(model.parentComponent))
 207                {
 208                    parentUIComponent = (scene.disposableComponents[model.parentComponent] as UIShape);
 209                }
 210                else
 211                {
 212                    parentUIComponent = scene.GetSharedComponent<UIScreenSpace>();
 213                }
 214            }
 215            else
 216            {
 217                parentUIComponent = scene.GetSharedComponent<UIScreenSpace>();
 218            }
 219
 220            uiGameObject =
 221                Object.Instantiate(
 222                    Resources.Load(prefabPath),
 223                    parentUIComponent != null ? parentUIComponent.childHookRectTransform : null) as GameObject;
 224
 225            referencesContainer = uiGameObject.GetComponent<T>();
 226
 227            referencesContainer.rectTransform.SetToMaxStretch();
 228
 229            childHookRectTransform = referencesContainer.childHookRectTransform;
 230
 231            referencesContainer.owner = this;
 232
 233            return referencesContainer as T;
 234        }
 235
 236        IEnumerator LayoutRefreshWatcher()
 237        {
 238            while (true)
 239            {
 240                // WaitForEndOfFrame doesn't work in batch mode
 241                yield return Application.isBatchMode ? null : new WaitForEndOfFrame();
 242
 243                if ( !isLayoutDirty )
 244                    continue;
 245
 246                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.
 254            RefreshDCLLayoutRecursively(refreshSize: true, refreshAlignmentAndPosition: false);
 255            FixMaxStretchRecursively();
 256            RefreshDCLLayoutRecursively_Internal(refreshSize: false, refreshAlignmentAndPosition: true);
 257            isLayoutDirty = false;
 258            OnLayoutRefresh?.Invoke();
 259            OnLayoutRefresh = null;
 260        }
 261
 262        public virtual void MarkLayoutDirty( System.Action OnRefresh = null )
 263        {
 264            UIShape rootParent = GetRootParent();
 265
 266            Assert.IsTrue(rootParent != null, "root parent must never be null");
 267
 268            if (rootParent.referencesContainer == null)
 269                return;
 270
 271            rootParent.isLayoutDirty = true;
 272
 273            if ( OnRefresh != null )
 274                rootParent.OnLayoutRefresh += OnRefresh;
 275        }
 276
 277        public void RefreshDCLLayout(bool refreshSize = true, bool refreshAlignmentAndPosition = true)
 278        {
 279            RectTransform parentRT = referencesContainer.GetComponentInParent<RectTransform>();
 280
 281            if (refreshSize)
 282            {
 283                RefreshDCLSize(parentRT);
 284            }
 285
 286            if (refreshAlignmentAndPosition)
 287            {
 288                // Alignment (Alignment uses size so we should always align AFTER resizing)
 289                RefreshDCLAlignmentAndPosition(parentRT);
 290            }
 291        }
 292
 293        protected virtual void RefreshDCLSize(RectTransform parentTransform = null)
 294        {
 295            if (parentTransform == null)
 296                parentTransform = referencesContainer.GetComponentInParent<RectTransform>();
 297
 298            Model model = (Model) this.model;
 299
 300            referencesContainer.layoutElementRT.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal,
 301                model.width.GetScaledValue(parentTransform.rect.width));
 302            referencesContainer.layoutElementRT.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical,
 303                model.height.GetScaledValue(parentTransform.rect.height));
 304        }
 305
 306        public void RefreshDCLAlignmentAndPosition(RectTransform parentTransform = null)
 307        {
 308            if (parentTransform == null)
 309                parentTransform = referencesContainer.GetComponentInParent<RectTransform>();
 310
 311            referencesContainer.layoutElement.ignoreLayout = false;
 312            ConfigureAlignment(referencesContainer.layoutGroup);
 313            Utils.ForceRebuildLayoutImmediate(parentTransform);
 314            referencesContainer.layoutElement.ignoreLayout = true;
 315
 316            Model model = (Model) this.model;
 317
 318            // Reposition
 319            Vector3 position = Vector3.zero;
 320            position.x = model.positionX.GetScaledValue(parentTransform.rect.width);
 321            position.y = model.positionY.GetScaledValue(parentTransform.rect.height);
 322
 323            position = Utils.Sanitize(position);
 324            referencesContainer.layoutElementRT.localPosition += position;
 325        }
 326
 327        public virtual void RefreshDCLLayoutRecursively(bool refreshSize = true,
 328            bool refreshAlignmentAndPosition = true)
 329        {
 330            RefreshDCLLayoutRecursively_Internal(refreshSize, refreshAlignmentAndPosition);
 331        }
 332
 333        public void RefreshDCLLayoutRecursively_Internal(bool refreshSize = true,
 334            bool refreshAlignmentAndPosition = true)
 335        {
 336            UIShape rootParent = GetRootParent();
 337
 338            Assert.IsTrue(rootParent != null, "root parent must never be null");
 339
 340            if (rootParent.referencesContainer == null)
 341                return;
 342
 343            Utils.InverseTransformChildTraversal<UIReferencesContainer>(
 344                (x) =>
 345                {
 346                    if (x.owner != null)
 347                        x.owner.RefreshDCLLayout(refreshSize, refreshAlignmentAndPosition);
 348                },
 349                rootParent.referencesContainer.transform);
 350        }
 351
 352        public void FixMaxStretchRecursively()
 353        {
 354            UIShape rootParent = GetRootParent();
 355
 356            Assert.IsTrue(rootParent != null, "root parent must never be null");
 357
 358            if (rootParent.referencesContainer == null)
 359                return;
 360
 361            Utils.InverseTransformChildTraversal<UIReferencesContainer>(
 362                (x) =>
 363                {
 364                    if (x.owner != null)
 365                    {
 366                        x.rectTransform.SetToMaxStretch();
 367                    }
 368                },
 369                rootParent.referencesContainer.transform);
 370        }
 371
 372        protected bool ReparentComponent(RectTransform targetTransform, string targetParent)
 373        {
 374            bool targetParentExists = !string.IsNullOrEmpty(targetParent) &&
 375                                      scene.disposableComponents.ContainsKey(targetParent);
 376
 377            if (targetParentExists && parentUIComponent == scene.disposableComponents[targetParent])
 378            {
 379                return false;
 380            }
 381
 382            if (parentUIComponent != null)
 383            {
 384                UIReferencesContainer[] parents = referencesContainer.GetComponentsInParent<UIReferencesContainer>(true)
 385
 386                foreach (var parent in parents)
 387                {
 388                    if (parent.owner != null)
 389                    {
 390                        parent.owner.OnChildDetached(parentUIComponent, this);
 391                    }
 392                }
 393            }
 394
 395            if (targetParentExists)
 396            {
 397                parentUIComponent = scene.disposableComponents[targetParent] as UIShape;
 398            }
 399            else
 400            {
 401                parentUIComponent = scene.GetSharedComponent<UIScreenSpace>();
 402            }
 403
 404            targetTransform.SetParent(parentUIComponent.childHookRectTransform, false);
 405            return true;
 406        }
 407
 408        public UIShape GetRootParent()
 409        {
 410            UIShape parent = null;
 411
 412            if (parentUIComponent != null && !(parentUIComponent is UIScreenSpace))
 413            {
 414                parent = parentUIComponent.GetRootParent();
 415            }
 416            else
 417            {
 418                parent = this;
 419            }
 420
 421            return parent;
 422        }
 423
 424        protected void ConfigureAlignment(LayoutGroup layout)
 425        {
 426            Model model = (Model) this.model;
 427            switch (model.vAlign)
 428            {
 429                case "top":
 430                    switch (model.hAlign)
 431                    {
 432                        case "left":
 433                            layout.childAlignment = TextAnchor.UpperLeft;
 434                            break;
 435                        case "right":
 436                            layout.childAlignment = TextAnchor.UpperRight;
 437                            break;
 438                        default:
 439                            layout.childAlignment = TextAnchor.UpperCenter;
 440                            break;
 441                    }
 442
 443                    break;
 444                case "bottom":
 445                    switch (model.hAlign)
 446                    {
 447                        case "left":
 448                            layout.childAlignment = TextAnchor.LowerLeft;
 449                            break;
 450                        case "right":
 451                            layout.childAlignment = TextAnchor.LowerRight;
 452                            break;
 453                        default:
 454                            layout.childAlignment = TextAnchor.LowerCenter;
 455                            break;
 456                    }
 457
 458                    break;
 459                default: // center
 460                    switch (model.hAlign)
 461                    {
 462                        case "left":
 463                            layout.childAlignment = TextAnchor.MiddleLeft;
 464                            break;
 465                        case "right":
 466                            layout.childAlignment = TextAnchor.MiddleRight;
 467                            break;
 468                        default:
 469                            layout.childAlignment = TextAnchor.MiddleCenter;
 470                            break;
 471                    }
 472
 473                    break;
 474            }
 475        }
 476
 477        protected void SetComponentDebugName()
 478        {
 479            if (referencesContainer == null || model == null)
 480            {
 481                return;
 482            }
 483
 484            referencesContainer.name = componentName;
 485        }
 486
 487        public override void Dispose()
 488        {
 489            if (childHookRectTransform)
 490                Utils.SafeDestroy(childHookRectTransform.gameObject);
 491
 492            screenSize.OnChange -= OnScreenResize;
 493
 494            if ( layoutRefreshWatcher != null )
 495                CoroutineStarter.Stop(layoutRefreshWatcher);
 496
 497            base.Dispose();
 498        }
 499
 500        public virtual void OnChildAttached(UIShape parentComponent, UIShape childComponent) { }
 501
 502        public virtual void OnChildDetached(UIShape parentComponent, UIShape childComponent) { }
 503    }
 504}