7248dc99078c3a2a907d92816333589da05488c7
[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 "HTTPHeaderMap.h"
57 #include "HitTestResult.h"
58 #include "InjectedScript.h"
59 #include "InjectedScriptHost.h"
60 #include "InspectorBackendDispatcher.h"
61 #include "InspectorCSSAgent.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 "InspectorTimelineAgent.h"
74 #include "InspectorValues.h"
75 #include "InspectorWorkerResource.h"
76 #include "IntRect.h"
77 #include "Page.h"
78 #include "ProgressTracker.h"
79 #include "Range.h"
80 #include "RenderInline.h"
81 #include "ResourceRequest.h"
82 #include "ResourceResponse.h"
83 #include "ScriptArguments.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 #include "InspectorDatabaseAgent.h"
108 #endif
109
110 #if ENABLE(DOM_STORAGE)
111 #include "InspectorDOMStorageAgent.h"
112 #include "Storage.h"
113 #include "StorageArea.h"
114 #endif
115
116 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
117 #include "InspectorApplicationCacheAgent.h"
118 #endif
119
120 #if ENABLE(FILE_SYSTEM)
121 #include "InspectorFileSystemAgent.h"
122 #endif
123
124 using namespace std;
125
126 namespace WebCore {
127
128 const char* const InspectorController::ElementsPanel = "elements";
129 const char* const InspectorController::ConsolePanel = "console";
130 const char* const InspectorController::ScriptsPanel = "scripts";
131 const char* const InspectorController::ProfilesPanel = "profiles";
132
133 const unsigned InspectorController::defaultAttachedHeight = 300;
134
135 static const unsigned maximumConsoleMessages = 1000;
136 static const unsigned expireConsoleMessagesStep = 100;
137
138 InspectorController::InspectorController(Page* page, InspectorClient* client)
139     : m_inspectedPage(page)
140     , m_client(client)
141     , m_openingFrontend(false)
142     , m_cssAgent(new InspectorCSSAgent())
143     , m_mainResourceIdentifier(0)
144     , m_expiredConsoleMessageCount(0)
145     , m_previousMessage(0)
146     , m_settingsLoaded(false)
147     , m_inspectorBackendDispatcher(new InspectorBackendDispatcher(this))
148     , m_injectedScriptHost(InjectedScriptHost::create(this))
149 #if ENABLE(JAVASCRIPT_DEBUGGER)
150     , m_attachDebuggerWhenShown(false)
151     , m_hasXHRBreakpointWithEmptyURL(false)
152     , m_profilerAgent(InspectorProfilerAgent::create(this))
153 #endif
154 {
155     m_state = new InspectorState(client);
156     ASSERT_ARG(page, page);
157     ASSERT_ARG(client, client);
158 }
159
160 InspectorController::~InspectorController()
161 {
162     // These should have been cleared in inspectedPageDestroyed().
163     ASSERT(!m_client);
164     ASSERT(!m_inspectedPage);
165     ASSERT(!m_highlightedNode);
166
167     releaseFrontendLifetimeAgents();
168
169     m_injectedScriptHost->disconnectController();
170 }
171
172 void InspectorController::inspectedPageDestroyed()
173 {
174     if (m_frontend)
175         m_frontend->disconnectFromBackend();
176
177     hideHighlight();
178
179 #if ENABLE(JAVASCRIPT_DEBUGGER)
180     m_debuggerAgent.clear();
181 #endif
182     ASSERT(m_inspectedPage);
183     m_inspectedPage = 0;
184
185     m_client->inspectorDestroyed();
186     m_client = 0;
187 }
188
189 bool InspectorController::enabled() const
190 {
191     if (!m_inspectedPage)
192         return false;
193     return m_inspectedPage->settings()->developerExtrasEnabled();
194 }
195
196 bool InspectorController::inspectorStartsAttached()
197 {
198     return m_state->getBoolean(InspectorState::inspectorStartsAttached);
199 }
200
201 void InspectorController::setInspectorStartsAttached(bool attached)
202 {
203     m_state->setBoolean(InspectorState::inspectorStartsAttached, attached);
204 }
205
206 void InspectorController::setInspectorAttachedHeight(long height)
207 {
208     m_state->setLong(InspectorState::inspectorAttachedHeight, height);
209 }
210
211 int InspectorController::inspectorAttachedHeight() const
212 {
213     return m_state->getBoolean(InspectorState::inspectorAttachedHeight);
214 }
215
216 bool InspectorController::searchingForNodeInPage() const
217 {
218     return m_state->getBoolean(InspectorState::searchingForNode);
219 }
220
221 void InspectorController::getInspectorState(RefPtr<InspectorObject>* state)
222 {
223 #if ENABLE(JAVASCRIPT_DEBUGGER)
224     if (m_debuggerAgent)
225         m_state->setLong(InspectorState::pauseOnExceptionsState, m_debuggerAgent->pauseOnExceptionsState());
226 #endif
227     *state = m_state->generateStateObjectForFrontend();
228 }
229
230 void InspectorController::restoreInspectorStateFromCookie(const String& inspectorStateCookie)
231 {
232     m_state->restoreFromInspectorCookie(inspectorStateCookie);
233     if (m_state->getBoolean(InspectorState::timelineProfilerEnabled))
234         startTimelineProfiler();
235 #if ENABLE(JAVASCRIPT_DEBUGGER)
236     if (m_state->getBoolean(InspectorState::userInitiatedProfiling))
237         startUserInitiatedProfiling();
238 #endif    
239 }
240
241 void InspectorController::inspect(Node* node)
242 {
243     if (!enabled())
244         return;
245
246     show();
247
248     if (node->nodeType() != Node::ELEMENT_NODE && node->nodeType() != Node::DOCUMENT_NODE)
249         node = node->parentNode();
250     m_nodeToFocus = node;
251
252     if (!m_frontend)
253         return;
254
255     focusNode();
256 }
257
258 void InspectorController::focusNode()
259 {
260     if (!enabled())
261         return;
262
263     ASSERT(m_frontend);
264     ASSERT(m_nodeToFocus);
265
266     long id = m_domAgent->pushNodePathToFrontend(m_nodeToFocus.get());
267     m_frontend->updateFocusedNode(id);
268     m_nodeToFocus = 0;
269 }
270
271 void InspectorController::highlight(Node* node)
272 {
273     if (!enabled())
274         return;
275     ASSERT_ARG(node, node);
276     m_highlightedNode = node;
277     m_client->highlight(node);
278 }
279
280 void InspectorController::highlightDOMNode(long nodeId)
281 {
282     Node* node = 0;
283     if (m_domAgent && (node = m_domAgent->nodeForId(nodeId)))
284         highlight(node);
285 }
286
287 void InspectorController::highlightFrame(unsigned long frameId)
288 {
289     Frame* mainFrame = m_inspectedPage->mainFrame();
290     for (Frame* frame = mainFrame; frame; frame = frame->tree()->traverseNext(mainFrame)) {
291         if (reinterpret_cast<uintptr_t>(frame) == frameId && frame->ownerElement()) {
292             highlight(frame->ownerElement());
293             return;
294         }
295     }
296 }
297
298 void InspectorController::hideHighlight()
299 {
300     if (!enabled())
301         return;
302     m_highlightedNode = 0;
303     m_client->hideHighlight();
304 }
305
306 void InspectorController::setConsoleMessagesEnabled(bool enabled, bool* newState)
307 {
308     *newState = enabled;
309     setConsoleMessagesEnabled(enabled);
310 }
311
312 void InspectorController::setConsoleMessagesEnabled(bool enabled)
313 {
314     m_state->setBoolean(InspectorState::consoleMessagesEnabled, enabled);
315     if (!enabled)
316         return;
317
318     if (m_expiredConsoleMessageCount)
319         m_frontend->updateConsoleMessageExpiredCount(m_expiredConsoleMessageCount);
320     unsigned messageCount = m_consoleMessages.size();
321     for (unsigned i = 0; i < messageCount; ++i)
322         m_consoleMessages[i]->addToFrontend(m_frontend.get(), m_injectedScriptHost.get());
323 }
324
325 void InspectorController::addMessageToConsole(MessageSource source, MessageType type, MessageLevel level, const String& message, PassRefPtr<ScriptArguments> arguments, PassRefPtr<ScriptCallStack> callStack)
326 {
327     if (!enabled())
328         return;
329
330     addConsoleMessage(new ConsoleMessage(source, type, level, message, arguments, callStack));
331 }
332
333 void InspectorController::addMessageToConsole(MessageSource source, MessageType type, MessageLevel level, const String& message, unsigned lineNumber, const String& sourceID)
334 {
335     if (!enabled())
336         return;
337
338     addConsoleMessage(new ConsoleMessage(source, type, level, message, lineNumber, sourceID));
339 }
340
341 void InspectorController::addConsoleMessage(PassOwnPtr<ConsoleMessage> consoleMessage)
342 {
343     ASSERT(enabled());
344     ASSERT_ARG(consoleMessage, consoleMessage);
345
346     if (m_previousMessage && m_previousMessage->isEqual(consoleMessage.get())) {
347         m_previousMessage->incrementCount();
348         if (m_state->getBoolean(InspectorState::consoleMessagesEnabled) && m_frontend)
349             m_previousMessage->updateRepeatCountInConsole(m_frontend.get());
350     } else {
351         m_previousMessage = consoleMessage.get();
352         m_consoleMessages.append(consoleMessage);
353         if (m_state->getBoolean(InspectorState::consoleMessagesEnabled) && m_frontend)
354             m_previousMessage->addToFrontend(m_frontend.get(), m_injectedScriptHost.get());
355     }
356
357     if (!m_frontend && m_consoleMessages.size() >= maximumConsoleMessages) {
358         m_expiredConsoleMessageCount += expireConsoleMessagesStep;
359         m_consoleMessages.remove(0, expireConsoleMessagesStep);
360     }
361 }
362
363 void InspectorController::clearConsoleMessages()
364 {
365     m_consoleMessages.clear();
366     m_expiredConsoleMessageCount = 0;
367     m_previousMessage = 0;
368     m_injectedScriptHost->releaseWrapperObjectGroup(0 /* release the group in all scripts */, "console");
369     if (m_domAgent)
370         m_domAgent->releaseDanglingNodes();
371     if (m_frontend)
372         m_frontend->consoleMessagesCleared();
373 }
374
375 void InspectorController::startGroup(PassRefPtr<ScriptArguments> arguments, PassRefPtr<ScriptCallStack> callStack, bool collapsed)
376 {
377     addConsoleMessage(new ConsoleMessage(JSMessageSource, collapsed ? StartGroupCollapsedMessageType : StartGroupMessageType, LogMessageLevel, "", arguments, callStack));
378 }
379
380 void InspectorController::endGroup(MessageSource source, unsigned lineNumber, const String& sourceURL)
381 {
382     addConsoleMessage(new ConsoleMessage(source, EndGroupMessageType, LogMessageLevel, String(), lineNumber, sourceURL));
383 }
384
385 void InspectorController::markTimeline(const String& message)
386 {
387     if (timelineAgent())
388         timelineAgent()->didMarkTimeline(message);
389 }
390
391 void InspectorController::mouseDidMoveOverElement(const HitTestResult& result, unsigned)
392 {
393     if (!enabled() || !searchingForNodeInPage())
394         return;
395
396     Node* node = result.innerNode();
397     while (node && node->nodeType() == Node::TEXT_NODE)
398         node = node->parentNode();
399     if (node)
400         highlight(node);
401 }
402
403 void InspectorController::handleMousePress()
404 {
405     if (!enabled())
406         return;
407
408     ASSERT(searchingForNodeInPage());
409     if (!m_highlightedNode)
410         return;
411
412     RefPtr<Node> node = m_highlightedNode;
413     setSearchingForNode(false);
414     inspect(node.get());
415 }
416
417 void InspectorController::setInspectorFrontendClient(PassOwnPtr<InspectorFrontendClient> client)
418 {
419     ASSERT(!m_inspectorFrontendClient);
420     m_inspectorFrontendClient = client;
421 }
422
423 void InspectorController::inspectedWindowScriptObjectCleared(Frame* frame)
424 {
425     // If the page is supposed to serve as InspectorFrontend notify inspetor frontend
426     // client that it's cleared so that the client can expose inspector bindings.
427     if (m_inspectorFrontendClient && frame == m_inspectedPage->mainFrame())
428         m_inspectorFrontendClient->windowObjectCleared();
429
430     if (enabled()) {
431         if (m_frontend && frame == m_inspectedPage->mainFrame())
432             m_injectedScriptHost->discardInjectedScripts();
433         if (m_scriptsToEvaluateOnLoad.size()) {
434             ScriptState* scriptState = mainWorldScriptState(frame);
435             for (Vector<String>::iterator it = m_scriptsToEvaluateOnLoad.begin();
436                  it != m_scriptsToEvaluateOnLoad.end(); ++it) {
437                 m_injectedScriptHost->injectScript(*it, scriptState);
438             }
439         }
440     }
441     if (!m_inspectorExtensionAPI.isEmpty())
442         m_injectedScriptHost->injectScript(m_inspectorExtensionAPI, mainWorldScriptState(frame));
443 }
444
445 void InspectorController::setSearchingForNode(bool enabled)
446 {
447     if (searchingForNodeInPage() == enabled)
448         return;
449     m_state->setBoolean(InspectorState::searchingForNode, enabled);
450     if (!enabled)
451         hideHighlight();
452 }
453
454 void InspectorController::setSearchingForNode(bool enabled, bool* newState)
455 {
456     *newState = enabled;
457     setSearchingForNode(enabled);
458 }
459
460 void InspectorController::setMonitoringXHREnabled(bool enabled, bool* newState)
461 {
462     *newState = enabled;
463     m_state->setBoolean(InspectorState::monitoringXHR, enabled);
464 }
465
466 void InspectorController::connectFrontend()
467 {
468     m_openingFrontend = false;
469     releaseFrontendLifetimeAgents();
470     m_frontend = new InspectorFrontend(m_client);
471     m_domAgent = InspectorDOMAgent::create(m_frontend.get());
472     m_resourceAgent = InspectorResourceAgent::create(m_inspectedPage, m_frontend.get());
473
474     m_cssAgent->setDOMAgent(m_domAgent.get());
475
476 #if ENABLE(DATABASE)
477     m_databaseAgent = InspectorDatabaseAgent::create(&m_databaseResources, m_frontend.get());
478 #endif
479
480 #if ENABLE(DOM_STORAGE)
481     m_domStorageAgent = InspectorDOMStorageAgent::create(&m_domStorageResources, m_frontend.get());
482 #endif
483
484     if (m_timelineAgent)
485         m_timelineAgent->resetFrontendProxyObject(m_frontend.get());
486
487     // Initialize Web Inspector title.
488     m_frontend->inspectedURLChanged(m_inspectedPage->mainFrame()->loader()->url().string());
489
490 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
491     m_applicationCacheAgent = new InspectorApplicationCacheAgent(this, m_frontend.get());
492 #endif
493
494 #if ENABLE(FILE_SYSTEM)
495     m_fileSystemAgent = InspectorFileSystemAgent::create(this, m_frontend.get());
496 #endif
497     
498     if (!InspectorInstrumentation::hasFrontends())
499         ScriptController::setCaptureCallStackForUncaughtExceptions(true);
500     InspectorInstrumentation::frontendCreated();
501 }
502
503 void InspectorController::reuseFrontend()
504 {
505     connectFrontend();
506     restoreDebugger();
507     restoreProfiler(ProfilerRestoreResetAgent);
508 }
509
510 void InspectorController::show()
511 {
512     if (!enabled())
513         return;
514
515     if (m_openingFrontend)
516         return;
517
518     if (m_frontend)
519         m_frontend->bringToFront();
520     else {
521         m_openingFrontend = true;
522         m_client->openInspectorFrontend(this);
523     }
524 }
525
526 void InspectorController::showPanel(const String& panel)
527 {
528     if (!enabled())
529         return;
530
531     show();
532
533     if (!m_frontend) {
534         m_showAfterVisible = panel;
535         return;
536     }
537     m_frontend->showPanel(panel);
538 }
539
540 void InspectorController::close()
541 {
542     if (!m_frontend)
543         return;
544     m_frontend->disconnectFromBackend();
545     disconnectFrontend();
546 }
547
548 void InspectorController::disconnectFrontend()
549 {
550     if (!m_frontend)
551         return;
552
553     m_frontend.clear();
554
555     InspectorInstrumentation::frontendDeleted();
556     if (!InspectorInstrumentation::hasFrontends())
557         ScriptController::setCaptureCallStackForUncaughtExceptions(false);
558
559 #if ENABLE(JAVASCRIPT_DEBUGGER)
560     // If the window is being closed with the debugger enabled,
561     // remember this state to re-enable debugger on the next window
562     // opening.
563     bool debuggerWasEnabled = debuggerEnabled();
564     disableDebugger();
565     m_attachDebuggerWhenShown = debuggerWasEnabled;
566 #endif
567     setSearchingForNode(false);
568     unbindAllResources();
569     stopTimelineProfiler();
570
571     hideHighlight();
572
573 #if ENABLE(JAVASCRIPT_DEBUGGER)
574     m_profilerAgent->setFrontend(0);
575     m_profilerAgent->stopUserInitiatedProfiling(true);
576 #endif
577
578     releaseFrontendLifetimeAgents();
579     m_timelineAgent.clear();
580     m_extraHeaders.clear();
581 }
582
583 void InspectorController::releaseFrontendLifetimeAgents()
584 {
585     m_resourceAgent.clear();
586
587     // This should be invoked prior to m_domAgent destruction.
588     m_cssAgent->setDOMAgent(0);
589
590     // m_domAgent is RefPtr. Remove DOM listeners first to ensure that there are
591     // no references to the DOM agent from the DOM tree.
592     if (m_domAgent)
593         m_domAgent->reset();
594     m_domAgent.clear();
595
596 #if ENABLE(DATABASE)
597     if (m_databaseAgent)
598         m_databaseAgent->clearFrontend();
599     m_databaseAgent.clear();
600 #endif
601
602 #if ENABLE(DOM_STORAGE)
603     m_domStorageAgent.clear();
604 #endif
605
606 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
607     m_applicationCacheAgent.clear();
608 #endif
609
610 #if ENABLE(FILE_SYSTEM)
611     if (m_fileSystemAgent)
612         m_fileSystemAgent->stop(); 
613         m_fileSystemAgent.clear();
614 #endif
615 }
616
617 void InspectorController::populateScriptObjects()
618 {
619     ASSERT(m_frontend);
620     if (!m_frontend)
621         return;
622
623     if (!m_showAfterVisible.isEmpty()) {
624         showPanel(m_showAfterVisible);
625         m_showAfterVisible = "";
626     }
627
628 #if ENABLE(JAVASCRIPT_DEBUGGER)
629     if (m_profilerAgent->enabled())
630         m_frontend->profilerWasEnabled();
631 #endif
632
633     m_domAgent->setDocument(m_inspectedPage->mainFrame()->document());
634
635     if (m_nodeToFocus)
636         focusNode();
637
638 #if ENABLE(DATABASE)
639     DatabaseResourcesMap::iterator databasesEnd = m_databaseResources.end();
640     for (DatabaseResourcesMap::iterator it = m_databaseResources.begin(); it != databasesEnd; ++it)
641         it->second->bind(m_frontend.get());
642 #endif
643 #if ENABLE(DOM_STORAGE)
644     DOMStorageResourcesMap::iterator domStorageEnd = m_domStorageResources.end();
645     for (DOMStorageResourcesMap::iterator it = m_domStorageResources.begin(); it != domStorageEnd; ++it)
646         it->second->bind(m_frontend.get());
647 #endif
648 #if ENABLE(JAVASCRIPT_DEBUGGER) && ENABLE(WORKERS)
649     WorkersMap::iterator workersEnd = m_workers.end();
650     for (WorkersMap::iterator it = m_workers.begin(); it != workersEnd; ++it) {
651         InspectorWorkerResource* worker = it->second.get();
652         m_frontend->didCreateWorker(worker->id(), worker->url(), worker->isSharedWorker());
653     }
654 #endif
655
656     // Dispatch pending frontend commands
657     for (Vector<pair<long, String> >::iterator it = m_pendingEvaluateTestCommands.begin(); it != m_pendingEvaluateTestCommands.end(); ++it)
658         m_frontend->evaluateForTestInFrontend((*it).first, (*it).second);
659     m_pendingEvaluateTestCommands.clear();
660
661     restoreDebugger();
662     restoreProfiler(ProfilerRestoreNoAction);
663 }
664
665 void InspectorController::restoreDebugger()
666 {
667     ASSERT(m_frontend);
668 #if ENABLE(JAVASCRIPT_DEBUGGER)
669     if (InspectorDebuggerAgent::isDebuggerAlwaysEnabled())
670         enableDebuggerFromFrontend(false);
671     else {
672         if (m_state->getBoolean(InspectorState::debuggerAlwaysEnabled) || m_attachDebuggerWhenShown)
673             enableDebugger();
674     }
675 #endif
676 }
677
678 void InspectorController::restoreProfiler(ProfilerRestoreAction action)
679 {
680     ASSERT(m_frontend);
681 #if ENABLE(JAVASCRIPT_DEBUGGER)
682     m_profilerAgent->setFrontend(m_frontend.get());
683     if (!ScriptProfiler::isProfilerAlwaysEnabled() && m_state->getBoolean(InspectorState::profilerAlwaysEnabled))
684         enableProfiler();
685     if (action == ProfilerRestoreResetAgent)
686         m_profilerAgent->resetState();
687 #endif
688 }
689
690 void InspectorController::unbindAllResources()
691 {
692 #if ENABLE(DATABASE)
693     DatabaseResourcesMap::iterator databasesEnd = m_databaseResources.end();
694     for (DatabaseResourcesMap::iterator it = m_databaseResources.begin(); it != databasesEnd; ++it)
695         it->second->unbind();
696 #endif
697 #if ENABLE(DOM_STORAGE)
698     DOMStorageResourcesMap::iterator domStorageEnd = m_domStorageResources.end();
699     for (DOMStorageResourcesMap::iterator it = m_domStorageResources.begin(); it != domStorageEnd; ++it)
700         it->second->unbind();
701 #endif
702     if (m_timelineAgent)
703         m_timelineAgent->reset();
704 }
705
706 void InspectorController::didCommitLoad(DocumentLoader* loader)
707 {
708     if (!enabled())
709         return;
710
711     if (m_resourceAgent)
712         m_resourceAgent->didCommitLoad(loader);
713     
714     ASSERT(m_inspectedPage);
715
716     if (loader->frame() == m_inspectedPage->mainFrame()) {
717         if (m_frontend)
718             m_frontend->inspectedURLChanged(loader->url().string());
719
720         m_injectedScriptHost->discardInjectedScripts();
721         clearConsoleMessages();
722
723         m_times.clear();
724         m_counts.clear();
725
726 #if ENABLE(JAVASCRIPT_DEBUGGER)
727         if (m_debuggerAgent) {
728             m_debuggerAgent->clearForPageNavigation();
729             restoreStickyBreakpoints();
730         }
731 #endif
732
733 #if ENABLE(JAVASCRIPT_DEBUGGER) && USE(JSC)
734         m_profilerAgent->stopUserInitiatedProfiling(true);
735         m_profilerAgent->resetState();
736 #endif
737
738         // unbindAllResources should be called before database and DOM storage
739         // resources are cleared so that it has a chance to unbind them.
740         unbindAllResources();
741
742         if (m_frontend) {
743             m_frontend->reset();
744             m_domAgent->reset();
745             m_cssAgent->reset();
746         }
747 #if ENABLE(WORKERS)
748         m_workers.clear();
749 #endif
750 #if ENABLE(DATABASE)
751         m_databaseResources.clear();
752 #endif
753 #if ENABLE(DOM_STORAGE)
754         m_domStorageResources.clear();
755 #endif
756
757         if (m_frontend) {
758             m_mainResourceIdentifier = 0;
759             m_frontend->didCommitLoad();
760             m_domAgent->setDocument(m_inspectedPage->mainFrame()->document());
761         }
762     }
763 }
764
765 void InspectorController::frameDetachedFromParent(Frame* rootFrame)
766 {
767     if (!enabled())
768         return;
769
770     if (m_resourceAgent)
771         m_resourceAgent->frameDetachedFromParent(rootFrame);
772 }
773
774 void InspectorController::didLoadResourceFromMemoryCache(DocumentLoader* loader, const CachedResource* cachedResource)
775 {
776     if (!enabled())
777         return;
778
779     ensureSettingsLoaded();
780
781     if (m_resourceAgent)
782         m_resourceAgent->didLoadResourceFromMemoryCache(loader, cachedResource);
783 }
784
785 void InspectorController::identifierForInitialRequest(unsigned long identifier, DocumentLoader* loader, const ResourceRequest& request)
786 {
787     if (!enabled())
788         return;
789     ASSERT(m_inspectedPage);
790
791     bool isMainResource = isMainResourceLoader(loader, request.url());
792     if (isMainResource)
793         m_mainResourceIdentifier = identifier;
794
795     ensureSettingsLoaded();
796
797     if (m_resourceAgent)
798         m_resourceAgent->identifierForInitialRequest(identifier, request.url(), loader);
799 }
800
801 void InspectorController::mainResourceFiredDOMContentEvent(DocumentLoader* loader, const KURL& url)
802 {
803     if (!enabled() || !isMainResourceLoader(loader, url))
804         return;
805
806     if (m_timelineAgent)
807         m_timelineAgent->didMarkDOMContentEvent();
808     if (m_frontend)
809         m_frontend->domContentEventFired(currentTime());
810 }
811
812 void InspectorController::mainResourceFiredLoadEvent(DocumentLoader* loader, const KURL& url)
813 {
814     if (!enabled() || !isMainResourceLoader(loader, url))
815         return;
816
817     if (m_timelineAgent)
818         m_timelineAgent->didMarkLoadEvent();
819     if (m_frontend)
820         m_frontend->loadEventFired(currentTime());
821 }
822
823 bool InspectorController::isMainResourceLoader(DocumentLoader* loader, const KURL& requestUrl)
824 {
825     return loader->frame() == m_inspectedPage->mainFrame() && requestUrl == loader->requestURL();
826 }
827
828 void InspectorController::willSendRequest(unsigned long identifier, ResourceRequest& request, const ResourceResponse& redirectResponse)
829 {
830     if (!enabled())
831         return;
832
833     request.setReportLoadTiming(true);
834
835     if (m_frontend) {
836         // Only enable raw headers if front-end is attached, as otherwise we may lack
837         // permissions to fetch the headers.
838         request.setReportRawHeaders(true);
839
840         if (m_extraHeaders) {
841             HTTPHeaderMap::const_iterator end = m_extraHeaders->end();
842             for (HTTPHeaderMap::const_iterator it = m_extraHeaders->begin(); it != end; ++it)
843                 request.setHTTPHeaderField(it->first, it->second);
844         }
845     }
846
847     bool isMainResource = m_mainResourceIdentifier == identifier;
848     if (m_timelineAgent)
849         m_timelineAgent->willSendResourceRequest(identifier, isMainResource, request);
850
851     if (m_resourceAgent)
852         m_resourceAgent->willSendRequest(identifier, request, redirectResponse);
853 }
854
855 void InspectorController::markResourceAsCached(unsigned long identifier)
856 {
857     if (!enabled())
858         return;
859
860     if (m_resourceAgent)
861         m_resourceAgent->markResourceAsCached(identifier);
862 }
863
864 void InspectorController::didReceiveResponse(unsigned long identifier, DocumentLoader* loader, const ResourceResponse& response)
865 {
866     if (!enabled())
867         return;
868
869     if (m_resourceAgent)
870         m_resourceAgent->didReceiveResponse(identifier, loader, response);
871
872     if (response.httpStatusCode() >= 400) {
873         String message = makeString("Failed to load resource: the server responded with a status of ", String::number(response.httpStatusCode()), " (", response.httpStatusText(), ')');
874         addConsoleMessage(new ConsoleMessage(OtherMessageSource, NetworkErrorMessageType, ErrorMessageLevel, message, response.url().string(), identifier));
875     }
876 }
877
878 void InspectorController::didReceiveContentLength(unsigned long identifier, int lengthReceived)
879 {
880     if (!enabled())
881         return;
882
883     if (m_resourceAgent)
884         m_resourceAgent->didReceiveContentLength(identifier, lengthReceived);
885 }
886
887 void InspectorController::didFinishLoading(unsigned long identifier, double finishTime)
888 {
889     if (!enabled())
890         return;
891
892     if (m_timelineAgent)
893         m_timelineAgent->didFinishLoadingResource(identifier, false, finishTime);
894
895     if (m_resourceAgent)
896         m_resourceAgent->didFinishLoading(identifier, finishTime);
897 }
898
899 void InspectorController::didFailLoading(unsigned long identifier, const ResourceError& error)
900 {
901     if (!enabled())
902         return;
903
904     if (m_timelineAgent)
905         m_timelineAgent->didFinishLoadingResource(identifier, true, 0);
906
907     String message = "Failed to load resource";
908         if (!error.localizedDescription().isEmpty())
909             message += ": " + error.localizedDescription();
910         addConsoleMessage(new ConsoleMessage(OtherMessageSource, NetworkErrorMessageType, ErrorMessageLevel, message, error.failingURL(), identifier));
911
912     if (m_resourceAgent)
913         m_resourceAgent->didFailLoading(identifier, error);
914 }
915
916 void InspectorController::resourceRetrievedByXMLHttpRequest(unsigned long identifier, const String& sourceString, const String& url, const String& sendURL, unsigned sendLineNumber)
917 {
918     if (!enabled())
919         return;
920
921     if (m_state->getBoolean(InspectorState::monitoringXHR))
922         addMessageToConsole(JSMessageSource, LogMessageType, LogMessageLevel, "XHR finished loading: \"" + url + "\".", sendLineNumber, sendURL);
923
924     if (m_resourceAgent)
925         m_resourceAgent->setInitialContent(identifier, sourceString, "XHR");
926 }
927
928 void InspectorController::scriptImported(unsigned long identifier, const String& sourceString)
929 {
930     if (!enabled())
931         return;
932
933     if (m_resourceAgent)
934         m_resourceAgent->setInitialContent(identifier, sourceString, "Script");
935 }
936
937 void InspectorController::ensureSettingsLoaded()
938 {
939     if (m_settingsLoaded)
940         return;
941     m_settingsLoaded = true;
942
943     m_state->loadFromSettings();
944 }
945
946 void InspectorController::startTimelineProfiler()
947 {
948     if (!enabled())
949         return;
950
951     if (m_timelineAgent)
952         return;
953
954     m_timelineAgent = new InspectorTimelineAgent(m_frontend.get());
955     if (m_frontend)
956         m_frontend->timelineProfilerWasStarted();
957
958     m_state->setBoolean(InspectorState::timelineProfilerEnabled, true);
959 }
960
961 void InspectorController::stopTimelineProfiler()
962 {
963     if (!enabled())
964         return;
965
966     if (!m_timelineAgent)
967         return;
968
969     m_timelineAgent = 0;
970     if (m_frontend)
971         m_frontend->timelineProfilerWasStopped();
972
973     m_state->setBoolean(InspectorState::timelineProfilerEnabled, false);
974 }
975
976 #if ENABLE(WORKERS)
977 class PostWorkerNotificationToFrontendTask : public ScriptExecutionContext::Task {
978 public:
979     static PassOwnPtr<PostWorkerNotificationToFrontendTask> create(PassRefPtr<InspectorWorkerResource> worker, InspectorController::WorkerAction action)
980     {
981         return new PostWorkerNotificationToFrontendTask(worker, action);
982     }
983
984 private:
985     PostWorkerNotificationToFrontendTask(PassRefPtr<InspectorWorkerResource> worker, InspectorController::WorkerAction action)
986         : m_worker(worker)
987         , m_action(action)
988     {
989     }
990
991     virtual void performTask(ScriptExecutionContext* scriptContext)
992     {
993         if (InspectorController* inspector = scriptContext->inspectorController())
994             inspector->postWorkerNotificationToFrontend(*m_worker, m_action);
995     }
996
997 private:
998     RefPtr<InspectorWorkerResource> m_worker;
999     InspectorController::WorkerAction m_action;
1000 };
1001
1002 void InspectorController::postWorkerNotificationToFrontend(const InspectorWorkerResource& worker, InspectorController::WorkerAction action)
1003 {
1004     if (!m_frontend)
1005         return;
1006 #if ENABLE(JAVASCRIPT_DEBUGGER)
1007     switch (action) {
1008     case InspectorController::WorkerCreated:
1009         m_frontend->didCreateWorker(worker.id(), worker.url(), worker.isSharedWorker());
1010         break;
1011     case InspectorController::WorkerDestroyed:
1012         m_frontend->didDestroyWorker(worker.id());
1013         break;
1014     }
1015 #endif
1016 }
1017
1018 void InspectorController::didCreateWorker(intptr_t id, const String& url, bool isSharedWorker)
1019 {
1020     if (!enabled())
1021         return;
1022
1023     RefPtr<InspectorWorkerResource> workerResource(InspectorWorkerResource::create(id, url, isSharedWorker));
1024     m_workers.set(id, workerResource);
1025     if (m_inspectedPage && m_frontend)
1026         m_inspectedPage->mainFrame()->document()->postTask(PostWorkerNotificationToFrontendTask::create(workerResource, InspectorController::WorkerCreated));
1027 }
1028
1029 void InspectorController::didDestroyWorker(intptr_t id)
1030 {
1031     if (!enabled())
1032         return;
1033
1034     WorkersMap::iterator workerResource = m_workers.find(id);
1035     if (workerResource == m_workers.end())
1036         return;
1037     if (m_inspectedPage && m_frontend)
1038         m_inspectedPage->mainFrame()->document()->postTask(PostWorkerNotificationToFrontendTask::create(workerResource->second, InspectorController::WorkerDestroyed));
1039     m_workers.remove(workerResource);
1040 }
1041 #endif // ENABLE(WORKERS)
1042
1043 #if ENABLE(DATABASE)
1044 void InspectorController::didOpenDatabase(PassRefPtr<Database> database, const String& domain, const String& name, const String& version)
1045 {
1046     if (!enabled())
1047         return;
1048
1049     RefPtr<InspectorDatabaseResource> resource = InspectorDatabaseResource::create(database, domain, name, version);
1050
1051     m_databaseResources.set(resource->id(), resource);
1052
1053     // Resources are only bound while visible.
1054     if (m_frontend)
1055         resource->bind(m_frontend.get());
1056 }
1057 #endif
1058
1059 void InspectorController::getCookies(RefPtr<InspectorArray>* cookies, WTF::String* cookiesString)
1060 {
1061     // If we can get raw cookies.
1062     ListHashSet<Cookie> rawCookiesList;
1063
1064     // If we can't get raw cookies - fall back to String representation
1065     String stringCookiesList;
1066
1067     // Return value to getRawCookies should be the same for every call because
1068     // the return value is platform/network backend specific, and the call will
1069     // always return the same true/false value.
1070     bool rawCookiesImplemented = false;
1071
1072     for (Frame* frame = m_inspectedPage->mainFrame(); frame; frame = frame->tree()->traverseNext(m_inspectedPage->mainFrame())) {
1073         Document* document = frame->document();
1074         const CachedResourceLoader::DocumentResourceMap& allResources = document->cachedResourceLoader()->allCachedResources();
1075         CachedResourceLoader::DocumentResourceMap::const_iterator end = allResources.end();
1076         for (CachedResourceLoader::DocumentResourceMap::const_iterator it = allResources.begin(); it != end; ++it) {
1077             Vector<Cookie> docCookiesList;
1078             rawCookiesImplemented = getRawCookies(document, KURL(ParsedURLString, it->second->url()), docCookiesList);
1079
1080             if (!rawCookiesImplemented) {
1081                 // FIXME: We need duplication checking for the String representation of cookies.
1082                 ExceptionCode ec = 0;
1083                 stringCookiesList += document->cookie(ec);
1084                 // Exceptions are thrown by cookie() in sandboxed frames. That won't happen here
1085                 // because "document" is the document of the main frame of the page.
1086                 ASSERT(!ec);
1087             } else {
1088                 int cookiesSize = docCookiesList.size();
1089                 for (int i = 0; i < cookiesSize; i++) {
1090                     if (!rawCookiesList.contains(docCookiesList[i]))
1091                         rawCookiesList.add(docCookiesList[i]);
1092                 }
1093             }
1094         }
1095     }
1096
1097     if (rawCookiesImplemented)
1098         *cookies = buildArrayForCookies(rawCookiesList);
1099     else
1100         *cookiesString = stringCookiesList;
1101 }
1102
1103 PassRefPtr<InspectorArray> InspectorController::buildArrayForCookies(ListHashSet<Cookie>& cookiesList)
1104 {
1105     RefPtr<InspectorArray> cookies = InspectorArray::create();
1106
1107     ListHashSet<Cookie>::iterator end = cookiesList.end();
1108     ListHashSet<Cookie>::iterator it = cookiesList.begin();
1109     for (int i = 0; it != end; ++it, i++)
1110         cookies->pushObject(buildObjectForCookie(*it));
1111
1112     return cookies;
1113 }
1114
1115 PassRefPtr<InspectorObject> InspectorController::buildObjectForCookie(const Cookie& cookie)
1116 {
1117     RefPtr<InspectorObject> value = InspectorObject::create();
1118     value->setString("name", cookie.name);
1119     value->setString("value", cookie.value);
1120     value->setString("domain", cookie.domain);
1121     value->setString("path", cookie.path);
1122     value->setNumber("expires", cookie.expires);
1123     value->setNumber("size", (cookie.name.length() + cookie.value.length()));
1124     value->setBoolean("httpOnly", cookie.httpOnly);
1125     value->setBoolean("secure", cookie.secure);
1126     value->setBoolean("session", cookie.session);
1127     return value;
1128 }
1129
1130 void InspectorController::deleteCookie(const String& cookieName, const String& domain)
1131 {
1132     for (Frame* frame = m_inspectedPage->mainFrame(); frame; frame = frame->tree()->traverseNext(m_inspectedPage->mainFrame())) {
1133         Document* document = frame->document();
1134         if (document->url().host() != domain)
1135             continue;
1136         const CachedResourceLoader::DocumentResourceMap& allResources = document->cachedResourceLoader()->allCachedResources();
1137         CachedResourceLoader::DocumentResourceMap::const_iterator end = allResources.end();
1138         for (CachedResourceLoader::DocumentResourceMap::const_iterator it = allResources.begin(); it != end; ++it)
1139             WebCore::deleteCookie(document, KURL(ParsedURLString, it->second->url()), cookieName);
1140     }
1141 }
1142
1143 #if ENABLE(DOM_STORAGE)
1144 void InspectorController::didUseDOMStorage(StorageArea* storageArea, bool isLocalStorage, Frame* frame)
1145 {
1146     if (!enabled())
1147         return;
1148
1149     DOMStorageResourcesMap::iterator domStorageEnd = m_domStorageResources.end();
1150     for (DOMStorageResourcesMap::iterator it = m_domStorageResources.begin(); it != domStorageEnd; ++it)
1151         if (it->second->isSameHostAndType(frame, isLocalStorage))
1152             return;
1153
1154     RefPtr<Storage> domStorage = Storage::create(frame, storageArea);
1155     RefPtr<InspectorDOMStorageResource> resource = InspectorDOMStorageResource::create(domStorage.get(), isLocalStorage, frame);
1156
1157     m_domStorageResources.set(resource->id(), resource);
1158
1159     // Resources are only bound while visible.
1160     if (m_frontend)
1161         resource->bind(m_frontend.get());
1162 }
1163 #endif
1164
1165 #if ENABLE(WEB_SOCKETS)
1166 void InspectorController::didCreateWebSocket(unsigned long identifier, const KURL& requestURL, const KURL& documentURL)
1167 {
1168     if (!enabled())
1169         return;
1170     ASSERT(m_inspectedPage);
1171
1172     if (m_resourceAgent)
1173         m_resourceAgent->didCreateWebSocket(identifier, requestURL);
1174     UNUSED_PARAM(documentURL);
1175 }
1176
1177 void InspectorController::willSendWebSocketHandshakeRequest(unsigned long identifier, const WebSocketHandshakeRequest& request)
1178 {
1179     if (m_resourceAgent)
1180         m_resourceAgent->willSendWebSocketHandshakeRequest(identifier, request);
1181 }
1182
1183 void InspectorController::didReceiveWebSocketHandshakeResponse(unsigned long identifier, const WebSocketHandshakeResponse& response)
1184 {
1185     if (m_resourceAgent)
1186         m_resourceAgent->didReceiveWebSocketHandshakeResponse(identifier, response);
1187 }
1188
1189 void InspectorController::didCloseWebSocket(unsigned long identifier)
1190 {
1191     if (m_resourceAgent)
1192         m_resourceAgent->didCloseWebSocket(identifier);
1193 }
1194 #endif // ENABLE(WEB_SOCKETS)
1195
1196 #if ENABLE(JAVASCRIPT_DEBUGGER)
1197 void InspectorController::addProfile(PassRefPtr<ScriptProfile> prpProfile, unsigned lineNumber, const String& sourceURL)
1198 {
1199     if (!enabled())
1200         return;
1201     m_profilerAgent->addProfile(prpProfile, lineNumber, sourceURL);
1202 }
1203
1204 void InspectorController::addProfileFinishedMessageToConsole(PassRefPtr<ScriptProfile> prpProfile, unsigned lineNumber, const String& sourceURL)
1205 {
1206     m_profilerAgent->addProfileFinishedMessageToConsole(prpProfile, lineNumber, sourceURL);
1207 }
1208
1209 void InspectorController::addStartProfilingMessageToConsole(const String& title, unsigned lineNumber, const String& sourceURL)
1210 {
1211     m_profilerAgent->addStartProfilingMessageToConsole(title, lineNumber, sourceURL);
1212 }
1213
1214
1215 bool InspectorController::isRecordingUserInitiatedProfile() const
1216 {
1217     return m_profilerAgent->isRecordingUserInitiatedProfile();
1218 }
1219
1220 String InspectorController::getCurrentUserInitiatedProfileName(bool incrementProfileNumber)
1221 {
1222     return m_profilerAgent->getCurrentUserInitiatedProfileName(incrementProfileNumber);
1223 }
1224
1225 void InspectorController::startUserInitiatedProfiling()
1226 {
1227     if (!enabled())
1228         return;
1229     m_profilerAgent->startUserInitiatedProfiling();
1230     m_state->setBoolean(InspectorState::userInitiatedProfiling, true);
1231 }
1232
1233 void InspectorController::stopUserInitiatedProfiling()
1234 {
1235     if (!enabled())
1236         return;
1237     m_profilerAgent->stopUserInitiatedProfiling();
1238     m_state->setBoolean(InspectorState::userInitiatedProfiling, false);
1239 }
1240
1241 bool InspectorController::profilerEnabled() const
1242 {
1243     return enabled() && m_profilerAgent->enabled();
1244 }
1245
1246 void InspectorController::enableProfiler(bool always, bool skipRecompile)
1247 {
1248     if (always)
1249         m_state->setBoolean(InspectorState::profilerAlwaysEnabled, true);
1250     m_profilerAgent->enable(skipRecompile);
1251 }
1252
1253 void InspectorController::disableProfiler(bool always)
1254 {
1255     if (always)
1256         m_state->setBoolean(InspectorState::profilerAlwaysEnabled, false);
1257     m_profilerAgent->disable();
1258 }
1259 #endif
1260
1261 #if ENABLE(JAVASCRIPT_DEBUGGER)
1262 void InspectorController::enableDebuggerFromFrontend(bool always)
1263 {
1264     ASSERT(!debuggerEnabled());
1265     if (always)
1266         m_state->setBoolean(InspectorState::debuggerAlwaysEnabled, true);
1267
1268     ASSERT(m_inspectedPage);
1269
1270     m_debuggerAgent = InspectorDebuggerAgent::create(this, m_frontend.get());
1271     restoreStickyBreakpoints();
1272
1273     m_frontend->debuggerWasEnabled();
1274 }
1275
1276 void InspectorController::enableDebugger()
1277 {
1278     if (!enabled())
1279         return;
1280
1281     if (debuggerEnabled())
1282         return;
1283
1284     if (!m_frontend)
1285         m_attachDebuggerWhenShown = true;
1286     else {
1287         m_frontend->attachDebuggerWhenShown();
1288         m_attachDebuggerWhenShown = false;
1289     }
1290 }
1291
1292 void InspectorController::disableDebugger(bool always)
1293 {
1294     if (!enabled())
1295         return;
1296
1297     if (always)
1298         m_state->setBoolean(InspectorState::debuggerAlwaysEnabled, false);
1299
1300     ASSERT(m_inspectedPage);
1301
1302     m_debuggerAgent.clear();
1303
1304     m_attachDebuggerWhenShown = false;
1305
1306     if (m_frontend)
1307         m_frontend->debuggerWasDisabled();
1308 }
1309
1310 void InspectorController::resume()
1311 {
1312     if (m_debuggerAgent)
1313         m_debuggerAgent->resume();
1314 }
1315
1316 void InspectorController::setStickyBreakpoints(PassRefPtr<InspectorObject> breakpoints)
1317 {
1318     m_state->setObject(InspectorState::stickyBreakpoints, breakpoints);
1319 }
1320
1321 void InspectorController::restoreStickyBreakpoints()
1322 {
1323     m_eventListenerBreakpoints.clear();
1324     m_XHRBreakpoints.clear();
1325     m_hasXHRBreakpointWithEmptyURL = false;
1326
1327     RefPtr<InspectorObject> allBreakpoints = m_state->getObject(InspectorState::stickyBreakpoints);
1328     KURL url = m_inspectedPage->mainFrame()->loader()->url();
1329     url.removeFragmentIdentifier();
1330     RefPtr<InspectorArray> breakpoints = allBreakpoints->getArray(url);
1331     if (!breakpoints)
1332         return;
1333     for (unsigned i = 0; i < breakpoints->length(); ++i)
1334         restoreStickyBreakpoint(breakpoints->get(i)->asObject());
1335 }
1336
1337 void InspectorController::restoreStickyBreakpoint(PassRefPtr<InspectorObject> breakpoint)
1338 {
1339     DEFINE_STATIC_LOCAL(String, eventListenerBreakpointType, ("EventListener"));
1340     DEFINE_STATIC_LOCAL(String, javaScriptBreakpointType, ("JS"));
1341     DEFINE_STATIC_LOCAL(String, xhrBreakpointType, ("XHR"));
1342
1343     if (!breakpoint)
1344         return;
1345     String type;
1346     if (!breakpoint->getString("type", &type))
1347         return;
1348     bool enabled;
1349     if (!breakpoint->getBoolean("enabled", &enabled))
1350         return;
1351     RefPtr<InspectorObject> condition = breakpoint->getObject("condition");
1352     if (!condition)
1353         return;
1354
1355     if (type == eventListenerBreakpointType) {
1356         if (!enabled)
1357             return;
1358         String eventName;
1359         if (condition->getString("eventName", &eventName))
1360             setEventListenerBreakpoint(eventName);
1361     } else if (type == javaScriptBreakpointType) {
1362         String url;
1363         if (!condition->getString("url", &url))
1364             return;
1365         double lineNumber;
1366         if (!condition->getNumber("lineNumber", &lineNumber))
1367             return;
1368         String javaScriptCondition;
1369         if (!condition->getString("condition", &javaScriptCondition))
1370             return;
1371         if (m_debuggerAgent)
1372             m_debuggerAgent->setStickyBreakpoint(url, static_cast<unsigned>(lineNumber), javaScriptCondition, enabled);
1373     } else if (type == xhrBreakpointType) {
1374         if (!enabled)
1375             return;
1376         String url;
1377         if (condition->getString("url", &url))
1378             setXHRBreakpoint(url);
1379     }
1380 }
1381
1382 void InspectorController::setEventListenerBreakpoint(const String& eventName)
1383 {
1384     m_eventListenerBreakpoints.add(eventName);
1385 }
1386
1387 void InspectorController::removeEventListenerBreakpoint(const String& eventName)
1388 {
1389     m_eventListenerBreakpoints.remove(eventName);
1390 }
1391
1392 bool InspectorController::hasEventListenerBreakpoint(const String& eventName)
1393 {
1394     return m_eventListenerBreakpoints.contains(eventName);
1395 }
1396
1397 void InspectorController::setXHRBreakpoint(const String& url)
1398 {
1399     if (url.isEmpty())
1400         m_hasXHRBreakpointWithEmptyURL = true;
1401     else
1402         m_XHRBreakpoints.add(url);
1403 }
1404
1405 void InspectorController::removeXHRBreakpoint(const String& url)
1406 {
1407     if (url.isEmpty())
1408         m_hasXHRBreakpointWithEmptyURL = false;
1409     else
1410         m_XHRBreakpoints.remove(url);
1411 }
1412
1413 bool InspectorController::hasXHRBreakpoint(const String& url, String* breakpointURL)
1414 {
1415     if (m_hasXHRBreakpointWithEmptyURL) {
1416         *breakpointURL = "";
1417         return true;
1418     }
1419     for (HashSet<String>::iterator it = m_XHRBreakpoints.begin(); it != m_XHRBreakpoints.end(); ++it) {
1420         if (url.contains(*it)) {
1421             *breakpointURL = *it;
1422             return true;
1423         }
1424     }
1425     return false;
1426 }
1427
1428 #endif
1429
1430 void InspectorController::setInjectedScriptSource(const String& source)
1431 {
1432      injectedScriptHost()->setInjectedScriptSource(source);
1433 }
1434
1435 void InspectorController::dispatchOnInjectedScript(long injectedScriptId, const String& methodName, const String& arguments, RefPtr<InspectorValue>* result, bool* hadException)
1436 {
1437     if (!m_frontend)
1438         return;
1439
1440     // FIXME: explicitly pass injectedScriptId along with node id to the frontend.
1441     bool injectedScriptIdIsNodeId = injectedScriptId <= 0;
1442
1443     InjectedScript injectedScript;
1444     if (injectedScriptIdIsNodeId)
1445         injectedScript = injectedScriptForNodeId(-injectedScriptId);
1446     else
1447         injectedScript = injectedScriptHost()->injectedScriptForId(injectedScriptId);
1448
1449     if (injectedScript.hasNoValue())
1450         return;
1451
1452     injectedScript.dispatch(methodName, arguments, result, hadException);
1453 }
1454
1455 void InspectorController::releaseWrapperObjectGroup(long injectedScriptId, const String& objectGroup)
1456 {
1457     injectedScriptHost()->releaseWrapperObjectGroup(injectedScriptId, objectGroup);
1458 }
1459
1460 void InspectorController::evaluateForTestInFrontend(long callId, const String& script)
1461 {
1462     if (m_frontend)
1463         m_frontend->evaluateForTestInFrontend(callId, script);
1464     else
1465         m_pendingEvaluateTestCommands.append(pair<long, String>(callId, script));
1466 }
1467
1468 void InspectorController::didEvaluateForTestInFrontend(long callId, const String& jsonResult)
1469 {
1470     ScriptState* scriptState = scriptStateFromPage(debuggerWorld(), m_inspectedPage);
1471     ScriptObject window;
1472     ScriptGlobalObject::get(scriptState, "window", window);
1473     ScriptFunctionCall function(window, "didEvaluateForTestInFrontend");
1474     function.appendArgument(callId);
1475     function.appendArgument(jsonResult);
1476     function.call();
1477 }
1478
1479 static Path quadToPath(const FloatQuad& quad)
1480 {
1481     Path quadPath;
1482     quadPath.moveTo(quad.p1());
1483     quadPath.addLineTo(quad.p2());
1484     quadPath.addLineTo(quad.p3());
1485     quadPath.addLineTo(quad.p4());
1486     quadPath.closeSubpath();
1487     return quadPath;
1488 }
1489
1490 static void drawOutlinedQuad(GraphicsContext& context, const FloatQuad& quad, const Color& fillColor)
1491 {
1492     static const int outlineThickness = 2;
1493     static const Color outlineColor(62, 86, 180, 228);
1494
1495     Path quadPath = quadToPath(quad);
1496
1497     // Clip out the quad, then draw with a 2px stroke to get a pixel
1498     // of outline (because inflating a quad is hard)
1499     {
1500         context.save();
1501         context.clipOut(quadPath);
1502
1503         context.setStrokeThickness(outlineThickness);
1504         context.setStrokeColor(outlineColor, ColorSpaceDeviceRGB);
1505         context.strokePath(quadPath);
1506
1507         context.restore();
1508     }
1509
1510     // Now do the fill
1511     context.setFillColor(fillColor, ColorSpaceDeviceRGB);
1512     context.fillPath(quadPath);
1513 }
1514
1515 static void drawOutlinedQuadWithClip(GraphicsContext& context, const FloatQuad& quad, const FloatQuad& clipQuad, const Color& fillColor)
1516 {
1517     context.save();
1518     Path clipQuadPath = quadToPath(clipQuad);
1519     context.clipOut(clipQuadPath);
1520     drawOutlinedQuad(context, quad, fillColor);
1521     context.restore();
1522 }
1523
1524 static void drawHighlightForBox(GraphicsContext& context, const FloatQuad& contentQuad, const FloatQuad& paddingQuad, const FloatQuad& borderQuad, const FloatQuad& marginQuad)
1525 {
1526     static const Color contentBoxColor(125, 173, 217, 128);
1527     static const Color paddingBoxColor(125, 173, 217, 160);
1528     static const Color borderBoxColor(125, 173, 217, 192);
1529     static const Color marginBoxColor(125, 173, 217, 228);
1530
1531     if (marginQuad != borderQuad)
1532         drawOutlinedQuadWithClip(context, marginQuad, borderQuad, marginBoxColor);
1533     if (borderQuad != paddingQuad)
1534         drawOutlinedQuadWithClip(context, borderQuad, paddingQuad, borderBoxColor);
1535     if (paddingQuad != contentQuad)
1536         drawOutlinedQuadWithClip(context, paddingQuad, contentQuad, paddingBoxColor);
1537
1538     drawOutlinedQuad(context, contentQuad, contentBoxColor);
1539 }
1540
1541 static void drawHighlightForLineBoxesOrSVGRenderer(GraphicsContext& context, const Vector<FloatQuad>& lineBoxQuads)
1542 {
1543     static const Color lineBoxColor(125, 173, 217, 128);
1544
1545     for (size_t i = 0; i < lineBoxQuads.size(); ++i)
1546         drawOutlinedQuad(context, lineBoxQuads[i], lineBoxColor);
1547 }
1548
1549 static inline void convertFromFrameToMainFrame(Frame* frame, IntRect& rect)
1550 {
1551     rect = frame->page()->mainFrame()->view()->windowToContents(frame->view()->contentsToWindow(rect));
1552 }
1553
1554 static inline IntSize frameToMainFrameOffset(Frame* frame)
1555 {
1556     IntPoint mainFramePoint = frame->page()->mainFrame()->view()->windowToContents(frame->view()->contentsToWindow(IntPoint()));
1557     return mainFramePoint - IntPoint();
1558 }
1559
1560 void InspectorController::drawNodeHighlight(GraphicsContext& context) const
1561 {
1562     if (!m_highlightedNode)
1563         return;
1564
1565     RenderObject* renderer = m_highlightedNode->renderer();
1566     Frame* containingFrame = m_highlightedNode->document()->frame();
1567     if (!renderer || !containingFrame)
1568         return;
1569
1570     IntSize mainFrameOffset = frameToMainFrameOffset(containingFrame);
1571     IntRect boundingBox = renderer->absoluteBoundingBoxRect(true);
1572     boundingBox.move(mainFrameOffset);
1573
1574     IntRect titleReferenceBox = boundingBox;
1575
1576     ASSERT(m_inspectedPage);
1577
1578     FrameView* view = m_inspectedPage->mainFrame()->view();
1579     FloatRect overlayRect = view->visibleContentRect();
1580     if (!overlayRect.contains(boundingBox) && !boundingBox.contains(enclosingIntRect(overlayRect)))
1581         overlayRect = view->visibleContentRect();
1582     context.translate(-overlayRect.x(), -overlayRect.y());
1583
1584     // RenderSVGRoot should be highlighted through the isBox() code path, all other SVG elements should just dump their absoluteQuads().
1585 #if ENABLE(SVG)
1586     bool isSVGRenderer = renderer->node() && renderer->node()->isSVGElement() && !renderer->isSVGRoot();
1587 #else
1588     bool isSVGRenderer = false;
1589 #endif
1590
1591     if (renderer->isBox() && !isSVGRenderer) {
1592         RenderBox* renderBox = toRenderBox(renderer);
1593
1594         IntRect contentBox = renderBox->contentBoxRect();
1595
1596         IntRect paddingBox(contentBox.x() - renderBox->paddingLeft(), contentBox.y() - renderBox->paddingTop(),
1597                            contentBox.width() + renderBox->paddingLeft() + renderBox->paddingRight(), contentBox.height() + renderBox->paddingTop() + renderBox->paddingBottom());
1598         IntRect borderBox(paddingBox.x() - renderBox->borderLeft(), paddingBox.y() - renderBox->borderTop(),
1599                           paddingBox.width() + renderBox->borderLeft() + renderBox->borderRight(), paddingBox.height() + renderBox->borderTop() + renderBox->borderBottom());
1600         IntRect marginBox(borderBox.x() - renderBox->marginLeft(), borderBox.y() - renderBox->marginTop(),
1601                           borderBox.width() + renderBox->marginLeft() + renderBox->marginRight(), borderBox.height() + renderBox->marginTop() + renderBox->marginBottom());
1602
1603         titleReferenceBox = marginBox;
1604         titleReferenceBox.move(mainFrameOffset);
1605         titleReferenceBox.move(boundingBox.x(), boundingBox.y());
1606
1607         FloatQuad absContentQuad = renderBox->localToAbsoluteQuad(FloatRect(contentBox));
1608         FloatQuad absPaddingQuad = renderBox->localToAbsoluteQuad(FloatRect(paddingBox));
1609         FloatQuad absBorderQuad = renderBox->localToAbsoluteQuad(FloatRect(borderBox));
1610         FloatQuad absMarginQuad = renderBox->localToAbsoluteQuad(FloatRect(marginBox));
1611
1612         absContentQuad.move(mainFrameOffset);
1613         absPaddingQuad.move(mainFrameOffset);
1614         absBorderQuad.move(mainFrameOffset);
1615         absMarginQuad.move(mainFrameOffset);
1616
1617         drawHighlightForBox(context, absContentQuad, absPaddingQuad, absBorderQuad, absMarginQuad);
1618     } else if (renderer->isRenderInline() || isSVGRenderer) {
1619         // FIXME: We should show margins/padding/border for inlines.
1620         Vector<FloatQuad> lineBoxQuads;
1621         renderer->absoluteQuads(lineBoxQuads);
1622         for (unsigned i = 0; i < lineBoxQuads.size(); ++i)
1623             lineBoxQuads[i] += mainFrameOffset;
1624
1625         drawHighlightForLineBoxesOrSVGRenderer(context, lineBoxQuads);
1626     }
1627
1628     // Draw node title if necessary.
1629
1630     if (!m_highlightedNode->isElementNode())
1631         return;
1632
1633     WebCore::Settings* settings = containingFrame->settings();
1634     drawElementTitle(context, titleReferenceBox, overlayRect, settings);
1635 }
1636
1637 void InspectorController::drawElementTitle(GraphicsContext& context, const IntRect& boundingBox, const FloatRect& overlayRect, WebCore::Settings* settings) const
1638 {
1639     static const int rectInflatePx = 4;
1640     static const int fontHeightPx = 12;
1641     static const int borderWidthPx = 1;
1642     static const Color tooltipBackgroundColor(255, 255, 194, 255);
1643     static const Color tooltipBorderColor(Color::black);
1644     static const Color tooltipFontColor(Color::black);
1645
1646     Element* element = static_cast<Element*>(m_highlightedNode.get());
1647     bool isXHTML = element->document()->isXHTMLDocument();
1648     String nodeTitle = isXHTML ? element->nodeName() : element->nodeName().lower();
1649     const AtomicString& idValue = element->getIdAttribute();
1650     if (!idValue.isNull() && !idValue.isEmpty()) {
1651         nodeTitle += "#";
1652         nodeTitle += idValue;
1653     }
1654     if (element->hasClass() && element->isStyledElement()) {
1655         const SpaceSplitString& classNamesString = static_cast<StyledElement*>(element)->classNames();
1656         size_t classNameCount = classNamesString.size();
1657         if (classNameCount) {
1658             HashSet<AtomicString> usedClassNames;
1659             for (size_t i = 0; i < classNameCount; ++i) {
1660                 const AtomicString& className = classNamesString[i];
1661                 if (usedClassNames.contains(className))
1662                     continue;
1663                 usedClassNames.add(className);
1664                 nodeTitle += ".";
1665                 nodeTitle += className;
1666             }
1667         }
1668     }
1669
1670     Element* highlightedElement = m_highlightedNode->isElementNode() ? static_cast<Element*>(m_highlightedNode.get()) : 0;
1671     nodeTitle += " [";
1672     nodeTitle += String::number(highlightedElement ? highlightedElement->offsetWidth() : boundingBox.width());
1673     nodeTitle.append(static_cast<UChar>(0x00D7)); // &times;
1674     nodeTitle += String::number(highlightedElement ? highlightedElement->offsetHeight() : boundingBox.height());
1675     nodeTitle += "]";
1676
1677     FontDescription desc;
1678     FontFamily family;
1679     family.setFamily(settings->fixedFontFamily());
1680     desc.setFamily(family);
1681     desc.setComputedSize(fontHeightPx);
1682     Font font = Font(desc, 0, 0);
1683     font.update(0);
1684
1685     TextRun nodeTitleRun(nodeTitle);
1686     IntPoint titleBasePoint = boundingBox.bottomLeft();
1687     titleBasePoint.move(rectInflatePx, rectInflatePx);
1688     IntRect titleRect = enclosingIntRect(font.selectionRectForText(nodeTitleRun, titleBasePoint, fontHeightPx));
1689     titleRect.inflate(rectInflatePx);
1690
1691     // The initial offsets needed to compensate for a 1px-thick border stroke (which is not a part of the rectangle).
1692     int dx = -borderWidthPx;
1693     int dy = borderWidthPx;
1694
1695     // If the tip sticks beyond the right of overlayRect, right-align the tip with the said boundary.
1696     if (titleRect.right() > overlayRect.right())
1697         dx = overlayRect.right() - titleRect.right();
1698
1699     // If the tip sticks beyond the left of overlayRect, left-align the tip with the said boundary.
1700     if (titleRect.x() + dx < overlayRect.x())
1701         dx = overlayRect.x() - titleRect.x() - borderWidthPx;
1702
1703     // If the tip sticks beyond the bottom of overlayRect, show the tip at top of bounding box.
1704     if (titleRect.bottom() > overlayRect.bottom()) {
1705         dy = boundingBox.y() - titleRect.bottom() - borderWidthPx;
1706         // If the tip still sticks beyond the bottom of overlayRect, bottom-align the tip with the said boundary.
1707         if (titleRect.bottom() + dy > overlayRect.bottom())
1708             dy = overlayRect.bottom() - titleRect.bottom();
1709     }
1710
1711     // If the tip sticks beyond the top of overlayRect, show the tip at top of overlayRect.
1712     if (titleRect.y() + dy < overlayRect.y())
1713         dy = overlayRect.y() - titleRect.y() + borderWidthPx;
1714
1715     titleRect.move(dx, dy);
1716     context.setStrokeColor(tooltipBorderColor, ColorSpaceDeviceRGB);
1717     context.setStrokeThickness(borderWidthPx);
1718     context.setFillColor(tooltipBackgroundColor, ColorSpaceDeviceRGB);
1719     context.drawRect(titleRect);
1720     context.setFillColor(tooltipFontColor, ColorSpaceDeviceRGB);
1721     context.drawText(font, nodeTitleRun, IntPoint(titleRect.x() + rectInflatePx, titleRect.y() + font.height()));
1722 }
1723
1724 void InspectorController::openInInspectedWindow(const String& url)
1725 {
1726     Frame* mainFrame = m_inspectedPage->mainFrame();
1727
1728     FrameLoadRequest request(mainFrame->document()->securityOrigin(), ResourceRequest(), "_blank");
1729
1730     bool created;
1731     WindowFeatures windowFeatures;
1732     Frame* newFrame = WebCore::createWindow(mainFrame, mainFrame, request, windowFeatures, created);
1733     if (!newFrame)
1734         return;
1735
1736     UserGestureIndicator indicator(DefinitelyProcessingUserGesture);
1737     newFrame->loader()->setOpener(mainFrame);
1738     newFrame->page()->setOpenedByDOM();
1739     newFrame->loader()->changeLocation(mainFrame->document()->securityOrigin(), newFrame->loader()->completeURL(url), "", false, false);
1740 }
1741
1742 void InspectorController::count(const String& title, unsigned lineNumber, const String& sourceID)
1743 {
1744     String identifier = makeString(title, '@', sourceID, ':', String::number(lineNumber));
1745     HashMap<String, unsigned>::iterator it = m_counts.find(identifier);
1746     int count;
1747     if (it == m_counts.end())
1748         count = 1;
1749     else {
1750         count = it->second + 1;
1751         m_counts.remove(it);
1752     }
1753
1754     m_counts.add(identifier, count);
1755
1756     String message = makeString(title, ": ", String::number(count));
1757     addMessageToConsole(JSMessageSource, LogMessageType, LogMessageLevel, message, lineNumber, sourceID);
1758 }
1759
1760 void InspectorController::startTiming(const String& title)
1761 {
1762     m_times.add(title, currentTime() * 1000);
1763 }
1764
1765 bool InspectorController::stopTiming(const String& title, double& elapsed)
1766 {
1767     HashMap<String, double>::iterator it = m_times.find(title);
1768     if (it == m_times.end())
1769         return false;
1770
1771     double startTime = it->second;
1772     m_times.remove(it);
1773
1774     elapsed = currentTime() * 1000 - startTime;
1775     return true;
1776 }
1777
1778 InjectedScript InspectorController::injectedScriptForNodeId(long id)
1779 {
1780
1781     Frame* frame = 0;
1782     if (id) {
1783         ASSERT(m_domAgent);
1784         Node* node = m_domAgent->nodeForId(id);
1785         if (node) {
1786             Document* document = node->ownerDocument();
1787             if (document)
1788                 frame = document->frame();
1789         }
1790     } else
1791         frame = m_inspectedPage->mainFrame();
1792
1793     if (frame)
1794         return m_injectedScriptHost->injectedScriptFor(mainWorldScriptState(frame));
1795
1796     return InjectedScript();
1797 }
1798
1799 void InspectorController::addScriptToEvaluateOnLoad(const String& source)
1800 {
1801     m_scriptsToEvaluateOnLoad.append(source);
1802 }
1803
1804 void InspectorController::removeAllScriptsToEvaluateOnLoad()
1805 {
1806     m_scriptsToEvaluateOnLoad.clear();
1807 }
1808
1809 void InspectorController::setInspectorExtensionAPI(const String& source)
1810 {
1811     m_inspectorExtensionAPI = source;
1812 }
1813
1814 void InspectorController::reloadPage()
1815 {
1816     // FIXME: Why do we set the user gesture indicator here?
1817     UserGestureIndicator indicator(DefinitelyProcessingUserGesture);
1818     m_inspectedPage->mainFrame()->navigationScheduler()->scheduleRefresh();
1819 }
1820
1821 void InspectorController::setExtraHeaders(PassRefPtr<InspectorObject> headers)
1822 {
1823     m_extraHeaders = adoptPtr(new HTTPHeaderMap());
1824     InspectorObject::const_iterator end = headers->end();
1825     for (InspectorObject::const_iterator it = headers->begin(); it != end; ++it) {
1826         String value;
1827         if (!it->second->asString(&value))
1828             continue;
1829         m_extraHeaders->add(it->first, value);
1830     }
1831 }
1832
1833 } // namespace WebCore
1834
1835 #endif // ENABLE(INSPECTOR)