5a4abc03aefd6172f3038bd8e9c9d9c9f3237814
[WebKit-https.git] / WebCore / inspector / InspectorController.cpp
1 /*
2  * Copyright (C) 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
3  * Copyright (C) 2008 Matt Lilek <webkit@mattlilek.com>
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
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.
17  *
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.
28  */
29
30 #include "config.h"
31 #include "InspectorController.h"
32
33 #if ENABLE(INSPECTOR)
34
35 #include "CachedResource.h"
36 #include "CachedResourceLoader.h"
37 #include "Chrome.h"
38 #include "Console.h"
39 #include "ConsoleMessage.h"
40 #include "Cookie.h"
41 #include "CookieJar.h"
42 #include "DOMWindow.h"
43 #include "Document.h"
44 #include "DocumentLoader.h"
45 #include "Element.h"
46 #include "FloatConversion.h"
47 #include "FloatQuad.h"
48 #include "FloatRect.h"
49 #include "Frame.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"
77 #include "IntRect.h"
78 #include "Page.h"
79 #include "ProgressTracker.h"
80 #include "Range.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"
92 #include "Settings.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>
104
105 #if ENABLE(DATABASE)
106 #include "Database.h"
107 #endif
108
109 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
110 #include "InspectorApplicationCacheAgent.h"
111 #endif
112
113 #if ENABLE(FILE_SYSTEM)
114 #include "InspectorFileSystemAgent.h"
115 #endif
116
117 #if ENABLE(DOM_STORAGE)
118 #include "Storage.h"
119 #include "StorageArea.h"
120 #endif
121
122 using namespace std;
123
124 namespace WebCore {
125
126 static const char* const domNativeBreakpointType = "DOM";
127 static const char* const eventListenerNativeBreakpointType = "EventListener";
128 static const char* const xhrNativeBreakpointType = "XHR";
129
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";
134
135 const unsigned InspectorController::defaultAttachedHeight = 300;
136
137 static const unsigned maximumConsoleMessages = 1000;
138 static const unsigned expireConsoleMessagesStep = 100;
139
140 InspectorController::InspectorController(Page* page, InspectorClient* client)
141     : m_inspectedPage(page)
142     , m_client(client)
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)
149     , m_groupLevel(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))
159 #endif
160 {
161     m_state = new InspectorState(client);
162     ASSERT_ARG(page, page);
163     ASSERT_ARG(client, client);
164 }
165
166 InspectorController::~InspectorController()
167 {
168     // These should have been cleared in inspectedPageDestroyed().
169     ASSERT(!m_client);
170     ASSERT(!m_inspectedPage);
171     ASSERT(!m_highlightedNode);
172
173     releaseFrontendLifetimeAgents();
174
175     m_inspectorBackend->disconnectController();
176     m_injectedScriptHost->disconnectController();
177 }
178
179 void InspectorController::inspectedPageDestroyed()
180 {
181     if (m_frontend)
182         m_frontend->disconnectFromBackend();
183
184     hideHighlight();
185
186 #if ENABLE(JAVASCRIPT_DEBUGGER)
187     m_debuggerAgent.clear();
188 #endif
189     ASSERT(m_inspectedPage);
190     m_inspectedPage = 0;
191
192     m_client->inspectorDestroyed();
193     m_client = 0;
194 }
195
196 bool InspectorController::enabled() const
197 {
198     if (!m_inspectedPage)
199         return false;
200     return m_inspectedPage->settings()->developerExtrasEnabled();
201 }
202
203 bool InspectorController::inspectorStartsAttached()
204 {
205     return m_state->getBoolean(InspectorState::inspectorStartsAttached);
206 }
207
208 void InspectorController::setInspectorStartsAttached(bool attached)
209 {
210     m_state->setBoolean(InspectorState::inspectorStartsAttached, attached);
211 }
212
213 void InspectorController::setInspectorAttachedHeight(long height)
214 {
215     m_state->setLong(InspectorState::inspectorAttachedHeight, height);
216 }
217
218 int InspectorController::inspectorAttachedHeight() const
219 {
220     return m_state->getBoolean(InspectorState::inspectorAttachedHeight);
221 }
222
223 bool InspectorController::searchingForNodeInPage() const
224 {
225     return m_state->getBoolean(InspectorState::searchingForNode);
226 }
227
228 void InspectorController::getInspectorState(RefPtr<InspectorObject>* state)
229 {
230 #if ENABLE(JAVASCRIPT_DEBUGGER)
231     if (m_debuggerAgent)
232         m_state->setLong(InspectorState::pauseOnExceptionsState, m_debuggerAgent->pauseOnExceptionsState());
233 #endif
234     *state = m_state->generateStateObjectForFrontend();
235 }
236
237 void InspectorController::restoreInspectorStateFromCookie(const String& inspectorStateCookie)
238 {
239     m_state->restoreFromInspectorCookie(inspectorStateCookie);
240     if (m_state->getBoolean(InspectorState::timelineProfilerEnabled))
241         startTimelineProfiler();
242 }
243
244 void InspectorController::inspect(Node* node)
245 {
246     if (!enabled())
247         return;
248
249     show();
250
251     if (node->nodeType() != Node::ELEMENT_NODE && node->nodeType() != Node::DOCUMENT_NODE)
252         node = node->parentNode();
253     m_nodeToFocus = node;
254
255     if (!m_frontend)
256         return;
257
258     focusNode();
259 }
260
261 void InspectorController::focusNode()
262 {
263     if (!enabled())
264         return;
265
266     ASSERT(m_frontend);
267     ASSERT(m_nodeToFocus);
268
269     long id = m_domAgent->pushNodePathToFrontend(m_nodeToFocus.get());
270     m_frontend->updateFocusedNode(id);
271     m_nodeToFocus = 0;
272 }
273
274 void InspectorController::highlight(Node* node)
275 {
276     if (!enabled())
277         return;
278     ASSERT_ARG(node, node);
279     m_highlightedNode = node;
280     m_client->highlight(node);
281 }
282
283 void InspectorController::highlightDOMNode(long nodeId)
284 {
285     Node* node = 0;
286     if (m_domAgent && (node = m_domAgent->nodeForId(nodeId)))
287         highlight(node);
288 }
289
290 void InspectorController::highlightFrame(unsigned long frameId)
291 {
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());
296             return;
297         }
298     }
299 }
300
301 void InspectorController::hideHighlight()
302 {
303     if (!enabled())
304         return;
305     m_highlightedNode = 0;
306     m_client->hideHighlight();
307 }
308
309 void InspectorController::setConsoleMessagesEnabled(bool enabled, bool* newState)
310 {
311     *newState = enabled;
312     setConsoleMessagesEnabled(enabled);
313 }
314
315 void InspectorController::setConsoleMessagesEnabled(bool enabled)
316 {
317     m_state->setBoolean(InspectorState::consoleMessagesEnabled, enabled);
318     if (!enabled)
319         return;
320
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());
326 }
327
328 void InspectorController::addMessageToConsole(MessageSource source, MessageType type, MessageLevel level, ScriptCallStack* callStack, const String& message)
329 {
330     if (!enabled())
331         return;
332
333     bool storeStackTrace = type == TraceMessageType || type == UncaughtExceptionMessageType || type == AssertMessageType;
334     addConsoleMessage(new ConsoleMessage(source, type, level, message, callStack, m_groupLevel, storeStackTrace));
335 }
336
337 void InspectorController::addMessageToConsole(MessageSource source, MessageType type, MessageLevel level, const String& message, unsigned lineNumber, const String& sourceID)
338 {
339     if (!enabled())
340         return;
341
342     addConsoleMessage(new ConsoleMessage(source, type, level, message, lineNumber, sourceID, m_groupLevel));
343 }
344
345 void InspectorController::addConsoleMessage(PassOwnPtr<ConsoleMessage> consoleMessage)
346 {
347     ASSERT(enabled());
348     ASSERT_ARG(consoleMessage, consoleMessage);
349
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());
354     } else {
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());
359     }
360
361     if (!m_frontend && m_consoleMessages.size() >= maximumConsoleMessages) {
362         m_expiredConsoleMessageCount += expireConsoleMessagesStep;
363         m_consoleMessages.remove(0, expireConsoleMessagesStep);
364     }
365 }
366
367 void InspectorController::clearConsoleMessages()
368 {
369     m_consoleMessages.clear();
370     m_expiredConsoleMessageCount = 0;
371     m_previousMessage = 0;
372     m_groupLevel = 0;
373     m_injectedScriptHost->releaseWrapperObjectGroup(0 /* release the group in all scripts */, "console");
374     if (m_domAgent)
375         m_domAgent->releaseDanglingNodes();
376     if (m_frontend)
377         m_frontend->consoleMessagesCleared();
378 }
379
380 void InspectorController::startGroup(MessageSource source, ScriptCallStack* callStack, bool collapsed)
381 {
382     ++m_groupLevel;
383
384     addConsoleMessage(new ConsoleMessage(source, collapsed ? StartGroupCollapsedMessageType : StartGroupMessageType, LogMessageLevel, String(), callStack, m_groupLevel));
385 }
386
387 void InspectorController::endGroup(MessageSource source, unsigned lineNumber, const String& sourceURL)
388 {
389     if (!m_groupLevel)
390         return;
391
392     --m_groupLevel;
393
394     addConsoleMessage(new ConsoleMessage(source, EndGroupMessageType, LogMessageLevel, String(), lineNumber, sourceURL, m_groupLevel));
395 }
396
397 void InspectorController::markTimeline(const String& message)
398 {
399     if (timelineAgent())
400         timelineAgent()->didMarkTimeline(message);
401 }
402
403 void InspectorController::mouseDidMoveOverElement(const HitTestResult& result, unsigned)
404 {
405     if (!enabled() || !searchingForNodeInPage())
406         return;
407
408     Node* node = result.innerNode();
409     while (node && node->nodeType() == Node::TEXT_NODE)
410         node = node->parentNode();
411     if (node)
412         highlight(node);
413 }
414
415 void InspectorController::handleMousePress()
416 {
417     if (!enabled())
418         return;
419
420     ASSERT(searchingForNodeInPage());
421     if (!m_highlightedNode)
422         return;
423
424     RefPtr<Node> node = m_highlightedNode;
425     setSearchingForNode(false);
426     inspect(node.get());
427 }
428
429 void InspectorController::setInspectorFrontendClient(PassOwnPtr<InspectorFrontendClient> client)
430 {
431     ASSERT(!m_inspectorFrontendClient);
432     m_inspectorFrontendClient = client;
433 }
434
435 void InspectorController::inspectedWindowScriptObjectCleared(Frame* frame)
436 {
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();
441
442     if (enabled()) {
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);
450             }
451         }
452     }
453     if (!m_inspectorExtensionAPI.isEmpty())
454         m_injectedScriptHost->injectScript(m_inspectorExtensionAPI, mainWorldScriptState(frame));
455 }
456
457 void InspectorController::setSearchingForNode(bool enabled)
458 {
459     if (searchingForNodeInPage() == enabled)
460         return;
461     m_state->setBoolean(InspectorState::searchingForNode, enabled);
462     if (!enabled)
463         hideHighlight();
464 }
465
466 void InspectorController::setSearchingForNode(bool enabled, bool* newState)
467 {
468     *newState = enabled;
469     setSearchingForNode(enabled);
470 }
471
472 void InspectorController::setMonitoringXHREnabled(bool enabled, bool* newState)
473 {
474     *newState = enabled;
475     m_state->setBoolean(InspectorState::monitoringXHR, enabled);
476 }
477
478 void InspectorController::connectFrontend()
479 {
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());
485
486 #if ENABLE(DATABASE)
487     m_storageAgent = InspectorStorageAgent::create(m_frontend.get());
488 #endif
489
490     if (m_timelineAgent)
491         m_timelineAgent->resetFrontendProxyObject(m_frontend.get());
492
493     // Initialize Web Inspector title.
494     m_frontend->inspectedURLChanged(m_inspectedPage->mainFrame()->loader()->url().string());
495
496 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
497     m_applicationCacheAgent = new InspectorApplicationCacheAgent(this, m_frontend.get());
498 #endif
499
500 #if ENABLE(FILE_SYSTEM)
501     m_fileSystemAgent = InspectorFileSystemAgent::create(this, m_frontend.get());
502 #endif
503     
504     if (!InspectorInstrumentation::hasFrontends())
505         ScriptController::setCaptureCallStackForUncaughtExceptions(true);
506     InspectorInstrumentation::frontendCreated();
507 }
508
509 void InspectorController::reuseFrontend()
510 {
511     connectFrontend();
512     restoreDebugger();
513     restoreProfiler();
514 }
515
516 void InspectorController::show()
517 {
518     if (!enabled())
519         return;
520
521     if (m_openingFrontend)
522         return;
523
524     if (m_frontend)
525         m_frontend->bringToFront();
526     else {
527         m_openingFrontend = true;
528         m_client->openInspectorFrontend(this);
529     }
530 }
531
532 void InspectorController::showPanel(const String& panel)
533 {
534     if (!enabled())
535         return;
536
537     show();
538
539     if (!m_frontend) {
540         m_showAfterVisible = panel;
541         return;
542     }
543     m_frontend->showPanel(panel);
544 }
545
546 void InspectorController::close()
547 {
548     if (!m_frontend)
549         return;
550     m_frontend->disconnectFromBackend();
551     disconnectFrontend();
552 }
553
554 void InspectorController::disconnectFrontend()
555 {
556     if (!m_frontend)
557         return;
558
559     m_frontend.clear();
560
561     InspectorInstrumentation::frontendDeleted();
562     if (!InspectorInstrumentation::hasFrontends())
563         ScriptController::setCaptureCallStackForUncaughtExceptions(false);
564
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
568     // opening.
569     bool debuggerWasEnabled = debuggerEnabled();
570     disableDebugger();
571     m_attachDebuggerWhenShown = debuggerWasEnabled;
572     clearNativeBreakpoints();
573 #endif
574     setSearchingForNode(false);
575     unbindAllResources();
576     stopTimelineProfiler();
577
578     hideHighlight();
579
580 #if ENABLE(JAVASCRIPT_DEBUGGER)
581     m_profilerAgent->setFrontend(0);
582     m_profilerAgent->stopUserInitiatedProfiling();
583 #endif
584
585     releaseFrontendLifetimeAgents();
586     m_timelineAgent.clear();
587 }
588
589 void InspectorController::releaseFrontendLifetimeAgents()
590 {
591     m_resourceAgent.clear();
592
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.
595     if (m_domAgent)
596         m_domAgent->reset();
597     m_domAgent.clear();
598
599 #if ENABLE(DATABASE)
600     if (m_storageAgent)
601         m_storageAgent->clearFrontend();
602     m_storageAgent.clear();
603 #endif
604
605 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
606     m_applicationCacheAgent.clear();
607 #endif
608
609 #if ENABLE(FILE_SYSTEM)
610     if (m_fileSystemAgent)
611         m_fileSystemAgent->stop(); 
612         m_fileSystemAgent.clear();
613 #endif
614 }
615
616 void InspectorController::populateScriptObjects()
617 {
618     ASSERT(m_frontend);
619     if (!m_frontend)
620         return;
621
622     if (!m_showAfterVisible.isEmpty()) {
623         showPanel(m_showAfterVisible);
624         m_showAfterVisible = "";
625     }
626
627 #if ENABLE(JAVASCRIPT_DEBUGGER)
628     if (m_profilerAgent->enabled())
629         m_frontend->profilerWasEnabled();
630 #endif
631
632     if (m_domContentEventTime != -1.0)
633         m_frontend->domContentEventFired(m_domContentEventTime);
634     if (m_loadEventTime != -1.0)
635         m_frontend->loadEventFired(m_loadEventTime);
636
637     m_domAgent->setDocument(m_inspectedPage->mainFrame()->document());
638
639     if (m_nodeToFocus)
640         focusNode();
641
642 #if ENABLE(DATABASE)
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());
646 #endif
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());
651 #endif
652 #if ENABLE(WORKERS)
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());
657     }
658 #endif
659
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();
664
665     restoreDebugger();
666     restoreProfiler();
667 }
668
669 void InspectorController::restoreDebugger()
670 {
671     ASSERT(m_frontend);
672 #if ENABLE(JAVASCRIPT_DEBUGGER)
673     if (InspectorDebuggerAgent::isDebuggerAlwaysEnabled())
674         enableDebuggerFromFrontend(false);
675     else {
676         if (m_state->getBoolean(InspectorState::debuggerAlwaysEnabled) || m_attachDebuggerWhenShown)
677             enableDebugger();
678     }
679 #endif
680 }
681
682 void InspectorController::restoreProfiler()
683 {
684     ASSERT(m_frontend);
685 #if ENABLE(JAVASCRIPT_DEBUGGER)
686     m_profilerAgent->setFrontend(m_frontend.get());
687     if (!ScriptProfiler::isProfilerAlwaysEnabled() && m_state->getBoolean(InspectorState::profilerAlwaysEnabled))
688         enableProfiler();
689 #endif
690 }
691
692 void InspectorController::unbindAllResources()
693 {
694 #if ENABLE(DATABASE)
695     DatabaseResourcesMap::iterator databasesEnd = m_databaseResources.end();
696     for (DatabaseResourcesMap::iterator it = m_databaseResources.begin(); it != databasesEnd; ++it)
697         it->second->unbind();
698 #endif
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();
703 #endif
704     if (m_timelineAgent)
705         m_timelineAgent->reset();
706 }
707
708 void InspectorController::didCommitLoad(DocumentLoader* loader)
709 {
710     if (!enabled())
711         return;
712
713     if (m_resourceAgent)
714         m_resourceAgent->didCommitLoad(loader);
715     
716     ASSERT(m_inspectedPage);
717
718     if (loader->frame() == m_inspectedPage->mainFrame()) {
719         if (m_frontend)
720             m_frontend->inspectedURLChanged(loader->url().string());
721
722         m_injectedScriptHost->discardInjectedScripts();
723         clearConsoleMessages();
724
725         m_times.clear();
726         m_counts.clear();
727
728 #if ENABLE(JAVASCRIPT_DEBUGGER)
729         if (m_debuggerAgent)
730             m_debuggerAgent->clearForPageNavigation();
731
732         clearNativeBreakpoints();
733 #endif
734
735 #if ENABLE(JAVASCRIPT_DEBUGGER) && USE(JSC)
736         m_profilerAgent->resetState();
737 #endif
738
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();
742
743         m_cssStore->reset();
744         if (m_frontend) {
745             m_frontend->reset();
746             m_domAgent->reset();
747         }
748 #if ENABLE(WORKERS)
749         m_workers.clear();
750 #endif
751 #if ENABLE(DATABASE)
752         m_databaseResources.clear();
753 #endif
754 #if ENABLE(DOM_STORAGE)
755         m_domStorageResources.clear();
756 #endif
757
758         if (m_frontend) {
759             m_mainResourceIdentifier = 0;
760             m_frontend->didCommitLoad();
761             m_domAgent->setDocument(m_inspectedPage->mainFrame()->document());
762         }
763     }
764 }
765
766 void InspectorController::frameDetachedFromParent(Frame* rootFrame)
767 {
768     if (!enabled())
769         return;
770
771     if (m_resourceAgent)
772         m_resourceAgent->frameDetachedFromParent(rootFrame);
773 }
774
775 void InspectorController::didLoadResourceFromMemoryCache(DocumentLoader* loader, const CachedResource* cachedResource)
776 {
777     if (!enabled())
778         return;
779
780     ensureSettingsLoaded();
781
782     if (m_resourceAgent)
783         m_resourceAgent->didLoadResourceFromMemoryCache(loader, cachedResource);
784 }
785
786 void InspectorController::identifierForInitialRequest(unsigned long identifier, DocumentLoader* loader, const ResourceRequest& request)
787 {
788     if (!enabled())
789         return;
790     ASSERT(m_inspectedPage);
791
792     bool isMainResource = isMainResourceLoader(loader, request.url());
793     if (isMainResource)
794         m_mainResourceIdentifier = identifier;
795
796     ensureSettingsLoaded();
797
798     if (m_resourceAgent)
799         m_resourceAgent->identifierForInitialRequest(identifier, request.url(), loader);
800 }
801
802 void InspectorController::mainResourceFiredDOMContentEvent(DocumentLoader* loader, const KURL& url)
803 {
804     if (!enabled() || !isMainResourceLoader(loader, url))
805         return;
806
807     m_domContentEventTime = currentTime();
808     if (m_timelineAgent)
809         m_timelineAgent->didMarkDOMContentEvent();
810     if (m_frontend)
811         m_frontend->domContentEventFired(m_domContentEventTime);
812 }
813
814 void InspectorController::mainResourceFiredLoadEvent(DocumentLoader* loader, const KURL& url)
815 {
816     if (!enabled() || !isMainResourceLoader(loader, url))
817         return;
818
819     m_loadEventTime = currentTime();
820     if (m_timelineAgent)
821         m_timelineAgent->didMarkLoadEvent();
822     if (m_frontend)
823         m_frontend->loadEventFired(m_loadEventTime);
824 }
825
826 bool InspectorController::isMainResourceLoader(DocumentLoader* loader, const KURL& requestUrl)
827 {
828     return loader->frame() == m_inspectedPage->mainFrame() && requestUrl == loader->requestURL();
829 }
830
831 void InspectorController::willSendRequest(unsigned long identifier, ResourceRequest& request, const ResourceResponse& redirectResponse)
832 {
833     if (!enabled())
834         return;
835
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.
839     if (m_frontend)
840         request.setReportRawHeaders(true);
841
842     bool isMainResource = m_mainResourceIdentifier == identifier;
843
844     if (m_timelineAgent)
845         m_timelineAgent->willSendResourceRequest(identifier, isMainResource, request);
846
847     if (m_resourceAgent)
848         m_resourceAgent->willSendRequest(identifier, request, redirectResponse);
849 }
850
851 void InspectorController::markResourceAsCached(unsigned long identifier)
852 {
853     if (!enabled())
854         return;
855
856     if (m_resourceAgent)
857         m_resourceAgent->markResourceAsCached(identifier);
858 }
859
860 void InspectorController::didReceiveResponse(unsigned long identifier, DocumentLoader* loader, const ResourceResponse& response)
861 {
862     if (!enabled())
863         return;
864
865     if (m_resourceAgent)
866         m_resourceAgent->didReceiveResponse(identifier, loader, response);
867
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());
871     }
872 }
873
874 void InspectorController::didReceiveContentLength(unsigned long identifier, int lengthReceived)
875 {
876     if (!enabled())
877         return;
878
879     if (m_resourceAgent)
880         m_resourceAgent->didReceiveContentLength(identifier, lengthReceived);
881 }
882
883 void InspectorController::didFinishLoading(unsigned long identifier, double finishTime)
884 {
885     if (!enabled())
886         return;
887
888     if (m_timelineAgent)
889         m_timelineAgent->didFinishLoadingResource(identifier, false, finishTime);
890
891     if (m_resourceAgent)
892         m_resourceAgent->didFinishLoading(identifier, finishTime);
893 }
894
895 void InspectorController::didFailLoading(unsigned long identifier, const ResourceError& error)
896 {
897     if (!enabled())
898         return;
899
900     if (m_timelineAgent)
901         m_timelineAgent->didFinishLoadingResource(identifier, true, 0);
902
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());
907
908     if (m_resourceAgent)
909         m_resourceAgent->didFailLoading(identifier, error);
910 }
911
912 void InspectorController::resourceRetrievedByXMLHttpRequest(unsigned long identifier, const String& sourceString, const String& url, const String& sendURL, unsigned sendLineNumber)
913 {
914     if (!enabled())
915         return;
916
917     if (m_state->getBoolean(InspectorState::monitoringXHR))
918         addMessageToConsole(JSMessageSource, LogMessageType, LogMessageLevel, "XHR finished loading: \"" + url + "\".", sendLineNumber, sendURL);
919
920     if (m_resourceAgent)
921         m_resourceAgent->setOverrideContent(identifier, sourceString, "XHR");
922 }
923
924 void InspectorController::scriptImported(unsigned long identifier, const String& sourceString)
925 {
926     if (!enabled())
927         return;
928
929     if (m_resourceAgent)
930         m_resourceAgent->setOverrideContent(identifier, sourceString, "Script");
931 }
932
933 void InspectorController::ensureSettingsLoaded()
934 {
935     if (m_settingsLoaded)
936         return;
937     m_settingsLoaded = true;
938
939     m_state->loadFromSettings();
940
941     if (m_state->getBoolean(InspectorState::resourceTrackingAlwaysEnabled))
942         m_state->setBoolean(InspectorState::resourceTrackingEnabled, true);
943 }
944
945 void InspectorController::startTimelineProfiler()
946 {
947     if (!enabled())
948         return;
949
950     if (m_timelineAgent)
951         return;
952
953     m_timelineAgent = new InspectorTimelineAgent(m_frontend.get());
954     if (m_frontend)
955         m_frontend->timelineProfilerWasStarted();
956
957     m_state->setBoolean(InspectorState::timelineProfilerEnabled, true);
958 }
959
960 void InspectorController::stopTimelineProfiler()
961 {
962     if (!enabled())
963         return;
964
965     if (!m_timelineAgent)
966         return;
967
968     m_timelineAgent = 0;
969     if (m_frontend)
970         m_frontend->timelineProfilerWasStopped();
971
972     m_state->setBoolean(InspectorState::timelineProfilerEnabled, false);
973 }
974
975 #if ENABLE(WORKERS)
976 class PostWorkerNotificationToFrontendTask : public ScriptExecutionContext::Task {
977 public:
978     static PassOwnPtr<PostWorkerNotificationToFrontendTask> create(PassRefPtr<InspectorWorkerResource> worker, InspectorController::WorkerAction action)
979     {
980         return new PostWorkerNotificationToFrontendTask(worker, action);
981     }
982
983 private:
984     PostWorkerNotificationToFrontendTask(PassRefPtr<InspectorWorkerResource> worker, InspectorController::WorkerAction action)
985         : m_worker(worker)
986         , m_action(action)
987     {
988     }
989
990     virtual void performTask(ScriptExecutionContext* scriptContext)
991     {
992         if (InspectorController* inspector = scriptContext->inspectorController())
993             inspector->postWorkerNotificationToFrontend(*m_worker, m_action);
994     }
995
996 private:
997     RefPtr<InspectorWorkerResource> m_worker;
998     InspectorController::WorkerAction m_action;
999 };
1000
1001 void InspectorController::postWorkerNotificationToFrontend(const InspectorWorkerResource& worker, InspectorController::WorkerAction action)
1002 {
1003     if (!m_frontend)
1004         return;
1005     switch (action) {
1006     case InspectorController::WorkerCreated:
1007         m_frontend->didCreateWorker(worker.id(), worker.url(), worker.isSharedWorker());
1008         break;
1009     case InspectorController::WorkerDestroyed:
1010         m_frontend->didDestroyWorker(worker.id());
1011         break;
1012     }
1013 }
1014
1015 void InspectorController::didCreateWorker(intptr_t id, const String& url, bool isSharedWorker)
1016 {
1017     if (!enabled())
1018         return;
1019
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));
1024 }
1025
1026 void InspectorController::didDestroyWorker(intptr_t id)
1027 {
1028     if (!enabled())
1029         return;
1030
1031     WorkersMap::iterator workerResource = m_workers.find(id);
1032     if (workerResource == m_workers.end())
1033         return;
1034     if (m_inspectedPage && m_frontend)
1035         m_inspectedPage->mainFrame()->document()->postTask(PostWorkerNotificationToFrontendTask::create(workerResource->second, InspectorController::WorkerDestroyed));
1036     m_workers.remove(workerResource);
1037 }
1038 #endif // ENABLE(WORKERS)
1039
1040 #if ENABLE(DATABASE)
1041 void InspectorController::selectDatabase(Database* database)
1042 {
1043     if (!m_frontend)
1044         return;
1045
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);
1049             break;
1050         }
1051     }
1052 }
1053
1054 Database* InspectorController::databaseForId(long databaseId)
1055 {
1056     DatabaseResourcesMap::iterator it = m_databaseResources.find(databaseId);
1057     if (it == m_databaseResources.end())
1058         return 0;
1059     return it->second->database();
1060 }
1061
1062 void InspectorController::didOpenDatabase(PassRefPtr<Database> database, const String& domain, const String& name, const String& version)
1063 {
1064     if (!enabled())
1065         return;
1066
1067     RefPtr<InspectorDatabaseResource> resource = InspectorDatabaseResource::create(database, domain, name, version);
1068
1069     m_databaseResources.set(resource->id(), resource);
1070
1071     // Resources are only bound while visible.
1072     if (m_frontend)
1073         resource->bind(m_frontend.get());
1074 }
1075 #endif
1076
1077 void InspectorController::getCookies(RefPtr<InspectorArray>* cookies, WTF::String* cookiesString)
1078 {
1079     // If we can get raw cookies.
1080     ListHashSet<Cookie> rawCookiesList;
1081
1082     // If we can't get raw cookies - fall back to String representation
1083     String stringCookiesList;
1084
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;
1089
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);
1097
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.
1104                 ASSERT(!ec);
1105             } else {
1106                 int cookiesSize = docCookiesList.size();
1107                 for (int i = 0; i < cookiesSize; i++) {
1108                     if (!rawCookiesList.contains(docCookiesList[i]))
1109                         rawCookiesList.add(docCookiesList[i]);
1110                 }
1111             }
1112         }
1113     }
1114
1115     if (rawCookiesImplemented)
1116         *cookies = buildArrayForCookies(rawCookiesList);
1117     else
1118         *cookiesString = stringCookiesList;
1119 }
1120
1121 PassRefPtr<InspectorArray> InspectorController::buildArrayForCookies(ListHashSet<Cookie>& cookiesList)
1122 {
1123     RefPtr<InspectorArray> cookies = InspectorArray::create();
1124
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));
1129
1130     return cookies;
1131 }
1132
1133 PassRefPtr<InspectorObject> InspectorController::buildObjectForCookie(const Cookie& cookie)
1134 {
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);
1145     return value;
1146 }
1147
1148 void InspectorController::deleteCookie(const String& cookieName, const String& domain)
1149 {
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)
1153             continue;
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);
1158     }
1159 }
1160
1161 #if ENABLE(DOM_STORAGE)
1162 void InspectorController::didUseDOMStorage(StorageArea* storageArea, bool isLocalStorage, Frame* frame)
1163 {
1164     if (!enabled())
1165         return;
1166
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))
1170             return;
1171
1172     RefPtr<Storage> domStorage = Storage::create(frame, storageArea);
1173     RefPtr<InspectorDOMStorageResource> resource = InspectorDOMStorageResource::create(domStorage.get(), isLocalStorage, frame);
1174
1175     m_domStorageResources.set(resource->id(), resource);
1176
1177     // Resources are only bound while visible.
1178     if (m_frontend)
1179         resource->bind(m_frontend.get());
1180 }
1181
1182 void InspectorController::selectDOMStorage(Storage* storage)
1183 {
1184     ASSERT(storage);
1185     if (!m_frontend)
1186         return;
1187
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;
1196             break;
1197         }
1198     }
1199     if (storageResourceId)
1200         m_frontend->selectDOMStorage(storageResourceId);
1201 }
1202
1203 void InspectorController::getDOMStorageEntries(long storageId, RefPtr<InspectorArray>* entries)
1204 {
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);
1216         }
1217     }
1218 }
1219
1220 void InspectorController::setDOMStorageItem(long storageId, const String& key, const String& value, bool* success)
1221 {
1222     InspectorDOMStorageResource* storageResource = getDOMStorageResourceForId(storageId);
1223     if (storageResource) {
1224         ExceptionCode exception = 0;
1225         storageResource->domStorage()->setItem(key, value, exception);
1226         *success = !exception;
1227     }
1228 }
1229
1230 void InspectorController::removeDOMStorageItem(long storageId, const String& key, bool* success)
1231 {
1232     InspectorDOMStorageResource* storageResource = getDOMStorageResourceForId(storageId);
1233     if (storageResource) {
1234         storageResource->domStorage()->removeItem(key);
1235         *success = true;
1236     }
1237 }
1238
1239 InspectorDOMStorageResource* InspectorController::getDOMStorageResourceForId(long storageId)
1240 {
1241     DOMStorageResourcesMap::iterator it = m_domStorageResources.find(storageId);
1242     if (it == m_domStorageResources.end())
1243         return 0;
1244     return it->second.get();
1245 }
1246 #endif
1247
1248 #if ENABLE(WEB_SOCKETS)
1249 void InspectorController::didCreateWebSocket(unsigned long identifier, const KURL& requestURL, const KURL& documentURL)
1250 {
1251     if (!enabled())
1252         return;
1253     ASSERT(m_inspectedPage);
1254
1255     if (m_resourceAgent)
1256         m_resourceAgent->didCreateWebSocket(identifier, requestURL);
1257     UNUSED_PARAM(documentURL);
1258 }
1259
1260 void InspectorController::willSendWebSocketHandshakeRequest(unsigned long identifier, const WebSocketHandshakeRequest& request)
1261 {
1262     if (m_resourceAgent)
1263         m_resourceAgent->willSendWebSocketHandshakeRequest(identifier, request);
1264 }
1265
1266 void InspectorController::didReceiveWebSocketHandshakeResponse(unsigned long identifier, const WebSocketHandshakeResponse& response)
1267 {
1268     if (m_resourceAgent)
1269         m_resourceAgent->didReceiveWebSocketHandshakeResponse(identifier, response);
1270 }
1271
1272 void InspectorController::didCloseWebSocket(unsigned long identifier)
1273 {
1274     if (m_resourceAgent)
1275         m_resourceAgent->didCloseWebSocket(identifier);
1276 }
1277 #endif // ENABLE(WEB_SOCKETS)
1278
1279 #if ENABLE(JAVASCRIPT_DEBUGGER)
1280 void InspectorController::addProfile(PassRefPtr<ScriptProfile> prpProfile, unsigned lineNumber, const String& sourceURL)
1281 {
1282     if (!enabled())
1283         return;
1284     m_profilerAgent->addProfile(prpProfile, lineNumber, sourceURL);
1285 }
1286
1287 void InspectorController::addProfileFinishedMessageToConsole(PassRefPtr<ScriptProfile> prpProfile, unsigned lineNumber, const String& sourceURL)
1288 {
1289     m_profilerAgent->addProfileFinishedMessageToConsole(prpProfile, lineNumber, sourceURL);
1290 }
1291
1292 void InspectorController::addStartProfilingMessageToConsole(const String& title, unsigned lineNumber, const String& sourceURL)
1293 {
1294     m_profilerAgent->addStartProfilingMessageToConsole(title, lineNumber, sourceURL);
1295 }
1296
1297
1298 bool InspectorController::isRecordingUserInitiatedProfile() const
1299 {
1300     return m_profilerAgent->isRecordingUserInitiatedProfile();
1301 }
1302
1303 String InspectorController::getCurrentUserInitiatedProfileName(bool incrementProfileNumber)
1304 {
1305     return m_profilerAgent->getCurrentUserInitiatedProfileName(incrementProfileNumber);
1306 }
1307
1308 void InspectorController::startUserInitiatedProfiling()
1309 {
1310     if (!enabled())
1311         return;
1312     m_profilerAgent->startUserInitiatedProfiling();
1313 }
1314
1315 void InspectorController::stopUserInitiatedProfiling()
1316 {
1317     if (!enabled())
1318         return;
1319     m_profilerAgent->stopUserInitiatedProfiling();
1320 }
1321
1322 bool InspectorController::profilerEnabled() const
1323 {
1324     return enabled() && m_profilerAgent->enabled();
1325 }
1326
1327 void InspectorController::enableProfiler(bool always, bool skipRecompile)
1328 {
1329     if (always)
1330         m_state->setBoolean(InspectorState::profilerAlwaysEnabled, true);
1331     m_profilerAgent->enable(skipRecompile);
1332 }
1333
1334 void InspectorController::disableProfiler(bool always)
1335 {
1336     if (always)
1337         m_state->setBoolean(InspectorState::profilerAlwaysEnabled, false);
1338     m_profilerAgent->disable();
1339 }
1340 #endif
1341
1342 #if ENABLE(JAVASCRIPT_DEBUGGER)
1343 void InspectorController::enableDebuggerFromFrontend(bool always)
1344 {
1345     ASSERT(!debuggerEnabled());
1346     if (always)
1347         m_state->setBoolean(InspectorState::debuggerAlwaysEnabled, true);
1348
1349     ASSERT(m_inspectedPage);
1350
1351     m_debuggerAgent = InspectorDebuggerAgent::create(this, m_frontend.get());
1352
1353     m_frontend->debuggerWasEnabled();
1354 }
1355
1356 void InspectorController::enableDebugger()
1357 {
1358     if (!enabled())
1359         return;
1360
1361     if (debuggerEnabled())
1362         return;
1363
1364     if (!m_frontend)
1365         m_attachDebuggerWhenShown = true;
1366     else {
1367         m_frontend->attachDebuggerWhenShown();
1368         m_attachDebuggerWhenShown = false;
1369     }
1370 }
1371
1372 void InspectorController::disableDebugger(bool always)
1373 {
1374     if (!enabled())
1375         return;
1376
1377     if (always)
1378         m_state->setBoolean(InspectorState::debuggerAlwaysEnabled, false);
1379
1380     ASSERT(m_inspectedPage);
1381
1382     m_debuggerAgent.clear();
1383
1384     m_attachDebuggerWhenShown = false;
1385
1386     if (m_frontend)
1387         m_frontend->debuggerWasDisabled();
1388 }
1389
1390 void InspectorController::resume()
1391 {
1392     if (m_debuggerAgent)
1393         m_debuggerAgent->resume();
1394 }
1395
1396 void InspectorController::setNativeBreakpoint(PassRefPtr<InspectorObject> breakpoint, String* breakpointId)
1397 {
1398     *breakpointId = "";
1399     String type;
1400     if (!breakpoint->getString("type", &type))
1401         return;
1402     RefPtr<InspectorObject> condition = breakpoint->getObject("condition");
1403     if (!condition)
1404         return;
1405     if (type == xhrNativeBreakpointType) {
1406         String url;
1407         if (!condition->getString("url", &url))
1408             return;
1409         *breakpointId = String::number(++m_lastBreakpointId);
1410         m_XHRBreakpoints.set(*breakpointId, url);
1411         m_nativeBreakpoints.set(*breakpointId, type);
1412     } else if (type == eventListenerNativeBreakpointType) {
1413         String eventName;
1414         if (!condition->getString("eventName", &eventName))
1415             return;
1416         if (m_eventListenerBreakpoints.contains(eventName))
1417             return;
1418         *breakpointId = eventName;
1419         m_eventListenerBreakpoints.add(eventName);
1420         m_nativeBreakpoints.set(*breakpointId, type);
1421     } else if (type == domNativeBreakpointType) {
1422         if (!m_domAgent)
1423             return;
1424         double nodeIdNumber;
1425         if (!condition->getNumber("nodeId", &nodeIdNumber))
1426             return;
1427         double domBreakpointTypeNumber;
1428         if (!condition->getNumber("type", &domBreakpointTypeNumber))
1429             return;
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);
1435     }
1436 }
1437
1438 void InspectorController::removeNativeBreakpoint(const String& breakpointId)
1439 {
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) {
1446         if (m_domAgent)
1447             m_domAgent->removeDOMBreakpoint(breakpointId);
1448     }
1449 }
1450
1451 String InspectorController::findEventListenerBreakpoint(const String& eventName)
1452 {
1453     return m_eventListenerBreakpoints.contains(eventName) ? eventName : "";
1454 }
1455
1456 String InspectorController::findXHRBreakpoint(const String& url)
1457 {
1458     for (HashMap<String, String>::iterator it = m_XHRBreakpoints.begin(); it != m_XHRBreakpoints.end(); ++it) {
1459         if (url.contains(it->second))
1460             return it->first;
1461     }
1462     return "";
1463 }
1464
1465 void InspectorController::clearNativeBreakpoints()
1466 {
1467     m_nativeBreakpoints.clear();
1468     m_eventListenerBreakpoints.clear();
1469     m_XHRBreakpoints.clear();
1470     m_lastBreakpointId = 0;
1471 }
1472 #endif
1473
1474 void InspectorController::evaluateForTestInFrontend(long callId, const String& script)
1475 {
1476     if (m_frontend)
1477         m_frontend->evaluateForTestInFrontend(callId, script);
1478     else
1479         m_pendingEvaluateTestCommands.append(pair<long, String>(callId, script));
1480 }
1481
1482 void InspectorController::didEvaluateForTestInFrontend(long callId, const String& jsonResult)
1483 {
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);
1490     function.call();
1491 }
1492
1493 #if ENABLE(JAVASCRIPT_DEBUGGER)
1494 String InspectorController::breakpointsSettingKey()
1495 {
1496     DEFINE_STATIC_LOCAL(String, keyPrefix, ("breakpoints:"));
1497     return keyPrefix + InspectorDebuggerAgent::md5Base16(m_inspectedPage->mainFrame()->loader()->url().string());
1498 }
1499
1500 PassRefPtr<InspectorValue> InspectorController::loadBreakpoints()
1501 {
1502     String jsonString;
1503     m_client->populateSetting(breakpointsSettingKey(), &jsonString);
1504     return InspectorValue::parseJSON(jsonString);
1505 }
1506
1507 void InspectorController::saveBreakpoints(PassRefPtr<InspectorObject> breakpoints)
1508 {
1509     m_client->storeSetting(breakpointsSettingKey(), breakpoints->toJSONString());
1510 }
1511 #endif
1512
1513 static Path quadToPath(const FloatQuad& quad)
1514 {
1515     Path quadPath;
1516     quadPath.moveTo(quad.p1());
1517     quadPath.addLineTo(quad.p2());
1518     quadPath.addLineTo(quad.p3());
1519     quadPath.addLineTo(quad.p4());
1520     quadPath.closeSubpath();
1521     return quadPath;
1522 }
1523
1524 static void drawOutlinedQuad(GraphicsContext& context, const FloatQuad& quad, const Color& fillColor)
1525 {
1526     static const int outlineThickness = 2;
1527     static const Color outlineColor(62, 86, 180, 228);
1528
1529     Path quadPath = quadToPath(quad);
1530
1531     // Clip out the quad, then draw with a 2px stroke to get a pixel
1532     // of outline (because inflating a quad is hard)
1533     {
1534         context.save();
1535         context.addPath(quadPath);
1536         context.clipOut(quadPath);
1537
1538         context.addPath(quadPath);
1539         context.setStrokeThickness(outlineThickness);
1540         context.setStrokeColor(outlineColor, ColorSpaceDeviceRGB);
1541         context.strokePath();
1542
1543         context.restore();
1544     }
1545
1546     // Now do the fill
1547     context.addPath(quadPath);
1548     context.setFillColor(fillColor, ColorSpaceDeviceRGB);
1549     context.fillPath();
1550 }
1551
1552 static void drawOutlinedQuadWithClip(GraphicsContext& context, const FloatQuad& quad, const FloatQuad& clipQuad, const Color& fillColor)
1553 {
1554     context.save();
1555     Path clipQuadPath = quadToPath(clipQuad);
1556     context.clipOut(clipQuadPath);
1557     drawOutlinedQuad(context, quad, fillColor);
1558     context.restore();
1559 }
1560
1561 static void drawHighlightForBox(GraphicsContext& context, const FloatQuad& contentQuad, const FloatQuad& paddingQuad, const FloatQuad& borderQuad, const FloatQuad& marginQuad)
1562 {
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);
1567
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);
1574
1575     drawOutlinedQuad(context, contentQuad, contentBoxColor);
1576 }
1577
1578 static void drawHighlightForLineBoxesOrSVGRenderer(GraphicsContext& context, const Vector<FloatQuad>& lineBoxQuads)
1579 {
1580     static const Color lineBoxColor(125, 173, 217, 128);
1581
1582     for (size_t i = 0; i < lineBoxQuads.size(); ++i)
1583         drawOutlinedQuad(context, lineBoxQuads[i], lineBoxColor);
1584 }
1585
1586 static inline void convertFromFrameToMainFrame(Frame* frame, IntRect& rect)
1587 {
1588     rect = frame->page()->mainFrame()->view()->windowToContents(frame->view()->contentsToWindow(rect));
1589 }
1590
1591 static inline IntSize frameToMainFrameOffset(Frame* frame)
1592 {
1593     IntPoint mainFramePoint = frame->page()->mainFrame()->view()->windowToContents(frame->view()->contentsToWindow(IntPoint()));
1594     return mainFramePoint - IntPoint();
1595 }
1596
1597 void InspectorController::drawNodeHighlight(GraphicsContext& context) const
1598 {
1599     if (!m_highlightedNode)
1600         return;
1601
1602     RenderObject* renderer = m_highlightedNode->renderer();
1603     Frame* containingFrame = m_highlightedNode->document()->frame();
1604     if (!renderer || !containingFrame)
1605         return;
1606
1607     IntSize mainFrameOffset = frameToMainFrameOffset(containingFrame);
1608     IntRect boundingBox = renderer->absoluteBoundingBoxRect(true);
1609     boundingBox.move(mainFrameOffset);
1610
1611     ASSERT(m_inspectedPage);
1612
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());
1618
1619     // RenderSVGRoot should be highlighted through the isBox() code path, all other SVG elements should just dump their absoluteQuads().
1620 #if ENABLE(SVG)
1621     bool isSVGRenderer = renderer->node() && renderer->node()->isSVGElement() && !renderer->isSVGRoot();
1622 #else
1623     bool isSVGRenderer = false;
1624 #endif
1625
1626     if (renderer->isBox() && !isSVGRenderer) {
1627         RenderBox* renderBox = toRenderBox(renderer);
1628
1629         IntRect contentBox = renderBox->contentBoxRect();
1630
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());
1637
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));
1642
1643         absContentQuad.move(mainFrameOffset);
1644         absPaddingQuad.move(mainFrameOffset);
1645         absBorderQuad.move(mainFrameOffset);
1646         absMarginQuad.move(mainFrameOffset);
1647
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;
1655
1656         drawHighlightForLineBoxesOrSVGRenderer(context, lineBoxQuads);
1657     }
1658
1659     // Draw node title if necessary.
1660
1661     if (!m_highlightedNode->isElementNode())
1662         return;
1663
1664     WebCore::Settings* settings = containingFrame->settings();
1665     drawElementTitle(context, boundingBox, overlayRect, settings);
1666 }
1667
1668 void InspectorController::drawElementTitle(GraphicsContext& context, const IntRect& boundingBox, const FloatRect& overlayRect, WebCore::Settings* settings) const
1669 {
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);
1676
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()) {
1682         nodeTitle += "#";
1683         nodeTitle += idValue;
1684     }
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))
1693                     continue;
1694                 usedClassNames.add(className);
1695                 nodeTitle += ".";
1696                 nodeTitle += className;
1697             }
1698         }
1699     }
1700     nodeTitle += " [";
1701     nodeTitle += String::number(boundingBox.width());
1702     nodeTitle.append(static_cast<UChar>(0x00D7)); // &times;
1703     nodeTitle += String::number(boundingBox.height());
1704     nodeTitle += "]";
1705
1706     FontDescription desc;
1707     FontFamily family;
1708     family.setFamily(settings->fixedFontFamily());
1709     desc.setFamily(family);
1710     desc.setComputedSize(fontHeightPx);
1711     Font font = Font(desc, 0, 0);
1712     font.update(0);
1713
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);
1719
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()));
1736 }
1737
1738 void InspectorController::openInInspectedWindow(const String& url)
1739 {
1740     ResourceRequest request;
1741     FrameLoadRequest frameRequest(request, "_blank");
1742     bool created;
1743     Frame* mainFrame = m_inspectedPage->mainFrame();
1744     WindowFeatures windowFeatures;
1745     Frame* newFrame = WebCore::createWindow(mainFrame, mainFrame, frameRequest, windowFeatures, created);
1746     if (!newFrame)
1747         return;
1748
1749     UserGestureIndicator indicator(DefinitelyProcessingUserGesture);
1750     newFrame->loader()->setOpener(mainFrame);
1751     newFrame->page()->setOpenedByDOM();
1752     newFrame->loader()->changeLocation(newFrame->loader()->completeURL(url), "", false, false);
1753 }
1754
1755 void InspectorController::count(const String& title, unsigned lineNumber, const String& sourceID)
1756 {
1757     String identifier = makeString(title, '@', sourceID, ':', String::number(lineNumber));
1758     HashMap<String, unsigned>::iterator it = m_counts.find(identifier);
1759     int count;
1760     if (it == m_counts.end())
1761         count = 1;
1762     else {
1763         count = it->second + 1;
1764         m_counts.remove(it);
1765     }
1766
1767     m_counts.add(identifier, count);
1768
1769     String message = makeString(title, ": ", String::number(count));
1770     addMessageToConsole(JSMessageSource, LogMessageType, LogMessageLevel, message, lineNumber, sourceID);
1771 }
1772
1773 void InspectorController::startTiming(const String& title)
1774 {
1775     m_times.add(title, currentTime() * 1000);
1776 }
1777
1778 bool InspectorController::stopTiming(const String& title, double& elapsed)
1779 {
1780     HashMap<String, double>::iterator it = m_times.find(title);
1781     if (it == m_times.end())
1782         return false;
1783
1784     double startTime = it->second;
1785     m_times.remove(it);
1786
1787     elapsed = currentTime() * 1000 - startTime;
1788     return true;
1789 }
1790
1791 InjectedScript InspectorController::injectedScriptForNodeId(long id)
1792 {
1793
1794     Frame* frame = 0;
1795     if (id) {
1796         ASSERT(m_domAgent);
1797         Node* node = m_domAgent->nodeForId(id);
1798         if (node) {
1799             Document* document = node->ownerDocument();
1800             if (document)
1801                 frame = document->frame();
1802         }
1803     } else
1804         frame = m_inspectedPage->mainFrame();
1805
1806     if (frame)
1807         return m_injectedScriptHost->injectedScriptFor(mainWorldScriptState(frame));
1808
1809     return InjectedScript();
1810 }
1811
1812 void InspectorController::addScriptToEvaluateOnLoad(const String& source)
1813 {
1814     m_scriptsToEvaluateOnLoad.append(source);
1815 }
1816
1817 void InspectorController::removeAllScriptsToEvaluateOnLoad()
1818 {
1819     m_scriptsToEvaluateOnLoad.clear();
1820 }
1821
1822 void InspectorController::setInspectorExtensionAPI(const String& source)
1823 {
1824     m_inspectorExtensionAPI = source;
1825 }
1826
1827 void InspectorController::reloadPage()
1828 {
1829     // FIXME: Why do we set the user gesture indicator here?
1830     UserGestureIndicator indicator(DefinitelyProcessingUserGesture);
1831     m_inspectedPage->mainFrame()->navigationScheduler()->scheduleRefresh();
1832 }
1833
1834 } // namespace WebCore
1835
1836 #endif // ENABLE(INSPECTOR)