Add preliminary (SPI) support for NSTextFinder on WKWebView
authortimothy_horton@apple.com <timothy_horton@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Fri, 6 Nov 2015 19:48:27 +0000 (19:48 +0000)
committertimothy_horton@apple.com <timothy_horton@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Fri, 6 Nov 2015 19:48:27 +0000 (19:48 +0000)
https://bugs.webkit.org/show_bug.cgi?id=150907
<rdar://problem/19171624>

Reviewed by Darin Adler.

New API test: WebKit2.FindInPage

* Platform/spi/mac/AppKitSPI.h:
Add some SPI.

* UIProcess/API/APIFindClient.h:
(API::FindClient::didFindString):
* UIProcess/API/C/WKPage.cpp:
(WKPageSetPageFindClient):
* UIProcess/WebPageProxy.cpp:
(WebKit::WebPageProxy::didFindString):
* UIProcess/WebPageProxy.h:
* UIProcess/WebPageProxy.messages.in:
* UIProcess/Cocoa/FindClient.h:
* UIProcess/Cocoa/FindClient.mm:
(WebKit::FindClient::didFindString):
Make didFindString return the match rects like didFindStringMatches does.

* WebProcess/WebPage/FindController.cpp:
(WebKit::FindController::updateFindUIAfterPageScroll):
(WebKit::FindController::findString):
Keep the most recent find match around for incremental find just like we do
for the non-incremental version. This way, getImageForFindMatch and selectFindMatch
will work for incremental find too!

* UIProcess/API/Cocoa/WKWebView.mm:
(-[WKWebView _ensureTextFinderClient]):
(-[WKWebView findMatchesForString:relativeToMatch:findOptions:maxResults:resultCollector:]):
(-[WKWebView documentContainerView]):
(-[WKWebView getSelectedText:]):
(-[WKWebView selectFindMatch:completionHandler:]):
Implement NSTextFinder's async client protocol and forward to the new WKTextFinderClient.

* UIProcess/API/Cocoa/WKWebViewPrivate.h:
Privately note our conformance to the aformentioned protocol.

* UIProcess/mac/WKTextFinderClient.h: Added.
* UIProcess/mac/WKTextFinderClient.mm: Added.
(WebKit::TextFinderFindClient::TextFinderFindClient):
(-[WKTextFinderMatch initWithClient:view:index:rects:]):
(-[WKTextFinderMatch containingView]):
(-[WKTextFinderMatch textRects]):
(-[WKTextFinderMatch generateTextImage:]):
(-[WKTextFinderMatch index]):
(-[WKTextFinderClient initWithPage:view:]):
(-[WKTextFinderClient willDestroyView:]):
(-[WKTextFinderClient findMatchesForString:relativeToMatch:findOptions:maxResults:resultCollector:]):
(-[WKTextFinderClient getSelectedText:]):
(-[WKTextFinderClient selectFindMatch:completionHandler:]):
(-[WKTextFinderClient didFindStringMatches:rects:index:]):
(-[WKTextFinderClient didGetImageForMatchResult:index:]):
(-[WKTextFinderClient didFindString:rects:index:]):
(-[WKTextFinderClient didFailToFindString:]):
(-[WKTextFinderClient getImageForMatchResult:completionHandler:]):
* WebKit2.xcodeproj/project.pbxproj:
Add WKTextFinderClient. It installs itself as the FindClient and FindMatchesClient,
so you can only use one mechanism or the other.

* TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj:
* TestWebKitAPI/Tests/WebKit2Cocoa/FindInPage.mm: Added.
(-[FindInPageNavigationDelegate webView:didFinishNavigation:]):
(TEST):
Add an API test.

* WebEditingTester/WK1WebDocumentController.m:
* WebEditingTester/WK2WebDocumentController.m:
(-[WK2WebDocumentController awakeFromNib]):
(-[WK2WebDocumentController contentView]):
Use incremental find, and show the overlay/indicator.

git-svn-id: https://svn.webkit.org/repository/webkit/trunk@192113 268f45cc-cd09-0410-ab3c-d52691b4dbfc

21 files changed:
Source/WebKit2/ChangeLog
Source/WebKit2/Platform/spi/mac/AppKitSPI.h
Source/WebKit2/UIProcess/API/APIFindClient.h
Source/WebKit2/UIProcess/API/C/WKPage.cpp
Source/WebKit2/UIProcess/API/Cocoa/WKWebView.mm
Source/WebKit2/UIProcess/API/Cocoa/WKWebViewPrivate.h
Source/WebKit2/UIProcess/Cocoa/FindClient.h
Source/WebKit2/UIProcess/Cocoa/FindClient.mm
Source/WebKit2/UIProcess/WebPageProxy.cpp
Source/WebKit2/UIProcess/WebPageProxy.h
Source/WebKit2/UIProcess/WebPageProxy.messages.in
Source/WebKit2/UIProcess/ios/WKPDFView.mm
Source/WebKit2/UIProcess/mac/WKTextFinderClient.h [new file with mode: 0644]
Source/WebKit2/UIProcess/mac/WKTextFinderClient.mm [new file with mode: 0644]
Source/WebKit2/WebKit2.xcodeproj/project.pbxproj
Source/WebKit2/WebProcess/WebPage/FindController.cpp
Tools/ChangeLog
Tools/TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj
Tools/TestWebKitAPI/Tests/WebKit2Cocoa/FindInPage.mm [new file with mode: 0644]
Tools/WebEditingTester/WK1WebDocumentController.m
Tools/WebEditingTester/WK2WebDocumentController.m

index 2dfd74e..efca9ed 100644 (file)
@@ -1,3 +1,69 @@
+2015-11-06  Tim Horton  <timothy_horton@apple.com>
+
+        Add preliminary (SPI) support for NSTextFinder on WKWebView
+        https://bugs.webkit.org/show_bug.cgi?id=150907
+        <rdar://problem/19171624>
+
+        Reviewed by Darin Adler.
+
+        New API test: WebKit2.FindInPage
+
+        * Platform/spi/mac/AppKitSPI.h:
+        Add some SPI.
+
+        * UIProcess/API/APIFindClient.h:
+        (API::FindClient::didFindString):
+        * UIProcess/API/C/WKPage.cpp:
+        (WKPageSetPageFindClient):
+        * UIProcess/WebPageProxy.cpp:
+        (WebKit::WebPageProxy::didFindString):
+        * UIProcess/WebPageProxy.h:
+        * UIProcess/WebPageProxy.messages.in:
+        * UIProcess/Cocoa/FindClient.h:
+        * UIProcess/Cocoa/FindClient.mm:
+        (WebKit::FindClient::didFindString):
+        Make didFindString return the match rects like didFindStringMatches does.
+
+        * WebProcess/WebPage/FindController.cpp:
+        (WebKit::FindController::updateFindUIAfterPageScroll):
+        (WebKit::FindController::findString):
+        Keep the most recent find match around for incremental find just like we do
+        for the non-incremental version. This way, getImageForFindMatch and selectFindMatch
+        will work for incremental find too!
+
+        * UIProcess/API/Cocoa/WKWebView.mm:
+        (-[WKWebView _ensureTextFinderClient]):
+        (-[WKWebView findMatchesForString:relativeToMatch:findOptions:maxResults:resultCollector:]):
+        (-[WKWebView documentContainerView]):
+        (-[WKWebView getSelectedText:]):
+        (-[WKWebView selectFindMatch:completionHandler:]):
+        Implement NSTextFinder's async client protocol and forward to the new WKTextFinderClient.
+
+        * UIProcess/API/Cocoa/WKWebViewPrivate.h:
+        Privately note our conformance to the aformentioned protocol.
+
+        * UIProcess/mac/WKTextFinderClient.h: Added.
+        * UIProcess/mac/WKTextFinderClient.mm: Added.
+        (WebKit::TextFinderFindClient::TextFinderFindClient):
+        (-[WKTextFinderMatch initWithClient:view:index:rects:]):
+        (-[WKTextFinderMatch containingView]):
+        (-[WKTextFinderMatch textRects]):
+        (-[WKTextFinderMatch generateTextImage:]):
+        (-[WKTextFinderMatch index]):
+        (-[WKTextFinderClient initWithPage:view:]):
+        (-[WKTextFinderClient willDestroyView:]):
+        (-[WKTextFinderClient findMatchesForString:relativeToMatch:findOptions:maxResults:resultCollector:]):
+        (-[WKTextFinderClient getSelectedText:]):
+        (-[WKTextFinderClient selectFindMatch:completionHandler:]):
+        (-[WKTextFinderClient didFindStringMatches:rects:index:]):
+        (-[WKTextFinderClient didGetImageForMatchResult:index:]):
+        (-[WKTextFinderClient didFindString:rects:index:]):
+        (-[WKTextFinderClient didFailToFindString:]):
+        (-[WKTextFinderClient getImageForMatchResult:completionHandler:]):
+        * WebKit2.xcodeproj/project.pbxproj:
+        Add WKTextFinderClient. It installs itself as the FindClient and FindMatchesClient,
+        so you can only use one mechanism or the other.
+
 2015-11-06  Chris Dumez  <cdumez@apple.com>
 
         [WK2][SpeculativeRevalidation] Save to disk cache relationship between resources
index a36f878..09507a3 100644 (file)
  * THE POSSIBILITY OF SUCH DAMAGE.
  */
 
+#if USE(APPKIT)
+
 #if USE(APPLE_INTERNAL_SDK)
 
 #import <AppKit/NSAccessibilityRemoteUIElement.h>
+#import <AppKit/NSTextFinder_Private.h>
 
 #else
 
 
 @end
 
+typedef enum : NSUInteger {
+    NSTextFinderAsynchronousDocumentFindOptionsBackwards = 1 << 0,
+    NSTextFinderAsynchronousDocumentFindOptionsWrap = 1 << 1,
+    NSTextFinderAsynchronousDocumentFindOptionsCaseInsensitive = 1 << 2,
+    NSTextFinderAsynchronousDocumentFindOptionsStartsWith = 1 << 3,
+} NSTextFinderAsynchronousDocumentFindOptions;
+
+@protocol NSTextFinderAsynchronousDocumentFindMatch <NSObject>
+@required
+@property (retain, nonatomic, readonly) NSView *containingView;
+@property (retain, nonatomic, readonly) NSArray *textRects;
+- (void)generateTextImage:(void (^)(NSImage *))completionHandler;
+@end
+
+@interface NSObject ()
+
+- (void)findMatchesForString:(NSString *)targetString relativeToMatch:(id <NSTextFinderAsynchronousDocumentFindMatch>)relativeMatch findOptions:(NSTextFinderAsynchronousDocumentFindOptions)findOptions maxResults:(NSUInteger)maxResults resultCollector:(void (^)(NSArray *matches, BOOL didWrap))resultCollector;
+- (NSView *)documentContainerView;
+- (void)getSelectedText:(void (^)(NSString *selectedTextString))completionHandler;
+- (void)selectFindMatch:(id <NSTextFinderAsynchronousDocumentFindMatch>)findMatch completionHandler:(void (^)(void))completionHandler;
+
+@end
+
 #endif // USE(APPLE_INTERNAL_SDK)
 
 @interface NSApplication ()
@@ -43,3 +69,5 @@
 - (void)_setCurrentEvent:(NSEvent *)event;
 
 @end
+
+#endif // PLATFORM(MAC)
index 00bdec9..0abf8f6 100644 (file)
 
 #include <wtf/text/WTFString.h>
 
+namespace WebCore {
+class IntRect;
+}
+
 namespace WebKit {
 class WebPageProxy;
 }
@@ -39,7 +43,7 @@ public:
     virtual ~FindClient() { }
 
     virtual void didCountStringMatches(WebKit::WebPageProxy*, const WTF::String&, uint32_t) { }
-    virtual void didFindString(WebKit::WebPageProxy*, const WTF::String&, uint32_t, int32_t) { }
+    virtual void didFindString(WebKit::WebPageProxy*, const WTF::String&, const Vector<WebCore::IntRect>& matchRects, uint32_t, int32_t) { }
     virtual void didFailToFindString(WebKit::WebPageProxy*, const WTF::String&) { }
 };
 
index ac57d3d..be7fc42 100644 (file)
@@ -887,7 +887,7 @@ void WKPageSetPageFindClient(WKPageRef pageRef, const WKPageFindClientBase* wkCl
         }
 
     private:
-        virtual void didFindString(WebPageProxy* page, const String& string, uint32_t matchCount, int32_t) override
+        virtual void didFindString(WebPageProxy* page, const String& string, const Vector<WebCore::IntRect>&, uint32_t matchCount, int32_t) override
         {
             if (!m_client.didFindString)
                 return;
index e0bab37..ce5bc7b 100644 (file)
@@ -31,6 +31,7 @@
 #import "APIFormClient.h"
 #import "APIPageConfiguration.h"
 #import "APISerializedScriptValue.h"
+#import "AppKitSPI.h"
 #import "CompletionHandlerCallChecker.h"
 #import "DiagnosticLoggingClient.h"
 #import "FindClient.h"
@@ -144,6 +145,7 @@ enum class DynamicViewportUpdateMode {
 #endif
 
 #if PLATFORM(MAC)
+#import "WKTextFinderClient.h"
 #import "WKViewInternal.h"
 #import <WebCore/ColorMac.h>
 
@@ -235,6 +237,7 @@ WKWebView* fromWebPageProxy(WebKit::WebPageProxy& page)
 #endif
 #if PLATFORM(MAC)
     std::unique_ptr<WebKit::WebViewImpl> _impl;
+    RetainPtr<WKTextFinderClient> _textFinderClient;
 #endif
 }
 
@@ -419,6 +422,10 @@ static bool shouldAllowPictureInPictureMediaPlayback()
 
 - (void)dealloc
 {
+#if PLATFORM(MAC)
+    [_textFinderClient willDestroyView:self];
+#endif
+
 #if PLATFORM(IOS)
     if (_remoteObjectRegistry)
         _page->process().processPool().removeMessageReceiver(Messages::RemoteObjectRegistry::messageReceiverName(), _page->pageID());
@@ -2644,6 +2651,33 @@ WEBCORE_COMMAND(yankAndSelect)
 }
 #endif
 
+- (WKTextFinderClient *)_ensureTextFinderClient
+{
+    if (!_textFinderClient)
+        _textFinderClient = adoptNS([[WKTextFinderClient alloc] initWithPage:*_page view:self]);
+    return _textFinderClient.get();
+}
+
+- (void)findMatchesForString:(NSString *)targetString relativeToMatch:(id <NSTextFinderAsynchronousDocumentFindMatch>)relativeMatch findOptions:(NSTextFinderAsynchronousDocumentFindOptions)findOptions maxResults:(NSUInteger)maxResults resultCollector:(void (^)(NSArray *matches, BOOL didWrap))resultCollector
+{
+    [[self _ensureTextFinderClient] findMatchesForString:targetString relativeToMatch:relativeMatch findOptions:findOptions maxResults:maxResults resultCollector:resultCollector];
+}
+
+- (NSView *)documentContainerView
+{
+    return self;
+}
+
+- (void)getSelectedText:(void (^)(NSString *selectedTextString))completionHandler
+{
+    [[self _ensureTextFinderClient] getSelectedText:completionHandler];
+}
+
+- (void)selectFindMatch:(id <NSTextFinderAsynchronousDocumentFindMatch>)findMatch completionHandler:(void (^)(void))completionHandler
+{
+    [[self _ensureTextFinderClient] selectFindMatch:findMatch completionHandler:completionHandler];
+}
+
 - (NSTextInputContext *)_web_superInputContext
 {
     return [super inputContext];
index 6601497..6f65dab 100644 (file)
@@ -232,6 +232,10 @@ typedef NS_ENUM(NSInteger, _WKImmediateActionType) {
 
 @end
 
+#if !TARGET_OS_IPHONE
+@interface WKWebView (WKNSTextFinderClient) <NSTextFinderClient>
+@end
+#endif
 
 @interface WKWebView (WKTesting)
 
index 3c1c145..aa6f709 100644 (file)
@@ -48,7 +48,7 @@ public:
 private:
     // From API::FindClient
     virtual void didCountStringMatches(WebPageProxy*, const String&, uint32_t matchCount);
-    virtual void didFindString(WebPageProxy*, const String&, uint32_t matchCount, int32_t matchIndex);
+    virtual void didFindString(WebPageProxy*, const String&, const Vector<WebCore::IntRect>&, uint32_t matchCount, int32_t matchIndex);
     virtual void didFailToFindString(WebPageProxy*, const String&);
     
     WKWebView *m_webView;
index df8fad0..447266c 100644 (file)
@@ -57,7 +57,7 @@ void FindClient::didCountStringMatches(WebPageProxy*, const String& string, uint
         [m_delegate.get() _webView:m_webView didCountMatches:matchCount forString:string];
 }
 
-void FindClient::didFindString(WebPageProxy*, const String& string, uint32_t matchCount, int32_t matchIndex)
+void FindClient::didFindString(WebPageProxy*, const String& string, const Vector<WebCore::IntRect>&, uint32_t matchCount, int32_t matchIndex)
 {
     if (m_delegateMethods.webviewDidFindString)
         [m_delegate.get() _webView:m_webView didFindMatches:matchCount forString:string withMatchIndex:matchIndex];
index 77be5d6..619f375 100644 (file)
@@ -4079,9 +4079,9 @@ void WebPageProxy::setTextIndicatorAnimationProgress(float progress)
 #endif
 }
 
-void WebPageProxy::didFindString(const String& string, uint32_t matchCount, int32_t matchIndex)
+void WebPageProxy::didFindString(const String& string, const Vector<WebCore::IntRect>& matchRects, uint32_t matchCount, int32_t matchIndex)
 {
-    m_findClient->didFindString(this, string, matchCount, matchIndex);
+    m_findClient->didFindString(this, string, matchRects, matchCount, matchIndex);
 }
 
 void WebPageProxy::didFindStringMatches(const String& string, const Vector<Vector<WebCore::IntRect>>& matchRects, int32_t firstIndexAfterSelection)
index 64f2dc6..d2ec4f3 100644 (file)
@@ -751,7 +751,7 @@ public:
     void setTextIndicator(const WebCore::TextIndicatorData&, uint64_t /* WebCore::TextIndicatorWindowLifetime */ lifetime = 0 /* Permanent */);
     void setTextIndicatorAnimationProgress(float);
     void clearTextIndicator();
-    void didFindString(const String&, uint32_t matchCount, int32_t matchIndex);
+    void didFindString(const String&, const Vector<WebCore::IntRect>&, uint32_t matchCount, int32_t matchIndex);
     void didFailToFindString(const String&);
     void didFindStringMatches(const String&, const Vector<Vector<WebCore::IntRect>>& matchRects, int32_t firstIndexAfterSelection);
 
index f3dc721..114291e 100644 (file)
@@ -233,7 +233,7 @@ messages -> WebPageProxy {
     DidCountStringMatches(String string, uint32_t matchCount)
     SetTextIndicator(struct WebCore::TextIndicatorData indicator, uint64_t lifetime)
     ClearTextIndicator()
-    DidFindString(String string, uint32_t matchCount, int32_t matchIndex)
+    DidFindString(String string, Vector<WebCore::IntRect> matchRect, uint32_t matchCount, int32_t matchIndex)
     DidFailToFindString(String string)
     DidFindStringMatches(String string, Vector<Vector<WebCore::IntRect>> matches, int32_t firstIndexAfterSelection)
     DidGetImageForFindMatch(WebKit::ShareableBitmap::Handle contentImageHandle, uint32_t matchIndex)
index a76bc17..8df3ef1 100644 (file)
@@ -607,7 +607,7 @@ static NSStringCompareOptions stringCompareOptions(_WKFindOptions options)
                 _currentFindMatchIndex = 0;
                 for (const auto& knownMatch : _cachedFindMatches) {
                     if (match.stringRange.location == [knownMatch stringRange].location && match.stringRange.length == [knownMatch stringRange].length) {
-                        page->findClient().didFindString(page.get(), string, _cachedFindMatches.size(), _currentFindMatchIndex);
+                        page->findClient().didFindString(page.get(), string, { }, _cachedFindMatches.size(), _currentFindMatchIndex);
                         break;
                     }
                     _currentFindMatchIndex++;
diff --git a/Source/WebKit2/UIProcess/mac/WKTextFinderClient.h b/Source/WebKit2/UIProcess/mac/WKTextFinderClient.h
new file mode 100644 (file)
index 0000000..eacc951
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2015 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef WKTextFinderClient_h
+#define WKTextFinderClient_h
+
+#import <WebKit/WKFoundation.h>
+
+#if PLATFORM(MAC) && WK_API_ENABLED
+
+OBJC_CLASS NSView;
+
+namespace WebKit {
+class WebPageProxy;
+}
+
+@interface WKTextFinderClient : NSObject
+
+- (instancetype)initWithPage:(WebKit::WebPageProxy&)page view:(NSView *)view;
+- (void)willDestroyView:(NSView *)view;
+
+@end
+
+#endif // PLATFORM(MAC)
+
+#endif // WKTextFinderClient_h
diff --git a/Source/WebKit2/UIProcess/mac/WKTextFinderClient.mm b/Source/WebKit2/UIProcess/mac/WKTextFinderClient.mm
new file mode 100644 (file)
index 0000000..84bde57
--- /dev/null
@@ -0,0 +1,275 @@
+/*
+ * Copyright (C) 2015 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#import "config.h"
+#import "WKTextFinderClient.h"
+
+#if PLATFORM(MAC) && WK_API_ENABLED
+
+#import "APIFindClient.h"
+#import "APIFindMatchesClient.h"
+#import "AppKitSPI.h"
+#import "WebImage.h"
+#import "WebPageProxy.h"
+#import <wtf/Deque.h>
+
+// FIXME: Implement support for replace.
+// FIXME: Implement scrollFindMatchToVisible.
+// FIXME: The NSTextFinder overlay doesn't move with scrolling; we should have a mode where we manage the overlay.
+
+using namespace WebCore;
+using namespace WebKit;
+
+@interface WKTextFinderClient ()
+
+- (void)didFindStringMatchesWithRects:(const Vector<Vector<IntRect>>&)rects;
+
+- (void)getImageForMatchResult:(id <NSTextFinderAsynchronousDocumentFindMatch>)findMatch completionHandler:(void (^)(NSImage *generatedImage))completionHandler;
+- (void)didGetImageForMatchResult:(WebImage *)string;
+
+@end
+
+namespace WebKit {
+
+class TextFinderFindClient : public API::FindMatchesClient, public API::FindClient {
+public:
+    explicit TextFinderFindClient(WKTextFinderClient *textFinderClient)
+        : m_textFinderClient(textFinderClient)
+    {
+    }
+
+private:
+    virtual void didFindStringMatches(WebPageProxy* page, const String&, const Vector<Vector<IntRect>>& matchRects, int32_t) override
+    {
+        [m_textFinderClient didFindStringMatchesWithRects:matchRects];
+    }
+
+    virtual void didGetImageForMatchResult(WebPageProxy* page, WebImage* image, int32_t index) override
+    {
+        [m_textFinderClient didGetImageForMatchResult:image];
+    }
+
+    virtual void didFindString(WebPageProxy*, const String&, const Vector<IntRect>& matchRects, uint32_t, int32_t) override
+    {
+        [m_textFinderClient didFindStringMatchesWithRects:{ matchRects }];
+    }
+
+    virtual void didFailToFindString(WebPageProxy*, const String& string) override
+    {
+        [m_textFinderClient didFindStringMatchesWithRects:{ }];
+    }
+
+    RetainPtr<WKTextFinderClient> m_textFinderClient;
+};
+    
+}
+
+@interface WKTextFinderMatch : NSObject <NSTextFinderAsynchronousDocumentFindMatch>
+
+@property (nonatomic, readonly) unsigned index;
+
+@end
+
+@implementation WKTextFinderMatch {
+    WKTextFinderClient *_client;
+    NSView *_view;
+    RetainPtr<NSArray> _rects;
+    unsigned _index;
+}
+
+- (instancetype)initWithClient:(WKTextFinderClient *)client view:(NSView *)view index:(unsigned)index rects:(NSArray *)rects
+{
+    self = [super init];
+
+    if (!self)
+        return nil;
+
+    _client = client;
+    _view = view;
+    _rects = rects;
+    _index = index;
+
+    return self;
+}
+
+- (NSView *)containingView
+{
+    return _view;
+}
+
+- (NSArray *)textRects
+{
+    return _rects.get();
+}
+
+- (void)generateTextImage:(void (^)(NSImage *generatedImage))completionHandler
+{
+    [_client getImageForMatchResult:self completionHandler:completionHandler];
+}
+
+- (unsigned)index
+{
+    return _index;
+}
+
+@end
+
+@implementation WKTextFinderClient {
+    WebPageProxy *_page;
+    NSView *_view;
+    Deque<std::function<void(NSArray *, bool didWrap)>> _findReplyCallbacks;
+    Deque<std::function<void(NSImage *)>> _imageReplyCallbacks;
+}
+
+- (instancetype)initWithPage:(WebPageProxy&)page view:(NSView *)view
+{
+    self = [super init];
+
+    if (!self)
+        return nil;
+
+    _page = &page;
+    _view = view;
+    
+    _page->setFindMatchesClient(std::make_unique<TextFinderFindClient>(self));
+    _page->setFindClient(std::make_unique<TextFinderFindClient>(self));
+
+    return self;
+}
+
+- (void)willDestroyView:(NSView *)view
+{
+    _page->setFindMatchesClient(nullptr);
+    _page->setFindClient(nullptr);
+
+    _page = nullptr;
+    _view = nil;
+}
+
+#pragma mark - NSTextFinderClient SPI
+
+- (void)findMatchesForString:(NSString *)targetString relativeToMatch:(id <NSTextFinderAsynchronousDocumentFindMatch>)relativeMatch findOptions:(NSTextFinderAsynchronousDocumentFindOptions)findOptions maxResults:(NSUInteger)maxResults resultCollector:(void (^)(NSArray *matches, BOOL didWrap))resultCollector
+{
+    unsigned kitFindOptions = 0;
+
+    if (findOptions & NSTextFinderAsynchronousDocumentFindOptionsBackwards)
+        kitFindOptions |= FindOptionsBackwards;
+    if (findOptions & NSTextFinderAsynchronousDocumentFindOptionsWrap)
+        kitFindOptions |= FindOptionsWrapAround;
+    if (findOptions & NSTextFinderAsynchronousDocumentFindOptionsCaseInsensitive)
+        kitFindOptions |= FindOptionsCaseInsensitive;
+    if (findOptions & NSTextFinderAsynchronousDocumentFindOptionsStartsWith)
+        kitFindOptions |= FindOptionsAtWordStarts;
+
+    RetainPtr<NSProgress> progress = [NSProgress progressWithTotalUnitCount:1];
+    auto copiedResultCollector = Block_copy(resultCollector);
+    _findReplyCallbacks.append([progress, copiedResultCollector] (NSArray *matches, bool didWrap) {
+        copiedResultCollector(matches, didWrap);
+        Block_release(copiedResultCollector);
+
+        [progress setCompletedUnitCount:1];
+    });
+
+    if (maxResults == 1)
+        _page->findString(targetString, static_cast<WebKit::FindOptions>(kitFindOptions), maxResults);
+    else
+        _page->findStringMatches(targetString, static_cast<WebKit::FindOptions>(kitFindOptions), maxResults);
+}
+
+- (void)getSelectedText:(void (^)(NSString *selectedTextString))completionHandler
+{
+    void (^copiedCompletionHandler)(NSString *) = Block_copy(completionHandler);
+
+    _page->getSelectionOrContentsAsString([copiedCompletionHandler] (const String& string, CallbackBase::Error) {
+        copiedCompletionHandler(string);
+        Block_release(copiedCompletionHandler);
+    });
+}
+
+- (void)selectFindMatch:(id <NSTextFinderAsynchronousDocumentFindMatch>)findMatch completionHandler:(void (^)(void))completionHandler
+{
+    ASSERT([findMatch isKindOfClass:[WKTextFinderMatch class]]);
+    ASSERT(!completionHandler);
+
+    WKTextFinderMatch *textFinderMatch = static_cast<WKTextFinderMatch *>(findMatch);
+    _page->selectFindMatch(textFinderMatch.index);
+}
+
+#pragma mark - FindMatchesClient
+
+static RetainPtr<NSArray> arrayFromRects(const Vector<IntRect>& matchRects)
+{
+    RetainPtr<NSMutableArray> nsMatchRects = adoptNS([[NSMutableArray alloc] initWithCapacity:matchRects.size()]);
+    for (auto& rect : matchRects)
+        [nsMatchRects addObject:[NSValue valueWithRect:rect]];
+    return nsMatchRects;
+}
+
+- (void)didFindStringMatchesWithRects:(const Vector<Vector<IntRect>>&)rectsForMatches
+{
+    if (_findReplyCallbacks.isEmpty())
+        return;
+
+    auto replyCallback = _findReplyCallbacks.takeFirst();
+    unsigned matchCount = rectsForMatches.size();
+    RetainPtr<NSMutableArray> matchObjects = adoptNS([[NSMutableArray alloc] initWithCapacity:matchCount]);
+    for (unsigned i = 0; i < matchCount; i++) {
+        RetainPtr<NSArray> nsMatchRects = arrayFromRects(rectsForMatches[i]);
+        RetainPtr<WKTextFinderMatch> match = adoptNS([[WKTextFinderMatch alloc] initWithClient:self view:_view index:i rects:nsMatchRects.get()]);
+        [matchObjects addObject:match.get()];
+    }
+
+    replyCallback(matchObjects.get(), NO);
+}
+
+- (void)didGetImageForMatchResult:(WebImage *)image
+{
+    if (_imageReplyCallbacks.isEmpty())
+        return;
+
+    auto imageCallback = _imageReplyCallbacks.takeFirst();
+    imageCallback([[[NSImage alloc] initWithCGImage:image->bitmap()->makeCGImage().get() size:NSZeroSize] autorelease]);
+}
+
+#pragma mark - WKTextFinderMatch callbacks
+
+- (void)getImageForMatchResult:(id <NSTextFinderAsynchronousDocumentFindMatch>)findMatch completionHandler:(void (^)(NSImage *generatedImage))completionHandler
+{
+    ASSERT([findMatch isKindOfClass:[WKTextFinderMatch class]]);
+
+    WKTextFinderMatch *textFinderMatch = static_cast<WKTextFinderMatch *>(findMatch);
+
+    auto copiedImageCallback = Block_copy(completionHandler);
+    _imageReplyCallbacks.append([copiedImageCallback] (NSImage *image) {
+        copiedImageCallback(image);
+        Block_release(copiedImageCallback);
+    });
+
+    _page->getImageForFindMatch(textFinderMatch.index);
+}
+
+@end
+
+#endif // PLATFORM(MAC)
index ff2698f..2f2ec1c 100644 (file)
                2DD12A081A8177F3002C74E6 /* WKPageRenderingProgressEvents.h in Headers */ = {isa = PBXBuildFile; fileRef = 2DD12A071A8177F3002C74E6 /* WKPageRenderingProgressEvents.h */; settings = {ATTRIBUTES = (Private, ); }; };
                2DD13BD518F7DADD00E130A1 /* FindControllerIOS.mm in Sources */ = {isa = PBXBuildFile; fileRef = 2DD13BD318F7DADD00E130A1 /* FindControllerIOS.mm */; };
                2DD67A2E1BD819730053B251 /* APIFindMatchesClient.h in Headers */ = {isa = PBXBuildFile; fileRef = 2DD67A2D1BD819730053B251 /* APIFindMatchesClient.h */; };
+               2DD67A351BD861060053B251 /* WKTextFinderClient.h in Headers */ = {isa = PBXBuildFile; fileRef = 2DD67A331BD861060053B251 /* WKTextFinderClient.h */; };
+               2DD67A361BD861060053B251 /* WKTextFinderClient.mm in Sources */ = {isa = PBXBuildFile; fileRef = 2DD67A341BD861060053B251 /* WKTextFinderClient.mm */; };
                2DD9EB2D1A6F012500BB1267 /* APINavigationClient.h in Headers */ = {isa = PBXBuildFile; fileRef = 2DD9EB2C1A6F012500BB1267 /* APINavigationClient.h */; };
                2DDE0AFA18298CC900F97EAA /* RemoteLayerTreePropertyApplier.h in Headers */ = {isa = PBXBuildFile; fileRef = 2DDE0AF818298CC900F97EAA /* RemoteLayerTreePropertyApplier.h */; };
                2DDE0AFB18298CC900F97EAA /* RemoteLayerTreePropertyApplier.mm in Sources */ = {isa = PBXBuildFile; fileRef = 2DDE0AF918298CC900F97EAA /* RemoteLayerTreePropertyApplier.mm */; };
                2DD12A071A8177F3002C74E6 /* WKPageRenderingProgressEvents.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WKPageRenderingProgressEvents.h; sourceTree = "<group>"; };
                2DD13BD318F7DADD00E130A1 /* FindControllerIOS.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = FindControllerIOS.mm; path = ios/FindControllerIOS.mm; sourceTree = "<group>"; };
                2DD67A2D1BD819730053B251 /* APIFindMatchesClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = APIFindMatchesClient.h; sourceTree = "<group>"; };
+               2DD67A331BD861060053B251 /* WKTextFinderClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WKTextFinderClient.h; sourceTree = "<group>"; };
+               2DD67A341BD861060053B251 /* WKTextFinderClient.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = WKTextFinderClient.mm; sourceTree = "<group>"; };
                2DD9EB2C1A6F012500BB1267 /* APINavigationClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = APINavigationClient.h; sourceTree = "<group>"; };
                2DDE0AF818298CC900F97EAA /* RemoteLayerTreePropertyApplier.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RemoteLayerTreePropertyApplier.h; sourceTree = "<group>"; };
                2DDE0AF918298CC900F97EAA /* RemoteLayerTreePropertyApplier.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = RemoteLayerTreePropertyApplier.mm; sourceTree = "<group>"; };
                                0FCB4E5D18BBE3D9000FCFC9 /* WKPrintingView.mm */,
                                513E462B1AD837560016234A /* WKSharingServicePickerDelegate.h */,
                                513E462C1AD837560016234A /* WKSharingServicePickerDelegate.mm */,
+                               2DD67A331BD861060053B251 /* WKTextFinderClient.h */,
+                               2DD67A341BD861060053B251 /* WKTextFinderClient.mm */,
                                0FCB4E5E18BBE3D9000FCFC9 /* WKTextInputWindowController.h */,
                                0FCB4E5F18BBE3D9000FCFC9 /* WKTextInputWindowController.mm */,
                                2D28A4951AF965A100F190C9 /* WKViewLayoutStrategy.h */,
                                D3B9484911FF4B6500032B39 /* WebSearchPopupMenu.h in Headers */,
                                1A4832D71A9CDF96008B4DFE /* WebsiteData.h in Headers */,
                                1A4832D11A9BDC2F008B4DFE /* WebsiteDataRecord.h in Headers */,
+                               2DD67A351BD861060053B251 /* WKTextFinderClient.h in Headers */,
                                1A53C2AA1A325730004E8C70 /* WebsiteDataStore.h in Headers */,
                                836034A01ACB34D600626549 /* WebSQLiteDatabaseTracker.h in Headers */,
                                1A52C0F81A38CDC70016160A /* WebStorageNamespaceProvider.h in Headers */,
                                E179FD9F134D38250015B883 /* ArgumentCodersMac.mm in Sources */,
                                BC032DA510F437D10058C15A /* ArgumentDecoder.cpp in Sources */,
                                BC032DA710F437D10058C15A /* ArgumentEncoder.cpp in Sources */,
+                               2DD67A361BD861060053B251 /* WKTextFinderClient.mm in Sources */,
                                C59C4A5818B81174007BDCB6 /* AssistedNodeInformation.cpp in Sources */,
                                839902021BE9A02B000F3653 /* NetworkLoad.cpp in Sources */,
                                515E7727183DD6F60007203F /* AsyncRequest.cpp in Sources */,
index 303e1b7..3070e15 100644 (file)
@@ -180,7 +180,14 @@ void FindController::updateFindUIAfterPageScroll(bool found, const String& strin
                 m_foundStringMatchIndex -= matchCount;
         }
 
-        m_webPage->send(Messages::WebPageProxy::DidFindString(string, matchCount, m_foundStringMatchIndex));
+        m_findMatches.clear();
+        Vector<IntRect> matchRects;
+        if (auto range = m_webPage->corePage()->selection().firstRange()) {
+            range->absoluteTextRects(matchRects);
+            m_findMatches.append(range);
+        }
+
+        m_webPage->send(Messages::WebPageProxy::DidFindString(string, matchRects, matchCount, m_foundStringMatchIndex));
 
         if (!(options & FindOptionsShowFindIndicator) || !selectedFrame || !updateFindIndicator(*selectedFrame, shouldShowOverlay))
             hideFindIndicator();
@@ -221,13 +228,15 @@ void FindController::findString(const String& string, FindOptions options, unsig
             if (fs.selectionBounds().isEmpty()) {
                 m_findMatches.clear();
                 int indexForSelection;
-                m_webPage->corePage()->findStringMatchingRanges(string, core(options), maxMatchCount, m_findMatches, indexForSelection);
+                m_webPage->corePage()->findStringMatchingRanges(string, coreOptions, maxMatchCount, m_findMatches, indexForSelection);
                 m_foundStringMatchIndex = indexForSelection;
                 foundStringStartsAfterSelection = true;
             }
         }
     }
 
+    m_findMatches.clear();
+
     bool found;
     if (pluginView)
         found = pluginView->findString(string, coreOptions, maxMatchCount);
index 7afe66c..03f360e 100644 (file)
@@ -1,3 +1,23 @@
+2015-11-06  Tim Horton  <timothy_horton@apple.com>
+
+        Add preliminary (SPI) support for NSTextFinder on WKWebView
+        https://bugs.webkit.org/show_bug.cgi?id=150907
+        <rdar://problem/19171624>
+
+        Reviewed by Darin Adler.
+
+        * TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj:
+        * TestWebKitAPI/Tests/WebKit2Cocoa/FindInPage.mm: Added.
+        (-[FindInPageNavigationDelegate webView:didFinishNavigation:]):
+        (TEST):
+        Add an API test.
+
+        * WebEditingTester/WK1WebDocumentController.m:
+        * WebEditingTester/WK2WebDocumentController.m:
+        (-[WK2WebDocumentController awakeFromNib]):
+        (-[WK2WebDocumentController contentView]):
+        Use incremental find, and show the overlay/indicator.
+
 2015-11-06  Alexey Proskuryakov  <ap@apple.com>
 
         iOS test results are not visible on the flakiness dashboard
index ed8378f..9dbc1b6 100644 (file)
@@ -36,6 +36,7 @@
                290F4275172A221C00939FF0 /* custom-protocol-sync-xhr.html in Copy Resources */ = {isa = PBXBuildFile; fileRef = 290F4274172A1FDE00939FF0 /* custom-protocol-sync-xhr.html */; };
                297234B7173AFAC700983601 /* CustomProtocolsInvalidScheme_Bundle.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 297234B5173AFAC700983601 /* CustomProtocolsInvalidScheme_Bundle.cpp */; };
                2D1FE0B01AD465C1006CD9E6 /* FixedLayoutSize.mm in Sources */ = {isa = PBXBuildFile; fileRef = 2D1FE0AF1AD465C1006CD9E6 /* FixedLayoutSize.mm */; };
+               2D8104CC1BEC13E70020DA46 /* FindInPage.mm in Sources */ = {isa = PBXBuildFile; fileRef = 2D8104CB1BEC13E70020DA46 /* FindInPage.mm */; };
                2D9A53AF1B31FA8D0074D5AA /* ShrinkToFit.mm in Sources */ = {isa = PBXBuildFile; fileRef = 2D9A53AE1B31FA8D0074D5AA /* ShrinkToFit.mm */; };
                2DD355361BD08378005DF4A7 /* AutoLayoutIntegration.mm in Sources */ = {isa = PBXBuildFile; fileRef = 2DD355351BD08378005DF4A7 /* AutoLayoutIntegration.mm */; };
                2DD7D3AF178227B30026E1E3 /* lots-of-text-vertical-lr.html in Copy Resources */ = {isa = PBXBuildFile; fileRef = 2DD7D3AE178227AC0026E1E3 /* lots-of-text-vertical-lr.html */; };
                29AB8AA3164C7A9300D49BEC /* TestBrowsingContextLoadDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TestBrowsingContextLoadDelegate.h; sourceTree = "<group>"; };
                2D1FE0AF1AD465C1006CD9E6 /* FixedLayoutSize.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = FixedLayoutSize.mm; sourceTree = "<group>"; };
                2D640B5417875DFF00BFAF99 /* ScrollPinningBehaviors.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ScrollPinningBehaviors.cpp; sourceTree = "<group>"; };
+               2D8104CB1BEC13E70020DA46 /* FindInPage.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = FindInPage.mm; sourceTree = "<group>"; };
                2D9A53AE1B31FA8D0074D5AA /* ShrinkToFit.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = ShrinkToFit.mm; sourceTree = "<group>"; };
                2DD355351BD08378005DF4A7 /* AutoLayoutIntegration.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = AutoLayoutIntegration.mm; sourceTree = "<group>"; };
                2DD7D3A9178205D00026E1E3 /* ResizeReversePaginatedWebView.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ResizeReversePaginatedWebView.cpp; sourceTree = "<group>"; };
                                A14FC5861B8991B600D107EB /* ContentFiltering.mm */,
                                A14FC5891B89927100D107EB /* ContentFilteringPlugIn.mm */,
                                A1A4FE5D18DD3DB700B5EA8A /* Download.mm */,
+                               2D8104CB1BEC13E70020DA46 /* FindInPage.mm */,
                                2D1FE0AF1AD465C1006CD9E6 /* FixedLayoutSize.mm */,
                                37D36ED61AF42ECD00BAF5D9 /* LoadAlternateHTMLString.mm */,
                                51CD1C6A1B38CE3600142CA5 /* ModalAlerts.mm */,
                                2D1FE0B01AD465C1006CD9E6 /* FixedLayoutSize.mm in Sources */,
                                1CB9BC381A67482300FE5678 /* WeakPtr.cpp in Sources */,
                                2E7765CD16C4D80A00BA2BB1 /* mainIOS.mm in Sources */,
+                               2D8104CC1BEC13E70020DA46 /* FindInPage.mm in Sources */,
                                41973B5D1AF22875006C7B36 /* SharedBuffer.cpp in Sources */,
                                2DD355361BD08378005DF4A7 /* AutoLayoutIntegration.mm in Sources */,
                                7AA6A1521AAC0B31002B2ED3 /* WorkQueue.cpp in Sources */,
diff --git a/Tools/TestWebKitAPI/Tests/WebKit2Cocoa/FindInPage.mm b/Tools/TestWebKitAPI/Tests/WebKit2Cocoa/FindInPage.mm
new file mode 100644 (file)
index 0000000..b489f6d
--- /dev/null
@@ -0,0 +1,124 @@
+/*
+ * Copyright (C) 2015 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+
+#import "PlatformUtilities.h"
+#import <WebKit/WKWebViewPrivate.h>
+#import <wtf/RetainPtr.h>
+
+#if WK_API_ENABLED && !PLATFORM(IOS)
+
+typedef enum : NSUInteger {
+    NSTextFinderAsynchronousDocumentFindOptionsBackwards = 1 << 0,
+} NSTextFinderAsynchronousDocumentFindOptions;
+
+@protocol NSTextFinderAsynchronousDocumentFindMatch <NSObject>
+@property (retain, nonatomic, readonly) NSArray *textRects;
+@end
+
+@interface WKWebView (NSTextFinderSupport)
+
+- (void)findMatchesForString:(NSString *)targetString relativeToMatch:(id <NSTextFinderAsynchronousDocumentFindMatch>)relativeMatch findOptions:(NSTextFinderAsynchronousDocumentFindOptions)findOptions maxResults:(NSUInteger)maxResults resultCollector:(void (^)(NSArray *matches, BOOL didWrap))resultCollector;
+
+@end
+
+static bool navigationDone;
+static bool findMatchesDone;
+
+@interface FindInPageNavigationDelegate : NSObject <WKNavigationDelegate>
+@end
+
+@implementation FindInPageNavigationDelegate
+
+- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
+{
+    navigationDone = true;
+}
+
+@end
+
+TEST(WebKit2, FindInPage)
+{
+    RetainPtr<WKWebView> webView = adoptNS([[WKWebView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100)]);
+
+    RetainPtr<FindInPageNavigationDelegate> delegate = adoptNS([[FindInPageNavigationDelegate alloc] init]);
+    [webView setNavigationDelegate:delegate.get()];
+
+    NSURLRequest *request = [NSURLRequest requestWithURL:[[NSBundle mainBundle] URLForResource:@"lots-of-text" withExtension:@"html" subdirectory:@"TestWebKitAPI.resources"]];
+    [webView loadRequest:request];
+
+    TestWebKitAPI::Util::run(&navigationDone);
+
+    NSTextFinderAsynchronousDocumentFindOptions noFindOptions = (NSTextFinderAsynchronousDocumentFindOptions)0;
+
+    // Find all matches.
+    [webView findMatchesForString:@"Birthday" relativeToMatch:nil findOptions:noFindOptions maxResults:NSUIntegerMax resultCollector:^(NSArray *matches, BOOL didWrap) {
+        EXPECT_EQ((NSUInteger)360, matches.count);
+
+        id <NSTextFinderAsynchronousDocumentFindMatch> firstMatch = [matches objectAtIndex:0];
+        EXPECT_EQ((NSUInteger)1, firstMatch.textRects.count);
+
+        findMatchesDone = true;
+    }];
+
+    TestWebKitAPI::Util::run(&findMatchesDone);
+    findMatchesDone = false;
+
+    // Find one match, doing an incremental search.
+    [webView findMatchesForString:@"Birthday" relativeToMatch:nil findOptions:noFindOptions maxResults:1 resultCollector:^(NSArray *matches, BOOL didWrap) {
+        EXPECT_EQ((NSUInteger)1, matches.count);
+
+        id <NSTextFinderAsynchronousDocumentFindMatch> firstMatch = [matches objectAtIndex:0];
+        EXPECT_EQ((NSUInteger)1, firstMatch.textRects.count);
+
+        // Find the next match in incremental mode.
+        [webView findMatchesForString:@"Birthday" relativeToMatch:nil findOptions:noFindOptions maxResults:1 resultCollector:^(NSArray *matches, BOOL didWrap) {
+            EXPECT_EQ((NSUInteger)1, matches.count);
+
+            id <NSTextFinderAsynchronousDocumentFindMatch> secondMatch = [matches objectAtIndex:0];
+            EXPECT_EQ((NSUInteger)1, secondMatch.textRects.count);
+
+            EXPECT_FALSE(NSEqualRects([firstMatch.textRects.lastObject rectValue], [secondMatch.textRects.lastObject rectValue]));
+
+            // Find the previous match in incremental mode.
+            [webView findMatchesForString:@"Birthday" relativeToMatch:nil findOptions:NSTextFinderAsynchronousDocumentFindOptionsBackwards maxResults:1 resultCollector:^(NSArray *matches, BOOL didWrap) {
+                EXPECT_EQ((NSUInteger)1, matches.count);
+
+                id <NSTextFinderAsynchronousDocumentFindMatch> firstMatchAgain = [matches objectAtIndex:0];
+                EXPECT_EQ((NSUInteger)1, firstMatchAgain.textRects.count);
+
+                EXPECT_TRUE(NSEqualRects([firstMatch.textRects.lastObject rectValue], [firstMatchAgain.textRects.lastObject rectValue]));
+                
+                findMatchesDone = true;
+            }];
+        }];
+
+    }];
+
+    TestWebKitAPI::Util::run(&findMatchesDone);
+}
+
+#endif
index de05662..57f79da 100644 (file)
@@ -31,7 +31,7 @@
 #import <WebKit/WebPreferenceKeysPrivate.h>
 #import <WebKit/WebViewPrivate.h>
 
-@interface WK1WebDocumentController()
+@interface WK1WebDocumentController () <WebUIDelegate>
 @property (nonatomic, strong) WebView *webView;
 @end
 
index efaf60a..49911d8 100644 (file)
@@ -73,7 +73,9 @@ static WKWebViewConfiguration *defaultConfiguration()
     self.window.title = @"WebEditor [WK2]";
 
     _textFinder = [[NSTextFinder alloc] init];
-    _textFinder.client = (id<NSTextFinderClient>)_webView;
+    _textFinder.incrementalSearchingEnabled = YES;
+    _textFinder.incrementalSearchingShouldDimContentView = YES;
+    _textFinder.client = _webView;
     _textFinder.findBarContainer = self;
 }
 
@@ -102,6 +104,11 @@ static WKWebViewConfiguration *defaultConfiguration()
     [self layout];
 }
 
+- (NSView *)contentView
+{
+    return _webView;
+}
+
 - (BOOL)isFindBarVisible
 {
     return _findBarVisible;