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