1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "ui/views/controls/scrollbar/scroll_bar.h"
6 
7 #include <algorithm>
8 #include <memory>
9 
10 #include "base/bind.h"
11 #include "base/callback.h"
12 #include "base/callback_helpers.h"
13 #include "base/compiler_specific.h"
14 #include "base/containers/flat_map.h"
15 #include "base/no_destructor.h"
16 #include "base/numerics/ranges.h"
17 #include "base/numerics/safe_conversions.h"
18 #include "base/strings/string16.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "build/build_config.h"
21 #include "ui/accessibility/ax_enums.mojom.h"
22 #include "ui/accessibility/ax_node_data.h"
23 #include "ui/base/l10n/l10n_util.h"
24 #include "ui/events/event.h"
25 #include "ui/events/keycodes/keyboard_codes.h"
26 #include "ui/gfx/canvas.h"
27 #include "ui/strings/grit/ui_strings.h"
28 #include "ui/views/controls/menu/menu_item_view.h"
29 #include "ui/views/controls/menu/menu_runner.h"
30 #include "ui/views/controls/scroll_view.h"
31 #include "ui/views/controls/scrollbar/base_scroll_bar_thumb.h"
32 #include "ui/views/metadata/metadata_impl_macros.h"
33 #include "ui/views/widget/widget.h"
34 
35 namespace views {
36 
37 ScrollBar::~ScrollBar() = default;
38 
IsHorizontal() const39 bool ScrollBar::IsHorizontal() const {
40   return is_horiz_;
41 }
42 
SetThumb(BaseScrollBarThumb * thumb)43 void ScrollBar::SetThumb(BaseScrollBarThumb* thumb) {
44   DCHECK(!thumb_);
45   thumb_ = thumb;
46   AddChildView(thumb);
47   thumb->set_context_menu_controller(this);
48 }
49 
ScrollByAmount(ScrollAmount amount)50 bool ScrollBar::ScrollByAmount(ScrollAmount amount) {
51   auto desired_offset = GetDesiredScrollOffset(amount);
52   if (!desired_offset)
53     return false;
54 
55   SetContentsScrollOffset(desired_offset.value());
56   ScrollContentsToOffset();
57   return true;
58 }
59 
ScrollToThumbPosition(int thumb_position,bool scroll_to_middle)60 void ScrollBar::ScrollToThumbPosition(int thumb_position,
61                                       bool scroll_to_middle) {
62   SetContentsScrollOffset(CalculateContentsOffset(
63       static_cast<float>(thumb_position), scroll_to_middle));
64   ScrollContentsToOffset();
65   SchedulePaint();
66 }
67 
ScrollByContentsOffset(int contents_offset)68 bool ScrollBar::ScrollByContentsOffset(int contents_offset) {
69   int old_offset = contents_scroll_offset_;
70   SetContentsScrollOffset(contents_scroll_offset_ - contents_offset);
71   if (old_offset == contents_scroll_offset_)
72     return false;
73 
74   ScrollContentsToOffset();
75   return true;
76 }
77 
GetMaxPosition() const78 int ScrollBar::GetMaxPosition() const {
79   return max_pos_;
80 }
81 
GetMinPosition() const82 int ScrollBar::GetMinPosition() const {
83   return 0;
84 }
85 
GetPosition() const86 int ScrollBar::GetPosition() const {
87   return thumb_->GetPosition();
88 }
89 
90 ///////////////////////////////////////////////////////////////////////////////
91 // ScrollBar, View implementation:
92 
GetAccessibleNodeData(ui::AXNodeData * node_data)93 void ScrollBar::GetAccessibleNodeData(ui::AXNodeData* node_data) {
94   node_data->role = ax::mojom::Role::kScrollBar;
95 }
96 
OnMousePressed(const ui::MouseEvent & event)97 bool ScrollBar::OnMousePressed(const ui::MouseEvent& event) {
98   if (event.IsOnlyLeftMouseButton())
99     ProcessPressEvent(event);
100   return true;
101 }
102 
OnMouseReleased(const ui::MouseEvent & event)103 void ScrollBar::OnMouseReleased(const ui::MouseEvent& event) {
104   repeater_.Stop();
105 }
106 
OnMouseCaptureLost()107 void ScrollBar::OnMouseCaptureLost() {
108   repeater_.Stop();
109 }
110 
OnKeyPressed(const ui::KeyEvent & event)111 bool ScrollBar::OnKeyPressed(const ui::KeyEvent& event) {
112   return ScrollByAmount(DetermineScrollAmountByKeyCode(event.key_code()));
113 }
114 
OnMouseWheel(const ui::MouseWheelEvent & event)115 bool ScrollBar::OnMouseWheel(const ui::MouseWheelEvent& event) {
116   OnScroll(event.x_offset(), event.y_offset());
117   return true;
118 }
119 
OnGestureEvent(ui::GestureEvent * event)120 void ScrollBar::OnGestureEvent(ui::GestureEvent* event) {
121   // If a fling is in progress, then stop the fling for any incoming gesture
122   // event (except for the GESTURE_END event that is generated at the end of the
123   // fling).
124   if (scroll_animator_ && scroll_animator_->is_scrolling() &&
125       (event->type() != ui::ET_GESTURE_END ||
126        event->details().touch_points() > 1)) {
127     scroll_animator_->Stop();
128   }
129 
130   if (event->type() == ui::ET_GESTURE_TAP_DOWN) {
131     ProcessPressEvent(*event);
132     event->SetHandled();
133     return;
134   }
135 
136   if (event->type() == ui::ET_GESTURE_LONG_PRESS) {
137     // For a long-press, the repeater started in tap-down should continue. So
138     // return early.
139     return;
140   }
141 
142   repeater_.Stop();
143 
144   if (event->type() == ui::ET_GESTURE_TAP) {
145     // TAP_DOWN would have already scrolled some amount. So scrolling again on
146     // TAP is not necessary.
147     event->SetHandled();
148     return;
149   }
150 
151   if (event->type() == ui::ET_GESTURE_SCROLL_BEGIN ||
152       event->type() == ui::ET_GESTURE_SCROLL_END) {
153     event->SetHandled();
154     return;
155   }
156 
157   if (event->type() == ui::ET_GESTURE_SCROLL_UPDATE) {
158     float scroll_amount_f;
159     int scroll_amount;
160     if (IsHorizontal()) {
161       scroll_amount_f = event->details().scroll_x() - roundoff_error_.x();
162       scroll_amount = base::ClampRound(scroll_amount_f);
163       roundoff_error_.set_x(scroll_amount - scroll_amount_f);
164     } else {
165       scroll_amount_f = event->details().scroll_y() - roundoff_error_.y();
166       scroll_amount = base::ClampRound(scroll_amount_f);
167       roundoff_error_.set_y(scroll_amount - scroll_amount_f);
168     }
169     if (ScrollByContentsOffset(scroll_amount))
170       event->SetHandled();
171     return;
172   }
173 
174   if (event->type() == ui::ET_SCROLL_FLING_START) {
175     if (!scroll_animator_)
176       scroll_animator_ = std::make_unique<ScrollAnimator>(this);
177     scroll_animator_->Start(
178         IsHorizontal() ? event->details().velocity_x() : 0.f,
179         IsHorizontal() ? 0.f : event->details().velocity_y());
180     event->SetHandled();
181   }
182 }
183 
184 ///////////////////////////////////////////////////////////////////////////////
185 // ScrollBar, ScrollDelegate implementation:
186 
OnScroll(float dx,float dy)187 bool ScrollBar::OnScroll(float dx, float dy) {
188   return IsHorizontal() ? ScrollByContentsOffset(dx)
189                         : ScrollByContentsOffset(dy);
190 }
191 
192 ///////////////////////////////////////////////////////////////////////////////
193 // ScrollBar, ContextMenuController implementation:
194 
195 enum ScrollBarContextMenuCommands {
196   ScrollBarContextMenuCommand_ScrollHere = 1,
197   ScrollBarContextMenuCommand_ScrollStart,
198   ScrollBarContextMenuCommand_ScrollEnd,
199   ScrollBarContextMenuCommand_ScrollPageUp,
200   ScrollBarContextMenuCommand_ScrollPageDown,
201   ScrollBarContextMenuCommand_ScrollPrev,
202   ScrollBarContextMenuCommand_ScrollNext
203 };
204 
ShowContextMenuForViewImpl(View * source,const gfx::Point & p,ui::MenuSourceType source_type)205 void ScrollBar::ShowContextMenuForViewImpl(View* source,
206                                            const gfx::Point& p,
207                                            ui::MenuSourceType source_type) {
208   Widget* widget = GetWidget();
209   gfx::Rect widget_bounds = widget->GetWindowBoundsInScreen();
210   gfx::Point temp_pt(p.x() - widget_bounds.x(), p.y() - widget_bounds.y());
211   View::ConvertPointFromWidget(this, &temp_pt);
212   context_menu_mouse_position_ = IsHorizontal() ? temp_pt.x() : temp_pt.y();
213 
214   if (!menu_model_) {
215     menu_model_ = std::make_unique<ui::SimpleMenuModel>(this);
216     menu_model_->AddItemWithStringId(ScrollBarContextMenuCommand_ScrollHere,
217                                      IDS_APP_SCROLLBAR_CXMENU_SCROLLHERE);
218     menu_model_->AddSeparator(ui::NORMAL_SEPARATOR);
219     menu_model_->AddItemWithStringId(
220         ScrollBarContextMenuCommand_ScrollStart,
221         IsHorizontal() ? IDS_APP_SCROLLBAR_CXMENU_SCROLLLEFTEDGE
222                        : IDS_APP_SCROLLBAR_CXMENU_SCROLLHOME);
223     menu_model_->AddItemWithStringId(
224         ScrollBarContextMenuCommand_ScrollEnd,
225         IsHorizontal() ? IDS_APP_SCROLLBAR_CXMENU_SCROLLRIGHTEDGE
226                        : IDS_APP_SCROLLBAR_CXMENU_SCROLLEND);
227     menu_model_->AddSeparator(ui::NORMAL_SEPARATOR);
228     menu_model_->AddItemWithStringId(ScrollBarContextMenuCommand_ScrollPageUp,
229                                      IDS_APP_SCROLLBAR_CXMENU_SCROLLPAGEUP);
230     menu_model_->AddItemWithStringId(ScrollBarContextMenuCommand_ScrollPageDown,
231                                      IDS_APP_SCROLLBAR_CXMENU_SCROLLPAGEDOWN);
232     menu_model_->AddSeparator(ui::NORMAL_SEPARATOR);
233     menu_model_->AddItemWithStringId(ScrollBarContextMenuCommand_ScrollPrev,
234                                      IsHorizontal()
235                                          ? IDS_APP_SCROLLBAR_CXMENU_SCROLLLEFT
236                                          : IDS_APP_SCROLLBAR_CXMENU_SCROLLUP);
237     menu_model_->AddItemWithStringId(ScrollBarContextMenuCommand_ScrollNext,
238                                      IsHorizontal()
239                                          ? IDS_APP_SCROLLBAR_CXMENU_SCROLLRIGHT
240                                          : IDS_APP_SCROLLBAR_CXMENU_SCROLLDOWN);
241   }
242   menu_runner_ = std::make_unique<MenuRunner>(
243       menu_model_.get(),
244       MenuRunner::HAS_MNEMONICS | views::MenuRunner::CONTEXT_MENU);
245   menu_runner_->RunMenuAt(GetWidget(), nullptr, gfx::Rect(p, gfx::Size()),
246                           MenuAnchorPosition::kTopLeft, source_type);
247 }
248 
249 ///////////////////////////////////////////////////////////////////////////////
250 // ScrollBar, Menu::Delegate implementation:
251 
IsCommandIdEnabled(int id) const252 bool ScrollBar::IsCommandIdEnabled(int id) const {
253   switch (id) {
254     case ScrollBarContextMenuCommand_ScrollPageUp:
255     case ScrollBarContextMenuCommand_ScrollPageDown:
256       return !IsHorizontal();
257   }
258   return true;
259 }
260 
IsCommandIdChecked(int id) const261 bool ScrollBar::IsCommandIdChecked(int id) const {
262   return false;
263 }
264 
ExecuteCommand(int id,int event_flags)265 void ScrollBar::ExecuteCommand(int id, int event_flags) {
266   switch (id) {
267     case ScrollBarContextMenuCommand_ScrollHere:
268       ScrollToThumbPosition(context_menu_mouse_position_, true);
269       break;
270     case ScrollBarContextMenuCommand_ScrollStart:
271       ScrollByAmount(ScrollAmount::kStart);
272       break;
273     case ScrollBarContextMenuCommand_ScrollEnd:
274       ScrollByAmount(ScrollAmount::kEnd);
275       break;
276     case ScrollBarContextMenuCommand_ScrollPageUp:
277       ScrollByAmount(ScrollAmount::kPrevPage);
278       break;
279     case ScrollBarContextMenuCommand_ScrollPageDown:
280       ScrollByAmount(ScrollAmount::kNextPage);
281       break;
282     case ScrollBarContextMenuCommand_ScrollPrev:
283       ScrollByAmount(ScrollAmount::kPrevLine);
284       break;
285     case ScrollBarContextMenuCommand_ScrollNext:
286       ScrollByAmount(ScrollAmount::kNextLine);
287       break;
288   }
289 }
290 
291 ///////////////////////////////////////////////////////////////////////////////
292 // ScrollBar implementation:
293 
OverlapsContent() const294 bool ScrollBar::OverlapsContent() const {
295   return false;
296 }
297 
Update(int viewport_size,int content_size,int contents_scroll_offset)298 void ScrollBar::Update(int viewport_size,
299                        int content_size,
300                        int contents_scroll_offset) {
301   max_pos_ = std::max(0, content_size - viewport_size);
302   // Make sure contents_size is always > 0 to avoid divide by zero errors in
303   // calculations throughout this code.
304   contents_size_ = std::max(1, content_size);
305   viewport_size_ = std::max(1, viewport_size);
306 
307   SetContentsScrollOffset(contents_scroll_offset);
308 
309   // Thumb Height and Thumb Pos.
310   // The height of the thumb is the ratio of the Viewport height to the
311   // content size multiplied by the height of the thumb track.
312   float ratio =
313       std::min<float>(1.0, static_cast<float>(viewport_size) / contents_size_);
314   thumb_->SetLength(base::ClampRound(ratio * GetTrackSize()));
315 
316   int thumb_position = CalculateThumbPosition(contents_scroll_offset);
317   thumb_->SetPosition(thumb_position);
318 }
319 
320 ///////////////////////////////////////////////////////////////////////////////
321 // ScrollBar, protected:
322 
GetThumb() const323 BaseScrollBarThumb* ScrollBar::GetThumb() const {
324   return thumb_;
325 }
326 
ScrollToPosition(int position)327 void ScrollBar::ScrollToPosition(int position) {
328   controller()->ScrollToPosition(this, position);
329 }
330 
GetScrollIncrement(bool is_page,bool is_positive)331 int ScrollBar::GetScrollIncrement(bool is_page, bool is_positive) {
332   return controller()->GetScrollIncrement(this, is_page, is_positive);
333 }
334 
ObserveScrollEvent(const ui::ScrollEvent & event)335 void ScrollBar::ObserveScrollEvent(const ui::ScrollEvent& event) {}
336 
ScrollBar(bool is_horiz)337 ScrollBar::ScrollBar(bool is_horiz)
338     : is_horiz_(is_horiz),
339       repeater_(base::BindRepeating(&ScrollBar::TrackClicked,
340                                     base::Unretained(this))) {
341   set_context_menu_controller(this);
342 }
343 
344 ///////////////////////////////////////////////////////////////////////////////
345 // ScrollBar, private:
346 
347 #if !defined(OS_APPLE)
348 // static
GetHideTimerForTesting(ScrollBar * scroll_bar)349 base::RetainingOneShotTimer* ScrollBar::GetHideTimerForTesting(
350     ScrollBar* scroll_bar) {
351   return nullptr;
352 }
353 #endif
354 
GetThumbSizeForTesting()355 int ScrollBar::GetThumbSizeForTesting() {
356   return thumb_->GetSize();
357 }
358 
ProcessPressEvent(const ui::LocatedEvent & event)359 void ScrollBar::ProcessPressEvent(const ui::LocatedEvent& event) {
360   gfx::Rect thumb_bounds = thumb_->bounds();
361   if (IsHorizontal()) {
362     if (GetMirroredXInView(event.x()) < thumb_bounds.x()) {
363       last_scroll_amount_ = ScrollAmount::kPrevPage;
364     } else if (GetMirroredXInView(event.x()) > thumb_bounds.right()) {
365       last_scroll_amount_ = ScrollAmount::kNextPage;
366     }
367   } else {
368     if (event.y() < thumb_bounds.y()) {
369       last_scroll_amount_ = ScrollAmount::kPrevPage;
370     } else if (event.y() > thumb_bounds.bottom()) {
371       last_scroll_amount_ = ScrollAmount::kNextPage;
372     }
373   }
374   TrackClicked();
375   repeater_.Start();
376 }
377 
TrackClicked()378 void ScrollBar::TrackClicked() {
379   ScrollByAmount(last_scroll_amount_);
380 }
381 
ScrollContentsToOffset()382 void ScrollBar::ScrollContentsToOffset() {
383   ScrollToPosition(contents_scroll_offset_);
384   thumb_->SetPosition(CalculateThumbPosition(contents_scroll_offset_));
385 }
386 
GetTrackSize() const387 int ScrollBar::GetTrackSize() const {
388   gfx::Rect track_bounds = GetTrackBounds();
389   return IsHorizontal() ? track_bounds.width() : track_bounds.height();
390 }
391 
CalculateThumbPosition(int contents_scroll_offset) const392 int ScrollBar::CalculateThumbPosition(int contents_scroll_offset) const {
393   // In some combination of viewport_size and contents_size_, the result of
394   // simple division can be rounded and there could be 1 pixel gap even when the
395   // contents scroll down to the bottom. See crbug.com/244671.
396   int thumb_max = GetTrackSize() - thumb_->GetSize();
397   if (contents_scroll_offset + viewport_size_ == contents_size_)
398     return thumb_max;
399   return (contents_scroll_offset * thumb_max) /
400          (contents_size_ - viewport_size_);
401 }
402 
CalculateContentsOffset(float thumb_position,bool scroll_to_middle) const403 int ScrollBar::CalculateContentsOffset(float thumb_position,
404                                        bool scroll_to_middle) const {
405   float thumb_size = static_cast<float>(thumb_->GetSize());
406   int track_size = GetTrackSize();
407   if (track_size == thumb_size)
408     return 0;
409   if (scroll_to_middle)
410     thumb_position = thumb_position - (thumb_size / 2);
411   float result = (thumb_position * (contents_size_ - viewport_size_)) /
412                  (track_size - thumb_size);
413   return base::ClampRound(result);
414 }
415 
SetContentsScrollOffset(int contents_scroll_offset)416 void ScrollBar::SetContentsScrollOffset(int contents_scroll_offset) {
417   contents_scroll_offset_ = base::ClampToRange(
418       contents_scroll_offset, GetMinPosition(), GetMaxPosition());
419 }
420 
DetermineScrollAmountByKeyCode(const ui::KeyboardCode & keycode) const421 ScrollBar::ScrollAmount ScrollBar::DetermineScrollAmountByKeyCode(
422     const ui::KeyboardCode& keycode) const {
423   // Reject arrows that don't match the scrollbar orientation.
424   if (IsHorizontal() ? (keycode == ui::VKEY_UP || keycode == ui::VKEY_DOWN)
425                      : (keycode == ui::VKEY_LEFT || keycode == ui::VKEY_RIGHT))
426     return ScrollAmount::kNone;
427 
428   static const base::NoDestructor<
429       base::flat_map<ui::KeyboardCode, ScrollAmount>>
430       kMap({
431           {ui::VKEY_LEFT, ScrollAmount::kPrevLine},
432           {ui::VKEY_RIGHT, ScrollAmount::kNextLine},
433           {ui::VKEY_UP, ScrollAmount::kPrevLine},
434           {ui::VKEY_DOWN, ScrollAmount::kNextLine},
435           {ui::VKEY_PRIOR, ScrollAmount::kPrevPage},
436           {ui::VKEY_NEXT, ScrollAmount::kNextPage},
437           {ui::VKEY_HOME, ScrollAmount::kStart},
438           {ui::VKEY_END, ScrollAmount::kEnd},
439       });
440 
441   const auto i = kMap->find(keycode);
442   return (i == kMap->end()) ? ScrollAmount::kNone : i->second;
443 }
444 
GetDesiredScrollOffset(ScrollAmount amount)445 base::Optional<int> ScrollBar::GetDesiredScrollOffset(ScrollAmount amount) {
446   switch (amount) {
447     case ScrollAmount::kStart:
448       return GetMinPosition();
449     case ScrollAmount::kEnd:
450       return GetMaxPosition();
451     case ScrollAmount::kPrevLine:
452       return contents_scroll_offset_ - GetScrollIncrement(false, false);
453     case ScrollAmount::kNextLine:
454       return contents_scroll_offset_ + GetScrollIncrement(false, true);
455     case ScrollAmount::kPrevPage:
456       return contents_scroll_offset_ - GetScrollIncrement(true, false);
457     case ScrollAmount::kNextPage:
458       return contents_scroll_offset_ + GetScrollIncrement(true, true);
459     default:
460       return base::nullopt;
461   }
462 }
463 
464 BEGIN_METADATA(ScrollBar, View)
465 ADD_READONLY_PROPERTY_METADATA(int, MaxPosition)
466 ADD_READONLY_PROPERTY_METADATA(int, MinPosition)
467 ADD_READONLY_PROPERTY_METADATA(int, Position)
468 END_METADATA
469 
470 }  // namespace views
471