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