fbe9aa6e826f8ea88f3c9312928990a787e6e83c
[WebKit-https.git] / Source / WebKit / chromium / src / ChromiumBridge.cpp
1 /*
2  * Copyright (C) 2009 Google Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
8  *     * Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *     * Redistributions in binary form must reproduce the above
11  * copyright notice, this list of conditions and the following disclaimer
12  * in the documentation and/or other materials provided with the
13  * distribution.
14  *     * Neither the name of Google Inc. nor the names of its
15  * contributors may be used to endorse or promote products derived from
16  * this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #include "config.h"
32 #include "ChromiumBridge.h"
33
34 #include <googleurl/src/url_util.h>
35
36 #include "Chrome.h"
37 #include "ChromeClientImpl.h"
38 #include "WebAudioBus.h"
39 #include "WebClipboard.h"
40 #include "WebCookie.h"
41 #include "WebCookieJar.h"
42 #include "WebData.h"
43 #include "WebDragData.h"
44 #include "WebFileUtilities.h"
45 #include "WebFrameClient.h"
46 #include "WebFrameImpl.h"
47 #include "WebIDBKey.h"
48 #include "WebImage.h"
49 #include "WebKit.h"
50 #include "WebKitClient.h"
51 #include "WebMimeRegistry.h"
52 #include "WebPluginContainerImpl.h"
53 #include "WebPluginListBuilderImpl.h"
54 #include "WebSandboxSupport.h"
55 #include "WebSerializedScriptValue.h"
56 #include "WebScreenInfo.h"
57 #include "WebString.h"
58 #include "WebURL.h"
59 #include "WebVector.h"
60 #include "WebViewClient.h"
61 #include "WebViewImpl.h"
62 #include "WebWorkerClientImpl.h"
63
64 #if PLATFORM(CG)
65 #include <CoreGraphics/CGContext.h>
66 #endif
67
68 #if OS(WINDOWS)
69 #include "WebRect.h"
70 #include "win/WebThemeEngine.h"
71 #endif
72
73 #if OS(LINUX) || OS(FREEBSD)
74 #include "linux/WebThemeEngine.h"
75 #include "WebFontInfo.h"
76 #include "WebFontRenderStyle.h"
77 #endif
78
79 #if OS(DARWIN)
80 #include "mac/WebThemeEngine.h"
81 #endif
82
83 #if WEBKIT_USING_SKIA
84 #include "NativeImageSkia.h"
85 #endif
86
87 #include "BitmapImage.h"
88 #include "Cookie.h"
89 #include "FrameView.h"
90 #include "GraphicsContext.h"
91 #include "IDBFactoryBackendProxy.h"
92 #include "KURL.h"
93 #include "NotImplemented.h"
94 #include "PlatformContextSkia.h"
95 #include "PluginData.h"
96 #include "SharedBuffer.h"
97
98 #include "Worker.h"
99 #include "WorkerContextProxy.h"
100 #include <wtf/Assertions.h>
101
102 // We are part of the WebKit implementation.
103 using namespace WebKit;
104
105 namespace WebCore {
106
107 static ChromeClientImpl* toChromeClientImpl(Widget* widget)
108 {
109     if (!widget)
110         return 0;
111
112     FrameView* view;
113     if (widget->isFrameView())
114         view = static_cast<FrameView*>(widget);
115     else if (widget->parent() && widget->parent()->isFrameView())
116         view = static_cast<FrameView*>(widget->parent());
117     else
118         return 0;
119
120     Page* page = view->frame() ? view->frame()->page() : 0;
121     if (!page)
122         return 0;
123
124     return static_cast<ChromeClientImpl*>(page->chrome()->client());
125 }
126
127 static WebWidgetClient* toWebWidgetClient(Widget* widget)
128 {
129     ChromeClientImpl* chromeClientImpl = toChromeClientImpl(widget);
130     if (!chromeClientImpl || !chromeClientImpl->webView())
131         return 0;
132     return chromeClientImpl->webView()->client();
133 }
134
135 static WebCookieJar* getCookieJar(const Document* document)
136 {
137     WebFrameImpl* frameImpl = WebFrameImpl::fromFrame(document->frame());
138     if (!frameImpl || !frameImpl->client())
139         return 0;
140     WebCookieJar* cookieJar = frameImpl->client()->cookieJar(frameImpl);
141     if (!cookieJar)
142         cookieJar = webKitClient()->cookieJar();
143     return cookieJar;
144 }
145
146 // Cache ----------------------------------------------------------------------
147
148 void ChromiumBridge::cacheMetadata(const KURL& url, double responseTime, const Vector<char>& data)
149 {
150     webKitClient()->cacheMetadata(url, responseTime, data.data(), data.size());
151 }
152
153 // Clipboard ------------------------------------------------------------------
154
155 bool ChromiumBridge::clipboardIsFormatAvailable(
156     PasteboardPrivate::ClipboardFormat format,
157     PasteboardPrivate::ClipboardBuffer buffer)
158 {
159     return webKitClient()->clipboard()->isFormatAvailable(
160         static_cast<WebClipboard::Format>(format),
161         static_cast<WebClipboard::Buffer>(buffer));
162 }
163
164 String ChromiumBridge::clipboardReadPlainText(
165     PasteboardPrivate::ClipboardBuffer buffer)
166 {
167     return webKitClient()->clipboard()->readPlainText(
168         static_cast<WebClipboard::Buffer>(buffer));
169 }
170
171 void ChromiumBridge::clipboardReadHTML(
172     PasteboardPrivate::ClipboardBuffer buffer,
173     String* htmlText, KURL* sourceURL)
174 {
175     WebURL url;
176     *htmlText = webKitClient()->clipboard()->readHTML(
177         static_cast<WebClipboard::Buffer>(buffer), &url);
178     *sourceURL = url;
179 }
180
181 void ChromiumBridge::clipboardWriteSelection(const String& htmlText,
182                                              const KURL& sourceURL,
183                                              const String& plainText,
184                                              bool writeSmartPaste)
185 {
186     webKitClient()->clipboard()->writeHTML(
187         htmlText, sourceURL, plainText, writeSmartPaste);
188 }
189
190 void ChromiumBridge::clipboardWritePlainText(const String& plainText)
191 {
192     webKitClient()->clipboard()->writePlainText(plainText);
193 }
194
195 void ChromiumBridge::clipboardWriteURL(const KURL& url, const String& title)
196 {
197     webKitClient()->clipboard()->writeURL(url, title);
198 }
199
200 void ChromiumBridge::clipboardWriteImage(NativeImagePtr image,
201                                          const KURL& sourceURL,
202                                          const String& title)
203 {
204 #if WEBKIT_USING_SKIA
205     WebImage webImage(*image);
206 #else
207     WebImage webImage(image);
208 #endif
209     webKitClient()->clipboard()->writeImage(webImage, sourceURL, title);
210 }
211
212 void ChromiumBridge::clipboardWriteData(const String& type,
213                                         const String& data,
214                                         const String& metadata)
215 {
216     webKitClient()->clipboard()->writeData(type, data, metadata);
217 }
218
219 HashSet<String> ChromiumBridge::clipboardReadAvailableTypes(
220     PasteboardPrivate::ClipboardBuffer buffer, bool* containsFilenames)
221 {
222     WebVector<WebString> result = webKitClient()->clipboard()->readAvailableTypes(
223         static_cast<WebClipboard::Buffer>(buffer), containsFilenames);
224     HashSet<String> types;
225     for (size_t i = 0; i < result.size(); ++i)
226         types.add(result[i]);
227     return types;
228 }
229
230 bool ChromiumBridge::clipboardReadData(PasteboardPrivate::ClipboardBuffer buffer,
231                                        const String& type, String& data, String& metadata)
232 {
233     WebString resultData;
234     WebString resultMetadata;
235     bool succeeded = webKitClient()->clipboard()->readData(
236         static_cast<WebClipboard::Buffer>(buffer), type, &resultData, &resultMetadata);
237     if (succeeded) {
238         data = resultData;
239         metadata = resultMetadata;
240     }
241     return succeeded;
242 }
243
244 Vector<String> ChromiumBridge::clipboardReadFilenames(PasteboardPrivate::ClipboardBuffer buffer)
245 {
246     WebVector<WebString> result = webKitClient()->clipboard()->readFilenames(
247         static_cast<WebClipboard::Buffer>(buffer));
248     Vector<String> convertedResult;
249     for (size_t i = 0; i < result.size(); ++i)
250         convertedResult.append(result[i]);
251     return convertedResult;
252 }
253
254 // Cookies --------------------------------------------------------------------
255
256 void ChromiumBridge::setCookies(const Document* document, const KURL& url,
257                                 const String& value)
258 {
259     WebCookieJar* cookieJar = getCookieJar(document);
260     if (cookieJar)
261         cookieJar->setCookie(url, document->firstPartyForCookies(), value);
262 }
263
264 String ChromiumBridge::cookies(const Document* document, const KURL& url)
265 {
266     String result;
267     WebCookieJar* cookieJar = getCookieJar(document);
268     if (cookieJar)
269         result = cookieJar->cookies(url, document->firstPartyForCookies());
270     return result;
271 }
272
273 String ChromiumBridge::cookieRequestHeaderFieldValue(const Document* document,
274                                                      const KURL& url)
275 {
276     String result;
277     WebCookieJar* cookieJar = getCookieJar(document);
278     if (cookieJar)
279         result = cookieJar->cookieRequestHeaderFieldValue(url, document->firstPartyForCookies());
280     return result;
281 }
282
283 bool ChromiumBridge::rawCookies(const Document* document, const KURL& url, Vector<Cookie>& rawCookies)
284 {
285     rawCookies.clear();
286     WebVector<WebCookie> webCookies;
287
288     WebCookieJar* cookieJar = getCookieJar(document);
289     if (cookieJar)
290         cookieJar->rawCookies(url, document->firstPartyForCookies(), webCookies);
291
292     for (unsigned i = 0; i < webCookies.size(); ++i) {
293         const WebCookie& webCookie = webCookies[i];
294         Cookie cookie(webCookie.name,
295                       webCookie.value,
296                       webCookie.domain,
297                       webCookie.path,
298                       webCookie.expires,
299                       webCookie.httpOnly,
300                       webCookie.secure,
301                       webCookie.session);
302         rawCookies.append(cookie);
303     }
304     return true;
305 }
306
307 void ChromiumBridge::deleteCookie(const Document* document, const KURL& url, const String& cookieName)
308 {
309     WebCookieJar* cookieJar = getCookieJar(document);
310     if (cookieJar)
311         cookieJar->deleteCookie(url, cookieName);
312 }
313
314 bool ChromiumBridge::cookiesEnabled(const Document* document)
315 {
316     bool result = false;
317     WebCookieJar* cookieJar = getCookieJar(document);
318     if (cookieJar)
319         result = cookieJar->cookiesEnabled(document->cookieURL(), document->firstPartyForCookies());
320     return result;
321 }
322
323 // DNS ------------------------------------------------------------------------
324
325 void ChromiumBridge::prefetchDNS(const String& hostname)
326 {
327     webKitClient()->prefetchHostName(hostname);
328 }
329
330 // File ------------------------------------------------------------------------
331
332 bool ChromiumBridge::fileExists(const String& path)
333 {
334     return webKitClient()->fileUtilities()->fileExists(path);
335 }
336
337 bool ChromiumBridge::deleteFile(const String& path)
338 {
339     return webKitClient()->fileUtilities()->deleteFile(path);
340 }
341
342 bool ChromiumBridge::deleteEmptyDirectory(const String& path)
343 {
344     return webKitClient()->fileUtilities()->deleteEmptyDirectory(path);
345 }
346
347 bool ChromiumBridge::getFileSize(const String& path, long long& result)
348 {
349     return webKitClient()->fileUtilities()->getFileSize(path, result);
350 }
351
352 void ChromiumBridge::revealFolderInOS(const String& path)
353 {
354     webKitClient()->fileUtilities()->revealFolderInOS(path);
355 }
356
357 bool ChromiumBridge::getFileModificationTime(const String& path, time_t& result)
358 {
359     double modificationTime;
360     if (!webKitClient()->fileUtilities()->getFileModificationTime(path, modificationTime))
361         return false;
362     result = static_cast<time_t>(modificationTime);
363     return true;
364 }
365
366 String ChromiumBridge::directoryName(const String& path)
367 {
368     return webKitClient()->fileUtilities()->directoryName(path);
369 }
370
371 String ChromiumBridge::pathByAppendingComponent(const String& path, const String& component)
372 {
373     return webKitClient()->fileUtilities()->pathByAppendingComponent(path, component);
374 }
375
376 bool ChromiumBridge::makeAllDirectories(const String& path)
377 {
378     return webKitClient()->fileUtilities()->makeAllDirectories(path);
379 }
380
381 String ChromiumBridge::getAbsolutePath(const String& path)
382 {
383     return webKitClient()->fileUtilities()->getAbsolutePath(path);
384 }
385
386 bool ChromiumBridge::isDirectory(const String& path)
387 {
388     return webKitClient()->fileUtilities()->isDirectory(path);
389 }
390
391 KURL ChromiumBridge::filePathToURL(const String& path)
392 {
393     return webKitClient()->fileUtilities()->filePathToURL(path);
394 }
395
396 PlatformFileHandle ChromiumBridge::openFile(const String& path, FileOpenMode mode)
397 {
398     return webKitClient()->fileUtilities()->openFile(path, mode);
399 }
400
401 void ChromiumBridge::closeFile(PlatformFileHandle& handle)
402 {
403     webKitClient()->fileUtilities()->closeFile(handle);
404 }
405
406 long long ChromiumBridge::seekFile(PlatformFileHandle handle, long long offset, FileSeekOrigin origin)
407 {
408     return webKitClient()->fileUtilities()->seekFile(handle, offset, origin);
409 }
410
411 bool ChromiumBridge::truncateFile(PlatformFileHandle handle, long long offset)
412 {
413     return webKitClient()->fileUtilities()->truncateFile(handle, offset);
414 }
415
416 int ChromiumBridge::readFromFile(PlatformFileHandle handle, char* data, int length)
417 {
418     return webKitClient()->fileUtilities()->readFromFile(handle, data, length);
419 }
420
421 int ChromiumBridge::writeToFile(PlatformFileHandle handle, const char* data, int length)
422 {
423     return webKitClient()->fileUtilities()->writeToFile(handle, data, length);
424 }
425
426 // Font -----------------------------------------------------------------------
427
428 #if OS(WINDOWS)
429 bool ChromiumBridge::ensureFontLoaded(HFONT font)
430 {
431     WebSandboxSupport* ss = webKitClient()->sandboxSupport();
432
433     // if there is no sandbox, then we can assume the font
434     // was able to be loaded successfully already
435     return ss ? ss->ensureFontLoaded(font) : true;
436 }
437 #endif
438
439 #if OS(LINUX) || OS(FREEBSD)
440 String ChromiumBridge::getFontFamilyForCharacters(const UChar* characters, size_t numCharacters)
441 {
442     if (webKitClient()->sandboxSupport())
443         return webKitClient()->sandboxSupport()->getFontFamilyForCharacters(characters, numCharacters);
444
445     WebCString family = WebFontInfo::familyForChars(characters, numCharacters);
446     if (family.data())
447         return WebString::fromUTF8(family.data());
448
449     return WebString();
450 }
451
452 void ChromiumBridge::getRenderStyleForStrike(const char* font, int sizeAndStyle, FontRenderStyle* result)
453 {
454     WebFontRenderStyle style;
455
456     if (webKitClient()->sandboxSupport())
457         webKitClient()->sandboxSupport()->getRenderStyleForStrike(font, sizeAndStyle, &style);
458     else
459         WebFontInfo::renderStyleForStrike(font, sizeAndStyle, &style);
460
461     style.toFontRenderStyle(result);
462 }
463 #endif
464
465 #if OS(DARWIN)
466 bool ChromiumBridge::loadFont(NSFont* srcFont, ATSFontContainerRef* out)
467 {
468     WebSandboxSupport* ss = webKitClient()->sandboxSupport();
469     if (ss)
470         return ss->loadFont(srcFont, out);
471
472     // This function should only be called in response to an error loading a
473     // font due to being blocked by the sandbox.
474     // This by definition shouldn't happen if there is no sandbox support.
475     ASSERT_NOT_REACHED();
476     *out = 0;
477     return false;
478 }
479 #endif
480
481 // Databases ------------------------------------------------------------------
482
483 PlatformFileHandle ChromiumBridge::databaseOpenFile(const String& vfsFileName, int desiredFlags)
484 {
485     return webKitClient()->databaseOpenFile(WebString(vfsFileName), desiredFlags);
486 }
487
488 int ChromiumBridge::databaseDeleteFile(const String& vfsFileName, bool syncDir)
489 {
490     return webKitClient()->databaseDeleteFile(WebString(vfsFileName), syncDir);
491 }
492
493 long ChromiumBridge::databaseGetFileAttributes(const String& vfsFileName)
494 {
495     return webKitClient()->databaseGetFileAttributes(WebString(vfsFileName));
496 }
497
498 long long ChromiumBridge::databaseGetFileSize(const String& vfsFileName)
499 {
500     return webKitClient()->databaseGetFileSize(WebString(vfsFileName));
501 }
502
503 // Indexed Database -----------------------------------------------------------
504
505 PassRefPtr<IDBFactoryBackendInterface> ChromiumBridge::idbFactory()
506 {
507     // There's no reason why we need to allocate a new proxy each time, but
508     // there's also no strong reason not to.
509     return IDBFactoryBackendProxy::create();
510 }
511
512 void ChromiumBridge::idbShutdown()
513 {
514     // In the browser process, this shuts down the utility process. In the renderer process, it does nothing.
515     webKitClient()->idbShutdown();
516 }
517
518 void ChromiumBridge::createIDBKeysFromSerializedValuesAndKeyPath(const Vector<RefPtr<SerializedScriptValue> >& values, const String& keyPath, Vector<RefPtr<IDBKey> >& keys)
519 {
520     WebVector<WebSerializedScriptValue> webValues = values;
521     WebVector<WebIDBKey> webKeys;
522     webKitClient()->createIDBKeysFromSerializedValuesAndKeyPath(webValues, WebString(keyPath), webKeys);
523
524     size_t webKeysSize = webKeys.size();
525     keys.reserveCapacity(webKeysSize);
526     for (size_t i = 0; i < webKeysSize; ++i)
527         keys.append(PassRefPtr<IDBKey>(webKeys[i]));
528 }
529
530 // Keygen ---------------------------------------------------------------------
531
532 String ChromiumBridge::signedPublicKeyAndChallengeString(
533     unsigned keySizeIndex, const String& challenge, const KURL& url)
534 {
535     return webKitClient()->signedPublicKeyAndChallengeString(keySizeIndex,
536                                                              WebString(challenge),
537                                                              WebURL(url));
538 }
539
540 // Language -------------------------------------------------------------------
541
542 String ChromiumBridge::computedDefaultLanguage()
543 {
544     return webKitClient()->defaultLocale();
545 }
546
547 // LayoutTestMode -------------------------------------------------------------
548
549 bool ChromiumBridge::layoutTestMode()
550 {
551     return WebKit::layoutTestMode();
552 }
553
554 // MimeType -------------------------------------------------------------------
555
556 bool ChromiumBridge::isSupportedImageMIMEType(const String& mimeType)
557 {
558     return webKitClient()->mimeRegistry()->supportsImageMIMEType(mimeType)
559         != WebMimeRegistry::IsNotSupported;
560 }
561
562 bool ChromiumBridge::isSupportedJavaScriptMIMEType(const String& mimeType)
563 {
564     return webKitClient()->mimeRegistry()->supportsJavaScriptMIMEType(mimeType)
565         != WebMimeRegistry::IsNotSupported;
566 }
567
568 bool ChromiumBridge::isSupportedNonImageMIMEType(const String& mimeType)
569 {
570     return webKitClient()->mimeRegistry()->supportsNonImageMIMEType(mimeType)
571         != WebMimeRegistry::IsNotSupported;
572 }
573
574 String ChromiumBridge::mimeTypeForExtension(const String& extension)
575 {
576     return webKitClient()->mimeRegistry()->mimeTypeForExtension(extension);
577 }
578
579 String ChromiumBridge::mimeTypeFromFile(const String& path)
580 {
581     return webKitClient()->mimeRegistry()->mimeTypeFromFile(path);
582 }
583
584 String ChromiumBridge::preferredExtensionForMIMEType(const String& mimeType)
585 {
586     return webKitClient()->mimeRegistry()->preferredExtensionForMIMEType(mimeType);
587 }
588
589 // Plugin ---------------------------------------------------------------------
590
591 bool ChromiumBridge::plugins(bool refresh, Vector<PluginInfo>* results)
592 {
593     WebPluginListBuilderImpl builder(results);
594     webKitClient()->getPluginList(refresh, &builder);
595     return true;  // FIXME: There is no need for this function to return a value.
596 }
597
598 NPObject* ChromiumBridge::pluginScriptableObject(Widget* widget)
599 {
600     if (!widget || !widget->isPluginContainer())
601         return 0;
602
603     return static_cast<WebPluginContainerImpl*>(widget)->scriptableObject();
604 }
605
606 // Resources ------------------------------------------------------------------
607
608 PassRefPtr<Image> ChromiumBridge::loadPlatformImageResource(const char* name)
609 {
610     const WebData& resource = webKitClient()->loadResource(name);
611     if (resource.isEmpty())
612         return Image::nullImage();
613
614     RefPtr<Image> image = BitmapImage::create();
615     image->setData(resource, true);
616     return image;
617 }
618
619 #if ENABLE(WEB_AUDIO)
620
621 PassOwnPtr<AudioBus> ChromiumBridge::loadPlatformAudioResource(const char* name, double sampleRate)
622 {
623     const WebData& resource = webKitClient()->loadResource(name);
624     if (resource.isEmpty())
625         return 0;
626     
627     return decodeAudioFileData(resource.data(), resource.size(), sampleRate);
628 }
629
630 PassOwnPtr<AudioBus> ChromiumBridge::decodeAudioFileData(const char* data, size_t size, double sampleRate)
631 {
632     WebAudioBus webAudioBus;
633     if (webKitClient()->loadAudioResource(&webAudioBus, data, size, sampleRate))
634         return webAudioBus.release();
635     return 0;
636 }
637
638 #endif // ENABLE(WEB_AUDIO)
639
640 // Sandbox --------------------------------------------------------------------
641
642 bool ChromiumBridge::sandboxEnabled()
643 {
644     return webKitClient()->sandboxEnabled();
645 }
646
647 // SharedTimers ---------------------------------------------------------------
648
649 void ChromiumBridge::setSharedTimerFiredFunction(void (*func)())
650 {
651     webKitClient()->setSharedTimerFiredFunction(func);
652 }
653
654 void ChromiumBridge::setSharedTimerFireTime(double fireTime)
655 {
656     webKitClient()->setSharedTimerFireTime(fireTime);
657 }
658
659 void ChromiumBridge::stopSharedTimer()
660 {
661     webKitClient()->stopSharedTimer();
662 }
663
664 // StatsCounters --------------------------------------------------------------
665
666 void ChromiumBridge::decrementStatsCounter(const char* name)
667 {
668     webKitClient()->decrementStatsCounter(name);
669 }
670
671 void ChromiumBridge::incrementStatsCounter(const char* name)
672 {
673     webKitClient()->incrementStatsCounter(name);
674 }
675
676 void ChromiumBridge::histogramCustomCounts(const char* name, int sample, int min, int max, int bucketCount)
677 {
678     webKitClient()->histogramCustomCounts(name, sample, min, max, bucketCount);
679 }
680
681 void ChromiumBridge::histogramEnumeration(const char* name, int sample, int boundaryValue)
682 {
683     webKitClient()->histogramEnumeration(name, sample, boundaryValue);
684 }
685
686 // Sudden Termination ---------------------------------------------------------
687
688 void ChromiumBridge::suddenTerminationChanged(bool enabled)
689 {
690     webKitClient()->suddenTerminationChanged(enabled);
691 }
692
693 // SystemTime -----------------------------------------------------------------
694
695 double ChromiumBridge::currentTime()
696 {
697     return webKitClient()->currentTime();
698 }
699
700 // Theming --------------------------------------------------------------------
701
702 #if OS(WINDOWS)
703
704 void ChromiumBridge::paintButton(
705     GraphicsContext* gc, int part, int state, int classicState,
706     const IntRect& rect)
707 {
708     webKitClient()->themeEngine()->paintButton(
709         gc->platformContext()->canvas(), part, state, classicState, rect);
710 }
711
712 void ChromiumBridge::paintMenuList(
713     GraphicsContext* gc, int part, int state, int classicState,
714     const IntRect& rect)
715 {
716     webKitClient()->themeEngine()->paintMenuList(
717         gc->platformContext()->canvas(), part, state, classicState, rect);
718 }
719
720 void ChromiumBridge::paintScrollbarArrow(
721     GraphicsContext* gc, int state, int classicState,
722     const IntRect& rect)
723 {
724     webKitClient()->themeEngine()->paintScrollbarArrow(
725         gc->platformContext()->canvas(), state, classicState, rect);
726 }
727
728 void ChromiumBridge::paintScrollbarThumb(
729     GraphicsContext* gc, int part, int state, int classicState,
730     const IntRect& rect)
731 {
732     webKitClient()->themeEngine()->paintScrollbarThumb(
733         gc->platformContext()->canvas(), part, state, classicState, rect);
734 }
735
736 void ChromiumBridge::paintScrollbarTrack(
737     GraphicsContext* gc, int part, int state, int classicState,
738     const IntRect& rect, const IntRect& alignRect)
739 {
740     webKitClient()->themeEngine()->paintScrollbarTrack(
741         gc->platformContext()->canvas(), part, state, classicState, rect,
742         alignRect);
743 }
744
745 void ChromiumBridge::paintSpinButton(
746     GraphicsContext* gc, int part, int state, int classicState,
747     const IntRect& rect)
748 {
749     webKitClient()->themeEngine()->paintSpinButton(
750         gc->platformContext()->canvas(), part, state, classicState, rect);
751 }
752
753 void ChromiumBridge::paintTextField(
754     GraphicsContext* gc, int part, int state, int classicState,
755     const IntRect& rect, const Color& color, bool fillContentArea,
756     bool drawEdges)
757 {
758     // Fallback to white when |color| is invalid.
759     RGBA32 backgroundColor = color.isValid() ? color.rgb() : Color::white;
760
761     webKitClient()->themeEngine()->paintTextField(
762         gc->platformContext()->canvas(), part, state, classicState, rect,
763         backgroundColor, fillContentArea, drawEdges);
764 }
765
766 void ChromiumBridge::paintTrackbar(
767     GraphicsContext* gc, int part, int state, int classicState,
768     const IntRect& rect)
769 {
770     webKitClient()->themeEngine()->paintTrackbar(
771         gc->platformContext()->canvas(), part, state, classicState, rect);
772 }
773
774 void ChromiumBridge::paintProgressBar(
775     GraphicsContext* gc, const IntRect& barRect, const IntRect& valueRect, bool determinate, double animatedSeconds)
776 {
777     webKitClient()->themeEngine()->paintProgressBar(
778         gc->platformContext()->canvas(), barRect, valueRect, determinate, animatedSeconds);
779 }
780
781 #elif OS(LINUX)
782
783 static WebThemeEngine::Part WebThemePart(ChromiumBridge::ThemePart part)
784 {
785     switch (part) {
786     case ChromiumBridge::PartScrollbarDownArrow: return WebThemeEngine::PartScrollbarDownArrow;
787     case ChromiumBridge::PartScrollbarLeftArrow: return WebThemeEngine::PartScrollbarLeftArrow;
788     case ChromiumBridge::PartScrollbarRightArrow: return WebThemeEngine::PartScrollbarRightArrow;
789     case ChromiumBridge::PartScrollbarUpArrow: return WebThemeEngine::PartScrollbarUpArrow;
790     case ChromiumBridge::PartScrollbarHorizontalThumb: return WebThemeEngine::PartScrollbarHorizontalThumb;
791     case ChromiumBridge::PartScrollbarVerticalThumb: return WebThemeEngine::PartScrollbarVerticalThumb;
792     case ChromiumBridge::PartScrollbarHorizontalTrack: return WebThemeEngine::PartScrollbarHorizontalTrack;
793     case ChromiumBridge::PartScrollbarVerticalTrack: return WebThemeEngine::PartScrollbarVerticalTrack;
794     }
795     ASSERT_NOT_REACHED();
796     return WebThemeEngine::PartScrollbarDownArrow;
797 }
798
799 static WebThemeEngine::State WebThemeState(ChromiumBridge::ThemePaintState state)
800 {
801     switch (state) {
802     case ChromiumBridge::StateDisabled: return WebThemeEngine::StateDisabled;
803     case ChromiumBridge::StateHover: return WebThemeEngine::StateHover;
804     case ChromiumBridge::StateNormal: return WebThemeEngine::StateNormal;
805     case ChromiumBridge::StatePressed: return WebThemeEngine::StatePressed;
806     }
807     ASSERT_NOT_REACHED();
808     return WebThemeEngine::StateDisabled;
809 }
810
811 static void GetWebThemeExtraParams(ChromiumBridge::ThemePart part, ChromiumBridge::ThemePaintState state, const ChromiumBridge::ThemePaintExtraParams* extraParams, WebThemeEngine::ExtraParams* webThemeExtraParams)
812 {
813     if (part == ChromiumBridge::PartScrollbarHorizontalTrack || part == ChromiumBridge::PartScrollbarVerticalTrack) {
814         webThemeExtraParams->scrollbarTrack.trackX = extraParams->scrollbarTrack.trackX;
815         webThemeExtraParams->scrollbarTrack.trackY = extraParams->scrollbarTrack.trackY;
816         webThemeExtraParams->scrollbarTrack.trackWidth = extraParams->scrollbarTrack.trackWidth;
817         webThemeExtraParams->scrollbarTrack.trackHeight = extraParams->scrollbarTrack.trackHeight;
818     }
819 }
820
821 IntSize ChromiumBridge::getThemePartSize(ThemePart part)
822 {
823      return webKitClient()->themeEngine()->getSize(WebThemePart(part));
824 }
825
826 void ChromiumBridge::paintThemePart(
827     GraphicsContext* gc, ThemePart part, ThemePaintState state, const IntRect& rect, const ThemePaintExtraParams* extraParams)
828 {
829     WebThemeEngine::ExtraParams webThemeExtraParams;
830     GetWebThemeExtraParams(part, state, extraParams, &webThemeExtraParams);
831     webKitClient()->themeEngine()->paint(
832         gc->platformContext()->canvas(), WebThemePart(part), WebThemeState(state), rect, &webThemeExtraParams);
833 }
834
835 #elif OS(DARWIN)
836
837 void ChromiumBridge::paintScrollbarThumb(
838     GraphicsContext* gc, ThemePaintState state, ThemePaintSize size, const IntRect& rect, const ThemePaintScrollbarInfo& scrollbarInfo)
839 {
840     WebThemeEngine::ScrollbarInfo webThemeScrollbarInfo;
841
842     webThemeScrollbarInfo.orientation = static_cast<WebThemeEngine::ScrollbarOrientation>(scrollbarInfo.orientation);
843     webThemeScrollbarInfo.parent = static_cast<WebThemeEngine::ScrollbarParent>(scrollbarInfo.parent);
844     webThemeScrollbarInfo.maxValue = scrollbarInfo.maxValue;
845     webThemeScrollbarInfo.currentValue = scrollbarInfo.currentValue;
846     webThemeScrollbarInfo.visibleSize = scrollbarInfo.visibleSize;
847     webThemeScrollbarInfo.totalSize = scrollbarInfo.totalSize;
848
849     webKitClient()->themeEngine()->paintScrollbarThumb(
850         gc->platformContext(),
851         static_cast<WebThemeEngine::State>(state),
852         static_cast<WebThemeEngine::Size>(size),
853         rect,
854         webThemeScrollbarInfo);
855 }
856
857 #endif
858
859 // Trace Event ----------------------------------------------------------------
860
861 void ChromiumBridge::traceEventBegin(const char* name, void* id, const char* extra)
862 {
863     webKitClient()->traceEventBegin(name, id, extra);
864 }
865
866 void ChromiumBridge::traceEventEnd(const char* name, void* id, const char* extra)
867 {
868     webKitClient()->traceEventEnd(name, id, extra);
869 }
870
871 // Visited Links --------------------------------------------------------------
872
873 LinkHash ChromiumBridge::visitedLinkHash(const UChar* url, unsigned length)
874 {
875     url_canon::RawCanonOutput<2048> buffer;
876     url_parse::Parsed parsed;
877     if (!url_util::Canonicalize(url, length, 0, &buffer, &parsed))
878         return 0;  // Invalid URLs are unvisited.
879     return webKitClient()->visitedLinkHash(buffer.data(), buffer.length());
880 }
881
882 LinkHash ChromiumBridge::visitedLinkHash(const KURL& base,
883                                          const AtomicString& attributeURL)
884 {
885     // Resolve the relative URL using googleurl and pass the absolute URL up to
886     // the embedder. We could create a GURL object from the base and resolve
887     // the relative URL that way, but calling the lower-level functions
888     // directly saves us the string allocation in most cases.
889     url_canon::RawCanonOutput<2048> buffer;
890     url_parse::Parsed parsed;
891
892 #if USE(GOOGLEURL)
893     const CString& cstr = base.utf8String();
894     const char* data = cstr.data();
895     int length = cstr.length();
896     const url_parse::Parsed& srcParsed = base.parsed();
897 #else
898     // When we're not using GoogleURL, first canonicalize it so we can resolve it
899     // below.
900     url_canon::RawCanonOutput<2048> srcCanon;
901     url_parse::Parsed srcParsed;
902     String str = base.string();
903     if (!url_util::Canonicalize(str.characters(), str.length(), 0, &srcCanon, &srcParsed))
904         return 0;
905     const char* data = srcCanon.data();
906     int length = srcCanon.length();
907 #endif
908
909     if (!url_util::ResolveRelative(data, length, srcParsed, attributeURL.characters(),
910                                    attributeURL.length(), 0, &buffer, &parsed))
911         return 0;  // Invalid resolved URL.
912
913     return webKitClient()->visitedLinkHash(buffer.data(), buffer.length());
914 }
915
916 bool ChromiumBridge::isLinkVisited(LinkHash visitedLinkHash)
917 {
918     return webKitClient()->isLinkVisited(visitedLinkHash);
919 }
920
921 // These are temporary methods that the WebKit layer can use to call to the
922 // Glue layer. Once the Glue layer moves entirely into the WebKit layer, these
923 // methods will be deleted.
924
925 void ChromiumBridge::notifyJSOutOfMemory(Frame* frame)
926 {
927     if (!frame)
928         return;
929
930     WebFrameImpl* webFrame = WebFrameImpl::fromFrame(frame);
931     if (!webFrame->client())
932         return;
933     webFrame->client()->didExhaustMemoryAvailableForScript(webFrame);
934 }
935
936 int ChromiumBridge::memoryUsageMB()
937 {
938     return static_cast<int>(webKitClient()->memoryUsageMB());
939 }
940
941 int ChromiumBridge::actualMemoryUsageMB()
942 {
943     return static_cast<int>(webKitClient()->actualMemoryUsageMB());
944 }
945
946 int ChromiumBridge::screenDepth(Widget* widget)
947 {
948     WebWidgetClient* client = toWebWidgetClient(widget);
949     if (!client)
950         return 0;
951     return client->screenInfo().depth;
952 }
953
954 int ChromiumBridge::screenDepthPerComponent(Widget* widget)
955 {
956     WebWidgetClient* client = toWebWidgetClient(widget);
957     if (!client)
958         return 0;
959     return client->screenInfo().depthPerComponent;
960 }
961
962 bool ChromiumBridge::screenIsMonochrome(Widget* widget)
963 {
964     WebWidgetClient* client = toWebWidgetClient(widget);
965     if (!client)
966         return 0;
967     return client->screenInfo().isMonochrome;
968 }
969
970 IntRect ChromiumBridge::screenRect(Widget* widget)
971 {
972     WebWidgetClient* client = toWebWidgetClient(widget);
973     if (!client)
974         return IntRect();
975     return client->screenInfo().rect;
976 }
977
978 IntRect ChromiumBridge::screenAvailableRect(Widget* widget)
979 {
980     WebWidgetClient* client = toWebWidgetClient(widget);
981     if (!client)
982         return IntRect();
983     return client->screenInfo().availableRect;
984 }
985
986 bool ChromiumBridge::popupsAllowed(NPP npp)
987 {
988     // FIXME: Give the embedder a way to control this.
989     return false;
990 }
991
992 WorkerContextProxy* WorkerContextProxy::create(Worker* worker)
993 {
994     return WebWorkerClientImpl::createWorkerContextProxy(worker);
995 }
996
997 } // namespace WebCore