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