OSDN Git Service

Merge WebKit at r80534: Intial merge by Git
[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 {
398 }
399
400 DOMWindow::~DOMWindow()
401 {
402     if (m_frame)
403         m_frame->clearFormerDOMWindow(this);
404
405     removeAllUnloadEventListeners(this);
406     removeAllBeforeUnloadEventListeners(this);
407 }
408
409 ScriptExecutionContext* DOMWindow::scriptExecutionContext() const
410 {
411     return document();
412 }
413
414 PassRefPtr<MediaQueryList> DOMWindow::matchMedia(const String& media)
415 {
416     return document() ? document()->mediaQueryMatcher()->matchMedia(media) : 0;
417 }
418
419 void DOMWindow::disconnectFrame()
420 {
421     m_frame = 0;
422     clear();
423 }
424
425 void DOMWindow::clear()
426 {
427     if (m_screen)
428         m_screen->disconnectFrame();
429     m_screen = 0;
430
431     if (m_selection)
432         m_selection->disconnectFrame();
433     m_selection = 0;
434
435     if (m_history)
436         m_history->disconnectFrame();
437     m_history = 0;
438
439     m_crypto = 0;
440
441     if (m_locationbar)
442         m_locationbar->disconnectFrame();
443     m_locationbar = 0;
444
445     if (m_menubar)
446         m_menubar->disconnectFrame();
447     m_menubar = 0;
448
449     if (m_personalbar)
450         m_personalbar->disconnectFrame();
451     m_personalbar = 0;
452
453     if (m_scrollbars)
454         m_scrollbars->disconnectFrame();
455     m_scrollbars = 0;
456
457     if (m_statusbar)
458         m_statusbar->disconnectFrame();
459     m_statusbar = 0;
460
461     if (m_toolbar)
462         m_toolbar->disconnectFrame();
463     m_toolbar = 0;
464
465     if (m_console)
466         m_console->disconnectFrame();
467     m_console = 0;
468
469     if (m_navigator)
470         m_navigator->disconnectFrame();
471     m_navigator = 0;
472
473 #if ENABLE(WEB_TIMING)
474     if (m_performance)
475         m_performance->disconnectFrame();
476     m_performance = 0;
477 #endif
478
479     if (m_location)
480         m_location->disconnectFrame();
481     m_location = 0;
482
483     if (m_media)
484         m_media->disconnectFrame();
485     m_media = 0;
486     
487 #if ENABLE(DOM_STORAGE)
488     if (m_sessionStorage)
489         m_sessionStorage->disconnectFrame();
490     m_sessionStorage = 0;
491
492     if (m_localStorage)
493         m_localStorage->disconnectFrame();
494     m_localStorage = 0;
495 #endif
496
497 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
498     if (m_applicationCache)
499         m_applicationCache->disconnectFrame();
500     m_applicationCache = 0;
501 #endif
502
503 #if ENABLE(NOTIFICATIONS)
504     if (m_notifications)
505         m_notifications->disconnectFrame();
506     m_notifications = 0;
507 #endif
508
509 #if ENABLE(INDEXED_DATABASE)
510     m_idbFactory = 0;
511 #endif
512 }
513
514 #if ENABLE(ORIENTATION_EVENTS)
515 int DOMWindow::orientation() const
516 {
517     if (!m_frame)
518         return 0;
519     
520     return m_frame->orientation();
521 }
522 #endif
523
524 Screen* DOMWindow::screen() const
525 {
526     if (!m_screen)
527         m_screen = Screen::create(m_frame);
528     return m_screen.get();
529 }
530
531 History* DOMWindow::history() const
532 {
533     if (!m_history)
534         m_history = History::create(m_frame);
535     return m_history.get();
536 }
537
538 Crypto* DOMWindow::crypto() const
539 {
540     if (!m_crypto)
541         m_crypto = Crypto::create();
542     return m_crypto.get();
543 }
544
545 BarInfo* DOMWindow::locationbar() const
546 {
547     if (!m_locationbar)
548         m_locationbar = BarInfo::create(m_frame, BarInfo::Locationbar);
549     return m_locationbar.get();
550 }
551
552 BarInfo* DOMWindow::menubar() const
553 {
554     if (!m_menubar)
555         m_menubar = BarInfo::create(m_frame, BarInfo::Menubar);
556     return m_menubar.get();
557 }
558
559 BarInfo* DOMWindow::personalbar() const
560 {
561     if (!m_personalbar)
562         m_personalbar = BarInfo::create(m_frame, BarInfo::Personalbar);
563     return m_personalbar.get();
564 }
565
566 BarInfo* DOMWindow::scrollbars() const
567 {
568     if (!m_scrollbars)
569         m_scrollbars = BarInfo::create(m_frame, BarInfo::Scrollbars);
570     return m_scrollbars.get();
571 }
572
573 BarInfo* DOMWindow::statusbar() const
574 {
575     if (!m_statusbar)
576         m_statusbar = BarInfo::create(m_frame, BarInfo::Statusbar);
577     return m_statusbar.get();
578 }
579
580 BarInfo* DOMWindow::toolbar() const
581 {
582     if (!m_toolbar)
583         m_toolbar = BarInfo::create(m_frame, BarInfo::Toolbar);
584     return m_toolbar.get();
585 }
586
587 Console* DOMWindow::console() const
588 {
589     if (!m_console)
590         m_console = Console::create(m_frame);
591     return m_console.get();
592 }
593
594 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
595 DOMApplicationCache* DOMWindow::applicationCache() const
596 {
597     if (!m_applicationCache)
598         m_applicationCache = DOMApplicationCache::create(m_frame);
599     return m_applicationCache.get();
600 }
601 #endif
602
603 Navigator* DOMWindow::navigator() const
604 {
605     if (!m_navigator)
606         m_navigator = Navigator::create(m_frame);
607     return m_navigator.get();
608 }
609
610 #if ENABLE(WEB_TIMING)
611 Performance* DOMWindow::performance() const
612 {
613     if (!m_performance)
614         m_performance = Performance::create(m_frame);
615     return m_performance.get();
616 }
617 #endif
618
619 Location* DOMWindow::location() const
620 {
621     if (!m_location)
622         m_location = Location::create(m_frame);
623     return m_location.get();
624 }
625
626 #if ENABLE(DOM_STORAGE)
627 Storage* DOMWindow::sessionStorage(ExceptionCode& ec) const
628 {
629     if (m_sessionStorage)
630         return m_sessionStorage.get();
631
632     Document* document = this->document();
633     if (!document)
634         return 0;
635
636     if (!document->securityOrigin()->canAccessLocalStorage()) {
637         ec = SECURITY_ERR;
638         return 0;
639     }
640
641     Page* page = document->page();
642     if (!page)
643         return 0;
644
645     RefPtr<StorageArea> storageArea = page->sessionStorage()->storageArea(document->securityOrigin());
646     InspectorInstrumentation::didUseDOMStorage(page, storageArea.get(), false, m_frame);
647
648     m_sessionStorage = Storage::create(m_frame, storageArea.release());
649     return m_sessionStorage.get();
650 }
651
652 Storage* DOMWindow::localStorage(ExceptionCode& ec) const
653 {
654     if (m_localStorage)
655         return m_localStorage.get();
656
657     Document* document = this->document();
658     if (!document)
659         return 0;
660
661     if (!document->securityOrigin()->canAccessLocalStorage()) {
662         ec = SECURITY_ERR;
663         return 0;
664     }
665
666     Page* page = document->page();
667     if (!page)
668         return 0;
669
670     if (!page->settings()->localStorageEnabled())
671         return 0;
672
673     RefPtr<StorageArea> storageArea = page->group().localStorage()->storageArea(document->securityOrigin());
674     InspectorInstrumentation::didUseDOMStorage(page, storageArea.get(), true, m_frame);
675
676     m_localStorage = Storage::create(m_frame, storageArea.release());
677     return m_localStorage.get();
678 }
679 #endif
680
681 #if ENABLE(NOTIFICATIONS)
682 NotificationCenter* DOMWindow::webkitNotifications() const
683 {
684     if (m_notifications)
685         return m_notifications.get();
686
687     Document* document = this->document();
688     if (!document)
689         return 0;
690     
691     Page* page = document->page();
692     if (!page)
693         return 0;
694
695     NotificationPresenter* provider = page->chrome()->notificationPresenter();
696     if (provider) 
697         m_notifications = NotificationCenter::create(document, provider);    
698       
699     return m_notifications.get();
700 }
701 #endif
702
703 void DOMWindow::pageDestroyed()
704 {
705 #if ENABLE(NOTIFICATIONS)
706     // Clearing Notifications requests involves accessing the client so it must be done
707     // before the frame is detached.
708     if (m_notifications)
709         m_notifications->disconnectFrame();
710     m_notifications = 0;
711 #endif
712 }
713
714 #if ENABLE(INDEXED_DATABASE)
715 IDBFactory* DOMWindow::webkitIndexedDB() const
716 {
717     if (m_idbFactory)
718         return m_idbFactory.get();
719
720     Document* document = this->document();
721     if (!document)
722         return 0;
723
724     // FIXME: See if access is allowed.
725
726     Page* page = document->page();
727     if (!page)
728         return 0;
729
730     // FIXME: See if indexedDatabase access is allowed.
731
732     m_idbFactory = IDBFactory::create(page->group().idbFactory());
733     return m_idbFactory.get();
734 }
735 #endif
736
737 #if ENABLE(FILE_SYSTEM)
738 void DOMWindow::requestFileSystem(int type, long long size, PassRefPtr<FileSystemCallback> successCallback, PassRefPtr<ErrorCallback> errorCallback)
739 {
740     Document* document = this->document();
741     if (!document)
742         return;
743
744     if (!AsyncFileSystem::isAvailable() || !document->securityOrigin()->canAccessFileSystem()) {
745         DOMFileSystem::scheduleCallback(document, errorCallback, FileError::create(FileError::SECURITY_ERR));
746         return;
747     }
748
749     AsyncFileSystem::Type fileSystemType = static_cast<AsyncFileSystem::Type>(type);
750     if (fileSystemType != AsyncFileSystem::Temporary && fileSystemType != AsyncFileSystem::Persistent) {
751         DOMFileSystem::scheduleCallback(document, errorCallback, FileError::create(FileError::INVALID_MODIFICATION_ERR));
752         return;
753     }
754
755     LocalFileSystem::localFileSystem().requestFileSystem(document, fileSystemType, size, FileSystemCallbacks::create(successCallback, errorCallback, document), false);
756 }
757
758 void DOMWindow::resolveLocalFileSystemURI(const String& uri, PassRefPtr<EntryCallback> successCallback, PassRefPtr<ErrorCallback> errorCallback)
759 {
760     Document* document = this->document();
761     if (!document)
762         return;
763
764     SecurityOrigin* securityOrigin = document->securityOrigin();
765     KURL completedURL = document->completeURL(uri);
766     if (!AsyncFileSystem::isAvailable() || !securityOrigin->canAccessFileSystem() || !securityOrigin->canRequest(completedURL)) {
767         DOMFileSystem::scheduleCallback(document, errorCallback, FileError::create(FileError::SECURITY_ERR));
768         return;
769     }
770
771     AsyncFileSystem::Type type;
772     String filePath;
773     if (!completedURL.isValid() || !DOMFileSystemBase::crackFileSystemURL(completedURL, type, filePath)) {
774         DOMFileSystem::scheduleCallback(document, errorCallback, FileError::create(FileError::SYNTAX_ERR));
775         return;
776     }
777
778     LocalFileSystem::localFileSystem().readFileSystem(document, type, ResolveURICallbacks::create(successCallback, errorCallback, document, filePath));
779 }
780
781 COMPILE_ASSERT(static_cast<int>(DOMWindow::TEMPORARY) == static_cast<int>(AsyncFileSystem::Temporary), enum_mismatch);
782 COMPILE_ASSERT(static_cast<int>(DOMWindow::PERSISTENT) == static_cast<int>(AsyncFileSystem::Persistent), enum_mismatch);
783
784 #endif
785
786 void DOMWindow::postMessage(PassRefPtr<SerializedScriptValue> message, MessagePort* port, const String& targetOrigin, DOMWindow* source, ExceptionCode& ec)
787 {
788     MessagePortArray ports;
789     if (port)
790         ports.append(port);
791     postMessage(message, &ports, targetOrigin, source, ec);
792 }
793
794 void DOMWindow::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, const String& targetOrigin, DOMWindow* source, ExceptionCode& ec)
795 {
796     if (!m_frame)
797         return;
798
799     // Compute the target origin.  We need to do this synchronously in order
800     // to generate the SYNTAX_ERR exception correctly.
801     RefPtr<SecurityOrigin> target;
802     if (targetOrigin != "*") {
803         target = SecurityOrigin::createFromString(targetOrigin);
804         if (target->isEmpty()) {
805             ec = SYNTAX_ERR;
806             return;
807         }
808     }
809
810     OwnPtr<MessagePortChannelArray> channels = MessagePort::disentanglePorts(ports, ec);
811     if (ec)
812         return;
813
814     // Capture the source of the message.  We need to do this synchronously
815     // in order to capture the source of the message correctly.
816     Document* sourceDocument = source->document();
817     if (!sourceDocument)
818         return;
819     String sourceOrigin = sourceDocument->securityOrigin()->toString();
820
821     // Schedule the message.
822     PostMessageTimer* timer = new PostMessageTimer(this, message, sourceOrigin, source, channels.release(), target.get());
823     timer->startOneShot(0);
824 }
825
826 void DOMWindow::postMessageTimerFired(PostMessageTimer* t)
827 {
828     OwnPtr<PostMessageTimer> timer(t);
829
830     if (!document())
831         return;
832
833     if (timer->targetOrigin()) {
834         // Check target origin now since the target document may have changed since the simer was scheduled.
835         if (!timer->targetOrigin()->isSameSchemeHostPort(document()->securityOrigin())) {
836             String message = makeString("Unable to post message to ", timer->targetOrigin()->toString(),
837                                         ". Recipient has origin ", document()->securityOrigin()->toString(), ".\n");
838             console()->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, message, 0, String());
839             return;
840         }
841     }
842
843     dispatchEvent(timer->event(document()));
844 }
845
846 DOMSelection* DOMWindow::getSelection()
847 {
848     if (!m_selection)
849         m_selection = DOMSelection::create(m_frame);
850     return m_selection.get();
851 }
852
853 Element* DOMWindow::frameElement() const
854 {
855     if (!m_frame)
856         return 0;
857
858     return m_frame->ownerElement();
859 }
860
861 void DOMWindow::focus()
862 {
863     if (!m_frame)
864         return;
865
866     Page* page = m_frame->page();
867     if (!page)
868         return;
869
870     // If we're a top level window, bring the window to the front.
871     if (m_frame == page->mainFrame())
872         page->chrome()->focus();
873
874     if (!m_frame)
875         return;
876
877     m_frame->eventHandler()->focusDocumentView();
878 }
879
880 void DOMWindow::blur()
881 {
882     if (!m_frame)
883         return;
884
885     Page* page = m_frame->page();
886     if (!page)
887         return;
888
889     if (m_frame != page->mainFrame())
890         return;
891
892     page->chrome()->unfocus();
893 }
894
895 void DOMWindow::close(ScriptExecutionContext* context)
896 {
897     if (!m_frame)
898         return;
899
900     Page* page = m_frame->page();
901     if (!page)
902         return;
903
904     if (m_frame != page->mainFrame())
905         return;
906
907     if (context) {
908         ASSERT(WTF::isMainThread());
909         Frame* activeFrame = static_cast<Document*>(context)->frame();
910         if (!activeFrame)
911             return;
912
913         if (!activeFrame->loader()->shouldAllowNavigation(m_frame))
914             return;
915     }
916
917     Settings* settings = m_frame->settings();
918     bool allowScriptsToCloseWindows = settings && settings->allowScriptsToCloseWindows();
919
920     if (!(page->openedByDOM() || page->backForward()->count() <= 1 || allowScriptsToCloseWindows))
921         return;
922
923     if (!m_frame->loader()->shouldClose())
924         return;
925
926     page->chrome()->closeWindowSoon();
927 }
928
929 void DOMWindow::print()
930 {
931     if (!m_frame)
932         return;
933
934     Page* page = m_frame->page();
935     if (!page)
936         return;
937
938     if (m_frame->loader()->activeDocumentLoader()->isLoading()) {
939         m_shouldPrintWhenFinishedLoading = true;
940         return;
941     }
942     m_shouldPrintWhenFinishedLoading = false;
943     page->chrome()->print(m_frame);
944 }
945
946 void DOMWindow::stop()
947 {
948     if (!m_frame)
949         return;
950
951     // We must check whether the load is complete asynchronously, because we might still be parsing
952     // the document until the callstack unwinds.
953     m_frame->loader()->stopForUserCancel(true);
954 }
955
956 void DOMWindow::alert(const String& message)
957 {
958     if (!m_frame)
959         return;
960
961     m_frame->document()->updateStyleIfNeeded();
962
963     Page* page = m_frame->page();
964     if (!page)
965         return;
966
967     page->chrome()->runJavaScriptAlert(m_frame, message);
968 }
969
970 bool DOMWindow::confirm(const String& message)
971 {
972     if (!m_frame)
973         return false;
974
975     m_frame->document()->updateStyleIfNeeded();
976
977     Page* page = m_frame->page();
978     if (!page)
979         return false;
980
981     return page->chrome()->runJavaScriptConfirm(m_frame, message);
982 }
983
984 String DOMWindow::prompt(const String& message, const String& defaultValue)
985 {
986     if (!m_frame)
987         return String();
988
989     m_frame->document()->updateStyleIfNeeded();
990
991     Page* page = m_frame->page();
992     if (!page)
993         return String();
994
995     String returnValue;
996     if (page->chrome()->runJavaScriptPrompt(m_frame, message, defaultValue, returnValue))
997         return returnValue;
998
999     return String();
1000 }
1001
1002 String DOMWindow::btoa(const String& stringToEncode, ExceptionCode& ec)
1003 {
1004     if (stringToEncode.isNull())
1005         return String();
1006
1007     if (!stringToEncode.containsOnlyLatin1()) {
1008         ec = INVALID_CHARACTER_ERR;
1009         return String();
1010     }
1011
1012     return base64Encode(stringToEncode.latin1());
1013 }
1014
1015 String DOMWindow::atob(const String& encodedString, ExceptionCode& ec)
1016 {
1017     if (encodedString.isNull())
1018         return String();
1019
1020     if (!encodedString.containsOnlyLatin1()) {
1021         ec = INVALID_CHARACTER_ERR;
1022         return String();
1023     }
1024
1025     Vector<char> out;
1026     if (!base64Decode(encodedString, out, FailOnInvalidCharacter)) {
1027         ec = INVALID_CHARACTER_ERR;
1028         return String();
1029     }
1030
1031     return String(out.data(), out.size());
1032 }
1033
1034 bool DOMWindow::find(const String& string, bool caseSensitive, bool backwards, bool wrap, bool /*wholeWord*/, bool /*searchInFrames*/, bool /*showDialog*/) const
1035 {
1036     if (!m_frame)
1037         return false;
1038
1039     // FIXME (13016): Support wholeWord, searchInFrames and showDialog
1040     return m_frame->editor()->findString(string, !backwards, caseSensitive, wrap, false);
1041 }
1042
1043 bool DOMWindow::offscreenBuffering() const
1044 {
1045     return true;
1046 }
1047
1048 int DOMWindow::outerHeight() const
1049 {
1050     if (!m_frame)
1051         return 0;
1052
1053     Page* page = m_frame->page();
1054     if (!page)
1055         return 0;
1056
1057     return static_cast<int>(page->chrome()->windowRect().height());
1058 }
1059
1060 int DOMWindow::outerWidth() const
1061 {
1062     if (!m_frame)
1063         return 0;
1064
1065     Page* page = m_frame->page();
1066     if (!page)
1067         return 0;
1068
1069     return static_cast<int>(page->chrome()->windowRect().width());
1070 }
1071
1072 int DOMWindow::innerHeight() const
1073 {
1074     if (!m_frame)
1075         return 0;
1076
1077     FrameView* view = m_frame->view();
1078     if (!view)
1079         return 0;
1080     
1081 #if PLATFORM(ANDROID)
1082     return static_cast<int>(view->actualHeight() / m_frame->pageZoomFactor());
1083 #else
1084     return static_cast<int>(view->height() / m_frame->pageZoomFactor());
1085 #endif
1086 }
1087
1088 int DOMWindow::innerWidth() const
1089 {
1090     if (!m_frame)
1091         return 0;
1092
1093     FrameView* view = m_frame->view();
1094     if (!view)
1095         return 0;
1096
1097 #if PLATFORM(ANDROID)
1098     return static_cast<int>(view->actualWidth() / m_frame->pageZoomFactor());
1099 #else
1100     return static_cast<int>(view->width() / m_frame->pageZoomFactor());
1101 #endif
1102 }
1103
1104 int DOMWindow::screenX() const
1105 {
1106     if (!m_frame)
1107         return 0;
1108
1109     Page* page = m_frame->page();
1110     if (!page)
1111         return 0;
1112
1113     return static_cast<int>(page->chrome()->windowRect().x());
1114 }
1115
1116 int DOMWindow::screenY() const
1117 {
1118     if (!m_frame)
1119         return 0;
1120
1121     Page* page = m_frame->page();
1122     if (!page)
1123         return 0;
1124
1125     return static_cast<int>(page->chrome()->windowRect().y());
1126 }
1127
1128 int DOMWindow::scrollX() const
1129 {
1130     if (!m_frame)
1131         return 0;
1132
1133     FrameView* view = m_frame->view();
1134     if (!view)
1135         return 0;
1136
1137     m_frame->document()->updateLayoutIgnorePendingStylesheets();
1138
1139 #if PLATFORM(ANDROID)
1140     return static_cast<int>(view->actualScrollX() / m_frame->pageZoomFactor());
1141 #else
1142     return static_cast<int>(view->scrollX() / m_frame->pageZoomFactor());
1143 #endif
1144 }
1145
1146 int DOMWindow::scrollY() const
1147 {
1148     if (!m_frame)
1149         return 0;
1150
1151     FrameView* view = m_frame->view();
1152     if (!view)
1153         return 0;
1154
1155     m_frame->document()->updateLayoutIgnorePendingStylesheets();
1156
1157 #if PLATFORM(ANDROID)
1158     return static_cast<int>(view->actualScrollY() / m_frame->pageZoomFactor());
1159 #else
1160     return static_cast<int>(view->scrollY() / m_frame->pageZoomFactor());
1161 #endif
1162 }
1163
1164 bool DOMWindow::closed() const
1165 {
1166     return !m_frame;
1167 }
1168
1169 unsigned DOMWindow::length() const
1170 {
1171     if (!m_frame)
1172         return 0;
1173
1174     return m_frame->tree()->childCount();
1175 }
1176
1177 String DOMWindow::name() const
1178 {
1179     if (!m_frame)
1180         return String();
1181
1182     return m_frame->tree()->name();
1183 }
1184
1185 void DOMWindow::setName(const String& string)
1186 {
1187     if (!m_frame)
1188         return;
1189
1190     m_frame->tree()->setName(string);
1191 }
1192
1193 void DOMWindow::setStatus(const String& string) 
1194 {
1195     m_status = string;
1196
1197     if (!m_frame)
1198         return;
1199
1200     Page* page = m_frame->page();
1201     if (!page)
1202         return;
1203
1204     ASSERT(m_frame->document()); // Client calls shouldn't be made when the frame is in inconsistent state.
1205     page->chrome()->setStatusbarText(m_frame, m_status);
1206
1207     
1208 void DOMWindow::setDefaultStatus(const String& string) 
1209 {
1210     m_defaultStatus = string;
1211
1212     if (!m_frame)
1213         return;
1214
1215     Page* page = m_frame->page();
1216     if (!page)
1217         return;
1218
1219     ASSERT(m_frame->document()); // Client calls shouldn't be made when the frame is in inconsistent state.
1220     page->chrome()->setStatusbarText(m_frame, m_defaultStatus);
1221 }
1222
1223 DOMWindow* DOMWindow::self() const
1224 {
1225     if (!m_frame)
1226         return 0;
1227
1228     return m_frame->domWindow();
1229 }
1230
1231 DOMWindow* DOMWindow::opener() const
1232 {
1233     if (!m_frame)
1234         return 0;
1235
1236     Frame* opener = m_frame->loader()->opener();
1237     if (!opener)
1238         return 0;
1239
1240     return opener->domWindow();
1241 }
1242
1243 DOMWindow* DOMWindow::parent() const
1244 {
1245     if (!m_frame)
1246         return 0;
1247
1248     Frame* parent = m_frame->tree()->parent(true);
1249     if (parent)
1250         return parent->domWindow();
1251
1252     return m_frame->domWindow();
1253 }
1254
1255 DOMWindow* DOMWindow::top() const
1256 {
1257     if (!m_frame)
1258         return 0;
1259
1260     Page* page = m_frame->page();
1261     if (!page)
1262         return 0;
1263
1264     return m_frame->tree()->top(true)->domWindow();
1265 }
1266
1267 Document* DOMWindow::document() const
1268 {
1269     // FIXME: This function shouldn't need a frame to work.
1270     if (!m_frame)
1271         return 0;
1272
1273     // 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.
1274     // FIXME: We should always zero out the frame pointer on navigation to avoid accidentally accessing the new frame content.
1275     if (m_frame->domWindow() != this)
1276         return 0;
1277
1278     ASSERT(m_frame->document());
1279     return m_frame->document();
1280 }
1281
1282 PassRefPtr<StyleMedia> DOMWindow::styleMedia() const
1283 {
1284     if (!m_media)
1285         m_media = StyleMedia::create(m_frame);
1286     return m_media.get();
1287 }
1288
1289 PassRefPtr<CSSStyleDeclaration> DOMWindow::getComputedStyle(Element* elt, const String& pseudoElt) const
1290 {
1291     if (!elt)
1292         return 0;
1293
1294     return computedStyle(elt, false, pseudoElt);
1295 }
1296
1297 PassRefPtr<CSSRuleList> DOMWindow::getMatchedCSSRules(Element* elt, const String&, bool authorOnly) const
1298 {
1299     if (!m_frame)
1300         return 0;
1301
1302     Settings* settings = m_frame->settings();
1303     return m_frame->document()->styleSelector()->styleRulesForElement(elt, authorOnly, false, settings && settings->crossOriginCheckInGetMatchedCSSRulesDisabled() ? AllCSSRules : SameOriginCSSRulesOnly);
1304 }
1305
1306 PassRefPtr<WebKitPoint> DOMWindow::webkitConvertPointFromNodeToPage(Node* node, const WebKitPoint* p) const
1307 {
1308     if (!node || !p)
1309         return 0;
1310
1311     m_frame->document()->updateLayoutIgnorePendingStylesheets();
1312
1313     FloatPoint pagePoint(p->x(), p->y());
1314     pagePoint = node->convertToPage(pagePoint);
1315     return WebKitPoint::create(pagePoint.x(), pagePoint.y());
1316 }
1317
1318 PassRefPtr<WebKitPoint> DOMWindow::webkitConvertPointFromPageToNode(Node* node, const WebKitPoint* p) const
1319 {
1320     if (!node || !p)
1321         return 0;
1322
1323     m_frame->document()->updateLayoutIgnorePendingStylesheets();
1324
1325     FloatPoint nodePoint(p->x(), p->y());
1326     nodePoint = node->convertFromPage(nodePoint);
1327     return WebKitPoint::create(nodePoint.x(), nodePoint.y());
1328 }
1329
1330 double DOMWindow::devicePixelRatio() const
1331 {
1332     if (!m_frame)
1333         return 0.0;
1334
1335     Page* page = m_frame->page();
1336     if (!page)
1337         return 0.0;
1338
1339     return page->chrome()->scaleFactor();
1340 }
1341
1342 #if ENABLE(DATABASE)
1343 PassRefPtr<Database> DOMWindow::openDatabase(const String& name, const String& version, const String& displayName, unsigned long estimatedSize, PassRefPtr<DatabaseCallback> creationCallback, ExceptionCode& ec)
1344 {
1345     RefPtr<Database> database = 0;
1346     if (m_frame && AbstractDatabase::isAvailable() && m_frame->document()->securityOrigin()->canAccessDatabase())
1347         database = Database::openDatabase(m_frame->document(), name, version, displayName, estimatedSize, creationCallback, ec);
1348
1349     if (!database && !ec)
1350         ec = SECURITY_ERR;
1351
1352     return database;
1353 }
1354 #endif
1355
1356 void DOMWindow::scrollBy(int x, int y) const
1357 {
1358     if (!m_frame)
1359         return;
1360
1361     m_frame->document()->updateLayoutIgnorePendingStylesheets();
1362
1363     RefPtr<FrameView> view = m_frame->view();
1364     if (!view)
1365         return;
1366
1367     view->scrollBy(IntSize(x, y));
1368 }
1369
1370 void DOMWindow::scrollTo(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     int zoomedX = static_cast<int>(x * m_frame->pageZoomFactor());
1382     int zoomedY = static_cast<int>(y * m_frame->pageZoomFactor());
1383     view->setScrollPosition(IntPoint(zoomedX, zoomedY));
1384 }
1385
1386 void DOMWindow::moveBy(float x, float y) const
1387 {
1388     if (!m_frame)
1389         return;
1390
1391     Page* page = m_frame->page();
1392     if (!page)
1393         return;
1394
1395     if (m_frame != page->mainFrame())
1396         return;
1397
1398     FloatRect fr = page->chrome()->windowRect();
1399     FloatRect update = fr;
1400     update.move(x, y);
1401     // Security check (the spec talks about UniversalBrowserWrite to disable this check...)
1402     adjustWindowRect(screenAvailableRect(page->mainFrame()->view()), fr, update);
1403     page->chrome()->setWindowRect(fr);
1404 }
1405
1406 void DOMWindow::moveTo(float x, float y) const
1407 {
1408     if (!m_frame)
1409         return;
1410
1411     Page* page = m_frame->page();
1412     if (!page)
1413         return;
1414
1415     if (m_frame != page->mainFrame())
1416         return;
1417
1418     FloatRect fr = page->chrome()->windowRect();
1419     FloatRect sr = screenAvailableRect(page->mainFrame()->view());
1420     fr.setLocation(sr.location());
1421     FloatRect update = fr;
1422     update.move(x, y);     
1423     // Security check (the spec talks about UniversalBrowserWrite to disable this check...)
1424     adjustWindowRect(sr, fr, update);
1425     page->chrome()->setWindowRect(fr);
1426 }
1427
1428 void DOMWindow::resizeBy(float x, float y) const
1429 {
1430     if (!m_frame)
1431         return;
1432
1433     Page* page = m_frame->page();
1434     if (!page)
1435         return;
1436
1437     if (m_frame != page->mainFrame())
1438         return;
1439
1440     FloatRect fr = page->chrome()->windowRect();
1441     FloatSize dest = fr.size() + FloatSize(x, y);
1442     FloatRect update(fr.location(), dest);
1443     adjustWindowRect(screenAvailableRect(page->mainFrame()->view()), fr, update);
1444     page->chrome()->setWindowRect(fr);
1445 }
1446
1447 void DOMWindow::resizeTo(float width, float height) const
1448 {
1449     if (!m_frame)
1450         return;
1451
1452     Page* page = m_frame->page();
1453     if (!page)
1454         return;
1455
1456     if (m_frame != page->mainFrame())
1457         return;
1458
1459     FloatRect fr = page->chrome()->windowRect();
1460     FloatSize dest = FloatSize(width, height);
1461     FloatRect update(fr.location(), dest);
1462     adjustWindowRect(screenAvailableRect(page->mainFrame()->view()), fr, update);
1463     page->chrome()->setWindowRect(fr);
1464 }
1465
1466 int DOMWindow::setTimeout(PassOwnPtr<ScheduledAction> action, int timeout, ExceptionCode& ec)
1467 {
1468     ScriptExecutionContext* context = scriptExecutionContext();
1469     if (!context) {
1470         ec = INVALID_ACCESS_ERR;
1471         return -1;
1472     }
1473     return DOMTimer::install(context, action, timeout, true);
1474 }
1475
1476 void DOMWindow::clearTimeout(int timeoutId)
1477 {
1478     ScriptExecutionContext* context = scriptExecutionContext();
1479     if (!context)
1480         return;
1481     DOMTimer::removeById(context, timeoutId);
1482 }
1483
1484 int DOMWindow::setInterval(PassOwnPtr<ScheduledAction> action, int timeout, ExceptionCode& ec)
1485 {
1486     ScriptExecutionContext* context = scriptExecutionContext();
1487     if (!context) {
1488         ec = INVALID_ACCESS_ERR;
1489         return -1;
1490     }
1491     return DOMTimer::install(context, action, timeout, false);
1492 }
1493
1494 void DOMWindow::clearInterval(int timeoutId)
1495 {
1496     ScriptExecutionContext* context = scriptExecutionContext();
1497     if (!context)
1498         return;
1499     DOMTimer::removeById(context, timeoutId);
1500 }
1501
1502 #if ENABLE(REQUEST_ANIMATION_FRAME)
1503 int DOMWindow::webkitRequestAnimationFrame(PassRefPtr<RequestAnimationFrameCallback> callback, Element* e)
1504 {
1505     if (Document* d = document())
1506         return d->webkitRequestAnimationFrame(callback, e);
1507     return 0;
1508 }
1509
1510 void DOMWindow::webkitCancelRequestAnimationFrame(int id)
1511 {
1512     if (Document* d = document())
1513         d->webkitCancelRequestAnimationFrame(id);
1514 }
1515 #endif
1516
1517 bool DOMWindow::addEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
1518 {
1519     if (!EventTarget::addEventListener(eventType, listener, useCapture))
1520         return false;
1521
1522     if (Document* document = this->document())
1523         document->addListenerTypeIfNeeded(eventType);
1524
1525     if (eventType == eventNames().unloadEvent)
1526         addUnloadEventListener(this);
1527     else if (eventType == eventNames().beforeunloadEvent && allowsBeforeUnloadListeners(this))
1528         addBeforeUnloadEventListener(this);
1529 #if ENABLE(DEVICE_ORIENTATION)
1530     else if (eventType == eventNames().devicemotionEvent && frame() && frame()->page() && frame()->page()->deviceMotionController())
1531         frame()->page()->deviceMotionController()->addListener(this);
1532     else if (eventType == eventNames().deviceorientationEvent && frame() && frame()->page() && frame()->page()->deviceOrientationController())
1533         frame()->page()->deviceOrientationController()->addListener(this);
1534 #endif
1535
1536     return true;
1537 }
1538
1539 bool DOMWindow::removeEventListener(const AtomicString& eventType, EventListener* listener, bool useCapture)
1540 {
1541     if (!EventTarget::removeEventListener(eventType, listener, useCapture))
1542         return false;
1543
1544     if (eventType == eventNames().unloadEvent)
1545         removeUnloadEventListener(this);
1546     else if (eventType == eventNames().beforeunloadEvent && allowsBeforeUnloadListeners(this))
1547         removeBeforeUnloadEventListener(this);
1548 #if ENABLE(DEVICE_ORIENTATION)
1549     else if (eventType == eventNames().devicemotionEvent && frame() && frame()->page() && frame()->page()->deviceMotionController())
1550         frame()->page()->deviceMotionController()->removeListener(this);
1551     else if (eventType == eventNames().deviceorientationEvent && frame() && frame()->page() && frame()->page()->deviceOrientationController())
1552         frame()->page()->deviceOrientationController()->removeListener(this);
1553 #endif
1554
1555     return true;
1556 }
1557
1558 void DOMWindow::dispatchLoadEvent()
1559 {
1560     RefPtr<Event> loadEvent(Event::create(eventNames().loadEvent, false, false));
1561     if (m_frame && m_frame->loader()->documentLoader() && !m_frame->loader()->documentLoader()->timing()->loadEventStart) {
1562         // The DocumentLoader (and thus its DocumentLoadTiming) might get destroyed while dispatching
1563         // the event, so protect it to prevent writing the end time into freed memory.
1564         RefPtr<DocumentLoader> documentLoader = m_frame->loader()->documentLoader();
1565         DocumentLoadTiming* timing = documentLoader->timing();
1566         dispatchTimedEvent(loadEvent, document(), &timing->loadEventStart, &timing->loadEventEnd);
1567     } else
1568         dispatchEvent(loadEvent, document());
1569
1570     // For load events, send a separate load event to the enclosing frame only.
1571     // This is a DOM extension and is independent of bubbling/capturing rules of
1572     // the DOM.
1573     Element* ownerElement = m_frame ? m_frame->ownerElement() : 0;
1574     if (ownerElement) {
1575         RefPtr<Event> ownerEvent = Event::create(eventNames().loadEvent, false, false);
1576         ownerEvent->setTarget(ownerElement);
1577         ownerElement->dispatchGenericEvent(ownerEvent.release());
1578     }
1579
1580     InspectorInstrumentation::loadEventFired(frame(), url());
1581 }
1582
1583 bool DOMWindow::dispatchEvent(PassRefPtr<Event> prpEvent, PassRefPtr<EventTarget> prpTarget)
1584 {
1585     RefPtr<EventTarget> protect = this;
1586     RefPtr<Event> event = prpEvent;
1587
1588     event->setTarget(prpTarget ? prpTarget : this);
1589     event->setCurrentTarget(this);
1590     event->setEventPhase(Event::AT_TARGET);
1591
1592     InspectorInstrumentationCookie cookie = InspectorInstrumentation::willDispatchEventOnWindow(frame(), *event, this);
1593
1594     bool result = fireEventListeners(event.get());
1595
1596     InspectorInstrumentation::didDispatchEventOnWindow(cookie);
1597
1598     return result;
1599 }
1600
1601 void DOMWindow::dispatchTimedEvent(PassRefPtr<Event> event, Document* target, double* startTime, double* endTime)
1602 {
1603     ASSERT(startTime);
1604     ASSERT(endTime);
1605     *startTime = currentTime();
1606     dispatchEvent(event, target);
1607     *endTime = currentTime();
1608 }
1609
1610 void DOMWindow::removeAllEventListeners()
1611 {
1612     EventTarget::removeAllEventListeners();
1613
1614 #if ENABLE(DEVICE_ORIENTATION)
1615     if (frame() && frame()->page() && frame()->page()->deviceMotionController())
1616         frame()->page()->deviceMotionController()->removeAllListeners(this);
1617     if (frame() && frame()->page() && frame()->page()->deviceOrientationController())
1618         frame()->page()->deviceOrientationController()->removeAllListeners(this);
1619 #endif
1620
1621     removeAllUnloadEventListeners(this);
1622     removeAllBeforeUnloadEventListeners(this);
1623 }
1624
1625 void DOMWindow::captureEvents()
1626 {
1627     // Not implemented.
1628 }
1629
1630 void DOMWindow::releaseEvents()
1631 {
1632     // Not implemented.
1633 }
1634
1635 void DOMWindow::finishedLoading()
1636 {
1637     if (m_shouldPrintWhenFinishedLoading) {
1638         m_shouldPrintWhenFinishedLoading = false;
1639         print();
1640     }
1641 }
1642
1643 EventTargetData* DOMWindow::eventTargetData()
1644 {
1645     return &m_eventTargetData;
1646 }
1647
1648 EventTargetData* DOMWindow::ensureEventTargetData()
1649 {
1650     return &m_eventTargetData;
1651 }
1652
1653 #if ENABLE(DOM_STORAGE) && defined(ANDROID)
1654 void DOMWindow::clearDOMStorage()
1655 {
1656     if (m_sessionStorage)
1657         m_sessionStorage->disconnectFrame();
1658     m_sessionStorage = 0;
1659
1660     if (m_localStorage)
1661         m_localStorage->disconnectFrame();
1662     m_localStorage = 0;
1663 }
1664 #endif
1665
1666 void DOMWindow::setLocation(const String& urlString, DOMWindow* activeWindow, DOMWindow* firstWindow, SetLocationLocking locking)
1667 {
1668     if (!m_frame)
1669         return;
1670
1671     Frame* activeFrame = activeWindow->frame();
1672     if (!activeFrame)
1673         return;
1674
1675     if (!activeFrame->loader()->shouldAllowNavigation(m_frame))
1676         return;
1677
1678     Frame* firstFrame = firstWindow->frame();
1679     if (!firstFrame)
1680         return;
1681
1682     KURL completedURL = firstFrame->document()->completeURL(urlString);
1683     if (completedURL.isNull())
1684         return;
1685
1686     if (isInsecureScriptAccess(activeWindow, urlString))
1687         return;
1688
1689     // We want a new history item if we are processing a user gesture.
1690     m_frame->navigationScheduler()->scheduleLocationChange(activeFrame->document()->securityOrigin(),
1691         completedURL, activeFrame->loader()->outgoingReferrer(),
1692         locking != LockHistoryBasedOnGestureState || !activeFrame->script()->anyPageIsProcessingUserGesture(),
1693         locking != LockHistoryBasedOnGestureState);
1694 }
1695
1696 void DOMWindow::printErrorMessage(const String& message)
1697 {
1698     if (message.isEmpty())
1699         return;
1700
1701     Settings* settings = m_frame->settings();
1702     if (!settings)
1703         return;
1704     if (settings->privateBrowsingEnabled())
1705         return;
1706
1707     // FIXME: Add arguments so that we can provide a correct source URL and line number.
1708     console()->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, message, 1, String());
1709 }
1710
1711 String DOMWindow::crossDomainAccessErrorMessage(DOMWindow* activeWindow)
1712 {
1713     const KURL& activeWindowURL = activeWindow->url();
1714     if (activeWindowURL.isNull())
1715         return String();
1716
1717     // FIXME: This error message should contain more specifics of why the same origin check has failed.
1718     // Perhaps we should involve the security origin object in composing it.
1719     // FIXME: This message, and other console messages, have extra newlines. Should remove them.
1720     return makeString("Unsafe JavaScript attempt to access frame with URL ", m_url.string(),
1721         " from frame with URL ", activeWindowURL.string(), ". Domains, protocols and ports must match.\n");
1722 }
1723
1724 bool DOMWindow::isInsecureScriptAccess(DOMWindow* activeWindow, const String& urlString)
1725 {
1726     if (!protocolIsJavaScript(urlString))
1727         return false;
1728
1729     // FIXME: Is there some way to eliminate the need for a separate "activeWindow == this" check?
1730     if (activeWindow == this)
1731         return false;
1732
1733     // FIXME: The name canAccess seems to be a roundabout way to ask "can execute script".
1734     // Can we name the SecurityOrigin function better to make this more clear?
1735     if (activeWindow->securityOrigin()->canAccess(securityOrigin()))
1736         return false;
1737
1738     printErrorMessage(crossDomainAccessErrorMessage(activeWindow));
1739     return true;
1740 }
1741
1742 Frame* DOMWindow::createWindow(const String& urlString, const AtomicString& frameName, const WindowFeatures& windowFeatures,
1743     DOMWindow* activeWindow, Frame* firstFrame, Frame* openerFrame, PrepareDialogFunction function, void* functionContext)
1744 {
1745     Frame* activeFrame = activeWindow->frame();
1746
1747     // For whatever reason, Firefox uses the first frame to determine the outgoingReferrer. We replicate that behavior here.
1748     String referrer = firstFrame->loader()->outgoingReferrer();
1749
1750     KURL completedURL = urlString.isEmpty() ? KURL(ParsedURLString, "") : firstFrame->document()->completeURL(urlString);
1751     ResourceRequest request(completedURL, referrer);
1752     FrameLoader::addHTTPOriginIfNeeded(request, firstFrame->loader()->outgoingOrigin());
1753     FrameLoadRequest frameRequest(activeWindow->securityOrigin(), request, frameName);
1754
1755     // We pass the opener frame for the lookupFrame in case the active frame is different from
1756     // the opener frame, and the name references a frame relative to the opener frame.
1757     bool created;
1758     Frame* newFrame = WebCore::createWindow(activeFrame, openerFrame, frameRequest, windowFeatures, created);
1759     if (!newFrame)
1760         return 0;
1761
1762     newFrame->loader()->setOpener(openerFrame);
1763     newFrame->page()->setOpenedByDOM();
1764
1765     if (newFrame->domWindow()->isInsecureScriptAccess(activeWindow, urlString))
1766         return newFrame;
1767
1768     if (function)
1769         function(newFrame->domWindow(), functionContext);
1770
1771     if (created)
1772         newFrame->loader()->changeLocation(activeWindow->securityOrigin(), completedURL, referrer, false, false);
1773     else if (!urlString.isEmpty()) {
1774         newFrame->navigationScheduler()->scheduleLocationChange(activeWindow->securityOrigin(), completedURL.string(), referrer,
1775             !activeFrame->script()->anyPageIsProcessingUserGesture(), false);
1776     }
1777
1778     return newFrame;
1779 }
1780
1781 PassRefPtr<DOMWindow> DOMWindow::open(const String& urlString, const AtomicString& frameName, const String& windowFeaturesString,
1782     DOMWindow* activeWindow, DOMWindow* firstWindow)
1783 {
1784     if (!m_frame)
1785         return 0;
1786     Frame* activeFrame = activeWindow->frame();
1787     if (!activeFrame)
1788         return 0;
1789     Frame* firstFrame = firstWindow->frame();
1790     if (!firstFrame)
1791         return 0;
1792
1793     if (!firstWindow->allowPopUp()) {
1794         // Because FrameTree::find() returns true for empty strings, we must check for empty frame names.
1795         // Otherwise, illegitimate window.open() calls with no name will pass right through the popup blocker.
1796         if (frameName.isEmpty() || !m_frame->tree()->find(frameName))
1797             return 0;
1798     }
1799
1800     // Get the target frame for the special cases of _top and _parent.
1801     // In those cases, we schedule a location change right now and return early.
1802     Frame* targetFrame = 0;
1803     if (frameName == "_top")
1804         targetFrame = m_frame->tree()->top();
1805     else if (frameName == "_parent") {
1806         if (Frame* parent = m_frame->tree()->parent())
1807             targetFrame = parent;
1808         else
1809             targetFrame = m_frame;
1810     }
1811     if (targetFrame) {
1812         if (!activeFrame->loader()->shouldAllowNavigation(targetFrame))
1813             return 0;
1814
1815         if (isInsecureScriptAccess(activeWindow, urlString))
1816             return targetFrame->domWindow();
1817
1818         if (urlString.isEmpty())
1819             return targetFrame->domWindow();
1820
1821         // For whatever reason, Firefox uses the first window rather than the active window to
1822         // determine the outgoing referrer. We replicate that behavior here.
1823         targetFrame->navigationScheduler()->scheduleLocationChange(activeFrame->document()->securityOrigin(),
1824             firstFrame->document()->completeURL(urlString).string(),
1825             firstFrame->loader()->outgoingReferrer(),
1826             !activeFrame->script()->anyPageIsProcessingUserGesture(), false);
1827
1828         return targetFrame->domWindow();
1829     }
1830
1831     WindowFeatures windowFeatures(windowFeaturesString);
1832     FloatRect windowRect(windowFeatures.xSet ? windowFeatures.x : 0, windowFeatures.ySet ? windowFeatures.y : 0,
1833         windowFeatures.widthSet ? windowFeatures.width : 0, windowFeatures.heightSet ? windowFeatures.height : 0);
1834     Page* page = m_frame->page();
1835     DOMWindow::adjustWindowRect(screenAvailableRect(page ? page->mainFrame()->view() : 0), windowRect, windowRect);
1836     windowFeatures.x = windowRect.x();
1837     windowFeatures.y = windowRect.y();
1838     windowFeatures.height = windowRect.height();
1839     windowFeatures.width = windowRect.width();
1840
1841     Frame* result = createWindow(urlString, frameName, windowFeatures, activeWindow, firstFrame, m_frame);
1842     return result ? result->domWindow() : 0;
1843 }
1844
1845 void DOMWindow::showModalDialog(const String& urlString, const String& dialogFeaturesString,
1846     DOMWindow* activeWindow, DOMWindow* firstWindow, PrepareDialogFunction function, void* functionContext)
1847 {
1848     if (!m_frame)
1849         return;
1850     Frame* activeFrame = activeWindow->frame();
1851     if (!activeFrame)
1852         return;
1853     Frame* firstFrame = firstWindow->frame();
1854     if (!firstFrame)
1855         return;
1856
1857     if (!canShowModalDialogNow(m_frame) || !firstWindow->allowPopUp())
1858         return;
1859
1860     Frame* dialogFrame = createWindow(urlString, emptyAtom, WindowFeatures(dialogFeaturesString, screenAvailableRect(m_frame->view())),
1861         activeWindow, firstFrame, m_frame, function, functionContext);
1862     if (!dialogFrame)
1863         return;
1864
1865     dialogFrame->page()->chrome()->runModal();
1866 }
1867
1868 #if ENABLE(BLOB)
1869 DOMURL* DOMWindow::webkitURL() const
1870 {
1871     if (!m_domURL)
1872         m_domURL = DOMURL::create(this->scriptExecutionContext());
1873     return m_domURL.get();
1874 }
1875 #endif
1876
1877 } // namespace WebCore