2011-01-21 Pavel Podivilov <podivilov@chromium.org>
[WebKit-https.git] / Source / WebCore / inspector / InspectorController.cpp
1 /*
2  * Copyright (C) 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
3  * Copyright (C) 2008 Matt Lilek <webkit@mattlilek.com>
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1.  Redistributions of source code must retain the above copyright
10  *     notice, this list of conditions and the following disclaimer.
11  * 2.  Redistributions in binary form must reproduce the above copyright
12  *     notice, this list of conditions and the following disclaimer in the
13  *     documentation and/or other materials provided with the distribution.
14  * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
15  *     its contributors may be used to endorse or promote products derived
16  *     from this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
19  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
22  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
28  */
29
30 #include "config.h"
31 #include "InspectorController.h"
32
33 #if ENABLE(INSPECTOR)
34
35 #include "CachedResource.h"
36 #include "CachedResourceLoader.h"
37 #include "Chrome.h"
38 #include "Cookie.h"
39 #include "CookieJar.h"
40 #include "DOMWindow.h"
41 #include "DOMWrapperWorld.h"
42 #include "Document.h"
43 #include "DocumentLoader.h"
44 #include "Element.h"
45 #include "FloatConversion.h"
46 #include "FloatQuad.h"
47 #include "FloatRect.h"
48 #include "Frame.h"
49 #include "FrameLoadRequest.h"
50 #include "FrameLoader.h"
51 #include "FrameTree.h"
52 #include "FrameView.h"
53 #include "GraphicsContext.h"
54 #include "HTMLFrameOwnerElement.h"
55 #include "HTTPHeaderMap.h"
56 #include "HitTestResult.h"
57 #include "InjectedScript.h"
58 #include "InjectedScriptHost.h"
59 #include "InspectorBackendDispatcher.h"
60 #include "InspectorBrowserDebuggerAgent.h"
61 #include "InspectorCSSAgent.h"
62 #include "InspectorClient.h"
63 #include "InspectorConsoleAgent.h"
64 #include "InspectorDOMAgent.h"
65 #include "InspectorDOMStorageResource.h"
66 #include "InspectorDatabaseResource.h"
67 #include "InspectorDebuggerAgent.h"
68 #include "InspectorFrontend.h"
69 #include "InspectorFrontendClient.h"
70 #include "InspectorInstrumentation.h"
71 #include "InspectorProfilerAgent.h"
72 #include "InspectorResourceAgent.h"
73 #include "InspectorRuntimeAgent.h"
74 #include "InspectorSettings.h"
75 #include "InspectorState.h"
76 #include "InspectorTimelineAgent.h"
77 #include "InspectorValues.h"
78 #include "InspectorWorkerResource.h"
79 #include "IntRect.h"
80 #include "Page.h"
81 #include "ProgressTracker.h"
82 #include "Range.h"
83 #include "RenderInline.h"
84 #include "ResourceRequest.h"
85 #include "ResourceResponse.h"
86 #include "ScriptArguments.h"
87 #include "ScriptCallStack.h"
88 #include "ScriptFunctionCall.h"
89 #include "ScriptObject.h"
90 #include "ScriptProfile.h"
91 #include "ScriptProfiler.h"
92 #include "ScriptSourceCode.h"
93 #include "ScriptState.h"
94 #include "SecurityOrigin.h"
95 #include "Settings.h"
96 #include "SharedBuffer.h"
97 #include "TextEncoding.h"
98 #include "TextIterator.h"
99 #include "TextRun.h"
100 #include "UserGestureIndicator.h"
101 #include "WindowFeatures.h"
102 #include <wtf/text/StringConcatenate.h>
103 #include <wtf/CurrentTime.h>
104 #include <wtf/ListHashSet.h>
105 #include <wtf/RefCounted.h>
106 #include <wtf/StdLibExtras.h>
107 #include <wtf/UnusedParam.h>
108
109 #if ENABLE(DATABASE)
110 #include "Database.h"
111 #include "InspectorDatabaseAgent.h"
112 #endif
113
114 #if ENABLE(DOM_STORAGE)
115 #include "InspectorDOMStorageAgent.h"
116 #include "Storage.h"
117 #include "StorageArea.h"
118 #endif
119
120 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
121 #include "InspectorApplicationCacheAgent.h"
122 #endif
123
124 #if ENABLE(FILE_SYSTEM)
125 #include "InspectorFileSystemAgent.h"
126 #endif
127
128 using namespace std;
129
130 namespace WebCore {
131
132 const char* const InspectorController::ElementsPanel = "elements";
133 const char* const InspectorController::ConsolePanel = "console";
134 const char* const InspectorController::ScriptsPanel = "scripts";
135 const char* const InspectorController::ProfilesPanel = "profiles";
136
137 InspectorController::InspectorController(Page* page, InspectorClient* client)
138     : m_inspectedPage(page)
139     , m_client(client)
140     , m_openingFrontend(false)
141     , m_cssAgent(new InspectorCSSAgent())
142     , m_state(new InspectorState(client))
143     , m_inspectorBackendDispatcher(new InspectorBackendDispatcher(this))
144     , m_injectedScriptHost(InjectedScriptHost::create(this))
145     , m_consoleAgent(new InspectorConsoleAgent(this))
146 #if ENABLE(JAVASCRIPT_DEBUGGER)
147     , m_attachDebuggerWhenShown(false)
148     , m_profilerAgent(InspectorProfilerAgent::create(this))
149 #endif
150 {
151     ASSERT_ARG(page, page);
152     ASSERT_ARG(client, client);
153 }
154
155 InspectorController::~InspectorController()
156 {
157     // These should have been cleared in inspectedPageDestroyed().
158     ASSERT(!m_client);
159     ASSERT(!m_inspectedPage);
160     ASSERT(!m_highlightedNode);
161
162     releaseFrontendLifetimeAgents();
163
164     m_injectedScriptHost->disconnectController();
165 }
166
167 void InspectorController::inspectedPageDestroyed()
168 {
169     if (m_frontend)
170         m_frontend->disconnectFromBackend();
171
172     hideHighlight();
173
174 #if ENABLE(JAVASCRIPT_DEBUGGER)
175     m_debuggerAgent.clear();
176     m_browserDebuggerAgent.clear();
177 #endif
178
179     ASSERT(m_inspectedPage);
180     m_inspectedPage = 0;
181
182     m_client->inspectorDestroyed();
183     m_client = 0;
184 }
185
186 bool InspectorController::enabled() const
187 {
188     if (!m_inspectedPage)
189         return false;
190     return m_inspectedPage->settings()->developerExtrasEnabled();
191 }
192
193 bool InspectorController::inspectorStartsAttached()
194 {
195     return m_settings->getBoolean(InspectorSettings::InspectorStartsAttached);
196 }
197
198 void InspectorController::setInspectorStartsAttached(bool attached)
199 {
200     m_settings->setBoolean(InspectorSettings::InspectorStartsAttached, attached);
201 }
202
203 void InspectorController::setInspectorAttachedHeight(long height)
204 {
205     m_settings->setLong(InspectorSettings::InspectorAttachedHeight, height);
206 }
207
208 long InspectorController::inspectorAttachedHeight() const
209 {
210     return m_settings->getLong(InspectorSettings::InspectorAttachedHeight);
211 }
212
213 bool InspectorController::searchingForNodeInPage() const
214 {
215     return m_state->getBoolean(InspectorState::searchingForNode);
216 }
217
218 void InspectorController::restoreInspectorStateFromCookie(const String& inspectorStateCookie)
219 {
220     m_state->restoreFromInspectorCookie(inspectorStateCookie);
221
222     if (!m_frontend) {
223         connectFrontend();
224         m_frontend->frontendReused();
225         m_frontend->inspectedURLChanged(inspectedURL().string());
226         m_domAgent->setDocument(m_inspectedPage->mainFrame()->document());
227         pushDataCollectedOffline();
228     }
229
230     m_resourceAgent = InspectorResourceAgent::restore(m_inspectedPage, m_state.get(), m_frontend.get());
231
232     if (m_state->getBoolean(InspectorState::timelineProfilerEnabled))
233         startTimelineProfiler();
234
235 #if ENABLE(JAVASCRIPT_DEBUGGER)
236     restoreDebugger();
237     restoreProfiler(ProfilerRestoreResetAgent);
238     if (m_state->getBoolean(InspectorState::userInitiatedProfiling))
239         startUserInitiatedProfiling();
240 #endif
241 }
242
243 void InspectorController::inspect(Node* node)
244 {
245     if (!enabled())
246         return;
247
248     show();
249
250     if (node->nodeType() != Node::ELEMENT_NODE && node->nodeType() != Node::DOCUMENT_NODE)
251         node = node->parentNode();
252     m_nodeToFocus = node;
253
254     if (!m_frontend)
255         return;
256
257     focusNode();
258 }
259
260 void InspectorController::focusNode()
261 {
262     if (!enabled())
263         return;
264
265     ASSERT(m_frontend);
266     ASSERT(m_nodeToFocus);
267
268     long id = m_domAgent->pushNodePathToFrontend(m_nodeToFocus.get());
269     m_frontend->updateFocusedNode(id);
270     m_nodeToFocus = 0;
271 }
272
273 void InspectorController::highlight(Node* node)
274 {
275     if (!enabled())
276         return;
277     ASSERT_ARG(node, node);
278     m_highlightedNode = node;
279     m_client->highlight(node);
280 }
281
282 void InspectorController::highlightDOMNode(long nodeId)
283 {
284     Node* node = 0;
285     if (m_domAgent && (node = m_domAgent->nodeForId(nodeId)))
286         highlight(node);
287 }
288
289 void InspectorController::highlightFrame(unsigned long frameId)
290 {
291     Frame* mainFrame = m_inspectedPage->mainFrame();
292     for (Frame* frame = mainFrame; frame; frame = frame->tree()->traverseNext(mainFrame)) {
293         if (reinterpret_cast<uintptr_t>(frame) == frameId && frame->ownerElement()) {
294             highlight(frame->ownerElement());
295             return;
296         }
297     }
298 }
299
300 void InspectorController::hideHighlight()
301 {
302     if (!enabled())
303         return;
304     m_highlightedNode = 0;
305     m_client->hideHighlight();
306 }
307
308 void InspectorController::mouseDidMoveOverElement(const HitTestResult& result, unsigned)
309 {
310     if (!enabled() || !searchingForNodeInPage())
311         return;
312
313     Node* node = result.innerNode();
314     while (node && node->nodeType() == Node::TEXT_NODE)
315         node = node->parentNode();
316     if (node)
317         highlight(node);
318 }
319
320 bool InspectorController::handleMousePress()
321 {
322     if (!enabled() || !searchingForNodeInPage())
323         return false;
324
325     if (m_highlightedNode) {
326         RefPtr<Node> node = m_highlightedNode;
327         setSearchingForNode(false);
328         inspect(node.get());
329     }
330     return true;
331 }
332
333 void InspectorController::setInspectorFrontendClient(PassOwnPtr<InspectorFrontendClient> client)
334 {
335     ASSERT(!m_inspectorFrontendClient);
336     m_inspectorFrontendClient = client;
337 }
338
339 void InspectorController::didClearWindowObjectInWorld(Frame* frame, DOMWrapperWorld* world)
340 {
341     if (world != mainThreadNormalWorld())
342         return;
343
344     // If the page is supposed to serve as InspectorFrontend notify inspetor frontend
345     // client that it's cleared so that the client can expose inspector bindings.
346     if (m_inspectorFrontendClient && frame == m_inspectedPage->mainFrame())
347         m_inspectorFrontendClient->windowObjectCleared();
348
349     if (enabled()) {
350         if (m_frontend && frame == m_inspectedPage->mainFrame())
351             m_injectedScriptHost->discardInjectedScripts();
352         if (m_scriptsToEvaluateOnLoad.size()) {
353             ScriptState* scriptState = mainWorldScriptState(frame);
354             for (Vector<String>::iterator it = m_scriptsToEvaluateOnLoad.begin();
355                  it != m_scriptsToEvaluateOnLoad.end(); ++it) {
356                 m_injectedScriptHost->injectScript(*it, scriptState);
357             }
358         }
359     }
360     if (!m_inspectorExtensionAPI.isEmpty())
361         m_injectedScriptHost->injectScript(m_inspectorExtensionAPI, mainWorldScriptState(frame));
362 }
363
364 void InspectorController::setSearchingForNode(bool enabled)
365 {
366     if (searchingForNodeInPage() == enabled)
367         return;
368     m_state->setBoolean(InspectorState::searchingForNode, enabled);
369     if (!enabled)
370         hideHighlight();
371 }
372
373 void InspectorController::setSearchingForNode(bool enabled, bool* newState)
374 {
375     *newState = enabled;
376     setSearchingForNode(enabled);
377 }
378
379 void InspectorController::connectFrontend()
380 {
381     m_openingFrontend = false;
382     releaseFrontendLifetimeAgents();
383     m_frontend = new InspectorFrontend(m_client);
384     m_domAgent = InspectorDOMAgent::create(m_injectedScriptHost.get(), m_frontend.get());
385     m_runtimeAgent = InspectorRuntimeAgent::create(m_injectedScriptHost.get());
386     m_cssAgent->setDOMAgent(m_domAgent.get());
387
388 #if ENABLE(DATABASE)
389     m_databaseAgent = InspectorDatabaseAgent::create(&m_databaseResources, m_frontend.get());
390 #endif
391
392 #if ENABLE(DOM_STORAGE)
393     m_domStorageAgent = InspectorDOMStorageAgent::create(&m_domStorageResources, m_frontend.get());
394 #endif
395
396     if (m_timelineAgent)
397         m_timelineAgent->resetFrontendProxyObject(m_frontend.get());
398
399     m_consoleAgent->setFrontend(m_frontend.get());
400
401     // Initialize Web Inspector title.
402     m_frontend->inspectedURLChanged(inspectedURL().string());
403
404 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
405     m_applicationCacheAgent = new InspectorApplicationCacheAgent(this, m_frontend.get());
406 #endif
407
408 #if ENABLE(FILE_SYSTEM)
409     m_fileSystemAgent = InspectorFileSystemAgent::create(this, m_frontend.get());
410 #endif
411     
412     if (!InspectorInstrumentation::hasFrontends())
413         ScriptController::setCaptureCallStackForUncaughtExceptions(true);
414     InspectorInstrumentation::frontendCreated();
415 }
416
417 void InspectorController::show()
418 {
419     if (!enabled())
420         return;
421
422     if (m_openingFrontend)
423         return;
424
425     if (m_frontend)
426         m_frontend->bringToFront();
427     else {
428         m_openingFrontend = true;
429         m_client->openInspectorFrontend(this);
430     }
431 }
432
433 void InspectorController::showPanel(const String& panel)
434 {
435     if (!enabled())
436         return;
437
438     show();
439
440     if (!m_frontend) {
441         m_showAfterVisible = panel;
442         return;
443     }
444     m_frontend->showPanel(panel);
445 }
446
447 void InspectorController::close()
448 {
449     if (!m_frontend)
450         return;
451     m_frontend->disconnectFromBackend();
452     disconnectFrontend();
453 }
454
455 void InspectorController::disconnectFrontend()
456 {
457     if (!m_frontend)
458         return;
459
460     m_frontend.clear();
461
462     InspectorInstrumentation::frontendDeleted();
463     if (!InspectorInstrumentation::hasFrontends())
464         ScriptController::setCaptureCallStackForUncaughtExceptions(false);
465
466 #if ENABLE(JAVASCRIPT_DEBUGGER)
467     // If the window is being closed with the debugger enabled,
468     // remember this state to re-enable debugger on the next window
469     // opening.
470     bool debuggerWasEnabled = debuggerEnabled();
471     disableDebugger();
472     m_attachDebuggerWhenShown = debuggerWasEnabled;
473 #endif
474     setSearchingForNode(false);
475     unbindAllResources();
476     stopTimelineProfiler();
477
478     hideHighlight();
479
480 #if ENABLE(JAVASCRIPT_DEBUGGER)
481     m_profilerAgent->setFrontend(0);
482     m_profilerAgent->stopUserInitiatedProfiling(true);
483 #endif
484     m_consoleAgent->setFrontend(0);
485
486     releaseFrontendLifetimeAgents();
487     m_timelineAgent.clear();
488     m_extraHeaders.clear();
489 }
490
491 InspectorResourceAgent* InspectorController::resourceAgent()
492 {
493     if (!m_resourceAgent && m_frontend)
494         m_resourceAgent = InspectorResourceAgent::create(m_inspectedPage, m_state.get(), m_frontend.get());
495     return m_resourceAgent.get();
496 }
497
498 void InspectorController::releaseFrontendLifetimeAgents()
499 {
500     m_resourceAgent.clear();
501     m_runtimeAgent.clear();
502
503     // This should be invoked prior to m_domAgent destruction.
504     m_cssAgent->setDOMAgent(0);
505
506     // m_domAgent is RefPtr. Remove DOM listeners first to ensure that there are
507     // no references to the DOM agent from the DOM tree.
508     if (m_domAgent)
509         m_domAgent->reset();
510     m_domAgent.clear();
511
512 #if ENABLE(DATABASE)
513     if (m_databaseAgent)
514         m_databaseAgent->clearFrontend();
515     m_databaseAgent.clear();
516 #endif
517
518 #if ENABLE(DOM_STORAGE)
519     m_domStorageAgent.clear();
520 #endif
521
522 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
523     m_applicationCacheAgent.clear();
524 #endif
525
526 #if ENABLE(FILE_SYSTEM)
527     if (m_fileSystemAgent)
528         m_fileSystemAgent->stop(); 
529         m_fileSystemAgent.clear();
530 #endif
531 }
532
533 void InspectorController::populateScriptObjects()
534 {
535     ASSERT(m_frontend);
536     if (!m_frontend)
537         return;
538
539     if (!m_showAfterVisible.isEmpty()) {
540         showPanel(m_showAfterVisible);
541         m_showAfterVisible = "";
542     }
543
544 #if ENABLE(JAVASCRIPT_DEBUGGER)
545     if (m_profilerAgent->enabled())
546         m_frontend->profilerWasEnabled();
547 #endif
548
549     pushDataCollectedOffline();
550
551     if (m_nodeToFocus)
552         focusNode();
553
554     // Dispatch pending frontend commands
555     for (Vector<pair<long, String> >::iterator it = m_pendingEvaluateTestCommands.begin(); it != m_pendingEvaluateTestCommands.end(); ++it)
556         m_frontend->evaluateForTestInFrontend((*it).first, (*it).second);
557     m_pendingEvaluateTestCommands.clear();
558
559     restoreDebugger();
560     restoreProfiler(ProfilerRestoreNoAction);
561 }
562
563 void InspectorController::pushDataCollectedOffline()
564 {
565     m_domAgent->setDocument(m_inspectedPage->mainFrame()->document());
566
567 #if ENABLE(DATABASE)
568     DatabaseResourcesMap::iterator databasesEnd = m_databaseResources.end();
569     for (DatabaseResourcesMap::iterator it = m_databaseResources.begin(); it != databasesEnd; ++it)
570         it->second->bind(m_frontend.get());
571 #endif
572 #if ENABLE(DOM_STORAGE)
573     DOMStorageResourcesMap::iterator domStorageEnd = m_domStorageResources.end();
574     for (DOMStorageResourcesMap::iterator it = m_domStorageResources.begin(); it != domStorageEnd; ++it)
575         it->second->bind(m_frontend.get());
576 #endif
577 #if ENABLE(JAVASCRIPT_DEBUGGER) && ENABLE(WORKERS)
578     WorkersMap::iterator workersEnd = m_workers.end();
579     for (WorkersMap::iterator it = m_workers.begin(); it != workersEnd; ++it) {
580         InspectorWorkerResource* worker = it->second.get();
581         m_frontend->didCreateWorker(worker->id(), worker->url(), worker->isSharedWorker());
582     }
583 #endif
584 }
585
586 void InspectorController::restoreDebugger()
587 {
588     ASSERT(m_frontend);
589 #if ENABLE(JAVASCRIPT_DEBUGGER)
590     if (InspectorDebuggerAgent::isDebuggerAlwaysEnabled() || m_attachDebuggerWhenShown || m_settings->getBoolean(InspectorSettings::DebuggerAlwaysEnabled)) {
591         enableDebugger(false);
592         m_attachDebuggerWhenShown = false;
593     }
594 #endif
595 }
596
597 void InspectorController::restoreProfiler(ProfilerRestoreAction action)
598 {
599     ASSERT(m_frontend);
600 #if ENABLE(JAVASCRIPT_DEBUGGER)
601     m_profilerAgent->setFrontend(m_frontend.get());
602     if (!ScriptProfiler::isProfilerAlwaysEnabled() && m_settings->getBoolean(InspectorSettings::ProfilerAlwaysEnabled))
603         enableProfiler();
604     if (action == ProfilerRestoreResetAgent)
605         m_profilerAgent->resetFrontendProfiles();
606 #endif
607 }
608
609 void InspectorController::unbindAllResources()
610 {
611 #if ENABLE(DATABASE)
612     DatabaseResourcesMap::iterator databasesEnd = m_databaseResources.end();
613     for (DatabaseResourcesMap::iterator it = m_databaseResources.begin(); it != databasesEnd; ++it)
614         it->second->unbind();
615 #endif
616 #if ENABLE(DOM_STORAGE)
617     DOMStorageResourcesMap::iterator domStorageEnd = m_domStorageResources.end();
618     for (DOMStorageResourcesMap::iterator it = m_domStorageResources.begin(); it != domStorageEnd; ++it)
619         it->second->unbind();
620 #endif
621     if (m_timelineAgent)
622         m_timelineAgent->reset();
623 }
624
625 void InspectorController::didCommitLoad(DocumentLoader* loader)
626 {
627     if (!enabled())
628         return;
629
630     if (m_resourceAgent)
631         m_resourceAgent->didCommitLoad(loader);
632     
633     ASSERT(m_inspectedPage);
634
635     if (loader->frame() == m_inspectedPage->mainFrame()) {
636         if (m_frontend)
637             m_frontend->inspectedURLChanged(loader->url().string());
638
639         m_injectedScriptHost->discardInjectedScripts();
640         m_consoleAgent->reset();
641
642 #if ENABLE(JAVASCRIPT_DEBUGGER)
643         if (m_debuggerAgent) {
644             m_debuggerAgent->clearForPageNavigation();
645             if (m_browserDebuggerAgent)
646                 m_browserDebuggerAgent->inspectedURLChanged(inspectedURL());
647         }
648 #endif
649
650 #if ENABLE(JAVASCRIPT_DEBUGGER) && USE(JSC)
651         m_profilerAgent->stopUserInitiatedProfiling(true);
652         m_profilerAgent->resetState();
653 #endif
654
655         // unbindAllResources should be called before database and DOM storage
656         // resources are cleared so that it has a chance to unbind them.
657         unbindAllResources();
658
659         if (m_frontend) {
660             m_frontend->reset();
661             m_domAgent->reset();
662             m_cssAgent->reset();
663         }
664 #if ENABLE(WORKERS)
665         m_workers.clear();
666 #endif
667 #if ENABLE(DATABASE)
668         m_databaseResources.clear();
669 #endif
670 #if ENABLE(DOM_STORAGE)
671         m_domStorageResources.clear();
672 #endif
673
674         if (m_frontend)
675             m_domAgent->setDocument(m_inspectedPage->mainFrame()->document());
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 bool InspectorController::isRecordingUserInitiatedProfile() const
986 {
987     return m_profilerAgent->isRecordingUserInitiatedProfile();
988 }
989
990 void InspectorController::startUserInitiatedProfiling()
991 {
992     if (!enabled())
993         return;
994     m_profilerAgent->startUserInitiatedProfiling();
995     m_state->setBoolean(InspectorState::userInitiatedProfiling, true);
996 }
997
998 void InspectorController::stopUserInitiatedProfiling()
999 {
1000     if (!enabled())
1001         return;
1002     m_profilerAgent->stopUserInitiatedProfiling();
1003     m_state->setBoolean(InspectorState::userInitiatedProfiling, false);
1004 }
1005
1006 bool InspectorController::profilerEnabled() const
1007 {
1008     return enabled() && m_profilerAgent->enabled();
1009 }
1010
1011 void InspectorController::enableProfiler(bool always, bool skipRecompile)
1012 {
1013     if (always)
1014         m_settings->setBoolean(InspectorSettings::ProfilerAlwaysEnabled, true);
1015     m_profilerAgent->enable(skipRecompile);
1016 }
1017
1018 void InspectorController::disableProfiler(bool always)
1019 {
1020     if (always)
1021         m_settings->setBoolean(InspectorSettings::ProfilerAlwaysEnabled, false);
1022     m_profilerAgent->disable();
1023 }
1024 #endif
1025
1026 #if ENABLE(JAVASCRIPT_DEBUGGER)
1027 void InspectorController::showAndEnableDebugger()
1028 {
1029     if (!enabled())
1030         return;
1031
1032     if (debuggerEnabled())
1033         return;
1034
1035     if (!m_frontend) {
1036         m_attachDebuggerWhenShown = true;
1037         showPanel(ScriptsPanel);
1038     } else
1039         enableDebugger(false);
1040 }
1041
1042 void InspectorController::enableDebugger(bool always)
1043 {
1044     ASSERT(!debuggerEnabled());
1045     if (always)
1046         m_settings->setBoolean(InspectorSettings::DebuggerAlwaysEnabled, true);
1047
1048     ASSERT(m_inspectedPage);
1049
1050     m_debuggerAgent = InspectorDebuggerAgent::create(this, m_frontend.get());
1051     m_browserDebuggerAgent = InspectorBrowserDebuggerAgent::create(this);
1052     m_browserDebuggerAgent->inspectedURLChanged(inspectedURL());
1053
1054     m_frontend->debuggerWasEnabled();
1055 }
1056
1057 void InspectorController::disableDebugger(bool always)
1058 {
1059     if (!enabled())
1060         return;
1061
1062     if (always)
1063         m_settings->setBoolean(InspectorSettings::DebuggerAlwaysEnabled, false);
1064
1065     ASSERT(m_inspectedPage);
1066
1067     m_debuggerAgent.clear();
1068     m_browserDebuggerAgent.clear();
1069
1070     m_attachDebuggerWhenShown = false;
1071
1072     if (m_frontend)
1073         m_frontend->debuggerWasDisabled();
1074 }
1075
1076 void InspectorController::resume()
1077 {
1078     if (m_debuggerAgent)
1079         m_debuggerAgent->resume();
1080 }
1081
1082 void InspectorController::setAllBrowserBreakpoints(PassRefPtr<InspectorObject> breakpoints)
1083 {
1084     m_state->setObject(InspectorState::browserBreakpoints, breakpoints);
1085 }
1086 #endif
1087
1088 void InspectorController::evaluateForTestInFrontend(long callId, const String& script)
1089 {
1090     if (m_frontend)
1091         m_frontend->evaluateForTestInFrontend(callId, script);
1092     else
1093         m_pendingEvaluateTestCommands.append(pair<long, String>(callId, script));
1094 }
1095
1096 void InspectorController::didEvaluateForTestInFrontend(long callId, const String& jsonResult)
1097 {
1098     ScriptState* scriptState = scriptStateFromPage(debuggerWorld(), m_inspectedPage);
1099     ScriptObject window;
1100     ScriptGlobalObject::get(scriptState, "window", window);
1101     ScriptFunctionCall function(window, "didEvaluateForTestInFrontend");
1102     function.appendArgument(callId);
1103     function.appendArgument(jsonResult);
1104     function.call();
1105 }
1106
1107 static Path quadToPath(const FloatQuad& quad)
1108 {
1109     Path quadPath;
1110     quadPath.moveTo(quad.p1());
1111     quadPath.addLineTo(quad.p2());
1112     quadPath.addLineTo(quad.p3());
1113     quadPath.addLineTo(quad.p4());
1114     quadPath.closeSubpath();
1115     return quadPath;
1116 }
1117
1118 static void drawOutlinedQuad(GraphicsContext& context, const FloatQuad& quad, const Color& fillColor)
1119 {
1120     static const int outlineThickness = 2;
1121     static const Color outlineColor(62, 86, 180, 228);
1122
1123     Path quadPath = quadToPath(quad);
1124
1125     // Clip out the quad, then draw with a 2px stroke to get a pixel
1126     // of outline (because inflating a quad is hard)
1127     {
1128         context.save();
1129         context.clipOut(quadPath);
1130
1131         context.setStrokeThickness(outlineThickness);
1132         context.setStrokeColor(outlineColor, ColorSpaceDeviceRGB);
1133         context.strokePath(quadPath);
1134
1135         context.restore();
1136     }
1137
1138     // Now do the fill
1139     context.setFillColor(fillColor, ColorSpaceDeviceRGB);
1140     context.fillPath(quadPath);
1141 }
1142
1143 static void drawOutlinedQuadWithClip(GraphicsContext& context, const FloatQuad& quad, const FloatQuad& clipQuad, const Color& fillColor)
1144 {
1145     context.save();
1146     Path clipQuadPath = quadToPath(clipQuad);
1147     context.clipOut(clipQuadPath);
1148     drawOutlinedQuad(context, quad, fillColor);
1149     context.restore();
1150 }
1151
1152 static void drawHighlightForBox(GraphicsContext& context, const FloatQuad& contentQuad, const FloatQuad& paddingQuad, const FloatQuad& borderQuad, const FloatQuad& marginQuad)
1153 {
1154     static const Color contentBoxColor(125, 173, 217, 128);
1155     static const Color paddingBoxColor(125, 173, 217, 160);
1156     static const Color borderBoxColor(125, 173, 217, 192);
1157     static const Color marginBoxColor(125, 173, 217, 228);
1158
1159     if (marginQuad != borderQuad)
1160         drawOutlinedQuadWithClip(context, marginQuad, borderQuad, marginBoxColor);
1161     if (borderQuad != paddingQuad)
1162         drawOutlinedQuadWithClip(context, borderQuad, paddingQuad, borderBoxColor);
1163     if (paddingQuad != contentQuad)
1164         drawOutlinedQuadWithClip(context, paddingQuad, contentQuad, paddingBoxColor);
1165
1166     drawOutlinedQuad(context, contentQuad, contentBoxColor);
1167 }
1168
1169 static void drawHighlightForLineBoxesOrSVGRenderer(GraphicsContext& context, const Vector<FloatQuad>& lineBoxQuads)
1170 {
1171     static const Color lineBoxColor(125, 173, 217, 128);
1172
1173     for (size_t i = 0; i < lineBoxQuads.size(); ++i)
1174         drawOutlinedQuad(context, lineBoxQuads[i], lineBoxColor);
1175 }
1176
1177 static inline void convertFromFrameToMainFrame(Frame* frame, IntRect& rect)
1178 {
1179     rect = frame->page()->mainFrame()->view()->windowToContents(frame->view()->contentsToWindow(rect));
1180 }
1181
1182 static inline IntSize frameToMainFrameOffset(Frame* frame)
1183 {
1184     IntPoint mainFramePoint = frame->page()->mainFrame()->view()->windowToContents(frame->view()->contentsToWindow(IntPoint()));
1185     return mainFramePoint - IntPoint();
1186 }
1187
1188 void InspectorController::drawNodeHighlight(GraphicsContext& context) const
1189 {
1190     if (!m_highlightedNode)
1191         return;
1192
1193     RenderObject* renderer = m_highlightedNode->renderer();
1194     Frame* containingFrame = m_highlightedNode->document()->frame();
1195     if (!renderer || !containingFrame)
1196         return;
1197
1198     IntSize mainFrameOffset = frameToMainFrameOffset(containingFrame);
1199     IntRect boundingBox = renderer->absoluteBoundingBoxRect(true);
1200     boundingBox.move(mainFrameOffset);
1201
1202     IntRect titleReferenceBox = boundingBox;
1203
1204     ASSERT(m_inspectedPage);
1205
1206     FrameView* view = m_inspectedPage->mainFrame()->view();
1207     FloatRect overlayRect = view->visibleContentRect();
1208     if (!overlayRect.contains(boundingBox) && !boundingBox.contains(enclosingIntRect(overlayRect)))
1209         overlayRect = view->visibleContentRect();
1210     context.translate(-overlayRect.x(), -overlayRect.y());
1211
1212     // RenderSVGRoot should be highlighted through the isBox() code path, all other SVG elements should just dump their absoluteQuads().
1213 #if ENABLE(SVG)
1214     bool isSVGRenderer = renderer->node() && renderer->node()->isSVGElement() && !renderer->isSVGRoot();
1215 #else
1216     bool isSVGRenderer = false;
1217 #endif
1218
1219     if (renderer->isBox() && !isSVGRenderer) {
1220         RenderBox* renderBox = toRenderBox(renderer);
1221
1222         IntRect contentBox = renderBox->contentBoxRect();
1223
1224         IntRect paddingBox(contentBox.x() - renderBox->paddingLeft(), contentBox.y() - renderBox->paddingTop(),
1225                            contentBox.width() + renderBox->paddingLeft() + renderBox->paddingRight(), contentBox.height() + renderBox->paddingTop() + renderBox->paddingBottom());
1226         IntRect borderBox(paddingBox.x() - renderBox->borderLeft(), paddingBox.y() - renderBox->borderTop(),
1227                           paddingBox.width() + renderBox->borderLeft() + renderBox->borderRight(), paddingBox.height() + renderBox->borderTop() + renderBox->borderBottom());
1228         IntRect marginBox(borderBox.x() - renderBox->marginLeft(), borderBox.y() - renderBox->marginTop(),
1229                           borderBox.width() + renderBox->marginLeft() + renderBox->marginRight(), borderBox.height() + renderBox->marginTop() + renderBox->marginBottom());
1230
1231         titleReferenceBox = marginBox;
1232         titleReferenceBox.move(mainFrameOffset);
1233         titleReferenceBox.move(boundingBox.x(), boundingBox.y());
1234
1235         FloatQuad absContentQuad = renderBox->localToAbsoluteQuad(FloatRect(contentBox));
1236         FloatQuad absPaddingQuad = renderBox->localToAbsoluteQuad(FloatRect(paddingBox));
1237         FloatQuad absBorderQuad = renderBox->localToAbsoluteQuad(FloatRect(borderBox));
1238         FloatQuad absMarginQuad = renderBox->localToAbsoluteQuad(FloatRect(marginBox));
1239
1240         absContentQuad.move(mainFrameOffset);
1241         absPaddingQuad.move(mainFrameOffset);
1242         absBorderQuad.move(mainFrameOffset);
1243         absMarginQuad.move(mainFrameOffset);
1244
1245         drawHighlightForBox(context, absContentQuad, absPaddingQuad, absBorderQuad, absMarginQuad);
1246     } else if (renderer->isRenderInline() || isSVGRenderer) {
1247         // FIXME: We should show margins/padding/border for inlines.
1248         Vector<FloatQuad> lineBoxQuads;
1249         renderer->absoluteQuads(lineBoxQuads);
1250         for (unsigned i = 0; i < lineBoxQuads.size(); ++i)
1251             lineBoxQuads[i] += mainFrameOffset;
1252
1253         drawHighlightForLineBoxesOrSVGRenderer(context, lineBoxQuads);
1254     }
1255
1256     // Draw node title if necessary.
1257
1258     if (!m_highlightedNode->isElementNode())
1259         return;
1260
1261     WebCore::Settings* settings = containingFrame->settings();
1262     drawElementTitle(context, titleReferenceBox, overlayRect, settings);
1263 }
1264
1265 void InspectorController::drawElementTitle(GraphicsContext& context, const IntRect& boundingBox, const FloatRect& overlayRect, WebCore::Settings* settings) const
1266 {
1267     static const int rectInflatePx = 4;
1268     static const int fontHeightPx = 12;
1269     static const int borderWidthPx = 1;
1270     static const Color tooltipBackgroundColor(255, 255, 194, 255);
1271     static const Color tooltipBorderColor(Color::black);
1272     static const Color tooltipFontColor(Color::black);
1273
1274     Element* element = static_cast<Element*>(m_highlightedNode.get());
1275     bool isXHTML = element->document()->isXHTMLDocument();
1276     String nodeTitle = isXHTML ? element->nodeName() : element->nodeName().lower();
1277     const AtomicString& idValue = element->getIdAttribute();
1278     if (!idValue.isNull() && !idValue.isEmpty()) {
1279         nodeTitle += "#";
1280         nodeTitle += idValue;
1281     }
1282     if (element->hasClass() && element->isStyledElement()) {
1283         const SpaceSplitString& classNamesString = static_cast<StyledElement*>(element)->classNames();
1284         size_t classNameCount = classNamesString.size();
1285         if (classNameCount) {
1286             HashSet<AtomicString> usedClassNames;
1287             for (size_t i = 0; i < classNameCount; ++i) {
1288                 const AtomicString& className = classNamesString[i];
1289                 if (usedClassNames.contains(className))
1290                     continue;
1291                 usedClassNames.add(className);
1292                 nodeTitle += ".";
1293                 nodeTitle += className;
1294             }
1295         }
1296     }
1297
1298     Element* highlightedElement = m_highlightedNode->isElementNode() ? static_cast<Element*>(m_highlightedNode.get()) : 0;
1299     nodeTitle += " [";
1300     nodeTitle += String::number(highlightedElement ? highlightedElement->offsetWidth() : boundingBox.width());
1301     nodeTitle.append(static_cast<UChar>(0x00D7)); // &times;
1302     nodeTitle += String::number(highlightedElement ? highlightedElement->offsetHeight() : boundingBox.height());
1303     nodeTitle += "]";
1304
1305     FontDescription desc;
1306     FontFamily family;
1307     family.setFamily(settings->fixedFontFamily());
1308     desc.setFamily(family);
1309     desc.setComputedSize(fontHeightPx);
1310     Font font = Font(desc, 0, 0);
1311     font.update(0);
1312
1313     TextRun nodeTitleRun(nodeTitle);
1314     IntPoint titleBasePoint = boundingBox.bottomLeft();
1315     titleBasePoint.move(rectInflatePx, rectInflatePx);
1316     IntRect titleRect = enclosingIntRect(font.selectionRectForText(nodeTitleRun, titleBasePoint, fontHeightPx));
1317     titleRect.inflate(rectInflatePx);
1318
1319     // The initial offsets needed to compensate for a 1px-thick border stroke (which is not a part of the rectangle).
1320     int dx = -borderWidthPx;
1321     int dy = borderWidthPx;
1322
1323     // If the tip sticks beyond the right of overlayRect, right-align the tip with the said boundary.
1324     if (titleRect.right() > overlayRect.right())
1325         dx = overlayRect.right() - titleRect.right();
1326
1327     // If the tip sticks beyond the left of overlayRect, left-align the tip with the said boundary.
1328     if (titleRect.x() + dx < overlayRect.x())
1329         dx = overlayRect.x() - titleRect.x() - borderWidthPx;
1330
1331     // If the tip sticks beyond the bottom of overlayRect, show the tip at top of bounding box.
1332     if (titleRect.bottom() > overlayRect.bottom()) {
1333         dy = boundingBox.y() - titleRect.bottom() - borderWidthPx;
1334         // If the tip still sticks beyond the bottom of overlayRect, bottom-align the tip with the said boundary.
1335         if (titleRect.bottom() + dy > overlayRect.bottom())
1336             dy = overlayRect.bottom() - titleRect.bottom();
1337     }
1338
1339     // If the tip sticks beyond the top of overlayRect, show the tip at top of overlayRect.
1340     if (titleRect.y() + dy < overlayRect.y())
1341         dy = overlayRect.y() - titleRect.y() + borderWidthPx;
1342
1343     titleRect.move(dx, dy);
1344     context.setStrokeColor(tooltipBorderColor, ColorSpaceDeviceRGB);
1345     context.setStrokeThickness(borderWidthPx);
1346     context.setFillColor(tooltipBackgroundColor, ColorSpaceDeviceRGB);
1347     context.drawRect(titleRect);
1348     context.setFillColor(tooltipFontColor, ColorSpaceDeviceRGB);
1349     context.drawText(font, nodeTitleRun, IntPoint(titleRect.x() + rectInflatePx, titleRect.y() + font.height()));
1350 }
1351
1352 void InspectorController::openInInspectedWindow(const String& url)
1353 {
1354     Frame* mainFrame = m_inspectedPage->mainFrame();
1355
1356     FrameLoadRequest request(mainFrame->document()->securityOrigin(), ResourceRequest(), "_blank");
1357
1358     bool created;
1359     WindowFeatures windowFeatures;
1360     Frame* newFrame = WebCore::createWindow(mainFrame, mainFrame, request, windowFeatures, created);
1361     if (!newFrame)
1362         return;
1363
1364     UserGestureIndicator indicator(DefinitelyProcessingUserGesture);
1365     newFrame->loader()->setOpener(mainFrame);
1366     newFrame->page()->setOpenedByDOM();
1367     newFrame->loader()->changeLocation(mainFrame->document()->securityOrigin(), newFrame->loader()->completeURL(url), "", false, false);
1368 }
1369
1370 void InspectorController::addScriptToEvaluateOnLoad(const String& source)
1371 {
1372     m_scriptsToEvaluateOnLoad.append(source);
1373 }
1374
1375 void InspectorController::removeAllScriptsToEvaluateOnLoad()
1376 {
1377     m_scriptsToEvaluateOnLoad.clear();
1378 }
1379
1380 void InspectorController::setInspectorExtensionAPI(const String& source)
1381 {
1382     m_inspectorExtensionAPI = source;
1383 }
1384
1385 KURL InspectorController::inspectedURL() const
1386 {
1387     return m_inspectedPage->mainFrame()->loader()->url();
1388 }
1389
1390 void InspectorController::reloadPage()
1391 {
1392     // FIXME: Why do we set the user gesture indicator here?
1393     UserGestureIndicator indicator(DefinitelyProcessingUserGesture);
1394     m_inspectedPage->mainFrame()->navigationScheduler()->scheduleRefresh();
1395 }
1396
1397 void InspectorController::setExtraHeaders(PassRefPtr<InspectorObject> headers)
1398 {
1399     m_extraHeaders = adoptPtr(new HTTPHeaderMap());
1400     InspectorObject::const_iterator end = headers->end();
1401     for (InspectorObject::const_iterator it = headers->begin(); it != end; ++it) {
1402         String value;
1403         if (!it->second->asString(&value))
1404             continue;
1405         m_extraHeaders->add(it->first, value);
1406     }
1407 }
1408
1409 } // namespace WebCore
1410
1411 #endif // ENABLE(INSPECTOR)