/* Copyright (c) 2019 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.ComponentModel; using Tizen.NUI.BaseComponents; using System.Runtime.InteropServices; using System.Diagnostics; using Tizen.NUI.Binding; namespace Tizen.NUI { /// /// This class implements a flex layout. /// The flex layout implementation is based on open source Facebook Yoga layout engine. /// For more information about the flex layout API and how to use it please refer to https://yogalayout.com/docs/ /// We implement the subset of the API in the class below. /// public class FlexLayout : LayoutGroup, global::System.IDisposable { /// /// FlexItemProperty /// [EditorBrowsable(EditorBrowsableState.Never)] internal static readonly BindableProperty FlexItemProperty = BindableProperty.CreateAttached("FlexItem", typeof(HandleRef), typeof(FlexLayout), default(HandleRef)); /// /// FlexAlignmentSelfProperty /// [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty FlexAlignmentSelfProperty = BindableProperty.CreateAttached("FlexAlignmentSelf", typeof(AlignmentType), typeof(FlexLayout), AlignmentType.Auto, propertyChanged: OnChildPropertyChanged); /// /// FlexPositionTypeProperty /// [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty FlexPositionTypeProperty = BindableProperty.CreateAttached("FlexPositionType", typeof(PositionType), typeof(FlexLayout), PositionType.Relative, propertyChanged: OnChildPropertyChanged); /// /// AspectRatioProperty /// [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty FlexAspectRatioProperty = BindableProperty.CreateAttached("FlexAspectRatio", typeof(float), typeof(FlexLayout), FlexUndefined, validateValue: (bindable, value) => (float)value > 0, propertyChanged: OnChildPropertyChanged); /// /// FlexBasisProperty /// [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty FlexBasisProperty = BindableProperty.CreateAttached("FlexBasis", typeof(float), typeof(FlexLayout), FlexUndefined, validateValue: (bindable, value) => (float)value >= 0, propertyChanged: OnChildPropertyChanged); /// /// FlexShrinkProperty /// [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty FlexShrinkProperty = BindableProperty.CreateAttached("FlexShrink", typeof(float), typeof(FlexLayout), 1.0f, validateValue: (bindable, value) => (float)value >= 0, propertyChanged: OnChildPropertyChanged); /// /// FlexGrowProperty /// [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty FlexGrowProperty = BindableProperty.CreateAttached("FlexGrow", typeof(float), typeof(FlexLayout), FlexUndefined, validateValue: (bindable, value) => (float)value >= 0, propertyChanged: OnChildPropertyChanged); private static bool LayoutDebugFlex = false; // Debug flag private global::System.Runtime.InteropServices.HandleRef swigCPtr; private bool swigCMemOwn; private bool disposed; private bool isDisposeQueued = false; private MeasureSpecification parentMeasureSpecificationWidth; private MeasureSpecification parentMeasureSpecificationHeight; private IntPtr _rootFlex; // Pointer to the unmanged flex layout class. internal const float FlexUndefined = 10E20F; // Auto setting which is equivalent to WrapContent. internal struct MeasuredSize { public MeasuredSize(float x, float y) { width = x; height = y; } public float width; public float height; }; /// /// Gets the alignment self of the child view. /// /// /// The child view. /// The value of alignment self. /// 8 public static AlignmentType GetFlexAlignmentSelf(View view) => GetAttachedValue(view, FlexAlignmentSelfProperty); /// /// Gets the position type of the child view. /// /// /// The child view. /// The value of position type /// 8 public static PositionType GetFlexPositionType(View view) => GetAttachedValue(view, FlexPositionTypeProperty); /// /// Gets the aspect ratio of the child view. /// /// /// The child view. /// The value of aspect ratio /// 8 public static float GetFlexAspectRatio(View view) => GetAttachedValue(view, FlexAspectRatioProperty); /// /// Gets the basis of the child view. /// /// /// The child view. /// The value of basis /// 8 public static float GetFlexBasis(View view) => GetAttachedValue(view, FlexBasisProperty); /// /// Gets the shrink of the child view. /// /// /// The child view. /// The value of shrink /// 8 public static float GetFlexShrink(View view) => GetAttachedValue(view, FlexShrinkProperty); /// /// Gets the grow of the child view. /// /// /// The child view. /// The value of grow /// 8 public static float GetFlexGrow(View view) => GetAttachedValue(view, FlexGrowProperty); /// /// Sets the alignment self of the child view.
/// Alignment self has the same options and effect as but instead of affecting the children within a container, /// you can apply this property to a single child to change its alignment within its parent.
/// Alignment self overrides any option set by the parent with . ///
/// The child view. /// The value of alignment self. /// 8 public static void SetFlexAlignmentSelf(View view, AlignmentType value) => SetAttachedValue(view, FlexAlignmentSelfProperty, value); /// /// Sets the position type of the child view.
/// The position type of an element defines how it is positioned within its parent. /// By default a child is positioned relatively. This means a child is positioned according to the normal flow of the layout, /// and then offset relative to that position based on the values of .
/// When positioned absolutely an element doesn't take part in the normal layout flow. /// It is instead laid out independent of its siblings. The position is determined based on the . ///
/// The child view. /// The value of position type. /// 8 public static void SetFlexPositionType(View view, PositionType value) => SetAttachedValue(view, FlexPositionTypeProperty, value); /// /// Sets the aspect ratio of the child view. /// Aspect ratio Defines as the ratio between the width and the height of a node /// e.g. if a node has an aspect ratio of 2 then its width is twice the size of its height.
/// Aspect ratio accepts any floating point value > 0. this has higher priority than flex grow. ///
/// The child view. /// The value of aspect ratio /// 8 public static void SetFlexAspectRatio(View view, float value) => SetAttachedValue(view, FlexAspectRatioProperty, value); /// /// Sets the flex basis of the child view. /// Flex basis is an axis-independent way of providing the default size of an item along the main axis.
/// Setting the flex basis of a child is similar to setting the width of that child if its parent is a container with /// or setting the height of a child if its parent is a container with .
/// The flex basis of an item is the default size of that item, the size of the item before any flex grow and flex shrink calculations are performed. ///
/// The child view. /// The value of basis /// 8 public static void SetFlexBasis(View view, float value) => SetAttachedValue(view, FlexBasisProperty, value); /// /// Sets the flex shrink of the child view. /// Flex shrink describes how to shrink children along the main axis in the case that the total size of the children overflow the size of the container on the main axis.
/// Flex shrink is very similar to flex grow and can be thought of in the same way if any overflowing size is considered to be negative remaining space. /// These two properties also work well together by allowing children to grow and shrink as needed.
/// Flex shrink accepts any floating point value >= 0, with 1 being the default value. A container will shrink its children weighted by the child’s flex shrink value. ///
/// The child view. /// The value of shrink /// 8 public static void SetFlexShrink(View view, float value) => SetAttachedValue(view, FlexShrinkProperty, value); /// /// Sets the grow of the child view. /// Flex grow describes how any space within a container should be distributed among its children along the main axis. /// After laying out its children, a container will distribute any remaining space according to the flex grow values specified by its children.
/// Flex grow accepts any floating point value >= 0, with 0 being the default value.
/// A container will distribute any remaining space among its children weighted by the child’s flex grow value. ///
/// The child view. /// The value of flex /// 8 public static void SetFlexGrow(View view, float value) => SetAttachedValue(view, FlexGrowProperty, value); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void ChildMeasureCallback( global::System.IntPtr child, float width, int measureModeWidth, float height, int measureModeHeight, out MeasuredSize measureSize ); event ChildMeasureCallback measureChildDelegate; // Stores a delegate to the child measure callback. Used for all children of this FlexLayout. internal FlexLayout(global::System.IntPtr cPtr, bool cMemoryOwn) { swigCMemOwn = cMemoryOwn; swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); _rootFlex = Interop.FlexLayout.FlexLayout_New(); measureChildDelegate = new ChildMeasureCallback(measureChild); } internal static global::System.Runtime.InteropServices.HandleRef getCPtr(FlexLayout obj) { return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } /// /// 6 public void Dispose() { // Throw exception if Dispose() is called in separate thread. if (!Window.IsInstalled()) { throw new System.InvalidOperationException("This API called from separate thread. This API must be called from MainThread."); } if (isDisposeQueued) { Dispose(DisposeTypes.Implicit); } else { Dispose(DisposeTypes.Explicit); System.GC.SuppressFinalize(this); } } /// /// 6 protected virtual void Dispose(DisposeTypes type) { if (disposed) { return; } if (type == DisposeTypes.Explicit) { // Called by User // Release your own managed resources here. // You should release all of your own disposable objects here. } // Release your own unmanaged resources here. // You should not access any managed member here except static instance. // because the execution order of Finalizes is non-deterministic. if (swigCPtr.Handle != global::System.IntPtr.Zero) { if (swigCMemOwn) { swigCMemOwn = false; Interop.FlexLayout.delete_FlexLayout(swigCPtr); } swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); } disposed = true; } /// /// Creates a FlexLayout object. /// /// 6 public FlexLayout() : this(Interop.FlexLayout.FlexLayout_New(), true) { if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } internal static FlexLayout DownCast(BaseHandle handle) { FlexLayout ret = new FlexLayout(Interop.FlexLayout.FlexLayout_DownCast(BaseHandle.getCPtr(handle)), true); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal FlexLayout(FlexLayout other) : this(Interop.FlexLayout.new_FlexLayout__SWIG_1(FlexLayout.getCPtr(other)), true) { if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } internal FlexLayout.AlignmentType GetFlexAlignment() { FlexLayout.AlignmentType ret = (FlexLayout.AlignmentType)Interop.FlexLayout.FlexLayout_GetFlexAlignment(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal FlexLayout.AlignmentType GetFlexItemsAlignment() { FlexLayout.AlignmentType ret = (FlexLayout.AlignmentType)Interop.FlexLayout.FlexLayout_GetFlexItemsAlignment(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// /// Gets/Sets the flex direction in the layout. /// The direction of the main-axis which determines the direction that flex items are laid out. /// /// 6 public FlexDirection Direction { get => (FlexDirection)Interop.FlexLayout.FlexLayout_GetFlexDirection(swigCPtr); set { Interop.FlexLayout.FlexLayout_SetFlexDirection(swigCPtr, (int)value); RequestLayout(); } } /// /// Gets/Sets the justification in the layout. /// Justify content describes how to align children within the main axis of their container.
/// For example, you can use this property to center a child horizontally within a container with set to /// or vertically within a container with set to . ///
/// 6 public FlexJustification Justification { get => (FlexJustification)Interop.FlexLayout.FlexLayout_GetFlexJustification(swigCPtr); set { Interop.FlexLayout.FlexLayout_SetFlexJustification(swigCPtr, (int)value); RequestLayout(); } } /// /// Gets/Sets the wrap in the layout. /// The flex wrap property is set on containers and controls what happens when children overflow the size of the container along the main axis.
/// By default children are forced into a single line (which can shrink elements).
/// If wrapping is allowed items are wrapped into multiple lines along the main axis if needed. wrap reverse behaves the same, but the order of the lines is reversed.
/// When wrapping lines can be used to specify how the lines are placed in the container. ///
/// 6 public FlexWrapType WrapType { get => (FlexWrapType)Interop.FlexLayout.FlexLayout_GetFlexWrap(swigCPtr); set { Interop.FlexLayout.FlexLayout_SetFlexWrap(swigCPtr, (int)value); RequestLayout(); } } /// /// Gets/Sets the alignment of the layout content. /// Alignment defines the distribution of lines along the cross-axis.
/// This only has effect when items are wrapped to multiple lines using flex wrap. ///
/// 6 public AlignmentType Alignment { get => GetFlexAlignment(); set { Interop.FlexLayout.FlexLayout_SetFlexAlignment(swigCPtr, (int)value); RequestLayout(); } } /// /// Gets/Sets the alignment of the layout items. /// Items alignment describes how to align children along the cross axis of their container.
/// Align items is very similar to but instead of applying to the main axis, align items applies to the cross axis. ///
/// 6 public AlignmentType ItemsAlignment { get => GetFlexItemsAlignment(); set { Interop.FlexLayout.FlexLayout_SetFlexItemsAlignment(swigCPtr, (int)value); RequestLayout(); } } /// /// Enumeration for the direction of the main axis in the flex container. /// This determines the direction that flex items are laid out in the flex container. /// /// 6 public enum FlexDirection { /// /// The flexible items are displayed vertically as a column /// Column, /// /// The flexible items are displayed vertically as a column, but in reverse order /// ColumnReverse, /// /// The flexible items are displayed horizontally as a row /// Row, /// /// The flexible items are displayed horizontally as a row, but in reverse order /// RowReverse } /// /// Enumeration for the alignment of the flex items when the items do not use all available space on the main-axis. /// /// 6 public enum FlexJustification { /// /// Items are positioned at the beginning of the container. /// FlexStart, /// /// Items are positioned at the center of the container. /// Center, /// /// Items are positioned at the end of the container. /// FlexEnd, /// /// Items are positioned with equal space between the lines. /// SpaceBetween, /// /// Items are positioned with equal space before, between, and after the lines.
/// Compared to using /// will result in space being distributed to the beginning of the first child and end of the last child. ///
SpaceAround } /// /// Enumeration for the wrap type of the flex container when there is no enough room for all the items on one flex line. /// /// 6 public enum FlexWrapType { /// /// Flex items laid out in single line (shrunk to fit the flex container along the main axis) /// NoWrap, /// /// Flex items laid out in multiple lines if needed /// Wrap } /// /// Enumeration for the alignment of the flex items or lines when the items or lines do not use all the available space on the cross-axis. /// /// 6 public enum AlignmentType { /// /// Inherits the same alignment from the parent /// Auto, /// /// At the beginning of the container /// FlexStart, /// /// At the center of the container /// Center, /// /// At the end of the container /// FlexEnd, /// /// Stretch to fit the container /// Stretch } /// /// Enumeration for the position type of the flex item how it is positioned within its parent. /// /// 8 public enum PositionType { /// /// Flex items laid out relatively. /// Relative, /// /// Flex items laid out absolutely. /// Absolute } private void measureChild(global::System.IntPtr childPtr, float width, int measureModeWidth, float height, int measureModeHeight, out MeasuredSize measureSize) { // We need to measure child layout View child = Registry.GetManagedBaseHandleFromNativePtr(childPtr) as View; LayoutItem childLayout = child.Layout; MeasureSpecification childWidthMeasureSpec = GetChildMeasureSpecification( new MeasureSpecification( new LayoutLength(parentMeasureSpecificationWidth.Size - (child.Margin.Start + child.Margin.End)), parentMeasureSpecificationWidth.Mode), new LayoutLength(Padding.Start + Padding.End), new LayoutLength(child.WidthSpecification)); MeasureSpecification childHeightMeasureSpec = GetChildMeasureSpecification( new MeasureSpecification( new LayoutLength(parentMeasureSpecificationHeight.Size - (child.Margin.Top + child.Margin.Bottom)), parentMeasureSpecificationHeight.Mode), new LayoutLength(Padding.Top + Padding.Bottom), new LayoutLength(child.HeightSpecification)); childLayout.Measure(childWidthMeasureSpec, childHeightMeasureSpec); measureSize.width = childLayout.MeasuredWidth.Size.AsRoundedValue(); measureSize.height = childLayout.MeasuredHeight.Size.AsRoundedValue(); } void InsertChild(LayoutItem child) { // Store created node for child IntPtr childPtr = Interop.FlexLayout.FlexLayout_AddChildWithMargin(swigCPtr, View.getCPtr(child.Owner), Extents.getCPtr(child.Owner.Margin), measureChildDelegate, LayoutChildren.Count - 1); HandleRef childHandleRef = new HandleRef(child.Owner, childPtr); SetAttachedValue(child.Owner, FlexItemProperty, childHandleRef); } /// /// Callback when child is added to container.
/// Derived classes can use this to set their own child properties on the child layout's owner.
///
/// The Layout child. /// 6 protected override void OnChildAdd(LayoutItem child) { InsertChild(child); } /// /// Callback when child is removed from container.
///
/// The Layout child. /// 6 protected override void OnChildRemove(LayoutItem child) { // When child View is removed from it's parent View (that is a Layout) then remove it from the layout too. // FlexLayout refers to the child as a View not LayoutItem. Interop.FlexLayout.FlexLayout_RemoveChild(swigCPtr, child); } /// /// Measure the layout and its content to determine the measured width and the measured height.
///
/// horizontal space requirements as imposed by the parent. /// vertical space requirements as imposed by the parent. /// 6 protected override void OnMeasure(MeasureSpecification widthMeasureSpec, MeasureSpecification heightMeasureSpec) { bool isLayoutRtl = Owner.LayoutDirection == ViewLayoutDirectionType.RTL; Extents padding = Owner.Padding; Extents margin = Owner.Margin; Interop.FlexLayout.FlexLayout_SetMargin(swigCPtr, Extents.getCPtr(margin)); Interop.FlexLayout.FlexLayout_SetPadding(swigCPtr, Extents.getCPtr(padding)); float width = FlexUndefined; // Behaves as WrapContent (Flex Auto) float height = FlexUndefined; // Behaves as WrapContent (Flex Auto) if (widthMeasureSpec.Mode == MeasureSpecification.ModeType.Exactly || widthMeasureSpec.Mode == MeasureSpecification.ModeType.AtMost) { width = widthMeasureSpec.Size.AsDecimal(); } if (heightMeasureSpec.Mode == MeasureSpecification.ModeType.Exactly || heightMeasureSpec.Mode == MeasureSpecification.ModeType.AtMost) { height = heightMeasureSpec.Size.AsDecimal(); } // Save measureSpec to measure children. // In other Layout, we can pass it as parameter to measuring child but in FlexLayout we can't // because measurChild function is called by native callback. parentMeasureSpecificationWidth = widthMeasureSpec; parentMeasureSpecificationHeight = heightMeasureSpec; // Assign child properties for (int i = 0; i < LayoutChildren.Count; i++) { LayoutItem layoutItem = LayoutChildren[i]; View Child = layoutItem?.Owner; HandleRef childHandleRef = (HandleRef)Child.GetValue(FlexItemProperty); if (childHandleRef.Handle == IntPtr.Zero || Child == null) continue; AlignmentType flexAlignemnt = GetFlexAlignmentSelf(Child); PositionType flexPosition = GetFlexPositionType(Child); float flexAspectRatio = GetFlexAspectRatio(Child); float flexBasis = GetFlexBasis(Child); float flexShrink = GetFlexShrink(Child); float flexGrow = GetFlexGrow(Child); Interop.FlexLayout.FlexLayout_SetFlexAlignmentSelf(childHandleRef, (int)flexAlignemnt); Interop.FlexLayout.FlexLayout_SetFlexPositionType(childHandleRef, (int)flexPosition); Interop.FlexLayout.FlexLayout_SetFlexAspectRatio(childHandleRef, flexAspectRatio); Interop.FlexLayout.FlexLayout_SetFlexBasis(childHandleRef, flexBasis); Interop.FlexLayout.FlexLayout_SetFlexShrink(childHandleRef, flexShrink); Interop.FlexLayout.FlexLayout_SetFlexGrow(childHandleRef, flexGrow); } Interop.FlexLayout.FlexLayout_CalculateLayout(swigCPtr, width, height, isLayoutRtl); LayoutLength flexLayoutWidth = new LayoutLength(Interop.FlexLayout.FlexLayout_GetWidth(swigCPtr)); LayoutLength flexLayoutHeight = new LayoutLength(Interop.FlexLayout.FlexLayout_GetHeight(swigCPtr)); Debug.WriteLineIf(LayoutDebugFlex, "FlexLayout OnMeasure width:" + flexLayoutWidth.AsRoundedValue() + " height:" + flexLayoutHeight.AsRoundedValue()); SetMeasuredDimensions(GetDefaultSize(flexLayoutWidth, widthMeasureSpec), GetDefaultSize(flexLayoutHeight, heightMeasureSpec)); } /// /// Assign a size and position to each of its children.
///
/// This is a new size or position for this layout. /// Left position, relative to parent. /// Top position, relative to parent. /// Right position, relative to parent. /// Bottom position, relative to parent. /// 6 protected override void OnLayout(bool changed, LayoutLength left, LayoutLength top, LayoutLength right, LayoutLength bottom) { bool isLayoutRtl = Owner.LayoutDirection == ViewLayoutDirectionType.RTL; LayoutLength width = right - left; LayoutLength height = bottom - top; // Call to FlexLayout implementation to calculate layout values for later retrieval. Interop.FlexLayout.FlexLayout_CalculateLayout(swigCPtr, width.AsDecimal(), height.AsDecimal(), isLayoutRtl); int count = LayoutChildren.Count; for (int childIndex = 0; childIndex < count; childIndex++) { LayoutItem childLayout = LayoutChildren[childIndex]; if (childLayout != null) { // Get the frame for the child, start, top, end, bottom. Vector4 frame = new Vector4(Interop.FlexLayout.FlexLayout_GetNodeFrame(swigCPtr, childIndex), true); childLayout.Layout(new LayoutLength(frame.X), new LayoutLength(frame.Y), new LayoutLength(frame.Z), new LayoutLength(frame.W)); } } } } // FLexlayout } // namesspace Tizen.NUI