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>, Noncopyable {
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 selectClosestWordFromMouseEvent(const PlatformMouseEvent&, Node* innerNode);
529 virtual void urlSelected(const DeprecatedString& url, const String& target);
530 virtual void urlSelected(const ResourceRequest&, const String& target);
532 // Methods with platform-specific overrides (and no base class implementation).
533 virtual void setTitle(const String&) = 0;
534 virtual void handledOnloadEvents() = 0;
535 virtual String userAgent() const = 0;
536 virtual String incomingReferrer() const = 0;
537 virtual String mimeTypeForFileName(const String&) const = 0;
538 virtual KJS::Bindings::Instance* getEmbedInstanceForWidget(Widget*) = 0;
539 virtual KJS::Bindings::Instance* getObjectInstanceForWidget(Widget*) = 0;
540 virtual KJS::Bindings::Instance* getAppletInstanceForWidget(Widget*) = 0;
541 virtual KJS::Bindings::RootObject* bindingRootObject() = 0;
543 virtual void markMisspellingsInAdjacentWords(const VisiblePosition&) = 0;
544 virtual void markMisspellings(const Selection&) = 0;
545 virtual void addMessageToConsole(const String& message, unsigned int lineNumber, const String& sourceID) = 0;
546 virtual void runJavaScriptAlert(const String& message) = 0;
547 virtual bool runJavaScriptConfirm(const String& message) = 0;
548 virtual bool runJavaScriptPrompt(const String& message, const String& defaultValue, String& result) = 0;
549 virtual bool shouldInterruptJavaScript() = 0;
550 virtual bool locationbarVisible() = 0;
551 virtual bool menubarVisible() = 0;
552 virtual bool personalbarVisible() = 0;
553 virtual bool statusbarVisible() = 0;
554 virtual bool toolbarVisible() = 0;
555 virtual void scheduleClose() = 0;
556 virtual void focusWindow() = 0;
557 virtual void unfocusWindow() = 0;
558 virtual void createEmptyDocument() = 0;
559 virtual Range* markedTextRange() const = 0;
560 virtual void registerCommandForUndo(PassRefPtr<EditCommand>) = 0;
561 virtual void registerCommandForRedo(PassRefPtr<EditCommand>) = 0;
562 virtual void clearUndoRedoOperations() = 0;
563 virtual void issueUndoCommand() = 0;
564 virtual void issueRedoCommand() = 0;
565 virtual void issueCutCommand() = 0;
566 virtual void issueCopyCommand() = 0;
567 virtual void issuePasteCommand() = 0;
568 virtual void issuePasteAndMatchStyleCommand() = 0;
569 virtual void issueTransposeCommand() = 0;
570 virtual void respondToChangedSelection(const Selection& oldSelection, bool closeTyping) = 0;
571 virtual void respondToChangedContents(const Selection& endingSelection) = 0;
572 virtual bool shouldChangeSelection(const Selection& oldSelection, const Selection& newSelection, EAffinity affinity, bool stillSelecting) const = 0;
573 virtual void partClearedInBegin() = 0;
574 virtual void saveDocumentState() = 0;
575 virtual void restoreDocumentState() = 0;
576 virtual bool canGoBackOrForward(int distance) const = 0;
577 virtual void openURLRequest(const ResourceRequest&) = 0;
578 virtual void submitForm(const ResourceRequest&) = 0;
579 virtual void urlSelected(const ResourceRequest&) = 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>*);
590 virtual bool isLoadTypeReload() = 0;
591 virtual KURL originalRequestURL() const = 0;
596 void finishedParsing();
598 void checkCompleted();
600 void reparseConfiguration();
605 void submitFormAgain();
609 void completed(bool);
610 void childCompleted(bool);
611 void parentCompleted();
613 void lifeSupportTimerFired(Timer<Frame>*);
614 void endLifeSupport();
616 virtual void clear(bool clearWindowProperties = true);
618 void caretBlinkTimerFired(Timer<Frame>*);
620 bool shouldUsePlugin(Node* element, const KURL& url, const String& mimeType, bool hasFallback, bool& useFallback);
621 bool loadPlugin(RenderPart* renderer, const KURL& url, const String& mimeType,
622 const Vector<String>& paramNames, const Vector<String>& paramValues, bool useFallback);
623 Frame* loadSubframe(Element* ownerElement, const KURL& url, const String& name, const String& referrer);
626 void submitForm(const char* action, const String& url, const FormData& formData,
627 const String& target, const String& contentType = String(),
628 const String& boundary = String());
630 bool requestObject(RenderPart* frame, const String& url, const AtomicString& frameName,
631 const String& serviceType, const Vector<String>& paramNames, const Vector<String>& paramValues);
632 bool requestFrame(Element* ownerElement, const String& url, const AtomicString& frameName);
634 Document* document() const;
635 void setDocument(Document* newDoc);
637 // Workaround for the fact that it's hard to delete a frame.
638 // Call this after doing user-triggered selections to make it easy to delete the frame you entirely selected.
639 void selectFrameElementInParentIfFullySelected();
641 virtual bool mouseDownMayStartSelect() const { return true; }
643 void handleFallbackContent();
646 void cancelRedirection(bool newLoadInProgress = false);
649 KJS::JSValue* executeScript(const String& filename, int baseLine, Node*, const String& script);
652 void setOpener(Frame* _opener);
654 void setOpenedByJS(bool _openedByJS);
656 void setSettings(Settings*);
658 void provisionalLoadStarted();
659 bool userGestureHint();
660 void didNotOpenURL(const KURL&);
661 void addData(const char* bytes, int length);
662 void addMetaData(const String& key, const String& value);
663 void setMediaType(const String&);
665 // root renderer for the document contained in this frame
666 RenderObject* renderer() const;
668 Element* ownerElement();
669 // renderer for the element that contains this frame
670 RenderPart* ownerRenderer();
672 IntRect selectionRect() const;
673 FloatRect visibleSelectionRect() const;
674 bool isFrameSet() const;
676 HTMLFormElement* currentForm() const;
678 RenderStyle* styleForSelectionStart(Node* &nodeToRemove) const;
680 void revealSelection(const RenderLayer::ScrollAlignment& alignment = RenderLayer::gAlignCenterIfNeeded) const;
681 void revealCaret(const RenderLayer::ScrollAlignment& alignment = RenderLayer::gAlignCenterIfNeeded) 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*);
717 static void clearTimers(FrameView*);
719 bool isActive() const;
720 virtual void setIsActive(bool flag);
721 void setWindowHasFocus(bool flag);
722 // Convenience, to avoid repeating the code to dig down to get this.
724 UChar backslashAsCurrencySymbol() const;
726 const Vector<MarkedTextUnderline>& markedTextUnderlines() const;
727 bool markedTextUsesUnderlines() const;
729 unsigned markAllMatchesForText(const String&, bool caseFlag, unsigned limit);
730 bool markedTextMatchesAreHighlighted() const;
731 void setMarkedTextMatchesAreHighlighted(bool flag);
733 // Call this method before handling a new user action, like on a mouse down or key down.
734 // Currently, all this does is clear the "don't submit form twice" data member.
735 void prepareForUserAction();
736 Node* mousePressNode();
738 void clearRecordedFormValues();
739 void recordFormValue(const String& name, const String& value, PassRefPtr<HTMLFormElement>);
741 bool isComplete() const;
742 bool isLoadingMainResource() const;
744 void replaceContentsWithScriptResult(const KURL& url);
746 void disconnectOwnerElement();
748 void setNeedsReapplyStyles();
751 virtual void startRedirectionTimer();
752 virtual void stopRedirectionTimer();
753 virtual void cleanupPluginObjects() { }
754 void cancelAndClear();
756 void handleAutoscroll(RenderObject*);
757 void startAutoscrollTimer();
758 void stopAutoscrollTimer();
761 void emitLoadEvent();
763 void receivedFirstData();
766 * @internal Extracts anchor and tries both encoded and decoded form.
770 void handleMousePressEventSingleClick(const MouseEventWithHitTestResults&);
771 void handleMousePressEventDoubleClick(const MouseEventWithHitTestResults&);
772 void handleMousePressEventTripleClick(const MouseEventWithHitTestResults&);
774 CSSComputedStyleDeclaration* selectionComputedStyle(Node* &nodeToRemove) const;
776 virtual void setStatusBarText(const String&);
778 void autoscrollTimerFired(Timer<Frame>*);
781 friend class FrameMac;
782 friend class FrameWin;
784 friend class FrameGdk;
787 friend class FrameQt;
790 RenderObject::NodeInfo nodeInfoAtPoint(const IntPoint&, bool allowShadowContent);
792 String documentTypeString() const;
794 void checkEmitLoadEvent();
795 bool didOpenURL(const KURL&);
796 virtual void didFirstLayout() {}
798 virtual void frameDetached();
800 void detachChildren();
802 void updateBaseURLForEmptyDocument();
806 void setResourceRequest(const ResourceRequest& request);
807 const ResourceRequest& resourceRequest() const;
809 bool containsPlugins() const;
811 bool prohibitsScrolling() const;
812 void setProhibitsScrolling(const bool);
814 // split out controller objects
815 FrameTree* tree() const;
816 SelectionController* selectionController() const;
817 SelectionController* dragCaretController() const;
818 DOMWindow* domWindow() const;
820 CommandByName* command() const;
822 friend class FramePrivate;
826 } // namespace WebCore