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.
31 #include "BrowserExtension.h"
33 #include "FrameView.h"
36 #include "TransferJobClient.h"
37 #include "EditAction.h"
38 #include "TextAffinity.h"
39 #include "TextGranularity.h"
41 #include <qscrollbar.h>
42 #include <DeprecatedStringList.h>
43 #include <kxmlcore/Noncopyable.h>
51 class SavedProperties;
60 class CSSComputedStyleDeclaration;
61 class CSSMutableStyleDeclaration;
62 class CSSStyleDeclaration;
63 class DrawContentsEvent;
70 class MouseEventWithHitTestResults;
74 class SelectionController;
75 class VisiblePosition;
77 template <typename T> class Timer;
79 struct MarkedTextUnderline {
80 MarkedTextUnderline(unsigned s, unsigned e, const Color& c, bool t)
81 : startOffset(s), endOffset(e), color(c), thick(t) { }
88 enum ObjectContentType {
95 class Frame : public Shared<Frame>, Noncopyable, TransferJobClient {
98 enum { NoXPosForVerticalArrowNavigation = INT_MIN };
100 Frame(Page*, RenderPart*);
103 virtual bool openURL(const KURL&);
104 virtual bool closeURL();
106 void didExplicitOpen();
111 * Stop loading the document and kill all data requests (for images, etc.)
113 void stopLoading(bool sendUnload = false);
116 * Returns a pointer to the @ref BrowserExtension.
118 BrowserExtension *browserExtension() const;
121 * Returns a pointer to the HTML document's view.
123 FrameView *view() const;
125 virtual void setView(FrameView*);
128 * Returns @p true if Javascript is enabled, @p false otherwise.
130 bool jScriptEnabled() const;
133 * Returns true if Java is enabled, false otherwise.
135 bool javaEnabled() const;
138 * Returns true if plugins are enabled, false otherwise.
140 bool pluginsEnabled() const;
143 * Enable/disable the automatic forwarding by <meta http-equiv="refresh" ....>
145 void setMetaRefreshEnabled( bool enable );
148 * Returns @p true if automtaic forwarding is enabled.
150 bool metaRefreshEnabled() const;
153 * Execute the specified snippet of JavaScript code.
155 KJS::JSValue* executeScript(Node*, const DeprecatedString& script, bool forceUserGesture = false);
158 * Implementation of CSS property -khtml-user-drag == auto
160 virtual bool shouldDragAutoNode(Node*, int x, int y) const;
163 * Specifies whether images contained in the document should be loaded
164 * automatically or not.
166 * @note Request will be ignored if called before @ref begin().
168 void setAutoloadImages( bool enable );
170 * Returns whether images contained in the document are loaded automatically
172 * @note that the returned information is unreliable as long as no begin()
175 bool autoloadImages() const;
177 KURL baseURL() const;
178 DeprecatedString baseTarget() const;
181 * Schedules a redirection after @p delay seconds.
183 void scheduleRedirection(double delay, const DeprecatedString &url, bool lockHistory = true);
186 * Make a location change, or schedule one for later.
187 * These are used for JavaScript-triggered location changes.
189 void changeLocation(const DeprecatedString &URL, const DeprecatedString &referrer, bool lockHistory = true, bool userGesture = false);
190 void scheduleLocationChange(const DeprecatedString &url, const DeprecatedString &referrer, bool lockHistory = true, bool userGesture = false);
191 bool isScheduledLocationChangePending() const;
194 * Schedules a history navigation operation (go forward, go back, etc.).
195 * This is used for JavaScript-triggered location changes.
197 void scheduleHistoryNavigation( int steps );
200 * Clears the widget and prepares it for new content.
202 * If you want @ref url() to return
203 * for example "file:/tmp/test.html", you can use the following code:
205 * view->begin( KURL("file:/tmp/test.html" ) );
208 * @param url is the url of the document to be displayed. Even if you
209 * are generating the HTML on the fly, it may be useful to specify
210 * a directory so that any images are found.
212 * All child frames and the old document are removed if you call
215 virtual void begin( const KURL &url = KURL());
218 * Writes another part of the HTML code to the widget.
221 * this function many times in sequence. But remember: The fewer calls
222 * you make, the faster the widget will be.
224 * The HTML code is send through a decoder which decodes the stream to
227 * The @p len parameter is needed for streams encoded in utf-16,
228 * since these can have \0 chars in them. In case the encoding
229 * you're using isn't utf-16, you can safely leave out the length
232 * Attention: Don't mix calls to @ref write( const char *) with calls
233 * to @ref write( const DeprecatedString & ).
235 * The result might not be what you want.
237 virtual void write( const char *str, int len = -1 );
240 * Writes another part of the HTML code to the widget.
243 * this function many times in sequence. But remember: The fewer calls
244 * you make, the faster the widget will be.
246 virtual void write( const DeprecatedString &str );
249 * Call this after your last call to @ref write().
253 void endIfNotLoading();
256 * Similar to end, but called to abort a load rather than cleanly end.
260 void paint(GraphicsContext*, const IntRect&);
262 void setEncoding(const DeprecatedString &encoding, bool userChosen);
265 * Returns the encoding the page currently uses.
267 * Note that the encoding might be different from the charset.
269 DeprecatedString encoding() const;
272 * Sets a user defined style sheet to be used on top of the HTML 4
273 * default style sheet.
275 * This gives a wide range of possibilities to
276 * change the layout of the page.
278 void setUserStyleSheet(const KURL &url);
281 * Sets a user defined style sheet to be used on top of the HTML 4
282 * default style sheet.
284 * This gives a wide range of possibilities to
285 * change the layout of the page.
287 void setUserStyleSheet(const DeprecatedString &styleSheet);
290 * Sets the standard font style.
292 * @param name The font name to use for standard text.
294 void setStandardFont( const DeprecatedString &name );
297 * Sets the fixed font style.
299 * @param name The font name to use for fixed text, e.g.
300 * the <tt><pre></tt> tag.
302 void setFixedFont( const DeprecatedString &name );
305 * Finds the anchor named @p name.
307 * If the anchor is found, the widget
308 * scrolls to the closest position. Returns @p if the anchor has
311 bool gotoAnchor( const DeprecatedString &name );
314 * Sets the Zoom factor. The value is given in percent, larger values mean a
315 * generally larger font and larger page contents. It is not guaranteed that
316 * all parts of the page are scaled with the same factor though.
318 * The given value should be in the range of 20..300, values outside that
319 * range are not guaranteed to work. A value of 100 will disable all zooming
320 * and show the page with the sizes determined via the given lengths in the
323 void setZoomFactor(int percent);
326 * Returns the current zoom factor.
328 int zoomFactor() const;
331 * Returns the text the user has marked.
333 virtual DeprecatedString selectedText() const;
336 * Returns the granularity of the selection (character, word, line, paragraph).
338 TextGranularity selectionGranularity() const;
341 * Sets the granularity of the selection (character, word, line, paragraph).
343 void setSelectionGranularity(TextGranularity granularity) const;
346 * Returns the drag caret of the HTML.
348 const SelectionController &dragCaret() const;
351 * Sets the current selection.
353 void setSelection(const SelectionController &, bool closeTyping = true, bool keepTypingStyle = false);
356 * Returns whether selection can be changed.
358 bool shouldChangeSelection(const SelectionController &) const;
361 * Returns a mark, to be used as emacs uses it.
363 const Selection &mark() const;
368 void setMark(const Selection &);
371 * Sets the current drag caret.
373 void setDragCaret(const SelectionController &);
376 * Transposes characters either side of caret selection.
381 * Invalidates the current selection.
383 void invalidateSelection();
385 void setCaretVisible(bool flag = true);
386 void paintCaret(GraphicsContext*, const IntRect&) const;
387 void paintDragCaret(GraphicsContext*, const IntRect&) const;
390 * Set info for vertical arrow navigation.
392 void setXPosForVerticalArrowNavigation(int x);
395 * Get info for vertical arrow navigation.
397 int xPosForVerticalArrowNavigation() const;
400 * Has the user selected anything?
402 * Call @ref selectedText() to
403 * retrieve the selected text.
405 * @return @p true if there is text selected.
407 bool hasSelection() const;
410 * Marks all text in the document as selected.
415 * Marks contents of node as selected.
416 * Returns whether the selection changed.
418 bool selectContentsOfNode(Node*);
421 * Returns whether editing should end in the given range
423 virtual bool shouldBeginEditing(const Range *) const;
426 * Returns whether editing should end in the given range
428 virtual bool shouldEndEditing(const Range *) const;
431 * Called when editing has begun.
433 virtual void didBeginEditing() const {};
436 * Called when editing has ended.
438 virtual void didEndEditing() const {};
441 * Returns the contentEditable "override" value for the part
443 virtual bool isContentEditable() const;
446 * Returns the most recent edit command applied.
448 EditCommandPtr lastEditCommand();
451 * Called when editing has been applied.
453 void appliedEditing(EditCommandPtr &);
456 * Called when editing has been unapplied.
458 void unappliedEditing(EditCommandPtr &);
461 * Called when editing has been reapplied.
463 void reappliedEditing(EditCommandPtr &);
466 * Returns the typing style for the document.
468 CSSMutableStyleDeclaration *typingStyle() const;
471 * Sets the typing style for the document.
473 void setTypingStyle(CSSMutableStyleDeclaration *);
476 * Clears the typing style for the document.
478 void clearTypingStyle();
480 virtual void tokenizerProcessedData() {}
482 const KHTMLSettings* settings() const;
484 void setJSStatusBarText(const String&);
485 void setJSDefaultStatusBarText(const String&);
486 String jsStatusBarText() const;
487 String jsDefaultStatusBarText() const;
490 * Referrer used for links in this page.
492 DeprecatedString referrer() const;
495 * Last-modified date (in raw string format), if received in the [HTTP] headers.
497 DeprecatedString lastModified() const;
499 bool isPointInsideSelection(int x, int y);
501 virtual bool tabsToLinks() const;
502 virtual bool tabsToAllControls() const;
504 // Editing operations.
505 enum TriState { falseTriState, trueTriState, mixedTriState };
506 void copyToPasteboard();
507 void cutToPasteboard();
508 void pasteFromPasteboard();
509 void pasteAndMatchStyle();
510 virtual bool canPaste() const = 0;
513 virtual bool canRedo() const = 0;
514 virtual bool canUndo() const = 0;
515 void computeAndSetTypingStyle(CSSStyleDeclaration *, EditAction editingAction=EditActionUnspecified);
516 void applyStyle(CSSStyleDeclaration *, EditAction editingAction=EditActionUnspecified);
517 void applyParagraphStyle(CSSStyleDeclaration *, EditAction editingAction=EditActionUnspecified);
518 TriState selectionHasStyle(CSSStyleDeclaration *) const;
519 bool selectionStartHasStyle(CSSStyleDeclaration *) const;
520 String selectionStartStylePropertyValue(int stylePropertyID) const;
521 void applyEditingStyleToBodyElement() const;
522 void removeEditingStyleFromBodyElement() const;
523 void applyEditingStyleToElement(Element *) const;
524 void removeEditingStyleFromElement(Element *) const;
525 virtual void print() = 0;
526 virtual bool isCharacterSmartReplaceExempt(const QChar &, bool);
528 // Used to keep the part alive when running a script that might destroy it.
531 static void endAllLifeSupport();
534 * returns a KURL object for the given url. Use when
535 * you know what you're doing.
537 KURL completeURL( const DeprecatedString &url );
539 virtual void handleMouseReleaseDoubleClickEvent(const MouseEventWithHitTestResults&);
540 virtual void handleMousePressEvent(const MouseEventWithHitTestResults&);
541 virtual void handleMouseMoveEvent(const MouseEventWithHitTestResults&);
542 virtual void handleMouseReleaseEvent(const MouseEventWithHitTestResults&);
544 void selectClosestWordFromMouseEvent(const PlatformMouseEvent&, Node* innerNode, int x, int y);
546 virtual void urlSelected(const DeprecatedString& url, const DeprecatedString& target);
547 virtual void urlSelected(const ResourceRequest&, const DeprecatedString& target);
550 // Methods with platform-specific overrides (and no base class implementation).
551 virtual void setTitle(const String &) = 0;
552 virtual void handledOnloadEvents() = 0;
553 virtual DeprecatedString userAgent() const = 0;
554 virtual DeprecatedString incomingReferrer() const = 0;
555 virtual DeprecatedString mimeTypeForFileName(const DeprecatedString &) const = 0;
556 virtual KJS::Bindings::Instance *getEmbedInstanceForWidget(Widget*) = 0;
557 virtual KJS::Bindings::Instance *getObjectInstanceForWidget(Widget*) = 0;
558 virtual KJS::Bindings::Instance *getAppletInstanceForWidget(Widget*) = 0;
559 virtual void markMisspellingsInAdjacentWords(const VisiblePosition &) = 0;
560 virtual void markMisspellings(const SelectionController &) = 0;
561 virtual void addMessageToConsole(const String& message, unsigned int lineNumber, const String& sourceID) = 0;
562 virtual void runJavaScriptAlert(const String& message) = 0;
563 virtual bool runJavaScriptConfirm(const String& message) = 0;
564 virtual bool runJavaScriptPrompt(const String& message, const String& defaultValue, String& result) = 0;
565 virtual bool locationbarVisible() = 0;
566 virtual bool menubarVisible() = 0;
567 virtual bool personalbarVisible() = 0;
568 virtual bool statusbarVisible() = 0;
569 virtual bool toolbarVisible() = 0;
570 virtual void scheduleClose() = 0;
571 virtual void unfocusWindow() = 0;
572 virtual void createEmptyDocument() = 0;
573 virtual Range *markedTextRange() const = 0;
574 virtual void registerCommandForUndo(const EditCommandPtr &) = 0;
575 virtual void registerCommandForRedo(const EditCommandPtr &) = 0;
576 virtual void clearUndoRedoOperations() = 0;
577 virtual void issueUndoCommand() = 0;
578 virtual void issueRedoCommand() = 0;
579 virtual void issueCutCommand() = 0;
580 virtual void issueCopyCommand() = 0;
581 virtual void issuePasteCommand() = 0;
582 virtual void issuePasteAndMatchStyleCommand() = 0;
583 virtual void issueTransposeCommand() = 0;
584 virtual void respondToChangedSelection(const SelectionController &oldSelection, bool closeTyping) = 0;
585 virtual void respondToChangedContents() = 0;
586 virtual bool shouldChangeSelection(const SelectionController &oldSelection, const SelectionController &newSelection, EAffinity affinity, bool stillSelecting) const = 0;
587 virtual void partClearedInBegin() = 0;
588 virtual void saveDocumentState() = 0;
589 virtual void restoreDocumentState() = 0;
590 virtual bool canGoBackOrForward(int distance) const = 0;
591 virtual void openURLRequest(const ResourceRequest&) = 0;
592 virtual void submitForm(const ResourceRequest&) = 0;
593 virtual void urlSelected(const ResourceRequest&) = 0;
594 virtual bool passSubframeEventToSubframe(MouseEventWithHitTestResults&, Frame* subframePart = 0) = 0;
595 virtual bool passWheelEventToChildWidget(Node *) = 0;
596 virtual bool lastEventIsMouseUp() const = 0;
597 virtual DeprecatedString overrideMediaType() const = 0;
599 virtual Plugin* createPlugin(const KURL& url, const DeprecatedStringList& paramNames, const DeprecatedStringList& paramValues, const DeprecatedString& mimeType) = 0;
600 virtual Frame* createFrame(const KURL& url, const DeprecatedString& name, RenderPart* renderer, const String& referrer) = 0;
601 virtual ObjectContentType objectContentType(const KURL& url, const DeprecatedString& mimeType) = 0;
603 virtual void redirectionTimerFired(Timer<Frame>*);
607 * Stops all animated images on the current and child pages
609 void stopAnimations();
613 void finishedParsing();
615 void checkCompleted();
617 void reparseConfiguration();
620 virtual void receivedRedirect(TransferJob*, const KURL&);
621 virtual void receivedAllData(TransferJob*);
625 void submitFormAgain();
629 void completed(bool);
630 void childCompleted(bool);
631 void parentCompleted();
633 void lifeSupportTimerFired(Timer<Frame>*);
634 void endLifeSupport();
636 virtual void clear(bool clearWindowProperties = true);
638 void clearCaretRectIfNeeded();
639 void setFocusNodeIfNeeded();
640 void selectionLayoutChanged();
641 void caretBlinkTimerFired(Timer<Frame>*);
643 bool shouldUsePlugin(Node* element, const KURL& url, const DeprecatedString& mimeType, bool hasFallback, bool& useFallback);
644 bool loadPlugin(RenderPart* renderer, const KURL &url, const DeprecatedString &mimeType,
645 const DeprecatedStringList& paramNames, const DeprecatedStringList& paramValues, bool useFallback);
646 Frame* loadSubframe(RenderPart* renderer, const KURL& url, const DeprecatedString& name, const String& referrer);
649 void submitForm(const char *action, const DeprecatedString &url, const FormData &formData,
650 const DeprecatedString &target, const DeprecatedString& contentType = DeprecatedString::null,
651 const DeprecatedString& boundary = DeprecatedString::null );
653 bool requestObject(RenderPart *frame, const DeprecatedString &url, const DeprecatedString &frameName,
654 const DeprecatedString &serviceType, const DeprecatedStringList ¶mNames, const DeprecatedStringList ¶mValues);
655 bool requestFrame(RenderPart *frame, const DeprecatedString &url, const DeprecatedString &frameName);
657 Document *document() const;
658 void setDocument(Document* newDoc);
660 // Workaround for the fact that it's hard to delete a frame.
661 // Call this after doing user-triggered selections to make it easy to delete the frame you entirely selected.
662 void selectFrameElementInParentIfFullySelected();
664 virtual bool mouseDownMayStartSelect() const { return true; }
666 void handleFallbackContent();
669 void cancelRedirection(bool newLoadInProgress = false);
672 KJS::JSValue* executeScript(const DeprecatedString& filename, int baseLine, Node*, const DeprecatedString& script);
675 void setOpener(Frame *_opener);
677 void setOpenedByJS(bool _openedByJS);
679 void setSettings(KHTMLSettings *);
681 void provisionalLoadStarted();
682 bool userGestureHint();
683 void didNotOpenURL(const KURL &);
684 void addData(const char *bytes, int length);
685 void addMetaData(const DeprecatedString &key, const DeprecatedString &value);
686 void setMediaType(const DeprecatedString &);
688 // root renderer for the document contained in this frame
689 RenderObject* renderer() const;
691 Element* ownerElement();
692 // renderer for the element that contains this frame
693 RenderPart* ownerRenderer();
695 IntRect selectionRect() const;
696 FloatRect visibleSelectionRect() const;
697 bool isFrameSet() const;
699 HTMLFormElement *currentForm() const;
701 RenderStyle *styleForSelectionStart(Node *&nodeToRemove) const;
703 // Scrolls as necessary to reveal the selection
704 void revealSelection();
705 // Centers the selection regardless of whether it was already visible
706 void centerSelectionInVisibleArea() const;
707 void setSelectionFromNone();
709 bool scrollOverflow(KWQScrollDirection direction, KWQScrollGranularity granularity);
711 void adjustPageHeight(float *newBottom, float oldTop, float oldBottom, float bottomLimit);
714 KJS::PausedTimeouts *pauseTimeouts();
715 void resumeTimeouts(KJS::PausedTimeouts *);
716 void saveWindowProperties(KJS::SavedProperties *windowProperties);
717 void saveLocationProperties(KJS::SavedProperties *locationProperties);
718 void restoreWindowProperties(KJS::SavedProperties *windowProperties);
719 void restoreLocationProperties(KJS::SavedProperties *locationProperties);
720 void saveInterpreterBuiltins(KJS::SavedBuiltins &interpreterBuiltins);
721 void restoreInterpreterBuiltins(const KJS::SavedBuiltins &interpreterBuiltins);
723 static Frame *frameForWidget(const Widget *);
724 static Node *nodeForWidget(const Widget *);
725 static Frame *frameForNode(Node *);
727 static void clearDocumentFocus(Widget *);
729 static const DeprecatedPtrList<Frame> &instances() { return mutableInstances(); }
730 static DeprecatedPtrList<Frame> &mutableInstances();
732 void updatePolicyBaseURL();
733 void setPolicyBaseURL(const String&);
736 void forceLayoutWithPageWidthRange(float minPageWidth, float maxPageWidth);
738 void sendResizeEvent();
739 void sendScrollEvent();
740 bool scrollbarsVisible();
741 void scrollToAnchor(const KURL &);
742 bool canMouseDownStartSelect(Node*);
743 bool passWidgetMouseDownEventToWidget(const MouseEventWithHitTestResults&, bool isDoubleClick);
744 bool passWidgetMouseDownEventToWidget(RenderWidget*);
745 virtual bool passMouseDownEventToWidget(Widget*) = 0;
748 static void clearTimers(FrameView *);
750 bool displaysWithFocusAttributes() const;
751 virtual void setDisplaysWithFocusAttributes(bool flag);
752 void setWindowHasFocus(bool flag);
753 // Convenience, to avoid repeating the code to dig down to get this.
755 QChar backslashAsCurrencySymbol() const;
757 DeprecatedValueList<MarkedTextUnderline> markedTextUnderlines() const;
758 bool markedTextUsesUnderlines() const;
759 unsigned highlightAllMatchesForString(const DeprecatedString &, bool caseFlag);
761 // Call this method before handling a new user action, like on a mouse down or key down.
762 // Currently, all this does is clear the "don't submit form twice" data member.
763 void prepareForUserAction();
764 Node *mousePressNode();
766 void clearRecordedFormValues();
767 void recordFormValue(const String& name, const String& value, PassRefPtr<HTMLFormElement>);
769 bool isComplete() const;
770 bool isLoadingMainResource() const;
772 void replaceContentsWithScriptResult(const KURL &url);
774 void disconnectOwnerRenderer();
777 virtual void startRedirectionTimer();
778 virtual void stopRedirectionTimer();
780 void handleAutoscroll(RenderLayer*);
781 void startAutoscrollTimer();
782 void stopAutoscrollTimer();
785 void emitLoadEvent();
787 void receivedFirstData();
789 bool deleteMe1(const MouseEventWithHitTestResults&);
790 bool deleteMe2(const MouseEventWithHitTestResults&);
791 void handleMouseMoveEventPart2(const MouseEventWithHitTestResults&);
794 * @internal Extracts anchor and tries both encoded and decoded form.
798 void handleMousePressEventSingleClick(const MouseEventWithHitTestResults&);
799 void handleMousePressEventDoubleClick(const MouseEventWithHitTestResults&);
800 void handleMousePressEventTripleClick(const MouseEventWithHitTestResults&);
802 CSSComputedStyleDeclaration *selectionComputedStyle(Node *&nodeToRemove) const;
804 virtual void setStatusBarText(const String&);
806 void autoscrollTimerFired(Timer<Frame>*);
809 friend class FrameMac;
810 friend class FrameWin;
812 void checkEmitLoadEvent();
813 bool didOpenURL(const KURL &);
814 virtual void didFirstLayout() {}
816 virtual void frameDetached();
818 virtual void detachFromView();
819 void updateBaseURLForEmptyDocument();
822 void setResourceRequest(const ResourceRequest& request);
823 const ResourceRequest& resourceRequest() const;
825 // split out controller objects
826 FrameTree* tree() const;
827 SelectionController& selection() const;
830 friend class FramePrivate;