OSDN Git Service

Merge "Serialize LayerAndroid"
[android-x86/external-webkit.git] / Source / WebCore / page / DOMWindow.cpp
1 /*
2  * Copyright (C) 2006, 2007, 2008, 2010 Apple Inc. All rights reserved.
3  * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
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.
13  *
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. 
25  */
26
27 #include "config.h"
28 #include "DOMWindow.h"
29
30 #include "AbstractDatabase.h"
31 #include "BackForwardController.h"
32 #include "BarInfo.h"
33 #include "Base64.h"
34 #include "BeforeUnloadEvent.h"
35 #include "CSSComputedStyleDeclaration.h"
36 #include "CSSRuleList.h"
37 #include "CSSStyleSelector.h"
38 #include "Chrome.h"
39 #include "Console.h"
40 #include "Crypto.h"
41 #include "DOMApplicationCache.h"
42 #include "DOMSelection.h"
43 #include "DOMSettableTokenList.h"
44 #include "DOMStringList.h"
45 #include "DOMTimer.h"
46 #include "DOMTokenList.h"
47 #include "DOMURL.h"
48 #include "Database.h"
49 #include "DatabaseCallback.h"
50 #include "DeviceMotionController.h"
51 #include "DeviceOrientationController.h"
52 #include "Document.h"
53 #include "DocumentLoader.h"
54 #include "Element.h"
55 #include "EventException.h"
56 #include "EventListener.h"
57 #include "EventNames.h"
58 #include "ExceptionCode.h"
59 #include "FloatRect.h"
60 #include "Frame.h"
61 #include "FrameLoadRequest.h"
62 #include "FrameLoader.h"
63 #include "FrameTree.h"
64 #include "FrameView.h"
65 #include "HTMLFrameOwnerElement.h"
66 #include "History.h"
67 #include "IDBFactory.h"
68 #include "IDBFactoryBackendInterface.h"
69 #include "InspectorInstrumentation.h"
70 #include "KURL.h"
71 #include "Location.h"
72 #include "MediaQueryList.h"
73 #include "MediaQueryMatcher.h"
74 #include "MessageEvent.h"
75 #include "Navigator.h"
76 #include "NotificationCenter.h"
77 #include "Page.h"
78 #include "PageGroup.h"
79 #include "PageTransitionEvent.h"
80 #include "Performance.h"
81 #include "PlatformScreen.h"
82 #include "PlatformString.h"
83 #include "Screen.h"
84 #include "SecurityOrigin.h"
85 #include "SerializedScriptValue.h"
86 #include "Settings.h"
87 #include "Storage.h"
88 #include "StorageArea.h"
89 #include "StorageNamespace.h"
90 #include "StyleMedia.h"
91 #include "SuddenTermination.h"
92 #include "WebKitPoint.h"
93 #include "WindowFeatures.h"
94 #include <algorithm>
95 #include <wtf/CurrentTime.h>
96 #include <wtf/MathExtras.h>
97 #include <wtf/text/StringConcatenate.h>
98
99 #if ENABLE(FILE_SYSTEM)
100 #include "AsyncFileSystem.h"
101 #include "DOMFileSystem.h"
102 #include "DOMFileSystemBase.h"
103 #include "EntryCallback.h"
104 #include "ErrorCallback.h"
105 #include "FileError.h"
106 #include "FileSystemCallback.h"
107 #include "FileSystemCallbacks.h"
108 #include "LocalFileSystem.h"
109 #endif
110
111 #if ENABLE(REQUEST_ANIMATION_FRAME)
112 #include "RequestAnimationFrameCallback.h"
113 #endif
114
115 using std::min;
116 using std::max;
117
118 namespace WebCore {
119
120 class PostMessageTimer : public TimerBase {
121 public:
122     PostMessageTimer(DOMWindow* window, PassRefPtr<SerializedScriptValue> message, const String& sourceOrigin, PassRefPtr<DOMWindow> source, PassOwnPtr<MessagePortChannelArray> channels, SecurityOrigin* targetOrigin)
123         : m_window(window)
124         , m_message(message)
125         , m_origin(sourceOrigin)
126         , m_source(source)
127         , m_channels(channels)
128         , m_targetOrigin(targetOrigin)
129     {
130     }
131
132     PassRefPtr<MessageEvent> event(ScriptExecutionContext* context)
133     {
134         OwnPtr<MessagePortArray> messagePorts = MessagePort::entanglePorts(*context, m_channels.release());
135         return MessageEvent::create(messagePorts.release(), m_message, m_origin, "", m_source);
136     }
137     SecurityOrigin* targetOrigin() const { return m_targetOrigin.get(); }
138
139 private:
140     virtual void fired()
141     {
142         m_window->postMessageTimerFired(this);
143     }
144
145     RefPtr<DOMWindow> m_window;
146     RefPtr<SerializedScriptValue> m_message;
147     String m_origin;
148     RefPtr<DOMWindow> m_source;
149     OwnPtr<MessagePortChannelArray> m_channels;
150     RefPtr<SecurityOrigin> m_targetOrigin;
151 };
152
153 typedef HashCountedSet<DOMWindow*> DOMWindowSet;
154
155 static DOMWindowSet& windowsWithUnloadEventListeners()
156 {
157     DEFINE_STATIC_LOCAL(DOMWindowSet, windowsWithUnloadEventListeners, ());
158     return windowsWithUnloadEventListeners;
159 }
160
161 static DOMWindowSet& windowsWithBeforeUnloadEventListeners()
162 {
163     DEFINE_STATIC_LOCAL(DOMWindowSet, windowsWithBeforeUnloadEventListeners, ());
164     return windowsWithBeforeUnloadEventListeners;
165 }
166
167 static void addUnloadEventListener(DOMWindow* domWindow)
168 {
169     DOMWindowSet& set = windowsWithUnloadEventListeners();
170     if (set.isEmpty())
171         disableSuddenTermination();
172     set.add(domWindow);
173 }
174
175 static void removeUnloadEventListener(DOMWindow* domWindow)
176 {
177     DOMWindowSet& set = windowsWithUnloadEventListeners();
178     DOMWindowSet::iterator it = set.find(domWindow);
179     if (it == set.end())
180         return;
181     set.remove(it);
182     if (set.isEmpty())
183         enableSuddenTermination();
184 }
185
186 static void removeAllUnloadEventListeners(DOMWindow* domWindow)
187 {
188     DOMWindowSet& set = windowsWithUnloadEventListeners();
189     DOMWindowSet::iterator it = set.find(domWindow);
190     if (it == set.end())
191         return;
192     set.removeAll(it);
193     if (set.isEmpty())
194         enableSuddenTermination();
195 }
196
197 static void addBeforeUnloadEventListener(DOMWindow* domWindow)
198 {
199     DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
200     if (set.isEmpty())
201         disableSuddenTermination();
202     set.add(domWindow);
203 }
204
205 static void removeBeforeUnloadEventListener(DOMWindow* domWindow)
206 {
207     DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
208     DOMWindowSet::iterator it = set.find(domWindow);
209     if (it == set.end())
210         return;
211     set.remove(it);
212     if (set.isEmpty())
213         enableSuddenTermination();
214 }
215
216 static void removeAllBeforeUnloadEventListeners(DOMWindow* domWindow)
217 {
218     DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
219     DOMWindowSet::iterator it = set.find(domWindow);
220     if (it == set.end())
221         return;
222     set.removeAll(it);
223     if (set.isEmpty())
224         enableSuddenTermination();
225 }
226
227 static bool allowsBeforeUnloadListeners(DOMWindow* window)
228 {
229     ASSERT_ARG(window, window);
230     Frame* frame = window->frame();
231     if (!frame)
232         return false;
233     Page* page = frame->page();
234     if (!page)
235         return false;
236     return frame == page->mainFrame();
237 }
238
239 bool DOMWindow::dispatchAllPendingBeforeUnloadEvents()
240 {
241     DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
242     if (set.isEmpty())
243         return true;
244
245     static bool alreadyDispatched = false;
246     ASSERT(!alreadyDispatched);
247     if (alreadyDispatched)
248         return true;
249
250     Vector<RefPtr<DOMWindow> > windows;
251     DOMWindowSet::iterator end = set.end();
252     for (DOMWindowSet::iterator it = set.begin(); it != end; ++it)
253         windows.append(it->first);
254
255     size_t size = windows.size();
256     for (size_t i = 0; i < size; ++i) {
257         DOMWindow* window = windows[i].get();
258         if (!set.contains(window))
259             continue;
260
261         Frame* frame = window->frame();
262         if (!frame)
263             continue;
264
265         if (!frame->loader()->shouldClose())
266             return false;
267     }
268
269     enableSuddenTermination();
270
271     alreadyDispatched = true;
272
273     return true;
274 }
275
276 unsigned DOMWindow::pendingUnloadEventListeners() const
277 {
278     return windowsWithUnloadEventListeners().count(const_cast<DOMWindow*>(this));
279 }
280
281 void DOMWindow::dispatchAllPendingUnloadEvents()
282 {
283     DOMWindowSet& set = windowsWithUnloadEventListeners();
284     if (set.isEmpty())
285         return;
286
287     static bool alreadyDispatched = false;
288     ASSERT(!alreadyDispatched);
289     if (alreadyDispatched)
290         return;
291
292     Vector<RefPtr<DOMWindow> > windows;
293     DOMWindowSet::iterator end = set.end();
294     for (DOMWindowSet::iterator it = set.begin(); it != end; ++it)
295         windows.append(it->first);
296
297     size_t size = windows.size();
298     for (size_t i = 0; i < size; ++i) {
299         DOMWindow* window = windows[i].get();
300         if (!set.contains(window))
301             continue;
302
303         window->dispatchEvent(PageTransitionEvent::create(eventNames().pagehideEvent, false), window->document());
304         window->dispatchEvent(Event::create(eventNames().unloadEvent, false, false), window->document());
305     }
306
307     enableSuddenTermination();
308
309     alreadyDispatched = true;
310 }
311
312 // This function:
313 // 1) Validates the pending changes are not changing to NaN
314 // 2) Constrains the window rect to no smaller than 100 in each dimension and no
315 //    bigger than the the float rect's dimensions.
316 // 3) Constrain window rect to within the top and left boundaries of the screen rect
317 // 4) Constraint the window rect to within the bottom and right boundaries of the
318 //    screen rect.
319 // 5) Translate the window rect coordinates to be within the coordinate space of
320 //    the screen rect.
321 void DOMWindow::adjustWindowRect(const FloatRect& screen, FloatRect& window, const FloatRect& pendingChanges)
322 {
323     // Make sure we're in a valid state before adjusting dimensions.
324     ASSERT(isfinite(screen.x()));
325     ASSERT(isfinite(screen.y()));
326     ASSERT(isfinite(screen.width()));
327     ASSERT(isfinite(screen.height()));
328     ASSERT(isfinite(window.x()));
329     ASSERT(isfinite(window.y()));
330     ASSERT(isfinite(window.width()));
331     ASSERT(isfinite(window.height()));
332     
333     // Update window values if new requested values are not NaN.
334     if (!isnan(pendingChanges.x()))
335         window.setX(pendingChanges.x());
336     if (!isnan(pendingChanges.y()))
337         window.setY(pendingChanges.y());
338     if (!isnan(pendingChanges.width()))
339         window.setWidth(pendingChanges.width());
340     if (!isnan(pendingChanges.height()))
341         window.setHeight(pendingChanges.height());
342     
343     // Resize the window to between 100 and the screen width and height.
344     window.setWidth(min(max(100.0f, window.width()), screen.width()));
345     window.setHeight(min(max(100.0f, window.height()), screen.height()));
346     
347     // Constrain the window position to the screen.
348     window.setX(max(screen.x(), min(window.x(), screen.maxX() - window.width())));
349     window.setY(max(screen.y(), min(window.y(), screen.maxY() - window.height())));
350 }
351
352 // FIXME: We can remove this function once V8 showModalDialog is changed to use DOMWindow.
353 void DOMWindow::parseModalDialogFeatures(const String& string, HashMap<String, String>& map)
354 {
355     WindowFeatures::parseDialogFeatures(string, map);
356 }
357
358 bool DOMWindow::allowPopUp(Frame* firstFrame)
359 {
360     ASSERT(firstFrame);
361
362     if (ScriptController::processingUserGesture())
363         return true;
364
365     Settings* settings = firstFrame->settings();
366     return settings && settings->javaScriptCanOpenWindowsAutomatically();
367 }
368
369 bool DOMWindow::allowPopUp()
370 {
371     return m_frame && allowPopUp(m_frame);
372 }
373
374 bool DOMWindow::canShowModalDialog(const Frame* frame)
375 {
376     if (!frame)
377         return false;
378     Page* page = frame->page();
379     if (!page)
380         return false;
381     return page->chrome()->canRunModal();
382 }
383
384 bool DOMWindow::canShowModalDialogNow(const Frame* frame)
385 {
386     if (!frame)
387         return false;
388     Page* page = frame->page();
389     if (!page)
390         return false;
391     return page->chrome()->canRunModalNow();
392 }
393
394 DOMWindow::DOMWindow(Frame* frame)
395     : m_shouldPrintWhenFinishedLoading(false)
396     , m_frame(frame)
397     , m_printTimer(this, &DOMWindow::printTimerFired)
398 {
399 }
400
401 DOMWindow::~DOMWindow()
402 {
403     if (m_frame)
404         m_frame->clearFormerDOMWindow(this);
405
406     removeAllUnloadEventListeners(this);
407     removeAllBeforeUnloadEventListeners(this);
408 }
409
410 ScriptExecutionContext* DOMWindow::scriptExecutionContext() const
411 {
412     return document();
413 }
414
415 PassRefPtr<MediaQueryList> DOMWindow::matchMedia(const String& media)
416 {
417     return document() ? document()->mediaQueryMatcher()->matchMedia(media) : 0;
418 }
419
420 void DOMWindow::disconnectFrame()
421 {
422     m_frame = 0;
423     clear();
424 }
425
426 void DOMWindow::clear()
427 {
428     if (m_screen)
429         m_screen->disconnectFrame();
430     m_screen = 0;
431
432     if (m_selection)
433         m_selection->disconnectFrame();
434     m_selection = 0;
435
436     if (m_history)
437         m_history->disconnectFrame();
438     m_history = 0;
439
440     m_crypto = 0;
441
442     if (m_locationbar)
443         m_locationbar->disconnectFrame();
444     m_locationbar = 0;
445
446     if (m_menubar)
447         m_menubar->disconnectFrame();
448     m_menubar = 0;
449
450     if (m_personalbar)
451         m_personalbar->disconnectFrame();
452     m_personalbar = 0;
453
454     if (m_scrollbars)
455         m_scrollbars->disconnectFrame();
456     m_scrollbars = 0;
457
458     if (m_statusbar)
459         m_statusbar->disconnectFrame();
460     m_statusbar = 0;
461
462     if (m_toolbar)
463         m_toolbar->disconnectFrame();
464     m_toolbar = 0;
465
466     if (m_console)
467         m_console->disconnectFrame();
468     m_console = 0;
469
470     if (m_navigator)
471         m_navigator->disconnectFrame();
472     m_navigator = 0;
473
474 #if ENABLE(WEB_TIMING)
475     if (m_performance)
476         m_performance->disconnectFrame();
477     m_performance = 0;
478 #endif
479
480     if (m_location)
481         m_location->disconnectFrame();
482     m_location = 0;
483
484     if (m_media)
485         m_media->disconnectFrame();
486     m_media = 0;
487     
488 #if ENABLE(DOM_STORAGE)
489     if (m_sessionStorage)
490         m_sessionStorage->disconnectFrame();
491     m_sessionStorage = 0;
492
493     if (m_localStorage)
494         m_localStorage->disconnectFrame();
495     m_localStorage = 0;
496 #endif
497
498 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
499     if (m_applicationCache)
500         m_applicationCache->disconnectFrame();
501     m_applicationCache = 0;
502 #endif
503
504 #if ENABLE(NOTIFICATIONS)
505     if (m_notifications)
506         m_notifications->disconnectFrame();
507     m_notifications = 0;
508 #endif
509
510 #if ENABLE(INDEXED_DATABASE)
511     m_idbFactory = 0;
512 #endif
513 }
514
515 #if ENABLE(ORIENTATION_EVENTS)
516 int DOMWindow::orientation() const
517 {
518     if (!m_frame)
519         return 0;
520     
521     return m_frame->orientation();
522 }
523 #endif
524
525 Screen* DOMWindow::screen() const
526 {
527     if (!m_screen)
528         m_screen = Screen::create(m_frame);
529     return m_screen.get();
530 }
531
532 History* DOMWindow::history() const
533 {
534     if (!m_history)
535         m_history = History::create(m_frame);
536     return m_history.get();
537 }
538
539 Crypto* DOMWindow::crypto() const
540 {
541     if (!m_crypto)
542         m_crypto = Crypto::create();
543     return m_crypto.get();
544 }
545
546 BarInfo* DOMWindow::locationbar() const
547 {
548     if (!m_locationbar)
549         m_locationbar = BarInfo::create(m_frame, BarInfo::Locationbar);
550     return m_locationbar.get();
551 }
552
553 BarInfo* DOMWindow::menubar() const
554 {
555     if (!m_menubar)
556         m_menubar = BarInfo::create(m_frame, BarInfo::Menubar);
557     return m_menubar.get();
558 }
559
560 BarInfo* DOMWindow::personalbar() const
561 {
562     if (!m_personalbar)
563         m_personalbar = BarInfo::create(m_frame, BarInfo::Personalbar);
564     return m_personalbar.get();
565 }
566
567 BarInfo* DOMWindow::scrollbars() const
568 {
569     if (!m_scrollbars)
570         m_scrollbars = BarInfo::create(m_frame, BarInfo::Scrollbars);
571     return m_scrollbars.get();
572 }
573
574 BarInfo* DOMWindow::statusbar() const
575 {
576     if (!m_statusbar)
577         m_statusbar = BarInfo::create(m_frame, BarInfo::Statusbar);
578     return m_statusbar.get();
579 }
580
581 BarInfo* DOMWindow::toolbar() const
582 {
583     if (!m_toolbar)
584         m_toolbar = BarInfo::create(m_frame, BarInfo::Toolbar);
585     return m_toolbar.get();
586 }
587
588 Console* DOMWindow::console() const
589 {
590     if (!m_console)
591         m_console = Console::create(m_frame);
592     return m_console.get();
593 }
594
595 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
596 DOMApplicationCache* DOMWindow::applicationCache() const
597 {
598     if (!m_applicationCache)
599         m_applicationCache = DOMApplicationCache::create(m_frame);
600     return m_applicationCache.get();
601 }
602 #endif
603
604 Navigator* DOMWindow::navigator() const
605 {
606     if (!m_navigator)
607         m_navigator = Navigator::create(m_frame);
608     return m_navigator.get();
609 }
610
611 #if ENABLE(WEB_TIMING)
612 Performance* DOMWindow::performance() const
613 {
614     if (!m_performance)
615         m_performance = Performance::create(m_frame);
616     return m_performance.get();
617 }
618 #endif
619
620 Location* DOMWindow::location() const
621 {
622     if (!m_location)
623         m_location = Location::create(m_frame);
624     return m_location.get();
625 }
626
627 #if ENABLE(DOM_STORAGE)
628 Storage* DOMWindow::sessionStorage(ExceptionCode& ec) const
629 {
630     if (m_sessionStorage)
631         return m_sessionStorage.get();
632
633     Document* document = this->document();
634     if (!document)
635         return 0;
636
637     if (!document->securityOrigin()->canAccessLocalStorage()) {
638         ec = SECURITY_ERR;
639         return 0;
640     }
641
642     Page* page = document->page();
643     if (!page)
644         return 0;
645
646     RefPtr<StorageArea> storageArea = page->sessionStorage()->storageArea(document->securityOrigin());
647     InspectorInstrumentation::didUseDOMStorage(page, storageArea.get(), false, m_frame);
648
649     m_sessionStorage = Storage::create(m_frame, storageArea.release());
650     return m_sessionStorage.get();
651 }
652
653 Storage* DOMWindow::localStorage(ExceptionCode& ec) const
654 {
655     if (m_localStorage)
656         return m_localStorage.get();
657
658     Document* document = this->document();
659     if (!document)
660         return 0;
661
662     if (!document->securityOrigin()->canAccessLocalStorage()) {
663         ec = SECURITY_ERR;
664         return 0;
665     }
666
667     Page* page = document->page();
668     if (!page)
669         return 0;
670
671     if (!page->settings()->localStorageEnabled())
672         return 0;
673
674     RefPtr<StorageArea> storageArea = page->group().localStorage()->storageArea(document->securityOrigin());
675     InspectorInstrumentation::didUseDOMStorage(page, storageArea.get(), true, m_frame);
676
677     m_localStorage = Storage::create(m_frame, storageArea.release());
678     return m_localStorage.get();
679 }
680 #endif
681
682 #if ENABLE(NOTIFICATIONS)
683 NotificationCenter* DOMWindow::webkitNotifications() const
684 {
685     if (m_notifications)
686         return m_notifications.get();
687
688     Document* document = this->document();
689     if (!document)
690         return 0;
691     
692     Page* page = document->page();
693     if (!page)
694         return 0;
695
696     NotificationPresenter* provider = page->chrome()->notificationPresenter();
697     if (provider) 
698         m_notifications = NotificationCenter::create(document, provider);    
699       
700     return m_notifications.get();
701 }
702 #endif
703
704 void DOMWindow::pageDestroyed()
705 {
706 #if ENABLE(NOTIFICATIONS)
707     // Clearing Notifications requests involves accessing the client so it must be done
708     // before the frame is detached.
709     if (m_notifications)
710         m_notifications->disconnectFrame();
711     m_notifications = 0;
712 #endif
713 }
714
715 void DOMWindow::resetGeolocation()
716 {
717     // Geolocation should cancel activities and permission requests when the page is detached.
718     if (m_navigator)
719         m_navigator->resetGeolocation();
720 }
721
722 #if ENABLE(INDEXED_DATABASE)
723 IDBFactory* DOMWindow::webkitIndexedDB() const
724 {
725     if (m_idbFactory)
726         return m_idbFactory.get();
727
728     Document* document = this->document();
729     if (!document)
730         return 0;
731
732     // FIXME: See if access is allowed.
733
734     Page* page = document->page();
735     if (!page)
736         return 0;
737
738     // FIXME: See if indexedDatabase access is allowed.
739
740     m_idbFactory = IDBFactory::create(page->group().idbFactory());
741     return m_idbFactory.get();
742 }
743 #endif
744
745 #if ENABLE(FILE_SYSTEM)
746 void DOMWindow::requestFileSystem(int type, long long size, PassRefPtr<FileSystemCallback> successCallback, PassRefPtr<ErrorCallback> errorCallback)
747 {
748     Document* document = this->document();
749     if (!document)
750         return;
751
752     if (!AsyncFileSystem::isAvailable() || !document->securityOrigin()->canAccessFileSystem()) {
753         DOMFileSystem::scheduleCallback(document, errorCallback, FileError::create(FileError::SECURITY_ERR));
754         return;
755     }
756
757     AsyncFileSystem::Type fileSystemType = static_cast<AsyncFileSystem::Type>(type);
758     if (fileSystemType != AsyncFileSystem::Temporary && fileSystemType != AsyncFileSystem::Persistent) {
759         DOMFileSystem::scheduleCallback(document, errorCallback, FileError::create(FileError::INVALID_MODIFICATION_ERR));
760         return;
761     }
762
763     LocalFileSystem::localFileSystem().requestFileSystem(document, fileSystemType, size, FileSystemCallbacks::create(successCallback, errorCallback, document), false);
764 }
765
766 void DOMWindow::resolveLocalFileSystemURL(const String& url, PassRefPtr<EntryCallback> successCallback, PassRefPtr<ErrorCallback> errorCallback)
767 {
768     Document* document = this->document();
769     if (!document)
770         return;
771
772     SecurityOrigin* securityOrigin = document->securityOrigin();
773     KURL completedURL = document->completeURL(url);
774     if (!AsyncFileSystem::isAvailable() || !securityOrigin->canAccessFileSystem() || !securityOrigin->canRequest(completedURL)) {
775         DOMFileSystem::scheduleCallback(document, errorCallback, FileError::create(FileError::SECURITY_ERR));
776         return;
777     }
778
779     AsyncFileSystem::Type type;
780     String filePath;
781     if (!completedURL.isValid() || !DOMFileSystemBase::crackFileSystemURL(completedURL, type, filePath)) {
782         DOMFileSystem::scheduleCallback(document, errorCallback, FileError::create(FileError::ENCODING_ERR));
783         return;
784     }
785
786     LocalFileSystem::localFileSystem().readFileSystem(document, type, ResolveURICallbacks::create(successCallback, errorCallback, document, filePath));
787 }
788
789 COMPILE_ASSERT(static_cast<int>(DOMWindow::TEMPORARY) == static_cast<int>(AsyncFileSystem::Temporary), enum_mismatch);
790 COMPILE_ASSERT(static_cast<int>(DOMWindow::PERSISTENT) == static_cast<int>(AsyncFileSystem::Persistent), enum_mismatch);
791
792 #endif
793
794 void DOMWindow::postMessage(PassRefPtr<SerializedScriptValue> message, MessagePort* port, const String& targetOrigin, DOMWindow* source, ExceptionCode& ec)
795 {
796     MessagePortArray ports;
797     if (port)
798         ports.append(port);
799     postMessage(message, &ports, targetOrigin, source, ec);
800 }
801
802 void DOMWindow::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, const String& targetOrigin, DOMWindow* source, ExceptionCode& ec)
803 {
804     if (!m_frame)
805         return;
806
807     // Compute the target origin.  We need to do this synchronously in order
808     // to generate the SYNTAX_ERR exception correctly.
809     RefPtr<SecurityOrigin> target;
810     if (targetOrigin != "*") {
811         target = SecurityOrigin::createFromString(targetOrigin);
812         if (target->isEmpty()) {
813             ec = SYNTAX_ERR;
814             return;
815         }
816     }
817
818     OwnPtr<MessagePortChannelArray> channels = MessagePort::disentanglePorts(ports, ec);
819     if (ec)
820         return;
821
822     // Capture the source of the message.  We need to do this synchronously
823     // in order to capture the source of the message correctly.
824     Document* sourceDocument = source->document();
825     if (!sourceDocument)
826         return;
827     String sourceOrigin = sourceDocument->securityOrigin()->toString();
828
829     // Schedule the message.
830     PostMessageTimer* timer = new PostMessageTimer(this, message, sourceOrigin, source, channels.release(), target.get());
831     timer->startOneShot(0);
832 }
833
834 void DOMWindow::postMessageTimerFired(PostMessageTimer* t)
835 {
836     OwnPtr<PostMessageTimer> timer(t);
837
838     if (!document())
839         return;
840
841     if (timer->targetOrigin()) {
842         // Check target origin now since the target document may have changed since the simer was scheduled.
843         if (!timer->targetOrigin()->isSameSchemeHostPort(document()->securityOrigin())) {
844             String message = makeString("Unable to post message to ", timer->targetOrigin()->toString(),
845                                         ". Recipient has origin ", document()->securityOrigin()->toString(), ".\n");
846             console()->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, message, 0, String());
847             return;
848         }
849     }
850
851     dispatchEvent(timer->event(document()));
852 }
853
854 DOMSelection* DOMWindow::getSelection()
855 {
856     if (!m_selection)
857         m_selection = DOMSelection::create(m_frame);
858     return m_selection.get();
859 }
860
861 Element* DOMWindow::frameElement() const
862 {
863     if (!m_frame)
864         return 0;
865
866     return m_frame->ownerElement();
867 }
868
869 void DOMWindow::focus()
870 {
871     if (!m_frame)
872         return;
873
874     Page* page = m_frame->page();
875     if (!page)
876         return;
877
878     // If we're a top level window, bring the window to the front.
879     if (m_frame == page->mainFrame())
880         page->chrome()->focus();
881
882     if (!m_frame)
883         return;
884
885     m_frame->eventHandler()->focusDocumentView();
886 }
887
888 void DOMWindow::blur()
889 {
890     if (!m_frame)
891         return;
892
893     Page* page = m_frame->page();
894     if (!page)
895         return;
896
897     if (m_frame != page->mainFrame())
898         return;
899
900     page->chrome()->unfocus();
901 }
902
903 void DOMWindow::close(ScriptExecutionContext* context)
904 {
905     if (!m_frame)
906         return;
907
908     Page* page = m_frame->page();
909     if (!page)
910         return;
911
912     if (m_frame != page->mainFrame())
913         return;
914
915     if (context) {
916         ASSERT(WTF::isMainThread());
917         Frame* activeFrame = static_cast<Document*>(context)->frame();
918         if (!activeFrame)
919             return;
920
921         if (!activeFrame->loader()->shouldAllowNavigation(m_frame))
922             return;
923     }
924
925     Settings* settings = m_frame->settings();
926     bool allowScriptsToCloseWindows = settings && settings->allowScriptsToCloseWindows();
927
928     if (!(page->openedByDOM() || page->backForward()->count() <= 1 || allowScriptsToCloseWindows))
929         return;
930
931     if (!m_frame->loader()->shouldClose())
932         return;
933
934     page->chrome()->closeWindowSoon();
935 }
936
937 void DOMWindow::print()
938 {
939     if (!m_frame)
940         return;
941
942     Page* page = m_frame->page();
943     if (!page)
944         return;
945
946     if (m_frame->loader()->activeDocumentLoader()->isLoading()) {
947         m_shouldPrintWhenFinishedLoading = true;
948         return;
949     }
950     m_shouldPrintWhenFinishedLoading = false;
951     page->chrome()->print(m_frame);
952 }
953
954 void DOMWindow::printTimerFired(Timer<DOMWindow>* timer)
955 {
956     ASSERT_UNUSED(timer, timer == &m_printTimer);
957     print();
958 }
959
960 void DOMWindow::stop()
961 {
962     if (!m_frame)
963         return;
964
965     // We must check whether the load is complete asynchronously, because we might still be parsing
966     // the document until the callstack unwinds.
967     m_frame->loader()->stopForUserCancel(true);
968 }
969
970 void DOMWindow::alert(const String& message)
971 {
972     if (!m_frame)
973         return;
974
975     m_frame->document()->updateStyleIfNeeded();
976
977     Page* page = m_frame->page();
978     if (!page)
979         return;
980
981     page->chrome()->runJavaScriptAlert(m_frame, message);
982 }
983
984 bool DOMWindow::confirm(const String& message)
985 {
986     if (!m_frame)
987         return false;
988
989     m_frame->document()->updateStyleIfNeeded();
990
991     Page* page = m_frame->page();
992     if (!page)
993         return false;
994
995     return page->chrome()->runJavaScriptConfirm(m_frame, message);
996 }
997
998 String DOMWindow::prompt(const String& message, const String& defaultValue)
999 {
1000     if (!m_frame)
1001         return String();
1002
1003     m_frame->document()->updateStyleIfNeeded();
1004
1005     Page* page = m_frame->page();
1006     if (!page)
1007         return String();
1008
1009     String returnValue;
1010     if (page->chrome()->runJavaScriptPrompt(m_frame, message, defaultValue, returnValue))
1011         return returnValue;
1012
1013     return String();
1014 }
1015
1016 String DOMWindow::btoa(const String& stringToEncode, ExceptionCode& ec)
1017 {
1018     if (stringToEncode.isNull())
1019         return String();
1020
1021     if (!stringToEncode.containsOnlyLatin1()) {
1022         ec = INVALID_CHARACTER_ERR;
1023         return String();
1024     }
1025
1026     return base64Encode(stringToEncode.latin1());
1027 }
1028
1029 String DOMWindow::atob(const String& encodedString, ExceptionCode& ec)
1030 {
1031     if (encodedString.isNull())
1032         return String();
1033
1034     if (!encodedString.containsOnlyLatin1()) {
1035         ec = INVALID_CHARACTER_ERR;
1036         return String();
1037     }
1038
1039     Vector<char> out;
1040     if (!base64Decode(encodedString, out, FailOnInvalidCharacter)) {
1041         ec = INVALID_CHARACTER_ERR;
1042         return String();
1043     }
1044
1045     return String(out.data(), out.size());
1046 }
1047
1048 bool DOMWindow::find(const String& string, bool caseSensitive, bool backwards, bool wrap, bool /*wholeWord*/, bool /*searchInFrames*/, bool /*showDialog*/) const
1049 {
1050     if (!m_frame)
1051         return false;
1052
1053     // FIXME (13016): Support wholeWord, searchInFrames and showDialog
1054     return m_frame->editor()->findString(string, !backwards, caseSensitive, wrap, false);
1055 }
1056
1057 bool DOMWindow::offscreenBuffering() const
1058 {
1059     return true;
1060 }
1061
1062 int DOMWindow::outerHeight() const
1063 {
1064     if (!m_frame)
1065         return 0;
1066
1067     Page* page = m_frame->page();
1068     if (!page)
1069         return 0;
1070
1071     return static_cast<int>(page->chrome()->windowRect().height());
1072 }
1073
1074 int DOMWindow::outerWidth() const
1075 {
1076     if (!m_frame)
1077         return 0;
1078
1079     Page* page = m_frame->page();
1080     if (!page)
1081         return 0;
1082
1083     return static_cast<int>(page->chrome()->windowRect().width());
1084 }
1085
1086 int DOMWindow::innerHeight() const
1087 {
1088     if (!m_frame)
1089         return 0;
1090
1091     FrameView* view = m_frame->view();
1092     if (!view)
1093         return 0;
1094     
1095 #if PLATFORM(ANDROID)
1096     return static_cast<int>(view->actualHeight() / m_frame->pageZoomFactor());
1097 #else
1098     return static_cast<int>(view->height() / m_frame->pageZoomFactor());
1099 #endif
1100 }
1101
1102 int DOMWindow::innerWidth() const
1103 {
1104     if (!m_frame)
1105         return 0;
1106
1107     FrameView* view = m_frame->view();
1108     if (!view)
1109         return 0;
1110
1111 #if PLATFORM(ANDROID)
1112     return static_cast<int>(view->actualWidth() / m_frame->pageZoomFactor());
1113 #else
1114     return static_cast<int>(view->width() / m_frame->pageZoomFactor());
1115 #endif
1116 }
1117
1118 int DOMWindow::screenX() const
1119 {
1120     if (!m_frame)
1121         return 0;
1122
1123     Page* page = m_frame->page();
1124     if (!page)
1125         return 0;
1126
1127     return static_cast<int>(page->chrome()->windowRect().x());
1128 }
1129
1130 int DOMWindow::screenY() const
1131 {
1132     if (!m_frame)
1133         return 0;
1134
1135     Page* page = m_frame->page();
1136     if (!page)
1137         return 0;
1138
1139     return static_cast<int>(page->chrome()->windowRect().y());
1140 }
1141
1142 int DOMWindow::scrollX() const
1143 {
1144     if (!m_frame)
1145         return 0;
1146
1147     FrameView* view = m_frame->view();
1148     if (!view)
1149         return 0;
1150
1151     m_frame->document()->updateLayoutIgnorePendingStylesheets();
1152
1153 #if PLATFORM(ANDROID)
1154     return static_cast<int>(view->actualScrollX() / m_frame->pageZoomFactor());
1155 #else
1156     return static_cast<int>(view->scrollX() / m_frame->pageZoomFactor());
1157 #endif
1158 }
1159
1160 int DOMWindow::scrollY() const
1161 {
1162     if (!m_frame)
1163         return 0;
1164
1165     FrameView* view = m_frame->view();
1166     if (!view)
1167         return 0;
1168
1169     m_frame->document()->updateLayoutIgnorePendingStylesheets();
1170
1171 #if PLATFORM(ANDROID)
1172     return static_cast<int>(view->actualScrollY() / m_frame->pageZoomFactor());
1173 #else
1174     return static_cast<int>(view->scrollY() / m_frame->pageZoomFactor());
1175 #endif
1176 }
1177
1178 bool DOMWindow::closed() const
1179 {
1180     return !m_frame;
1181 }
1182
1183 unsigned DOMWindow::length() const
1184 {
1185     if (!m_frame)
1186         return 0;
1187
1188     return m_frame->tree()->childCount();
1189 }
1190
1191 String DOMWindow::name() const
1192 {
1193     if (!m_frame)
1194         return String();
1195
1196     return m_frame->tree()->name();
1197 }
1198
1199 void DOMWindow::setName(const String& string)
1200 {
1201     if (!m_frame)
1202         return;
1203
1204     m_frame->tree()->setName(string);
1205 }
1206
1207 void DOMWindow::setStatus(const String& string) 
1208 {
1209     m_status = string;
1210
1211     if (!m_frame)
1212         return;
1213
1214     Page* page = m_frame->page();
1215     if (!page)
1216         return;
1217
1218     ASSERT(m_frame->document()); // Client calls shouldn't be made when the frame is in inconsistent state.
1219     page->chrome()->setStatusbarText(m_frame, m_status);
1220
1221     
1222 void DOMWindow::setDefaultStatus(const String& string) 
1223 {
1224     m_defaultStatus = string;
1225
1226     if (!m_frame)
1227         return;
1228
1229     Page* page = m_frame->page();
1230     if (!page)
1231         return;
1232
1233     ASSERT(m_frame->document()); // Client calls shouldn't be made when the frame is in inconsistent state.
1234     page->chrome()->setStatusbarText(m_frame, m_defaultStatus);
1235 }
1236
1237 DOMWindow* DOMWindow::self() const
1238 {
1239     if (!m_frame)
1240         return 0;
1241
1242     return m_frame->domWindow();
1243 }
1244
1245 DOMWindow* DOMWindow::opener() const
1246 {
1247     if (!m_frame)
1248         return 0;
1249
1250     Frame* opener = m_frame->loader()->opener();
1251     if (!opener)
1252         return 0;
1253
1254     return opener->domWindow();
1255 }
1256
1257 DOMWindow* DOMWindow::parent() const
1258 {
1259     if (!m_frame)
1260         return 0;
1261
1262     Frame* parent = m_frame->tree()->parent(true);
1263     if (parent)
1264         return parent->domWindow();
1265
1266     return m_frame->domWindow();
1267 }
1268
1269 DOMWindow* DOMWindow::top() const
1270 {
1271     if (!m_frame)
1272         return 0;
1273
1274     Page* page = m_frame->page();
1275     if (!page)
1276         return 0;
1277
1278     return m_frame->tree()->top(true)->domWindow();
1279 }
1280
1281 Document* DOMWindow::document() const
1282 {
1283     // FIXME: This function shouldn't need a frame to work.
1284     if (!m_frame)
1285         return 0;
1286
1287     // 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.
1288     // FIXME: We should always zero out the frame pointer on navigation to avoid accidentally accessing the new frame content.
1289     if (m_frame->domWindow() != this)
1290         return 0;
1291
1292     ASSERT(m_frame->document());
1293     return m_frame->document();
1294 }
1295
1296 PassRefPtr<StyleMedia> DOMWindow::styleMedia() const
1297 {
1298     if (!m_media)
1299         m_media = StyleMedia::create(m_frame);
1300     return m_media.get();
1301 }
1302
1303 PassRefPtr<CSSStyleDeclaration> DOMWindow::getComputedStyle(Element* elt, const String& pseudoElt) const
1304 {
1305     if (!elt)
1306         return 0;
1307
1308     return computedStyle(elt, false, pseudoElt);
1309 }
1310
1311 PassRefPtr<CSSRuleList> DOMWindow::getMatchedCSSRules(Element* elt, const String&, bool authorOnly) const
1312 {
1313     if (!m_frame)
1314         return 0;
1315
1316     Settings* settings = m_frame->settings();
1317     return m_frame->document()->styleSelector()->styleRulesForElement(elt, authorOnly, false, settings && settings->crossOriginCheckInGetMatchedCSSRulesDisabled() ? AllCSSRules : SameOriginCSSRulesOnly);
1318 }
1319
1320 PassRefPtr<WebKitPoint> DOMWindow::webkitConvertPointFromNodeToPage(Node* node, const WebKitPoint* p) const
1321 {
1322     if (!node || !p)
1323         return 0;
1324
1325     m_frame->document()->updateLayoutIgnorePendingStylesheets();
1326
1327     FloatPoint pagePoint(p->x(), p->y());
1328     pagePoint = node->convertToPage(pagePoint);
1329     return WebKitPoint::create(pagePoint.x(), pagePoint.y());
1330 }
1331
1332 PassRefPtr<WebKitPoint> DOMWindow::webkitConvertPointFromPageToNode(Node* node, const WebKitPoint* p) const
1333 {
1334     if (!node || !p)
1335         return 0;
1336
1337     m_frame->document()->updateLayoutIgnorePendingStylesheets();
1338
1339     FloatPoint nodePoint(p->x(), p->y());
1340     nodePoint = node->convertFromPage(nodePoint);
1341     return WebKitPoint::create(nodePoint.x(), nodePoint.y());
1342 }
1343
1344 double DOMWindow::devicePixelRatio() const
1345 {
1346     if (!m_frame)
1347         return 0.0;
1348
1349     Page* page = m_frame->page();
1350     if (!page)
1351         return 0.0;
1352
1353     return page->chrome()->scaleFactor();
1354 }
1355
1356 #if ENABLE(DATABASE)
1357 PassRefPtr<Database> DOMWindow::openDatabase(const String& name, const String& version, const String& displayName, unsigned long estimatedSize, PassRefPtr<DatabaseCallback> creationCallback, ExceptionCode& ec)
1358 {
1359     RefPtr<Database> database = 0;
1360     if (m_frame && AbstractDatabase::isAvailable() && m_frame->document()->securityOrigin()->canAccessDatabase())
1361         database = Database::openDatabase(m_frame->document(), name, version, displayName, estimatedSize, creationCallback, ec);
1362
1363     if (!database && !ec)
1364         ec = SECURITY_ERR;
1365
1366     return database;
1367 }
1368 #endif
1369
1370 void DOMWindow::scrollBy(int x, int y) const
1371 {
1372     if (!m_frame)
1373         return;
1374
1375     m_frame->document()->updateLayoutIgnorePendingStylesheets();
1376
1377     RefPtr<FrameView> view = m_frame->view();
1378     if (!view)
1379         return;
1380
1381     view->scrollBy(IntSize(x, y));
1382 }
1383
1384 void DOMWindow::scrollTo(int x, int y) const
1385 {
1386     if (!m_frame)
1387         return;
1388
1389     m_frame->document()->updateLayoutIgnorePendingStylesheets();
1390
1391     RefPtr<FrameView> view = m_frame->view();
1392     if (!view)
1393         return;
1394
1395     int zoomedX = static_cast<int>(x * m_frame->pageZoomFactor());
1396     int zoomedY = static_cast<int>(y * m_frame->pageZoomFactor());
1397     view->setScrollPosition(IntPoint(zoomedX, zoomedY));
1398 }
1399
1400 void DOMWindow::moveBy(float x, float y) const
1401 {
1402     if (!m_frame)
1403         return;
1404
1405     Page* page = m_frame->page();
1406     if (!page)
1407         return;
1408
1409     if (m_frame != page->mainFrame())
1410         return;
1411
1412     FloatRect fr = page->chrome()->windowRect();
1413     FloatRect update = fr;
1414     update.move(x, y);
1415     // Security check (the spec talks about UniversalBrowserWrite to disable this check...)
1416     adjustWindowRect(screenAvailableRect(page->mainFrame()->view()), fr, update);
1417     page->chrome()->setWindowRect(fr);
1418 }
1419
1420 void DOMWindow::moveTo(float x, float y) const
1421 {
1422     if (!m_frame)
1423         return;
1424
1425     Page* page = m_frame->page();
1426     if (!page)
1427         return;
1428
1429     if (m_frame != page->mainFrame())
1430         return;
1431
1432     FloatRect fr = page->chrome()->windowRect();
1433     FloatRect sr = screenAvailableRect(page->mainFrame()->view());
1434     fr.setLocation(sr.location());
1435     FloatRect update = fr;
1436     update.move(x, y);     
1437     // Security check (the spec talks about UniversalBrowserWrite to disable this check...)
1438     adjustWindowRect(sr, fr, update);
1439     page->chrome()->setWindowRect(fr);
1440 }
1441
1442 void DOMWindow::resizeBy(float x, float y) const
1443 {
1444     if (!m_frame)
1445         return;
1446
1447     Page* page = m_frame->page();
1448     if (!page)
1449         return;
1450
1451     if (m_frame != page->mainFrame())
1452         return;
1453
1454     FloatRect fr = page->chrome()->windowRect();
1455     FloatSize dest = fr.size() + FloatSize(x, y);
1456     FloatRect update(fr.location(), dest);
1457     adjustWindowRect(screenAvailableRect(page->mainFrame()->view()), fr, update);
1458     page->chrome()->setWindowRect(fr);
1459 }
1460
1461 void DOMWindow::resizeTo(float width, float height) const
1462 {
1463     if (!m_frame)
1464         return;
1465
1466     Page* page = m_frame->page();
1467     if (!page)
1468         return;
1469
1470     if (m_frame != page->mainFrame())
1471         return;
1472
1473     FloatRect fr = page->chrome()->windowRect();
1474     FloatSize dest = FloatSize(width, height);
1475     FloatRect update(fr.location(), dest);
1476     adjustWindowRect(screenAvailableRect(page->mainFrame()->view()), fr, update);
1477     page->chrome()->setWindowRect(fr);
1478 }
1479
1480 int DOMWindow::setTimeout(PassOwnPtr<ScheduledAction> action, int timeout, ExceptionCode& ec)
1481 {
1482     ScriptExecutionContext* context = scriptExecutionContext();
1483     if (!context) {
1484         ec = INVALID_ACCESS_ERR;
1485         return -1;
1486     }
1487     return DOMTimer::install(context, action, timeout, true);
1488 }
1489
1490 void DOMWindow::clearTimeout(int timeoutId)
1491 {
1492     ScriptExecutionContext* context = scriptExecutionContext();
1493     if (!context)
1494         return;
1495     DOMTimer::removeById(context, timeoutId);
1496 }
1497
1498 int DOMWindow::setInterval(PassOwnPtr<ScheduledAction> action, int timeout, ExceptionCode& ec)
1499 {
1500     ScriptExecutionContext* context = scriptExecutionContext();
1501     if (!context) {
1502         ec = INVALID_ACCESS_ERR;
1503         return -1;
1504     }
1505     return DOMTimer::install(context, action, timeout, false);
1506 }
1507
1508 void DOMWindow::clearInterval(int timeoutId)
1509 {
1510     ScriptExecutionContext* context = scriptExecutionContext();
1511     if (!context)
1512         return;
1513     DOMTimer::removeById(context, timeoutId);
1514 }
1515
1516 #if ENABLE(REQUEST_ANIMATION_FRAME)
1517 int DOMWindow::webkitRequestAnimationFrame(PassRefPtr<RequestAnimationFrameCallback> callback, Element* e)
1518 {
1519     if (Document* d = document())
1520         return d->webkitRequestAnimationFrame(callback, e);
1521     return 0;
1522 }
1523
1524 void DOMWindow::webkitCancelRequestAnimationFrame(int id)
1525 {
1526     if (Document* d = document())
1527         d->webkitCancelRequestAnimationFrame(id);
1528 }
1529 #endif
1530
1531 bool DOMWindow::addEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
1532 {
1533     if (!EventTarget::addEventListener(eventType, listener, useCapture))
1534         return false;
1535
1536     if (Document* document = this->document())
1537         document->addListenerTypeIfNeeded(eventType);
1538
1539     if (eventType == eventNames().unloadEvent)
1540         addUnloadEventListener(this);
1541     else if (eventType == eventNames().beforeunloadEvent && allowsBeforeUnloadListeners(this))
1542         addBeforeUnloadEventListener(this);
1543 #if ENABLE(DEVICE_ORIENTATION)
1544     else if (eventType == eventNames().devicemotionEvent && frame() && frame()->page() && frame()->page()->deviceMotionController())
1545         frame()->page()->deviceMotionController()->addListener(this);
1546     else if (eventType == eventNames().deviceorientationEvent && frame() && frame()->page() && frame()->page()->deviceOrientationController())
1547         frame()->page()->deviceOrientationController()->addListener(this);
1548 #endif
1549
1550     return true;
1551 }
1552
1553 bool DOMWindow::removeEventListener(const AtomicString& eventType, EventListener* listener, bool useCapture)
1554 {
1555     if (!EventTarget::removeEventListener(eventType, listener, useCapture))
1556         return false;
1557
1558     if (eventType == eventNames().unloadEvent)
1559         removeUnloadEventListener(this);
1560     else if (eventType == eventNames().beforeunloadEvent && allowsBeforeUnloadListeners(this))
1561         removeBeforeUnloadEventListener(this);
1562 #if ENABLE(DEVICE_ORIENTATION)
1563     else if (eventType == eventNames().devicemotionEvent && frame() && frame()->page() && frame()->page()->deviceMotionController())
1564         frame()->page()->deviceMotionController()->removeListener(this);
1565     else if (eventType == eventNames().deviceorientationEvent && frame() && frame()->page() && frame()->page()->deviceOrientationController())
1566         frame()->page()->deviceOrientationController()->removeListener(this);
1567 #endif
1568
1569     return true;
1570 }
1571
1572 void DOMWindow::dispatchLoadEvent()
1573 {
1574     RefPtr<Event> loadEvent(Event::create(eventNames().loadEvent, false, false));
1575     if (m_frame && m_frame->loader()->documentLoader() && !m_frame->loader()->documentLoader()->timing()->loadEventStart) {
1576         // The DocumentLoader (and thus its DocumentLoadTiming) might get destroyed while dispatching
1577         // the event, so protect it to prevent writing the end time into freed memory.
1578         RefPtr<DocumentLoader> documentLoader = m_frame->loader()->documentLoader();
1579         DocumentLoadTiming* timing = documentLoader->timing();
1580         dispatchTimedEvent(loadEvent, document(), &timing->loadEventStart, &timing->loadEventEnd);
1581     } else
1582         dispatchEvent(loadEvent, document());
1583
1584     // For load events, send a separate load event to the enclosing frame only.
1585     // This is a DOM extension and is independent of bubbling/capturing rules of
1586     // the DOM.
1587     Element* ownerElement = m_frame ? m_frame->ownerElement() : 0;
1588     if (ownerElement)
1589         ownerElement->dispatchEvent(Event::create(eventNames().loadEvent, false, false));
1590
1591     InspectorInstrumentation::loadEventFired(frame(), url());
1592 }
1593
1594 bool DOMWindow::dispatchEvent(PassRefPtr<Event> prpEvent, PassRefPtr<EventTarget> prpTarget)
1595 {
1596     RefPtr<EventTarget> protect = this;
1597     RefPtr<Event> event = prpEvent;
1598
1599     event->setTarget(prpTarget ? prpTarget : this);
1600     event->setCurrentTarget(this);
1601     event->setEventPhase(Event::AT_TARGET);
1602
1603     InspectorInstrumentationCookie cookie = InspectorInstrumentation::willDispatchEventOnWindow(frame(), *event, this);
1604
1605     bool result = fireEventListeners(event.get());
1606
1607     InspectorInstrumentation::didDispatchEventOnWindow(cookie);
1608
1609     return result;
1610 }
1611
1612 void DOMWindow::dispatchTimedEvent(PassRefPtr<Event> event, Document* target, double* startTime, double* endTime)
1613 {
1614     ASSERT(startTime);
1615     ASSERT(endTime);
1616     *startTime = currentTime();
1617     dispatchEvent(event, target);
1618     *endTime = currentTime();
1619 }
1620
1621 void DOMWindow::removeAllEventListeners()
1622 {
1623     EventTarget::removeAllEventListeners();
1624
1625 #if ENABLE(DEVICE_ORIENTATION)
1626     if (frame() && frame()->page() && frame()->page()->deviceMotionController())
1627         frame()->page()->deviceMotionController()->removeAllListeners(this);
1628     if (frame() && frame()->page() && frame()->page()->deviceOrientationController())
1629         frame()->page()->deviceOrientationController()->removeAllListeners(this);
1630 #endif
1631
1632     removeAllUnloadEventListeners(this);
1633     removeAllBeforeUnloadEventListeners(this);
1634 }
1635
1636 void DOMWindow::captureEvents()
1637 {
1638     // Not implemented.
1639 }
1640
1641 void DOMWindow::releaseEvents()
1642 {
1643     // Not implemented.
1644 }
1645
1646 void DOMWindow::finishedLoading()
1647 {
1648     if (m_shouldPrintWhenFinishedLoading) {
1649         m_shouldPrintWhenFinishedLoading = false;
1650
1651         m_printTimer.stop();
1652         m_printTimer.startOneShot(0);
1653     }
1654 }
1655
1656 EventTargetData* DOMWindow::eventTargetData()
1657 {
1658     return &m_eventTargetData;
1659 }
1660
1661 EventTargetData* DOMWindow::ensureEventTargetData()
1662 {
1663     return &m_eventTargetData;
1664 }
1665
1666 #if ENABLE(DOM_STORAGE) && defined(ANDROID)
1667 void DOMWindow::clearDOMStorage()
1668 {
1669     if (m_sessionStorage)
1670         m_sessionStorage->disconnectFrame();
1671     m_sessionStorage = 0;
1672
1673     if (m_localStorage)
1674         m_localStorage->disconnectFrame();
1675     m_localStorage = 0;
1676 }
1677 #endif
1678
1679 void DOMWindow::setLocation(const String& urlString, DOMWindow* activeWindow, DOMWindow* firstWindow, SetLocationLocking locking)
1680 {
1681     if (!m_frame)
1682         return;
1683
1684     Frame* activeFrame = activeWindow->frame();
1685     if (!activeFrame)
1686         return;
1687
1688     if (!activeFrame->loader()->shouldAllowNavigation(m_frame))
1689         return;
1690
1691     Frame* firstFrame = firstWindow->frame();
1692     if (!firstFrame)
1693         return;
1694
1695     KURL completedURL = firstFrame->document()->completeURL(urlString);
1696     if (completedURL.isNull())
1697         return;
1698
1699     if (isInsecureScriptAccess(activeWindow, urlString))
1700         return;
1701
1702     // We want a new history item if we are processing a user gesture.
1703     m_frame->navigationScheduler()->scheduleLocationChange(activeFrame->document()->securityOrigin(),
1704         completedURL, activeFrame->loader()->outgoingReferrer(),
1705         locking != LockHistoryBasedOnGestureState || !activeFrame->script()->anyPageIsProcessingUserGesture(),
1706         locking != LockHistoryBasedOnGestureState);
1707 }
1708
1709 void DOMWindow::printErrorMessage(const String& message)
1710 {
1711     if (message.isEmpty())
1712         return;
1713
1714     Settings* settings = m_frame->settings();
1715     if (!settings)
1716         return;
1717     if (settings->privateBrowsingEnabled())
1718         return;
1719
1720     // FIXME: Add arguments so that we can provide a correct source URL and line number.
1721     console()->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, message, 1, String());
1722 }
1723
1724 String DOMWindow::crossDomainAccessErrorMessage(DOMWindow* activeWindow)
1725 {
1726     const KURL& activeWindowURL = activeWindow->url();
1727     if (activeWindowURL.isNull())
1728         return String();
1729
1730     // FIXME: This error message should contain more specifics of why the same origin check has failed.
1731     // Perhaps we should involve the security origin object in composing it.
1732     // FIXME: This message, and other console messages, have extra newlines. Should remove them.
1733     return makeString("Unsafe JavaScript attempt to access frame with URL ", m_url.string(),
1734         " from frame with URL ", activeWindowURL.string(), ". Domains, protocols and ports must match.\n");
1735 }
1736
1737 bool DOMWindow::isInsecureScriptAccess(DOMWindow* activeWindow, const String& urlString)
1738 {
1739     if (!protocolIsJavaScript(urlString))
1740         return false;
1741
1742     // FIXME: Is there some way to eliminate the need for a separate "activeWindow == this" check?
1743     if (activeWindow == this)
1744         return false;
1745
1746     // FIXME: The name canAccess seems to be a roundabout way to ask "can execute script".
1747     // Can we name the SecurityOrigin function better to make this more clear?
1748     if (activeWindow->securityOrigin()->canAccess(securityOrigin()))
1749         return false;
1750
1751     printErrorMessage(crossDomainAccessErrorMessage(activeWindow));
1752     return true;
1753 }
1754
1755 Frame* DOMWindow::createWindow(const String& urlString, const AtomicString& frameName, const WindowFeatures& windowFeatures,
1756     DOMWindow* activeWindow, Frame* firstFrame, Frame* openerFrame, PrepareDialogFunction function, void* functionContext)
1757 {
1758     Frame* activeFrame = activeWindow->frame();
1759
1760     // For whatever reason, Firefox uses the first frame to determine the outgoingReferrer. We replicate that behavior here.
1761     String referrer = firstFrame->loader()->outgoingReferrer();
1762
1763     KURL completedURL = urlString.isEmpty() ? KURL(ParsedURLString, "") : firstFrame->document()->completeURL(urlString);
1764     ResourceRequest request(completedURL, referrer);
1765     FrameLoader::addHTTPOriginIfNeeded(request, firstFrame->loader()->outgoingOrigin());
1766     FrameLoadRequest frameRequest(activeWindow->securityOrigin(), request, frameName);
1767
1768     // We pass the opener frame for the lookupFrame in case the active frame is different from
1769     // the opener frame, and the name references a frame relative to the opener frame.
1770     bool created;
1771     Frame* newFrame = WebCore::createWindow(activeFrame, openerFrame, frameRequest, windowFeatures, created);
1772     if (!newFrame)
1773         return 0;
1774
1775     newFrame->loader()->setOpener(openerFrame);
1776     newFrame->page()->setOpenedByDOM();
1777
1778     if (newFrame->domWindow()->isInsecureScriptAccess(activeWindow, urlString))
1779         return newFrame;
1780
1781     if (function)
1782         function(newFrame->domWindow(), functionContext);
1783
1784     if (created)
1785         newFrame->loader()->changeLocation(activeWindow->securityOrigin(), completedURL, referrer, false, false);
1786     else if (!urlString.isEmpty()) {
1787         newFrame->navigationScheduler()->scheduleLocationChange(activeWindow->securityOrigin(), completedURL.string(), referrer,
1788             !activeFrame->script()->anyPageIsProcessingUserGesture(), false);
1789     }
1790
1791     return newFrame;
1792 }
1793
1794 PassRefPtr<DOMWindow> DOMWindow::open(const String& urlString, const AtomicString& frameName, const String& windowFeaturesString,
1795     DOMWindow* activeWindow, DOMWindow* firstWindow)
1796 {
1797     if (!m_frame)
1798         return 0;
1799     Frame* activeFrame = activeWindow->frame();
1800     if (!activeFrame)
1801         return 0;
1802     Frame* firstFrame = firstWindow->frame();
1803     if (!firstFrame)
1804         return 0;
1805
1806     if (!firstWindow->allowPopUp()) {
1807         // Because FrameTree::find() returns true for empty strings, we must check for empty frame names.
1808         // Otherwise, illegitimate window.open() calls with no name will pass right through the popup blocker.
1809         if (frameName.isEmpty() || !m_frame->tree()->find(frameName))
1810             return 0;
1811     }
1812
1813     // Get the target frame for the special cases of _top and _parent.
1814     // In those cases, we schedule a location change right now and return early.
1815     Frame* targetFrame = 0;
1816     if (frameName == "_top")
1817         targetFrame = m_frame->tree()->top();
1818     else if (frameName == "_parent") {
1819         if (Frame* parent = m_frame->tree()->parent())
1820             targetFrame = parent;
1821         else
1822             targetFrame = m_frame;
1823     }
1824     if (targetFrame) {
1825         if (!activeFrame->loader()->shouldAllowNavigation(targetFrame))
1826             return 0;
1827
1828         if (isInsecureScriptAccess(activeWindow, urlString))
1829             return targetFrame->domWindow();
1830
1831         if (urlString.isEmpty())
1832             return targetFrame->domWindow();
1833
1834         // For whatever reason, Firefox uses the first window rather than the active window to
1835         // determine the outgoing referrer. We replicate that behavior here.
1836         targetFrame->navigationScheduler()->scheduleLocationChange(activeFrame->document()->securityOrigin(),
1837             firstFrame->document()->completeURL(urlString).string(),
1838             firstFrame->loader()->outgoingReferrer(),
1839             !activeFrame->script()->anyPageIsProcessingUserGesture(), false);
1840
1841         return targetFrame->domWindow();
1842     }
1843
1844     WindowFeatures windowFeatures(windowFeaturesString);
1845     FloatRect windowRect(windowFeatures.xSet ? windowFeatures.x : 0, windowFeatures.ySet ? windowFeatures.y : 0,
1846         windowFeatures.widthSet ? windowFeatures.width : 0, windowFeatures.heightSet ? windowFeatures.height : 0);
1847     Page* page = m_frame->page();
1848     DOMWindow::adjustWindowRect(screenAvailableRect(page ? page->mainFrame()->view() : 0), windowRect, windowRect);
1849     windowFeatures.x = windowRect.x();
1850     windowFeatures.y = windowRect.y();
1851     windowFeatures.height = windowRect.height();
1852     windowFeatures.width = windowRect.width();
1853
1854     Frame* result = createWindow(urlString, frameName, windowFeatures, activeWindow, firstFrame, m_frame);
1855     return result ? result->domWindow() : 0;
1856 }
1857
1858 void DOMWindow::showModalDialog(const String& urlString, const String& dialogFeaturesString,
1859     DOMWindow* activeWindow, DOMWindow* firstWindow, PrepareDialogFunction function, void* functionContext)
1860 {
1861     if (!m_frame)
1862         return;
1863     Frame* activeFrame = activeWindow->frame();
1864     if (!activeFrame)
1865         return;
1866     Frame* firstFrame = firstWindow->frame();
1867     if (!firstFrame)
1868         return;
1869
1870     if (!canShowModalDialogNow(m_frame) || !firstWindow->allowPopUp())
1871         return;
1872
1873     Frame* dialogFrame = createWindow(urlString, emptyAtom, WindowFeatures(dialogFeaturesString, screenAvailableRect(m_frame->view())),
1874         activeWindow, firstFrame, m_frame, function, functionContext);
1875     if (!dialogFrame)
1876         return;
1877
1878     dialogFrame->page()->chrome()->runModal();
1879 }
1880
1881 #if ENABLE(BLOB)
1882 DOMURL* DOMWindow::webkitURL() const
1883 {
1884     if (!m_domURL)
1885         m_domURL = DOMURL::create(this->scriptExecutionContext());
1886     return m_domURL.get();
1887 }
1888 #endif
1889
1890 } // namespace WebCore