1/*
2 * Copyright (C) 2006, 2007, 2009, 2011 Apple Inc. All rights reserved.
3 * Copyright (C) 2008, 2010 Nokia Corporation and/or its subsidiary(-ies)
4 * Copyright (C) 2012, Samsung Electronics. All rights reserved.
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Library General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 * Library General Public License for more details.
15 *
16 * You should have received a copy of the GNU Library General Public License
17 * along with this library; see the file COPYING.LIB.  If not, write to
18 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19 * Boston, MA 02110-1301, USA.
20 */
21
22#include "config.h"
23#include "core/page/Chrome.h"
24
25#include "public/platform/WebScreenInfo.h"
26#include "HTMLNames.h"
27#include "core/dom/Document.h"
28#include "core/html/HTMLInputElement.h"
29#include "core/inspector/InspectorInstrumentation.h"
30#include "core/page/ChromeClient.h"
31#include "core/page/Frame.h"
32#include "core/page/FrameTree.h"
33#include "core/page/Page.h"
34#include "core/page/PageGroupLoadDeferrer.h"
35#include "core/page/PopupOpeningObserver.h"
36#include "core/page/WindowFeatures.h"
37#include "core/platform/ColorChooser.h"
38#include "core/platform/DateTimeChooser.h"
39#include "core/platform/FileChooser.h"
40#include "core/platform/graphics/FloatRect.h"
41#include "core/platform/network/DNS.h"
42#include "core/rendering/HitTestResult.h"
43#include "wtf/PassRefPtr.h"
44#include "wtf/Vector.h"
45
46namespace WebCore {
47
48using namespace HTMLNames;
49using namespace std;
50
51Chrome::Chrome(Page* page, ChromeClient* client)
52    : m_page(page)
53    , m_client(client)
54{
55    ASSERT(m_client);
56}
57
58Chrome::~Chrome()
59{
60    m_client->chromeDestroyed();
61}
62
63PassOwnPtr<Chrome> Chrome::create(Page* page, ChromeClient* client)
64{
65    return adoptPtr(new Chrome(page, client));
66}
67
68void Chrome::invalidateContentsAndRootView(const IntRect& updateRect)
69{
70    m_client->invalidateContentsAndRootView(updateRect);
71}
72
73void Chrome::invalidateContentsForSlowScroll(const IntRect& updateRect)
74{
75    m_client->invalidateContentsForSlowScroll(updateRect);
76}
77
78void Chrome::scroll(const IntSize& scrollDelta, const IntRect& rectToScroll, const IntRect& clipRect)
79{
80    m_client->scroll(scrollDelta, rectToScroll, clipRect);
81    InspectorInstrumentation::didScroll(m_page);
82}
83
84IntPoint Chrome::screenToRootView(const IntPoint& point) const
85{
86    return m_client->screenToRootView(point);
87}
88
89IntRect Chrome::rootViewToScreen(const IntRect& rect) const
90{
91    return m_client->rootViewToScreen(rect);
92}
93
94WebKit::WebScreenInfo Chrome::screenInfo() const
95{
96    return m_client->screenInfo();
97}
98
99void Chrome::contentsSizeChanged(Frame* frame, const IntSize& size) const
100{
101    m_client->contentsSizeChanged(frame, size);
102}
103
104void Chrome::layoutUpdated(Frame* frame) const
105{
106    m_client->layoutUpdated(frame);
107}
108
109void Chrome::setWindowRect(const FloatRect& rect) const
110{
111    m_client->setWindowRect(rect);
112}
113
114FloatRect Chrome::windowRect() const
115{
116    return m_client->windowRect();
117}
118
119FloatRect Chrome::pageRect() const
120{
121    return m_client->pageRect();
122}
123
124void Chrome::focus() const
125{
126    m_client->focus();
127}
128
129void Chrome::unfocus() const
130{
131    m_client->unfocus();
132}
133
134bool Chrome::canTakeFocus(FocusDirection direction) const
135{
136    return m_client->canTakeFocus(direction);
137}
138
139void Chrome::takeFocus(FocusDirection direction) const
140{
141    m_client->takeFocus(direction);
142}
143
144void Chrome::focusedNodeChanged(Node* node) const
145{
146    m_client->focusedNodeChanged(node);
147}
148
149void Chrome::show(NavigationPolicy policy) const
150{
151    m_client->show(policy);
152}
153
154bool Chrome::canRunModal() const
155{
156    return m_client->canRunModal();
157}
158
159static bool canRunModalIfDuringPageDismissal(Page* page, ChromeClient::DialogType dialog, const String& message)
160{
161    for (Frame* frame = page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
162        FrameLoader::PageDismissalType dismissal = frame->loader()->pageDismissalEventBeingDispatched();
163        if (dismissal != FrameLoader::NoDismissal)
164            return page->chrome().client()->shouldRunModalDialogDuringPageDismissal(dialog, message, dismissal);
165    }
166    return true;
167}
168
169bool Chrome::canRunModalNow() const
170{
171    return canRunModal() && canRunModalIfDuringPageDismissal(m_page, ChromeClient::HTMLDialog, String());
172}
173
174void Chrome::runModal() const
175{
176    // Defer callbacks in all the other pages in this group, so we don't try to run JavaScript
177    // in a way that could interact with this view.
178    PageGroupLoadDeferrer deferrer(m_page, false);
179
180    TimerBase::fireTimersInNestedEventLoop();
181    m_client->runModal();
182}
183
184void Chrome::setWindowFeatures(const WindowFeatures& features) const
185{
186    m_client->setToolbarsVisible(features.toolBarVisible || features.locationBarVisible);
187    m_client->setStatusbarVisible(features.statusBarVisible);
188    m_client->setScrollbarsVisible(features.scrollbarsVisible);
189    m_client->setMenubarVisible(features.menuBarVisible);
190    m_client->setResizable(features.resizable);
191}
192
193bool Chrome::toolbarsVisible() const
194{
195    return m_client->toolbarsVisible();
196}
197
198bool Chrome::statusbarVisible() const
199{
200    return m_client->statusbarVisible();
201}
202
203bool Chrome::scrollbarsVisible() const
204{
205    return m_client->scrollbarsVisible();
206}
207
208bool Chrome::menubarVisible() const
209{
210    return m_client->menubarVisible();
211}
212
213bool Chrome::canRunBeforeUnloadConfirmPanel()
214{
215    return m_client->canRunBeforeUnloadConfirmPanel();
216}
217
218bool Chrome::runBeforeUnloadConfirmPanel(const String& message, Frame* frame)
219{
220    // Defer loads in case the client method runs a new event loop that would
221    // otherwise cause the load to continue while we're in the middle of executing JavaScript.
222    PageGroupLoadDeferrer deferrer(m_page, true);
223
224    InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRunJavaScriptDialog(m_page, message);
225    bool ok = m_client->runBeforeUnloadConfirmPanel(message, frame);
226    InspectorInstrumentation::didRunJavaScriptDialog(cookie);
227    return ok;
228}
229
230void Chrome::closeWindowSoon()
231{
232    m_client->closeWindowSoon();
233}
234
235void Chrome::runJavaScriptAlert(Frame* frame, const String& message)
236{
237    if (!canRunModalIfDuringPageDismissal(m_page, ChromeClient::AlertDialog, message))
238        return;
239
240    // Defer loads in case the client method runs a new event loop that would
241    // otherwise cause the load to continue while we're in the middle of executing JavaScript.
242    PageGroupLoadDeferrer deferrer(m_page, true);
243
244    ASSERT(frame);
245    notifyPopupOpeningObservers();
246    String displayMessage = frame->displayStringModifiedByEncoding(message);
247
248    InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRunJavaScriptDialog(m_page, displayMessage);
249    m_client->runJavaScriptAlert(frame, displayMessage);
250    InspectorInstrumentation::didRunJavaScriptDialog(cookie);
251}
252
253bool Chrome::runJavaScriptConfirm(Frame* frame, const String& message)
254{
255    if (!canRunModalIfDuringPageDismissal(m_page, ChromeClient::ConfirmDialog, message))
256        return false;
257
258    // Defer loads in case the client method runs a new event loop that would
259    // otherwise cause the load to continue while we're in the middle of executing JavaScript.
260    PageGroupLoadDeferrer deferrer(m_page, true);
261
262    ASSERT(frame);
263    notifyPopupOpeningObservers();
264    String displayMessage = frame->displayStringModifiedByEncoding(message);
265
266    InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRunJavaScriptDialog(m_page, displayMessage);
267    bool ok = m_client->runJavaScriptConfirm(frame, displayMessage);
268    InspectorInstrumentation::didRunJavaScriptDialog(cookie);
269    return ok;
270}
271
272bool Chrome::runJavaScriptPrompt(Frame* frame, const String& prompt, const String& defaultValue, String& result)
273{
274    if (!canRunModalIfDuringPageDismissal(m_page, ChromeClient::PromptDialog, prompt))
275        return false;
276
277    // Defer loads in case the client method runs a new event loop that would
278    // otherwise cause the load to continue while we're in the middle of executing JavaScript.
279    PageGroupLoadDeferrer deferrer(m_page, true);
280
281    ASSERT(frame);
282    notifyPopupOpeningObservers();
283    String displayPrompt = frame->displayStringModifiedByEncoding(prompt);
284
285    InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRunJavaScriptDialog(m_page, displayPrompt);
286    bool ok = m_client->runJavaScriptPrompt(frame, displayPrompt, frame->displayStringModifiedByEncoding(defaultValue), result);
287    InspectorInstrumentation::didRunJavaScriptDialog(cookie);
288
289    if (ok)
290        result = frame->displayStringModifiedByEncoding(result);
291
292    return ok;
293}
294
295void Chrome::setStatusbarText(Frame* frame, const String& status)
296{
297    ASSERT(frame);
298    m_client->setStatusbarText(frame->displayStringModifiedByEncoding(status));
299}
300
301IntRect Chrome::windowResizerRect() const
302{
303    return m_client->windowResizerRect();
304}
305
306void Chrome::mouseDidMoveOverElement(const HitTestResult& result, unsigned modifierFlags)
307{
308    if (result.innerNode()) {
309        Document* document = result.innerNode()->document();
310        if (document && document->isDNSPrefetchEnabled())
311            prefetchDNS(result.absoluteLinkURL().host());
312    }
313    m_client->mouseDidMoveOverElement(result, modifierFlags);
314}
315
316void Chrome::setToolTip(const HitTestResult& result)
317{
318    // First priority is a potential toolTip representing a spelling or grammar error
319    TextDirection toolTipDirection;
320    String toolTip = result.spellingToolTip(toolTipDirection);
321
322    // Next we'll consider a tooltip for element with "title" attribute
323    if (toolTip.isEmpty())
324        toolTip = result.title(toolTipDirection);
325
326    // Lastly, for <input type="file"> that allow multiple files, we'll consider a tooltip for the selected filenames
327    if (toolTip.isEmpty()) {
328        if (Node* node = result.innerNonSharedNode()) {
329            if (node->hasTagName(inputTag)) {
330                HTMLInputElement* input = toHTMLInputElement(node);
331                toolTip = input->defaultToolTip();
332
333                // FIXME: We should obtain text direction of tooltip from
334                // ChromeClient or platform. As of October 2011, all client
335                // implementations don't use text direction information for
336                // ChromeClient::setToolTip. We'll work on tooltip text
337                // direction during bidi cleanup in form inputs.
338                toolTipDirection = LTR;
339            }
340        }
341    }
342
343    m_client->setToolTip(toolTip, toolTipDirection);
344}
345
346void Chrome::print(Frame* frame)
347{
348    // FIXME: This should have PageGroupLoadDeferrer, like runModal() or runJavaScriptAlert(), becasue it's no different from those.
349    m_client->print(frame);
350}
351
352void Chrome::enumerateChosenDirectory(FileChooser* fileChooser)
353{
354    m_client->enumerateChosenDirectory(fileChooser);
355}
356
357PassOwnPtr<ColorChooser> Chrome::createColorChooser(ColorChooserClient* client, const Color& initialColor)
358{
359    notifyPopupOpeningObservers();
360    return m_client->createColorChooser(client, initialColor);
361}
362
363PassRefPtr<DateTimeChooser> Chrome::openDateTimeChooser(DateTimeChooserClient* client, const DateTimeChooserParameters& parameters)
364{
365    notifyPopupOpeningObservers();
366    return m_client->openDateTimeChooser(client, parameters);
367}
368
369void Chrome::runOpenPanel(Frame* frame, PassRefPtr<FileChooser> fileChooser)
370{
371    notifyPopupOpeningObservers();
372    m_client->runOpenPanel(frame, fileChooser);
373}
374
375void Chrome::dispatchViewportPropertiesDidChange(const ViewportArguments& arguments) const
376{
377    m_client->dispatchViewportPropertiesDidChange(arguments);
378}
379
380void Chrome::setCursor(const Cursor& cursor)
381{
382    m_client->setCursor(cursor);
383}
384
385void Chrome::scheduleAnimation()
386{
387    m_client->scheduleAnimation();
388}
389
390// --------
391
392bool Chrome::hasOpenedPopup() const
393{
394    return m_client->hasOpenedPopup();
395}
396
397PassRefPtr<PopupMenu> Chrome::createPopupMenu(Frame& frame, PopupMenuClient* client) const
398{
399    notifyPopupOpeningObservers();
400    return m_client->createPopupMenu(frame, client);
401}
402
403void Chrome::registerPopupOpeningObserver(PopupOpeningObserver* observer)
404{
405    ASSERT(observer);
406    m_popupOpeningObservers.append(observer);
407}
408
409void Chrome::unregisterPopupOpeningObserver(PopupOpeningObserver* observer)
410{
411    size_t index = m_popupOpeningObservers.find(observer);
412    ASSERT(index != notFound);
413    m_popupOpeningObservers.remove(index);
414}
415
416void Chrome::notifyPopupOpeningObservers() const
417{
418    const Vector<PopupOpeningObserver*> observers(m_popupOpeningObservers);
419    for (size_t i = 0; i < observers.size(); ++i)
420        observers[i]->willOpenPopup();
421}
422
423} // namespace WebCore
424