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