4099b29f43719681b1c4f48cf7d1ae3201584d20
[WebKit-https.git] / Source / WebCore / inspector / InspectorPageAgent.cpp
1 /*
2  * Copyright (C) 2011 Google 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 are
6  * met:
7  *
8  *     * Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *     * Redistributions in binary form must reproduce the above
11  * copyright notice, this list of conditions and the following disclaimer
12  * in the documentation and/or other materials provided with the
13  * distribution.
14  *     * Neither the name of Google Inc. nor the names of its
15  * contributors may be used to endorse or promote products derived from
16  * this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #include "config.h"
32 #include "InspectorPageAgent.h"
33
34 #if ENABLE(INSPECTOR)
35
36 #include "CachedCSSStyleSheet.h"
37 #include "CachedFont.h"
38 #include "CachedImage.h"
39 #include "CachedResource.h"
40 #include "CachedResourceLoader.h"
41 #include "CachedScript.h"
42 #include "Cookie.h"
43 #include "CookieJar.h"
44 #include "DOMImplementation.h"
45 #include "DOMPatchSupport.h"
46 #include "DOMWrapperWorld.h"
47 #include "Document.h"
48 #include "DocumentLoader.h"
49 #include "Frame.h"
50 #include "FrameLoader.h"
51 #include "FrameSnapshotting.h"
52 #include "FrameView.h"
53 #include "HTMLFrameOwnerElement.h"
54 #include "HTMLNames.h"
55 #include "ImageBuffer.h"
56 #include "InspectorClient.h"
57 #include "InspectorDOMAgent.h"
58 #include "InspectorInstrumentation.h"
59 #include "InspectorOverlay.h"
60 #include "InspectorWebFrontendDispatchers.h"
61 #include "InstrumentingAgents.h"
62 #include "MainFrame.h"
63 #include "MemoryCache.h"
64 #include "Page.h"
65 #include "ResourceBuffer.h"
66 #include "ScriptController.h"
67 #include "SecurityOrigin.h"
68 #include "Settings.h"
69 #include "TextEncoding.h"
70 #include "TextResourceDecoder.h"
71 #include "UserGestureIndicator.h"
72 #include <bindings/ScriptValue.h>
73 #include <inspector/ContentSearchUtilities.h>
74 #include <inspector/IdentifiersFactory.h>
75 #include <inspector/InspectorValues.h>
76 #include <wtf/CurrentTime.h>
77 #include <wtf/ListHashSet.h>
78 #include <wtf/Vector.h>
79 #include <wtf/text/Base64.h>
80 #include <wtf/text/StringBuilder.h>
81 #include <yarr/RegularExpression.h>
82
83 #if ENABLE(WEB_ARCHIVE) && USE(CF)
84 #include "LegacyWebArchive.h"
85 #endif
86
87 using namespace Inspector;
88
89 namespace WebCore {
90
91 static bool decodeBuffer(const char* buffer, unsigned size, const String& textEncodingName, String* result)
92 {
93     if (buffer) {
94         TextEncoding encoding(textEncodingName);
95         if (!encoding.isValid())
96             encoding = WindowsLatin1Encoding();
97         *result = encoding.decode(buffer, size);
98         return true;
99     }
100     return false;
101 }
102
103 static bool prepareCachedResourceBuffer(CachedResource* cachedResource, bool* hasZeroSize)
104 {
105     *hasZeroSize = false;
106     if (!cachedResource)
107         return false;
108
109     // Zero-sized resources don't have data at all -- so fake the empty buffer, instead of indicating error by returning 0.
110     if (!cachedResource->encodedSize()) {
111         *hasZeroSize = true;
112         return true;
113     }
114
115     return true;
116 }
117
118 static bool hasTextContent(CachedResource* cachedResource)
119 {
120     InspectorPageAgent::ResourceType type = InspectorPageAgent::cachedResourceType(*cachedResource);
121     return type == InspectorPageAgent::DocumentResource || type == InspectorPageAgent::StylesheetResource || type == InspectorPageAgent::ScriptResource || type == InspectorPageAgent::XHRResource;
122 }
123
124 static PassRefPtr<TextResourceDecoder> createXHRTextDecoder(const String& mimeType, const String& textEncodingName)
125 {
126     RefPtr<TextResourceDecoder> decoder;
127     if (!textEncodingName.isEmpty())
128         decoder = TextResourceDecoder::create("text/plain", textEncodingName);
129     else if (DOMImplementation::isXMLMIMEType(mimeType.lower())) {
130         decoder = TextResourceDecoder::create("application/xml");
131         decoder->useLenientXMLDecoding();
132     } else if (equalIgnoringCase(mimeType, "text/html"))
133         decoder = TextResourceDecoder::create("text/html", "UTF-8");
134     else
135         decoder = TextResourceDecoder::create("text/plain", "UTF-8");
136     return decoder;
137 }
138
139 bool InspectorPageAgent::cachedResourceContent(CachedResource* cachedResource, String* result, bool* base64Encoded)
140 {
141     bool hasZeroSize;
142     bool prepared = prepareCachedResourceBuffer(cachedResource, &hasZeroSize);
143     if (!prepared)
144         return false;
145
146     *base64Encoded = !hasTextContent(cachedResource);
147     if (*base64Encoded) {
148         RefPtr<SharedBuffer> buffer = hasZeroSize ? SharedBuffer::create() : cachedResource->resourceBuffer()->sharedBuffer();
149
150         if (!buffer)
151             return false;
152
153         *result = base64Encode(buffer->data(), buffer->size());
154         return true;
155     }
156
157     if (hasZeroSize) {
158         *result = emptyString();
159         return true;
160     }
161
162     if (cachedResource) {
163         switch (cachedResource->type()) {
164         case CachedResource::CSSStyleSheet:
165             *result = toCachedCSSStyleSheet(cachedResource)->sheetText(false);
166             return true;
167         case CachedResource::Script:
168             *result = toCachedScript(cachedResource)->script();
169             return true;
170         case CachedResource::RawResource: {
171             ResourceBuffer* buffer = cachedResource->resourceBuffer();
172             if (!buffer)
173                 return false;
174             RefPtr<TextResourceDecoder> decoder = createXHRTextDecoder(cachedResource->response().mimeType(), cachedResource->response().textEncodingName());
175             // We show content for raw resources only for certain mime types (text, html and xml). Otherwise decoder will be null.
176             if (!decoder)
177                 return false;
178             *result = decoder->decodeAndFlush(buffer->data(), buffer->size());
179             return true;
180         }
181         default:
182             ResourceBuffer* buffer = cachedResource->resourceBuffer();
183             return decodeBuffer(buffer ? buffer->data() : nullptr, buffer ? buffer->size() : 0, cachedResource->encoding(), result);
184         }
185     }
186     return false;
187 }
188
189 bool InspectorPageAgent::mainResourceContent(Frame* frame, bool withBase64Encode, String* result)
190 {
191     RefPtr<ResourceBuffer> buffer = frame->loader().documentLoader()->mainResourceData();
192     if (!buffer)
193         return false;
194     String textEncodingName = frame->document()->inputEncoding();
195
196     return InspectorPageAgent::dataContent(buffer->data(), buffer->size(), textEncodingName, withBase64Encode, result);
197 }
198
199 // static
200 bool InspectorPageAgent::sharedBufferContent(PassRefPtr<SharedBuffer> buffer, const String& textEncodingName, bool withBase64Encode, String* result)
201 {
202     return dataContent(buffer ? buffer->data() : nullptr, buffer ? buffer->size() : 0, textEncodingName, withBase64Encode, result);
203 }
204
205 bool InspectorPageAgent::dataContent(const char* data, unsigned size, const String& textEncodingName, bool withBase64Encode, String* result)
206 {
207     if (withBase64Encode) {
208         *result = base64Encode(data, size);
209         return true;
210     }
211
212     return decodeBuffer(data, size, textEncodingName, result);
213 }
214
215 // static
216 void InspectorPageAgent::resourceContent(ErrorString& errorString, Frame* frame, const URL& url, String* result, bool* base64Encoded)
217 {
218     DocumentLoader* loader = assertDocumentLoader(errorString, frame);
219     if (!loader)
220         return;
221
222     RefPtr<SharedBuffer> buffer;
223     bool success = false;
224     if (equalIgnoringFragmentIdentifier(url, loader->url())) {
225         *base64Encoded = false;
226         success = mainResourceContent(frame, *base64Encoded, result);
227     }
228
229     if (!success)
230         success = cachedResourceContent(cachedResource(frame, url), result, base64Encoded);
231
232     if (!success)
233         errorString = ASCIILiteral("No resource with given URL found");
234 }
235
236 //static
237 String InspectorPageAgent::sourceMapURLForResource(CachedResource* cachedResource)
238 {
239     DEPRECATED_DEFINE_STATIC_LOCAL(String, sourceMapHTTPHeader, (ASCIILiteral("SourceMap")));
240     DEPRECATED_DEFINE_STATIC_LOCAL(String, sourceMapHTTPHeaderDeprecated, (ASCIILiteral("X-SourceMap")));
241
242     if (!cachedResource)
243         return String();
244
245     // Scripts are handled in a separate path.
246     if (cachedResource->type() != CachedResource::CSSStyleSheet)
247         return String();
248
249     String sourceMapHeader = cachedResource->response().httpHeaderField(sourceMapHTTPHeader);
250     if (!sourceMapHeader.isEmpty())
251         return sourceMapHeader;
252
253     sourceMapHeader = cachedResource->response().httpHeaderField(sourceMapHTTPHeaderDeprecated);
254     if (!sourceMapHeader.isEmpty())
255         return sourceMapHeader;
256
257     String content;
258     bool base64Encoded;
259     if (InspectorPageAgent::cachedResourceContent(cachedResource, &content, &base64Encoded) && !base64Encoded)
260         return ContentSearchUtilities::findStylesheetSourceMapURL(content);
261
262     return String();
263 }
264
265 CachedResource* InspectorPageAgent::cachedResource(Frame* frame, const URL& url)
266 {
267     CachedResource* cachedResource = frame->document()->cachedResourceLoader()->cachedResource(url);
268     if (!cachedResource) {
269         ResourceRequest request(url);
270 #if ENABLE(CACHE_PARTITIONING)
271         request.setCachePartition(frame->document()->topOrigin()->cachePartition());
272 #endif
273         cachedResource = memoryCache()->resourceForRequest(request, frame->page()->sessionID());
274     }
275
276     return cachedResource;
277 }
278
279 Inspector::Protocol::Page::ResourceType InspectorPageAgent::resourceTypeJson(InspectorPageAgent::ResourceType resourceType)
280 {
281     switch (resourceType) {
282     case DocumentResource:
283         return Inspector::Protocol::Page::ResourceType::Document;
284     case ImageResource:
285         return Inspector::Protocol::Page::ResourceType::Image;
286     case FontResource:
287         return Inspector::Protocol::Page::ResourceType::Font;
288     case StylesheetResource:
289         return Inspector::Protocol::Page::ResourceType::Stylesheet;
290     case ScriptResource:
291         return Inspector::Protocol::Page::ResourceType::Script;
292     case XHRResource:
293         return Inspector::Protocol::Page::ResourceType::XHR;
294     case WebSocketResource:
295         return Inspector::Protocol::Page::ResourceType::WebSocket;
296     case OtherResource:
297         return Inspector::Protocol::Page::ResourceType::Other;
298     }
299     return Inspector::Protocol::Page::ResourceType::Other;
300 }
301
302 InspectorPageAgent::ResourceType InspectorPageAgent::cachedResourceType(const CachedResource& cachedResource)
303 {
304     switch (cachedResource.type()) {
305     case CachedResource::ImageResource:
306         return InspectorPageAgent::ImageResource;
307     case CachedResource::FontResource:
308         return InspectorPageAgent::FontResource;
309     case CachedResource::CSSStyleSheet:
310         // Fall through.
311 #if ENABLE(XSLT)
312     case CachedResource::XSLStyleSheet:
313 #endif
314         return InspectorPageAgent::StylesheetResource;
315     case CachedResource::Script:
316         return InspectorPageAgent::ScriptResource;
317     case CachedResource::RawResource:
318         return InspectorPageAgent::XHRResource;
319     case CachedResource::MainResource:
320         return InspectorPageAgent::DocumentResource;
321     default:
322         break;
323     }
324     return InspectorPageAgent::OtherResource;
325 }
326
327 Inspector::Protocol::Page::ResourceType InspectorPageAgent::cachedResourceTypeJson(const CachedResource& cachedResource)
328 {
329     return resourceTypeJson(cachedResourceType(cachedResource));
330 }
331
332 InspectorPageAgent::InspectorPageAgent(InstrumentingAgents* instrumentingAgents, Page* page, InspectorClient* client, InspectorOverlay* overlay)
333     : InspectorAgentBase(ASCIILiteral("Page"), instrumentingAgents)
334     , m_page(page)
335     , m_client(client)
336     , m_overlay(overlay)
337     , m_lastScriptIdentifier(0)
338     , m_enabled(false)
339     , m_isFirstLayoutAfterOnLoad(false)
340     , m_originalScriptExecutionDisabled(false)
341     , m_ignoreScriptsEnabledNotification(false)
342     , m_showPaintRects(false)
343 {
344 }
345
346 void InspectorPageAgent::didCreateFrontendAndBackend(Inspector::InspectorFrontendChannel* frontendChannel, InspectorBackendDispatcher* backendDispatcher)
347 {
348     m_frontendDispatcher = std::make_unique<InspectorPageFrontendDispatcher>(frontendChannel);
349     m_backendDispatcher = InspectorPageBackendDispatcher::create(backendDispatcher, this);
350 }
351
352 void InspectorPageAgent::willDestroyFrontendAndBackend(InspectorDisconnectReason)
353 {
354     m_frontendDispatcher = nullptr;
355     m_backendDispatcher.clear();
356
357     ErrorString unused;
358     disable(unused);
359 #if ENABLE(TOUCH_EVENTS)
360     updateTouchEventEmulationInPage(false);
361 #endif
362 }
363
364 void InspectorPageAgent::enable(ErrorString&)
365 {
366     m_enabled = true;
367     m_instrumentingAgents->setInspectorPageAgent(this);
368
369     if (Frame* frame = mainFrame())
370         m_originalScriptExecutionDisabled = !frame->settings().isScriptEnabled();
371 }
372
373 void InspectorPageAgent::disable(ErrorString&)
374 {
375     m_enabled = false;
376     m_scriptsToEvaluateOnLoad.clear();
377     m_instrumentingAgents->setInspectorPageAgent(nullptr);
378
379     ErrorString unused;
380     setScriptExecutionDisabled(unused, m_originalScriptExecutionDisabled);
381     setShowPaintRects(unused, false);
382     setShowDebugBorders(unused, false);
383     setShowFPSCounter(unused, false);
384     setEmulatedMedia(unused, emptyString());
385     setContinuousPaintingEnabled(unused, false);
386 }
387
388 void InspectorPageAgent::addScriptToEvaluateOnLoad(ErrorString&, const String& source, String* identifier)
389 {
390     if (!m_scriptsToEvaluateOnLoad)
391         m_scriptsToEvaluateOnLoad = InspectorObject::create();
392
393     // Assure we don't override existing ids -- m_lastScriptIdentifier could get out of sync WRT actual
394     // scripts once we restored the scripts from the cookie during navigation.
395     do {
396         *identifier = String::number(++m_lastScriptIdentifier);
397     } while (m_scriptsToEvaluateOnLoad->find(*identifier) != m_scriptsToEvaluateOnLoad->end());
398
399     m_scriptsToEvaluateOnLoad->setString(*identifier, source);
400 }
401
402 void InspectorPageAgent::removeScriptToEvaluateOnLoad(ErrorString& error, const String& identifier)
403 {
404     if (!m_scriptsToEvaluateOnLoad || m_scriptsToEvaluateOnLoad->find(identifier) == m_scriptsToEvaluateOnLoad->end()) {
405         error = ASCIILiteral("Script not found");
406         return;
407     }
408
409     m_scriptsToEvaluateOnLoad->remove(identifier);
410 }
411
412 void InspectorPageAgent::reload(ErrorString&, const bool* const optionalIgnoreCache, const String* optionalScriptToEvaluateOnLoad)
413 {
414     m_pendingScriptToEvaluateOnLoadOnce = optionalScriptToEvaluateOnLoad ? *optionalScriptToEvaluateOnLoad : "";
415     m_page->mainFrame().loader().reload(optionalIgnoreCache ? *optionalIgnoreCache : false);
416 }
417
418 void InspectorPageAgent::navigate(ErrorString&, const String& url)
419 {
420     UserGestureIndicator indicator(DefinitelyProcessingUserGesture);
421     Frame& frame = m_page->mainFrame();
422     frame.loader().changeLocation(frame.document()->securityOrigin(), frame.document()->completeURL(url), "", LockHistory::No, LockBackForwardList::No);
423 }
424
425 static PassRefPtr<Inspector::Protocol::Page::Cookie> buildObjectForCookie(const Cookie& cookie)
426 {
427     return Inspector::Protocol::Page::Cookie::create()
428         .setName(cookie.name)
429         .setValue(cookie.value)
430         .setDomain(cookie.domain)
431         .setPath(cookie.path)
432         .setExpires(cookie.expires)
433         .setSize((cookie.name.length() + cookie.value.length()))
434         .setHttpOnly(cookie.httpOnly)
435         .setSecure(cookie.secure)
436         .setSession(cookie.session)
437         .release();
438 }
439
440 static PassRefPtr<Inspector::Protocol::Array<Inspector::Protocol::Page::Cookie>> buildArrayForCookies(ListHashSet<Cookie>& cookiesList)
441 {
442     RefPtr<Inspector::Protocol::Array<Inspector::Protocol::Page::Cookie>> cookies = Inspector::Protocol::Array<Inspector::Protocol::Page::Cookie>::create();
443
444     for (auto& cookie : cookiesList)
445         cookies->addItem(buildObjectForCookie(cookie));
446
447     return cookies;
448 }
449
450 static Vector<CachedResource*> cachedResourcesForFrame(Frame* frame)
451 {
452     Vector<CachedResource*> result;
453
454     for (auto& cachedResourceHandle : frame->document()->cachedResourceLoader()->allCachedResources().values()) {
455         auto* cachedResource = cachedResourceHandle.get();
456         if (cachedResource->resourceRequest().hiddenFromInspector())
457             continue;
458
459         switch (cachedResource->type()) {
460         case CachedResource::ImageResource:
461             // Skip images that were not auto loaded (images disabled in the user agent).
462         case CachedResource::FontResource:
463             // Skip fonts that were referenced in CSS but never used/downloaded.
464             if (cachedResource->stillNeedsLoad())
465                 continue;
466             break;
467         default:
468             // All other CachedResource types download immediately.
469             break;
470         }
471
472         result.append(cachedResource);
473     }
474
475     return result;
476 }
477
478 static Vector<URL> allResourcesURLsForFrame(Frame* frame)
479 {
480     Vector<URL> result;
481
482     result.append(frame->loader().documentLoader()->url());
483
484     for (auto* cachedResource : cachedResourcesForFrame(frame))
485         result.append(cachedResource->url());
486
487     return result;
488 }
489
490 void InspectorPageAgent::getCookies(ErrorString&, RefPtr<Inspector::Protocol::Array<Inspector::Protocol::Page::Cookie>>& cookies)
491 {
492     // If we can get raw cookies.
493     ListHashSet<Cookie> rawCookiesList;
494
495     // If we can't get raw cookies - fall back to String representation
496     StringBuilder stringCookiesList;
497
498     // Return value to getRawCookies should be the same for every call because
499     // the return value is platform/network backend specific, and the call will
500     // always return the same true/false value.
501     bool rawCookiesImplemented = false;
502
503     for (Frame* frame = mainFrame(); frame; frame = frame->tree().traverseNext(mainFrame())) {
504         Document* document = frame->document();
505
506         for (auto& url : allResourcesURLsForFrame(frame)) {
507             Vector<Cookie> docCookiesList;
508             rawCookiesImplemented = getRawCookies(document, URL(ParsedURLString, url), docCookiesList);
509
510             if (!rawCookiesImplemented) {
511                 // FIXME: We need duplication checking for the String representation of cookies.
512                 // Exceptions are thrown by cookie() in sandboxed frames. That won't happen here
513                 // because "document" is the document of the main frame of the page.
514                 stringCookiesList.append(document->cookie(ASSERT_NO_EXCEPTION));
515             } else {
516                 int cookiesSize = docCookiesList.size();
517                 for (int i = 0; i < cookiesSize; i++) {
518                     if (!rawCookiesList.contains(docCookiesList[i]))
519                         rawCookiesList.add(docCookiesList[i]);
520                 }
521             }
522         }
523     }
524
525     // FIXME: Do not return empty string/empty array. Make returns optional instead. https://bugs.webkit.org/show_bug.cgi?id=80855
526     if (rawCookiesImplemented)
527         cookies = buildArrayForCookies(rawCookiesList);
528     else
529         cookies = Inspector::Protocol::Array<Inspector::Protocol::Page::Cookie>::create();
530 }
531
532 void InspectorPageAgent::deleteCookie(ErrorString&, const String& cookieName, const String& url)
533 {
534     URL parsedURL(ParsedURLString, url);
535     for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext(&m_page->mainFrame()))
536         WebCore::deleteCookie(frame->document(), parsedURL, cookieName);
537 }
538
539 void InspectorPageAgent::getResourceTree(ErrorString&, RefPtr<Inspector::Protocol::Page::FrameResourceTree>& object)
540 {
541     object = buildObjectForFrameTree(&m_page->mainFrame());
542 }
543
544 void InspectorPageAgent::getResourceContent(ErrorString& errorString, const String& frameId, const String& url, String* content, bool* base64Encoded)
545 {
546     Frame* frame = assertFrame(errorString, frameId);
547     if (!frame)
548         return;
549
550     resourceContent(errorString, frame, URL(ParsedURLString, url), content, base64Encoded);
551 }
552
553 static bool textContentForCachedResource(CachedResource* cachedResource, String* result)
554 {
555     if (hasTextContent(cachedResource)) {
556         String content;
557         bool base64Encoded;
558         if (InspectorPageAgent::cachedResourceContent(cachedResource, result, &base64Encoded)) {
559             ASSERT(!base64Encoded);
560             return true;
561         }
562     }
563     return false;
564 }
565
566 void InspectorPageAgent::searchInResource(ErrorString&, const String& frameId, const String& url, const String& query, const bool* const optionalCaseSensitive, const bool* const optionalIsRegex, RefPtr<Inspector::Protocol::Array<Inspector::Protocol::GenericTypes::SearchMatch>>& results)
567 {
568     results = Inspector::Protocol::Array<Inspector::Protocol::GenericTypes::SearchMatch>::create();
569
570     bool isRegex = optionalIsRegex ? *optionalIsRegex : false;
571     bool caseSensitive = optionalCaseSensitive ? *optionalCaseSensitive : false;
572
573     Frame* frame = frameForId(frameId);
574     if (!frame)
575         return;
576
577     DocumentLoader* loader = frame->loader().documentLoader();
578     if (!loader)
579         return;
580
581     URL kurl(ParsedURLString, url);
582
583     String content;
584     bool success = false;
585     if (equalIgnoringFragmentIdentifier(kurl, loader->url()))
586         success = mainResourceContent(frame, false, &content);
587
588     if (!success) {
589         CachedResource* resource = cachedResource(frame, kurl);
590         if (resource)
591             success = textContentForCachedResource(resource, &content);
592     }
593
594     if (!success)
595         return;
596
597     results = ContentSearchUtilities::searchInTextByLines(content, query, caseSensitive, isRegex);
598 }
599
600 static PassRefPtr<Inspector::Protocol::Page::SearchResult> buildObjectForSearchResult(const String& frameId, const String& url, int matchesCount)
601 {
602     return Inspector::Protocol::Page::SearchResult::create()
603         .setUrl(url)
604         .setFrameId(frameId)
605         .setMatchesCount(matchesCount)
606         .release();
607 }
608
609 void InspectorPageAgent::searchInResources(ErrorString&, const String& text, const bool* const optionalCaseSensitive, const bool* const optionalIsRegex, RefPtr<Inspector::Protocol::Array<Inspector::Protocol::Page::SearchResult>>& results)
610 {
611     RefPtr<Inspector::Protocol::Array<Inspector::Protocol::Page::SearchResult>> searchResults = Inspector::Protocol::Array<Inspector::Protocol::Page::SearchResult>::create();
612
613     bool isRegex = optionalIsRegex ? *optionalIsRegex : false;
614     bool caseSensitive = optionalCaseSensitive ? *optionalCaseSensitive : false;
615     JSC::Yarr::RegularExpression regex = ContentSearchUtilities::createSearchRegex(text, caseSensitive, isRegex);
616
617     for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext(&m_page->mainFrame())) {
618         String content;
619
620         for (auto* cachedResource : cachedResourcesForFrame(frame)) {
621             if (textContentForCachedResource(cachedResource, &content)) {
622                 int matchesCount = ContentSearchUtilities::countRegularExpressionMatches(regex, content);
623                 if (matchesCount)
624                     searchResults->addItem(buildObjectForSearchResult(frameId(frame), cachedResource->url(), matchesCount));
625             }
626         }
627
628         if (mainResourceContent(frame, false, &content)) {
629             int matchesCount = ContentSearchUtilities::countRegularExpressionMatches(regex, content);
630             if (matchesCount)
631                 searchResults->addItem(buildObjectForSearchResult(frameId(frame), frame->document()->url(), matchesCount));
632         }
633     }
634
635     results = searchResults;
636 }
637
638 void InspectorPageAgent::setDocumentContent(ErrorString& errorString, const String& frameId, const String& html)
639 {
640     Frame* frame = assertFrame(errorString, frameId);
641     if (!frame)
642         return;
643
644     Document* document = frame->document();
645     if (!document) {
646         errorString = ASCIILiteral("No Document instance to set HTML for");
647         return;
648     }
649     DOMPatchSupport::patchDocument(document, html);
650 }
651
652 void InspectorPageAgent::setShowPaintRects(ErrorString&, bool show)
653 {
654     m_showPaintRects = show;
655     m_client->setShowPaintRects(show);
656
657     if (m_client->overridesShowPaintRects())
658         return;
659
660     m_overlay->setShowingPaintRects(show);
661 }
662
663 void InspectorPageAgent::canShowDebugBorders(ErrorString&, bool* outParam)
664 {
665     *outParam = m_client->canShowDebugBorders();
666 }
667
668 void InspectorPageAgent::setShowDebugBorders(ErrorString&, bool show)
669 {
670     m_client->setShowDebugBorders(show);
671     if (mainFrame() && mainFrame()->view())
672         mainFrame()->view()->invalidate();
673 }
674
675 void InspectorPageAgent::canShowFPSCounter(ErrorString&, bool* outParam)
676 {
677     *outParam = m_client->canShowFPSCounter();
678 }
679
680 void InspectorPageAgent::setShowFPSCounter(ErrorString&, bool show)
681 {
682     m_client->setShowFPSCounter(show);
683
684     if (mainFrame() && mainFrame()->view())
685         mainFrame()->view()->invalidate();
686 }
687
688 void InspectorPageAgent::canContinuouslyPaint(ErrorString&, bool* outParam)
689 {
690     *outParam = m_client->canContinuouslyPaint();
691 }
692
693 void InspectorPageAgent::setContinuousPaintingEnabled(ErrorString&, bool enabled)
694 {
695     m_client->setContinuousPaintingEnabled(enabled);
696
697     if (!enabled && mainFrame() && mainFrame()->view())
698         mainFrame()->view()->invalidate();
699 }
700
701 void InspectorPageAgent::getScriptExecutionStatus(ErrorString&, InspectorPageBackendDispatcherHandler::Result* status)
702 {
703     bool disabledByScriptController = false;
704     bool disabledInSettings = false;
705     Frame* frame = mainFrame();
706     if (frame) {
707         disabledByScriptController = !frame->script().canExecuteScripts(NotAboutToExecuteScript);
708         disabledInSettings = !frame->settings().isScriptEnabled();
709     }
710
711     if (!disabledByScriptController) {
712         *status = InspectorPageBackendDispatcherHandler::Result::Allowed;
713         return;
714     }
715
716     if (disabledInSettings)
717         *status = InspectorPageBackendDispatcherHandler::Result::Disabled;
718     else
719         *status = InspectorPageBackendDispatcherHandler::Result::Forbidden;
720 }
721
722 void InspectorPageAgent::setScriptExecutionDisabled(ErrorString&, bool value)
723 {
724     if (!mainFrame())
725         return;
726
727     m_ignoreScriptsEnabledNotification = true;
728     mainFrame()->settings().setScriptEnabled(!value);
729     m_ignoreScriptsEnabledNotification = false;
730 }
731
732 void InspectorPageAgent::didClearWindowObjectInWorld(Frame* frame, DOMWrapperWorld& world)
733 {
734     if (&world != &mainThreadNormalWorld())
735         return;
736
737     if (!m_frontendDispatcher)
738         return;
739
740     if (m_scriptsToEvaluateOnLoad) {
741         for (auto& keyValuePair : *m_scriptsToEvaluateOnLoad) {
742             String scriptText;
743             if (keyValuePair.value->asString(scriptText))
744                 frame->script().executeScript(scriptText);
745         }
746     }
747
748     if (!m_scriptToEvaluateOnLoadOnce.isEmpty())
749         frame->script().executeScript(m_scriptToEvaluateOnLoadOnce);
750 }
751
752 void InspectorPageAgent::domContentEventFired()
753 {
754     m_isFirstLayoutAfterOnLoad = true;
755     m_frontendDispatcher->domContentEventFired(currentTime());
756 }
757
758 void InspectorPageAgent::loadEventFired()
759 {
760     m_frontendDispatcher->loadEventFired(currentTime());
761 }
762
763 void InspectorPageAgent::frameNavigated(DocumentLoader* loader)
764 {
765     if (loader->frame()->isMainFrame()) {
766         m_scriptToEvaluateOnLoadOnce = m_pendingScriptToEvaluateOnLoadOnce;
767         m_pendingScriptToEvaluateOnLoadOnce = String();
768     }
769     m_frontendDispatcher->frameNavigated(buildObjectForFrame(loader->frame()));
770 }
771
772 void InspectorPageAgent::frameDetached(Frame* frame)
773 {
774     HashMap<Frame*, String>::iterator iterator = m_frameToIdentifier.find(frame);
775     if (iterator != m_frameToIdentifier.end()) {
776         m_frontendDispatcher->frameDetached(iterator->value);
777         m_identifierToFrame.remove(iterator->value);
778         m_frameToIdentifier.remove(iterator);
779     }
780 }
781
782 Frame* InspectorPageAgent::mainFrame()
783 {
784     // FIXME: This should return a Frame&
785     return &m_page->mainFrame();
786 }
787
788 Frame* InspectorPageAgent::frameForId(const String& frameId)
789 {
790     return frameId.isEmpty() ? nullptr : m_identifierToFrame.get(frameId);
791 }
792
793 String InspectorPageAgent::frameId(Frame* frame)
794 {
795     if (!frame)
796         return "";
797     String identifier = m_frameToIdentifier.get(frame);
798     if (identifier.isNull()) {
799         identifier = IdentifiersFactory::createIdentifier();
800         m_frameToIdentifier.set(frame, identifier);
801         m_identifierToFrame.set(identifier, frame);
802     }
803     return identifier;
804 }
805
806 bool InspectorPageAgent::hasIdForFrame(Frame* frame) const
807 {
808     return frame && m_frameToIdentifier.contains(frame);
809 }
810
811 String InspectorPageAgent::loaderId(DocumentLoader* loader)
812 {
813     if (!loader)
814         return "";
815     String identifier = m_loaderToIdentifier.get(loader);
816     if (identifier.isNull()) {
817         identifier = IdentifiersFactory::createIdentifier();
818         m_loaderToIdentifier.set(loader, identifier);
819     }
820     return identifier;
821 }
822
823 Frame* InspectorPageAgent::findFrameWithSecurityOrigin(const String& originRawString)
824 {
825     for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
826         RefPtr<SecurityOrigin> documentOrigin = frame->document()->securityOrigin();
827         if (documentOrigin->toRawString() == originRawString)
828             return frame;
829     }
830     return nullptr;
831 }
832
833 Frame* InspectorPageAgent::assertFrame(ErrorString& errorString, const String& frameId)
834 {
835     Frame* frame = frameForId(frameId);
836     if (!frame)
837         errorString = ASCIILiteral("No frame for given id found");
838     return frame;
839 }
840
841 // static
842 DocumentLoader* InspectorPageAgent::assertDocumentLoader(ErrorString& errorString, Frame* frame)
843 {
844     FrameLoader& frameLoader = frame->loader();
845     DocumentLoader* documentLoader = frameLoader.documentLoader();
846     if (!documentLoader)
847         errorString = ASCIILiteral("No documentLoader for given frame found");
848     return documentLoader;
849 }
850
851 void InspectorPageAgent::loaderDetachedFromFrame(DocumentLoader* loader)
852 {
853     m_loaderToIdentifier.remove(loader);
854 }
855
856 void InspectorPageAgent::frameStartedLoading(Frame& frame)
857 {
858     m_frontendDispatcher->frameStartedLoading(frameId(&frame));
859 }
860
861 void InspectorPageAgent::frameStoppedLoading(Frame& frame)
862 {
863     m_frontendDispatcher->frameStoppedLoading(frameId(&frame));
864 }
865
866 void InspectorPageAgent::frameScheduledNavigation(Frame& frame, double delay)
867 {
868     m_frontendDispatcher->frameScheduledNavigation(frameId(&frame), delay);
869 }
870
871 void InspectorPageAgent::frameClearedScheduledNavigation(Frame& frame)
872 {
873     m_frontendDispatcher->frameClearedScheduledNavigation(frameId(&frame));
874 }
875
876 void InspectorPageAgent::willRunJavaScriptDialog(const String& message)
877 {
878     m_frontendDispatcher->javascriptDialogOpening(message);
879 }
880
881 void InspectorPageAgent::didRunJavaScriptDialog()
882 {
883     m_frontendDispatcher->javascriptDialogClosed();
884 }
885
886 void InspectorPageAgent::didPaint(RenderObject* renderer, const LayoutRect& rect)
887 {
888     if (!m_enabled || !m_showPaintRects)
889         return;
890
891     LayoutRect absoluteRect = LayoutRect(renderer->localToAbsoluteQuad(FloatRect(rect)).boundingBox());
892     FrameView* view = renderer->document().view();
893     
894     LayoutRect rootRect = absoluteRect;
895     if (!view->frame().isMainFrame()) {
896         IntRect rootViewRect = view->contentsToRootView(snappedIntRect(absoluteRect));
897         rootRect = view->frame().mainFrame().view()->rootViewToContents(rootViewRect);
898     }
899     
900     if (m_client->overridesShowPaintRects()) {
901         m_client->showPaintRect(rootRect);
902         return;
903     }
904
905     m_overlay->showPaintRect(rootRect);
906 }
907
908 void InspectorPageAgent::didLayout()
909 {
910     bool isFirstLayout = m_isFirstLayoutAfterOnLoad;
911     if (isFirstLayout)
912         m_isFirstLayoutAfterOnLoad = false;
913
914     if (!m_enabled)
915         return;
916
917     m_overlay->update();
918 }
919
920 void InspectorPageAgent::didScroll()
921 {
922     if (m_enabled)
923         m_overlay->update();
924 }
925
926 void InspectorPageAgent::didRecalculateStyle()
927 {
928     if (m_enabled)
929         m_overlay->update();
930 }
931
932 void InspectorPageAgent::scriptsEnabled(bool isEnabled)
933 {
934     if (m_ignoreScriptsEnabledNotification)
935         return;
936
937     m_frontendDispatcher->scriptsEnabled(isEnabled);
938 }
939
940 PassRefPtr<Inspector::Protocol::Page::Frame> InspectorPageAgent::buildObjectForFrame(Frame* frame)
941 {
942     RefPtr<Inspector::Protocol::Page::Frame> frameObject = Inspector::Protocol::Page::Frame::create()
943         .setId(frameId(frame))
944         .setLoaderId(loaderId(frame->loader().documentLoader()))
945         .setUrl(frame->document()->url().string())
946         .setMimeType(frame->loader().documentLoader()->responseMIMEType())
947         .setSecurityOrigin(frame->document()->securityOrigin()->toRawString());
948     if (frame->tree().parent())
949         frameObject->setParentId(frameId(frame->tree().parent()));
950     if (frame->ownerElement()) {
951         String name = frame->ownerElement()->getNameAttribute();
952         if (name.isEmpty())
953             name = frame->ownerElement()->getAttribute(HTMLNames::idAttr);
954         frameObject->setName(name);
955     }
956
957     return frameObject;
958 }
959
960 PassRefPtr<Inspector::Protocol::Page::FrameResourceTree> InspectorPageAgent::buildObjectForFrameTree(Frame* frame)
961 {
962     RefPtr<Inspector::Protocol::Page::Frame> frameObject = buildObjectForFrame(frame);
963     RefPtr<Inspector::Protocol::Array<Inspector::Protocol::Page::FrameResource>> subresources = Inspector::Protocol::Array<Inspector::Protocol::Page::FrameResource>::create();
964     RefPtr<Inspector::Protocol::Page::FrameResourceTree> result = Inspector::Protocol::Page::FrameResourceTree::create()
965          .setFrame(frameObject)
966          .setResources(subresources);
967
968     for (auto* cachedResource : cachedResourcesForFrame(frame)) {
969         RefPtr<Inspector::Protocol::Page::FrameResource> resourceObject = Inspector::Protocol::Page::FrameResource::create()
970             .setUrl(cachedResource->url())
971             .setType(cachedResourceTypeJson(*cachedResource))
972             .setMimeType(cachedResource->response().mimeType());
973         if (cachedResource->wasCanceled())
974             resourceObject->setCanceled(true);
975         else if (cachedResource->status() == CachedResource::LoadError)
976             resourceObject->setFailed(true);
977         String sourceMappingURL = InspectorPageAgent::sourceMapURLForResource(cachedResource);
978         if (!sourceMappingURL.isEmpty())
979             resourceObject->setSourceMapURL(sourceMappingURL);
980         subresources->addItem(resourceObject);
981     }
982
983     RefPtr<Inspector::Protocol::Array<Inspector::Protocol::Page::FrameResourceTree>> childrenArray;
984     for (Frame* child = frame->tree().firstChild(); child; child = child->tree().nextSibling()) {
985         if (!childrenArray) {
986             childrenArray = Inspector::Protocol::Array<Inspector::Protocol::Page::FrameResourceTree>::create();
987             result->setChildFrames(childrenArray);
988         }
989         childrenArray->addItem(buildObjectForFrameTree(child));
990     }
991     return result;
992 }
993
994 #if ENABLE(TOUCH_EVENTS)
995 void InspectorPageAgent::updateTouchEventEmulationInPage(bool enabled)
996 {
997     if (mainFrame())
998         mainFrame()->settings().setTouchEventEmulationEnabled(enabled);
999 }
1000 #endif
1001
1002 void InspectorPageAgent::setTouchEmulationEnabled(ErrorString& error, bool enabled)
1003 {
1004 #if ENABLE(TOUCH_EVENTS)
1005     UNUSED_PARAM(error);
1006     updateTouchEventEmulationInPage(enabled);
1007 #else
1008     error = ASCIILiteral("Touch events emulation not supported");
1009     UNUSED_PARAM(enabled);
1010 #endif
1011 }
1012
1013 void InspectorPageAgent::setEmulatedMedia(ErrorString&, const String& media)
1014 {
1015     if (media == m_emulatedMedia)
1016         return;
1017
1018     m_emulatedMedia = media;
1019     Document* document = m_page->mainFrame().document();
1020     if (document) {
1021         document->styleResolverChanged(RecalcStyleImmediately);
1022         document->updateLayout();
1023     }
1024 }
1025
1026 void InspectorPageAgent::applyEmulatedMedia(String* media)
1027 {
1028     if (!m_emulatedMedia.isEmpty())
1029         *media = m_emulatedMedia;
1030 }
1031
1032 void InspectorPageAgent::getCompositingBordersVisible(ErrorString&, bool* outParam)
1033 {
1034     *outParam = m_page->settings().showDebugBorders() || m_page->settings().showRepaintCounter();
1035 }
1036
1037 void InspectorPageAgent::setCompositingBordersVisible(ErrorString&, bool visible)
1038 {
1039     m_page->settings().setShowDebugBorders(visible);
1040     m_page->settings().setShowRepaintCounter(visible);
1041 }
1042
1043 void InspectorPageAgent::snapshotNode(ErrorString& errorString, int nodeId, String* outDataURL)
1044 {
1045     Frame* frame = mainFrame();
1046     ASSERT(frame);
1047
1048     InspectorDOMAgent* domAgent = m_instrumentingAgents->inspectorDOMAgent();
1049     ASSERT(domAgent);
1050     Node* node = domAgent->assertNode(errorString, nodeId);
1051     if (!node)
1052         return;
1053
1054     std::unique_ptr<ImageBuffer> snapshot = WebCore::snapshotNode(*frame, *node);
1055     if (!snapshot) {
1056         errorString = ASCIILiteral("Could not capture snapshot");
1057         return;
1058     }
1059
1060     *outDataURL = snapshot->toDataURL(ASCIILiteral("image/png"));
1061 }
1062
1063 void InspectorPageAgent::snapshotRect(ErrorString& errorString, int x, int y, int width, int height, const String& coordinateSystem, String* outDataURL)
1064 {
1065     Frame* frame = mainFrame();
1066     ASSERT(frame);
1067
1068     SnapshotOptions options = SnapshotOptionsNone;
1069     if (coordinateSystem == "Viewport")
1070         options |= SnapshotOptionsInViewCoordinates;
1071
1072     IntRect rectangle(x, y, width, height);
1073     std::unique_ptr<ImageBuffer> snapshot = snapshotFrameRect(*frame, rectangle, options);
1074
1075     if (!snapshot) {
1076         errorString = ASCIILiteral("Could not capture snapshot");
1077         return;
1078     }
1079
1080     *outDataURL = snapshot->toDataURL(ASCIILiteral("image/png"));
1081 }
1082
1083 void InspectorPageAgent::handleJavaScriptDialog(ErrorString& errorString, bool accept, const String* promptText)
1084 {
1085     if (!m_client->handleJavaScriptDialog(accept, promptText))
1086         errorString = ASCIILiteral("Could not handle JavaScript dialog");
1087 }
1088
1089 void InspectorPageAgent::archive(ErrorString& errorString, String* data)
1090 {
1091     Frame* frame = mainFrame();
1092     if (!frame) {
1093         errorString = ASCIILiteral("No main frame");
1094         return;
1095     }
1096
1097 #if ENABLE(WEB_ARCHIVE) && USE(CF)
1098     RefPtr<LegacyWebArchive> archive = LegacyWebArchive::create(frame);
1099     if (!archive) {
1100         errorString = ASCIILiteral("Could not create web archive for main frame");
1101         return;
1102     }
1103
1104     RetainPtr<CFDataRef> buffer = archive->rawDataRepresentation();
1105     *data = base64Encode(CFDataGetBytePtr(buffer.get()), CFDataGetLength(buffer.get()));
1106 #else
1107     UNUSED_PARAM(data);
1108     errorString = ASCIILiteral("No support for creating archives");
1109 #endif
1110 }
1111
1112 } // namespace WebCore
1113
1114 #endif // ENABLE(INSPECTOR)