OSDN Git Service

Merge WebKit at r75315: Fix conflicts
[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 "Database.h"
47 #include "DatabaseCallback.h"
48 #include "DeviceMotionController.h"
49 #include "DeviceOrientationController.h"
50 #include "Document.h"
51 #include "DocumentLoader.h"
52 #include "Element.h"
53 #include "EventException.h"
54 #include "EventListener.h"
55 #include "EventNames.h"
56 #include "ExceptionCode.h"
57 #include "FloatRect.h"
58 #include "Frame.h"
59 #include "FrameLoadRequest.h"
60 #include "FrameLoader.h"
61 #include "FrameTree.h"
62 #include "FrameView.h"
63 #include "HTMLFrameOwnerElement.h"
64 #include "History.h"
65 #include "IDBFactory.h"
66 #include "IDBFactoryBackendInterface.h"
67 #include "InspectorController.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 using std::min;
109 using std::max;
110
111 namespace WebCore {
112
113 class PostMessageTimer : public TimerBase {
114 public:
115     PostMessageTimer(DOMWindow* window, PassRefPtr<SerializedScriptValue> message, const String& sourceOrigin, PassRefPtr<DOMWindow> source, PassOwnPtr<MessagePortChannelArray> channels, SecurityOrigin* targetOrigin)
116         : m_window(window)
117         , m_message(message)
118         , m_origin(sourceOrigin)
119         , m_source(source)
120         , m_channels(channels)
121         , m_targetOrigin(targetOrigin)
122     {
123     }
124
125     PassRefPtr<MessageEvent> event(ScriptExecutionContext* context)
126     {
127         OwnPtr<MessagePortArray> messagePorts = MessagePort::entanglePorts(*context, m_channels.release());
128         return MessageEvent::create(messagePorts.release(), m_message, m_origin, "", m_source);
129     }
130     SecurityOrigin* targetOrigin() const { return m_targetOrigin.get(); }
131
132 private:
133     virtual void fired()
134     {
135         m_window->postMessageTimerFired(this);
136     }
137
138     RefPtr<DOMWindow> m_window;
139     RefPtr<SerializedScriptValue> m_message;
140     String m_origin;
141     RefPtr<DOMWindow> m_source;
142     OwnPtr<MessagePortChannelArray> m_channels;
143     RefPtr<SecurityOrigin> m_targetOrigin;
144 };
145
146 typedef HashCountedSet<DOMWindow*> DOMWindowSet;
147
148 static DOMWindowSet& windowsWithUnloadEventListeners()
149 {
150     DEFINE_STATIC_LOCAL(DOMWindowSet, windowsWithUnloadEventListeners, ());
151     return windowsWithUnloadEventListeners;
152 }
153
154 static DOMWindowSet& windowsWithBeforeUnloadEventListeners()
155 {
156     DEFINE_STATIC_LOCAL(DOMWindowSet, windowsWithBeforeUnloadEventListeners, ());
157     return windowsWithBeforeUnloadEventListeners;
158 }
159
160 static void addUnloadEventListener(DOMWindow* domWindow)
161 {
162     DOMWindowSet& set = windowsWithUnloadEventListeners();
163     if (set.isEmpty())
164         disableSuddenTermination();
165     set.add(domWindow);
166 }
167
168 static void removeUnloadEventListener(DOMWindow* domWindow)
169 {
170     DOMWindowSet& set = windowsWithUnloadEventListeners();
171     DOMWindowSet::iterator it = set.find(domWindow);
172     if (it == set.end())
173         return;
174     set.remove(it);
175     if (set.isEmpty())
176         enableSuddenTermination();
177 }
178
179 static void removeAllUnloadEventListeners(DOMWindow* domWindow)
180 {
181     DOMWindowSet& set = windowsWithUnloadEventListeners();
182     DOMWindowSet::iterator it = set.find(domWindow);
183     if (it == set.end())
184         return;
185     set.removeAll(it);
186     if (set.isEmpty())
187         enableSuddenTermination();
188 }
189
190 static void addBeforeUnloadEventListener(DOMWindow* domWindow)
191 {
192     DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
193     if (set.isEmpty())
194         disableSuddenTermination();
195     set.add(domWindow);
196 }
197
198 static void removeBeforeUnloadEventListener(DOMWindow* domWindow)
199 {
200     DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
201     DOMWindowSet::iterator it = set.find(domWindow);
202     if (it == set.end())
203         return;
204     set.remove(it);
205     if (set.isEmpty())
206         enableSuddenTermination();
207 }
208
209 static void removeAllBeforeUnloadEventListeners(DOMWindow* domWindow)
210 {
211     DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
212     DOMWindowSet::iterator it = set.find(domWindow);
213     if (it == set.end())
214         return;
215     set.removeAll(it);
216     if (set.isEmpty())
217         enableSuddenTermination();
218 }
219
220 static bool allowsBeforeUnloadListeners(DOMWindow* window)
221 {
222     ASSERT_ARG(window, window);
223     Frame* frame = window->frame();
224     if (!frame)
225         return false;
226     Page* page = frame->page();
227     if (!page)
228         return false;
229     return frame == page->mainFrame();
230 }
231
232 bool DOMWindow::dispatchAllPendingBeforeUnloadEvents()
233 {
234     DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
235     if (set.isEmpty())
236         return true;
237
238     static bool alreadyDispatched = false;
239     ASSERT(!alreadyDispatched);
240     if (alreadyDispatched)
241         return true;
242
243     Vector<RefPtr<DOMWindow> > windows;
244     DOMWindowSet::iterator end = set.end();
245     for (DOMWindowSet::iterator it = set.begin(); it != end; ++it)
246         windows.append(it->first);
247
248     size_t size = windows.size();
249     for (size_t i = 0; i < size; ++i) {
250         DOMWindow* window = windows[i].get();
251         if (!set.contains(window))
252             continue;
253
254         Frame* frame = window->frame();
255         if (!frame)
256             continue;
257
258         if (!frame->loader()->shouldClose())
259             return false;
260     }
261
262     enableSuddenTermination();
263
264     alreadyDispatched = true;
265
266     return true;
267 }
268
269 unsigned DOMWindow::pendingUnloadEventListeners() const
270 {
271     return windowsWithUnloadEventListeners().count(const_cast<DOMWindow*>(this));
272 }
273
274 void DOMWindow::dispatchAllPendingUnloadEvents()
275 {
276     DOMWindowSet& set = windowsWithUnloadEventListeners();
277     if (set.isEmpty())
278         return;
279
280     static bool alreadyDispatched = false;
281     ASSERT(!alreadyDispatched);
282     if (alreadyDispatched)
283         return;
284
285     Vector<RefPtr<DOMWindow> > windows;
286     DOMWindowSet::iterator end = set.end();
287     for (DOMWindowSet::iterator it = set.begin(); it != end; ++it)
288         windows.append(it->first);
289
290     size_t size = windows.size();
291     for (size_t i = 0; i < size; ++i) {
292         DOMWindow* window = windows[i].get();
293         if (!set.contains(window))
294             continue;
295
296         window->dispatchEvent(PageTransitionEvent::create(eventNames().pagehideEvent, false), window->document());
297         window->dispatchEvent(Event::create(eventNames().unloadEvent, false, false), window->document());
298     }
299
300     enableSuddenTermination();
301
302     alreadyDispatched = true;
303 }
304
305 // This function:
306 // 1) Validates the pending changes are not changing to NaN
307 // 2) Constrains the window rect to no smaller than 100 in each dimension and no
308 //    bigger than the the float rect's dimensions.
309 // 3) Constrain window rect to within the top and left boundaries of the screen rect
310 // 4) Constraint the window rect to within the bottom and right boundaries of the
311 //    screen rect.
312 // 5) Translate the window rect coordinates to be within the coordinate space of
313 //    the screen rect.
314 void DOMWindow::adjustWindowRect(const FloatRect& screen, FloatRect& window, const FloatRect& pendingChanges)
315 {
316     // Make sure we're in a valid state before adjusting dimensions.
317     ASSERT(isfinite(screen.x()));
318     ASSERT(isfinite(screen.y()));
319     ASSERT(isfinite(screen.width()));
320     ASSERT(isfinite(screen.height()));
321     ASSERT(isfinite(window.x()));
322     ASSERT(isfinite(window.y()));
323     ASSERT(isfinite(window.width()));
324     ASSERT(isfinite(window.height()));
325     
326     // Update window values if new requested values are not NaN.
327     if (!isnan(pendingChanges.x()))
328         window.setX(pendingChanges.x());
329     if (!isnan(pendingChanges.y()))
330         window.setY(pendingChanges.y());
331     if (!isnan(pendingChanges.width()))
332         window.setWidth(pendingChanges.width());
333     if (!isnan(pendingChanges.height()))
334         window.setHeight(pendingChanges.height());
335     
336     // Resize the window to between 100 and the screen width and height.
337     window.setWidth(min(max(100.0f, window.width()), screen.width()));
338     window.setHeight(min(max(100.0f, window.height()), screen.height()));
339     
340     // Constrain the window position to the screen.
341     window.setX(max(screen.x(), min(window.x(), screen.right() - window.width())));
342     window.setY(max(screen.y(), min(window.y(), screen.bottom() - window.height())));
343 }
344
345 // FIXME: We can remove this function once V8 showModalDialog is changed to use DOMWindow.
346 void DOMWindow::parseModalDialogFeatures(const String& string, HashMap<String, String>& map)
347 {
348     WindowFeatures::parseDialogFeatures(string, map);
349 }
350
351 bool DOMWindow::allowPopUp(Frame* firstFrame)
352 {
353     ASSERT(firstFrame);
354
355     if (ScriptController::processingUserGesture())
356         return true;
357
358     Settings* settings = firstFrame->settings();
359     return settings && settings->javaScriptCanOpenWindowsAutomatically();
360 }
361
362 bool DOMWindow::allowPopUp()
363 {
364     return m_frame && allowPopUp(m_frame);
365 }
366
367 bool DOMWindow::canShowModalDialog(const Frame* frame)
368 {
369     if (!frame)
370         return false;
371     Page* page = frame->page();
372     if (!page)
373         return false;
374     return page->chrome()->canRunModal();
375 }
376
377 bool DOMWindow::canShowModalDialogNow(const Frame* frame)
378 {
379     if (!frame)
380         return false;
381     Page* page = frame->page();
382     if (!page)
383         return false;
384     return page->chrome()->canRunModalNow();
385 }
386
387 DOMWindow::DOMWindow(Frame* frame)
388     : m_shouldPrintWhenFinishedLoading(false)
389     , m_frame(frame)
390 {
391 }
392
393 DOMWindow::~DOMWindow()
394 {
395     if (m_frame)
396         m_frame->clearFormerDOMWindow(this);
397
398     removeAllUnloadEventListeners(this);
399     removeAllBeforeUnloadEventListeners(this);
400 }
401
402 ScriptExecutionContext* DOMWindow::scriptExecutionContext() const
403 {
404     return document();
405 }
406
407 PassRefPtr<MediaQueryList> DOMWindow::matchMedia(const String& media)
408 {
409     return document() ? document()->mediaQueryMatcher()->matchMedia(media) : 0;
410 }
411
412 void DOMWindow::disconnectFrame()
413 {
414     m_frame = 0;
415     clear();
416 }
417
418 void DOMWindow::clear()
419 {
420     if (m_screen)
421         m_screen->disconnectFrame();
422     m_screen = 0;
423
424     if (m_selection)
425         m_selection->disconnectFrame();
426     m_selection = 0;
427
428     if (m_history)
429         m_history->disconnectFrame();
430     m_history = 0;
431
432     if (m_locationbar)
433         m_locationbar->disconnectFrame();
434     m_locationbar = 0;
435
436     if (m_menubar)
437         m_menubar->disconnectFrame();
438     m_menubar = 0;
439
440     if (m_personalbar)
441         m_personalbar->disconnectFrame();
442     m_personalbar = 0;
443
444     if (m_scrollbars)
445         m_scrollbars->disconnectFrame();
446     m_scrollbars = 0;
447
448     if (m_statusbar)
449         m_statusbar->disconnectFrame();
450     m_statusbar = 0;
451
452     if (m_toolbar)
453         m_toolbar->disconnectFrame();
454     m_toolbar = 0;
455
456     if (m_console)
457         m_console->disconnectFrame();
458     m_console = 0;
459
460     if (m_navigator)
461         m_navigator->disconnectFrame();
462     m_navigator = 0;
463
464 #if ENABLE(WEB_TIMING)
465     if (m_performance)
466         m_performance->disconnectFrame();
467     m_performance = 0;
468 #endif
469
470     if (m_location)
471         m_location->disconnectFrame();
472     m_location = 0;
473
474     if (m_media)
475         m_media->disconnectFrame();
476     m_media = 0;
477     
478 #if ENABLE(DOM_STORAGE)
479     if (m_sessionStorage)
480         m_sessionStorage->disconnectFrame();
481     m_sessionStorage = 0;
482
483     if (m_localStorage)
484         m_localStorage->disconnectFrame();
485     m_localStorage = 0;
486 #endif
487
488 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
489     if (m_applicationCache)
490         m_applicationCache->disconnectFrame();
491     m_applicationCache = 0;
492 #endif
493
494 #if ENABLE(NOTIFICATIONS)
495     if (m_notifications)
496         m_notifications->disconnectFrame();
497     m_notifications = 0;
498 #endif
499
500 #if ENABLE(INDEXED_DATABASE)
501     m_idbFactory = 0;
502 #endif
503 }
504
505 #if ENABLE(ORIENTATION_EVENTS)
506 int DOMWindow::orientation() const
507 {
508     if (!m_frame)
509         return 0;
510     
511     return m_frame->orientation();
512 }
513 #endif
514
515 Screen* DOMWindow::screen() const
516 {
517     if (!m_screen)
518         m_screen = Screen::create(m_frame);
519     return m_screen.get();
520 }
521
522 History* DOMWindow::history() const
523 {
524     if (!m_history)
525         m_history = History::create(m_frame);
526     return m_history.get();
527 }
528
529 BarInfo* DOMWindow::locationbar() const
530 {
531     if (!m_locationbar)
532         m_locationbar = BarInfo::create(m_frame, BarInfo::Locationbar);
533     return m_locationbar.get();
534 }
535
536 BarInfo* DOMWindow::menubar() const
537 {
538     if (!m_menubar)
539         m_menubar = BarInfo::create(m_frame, BarInfo::Menubar);
540     return m_menubar.get();
541 }
542
543 BarInfo* DOMWindow::personalbar() const
544 {
545     if (!m_personalbar)
546         m_personalbar = BarInfo::create(m_frame, BarInfo::Personalbar);
547     return m_personalbar.get();
548 }
549
550 BarInfo* DOMWindow::scrollbars() const
551 {
552     if (!m_scrollbars)
553         m_scrollbars = BarInfo::create(m_frame, BarInfo::Scrollbars);
554     return m_scrollbars.get();
555 }
556
557 BarInfo* DOMWindow::statusbar() const
558 {
559     if (!m_statusbar)
560         m_statusbar = BarInfo::create(m_frame, BarInfo::Statusbar);
561     return m_statusbar.get();
562 }
563
564 BarInfo* DOMWindow::toolbar() const
565 {
566     if (!m_toolbar)
567         m_toolbar = BarInfo::create(m_frame, BarInfo::Toolbar);
568     return m_toolbar.get();
569 }
570
571 Console* DOMWindow::console() const
572 {
573     if (!m_console)
574         m_console = Console::create(m_frame);
575     return m_console.get();
576 }
577
578 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
579 DOMApplicationCache* DOMWindow::applicationCache() const
580 {
581     if (!m_applicationCache)
582         m_applicationCache = DOMApplicationCache::create(m_frame);
583     return m_applicationCache.get();
584 }
585 #endif
586
587 Navigator* DOMWindow::navigator() const
588 {
589     if (!m_navigator)
590         m_navigator = Navigator::create(m_frame);
591     return m_navigator.get();
592 }
593
594 #if ENABLE(WEB_TIMING)
595 Performance* DOMWindow::performance() const
596 {
597     if (!m_performance)
598         m_performance = Performance::create(m_frame);
599     return m_performance.get();
600 }
601 #endif
602
603 Location* DOMWindow::location() const
604 {
605     if (!m_location)
606         m_location = Location::create(m_frame);
607     return m_location.get();
608 }
609
610 #if ENABLE(DOM_STORAGE)
611 Storage* DOMWindow::sessionStorage(ExceptionCode& ec) const
612 {
613     if (m_sessionStorage)
614         return m_sessionStorage.get();
615
616     Document* document = this->document();
617     if (!document)
618         return 0;
619
620     if (!document->securityOrigin()->canAccessLocalStorage()) {
621         ec = SECURITY_ERR;
622         return 0;
623     }
624
625     Page* page = document->page();
626     if (!page)
627         return 0;
628
629     RefPtr<StorageArea> storageArea = page->sessionStorage()->storageArea(document->securityOrigin());
630 #if ENABLE(INSPECTOR)
631     page->inspectorController()->didUseDOMStorage(storageArea.get(), false, m_frame);
632 #endif
633
634     m_sessionStorage = Storage::create(m_frame, storageArea.release());
635     return m_sessionStorage.get();
636 }
637
638 Storage* DOMWindow::localStorage(ExceptionCode& ec) const
639 {
640     if (m_localStorage)
641         return m_localStorage.get();
642
643     Document* document = this->document();
644     if (!document)
645         return 0;
646
647     if (!document->securityOrigin()->canAccessLocalStorage()) {
648         ec = SECURITY_ERR;
649         return 0;
650     }
651
652     Page* page = document->page();
653     if (!page)
654         return 0;
655
656     if (!page->settings()->localStorageEnabled())
657         return 0;
658
659     RefPtr<StorageArea> storageArea = page->group().localStorage()->storageArea(document->securityOrigin());
660 #if ENABLE(INSPECTOR)
661     page->inspectorController()->didUseDOMStorage(storageArea.get(), true, m_frame);
662 #endif
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     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 bool DOMWindow::addEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
1484 {
1485     if (!EventTarget::addEventListener(eventType, listener, useCapture))
1486         return false;
1487
1488     if (Document* document = this->document())
1489         document->addListenerTypeIfNeeded(eventType);
1490
1491     if (eventType == eventNames().unloadEvent)
1492         addUnloadEventListener(this);
1493     else if (eventType == eventNames().beforeunloadEvent && allowsBeforeUnloadListeners(this))
1494         addBeforeUnloadEventListener(this);
1495 #if ENABLE(DEVICE_ORIENTATION)
1496     else if (eventType == eventNames().devicemotionEvent && frame() && frame()->page() && frame()->page()->deviceMotionController())
1497         frame()->page()->deviceMotionController()->addListener(this);
1498     else if (eventType == eventNames().deviceorientationEvent && frame() && frame()->page() && frame()->page()->deviceOrientationController())
1499         frame()->page()->deviceOrientationController()->addListener(this);
1500 #endif
1501
1502     return true;
1503 }
1504
1505 bool DOMWindow::removeEventListener(const AtomicString& eventType, EventListener* listener, bool useCapture)
1506 {
1507     if (!EventTarget::removeEventListener(eventType, listener, useCapture))
1508         return false;
1509
1510     if (eventType == eventNames().unloadEvent)
1511         removeUnloadEventListener(this);
1512     else if (eventType == eventNames().beforeunloadEvent && allowsBeforeUnloadListeners(this))
1513         removeBeforeUnloadEventListener(this);
1514 #if ENABLE(DEVICE_ORIENTATION)
1515     else if (eventType == eventNames().devicemotionEvent && frame() && frame()->page() && frame()->page()->deviceMotionController())
1516         frame()->page()->deviceMotionController()->removeListener(this);
1517     else if (eventType == eventNames().deviceorientationEvent && frame() && frame()->page() && frame()->page()->deviceOrientationController())
1518         frame()->page()->deviceOrientationController()->removeListener(this);
1519 #endif
1520
1521     return true;
1522 }
1523
1524 void DOMWindow::dispatchLoadEvent()
1525 {
1526     RefPtr<Event> loadEvent(Event::create(eventNames().loadEvent, false, false));
1527     // The DocumentLoader (and thus its DocumentLoadTiming) might get destroyed while dispatching
1528     // the event, so protect it to prevent writing the end time into freed memory.
1529     if (RefPtr<DocumentLoader> documentLoader = m_frame ? m_frame->loader()->documentLoader() : 0) {
1530         DocumentLoadTiming* timing = documentLoader->timing();
1531         dispatchTimedEvent(loadEvent, document(), &timing->loadEventStart, &timing->loadEventEnd);
1532     } else
1533         dispatchEvent(loadEvent, document());
1534
1535     // For load events, send a separate load event to the enclosing frame only.
1536     // This is a DOM extension and is independent of bubbling/capturing rules of
1537     // the DOM.
1538     Element* ownerElement = document()->ownerElement();
1539     if (ownerElement) {
1540         RefPtr<Event> ownerEvent = Event::create(eventNames().loadEvent, false, false);
1541         ownerEvent->setTarget(ownerElement);
1542         ownerElement->dispatchGenericEvent(ownerEvent.release());
1543     }
1544
1545 #if ENABLE(INSPECTOR)
1546     if (!frame() || !frame()->page())
1547         return;
1548
1549     if (InspectorController* controller = frame()->page()->inspectorController())
1550         controller->mainResourceFiredLoadEvent(frame()->loader()->documentLoader(), url());
1551 #endif
1552 }
1553
1554 bool DOMWindow::dispatchEvent(PassRefPtr<Event> prpEvent, PassRefPtr<EventTarget> prpTarget)
1555 {
1556     RefPtr<EventTarget> protect = this;
1557     RefPtr<Event> event = prpEvent;
1558
1559     event->setTarget(prpTarget ? prpTarget : this);
1560     event->setCurrentTarget(this);
1561     event->setEventPhase(Event::AT_TARGET);
1562
1563     InspectorInstrumentationCookie cookie = InspectorInstrumentation::willDispatchEventOnWindow(frame(), *event, this);
1564
1565     bool result = fireEventListeners(event.get());
1566
1567     InspectorInstrumentation::didDispatchEventOnWindow(cookie);
1568
1569     return result;
1570 }
1571
1572 void DOMWindow::dispatchTimedEvent(PassRefPtr<Event> event, Document* target, double* startTime, double* endTime)
1573 {
1574     ASSERT(startTime);
1575     ASSERT(endTime);
1576     *startTime = currentTime();
1577     dispatchEvent(event, target);
1578     *endTime = currentTime();
1579     ASSERT(*endTime >= *startTime);
1580 }
1581
1582 void DOMWindow::removeAllEventListeners()
1583 {
1584     EventTarget::removeAllEventListeners();
1585
1586 #if ENABLE(DEVICE_ORIENTATION)
1587     if (frame() && frame()->page() && frame()->page()->deviceMotionController())
1588         frame()->page()->deviceMotionController()->removeAllListeners(this);
1589     if (frame() && frame()->page() && frame()->page()->deviceOrientationController())
1590         frame()->page()->deviceOrientationController()->removeAllListeners(this);
1591 #endif
1592
1593     removeAllUnloadEventListeners(this);
1594     removeAllBeforeUnloadEventListeners(this);
1595 }
1596
1597 void DOMWindow::captureEvents()
1598 {
1599     // Not implemented.
1600 }
1601
1602 void DOMWindow::releaseEvents()
1603 {
1604     // Not implemented.
1605 }
1606
1607 void DOMWindow::finishedLoading()
1608 {
1609     if (m_shouldPrintWhenFinishedLoading) {
1610         m_shouldPrintWhenFinishedLoading = false;
1611         print();
1612     }
1613 }
1614
1615 EventTargetData* DOMWindow::eventTargetData()
1616 {
1617     return &m_eventTargetData;
1618 }
1619
1620 EventTargetData* DOMWindow::ensureEventTargetData()
1621 {
1622     return &m_eventTargetData;
1623 }
1624
1625 #if ENABLE(BLOB)
1626 String DOMWindow::createObjectURL(Blob* blob)
1627 {
1628     return scriptExecutionContext()->createPublicBlobURL(blob).string();
1629 }
1630
1631 void DOMWindow::revokeObjectURL(const String& blobURLString)
1632 {
1633     scriptExecutionContext()->revokePublicBlobURL(KURL(KURL(), blobURLString));
1634 }
1635 #endif
1636
1637 #if ENABLE(DOM_STORAGE) && defined(ANDROID)
1638 void DOMWindow::clearDOMStorage()
1639 {
1640     if (m_sessionStorage)
1641         m_sessionStorage->disconnectFrame();
1642     m_sessionStorage = 0;
1643
1644     if (m_localStorage)
1645         m_localStorage->disconnectFrame();
1646     m_localStorage = 0;
1647 }
1648 #endif
1649
1650 void DOMWindow::setLocation(const String& urlString, DOMWindow* activeWindow, DOMWindow* firstWindow, SetLocationLocking locking)
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     // FIXME: It's much better for client API if a new window starts with a URL, here where we
1729     // know what URL we are going to open. Unfortunately, this code passes the empty string
1730     // for the URL, but there's a reason for that. Before loading we have to set up the opener,
1731     // openedByDOM, and dialogArguments values. Also, to decide whether to use the URL we currently
1732     // do an isInsecureScriptAccess call using the window we create, which can't be done before
1733     // creating it. We'd have to resolve all those issues to pass the URL instead of an empty string.
1734
1735     // For whatever reason, Firefox uses the first frame to determine the outgoingReferrer. We replicate that behavior here.
1736     String referrer = firstFrame->loader()->outgoingReferrer();
1737
1738     ResourceRequest request(KURL(), referrer);
1739     FrameLoader::addHTTPOriginIfNeeded(request, firstFrame->loader()->outgoingOrigin());
1740     FrameLoadRequest frameRequest(activeWindow->securityOrigin(), request, frameName);
1741
1742     // We pass the opener frame for the lookupFrame in case the active frame is different from
1743     // the opener frame, and the name references a frame relative to the opener frame.
1744     bool created;
1745     Frame* newFrame = WebCore::createWindow(activeFrame, openerFrame, frameRequest, windowFeatures, created);
1746     if (!newFrame)
1747         return 0;
1748
1749     newFrame->loader()->setOpener(openerFrame);
1750     newFrame->page()->setOpenedByDOM();
1751
1752     if (newFrame->domWindow()->isInsecureScriptAccess(activeWindow, urlString))
1753         return newFrame;
1754
1755     if (function)
1756         function(newFrame->domWindow(), functionContext);
1757
1758     KURL completedURL = urlString.isEmpty() ? KURL(ParsedURLString, "") : firstFrame->document()->completeURL(urlString);
1759
1760     if (created)
1761         newFrame->loader()->changeLocation(activeWindow->securityOrigin(), completedURL, referrer, false, false);
1762     else if (!urlString.isEmpty()) {
1763         newFrame->navigationScheduler()->scheduleLocationChange(activeWindow->securityOrigin(), completedURL.string(), referrer,
1764             !activeFrame->script()->anyPageIsProcessingUserGesture(), false);
1765     }
1766
1767     return newFrame;
1768 }
1769
1770 PassRefPtr<DOMWindow> DOMWindow::open(const String& urlString, const AtomicString& frameName, const String& windowFeaturesString,
1771     DOMWindow* activeWindow, DOMWindow* firstWindow)
1772 {
1773     if (!m_frame)
1774         return 0;
1775     Frame* activeFrame = activeWindow->frame();
1776     if (!activeFrame)
1777         return 0;
1778     Frame* firstFrame = firstWindow->frame();
1779     if (!firstFrame)
1780         return 0;
1781
1782     if (!firstWindow->allowPopUp()) {
1783         // Because FrameTree::find() returns true for empty strings, we must check for empty frame names.
1784         // Otherwise, illegitimate window.open() calls with no name will pass right through the popup blocker.
1785         if (frameName.isEmpty() || !m_frame->tree()->find(frameName))
1786             return 0;
1787     }
1788
1789     // Get the target frame for the special cases of _top and _parent.
1790     // In those cases, we schedule a location change right now and return early.
1791     Frame* targetFrame = 0;
1792     if (frameName == "_top")
1793         targetFrame = m_frame->tree()->top();
1794     else if (frameName == "_parent") {
1795         if (Frame* parent = m_frame->tree()->parent())
1796             targetFrame = parent;
1797         else
1798             targetFrame = m_frame;
1799     }
1800     if (targetFrame) {
1801         if (!activeFrame->loader()->shouldAllowNavigation(targetFrame))
1802             return 0;
1803
1804         if (isInsecureScriptAccess(activeWindow, urlString))
1805             return targetFrame->domWindow();
1806
1807         if (urlString.isEmpty())
1808             return targetFrame->domWindow();
1809
1810         // For whatever reason, Firefox uses the first window rather than the active window to
1811         // determine the outgoing referrer. We replicate that behavior here.
1812         targetFrame->navigationScheduler()->scheduleLocationChange(activeFrame->document()->securityOrigin(),
1813             firstFrame->document()->completeURL(urlString).string(),
1814             firstFrame->loader()->outgoingReferrer(),
1815             !activeFrame->script()->anyPageIsProcessingUserGesture(), false);
1816
1817         return targetFrame->domWindow();
1818     }
1819
1820     WindowFeatures windowFeatures(windowFeaturesString);
1821     FloatRect windowRect(windowFeatures.xSet ? windowFeatures.x : 0, windowFeatures.ySet ? windowFeatures.y : 0,
1822         windowFeatures.widthSet ? windowFeatures.width : 0, windowFeatures.heightSet ? windowFeatures.height : 0);
1823     Page* page = m_frame->page();
1824     DOMWindow::adjustWindowRect(screenAvailableRect(page ? page->mainFrame()->view() : 0), windowRect, windowRect);
1825     windowFeatures.x = windowRect.x();
1826     windowFeatures.y = windowRect.y();
1827     windowFeatures.height = windowRect.height();
1828     windowFeatures.width = windowRect.width();
1829
1830     Frame* result = createWindow(urlString, frameName, windowFeatures, activeWindow, firstFrame, m_frame);
1831     return result ? result->domWindow() : 0;
1832 }
1833
1834 void DOMWindow::showModalDialog(const String& urlString, const String& dialogFeaturesString,
1835     DOMWindow* activeWindow, DOMWindow* firstWindow, PrepareDialogFunction function, void* functionContext)
1836 {
1837     if (!m_frame)
1838         return;
1839     Frame* activeFrame = activeWindow->frame();
1840     if (!activeFrame)
1841         return;
1842     Frame* firstFrame = firstWindow->frame();
1843     if (!firstFrame)
1844         return;
1845
1846     if (!canShowModalDialogNow(m_frame) || !firstWindow->allowPopUp())
1847         return;
1848
1849     Frame* dialogFrame = createWindow(urlString, emptyAtom, WindowFeatures(dialogFeaturesString, screenAvailableRect(m_frame->view())),
1850         activeWindow, firstFrame, m_frame, function, functionContext);
1851     if (!dialogFrame)
1852         return;
1853
1854     dialogFrame->page()->chrome()->runModal();
1855 }
1856
1857 } // namespace WebCore