Merge "[Release] Webkit2-efl-123997_0.11.75" into tizen_2.2
[framework/web/webkit-efl.git] / Source / WebKit2 / WebProcess / WebPage / FindController.cpp
1 /*
2  * Copyright (C) 2010 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 INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "FindController.h"
28
29 #include "ShareableBitmap.h"
30 #include "WKPage.h"
31 #include "WebCoreArgumentCoders.h"
32 #include "WebPage.h"
33 #include "WebPageProxyMessages.h"
34 #include "WebProcess.h"
35 #include <WebCore/DocumentMarkerController.h>
36 #include <WebCore/FloatQuad.h>
37 #include <WebCore/FocusController.h>
38 #include <WebCore/Frame.h>
39 #include <WebCore/FrameView.h>
40 #include <WebCore/GraphicsContext.h>
41 #include <WebCore/Page.h>
42
43 using namespace std;
44 using namespace WebCore;
45
46 namespace WebKit {
47
48 static WebCore::FindOptions core(FindOptions options)
49 {
50     return (options & FindOptionsCaseInsensitive ? CaseInsensitive : 0)
51         | (options & FindOptionsAtWordStarts ? AtWordStarts : 0)
52         | (options & FindOptionsTreatMedialCapitalAsWordStart ? TreatMedialCapitalAsWordStart : 0)
53         | (options & FindOptionsBackwards ? Backwards : 0)
54         | (options & FindOptionsWrapAround ? WrapAround : 0);
55 }
56
57 FindController::FindController(WebPage* webPage)
58     : m_webPage(webPage)
59     , m_findPageOverlay(0)
60     , m_isShowingFindIndicator(false)
61 #if ENABLE(TIZEN_FIND_STRING)
62     , m_activeMatchIndexInCurrentFrame(0)
63 #endif
64 {
65 }
66
67 FindController::~FindController()
68 {
69 }
70
71 void FindController::countStringMatches(const String& string, FindOptions options, unsigned maxMatchCount)
72 {
73     if (maxMatchCount == numeric_limits<unsigned>::max())
74         --maxMatchCount;
75     
76     unsigned matchCount = m_webPage->corePage()->markAllMatchesForText(string, core(options), false, maxMatchCount + 1);
77     m_webPage->corePage()->unmarkAllTextMatches();
78
79     // Check if we have more matches than allowed.
80     if (matchCount > maxMatchCount)
81         matchCount = static_cast<unsigned>(kWKMoreThanMaximumMatchCount);
82     
83     m_webPage->send(Messages::WebPageProxy::DidCountStringMatches(string, matchCount));
84 }
85
86 static Frame* frameWithSelection(Page* page)
87 {
88     for (Frame* frame = page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
89         if (frame->selection()->isRange())
90             return frame;
91     }
92
93     return 0;
94 }
95
96 void FindController::updateFindUIAfterPageScroll(bool found, const String& string, FindOptions options, unsigned maxMatchCount)
97 {
98     Frame* selectedFrame = frameWithSelection(m_webPage->corePage());
99
100     bool shouldShowOverlay = false;
101
102     if (!found) {
103         m_webPage->corePage()->unmarkAllTextMatches();
104
105         // Clear the selection.
106         if (selectedFrame)
107             selectedFrame->selection()->clear();
108
109         hideFindIndicator();
110
111         m_webPage->send(Messages::WebPageProxy::DidFailToFindString(string));
112     } else {
113         shouldShowOverlay = options & FindOptionsShowOverlay;
114         bool shouldShowHighlight = options & FindOptionsShowHighlight;
115         unsigned matchCount = 1;
116
117         if (shouldShowOverlay || shouldShowHighlight) {
118
119             if (maxMatchCount == numeric_limits<unsigned>::max())
120                 --maxMatchCount;
121
122             m_webPage->corePage()->unmarkAllTextMatches();
123             matchCount = m_webPage->corePage()->markAllMatchesForText(string, core(options), shouldShowHighlight, maxMatchCount + 1);
124
125             // Check if we have more matches than allowed.
126             if (matchCount > maxMatchCount) {
127                 shouldShowOverlay = false;
128                 matchCount = static_cast<unsigned>(kWKMoreThanMaximumMatchCount);
129             }
130         }
131
132         m_webPage->send(Messages::WebPageProxy::DidFindString(string, matchCount));
133
134         if (!(options & FindOptionsShowFindIndicator) || !updateFindIndicator(selectedFrame, shouldShowOverlay)) {
135             // Either we shouldn't show the find indicator, or we couldn't update it.
136             hideFindIndicator();
137         }
138     }
139
140     if (!shouldShowOverlay) {
141         if (m_findPageOverlay) {
142             // Get rid of the overlay.
143             m_webPage->uninstallPageOverlay(m_findPageOverlay, false);
144         }
145         
146         ASSERT(!m_findPageOverlay);
147     } else {
148         if (!m_findPageOverlay) {
149             RefPtr<PageOverlay> findPageOverlay = PageOverlay::create(this);
150             m_findPageOverlay = findPageOverlay.get();
151             m_webPage->installPageOverlay(findPageOverlay.release());
152         } else {
153             // The page overlay needs to be repainted.
154             m_findPageOverlay->setNeedsDisplay();
155         }
156     }
157 }
158
159 #if ENABLE(TIZEN_FIND_STRING)
160 void FindController::setActiveMatchHighlight(int activeMatchIndex)
161 {
162     if (activeMatchIndex >= static_cast<int>(m_findMatches.size()))
163         m_activeMatchIndexInCurrentFrame = 0;
164     else if (activeMatchIndex < 0)
165         m_activeMatchIndexInCurrentFrame = m_findMatches.size() - 1;
166     else
167         m_activeMatchIndexInCurrentFrame = activeMatchIndex;
168
169     Frame* frame = m_findMatches[m_activeMatchIndexInCurrentFrame]->startContainer()->document()->frame();
170     if (!frame)
171         return;
172
173     m_activeMatch = m_findMatches[m_activeMatchIndexInCurrentFrame];
174
175     // Scroll to the position of the active matching text.
176     m_activeMatch->firstNode()->renderer()->scrollRectToVisible(m_activeMatch->boundingBox(),
177         ScrollAlignment::alignCenterIfNeeded, ScrollAlignment::alignCenterIfNeeded);
178
179     frame->document()->markers()->setMarkersActive(m_activeMatch.get(), true);
180 }
181 #endif
182
183 void FindController::findString(const String& string, FindOptions options, unsigned maxMatchCount)
184 {
185 #if ENABLE(TIZEN_FIND_STRING)
186     m_findMatches.clear();
187     int indexForSelection;
188
189     m_webPage->corePage()->findStringMatchingRanges(string, core(options), maxMatchCount, &m_findMatches, indexForSelection);
190
191     bool found = !m_findMatches.isEmpty();
192
193     // highlight the text matches found.
194     m_webPage->drawingArea()->dispatchAfterEnsuringUpdatedScrollPosition(WTF::bind(&FindController::updateFindUIAfterPageScroll, this, found, string, options, maxMatchCount));
195
196     if (!found) {
197         m_activeMatchIndexInCurrentFrame = -1;
198         return;
199     }
200
201     if (!m_oldString || m_oldString != string) {
202         m_oldString = string;
203         if (options & FindOptionsBackwards)
204             setActiveMatchHighlight(m_findMatches.size() - 1); // Should we use m_lastMatchCount instead of m_findMatches.size()
205         else
206             setActiveMatchHighlight(0);
207     } else {
208         if (options & FindOptionsBackwards)
209             setActiveMatchHighlight(m_activeMatchIndexInCurrentFrame - 1);
210         else
211             setActiveMatchHighlight(m_activeMatchIndexInCurrentFrame + 1);
212     }
213 #else
214     bool found = m_webPage->corePage()->findString(string, core(options));
215
216     m_webPage->drawingArea()->dispatchAfterEnsuringUpdatedScrollPosition(WTF::bind(&FindController::updateFindUIAfterPageScroll, this, found, string, options, maxMatchCount));
217 #endif
218 }
219
220 void FindController::findStringMatches(const String& string, FindOptions options, unsigned maxMatchCount)
221 {
222     m_findMatches.clear();
223     int indexForSelection;
224
225     m_webPage->corePage()->findStringMatchingRanges(string, core(options), maxMatchCount, &m_findMatches, indexForSelection);
226
227     Vector<Vector<IntRect> > matchRects;
228     for (size_t i = 0; i < m_findMatches.size(); ++i) {
229         Vector<IntRect> rects;
230         m_findMatches[i]->textRects(rects);
231         matchRects.append(rects);
232     }
233
234     m_webPage->send(Messages::WebPageProxy::DidFindStringMatches(string, matchRects, indexForSelection));
235 }
236
237 bool FindController::getFindIndicatorBitmapAndRect(Frame* frame, ShareableBitmap::Handle& handle, IntRect& selectionRect)
238 {
239     selectionRect = enclosingIntRect(frame->selection()->bounds());
240
241     // Selection rect can be empty for matches that are currently obscured from view.
242     if (selectionRect.isEmpty())
243         return false;
244
245     IntSize backingStoreSize = selectionRect.size();
246     backingStoreSize.scale(m_webPage->corePage()->deviceScaleFactor());
247
248     // Create a backing store and paint the find indicator text into it.
249     RefPtr<ShareableBitmap> findIndicatorTextBackingStore = ShareableBitmap::createShareable(backingStoreSize, ShareableBitmap::SupportsAlpha);
250     if (!findIndicatorTextBackingStore)
251         return false;
252
253     OwnPtr<GraphicsContext> graphicsContext = findIndicatorTextBackingStore->createGraphicsContext();
254     graphicsContext->scale(FloatSize(m_webPage->corePage()->deviceScaleFactor(), m_webPage->corePage()->deviceScaleFactor()));
255
256     IntRect paintRect = selectionRect;
257     paintRect.move(frame->view()->frameRect().x(), frame->view()->frameRect().y());
258     paintRect.move(-frame->view()->scrollOffset());
259
260     graphicsContext->translate(-paintRect.x(), -paintRect.y());
261     frame->view()->setPaintBehavior(PaintBehaviorSelectionOnly | PaintBehaviorForceBlackText | PaintBehaviorFlattenCompositingLayers);
262     frame->document()->updateLayout();
263
264     frame->view()->paint(graphicsContext.get(), paintRect);
265     frame->view()->setPaintBehavior(PaintBehaviorNormal);
266
267     if (!findIndicatorTextBackingStore->createHandle(handle))
268         return false;
269     return true;
270 }
271
272 void FindController::getImageForFindMatch(uint32_t matchIndex)
273 {
274     if (matchIndex >= m_findMatches.size())
275         return;
276     Frame* frame = m_findMatches[matchIndex]->startContainer()->document()->frame();
277     if (!frame)
278         return;
279
280     VisibleSelection oldSelection = frame->selection()->selection();
281     frame->selection()->setSelection(VisibleSelection(m_findMatches[matchIndex].get()));
282
283     IntRect selectionRect;
284     ShareableBitmap::Handle handle;
285     getFindIndicatorBitmapAndRect(frame, handle, selectionRect);
286
287     frame->selection()->setSelection(oldSelection);
288
289     m_webPage->send(Messages::WebPageProxy::DidGetImageForFindMatch(handle, matchIndex));
290 }
291
292 void FindController::selectFindMatch(uint32_t matchIndex)
293 {
294     if (matchIndex >= m_findMatches.size())
295         return;
296     Frame* frame = m_findMatches[matchIndex]->startContainer()->document()->frame();
297     if (!frame)
298         return;
299     frame->selection()->setSelection(VisibleSelection(m_findMatches[matchIndex].get()));
300 }
301
302 void FindController::hideFindUI()
303 {
304     m_findMatches.clear();
305     if (m_findPageOverlay)
306         m_webPage->uninstallPageOverlay(m_findPageOverlay, false);
307
308     m_webPage->corePage()->unmarkAllTextMatches();
309     hideFindIndicator();
310 }
311
312 bool FindController::updateFindIndicator(Frame* selectedFrame, bool isShowingOverlay, bool shouldAnimate)
313 {
314     if (!selectedFrame)
315         return false;
316
317     IntRect selectionRect;
318     ShareableBitmap::Handle handle;
319     if (!getFindIndicatorBitmapAndRect(selectedFrame, handle, selectionRect))
320         return false;
321
322     // We want the selection rect in window coordinates.
323     IntRect selectionRectInWindowCoordinates = selectedFrame->view()->contentsToWindow(selectionRect);
324
325     Vector<FloatRect> textRects;
326     selectedFrame->selection()->getClippedVisibleTextRectangles(textRects);
327
328     // We want the text rects in selection rect coordinates.
329     Vector<FloatRect> textRectsInSelectionRectCoordinates;
330     
331     for (size_t i = 0; i < textRects.size(); ++i) {
332         IntRect textRectInSelectionRectCoordinates = selectedFrame->view()->contentsToWindow(enclosingIntRect(textRects[i]));
333         textRectInSelectionRectCoordinates.move(-selectionRectInWindowCoordinates.x(), -selectionRectInWindowCoordinates.y());
334
335         textRectsInSelectionRectCoordinates.append(textRectInSelectionRectCoordinates);
336     }            
337
338     m_webPage->send(Messages::WebPageProxy::SetFindIndicator(selectionRectInWindowCoordinates, textRectsInSelectionRectCoordinates, m_webPage->corePage()->deviceScaleFactor(), handle, !isShowingOverlay, shouldAnimate));
339     m_findIndicatorRect = selectionRectInWindowCoordinates;
340     m_isShowingFindIndicator = true;
341
342     return true;
343 }
344
345 void FindController::hideFindIndicator()
346 {
347     if (!m_isShowingFindIndicator)
348         return;
349
350     ShareableBitmap::Handle handle;
351     m_webPage->send(Messages::WebPageProxy::SetFindIndicator(FloatRect(), Vector<FloatRect>(), m_webPage->corePage()->deviceScaleFactor(), handle, false, true));
352     m_isShowingFindIndicator = false;
353 }
354
355 void FindController::showFindIndicatorInSelection()
356 {
357     Frame* selectedFrame = m_webPage->corePage()->focusController()->focusedOrMainFrame();
358     if (!selectedFrame)
359         return;
360     
361     updateFindIndicator(selectedFrame, false);
362 }
363
364 void FindController::deviceScaleFactorDidChange()
365 {
366     ASSERT(isShowingOverlay());
367
368     Frame* selectedFrame = frameWithSelection(m_webPage->corePage());
369     if (!selectedFrame)
370         return;
371
372     updateFindIndicator(selectedFrame, true, false);
373 }
374
375 Vector<IntRect> FindController::rectsForTextMatches()
376 {
377     Vector<IntRect> rects;
378
379     for (Frame* frame = m_webPage->corePage()->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
380         Document* document = frame->document();
381         if (!document)
382             continue;
383
384         IntRect visibleRect = frame->view()->visibleContentRect();
385         Vector<IntRect> frameRects = document->markers()->renderedRectsForMarkers(DocumentMarker::TextMatch);
386
387 #if !ENABLE(TIZEN_WEBKIT2_TILED_AC)
388         IntPoint frameOffset(-frame->view()->scrollOffset().width(), -frame->view()->scrollOffset().height());
389         frameOffset = frame->view()->convertToContainingWindow(frameOffset);
390 #else
391         IntPoint frameOffset;
392         if (!frame->view()->delegatesScrolling()) {
393             frameOffset = IntPoint(-frame->view()->scrollOffset().width(), -frame->view()->scrollOffset().height());
394             frameOffset = frame->view()->convertToContainingWindow(frameOffset);
395         }
396 #endif
397
398         for (Vector<IntRect>::iterator it = frameRects.begin(), end = frameRects.end(); it != end; ++it) {
399             it->intersect(visibleRect);
400             it->move(frameOffset.x(), frameOffset.y());
401             rects.append(*it);
402         }
403     }
404
405     return rects;
406 }
407
408 void FindController::pageOverlayDestroyed(PageOverlay*)
409 {
410 }
411
412 void FindController::willMoveToWebPage(PageOverlay*, WebPage* webPage)
413 {
414     if (webPage)
415         return;
416
417     // The page overlay is moving away from the web page, reset it.
418     ASSERT(m_findPageOverlay);
419     m_findPageOverlay = 0;
420 }
421     
422 void FindController::didMoveToWebPage(PageOverlay*, WebPage*)
423 {
424 }
425
426 static const float shadowOffsetX = 0.0;
427 static const float shadowOffsetY = 1.0;
428 static const float shadowBlurRadius = 2.0;
429 static const float whiteFrameThickness = 1.0;
430
431 static const float overlayBackgroundRed = 0.1;
432 static const float overlayBackgroundGreen = 0.1;
433 static const float overlayBackgroundBlue = 0.1;
434 static const float overlayBackgroundAlpha = 0.25;
435
436 static Color overlayBackgroundColor(float fractionFadedIn)
437 {
438     return Color(overlayBackgroundRed, overlayBackgroundGreen, overlayBackgroundBlue, overlayBackgroundAlpha * fractionFadedIn);
439 }
440
441 static Color holeShadowColor(float fractionFadedIn)
442 {
443     return Color(0.0f, 0.0f, 0.0f, fractionFadedIn);
444 }
445
446 static Color holeFillColor(float fractionFadedIn)
447 {
448     return Color(1.0f, 1.0f, 1.0f, fractionFadedIn);
449 }
450
451 void FindController::drawRect(PageOverlay* pageOverlay, GraphicsContext& graphicsContext, const IntRect& dirtyRect)
452 {
453     float fractionFadedIn = pageOverlay->fractionFadedIn();
454
455     Vector<IntRect> rects = rectsForTextMatches();
456
457     // Draw the background.
458     graphicsContext.fillRect(dirtyRect, overlayBackgroundColor(fractionFadedIn), ColorSpaceSRGB);
459
460     {
461         GraphicsContextStateSaver stateSaver(graphicsContext);
462
463         graphicsContext.setShadow(FloatSize(shadowOffsetX, shadowOffsetY), shadowBlurRadius, holeShadowColor(fractionFadedIn), ColorSpaceSRGB);
464         graphicsContext.setFillColor(holeFillColor(fractionFadedIn), ColorSpaceSRGB);
465
466         // Draw white frames around the holes.
467         for (size_t i = 0; i < rects.size(); ++i) {
468             IntRect whiteFrameRect = rects[i];
469             whiteFrameRect.inflate(1);
470
471             graphicsContext.fillRect(whiteFrameRect);
472         }
473     }
474
475     graphicsContext.setFillColor(Color::transparent, ColorSpaceSRGB);
476
477     // Clear out the holes.
478     for (size_t i = 0; i < rects.size(); ++i)
479         graphicsContext.fillRect(rects[i]);
480
481     if (!m_isShowingFindIndicator)
482         return;
483
484     if (Frame* selectedFrame = frameWithSelection(m_webPage->corePage())) {
485         IntRect findIndicatorRect = selectedFrame->view()->contentsToWindow(enclosingIntRect(selectedFrame->selection()->bounds()));
486
487         if (findIndicatorRect != m_findIndicatorRect)
488             hideFindIndicator();
489     }
490 }
491
492 bool FindController::mouseEvent(PageOverlay* pageOverlay, const WebMouseEvent& mouseEvent)
493 {
494     // If we get a mouse down event inside the page overlay we should hide the find UI.
495     if (mouseEvent.type() == WebEvent::MouseDown) {
496         // Dismiss the overlay.
497         hideFindUI();
498     }
499
500     return false;
501 }
502
503 } // namespace WebKit