OSDN Git Service

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