tizen beta release
[profile/ivi/webkit-efl.git] / 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::theme()->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::theme();
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
121 #if ENABLE(TIZEN_CAIRO_SCALE_PATCH)
122     ScrollView * sv = (ScrollView *)m_scrollableArea;
123     position *= sv->scaleFactor();
124 #endif
125
126     if (position == m_currentPos)
127         return;
128
129     int oldThumbPosition = theme()->thumbPosition(this);
130     m_currentPos = position;
131     updateThumbPosition();
132     if (m_pressedPart == ThumbPart)
133         setPressedPos(m_pressedPos + theme()->thumbPosition(this) - oldThumbPosition);    
134 }
135
136 void Scrollbar::setProportion(int visibleSize, int totalSize)
137 {
138     if (visibleSize == m_visibleSize && totalSize == m_totalSize)
139         return;
140
141     m_visibleSize = visibleSize;
142     m_totalSize = totalSize;
143
144     updateThumbProportion();
145 }
146
147 void Scrollbar::setSteps(int lineStep, int pageStep, int pixelsPerStep)
148 {
149     m_lineStep = lineStep;
150     m_pageStep = pageStep;
151     m_pixelStep = 1.0f / pixelsPerStep;
152 }
153
154 void Scrollbar::updateThumb()
155 {
156 #ifdef THUMB_POSITION_AFFECTS_BUTTONS
157     invalidate();
158 #else
159     theme()->invalidateParts(this, ForwardTrackPart | BackTrackPart | ThumbPart);
160 #endif
161 }
162
163 void Scrollbar::updateThumbPosition()
164 {
165     updateThumb();
166 }
167
168 void Scrollbar::updateThumbProportion()
169 {
170     updateThumb();
171 }
172
173 void Scrollbar::paint(GraphicsContext* context, const IntRect& damageRect)
174 {
175     if (context->updatingControlTints() && theme()->supportsControlTints()) {
176         invalidate();
177         return;
178     }
179
180     if (context->paintingDisabled() || !frameRect().intersects(damageRect))
181         return;
182
183     if (!theme()->paint(this, context, damageRect))
184         Widget::paint(context, damageRect);
185 }
186
187 void Scrollbar::autoscrollTimerFired(Timer<Scrollbar>*)
188 {
189     autoscrollPressedPart(theme()->autoscrollTimerDelay());
190 }
191
192 static bool thumbUnderMouse(Scrollbar* scrollbar)
193 {
194     int thumbPos = scrollbar->theme()->trackPosition(scrollbar) + scrollbar->theme()->thumbPosition(scrollbar);
195     int thumbLength = scrollbar->theme()->thumbLength(scrollbar);
196     return scrollbar->pressedPos() >= thumbPos && scrollbar->pressedPos() < thumbPos + thumbLength;
197 }
198
199 void Scrollbar::autoscrollPressedPart(double delay)
200 {
201     // Don't do anything for the thumb or if nothing was pressed.
202     if (m_pressedPart == ThumbPart || m_pressedPart == NoPart)
203         return;
204
205     // Handle the track.
206     if ((m_pressedPart == BackTrackPart || m_pressedPart == ForwardTrackPart) && thumbUnderMouse(this)) {
207         theme()->invalidatePart(this, m_pressedPart);
208         setHoveredPart(ThumbPart);
209         return;
210     }
211
212     // Handle the arrows and track.
213     if (m_scrollableArea && m_scrollableArea->scroll(pressedPartScrollDirection(), pressedPartScrollGranularity()))
214         startTimerIfNeeded(delay);
215 }
216
217 void Scrollbar::startTimerIfNeeded(double delay)
218 {
219     // Don't do anything for the thumb.
220     if (m_pressedPart == ThumbPart)
221         return;
222
223     // Handle the track.  We halt track scrolling once the thumb is level
224     // with us.
225     if ((m_pressedPart == BackTrackPart || m_pressedPart == ForwardTrackPart) && thumbUnderMouse(this)) {
226         theme()->invalidatePart(this, m_pressedPart);
227         setHoveredPart(ThumbPart);
228         return;
229     }
230
231     // We can't scroll if we've hit the beginning or end.
232     ScrollDirection dir = pressedPartScrollDirection();
233     if (dir == ScrollUp || dir == ScrollLeft) {
234         if (m_currentPos == 0)
235             return;
236     } else {
237         if (m_currentPos == maximum())
238             return;
239     }
240
241     m_scrollTimer.startOneShot(delay);
242 }
243
244 void Scrollbar::stopTimerIfNeeded()
245 {
246     if (m_scrollTimer.isActive())
247         m_scrollTimer.stop();
248 }
249
250 ScrollDirection Scrollbar::pressedPartScrollDirection()
251 {
252     if (m_orientation == HorizontalScrollbar) {
253         if (m_pressedPart == BackButtonStartPart || m_pressedPart == BackButtonEndPart || m_pressedPart == BackTrackPart)
254             return ScrollLeft;
255         return ScrollRight;
256     } else {
257         if (m_pressedPart == BackButtonStartPart || m_pressedPart == BackButtonEndPart || m_pressedPart == BackTrackPart)
258             return ScrollUp;
259         return ScrollDown;
260     }
261 }
262
263 ScrollGranularity Scrollbar::pressedPartScrollGranularity()
264 {
265     if (m_pressedPart == BackButtonStartPart || m_pressedPart == BackButtonEndPart ||  m_pressedPart == ForwardButtonStartPart || m_pressedPart == ForwardButtonEndPart)
266         return ScrollByLine;
267     return ScrollByPage;
268 }
269
270 void Scrollbar::moveThumb(int pos, bool draggingDocument)
271 {
272     if (!m_scrollableArea)
273         return;
274
275     int delta = pos - m_pressedPos;
276
277     if (draggingDocument) {
278         if (m_draggingDocument)
279             delta = pos - m_documentDragPos;
280         m_draggingDocument = true;
281         FloatPoint currentPosition = m_scrollableArea->scrollAnimator()->currentPosition();
282         int destinationPosition = (m_orientation == HorizontalScrollbar ? currentPosition.x() : currentPosition.y()) + delta;
283         if (delta > 0)
284             destinationPosition = min(destinationPosition + delta, maximum());
285         else if (delta < 0)
286             destinationPosition = max(destinationPosition + delta, 0);
287         m_scrollableArea->scrollToOffsetWithoutAnimation(m_orientation, destinationPosition);
288         m_documentDragPos = pos;
289         return;
290     }
291
292     if (m_draggingDocument) {
293         delta += m_pressedPos - m_documentDragPos;
294         m_draggingDocument = false;
295     }
296
297     // Drag the thumb.
298     int thumbPos = theme()->thumbPosition(this);
299     int thumbLen = theme()->thumbLength(this);
300     int trackLen = theme()->trackLength(this);
301     int maxPos = trackLen - thumbLen;
302     if (delta > 0)
303         delta = min(maxPos - thumbPos, delta);
304     else if (delta < 0)
305         delta = max(-thumbPos, delta);
306     
307     if (delta) {
308         float newPosition = static_cast<float>(thumbPos + delta) * maximum() / (trackLen - thumbLen);
309         m_scrollableArea->scrollToOffsetWithoutAnimation(m_orientation, newPosition);
310     }
311 }
312
313 void Scrollbar::setHoveredPart(ScrollbarPart part)
314 {
315     if (part == m_hoveredPart)
316         return;
317
318     if ((m_hoveredPart == NoPart || part == NoPart) && theme()->invalidateOnMouseEnterExit())
319         invalidate();  // Just invalidate the whole scrollbar, since the buttons at either end change anyway.
320     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.
321         theme()->invalidatePart(this, part);
322         theme()->invalidatePart(this, m_hoveredPart);
323     }
324     m_hoveredPart = part;
325 }
326
327 void Scrollbar::setPressedPart(ScrollbarPart part)
328 {
329     if (m_pressedPart != NoPart)
330         theme()->invalidatePart(this, m_pressedPart);
331     m_pressedPart = part;
332     if (m_pressedPart != NoPart)
333         theme()->invalidatePart(this, m_pressedPart);
334     else if (m_hoveredPart != NoPart)  // When we no longer have a pressed part, we can start drawing a hovered state on the hovered part.
335         theme()->invalidatePart(this, m_hoveredPart);
336 }
337
338 bool Scrollbar::mouseMoved(const PlatformMouseEvent& evt)
339 {
340     if (m_pressedPart == ThumbPart) {
341         if (theme()->shouldSnapBackToDragOrigin(this, evt)) {
342             if (m_scrollableArea)
343                 m_scrollableArea->scrollToOffsetWithoutAnimation(m_orientation, m_dragOrigin);
344         } else {
345             moveThumb(m_orientation == HorizontalScrollbar ? 
346                       convertFromContainingWindow(evt.pos()).x() :
347                       convertFromContainingWindow(evt.pos()).y(), theme()->shouldDragDocumentInsteadOfThumb(this, evt));
348         }
349         return true;
350     }
351
352     if (m_pressedPart != NoPart)
353         m_pressedPos = (orientation() == HorizontalScrollbar ? convertFromContainingWindow(evt.pos()).x() : convertFromContainingWindow(evt.pos()).y());
354
355     ScrollbarPart part = theme()->hitTest(this, evt);
356     if (part != m_hoveredPart) {
357         if (m_pressedPart != NoPart) {
358             if (part == m_pressedPart) {
359                 // The mouse is moving back over the pressed part.  We
360                 // need to start up the timer action again.
361                 startTimerIfNeeded(theme()->autoscrollTimerDelay());
362                 theme()->invalidatePart(this, m_pressedPart);
363             } else if (m_hoveredPart == m_pressedPart) {
364                 // The mouse is leaving the pressed part.  Kill our timer
365                 // if needed.
366                 stopTimerIfNeeded();
367                 theme()->invalidatePart(this, m_pressedPart);
368             }
369         } 
370         
371         setHoveredPart(part);
372     } 
373
374     return true;
375 }
376
377 void Scrollbar::mouseEntered()
378 {
379     if (m_scrollableArea)
380         m_scrollableArea->scrollAnimator()->mouseEnteredScrollbar(this);
381 }
382
383 bool Scrollbar::mouseExited()
384 {
385     if (m_scrollableArea)
386         m_scrollableArea->scrollAnimator()->mouseExitedScrollbar(this);
387     setHoveredPart(NoPart);
388     return true;
389 }
390
391 bool Scrollbar::mouseUp(const PlatformMouseEvent& mouseEvent)
392 {
393     setPressedPart(NoPart);
394     m_pressedPos = 0;
395     m_draggingDocument = false;
396     stopTimerIfNeeded();
397
398     if (m_scrollableArea) {
399         // m_hoveredPart won't be updated until the next mouseMoved or mouseDown, so we have to hit test
400         // to really know if the mouse has exited the scrollbar on a mouseUp.
401         ScrollbarPart part = theme()->hitTest(this, mouseEvent);
402         if (part == NoPart)
403             m_scrollableArea->scrollAnimator()->mouseExitedScrollbar(this);
404     }
405
406     if (parent() && parent()->isFrameView())
407         static_cast<FrameView*>(parent())->frame()->eventHandler()->setMousePressed(false);
408
409     return true;
410 }
411
412 bool Scrollbar::mouseDown(const PlatformMouseEvent& evt)
413 {
414     // Early exit for right click
415     if (evt.button() == RightButton)
416         return true; // FIXME: Handled as context menu by Qt right now.  Should just avoid even calling this method on a right click though.
417
418     setPressedPart(theme()->hitTest(this, evt));
419     int pressedPos = (orientation() == HorizontalScrollbar ? convertFromContainingWindow(evt.pos()).x() : convertFromContainingWindow(evt.pos()).y());
420     
421     if ((m_pressedPart == BackTrackPart || m_pressedPart == ForwardTrackPart) && theme()->shouldCenterOnThumb(this, evt)) {
422         setHoveredPart(ThumbPart);
423         setPressedPart(ThumbPart);
424         m_dragOrigin = m_currentPos;
425         int thumbLen = theme()->thumbLength(this);
426         int desiredPos = pressedPos;
427         // Set the pressed position to the middle of the thumb so that when we do the move, the delta
428         // will be from the current pixel position of the thumb to the new desired position for the thumb.
429         m_pressedPos = theme()->trackPosition(this) + theme()->thumbPosition(this) + thumbLen / 2;
430         moveThumb(desiredPos);
431         return true;
432     } else if (m_pressedPart == ThumbPart)
433         m_dragOrigin = m_currentPos;
434     
435     m_pressedPos = pressedPos;
436
437     autoscrollPressedPart(theme()->initialAutoscrollTimerDelay());
438     return true;
439 }
440
441 void Scrollbar::setFrameRect(const IntRect& rect)
442 {
443     // Get our window resizer rect and see if we overlap.  Adjust to avoid the overlap
444     // if necessary.
445     IntRect adjustedRect(rect);
446     bool overlapsResizer = false;
447     ScrollView* view = parent();
448     if (view && !rect.isEmpty() && !view->windowResizerRect().isEmpty()) {
449         IntRect resizerRect = view->convertFromContainingWindow(view->windowResizerRect());
450         if (rect.intersects(resizerRect)) {
451             if (orientation() == HorizontalScrollbar) {
452                 int overlap = rect.maxX() - resizerRect.x();
453                 if (overlap > 0 && resizerRect.maxX() >= rect.maxX()) {
454                     adjustedRect.setWidth(rect.width() - overlap);
455                     overlapsResizer = true;
456                 }
457             } else {
458                 int overlap = rect.maxY() - resizerRect.y();
459                 if (overlap > 0 && resizerRect.maxY() >= rect.maxY()) {
460                     adjustedRect.setHeight(rect.height() - overlap);
461                     overlapsResizer = true;
462                 }
463             }
464         }
465     }
466     if (overlapsResizer != m_overlapsResizer) {
467         m_overlapsResizer = overlapsResizer;
468         if (view)
469             view->adjustScrollbarsAvoidingResizerCount(m_overlapsResizer ? 1 : -1);
470     }
471
472     Widget::setFrameRect(adjustedRect);
473 }
474
475 void Scrollbar::setParent(ScrollView* parentView)
476 {
477     if (!parentView && m_overlapsResizer && parent())
478         parent()->adjustScrollbarsAvoidingResizerCount(-1);
479     Widget::setParent(parentView);
480 }
481
482 void Scrollbar::setEnabled(bool e)
483
484     if (m_enabled == e)
485         return;
486     m_enabled = e;
487     theme()->updateEnabledState(this);
488     invalidate();
489 }
490
491 bool Scrollbar::isOverlayScrollbar() const
492 {
493     return m_theme->usesOverlayScrollbars();
494 }
495
496 bool Scrollbar::isWindowActive() const
497 {
498     return m_scrollableArea && m_scrollableArea->isActive();
499 }
500     
501 AXObjectCache* Scrollbar::axObjectCache() const
502 {
503     if (!parent() || !parent()->isFrameView())
504         return 0;
505     
506     // FIXME: Accessing the FrameView and Document here is a layering violation
507     // and should be removed.
508     Document* document = static_cast<FrameView*>(parent())->frame()->document();
509     return document->axObjectCache();
510 }
511
512 void Scrollbar::invalidateRect(const IntRect& rect)
513 {
514     if (suppressInvalidation())
515         return;
516
517     if (m_scrollableArea)
518         m_scrollableArea->invalidateScrollbar(this, rect);
519 }
520
521 IntRect Scrollbar::convertToContainingView(const IntRect& localRect) const
522 {
523     if (m_scrollableArea)
524         return m_scrollableArea->convertFromScrollbarToContainingView(this, localRect);
525
526     return Widget::convertToContainingView(localRect);
527 }
528
529 IntRect Scrollbar::convertFromContainingView(const IntRect& parentRect) const
530 {
531     if (m_scrollableArea)
532         return m_scrollableArea->convertFromContainingViewToScrollbar(this, parentRect);
533
534     return Widget::convertFromContainingView(parentRect);
535 }
536
537 IntPoint Scrollbar::convertToContainingView(const IntPoint& localPoint) const
538 {
539     if (m_scrollableArea)
540         return m_scrollableArea->convertFromScrollbarToContainingView(this, localPoint);
541
542     return Widget::convertToContainingView(localPoint);
543 }
544
545 IntPoint Scrollbar::convertFromContainingView(const IntPoint& parentPoint) const
546 {
547     if (m_scrollableArea)
548         return m_scrollableArea->convertFromContainingViewToScrollbar(this, parentPoint);
549
550     return Widget::convertFromContainingView(parentPoint);
551 }
552
553 } // namespace WebCore