< 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:511
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        {
 101242            if (type == Unit.PIXELS)
 91343                return value;
 44
 45            // Prevent division by zero
 9946            if (parentSize <= Mathf.Epsilon)
 047                parentSize = 1;
 48
 9949            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)
 173        {
 174            isLayoutDirty = GetRootParent() == this;
 175        }
 176
 177        public override int GetClassId() { return (int) CLASS_ID.UI_IMAGE_SHAPE; }
 178
 179        public string GetDebugName()
 180        {
 181            Model model = (Model) this.model;
 182
 183            if (string.IsNullOrEmpty(model.name))
 184            {
 185                return GetType().Name;
 186            }
 187            else
 188            {
 189                return GetType().Name + " - " + model.name;
 190            }
 191        }
 192
 193        public override IEnumerator ApplyChanges(BaseModel newJson) { return null; }
 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                // When running tests this is empty.
 247                if (!string.IsNullOrEmpty(CommonScriptableObjects.sceneID))
 248                {
 249                    if (CommonScriptableObjects.sceneID.Get() != scene.sceneData.id)
 250                        continue;
 251                }
 252
 253                RefreshAll();
 254            }
 255        }
 256
 257        public virtual void RefreshAll()
 258        {
 259            // We are not using the _Internal here because the method is overridden
 260            // by some UI shapes.
 261            RefreshDCLLayoutRecursively(refreshSize: true, refreshAlignmentAndPosition: false);
 262            FixMaxStretchRecursively();
 263            RefreshDCLLayoutRecursively_Internal(refreshSize: false, refreshAlignmentAndPosition: true);
 264            isLayoutDirty = false;
 265            OnLayoutRefresh?.Invoke();
 266            OnLayoutRefresh = null;
 267        }
 268
 269        public virtual void MarkLayoutDirty( System.Action OnRefresh = null )
 270        {
 271            UIShape rootParent = GetRootParent();
 272
 273            Assert.IsTrue(rootParent != null, "root parent must never be null");
 274
 275            if (rootParent.referencesContainer == null)
 276                return;
 277
 278            rootParent.isLayoutDirty = true;
 279
 280            if ( OnRefresh != null )
 281                rootParent.OnLayoutRefresh += OnRefresh;
 282        }
 283
 284        public void RefreshDCLLayout(bool refreshSize = true, bool refreshAlignmentAndPosition = true)
 285        {
 286            RectTransform parentRT = referencesContainer.GetComponentInParent<RectTransform>();
 287
 288            if (refreshSize)
 289            {
 290                RefreshDCLSize(parentRT);
 291            }
 292
 293            if (refreshAlignmentAndPosition)
 294            {
 295                // Alignment (Alignment uses size so we should always align AFTER resizing)
 296                RefreshDCLAlignmentAndPosition(parentRT);
 297            }
 298        }
 299
 300        protected virtual void RefreshDCLSize(RectTransform parentTransform = null)
 301        {
 302            if (parentTransform == null)
 303                parentTransform = referencesContainer.GetComponentInParent<RectTransform>();
 304
 305            Model model = (Model) this.model;
 306
 307            referencesContainer.layoutElementRT.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal,
 308                model.width.GetScaledValue(parentTransform.rect.width));
 309            referencesContainer.layoutElementRT.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical,
 310                model.height.GetScaledValue(parentTransform.rect.height));
 311        }
 312
 313        public void RefreshDCLAlignmentAndPosition(RectTransform parentTransform = null)
 314        {
 315            if (parentTransform == null)
 316                parentTransform = referencesContainer.GetComponentInParent<RectTransform>();
 317
 318            referencesContainer.layoutElement.ignoreLayout = false;
 319            ConfigureAlignment(referencesContainer.layoutGroup);
 320            Utils.ForceRebuildLayoutImmediate(parentTransform);
 321            referencesContainer.layoutElement.ignoreLayout = true;
 322
 323            Model model = (Model) this.model;
 324
 325            // Reposition
 326            Vector3 position = Vector3.zero;
 327            position.x = model.positionX.GetScaledValue(parentTransform.rect.width);
 328            position.y = model.positionY.GetScaledValue(parentTransform.rect.height);
 329
 330            position = Utils.Sanitize(position);
 331            referencesContainer.layoutElementRT.localPosition += position;
 332        }
 333
 334        public virtual void RefreshDCLLayoutRecursively(bool refreshSize = true,
 335            bool refreshAlignmentAndPosition = true)
 336        {
 337            RefreshDCLLayoutRecursively_Internal(refreshSize, refreshAlignmentAndPosition);
 338        }
 339
 340        public void RefreshDCLLayoutRecursively_Internal(bool refreshSize = true,
 341            bool refreshAlignmentAndPosition = true)
 342        {
 343            UIShape rootParent = GetRootParent();
 344
 345            Assert.IsTrue(rootParent != null, "root parent must never be null");
 346
 347            if (rootParent.referencesContainer == null)
 348                return;
 349
 350            Utils.InverseTransformChildTraversal<UIReferencesContainer>(
 351                (x) =>
 352                {
 353                    if (x.owner != null)
 354                        x.owner.RefreshDCLLayout(refreshSize, refreshAlignmentAndPosition);
 355                },
 356                rootParent.referencesContainer.transform);
 357        }
 358
 359        public void FixMaxStretchRecursively()
 360        {
 361            UIShape rootParent = GetRootParent();
 362
 363            Assert.IsTrue(rootParent != null, "root parent must never be null");
 364
 365            if (rootParent.referencesContainer == null)
 366                return;
 367
 368            Utils.InverseTransformChildTraversal<UIReferencesContainer>(
 369                (x) =>
 370                {
 371                    if (x.owner != null)
 372                    {
 373                        x.rectTransform.SetToMaxStretch();
 374                    }
 375                },
 376                rootParent.referencesContainer.transform);
 377        }
 378
 379        protected bool ReparentComponent(RectTransform targetTransform, string targetParent)
 380        {
 381            bool targetParentExists = !string.IsNullOrEmpty(targetParent) &&
 382                                      scene.disposableComponents.ContainsKey(targetParent);
 383
 384            if (targetParentExists && parentUIComponent == scene.disposableComponents[targetParent])
 385            {
 386                return false;
 387            }
 388
 389            if (parentUIComponent != null)
 390            {
 391                UIReferencesContainer[] parents = referencesContainer.GetComponentsInParent<UIReferencesContainer>(true)
 392
 393                foreach (var parent in parents)
 394                {
 395                    if (parent.owner != null)
 396                    {
 397                        parent.owner.OnChildDetached(parentUIComponent, this);
 398                    }
 399                }
 400            }
 401
 402            if (targetParentExists)
 403            {
 404                parentUIComponent = scene.disposableComponents[targetParent] as UIShape;
 405            }
 406            else
 407            {
 408                parentUIComponent = scene.GetSharedComponent<UIScreenSpace>();
 409            }
 410
 411            targetTransform.SetParent(parentUIComponent.childHookRectTransform, false);
 412            return true;
 413        }
 414
 415        public UIShape GetRootParent()
 416        {
 417            UIShape parent = null;
 418
 419            if (parentUIComponent != null && !(parentUIComponent is UIScreenSpace))
 420            {
 421                parent = parentUIComponent.GetRootParent();
 422            }
 423            else
 424            {
 425                parent = this;
 426            }
 427
 428            return parent;
 429        }
 430
 431        protected void ConfigureAlignment(LayoutGroup layout)
 432        {
 433            Model model = (Model) this.model;
 434            switch (model.vAlign)
 435            {
 436                case "top":
 437                    switch (model.hAlign)
 438                    {
 439                        case "left":
 440                            layout.childAlignment = TextAnchor.UpperLeft;
 441                            break;
 442                        case "right":
 443                            layout.childAlignment = TextAnchor.UpperRight;
 444                            break;
 445                        default:
 446                            layout.childAlignment = TextAnchor.UpperCenter;
 447                            break;
 448                    }
 449
 450                    break;
 451                case "bottom":
 452                    switch (model.hAlign)
 453                    {
 454                        case "left":
 455                            layout.childAlignment = TextAnchor.LowerLeft;
 456                            break;
 457                        case "right":
 458                            layout.childAlignment = TextAnchor.LowerRight;
 459                            break;
 460                        default:
 461                            layout.childAlignment = TextAnchor.LowerCenter;
 462                            break;
 463                    }
 464
 465                    break;
 466                default: // center
 467                    switch (model.hAlign)
 468                    {
 469                        case "left":
 470                            layout.childAlignment = TextAnchor.MiddleLeft;
 471                            break;
 472                        case "right":
 473                            layout.childAlignment = TextAnchor.MiddleRight;
 474                            break;
 475                        default:
 476                            layout.childAlignment = TextAnchor.MiddleCenter;
 477                            break;
 478                    }
 479
 480                    break;
 481            }
 482        }
 483
 484        protected void SetComponentDebugName()
 485        {
 486            if (referencesContainer == null || model == null)
 487            {
 488                return;
 489            }
 490
 491            referencesContainer.name = componentName;
 492        }
 493
 494        public override void Dispose()
 495        {
 496            if (childHookRectTransform)
 497                Utils.SafeDestroy(childHookRectTransform.gameObject);
 498
 499            screenSize.OnChange -= OnScreenResize;
 500
 501            if ( layoutRefreshWatcher != null )
 502                CoroutineStarter.Stop(layoutRefreshWatcher);
 503
 504            base.Dispose();
 505        }
 506
 507        public virtual void OnChildAttached(UIShape parentComponent, UIShape childComponent) { }
 508
 509        public virtual void OnChildDetached(UIShape parentComponent, UIShape childComponent) { }
 510    }
 511}