2 * Copyright (C) 2006, 2007, 2008, 2010 Apple Inc. All rights reserved.
3 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
15 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
18 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 #include "DOMWindow.h"
30 #include "AbstractDatabase.h"
31 #include "BackForwardController.h"
34 #include "BeforeUnloadEvent.h"
35 #include "CSSComputedStyleDeclaration.h"
36 #include "CSSRuleList.h"
37 #include "CSSStyleSelector.h"
40 #include "DOMApplicationCache.h"
41 #include "DOMSelection.h"
42 #include "DOMSettableTokenList.h"
43 #include "DOMStringList.h"
45 #include "DOMTokenList.h"
48 #include "DatabaseCallback.h"
49 #include "DeviceMotionController.h"
50 #include "DeviceOrientationController.h"
52 #include "DocumentLoader.h"
54 #include "EventException.h"
55 #include "EventListener.h"
56 #include "EventNames.h"
57 #include "ExceptionCode.h"
58 #include "FloatRect.h"
60 #include "FrameLoadRequest.h"
61 #include "FrameLoader.h"
62 #include "FrameTree.h"
63 #include "FrameView.h"
64 #include "HTMLFrameOwnerElement.h"
66 #include "IDBFactory.h"
67 #include "IDBFactoryBackendInterface.h"
68 #include "InspectorInstrumentation.h"
71 #include "MediaQueryList.h"
72 #include "MediaQueryMatcher.h"
73 #include "MessageEvent.h"
74 #include "Navigator.h"
75 #include "NotificationCenter.h"
77 #include "PageGroup.h"
78 #include "PageTransitionEvent.h"
79 #include "Performance.h"
80 #include "PlatformScreen.h"
81 #include "PlatformString.h"
83 #include "SecurityOrigin.h"
84 #include "SerializedScriptValue.h"
87 #include "StorageArea.h"
88 #include "StorageNamespace.h"
89 #include "StyleMedia.h"
90 #include "SuddenTermination.h"
91 #include "WebKitPoint.h"
92 #include "WindowFeatures.h"
94 #include <wtf/CurrentTime.h>
95 #include <wtf/MathExtras.h>
96 #include <wtf/text/StringConcatenate.h>
98 #if ENABLE(FILE_SYSTEM)
99 #include "AsyncFileSystem.h"
100 #include "DOMFileSystem.h"
101 #include "ErrorCallback.h"
102 #include "FileError.h"
103 #include "FileSystemCallback.h"
104 #include "FileSystemCallbacks.h"
105 #include "LocalFileSystem.h"
108 #if ENABLE(REQUEST_ANIMATION_FRAME)
109 #include "RequestAnimationFrameCallback.h"
117 class PostMessageTimer : public TimerBase {
119 PostMessageTimer(DOMWindow* window, PassRefPtr<SerializedScriptValue> message, const String& sourceOrigin, PassRefPtr<DOMWindow> source, PassOwnPtr<MessagePortChannelArray> channels, SecurityOrigin* targetOrigin)
122 , m_origin(sourceOrigin)
124 , m_channels(channels)
125 , m_targetOrigin(targetOrigin)
129 PassRefPtr<MessageEvent> event(ScriptExecutionContext* context)
131 OwnPtr<MessagePortArray> messagePorts = MessagePort::entanglePorts(*context, m_channels.release());
132 return MessageEvent::create(messagePorts.release(), m_message, m_origin, "", m_source);
134 SecurityOrigin* targetOrigin() const { return m_targetOrigin.get(); }
139 m_window->postMessageTimerFired(this);
142 RefPtr<DOMWindow> m_window;
143 RefPtr<SerializedScriptValue> m_message;
145 RefPtr<DOMWindow> m_source;
146 OwnPtr<MessagePortChannelArray> m_channels;
147 RefPtr<SecurityOrigin> m_targetOrigin;
150 typedef HashCountedSet<DOMWindow*> DOMWindowSet;
152 static DOMWindowSet& windowsWithUnloadEventListeners()
154 DEFINE_STATIC_LOCAL(DOMWindowSet, windowsWithUnloadEventListeners, ());
155 return windowsWithUnloadEventListeners;
158 static DOMWindowSet& windowsWithBeforeUnloadEventListeners()
160 DEFINE_STATIC_LOCAL(DOMWindowSet, windowsWithBeforeUnloadEventListeners, ());
161 return windowsWithBeforeUnloadEventListeners;
164 static void addUnloadEventListener(DOMWindow* domWindow)
166 DOMWindowSet& set = windowsWithUnloadEventListeners();
168 disableSuddenTermination();
172 static void removeUnloadEventListener(DOMWindow* domWindow)
174 DOMWindowSet& set = windowsWithUnloadEventListeners();
175 DOMWindowSet::iterator it = set.find(domWindow);
180 enableSuddenTermination();
183 static void removeAllUnloadEventListeners(DOMWindow* domWindow)
185 DOMWindowSet& set = windowsWithUnloadEventListeners();
186 DOMWindowSet::iterator it = set.find(domWindow);
191 enableSuddenTermination();
194 static void addBeforeUnloadEventListener(DOMWindow* domWindow)
196 DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
198 disableSuddenTermination();
202 static void removeBeforeUnloadEventListener(DOMWindow* domWindow)
204 DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
205 DOMWindowSet::iterator it = set.find(domWindow);
210 enableSuddenTermination();
213 static void removeAllBeforeUnloadEventListeners(DOMWindow* domWindow)
215 DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
216 DOMWindowSet::iterator it = set.find(domWindow);
221 enableSuddenTermination();
224 static bool allowsBeforeUnloadListeners(DOMWindow* window)
226 ASSERT_ARG(window, window);
227 Frame* frame = window->frame();
230 Page* page = frame->page();
233 return frame == page->mainFrame();
236 bool DOMWindow::dispatchAllPendingBeforeUnloadEvents()
238 DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
242 static bool alreadyDispatched = false;
243 ASSERT(!alreadyDispatched);
244 if (alreadyDispatched)
247 Vector<RefPtr<DOMWindow> > windows;
248 DOMWindowSet::iterator end = set.end();
249 for (DOMWindowSet::iterator it = set.begin(); it != end; ++it)
250 windows.append(it->first);
252 size_t size = windows.size();
253 for (size_t i = 0; i < size; ++i) {
254 DOMWindow* window = windows[i].get();
255 if (!set.contains(window))
258 Frame* frame = window->frame();
262 if (!frame->loader()->shouldClose())
266 enableSuddenTermination();
268 alreadyDispatched = true;
273 unsigned DOMWindow::pendingUnloadEventListeners() const
275 return windowsWithUnloadEventListeners().count(const_cast<DOMWindow*>(this));
278 void DOMWindow::dispatchAllPendingUnloadEvents()
280 DOMWindowSet& set = windowsWithUnloadEventListeners();
284 static bool alreadyDispatched = false;
285 ASSERT(!alreadyDispatched);
286 if (alreadyDispatched)
289 Vector<RefPtr<DOMWindow> > windows;
290 DOMWindowSet::iterator end = set.end();
291 for (DOMWindowSet::iterator it = set.begin(); it != end; ++it)
292 windows.append(it->first);
294 size_t size = windows.size();
295 for (size_t i = 0; i < size; ++i) {
296 DOMWindow* window = windows[i].get();
297 if (!set.contains(window))
300 window->dispatchEvent(PageTransitionEvent::create(eventNames().pagehideEvent, false), window->document());
301 window->dispatchEvent(Event::create(eventNames().unloadEvent, false, false), window->document());
304 enableSuddenTermination();
306 alreadyDispatched = true;
310 // 1) Validates the pending changes are not changing to NaN
311 // 2) Constrains the window rect to no smaller than 100 in each dimension and no
312 // bigger than the the float rect's dimensions.
313 // 3) Constrain window rect to within the top and left boundaries of the screen rect
314 // 4) Constraint the window rect to within the bottom and right boundaries of the
316 // 5) Translate the window rect coordinates to be within the coordinate space of
318 void DOMWindow::adjustWindowRect(const FloatRect& screen, FloatRect& window, const FloatRect& pendingChanges)
320 // Make sure we're in a valid state before adjusting dimensions.
321 ASSERT(isfinite(screen.x()));
322 ASSERT(isfinite(screen.y()));
323 ASSERT(isfinite(screen.width()));
324 ASSERT(isfinite(screen.height()));
325 ASSERT(isfinite(window.x()));
326 ASSERT(isfinite(window.y()));
327 ASSERT(isfinite(window.width()));
328 ASSERT(isfinite(window.height()));
330 // Update window values if new requested values are not NaN.
331 if (!isnan(pendingChanges.x()))
332 window.setX(pendingChanges.x());
333 if (!isnan(pendingChanges.y()))
334 window.setY(pendingChanges.y());
335 if (!isnan(pendingChanges.width()))
336 window.setWidth(pendingChanges.width());
337 if (!isnan(pendingChanges.height()))
338 window.setHeight(pendingChanges.height());
340 // Resize the window to between 100 and the screen width and height.
341 window.setWidth(min(max(100.0f, window.width()), screen.width()));
342 window.setHeight(min(max(100.0f, window.height()), screen.height()));
344 // Constrain the window position to the screen.
345 window.setX(max(screen.x(), min(window.x(), screen.right() - window.width())));
346 window.setY(max(screen.y(), min(window.y(), screen.bottom() - window.height())));
349 // FIXME: We can remove this function once V8 showModalDialog is changed to use DOMWindow.
350 void DOMWindow::parseModalDialogFeatures(const String& string, HashMap<String, String>& map)
352 WindowFeatures::parseDialogFeatures(string, map);
355 bool DOMWindow::allowPopUp(Frame* firstFrame)
359 if (ScriptController::processingUserGesture())
362 Settings* settings = firstFrame->settings();
363 return settings && settings->javaScriptCanOpenWindowsAutomatically();
366 bool DOMWindow::allowPopUp()
368 return m_frame && allowPopUp(m_frame);
371 bool DOMWindow::canShowModalDialog(const Frame* frame)
375 Page* page = frame->page();
378 return page->chrome()->canRunModal();
381 bool DOMWindow::canShowModalDialogNow(const Frame* frame)
385 Page* page = frame->page();
388 return page->chrome()->canRunModalNow();
391 DOMWindow::DOMWindow(Frame* frame)
392 : m_shouldPrintWhenFinishedLoading(false)
397 DOMWindow::~DOMWindow()
400 m_frame->clearFormerDOMWindow(this);
402 removeAllUnloadEventListeners(this);
403 removeAllBeforeUnloadEventListeners(this);
406 ScriptExecutionContext* DOMWindow::scriptExecutionContext() const
411 PassRefPtr<MediaQueryList> DOMWindow::matchMedia(const String& media)
413 return document() ? document()->mediaQueryMatcher()->matchMedia(media) : 0;
416 void DOMWindow::disconnectFrame()
422 void DOMWindow::clear()
425 m_screen->disconnectFrame();
429 m_selection->disconnectFrame();
433 m_history->disconnectFrame();
437 m_locationbar->disconnectFrame();
441 m_menubar->disconnectFrame();
445 m_personalbar->disconnectFrame();
449 m_scrollbars->disconnectFrame();
453 m_statusbar->disconnectFrame();
457 m_toolbar->disconnectFrame();
461 m_console->disconnectFrame();
465 m_navigator->disconnectFrame();
468 #if ENABLE(WEB_TIMING)
470 m_performance->disconnectFrame();
475 m_location->disconnectFrame();
479 m_media->disconnectFrame();
482 #if ENABLE(DOM_STORAGE)
483 if (m_sessionStorage)
484 m_sessionStorage->disconnectFrame();
485 m_sessionStorage = 0;
488 m_localStorage->disconnectFrame();
492 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
493 if (m_applicationCache)
494 m_applicationCache->disconnectFrame();
495 m_applicationCache = 0;
498 #if ENABLE(NOTIFICATIONS)
500 m_notifications->disconnectFrame();
504 #if ENABLE(INDEXED_DATABASE)
509 #if ENABLE(ORIENTATION_EVENTS)
510 int DOMWindow::orientation() const
515 return m_frame->orientation();
519 Screen* DOMWindow::screen() const
522 m_screen = Screen::create(m_frame);
523 return m_screen.get();
526 History* DOMWindow::history() const
529 m_history = History::create(m_frame);
530 return m_history.get();
533 BarInfo* DOMWindow::locationbar() const
536 m_locationbar = BarInfo::create(m_frame, BarInfo::Locationbar);
537 return m_locationbar.get();
540 BarInfo* DOMWindow::menubar() const
543 m_menubar = BarInfo::create(m_frame, BarInfo::Menubar);
544 return m_menubar.get();
547 BarInfo* DOMWindow::personalbar() const
550 m_personalbar = BarInfo::create(m_frame, BarInfo::Personalbar);
551 return m_personalbar.get();
554 BarInfo* DOMWindow::scrollbars() const
557 m_scrollbars = BarInfo::create(m_frame, BarInfo::Scrollbars);
558 return m_scrollbars.get();
561 BarInfo* DOMWindow::statusbar() const
564 m_statusbar = BarInfo::create(m_frame, BarInfo::Statusbar);
565 return m_statusbar.get();
568 BarInfo* DOMWindow::toolbar() const
571 m_toolbar = BarInfo::create(m_frame, BarInfo::Toolbar);
572 return m_toolbar.get();
575 Console* DOMWindow::console() const
578 m_console = Console::create(m_frame);
579 return m_console.get();
582 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
583 DOMApplicationCache* DOMWindow::applicationCache() const
585 if (!m_applicationCache)
586 m_applicationCache = DOMApplicationCache::create(m_frame);
587 return m_applicationCache.get();
591 Navigator* DOMWindow::navigator() const
594 m_navigator = Navigator::create(m_frame);
595 return m_navigator.get();
598 #if ENABLE(WEB_TIMING)
599 Performance* DOMWindow::performance() const
602 m_performance = Performance::create(m_frame);
603 return m_performance.get();
607 Location* DOMWindow::location() const
610 m_location = Location::create(m_frame);
611 return m_location.get();
614 #if ENABLE(DOM_STORAGE)
615 Storage* DOMWindow::sessionStorage(ExceptionCode& ec) const
617 if (m_sessionStorage)
618 return m_sessionStorage.get();
620 Document* document = this->document();
624 if (!document->securityOrigin()->canAccessLocalStorage()) {
629 Page* page = document->page();
633 RefPtr<StorageArea> storageArea = page->sessionStorage()->storageArea(document->securityOrigin());
634 InspectorInstrumentation::didUseDOMStorage(page, storageArea.get(), false, m_frame);
636 m_sessionStorage = Storage::create(m_frame, storageArea.release());
637 return m_sessionStorage.get();
640 Storage* DOMWindow::localStorage(ExceptionCode& ec) const
643 return m_localStorage.get();
645 Document* document = this->document();
649 if (!document->securityOrigin()->canAccessLocalStorage()) {
654 Page* page = document->page();
658 if (!page->settings()->localStorageEnabled())
661 RefPtr<StorageArea> storageArea = page->group().localStorage()->storageArea(document->securityOrigin());
662 InspectorInstrumentation::didUseDOMStorage(page, storageArea.get(), true, m_frame);
664 m_localStorage = Storage::create(m_frame, storageArea.release());
665 return m_localStorage.get();
669 #if ENABLE(NOTIFICATIONS)
670 NotificationCenter* DOMWindow::webkitNotifications() const
673 return m_notifications.get();
675 Document* document = this->document();
679 Page* page = document->page();
683 NotificationPresenter* provider = page->chrome()->notificationPresenter();
685 m_notifications = NotificationCenter::create(document, provider);
687 return m_notifications.get();
691 void DOMWindow::pageDestroyed()
693 #if ENABLE(NOTIFICATIONS)
694 // Clearing Notifications requests involves accessing the client so it must be done
695 // before the frame is detached.
697 m_notifications->disconnectFrame();
702 #if ENABLE(INDEXED_DATABASE)
703 IDBFactory* DOMWindow::webkitIndexedDB() const
706 return m_idbFactory.get();
708 Document* document = this->document();
712 // FIXME: See if access is allowed.
714 Page* page = document->page();
718 // FIXME: See if indexedDatabase access is allowed.
720 m_idbFactory = IDBFactory::create(page->group().idbFactory());
721 return m_idbFactory.get();
725 #if ENABLE(FILE_SYSTEM)
726 void DOMWindow::requestFileSystem(int type, long long size, PassRefPtr<FileSystemCallback> successCallback, PassRefPtr<ErrorCallback> errorCallback)
728 Document* document = this->document();
732 if (!AsyncFileSystem::isAvailable() || !document->securityOrigin()->canAccessFileSystem()) {
733 DOMFileSystem::scheduleCallback(document, errorCallback, FileError::create(FileError::SECURITY_ERR));
737 AsyncFileSystem::Type fileSystemType = static_cast<AsyncFileSystem::Type>(type);
738 if (fileSystemType != AsyncFileSystem::Temporary && fileSystemType != AsyncFileSystem::Persistent) {
739 DOMFileSystem::scheduleCallback(document, errorCallback, FileError::create(FileError::INVALID_MODIFICATION_ERR));
743 LocalFileSystem::localFileSystem().requestFileSystem(document, fileSystemType, size, FileSystemCallbacks::create(successCallback, errorCallback, document), false);
746 COMPILE_ASSERT(static_cast<int>(DOMWindow::TEMPORARY) == static_cast<int>(AsyncFileSystem::Temporary), enum_mismatch);
747 COMPILE_ASSERT(static_cast<int>(DOMWindow::PERSISTENT) == static_cast<int>(AsyncFileSystem::Persistent), enum_mismatch);
751 void DOMWindow::postMessage(PassRefPtr<SerializedScriptValue> message, MessagePort* port, const String& targetOrigin, DOMWindow* source, ExceptionCode& ec)
753 MessagePortArray ports;
756 postMessage(message, &ports, targetOrigin, source, ec);
759 void DOMWindow::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, const String& targetOrigin, DOMWindow* source, ExceptionCode& ec)
764 // Compute the target origin. We need to do this synchronously in order
765 // to generate the SYNTAX_ERR exception correctly.
766 RefPtr<SecurityOrigin> target;
767 if (targetOrigin != "*") {
768 target = SecurityOrigin::createFromString(targetOrigin);
769 if (target->isEmpty()) {
775 OwnPtr<MessagePortChannelArray> channels = MessagePort::disentanglePorts(ports, ec);
779 // Capture the source of the message. We need to do this synchronously
780 // in order to capture the source of the message correctly.
781 Document* sourceDocument = source->document();
784 String sourceOrigin = sourceDocument->securityOrigin()->toString();
786 // Schedule the message.
787 PostMessageTimer* timer = new PostMessageTimer(this, message, sourceOrigin, source, channels.release(), target.get());
788 timer->startOneShot(0);
791 void DOMWindow::postMessageTimerFired(PostMessageTimer* t)
793 OwnPtr<PostMessageTimer> timer(t);
798 if (timer->targetOrigin()) {
799 // Check target origin now since the target document may have changed since the simer was scheduled.
800 if (!timer->targetOrigin()->isSameSchemeHostPort(document()->securityOrigin())) {
801 String message = makeString("Unable to post message to ", timer->targetOrigin()->toString(),
802 ". Recipient has origin ", document()->securityOrigin()->toString(), ".\n");
803 console()->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, message, 0, String());
808 dispatchEvent(timer->event(document()));
811 DOMSelection* DOMWindow::getSelection()
814 m_selection = DOMSelection::create(m_frame);
815 return m_selection.get();
818 Element* DOMWindow::frameElement() const
823 return m_frame->ownerElement();
826 void DOMWindow::focus()
831 Page* page = m_frame->page();
835 // If we're a top level window, bring the window to the front.
836 if (m_frame == page->mainFrame())
837 page->chrome()->focus();
842 m_frame->eventHandler()->focusDocumentView();
845 void DOMWindow::blur()
850 Page* page = m_frame->page();
854 if (m_frame != page->mainFrame())
857 page->chrome()->unfocus();
860 void DOMWindow::close(ScriptExecutionContext* context)
865 Page* page = m_frame->page();
869 if (m_frame != page->mainFrame())
873 ASSERT(WTF::isMainThread());
874 Frame* activeFrame = static_cast<Document*>(context)->frame();
878 if (!activeFrame->loader()->shouldAllowNavigation(m_frame))
882 Settings* settings = m_frame->settings();
883 bool allowScriptsToCloseWindows = settings && settings->allowScriptsToCloseWindows();
885 if (!(page->openedByDOM() || page->backForward()->count() <= 1 || allowScriptsToCloseWindows))
888 if (!m_frame->loader()->shouldClose())
891 page->chrome()->closeWindowSoon();
894 void DOMWindow::print()
899 Page* page = m_frame->page();
903 if (m_frame->loader()->activeDocumentLoader()->isLoading()) {
904 m_shouldPrintWhenFinishedLoading = true;
907 m_shouldPrintWhenFinishedLoading = false;
908 page->chrome()->print(m_frame);
911 void DOMWindow::stop()
916 // We must check whether the load is complete asynchronously, because we might still be parsing
917 // the document until the callstack unwinds.
918 m_frame->loader()->stopForUserCancel(true);
921 void DOMWindow::alert(const String& message)
926 m_frame->document()->updateStyleIfNeeded();
928 Page* page = m_frame->page();
932 page->chrome()->runJavaScriptAlert(m_frame, message);
935 bool DOMWindow::confirm(const String& message)
940 m_frame->document()->updateStyleIfNeeded();
942 Page* page = m_frame->page();
946 return page->chrome()->runJavaScriptConfirm(m_frame, message);
949 String DOMWindow::prompt(const String& message, const String& defaultValue)
954 m_frame->document()->updateStyleIfNeeded();
956 Page* page = m_frame->page();
961 if (page->chrome()->runJavaScriptPrompt(m_frame, message, defaultValue, returnValue))
967 static bool isSafeToConvertCharList(const String& string)
969 for (unsigned i = 0; i < string.length(); i++) {
970 if (string[i] > 0xFF)
977 String DOMWindow::btoa(const String& stringToEncode, ExceptionCode& ec)
979 if (stringToEncode.isNull())
982 if (!isSafeToConvertCharList(stringToEncode)) {
983 ec = INVALID_CHARACTER_ERR;
988 in.append(stringToEncode.characters(), stringToEncode.length());
991 base64Encode(in, out);
993 return String(out.data(), out.size());
996 String DOMWindow::atob(const String& encodedString, ExceptionCode& ec)
998 if (encodedString.isNull())
1001 if (!isSafeToConvertCharList(encodedString)) {
1002 ec = INVALID_CHARACTER_ERR;
1007 if (!base64Decode(encodedString, out, FailOnInvalidCharacter)) {
1008 ec = INVALID_CHARACTER_ERR;
1012 return String(out.data(), out.size());
1015 bool DOMWindow::find(const String& string, bool caseSensitive, bool backwards, bool wrap, bool /*wholeWord*/, bool /*searchInFrames*/, bool /*showDialog*/) const
1020 // FIXME (13016): Support wholeWord, searchInFrames and showDialog
1021 return m_frame->editor()->findString(string, !backwards, caseSensitive, wrap, false);
1024 bool DOMWindow::offscreenBuffering() const
1029 int DOMWindow::outerHeight() const
1034 Page* page = m_frame->page();
1038 return static_cast<int>(page->chrome()->windowRect().height());
1041 int DOMWindow::outerWidth() const
1046 Page* page = m_frame->page();
1050 return static_cast<int>(page->chrome()->windowRect().width());
1053 int DOMWindow::innerHeight() const
1058 FrameView* view = m_frame->view();
1062 #if PLATFORM(ANDROID)
1063 return static_cast<int>(view->actualHeight() / m_frame->pageZoomFactor());
1065 return static_cast<int>(view->height() / m_frame->pageZoomFactor());
1069 int DOMWindow::innerWidth() const
1074 FrameView* view = m_frame->view();
1078 #if PLATFORM(ANDROID)
1079 return static_cast<int>(view->actualWidth() / m_frame->pageZoomFactor());
1081 return static_cast<int>(view->width() / m_frame->pageZoomFactor());
1085 int DOMWindow::screenX() const
1090 Page* page = m_frame->page();
1094 return static_cast<int>(page->chrome()->windowRect().x());
1097 int DOMWindow::screenY() const
1102 Page* page = m_frame->page();
1106 return static_cast<int>(page->chrome()->windowRect().y());
1109 int DOMWindow::scrollX() const
1114 FrameView* view = m_frame->view();
1118 m_frame->document()->updateLayoutIgnorePendingStylesheets();
1120 #if PLATFORM(ANDROID)
1121 return static_cast<int>(view->actualScrollX() / m_frame->pageZoomFactor());
1123 return static_cast<int>(view->scrollX() / m_frame->pageZoomFactor());
1127 int DOMWindow::scrollY() const
1132 FrameView* view = m_frame->view();
1136 m_frame->document()->updateLayoutIgnorePendingStylesheets();
1138 #if PLATFORM(ANDROID)
1139 return static_cast<int>(view->actualScrollY() / m_frame->pageZoomFactor());
1141 return static_cast<int>(view->scrollY() / m_frame->pageZoomFactor());
1145 bool DOMWindow::closed() const
1150 unsigned DOMWindow::length() const
1155 return m_frame->tree()->childCount();
1158 String DOMWindow::name() const
1163 return m_frame->tree()->name();
1166 void DOMWindow::setName(const String& string)
1171 m_frame->tree()->setName(string);
1174 void DOMWindow::setStatus(const String& string)
1181 Page* page = m_frame->page();
1185 ASSERT(m_frame->document()); // Client calls shouldn't be made when the frame is in inconsistent state.
1186 page->chrome()->setStatusbarText(m_frame, m_status);
1189 void DOMWindow::setDefaultStatus(const String& string)
1191 m_defaultStatus = string;
1196 Page* page = m_frame->page();
1200 ASSERT(m_frame->document()); // Client calls shouldn't be made when the frame is in inconsistent state.
1201 page->chrome()->setStatusbarText(m_frame, m_defaultStatus);
1204 DOMWindow* DOMWindow::self() const
1209 return m_frame->domWindow();
1212 DOMWindow* DOMWindow::opener() const
1217 Frame* opener = m_frame->loader()->opener();
1221 return opener->domWindow();
1224 DOMWindow* DOMWindow::parent() const
1229 Frame* parent = m_frame->tree()->parent(true);
1231 return parent->domWindow();
1233 return m_frame->domWindow();
1236 DOMWindow* DOMWindow::top() const
1241 Page* page = m_frame->page();
1245 return m_frame->tree()->top(true)->domWindow();
1248 Document* DOMWindow::document() const
1250 // FIXME: This function shouldn't need a frame to work.
1254 // The m_frame pointer is not zeroed out when the window is put into b/f cache, so it can hold an unrelated document/window pair.
1255 // FIXME: We should always zero out the frame pointer on navigation to avoid accidentally accessing the new frame content.
1256 if (m_frame->domWindow() != this)
1259 ASSERT(m_frame->document());
1260 return m_frame->document();
1263 PassRefPtr<StyleMedia> DOMWindow::styleMedia() const
1266 m_media = StyleMedia::create(m_frame);
1267 return m_media.get();
1270 PassRefPtr<CSSStyleDeclaration> DOMWindow::getComputedStyle(Element* elt, const String& pseudoElt) const
1275 return computedStyle(elt, false, pseudoElt);
1278 PassRefPtr<CSSRuleList> DOMWindow::getMatchedCSSRules(Element* elt, const String&, bool authorOnly) const
1283 Settings* settings = m_frame->settings();
1284 return m_frame->document()->styleSelector()->styleRulesForElement(elt, authorOnly, false, settings && settings->crossOriginCheckInGetMatchedCSSRulesDisabled() ? AllCSSRules : SameOriginCSSRulesOnly);
1287 PassRefPtr<WebKitPoint> DOMWindow::webkitConvertPointFromNodeToPage(Node* node, const WebKitPoint* p) const
1292 m_frame->document()->updateLayoutIgnorePendingStylesheets();
1294 FloatPoint pagePoint(p->x(), p->y());
1295 pagePoint = node->convertToPage(pagePoint);
1296 return WebKitPoint::create(pagePoint.x(), pagePoint.y());
1299 PassRefPtr<WebKitPoint> DOMWindow::webkitConvertPointFromPageToNode(Node* node, const WebKitPoint* p) const
1304 m_frame->document()->updateLayoutIgnorePendingStylesheets();
1306 FloatPoint nodePoint(p->x(), p->y());
1307 nodePoint = node->convertFromPage(nodePoint);
1308 return WebKitPoint::create(nodePoint.x(), nodePoint.y());
1311 double DOMWindow::devicePixelRatio() const
1316 Page* page = m_frame->page();
1320 return page->chrome()->scaleFactor();
1323 #if ENABLE(DATABASE)
1324 PassRefPtr<Database> DOMWindow::openDatabase(const String& name, const String& version, const String& displayName, unsigned long estimatedSize, PassRefPtr<DatabaseCallback> creationCallback, ExceptionCode& ec)
1326 RefPtr<Database> database = 0;
1327 if (m_frame && AbstractDatabase::isAvailable() && m_frame->document()->securityOrigin()->canAccessDatabase())
1328 database = Database::openDatabase(m_frame->document(), name, version, displayName, estimatedSize, creationCallback, ec);
1330 if (!database && !ec)
1337 void DOMWindow::scrollBy(int x, int y) const
1342 m_frame->document()->updateLayoutIgnorePendingStylesheets();
1344 RefPtr<FrameView> view = m_frame->view();
1348 view->scrollBy(IntSize(x, y));
1351 void DOMWindow::scrollTo(int x, int y) const
1356 m_frame->document()->updateLayoutIgnorePendingStylesheets();
1358 RefPtr<FrameView> view = m_frame->view();
1362 int zoomedX = static_cast<int>(x * m_frame->pageZoomFactor());
1363 int zoomedY = static_cast<int>(y * m_frame->pageZoomFactor());
1364 view->setScrollPosition(IntPoint(zoomedX, zoomedY));
1367 void DOMWindow::moveBy(float x, float y) const
1372 Page* page = m_frame->page();
1376 if (m_frame != page->mainFrame())
1379 FloatRect fr = page->chrome()->windowRect();
1380 FloatRect update = fr;
1382 // Security check (the spec talks about UniversalBrowserWrite to disable this check...)
1383 adjustWindowRect(screenAvailableRect(page->mainFrame()->view()), fr, update);
1384 page->chrome()->setWindowRect(fr);
1387 void DOMWindow::moveTo(float x, float y) const
1392 Page* page = m_frame->page();
1396 if (m_frame != page->mainFrame())
1399 FloatRect fr = page->chrome()->windowRect();
1400 FloatRect sr = screenAvailableRect(page->mainFrame()->view());
1401 fr.setLocation(sr.location());
1402 FloatRect update = fr;
1404 // Security check (the spec talks about UniversalBrowserWrite to disable this check...)
1405 adjustWindowRect(sr, fr, update);
1406 page->chrome()->setWindowRect(fr);
1409 void DOMWindow::resizeBy(float x, float y) const
1414 Page* page = m_frame->page();
1418 if (m_frame != page->mainFrame())
1421 FloatRect fr = page->chrome()->windowRect();
1422 FloatSize dest = fr.size() + FloatSize(x, y);
1423 FloatRect update(fr.location(), dest);
1424 adjustWindowRect(screenAvailableRect(page->mainFrame()->view()), fr, update);
1425 page->chrome()->setWindowRect(fr);
1428 void DOMWindow::resizeTo(float width, float height) const
1433 Page* page = m_frame->page();
1437 if (m_frame != page->mainFrame())
1440 FloatRect fr = page->chrome()->windowRect();
1441 FloatSize dest = FloatSize(width, height);
1442 FloatRect update(fr.location(), dest);
1443 adjustWindowRect(screenAvailableRect(page->mainFrame()->view()), fr, update);
1444 page->chrome()->setWindowRect(fr);
1447 int DOMWindow::setTimeout(PassOwnPtr<ScheduledAction> action, int timeout, ExceptionCode& ec)
1449 ScriptExecutionContext* context = scriptExecutionContext();
1451 ec = INVALID_ACCESS_ERR;
1454 return DOMTimer::install(context, action, timeout, true);
1457 void DOMWindow::clearTimeout(int timeoutId)
1459 ScriptExecutionContext* context = scriptExecutionContext();
1462 DOMTimer::removeById(context, timeoutId);
1465 int DOMWindow::setInterval(PassOwnPtr<ScheduledAction> action, int timeout, ExceptionCode& ec)
1467 ScriptExecutionContext* context = scriptExecutionContext();
1469 ec = INVALID_ACCESS_ERR;
1472 return DOMTimer::install(context, action, timeout, false);
1475 void DOMWindow::clearInterval(int timeoutId)
1477 ScriptExecutionContext* context = scriptExecutionContext();
1480 DOMTimer::removeById(context, timeoutId);
1483 #if ENABLE(REQUEST_ANIMATION_FRAME)
1484 int DOMWindow::webkitRequestAnimationFrame(PassRefPtr<RequestAnimationFrameCallback> callback, Element* e)
1486 if (Document* d = document())
1487 return d->webkitRequestAnimationFrame(callback, e);
1491 void DOMWindow::webkitCancelRequestAnimationFrame(int id)
1493 if (Document* d = document())
1494 d->webkitCancelRequestAnimationFrame(id);
1498 bool DOMWindow::addEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
1500 if (!EventTarget::addEventListener(eventType, listener, useCapture))
1503 if (Document* document = this->document())
1504 document->addListenerTypeIfNeeded(eventType);
1506 if (eventType == eventNames().unloadEvent)
1507 addUnloadEventListener(this);
1508 else if (eventType == eventNames().beforeunloadEvent && allowsBeforeUnloadListeners(this))
1509 addBeforeUnloadEventListener(this);
1510 #if ENABLE(DEVICE_ORIENTATION)
1511 else if (eventType == eventNames().devicemotionEvent && frame() && frame()->page() && frame()->page()->deviceMotionController())
1512 frame()->page()->deviceMotionController()->addListener(this);
1513 else if (eventType == eventNames().deviceorientationEvent && frame() && frame()->page() && frame()->page()->deviceOrientationController())
1514 frame()->page()->deviceOrientationController()->addListener(this);
1520 bool DOMWindow::removeEventListener(const AtomicString& eventType, EventListener* listener, bool useCapture)
1522 if (!EventTarget::removeEventListener(eventType, listener, useCapture))
1525 if (eventType == eventNames().unloadEvent)
1526 removeUnloadEventListener(this);
1527 else if (eventType == eventNames().beforeunloadEvent && allowsBeforeUnloadListeners(this))
1528 removeBeforeUnloadEventListener(this);
1529 #if ENABLE(DEVICE_ORIENTATION)
1530 else if (eventType == eventNames().devicemotionEvent && frame() && frame()->page() && frame()->page()->deviceMotionController())
1531 frame()->page()->deviceMotionController()->removeListener(this);
1532 else if (eventType == eventNames().deviceorientationEvent && frame() && frame()->page() && frame()->page()->deviceOrientationController())
1533 frame()->page()->deviceOrientationController()->removeListener(this);
1539 void DOMWindow::dispatchLoadEvent()
1541 RefPtr<Event> loadEvent(Event::create(eventNames().loadEvent, false, false));
1542 // The DocumentLoader (and thus its DocumentLoadTiming) might get destroyed while dispatching
1543 // the event, so protect it to prevent writing the end time into freed memory.
1544 if (RefPtr<DocumentLoader> documentLoader = m_frame ? m_frame->loader()->documentLoader() : 0) {
1545 DocumentLoadTiming* timing = documentLoader->timing();
1546 dispatchTimedEvent(loadEvent, document(), &timing->loadEventStart, &timing->loadEventEnd);
1548 dispatchEvent(loadEvent, document());
1550 // For load events, send a separate load event to the enclosing frame only.
1551 // This is a DOM extension and is independent of bubbling/capturing rules of
1553 Element* ownerElement = document()->ownerElement();
1555 RefPtr<Event> ownerEvent = Event::create(eventNames().loadEvent, false, false);
1556 ownerEvent->setTarget(ownerElement);
1557 ownerElement->dispatchGenericEvent(ownerEvent.release());
1560 InspectorInstrumentation::mainResourceFiredLoadEvent(frame(), url());
1563 bool DOMWindow::dispatchEvent(PassRefPtr<Event> prpEvent, PassRefPtr<EventTarget> prpTarget)
1565 RefPtr<EventTarget> protect = this;
1566 RefPtr<Event> event = prpEvent;
1568 event->setTarget(prpTarget ? prpTarget : this);
1569 event->setCurrentTarget(this);
1570 event->setEventPhase(Event::AT_TARGET);
1572 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willDispatchEventOnWindow(frame(), *event, this);
1574 bool result = fireEventListeners(event.get());
1576 InspectorInstrumentation::didDispatchEventOnWindow(cookie);
1581 void DOMWindow::dispatchTimedEvent(PassRefPtr<Event> event, Document* target, double* startTime, double* endTime)
1585 *startTime = currentTime();
1586 dispatchEvent(event, target);
1587 *endTime = currentTime();
1588 ASSERT(*endTime >= *startTime);
1591 void DOMWindow::removeAllEventListeners()
1593 EventTarget::removeAllEventListeners();
1595 #if ENABLE(DEVICE_ORIENTATION)
1596 if (frame() && frame()->page() && frame()->page()->deviceMotionController())
1597 frame()->page()->deviceMotionController()->removeAllListeners(this);
1598 if (frame() && frame()->page() && frame()->page()->deviceOrientationController())
1599 frame()->page()->deviceOrientationController()->removeAllListeners(this);
1602 removeAllUnloadEventListeners(this);
1603 removeAllBeforeUnloadEventListeners(this);
1606 void DOMWindow::captureEvents()
1611 void DOMWindow::releaseEvents()
1616 void DOMWindow::finishedLoading()
1618 if (m_shouldPrintWhenFinishedLoading) {
1619 m_shouldPrintWhenFinishedLoading = false;
1624 EventTargetData* DOMWindow::eventTargetData()
1626 return &m_eventTargetData;
1629 EventTargetData* DOMWindow::ensureEventTargetData()
1631 return &m_eventTargetData;
1634 #if ENABLE(DOM_STORAGE) && defined(ANDROID)
1635 void DOMWindow::clearDOMStorage()
1637 if (m_sessionStorage)
1638 m_sessionStorage->disconnectFrame();
1639 m_sessionStorage = 0;
1642 m_localStorage->disconnectFrame();
1647 void DOMWindow::setLocation(const String& urlString, DOMWindow* activeWindow, DOMWindow* firstWindow, SetLocationLocking locking)
1652 Frame* activeFrame = activeWindow->frame();
1656 if (!activeFrame->loader()->shouldAllowNavigation(m_frame))
1659 Frame* firstFrame = firstWindow->frame();
1663 KURL completedURL = firstFrame->document()->completeURL(urlString);
1664 if (completedURL.isNull())
1667 if (isInsecureScriptAccess(activeWindow, urlString))
1670 // We want a new history item if we are processing a user gesture.
1671 m_frame->navigationScheduler()->scheduleLocationChange(activeFrame->document()->securityOrigin(),
1672 completedURL, activeFrame->loader()->outgoingReferrer(),
1673 locking != LockHistoryBasedOnGestureState || !activeFrame->script()->anyPageIsProcessingUserGesture(),
1674 locking != LockHistoryBasedOnGestureState);
1677 void DOMWindow::printErrorMessage(const String& message)
1679 if (message.isEmpty())
1682 Settings* settings = m_frame->settings();
1685 if (settings->privateBrowsingEnabled())
1688 // FIXME: Add arguments so that we can provide a correct source URL and line number.
1689 console()->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, message, 1, String());
1692 String DOMWindow::crossDomainAccessErrorMessage(DOMWindow* activeWindow)
1694 const KURL& activeWindowURL = activeWindow->url();
1695 if (activeWindowURL.isNull())
1698 // FIXME: This error message should contain more specifics of why the same origin check has failed.
1699 // Perhaps we should involve the security origin object in composing it.
1700 // FIXME: This message, and other console messages, have extra newlines. Should remove them.
1701 return makeString("Unsafe JavaScript attempt to access frame with URL ", m_url.string(),
1702 " from frame with URL ", activeWindowURL.string(), ". Domains, protocols and ports must match.\n");
1705 bool DOMWindow::isInsecureScriptAccess(DOMWindow* activeWindow, const String& urlString)
1707 if (!protocolIsJavaScript(urlString))
1710 // FIXME: Is there some way to eliminate the need for a separate "activeWindow == this" check?
1711 if (activeWindow == this)
1714 // FIXME: The name canAccess seems to be a roundabout way to ask "can execute script".
1715 // Can we name the SecurityOrigin function better to make this more clear?
1716 if (activeWindow->securityOrigin()->canAccess(securityOrigin()))
1719 printErrorMessage(crossDomainAccessErrorMessage(activeWindow));
1723 Frame* DOMWindow::createWindow(const String& urlString, const AtomicString& frameName, const WindowFeatures& windowFeatures,
1724 DOMWindow* activeWindow, Frame* firstFrame, Frame* openerFrame, PrepareDialogFunction function, void* functionContext)
1726 Frame* activeFrame = activeWindow->frame();
1728 // For whatever reason, Firefox uses the first frame to determine the outgoingReferrer. We replicate that behavior here.
1729 String referrer = firstFrame->loader()->outgoingReferrer();
1731 KURL completedURL = urlString.isEmpty() ? KURL(ParsedURLString, "") : firstFrame->document()->completeURL(urlString);
1732 ResourceRequest request(completedURL, referrer);
1733 FrameLoader::addHTTPOriginIfNeeded(request, firstFrame->loader()->outgoingOrigin());
1734 FrameLoadRequest frameRequest(activeWindow->securityOrigin(), request, frameName);
1736 // We pass the opener frame for the lookupFrame in case the active frame is different from
1737 // the opener frame, and the name references a frame relative to the opener frame.
1739 Frame* newFrame = WebCore::createWindow(activeFrame, openerFrame, frameRequest, windowFeatures, created);
1743 newFrame->loader()->setOpener(openerFrame);
1744 newFrame->page()->setOpenedByDOM();
1746 if (newFrame->domWindow()->isInsecureScriptAccess(activeWindow, urlString))
1750 function(newFrame->domWindow(), functionContext);
1753 newFrame->loader()->changeLocation(activeWindow->securityOrigin(), completedURL, referrer, false, false);
1754 else if (!urlString.isEmpty()) {
1755 newFrame->navigationScheduler()->scheduleLocationChange(activeWindow->securityOrigin(), completedURL.string(), referrer,
1756 !activeFrame->script()->anyPageIsProcessingUserGesture(), false);
1762 PassRefPtr<DOMWindow> DOMWindow::open(const String& urlString, const AtomicString& frameName, const String& windowFeaturesString,
1763 DOMWindow* activeWindow, DOMWindow* firstWindow)
1767 Frame* activeFrame = activeWindow->frame();
1770 Frame* firstFrame = firstWindow->frame();
1774 if (!firstWindow->allowPopUp()) {
1775 // Because FrameTree::find() returns true for empty strings, we must check for empty frame names.
1776 // Otherwise, illegitimate window.open() calls with no name will pass right through the popup blocker.
1777 if (frameName.isEmpty() || !m_frame->tree()->find(frameName))
1781 // Get the target frame for the special cases of _top and _parent.
1782 // In those cases, we schedule a location change right now and return early.
1783 Frame* targetFrame = 0;
1784 if (frameName == "_top")
1785 targetFrame = m_frame->tree()->top();
1786 else if (frameName == "_parent") {
1787 if (Frame* parent = m_frame->tree()->parent())
1788 targetFrame = parent;
1790 targetFrame = m_frame;
1793 if (!activeFrame->loader()->shouldAllowNavigation(targetFrame))
1796 if (isInsecureScriptAccess(activeWindow, urlString))
1797 return targetFrame->domWindow();
1799 if (urlString.isEmpty())
1800 return targetFrame->domWindow();
1802 // For whatever reason, Firefox uses the first window rather than the active window to
1803 // determine the outgoing referrer. We replicate that behavior here.
1804 targetFrame->navigationScheduler()->scheduleLocationChange(activeFrame->document()->securityOrigin(),
1805 firstFrame->document()->completeURL(urlString).string(),
1806 firstFrame->loader()->outgoingReferrer(),
1807 !activeFrame->script()->anyPageIsProcessingUserGesture(), false);
1809 return targetFrame->domWindow();
1812 WindowFeatures windowFeatures(windowFeaturesString);
1813 FloatRect windowRect(windowFeatures.xSet ? windowFeatures.x : 0, windowFeatures.ySet ? windowFeatures.y : 0,
1814 windowFeatures.widthSet ? windowFeatures.width : 0, windowFeatures.heightSet ? windowFeatures.height : 0);
1815 Page* page = m_frame->page();
1816 DOMWindow::adjustWindowRect(screenAvailableRect(page ? page->mainFrame()->view() : 0), windowRect, windowRect);
1817 windowFeatures.x = windowRect.x();
1818 windowFeatures.y = windowRect.y();
1819 windowFeatures.height = windowRect.height();
1820 windowFeatures.width = windowRect.width();
1822 Frame* result = createWindow(urlString, frameName, windowFeatures, activeWindow, firstFrame, m_frame);
1823 return result ? result->domWindow() : 0;
1826 void DOMWindow::showModalDialog(const String& urlString, const String& dialogFeaturesString,
1827 DOMWindow* activeWindow, DOMWindow* firstWindow, PrepareDialogFunction function, void* functionContext)
1831 Frame* activeFrame = activeWindow->frame();
1834 Frame* firstFrame = firstWindow->frame();
1838 if (!canShowModalDialogNow(m_frame) || !firstWindow->allowPopUp())
1841 Frame* dialogFrame = createWindow(urlString, emptyAtom, WindowFeatures(dialogFeaturesString, screenAvailableRect(m_frame->view())),
1842 activeWindow, firstFrame, m_frame, function, functionContext);
1846 dialogFrame->page()->chrome()->runModal();
1850 DOMURL* DOMWindow::webkitURL() const
1853 m_domURL = DOMURL::create(this->scriptExecutionContext());
1854 return m_domURL.get();
1858 } // namespace WebCore