2 * Copyright (c) 2019 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 using Tizen.NUI.BaseComponents;
19 using System.Runtime.InteropServices;
20 using System.Collections.Generic;
21 using System.Diagnostics;
23 using System.ComponentModel;
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.
31 internal class LayoutController : Disposable
33 static bool LayoutDebugController = false; // Debug flag
35 [UnmanagedFunctionPointer(CallingConvention.StdCall)]
36 internal delegate void Callback(int id);
38 event Callback _instance;
40 private Window _window;
42 Animation _coreAnimation;
44 private List<LayoutData> _layoutTransitionDataQueue;
46 private List<LayoutItem> _itemRemovalQueue;
49 /// Constructs a LayoutController which controls the measuring and layouting.<br />
50 /// <param name="window">Window attach this LayoutController to.</param>
52 public LayoutController(Window window) : this(Interop.LayoutController.LayoutController_New(), true)
55 _instance = new Callback(Process);
56 Interop.LayoutController.LayoutController_SetCallback(swigCPtr, _instance);
58 _layoutTransitionDataQueue = new List<LayoutData>();
61 internal LayoutController(global::System.IntPtr cPtr, bool cMemoryOwn) : base(cPtr, cMemoryOwn)
66 /// Get the unique id of the LayoutController
70 return Interop.LayoutController.LayoutController_GetId(swigCPtr);
74 /// Request relayout of a LayoutItem and it's parent tree.
76 /// <param name="layoutItem">LayoutItem that is required to be laid out again.</param>
77 public void RequestLayout(LayoutItem layoutItem)
79 // Go up the tree and mark all parents to relayout
80 ILayoutParent layoutParent = layoutItem.GetParent();
81 if (layoutParent != null)
83 LayoutGroup layoutGroup = layoutParent as LayoutGroup;
84 if(! layoutGroup.LayoutRequested)
86 layoutGroup.RequestLayout();
92 /// Get the Layouting animation object that transitions layouts and content.
93 /// Use OverrideCoreAnimation to explicitly control Playback.
95 /// <returns> The layouting core Animation. </returns>
96 [EditorBrowsable(EditorBrowsableState.Never)]
97 public Animation GetCoreAnimation()
99 return _coreAnimation;
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.
107 [EditorBrowsable(EditorBrowsableState.Never)]
108 public bool OverrideCoreAnimation {get;set;} = false;
111 /// Add transition data for a LayoutItem to the transition stack.
113 /// <param name="transitionDataEntry">Transition data for a LayoutItem.</param>
114 internal void AddTransitionDataEntry( LayoutData transitionDataEntry)
116 _layoutTransitionDataQueue.Add(transitionDataEntry);
120 /// Add LayoutItem to a removal stack for removal after transitions finish.
122 /// <param name="itemToRemove">LayoutItem to remove.</param>
123 internal void AddToRemovalStack( LayoutItem itemToRemove)
125 if (_itemRemovalQueue == null)
127 _itemRemovalQueue = new List<LayoutItem>();
129 _itemRemovalQueue.Add(itemToRemove);
133 /// Dispose Explict or Implicit
135 protected override void Dispose(DisposeTypes type)
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.
146 if (swigCPtr.Handle != global::System.IntPtr.Zero)
148 Interop.LayoutController.delete_LayoutController(swigCPtr);
149 swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero);
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)
160 for (uint i = 0; i < rootNode.ChildCount; i++)
162 View view = rootNode.GetChildAt(i);
163 if (view.Layout == null )
165 view.Layout = new AbsoluteLayout();
166 AutomaticallyAssignLayouts(rootNode);
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)
175 if (rootNode.Layout != null)
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);
185 // Search children of supplied node for a layout.
186 for (uint i = 0; i < rootNode.ChildCount; i++)
188 View view = rootNode.GetChildAt(i);
189 FindRootLayouts(view);
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)
200 // Get parent MeasureSpecification, this could be the Window or View with an exact size.
201 Container parentNode = root.GetParent();
203 Position2D rootPosition = root.Position2D;
204 View parentView = parentNode as View;
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);
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);
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.
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;
227 if ( root.WidthSpecification >= 0 )
229 // exact size provided so match width exactly
230 width = new LayoutLength(root.WidthSpecification);
231 widthMode = MeasureSpecification.ModeType.Exactly;
233 else if (root.WidthSpecification == LayoutParamPolicies.MatchParent)
236 widthMode = MeasureSpecification.ModeType.Exactly;
239 if (root.HeightSpecification >= 0 )
241 // exact size provided so match height exactly
242 height = new LayoutLength(root.HeightSpecification);
243 heightMode = MeasureSpecification.ModeType.Exactly;
245 else if (root.HeightSpecification == LayoutParamPolicies.MatchParent)
247 heightMode = MeasureSpecification.ModeType.Exactly;
250 MeasureSpecification parentWidthSpecification =
251 new MeasureSpecification( width, widthMode);
253 MeasureSpecification parentHeightSpecification =
254 new MeasureSpecification( height, heightMode);
256 // Start at root with it's parent's widthSpecification and heightSpecification
257 MeasureHierarchy(root, parentWidthSpecification, parentHeightSpecification);
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 );
265 bool readyToPlay = SetupCoreAnimation();
267 if (readyToPlay && OverrideCoreAnimation==false)
275 /// Entry point into the C# Layouting that starts the Processing
277 private void Process(int id)
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++)
283 Layer layer = _window.GetLayer(layerIndex);
286 for (uint i = 0; i < layer.ChildCount; i++)
288 View view = layer.GetChildAt(i);
289 FindRootLayouts(view);
297 /// Starts measuring the tree, starting from the root layout.
299 private void MeasureHierarchy(View root, MeasureSpecification widthSpec, MeasureSpecification heightSpec)
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
305 // If in a leaf View with no layout, it's natural size is bubbled back up.
307 if (root.Layout != null)
309 root.Layout.Measure(widthSpec, heightSpec);
314 /// Performs the layouting positioning
316 private void PerformLayout(View root, LayoutLength left, LayoutLength top, LayoutLength right, LayoutLength bottom)
318 if(root.Layout != null)
320 root.Layout.Layout(left, top, right, bottom);
325 /// Play the animation.
327 private void PlayAnimation()
329 Debug.WriteLineIf( LayoutDebugController, "LayoutController Playing, Core Duration:" + _coreAnimation.Duration);
330 _coreAnimation.Play();
333 private void AnimationFinished(object sender, EventArgs e)
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)
339 foreach (LayoutItem item in _itemRemovalQueue)
341 // Check incase the parent was already removed and the Owner was
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)
350 layoutGroup.Owner?.RemoveChild(item.Owner);
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
363 Debug.WriteLineIf( LayoutDebugController, "LayoutController AnimationFinished");
364 _coreAnimation?.Clear();
368 /// Set up the animation from each LayoutItems position data.
369 /// Iterates the transition stack, adding an Animator to the core animation.
371 private bool SetupCoreAnimation()
373 // Initialize animation for this layout run.
374 bool animationPending = false;
376 Debug.WriteLineIf( LayoutDebugController,
377 "LayoutController SetupCoreAnimation for:" + _layoutTransitionDataQueue.Count);
379 if (_layoutTransitionDataQueue.Count > 0 ) // Something to animate
383 _coreAnimation = new Animation();
385 _coreAnimation.EndAction = Animation.EndActions.StopFinal;
386 _coreAnimation.Finished += AnimationFinished;
388 // Iterate all items that have been queued for repositioning.
389 foreach (LayoutData layoutPositionData in _layoutTransitionDataQueue)
391 AddAnimatorsToAnimation(layoutPositionData);
394 animationPending = true;
396 // transitions have now been applied, clear stack, ready for new transitions on
397 // next layout traversal.
398 _layoutTransitionDataQueue.Clear();
400 return animationPending;
403 private void SetupAnimationForPosition(LayoutData layoutPositionData, TransitionComponents positionTransitionComponents)
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 )
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 );
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 );
425 private void SetupAnimationForSize(LayoutData layoutPositionData, TransitionComponents sizeTransitionComponents)
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)
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);
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);
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 );
455 void SetupAnimationForCustomTransitions(TransitionList transitionsToAnimate, View view )
457 if (transitionsToAnimate?.Count > 0)
459 foreach (LayoutTransition transition in transitionsToAnimate)
461 if ( transition.AnimatableProperty != AnimatableProperties.Position &&
462 transition.AnimatableProperty != AnimatableProperties.Size )
464 _coreAnimation.AnimateTo(view,
465 transition.AnimatableProperty.ToString(),
466 transition.TargetValue,
467 transition.Animator.Delay,
468 transition.Animator.Duration,
469 transition.Animator.AlphaFunction );
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 );
482 /// Iterate transitions and replace Position Components if replacements found in list.
484 private void FindAndReplaceAnimatorComponentsForProperty(TransitionList sourceTransitionList,
485 AnimatableProperties propertyToMatch,
486 ref TransitionComponents transitionComponentToUpdate)
488 foreach( LayoutTransition transition in sourceTransitionList)
490 if (transition.AnimatableProperty == propertyToMatch)
492 // Matched property to animate is for the propertyToMatch so use provided Animator.
493 transitionComponentToUpdate = transition.Animator;
498 private TransitionComponents CreateDefaultTransitionComponent( int delay, int duration )
500 AlphaFunction alphaFunction = new AlphaFunction(AlphaFunction.BuiltinFunctions.Linear);
501 return new TransitionComponents(delay, duration, alphaFunction);
505 /// Sets up the main animation with the animators for each item (each layoutPositionData structure)
507 private void AddAnimatorsToAnimation( LayoutData layoutPositionData )
509 LayoutTransition positionTransition = new LayoutTransition();
510 LayoutTransition sizeTransition = new LayoutTransition();
511 TransitionCondition conditionForAnimators = layoutPositionData.ConditionForAnimation;
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))
517 conditionForAnimators = TransitionCondition.LayoutChanged;
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);
524 bool matchedCustomTransitions = false;
527 TransitionList transitionsForCurrentCondition = new TransitionList();
528 // Note, Transitions set on View rather than LayoutItem so if the Layout changes the transition persist.
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))
534 // Child has transitions for the condition
535 matchedCustomTransitions = layoutPositionData.Item.Owner.LayoutTransitions.TryGetValue(conditionForAnimators, out transitionsForCurrentCondition);
538 if (!matchedCustomTransitions)
540 // Inherit parent transitions as none already set on View for the condition.
541 ILayoutParent layoutParent = layoutPositionData.Item.GetParent();
542 if (layoutParent !=null)
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))
551 // Copy parent transitions to temporary TransitionList. List contains transitions for the current condition.
552 LayoutTransitionsHelper.CopyTransitions(parentTransitionList,
553 transitionsForCurrentCondition);
559 // Position/Size transitions can be displayed for a layout changing to another layout or an item being added or removed.
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.
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);
572 FindAndReplaceAnimatorComponentsForProperty(transitionsForCurrentCondition,
573 AnimatableProperties.Size,
574 ref sizeTransitionComponents);
576 // Add animators to the core Animation,
578 SetupAnimationForCustomTransitions(transitionsForCurrentCondition, layoutPositionData.Item.Owner);
580 SetupAnimationForPosition(layoutPositionData, positionTransitionComponents);
582 SetupAnimationForSize(layoutPositionData, sizeTransitionComponents);
585 } // class LayoutController
586 } // namespace Tizen.NUI