2 * Copyright (C) 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
3 * Copyright (C) 2008 Matt Lilek <webkit@mattlilek.com>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
15 * its contributors may be used to endorse or promote products derived
16 * from this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
19 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
22 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 #include "InspectorController.h"
35 #include "CachedResource.h"
36 #include "CachedResourceLoader.h"
39 #include "ConsoleMessage.h"
41 #include "CookieJar.h"
42 #include "DOMWindow.h"
44 #include "DocumentLoader.h"
46 #include "FloatConversion.h"
47 #include "FloatQuad.h"
48 #include "FloatRect.h"
50 #include "FrameLoadRequest.h"
51 #include "FrameLoader.h"
52 #include "FrameTree.h"
53 #include "FrameView.h"
54 #include "GraphicsContext.h"
55 #include "HTMLFrameOwnerElement.h"
56 #include "HitTestResult.h"
57 #include "InjectedScript.h"
58 #include "InjectedScriptHost.h"
59 #include "InspectorBackend.h"
60 #include "InspectorBackendDispatcher.h"
61 #include "InspectorCSSStore.h"
62 #include "InspectorClient.h"
63 #include "InspectorDOMAgent.h"
64 #include "InspectorDOMStorageResource.h"
65 #include "InspectorDatabaseResource.h"
66 #include "InspectorDebuggerAgent.h"
67 #include "InspectorFrontend.h"
68 #include "InspectorFrontendClient.h"
69 #include "InspectorInstrumentation.h"
70 #include "InspectorProfilerAgent.h"
71 #include "InspectorResourceAgent.h"
72 #include "InspectorState.h"
73 #include "InspectorStorageAgent.h"
74 #include "InspectorTimelineAgent.h"
75 #include "InspectorValues.h"
76 #include "InspectorWorkerResource.h"
79 #include "ProgressTracker.h"
81 #include "RenderInline.h"
82 #include "ResourceRequest.h"
83 #include "ResourceResponse.h"
84 #include "ScriptCallStack.h"
85 #include "ScriptFunctionCall.h"
86 #include "ScriptObject.h"
87 #include "ScriptProfile.h"
88 #include "ScriptProfiler.h"
89 #include "ScriptSourceCode.h"
90 #include "ScriptState.h"
91 #include "SecurityOrigin.h"
93 #include "SharedBuffer.h"
94 #include "TextEncoding.h"
95 #include "TextIterator.h"
96 #include "UserGestureIndicator.h"
97 #include "WindowFeatures.h"
98 #include <wtf/text/StringConcatenate.h>
99 #include <wtf/CurrentTime.h>
100 #include <wtf/ListHashSet.h>
101 #include <wtf/RefCounted.h>
102 #include <wtf/StdLibExtras.h>
103 #include <wtf/UnusedParam.h>
106 #include "Database.h"
109 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
110 #include "InspectorApplicationCacheAgent.h"
113 #if ENABLE(FILE_SYSTEM)
114 #include "InspectorFileSystemAgent.h"
117 #if ENABLE(DOM_STORAGE)
119 #include "StorageArea.h"
126 static const char* const domNativeBreakpointType = "DOM";
127 static const char* const eventListenerNativeBreakpointType = "EventListener";
128 static const char* const xhrNativeBreakpointType = "XHR";
130 const char* const InspectorController::ElementsPanel = "elements";
131 const char* const InspectorController::ConsolePanel = "console";
132 const char* const InspectorController::ScriptsPanel = "scripts";
133 const char* const InspectorController::ProfilesPanel = "profiles";
135 const unsigned InspectorController::defaultAttachedHeight = 300;
137 static const unsigned maximumConsoleMessages = 1000;
138 static const unsigned expireConsoleMessagesStep = 100;
140 InspectorController::InspectorController(Page* page, InspectorClient* client)
141 : m_inspectedPage(page)
143 , m_openingFrontend(false)
144 , m_cssStore(new InspectorCSSStore(this))
145 , m_mainResourceIdentifier(0)
146 , m_loadEventTime(-1.0)
147 , m_domContentEventTime(-1.0)
148 , m_expiredConsoleMessageCount(0)
150 , m_previousMessage(0)
151 , m_settingsLoaded(false)
152 , m_inspectorBackend(InspectorBackend::create(this))
153 , m_inspectorBackendDispatcher(new InspectorBackendDispatcher(this))
154 , m_injectedScriptHost(InjectedScriptHost::create(this))
155 #if ENABLE(JAVASCRIPT_DEBUGGER)
156 , m_attachDebuggerWhenShown(false)
157 , m_lastBreakpointId(0)
158 , m_profilerAgent(InspectorProfilerAgent::create(this))
161 m_state = new InspectorState(client);
162 ASSERT_ARG(page, page);
163 ASSERT_ARG(client, client);
166 InspectorController::~InspectorController()
168 // These should have been cleared in inspectedPageDestroyed().
170 ASSERT(!m_inspectedPage);
171 ASSERT(!m_highlightedNode);
173 releaseFrontendLifetimeAgents();
175 m_inspectorBackend->disconnectController();
176 m_injectedScriptHost->disconnectController();
179 void InspectorController::inspectedPageDestroyed()
182 m_frontend->disconnectFromBackend();
186 #if ENABLE(JAVASCRIPT_DEBUGGER)
187 m_debuggerAgent.clear();
189 ASSERT(m_inspectedPage);
192 m_client->inspectorDestroyed();
196 bool InspectorController::enabled() const
198 if (!m_inspectedPage)
200 return m_inspectedPage->settings()->developerExtrasEnabled();
203 bool InspectorController::inspectorStartsAttached()
205 return m_state->getBoolean(InspectorState::inspectorStartsAttached);
208 void InspectorController::setInspectorStartsAttached(bool attached)
210 m_state->setBoolean(InspectorState::inspectorStartsAttached, attached);
213 void InspectorController::setInspectorAttachedHeight(long height)
215 m_state->setLong(InspectorState::inspectorAttachedHeight, height);
218 int InspectorController::inspectorAttachedHeight() const
220 return m_state->getBoolean(InspectorState::inspectorAttachedHeight);
223 bool InspectorController::searchingForNodeInPage() const
225 return m_state->getBoolean(InspectorState::searchingForNode);
228 void InspectorController::getInspectorState(RefPtr<InspectorObject>* state)
230 #if ENABLE(JAVASCRIPT_DEBUGGER)
232 m_state->setLong(InspectorState::pauseOnExceptionsState, m_debuggerAgent->pauseOnExceptionsState());
234 *state = m_state->generateStateObjectForFrontend();
237 void InspectorController::restoreInspectorStateFromCookie(const String& inspectorStateCookie)
239 m_state->restoreFromInspectorCookie(inspectorStateCookie);
240 if (m_state->getBoolean(InspectorState::timelineProfilerEnabled))
241 startTimelineProfiler();
244 void InspectorController::inspect(Node* node)
251 if (node->nodeType() != Node::ELEMENT_NODE && node->nodeType() != Node::DOCUMENT_NODE)
252 node = node->parentNode();
253 m_nodeToFocus = node;
261 void InspectorController::focusNode()
267 ASSERT(m_nodeToFocus);
269 long id = m_domAgent->pushNodePathToFrontend(m_nodeToFocus.get());
270 m_frontend->updateFocusedNode(id);
274 void InspectorController::highlight(Node* node)
278 ASSERT_ARG(node, node);
279 m_highlightedNode = node;
280 m_client->highlight(node);
283 void InspectorController::highlightDOMNode(long nodeId)
286 if (m_domAgent && (node = m_domAgent->nodeForId(nodeId)))
290 void InspectorController::highlightFrame(unsigned long frameId)
292 Frame* mainFrame = m_inspectedPage->mainFrame();
293 for (Frame* frame = mainFrame; frame; frame = frame->tree()->traverseNext(mainFrame)) {
294 if (reinterpret_cast<uintptr_t>(frame) == frameId && frame->ownerElement()) {
295 highlight(frame->ownerElement());
301 void InspectorController::hideHighlight()
305 m_highlightedNode = 0;
306 m_client->hideHighlight();
309 void InspectorController::setConsoleMessagesEnabled(bool enabled, bool* newState)
312 setConsoleMessagesEnabled(enabled);
315 void InspectorController::setConsoleMessagesEnabled(bool enabled)
317 m_state->setBoolean(InspectorState::consoleMessagesEnabled, enabled);
321 if (m_expiredConsoleMessageCount)
322 m_frontend->updateConsoleMessageExpiredCount(m_expiredConsoleMessageCount);
323 unsigned messageCount = m_consoleMessages.size();
324 for (unsigned i = 0; i < messageCount; ++i)
325 m_consoleMessages[i]->addToFrontend(m_frontend.get(), m_injectedScriptHost.get());
328 void InspectorController::addMessageToConsole(MessageSource source, MessageType type, MessageLevel level, ScriptCallStack* callStack, const String& message)
333 bool storeStackTrace = type == TraceMessageType || type == UncaughtExceptionMessageType || type == AssertMessageType;
334 addConsoleMessage(new ConsoleMessage(source, type, level, message, callStack, m_groupLevel, storeStackTrace));
337 void InspectorController::addMessageToConsole(MessageSource source, MessageType type, MessageLevel level, const String& message, unsigned lineNumber, const String& sourceID)
342 addConsoleMessage(new ConsoleMessage(source, type, level, message, lineNumber, sourceID, m_groupLevel));
345 void InspectorController::addConsoleMessage(PassOwnPtr<ConsoleMessage> consoleMessage)
348 ASSERT_ARG(consoleMessage, consoleMessage);
350 if (m_previousMessage && m_previousMessage->isEqual(consoleMessage.get())) {
351 m_previousMessage->incrementCount();
352 if (m_state->getBoolean(InspectorState::consoleMessagesEnabled) && m_frontend)
353 m_previousMessage->updateRepeatCountInConsole(m_frontend.get());
355 m_previousMessage = consoleMessage.get();
356 m_consoleMessages.append(consoleMessage);
357 if (m_state->getBoolean(InspectorState::consoleMessagesEnabled) && m_frontend)
358 m_previousMessage->addToFrontend(m_frontend.get(), m_injectedScriptHost.get());
361 if (!m_frontend && m_consoleMessages.size() >= maximumConsoleMessages) {
362 m_expiredConsoleMessageCount += expireConsoleMessagesStep;
363 m_consoleMessages.remove(0, expireConsoleMessagesStep);
367 void InspectorController::clearConsoleMessages()
369 m_consoleMessages.clear();
370 m_expiredConsoleMessageCount = 0;
371 m_previousMessage = 0;
373 m_injectedScriptHost->releaseWrapperObjectGroup(0 /* release the group in all scripts */, "console");
375 m_domAgent->releaseDanglingNodes();
377 m_frontend->consoleMessagesCleared();
380 void InspectorController::startGroup(MessageSource source, ScriptCallStack* callStack, bool collapsed)
384 addConsoleMessage(new ConsoleMessage(source, collapsed ? StartGroupCollapsedMessageType : StartGroupMessageType, LogMessageLevel, String(), callStack, m_groupLevel));
387 void InspectorController::endGroup(MessageSource source, unsigned lineNumber, const String& sourceURL)
394 addConsoleMessage(new ConsoleMessage(source, EndGroupMessageType, LogMessageLevel, String(), lineNumber, sourceURL, m_groupLevel));
397 void InspectorController::markTimeline(const String& message)
400 timelineAgent()->didMarkTimeline(message);
403 void InspectorController::mouseDidMoveOverElement(const HitTestResult& result, unsigned)
405 if (!enabled() || !searchingForNodeInPage())
408 Node* node = result.innerNode();
409 while (node && node->nodeType() == Node::TEXT_NODE)
410 node = node->parentNode();
415 void InspectorController::handleMousePress()
420 ASSERT(searchingForNodeInPage());
421 if (!m_highlightedNode)
424 RefPtr<Node> node = m_highlightedNode;
425 setSearchingForNode(false);
429 void InspectorController::setInspectorFrontendClient(PassOwnPtr<InspectorFrontendClient> client)
431 ASSERT(!m_inspectorFrontendClient);
432 m_inspectorFrontendClient = client;
435 void InspectorController::inspectedWindowScriptObjectCleared(Frame* frame)
437 // If the page is supposed to serve as InspectorFrontend notify inspetor frontend
438 // client that it's cleared so that the client can expose inspector bindings.
439 if (m_inspectorFrontendClient && frame == m_inspectedPage->mainFrame())
440 m_inspectorFrontendClient->windowObjectCleared();
443 if (m_frontend && frame == m_inspectedPage->mainFrame())
444 m_injectedScriptHost->discardInjectedScripts();
445 if (m_scriptsToEvaluateOnLoad.size()) {
446 ScriptState* scriptState = mainWorldScriptState(frame);
447 for (Vector<String>::iterator it = m_scriptsToEvaluateOnLoad.begin();
448 it != m_scriptsToEvaluateOnLoad.end(); ++it) {
449 m_injectedScriptHost->injectScript(*it, scriptState);
453 if (!m_inspectorExtensionAPI.isEmpty())
454 m_injectedScriptHost->injectScript(m_inspectorExtensionAPI, mainWorldScriptState(frame));
457 void InspectorController::setSearchingForNode(bool enabled)
459 if (searchingForNodeInPage() == enabled)
461 m_state->setBoolean(InspectorState::searchingForNode, enabled);
466 void InspectorController::setSearchingForNode(bool enabled, bool* newState)
469 setSearchingForNode(enabled);
472 void InspectorController::setMonitoringXHREnabled(bool enabled, bool* newState)
475 m_state->setBoolean(InspectorState::monitoringXHR, enabled);
478 void InspectorController::connectFrontend()
480 m_openingFrontend = false;
481 releaseFrontendLifetimeAgents();
482 m_frontend = new InspectorFrontend(m_client);
483 m_domAgent = InspectorDOMAgent::create(m_cssStore.get(), m_frontend.get());
484 m_resourceAgent = InspectorResourceAgent::create(m_inspectedPage, m_frontend.get());
487 m_storageAgent = InspectorStorageAgent::create(m_frontend.get());
491 m_timelineAgent->resetFrontendProxyObject(m_frontend.get());
493 // Initialize Web Inspector title.
494 m_frontend->inspectedURLChanged(m_inspectedPage->mainFrame()->loader()->url().string());
496 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
497 m_applicationCacheAgent = new InspectorApplicationCacheAgent(this, m_frontend.get());
500 #if ENABLE(FILE_SYSTEM)
501 m_fileSystemAgent = InspectorFileSystemAgent::create(this, m_frontend.get());
504 if (!InspectorInstrumentation::hasFrontends())
505 ScriptController::setCaptureCallStackForUncaughtExceptions(true);
506 InspectorInstrumentation::frontendCreated();
509 void InspectorController::reuseFrontend()
516 void InspectorController::show()
521 if (m_openingFrontend)
525 m_frontend->bringToFront();
527 m_openingFrontend = true;
528 m_client->openInspectorFrontend(this);
532 void InspectorController::showPanel(const String& panel)
540 m_showAfterVisible = panel;
543 m_frontend->showPanel(panel);
546 void InspectorController::close()
550 m_frontend->disconnectFromBackend();
551 disconnectFrontend();
554 void InspectorController::disconnectFrontend()
561 InspectorInstrumentation::frontendDeleted();
562 if (!InspectorInstrumentation::hasFrontends())
563 ScriptController::setCaptureCallStackForUncaughtExceptions(false);
565 #if ENABLE(JAVASCRIPT_DEBUGGER)
566 // If the window is being closed with the debugger enabled,
567 // remember this state to re-enable debugger on the next window
569 bool debuggerWasEnabled = debuggerEnabled();
571 m_attachDebuggerWhenShown = debuggerWasEnabled;
572 clearNativeBreakpoints();
574 setSearchingForNode(false);
575 unbindAllResources();
576 stopTimelineProfiler();
580 #if ENABLE(JAVASCRIPT_DEBUGGER)
581 m_profilerAgent->setFrontend(0);
582 m_profilerAgent->stopUserInitiatedProfiling();
585 releaseFrontendLifetimeAgents();
586 m_timelineAgent.clear();
589 void InspectorController::releaseFrontendLifetimeAgents()
591 m_resourceAgent.clear();
593 // m_domAgent is RefPtr. Remove DOM listeners first to ensure that there are
594 // no references to the DOM agent from the DOM tree.
601 m_storageAgent->clearFrontend();
602 m_storageAgent.clear();
605 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
606 m_applicationCacheAgent.clear();
609 #if ENABLE(FILE_SYSTEM)
610 if (m_fileSystemAgent)
611 m_fileSystemAgent->stop();
612 m_fileSystemAgent.clear();
616 void InspectorController::populateScriptObjects()
622 if (!m_showAfterVisible.isEmpty()) {
623 showPanel(m_showAfterVisible);
624 m_showAfterVisible = "";
627 #if ENABLE(JAVASCRIPT_DEBUGGER)
628 if (m_profilerAgent->enabled())
629 m_frontend->profilerWasEnabled();
632 if (m_domContentEventTime != -1.0)
633 m_frontend->domContentEventFired(m_domContentEventTime);
634 if (m_loadEventTime != -1.0)
635 m_frontend->loadEventFired(m_loadEventTime);
637 m_domAgent->setDocument(m_inspectedPage->mainFrame()->document());
643 DatabaseResourcesMap::iterator databasesEnd = m_databaseResources.end();
644 for (DatabaseResourcesMap::iterator it = m_databaseResources.begin(); it != databasesEnd; ++it)
645 it->second->bind(m_frontend.get());
647 #if ENABLE(DOM_STORAGE)
648 DOMStorageResourcesMap::iterator domStorageEnd = m_domStorageResources.end();
649 for (DOMStorageResourcesMap::iterator it = m_domStorageResources.begin(); it != domStorageEnd; ++it)
650 it->second->bind(m_frontend.get());
653 WorkersMap::iterator workersEnd = m_workers.end();
654 for (WorkersMap::iterator it = m_workers.begin(); it != workersEnd; ++it) {
655 InspectorWorkerResource* worker = it->second.get();
656 m_frontend->didCreateWorker(worker->id(), worker->url(), worker->isSharedWorker());
660 // Dispatch pending frontend commands
661 for (Vector<pair<long, String> >::iterator it = m_pendingEvaluateTestCommands.begin(); it != m_pendingEvaluateTestCommands.end(); ++it)
662 m_frontend->evaluateForTestInFrontend((*it).first, (*it).second);
663 m_pendingEvaluateTestCommands.clear();
669 void InspectorController::restoreDebugger()
672 #if ENABLE(JAVASCRIPT_DEBUGGER)
673 if (InspectorDebuggerAgent::isDebuggerAlwaysEnabled())
674 enableDebuggerFromFrontend(false);
676 if (m_state->getBoolean(InspectorState::debuggerAlwaysEnabled) || m_attachDebuggerWhenShown)
682 void InspectorController::restoreProfiler()
685 #if ENABLE(JAVASCRIPT_DEBUGGER)
686 m_profilerAgent->setFrontend(m_frontend.get());
687 if (!ScriptProfiler::isProfilerAlwaysEnabled() && m_state->getBoolean(InspectorState::profilerAlwaysEnabled))
692 void InspectorController::unbindAllResources()
695 DatabaseResourcesMap::iterator databasesEnd = m_databaseResources.end();
696 for (DatabaseResourcesMap::iterator it = m_databaseResources.begin(); it != databasesEnd; ++it)
697 it->second->unbind();
699 #if ENABLE(DOM_STORAGE)
700 DOMStorageResourcesMap::iterator domStorageEnd = m_domStorageResources.end();
701 for (DOMStorageResourcesMap::iterator it = m_domStorageResources.begin(); it != domStorageEnd; ++it)
702 it->second->unbind();
705 m_timelineAgent->reset();
708 void InspectorController::didCommitLoad(DocumentLoader* loader)
714 m_resourceAgent->didCommitLoad(loader);
716 ASSERT(m_inspectedPage);
718 if (loader->frame() == m_inspectedPage->mainFrame()) {
720 m_frontend->inspectedURLChanged(loader->url().string());
722 m_injectedScriptHost->discardInjectedScripts();
723 clearConsoleMessages();
728 #if ENABLE(JAVASCRIPT_DEBUGGER)
730 m_debuggerAgent->clearForPageNavigation();
732 clearNativeBreakpoints();
735 #if ENABLE(JAVASCRIPT_DEBUGGER) && USE(JSC)
736 m_profilerAgent->resetState();
739 // unbindAllResources should be called before database and DOM storage
740 // resources are cleared so that it has a chance to unbind them.
741 unbindAllResources();
752 m_databaseResources.clear();
754 #if ENABLE(DOM_STORAGE)
755 m_domStorageResources.clear();
759 m_mainResourceIdentifier = 0;
760 m_frontend->didCommitLoad();
761 m_domAgent->setDocument(m_inspectedPage->mainFrame()->document());
766 void InspectorController::frameDetachedFromParent(Frame* rootFrame)
772 m_resourceAgent->frameDetachedFromParent(rootFrame);
775 void InspectorController::didLoadResourceFromMemoryCache(DocumentLoader* loader, const CachedResource* cachedResource)
780 ensureSettingsLoaded();
783 m_resourceAgent->didLoadResourceFromMemoryCache(loader, cachedResource);
786 void InspectorController::identifierForInitialRequest(unsigned long identifier, DocumentLoader* loader, const ResourceRequest& request)
790 ASSERT(m_inspectedPage);
792 bool isMainResource = isMainResourceLoader(loader, request.url());
794 m_mainResourceIdentifier = identifier;
796 ensureSettingsLoaded();
799 m_resourceAgent->identifierForInitialRequest(identifier, request.url(), loader);
802 void InspectorController::mainResourceFiredDOMContentEvent(DocumentLoader* loader, const KURL& url)
804 if (!enabled() || !isMainResourceLoader(loader, url))
807 m_domContentEventTime = currentTime();
809 m_timelineAgent->didMarkDOMContentEvent();
811 m_frontend->domContentEventFired(m_domContentEventTime);
814 void InspectorController::mainResourceFiredLoadEvent(DocumentLoader* loader, const KURL& url)
816 if (!enabled() || !isMainResourceLoader(loader, url))
819 m_loadEventTime = currentTime();
821 m_timelineAgent->didMarkLoadEvent();
823 m_frontend->loadEventFired(m_loadEventTime);
826 bool InspectorController::isMainResourceLoader(DocumentLoader* loader, const KURL& requestUrl)
828 return loader->frame() == m_inspectedPage->mainFrame() && requestUrl == loader->requestURL();
831 void InspectorController::willSendRequest(unsigned long identifier, ResourceRequest& request, const ResourceResponse& redirectResponse)
836 request.setReportLoadTiming(true);
837 // Only enable raw headers if front-end is attached, as otherwise we may lack
838 // permissions to fetch the headers.
840 request.setReportRawHeaders(true);
842 bool isMainResource = m_mainResourceIdentifier == identifier;
845 m_timelineAgent->willSendResourceRequest(identifier, isMainResource, request);
848 m_resourceAgent->willSendRequest(identifier, request, redirectResponse);
851 void InspectorController::markResourceAsCached(unsigned long identifier)
857 m_resourceAgent->markResourceAsCached(identifier);
860 void InspectorController::didReceiveResponse(unsigned long identifier, DocumentLoader* loader, const ResourceResponse& response)
866 m_resourceAgent->didReceiveResponse(identifier, loader, response);
868 if (response.httpStatusCode() >= 400) {
869 String message = makeString("Failed to load resource: the server responded with a status of ", String::number(response.httpStatusCode()), " (", response.httpStatusText(), ')');
870 addMessageToConsole(OtherMessageSource, LogMessageType, ErrorMessageLevel, message, 0, response.url().string());
874 void InspectorController::didReceiveContentLength(unsigned long identifier, int lengthReceived)
880 m_resourceAgent->didReceiveContentLength(identifier, lengthReceived);
883 void InspectorController::didFinishLoading(unsigned long identifier, double finishTime)
889 m_timelineAgent->didFinishLoadingResource(identifier, false, finishTime);
892 m_resourceAgent->didFinishLoading(identifier, finishTime);
895 void InspectorController::didFailLoading(unsigned long identifier, const ResourceError& error)
901 m_timelineAgent->didFinishLoadingResource(identifier, true, 0);
903 String message = "Failed to load resource";
904 if (!error.localizedDescription().isEmpty())
905 message += ": " + error.localizedDescription();
906 addMessageToConsole(OtherMessageSource, LogMessageType, ErrorMessageLevel, message, 0, error.failingURL());
909 m_resourceAgent->didFailLoading(identifier, error);
912 void InspectorController::resourceRetrievedByXMLHttpRequest(unsigned long identifier, const String& sourceString, const String& url, const String& sendURL, unsigned sendLineNumber)
917 if (m_state->getBoolean(InspectorState::monitoringXHR))
918 addMessageToConsole(JSMessageSource, LogMessageType, LogMessageLevel, "XHR finished loading: \"" + url + "\".", sendLineNumber, sendURL);
921 m_resourceAgent->setOverrideContent(identifier, sourceString, "XHR");
924 void InspectorController::scriptImported(unsigned long identifier, const String& sourceString)
930 m_resourceAgent->setOverrideContent(identifier, sourceString, "Script");
933 void InspectorController::ensureSettingsLoaded()
935 if (m_settingsLoaded)
937 m_settingsLoaded = true;
939 m_state->loadFromSettings();
941 if (m_state->getBoolean(InspectorState::resourceTrackingAlwaysEnabled))
942 m_state->setBoolean(InspectorState::resourceTrackingEnabled, true);
945 void InspectorController::startTimelineProfiler()
953 m_timelineAgent = new InspectorTimelineAgent(m_frontend.get());
955 m_frontend->timelineProfilerWasStarted();
957 m_state->setBoolean(InspectorState::timelineProfilerEnabled, true);
960 void InspectorController::stopTimelineProfiler()
965 if (!m_timelineAgent)
970 m_frontend->timelineProfilerWasStopped();
972 m_state->setBoolean(InspectorState::timelineProfilerEnabled, false);
976 class PostWorkerNotificationToFrontendTask : public ScriptExecutionContext::Task {
978 static PassOwnPtr<PostWorkerNotificationToFrontendTask> create(PassRefPtr<InspectorWorkerResource> worker, InspectorController::WorkerAction action)
980 return new PostWorkerNotificationToFrontendTask(worker, action);
984 PostWorkerNotificationToFrontendTask(PassRefPtr<InspectorWorkerResource> worker, InspectorController::WorkerAction action)
990 virtual void performTask(ScriptExecutionContext* scriptContext)
992 if (InspectorController* inspector = scriptContext->inspectorController())
993 inspector->postWorkerNotificationToFrontend(*m_worker, m_action);
997 RefPtr<InspectorWorkerResource> m_worker;
998 InspectorController::WorkerAction m_action;
1001 void InspectorController::postWorkerNotificationToFrontend(const InspectorWorkerResource& worker, InspectorController::WorkerAction action)
1006 case InspectorController::WorkerCreated:
1007 m_frontend->didCreateWorker(worker.id(), worker.url(), worker.isSharedWorker());
1009 case InspectorController::WorkerDestroyed:
1010 m_frontend->didDestroyWorker(worker.id());
1015 void InspectorController::didCreateWorker(intptr_t id, const String& url, bool isSharedWorker)
1020 RefPtr<InspectorWorkerResource> workerResource(InspectorWorkerResource::create(id, url, isSharedWorker));
1021 m_workers.set(id, workerResource);
1022 if (m_inspectedPage && m_frontend)
1023 m_inspectedPage->mainFrame()->document()->postTask(PostWorkerNotificationToFrontendTask::create(workerResource, InspectorController::WorkerCreated));
1026 void InspectorController::didDestroyWorker(intptr_t id)
1031 WorkersMap::iterator workerResource = m_workers.find(id);
1032 if (workerResource == m_workers.end())
1034 if (m_inspectedPage && m_frontend)
1035 m_inspectedPage->mainFrame()->document()->postTask(PostWorkerNotificationToFrontendTask::create(workerResource->second, InspectorController::WorkerDestroyed));
1036 m_workers.remove(workerResource);
1038 #endif // ENABLE(WORKERS)
1040 #if ENABLE(DATABASE)
1041 void InspectorController::selectDatabase(Database* database)
1046 for (DatabaseResourcesMap::iterator it = m_databaseResources.begin(); it != m_databaseResources.end(); ++it) {
1047 if (it->second->database() == database) {
1048 m_frontend->selectDatabase(it->first);
1054 Database* InspectorController::databaseForId(long databaseId)
1056 DatabaseResourcesMap::iterator it = m_databaseResources.find(databaseId);
1057 if (it == m_databaseResources.end())
1059 return it->second->database();
1062 void InspectorController::didOpenDatabase(PassRefPtr<Database> database, const String& domain, const String& name, const String& version)
1067 RefPtr<InspectorDatabaseResource> resource = InspectorDatabaseResource::create(database, domain, name, version);
1069 m_databaseResources.set(resource->id(), resource);
1071 // Resources are only bound while visible.
1073 resource->bind(m_frontend.get());
1077 void InspectorController::getCookies(RefPtr<InspectorArray>* cookies, WTF::String* cookiesString)
1079 // If we can get raw cookies.
1080 ListHashSet<Cookie> rawCookiesList;
1082 // If we can't get raw cookies - fall back to String representation
1083 String stringCookiesList;
1085 // Return value to getRawCookies should be the same for every call because
1086 // the return value is platform/network backend specific, and the call will
1087 // always return the same true/false value.
1088 bool rawCookiesImplemented = false;
1090 for (Frame* frame = m_inspectedPage->mainFrame(); frame; frame = frame->tree()->traverseNext(m_inspectedPage->mainFrame())) {
1091 Document* document = frame->document();
1092 const CachedResourceLoader::DocumentResourceMap& allResources = document->cachedResourceLoader()->allCachedResources();
1093 CachedResourceLoader::DocumentResourceMap::const_iterator end = allResources.end();
1094 for (CachedResourceLoader::DocumentResourceMap::const_iterator it = allResources.begin(); it != end; ++it) {
1095 Vector<Cookie> docCookiesList;
1096 rawCookiesImplemented = getRawCookies(document, KURL(ParsedURLString, it->second->url()), docCookiesList);
1098 if (!rawCookiesImplemented) {
1099 // FIXME: We need duplication checking for the String representation of cookies.
1100 ExceptionCode ec = 0;
1101 stringCookiesList += document->cookie(ec);
1102 // Exceptions are thrown by cookie() in sandboxed frames. That won't happen here
1103 // because "document" is the document of the main frame of the page.
1106 int cookiesSize = docCookiesList.size();
1107 for (int i = 0; i < cookiesSize; i++) {
1108 if (!rawCookiesList.contains(docCookiesList[i]))
1109 rawCookiesList.add(docCookiesList[i]);
1115 if (rawCookiesImplemented)
1116 *cookies = buildArrayForCookies(rawCookiesList);
1118 *cookiesString = stringCookiesList;
1121 PassRefPtr<InspectorArray> InspectorController::buildArrayForCookies(ListHashSet<Cookie>& cookiesList)
1123 RefPtr<InspectorArray> cookies = InspectorArray::create();
1125 ListHashSet<Cookie>::iterator end = cookiesList.end();
1126 ListHashSet<Cookie>::iterator it = cookiesList.begin();
1127 for (int i = 0; it != end; ++it, i++)
1128 cookies->pushObject(buildObjectForCookie(*it));
1133 PassRefPtr<InspectorObject> InspectorController::buildObjectForCookie(const Cookie& cookie)
1135 RefPtr<InspectorObject> value = InspectorObject::create();
1136 value->setString("name", cookie.name);
1137 value->setString("value", cookie.value);
1138 value->setString("domain", cookie.domain);
1139 value->setString("path", cookie.path);
1140 value->setNumber("expires", cookie.expires);
1141 value->setNumber("size", (cookie.name.length() + cookie.value.length()));
1142 value->setBoolean("httpOnly", cookie.httpOnly);
1143 value->setBoolean("secure", cookie.secure);
1144 value->setBoolean("session", cookie.session);
1148 void InspectorController::deleteCookie(const String& cookieName, const String& domain)
1150 for (Frame* frame = m_inspectedPage->mainFrame(); frame; frame = frame->tree()->traverseNext(m_inspectedPage->mainFrame())) {
1151 Document* document = frame->document();
1152 if (document->url().host() != domain)
1154 const CachedResourceLoader::DocumentResourceMap& allResources = document->cachedResourceLoader()->allCachedResources();
1155 CachedResourceLoader::DocumentResourceMap::const_iterator end = allResources.end();
1156 for (CachedResourceLoader::DocumentResourceMap::const_iterator it = allResources.begin(); it != end; ++it)
1157 WebCore::deleteCookie(document, KURL(ParsedURLString, it->second->url()), cookieName);
1161 #if ENABLE(DOM_STORAGE)
1162 void InspectorController::didUseDOMStorage(StorageArea* storageArea, bool isLocalStorage, Frame* frame)
1167 DOMStorageResourcesMap::iterator domStorageEnd = m_domStorageResources.end();
1168 for (DOMStorageResourcesMap::iterator it = m_domStorageResources.begin(); it != domStorageEnd; ++it)
1169 if (it->second->isSameHostAndType(frame, isLocalStorage))
1172 RefPtr<Storage> domStorage = Storage::create(frame, storageArea);
1173 RefPtr<InspectorDOMStorageResource> resource = InspectorDOMStorageResource::create(domStorage.get(), isLocalStorage, frame);
1175 m_domStorageResources.set(resource->id(), resource);
1177 // Resources are only bound while visible.
1179 resource->bind(m_frontend.get());
1182 void InspectorController::selectDOMStorage(Storage* storage)
1188 Frame* frame = storage->frame();
1189 ExceptionCode ec = 0;
1190 bool isLocalStorage = (frame->domWindow()->localStorage(ec) == storage && !ec);
1191 long storageResourceId = 0;
1192 DOMStorageResourcesMap::iterator domStorageEnd = m_domStorageResources.end();
1193 for (DOMStorageResourcesMap::iterator it = m_domStorageResources.begin(); it != domStorageEnd; ++it) {
1194 if (it->second->isSameHostAndType(frame, isLocalStorage)) {
1195 storageResourceId = it->first;
1199 if (storageResourceId)
1200 m_frontend->selectDOMStorage(storageResourceId);
1203 void InspectorController::getDOMStorageEntries(long storageId, RefPtr<InspectorArray>* entries)
1205 InspectorDOMStorageResource* storageResource = getDOMStorageResourceForId(storageId);
1206 if (storageResource) {
1207 storageResource->startReportingChangesToFrontend();
1208 Storage* domStorage = storageResource->domStorage();
1209 for (unsigned i = 0; i < domStorage->length(); ++i) {
1210 String name(domStorage->key(i));
1211 String value(domStorage->getItem(name));
1212 RefPtr<InspectorArray> entry = InspectorArray::create();
1213 entry->pushString(name);
1214 entry->pushString(value);
1215 (*entries)->pushArray(entry);
1220 void InspectorController::setDOMStorageItem(long storageId, const String& key, const String& value, bool* success)
1222 InspectorDOMStorageResource* storageResource = getDOMStorageResourceForId(storageId);
1223 if (storageResource) {
1224 ExceptionCode exception = 0;
1225 storageResource->domStorage()->setItem(key, value, exception);
1226 *success = !exception;
1230 void InspectorController::removeDOMStorageItem(long storageId, const String& key, bool* success)
1232 InspectorDOMStorageResource* storageResource = getDOMStorageResourceForId(storageId);
1233 if (storageResource) {
1234 storageResource->domStorage()->removeItem(key);
1239 InspectorDOMStorageResource* InspectorController::getDOMStorageResourceForId(long storageId)
1241 DOMStorageResourcesMap::iterator it = m_domStorageResources.find(storageId);
1242 if (it == m_domStorageResources.end())
1244 return it->second.get();
1248 #if ENABLE(WEB_SOCKETS)
1249 void InspectorController::didCreateWebSocket(unsigned long identifier, const KURL& requestURL, const KURL& documentURL)
1253 ASSERT(m_inspectedPage);
1255 if (m_resourceAgent)
1256 m_resourceAgent->didCreateWebSocket(identifier, requestURL);
1257 UNUSED_PARAM(documentURL);
1260 void InspectorController::willSendWebSocketHandshakeRequest(unsigned long identifier, const WebSocketHandshakeRequest& request)
1262 if (m_resourceAgent)
1263 m_resourceAgent->willSendWebSocketHandshakeRequest(identifier, request);
1266 void InspectorController::didReceiveWebSocketHandshakeResponse(unsigned long identifier, const WebSocketHandshakeResponse& response)
1268 if (m_resourceAgent)
1269 m_resourceAgent->didReceiveWebSocketHandshakeResponse(identifier, response);
1272 void InspectorController::didCloseWebSocket(unsigned long identifier)
1274 if (m_resourceAgent)
1275 m_resourceAgent->didCloseWebSocket(identifier);
1277 #endif // ENABLE(WEB_SOCKETS)
1279 #if ENABLE(JAVASCRIPT_DEBUGGER)
1280 void InspectorController::addProfile(PassRefPtr<ScriptProfile> prpProfile, unsigned lineNumber, const String& sourceURL)
1284 m_profilerAgent->addProfile(prpProfile, lineNumber, sourceURL);
1287 void InspectorController::addProfileFinishedMessageToConsole(PassRefPtr<ScriptProfile> prpProfile, unsigned lineNumber, const String& sourceURL)
1289 m_profilerAgent->addProfileFinishedMessageToConsole(prpProfile, lineNumber, sourceURL);
1292 void InspectorController::addStartProfilingMessageToConsole(const String& title, unsigned lineNumber, const String& sourceURL)
1294 m_profilerAgent->addStartProfilingMessageToConsole(title, lineNumber, sourceURL);
1298 bool InspectorController::isRecordingUserInitiatedProfile() const
1300 return m_profilerAgent->isRecordingUserInitiatedProfile();
1303 String InspectorController::getCurrentUserInitiatedProfileName(bool incrementProfileNumber)
1305 return m_profilerAgent->getCurrentUserInitiatedProfileName(incrementProfileNumber);
1308 void InspectorController::startUserInitiatedProfiling()
1312 m_profilerAgent->startUserInitiatedProfiling();
1315 void InspectorController::stopUserInitiatedProfiling()
1319 m_profilerAgent->stopUserInitiatedProfiling();
1322 bool InspectorController::profilerEnabled() const
1324 return enabled() && m_profilerAgent->enabled();
1327 void InspectorController::enableProfiler(bool always, bool skipRecompile)
1330 m_state->setBoolean(InspectorState::profilerAlwaysEnabled, true);
1331 m_profilerAgent->enable(skipRecompile);
1334 void InspectorController::disableProfiler(bool always)
1337 m_state->setBoolean(InspectorState::profilerAlwaysEnabled, false);
1338 m_profilerAgent->disable();
1342 #if ENABLE(JAVASCRIPT_DEBUGGER)
1343 void InspectorController::enableDebuggerFromFrontend(bool always)
1345 ASSERT(!debuggerEnabled());
1347 m_state->setBoolean(InspectorState::debuggerAlwaysEnabled, true);
1349 ASSERT(m_inspectedPage);
1351 m_debuggerAgent = InspectorDebuggerAgent::create(this, m_frontend.get());
1353 m_frontend->debuggerWasEnabled();
1356 void InspectorController::enableDebugger()
1361 if (debuggerEnabled())
1365 m_attachDebuggerWhenShown = true;
1367 m_frontend->attachDebuggerWhenShown();
1368 m_attachDebuggerWhenShown = false;
1372 void InspectorController::disableDebugger(bool always)
1378 m_state->setBoolean(InspectorState::debuggerAlwaysEnabled, false);
1380 ASSERT(m_inspectedPage);
1382 m_debuggerAgent.clear();
1384 m_attachDebuggerWhenShown = false;
1387 m_frontend->debuggerWasDisabled();
1390 void InspectorController::resume()
1392 if (m_debuggerAgent)
1393 m_debuggerAgent->resume();
1396 void InspectorController::setNativeBreakpoint(PassRefPtr<InspectorObject> breakpoint, String* breakpointId)
1400 if (!breakpoint->getString("type", &type))
1402 RefPtr<InspectorObject> condition = breakpoint->getObject("condition");
1405 if (type == xhrNativeBreakpointType) {
1407 if (!condition->getString("url", &url))
1409 *breakpointId = String::number(++m_lastBreakpointId);
1410 m_XHRBreakpoints.set(*breakpointId, url);
1411 m_nativeBreakpoints.set(*breakpointId, type);
1412 } else if (type == eventListenerNativeBreakpointType) {
1414 if (!condition->getString("eventName", &eventName))
1416 if (m_eventListenerBreakpoints.contains(eventName))
1418 *breakpointId = eventName;
1419 m_eventListenerBreakpoints.add(eventName);
1420 m_nativeBreakpoints.set(*breakpointId, type);
1421 } else if (type == domNativeBreakpointType) {
1424 double nodeIdNumber;
1425 if (!condition->getNumber("nodeId", &nodeIdNumber))
1427 double domBreakpointTypeNumber;
1428 if (!condition->getNumber("type", &domBreakpointTypeNumber))
1430 long nodeId = (long) nodeIdNumber;
1431 long domBreakpointType = (long) domBreakpointTypeNumber;
1432 *breakpointId = m_domAgent->setDOMBreakpoint(nodeId, domBreakpointType);
1433 if (!breakpointId->isEmpty())
1434 m_nativeBreakpoints.set(*breakpointId, type);
1438 void InspectorController::removeNativeBreakpoint(const String& breakpointId)
1440 String type = m_nativeBreakpoints.take(breakpointId);
1441 if (type == xhrNativeBreakpointType)
1442 m_XHRBreakpoints.remove(breakpointId);
1443 else if (type == eventListenerNativeBreakpointType)
1444 m_eventListenerBreakpoints.remove(breakpointId);
1445 else if (type == domNativeBreakpointType) {
1447 m_domAgent->removeDOMBreakpoint(breakpointId);
1451 String InspectorController::findEventListenerBreakpoint(const String& eventName)
1453 return m_eventListenerBreakpoints.contains(eventName) ? eventName : "";
1456 String InspectorController::findXHRBreakpoint(const String& url)
1458 for (HashMap<String, String>::iterator it = m_XHRBreakpoints.begin(); it != m_XHRBreakpoints.end(); ++it) {
1459 if (url.contains(it->second))
1465 void InspectorController::clearNativeBreakpoints()
1467 m_nativeBreakpoints.clear();
1468 m_eventListenerBreakpoints.clear();
1469 m_XHRBreakpoints.clear();
1470 m_lastBreakpointId = 0;
1474 void InspectorController::evaluateForTestInFrontend(long callId, const String& script)
1477 m_frontend->evaluateForTestInFrontend(callId, script);
1479 m_pendingEvaluateTestCommands.append(pair<long, String>(callId, script));
1482 void InspectorController::didEvaluateForTestInFrontend(long callId, const String& jsonResult)
1484 ScriptState* scriptState = scriptStateFromPage(debuggerWorld(), m_inspectedPage);
1485 ScriptObject window;
1486 ScriptGlobalObject::get(scriptState, "window", window);
1487 ScriptFunctionCall function(window, "didEvaluateForTestInFrontend");
1488 function.appendArgument(callId);
1489 function.appendArgument(jsonResult);
1493 #if ENABLE(JAVASCRIPT_DEBUGGER)
1494 String InspectorController::breakpointsSettingKey()
1496 DEFINE_STATIC_LOCAL(String, keyPrefix, ("breakpoints:"));
1497 return keyPrefix + InspectorDebuggerAgent::md5Base16(m_inspectedPage->mainFrame()->loader()->url().string());
1500 PassRefPtr<InspectorValue> InspectorController::loadBreakpoints()
1503 m_client->populateSetting(breakpointsSettingKey(), &jsonString);
1504 return InspectorValue::parseJSON(jsonString);
1507 void InspectorController::saveBreakpoints(PassRefPtr<InspectorObject> breakpoints)
1509 m_client->storeSetting(breakpointsSettingKey(), breakpoints->toJSONString());
1513 static Path quadToPath(const FloatQuad& quad)
1516 quadPath.moveTo(quad.p1());
1517 quadPath.addLineTo(quad.p2());
1518 quadPath.addLineTo(quad.p3());
1519 quadPath.addLineTo(quad.p4());
1520 quadPath.closeSubpath();
1524 static void drawOutlinedQuad(GraphicsContext& context, const FloatQuad& quad, const Color& fillColor)
1526 static const int outlineThickness = 2;
1527 static const Color outlineColor(62, 86, 180, 228);
1529 Path quadPath = quadToPath(quad);
1531 // Clip out the quad, then draw with a 2px stroke to get a pixel
1532 // of outline (because inflating a quad is hard)
1535 context.addPath(quadPath);
1536 context.clipOut(quadPath);
1538 context.addPath(quadPath);
1539 context.setStrokeThickness(outlineThickness);
1540 context.setStrokeColor(outlineColor, ColorSpaceDeviceRGB);
1541 context.strokePath();
1547 context.addPath(quadPath);
1548 context.setFillColor(fillColor, ColorSpaceDeviceRGB);
1552 static void drawOutlinedQuadWithClip(GraphicsContext& context, const FloatQuad& quad, const FloatQuad& clipQuad, const Color& fillColor)
1555 Path clipQuadPath = quadToPath(clipQuad);
1556 context.clipOut(clipQuadPath);
1557 drawOutlinedQuad(context, quad, fillColor);
1561 static void drawHighlightForBox(GraphicsContext& context, const FloatQuad& contentQuad, const FloatQuad& paddingQuad, const FloatQuad& borderQuad, const FloatQuad& marginQuad)
1563 static const Color contentBoxColor(125, 173, 217, 128);
1564 static const Color paddingBoxColor(125, 173, 217, 160);
1565 static const Color borderBoxColor(125, 173, 217, 192);
1566 static const Color marginBoxColor(125, 173, 217, 228);
1568 if (marginQuad != borderQuad)
1569 drawOutlinedQuadWithClip(context, marginQuad, borderQuad, marginBoxColor);
1570 if (borderQuad != paddingQuad)
1571 drawOutlinedQuadWithClip(context, borderQuad, paddingQuad, borderBoxColor);
1572 if (paddingQuad != contentQuad)
1573 drawOutlinedQuadWithClip(context, paddingQuad, contentQuad, paddingBoxColor);
1575 drawOutlinedQuad(context, contentQuad, contentBoxColor);
1578 static void drawHighlightForLineBoxesOrSVGRenderer(GraphicsContext& context, const Vector<FloatQuad>& lineBoxQuads)
1580 static const Color lineBoxColor(125, 173, 217, 128);
1582 for (size_t i = 0; i < lineBoxQuads.size(); ++i)
1583 drawOutlinedQuad(context, lineBoxQuads[i], lineBoxColor);
1586 static inline void convertFromFrameToMainFrame(Frame* frame, IntRect& rect)
1588 rect = frame->page()->mainFrame()->view()->windowToContents(frame->view()->contentsToWindow(rect));
1591 static inline IntSize frameToMainFrameOffset(Frame* frame)
1593 IntPoint mainFramePoint = frame->page()->mainFrame()->view()->windowToContents(frame->view()->contentsToWindow(IntPoint()));
1594 return mainFramePoint - IntPoint();
1597 void InspectorController::drawNodeHighlight(GraphicsContext& context) const
1599 if (!m_highlightedNode)
1602 RenderObject* renderer = m_highlightedNode->renderer();
1603 Frame* containingFrame = m_highlightedNode->document()->frame();
1604 if (!renderer || !containingFrame)
1607 IntSize mainFrameOffset = frameToMainFrameOffset(containingFrame);
1608 IntRect boundingBox = renderer->absoluteBoundingBoxRect(true);
1609 boundingBox.move(mainFrameOffset);
1611 ASSERT(m_inspectedPage);
1613 FrameView* view = m_inspectedPage->mainFrame()->view();
1614 FloatRect overlayRect = view->visibleContentRect();
1615 if (!overlayRect.contains(boundingBox) && !boundingBox.contains(enclosingIntRect(overlayRect)))
1616 overlayRect = view->visibleContentRect();
1617 context.translate(-overlayRect.x(), -overlayRect.y());
1619 // RenderSVGRoot should be highlighted through the isBox() code path, all other SVG elements should just dump their absoluteQuads().
1621 bool isSVGRenderer = renderer->node() && renderer->node()->isSVGElement() && !renderer->isSVGRoot();
1623 bool isSVGRenderer = false;
1626 if (renderer->isBox() && !isSVGRenderer) {
1627 RenderBox* renderBox = toRenderBox(renderer);
1629 IntRect contentBox = renderBox->contentBoxRect();
1631 IntRect paddingBox(contentBox.x() - renderBox->paddingLeft(), contentBox.y() - renderBox->paddingTop(),
1632 contentBox.width() + renderBox->paddingLeft() + renderBox->paddingRight(), contentBox.height() + renderBox->paddingTop() + renderBox->paddingBottom());
1633 IntRect borderBox(paddingBox.x() - renderBox->borderLeft(), paddingBox.y() - renderBox->borderTop(),
1634 paddingBox.width() + renderBox->borderLeft() + renderBox->borderRight(), paddingBox.height() + renderBox->borderTop() + renderBox->borderBottom());
1635 IntRect marginBox(borderBox.x() - renderBox->marginLeft(), borderBox.y() - renderBox->marginTop(),
1636 borderBox.width() + renderBox->marginLeft() + renderBox->marginRight(), borderBox.height() + renderBox->marginTop() + renderBox->marginBottom());
1638 FloatQuad absContentQuad = renderBox->localToAbsoluteQuad(FloatRect(contentBox));
1639 FloatQuad absPaddingQuad = renderBox->localToAbsoluteQuad(FloatRect(paddingBox));
1640 FloatQuad absBorderQuad = renderBox->localToAbsoluteQuad(FloatRect(borderBox));
1641 FloatQuad absMarginQuad = renderBox->localToAbsoluteQuad(FloatRect(marginBox));
1643 absContentQuad.move(mainFrameOffset);
1644 absPaddingQuad.move(mainFrameOffset);
1645 absBorderQuad.move(mainFrameOffset);
1646 absMarginQuad.move(mainFrameOffset);
1648 drawHighlightForBox(context, absContentQuad, absPaddingQuad, absBorderQuad, absMarginQuad);
1649 } else if (renderer->isRenderInline() || isSVGRenderer) {
1650 // FIXME: We should show margins/padding/border for inlines.
1651 Vector<FloatQuad> lineBoxQuads;
1652 renderer->absoluteQuads(lineBoxQuads);
1653 for (unsigned i = 0; i < lineBoxQuads.size(); ++i)
1654 lineBoxQuads[i] += mainFrameOffset;
1656 drawHighlightForLineBoxesOrSVGRenderer(context, lineBoxQuads);
1659 // Draw node title if necessary.
1661 if (!m_highlightedNode->isElementNode())
1664 WebCore::Settings* settings = containingFrame->settings();
1665 drawElementTitle(context, boundingBox, overlayRect, settings);
1668 void InspectorController::drawElementTitle(GraphicsContext& context, const IntRect& boundingBox, const FloatRect& overlayRect, WebCore::Settings* settings) const
1670 static const int rectInflatePx = 4;
1671 static const int fontHeightPx = 12;
1672 static const int borderWidthPx = 1;
1673 static const Color tooltipBackgroundColor(255, 255, 194, 255);
1674 static const Color tooltipBorderColor(Color::black);
1675 static const Color tooltipFontColor(Color::black);
1677 Element* element = static_cast<Element*>(m_highlightedNode.get());
1678 bool isXHTML = element->document()->isXHTMLDocument();
1679 String nodeTitle = isXHTML ? element->nodeName() : element->nodeName().lower();
1680 const AtomicString& idValue = element->getIdAttribute();
1681 if (!idValue.isNull() && !idValue.isEmpty()) {
1683 nodeTitle += idValue;
1685 if (element->hasClass() && element->isStyledElement()) {
1686 const SpaceSplitString& classNamesString = static_cast<StyledElement*>(element)->classNames();
1687 size_t classNameCount = classNamesString.size();
1688 if (classNameCount) {
1689 HashSet<AtomicString> usedClassNames;
1690 for (size_t i = 0; i < classNameCount; ++i) {
1691 const AtomicString& className = classNamesString[i];
1692 if (usedClassNames.contains(className))
1694 usedClassNames.add(className);
1696 nodeTitle += className;
1701 nodeTitle += String::number(boundingBox.width());
1702 nodeTitle.append(static_cast<UChar>(0x00D7)); // ×
1703 nodeTitle += String::number(boundingBox.height());
1706 FontDescription desc;
1708 family.setFamily(settings->fixedFontFamily());
1709 desc.setFamily(family);
1710 desc.setComputedSize(fontHeightPx);
1711 Font font = Font(desc, 0, 0);
1714 TextRun nodeTitleRun(nodeTitle);
1715 IntPoint titleBasePoint = boundingBox.bottomLeft();
1716 titleBasePoint.move(rectInflatePx, rectInflatePx);
1717 IntRect titleRect = enclosingIntRect(font.selectionRectForText(nodeTitleRun, titleBasePoint, fontHeightPx));
1718 titleRect.inflate(rectInflatePx);
1720 // The initial offsets needed to compensate for a 1px-thick border stroke (which is not a part of the rectangle).
1721 int dx = -borderWidthPx;
1722 int dy = borderWidthPx;
1723 if (titleRect.right() > overlayRect.right())
1724 dx += overlayRect.right() - titleRect.right();
1725 if (titleRect.x() + dx < overlayRect.x())
1726 dx = overlayRect.x() - titleRect.x();
1727 if (titleRect.bottom() > overlayRect.bottom())
1728 dy += overlayRect.bottom() - titleRect.bottom() - borderWidthPx;
1729 titleRect.move(dx, dy);
1730 context.setStrokeColor(tooltipBorderColor, ColorSpaceDeviceRGB);
1731 context.setStrokeThickness(borderWidthPx);
1732 context.setFillColor(tooltipBackgroundColor, ColorSpaceDeviceRGB);
1733 context.drawRect(titleRect);
1734 context.setFillColor(tooltipFontColor, ColorSpaceDeviceRGB);
1735 context.drawText(font, nodeTitleRun, IntPoint(titleRect.x() + rectInflatePx, titleRect.y() + font.height()));
1738 void InspectorController::openInInspectedWindow(const String& url)
1740 ResourceRequest request;
1741 FrameLoadRequest frameRequest(request, "_blank");
1743 Frame* mainFrame = m_inspectedPage->mainFrame();
1744 WindowFeatures windowFeatures;
1745 Frame* newFrame = WebCore::createWindow(mainFrame, mainFrame, frameRequest, windowFeatures, created);
1749 UserGestureIndicator indicator(DefinitelyProcessingUserGesture);
1750 newFrame->loader()->setOpener(mainFrame);
1751 newFrame->page()->setOpenedByDOM();
1752 newFrame->loader()->changeLocation(newFrame->loader()->completeURL(url), "", false, false);
1755 void InspectorController::count(const String& title, unsigned lineNumber, const String& sourceID)
1757 String identifier = makeString(title, '@', sourceID, ':', String::number(lineNumber));
1758 HashMap<String, unsigned>::iterator it = m_counts.find(identifier);
1760 if (it == m_counts.end())
1763 count = it->second + 1;
1764 m_counts.remove(it);
1767 m_counts.add(identifier, count);
1769 String message = makeString(title, ": ", String::number(count));
1770 addMessageToConsole(JSMessageSource, LogMessageType, LogMessageLevel, message, lineNumber, sourceID);
1773 void InspectorController::startTiming(const String& title)
1775 m_times.add(title, currentTime() * 1000);
1778 bool InspectorController::stopTiming(const String& title, double& elapsed)
1780 HashMap<String, double>::iterator it = m_times.find(title);
1781 if (it == m_times.end())
1784 double startTime = it->second;
1787 elapsed = currentTime() * 1000 - startTime;
1791 InjectedScript InspectorController::injectedScriptForNodeId(long id)
1797 Node* node = m_domAgent->nodeForId(id);
1799 Document* document = node->ownerDocument();
1801 frame = document->frame();
1804 frame = m_inspectedPage->mainFrame();
1807 return m_injectedScriptHost->injectedScriptFor(mainWorldScriptState(frame));
1809 return InjectedScript();
1812 void InspectorController::addScriptToEvaluateOnLoad(const String& source)
1814 m_scriptsToEvaluateOnLoad.append(source);
1817 void InspectorController::removeAllScriptsToEvaluateOnLoad()
1819 m_scriptsToEvaluateOnLoad.clear();
1822 void InspectorController::setInspectorExtensionAPI(const String& source)
1824 m_inspectorExtensionAPI = source;
1827 void InspectorController::reloadPage()
1829 // FIXME: Why do we set the user gesture indicator here?
1830 UserGestureIndicator indicator(DefinitelyProcessingUserGesture);
1831 m_inspectedPage->mainFrame()->navigationScheduler()->scheduleRefresh();
1834 } // namespace WebCore
1836 #endif // ENABLE(INSPECTOR)