1 // -*- c-basic-offset: 2 -*-
2 /* This file is part of the KDE project
4 * Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>
5 * 1999-2001 Lars Knoll <knoll@kde.org>
6 * 1999-2001 Antti Koivisto <koivisto@kde.org>
7 * 2000-2001 Simon Hausmann <hausmann@kde.org>
8 * 2000-2001 Dirk Mueller <mueller@kde.org>
9 * 2000 Stefan Schimanski <1Stein@gmx.de>
10 * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc.
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.
32 #include "EditAction.h"
33 #include "FrameView.h"
36 #include "RenderLayer.h"
37 #include "ScrollBar.h"
38 #include "TextAffinity.h"
39 #include "TextGranularity.h"
40 #include <wtf/Vector.h>
46 class SavedProperties;
57 class CSSComputedStyleDeclaration;
58 class CSSMutableStyleDeclaration;
59 class CSSStyleDeclaration;
60 class DrawContentsEvent;
67 struct FrameLoadRequest;
73 class MouseEventWithHitTestResults;
78 class ResourceRequest;
80 class SelectionController;
82 class VisiblePosition;
84 template <typename T> class Timer;
86 struct MarkedTextUnderline {
88 : startOffset(0), endOffset(0), thick(false) { }
89 MarkedTextUnderline(unsigned s, unsigned e, const Color& c, bool t)
90 : startOffset(s), endOffset(e), color(c), thick(t) { }
97 enum ObjectContentType {
104 class Frame : public Shared<Frame> {
106 enum { NoXPosForVerticalArrowNavigation = INT_MIN };
108 Frame(Page*, Element*, PassRefPtr<EditorClient>);
111 // FIXME: Merge these methods and move them into FrameLoader.
112 void changeLocation(const DeprecatedString& URL, const String& referrer, bool lockHistory = true, bool userGesture = false);
113 virtual void urlSelected(const ResourceRequest&, const String& target, const Event* triggeringEvent, bool lockHistory = false);
114 virtual void urlSelected(const FrameLoadRequest&, const Event* triggeringEvent) = 0;
116 bool requestFrame(Element* ownerElement, const String& url, const AtomicString& frameName);
117 virtual Frame* createFrame(const KURL& url, const String& name, Element* ownerElement, const String& referrer) = 0;
118 Frame* loadSubframe(Element* ownerElement, const KURL& url, const String& name, const String& referrer);
120 virtual void submitForm(const FrameLoadRequest&) = 0;
121 void submitForm(const char* action, const String& url, const FormData& formData,
122 const String& target, const String& contentType = String(),
123 const String& boundary = String());
124 void submitFormAgain();
127 void stopLoading(bool sendUnload = false);
128 virtual bool closeURL();
130 void cancelRedirection(bool newLoadInProgress = false);
133 void didExplicitOpen();
136 void commitIconURLToIconDatabase();
139 void pageDestroyed();
141 FrameView* view() const;
142 virtual void setView(FrameView*);
145 * Returns @p true if Javascript is enabled, @p false otherwise.
147 bool javaScriptEnabled() const;
150 * Returns true if Java is enabled, false otherwise.
152 bool javaEnabled() const;
155 * Returns true if plugins are enabled, false otherwise.
157 bool pluginsEnabled() const;
160 * Execute the specified snippet of JavaScript code.
162 KJS::JSValue* executeScript(Node*, const String& script, bool forceUserGesture = false);
165 * Implementation of CSS property -webkit-user-drag == auto
167 virtual bool shouldDragAutoNode(Node*, const IntPoint&) const;
170 * Specifies whether images contained in the document should be loaded
171 * automatically or not.
173 * @note Request will be ignored if called before @ref begin().
175 void setAutoLoadImages(bool enable);
177 * Returns whether images contained in the document are loaded automatically
179 * @note that the returned information is unreliable as long as no begin()
182 bool autoLoadImages() const;
184 KURL baseURL() const;
185 String baseTarget() const;
188 * Schedules a redirection after @p delay seconds.
190 void scheduleRedirection(double delay, const DeprecatedString& url, bool lockHistory = true);
193 * Make a location change, or schedule one for later.
194 * These are used for JavaScript-triggered location changes.
196 void scheduleLocationChange(const DeprecatedString& url, const String& referrer, bool lockHistory = true, bool userGesture = false);
197 void scheduleRefresh(bool userGesture = false);
198 bool isScheduledLocationChangePending() const;
201 * Schedules a history navigation operation (go forward, go back, etc.).
202 * This is used for JavaScript-triggered location changes.
204 void scheduleHistoryNavigation(int steps);
206 virtual bool canGoBackOrForward(int distance) const = 0;
207 virtual void goBackOrForward(int distance) = 0;
208 virtual int getHistoryLength() = 0;
209 virtual KURL historyURL(int distance) = 0;
212 * Clears the widget and prepares it for new content.
214 * If you want @ref url() to return
215 * for example "file:/tmp/test.html", you can use the following code:
217 * view->begin(KURL("file:/tmp/test.html"));
220 * @param url is the url of the document to be displayed. Even if you
221 * are generating the HTML on the fly, it may be useful to specify
222 * a directory so that any images are found.
224 * All child frames and the old document are removed if you call
227 virtual void begin(const KURL& url = KURL());
230 * Writes another part of the HTML code to the widget.
233 * this function many times in sequence. But remember: The fewer calls
234 * you make, the faster the widget will be.
236 * The HTML code is sent through a decoder which decodes the stream to
239 * The @p len parameter is needed for streams encoded in utf-16,
240 * since these can have \0 chars in them. In case the encoding
241 * you're using isn't utf-16, you can safely leave out the length
244 * Attention: Don't mix calls to @ref write(const char*) with calls
245 * to @ref write(const String&).
247 * The result might not be what you want.
249 virtual void write(const char* str, int len = -1);
252 * Writes another part of the HTML code to the widget.
255 * this function many times in sequence. But remember: The fewer calls
256 * you make, the faster the widget will be.
258 virtual void write(const String&);
261 * Call this after your last call to @ref write().
265 void endIfNotLoading();
267 void paint(GraphicsContext*, const IntRect&);
269 void setEncoding(const String& encoding, bool userChosen);
270 String encoding() const;
273 * Sets a user defined style sheet to be used on top of the HTML4,
274 * SVG and printing default style sheets.
276 void setUserStyleSheetLocation(const KURL&);
277 void setUserStyleSheet(const String& styleSheetData);
280 * Sets the standard font style.
282 * @param name The font name to use for standard text.
284 void setStandardFont(const String& name);
287 * Sets the fixed font style.
289 * @param name The font name to use for fixed text, e.g.
290 * the <tt><pre></tt> tag.
292 void setFixedFont(const String& name);
295 * Finds the anchor named @p name.
297 * If the anchor is found, the widget
298 * scrolls to the closest position. Returns @p if the anchor has
301 bool gotoAnchor(const String& name);
304 * Sets the Zoom factor. The value is given in percent, larger values mean a
305 * generally larger font and larger page contents. It is not guaranteed that
306 * all parts of the page are scaled with the same factor though.
308 * The given value should be in the range of 20..300, values outside that
309 * range are not guaranteed to work. A value of 100 will disable all zooming
310 * and show the page with the sizes determined via the given lengths in the
313 void setZoomFactor(int percent);
316 * Returns the current zoom factor.
318 int zoomFactor() const;
321 * Returns the text the user has marked.
323 virtual String selectedText() const;
325 bool findString(const String&, bool, bool, bool);
328 * Returns the granularity of the selection (character, word, line, paragraph).
330 TextGranularity selectionGranularity() const;
333 * Sets the granularity of the selection (character, word, line, paragraph).
335 void setSelectionGranularity(TextGranularity granularity) const;
337 // FIXME: Replace these with functions on the selection controller.
338 bool shouldChangeSelection(const Selection&) const;
339 virtual bool shouldDeleteSelection(const Selection&) const;
340 void clearCaretRectIfNeeded();
341 void setFocusNodeIfNeeded();
342 void selectionLayoutChanged();
343 void notifyRendererOfSelectionChange(bool userTriggered);
346 * Returns a mark, to be used as emacs uses it.
348 const Selection& mark() const;
349 void setMark(const Selection&);
352 * Transposes characters either side of caret selection.
357 * Invalidates the current selection.
359 void invalidateSelection();
361 void setCaretVisible(bool flag = true);
362 void paintCaret(GraphicsContext*, const IntRect&) const;
363 void paintDragCaret(GraphicsContext*, const IntRect&) const;
366 * Set info for vertical arrow navigation.
368 void setXPosForVerticalArrowNavigation(int x);
371 * Get info for vertical arrow navigation.
373 int xPosForVerticalArrowNavigation() const;
376 * Has the user selected anything?
378 * Call @ref selectedText() to
379 * retrieve the selected text.
381 * @return @p true if there is text selected.
383 bool hasSelection() const;
386 * Returns whether editing should end in the given range
388 virtual bool shouldBeginEditing(const Range*) const;
391 * Returns whether editing should end in the given range
393 virtual bool shouldEndEditing(const Range*) const;
396 * Called when editing has begun.
398 virtual void didBeginEditing() const {};
401 * Called when editing has ended.
403 virtual void didEndEditing() const {};
406 * Returns the contentEditable "override" value for the part
408 virtual bool isContentEditable() const;
410 virtual void textFieldDidBeginEditing(Element*);
411 virtual void textFieldDidEndEditing(Element*);
412 virtual void textDidChangeInTextField(Element*);
413 virtual bool doTextFieldCommandFromEvent(Element*, const PlatformKeyboardEvent*);
414 virtual void textWillBeDeletedInTextField(Element* input);
415 virtual void textDidChangeInTextArea(Element*);
417 virtual bool inputManagerHasMarkedText() const { return false; }
419 virtual void setSecureKeyboardEntry(bool) {};
420 virtual bool isSecureKeyboardEntry() { return false; }
422 bool isSelectionInPasswordField();
425 * Called when editing has been applied.
427 void appliedEditing(PassRefPtr<EditCommand>);
430 * Called when editing has been unapplied.
432 void unappliedEditing(PassRefPtr<EditCommand>);
435 * Called when editing has been reapplied.
437 void reappliedEditing(PassRefPtr<EditCommand>);
440 * Returns the typing style for the document.
442 CSSMutableStyleDeclaration* typingStyle() const;
445 * Sets the typing style for the document.
447 void setTypingStyle(CSSMutableStyleDeclaration*);
450 * Clears the typing style for the document.
452 void clearTypingStyle();
454 virtual void tokenizerProcessedData() {}
456 bool inViewSourceMode() const;
457 void setInViewSourceMode(bool = true) const;
459 const Settings* settings() const;
461 void setJSStatusBarText(const String&);
462 void setJSDefaultStatusBarText(const String&);
463 String jsStatusBarText() const;
464 String jsDefaultStatusBarText() const;
467 * Referrer used for links in this page.
469 String referrer() const;
472 * Last-modified date (in raw string format), if received in the [HTTP] headers.
474 String lastModified() const;
476 virtual bool tabsToLinks() const;
477 virtual bool tabsToAllControls() const;
479 // Editing operations.
480 enum TriState { falseTriState, trueTriState, mixedTriState };
481 void copyToPasteboard();
482 void cutToPasteboard();
483 void pasteFromPasteboard();
484 void pasteAndMatchStyle();
486 virtual bool canPaste() const = 0;
489 virtual bool canRedo() const = 0;
490 virtual bool canUndo() const = 0;
491 void computeAndSetTypingStyle(CSSStyleDeclaration* , EditAction editingAction=EditActionUnspecified);
492 void applyStyle(CSSStyleDeclaration* , EditAction editingAction=EditActionUnspecified);
493 void applyParagraphStyle(CSSStyleDeclaration* , EditAction editingAction=EditActionUnspecified);
496 TriState selectionHasStyle(CSSStyleDeclaration*) const;
497 bool selectionStartHasStyle(CSSStyleDeclaration*) const;
498 String selectionStartStylePropertyValue(int stylePropertyID) const;
499 void applyEditingStyleToBodyElement() const;
500 void removeEditingStyleFromBodyElement() const;
501 void applyEditingStyleToElement(Element*) const;
502 void removeEditingStyleFromElement(Element*) const;
503 virtual void print() = 0;
504 virtual bool isCharacterSmartReplaceExempt(UChar, bool);
506 // Used to keep the part alive when running a script that might destroy it.
509 static void endAllLifeSupport();
512 * returns a KURL object for the given url. Use when
513 * you know what you're doing.
515 KURL completeURL(const DeprecatedString& url);
517 virtual void handleMousePressEvent(const MouseEventWithHitTestResults&);
518 virtual void handleMouseMoveEvent(const MouseEventWithHitTestResults&);
519 virtual void handleMouseReleaseEvent(const MouseEventWithHitTestResults&);
521 void updateSelectionForMouseDragOverPosition(const VisiblePosition&);
523 void selectClosestWordFromMouseEvent(const PlatformMouseEvent&, Node* innerNode);
525 // Methods with platform-specific overrides (and no base class implementation).
526 virtual void setTitle(const String&) = 0;
527 virtual void handledOnloadEvents() = 0;
528 virtual String userAgent() const = 0;
529 virtual String mimeTypeForFileName(const String&) const = 0;
530 virtual KJS::Bindings::Instance* getEmbedInstanceForWidget(Widget*) = 0;
531 virtual KJS::Bindings::Instance* getObjectInstanceForWidget(Widget*) = 0;
532 virtual KJS::Bindings::Instance* getAppletInstanceForWidget(Widget*) = 0;
533 virtual KJS::Bindings::RootObject* bindingRootObject() = 0;
534 virtual Widget* createJavaAppletWidget(const IntSize&, Element*, const HashMap<String, String>& args) = 0;
536 virtual void markMisspellingsInAdjacentWords(const VisiblePosition&) = 0;
537 virtual void markMisspellings(const Selection&) = 0;
538 virtual void addMessageToConsole(const String& message, unsigned int lineNumber, const String& sourceID) = 0;
539 virtual void runJavaScriptAlert(const String& message) = 0;
540 virtual bool runJavaScriptConfirm(const String& message) = 0;
541 virtual bool runJavaScriptPrompt(const String& message, const String& defaultValue, String& result) = 0;
542 virtual bool shouldInterruptJavaScript() = 0;
543 virtual bool locationbarVisible() = 0;
544 virtual bool menubarVisible() = 0;
545 virtual bool personalbarVisible() = 0;
546 virtual bool statusbarVisible() = 0;
547 virtual bool toolbarVisible() = 0;
548 virtual void scheduleClose() = 0;
549 virtual void focusWindow() = 0;
550 virtual void unfocusWindow() = 0;
551 virtual void createEmptyDocument() = 0;
552 virtual Range* markedTextRange() const = 0;
553 virtual void registerCommandForUndo(PassRefPtr<EditCommand>) = 0;
554 virtual void registerCommandForRedo(PassRefPtr<EditCommand>) = 0;
555 virtual void clearUndoRedoOperations() = 0;
556 virtual void issueUndoCommand() = 0;
557 virtual void issueRedoCommand() = 0;
558 virtual void issueCutCommand() = 0;
559 virtual void issueCopyCommand() = 0;
560 virtual void issuePasteCommand() = 0;
561 virtual void issuePasteAndMatchStyleCommand() = 0;
562 virtual void issueTransposeCommand() = 0;
563 virtual void respondToChangedSelection(const Selection& oldSelection, bool closeTyping) = 0;
564 virtual void respondToChangedContents(const Selection& endingSelection) = 0;
565 virtual bool shouldChangeSelection(const Selection& oldSelection, const Selection& newSelection, EAffinity affinity, bool stillSelecting) const = 0;
566 virtual void partClearedInBegin() = 0;
567 virtual void saveDocumentState() = 0;
568 virtual void restoreDocumentState() = 0;
569 virtual bool lastEventIsMouseUp() const = 0;
570 virtual String overrideMediaType() const = 0;
571 virtual void redirectDataToPlugin(Widget* pluginWidget) { }
572 virtual void setupRootForPrinting(bool onOrOff) { }
573 virtual Vector<IntRect> computePageRects(const IntRect& printRect, float userScaleFactor) { return Vector<IntRect>(); }
575 virtual Plugin* createPlugin(Element* node, const KURL& url, const Vector<String>& paramNames, const Vector<String>& paramValues, const String& mimeType) = 0;
576 virtual ObjectContentType objectContentType(const KURL& url, const String& mimeType) = 0;
578 virtual void redirectionTimerFired(Timer<Frame>*);
580 virtual bool isLoadTypeReload() = 0;
581 virtual KURL originalRequestURL() const = 0;
586 void finishedParsing();
588 void checkCompleted();
590 void reparseConfiguration();
597 void completed(bool);
598 void childCompleted(bool);
599 void parentCompleted();
601 void lifeSupportTimerFired(Timer<Frame>*);
602 void endLifeSupport();
604 virtual void clear(bool clearWindowProperties = true);
606 void caretBlinkTimerFired(Timer<Frame>*);
608 bool shouldUsePlugin(Node* element, const KURL& url, const String& mimeType, bool hasFallback, bool& useFallback);
609 bool loadPlugin(RenderPart* renderer, const KURL& url, const String& mimeType,
610 const Vector<String>& paramNames, const Vector<String>& paramValues, bool useFallback);
613 bool requestObject(RenderPart* frame, const String& url, const AtomicString& frameName,
614 const String& serviceType, const Vector<String>& paramNames, const Vector<String>& paramValues);
615 Document* document() const;
616 void setDocument(Document* newDoc);
618 virtual bool mouseDownMayStartSelect() const { return true; }
619 bool mouseDownMayStartAutoscroll() const;
620 void setMouseDownMayStartAutoscroll(bool b);
622 bool mouseDownMayStartDrag() const;
623 void setMouseDownMayStartDrag(bool b);
625 void handleFallbackContent();
628 KJS::JSValue* executeScript(const String& filename, int baseLine, Node*, const String& script);
629 KJSProxy* scriptProxy();
631 void setOpener(Frame* _opener);
633 void setOpenedByJS(bool _openedByJS);
635 void setSettings(Settings*);
637 void provisionalLoadStarted();
638 bool userGestureHint();
639 void didNotOpenURL(const KURL&);
640 void addData(const char* bytes, int length);
641 void addMetaData(const String& key, const String& value);
642 void setMediaType(const String&);
644 // root renderer for the document contained in this frame
645 RenderObject* renderer() const;
647 Element* ownerElement();
648 // renderer for the element that contains this frame
649 RenderPart* ownerRenderer();
651 IntRect selectionRect() const;
652 FloatRect visibleSelectionRect() const;
653 bool isFrameSet() const;
655 HTMLFormElement* currentForm() const;
657 RenderStyle* styleForSelectionStart(Node* &nodeToRemove) const;
659 void revealSelection(const RenderLayer::ScrollAlignment& alignment = RenderLayer::gAlignCenterIfNeeded) const;
660 void revealCaret(const RenderLayer::ScrollAlignment& alignment = RenderLayer::gAlignCenterIfNeeded) const;
661 void setSelectionFromNone();
663 bool scrollOverflow(ScrollDirection direction, ScrollGranularity granularity);
665 void adjustPageHeight(float* newBottom, float oldTop, float oldBottom, float bottomLimit);
668 KJS::PausedTimeouts* pauseTimeouts();
669 void resumeTimeouts(KJS::PausedTimeouts*);
670 void saveWindowProperties(KJS::SavedProperties* windowProperties);
671 void saveLocationProperties(KJS::SavedProperties* locationProperties);
672 void restoreWindowProperties(KJS::SavedProperties* windowProperties);
673 void restoreLocationProperties(KJS::SavedProperties* locationProperties);
674 void saveInterpreterBuiltins(KJS::SavedBuiltins& interpreterBuiltins);
675 void restoreInterpreterBuiltins(const KJS::SavedBuiltins& interpreterBuiltins);
677 static Frame* frameForWidget(const Widget*);
678 static Node* nodeForWidget(const Widget*);
679 static Frame* frameForNode(Node*);
681 static void clearDocumentFocus(Widget*);
683 void updatePolicyBaseURL();
684 void setPolicyBaseURL(const String&);
687 void forceLayoutWithPageWidthRange(float minPageWidth, float maxPageWidth);
689 void sendResizeEvent();
690 void sendScrollEvent();
691 bool scrollbarsVisible();
692 void scrollToAnchor(const KURL&);
693 bool canMouseDownStartSelect(Node*);
696 static void clearTimers(FrameView*);
698 bool isActive() const;
699 virtual void setIsActive(bool flag);
700 void setWindowHasFocus(bool flag);
701 // Convenience, to avoid repeating the code to dig down to get this.
703 UChar backslashAsCurrencySymbol() const;
705 const Vector<MarkedTextUnderline>& markedTextUnderlines() const;
706 bool markedTextUsesUnderlines() const;
708 unsigned markAllMatchesForText(const String&, bool caseFlag, unsigned limit);
709 bool markedTextMatchesAreHighlighted() const;
710 void setMarkedTextMatchesAreHighlighted(bool flag);
712 // Call this method before handling a new user action, like on a mouse down or key down.
713 // Currently, all this does is clear the "don't submit form twice" data member.
714 void prepareForUserAction();
715 Node* mousePressNode();
717 void clearRecordedFormValues();
718 void recordFormValue(const String& name, const String& value, PassRefPtr<HTMLFormElement>);
720 bool isComplete() const;
721 bool isLoadingMainResource() const;
723 void replaceContentsWithScriptResult(const KURL& url);
725 void disconnectOwnerElement();
727 void setNeedsReapplyStyles();
729 void stopAutoscrollTimer();
730 RenderObject* autoscrollRenderer() const;
733 virtual void startRedirectionTimer();
734 virtual void stopRedirectionTimer();
735 virtual void cleanupPluginObjects() { }
736 void cancelAndClear();
738 void handleAutoscroll(RenderObject*);
739 void startAutoscrollTimer();
740 void setAutoscrollRenderer(RenderObject*);
743 void emitLoadEvent();
745 void receivedFirstData();
748 * @internal Extracts anchor and tries both encoded and decoded form.
752 void handleMousePressEventSingleClick(const MouseEventWithHitTestResults&);
753 void handleMousePressEventDoubleClick(const MouseEventWithHitTestResults&);
754 void handleMousePressEventTripleClick(const MouseEventWithHitTestResults&);
756 CSSComputedStyleDeclaration* selectionComputedStyle(Node* &nodeToRemove) const;
758 virtual void setStatusBarText(const String&);
760 void autoscrollTimerFired(Timer<Frame>*);
763 friend class FrameGdk;
764 friend class FrameLoader;
765 friend class FrameMac;
766 friend class FrameQt;
767 friend class FrameWin;
769 HitTestResult hitTestResultAtPoint(const IntPoint&, bool allowShadowContent);
771 String documentTypeString() const;
773 void checkEmitLoadEvent();
774 bool didOpenURL(const KURL&);
775 virtual void didFirstLayout() {}
777 virtual void frameDetached();
779 void detachChildren();
781 void updateBaseURLForEmptyDocument();
785 void setResponseMIMEType(const String&);
786 const String& responseMIMEType() const;
788 bool containsPlugins() const;
790 bool prohibitsScrolling() const;
791 void setProhibitsScrolling(const bool);
793 // split out controller objects
794 FrameTree* tree() const;
795 SelectionController* selectionController() const;
796 SelectionController* dragCaretController() const;
797 DOMWindow* domWindow() const;
798 Editor* editor() const;
799 CommandByName* command() const;
800 FrameLoader* loader() const;
803 friend class FramePrivate;
807 } // namespace WebCore