64b9494b45c1e4c82ec1bd14bb6446553b9d61a4
[WebKit-https.git] / Source / 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 "Cookie.h"
39 #include "CookieJar.h"
40 #include "DOMWindow.h"
41 #include "DOMWrapperWorld.h"
42 #include "Document.h"
43 #include "DocumentLoader.h"
44 #include "Element.h"
45 #include "FloatConversion.h"
46 #include "FloatQuad.h"
47 #include "FloatRect.h"
48 #include "Frame.h"
49 #include "FrameLoadRequest.h"
50 #include "FrameLoader.h"
51 #include "FrameTree.h"
52 #include "FrameView.h"
53 #include "GraphicsContext.h"
54 #include "HTMLFrameOwnerElement.h"
55 #include "HTTPHeaderMap.h"
56 #include "HitTestResult.h"
57 #include "InjectedScript.h"
58 #include "InjectedScriptHost.h"
59 #include "InspectorBackendDispatcher.h"
60 #include "InspectorBrowserDebuggerAgent.h"
61 #include "InspectorCSSAgent.h"
62 #include "InspectorClient.h"
63 #include "InspectorConsoleAgent.h"
64 #include "InspectorDOMAgent.h"
65 #include "InspectorDOMStorageResource.h"
66 #include "InspectorDatabaseResource.h"
67 #include "InspectorDebuggerAgent.h"
68 #include "InspectorFrontend.h"
69 #include "InspectorFrontendClient.h"
70 #include "InspectorInstrumentation.h"
71 #include "InspectorProfilerAgent.h"
72 #include "InspectorResourceAgent.h"
73 #include "InspectorRuntimeAgent.h"
74 #include "InspectorSettings.h"
75 #include "InspectorState.h"
76 #include "InspectorTimelineAgent.h"
77 #include "InspectorValues.h"
78 #include "InspectorWorkerResource.h"
79 #include "IntRect.h"
80 #include "Page.h"
81 #include "ProgressTracker.h"
82 #include "Range.h"
83 #include "RenderInline.h"
84 #include "ResourceRequest.h"
85 #include "ResourceResponse.h"
86 #include "ScriptArguments.h"
87 #include "ScriptCallStack.h"
88 #include "ScriptFunctionCall.h"
89 #include "ScriptObject.h"
90 #include "ScriptProfile.h"
91 #include "ScriptProfiler.h"
92 #include "ScriptSourceCode.h"
93 #include "ScriptState.h"
94 #include "SecurityOrigin.h"
95 #include "Settings.h"
96 #include "SharedBuffer.h"
97 #include "TextEncoding.h"
98 #include "TextIterator.h"
99 #include "TextRun.h"
100 #include "UserGestureIndicator.h"
101 #include "WindowFeatures.h"
102 #include <wtf/text/StringConcatenate.h>
103 #include <wtf/CurrentTime.h>
104 #include <wtf/ListHashSet.h>
105 #include <wtf/RefCounted.h>
106 #include <wtf/StdLibExtras.h>
107 #include <wtf/UnusedParam.h>
108
109 #if ENABLE(DATABASE)
110 #include "Database.h"
111 #include "InspectorDatabaseAgent.h"
112 #endif
113
114 #if ENABLE(DOM_STORAGE)
115 #include "InspectorDOMStorageAgent.h"
116 #include "Storage.h"
117 #include "StorageArea.h"
118 #endif
119
120 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
121 #include "InspectorApplicationCacheAgent.h"
122 #endif
123
124 #if ENABLE(FILE_SYSTEM)
125 #include "InspectorFileSystemAgent.h"
126 #endif
127
128 using namespace std;
129
130 namespace WebCore {
131
132 const char* const InspectorController::ElementsPanel = "elements";
133 const char* const InspectorController::ConsolePanel = "console";
134 const char* const InspectorController::ScriptsPanel = "scripts";
135 const char* const InspectorController::ProfilesPanel = "profiles";
136
137 InspectorController::InspectorController(Page* page, InspectorClient* client)
138     : m_inspectedPage(page)
139     , m_client(client)
140     , m_openingFrontend(false)
141     , m_cssAgent(new InspectorCSSAgent())
142     , m_state(new InspectorState(client))
143     , m_inspectorBackendDispatcher(new InspectorBackendDispatcher(this))
144     , m_injectedScriptHost(InjectedScriptHost::create(this))
145     , m_consoleAgent(new InspectorConsoleAgent(this))
146 #if ENABLE(JAVASCRIPT_DEBUGGER)
147     , m_attachDebuggerWhenShown(false)
148     , m_profilerAgent(InspectorProfilerAgent::create(this))
149 #endif
150 {
151     ASSERT_ARG(page, page);
152     ASSERT_ARG(client, client);
153 }
154
155 InspectorController::~InspectorController()
156 {
157     // These should have been cleared in inspectedPageDestroyed().
158     ASSERT(!m_client);
159     ASSERT(!m_inspectedPage);
160     ASSERT(!m_highlightedNode);
161
162     releaseFrontendLifetimeAgents();
163
164     m_injectedScriptHost->disconnectController();
165 }
166
167 void InspectorController::inspectedPageDestroyed()
168 {
169     if (m_frontend)
170         m_frontend->disconnectFromBackend();
171
172     hideHighlight();
173
174 #if ENABLE(JAVASCRIPT_DEBUGGER)
175     m_debuggerAgent.clear();
176     m_browserDebuggerAgent.clear();
177 #endif
178
179     ASSERT(m_inspectedPage);
180     m_inspectedPage = 0;
181
182     m_client->inspectorDestroyed();
183     m_client = 0;
184 }
185
186 bool InspectorController::enabled() const
187 {
188     if (!m_inspectedPage)
189         return false;
190     return m_inspectedPage->settings()->developerExtrasEnabled();
191 }
192
193 bool InspectorController::inspectorStartsAttached()
194 {
195     return m_settings->getBoolean(InspectorSettings::InspectorStartsAttached);
196 }
197
198 void InspectorController::setInspectorStartsAttached(bool attached)
199 {
200     m_settings->setBoolean(InspectorSettings::InspectorStartsAttached, attached);
201 }
202
203 void InspectorController::setInspectorAttachedHeight(long height)
204 {
205     m_settings->setLong(InspectorSettings::InspectorAttachedHeight, height);
206 }
207
208 long InspectorController::inspectorAttachedHeight() const
209 {
210     return m_settings->getLong(InspectorSettings::InspectorAttachedHeight);
211 }
212
213 bool InspectorController::searchingForNodeInPage() const
214 {
215     return m_state->getBoolean(InspectorState::searchingForNode);
216 }
217
218 void InspectorController::restoreInspectorStateFromCookie(const String& inspectorStateCookie)
219 {
220     m_state->restoreFromInspectorCookie(inspectorStateCookie);
221
222     if (!m_frontend) {
223         connectFrontend();
224         m_frontend->frontendReused();
225         m_frontend->inspectedURLChanged(m_inspectedPage->mainFrame()->loader()->url().string());
226         m_domAgent->setDocument(m_inspectedPage->mainFrame()->document());
227         pushDataCollectedOffline();
228     }
229
230     m_resourceAgent = InspectorResourceAgent::restore(m_inspectedPage, m_state.get(), m_frontend.get());
231
232     if (m_state->getBoolean(InspectorState::timelineProfilerEnabled))
233         startTimelineProfiler();
234
235 #if ENABLE(JAVASCRIPT_DEBUGGER)
236     restoreDebugger();
237     restoreProfiler(ProfilerRestoreResetAgent);
238     if (m_state->getBoolean(InspectorState::userInitiatedProfiling))
239         startUserInitiatedProfiling();
240 #endif
241 }
242
243 void InspectorController::inspect(Node* node)
244 {
245     if (!enabled())
246         return;
247
248     show();
249
250     if (node->nodeType() != Node::ELEMENT_NODE && node->nodeType() != Node::DOCUMENT_NODE)
251         node = node->parentNode();
252     m_nodeToFocus = node;
253
254     if (!m_frontend)
255         return;
256
257     focusNode();
258 }
259
260 void InspectorController::focusNode()
261 {
262     if (!enabled())
263         return;
264
265     ASSERT(m_frontend);
266     ASSERT(m_nodeToFocus);
267
268     long id = m_domAgent->pushNodePathToFrontend(m_nodeToFocus.get());
269     m_frontend->updateFocusedNode(id);
270     m_nodeToFocus = 0;
271 }
272
273 void InspectorController::highlight(Node* node)
274 {
275     if (!enabled())
276         return;
277     ASSERT_ARG(node, node);
278     m_highlightedNode = node;
279     m_client->highlight(node);
280 }
281
282 void InspectorController::highlightDOMNode(long nodeId)
283 {
284     Node* node = 0;
285     if (m_domAgent && (node = m_domAgent->nodeForId(nodeId)))
286         highlight(node);
287 }
288
289 void InspectorController::highlightFrame(unsigned long frameId)
290 {
291     Frame* mainFrame = m_inspectedPage->mainFrame();
292     for (Frame* frame = mainFrame; frame; frame = frame->tree()->traverseNext(mainFrame)) {
293         if (reinterpret_cast<uintptr_t>(frame) == frameId && frame->ownerElement()) {
294             highlight(frame->ownerElement());
295             return;
296         }
297     }
298 }
299
300 void InspectorController::hideHighlight()
301 {
302     if (!enabled())
303         return;
304     m_highlightedNode = 0;
305     m_client->hideHighlight();
306 }
307
308 void InspectorController::mouseDidMoveOverElement(const HitTestResult& result, unsigned)
309 {
310     if (!enabled() || !searchingForNodeInPage())
311         return;
312
313     Node* node = result.innerNode();
314     while (node && node->nodeType() == Node::TEXT_NODE)
315         node = node->parentNode();
316     if (node)
317         highlight(node);
318 }
319
320 bool InspectorController::handleMousePress()
321 {
322     if (!enabled() || !searchingForNodeInPage())
323         return false;
324
325     if (m_highlightedNode) {
326         RefPtr<Node> node = m_highlightedNode;
327         setSearchingForNode(false);
328         inspect(node.get());
329     }
330     return true;
331 }
332
333 void InspectorController::setInspectorFrontendClient(PassOwnPtr<InspectorFrontendClient> client)
334 {
335     ASSERT(!m_inspectorFrontendClient);
336     m_inspectorFrontendClient = client;
337 }
338
339 void InspectorController::didClearWindowObjectInWorld(Frame* frame, DOMWrapperWorld* world)
340 {
341     if (world != mainThreadNormalWorld())
342         return;
343
344     // If the page is supposed to serve as InspectorFrontend notify inspetor frontend
345     // client that it's cleared so that the client can expose inspector bindings.
346     if (m_inspectorFrontendClient && frame == m_inspectedPage->mainFrame())
347         m_inspectorFrontendClient->windowObjectCleared();
348
349     if (enabled()) {
350         if (m_frontend && frame == m_inspectedPage->mainFrame())
351             m_injectedScriptHost->discardInjectedScripts();
352         if (m_scriptsToEvaluateOnLoad.size()) {
353             ScriptState* scriptState = mainWorldScriptState(frame);
354             for (Vector<String>::iterator it = m_scriptsToEvaluateOnLoad.begin();
355                  it != m_scriptsToEvaluateOnLoad.end(); ++it) {
356                 m_injectedScriptHost->injectScript(*it, scriptState);
357             }
358         }
359     }
360     if (!m_inspectorExtensionAPI.isEmpty())
361         m_injectedScriptHost->injectScript(m_inspectorExtensionAPI, mainWorldScriptState(frame));
362 }
363
364 void InspectorController::setSearchingForNode(bool enabled)
365 {
366     if (searchingForNodeInPage() == enabled)
367         return;
368     m_state->setBoolean(InspectorState::searchingForNode, enabled);
369     if (!enabled)
370         hideHighlight();
371 }
372
373 void InspectorController::setSearchingForNode(bool enabled, bool* newState)
374 {
375     *newState = enabled;
376     setSearchingForNode(enabled);
377 }
378
379 void InspectorController::connectFrontend()
380 {
381     m_openingFrontend = false;
382     releaseFrontendLifetimeAgents();
383     m_frontend = new InspectorFrontend(m_client);
384     m_domAgent = InspectorDOMAgent::create(m_injectedScriptHost.get(), m_frontend.get());
385     m_runtimeAgent = InspectorRuntimeAgent::create(m_injectedScriptHost.get());
386     m_cssAgent->setDOMAgent(m_domAgent.get());
387
388 #if ENABLE(DATABASE)
389     m_databaseAgent = InspectorDatabaseAgent::create(&m_databaseResources, m_frontend.get());
390 #endif
391
392 #if ENABLE(DOM_STORAGE)
393     m_domStorageAgent = InspectorDOMStorageAgent::create(&m_domStorageResources, m_frontend.get());
394 #endif
395
396     if (m_timelineAgent)
397         m_timelineAgent->resetFrontendProxyObject(m_frontend.get());
398
399     m_consoleAgent->setFrontend(m_frontend.get());
400
401     // Initialize Web Inspector title.
402     m_frontend->inspectedURLChanged(m_inspectedPage->mainFrame()->loader()->url().string());
403
404 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
405     m_applicationCacheAgent = new InspectorApplicationCacheAgent(this, m_frontend.get());
406 #endif
407
408 #if ENABLE(FILE_SYSTEM)
409     m_fileSystemAgent = InspectorFileSystemAgent::create(this, m_frontend.get());
410 #endif
411     
412     if (!InspectorInstrumentation::hasFrontends())
413         ScriptController::setCaptureCallStackForUncaughtExceptions(true);
414     InspectorInstrumentation::frontendCreated();
415 }
416
417 void InspectorController::show()
418 {
419     if (!enabled())
420         return;
421
422     if (m_openingFrontend)
423         return;
424
425     if (m_frontend)
426         m_frontend->bringToFront();
427     else {
428         m_openingFrontend = true;
429         m_client->openInspectorFrontend(this);
430     }
431 }
432
433 void InspectorController::showPanel(const String& panel)
434 {
435     if (!enabled())
436         return;
437
438     show();
439
440     if (!m_frontend) {
441         m_showAfterVisible = panel;
442         return;
443     }
444     m_frontend->showPanel(panel);
445 }
446
447 void InspectorController::close()
448 {
449     if (!m_frontend)
450         return;
451     m_frontend->disconnectFromBackend();
452     disconnectFrontend();
453 }
454
455 void InspectorController::disconnectFrontend()
456 {
457     if (!m_frontend)
458         return;
459
460     m_frontend.clear();
461
462     InspectorInstrumentation::frontendDeleted();
463     if (!InspectorInstrumentation::hasFrontends())
464         ScriptController::setCaptureCallStackForUncaughtExceptions(false);
465
466 #if ENABLE(JAVASCRIPT_DEBUGGER)
467     // If the window is being closed with the debugger enabled,
468     // remember this state to re-enable debugger on the next window
469     // opening.
470     bool debuggerWasEnabled = debuggerEnabled();
471     disableDebugger();
472     m_attachDebuggerWhenShown = debuggerWasEnabled;
473 #endif
474     setSearchingForNode(false);
475     unbindAllResources();
476     stopTimelineProfiler();
477
478     hideHighlight();
479
480 #if ENABLE(JAVASCRIPT_DEBUGGER)
481     m_profilerAgent->setFrontend(0);
482     m_profilerAgent->stopUserInitiatedProfiling(true);
483 #endif
484     m_consoleAgent->setFrontend(0);
485
486     releaseFrontendLifetimeAgents();
487     m_timelineAgent.clear();
488     m_extraHeaders.clear();
489 }
490
491 InspectorResourceAgent* InspectorController::resourceAgent()
492 {
493     if (!m_resourceAgent && m_frontend)
494         m_resourceAgent = InspectorResourceAgent::create(m_inspectedPage, m_state.get(), m_frontend.get());
495     return m_resourceAgent.get();
496 }
497
498 void InspectorController::releaseFrontendLifetimeAgents()
499 {
500     m_resourceAgent.clear();
501     m_runtimeAgent.clear();
502
503     // This should be invoked prior to m_domAgent destruction.
504     m_cssAgent->setDOMAgent(0);
505
506     // m_domAgent is RefPtr. Remove DOM listeners first to ensure that there are
507     // no references to the DOM agent from the DOM tree.
508     if (m_domAgent)
509         m_domAgent->reset();
510     m_domAgent.clear();
511
512 #if ENABLE(DATABASE)
513     if (m_databaseAgent)
514         m_databaseAgent->clearFrontend();
515     m_databaseAgent.clear();
516 #endif
517
518 #if ENABLE(DOM_STORAGE)
519     m_domStorageAgent.clear();
520 #endif
521
522 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
523     m_applicationCacheAgent.clear();
524 #endif
525
526 #if ENABLE(FILE_SYSTEM)
527     if (m_fileSystemAgent)
528         m_fileSystemAgent->stop(); 
529         m_fileSystemAgent.clear();
530 #endif
531 }
532
533 void InspectorController::populateScriptObjects()
534 {
535     ASSERT(m_frontend);
536     if (!m_frontend)
537         return;
538
539     if (!m_showAfterVisible.isEmpty()) {
540         showPanel(m_showAfterVisible);
541         m_showAfterVisible = "";
542     }
543
544 #if ENABLE(JAVASCRIPT_DEBUGGER)
545     if (m_profilerAgent->enabled())
546         m_frontend->profilerWasEnabled();
547 #endif
548
549     pushDataCollectedOffline();
550
551     if (m_nodeToFocus)
552         focusNode();
553
554     // Dispatch pending frontend commands
555     for (Vector<pair<long, String> >::iterator it = m_pendingEvaluateTestCommands.begin(); it != m_pendingEvaluateTestCommands.end(); ++it)
556         m_frontend->evaluateForTestInFrontend((*it).first, (*it).second);
557     m_pendingEvaluateTestCommands.clear();
558
559     restoreDebugger();
560     restoreProfiler(ProfilerRestoreNoAction);
561 }
562
563 void InspectorController::pushDataCollectedOffline()
564 {
565     m_domAgent->setDocument(m_inspectedPage->mainFrame()->document());
566
567 #if ENABLE(DATABASE)
568     DatabaseResourcesMap::iterator databasesEnd = m_databaseResources.end();
569     for (DatabaseResourcesMap::iterator it = m_databaseResources.begin(); it != databasesEnd; ++it)
570         it->second->bind(m_frontend.get());
571 #endif
572 #if ENABLE(DOM_STORAGE)
573     DOMStorageResourcesMap::iterator domStorageEnd = m_domStorageResources.end();
574     for (DOMStorageResourcesMap::iterator it = m_domStorageResources.begin(); it != domStorageEnd; ++it)
575         it->second->bind(m_frontend.get());
576 #endif
577 #if ENABLE(JAVASCRIPT_DEBUGGER) && ENABLE(WORKERS)
578     WorkersMap::iterator workersEnd = m_workers.end();
579     for (WorkersMap::iterator it = m_workers.begin(); it != workersEnd; ++it) {
580         InspectorWorkerResource* worker = it->second.get();
581         m_frontend->didCreateWorker(worker->id(), worker->url(), worker->isSharedWorker());
582     }
583 #endif
584 }
585
586 void InspectorController::restoreDebugger()
587 {
588     ASSERT(m_frontend);
589 #if ENABLE(JAVASCRIPT_DEBUGGER)
590     if (InspectorDebuggerAgent::isDebuggerAlwaysEnabled() || m_attachDebuggerWhenShown || m_settings->getBoolean(InspectorSettings::DebuggerAlwaysEnabled)) {
591         enableDebugger(false);
592         m_attachDebuggerWhenShown = false;
593     }
594 #endif
595 }
596
597 void InspectorController::restoreProfiler(ProfilerRestoreAction action)
598 {
599     ASSERT(m_frontend);
600 #if ENABLE(JAVASCRIPT_DEBUGGER)
601     m_profilerAgent->setFrontend(m_frontend.get());
602     if (!ScriptProfiler::isProfilerAlwaysEnabled() && m_settings->getBoolean(InspectorSettings::ProfilerAlwaysEnabled))
603         enableProfiler();
604     if (action == ProfilerRestoreResetAgent)
605         m_profilerAgent->resetFrontendProfiles();
606 #endif
607 }
608
609 void InspectorController::unbindAllResources()
610 {
611 #if ENABLE(DATABASE)
612     DatabaseResourcesMap::iterator databasesEnd = m_databaseResources.end();
613     for (DatabaseResourcesMap::iterator it = m_databaseResources.begin(); it != databasesEnd; ++it)
614         it->second->unbind();
615 #endif
616 #if ENABLE(DOM_STORAGE)
617     DOMStorageResourcesMap::iterator domStorageEnd = m_domStorageResources.end();
618     for (DOMStorageResourcesMap::iterator it = m_domStorageResources.begin(); it != domStorageEnd; ++it)
619         it->second->unbind();
620 #endif
621     if (m_timelineAgent)
622         m_timelineAgent->reset();
623 }
624
625 void InspectorController::didCommitLoad(DocumentLoader* loader)
626 {
627     if (!enabled())
628         return;
629
630     if (m_resourceAgent)
631         m_resourceAgent->didCommitLoad(loader);
632     
633     ASSERT(m_inspectedPage);
634
635     if (loader->frame() == m_inspectedPage->mainFrame()) {
636         if (m_frontend)
637             m_frontend->inspectedURLChanged(loader->url().string());
638
639         m_injectedScriptHost->discardInjectedScripts();
640         m_consoleAgent->reset();
641
642 #if ENABLE(JAVASCRIPT_DEBUGGER)
643         if (m_debuggerAgent) {
644             m_debuggerAgent->clearForPageNavigation();
645             if (m_browserDebuggerAgent)
646                 m_browserDebuggerAgent->clearForPageNavigation();
647             restoreStickyBreakpoints();
648         }
649 #endif
650
651 #if ENABLE(JAVASCRIPT_DEBUGGER) && USE(JSC)
652         m_profilerAgent->stopUserInitiatedProfiling(true);
653         m_profilerAgent->resetState();
654 #endif
655
656         // unbindAllResources should be called before database and DOM storage
657         // resources are cleared so that it has a chance to unbind them.
658         unbindAllResources();
659
660         if (m_frontend) {
661             m_frontend->reset();
662             m_domAgent->reset();
663             m_cssAgent->reset();
664         }
665 #if ENABLE(WORKERS)
666         m_workers.clear();
667 #endif
668 #if ENABLE(DATABASE)
669         m_databaseResources.clear();
670 #endif
671 #if ENABLE(DOM_STORAGE)
672         m_domStorageResources.clear();
673 #endif
674
675         if (m_frontend)
676             m_domAgent->setDocument(m_inspectedPage->mainFrame()->document());
677     }
678 }
679
680 void InspectorController::mainResourceFiredDOMContentEvent(DocumentLoader* loader, const KURL& url)
681 {
682     if (!enabled() || !isMainResourceLoader(loader, url))
683         return;
684
685     if (m_timelineAgent)
686         m_timelineAgent->didMarkDOMContentEvent();
687     if (m_frontend)
688         m_frontend->domContentEventFired(currentTime());
689 }
690
691 void InspectorController::mainResourceFiredLoadEvent(DocumentLoader* loader, const KURL& url)
692 {
693     if (!enabled() || !isMainResourceLoader(loader, url))
694         return;
695
696     if (m_timelineAgent)
697         m_timelineAgent->didMarkLoadEvent();
698     if (m_frontend)
699         m_frontend->loadEventFired(currentTime());
700 }
701
702 bool InspectorController::isMainResourceLoader(DocumentLoader* loader, const KURL& requestUrl)
703 {
704     return loader->frame() == m_inspectedPage->mainFrame() && requestUrl == loader->requestURL();
705 }
706
707 void InspectorController::willSendRequest(ResourceRequest& request)
708 {
709     if (!enabled())
710         return;
711
712     if (m_frontend) {
713         // Only enable load timing and raw headers if front-end is attached, as otherwise we may produce overhead.
714         request.setReportLoadTiming(true);
715         request.setReportRawHeaders(true);
716
717         if (m_extraHeaders) {
718             HTTPHeaderMap::const_iterator end = m_extraHeaders->end();
719             for (HTTPHeaderMap::const_iterator it = m_extraHeaders->begin(); it != end; ++it)
720                 request.setHTTPHeaderField(it->first, it->second);
721         }
722     }
723 }
724
725 void InspectorController::ensureSettingsLoaded()
726 {
727     if (m_settings)
728         return;
729     m_settings = new InspectorSettings(m_client);
730     m_state->setBoolean(InspectorState::monitoringXHR, m_settings->getBoolean(InspectorSettings::MonitoringXHREnabled));
731 }
732
733 void InspectorController::startTimelineProfiler()
734 {
735     if (!enabled())
736         return;
737
738     if (m_timelineAgent)
739         return;
740
741     m_timelineAgent = new InspectorTimelineAgent(m_frontend.get());
742     if (m_frontend)
743         m_frontend->timelineProfilerWasStarted();
744
745     m_state->setBoolean(InspectorState::timelineProfilerEnabled, true);
746 }
747
748 void InspectorController::stopTimelineProfiler()
749 {
750     if (!enabled())
751         return;
752
753     if (!m_timelineAgent)
754         return;
755
756     m_timelineAgent = 0;
757     if (m_frontend)
758         m_frontend->timelineProfilerWasStopped();
759
760     m_state->setBoolean(InspectorState::timelineProfilerEnabled, false);
761 }
762
763 #if ENABLE(WORKERS)
764 class PostWorkerNotificationToFrontendTask : public ScriptExecutionContext::Task {
765 public:
766     static PassOwnPtr<PostWorkerNotificationToFrontendTask> create(PassRefPtr<InspectorWorkerResource> worker, InspectorController::WorkerAction action)
767     {
768         return new PostWorkerNotificationToFrontendTask(worker, action);
769     }
770
771 private:
772     PostWorkerNotificationToFrontendTask(PassRefPtr<InspectorWorkerResource> worker, InspectorController::WorkerAction action)
773         : m_worker(worker)
774         , m_action(action)
775     {
776     }
777
778     virtual void performTask(ScriptExecutionContext* scriptContext)
779     {
780         if (scriptContext->isDocument()) {
781             if (InspectorController* inspector = static_cast<Document*>(scriptContext)->page()->inspectorController())
782                 inspector->postWorkerNotificationToFrontend(*m_worker, m_action);
783         }
784     }
785
786 private:
787     RefPtr<InspectorWorkerResource> m_worker;
788     InspectorController::WorkerAction m_action;
789 };
790
791 void InspectorController::postWorkerNotificationToFrontend(const InspectorWorkerResource& worker, InspectorController::WorkerAction action)
792 {
793     if (!m_frontend)
794         return;
795 #if ENABLE(JAVASCRIPT_DEBUGGER)
796     switch (action) {
797     case InspectorController::WorkerCreated:
798         m_frontend->didCreateWorker(worker.id(), worker.url(), worker.isSharedWorker());
799         break;
800     case InspectorController::WorkerDestroyed:
801         m_frontend->didDestroyWorker(worker.id());
802         break;
803     }
804 #endif
805 }
806
807 void InspectorController::didCreateWorker(intptr_t id, const String& url, bool isSharedWorker)
808 {
809     if (!enabled())
810         return;
811
812     RefPtr<InspectorWorkerResource> workerResource(InspectorWorkerResource::create(id, url, isSharedWorker));
813     m_workers.set(id, workerResource);
814     if (m_inspectedPage && m_frontend)
815         m_inspectedPage->mainFrame()->document()->postTask(PostWorkerNotificationToFrontendTask::create(workerResource, InspectorController::WorkerCreated));
816 }
817
818 void InspectorController::didDestroyWorker(intptr_t id)
819 {
820     if (!enabled())
821         return;
822
823     WorkersMap::iterator workerResource = m_workers.find(id);
824     if (workerResource == m_workers.end())
825         return;
826     if (m_inspectedPage && m_frontend)
827         m_inspectedPage->mainFrame()->document()->postTask(PostWorkerNotificationToFrontendTask::create(workerResource->second, InspectorController::WorkerDestroyed));
828     m_workers.remove(workerResource);
829 }
830 #endif // ENABLE(WORKERS)
831
832 #if ENABLE(DATABASE)
833 void InspectorController::didOpenDatabase(PassRefPtr<Database> database, const String& domain, const String& name, const String& version)
834 {
835     if (!enabled())
836         return;
837
838     RefPtr<InspectorDatabaseResource> resource = InspectorDatabaseResource::create(database, domain, name, version);
839
840     m_databaseResources.set(resource->id(), resource);
841
842     // Resources are only bound while visible.
843     if (m_frontend)
844         resource->bind(m_frontend.get());
845 }
846 #endif
847
848 void InspectorController::getCookies(RefPtr<InspectorArray>* cookies, WTF::String* cookiesString)
849 {
850     // If we can get raw cookies.
851     ListHashSet<Cookie> rawCookiesList;
852
853     // If we can't get raw cookies - fall back to String representation
854     String stringCookiesList;
855
856     // Return value to getRawCookies should be the same for every call because
857     // the return value is platform/network backend specific, and the call will
858     // always return the same true/false value.
859     bool rawCookiesImplemented = false;
860
861     for (Frame* frame = m_inspectedPage->mainFrame(); frame; frame = frame->tree()->traverseNext(m_inspectedPage->mainFrame())) {
862         Document* document = frame->document();
863         const CachedResourceLoader::DocumentResourceMap& allResources = document->cachedResourceLoader()->allCachedResources();
864         CachedResourceLoader::DocumentResourceMap::const_iterator end = allResources.end();
865         for (CachedResourceLoader::DocumentResourceMap::const_iterator it = allResources.begin(); it != end; ++it) {
866             Vector<Cookie> docCookiesList;
867             rawCookiesImplemented = getRawCookies(document, KURL(ParsedURLString, it->second->url()), docCookiesList);
868
869             if (!rawCookiesImplemented) {
870                 // FIXME: We need duplication checking for the String representation of cookies.
871                 ExceptionCode ec = 0;
872                 stringCookiesList += document->cookie(ec);
873                 // Exceptions are thrown by cookie() in sandboxed frames. That won't happen here
874                 // because "document" is the document of the main frame of the page.
875                 ASSERT(!ec);
876             } else {
877                 int cookiesSize = docCookiesList.size();
878                 for (int i = 0; i < cookiesSize; i++) {
879                     if (!rawCookiesList.contains(docCookiesList[i]))
880                         rawCookiesList.add(docCookiesList[i]);
881                 }
882             }
883         }
884     }
885
886     if (rawCookiesImplemented)
887         *cookies = buildArrayForCookies(rawCookiesList);
888     else
889         *cookiesString = stringCookiesList;
890 }
891
892 PassRefPtr<InspectorArray> InspectorController::buildArrayForCookies(ListHashSet<Cookie>& cookiesList)
893 {
894     RefPtr<InspectorArray> cookies = InspectorArray::create();
895
896     ListHashSet<Cookie>::iterator end = cookiesList.end();
897     ListHashSet<Cookie>::iterator it = cookiesList.begin();
898     for (int i = 0; it != end; ++it, i++)
899         cookies->pushObject(buildObjectForCookie(*it));
900
901     return cookies;
902 }
903
904 PassRefPtr<InspectorObject> InspectorController::buildObjectForCookie(const Cookie& cookie)
905 {
906     RefPtr<InspectorObject> value = InspectorObject::create();
907     value->setString("name", cookie.name);
908     value->setString("value", cookie.value);
909     value->setString("domain", cookie.domain);
910     value->setString("path", cookie.path);
911     value->setNumber("expires", cookie.expires);
912     value->setNumber("size", (cookie.name.length() + cookie.value.length()));
913     value->setBoolean("httpOnly", cookie.httpOnly);
914     value->setBoolean("secure", cookie.secure);
915     value->setBoolean("session", cookie.session);
916     return value;
917 }
918
919 void InspectorController::deleteCookie(const String& cookieName, const String& domain)
920 {
921     for (Frame* frame = m_inspectedPage->mainFrame(); frame; frame = frame->tree()->traverseNext(m_inspectedPage->mainFrame())) {
922         Document* document = frame->document();
923         if (document->url().host() != domain)
924             continue;
925         const CachedResourceLoader::DocumentResourceMap& allResources = document->cachedResourceLoader()->allCachedResources();
926         CachedResourceLoader::DocumentResourceMap::const_iterator end = allResources.end();
927         for (CachedResourceLoader::DocumentResourceMap::const_iterator it = allResources.begin(); it != end; ++it)
928             WebCore::deleteCookie(document, KURL(ParsedURLString, it->second->url()), cookieName);
929     }
930 }
931
932 #if ENABLE(DOM_STORAGE)
933 void InspectorController::didUseDOMStorage(StorageArea* storageArea, bool isLocalStorage, Frame* frame)
934 {
935     if (!enabled())
936         return;
937
938     DOMStorageResourcesMap::iterator domStorageEnd = m_domStorageResources.end();
939     for (DOMStorageResourcesMap::iterator it = m_domStorageResources.begin(); it != domStorageEnd; ++it)
940         if (it->second->isSameHostAndType(frame, isLocalStorage))
941             return;
942
943     RefPtr<Storage> domStorage = Storage::create(frame, storageArea);
944     RefPtr<InspectorDOMStorageResource> resource = InspectorDOMStorageResource::create(domStorage.get(), isLocalStorage, frame);
945
946     m_domStorageResources.set(resource->id(), resource);
947
948     // Resources are only bound while visible.
949     if (m_frontend)
950         resource->bind(m_frontend.get());
951 }
952 #endif
953
954 #if ENABLE(WEB_SOCKETS)
955 void InspectorController::didCreateWebSocket(unsigned long identifier, const KURL& requestURL, const KURL& documentURL)
956 {
957     if (!enabled())
958         return;
959     ASSERT(m_inspectedPage);
960
961     if (m_resourceAgent)
962         m_resourceAgent->didCreateWebSocket(identifier, requestURL);
963     UNUSED_PARAM(documentURL);
964 }
965
966 void InspectorController::willSendWebSocketHandshakeRequest(unsigned long identifier, const WebSocketHandshakeRequest& request)
967 {
968     if (m_resourceAgent)
969         m_resourceAgent->willSendWebSocketHandshakeRequest(identifier, request);
970 }
971
972 void InspectorController::didReceiveWebSocketHandshakeResponse(unsigned long identifier, const WebSocketHandshakeResponse& response)
973 {
974     if (m_resourceAgent)
975         m_resourceAgent->didReceiveWebSocketHandshakeResponse(identifier, response);
976 }
977
978 void InspectorController::didCloseWebSocket(unsigned long identifier)
979 {
980     if (m_resourceAgent)
981         m_resourceAgent->didCloseWebSocket(identifier);
982 }
983 #endif // ENABLE(WEB_SOCKETS)
984
985 #if ENABLE(JAVASCRIPT_DEBUGGER)
986 bool InspectorController::isRecordingUserInitiatedProfile() const
987 {
988     return m_profilerAgent->isRecordingUserInitiatedProfile();
989 }
990
991 void InspectorController::startUserInitiatedProfiling()
992 {
993     if (!enabled())
994         return;
995     m_profilerAgent->startUserInitiatedProfiling();
996     m_state->setBoolean(InspectorState::userInitiatedProfiling, true);
997 }
998
999 void InspectorController::stopUserInitiatedProfiling()
1000 {
1001     if (!enabled())
1002         return;
1003     m_profilerAgent->stopUserInitiatedProfiling();
1004     m_state->setBoolean(InspectorState::userInitiatedProfiling, false);
1005 }
1006
1007 bool InspectorController::profilerEnabled() const
1008 {
1009     return enabled() && m_profilerAgent->enabled();
1010 }
1011
1012 void InspectorController::enableProfiler(bool always, bool skipRecompile)
1013 {
1014     if (always)
1015         m_settings->setBoolean(InspectorSettings::ProfilerAlwaysEnabled, true);
1016     m_profilerAgent->enable(skipRecompile);
1017 }
1018
1019 void InspectorController::disableProfiler(bool always)
1020 {
1021     if (always)
1022         m_settings->setBoolean(InspectorSettings::ProfilerAlwaysEnabled, false);
1023     m_profilerAgent->disable();
1024 }
1025 #endif
1026
1027 #if ENABLE(JAVASCRIPT_DEBUGGER)
1028 void InspectorController::showAndEnableDebugger()
1029 {
1030     if (!enabled())
1031         return;
1032
1033     if (debuggerEnabled())
1034         return;
1035
1036     if (!m_frontend) {
1037         m_attachDebuggerWhenShown = true;
1038         showPanel(ScriptsPanel);
1039     } else
1040         enableDebugger(false);
1041 }
1042
1043 void InspectorController::enableDebugger(bool always)
1044 {
1045     ASSERT(!debuggerEnabled());
1046     if (always)
1047         m_settings->setBoolean(InspectorSettings::DebuggerAlwaysEnabled, true);
1048
1049     ASSERT(m_inspectedPage);
1050
1051     m_debuggerAgent = InspectorDebuggerAgent::create(this, m_frontend.get());
1052     m_browserDebuggerAgent = InspectorBrowserDebuggerAgent::create(this);
1053     restoreStickyBreakpoints();
1054
1055     m_frontend->debuggerWasEnabled();
1056 }
1057
1058 void InspectorController::disableDebugger(bool always)
1059 {
1060     if (!enabled())
1061         return;
1062
1063     if (always)
1064         m_settings->setBoolean(InspectorSettings::DebuggerAlwaysEnabled, false);
1065
1066     ASSERT(m_inspectedPage);
1067
1068     m_debuggerAgent.clear();
1069     m_browserDebuggerAgent.clear();
1070
1071     m_attachDebuggerWhenShown = false;
1072
1073     if (m_frontend)
1074         m_frontend->debuggerWasDisabled();
1075 }
1076
1077 void InspectorController::resume()
1078 {
1079     if (m_debuggerAgent)
1080         m_debuggerAgent->resume();
1081 }
1082
1083 void InspectorController::setStickyBreakpoints(PassRefPtr<InspectorObject> breakpoints)
1084 {
1085     m_state->setObject(InspectorState::stickyBreakpoints, breakpoints);
1086 }
1087
1088 void InspectorController::restoreStickyBreakpoints()
1089 {
1090     RefPtr<InspectorObject> allBreakpoints = m_state->getObject(InspectorState::stickyBreakpoints);
1091     KURL url = m_inspectedPage->mainFrame()->loader()->url();
1092     url.removeFragmentIdentifier();
1093     RefPtr<InspectorArray> breakpoints = allBreakpoints->getArray(url);
1094     if (!breakpoints)
1095         return;
1096     for (unsigned i = 0; i < breakpoints->length(); ++i)
1097         restoreStickyBreakpoint(breakpoints->get(i)->asObject());
1098 }
1099
1100 void InspectorController::restoreStickyBreakpoint(PassRefPtr<InspectorObject> breakpoint)
1101 {
1102     DEFINE_STATIC_LOCAL(String, eventListenerBreakpointType, ("EventListener"));
1103     DEFINE_STATIC_LOCAL(String, javaScriptBreakpointType, ("JS"));
1104     DEFINE_STATIC_LOCAL(String, xhrBreakpointType, ("XHR"));
1105
1106     if (!breakpoint)
1107         return;
1108     String type;
1109     if (!breakpoint->getString("type", &type))
1110         return;
1111     bool enabled;
1112     if (!breakpoint->getBoolean("enabled", &enabled))
1113         return;
1114     RefPtr<InspectorObject> condition = breakpoint->getObject("condition");
1115     if (!condition)
1116         return;
1117
1118     if (type == eventListenerBreakpointType && m_browserDebuggerAgent) {
1119         if (!enabled)
1120             return;
1121         String eventName;
1122         if (!condition->getString("eventName", &eventName))
1123             return;
1124         m_browserDebuggerAgent->setEventListenerBreakpoint(eventName);
1125     } else if (type == javaScriptBreakpointType && m_debuggerAgent) {
1126         String url;
1127         if (!condition->getString("url", &url))
1128             return;
1129         double lineNumber;
1130         if (!condition->getNumber("lineNumber", &lineNumber))
1131             return;
1132         String javaScriptCondition;
1133         if (!condition->getString("condition", &javaScriptCondition))
1134             return;
1135         m_debuggerAgent->setStickyBreakpoint(url, static_cast<unsigned>(lineNumber), javaScriptCondition, enabled);
1136     } else if (type == xhrBreakpointType && m_browserDebuggerAgent) {
1137         if (!enabled)
1138             return;
1139         String url;
1140         if (!condition->getString("url", &url))
1141             return;
1142         m_browserDebuggerAgent->setXHRBreakpoint(url);
1143     }
1144 }
1145 #endif
1146
1147 void InspectorController::evaluateForTestInFrontend(long callId, const String& script)
1148 {
1149     if (m_frontend)
1150         m_frontend->evaluateForTestInFrontend(callId, script);
1151     else
1152         m_pendingEvaluateTestCommands.append(pair<long, String>(callId, script));
1153 }
1154
1155 void InspectorController::didEvaluateForTestInFrontend(long callId, const String& jsonResult)
1156 {
1157     ScriptState* scriptState = scriptStateFromPage(debuggerWorld(), m_inspectedPage);
1158     ScriptObject window;
1159     ScriptGlobalObject::get(scriptState, "window", window);
1160     ScriptFunctionCall function(window, "didEvaluateForTestInFrontend");
1161     function.appendArgument(callId);
1162     function.appendArgument(jsonResult);
1163     function.call();
1164 }
1165
1166 static Path quadToPath(const FloatQuad& quad)
1167 {
1168     Path quadPath;
1169     quadPath.moveTo(quad.p1());
1170     quadPath.addLineTo(quad.p2());
1171     quadPath.addLineTo(quad.p3());
1172     quadPath.addLineTo(quad.p4());
1173     quadPath.closeSubpath();
1174     return quadPath;
1175 }
1176
1177 static void drawOutlinedQuad(GraphicsContext& context, const FloatQuad& quad, const Color& fillColor)
1178 {
1179     static const int outlineThickness = 2;
1180     static const Color outlineColor(62, 86, 180, 228);
1181
1182     Path quadPath = quadToPath(quad);
1183
1184     // Clip out the quad, then draw with a 2px stroke to get a pixel
1185     // of outline (because inflating a quad is hard)
1186     {
1187         context.save();
1188         context.clipOut(quadPath);
1189
1190         context.setStrokeThickness(outlineThickness);
1191         context.setStrokeColor(outlineColor, ColorSpaceDeviceRGB);
1192         context.strokePath(quadPath);
1193
1194         context.restore();
1195     }
1196
1197     // Now do the fill
1198     context.setFillColor(fillColor, ColorSpaceDeviceRGB);
1199     context.fillPath(quadPath);
1200 }
1201
1202 static void drawOutlinedQuadWithClip(GraphicsContext& context, const FloatQuad& quad, const FloatQuad& clipQuad, const Color& fillColor)
1203 {
1204     context.save();
1205     Path clipQuadPath = quadToPath(clipQuad);
1206     context.clipOut(clipQuadPath);
1207     drawOutlinedQuad(context, quad, fillColor);
1208     context.restore();
1209 }
1210
1211 static void drawHighlightForBox(GraphicsContext& context, const FloatQuad& contentQuad, const FloatQuad& paddingQuad, const FloatQuad& borderQuad, const FloatQuad& marginQuad)
1212 {
1213     static const Color contentBoxColor(125, 173, 217, 128);
1214     static const Color paddingBoxColor(125, 173, 217, 160);
1215     static const Color borderBoxColor(125, 173, 217, 192);
1216     static const Color marginBoxColor(125, 173, 217, 228);
1217
1218     if (marginQuad != borderQuad)
1219         drawOutlinedQuadWithClip(context, marginQuad, borderQuad, marginBoxColor);
1220     if (borderQuad != paddingQuad)
1221         drawOutlinedQuadWithClip(context, borderQuad, paddingQuad, borderBoxColor);
1222     if (paddingQuad != contentQuad)
1223         drawOutlinedQuadWithClip(context, paddingQuad, contentQuad, paddingBoxColor);
1224
1225     drawOutlinedQuad(context, contentQuad, contentBoxColor);
1226 }
1227
1228 static void drawHighlightForLineBoxesOrSVGRenderer(GraphicsContext& context, const Vector<FloatQuad>& lineBoxQuads)
1229 {
1230     static const Color lineBoxColor(125, 173, 217, 128);
1231
1232     for (size_t i = 0; i < lineBoxQuads.size(); ++i)
1233         drawOutlinedQuad(context, lineBoxQuads[i], lineBoxColor);
1234 }
1235
1236 static inline void convertFromFrameToMainFrame(Frame* frame, IntRect& rect)
1237 {
1238     rect = frame->page()->mainFrame()->view()->windowToContents(frame->view()->contentsToWindow(rect));
1239 }
1240
1241 static inline IntSize frameToMainFrameOffset(Frame* frame)
1242 {
1243     IntPoint mainFramePoint = frame->page()->mainFrame()->view()->windowToContents(frame->view()->contentsToWindow(IntPoint()));
1244     return mainFramePoint - IntPoint();
1245 }
1246
1247 void InspectorController::drawNodeHighlight(GraphicsContext& context) const
1248 {
1249     if (!m_highlightedNode)
1250         return;
1251
1252     RenderObject* renderer = m_highlightedNode->renderer();
1253     Frame* containingFrame = m_highlightedNode->document()->frame();
1254     if (!renderer || !containingFrame)
1255         return;
1256
1257     IntSize mainFrameOffset = frameToMainFrameOffset(containingFrame);
1258     IntRect boundingBox = renderer->absoluteBoundingBoxRect(true);
1259     boundingBox.move(mainFrameOffset);
1260
1261     IntRect titleReferenceBox = boundingBox;
1262
1263     ASSERT(m_inspectedPage);
1264
1265     FrameView* view = m_inspectedPage->mainFrame()->view();
1266     FloatRect overlayRect = view->visibleContentRect();
1267     if (!overlayRect.contains(boundingBox) && !boundingBox.contains(enclosingIntRect(overlayRect)))
1268         overlayRect = view->visibleContentRect();
1269     context.translate(-overlayRect.x(), -overlayRect.y());
1270
1271     // RenderSVGRoot should be highlighted through the isBox() code path, all other SVG elements should just dump their absoluteQuads().
1272 #if ENABLE(SVG)
1273     bool isSVGRenderer = renderer->node() && renderer->node()->isSVGElement() && !renderer->isSVGRoot();
1274 #else
1275     bool isSVGRenderer = false;
1276 #endif
1277
1278     if (renderer->isBox() && !isSVGRenderer) {
1279         RenderBox* renderBox = toRenderBox(renderer);
1280
1281         IntRect contentBox = renderBox->contentBoxRect();
1282
1283         IntRect paddingBox(contentBox.x() - renderBox->paddingLeft(), contentBox.y() - renderBox->paddingTop(),
1284                            contentBox.width() + renderBox->paddingLeft() + renderBox->paddingRight(), contentBox.height() + renderBox->paddingTop() + renderBox->paddingBottom());
1285         IntRect borderBox(paddingBox.x() - renderBox->borderLeft(), paddingBox.y() - renderBox->borderTop(),
1286                           paddingBox.width() + renderBox->borderLeft() + renderBox->borderRight(), paddingBox.height() + renderBox->borderTop() + renderBox->borderBottom());
1287         IntRect marginBox(borderBox.x() - renderBox->marginLeft(), borderBox.y() - renderBox->marginTop(),
1288                           borderBox.width() + renderBox->marginLeft() + renderBox->marginRight(), borderBox.height() + renderBox->marginTop() + renderBox->marginBottom());
1289
1290         titleReferenceBox = marginBox;
1291         titleReferenceBox.move(mainFrameOffset);
1292         titleReferenceBox.move(boundingBox.x(), boundingBox.y());
1293
1294         FloatQuad absContentQuad = renderBox->localToAbsoluteQuad(FloatRect(contentBox));
1295         FloatQuad absPaddingQuad = renderBox->localToAbsoluteQuad(FloatRect(paddingBox));
1296         FloatQuad absBorderQuad = renderBox->localToAbsoluteQuad(FloatRect(borderBox));
1297         FloatQuad absMarginQuad = renderBox->localToAbsoluteQuad(FloatRect(marginBox));
1298
1299         absContentQuad.move(mainFrameOffset);
1300         absPaddingQuad.move(mainFrameOffset);
1301         absBorderQuad.move(mainFrameOffset);
1302         absMarginQuad.move(mainFrameOffset);
1303
1304         drawHighlightForBox(context, absContentQuad, absPaddingQuad, absBorderQuad, absMarginQuad);
1305     } else if (renderer->isRenderInline() || isSVGRenderer) {
1306         // FIXME: We should show margins/padding/border for inlines.
1307         Vector<FloatQuad> lineBoxQuads;
1308         renderer->absoluteQuads(lineBoxQuads);
1309         for (unsigned i = 0; i < lineBoxQuads.size(); ++i)
1310             lineBoxQuads[i] += mainFrameOffset;
1311
1312         drawHighlightForLineBoxesOrSVGRenderer(context, lineBoxQuads);
1313     }
1314
1315     // Draw node title if necessary.
1316
1317     if (!m_highlightedNode->isElementNode())
1318         return;
1319
1320     WebCore::Settings* settings = containingFrame->settings();
1321     drawElementTitle(context, titleReferenceBox, overlayRect, settings);
1322 }
1323
1324 void InspectorController::drawElementTitle(GraphicsContext& context, const IntRect& boundingBox, const FloatRect& overlayRect, WebCore::Settings* settings) const
1325 {
1326     static const int rectInflatePx = 4;
1327     static const int fontHeightPx = 12;
1328     static const int borderWidthPx = 1;
1329     static const Color tooltipBackgroundColor(255, 255, 194, 255);
1330     static const Color tooltipBorderColor(Color::black);
1331     static const Color tooltipFontColor(Color::black);
1332
1333     Element* element = static_cast<Element*>(m_highlightedNode.get());
1334     bool isXHTML = element->document()->isXHTMLDocument();
1335     String nodeTitle = isXHTML ? element->nodeName() : element->nodeName().lower();
1336     const AtomicString& idValue = element->getIdAttribute();
1337     if (!idValue.isNull() && !idValue.isEmpty()) {
1338         nodeTitle += "#";
1339         nodeTitle += idValue;
1340     }
1341     if (element->hasClass() && element->isStyledElement()) {
1342         const SpaceSplitString& classNamesString = static_cast<StyledElement*>(element)->classNames();
1343         size_t classNameCount = classNamesString.size();
1344         if (classNameCount) {
1345             HashSet<AtomicString> usedClassNames;
1346             for (size_t i = 0; i < classNameCount; ++i) {
1347                 const AtomicString& className = classNamesString[i];
1348                 if (usedClassNames.contains(className))
1349                     continue;
1350                 usedClassNames.add(className);
1351                 nodeTitle += ".";
1352                 nodeTitle += className;
1353             }
1354         }
1355     }
1356
1357     Element* highlightedElement = m_highlightedNode->isElementNode() ? static_cast<Element*>(m_highlightedNode.get()) : 0;
1358     nodeTitle += " [";
1359     nodeTitle += String::number(highlightedElement ? highlightedElement->offsetWidth() : boundingBox.width());
1360     nodeTitle.append(static_cast<UChar>(0x00D7)); // &times;
1361     nodeTitle += String::number(highlightedElement ? highlightedElement->offsetHeight() : boundingBox.height());
1362     nodeTitle += "]";
1363
1364     FontDescription desc;
1365     FontFamily family;
1366     family.setFamily(settings->fixedFontFamily());
1367     desc.setFamily(family);
1368     desc.setComputedSize(fontHeightPx);
1369     Font font = Font(desc, 0, 0);
1370     font.update(0);
1371
1372     TextRun nodeTitleRun(nodeTitle);
1373     IntPoint titleBasePoint = boundingBox.bottomLeft();
1374     titleBasePoint.move(rectInflatePx, rectInflatePx);
1375     IntRect titleRect = enclosingIntRect(font.selectionRectForText(nodeTitleRun, titleBasePoint, fontHeightPx));
1376     titleRect.inflate(rectInflatePx);
1377
1378     // The initial offsets needed to compensate for a 1px-thick border stroke (which is not a part of the rectangle).
1379     int dx = -borderWidthPx;
1380     int dy = borderWidthPx;
1381
1382     // If the tip sticks beyond the right of overlayRect, right-align the tip with the said boundary.
1383     if (titleRect.right() > overlayRect.right())
1384         dx = overlayRect.right() - titleRect.right();
1385
1386     // If the tip sticks beyond the left of overlayRect, left-align the tip with the said boundary.
1387     if (titleRect.x() + dx < overlayRect.x())
1388         dx = overlayRect.x() - titleRect.x() - borderWidthPx;
1389
1390     // If the tip sticks beyond the bottom of overlayRect, show the tip at top of bounding box.
1391     if (titleRect.bottom() > overlayRect.bottom()) {
1392         dy = boundingBox.y() - titleRect.bottom() - borderWidthPx;
1393         // If the tip still sticks beyond the bottom of overlayRect, bottom-align the tip with the said boundary.
1394         if (titleRect.bottom() + dy > overlayRect.bottom())
1395             dy = overlayRect.bottom() - titleRect.bottom();
1396     }
1397
1398     // If the tip sticks beyond the top of overlayRect, show the tip at top of overlayRect.
1399     if (titleRect.y() + dy < overlayRect.y())
1400         dy = overlayRect.y() - titleRect.y() + borderWidthPx;
1401
1402     titleRect.move(dx, dy);
1403     context.setStrokeColor(tooltipBorderColor, ColorSpaceDeviceRGB);
1404     context.setStrokeThickness(borderWidthPx);
1405     context.setFillColor(tooltipBackgroundColor, ColorSpaceDeviceRGB);
1406     context.drawRect(titleRect);
1407     context.setFillColor(tooltipFontColor, ColorSpaceDeviceRGB);
1408     context.drawText(font, nodeTitleRun, IntPoint(titleRect.x() + rectInflatePx, titleRect.y() + font.height()));
1409 }
1410
1411 void InspectorController::openInInspectedWindow(const String& url)
1412 {
1413     Frame* mainFrame = m_inspectedPage->mainFrame();
1414
1415     FrameLoadRequest request(mainFrame->document()->securityOrigin(), ResourceRequest(), "_blank");
1416
1417     bool created;
1418     WindowFeatures windowFeatures;
1419     Frame* newFrame = WebCore::createWindow(mainFrame, mainFrame, request, windowFeatures, created);
1420     if (!newFrame)
1421         return;
1422
1423     UserGestureIndicator indicator(DefinitelyProcessingUserGesture);
1424     newFrame->loader()->setOpener(mainFrame);
1425     newFrame->page()->setOpenedByDOM();
1426     newFrame->loader()->changeLocation(mainFrame->document()->securityOrigin(), newFrame->loader()->completeURL(url), "", false, false);
1427 }
1428
1429 void InspectorController::addScriptToEvaluateOnLoad(const String& source)
1430 {
1431     m_scriptsToEvaluateOnLoad.append(source);
1432 }
1433
1434 void InspectorController::removeAllScriptsToEvaluateOnLoad()
1435 {
1436     m_scriptsToEvaluateOnLoad.clear();
1437 }
1438
1439 void InspectorController::setInspectorExtensionAPI(const String& source)
1440 {
1441     m_inspectorExtensionAPI = source;
1442 }
1443
1444 void InspectorController::reloadPage()
1445 {
1446     // FIXME: Why do we set the user gesture indicator here?
1447     UserGestureIndicator indicator(DefinitelyProcessingUserGesture);
1448     m_inspectedPage->mainFrame()->navigationScheduler()->scheduleRefresh();
1449 }
1450
1451 void InspectorController::setExtraHeaders(PassRefPtr<InspectorObject> headers)
1452 {
1453     m_extraHeaders = adoptPtr(new HTTPHeaderMap());
1454     InspectorObject::const_iterator end = headers->end();
1455     for (InspectorObject::const_iterator it = headers->begin(); it != end; ++it) {
1456         String value;
1457         if (!it->second->asString(&value))
1458             continue;
1459         m_extraHeaders->add(it->first, value);
1460     }
1461 }
1462
1463 } // namespace WebCore
1464
1465 #endif // ENABLE(INSPECTOR)