AX: Webkit2 not sending UAZoomFocusChanged notifications
[WebKit-https.git] / Source / WebKit2 / UIProcess / API / mac / PageClientImpl.mm
1 /*
2  * Copyright (C) 2010 Apple 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 INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #import "config.h"
27 #import "PageClientImpl.h"
28
29 #import "DataReference.h"
30 #import "DictionaryPopupInfo.h"
31 #import "FindIndicator.h"
32 #import "NativeWebKeyboardEvent.h"
33 #import "WKAPICast.h"
34 #import "WKStringCF.h"
35 #import "WKViewInternal.h"
36 #import "WebContextMenuProxyMac.h"
37 #import "WebEditCommandProxy.h"
38 #import "WebPopupMenuProxyMac.h"
39 #import <WebCore/Cursor.h>
40 #import <WebCore/FloatRect.h>
41 #import <WebCore/FoundationExtras.h>
42 #import <WebCore/GraphicsContext.h>
43 #import <WebCore/KeyboardEvent.h>
44 #import <WebCore/NotImplemented.h>
45 #import <wtf/PassOwnPtr.h>
46 #import <wtf/text/CString.h>
47 #import <wtf/text/WTFString.h>
48
49 @interface NSApplication (WebNSApplicationDetails)
50 - (NSCursor *)_cursorRectCursor;
51 @end
52
53 using namespace WebCore;
54
55 @interface WebEditCommandObjC : NSObject
56 {
57     RefPtr<WebKit::WebEditCommandProxy> m_command;
58 }
59
60 - (id)initWithWebEditCommandProxy:(PassRefPtr<WebKit::WebEditCommandProxy>)command;
61 - (WebKit::WebEditCommandProxy*)command;
62
63 @end
64
65 @implementation WebEditCommandObjC
66
67 - (id)initWithWebEditCommandProxy:(PassRefPtr<WebKit::WebEditCommandProxy>)command
68 {
69     self = [super init];
70     if (!self)
71         return nil;
72
73     m_command = command;
74     return self;
75 }
76
77 - (WebKit::WebEditCommandProxy*)command
78 {
79     return m_command.get();
80 }
81
82 @end
83
84 @interface WebEditorUndoTargetObjC : NSObject
85
86 - (void)undoEditing:(id)sender;
87 - (void)redoEditing:(id)sender;
88
89 @end
90
91 @implementation WebEditorUndoTargetObjC
92
93 - (void)undoEditing:(id)sender
94 {
95     ASSERT([sender isKindOfClass:[WebEditCommandObjC class]]);
96     [sender command]->unapply();
97 }
98
99 - (void)redoEditing:(id)sender
100 {
101     ASSERT([sender isKindOfClass:[WebEditCommandObjC class]]);
102     [sender command]->reapply();
103 }
104
105 @end
106
107 namespace WebKit {
108
109 NSString* nsStringFromWebCoreString(const String& string)
110 {
111     return string.impl() ? HardAutorelease(WKStringCopyCFString(0, toAPI(string.impl()))) : @"";
112 }
113
114 PassOwnPtr<PageClientImpl> PageClientImpl::create(WKView* wkView)
115 {
116     return adoptPtr(new PageClientImpl(wkView));
117 }
118
119 PageClientImpl::PageClientImpl(WKView* wkView)
120     : m_wkView(wkView)
121     , m_undoTarget(AdoptNS, [[WebEditorUndoTargetObjC alloc] init])
122 {
123 }
124
125 PageClientImpl::~PageClientImpl()
126 {
127 }
128
129 PassOwnPtr<DrawingAreaProxy> PageClientImpl::createDrawingAreaProxy()
130 {
131     return [m_wkView _createDrawingAreaProxy];
132 }
133
134 void PageClientImpl::setViewNeedsDisplay(const WebCore::IntRect& rect)
135 {
136     [m_wkView setNeedsDisplayInRect:rect];
137 }
138
139 void PageClientImpl::displayView()
140 {
141     [m_wkView displayIfNeeded];
142 }
143
144 void PageClientImpl::scrollView(const IntRect& scrollRect, const IntSize& scrollOffset)
145 {
146     NSRect clippedScrollRect = NSIntersectionRect(scrollRect, NSOffsetRect(scrollRect, -scrollOffset.width(), -scrollOffset.height()));
147
148     [m_wkView translateRectsNeedingDisplayInRect:clippedScrollRect by:scrollOffset];
149     [m_wkView scrollRect:clippedScrollRect by:scrollOffset];
150 }
151
152 IntSize PageClientImpl::viewSize()
153 {
154     return IntSize([m_wkView bounds].size);
155 }
156
157 bool PageClientImpl::isViewWindowActive()
158 {
159     return [[m_wkView window] isKeyWindow];
160 }
161
162 bool PageClientImpl::isViewFocused()
163 {
164     return [m_wkView _isFocused];
165 }
166
167 bool PageClientImpl::isViewVisible()
168 {
169     if (![m_wkView window])
170         return false;
171
172     if ([m_wkView isHiddenOrHasHiddenAncestor])
173         return false;
174
175     return true;
176 }
177
178 bool PageClientImpl::isViewInWindow()
179 {
180     return [m_wkView window];
181 }
182
183 void PageClientImpl::processDidCrash()
184 {
185     [m_wkView _processDidCrash];
186 }
187     
188 void PageClientImpl::pageClosed()
189 {
190     [m_wkView _pageClosed];
191 }
192
193 void PageClientImpl::didRelaunchProcess()
194 {
195     [m_wkView _didRelaunchProcess];
196 }
197
198 void PageClientImpl::takeFocus(bool direction)
199 {
200     [m_wkView _takeFocus:direction];
201 }
202
203 void PageClientImpl::toolTipChanged(const String& oldToolTip, const String& newToolTip)
204 {
205     [m_wkView _toolTipChangedFrom:nsStringFromWebCoreString(oldToolTip) to:nsStringFromWebCoreString(newToolTip)];
206 }
207
208 void PageClientImpl::setCursor(const WebCore::Cursor& cursor)
209 {
210     if (![NSApp _cursorRectCursor])
211         [m_wkView _setCursor:cursor.platformCursor()];
212 }
213
214 void PageClientImpl::setViewportArguments(const WebCore::ViewportArguments&)
215 {
216
217 }
218
219 static NSString* nameForEditAction(EditAction editAction)
220 {
221     // FIXME: Use localized strings.
222     // FIXME: Move this to a platform independent location.
223
224     switch (editAction) {
225     case EditActionUnspecified: return nil;
226     case EditActionSetColor: return @"Set Color";
227     case EditActionSetBackgroundColor: return @"Set Background Color";
228     case EditActionTurnOffKerning: return @"Turn Off Kerning";
229     case EditActionTightenKerning: return @"Tighten Kerning";
230     case EditActionLoosenKerning: return @"Loosen Kerning";
231     case EditActionUseStandardKerning: return @"Use Standard Kerning";
232     case EditActionTurnOffLigatures: return @"Turn Off Ligatures";
233     case EditActionUseStandardLigatures: return @"Use Standard Ligatures";
234     case EditActionUseAllLigatures: return @"Use All Ligatures";
235     case EditActionRaiseBaseline: return @"Raise Baseline";
236     case EditActionLowerBaseline: return @"Lower Baseline";
237     case EditActionSetTraditionalCharacterShape: return @"Set Traditional Character Shape";
238     case EditActionSetFont: return @"Set Font";
239     case EditActionChangeAttributes: return @"Change Attributes";
240     case EditActionAlignLeft: return @"Align Left";
241     case EditActionAlignRight: return @"Align Right";
242     case EditActionCenter: return @"Center";
243     case EditActionJustify: return @"Justify";
244     case EditActionSetWritingDirection: return @"Set Writing Direction";
245     case EditActionSubscript: return @"Subscript";
246     case EditActionSuperscript: return @"Superscript";
247     case EditActionUnderline: return @"Underline";
248     case EditActionOutline: return @"Outline";
249     case EditActionUnscript: return @"Unscript";
250     case EditActionDrag: return @"Drag";
251     case EditActionCut: return @"Cut";
252     case EditActionPaste: return @"Paste";
253     case EditActionPasteFont: return @"Paste Font";
254     case EditActionPasteRuler: return @"Paste Ruler";
255     case EditActionTyping: return @"Typing";
256     case EditActionCreateLink: return @"Create Link";
257     case EditActionUnlink: return @"Unlink";
258     case EditActionInsertList: return @"Insert List";
259     case EditActionFormatBlock: return @"Formatting";
260     case EditActionIndent: return @"Indent";
261     case EditActionOutdent: return @"Outdent";
262     }
263     return nil;
264 }
265
266 void PageClientImpl::registerEditCommand(PassRefPtr<WebEditCommandProxy> prpCommand, WebPageProxy::UndoOrRedo undoOrRedo)
267 {
268     RefPtr<WebEditCommandProxy> command = prpCommand;
269
270     RetainPtr<WebEditCommandObjC> commandObjC(AdoptNS, [[WebEditCommandObjC alloc] initWithWebEditCommandProxy:command]);
271     NSString *actionName = nameForEditAction(command->editAction());
272
273     NSUndoManager *undoManager = [m_wkView undoManager];
274     [undoManager registerUndoWithTarget:m_undoTarget.get() selector:((undoOrRedo == WebPageProxy::Undo) ? @selector(undoEditing:) : @selector(redoEditing:)) object:commandObjC.get()];
275     if (actionName)
276         [undoManager setActionName:actionName];
277 }
278
279 void PageClientImpl::clearAllEditCommands()
280 {
281     [[m_wkView undoManager] removeAllActionsWithTarget:m_undoTarget.get()];
282 }
283
284 void PageClientImpl::interceptKeyEvent(const NativeWebKeyboardEvent& event, Vector<WebCore::KeypressCommand>& commandsList, uint32_t selectionStart, uint32_t selectionEnd, Vector<WebCore::CompositionUnderline>& underlines)
285 {
286     commandsList = [m_wkView _interceptKeyEvent:event.nativeEvent()];
287     [m_wkView _getTextInputState:selectionStart selectionEnd:selectionEnd underlines:underlines];
288 }
289
290 void PageClientImpl::setDragImage(const IntPoint& clientPosition, const IntSize& imageSize, PassRefPtr<ShareableBitmap> dragImage, bool isLinkDrag)
291 {
292     OwnPtr<GraphicsContext> graphicsContext = dragImage->createGraphicsContext();
293     RetainPtr<NSImage> dragNSImage(AdoptNS, [[NSImage alloc] initWithCGImage:CGBitmapContextCreateImage(graphicsContext->platformContext()) size:imageSize]);
294     [m_wkView _setDragImage:dragNSImage.get() at:clientPosition linkDrag:isLinkDrag];
295 }
296     
297 FloatRect PageClientImpl::convertToDeviceSpace(const FloatRect& rect)
298 {
299     return [m_wkView _convertToDeviceSpace:rect];
300 }
301
302 FloatRect PageClientImpl::convertToUserSpace(const FloatRect& rect)
303 {
304     return [m_wkView _convertToUserSpace:rect];
305 }
306     
307 IntRect PageClientImpl::windowToScreen(const IntRect& rect)
308 {
309     NSRect tempRect = rect;
310     tempRect = [m_wkView convertRect:tempRect toView:nil];
311     tempRect.origin = [[m_wkView window] convertBaseToScreen:tempRect.origin];
312     return enclosingIntRect(tempRect);
313 }
314
315 void PageClientImpl::doneWithKeyEvent(const NativeWebKeyboardEvent& event, bool wasEventHandled)
316 {
317     NSEvent* nativeEvent = event.nativeEvent();
318     if ([nativeEvent type] != NSKeyDown)
319         return;
320     if (wasEventHandled)
321         [NSCursor setHiddenUntilMouseMoves:YES];
322     else {
323         [m_wkView _setEventBeingResent:nativeEvent];
324         [[NSApplication sharedApplication] sendEvent:nativeEvent];
325     }
326 }
327
328 PassRefPtr<WebPopupMenuProxy> PageClientImpl::createPopupMenuProxy(WebPageProxy* page)
329 {
330     return WebPopupMenuProxyMac::create(m_wkView, page);
331 }
332
333 PassRefPtr<WebContextMenuProxy> PageClientImpl::createContextMenuProxy(WebPageProxy* page)
334 {
335     return WebContextMenuProxyMac::create(m_wkView, page);
336 }
337
338 void PageClientImpl::setFindIndicator(PassRefPtr<FindIndicator> findIndicator, bool fadeOut)
339 {
340     [m_wkView _setFindIndicator:findIndicator fadeOut:fadeOut];
341 }
342
343 void PageClientImpl::accessibilityWebProcessTokenReceived(const CoreIPC::DataReference& data)
344 {
345     NSData* remoteToken = [NSData dataWithBytes:data.data() length:data.size()];
346     [m_wkView _setAccessibilityWebProcessToken:remoteToken];
347 }
348     
349 #if USE(ACCELERATED_COMPOSITING)
350 void PageClientImpl::enterAcceleratedCompositingMode(const LayerTreeContext& layerTreeContext)
351 {
352     [m_wkView _enterAcceleratedCompositingMode:layerTreeContext];
353 }
354
355 void PageClientImpl::exitAcceleratedCompositingMode()
356 {
357     [m_wkView _exitAcceleratedCompositingMode];
358 }
359 #endif // USE(ACCELERATED_COMPOSITING)
360
361 void PageClientImpl::setComplexTextInputEnabled(uint64_t pluginComplexTextInputIdentifier, bool complexTextInputEnabled)
362 {
363     [m_wkView _setComplexTextInputEnabled:complexTextInputEnabled pluginComplexTextInputIdentifier:pluginComplexTextInputIdentifier];
364 }
365
366 void PageClientImpl::setAutodisplay(bool newState)
367 {
368     if (!newState && [[m_wkView window] isAutodisplay])
369         [m_wkView displayIfNeeded];
370     
371     [[m_wkView window] setAutodisplay:newState];
372
373     // For some reason, painting doesn't happen for a long time without this call, <rdar://problem/8975229>.
374     if (newState)
375         [m_wkView displayIfNeeded];
376 }
377
378 CGContextRef PageClientImpl::containingWindowGraphicsContext()
379 {
380     NSWindow *window = [m_wkView window];
381
382     // Don't try to get the graphics context if the NSWindow doesn't have a window device.
383     if ([window windowNumber] <= 0)
384         return 0;
385
386     return static_cast<CGContextRef>([[window graphicsContext] graphicsPort]);
387 }
388
389 void PageClientImpl::didChangeScrollbarsForMainFrame() const
390 {
391     [m_wkView _didChangeScrollbarsForMainFrame];
392 }
393
394 void PageClientImpl::didCommitLoadForMainFrame(bool useCustomRepresentation)
395 {
396     [m_wkView _setPageHasCustomRepresentation:useCustomRepresentation];
397 }
398
399 void PageClientImpl::didFinishLoadingDataForCustomRepresentation(const String& suggestedFilename, const CoreIPC::DataReference& dataReference)
400 {
401     [m_wkView _didFinishLoadingDataForCustomRepresentationWithSuggestedFilename:suggestedFilename dataReference:dataReference];
402 }
403
404 double PageClientImpl::customRepresentationZoomFactor()
405 {
406     return [m_wkView _customRepresentationZoomFactor];
407 }
408
409 void PageClientImpl::setCustomRepresentationZoomFactor(double zoomFactor)
410 {
411     [m_wkView _setCustomRepresentationZoomFactor:zoomFactor];
412 }
413
414 void PageClientImpl::flashBackingStoreUpdates(const Vector<IntRect>&)
415 {
416     notImplemented();
417 }
418
419 void PageClientImpl::didPerformDictionaryLookup(const String& text, double scaleFactor, const DictionaryPopupInfo& dictionaryPopupInfo)
420 {
421     NSFontDescriptor *fontDescriptor = [NSFontDescriptor fontDescriptorWithFontAttributes:(NSDictionary *)dictionaryPopupInfo.fontInfo.fontAttributeDictionary.get()];
422     NSFont *font = [NSFont fontWithDescriptor:fontDescriptor size:((scaleFactor != 1) ? [fontDescriptor pointSize] * scaleFactor : 0)];
423
424     RetainPtr<NSMutableAttributedString> attributedString(AdoptNS, [[NSMutableAttributedString alloc] initWithString:nsStringFromWebCoreString(text)]);
425     [attributedString.get() addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [attributedString.get() length])];
426
427     NSPoint textBaselineOrigin = dictionaryPopupInfo.origin;
428     textBaselineOrigin.y += [font ascender];
429     
430     // If the dictionary lookup is being triggered by a hot key, force the overlay style.
431     NSDictionary *options = (dictionaryPopupInfo.type == DictionaryPopupInfo::HotKey) ? [NSDictionary dictionaryWithObject:NSDefinitionPresentationTypeOverlay forKey:NSDefinitionPresentationTypeKey] : 0;
432     [m_wkView showDefinitionForAttributedString:attributedString.get() range:NSMakeRange(0, [attributedString.get() length]) options:options baselineOriginProvider:^(NSRange adjustedRange) { return (NSPoint)textBaselineOrigin; }];
433 }
434
435 } // namespace WebKit