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:");
393 BOOL URLIsFileURL = [[URL scheme] compare:@"file" options:(NSCaseInsensitiveSearch|NSLiteralSearch)] == NSOrderedSame;
395 return referrerIsFileURL || !URLIsFileURL;
398 - (void)saveDocumentState
400 DocumentImpl *doc = _part->xmlDocImpl();
402 QStringList list = doc->docState();
403 NSMutableArray *documentState = [[[NSMutableArray alloc] init] autorelease];
405 for (uint i = 0; i < list.count(); i++){
407 [documentState addObject: [NSString stringWithCharacters: (const unichar *)s.unicode() length: s.length()]];
409 [self saveDocumentState: documentState];
413 - (void)restoreDocumentState
415 DocumentImpl *doc = _part->xmlDocImpl();
418 NSArray *documentState = [self documentState];
421 for (uint i = 0; i < [documentState count]; i++){
422 NSString *string = [documentState objectAtIndex: i];
423 s.append(QString::fromNSString(string));
426 doc->setRestoreState(s);
430 - (void)scrollToAnchorWithURL:(NSURL *)URL
432 _part->scrollToAnchor(KURL(URL).url().latin1());
435 - (BOOL)scrollOverflowInDirection:(WebScrollDirection)direction granularity:(WebScrollGranularity)granularity
440 return _part->scrollOverflow((KWQScrollDirection)direction, (KWQScrollGranularity)granularity);
443 - (BOOL)scrollOverflowWithScrollWheelEvent:(NSEvent *)event
448 return _part->scrollOverflowWithScrollWheelEvent(event);
451 - (BOOL)saveDocumentToPageCache
453 DocumentImpl *doc = _part->xmlDocImpl();
461 _part->clearTimers();
463 SavedProperties *windowProperties = new SavedProperties;
464 _part->saveWindowProperties(windowProperties);
466 SavedProperties *locationProperties = new SavedProperties;
467 _part->saveLocationProperties(locationProperties);
469 SavedBuiltins *interpreterBuiltins = new SavedBuiltins;
470 _part->saveInterpreterBuiltins(*interpreterBuiltins);
472 KWQPageState *pageState = [[[KWQPageState alloc] initWithDocument:doc
474 windowProperties:windowProperties
475 locationProperties:locationProperties
476 interpreterBuiltins:interpreterBuiltins] autorelease];
477 [pageState setPausedActions: _part->pauseActions((const void *)pageState)];
479 return [self saveDocumentToPageCache:pageState];
484 return _part->canCachePage();
502 - (void)createKHTMLViewWithNSView:(NSView *)view marginWidth:(int)mw marginHeight:(int)mh
504 // If we own the view, delete the old one - otherwise the render _part will take care of deleting the view.
505 [self removeFromFrame];
507 KHTMLView *kview = new KHTMLView(_part, 0);
508 _part->setView(kview);
511 kview->setView(view);
513 kview->setMarginWidth(mw);
515 kview->setMarginHeight(mh);
518 - (void)scrollToAnchor:(NSString *)a
520 _part->gotoAnchor(QString::fromNSString(a));
523 - (BOOL)isSelectionEditable
525 // EDIT FIXME: This needs to consider the entire selected range
526 NodeImpl *startNode = _part->selection().start().node();
527 return startNode ? startNode->isContentEditable() : NO;
530 - (WebSelectionState)selectionState
532 switch (_part->selection().state()) {
533 case Selection::NONE:
534 return WebSelectionStateNone;
535 case Selection::CARET:
536 return WebSelectionStateCaret;
537 case Selection::RANGE:
538 return WebSelectionStateRange;
541 ASSERT_NOT_REACHED();
542 return WebSelectionStateNone;
545 - (NSString *)_documentTypeString
547 NSString *documentTypeString = nil;
548 DOM::DocumentImpl *doc = _part->xmlDocImpl();
550 DocumentTypeImpl *doctype = doc->doctype();
552 documentTypeString = doctype->toString().string().getNSString();
555 return documentTypeString;
558 - (NSString *)_stringWithDocumentTypeStringAndMarkupString:(NSString *)markupString
560 NSString *documentTypeString = [self _documentTypeString];
561 if (documentTypeString && markupString) {
562 return [NSString stringWithFormat:@"%@%@", documentTypeString, markupString];
563 } else if (documentTypeString) {
564 return documentTypeString;
565 } else if (markupString) {
572 - (NSArray *)nodesFromList:(QPtrList<NodeImpl> *)nodeList
574 NSMutableArray *nodes = [NSMutableArray arrayWithCapacity:nodeList->count()];
575 for (QPtrListIterator<NodeImpl> i(*nodeList); i.current(); ++i) {
576 [nodes addObject:[DOMNode _nodeWithImpl:i.current()]];
581 - (NSString *)markupStringFromNode:(DOMNode *)node nodes:(NSArray **)nodes
583 // FIXME: This is never "for interchange". Is that right? See the next method.
584 QPtrList<NodeImpl> nodeList;
585 NSString *markupString = createMarkup([node _nodeImpl], IncludeNode, nodes ? &nodeList : 0).getNSString();
587 *nodes = [self nodesFromList:&nodeList];
589 return [self _stringWithDocumentTypeStringAndMarkupString:markupString];
592 - (NSString *)markupStringFromRange:(DOMRange *)range nodes:(NSArray **)nodes
594 // FIXME: This is always "for interchange". Is that right? See the previous method.
595 QPtrList<NodeImpl> nodeList;
596 NSString *markupString = createMarkup([range _rangeImpl], nodes ? &nodeList : 0, AnnotateForInterchange).getNSString();
598 *nodes = [self nodesFromList:&nodeList];
600 return [self _stringWithDocumentTypeStringAndMarkupString:markupString];
603 - (NSString *)selectedString
605 QString text = _part->selectedText();
606 text.replace(QChar('\\'), _part->backslashAsCurrencySymbol());
607 return [[text.getNSString() copy] autorelease];
610 - (NSString *)stringForRange:(DOMRange *)range
612 QString text = _part->text([range _rangeImpl]);
613 text.replace(QChar('\\'), _part->backslashAsCurrencySymbol());
614 return [[text.getNSString() copy] autorelease];
625 DocumentImpl *doc = _part->xmlDocImpl();
627 doc->setFocusNode(0);
633 _part->clearSelection();
638 return _part->isFrameSet();
641 - (NSString *)styleSheetForPrinting
643 if (!_part->settings()->shouldPrintBackgrounds()) {
644 return @"* { background-image: none !important; background-color: white !important;}";
649 - (void)reapplyStylesForDeviceType:(WebCoreDeviceType)deviceType
651 _part->setMediaType(deviceType == WebCoreDeviceScreen ? "screen" : "print");
652 DocumentImpl *doc = _part->xmlDocImpl();
654 static QPaintDevice screen;
655 static QPrinter printer;
656 doc->setPaintDevice(deviceType == WebCoreDeviceScreen ? &screen : &printer);
657 if (deviceType != WebCoreDeviceScreen) {
658 doc->setPrintStyleSheet(QString::fromNSString([self styleSheetForPrinting]));
661 return _part->reparseConfiguration();
664 static BOOL nowPrinting(WebCoreBridge *self)
666 DocumentImpl *doc = self->_part->xmlDocImpl();
667 return doc && doc->paintDevice() && doc->paintDevice()->devType() == QInternal::Printer;
670 // Set or unset the printing mode in the view. We only toy with this if we're printing.
671 - (void)_setupRootForPrinting:(BOOL)onOrOff
673 if (nowPrinting(self)) {
674 RenderCanvas *root = static_cast<khtml::RenderCanvas *>(_part->xmlDocImpl()->renderer());
676 root->setPrintingMode(onOrOff);
681 - (void)forceLayoutAdjustingViewSize:(BOOL)flag
683 [self _setupRootForPrinting:YES];
684 _part->forceLayout();
686 [self adjustViewSize];
688 [self _setupRootForPrinting:NO];
691 - (void)forceLayoutWithMinimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustingViewSize:(BOOL)flag
693 [self _setupRootForPrinting:YES];
694 _part->forceLayoutWithPageWidthRange(minPageWidth, maxPageWidth);
696 [self adjustViewSize];
698 [self _setupRootForPrinting:NO];
701 - (void)sendResizeEvent
703 _part->sendResizeEvent();
706 - (void)sendScrollEvent
708 _part->sendScrollEvent();
711 - (void)drawRect:(NSRect)rect withPainter:(QPainter *)p
713 [self _setupRootForPrinting:YES];
714 _part->paint(p, QRect(rect));
715 [self _setupRootForPrinting:NO];
718 - (void)drawRect:(NSRect)rect
720 QPainter painter(nowPrinting(self));
721 bool displaysWithFocusAttributes = _part->displaysWithFocusAttributes();
722 painter.setUsesInactiveTextBackgroundColor(!displaysWithFocusAttributes);
723 painter.setDrawsFocusRing(displaysWithFocusAttributes);
724 [self drawRect:rect withPainter:&painter];
727 // Used by pagination code called from AppKit when a standalone web page is printed.
728 - (NSArray*)computePageRectsWithPrintWidthScaleFactor:(float)printWidthScaleFactor printHeight:(float)printHeight
730 [self _setupRootForPrinting:YES];
731 NSMutableArray* pages = [NSMutableArray arrayWithCapacity:5];
732 if (printWidthScaleFactor <= 0) {
733 ERROR("printWidthScaleFactor has bad value %.2f", printWidthScaleFactor);
737 if (printHeight <= 0) {
738 ERROR("printHeight has bad value %.2f", printHeight);
742 if (!_part || !_part->xmlDocImpl() || !_part->view()) return pages;
743 RenderCanvas* root = static_cast<khtml::RenderCanvas *>(_part->xmlDocImpl()->renderer());
744 if (!root) return pages;
746 KHTMLView* view = _part->view();
747 NSView* documentView = view->getDocumentView();
751 float currPageHeight = printHeight;
752 float docHeight = root->layer()->height();
753 float docWidth = root->layer()->width();
754 float printWidth = docWidth/printWidthScaleFactor;
756 // We need to give the part the opportunity to adjust the page height at each step.
757 for (float i = 0; i < docHeight; i += currPageHeight) {
758 float proposedBottom = kMin(docHeight, i + printHeight);
759 _part->adjustPageHeight(&proposedBottom, i, proposedBottom, i);
760 currPageHeight = kMax(1.0f, proposedBottom - i);
761 for (float j = 0; j < docWidth; j += printWidth) {
762 NSValue* val = [NSValue valueWithRect: NSMakeRect(j, i, printWidth, currPageHeight)];
763 [pages addObject: val];
766 [self _setupRootForPrinting:NO];
771 // This is to support the case where a webview is embedded in the view that's being printed
772 - (void)adjustPageHeightNew:(float *)newBottom top:(float)oldTop bottom:(float)oldBottom limit:(float)bottomLimit
774 [self _setupRootForPrinting:YES];
775 _part->adjustPageHeight(newBottom, oldTop, oldBottom, bottomLimit);
776 [self _setupRootForPrinting:NO];
779 - (NSObject *)copyDOMNode:(NodeImpl *)node copier:(id <WebCoreDOMTreeCopier>)copier
781 NSMutableArray *children = [[NSMutableArray alloc] init];
782 for (NodeImpl *child = node->firstChild(); child; child = child->nextSibling()) {
783 [children addObject:[self copyDOMNode:child copier:copier]];
785 NSObject *copiedNode = [copier nodeWithName:node->nodeName().string().getNSString()
786 value:node->nodeValue().string().getNSString()
787 source:createMarkup(node, ChildrenOnly).getNSString()
793 - (NSObject *)copyDOMTree:(id <WebCoreDOMTreeCopier>)copier
795 DocumentImpl *doc = _part->xmlDocImpl();
799 return [self copyDOMNode:doc copier:copier];
802 - (NSObject *)copyRenderNode:(RenderObject *)node copier:(id <WebCoreRenderTreeCopier>)copier
804 NSMutableArray *children = [[NSMutableArray alloc] init];
805 for (RenderObject *child = node->firstChild(); child; child = child->nextSibling()) {
806 [children addObject:[self copyRenderNode:child copier:copier]];
809 NSString *name = [[NSString alloc] initWithUTF8String:node->renderName()];
811 RenderPart *nodeRenderPart = dynamic_cast<RenderPart *>(node);
812 QWidget *widget = nodeRenderPart ? nodeRenderPart->widget() : 0;
813 NSView *view = widget ? widget->getView() : nil;
816 node->absolutePosition(nx,ny);
817 NSObject *copiedNode = [copier nodeWithName:name
818 position:NSMakePoint(nx,ny)
819 rect:NSMakeRect(node->xPos(), node->yPos(), node->width(), node->height())
829 - (NSObject *)copyRenderTree:(id <WebCoreRenderTreeCopier>)copier
831 RenderObject *renderer = _part->renderer();
835 return [self copyRenderNode:renderer copier:copier];
838 - (void)removeFromFrame
843 - (void)installInFrame:(NSView *)view
845 // If this isn't the main frame, it must have a render _part set, or it
846 // won't ever get installed in the view hierarchy.
847 ASSERT(self == [self mainFrame] || _renderPart != nil);
849 _part->view()->setView(view);
851 _renderPart->setWidget(_part->view());
852 // Now the render part owns the view, so we don't any more.
855 _part->view()->initScrollBars();
858 - (void)setActivationEventNumber:(int)num
860 _part->setActivationEventNumber(num);
863 - (void)mouseDown:(NSEvent *)event
865 _part->mouseDown(event);
868 - (void)mouseDragged:(NSEvent *)event
870 _part->mouseDragged(event);
873 - (void)mouseUp:(NSEvent *)event
875 _part->mouseUp(event);
878 - (void)mouseMoved:(NSEvent *)event
880 _part->mouseMoved(event);
883 - (BOOL)sendContextMenuEvent:(NSEvent *)event
885 return _part->sendContextMenuEvent(event);
888 - (DOMElement *)elementForView:(NSView *)view
890 // FIXME: implemented currently for only a subset of the KWQ widgets
891 if ([view conformsToProtocol:@protocol(KWQWidgetHolder)]) {
892 NSView <KWQWidgetHolder> *widgetHolder = view;
893 QWidget *widget = [widgetHolder widget];
895 NodeImpl *node = static_cast<const RenderWidget *>(widget->eventFilterObject())->element();
896 return [DOMElement _elementWithImpl:static_cast<ElementImpl *>(node)];
902 static NSView *viewForElement(ElementImpl *elementImpl)
904 RenderObject *renderer = elementImpl->renderer();
905 if (renderer && renderer->isWidget()) {
906 QWidget *widget = static_cast<const RenderWidget *>(renderer)->widget();
909 return widget->getView();
915 static HTMLInputElementImpl *inputElementFromDOMElement(DOMElement *element)
917 NodeImpl *node = [element _nodeImpl];
918 if (node && idFromNode(node) == ID_INPUT) {
919 return static_cast<HTMLInputElementImpl *>(node);
924 static HTMLFormElementImpl *formElementFromDOMElement(DOMElement *element)
926 NodeImpl *node = [element _nodeImpl];
927 // This should not be necessary, but an XSL file on
928 // maps.google.com crashes otherwise because it is an xslt file
929 // that contains <form> elements that aren't in any namespace, so
930 // they come out as generic CML elements
931 if (node && node->isHTMLElement() && idFromNode(node) == ID_FORM) {
932 return static_cast<HTMLFormElementImpl *>(node);
937 - (DOMElement *)elementWithName:(NSString *)name inForm:(DOMElement *)form
939 HTMLFormElementImpl *formElement = formElementFromDOMElement(form);
941 QPtrVector<HTMLGenericFormElementImpl> &elements = formElement->formElements;
942 QString targetName = QString::fromNSString(name);
943 for (unsigned int i = 0; i < elements.count(); i++) {
944 HTMLGenericFormElementImpl *elt = elements.at(i);
945 // Skip option elements, other duds
946 if (elt->name() == targetName) {
947 return [DOMElement _elementWithImpl:elt];
954 - (BOOL)elementDoesAutoComplete:(DOMElement *)element
956 HTMLInputElementImpl *inputElement = inputElementFromDOMElement(element);
957 return inputElement != nil
958 && inputElement->inputType() == HTMLInputElementImpl::TEXT
959 && inputElement->autoComplete();
962 - (BOOL)elementIsPassword:(DOMElement *)element
964 HTMLInputElementImpl *inputElement = inputElementFromDOMElement(element);
965 return inputElement != nil
966 && inputElement->inputType() == HTMLInputElementImpl::PASSWORD;
969 - (DOMElement *)formForElement:(DOMElement *)element;
971 HTMLInputElementImpl *inputElement = inputElementFromDOMElement(element);
973 HTMLFormElementImpl *formElement = inputElement->form();
975 return [DOMElement _elementWithImpl:formElement];
981 - (DOMElement *)currentForm
983 HTMLFormElementImpl *formElement = _part->currentForm();
984 return formElement ? [DOMElement _elementWithImpl:formElement] : nil;
987 - (NSArray *)controlsInForm:(DOMElement *)form
989 NSMutableArray *results = nil;
990 HTMLFormElementImpl *formElement = formElementFromDOMElement(form);
992 QPtrVector<HTMLGenericFormElementImpl> &elements = formElement->formElements;
993 for (unsigned int i = 0; i < elements.count(); i++) {
994 if (elements.at(i)->isEnumeratable()) { // Skip option elements, other duds
995 NSView *view = viewForElement(elements.at(i));
998 results = [NSMutableArray arrayWithObject:view];
1000 [results addObject:view];
1009 - (NSString *)searchForLabels:(NSArray *)labels beforeElement:(DOMElement *)element
1011 return _part->searchForLabelsBeforeElement(labels, [element _elementImpl]);
1014 - (NSString *)matchLabels:(NSArray *)labels againstElement:(DOMElement *)element
1016 return _part->matchLabelsAgainstElement(labels, [element _elementImpl]);
1019 - (NSDictionary *)elementAtPoint:(NSPoint)point
1021 RenderObject *renderer = _part->renderer();
1025 RenderObject::NodeInfo nodeInfo(true, true);
1026 renderer->layer()->hitTest(nodeInfo, (int)point.x, (int)point.y);
1028 NSMutableDictionary *element = [NSMutableDictionary dictionary];
1029 [element setObject:[NSNumber numberWithBool:_part->isPointInsideSelection((int)point.x, (int)point.y)]
1030 forKey:WebCoreElementIsSelectedKey];
1032 // Find the title in the nearest enclosing DOM node.
1033 // For <area> tags in image maps, walk the tree for the <area>, not the <img> using it.
1034 for (NodeImpl *titleNode = nodeInfo.innerNode(); titleNode; titleNode = titleNode->parentNode()) {
1035 if (titleNode->isElementNode()) {
1036 const AtomicString& title = static_cast<ElementImpl *>(titleNode)->getAttribute(ATTR_TITLE);
1037 if (!title.isNull()) {
1038 // We found a node with a title.
1039 QString titleText = title.string();
1040 titleText.replace(QChar('\\'), _part->backslashAsCurrencySymbol());
1041 [element setObject:titleText.getNSString() forKey:WebCoreElementTitleKey];
1047 NodeImpl *URLNode = nodeInfo.URLElement();
1049 ElementImpl *e = static_cast<ElementImpl *>(URLNode);
1050 DocumentImpl *doc = e->getDocument();
1053 const AtomicString& title = e->getAttribute(ATTR_TITLE);
1054 if (!title.isEmpty()) {
1055 QString titleText = title.string();
1056 titleText.replace(QChar('\\'), _part->backslashAsCurrencySymbol());
1057 [element setObject:titleText.getNSString() forKey:WebCoreElementLinkTitleKey];
1060 const AtomicString& link = e->getAttribute(ATTR_HREF);
1061 if (!link.isNull()) {
1062 if (e->firstChild()) {
1064 r.setStartBefore(e->firstChild());
1065 r.setEndAfter(e->lastChild());
1066 QString t = _part->text(r);
1068 [element setObject:t.getNSString() forKey:WebCoreElementLinkLabelKey];
1071 QString URLString = parseURL(link).string();
1072 [element setObject:doc->completeURL(URLString).getNSString() forKey:WebCoreElementLinkURLKey];
1075 DOMString target = e->getAttribute(ATTR_TARGET);
1076 if (target.isEmpty() && doc) { // FIXME: Take out this doc check when we're not just before a release.
1077 target = doc->baseTarget();
1079 if (!target.isEmpty()) {
1080 [element setObject:target.string().getNSString() forKey:WebCoreElementLinkTargetFrameKey];
1084 NodeImpl *node = nodeInfo.innerNonSharedNode();
1086 [element setObject:[DOMNode _nodeWithImpl:node] forKey:WebCoreElementDOMNodeKey];
1088 if (node->renderer() && node->renderer()->isImage()) {
1089 RenderImage *r = static_cast<RenderImage *>(node->renderer());
1090 NSImage *image = r->pixmap().image();
1091 // Only return image information if there is an image.
1092 if (image && !r->isDisplayingError()) {
1093 [element setObject:r->pixmap().image() forKey:WebCoreElementImageKey];
1097 if (r->absolutePosition(x, y)) {
1098 NSValue *rect = [NSValue valueWithRect:NSMakeRect(x, y, r->contentWidth(), r->contentHeight())];
1099 [element setObject:rect forKey:WebCoreElementImageRectKey];
1102 ElementImpl *i = static_cast<ElementImpl*>(node);
1104 // FIXME: Code copied from RenderImage::updateFromElement; should share.
1106 if (idFromNode(i) == ID_OBJECT) {
1107 attr = i->getAttribute(ATTR_DATA);
1109 attr = i->getAttribute(ATTR_SRC);
1111 if (!attr.isEmpty()) {
1112 QString URLString = parseURL(attr).string();
1113 [element setObject:i->getDocument()->completeURL(URLString).getNSString() forKey:WebCoreElementImageURLKey];
1116 // FIXME: Code copied from RenderImage::updateFromElement; should share.
1118 if (idFromNode(i) == ID_INPUT)
1119 alt = static_cast<HTMLInputElementImpl *>(i)->altText();
1120 else if (idFromNode(i) == ID_IMG)
1121 alt = static_cast<HTMLImageElementImpl *>(i)->altText();
1122 if (!alt.isNull()) {
1123 QString altText = alt.string();
1124 altText.replace(QChar('\\'), _part->backslashAsCurrencySymbol());
1125 [element setObject:altText.getNSString() forKey:WebCoreElementImageAltStringKey];
1133 - (NSURL *)URLWithAttributeString:(NSString *)string
1135 DocumentImpl *doc = _part->xmlDocImpl();
1139 QString rel = parseURL(QString::fromNSString(string)).string();
1140 return KURL(doc->baseURL(), rel, doc->decoder() ? doc->decoder()->codec() : 0).getNSURL();
1143 - (BOOL)searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag
1145 return _part->findString(string, forward, caseFlag, wrapFlag);
1148 - (void)jumpToSelection
1150 _part->jumpToSelection();
1153 - (NSString *)advanceToNextMisspelling
1155 return _part->advanceToNextMisspelling().getNSString();
1158 - (NSString *)advanceToNextMisspellingStartingJustBeforeSelection
1160 return _part->advanceToNextMisspelling(true).getNSString();
1163 - (void)setTextSizeMultiplier:(float)multiplier
1165 int newZoomFactor = (int)rint(multiplier * 100);
1166 if (_part->zoomFactor() == newZoomFactor) {
1169 _part->setZoomFactor(newZoomFactor);
1172 - (CFStringEncoding)textEncoding
1174 return KWQCFStringEncodingFromIANACharsetName(_part->encoding().latin1());
1177 - (NSView *)nextKeyView
1179 DocumentImpl *doc = _part->xmlDocImpl();
1183 return _part->nextKeyView(doc->focusNode(), KWQSelectingNext);
1186 - (NSView *)previousKeyView
1188 DocumentImpl *doc = _part->xmlDocImpl();
1192 return _part->nextKeyView(doc->focusNode(), KWQSelectingPrevious);
1195 - (NSView *)nextKeyViewInsideWebFrameViews
1197 DocumentImpl *doc = _part->xmlDocImpl();
1202 return _part->nextKeyViewInFrameHierarchy(doc->focusNode(), KWQSelectingNext);
1205 - (NSView *)previousKeyViewInsideWebFrameViews
1207 DocumentImpl *doc = _part->xmlDocImpl();
1212 return _part->nextKeyViewInFrameHierarchy(doc->focusNode(), KWQSelectingPrevious);
1215 - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)string
1217 return [self stringByEvaluatingJavaScriptFromString:string forceUserGesture:true];
1221 - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)string forceUserGesture:(BOOL)forceUserGesture
1223 _part->createEmptyDocument();
1224 return _part->executeScript(QString::fromNSString(string), forceUserGesture).asString().getNSString();
1227 - (WebScriptObject *)windowScriptObject
1229 return _part->windowScriptObject();
1232 - (NPObject *)windowScriptNPObject
1234 return _part->windowScriptNPObject();
1237 - (DOMDocument *)DOMDocument
1239 return [DOMDocument _documentWithImpl:_part->xmlDocImpl()];
1242 - (DOMHTMLElement *)frameElement
1244 return (DOMHTMLElement *)[[self DOMDocument] _ownerElement];
1247 - (NSAttributedString *)selectedAttributedString
1249 return _part->attributedString(_part->selectionStart(), _part->selectionStartOffset(), _part->selectionEnd(), _part->selectionEndOffset());
1252 - (NSAttributedString *)attributedStringFrom:(DOMNode *)start startOffset:(int)startOffset to:(DOMNode *)end endOffset:(int)endOffset
1254 DOMNode *startNode = start;
1255 DOMNode *endNode = end;
1256 return _part->attributedString([startNode _nodeImpl], startOffset, [endNode _nodeImpl], endOffset);
1259 - (NSRect)selectionRect
1261 return _part->selectionRect();
1264 - (NSRect)visibleSelectionRect
1266 return _part->visibleSelectionRect();
1269 - (void)centerSelectionInVisibleArea
1271 _part->centerSelectionInVisibleArea();
1274 - (NSRect)caretRectAtNode:(DOMNode *)node offset:(int)offset affinity:(NSSelectionAffinity)affinity
1276 return [node _nodeImpl]->renderer()->caretRect(offset, static_cast<EAffinity>(affinity));
1278 - (NSRect)firstRectForDOMRange:(DOMRange *)range
1280 int extraWidthToEndOfLine = 0;
1281 QRect startCaretRect = [[range startContainer] _nodeImpl]->renderer()->caretRect([range startOffset], UPSTREAM, &extraWidthToEndOfLine);
1282 QRect endCaretRect = [[range startContainer] _nodeImpl]->renderer()->caretRect([range endOffset], UPSTREAM);
1284 if (startCaretRect.y() == endCaretRect.y()) {
1285 // start and end are on the same line
1286 return QRect(MIN(startCaretRect.x(), endCaretRect.x()),
1288 abs(endCaretRect.x() - startCaretRect.x()),
1289 MAX(startCaretRect.height(), endCaretRect.height()));
1292 // start and end aren't on the same line, so go from start to the end of its line
1293 return QRect(startCaretRect.x(),
1295 startCaretRect.width() + extraWidthToEndOfLine,
1296 startCaretRect.height());
1299 - (NSImage *)selectionImage
1301 return _part->selectionImage();
1304 - (void)setName:(NSString *)name
1306 _part->KHTMLPart::setName(QString::fromNSString(name));
1311 return _part->name().getNSString();
1316 return _part->url().getNSURL();
1321 return _part->completeURL(_part->xmlDocImpl()->baseURL()).getNSURL();
1324 - (NSString *)referrer
1326 return _part->referrer().getNSString();
1329 - (NSString *)domain
1331 DocumentImpl *doc = _part->xmlDocImpl();
1332 if (doc && doc->isHTMLDocument()) {
1333 return doc->domain().string().getNSString();
1338 - (WebCoreBridge *)opener
1340 KHTMLPart *openerPart = _part->opener();
1343 return KWQ(openerPart)->bridge();
1348 + (NSString *)stringWithData:(NSData *)data textEncoding:(CFStringEncoding)textEncoding
1350 if (textEncoding == kCFStringEncodingInvalidId || textEncoding == kCFStringEncodingISOLatin1) {
1351 textEncoding = kCFStringEncodingWindowsLatin1;
1353 return QTextCodec(textEncoding).toUnicode((const char*)[data bytes], [data length]).getNSString();
1356 + (NSString *)stringWithData:(NSData *)data textEncodingName:(NSString *)textEncodingName
1358 CFStringEncoding textEncoding = KWQCFStringEncodingFromIANACharsetName([textEncodingName lossyCString]);
1359 return [WebCoreBridge stringWithData:data textEncoding:textEncoding];
1364 RenderObject *renderer = _part->renderer();
1365 return renderer ? renderer->needsLayout() : false;
1368 - (void)setNeedsLayout
1370 RenderObject *renderer = _part->renderer();
1372 renderer->setNeedsLayout(true);
1375 - (BOOL)interceptKeyEvent:(NSEvent *)event toView:(NSView *)view
1377 return _part->keyEvent(event);
1380 - (NSString *)renderTreeAsExternalRepresentation
1382 return externalRepresentation(_part->renderer()).getNSString();
1385 - (void)setSelectionFromNone
1387 _part->setSelectionFromNone();
1390 - (void)setDisplaysWithFocusAttributes:(BOOL)flag
1392 _part->setDisplaysWithFocusAttributes(flag);
1395 - (void)setWindowHasFocus:(BOOL)flag
1397 _part->setWindowHasFocus(flag);
1400 - (void)setShouldCreateRenderers:(BOOL)f
1402 _shouldCreateRenderers = f;
1405 - (BOOL)shouldCreateRenderers
1407 return _shouldCreateRenderers;
1410 - (int)numPendingOrLoadingRequests
1412 DocumentImpl *doc = _part->xmlDocImpl();
1415 return KWQNumberOfPendingOrLoadingRequests (doc->docLoader());
1419 - (BOOL)doneProcessingData
1421 DocumentImpl *doc = _part->xmlDocImpl();
1423 Tokenizer* tok = doc->tokenizer();
1425 return !tok->processingData();
1430 - (NSColor *)bodyBackgroundColor
1432 return _part->bodyBackgroundColor();
1435 - (NSColor *)selectionColor
1437 RenderCanvas* root = static_cast<khtml::RenderCanvas *>(_part->xmlDocImpl()->renderer());
1439 RenderStyle *pseudoStyle = root->getPseudoStyle(RenderStyle::SELECTION);
1440 if (pseudoStyle && pseudoStyle->backgroundColor().isValid()) {
1441 return pseudoStyle->backgroundColor().getNSColor();
1444 return _part->displaysWithFocusAttributes() ? [NSColor selectedTextBackgroundColor] : [NSColor secondarySelectedControlColor];
1447 - (void)adjustViewSize
1449 KHTMLView *view = _part->view();
1451 view->adjustViewSize();
1454 -(id)accessibilityTree
1456 KWQAccObjectCache::enableAccessibility();
1457 if (!_part || !_part->xmlDocImpl()) return nil;
1458 RenderCanvas* root = static_cast<khtml::RenderCanvas *>(_part->xmlDocImpl()->renderer());
1459 if (!root) return nil;
1460 return _part->xmlDocImpl()->getAccObjectCache()->accObject(root);
1463 - (void)setDrawsBackground:(BOOL)drawsBackground
1465 if (_part && _part->view())
1466 _part->view()->setTransparent(!drawsBackground);
1469 - (void)undoEditing:(id)arg
1471 ASSERT([arg isKindOfClass:[KWQEditCommand class]]);
1472 [arg command]->unapply();
1475 - (void)redoEditing:(id)arg
1477 ASSERT([arg isKindOfClass:[KWQEditCommand class]]);
1478 [arg command]->reapply();
1481 - (DOMRange *)rangeByExpandingSelectionWithGranularity:(WebSelectionGranularity)granularity
1483 if (!partHasSelection(self))
1486 // NOTE: The enums *must* match the very similar ones declared in ktml_selection.h
1487 Selection selection(_part->selection());
1488 _part->setSelectionGranularity(static_cast<ETextGranularity>(granularity));
1489 selection.expandUsingGranularity(static_cast<ETextGranularity>(granularity));
1490 return [DOMRange _rangeWithImpl:selection.toRange().handle()];
1493 - (DOMRange *)rangeByAlteringCurrentSelection:(WebSelectionAlteration)alteration direction:(WebSelectionDirection)direction granularity:(WebSelectionGranularity)granularity
1495 if (!partHasSelection(self))
1498 // NOTE: The enums *must* match the very similar ones declared in ktml_selection.h
1499 Selection selection(_part->selection());
1500 _part->setSelectionGranularity(static_cast<ETextGranularity>(granularity));
1501 selection.modify(static_cast<Selection::EAlter>(alteration),
1502 static_cast<Selection::EDirection>(direction),
1503 static_cast<ETextGranularity>(granularity));
1504 return [DOMRange _rangeWithImpl:selection.toRange().handle()];
1507 - (void)alterCurrentSelection:(WebSelectionAlteration)alteration direction:(WebSelectionDirection)direction granularity:(WebSelectionGranularity)granularity
1509 if (!partHasSelection(self))
1512 // NOTE: The enums *must* match the very similar ones declared in dom_selection.h
1513 Selection selection(_part->selection());
1514 _part->setSelectionGranularity(static_cast<ETextGranularity>(granularity));
1515 selection.modify(static_cast<Selection::EAlter>(alteration),
1516 static_cast<Selection::EDirection>(direction),
1517 static_cast<ETextGranularity>(granularity));
1519 // save vertical navigation x position if necessary; many types of motion blow it away
1520 int xPos = KHTMLPart::NoXPosForVerticalArrowNavigation;
1521 switch (granularity) {
1522 case WebSelectByLine:
1523 case WebSelectByParagraph:
1524 xPos = _part->xPosForVerticalArrowNavigation();
1526 case WebSelectByCharacter:
1527 case WebSelectByWord:
1528 case WebSelectToLineBoundary:
1529 case WebSelectToParagraphBoundary:
1530 case WebSelectToDocumentBoundary:
1535 // setting the selection always clears saved vertical navigation x position
1536 _part->setSelection(selection);
1538 // restore vertical navigation x position if necessary
1539 if (xPos != KHTMLPart::NoXPosForVerticalArrowNavigation)
1540 _part->setXPosForVerticalArrowNavigation(xPos);
1542 [self ensureSelectionVisible];
1545 - (DOMRange *)rangeByAlteringCurrentSelection:(WebSelectionAlteration)alteration verticalDistance:(float)verticalDistance
1547 if (!partHasSelection(self))
1550 Selection selection(_part->selection());
1551 selection.modify(static_cast<Selection::EAlter>(alteration), static_cast<int>(verticalDistance));
1552 return [DOMRange _rangeWithImpl:selection.toRange().handle()];
1555 - (void)alterCurrentSelection:(WebSelectionAlteration)alteration verticalDistance:(float)verticalDistance
1557 if (!partHasSelection(self))
1560 Selection selection(_part->selection());
1561 selection.modify(static_cast<Selection::EAlter>(alteration), static_cast<int>(verticalDistance));
1563 // setting the selection always clears saved vertical navigation x position, so preserve it
1564 int xPos = _part->xPosForVerticalArrowNavigation();
1565 _part->setSelection(selection);
1566 _part->setXPosForVerticalArrowNavigation(xPos);
1568 [self ensureSelectionVisible];
1571 - (WebSelectionGranularity)selectionGranularity
1573 // NOTE: The enums *must* match the very similar ones declared in dom_selection.h
1574 return static_cast<WebSelectionGranularity>(_part->selectionGranularity());
1577 - (void)setSelectedDOMRange:(DOMRange *)range affinity:(NSSelectionAffinity)selectionAffinity
1579 NodeImpl *startContainer = [[range startContainer] _nodeImpl];
1580 NodeImpl *endContainer = [[range endContainer] _nodeImpl];
1581 ASSERT(startContainer);
1582 ASSERT(endContainer);
1583 ASSERT(startContainer->getDocument());
1584 ASSERT(startContainer->getDocument() == endContainer->getDocument());
1586 _part->xmlDocImpl()->updateLayout();
1588 EAffinity affinity = static_cast<EAffinity>(selectionAffinity);
1590 bool rangeCollapsed = [range collapsed];
1591 if (!rangeCollapsed)
1592 affinity = DOWNSTREAM;
1594 // Work around bug where isRenderedContent returns false for <br> elements at the ends of lines.
1595 // If that bug wasn't an issue, we could just make the position from the range directly.
1596 Position start(startContainer, [range startOffset]);
1597 Position end(endContainer, [range endOffset]);
1598 VisiblePosition visibleStart(start, affinity, khtml::VisiblePosition::INIT_UP);
1599 start = visibleStart.deepEquivalent();
1601 if (rangeCollapsed) {
1602 setAffinityUsingLinePosition(visibleStart);
1603 affinity = visibleStart.affinity();
1606 // FIXME: Can we provide extentAffinity?
1607 Selection selection(start, affinity, end, khtml::SEL_DEFAULT_AFFINITY);
1608 _part->setSelection(selection);
1611 - (DOMRange *)selectedDOMRange
1613 return [DOMRange _rangeWithImpl:_part->selection().toRange().handle()];
1616 - (NSSelectionAffinity)selectionAffinity
1618 return static_cast<NSSelectionAffinity>(_part->selection().startAffinity());
1621 - (void)setMarkDOMRange:(DOMRange *)range
1623 _part->setMark(Selection([range _rangeImpl], khtml::SEL_DEFAULT_AFFINITY, khtml::SEL_DEFAULT_AFFINITY));
1626 - (DOMRange *)markDOMRange
1628 return [DOMRange _rangeWithImpl:_part->mark().toRange().handle()];
1631 - (void)setMarkedTextDOMRange:(DOMRange *)range customAttributes:(NSArray *)attributes ranges:(NSArray *)ranges
1633 _part->setMarkedTextRange([range _rangeImpl], attributes, ranges);
1636 - (DOMRange *)markedTextDOMRange
1638 return [DOMRange _rangeWithImpl:_part->markedTextRange().handle()];
1641 // Given proposedRange, returns an extended range that includes adjacent whitespace that should
1642 // be deleted along with the proposed range in order to preserve proper spacing and punctuation of
1643 // the text surrounding the deletion.
1644 - (DOMRange *)smartDeleteRangeForProposedRange:(DOMRange *)proposedRange
1646 NodeImpl *startContainer = [[proposedRange startContainer] _nodeImpl];
1647 NodeImpl *endContainer = [[proposedRange endContainer] _nodeImpl];
1648 if (startContainer == nil || endContainer == nil)
1651 ASSERT(startContainer->getDocument());
1652 ASSERT(startContainer->getDocument() == endContainer->getDocument());
1654 _part->xmlDocImpl()->updateLayout();
1656 Position start(startContainer, [proposedRange startOffset]);
1657 Position end(endContainer, [proposedRange endOffset]);
1658 Position newStart = start.upstream(DOM::StayInBlock).leadingWhitespacePosition(khtml::DOWNSTREAM, true);
1659 if (newStart.isNull())
1661 Position newEnd = end.downstream(DOM::StayInBlock).trailingWhitespacePosition(khtml::DOWNSTREAM, true);
1662 if (newEnd.isNull())
1665 return [DOMRange _rangeWithImpl:Range(newStart.node(), newStart.offset(), newEnd.node(), newEnd.offset()).handle()];
1668 // Determines whether whitespace needs to be added around aString to preserve proper spacing and
1669 // punctuation when itÕs inserted into the receiverÕs text over charRange. Returns by reference
1670 // in beforeString and afterString any whitespace that should be added, unless either or both are
1671 // nil. Both are returned as nil if aString is nil or if smart insertion and deletion are disabled.
1672 - (void)smartInsertForString:(NSString *)pasteString replacingRange:(DOMRange *)rangeToReplace beforeString:(NSString **)beforeString afterString:(NSString **)afterString
1674 // give back nil pointers in case of early returns
1676 *beforeString = nil;
1680 // inspect destination
1681 NodeImpl *startContainer = [[rangeToReplace startContainer] _nodeImpl];
1682 NodeImpl *endContainer = [[rangeToReplace endContainer] _nodeImpl];
1684 Position startPos(startContainer, [rangeToReplace startOffset]);
1685 Position endPos(endContainer, [rangeToReplace endOffset]);
1687 VisiblePosition startVisiblePos = VisiblePosition(startPos, khtml::VP_DEFAULT_AFFINITY);
1688 VisiblePosition endVisiblePos = VisiblePosition(endPos, khtml::VP_DEFAULT_AFFINITY);
1690 // this check also ensures startContainer, startPos, endContainer, and endPos are non-null
1691 if (startVisiblePos.isNull() || endVisiblePos.isNull())
1694 bool addLeadingSpace = startPos.leadingWhitespacePosition(khtml::VP_DEFAULT_AFFINITY, true).isNull() && !isFirstVisiblePositionInParagraph(startVisiblePos);
1695 if (addLeadingSpace) {
1696 QChar previousChar = startVisiblePos.previous().character();
1697 if (!previousChar.isNull()) {
1698 addLeadingSpace = !_part->isCharacterSmartReplaceExempt(previousChar, true);
1702 bool addTrailingSpace = endPos.trailingWhitespacePosition(khtml::VP_DEFAULT_AFFINITY, true).isNull() && !isLastVisiblePositionInParagraph(endVisiblePos);
1703 if (addTrailingSpace) {
1704 QChar thisChar = endVisiblePos.character();
1705 if (!thisChar.isNull()) {
1706 addTrailingSpace = !_part->isCharacterSmartReplaceExempt(thisChar, false);
1711 bool hasWhitespaceAtStart = false;
1712 bool hasWhitespaceAtEnd = false;
1713 unsigned pasteLength = [pasteString length];
1714 if (pasteLength > 0) {
1715 NSCharacterSet *whiteSet = [NSCharacterSet whitespaceAndNewlineCharacterSet];
1717 if ([whiteSet characterIsMember:[pasteString characterAtIndex:0]]) {
1718 hasWhitespaceAtStart = YES;
1720 if ([whiteSet characterIsMember:[pasteString characterAtIndex:(pasteLength - 1)]]) {
1721 hasWhitespaceAtEnd = YES;
1725 // issue the verdict
1726 if (beforeString && addLeadingSpace && !hasWhitespaceAtStart)
1727 *beforeString = @" ";
1728 if (afterString && addTrailingSpace && !hasWhitespaceAtEnd)
1729 *afterString = @" ";
1732 - (DOMDocumentFragment *)documentFragmentWithMarkupString:(NSString *)markupString baseURLString:(NSString *)baseURLString
1734 if (!_part || !_part->xmlDocImpl())
1737 DocumentFragmentImpl *fragment = createFragmentFromMarkup(_part->xmlDocImpl(), QString::fromNSString(markupString), QString::fromNSString(baseURLString));
1738 return [DOMDocumentFragment _documentFragmentWithImpl:fragment];
1741 - (DOMDocumentFragment *)documentFragmentWithText:(NSString *)text
1743 if (!partHasSelection(self) || !text)
1746 return [DOMDocumentFragment _documentFragmentWithImpl:createFragmentFromText(_part->xmlDocImpl(), QString::fromNSString(text))];
1749 - (void)replaceSelectionWithFragment:(DOMDocumentFragment *)fragment selectReplacement:(BOOL)selectReplacement smartReplace:(BOOL)smartReplace matchStyle:(BOOL)matchStyle
1751 if (!partHasSelection(self) || !fragment)
1754 EditCommandPtr(new ReplaceSelectionCommand(_part->xmlDocImpl(), [fragment _fragmentImpl], selectReplacement, smartReplace, matchStyle)).apply();
1755 [self ensureSelectionVisible];
1758 - (void)replaceSelectionWithNode:(DOMNode *)node selectReplacement:(BOOL)selectReplacement smartReplace:(BOOL)smartReplace
1760 DOMDocumentFragment *fragment = [[self DOMDocument] createDocumentFragment];
1761 [fragment appendChild:node];
1762 [self replaceSelectionWithFragment:fragment selectReplacement:selectReplacement smartReplace:smartReplace matchStyle:NO];
1765 - (void)replaceSelectionWithMarkupString:(NSString *)markupString baseURLString:(NSString *)baseURLString selectReplacement:(BOOL)selectReplacement smartReplace:(BOOL)smartReplace
1767 DOMDocumentFragment *fragment = [self documentFragmentWithMarkupString:markupString baseURLString:baseURLString];
1768 [self replaceSelectionWithFragment:fragment selectReplacement:selectReplacement smartReplace:smartReplace matchStyle:NO];
1771 - (void)replaceSelectionWithText:(NSString *)text selectReplacement:(BOOL)selectReplacement smartReplace:(BOOL)smartReplace
1773 [self replaceSelectionWithFragment:[self documentFragmentWithText:text] selectReplacement:selectReplacement smartReplace:smartReplace matchStyle:YES];
1776 - (void)insertLineBreak
1778 if (!partHasSelection(self))
1781 TypingCommand::insertLineBreak(_part->xmlDocImpl());
1782 [self ensureSelectionVisible];
1785 - (void)insertParagraphSeparator
1787 if (!partHasSelection(self))
1790 TypingCommand::insertParagraphSeparator(_part->xmlDocImpl());
1791 [self ensureSelectionVisible];
1794 - (void)insertParagraphSeparatorInQuotedContent
1796 if (!partHasSelection(self))
1799 TypingCommand::insertParagraphSeparatorInQuotedContent(_part->xmlDocImpl());
1800 [self ensureSelectionVisible];
1803 - (void)insertText:(NSString *)text selectInsertedText:(BOOL)selectInsertedText
1805 if (!partHasSelection(self))
1808 TypingCommand::insertText(_part->xmlDocImpl(), text, selectInsertedText);
1809 [self ensureSelectionVisible];
1812 - (void)setSelectionToDragCaret
1814 _part->setSelection(_part->dragCaret());
1817 - (void)moveSelectionToDragCaret:(DOMDocumentFragment *)selectionFragment smartMove:(BOOL)smartMove
1819 Position base = _part->dragCaret().base();
1820 EditCommandPtr(new MoveSelectionCommand(_part->xmlDocImpl(), [selectionFragment _fragmentImpl], base, smartMove)).apply();
1823 - (VisiblePosition)_visiblePositionForPoint:(NSPoint)point
1825 RenderObject *renderer = _part->renderer();
1827 return VisiblePosition();
1830 RenderObject::NodeInfo nodeInfo(true, true);
1831 renderer->layer()->hitTest(nodeInfo, (int)point.x, (int)point.y);
1832 NodeImpl *node = nodeInfo.innerNode();
1833 if (!node->renderer())
1834 return VisiblePosition();
1836 return node->renderer()->positionForCoordinates((int)point.x, (int)point.y);
1839 - (void)moveDragCaretToPoint:(NSPoint)point
1841 Selection dragCaret([self _visiblePositionForPoint:point]);
1842 _part->setDragCaret(dragCaret);
1845 - (void)removeDragCaret
1847 _part->setDragCaret(Selection());
1850 - (DOMRange *)dragCaretDOMRange
1852 return [DOMRange _rangeWithImpl:_part->dragCaret().toRange().handle()];
1855 - (DOMRange *)editableDOMRangeForPoint:(NSPoint)point
1857 VisiblePosition position = [self _visiblePositionForPoint:point];
1858 return position.isNull() ? nil : [DOMRange _rangeWithImpl:Selection(position).toRange().handle()];
1861 - (void)deleteSelectionWithSmartDelete:(BOOL)smartDelete
1863 if (!partHasSelection(self))
1866 EditCommandPtr(new DeleteSelectionCommand(_part->xmlDocImpl(), smartDelete)).apply();
1869 - (void)deleteKeyPressedWithSmartDelete:(BOOL)smartDelete
1871 if (!_part || !_part->xmlDocImpl())
1874 TypingCommand::deleteKeyPressed(_part->xmlDocImpl(), smartDelete);
1875 [self ensureSelectionVisible];
1878 - (void)forwardDeleteKeyPressedWithSmartDelete:(BOOL)smartDelete
1880 if (!_part || !_part->xmlDocImpl())
1883 TypingCommand::forwardDeleteKeyPressed(_part->xmlDocImpl(), smartDelete);
1884 [self ensureSelectionVisible];
1887 - (DOMCSSStyleDeclaration *)typingStyle
1889 if (!_part || !_part->typingStyle())
1891 return [DOMCSSStyleDeclaration _styleDeclarationWithImpl:_part->typingStyle()];
1894 - (void)setTypingStyle:(DOMCSSStyleDeclaration *)style withUndoAction:(WebUndoAction)undoAction
1898 _part->computeAndSetTypingStyle([style _styleDeclarationImpl], static_cast<EditAction>(undoAction));
1901 - (void)applyStyle:(DOMCSSStyleDeclaration *)style withUndoAction:(WebUndoAction)undoAction
1905 _part->applyStyle([style _styleDeclarationImpl], static_cast<EditAction>(undoAction));
1908 - (void)applyParagraphStyle:(DOMCSSStyleDeclaration *)style withUndoAction:(WebUndoAction)undoAction
1912 _part->applyParagraphStyle([style _styleDeclarationImpl], static_cast<EditAction>(undoAction));
1915 - (BOOL)selectionStartHasStyle:(DOMCSSStyleDeclaration *)style
1919 return _part->selectionStartHasStyle([style _styleDeclarationImpl]);
1922 - (NSCellStateValue)selectionHasStyle:(DOMCSSStyleDeclaration *)style
1926 switch (_part->selectionHasStyle([style _styleDeclarationImpl])) {
1927 case KHTMLPart::falseTriState:
1929 case KHTMLPart::trueTriState:
1931 case KHTMLPart::mixedTriState:
1932 return NSMixedState;
1937 - (void)applyEditingStyleToBodyElement
1941 _part->applyEditingStyleToBodyElement();
1944 - (void)removeEditingStyleFromBodyElement
1948 _part->removeEditingStyleFromBodyElement();
1951 - (void)applyEditingStyleToElement:(DOMElement *)element
1955 _part->applyEditingStyleToElement([element _elementImpl]);
1958 - (void)removeEditingStyleFromElement:(DOMElement *)element
1962 _part->removeEditingStyleFromElement([element _elementImpl]);
1965 - (NSFont *)fontForSelection:(BOOL *)hasMultipleFonts
1967 bool multipleFonts = false;
1970 font = _part->fontForSelection(hasMultipleFonts ? &multipleFonts : 0);
1971 if (hasMultipleFonts)
1972 *hasMultipleFonts = multipleFonts;
1976 - (NSDictionary *)fontAttributesForSelectionStart
1978 return _part ? _part->fontAttributesForSelectionStart() : nil;
1981 - (NSWritingDirection)baseWritingDirectionForSelectionStart
1983 return _part ? _part->baseWritingDirectionForSelectionStart() : NSWritingDirectionLeftToRight;
1986 - (void)ensureSelectionVisible
1988 if (!partHasSelection(self))
1991 KHTMLView *v = _part->view();
1995 Position extent = _part->selection().extent();
1996 if (extent.isNull())
1999 RenderObject *renderer = extent.node()->renderer();
2003 NSView *documentView = v->getDocumentView();
2007 QRect extentRect = renderer->caretRect(extent.offset(), _part->selection().extentAffinity());
2008 if (!NSContainsRect([documentView visibleRect], NSRect(extentRect))) {
2009 v->ensureRectVisibleCentered(extentRect, true);
2013 // [info draggingLocation] is in window coords
2015 - (BOOL)eventMayStartDrag:(NSEvent *)event
2017 return _part ? _part->eventMayStartDrag(event) : NO;
2020 - (NSDragOperation)dragOperationForDraggingInfo:(id <NSDraggingInfo>)info
2022 NSDragOperation op = NSDragOperationNone;
2024 KHTMLView *v = _part->view();
2026 // Sending an event can result in the destruction of the view and part.
2029 KWQClipboard::AccessPolicy policy = _part->baseURL().isLocalFile() ? KWQClipboard::Readable : KWQClipboard::TypesReadable;
2030 KWQClipboard *clipboard = new KWQClipboard(true, [info draggingPasteboard], policy);
2032 NSDragOperation srcOp = [info draggingSourceOperationMask];
2033 clipboard->setSourceOperation(srcOp);
2035 if (v->updateDragAndDrop(QPoint([info draggingLocation]), clipboard)) {
2036 // *op unchanged if no source op was set
2037 if (!clipboard->destinationOperation(&op)) {
2038 // The element accepted but they didn't pick an operation, so we pick one for them
2040 if (srcOp & NSDragOperationCopy) {
2041 op = NSDragOperationCopy;
2042 } else if (srcOp & NSDragOperationMove || srcOp & NSDragOperationGeneric) {
2043 op = NSDragOperationMove;
2044 } else if (srcOp & NSDragOperationLink) {
2045 op = NSDragOperationLink;
2047 op = NSDragOperationGeneric;
2049 } else if (!(op & srcOp)) {
2050 // make sure WC picked an op that was offered. Cocoa doesn't seem to enforce this,
2052 op = NSDragOperationNone;
2055 clipboard->setAccessPolicy(KWQClipboard::Numb); // invalidate clipboard here for security
2065 - (void)dragExitedWithDraggingInfo:(id <NSDraggingInfo>)info
2068 KHTMLView *v = _part->view();
2070 // Sending an event can result in the destruction of the view and part.
2073 KWQClipboard::AccessPolicy policy = _part->baseURL().isLocalFile() ? KWQClipboard::Readable : KWQClipboard::TypesReadable;
2074 KWQClipboard *clipboard = new KWQClipboard(true, [info draggingPasteboard], policy);
2076 clipboard->setSourceOperation([info draggingSourceOperationMask]);
2078 v->cancelDragAndDrop(QPoint([info draggingLocation]), clipboard);
2079 clipboard->setAccessPolicy(KWQClipboard::Numb); // invalidate clipboard here for security
2087 - (BOOL)concludeDragForDraggingInfo:(id <NSDraggingInfo>)info
2090 KHTMLView *v = _part->view();
2092 // Sending an event can result in the destruction of the view and part.
2095 KWQClipboard *clipboard = new KWQClipboard(true, [info draggingPasteboard], KWQClipboard::Readable);
2097 clipboard->setSourceOperation([info draggingSourceOperationMask]);
2099 BOOL result = v->performDragAndDrop(QPoint([info draggingLocation]), clipboard);
2100 clipboard->setAccessPolicy(KWQClipboard::Numb); // invalidate clipboard here for security
2111 - (void)dragSourceMovedTo:(NSPoint)windowLoc
2114 _part->dragSourceMovedTo(QPoint(windowLoc));
2118 - (void)dragSourceEndedAt:(NSPoint)windowLoc operation:(NSDragOperation)operation
2121 _part->dragSourceEndedAt(QPoint(windowLoc), operation);
2127 return _part->mayCut();
2130 - (BOOL)mayDHTMLCopy
2132 return _part->mayCopy();
2135 - (BOOL)mayDHTMLPaste
2137 return _part->mayPaste();
2142 return _part->tryCut();
2145 - (BOOL)tryDHTMLCopy
2147 return _part->tryCopy();
2150 - (BOOL)tryDHTMLPaste
2152 return _part->tryPaste();
2155 - (DOMRange *)rangeOfCharactersAroundCaret
2160 Selection selection(_part->selection());
2161 if (!selection.isCaret())
2164 VisiblePosition caret(selection.start(), selection.startAffinity());
2165 VisiblePosition next = caret.next();
2166 VisiblePosition previous = caret.previous();
2167 if (caret == next || caret == previous)
2170 return [DOMRange _rangeWithImpl:makeRange(previous, next).handle()];
2173 - (NSMutableDictionary *)dashboardRegions
2175 return _part->dashboardRegionsDictionary();
2180 @implementation WebCoreBridge (WebCoreBridgeInternal)
2182 - (RootObject *)executionContextForView:(NSView *)aView
2184 KWQKHTMLPart *part = [self part];
2185 RootObject *root = new RootObject(aView); // The root gets deleted by JavaScriptCore.
2186 root->setRootObjectImp(static_cast<ObjectImp *>(Window::retrieveWindow(part)));
2187 root->setInterpreter(KJSProxy::proxy(part)->interpreter());
2188 part->addPluginRootObject(root);