initial import
[vuplus_webkit] / Source / WebCore / platform / Scrollbar.cpp
1 /*
2  * Copyright (C) 2004, 2006, 2008 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "Scrollbar.h"
28
29 #include "GraphicsContext.h"
30 #include "PlatformMouseEvent.h"
31 #include "ScrollAnimator.h"
32 #include "ScrollableArea.h"
33 #include "ScrollbarTheme.h"
34 #include <algorithm>
35
36 // FIXME: The following #includes are a layering violation and should be removed.
37 #include "AXObjectCache.h"
38 #include "AccessibilityScrollbar.h"
39 #include "Document.h"
40 #include "EventHandler.h"
41 #include "Frame.h"
42 #include "FrameView.h"
43
44 using namespace std;
45
46 #if (PLATFORM(CHROMIUM) && (OS(UNIX) && !OS(DARWIN))) || PLATFORM(GTK)
47 // The position of the scrollbar thumb affects the appearance of the steppers, so
48 // when the thumb moves, we have to invalidate them for painting.
49 #define THUMB_POSITION_AFFECTS_BUTTONS
50 #endif
51
52 namespace WebCore {
53
54 #if !PLATFORM(EFL)
55 PassRefPtr<Scrollbar> Scrollbar::createNativeScrollbar(ScrollableArea* scrollableArea, ScrollbarOrientation orientation, ScrollbarControlSize size)
56 {
57     return adoptRef(new Scrollbar(scrollableArea, orientation, size));
58 }
59 #endif
60
61 int Scrollbar::maxOverlapBetweenPages()
62 {
63     static int maxOverlapBetweenPages = ScrollbarTheme::nativeTheme()->maxOverlapBetweenPages();
64     return maxOverlapBetweenPages;
65 }
66
67 Scrollbar::Scrollbar(ScrollableArea* scrollableArea, ScrollbarOrientation orientation, ScrollbarControlSize controlSize,
68                      ScrollbarTheme* theme)
69     : m_scrollableArea(scrollableArea)
70     , m_orientation(orientation)
71     , m_controlSize(controlSize)
72     , m_theme(theme)
73     , m_visibleSize(0)
74     , m_totalSize(0)
75     , m_currentPos(0)
76     , m_dragOrigin(0)
77     , m_lineStep(0)
78     , m_pageStep(0)
79     , m_pixelStep(1)
80     , m_hoveredPart(NoPart)
81     , m_pressedPart(NoPart)
82     , m_pressedPos(0)
83     , m_draggingDocument(false)
84     , m_documentDragPos(0)
85     , m_enabled(true)
86     , m_scrollTimer(this, &Scrollbar::autoscrollTimerFired)
87     , m_overlapsResizer(false)
88     , m_suppressInvalidation(false)
89 {
90     if (!m_theme)
91         m_theme = ScrollbarTheme::nativeTheme();
92
93     m_theme->registerScrollbar(this);
94
95     // FIXME: This is ugly and would not be necessary if we fix cross-platform code to actually query for
96     // scrollbar thickness and use it when sizing scrollbars (rather than leaving one dimension of the scrollbar
97     // alone when sizing).
98     int thickness = m_theme->scrollbarThickness(controlSize);
99     Widget::setFrameRect(IntRect(0, 0, thickness, thickness));
100
101     if (m_scrollableArea)
102         m_currentPos = static_cast<float>(m_scrollableArea->scrollPosition(this));
103 }
104
105 Scrollbar::~Scrollbar()
106 {
107     if (AXObjectCache::accessibilityEnabled() && axObjectCache())
108         axObjectCache()->remove(this);
109     
110     stopTimerIfNeeded();
111     
112     m_theme->unregisterScrollbar(this);
113 }
114
115 void Scrollbar::offsetDidChange()
116 {
117     ASSERT(m_scrollableArea);
118
119     float position = static_cast<float>(m_scrollableArea->scrollPosition(this));
120     if (position == m_currentPos)
121         return;
122
123     int oldThumbPosition = theme()->thumbPosition(this);
124     m_currentPos = position;
125     updateThumbPosition();
126     if (m_pressedPart == ThumbPart)
127         setPressedPos(m_pressedPos + theme()->thumbPosition(this) - oldThumbPosition);    
128 }
129
130 void Scrollbar::setProportion(int visibleSize, int totalSize)
131 {
132     if (visibleSize == m_visibleSize && totalSize == m_totalSize)
133         return;
134
135     m_visibleSize = visibleSize;
136     m_totalSize = totalSize;
137
138     updateThumbProportion();
139 }
140
141 void Scrollbar::setSteps(int lineStep, int pageStep, int pixelsPerStep)
142 {
143     m_lineStep = lineStep;
144     m_pageStep = pageStep;
145     m_pixelStep = 1.0f / pixelsPerStep;
146 }
147
148 void Scrollbar::updateThumb()
149 {
150 #ifdef THUMB_POSITION_AFFECTS_BUTTONS
151     invalidate();
152 #else
153     theme()->invalidateParts(this, ForwardTrackPart | BackTrackPart | ThumbPart);
154 #endif
155 }
156
157 void Scrollbar::updateThumbPosition()
158 {
159     updateThumb();
160 }
161
162 void Scrollbar::updateThumbProportion()
163 {
164     updateThumb();
165 }
166
167 void Scrollbar::paint(GraphicsContext* context, const IntRect& damageRect)
168 {
169     if (context->updatingControlTints() && theme()->supportsControlTints()) {
170         invalidate();
171         return;
172     }
173
174     if (context->paintingDisabled() || !frameRect().intersects(damageRect))
175         return;
176
177     if (!theme()->paint(this, context, damageRect))
178         Widget::paint(context, damageRect);
179 }
180
181 void Scrollbar::autoscrollTimerFired(Timer<Scrollbar>*)
182 {
183     autoscrollPressedPart(theme()->autoscrollTimerDelay());
184 }
185
186 static bool thumbUnderMouse(Scrollbar* scrollbar)
187 {
188     int thumbPos = scrollbar->theme()->trackPosition(scrollbar) + scrollbar->theme()->thumbPosition(scrollbar);
189     int thumbLength = scrollbar->theme()->thumbLength(scrollbar);
190     return scrollbar->pressedPos() >= thumbPos && scrollbar->pressedPos() < thumbPos + thumbLength;
191 }
192
193 void Scrollbar::autoscrollPressedPart(double delay)
194 {
195     // Don't do anything for the thumb or if nothing was pressed.
196     if (m_pressedPart == ThumbPart || m_pressedPart == NoPart)
197         return;
198
199     // Handle the track.
200     if ((m_pressedPart == BackTrackPart || m_pressedPart == ForwardTrackPart) && thumbUnderMouse(this)) {
201         theme()->invalidatePart(this, m_pressedPart);
202         setHoveredPart(ThumbPart);
203         return;
204     }
205
206     // Handle the arrows and track.
207     if (m_scrollableArea && m_scrollableArea->scroll(pressedPartScrollDirection(), pressedPartScrollGranularity()))
208         startTimerIfNeeded(delay);
209 }
210
211 void Scrollbar::startTimerIfNeeded(double delay)
212 {
213     // Don't do anything for the thumb.
214     if (m_pressedPart == ThumbPart)
215         return;
216
217     // Handle the track.  We halt track scrolling once the thumb is level
218     // with us.
219     if ((m_pressedPart == BackTrackPart || m_pressedPart == ForwardTrackPart) && thumbUnderMouse(this)) {
220         theme()->invalidatePart(this, m_pressedPart);
221         setHoveredPart(ThumbPart);
222         return;
223     }
224
225     // We can't scroll if we've hit the beginning or end.
226     ScrollDirection dir = pressedPartScrollDirection();
227     if (dir == ScrollUp || dir == ScrollLeft) {
228         if (m_currentPos == 0)
229             return;
230     } else {
231         if (m_currentPos == maximum())
232             return;
233     }
234
235     m_scrollTimer.startOneShot(delay);
236 }
237
238 void Scrollbar::stopTimerIfNeeded()
239 {
240     if (m_scrollTimer.isActive())
241         m_scrollTimer.stop();
242 }
243
244 ScrollDirection Scrollbar::pressedPartScrollDirection()
245 {
246     if (m_orientation == HorizontalScrollbar) {
247         if (m_pressedPart == BackButtonStartPart || m_pressedPart == BackButtonEndPart || m_pressedPart == BackTrackPart)
248             return ScrollLeft;
249         return ScrollRight;
250     } else {
251         if (m_pressedPart == BackButtonStartPart || m_pressedPart == BackButtonEndPart || m_pressedPart == BackTrackPart)
252             return ScrollUp;
253         return ScrollDown;
254     }
255 }
256
257 ScrollGranularity Scrollbar::pressedPartScrollGranularity()
258 {
259     if (m_pressedPart == BackButtonStartPart || m_pressedPart == BackButtonEndPart ||  m_pressedPart == ForwardButtonStartPart || m_pressedPart == ForwardButtonEndPart)
260         return ScrollByLine;
261     return ScrollByPage;
262 }
263
264 void Scrollbar::moveThumb(int pos, bool draggingDocument)
265 {
266     if (!m_scrollableArea)
267         return;
268
269     int delta = pos - m_pressedPos;
270
271     if (draggingDocument) {
272         if (m_draggingDocument)
273             delta = pos - m_documentDragPos;
274         m_draggingDocument = true;
275         FloatPoint currentPosition = m_scrollableArea->scrollAnimator()->currentPosition();
276         int destinationPosition = (m_orientation == HorizontalScrollbar ? currentPosition.x() : currentPosition.y()) + delta;
277         if (delta > 0)
278             destinationPosition = min(destinationPosition + delta, maximum());
279         else if (delta < 0)
280             destinationPosition = max(destinationPosition + delta, 0);
281         m_scrollableArea->scrollToOffsetWithoutAnimation(m_orientation, destinationPosition);
282         m_documentDragPos = pos;
283         return;
284     }
285
286     if (m_draggingDocument) {
287         delta += m_pressedPos - m_documentDragPos;
288         m_draggingDocument = false;
289     }
290
291     // Drag the thumb.
292     int thumbPos = theme()->thumbPosition(this);
293     int thumbLen = theme()->thumbLength(this);
294     int trackLen = theme()->trackLength(this);
295     int maxPos = trackLen - thumbLen;
296     if (delta > 0)
297         delta = min(maxPos - thumbPos, delta);
298     else if (delta < 0)
299         delta = max(-thumbPos, delta);
300     
301     if (delta) {
302         float newPosition = static_cast<float>(thumbPos + delta) * maximum() / (trackLen - thumbLen);
303         m_scrollableArea->scrollToOffsetWithoutAnimation(m_orientation, newPosition);
304     }
305 }
306
307 void Scrollbar::setHoveredPart(ScrollbarPart part)
308 {
309     if (part == m_hoveredPart)
310         return;
311
312     if ((m_hoveredPart == NoPart || part == NoPart) && theme()->invalidateOnMouseEnterExit())
313         invalidate();  // Just invalidate the whole scrollbar, since the buttons at either end change anyway.
314     else if (m_pressedPart == NoPart) {  // When there's a pressed part, we don't draw a hovered state, so there's no reason to invalidate.
315         theme()->invalidatePart(this, part);
316         theme()->invalidatePart(this, m_hoveredPart);
317     }
318     m_hoveredPart = part;
319 }
320
321 void Scrollbar::setPressedPart(ScrollbarPart part)
322 {
323     if (m_pressedPart != NoPart)
324         theme()->invalidatePart(this, m_pressedPart);
325     m_pressedPart = part;
326     if (m_pressedPart != NoPart)
327         theme()->invalidatePart(this, m_pressedPart);
328     else if (m_hoveredPart != NoPart)  // When we no longer have a pressed part, we can start drawing a hovered state on the hovered part.
329         theme()->invalidatePart(this, m_hoveredPart);
330 }
331
332 bool Scrollbar::mouseMoved(const PlatformMouseEvent& evt)
333 {
334     if (m_pressedPart == ThumbPart) {
335         if (theme()->shouldSnapBackToDragOrigin(this, evt)) {
336             if (m_scrollableArea)
337                 m_scrollableArea->scrollToOffsetWithoutAnimation(m_orientation, m_dragOrigin);
338         } else {
339             moveThumb(m_orientation == HorizontalScrollbar ? 
340                       convertFromContainingWindow(evt.pos()).x() :
341                       convertFromContainingWindow(evt.pos()).y(), theme()->shouldDragDocumentInsteadOfThumb(this, evt));
342         }
343         return true;
344     }
345
346     if (m_pressedPart != NoPart)
347         m_pressedPos = (orientation() == HorizontalScrollbar ? convertFromContainingWindow(evt.pos()).x() : convertFromContainingWindow(evt.pos()).y());
348
349     ScrollbarPart part = theme()->hitTest(this, evt);    
350     if (part != m_hoveredPart) {
351         if (m_pressedPart != NoPart) {
352             if (part == m_pressedPart) {
353                 // The mouse is moving back over the pressed part.  We
354                 // need to start up the timer action again.
355                 startTimerIfNeeded(theme()->autoscrollTimerDelay());
356                 theme()->invalidatePart(this, m_pressedPart);
357             } else if (m_hoveredPart == m_pressedPart) {
358                 // The mouse is leaving the pressed part.  Kill our timer
359                 // if needed.
360                 stopTimerIfNeeded();
361                 theme()->invalidatePart(this, m_pressedPart);
362             }
363         } 
364         
365         setHoveredPart(part);
366     } 
367
368     return true;
369 }
370
371 bool Scrollbar::mouseExited()
372 {
373     setHoveredPart(NoPart);
374     return true;
375 }
376
377 bool Scrollbar::mouseUp()
378 {
379     setPressedPart(NoPart);
380     m_pressedPos = 0;
381     m_draggingDocument = false;
382     stopTimerIfNeeded();
383
384     if (parent() && parent()->isFrameView())
385         static_cast<FrameView*>(parent())->frame()->eventHandler()->setMousePressed(false);
386
387     return true;
388 }
389
390 bool Scrollbar::mouseDown(const PlatformMouseEvent& evt)
391 {
392     // Early exit for right click
393     if (evt.button() == RightButton)
394         return true; // FIXME: Handled as context menu by Qt right now.  Should just avoid even calling this method on a right click though.
395
396     setPressedPart(theme()->hitTest(this, evt));
397     int pressedPos = (orientation() == HorizontalScrollbar ? convertFromContainingWindow(evt.pos()).x() : convertFromContainingWindow(evt.pos()).y());
398     
399     if ((m_pressedPart == BackTrackPart || m_pressedPart == ForwardTrackPart) && theme()->shouldCenterOnThumb(this, evt)) {
400         setHoveredPart(ThumbPart);
401         setPressedPart(ThumbPart);
402         m_dragOrigin = m_currentPos;
403         int thumbLen = theme()->thumbLength(this);
404         int desiredPos = pressedPos;
405         // Set the pressed position to the middle of the thumb so that when we do the move, the delta
406         // will be from the current pixel position of the thumb to the new desired position for the thumb.
407         m_pressedPos = theme()->trackPosition(this) + theme()->thumbPosition(this) + thumbLen / 2;
408         moveThumb(desiredPos);
409         return true;
410     } else if (m_pressedPart == ThumbPart)
411         m_dragOrigin = m_currentPos;
412     
413     m_pressedPos = pressedPos;
414
415     autoscrollPressedPart(theme()->initialAutoscrollTimerDelay());
416     return true;
417 }
418
419 void Scrollbar::setFrameRect(const IntRect& rect)
420 {
421     // Get our window resizer rect and see if we overlap.  Adjust to avoid the overlap
422     // if necessary.
423     IntRect adjustedRect(rect);
424     bool overlapsResizer = false;
425     ScrollView* view = parent();
426     if (view && !rect.isEmpty() && !view->windowResizerRect().isEmpty()) {
427         IntRect resizerRect = view->convertFromContainingWindow(view->windowResizerRect());
428         if (rect.intersects(resizerRect)) {
429             if (orientation() == HorizontalScrollbar) {
430                 int overlap = rect.maxX() - resizerRect.x();
431                 if (overlap > 0 && resizerRect.maxX() >= rect.maxX()) {
432                     adjustedRect.setWidth(rect.width() - overlap);
433                     overlapsResizer = true;
434                 }
435             } else {
436                 int overlap = rect.maxY() - resizerRect.y();
437                 if (overlap > 0 && resizerRect.maxY() >= rect.maxY()) {
438                     adjustedRect.setHeight(rect.height() - overlap);
439                     overlapsResizer = true;
440                 }
441             }
442         }
443     }
444     if (overlapsResizer != m_overlapsResizer) {
445         m_overlapsResizer = overlapsResizer;
446         if (view)
447             view->adjustScrollbarsAvoidingResizerCount(m_overlapsResizer ? 1 : -1);
448     }
449
450     Widget::setFrameRect(adjustedRect);
451 }
452
453 void Scrollbar::setParent(ScrollView* parentView)
454 {
455     if (!parentView && m_overlapsResizer && parent())
456         parent()->adjustScrollbarsAvoidingResizerCount(-1);
457     Widget::setParent(parentView);
458 }
459
460 void Scrollbar::setEnabled(bool e)
461
462     if (m_enabled == e)
463         return;
464     m_enabled = e;
465     theme()->updateEnabledState(this);
466     invalidate();
467 }
468
469 bool Scrollbar::isOverlayScrollbar() const
470 {
471     return m_theme->usesOverlayScrollbars();
472 }
473
474 bool Scrollbar::isWindowActive() const
475 {
476     return m_scrollableArea && m_scrollableArea->isActive();
477 }
478     
479 AXObjectCache* Scrollbar::axObjectCache() const
480 {
481     if (!parent() || !parent()->isFrameView())
482         return 0;
483     
484     // FIXME: Accessing the FrameView and Document here is a layering violation
485     // and should be removed.
486     Document* document = static_cast<FrameView*>(parent())->frame()->document();
487     return document->axObjectCache();
488 }
489
490 void Scrollbar::invalidateRect(const IntRect& rect)
491 {
492     if (suppressInvalidation())
493         return;
494
495     if (m_scrollableArea)
496         m_scrollableArea->invalidateScrollbar(this, rect);
497 }
498
499 IntRect Scrollbar::convertToContainingView(const IntRect& localRect) const
500 {
501     if (m_scrollableArea)
502         return m_scrollableArea->convertFromScrollbarToContainingView(this, localRect);
503
504     return Widget::convertToContainingView(localRect);
505 }
506
507 IntRect Scrollbar::convertFromContainingView(const IntRect& parentRect) const
508 {
509     if (m_scrollableArea)
510         return m_scrollableArea->convertFromContainingViewToScrollbar(this, parentRect);
511
512     return Widget::convertFromContainingView(parentRect);
513 }
514
515 IntPoint Scrollbar::convertToContainingView(const IntPoint& localPoint) const
516 {
517     if (m_scrollableArea)
518         return m_scrollableArea->convertFromScrollbarToContainingView(this, localPoint);
519
520     return Widget::convertToContainingView(localPoint);
521 }
522
523 IntPoint Scrollbar::convertFromContainingView(const IntPoint& parentPoint) const
524 {
525     if (m_scrollableArea)
526         return m_scrollableArea->convertFromContainingViewToScrollbar(this, parentPoint);
527
528     return Widget::convertFromContainingView(parentPoint);
529 }
530
531 } // namespace WebCore