1d544776ad02b480dfadbe8f8df443d481aa61b7
[platform/core/csapi/tizenfx.git] / src / Tizen.NUI / src / internal / Layouting / LayoutController.cs
1 /*
2  * Copyright (c) 2019 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17
18 using Tizen.NUI.BaseComponents;
19 using System.Runtime.InteropServices;
20 using System.Collections.Generic;
21 using System.Diagnostics;
22 using System;
23 using System.ComponentModel;
24
25 namespace Tizen.NUI
26 {
27     /// <summary>
28     /// [Draft] The class that initiates the Measuring and Layouting of the tree,
29     ///         It sets a callback that becomes the entry point into the C# Layouting.
30     /// </summary>
31     internal class LayoutController : Disposable
32     {
33         static bool LayoutDebugController = false; // Debug flag
34
35         [UnmanagedFunctionPointer(CallingConvention.StdCall)]
36         internal delegate void Callback(int id);
37
38         event Callback _instance;
39
40         private Window _window;
41
42         Animation _coreAnimation;
43
44         private List<LayoutData> _layoutTransitionDataQueue;
45
46         private List<LayoutItem> _itemRemovalQueue;
47
48         /// <summary>
49         /// Constructs a LayoutController which controls the measuring and layouting.<br />
50         /// <param name="window">Window attach this LayoutController to.</param>
51         /// </summary>
52         public LayoutController(Window window) : this(Interop.LayoutController.LayoutController_New(), true)
53         {
54             _window = window;
55             _instance = new Callback(Process);
56             Interop.LayoutController.LayoutController_SetCallback(swigCPtr, _instance);
57
58             _layoutTransitionDataQueue = new List<LayoutData>();
59         }
60
61         internal LayoutController(global::System.IntPtr cPtr, bool cMemoryOwn) : base(cPtr, cMemoryOwn)
62         {
63         }
64
65         /// <summary>
66         /// Get the unique id of the LayoutController
67         /// </summary>
68         public int GetId()
69         {
70             return Interop.LayoutController.LayoutController_GetId(swigCPtr);
71         }
72
73         /// <summary>
74         /// Request relayout of a LayoutItem and it's parent tree.
75         /// </summary>
76         /// <param name="layoutItem">LayoutItem that is required to be laid out again.</param>
77         public void RequestLayout(LayoutItem layoutItem)
78         {
79             // Go up the tree and mark all parents to relayout
80             ILayoutParent layoutParent = layoutItem.GetParent();
81             if (layoutParent != null)
82             {
83                  LayoutGroup layoutGroup =  layoutParent as LayoutGroup;
84                  if(! layoutGroup.LayoutRequested)
85                  {
86                     layoutGroup.RequestLayout();
87                  }
88             }
89         }
90
91         /// <summary>
92         /// Get the Layouting animation object that transitions layouts and content.
93         /// Use OverrideCoreAnimation to explicitly control Playback.
94         /// </summary>
95         /// <returns> The layouting core Animation. </returns>
96         [EditorBrowsable(EditorBrowsableState.Never)]
97         public Animation GetCoreAnimation()
98         {
99             return _coreAnimation;
100         }
101
102         /// <summary>
103         /// Set or Get Layouting core animation override property.
104         /// Gives explicit control over the Layouting animation playback if set to True.
105         /// Reset to False if explicit control no longer required.
106         /// </summary>
107         [EditorBrowsable(EditorBrowsableState.Never)]
108         public bool OverrideCoreAnimation {get;set;} = false;
109
110         /// <summary>
111         /// Add transition data for a LayoutItem to the transition stack.
112         /// </summary>
113         /// <param name="transitionDataEntry">Transition data for a LayoutItem.</param>
114         internal void AddTransitionDataEntry( LayoutData transitionDataEntry)
115         {
116             _layoutTransitionDataQueue.Add(transitionDataEntry);
117         }
118
119         /// <summary>
120         /// Add LayoutItem to a removal stack for removal after transitions finish.
121         /// </summary>
122         /// <param name="itemToRemove">LayoutItem to remove.</param>
123         internal void AddToRemovalStack( LayoutItem itemToRemove)
124         {
125             if (_itemRemovalQueue == null)
126             {
127                 _itemRemovalQueue = new List<LayoutItem>();
128             }
129             _itemRemovalQueue.Add(itemToRemove);
130         }
131
132         /// <summary>
133         /// Dispose Explict or Implicit
134         /// </summary>
135         protected override void Dispose(DisposeTypes type)
136         {
137             if (disposed)
138             {
139                 return;
140             }
141
142             //Release your own unmanaged resources here.
143             //You should not access any managed member here except static instance.
144             //because the execution order of Finalizes is non-deterministic.
145
146             if (swigCPtr.Handle != global::System.IntPtr.Zero)
147             {
148                 Interop.LayoutController.delete_LayoutController(swigCPtr);
149                 swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero);
150             }
151
152             base.Dispose(type);
153         }
154
155         // Traverse through children from the provided root.
156         // If a child has no layout but is a pure View then assign a default layout and continue traversal.
157         // If child has no layout and not a pure View then assign a LayoutItem that terminates the layouting (leaf),
158         private void AutomaticallyAssignLayouts(View rootNode)
159         {
160             for (uint i = 0; i < rootNode.ChildCount; i++)
161             {
162                 View view = rootNode.GetChildAt(i);
163                 if (view.Layout == null )
164                 {
165                     view.Layout = new AbsoluteLayout();
166                     AutomaticallyAssignLayouts(rootNode);
167                 }
168             }
169         }
170
171         // Traverse the tree looking for a root node that is a layout.
172         // Once found, it's children can be assigned Layouts and the Measure process started.
173         private void FindRootLayouts(View rootNode)
174         {
175             if (rootNode.Layout != null)
176             {
177                 Debug.WriteLineIf( LayoutDebugController, "LayoutController Root found:" + rootNode.Name);
178                 // rootNode has a layout, ensure all children have default layouts or layout items.
179                 AutomaticallyAssignLayouts(rootNode);
180                 // rootNode has a layout, start measuring and layouting from here.
181                 MeasureAndLayout(rootNode);
182             }
183             else
184             {
185                 // Search children of supplied node for a layout.
186                 for (uint i = 0; i < rootNode.ChildCount; i++)
187                 {
188                     View view = rootNode.GetChildAt(i);
189                     FindRootLayouts(view);
190                 }
191             }
192         }
193
194         // Starts of the actual measuring and layouting from the given root node.
195         // Can be called from multiple starting roots but in series.
196         void MeasureAndLayout(View root)
197         {
198             if (root !=null)
199             {
200                 // Get parent MeasureSpecification, this could be the Window or View with an exact size.
201                 Container parentNode = root.GetParent();
202                 Size2D rootSize;
203                 Position2D rootPosition = root.Position2D;
204                 View parentView = parentNode as View;
205                 if (parentView)
206                 {
207                     // Get parent View's Size.  If using Legacy size negotiation then should have been set already.
208                     rootSize = new Size2D(parentView.Size2D.Width, parentView.Size2D.Height);
209                 }
210                 else
211                 {
212                     // Parent not a View so assume it's a Layer which is the size of the window.
213                     rootSize = new Size2D(_window.Size.Width, _window.Size.Height);
214                 }
215
216                 // Determine measure specification for root.
217                 // The root layout policy could be an exact size, be match parent or wrap children.
218                 // If wrap children then at most it can be the root parent size.
219                 // If match parent then should be root parent size.
220                 // If exact then should be that size limited by the root parent size.
221
222                 LayoutLength width = new LayoutLength(rootSize.Width);
223                 LayoutLength height = new LayoutLength(rootSize.Height);
224                 MeasureSpecification.ModeType widthMode = MeasureSpecification.ModeType.Unspecified;
225                 MeasureSpecification.ModeType heightMode = MeasureSpecification.ModeType.Unspecified;
226
227                 if ( root.WidthSpecification >= 0 )
228                 {
229                     // exact size provided so match width exactly
230                     width = new LayoutLength(root.WidthSpecification);
231                     widthMode = MeasureSpecification.ModeType.Exactly;
232                 }
233                 else if (root.WidthSpecification == LayoutParamPolicies.MatchParent)
234                 {
235
236                     widthMode = MeasureSpecification.ModeType.Exactly;
237                 }
238
239                 if (root.HeightSpecification >= 0 )
240                 {
241                     // exact size provided so match height exactly
242                     height = new LayoutLength(root.HeightSpecification);
243                     heightMode = MeasureSpecification.ModeType.Exactly;
244                 }
245                 else if (root.HeightSpecification == LayoutParamPolicies.MatchParent)
246                 {
247                     heightMode = MeasureSpecification.ModeType.Exactly;
248                 }
249
250                 MeasureSpecification parentWidthSpecification =
251                     new MeasureSpecification( width, widthMode);
252
253                 MeasureSpecification parentHeightSpecification =
254                     new MeasureSpecification( height, heightMode);
255
256                 // Start at root with it's parent's widthSpecification and heightSpecification
257                 MeasureHierarchy(root, parentWidthSpecification, parentHeightSpecification);
258
259                 // Start at root which was just measured.
260                 PerformLayout( root, new LayoutLength(rootPosition.X),
261                                      new LayoutLength(rootPosition.Y),
262                                      new LayoutLength(rootPosition.X) + root.Layout.MeasuredWidth.Size,
263                                      new LayoutLength(rootPosition.Y) + root.Layout.MeasuredHeight.Size );
264
265                 bool readyToPlay = SetupCoreAnimation();
266
267                 if (readyToPlay && OverrideCoreAnimation==false)
268                 {
269                     PlayAnimation();
270                 }
271             }
272         }
273
274         /// <summary>
275         /// Entry point into the C# Layouting that starts the Processing
276         /// </summary>
277         private void Process(int id)
278         {
279             // First layer in the Window should be the default layer (index 0 )
280             uint numberOfLayers = _window.LayerCount;
281             for (uint layerIndex = 0; layerIndex < numberOfLayers; layerIndex++)
282             {
283                 Layer layer = _window.GetLayer(layerIndex);
284                 if (layer)
285                 {
286                     for (uint i = 0; i < layer.ChildCount; i++)
287                     {
288                         View view = layer.GetChildAt(i);
289                         FindRootLayouts(view);
290                     }
291                 }
292             }
293
294         }
295
296         /// <summary>
297         /// Starts measuring the tree, starting from the root layout.
298         /// </summary>
299         private void MeasureHierarchy(View root, MeasureSpecification widthSpec, MeasureSpecification heightSpec)
300         {
301             // Does this View have a layout?
302             // Yes - measure the layout. It will call this method again for each of it's children.
303             // No -  reached leaf or no layouts set
304             //
305             // If in a leaf View with no layout, it's natural size is bubbled back up.
306
307             if (root.Layout != null)
308             {
309                 root.Layout.Measure(widthSpec, heightSpec);
310             }
311         }
312
313         /// <summary>
314         /// Performs the layouting positioning
315         /// </summary>
316         private void PerformLayout(View root, LayoutLength left, LayoutLength top, LayoutLength right, LayoutLength bottom)
317         {
318             if(root.Layout != null)
319             {
320                 root.Layout.Layout(left, top, right, bottom);
321             }
322         }
323
324         /// <summary>
325         /// Play the animation.
326         /// </summary>
327         private void PlayAnimation()
328         {
329             Debug.WriteLineIf( LayoutDebugController, "LayoutController Playing, Core Duration:" + _coreAnimation.Duration);
330             _coreAnimation.Play();
331         }
332
333         private void AnimationFinished(object sender, EventArgs e)
334         {
335             // Iterate list of LayoutItem that were set for removal.
336             // Now the core animation has finished their Views can be removed.
337             if (_itemRemovalQueue != null)
338             {
339                 foreach (LayoutItem item in _itemRemovalQueue)
340                 {
341                     // Check incase the parent was already removed and the Owner was
342                     // removed already.
343                     if (item.Owner)
344                     {
345                         // Check again incase the parent has already been removed.
346                         ILayoutParent layoutParent = item.GetParent();
347                         LayoutGroup layoutGroup = layoutParent as LayoutGroup;
348                         if (layoutGroup !=null)
349                         {
350                             layoutGroup.Owner?.RemoveChild(item.Owner);
351                         }
352
353                     }
354                 }
355                 _itemRemovalQueue.Clear();
356                 // If LayoutItems added to stack whilst the core animation is playing
357                 // they would have been cleared here.
358                 // Could have another stack to be added to whilst the animation is running.
359                 // After the running stack is cleared it can be populated with the content
360                 // of the other stack.  Then the main removal stack iterated when AnimationFinished
361                 // occurs again.
362             }
363             Debug.WriteLineIf( LayoutDebugController, "LayoutController AnimationFinished");
364             _coreAnimation?.Clear();
365         }
366
367         /// <summary>
368         /// Set up the animation from each LayoutItems position data.
369         /// Iterates the transition stack, adding an Animator to the core animation.
370         /// </summary>
371         private bool SetupCoreAnimation()
372         {
373             // Initialize animation for this layout run.
374             bool animationPending = false;
375
376             Debug.WriteLineIf( LayoutDebugController,
377                                "LayoutController SetupCoreAnimation for:" + _layoutTransitionDataQueue.Count);
378
379             if (_layoutTransitionDataQueue.Count > 0 ) // Something to animate
380             {
381                 if (!_coreAnimation)
382                 {
383                     _coreAnimation = new Animation();
384                 }
385                 _coreAnimation.EndAction = Animation.EndActions.StopFinal;
386                 _coreAnimation.Finished += AnimationFinished;
387
388                 // Iterate all items that have been queued for repositioning.
389                 foreach (LayoutData layoutPositionData in _layoutTransitionDataQueue)
390                 {
391                     AddAnimatorsToAnimation(layoutPositionData);
392                 }
393
394                 animationPending = true;
395
396                 // transitions have now been applied, clear stack, ready for new transitions on
397                 // next layout traversal.
398                 _layoutTransitionDataQueue.Clear();
399             }
400             return animationPending;
401         }
402
403         private void SetupAnimationForPosition(LayoutData layoutPositionData, TransitionComponents positionTransitionComponents)
404         {
405             // A removed item does not have a valid target position within the layout so don't try to position.
406             if( layoutPositionData.ConditionForAnimation != TransitionCondition.Remove )
407             {
408                 _coreAnimation.AnimateTo(layoutPositionData.Item.Owner, "Position",
409                             new Vector3(layoutPositionData.Left,
410                                         layoutPositionData.Top,
411                                         layoutPositionData.Item.Owner.Position.Z),
412                             positionTransitionComponents.Delay,
413                             positionTransitionComponents.Duration,
414                             positionTransitionComponents.AlphaFunction );
415
416                 Debug.WriteLineIf( LayoutDebugController,
417                                    "LayoutController SetupAnimationForPosition View:" + layoutPositionData.Item.Owner.Name +
418                                    " left:" + layoutPositionData.Left +
419                                    " top:" + layoutPositionData.Top +
420                                    " delay:" + positionTransitionComponents.Delay +
421                                    " duration:" + positionTransitionComponents.Duration );
422             }
423         }
424
425         private void SetupAnimationForSize(LayoutData layoutPositionData, TransitionComponents sizeTransitionComponents)
426         {
427             // Text size cant be animated so is set to it's final size.
428             // It is due to the internals of the Text not being able to recalculate fast enough.
429             if (layoutPositionData.Item.Owner is TextLabel || layoutPositionData.Item.Owner is TextField)
430             {
431                 float itemWidth = layoutPositionData.Right-layoutPositionData.Left;
432                 float itemHeight = layoutPositionData.Bottom-layoutPositionData.Top;
433                 // Set size directly.
434                 layoutPositionData.Item.Owner.Size2D = new Size2D((int)itemWidth, (int)itemHeight);
435             }
436             else
437             {
438                 _coreAnimation.AnimateTo(layoutPositionData.Item.Owner, "Size",
439                                          new Vector3(layoutPositionData.Right-layoutPositionData.Left,
440                                                      layoutPositionData.Bottom-layoutPositionData.Top,
441                                                      layoutPositionData.Item.Owner.Position.Z),
442                                          sizeTransitionComponents.Delay,
443                                          sizeTransitionComponents.Duration,
444                                          sizeTransitionComponents.AlphaFunction);
445
446                 Debug.WriteLineIf( LayoutDebugController,
447                                   "LayoutController SetupAnimationForSize View:" + layoutPositionData.Item.Owner.Name +
448                                    " width:" + (layoutPositionData.Right-layoutPositionData.Left) +
449                                    " height:" + (layoutPositionData.Bottom-layoutPositionData.Top) +
450                                    " delay:" + sizeTransitionComponents.Delay +
451                                    " duration:" + sizeTransitionComponents.Duration );
452             }
453         }
454
455         void SetupAnimationForCustomTransitions(TransitionList transitionsToAnimate, View view )
456         {
457             if (transitionsToAnimate?.Count > 0)
458             {
459                 foreach (LayoutTransition transition in transitionsToAnimate)
460                 {
461                     if ( transition.AnimatableProperty != AnimatableProperties.Position &&
462                         transition.AnimatableProperty != AnimatableProperties.Size )
463                     {
464                         _coreAnimation.AnimateTo(view,
465                                                  transition.AnimatableProperty.ToString(),
466                                                  transition.TargetValue,
467                                                  transition.Animator.Delay,
468                                                  transition.Animator.Duration,
469                                                  transition.Animator.AlphaFunction );
470
471                         Debug.WriteLineIf( LayoutDebugController,
472                                            "LayoutController SetupAnimationForCustomTransitions View:" + view.Name +
473                                            " Property:" + transition.AnimatableProperty.ToString() +
474                                            " delay:" + transition.Animator.Delay +
475                                            " duration:" + transition.Animator.Duration );
476                     }
477                 }
478             }
479         }
480
481         /// <summary>
482         /// Iterate transitions and replace Position Components if replacements found in list.
483         /// </summary>
484         private void FindAndReplaceAnimatorComponentsForProperty(TransitionList sourceTransitionList,
485                                                                  AnimatableProperties propertyToMatch,
486                                                                  ref TransitionComponents transitionComponentToUpdate)
487         {
488             foreach( LayoutTransition transition in sourceTransitionList)
489             {
490                 if (transition.AnimatableProperty == propertyToMatch)
491                 {
492                     // Matched property to animate is for the propertyToMatch so use provided Animator.
493                     transitionComponentToUpdate = transition.Animator;
494                 }
495             }
496         }
497
498         private TransitionComponents CreateDefaultTransitionComponent( int delay, int duration )
499         {
500             AlphaFunction alphaFunction = new AlphaFunction(AlphaFunction.BuiltinFunctions.Linear);
501             return new TransitionComponents(delay, duration, alphaFunction);
502         }
503
504         /// <summary>
505         /// Sets up the main animation with the animators for each item (each layoutPositionData structure)
506         /// </summary>
507         private void AddAnimatorsToAnimation( LayoutData layoutPositionData )
508         {
509             LayoutTransition positionTransition = new LayoutTransition();
510             LayoutTransition sizeTransition = new LayoutTransition();
511             TransitionCondition conditionForAnimators = layoutPositionData.ConditionForAnimation;
512
513             // LayoutChanged transitions overrides ChangeOnAdd and ChangeOnRemove as siblings will
514             // reposition to the new layout not to the insertion/removal of a sibling.
515             if (layoutPositionData.ConditionForAnimation.HasFlag(TransitionCondition.LayoutChanged))
516             {
517                 conditionForAnimators = TransitionCondition.LayoutChanged;
518             }
519
520             // Set up a default transitions, will be overwritten if inherited from parent or set explicitly.
521             TransitionComponents positionTransitionComponents = CreateDefaultTransitionComponent(0, 300);
522             TransitionComponents sizeTransitionComponents = CreateDefaultTransitionComponent(0, 300);
523
524             bool matchedCustomTransitions = false;
525
526
527             TransitionList transitionsForCurrentCondition = new TransitionList();
528             // Note, Transitions set on View rather than LayoutItem so if the Layout changes the transition persist.
529
530             // Check if item to animate has it's own Transitions for this condition.
531             // If a key exists then a List of atleast 1 transition exists.
532             if (layoutPositionData.Item.Owner.LayoutTransitions.ContainsKey(conditionForAnimators))
533             {
534                 // Child has transitions for the condition
535                 matchedCustomTransitions = layoutPositionData.Item.Owner.LayoutTransitions.TryGetValue(conditionForAnimators, out transitionsForCurrentCondition);
536             }
537
538             if (!matchedCustomTransitions)
539             {
540                 // Inherit parent transitions as none already set on View for the condition.
541                 ILayoutParent layoutParent = layoutPositionData.Item.GetParent();
542                 if (layoutParent !=null)
543                 {
544                     // Item doesn't have it's own transitions for this condition so copy parents if
545                     // has a parent with transitions.
546                     LayoutGroup layoutGroup = layoutParent as LayoutGroup;
547                     TransitionList parentTransitionList;
548                     // Note TryGetValue returns null if key not matched.
549                     if (layoutGroup !=null && layoutGroup.Owner.LayoutTransitions.TryGetValue(conditionForAnimators, out parentTransitionList))
550                     {
551                         // Copy parent transitions to temporary TransitionList. List contains transitions for the current condition.
552                         LayoutTransitionsHelper.CopyTransitions(parentTransitionList,
553                                                                 transitionsForCurrentCondition);
554                     }
555                 }
556             }
557
558
559             // Position/Size transitions can be displayed for a layout changing to another layout or an item being added or removed.
560
561             // There can only be one position transition and one size position, they will be replaced if set multiple times.
562             // transitionsForCurrentCondition represent all non position (custom) properties that should be animated.
563
564             // Search for Position property in the transitionsForCurrentCondition list of custom transitions,
565             // and only use the particular parts of the animator as custom transitions should not effect all parameters of Position.
566             // Typically Delay, Duration and Alphafunction can be custom.
567             FindAndReplaceAnimatorComponentsForProperty(transitionsForCurrentCondition,
568                                                         AnimatableProperties.Position,
569                                                         ref positionTransitionComponents);
570
571             // Size
572             FindAndReplaceAnimatorComponentsForProperty(transitionsForCurrentCondition,
573                                                         AnimatableProperties.Size,
574                                                         ref sizeTransitionComponents);
575
576             // Add animators to the core Animation,
577
578             SetupAnimationForCustomTransitions(transitionsForCurrentCondition, layoutPositionData.Item.Owner);
579
580             SetupAnimationForPosition(layoutPositionData, positionTransitionComponents);
581
582             SetupAnimationForSize(layoutPositionData, sizeTransitionComponents);
583         }
584
585     } // class LayoutController
586 } // namespace Tizen.NUI