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