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 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
193 if (currentValue == value) return;
195 if (currentValue < minValue) currentValue = minValue;
196 else if (currentValue > maxValue) currentValue = maxValue;
198 currentValue = value;
200 UpdateCurrentValue();
205 /// The max value of Picker.
207 /// <since_tizen> 9 </since_tizen>
216 if (maxValue == value) return;
217 if (currentValue > value) currentValue = value;
220 needItemUpdate = true;
227 /// The min value of Picker.
229 /// <since_tizen> 9 </since_tizen>
238 if (minValue == value) return;
239 if (currentValue < value) currentValue = value;
242 needItemUpdate = true;
249 [EditorBrowsable(EditorBrowsableState.Never)]
250 public override void OnInitialize()
253 SetAccessibilityConstructor(Role.List);
259 /// Applies style to Picker.
261 /// <param name="viewStyle">The style to apply.</param>
262 [EditorBrowsable(EditorBrowsableState.Never)]
263 public override void ApplyStyle(ViewStyle viewStyle)
265 base.ApplyStyle(viewStyle);
267 var pickerStyle = viewStyle as PickerStyle;
269 if (pickerStyle == null) return;
271 pickerScroller?.SetPickerStyle(pickerStyle);
273 //Apply StartScrollOffset style.
274 if (pickerStyle.StartScrollOffset != null)
276 startScrollOffset = (int)pickerStyle.StartScrollOffset.Height;
279 //Apply ItemTextLabel style.
280 if (pickerStyle.ItemTextLabel != null)
282 if (itemTextLabel == null)
284 itemTextLabel = (TextLabelStyle)pickerStyle.ItemTextLabel.Clone();
288 itemTextLabel.MergeDirectly(pickerStyle.ItemTextLabel);
291 itemHeight = (int)(pickerStyle.ItemTextLabel.Size?.Height ?? 0);
293 if (itemList != null)
294 foreach (TextLabel textLabel in itemList)
295 textLabel.ApplyStyle(pickerStyle.ItemTextLabel);
298 //Apply PickerCenterLine style.
299 if (pickerStyle.Divider != null && upLine != null && downLine != null)
301 upLine.ApplyStyle(pickerStyle.Divider);
302 downLine.ApplyStyle(pickerStyle.Divider);
303 downLine.PositionY = (int)pickerStyle.Divider.PositionY + itemHeight;
306 startScrollY = (itemHeight * dummyItemsForLoop) + startScrollOffset;
307 startY = startScrollOffset;
311 [EditorBrowsable(EditorBrowsableState.Never)]
312 public override void OnRelayout(Vector2 size, RelayoutContainer container)
314 if (size == null) return;
316 if (size.Equals(this.size))
321 this.size = new Vector2(size);
323 if (pickerScroller != null && itemList != null)
325 pickerScroller.ScrollAvailableArea = new Vector2(0, (itemList.Count * itemHeight) - size.Height);
329 private void Initialize()
331 HeightSpecification = LayoutParamPolicies.MatchParent;
333 //Picker Using scroller internally. actually it is a kind of scroller which has infinity loop,
334 //and item center align features.
335 pickerScroller = new PickerScroller()
337 WidthSpecification = LayoutParamPolicies.MatchParent,
338 HeightSpecification = LayoutParamPolicies.MatchParent,
339 ScrollingDirection = ScrollableBase.Direction.Vertical,
340 Layout = new LinearLayout()
342 LinearOrientation = LinearLayout.Orientation.Vertical,
344 //FIXME: Need to expand as many as possible;
345 // When user want to start list middle of the list item. currently confused how to create list before render.
346 ScrollAvailableArea = new Vector2(0, 10000),
347 Name = "pickerScroller",
350 pickerScroller.Scrolling += OnScroll;
351 pickerScroller.ScrollAnimationEnded += OnScrollAnimationEnded;
352 pickerScroller.ScrollAnimationStarted += OnScrollAnimationStarted;
354 itemList = new List<TextLabel>();
356 minValue = maxValue = currentValue = 0;
357 displayedValues = null;
358 //Those many flags for min, max, value method calling sequence dependency.
359 needItemUpdate = true;
360 displayedValuesUpdate = false;
368 private void OnValueChanged()
370 ValueChangedEventArgs eventArgs =
371 new ValueChangedEventArgs(displayedValuesUpdate ? Int32.Parse(itemList[currentValue].Name) : Int32.Parse(itemList[currentValue].Text));
372 ValueChanged?.Invoke(this, eventArgs);
375 private void PageAdjust(float positionY)
377 //Check the scroll is going out to the dummys if so, bring it back to page.
378 if (positionY > -(startScrollY - (itemHeight * 2)))
379 pickerScroller.ScrollTo(-positionY + pageSize, false);
380 else if (positionY < -(startScrollY + pageSize - (itemHeight * 2)))
381 pickerScroller.ScrollTo(-positionY - pageSize, false);
384 private void OnScroll(object sender, ScrollEventArgs e)
386 if (!loopEnabled || onAnimation || onAlignAnimation) return;
388 PageAdjust(e.Position.Y);
391 private void OnScrollAnimationStarted(object sender, ScrollEventArgs e)
396 private void OnScrollAnimationEnded(object sender, ScrollEventArgs e)
398 //Ignore if the scroll position was not changed. (called it from this function)
399 if (lastScrollPosion == (int)e.Position.Y) return;
401 //Calc offset from closest item.
402 int offset = (int)(e.Position.Y + startScrollOffset) % itemHeight;
403 if (offset < -(itemHeight / 2)) offset += itemHeight;
405 lastScrollPosion = (int)(-e.Position.Y + offset);
408 if (onAlignAnimation) {
409 onAlignAnimation = false;
410 if (loopEnabled == true)
412 PageAdjust(e.Position.Y);
414 if (currentValue != ((int)(-e.Position.Y / itemHeight) + 2))
416 currentValue = ((int)(-e.Position.Y / itemHeight) + 2);
423 //Item center align with animation, otherwise changed event emit.
425 onAlignAnimation = true;
426 pickerScroller.ScrollTo(-e.Position.Y + offset, true);
429 if (currentValue != ((int)(-e.Position.Y / itemHeight) + 2))
431 currentValue = ((int)(-e.Position.Y / itemHeight) + 2);
437 //This is UI requirement. It helps where exactly center item is.
438 private void AddLine()
441 downLine = new View();
447 private String GetItemText(bool loopEnabled, int idx)
449 if (!loopEnabled) return " ";
451 if (displayedValuesUpdate) {
452 idx = idx - MinValue;
453 if (idx <= displayedValues.Count) {
454 return displayedValues[idx];
459 return idx.ToString();
463 //FIXME: If textVisual can add in scroller please change it to textVisual for performance
464 [SuppressMessage("Microsoft.Reliability",
465 "CA2000:DisposeObjectsBeforeLosingScope",
466 Justification = "The items are added to itemList and are disposed in Picker.Dispose().")]
467 private void AddPickerItem(bool loopEnabled, int idx)
469 TextLabel temp = new TextLabel(itemTextLabel)
471 WidthSpecification = LayoutParamPolicies.MatchParent,
472 Text = GetItemText(loopEnabled, idx),
473 Name = idx.ToString(),
477 pickerScroller.Add(temp);
480 private void UpdateCurrentValue()
482 // -2 for center align
483 int startItemIdx = (currentValue == 0) ? -2 : currentValue - minValue - 2;
485 if (loopEnabled) startY = ((dummyItemsForLoop + startItemIdx) * itemHeight) + startScrollOffset;
486 // + 2 for non loop picker center align
487 else startY = ((2 + startItemIdx) * itemHeight) + startScrollOffset;
488 pickerScroller.ScrollTo(startY, false);
491 private void UpdateValueList()
493 if (!needItemUpdate) return;
494 if (minValue > maxValue) return;
496 //FIXME: This is wrong.
497 // But scroller can't update item property after added please fix me.
498 if (itemList.Count > 0) {
500 pickerScroller.RemoveAllChildren();
503 if (maxValue - minValue + 1 >= scrollVisibleItems)
506 //Current scroller can't add at specific index.
507 //So need below calc.
508 int dummyStartIdx = 0;
509 if (maxValue - minValue >= dummyItemsForLoop)
510 dummyStartIdx = maxValue - dummyItemsForLoop + 1;
512 dummyStartIdx = maxValue - (dummyItemsForLoop % (maxValue - minValue + 1)) + 1;
514 //Start add items in scroller. first dummys for scroll anim.
515 for (int i = 0; i < dummyItemsForLoop; i++)
517 if (dummyStartIdx > maxValue) dummyStartIdx = minValue;
518 AddPickerItem(loopEnabled, dummyStartIdx++);
521 for (int i = minValue; i <= maxValue; i++)
523 AddPickerItem(loopEnabled, i);
525 //Last dummys for scroll anim.
526 dummyStartIdx = minValue;
527 for (int i = 0; i < dummyItemsForLoop; i++)
529 if (dummyStartIdx > maxValue) dummyStartIdx = minValue;
530 AddPickerItem(loopEnabled, dummyStartIdx++);
537 for (int i = 0; i < 2; i++)
538 AddPickerItem(loopEnabled, 0);
539 for (int i = minValue; i <= maxValue; i++)
540 AddPickerItem(!loopEnabled, i);
541 for (int i = 0; i < 2; i++)
542 AddPickerItem(loopEnabled, 0);
545 pageSize = itemHeight * (maxValue - minValue + 1);
547 UpdateCurrentValue();
549 //Give a correct scroll area.
552 pickerScroller.ScrollAvailableArea = new Vector2(0, (itemList.Count * itemHeight) - size.Height);
555 needItemUpdate = false;
558 internal class PickerScroller : ScrollableBase
560 private int itemHeight;
561 private int startScrollOffset;
562 private float velocityOfLastPan = 0.0f;
563 private float panAnimationDuration = 0.0f;
564 private float panAnimationDelta = 0.0f;
565 private float decelerationRate = 0.0f;
566 private float logValueOfDeceleration = 0.0f;
567 private delegate float UserAlphaFunctionDelegate(float progress);
568 private UserAlphaFunctionDelegate customScrollAlphaFunction;
570 public PickerScroller() : base()
572 //Default rate is 0.998. this is for reduce scroll animation length.
573 decelerationRate = 0.991f;
574 logValueOfDeceleration = (float)Math.Log(decelerationRate);
577 public void SetPickerStyle(PickerStyle pickerStyle)
579 if (pickerStyle.StartScrollOffset != null)
581 startScrollOffset = (int)pickerStyle.StartScrollOffset.Height;
584 if (pickerStyle.ItemTextLabel?.Size != null)
586 itemHeight = (int)pickerStyle.ItemTextLabel.Size.Height;
589 if (pickerStyle.Size != null)
591 Size = new Size(-1, pickerStyle.Size.Height);
595 private float CustomScrollAlphaFunction(float progress)
597 if (panAnimationDelta == 0)
603 // Parameter "progress" is normalized value. We need to multiply target duration to calculate distance.
604 // Can get real distance using equation of deceleration (check Decelerating function)
605 // After get real distance, normalize it
606 float realDuration = progress * panAnimationDuration;
607 float realDistance = velocityOfLastPan * ((float)Math.Pow(decelerationRate, realDuration) - 1) / logValueOfDeceleration;
608 float result = Math.Min(realDistance / Math.Abs(panAnimationDelta), 1.0f);
614 //Override Decelerating for Picker feature.
615 protected override void Decelerating(float velocity, Animation animation)
617 //Reduce Scroll animation speed.
618 //The picker is to select items in the scroll area, it is not correct to animate
619 //the scroll with very high speed.
621 velocityOfLastPan = Math.Abs(velocity);
623 float currentScrollPosition = -ContentContainer.PositionY;
624 panAnimationDelta = (velocityOfLastPan * decelerationRate) / (1 - decelerationRate);
625 panAnimationDelta = velocity > 0 ? -panAnimationDelta : panAnimationDelta;
627 float destination = -(panAnimationDelta + currentScrollPosition);
628 //Animation destination has to center of the item.
629 float align = destination % itemHeight;
630 destination -= align;
631 destination -= startScrollOffset;
633 float adjustDestination = AdjustTargetPositionOfScrollAnimation(destination);
635 float maxPosition = ScrollAvailableArea != null ? ScrollAvailableArea.Y : 0;
636 float minPosition = ScrollAvailableArea != null ? ScrollAvailableArea.X : 0;
638 if (destination < -maxPosition || destination > minPosition)
640 panAnimationDelta = velocity > 0 ? (currentScrollPosition - minPosition) : (maxPosition - currentScrollPosition);
641 destination = velocity > 0 ? minPosition : -maxPosition;
642 destination = -maxPosition + itemHeight;
644 if (panAnimationDelta == 0)
646 panAnimationDuration = 0.0f;
650 panAnimationDuration = (float)Math.Log((panAnimationDelta * logValueOfDeceleration / velocityOfLastPan + 1), decelerationRate);
655 panAnimationDuration = (float)Math.Log(-DecelerationThreshold * logValueOfDeceleration / velocityOfLastPan) / logValueOfDeceleration;
657 if (adjustDestination != destination)
659 destination = adjustDestination;
660 panAnimationDelta = destination + currentScrollPosition;
661 velocityOfLastPan = Math.Abs(panAnimationDelta * logValueOfDeceleration / ((float)Math.Pow(decelerationRate, panAnimationDuration) - 1));
662 panAnimationDuration = (float)Math.Log(-DecelerationThreshold * logValueOfDeceleration / velocityOfLastPan) / logValueOfDeceleration;
666 customScrollAlphaFunction = new UserAlphaFunctionDelegate(CustomScrollAlphaFunction);
667 animation.DefaultAlphaFunction = new AlphaFunction(customScrollAlphaFunction);
668 animation.Duration = (int)panAnimationDuration;
669 animation.AnimateTo(ContentContainer, "PositionY", (int)destination);