b0000b96ace7bd83beb997bdb7f1ba1ad4fba812
[WebKit-https.git] / WebCore / kwq / WebCoreBridge.mm
1 /*
2  * Copyright (C) 2004 Apple Computer, Inc.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
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.
12  *
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. 
24  */
25
26 #import "WebCoreBridge.h"
27
28 #include <CoreFoundation/CFCharacterSetPriv.h>
29
30 #import "csshelper.h"
31 #import "dom2_eventsimpl.h"
32 #import "dom2_rangeimpl.h"
33 #import "dom2_viewsimpl.h"
34 #import "dom_docimpl.h"
35 #import "dom_node.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"
41 #import "htmlattrs.h"
42 #import "htmlediting.h"
43 #import "htmltags.h"
44 #import "khtml_part.h"
45 #import "khtmlview.h"
46 #import "kjs_proxy.h"
47 #import "kjs_window.h"
48 #import "loader.h"
49 #import "markup.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"
56 #import "selection.h"
57 #import "visible_position.h"
58 #import "xml_tokenizer.h"
59
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>
65
66 #import "KWQAssertions.h"
67 #import "KWQCharsets.h"
68 #import "KWQClipboard.h"
69 #import "KWQDOMNode.h"
70 #import "KWQEditCommand.h"
71 #import "KWQFont.h"
72 #import "KWQFoundationExtras.h"
73 #import "KWQFrame.h"
74 #import "KWQKHTMLPart.h"
75 #import "KWQLoader.h"
76 #import "KWQPageState.h"
77 #import "KWQRenderTreeDebug.h"
78 #import "KWQView.h"
79 #import "KWQPrinter.h"
80 #import "KWQAccObjectCache.h"
81
82 #import "DOMInternal.h"
83 #import "WebCoreImageRenderer.h"
84 #import "WebCoreTextRendererFactory.h"
85 #import "WebCoreViewFactory.h"
86 #import "WebCoreSettings.h"
87
88 @class NSView;
89
90 using DOM::AtomicString;
91 using DOM::CSSStyleDeclarationImpl;
92 using DOM::DocumentFragmentImpl;
93 using DOM::DocumentImpl;
94 using DOM::DocumentTypeImpl;
95 using DOM::DOMString;
96 using DOM::Element;
97 using DOM::ElementImpl;
98 using DOM::HTMLElementImpl;
99 using DOM::HTMLFormElementImpl;
100 using DOM::HTMLGenericFormElementImpl;
101 using DOM::HTMLImageElementImpl;
102 using DOM::HTMLInputElementImpl;
103 using DOM::Node;
104 using DOM::NodeImpl;
105 using DOM::Position;
106 using DOM::Range;
107
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;
133
134 using KJS::ExecState;
135 using KJS::ObjectImp;
136 using KJS::SavedProperties;
137 using KJS::SavedBuiltins;
138 using KJS::Window;
139
140 using KParts::URLArgs;
141
142 using KJS::Bindings::RootObject;
143
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
157
158 NSString *WebCorePageCacheStateKey =            @"WebCorePageCacheState";
159
160 @interface WebCoreBridge (WebCoreBridgeInternal)
161 - (RootObject *)executionContextForView:(NSView *)aView;
162 @end
163
164 static RootObject *rootForView(void *v)
165 {
166     NSView *aView = (NSView *)v;
167     WebCoreBridge *aBridge = [[WebCoreViewFactory sharedFactory] bridgeForView:aView];
168     RootObject *root = 0;
169
170     if (aBridge)
171         root = [aBridge executionContextForView:aView];
172
173     return root;
174 }
175
176 static pthread_t mainThread = 0;
177
178 static void updateRenderingForBindings (ExecState *exec, ObjectImp *rootObject)
179 {
180     if (pthread_self() != mainThread)
181         return;
182         
183     if (!rootObject)
184         return;
185         
186     Window *window = static_cast<Window*>(rootObject);
187     if (!window)
188         return;
189         
190     DOM::DocumentImpl *doc = static_cast<DOM::DocumentImpl*>(window->part()->document().handle());
191     if (doc)
192         doc->updateRendering();
193 }
194
195 static BOOL partHasSelection(WebCoreBridge *bridge)
196 {
197     if (!bridge)
198         return NO;
199     
200     KHTMLPart *part = bridge->_part;
201     if (!part)
202         return NO;
203         
204     if (part->selection().isNone())
205         return NO;
206
207     // If a part has a selection, it should also have a document.        
208     ASSERT(part->xmlDocImpl());
209
210     return YES;
211 }
212
213 static BOOL hasCaseInsensitivePrefix(NSString *string, NSString *prefix)
214 {
215     return [string rangeOfString:prefix options:(NSCaseInsensitiveSearch | NSAnchoredSearch)].location !=
216         NSNotFound;
217 }
218
219 @implementation WebCoreBridge
220
221 static bool initializedObjectCacheSize = FALSE;
222 static bool initializedKJS = FALSE;
223
224 + (WebCoreBridge *)bridgeForDOMDocument:(DOMDocument *)document
225 {
226     return ((KWQKHTMLPart *)[document _documentImpl]->part())->bridge();
227 }
228
229 - init
230 {
231     [super init];
232     
233     _part = new KWQKHTMLPart;
234     _part->setBridge(self);
235
236     if (!initializedObjectCacheSize){
237         khtml::Cache::setSize([self getObjectCacheSize]);
238         initializedObjectCacheSize = TRUE;
239     }
240     
241     if (!initializedKJS) {
242         mainThread = pthread_self();
243         
244         RootObject::setFindRootObjectForNativeHandleFunction (rootForView);
245
246         KJS::Bindings::Instance::setDidExecuteFunction(updateRenderingForBindings);
247         
248         initializedKJS = TRUE;
249     }
250     
251     _shouldCreateRenderers = YES;
252     
253     return self;
254 }
255
256 - (void)initializeSettings: (WebCoreSettings *)settings
257 {
258     _part->setSettings ([settings settings]);
259 }
260
261 - (void)dealloc
262 {
263     [self removeFromFrame];
264     
265     if (_renderPart) {
266         _renderPart->deref(_renderPartArena);
267     }
268     _part->setBridge(nil);
269     _part->deref();
270         
271     [super dealloc];
272 }
273
274 - (void)finalize
275 {
276     // FIXME: This work really should not be done at deallocation time.
277     // We need to do it at some well-defined time instead.
278
279     [self removeFromFrame];
280     
281     if (_renderPart) {
282         _renderPart->deref(_renderPartArena);
283     }
284     _part->setBridge(nil);
285     _part->deref();
286         
287     [super finalize];
288 }
289
290 - (KWQKHTMLPart *)part
291 {
292     return _part;
293 }
294
295 - (void)setRenderPart:(KHTMLRenderPart *)newPart;
296 {
297     RenderArena *arena = newPart->ref();
298     if (_renderPart) {
299         _renderPart->deref(_renderPartArena);
300     }
301     _renderPart = newPart;
302     _renderPartArena = arena;
303 }
304
305 - (KHTMLRenderPart *)renderPart
306 {
307     return _renderPart;
308 }
309
310 - (void)setParent:(WebCoreBridge *)parent
311 {
312     _part->setParent([parent part]);
313 }
314
315 - (void)provisionalLoadStarted
316 {
317     _part->provisionalLoadStarted();
318 }
319
320 - (void)openURL:(NSURL *)URL reload:(BOOL)reload contentType:(NSString *)contentType refresh:(NSString *)refresh lastModified:(NSDate *)lastModified pageCache:(NSDictionary *)pageCache
321 {
322     if (pageCache) {
323         KWQPageState *state = [pageCache objectForKey:WebCorePageCacheStateKey];
324         _part->openURLFromPageCache(state);
325         [state invalidate];
326         return;
327     }
328         
329     // arguments
330     URLArgs args(_part->browserExtension()->urlArgs());
331     args.reload = reload;
332     if (contentType) {
333         args.serviceType = QString::fromNSString(contentType);
334     }
335     _part->browserExtension()->setURLArgs(args);
336
337     // opening the URL
338     if (_part->didOpenURL(URL)) {
339         // things we have to set up after calling didOpenURL
340         if (refresh) {
341             _part->addMetaData("http-refresh", QString::fromNSString(refresh));
342         }
343         if (lastModified) {
344             NSString *modifiedString = [lastModified descriptionWithCalendarFormat:@"%a %b %d %Y %H:%M:%S" timeZone:nil locale:nil];
345             _part->addMetaData("modified", QString::fromNSString(modifiedString));
346         }
347     }
348 }
349
350 - (void)setEncoding:(NSString *)encoding userChosen:(BOOL)userChosen
351 {
352     _part->setEncoding(QString::fromNSString(encoding), userChosen);
353 }
354
355 - (void)addData:(NSData *)data
356 {
357     DocumentImpl *doc = _part->xmlDocImpl();
358     
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
362     // has been created. 
363     if (doc){
364         doc->setShouldCreateRenderers([self shouldCreateRenderers]);
365         _part->addData((const char *)[data bytes], [data length]);
366     }
367 }
368
369 - (void)closeURL
370 {
371     _part->closeURL();
372 }
373
374 - (void)didNotOpenURL:(NSURL *)URL pageCache:(NSDictionary *)pageCache
375 {
376     _part->didNotOpenURL(KURL(URL).url());
377
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();
382     if (doc) {
383         doc->setInPageCache(NO);
384     }
385     KWQPageState *state = [pageCache objectForKey:WebCorePageCacheStateKey];
386     [state invalidate];
387 }
388
389 - (BOOL)canLoadURL:(NSURL *)URL fromReferrer:(NSString *)referrer hideReferrer:(BOOL *)hideReferrer
390 {
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;
394
395     return referrerIsFileURL || !URLIsFileURL;
396 }
397
398 - (void)saveDocumentState
399 {
400     DocumentImpl *doc = _part->xmlDocImpl();
401     if (doc != 0){
402         QStringList list = doc->docState();
403         NSMutableArray *documentState = [[[NSMutableArray alloc] init] autorelease];
404         
405         for (uint i = 0; i < list.count(); i++){
406             QString s = list[i];
407             [documentState addObject: [NSString stringWithCharacters: (const unichar *)s.unicode() length: s.length()]];
408         }
409         [self saveDocumentState: documentState];
410     }
411 }
412
413 - (void)restoreDocumentState
414 {
415     DocumentImpl *doc = _part->xmlDocImpl();
416     
417     if (doc != 0){
418         NSArray *documentState = [self documentState];
419         
420         QStringList s;
421         for (uint i = 0; i < [documentState count]; i++){
422             NSString *string = [documentState objectAtIndex: i];
423             s.append(QString::fromNSString(string));
424         }
425             
426         doc->setRestoreState(s);
427     }
428 }
429
430 - (void)scrollToAnchorWithURL:(NSURL *)URL
431 {
432     _part->scrollToAnchor(KURL(URL).url().latin1());
433 }
434
435 - (BOOL)scrollOverflowInDirection:(WebScrollDirection)direction granularity:(WebScrollGranularity)granularity
436 {
437     if (_part == NULL) {
438         return NO;
439     }
440     return _part->scrollOverflow((KWQScrollDirection)direction, (KWQScrollGranularity)granularity);
441 }
442
443 - (BOOL)scrollOverflowWithScrollWheelEvent:(NSEvent *)event
444 {
445     if (_part == NULL) {
446         return NO;
447     }    
448     return _part->scrollOverflowWithScrollWheelEvent(event);
449 }
450
451 - (BOOL)saveDocumentToPageCache
452 {
453     DocumentImpl *doc = _part->xmlDocImpl();
454     if (!doc) {
455         return NO;
456     }
457     
458     if (!doc->view()) {
459         return NO;
460     }
461     _part->clearTimers();
462
463     SavedProperties *windowProperties = new SavedProperties;
464     _part->saveWindowProperties(windowProperties);
465
466     SavedProperties *locationProperties = new SavedProperties;
467     _part->saveLocationProperties(locationProperties);
468     
469     SavedBuiltins *interpreterBuiltins = new SavedBuiltins;
470     _part->saveInterpreterBuiltins(*interpreterBuiltins);
471
472     KWQPageState *pageState = [[[KWQPageState alloc] initWithDocument:doc
473                                                                   URL:_part->m_url
474                                                      windowProperties:windowProperties
475                                                    locationProperties:locationProperties
476                                                   interpreterBuiltins:interpreterBuiltins] autorelease];
477     [pageState setPausedActions: _part->pauseActions((const void *)pageState)];
478
479     return [self saveDocumentToPageCache:pageState];
480 }
481
482 - (BOOL)canCachePage
483 {
484     return _part->canCachePage();
485 }
486
487 - (void)clear
488 {
489     _part->clear();
490 }
491
492 - (void)end
493 {
494     _part->end();
495 }
496
497 - (void)stop
498 {
499     _part->stop();
500 }
501
502 - (void)createKHTMLViewWithNSView:(NSView *)view marginWidth:(int)mw marginHeight:(int)mh
503 {
504     // If we own the view, delete the old one - otherwise the render _part will take care of deleting the view.
505     [self removeFromFrame];
506
507     KHTMLView *kview = new KHTMLView(_part, 0);
508     _part->setView(kview);
509     kview->deref();
510
511     kview->setView(view);
512     if (mw >= 0)
513         kview->setMarginWidth(mw);
514     if (mh >= 0)
515         kview->setMarginHeight(mh);
516 }
517
518 - (void)scrollToAnchor:(NSString *)a
519 {
520     _part->gotoAnchor(QString::fromNSString(a));
521 }
522
523 - (BOOL)isSelectionEditable
524 {
525     // EDIT FIXME: This needs to consider the entire selected range
526     NodeImpl *startNode = _part->selection().start().node();
527     return startNode ? startNode->isContentEditable() : NO;
528 }
529
530 - (WebSelectionState)selectionState
531 {
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;
539     }
540     
541     ASSERT_NOT_REACHED();
542     return WebSelectionStateNone;
543 }
544
545 - (NSString *)_documentTypeString
546 {
547     NSString *documentTypeString = nil;
548     DOM::DocumentImpl *doc = _part->xmlDocImpl();
549     if (doc) {
550         DocumentTypeImpl *doctype = doc->doctype();
551         if (doctype) {
552             documentTypeString = doctype->toString().string().getNSString();
553         }
554     }
555     return documentTypeString;
556 }
557
558 - (NSString *)_stringWithDocumentTypeStringAndMarkupString:(NSString *)markupString
559 {
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) {
566         return markupString;
567     } else {
568         return @"";
569     }
570 }
571
572 - (NSArray *)nodesFromList:(QPtrList<NodeImpl> *)nodeList
573 {
574     NSMutableArray *nodes = [NSMutableArray arrayWithCapacity:nodeList->count()];
575     for (QPtrListIterator<NodeImpl> i(*nodeList); i.current(); ++i) {
576         [nodes addObject:[DOMNode _nodeWithImpl:i.current()]];
577     }
578     return nodes;
579 }
580
581 - (NSString *)markupStringFromNode:(DOMNode *)node nodes:(NSArray **)nodes
582 {
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();
586     if (nodes) {
587         *nodes = [self nodesFromList:&nodeList];
588     }
589     return [self _stringWithDocumentTypeStringAndMarkupString:markupString];
590 }
591
592 - (NSString *)markupStringFromRange:(DOMRange *)range nodes:(NSArray **)nodes
593 {
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();
597     if (nodes) {
598         *nodes = [self nodesFromList:&nodeList];
599     }
600     return [self _stringWithDocumentTypeStringAndMarkupString:markupString];
601 }
602
603 - (NSString *)selectedString
604 {
605     QString text = _part->selectedText();
606     text.replace(QChar('\\'), _part->backslashAsCurrencySymbol());
607     return [[text.getNSString() copy] autorelease];
608 }
609
610 - (NSString *)stringForRange:(DOMRange *)range
611 {
612     QString text = _part->text([range _rangeImpl]);
613     text.replace(QChar('\\'), _part->backslashAsCurrencySymbol());
614     return [[text.getNSString() copy] autorelease];
615 }
616
617 - (void)selectAll
618 {
619     _part->selectAll();
620 }
621
622 - (void)deselectAll
623 {
624     [self deselectText];
625     DocumentImpl *doc = _part->xmlDocImpl();
626     if (doc) {
627         doc->setFocusNode(0);
628     }
629 }
630
631 - (void)deselectText
632 {
633     _part->clearSelection();
634 }
635
636 - (BOOL)isFrameSet
637 {
638     return _part->isFrameSet();
639 }
640
641 - (NSString *)styleSheetForPrinting
642 {
643     if (!_part->settings()->shouldPrintBackgrounds()) {
644         return @"* { background-image: none !important; background-color: white !important;}";
645     }
646     return nil;
647 }
648
649 - (void)reapplyStylesForDeviceType:(WebCoreDeviceType)deviceType
650 {
651     _part->setMediaType(deviceType == WebCoreDeviceScreen ? "screen" : "print");
652     DocumentImpl *doc = _part->xmlDocImpl();
653     if (doc) {
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]));
659         }
660     }
661     return _part->reparseConfiguration();
662 }
663
664 static BOOL nowPrinting(WebCoreBridge *self)
665 {
666     DocumentImpl *doc = self->_part->xmlDocImpl();
667     return doc && doc->paintDevice() && doc->paintDevice()->devType() == QInternal::Printer;
668 }
669
670 // Set or unset the printing mode in the view.  We only toy with this if we're printing.
671 - (void)_setupRootForPrinting:(BOOL)onOrOff
672 {
673     if (nowPrinting(self)) {
674         RenderCanvas *root = static_cast<khtml::RenderCanvas *>(_part->xmlDocImpl()->renderer());
675         if (root) {
676             root->setPrintingMode(onOrOff);
677         }
678     }
679 }
680
681 - (void)forceLayoutAdjustingViewSize:(BOOL)flag
682 {
683     [self _setupRootForPrinting:YES];
684     _part->forceLayout();
685     if (flag) {
686         [self adjustViewSize];
687     }
688     [self _setupRootForPrinting:NO];
689 }
690
691 - (void)forceLayoutWithMinimumPageWidth:(float)minPageWidth maximumPageWidth:(float)maxPageWidth adjustingViewSize:(BOOL)flag
692 {
693     [self _setupRootForPrinting:YES];
694     _part->forceLayoutWithPageWidthRange(minPageWidth, maxPageWidth);
695     if (flag) {
696         [self adjustViewSize];
697     }
698     [self _setupRootForPrinting:NO];
699 }
700
701 - (void)sendResizeEvent
702 {
703     _part->sendResizeEvent();
704 }
705
706 - (void)sendScrollEvent
707 {
708     _part->sendScrollEvent();
709 }
710
711 - (void)drawRect:(NSRect)rect withPainter:(QPainter *)p
712 {
713     [self _setupRootForPrinting:YES];
714     _part->paint(p, QRect(rect));
715     [self _setupRootForPrinting:NO];
716 }
717
718 - (void)drawRect:(NSRect)rect
719 {
720     QPainter painter(nowPrinting(self));
721     bool displaysWithFocusAttributes = _part->displaysWithFocusAttributes();
722     painter.setUsesInactiveTextBackgroundColor(!displaysWithFocusAttributes);
723     painter.setDrawsFocusRing(displaysWithFocusAttributes);
724     [self drawRect:rect withPainter:&painter];
725 }
726
727 // Used by pagination code called from AppKit when a standalone web page is printed.
728 - (NSArray*)computePageRectsWithPrintWidthScaleFactor:(float)printWidthScaleFactor printHeight:(float)printHeight
729 {
730     [self _setupRootForPrinting:YES];
731     NSMutableArray* pages = [NSMutableArray arrayWithCapacity:5];
732     if (printWidthScaleFactor <= 0) {
733         ERROR("printWidthScaleFactor has bad value %.2f", printWidthScaleFactor);
734         return pages;
735     }
736     
737     if (printHeight <= 0) {
738         ERROR("printHeight has bad value %.2f", printHeight);
739         return pages;
740     }
741         
742     if (!_part || !_part->xmlDocImpl() || !_part->view()) return pages;
743     RenderCanvas* root = static_cast<khtml::RenderCanvas *>(_part->xmlDocImpl()->renderer());
744     if (!root) return pages;
745     
746     KHTMLView* view = _part->view();
747     NSView* documentView = view->getDocumentView();
748     if (!documentView)
749         return pages;
750         
751     float currPageHeight = printHeight;
752     float docHeight = root->layer()->height();
753     float docWidth = root->layer()->width();
754     float printWidth = docWidth/printWidthScaleFactor;
755     
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];
764         }
765     }
766     [self _setupRootForPrinting:NO];
767     
768     return pages;
769 }
770
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
773 {
774     [self _setupRootForPrinting:YES];
775     _part->adjustPageHeight(newBottom, oldTop, oldBottom, bottomLimit);
776     [self _setupRootForPrinting:NO];
777 }
778
779 - (NSObject *)copyDOMNode:(NodeImpl *)node copier:(id <WebCoreDOMTreeCopier>)copier
780 {
781     NSMutableArray *children = [[NSMutableArray alloc] init];
782     for (NodeImpl *child = node->firstChild(); child; child = child->nextSibling()) {
783         [children addObject:[self copyDOMNode:child copier:copier]];
784     }
785     NSObject *copiedNode = [copier nodeWithName:node->nodeName().string().getNSString()
786                                           value:node->nodeValue().string().getNSString()
787                                          source:createMarkup(node, ChildrenOnly).getNSString()
788                                        children:children];
789     [children release];
790     return copiedNode;
791 }
792
793 - (NSObject *)copyDOMTree:(id <WebCoreDOMTreeCopier>)copier
794 {
795     DocumentImpl *doc = _part->xmlDocImpl();
796     if (!doc) {
797         return nil;
798     }
799     return [self copyDOMNode:doc copier:copier];
800 }
801
802 - (NSObject *)copyRenderNode:(RenderObject *)node copier:(id <WebCoreRenderTreeCopier>)copier
803 {
804     NSMutableArray *children = [[NSMutableArray alloc] init];
805     for (RenderObject *child = node->firstChild(); child; child = child->nextSibling()) {
806         [children addObject:[self copyRenderNode:child copier:copier]];
807     }
808           
809     NSString *name = [[NSString alloc] initWithUTF8String:node->renderName()];
810     
811     RenderPart *nodeRenderPart = dynamic_cast<RenderPart *>(node);
812     QWidget *widget = nodeRenderPart ? nodeRenderPart->widget() : 0;
813     NSView *view = widget ? widget->getView() : nil;
814     
815     int nx, ny;
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())
820                                            view:view
821                                        children:children];
822     
823     [name release];
824     [children release];
825     
826     return copiedNode;
827 }
828
829 - (NSObject *)copyRenderTree:(id <WebCoreRenderTreeCopier>)copier
830 {
831     RenderObject *renderer = _part->renderer();
832     if (!renderer) {
833         return nil;
834     }
835     return [self copyRenderNode:renderer copier:copier];
836 }
837
838 - (void)removeFromFrame
839 {
840     _part->setView(0);
841 }
842
843 - (void)installInFrame:(NSView *)view
844 {
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);
848
849     _part->view()->setView(view);
850     if (_renderPart) {
851         _renderPart->setWidget(_part->view());
852         // Now the render part owns the view, so we don't any more.
853     }
854
855     _part->view()->initScrollBars();
856 }
857
858 - (void)setActivationEventNumber:(int)num
859 {
860     _part->setActivationEventNumber(num);
861 }
862
863 - (void)mouseDown:(NSEvent *)event
864 {
865     _part->mouseDown(event);
866 }
867
868 - (void)mouseDragged:(NSEvent *)event
869 {
870     _part->mouseDragged(event);
871 }
872
873 - (void)mouseUp:(NSEvent *)event
874 {
875     _part->mouseUp(event);
876 }
877
878 - (void)mouseMoved:(NSEvent *)event
879 {
880     _part->mouseMoved(event);
881 }
882
883 - (BOOL)sendContextMenuEvent:(NSEvent *)event
884 {
885     return _part->sendContextMenuEvent(event);
886 }
887
888 - (DOMElement *)elementForView:(NSView *)view
889 {
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];
894         if (widget != nil) {
895             NodeImpl *node = static_cast<const RenderWidget *>(widget->eventFilterObject())->element();
896             return [DOMElement _elementWithImpl:static_cast<ElementImpl *>(node)];
897         }
898     }
899     return nil;
900 }
901
902 static NSView *viewForElement(ElementImpl *elementImpl)
903 {
904     RenderObject *renderer = elementImpl->renderer();
905     if (renderer && renderer->isWidget()) {
906         QWidget *widget = static_cast<const RenderWidget *>(renderer)->widget();
907         if (widget) {
908             widget->populate();
909             return widget->getView();
910         }
911     }
912     return nil;
913 }
914
915 static HTMLInputElementImpl *inputElementFromDOMElement(DOMElement *element)
916 {
917     NodeImpl *node = [element _nodeImpl];
918     if (node && idFromNode(node) == ID_INPUT) {
919         return static_cast<HTMLInputElementImpl *>(node);
920     }
921     return nil;
922 }
923
924 static HTMLFormElementImpl *formElementFromDOMElement(DOMElement *element)
925 {
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);
933     }
934     return nil;
935 }
936
937 - (DOMElement *)elementWithName:(NSString *)name inForm:(DOMElement *)form
938 {
939     HTMLFormElementImpl *formElement = formElementFromDOMElement(form);
940     if (formElement) {
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];
948             }
949         }
950     }
951     return nil;
952 }
953
954 - (BOOL)elementDoesAutoComplete:(DOMElement *)element
955 {
956     HTMLInputElementImpl *inputElement = inputElementFromDOMElement(element);
957     return inputElement != nil
958         && inputElement->inputType() == HTMLInputElementImpl::TEXT
959         && inputElement->autoComplete();
960 }
961
962 - (BOOL)elementIsPassword:(DOMElement *)element
963 {
964     HTMLInputElementImpl *inputElement = inputElementFromDOMElement(element);
965     return inputElement != nil
966         && inputElement->inputType() == HTMLInputElementImpl::PASSWORD;
967 }
968
969 - (DOMElement *)formForElement:(DOMElement *)element;
970 {
971     HTMLInputElementImpl *inputElement = inputElementFromDOMElement(element);
972     if (inputElement) {
973         HTMLFormElementImpl *formElement = inputElement->form();
974         if (formElement) {
975             return [DOMElement _elementWithImpl:formElement];
976         }
977     }
978     return nil;
979 }
980
981 - (DOMElement *)currentForm
982 {
983     HTMLFormElementImpl *formElement = _part->currentForm();
984     return formElement ? [DOMElement _elementWithImpl:formElement] : nil;
985 }
986
987 - (NSArray *)controlsInForm:(DOMElement *)form
988 {
989     NSMutableArray *results = nil;
990     HTMLFormElementImpl *formElement = formElementFromDOMElement(form);
991     if (formElement) {
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));
996                 if (view) {
997                     if (!results) {
998                         results = [NSMutableArray arrayWithObject:view];
999                     } else {
1000                         [results addObject:view];
1001                     }
1002                 }
1003             }
1004         }
1005     }
1006     return results;
1007 }
1008
1009 - (NSString *)searchForLabels:(NSArray *)labels beforeElement:(DOMElement *)element
1010 {
1011     return _part->searchForLabelsBeforeElement(labels, [element _elementImpl]);
1012 }
1013
1014 - (NSString *)matchLabels:(NSArray *)labels againstElement:(DOMElement *)element
1015 {
1016     return _part->matchLabelsAgainstElement(labels, [element _elementImpl]);
1017 }
1018
1019 - (NSDictionary *)elementAtPoint:(NSPoint)point
1020 {
1021     RenderObject *renderer = _part->renderer();
1022     if (!renderer) {
1023         return nil;
1024     }
1025     RenderObject::NodeInfo nodeInfo(true, true);
1026     renderer->layer()->hitTest(nodeInfo, (int)point.x, (int)point.y);
1027     
1028     NSMutableDictionary *element = [NSMutableDictionary dictionary];
1029     [element setObject:[NSNumber numberWithBool:_part->isPointInsideSelection((int)point.x, (int)point.y)]
1030                 forKey:WebCoreElementIsSelectedKey];
1031     
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];
1042                 break;
1043             }
1044         }
1045     }
1046
1047     NodeImpl *URLNode = nodeInfo.URLElement();
1048     if (URLNode) {
1049         ElementImpl *e = static_cast<ElementImpl *>(URLNode);
1050         DocumentImpl *doc = e->getDocument();
1051         ASSERT(doc);
1052         
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];
1058         }
1059         
1060         const AtomicString& link = e->getAttribute(ATTR_HREF);
1061         if (!link.isNull()) {
1062             if (e->firstChild()) {
1063                 Range r(doc);
1064                 r.setStartBefore(e->firstChild());
1065                 r.setEndAfter(e->lastChild());
1066                 QString t = _part->text(r);
1067                 if (!t.isEmpty()) {
1068                     [element setObject:t.getNSString() forKey:WebCoreElementLinkLabelKey];
1069                 }
1070             }
1071             QString URLString = parseURL(link).string();
1072             [element setObject:doc->completeURL(URLString).getNSString() forKey:WebCoreElementLinkURLKey];
1073         }
1074         
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();
1078         }
1079         if (!target.isEmpty()) {
1080             [element setObject:target.string().getNSString() forKey:WebCoreElementLinkTargetFrameKey];
1081         }
1082     }
1083
1084     NodeImpl *node = nodeInfo.innerNonSharedNode();
1085     if (node) {
1086         [element setObject:[DOMNode _nodeWithImpl:node] forKey:WebCoreElementDOMNodeKey];
1087     
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];
1094             }
1095                 
1096             int x, y;
1097             if (r->absolutePosition(x, y)) {
1098                 NSValue *rect = [NSValue valueWithRect:NSMakeRect(x, y, r->contentWidth(), r->contentHeight())];
1099                 [element setObject:rect forKey:WebCoreElementImageRectKey];
1100             }
1101                 
1102             ElementImpl *i = static_cast<ElementImpl*>(node);
1103     
1104             // FIXME: Code copied from RenderImage::updateFromElement; should share.
1105             DOMString attr;
1106             if (idFromNode(i) == ID_OBJECT) {
1107                 attr = i->getAttribute(ATTR_DATA);
1108             } else {
1109                 attr = i->getAttribute(ATTR_SRC);
1110             }
1111             if (!attr.isEmpty()) {
1112                 QString URLString = parseURL(attr).string();
1113                 [element setObject:i->getDocument()->completeURL(URLString).getNSString() forKey:WebCoreElementImageURLKey];
1114             }
1115             
1116             // FIXME: Code copied from RenderImage::updateFromElement; should share.
1117             DOMString alt;
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];
1126             }
1127         }
1128     }
1129     
1130     return element;
1131 }
1132
1133 - (NSURL *)URLWithAttributeString:(NSString *)string
1134 {
1135     DocumentImpl *doc = _part->xmlDocImpl();
1136     if (!doc) {
1137         return nil;
1138     }
1139     QString rel = parseURL(QString::fromNSString(string)).string();
1140     return KURL(doc->baseURL(), rel, doc->decoder() ? doc->decoder()->codec() : 0).getNSURL();
1141 }
1142
1143 - (BOOL)searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag
1144 {
1145     return _part->findString(string, forward, caseFlag, wrapFlag);
1146 }
1147
1148 - (void)jumpToSelection
1149 {
1150     _part->jumpToSelection();
1151 }
1152
1153 - (NSString *)advanceToNextMisspelling
1154 {
1155     return _part->advanceToNextMisspelling().getNSString();
1156 }
1157
1158 - (NSString *)advanceToNextMisspellingStartingJustBeforeSelection
1159 {
1160     return _part->advanceToNextMisspelling(true).getNSString();
1161 }
1162
1163 - (void)setTextSizeMultiplier:(float)multiplier
1164 {
1165     int newZoomFactor = (int)rint(multiplier * 100);
1166     if (_part->zoomFactor() == newZoomFactor) {
1167         return;
1168     }
1169     _part->setZoomFactor(newZoomFactor);
1170 }
1171
1172 - (CFStringEncoding)textEncoding
1173 {
1174     return KWQCFStringEncodingFromIANACharsetName(_part->encoding().latin1());
1175 }
1176
1177 - (NSView *)nextKeyView
1178 {
1179     DocumentImpl *doc = _part->xmlDocImpl();
1180     if (!doc) {
1181         return nil;
1182     }
1183     return _part->nextKeyView(doc->focusNode(), KWQSelectingNext);
1184 }
1185
1186 - (NSView *)previousKeyView
1187 {
1188     DocumentImpl *doc = _part->xmlDocImpl();
1189     if (!doc) {
1190         return nil;
1191     }
1192     return _part->nextKeyView(doc->focusNode(), KWQSelectingPrevious);
1193 }
1194
1195 - (NSView *)nextKeyViewInsideWebFrameViews
1196 {
1197     DocumentImpl *doc = _part->xmlDocImpl();
1198     if (!doc) {
1199         return nil;
1200     }
1201     
1202     return _part->nextKeyViewInFrameHierarchy(doc->focusNode(), KWQSelectingNext);
1203 }
1204
1205 - (NSView *)previousKeyViewInsideWebFrameViews
1206 {
1207     DocumentImpl *doc = _part->xmlDocImpl();
1208     if (!doc) {
1209         return nil;
1210     }
1211
1212     return _part->nextKeyViewInFrameHierarchy(doc->focusNode(), KWQSelectingPrevious);
1213 }
1214
1215 - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)string
1216 {
1217     return [self stringByEvaluatingJavaScriptFromString:string forceUserGesture:true];
1218 }
1219
1220 // 
1221 - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)string forceUserGesture:(BOOL)forceUserGesture
1222 {
1223     _part->createEmptyDocument();
1224     return _part->executeScript(QString::fromNSString(string), forceUserGesture).asString().getNSString();
1225 }
1226
1227 - (WebScriptObject *)windowScriptObject
1228 {
1229     return _part->windowScriptObject();
1230 }
1231
1232 - (NPObject *)windowScriptNPObject
1233 {
1234     return _part->windowScriptNPObject();
1235 }
1236
1237 - (DOMDocument *)DOMDocument
1238 {
1239     return [DOMDocument _documentWithImpl:_part->xmlDocImpl()];
1240 }
1241
1242 - (DOMHTMLElement *)frameElement
1243 {
1244     return (DOMHTMLElement *)[[self DOMDocument] _ownerElement];
1245 }
1246
1247 - (NSAttributedString *)selectedAttributedString
1248 {
1249     return _part->attributedString(_part->selectionStart(), _part->selectionStartOffset(), _part->selectionEnd(), _part->selectionEndOffset());
1250 }
1251
1252 - (NSAttributedString *)attributedStringFrom:(DOMNode *)start startOffset:(int)startOffset to:(DOMNode *)end endOffset:(int)endOffset
1253 {
1254     DOMNode *startNode = start;
1255     DOMNode *endNode = end;
1256     return _part->attributedString([startNode _nodeImpl], startOffset, [endNode _nodeImpl], endOffset);
1257 }
1258
1259 - (NSRect)selectionRect
1260 {
1261     return _part->selectionRect(); 
1262 }
1263
1264 - (NSRect)visibleSelectionRect
1265 {
1266     return _part->visibleSelectionRect(); 
1267 }
1268
1269 - (void)centerSelectionInVisibleArea
1270 {
1271     _part->centerSelectionInVisibleArea(); 
1272 }
1273
1274 - (NSRect)caretRectAtNode:(DOMNode *)node offset:(int)offset affinity:(NSSelectionAffinity)affinity
1275 {
1276     return [node _nodeImpl]->renderer()->caretRect(offset, static_cast<EAffinity>(affinity));
1277 }
1278 - (NSRect)firstRectForDOMRange:(DOMRange *)range
1279 {
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);
1283
1284     if (startCaretRect.y() == endCaretRect.y()) {
1285         // start and end are on the same line
1286         return QRect(MIN(startCaretRect.x(), endCaretRect.x()), 
1287                      startCaretRect.y(), 
1288                      abs(endCaretRect.x() - startCaretRect.x()),
1289                      MAX(startCaretRect.height(), endCaretRect.height()));
1290     }
1291
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(), 
1294                  startCaretRect.y(),
1295                  startCaretRect.width() + extraWidthToEndOfLine,
1296                  startCaretRect.height());
1297 }
1298
1299 - (NSImage *)selectionImage
1300 {
1301     return _part->selectionImage();
1302 }
1303
1304 - (void)setName:(NSString *)name
1305 {
1306     _part->KHTMLPart::setName(QString::fromNSString(name));
1307 }
1308
1309 - (NSString *)name
1310 {
1311     return _part->name().getNSString();
1312 }
1313
1314 - (NSURL *)URL
1315 {
1316     return _part->url().getNSURL();
1317 }
1318
1319 - (NSURL *)baseURL
1320 {
1321     return _part->completeURL(_part->xmlDocImpl()->baseURL()).getNSURL();
1322 }
1323
1324 - (NSString *)referrer
1325 {
1326     return _part->referrer().getNSString();
1327 }
1328
1329 - (NSString *)domain
1330 {
1331     DocumentImpl *doc = _part->xmlDocImpl();
1332     if (doc && doc->isHTMLDocument()) {
1333         return doc->domain().string().getNSString();
1334     }
1335     return nil;
1336 }
1337
1338 - (WebCoreBridge *)opener
1339 {
1340     KHTMLPart *openerPart = _part->opener();
1341
1342     if (openerPart)
1343         return KWQ(openerPart)->bridge();
1344
1345     return nil;
1346 }
1347
1348 + (NSString *)stringWithData:(NSData *)data textEncoding:(CFStringEncoding)textEncoding
1349 {
1350     if (textEncoding == kCFStringEncodingInvalidId || textEncoding == kCFStringEncodingISOLatin1) {
1351         textEncoding = kCFStringEncodingWindowsLatin1;
1352     }
1353     return QTextCodec(textEncoding).toUnicode((const char*)[data bytes], [data length]).getNSString();
1354 }
1355
1356 + (NSString *)stringWithData:(NSData *)data textEncodingName:(NSString *)textEncodingName
1357 {
1358     CFStringEncoding textEncoding = KWQCFStringEncodingFromIANACharsetName([textEncodingName lossyCString]);
1359     return [WebCoreBridge stringWithData:data textEncoding:textEncoding];
1360 }
1361
1362 - (BOOL)needsLayout
1363 {
1364     RenderObject *renderer = _part->renderer();
1365     return renderer ? renderer->needsLayout() : false;
1366 }
1367
1368 - (void)setNeedsLayout
1369 {
1370     RenderObject *renderer = _part->renderer();
1371     if (renderer)
1372         renderer->setNeedsLayout(true);
1373 }
1374
1375 - (BOOL)interceptKeyEvent:(NSEvent *)event toView:(NSView *)view
1376 {
1377     return _part->keyEvent(event);
1378 }
1379
1380 - (NSString *)renderTreeAsExternalRepresentation
1381 {
1382     return externalRepresentation(_part->renderer()).getNSString();
1383 }
1384
1385 - (void)setSelectionFromNone
1386 {
1387     _part->setSelectionFromNone();
1388 }
1389
1390 - (void)setDisplaysWithFocusAttributes:(BOOL)flag
1391 {
1392     _part->setDisplaysWithFocusAttributes(flag);
1393 }
1394
1395 - (void)setWindowHasFocus:(BOOL)flag
1396 {
1397     _part->setWindowHasFocus(flag);
1398 }
1399
1400 - (void)setShouldCreateRenderers:(BOOL)f
1401 {
1402     _shouldCreateRenderers = f;
1403 }
1404
1405 - (BOOL)shouldCreateRenderers
1406 {
1407     return _shouldCreateRenderers;
1408 }
1409
1410 - (int)numPendingOrLoadingRequests
1411 {
1412     DocumentImpl *doc = _part->xmlDocImpl();
1413     
1414     if (doc)
1415         return KWQNumberOfPendingOrLoadingRequests (doc->docLoader());
1416     return 0;
1417 }
1418
1419 - (BOOL)doneProcessingData
1420 {
1421     DocumentImpl *doc = _part->xmlDocImpl();
1422     if (doc) {
1423         Tokenizer* tok = doc->tokenizer();
1424         if (tok)
1425             return !tok->processingData();
1426     }
1427     return YES;
1428 }
1429
1430 - (NSColor *)bodyBackgroundColor
1431 {
1432     return _part->bodyBackgroundColor();
1433 }
1434
1435 - (NSColor *)selectionColor
1436 {
1437     RenderCanvas* root = static_cast<khtml::RenderCanvas *>(_part->xmlDocImpl()->renderer());
1438     if (root) {
1439         RenderStyle *pseudoStyle = root->getPseudoStyle(RenderStyle::SELECTION);
1440         if (pseudoStyle && pseudoStyle->backgroundColor().isValid()) {
1441             return pseudoStyle->backgroundColor().getNSColor();
1442         }
1443     }
1444     return _part->displaysWithFocusAttributes() ? [NSColor selectedTextBackgroundColor] : [NSColor secondarySelectedControlColor];
1445 }
1446
1447 - (void)adjustViewSize
1448 {
1449     KHTMLView *view = _part->view();
1450     if (view)
1451         view->adjustViewSize();
1452 }
1453
1454 -(id)accessibilityTree
1455 {
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);
1461 }
1462
1463 - (void)setDrawsBackground:(BOOL)drawsBackground
1464 {
1465     if (_part && _part->view())
1466         _part->view()->setTransparent(!drawsBackground);
1467 }
1468
1469 - (void)undoEditing:(id)arg
1470 {
1471     ASSERT([arg isKindOfClass:[KWQEditCommand class]]);
1472     [arg command]->unapply();
1473 }
1474
1475 - (void)redoEditing:(id)arg
1476 {
1477     ASSERT([arg isKindOfClass:[KWQEditCommand class]]);
1478     [arg command]->reapply();
1479 }
1480
1481 - (DOMRange *)rangeByExpandingSelectionWithGranularity:(WebSelectionGranularity)granularity
1482 {
1483     if (!partHasSelection(self))
1484         return nil;
1485         
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()];
1491 }
1492
1493 - (DOMRange *)rangeByAlteringCurrentSelection:(WebSelectionAlteration)alteration direction:(WebSelectionDirection)direction granularity:(WebSelectionGranularity)granularity
1494 {
1495     if (!partHasSelection(self))
1496         return nil;
1497         
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()];
1505 }
1506
1507 - (void)alterCurrentSelection:(WebSelectionAlteration)alteration direction:(WebSelectionDirection)direction granularity:(WebSelectionGranularity)granularity
1508 {
1509     if (!partHasSelection(self))
1510         return;
1511         
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));
1518
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();
1525             break;
1526         case WebSelectByCharacter:
1527         case WebSelectByWord:
1528         case WebSelectToLineBoundary:
1529         case WebSelectToParagraphBoundary:
1530         case WebSelectToDocumentBoundary:
1531             break;
1532     }
1533
1534     
1535     // setting the selection always clears saved vertical navigation x position
1536     _part->setSelection(selection);
1537     
1538     // restore vertical navigation x position if necessary
1539     if (xPos != KHTMLPart::NoXPosForVerticalArrowNavigation)
1540         _part->setXPosForVerticalArrowNavigation(xPos);
1541
1542     [self ensureSelectionVisible];
1543 }
1544
1545 - (DOMRange *)rangeByAlteringCurrentSelection:(WebSelectionAlteration)alteration verticalDistance:(float)verticalDistance
1546 {
1547     if (!partHasSelection(self))
1548         return nil;
1549         
1550     Selection selection(_part->selection());
1551     selection.modify(static_cast<Selection::EAlter>(alteration), static_cast<int>(verticalDistance));
1552     return [DOMRange _rangeWithImpl:selection.toRange().handle()];
1553 }
1554
1555 - (void)alterCurrentSelection:(WebSelectionAlteration)alteration verticalDistance:(float)verticalDistance
1556 {
1557     if (!partHasSelection(self))
1558         return;
1559         
1560     Selection selection(_part->selection());
1561     selection.modify(static_cast<Selection::EAlter>(alteration), static_cast<int>(verticalDistance));
1562
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);
1567
1568     [self ensureSelectionVisible];
1569 }
1570
1571 - (WebSelectionGranularity)selectionGranularity
1572 {
1573     // NOTE: The enums *must* match the very similar ones declared in dom_selection.h
1574     return static_cast<WebSelectionGranularity>(_part->selectionGranularity());
1575 }
1576
1577 - (void)setSelectedDOMRange:(DOMRange *)range affinity:(NSSelectionAffinity)selectionAffinity
1578 {
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());
1585     
1586     _part->xmlDocImpl()->updateLayout();
1587
1588     EAffinity affinity = static_cast<EAffinity>(selectionAffinity);
1589
1590     bool rangeCollapsed = [range collapsed];
1591     if (!rangeCollapsed)
1592         affinity = DOWNSTREAM;
1593     
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();
1600
1601     if (rangeCollapsed) {
1602         setAffinityUsingLinePosition(visibleStart);
1603         affinity = visibleStart.affinity();
1604     }
1605
1606     // FIXME: Can we provide extentAffinity?
1607     Selection selection(start, affinity, end, khtml::SEL_DEFAULT_AFFINITY);
1608     _part->setSelection(selection);
1609 }
1610
1611 - (DOMRange *)selectedDOMRange
1612 {
1613     return [DOMRange _rangeWithImpl:_part->selection().toRange().handle()];
1614 }
1615
1616 - (NSSelectionAffinity)selectionAffinity
1617 {
1618     return static_cast<NSSelectionAffinity>(_part->selection().startAffinity());
1619 }
1620
1621 - (void)setMarkDOMRange:(DOMRange *)range
1622 {
1623     _part->setMark(Selection([range _rangeImpl], khtml::SEL_DEFAULT_AFFINITY, khtml::SEL_DEFAULT_AFFINITY));
1624 }
1625
1626 - (DOMRange *)markDOMRange
1627 {
1628     return [DOMRange _rangeWithImpl:_part->mark().toRange().handle()];
1629 }
1630
1631 - (void)setMarkedTextDOMRange:(DOMRange *)range customAttributes:(NSArray *)attributes ranges:(NSArray *)ranges
1632 {
1633     _part->setMarkedTextRange([range _rangeImpl], attributes, ranges);
1634 }
1635
1636 - (DOMRange *)markedTextDOMRange
1637 {
1638     return [DOMRange _rangeWithImpl:_part->markedTextRange().handle()];
1639 }
1640
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
1645 {
1646     NodeImpl *startContainer = [[proposedRange startContainer] _nodeImpl];
1647     NodeImpl *endContainer = [[proposedRange endContainer] _nodeImpl];
1648     if (startContainer == nil || endContainer == nil)
1649         return nil;
1650
1651     ASSERT(startContainer->getDocument());
1652     ASSERT(startContainer->getDocument() == endContainer->getDocument());
1653     
1654     _part->xmlDocImpl()->updateLayout();
1655
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())
1660         newStart = start;
1661     Position newEnd = end.downstream(DOM::StayInBlock).trailingWhitespacePosition(khtml::DOWNSTREAM, true);
1662     if (newEnd.isNull())
1663         newEnd = end;
1664
1665     return [DOMRange _rangeWithImpl:Range(newStart.node(), newStart.offset(), newEnd.node(), newEnd.offset()).handle()];
1666 }
1667
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
1673 {
1674     // give back nil pointers in case of early returns
1675     if (beforeString)
1676         *beforeString = nil;
1677     if (afterString)
1678         *afterString = nil;
1679         
1680     // inspect destination
1681     NodeImpl *startContainer = [[rangeToReplace startContainer] _nodeImpl];
1682     NodeImpl *endContainer = [[rangeToReplace endContainer] _nodeImpl];
1683
1684     Position startPos(startContainer, [rangeToReplace startOffset]);
1685     Position endPos(endContainer, [rangeToReplace endOffset]);
1686
1687     VisiblePosition startVisiblePos = VisiblePosition(startPos, khtml::VP_DEFAULT_AFFINITY);
1688     VisiblePosition endVisiblePos = VisiblePosition(endPos, khtml::VP_DEFAULT_AFFINITY);
1689     
1690     // this check also ensures startContainer, startPos, endContainer, and endPos are non-null
1691     if (startVisiblePos.isNull() || endVisiblePos.isNull())
1692         return;
1693
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);
1699         }
1700     }
1701     
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);
1707         }
1708     }
1709     
1710     // inspect source
1711     bool hasWhitespaceAtStart = false;
1712     bool hasWhitespaceAtEnd = false;
1713     unsigned pasteLength = [pasteString length];
1714     if (pasteLength > 0) {
1715         NSCharacterSet *whiteSet = [NSCharacterSet whitespaceAndNewlineCharacterSet];
1716         
1717         if ([whiteSet characterIsMember:[pasteString characterAtIndex:0]]) {
1718             hasWhitespaceAtStart = YES;
1719         }
1720         if ([whiteSet characterIsMember:[pasteString characterAtIndex:(pasteLength - 1)]]) {
1721             hasWhitespaceAtEnd = YES;
1722         }
1723     }
1724     
1725     // issue the verdict
1726     if (beforeString && addLeadingSpace && !hasWhitespaceAtStart)
1727         *beforeString = @" ";
1728     if (afterString && addTrailingSpace && !hasWhitespaceAtEnd)
1729         *afterString = @" ";
1730 }
1731
1732 - (DOMDocumentFragment *)documentFragmentWithMarkupString:(NSString *)markupString baseURLString:(NSString *)baseURLString 
1733 {
1734     if (!_part || !_part->xmlDocImpl())
1735         return 0;
1736
1737     DocumentFragmentImpl *fragment = createFragmentFromMarkup(_part->xmlDocImpl(), QString::fromNSString(markupString), QString::fromNSString(baseURLString));
1738     return [DOMDocumentFragment _documentFragmentWithImpl:fragment];
1739 }
1740
1741 - (DOMDocumentFragment *)documentFragmentWithText:(NSString *)text
1742 {
1743     if (!partHasSelection(self) || !text)
1744         return 0;
1745     
1746     return [DOMDocumentFragment _documentFragmentWithImpl:createFragmentFromText(_part->xmlDocImpl(), QString::fromNSString(text))];
1747 }
1748
1749 - (void)replaceSelectionWithFragment:(DOMDocumentFragment *)fragment selectReplacement:(BOOL)selectReplacement smartReplace:(BOOL)smartReplace matchStyle:(BOOL)matchStyle
1750 {
1751     if (!partHasSelection(self) || !fragment)
1752         return;
1753     
1754     EditCommandPtr(new ReplaceSelectionCommand(_part->xmlDocImpl(), [fragment _fragmentImpl], selectReplacement, smartReplace, matchStyle)).apply();
1755     [self ensureSelectionVisible];
1756 }
1757
1758 - (void)replaceSelectionWithNode:(DOMNode *)node selectReplacement:(BOOL)selectReplacement smartReplace:(BOOL)smartReplace
1759 {
1760     DOMDocumentFragment *fragment = [[self DOMDocument] createDocumentFragment];
1761     [fragment appendChild:node];
1762     [self replaceSelectionWithFragment:fragment selectReplacement:selectReplacement smartReplace:smartReplace matchStyle:NO];
1763 }
1764
1765 - (void)replaceSelectionWithMarkupString:(NSString *)markupString baseURLString:(NSString *)baseURLString selectReplacement:(BOOL)selectReplacement smartReplace:(BOOL)smartReplace
1766 {
1767     DOMDocumentFragment *fragment = [self documentFragmentWithMarkupString:markupString baseURLString:baseURLString];
1768     [self replaceSelectionWithFragment:fragment selectReplacement:selectReplacement smartReplace:smartReplace matchStyle:NO];
1769 }
1770
1771 - (void)replaceSelectionWithText:(NSString *)text selectReplacement:(BOOL)selectReplacement smartReplace:(BOOL)smartReplace
1772 {
1773     [self replaceSelectionWithFragment:[self documentFragmentWithText:text] selectReplacement:selectReplacement smartReplace:smartReplace matchStyle:YES];
1774 }
1775
1776 - (void)insertLineBreak
1777 {
1778     if (!partHasSelection(self))
1779         return;
1780     
1781     TypingCommand::insertLineBreak(_part->xmlDocImpl());
1782     [self ensureSelectionVisible];
1783 }
1784
1785 - (void)insertParagraphSeparator
1786 {
1787     if (!partHasSelection(self))
1788         return;
1789     
1790     TypingCommand::insertParagraphSeparator(_part->xmlDocImpl());
1791     [self ensureSelectionVisible];
1792 }
1793
1794 - (void)insertParagraphSeparatorInQuotedContent
1795 {
1796     if (!partHasSelection(self))
1797         return;
1798     
1799     TypingCommand::insertParagraphSeparatorInQuotedContent(_part->xmlDocImpl());
1800     [self ensureSelectionVisible];
1801 }
1802
1803 - (void)insertText:(NSString *)text selectInsertedText:(BOOL)selectInsertedText
1804 {
1805     if (!partHasSelection(self))
1806         return;
1807     
1808     TypingCommand::insertText(_part->xmlDocImpl(), text, selectInsertedText);
1809     [self ensureSelectionVisible];
1810 }
1811
1812 - (void)setSelectionToDragCaret
1813 {
1814     _part->setSelection(_part->dragCaret());
1815 }
1816
1817 - (void)moveSelectionToDragCaret:(DOMDocumentFragment *)selectionFragment smartMove:(BOOL)smartMove
1818 {
1819     Position base = _part->dragCaret().base();
1820     EditCommandPtr(new MoveSelectionCommand(_part->xmlDocImpl(), [selectionFragment _fragmentImpl], base, smartMove)).apply();
1821 }
1822
1823 - (VisiblePosition)_visiblePositionForPoint:(NSPoint)point
1824 {
1825     RenderObject *renderer = _part->renderer();
1826     if (!renderer) {
1827         return VisiblePosition();
1828     }
1829     
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();
1835     
1836     return node->renderer()->positionForCoordinates((int)point.x, (int)point.y);
1837 }
1838
1839 - (void)moveDragCaretToPoint:(NSPoint)point
1840 {   
1841     Selection dragCaret([self _visiblePositionForPoint:point]);
1842     _part->setDragCaret(dragCaret);
1843 }
1844
1845 - (void)removeDragCaret
1846 {
1847     _part->setDragCaret(Selection());
1848 }
1849
1850 - (DOMRange *)dragCaretDOMRange
1851 {
1852     return [DOMRange _rangeWithImpl:_part->dragCaret().toRange().handle()];
1853 }
1854
1855 - (DOMRange *)editableDOMRangeForPoint:(NSPoint)point
1856 {
1857     VisiblePosition position = [self _visiblePositionForPoint:point];
1858     return position.isNull() ? nil : [DOMRange _rangeWithImpl:Selection(position).toRange().handle()];
1859 }
1860
1861 - (void)deleteSelectionWithSmartDelete:(BOOL)smartDelete
1862 {
1863     if (!partHasSelection(self))
1864         return;
1865     
1866     EditCommandPtr(new DeleteSelectionCommand(_part->xmlDocImpl(), smartDelete)).apply();
1867 }
1868
1869 - (void)deleteKeyPressedWithSmartDelete:(BOOL)smartDelete
1870 {
1871     if (!_part || !_part->xmlDocImpl())
1872         return;
1873     
1874     TypingCommand::deleteKeyPressed(_part->xmlDocImpl(), smartDelete);
1875     [self ensureSelectionVisible];
1876 }
1877
1878 - (void)forwardDeleteKeyPressedWithSmartDelete:(BOOL)smartDelete
1879 {
1880     if (!_part || !_part->xmlDocImpl())
1881         return;
1882     
1883     TypingCommand::forwardDeleteKeyPressed(_part->xmlDocImpl(), smartDelete);
1884     [self ensureSelectionVisible];
1885 }
1886
1887 - (DOMCSSStyleDeclaration *)typingStyle
1888 {
1889     if (!_part || !_part->typingStyle())
1890         return nil;
1891     return [DOMCSSStyleDeclaration _styleDeclarationWithImpl:_part->typingStyle()];
1892 }
1893
1894 - (void)setTypingStyle:(DOMCSSStyleDeclaration *)style withUndoAction:(WebUndoAction)undoAction
1895 {
1896     if (!_part)
1897         return;
1898     _part->computeAndSetTypingStyle([style _styleDeclarationImpl], static_cast<EditAction>(undoAction));
1899 }
1900
1901 - (void)applyStyle:(DOMCSSStyleDeclaration *)style withUndoAction:(WebUndoAction)undoAction
1902 {
1903     if (!_part)
1904         return;
1905     _part->applyStyle([style _styleDeclarationImpl], static_cast<EditAction>(undoAction));
1906 }
1907
1908 - (void)applyParagraphStyle:(DOMCSSStyleDeclaration *)style withUndoAction:(WebUndoAction)undoAction
1909 {
1910     if (!_part)
1911         return;
1912     _part->applyParagraphStyle([style _styleDeclarationImpl], static_cast<EditAction>(undoAction));
1913 }
1914
1915 - (BOOL)selectionStartHasStyle:(DOMCSSStyleDeclaration *)style
1916 {
1917     if (!_part)
1918         return NO;
1919     return _part->selectionStartHasStyle([style _styleDeclarationImpl]);
1920 }
1921
1922 - (NSCellStateValue)selectionHasStyle:(DOMCSSStyleDeclaration *)style
1923 {
1924     if (!_part)
1925         return NSOffState;
1926     switch (_part->selectionHasStyle([style _styleDeclarationImpl])) {
1927         case KHTMLPart::falseTriState:
1928             return NSOffState;
1929         case KHTMLPart::trueTriState:
1930             return NSOnState;
1931         case KHTMLPart::mixedTriState:
1932             return NSMixedState;
1933     }
1934     return NSOffState;
1935 }
1936
1937 - (void)applyEditingStyleToBodyElement
1938 {
1939     if (!_part)
1940         return;
1941     _part->applyEditingStyleToBodyElement();
1942 }
1943
1944 - (void)removeEditingStyleFromBodyElement
1945 {
1946     if (!_part)
1947         return;
1948     _part->removeEditingStyleFromBodyElement();
1949 }
1950
1951 - (void)applyEditingStyleToElement:(DOMElement *)element
1952 {
1953     if (!_part)
1954         return;
1955     _part->applyEditingStyleToElement([element _elementImpl]);
1956 }
1957
1958 - (void)removeEditingStyleFromElement:(DOMElement *)element
1959 {
1960     if (!_part)
1961         return;
1962     _part->removeEditingStyleFromElement([element _elementImpl]);
1963 }
1964
1965 - (NSFont *)fontForSelection:(BOOL *)hasMultipleFonts
1966 {
1967     bool multipleFonts = false;
1968     NSFont *font = nil;
1969     if (_part)
1970         font = _part->fontForSelection(hasMultipleFonts ? &multipleFonts : 0);
1971     if (hasMultipleFonts)
1972         *hasMultipleFonts = multipleFonts;
1973     return font;
1974 }
1975
1976 - (NSDictionary *)fontAttributesForSelectionStart
1977 {
1978     return _part ? _part->fontAttributesForSelectionStart() : nil;
1979 }
1980
1981 - (NSWritingDirection)baseWritingDirectionForSelectionStart
1982 {
1983     return _part ? _part->baseWritingDirectionForSelectionStart() : NSWritingDirectionLeftToRight;
1984 }
1985
1986 - (void)ensureSelectionVisible
1987 {
1988     if (!partHasSelection(self))
1989         return;
1990     
1991     KHTMLView *v = _part->view();
1992     if (!v)
1993         return;
1994
1995     Position extent = _part->selection().extent();
1996     if (extent.isNull())
1997         return;
1998     
1999     RenderObject *renderer = extent.node()->renderer();
2000     if (!renderer)
2001         return;
2002     
2003     NSView *documentView = v->getDocumentView();
2004     if (!documentView)
2005         return;
2006     
2007     QRect extentRect = renderer->caretRect(extent.offset(), _part->selection().extentAffinity());
2008     if (!NSContainsRect([documentView visibleRect], NSRect(extentRect))) {
2009         v->ensureRectVisibleCentered(extentRect, true);
2010     }
2011 }
2012
2013 // [info draggingLocation] is in window coords
2014
2015 - (BOOL)eventMayStartDrag:(NSEvent *)event
2016 {
2017     return _part ? _part->eventMayStartDrag(event) : NO;
2018 }
2019
2020 - (NSDragOperation)dragOperationForDraggingInfo:(id <NSDraggingInfo>)info
2021 {
2022     NSDragOperation op = NSDragOperationNone;
2023     if (_part) {
2024         KHTMLView *v = _part->view();
2025         if (v) {
2026             // Sending an event can result in the destruction of the view and part.
2027             v->ref();
2028             
2029             KWQClipboard::AccessPolicy policy = _part->baseURL().isLocalFile() ? KWQClipboard::Readable : KWQClipboard::TypesReadable;
2030             KWQClipboard *clipboard = new KWQClipboard(true, [info draggingPasteboard], policy);
2031             clipboard->ref();
2032             NSDragOperation srcOp = [info draggingSourceOperationMask];
2033             clipboard->setSourceOperation(srcOp);
2034
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
2039                     // (as does WinIE).
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;
2046                     } else {
2047                         op = NSDragOperationGeneric;
2048                     }
2049                 } else if (!(op & srcOp)) {
2050                     // make sure WC picked an op that was offered.  Cocoa doesn't seem to enforce this,
2051                     // but IE does.
2052                     op = NSDragOperationNone;
2053                 }
2054             }
2055             clipboard->setAccessPolicy(KWQClipboard::Numb);    // invalidate clipboard here for security
2056
2057             clipboard->deref();
2058             v->deref();
2059             return op;
2060         }
2061     }
2062     return op;
2063 }
2064
2065 - (void)dragExitedWithDraggingInfo:(id <NSDraggingInfo>)info
2066 {
2067     if (_part) {
2068         KHTMLView *v = _part->view();
2069         if (v) {
2070             // Sending an event can result in the destruction of the view and part.
2071             v->ref();
2072
2073             KWQClipboard::AccessPolicy policy = _part->baseURL().isLocalFile() ? KWQClipboard::Readable : KWQClipboard::TypesReadable;
2074             KWQClipboard *clipboard = new KWQClipboard(true, [info draggingPasteboard], policy);
2075             clipboard->ref();
2076             clipboard->setSourceOperation([info draggingSourceOperationMask]);
2077             
2078             v->cancelDragAndDrop(QPoint([info draggingLocation]), clipboard);
2079             clipboard->setAccessPolicy(KWQClipboard::Numb);    // invalidate clipboard here for security
2080
2081             clipboard->deref();
2082             v->deref();
2083         }
2084     }
2085 }
2086
2087 - (BOOL)concludeDragForDraggingInfo:(id <NSDraggingInfo>)info
2088 {
2089     if (_part) {
2090         KHTMLView *v = _part->view();
2091         if (v) {
2092             // Sending an event can result in the destruction of the view and part.
2093             v->ref();
2094
2095             KWQClipboard *clipboard = new KWQClipboard(true, [info draggingPasteboard], KWQClipboard::Readable);
2096             clipboard->ref();
2097             clipboard->setSourceOperation([info draggingSourceOperationMask]);
2098
2099             BOOL result = v->performDragAndDrop(QPoint([info draggingLocation]), clipboard);
2100             clipboard->setAccessPolicy(KWQClipboard::Numb);    // invalidate clipboard here for security
2101
2102             clipboard->deref();
2103             v->deref();
2104
2105             return result;
2106         }
2107     }
2108     return NO;
2109 }
2110
2111 - (void)dragSourceMovedTo:(NSPoint)windowLoc
2112 {
2113     if (_part) {
2114         _part->dragSourceMovedTo(QPoint(windowLoc));
2115     }
2116 }
2117
2118 - (void)dragSourceEndedAt:(NSPoint)windowLoc operation:(NSDragOperation)operation
2119 {
2120     if (_part) {
2121         _part->dragSourceEndedAt(QPoint(windowLoc), operation);
2122     }
2123 }
2124
2125 - (BOOL)mayDHTMLCut
2126 {
2127     return _part->mayCut();
2128 }
2129
2130 - (BOOL)mayDHTMLCopy
2131 {
2132     return _part->mayCopy();
2133 }
2134
2135 - (BOOL)mayDHTMLPaste
2136 {
2137     return _part->mayPaste();
2138 }
2139
2140 - (BOOL)tryDHTMLCut
2141 {
2142     return _part->tryCut();
2143 }
2144
2145 - (BOOL)tryDHTMLCopy
2146 {
2147     return _part->tryCopy();
2148 }
2149
2150 - (BOOL)tryDHTMLPaste
2151 {
2152     return _part->tryPaste();
2153 }
2154
2155 - (DOMRange *)rangeOfCharactersAroundCaret
2156 {
2157     if (!_part)
2158         return nil;
2159         
2160     Selection selection(_part->selection());
2161     if (!selection.isCaret())
2162         return nil;
2163
2164     VisiblePosition caret(selection.start(), selection.startAffinity());
2165     VisiblePosition next = caret.next();
2166     VisiblePosition previous = caret.previous();
2167     if (caret == next || caret == previous)
2168         return nil;
2169
2170     return [DOMRange _rangeWithImpl:makeRange(previous, next).handle()];
2171 }
2172
2173 - (NSMutableDictionary *)dashboardRegions
2174 {
2175     return _part->dashboardRegionsDictionary();
2176 }
2177
2178 @end
2179
2180 @implementation WebCoreBridge (WebCoreBridgeInternal)
2181
2182 - (RootObject *)executionContextForView:(NSView *)aView
2183 {
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);
2189     return root;
2190 }
2191
2192 @end