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