1 /* This file is part of the KDE project
3 * Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>
4 * 1999 Lars Knoll <knoll@kde.org>
5 * 1999 Antti Koivisto <koivisto@kde.org>
6 * 2000 Simon Hausmann <hausmann@kde.org>
7 * 2000 Stefan Schimanski <1Stein@gmx.de>
8 * 2001 George Staikos <staikos@kde.org>
9 * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc.
10 * Copyright (C) 2005 Alexey Proskuryakov <ap@nypop.com>
12 * This library is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Library General Public
14 * License as published by the Free Software Foundation; either
15 * version 2 of the License, or (at your option) any later version.
17 * This library is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Library General Public License for more details.
22 * You should have received a copy of the GNU Library General Public License
23 * along with this library; see the file COPYING.LIB. If not, write to
24 * the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 * Boston, MA 02111-1307, USA.
30 #include "FramePrivate.h"
32 #include "ApplyStyleCommand.h"
33 #include "CSSComputedStyleDeclaration.h"
34 #include "CSSProperty.h"
35 #include "CSSPropertyNames.h"
37 #include "CachedCSSStyleSheet.h"
38 #include "DOMImplementation.h"
39 #include "DOMWindow.h"
41 #include "DocLoader.h"
42 #include "DocumentType.h"
43 #include "EditingText.h"
45 #include "EventNames.h"
46 #include "FloatRect.h"
48 #include "GraphicsContext.h"
49 #include "HTMLFormElement.h"
50 #include "HTMLFrameElement.h"
51 #include "HTMLGenericFormElement.h"
52 #include "HTMLInputElement.h"
53 #include "HTMLNames.h"
54 #include "HTMLObjectElement.h"
55 #include "HTMLViewSourceDocument.h"
56 #include "ImageDocument.h"
57 #include "loader/icon/IconDatabase.h"
58 #include "loader/icon/IconLoader.h"
59 #include "MediaFeatureNames.h"
60 #include "MouseEventWithHitTestResults.h"
63 #include "PlatformScrollBar.h"
64 #include "PlugInInfoStore.h"
66 #include "PluginDocument.h"
67 #include "RenderPart.h"
68 #include "RenderTextControl.h"
69 #include "RenderTheme.h"
70 #include "RenderView.h"
71 #include "SegmentedString.h"
72 #include "TextDocument.h"
73 #include "TextIterator.h"
74 #include "TypingCommand.h"
75 #include "XMLTokenizer.h"
76 #include "cssstyleselector.h"
77 #include "htmlediting.h"
78 #include "kjs_window.h"
80 #include "visible_units.h"
81 #include "xmlhttprequest.h"
83 #include <sys/types.h>
84 #include <wtf/Platform.h>
96 #include "XLinkNames.h"
98 #include "SVGDocument.h"
99 #include "SVGDocumentExtensions.h"
107 using KJS::PausedTimeouts;
108 using KJS::SavedProperties;
109 using KJS::SavedBuiltins;
115 using namespace EventNames;
116 using namespace HTMLNames;
118 const double caretBlinkFrequency = 0.5;
119 const double autoscrollInterval = 0.1;
121 class UserStyleSheetLoader : public CachedResourceClient {
123 UserStyleSheetLoader(Frame* frame, const String& url, DocLoader* dl)
125 , m_cachedSheet(Cache::requestStyleSheet(dl, url, false, 0, ""))
127 m_cachedSheet->ref(this);
129 ~UserStyleSheetLoader()
131 m_cachedSheet->deref(this);
134 virtual void setStyleSheet(const String& /*URL*/, const String& sheet)
136 m_frame->setUserStyleSheet(sheet);
139 CachedCSSStyleSheet* m_cachedSheet;
143 struct FrameCounter {
145 ~FrameCounter() { if (count != 0) fprintf(stderr, "LEAK: %d Frame\n", count); }
147 int FrameCounter::count = 0;
148 static FrameCounter frameCounter;
151 static inline Frame* parentFromOwnerElement(Element* ownerElement)
155 return ownerElement->document()->frame();
158 Frame::Frame(Page* page, Element* ownerElement)
159 : d(new FramePrivate(page, parentFromOwnerElement(ownerElement), this, ownerElement))
161 AtomicString::init();
165 QualifiedName::init();
166 MediaFeatureNames::init();
174 if (d->m_ownerElement)
175 d->m_page->incrementFrameCount();
177 // FIXME: Frames were originally created with a refcount of 1, leave this
178 // ref call here until we can straighten that out.
181 ++FrameCounter::count;
187 ASSERT(!d->m_lifeSupportTimer.isActive());
190 --FrameCounter::count;
195 if (d->m_jscript && d->m_jscript->haveInterpreter())
196 if (Window* w = Window::retrieveWindow(this)) {
197 w->disconnectFrame();
198 // Must clear the window pointer, otherwise we will not
199 // garbage-collect collect the window (inside the call to
204 disconnectOwnerElement();
207 d->m_domWindow->disconnectFrame();
210 HashSet<Frame*> openedBy = d->m_openedFrames;
211 HashSet<Frame*>::iterator end = openedBy.end();
212 for (HashSet<Frame*>::iterator it = openedBy.begin(); it != end; ++it)
217 d->m_view->m_frame = 0;
220 ASSERT(!d->m_lifeSupportTimer.isActive());
222 delete d->m_userStyleSheetLoader;
227 KURL Frame::iconURL()
229 // If this isn't a top level frame, return nothing
230 if (tree() && tree()->parent())
233 // If we have an iconURL from a Link element, return that
234 if (document() && !document()->iconURL().isEmpty())
235 return KURL(document()->iconURL().deprecatedString());
237 // Don't return a favicon iconURL unless we're http or https
238 if (d->m_url.protocol() != "http" && d->m_url.protocol() != "https")
242 url.setProtocol(d->m_url.protocol());
243 url.setHost(d->m_url.host());
244 url.setPath("/favicon.ico");
248 bool Frame::didOpenURL(const KURL& url)
250 if (d->m_scheduledRedirection == locationChangeScheduledDuringLoad) {
251 // A redirect was shceduled before the document was created. This can happen
252 // when one frame changes another frame's location.
258 // clear last edit command
259 d->m_lastEditCommand = 0;
263 d->m_bComplete = false;
264 d->m_bLoadingMainResource = true;
265 d->m_bLoadEventEmitted = false;
267 d->m_kjsStatusBarText = String();
268 d->m_kjsDefaultStatusBarText = String();
270 d->m_bJScriptEnabled = d->m_settings->isJavaScriptEnabled();
271 d->m_bJavaEnabled = d->m_settings->isJavaEnabled();
272 d->m_bPluginsEnabled = d->m_settings->isPluginsEnabled();
274 // initializing d->m_url to the new url breaks relative links when opening such a link after this call and _before_ begin() is called (when the first
275 // data arrives) (Simon)
277 if (d->m_url.protocol().startsWith("http") && !d->m_url.host().isEmpty() && d->m_url.path().isEmpty())
278 d->m_url.setPath("/");
279 d->m_workingURL = d->m_url;
286 void Frame::didExplicitOpen()
288 d->m_bComplete = false;
289 d->m_bLoadEventEmitted = false;
291 // Prevent window.open(url) -- eg window.open("about:blank") -- from blowing away results
292 // from a subsequent window.document.open / window.document.write call.
293 // Cancelling redirection here works for all cases because document.open
294 // implicitly precedes document.write.
296 d->m_url = d->m_doc->URL();
299 void Frame::stopLoading(bool sendUnload)
301 if (d->m_doc && d->m_doc->tokenizer())
302 d->m_doc->tokenizer()->stopParsing();
304 d->m_metaData.clear();
308 if (d->m_bLoadEventEmitted && !d->m_bUnloadEventEmitted) {
309 Node* currentFocusNode = d->m_doc->focusNode();
310 if (currentFocusNode)
311 currentFocusNode->aboutToUnload();
312 d->m_doc->dispatchWindowEvent(unloadEvent, false, false);
314 d->m_doc->updateRendering();
315 d->m_bUnloadEventEmitted = true;
319 if (d->m_doc && !d->m_doc->inPageCache())
320 d->m_doc->removeAllEventListenersFromAllNodes();
323 d->m_bComplete = true; // to avoid calling completed() in finishedParsing() (David)
324 d->m_bLoadingMainResource = false;
325 d->m_bLoadEventEmitted = true; // don't want that one either
326 d->m_cachePolicy = CachePolicyVerify; // Why here?
328 if (d->m_doc && d->m_doc->parsing()) {
330 d->m_doc->setParsing(false);
333 d->m_workingURL = KURL();
335 if (Document *doc = d->m_doc.get()) {
336 if (DocLoader *docLoader = doc->docLoader())
337 Cache::loader()->cancelRequests(docLoader);
338 XMLHttpRequest::cancelRequests(doc);
341 // tell all subframes to stop as well
342 for (Frame* child = tree()->firstChild(); child; child = child->tree()->nextSibling())
343 child->stopLoading(sendUnload);
345 d->m_bPendingChildRedirection = false;
350 BrowserExtension *Frame::browserExtension() const
352 return d->m_extension;
355 FrameView* Frame::view() const
357 return d->m_view.get();
360 void Frame::setView(FrameView* view)
365 bool Frame::jScriptEnabled() const
367 return d->m_bJScriptEnabled;
370 KJSProxy *Frame::jScript()
372 if (!d->m_bJScriptEnabled)
376 d->m_jscript = new KJSProxy(this);
381 static bool getString(JSValue* result, String& string)
387 if (!result->getString(ustring))
393 void Frame::replaceContentsWithScriptResult(const KURL& url)
395 JSValue* ret = executeScript(0, KURL::decode_string(url.url().mid(strlen("javascript:"))));
397 if (getString(ret, scriptResult)) {
404 JSValue* Frame::executeScript(Node* n, const String& script, bool forceUserGesture)
406 KJSProxy *proxy = jScript();
411 d->m_runningScripts++;
412 // If forceUserGesture is true, then make the script interpreter
413 // treat it as if triggered by a user gesture even if there is no
414 // current DOM event being processed.
415 JSValue* ret = proxy->evaluate(forceUserGesture ? DeprecatedString::null : d->m_url.url(), 0, script, n);
416 d->m_runningScripts--;
418 if (!d->m_runningScripts)
421 Document::updateDocumentsRendering();
426 bool Frame::javaEnabled() const
428 return d->m_settings->isJavaEnabled();
431 bool Frame::pluginsEnabled() const
433 return d->m_bPluginsEnabled;
436 void Frame::setAutoloadImages(bool enable)
438 if (d->m_doc && d->m_doc->docLoader()->autoloadImages() == enable)
442 d->m_doc->docLoader()->setAutoloadImages(enable);
445 bool Frame::autoloadImages() const
448 return d->m_doc->docLoader()->autoloadImages();
453 void Frame::cancelAndClear()
463 void Frame::clear(bool clearWindowProperties)
467 d->m_bCleared = true;
468 d->m_mousePressNode = 0;
471 // FIXME: This is a temporary hack to work around a mismatch between WebCore and WebKit
472 // regarding frame lifetime. The proper solution is to move all frame management
473 // into WebCore, so frames can work the same way on all platforms.
474 for (Frame* descendant = tree()->firstChild(); descendant; descendant = descendant->tree()->traverseNext())
475 descendant->disconnectOwnerElement();
479 d->m_doc->cancelParsing();
483 // Moving past doc so that onUnload works.
484 if (clearWindowProperties && d->m_jscript)
485 d->m_jscript->clear();
490 // do not drop the document before the jscript and view are cleared, as some destructors
491 // might still try to access the document.
495 d->m_plugins.clear();
496 cleanupPluginObjects();
498 d->m_scheduledRedirection = noRedirectionScheduled;
499 d->m_delayRedirect = 0;
500 d->m_redirectURL = DeprecatedString::null;
501 d->m_redirectReferrer = String();
502 d->m_redirectLockHistory = true;
503 d->m_redirectUserGesture = false;
504 d->m_bHTTPRefresh = false;
505 d->m_bFirstData = true;
507 d->m_bMousePressed = false;
509 if (!d->m_haveEncoding)
510 d->m_encoding = String();
513 Document *Frame::document() const
516 return d->m_doc.get();
520 void Frame::setDocument(Document* newDoc)
531 void Frame::receivedFirstData()
533 begin(d->m_workingURL);
535 d->m_doc->docLoader()->setCachePolicy(d->m_cachePolicy);
536 d->m_workingURL = KURL();
538 // When the first data arrives, the metadata has just been made available
539 DeprecatedString qData;
541 // Support for http-refresh
542 qData = d->m_metaData.get("http-refresh").deprecatedString();
543 if (!qData.isEmpty()) {
545 int pos = qData.find(';');
547 pos = qData.find(',');
550 delay = qData.stripWhiteSpace().toDouble();
551 // We want a new history item if the refresh timeout > 1 second
552 scheduleRedirection(delay, d->m_url.url(), delay <= 1);
554 int end_pos = qData.length();
555 delay = qData.left(pos).stripWhiteSpace().toDouble();
556 while (qData[++pos] == ' ');
557 if (qData.find("url", pos, false) == pos) {
559 while (qData[pos] == ' ' || qData[pos] == '=')
561 if (qData[pos] == '"') {
563 int index = end_pos-1;
564 while (index > pos) {
565 if (qData[index] == '"')
573 // We want a new history item if the refresh timeout > 1 second
574 scheduleRedirection(delay, d->m_doc->completeURL(qData.mid(pos, end_pos)), delay <= 1);
576 d->m_bHTTPRefresh = true;
579 // Support for http last-modified
580 d->m_lastModified = d->m_metaData.get("modified");
583 void Frame::childBegin()
585 // We need to do this when the child is created so as to avoid the parent thining the child
586 // is complete before it has even started loading.
587 // FIXME: do we really still need this?
588 d->m_bComplete = false;
591 void Frame::setResourceRequest(const ResourceRequest& request)
593 d->m_request = request;
596 const ResourceRequest& Frame::resourceRequest() const
601 void Frame::begin(const KURL& url)
603 if (d->m_workingURL.isEmpty())
604 createEmptyDocument(); // Creates an empty document if we don't have one already
607 partClearedInBegin();
609 d->m_bCleared = false;
610 d->m_bComplete = false;
611 d->m_bLoadEventEmitted = false;
612 d->m_bLoadingMainResource = true;
615 ref.setUser(DeprecatedString());
616 ref.setPass(DeprecatedString());
617 ref.setRef(DeprecatedString());
618 d->m_referrer = ref.url();
622 // We don't need KDE chained URI handling or window caption setting
623 if (!d->m_url.isEmpty())
627 if (d->m_request.m_responseMIMEType == "image/svg+xml")
628 d->m_doc = DOMImplementation::instance()->createSVGDocument(d->m_view.get());
631 if (DOMImplementation::isXMLMIMEType(d->m_request.m_responseMIMEType))
632 d->m_doc = DOMImplementation::instance()->createDocument(d->m_view.get());
633 else if (DOMImplementation::isTextMIMEType(d->m_request.m_responseMIMEType))
634 d->m_doc = new TextDocument(DOMImplementation::instance(), d->m_view.get());
635 else if ((d->m_request.m_responseMIMEType == "application/pdf" || d->m_request.m_responseMIMEType == "text/pdf") && PlugInInfoStore::supportsMIMEType(d->m_request.m_responseMIMEType))
636 d->m_doc = new PluginDocument(DOMImplementation::instance(), d->m_view.get());
637 else if (Image::supportsType(d->m_request.m_responseMIMEType))
638 d->m_doc = new ImageDocument(DOMImplementation::instance(), d->m_view.get());
639 else if (PlugInInfoStore::supportsMIMEType(d->m_request.m_responseMIMEType))
640 d->m_doc = new PluginDocument(DOMImplementation::instance(), d->m_view.get());
641 else if (inViewSourceMode())
642 d->m_doc = new HTMLViewSourceDocument(DOMImplementation::instance(), d->m_view.get());
644 d->m_doc = DOMImplementation::instance()->createHTMLDocument(d->m_view.get());
646 if (!d->m_doc->attached())
648 d->m_doc->setURL(d->m_url.url());
649 // We prefer m_baseURL over d->m_url because d->m_url changes when we are
650 // about to load a new page.
651 d->m_doc->setBaseURL(baseurl.url());
653 d->m_doc->setDecoder(d->m_decoder.get());
655 updatePolicyBaseURL();
657 setAutoloadImages(d->m_settings->autoLoadImages());
658 const KURL& userStyleSheet = d->m_settings->userStyleSheetLocation();
660 if (!userStyleSheet.isEmpty())
661 setUserStyleSheetLocation(KURL(userStyleSheet));
663 restoreDocumentState();
665 d->m_doc->implicitOpen();
668 d->m_view->resizeContents(0, 0);
671 void Frame::write(const char* str, int len)
679 if (Tokenizer* t = d->m_doc->tokenizer()) {
680 if (t->wantsRawData()) {
681 t->writeRawData(str, len);
687 d->m_decoder = new Decoder(d->m_request.m_responseMIMEType, settings()->encoding());
688 if (!d->m_encoding.isNull())
689 d->m_decoder->setEncoding(d->m_encoding,
690 d->m_haveEncoding ? Decoder::UserChosenEncoding : Decoder::EncodingFromHTTPHeader);
692 d->m_doc->setDecoder(d->m_decoder.get());
695 String decoded = d->m_decoder->decode(str, len);
697 if (decoded.isEmpty())
700 if (d->m_bFirstData) {
701 d->m_bFirstData = false;
702 d->m_doc->determineParseMode(decoded);
703 if (d->m_decoder->encoding().usesVisualOrdering())
704 d->m_doc->setVisuallyOrdered();
705 d->m_doc->recalcStyle(Node::Force);
708 if (Tokenizer* t = d->m_doc->tokenizer()) {
709 ASSERT(!t->wantsRawData());
710 t->write(decoded, true);
714 void Frame::write(const String& str)
719 if (d->m_bFirstData) {
720 // determine the parse mode
721 d->m_doc->setParseMode(Document::Strict);
722 d->m_bFirstData = false;
724 Tokenizer* t = d->m_doc->tokenizer();
731 d->m_bLoadingMainResource = false;
735 void Frame::endIfNotLoading()
737 // http://bugzilla.opendarwin.org/show_bug.cgi?id=10854
738 // The frame's last ref may be remove and it be deleted by checkCompleted(),
739 // so we'll add a protective refcount
740 RefPtr<Frame> protector(this);
742 if (d->m_bLoadingMainResource)
745 // make sure nothing's left in there...
748 String decoded = d->m_decoder->flush();
749 if (d->m_bFirstData) {
750 d->m_bFirstData = false;
751 d->m_doc->determineParseMode(decoded);
755 d->m_doc->finishParsing();
757 // WebKit partially uses WebCore when loading non-HTML docs. In these cases doc==nil, but
758 // WebCore is enough involved that we need to checkCompleted() in order for m_bComplete to
759 // become true. An example is when a subframe is a pure text doc, and that subframe is the
760 // last one to complete.
763 // FIXME - Right now, we kick off the icon loader when the frame is done receiving all its main resource.
764 // We could kick off the icon loader after we're done parsing the HEAD element, if that becomes convinient to find
767 // Don't load an icon if -
768 // 1) This is not the main frame
769 // 2) The database is disabled
770 // 3) We have no valid icon URL
771 // 4) We already have an unexpired icon
773 if (tree()->parent())
777 if (IconDatabase* sharedIconDatabase = IconDatabase::sharedIconDatabase()) {
778 if (!sharedIconDatabase->enabled())
781 String url(iconURL().url());
785 // If we already have an unexpired icon, we won't kick off a load but we *will* map the appropriate URLs to it
786 if (sharedIconDatabase->hasEntryForIconURL(url) && !isLoadTypeReload() && !sharedIconDatabase->isIconExpiredForIconURL(url)) {
787 commitIconURLToIconDatabase();
791 if (!d->m_iconLoader)
792 d->m_iconLoader = IconLoader::createForFrame(this);
793 d->m_iconLoader->startLoading();
797 void Frame::commitIconURLToIconDatabase()
799 KURL icon = iconURL();
801 IconDatabase* iconDatabase = IconDatabase::sharedIconDatabase();
802 ASSERT(iconDatabase);
803 iconDatabase->setIconURLForPageURL(icon.url(), this->url().url());
804 iconDatabase->setIconURLForPageURL(icon.url(), originalRequestURL().url());
809 // http://bugzilla.opendarwin.org/show_bug.cgi?id=10854
810 // The frame's last ref may be remove and it be deleted by checkCompleted(),
811 // so we'll add a protective refcount
812 RefPtr<Frame> protector(this);
815 if (d->m_doc->tokenizer())
816 d->m_doc->tokenizer()->stopParsing();
817 d->m_doc->finishParsing();
819 // WebKit partially uses WebCore when loading non-HTML docs. In these cases doc==nil, but
820 // WebCore is enough involved that we need to checkCompleted() in order for m_bComplete to
821 // become true. An example is when a subframe is a pure text doc, and that subframe is the
822 // last one to complete.
825 d->m_iconLoader->stopLoading();
828 void Frame::gotoAnchor()
830 // If our URL has no ref, then we have no place we need to jump to.
831 if (!d->m_url.hasRef())
834 DeprecatedString ref = d->m_url.encodedHtmlRef();
835 if (!gotoAnchor(ref)) {
836 // Can't use htmlRef() here because it doesn't know which encoding to use to decode.
837 // Decoding here has to match encoding in completeURL, which means it has to use the
838 // page's encoding rather than UTF-8.
840 gotoAnchor(KURL::decode_string(ref, d->m_decoder->encoding()));
844 void Frame::finishedParsing()
846 RefPtr<Frame> protector(this);
850 return; // We are being destroyed by something checkCompleted called.
852 // check if the scrollbars are really needed for the content
853 // if not, remove them, relayout, and repaint
855 d->m_view->restoreScrollBar();
859 void Frame::loadDone()
865 void Frame::checkCompleted()
867 // Any frame that hasn't completed yet ?
868 for (Frame* child = tree()->firstChild(); child; child = child->tree()->nextSibling())
869 if (!child->d->m_bComplete)
872 // Have we completed before?
876 // Are we still parsing?
877 if (d->m_doc && d->m_doc->parsing())
880 // Still waiting for images/scripts from the loader ?
882 if (d->m_doc && d->m_doc->docLoader())
883 requests = Cache::loader()->numRequests(d->m_doc->docLoader());
889 // Now do what should be done when we are really completed.
890 d->m_bComplete = true;
892 checkEmitLoadEvent(); // if we didn't do it before
894 if (d->m_scheduledRedirection != noRedirectionScheduled) {
895 // Do not start redirection for frames here! That action is
896 // deferred until the parent emits a completed signal.
897 if (!tree()->parent())
898 startRedirectionTimer();
902 completed(d->m_bPendingChildRedirection);
906 void Frame::checkEmitLoadEvent()
908 if (d->m_bLoadEventEmitted || !d->m_doc || d->m_doc->parsing())
911 for (Frame* child = tree()->firstChild(); child; child = child->tree()->nextSibling())
912 if (!child->d->m_bComplete) // still got a frame running -> too early
915 // All frames completed -> set their domain to the frameset's domain
916 // This must only be done when loading the frameset initially (#22039),
917 // not when following a link in a frame (#44162).
919 String domain = d->m_doc->domain();
920 for (Frame* child = tree()->firstChild(); child; child = child->tree()->nextSibling())
922 child->d->m_doc->setDomain(domain);
925 d->m_bLoadEventEmitted = true;
926 d->m_bUnloadEventEmitted = false;
928 d->m_doc->implicitClose();
931 const Settings *Frame::settings() const
933 return d->m_settings;
936 KURL Frame::baseURL() const
940 return d->m_doc->baseURL();
943 String Frame::baseTarget() const
947 return d->m_doc->baseTarget();
950 KURL Frame::completeURL(const DeprecatedString& url)
955 return KURL(d->m_doc->completeURL(url));
958 void Frame::scheduleRedirection(double delay, const DeprecatedString& url, bool doLockHistory)
960 if (delay < 0 || delay > INT_MAX / 1000)
962 if (d->m_scheduledRedirection == noRedirectionScheduled || delay <= d->m_delayRedirect)
964 d->m_scheduledRedirection = redirectionScheduled;
965 d->m_delayRedirect = delay;
966 d->m_redirectURL = url;
967 d->m_redirectReferrer = String();
968 d->m_redirectLockHistory = doLockHistory;
969 d->m_redirectUserGesture = false;
971 stopRedirectionTimer();
973 startRedirectionTimer();
977 void Frame::scheduleLocationChange(const DeprecatedString& url, const String& referrer, bool lockHistory, bool userGesture)
981 // If the URL we're going to navigate to is the same as the current one, except for the
982 // fragment part, we don't need to schedule the location change.
983 if (u.hasRef() && equalIgnoringRef(d->m_url, u)) {
984 changeLocation(url, referrer, lockHistory, userGesture);
988 // Handle a location change of a page with no document as a special case.
989 // This may happen when a frame changes the location of another frame.
990 d->m_scheduledRedirection = d->m_doc ? locationChangeScheduled : locationChangeScheduledDuringLoad;
992 // If a redirect was scheduled during a load, then stop the current load.
993 // Otherwise when the current load transitions from a provisional to a
994 // committed state, pending redirects may be cancelled.
995 if (d->m_scheduledRedirection == locationChangeScheduledDuringLoad) {
999 d->m_delayRedirect = 0;
1000 d->m_redirectURL = url;
1001 d->m_redirectReferrer = referrer;
1002 d->m_redirectLockHistory = lockHistory;
1003 d->m_redirectUserGesture = userGesture;
1004 stopRedirectionTimer();
1006 startRedirectionTimer();
1009 void Frame::scheduleRefresh(bool userGesture)
1011 // Handle a location change of a page with no document as a special case.
1012 // This may happen when a frame requests a refresh of another frame.
1013 d->m_scheduledRedirection = d->m_doc ? locationChangeScheduled : locationChangeScheduledDuringLoad;
1015 // If a refresh was scheduled during a load, then stop the current load.
1016 // Otherwise when the current load transitions from a provisional to a
1017 // committed state, pending redirects may be cancelled.
1018 if (d->m_scheduledRedirection == locationChangeScheduledDuringLoad)
1021 d->m_delayRedirect = 0;
1022 d->m_redirectURL = url().url();
1023 d->m_redirectReferrer = referrer();
1024 d->m_redirectLockHistory = true;
1025 d->m_redirectUserGesture = userGesture;
1026 d->m_cachePolicy = CachePolicyRefresh;
1027 stopRedirectionTimer();
1029 startRedirectionTimer();
1032 bool Frame::isScheduledLocationChangePending() const
1034 switch (d->m_scheduledRedirection) {
1035 case noRedirectionScheduled:
1036 case redirectionScheduled:
1038 case historyNavigationScheduled:
1039 case locationChangeScheduled:
1040 case locationChangeScheduledDuringLoad:
1046 void Frame::scheduleHistoryNavigation(int steps)
1048 // navigation will always be allowed in the 0 steps case, which is OK because
1049 // that's supposed to force a reload.
1050 if (!canGoBackOrForward(steps)) {
1051 cancelRedirection();
1055 // If the URL we're going to navigate to is the same as the current one, except for the
1056 // fragment part, we don't need to schedule the navigation.
1057 if (d->m_extension) {
1058 KURL u = d->m_extension->historyURL(steps);
1060 if (equalIgnoringRef(d->m_url, u)) {
1061 d->m_extension->goBackOrForward(steps);
1066 d->m_scheduledRedirection = historyNavigationScheduled;
1067 d->m_delayRedirect = 0;
1068 d->m_redirectURL = DeprecatedString::null;
1069 d->m_redirectReferrer = String();
1070 d->m_scheduledHistoryNavigationSteps = steps;
1071 stopRedirectionTimer();
1073 startRedirectionTimer();
1076 void Frame::cancelRedirection(bool cancelWithLoadInProgress)
1079 d->m_cancelWithLoadInProgress = cancelWithLoadInProgress;
1080 d->m_scheduledRedirection = noRedirectionScheduled;
1081 stopRedirectionTimer();
1085 void Frame::changeLocation(const DeprecatedString& URL, const String& referrer, bool lockHistory, bool userGesture)
1087 if (URL.find("javascript:", 0, false) == 0) {
1088 String script = KURL::decode_string(URL.mid(11));
1089 JSValue* result = executeScript(0, script, userGesture);
1090 String scriptResult;
1091 if (getString(result, scriptResult)) {
1093 write(scriptResult);
1099 ResourceRequest request(completeURL(URL));
1100 request.setLockHistory(lockHistory);
1101 if (!referrer.isEmpty())
1102 request.setReferrer(referrer);
1104 request.reload = (d->m_cachePolicy == CachePolicyReload) || (d->m_cachePolicy == CachePolicyRefresh);
1106 urlSelected(request, "_self");
1109 void Frame::redirectionTimerFired(Timer<Frame>*)
1111 if (d->m_scheduledRedirection == historyNavigationScheduled) {
1112 d->m_scheduledRedirection = noRedirectionScheduled;
1114 // Special case for go(0) from a frame -> reload only the frame
1115 // go(i!=0) from a frame navigates into the history of the frame only,
1116 // in both IE and NS (but not in Mozilla).... we can't easily do that
1118 if (d->m_scheduledHistoryNavigationSteps == 0) // add && parent() to get only frames, but doesn't matter
1119 openURL(url()); /// ## need args.reload=true?
1121 if (d->m_extension) {
1122 d->m_extension->goBackOrForward(d->m_scheduledHistoryNavigationSteps);
1128 DeprecatedString URL = d->m_redirectURL;
1129 String referrer = d->m_redirectReferrer;
1130 bool lockHistory = d->m_redirectLockHistory;
1131 bool userGesture = d->m_redirectUserGesture;
1133 d->m_scheduledRedirection = noRedirectionScheduled;
1134 d->m_delayRedirect = 0;
1135 d->m_redirectURL = DeprecatedString::null;
1136 d->m_redirectReferrer = String();
1138 changeLocation(URL, referrer, lockHistory, userGesture);
1141 String Frame::encoding() const
1143 if (d->m_haveEncoding && !d->m_encoding.isEmpty())
1144 return d->m_encoding;
1145 if (d->m_decoder && d->m_decoder->encoding().isValid())
1146 return d->m_decoder->encoding().name();
1147 return settings()->encoding();
1150 void Frame::setUserStyleSheetLocation(const KURL& url)
1152 delete d->m_userStyleSheetLoader;
1153 d->m_userStyleSheetLoader = 0;
1154 if (d->m_doc && d->m_doc->docLoader())
1155 d->m_userStyleSheetLoader = new UserStyleSheetLoader(this, url.url(), d->m_doc->docLoader());
1158 void Frame::setUserStyleSheet(const String& styleSheet)
1160 delete d->m_userStyleSheetLoader;
1161 d->m_userStyleSheetLoader = 0;
1163 d->m_doc->setUserStyleSheet(styleSheet);
1166 bool Frame::gotoAnchor(const String& name)
1171 Node *n = d->m_doc->getElementById(AtomicString(name));
1173 n = d->m_doc->anchors()->namedItem(name, !d->m_doc->inCompatMode());
1175 d->m_doc->setCSSTarget(n); // Setting to null will clear the current target.
1177 // Implement the rule that "" and "top" both mean top of page as in other browsers.
1178 if (!n && !(name.isEmpty() || name.lower() == "top"))
1181 // We need to update the layout before scrolling, otherwise we could
1182 // really mess things up if an anchor scroll comes at a bad moment.
1184 d->m_doc->updateRendering();
1185 // Only do a layout if changes have occurred that make it necessary.
1186 if (d->m_view && d->m_doc->renderer() && d->m_doc->renderer()->needsLayout()) {
1187 d->m_view->layout();
1191 // Scroll nested layers and frames to reveal the anchor.
1192 RenderObject *renderer;
1195 renderer = n->renderer();
1196 rect = n->getRect();
1198 // If there's no node, we should scroll to the top of the document.
1199 renderer = d->m_doc->renderer();
1204 // Align to the top and to the closest side (this matches other browsers).
1205 renderer->enclosingLayer()->scrollRectToVisible(rect, RenderLayer::gAlignToEdgeIfNeeded, RenderLayer::gAlignTopAlways);
1211 void Frame::setStandardFont(const String& name)
1213 d->m_settings->setStdFontName(AtomicString(name));
1216 void Frame::setFixedFont(const String& name)
1218 d->m_settings->setFixedFontName(AtomicString(name));
1221 String Frame::selectedText() const
1223 return plainText(selectionController()->toRange().get());
1226 bool Frame::hasSelection() const
1228 return selectionController()->isCaretOrRange();
1231 SelectionController* Frame::selectionController() const
1233 return &(d->m_selectionController);
1236 TextGranularity Frame::selectionGranularity() const
1238 return d->m_selectionGranularity;
1241 void Frame::setSelectionGranularity(TextGranularity granularity) const
1243 d->m_selectionGranularity = granularity;
1246 SelectionController* Frame::dragCaretController() const
1248 return d->m_page->dragCaretController();
1251 const Selection& Frame::mark() const
1256 void Frame::setMark(const Selection& s)
1258 ASSERT(!s.base().node() || s.base().node()->document() == document());
1259 ASSERT(!s.extent().node() || s.extent().node()->document() == document());
1260 ASSERT(!s.start().node() || s.start().node()->document() == document());
1261 ASSERT(!s.end().node() || s.end().node()->document() == document());
1266 void Frame::notifyRendererOfSelectionChange(bool userTriggered)
1268 RenderObject* renderer = 0;
1269 if (selectionController()->rootEditableElement())
1270 renderer = selectionController()->rootEditableElement()->shadowAncestorNode()->renderer();
1272 // If the current selection is in a textfield or textarea, notify the renderer that the selection has changed
1273 if (renderer && (renderer->isTextArea() || renderer->isTextField()))
1274 static_cast<RenderTextControl*>(renderer)->selectionChanged(userTriggered);
1277 void Frame::invalidateSelection()
1279 clearCaretRectIfNeeded();
1280 selectionController()->setNeedsLayout();
1281 selectionLayoutChanged();
1284 void Frame::setCaretVisible(bool flag)
1286 if (d->m_caretVisible == flag)
1288 clearCaretRectIfNeeded();
1290 setFocusNodeIfNeeded();
1291 d->m_caretVisible = flag;
1292 selectionLayoutChanged();
1296 void Frame::clearCaretRectIfNeeded()
1298 if (d->m_caretPaint) {
1299 d->m_caretPaint = false;
1300 selectionController()->needsCaretRepaint();
1304 // Helper function that tells whether a particular node is an element that has an entire
1305 // Frame and FrameView, a <frame>, <iframe>, or <object>.
1306 static bool isFrameElement(const Node *n)
1310 RenderObject *renderer = n->renderer();
1311 if (!renderer || !renderer->isWidget())
1313 Widget* widget = static_cast<RenderWidget*>(renderer)->widget();
1314 return widget && widget->isFrameView();
1317 void Frame::setFocusNodeIfNeeded()
1319 if (!document() || selectionController()->isNone() || !d->m_isActive)
1322 Node* target = selectionController()->rootEditableElement();
1324 RenderObject* renderer = target->renderer();
1326 // Walk up the render tree to search for a node to focus.
1327 // Walking up the DOM tree wouldn't work for shadow trees, like those behind the engine-based text fields.
1329 // We don't want to set focus on a subframe when selecting in a parent frame,
1330 // so add the !isFrameElement check here. There's probably a better way to make this
1331 // work in the long term, but this is the safest fix at this time.
1332 if (target && target->isMouseFocusable() && !isFrameElement(target)) {
1333 document()->setFocusNode(target);
1336 renderer = renderer->parent();
1338 target = renderer->element();
1340 document()->setFocusNode(0);
1344 void Frame::selectionLayoutChanged()
1346 // kill any caret blink timer now running
1347 d->m_caretBlinkTimer.stop();
1349 // see if a new caret blink timer needs to be started
1350 if (d->m_caretVisible && d->m_caretBlinks &&
1351 selectionController()->isCaret() && selectionController()->start().node()->isContentEditable()) {
1352 d->m_caretBlinkTimer.startRepeating(caretBlinkFrequency);
1353 d->m_caretPaint = true;
1354 selectionController()->needsCaretRepaint();
1358 d->m_doc->updateSelection();
1361 void Frame::setXPosForVerticalArrowNavigation(int x)
1363 d->m_xPosForVerticalArrowNavigation = x;
1366 int Frame::xPosForVerticalArrowNavigation() const
1368 return d->m_xPosForVerticalArrowNavigation;
1371 void Frame::caretBlinkTimerFired(Timer<Frame>*)
1373 // Might be better to turn the timer off during some of these circumstances
1374 // and assert rather then letting the timer fire and do nothing here.
1375 // Could do that in selectionLayoutChanged.
1377 if (!d->m_caretVisible)
1379 if (!d->m_caretBlinks)
1381 if (!selectionController()->isCaret())
1383 bool caretPaint = d->m_caretPaint;
1384 if (d->m_bMousePressed && caretPaint)
1386 d->m_caretPaint = !caretPaint;
1387 selectionController()->needsCaretRepaint();
1390 void Frame::paintCaret(GraphicsContext* p, const IntRect& rect) const
1392 if (d->m_caretPaint)
1393 selectionController()->paintCaret(p, rect);
1396 void Frame::paintDragCaret(GraphicsContext* p, const IntRect& rect) const
1398 SelectionController* dragCaretController = d->m_page->dragCaretController();
1399 assert(dragCaretController->selection().isCaret());
1400 if (dragCaretController->selection().start().node()->document()->frame() == this)
1401 dragCaretController->paintCaret(p, rect);
1404 void Frame::urlSelected(const DeprecatedString& url, const String& target)
1406 urlSelected(ResourceRequest(completeURL(url)), target);
1409 void Frame::urlSelected(const ResourceRequest& request, const String& _target)
1411 String target = _target;
1412 if (target.isEmpty() && d->m_doc)
1413 target = d->m_doc->baseTarget();
1415 const KURL& url = request.url();
1417 if (url.url().startsWith("javascript:", false)) {
1418 executeScript(0, KURL::decode_string(url.url().mid(11)), true);
1423 // ### ERROR HANDLING
1426 ResourceRequest requestCopy = request;
1427 requestCopy.frameName = target;
1429 if (d->m_bHTTPRefresh)
1430 d->m_bHTTPRefresh = false;
1432 if (!d->m_referrer.isEmpty())
1433 requestCopy.setReferrer(d->m_referrer);
1435 urlSelected(requestCopy);
1438 bool Frame::requestFrame(Element* ownerElement, const String& urlParam, const AtomicString& frameName)
1440 DeprecatedString _url = urlParam.deprecatedString();
1441 // Support for <frame src="javascript:string">
1444 if (_url.startsWith("javascript:", false)) {
1446 url = "about:blank";
1448 url = completeURL(_url);
1450 Frame* frame = tree()->child(frameName);
1452 ResourceRequest request(url);
1453 request.setReferrer(d->m_referrer);
1454 request.reload = (d->m_cachePolicy == CachePolicyReload) || (d->m_cachePolicy == CachePolicyRefresh);
1455 frame->openURLRequest(request);
1457 frame = loadSubframe(ownerElement, url, frameName, d->m_referrer);
1462 if (!scriptURL.isEmpty())
1463 frame->replaceContentsWithScriptResult(scriptURL);
1468 bool Frame::requestObject(RenderPart* renderer, const String& url, const AtomicString& frameName,
1469 const String& mimeType, const Vector<String>& paramNames, const Vector<String>& paramValues)
1473 completedURL = completeURL(url.deprecatedString());
1475 if (url.isEmpty() && mimeType.isEmpty())
1479 if (shouldUsePlugin(renderer->element(), completedURL, mimeType, renderer->hasFallbackContent(), useFallback))
1480 return loadPlugin(renderer, completedURL, mimeType, paramNames, paramValues, useFallback);
1482 ASSERT(renderer->node()->hasTagName(objectTag) || renderer->node()->hasTagName(embedTag));
1483 AtomicString uniqueFrameName = tree()->uniqueChildName(frameName);
1484 static_cast<HTMLPlugInElement*>(renderer->node())->setFrameName(uniqueFrameName);
1486 // FIXME: ok to always make a new one? when does the old frame get removed?
1487 return loadSubframe(static_cast<Element*>(renderer->node()), completedURL, uniqueFrameName, d->m_referrer);
1490 bool Frame::shouldUsePlugin(Node* element, const KURL& url, const String& mimeType, bool hasFallback, bool& useFallback)
1492 useFallback = false;
1493 ObjectContentType objectType = objectContentType(url, mimeType);
1495 // if an object's content can't be handled and it has no fallback, let
1496 // it be handled as a plugin to show the broken plugin icon
1497 if (objectType == ObjectContentNone && hasFallback)
1500 return objectType == ObjectContentNone || objectType == ObjectContentPlugin;
1504 bool Frame::loadPlugin(RenderPart *renderer, const KURL& url, const String& mimeType,
1505 const Vector<String>& paramNames, const Vector<String>& paramValues, bool useFallback)
1508 checkEmitLoadEvent();
1512 Element *pluginElement;
1513 if (renderer && renderer->node() && renderer->node()->isElementNode())
1514 pluginElement = static_cast<Element*>(renderer->node());
1518 Plugin* plugin = createPlugin(pluginElement, url, paramNames, paramValues, mimeType);
1520 checkEmitLoadEvent();
1523 d->m_plugins.append(plugin);
1525 if (renderer && plugin->view())
1526 renderer->setWidget(plugin->view());
1528 checkEmitLoadEvent();
1533 Frame* Frame::loadSubframe(Element* ownerElement, const KURL& url, const String& name, const String& referrer)
1535 Frame* frame = createFrame(url, name, ownerElement, referrer);
1537 checkEmitLoadEvent();
1541 frame->childBegin();
1543 if (ownerElement->renderer() && frame->view())
1544 static_cast<RenderWidget*>(ownerElement->renderer())->setWidget(frame->view());
1546 checkEmitLoadEvent();
1548 // In these cases, the synchronous load would have finished
1549 // before we could connect the signals, so make sure to send the
1550 // completed() signal for the child by hand
1551 // FIXME: In this case the Frame will have finished loading before
1552 // it's being added to the child list. It would be a good idea to
1553 // create the child first, then invoke the loader separately.
1554 if (url.isEmpty() || url == "about:blank") {
1555 frame->completed(false);
1556 frame->checkCompleted();
1562 void Frame::clearRecordedFormValues()
1564 d->m_formAboutToBeSubmitted = 0;
1565 d->m_formValuesAboutToBeSubmitted.clear();
1568 void Frame::recordFormValue(const String& name, const String& value, PassRefPtr<HTMLFormElement> element)
1570 d->m_formAboutToBeSubmitted = element;
1571 d->m_formValuesAboutToBeSubmitted.set(name, value);
1574 void Frame::submitFormAgain()
1576 FramePrivate::SubmitForm* form = d->m_submitForm;
1577 d->m_submitForm = 0;
1578 if (d->m_doc && !d->m_doc->parsing() && form)
1579 submitForm(form->submitAction, form->submitUrl, form->submitFormData,
1580 form->target, form->submitContentType, form->submitBoundary);
1584 void Frame::submitForm(const char *action, const String& url, const FormData& formData, const String& _target, const String& contentType, const String& boundary)
1586 KURL u = completeURL(url.deprecatedString());
1589 // ### ERROR HANDLING!
1592 DeprecatedString urlstring = u.url();
1593 if (urlstring.startsWith("javascript:", false)) {
1594 urlstring = KURL::decode_string(urlstring);
1595 d->m_executingJavaScriptFormAction = true;
1596 executeScript(0, urlstring.mid(11));
1597 d->m_executingJavaScriptFormAction = false;
1601 ResourceRequest request;
1603 if (!d->m_referrer.isEmpty())
1604 request.setReferrer(d->m_referrer);
1606 request.frameName = _target.isEmpty() ? d->m_doc->baseTarget() : _target ;
1608 // Handle mailto: forms
1609 if (u.protocol() == "mailto") {
1610 // 1) Check for attach= and strip it
1611 DeprecatedString q = u.query().mid(1);
1612 DeprecatedStringList nvps = DeprecatedStringList::split("&", q);
1613 bool triedToAttach = false;
1615 for (DeprecatedStringList::Iterator nvp = nvps.begin(); nvp != nvps.end(); ++nvp) {
1616 DeprecatedStringList pair = DeprecatedStringList::split("=", *nvp);
1617 if (pair.count() >= 2) {
1618 if (pair.first().lower() == "attach") {
1619 nvp = nvps.remove(nvp);
1620 triedToAttach = true;
1627 DeprecatedString bodyEnc;
1628 if (contentType.lower() == "multipart/form-data")
1629 // FIXME: is this correct? I suspect not
1630 bodyEnc = KURL::encode_string(formData.flattenToString().deprecatedString());
1631 else if (contentType.lower() == "text/plain") {
1632 // Convention seems to be to decode, and s/&/\n/
1633 DeprecatedString tmpbody = formData.flattenToString().deprecatedString();
1634 tmpbody.replace('&', '\n');
1635 tmpbody.replace('+', ' ');
1636 tmpbody = KURL::decode_string(tmpbody); // Decode the rest of it
1637 bodyEnc = KURL::encode_string(tmpbody); // Recode for the URL
1639 bodyEnc = KURL::encode_string(formData.flattenToString().deprecatedString());
1641 nvps.append(String::sprintf("body=%s", bodyEnc.latin1()).deprecatedString());
1646 if (strcmp(action, "get") == 0) {
1647 if (u.protocol() != "mailto")
1648 u.setQuery(formData.flattenToString().deprecatedString());
1649 request.setDoPost(false);
1651 request.postData = formData;
1652 request.setDoPost(true);
1654 // construct some user headers if necessary
1655 if (contentType.isNull() || contentType == "application/x-www-form-urlencoded")
1656 request.setContentType("Content-Type: application/x-www-form-urlencoded");
1657 else // contentType must be "multipart/form-data"
1658 request.setContentType("Content-Type: " + contentType + "; boundary=" + boundary);
1661 if (d->m_doc->parsing() || d->m_runningScripts > 0) {
1662 if (d->m_submitForm)
1664 d->m_submitForm = new FramePrivate::SubmitForm;
1665 d->m_submitForm->submitAction = action;
1666 d->m_submitForm->submitUrl = url;
1667 d->m_submitForm->submitFormData = formData;
1668 d->m_submitForm->target = _target;
1669 d->m_submitForm->submitContentType = contentType;
1670 d->m_submitForm->submitBoundary = boundary;
1673 submitForm(request);
1677 void Frame::parentCompleted()
1679 if (d->m_scheduledRedirection != noRedirectionScheduled && !d->m_redirectionTimer.isActive())
1680 startRedirectionTimer();
1683 void Frame::childCompleted(bool complete)
1685 if (complete && !tree()->parent())
1686 d->m_bPendingChildRedirection = true;
1690 int Frame::zoomFactor() const
1692 return d->m_zoomFactor;
1695 void Frame::setZoomFactor(int percent)
1697 if (d->m_zoomFactor == percent)
1700 d->m_zoomFactor = percent;
1703 d->m_doc->recalcStyle(Node::Force);
1705 for (Frame* child = tree()->firstChild(); child; child = child->tree()->nextSibling())
1706 child->setZoomFactor(d->m_zoomFactor);
1708 if (d->m_doc && d->m_doc->renderer() && d->m_doc->renderer()->needsLayout())
1712 void Frame::setJSStatusBarText(const String& text)
1714 d->m_kjsStatusBarText = text;
1715 setStatusBarText(d->m_kjsStatusBarText);
1718 void Frame::setJSDefaultStatusBarText(const String& text)
1720 d->m_kjsDefaultStatusBarText = text;
1721 setStatusBarText(d->m_kjsDefaultStatusBarText);
1724 String Frame::jsStatusBarText() const
1726 return d->m_kjsStatusBarText;
1729 String Frame::jsDefaultStatusBarText() const
1731 return d->m_kjsDefaultStatusBarText;
1734 String Frame::referrer() const
1736 return d->m_referrer;
1739 String Frame::lastModified() const
1741 return d->m_lastModified;
1744 void Frame::reparseConfiguration()
1746 setAutoloadImages(d->m_settings->autoLoadImages());
1748 d->m_bJScriptEnabled = d->m_settings->isJavaScriptEnabled();
1749 d->m_bJavaEnabled = d->m_settings->isJavaEnabled();
1750 d->m_bPluginsEnabled = d->m_settings->isPluginsEnabled();
1752 const KURL& userStyleSheetLocation = d->m_settings->userStyleSheetLocation();
1753 if (!userStyleSheetLocation.isEmpty())
1754 setUserStyleSheetLocation(userStyleSheetLocation);
1756 setUserStyleSheet(String());
1758 // FIXME: It's not entirely clear why the following is needed.
1759 // The document automatically does this as required when you set the style sheet.
1760 // But we had problems when this code was removed. Details are in
1761 // <http://bugzilla.opendarwin.org/show_bug.cgi?id=8079>.
1763 d->m_doc->updateStyleSelector();
1766 bool Frame::shouldDragAutoNode(Node *node, const IntPoint& point) const
1772 bool Frame::isPointInsideSelection(const IntPoint& point)
1774 // Treat a collapsed selection like no selection.
1775 if (!selectionController()->isRange())
1777 if (!document()->renderer())
1780 RenderObject::NodeInfo nodeInfo(true, true);
1781 document()->renderer()->layer()->hitTest(nodeInfo, point);
1782 Node *innerNode = nodeInfo.innerNode();
1783 if (!innerNode || !innerNode->renderer())
1786 Position pos(innerNode->renderer()->positionForPoint(point).deepEquivalent());
1790 Node *n = selectionController()->start().node();
1792 if (n == pos.node()) {
1793 if ((n == selectionController()->start().node() && pos.offset() < selectionController()->start().offset()) ||
1794 (n == selectionController()->end().node() && pos.offset() > selectionController()->end().offset())) {
1799 if (n == selectionController()->end().node())
1801 n = n->traverseNextNode();
1807 void Frame::selectClosestWordFromMouseEvent(const PlatformMouseEvent& mouse, Node *innerNode)
1809 Selection newSelection;
1811 if (innerNode && innerNode->renderer() && mouseDownMayStartSelect() && innerNode->renderer()->shouldSelect()) {
1812 IntPoint vPoint = view()->viewportToContents(mouse.pos());
1813 VisiblePosition pos(innerNode->renderer()->positionForPoint(vPoint));
1814 if (pos.isNotNull()) {
1815 newSelection = Selection(pos);
1816 newSelection.expandUsingGranularity(WordGranularity);
1820 if (newSelection.isRange()) {
1821 d->m_selectionGranularity = WordGranularity;
1822 d->m_beganSelectingText = true;
1825 if (shouldChangeSelection(newSelection))
1826 selectionController()->setSelection(newSelection);
1829 void Frame::handleMousePressEventDoubleClick(const MouseEventWithHitTestResults& event)
1831 if (event.event().button() == LeftButton) {
1832 if (selectionController()->isRange())
1833 // A double-click when range is already selected
1834 // should not change the selection. So, do not call
1835 // selectClosestWordFromMouseEvent, but do set
1836 // m_beganSelectingText to prevent handleMouseReleaseEvent
1837 // from setting caret selection.
1838 d->m_beganSelectingText = true;
1840 selectClosestWordFromMouseEvent(event.event(), event.targetNode());
1844 void Frame::handleMousePressEventTripleClick(const MouseEventWithHitTestResults& event)
1846 Node *innerNode = event.targetNode();
1848 if (event.event().button() == LeftButton && innerNode && innerNode->renderer() &&
1849 mouseDownMayStartSelect() && innerNode->renderer()->shouldSelect()) {
1850 Selection newSelection;
1851 IntPoint vPoint = view()->viewportToContents(event.event().pos());
1852 VisiblePosition pos(innerNode->renderer()->positionForPoint(vPoint));
1853 if (pos.isNotNull()) {
1854 newSelection = Selection(pos);
1855 newSelection.expandUsingGranularity(ParagraphGranularity);
1857 if (newSelection.isRange()) {
1858 d->m_selectionGranularity = ParagraphGranularity;
1859 d->m_beganSelectingText = true;
1862 if (shouldChangeSelection(newSelection))
1863 selectionController()->setSelection(newSelection);
1867 void Frame::handleMousePressEventSingleClick(const MouseEventWithHitTestResults& event)
1869 Node *innerNode = event.targetNode();
1871 if (event.event().button() == LeftButton) {
1872 if (innerNode && innerNode->renderer() &&
1873 mouseDownMayStartSelect() && innerNode->renderer()->shouldSelect()) {
1875 // Extend the selection if the Shift key is down, unless the click is in a link.
1876 bool extendSelection = event.event().shiftKey() && !event.isOverLink();
1878 // Don't restart the selection when the mouse is pressed on an
1879 // existing selection so we can allow for text dragging.
1880 IntPoint vPoint = view()->viewportToContents(event.event().pos());
1881 if (!extendSelection && isPointInsideSelection(vPoint))
1884 VisiblePosition visiblePos(innerNode->renderer()->positionForPoint(vPoint));
1885 if (visiblePos.isNull())
1886 visiblePos = VisiblePosition(innerNode, innerNode->caretMinOffset(), DOWNSTREAM);
1887 Position pos = visiblePos.deepEquivalent();
1889 Selection newSelection = selectionController()->selection();
1890 if (extendSelection && newSelection.isCaretOrRange()) {
1891 selectionController()->clearModifyBias();
1893 // See <rdar://problem/3668157> REGRESSION (Mail): shift-click deselects when selection
1894 // was created right-to-left
1895 Position start = newSelection.start();
1896 Position end = newSelection.end();
1897 short before = Range::compareBoundaryPoints(pos.node(), pos.offset(), start.node(), start.offset());
1899 newSelection = Selection(pos, end);
1901 newSelection = Selection(start, pos);
1903 if (d->m_selectionGranularity != CharacterGranularity)
1904 newSelection.expandUsingGranularity(d->m_selectionGranularity);
1905 d->m_beganSelectingText = true;
1907 newSelection = Selection(visiblePos);
1908 d->m_selectionGranularity = CharacterGranularity;
1911 if (shouldChangeSelection(newSelection))
1912 selectionController()->setSelection(newSelection);
1917 void Frame::handleMousePressEvent(const MouseEventWithHitTestResults& event)
1919 Node *innerNode = event.targetNode();
1921 d->m_mousePressNode = innerNode;
1922 d->m_dragStartPos = event.event().pos();
1924 if (event.event().button() == LeftButton || event.event().button() == MiddleButton) {
1925 d->m_bMousePressed = true;
1926 d->m_beganSelectingText = false;
1928 if (event.event().clickCount() == 2) {
1929 handleMousePressEventDoubleClick(event);
1932 if (event.event().clickCount() >= 3) {
1933 handleMousePressEventTripleClick(event);
1936 handleMousePressEventSingleClick(event);
1940 void Frame::handleMouseMoveEvent(const MouseEventWithHitTestResults& event)
1942 // Mouse not pressed. Do nothing.
1943 if (!d->m_bMousePressed)
1946 Node *innerNode = event.targetNode();
1948 if (event.event().button() != 0 || !innerNode || !innerNode->renderer() || !mouseDownMayStartSelect() || !innerNode->renderer()->shouldSelect())
1951 // handle making selection
1952 IntPoint vPoint = view()->viewportToContents(event.event().pos());
1953 VisiblePosition pos(innerNode->renderer()->positionForPoint(vPoint));
1955 // Don't modify the selection if we're not on a node.
1959 // Restart the selection if this is the first mouse move. This work is usually
1960 // done in handleMousePressEvent, but not if the mouse press was on an existing selection.
1961 Selection newSelection = selectionController()->selection();
1962 selectionController()->clearModifyBias();
1964 if (!d->m_beganSelectingText) {
1965 d->m_beganSelectingText = true;
1966 newSelection = Selection(pos);
1969 newSelection.setExtent(pos);
1970 if (d->m_selectionGranularity != CharacterGranularity)
1971 newSelection.expandUsingGranularity(d->m_selectionGranularity);
1973 if (shouldChangeSelection(newSelection))
1974 selectionController()->setSelection(newSelection);
1977 void Frame::handleMouseReleaseEvent(const MouseEventWithHitTestResults& event)
1979 stopAutoscrollTimer();
1981 // Used to prevent mouseMoveEvent from initiating a drag before
1982 // the mouse is pressed again.
1983 d->m_bMousePressed = false;
1985 // Clear the selection if the mouse didn't move after the last mouse press.
1986 // We do this so when clicking on the selection, the selection goes away.
1987 // However, if we are editing, place the caret.
1988 if (mouseDownMayStartSelect() && !d->m_beganSelectingText
1989 && d->m_dragStartPos == event.event().pos()
1990 && selectionController()->isRange()) {
1991 Selection newSelection;
1992 Node *node = event.targetNode();
1993 if (node && node->isContentEditable() && node->renderer()) {
1994 IntPoint vPoint = view()->viewportToContents(event.event().pos());
1995 VisiblePosition pos = node->renderer()->positionForPoint(vPoint);
1996 newSelection = Selection(pos);
1998 if (shouldChangeSelection(newSelection))
1999 selectionController()->setSelection(newSelection);
2002 notifyRendererOfSelectionChange(true);
2004 selectFrameElementInParentIfFullySelected();
2007 void Frame::selectAll()
2012 Node* root = selectionController()->isContentEditable() ? selectionController()->rootEditableElement() : d->m_doc->documentElement();
2013 selectContentsOfNode(root);
2014 selectFrameElementInParentIfFullySelected();
2015 notifyRendererOfSelectionChange(true);
2018 bool Frame::selectContentsOfNode(Node* node)
2020 Selection newSelection(Selection::selectionFromContentsOfNode(node));
2021 if (shouldChangeSelection(newSelection)) {
2022 selectionController()->setSelection(newSelection);
2028 bool Frame::shouldChangeSelection(const Selection& newSelection) const
2030 return shouldChangeSelection(selectionController()->selection(), newSelection, newSelection.affinity(), false);
2033 bool Frame::shouldDeleteSelection(const Selection& newSelection) const
2038 bool Frame::shouldBeginEditing(const Range *range) const
2043 bool Frame::shouldEndEditing(const Range *range) const
2048 bool Frame::isContentEditable() const
2052 return d->m_doc->inDesignMode();
2055 void Frame::textFieldDidBeginEditing(Element* input)
2059 void Frame::textFieldDidEndEditing(Element* input)
2063 void Frame::textDidChangeInTextField(Element* input)
2067 bool Frame::doTextFieldCommandFromEvent(Element* input, const PlatformKeyboardEvent* evt)
2072 void Frame::textWillBeDeletedInTextField(Element* input)
2076 void Frame::textDidChangeInTextArea(Element* input)
2080 bool Frame::isSelectionInPasswordField()
2082 Node* startNode = selectionController()->start().node();
2084 startNode = startNode->shadowAncestorNode();
2085 return startNode && startNode->hasTagName(inputTag) && static_cast<HTMLInputElement*>(startNode)->inputType() == HTMLInputElement::PASSWORD;
2088 EditCommand* Frame::lastEditCommand()
2090 return d->m_lastEditCommand.get();
2093 static void dispatchEditableContentChangedEvents(const EditCommand& command)
2095 Element* startRoot = command.startingRootEditableElement();
2096 Element* endRoot = command.endingRootEditableElement();
2099 startRoot->dispatchEvent(new Event(khtmlEditableContentChangedEvent, false, false), ec, true);
2100 if (endRoot && endRoot != startRoot)
2101 endRoot->dispatchEvent(new Event(khtmlEditableContentChangedEvent, false, false), ec, true);
2104 void Frame::appliedEditing(PassRefPtr<EditCommand> cmd)
2106 dispatchEditableContentChangedEvents(*cmd);
2108 Selection newSelection(cmd->endingSelection());
2109 if (shouldChangeSelection(newSelection))
2110 selectionController()->setSelection(newSelection, false);
2112 // Now set the typing style from the command. Clear it when done.
2113 // This helps make the case work where you completely delete a piece
2114 // of styled text and then type a character immediately after.
2115 // That new character needs to take on the style of the just-deleted text.
2116 // FIXME: Improve typing style.
2117 // See this bug: <rdar://problem/3769899> Implementation of typing style needs improvement
2118 if (cmd->typingStyle()) {
2119 setTypingStyle(cmd->typingStyle());
2120 cmd->setTypingStyle(0);
2123 // Command will be equal to last edit command only in the case of typing
2124 if (d->m_lastEditCommand == cmd)
2125 assert(cmd->isTypingCommand());
2127 // Only register a new undo command if the command passed in is
2128 // different from the last command
2129 d->m_lastEditCommand = cmd.get();
2130 registerCommandForUndo(cmd);
2132 respondToChangedContents(newSelection);
2135 void Frame::unappliedEditing(PassRefPtr<EditCommand> cmd)
2137 dispatchEditableContentChangedEvents(*cmd);
2139 Selection newSelection(cmd->startingSelection());
2140 if (shouldChangeSelection(newSelection))
2141 selectionController()->setSelection(newSelection, true);
2143 d->m_lastEditCommand = 0;
2144 registerCommandForRedo(cmd);
2145 respondToChangedContents(newSelection);
2148 void Frame::reappliedEditing(PassRefPtr<EditCommand> cmd)
2150 dispatchEditableContentChangedEvents(*cmd);
2152 Selection newSelection(cmd->endingSelection());
2153 if (shouldChangeSelection(newSelection))
2154 selectionController()->setSelection(newSelection, true);
2156 d->m_lastEditCommand = 0;
2157 registerCommandForUndo(cmd);
2158 respondToChangedContents(newSelection);
2161 CSSMutableStyleDeclaration *Frame::typingStyle() const
2163 return d->m_typingStyle.get();
2166 void Frame::setTypingStyle(CSSMutableStyleDeclaration *style)
2168 d->m_typingStyle = style;
2171 void Frame::clearTypingStyle()
2173 d->m_typingStyle = 0;
2176 JSValue* Frame::executeScript(const String& filename, int baseLine, Node* n, const String& script)
2178 // FIXME: This is missing stuff that the other executeScript has.
2179 // --> d->m_runningScripts and submitFormAgain.
2181 KJSProxy* proxy = jScript();
2184 JSValue* ret = proxy->evaluate(filename, baseLine, script, n);
2185 Document::updateDocumentsRendering();
2189 Frame *Frame::opener()
2194 void Frame::setOpener(Frame* opener)
2197 d->m_opener->d->m_openedFrames.remove(this);
2199 opener->d->m_openedFrames.add(this);
2200 d->m_opener = opener;
2203 bool Frame::openedByJS()
2205 return d->m_openedByJS;
2208 void Frame::setOpenedByJS(bool _openedByJS)
2210 d->m_openedByJS = _openedByJS;
2213 bool Frame::tabsToLinks() const
2218 bool Frame::tabsToAllControls() const
2223 void Frame::copyToPasteboard()
2228 void Frame::cutToPasteboard()
2233 void Frame::pasteFromPasteboard()
2235 issuePasteCommand();
2238 void Frame::pasteAndMatchStyle()
2240 issuePasteAndMatchStyleCommand();
2243 bool Frame::mayCopy()
2245 return !isSelectionInPasswordField();
2248 void Frame::transpose()
2250 issueTransposeCommand();
2264 void Frame::computeAndSetTypingStyle(CSSStyleDeclaration *style, EditAction editingAction)
2266 if (!style || style->length() == 0) {
2271 // Calculate the current typing style.
2272 RefPtr<CSSMutableStyleDeclaration> mutableStyle = style->makeMutable();
2273 if (typingStyle()) {
2274 typingStyle()->merge(mutableStyle.get());
2275 mutableStyle = typingStyle();
2278 Node *node = selectionController()->selection().visibleStart().deepEquivalent().node();
2279 CSSComputedStyleDeclaration computedStyle(node);
2280 computedStyle.diff(mutableStyle.get());
2282 // Handle block styles, substracting these from the typing style.
2283 RefPtr<CSSMutableStyleDeclaration> blockStyle = mutableStyle->copyBlockProperties();
2284 blockStyle->diff(mutableStyle.get());
2285 if (document() && blockStyle->length() > 0)
2286 applyCommand(new ApplyStyleCommand(document(), blockStyle.get(), editingAction));
2288 // Set the remaining style as the typing style.
2289 d->m_typingStyle = mutableStyle.release();
2292 void Frame::applyStyle(CSSStyleDeclaration *style, EditAction editingAction)
2294 switch (selectionController()->state()) {
2295 case Selection::NONE:
2298 case Selection::CARET: {
2299 computeAndSetTypingStyle(style, editingAction);
2302 case Selection::RANGE:
2303 if (document() && style)
2304 applyCommand(new ApplyStyleCommand(document(), style, editingAction));
2309 void Frame::applyParagraphStyle(CSSStyleDeclaration *style, EditAction editingAction)
2311 switch (selectionController()->state()) {
2312 case Selection::NONE:
2315 case Selection::CARET:
2316 case Selection::RANGE:
2317 if (document() && style)
2318 applyCommand(new ApplyStyleCommand(document(), style, editingAction, ApplyStyleCommand::ForceBlockProperties));
2323 static void updateState(CSSMutableStyleDeclaration *desiredStyle, CSSComputedStyleDeclaration *computedStyle, bool& atStart, Frame::TriState& state)
2325 DeprecatedValueListConstIterator<CSSProperty> end;
2326 for (DeprecatedValueListConstIterator<CSSProperty> it = desiredStyle->valuesIterator(); it != end; ++it) {
2327 int propertyID = (*it).id();
2328 String desiredProperty = desiredStyle->getPropertyValue(propertyID);
2329 String computedProperty = computedStyle->getPropertyValue(propertyID);
2330 Frame::TriState propertyState = equalIgnoringCase(desiredProperty, computedProperty)
2331 ? Frame::trueTriState : Frame::falseTriState;
2333 state = propertyState;
2335 } else if (state != propertyState) {
2336 state = Frame::mixedTriState;
2342 Frame::TriState Frame::selectionListState() const
2344 TriState state = falseTriState;
2346 if (!selectionController()->isRange()) {
2347 Node* selectionNode = selectionController()->selection().start().node();
2348 if (enclosingList(selectionNode))
2349 return trueTriState;
2351 //FIXME: Support ranges
2357 Frame::TriState Frame::selectionHasStyle(CSSStyleDeclaration *style) const
2359 bool atStart = true;
2360 TriState state = falseTriState;
2362 RefPtr<CSSMutableStyleDeclaration> mutableStyle = style->makeMutable();
2364 if (!selectionController()->isRange()) {
2366 RefPtr<CSSComputedStyleDeclaration> selectionStyle = selectionComputedStyle(nodeToRemove);
2367 if (!selectionStyle)
2368 return falseTriState;
2369 updateState(mutableStyle.get(), selectionStyle.get(), atStart, state);
2371 ExceptionCode ec = 0;
2372 nodeToRemove->remove(ec);
2376 for (Node* node = selectionController()->start().node(); node; node = node->traverseNextNode()) {
2377 RefPtr<CSSComputedStyleDeclaration> computedStyle = new CSSComputedStyleDeclaration(node);
2379 updateState(mutableStyle.get(), computedStyle.get(), atStart, state);
2380 if (state == mixedTriState)
2382 if (node == selectionController()->end().node())
2390 bool Frame::selectionStartHasStyle(CSSStyleDeclaration *style) const
2393 RefPtr<CSSStyleDeclaration> selectionStyle = selectionComputedStyle(nodeToRemove);
2394 if (!selectionStyle)
2397 RefPtr<CSSMutableStyleDeclaration> mutableStyle = style->makeMutable();
2400 DeprecatedValueListConstIterator<CSSProperty> end;
2401 for (DeprecatedValueListConstIterator<CSSProperty> it = mutableStyle->valuesIterator(); it != end; ++it) {
2402 int propertyID = (*it).id();
2403 if (!equalIgnoringCase(mutableStyle->getPropertyValue(propertyID), selectionStyle->getPropertyValue(propertyID))) {
2410 ExceptionCode ec = 0;
2411 nodeToRemove->remove(ec);
2418 String Frame::selectionStartStylePropertyValue(int stylePropertyID) const
2421 RefPtr<CSSStyleDeclaration> selectionStyle = selectionComputedStyle(nodeToRemove);
2422 if (!selectionStyle)
2425 String value = selectionStyle->getPropertyValue(stylePropertyID);
2428 ExceptionCode ec = 0;
2429 nodeToRemove->remove(ec);
2436 CSSComputedStyleDeclaration *Frame::selectionComputedStyle(Node *&nodeToRemove) const
2443 if (selectionController()->isNone())
2446 RefPtr<Range> range(selectionController()->toRange());
2447 Position pos = range->editingStartPosition();
2449 Element *elem = pos.element();
2453 RefPtr<Element> styleElement = elem;
2454 ExceptionCode ec = 0;
2456 if (d->m_typingStyle) {
2457 styleElement = document()->createElementNS(xhtmlNamespaceURI, "span", ec);
2460 styleElement->setAttribute(styleAttr, d->m_typingStyle->cssText().impl(), ec);
2463 styleElement->appendChild(document()->createEditingTextNode(""), ec);
2466 if (elem->renderer() && elem->renderer()->canHaveChildren()) {
2467 elem->appendChild(styleElement, ec);
2469 Node *parent = elem->parent();
2470 Node *next = elem->nextSibling();
2473 parent->insertBefore(styleElement, next, ec);
2475 parent->appendChild(styleElement, ec);
2480 nodeToRemove = styleElement.get();
2483 return new CSSComputedStyleDeclaration(styleElement);
2486 void Frame::applyEditingStyleToBodyElement() const
2491 RefPtr<NodeList> list = d->m_doc->getElementsByTagName("body");
2492 unsigned len = list->length();
2493 for (unsigned i = 0; i < len; i++) {
2494 applyEditingStyleToElement(static_cast<Element*>(list->item(i)));
2498 void Frame::removeEditingStyleFromBodyElement() const
2503 RefPtr<NodeList> list = d->m_doc->getElementsByTagName("body");
2504 unsigned len = list->length();
2505 for (unsigned i = 0; i < len; i++) {
2506 removeEditingStyleFromElement(static_cast<Element*>(list->item(i)));
2510 void Frame::applyEditingStyleToElement(Element* element) const
2515 CSSStyleDeclaration* style = element->style();
2518 ExceptionCode ec = 0;
2519 style->setProperty(CSS_PROP_WORD_WRAP, "break-word", false, ec);
2521 style->setProperty(CSS_PROP__WEBKIT_NBSP_MODE, "space", false, ec);
2523 style->setProperty(CSS_PROP__WEBKIT_LINE_BREAK, "after-white-space", false, ec);
2527 void Frame::removeEditingStyleFromElement(Element*) const
2531 bool Frame::isCharacterSmartReplaceExempt(UChar, bool)
2538 static HashSet<Frame*> lifeSupportSet;
2541 void Frame::endAllLifeSupport()
2544 HashSet<Frame*> lifeSupportCopy = lifeSupportSet;
2545 HashSet<Frame*>::iterator end = lifeSupportCopy.end();
2546 for (HashSet<Frame*>::iterator it = lifeSupportCopy.begin(); it != end; ++it)
2547 (*it)->endLifeSupport();
2551 void Frame::keepAlive()
2553 if (d->m_lifeSupportTimer.isActive())
2557 lifeSupportSet.add(this);
2559 d->m_lifeSupportTimer.startOneShot(0);
2562 void Frame::endLifeSupport()
2564 if (!d->m_lifeSupportTimer.isActive())
2566 d->m_lifeSupportTimer.stop();
2568 lifeSupportSet.remove(this);
2573 void Frame::lifeSupportTimerFired(Timer<Frame>*)
2576 lifeSupportSet.remove(this);
2581 // Workaround for the fact that it's hard to delete a frame.
2582 // Call this after doing user-triggered selections to make it easy to delete the frame you entirely selected.
2583 // Can't do this implicitly as part of every setSelection call because in some contexts it might not be good
2584 // for the focus to move to another frame. So instead we call it from places where we are selecting with the
2585 // mouse or the keyboard after setting the selection.
2586 void Frame::selectFrameElementInParentIfFullySelected()
2588 // Find the parent frame; if there is none, then we have nothing to do.
2589 Frame *parent = tree()->parent();
2592 FrameView *parentView = parent->view();
2596 // Check if the selection contains the entire frame contents; if not, then there is nothing to do.
2597 if (!selectionController()->isRange())
2599 if (!isStartOfDocument(selectionController()->selection().visibleStart()))
2601 if (!isEndOfDocument(selectionController()->selection().visibleEnd()))
2604 // Get to the <iframe> or <frame> (or even <object>) element in the parent frame.
2605 Document *doc = document();
2608 Element *ownerElement = doc->ownerElement();
2611 Node *ownerElementParent = ownerElement->parentNode();
2612 if (!ownerElementParent)
2615 // This method's purpose is it to make it easier to select iframes (in order to delete them). Don't do anything if the iframe isn't deletable.
2616 if (!ownerElementParent->isContentEditable())
2619 // Create compute positions before and after the element.
2620 unsigned ownerElementNodeIndex = ownerElement->nodeIndex();
2621 VisiblePosition beforeOwnerElement(VisiblePosition(ownerElementParent, ownerElementNodeIndex, SEL_DEFAULT_AFFINITY));
2622 VisiblePosition afterOwnerElement(VisiblePosition(ownerElementParent, ownerElementNodeIndex + 1, VP_UPSTREAM_IF_POSSIBLE));
2624 // Focus on the parent frame, and then select from before this element to after.
2625 Selection newSelection(beforeOwnerElement, afterOwnerElement);
2626 if (parent->shouldChangeSelection(newSelection)) {
2627 parentView->setFocus();
2628 parent->selectionController()->setSelection(newSelection);
2632 void Frame::handleFallbackContent()
2634 Element* owner = ownerElement();
2635 if (!owner || !owner->hasTagName(objectTag))
2637 static_cast<HTMLObjectElement*>(owner)->renderFallbackContent();
2640 void Frame::setSettings(Settings *settings)
2642 d->m_settings = settings;
2645 void Frame::provisionalLoadStarted()
2647 // we don't want to wait until we get an actual http response back
2648 // to cancel pending redirects, otherwise they might fire before
2650 cancelRedirection(true);
2653 bool Frame::userGestureHint()
2655 Frame *rootFrame = this;
2656 while (rootFrame->tree()->parent())
2657 rootFrame = rootFrame->tree()->parent();
2659 if (rootFrame->jScript())
2660 return rootFrame->jScript()->interpreter()->wasRunByUserGesture();
2662 return true; // If JavaScript is disabled, a user gesture must have initiated the navigation
2665 RenderObject *Frame::renderer() const
2667 Document *doc = document();
2668 return doc ? doc->renderer() : 0;
2671 Element* Frame::ownerElement()
2673 return d->m_ownerElement;
2676 RenderPart* Frame::ownerRenderer()
2678 Element* ownerElement = d->m_ownerElement;
2681 return static_cast<RenderPart*>(ownerElement->renderer());
2684 IntRect Frame::selectionRect() const
2686 RenderView *root = static_cast<RenderView*>(renderer());
2690 return root->selectionRect();
2693 // returns FloatRect because going through IntRect would truncate any floats
2694 FloatRect Frame::visibleSelectionRect() const
2699 return intersection(selectionRect(), d->m_view->visibleContentRect());
2702 bool Frame::isFrameSet() const
2704 Document* document = d->m_doc.get();
2705 if (!document || !document->isHTMLDocument())
2707 Node *body = static_cast<HTMLDocument*>(document)->body();
2708 return body && body->renderer() && body->hasTagName(framesetTag);
2711 bool Frame::openURL(const KURL& URL)
2713 ASSERT_NOT_REACHED();
2717 void Frame::didNotOpenURL(const KURL& URL)
2719 if (d->m_submittedFormURL == URL)
2720 d->m_submittedFormURL = KURL();
2723 // Scans logically forward from "start", including any child frames
2724 static HTMLFormElement *scanForForm(Node *start)
2727 for (n = start; n; n = n->traverseNextNode()) {
2728 if (n->hasTagName(formTag))
2729 return static_cast<HTMLFormElement*>(n);
2730 else if (n->isHTMLElement() && static_cast<HTMLElement*>(n)->isGenericFormElement())
2731 return static_cast<HTMLGenericFormElement*>(n)->form();
2732 else if (n->hasTagName(frameTag) || n->hasTagName(iframeTag)) {
2733 Node *childDoc = static_cast<HTMLFrameElement*>(n)->contentDocument();
2734 if (HTMLFormElement *frameResult = scanForForm(childDoc))
2741 // We look for either the form containing the current focus, or for one immediately after it
2742 HTMLFormElement *Frame::currentForm() const
2744 // start looking either at the active (first responder) node, or where the selection is
2745 Node *start = d->m_doc ? d->m_doc->focusNode() : 0;
2747 start = selectionController()->start().node();
2749 // try walking up the node tree to find a form element
2751 for (n = start; n; n = n->parentNode()) {
2752 if (n->hasTagName(formTag))
2753 return static_cast<HTMLFormElement*>(n);
2754 else if (n->isHTMLElement()
2755 && static_cast<HTMLElement*>(n)->isGenericFormElement())
2756 return static_cast<HTMLGenericFormElement*>(n)->form();
2759 // try walking forward in the node tree to find a form element
2760 return start ? scanForForm(start) : 0;
2763 void Frame::setEncoding(const String& name, bool userChosen)
2765 if (!d->m_workingURL.isEmpty())
2766 receivedFirstData();
2767 d->m_encoding = name;
2768 d->m_haveEncoding = userChosen;
2771 void Frame::addData(const char *bytes, int length)
2773 ASSERT(d->m_workingURL.isEmpty());
2775 ASSERT(d->m_doc->parsing());
2776 write(bytes, length);
2779 // FIXME: should this go in SelectionController?
2780 void Frame::revealSelection(const RenderLayer::ScrollAlignment& alignment) const
2784 switch (selectionController()->state()) {
2785 case Selection::NONE:
2788 case Selection::CARET:
2789 rect = selectionController()->caretRect();
2792 case Selection::RANGE:
2793 rect = selectionRect();
2797 Position start = selectionController()->start();
2798 Position end = selectionController()->end();
2800 ASSERT(start.node());
2801 if (start.node() && start.node()->renderer()) {
2802 RenderLayer *layer = start.node()->renderer()->enclosingLayer();
2804 ASSERT(!end.node() || !end.node()->renderer()
2805 || (end.node()->renderer()->enclosingLayer() == layer));
2806 layer->scrollRectToVisible(rect, alignment, alignment);
2811 void Frame::revealCaret(const RenderLayer::ScrollAlignment& alignment) const
2813 if (!hasSelection())
2816 Position extent = selectionController()->extent();
2817 if (extent.node() && extent.node()->renderer()) {
2818 IntRect extentRect = VisiblePosition(extent).caretRect();
2819 RenderLayer* layer = extent.node()->renderer()->enclosingLayer();
2821 layer->scrollRectToVisible(extentRect, alignment, alignment);
2825 // FIXME: should this be here?
2826 bool Frame::scrollOverflow(ScrollDirection direction, ScrollGranularity granularity)
2832 Node *node = document()->focusNode();
2834 node = d->m_mousePressNode.get();
2838 RenderObject *r = node->renderer();
2840 return r->scroll(direction, granularity);
2847 void Frame::handleAutoscroll(RenderLayer* layer)
2849 if (d->m_autoscrollTimer.isActive())
2851 d->m_autoscrollLayer = layer;
2852 startAutoscrollTimer();
2855 void Frame::autoscrollTimerFired(Timer<Frame>*)
2857 if (!d->m_bMousePressed){
2858 stopAutoscrollTimer();
2861 if (d->m_autoscrollLayer) {
2862 d->m_autoscrollLayer->autoscroll();
2866 RenderObject::NodeInfo Frame::nodeInfoAtPoint(const IntPoint& point, bool allowShadowContent)
2868 RenderObject::NodeInfo nodeInfo(true, true);
2869 renderer()->layer()->hitTest(nodeInfo, point);
2873 IntPoint widgetPoint(point);
2876 n = nodeInfo.innerNode();
2877 if (!n || !n->renderer() || !n->renderer()->isWidget())
2879 widget = static_cast<RenderWidget*>(n->renderer())->widget();
2880 if (!widget || !widget->isFrameView())
2882 Frame* frame = static_cast<HTMLFrameElement*>(n)->contentFrame();
2883 if (!frame || !frame->renderer())
2886 n->renderer()->absolutePosition(absX, absY, true);
2887 FrameView *view = static_cast<FrameView*>(widget);
2888 widgetPoint.setX(widgetPoint.x() - absX + view->contentsX());
2889 widgetPoint.setY(widgetPoint.y() - absY + view->contentsY());
2891 RenderObject::NodeInfo widgetNodeInfo(true, true);
2892 frame->renderer()->layer()->hitTest(widgetNodeInfo, widgetPoint);
2893 nodeInfo = widgetNodeInfo;
2896 if (!allowShadowContent) {
2897 Node* node = nodeInfo.innerNode();
2899 node = node->shadowAncestorNode();
2900 nodeInfo.setInnerNode(node);
2901 node = nodeInfo.innerNonSharedNode();
2903 node = node->shadowAncestorNode();
2904 nodeInfo.setInnerNonSharedNode(node);
2909 bool Frame::hasSelection()
2911 if (selectionController()->isNone())
2914 // If a part has a selection, it should also have a document.
2920 void Frame::startAutoscrollTimer()
2922 d->m_autoscrollTimer.startRepeating(autoscrollInterval);
2925 void Frame::stopAutoscrollTimer()
2927 d->m_autoscrollLayer = 0;
2928 d->m_autoscrollTimer.stop();
2931 // FIXME: why is this here instead of on the FrameView?
2932 void Frame::paint(GraphicsContext* p, const IntRect& rect)
2936 if (!document() || document()->printing())
2937 fillWithRed = false; // Printing, don't fill with red (can't remember why).
2938 else if (document()->ownerElement())
2939 fillWithRed = false; // Subframe, don't fill with red.
2940 else if (view() && view()->isTransparent())
2941 fillWithRed = false; // Transparent, don't fill with red.
2942 else if (d->m_paintRestriction == PaintRestrictionSelectionOnly || d->m_paintRestriction == PaintRestrictionSelectionOnlyWhiteText)
2943 fillWithRed = false; // Selections are transparent, don't fill with red.
2944 else if (d->m_elementToDraw)
2945 fillWithRed = false; // Element images are transparent, don't fill with red.
2950 p->fillRect(rect, Color(0xFF, 0, 0));
2954 // d->m_elementToDraw is used to draw only one element
2955 RenderObject *eltRenderer = d->m_elementToDraw ? d->m_elementToDraw->renderer() : 0;
2956 if (d->m_paintRestriction == PaintRestrictionNone)
2957 renderer()->document()->invalidateRenderedRectsForMarkersInRect(rect);
2958 renderer()->layer()->paint(p, rect, d->m_paintRestriction, eltRenderer);
2961 // Regions may have changed as a result of the visibility/z-index of element changing.
2962 if (renderer()->document()->dashboardRegionsDirty())
2963 renderer()->view()->frameView()->updateDashboardRegions();
2966 LOG_ERROR("called Frame::paint with nil renderer");
2971 void Frame::adjustPageHeight(float *newBottom, float oldTop, float oldBottom, float bottomLimit)
2973 RenderView *root = static_cast<RenderView*>(document()->renderer());
2975 // Use a context with painting disabled.
2976 GraphicsContext context(0);
2977 root->setTruncatedAt((int)floorf(oldBottom));
2978 IntRect dirtyRect(0, (int)floorf(oldTop), root->docWidth(), (int)ceilf(oldBottom - oldTop));
2979 root->layer()->paint(&context, dirtyRect);
2980 *newBottom = root->bestTruncatedAt();
2981 if (*newBottom == 0)
2982 *newBottom = oldBottom;
2984 *newBottom = oldBottom;
2989 PausedTimeouts *Frame::pauseTimeouts()
2992 if (d->m_doc && d->m_doc->svgExtensions())
2993 d->m_doc->accessSVGExtensions()->pauseAnimations();
2996 if (d->m_doc && d->m_jscript) {
2997 if (Window* w = Window::retrieveWindow(this))
2998 return w->pauseTimeouts();
3003 void Frame::resumeTimeouts(PausedTimeouts* t)
3006 if (d->m_doc && d->m_doc->svgExtensions())
3007 d->m_doc->accessSVGExtensions()->unpauseAnimations();
3010 if (d->m_doc && d->m_jscript && d->m_bJScriptEnabled) {
3011 if (Window* w = Window::retrieveWindow(this))
3012 w->resumeTimeouts(t);
3016 bool Frame::canCachePage()
3018 // Only save page state if:
3019 // 1. We're not a frame or frameset.
3020 // 2. The page has no unload handler.
3021 // 3. The page has no password fields.
3022 // 4. The URL for the page is not https.
3023 // 5. The page has no applets.
3024 if (tree()->childCount() || d->m_plugins.size() ||
3026 d->m_url.protocol().startsWith("https") ||
3027 (d->m_doc && (d->m_doc->applets()->length() != 0 ||
3028 d->m_doc->hasWindowEventListener(unloadEvent) ||
3029 d->m_doc->hasPasswordField()))) {
3035 void Frame::saveWindowProperties(KJS::SavedProperties *windowProperties)
3037 Window *window = Window::retrieveWindow(this);
3039 window->saveProperties(*windowProperties);
3042 void Frame::saveLocationProperties(SavedProperties *locationProperties)
3044 Window *window = Window::retrieveWindow(this);
3047 Location *location = window->location();
3048 location->saveProperties(*locationProperties);
3052 void Frame::restoreWindowProperties(SavedProperties *windowProperties)
3054 Window *window = Window::retrieveWindow(this);
3056 window->restoreProperties(*windowProperties);
3059 void Frame::restoreLocationProperties(SavedProperties *locationProperties)
3061 Window *window = Window::retrieveWindow(this);
3064 Location *location = window->location();
3065 location->restoreProperties(*locationProperties);
3069 void Frame::saveInterpreterBuiltins(SavedBuiltins& interpreterBuiltins)
3072 jScript()->interpreter()->saveBuiltins(interpreterBuiltins);
3075 void Frame::restoreInterpreterBuiltins(const SavedBuiltins& interpreterBuiltins)
3078 jScript()->interpreter()->restoreBuiltins(interpreterBuiltins);
3081 Frame *Frame::frameForWidget(const Widget *widget)
3083 ASSERT_ARG(widget, widget);
3085 Node *node = nodeForWidget(widget);
3087 return frameForNode(node);
3089 // Assume all widgets are either form controls, or FrameViews.
3090 ASSERT(widget->isFrameView());
3091 return static_cast<const FrameView*>(widget)->frame();
3094 Frame *Frame::frameForNode(Node *node)
3096 ASSERT_ARG(node, node);
3097 return node->document()->frame();
3100 Node* Frame::nodeForWidget(const Widget* widget)
3102 ASSERT_ARG(widget, widget);
3103 WidgetClient* client = widget->client();
3106 return client->element(const_cast<Widget*>(widget));
3109 void Frame::clearDocumentFocus(Widget *widget)
3111 Node *node = nodeForWidget(widget);
3113 node->document()->setFocusNode(0);
3116 void Frame::updatePolicyBaseURL()
3118 if (tree()->parent() && tree()->parent()->document())
3119 setPolicyBaseURL(tree()->parent()->document()->policyBaseURL());
3121 setPolicyBaseURL(d->m_url.url());
3124 void Frame::setPolicyBaseURL(const String& s)
3127 document()->setPolicyBaseURL(s);
3128 for (Frame* child = tree()->firstChild(); child; child = child->tree()->nextSibling())
3129 child->setPolicyBaseURL(s);
3132 void Frame::forceLayout()
3134 FrameView *v = d->m_view.get();
3137 // We cannot unschedule a pending relayout, since the force can be called with
3138 // a tiny rectangle from a drawRect update. By unscheduling we in effect
3139 // "validate" and stop the necessary full repaint from occurring. Basically any basic
3140 // append/remove DHTML is broken by this call. For now, I have removed the optimization
3141 // until we have a better invalidation stategy. -dwh
3142 //v->unscheduleRelayout();
3146 void Frame::forceLayoutWithPageWidthRange(float minPageWidth, float maxPageWidth)
3148 // Dumping externalRepresentation(m_frame->renderer()).ascii() is a good trick to see
3149 // the state of things before and after the layout
3150 RenderView *root = static_cast<RenderView*>(document()->renderer());
3152 // This magic is basically copied from khtmlview::print
3153 int pageW = (int)ceilf(minPageWidth);
3154 root->setWidth(pageW);
3155 root->setNeedsLayoutAndMinMaxRecalc();
3158 // If we don't fit in the minimum page width, we'll lay out again. If we don't fit in the
3159 // maximum page width, we will lay out to the maximum page width and clip extra content.
3160 // FIXME: We are assuming a shrink-to-fit printing implementation. A cropping
3161 // implementation should not do this!
3162 int rightmostPos = root->rightmostPosition();
3163 if (rightmostPos > minPageWidth) {
3164 pageW = min(rightmostPos, (int)ceilf(maxPageWidth));
3165 root->setWidth(pageW);
3166 root->setNeedsLayoutAndMinMaxRecalc();
3172 void Frame::sendResizeEvent()
3174 if (Document* doc = document())
3175 doc->dispatchWindowEvent(EventNames::resizeEvent, false, false);
3178 void Frame::sendScrollEvent()
3180 FrameView *v = d->m_view.get();
3182 Document *doc = document();
3185 doc->dispatchHTMLEvent(scrollEvent, true, false);
3189 bool Frame::scrollbarsVisible()
3194 if (view()->hScrollBarMode() == ScrollBarAlwaysOff || view()->vScrollBarMode() == ScrollBarAlwaysOff)
3200 void Frame::addMetaData(const String& key, const String& value)
3202 d->m_metaData.set(key, value);
3205 // This does the same kind of work that Frame::openURL does, except it relies on the fact
3206 // that a higher level already checked that the URLs match and the scrolling is the right thing to do.
3207 void Frame::scrollToAnchor(const KURL& URL)
3214 // It's important to model this as a load that starts and immediately finishes.
3215 // Otherwise, the parent frame may think we never finished loading.
3216 d->m_bComplete = false;
3220 bool Frame::closeURL()
3222 saveDocumentState();
3224 clearUndoRedoOperations();
3228 bool Frame::canMouseDownStartSelect(Node* node)
3230 if (!node || !node->renderer())
3233 // Check to see if -webkit-user-select has been set to none
3234 if (!node->renderer()->canSelect())
3237 // Some controls and images can't start a select on a mouse down.
3238 for (RenderObject* curr = node->renderer(); curr; curr = curr->parent()) {
3239 if (curr->style()->userSelect() == SELECT_IGNORE)
3246 void Frame::handleMouseReleaseDoubleClickEvent(const MouseEventWithHitTestResults& event)
3248 passWidgetMouseDownEventToWidget(event, true);
3251 bool Frame::passWidgetMouseDownEventToWidget(const MouseEventWithHitTestResults& event, bool isDoubleClick)
3253 // Figure out which view to send the event to.
3254 RenderObject *target = event.targetNode() ? event.targetNode()->renderer() : 0;
3258 Widget* widget = RenderLayer::gScrollBar;
3260 if (!target->isWidget())
3262 widget = static_cast<RenderWidget*>(target)->widget();
3265 // Doubleclick events don't exist in Cocoa. Since passWidgetMouseDownEventToWidget will
3266 // just pass _currentEvent down to the widget, we don't want to call it for events that
3267 // don't correspond to Cocoa events. The mousedown/ups will have already been passed on as
3268 // part of the pressed/released handling.
3270 return passMouseDownEventToWidget(widget);
3274 bool Frame::passWidgetMouseDownEventToWidget(RenderWidget *renderWidget)
3276 return passMouseDownEventToWidget(renderWidget->widget());
3279 void Frame::clearTimers(FrameView *view)
3282 view->unscheduleRelayout();
3283 if (view->frame()) {
3284 Document* document = view->frame()->document();
3285 if (document && document->renderer() && document->renderer()->layer())
3286 document->renderer()->layer()->suspendMarquees();
3291 void Frame::clearTimers()
3293 clearTimers(d->m_view.get());
3296 RenderStyle *Frame::styleForSelectionStart(Node *&nodeToRemove) const
3302 if (selectionController()->isNone())
3305 Position pos = selectionController()->selection().visibleStart().deepEquivalent();
3306 if (!pos.inRenderedContent())
3308 Node *node = pos.node();
3312 if (!d->m_typingStyle)
3313 return node->renderer()->style();
3315 ExceptionCode ec = 0;
3316 RefPtr<Element> styleElement = document()->createElementNS(xhtmlNamespaceURI, "span", ec);
3319 styleElement->setAttribute(styleAttr, d->m_typingStyle->cssText().impl(), ec);
3322 styleElement->appendChild(document()->createEditingTextNode(""), ec);
3325 node->parentNode()->appendChild(styleElement, ec);
3328 nodeToRemove = styleElement.get();
3329 return styleElement->renderer()->style();
3332 void Frame::setMediaType(const String& type)
3335 d->m_view->setMediaType(type);
3338 void Frame::setSelectionFromNone()
3340 // Put a caret inside the body if the entire frame is editable (either the
3341 // entire WebView is editable or designMode is on for this document).
3342 Document *doc = document();
3343 if (!doc || !selectionController()->isNone() || !isContentEditable())
3346 Node* node = doc->documentElement();
3347 while (node && !node->hasTagName(bodyTag))
3348 node = node->traverseNextNode();
3350 selectionController()->setSelection(Selection(Position(node, 0), DOWNSTREAM));
3353 bool Frame::isActive() const
3355 return d->m_isActive;
3358 void Frame::setIsActive(bool flag)
3360 if (d->m_isActive == flag)
3363 d->m_isActive = flag;
3365 // This method does the job of updating the view based on whether the view is "active".
3366 // This involves three kinds of drawing updates:
3368 // 1. The background color used to draw behind selected content (active | inactive color)
3370 d->m_view->updateContents(enclosingIntRect(visibleSelectionRect()));
3372 // 2. Caret blinking (blinks | does not blink)
3374 setSelectionFromNone();
3375 setCaretVisible(flag);
3377 // 3. The drawing of a focus ring around links in web pages.
3378 Document *doc = document();
3380 Node *node = doc->focusNode();
3383 if (node->renderer() && node->renderer()->style()->hasAppearance())
3384 theme()->stateChanged(node->renderer(), FocusState);
3388 // 4. Changing the tint of controls from clear to aqua/graphite and vice versa. We
3389 // do a "fake" paint. When the theme gets a paint call, it can then do an invalidate. This is only
3390 // done if the theme supports control tinting.
3391 if (doc && d->m_view && theme()->supportsControlTints() && renderer()) {
3392 doc->updateLayout(); // Ensure layout is up to date.
3393 IntRect visibleRect(enclosingIntRect(d->m_view->visibleContentRect()));
3394 GraphicsContext context((PlatformGraphicsContext*)0);
3395 context.setUpdatingControlTints(true);
3396 paint(&context, visibleRect);
3399 // 5. Enable or disable secure keyboard entry
3400 if ((flag && !isSecureKeyboardEntry() && doc && doc->focusNode() && doc->focusNode()->hasTagName(inputTag) &&
3401 static_cast<HTMLInputElement*>(doc->focusNode())->inputType() == HTMLInputElement::PASSWORD) ||
3402 (!flag && isSecureKeyboardEntry()))
3403 setSecureKeyboardEntry(flag);
3406 void Frame::setWindowHasFocus(bool flag)
3408 if (d->m_windowHasFocus == flag)
3410 d->m_windowHasFocus = flag;
3412 if (Document *doc = document())
3413 doc->dispatchWindowEvent(flag ? focusEvent : blurEvent, false, false);
3416 bool Frame::inViewSourceMode() const
3418 return d->m_inViewSourceMode;
3421 void Frame::setInViewSourceMode(bool mode) const
3423 d->m_inViewSourceMode = mode;
3426 UChar Frame::backslashAsCurrencySymbol() const
3428 Document *doc = document();
3431 Decoder *decoder = doc->decoder();
3435 return decoder->encoding().backslashAsCurrencySymbol();
3438 bool Frame::markedTextUsesUnderlines() const
3440 return d->m_markedTextUsesUnderlines;
3443 const Vector<MarkedTextUnderline>& Frame::markedTextUnderlines() const
3445 return d->m_markedTextUnderlines;
3448 // Searches from the beginning of the document if nothing is selected.
3449 bool Frame::findString(const String& target, bool forward, bool caseFlag, bool wrapFlag)
3451 if (target.isEmpty())
3454 // Initially search from the start (if forward) or end (if backward) of the selection, and search to edge of document.
3455 RefPtr<Range> searchRange(rangeOfContents(document()));
3456 Selection selection(selectionController()->selection());
3457 if (!selection.isNone()) {
3459 setStart(searchRange.get(), selection.visibleStart());
3461 setEnd(searchRange.get(), selection.visibleEnd());
3463 RefPtr<Range> resultRange(findPlainText(searchRange.get(), target, forward, caseFlag));
3464 // If the found range is already selected, find again.
3465 // Build a selection with the found range to remove collapsed whitespace.
3466 // Compare ranges instead of selection objects to ignore the way that the current selection was made.
3467 if (!selection.isNone() && *Selection(resultRange.get()).toRange() == *selection.toRange()) {
3468 searchRange = rangeOfContents(document());
3470 setStart(searchRange.get(), selection.visibleEnd());
3472 setEnd(searchRange.get(), selection.visibleStart());
3473 resultRange = findPlainText(searchRange.get(), target, forward, caseFlag);
3478 // If we didn't find anything and we're wrapping, search again in the entire document (this will
3479 // redundantly re-search the area already searched in some cases).
3480 if (resultRange->collapsed(exception) && wrapFlag) {
3481 searchRange = rangeOfContents(document());
3482 resultRange = findPlainText(searchRange.get(), target, forward, caseFlag);
3483 // We used to return false here if we ended up with the same range that we started with
3484 // (e.g., the selection was already the only instance of this text). But we decided that
3485 // this should be a success case instead, so we'll just fall through in that case.
3488 if (resultRange->collapsed(exception))
3491 selectionController()->setSelection(Selection(resultRange.get(), DOWNSTREAM));
3496 unsigned Frame::markAllMatchesForText(const String& target, bool caseFlag)
3498 if (target.isEmpty())
3501 RefPtr<Range> searchRange(rangeOfContents(document()));
3504 unsigned matchCount = 0;
3506 RefPtr<Range> resultRange(findPlainText(searchRange.get(), target, true, caseFlag));
3507 if (resultRange->collapsed(exception))
3510 // A non-collapsed result range can in some funky whitespace cases still not
3511 // advance the range's start position (4509328). Break to avoid infinite loop.
3512 VisiblePosition newStart = endVisiblePosition(resultRange.get(), DOWNSTREAM);
3513 if (newStart == startVisiblePosition(searchRange.get(), DOWNSTREAM))
3517 document()->addMarker(resultRange.get(), DocumentMarker::TextMatch);
3519 setStart(searchRange.get(), newStart);
3522 // Do a "fake" paint in order to execute the code that computes the rendered rect for
3524 Document* doc = document();
3525 if (doc && d->m_view && renderer()) {
3526 doc->updateLayout(); // Ensure layout is up to date.
3527 IntRect visibleRect(enclosingIntRect(d->m_view->visibleContentRect()));
3528 GraphicsContext context((PlatformGraphicsContext*)0);
3529 context.setPaintingDisabled(true);
3530 paint(&context, visibleRect);
3536 bool Frame::markedTextMatchesAreHighlighted() const
3538 return d->m_highlightTextMatches;
3541 void Frame::setMarkedTextMatchesAreHighlighted(bool flag)
3543 if (flag == d->m_highlightTextMatches)
3546 d->m_highlightTextMatches = flag;
3547 document()->repaintMarkers(DocumentMarker::TextMatch);
3550 void Frame::prepareForUserAction()
3552 // Reset the multiple form submission protection code.
3553 // We'll let you submit the same form twice if you do two separate user actions.
3554 d->m_submittedFormURL = KURL();
3557 Node *Frame::mousePressNode()
3559 return d->m_mousePressNode.get();
3562 bool Frame::isComplete() const
3564 return d->m_bComplete;
3567 bool Frame::isLoadingMainResource() const
3569 return d->m_bLoadingMainResource;
3572 FrameTree* Frame::tree() const
3574 return &d->m_treeNode;
3577 DOMWindow* Frame::domWindow() const
3579 if (!d->m_domWindow)
3580 d->m_domWindow = new DOMWindow(const_cast<Frame*>(this));
3582 return d->m_domWindow.get();
3585 KURL Frame::url() const
3590 void Frame::startRedirectionTimer()
3592 d->m_redirectionTimer.startOneShot(d->m_delayRedirect);
3595 void Frame::stopRedirectionTimer()
3597 d->m_redirectionTimer.stop();
3600 void Frame::frameDetached()
3604 void Frame::updateBaseURLForEmptyDocument()
3606 Element* owner = ownerElement();
3607 // FIXME: Should embed be included?
3608 if (owner && (owner->hasTagName(iframeTag) || owner->hasTagName(objectTag) || owner->hasTagName(embedTag)))
3609 d->m_doc->setBaseURL(tree()->parent()->d->m_doc->baseURL());
3612 Page* Frame::page() const
3617 void Frame::pageDestroyed()
3621 // This will stop any JS timers
3622 if (d->m_jscript && d->m_jscript->haveInterpreter())
3623 if (Window* w = Window::retrieveWindow(this))
3624 w->disconnectFrame();
3627 void Frame::completed(bool complete)
3630 for (Frame* child = tree()->firstChild(); child; child = child->tree()->nextSibling())
3631 child->parentCompleted();
3632 if (Frame* parent = tree()->parent())
3633 parent->childCompleted(complete);
3638 void Frame::setStatusBarText(const String&)
3642 void Frame::started()
3644 for (Frame* frame = this; frame; frame = frame->tree()->parent())
3645 frame->d->m_bComplete = false;
3648 void Frame::disconnectOwnerElement()
3650 if (d->m_ownerElement && d->m_page)
3651 d->m_page->decrementFrameCount();
3653 d->m_ownerElement = 0;
3656 String Frame::documentTypeString() const
3658 if (Document *doc = document())
3659 if (DocumentType *doctype = doc->realDocType())
3660 return doctype->toString();
3665 bool Frame::containsPlugins() const
3667 return d->m_plugins.size() != 0;
3670 bool Frame::prohibitsScrolling() const
3672 return d->m_prohibitsScrolling;
3675 void Frame::setProhibitsScrolling(const bool prohibit)
3677 d->m_prohibitsScrolling = prohibit;
3680 } // namespace WebCore