2 * Copyright (C) 2004 Apple Computer, Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 #import "WebCoreBridge.h"
28 #include <CoreFoundation/CFCharacterSetPriv.h>
31 #import "dom2_eventsimpl.h"
32 #import "dom2_rangeimpl.h"
33 #import "dom2_viewsimpl.h"
34 #import "dom_docimpl.h"
36 #import "dom_nodeimpl.h"
37 #import "dom_position.h"
38 #import "html_documentimpl.h"
39 #import "html_formimpl.h"
40 #import "html_imageimpl.h"
42 #import "htmlediting.h"
44 #import "khtml_part.h"
47 #import "kjs_window.h"
50 #import "render_canvas.h"
51 #import "render_frames.h"
52 #import "render_image.h"
53 #import "render_object.h"
54 #import "render_replaced.h"
55 #import "render_style.h"
57 #import "visible_position.h"
58 #import "xml_tokenizer.h"
60 #import <JavaScriptCore/npruntime.h>
61 #import <JavaScriptCore/jni_jsobject.h>
62 #import <JavaScriptCore/object.h>
63 #import <JavaScriptCore/runtime_root.h>
64 #import <JavaScriptCore/property_map.h>
66 #import "KWQAssertions.h"
67 #import "KWQCharsets.h"
68 #import "KWQClipboard.h"
69 #import "KWQDOMNode.h"
70 #import "KWQEditCommand.h"
72 #import "KWQFoundationExtras.h"
74 #import "KWQKHTMLPart.h"
76 #import "KWQPageState.h"
77 #import "KWQRenderTreeDebug.h"
79 #import "KWQPrinter.h"
80 #import "KWQAccObjectCache.h"
82 #import "DOMInternal.h"
83 #import "WebCoreImageRenderer.h"
84 #import "WebCoreTextRendererFactory.h"
85 #import "WebCoreViewFactory.h"
86 #import "WebCoreSettings.h"
90 using DOM::AtomicString;
91 using DOM::CSSStyleDeclarationImpl;
92 using DOM::DocumentFragmentImpl;
93 using DOM::DocumentImpl;
94 using DOM::DocumentTypeImpl;
97 using DOM::ElementImpl;
98 using DOM::HTMLElementImpl;
99 using DOM::HTMLFormElementImpl;
100 using DOM::HTMLGenericFormElementImpl;
101 using DOM::HTMLImageElementImpl;
102 using DOM::HTMLInputElementImpl;
108 using khtml::ChildrenOnly;
109 using khtml::createMarkup;
110 using khtml::Decoder;
111 using khtml::DeleteSelectionCommand;
112 using khtml::DOWNSTREAM;
113 using khtml::EAffinity;
114 using khtml::EditAction;
115 using khtml::EditCommandPtr;
116 using khtml::ETextGranularity;
117 using khtml::IncludeNode;
118 using khtml::MoveSelectionCommand;
119 using khtml::parseURL;
120 using khtml::RenderCanvas;
121 using khtml::RenderImage;
122 using khtml::RenderObject;
123 using khtml::RenderPart;
124 using khtml::RenderStyle;
125 using khtml::RenderWidget;
126 using khtml::ReplaceSelectionCommand;
127 using khtml::Selection;
128 using khtml::setAffinityUsingLinePosition;
129 using khtml::Tokenizer;
130 using khtml::TypingCommand;
131 using khtml::UPSTREAM;
132 using khtml::VisiblePosition;
134 using KJS::ExecState;
135 using KJS::ObjectImp;
136 using KJS::SavedProperties;
137 using KJS::SavedBuiltins;
140 using KParts::URLArgs;
142 using KJS::Bindings::RootObject;
144 NSString *WebCoreElementDOMNodeKey = @"WebElementDOMNode";
145 NSString *WebCoreElementFrameKey = @"WebElementFrame";
146 NSString *WebCoreElementImageAltStringKey = @"WebElementImageAltString";
147 NSString *WebCoreElementImageKey = @"WebElementImage";
148 NSString *WebCoreElementImageRectKey = @"WebElementImageRect";
149 NSString *WebCoreElementImageURLKey = @"WebElementImageURL";
150 NSString *WebCoreElementIsSelectedKey = @"WebElementIsSelected";
151 NSString *WebCoreElementLinkURLKey = @"WebElementLinkURL";
152 NSString *WebCoreElementLinkTargetFrameKey = @"WebElementTargetFrame";
153 NSString *WebCoreElementLinkLabelKey = @"WebElementLinkLabel";
154 NSString *WebCoreElementLinkTitleKey = @"WebElementLinkTitle";
155 NSString *WebCoreElementNameKey = @"WebElementName";
156 NSString *WebCoreElementTitleKey = @"WebCoreElementTitle"; // not in WebKit API for now, could be in API some day
158 NSString *WebCorePageCacheStateKey = @"WebCorePageCacheState";
160 @interface WebCoreBridge (WebCoreBridgeInternal)
161 - (RootObject *)executionContextForView:(NSView *)aView;
164 static RootObject *rootForView(void *v)
166 NSView *aView = (NSView *)v;
167 WebCoreBridge *aBridge = [[WebCoreViewFactory sharedFactory] bridgeForView:aView];
168 RootObject *root = 0;
171 root = [aBridge executionContextForView:aView];
176 static pthread_t mainThread = 0;
178 static void updateRenderingForBindings (ExecState *exec, ObjectImp *rootObject)
180 if (pthread_self() != mainThread)
186 Window *window = static_cast<Window*>(rootObject);
190 DOM::DocumentImpl *doc = static_cast<DOM::DocumentImpl*>(window->part()->document().handle());
192 doc->updateRendering();
195 static BOOL partHasSelection(WebCoreBridge *bridge)
200 KHTMLPart *part = bridge->_part;
204 if (part->selection().isNone())
207 // If a part has a selection, it should also have a document.
208 ASSERT(part->xmlDocImpl());
213 static BOOL hasCaseInsensitivePrefix(NSString *string, NSString *prefix)
215 return [string rangeOfString:prefix options:(NSCaseInsensitiveSearch | NSAnchoredSearch)].location !=
219 @implementation WebCoreBridge
221 static bool initializedObjectCacheSize = FALSE;
222 static bool initializedKJS = FALSE;
224 + (WebCoreBridge *)bridgeForDOMDocument:(DOMDocument *)document
226 return ((KWQKHTMLPart *)[document _documentImpl]->part())->bridge();
233 _part = new KWQKHTMLPart;
234 _part->setBridge(self);
236 if (!initializedObjectCacheSize){
237 khtml::Cache::setSize([self getObjectCacheSize]);
238 initializedObjectCacheSize = TRUE;
241 if (!initializedKJS) {
242 mainThread = pthread_self();
244 RootObject::setFindRootObjectForNativeHandleFunction (rootForView);
246 KJS::Bindings::Instance::setDidExecuteFunction(updateRenderingForBindings);
248 initializedKJS = TRUE;
251 _shouldCreateRenderers = YES;
256 - (void)initializeSettings: (WebCoreSettings *)settings
258 _part->setSettings ([settings settings]);
263 [self removeFromFrame];
266 _renderPart->deref(_renderPartArena);
268 _part->setBridge(nil);
276 // FIXME: This work really should not be done at deallocation time.
277 // We need to do it at some well-defined time instead.
279 [self removeFromFrame];
282 _renderPart->deref(_renderPartArena);
284 _part->setBridge(nil);
290 - (KWQKHTMLPart *)part
295 - (void)setRenderPart:(KHTMLRenderPart *)newPart;
297 RenderArena *arena = newPart->ref();
299 _renderPart->deref(_renderPartArena);
301 _renderPart = newPart;
302 _renderPartArena = arena;
305 - (KHTMLRenderPart *)renderPart
310 - (void)setParent:(WebCoreBridge *)parent
312 _part->setParent([parent part]);
315 - (void)provisionalLoadStarted
317 _part->provisionalLoadStarted();
320 - (void)openURL:(NSURL *)URL reload:(BOOL)reload contentType:(NSString *)contentType refresh:(NSString *)refresh lastModified:(NSDate *)lastModified pageCache:(NSDictionary *)pageCache
323 KWQPageState *state = [pageCache objectForKey:WebCorePageCacheStateKey];
324 _part->openURLFromPageCache(state);
330 URLArgs args(_part->browserExtension()->urlArgs());
331 args.reload = reload;
333 args.serviceType = QString::fromNSString(contentType);
335 _part->browserExtension()->setURLArgs(args);
338 if (_part->didOpenURL(URL)) {
339 // things we have to set up after calling didOpenURL
341 _part->addMetaData("http-refresh", QString::fromNSString(refresh));
344 NSString *modifiedString = [lastModified descriptionWithCalendarFormat:@"%a %b %d %Y %H:%M:%S" timeZone:nil locale:nil];
345 _part->addMetaData("modified", QString::fromNSString(modifiedString));
350 - (void)setEncoding:(NSString *)encoding userChosen:(BOOL)userChosen
352 _part->setEncoding(QString::fromNSString(encoding), userChosen);
355 - (void)addData:(NSData *)data
357 DocumentImpl *doc = _part->xmlDocImpl();
359 // Document may be nil if the part is about to redirect
360 // as a result of JS executing during load, i.e. one frame
361 // changing another's location before the frame's document
364 doc->setShouldCreateRenderers([self shouldCreateRenderers]);
365 _part->addData((const char *)[data bytes], [data length]);
374 - (void)didNotOpenURL:(NSURL *)URL pageCache:(NSDictionary *)pageCache
376 _part->didNotOpenURL(KURL(URL).url());
378 // We might have made a page cache item, but now we're bailing out due to an error before we ever
379 // transitioned to the new page (before WebFrameState==commit). The goal here is to restore any state
380 // so that the existing view (that wenever got far enough to replace) can continue being used.
381 DocumentImpl *doc = _part->xmlDocImpl();
383 doc->setInPageCache(NO);
385 KWQPageState *state = [pageCache objectForKey:WebCorePageCacheStateKey];
389 - (BOOL)canLoadURL:(NSURL *)URL fromReferrer:(NSString *)referrer hideReferrer:(BOOL *)hideReferrer
391 *hideReferrer = !hasCaseInsensitivePrefix(referrer,@"http:") && !hasCaseInsensitivePrefix(referrer, @"https:");
392 BOOL referrerIsFileURL = hasCaseInsensitivePrefix(referrer, @"file:");
394 // FIXME: temporarily let Safari RSS load local file resources, this is a
395 // hole in the security check but can be fixed later.
396 BOOL referrerIsFeedURL = hasCaseInsensitivePrefix(referrer, @"feed:") || hasCaseInsensitivePrefix(referrer, @"feeds:");
398 BOOL URLIsFileURL = [[URL scheme] compare:@"file" options:(NSCaseInsensitiveSearch|NSLiteralSearch)] == NSOrderedSame;
400 return referrerIsFileURL || !URLIsFileURL || referrerIsFeedURL;
403 - (void)saveDocumentState
405 DocumentImpl *doc = _part->xmlDocImpl();
407 QStringList list = doc->docState();
408 NSMutableArray *documentState = [[[NSMutableArray alloc] init] autorelease];
410 for (uint i = 0; i < list.count(); i++){
412 [documentState addObject: [NSString stringWithCharacters: (const unichar *)s.unicode() length: s.length()]];
414 [self saveDocumentState: documentState];
418 - (void)restoreDocumentState
420 DocumentImpl *doc = _part->xmlDocImpl();
423 NSArray *documentState = [self documentState];
426 for (uint i = 0; i < [documentState count]; i++){
427 NSString *string = [documentState objectAtIndex: i];
428 s.append(QString::fromNSString(string));
431 doc->setRestoreState(s);
435 - (void)scrollToAnchorWithURL:(NSURL *)URL
437 _part->scrollToAnchor(KURL(URL).url().latin1());
440 - (BOOL)scrollOverflowInDirection:(WebScrollDirection)direction granularity:(WebScrollGranularity)granularity
445 return _part->scrollOverflow((KWQScrollDirection)direction, (KWQScrollGranularity)granularity);
448 - (BOOL)scrollOverflowWithScrollWheelEvent:(NSEvent *)event
453 return _part->scrollOverflowWithScrollWheelEvent(event);
456 - (BOOL)saveDocumentToPageCache
458 DocumentImpl *doc = _part->xmlDocImpl();
466 _part->clearTimers();
468 SavedProperties *windowProperties = new SavedProperties;
469 _part->saveWindowProperties(windowProperties);
471 SavedProperties *locationProperties = new SavedProperties;
472 _part->saveLocationProperties(locationProperties);
474 SavedBuiltins *interpreterBuiltins = new SavedBuiltins;
475 _part->saveInterpreterBuiltins(*interpreterBuiltins);
477 KWQPageState *pageState = [[[KWQPageState alloc] initWithDocument:doc
479 windowProperties:windowProperties
480 locationProperties:locationProperties
481 interpreterBuiltins:interpreterBuiltins] autorelease];
482 [pageState setPausedActions: _part->pauseActions((const void *)pageState)];
484 return [self saveDocumentToPageCache:pageState];
489 return _part->canCachePage();
507 - (void)createKHTMLViewWithNSView:(NSView *)view marginWidth:(int)mw marginHeight:(int)mh
509 // If we own the view, delete the old one - otherwise the render _part will take care of deleting the view.
510 [self removeFromFrame];
512 KHTMLView *kview = new KHTMLView(_part, 0);
513 _part->setView(kview);
516 kview->setView(view);
518 kview->setMarginWidth(mw);
520 kview->setMarginHeight(mh);
523 - (void)scrollToAnchor:(NSString *)a
525 _part->gotoAnchor(QString::fromNSString(a));
528 - (BOOL)isSelectionEditable
530 // EDIT FIXME: This needs to consider the entire selected range
531 NodeImpl *startNode = _part->selection().start().node();
532 return startNode ? startNode->isContentEditable() : NO;
535 - (WebSelectionState)selectionState
537 switch (_part->selection().state()) {
538 case Selection::NONE:
539 return WebSelectionStateNone;
540 case Selection::CARET:
541 return WebSelectionStateCaret;
542 case Selection::RANGE:
543 return WebSelectionStateRange;
546 ASSERT_NOT_REACHED();
547 return WebSelectionStateNone;
550 - (NSString *)_documentTypeString
552 NSString *documentTypeString = nil;
553 DOM::DocumentImpl *doc = _part->xmlDocImpl();
555 DocumentTypeImpl *doctype = doc->doctype();
557 documentTypeString = doctype->toString().string().getNSString();
560 return documentTypeString;
563 - (NSString *)_stringWithDocumentTypeStringAndMarkupString:(NSString *)markupString
565 NSString *documentTypeString = [self _documentTypeString];
566 if (documentTypeString && markupString) {
567 return [NSString stringWithFormat:@"%@%@", documentTypeString, markupString];
568 } else if (documentTypeString) {
569 return documentTypeString;
570 } else if (markupString) {
577 - (NSArray *)nodesFromList:(QPtrList<NodeImpl> *)nodeList
579 NSMutableArray *nodes = [NSMutableArray arrayWithCapacity:nodeList->count()];
580 for (QPtrListIterator<NodeImpl> i(*nodeList); i.current(); ++i) {
581 [nodes addObject:[DOMNode _nodeWithImpl:i.current()]];
586 - (NSString *)markupStringFromNode:(DOMNode *)node nodes:(NSArray **)nodes
588 // FIXME: This is never "for interchange". Is that right? See the next method.
589 QPtrList<NodeImpl> nodeList;
590 NSString *markupString = createMarkup([node _nodeImpl], IncludeNode, nodes ? &nodeList : 0).getNSString();
592 *nodes = [self nodesFromList:&nodeList];
594 return [self _stringWithDocumentTypeStringAndMarkupString:markupString];
597 - (NSString *)markupStringFromRange:(DOMRange *)range nodes:(NSArray **)nodes
599 // FIXME: This is always "for interchange". Is that right? See the previous method.
600 QPtrList<NodeImpl> nodeList;
601 NSString *markupString = createMarkup([range _rangeImpl], nodes ? &nodeList : 0, AnnotateForInterchange).getNSString();
603 *nodes = [self nodesFromList:&nodeList];
605 return [self _stringWithDocumentTypeStringAndMarkupString:markupString];
608 - (NSString *)selectedString
610 QString text = _part->selectedText();
611 text.replace(QChar('\\'), _part->backslashAsCurrencySymbol());
612 return [[text.getNSString() copy] autorelease];
615 - (NSString *)stringForRange:(DOMRange *)range
617 QString text = _part->text([range _rangeImpl]);
618 text.replace(QChar('\\'), _part->backslashAsCurrencySymbol());
619 return [[text.getNSString() copy] autorelease];
630 DocumentImpl *doc = _part->xmlDocImpl();
632 doc->setFocusNode(0);
638 _part->clearSelection();
643 return _part->isFrameSet();
646 - (NSString *)styleSheetForPrinting
648 if (!_part->settings()->shouldPrintBackgrounds()) {
649 return @"* { background-image: none !important; background-color: white !important;}";
654 - (void)reapplyStylesForDeviceType:(WebCoreDeviceType)deviceType
656 _part->setMediaType(deviceType == WebCoreDeviceScreen ? "screen" : "print");
657 DocumentImpl *doc = _part->xmlDocImpl();
659 static QPaintDevice screen;
660 static QPrinter printer;
661 doc->setPaintDevice(deviceType == WebCoreDeviceScreen ? &screen : &printer);
662 if (deviceType != WebCoreDeviceScreen) {
663 doc->setPrintStyleSheet(QString::fromNSString([self styleSheetForPrinting]));
666 return _part->reparseConfiguration();
669 static BOOL nowPrinting(WebCoreBridge *self)
671 DocumentImpl *doc = self->_part->xmlDocImpl();
672 return doc && doc->paintDevice() && doc->paintDevice()->devType() == QInternal::Printer;
675 // Set or unset the printing mode in the view. We only toy with this if we're printing.
676 - (void)_setupRootForPrinting:(BOOL)onOrOff
678 if (nowPrinting(self)) {
679 RenderCanvas *root = static_cast<khtml::RenderCanvas *>(_part->xmlDocImpl()->renderer());
681 root->setPrintingMode(onOrOff);
686 - (void)forceLayoutAdjustingViewSize:(BOOL)flag
688 [self _setupRootForPrinting:YES];
689 _part->forceLayout();
691 [self adjustViewSize];
693 [self _setupRootForPrinting:NO];
696 - (void)forceLayoutWithMinimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustingViewSize:(BOOL)flag
698 [self _setupRootForPrinting:YES];
699 _part->forceLayoutWithPageWidthRange(minPageWidth, maxPageWidth);
701 [self adjustViewSize];
703 [self _setupRootForPrinting:NO];
706 - (void)sendResizeEvent
708 _part->sendResizeEvent();
711 - (void)sendScrollEvent
713 _part->sendScrollEvent();
716 - (void)drawRect:(NSRect)rect withPainter:(QPainter *)p
718 [self _setupRootForPrinting:YES];
719 _part->paint(p, QRect(rect));
720 [self _setupRootForPrinting:NO];
723 - (void)drawRect:(NSRect)rect
725 QPainter painter(nowPrinting(self));
726 bool displaysWithFocusAttributes = _part->displaysWithFocusAttributes();
727 painter.setUsesInactiveTextBackgroundColor(!displaysWithFocusAttributes);
728 painter.setDrawsFocusRing(displaysWithFocusAttributes);
729 [self drawRect:rect withPainter:&painter];
732 // Used by pagination code called from AppKit when a standalone web page is printed.
733 - (NSArray*)computePageRectsWithPrintWidthScaleFactor:(float)printWidthScaleFactor printHeight:(float)printHeight
735 [self _setupRootForPrinting:YES];
736 NSMutableArray* pages = [NSMutableArray arrayWithCapacity:5];
737 if (printWidthScaleFactor <= 0) {
738 ERROR("printWidthScaleFactor has bad value %.2f", printWidthScaleFactor);
742 if (printHeight <= 0) {
743 ERROR("printHeight has bad value %.2f", printHeight);
747 if (!_part || !_part->xmlDocImpl() || !_part->view()) return pages;
748 RenderCanvas* root = static_cast<khtml::RenderCanvas *>(_part->xmlDocImpl()->renderer());
749 if (!root) return pages;
751 KHTMLView* view = _part->view();
752 NSView* documentView = view->getDocumentView();
756 float currPageHeight = printHeight;
757 float docHeight = root->layer()->height();
758 float docWidth = root->layer()->width();
759 float printWidth = docWidth/printWidthScaleFactor;
761 // We need to give the part the opportunity to adjust the page height at each step.
762 for (float i = 0; i < docHeight; i += currPageHeight) {
763 float proposedBottom = kMin(docHeight, i + printHeight);
764 _part->adjustPageHeight(&proposedBottom, i, proposedBottom, i);
765 currPageHeight = kMax(1.0f, proposedBottom - i);
766 for (float j = 0; j < docWidth; j += printWidth) {
767 NSValue* val = [NSValue valueWithRect: NSMakeRect(j, i, printWidth, currPageHeight)];
768 [pages addObject: val];
771 [self _setupRootForPrinting:NO];
776 // This is to support the case where a webview is embedded in the view that's being printed
777 - (void)adjustPageHeightNew:(float *)newBottom top:(float)oldTop bottom:(float)oldBottom limit:(float)bottomLimit
779 [self _setupRootForPrinting:YES];
780 _part->adjustPageHeight(newBottom, oldTop, oldBottom, bottomLimit);
781 [self _setupRootForPrinting:NO];
784 - (NSObject *)copyDOMNode:(NodeImpl *)node copier:(id <WebCoreDOMTreeCopier>)copier
786 NSMutableArray *children = [[NSMutableArray alloc] init];
787 for (NodeImpl *child = node->firstChild(); child; child = child->nextSibling()) {
788 [children addObject:[self copyDOMNode:child copier:copier]];
790 NSObject *copiedNode = [copier nodeWithName:node->nodeName().string().getNSString()
791 value:node->nodeValue().string().getNSString()
792 source:createMarkup(node, ChildrenOnly).getNSString()
798 - (NSObject *)copyDOMTree:(id <WebCoreDOMTreeCopier>)copier
800 DocumentImpl *doc = _part->xmlDocImpl();
804 return [self copyDOMNode:doc copier:copier];
807 - (NSObject *)copyRenderNode:(RenderObject *)node copier:(id <WebCoreRenderTreeCopier>)copier
809 NSMutableArray *children = [[NSMutableArray alloc] init];
810 for (RenderObject *child = node->firstChild(); child; child = child->nextSibling()) {
811 [children addObject:[self copyRenderNode:child copier:copier]];
814 NSString *name = [[NSString alloc] initWithUTF8String:node->renderName()];
816 RenderPart *nodeRenderPart = dynamic_cast<RenderPart *>(node);
817 QWidget *widget = nodeRenderPart ? nodeRenderPart->widget() : 0;
818 NSView *view = widget ? widget->getView() : nil;
821 node->absolutePosition(nx,ny);
822 NSObject *copiedNode = [copier nodeWithName:name
823 position:NSMakePoint(nx,ny)
824 rect:NSMakeRect(node->xPos(), node->yPos(), node->width(), node->height())
834 - (NSObject *)copyRenderTree:(id <WebCoreRenderTreeCopier>)copier
836 RenderObject *renderer = _part->renderer();
840 return [self copyRenderNode:renderer copier:copier];
843 - (void)removeFromFrame
848 - (void)installInFrame:(NSView *)view
850 // If this isn't the main frame, it must have a render _part set, or it
851 // won't ever get installed in the view hierarchy.
852 ASSERT(self == [self mainFrame] || _renderPart != nil);
854 _part->view()->setView(view);
856 _renderPart->setWidget(_part->view());
857 // Now the render part owns the view, so we don't any more.
860 _part->view()->initScrollBars();
863 - (void)setActivationEventNumber:(int)num
865 _part->setActivationEventNumber(num);
868 - (void)mouseDown:(NSEvent *)event
870 _part->mouseDown(event);
873 - (void)mouseDragged:(NSEvent *)event
875 _part->mouseDragged(event);
878 - (void)mouseUp:(NSEvent *)event
880 _part->mouseUp(event);
883 - (void)mouseMoved:(NSEvent *)event
885 _part->mouseMoved(event);
888 - (BOOL)sendContextMenuEvent:(NSEvent *)event
890 return _part->sendContextMenuEvent(event);
893 - (DOMElement *)elementForView:(NSView *)view
895 // FIXME: implemented currently for only a subset of the KWQ widgets
896 if ([view conformsToProtocol:@protocol(KWQWidgetHolder)]) {
897 NSView <KWQWidgetHolder> *widgetHolder = view;
898 QWidget *widget = [widgetHolder widget];
900 NodeImpl *node = static_cast<const RenderWidget *>(widget->eventFilterObject())->element();
901 return [DOMElement _elementWithImpl:static_cast<ElementImpl *>(node)];
907 static NSView *viewForElement(ElementImpl *elementImpl)
909 RenderObject *renderer = elementImpl->renderer();
910 if (renderer && renderer->isWidget()) {
911 QWidget *widget = static_cast<const RenderWidget *>(renderer)->widget();
914 return widget->getView();
920 static HTMLInputElementImpl *inputElementFromDOMElement(DOMElement *element)
922 NodeImpl *node = [element _nodeImpl];
923 if (node && idFromNode(node) == ID_INPUT) {
924 return static_cast<HTMLInputElementImpl *>(node);
929 static HTMLFormElementImpl *formElementFromDOMElement(DOMElement *element)
931 NodeImpl *node = [element _nodeImpl];
932 // This should not be necessary, but an XSL file on
933 // maps.google.com crashes otherwise because it is an xslt file
934 // that contains <form> elements that aren't in any namespace, so
935 // they come out as generic CML elements
936 if (node && node->isHTMLElement() && idFromNode(node) == ID_FORM) {
937 return static_cast<HTMLFormElementImpl *>(node);
942 - (DOMElement *)elementWithName:(NSString *)name inForm:(DOMElement *)form
944 HTMLFormElementImpl *formElement = formElementFromDOMElement(form);
946 QPtrVector<HTMLGenericFormElementImpl> &elements = formElement->formElements;
947 QString targetName = QString::fromNSString(name);
948 for (unsigned int i = 0; i < elements.count(); i++) {
949 HTMLGenericFormElementImpl *elt = elements.at(i);
950 // Skip option elements, other duds
951 if (elt->name() == targetName) {
952 return [DOMElement _elementWithImpl:elt];
959 - (BOOL)elementDoesAutoComplete:(DOMElement *)element
961 HTMLInputElementImpl *inputElement = inputElementFromDOMElement(element);
962 return inputElement != nil
963 && inputElement->inputType() == HTMLInputElementImpl::TEXT
964 && inputElement->autoComplete();
967 - (BOOL)elementIsPassword:(DOMElement *)element
969 HTMLInputElementImpl *inputElement = inputElementFromDOMElement(element);
970 return inputElement != nil
971 && inputElement->inputType() == HTMLInputElementImpl::PASSWORD;
974 - (DOMElement *)formForElement:(DOMElement *)element;
976 HTMLInputElementImpl *inputElement = inputElementFromDOMElement(element);
978 HTMLFormElementImpl *formElement = inputElement->form();
980 return [DOMElement _elementWithImpl:formElement];
986 - (DOMElement *)currentForm
988 HTMLFormElementImpl *formElement = _part->currentForm();
989 return formElement ? [DOMElement _elementWithImpl:formElement] : nil;
992 - (NSArray *)controlsInForm:(DOMElement *)form
994 NSMutableArray *results = nil;
995 HTMLFormElementImpl *formElement = formElementFromDOMElement(form);
997 QPtrVector<HTMLGenericFormElementImpl> &elements = formElement->formElements;
998 for (unsigned int i = 0; i < elements.count(); i++) {
999 if (elements.at(i)->isEnumeratable()) { // Skip option elements, other duds
1000 NSView *view = viewForElement(elements.at(i));
1003 results = [NSMutableArray arrayWithObject:view];
1005 [results addObject:view];
1014 - (NSString *)searchForLabels:(NSArray *)labels beforeElement:(DOMElement *)element
1016 return _part->searchForLabelsBeforeElement(labels, [element _elementImpl]);
1019 - (NSString *)matchLabels:(NSArray *)labels againstElement:(DOMElement *)element
1021 return _part->matchLabelsAgainstElement(labels, [element _elementImpl]);
1024 - (NSDictionary *)elementAtPoint:(NSPoint)point
1026 RenderObject *renderer = _part->renderer();
1030 RenderObject::NodeInfo nodeInfo(true, true);
1031 renderer->layer()->hitTest(nodeInfo, (int)point.x, (int)point.y);
1033 NSMutableDictionary *element = [NSMutableDictionary dictionary];
1034 [element setObject:[NSNumber numberWithBool:_part->isPointInsideSelection((int)point.x, (int)point.y)]
1035 forKey:WebCoreElementIsSelectedKey];
1037 // Find the title in the nearest enclosing DOM node.
1038 // For <area> tags in image maps, walk the tree for the <area>, not the <img> using it.
1039 for (NodeImpl *titleNode = nodeInfo.innerNode(); titleNode; titleNode = titleNode->parentNode()) {
1040 if (titleNode->isElementNode()) {
1041 const AtomicString& title = static_cast<ElementImpl *>(titleNode)->getAttribute(ATTR_TITLE);
1042 if (!title.isNull()) {
1043 // We found a node with a title.
1044 QString titleText = title.string();
1045 titleText.replace(QChar('\\'), _part->backslashAsCurrencySymbol());
1046 [element setObject:titleText.getNSString() forKey:WebCoreElementTitleKey];
1052 NodeImpl *URLNode = nodeInfo.URLElement();
1054 ElementImpl *e = static_cast<ElementImpl *>(URLNode);
1055 DocumentImpl *doc = e->getDocument();
1058 const AtomicString& title = e->getAttribute(ATTR_TITLE);
1059 if (!title.isEmpty()) {
1060 QString titleText = title.string();
1061 titleText.replace(QChar('\\'), _part->backslashAsCurrencySymbol());
1062 [element setObject:titleText.getNSString() forKey:WebCoreElementLinkTitleKey];
1065 const AtomicString& link = e->getAttribute(ATTR_HREF);
1066 if (!link.isNull()) {
1067 if (e->firstChild()) {
1069 r.setStartBefore(e->firstChild());
1070 r.setEndAfter(e->lastChild());
1071 QString t = _part->text(r);
1073 [element setObject:t.getNSString() forKey:WebCoreElementLinkLabelKey];
1076 QString URLString = parseURL(link).string();
1077 [element setObject:doc->completeURL(URLString).getNSString() forKey:WebCoreElementLinkURLKey];
1080 DOMString target = e->getAttribute(ATTR_TARGET);
1081 if (target.isEmpty() && doc) { // FIXME: Take out this doc check when we're not just before a release.
1082 target = doc->baseTarget();
1084 if (!target.isEmpty()) {
1085 [element setObject:target.string().getNSString() forKey:WebCoreElementLinkTargetFrameKey];
1089 NodeImpl *node = nodeInfo.innerNonSharedNode();
1091 [element setObject:[DOMNode _nodeWithImpl:node] forKey:WebCoreElementDOMNodeKey];
1093 if (node->renderer() && node->renderer()->isImage()) {
1094 RenderImage *r = static_cast<RenderImage *>(node->renderer());
1095 NSImage *image = r->pixmap().image();
1096 // Only return image information if there is an image.
1097 if (image && !r->isDisplayingError()) {
1098 [element setObject:r->pixmap().image() forKey:WebCoreElementImageKey];
1102 if (r->absolutePosition(x, y)) {
1103 NSValue *rect = [NSValue valueWithRect:NSMakeRect(x, y, r->contentWidth(), r->contentHeight())];
1104 [element setObject:rect forKey:WebCoreElementImageRectKey];
1107 ElementImpl *i = static_cast<ElementImpl*>(node);
1109 // FIXME: Code copied from RenderImage::updateFromElement; should share.
1111 if (idFromNode(i) == ID_OBJECT) {
1112 attr = i->getAttribute(ATTR_DATA);
1114 attr = i->getAttribute(ATTR_SRC);
1116 if (!attr.isEmpty()) {
1117 QString URLString = parseURL(attr).string();
1118 [element setObject:i->getDocument()->completeURL(URLString).getNSString() forKey:WebCoreElementImageURLKey];
1121 // FIXME: Code copied from RenderImage::updateFromElement; should share.
1123 if (idFromNode(i) == ID_INPUT)
1124 alt = static_cast<HTMLInputElementImpl *>(i)->altText();
1125 else if (idFromNode(i) == ID_IMG)
1126 alt = static_cast<HTMLImageElementImpl *>(i)->altText();
1127 if (!alt.isNull()) {
1128 QString altText = alt.string();
1129 altText.replace(QChar('\\'), _part->backslashAsCurrencySymbol());
1130 [element setObject:altText.getNSString() forKey:WebCoreElementImageAltStringKey];
1138 - (NSURL *)URLWithAttributeString:(NSString *)string
1140 DocumentImpl *doc = _part->xmlDocImpl();
1144 QString rel = parseURL(QString::fromNSString(string)).string();
1145 return KURL(doc->baseURL(), rel, doc->decoder() ? doc->decoder()->codec() : 0).getNSURL();
1148 - (BOOL)searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag
1150 return _part->findString(string, forward, caseFlag, wrapFlag);
1153 - (void)jumpToSelection
1155 _part->jumpToSelection();
1158 - (NSString *)advanceToNextMisspelling
1160 return _part->advanceToNextMisspelling().getNSString();
1163 - (NSString *)advanceToNextMisspellingStartingJustBeforeSelection
1165 return _part->advanceToNextMisspelling(true).getNSString();
1168 - (void)setTextSizeMultiplier:(float)multiplier
1170 int newZoomFactor = (int)rint(multiplier * 100);
1171 if (_part->zoomFactor() == newZoomFactor) {
1174 _part->setZoomFactor(newZoomFactor);
1177 - (CFStringEncoding)textEncoding
1179 return KWQCFStringEncodingFromIANACharsetName(_part->encoding().latin1());
1182 - (NSView *)nextKeyView
1184 DocumentImpl *doc = _part->xmlDocImpl();
1188 return _part->nextKeyView(doc->focusNode(), KWQSelectingNext);
1191 - (NSView *)previousKeyView
1193 DocumentImpl *doc = _part->xmlDocImpl();
1197 return _part->nextKeyView(doc->focusNode(), KWQSelectingPrevious);
1200 - (NSView *)nextKeyViewInsideWebFrameViews
1202 DocumentImpl *doc = _part->xmlDocImpl();
1207 return _part->nextKeyViewInFrameHierarchy(doc->focusNode(), KWQSelectingNext);
1210 - (NSView *)previousKeyViewInsideWebFrameViews
1212 DocumentImpl *doc = _part->xmlDocImpl();
1217 return _part->nextKeyViewInFrameHierarchy(doc->focusNode(), KWQSelectingPrevious);
1220 - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)string
1222 return [self stringByEvaluatingJavaScriptFromString:string forceUserGesture:true];
1226 - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)string forceUserGesture:(BOOL)forceUserGesture
1228 _part->createEmptyDocument();
1229 return _part->executeScript(QString::fromNSString(string), forceUserGesture).asString().getNSString();
1232 - (WebScriptObject *)windowScriptObject
1234 return _part->windowScriptObject();
1237 - (NPObject *)windowScriptNPObject
1239 return _part->windowScriptNPObject();
1242 - (DOMDocument *)DOMDocument
1244 return [DOMDocument _documentWithImpl:_part->xmlDocImpl()];
1247 - (DOMHTMLElement *)frameElement
1249 return (DOMHTMLElement *)[[self DOMDocument] _ownerElement];
1252 - (NSAttributedString *)selectedAttributedString
1254 return _part->attributedString(_part->selectionStart(), _part->selectionStartOffset(), _part->selectionEnd(), _part->selectionEndOffset());
1257 - (NSAttributedString *)attributedStringFrom:(DOMNode *)start startOffset:(int)startOffset to:(DOMNode *)end endOffset:(int)endOffset
1259 DOMNode *startNode = start;
1260 DOMNode *endNode = end;
1261 return _part->attributedString([startNode _nodeImpl], startOffset, [endNode _nodeImpl], endOffset);
1264 - (NSRect)selectionRect
1266 return _part->selectionRect();
1269 - (NSRect)visibleSelectionRect
1271 return _part->visibleSelectionRect();
1274 - (void)centerSelectionInVisibleArea
1276 _part->centerSelectionInVisibleArea();
1279 - (NSRect)caretRectAtNode:(DOMNode *)node offset:(int)offset affinity:(NSSelectionAffinity)affinity
1281 return [node _nodeImpl]->renderer()->caretRect(offset, static_cast<EAffinity>(affinity));
1283 - (NSRect)firstRectForDOMRange:(DOMRange *)range
1285 int extraWidthToEndOfLine = 0;
1286 QRect startCaretRect = [[range startContainer] _nodeImpl]->renderer()->caretRect([range startOffset], UPSTREAM, &extraWidthToEndOfLine);
1287 QRect endCaretRect = [[range startContainer] _nodeImpl]->renderer()->caretRect([range endOffset], UPSTREAM);
1289 if (startCaretRect.y() == endCaretRect.y()) {
1290 // start and end are on the same line
1291 return QRect(MIN(startCaretRect.x(), endCaretRect.x()),
1293 abs(endCaretRect.x() - startCaretRect.x()),
1294 MAX(startCaretRect.height(), endCaretRect.height()));
1297 // start and end aren't on the same line, so go from start to the end of its line
1298 return QRect(startCaretRect.x(),
1300 startCaretRect.width() + extraWidthToEndOfLine,
1301 startCaretRect.height());
1304 - (NSImage *)selectionImage
1306 return _part->selectionImage();
1309 - (void)setName:(NSString *)name
1311 _part->KHTMLPart::setName(QString::fromNSString(name));
1316 return _part->name().getNSString();
1321 return _part->url().getNSURL();
1326 return _part->completeURL(_part->xmlDocImpl()->baseURL()).getNSURL();
1329 - (NSString *)referrer
1331 return _part->referrer().getNSString();
1334 - (NSString *)domain
1336 DocumentImpl *doc = _part->xmlDocImpl();
1337 if (doc && doc->isHTMLDocument()) {
1338 return doc->domain().string().getNSString();
1343 - (WebCoreBridge *)opener
1345 KHTMLPart *openerPart = _part->opener();
1348 return KWQ(openerPart)->bridge();
1353 + (NSString *)stringWithData:(NSData *)data textEncoding:(CFStringEncoding)textEncoding
1355 if (textEncoding == kCFStringEncodingInvalidId || textEncoding == kCFStringEncodingISOLatin1) {
1356 textEncoding = kCFStringEncodingWindowsLatin1;
1358 return QTextCodec(textEncoding).toUnicode((const char*)[data bytes], [data length]).getNSString();
1361 + (NSString *)stringWithData:(NSData *)data textEncodingName:(NSString *)textEncodingName
1363 CFStringEncoding textEncoding = KWQCFStringEncodingFromIANACharsetName([textEncodingName lossyCString]);
1364 return [WebCoreBridge stringWithData:data textEncoding:textEncoding];
1369 RenderObject *renderer = _part->renderer();
1370 return renderer ? renderer->needsLayout() : false;
1373 - (void)setNeedsLayout
1375 RenderObject *renderer = _part->renderer();
1377 renderer->setNeedsLayout(true);
1380 - (BOOL)interceptKeyEvent:(NSEvent *)event toView:(NSView *)view
1382 return _part->keyEvent(event);
1385 - (NSString *)renderTreeAsExternalRepresentation
1387 return externalRepresentation(_part->renderer()).getNSString();
1390 - (void)setSelectionFromNone
1392 _part->setSelectionFromNone();
1395 - (void)setDisplaysWithFocusAttributes:(BOOL)flag
1397 _part->setDisplaysWithFocusAttributes(flag);
1400 - (void)setWindowHasFocus:(BOOL)flag
1402 _part->setWindowHasFocus(flag);
1405 - (void)setShouldCreateRenderers:(BOOL)f
1407 _shouldCreateRenderers = f;
1410 - (BOOL)shouldCreateRenderers
1412 return _shouldCreateRenderers;
1415 - (int)numPendingOrLoadingRequests
1417 DocumentImpl *doc = _part->xmlDocImpl();
1420 return KWQNumberOfPendingOrLoadingRequests (doc->docLoader());
1424 - (BOOL)doneProcessingData
1426 DocumentImpl *doc = _part->xmlDocImpl();
1428 Tokenizer* tok = doc->tokenizer();
1430 return !tok->processingData();
1435 - (NSColor *)bodyBackgroundColor
1437 return _part->bodyBackgroundColor();
1440 - (NSColor *)selectionColor
1442 RenderCanvas* root = static_cast<khtml::RenderCanvas *>(_part->xmlDocImpl()->renderer());
1444 RenderStyle *pseudoStyle = root->getPseudoStyle(RenderStyle::SELECTION);
1445 if (pseudoStyle && pseudoStyle->backgroundColor().isValid()) {
1446 return pseudoStyle->backgroundColor().getNSColor();
1449 return _part->displaysWithFocusAttributes() ? [NSColor selectedTextBackgroundColor] : [NSColor secondarySelectedControlColor];
1452 - (void)adjustViewSize
1454 KHTMLView *view = _part->view();
1456 view->adjustViewSize();
1459 -(id)accessibilityTree
1461 KWQAccObjectCache::enableAccessibility();
1462 if (!_part || !_part->xmlDocImpl()) return nil;
1463 RenderCanvas* root = static_cast<khtml::RenderCanvas *>(_part->xmlDocImpl()->renderer());
1464 if (!root) return nil;
1465 return _part->xmlDocImpl()->getAccObjectCache()->accObject(root);
1468 - (void)setDrawsBackground:(BOOL)drawsBackground
1470 if (_part && _part->view())
1471 _part->view()->setTransparent(!drawsBackground);
1474 - (void)undoEditing:(id)arg
1476 ASSERT([arg isKindOfClass:[KWQEditCommand class]]);
1477 [arg command]->unapply();
1480 - (void)redoEditing:(id)arg
1482 ASSERT([arg isKindOfClass:[KWQEditCommand class]]);
1483 [arg command]->reapply();
1486 - (DOMRange *)rangeByExpandingSelectionWithGranularity:(WebSelectionGranularity)granularity
1488 if (!partHasSelection(self))
1491 // NOTE: The enums *must* match the very similar ones declared in ktml_selection.h
1492 Selection selection(_part->selection());
1493 _part->setSelectionGranularity(static_cast<ETextGranularity>(granularity));
1494 selection.expandUsingGranularity(static_cast<ETextGranularity>(granularity));
1495 return [DOMRange _rangeWithImpl:selection.toRange().handle()];
1498 - (DOMRange *)rangeByAlteringCurrentSelection:(WebSelectionAlteration)alteration direction:(WebSelectionDirection)direction granularity:(WebSelectionGranularity)granularity
1500 if (!partHasSelection(self))
1503 // NOTE: The enums *must* match the very similar ones declared in ktml_selection.h
1504 Selection selection(_part->selection());
1505 _part->setSelectionGranularity(static_cast<ETextGranularity>(granularity));
1506 selection.modify(static_cast<Selection::EAlter>(alteration),
1507 static_cast<Selection::EDirection>(direction),
1508 static_cast<ETextGranularity>(granularity));
1509 return [DOMRange _rangeWithImpl:selection.toRange().handle()];
1512 - (void)alterCurrentSelection:(WebSelectionAlteration)alteration direction:(WebSelectionDirection)direction granularity:(WebSelectionGranularity)granularity
1514 if (!partHasSelection(self))
1517 // NOTE: The enums *must* match the very similar ones declared in dom_selection.h
1518 Selection selection(_part->selection());
1519 _part->setSelectionGranularity(static_cast<ETextGranularity>(granularity));
1520 selection.modify(static_cast<Selection::EAlter>(alteration),
1521 static_cast<Selection::EDirection>(direction),
1522 static_cast<ETextGranularity>(granularity));
1524 // save vertical navigation x position if necessary; many types of motion blow it away
1525 int xPos = KHTMLPart::NoXPosForVerticalArrowNavigation;
1526 switch (granularity) {
1527 case WebSelectByLine:
1528 case WebSelectByParagraph:
1529 xPos = _part->xPosForVerticalArrowNavigation();
1531 case WebSelectByCharacter:
1532 case WebSelectByWord:
1533 case WebSelectToLineBoundary:
1534 case WebSelectToParagraphBoundary:
1535 case WebSelectToDocumentBoundary:
1540 // setting the selection always clears saved vertical navigation x position
1541 _part->setSelection(selection);
1543 // restore vertical navigation x position if necessary
1544 if (xPos != KHTMLPart::NoXPosForVerticalArrowNavigation)
1545 _part->setXPosForVerticalArrowNavigation(xPos);
1547 [self ensureSelectionVisible];
1550 - (DOMRange *)rangeByAlteringCurrentSelection:(WebSelectionAlteration)alteration verticalDistance:(float)verticalDistance
1552 if (!partHasSelection(self))
1555 Selection selection(_part->selection());
1556 selection.modify(static_cast<Selection::EAlter>(alteration), static_cast<int>(verticalDistance));
1557 return [DOMRange _rangeWithImpl:selection.toRange().handle()];
1560 - (void)alterCurrentSelection:(WebSelectionAlteration)alteration verticalDistance:(float)verticalDistance
1562 if (!partHasSelection(self))
1565 Selection selection(_part->selection());
1566 selection.modify(static_cast<Selection::EAlter>(alteration), static_cast<int>(verticalDistance));
1568 // setting the selection always clears saved vertical navigation x position, so preserve it
1569 int xPos = _part->xPosForVerticalArrowNavigation();
1570 _part->setSelection(selection);
1571 _part->setXPosForVerticalArrowNavigation(xPos);
1573 [self ensureSelectionVisible];
1576 - (WebSelectionGranularity)selectionGranularity
1578 // NOTE: The enums *must* match the very similar ones declared in dom_selection.h
1579 return static_cast<WebSelectionGranularity>(_part->selectionGranularity());
1582 - (void)setSelectedDOMRange:(DOMRange *)range affinity:(NSSelectionAffinity)selectionAffinity
1584 NodeImpl *startContainer = [[range startContainer] _nodeImpl];
1585 NodeImpl *endContainer = [[range endContainer] _nodeImpl];
1586 ASSERT(startContainer);
1587 ASSERT(endContainer);
1588 ASSERT(startContainer->getDocument());
1589 ASSERT(startContainer->getDocument() == endContainer->getDocument());
1591 _part->xmlDocImpl()->updateLayout();
1593 EAffinity affinity = static_cast<EAffinity>(selectionAffinity);
1595 bool rangeCollapsed = [range collapsed];
1596 if (!rangeCollapsed)
1597 affinity = DOWNSTREAM;
1599 // Work around bug where isRenderedContent returns false for <br> elements at the ends of lines.
1600 // If that bug wasn't an issue, we could just make the position from the range directly.
1601 Position start(startContainer, [range startOffset]);
1602 Position end(endContainer, [range endOffset]);
1603 VisiblePosition visibleStart(start, affinity, khtml::VisiblePosition::INIT_UP);
1604 start = visibleStart.deepEquivalent();
1606 if (rangeCollapsed) {
1607 setAffinityUsingLinePosition(visibleStart);
1608 affinity = visibleStart.affinity();
1611 // FIXME: Can we provide extentAffinity?
1612 Selection selection(start, affinity, end, khtml::SEL_DEFAULT_AFFINITY);
1613 _part->setSelection(selection);
1616 - (DOMRange *)selectedDOMRange
1618 return [DOMRange _rangeWithImpl:_part->selection().toRange().handle()];
1621 - (NSSelectionAffinity)selectionAffinity
1623 return static_cast<NSSelectionAffinity>(_part->selection().startAffinity());
1626 - (void)setMarkDOMRange:(DOMRange *)range
1628 _part->setMark(Selection([range _rangeImpl], khtml::SEL_DEFAULT_AFFINITY, khtml::SEL_DEFAULT_AFFINITY));
1631 - (DOMRange *)markDOMRange
1633 return [DOMRange _rangeWithImpl:_part->mark().toRange().handle()];
1636 - (void)setMarkedTextDOMRange:(DOMRange *)range customAttributes:(NSArray *)attributes ranges:(NSArray *)ranges
1638 _part->setMarkedTextRange([range _rangeImpl], attributes, ranges);
1641 - (DOMRange *)markedTextDOMRange
1643 return [DOMRange _rangeWithImpl:_part->markedTextRange().handle()];
1646 // Given proposedRange, returns an extended range that includes adjacent whitespace that should
1647 // be deleted along with the proposed range in order to preserve proper spacing and punctuation of
1648 // the text surrounding the deletion.
1649 - (DOMRange *)smartDeleteRangeForProposedRange:(DOMRange *)proposedRange
1651 NodeImpl *startContainer = [[proposedRange startContainer] _nodeImpl];
1652 NodeImpl *endContainer = [[proposedRange endContainer] _nodeImpl];
1653 if (startContainer == nil || endContainer == nil)
1656 ASSERT(startContainer->getDocument());
1657 ASSERT(startContainer->getDocument() == endContainer->getDocument());
1659 _part->xmlDocImpl()->updateLayout();
1661 Position start(startContainer, [proposedRange startOffset]);
1662 Position end(endContainer, [proposedRange endOffset]);
1663 Position newStart = start.upstream(DOM::StayInBlock).leadingWhitespacePosition(khtml::DOWNSTREAM, true);
1664 if (newStart.isNull())
1666 Position newEnd = end.downstream(DOM::StayInBlock).trailingWhitespacePosition(khtml::DOWNSTREAM, true);
1667 if (newEnd.isNull())
1670 return [DOMRange _rangeWithImpl:Range(newStart.node(), newStart.offset(), newEnd.node(), newEnd.offset()).handle()];
1673 // Determines whether whitespace needs to be added around aString to preserve proper spacing and
1674 // punctuation when itÕs inserted into the receiverÕs text over charRange. Returns by reference
1675 // in beforeString and afterString any whitespace that should be added, unless either or both are
1676 // nil. Both are returned as nil if aString is nil or if smart insertion and deletion are disabled.
1677 - (void)smartInsertForString:(NSString *)pasteString replacingRange:(DOMRange *)rangeToReplace beforeString:(NSString **)beforeString afterString:(NSString **)afterString
1679 // give back nil pointers in case of early returns
1681 *beforeString = nil;
1685 // inspect destination
1686 NodeImpl *startContainer = [[rangeToReplace startContainer] _nodeImpl];
1687 NodeImpl *endContainer = [[rangeToReplace endContainer] _nodeImpl];
1689 Position startPos(startContainer, [rangeToReplace startOffset]);
1690 Position endPos(endContainer, [rangeToReplace endOffset]);
1692 VisiblePosition startVisiblePos = VisiblePosition(startPos, khtml::VP_DEFAULT_AFFINITY);
1693 VisiblePosition endVisiblePos = VisiblePosition(endPos, khtml::VP_DEFAULT_AFFINITY);
1695 // this check also ensures startContainer, startPos, endContainer, and endPos are non-null
1696 if (startVisiblePos.isNull() || endVisiblePos.isNull())
1699 bool addLeadingSpace = startPos.leadingWhitespacePosition(khtml::VP_DEFAULT_AFFINITY, true).isNull() && !isFirstVisiblePositionInParagraph(startVisiblePos);
1700 if (addLeadingSpace) {
1701 QChar previousChar = startVisiblePos.previous().character();
1702 if (!previousChar.isNull()) {
1703 addLeadingSpace = !_part->isCharacterSmartReplaceExempt(previousChar, true);
1707 bool addTrailingSpace = endPos.trailingWhitespacePosition(khtml::VP_DEFAULT_AFFINITY, true).isNull() && !isLastVisiblePositionInParagraph(endVisiblePos);
1708 if (addTrailingSpace) {
1709 QChar thisChar = endVisiblePos.character();
1710 if (!thisChar.isNull()) {
1711 addTrailingSpace = !_part->isCharacterSmartReplaceExempt(thisChar, false);
1716 bool hasWhitespaceAtStart = false;
1717 bool hasWhitespaceAtEnd = false;
1718 unsigned pasteLength = [pasteString length];
1719 if (pasteLength > 0) {
1720 NSCharacterSet *whiteSet = [NSCharacterSet whitespaceAndNewlineCharacterSet];
1722 if ([whiteSet characterIsMember:[pasteString characterAtIndex:0]]) {
1723 hasWhitespaceAtStart = YES;
1725 if ([whiteSet characterIsMember:[pasteString characterAtIndex:(pasteLength - 1)]]) {
1726 hasWhitespaceAtEnd = YES;
1730 // issue the verdict
1731 if (beforeString && addLeadingSpace && !hasWhitespaceAtStart)
1732 *beforeString = @" ";
1733 if (afterString && addTrailingSpace && !hasWhitespaceAtEnd)
1734 *afterString = @" ";
1737 - (DOMDocumentFragment *)documentFragmentWithMarkupString:(NSString *)markupString baseURLString:(NSString *)baseURLString
1739 if (!_part || !_part->xmlDocImpl())
1742 DocumentFragmentImpl *fragment = createFragmentFromMarkup(_part->xmlDocImpl(), QString::fromNSString(markupString), QString::fromNSString(baseURLString));
1743 return [DOMDocumentFragment _documentFragmentWithImpl:fragment];
1746 - (DOMDocumentFragment *)documentFragmentWithText:(NSString *)text
1748 if (!partHasSelection(self) || !text)
1751 return [DOMDocumentFragment _documentFragmentWithImpl:createFragmentFromText(_part->xmlDocImpl(), QString::fromNSString(text))];
1754 - (void)replaceSelectionWithFragment:(DOMDocumentFragment *)fragment selectReplacement:(BOOL)selectReplacement smartReplace:(BOOL)smartReplace matchStyle:(BOOL)matchStyle
1756 if (!partHasSelection(self) || !fragment)
1759 EditCommandPtr(new ReplaceSelectionCommand(_part->xmlDocImpl(), [fragment _fragmentImpl], selectReplacement, smartReplace, matchStyle)).apply();
1760 [self ensureSelectionVisible];
1763 - (void)replaceSelectionWithNode:(DOMNode *)node selectReplacement:(BOOL)selectReplacement smartReplace:(BOOL)smartReplace
1765 DOMDocumentFragment *fragment = [[self DOMDocument] createDocumentFragment];
1766 [fragment appendChild:node];
1767 [self replaceSelectionWithFragment:fragment selectReplacement:selectReplacement smartReplace:smartReplace matchStyle:NO];
1770 - (void)replaceSelectionWithMarkupString:(NSString *)markupString baseURLString:(NSString *)baseURLString selectReplacement:(BOOL)selectReplacement smartReplace:(BOOL)smartReplace
1772 DOMDocumentFragment *fragment = [self documentFragmentWithMarkupString:markupString baseURLString:baseURLString];
1773 [self replaceSelectionWithFragment:fragment selectReplacement:selectReplacement smartReplace:smartReplace matchStyle:NO];
1776 - (void)replaceSelectionWithText:(NSString *)text selectReplacement:(BOOL)selectReplacement smartReplace:(BOOL)smartReplace
1778 [self replaceSelectionWithFragment:[self documentFragmentWithText:text] selectReplacement:selectReplacement smartReplace:smartReplace matchStyle:YES];
1781 - (void)insertLineBreak
1783 if (!partHasSelection(self))
1786 TypingCommand::insertLineBreak(_part->xmlDocImpl());
1787 [self ensureSelectionVisible];
1790 - (void)insertParagraphSeparator
1792 if (!partHasSelection(self))
1795 TypingCommand::insertParagraphSeparator(_part->xmlDocImpl());
1796 [self ensureSelectionVisible];
1799 - (void)insertParagraphSeparatorInQuotedContent
1801 if (!partHasSelection(self))
1804 TypingCommand::insertParagraphSeparatorInQuotedContent(_part->xmlDocImpl());
1805 [self ensureSelectionVisible];
1808 - (void)insertText:(NSString *)text selectInsertedText:(BOOL)selectInsertedText
1810 if (!partHasSelection(self))
1813 TypingCommand::insertText(_part->xmlDocImpl(), text, selectInsertedText);
1814 [self ensureSelectionVisible];
1817 - (void)setSelectionToDragCaret
1819 _part->setSelection(_part->dragCaret());
1822 - (void)moveSelectionToDragCaret:(DOMDocumentFragment *)selectionFragment smartMove:(BOOL)smartMove
1824 Position base = _part->dragCaret().base();
1825 EditCommandPtr(new MoveSelectionCommand(_part->xmlDocImpl(), [selectionFragment _fragmentImpl], base, smartMove)).apply();
1828 - (VisiblePosition)_visiblePositionForPoint:(NSPoint)point
1830 RenderObject *renderer = _part->renderer();
1832 return VisiblePosition();
1835 RenderObject::NodeInfo nodeInfo(true, true);
1836 renderer->layer()->hitTest(nodeInfo, (int)point.x, (int)point.y);
1837 NodeImpl *node = nodeInfo.innerNode();
1838 if (!node->renderer())
1839 return VisiblePosition();
1841 return node->renderer()->positionForCoordinates((int)point.x, (int)point.y);
1844 - (void)moveDragCaretToPoint:(NSPoint)point
1846 Selection dragCaret([self _visiblePositionForPoint:point]);
1847 _part->setDragCaret(dragCaret);
1850 - (void)removeDragCaret
1852 _part->setDragCaret(Selection());
1855 - (DOMRange *)dragCaretDOMRange
1857 return [DOMRange _rangeWithImpl:_part->dragCaret().toRange().handle()];
1860 - (DOMRange *)editableDOMRangeForPoint:(NSPoint)point
1862 VisiblePosition position = [self _visiblePositionForPoint:point];
1863 return position.isNull() ? nil : [DOMRange _rangeWithImpl:Selection(position).toRange().handle()];
1866 - (void)deleteSelectionWithSmartDelete:(BOOL)smartDelete
1868 if (!partHasSelection(self))
1871 EditCommandPtr(new DeleteSelectionCommand(_part->xmlDocImpl(), smartDelete)).apply();
1874 - (void)deleteKeyPressedWithSmartDelete:(BOOL)smartDelete
1876 if (!_part || !_part->xmlDocImpl())
1879 TypingCommand::deleteKeyPressed(_part->xmlDocImpl(), smartDelete);
1880 [self ensureSelectionVisible];
1883 - (void)forwardDeleteKeyPressedWithSmartDelete:(BOOL)smartDelete
1885 if (!_part || !_part->xmlDocImpl())
1888 TypingCommand::forwardDeleteKeyPressed(_part->xmlDocImpl(), smartDelete);
1889 [self ensureSelectionVisible];
1892 - (DOMCSSStyleDeclaration *)typingStyle
1894 if (!_part || !_part->typingStyle())
1896 return [DOMCSSStyleDeclaration _styleDeclarationWithImpl:_part->typingStyle()];
1899 - (void)setTypingStyle:(DOMCSSStyleDeclaration *)style withUndoAction:(WebUndoAction)undoAction
1903 _part->computeAndSetTypingStyle([style _styleDeclarationImpl], static_cast<EditAction>(undoAction));
1906 - (void)applyStyle:(DOMCSSStyleDeclaration *)style withUndoAction:(WebUndoAction)undoAction
1910 _part->applyStyle([style _styleDeclarationImpl], static_cast<EditAction>(undoAction));
1913 - (void)applyParagraphStyle:(DOMCSSStyleDeclaration *)style withUndoAction:(WebUndoAction)undoAction
1917 _part->applyParagraphStyle([style _styleDeclarationImpl], static_cast<EditAction>(undoAction));
1920 - (BOOL)selectionStartHasStyle:(DOMCSSStyleDeclaration *)style
1924 return _part->selectionStartHasStyle([style _styleDeclarationImpl]);
1927 - (NSCellStateValue)selectionHasStyle:(DOMCSSStyleDeclaration *)style
1931 switch (_part->selectionHasStyle([style _styleDeclarationImpl])) {
1932 case KHTMLPart::falseTriState:
1934 case KHTMLPart::trueTriState:
1936 case KHTMLPart::mixedTriState:
1937 return NSMixedState;
1942 - (void)applyEditingStyleToBodyElement
1946 _part->applyEditingStyleToBodyElement();
1949 - (void)removeEditingStyleFromBodyElement
1953 _part->removeEditingStyleFromBodyElement();
1956 - (void)applyEditingStyleToElement:(DOMElement *)element
1960 _part->applyEditingStyleToElement([element _elementImpl]);
1963 - (void)removeEditingStyleFromElement:(DOMElement *)element
1967 _part->removeEditingStyleFromElement([element _elementImpl]);
1970 - (NSFont *)fontForSelection:(BOOL *)hasMultipleFonts
1972 bool multipleFonts = false;
1975 font = _part->fontForSelection(hasMultipleFonts ? &multipleFonts : 0);
1976 if (hasMultipleFonts)
1977 *hasMultipleFonts = multipleFonts;
1981 - (NSDictionary *)fontAttributesForSelectionStart
1983 return _part ? _part->fontAttributesForSelectionStart() : nil;
1986 - (NSWritingDirection)baseWritingDirectionForSelectionStart
1988 return _part ? _part->baseWritingDirectionForSelectionStart() : NSWritingDirectionLeftToRight;
1991 - (void)ensureSelectionVisible
1993 if (!partHasSelection(self))
1996 KHTMLView *v = _part->view();
2000 Position extent = _part->selection().extent();
2001 if (extent.isNull())
2004 RenderObject *renderer = extent.node()->renderer();
2008 NSView *documentView = v->getDocumentView();
2012 QRect extentRect = renderer->caretRect(extent.offset(), _part->selection().extentAffinity());
2013 if (!NSContainsRect([documentView visibleRect], NSRect(extentRect))) {
2014 v->ensureRectVisibleCentered(extentRect, true);
2018 // [info draggingLocation] is in window coords
2020 - (BOOL)eventMayStartDrag:(NSEvent *)event
2022 return _part ? _part->eventMayStartDrag(event) : NO;
2025 - (NSDragOperation)dragOperationForDraggingInfo:(id <NSDraggingInfo>)info
2027 NSDragOperation op = NSDragOperationNone;
2029 KHTMLView *v = _part->view();
2031 // Sending an event can result in the destruction of the view and part.
2034 KWQClipboard::AccessPolicy policy = _part->baseURL().isLocalFile() ? KWQClipboard::Readable : KWQClipboard::TypesReadable;
2035 KWQClipboard *clipboard = new KWQClipboard(true, [info draggingPasteboard], policy);
2037 NSDragOperation srcOp = [info draggingSourceOperationMask];
2038 clipboard->setSourceOperation(srcOp);
2040 if (v->updateDragAndDrop(QPoint([info draggingLocation]), clipboard)) {
2041 // *op unchanged if no source op was set
2042 if (!clipboard->destinationOperation(&op)) {
2043 // The element accepted but they didn't pick an operation, so we pick one for them
2045 if (srcOp & NSDragOperationCopy) {
2046 op = NSDragOperationCopy;
2047 } else if (srcOp & NSDragOperationMove || srcOp & NSDragOperationGeneric) {
2048 op = NSDragOperationMove;
2049 } else if (srcOp & NSDragOperationLink) {
2050 op = NSDragOperationLink;
2052 op = NSDragOperationGeneric;
2054 } else if (!(op & srcOp)) {
2055 // make sure WC picked an op that was offered. Cocoa doesn't seem to enforce this,
2057 op = NSDragOperationNone;
2060 clipboard->setAccessPolicy(KWQClipboard::Numb); // invalidate clipboard here for security
2070 - (void)dragExitedWithDraggingInfo:(id <NSDraggingInfo>)info
2073 KHTMLView *v = _part->view();
2075 // Sending an event can result in the destruction of the view and part.
2078 KWQClipboard::AccessPolicy policy = _part->baseURL().isLocalFile() ? KWQClipboard::Readable : KWQClipboard::TypesReadable;
2079 KWQClipboard *clipboard = new KWQClipboard(true, [info draggingPasteboard], policy);
2081 clipboard->setSourceOperation([info draggingSourceOperationMask]);
2083 v->cancelDragAndDrop(QPoint([info draggingLocation]), clipboard);
2084 clipboard->setAccessPolicy(KWQClipboard::Numb); // invalidate clipboard here for security
2092 - (BOOL)concludeDragForDraggingInfo:(id <NSDraggingInfo>)info
2095 KHTMLView *v = _part->view();
2097 // Sending an event can result in the destruction of the view and part.
2100 KWQClipboard *clipboard = new KWQClipboard(true, [info draggingPasteboard], KWQClipboard::Readable);
2102 clipboard->setSourceOperation([info draggingSourceOperationMask]);
2104 BOOL result = v->performDragAndDrop(QPoint([info draggingLocation]), clipboard);
2105 clipboard->setAccessPolicy(KWQClipboard::Numb); // invalidate clipboard here for security
2116 - (void)dragSourceMovedTo:(NSPoint)windowLoc
2119 _part->dragSourceMovedTo(QPoint(windowLoc));
2123 - (void)dragSourceEndedAt:(NSPoint)windowLoc operation:(NSDragOperation)operation
2126 _part->dragSourceEndedAt(QPoint(windowLoc), operation);
2132 return _part->mayCut();
2135 - (BOOL)mayDHTMLCopy
2137 return _part->mayCopy();
2140 - (BOOL)mayDHTMLPaste
2142 return _part->mayPaste();
2147 return _part->tryCut();
2150 - (BOOL)tryDHTMLCopy
2152 return _part->tryCopy();
2155 - (BOOL)tryDHTMLPaste
2157 return _part->tryPaste();
2160 - (DOMRange *)rangeOfCharactersAroundCaret
2165 Selection selection(_part->selection());
2166 if (!selection.isCaret())
2169 VisiblePosition caret(selection.start(), selection.startAffinity());
2170 VisiblePosition next = caret.next();
2171 VisiblePosition previous = caret.previous();
2172 if (caret == next || caret == previous)
2175 return [DOMRange _rangeWithImpl:makeRange(previous, next).handle()];
2178 - (NSMutableDictionary *)dashboardRegions
2180 return _part->dashboardRegionsDictionary();
2185 @implementation WebCoreBridge (WebCoreBridgeInternal)
2187 - (RootObject *)executionContextForView:(NSView *)aView
2189 KWQKHTMLPart *part = [self part];
2190 RootObject *root = new RootObject(aView); // The root gets deleted by JavaScriptCore.
2191 root->setRootObjectImp(static_cast<ObjectImp *>(Window::retrieveWindow(part)));
2192 root->setInterpreter(KJSProxy::proxy(part)->interpreter());
2193 part->addPluginRootObject(root);