2011-01-20 Pavel Feldman <pfeldman@chromium.org>
[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     if (m_state->getBoolean(InspectorState::timelineProfilerEnabled))
231         startTimelineProfiler();
232
233 #if ENABLE(JAVASCRIPT_DEBUGGER)
234     restoreDebugger();
235     restoreProfiler(ProfilerRestoreResetAgent);
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::mouseDidMoveOverElement(const HitTestResult& result, unsigned)
307 {
308     if (!enabled() || !searchingForNodeInPage())
309         return;
310
311     Node* node = result.innerNode();
312     while (node && node->nodeType() == Node::TEXT_NODE)
313         node = node->parentNode();
314     if (node)
315         highlight(node);
316 }
317
318 bool InspectorController::handleMousePress()
319 {
320     if (!enabled() || !searchingForNodeInPage())
321         return false;
322
323     if (m_highlightedNode) {
324         RefPtr<Node> node = m_highlightedNode;
325         setSearchingForNode(false);
326         inspect(node.get());
327     }
328     return true;
329 }
330
331 void InspectorController::setInspectorFrontendClient(PassOwnPtr<InspectorFrontendClient> client)
332 {
333     ASSERT(!m_inspectorFrontendClient);
334     m_inspectorFrontendClient = client;
335 }
336
337 void InspectorController::didClearWindowObjectInWorld(Frame* frame, DOMWrapperWorld* world)
338 {
339     if (world != mainThreadNormalWorld())
340         return;
341
342     // If the page is supposed to serve as InspectorFrontend notify inspetor frontend
343     // client that it's cleared so that the client can expose inspector bindings.
344     if (m_inspectorFrontendClient && frame == m_inspectedPage->mainFrame())
345         m_inspectorFrontendClient->windowObjectCleared();
346
347     if (enabled()) {
348         if (m_frontend && frame == m_inspectedPage->mainFrame())
349             m_injectedScriptHost->discardInjectedScripts();
350         if (m_scriptsToEvaluateOnLoad.size()) {
351             ScriptState* scriptState = mainWorldScriptState(frame);
352             for (Vector<String>::iterator it = m_scriptsToEvaluateOnLoad.begin();
353                  it != m_scriptsToEvaluateOnLoad.end(); ++it) {
354                 m_injectedScriptHost->injectScript(*it, scriptState);
355             }
356         }
357     }
358     if (!m_inspectorExtensionAPI.isEmpty())
359         m_injectedScriptHost->injectScript(m_inspectorExtensionAPI, mainWorldScriptState(frame));
360 }
361
362 void InspectorController::setSearchingForNode(bool enabled)
363 {
364     if (searchingForNodeInPage() == enabled)
365         return;
366     m_state->setBoolean(InspectorState::searchingForNode, enabled);
367     if (!enabled)
368         hideHighlight();
369 }
370
371 void InspectorController::setSearchingForNode(bool enabled, bool* newState)
372 {
373     *newState = enabled;
374     setSearchingForNode(enabled);
375 }
376
377 void InspectorController::connectFrontend()
378 {
379     m_openingFrontend = false;
380     releaseFrontendLifetimeAgents();
381     m_frontend = new InspectorFrontend(m_client);
382     m_domAgent = InspectorDOMAgent::create(m_injectedScriptHost.get(), m_frontend.get());
383     m_resourceAgent = InspectorResourceAgent::create(m_inspectedPage, m_frontend.get());
384     m_runtimeAgent = InspectorRuntimeAgent::create(m_injectedScriptHost.get());
385
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 void InspectorController::releaseFrontendLifetimeAgents()
492 {
493     m_resourceAgent.clear();
494     m_runtimeAgent.clear();
495
496     // This should be invoked prior to m_domAgent destruction.
497     m_cssAgent->setDOMAgent(0);
498
499     // m_domAgent is RefPtr. Remove DOM listeners first to ensure that there are
500     // no references to the DOM agent from the DOM tree.
501     if (m_domAgent)
502         m_domAgent->reset();
503     m_domAgent.clear();
504
505 #if ENABLE(DATABASE)
506     if (m_databaseAgent)
507         m_databaseAgent->clearFrontend();
508     m_databaseAgent.clear();
509 #endif
510
511 #if ENABLE(DOM_STORAGE)
512     m_domStorageAgent.clear();
513 #endif
514
515 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
516     m_applicationCacheAgent.clear();
517 #endif
518
519 #if ENABLE(FILE_SYSTEM)
520     if (m_fileSystemAgent)
521         m_fileSystemAgent->stop(); 
522         m_fileSystemAgent.clear();
523 #endif
524 }
525
526 void InspectorController::populateScriptObjects()
527 {
528     ASSERT(m_frontend);
529     if (!m_frontend)
530         return;
531
532     if (!m_showAfterVisible.isEmpty()) {
533         showPanel(m_showAfterVisible);
534         m_showAfterVisible = "";
535     }
536
537 #if ENABLE(JAVASCRIPT_DEBUGGER)
538     if (m_profilerAgent->enabled())
539         m_frontend->profilerWasEnabled();
540 #endif
541
542     pushDataCollectedOffline();
543
544     if (m_nodeToFocus)
545         focusNode();
546
547     // Dispatch pending frontend commands
548     for (Vector<pair<long, String> >::iterator it = m_pendingEvaluateTestCommands.begin(); it != m_pendingEvaluateTestCommands.end(); ++it)
549         m_frontend->evaluateForTestInFrontend((*it).first, (*it).second);
550     m_pendingEvaluateTestCommands.clear();
551
552     restoreDebugger();
553     restoreProfiler(ProfilerRestoreNoAction);
554 }
555
556 void InspectorController::pushDataCollectedOffline()
557 {
558     m_domAgent->setDocument(m_inspectedPage->mainFrame()->document());
559
560 #if ENABLE(DATABASE)
561     DatabaseResourcesMap::iterator databasesEnd = m_databaseResources.end();
562     for (DatabaseResourcesMap::iterator it = m_databaseResources.begin(); it != databasesEnd; ++it)
563         it->second->bind(m_frontend.get());
564 #endif
565 #if ENABLE(DOM_STORAGE)
566     DOMStorageResourcesMap::iterator domStorageEnd = m_domStorageResources.end();
567     for (DOMStorageResourcesMap::iterator it = m_domStorageResources.begin(); it != domStorageEnd; ++it)
568         it->second->bind(m_frontend.get());
569 #endif
570 #if ENABLE(JAVASCRIPT_DEBUGGER) && ENABLE(WORKERS)
571     WorkersMap::iterator workersEnd = m_workers.end();
572     for (WorkersMap::iterator it = m_workers.begin(); it != workersEnd; ++it) {
573         InspectorWorkerResource* worker = it->second.get();
574         m_frontend->didCreateWorker(worker->id(), worker->url(), worker->isSharedWorker());
575     }
576 #endif
577 }
578
579 void InspectorController::restoreDebugger()
580 {
581     ASSERT(m_frontend);
582 #if ENABLE(JAVASCRIPT_DEBUGGER)
583     if (InspectorDebuggerAgent::isDebuggerAlwaysEnabled() || m_attachDebuggerWhenShown || m_settings->getBoolean(InspectorSettings::DebuggerAlwaysEnabled)) {
584         enableDebugger(false);
585         m_attachDebuggerWhenShown = false;
586     }
587 #endif
588 }
589
590 void InspectorController::restoreProfiler(ProfilerRestoreAction action)
591 {
592     ASSERT(m_frontend);
593 #if ENABLE(JAVASCRIPT_DEBUGGER)
594     m_profilerAgent->setFrontend(m_frontend.get());
595     if (!ScriptProfiler::isProfilerAlwaysEnabled() && m_settings->getBoolean(InspectorSettings::ProfilerAlwaysEnabled))
596         enableProfiler();
597     if (action == ProfilerRestoreResetAgent)
598         m_profilerAgent->resetState();
599 #endif
600 }
601
602 void InspectorController::unbindAllResources()
603 {
604 #if ENABLE(DATABASE)
605     DatabaseResourcesMap::iterator databasesEnd = m_databaseResources.end();
606     for (DatabaseResourcesMap::iterator it = m_databaseResources.begin(); it != databasesEnd; ++it)
607         it->second->unbind();
608 #endif
609 #if ENABLE(DOM_STORAGE)
610     DOMStorageResourcesMap::iterator domStorageEnd = m_domStorageResources.end();
611     for (DOMStorageResourcesMap::iterator it = m_domStorageResources.begin(); it != domStorageEnd; ++it)
612         it->second->unbind();
613 #endif
614     if (m_timelineAgent)
615         m_timelineAgent->reset();
616 }
617
618 void InspectorController::didCommitLoad(DocumentLoader* loader)
619 {
620     if (!enabled())
621         return;
622
623     if (m_resourceAgent)
624         m_resourceAgent->didCommitLoad(loader);
625     
626     ASSERT(m_inspectedPage);
627
628     if (loader->frame() == m_inspectedPage->mainFrame()) {
629         if (m_frontend)
630             m_frontend->inspectedURLChanged(loader->url().string());
631
632         m_injectedScriptHost->discardInjectedScripts();
633         m_consoleAgent->reset();
634
635 #if ENABLE(JAVASCRIPT_DEBUGGER)
636         if (m_debuggerAgent) {
637             m_debuggerAgent->clearForPageNavigation();
638             if (m_browserDebuggerAgent)
639                 m_browserDebuggerAgent->clearForPageNavigation();
640             restoreStickyBreakpoints();
641         }
642 #endif
643
644 #if ENABLE(JAVASCRIPT_DEBUGGER) && USE(JSC)
645         m_profilerAgent->stopUserInitiatedProfiling(true);
646         m_profilerAgent->resetState();
647 #endif
648
649         // unbindAllResources should be called before database and DOM storage
650         // resources are cleared so that it has a chance to unbind them.
651         unbindAllResources();
652
653         if (m_frontend) {
654             m_frontend->reset();
655             m_domAgent->reset();
656             m_cssAgent->reset();
657         }
658 #if ENABLE(WORKERS)
659         m_workers.clear();
660 #endif
661 #if ENABLE(DATABASE)
662         m_databaseResources.clear();
663 #endif
664 #if ENABLE(DOM_STORAGE)
665         m_domStorageResources.clear();
666 #endif
667
668         if (m_frontend)
669             m_domAgent->setDocument(m_inspectedPage->mainFrame()->document());
670     }
671 }
672
673 void InspectorController::mainResourceFiredDOMContentEvent(DocumentLoader* loader, const KURL& url)
674 {
675     if (!enabled() || !isMainResourceLoader(loader, url))
676         return;
677
678     if (m_timelineAgent)
679         m_timelineAgent->didMarkDOMContentEvent();
680     if (m_frontend)
681         m_frontend->domContentEventFired(currentTime());
682 }
683
684 void InspectorController::mainResourceFiredLoadEvent(DocumentLoader* loader, const KURL& url)
685 {
686     if (!enabled() || !isMainResourceLoader(loader, url))
687         return;
688
689     if (m_timelineAgent)
690         m_timelineAgent->didMarkLoadEvent();
691     if (m_frontend)
692         m_frontend->loadEventFired(currentTime());
693 }
694
695 bool InspectorController::isMainResourceLoader(DocumentLoader* loader, const KURL& requestUrl)
696 {
697     return loader->frame() == m_inspectedPage->mainFrame() && requestUrl == loader->requestURL();
698 }
699
700 void InspectorController::willSendRequest(ResourceRequest& request)
701 {
702     if (!enabled())
703         return;
704
705     if (m_frontend) {
706         // Only enable load timing and raw headers if front-end is attached, as otherwise we may produce overhead.
707         request.setReportLoadTiming(true);
708         request.setReportRawHeaders(true);
709
710         if (m_extraHeaders) {
711             HTTPHeaderMap::const_iterator end = m_extraHeaders->end();
712             for (HTTPHeaderMap::const_iterator it = m_extraHeaders->begin(); it != end; ++it)
713                 request.setHTTPHeaderField(it->first, it->second);
714         }
715     }
716 }
717
718 void InspectorController::ensureSettingsLoaded()
719 {
720     if (m_settings)
721         return;
722     m_settings = new InspectorSettings(m_client);
723     m_state->setBoolean(InspectorState::monitoringXHR, m_settings->getBoolean(InspectorSettings::MonitoringXHREnabled));
724 }
725
726 void InspectorController::startTimelineProfiler()
727 {
728     if (!enabled())
729         return;
730
731     if (m_timelineAgent)
732         return;
733
734     m_timelineAgent = new InspectorTimelineAgent(m_frontend.get());
735     if (m_frontend)
736         m_frontend->timelineProfilerWasStarted();
737
738     m_state->setBoolean(InspectorState::timelineProfilerEnabled, true);
739 }
740
741 void InspectorController::stopTimelineProfiler()
742 {
743     if (!enabled())
744         return;
745
746     if (!m_timelineAgent)
747         return;
748
749     m_timelineAgent = 0;
750     if (m_frontend)
751         m_frontend->timelineProfilerWasStopped();
752
753     m_state->setBoolean(InspectorState::timelineProfilerEnabled, false);
754 }
755
756 #if ENABLE(WORKERS)
757 class PostWorkerNotificationToFrontendTask : public ScriptExecutionContext::Task {
758 public:
759     static PassOwnPtr<PostWorkerNotificationToFrontendTask> create(PassRefPtr<InspectorWorkerResource> worker, InspectorController::WorkerAction action)
760     {
761         return new PostWorkerNotificationToFrontendTask(worker, action);
762     }
763
764 private:
765     PostWorkerNotificationToFrontendTask(PassRefPtr<InspectorWorkerResource> worker, InspectorController::WorkerAction action)
766         : m_worker(worker)
767         , m_action(action)
768     {
769     }
770
771     virtual void performTask(ScriptExecutionContext* scriptContext)
772     {
773         if (scriptContext->isDocument()) {
774             if (InspectorController* inspector = static_cast<Document*>(scriptContext)->page()->inspectorController())
775                 inspector->postWorkerNotificationToFrontend(*m_worker, m_action);
776         }
777     }
778
779 private:
780     RefPtr<InspectorWorkerResource> m_worker;
781     InspectorController::WorkerAction m_action;
782 };
783
784 void InspectorController::postWorkerNotificationToFrontend(const InspectorWorkerResource& worker, InspectorController::WorkerAction action)
785 {
786     if (!m_frontend)
787         return;
788 #if ENABLE(JAVASCRIPT_DEBUGGER)
789     switch (action) {
790     case InspectorController::WorkerCreated:
791         m_frontend->didCreateWorker(worker.id(), worker.url(), worker.isSharedWorker());
792         break;
793     case InspectorController::WorkerDestroyed:
794         m_frontend->didDestroyWorker(worker.id());
795         break;
796     }
797 #endif
798 }
799
800 void InspectorController::didCreateWorker(intptr_t id, const String& url, bool isSharedWorker)
801 {
802     if (!enabled())
803         return;
804
805     RefPtr<InspectorWorkerResource> workerResource(InspectorWorkerResource::create(id, url, isSharedWorker));
806     m_workers.set(id, workerResource);
807     if (m_inspectedPage && m_frontend)
808         m_inspectedPage->mainFrame()->document()->postTask(PostWorkerNotificationToFrontendTask::create(workerResource, InspectorController::WorkerCreated));
809 }
810
811 void InspectorController::didDestroyWorker(intptr_t id)
812 {
813     if (!enabled())
814         return;
815
816     WorkersMap::iterator workerResource = m_workers.find(id);
817     if (workerResource == m_workers.end())
818         return;
819     if (m_inspectedPage && m_frontend)
820         m_inspectedPage->mainFrame()->document()->postTask(PostWorkerNotificationToFrontendTask::create(workerResource->second, InspectorController::WorkerDestroyed));
821     m_workers.remove(workerResource);
822 }
823 #endif // ENABLE(WORKERS)
824
825 #if ENABLE(DATABASE)
826 void InspectorController::didOpenDatabase(PassRefPtr<Database> database, const String& domain, const String& name, const String& version)
827 {
828     if (!enabled())
829         return;
830
831     RefPtr<InspectorDatabaseResource> resource = InspectorDatabaseResource::create(database, domain, name, version);
832
833     m_databaseResources.set(resource->id(), resource);
834
835     // Resources are only bound while visible.
836     if (m_frontend)
837         resource->bind(m_frontend.get());
838 }
839 #endif
840
841 void InspectorController::getCookies(RefPtr<InspectorArray>* cookies, WTF::String* cookiesString)
842 {
843     // If we can get raw cookies.
844     ListHashSet<Cookie> rawCookiesList;
845
846     // If we can't get raw cookies - fall back to String representation
847     String stringCookiesList;
848
849     // Return value to getRawCookies should be the same for every call because
850     // the return value is platform/network backend specific, and the call will
851     // always return the same true/false value.
852     bool rawCookiesImplemented = false;
853
854     for (Frame* frame = m_inspectedPage->mainFrame(); frame; frame = frame->tree()->traverseNext(m_inspectedPage->mainFrame())) {
855         Document* document = frame->document();
856         const CachedResourceLoader::DocumentResourceMap& allResources = document->cachedResourceLoader()->allCachedResources();
857         CachedResourceLoader::DocumentResourceMap::const_iterator end = allResources.end();
858         for (CachedResourceLoader::DocumentResourceMap::const_iterator it = allResources.begin(); it != end; ++it) {
859             Vector<Cookie> docCookiesList;
860             rawCookiesImplemented = getRawCookies(document, KURL(ParsedURLString, it->second->url()), docCookiesList);
861
862             if (!rawCookiesImplemented) {
863                 // FIXME: We need duplication checking for the String representation of cookies.
864                 ExceptionCode ec = 0;
865                 stringCookiesList += document->cookie(ec);
866                 // Exceptions are thrown by cookie() in sandboxed frames. That won't happen here
867                 // because "document" is the document of the main frame of the page.
868                 ASSERT(!ec);
869             } else {
870                 int cookiesSize = docCookiesList.size();
871                 for (int i = 0; i < cookiesSize; i++) {
872                     if (!rawCookiesList.contains(docCookiesList[i]))
873                         rawCookiesList.add(docCookiesList[i]);
874                 }
875             }
876         }
877     }
878
879     if (rawCookiesImplemented)
880         *cookies = buildArrayForCookies(rawCookiesList);
881     else
882         *cookiesString = stringCookiesList;
883 }
884
885 PassRefPtr<InspectorArray> InspectorController::buildArrayForCookies(ListHashSet<Cookie>& cookiesList)
886 {
887     RefPtr<InspectorArray> cookies = InspectorArray::create();
888
889     ListHashSet<Cookie>::iterator end = cookiesList.end();
890     ListHashSet<Cookie>::iterator it = cookiesList.begin();
891     for (int i = 0; it != end; ++it, i++)
892         cookies->pushObject(buildObjectForCookie(*it));
893
894     return cookies;
895 }
896
897 PassRefPtr<InspectorObject> InspectorController::buildObjectForCookie(const Cookie& cookie)
898 {
899     RefPtr<InspectorObject> value = InspectorObject::create();
900     value->setString("name", cookie.name);
901     value->setString("value", cookie.value);
902     value->setString("domain", cookie.domain);
903     value->setString("path", cookie.path);
904     value->setNumber("expires", cookie.expires);
905     value->setNumber("size", (cookie.name.length() + cookie.value.length()));
906     value->setBoolean("httpOnly", cookie.httpOnly);
907     value->setBoolean("secure", cookie.secure);
908     value->setBoolean("session", cookie.session);
909     return value;
910 }
911
912 void InspectorController::deleteCookie(const String& cookieName, const String& domain)
913 {
914     for (Frame* frame = m_inspectedPage->mainFrame(); frame; frame = frame->tree()->traverseNext(m_inspectedPage->mainFrame())) {
915         Document* document = frame->document();
916         if (document->url().host() != domain)
917             continue;
918         const CachedResourceLoader::DocumentResourceMap& allResources = document->cachedResourceLoader()->allCachedResources();
919         CachedResourceLoader::DocumentResourceMap::const_iterator end = allResources.end();
920         for (CachedResourceLoader::DocumentResourceMap::const_iterator it = allResources.begin(); it != end; ++it)
921             WebCore::deleteCookie(document, KURL(ParsedURLString, it->second->url()), cookieName);
922     }
923 }
924
925 #if ENABLE(DOM_STORAGE)
926 void InspectorController::didUseDOMStorage(StorageArea* storageArea, bool isLocalStorage, Frame* frame)
927 {
928     if (!enabled())
929         return;
930
931     DOMStorageResourcesMap::iterator domStorageEnd = m_domStorageResources.end();
932     for (DOMStorageResourcesMap::iterator it = m_domStorageResources.begin(); it != domStorageEnd; ++it)
933         if (it->second->isSameHostAndType(frame, isLocalStorage))
934             return;
935
936     RefPtr<Storage> domStorage = Storage::create(frame, storageArea);
937     RefPtr<InspectorDOMStorageResource> resource = InspectorDOMStorageResource::create(domStorage.get(), isLocalStorage, frame);
938
939     m_domStorageResources.set(resource->id(), resource);
940
941     // Resources are only bound while visible.
942     if (m_frontend)
943         resource->bind(m_frontend.get());
944 }
945 #endif
946
947 #if ENABLE(WEB_SOCKETS)
948 void InspectorController::didCreateWebSocket(unsigned long identifier, const KURL& requestURL, const KURL& documentURL)
949 {
950     if (!enabled())
951         return;
952     ASSERT(m_inspectedPage);
953
954     if (m_resourceAgent)
955         m_resourceAgent->didCreateWebSocket(identifier, requestURL);
956     UNUSED_PARAM(documentURL);
957 }
958
959 void InspectorController::willSendWebSocketHandshakeRequest(unsigned long identifier, const WebSocketHandshakeRequest& request)
960 {
961     if (m_resourceAgent)
962         m_resourceAgent->willSendWebSocketHandshakeRequest(identifier, request);
963 }
964
965 void InspectorController::didReceiveWebSocketHandshakeResponse(unsigned long identifier, const WebSocketHandshakeResponse& response)
966 {
967     if (m_resourceAgent)
968         m_resourceAgent->didReceiveWebSocketHandshakeResponse(identifier, response);
969 }
970
971 void InspectorController::didCloseWebSocket(unsigned long identifier)
972 {
973     if (m_resourceAgent)
974         m_resourceAgent->didCloseWebSocket(identifier);
975 }
976 #endif // ENABLE(WEB_SOCKETS)
977
978 #if ENABLE(JAVASCRIPT_DEBUGGER)
979 void InspectorController::addProfile(PassRefPtr<ScriptProfile> prpProfile, unsigned lineNumber, const String& sourceURL)
980 {
981     if (!enabled())
982         return;
983     m_profilerAgent->addProfile(prpProfile, lineNumber, sourceURL);
984 }
985
986 bool InspectorController::isRecordingUserInitiatedProfile() const
987 {
988     return m_profilerAgent->isRecordingUserInitiatedProfile();
989 }
990
991 String InspectorController::getCurrentUserInitiatedProfileName(bool incrementProfileNumber)
992 {
993     return m_profilerAgent->getCurrentUserInitiatedProfileName(incrementProfileNumber);
994 }
995
996 void InspectorController::startUserInitiatedProfiling()
997 {
998     if (!enabled())
999         return;
1000     m_profilerAgent->startUserInitiatedProfiling();
1001     m_state->setBoolean(InspectorState::userInitiatedProfiling, true);
1002 }
1003
1004 void InspectorController::stopUserInitiatedProfiling()
1005 {
1006     if (!enabled())
1007         return;
1008     m_profilerAgent->stopUserInitiatedProfiling();
1009     m_state->setBoolean(InspectorState::userInitiatedProfiling, false);
1010 }
1011
1012 bool InspectorController::profilerEnabled() const
1013 {
1014     return enabled() && m_profilerAgent->enabled();
1015 }
1016
1017 void InspectorController::enableProfiler(bool always, bool skipRecompile)
1018 {
1019     if (always)
1020         m_settings->setBoolean(InspectorSettings::ProfilerAlwaysEnabled, true);
1021     m_profilerAgent->enable(skipRecompile);
1022 }
1023
1024 void InspectorController::disableProfiler(bool always)
1025 {
1026     if (always)
1027         m_settings->setBoolean(InspectorSettings::ProfilerAlwaysEnabled, false);
1028     m_profilerAgent->disable();
1029 }
1030 #endif
1031
1032 #if ENABLE(JAVASCRIPT_DEBUGGER)
1033 void InspectorController::showAndEnableDebugger()
1034 {
1035     if (!enabled())
1036         return;
1037
1038     if (debuggerEnabled())
1039         return;
1040
1041     if (!m_frontend) {
1042         m_attachDebuggerWhenShown = true;
1043         showPanel(ScriptsPanel);
1044     } else
1045         enableDebugger(false);
1046 }
1047
1048 void InspectorController::enableDebugger(bool always)
1049 {
1050     ASSERT(!debuggerEnabled());
1051     if (always)
1052         m_settings->setBoolean(InspectorSettings::DebuggerAlwaysEnabled, true);
1053
1054     ASSERT(m_inspectedPage);
1055
1056     m_debuggerAgent = InspectorDebuggerAgent::create(this, m_frontend.get());
1057     m_browserDebuggerAgent = InspectorBrowserDebuggerAgent::create(this);
1058     restoreStickyBreakpoints();
1059
1060     m_frontend->debuggerWasEnabled();
1061 }
1062
1063 void InspectorController::disableDebugger(bool always)
1064 {
1065     if (!enabled())
1066         return;
1067
1068     if (always)
1069         m_settings->setBoolean(InspectorSettings::DebuggerAlwaysEnabled, false);
1070
1071     ASSERT(m_inspectedPage);
1072
1073     m_debuggerAgent.clear();
1074     m_browserDebuggerAgent.clear();
1075
1076     m_attachDebuggerWhenShown = false;
1077
1078     if (m_frontend)
1079         m_frontend->debuggerWasDisabled();
1080 }
1081
1082 void InspectorController::resume()
1083 {
1084     if (m_debuggerAgent)
1085         m_debuggerAgent->resume();
1086 }
1087
1088 void InspectorController::setStickyBreakpoints(PassRefPtr<InspectorObject> breakpoints)
1089 {
1090     m_state->setObject(InspectorState::stickyBreakpoints, breakpoints);
1091 }
1092
1093 void InspectorController::restoreStickyBreakpoints()
1094 {
1095     RefPtr<InspectorObject> allBreakpoints = m_state->getObject(InspectorState::stickyBreakpoints);
1096     KURL url = m_inspectedPage->mainFrame()->loader()->url();
1097     url.removeFragmentIdentifier();
1098     RefPtr<InspectorArray> breakpoints = allBreakpoints->getArray(url);
1099     if (!breakpoints)
1100         return;
1101     for (unsigned i = 0; i < breakpoints->length(); ++i)
1102         restoreStickyBreakpoint(breakpoints->get(i)->asObject());
1103 }
1104
1105 void InspectorController::restoreStickyBreakpoint(PassRefPtr<InspectorObject> breakpoint)
1106 {
1107     DEFINE_STATIC_LOCAL(String, eventListenerBreakpointType, ("EventListener"));
1108     DEFINE_STATIC_LOCAL(String, javaScriptBreakpointType, ("JS"));
1109     DEFINE_STATIC_LOCAL(String, xhrBreakpointType, ("XHR"));
1110
1111     if (!breakpoint)
1112         return;
1113     String type;
1114     if (!breakpoint->getString("type", &type))
1115         return;
1116     bool enabled;
1117     if (!breakpoint->getBoolean("enabled", &enabled))
1118         return;
1119     RefPtr<InspectorObject> condition = breakpoint->getObject("condition");
1120     if (!condition)
1121         return;
1122
1123     if (type == eventListenerBreakpointType && m_browserDebuggerAgent) {
1124         if (!enabled)
1125             return;
1126         String eventName;
1127         if (!condition->getString("eventName", &eventName))
1128             return;
1129         m_browserDebuggerAgent->setEventListenerBreakpoint(eventName);
1130     } else if (type == javaScriptBreakpointType && m_debuggerAgent) {
1131         String url;
1132         if (!condition->getString("url", &url))
1133             return;
1134         double lineNumber;
1135         if (!condition->getNumber("lineNumber", &lineNumber))
1136             return;
1137         String javaScriptCondition;
1138         if (!condition->getString("condition", &javaScriptCondition))
1139             return;
1140         m_debuggerAgent->setStickyBreakpoint(url, static_cast<unsigned>(lineNumber), javaScriptCondition, enabled);
1141     } else if (type == xhrBreakpointType && m_browserDebuggerAgent) {
1142         if (!enabled)
1143             return;
1144         String url;
1145         if (!condition->getString("url", &url))
1146             return;
1147         m_browserDebuggerAgent->setXHRBreakpoint(url);
1148     }
1149 }
1150 #endif
1151
1152 void InspectorController::evaluateForTestInFrontend(long callId, const String& script)
1153 {
1154     if (m_frontend)
1155         m_frontend->evaluateForTestInFrontend(callId, script);
1156     else
1157         m_pendingEvaluateTestCommands.append(pair<long, String>(callId, script));
1158 }
1159
1160 void InspectorController::didEvaluateForTestInFrontend(long callId, const String& jsonResult)
1161 {
1162     ScriptState* scriptState = scriptStateFromPage(debuggerWorld(), m_inspectedPage);
1163     ScriptObject window;
1164     ScriptGlobalObject::get(scriptState, "window", window);
1165     ScriptFunctionCall function(window, "didEvaluateForTestInFrontend");
1166     function.appendArgument(callId);
1167     function.appendArgument(jsonResult);
1168     function.call();
1169 }
1170
1171 static Path quadToPath(const FloatQuad& quad)
1172 {
1173     Path quadPath;
1174     quadPath.moveTo(quad.p1());
1175     quadPath.addLineTo(quad.p2());
1176     quadPath.addLineTo(quad.p3());
1177     quadPath.addLineTo(quad.p4());
1178     quadPath.closeSubpath();
1179     return quadPath;
1180 }
1181
1182 static void drawOutlinedQuad(GraphicsContext& context, const FloatQuad& quad, const Color& fillColor)
1183 {
1184     static const int outlineThickness = 2;
1185     static const Color outlineColor(62, 86, 180, 228);
1186
1187     Path quadPath = quadToPath(quad);
1188
1189     // Clip out the quad, then draw with a 2px stroke to get a pixel
1190     // of outline (because inflating a quad is hard)
1191     {
1192         context.save();
1193         context.clipOut(quadPath);
1194
1195         context.setStrokeThickness(outlineThickness);
1196         context.setStrokeColor(outlineColor, ColorSpaceDeviceRGB);
1197         context.strokePath(quadPath);
1198
1199         context.restore();
1200     }
1201
1202     // Now do the fill
1203     context.setFillColor(fillColor, ColorSpaceDeviceRGB);
1204     context.fillPath(quadPath);
1205 }
1206
1207 static void drawOutlinedQuadWithClip(GraphicsContext& context, const FloatQuad& quad, const FloatQuad& clipQuad, const Color& fillColor)
1208 {
1209     context.save();
1210     Path clipQuadPath = quadToPath(clipQuad);
1211     context.clipOut(clipQuadPath);
1212     drawOutlinedQuad(context, quad, fillColor);
1213     context.restore();
1214 }
1215
1216 static void drawHighlightForBox(GraphicsContext& context, const FloatQuad& contentQuad, const FloatQuad& paddingQuad, const FloatQuad& borderQuad, const FloatQuad& marginQuad)
1217 {
1218     static const Color contentBoxColor(125, 173, 217, 128);
1219     static const Color paddingBoxColor(125, 173, 217, 160);
1220     static const Color borderBoxColor(125, 173, 217, 192);
1221     static const Color marginBoxColor(125, 173, 217, 228);
1222
1223     if (marginQuad != borderQuad)
1224         drawOutlinedQuadWithClip(context, marginQuad, borderQuad, marginBoxColor);
1225     if (borderQuad != paddingQuad)
1226         drawOutlinedQuadWithClip(context, borderQuad, paddingQuad, borderBoxColor);
1227     if (paddingQuad != contentQuad)
1228         drawOutlinedQuadWithClip(context, paddingQuad, contentQuad, paddingBoxColor);
1229
1230     drawOutlinedQuad(context, contentQuad, contentBoxColor);
1231 }
1232
1233 static void drawHighlightForLineBoxesOrSVGRenderer(GraphicsContext& context, const Vector<FloatQuad>& lineBoxQuads)
1234 {
1235     static const Color lineBoxColor(125, 173, 217, 128);
1236
1237     for (size_t i = 0; i < lineBoxQuads.size(); ++i)
1238         drawOutlinedQuad(context, lineBoxQuads[i], lineBoxColor);
1239 }
1240
1241 static inline void convertFromFrameToMainFrame(Frame* frame, IntRect& rect)
1242 {
1243     rect = frame->page()->mainFrame()->view()->windowToContents(frame->view()->contentsToWindow(rect));
1244 }
1245
1246 static inline IntSize frameToMainFrameOffset(Frame* frame)
1247 {
1248     IntPoint mainFramePoint = frame->page()->mainFrame()->view()->windowToContents(frame->view()->contentsToWindow(IntPoint()));
1249     return mainFramePoint - IntPoint();
1250 }
1251
1252 void InspectorController::drawNodeHighlight(GraphicsContext& context) const
1253 {
1254     if (!m_highlightedNode)
1255         return;
1256
1257     RenderObject* renderer = m_highlightedNode->renderer();
1258     Frame* containingFrame = m_highlightedNode->document()->frame();
1259     if (!renderer || !containingFrame)
1260         return;
1261
1262     IntSize mainFrameOffset = frameToMainFrameOffset(containingFrame);
1263     IntRect boundingBox = renderer->absoluteBoundingBoxRect(true);
1264     boundingBox.move(mainFrameOffset);
1265
1266     IntRect titleReferenceBox = boundingBox;
1267
1268     ASSERT(m_inspectedPage);
1269
1270     FrameView* view = m_inspectedPage->mainFrame()->view();
1271     FloatRect overlayRect = view->visibleContentRect();
1272     if (!overlayRect.contains(boundingBox) && !boundingBox.contains(enclosingIntRect(overlayRect)))
1273         overlayRect = view->visibleContentRect();
1274     context.translate(-overlayRect.x(), -overlayRect.y());
1275
1276     // RenderSVGRoot should be highlighted through the isBox() code path, all other SVG elements should just dump their absoluteQuads().
1277 #if ENABLE(SVG)
1278     bool isSVGRenderer = renderer->node() && renderer->node()->isSVGElement() && !renderer->isSVGRoot();
1279 #else
1280     bool isSVGRenderer = false;
1281 #endif
1282
1283     if (renderer->isBox() && !isSVGRenderer) {
1284         RenderBox* renderBox = toRenderBox(renderer);
1285
1286         IntRect contentBox = renderBox->contentBoxRect();
1287
1288         IntRect paddingBox(contentBox.x() - renderBox->paddingLeft(), contentBox.y() - renderBox->paddingTop(),
1289                            contentBox.width() + renderBox->paddingLeft() + renderBox->paddingRight(), contentBox.height() + renderBox->paddingTop() + renderBox->paddingBottom());
1290         IntRect borderBox(paddingBox.x() - renderBox->borderLeft(), paddingBox.y() - renderBox->borderTop(),
1291                           paddingBox.width() + renderBox->borderLeft() + renderBox->borderRight(), paddingBox.height() + renderBox->borderTop() + renderBox->borderBottom());
1292         IntRect marginBox(borderBox.x() - renderBox->marginLeft(), borderBox.y() - renderBox->marginTop(),
1293                           borderBox.width() + renderBox->marginLeft() + renderBox->marginRight(), borderBox.height() + renderBox->marginTop() + renderBox->marginBottom());
1294
1295         titleReferenceBox = marginBox;
1296         titleReferenceBox.move(mainFrameOffset);
1297         titleReferenceBox.move(boundingBox.x(), boundingBox.y());
1298
1299         FloatQuad absContentQuad = renderBox->localToAbsoluteQuad(FloatRect(contentBox));
1300         FloatQuad absPaddingQuad = renderBox->localToAbsoluteQuad(FloatRect(paddingBox));
1301         FloatQuad absBorderQuad = renderBox->localToAbsoluteQuad(FloatRect(borderBox));
1302         FloatQuad absMarginQuad = renderBox->localToAbsoluteQuad(FloatRect(marginBox));
1303
1304         absContentQuad.move(mainFrameOffset);
1305         absPaddingQuad.move(mainFrameOffset);
1306         absBorderQuad.move(mainFrameOffset);
1307         absMarginQuad.move(mainFrameOffset);
1308
1309         drawHighlightForBox(context, absContentQuad, absPaddingQuad, absBorderQuad, absMarginQuad);
1310     } else if (renderer->isRenderInline() || isSVGRenderer) {
1311         // FIXME: We should show margins/padding/border for inlines.
1312         Vector<FloatQuad> lineBoxQuads;
1313         renderer->absoluteQuads(lineBoxQuads);
1314         for (unsigned i = 0; i < lineBoxQuads.size(); ++i)
1315             lineBoxQuads[i] += mainFrameOffset;
1316
1317         drawHighlightForLineBoxesOrSVGRenderer(context, lineBoxQuads);
1318     }
1319
1320     // Draw node title if necessary.
1321
1322     if (!m_highlightedNode->isElementNode())
1323         return;
1324
1325     WebCore::Settings* settings = containingFrame->settings();
1326     drawElementTitle(context, titleReferenceBox, overlayRect, settings);
1327 }
1328
1329 void InspectorController::drawElementTitle(GraphicsContext& context, const IntRect& boundingBox, const FloatRect& overlayRect, WebCore::Settings* settings) const
1330 {
1331     static const int rectInflatePx = 4;
1332     static const int fontHeightPx = 12;
1333     static const int borderWidthPx = 1;
1334     static const Color tooltipBackgroundColor(255, 255, 194, 255);
1335     static const Color tooltipBorderColor(Color::black);
1336     static const Color tooltipFontColor(Color::black);
1337
1338     Element* element = static_cast<Element*>(m_highlightedNode.get());
1339     bool isXHTML = element->document()->isXHTMLDocument();
1340     String nodeTitle = isXHTML ? element->nodeName() : element->nodeName().lower();
1341     const AtomicString& idValue = element->getIdAttribute();
1342     if (!idValue.isNull() && !idValue.isEmpty()) {
1343         nodeTitle += "#";
1344         nodeTitle += idValue;
1345     }
1346     if (element->hasClass() && element->isStyledElement()) {
1347         const SpaceSplitString& classNamesString = static_cast<StyledElement*>(element)->classNames();
1348         size_t classNameCount = classNamesString.size();
1349         if (classNameCount) {
1350             HashSet<AtomicString> usedClassNames;
1351             for (size_t i = 0; i < classNameCount; ++i) {
1352                 const AtomicString& className = classNamesString[i];
1353                 if (usedClassNames.contains(className))
1354                     continue;
1355                 usedClassNames.add(className);
1356                 nodeTitle += ".";
1357                 nodeTitle += className;
1358             }
1359         }
1360     }
1361
1362     Element* highlightedElement = m_highlightedNode->isElementNode() ? static_cast<Element*>(m_highlightedNode.get()) : 0;
1363     nodeTitle += " [";
1364     nodeTitle += String::number(highlightedElement ? highlightedElement->offsetWidth() : boundingBox.width());
1365     nodeTitle.append(static_cast<UChar>(0x00D7)); // &times;
1366     nodeTitle += String::number(highlightedElement ? highlightedElement->offsetHeight() : boundingBox.height());
1367     nodeTitle += "]";
1368
1369     FontDescription desc;
1370     FontFamily family;
1371     family.setFamily(settings->fixedFontFamily());
1372     desc.setFamily(family);
1373     desc.setComputedSize(fontHeightPx);
1374     Font font = Font(desc, 0, 0);
1375     font.update(0);
1376
1377     TextRun nodeTitleRun(nodeTitle);
1378     IntPoint titleBasePoint = boundingBox.bottomLeft();
1379     titleBasePoint.move(rectInflatePx, rectInflatePx);
1380     IntRect titleRect = enclosingIntRect(font.selectionRectForText(nodeTitleRun, titleBasePoint, fontHeightPx));
1381     titleRect.inflate(rectInflatePx);
1382
1383     // The initial offsets needed to compensate for a 1px-thick border stroke (which is not a part of the rectangle).
1384     int dx = -borderWidthPx;
1385     int dy = borderWidthPx;
1386
1387     // If the tip sticks beyond the right of overlayRect, right-align the tip with the said boundary.
1388     if (titleRect.right() > overlayRect.right())
1389         dx = overlayRect.right() - titleRect.right();
1390
1391     // If the tip sticks beyond the left of overlayRect, left-align the tip with the said boundary.
1392     if (titleRect.x() + dx < overlayRect.x())
1393         dx = overlayRect.x() - titleRect.x() - borderWidthPx;
1394
1395     // If the tip sticks beyond the bottom of overlayRect, show the tip at top of bounding box.
1396     if (titleRect.bottom() > overlayRect.bottom()) {
1397         dy = boundingBox.y() - titleRect.bottom() - borderWidthPx;
1398         // If the tip still sticks beyond the bottom of overlayRect, bottom-align the tip with the said boundary.
1399         if (titleRect.bottom() + dy > overlayRect.bottom())
1400             dy = overlayRect.bottom() - titleRect.bottom();
1401     }
1402
1403     // If the tip sticks beyond the top of overlayRect, show the tip at top of overlayRect.
1404     if (titleRect.y() + dy < overlayRect.y())
1405         dy = overlayRect.y() - titleRect.y() + borderWidthPx;
1406
1407     titleRect.move(dx, dy);
1408     context.setStrokeColor(tooltipBorderColor, ColorSpaceDeviceRGB);
1409     context.setStrokeThickness(borderWidthPx);
1410     context.setFillColor(tooltipBackgroundColor, ColorSpaceDeviceRGB);
1411     context.drawRect(titleRect);
1412     context.setFillColor(tooltipFontColor, ColorSpaceDeviceRGB);
1413     context.drawText(font, nodeTitleRun, IntPoint(titleRect.x() + rectInflatePx, titleRect.y() + font.height()));
1414 }
1415
1416 void InspectorController::openInInspectedWindow(const String& url)
1417 {
1418     Frame* mainFrame = m_inspectedPage->mainFrame();
1419
1420     FrameLoadRequest request(mainFrame->document()->securityOrigin(), ResourceRequest(), "_blank");
1421
1422     bool created;
1423     WindowFeatures windowFeatures;
1424     Frame* newFrame = WebCore::createWindow(mainFrame, mainFrame, request, windowFeatures, created);
1425     if (!newFrame)
1426         return;
1427
1428     UserGestureIndicator indicator(DefinitelyProcessingUserGesture);
1429     newFrame->loader()->setOpener(mainFrame);
1430     newFrame->page()->setOpenedByDOM();
1431     newFrame->loader()->changeLocation(mainFrame->document()->securityOrigin(), newFrame->loader()->completeURL(url), "", false, false);
1432 }
1433
1434 void InspectorController::addScriptToEvaluateOnLoad(const String& source)
1435 {
1436     m_scriptsToEvaluateOnLoad.append(source);
1437 }
1438
1439 void InspectorController::removeAllScriptsToEvaluateOnLoad()
1440 {
1441     m_scriptsToEvaluateOnLoad.clear();
1442 }
1443
1444 void InspectorController::setInspectorExtensionAPI(const String& source)
1445 {
1446     m_inspectorExtensionAPI = source;
1447 }
1448
1449 void InspectorController::reloadPage()
1450 {
1451     // FIXME: Why do we set the user gesture indicator here?
1452     UserGestureIndicator indicator(DefinitelyProcessingUserGesture);
1453     m_inspectedPage->mainFrame()->navigationScheduler()->scheduleRefresh();
1454 }
1455
1456 void InspectorController::setExtraHeaders(PassRefPtr<InspectorObject> headers)
1457 {
1458     m_extraHeaders = adoptPtr(new HTTPHeaderMap());
1459     InspectorObject::const_iterator end = headers->end();
1460     for (InspectorObject::const_iterator it = headers->begin(); it != end; ++it) {
1461         String value;
1462         if (!it->second->asString(&value))
1463             continue;
1464         m_extraHeaders->add(it->first, value);
1465     }
1466 }
1467
1468 } // namespace WebCore
1469
1470 #endif // ENABLE(INSPECTOR)