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 "DeprecatedStringList.h"
34 #include "EditAction.h"
35 #include "FrameView.h"
37 #include "RenderObject.h"
38 #include "ScrollBar.h"
39 #include "TextAffinity.h"
40 #include "TextGranularity.h"
41 #include <wtf/Vector.h>
47 class SavedProperties;
57 class CSSComputedStyleDeclaration;
58 class CSSMutableStyleDeclaration;
59 class CSSStyleDeclaration;
60 class DrawContentsEvent;
68 class MouseEventWithHitTestResults;
72 class SelectionController;
74 class VisiblePosition;
76 template <typename T> class Timer;
78 struct MarkedTextUnderline {
80 : startOffset(0), endOffset(0), thick(false) { }
81 MarkedTextUnderline(unsigned s, unsigned e, const Color& c, bool t)
82 : startOffset(s), endOffset(e), color(c), thick(t) { }
89 enum ObjectContentType {
96 class Frame : public Shared<Frame>, Noncopyable {
98 enum { NoXPosForVerticalArrowNavigation = INT_MIN };
100 Frame(Page*, Element*);
103 virtual bool openURL(const KURL&);
104 virtual bool closeURL();
106 void didExplicitOpen();
109 void pageDestroyed();
112 * Stop loading the document and kill all data requests (for images, etc.)
114 void stopLoading(bool sendUnload = false);
117 * Returns a pointer to the @ref BrowserExtension.
119 BrowserExtension* browserExtension() const;
122 * Returns a pointer to the HTML document's view.
124 FrameView* view() const;
126 virtual void setView(FrameView*);
129 * Returns @p true if Javascript is enabled, @p false otherwise.
131 bool jScriptEnabled() const;
134 * Returns true if Java is enabled, false otherwise.
136 bool javaEnabled() const;
139 * Returns true if plugins are enabled, false otherwise.
141 bool pluginsEnabled() const;
144 * Execute the specified snippet of JavaScript code.
146 KJS::JSValue* executeScript(Node*, const String& script, bool forceUserGesture = false);
149 * Implementation of CSS property -webkit-user-drag == auto
151 virtual bool shouldDragAutoNode(Node*, const IntPoint&) const;
154 * Specifies whether images contained in the document should be loaded
155 * automatically or not.
157 * @note Request will be ignored if called before @ref begin().
159 void setAutoloadImages(bool enable);
161 * Returns whether images contained in the document are loaded automatically
163 * @note that the returned information is unreliable as long as no begin()
166 bool autoloadImages() const;
168 KURL baseURL() const;
169 String baseTarget() const;
172 * Schedules a redirection after @p delay seconds.
174 void scheduleRedirection(double delay, const DeprecatedString& url, bool lockHistory = true);
177 * Make a location change, or schedule one for later.
178 * These are used for JavaScript-triggered location changes.
180 void changeLocation(const DeprecatedString& URL, const String& referrer, bool lockHistory = true, bool userGesture = false);
181 void scheduleLocationChange(const DeprecatedString& url, const String& referrer, bool lockHistory = true, bool userGesture = false);
182 void scheduleRefresh(bool userGesture = false);
183 bool isScheduledLocationChangePending() const;
186 * Schedules a history navigation operation (go forward, go back, etc.).
187 * This is used for JavaScript-triggered location changes.
189 void scheduleHistoryNavigation(int steps);
192 * Clears the widget and prepares it for new content.
194 * If you want @ref url() to return
195 * for example "file:/tmp/test.html", you can use the following code:
197 * view->begin(KURL("file:/tmp/test.html"));
200 * @param url is the url of the document to be displayed. Even if you
201 * are generating the HTML on the fly, it may be useful to specify
202 * a directory so that any images are found.
204 * All child frames and the old document are removed if you call
207 virtual void begin(const KURL& url = KURL());
210 * Writes another part of the HTML code to the widget.
213 * this function many times in sequence. But remember: The fewer calls
214 * you make, the faster the widget will be.
216 * The HTML code is sent through a decoder which decodes the stream to
219 * The @p len parameter is needed for streams encoded in utf-16,
220 * since these can have \0 chars in them. In case the encoding
221 * you're using isn't utf-16, you can safely leave out the length
224 * Attention: Don't mix calls to @ref write(const char*) with calls
225 * to @ref write(const String&).
227 * The result might not be what you want.
229 virtual void write(const char* str, int len = -1);
232 * Writes another part of the HTML code to the widget.
235 * this function many times in sequence. But remember: The fewer calls
236 * you make, the faster the widget will be.
238 virtual void write(const String&);
241 * Call this after your last call to @ref write().
245 void endIfNotLoading();
248 * Similar to end, but called to abort a load rather than cleanly end.
252 void paint(GraphicsContext*, const IntRect&);
254 void setEncoding(const String& encoding, bool userChosen);
255 String encoding() const;
258 * Sets a user defined style sheet to be used on top of the HTML4,
259 * SVG and printing default style sheets.
261 void setUserStyleSheetLocation(const KURL&);
262 void setUserStyleSheet(const String& styleSheetData);
265 * Sets the standard font style.
267 * @param name The font name to use for standard text.
269 void setStandardFont(const String& name);
272 * Sets the fixed font style.
274 * @param name The font name to use for fixed text, e.g.
275 * the <tt><pre></tt> tag.
277 void setFixedFont(const String& name);
280 * Finds the anchor named @p name.
282 * If the anchor is found, the widget
283 * scrolls to the closest position. Returns @p if the anchor has
286 bool gotoAnchor(const String& name);
289 * Sets the Zoom factor. The value is given in percent, larger values mean a
290 * generally larger font and larger page contents. It is not guaranteed that
291 * all parts of the page are scaled with the same factor though.
293 * The given value should be in the range of 20..300, values outside that
294 * range are not guaranteed to work. A value of 100 will disable all zooming
295 * and show the page with the sizes determined via the given lengths in the
298 void setZoomFactor(int percent);
301 * Returns the current zoom factor.
303 int zoomFactor() const;
306 * Returns the text the user has marked.
308 virtual String selectedText() const;
310 bool findString(const String&, bool, bool, bool);
313 * Returns the granularity of the selection (character, word, line, paragraph).
315 TextGranularity selectionGranularity() const;
318 * Sets the granularity of the selection (character, word, line, paragraph).
320 void setSelectionGranularity(TextGranularity granularity) const;
322 // FIXME: Replace these with functions on the selection controller.
323 bool shouldChangeSelection(const Selection&) const;
324 virtual bool shouldDeleteSelection(const Selection&) const;
325 void clearCaretRectIfNeeded();
326 void setFocusNodeIfNeeded();
327 void selectionLayoutChanged();
328 void notifyRendererOfSelectionChange(bool userTriggered);
331 * Returns a mark, to be used as emacs uses it.
333 const Selection& mark() const;
334 void setMark(const Selection&);
337 * Transposes characters either side of caret selection.
342 * Invalidates the current selection.
344 void invalidateSelection();
346 void setCaretVisible(bool flag = true);
347 void paintCaret(GraphicsContext*, const IntRect&) const;
348 void paintDragCaret(GraphicsContext*, const IntRect&) const;
351 * Set info for vertical arrow navigation.
353 void setXPosForVerticalArrowNavigation(int x);
356 * Get info for vertical arrow navigation.
358 int xPosForVerticalArrowNavigation() const;
361 * Has the user selected anything?
363 * Call @ref selectedText() to
364 * retrieve the selected text.
366 * @return @p true if there is text selected.
368 bool hasSelection() const;
371 * Marks all text in the document as selected.
376 * Marks contents of node as selected.
377 * Returns whether the selection changed.
379 bool selectContentsOfNode(Node*);
382 * Returns whether editing should end in the given range
384 virtual bool shouldBeginEditing(const Range*) const;
387 * Returns whether editing should end in the given range
389 virtual bool shouldEndEditing(const Range*) const;
392 * Called when editing has begun.
394 virtual void didBeginEditing() const {};
397 * Called when editing has ended.
399 virtual void didEndEditing() const {};
402 * Returns the contentEditable "override" value for the part
404 virtual bool isContentEditable() const;
406 virtual void textFieldDidBeginEditing(Element*);
407 virtual void textFieldDidEndEditing(Element*);
408 virtual void textDidChangeInTextField(Element*);
409 virtual bool doTextFieldCommandFromEvent(Element*, const PlatformKeyboardEvent*);
410 virtual void textWillBeDeletedInTextField(Element* input);
411 virtual void textDidChangeInTextArea(Element*);
413 virtual bool inputManagerHasMarkedText() const { return false; }
415 virtual void setSecureKeyboardEntry(bool) {};
416 virtual bool isSecureKeyboardEntry() { return false; }
418 bool isSelectionInPasswordField();
421 * Returns the most recent edit command applied.
423 EditCommand* lastEditCommand();
426 * Called when editing has been applied.
428 void appliedEditing(PassRefPtr<EditCommand>);
431 * Called when editing has been unapplied.
433 void unappliedEditing(PassRefPtr<EditCommand>);
436 * Called when editing has been reapplied.
438 void reappliedEditing(PassRefPtr<EditCommand>);
441 * Returns the typing style for the document.
443 CSSMutableStyleDeclaration* typingStyle() const;
446 * Sets the typing style for the document.
448 void setTypingStyle(CSSMutableStyleDeclaration*);
451 * Clears the typing style for the document.
453 void clearTypingStyle();
455 virtual void tokenizerProcessedData() {}
457 bool inViewSourceMode() const;
458 void setInViewSourceMode(bool = true) const;
460 const Settings* settings() const;
462 void setJSStatusBarText(const String&);
463 void setJSDefaultStatusBarText(const String&);
464 String jsStatusBarText() const;
465 String jsDefaultStatusBarText() const;
468 * Referrer used for links in this page.
470 String referrer() const;
473 * Last-modified date (in raw string format), if received in the [HTTP] headers.
475 String lastModified() const;
477 bool isPointInsideSelection(const IntPoint&);
479 virtual bool tabsToLinks() const;
480 virtual bool tabsToAllControls() const;
482 // Editing operations.
483 enum TriState { falseTriState, trueTriState, mixedTriState };
484 void copyToPasteboard();
485 void cutToPasteboard();
486 void pasteFromPasteboard();
487 void pasteAndMatchStyle();
489 virtual bool canPaste() const = 0;
492 virtual bool canRedo() const = 0;
493 virtual bool canUndo() const = 0;
494 void computeAndSetTypingStyle(CSSStyleDeclaration* , EditAction editingAction=EditActionUnspecified);
495 void applyStyle(CSSStyleDeclaration* , EditAction editingAction=EditActionUnspecified);
496 void applyParagraphStyle(CSSStyleDeclaration* , EditAction editingAction=EditActionUnspecified);
497 TriState selectionHasStyle(CSSStyleDeclaration*) const;
498 bool selectionStartHasStyle(CSSStyleDeclaration*) const;
499 TriState selectionListState() const;
500 String selectionStartStylePropertyValue(int stylePropertyID) const;
501 void applyEditingStyleToBodyElement() const;
502 void removeEditingStyleFromBodyElement() const;
503 void applyEditingStyleToElement(Element*) const;
504 void removeEditingStyleFromElement(Element*) const;
505 virtual void print() = 0;
506 virtual bool isCharacterSmartReplaceExempt(UChar, bool);
508 // Used to keep the part alive when running a script that might destroy it.
511 static void endAllLifeSupport();
514 * returns a KURL object for the given url. Use when
515 * you know what you're doing.
517 KURL completeURL(const DeprecatedString& url);
519 virtual void handleMouseReleaseDoubleClickEvent(const MouseEventWithHitTestResults&);
520 virtual void handleMousePressEvent(const MouseEventWithHitTestResults&);
521 virtual void handleMouseMoveEvent(const MouseEventWithHitTestResults&);
522 virtual void handleMouseReleaseEvent(const MouseEventWithHitTestResults&);
524 void selectClosestWordFromMouseEvent(const PlatformMouseEvent&, Node* innerNode);
526 virtual void urlSelected(const DeprecatedString& url, const String& target);
527 virtual void urlSelected(const ResourceRequest&, const String& target);
530 // Methods with platform-specific overrides (and no base class implementation).
531 virtual void setTitle(const String&) = 0;
532 virtual void handledOnloadEvents() = 0;
533 virtual String userAgent() const = 0;
534 virtual String incomingReferrer() const = 0;
535 virtual String mimeTypeForFileName(const String&) const = 0;
536 virtual KJS::Bindings::Instance* getEmbedInstanceForWidget(Widget*) = 0;
537 virtual KJS::Bindings::Instance* getObjectInstanceForWidget(Widget*) = 0;
538 virtual KJS::Bindings::Instance* getAppletInstanceForWidget(Widget*) = 0;
539 virtual KJS::Bindings::RootObject* bindingRootObject() = 0;
541 virtual void markMisspellingsInAdjacentWords(const VisiblePosition&) = 0;
542 virtual void markMisspellings(const Selection&) = 0;
543 virtual void addMessageToConsole(const String& message, unsigned int lineNumber, const String& sourceID) = 0;
544 virtual void runJavaScriptAlert(const String& message) = 0;
545 virtual bool runJavaScriptConfirm(const String& message) = 0;
546 virtual bool runJavaScriptPrompt(const String& message, const String& defaultValue, String& result) = 0;
547 virtual bool shouldInterruptJavaScript() = 0;
548 virtual bool locationbarVisible() = 0;
549 virtual bool menubarVisible() = 0;
550 virtual bool personalbarVisible() = 0;
551 virtual bool statusbarVisible() = 0;
552 virtual bool toolbarVisible() = 0;
553 virtual void scheduleClose() = 0;
554 virtual void focusWindow() = 0;
555 virtual void unfocusWindow() = 0;
556 virtual void createEmptyDocument() = 0;
557 virtual Range* markedTextRange() const = 0;
558 virtual void registerCommandForUndo(PassRefPtr<EditCommand>) = 0;
559 virtual void registerCommandForRedo(PassRefPtr<EditCommand>) = 0;
560 virtual void clearUndoRedoOperations() = 0;
561 virtual void issueUndoCommand() = 0;
562 virtual void issueRedoCommand() = 0;
563 virtual void issueCutCommand() = 0;
564 virtual void issueCopyCommand() = 0;
565 virtual void issuePasteCommand() = 0;
566 virtual void issuePasteAndMatchStyleCommand() = 0;
567 virtual void issueTransposeCommand() = 0;
568 virtual void respondToChangedSelection(const Selection& oldSelection, bool closeTyping) = 0;
569 virtual void respondToChangedContents(const Selection& endingSelection) = 0;
570 virtual bool shouldChangeSelection(const Selection& oldSelection, const Selection& newSelection, EAffinity affinity, bool stillSelecting) const = 0;
571 virtual void partClearedInBegin() = 0;
572 virtual void saveDocumentState() = 0;
573 virtual void restoreDocumentState() = 0;
574 virtual bool canGoBackOrForward(int distance) const = 0;
575 virtual void openURLRequest(const ResourceRequest&) = 0;
576 virtual void submitForm(const ResourceRequest&) = 0;
577 virtual void urlSelected(const ResourceRequest&) = 0;
578 virtual bool passSubframeEventToSubframe(MouseEventWithHitTestResults&, Frame* subframePart = 0) = 0;
579 virtual bool passWheelEventToChildWidget(Node*) = 0;
580 virtual bool lastEventIsMouseUp() const = 0;
581 virtual String overrideMediaType() const = 0;
582 virtual void redirectDataToPlugin(Widget* pluginWidget) { }
584 virtual Plugin* createPlugin(Element* node, const KURL& url, const Vector<String>& paramNames, const Vector<String>& paramValues, const String& mimeType) = 0;
585 virtual Frame* createFrame(const KURL& url, const String& name, Element* ownerElement, const String& referrer) = 0;
586 virtual ObjectContentType objectContentType(const KURL& url, const String& mimeType) = 0;
588 virtual void redirectionTimerFired(Timer<Frame>*);
593 void finishedParsing();
595 void checkCompleted();
597 void reparseConfiguration();
603 void submitFormAgain();
607 void completed(bool);
608 void childCompleted(bool);
609 void parentCompleted();
611 void lifeSupportTimerFired(Timer<Frame>*);
612 void endLifeSupport();
614 virtual void clear(bool clearWindowProperties = true);
616 void caretBlinkTimerFired(Timer<Frame>*);
618 bool shouldUsePlugin(Node* element, const KURL& url, const String& mimeType, bool hasFallback, bool& useFallback);
619 bool loadPlugin(RenderPart* renderer, const KURL& url, const String& mimeType,
620 const Vector<String>& paramNames, const Vector<String>& paramValues, bool useFallback);
621 Frame* loadSubframe(Element* ownerElement, const KURL& url, const String& name, const String& referrer);
624 void submitForm(const char* action, const String& url, const FormData& formData,
625 const String& target, const String& contentType = String(),
626 const String& boundary = String());
628 bool requestObject(RenderPart* frame, const String& url, const AtomicString& frameName,
629 const String& serviceType, const Vector<String>& paramNames, const Vector<String>& paramValues);
630 bool requestFrame(Element* ownerElement, const String& url, const AtomicString& frameName);
632 Document* document() const;
633 void setDocument(Document* newDoc);
635 // Workaround for the fact that it's hard to delete a frame.
636 // Call this after doing user-triggered selections to make it easy to delete the frame you entirely selected.
637 void selectFrameElementInParentIfFullySelected();
639 virtual bool mouseDownMayStartSelect() const { return true; }
641 void handleFallbackContent();
644 void cancelRedirection(bool newLoadInProgress = false);
647 KJS::JSValue* executeScript(const String& filename, int baseLine, Node*, const String& script);
650 void setOpener(Frame* _opener);
652 void setOpenedByJS(bool _openedByJS);
654 void setSettings(Settings*);
656 void provisionalLoadStarted();
657 bool userGestureHint();
658 void didNotOpenURL(const KURL&);
659 void addData(const char* bytes, int length);
660 void addMetaData(const String& key, const String& value);
661 void setMediaType(const String&);
663 // root renderer for the document contained in this frame
664 RenderObject* renderer() const;
666 Element* ownerElement();
667 // renderer for the element that contains this frame
668 RenderPart* ownerRenderer();
670 IntRect selectionRect() const;
671 FloatRect visibleSelectionRect() const;
672 bool isFrameSet() const;
674 HTMLFormElement* currentForm() const;
676 RenderStyle* styleForSelectionStart(Node* &nodeToRemove) const;
678 // Scrolls as necessary to reveal the selection
679 void revealSelection();
680 // Centers the selection regardless of whether it was already visible
681 void centerSelectionInVisibleArea() const;
682 void setSelectionFromNone();
684 bool scrollOverflow(ScrollDirection direction, ScrollGranularity granularity);
686 void adjustPageHeight(float* newBottom, float oldTop, float oldBottom, float bottomLimit);
689 KJS::PausedTimeouts* pauseTimeouts();
690 void resumeTimeouts(KJS::PausedTimeouts*);
691 void saveWindowProperties(KJS::SavedProperties* windowProperties);
692 void saveLocationProperties(KJS::SavedProperties* locationProperties);
693 void restoreWindowProperties(KJS::SavedProperties* windowProperties);
694 void restoreLocationProperties(KJS::SavedProperties* locationProperties);
695 void saveInterpreterBuiltins(KJS::SavedBuiltins& interpreterBuiltins);
696 void restoreInterpreterBuiltins(const KJS::SavedBuiltins& interpreterBuiltins);
698 static Frame* frameForWidget(const Widget*);
699 static Node* nodeForWidget(const Widget*);
700 static Frame* frameForNode(Node*);
702 static void clearDocumentFocus(Widget*);
704 void updatePolicyBaseURL();
705 void setPolicyBaseURL(const String&);
708 void forceLayoutWithPageWidthRange(float minPageWidth, float maxPageWidth);
710 void sendResizeEvent();
711 void sendScrollEvent();
712 bool scrollbarsVisible();
713 void scrollToAnchor(const KURL&);
714 bool canMouseDownStartSelect(Node*);
715 bool passWidgetMouseDownEventToWidget(const MouseEventWithHitTestResults&, bool isDoubleClick);
716 bool passWidgetMouseDownEventToWidget(RenderWidget*);
717 virtual bool passMouseDownEventToWidget(Widget*) = 0;
720 static void clearTimers(FrameView*);
722 bool isActive() const;
723 virtual void setIsActive(bool flag);
724 void setWindowHasFocus(bool flag);
725 // Convenience, to avoid repeating the code to dig down to get this.
727 UChar backslashAsCurrencySymbol() const;
729 const Vector<MarkedTextUnderline>& markedTextUnderlines() const;
730 bool markedTextUsesUnderlines() const;
732 unsigned markAllMatchesForText(const String&, bool caseFlag);
733 bool markedTextMatchesAreHighlighted() const;
734 void setMarkedTextMatchesAreHighlighted(bool flag);
736 // Call this method before handling a new user action, like on a mouse down or key down.
737 // Currently, all this does is clear the "don't submit form twice" data member.
738 void prepareForUserAction();
739 Node* mousePressNode();
741 void clearRecordedFormValues();
742 void recordFormValue(const String& name, const String& value, PassRefPtr<HTMLFormElement>);
744 bool isComplete() const;
745 bool isLoadingMainResource() const;
747 void replaceContentsWithScriptResult(const KURL& url);
749 void disconnectOwnerElement();
751 void setNeedsReapplyStyles();
754 virtual void startRedirectionTimer();
755 virtual void stopRedirectionTimer();
756 virtual void cleanupPluginObjects() { }
758 void handleAutoscroll(RenderLayer*);
759 void startAutoscrollTimer();
760 void stopAutoscrollTimer();
763 void emitLoadEvent();
765 void receivedFirstData();
768 * @internal Extracts anchor and tries both encoded and decoded form.
772 void handleMousePressEventSingleClick(const MouseEventWithHitTestResults&);
773 void handleMousePressEventDoubleClick(const MouseEventWithHitTestResults&);
774 void handleMousePressEventTripleClick(const MouseEventWithHitTestResults&);
776 CSSComputedStyleDeclaration* selectionComputedStyle(Node* &nodeToRemove) const;
778 virtual void setStatusBarText(const String&);
780 void autoscrollTimerFired(Timer<Frame>*);
783 friend class FrameMac;
784 friend class FrameWin;
786 friend class FrameGdk;
789 friend class FrameQt;
792 RenderObject::NodeInfo nodeInfoAtPoint(const IntPoint&, bool allowShadowContent);
794 String documentTypeString() const;
796 void checkEmitLoadEvent();
797 bool didOpenURL(const KURL&);
798 virtual void didFirstLayout() {}
800 virtual void frameDetached();
802 void updateBaseURLForEmptyDocument();
805 void setResourceRequest(const ResourceRequest& request);
806 const ResourceRequest& resourceRequest() const;
808 bool containsPlugins() const;
810 bool prohibitsScrolling() const;
811 void setProhibitsScrolling(const bool);
813 // split out controller objects
814 FrameTree* tree() const;
815 SelectionController* selectionController() const;
816 SelectionController* dragCaretController() const;
817 DOMWindow* domWindow() const;
820 friend class FramePrivate;
824 } // namespace WebCore