1 /* Copyright (c) 2021 Samsung Electronics Co., Ltd.
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
7 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 using Tizen.NUI.BaseComponents;
19 using System.Collections.Generic;
20 using System.Collections.ObjectModel;
21 using System.ComponentModel;
22 using System.Diagnostics.CodeAnalysis;
24 namespace Tizen.NUI.Components
27 /// ValueChangedEventArgs is a class to notify changed Picker value argument which will sent to user.
29 /// <since_tizen> 9 </since_tizen>
30 public class ValueChangedEventArgs : EventArgs
33 /// ValueChangedEventArgs default constructor.
34 /// <param name="value">value of Picker.</param>
36 [EditorBrowsable(EditorBrowsableState.Never)]
37 public ValueChangedEventArgs(int value)
43 /// ValueChangedEventArgs default constructor.
44 /// <returns>The current value of Picker.</returns>
46 /// <since_tizen> 9 </since_tizen>
47 public int Value { get; }
52 /// Picker is a class which provides a function that allows the user to select
53 /// a value through a scrolling motion by expressing the specified value as a list.
55 /// <since_tizen> 9 </since_tizen>
56 public partial class Picker : Control
58 //Tizen 6.5 base components Picker guide visible scroll item is 5.
59 private const int scrollVisibleItems = 5;
60 //Dummy item count for loop feature. Max value of scrolling distance in
61 //RPI target is bigger than 20 items height. it can adjust depends on the internal logic and device env.
62 private const int dummyItemsForLoop = 20;
63 private int startScrollOffset;
64 private int itemHeight;
65 private int startScrollY;
68 private int currentValue;
71 private int lastScrollPosion;
72 private bool onAnimation; //Scroller on animation check.
73 private bool onAlignAnimation;
74 private bool displayedValuesUpdate; //User sets displayed value check.
75 private bool needItemUpdate; //min, max or display value updated check.
76 private bool loopEnabled;
77 private ReadOnlyCollection<string> displayedValues;
78 private PickerScroller pickerScroller;
80 private View downLine;
81 private IList<TextLabel> itemList;
83 private TextLabelStyle itemTextLabel;
86 /// Creates a new instance of Picker.
88 /// <since_tizen> 9 </since_tizen>
94 /// Creates a new instance of Picker.
96 /// <param name="style">Creates Picker by special style defined in UX.</param>
97 /// <since_tizen> 9 </since_tizen>
98 public Picker(string style) : base(style)
103 /// Creates a new instance of Picker.
105 /// <param name="pickerStyle">Creates Picker by style customized by user.</param>
106 /// <since_tizen> 9 </since_tizen>
107 public Picker(PickerStyle pickerStyle) : base(pickerStyle)
112 /// Dispose Picker and all children on it.
114 /// <param name="type">Dispose type.</param>
115 [EditorBrowsable(EditorBrowsableState.Never)]
116 protected override void Dispose(DisposeTypes type)
123 if (type == DisposeTypes.Explicit)
125 if (itemList != null)
127 foreach (TextLabel textLabel in itemList)
129 if (pickerScroller) pickerScroller.Remove(textLabel);
130 Utility.Dispose(textLabel);
136 if (pickerScroller != null)
138 Remove(pickerScroller);
139 Utility.Dispose(pickerScroller);
140 pickerScroller = null;
144 Utility.Dispose(upLine);
146 Utility.Dispose(downLine);
153 /// An event emitted when Picker value changed, user can subscribe or unsubscribe to this event handler.
155 /// <since_tizen> 9 </since_tizen>
156 public event EventHandler<ValueChangedEventArgs> ValueChanged;
161 /// The values to be displayed instead of numbers.
163 /// <since_tizen> 9 </since_tizen>
164 public ReadOnlyCollection<String> DisplayedValues
168 return displayedValues;
172 displayedValues = value;
174 needItemUpdate = true;
175 displayedValuesUpdate = true;
182 /// The Current value of Picker.
184 /// <since_tizen> 9 </since_tizen>
185 public int CurrentValue
189 return (int)GetValue(CurrentValueProperty);
193 SetValue(CurrentValueProperty, value);
194 NotifyPropertyChanged();
197 private int InternalCurrentValue
205 if (currentValue == value) return;
207 if (currentValue < minValue) currentValue = minValue;
208 else if (currentValue > maxValue) currentValue = maxValue;
210 currentValue = value;
212 UpdateCurrentValue();
217 /// The max value of Picker.
219 /// <since_tizen> 9 </since_tizen>
224 return (int)GetValue(MaxValueProperty);
228 SetValue(MaxValueProperty, value);
229 NotifyPropertyChanged();
232 private int InternalMaxValue
240 if (maxValue == value) return;
241 if (currentValue > value) currentValue = value;
244 needItemUpdate = true;
251 /// The min value of Picker.
253 /// <since_tizen> 9 </since_tizen>
258 return (int)GetValue(MinValueProperty);
262 SetValue(MinValueProperty, value);
263 NotifyPropertyChanged();
266 private int InternalMinValue
274 if (minValue == value) return;
275 if (currentValue < value) currentValue = value;
278 needItemUpdate = true;
285 [EditorBrowsable(EditorBrowsableState.Never)]
286 public override void OnInitialize()
289 SetAccessibilityConstructor(Role.List);
295 /// Applies style to Picker.
297 /// <param name="viewStyle">The style to apply.</param>
298 [EditorBrowsable(EditorBrowsableState.Never)]
299 public override void ApplyStyle(ViewStyle viewStyle)
301 base.ApplyStyle(viewStyle);
303 var pickerStyle = viewStyle as PickerStyle;
305 if (pickerStyle == null) return;
307 pickerScroller?.SetPickerStyle(pickerStyle);
309 //Apply StartScrollOffset style.
310 if (pickerStyle.StartScrollOffset != null)
312 startScrollOffset = (int)pickerStyle.StartScrollOffset.Height;
315 //Apply ItemTextLabel style.
316 if (pickerStyle.ItemTextLabel != null)
318 if (itemTextLabel == null)
320 itemTextLabel = (TextLabelStyle)pickerStyle.ItemTextLabel.Clone();
324 itemTextLabel.MergeDirectly(pickerStyle.ItemTextLabel);
327 itemHeight = (int)(pickerStyle.ItemTextLabel.Size?.Height ?? 0);
329 if (itemList != null)
330 foreach (TextLabel textLabel in itemList)
331 textLabel.ApplyStyle(pickerStyle.ItemTextLabel);
334 //Apply PickerCenterLine style.
335 if (pickerStyle.Divider != null && upLine != null && downLine != null)
337 upLine.ApplyStyle(pickerStyle.Divider);
338 downLine.ApplyStyle(pickerStyle.Divider);
339 downLine.PositionY = (int)pickerStyle.Divider.PositionY + itemHeight;
342 startScrollY = (itemHeight * dummyItemsForLoop) + startScrollOffset;
343 startY = startScrollOffset;
347 [EditorBrowsable(EditorBrowsableState.Never)]
348 public override void OnRelayout(Vector2 size, RelayoutContainer container)
350 if (size == null) return;
352 if (size.Equals(this.size))
357 this.size = new Vector2(size);
359 if (pickerScroller != null && itemList != null)
361 pickerScroller.ScrollAvailableArea = new Vector2(0, (itemList.Count * itemHeight) - size.Height);
365 private void Initialize()
367 HeightSpecification = LayoutParamPolicies.MatchParent;
369 //Picker Using scroller internally. actually it is a kind of scroller which has infinity loop,
370 //and item center align features.
371 pickerScroller = new PickerScroller()
373 WidthSpecification = LayoutParamPolicies.MatchParent,
374 HeightSpecification = LayoutParamPolicies.MatchParent,
375 ScrollingDirection = ScrollableBase.Direction.Vertical,
376 Layout = new LinearLayout()
378 LinearOrientation = LinearLayout.Orientation.Vertical,
380 //FIXME: Need to expand as many as possible;
381 // When user want to start list middle of the list item. currently confused how to create list before render.
382 ScrollAvailableArea = new Vector2(0, 10000),
383 Name = "pickerScroller",
386 pickerScroller.Scrolling += OnScroll;
387 pickerScroller.ScrollAnimationEnded += OnScrollAnimationEnded;
388 pickerScroller.ScrollAnimationStarted += OnScrollAnimationStarted;
390 itemList = new List<TextLabel>();
392 minValue = maxValue = currentValue = 0;
393 displayedValues = null;
394 //Those many flags for min, max, value method calling sequence dependency.
395 needItemUpdate = true;
396 displayedValuesUpdate = false;
404 private void OnValueChanged()
406 ValueChangedEventArgs eventArgs =
407 new ValueChangedEventArgs(displayedValuesUpdate ? Int32.Parse(itemList[currentValue].Name) : Int32.Parse(itemList[currentValue].Text));
408 ValueChanged?.Invoke(this, eventArgs);
411 private void PageAdjust(float positionY)
413 //Check the scroll is going out to the dummys if so, bring it back to page.
414 if (positionY > -(startScrollY - (itemHeight * 2)))
415 pickerScroller.ScrollTo(-positionY + pageSize, false);
416 else if (positionY < -(startScrollY + pageSize - (itemHeight * 2)))
417 pickerScroller.ScrollTo(-positionY - pageSize, false);
420 private void OnScroll(object sender, ScrollEventArgs e)
422 if (!loopEnabled || onAnimation || onAlignAnimation) return;
424 PageAdjust(e.Position.Y);
427 private void OnScrollAnimationStarted(object sender, ScrollEventArgs e)
432 private void OnScrollAnimationEnded(object sender, ScrollEventArgs e)
434 //Ignore if the scroll position was not changed. (called it from this function)
435 if (lastScrollPosion == (int)e.Position.Y) return;
437 //Calc offset from closest item.
438 int offset = (int)(e.Position.Y + startScrollOffset) % itemHeight;
439 if (offset < -(itemHeight / 2)) offset += itemHeight;
441 lastScrollPosion = (int)(-e.Position.Y + offset);
444 if (onAlignAnimation) {
445 onAlignAnimation = false;
446 if (loopEnabled == true)
448 PageAdjust(e.Position.Y);
450 if (currentValue != ((int)(-e.Position.Y / itemHeight) + 2))
452 currentValue = ((int)(-e.Position.Y / itemHeight) + 2);
459 //Item center align with animation, otherwise changed event emit.
461 onAlignAnimation = true;
462 pickerScroller.ScrollTo(-e.Position.Y + offset, true);
465 if (currentValue != ((int)(-e.Position.Y / itemHeight) + 2))
467 currentValue = ((int)(-e.Position.Y / itemHeight) + 2);
473 //This is UI requirement. It helps where exactly center item is.
474 private void AddLine()
477 downLine = new View();
483 private String GetItemText(bool loopEnabled, int idx)
485 if (!loopEnabled) return " ";
487 if (displayedValuesUpdate) {
488 idx = idx - MinValue;
489 if (idx <= displayedValues.Count) {
490 return displayedValues[idx];
495 return idx.ToString();
499 //FIXME: If textVisual can add in scroller please change it to textVisual for performance
500 [SuppressMessage("Microsoft.Reliability",
501 "CA2000:DisposeObjectsBeforeLosingScope",
502 Justification = "The items are added to itemList and are disposed in Picker.Dispose().")]
503 private void AddPickerItem(bool loopEnabled, int idx)
505 TextLabel temp = new TextLabel(itemTextLabel)
507 WidthSpecification = LayoutParamPolicies.MatchParent,
508 Text = GetItemText(loopEnabled, idx),
509 Name = idx.ToString(),
513 pickerScroller.Add(temp);
516 private void UpdateCurrentValue()
518 // -2 for center align
519 int startItemIdx = (currentValue == 0) ? -2 : currentValue - minValue - 2;
521 if (loopEnabled) startY = ((dummyItemsForLoop + startItemIdx) * itemHeight) + startScrollOffset;
522 // + 2 for non loop picker center align
525 startY = ((2 + startItemIdx) * itemHeight) + startScrollOffset;
526 currentValue = currentValue - minValue + 2;
528 pickerScroller.ScrollTo(startY, false);
531 private void UpdateValueList()
533 if (!needItemUpdate) return;
534 if (minValue > maxValue) return;
536 //FIXME: This is wrong.
537 // But scroller can't update item property after added please fix me.
538 if (itemList.Count > 0) {
540 pickerScroller.RemoveAllChildren();
543 if (maxValue - minValue + 1 >= scrollVisibleItems)
546 //Current scroller can't add at specific index.
547 //So need below calc.
548 int dummyStartIdx = 0;
549 if (maxValue - minValue >= dummyItemsForLoop)
550 dummyStartIdx = maxValue - dummyItemsForLoop + 1;
552 dummyStartIdx = maxValue - (dummyItemsForLoop % (maxValue - minValue + 1)) + 1;
554 //Start add items in scroller. first dummys for scroll anim.
555 for (int i = 0; i < dummyItemsForLoop; i++)
557 if (dummyStartIdx > maxValue) dummyStartIdx = minValue;
558 AddPickerItem(loopEnabled, dummyStartIdx++);
561 for (int i = minValue; i <= maxValue; i++)
563 AddPickerItem(loopEnabled, i);
565 //Last dummys for scroll anim.
566 dummyStartIdx = minValue;
567 for (int i = 0; i < dummyItemsForLoop; i++)
569 if (dummyStartIdx > maxValue) dummyStartIdx = minValue;
570 AddPickerItem(loopEnabled, dummyStartIdx++);
577 for (int i = 0; i < 2; i++)
578 AddPickerItem(loopEnabled, 0);
579 for (int i = minValue; i <= maxValue; i++)
580 AddPickerItem(!loopEnabled, i);
581 for (int i = 0; i < 2; i++)
582 AddPickerItem(loopEnabled, 0);
585 pageSize = itemHeight * (maxValue - minValue + 1);
587 UpdateCurrentValue();
589 //Give a correct scroll area.
592 pickerScroller.ScrollAvailableArea = new Vector2(0, (itemList.Count * itemHeight) - size.Height);
595 needItemUpdate = false;
598 internal class PickerScroller : ScrollableBase
600 private int itemHeight;
601 private int startScrollOffset;
602 private float velocityOfLastPan = 0.0f;
603 private float panAnimationDuration = 0.0f;
604 private float panAnimationDelta = 0.0f;
605 private float decelerationRate = 0.0f;
606 private float logValueOfDeceleration = 0.0f;
607 private delegate float UserAlphaFunctionDelegate(float progress);
608 private UserAlphaFunctionDelegate customScrollAlphaFunction;
610 public PickerScroller() : base()
612 //Default rate is 0.998. this is for reduce scroll animation length.
613 decelerationRate = 0.991f;
614 logValueOfDeceleration = (float)Math.Log(decelerationRate);
617 public void SetPickerStyle(PickerStyle pickerStyle)
619 if (pickerStyle.StartScrollOffset != null)
621 startScrollOffset = (int)pickerStyle.StartScrollOffset.Height;
624 if (pickerStyle.ItemTextLabel?.Size != null)
626 itemHeight = (int)pickerStyle.ItemTextLabel.Size.Height;
629 if (pickerStyle.Size != null)
631 Size = new Size(-1, pickerStyle.Size.Height);
635 private float CustomScrollAlphaFunction(float progress)
637 if (panAnimationDelta == 0)
643 // Parameter "progress" is normalized value. We need to multiply target duration to calculate distance.
644 // Can get real distance using equation of deceleration (check Decelerating function)
645 // After get real distance, normalize it
646 float realDuration = progress * panAnimationDuration;
647 float realDistance = velocityOfLastPan * ((float)Math.Pow(decelerationRate, realDuration) - 1) / logValueOfDeceleration;
648 float result = Math.Min(realDistance / Math.Abs(panAnimationDelta), 1.0f);
654 //Override Decelerating for Picker feature.
655 protected override void Decelerating(float velocity, Animation animation)
657 //Reduce Scroll animation speed.
658 //The picker is to select items in the scroll area, it is not correct to animate
659 //the scroll with very high speed.
661 velocityOfLastPan = Math.Abs(velocity);
663 float currentScrollPosition = -ContentContainer.PositionY;
664 panAnimationDelta = (velocityOfLastPan * decelerationRate) / (1 - decelerationRate);
665 panAnimationDelta = velocity > 0 ? -panAnimationDelta : panAnimationDelta;
667 float destination = -(panAnimationDelta + currentScrollPosition);
668 //Animation destination has to center of the item.
669 float align = destination % itemHeight;
670 destination -= align;
671 destination -= startScrollOffset;
673 float adjustDestination = AdjustTargetPositionOfScrollAnimation(destination);
675 float maxPosition = ScrollAvailableArea != null ? ScrollAvailableArea.Y : 0;
676 float minPosition = ScrollAvailableArea != null ? ScrollAvailableArea.X : 0;
678 if (destination < -maxPosition || destination > minPosition)
680 panAnimationDelta = velocity > 0 ? (currentScrollPosition - minPosition) : (maxPosition - currentScrollPosition);
681 destination = velocity > 0 ? minPosition : -maxPosition;
682 destination = -maxPosition + itemHeight;
684 if (panAnimationDelta == 0)
686 panAnimationDuration = 0.0f;
690 panAnimationDuration = (float)Math.Log((panAnimationDelta * logValueOfDeceleration / velocityOfLastPan + 1), decelerationRate);
695 panAnimationDuration = (float)Math.Log(-DecelerationThreshold * logValueOfDeceleration / velocityOfLastPan) / logValueOfDeceleration;
697 if (adjustDestination != destination)
699 destination = adjustDestination;
700 panAnimationDelta = destination + currentScrollPosition;
701 velocityOfLastPan = Math.Abs(panAnimationDelta * logValueOfDeceleration / ((float)Math.Pow(decelerationRate, panAnimationDuration) - 1));
702 panAnimationDuration = (float)Math.Log(-DecelerationThreshold * logValueOfDeceleration / velocityOfLastPan) / logValueOfDeceleration;
706 customScrollAlphaFunction = new UserAlphaFunctionDelegate(CustomScrollAlphaFunction);
707 animation.DefaultAlphaFunction = new AlphaFunction(customScrollAlphaFunction);
708 animation.Duration = (int)panAnimationDuration;
709 animation.AnimateTo(ContentContainer, "PositionY", (int)destination);