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