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 "EditAction.h"
34 #include "FrameView.h"
36 #include "RenderObject.h"
37 #include "RenderLayer.h"
38 #include "ScrollBar.h"
39 #include "TextAffinity.h"
40 #include "TextGranularity.h"
41 #include <wtf/Vector.h>
47 class SavedProperties;
58 class CSSComputedStyleDeclaration;
59 class CSSMutableStyleDeclaration;
60 class CSSStyleDeclaration;
61 class DrawContentsEvent;
69 class MouseEventWithHitTestResults;
73 class SelectionController;
75 class VisiblePosition;
77 template <typename T> class Timer;
79 struct MarkedTextUnderline {
81 : startOffset(0), endOffset(0), thick(false) { }
82 MarkedTextUnderline(unsigned s, unsigned e, const Color& c, bool t)
83 : startOffset(s), endOffset(e), color(c), thick(t) { }
90 enum ObjectContentType {
97 class Frame : public Shared<Frame> {
99 enum { NoXPosForVerticalArrowNavigation = INT_MIN };
101 Frame(Page*, Element*);
104 virtual bool openURL(const KURL&);
105 virtual bool closeURL();
107 void didExplicitOpen();
110 void commitIconURLToIconDatabase();
113 void pageDestroyed();
116 * Stop loading the document and kill all data requests (for images, etc.)
118 void stopLoading(bool sendUnload = false);
121 * Returns a pointer to the @ref BrowserExtension.
123 BrowserExtension* browserExtension() const;
126 * Returns a pointer to the HTML document's view.
128 FrameView* view() const;
130 virtual void setView(FrameView*);
133 * Returns @p true if Javascript is enabled, @p false otherwise.
135 bool jScriptEnabled() const;
138 * Returns true if Java is enabled, false otherwise.
140 bool javaEnabled() const;
143 * Returns true if plugins are enabled, false otherwise.
145 bool pluginsEnabled() const;
148 * Execute the specified snippet of JavaScript code.
150 KJS::JSValue* executeScript(Node*, const String& script, bool forceUserGesture = false);
153 * Implementation of CSS property -webkit-user-drag == auto
155 virtual bool shouldDragAutoNode(Node*, const IntPoint&) const;
158 * Specifies whether images contained in the document should be loaded
159 * automatically or not.
161 * @note Request will be ignored if called before @ref begin().
163 void setAutoloadImages(bool enable);
165 * Returns whether images contained in the document are loaded automatically
167 * @note that the returned information is unreliable as long as no begin()
170 bool autoloadImages() const;
172 KURL baseURL() const;
173 String baseTarget() const;
176 * Schedules a redirection after @p delay seconds.
178 void scheduleRedirection(double delay, const DeprecatedString& url, bool lockHistory = true);
181 * Make a location change, or schedule one for later.
182 * These are used for JavaScript-triggered location changes.
184 void changeLocation(const DeprecatedString& URL, const String& referrer, bool lockHistory = true, bool userGesture = false);
185 void scheduleLocationChange(const DeprecatedString& url, const String& referrer, bool lockHistory = true, bool userGesture = false);
186 void scheduleRefresh(bool userGesture = false);
187 bool isScheduledLocationChangePending() const;
190 * Schedules a history navigation operation (go forward, go back, etc.).
191 * This is used for JavaScript-triggered location changes.
193 void scheduleHistoryNavigation(int steps);
196 * Clears the widget and prepares it for new content.
198 * If you want @ref url() to return
199 * for example "file:/tmp/test.html", you can use the following code:
201 * view->begin(KURL("file:/tmp/test.html"));
204 * @param url is the url of the document to be displayed. Even if you
205 * are generating the HTML on the fly, it may be useful to specify
206 * a directory so that any images are found.
208 * All child frames and the old document are removed if you call
211 virtual void begin(const KURL& url = KURL());
214 * Writes another part of the HTML code to the widget.
217 * this function many times in sequence. But remember: The fewer calls
218 * you make, the faster the widget will be.
220 * The HTML code is sent through a decoder which decodes the stream to
223 * The @p len parameter is needed for streams encoded in utf-16,
224 * since these can have \0 chars in them. In case the encoding
225 * you're using isn't utf-16, you can safely leave out the length
228 * Attention: Don't mix calls to @ref write(const char*) with calls
229 * to @ref write(const String&).
231 * The result might not be what you want.
233 virtual void write(const char* str, int len = -1);
236 * Writes another part of the HTML code to the widget.
239 * this function many times in sequence. But remember: The fewer calls
240 * you make, the faster the widget will be.
242 virtual void write(const String&);
245 * Call this after your last call to @ref write().
249 void endIfNotLoading();
252 * Similar to end, but called to abort a load rather than cleanly end.
256 void paint(GraphicsContext*, const IntRect&);
258 void setEncoding(const String& encoding, bool userChosen);
259 String encoding() const;
262 * Sets a user defined style sheet to be used on top of the HTML4,
263 * SVG and printing default style sheets.
265 void setUserStyleSheetLocation(const KURL&);
266 void setUserStyleSheet(const String& styleSheetData);
269 * Sets the standard font style.
271 * @param name The font name to use for standard text.
273 void setStandardFont(const String& name);
276 * Sets the fixed font style.
278 * @param name The font name to use for fixed text, e.g.
279 * the <tt><pre></tt> tag.
281 void setFixedFont(const String& name);
284 * Finds the anchor named @p name.
286 * If the anchor is found, the widget
287 * scrolls to the closest position. Returns @p if the anchor has
290 bool gotoAnchor(const String& name);
293 * Sets the Zoom factor. The value is given in percent, larger values mean a
294 * generally larger font and larger page contents. It is not guaranteed that
295 * all parts of the page are scaled with the same factor though.
297 * The given value should be in the range of 20..300, values outside that
298 * range are not guaranteed to work. A value of 100 will disable all zooming
299 * and show the page with the sizes determined via the given lengths in the
302 void setZoomFactor(int percent);
305 * Returns the current zoom factor.
307 int zoomFactor() const;
310 * Returns the text the user has marked.
312 virtual String selectedText() const;
314 bool findString(const String&, bool, bool, bool);
317 * Returns the granularity of the selection (character, word, line, paragraph).
319 TextGranularity selectionGranularity() const;
322 * Sets the granularity of the selection (character, word, line, paragraph).
324 void setSelectionGranularity(TextGranularity granularity) const;
326 // FIXME: Replace these with functions on the selection controller.
327 bool shouldChangeSelection(const Selection&) const;
328 virtual bool shouldDeleteSelection(const Selection&) const;
329 void clearCaretRectIfNeeded();
330 void setFocusNodeIfNeeded();
331 void selectionLayoutChanged();
332 void notifyRendererOfSelectionChange(bool userTriggered);
335 * Returns a mark, to be used as emacs uses it.
337 const Selection& mark() const;
338 void setMark(const Selection&);
341 * Transposes characters either side of caret selection.
346 * Invalidates the current selection.
348 void invalidateSelection();
350 void setCaretVisible(bool flag = true);
351 void paintCaret(GraphicsContext*, const IntRect&) const;
352 void paintDragCaret(GraphicsContext*, const IntRect&) const;
355 * Set info for vertical arrow navigation.
357 void setXPosForVerticalArrowNavigation(int x);
360 * Get info for vertical arrow navigation.
362 int xPosForVerticalArrowNavigation() const;
365 * Has the user selected anything?
367 * Call @ref selectedText() to
368 * retrieve the selected text.
370 * @return @p true if there is text selected.
372 bool hasSelection() const;
375 * Marks all text in the document as selected.
380 * Marks contents of node as selected.
381 * Returns whether the selection changed.
383 bool selectContentsOfNode(Node*);
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 * Returns the most recent edit command applied.
427 EditCommand* lastEditCommand();
430 * Called when editing has been applied.
432 void appliedEditing(PassRefPtr<EditCommand>);
435 * Called when editing has been unapplied.
437 void unappliedEditing(PassRefPtr<EditCommand>);
440 * Called when editing has been reapplied.
442 void reappliedEditing(PassRefPtr<EditCommand>);
445 * Returns the typing style for the document.
447 CSSMutableStyleDeclaration* typingStyle() const;
450 * Sets the typing style for the document.
452 void setTypingStyle(CSSMutableStyleDeclaration*);
455 * Clears the typing style for the document.
457 void clearTypingStyle();
459 virtual void tokenizerProcessedData() {}
461 bool inViewSourceMode() const;
462 void setInViewSourceMode(bool = true) const;
464 const Settings* settings() const;
466 void setJSStatusBarText(const String&);
467 void setJSDefaultStatusBarText(const String&);
468 String jsStatusBarText() const;
469 String jsDefaultStatusBarText() const;
472 * Referrer used for links in this page.
474 String referrer() const;
477 * Last-modified date (in raw string format), if received in the [HTTP] headers.
479 String lastModified() const;
481 bool isPointInsideSelection(const IntPoint&);
483 virtual bool tabsToLinks() const;
484 virtual bool tabsToAllControls() const;
486 // Editing operations.
487 enum TriState { falseTriState, trueTriState, mixedTriState };
488 void copyToPasteboard();
489 void cutToPasteboard();
490 void pasteFromPasteboard();
491 void pasteAndMatchStyle();
493 virtual bool canPaste() const = 0;
496 virtual bool canRedo() const = 0;
497 virtual bool canUndo() const = 0;
498 void computeAndSetTypingStyle(CSSStyleDeclaration* , EditAction editingAction=EditActionUnspecified);
499 void applyStyle(CSSStyleDeclaration* , EditAction editingAction=EditActionUnspecified);
500 void applyParagraphStyle(CSSStyleDeclaration* , EditAction editingAction=EditActionUnspecified);
501 TriState selectionHasStyle(CSSStyleDeclaration*) const;
502 bool selectionStartHasStyle(CSSStyleDeclaration*) const;
503 TriState selectionListState() const;
504 String selectionStartStylePropertyValue(int stylePropertyID) const;
505 void applyEditingStyleToBodyElement() const;
506 void removeEditingStyleFromBodyElement() const;
507 void applyEditingStyleToElement(Element*) const;
508 void removeEditingStyleFromElement(Element*) const;
509 virtual void print() = 0;
510 virtual bool isCharacterSmartReplaceExempt(UChar, bool);
512 // Used to keep the part alive when running a script that might destroy it.
515 static void endAllLifeSupport();
518 * returns a KURL object for the given url. Use when
519 * you know what you're doing.
521 KURL completeURL(const DeprecatedString& url);
523 virtual void handleMousePressEvent(const MouseEventWithHitTestResults&);
524 virtual void handleMouseMoveEvent(const MouseEventWithHitTestResults&);
525 virtual void handleMouseReleaseEvent(const MouseEventWithHitTestResults&);
527 void updateSelectionForMouseDragOverPosition(const VisiblePosition&);
529 void selectClosestWordFromMouseEvent(const PlatformMouseEvent&, Node* innerNode);
531 virtual void urlSelected(const DeprecatedString& url, const String& target);
532 virtual void urlSelected(const ResourceRequest&, const String& target);
534 // Methods with platform-specific overrides (and no base class implementation).
535 virtual void setTitle(const String&) = 0;
536 virtual void handledOnloadEvents() = 0;
537 virtual String userAgent() const = 0;
538 virtual String incomingReferrer() const = 0;
539 virtual String mimeTypeForFileName(const String&) const = 0;
540 virtual KJS::Bindings::Instance* getEmbedInstanceForWidget(Widget*) = 0;
541 virtual KJS::Bindings::Instance* getObjectInstanceForWidget(Widget*) = 0;
542 virtual KJS::Bindings::Instance* getAppletInstanceForWidget(Widget*) = 0;
543 virtual KJS::Bindings::RootObject* bindingRootObject() = 0;
544 virtual Widget* createJavaAppletWidget(const IntSize&, Element*, const HashMap<String, String>& args) = 0;
546 virtual void markMisspellingsInAdjacentWords(const VisiblePosition&) = 0;
547 virtual void markMisspellings(const Selection&) = 0;
548 virtual void addMessageToConsole(const String& message, unsigned int lineNumber, const String& sourceID) = 0;
549 virtual void runJavaScriptAlert(const String& message) = 0;
550 virtual bool runJavaScriptConfirm(const String& message) = 0;
551 virtual bool runJavaScriptPrompt(const String& message, const String& defaultValue, String& result) = 0;
552 virtual bool shouldInterruptJavaScript() = 0;
553 virtual bool locationbarVisible() = 0;
554 virtual bool menubarVisible() = 0;
555 virtual bool personalbarVisible() = 0;
556 virtual bool statusbarVisible() = 0;
557 virtual bool toolbarVisible() = 0;
558 virtual void scheduleClose() = 0;
559 virtual void focusWindow() = 0;
560 virtual void unfocusWindow() = 0;
561 virtual void createEmptyDocument() = 0;
562 virtual Range* markedTextRange() const = 0;
563 virtual void registerCommandForUndo(PassRefPtr<EditCommand>) = 0;
564 virtual void registerCommandForRedo(PassRefPtr<EditCommand>) = 0;
565 virtual void clearUndoRedoOperations() = 0;
566 virtual void issueUndoCommand() = 0;
567 virtual void issueRedoCommand() = 0;
568 virtual void issueCutCommand() = 0;
569 virtual void issueCopyCommand() = 0;
570 virtual void issuePasteCommand() = 0;
571 virtual void issuePasteAndMatchStyleCommand() = 0;
572 virtual void issueTransposeCommand() = 0;
573 virtual void respondToChangedSelection(const Selection& oldSelection, bool closeTyping) = 0;
574 virtual void respondToChangedContents(const Selection& endingSelection) = 0;
575 virtual bool shouldChangeSelection(const Selection& oldSelection, const Selection& newSelection, EAffinity affinity, bool stillSelecting) const = 0;
576 virtual void partClearedInBegin() = 0;
577 virtual void saveDocumentState() = 0;
578 virtual void restoreDocumentState() = 0;
579 virtual bool canGoBackOrForward(int distance) const = 0;
580 virtual void openURLRequest(const ResourceRequest&) = 0;
581 virtual void submitForm(const ResourceRequest&) = 0;
582 virtual void urlSelected(const ResourceRequest&) = 0;
583 virtual bool lastEventIsMouseUp() const = 0;
584 virtual String overrideMediaType() const = 0;
585 virtual void redirectDataToPlugin(Widget* pluginWidget) { }
587 virtual Plugin* createPlugin(Element* node, const KURL& url, const Vector<String>& paramNames, const Vector<String>& paramValues, const String& mimeType) = 0;
588 virtual Frame* createFrame(const KURL& url, const String& name, Element* ownerElement, const String& referrer) = 0;
589 virtual ObjectContentType objectContentType(const KURL& url, const String& mimeType) = 0;
591 virtual void redirectionTimerFired(Timer<Frame>*);
593 virtual bool isLoadTypeReload() = 0;
594 virtual KURL originalRequestURL() const = 0;
599 void finishedParsing();
601 void checkCompleted();
603 void reparseConfiguration();
608 void submitFormAgain();
612 void completed(bool);
613 void childCompleted(bool);
614 void parentCompleted();
616 void lifeSupportTimerFired(Timer<Frame>*);
617 void endLifeSupport();
619 virtual void clear(bool clearWindowProperties = true);
621 void caretBlinkTimerFired(Timer<Frame>*);
623 bool shouldUsePlugin(Node* element, const KURL& url, const String& mimeType, bool hasFallback, bool& useFallback);
624 bool loadPlugin(RenderPart* renderer, const KURL& url, const String& mimeType,
625 const Vector<String>& paramNames, const Vector<String>& paramValues, bool useFallback);
626 Frame* loadSubframe(Element* ownerElement, const KURL& url, const String& name, const String& referrer);
629 void submitForm(const char* action, const String& url, const FormData& formData,
630 const String& target, const String& contentType = String(),
631 const String& boundary = String());
633 bool requestObject(RenderPart* frame, const String& url, const AtomicString& frameName,
634 const String& serviceType, const Vector<String>& paramNames, const Vector<String>& paramValues);
635 bool requestFrame(Element* ownerElement, const String& url, const AtomicString& frameName);
637 Document* document() const;
638 void setDocument(Document* newDoc);
640 // Workaround for the fact that it's hard to delete a frame.
641 // Call this after doing user-triggered selections to make it easy to delete the frame you entirely selected.
642 void selectFrameElementInParentIfFullySelected();
644 virtual bool mouseDownMayStartSelect() const { return true; }
645 bool mouseDownMayStartAutoscroll() const;
646 void setMouseDownMayStartAutoscroll(bool b);
648 bool mouseDownMayStartDrag() const;
649 void setMouseDownMayStartDrag(bool b);
651 void handleFallbackContent();
654 void cancelRedirection(bool newLoadInProgress = false);
657 KJS::JSValue* executeScript(const String& filename, int baseLine, Node*, const String& script);
660 void setOpener(Frame* _opener);
662 void setOpenedByJS(bool _openedByJS);
664 void setSettings(Settings*);
666 void provisionalLoadStarted();
667 bool userGestureHint();
668 void didNotOpenURL(const KURL&);
669 void addData(const char* bytes, int length);
670 void addMetaData(const String& key, const String& value);
671 void setMediaType(const String&);
673 // root renderer for the document contained in this frame
674 RenderObject* renderer() const;
676 Element* ownerElement();
677 // renderer for the element that contains this frame
678 RenderPart* ownerRenderer();
680 IntRect selectionRect() const;
681 FloatRect visibleSelectionRect() const;
682 bool isFrameSet() const;
684 HTMLFormElement* currentForm() const;
686 RenderStyle* styleForSelectionStart(Node* &nodeToRemove) const;
688 void revealSelection(const RenderLayer::ScrollAlignment& alignment = RenderLayer::gAlignCenterIfNeeded) const;
689 void revealCaret(const RenderLayer::ScrollAlignment& alignment = RenderLayer::gAlignCenterIfNeeded) const;
690 void setSelectionFromNone();
692 bool scrollOverflow(ScrollDirection direction, ScrollGranularity granularity);
694 void adjustPageHeight(float* newBottom, float oldTop, float oldBottom, float bottomLimit);
697 KJS::PausedTimeouts* pauseTimeouts();
698 void resumeTimeouts(KJS::PausedTimeouts*);
699 void saveWindowProperties(KJS::SavedProperties* windowProperties);
700 void saveLocationProperties(KJS::SavedProperties* locationProperties);
701 void restoreWindowProperties(KJS::SavedProperties* windowProperties);
702 void restoreLocationProperties(KJS::SavedProperties* locationProperties);
703 void saveInterpreterBuiltins(KJS::SavedBuiltins& interpreterBuiltins);
704 void restoreInterpreterBuiltins(const KJS::SavedBuiltins& interpreterBuiltins);
706 static Frame* frameForWidget(const Widget*);
707 static Node* nodeForWidget(const Widget*);
708 static Frame* frameForNode(Node*);
710 static void clearDocumentFocus(Widget*);
712 void updatePolicyBaseURL();
713 void setPolicyBaseURL(const String&);
716 void forceLayoutWithPageWidthRange(float minPageWidth, float maxPageWidth);
718 void sendResizeEvent();
719 void sendScrollEvent();
720 bool scrollbarsVisible();
721 void scrollToAnchor(const KURL&);
722 bool canMouseDownStartSelect(Node*);
725 static void clearTimers(FrameView*);
727 bool isActive() const;
728 virtual void setIsActive(bool flag);
729 void setWindowHasFocus(bool flag);
730 // Convenience, to avoid repeating the code to dig down to get this.
732 UChar backslashAsCurrencySymbol() const;
734 const Vector<MarkedTextUnderline>& markedTextUnderlines() const;
735 bool markedTextUsesUnderlines() const;
737 unsigned markAllMatchesForText(const String&, bool caseFlag, unsigned limit);
738 bool markedTextMatchesAreHighlighted() const;
739 void setMarkedTextMatchesAreHighlighted(bool flag);
741 // Call this method before handling a new user action, like on a mouse down or key down.
742 // Currently, all this does is clear the "don't submit form twice" data member.
743 void prepareForUserAction();
744 Node* mousePressNode();
746 void clearRecordedFormValues();
747 void recordFormValue(const String& name, const String& value, PassRefPtr<HTMLFormElement>);
749 bool isComplete() const;
750 bool isLoadingMainResource() const;
752 void replaceContentsWithScriptResult(const KURL& url);
754 void disconnectOwnerElement();
756 void setNeedsReapplyStyles();
758 void stopAutoscrollTimer();
759 RenderObject* autoscrollRenderer() const;
762 virtual void startRedirectionTimer();
763 virtual void stopRedirectionTimer();
764 virtual void cleanupPluginObjects() { }
765 void cancelAndClear();
767 void handleAutoscroll(RenderObject*);
768 void startAutoscrollTimer();
769 void setAutoscrollRenderer(RenderObject*);
772 void emitLoadEvent();
774 void receivedFirstData();
777 * @internal Extracts anchor and tries both encoded and decoded form.
781 void handleMousePressEventSingleClick(const MouseEventWithHitTestResults&);
782 void handleMousePressEventDoubleClick(const MouseEventWithHitTestResults&);
783 void handleMousePressEventTripleClick(const MouseEventWithHitTestResults&);
785 CSSComputedStyleDeclaration* selectionComputedStyle(Node* &nodeToRemove) const;
787 virtual void setStatusBarText(const String&);
789 void autoscrollTimerFired(Timer<Frame>*);
792 friend class FrameMac;
793 friend class FrameWin;
795 friend class FrameGdk;
798 friend class FrameQt;
801 RenderObject::NodeInfo nodeInfoAtPoint(const IntPoint&, bool allowShadowContent);
803 String documentTypeString() const;
805 void checkEmitLoadEvent();
806 bool didOpenURL(const KURL&);
807 virtual void didFirstLayout() {}
809 virtual void frameDetached();
811 void detachChildren();
813 void updateBaseURLForEmptyDocument();
817 void setResourceRequest(const ResourceRequest&);
818 const ResourceRequest& resourceRequest() const;
820 void setResponseMIMEType(const String&);
821 const String& responseMIMEType() const;
823 bool containsPlugins() const;
825 bool prohibitsScrolling() const;
826 void setProhibitsScrolling(const bool);
828 // split out controller objects
829 FrameTree* tree() const;
830 SelectionController* selectionController() const;
831 SelectionController* dragCaretController() const;
832 DOMWindow* domWindow() const;
834 CommandByName* command() const;
836 friend class FramePrivate;
840 } // namespace WebCore