[NUI] refactoring ScrollTo. (#3042) (#3043)
[platform/core/csapi/tizenfx.git] / src / Tizen.NUI.Components / Controls / RecyclerView / CollectionView.cs
1 /* Copyright (c) 2021 Samsung Electronics Co., Ltd.
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  *
15  */
16 using System;
17 using System.Linq;
18 using System.Collections;
19 using System.Collections.Generic;
20 using System.Collections.Specialized;
21 using System.Windows.Input;
22 using System.ComponentModel;
23 using Tizen.NUI.BaseComponents;
24 using Tizen.NUI.Binding;
25
26 namespace Tizen.NUI.Components
27 {
28     /// <summary>
29     /// Selectable RecyclerView that presenting a collection of items with variable layouters.
30     /// </summary>
31     /// <since_tizen> 9 </since_tizen>
32     public class CollectionView : RecyclerView
33     {
34         /// <summary>
35         /// Binding Property of selected item in single selection.
36         /// </summary>
37         /// <since_tizen> 9 </since_tizen>
38         public static readonly BindableProperty SelectedItemProperty =
39             BindableProperty.Create(nameof(SelectedItem), typeof(object), typeof(CollectionView), null,
40                 propertyChanged: (bindable, oldValue, newValue) =>
41                 {
42                     var colView = (CollectionView)bindable;
43                     oldValue = colView.selectedItem;
44                     colView.selectedItem = newValue;
45                     var args = new SelectionChangedEventArgs(oldValue, newValue);
46
47                     foreach (RecyclerViewItem item in colView.ContentContainer.Children.Where((item) => item is RecyclerViewItem))
48                     {
49                         if (item.BindingContext == null) continue;
50                         if (item.BindingContext == oldValue) item.IsSelected = false;
51                         else if (item.BindingContext == newValue) item.IsSelected = true;
52                     }
53
54                     SelectionPropertyChanged(colView, args);
55                 },
56                 defaultValueCreator: (bindable) =>
57                 {
58                     var colView = (CollectionView)bindable;
59                     return colView.selectedItem;
60                 });
61
62         /// <summary>
63         /// Binding Property of selected items list in multiple selection.
64         /// </summary>
65         /// <since_tizen> 9 </since_tizen>
66         public static readonly BindableProperty SelectedItemsProperty =
67             BindableProperty.Create(nameof(SelectedItems), typeof(IList<object>), typeof(CollectionView), null,
68                 propertyChanged: (bindable, oldValue, newValue) =>
69                 {
70                     var colView = (CollectionView)bindable;
71                     var oldSelection = colView.selectedItems ?? selectEmpty;
72                     //FIXME : CoerceSelectedItems calls only isCreatedByXaml
73                     var newSelection = (SelectionList)CoerceSelectedItems(colView, newValue);
74                     colView.selectedItems = newSelection;
75                     colView.SelectedItemsPropertyChanged(oldSelection, newSelection);
76                 },
77                 defaultValueCreator: (bindable) =>
78                 {
79                     var colView = (CollectionView)bindable;
80                     colView.selectedItems = colView.selectedItems ?? new SelectionList(colView);
81                     return colView.selectedItems;
82                 });
83
84         /// <summary>
85         /// Binding Property of selected items list in multiple selection.
86         /// </summary>
87         /// <since_tizen> 9 </since_tizen>
88         public static readonly BindableProperty SelectionModeProperty =
89             BindableProperty.Create(nameof(SelectionMode), typeof(ItemSelectionMode), typeof(CollectionView), ItemSelectionMode.None,
90                 propertyChanged: (bindable, oldValue, newValue) =>
91                 {
92                     var colView = (CollectionView)bindable;
93                     oldValue = colView.selectionMode;
94                     colView.selectionMode = (ItemSelectionMode)newValue;
95                     SelectionModePropertyChanged(colView, oldValue, newValue);
96                 },
97                 defaultValueCreator: (bindable) =>
98                 {
99                     var colView = (CollectionView)bindable;
100                     return colView.selectionMode;
101                 });
102
103
104         private static readonly IList<object> selectEmpty = new List<object>(0);
105         private DataTemplate itemTemplate = null;
106         private IEnumerable itemsSource = null;
107         private ItemsLayouter itemsLayouter = null;
108         private DataTemplate groupHeaderTemplate;
109         private DataTemplate groupFooterTemplate;
110         private bool isGrouped;
111         private bool wasRelayouted = false;
112         private bool needInitalizeLayouter = false;
113         private object selectedItem;
114         private SelectionList selectedItems;
115         private bool suppressSelectionChangeNotification;
116         private ItemSelectionMode selectionMode = ItemSelectionMode.None;
117         private RecyclerViewItem header;
118         private RecyclerViewItem footer;
119         private View focusedView;
120         private int prevFocusedDataIndex = 0;
121         private List<RecyclerViewItem> recycleGroupHeaderCache { get; } = new List<RecyclerViewItem>();
122         private List<RecyclerViewItem> recycleGroupFooterCache { get; } = new List<RecyclerViewItem>();
123         private bool delayedScrollTo;
124         private (float position, bool anim) delayedScrollToParam;
125
126         private bool delayedIndexScrollTo;
127         private (int index, bool anim, ItemScrollTo scrollTo) delayedIndexScrollToParam;
128
129         /// <summary>
130         /// Base constructor.
131         /// </summary>
132         /// <since_tizen> 9 </since_tizen>
133         public CollectionView() : base()
134         {
135             FocusGroup = true;
136             SetKeyboardNavigationSupport(true);
137         }
138
139         /// <summary>
140         /// Base constructor with ItemsSource
141         /// </summary>
142         /// <param name="itemsSource">item's data source</param>
143         /// <since_tizen> 9 </since_tizen>
144         public CollectionView(IEnumerable itemsSource) : this()
145         {
146             ItemsSource = itemsSource;
147         }
148
149         /// <summary>
150         /// Base constructor with ItemsSource, ItemsLayouter and ItemTemplate
151         /// </summary>
152         /// <param name="itemsSource">item's data source</param>
153         /// <param name="layouter">item's layout manager</param>
154         /// <param name="template">item's view template with data bindings</param>
155         [EditorBrowsable(EditorBrowsableState.Never)]
156         public CollectionView(IEnumerable itemsSource, ItemsLayouter layouter, DataTemplate template) : this()
157         {
158             ItemsSource = itemsSource;
159             ItemTemplate = template;
160             ItemsLayouter = layouter;
161         }
162
163         /// <summary>
164         /// Event of Selection changed.
165         /// previous selection list and current selection will be provided.
166         /// </summary>
167         /// <since_tizen> 9 </since_tizen>
168         public event EventHandler<SelectionChangedEventArgs> SelectionChanged;
169
170         /// <summary>
171         /// Align item in the viewport when ScrollTo() calls.
172         /// </summary>
173         /// <since_tizen> 9 </since_tizen>
174         public enum ItemScrollTo
175         {
176             /// <summary>
177             /// Scroll to show item in nearest viewport on scroll direction.
178             /// item is above the scroll viewport, item will be came into front,
179             /// item is under the scroll viewport, item will be came into end,
180             /// item is in the scroll viewport, no scroll.
181             /// </summary>
182             /// <since_tizen> 9 </since_tizen>
183             Nearest,
184             /// <summary>
185             /// Scroll to show item in start of the viewport.
186             /// </summary>
187             /// <since_tizen> 9 </since_tizen>
188             Start,
189             /// <summary>
190             /// Scroll to show item in center of the viewport.
191             /// </summary>
192             /// <since_tizen> 9 </since_tizen>
193             Center,
194             /// <summary>
195             /// Scroll to show item in end of the viewport.
196             /// </summary>
197             /// <since_tizen> 9 </since_tizen>
198             End,
199         }
200
201         /// <summary>
202         /// Item's source data in IEnumerable.
203         /// </summary>
204         /// <since_tizen> 9 </since_tizen>
205         public override IEnumerable ItemsSource
206         {
207             get
208             {
209                 return itemsSource;
210             }
211             set
212             {
213                 if (itemsSource != null)
214                 {
215                     // Clearing old data!
216                     if (itemsSource is INotifyCollectionChanged prevNotifyCollectionChanged)
217                     {
218                         prevNotifyCollectionChanged.CollectionChanged -= CollectionChanged;
219                     }
220                     itemsLayouter?.Clear();
221                     if (selectedItem != null) selectedItem = null;
222                     selectedItems?.Clear();
223                 }
224
225                 itemsSource = value;
226                 if (value == null)
227                 {
228                     InternalItemSource?.Dispose();
229                     InternalItemSource = null;
230                     //layouter.Clear()
231                     return;
232                 }
233                 if (itemsSource is INotifyCollectionChanged newNotifyCollectionChanged)
234                 {
235                     newNotifyCollectionChanged.CollectionChanged += CollectionChanged;
236                 }
237
238                 InternalItemSource?.Dispose();
239                 InternalItemSource = ItemsSourceFactory.Create(this);
240
241                 if (itemsLayouter == null) return;
242
243                 needInitalizeLayouter = true;
244                 Init();
245             }
246         }
247
248         /// <summary>
249         /// DataTemplate for items.
250         /// Create visual contents and binding properties.
251         /// return object type is restricted RecyclerViewItem.
252         /// <seealso cref="Tizen.NUI.Binding.DataTemplate" />
253         /// </summary>
254         /// <since_tizen> 9 </since_tizen>
255         public override DataTemplate ItemTemplate
256         {
257             get
258             {
259                 return itemTemplate;
260             }
261             set
262             {
263                 itemTemplate = value;
264                 if (value == null)
265                 {
266                     //layouter.clear()
267                     return;
268                 }
269
270                 needInitalizeLayouter = true;
271                 Init();
272             }
273         }
274
275         /// <summary>
276         /// Items Layouter.
277         /// Layouting items on the scroll ContentContainer.
278         /// <seealso cref="ItemsLayouter" />
279         /// <seealso cref="LinearLayouter" />
280         /// <seealso cref="GridLayouter" />
281         /// </summary>
282         /// <since_tizen> 9 </since_tizen>
283         public virtual ItemsLayouter ItemsLayouter
284         {
285             get
286             {
287                 return itemsLayouter;
288             }
289             set
290             {
291                 itemsLayouter = value;
292                 base.InternalItemsLayouter = ItemsLayouter;
293                 if (value == null)
294                 {
295                     needInitalizeLayouter = false;
296                     return;
297                 }
298
299                 needInitalizeLayouter = true;
300
301                 var styleName = "Tizen.NUI.Components." + (itemsLayouter is LinearLayouter? "LinearLayouter" : (itemsLayouter is GridLayouter ? "GridLayouter" : "ItemsLayouter"));
302                 ViewStyle layouterStyle = ThemeManager.GetStyle(styleName);
303                 if (layouterStyle != null)
304                 {
305                     itemsLayouter.Padding = new Extents(layouterStyle.Padding);
306                 }
307                 Init();
308             }
309         }
310
311         /// <summary>
312         /// Scrolling direction to display items layout.
313         /// </summary>
314         /// <since_tizen> 9 </since_tizen>
315         public new Direction ScrollingDirection
316         {
317             get
318             {
319                 return base.ScrollingDirection;
320             }
321             set
322             {
323                 if (base.ScrollingDirection != value)
324                 {
325                     base.ScrollingDirection = value;
326                     needInitalizeLayouter = true;
327                     Init();
328                 }
329             }
330         }
331
332         /// <summary>
333         /// Selected item in single selection.
334         /// </summary>
335         /// <since_tizen> 9 </since_tizen>
336         public object SelectedItem
337         {
338             get => GetValue(SelectedItemProperty);
339             set => SetValue(SelectedItemProperty, value);
340         }
341
342         /// <summary>
343         /// Selected items list in multiple selection.
344         /// </summary>
345         /// <since_tizen> 9 </since_tizen>
346         public IList<object> SelectedItems
347         {
348             get => (IList<object>)GetValue(SelectedItemsProperty);
349             // set => SetValue(SelectedItemsProperty, new SelectionList(this, value));
350         }
351
352         /// <summary>
353         /// Selection mode to handle items selection. See ItemSelectionMode for details.
354         /// </summary>
355         /// <since_tizen> 9 </since_tizen>
356         public ItemSelectionMode SelectionMode
357         {
358             get => (ItemSelectionMode)GetValue(SelectionModeProperty);
359             set => SetValue(SelectionModeProperty, value);
360         }
361
362         /// <summary>
363         /// Command of selection changed.
364         /// </summary>
365         [EditorBrowsable(EditorBrowsableState.Never)]
366         public ICommand SelectionChangedCommand { set; get; }
367
368         /// <summary>
369         /// Command parameter of selection changed.
370         /// </summary>
371         [EditorBrowsable(EditorBrowsableState.Never)]
372         public object SelectionChangedCommandParameter { set; get; }
373
374         /// <summary>
375         /// Header item placed in top-most position.
376         /// </summary>
377         /// <remarks>Please note that, internal index will be increased by header.</remarks>
378         /// <since_tizen> 9 </since_tizen>
379         public RecyclerViewItem Header
380         {
381             get => header;
382             set
383             {
384                 if (header != null)
385                 {
386                     //ContentContainer.Remove(header);
387                     Utility.Dispose(header);
388                 }
389                 if (value != null)
390                 {
391                     value.Index = 0;
392                     value.ParentItemsView = this;
393                     value.IsHeader = true;
394                     ContentContainer.Add(value);
395                 }
396                 header = value;
397                 needInitalizeLayouter = true;
398                 Init();
399             }
400         }
401
402         /// <summary>
403         /// Footer item placed in bottom-most position.
404         /// </summary>
405         /// <remarks>Please note that, internal index will be increased by footer.</remarks>
406         /// <since_tizen> 9 </since_tizen>
407         public RecyclerViewItem Footer
408         {
409             get => footer;
410             set
411             {
412                 if (footer != null)
413                 {
414                     //ContentContainer.Remove(footer);
415                     Utility.Dispose(footer);
416                 }
417                 if (value != null)
418                 {
419                     value.Index = InternalItemSource?.Count ?? 0;
420                     value.ParentItemsView = this;
421                     value.IsFooter = true;
422                     ContentContainer.Add(value);
423                 }
424                 footer = value;
425                 needInitalizeLayouter = true;
426                 Init();
427             }
428         }
429
430         /// <summary>
431         /// Enable groupable view.
432         /// </summary>
433         [EditorBrowsable(EditorBrowsableState.Never)]
434         public bool IsGrouped
435         {
436             get => isGrouped;
437             set
438             {
439                 isGrouped = value;
440                 needInitalizeLayouter = true;
441                 //Need to re-intialize Internal Item Source.
442                 if (InternalItemSource != null)
443                 {
444                     InternalItemSource.Dispose();
445                     InternalItemSource = null;
446                 }
447                 if (ItemsSource != null)
448                     InternalItemSource = ItemsSourceFactory.Create(this);
449                 Init();
450             }
451         }
452
453         /// <summary>
454         ///  DataTemplate of group header.
455         /// </summary>
456         /// <remarks>Please note that, internal index will be increased by group header.
457         /// GroupHeaderTemplate is essential for groupable view.</remarks>        
458         [EditorBrowsable(EditorBrowsableState.Never)]
459         public DataTemplate GroupHeaderTemplate
460         {
461             get
462             {
463                 return groupHeaderTemplate;
464             }
465             set
466             {
467                 groupHeaderTemplate = value;
468                 needInitalizeLayouter = true;
469                 Init();
470             }
471         }
472
473         /// <summary>
474         /// DataTemplate of group footer. Group feature is not supported yet.
475         /// </summary>
476         /// <remarks>Please note that, internal index will be increased by group footer.</remarks>
477         [EditorBrowsable(EditorBrowsableState.Never)]
478         public DataTemplate GroupFooterTemplate
479         {
480             get
481             {
482                 return groupFooterTemplate;
483             }
484             set
485             {
486                 groupFooterTemplate = value;
487                 needInitalizeLayouter = true;
488                 Init();
489             }
490         }
491
492         /// <summary>
493         /// Internal encapsulated items data source.
494         /// </summary>
495         internal new IGroupableItemSource InternalItemSource
496         {
497             get
498             {
499                 return (base.InternalItemSource as IGroupableItemSource);
500             }
501             set
502             {
503                 base.InternalItemSource = value;
504             }
505         }
506
507         /// <summary>
508         /// Size strategy of measuring scroll content. see details in ItemSizingStrategy.
509         /// </summary>
510         [EditorBrowsable(EditorBrowsableState.Never)]
511         internal ItemSizingStrategy SizingStrategy { get; set; }
512
513         /// <inheritdoc/>
514         /// <since_tizen> 9 </since_tizen>
515         public override void OnRelayout(Vector2 size, RelayoutContainer container)
516         {
517             base.OnRelayout(size, container);
518
519             wasRelayouted = true;
520             if (needInitalizeLayouter) Init();
521         }
522
523         /// <inheritdoc/>
524         [EditorBrowsable(EditorBrowsableState.Never)]
525         public override void NotifyDataSetChanged()
526         {
527             if (selectedItem != null)
528             {
529                 selectedItem = null;
530             }
531             if (selectedItems != null)
532             {
533                 selectedItems.Clear();
534             }
535
536             base.NotifyDataSetChanged();
537         }
538
539         /// <inheritdoc/>
540         [EditorBrowsable(EditorBrowsableState.Never)]
541         public override View GetNextFocusableView(View currentFocusedView, View.FocusDirection direction, bool loopEnabled)
542         {
543             View nextFocusedView = null;
544
545             if (focusedView == null)
546             {
547                 // If focusedView is null, find child which has previous data index
548                 if (ContentContainer.Children.Count > 0 && InternalItemSource.Count > 0)
549                 {
550                     for (int i = 0; i < ContentContainer.Children.Count; i++)
551                     {
552                         RecyclerViewItem item = Children[i] as RecyclerViewItem;
553                         if (item?.Index == prevFocusedDataIndex)
554                         {
555                             nextFocusedView = item;
556                             break;
557                         }
558                     }
559                 }
560             }
561             else
562             {
563                 // If this is not first focus, request next focus to Layouter
564                 nextFocusedView = ItemsLayouter.RequestNextFocusableView(currentFocusedView, direction, loopEnabled);
565             }
566
567             if (nextFocusedView != null)
568             {
569                 // Check next focused view is inside of visible area.
570                 // If it is not, move scroll position to make it visible.
571                 Position scrollPosition = ContentContainer.CurrentPosition;
572                 float targetPosition = -(ScrollingDirection == Direction.Horizontal ? scrollPosition.X : scrollPosition.Y);
573
574                 float left = nextFocusedView.Position.X;
575                 float right = nextFocusedView.Position.X + nextFocusedView.Size.Width;
576                 float top = nextFocusedView.Position.Y;
577                 float bottom = nextFocusedView.Position.Y + nextFocusedView.Size.Height;
578
579                 float visibleRectangleLeft = -scrollPosition.X;
580                 float visibleRectangleRight = -scrollPosition.X + Size.Width;
581                 float visibleRectangleTop = -scrollPosition.Y;
582                 float visibleRectangleBottom = -scrollPosition.Y + Size.Height;
583
584                 if (ScrollingDirection == Direction.Horizontal)
585                 {
586                     if ((direction == View.FocusDirection.Left || direction == View.FocusDirection.Up) && left < visibleRectangleLeft)
587                     {
588                         targetPosition = left;
589                     }
590                     else if ((direction == View.FocusDirection.Right || direction == View.FocusDirection.Down) && right > visibleRectangleRight)
591                     {
592                         targetPosition = right - Size.Width;
593                     }
594                 }
595                 else
596                 {
597                     if ((direction == View.FocusDirection.Up || direction == View.FocusDirection.Left) && top < visibleRectangleTop)
598                     {
599                         targetPosition = top;
600                     }
601                     else if ((direction == View.FocusDirection.Down || direction == View.FocusDirection.Right) && bottom > visibleRectangleBottom)
602                     {
603                         targetPosition = bottom - Size.Height;
604                     }
605                 }
606
607                 focusedView = nextFocusedView;
608                 prevFocusedDataIndex = (nextFocusedView as RecyclerViewItem)?.Index ?? -1;
609
610                 ScrollTo(targetPosition, true);
611             }
612             else
613             {
614                 // If nextView is null, it means that we should move focus to outside of Control.
615                 // Return FocusableView depending on direction.
616                 switch (direction)
617                 {
618                     case View.FocusDirection.Left:
619                         {
620                             nextFocusedView = LeftFocusableView;
621                             break;
622                         }
623                     case View.FocusDirection.Right:
624                         {
625                             nextFocusedView = RightFocusableView;
626                             break;
627                         }
628                     case View.FocusDirection.Up:
629                         {
630                             nextFocusedView = UpFocusableView;
631                             break;
632                         }
633                     case View.FocusDirection.Down:
634                         {
635                             nextFocusedView = DownFocusableView;
636                             break;
637                         }
638                 }
639
640                 if (nextFocusedView != null)
641                 {
642                     focusedView = null;
643                 }
644                 else
645                 {
646                     //If FocusableView doesn't exist, not move focus.
647                     nextFocusedView = focusedView;
648                 }
649             }
650
651             return nextFocusedView;
652         }
653
654         /// <summary>
655         /// Update selected items list in multiple selection.
656         /// </summary>
657         /// <param name="newSelection">updated selection list by user</param>
658         /// <since_tizen> 9 </since_tizen>
659         public void UpdateSelectedItems(IList<object> newSelection)
660         {
661             var oldSelection = new List<object>(SelectedItems);
662
663             suppressSelectionChangeNotification = true;
664
665             SelectedItems.Clear();
666
667             if (newSelection?.Count > 0)
668             {
669                 for (int n = 0; n < newSelection.Count; n++)
670                 {
671                     SelectedItems.Add(newSelection[n]);
672                 }
673             }
674
675             suppressSelectionChangeNotification = false;
676
677             SelectedItemsPropertyChanged(oldSelection, newSelection);
678         }
679
680         /// <summary>
681         /// Scroll to specific position with or without animation.
682         /// </summary>
683         /// <param name="position">Destination.</param>
684         /// <param name="animate">Scroll with or without animation</param>
685         /// <since_tizen> 9 </since_tizen>
686         public new void ScrollTo(float position, bool animate)
687         {
688             if (ItemsLayouter == null) throw new Exception("Item Layouter must exist.");
689             if ((InternalItemSource == null) || needInitalizeLayouter)
690             {
691                 delayedScrollTo = true;
692                 delayedScrollToParam = (position, animate);
693                 return;
694             }
695
696             base.ScrollTo(position, animate);
697         }
698
699         /// <summary>
700         /// Scrolls to the item at the specified index.
701         /// </summary>
702         /// <param name="index">Index of item.</param>
703         [EditorBrowsable(EditorBrowsableState.Never)]
704         public new void ScrollToIndex(int index)
705         {
706             ScrollTo(index, true, ItemScrollTo.Start);
707         }
708
709         /// <summary>
710         /// Scroll to specific item's aligned position with or without animation.
711         /// </summary>
712         /// <param name="index">Target item index of dataset.</param>
713         /// <param name="animate">Boolean flag of animation.</param>
714         /// <param name="align">Align state of item. See details in <see cref="ItemScrollTo"/>.</param>
715         /// <since_tizen> 9 </since_tizen>
716         public virtual void ScrollTo(int index, bool animate = false, ItemScrollTo align = ItemScrollTo.Nearest)
717         {
718             if (ItemsLayouter == null) throw new Exception("Item Layouter must exist.");
719             if ((InternalItemSource == null) || needInitalizeLayouter)
720             {
721                 delayedIndexScrollTo = true;
722                 delayedIndexScrollToParam = (index, animate, align);
723                 return;
724             }
725             if (index < 0 || index >= InternalItemSource.Count)
726             {
727                 throw new Exception("index is out of boundary. index should be a value between (0, " + InternalItemSource.Count.ToString() + ").");
728             }
729
730             float scrollPos, curPos, curSize, curItemSize;
731             (float x, float y) = ItemsLayouter.GetItemPosition(index);
732             (float width, float height) = ItemsLayouter.GetItemSize(index);
733             if (ScrollingDirection == Direction.Horizontal)
734             {
735                 scrollPos = x;
736                 curPos = ScrollPosition.X;
737                 curSize = Size.Width;
738                 curItemSize = width;
739             }
740             else
741             {
742                 scrollPos = y;
743                 curPos = ScrollPosition.Y;
744                 curSize = Size.Height;
745                 curItemSize = height;
746             }
747
748             //Console.WriteLine("[NUI] ScrollTo [{0}:{1}], curPos{2}, itemPos{3}, curSize{4}, itemSize{5}", InternalItemSource.GetPosition(item), align, curPos, scrollPos, curSize, curItemSize);
749             switch (align)
750             {
751                 case ItemScrollTo.Start:
752                     //nothing necessary.
753                     break;
754                 case ItemScrollTo.Center:
755                     scrollPos = scrollPos - (curSize / 2) + (curItemSize / 2);
756                     break;
757                 case ItemScrollTo.End:
758                     scrollPos = scrollPos - curSize + curItemSize;
759                     break;
760                 case ItemScrollTo.Nearest:
761                     if (scrollPos < curPos - curItemSize)
762                     {
763                         // item is placed before the current screen. scrollTo.Top
764                     }
765                     else if (scrollPos >= curPos + curSize + curItemSize)
766                     {
767                         // item is placed after the current screen. scrollTo.End
768                         scrollPos = scrollPos - curSize + curItemSize;
769                     }
770                     else
771                     {
772                         // item is in the scroller. ScrollTo() is ignored.
773                         return;
774                     }
775                     break;
776             }
777
778             //Console.WriteLine("[NUI] ScrollTo [{0}]-------------------", scrollPos);
779             base.ScrollTo(scrollPos, animate);
780         }
781
782         /// <summary>
783         /// Apply style to CollectionView
784         /// </summary>
785         /// <param name="viewStyle">The style to apply.</param>
786         [EditorBrowsable(EditorBrowsableState.Never)]
787         public override void ApplyStyle(ViewStyle viewStyle)
788         {
789             base.ApplyStyle(viewStyle);
790             if (viewStyle != null)
791             {
792                 //Extension = RecyclerViewItemStyle.CreateExtension();
793             }
794             if (itemsLayouter != null)
795             {
796                 string styleName = "Tizen.NUI.Compoenents." + (itemsLayouter is LinearLayouter? "LinearLayouter" : (itemsLayouter is GridLayouter ? "GridLayouter" : "ItemsLayouter"));
797                 ViewStyle layouterStyle = ThemeManager.GetStyle(styleName);
798                 if (layouterStyle != null)
799                     itemsLayouter.Padding = new Extents(layouterStyle.Padding);
800             }
801         }
802
803         // Realize and Decorate the item.
804         internal override RecyclerViewItem RealizeItem(int index)
805         {
806             RecyclerViewItem item;
807             if (index == 0 && Header != null)
808             {
809                 Header.Show();
810                 return Header;
811             }
812
813             if (index == InternalItemSource.Count - 1 && Footer != null)
814             {
815                 Footer.Show();
816                 return Footer;
817             }
818
819             if (isGrouped)
820             {
821                 var context = InternalItemSource.GetItem(index);
822                 if (InternalItemSource.IsGroupHeader(index))
823                 {
824                     DataTemplate templ = (groupHeaderTemplate as DataTemplateSelector)?.SelectDataTemplate(context, this) ?? groupHeaderTemplate;
825
826                     RecyclerViewItem groupHeader = PopRecycleGroupCache(templ, true);
827                     if (groupHeader == null)
828                     {
829                         groupHeader = (RecyclerViewItem)DataTemplateExtensions.CreateContent(groupHeaderTemplate, context, this);
830
831                         groupHeader.Template = templ;
832                         groupHeader.isGroupHeader = true;
833                         groupHeader.isGroupFooter = false;
834                         ContentContainer.Add(groupHeader);
835                     }
836                     groupHeader.ParentItemsView = this;
837                     groupHeader.Index = index;
838                     groupHeader.ParentGroup = context;
839                     groupHeader.BindingContext = context;
840                     //group selection?
841                     item = groupHeader;
842                 }
843                 else if (InternalItemSource.IsGroupFooter(index))
844                 {
845                     DataTemplate templ = (groupFooterTemplate as DataTemplateSelector)?.SelectDataTemplate(context, this) ?? groupFooterTemplate;
846
847                     RecyclerViewItem groupFooter = PopRecycleGroupCache(templ, false);
848                     if (groupFooter == null)
849                     {
850                         groupFooter = (RecyclerViewItem)DataTemplateExtensions.CreateContent(groupFooterTemplate, context, this);
851
852                         groupFooter.Template = templ;
853                         groupFooter.isGroupHeader = false;
854                         groupFooter.isGroupFooter = true;
855                         ContentContainer.Add(groupFooter);
856                     }
857                     groupFooter.ParentItemsView = this;
858                     groupFooter.Index = index;
859                     groupFooter.ParentGroup = context;
860                     groupFooter.BindingContext = context;
861
862                     //group selection?
863                     item = groupFooter;
864                 }
865                 else
866                 {
867                     item = base.RealizeItem(index);
868                     item.ParentGroup = InternalItemSource.GetGroupParent(index);
869                 }
870             }
871             else
872             {
873                 item = base.RealizeItem(index);
874             }
875
876             switch (SelectionMode)
877             {
878                 case ItemSelectionMode.Single:
879                 case ItemSelectionMode.SingleAlways:
880                     if (item.BindingContext != null && item.BindingContext == SelectedItem)
881                     {
882                         item.IsSelected = true;
883                     }
884                     break;
885
886                 case ItemSelectionMode.Multiple:
887                     if ((item.BindingContext != null) && (SelectedItems?.Contains(item.BindingContext) ?? false))
888                     {
889                         item.IsSelected = true;
890                     }
891                     break;
892                 case ItemSelectionMode.None:
893                     item.IsSelectable = false;
894                     break;
895             }
896             return item;
897         }
898
899         // Unrealize and caching the item.
900         internal override void UnrealizeItem(RecyclerViewItem item, bool recycle = true)
901         {
902             if (item == null) return;
903             if (item == Header)
904             {
905                 item.Hide();
906                 return;
907             }
908             if (item == Footer)
909             {
910                 item.Hide();
911                 return;
912             }
913             if (item.isGroupHeader || item.isGroupFooter)
914             {
915                 item.Index = -1;
916                 item.ParentItemsView = null;
917                 item.BindingContext = null; 
918                 item.IsPressed = false;
919                 item.IsSelected = false;
920                 item.IsEnabled = true;
921                 item.UpdateState();
922                 //item.Relayout -= OnItemRelayout;
923                 if (!recycle || !PushRecycleGroupCache(item))
924                     Utility.Dispose(item);
925                 return;
926             }
927
928             base.UnrealizeItem(item, recycle);
929         }
930
931         internal void SelectedItemsPropertyChanged(IList<object> oldSelection, IList<object> newSelection)
932         {
933             if (suppressSelectionChangeNotification)
934             {
935                 return;
936             }
937
938             foreach (RecyclerViewItem item in ContentContainer.Children.Where((item) => item is RecyclerViewItem))
939             {
940                 if (item.BindingContext == null) continue;
941                 if (newSelection.Contains(item.BindingContext))
942                 {
943                     if (!item.IsSelected) item.IsSelected = true;
944                 }
945                 else
946                 {
947                     if (item.IsSelected) item.IsSelected = false;
948                 }
949             }
950             SelectionPropertyChanged(this, new SelectionChangedEventArgs(oldSelection, newSelection));
951
952             OnPropertyChanged(SelectedItemsProperty.PropertyName);
953         }
954
955         /// <summary>
956         /// Internal selection callback.
957         /// </summary>
958         /// <since_tizen> 9 </since_tizen>
959         protected virtual void OnSelectionChanged(SelectionChangedEventArgs args)
960         {
961             //Selection Callback
962         }
963
964         /// <summary>
965         /// Adjust scrolling position by own scrolling rules.
966         /// Override this function when developer wants to change destination of flicking.(e.g. always snap to center of item)
967         /// </summary>
968         /// <param name="position">Scroll position which is calculated by ScrollableBase</param>
969         /// <returns>Adjusted scroll destination</returns>
970         [EditorBrowsable(EditorBrowsableState.Never)]
971         protected override float AdjustTargetPositionOfScrollAnimation(float position)
972         {
973             // Destination is depending on implementation of layout manager.
974             // Get destination from layout manager.
975             return ItemsLayouter?.CalculateCandidateScrollPosition(position) ?? position;
976         }
977
978         /// <summary>
979         /// OnScroll event callback. Requesting layout to the layouter with given scrollPosition.
980         /// </summary>
981         /// <param name="source">Scroll source object</param>
982         /// <param name="args">Scroll event argument</param>
983         /// <since_tizen> 9 </since_tizen>
984         protected override void OnScrolling(object source, ScrollEventArgs args)
985         {
986             if (disposed) return;
987
988             if (needInitalizeLayouter && (ItemsLayouter != null))
989             {
990                 ItemsLayouter.Initialize(this);
991                 needInitalizeLayouter = false;
992             }
993
994             base.OnScrolling(source, args);
995         }
996
997         /// <summary>
998         /// Dispose ItemsView and all children on it.
999         /// </summary>
1000         /// <param name="type">Dispose type.</param>
1001         /// <since_tizen> 9 </since_tizen>
1002         protected override void Dispose(DisposeTypes type)
1003         {
1004             if (disposed)
1005             {
1006                 return;
1007             }
1008
1009             if (type == DisposeTypes.Explicit)
1010             {
1011                 // From now on, no need to use this properties,
1012                 // so remove reference, to push it into garbage collector.
1013
1014                 // Arugable to disposing user-created members.
1015                 /*
1016                 if (Header != null)
1017                 {
1018                     Utility.Dispose(Header);
1019                     Header = null;
1020                 }
1021                 if (Footer != null)
1022                 {
1023                     Utility.Dispose(Footer);
1024                     Footer = null;
1025                 }
1026                 */
1027
1028                 groupHeaderTemplate = null;
1029                 groupFooterTemplate = null;
1030
1031                 if (selectedItem != null) 
1032                 {
1033                     selectedItem = null;
1034                 }
1035                 if (selectedItems != null)
1036                 {
1037                     selectedItems.Clear();
1038                     selectedItems = null;
1039                 }
1040                 if (InternalItemSource != null)
1041                 {
1042                     InternalItemSource.Dispose();
1043                     InternalItemSource = null;
1044                 }
1045                 if (recycleGroupHeaderCache != null)
1046                 {
1047                     foreach(RecyclerViewItem item in recycleGroupHeaderCache)
1048                     {
1049                         UnrealizeItem(item, false);
1050                     }
1051                     recycleGroupHeaderCache.Clear();
1052                 }
1053                 if (recycleGroupFooterCache != null)
1054                 {
1055                     foreach(RecyclerViewItem item in recycleGroupFooterCache)
1056                     {
1057                         UnrealizeItem(item, false);
1058                     }
1059                     recycleGroupFooterCache.Clear();
1060                 }
1061             }
1062
1063             base.Dispose(type);
1064         }
1065
1066         private static void SelectionPropertyChanged(CollectionView colView, SelectionChangedEventArgs args)
1067         {
1068             var command = colView.SelectionChangedCommand;
1069
1070             if (command != null)
1071             {
1072                 var commandParameter = colView.SelectionChangedCommandParameter;
1073
1074                 if (command.CanExecute(commandParameter))
1075                 {
1076                     command.Execute(commandParameter);
1077                 }
1078             }
1079             colView.SelectionChanged?.Invoke(colView, args);
1080             colView.OnSelectionChanged(args);
1081         }
1082
1083         private static object CoerceSelectedItems(BindableObject bindable, object value)
1084         {
1085             if (value == null)
1086             {
1087                 return new SelectionList((CollectionView)bindable);
1088             }
1089
1090             if (value is SelectionList)
1091             {
1092                 return value;
1093             }
1094
1095             return new SelectionList((CollectionView)bindable, value as IList<object>);
1096         }
1097
1098         private static void SelectionModePropertyChanged(BindableObject bindable, object oldValue, object newValue)
1099         {
1100             var colView = (CollectionView)bindable;
1101
1102             var oldMode = (ItemSelectionMode)oldValue;
1103             var newMode = (ItemSelectionMode)newValue;
1104
1105             IList<object> previousSelection = new List<object>();
1106             IList<object> newSelection = new List<object>();
1107
1108             switch (oldMode)
1109             {
1110                 case ItemSelectionMode.None:
1111                     break;
1112                 case ItemSelectionMode.Single:
1113                     if (colView.SelectedItem != null)
1114                     {
1115                         previousSelection.Add(colView.SelectedItem);
1116                     }
1117                     break;
1118                 case ItemSelectionMode.Multiple:
1119                     previousSelection = colView.SelectedItems;
1120                     break;
1121             }
1122
1123             switch (newMode)
1124             {
1125                 case ItemSelectionMode.None:
1126                     break;
1127                 case ItemSelectionMode.Single:
1128                     if (colView.SelectedItem != null)
1129                     {
1130                         newSelection.Add(colView.SelectedItem);
1131                     }
1132                     break;
1133                 case ItemSelectionMode.Multiple:
1134                     newSelection = colView.SelectedItems;
1135                     break;
1136             }
1137
1138             if (previousSelection.Count == newSelection.Count)
1139             {
1140                 if (previousSelection.Count == 0 || (previousSelection[0] == newSelection[0]))
1141                 {
1142                     // Both selections are empty or have the same single item; no reason to signal a change
1143                     return;
1144                 }
1145             }
1146
1147             var args = new SelectionChangedEventArgs(previousSelection, newSelection);
1148             SelectionPropertyChanged(colView, args);
1149         }
1150
1151         private void Init()
1152         {
1153             if (ItemsSource == null) return;
1154             if (ItemsLayouter == null) return;
1155             if (ItemTemplate == null) return;
1156
1157             if (disposed) return;
1158             if (needInitalizeLayouter)
1159             {
1160                 if (InternalItemSource == null) return;
1161
1162                 InternalItemSource.HasHeader = (header != null);
1163                 InternalItemSource.HasFooter = (footer != null);
1164             }
1165
1166             if (!wasRelayouted) return;
1167
1168             if (needInitalizeLayouter)
1169             {
1170                 ItemsLayouter.Initialize(this);
1171                 needInitalizeLayouter = false;
1172             }
1173             ItemsLayouter.RequestLayout(0.0f, true);
1174
1175             if (delayedScrollTo)
1176             {
1177                 delayedScrollTo = false;
1178                 ScrollTo(delayedScrollToParam.position, delayedScrollToParam.anim);
1179             }
1180
1181             if (delayedIndexScrollTo)
1182             {
1183                 delayedIndexScrollTo = false;
1184                 ScrollTo(delayedIndexScrollToParam.index, delayedIndexScrollToParam.anim, delayedIndexScrollToParam.scrollTo);
1185             }
1186
1187             if (ScrollingDirection == Direction.Horizontal)
1188             {
1189                 ContentContainer.SizeWidth = ItemsLayouter.CalculateLayoutOrientationSize();
1190             }
1191             else
1192             {
1193                 ContentContainer.SizeHeight = ItemsLayouter.CalculateLayoutOrientationSize();
1194             }
1195         }
1196
1197         private bool PushRecycleGroupCache(RecyclerViewItem item)
1198         {
1199             if (item == null) throw new ArgumentNullException(nameof(item));
1200             if (RecycleCache.Count >= 20) return false;
1201             if (item.Template == null) return false;
1202             if (item.isGroupHeader)
1203             {
1204                 recycleGroupHeaderCache.Add(item);
1205             }
1206             else if (item.isGroupFooter)
1207             {
1208                 recycleGroupFooterCache.Add(item);
1209             }
1210             else return false;
1211             item.Hide();
1212             item.Index = -1;
1213             return true;
1214         }
1215
1216         private RecyclerViewItem PopRecycleGroupCache(DataTemplate Template, bool isHeader)
1217         {
1218             RecyclerViewItem viewItem = null;
1219
1220             var Cache = (isHeader ? recycleGroupHeaderCache : recycleGroupFooterCache);
1221             for (int i = 0; i < Cache.Count; i++)
1222             {
1223                 viewItem = Cache[i];
1224                 if (Template == viewItem.Template) break;
1225             }
1226
1227             if (viewItem != null)
1228             {
1229                 Cache.Remove(viewItem);
1230                 viewItem.Show();
1231             }
1232             return viewItem;
1233         }
1234         private void CollectionChanged(object sender, NotifyCollectionChangedEventArgs args)
1235         {
1236             switch (args.Action)
1237             {
1238                 case NotifyCollectionChangedAction.Add:
1239                     break;
1240                 case NotifyCollectionChangedAction.Remove:
1241                     // Clear removed items.
1242                     if (args.OldItems != null)
1243                     {
1244                         if (args.OldItems.Contains(selectedItem))
1245                         {
1246                             selectedItem = null;
1247                         }
1248                         
1249                         if (selectedItems != null)
1250                         {
1251                             foreach (object removed in args.OldItems)
1252                             {
1253                                 if (selectedItems.Contains(removed))
1254                                 {
1255                                     selectedItems.Remove(removed);
1256                                 }
1257                             }
1258                         }
1259                     }
1260                     break;
1261                 case NotifyCollectionChangedAction.Replace:
1262                     break;
1263                 case NotifyCollectionChangedAction.Move:
1264                     break;
1265                 case NotifyCollectionChangedAction.Reset:
1266                     break;
1267                 default:
1268                     throw new ArgumentOutOfRangeException(nameof(args));
1269             }
1270         }
1271
1272     }
1273 }