Follow formatting NUI
[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 != null && !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 the tree looking for a root node that is a layout.
156         // Once found, it's children can be assigned Layouts and the Measure process started.
157         private void FindRootLayouts(View rootNode)
158         {
159             if (rootNode.Layout != null)
160             {
161                 Debug.WriteLineIf(LayoutDebugController, "LayoutController Root found:" + rootNode.Name);
162                 // rootNode has a layout, start measuring and layouting from here.
163                 MeasureAndLayout(rootNode);
164             }
165             else
166             {
167                 // Search children of supplied node for a layout.
168                 for (uint i = 0; i < rootNode.ChildCount; i++)
169                 {
170                     View view = rootNode.GetChildAt(i);
171                     FindRootLayouts(view);
172                 }
173             }
174         }
175
176         // Starts of the actual measuring and layouting from the given root node.
177         // Can be called from multiple starting roots but in series.
178         void MeasureAndLayout(View root)
179         {
180             if (root != null)
181             {
182                 // Get parent MeasureSpecification, this could be the Window or View with an exact size.
183                 Container parentNode = root.GetParent();
184                 Size2D rootSize;
185                 Position2D rootPosition = root.Position2D;
186                 View parentView = parentNode as View;
187                 if (parentView != null)
188                 {
189                     // Get parent View's Size.  If using Legacy size negotiation then should have been set already.
190                     rootSize = new Size2D(parentView.Size2D.Width, parentView.Size2D.Height);
191                 }
192                 else
193                 {
194                     // Parent not a View so assume it's a Layer which is the size of the window.
195                     rootSize = new Size2D(_window.Size.Width, _window.Size.Height);
196                 }
197
198                 // Determine measure specification for root.
199                 // The root layout policy could be an exact size, be match parent or wrap children.
200                 // If wrap children then at most it can be the root parent size.
201                 // If match parent then should be root parent size.
202                 // If exact then should be that size limited by the root parent size.
203
204                 LayoutLength width = new LayoutLength(rootSize.Width);
205                 LayoutLength height = new LayoutLength(rootSize.Height);
206                 MeasureSpecification.ModeType widthMode = MeasureSpecification.ModeType.Unspecified;
207                 MeasureSpecification.ModeType heightMode = MeasureSpecification.ModeType.Unspecified;
208
209                 if (root.WidthSpecification >= 0)
210                 {
211                     // exact size provided so match width exactly
212                     width = new LayoutLength(root.WidthSpecification);
213                     widthMode = MeasureSpecification.ModeType.Exactly;
214                 }
215                 else if (root.WidthSpecification == LayoutParamPolicies.MatchParent)
216                 {
217
218                     widthMode = MeasureSpecification.ModeType.Exactly;
219                 }
220
221                 if (root.HeightSpecification >= 0)
222                 {
223                     // exact size provided so match height exactly
224                     height = new LayoutLength(root.HeightSpecification);
225                     heightMode = MeasureSpecification.ModeType.Exactly;
226                 }
227                 else if (root.HeightSpecification == LayoutParamPolicies.MatchParent)
228                 {
229                     heightMode = MeasureSpecification.ModeType.Exactly;
230                 }
231
232                 MeasureSpecification parentWidthSpecification =
233                     new MeasureSpecification(width, widthMode);
234
235                 MeasureSpecification parentHeightSpecification =
236                     new MeasureSpecification(height, heightMode);
237
238                 // Start at root with it's parent's widthSpecification and heightSpecification
239                 MeasureHierarchy(root, parentWidthSpecification, parentHeightSpecification);
240
241                 // Start at root which was just measured.
242                 PerformLayout(root, new LayoutLength(rootPosition.X),
243                                      new LayoutLength(rootPosition.Y),
244                                      new LayoutLength(rootPosition.X) + root.Layout.MeasuredWidth.Size,
245                                      new LayoutLength(rootPosition.Y) + root.Layout.MeasuredHeight.Size);
246
247                 bool readyToPlay = SetupCoreAnimation();
248
249                 if (readyToPlay && OverrideCoreAnimation == false)
250                 {
251                     PlayAnimation();
252                 }
253             }
254         }
255
256         /// <summary>
257         /// Entry point into the C# Layouting that starts the Processing
258         /// </summary>
259         private void Process(int id)
260         {
261             // First layer in the Window should be the default layer (index 0 )
262             uint numberOfLayers = _window.LayerCount;
263             for (uint layerIndex = 0; layerIndex < numberOfLayers; layerIndex++)
264             {
265                 Layer layer = _window.GetLayer(layerIndex);
266                 if (layer != null)
267                 {
268                     for (uint i = 0; i < layer.ChildCount; i++)
269                     {
270                         View view = layer.GetChildAt(i);
271                         FindRootLayouts(view);
272                     }
273                 }
274             }
275
276         }
277
278         /// <summary>
279         /// Starts measuring the tree, starting from the root layout.
280         /// </summary>
281         private void MeasureHierarchy(View root, MeasureSpecification widthSpec, MeasureSpecification heightSpec)
282         {
283             // Does this View have a layout?
284             // Yes - measure the layout. It will call this method again for each of it's children.
285             // No -  reached leaf or no layouts set
286             //
287             // If in a leaf View with no layout, it's natural size is bubbled back up.
288
289             if (root.Layout != null)
290             {
291                 root.Layout.Measure(widthSpec, heightSpec);
292             }
293         }
294
295         /// <summary>
296         /// Performs the layouting positioning
297         /// </summary>
298         private void PerformLayout(View root, LayoutLength left, LayoutLength top, LayoutLength right, LayoutLength bottom)
299         {
300             if (root.Layout != null)
301             {
302                 root.Layout.Layout(left, top, right, bottom);
303             }
304         }
305
306         /// <summary>
307         /// Play the animation.
308         /// </summary>
309         private void PlayAnimation()
310         {
311             Debug.WriteLineIf(LayoutDebugController, "LayoutController Playing, Core Duration:" + _coreAnimation.Duration);
312             _coreAnimation.Play();
313         }
314
315         private void AnimationFinished(object sender, EventArgs e)
316         {
317             // Iterate list of LayoutItem that were set for removal.
318             // Now the core animation has finished their Views can be removed.
319             if (_itemRemovalQueue != null)
320             {
321                 foreach (LayoutItem item in _itemRemovalQueue)
322                 {
323                     // Check incase the parent was already removed and the Owner was
324                     // removed already.
325                     if (item.Owner)
326                     {
327                         // Check again incase the parent has already been removed.
328                         ILayoutParent layoutParent = item.GetParent();
329                         LayoutGroup layoutGroup = layoutParent as LayoutGroup;
330                         if (layoutGroup != null)
331                         {
332                             layoutGroup.Owner?.RemoveChild(item.Owner);
333                         }
334
335                     }
336                 }
337                 _itemRemovalQueue.Clear();
338                 // If LayoutItems added to stack whilst the core animation is playing
339                 // they would have been cleared here.
340                 // Could have another stack to be added to whilst the animation is running.
341                 // After the running stack is cleared it can be populated with the content
342                 // of the other stack.  Then the main removal stack iterated when AnimationFinished
343                 // occurs again.
344             }
345             Debug.WriteLineIf(LayoutDebugController, "LayoutController AnimationFinished");
346             _coreAnimation?.Clear();
347         }
348
349         /// <summary>
350         /// Set up the animation from each LayoutItems position data.
351         /// Iterates the transition stack, adding an Animator to the core animation.
352         /// </summary>
353         private bool SetupCoreAnimation()
354         {
355             // Initialize animation for this layout run.
356             bool animationPending = false;
357
358             Debug.WriteLineIf(LayoutDebugController,
359                                "LayoutController SetupCoreAnimation for:" + _layoutTransitionDataQueue.Count);
360
361             if (_layoutTransitionDataQueue.Count > 0) // Something to animate
362             {
363                 if (!_coreAnimation)
364                 {
365                     _coreAnimation = new Animation();
366                 }
367                 _coreAnimation.EndAction = Animation.EndActions.StopFinal;
368                 _coreAnimation.Finished += AnimationFinished;
369
370                 // Iterate all items that have been queued for repositioning.
371                 foreach (LayoutData layoutPositionData in _layoutTransitionDataQueue)
372                 {
373                     AddAnimatorsToAnimation(layoutPositionData);
374                 }
375
376                 animationPending = true;
377
378                 // transitions have now been applied, clear stack, ready for new transitions on
379                 // next layout traversal.
380                 _layoutTransitionDataQueue.Clear();
381             }
382             return animationPending;
383         }
384
385         private void SetupAnimationForPosition(LayoutData layoutPositionData, TransitionComponents positionTransitionComponents)
386         {
387             // A removed item does not have a valid target position within the layout so don't try to position.
388             if (layoutPositionData.ConditionForAnimation != TransitionCondition.Remove)
389             {
390                 _coreAnimation.AnimateTo(layoutPositionData.Item.Owner, "Position",
391                             new Vector3(layoutPositionData.Left,
392                                         layoutPositionData.Top,
393                                         layoutPositionData.Item.Owner.Position.Z),
394                             positionTransitionComponents.Delay,
395                             positionTransitionComponents.Duration,
396                             positionTransitionComponents.AlphaFunction);
397
398                 Debug.WriteLineIf(LayoutDebugController,
399                                    "LayoutController SetupAnimationForPosition View:" + layoutPositionData.Item.Owner.Name +
400                                    " left:" + layoutPositionData.Left +
401                                    " top:" + layoutPositionData.Top +
402                                    " delay:" + positionTransitionComponents.Delay +
403                                    " duration:" + positionTransitionComponents.Duration);
404             }
405         }
406
407         private void SetupAnimationForSize(LayoutData layoutPositionData, TransitionComponents sizeTransitionComponents)
408         {
409             // Text size cant be animated so is set to it's final size.
410             // It is due to the internals of the Text not being able to recalculate fast enough.
411             if (layoutPositionData.Item.Owner is TextLabel || layoutPositionData.Item.Owner is TextField)
412             {
413                 float itemWidth = layoutPositionData.Right - layoutPositionData.Left;
414                 float itemHeight = layoutPositionData.Bottom - layoutPositionData.Top;
415                 // Set size directly.
416                 layoutPositionData.Item.Owner.Size2D = new Size2D((int)itemWidth, (int)itemHeight);
417             }
418             else
419             {
420                 _coreAnimation.AnimateTo(layoutPositionData.Item.Owner, "Size",
421                                          new Vector3(layoutPositionData.Right - layoutPositionData.Left,
422                                                      layoutPositionData.Bottom - layoutPositionData.Top,
423                                                      layoutPositionData.Item.Owner.Position.Z),
424                                          sizeTransitionComponents.Delay,
425                                          sizeTransitionComponents.Duration,
426                                          sizeTransitionComponents.AlphaFunction);
427
428                 Debug.WriteLineIf(LayoutDebugController,
429                                   "LayoutController SetupAnimationForSize View:" + layoutPositionData.Item.Owner.Name +
430                                    " width:" + (layoutPositionData.Right - layoutPositionData.Left) +
431                                    " height:" + (layoutPositionData.Bottom - layoutPositionData.Top) +
432                                    " delay:" + sizeTransitionComponents.Delay +
433                                    " duration:" + sizeTransitionComponents.Duration);
434             }
435         }
436
437         void SetupAnimationForCustomTransitions(TransitionList transitionsToAnimate, View view)
438         {
439             if (transitionsToAnimate?.Count > 0)
440             {
441                 foreach (LayoutTransition transition in transitionsToAnimate)
442                 {
443                     if (transition.AnimatableProperty != AnimatableProperties.Position &&
444                         transition.AnimatableProperty != AnimatableProperties.Size)
445                     {
446                         _coreAnimation.AnimateTo(view,
447                                                  transition.AnimatableProperty.ToString(),
448                                                  transition.TargetValue,
449                                                  transition.Animator.Delay,
450                                                  transition.Animator.Duration,
451                                                  transition.Animator.AlphaFunction);
452
453                         Debug.WriteLineIf(LayoutDebugController,
454                                            "LayoutController SetupAnimationForCustomTransitions View:" + view.Name +
455                                            " Property:" + transition.AnimatableProperty.ToString() +
456                                            " delay:" + transition.Animator.Delay +
457                                            " duration:" + transition.Animator.Duration);
458                     }
459                 }
460             }
461         }
462
463         /// <summary>
464         /// Iterate transitions and replace Position Components if replacements found in list.
465         /// </summary>
466         private void FindAndReplaceAnimatorComponentsForProperty(TransitionList sourceTransitionList,
467                                                                  AnimatableProperties propertyToMatch,
468                                                                  ref TransitionComponents transitionComponentToUpdate)
469         {
470             foreach (LayoutTransition transition in sourceTransitionList)
471             {
472                 if (transition.AnimatableProperty == propertyToMatch)
473                 {
474                     // Matched property to animate is for the propertyToMatch so use provided Animator.
475                     transitionComponentToUpdate = transition.Animator;
476                 }
477             }
478         }
479
480         private TransitionComponents CreateDefaultTransitionComponent(int delay, int duration)
481         {
482             AlphaFunction alphaFunction = new AlphaFunction(AlphaFunction.BuiltinFunctions.Linear);
483             return new TransitionComponents(delay, duration, alphaFunction);
484         }
485
486         /// <summary>
487         /// Sets up the main animation with the animators for each item (each layoutPositionData structure)
488         /// </summary>
489         private void AddAnimatorsToAnimation(LayoutData layoutPositionData)
490         {
491             LayoutTransition positionTransition = new LayoutTransition();
492             LayoutTransition sizeTransition = new LayoutTransition();
493             TransitionCondition conditionForAnimators = layoutPositionData.ConditionForAnimation;
494
495             // LayoutChanged transitions overrides ChangeOnAdd and ChangeOnRemove as siblings will
496             // reposition to the new layout not to the insertion/removal of a sibling.
497             if (layoutPositionData.ConditionForAnimation.HasFlag(TransitionCondition.LayoutChanged))
498             {
499                 conditionForAnimators = TransitionCondition.LayoutChanged;
500             }
501
502             // Set up a default transitions, will be overwritten if inherited from parent or set explicitly.
503             TransitionComponents positionTransitionComponents = CreateDefaultTransitionComponent(0, 300);
504             TransitionComponents sizeTransitionComponents = CreateDefaultTransitionComponent(0, 300);
505
506             bool matchedCustomTransitions = false;
507
508
509             TransitionList transitionsForCurrentCondition = new TransitionList();
510             // Note, Transitions set on View rather than LayoutItem so if the Layout changes the transition persist.
511
512             // Check if item to animate has it's own Transitions for this condition.
513             // If a key exists then a List of atleast 1 transition exists.
514             if (layoutPositionData.Item.Owner.LayoutTransitions.ContainsKey(conditionForAnimators))
515             {
516                 // Child has transitions for the condition
517                 matchedCustomTransitions = layoutPositionData.Item.Owner.LayoutTransitions.TryGetValue(conditionForAnimators, out transitionsForCurrentCondition);
518             }
519
520             if (!matchedCustomTransitions)
521             {
522                 // Inherit parent transitions as none already set on View for the condition.
523                 ILayoutParent layoutParent = layoutPositionData.Item.GetParent();
524                 if (layoutParent != null)
525                 {
526                     // Item doesn't have it's own transitions for this condition so copy parents if
527                     // has a parent with transitions.
528                     LayoutGroup layoutGroup = layoutParent as LayoutGroup;
529                     TransitionList parentTransitionList;
530                     // Note TryGetValue returns null if key not matched.
531                     if (layoutGroup != null && layoutGroup.Owner.LayoutTransitions.TryGetValue(conditionForAnimators, out parentTransitionList))
532                     {
533                         // Copy parent transitions to temporary TransitionList. List contains transitions for the current condition.
534                         LayoutTransitionsHelper.CopyTransitions(parentTransitionList,
535                                                                 transitionsForCurrentCondition);
536                     }
537                 }
538             }
539
540
541             // Position/Size transitions can be displayed for a layout changing to another layout or an item being added or removed.
542
543             // There can only be one position transition and one size position, they will be replaced if set multiple times.
544             // transitionsForCurrentCondition represent all non position (custom) properties that should be animated.
545
546             // Search for Position property in the transitionsForCurrentCondition list of custom transitions,
547             // and only use the particular parts of the animator as custom transitions should not effect all parameters of Position.
548             // Typically Delay, Duration and Alphafunction can be custom.
549             FindAndReplaceAnimatorComponentsForProperty(transitionsForCurrentCondition,
550                                                         AnimatableProperties.Position,
551                                                         ref positionTransitionComponents);
552
553             // Size
554             FindAndReplaceAnimatorComponentsForProperty(transitionsForCurrentCondition,
555                                                         AnimatableProperties.Size,
556                                                         ref sizeTransitionComponents);
557
558             // Add animators to the core Animation,
559
560             SetupAnimationForCustomTransitions(transitionsForCurrentCondition, layoutPositionData.Item.Owner);
561
562             SetupAnimationForPosition(layoutPositionData, positionTransitionComponents);
563
564             SetupAnimationForSize(layoutPositionData, sizeTransitionComponents);
565         }
566
567     } // class LayoutController
568 } // namespace Tizen.NUI