diff options
Diffstat (limited to 'Source/WebCore/platform/chromium')
76 files changed, 10630 insertions, 0 deletions
diff --git a/Source/WebCore/platform/chromium/ChromiumBridge.h b/Source/WebCore/platform/chromium/ChromiumBridge.h new file mode 100644 index 0000000..56969ef --- /dev/null +++ b/Source/WebCore/platform/chromium/ChromiumBridge.h @@ -0,0 +1,360 @@ +/* + * Copyright (c) 2010, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef ChromiumBridge_h +#define ChromiumBridge_h + +#if ENABLE(WEB_AUDIO) +#include "AudioBus.h" +#endif + +#include "FileSystem.h" +#include "ImageSource.h" +#include "LinkHash.h" +#include "PassRefPtr.h" +#include "PasteboardPrivate.h" +#include "PluginData.h" + +#include <wtf/Forward.h> +#include <wtf/HashSet.h> +#include <wtf/Vector.h> + +typedef struct NPObject NPObject; +typedef struct _NPP NPP_t; +typedef NPP_t* NPP; + +#if OS(DARWIN) +typedef struct CGFont* CGFontRef; +typedef uintptr_t ATSFontContainerRef; +#ifdef __OBJC__ +@class NSFont; +#else +class NSFont; +#endif +#endif // OS(DARWIN) + +#if OS(WINDOWS) +typedef struct HFONT__* HFONT; +#endif + +namespace WebCore { + + class ClipboardData; + class Color; + class Cursor; + class Document; + class Frame; + class GeolocationServiceBridge; + class GeolocationServiceChromium; + class GraphicsContext; + class Image; + class IDBFactoryBackendInterface; + class IDBKey; + class IntRect; + class KURL; + class SerializedScriptValue; + class Widget; + + struct Cookie; + struct FontRenderStyle; + + // An interface to the embedding layer, which has the ability to answer + // questions about the system and so on... + + class ChromiumBridge { + public: + // Cache -------------------------------------------------------------- + static void cacheMetadata(const KURL& url, double responseTime, const Vector<char>&); + + // Clipboard ---------------------------------------------------------- + static bool clipboardIsFormatAvailable(PasteboardPrivate::ClipboardFormat, PasteboardPrivate::ClipboardBuffer); + + static String clipboardReadPlainText(PasteboardPrivate::ClipboardBuffer); + static void clipboardReadHTML(PasteboardPrivate::ClipboardBuffer, String*, KURL*); + + // Only the clipboardRead functions take a buffer argument because + // Chromium currently uses a different technique to write to alternate + // clipboard buffers. + static void clipboardWriteSelection(const String&, const KURL&, const String&, bool); + static void clipboardWritePlainText(const String&); + static void clipboardWriteURL(const KURL&, const String&); + static void clipboardWriteImage(NativeImagePtr, const KURL&, const String&); + static void clipboardWriteData(const String& type, const String& data, const String& metadata); + + // Interface for handling copy and paste, drag and drop, and selection copy. + static HashSet<String> clipboardReadAvailableTypes(PasteboardPrivate::ClipboardBuffer, bool* containsFilenames); + static bool clipboardReadData(PasteboardPrivate::ClipboardBuffer, const String& type, String& data, String& metadata); + static Vector<String> clipboardReadFilenames(PasteboardPrivate::ClipboardBuffer); + + // Cookies ------------------------------------------------------------ + static void setCookies(const Document*, const KURL&, const String& value); + static String cookies(const Document*, const KURL&); + static String cookieRequestHeaderFieldValue(const Document*, const KURL&); + static bool rawCookies(const Document*, const KURL& url, Vector<Cookie>&); + static void deleteCookie(const Document*, const KURL& url, const String& cookieName); + static bool cookiesEnabled(const Document*); + + // DNS ---------------------------------------------------------------- + static void prefetchDNS(const String& hostname); + + // File --------------------------------------------------------------- + static void revealFolderInOS(const String&); + static bool fileExists(const String&); + static bool deleteFile(const String&); + static bool deleteEmptyDirectory(const String&); + static bool getFileSize(const String&, long long& result); + static bool getFileModificationTime(const String&, time_t& result); + static String directoryName(const String& path); + static String pathByAppendingComponent(const String& path, const String& component); + static bool makeAllDirectories(const String& path); + static String getAbsolutePath(const String&); + static bool isDirectory(const String&); + static KURL filePathToURL(const String&); + static PlatformFileHandle openFile(const String& path, FileOpenMode); + static void closeFile(PlatformFileHandle&); + static long long seekFile(PlatformFileHandle, long long offset, FileSeekOrigin); + static bool truncateFile(PlatformFileHandle, long long offset); + static int readFromFile(PlatformFileHandle, char* data, int length); + static int writeToFile(PlatformFileHandle, const char* data, int length); + + // Font --------------------------------------------------------------- +#if OS(WINDOWS) + static bool ensureFontLoaded(HFONT font); +#endif +#if OS(LINUX) || OS(FREEBSD) + static void getRenderStyleForStrike(const char* family, int sizeAndStyle, FontRenderStyle* result); + static String getFontFamilyForCharacters(const UChar*, size_t numCharacters); +#endif +#if OS(DARWIN) + static bool loadFont(NSFont* srcFont, ATSFontContainerRef* out); +#endif + + // Forms -------------------------------------------------------------- + static void notifyFormStateChanged(const Document*); + +#if !ENABLE(CLIENT_BASED_GEOLOCATION) + // Geolocation -------------------------------------------------------- + static GeolocationServiceBridge* createGeolocationServiceBridge(GeolocationServiceChromium*); +#endif + // Databases ---------------------------------------------------------- + // Returns a handle to the DB file and ooptionally a handle to its containing directory + static PlatformFileHandle databaseOpenFile(const String& vfsFleName, int desiredFlags); + // Returns a SQLite code (SQLITE_OK = 0, on success) + static int databaseDeleteFile(const String& vfsFileName, bool syncDir = false); + // Returns the attributes of the DB file + static long databaseGetFileAttributes(const String& vfsFileName); + // Returns the size of the DB file + static long long databaseGetFileSize(const String& vfsFileName); + + // IndexedDB ---------------------------------------------------------- + static PassRefPtr<IDBFactoryBackendInterface> idbFactory(); + static void idbShutdown(); + // Extracts keyPath from values and returns the corresponding keys. + static void createIDBKeysFromSerializedValuesAndKeyPath(const Vector<RefPtr<SerializedScriptValue> >& values, const String& keyPath, Vector<RefPtr<IDBKey> >& keys); + + // JavaScript --------------------------------------------------------- + static void notifyJSOutOfMemory(Frame*); + static bool allowScriptDespiteSettings(const KURL& documentURL); + + // Keygen ------------------------------------------------------------- + static String signedPublicKeyAndChallengeString(unsigned keySizeIndex, const String& challenge, const KURL& url); + + // Language ----------------------------------------------------------- + static String computedDefaultLanguage(); + + // LayoutTestMode ----------------------------------------------------- + static bool layoutTestMode(); + + // Memory ------------------------------------------------------------- + // Returns the current space allocated for the pagefile, in MB. + // That is committed size for Windows and virtual memory size for POSIX + static int memoryUsageMB(); + + // Same as above, but always returns actual value, without any caches. + static int actualMemoryUsageMB(); + + // MimeType ----------------------------------------------------------- + static bool isSupportedImageMIMEType(const String& mimeType); + static bool isSupportedJavaScriptMIMEType(const String& mimeType); + static bool isSupportedNonImageMIMEType(const String& mimeType); + static String mimeTypeForExtension(const String& fileExtension); + static String mimeTypeFromFile(const String& filePath); + static String preferredExtensionForMIMEType(const String& mimeType); + + // Plugin ------------------------------------------------------------- + static bool plugins(bool refresh, Vector<PluginInfo>*); + static NPObject* pluginScriptableObject(Widget*); + static bool popupsAllowed(NPP); + + // Resources ---------------------------------------------------------- + static PassRefPtr<Image> loadPlatformImageResource(const char* name); + +#if ENABLE(WEB_AUDIO) + static PassOwnPtr<AudioBus> loadPlatformAudioResource(const char* name, double sampleRate); + static PassOwnPtr<AudioBus> decodeAudioFileData(const char* data, size_t size, double sampleRate); +#endif + + // Sandbox ------------------------------------------------------------ + static bool sandboxEnabled(); + + // Screen ------------------------------------------------------------- + static int screenDepth(Widget*); + static int screenDepthPerComponent(Widget*); + static bool screenIsMonochrome(Widget*); + static IntRect screenRect(Widget*); + static IntRect screenAvailableRect(Widget*); + + // SharedTimers ------------------------------------------------------- + static void setSharedTimerFiredFunction(void (*func)()); + static void setSharedTimerFireTime(double fireTime); + static void stopSharedTimer(); + + // StatsCounters ------------------------------------------------------ + static void decrementStatsCounter(const char* name); + static void incrementStatsCounter(const char* name); + static void histogramCustomCounts(const char* name, int sample, int min, int max, int bucketCount); + static void histogramEnumeration(const char* name, int sample, int boundaryValue); + + // Sudden Termination + static void suddenTerminationChanged(bool enabled); + + // SystemTime --------------------------------------------------------- + static double currentTime(); + + // Theming ------------------------------------------------------------ +#if OS(WINDOWS) + static void paintButton( + GraphicsContext*, int part, int state, int classicState, const IntRect&); + static void paintMenuList( + GraphicsContext*, int part, int state, int classicState, const IntRect&); + static void paintScrollbarArrow( + GraphicsContext*, int state, int classicState, const IntRect&); + static void paintScrollbarThumb( + GraphicsContext*, int part, int state, int classicState, const IntRect&); + static void paintScrollbarTrack( + GraphicsContext*, int part, int state, int classicState, const IntRect&, const IntRect& alignRect); + static void paintSpinButton( + GraphicsContext*, int part, int state, int classicState, const IntRect&); + static void paintTextField( + GraphicsContext*, int part, int state, int classicState, const IntRect&, const Color&, bool fillContentArea, bool drawEdges); + static void paintTrackbar( + GraphicsContext*, int part, int state, int classicState, const IntRect&); + static void paintProgressBar( + GraphicsContext*, const IntRect& barRect, const IntRect& valueRect, bool determinate, double animatedSeconds); +#elif OS(LINUX) + // The UI part which is being accessed. + enum ThemePart { + PartScrollbarDownArrow, + PartScrollbarLeftArrow, + PartScrollbarRightArrow, + PartScrollbarUpArrow, + PartScrollbarHorizontalThumb, + PartScrollbarVerticalThumb, + PartScrollbarHorizontalTrack, + PartScrollbarVerticalTrack, + }; + + // The current state of the associated Part. + enum ThemePaintState { + StateDisabled, + StateHover, + StateNormal, + StatePressed, + }; + + struct ScrollbarTrackExtraParams { + // The bounds of the entire track, as opposed to the part being painted. + int trackX; + int trackY; + int trackWidth; + int trackHeight; + }; + + union ThemePaintExtraParams { + ScrollbarTrackExtraParams scrollbarTrack; + }; + + // Gets the size of the given theme part. For variable sized items + // like vertical scrollbar thumbs, the width will be the required width of + // the track while the height will be the minimum height. + static IntSize getThemePartSize(ThemePart); + // Paint the given the given theme part. + static void paintThemePart(GraphicsContext*, ThemePart, ThemePaintState, const IntRect&, const ThemePaintExtraParams*); +#elif OS(DARWIN) + enum ThemePaintState { + StateDisabled, + StateInactive, + StateActive, + StatePressed, + }; + + enum ThemePaintSize { + SizeRegular, + SizeSmall, + }; + + enum ThemePaintScrollbarOrientation { + ScrollbarOrientationHorizontal, + ScrollbarOrientationVertical, + }; + + enum ThemePaintScrollbarParent { + ScrollbarParentScrollView, + ScrollbarParentRenderLayer, + }; + + struct ThemePaintScrollbarInfo { + ThemePaintScrollbarOrientation orientation; + ThemePaintScrollbarParent parent; + int maxValue; + int currentValue; + int visibleSize; + int totalSize; + }; + + static void paintScrollbarThumb(GraphicsContext*, ThemePaintState, ThemePaintSize, const IntRect&, const ThemePaintScrollbarInfo&); +#endif + + // Trace Event -------------------------------------------------------- + static void traceEventBegin(const char* name, void* id, const char* extra); + static void traceEventEnd(const char* name, void* id, const char* extra); + + // Visited links ------------------------------------------------------ + static LinkHash visitedLinkHash(const UChar* url, unsigned length); + static LinkHash visitedLinkHash(const KURL& base, const AtomicString& attributeURL); + static bool isLinkVisited(LinkHash); + + // Widget ------------------------------------------------------------- + static void widgetSetCursor(Widget*, const Cursor&); + }; + +} // namespace WebCore + +#endif diff --git a/Source/WebCore/platform/chromium/ChromiumDataObject.cpp b/Source/WebCore/platform/chromium/ChromiumDataObject.cpp new file mode 100644 index 0000000..78b794b --- /dev/null +++ b/Source/WebCore/platform/chromium/ChromiumDataObject.cpp @@ -0,0 +1,219 @@ +/* + * Copyright (c) 2010, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "ChromiumDataObject.h" + +namespace WebCore { + +ChromiumDataObject::ChromiumDataObject(PassRefPtr<ChromiumDataObjectLegacy> data) + : RefCounted<ChromiumDataObject>() + , m_legacyData(data) +{ +} + +ChromiumDataObject::ChromiumDataObject(PassRefPtr<ReadableDataObject> data) + : RefCounted<ChromiumDataObject>() + , m_readableData(data) +{ +} + +ChromiumDataObject::ChromiumDataObject(PassRefPtr<WritableDataObject> data) + : RefCounted<ChromiumDataObject>() + , m_writableData(data) +{ +} + +PassRefPtr<ChromiumDataObject> ChromiumDataObject::create(PassRefPtr<ChromiumDataObjectLegacy> data) +{ + return adoptRef(new ChromiumDataObject(data)); +} + +PassRefPtr<ChromiumDataObject> ChromiumDataObject::createReadable(Clipboard::ClipboardType clipboardType) +{ + return adoptRef(new ChromiumDataObject(ReadableDataObject::create(clipboardType))); +} + +PassRefPtr<ChromiumDataObject> ChromiumDataObject::createWritable(Clipboard::ClipboardType clipboardType) +{ + return adoptRef(new ChromiumDataObject(WritableDataObject::create(clipboardType))); +} + +void ChromiumDataObject::clearData(const String& type) +{ + if (m_legacyData) + m_legacyData->clearData(type); + else + m_writableData->clearData(type); +} + +void ChromiumDataObject::clearAll() +{ + if (m_legacyData) + m_legacyData->clearAll(); + else + m_writableData->clearAll(); +} + +void ChromiumDataObject::clearAllExceptFiles() +{ + if (m_legacyData) + m_legacyData->clearAllExceptFiles(); + else + m_writableData->clearAllExceptFiles(); +} + +bool ChromiumDataObject::hasData() const +{ + if (m_legacyData) + return m_legacyData->hasData(); + return m_readableData->hasData(); +} + +HashSet<String> ChromiumDataObject::types() const +{ + if (m_legacyData) + return m_legacyData->types(); + return m_readableData->types(); +} + +String ChromiumDataObject::getData(const String& type, bool& success) +{ + if (m_legacyData) + return m_legacyData->getData(type, success); + return m_readableData->getData(type, success); +} + +bool ChromiumDataObject::setData(const String& type, const String& data) +{ + if (m_legacyData) + return m_legacyData->setData(type, data); + return m_writableData->setData(type, data); +} + +String ChromiumDataObject::urlTitle() const +{ + if (m_legacyData) + return m_legacyData->urlTitle(); + return m_readableData->urlTitle(); +} + +void ChromiumDataObject::setUrlTitle(const String& urlTitle) +{ + if (m_legacyData) + m_legacyData->setUrlTitle(urlTitle); + else + m_writableData->setUrlTitle(urlTitle); +} + +KURL ChromiumDataObject::htmlBaseUrl() const +{ + if (m_legacyData) + return m_legacyData->htmlBaseUrl(); + return m_readableData->htmlBaseUrl(); +} + +void ChromiumDataObject::setHtmlBaseUrl(const KURL& url) +{ + if (m_legacyData) + m_legacyData->setHtmlBaseUrl(url); + else + m_writableData->setHtmlBaseUrl(url); +} + +bool ChromiumDataObject::containsFilenames() const +{ + if (m_legacyData) + return m_legacyData->containsFilenames(); + return m_readableData->containsFilenames(); +} + +Vector<String> ChromiumDataObject::filenames() const +{ + if (m_legacyData) + return m_legacyData->filenames(); + return m_readableData->filenames(); +} + +void ChromiumDataObject::setFilenames(const Vector<String>& filenames) +{ + if (m_legacyData) + m_legacyData->setFilenames(filenames); + else + ASSERT_NOT_REACHED(); +} + +String ChromiumDataObject::fileExtension() const +{ + if (m_legacyData) + return m_legacyData->fileExtension(); + return m_writableData->fileExtension(); +} + +void ChromiumDataObject::setFileExtension(const String& fileExtension) +{ + if (m_legacyData) + m_legacyData->setFileExtension(fileExtension); + else + m_writableData->setFileExtension(fileExtension); +} + +String ChromiumDataObject::fileContentFilename() const +{ + if (m_legacyData) + return m_legacyData->fileContentFilename(); + return m_writableData->fileContentFilename(); +} + +void ChromiumDataObject::setFileContentFilename(const String& fileContentFilename) +{ + if (m_legacyData) + m_legacyData->setFileContentFilename(fileContentFilename); + else + m_writableData->setFileContentFilename(fileContentFilename); +} + +PassRefPtr<SharedBuffer> ChromiumDataObject::fileContent() const +{ + if (m_legacyData) + return m_legacyData->fileContent(); + return m_writableData->fileContent(); +} + +void ChromiumDataObject::setFileContent(PassRefPtr<SharedBuffer> fileContent) +{ + if (m_legacyData) + m_legacyData->setFileContent(fileContent); + else + m_writableData->setFileContent(fileContent); +} + +} + diff --git a/Source/WebCore/platform/chromium/ChromiumDataObject.h b/Source/WebCore/platform/chromium/ChromiumDataObject.h new file mode 100644 index 0000000..4aac5c9 --- /dev/null +++ b/Source/WebCore/platform/chromium/ChromiumDataObject.h @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2010, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef ChromiumDataObject_h +#define ChromiumDataObject_h + +#include "ChromiumDataObjectLegacy.h" +#include "ReadableDataObject.h" +#include "WritableDataObject.h" +#include <wtf/RefPtr.h> + +namespace WebCore { + +class ChromiumDataObject : public RefCounted<ChromiumDataObject> { +public: + static PassRefPtr<ChromiumDataObject> create(PassRefPtr<ChromiumDataObjectLegacy> data); + static PassRefPtr<ChromiumDataObject> createReadable(Clipboard::ClipboardType); + static PassRefPtr<ChromiumDataObject> createWritable(Clipboard::ClipboardType); + + void clearData(const String& type); + void clearAll(); + void clearAllExceptFiles(); + + bool hasData() const; + + HashSet<String> types() const; + String getData(const String& type, bool& success); + bool setData(const String& type, const String& data); + + // Special handlers for URL/HTML metadata. + String urlTitle() const; + void setUrlTitle(const String& urlTitle); + KURL htmlBaseUrl() const; + void setHtmlBaseUrl(const KURL& url); + + // Used to handle files being dragged in. + bool containsFilenames() const; + Vector<String> filenames() const; + void setFilenames(const Vector<String>& filenames); + + // Used to handle files (images) being dragged out. + String fileExtension() const; + void setFileExtension(const String& fileExtension); + String fileContentFilename() const; + void setFileContentFilename(const String& fileContentFilename); + PassRefPtr<SharedBuffer> fileContent() const; + void setFileContent(PassRefPtr<SharedBuffer> fileContent); + +private: + ChromiumDataObject(PassRefPtr<ChromiumDataObjectLegacy>); + ChromiumDataObject(PassRefPtr<ReadableDataObject>); + ChromiumDataObject(PassRefPtr<WritableDataObject>); + + RefPtr<ChromiumDataObjectLegacy> m_legacyData; + RefPtr<ReadableDataObject> m_readableData; + RefPtr<WritableDataObject> m_writableData; +}; + +} + +#endif diff --git a/Source/WebCore/platform/chromium/ChromiumDataObjectLegacy.cpp b/Source/WebCore/platform/chromium/ChromiumDataObjectLegacy.cpp new file mode 100644 index 0000000..a2952c0 --- /dev/null +++ b/Source/WebCore/platform/chromium/ChromiumDataObjectLegacy.cpp @@ -0,0 +1,249 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "ChromiumDataObjectLegacy.h" + +#include "ChromiumBridge.h" +#include "ClipboardMimeTypes.h" +#include "Pasteboard.h" + +namespace WebCore { + +// Per RFC 2483, the line separator for "text/..." MIME types is CR-LF. +static char const* const textMIMETypeLineSeparator = "\r\n"; + +void ChromiumDataObjectLegacy::clearData(const String& type) +{ + if (type == mimeTypeTextPlain) { + m_plainText = ""; + return; + } + + if (type == mimeTypeURL || type == mimeTypeTextURIList) { + m_uriList = ""; + m_url = KURL(); + m_urlTitle = ""; + return; + } + + if (type == mimeTypeTextHTML) { + m_textHtml = ""; + m_htmlBaseUrl = KURL(); + return; + } + + if (type == mimeTypeDownloadURL) { + m_downloadMetadata = ""; + return; + } +} + +void ChromiumDataObjectLegacy::clearAll() +{ + clearAllExceptFiles(); + m_filenames.clear(); +} + +void ChromiumDataObjectLegacy::clearAllExceptFiles() +{ + m_urlTitle = ""; + m_url = KURL(); + m_uriList = ""; + m_downloadMetadata = ""; + m_fileExtension = ""; + m_plainText = ""; + m_textHtml = ""; + m_htmlBaseUrl = KURL(); + m_fileContentFilename = ""; + if (m_fileContent) + m_fileContent->clear(); +} + +bool ChromiumDataObjectLegacy::hasData() const +{ + return !m_url.isEmpty() + || !m_uriList.isEmpty() + || !m_downloadMetadata.isEmpty() + || !m_fileExtension.isEmpty() + || !m_filenames.isEmpty() + || !m_plainText.isEmpty() + || !m_textHtml.isEmpty() + || m_fileContent; +} + +HashSet<String> ChromiumDataObjectLegacy::types() const +{ + // This is currently broken for pasteboard events, and always has been. + HashSet<String> results; + + if (!m_plainText.isEmpty()) { + results.add(mimeTypeText); + results.add(mimeTypeTextPlain); + } + + if (m_url.isValid()) + results.add(mimeTypeURL); + + if (!m_uriList.isEmpty()) + results.add(mimeTypeTextURIList); + + if (!m_textHtml.isEmpty()) + results.add(mimeTypeTextHTML); + + if (!m_filenames.isEmpty()) + results.add("Files"); + + return results; +} + +String ChromiumDataObjectLegacy::getData(const String& type, bool& success) +{ + if (type == mimeTypeTextPlain) { + if (m_clipboardType == Clipboard::CopyAndPaste) { + PasteboardPrivate::ClipboardBuffer buffer = + Pasteboard::generalPasteboard()->isSelectionMode() ? + PasteboardPrivate::SelectionBuffer : + PasteboardPrivate::StandardBuffer; + String text = ChromiumBridge::clipboardReadPlainText(buffer); + success = !text.isEmpty(); + return text; + } + success = !m_plainText.isEmpty(); + return m_plainText; + } + + if (type == mimeTypeURL) { + success = !m_url.isEmpty(); + return m_url.string(); + } + + if (type == mimeTypeTextURIList) { + success = !m_uriList.isEmpty(); + return m_uriList; + } + + if (type == mimeTypeTextHTML) { + if (m_clipboardType == Clipboard::CopyAndPaste) { + PasteboardPrivate::ClipboardBuffer buffer = + Pasteboard::generalPasteboard()->isSelectionMode() ? + PasteboardPrivate::SelectionBuffer : + PasteboardPrivate::StandardBuffer; + String htmlText; + KURL sourceURL; + ChromiumBridge::clipboardReadHTML(buffer, &htmlText, &sourceURL); + success = !htmlText.isEmpty(); + return htmlText; + } + success = !m_textHtml.isEmpty(); + return m_textHtml; + } + + if (type == mimeTypeDownloadURL) { + success = !m_downloadMetadata.isEmpty(); + return m_downloadMetadata; + } + + success = false; + return String(); +} + +bool ChromiumDataObjectLegacy::setData(const String& type, const String& data) +{ + if (type == mimeTypeTextPlain) { + m_plainText = data; + return true; + } + + if (type == mimeTypeURL || type == mimeTypeTextURIList) { + m_url = KURL(); + Vector<String> uriList; + // Line separator is \r\n per RFC 2483 - however, for compatibility + // reasons we also allow just \n here. + data.split('\n', uriList); + // Process the input and copy the first valid URL into the url member. + // In case no URLs can be found, subsequent calls to getData("URL") + // will get an empty string. This is in line with the HTML5 spec (see + // "The DragEvent and DataTransfer interfaces"). + for (size_t i = 0; i < uriList.size(); ++i) { + String& line = uriList[i]; + line = line.stripWhiteSpace(); + if (line.isEmpty()) + continue; + if (line[0] == '#') + continue; + KURL url = KURL(ParsedURLString, line); + if (url.isValid()) { + m_url = url; + break; + } + } + m_uriList = data; + return true; + } + + if (type == mimeTypeTextHTML) { + m_textHtml = data; + m_htmlBaseUrl = KURL(); + return true; + } + + if (type == mimeTypeDownloadURL) { + m_downloadMetadata = data; + return true; + } + + return false; +} + +ChromiumDataObjectLegacy::ChromiumDataObjectLegacy(Clipboard::ClipboardType clipboardType) + : m_clipboardType(clipboardType) +{ +} + +ChromiumDataObjectLegacy::ChromiumDataObjectLegacy(const ChromiumDataObjectLegacy& other) + : RefCounted<ChromiumDataObjectLegacy>() + , m_clipboardType(other.m_clipboardType) + , m_urlTitle(other.m_urlTitle) + , m_downloadMetadata(other.m_downloadMetadata) + , m_fileExtension(other.m_fileExtension) + , m_filenames(other.m_filenames) + , m_plainText(other.m_plainText) + , m_textHtml(other.m_textHtml) + , m_htmlBaseUrl(other.m_htmlBaseUrl) + , m_fileContentFilename(other.m_fileContentFilename) + , m_url(other.m_url) + , m_uriList(other.m_uriList) +{ + if (other.m_fileContent.get()) + m_fileContent = other.m_fileContent->copy(); +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/ChromiumDataObjectLegacy.h b/Source/WebCore/platform/chromium/ChromiumDataObjectLegacy.h new file mode 100644 index 0000000..55be7aa --- /dev/null +++ b/Source/WebCore/platform/chromium/ChromiumDataObjectLegacy.h @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef ChromiumDataObjectLegacy_h +#define ChromiumDataObjectLegacy_h + +#include "Clipboard.h" +#include "KURL.h" +#include "PlatformString.h" +#include "SharedBuffer.h" +#include <wtf/HashSet.h> +#include <wtf/RefPtr.h> +#include <wtf/Vector.h> +#include <wtf/text/StringHash.h> + +namespace WebCore { + +// A data object for holding data that would be in a clipboard or moved +// during a drag-n-drop operation. This is the data that WebCore is aware +// of and is not specific to a platform. +class ChromiumDataObjectLegacy : public RefCounted<ChromiumDataObjectLegacy> { +public: + static PassRefPtr<ChromiumDataObjectLegacy> create(Clipboard::ClipboardType clipboardType) + { + return adoptRef(new ChromiumDataObjectLegacy(clipboardType)); + } + + PassRefPtr<ChromiumDataObjectLegacy> copy() const + { + return adoptRef(new ChromiumDataObjectLegacy(*this)); + } + + void clearData(const String& type); + void clearAll(); + void clearAllExceptFiles(); + + bool hasData() const; + + HashSet<String> types() const; + String getData(const String& type, bool& success); + bool setData(const String& type, const String& data); + + // Special handlers for URL/HTML metadata. + String urlTitle() const { return m_urlTitle; } + void setUrlTitle(const String& urlTitle) { m_urlTitle = urlTitle; } + KURL htmlBaseUrl() const { return m_htmlBaseUrl; } + void setHtmlBaseUrl(const KURL& url) { m_htmlBaseUrl = url; } + + // Used to handle files being dragged in. + bool containsFilenames() const { return !m_filenames.isEmpty(); } + Vector<String> filenames() const { return m_filenames; } + void setFilenames(const Vector<String>& filenames) { m_filenames = filenames; } + + // Used to handle files (images) being dragged out. + String fileExtension() const { return m_fileExtension; } + void setFileExtension(const String& fileExtension) { m_fileExtension = fileExtension; } + String fileContentFilename() const { return m_fileContentFilename; } + void setFileContentFilename(const String& fileContentFilename) { m_fileContentFilename = fileContentFilename; } + PassRefPtr<SharedBuffer> fileContent() const { return m_fileContent; } + void setFileContent(PassRefPtr<SharedBuffer> fileContent) { m_fileContent = fileContent; } + +private: + ChromiumDataObjectLegacy(Clipboard::ClipboardType); + ChromiumDataObjectLegacy(const ChromiumDataObjectLegacy&); + + Clipboard::ClipboardType m_clipboardType; + + String m_urlTitle; + + String m_downloadMetadata; + + String m_fileExtension; + Vector<String> m_filenames; + + String m_plainText; + + String m_textHtml; + KURL m_htmlBaseUrl; + + String m_fileContentFilename; + RefPtr<SharedBuffer> m_fileContent; + + // These two are linked. Setting m_url will set m_uriList to the same + // string value; setting m_uriList will cause its contents to be parsed + // according to RFC 2483 and the first URL found will be set in m_url. + KURL m_url; + String m_uriList; +}; + +} // namespace WebCore + +#endif diff --git a/Source/WebCore/platform/chromium/ClipboardChromium.cpp b/Source/WebCore/platform/chromium/ClipboardChromium.cpp new file mode 100644 index 0000000..46b4339 --- /dev/null +++ b/Source/WebCore/platform/chromium/ClipboardChromium.cpp @@ -0,0 +1,352 @@ +/* + * Copyright (C) 2006, 2007 Apple Inc. All rights reserved. + * Copyright (C) 2008, 2009 Google Inc. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "ClipboardChromium.h" + +#include "CachedImage.h" +#include "ChromiumDataObject.h" +#include "ClipboardMimeTypes.h" +#include "ClipboardUtilitiesChromium.h" +#include "Document.h" +#include "DragData.h" +#include "Element.h" +#include "FileList.h" +#include "Frame.h" +#include "HTMLNames.h" +#include "HTMLParserIdioms.h" +#include "Image.h" +#include "MIMETypeRegistry.h" +#include "NamedNodeMap.h" +#include "Range.h" +#include "RenderImage.h" +#include "ScriptExecutionContext.h" +#include "markup.h" + +#include <wtf/text/StringBuilder.h> +#include <wtf/text/WTFString.h> + +namespace WebCore { + +using namespace HTMLNames; + +// We provide the IE clipboard types (URL and Text), and the clipboard types specified in the WHATWG Web Applications 1.0 draft +// see http://www.whatwg.org/specs/web-apps/current-work/ Section 6.3.5.3 + +static String normalizeType(const String& type) +{ + String cleanType = type.stripWhiteSpace().lower(); + if (cleanType == mimeTypeText || cleanType.startsWith(mimeTypeTextPlainEtc)) + return mimeTypeTextPlain; + return cleanType; +} + +PassRefPtr<Clipboard> Clipboard::create(ClipboardAccessPolicy policy, DragData* dragData, Frame* frame) +{ + return ClipboardChromium::create(DragAndDrop, dragData->platformData(), policy, frame); +} + +ClipboardChromium::ClipboardChromium(ClipboardType clipboardType, + PassRefPtr<ChromiumDataObject> dataObject, + ClipboardAccessPolicy policy, + Frame* frame) + : Clipboard(policy, clipboardType) + , m_dataObject(dataObject) + , m_frame(frame) +{ +} + +PassRefPtr<ClipboardChromium> ClipboardChromium::create(ClipboardType clipboardType, + PassRefPtr<ChromiumDataObject> dataObject, ClipboardAccessPolicy policy, Frame* frame) +{ + return adoptRef(new ClipboardChromium(clipboardType, dataObject, policy, frame)); +} + +PassRefPtr<ClipboardChromium> ClipboardChromium::create(ClipboardType clipboardType, + ClipboardAccessPolicy policy, Frame* frame) +{ + RefPtr<ChromiumDataObject> dataObject = + policy == ClipboardWritable ? + ChromiumDataObject::createWritable(clipboardType) : + ChromiumDataObject::createReadable(clipboardType); + return adoptRef(new ClipboardChromium(clipboardType, dataObject, policy, frame)); +} + +void ClipboardChromium::clearData(const String& type) +{ + if (policy() != ClipboardWritable || !m_dataObject) + return; + + m_dataObject->clearData(normalizeType(type)); + + ASSERT_NOT_REACHED(); +} + +void ClipboardChromium::clearAllData() +{ + if (policy() != ClipboardWritable) + return; + + m_dataObject->clearAll(); +} + +String ClipboardChromium::getData(const String& type, bool& success) const +{ + success = false; + if (policy() != ClipboardReadable || !m_dataObject) + return String(); + + return m_dataObject->getData(normalizeType(type), success); +} + +bool ClipboardChromium::setData(const String& type, const String& data) +{ + if (policy() != ClipboardWritable) + return false; + + return m_dataObject->setData(normalizeType(type), data); +} + +// extensions beyond IE's API +HashSet<String> ClipboardChromium::types() const +{ + HashSet<String> results; + if (policy() != ClipboardReadable && policy() != ClipboardTypesReadable) + return results; + + if (!m_dataObject) + return results; + + results = m_dataObject->types(); + + return results; +} + +PassRefPtr<FileList> ClipboardChromium::files() const +{ + if (policy() != ClipboardReadable) + return FileList::create(); + + if (!m_dataObject) + return FileList::create(); + + const Vector<String>& filenames = m_dataObject->filenames(); + RefPtr<FileList> fileList = FileList::create(); + for (size_t i = 0; i < filenames.size(); ++i) + fileList->append(File::create(filenames.at(i))); + + return fileList.release(); +} + +void ClipboardChromium::setDragImage(CachedImage* image, Node* node, const IntPoint& loc) +{ + if (policy() != ClipboardImageWritable && policy() != ClipboardWritable) + return; + + if (m_dragImage) + m_dragImage->removeClient(this); + m_dragImage = image; + if (m_dragImage) + m_dragImage->addClient(this); + + m_dragLoc = loc; + m_dragImageElement = node; +} + +void ClipboardChromium::setDragImage(CachedImage* img, const IntPoint& loc) +{ + setDragImage(img, 0, loc); +} + +void ClipboardChromium::setDragImageElement(Node* node, const IntPoint& loc) +{ + setDragImage(0, node, loc); +} + +DragImageRef ClipboardChromium::createDragImage(IntPoint& loc) const +{ + DragImageRef result = 0; + if (m_dragImageElement) { + if (m_frame) { + result = m_frame->nodeImage(m_dragImageElement.get()); + loc = m_dragLoc; + } + } else if (m_dragImage) { + result = createDragImageFromImage(m_dragImage->image()); + loc = m_dragLoc; + } + return result; +} + +static String imageToMarkup(const String& url, Element* element) +{ + StringBuilder markup; + markup.append("<img src=\""); + markup.append(url); + markup.append('"'); + // Copy over attributes. If we are dragging an image, we expect things like + // the id to be copied as well. + NamedNodeMap* attrs = element->attributes(); + unsigned length = attrs->length(); + for (unsigned i = 0; i < length; ++i) { + Attribute* attr = attrs->attributeItem(i); + if (attr->localName() == "src") + continue; + markup.append(' '); + markup.append(attr->localName()); + markup.append("=\""); + String escapedAttr = attr->value(); + escapedAttr.replace("\"", """); + markup.append(escapedAttr); + markup.append('"'); + } + + markup.append("/>"); + return markup.toString(); +} + +static CachedImage* getCachedImage(Element* element) +{ + // Attempt to pull CachedImage from element + ASSERT(element); + RenderObject* renderer = element->renderer(); + if (!renderer || !renderer->isImage()) + return 0; + + RenderImage* image = toRenderImage(renderer); + if (image->cachedImage() && !image->cachedImage()->errorOccurred()) + return image->cachedImage(); + + return 0; +} + +static void writeImageToDataObject(ChromiumDataObject* dataObject, Element* element, + const KURL& url) +{ + // Shove image data into a DataObject for use as a file + CachedImage* cachedImage = getCachedImage(element); + if (!cachedImage || !cachedImage->image() || !cachedImage->isLoaded()) + return; + + SharedBuffer* imageBuffer = cachedImage->image()->data(); + if (!imageBuffer || !imageBuffer->size()) + return; + + dataObject->setFileContent(imageBuffer); + + // Determine the filename for the file contents of the image. We try to + // use the alt tag if one exists, otherwise we fall back on the suggested + // filename in the http header, and finally we resort to using the filename + // in the URL. + String extension = MIMETypeRegistry::getPreferredExtensionForMIMEType( + cachedImage->response().mimeType()); + dataObject->setFileExtension(extension.isEmpty() ? "" : "." + extension); + String title = element->getAttribute(altAttr); + if (title.isEmpty()) + title = cachedImage->response().suggestedFilename(); + + title = ClipboardChromium::validateFileName(title, dataObject); + dataObject->setFileContentFilename(title + dataObject->fileExtension()); +} + +void ClipboardChromium::declareAndWriteDragImage(Element* element, const KURL& url, const String& title, Frame* frame) +{ + if (!m_dataObject) + return; + + m_dataObject->setData(mimeTypeURL, url); + m_dataObject->setUrlTitle(title); + + // Write the bytes in the image to the file format. + writeImageToDataObject(m_dataObject.get(), element, url); + + AtomicString imageURL = element->getAttribute(srcAttr); + if (imageURL.isEmpty()) + return; + + String fullURL = frame->document()->completeURL(stripLeadingAndTrailingHTMLSpaces(imageURL)); + if (fullURL.isEmpty()) + return; + + // Put img tag on the clipboard referencing the image + m_dataObject->setData(mimeTypeTextHTML, imageToMarkup(fullURL, element)); +} + +void ClipboardChromium::writeURL(const KURL& url, const String& title, Frame*) +{ + if (!m_dataObject) + return; + ASSERT(!url.isEmpty()); + m_dataObject->setData(mimeTypeURL, url); + m_dataObject->setUrlTitle(title); + + // The URL can also be used as plain text. + m_dataObject->setData(mimeTypeTextPlain, url.string()); + + // The URL can also be used as an HTML fragment. + m_dataObject->setData(mimeTypeTextHTML, urlToMarkup(url, title)); + m_dataObject->setHtmlBaseUrl(url); +} + +void ClipboardChromium::writeRange(Range* selectedRange, Frame* frame) +{ + ASSERT(selectedRange); + if (!m_dataObject) + return; + + m_dataObject->setData(mimeTypeTextHTML, createMarkup(selectedRange, 0, AnnotateForInterchange, false, AbsoluteURLs)); + m_dataObject->setHtmlBaseUrl(frame->document()->url()); + + String str = frame->editor()->selectedText(); +#if OS(WINDOWS) + replaceNewlinesWithWindowsStyleNewlines(str); +#endif + replaceNBSPWithSpace(str); + m_dataObject->setData(mimeTypeTextPlain, str); +} + +void ClipboardChromium::writePlainText(const String& text) +{ + if (!m_dataObject) + return; + + String str = text; +#if OS(WINDOWS) + replaceNewlinesWithWindowsStyleNewlines(str); +#endif + replaceNBSPWithSpace(str); + m_dataObject->setData(mimeTypeTextPlain, str); +} + +bool ClipboardChromium::hasData() +{ + if (!m_dataObject) + return false; + + return m_dataObject->hasData(); +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/ClipboardChromium.h b/Source/WebCore/platform/chromium/ClipboardChromium.h new file mode 100644 index 0000000..1d69921 --- /dev/null +++ b/Source/WebCore/platform/chromium/ClipboardChromium.h @@ -0,0 +1,96 @@ +// Copyright (c) 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#ifndef ClipboardChromium_h +#define ClipboardChromium_h + +#include "Clipboard.h" + +#include "CachedResourceClient.h" + +namespace WebCore { + + class CachedImage; + class ChromiumDataObject; + class Frame; + class IntPoint; + + class ClipboardChromium : public Clipboard, public CachedResourceClient { + public: + ~ClipboardChromium() {} + + static PassRefPtr<ClipboardChromium> create( + ClipboardType, PassRefPtr<ChromiumDataObject>, ClipboardAccessPolicy, Frame*); + + static PassRefPtr<ClipboardChromium> create( + ClipboardType, ClipboardAccessPolicy, Frame*); + + // Returns the file name (not including the extension). This removes any + // invalid file system characters as well as making sure the + // path + extension is not bigger than allowed by the file system. + // This may change the file extension in dataObject. + static String validateFileName(const String& title, ChromiumDataObject* dataObject); + + virtual void clearData(const String& type); + void clearAllData(); + String getData(const String& type, bool& success) const; + bool setData(const String& type, const String& data); + + // extensions beyond IE's API + virtual HashSet<String> types() const; + virtual PassRefPtr<FileList> files() const; + + void setDragImage(CachedImage*, const IntPoint&); + void setDragImageElement(Node*, const IntPoint&); + + PassRefPtr<ChromiumDataObject> dataObject() + { + return m_dataObject; + } + + virtual DragImageRef createDragImage(IntPoint& dragLoc) const; + virtual void declareAndWriteDragImage(Element*, const KURL&, const String& title, Frame*); + virtual void writeURL(const KURL&, const String&, Frame*); + virtual void writeRange(Range*, Frame*); + virtual void writePlainText(const String&); + + virtual bool hasData(); + + private: + ClipboardChromium(ClipboardType, PassRefPtr<ChromiumDataObject>, ClipboardAccessPolicy, Frame*); + + void resetFromClipboard(); + void setDragImage(CachedImage*, Node*, const IntPoint&); + RefPtr<ChromiumDataObject> m_dataObject; + Frame* m_frame; + }; + +} // namespace WebCore + +#endif // ClipboardChromium_h diff --git a/Source/WebCore/platform/chromium/ClipboardChromiumLinux.cpp b/Source/WebCore/platform/chromium/ClipboardChromiumLinux.cpp new file mode 100644 index 0000000..2c89f6e --- /dev/null +++ b/Source/WebCore/platform/chromium/ClipboardChromiumLinux.cpp @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2009 Apple Inc. All rights reserved. + * Copyright (C) 2009 Google Inc. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "ClipboardChromium.h" + +#include "ChromiumDataObject.h" +#include "NotImplemented.h" + +namespace WebCore { + +String ClipboardChromium::validateFileName(const String& title, ChromiumDataObject* dataObject) +{ + notImplemented(); + return title; +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/ClipboardChromiumMac.cpp b/Source/WebCore/platform/chromium/ClipboardChromiumMac.cpp new file mode 100644 index 0000000..2c89f6e --- /dev/null +++ b/Source/WebCore/platform/chromium/ClipboardChromiumMac.cpp @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2009 Apple Inc. All rights reserved. + * Copyright (C) 2009 Google Inc. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "ClipboardChromium.h" + +#include "ChromiumDataObject.h" +#include "NotImplemented.h" + +namespace WebCore { + +String ClipboardChromium::validateFileName(const String& title, ChromiumDataObject* dataObject) +{ + notImplemented(); + return title; +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/ClipboardChromiumWin.cpp b/Source/WebCore/platform/chromium/ClipboardChromiumWin.cpp new file mode 100644 index 0000000..d9bbeb5 --- /dev/null +++ b/Source/WebCore/platform/chromium/ClipboardChromiumWin.cpp @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2009 Apple Inc. All rights reserved. + * Copyright (C) 2009 Google Inc. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "ClipboardChromium.h" + +#include "ChromiumDataObject.h" + +#include <shlwapi.h> + +namespace WebCore { + +// Returns true if the specified character is not valid in a file name. This +// is intended for use with removeCharacters. +static bool isInvalidFileCharacter(UChar c) +{ + return (PathGetCharType(c) & (GCT_LFNCHAR | GCT_SHORTCHAR)) == 0; +} + +String ClipboardChromium::validateFileName(const String& title, ChromiumDataObject* dataObject) +{ + // Remove any invalid file system characters. + String result = title.removeCharacters(&isInvalidFileCharacter); + if (result.length() + dataObject->fileExtension().length() + 1 >= MAX_PATH) { + if (dataObject->fileExtension().length() + 1 >= MAX_PATH) + dataObject->setFileExtension(""); + if (result.length() + dataObject->fileExtension().length() + 1 >= MAX_PATH) + result = result.substring(0, MAX_PATH - dataObject->fileExtension().length() - 1); + } + return result; +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/ClipboardMimeTypes.cpp b/Source/WebCore/platform/chromium/ClipboardMimeTypes.cpp new file mode 100644 index 0000000..f689e0e --- /dev/null +++ b/Source/WebCore/platform/chromium/ClipboardMimeTypes.cpp @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2010 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "ClipboardMimeTypes.h" + +namespace WebCore { + +const char mimeTypeText[] = "text"; +const char mimeTypeTextPlain[] = "text/plain"; +const char mimeTypeTextPlainEtc[] = "text/plain;"; +const char mimeTypeTextHTML[] = "text/html"; +const char mimeTypeURL[] = "url"; +const char mimeTypeTextURIList[] = "text/uri-list"; +const char mimeTypeDownloadURL[] = "downloadurl"; + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/ClipboardMimeTypes.h b/Source/WebCore/platform/chromium/ClipboardMimeTypes.h new file mode 100644 index 0000000..9bdccfe --- /dev/null +++ b/Source/WebCore/platform/chromium/ClipboardMimeTypes.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2010 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef ClipboardMimeTypes_h +#define ClipboardMimeTypes_h + +namespace WebCore { + +extern const char mimeTypeText[]; +extern const char mimeTypeTextPlain[]; +extern const char mimeTypeTextPlainEtc[]; +extern const char mimeTypeTextHTML[]; +extern const char mimeTypeURL[]; +extern const char mimeTypeTextURIList[]; +extern const char mimeTypeDownloadURL[]; + +} // namespace WebCore + +#endif diff --git a/Source/WebCore/platform/chromium/ClipboardUtilitiesChromium.cpp b/Source/WebCore/platform/chromium/ClipboardUtilitiesChromium.cpp new file mode 100644 index 0000000..b0680ac --- /dev/null +++ b/Source/WebCore/platform/chromium/ClipboardUtilitiesChromium.cpp @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "ClipboardUtilitiesChromium.h" + +#include "KURL.h" +#include "PlatformString.h" + +namespace WebCore { + +#if OS(WINDOWS) +void replaceNewlinesWithWindowsStyleNewlines(String& str) +{ + static const UChar Newline = '\n'; + static const char* const WindowsNewline("\r\n"); + str.replace(Newline, WindowsNewline); +} +#endif + +void replaceNBSPWithSpace(String& str) +{ + static const UChar NonBreakingSpaceCharacter = 0xA0; + static const UChar SpaceCharacter = ' '; + str.replace(NonBreakingSpaceCharacter, SpaceCharacter); +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/ClipboardUtilitiesChromium.h b/Source/WebCore/platform/chromium/ClipboardUtilitiesChromium.h new file mode 100644 index 0000000..9fdad42 --- /dev/null +++ b/Source/WebCore/platform/chromium/ClipboardUtilitiesChromium.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include <wtf/Forward.h> + +namespace WebCore { + +class KURL; + +#if OS(WINDOWS) +void replaceNewlinesWithWindowsStyleNewlines(String&); +#endif +void replaceNBSPWithSpace(String&); + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/ContextMenuChromium.cpp b/Source/WebCore/platform/chromium/ContextMenuChromium.cpp new file mode 100644 index 0000000..9bddd28 --- /dev/null +++ b/Source/WebCore/platform/chromium/ContextMenuChromium.cpp @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "ContextMenu.h" + +namespace WebCore { + +// This is a stub implementation of WebKit's ContextMenu class that does +// nothing. + +ContextMenu::ContextMenu() +{ +} + +ContextMenu::ContextMenu(const PlatformMenuDescription menu) +{ +} + +ContextMenu::~ContextMenu() +{ +} + +unsigned ContextMenu::itemCount() const +{ + return m_items.size(); +} + +void ContextMenu::insertItem(unsigned position, ContextMenuItem& item) +{ + m_items.insert(position, item); +} + +void ContextMenu::appendItem(ContextMenuItem& item) +{ + m_items.append(item); +} + +ContextMenuItem* ContextMenu::itemWithAction(unsigned action) +{ + for (size_t i = 0; i < m_items.size(); ++i) { + if (m_items[i].action() == static_cast<ContextMenuAction>(action)) + return &m_items[i]; + } + return 0; +} + +ContextMenuItem* ContextMenu::itemAtIndex(unsigned index, const PlatformMenuDescription platformDescription) +{ + return &m_items[index]; +} + +void ContextMenu::setPlatformDescription(PlatformMenuDescription menu) +{ +} + +PlatformMenuDescription ContextMenu::platformDescription() const +{ + return 0; +} + +PlatformMenuDescription ContextMenu::releasePlatformDescription() +{ + return 0; +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/ContextMenuItemChromium.cpp b/Source/WebCore/platform/chromium/ContextMenuItemChromium.cpp new file mode 100644 index 0000000..6a0d657 --- /dev/null +++ b/Source/WebCore/platform/chromium/ContextMenuItemChromium.cpp @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "ContextMenuItem.h" + +namespace WebCore { + +// This is a stub implementation of WebKit's ContextMenu class that does +// nothing. + +ContextMenuItem::ContextMenuItem(PlatformMenuItemDescription item) +{ +} + +ContextMenuItem::ContextMenuItem(ContextMenu* subMenu) +{ +} + +ContextMenuItem::ContextMenuItem(ContextMenuItemType type, ContextMenuAction action, const String& title, ContextMenu* subMenu) +{ + m_platformDescription.type = type; + m_platformDescription.action = action; + m_platformDescription.title = title; +} + +ContextMenuItem::~ContextMenuItem() +{ +} + +PlatformMenuItemDescription ContextMenuItem::releasePlatformDescription() +{ + return m_platformDescription; +} + +ContextMenuItemType ContextMenuItem::type() const +{ + return m_platformDescription.type; +} + +ContextMenuAction ContextMenuItem::action() const +{ + return m_platformDescription.action; +} + +String ContextMenuItem::title() const +{ + return m_platformDescription.title; +} + +bool ContextMenuItem::checked() const +{ + return m_platformDescription.checked; +} + +bool ContextMenuItem::enabled() const +{ + return m_platformDescription.enabled; +} + +PlatformMenuDescription ContextMenuItem::platformSubMenu() const +{ + return PlatformMenuDescription(); +} + +void ContextMenuItem::setType(ContextMenuItemType type) +{ + m_platformDescription.type = type; +} + +void ContextMenuItem::setAction(ContextMenuAction action) +{ + m_platformDescription.action = action; +} + +void ContextMenuItem::setTitle(const String& title) +{ + m_platformDescription.title = title; +} + +void ContextMenuItem::setSubMenu(ContextMenu* subMenu) +{ +} + +void ContextMenuItem::setChecked(bool checked) +{ + m_platformDescription.checked = checked; +} + +void ContextMenuItem::setEnabled(bool enabled) +{ + m_platformDescription.enabled = enabled; +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/CursorChromium.cpp b/Source/WebCore/platform/chromium/CursorChromium.cpp new file mode 100644 index 0000000..0119f07 --- /dev/null +++ b/Source/WebCore/platform/chromium/CursorChromium.cpp @@ -0,0 +1,317 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "Cursor.h" + +namespace WebCore { + +Cursor::Cursor(const Cursor& other) + : m_platformCursor(other.m_platformCursor) +{ +} + +Cursor::Cursor(Image* image, const IntPoint& hotSpot) + : m_platformCursor(image, hotSpot) +{ +} + +Cursor::~Cursor() +{ +} + +Cursor& Cursor::operator=(const Cursor& other) +{ + m_platformCursor = other.m_platformCursor; + return *this; +} + +Cursor::Cursor(PlatformCursor c) + : m_platformCursor(c) +{ +} + +const Cursor& pointerCursor() +{ + static const Cursor c(PlatformCursor::TypePointer); + return c; +} + +const Cursor& crossCursor() +{ + static const Cursor c(PlatformCursor::TypeCross); + return c; +} + +const Cursor& handCursor() +{ + static const Cursor c(PlatformCursor::TypeHand); + return c; +} + +const Cursor& iBeamCursor() +{ + static const Cursor c(PlatformCursor::TypeIBeam); + return c; +} + +const Cursor& waitCursor() +{ + static const Cursor c(PlatformCursor::TypeWait); + return c; +} + +const Cursor& helpCursor() +{ + static const Cursor c(PlatformCursor::TypeHelp); + return c; +} + +const Cursor& eastResizeCursor() +{ + static const Cursor c(PlatformCursor::TypeEastResize); + return c; +} + +const Cursor& northResizeCursor() +{ + static const Cursor c(PlatformCursor::TypeNorthResize); + return c; +} + +const Cursor& northEastResizeCursor() +{ + static const Cursor c(PlatformCursor::TypeNorthEastResize); + return c; +} + +const Cursor& northWestResizeCursor() +{ + static const Cursor c(PlatformCursor::TypeNorthWestResize); + return c; +} + +const Cursor& southResizeCursor() +{ + static const Cursor c(PlatformCursor::TypeSouthResize); + return c; +} + +const Cursor& southEastResizeCursor() +{ + static const Cursor c(PlatformCursor::TypeSouthEastResize); + return c; +} + +const Cursor& southWestResizeCursor() +{ + static const Cursor c(PlatformCursor::TypeSouthWestResize); + return c; +} + +const Cursor& westResizeCursor() +{ + static const Cursor c(PlatformCursor::TypeWestResize); + return c; +} + +const Cursor& northSouthResizeCursor() +{ + static const Cursor c(PlatformCursor::TypeNorthSouthResize); + return c; +} + +const Cursor& eastWestResizeCursor() +{ + static const Cursor c(PlatformCursor::TypeEastWestResize); + return c; +} + +const Cursor& northEastSouthWestResizeCursor() +{ + static const Cursor c(PlatformCursor::TypeNorthEastSouthWestResize); + return c; +} + +const Cursor& northWestSouthEastResizeCursor() +{ + static const Cursor c(PlatformCursor::TypeNorthWestSouthEastResize); + return c; +} + +const Cursor& columnResizeCursor() +{ + static const Cursor c(PlatformCursor::TypeColumnResize); + return c; +} + +const Cursor& rowResizeCursor() +{ + static const Cursor c(PlatformCursor::TypeRowResize); + return c; +} + +const Cursor& middlePanningCursor() +{ + static const Cursor c(PlatformCursor::TypeMiddlePanning); + return c; +} + +const Cursor& eastPanningCursor() +{ + static const Cursor c(PlatformCursor::TypeEastPanning); + return c; +} + +const Cursor& northPanningCursor() +{ + static const Cursor c(PlatformCursor::TypeNorthPanning); + return c; +} + +const Cursor& northEastPanningCursor() +{ + static const Cursor c(PlatformCursor::TypeNorthEastPanning); + return c; +} + +const Cursor& northWestPanningCursor() +{ + static const Cursor c(PlatformCursor::TypeNorthWestPanning); + return c; +} + +const Cursor& southPanningCursor() +{ + static const Cursor c(PlatformCursor::TypeSouthPanning); + return c; +} + +const Cursor& southEastPanningCursor() +{ + static const Cursor c(PlatformCursor::TypeSouthEastPanning); + return c; +} + +const Cursor& southWestPanningCursor() +{ + static const Cursor c(PlatformCursor::TypeSouthWestPanning); + return c; +} + +const Cursor& westPanningCursor() +{ + static const Cursor c(PlatformCursor::TypeWestPanning); + return c; +} + +const Cursor& moveCursor() +{ + static const Cursor c(PlatformCursor::TypeMove); + return c; +} + +const Cursor& verticalTextCursor() +{ + static const Cursor c(PlatformCursor::TypeVerticalText); + return c; +} + +const Cursor& cellCursor() +{ + static const Cursor c(PlatformCursor::TypeCell); + return c; +} + +const Cursor& contextMenuCursor() +{ + static const Cursor c(PlatformCursor::TypeContextMenu); + return c; +} + +const Cursor& aliasCursor() +{ + static const Cursor c(PlatformCursor::TypeAlias); + return c; +} + +const Cursor& progressCursor() +{ + static const Cursor c(PlatformCursor::TypeProgress); + return c; +} + +const Cursor& noDropCursor() +{ + static const Cursor c(PlatformCursor::TypeNoDrop); + return c; +} + +const Cursor& copyCursor() +{ + static const Cursor c(PlatformCursor::TypeCopy); + return c; +} + +const Cursor& noneCursor() +{ + static const Cursor c(PlatformCursor::TypeNone); + return c; +} + +const Cursor& notAllowedCursor() +{ + static const Cursor c(PlatformCursor::TypeNotAllowed); + return c; +} + +const Cursor& zoomInCursor() +{ + static const Cursor c(PlatformCursor::TypeZoomIn); + return c; +} + +const Cursor& zoomOutCursor() +{ + static const Cursor c(PlatformCursor::TypeZoomOut); + return c; +} + +const Cursor& grabCursor() +{ + return pointerCursor(); +} + +const Cursor& grabbingCursor() +{ + return pointerCursor(); +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/DragDataChromium.cpp b/Source/WebCore/platform/chromium/DragDataChromium.cpp new file mode 100644 index 0000000..2b04523 --- /dev/null +++ b/Source/WebCore/platform/chromium/DragDataChromium.cpp @@ -0,0 +1,154 @@ +/* + * Copyright (C) 2007 Apple Inc. All rights reserved. + * Copyright (C) 2008, 2009 Google Inc. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +// Modified from DragDataWin.cpp to not directly call any windows methods as +// they may not be available to us in the multiprocess + +#include "config.h" +#include "DragData.h" + +#include "ChromiumBridge.h" +#include "ChromiumDataObject.h" +#include "ClipboardMimeTypes.h" +#include "DocumentFragment.h" +#include "FileSystem.h" +#include "KURL.h" +#include "markup.h" +#include "NotImplemented.h" +#include "PlatformString.h" + +namespace WebCore { + +static bool containsHTML(const ChromiumDataObject* dropData) +{ + return dropData->types().contains(mimeTypeTextHTML); +} + +bool DragData::containsURL(FilenameConversionPolicy filenamePolicy) const +{ + return m_platformDragData->types().contains(mimeTypeURL) + || (filenamePolicy == ConvertFilenames && m_platformDragData->containsFilenames()); +} + +String DragData::asURL(FilenameConversionPolicy filenamePolicy, String* title) const +{ + String url; + if (m_platformDragData->types().contains(mimeTypeURL)) { + bool ignoredSuccess; + url = m_platformDragData->getData(mimeTypeURL, ignoredSuccess); + if (title) + *title = m_platformDragData->urlTitle(); + } else if (filenamePolicy == ConvertFilenames && containsFiles()) { + url = ChromiumBridge::filePathToURL(ChromiumBridge::getAbsolutePath(m_platformDragData->filenames()[0])); + } + return url; +} + +bool DragData::containsFiles() const +{ + return m_platformDragData->containsFilenames(); +} + +void DragData::asFilenames(Vector<String>& result) const +{ + const Vector<String>& filenames = m_platformDragData->filenames(); + for (size_t i = 0; i < filenames.size(); ++i) + result.append(filenames[i]); +} + +bool DragData::containsPlainText() const +{ + return m_platformDragData->types().contains(mimeTypeTextPlain); +} + +String DragData::asPlainText() const +{ + bool ignoredSuccess; + return m_platformDragData->getData(mimeTypeTextPlain, ignoredSuccess); +} + +bool DragData::containsColor() const +{ + notImplemented(); + return false; +} + +bool DragData::canSmartReplace() const +{ + // Mimic the situations in which mac allows drag&drop to do a smart replace. + // This is allowed whenever the drag data contains a 'range' (ie., + // ClipboardWin::writeRange is called). For example, dragging a link + // should not result in a space being added. + return m_platformDragData->types().contains(mimeTypeTextPlain) + && !m_platformDragData->types().contains(mimeTypeURL); +} + +bool DragData::containsCompatibleContent() const +{ + return containsPlainText() + || containsURL() + || containsHTML(m_platformDragData) + || containsColor() + || containsFiles(); +} + +PassRefPtr<DocumentFragment> DragData::asFragment(Document* doc) const +{ + /* + * Order is richest format first. On OSX this is: + * * Web Archive + * * Filenames + * * HTML + * * RTF + * * TIFF + * * PICT + */ + + if (containsFiles()) { + // FIXME: Implement this. Should be pretty simple to make some HTML + // and call createFragmentFromMarkup. + //if (RefPtr<DocumentFragment> fragment = createFragmentFromMarkup(doc, + // ?, KURL())) + // return fragment; + } + + if (m_platformDragData->types().contains(mimeTypeTextHTML)) { + bool ignoredSuccess; + RefPtr<DocumentFragment> fragment = createFragmentFromMarkup(doc, + m_platformDragData->getData(mimeTypeTextHTML, ignoredSuccess), m_platformDragData->htmlBaseUrl(), FragmentScriptingNotAllowed); + return fragment.release(); + } + + return 0; +} + +Color DragData::asColor() const +{ + notImplemented(); + return Color(); +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/DragDataRef.h b/Source/WebCore/platform/chromium/DragDataRef.h new file mode 100644 index 0000000..de1fa1c --- /dev/null +++ b/Source/WebCore/platform/chromium/DragDataRef.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef DragDataRef_h +#define DragDataRef_h + +#include "ChromiumDataObject.h" + +namespace WebCore { + + typedef ChromiumDataObject* DragDataRef; + +} // namespace WebCore + +#endif diff --git a/Source/WebCore/platform/chromium/DragImageChromiumMac.cpp b/Source/WebCore/platform/chromium/DragImageChromiumMac.cpp new file mode 100644 index 0000000..a0c2e20 --- /dev/null +++ b/Source/WebCore/platform/chromium/DragImageChromiumMac.cpp @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2010, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "DragImage.h" + +#include "Image.h" +#include "NotImplemented.h" +#include <wtf/RetainPtr.h> + +#include <CoreGraphics/CGBitmapContext.h> +#include <CoreGraphics/CGImage.h> + +namespace WebCore { + +IntSize dragImageSize(DragImageRef image) +{ + if (!image) + return IntSize(); + return IntSize(CGImageGetWidth(image), CGImageGetHeight(image)); +} + +void deleteDragImage(DragImageRef image) +{ + CGImageRelease(image); +} + +DragImageRef scaleDragImage(DragImageRef image, FloatSize scale) +{ + if (!image) + return 0; + size_t width = roundf(CGImageGetWidth(image) * scale.width()); + size_t height = roundf(CGImageGetHeight(image) * scale.height()); + + RetainPtr<CGColorSpaceRef> deviceRGB(WTF::AdoptCF, CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB)); + CGContextRef context = CGBitmapContextCreate(0, width, height, 8, width * 4, deviceRGB.get(), kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host); + + if (!context) + return 0; + CGContextDrawImage(context, CGRectMake(0, 0, width, height), image); + CGImageRelease(image); + + CGImageRef scaledImage = CGBitmapContextCreateImage(context); + CGContextRelease(context); + return scaledImage; +} + +DragImageRef dissolveDragImageToFraction(DragImageRef image, float delta) +{ + if (!image) + return 0; + size_t width = CGImageGetWidth(image); + size_t height = CGImageGetHeight(image); + + RetainPtr<CGColorSpaceRef> deviceRGB(WTF::AdoptCF, CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB)); + CGContextRef context = CGBitmapContextCreate(0, width, height, 8, width * 4, deviceRGB.get(), kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host); + + if (!context) + return 0; + // From CGContext.h: + // The Porter-Duff "source over" mode is called `kCGBlendModeNormal': + // R = S + D*(1 - Sa) + // This is the same as NSCompositeSourceOver, which is what -[NSImage dissolveToPoint:fraction:] uses. + CGContextSetAlpha(context, delta); + CGContextSetBlendMode(context, kCGBlendModeNormal); + CGContextDrawImage(context, CGRectMake(0, 0, width, height), image); + CGImageRelease(image); + + CGImageRef dissolvedImage = CGBitmapContextCreateImage(context); + CGContextRelease(context); + return dissolvedImage; +} + +DragImageRef createDragImageFromImage(Image* image) +{ + if (!image) + return 0; + return CGImageCreateCopy(image->nativeImageForCurrentFrame()); +} + +DragImageRef createDragImageIconForCachedImage(CachedImage*) +{ + notImplemented(); + return 0; +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/DragImageChromiumSkia.cpp b/Source/WebCore/platform/chromium/DragImageChromiumSkia.cpp new file mode 100644 index 0000000..e5c1cee --- /dev/null +++ b/Source/WebCore/platform/chromium/DragImageChromiumSkia.cpp @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "DragImage.h" + +#include "Image.h" +#include "NativeImageSkia.h" +#include "NotImplemented.h" +#include "RefPtr.h" +#include "SkBitmap.h" + +#include "skia/ext/image_operations.h" + +namespace WebCore { + +IntSize dragImageSize(DragImageRef image) +{ + if (!image) + return IntSize(); + + return IntSize(image->width(), image->height()); +} + +void deleteDragImage(DragImageRef image) +{ + delete image; +} + +DragImageRef scaleDragImage(DragImageRef image, FloatSize scale) +{ + if (!image) + return 0; + + int imageWidth = scale.width() * image->width(); + int imageHeight = scale.height() * image->height(); + DragImageRef scaledImage = new SkBitmap( + skia::ImageOperations::Resize(*image, skia::ImageOperations::RESIZE_LANCZOS3, + imageWidth, imageHeight)); + delete image; + return scaledImage; +} + +DragImageRef dissolveDragImageToFraction(DragImageRef image, float fraction) +{ + if (!image) + return 0; + + image->setIsOpaque(false); + image->lockPixels(); + + for (int row = 0; row < image->height(); ++row) { + for (int column = 0; column < image->width(); ++column) { + uint32_t* pixel = image->getAddr32(column, row); + *pixel = SkPreMultiplyARGB(SkColorGetA(*pixel) * fraction, + SkColorGetR(*pixel), + SkColorGetG(*pixel), + SkColorGetB(*pixel)); + } + } + + image->unlockPixels(); + + return image; +} + +DragImageRef createDragImageFromImage(Image* image) +{ + if (!image) + return 0; + + NativeImageSkia* bitmap = image->nativeImageForCurrentFrame(); + if (!bitmap) + return 0; + + SkBitmap* dragImage = new SkBitmap(); + bitmap->copyTo(dragImage, SkBitmap::kARGB_8888_Config); + return dragImage; +} + +DragImageRef createDragImageIconForCachedImage(CachedImage*) +{ + notImplemented(); + return 0; +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/DragImageRef.h b/Source/WebCore/platform/chromium/DragImageRef.h new file mode 100644 index 0000000..a2d7f8d --- /dev/null +++ b/Source/WebCore/platform/chromium/DragImageRef.h @@ -0,0 +1,48 @@ +// Copyright (c) 2008, 2009, Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#ifndef DragImageRef_h +#define DragImageRef_h + +#if OS(DARWIN) +typedef struct CGImage* CGImageRef; +#else +class SkBitmap; +#endif + +namespace WebCore { + +#if OS(DARWIN) +typedef CGImageRef DragImageRef; +#else +typedef SkBitmap* DragImageRef; +#endif + +} // namespace WebCore + +#endif diff --git a/Source/WebCore/platform/chromium/FileChooserChromium.cpp b/Source/WebCore/platform/chromium/FileChooserChromium.cpp new file mode 100644 index 0000000..3d75b42 --- /dev/null +++ b/Source/WebCore/platform/chromium/FileChooserChromium.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2006, 2007 Apple Inc. All rights reserved. + * Copyright (C) 2008, 2009 Google Inc. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "FileChooser.h" + +#include "FileSystem.h" +#include "LocalizedStrings.h" +#include "StringTruncator.h" + +namespace WebCore { + +String FileChooser::basenameForWidth(const Font& font, int width) const +{ + if (width <= 0) + return String(); + + String string; + if (m_filenames.isEmpty()) + string = fileButtonNoFileSelectedLabel(); + else if (m_filenames.size() == 1) + string = pathGetDisplayFileName(m_filenames[0]); + else + return StringTruncator::rightTruncate(multipleFileUploadText(m_filenames.size()), width, font, false); + + return StringTruncator::centerTruncate(string, static_cast<float>(width), font, false); +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/FileSystemChromium.cpp b/Source/WebCore/platform/chromium/FileSystemChromium.cpp new file mode 100644 index 0000000..d8a1e3f --- /dev/null +++ b/Source/WebCore/platform/chromium/FileSystemChromium.cpp @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "FileSystem.h" + +#include "ChromiumBridge.h" +#include "NotImplemented.h" +#include "PlatformString.h" + +namespace WebCore { + +bool deleteFile(const String& path) +{ + return ChromiumBridge::deleteFile(path); +} + +bool deleteEmptyDirectory(const String& path) +{ + return ChromiumBridge::deleteEmptyDirectory(path); +} + +bool getFileSize(const String& path, long long& result) +{ + return ChromiumBridge::getFileSize(path, result); +} + +bool getFileModificationTime(const String& path, time_t& result) +{ + return ChromiumBridge::getFileModificationTime(path, result); +} + +void revealFolderInOS(const String& path) +{ + ChromiumBridge::revealFolderInOS(path); +} + +String directoryName(const String& path) +{ + return ChromiumBridge::directoryName(path); +} + +String pathByAppendingComponent(const String& path, const String& component) +{ + return ChromiumBridge::pathByAppendingComponent(path, component); +} + +bool makeAllDirectories(const String& path) +{ + return ChromiumBridge::makeAllDirectories(path); +} + +bool fileExists(const String& path) +{ + return ChromiumBridge::fileExists(path); +} + +PlatformFileHandle openFile(const String& path, FileOpenMode mode) +{ + return ChromiumBridge::openFile(path, mode); +} + +void closeFile(PlatformFileHandle& handle) +{ + return ChromiumBridge::closeFile(handle); +} + +long long seekFile(PlatformFileHandle handle, long long offset, FileSeekOrigin origin) +{ + return ChromiumBridge::seekFile(handle, offset, origin); +} + +bool truncateFile(PlatformFileHandle handle, long long offset) +{ + return ChromiumBridge::truncateFile(handle, offset); +} + +int readFromFile(PlatformFileHandle handle, char* data, int length) +{ + return ChromiumBridge::readFromFile(handle, data, length); +} + +int writeToFile(PlatformFileHandle handle, const char* data, int length) +{ + return ChromiumBridge::writeToFile(handle, data, length); +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/FileSystemChromiumLinux.cpp b/Source/WebCore/platform/chromium/FileSystemChromiumLinux.cpp new file mode 100644 index 0000000..24f8da5 --- /dev/null +++ b/Source/WebCore/platform/chromium/FileSystemChromiumLinux.cpp @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "FileSystem.h" + +namespace WebCore { + +String pathGetFileName(const String& path) +{ + return path.substring(path.reverseFind('/') + 1); +} + +String pathGetDisplayFileName(const String& path) +{ + return pathGetFileName(path); +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/FileSystemChromiumMac.mm b/Source/WebCore/platform/chromium/FileSystemChromiumMac.mm new file mode 100644 index 0000000..29563de --- /dev/null +++ b/Source/WebCore/platform/chromium/FileSystemChromiumMac.mm @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "FileSystem.h" + +#import <Foundation/NSFileManager.h> +#include "PlatformString.h" + +namespace WebCore { + +String pathGetFileName(const String& path) +{ + return [path lastPathComponent]; +} + +String pathGetDisplayFileName(const String& path) +{ + return [[NSFileManager defaultManager] displayNameAtPath:path]; +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/FileSystemChromiumWin.cpp b/Source/WebCore/platform/chromium/FileSystemChromiumWin.cpp new file mode 100644 index 0000000..0e605dc --- /dev/null +++ b/Source/WebCore/platform/chromium/FileSystemChromiumWin.cpp @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "FileSystem.h" + +#include <windows.h> +#include <shlwapi.h> + +namespace WebCore { + +String pathGetFileName(const String& path) +{ + return String(PathFindFileName(String(path).charactersWithNullTermination())); +} + +String pathGetDisplayFileName(const String& path) +{ + return pathGetFileName(path); +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/FramelessScrollView.cpp b/Source/WebCore/platform/chromium/FramelessScrollView.cpp new file mode 100644 index 0000000..3fbf2d6 --- /dev/null +++ b/Source/WebCore/platform/chromium/FramelessScrollView.cpp @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "FramelessScrollView.h" + +#include "FramelessScrollViewClient.h" + +namespace WebCore { + +FramelessScrollView::~FramelessScrollView() +{ + // Remove native scrollbars now before we lose the connection to the HostWindow. + setHasHorizontalScrollbar(false); + setHasVerticalScrollbar(false); +} + +void FramelessScrollView::invalidateScrollbarRect(Scrollbar* scrollbar, const IntRect& rect) +{ + // Add in our offset within the ScrollView. + IntRect dirtyRect = rect; + dirtyRect.move(scrollbar->x(), scrollbar->y()); + invalidateRect(dirtyRect); +} + +bool FramelessScrollView::isActive() const +{ + // FIXME + return true; +} + +void FramelessScrollView::invalidateRect(const IntRect& rect) +{ + if (HostWindow* h = hostWindow()) + h->invalidateContentsAndWindow(rect, false /*immediate*/); +} + +HostWindow* FramelessScrollView::hostWindow() const +{ + return const_cast<FramelessScrollViewClient*>(m_client); +} + +IntRect FramelessScrollView::windowClipRect(bool clipToContents) const +{ + return contentsToWindow(visibleContentRect(!clipToContents)); +} + +void FramelessScrollView::paintContents(GraphicsContext*, const IntRect& damageRect) +{ +} + +void FramelessScrollView::contentsResized() +{ +} + +void FramelessScrollView::visibleContentsResized() +{ +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/FramelessScrollView.h b/Source/WebCore/platform/chromium/FramelessScrollView.h new file mode 100644 index 0000000..300f418 --- /dev/null +++ b/Source/WebCore/platform/chromium/FramelessScrollView.h @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef FramelessScrollView_h +#define FramelessScrollView_h + +#include "ScrollView.h" + +namespace WebCore { + + class FramelessScrollViewClient; + class PlatformKeyboardEvent; + class PlatformMouseEvent; + class PlatformWheelEvent; + + // A FramelessScrollView is a ScrollView that can be used to render custom + // content, which does not have an associated Frame. + // + // NOTE: It may be better to just develop a custom subclass of Widget that + // can have scroll bars for this instead of trying to reuse ScrollView. + // + class FramelessScrollView : public ScrollView { + public: + FramelessScrollView() : m_client(0) {} + ~FramelessScrollView(); + + FramelessScrollViewClient* client() const { return m_client; } + void setClient(FramelessScrollViewClient* client) { m_client = client; } + + // Event handlers that subclasses must implement. + virtual bool handleMouseDownEvent(const PlatformMouseEvent&) = 0; + virtual bool handleMouseMoveEvent(const PlatformMouseEvent&) = 0; + virtual bool handleMouseReleaseEvent(const PlatformMouseEvent&) = 0; + virtual bool handleWheelEvent(const PlatformWheelEvent&) = 0; + virtual bool handleKeyEvent(const PlatformKeyboardEvent&) = 0; + + // ScrollbarClient public methods: + virtual void invalidateScrollbarRect(Scrollbar*, const IntRect&); + virtual bool isActive() const; + + // Widget public methods: + virtual void invalidateRect(const IntRect&); + + // ScrollView public methods: + virtual HostWindow* hostWindow() const; + virtual IntRect windowClipRect(bool clipToContents = true) const; + + protected: + // ScrollView protected methods: + virtual void paintContents(GraphicsContext*, const IntRect& damageRect); + virtual void contentsResized(); + virtual void visibleContentsResized(); + + private: + FramelessScrollViewClient* m_client; + }; + +} // namespace WebCore + +#endif diff --git a/Source/WebCore/platform/chromium/FramelessScrollViewClient.h b/Source/WebCore/platform/chromium/FramelessScrollViewClient.h new file mode 100644 index 0000000..35bae10 --- /dev/null +++ b/Source/WebCore/platform/chromium/FramelessScrollViewClient.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef FramelessScrollViewClient_h +#define FramelessScrollViewClient_h + +#include "HostWindow.h" + +namespace WebCore { + class FramelessScrollView; + + class FramelessScrollViewClient : public HostWindow { + public: + virtual void popupClosed(FramelessScrollView* popup_view) = 0; + }; + +} // namespace WebCore + +#endif diff --git a/Source/WebCore/platform/chromium/GeolocationServiceChromium.cpp b/Source/WebCore/platform/chromium/GeolocationServiceChromium.cpp new file mode 100644 index 0000000..c5e73ae --- /dev/null +++ b/Source/WebCore/platform/chromium/GeolocationServiceChromium.cpp @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2010, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "GeolocationServiceChromium.h" + +#include "ChromiumBridge.h" + +#if ENABLE(CLIENT_BASED_GEOLOCATION) +#error "This file should not be compiled when ENABLE(CLIENT_BASED_GEOLOCATION)" +#endif // ENABLE(CLIENT_BASED_GEOLOCATION) + +namespace WebCore { + +GeolocationServiceBridge::~GeolocationServiceBridge() +{ +} + +GeolocationServiceChromium::GeolocationServiceChromium(GeolocationServiceClient* c) + : GeolocationService(c), + m_geolocation(static_cast<Geolocation*>(c)), + m_geolocationServiceBridge(ChromiumBridge::createGeolocationServiceBridge(this)), + m_lastError(PositionError::create(PositionError::POSITION_UNAVAILABLE, "")) +{ +} + +void GeolocationServiceChromium::setIsAllowed(bool allowed) +{ + m_geolocation->setIsAllowed(allowed); +} + +void GeolocationServiceChromium::setLastPosition(PassRefPtr<Geoposition> geoposition) +{ + m_lastPosition = geoposition; + positionChanged(); +} + +void GeolocationServiceChromium::setLastError(int errorCode, const String& message) +{ + m_lastError = PositionError::create(static_cast<PositionError::ErrorCode>(errorCode), message); + errorOccurred(); +} + +Frame* GeolocationServiceChromium::frame() +{ + return m_geolocation->frame(); +} + +bool GeolocationServiceChromium::startUpdating(PositionOptions* options) +{ + return m_geolocationServiceBridge->startUpdating(options); +} + +void GeolocationServiceChromium::stopUpdating() +{ + return m_geolocationServiceBridge->stopUpdating(); +} + +void GeolocationServiceChromium::suspend() +{ + return m_geolocationServiceBridge->suspend(); +} + +void GeolocationServiceChromium::resume() +{ + return m_geolocationServiceBridge->resume(); +} + +Geoposition* GeolocationServiceChromium::lastPosition() const +{ + return m_lastPosition.get(); +} + +PositionError* GeolocationServiceChromium::lastError() const +{ + return m_lastError.get(); +} + +static GeolocationService* createGeolocationServiceChromium(GeolocationServiceClient* c) +{ + return new GeolocationServiceChromium(c); +} + +// Sets up the factory function for GeolocationService. +GeolocationService::FactoryFunction* GeolocationService::s_factoryFunction = &createGeolocationServiceChromium; + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/GeolocationServiceChromium.h b/Source/WebCore/platform/chromium/GeolocationServiceChromium.h new file mode 100644 index 0000000..7e6f633 --- /dev/null +++ b/Source/WebCore/platform/chromium/GeolocationServiceChromium.h @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2010, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef GeolocationServiceChromium_h +#define GeolocationServiceChromium_h + +#include "Geolocation.h" +#include "GeolocationService.h" +#include "Geoposition.h" +#include "PlatformString.h" +#include "PositionError.h" + +namespace WebCore { + +// Provides an interface for GeolocationServiceChromium to call into the embedder. +class GeolocationServiceBridge { +public: + virtual ~GeolocationServiceBridge(); + // Called by GeolocationServiceChromium. + virtual bool startUpdating(PositionOptions*) = 0; + virtual void stopUpdating() = 0; + virtual void suspend() = 0; + virtual void resume() = 0; + + // Called by the embedder, to identify this bridge. + virtual int getBridgeId() const = 0; + virtual void attachBridgeIfNeeded() = 0; +}; + +// This class extends GeolocationService, and uses GeolocationServiceBridge to +// call into the embedder, as well as provides a few extra methods so that the +// embedder can notify permission, position, error, etc. +class GeolocationServiceChromium : public GeolocationService { +public: + explicit GeolocationServiceChromium(GeolocationServiceClient*); + + GeolocationServiceBridge* geolocationServiceBridge() const { return m_geolocationServiceBridge.get(); } + void setIsAllowed(bool allowed); + void setLastPosition(PassRefPtr<Geoposition>); + void setLastError(int errorCode, const String& message); + Frame* frame(); + + // From GeolocationService. + virtual bool startUpdating(PositionOptions*); + virtual void stopUpdating(); + virtual void suspend(); + virtual void resume(); + virtual Geoposition* lastPosition() const; + virtual PositionError* lastError() const; + +private: + Geolocation* m_geolocation; + OwnPtr<GeolocationServiceBridge> m_geolocationServiceBridge; + RefPtr<Geoposition> m_lastPosition; + RefPtr<PositionError> m_lastError; +}; + +} // namespace WebCore + +#endif // GeolocationServiceChromium_h diff --git a/Source/WebCore/platform/chromium/KeyCodeConversion.h b/Source/WebCore/platform/chromium/KeyCodeConversion.h new file mode 100644 index 0000000..8bd0b46 --- /dev/null +++ b/Source/WebCore/platform/chromium/KeyCodeConversion.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef KeyCodeConversion_h +#define KeyCodeConversion_h + +namespace WebCore { + + int windowsKeyCodeForKeyEvent(unsigned keycode); + +} // namespace WebCore + +#endif diff --git a/Source/WebCore/platform/chromium/KeyCodeConversionGtk.cpp b/Source/WebCore/platform/chromium/KeyCodeConversionGtk.cpp new file mode 100644 index 0000000..a7f4245 --- /dev/null +++ b/Source/WebCore/platform/chromium/KeyCodeConversionGtk.cpp @@ -0,0 +1,409 @@ +/* + * Copyright (C) 2006, 2007 Apple Inc. All rights reserved. + * Copyright (C) 2006 Michael Emmel mike.emmel@gmail.com + * Copyright (C) 2007 Holger Hans Peter Freyther + * Copyright (C) 2008 Collabora, Ltd. All rights reserved. + * Copyright (C) 2008, 2009 Google Inc. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +// windowsKeyCodeForKeyEvent is copied from platform/gtk/KeyEventGtk.cpp + +#include "config.h" +#include "KeyCodeConversion.h" + +#include "KeyboardCodes.h" + +#include <gdk/gdkkeysyms.h> + +namespace WebCore { + +int windowsKeyCodeForKeyEvent(unsigned keycode) +{ + switch (keycode) { + case GDK_KP_0: + return VKEY_NUMPAD0; // (60) Numeric keypad 0 key + case GDK_KP_1: + return VKEY_NUMPAD1; // (61) Numeric keypad 1 key + case GDK_KP_2: + return VKEY_NUMPAD2; // (62) Numeric keypad 2 key + case GDK_KP_3: + return VKEY_NUMPAD3; // (63) Numeric keypad 3 key + case GDK_KP_4: + return VKEY_NUMPAD4; // (64) Numeric keypad 4 key + case GDK_KP_5: + return VKEY_NUMPAD5; //(65) Numeric keypad 5 key + case GDK_KP_6: + return VKEY_NUMPAD6; // (66) Numeric keypad 6 key + case GDK_KP_7: + return VKEY_NUMPAD7; // (67) Numeric keypad 7 key + case GDK_KP_8: + return VKEY_NUMPAD8; // (68) Numeric keypad 8 key + case GDK_KP_9: + return VKEY_NUMPAD9; // (69) Numeric keypad 9 key + case GDK_KP_Multiply: + return VKEY_MULTIPLY; // (6A) Multiply key + case GDK_KP_Add: + return VKEY_ADD; // (6B) Add key + case GDK_KP_Subtract: + return VKEY_SUBTRACT; // (6D) Subtract key + case GDK_KP_Decimal: + return VKEY_DECIMAL; // (6E) Decimal key + case GDK_KP_Divide: + return VKEY_DIVIDE; // (6F) Divide key + + case GDK_KP_Page_Up: + return VKEY_PRIOR; // (21) PAGE UP key + case GDK_KP_Page_Down: + return VKEY_NEXT; // (22) PAGE DOWN key + case GDK_KP_End: + return VKEY_END; // (23) END key + case GDK_KP_Home: + return VKEY_HOME; // (24) HOME key + case GDK_KP_Left: + return VKEY_LEFT; // (25) LEFT ARROW key + case GDK_KP_Up: + return VKEY_UP; // (26) UP ARROW key + case GDK_KP_Right: + return VKEY_RIGHT; // (27) RIGHT ARROW key + case GDK_KP_Down: + return VKEY_DOWN; // (28) DOWN ARROW key + + case GDK_BackSpace: + return VKEY_BACK; // (08) BACKSPACE key + case GDK_ISO_Left_Tab: + case GDK_3270_BackTab: + case GDK_Tab: + return VKEY_TAB; // (09) TAB key + case GDK_Clear: + return VKEY_CLEAR; // (0C) CLEAR key + case GDK_ISO_Enter: + case GDK_KP_Enter: + case GDK_Return: + return VKEY_RETURN; //(0D) Return key + case GDK_Shift_L: + case GDK_Shift_R: + return VKEY_SHIFT; // (10) SHIFT key + case GDK_Control_L: + case GDK_Control_R: + return VKEY_CONTROL; // (11) CTRL key + case GDK_Menu: + return VKEY_APPS; // (5D) Applications key (Natural keyboard) + case GDK_Alt_L: + case GDK_Alt_R: + return VKEY_MENU; // (12) ALT key + + case GDK_Pause: + return VKEY_PAUSE; // (13) PAUSE key + case GDK_Caps_Lock: + return VKEY_CAPITAL; // (14) CAPS LOCK key + case GDK_Kana_Lock: + case GDK_Kana_Shift: + return VKEY_KANA; // (15) Input Method Editor (IME) Kana mode + case GDK_Hangul: + return VKEY_HANGUL; // VKEY_HANGUL (15) IME Hangul mode + // VKEY_JUNJA (17) IME Junja mode + // VKEY_FINAL (18) IME final mode + case GDK_Hangul_Hanja: + return VKEY_HANJA; // (19) IME Hanja mode + case GDK_Kanji: + return VKEY_KANJI; // (19) IME Kanji mode + case GDK_Escape: + return VKEY_ESCAPE; // (1B) ESC key + // VKEY_CONVERT (1C) IME convert + // VKEY_NONCONVERT (1D) IME nonconvert + // VKEY_ACCEPT (1E) IME accept + // VKEY_MODECHANGE (1F) IME mode change request + case GDK_space: + return VKEY_SPACE; // (20) SPACEBAR + case GDK_Page_Up: + return VKEY_PRIOR; // (21) PAGE UP key + case GDK_Page_Down: + return VKEY_NEXT; // (22) PAGE DOWN key + case GDK_End: + return VKEY_END; // (23) END key + case GDK_Home: + return VKEY_HOME; // (24) HOME key + case GDK_Left: + return VKEY_LEFT; // (25) LEFT ARROW key + case GDK_Up: + return VKEY_UP; // (26) UP ARROW key + case GDK_Right: + return VKEY_RIGHT; // (27) RIGHT ARROW key + case GDK_Down: + return VKEY_DOWN; // (28) DOWN ARROW key + case GDK_Select: + return VKEY_SELECT; // (29) SELECT key + case GDK_Print: + return VKEY_PRINT; // (2A) PRINT key + case GDK_Execute: + return VKEY_EXECUTE;// (2B) EXECUTE key + //dunno on this + //case GDK_PrintScreen: + // return VKEY_SNAPSHOT; // (2C) PRINT SCREEN key + case GDK_Insert: + return VKEY_INSERT; // (2D) INS key + case GDK_Delete: + return VKEY_DELETE; // (2E) DEL key + case GDK_Help: + return VKEY_HELP; // (2F) HELP key + case GDK_0: + case GDK_parenright: + return VKEY_0; // (30) 0) key + case GDK_1: + case GDK_exclam: + return VKEY_1; // (31) 1 ! key + case GDK_2: + case GDK_at: + return VKEY_2; // (32) 2 & key + case GDK_3: + case GDK_numbersign: + return VKEY_3; //case '3': case '#'; + case GDK_4: + case GDK_dollar: // (34) 4 key '$'; + return VKEY_4; + case GDK_5: + case GDK_percent: + return VKEY_5; // (35) 5 key '%' + case GDK_6: + case GDK_asciicircum: + return VKEY_6; // (36) 6 key '^' + case GDK_7: + case GDK_ampersand: + return VKEY_7; // (37) 7 key case '&' + case GDK_8: + case GDK_asterisk: + return VKEY_8; // (38) 8 key '*' + case GDK_9: + case GDK_parenleft: + return VKEY_9; // (39) 9 key '(' + case GDK_a: + case GDK_A: + return VKEY_A; // (41) A key case 'a': case 'A': return 0x41; + case GDK_b: + case GDK_B: + return VKEY_B; // (42) B key case 'b': case 'B': return 0x42; + case GDK_c: + case GDK_C: + return VKEY_C; // (43) C key case 'c': case 'C': return 0x43; + case GDK_d: + case GDK_D: + return VKEY_D; // (44) D key case 'd': case 'D': return 0x44; + case GDK_e: + case GDK_E: + return VKEY_E; // (45) E key case 'e': case 'E': return 0x45; + case GDK_f: + case GDK_F: + return VKEY_F; // (46) F key case 'f': case 'F': return 0x46; + case GDK_g: + case GDK_G: + return VKEY_G; // (47) G key case 'g': case 'G': return 0x47; + case GDK_h: + case GDK_H: + return VKEY_H; // (48) H key case 'h': case 'H': return 0x48; + case GDK_i: + case GDK_I: + return VKEY_I; // (49) I key case 'i': case 'I': return 0x49; + case GDK_j: + case GDK_J: + return VKEY_J; // (4A) J key case 'j': case 'J': return 0x4A; + case GDK_k: + case GDK_K: + return VKEY_K; // (4B) K key case 'k': case 'K': return 0x4B; + case GDK_l: + case GDK_L: + return VKEY_L; // (4C) L key case 'l': case 'L': return 0x4C; + case GDK_m: + case GDK_M: + return VKEY_M; // (4D) M key case 'm': case 'M': return 0x4D; + case GDK_n: + case GDK_N: + return VKEY_N; // (4E) N key case 'n': case 'N': return 0x4E; + case GDK_o: + case GDK_O: + return VKEY_O; // (4F) O key case 'o': case 'O': return 0x4F; + case GDK_p: + case GDK_P: + return VKEY_P; // (50) P key case 'p': case 'P': return 0x50; + case GDK_q: + case GDK_Q: + return VKEY_Q; // (51) Q key case 'q': case 'Q': return 0x51; + case GDK_r: + case GDK_R: + return VKEY_R; // (52) R key case 'r': case 'R': return 0x52; + case GDK_s: + case GDK_S: + return VKEY_S; // (53) S key case 's': case 'S': return 0x53; + case GDK_t: + case GDK_T: + return VKEY_T; // (54) T key case 't': case 'T': return 0x54; + case GDK_u: + case GDK_U: + return VKEY_U; // (55) U key case 'u': case 'U': return 0x55; + case GDK_v: + case GDK_V: + return VKEY_V; // (56) V key case 'v': case 'V': return 0x56; + case GDK_w: + case GDK_W: + return VKEY_W; // (57) W key case 'w': case 'W': return 0x57; + case GDK_x: + case GDK_X: + return VKEY_X; // (58) X key case 'x': case 'X': return 0x58; + case GDK_y: + case GDK_Y: + return VKEY_Y; // (59) Y key case 'y': case 'Y': return 0x59; + case GDK_z: + case GDK_Z: + return VKEY_Z; // (5A) Z key case 'z': case 'Z': return 0x5A; + case GDK_Meta_L: + case GDK_Super_L: + return VKEY_LWIN; // (5B) Left Windows key (Microsoft Natural keyboard) + case GDK_Meta_R: + case GDK_Super_R: + return VKEY_RWIN; // (5C) Right Windows key (Natural keyboard) + // VKEY_SLEEP (5F) Computer Sleep key + // VKEY_SEPARATOR (6C) Separator key + // VKEY_SUBTRACT (6D) Subtract key + // VKEY_DECIMAL (6E) Decimal key + // VKEY_DIVIDE (6F) Divide key + // handled by key code above + + case GDK_Num_Lock: + return VKEY_NUMLOCK; // (90) NUM LOCK key + + case GDK_Scroll_Lock: + return VKEY_SCROLL; // (91) SCROLL LOCK key + + // VKEY_LSHIFT (A0) Left SHIFT key + // VKEY_RSHIFT (A1) Right SHIFT key + // VKEY_LCONTROL (A2) Left CONTROL key + // VKEY_RCONTROL (A3) Right CONTROL key + // VKEY_LMENU (A4) Left MENU key + // VKEY_RMENU (A5) Right MENU key + // VKEY_BROWSER_BACK (A6) Windows 2000/XP: Browser Back key + // VKEY_BROWSER_FORWARD (A7) Windows 2000/XP: Browser Forward key + // VKEY_BROWSER_REFRESH (A8) Windows 2000/XP: Browser Refresh key + // VKEY_BROWSER_STOP (A9) Windows 2000/XP: Browser Stop key + // VKEY_BROWSER_SEARCH (AA) Windows 2000/XP: Browser Search key + // VKEY_BROWSER_FAVORITES (AB) Windows 2000/XP: Browser Favorites key + // VKEY_BROWSER_HOME (AC) Windows 2000/XP: Browser Start and Home key + // VKEY_VOLUME_MUTE (AD) Windows 2000/XP: Volume Mute key + // VKEY_VOLUME_DOWN (AE) Windows 2000/XP: Volume Down key + // VKEY_VOLUME_UP (AF) Windows 2000/XP: Volume Up key + // VKEY_MEDIA_NEXT_TRACK (B0) Windows 2000/XP: Next Track key + // VKEY_MEDIA_PREV_TRACK (B1) Windows 2000/XP: Previous Track key + // VKEY_MEDIA_STOP (B2) Windows 2000/XP: Stop Media key + // VKEY_MEDIA_PLAY_PAUSE (B3) Windows 2000/XP: Play/Pause Media key + // VKEY_LAUNCH_MAIL (B4) Windows 2000/XP: Start Mail key + // VKEY_LAUNCH_MEDIA_SELECT (B5) Windows 2000/XP: Select Media key + // VKEY_LAUNCH_APP1 (B6) Windows 2000/XP: Start Application 1 key + // VKEY_LAUNCH_APP2 (B7) Windows 2000/XP: Start Application 2 key + + // VKEY_OEM_1 (BA) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the ';:' key + case GDK_semicolon: + case GDK_colon: + return VKEY_OEM_1; //case ';': case ':': return 0xBA; + // VKEY_OEM_PLUS (BB) Windows 2000/XP: For any country/region, the '+' key + case GDK_plus: + case GDK_equal: + return VKEY_OEM_PLUS; //case '=': case '+': return 0xBB; + // VKEY_OEM_COMMA (BC) Windows 2000/XP: For any country/region, the ',' key + case GDK_comma: + case GDK_less: + return VKEY_OEM_COMMA; //case ',': case '<': return 0xBC; + // VKEY_OEM_MINUS (BD) Windows 2000/XP: For any country/region, the '-' key + case GDK_minus: + case GDK_underscore: + return VKEY_OEM_MINUS; //case '-': case '_': return 0xBD; + // VKEY_OEM_PERIOD (BE) Windows 2000/XP: For any country/region, the '.' key + case GDK_period: + case GDK_greater: + return VKEY_OEM_PERIOD; //case '.': case '>': return 0xBE; + // VKEY_OEM_2 (BF) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '/?' key + case GDK_slash: + case GDK_question: + return VKEY_OEM_2; //case '/': case '?': return 0xBF; + // VKEY_OEM_3 (C0) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '`~' key + case GDK_asciitilde: + case GDK_quoteleft: + return VKEY_OEM_3; //case '`': case '~': return 0xC0; + // VKEY_OEM_4 (DB) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '[{' key + case GDK_bracketleft: + case GDK_braceleft: + return VKEY_OEM_4; //case '[': case '{': return 0xDB; + // VKEY_OEM_5 (DC) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '\|' key + case GDK_backslash: + case GDK_bar: + return VKEY_OEM_5; //case '\\': case '|': return 0xDC; + // VKEY_OEM_6 (DD) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the ']}' key + case GDK_bracketright: + case GDK_braceright: + return VKEY_OEM_6; // case ']': case '}': return 0xDD; + // VKEY_OEM_7 (DE) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the 'single-quote/double-quote' key + case GDK_quoteright: + case GDK_quotedbl: + return VKEY_OEM_7; // case '\'': case '"': return 0xDE; + // VKEY_OEM_8 (DF) Used for miscellaneous characters; it can vary by keyboard. + // VKEY_OEM_102 (E2) Windows 2000/XP: Either the angle bracket key or the backslash key on the RT 102-key keyboard + // VKEY_PROCESSKEY (E5) Windows 95/98/Me, Windows NT 4.0, Windows 2000/XP: IME PROCESS key + // VKEY_PACKET (E7) Windows 2000/XP: Used to pass Unicode characters as if they were keystrokes. The VKEY_PACKET key is the low word of a 32-bit Virtual Key value used for non-keyboard input methods. For more information, see Remark in KEYBDINPUT,SendInput, WM_KEYDOWN, and WM_KEYUP + // VKEY_ATTN (F6) Attn key + // VKEY_CRSEL (F7) CrSel key + // VKEY_EXSEL (F8) ExSel key + // VKEY_EREOF (F9) Erase EOF key + // VKEY_PLAY (FA) Play key + // VKEY_ZOOM (FB) Zoom key + // VKEY_NONAME (FC) Reserved for future use + // VKEY_PA1 (FD) PA1 key + // VKEY_OEM_CLEAR (FE) Clear key + case GDK_F1: + case GDK_F2: + case GDK_F3: + case GDK_F4: + case GDK_F5: + case GDK_F6: + case GDK_F7: + case GDK_F8: + case GDK_F9: + case GDK_F10: + case GDK_F11: + case GDK_F12: + case GDK_F13: + case GDK_F14: + case GDK_F15: + case GDK_F16: + case GDK_F17: + case GDK_F18: + case GDK_F19: + case GDK_F20: + case GDK_F21: + case GDK_F22: + case GDK_F23: + case GDK_F24: + return VKEY_F1 + (keycode - GDK_F1); + default: + return 0; + } +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/KeyboardCodes.h b/Source/WebCore/platform/chromium/KeyboardCodes.h new file mode 100644 index 0000000..a58ba35 --- /dev/null +++ b/Source/WebCore/platform/chromium/KeyboardCodes.h @@ -0,0 +1,555 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef KeyboardCodes_h +#define KeyboardCodes_h + +#if OS(WINDOWS) +#include <windows.h> +#endif + +#include "WindowsKeyboardCodes.h" + +namespace WebCore { + + enum { + // VKEY_LBUTTON (01) Left mouse button + // VKEY_RBUTTON (02) Right mouse button + // VKEY_CANCEL (03) Control-break processing + // VKEY_MBUTTON (04) Middle mouse button (three-button mouse) + // VKEY_XBUTTON1 (05) + // VKEY_XBUTTON2 (06) + + // VKEY_BACK (08) BACKSPACE key + VKEY_BACK = VK_BACK, + + // VKEY_TAB (09) TAB key + VKEY_TAB = VK_TAB, + + // VKEY_CLEAR (0C) CLEAR key + VKEY_CLEAR = VK_CLEAR, + + // VKEY_RETURN (0D) + VKEY_RETURN = VK_RETURN, + + // VKEY_SHIFT (10) SHIFT key + VKEY_SHIFT = VK_SHIFT, + + // VKEY_CONTROL (11) CTRL key + VKEY_CONTROL = VK_CONTROL, + + // VKEY_MENU (12) ALT key + VKEY_MENU = VK_MENU, + + // VKEY_PAUSE (13) PAUSE key + VKEY_PAUSE = VK_PAUSE, + + // VKEY_CAPITAL (14) CAPS LOCK key + VKEY_CAPITAL = VK_CAPITAL, + + // VKEY_KANA (15) Input Method Editor (IME) Kana mode + VKEY_KANA = VK_KANA, + + // VKEY_HANGUEL (15) IME Hanguel mode (maintained for compatibility, use VKEY_HANGUL) + // VKEY_HANGUL (15) IME Hangul mode + VKEY_HANGUL = VK_HANGUL, + + // VKEY_JUNJA (17) IME Junja mode + VKEY_JUNJA = VK_JUNJA, + + // VKEY_FINAL (18) IME final mode + VKEY_FINAL = VK_FINAL, + + // VKEY_HANJA (19) IME Hanja mode + VKEY_HANJA = VK_HANJA, + + // VKEY_KANJI (19) IME Kanji mode + VKEY_KANJI = VK_KANJI, + + // VKEY_ESCAPE (1B) ESC key + VKEY_ESCAPE = VK_ESCAPE, + + // VKEY_CONVERT (1C) IME convert + VKEY_CONVERT = VK_CONVERT, + + // VKEY_NONCONVERT (1D) IME nonconvert + VKEY_NONCONVERT = VK_NONCONVERT, + + // VKEY_ACCEPT (1E) IME accept + VKEY_ACCEPT = VK_ACCEPT, + + // VKEY_MODECHANGE (1F) IME mode change request + VKEY_MODECHANGE = VK_MODECHANGE, + + // VKEY_SPACE (20) SPACEBAR + VKEY_SPACE = VK_SPACE, + + // VKEY_PRIOR (21) PAGE UP key + VKEY_PRIOR = VK_PRIOR, + + // VKEY_NEXT (22) PAGE DOWN key + VKEY_NEXT = VK_NEXT, + + // VKEY_END (23) END key + VKEY_END = VK_END, + + // VKEY_HOME (24) HOME key + VKEY_HOME = VK_HOME, + + // VKEY_LEFT (25) LEFT ARROW key + VKEY_LEFT = VK_LEFT, + + // VKEY_UP (26) UP ARROW key + VKEY_UP = VK_UP, + + // VKEY_RIGHT (27) RIGHT ARROW key + VKEY_RIGHT = VK_RIGHT, + + // VKEY_DOWN (28) DOWN ARROW key + VKEY_DOWN = VK_DOWN, + + // VKEY_SELECT (29) SELECT key + VKEY_SELECT = VK_SELECT, + + // VKEY_PRINT (2A) PRINT key + VKEY_PRINT = VK_PRINT, + + // VKEY_EXECUTE (2B) EXECUTE key + VKEY_EXECUTE = VK_EXECUTE, + + // VKEY_SNAPSHOT (2C) PRINT SCREEN key + VKEY_SNAPSHOT = VK_SNAPSHOT, + + // VKEY_INSERT (2D) INS key + VKEY_INSERT = VK_INSERT, + + // VKEY_DELETE (2E) DEL key + VKEY_DELETE = VK_DELETE, + + // VKEY_HELP (2F) HELP key + VKEY_HELP = VK_HELP, + + // (30) 0 key + VKEY_0 = '0', + + // (31) 1 key + VKEY_1 = '1', + + // (32) 2 key + VKEY_2 = '2', + + // (33) 3 key + VKEY_3 = '3', + + // (34) 4 key + VKEY_4 = '4', + + // (35) 5 key, + + VKEY_5 = '5', + + // (36) 6 key + VKEY_6 = '6', + + // (37) 7 key + VKEY_7 = '7', + + // (38) 8 key + VKEY_8 = '8', + + // (39) 9 key + VKEY_9 = '9', + + // (41) A key + VKEY_A = 'A', + + // (42) B key + VKEY_B = 'B', + + // (43) C key + VKEY_C = 'C', + + // (44) D key + VKEY_D = 'D', + + // (45) E key + VKEY_E = 'E', + + // (46) F key + VKEY_F = 'F', + + // (47) G key + VKEY_G = 'G', + + // (48) H key + VKEY_H = 'H', + + // (49) I key + VKEY_I = 'I', + + // (4A) J key + VKEY_J = 'J', + + // (4B) K key + VKEY_K = 'K', + + // (4C) L key + VKEY_L = 'L', + + // (4D) M key + VKEY_M = 'M', + + // (4E) N key + VKEY_N = 'N', + + // (4F) O key + VKEY_O = 'O', + + // (50) P key + VKEY_P = 'P', + + // (51) Q key + VKEY_Q = 'Q', + + // (52) R key + VKEY_R = 'R', + + // (53) S key + VKEY_S = 'S', + + // (54) T key + VKEY_T = 'T', + + // (55) U key + VKEY_U = 'U', + + // (56) V key + VKEY_V = 'V', + + // (57) W key + VKEY_W = 'W', + + // (58) X key + VKEY_X = 'X', + + // (59) Y key + VKEY_Y = 'Y', + + // (5A) Z key + VKEY_Z = 'Z', + + // VKEY_LWIN (5B) Left Windows key (Microsoft Natural keyboard) + VKEY_LWIN = VK_LWIN, + + // VKEY_RWIN (5C) Right Windows key (Natural keyboard) + VKEY_RWIN = VK_RWIN, + + // VKEY_APPS (5D) Applications key (Natural keyboard) + VKEY_APPS = VK_APPS, + + // VKEY_SLEEP (5F) Computer Sleep key + VKEY_SLEEP = VK_SLEEP, + + // VKEY_NUMPAD0 (60) Numeric keypad 0 key + VKEY_NUMPAD0 = VK_NUMPAD0, + + // VKEY_NUMPAD1 (61) Numeric keypad 1 key + VKEY_NUMPAD1 = VK_NUMPAD1, + + // VKEY_NUMPAD2 (62) Numeric keypad 2 key + VKEY_NUMPAD2 = VK_NUMPAD2, + + // VKEY_NUMPAD3 (63) Numeric keypad 3 key + VKEY_NUMPAD3 = VK_NUMPAD3, + + // VKEY_NUMPAD4 (64) Numeric keypad 4 key + VKEY_NUMPAD4 = VK_NUMPAD4, + + // VKEY_NUMPAD5 (65) Numeric keypad 5 key + VKEY_NUMPAD5 = VK_NUMPAD5, + + // VKEY_NUMPAD6 (66) Numeric keypad 6 key + VKEY_NUMPAD6 = VK_NUMPAD6, + + // VKEY_NUMPAD7 (67) Numeric keypad 7 key + VKEY_NUMPAD7 = VK_NUMPAD7, + + // VKEY_NUMPAD8 (68) Numeric keypad 8 key + VKEY_NUMPAD8 = VK_NUMPAD8, + + // VKEY_NUMPAD9 (69) Numeric keypad 9 key + VKEY_NUMPAD9 = VK_NUMPAD9, + + // VKEY_MULTIPLY (6A) Multiply key + VKEY_MULTIPLY = VK_MULTIPLY, + + // VKEY_ADD (6B) Add key + VKEY_ADD = VK_ADD, + + // VKEY_SEPARATOR (6C) Separator key + VKEY_SEPARATOR = VK_SEPARATOR, + + // VKEY_SUBTRACT (6D) Subtract key + VKEY_SUBTRACT = VK_SUBTRACT, + + // VKEY_DECIMAL (6E) Decimal key + VKEY_DECIMAL = VK_DECIMAL, + + // VKEY_DIVIDE (6F) Divide key + VKEY_DIVIDE = VK_DIVIDE, + + // VKEY_F1 (70) F1 key + VKEY_F1 = VK_F1, + + // VKEY_F2 (71) F2 key + VKEY_F2 = VK_F2, + + // VKEY_F3 (72) F3 key + VKEY_F3 = VK_F3, + + // VKEY_F4 (73) F4 key + VKEY_F4 = VK_F4, + + // VKEY_F5 (74) F5 key + VKEY_F5 = VK_F5, + + // VKEY_F6 (75) F6 key + VKEY_F6 = VK_F6, + + // VKEY_F7 (76) F7 key + VKEY_F7 = VK_F7, + + // VKEY_F8 (77) F8 key + VKEY_F8 = VK_F8, + + // VKEY_F9 (78) F9 key + VKEY_F9 = VK_F9, + + // VKEY_F10 (79) F10 key + VKEY_F10 = VK_F10, + + // VKEY_F11 (7A) F11 key + VKEY_F11 = VK_F11, + + // VKEY_F12 (7B) F12 key + VKEY_F12 = VK_F12, + + // VKEY_F13 (7C) F13 key + VKEY_F13 = VK_F13, + + // VKEY_F14 (7D) F14 key + VKEY_F14 = VK_F14, + + // VKEY_F15 (7E) F15 key + VKEY_F15 = VK_F15, + + // VKEY_F16 (7F) F16 key + VKEY_F16 = VK_F16, + + // VKEY_F17 (80H) F17 key + VKEY_F17 = VK_F17, + + // VKEY_F18 (81H) F18 key + VKEY_F18 = VK_F18, + + // VKEY_F19 (82H) F19 key + VKEY_F19 = VK_F19, + + // VKEY_F20 (83H) F20 key + VKEY_F20 = VK_F20, + + // VKEY_F21 (84H) F21 key + VKEY_F21 = VK_F21, + + // VKEY_F22 (85H) F22 key + VKEY_F22 = VK_F22, + + // VKEY_F23 (86H) F23 key + VKEY_F23 = VK_F23, + + // VKEY_F24 (87H) F24 key + VKEY_F24 = VK_F24, + + // VKEY_NUMLOCK (90) NUM LOCK key + VKEY_NUMLOCK = VK_NUMLOCK, + + // VKEY_SCROLL (91) SCROLL LOCK key + VKEY_SCROLL = VK_SCROLL, + + // VKEY_LSHIFT (A0) Left SHIFT key + VKEY_LSHIFT = VK_LSHIFT, + + // VKEY_RSHIFT (A1) Right SHIFT key + VKEY_RSHIFT = VK_RSHIFT, + + // VKEY_LCONTROL (A2) Left CONTROL key + VKEY_LCONTROL = VK_LCONTROL, + + // VKEY_RCONTROL (A3) Right CONTROL key + VKEY_RCONTROL = VK_RCONTROL, + + // VKEY_LMENU (A4) Left MENU key + VKEY_LMENU = VK_LMENU, + + // VKEY_RMENU (A5) Right MENU key + VKEY_RMENU = VK_RMENU, + + // VKEY_BROWSER_BACK (A6) Windows 2000/XP: Browser Back key + VKEY_BROWSER_BACK = VK_BROWSER_BACK, + + // VKEY_BROWSER_FORWARD (A7) Windows 2000/XP: Browser Forward key + VKEY_BROWSER_FORWARD = VK_BROWSER_FORWARD, + + // VKEY_BROWSER_REFRESH (A8) Windows 2000/XP: Browser Refresh key + VKEY_BROWSER_REFRESH = VK_BROWSER_REFRESH, + + // VKEY_BROWSER_STOP (A9) Windows 2000/XP: Browser Stop key + VKEY_BROWSER_STOP = VK_BROWSER_STOP, + + // VKEY_BROWSER_SEARCH (AA) Windows 2000/XP: Browser Search key + VKEY_BROWSER_SEARCH = VK_BROWSER_SEARCH, + + // VKEY_BROWSER_FAVORITES (AB) Windows 2000/XP: Browser Favorites key + VKEY_BROWSER_FAVORITES = VK_BROWSER_FAVORITES, + + // VKEY_BROWSER_HOME (AC) Windows 2000/XP: Browser Start and Home key + VKEY_BROWSER_HOME = VK_BROWSER_HOME, + + // VKEY_VOLUME_MUTE (AD) Windows 2000/XP: Volume Mute key + VKEY_VOLUME_MUTE = VK_VOLUME_MUTE, + + // VKEY_VOLUME_DOWN (AE) Windows 2000/XP: Volume Down key + VKEY_VOLUME_DOWN = VK_VOLUME_DOWN, + + // VKEY_VOLUME_UP (AF) Windows 2000/XP: Volume Up key + VKEY_VOLUME_UP = VK_VOLUME_UP, + + // VKEY_MEDIA_NEXT_TRACK (B0) Windows 2000/XP: Next Track key + VKEY_MEDIA_NEXT_TRACK = VK_MEDIA_NEXT_TRACK, + + // VKEY_MEDIA_PREV_TRACK (B1) Windows 2000/XP: Previous Track key + VKEY_MEDIA_PREV_TRACK = VK_MEDIA_PREV_TRACK, + + // VKEY_MEDIA_STOP (B2) Windows 2000/XP: Stop Media key + VKEY_MEDIA_STOP = VK_MEDIA_STOP, + + // VKEY_MEDIA_PLAY_PAUSE (B3) Windows 2000/XP: Play/Pause Media key + VKEY_MEDIA_PLAY_PAUSE = VK_MEDIA_PLAY_PAUSE, + + // VKEY_LAUNCH_MAIL (B4) Windows 2000/XP: Start Mail key + VKEY_MEDIA_LAUNCH_MAIL = 0xB4, + + // VKEY_LAUNCH_MEDIA_SELECT (B5) Windows 2000/XP: Select Media key + VKEY_MEDIA_LAUNCH_MEDIA_SELECT = 0xB5, + + // VKEY_LAUNCH_APP1 (B6) Windows 2000/XP: Start Application 1 key + VKEY_MEDIA_LAUNCH_APP1 = 0xB6, + + // VKEY_LAUNCH_APP2 (B7) Windows 2000/XP: Start Application 2 key + VKEY_MEDIA_LAUNCH_APP2 = 0xB7, + + // VKEY_OEM_1 (BA) Used for miscellaneous characters, it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the ',:' key + VKEY_OEM_1 = VK_OEM_1, + + // VKEY_OEM_PLUS (BB) Windows 2000/XP: For any country/region, the '+' key + VKEY_OEM_PLUS = VK_OEM_PLUS, + + // VKEY_OEM_COMMA (BC) Windows 2000/XP: For any country/region, the ',' key + VKEY_OEM_COMMA = VK_OEM_COMMA, + + // VKEY_OEM_MINUS (BD) Windows 2000/XP: For any country/region, the '-' key + VKEY_OEM_MINUS = VK_OEM_MINUS, + + // VKEY_OEM_PERIOD (BE) Windows 2000/XP: For any country/region, the '.' key + VKEY_OEM_PERIOD = VK_OEM_PERIOD, + + // VKEY_OEM_2 (BF) Used for miscellaneous characters, it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '/?' key + VKEY_OEM_2 = VK_OEM_2, + + // VKEY_OEM_3 (C0) Used for miscellaneous characters, it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '`~' key + VKEY_OEM_3 = VK_OEM_3, + + // VKEY_OEM_4 (DB) Used for miscellaneous characters, it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '[{' key + VKEY_OEM_4 = VK_OEM_4, + + // VKEY_OEM_5 (DC) Used for miscellaneous characters, it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '\|' key + VKEY_OEM_5 = VK_OEM_5, + + // VKEY_OEM_6 (DD) Used for miscellaneous characters, it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the ']}' key + VKEY_OEM_6 = VK_OEM_6, + + // VKEY_OEM_7 (DE) Used for miscellaneous characters, it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the 'single-quote/double-quote' key + VKEY_OEM_7 = VK_OEM_7, + + // VKEY_OEM_8 (DF) Used for miscellaneous characters, it can vary by keyboard. + VKEY_OEM_8 = VK_OEM_8, + + // VKEY_OEM_102 (E2) Windows 2000/XP: Either the angle bracket key or the backslash key on the RT 102-key keyboard + VKEY_OEM_102 = VK_OEM_102, + + // VKEY_PROCESSKEY (E5) Windows 95/98/Me, Windows NT 4.0, Windows 2000/XP: IME PROCESS key + VKEY_PROCESSKEY = VK_PROCESSKEY, + + // VKEY_PACKET (E7) Windows 2000/XP: Used to pass Unicode characters as if they were keystrokes. The VKEY_PACKET key is the low word of a 32-bit Virtual Key value used for non-keyboard input methods. For more information, see Remark in KEYBDINPUT,SendInput, WM_KEYDOWN, and WM_KEYUP + VKEY_PACKET = VK_PACKET, + + // VKEY_ATTN (F6) Attn key + VKEY_ATTN = VK_ATTN, + + // VKEY_CRSEL (F7) CrSel key + VKEY_CRSEL = VK_CRSEL, + + // VKEY_EXSEL (F8) ExSel key + VKEY_EXSEL = VK_EXSEL, + + // VKEY_EREOF (F9) Erase EOF key + VKEY_EREOF = VK_EREOF, + + // VKEY_PLAY (FA) Play key + VKEY_PLAY = VK_PLAY, + + // VKEY_ZOOM (FB) Zoom key + VKEY_ZOOM = VK_ZOOM, + + // VKEY_NONAME (FC) Reserved for future use + VKEY_NONAME = VK_NONAME, + + // VKEY_PA1 (FD) PA1 key + VKEY_PA1 = VK_PA1, + + // VKEY_OEM_CLEAR (FE) Clear key + VKEY_OEM_CLEAR = VK_OEM_CLEAR, + + VKEY_UNKNOWN = 0 + }; + +} // namespace WebCore + +#endif diff --git a/Source/WebCore/platform/chromium/LanguageChromium.cpp b/Source/WebCore/platform/chromium/LanguageChromium.cpp new file mode 100644 index 0000000..69fe372 --- /dev/null +++ b/Source/WebCore/platform/chromium/LanguageChromium.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "Language.h" + +#include "ChromiumBridge.h" +#include "PlatformString.h" + +namespace WebCore { + +String platformDefaultLanguage() +{ + static String computedDefaultLanguage; + if (computedDefaultLanguage.isEmpty()) + computedDefaultLanguage = ChromiumBridge::computedDefaultLanguage(); + return computedDefaultLanguage; +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/LinkHashChromium.cpp b/Source/WebCore/platform/chromium/LinkHashChromium.cpp new file mode 100644 index 0000000..9cb93ea --- /dev/null +++ b/Source/WebCore/platform/chromium/LinkHashChromium.cpp @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "LinkHash.h" + +#include "ChromiumBridge.h" + +namespace WebCore { + +LinkHash visitedLinkHash(const UChar* url, unsigned length) +{ + return ChromiumBridge::visitedLinkHash(url, length); +} + +LinkHash visitedLinkHash(const KURL& base, const AtomicString& attributeURL) +{ + return ChromiumBridge::visitedLinkHash(base, attributeURL); +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/MIMETypeRegistryChromium.cpp b/Source/WebCore/platform/chromium/MIMETypeRegistryChromium.cpp new file mode 100644 index 0000000..9df8847 --- /dev/null +++ b/Source/WebCore/platform/chromium/MIMETypeRegistryChromium.cpp @@ -0,0 +1,151 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "MIMETypeRegistry.h" + +#include "ChromiumBridge.h" +#include "MediaPlayer.h" +#include "PluginDataChromium.h" +#include <wtf/text/CString.h> + +// NOTE: Unlike other ports, we don't use the shared implementation bits in +// MIMETypeRegistry.cpp. Instead, we need to route most functions via the +// ChromiumBridge to the embedder. + +namespace WebCore { + +String MIMETypeRegistry::getMIMETypeForExtension(const String &ext) +{ + return ChromiumBridge::mimeTypeForExtension(ext); +} + +// Returns the file extension if one is found. Does not include the dot in the +// filename. E.g., 'html'. +String MIMETypeRegistry::getPreferredExtensionForMIMEType(const String& type) +{ + // Prune out any parameters in case they happen to have snuck in there... + // FIXME: Is this really necessary?? + String mimeType = type.substring(0, static_cast<unsigned>(type.find(';'))); + + String ext = ChromiumBridge::preferredExtensionForMIMEType(type); + if (!ext.isEmpty() && ext[0] == '.') + ext = ext.substring(1); + + return ext; +} + +String MIMETypeRegistry::getMIMETypeForPath(const String& path) +{ + int pos = path.reverseFind('.'); + if (pos < 0) + return "application/octet-stream"; + String extension = path.substring(pos + 1); + String mimeType = getMIMETypeForExtension(extension); + if (mimeType.isEmpty()) { + // If there's no mimetype registered for the extension, check to see + // if a plugin can handle the extension. + mimeType = getPluginMimeTypeFromExtension(extension); + } + if (mimeType.isEmpty()) + return "application/octet-stream"; + return mimeType; +} + +bool MIMETypeRegistry::isSupportedImageMIMEType(const String& mimeType) +{ + return ChromiumBridge::isSupportedImageMIMEType(mimeType); +} + +bool MIMETypeRegistry::isSupportedImageResourceMIMEType(const String& mimeType) +{ + return isSupportedImageMIMEType(mimeType); +} + +bool MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(const String& mimeType) +{ + return mimeType == "image/jpeg" || mimeType == "image/png"; +} + +bool MIMETypeRegistry::isSupportedJavaScriptMIMEType(const String& mimeType) +{ + return ChromiumBridge::isSupportedJavaScriptMIMEType(mimeType); +} + +bool MIMETypeRegistry::isSupportedNonImageMIMEType(const String& mimeType) +{ + return ChromiumBridge::isSupportedNonImageMIMEType(mimeType); +} + +bool MIMETypeRegistry::isSupportedMediaMIMEType(const String& mimeType) +{ + HashSet<String> supportedMediaMIMETypes; +#if ENABLE(VIDEO) + MediaPlayer::getSupportedTypes(supportedMediaMIMETypes); +#endif + return !mimeType.isEmpty() && supportedMediaMIMETypes.contains(mimeType); +} + +bool MIMETypeRegistry::isJavaAppletMIMEType(const String& mimeType) +{ + // Since this set is very limited and is likely to remain so we won't bother with the overhead + // of using a hash set. + // Any of the MIME types below may be followed by any number of specific versions of the JVM, + // which is why we use startsWith() + return mimeType.startsWith("application/x-java-applet", false) + || mimeType.startsWith("application/x-java-bean", false) + || mimeType.startsWith("application/x-java-vm", false); +} + +String MIMETypeRegistry::getMediaMIMETypeForExtension(const String&) +{ + return String(); +} + +bool MIMETypeRegistry::isApplicationPluginMIMEType(const String&) +{ + return false; +} + +static HashSet<String>& dummyHashSet() +{ + ASSERT_NOT_REACHED(); + static HashSet<String> dummy; + return dummy; +} + +// NOTE: the following methods should never be reached +HashSet<String>& MIMETypeRegistry::getSupportedImageMIMETypes() { return dummyHashSet(); } +HashSet<String>& MIMETypeRegistry::getSupportedImageResourceMIMETypes() { return dummyHashSet(); } +HashSet<String>& MIMETypeRegistry::getSupportedImageMIMETypesForEncoding() { return dummyHashSet(); } +HashSet<String>& MIMETypeRegistry::getSupportedNonImageMIMETypes() { return dummyHashSet(); } +HashSet<String>& MIMETypeRegistry::getSupportedMediaMIMETypes() { return dummyHashSet(); } + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/PasteboardChromium.cpp b/Source/WebCore/platform/chromium/PasteboardChromium.cpp new file mode 100644 index 0000000..907a4b9 --- /dev/null +++ b/Source/WebCore/platform/chromium/PasteboardChromium.cpp @@ -0,0 +1,197 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "Pasteboard.h" + +#include "ChromiumBridge.h" +#include "ClipboardUtilitiesChromium.h" +#include "DocumentFragment.h" +#include "Document.h" +#include "Element.h" +#include "Frame.h" +#include "HTMLNames.h" +#include "HTMLParserIdioms.h" +#include "Image.h" +#include "KURL.h" +#include "markup.h" +#include "NativeImageSkia.h" +#include "Range.h" +#include "RenderImage.h" + +#if ENABLE(SVG) +#include "SVGNames.h" +#include "XLinkNames.h" +#endif + +namespace WebCore { + +Pasteboard* Pasteboard::generalPasteboard() +{ + static Pasteboard* pasteboard = new Pasteboard; + return pasteboard; +} + +Pasteboard::Pasteboard() + : m_selectionMode(false) +{ +} + +void Pasteboard::clear() +{ + // The ScopedClipboardWriter class takes care of clearing the clipboard's + // previous contents. +} + +bool Pasteboard::isSelectionMode() const +{ + return m_selectionMode; +} + +void Pasteboard::setSelectionMode(bool selectionMode) +{ + m_selectionMode = selectionMode; +} + +void Pasteboard::writeSelection(Range* selectedRange, bool canSmartCopyOrDelete, Frame* frame) +{ + String html = createMarkup(selectedRange, 0, AnnotateForInterchange, false, AbsoluteURLs); + ExceptionCode ec = 0; + KURL url = selectedRange->startContainer(ec)->document()->url(); + String plainText = frame->editor()->selectedText(); +#if OS(WINDOWS) + replaceNewlinesWithWindowsStyleNewlines(plainText); +#endif + replaceNBSPWithSpace(plainText); + + ChromiumBridge::clipboardWriteSelection(html, url, plainText, canSmartCopyOrDelete); +} + +void Pasteboard::writePlainText(const String& text) +{ +#if OS(WINDOWS) + String plainText(text); + replaceNewlinesWithWindowsStyleNewlines(plainText); + ChromiumBridge::clipboardWritePlainText(plainText); +#else + ChromiumBridge::clipboardWritePlainText(text); +#endif +} + +void Pasteboard::writeURL(const KURL& url, const String& titleStr, Frame* frame) +{ + ASSERT(!url.isEmpty()); + + String title(titleStr); + if (title.isEmpty()) { + title = url.lastPathComponent(); + if (title.isEmpty()) + title = url.host(); + } + + ChromiumBridge::clipboardWriteURL(url, title); +} + +void Pasteboard::writeImage(Node* node, const KURL&, const String& title) +{ + ASSERT(node); + ASSERT(node->renderer()); + ASSERT(node->renderer()->isImage()); + RenderImage* renderer = toRenderImage(node->renderer()); + CachedImage* cachedImage = renderer->cachedImage(); + if (!cachedImage || cachedImage->errorOccurred()) + return; + Image* image = cachedImage->image(); + ASSERT(image); + + NativeImagePtr bitmap = image->nativeImageForCurrentFrame(); + if (!bitmap) + return; + + // If the image is wrapped in a link, |url| points to the target of the + // link. This isn't useful to us, so get the actual image URL. + AtomicString urlString; + if (node->hasTagName(HTMLNames::imgTag) || node->hasTagName(HTMLNames::inputTag)) + urlString = static_cast<Element*>(node)->getAttribute(HTMLNames::srcAttr); +#if ENABLE(SVG) + else if (node->hasTagName(SVGNames::imageTag)) + urlString = static_cast<Element*>(node)->getAttribute(XLinkNames::hrefAttr); +#endif + else if (node->hasTagName(HTMLNames::embedTag) || node->hasTagName(HTMLNames::objectTag)) { + Element* element = static_cast<Element*>(node); + urlString = element->getAttribute(element->imageSourceAttributeName()); + } + KURL url = urlString.isEmpty() ? KURL() : node->document()->completeURL(stripLeadingAndTrailingHTMLSpaces(urlString)); + + ChromiumBridge::clipboardWriteImage(bitmap, url, title); +} + +bool Pasteboard::canSmartReplace() +{ + return ChromiumBridge::clipboardIsFormatAvailable(PasteboardPrivate::WebSmartPasteFormat, m_selectionMode ? PasteboardPrivate::SelectionBuffer : PasteboardPrivate::StandardBuffer); +} + +String Pasteboard::plainText(Frame* frame) +{ + return ChromiumBridge::clipboardReadPlainText(m_selectionMode ? PasteboardPrivate::SelectionBuffer : PasteboardPrivate::StandardBuffer); +} + +PassRefPtr<DocumentFragment> Pasteboard::documentFragment(Frame* frame, PassRefPtr<Range> context, bool allowPlainText, bool& chosePlainText) +{ + chosePlainText = false; + PasteboardPrivate::ClipboardBuffer buffer = m_selectionMode ? PasteboardPrivate::SelectionBuffer : PasteboardPrivate::StandardBuffer; + + if (ChromiumBridge::clipboardIsFormatAvailable(PasteboardPrivate::HTMLFormat, buffer)) { + String markup; + KURL srcURL; + ChromiumBridge::clipboardReadHTML(buffer, &markup, &srcURL); + + RefPtr<DocumentFragment> fragment = + createFragmentFromMarkup(frame->document(), markup, srcURL, FragmentScriptingNotAllowed); + if (fragment) + return fragment.release(); + } + + if (allowPlainText) { + String markup = ChromiumBridge::clipboardReadPlainText(buffer); + if (!markup.isEmpty()) { + chosePlainText = true; + + RefPtr<DocumentFragment> fragment = + createFragmentFromText(context.get(), markup); + if (fragment) + return fragment.release(); + } + } + + return 0; +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/PasteboardPrivate.h b/Source/WebCore/platform/chromium/PasteboardPrivate.h new file mode 100644 index 0000000..1de7fe3 --- /dev/null +++ b/Source/WebCore/platform/chromium/PasteboardPrivate.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2008, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef PasteboardPrivate_h +#define PasteboardPrivate_h + +namespace WebCore { + + class PasteboardPrivate { + public: + enum ClipboardFormat { + HTMLFormat, + BookmarkFormat, + WebSmartPasteFormat, + }; + enum ClipboardBuffer { + StandardBuffer, + SelectionBuffer, + DragBuffer, + }; + }; + +} // namespace WebCore + +#endif diff --git a/Source/WebCore/platform/chromium/PlatformBridge.h b/Source/WebCore/platform/chromium/PlatformBridge.h new file mode 100644 index 0000000..ecb7b45 --- /dev/null +++ b/Source/WebCore/platform/chromium/PlatformBridge.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2010 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef PlatformBridge_h +#define PlatformBridge_h + +#include "ChromiumBridge.h" + +namespace WebCore { + +// FIXME: A better name for ChromiumBridge is PlatformBridge. Android already +// uses PlatformBridge so the code that is shared among the Android and Chromium +// ports is gradually moving towards using PlatformBridge. Once the Android +// unforking is done, we will change the name of ChromiumBridge to PlatformBridge +// and merge the two classes into one that will be shared by both ports. +typedef ChromiumBridge PlatformBridge; + +} // namespace WebCore + +#endif // PlatformBridge_h diff --git a/Source/WebCore/platform/chromium/PlatformCursor.h b/Source/WebCore/platform/chromium/PlatformCursor.h new file mode 100644 index 0000000..692c007 --- /dev/null +++ b/Source/WebCore/platform/chromium/PlatformCursor.h @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef PlatformCursor_h +#define PlatformCursor_h + +#include "Image.h" +#include "IntPoint.h" +#include "RefPtr.h" + +namespace WebCore { + + class PlatformCursor { + public: + enum Type { + TypePointer, + TypeCross, + TypeHand, + TypeIBeam, + TypeWait, + TypeHelp, + TypeEastResize, + TypeNorthResize, + TypeNorthEastResize, + TypeNorthWestResize, + TypeSouthResize, + TypeSouthEastResize, + TypeSouthWestResize, + TypeWestResize, + TypeNorthSouthResize, + TypeEastWestResize, + TypeNorthEastSouthWestResize, + TypeNorthWestSouthEastResize, + TypeColumnResize, + TypeRowResize, + TypeMiddlePanning, + TypeEastPanning, + TypeNorthPanning, + TypeNorthEastPanning, + TypeNorthWestPanning, + TypeSouthPanning, + TypeSouthEastPanning, + TypeSouthWestPanning, + TypeWestPanning, + TypeMove, + TypeVerticalText, + TypeCell, + TypeContextMenu, + TypeAlias, + TypeProgress, + TypeNoDrop, + TypeCopy, + TypeNone, + TypeNotAllowed, + TypeZoomIn, + TypeZoomOut, + TypeCustom + }; + + // Cursor.h assumes that it can initialize us to 0. + explicit PlatformCursor(int type = 0) : m_type(TypePointer) {} + + PlatformCursor(Type type) : m_type(type) {} + + PlatformCursor(Image* image, const IntPoint& hotSpot) + : m_image(image) + , m_hotSpot(hotSpot) + , m_type(TypeCustom) {} + + PassRefPtr<Image> customImage() const { return m_image; } + const IntPoint& hotSpot() const { return m_hotSpot; } + Type type() const { return m_type; } + + private: + RefPtr<Image> m_image; + IntPoint m_hotSpot; + Type m_type; + }; + +} // namespace WebCore + +#endif diff --git a/Source/WebCore/platform/chromium/PlatformKeyboardEventChromium.cpp b/Source/WebCore/platform/chromium/PlatformKeyboardEventChromium.cpp new file mode 100644 index 0000000..4e515e5 --- /dev/null +++ b/Source/WebCore/platform/chromium/PlatformKeyboardEventChromium.cpp @@ -0,0 +1,107 @@ +/* + * Copyright (C) 2006, 2007 Apple Inc. All rights reserved. + * Copyright (C) 2008, 2009 Google Inc. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PlatformKeyboardEvent.h" + +#if OS(WINDOWS) +#include <windows.h> +#elif OS(DARWIN) +#import <Carbon/Carbon.h> +#else +#include "NotImplemented.h" +#endif + +namespace WebCore { + +#if OS(WINDOWS) +static const unsigned short HIGH_BIT_MASK_SHORT = 0x8000; +#endif + +void PlatformKeyboardEvent::disambiguateKeyDownEvent(Type type, bool backwardCompatibilityMode) +{ +#if OS(WINDOWS) + // No KeyDown events on Windows to disambiguate. + ASSERT_NOT_REACHED(); +#else + // Can only change type from KeyDown to RawKeyDown or Char, as we lack information for other conversions. + ASSERT(m_type == KeyDown); + ASSERT(type == RawKeyDown || type == Char); + m_type = type; + if (backwardCompatibilityMode) + return; + + if (type == RawKeyDown) { + m_text = String(); + m_unmodifiedText = String(); + } else { + m_keyIdentifier = String(); + m_windowsVirtualKeyCode = 0; +#if OS(DARWIN) + if (m_text.length() == 1 && (m_text[0U] >= 0xF700 && m_text[0U] <= 0xF7FF)) { + // According to NSEvents.h, OpenStep reserves the range 0xF700-0xF8FF for function keys. However, some actual private use characters + // happen to be in this range, e.g. the Apple logo (Option+Shift+K). + // 0xF7FF is an arbitrary cut-off. + m_text = String(); + m_unmodifiedText = String(); + } +#endif + } +#endif +} + +bool PlatformKeyboardEvent::currentCapsLockState() +{ +#if OS(WINDOWS) + // FIXME: Does this even work inside the sandbox? + return GetKeyState(VK_CAPITAL) & 1; +#elif OS(DARWIN) + return GetCurrentKeyModifiers() & alphaLock; +#else + notImplemented(); + return false; +#endif +} + +void PlatformKeyboardEvent::getCurrentModifierState(bool& shiftKey, bool& ctrlKey, bool& altKey, bool& metaKey) +{ +#if OS(WINDOWS) + shiftKey = GetKeyState(VK_SHIFT) & HIGH_BIT_MASK_SHORT; + ctrlKey = GetKeyState(VK_CONTROL) & HIGH_BIT_MASK_SHORT; + altKey = GetKeyState(VK_MENU) & HIGH_BIT_MASK_SHORT; + metaKey = false; +#elif OS(DARWIN) + UInt32 currentModifiers = GetCurrentKeyModifiers(); + shiftKey = currentModifiers & ::shiftKey; + ctrlKey = currentModifiers & ::controlKey; + altKey = currentModifiers & ::optionKey; + metaKey = currentModifiers & ::cmdKey; +#else + notImplemented(); +#endif +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/PlatformScreenChromium.cpp b/Source/WebCore/platform/chromium/PlatformScreenChromium.cpp new file mode 100644 index 0000000..e659ef5 --- /dev/null +++ b/Source/WebCore/platform/chromium/PlatformScreenChromium.cpp @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PlatformScreen.h" + +#include "ChromiumBridge.h" +#include "IntRect.h" + +namespace WebCore { + +int screenDepth(Widget* widget) +{ + return ChromiumBridge::screenDepth(widget); +} + +int screenDepthPerComponent(Widget* widget) +{ + return ChromiumBridge::screenDepthPerComponent(widget); +} + +bool screenIsMonochrome(Widget* widget) +{ + return ChromiumBridge::screenIsMonochrome(widget); +} + +FloatRect screenRect(Widget* widget) +{ + return ChromiumBridge::screenRect(widget); +} + +FloatRect screenAvailableRect(Widget* widget) +{ + return ChromiumBridge::screenAvailableRect(widget); +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/PlatformThemeChromiumGtk.cpp b/Source/WebCore/platform/chromium/PlatformThemeChromiumGtk.cpp new file mode 100644 index 0000000..6529482 --- /dev/null +++ b/Source/WebCore/platform/chromium/PlatformThemeChromiumGtk.cpp @@ -0,0 +1,221 @@ +/* + * Copyright (C) 2010 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PlatformThemeChromiumGtk.h" + +namespace WebCore { + +unsigned PlatformThemeChromiumGtk::s_thumbInactiveColor = 0xeaeaea; +unsigned PlatformThemeChromiumGtk::s_thumbActiveColor = 0xf4f4f4; +unsigned PlatformThemeChromiumGtk::s_trackColor = 0xd3d3d3; + +void PlatformThemeChromiumGtk::setScrollbarColors( + SkColor inactiveColor, SkColor activeColor, SkColor trackColor) +{ + s_thumbInactiveColor = inactiveColor; + s_thumbActiveColor = activeColor; + s_trackColor = trackColor; +} + +static SkScalar clamp(SkScalar value, SkScalar min, SkScalar max) +{ + return std::min(std::max(value, min), max); +} + +SkColor PlatformThemeChromiumGtk::saturateAndBrighten(const SkScalar hsv[3], SkScalar saturateAmount, SkScalar brightenAmount) +{ + SkScalar color[3]; + color[0] = hsv[0]; + color[1] = clamp(hsv[1] + saturateAmount, 0.0, 1.0); + color[2] = clamp(hsv[2] + brightenAmount, 0.0, 1.0); + return SkHSVToColor(color); +} + +SkColor PlatformThemeChromiumGtk::outlineColor(const SkScalar hsv1[3], const SkScalar hsv2[3]) +{ + // GTK Theme engines have way too much control over the layout of + // the scrollbar. We might be able to more closely approximate its + // look-and-feel, if we sent whole images instead of just colors + // from the browser to the renderer. But even then, some themes + // would just break. + // + // So, instead, we don't even try to 100% replicate the look of + // the native scrollbar. We render our own version, but we make + // sure to pick colors that blend in nicely with the system GTK + // theme. In most cases, we can just sample a couple of pixels + // from the system scrollbar and use those colors to draw our + // scrollbar. + // + // This works fine for the track color and the overall thumb + // color. But it fails spectacularly for the outline color used + // around the thumb piece. Not all themes have a clearly defined + // outline. For some of them it is partially transparent, and for + // others the thickness is very unpredictable. + // + // So, instead of trying to approximate the system theme, we + // instead try to compute a reasonable looking choice based on the + // known color of the track and the thumb piece. This is difficult + // when trying to deal both with high- and low-contrast themes, + // and both with positive and inverted themes. + // + // The following code has been tested to look OK with all of the + // default GTK themes. + SkScalar minDiff = clamp((hsv1[1] + hsv2[1]) * 1.2, 0.28, 0.5); + SkScalar diff = clamp(fabs(hsv1[2] - hsv2[2]) / 2, minDiff, 0.5); + + if (hsv1[2] + hsv2[2] > 1.0) + diff = -diff; + + return saturateAndBrighten(hsv2, -0.2, diff); +} + +void PlatformThemeChromiumGtk::paintArrowButton(GraphicsContext* gc, const IntRect& rect, ArrowDirection direction, ControlStates states) +{ + SkCanvas* const canvas = gc->platformContext()->canvas(); + int widthMiddle, lengthMiddle; + SkPaint paint; + if (direction == North || direction == South) { + widthMiddle = rect.width() / 2 + 1; + lengthMiddle = rect.height() / 2 + 1; + } else { + lengthMiddle = rect.width() / 2 + 1; + widthMiddle = rect.height() / 2 + 1; + } + + // Calculate button color. + SkScalar trackHSV[3]; + SkColorToHSV(trackColor(), trackHSV); + SkColor buttonColor = saturateAndBrighten(trackHSV, 0, 0.2); + SkColor backgroundColor = buttonColor; + if (states & PressedState) { + SkScalar buttonHSV[3]; + SkColorToHSV(buttonColor, buttonHSV); + buttonColor = saturateAndBrighten(buttonHSV, 0, -0.1); + } else if (states & HoverState) { + SkScalar buttonHSV[3]; + SkColorToHSV(buttonColor, buttonHSV); + buttonColor = saturateAndBrighten(buttonHSV, 0, 0.05); + } + + SkIRect skrect; + skrect.set(rect.x(), rect.y(), rect.x() + rect.width(), rect.y() + rect.height()); + // Paint the background (the area visible behind the rounded corners). + paint.setColor(backgroundColor); + canvas->drawIRect(skrect, paint); + + // Paint the button's outline and fill the middle + SkPath outline; + switch (direction) { + case North: + outline.moveTo(rect.x() + 0.5, rect.y() + rect.height() + 0.5); + outline.rLineTo(0, -(rect.height() - 2)); + outline.rLineTo(2, -2); + outline.rLineTo(rect.width() - 5, 0); + outline.rLineTo(2, 2); + outline.rLineTo(0, rect.height() - 2); + break; + case South: + outline.moveTo(rect.x() + 0.5, rect.y() - 0.5); + outline.rLineTo(0, rect.height() - 2); + outline.rLineTo(2, 2); + outline.rLineTo(rect.width() - 5, 0); + outline.rLineTo(2, -2); + outline.rLineTo(0, -(rect.height() - 2)); + break; + case East: + outline.moveTo(rect.x() - 0.5, rect.y() + 0.5); + outline.rLineTo(rect.width() - 2, 0); + outline.rLineTo(2, 2); + outline.rLineTo(0, rect.height() - 5); + outline.rLineTo(-2, 2); + outline.rLineTo(-(rect.width() - 2), 0); + break; + case West: + outline.moveTo(rect.x() + rect.width() + 0.5, rect.y() + 0.5); + outline.rLineTo(-(rect.width() - 2), 0); + outline.rLineTo(-2, 2); + outline.rLineTo(0, rect.height() - 5); + outline.rLineTo(2, 2); + outline.rLineTo(rect.width() - 2, 0); + break; + } + outline.close(); + + paint.setStyle(SkPaint::kFill_Style); + paint.setColor(buttonColor); + canvas->drawPath(outline, paint); + + paint.setAntiAlias(true); + paint.setStyle(SkPaint::kStroke_Style); + SkScalar thumbHSV[3]; + SkColorToHSV(thumbInactiveColor(), thumbHSV); + paint.setColor(outlineColor(trackHSV, thumbHSV)); + canvas->drawPath(outline, paint); + + // If the button is disabled or read-only, the arrow is drawn with the outline color. + if (states & EnabledState && !(states & ReadOnlyState)) + paint.setColor(SK_ColorBLACK); + + paint.setAntiAlias(false); + paint.setStyle(SkPaint::kFill_Style); + + SkPath path; + // The constants in this block of code are hand-tailored to produce good + // looking arrows without anti-aliasing. + switch (direction) { + case North: + path.moveTo(rect.x() + widthMiddle - 4, rect.y() + lengthMiddle + 2); + path.rLineTo(7, 0); + path.rLineTo(-4, -4); + break; + case South: + path.moveTo(rect.x() + widthMiddle - 4, rect.y() + lengthMiddle - 3); + path.rLineTo(7, 0); + path.rLineTo(-4, 4); + break; + case East: + path.moveTo(rect.x() + lengthMiddle - 3, rect.y() + widthMiddle - 4); + path.rLineTo(0, 7); + path.rLineTo(4, -4); + break; + case West: + path.moveTo(rect.x() + lengthMiddle + 1, rect.y() + widthMiddle - 5); + path.rLineTo(0, 9); + path.rLineTo(-4, -4); + break; + } + path.close(); + + canvas->drawPath(path, paint); +} + +} // namespace WebCore + diff --git a/Source/WebCore/platform/chromium/PlatformThemeChromiumGtk.h b/Source/WebCore/platform/chromium/PlatformThemeChromiumGtk.h new file mode 100644 index 0000000..bdc2683 --- /dev/null +++ b/Source/WebCore/platform/chromium/PlatformThemeChromiumGtk.h @@ -0,0 +1,71 @@ +/* + * Copyright (C) 2010 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef PlatformThemeChromiumGtk_h +#define PlatformThemeChromiumGtk_h + +#include "PlatformContextSkia.h" +#include "SkColor.h" +#include "SkScalar.h" +#include "ThemeTypes.h" + +namespace WebCore { + +class PlatformThemeChromiumGtk { +public: + enum ArrowDirection { + North, + East, + South, + West, + }; + + static void setScrollbarColors(unsigned inactiveColor, + unsigned activeColor, + unsigned trackColor); + static unsigned thumbInactiveColor() { return s_thumbInactiveColor; } + static unsigned thumbActiveColor() { return s_thumbActiveColor; } + static unsigned trackColor() { return s_trackColor; } + + static SkColor saturateAndBrighten(const SkScalar hsv[3], SkScalar saturateAmount, SkScalar brightenAmount); + static SkColor outlineColor(const SkScalar hsv1[3], const SkScalar hsv2[3]); + static void paintArrowButton(GraphicsContext*, const IntRect&, ArrowDirection, ControlStates); + +private: + PlatformThemeChromiumGtk() {} + + static unsigned s_thumbInactiveColor; + static unsigned s_thumbActiveColor; + static unsigned s_trackColor; +}; + +} // namespace WebCore + +#endif // PlatformThemeChromiumGtk_h diff --git a/Source/WebCore/platform/chromium/PlatformWidget.h b/Source/WebCore/platform/chromium/PlatformWidget.h new file mode 100644 index 0000000..b9dddf3 --- /dev/null +++ b/Source/WebCore/platform/chromium/PlatformWidget.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef PlatformWidget_h +#define PlatformWidget_h + +#include <wtf/StdLibExtras.h> // for intptr_t + +// PlatformWidget is an opaque identifier corresponding to whatever native +// view type the embedder may use. PlatformWidget CANNOT be assumed to be +// a valid pointer. Some embedders may not use this identifier at all. + +typedef intptr_t PlatformWidget; + +#endif diff --git a/Source/WebCore/platform/chromium/PopupMenuChromium.cpp b/Source/WebCore/platform/chromium/PopupMenuChromium.cpp new file mode 100644 index 0000000..04eeb93 --- /dev/null +++ b/Source/WebCore/platform/chromium/PopupMenuChromium.cpp @@ -0,0 +1,1418 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PopupMenuChromium.h" + +#include "CharacterNames.h" +#include "Chrome.h" +#include "ChromeClientChromium.h" +#include "Font.h" +#include "FontSelector.h" +#include "FrameView.h" +#include "Frame.h" +#include "FramelessScrollView.h" +#include "FramelessScrollViewClient.h" +#include "GraphicsContext.h" +#include "IntRect.h" +#include "KeyboardCodes.h" +#include "Page.h" +#include "PlatformKeyboardEvent.h" +#include "PlatformMouseEvent.h" +#include "PlatformScreen.h" +#include "PlatformWheelEvent.h" +#include "PopupMenuClient.h" +#include "RenderTheme.h" +#include "ScrollbarTheme.h" +#include "StringTruncator.h" +#include "SystemTime.h" +#include "UserGestureIndicator.h" + +#include <wtf/CurrentTime.h> + +using namespace WTF; +using namespace Unicode; + +using std::min; +using std::max; + +namespace WebCore { + +typedef unsigned long long TimeStamp; + +static const int kMaxVisibleRows = 20; +static const int kMaxHeight = 500; +static const int kBorderSize = 1; +static const int kTextToLabelPadding = 10; +static const int kLabelToIconPadding = 5; +static const TimeStamp kTypeAheadTimeoutMs = 1000; + +// The settings used for the drop down menu. +// This is the delegate used if none is provided. +static const PopupContainerSettings dropDownSettings = { + true, // setTextOnIndexChange + true, // acceptOnAbandon + false, // loopSelectionNavigation + false, // restrictWidthOfListBox + // display item text in its first strong directional character's directionality. + PopupContainerSettings::FirstStrongDirectionalCharacterDirection, +}; + +// This class uses WebCore code to paint and handle events for a drop-down list +// box ("combobox" on Windows). +class PopupListBox : public FramelessScrollView { +public: + static PassRefPtr<PopupListBox> create(PopupMenuClient* client, const PopupContainerSettings& settings) + { + return adoptRef(new PopupListBox(client, settings)); + } + + // FramelessScrollView + virtual void paint(GraphicsContext*, const IntRect&); + virtual bool handleMouseDownEvent(const PlatformMouseEvent&); + virtual bool handleMouseMoveEvent(const PlatformMouseEvent&); + virtual bool handleMouseReleaseEvent(const PlatformMouseEvent&); + virtual bool handleWheelEvent(const PlatformWheelEvent&); + virtual bool handleKeyEvent(const PlatformKeyboardEvent&); + + // ScrollView + virtual HostWindow* hostWindow() const; + + // PopupListBox methods + + // Hides the popup. + void hidePopup(); + + // Updates our internal list to match the client. + void updateFromElement(); + + // Frees any allocated resources used in a particular popup session. + void clear(); + + // Sets the index of the option that is displayed in the <select> widget in the page + void setOriginalIndex(int index); + + // Gets the index of the item that the user is currently moused over or has selected with + // the keyboard. This is not the same as the original index, since the user has not yet + // accepted this input. + int selectedIndex() const { return m_selectedIndex; } + + // Moves selection down/up the given number of items, scrolling if necessary. + // Positive is down. The resulting index will be clamped to the range + // [0, numItems), and non-option items will be skipped. + void adjustSelectedIndex(int delta); + + // Returns the number of items in the list. + int numItems() const { return static_cast<int>(m_items.size()); } + + void setBaseWidth(int width) { m_baseWidth = width; } + + // Computes the size of widget and children. + void layout(); + + // Returns whether the popup wants to process events for the passed key. + bool isInterestedInEventForKey(int keyCode); + + // Gets the height of a row. + int getRowHeight(int index); + + void setMaxHeight(int maxHeight) { m_maxHeight = maxHeight; } + + void disconnectClient() { m_popupClient = 0; } + + const Vector<PopupItem*>& items() const { return m_items; } + +private: + friend class PopupContainer; + friend class RefCounted<PopupListBox>; + + PopupListBox(PopupMenuClient* client, const PopupContainerSettings& settings) + : m_settings(settings) + , m_originalIndex(0) + , m_selectedIndex(0) + , m_acceptedIndexOnAbandon(-1) + , m_visibleRows(0) + , m_baseWidth(0) + , m_maxHeight(kMaxHeight) + , m_popupClient(client) + , m_repeatingChar(0) + , m_lastCharTime(0) + { + setScrollbarModes(ScrollbarAlwaysOff, ScrollbarAlwaysOff); + } + + ~PopupListBox() + { + clear(); + } + + // Closes the popup + void abandon(); + + // Returns true if the selection can be changed to index. + // Disabled items, or labels cannot be selected. + bool isSelectableItem(int index); + + // Select an index in the list, scrolling if necessary. + void selectIndex(int index); + + // Accepts the selected index as the value to be displayed in the <select> widget on + // the web page, and closes the popup. + void acceptIndex(int index); + + // Clears the selection (so no row appears selected). + void clearSelection(); + + // Scrolls to reveal the given index. + void scrollToRevealRow(int index); + void scrollToRevealSelection() { scrollToRevealRow(m_selectedIndex); } + + // Invalidates the row at the given index. + void invalidateRow(int index); + + // Get the bounds of a row. + IntRect getRowBounds(int index); + + // Converts a point to an index of the row the point is over + int pointToRowIndex(const IntPoint&); + + // Paint an individual row + void paintRow(GraphicsContext*, const IntRect&, int rowIndex); + + // Test if the given point is within the bounds of the popup window. + bool isPointInBounds(const IntPoint&); + + // Called when the user presses a text key. Does a prefix-search of the items. + void typeAheadFind(const PlatformKeyboardEvent&); + + // Returns the font to use for the given row + Font getRowFont(int index); + + // Moves the selection down/up one item, taking care of looping back to the + // first/last element if m_loopSelectionNavigation is true. + void selectPreviousRow(); + void selectNextRow(); + + // The settings that specify the behavior for this Popup window. + PopupContainerSettings m_settings; + + // This is the index of the item marked as "selected" - i.e. displayed in the widget on the + // page. + int m_originalIndex; + + // This is the index of the item that the user is hovered over or has selected using the + // keyboard in the list. They have not confirmed this selection by clicking or pressing + // enter yet however. + int m_selectedIndex; + + // If >= 0, this is the index we should accept if the popup is "abandoned". + // This is used for keyboard navigation, where we want the + // selection to change immediately, and is only used if the settings + // acceptOnAbandon field is true. + int m_acceptedIndexOnAbandon; + + // This is the number of rows visible in the popup. The maximum number visible at a time is + // defined as being kMaxVisibleRows. For a scrolled popup, this can be thought of as the + // page size in data units. + int m_visibleRows; + + // Our suggested width, not including scrollbar. + int m_baseWidth; + + // The maximum height we can be without being off-screen. + int m_maxHeight; + + // A list of the options contained within the <select> + Vector<PopupItem*> m_items; + + // The <select> PopupMenuClient that opened us. + PopupMenuClient* m_popupClient; + + // The scrollbar which has mouse capture. Mouse events go straight to this + // if non-NULL. + RefPtr<Scrollbar> m_capturingScrollbar; + + // The last scrollbar that the mouse was over. Used for mouseover highlights. + RefPtr<Scrollbar> m_lastScrollbarUnderMouse; + + // The string the user has typed so far into the popup. Used for typeAheadFind. + String m_typedString; + + // The char the user has hit repeatedly. Used for typeAheadFind. + UChar m_repeatingChar; + + // The last time the user hit a key. Used for typeAheadFind. + TimeStamp m_lastCharTime; +}; + +static PlatformMouseEvent constructRelativeMouseEvent(const PlatformMouseEvent& e, + FramelessScrollView* parent, + FramelessScrollView* child) +{ + IntPoint pos = parent->convertSelfToChild(child, e.pos()); + + // FIXME: This is a horrible hack since PlatformMouseEvent has no setters for x/y. + PlatformMouseEvent relativeEvent = e; + IntPoint& relativePos = const_cast<IntPoint&>(relativeEvent.pos()); + relativePos.setX(pos.x()); + relativePos.setY(pos.y()); + return relativeEvent; +} + +static PlatformWheelEvent constructRelativeWheelEvent(const PlatformWheelEvent& e, + FramelessScrollView* parent, + FramelessScrollView* child) +{ + IntPoint pos = parent->convertSelfToChild(child, e.pos()); + + // FIXME: This is a horrible hack since PlatformWheelEvent has no setters for x/y. + PlatformWheelEvent relativeEvent = e; + IntPoint& relativePos = const_cast<IntPoint&>(relativeEvent.pos()); + relativePos.setX(pos.x()); + relativePos.setY(pos.y()); + return relativeEvent; +} + +/////////////////////////////////////////////////////////////////////////////// +// PopupContainer implementation + +// static +PassRefPtr<PopupContainer> PopupContainer::create(PopupMenuClient* client, + PopupType popupType, + const PopupContainerSettings& settings) +{ + return adoptRef(new PopupContainer(client, popupType, settings)); +} + +PopupContainer::PopupContainer(PopupMenuClient* client, + PopupType popupType, + const PopupContainerSettings& settings) + : m_listBox(PopupListBox::create(client, settings)) + , m_settings(settings) + , m_popupType(popupType) + , m_popupOpen(false) +{ + setScrollbarModes(ScrollbarAlwaysOff, ScrollbarAlwaysOff); +} + +PopupContainer::~PopupContainer() +{ + if (m_listBox && m_listBox->parent()) + removeChild(m_listBox.get()); +} + +void PopupContainer::showPopup(FrameView* view) +{ + // Pre-layout, our size matches the <select> dropdown control. + int selectHeight = frameRect().height(); + + // Reset the max height to its default value, it will be recomputed below + // if necessary. + m_listBox->setMaxHeight(kMaxHeight); + + // Lay everything out to figure out our preferred size, then tell the view's + // WidgetClient about it. It should assign us a client. + layout(); + + m_frameView = view; + ChromeClientChromium* chromeClient = chromeClientChromium(); + if (chromeClient) { + // If the popup would extend past the bottom of the screen, open upwards + // instead. + FloatRect screen = screenAvailableRect(view); + IntRect widgetRect = chromeClient->windowToScreen(frameRect()); + + if (widgetRect.bottom() > static_cast<int>(screen.bottom())) { + if (widgetRect.y() - widgetRect.height() - selectHeight > 0) { + // There is enough room to open upwards. + widgetRect.move(0, -(widgetRect.height() + selectHeight)); + } else { + // Figure whether upwards or downwards has more room and set the + // maximum number of items. + int spaceAbove = widgetRect.y() - selectHeight; + int spaceBelow = screen.bottom() - widgetRect.y(); + if (spaceAbove > spaceBelow) + m_listBox->setMaxHeight(spaceAbove); + else + m_listBox->setMaxHeight(spaceBelow); + layout(); + // Our size has changed, recompute the widgetRect. + widgetRect = chromeClient->windowToScreen(frameRect()); + // And move upwards if necessary. + if (spaceAbove > spaceBelow) + widgetRect.move(0, -(widgetRect.height() + selectHeight)); + } + } + chromeClient->popupOpened(this, widgetRect, false); + m_popupOpen = true; + } + + if (!m_listBox->parent()) + addChild(m_listBox.get()); + + // Enable scrollbars after the listbox is inserted into the hierarchy, + // so it has a proper WidgetClient. + m_listBox->setVerticalScrollbarMode(ScrollbarAuto); + + m_listBox->scrollToRevealSelection(); + + invalidate(); +} + +void PopupContainer::showExternal(const IntRect& rect, FrameView* v, int index) +{ + if (!listBox()) + return; + + listBox()->setBaseWidth(rect.width()); + listBox()->updateFromElement(); + + if (listBox()->numItems() < 1) { + hidePopup(); + return; + } + + // Adjust the popup position to account for scrolling. + IntPoint location = v->contentsToWindow(rect.location()); + IntRect popupRect(location, rect.size()); + + // Get the ChromeClient and pass it the popup menu's listbox data. + m_frameView = v; + chromeClientChromium()->popupOpened(this, popupRect, true); + + // The popup sends its "closed" notification through its parent. Set the + // parent, even though external popups have no real on-screen widget but a + // native menu (see |PopupListBox::hidePopup()|); + if (!m_listBox->parent()) + addChild(m_listBox.get()); +} + +void PopupContainer::hidePopup() +{ + listBox()->hidePopup(); +} + +void PopupContainer::notifyPopupHidden() +{ + if (!m_popupOpen) + return; + m_popupOpen = false; + chromeClientChromium()->popupClosed(this); +} + +void PopupContainer::layout() +{ + m_listBox->layout(); + + // Place the listbox within our border. + m_listBox->move(kBorderSize, kBorderSize); + + // popupWidth is the width of <select> element. Record it before resize frame. + int popupWidth = frameRect().width(); + // Size ourselves to contain listbox + border. + int listBoxWidth = m_listBox->width() + kBorderSize * 2; + resize(listBoxWidth, m_listBox->height() + kBorderSize * 2); + + // Adjust the starting x-axis for RTL dropdown. For RTL dropdown, the right edge + // of dropdown box should be aligned with the right edge of <select> element box, + // and the dropdown box should be expanded to left if more space needed. + PopupMenuClient* popupClient = m_listBox->m_popupClient; + if (popupClient) { + bool rightAligned = m_listBox->m_popupClient->menuStyle().textDirection() == RTL; + if (rightAligned) + move(x() + popupWidth - listBoxWidth, y()); + } + invalidate(); +} + +bool PopupContainer::handleMouseDownEvent(const PlatformMouseEvent& event) +{ + UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture); + return m_listBox->handleMouseDownEvent( + constructRelativeMouseEvent(event, this, m_listBox.get())); +} + +bool PopupContainer::handleMouseMoveEvent(const PlatformMouseEvent& event) +{ + UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture); + return m_listBox->handleMouseMoveEvent( + constructRelativeMouseEvent(event, this, m_listBox.get())); +} + +bool PopupContainer::handleMouseReleaseEvent(const PlatformMouseEvent& event) +{ + UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture); + return m_listBox->handleMouseReleaseEvent( + constructRelativeMouseEvent(event, this, m_listBox.get())); +} + +bool PopupContainer::handleWheelEvent(const PlatformWheelEvent& event) +{ + UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture); + return m_listBox->handleWheelEvent( + constructRelativeWheelEvent(event, this, m_listBox.get())); +} + +bool PopupContainer::handleKeyEvent(const PlatformKeyboardEvent& event) +{ + UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture); + return m_listBox->handleKeyEvent(event); +} + +void PopupContainer::hide() +{ + m_listBox->abandon(); +} + +void PopupContainer::paint(GraphicsContext* gc, const IntRect& rect) +{ + // adjust coords for scrolled frame + IntRect r = intersection(rect, frameRect()); + int tx = x(); + int ty = y(); + + r.move(-tx, -ty); + + gc->translate(static_cast<float>(tx), static_cast<float>(ty)); + m_listBox->paint(gc, r); + gc->translate(-static_cast<float>(tx), -static_cast<float>(ty)); + + paintBorder(gc, rect); +} + +void PopupContainer::paintBorder(GraphicsContext* gc, const IntRect& rect) +{ + // FIXME: Where do we get the border color from? + Color borderColor(127, 157, 185); + + gc->setStrokeStyle(NoStroke); + gc->setFillColor(borderColor, ColorSpaceDeviceRGB); + + int tx = x(); + int ty = y(); + + // top, left, bottom, right + gc->drawRect(IntRect(tx, ty, width(), kBorderSize)); + gc->drawRect(IntRect(tx, ty, kBorderSize, height())); + gc->drawRect(IntRect(tx, ty + height() - kBorderSize, width(), kBorderSize)); + gc->drawRect(IntRect(tx + width() - kBorderSize, ty, kBorderSize, height())); +} + +bool PopupContainer::isInterestedInEventForKey(int keyCode) +{ + return m_listBox->isInterestedInEventForKey(keyCode); +} + +ChromeClientChromium* PopupContainer::chromeClientChromium() +{ + return static_cast<ChromeClientChromium*>(m_frameView->frame()->page()->chrome()->client()); +} + +void PopupContainer::show(const IntRect& r, FrameView* v, int index) +{ + // The rect is the size of the select box. It's usually larger than we need. + // subtract border size so that usually the container will be displayed + // exactly the same width as the select box. + listBox()->setBaseWidth(max(r.width() - kBorderSize * 2, 0)); + + listBox()->updateFromElement(); + + // We set the selected item in updateFromElement(), and disregard the + // index passed into this function (same as Webkit's PopupMenuWin.cpp) + // FIXME: make sure this is correct, and add an assertion. + // ASSERT(popupWindow(popup)->listBox()->selectedIndex() == index); + + // Convert point to main window coords. + IntPoint location = v->contentsToWindow(r.location()); + + // Move it below the select widget. + location.move(0, r.height()); + + IntRect popupRect(location, r.size()); + setFrameRect(popupRect); + showPopup(v); +} + +void PopupContainer::refresh() +{ + listBox()->updateFromElement(); + layout(); +} + +int PopupContainer::selectedIndex() const +{ + return m_listBox->selectedIndex(); +} + +int PopupContainer::menuItemHeight() const +{ + return m_listBox->getRowHeight(0); +} + +int PopupContainer::menuItemFontSize() const +{ + return m_listBox->getRowFont(0).size(); +} + +PopupMenuStyle PopupContainer::menuStyle() const +{ + return m_listBox->m_popupClient->menuStyle(); +} + +const WTF::Vector<PopupItem*>& PopupContainer:: popupData() const +{ + return m_listBox->items(); +} + +/////////////////////////////////////////////////////////////////////////////// +// PopupListBox implementation + +bool PopupListBox::handleMouseDownEvent(const PlatformMouseEvent& event) +{ + Scrollbar* scrollbar = scrollbarAtPoint(event.pos()); + if (scrollbar) { + m_capturingScrollbar = scrollbar; + m_capturingScrollbar->mouseDown(event); + return true; + } + + if (!isPointInBounds(event.pos())) + abandon(); + + return true; +} + +bool PopupListBox::handleMouseMoveEvent(const PlatformMouseEvent& event) +{ + if (m_capturingScrollbar) { + m_capturingScrollbar->mouseMoved(event); + return true; + } + + Scrollbar* scrollbar = scrollbarAtPoint(event.pos()); + if (m_lastScrollbarUnderMouse != scrollbar) { + // Send mouse exited to the old scrollbar. + if (m_lastScrollbarUnderMouse) + m_lastScrollbarUnderMouse->mouseExited(); + m_lastScrollbarUnderMouse = scrollbar; + } + + if (scrollbar) { + scrollbar->mouseMoved(event); + return true; + } + + if (!isPointInBounds(event.pos())) + return false; + + selectIndex(pointToRowIndex(event.pos())); + return true; +} + +bool PopupListBox::handleMouseReleaseEvent(const PlatformMouseEvent& event) +{ + if (m_capturingScrollbar) { + m_capturingScrollbar->mouseUp(); + m_capturingScrollbar = 0; + return true; + } + + if (!isPointInBounds(event.pos())) + return true; + + acceptIndex(pointToRowIndex(event.pos())); + return true; +} + +bool PopupListBox::handleWheelEvent(const PlatformWheelEvent& event) +{ + if (!isPointInBounds(event.pos())) { + abandon(); + return true; + } + + // Pass it off to the scroll view. + // Sadly, WebCore devs don't understand the whole "const" thing. + wheelEvent(const_cast<PlatformWheelEvent&>(event)); + return true; +} + +// Should be kept in sync with handleKeyEvent(). +bool PopupListBox::isInterestedInEventForKey(int keyCode) +{ + switch (keyCode) { + case VKEY_ESCAPE: + case VKEY_RETURN: + case VKEY_UP: + case VKEY_DOWN: + case VKEY_PRIOR: + case VKEY_NEXT: + case VKEY_HOME: + case VKEY_END: + case VKEY_TAB: + return true; + default: + return false; + } +} + +static bool isCharacterTypeEvent(const PlatformKeyboardEvent& event) +{ + // Check whether the event is a character-typed event or not. + // We use RawKeyDown/Char/KeyUp event scheme on all platforms, + // so PlatformKeyboardEvent::Char (not RawKeyDown) type event + // is considered as character type event. + return event.type() == PlatformKeyboardEvent::Char; +} + +bool PopupListBox::handleKeyEvent(const PlatformKeyboardEvent& event) +{ + if (event.type() == PlatformKeyboardEvent::KeyUp) + return true; + + if (numItems() == 0 && event.windowsVirtualKeyCode() != VKEY_ESCAPE) + return true; + + switch (event.windowsVirtualKeyCode()) { + case VKEY_ESCAPE: + abandon(); // may delete this + return true; + case VKEY_RETURN: + if (m_selectedIndex == -1) { + hidePopup(); + // Don't eat the enter if nothing is selected. + return false; + } + acceptIndex(m_selectedIndex); // may delete this + return true; + case VKEY_UP: + selectPreviousRow(); + break; + case VKEY_DOWN: + selectNextRow(); + break; + case VKEY_PRIOR: + adjustSelectedIndex(-m_visibleRows); + break; + case VKEY_NEXT: + adjustSelectedIndex(m_visibleRows); + break; + case VKEY_HOME: + adjustSelectedIndex(-m_selectedIndex); + break; + case VKEY_END: + adjustSelectedIndex(m_items.size()); + break; + default: + if (!event.ctrlKey() && !event.altKey() && !event.metaKey() + && isPrintableChar(event.windowsVirtualKeyCode()) + && isCharacterTypeEvent(event)) + typeAheadFind(event); + break; + } + + if (m_originalIndex != m_selectedIndex) { + // Keyboard events should update the selection immediately (but we don't + // want to fire the onchange event until the popup is closed, to match + // IE). We change the original index so we revert to that when the + // popup is closed. + if (m_settings.acceptOnAbandon) + m_acceptedIndexOnAbandon = m_selectedIndex; + + setOriginalIndex(m_selectedIndex); + if (m_settings.setTextOnIndexChange) + m_popupClient->setTextFromItem(m_selectedIndex); + } + if (event.windowsVirtualKeyCode() == VKEY_TAB) { + // TAB is a special case as it should select the current item if any and + // advance focus. + if (m_selectedIndex >= 0) { + acceptIndex(m_selectedIndex); // May delete us. + // Return false so the TAB key event is propagated to the page. + return false; + } + // Call abandon() so we honor m_acceptedIndexOnAbandon if set. + abandon(); + // Return false so the TAB key event is propagated to the page. + return false; + } + + return true; +} + +HostWindow* PopupListBox::hostWindow() const +{ + // Our parent is the root ScrollView, so it is the one that has a + // HostWindow. FrameView::hostWindow() works similarly. + return parent() ? parent()->hostWindow() : 0; +} + +// From HTMLSelectElement.cpp +static String stripLeadingWhiteSpace(const String& string) +{ + int length = string.length(); + int i; + for (i = 0; i < length; ++i) + if (string[i] != noBreakSpace + && (string[i] <= 0x7F ? !isspace(string[i]) : (direction(string[i]) != WhiteSpaceNeutral))) + break; + + return string.substring(i, length - i); +} + +// From HTMLSelectElement.cpp, with modifications +void PopupListBox::typeAheadFind(const PlatformKeyboardEvent& event) +{ + TimeStamp now = static_cast<TimeStamp>(currentTime() * 1000.0f); + TimeStamp delta = now - m_lastCharTime; + + // Reset the time when user types in a character. The time gap between + // last character and the current character is used to indicate whether + // user typed in a string or just a character as the search prefix. + m_lastCharTime = now; + + UChar c = event.windowsVirtualKeyCode(); + + String prefix; + int searchStartOffset = 1; + if (delta > kTypeAheadTimeoutMs) { + m_typedString = prefix = String(&c, 1); + m_repeatingChar = c; + } else { + m_typedString.append(c); + + if (c == m_repeatingChar) + // The user is likely trying to cycle through all the items starting with this character, so just search on the character + prefix = String(&c, 1); + else { + m_repeatingChar = 0; + prefix = m_typedString; + searchStartOffset = 0; + } + } + + // Compute a case-folded copy of the prefix string before beginning the search for + // a matching element. This code uses foldCase to work around the fact that + // String::startWith does not fold non-ASCII characters. This code can be changed + // to use startWith once that is fixed. + String prefixWithCaseFolded(prefix.foldCase()); + int itemCount = numItems(); + int index = (max(0, m_selectedIndex) + searchStartOffset) % itemCount; + for (int i = 0; i < itemCount; i++, index = (index + 1) % itemCount) { + if (!isSelectableItem(index)) + continue; + + if (stripLeadingWhiteSpace(m_items[index]->label).foldCase().startsWith(prefixWithCaseFolded)) { + selectIndex(index); + return; + } + } +} + +void PopupListBox::paint(GraphicsContext* gc, const IntRect& rect) +{ + // adjust coords for scrolled frame + IntRect r = intersection(rect, frameRect()); + int tx = x() - scrollX(); + int ty = y() - scrollY(); + + r.move(-tx, -ty); + + // set clip rect to match revised damage rect + gc->save(); + gc->translate(static_cast<float>(tx), static_cast<float>(ty)); + gc->clip(r); + + // FIXME: Can we optimize scrolling to not require repainting the entire + // window? Should we? + for (int i = 0; i < numItems(); ++i) + paintRow(gc, r, i); + + // Special case for an empty popup. + if (numItems() == 0) + gc->fillRect(r, Color::white, ColorSpaceDeviceRGB); + + gc->restore(); + + ScrollView::paint(gc, rect); +} + +static const int separatorPadding = 4; +static const int separatorHeight = 1; + +void PopupListBox::paintRow(GraphicsContext* gc, const IntRect& rect, int rowIndex) +{ + // This code is based largely on RenderListBox::paint* methods. + + IntRect rowRect = getRowBounds(rowIndex); + if (!rowRect.intersects(rect)) + return; + + PopupMenuStyle style = m_popupClient->itemStyle(rowIndex); + + // Paint background + Color backColor, textColor, labelColor; + if (rowIndex == m_selectedIndex) { + backColor = RenderTheme::defaultTheme()->activeListBoxSelectionBackgroundColor(); + textColor = RenderTheme::defaultTheme()->activeListBoxSelectionForegroundColor(); + labelColor = textColor; + } else { + backColor = style.backgroundColor(); + textColor = style.foregroundColor(); + // FIXME: for now the label color is hard-coded. It should be added to + // the PopupMenuStyle. + labelColor = Color(115, 115, 115); + } + + // If we have a transparent background, make sure it has a color to blend + // against. + if (backColor.hasAlpha()) + gc->fillRect(rowRect, Color::white, ColorSpaceDeviceRGB); + + gc->fillRect(rowRect, backColor, ColorSpaceDeviceRGB); + + if (m_popupClient->itemIsSeparator(rowIndex)) { + IntRect separatorRect( + rowRect.x() + separatorPadding, + rowRect.y() + (rowRect.height() - separatorHeight) / 2, + rowRect.width() - 2 * separatorPadding, separatorHeight); + gc->fillRect(separatorRect, textColor, ColorSpaceDeviceRGB); + return; + } + + if (!style.isVisible()) + return; + + gc->setFillColor(textColor, ColorSpaceDeviceRGB); + + Font itemFont = getRowFont(rowIndex); + // FIXME: http://crbug.com/19872 We should get the padding of individual option + // elements. This probably implies changes to PopupMenuClient. + bool rightAligned = m_popupClient->menuStyle().textDirection() == RTL; + int textX = 0; + int maxWidth = 0; + if (rightAligned) + maxWidth = rowRect.width() - max(0, m_popupClient->clientPaddingRight() - m_popupClient->clientInsetRight()); + else { + textX = max(0, m_popupClient->clientPaddingLeft() - m_popupClient->clientInsetLeft()); + maxWidth = rowRect.width() - textX; + } + // Prepare text to be drawn. + String itemText = m_popupClient->itemText(rowIndex); + String itemLabel = m_popupClient->itemLabel(rowIndex); + String itemIcon = m_popupClient->itemIcon(rowIndex); + if (m_settings.restrictWidthOfListBox) { // Truncate strings to fit in. + // FIXME: We should leftTruncate for the rtl case. + // StringTruncator::leftTruncate would have to be implemented. + String str = StringTruncator::rightTruncate(itemText, maxWidth, itemFont); + if (str != itemText) { + itemText = str; + // Don't display the label or icon, we already don't have enough room for the item text. + itemLabel = ""; + itemIcon = ""; + } else if (!itemLabel.isEmpty()) { + int availableWidth = maxWidth - kTextToLabelPadding - + StringTruncator::width(itemText, itemFont); + itemLabel = StringTruncator::rightTruncate(itemLabel, availableWidth, itemFont); + } + } + + // Prepare the directionality to draw text. + bool rtl = false; + if (m_settings.itemTextDirectionalityHint == PopupContainerSettings::DOMElementDirection) + rtl = style.textDirection() == RTL; + else if (m_settings.itemTextDirectionalityHint == + PopupContainerSettings::FirstStrongDirectionalCharacterDirection) + rtl = itemText.defaultWritingDirection() == WTF::Unicode::RightToLeft; + TextRun textRun(itemText.characters(), itemText.length(), false, 0, 0, rtl); + // If the text is right-to-left, make it right-aligned by adjusting its + // beginning position. + if (rightAligned) + textX += maxWidth - itemFont.width(textRun); + + // Draw the item text. + int textY = rowRect.y() + itemFont.ascent() + (rowRect.height() - itemFont.height()) / 2; + gc->drawBidiText(itemFont, textRun, IntPoint(textX, textY)); + + // We are using the left padding as the right padding includes room for the scroll-bar which + // does not show in this case. + int rightPadding = max(0, m_popupClient->clientPaddingLeft() - m_popupClient->clientInsetLeft()); + int remainingWidth = rowRect.width() - rightPadding; + + // Draw the icon if applicable. + RefPtr<Image> image(Image::loadPlatformResource(itemIcon.utf8().data())); + if (image && !image->isNull()) { + IntRect imageRect = image->rect(); + remainingWidth -= (imageRect.width() + kLabelToIconPadding); + imageRect.setX(rowRect.width() - rightPadding - imageRect.width()); + imageRect.setY(rowRect.y() + (rowRect.height() - imageRect.height()) / 2); + gc->drawImage(image.get(), ColorSpaceDeviceRGB, imageRect); + } + + // Draw the the label if applicable. + if (itemLabel.isEmpty()) + return; + TextRun labelTextRun(itemLabel.characters(), itemLabel.length(), false, 0, 0, rtl); + if (rightAligned) + textX = max(0, m_popupClient->clientPaddingLeft() - m_popupClient->clientInsetLeft()); + else + textX = remainingWidth - itemFont.width(labelTextRun); + + gc->setFillColor(labelColor, ColorSpaceDeviceRGB); + gc->drawBidiText(itemFont, labelTextRun, IntPoint(textX, textY)); +} + +Font PopupListBox::getRowFont(int rowIndex) +{ + Font itemFont = m_popupClient->itemStyle(rowIndex).font(); + if (m_popupClient->itemIsLabel(rowIndex)) { + // Bold-ify labels (ie, an <optgroup> heading). + FontDescription d = itemFont.fontDescription(); + d.setWeight(FontWeightBold); + Font font(d, itemFont.letterSpacing(), itemFont.wordSpacing()); + font.update(0); + return font; + } + + return itemFont; +} + +void PopupListBox::abandon() +{ + RefPtr<PopupListBox> keepAlive(this); + + m_selectedIndex = m_originalIndex; + + hidePopup(); + + if (m_acceptedIndexOnAbandon >= 0) { + if (m_popupClient) + m_popupClient->valueChanged(m_acceptedIndexOnAbandon); + m_acceptedIndexOnAbandon = -1; + } +} + +int PopupListBox::pointToRowIndex(const IntPoint& point) +{ + int y = scrollY() + point.y(); + + // FIXME: binary search if perf matters. + for (int i = 0; i < numItems(); ++i) { + if (y < m_items[i]->yOffset) + return i-1; + } + + // Last item? + if (y < contentsHeight()) + return m_items.size()-1; + + return -1; +} + +void PopupListBox::acceptIndex(int index) +{ + // Clear m_acceptedIndexOnAbandon once user accepts the selected index. + if (m_acceptedIndexOnAbandon >= 0) + m_acceptedIndexOnAbandon = -1; + + if (index >= numItems()) + return; + + if (index < 0) { + if (m_popupClient) { + // Enter pressed with no selection, just close the popup. + hidePopup(); + } + return; + } + + if (isSelectableItem(index)) { + RefPtr<PopupListBox> keepAlive(this); + + // Hide ourselves first since valueChanged may have numerous side-effects. + hidePopup(); + + // Tell the <select> PopupMenuClient what index was selected. + m_popupClient->valueChanged(index); + } +} + +void PopupListBox::selectIndex(int index) +{ + if (index < 0 || index >= numItems()) + return; + + bool isSelectable = isSelectableItem(index); + if (index != m_selectedIndex && isSelectable) { + invalidateRow(m_selectedIndex); + m_selectedIndex = index; + invalidateRow(m_selectedIndex); + + scrollToRevealSelection(); + m_popupClient->selectionChanged(m_selectedIndex); + } else if (!isSelectable) { + clearSelection(); + } +} + +void PopupListBox::setOriginalIndex(int index) +{ + m_originalIndex = m_selectedIndex = index; +} + +int PopupListBox::getRowHeight(int index) +{ + if (index < 0) + return 0; + + if (m_popupClient->itemStyle(index).isDisplayNone()) + return 0; + + String icon = m_popupClient->itemIcon(index); + RefPtr<Image> image(Image::loadPlatformResource(icon.utf8().data())); + + int fontHeight = getRowFont(index).height(); + int iconHeight = (image && !image->isNull()) ? image->rect().height() : 0; + + return max(fontHeight, iconHeight); +} + +IntRect PopupListBox::getRowBounds(int index) +{ + if (index < 0) + return IntRect(0, 0, visibleWidth(), getRowHeight(index)); + + return IntRect(0, m_items[index]->yOffset, visibleWidth(), getRowHeight(index)); +} + +void PopupListBox::invalidateRow(int index) +{ + if (index < 0) + return; + + // Invalidate in the window contents, as FramelessScrollView::invalidateRect + // paints in the window coordinates. + invalidateRect(contentsToWindow(getRowBounds(index))); +} + +void PopupListBox::scrollToRevealRow(int index) +{ + if (index < 0) + return; + + IntRect rowRect = getRowBounds(index); + + if (rowRect.y() < scrollY()) { + // Row is above current scroll position, scroll up. + ScrollView::setScrollPosition(IntPoint(0, rowRect.y())); + } else if (rowRect.bottom() > scrollY() + visibleHeight()) { + // Row is below current scroll position, scroll down. + ScrollView::setScrollPosition(IntPoint(0, rowRect.bottom() - visibleHeight())); + } +} + +bool PopupListBox::isSelectableItem(int index) +{ + ASSERT(index >= 0 && index < numItems()); + return m_items[index]->type == PopupItem::TypeOption && m_popupClient->itemIsEnabled(index); +} + +void PopupListBox::clearSelection() +{ + if (m_selectedIndex != -1) { + invalidateRow(m_selectedIndex); + m_selectedIndex = -1; + m_popupClient->selectionCleared(); + } +} + +void PopupListBox::selectNextRow() +{ + if (!m_settings.loopSelectionNavigation || m_selectedIndex != numItems() - 1) { + adjustSelectedIndex(1); + return; + } + + // We are moving past the last item, no row should be selected. + clearSelection(); +} + +void PopupListBox::selectPreviousRow() +{ + if (!m_settings.loopSelectionNavigation || m_selectedIndex > 0) { + adjustSelectedIndex(-1); + return; + } + + if (m_selectedIndex == 0) { + // We are moving past the first item, clear the selection. + clearSelection(); + return; + } + + // No row is selected, jump to the last item. + selectIndex(numItems() - 1); + scrollToRevealSelection(); +} + +void PopupListBox::adjustSelectedIndex(int delta) +{ + int targetIndex = m_selectedIndex + delta; + targetIndex = min(max(targetIndex, 0), numItems() - 1); + if (!isSelectableItem(targetIndex)) { + // We didn't land on an option. Try to find one. + // We try to select the closest index to target, prioritizing any in + // the range [current, target]. + + int dir = delta > 0 ? 1 : -1; + int testIndex = m_selectedIndex; + int bestIndex = m_selectedIndex; + bool passedTarget = false; + while (testIndex >= 0 && testIndex < numItems()) { + if (isSelectableItem(testIndex)) + bestIndex = testIndex; + if (testIndex == targetIndex) + passedTarget = true; + if (passedTarget && bestIndex != m_selectedIndex) + break; + + testIndex += dir; + } + + // Pick the best index, which may mean we don't change. + targetIndex = bestIndex; + } + + // Select the new index, and ensure its visible. We do this regardless of + // whether the selection changed to ensure keyboard events always bring the + // selection into view. + selectIndex(targetIndex); + scrollToRevealSelection(); +} + +void PopupListBox::hidePopup() +{ + if (parent()) { + PopupContainer* container = static_cast<PopupContainer*>(parent()); + if (container->client()) + container->client()->popupClosed(container); + container->notifyPopupHidden(); + } + + if (m_popupClient) + m_popupClient->popupDidHide(); +} + +void PopupListBox::updateFromElement() +{ + clear(); + + int size = m_popupClient->listSize(); + for (int i = 0; i < size; ++i) { + PopupItem::Type type; + if (m_popupClient->itemIsSeparator(i)) + type = PopupItem::TypeSeparator; + else if (m_popupClient->itemIsLabel(i)) + type = PopupItem::TypeGroup; + else + type = PopupItem::TypeOption; + m_items.append(new PopupItem(m_popupClient->itemText(i), type)); + m_items[i]->enabled = isSelectableItem(i); + } + + m_selectedIndex = m_popupClient->selectedIndex(); + setOriginalIndex(m_selectedIndex); + + layout(); +} + +void PopupListBox::layout() +{ + // Size our child items. + int baseWidth = 0; + int paddingWidth = 0; + int y = 0; + for (int i = 0; i < numItems(); ++i) { + // Place the item vertically. + m_items[i]->yOffset = y; + if (m_popupClient->itemStyle(i).isDisplayNone()) + continue; + y += getRowHeight(i); + + // Ensure the popup is wide enough to fit this item. + Font itemFont = getRowFont(i); + String text = m_popupClient->itemText(i); + String label = m_popupClient->itemLabel(i); + String icon = m_popupClient->itemIcon(i); + RefPtr<Image> iconImage(Image::loadPlatformResource(icon.utf8().data())); + int width = 0; + if (!text.isEmpty()) + width = itemFont.width(TextRun(text)); + if (!label.isEmpty()) { + if (width > 0) + width += kTextToLabelPadding; + width += itemFont.width(TextRun(label)); + } + if (iconImage && !iconImage->isNull()) { + if (width > 0) + width += kLabelToIconPadding; + width += iconImage->rect().width(); + } + + baseWidth = max(baseWidth, width); + // FIXME: http://b/1210481 We should get the padding of individual option elements. + paddingWidth = max(paddingWidth, + m_popupClient->clientPaddingLeft() + m_popupClient->clientPaddingRight()); + } + + // Calculate scroll bar width. + int windowHeight = 0; + +#if OS(DARWIN) + // Set the popup's window to contain all available items on Mac only, which + // uses native controls that manage their own scrolling. This allows hit + // testing to work when selecting items in popups that have more menu entries + // than the maximum window size. + m_visibleRows = numItems(); +#else + m_visibleRows = min(numItems(), kMaxVisibleRows); +#endif + + for (int i = 0; i < m_visibleRows; ++i) { + int rowHeight = getRowHeight(i); + +#if !OS(DARWIN) + // Only clip the window height for non-Mac platforms. + if (windowHeight + rowHeight > m_maxHeight) { + m_visibleRows = i; + break; + } +#endif + + windowHeight += rowHeight; + } + + // Set our widget and scrollable contents sizes. + int scrollbarWidth = 0; + if (m_visibleRows < numItems()) + scrollbarWidth = ScrollbarTheme::nativeTheme()->scrollbarThickness(); + + int windowWidth; + int contentWidth; + if (m_settings.restrictWidthOfListBox) { + windowWidth = m_baseWidth; + contentWidth = m_baseWidth - scrollbarWidth - paddingWidth; + } else { + windowWidth = baseWidth + scrollbarWidth + paddingWidth; + contentWidth = baseWidth; + + if (windowWidth < m_baseWidth) { + windowWidth = m_baseWidth; + contentWidth = m_baseWidth - scrollbarWidth - paddingWidth; + } else + m_baseWidth = baseWidth; + } + + resize(windowWidth, windowHeight); + setContentsSize(IntSize(contentWidth, getRowBounds(numItems() - 1).bottom())); + + if (hostWindow()) + scrollToRevealSelection(); + + invalidate(); +} + +void PopupListBox::clear() +{ + for (Vector<PopupItem*>::iterator it = m_items.begin(); it != m_items.end(); ++it) + delete *it; + m_items.clear(); +} + +bool PopupListBox::isPointInBounds(const IntPoint& point) +{ + return numItems() != 0 && IntRect(0, 0, width(), height()).contains(point); +} + +/////////////////////////////////////////////////////////////////////////////// +// PopupMenuChromium implementation +// +// Note: you cannot add methods to this class, since it is defined above the +// portability layer. To access methods and properties on the +// popup widgets, use |popupWindow| above. + +PopupMenuChromium::PopupMenuChromium(PopupMenuClient* client) + : m_popupClient(client) +{ +} + +PopupMenuChromium::~PopupMenuChromium() +{ + // When the PopupMenuChromium is destroyed, the client could already have been + // deleted. + if (p.popup) + p.popup->listBox()->disconnectClient(); + hide(); +} + +// The Mac Chromium implementation relies on external control (a Cocoa control) +// to display, handle the input tracking and menu item selection for the popup. +// Windows and Linux Chromium let our WebKit port handle the display, while +// another process manages the popup window and input handling. +void PopupMenuChromium::show(const IntRect& r, FrameView* v, int index) +{ + if (!p.popup) + p.popup = PopupContainer::create(client(), PopupContainer::Select, dropDownSettings); +#if OS(DARWIN) + p.popup->showExternal(r, v, index); +#else + p.popup->show(r, v, index); +#endif +} + +void PopupMenuChromium::hide() +{ + if (p.popup) + p.popup->hide(); +} + +void PopupMenuChromium::updateFromElement() +{ + p.popup->listBox()->updateFromElement(); +} + + +void PopupMenuChromium::disconnectClient() +{ + m_popupClient = 0; +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/PopupMenuChromium.h b/Source/WebCore/platform/chromium/PopupMenuChromium.h new file mode 100644 index 0000000..ca47ccf --- /dev/null +++ b/Source/WebCore/platform/chromium/PopupMenuChromium.h @@ -0,0 +1,227 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef PopupMenuChromium_h +#define PopupMenuChromium_h + +#include "config.h" + +#include "FramelessScrollView.h" +#include "IntRect.h" +#include "PlatformString.h" +#include "PopupMenu.h" +#include "PopupMenuPrivate.h" +#include "PopupMenuStyle.h" + +namespace WebCore { + +class ChromeClientChromium; +class FrameView; +class PopupListBox; +class PopupMenuClient; + +// A container for the data for each menu item (e.g. represented by <option> +// or <optgroup> in a <select> widget) and is used by PopupListBox. +struct PopupItem { + enum Type { + TypeOption, + TypeGroup, + TypeSeparator + }; + + PopupItem(const String& label, Type type) + : label(label) + , type(type) + , yOffset(0) + { + } + String label; + Type type; + int yOffset; // y offset of this item, relative to the top of the popup. + bool enabled; +}; + +// FIXME: Our FramelessScrollView classes should probably implement HostWindow! + +// The PopupContainer class holds a PopupListBox (see cpp file). Its sole purpose is to be +// able to draw a border around its child. All its paint/event handling is +// just forwarded to the child listBox (with the appropriate transforms). +// NOTE: this class is exposed so it can be instantiated direcly for the +// autofill popup. We cannot use the Popup class directly in that case as the +// autofill popup should not be focused when shown and we want to forward the +// key events to it (through handleKeyEvent). + +struct PopupContainerSettings { + // Whether the PopupMenuClient should be told to change its text when a + // new item is selected by using the arrow keys. + bool setTextOnIndexChange; + + // Whether the selection should be accepted when the popup menu is + // closed (through ESC being pressed or the focus going away). + // Note that when TAB is pressed, the selection is always accepted + // regardless of this setting. + bool acceptOnAbandon; + + // Whether we should move the selection to the first/last item when + // the user presses down/up arrow keys and the last/first item is + // selected. + bool loopSelectionNavigation; + + // Whether we should restrict the width of the PopupListBox or not. + // Autocomplete popups are restricted, combo-boxes (select tags) aren't. + bool restrictWidthOfListBox; + + // A hint on the display directionality of the item text in popup menu. + // + // We could either display the items in the drop-down using its DOM element's + // directionality, or we could display the items in the drop-down using heuristics: + // such as in its first strong directionality character's direction. + // Please refer to the discussion (especially comment #7 and #10) in + // https://bugs.webkit.org/show_bug.cgi?id=27889 for details. + enum DirectionalityHint { + // Use the DOM element's directionality to display the item text in popup menu. + DOMElementDirection, + // Use the item text's first strong-directional character's directionality + // to display the item text in popup menu. + FirstStrongDirectionalCharacterDirection, + }; + DirectionalityHint itemTextDirectionalityHint; +}; + +class PopupContainer : public FramelessScrollView { +public: + enum PopupType { + Select, // HTML select popup. + Suggestion, // Autocomplete/autofill popup. + }; + + static PassRefPtr<PopupContainer> create(PopupMenuClient*, PopupType, + const PopupContainerSettings&); + + // Whether a key event should be sent to this popup. + virtual bool isInterestedInEventForKey(int keyCode); + + // FramelessScrollView + virtual void paint(GraphicsContext*, const IntRect&); + virtual void hide(); + virtual bool handleMouseDownEvent(const PlatformMouseEvent&); + virtual bool handleMouseMoveEvent(const PlatformMouseEvent&); + virtual bool handleMouseReleaseEvent(const PlatformMouseEvent&); + virtual bool handleWheelEvent(const PlatformWheelEvent&); + virtual bool handleKeyEvent(const PlatformKeyboardEvent&); + + // PopupContainer methods + + // Show the popup + void showPopup(FrameView*); + + // Used on Mac Chromium for HTML select popup menus. + void showExternal(const IntRect&, FrameView*, int index); + + // Show the popup in the specified rect for the specified frame. + // Note: this code was somehow arbitrarily factored-out of the Popup class + // so WebViewImpl can create a PopupContainer. This method is used for + // displaying auto complete popup menus on Mac Chromium, and for all + // popups on other platforms. + void show(const IntRect&, FrameView*, int index); + + // Hides the popup. + void hidePopup(); + + // The popup was hidden. + void notifyPopupHidden(); + + // Compute size of widget and children. + void layout(); + + PopupListBox* listBox() const { return m_listBox.get(); } + + // Gets the index of the item that the user is currently moused-over or + // has selected with the keyboard up/down arrows. + int selectedIndex() const; + + // Refresh the popup values from the PopupMenuClient. + void refresh(); + + // The menu per-item data. + const WTF::Vector<PopupItem*>& popupData() const; + + // The height of a row in the menu. + int menuItemHeight() const; + + // The size of the font being used. + int menuItemFontSize() const; + + // The style of the menu being used. + PopupMenuStyle menuStyle() const; + + PopupType popupType() const { return m_popupType; } + +private: + friend class WTF::RefCounted<PopupContainer>; + + PopupContainer(PopupMenuClient*, PopupType popupType, const PopupContainerSettings&); + ~PopupContainer(); + + // Paint the border. + void paintBorder(GraphicsContext*, const IntRect&); + + // Returns the ChromeClient of the page this popup is associated with. + ChromeClientChromium* chromeClientChromium(); + + RefPtr<PopupListBox> m_listBox; + RefPtr<FrameView> m_frameView; + + PopupContainerSettings m_settings; + PopupType m_popupType; + // Whether the popup is currently open. + bool m_popupOpen; +}; + +class PopupMenuChromium : public PopupMenu { +public: + PopupMenuChromium(PopupMenuClient*); + ~PopupMenuChromium(); + + virtual void show(const IntRect&, FrameView*, int index); + virtual void hide(); + virtual void updateFromElement(); + virtual void disconnectClient(); + +private: + PopupMenuClient* client() const { return m_popupClient; } + + PopupMenuClient* m_popupClient; + PopupMenuPrivate p; +}; + +} // namespace WebCore + +#endif diff --git a/Source/WebCore/platform/chromium/PopupMenuPrivate.h b/Source/WebCore/platform/chromium/PopupMenuPrivate.h new file mode 100644 index 0000000..fb8f850 --- /dev/null +++ b/Source/WebCore/platform/chromium/PopupMenuPrivate.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef PopupMenuPrivate_h +#define PopupMenuPrivate_h + +#include "RefPtr.h" + +namespace WebCore { + + class PopupContainer; + + struct PopupMenuPrivate { + RefPtr<PopupContainer> popup; + }; + +} // namespace WebCore + +#endif diff --git a/Source/WebCore/platform/chromium/ReadableDataObject.cpp b/Source/WebCore/platform/chromium/ReadableDataObject.cpp new file mode 100644 index 0000000..97c481b --- /dev/null +++ b/Source/WebCore/platform/chromium/ReadableDataObject.cpp @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2010 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "ReadableDataObject.h" + +#include "ChromiumBridge.h" +#include "ClipboardMimeTypes.h" +#include "Pasteboard.h" +#include "PasteboardPrivate.h" + +namespace WebCore { + +static PasteboardPrivate::ClipboardBuffer clipboardBuffer(Clipboard::ClipboardType clipboardType) +{ + return clipboardType == Clipboard::DragAndDrop ? PasteboardPrivate::DragBuffer : PasteboardPrivate::StandardBuffer; +} + +PassRefPtr<ReadableDataObject> ReadableDataObject::create(Clipboard::ClipboardType clipboardType) +{ + return adoptRef(new ReadableDataObject(clipboardType)); +} + +ReadableDataObject::ReadableDataObject(Clipboard::ClipboardType clipboardType) + : m_clipboardType(clipboardType) + , m_containsFilenames(false) + , m_isTypeCacheInitialized(false) +{ +} + +bool ReadableDataObject::hasData() const +{ + ensureTypeCacheInitialized(); + return !m_types.isEmpty() || m_containsFilenames; +} + +HashSet<String> ReadableDataObject::types() const +{ + ensureTypeCacheInitialized(); + return m_types; +} + +String ReadableDataObject::getData(const String& type, bool& succeeded) const +{ + String data; + String ignoredMetadata; + // Since the Chromium-side bridge isn't complete yet, we special case this + // for copy-and-paste, since that code path no longer uses + // ChromiumDataObjectLegacy. + if (m_clipboardType == Clipboard::CopyAndPaste) { + if (type == mimeTypeTextPlain) { + PasteboardPrivate::ClipboardBuffer buffer = + Pasteboard::generalPasteboard()->isSelectionMode() ? + PasteboardPrivate::SelectionBuffer : + PasteboardPrivate::StandardBuffer; + data = ChromiumBridge::clipboardReadPlainText(buffer); + } else if (type == mimeTypeTextHTML) { + PasteboardPrivate::ClipboardBuffer buffer = + Pasteboard::generalPasteboard()->isSelectionMode() ? + PasteboardPrivate::SelectionBuffer : + PasteboardPrivate::StandardBuffer; + KURL ignoredSourceURL; + ChromiumBridge::clipboardReadHTML(buffer, &data, &ignoredSourceURL); + } + succeeded = !data.isEmpty(); + return data; + } + succeeded = ChromiumBridge::clipboardReadData( + clipboardBuffer(m_clipboardType), type, data, ignoredMetadata); + return data; +} + +String ReadableDataObject::urlTitle() const +{ + String ignoredData; + String urlTitle; + ChromiumBridge::clipboardReadData( + clipboardBuffer(m_clipboardType), mimeTypeTextURIList, ignoredData, urlTitle); + return urlTitle; +} + +KURL ReadableDataObject::htmlBaseUrl() const +{ + String ignoredData; + String htmlBaseUrl; + ChromiumBridge::clipboardReadData( + clipboardBuffer(m_clipboardType), mimeTypeTextHTML, ignoredData, htmlBaseUrl); + return KURL(ParsedURLString, htmlBaseUrl); +} + +bool ReadableDataObject::containsFilenames() const +{ + ensureTypeCacheInitialized(); + return m_containsFilenames; +} + +Vector<String> ReadableDataObject::filenames() const +{ + return ChromiumBridge::clipboardReadFilenames(clipboardBuffer(m_clipboardType)); +} + +void ReadableDataObject::ensureTypeCacheInitialized() const +{ + if (m_isTypeCacheInitialized) + return; + + m_types = ChromiumBridge::clipboardReadAvailableTypes( + clipboardBuffer(m_clipboardType), &m_containsFilenames); + m_isTypeCacheInitialized = true; +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/ReadableDataObject.h b/Source/WebCore/platform/chromium/ReadableDataObject.h new file mode 100644 index 0000000..027e0ed --- /dev/null +++ b/Source/WebCore/platform/chromium/ReadableDataObject.h @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2010 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef ReadableDataObject_h +#define ReadableDataObject_h + +#include "Clipboard.h" +#include "PlatformString.h" +#include <wtf/HashSet.h> +#include <wtf/RefCounted.h> +#include <wtf/RefPtr.h> +#include <wtf/text/StringHash.h> + +namespace WebCore { + +// Used for one way communication of drag/drop and copy/paste data from the +// browser to the renderer. +class ReadableDataObject : public RefCounted<ReadableDataObject> { +public: + static PassRefPtr<ReadableDataObject> create(Clipboard::ClipboardType); + + bool hasData() const; + HashSet<String> types() const; + String getData(const String& type, bool& succeeded) const; + + String urlTitle() const; + KURL htmlBaseUrl() const; + + bool containsFilenames() const; + Vector<String> filenames() const; + +private: + explicit ReadableDataObject(Clipboard::ClipboardType); + + // This isn't always const... but most of the time it is. + void ensureTypeCacheInitialized() const; + + Clipboard::ClipboardType m_clipboardType; + + // To avoid making a lot of IPC calls for each drag event, we cache some + // values in the renderer. + mutable HashSet<String> m_types; + mutable bool m_containsFilenames; + mutable bool m_isTypeCacheInitialized; +}; + +} // namespace WebCore + +#endif diff --git a/Source/WebCore/platform/chromium/SSLKeyGeneratorChromium.cpp b/Source/WebCore/platform/chromium/SSLKeyGeneratorChromium.cpp new file mode 100644 index 0000000..49d9517 --- /dev/null +++ b/Source/WebCore/platform/chromium/SSLKeyGeneratorChromium.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "SSLKeyGenerator.h" + +#include "ChromiumBridge.h" +#include "PlatformString.h" + +namespace WebCore { + +// These are defined in webkit/api/src/LocalizedStrings.cpp. +String keygenMenuHighGradeKeySize(); +String keygenMenuMediumGradeKeySize(); + +void getSupportedKeySizes(Vector<String>& sizes) +{ + sizes.resize(2); + sizes[0] = keygenMenuHighGradeKeySize(); + sizes[1] = keygenMenuMediumGradeKeySize(); +} + +String signedPublicKeyAndChallengeString(unsigned keySizeIndex, + const String& challengeString, + const KURL& url) +{ + return ChromiumBridge::signedPublicKeyAndChallengeString(keySizeIndex, + challengeString, + url); +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/ScrollbarThemeChromium.cpp b/Source/WebCore/platform/chromium/ScrollbarThemeChromium.cpp new file mode 100644 index 0000000..234d0ee --- /dev/null +++ b/Source/WebCore/platform/chromium/ScrollbarThemeChromium.cpp @@ -0,0 +1,149 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * Copyright (C) 2008, 2009 Google Inc. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "ScrollbarThemeChromium.h" + +#include "ChromiumBridge.h" +#include "PlatformMouseEvent.h" +#include "Scrollbar.h" +#include "ScrollbarClient.h" +#include "ScrollbarThemeComposite.h" + +// ----------------------------------------------------------------------------- +// This file contains scrollbar theme code that is cross platform. Additional +// members of ScrollbarThemeChromium can be found in the platform specific files +// ----------------------------------------------------------------------------- + +namespace WebCore { + +bool ScrollbarThemeChromium::hasThumb(Scrollbar* scrollbar) +{ + // This method is just called as a paint-time optimization to see if + // painting the thumb can be skipped. We don't have to be exact here. + return thumbLength(scrollbar) > 0; +} + +IntRect ScrollbarThemeChromium::backButtonRect(Scrollbar* scrollbar, ScrollbarPart part, bool) +{ + // Windows and Linux just have single arrows. + if (part == BackButtonEndPart) + return IntRect(); + + IntSize size = buttonSize(scrollbar); + return IntRect(scrollbar->x(), scrollbar->y(), size.width(), size.height()); +} + +IntRect ScrollbarThemeChromium::forwardButtonRect(Scrollbar* scrollbar, ScrollbarPart part, bool) +{ + // Windows and Linux just have single arrows. + if (part == ForwardButtonStartPart) + return IntRect(); + + IntSize size = buttonSize(scrollbar); + int x, y; + if (scrollbar->orientation() == HorizontalScrollbar) { + x = scrollbar->x() + scrollbar->width() - size.width(); + y = scrollbar->y(); + } else { + x = scrollbar->x(); + y = scrollbar->y() + scrollbar->height() - size.height(); + } + return IntRect(x, y, size.width(), size.height()); +} + +IntRect ScrollbarThemeChromium::trackRect(Scrollbar* scrollbar, bool) +{ + IntSize bs = buttonSize(scrollbar); + // The buttons at the top and bottom of the scrollbar are square, so the + // thickness of the scrollbar is also their height. + int thickness = scrollbarThickness(scrollbar->controlSize()); + if (scrollbar->orientation() == HorizontalScrollbar) { + // Once the scrollbar becomes smaller than the natural size of the + // two buttons, the track disappears. + if (scrollbar->width() < 2 * thickness) + return IntRect(); + return IntRect(scrollbar->x() + bs.width(), scrollbar->y(), scrollbar->width() - 2 * bs.width(), thickness); + } + if (scrollbar->height() < 2 * thickness) + return IntRect(); + return IntRect(scrollbar->x(), scrollbar->y() + bs.height(), thickness, scrollbar->height() - 2 * bs.height()); +} + +void ScrollbarThemeChromium::paintTrackBackground(GraphicsContext* context, Scrollbar* scrollbar, const IntRect& rect) +{ + // Just assume a forward track part. We only paint the track as a single piece when there is no thumb. + if (!hasThumb(scrollbar)) + paintTrackPiece(context, scrollbar, rect, ForwardTrackPart); +} + +void ScrollbarThemeChromium::paintTickmarks(GraphicsContext* context, Scrollbar* scrollbar, const IntRect& rect) +{ + if (scrollbar->orientation() != VerticalScrollbar) + return; + + if (rect.height() <= 0 || rect.width() <= 0) + return; // nothing to draw on. + + // Get the tickmarks for the frameview. + Vector<IntRect> tickmarks; + scrollbar->client()->getTickmarks(tickmarks); + if (!tickmarks.size()) + return; + + // Get the image for the tickmarks. + static RefPtr<Image> dash = Image::loadPlatformResource("tickmarkDash"); + if (dash->isNull()) { + ASSERT_NOT_REACHED(); + return; + } + + context->save(); + + for (Vector<IntRect>::const_iterator i = tickmarks.begin(); i != tickmarks.end(); ++i) { + // Calculate how far down (in %) the tick-mark should appear. + const float percent = static_cast<float>(i->y()) / scrollbar->totalSize(); + + // Calculate how far down (in pixels) the tick-mark should appear. + const int yPos = rect.topLeft().y() + (rect.height() * percent); + + IntPoint tick(scrollbar->x(), yPos); + context->drawImage(dash.get(), ColorSpaceDeviceRGB, tick); + } + + context->restore(); +} + +void ScrollbarThemeChromium::paintScrollCorner(ScrollView* view, GraphicsContext* context, const IntRect& cornerRect) +{ + // ScrollbarThemeComposite::paintScrollCorner incorrectly assumes that the + // ScrollView is a FrameView (see FramelessScrollView), so we cannot let + // that code run. For FrameView's this is correct since we don't do custom + // scrollbar corner rendering, which ScrollbarThemeComposite supports. + ScrollbarTheme::paintScrollCorner(view, context, cornerRect); +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/ScrollbarThemeChromium.h b/Source/WebCore/platform/chromium/ScrollbarThemeChromium.h new file mode 100644 index 0000000..b53d4ae --- /dev/null +++ b/Source/WebCore/platform/chromium/ScrollbarThemeChromium.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef ScrollbarThemeChromium_h +#define ScrollbarThemeChromium_h + +#include "ScrollbarThemeComposite.h" + +namespace WebCore { + + class PlatformMouseEvent; + + // This class contains the scrollbar code which is shared between Chromium + // Windows and Linux. + class ScrollbarThemeChromium : public ScrollbarThemeComposite { + protected: + virtual bool hasButtons(Scrollbar*) { return true; } + virtual bool hasThumb(Scrollbar*); + + virtual IntRect backButtonRect(Scrollbar*, ScrollbarPart, bool painting = false); + virtual IntRect forwardButtonRect(Scrollbar*, ScrollbarPart, bool painting = false); + virtual IntRect trackRect(Scrollbar*, bool painting = false); + + virtual void paintScrollCorner(ScrollView*, GraphicsContext*, const IntRect&); + + virtual void paintTrackBackground(GraphicsContext*, Scrollbar*, const IntRect&); + virtual void paintTickmarks(GraphicsContext*, Scrollbar*, const IntRect&); + + virtual IntSize buttonSize(Scrollbar*) = 0; + }; +} // namespace WebCore + +#endif diff --git a/Source/WebCore/platform/chromium/ScrollbarThemeChromiumLinux.cpp b/Source/WebCore/platform/chromium/ScrollbarThemeChromiumLinux.cpp new file mode 100644 index 0000000..ba10953 --- /dev/null +++ b/Source/WebCore/platform/chromium/ScrollbarThemeChromiumLinux.cpp @@ -0,0 +1,151 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "ScrollbarThemeChromiumLinux.h" + +#include "ChromiumBridge.h" +#include "PlatformMouseEvent.h" +#include "Scrollbar.h" + +namespace WebCore { + +ScrollbarTheme* ScrollbarTheme::nativeTheme() +{ + static ScrollbarThemeChromiumLinux theme; + return &theme; +} + +int ScrollbarThemeChromiumLinux::scrollbarThickness(ScrollbarControlSize controlSize) +{ + // Horiz and Vert scrollbars are the same thickness. + IntSize scrollbarSize = ChromiumBridge::getThemePartSize(ChromiumBridge::PartScrollbarVerticalTrack); + return scrollbarSize.width(); +} + +void ScrollbarThemeChromiumLinux::paintTrackPiece(GraphicsContext* gc, Scrollbar* scrollbar, const IntRect& rect, ScrollbarPart partType) +{ + ChromiumBridge::ThemePaintState state = scrollbar->hoveredPart() == partType ? ChromiumBridge::StateHover : ChromiumBridge::StateNormal; + IntRect alignRect = trackRect(scrollbar, false); + ChromiumBridge::ThemePaintExtraParams extraParams; + extraParams.scrollbarTrack.trackX = alignRect.x(); + extraParams.scrollbarTrack.trackY = alignRect.y(); + extraParams.scrollbarTrack.trackWidth = alignRect.width(); + extraParams.scrollbarTrack.trackHeight = alignRect.height(); + ChromiumBridge::paintThemePart( + gc, + scrollbar->orientation() == HorizontalScrollbar ? ChromiumBridge::PartScrollbarHorizontalTrack : ChromiumBridge::PartScrollbarVerticalTrack, + state, + rect, + &extraParams); +} + +void ScrollbarThemeChromiumLinux::paintButton(GraphicsContext* gc, Scrollbar* scrollbar, const IntRect& rect, ScrollbarPart part) +{ + ChromiumBridge::ThemePart paintPart; + ChromiumBridge::ThemePaintState state = ChromiumBridge::StateNormal; + bool checkMin = false; + bool checkMax = false; + if (scrollbar->orientation() == HorizontalScrollbar) { + if (part == BackButtonStartPart) { + paintPart = ChromiumBridge::PartScrollbarLeftArrow; + checkMin = true; + } else { + paintPart = ChromiumBridge::PartScrollbarRightArrow; + checkMax = true; + } + } else { + if (part == BackButtonStartPart) { + paintPart = ChromiumBridge::PartScrollbarUpArrow; + checkMin = true; + } else { + paintPart = ChromiumBridge::PartScrollbarDownArrow; + checkMax = true; + } + } + if ((checkMin && (scrollbar->currentPos() <= 0)) + || (checkMax && scrollbar->currentPos() == scrollbar->maximum())) { + state = ChromiumBridge::StateDisabled; + } else { + if (part == scrollbar->pressedPart()) + state = ChromiumBridge::StatePressed; + else if (part == scrollbar->hoveredPart()) + state = ChromiumBridge::StateHover; + } + ChromiumBridge::paintThemePart(gc, paintPart, state, rect, 0); +} + +void ScrollbarThemeChromiumLinux::paintThumb(GraphicsContext* gc, Scrollbar* scrollbar, const IntRect& rect) +{ + ChromiumBridge::ThemePaintState state; + + if (scrollbar->pressedPart() == ThumbPart) + state = ChromiumBridge::StatePressed; + else if (scrollbar->hoveredPart() == ThumbPart) + state = ChromiumBridge::StateHover; + else + state = ChromiumBridge::StateNormal; + ChromiumBridge::paintThemePart( + gc, + scrollbar->orientation() == HorizontalScrollbar ? ChromiumBridge::PartScrollbarHorizontalThumb : ChromiumBridge::PartScrollbarVerticalThumb, + state, + rect, + 0); +} + +bool ScrollbarThemeChromiumLinux::shouldCenterOnThumb(Scrollbar*, const PlatformMouseEvent& evt) +{ + return (evt.shiftKey() && evt.button() == LeftButton) || (evt.button() == MiddleButton); +} + +IntSize ScrollbarThemeChromiumLinux::buttonSize(Scrollbar* scrollbar) +{ + if (scrollbar->orientation() == VerticalScrollbar) { + IntSize size = ChromiumBridge::getThemePartSize(ChromiumBridge::PartScrollbarUpArrow); + return IntSize(size.width(), scrollbar->height() < 2 * size.height() ? scrollbar->height() / 2 : size.height()); + } + + // HorizontalScrollbar + IntSize size = ChromiumBridge::getThemePartSize(ChromiumBridge::PartScrollbarLeftArrow); + return IntSize(scrollbar->width() < 2 * size.width() ? scrollbar->width() / 2 : size.width(), size.height()); +} + +int ScrollbarThemeChromiumLinux::minimumThumbLength(Scrollbar* scrollbar) +{ + if (scrollbar->orientation() == VerticalScrollbar) { + IntSize size = ChromiumBridge::getThemePartSize(ChromiumBridge::PartScrollbarVerticalThumb); + return size.height(); + } + + IntSize size = ChromiumBridge::getThemePartSize(ChromiumBridge::PartScrollbarHorizontalThumb); + return size.width(); +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/ScrollbarThemeChromiumLinux.h b/Source/WebCore/platform/chromium/ScrollbarThemeChromiumLinux.h new file mode 100644 index 0000000..8e802e7 --- /dev/null +++ b/Source/WebCore/platform/chromium/ScrollbarThemeChromiumLinux.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef ScrollbarThemeChromiumLinux_h +#define ScrollbarThemeChromiumLinux_h + +#include "ScrollbarThemeChromium.h" + +namespace WebCore { + class ScrollbarThemeChromiumLinux : public ScrollbarThemeChromium { + public: + virtual int scrollbarThickness(ScrollbarControlSize); + + protected: + virtual void paintTrackPiece(GraphicsContext*, Scrollbar*, const IntRect&, ScrollbarPart); + virtual void paintButton(GraphicsContext*, Scrollbar*, const IntRect&, ScrollbarPart); + virtual void paintThumb(GraphicsContext*, Scrollbar*, const IntRect&); + virtual bool shouldCenterOnThumb(Scrollbar*, const PlatformMouseEvent&); + virtual IntSize buttonSize(Scrollbar*); + virtual int minimumThumbLength(Scrollbar*); + }; +} // namespace WebCore + +#endif diff --git a/Source/WebCore/platform/chromium/ScrollbarThemeChromiumMac.h b/Source/WebCore/platform/chromium/ScrollbarThemeChromiumMac.h new file mode 100644 index 0000000..1ab2f18 --- /dev/null +++ b/Source/WebCore/platform/chromium/ScrollbarThemeChromiumMac.h @@ -0,0 +1,74 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * Copyright (C) 2009 Google Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef ScrollbarThemeChromiumMac_h +#define ScrollbarThemeChromiumMac_h + +#include "ScrollbarThemeComposite.h" + +// This file (and its associated .mm file) is a clone of ScrollbarThemeMac.h. +// See the .mm file for details. + +namespace WebCore { + +class ScrollbarThemeChromiumMac : public ScrollbarThemeComposite { +public: + ScrollbarThemeChromiumMac(); + virtual ~ScrollbarThemeChromiumMac(); + + virtual bool paint(Scrollbar*, GraphicsContext* context, const IntRect& damageRect); + + virtual int scrollbarThickness(ScrollbarControlSize = RegularScrollbar); + + virtual bool supportsControlTints() const { return true; } + + virtual double initialAutoscrollTimerDelay(); + virtual double autoscrollTimerDelay(); + + virtual ScrollbarButtonsPlacement buttonsPlacement() const; + + virtual void registerScrollbar(Scrollbar*); + virtual void unregisterScrollbar(Scrollbar*); + +protected: + virtual bool hasButtons(Scrollbar*); + virtual bool hasThumb(Scrollbar*); + + virtual IntRect backButtonRect(Scrollbar*, ScrollbarPart, bool painting = false); + virtual IntRect forwardButtonRect(Scrollbar*, ScrollbarPart, bool painting = false); + virtual IntRect trackRect(Scrollbar*, bool painting = false); + + virtual int minimumThumbLength(Scrollbar*); + + virtual bool shouldCenterOnThumb(Scrollbar*, const PlatformMouseEvent&); + +public: + void preferencesChanged(); +}; + +} + +#endif // ScrollbarThemeChromiumMac_h diff --git a/Source/WebCore/platform/chromium/ScrollbarThemeChromiumMac.mm b/Source/WebCore/platform/chromium/ScrollbarThemeChromiumMac.mm new file mode 100644 index 0000000..0aa3e10 --- /dev/null +++ b/Source/WebCore/platform/chromium/ScrollbarThemeChromiumMac.mm @@ -0,0 +1,489 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * Copyright (C) 2009 Google Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "ScrollbarThemeChromiumMac.h" + +#include "ChromiumBridge.h" +#include "FrameView.h" +#include "ImageBuffer.h" +#include "PlatformMouseEvent.h" +#include "ScrollView.h" +#include <Carbon/Carbon.h> +#include <wtf/StdLibExtras.h> +#include <wtf/UnusedParam.h> + + +// FIXME: There are repainting problems due to Aqua scroll bar buttons' visual overflow. + +using namespace std; +using namespace WebCore; + +// This file (and its associated .h file) is a clone of ScrollbarThemeMac.mm. +// Because we want to draw tickmarks in the scrollbar, we must maintain a fork. +// Please maintain this file by performing parallel changes to it. +// +// The only changes from ScrollbarThemeMac should be: +// - The classname change from ScrollbarThemeMac to ScrollbarThemeChromiumMac. +// - In paint() the code to paint the track, tickmarks, and thumb separately. +// - In paint() the thumb is drawn via ChromeBridge/WebThemeEngine. +// +// For all other differences, if it was introduced in this file, then the +// maintainer forgot to include it in the list; otherwise it is an update that +// should have been applied to this file but was not. + +static HashSet<Scrollbar*>* gScrollbars; + +@interface ScrollbarPrefsObserver : NSObject +{ + +} + ++ (void)registerAsObserver; ++ (void)appearancePrefsChanged:(NSNotification*)theNotification; ++ (void)behaviorPrefsChanged:(NSNotification*)theNotification; + +@end + +@implementation ScrollbarPrefsObserver + ++ (void)appearancePrefsChanged:(NSNotification*)unusedNotification +{ + UNUSED_PARAM(unusedNotification); + + static_cast<ScrollbarThemeChromiumMac*>(ScrollbarTheme::nativeTheme())->preferencesChanged(); + if (!gScrollbars) + return; + HashSet<Scrollbar*>::iterator end = gScrollbars->end(); + for (HashSet<Scrollbar*>::iterator it = gScrollbars->begin(); it != end; ++it) { + (*it)->styleChanged(); + (*it)->invalidate(); + } +} + ++ (void)behaviorPrefsChanged:(NSNotification*)unusedNotification +{ + UNUSED_PARAM(unusedNotification); + + static_cast<ScrollbarThemeChromiumMac*>(ScrollbarTheme::nativeTheme())->preferencesChanged(); +} + ++ (void)registerAsObserver +{ + [[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(appearancePrefsChanged:) name:@"AppleAquaScrollBarVariantChanged" object:nil suspensionBehavior:NSNotificationSuspensionBehaviorDeliverImmediately]; + [[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(behaviorPrefsChanged:) name:@"AppleNoRedisplayAppearancePreferenceChanged" object:nil suspensionBehavior:NSNotificationSuspensionBehaviorCoalesce]; +} + +@end + +namespace WebCore { + +ScrollbarTheme* ScrollbarTheme::nativeTheme() +{ + DEFINE_STATIC_LOCAL(ScrollbarThemeChromiumMac, theme, ()); + return &theme; +} + +// FIXME: Get these numbers from CoreUI. +static int cScrollbarThickness[] = { 15, 11 }; +static int cRealButtonLength[] = { 28, 21 }; +static int cButtonInset[] = { 14, 11 }; +static int cButtonHitInset[] = { 3, 2 }; +// cRealButtonLength - cButtonInset +static int cButtonLength[] = { 14, 10 }; +static int cThumbMinLength[] = { 26, 20 }; + +static int cOuterButtonLength[] = { 16, 14 }; // The outer button in a double button pair is a bit bigger. +static int cOuterButtonOverlap = 2; + +static float gInitialButtonDelay = 0.5f; +static float gAutoscrollButtonDelay = 0.05f; +static bool gJumpOnTrackClick = false; +static ScrollbarButtonsPlacement gButtonPlacement = ScrollbarButtonsDoubleEnd; + +static void updateArrowPlacement() +{ + NSString *buttonPlacement = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleScrollBarVariant"]; + if ([buttonPlacement isEqualToString:@"Single"]) + gButtonPlacement = ScrollbarButtonsSingle; + else if ([buttonPlacement isEqualToString:@"DoubleMin"]) + gButtonPlacement = ScrollbarButtonsDoubleStart; + else if ([buttonPlacement isEqualToString:@"DoubleBoth"]) + gButtonPlacement = ScrollbarButtonsDoubleBoth; + else + gButtonPlacement = ScrollbarButtonsDoubleEnd; // The default is ScrollbarButtonsDoubleEnd. +} + +void ScrollbarThemeChromiumMac::registerScrollbar(Scrollbar* scrollbar) +{ + if (!gScrollbars) + gScrollbars = new HashSet<Scrollbar*>; + gScrollbars->add(scrollbar); +} + +void ScrollbarThemeChromiumMac::unregisterScrollbar(Scrollbar* scrollbar) +{ + gScrollbars->remove(scrollbar); + if (gScrollbars->isEmpty()) { + delete gScrollbars; + gScrollbars = 0; + } +} + +ScrollbarThemeChromiumMac::ScrollbarThemeChromiumMac() +{ + static bool initialized; + if (!initialized) { + initialized = true; + [ScrollbarPrefsObserver registerAsObserver]; + preferencesChanged(); + } +} + +ScrollbarThemeChromiumMac::~ScrollbarThemeChromiumMac() +{ +} + +void ScrollbarThemeChromiumMac::preferencesChanged() +{ + NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; + [defaults synchronize]; + updateArrowPlacement(); + gInitialButtonDelay = [defaults floatForKey:@"NSScrollerButtonDelay"]; + gAutoscrollButtonDelay = [defaults floatForKey:@"NSScrollerButtonPeriod"]; + gJumpOnTrackClick = [defaults boolForKey:@"AppleScrollerPagingBehavior"]; +} + +int ScrollbarThemeChromiumMac::scrollbarThickness(ScrollbarControlSize controlSize) +{ + return cScrollbarThickness[controlSize]; +} + +double ScrollbarThemeChromiumMac::initialAutoscrollTimerDelay() +{ + return gInitialButtonDelay; +} + +double ScrollbarThemeChromiumMac::autoscrollTimerDelay() +{ + return gAutoscrollButtonDelay; +} + +ScrollbarButtonsPlacement ScrollbarThemeChromiumMac::buttonsPlacement() const +{ + return gButtonPlacement; +} + +bool ScrollbarThemeChromiumMac::hasButtons(Scrollbar* scrollbar) +{ + return scrollbar->enabled() && (scrollbar->orientation() == HorizontalScrollbar ? + scrollbar->width() : + scrollbar->height()) >= 2 * (cRealButtonLength[scrollbar->controlSize()] - cButtonHitInset[scrollbar->controlSize()]); +} + +bool ScrollbarThemeChromiumMac::hasThumb(Scrollbar* scrollbar) +{ + return scrollbar->enabled() && (scrollbar->orientation() == HorizontalScrollbar ? + scrollbar->width() : + scrollbar->height()) >= 2 * cButtonInset[scrollbar->controlSize()] + cThumbMinLength[scrollbar->controlSize()] + 1; +} + +static IntRect buttonRepaintRect(const IntRect& buttonRect, ScrollbarOrientation orientation, ScrollbarControlSize controlSize, bool start) +{ + IntRect paintRect(buttonRect); + if (orientation == HorizontalScrollbar) { + paintRect.setWidth(cRealButtonLength[controlSize]); + if (!start) + paintRect.setX(buttonRect.x() - (cRealButtonLength[controlSize] - buttonRect.width())); + } else { + paintRect.setHeight(cRealButtonLength[controlSize]); + if (!start) + paintRect.setY(buttonRect.y() - (cRealButtonLength[controlSize] - buttonRect.height())); + } + + return paintRect; +} + +IntRect ScrollbarThemeChromiumMac::backButtonRect(Scrollbar* scrollbar, ScrollbarPart part, bool painting) +{ + IntRect result; + + if (part == BackButtonStartPart && (buttonsPlacement() == ScrollbarButtonsNone || buttonsPlacement() == ScrollbarButtonsDoubleEnd)) + return result; + + if (part == BackButtonEndPart && (buttonsPlacement() == ScrollbarButtonsNone || buttonsPlacement() == ScrollbarButtonsDoubleStart || buttonsPlacement() == ScrollbarButtonsSingle)) + return result; + + int thickness = scrollbarThickness(scrollbar->controlSize()); + bool outerButton = part == BackButtonStartPart && (buttonsPlacement() == ScrollbarButtonsDoubleStart || buttonsPlacement() == ScrollbarButtonsDoubleBoth); + if (outerButton) { + if (scrollbar->orientation() == HorizontalScrollbar) + result = IntRect(scrollbar->x(), scrollbar->y(), cOuterButtonLength[scrollbar->controlSize()] + painting ? cOuterButtonOverlap : 0, thickness); + else + result = IntRect(scrollbar->x(), scrollbar->y(), thickness, cOuterButtonLength[scrollbar->controlSize()] + painting ? cOuterButtonOverlap : 0); + return result; + } + + // Our repaint rect is slightly larger, since we are a button that is adjacent to the track. + if (scrollbar->orientation() == HorizontalScrollbar) { + int start = part == BackButtonStartPart ? scrollbar->x() : scrollbar->x() + scrollbar->width() - cOuterButtonLength[scrollbar->controlSize()] - cButtonLength[scrollbar->controlSize()]; + result = IntRect(start, scrollbar->y(), cButtonLength[scrollbar->controlSize()], thickness); + } else { + int start = part == BackButtonStartPart ? scrollbar->y() : scrollbar->y() + scrollbar->height() - cOuterButtonLength[scrollbar->controlSize()] - cButtonLength[scrollbar->controlSize()]; + result = IntRect(scrollbar->x(), start, thickness, cButtonLength[scrollbar->controlSize()]); + } + + if (painting) + return buttonRepaintRect(result, scrollbar->orientation(), scrollbar->controlSize(), part == BackButtonStartPart); + return result; +} + +IntRect ScrollbarThemeChromiumMac::forwardButtonRect(Scrollbar* scrollbar, ScrollbarPart part, bool painting) +{ + IntRect result; + + if (part == ForwardButtonEndPart && (buttonsPlacement() == ScrollbarButtonsNone || buttonsPlacement() == ScrollbarButtonsDoubleStart)) + return result; + + if (part == ForwardButtonStartPart && (buttonsPlacement() == ScrollbarButtonsNone || buttonsPlacement() == ScrollbarButtonsDoubleEnd || buttonsPlacement() == ScrollbarButtonsSingle)) + return result; + + int thickness = scrollbarThickness(scrollbar->controlSize()); + int outerButtonLength = cOuterButtonLength[scrollbar->controlSize()]; + int buttonLength = cButtonLength[scrollbar->controlSize()]; + + bool outerButton = part == ForwardButtonEndPart && (buttonsPlacement() == ScrollbarButtonsDoubleEnd || buttonsPlacement() == ScrollbarButtonsDoubleBoth); + if (outerButton) { + if (scrollbar->orientation() == HorizontalScrollbar) { + result = IntRect(scrollbar->x() + scrollbar->width() - outerButtonLength, scrollbar->y(), outerButtonLength, thickness); + if (painting) + result.inflateX(cOuterButtonOverlap); + } else { + result = IntRect(scrollbar->x(), scrollbar->y() + scrollbar->height() - outerButtonLength, thickness, outerButtonLength); + if (painting) + result.inflateY(cOuterButtonOverlap); + } + return result; + } + + if (scrollbar->orientation() == HorizontalScrollbar) { + int start = part == ForwardButtonEndPart ? scrollbar->x() + scrollbar->width() - buttonLength : scrollbar->x() + outerButtonLength; + result = IntRect(start, scrollbar->y(), buttonLength, thickness); + } else { + int start = part == ForwardButtonEndPart ? scrollbar->y() + scrollbar->height() - buttonLength : scrollbar->y() + outerButtonLength; + result = IntRect(scrollbar->x(), start, thickness, buttonLength); + } + if (painting) + return buttonRepaintRect(result, scrollbar->orientation(), scrollbar->controlSize(), part == ForwardButtonStartPart); + return result; +} + +IntRect ScrollbarThemeChromiumMac::trackRect(Scrollbar* scrollbar, bool painting) +{ + if (painting || !hasButtons(scrollbar)) + return scrollbar->frameRect(); + + IntRect result; + int thickness = scrollbarThickness(scrollbar->controlSize()); + int startWidth = 0; + int endWidth = 0; + int outerButtonLength = cOuterButtonLength[scrollbar->controlSize()]; + int buttonLength = cButtonLength[scrollbar->controlSize()]; + int doubleButtonLength = outerButtonLength + buttonLength; + switch (buttonsPlacement()) { + case ScrollbarButtonsSingle: + startWidth = buttonLength; + endWidth = buttonLength; + break; + case ScrollbarButtonsDoubleStart: + startWidth = doubleButtonLength; + break; + case ScrollbarButtonsDoubleEnd: + endWidth = doubleButtonLength; + break; + case ScrollbarButtonsDoubleBoth: + startWidth = doubleButtonLength; + endWidth = doubleButtonLength; + break; + default: + break; + } + + int totalWidth = startWidth + endWidth; + if (scrollbar->orientation() == HorizontalScrollbar) + return IntRect(scrollbar->x() + startWidth, scrollbar->y(), scrollbar->width() - totalWidth, thickness); + return IntRect(scrollbar->x(), scrollbar->y() + startWidth, thickness, scrollbar->height() - totalWidth); +} + +int ScrollbarThemeChromiumMac::minimumThumbLength(Scrollbar* scrollbar) +{ + return cThumbMinLength[scrollbar->controlSize()]; +} + +bool ScrollbarThemeChromiumMac::shouldCenterOnThumb(Scrollbar*, const PlatformMouseEvent& evt) +{ + if (evt.button() != LeftButton) + return false; + if (gJumpOnTrackClick) + return !evt.altKey(); + return evt.altKey(); +} + +static int scrollbarPartToHIPressedState(ScrollbarPart part) +{ + switch (part) { + case BackButtonStartPart: + return kThemeTopOutsideArrowPressed; + case BackButtonEndPart: + return kThemeTopOutsideArrowPressed; // This does not make much sense. For some reason the outside constant is required. + case ForwardButtonStartPart: + return kThemeTopInsideArrowPressed; + case ForwardButtonEndPart: + return kThemeBottomOutsideArrowPressed; + case ThumbPart: + return kThemeThumbPressed; + default: + return 0; + } +} + +static ChromiumBridge::ThemePaintState scrollbarStateToThemeState(Scrollbar* scrollbar) { + if (!scrollbar->enabled()) + return ChromiumBridge::StateDisabled; + if (!scrollbar->client()->isActive()) + return ChromiumBridge::StateInactive; + if (scrollbar->pressedPart() == ThumbPart) + return ChromiumBridge::StatePressed; + + return ChromiumBridge::StateActive; +} + +bool ScrollbarThemeChromiumMac::paint(Scrollbar* scrollbar, GraphicsContext* context, const IntRect& damageRect) +{ + HIThemeTrackDrawInfo trackInfo; + trackInfo.version = 0; + trackInfo.kind = scrollbar->controlSize() == RegularScrollbar ? kThemeMediumScrollBar : kThemeSmallScrollBar; + trackInfo.bounds = scrollbar->frameRect(); + trackInfo.min = 0; + trackInfo.max = scrollbar->maximum(); + trackInfo.value = scrollbar->currentPos(); + trackInfo.trackInfo.scrollbar.viewsize = scrollbar->visibleSize(); + trackInfo.attributes = 0; + if (scrollbar->orientation() == HorizontalScrollbar) + trackInfo.attributes |= kThemeTrackHorizontal; + + if (!scrollbar->enabled()) + trackInfo.enableState = kThemeTrackDisabled; + else + trackInfo.enableState = scrollbar->client()->isActive() ? kThemeTrackActive : kThemeTrackInactive; + + if (!hasButtons(scrollbar)) + trackInfo.enableState = kThemeTrackNothingToScroll; + trackInfo.trackInfo.scrollbar.pressState = scrollbarPartToHIPressedState(scrollbar->pressedPart()); + + CGAffineTransform currentCTM = CGContextGetCTM(context->platformContext()); + + // The Aqua scrollbar is buggy when rotated and scaled. We will just draw into a bitmap if we detect a scale or rotation. + bool canDrawDirectly = currentCTM.a == 1.0f && currentCTM.b == 0.0f && currentCTM.c == 0.0f && (currentCTM.d == 1.0f || currentCTM.d == -1.0f); + GraphicsContext* drawingContext = context; + OwnPtr<ImageBuffer> imageBuffer; + if (!canDrawDirectly) { + trackInfo.bounds = IntRect(IntPoint(), scrollbar->frameRect().size()); + + IntRect bufferRect(scrollbar->frameRect()); + bufferRect.intersect(damageRect); + bufferRect.move(-scrollbar->frameRect().x(), -scrollbar->frameRect().y()); + + imageBuffer = ImageBuffer::create(bufferRect.size()); + if (!imageBuffer) + return true; + + drawingContext = imageBuffer->context(); + } + + // Draw thumbless. + HIThemeDrawTrack(&trackInfo, 0, drawingContext->platformContext(), kHIThemeOrientationNormal); + + Vector<IntRect> tickmarks; + scrollbar->client()->getTickmarks(tickmarks); + if (scrollbar->orientation() == VerticalScrollbar && tickmarks.size()) { + drawingContext->save(); + drawingContext->setShouldAntialias(false); + drawingContext->setStrokeColor(Color(0xCC, 0xAA, 0x00, 0xFF), ColorSpaceDeviceRGB); + drawingContext->setFillColor(Color(0xFF, 0xDD, 0x00, 0xFF), ColorSpaceDeviceRGB); + + IntRect thumbArea = trackRect(scrollbar, false); + if (!canDrawDirectly) { + thumbArea.setX(0); + thumbArea.setY(0); + } + // The ends are rounded and the thumb doesn't go there. + thumbArea.inflateY(-thumbArea.width()); + + for (Vector<IntRect>::const_iterator i = tickmarks.begin(); i != tickmarks.end(); ++i) { + // Calculate how far down (in %) the tick-mark should appear. + const float percent = static_cast<float>(i->y()) / scrollbar->totalSize(); + if (percent < 0.0 || percent > 1.0) + continue; + + // Calculate how far down (in pixels) the tick-mark should appear. + const int yPos = static_cast<int>((thumbArea.topLeft().y() + (thumbArea.height() * percent))) & ~1; + + // Paint. + const int indent = 2; + FloatRect tickRect(thumbArea.topLeft().x() + indent, yPos, thumbArea.width() - 2 * indent - 1, 2); + drawingContext->fillRect(tickRect); + drawingContext->strokeRect(tickRect, 1); + } + + drawingContext->restore(); + } + + if (hasThumb(scrollbar)) { + ChromiumBridge::ThemePaintScrollbarInfo scrollbarInfo; + scrollbarInfo.orientation = scrollbar->orientation() == HorizontalScrollbar ? ChromiumBridge::ScrollbarOrientationHorizontal : ChromiumBridge::ScrollbarOrientationVertical; + scrollbarInfo.parent = scrollbar->parent() && scrollbar->parent()->isFrameView() && static_cast<FrameView*>(scrollbar->parent())->isScrollViewScrollbar(scrollbar) ? ChromiumBridge::ScrollbarParentScrollView : ChromiumBridge::ScrollbarParentRenderLayer; + scrollbarInfo.maxValue = scrollbar->maximum(); + scrollbarInfo.currentValue = scrollbar->currentPos(); + scrollbarInfo.visibleSize = scrollbar->visibleSize(); + scrollbarInfo.totalSize = scrollbar->totalSize(); + + ChromiumBridge::paintScrollbarThumb( + drawingContext, + scrollbarStateToThemeState(scrollbar), + scrollbar->controlSize() == RegularScrollbar ? ChromiumBridge::SizeRegular : ChromiumBridge::SizeSmall, + scrollbar->frameRect(), + scrollbarInfo); + } + + if (!canDrawDirectly) + context->drawImageBuffer(imageBuffer.get(), ColorSpaceDeviceRGB, scrollbar->frameRect().location()); + + return true; +} + +} + diff --git a/Source/WebCore/platform/chromium/ScrollbarThemeChromiumWin.cpp b/Source/WebCore/platform/chromium/ScrollbarThemeChromiumWin.cpp new file mode 100644 index 0000000..ba7e97b --- /dev/null +++ b/Source/WebCore/platform/chromium/ScrollbarThemeChromiumWin.cpp @@ -0,0 +1,271 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * Copyright (C) 2008, 2009 Google Inc. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "ScrollbarThemeChromiumWin.h" + +#include <windows.h> +#include <vsstyle.h> + +#include "ChromiumBridge.h" +#include "GraphicsContext.h" +#include "PlatformContextSkia.h" +#include "PlatformMouseEvent.h" +#include "Scrollbar.h" +#include "WindowsVersion.h" + +namespace WebCore { + +ScrollbarTheme* ScrollbarTheme::nativeTheme() +{ + static ScrollbarThemeChromiumWin theme; + return &theme; +} + +// The scrollbar size in DumpRenderTree on the Mac - so we can match their +// layout results. Entries are for regular, small, and mini scrollbars. +// Metrics obtained using [NSScroller scrollerWidthForControlSize:] +static const int kMacScrollbarSize[3] = { 15, 11, 15 }; + +// Constants used to figure the drag rect outside which we should snap the +// scrollbar thumb back to its origin. These calculations are based on +// observing the behavior of the MSVC8 main window scrollbar + some +// guessing/extrapolation. +static const int kOffEndMultiplier = 3; +static const int kOffSideMultiplier = 8; + +int ScrollbarThemeChromiumWin::scrollbarThickness(ScrollbarControlSize controlSize) +{ + static int thickness; + if (!thickness) { + if (ChromiumBridge::layoutTestMode()) + return kMacScrollbarSize[controlSize]; + thickness = GetSystemMetrics(SM_CXVSCROLL); + } + return thickness; +} + +bool ScrollbarThemeChromiumWin::invalidateOnMouseEnterExit() +{ + return isVistaOrNewer(); +} + +bool ScrollbarThemeChromiumWin::shouldSnapBackToDragOrigin(Scrollbar* scrollbar, const PlatformMouseEvent& evt) +{ + // Find the rect within which we shouldn't snap, by expanding the track rect + // in both dimensions. + IntRect rect = trackRect(scrollbar); + const bool horz = scrollbar->orientation() == HorizontalScrollbar; + const int thickness = scrollbarThickness(scrollbar->controlSize()); + rect.inflateX((horz ? kOffEndMultiplier : kOffSideMultiplier) * thickness); + rect.inflateY((horz ? kOffSideMultiplier : kOffEndMultiplier) * thickness); + + // Convert the event to local coordinates. + IntPoint mousePosition = scrollbar->convertFromContainingWindow(evt.pos()); + mousePosition.move(scrollbar->x(), scrollbar->y()); + + // We should snap iff the event is outside our calculated rect. + return !rect.contains(mousePosition); +} + +void ScrollbarThemeChromiumWin::paintTrackPiece(GraphicsContext* gc, Scrollbar* scrollbar, const IntRect& rect, ScrollbarPart partType) +{ + bool horz = scrollbar->orientation() == HorizontalScrollbar; + + int partId; + if (partType == BackTrackPart) + partId = horz ? SBP_UPPERTRACKHORZ : SBP_UPPERTRACKVERT; + else + partId = horz ? SBP_LOWERTRACKHORZ : SBP_LOWERTRACKVERT; + + IntRect alignRect = trackRect(scrollbar, false); + + // Draw the track area before/after the thumb on the scroll bar. + ChromiumBridge::paintScrollbarTrack( + gc, + partId, + getThemeState(scrollbar, partType), + getClassicThemeState(scrollbar, partType), + rect, + alignRect); +} + +void ScrollbarThemeChromiumWin::paintButton(GraphicsContext* gc, Scrollbar* scrollbar, const IntRect& rect, ScrollbarPart part) +{ + bool horz = scrollbar->orientation() == HorizontalScrollbar; + + int partId; + if (part == BackButtonStartPart || part == ForwardButtonStartPart) + partId = horz ? DFCS_SCROLLLEFT : DFCS_SCROLLUP; + else + partId = horz ? DFCS_SCROLLRIGHT : DFCS_SCROLLDOWN; + + // Draw the thumb (the box you drag in the scroll bar to scroll). + ChromiumBridge::paintScrollbarArrow( + gc, + getThemeArrowState(scrollbar, part), + partId | getClassicThemeState(scrollbar, part), + rect); +} + +void ScrollbarThemeChromiumWin::paintThumb(GraphicsContext* gc, Scrollbar* scrollbar, const IntRect& rect) +{ + bool horz = scrollbar->orientation() == HorizontalScrollbar; + + // Draw the thumb (the box you drag in the scroll bar to scroll). + ChromiumBridge::paintScrollbarThumb( + gc, + horz ? SBP_THUMBBTNHORZ : SBP_THUMBBTNVERT, + getThemeState(scrollbar, ThumbPart), + getClassicThemeState(scrollbar, ThumbPart), + rect); + + // Draw the gripper (the three little lines on the thumb). + ChromiumBridge::paintScrollbarThumb( + gc, + horz ? SBP_GRIPPERHORZ : SBP_GRIPPERVERT, + getThemeState(scrollbar, ThumbPart), + getClassicThemeState(scrollbar, ThumbPart), + rect); +} + +int ScrollbarThemeChromiumWin::getThemeState(Scrollbar* scrollbar, ScrollbarPart part) const +{ + // When dragging the thumb, draw thumb pressed and other segments normal + // regardless of where the cursor actually is. See also four places in + // getThemeArrowState(). + if (scrollbar->pressedPart() == ThumbPart) { + if (part == ThumbPart) + return SCRBS_PRESSED; + return isVistaOrNewer() ? SCRBS_HOVER : SCRBS_NORMAL; + } + if (!scrollbar->enabled()) + return SCRBS_DISABLED; + if (scrollbar->hoveredPart() != part || part == BackTrackPart || part == ForwardTrackPart) + return (scrollbar->hoveredPart() == NoPart || !isVistaOrNewer()) ? SCRBS_NORMAL : SCRBS_HOVER; + if (scrollbar->pressedPart() == NoPart) + return SCRBS_HOT; + return (scrollbar->pressedPart() == part) ? SCRBS_PRESSED : SCRBS_NORMAL; +} + +int ScrollbarThemeChromiumWin::getThemeArrowState(Scrollbar* scrollbar, ScrollbarPart part) const +{ + // We could take advantage of knowing the values in the state enum to write + // some simpler code, but treating the state enum as a black box seems + // clearer and more future-proof. + if (part == BackButtonStartPart || part == ForwardButtonStartPart) { + if (scrollbar->orientation() == HorizontalScrollbar) { + if (scrollbar->pressedPart() == ThumbPart) + return !isVistaOrNewer() ? ABS_LEFTNORMAL : ABS_LEFTHOVER; + if (!scrollbar->enabled()) + return ABS_LEFTDISABLED; + if (scrollbar->hoveredPart() != part) + return ((scrollbar->hoveredPart() == NoPart) || !isVistaOrNewer()) ? ABS_LEFTNORMAL : ABS_LEFTHOVER; + if (scrollbar->pressedPart() == NoPart) + return ABS_LEFTHOT; + return (scrollbar->pressedPart() == part) ? + ABS_LEFTPRESSED : ABS_LEFTNORMAL; + } + if (scrollbar->pressedPart() == ThumbPart) + return !isVistaOrNewer() ? ABS_UPNORMAL : ABS_UPHOVER; + if (!scrollbar->enabled()) + return ABS_UPDISABLED; + if (scrollbar->hoveredPart() != part) + return ((scrollbar->hoveredPart() == NoPart) || !isVistaOrNewer()) ? ABS_UPNORMAL : ABS_UPHOVER; + if (scrollbar->pressedPart() == NoPart) + return ABS_UPHOT; + return (scrollbar->pressedPart() == part) ? ABS_UPPRESSED : ABS_UPNORMAL; + } + if (scrollbar->orientation() == HorizontalScrollbar) { + if (scrollbar->pressedPart() == ThumbPart) + return !isVistaOrNewer() ? ABS_RIGHTNORMAL : ABS_RIGHTHOVER; + if (!scrollbar->enabled()) + return ABS_RIGHTDISABLED; + if (scrollbar->hoveredPart() != part) + return ((scrollbar->hoveredPart() == NoPart) || !isVistaOrNewer()) ? ABS_RIGHTNORMAL : ABS_RIGHTHOVER; + if (scrollbar->pressedPart() == NoPart) + return ABS_RIGHTHOT; + return (scrollbar->pressedPart() == part) ? ABS_RIGHTPRESSED : ABS_RIGHTNORMAL; + } + if (scrollbar->pressedPart() == ThumbPart) + return !isVistaOrNewer() ? ABS_DOWNNORMAL : ABS_DOWNHOVER; + if (!scrollbar->enabled()) + return ABS_DOWNDISABLED; + if (scrollbar->hoveredPart() != part) + return ((scrollbar->hoveredPart() == NoPart) || !isVistaOrNewer()) ? ABS_DOWNNORMAL : ABS_DOWNHOVER; + if (scrollbar->pressedPart() == NoPart) + return ABS_DOWNHOT; + return (scrollbar->pressedPart() == part) ? ABS_DOWNPRESSED : ABS_DOWNNORMAL; +} + +int ScrollbarThemeChromiumWin::getClassicThemeState(Scrollbar* scrollbar, ScrollbarPart part) const +{ + // When dragging the thumb, draw the buttons normal even when hovered. + if (scrollbar->pressedPart() == ThumbPart) + return 0; + if (!scrollbar->enabled()) + return DFCS_INACTIVE; + if (scrollbar->hoveredPart() != part || part == BackTrackPart || part == ForwardTrackPart) + return 0; + if (scrollbar->pressedPart() == NoPart) + return DFCS_HOT; + return (scrollbar->pressedPart() == part) ? (DFCS_PUSHED | DFCS_FLAT) : 0; +} + +bool ScrollbarThemeChromiumWin::shouldCenterOnThumb(Scrollbar*, const PlatformMouseEvent& evt) +{ + return evt.shiftKey() && evt.button() == LeftButton; +} + +IntSize ScrollbarThemeChromiumWin::buttonSize(Scrollbar* scrollbar) +{ + // Our desired rect is essentially thickness by thickness. + + // Our actual rect will shrink to half the available space when we have < 2 + // times thickness pixels left. This allows the scrollbar to scale down + // and function even at tiny sizes. + + int thickness = scrollbarThickness(scrollbar->controlSize()); + + // In layout test mode, we force the button "girth" (i.e., the length of + // the button along the axis of the scrollbar) to be a fixed size. + // FIXME: This is retarded! scrollbarThickness is already fixed in layout + // test mode so that should be enough to result in repeatable results, but + // preserving this hack avoids having to rebaseline pixel tests. + const int kLayoutTestModeGirth = 17; + int girth = ChromiumBridge::layoutTestMode() ? kLayoutTestModeGirth : thickness; + + if (scrollbar->orientation() == HorizontalScrollbar) { + int width = scrollbar->width() < 2 * girth ? scrollbar->width() / 2 : girth; + return IntSize(width, thickness); + } + + int height = scrollbar->height() < 2 * girth ? scrollbar->height() / 2 : girth; + return IntSize(thickness, height); +} + + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/ScrollbarThemeChromiumWin.h b/Source/WebCore/platform/chromium/ScrollbarThemeChromiumWin.h new file mode 100644 index 0000000..69cfa13 --- /dev/null +++ b/Source/WebCore/platform/chromium/ScrollbarThemeChromiumWin.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef ScrollbarThemeChromiumWin_h +#define ScrollbarThemeChromiumWin_h + +#include "ScrollbarThemeChromium.h" + +namespace WebCore { + class ScrollbarThemeChromiumWin : public ScrollbarThemeChromium { + public: + virtual int scrollbarThickness(ScrollbarControlSize); + virtual bool invalidateOnMouseEnterExit(); + virtual bool shouldSnapBackToDragOrigin(Scrollbar*, const PlatformMouseEvent&); + + protected: + virtual void paintTrackPiece(GraphicsContext*, Scrollbar*, const IntRect&, ScrollbarPart); + virtual void paintButton(GraphicsContext*, Scrollbar*, const IntRect&, ScrollbarPart); + virtual void paintThumb(GraphicsContext*, Scrollbar*, const IntRect&); + virtual bool shouldCenterOnThumb(Scrollbar*, const PlatformMouseEvent&); + virtual IntSize buttonSize(Scrollbar*); + + private: + int getThemeState(Scrollbar*, ScrollbarPart) const; + int getThemeArrowState(Scrollbar*, ScrollbarPart) const; + int getClassicThemeState(Scrollbar*, ScrollbarPart) const; + }; +} // namespace WebCore + +#endif diff --git a/Source/WebCore/platform/chromium/SearchPopupMenuChromium.cpp b/Source/WebCore/platform/chromium/SearchPopupMenuChromium.cpp new file mode 100644 index 0000000..ca5bebe --- /dev/null +++ b/Source/WebCore/platform/chromium/SearchPopupMenuChromium.cpp @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "SearchPopupMenuChromium.h" + +#include "NotImplemented.h" +#include <wtf/text/AtomicString.h> + +namespace WebCore { + +SearchPopupMenuChromium::SearchPopupMenuChromium(PopupMenuClient* client) + : m_popup(adoptRef(new PopupMenuChromium(client))) +{ +} + +PopupMenu* SearchPopupMenuChromium::popupMenu() +{ + return m_popup.get(); +} + +bool SearchPopupMenuChromium::enabled() +{ + return false; +} + +void SearchPopupMenuChromium::saveRecentSearches(const AtomicString& name, const Vector<String>& searchItems) +{ + notImplemented(); +} + +void SearchPopupMenuChromium::loadRecentSearches(const AtomicString& name, Vector<String>& searchItems) +{ + notImplemented(); +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/SearchPopupMenuChromium.h b/Source/WebCore/platform/chromium/SearchPopupMenuChromium.h new file mode 100644 index 0000000..827ff66 --- /dev/null +++ b/Source/WebCore/platform/chromium/SearchPopupMenuChromium.h @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + * + */ + +#ifndef SearchPopupMenuChromium_h +#define SearchPopupMenuChromium_h + +#include "PopupMenuChromium.h" +#include "SearchPopupMenu.h" + +namespace WebCore { + +class SearchPopupMenuChromium : public SearchPopupMenu { +public: + SearchPopupMenuChromium(PopupMenuClient*); + + virtual PopupMenu* popupMenu(); + virtual void saveRecentSearches(const AtomicString& name, const Vector<String>& searchItems); + virtual void loadRecentSearches(const AtomicString& name, Vector<String>& searchItems); + virtual bool enabled(); + +private: + RefPtr<PopupMenuChromium> m_popup; +}; + +} + +#endif // SearchPopupMenuChromium_h diff --git a/Source/WebCore/platform/chromium/SharedTimerChromium.cpp b/Source/WebCore/platform/chromium/SharedTimerChromium.cpp new file mode 100644 index 0000000..5a6a000 --- /dev/null +++ b/Source/WebCore/platform/chromium/SharedTimerChromium.cpp @@ -0,0 +1,48 @@ +/* + * Copyright (C) 2006 Apple Computer, Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "SharedTimer.h" + +#include "ChromiumBridge.h" + +namespace WebCore { + +void setSharedTimerFiredFunction(void (*f)()) +{ + ChromiumBridge::setSharedTimerFiredFunction(f); +} + +void setSharedTimerFireTime(double fireTime) +{ + ChromiumBridge::setSharedTimerFireTime(fireTime); +} + +void stopSharedTimer() +{ + ChromiumBridge::stopSharedTimer(); +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/SoundChromiumPosix.cpp b/Source/WebCore/platform/chromium/SoundChromiumPosix.cpp new file mode 100644 index 0000000..2767d76 --- /dev/null +++ b/Source/WebCore/platform/chromium/SoundChromiumPosix.cpp @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "Sound.h" + +#include "NotImplemented.h" + +namespace WebCore { + +void systemBeep() +{ + notImplemented(); +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/SoundChromiumWin.cpp b/Source/WebCore/platform/chromium/SoundChromiumWin.cpp new file mode 100644 index 0000000..e145477 --- /dev/null +++ b/Source/WebCore/platform/chromium/SoundChromiumWin.cpp @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2006, 2007 Apple Inc. All rights reserved. + * Copyright (C) 2008, 2009 Google Inc. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "Sound.h" + +#include <windows.h> + +namespace WebCore { + +void systemBeep() +{ + MessageBeep(static_cast<UINT>(-1)); +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/SuddenTerminationChromium.cpp b/Source/WebCore/platform/chromium/SuddenTerminationChromium.cpp new file mode 100644 index 0000000..54b8304 --- /dev/null +++ b/Source/WebCore/platform/chromium/SuddenTerminationChromium.cpp @@ -0,0 +1,48 @@ +/*
+ * Copyright (C) 2009 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "SuddenTermination.h"
+
+#include "ChromiumBridge.h"
+
+namespace WebCore {
+
+void disableSuddenTermination()
+{
+ ChromiumBridge::suddenTerminationChanged(false);
+}
+
+void enableSuddenTermination()
+{
+ ChromiumBridge::suddenTerminationChanged(true);
+}
+
+} // namespace WebCore
diff --git a/Source/WebCore/platform/chromium/SystemTimeChromium.cpp b/Source/WebCore/platform/chromium/SystemTimeChromium.cpp new file mode 100644 index 0000000..52ac262 --- /dev/null +++ b/Source/WebCore/platform/chromium/SystemTimeChromium.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "SystemTime.h" + +#include "ChromiumBridge.h" +#include "NotImplemented.h" + +namespace WebCore { + +// Get the current time in seconds since epoch. +double currentTime() +{ + return ChromiumBridge::currentTime(); +} + +float userIdleTime() +{ + // Needed for back/forward cache, which we currently have disabled. + notImplemented(); + return 0.0F; +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/TemporaryLinkStubs.cpp b/Source/WebCore/platform/chromium/TemporaryLinkStubs.cpp new file mode 100644 index 0000000..3c747d0 --- /dev/null +++ b/Source/WebCore/platform/chromium/TemporaryLinkStubs.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" + +#include "CookieStorage.h" +#include "KURL.h" +#include "NotImplemented.h" +#include "SharedBuffer.h" + +namespace WebCore { + +String KURL::fileSystemPath() const +{ + notImplemented(); + return String(); +} + +PassRefPtr<SharedBuffer> SharedBuffer::createWithContentsOfFile(const String&) +{ + notImplemented(); + return 0; +} + +void setCookieStoragePrivateBrowsingEnabled(bool) +{ + notImplemented(); +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/ThemeChromiumMac.h b/Source/WebCore/platform/chromium/ThemeChromiumMac.h new file mode 100644 index 0000000..5580d1d --- /dev/null +++ b/Source/WebCore/platform/chromium/ThemeChromiumMac.h @@ -0,0 +1,60 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * Copyright (C) 2009 Google Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef ThemeChromiumMac_h +#define ThemeChromiumMac_h + +#include "Theme.h" + +// This file (and its associated .mm file) is a clone of ThemeMac.h. See +// the .mm file for details. + +namespace WebCore { + +class ThemeChromiumMac : public Theme { +public: + ThemeChromiumMac() { } + virtual ~ThemeChromiumMac() { } + + virtual int baselinePositionAdjustment(ControlPart) const; + + virtual FontDescription controlFont(ControlPart, const Font&, float zoomFactor) const; + + virtual LengthSize controlSize(ControlPart, const Font&, const LengthSize&, float zoomFactor) const; + virtual LengthSize minimumControlSize(ControlPart, const Font&, float zoomFactor) const; + + virtual LengthBox controlPadding(ControlPart, const Font&, const LengthBox& zoomedBox, float zoomFactor) const; + virtual LengthBox controlBorder(ControlPart, const Font&, const LengthBox& zoomedBox, float zoomFactor) const; + + virtual bool controlRequiresPreWhiteSpace(ControlPart part) const { return part == PushButtonPart; } + + virtual void paint(ControlPart, ControlStates, GraphicsContext*, const IntRect&, float zoomFactor, ScrollView*) const; + virtual void inflateControlPaintRect(ControlPart, ControlStates, IntRect&, float zoomFactor) const; +}; + +} // namespace WebCore + +#endif // ThemeChromiumMac_h diff --git a/Source/WebCore/platform/chromium/ThemeChromiumMac.mm b/Source/WebCore/platform/chromium/ThemeChromiumMac.mm new file mode 100644 index 0000000..5e457f3 --- /dev/null +++ b/Source/WebCore/platform/chromium/ThemeChromiumMac.mm @@ -0,0 +1,844 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * Copyright (C) 2009 Google Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#import "config.h" +#import "ThemeChromiumMac.h" + +#import "BlockExceptions.h" +#import "GraphicsContext.h" +#import "LocalCurrentGraphicsContext.h" +#import "ScrollView.h" +#import "WebCoreSystemInterface.h" +#import <Carbon/Carbon.h> +#include <wtf/StdLibExtras.h> +#import <objc/runtime.h> + +using namespace std; + +// This file (and its associated .h file) is a clone of ThemeMac.mm. +// Because the original file is designed to run in-process inside a Cocoa view, +// we must maintain a fork. Please maintain this file by performing parallel +// changes to it. +// +// The only changes from ThemeMac should be: +// - The classname change from ThemeMac to ThemeChromiumMac. +// - The import of FlippedView() and its use as the parent view for cell +// rendering. +// - In updateStates() the code to update the cells' inactive state. +// - In paintButton() the code to save/restore the window's default button cell. +// - The Snow Leopard focus ring bug fix and its use around every call to +// -[NSButtonCell drawWithFrame:inView:]. +// +// For all other differences, if it was introduced in this file, then the +// maintainer forgot to include it in the list; otherwise it is an update that +// should have been applied to this file but was not. + +// FIXME: Default buttons really should be more like push buttons and not like buttons. + +// --- START fix for Snow Leopard focus ring bug --- + +// There is a bug in the Cocoa focus ring drawing code. The code calls +[NSView +// focusView] (to get the currently focused view) and then calls an NSRect- +// returning method on that view to obtain a clipping rect. However, if there is +// no focused view (as there won't be if the destination is a context), the rect +// returned from the method invocation on nil is garbage. +// +// The garbage fortunately does not clip the focus ring on Leopard, but +// unfortunately does so on Snow Leopard. Therefore, if a runtime test shows +// that focus ring drawing fails, we swizzle NSView to ensure it returns a valid +// view with a valid clipping rectangle. +// +// FIXME: After the referenced bug is fixed on all supported platforms, remove +// this code. +// +// References: +// <http://crbug.com/27493> +// <rdar://problem/7604051> (<http://openradar.appspot.com/7604051>) + +@interface TCMVisibleView : NSView + +@end + +@implementation TCMVisibleView + +- (struct CGRect)_focusRingVisibleRect +{ + return CGRectZero; +} + +- (id)_focusRingClipAncestor +{ + return self; +} + +@end + +@interface NSView (TCMInterposing) ++ (NSView *)TCMInterposing_focusView; +@end + +namespace FocusIndicationFix { + +bool currentOSHasSetFocusRingStyleInBitmapBug() +{ + UInt32 pixel = 0; + UInt32* pixelPlane = &pixel; + UInt32** pixelPlanes = &pixelPlane; + NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:(UInt8**)pixelPlanes + pixelsWide:1 + pixelsHigh:1 + bitsPerSample:8 + samplesPerPixel:4 + hasAlpha:YES + isPlanar:NO + colorSpaceName:NSCalibratedRGBColorSpace + bitmapFormat:NSAlphaFirstBitmapFormat + bytesPerRow:4 + bitsPerPixel:32]; + [NSGraphicsContext saveGraphicsState]; + [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithBitmapImageRep:bitmap]]; + NSSetFocusRingStyle(NSFocusRingOnly); + NSRectFill(NSMakeRect(0, 0, 1, 1)); + [NSGraphicsContext restoreGraphicsState]; + [bitmap release]; + + return !pixel; +} + +bool swizzleFocusView() +{ + if (!currentOSHasSetFocusRingStyleInBitmapBug()) + return false; + + Class nsview = [NSView class]; + Method m1 = class_getClassMethod(nsview, @selector(focusView)); + Method m2 = class_getClassMethod(nsview, @selector(TCMInterposing_focusView)); + if (m1 && m2) { + method_exchangeImplementations(m1, m2); + return true; + } + + return false; +} + +static bool interpose = false; + +// A class to restrict the amount of time spent messing with interposing. It +// only stacks one-deep. +class ScopedFixer { +public: + ScopedFixer() + { + static bool swizzled = swizzleFocusView(); + interpose = swizzled; + } + + ~ScopedFixer() + { + interpose = false; + } +}; + +} // namespace FocusIndicationFix + +@implementation NSView (TCMInterposing) + ++ (NSView *)TCMInterposing_focusView +{ + NSView *view = [self TCMInterposing_focusView]; // call original (was swizzled) + if (!view && FocusIndicationFix::interpose) { + static TCMVisibleView* fixedView = [[TCMVisibleView alloc] init]; + view = fixedView; + } + + return view; +} + +@end + +// --- END fix for Snow Leopard focus ring bug --- + +namespace WebCore { + +// Pick up utility function from RenderThemeChromiumMac. +extern NSView* FlippedView(); + +enum { + topMargin, + rightMargin, + bottomMargin, + leftMargin +}; + +Theme* platformTheme() +{ + DEFINE_STATIC_LOCAL(ThemeChromiumMac, themeMac, ()); + return &themeMac; +} + +// Helper functions used by a bunch of different control parts. + +static NSControlSize controlSizeForFont(const Font& font) +{ + int fontSize = font.pixelSize(); + if (fontSize >= 16) + return NSRegularControlSize; + if (fontSize >= 11) + return NSSmallControlSize; + return NSMiniControlSize; +} + +static LengthSize sizeFromNSControlSize(NSControlSize nsControlSize, const LengthSize& zoomedSize, float zoomFactor, const IntSize* sizes) +{ + IntSize controlSize = sizes[nsControlSize]; + if (zoomFactor != 1.0f) + controlSize = IntSize(controlSize.width() * zoomFactor, controlSize.height() * zoomFactor); + LengthSize result = zoomedSize; + if (zoomedSize.width().isIntrinsicOrAuto() && controlSize.width() > 0) + result.setWidth(Length(controlSize.width(), Fixed)); + if (zoomedSize.height().isIntrinsicOrAuto() && controlSize.height() > 0) + result.setHeight(Length(controlSize.height(), Fixed)); + return result; +} + +static LengthSize sizeFromFont(const Font& font, const LengthSize& zoomedSize, float zoomFactor, const IntSize* sizes) +{ + return sizeFromNSControlSize(controlSizeForFont(font), zoomedSize, zoomFactor, sizes); +} + +static ControlSize controlSizeFromPixelSize(const IntSize* sizes, const IntSize& minZoomedSize, float zoomFactor) +{ + if (minZoomedSize.width() >= static_cast<int>(sizes[NSRegularControlSize].width() * zoomFactor) && + minZoomedSize.height() >= static_cast<int>(sizes[NSRegularControlSize].height() * zoomFactor)) + return NSRegularControlSize; + if (minZoomedSize.width() >= static_cast<int>(sizes[NSSmallControlSize].width() * zoomFactor) && + minZoomedSize.height() >= static_cast<int>(sizes[NSSmallControlSize].height() * zoomFactor)) + return NSSmallControlSize; + return NSMiniControlSize; +} + +static void setControlSize(NSCell* cell, const IntSize* sizes, const IntSize& minZoomedSize, float zoomFactor) +{ + ControlSize size = controlSizeFromPixelSize(sizes, minZoomedSize, zoomFactor); + if (size != [cell controlSize]) // Only update if we have to, since AppKit does work even if the size is the same. + [cell setControlSize:(NSControlSize)size]; +} + +static void updateStates(NSCell* cell, ControlStates states) +{ + // Hover state is not supported by Aqua. + + // Pressed state + bool oldPressed = [cell isHighlighted]; + bool pressed = states & PressedState; + if (pressed != oldPressed) + [cell setHighlighted:pressed]; + + // Enabled state + bool oldEnabled = [cell isEnabled]; + bool enabled = states & EnabledState; + if (enabled != oldEnabled) + [cell setEnabled:enabled]; + + // Focused state + bool oldFocused = [cell showsFirstResponder]; + bool focused = states & FocusState; + if (focused != oldFocused) + [cell setShowsFirstResponder:focused]; + + // Checked and Indeterminate + bool oldIndeterminate = [cell state] == NSMixedState; + bool indeterminate = (states & IndeterminateState); + bool checked = states & CheckedState; + bool oldChecked = [cell state] == NSOnState; + if (oldIndeterminate != indeterminate || checked != oldChecked) + [cell setState:indeterminate ? NSMixedState : (checked ? NSOnState : NSOffState)]; + + // Window Inactive state + NSControlTint oldTint = [cell controlTint]; + bool windowInactive = (states & WindowInactiveState); + NSControlTint tint = windowInactive ? static_cast<NSControlTint>(NSClearControlTint) + : [NSColor currentControlTint]; + if (tint != oldTint) + [cell setControlTint:tint]; +} + +static ThemeDrawState convertControlStatesToThemeDrawState(ThemeButtonKind kind, ControlStates states) +{ + if (states & ReadOnlyState) + return kThemeStateUnavailableInactive; + if (!(states & EnabledState)) + return kThemeStateUnavailableInactive; + + // Do not process PressedState if !EnabledState or ReadOnlyState. + if (states & PressedState) { + if (kind == kThemeIncDecButton || kind == kThemeIncDecButtonSmall || kind == kThemeIncDecButtonMini) + return states & SpinUpState ? kThemeStatePressedUp : kThemeStatePressedDown; + return kThemeStatePressed; + } + return kThemeStateActive; +} + +static IntRect inflateRect(const IntRect& zoomedRect, const IntSize& zoomedSize, const int* margins, float zoomFactor) +{ + // Only do the inflation if the available width/height are too small. Otherwise try to + // fit the glow/check space into the available box's width/height. + int widthDelta = zoomedRect.width() - (zoomedSize.width() + margins[leftMargin] * zoomFactor + margins[rightMargin] * zoomFactor); + int heightDelta = zoomedRect.height() - (zoomedSize.height() + margins[topMargin] * zoomFactor + margins[bottomMargin] * zoomFactor); + IntRect result(zoomedRect); + if (widthDelta < 0) { + result.setX(result.x() - margins[leftMargin] * zoomFactor); + result.setWidth(result.width() - widthDelta); + } + if (heightDelta < 0) { + result.setY(result.y() - margins[topMargin] * zoomFactor); + result.setHeight(result.height() - heightDelta); + } + return result; +} + +// Checkboxes + +static const IntSize* checkboxSizes() +{ + static const IntSize sizes[3] = { IntSize(14, 14), IntSize(12, 12), IntSize(10, 10) }; + return sizes; +} + +static const int* checkboxMargins(NSControlSize controlSize) +{ + static const int margins[3][4] = + { + { 3, 4, 4, 2 }, + { 4, 3, 3, 3 }, + { 4, 3, 3, 3 }, + }; + return margins[controlSize]; +} + +static LengthSize checkboxSize(const Font& font, const LengthSize& zoomedSize, float zoomFactor) +{ + // If the width and height are both specified, then we have nothing to do. + if (!zoomedSize.width().isIntrinsicOrAuto() && !zoomedSize.height().isIntrinsicOrAuto()) + return zoomedSize; + + // Use the font size to determine the intrinsic width of the control. + return sizeFromFont(font, zoomedSize, zoomFactor, checkboxSizes()); +} + +static NSButtonCell *checkbox(ControlStates states, const IntRect& zoomedRect, float zoomFactor) +{ + static NSButtonCell *checkboxCell; + if (!checkboxCell) { + checkboxCell = [[NSButtonCell alloc] init]; + [checkboxCell setButtonType:NSSwitchButton]; + [checkboxCell setTitle:nil]; + [checkboxCell setAllowsMixedState:YES]; + [checkboxCell setFocusRingType:NSFocusRingTypeExterior]; + } + + // Set the control size based off the rectangle we're painting into. + setControlSize(checkboxCell, checkboxSizes(), zoomedRect.size(), zoomFactor); + + // Update the various states we respond to. + updateStates(checkboxCell, states); + + return checkboxCell; +} + +// FIXME: Share more code with radio buttons. +static void paintCheckbox(ControlStates states, GraphicsContext* context, const IntRect& zoomedRect, float zoomFactor, ScrollView* scrollView) +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS + + // Determine the width and height needed for the control and prepare the cell for painting. + NSButtonCell *checkboxCell = checkbox(states, zoomedRect, zoomFactor); + LocalCurrentGraphicsContext localContext(context); + + context->save(); + + NSControlSize controlSize = [checkboxCell controlSize]; + IntSize zoomedSize = checkboxSizes()[controlSize]; + zoomedSize.setWidth(zoomedSize.width() * zoomFactor); + zoomedSize.setHeight(zoomedSize.height() * zoomFactor); + IntRect inflatedRect = inflateRect(zoomedRect, zoomedSize, checkboxMargins(controlSize), zoomFactor); + + if (zoomFactor != 1.0f) { + inflatedRect.setWidth(inflatedRect.width() / zoomFactor); + inflatedRect.setHeight(inflatedRect.height() / zoomFactor); + context->translate(inflatedRect.x(), inflatedRect.y()); + context->scale(FloatSize(zoomFactor, zoomFactor)); + context->translate(-inflatedRect.x(), -inflatedRect.y()); + } + + { + FocusIndicationFix::ScopedFixer fix; + [checkboxCell drawWithFrame:NSRect(inflatedRect) inView:FlippedView()]; + } + [checkboxCell setControlView:nil]; + + context->restore(); + + END_BLOCK_OBJC_EXCEPTIONS +} + +// Radio Buttons + +static const IntSize* radioSizes() +{ + static const IntSize sizes[3] = { IntSize(14, 15), IntSize(12, 13), IntSize(10, 10) }; + return sizes; +} + +static const int* radioMargins(NSControlSize controlSize) +{ + static const int margins[3][4] = + { + { 2, 2, 4, 2 }, + { 3, 2, 3, 2 }, + { 1, 0, 2, 0 }, + }; + return margins[controlSize]; +} + +static LengthSize radioSize(const Font& font, const LengthSize& zoomedSize, float zoomFactor) +{ + // If the width and height are both specified, then we have nothing to do. + if (!zoomedSize.width().isIntrinsicOrAuto() && !zoomedSize.height().isIntrinsicOrAuto()) + return zoomedSize; + + // Use the font size to determine the intrinsic width of the control. + return sizeFromFont(font, zoomedSize, zoomFactor, radioSizes()); +} + +static NSButtonCell *radio(ControlStates states, const IntRect& zoomedRect, float zoomFactor) +{ + static NSButtonCell *radioCell; + if (!radioCell) { + radioCell = [[NSButtonCell alloc] init]; + [radioCell setButtonType:NSRadioButton]; + [radioCell setTitle:nil]; + [radioCell setFocusRingType:NSFocusRingTypeExterior]; + } + + // Set the control size based off the rectangle we're painting into. + setControlSize(radioCell, radioSizes(), zoomedRect.size(), zoomFactor); + + // Update the various states we respond to. + updateStates(radioCell, states); + + return radioCell; +} + +static void paintRadio(ControlStates states, GraphicsContext* context, const IntRect& zoomedRect, float zoomFactor, ScrollView* scrollView) +{ + // Determine the width and height needed for the control and prepare the cell for painting. + NSButtonCell *radioCell = radio(states, zoomedRect, zoomFactor); + LocalCurrentGraphicsContext localContext(context); + + context->save(); + + NSControlSize controlSize = [radioCell controlSize]; + IntSize zoomedSize = radioSizes()[controlSize]; + zoomedSize.setWidth(zoomedSize.width() * zoomFactor); + zoomedSize.setHeight(zoomedSize.height() * zoomFactor); + IntRect inflatedRect = inflateRect(zoomedRect, zoomedSize, radioMargins(controlSize), zoomFactor); + + if (zoomFactor != 1.0f) { + inflatedRect.setWidth(inflatedRect.width() / zoomFactor); + inflatedRect.setHeight(inflatedRect.height() / zoomFactor); + context->translate(inflatedRect.x(), inflatedRect.y()); + context->scale(FloatSize(zoomFactor, zoomFactor)); + context->translate(-inflatedRect.x(), -inflatedRect.y()); + } + + BEGIN_BLOCK_OBJC_EXCEPTIONS + { + FocusIndicationFix::ScopedFixer fix; + [radioCell drawWithFrame:NSRect(inflatedRect) inView:FlippedView()]; + } + [radioCell setControlView:nil]; + END_BLOCK_OBJC_EXCEPTIONS + + context->restore(); +} + +// Buttons + +// Buttons really only constrain height. They respect width. +static const IntSize* buttonSizes() +{ + static const IntSize sizes[3] = { IntSize(0, 21), IntSize(0, 18), IntSize(0, 15) }; + return sizes; +} + +#if ENABLE(DATALIST) +static const IntSize* listButtonSizes() +{ + static const IntSize sizes[3] = { IntSize(21, 21), IntSize(19, 18), IntSize(17, 16) }; + return sizes; +} +#endif + +static const int* buttonMargins(NSControlSize controlSize) +{ + static const int margins[3][4] = + { + { 4, 6, 7, 6 }, + { 4, 5, 6, 5 }, + { 0, 1, 1, 1 }, + }; + return margins[controlSize]; +} + +static void setupButtonCell(NSButtonCell *&buttonCell, ControlPart part, ControlStates states, const IntRect& zoomedRect, float zoomFactor) +{ + if (!buttonCell) { + buttonCell = [[NSButtonCell alloc] init]; + [buttonCell setTitle:nil]; + [buttonCell setButtonType:NSMomentaryPushInButton]; + if (states & DefaultState) + [buttonCell setKeyEquivalent:@"\r"]; + } + + // Set the control size based off the rectangle we're painting into. + const IntSize* sizes = buttonSizes(); +#if ENABLE(DATALIST) + if (part == ListButtonPart) { + [buttonCell setBezelStyle:NSRoundedDisclosureBezelStyle]; + sizes = listButtonSizes(); + } else +#endif + if (part == SquareButtonPart || zoomedRect.height() > buttonSizes()[NSRegularControlSize].height() * zoomFactor) { + // Use the square button + if ([buttonCell bezelStyle] != NSShadowlessSquareBezelStyle) + [buttonCell setBezelStyle:NSShadowlessSquareBezelStyle]; + } else if ([buttonCell bezelStyle] != NSRoundedBezelStyle) + [buttonCell setBezelStyle:NSRoundedBezelStyle]; + + setControlSize(buttonCell, sizes, zoomedRect.size(), zoomFactor); + + // Update the various states we respond to. + updateStates(buttonCell, states); +} + +static NSButtonCell *button(ControlPart part, ControlStates states, const IntRect& zoomedRect, float zoomFactor) +{ + bool isDefault = states & DefaultState; + static NSButtonCell *cells[2]; + setupButtonCell(cells[isDefault], part, states, zoomedRect, zoomFactor); + return cells[isDefault]; +} + +static void paintButton(ControlPart part, ControlStates states, GraphicsContext* context, const IntRect& zoomedRect, float zoomFactor, ScrollView* scrollView) +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS + + // Determine the width and height needed for the control and prepare the cell for painting. + NSButtonCell *buttonCell = button(part, states, zoomedRect, zoomFactor); + LocalCurrentGraphicsContext localContext(context); + + NSControlSize controlSize = [buttonCell controlSize]; +#if ENABLE(DATALIST) + IntSize zoomedSize = (part == ListButtonPart ? listButtonSizes() : buttonSizes())[controlSize]; +#else + IntSize zoomedSize = buttonSizes()[controlSize]; +#endif + zoomedSize.setWidth(zoomedRect.width()); // Buttons don't ever constrain width, so the zoomed width can just be honored. + zoomedSize.setHeight(zoomedSize.height() * zoomFactor); + IntRect inflatedRect = zoomedRect; + if ([buttonCell bezelStyle] == NSRoundedBezelStyle) { + // Center the button within the available space. + if (inflatedRect.height() > zoomedSize.height()) { + inflatedRect.setY(inflatedRect.y() + (inflatedRect.height() - zoomedSize.height()) / 2); + inflatedRect.setHeight(zoomedSize.height()); + } + + // Now inflate it to account for the shadow. + inflatedRect = inflateRect(inflatedRect, zoomedSize, buttonMargins(controlSize), zoomFactor); + + if (zoomFactor != 1.0f) { + inflatedRect.setWidth(inflatedRect.width() / zoomFactor); + inflatedRect.setHeight(inflatedRect.height() / zoomFactor); + context->translate(inflatedRect.x(), inflatedRect.y()); + context->scale(FloatSize(zoomFactor, zoomFactor)); + context->translate(-inflatedRect.x(), -inflatedRect.y()); + } + } + + { + FocusIndicationFix::ScopedFixer fix; + [buttonCell drawWithFrame:NSRect(inflatedRect) inView:FlippedView()]; + } + [buttonCell setControlView:nil]; + + END_BLOCK_OBJC_EXCEPTIONS +} + +// Stepper + +static const IntSize* stepperSizes() +{ + static const IntSize sizes[3] = { IntSize(19, 27), IntSize(15, 22), IntSize(13, 15) }; + return sizes; +} + +// We don't use controlSizeForFont() for steppers because the stepper height +// should be equal to or less than the corresponding text field height, +static NSControlSize stepperControlSizeForFont(const Font& font) +{ + int fontSize = font.pixelSize(); + if (fontSize >= 18) + return NSRegularControlSize; + if (fontSize >= 13) + return NSSmallControlSize; + return NSMiniControlSize; +} + +static void paintStepper(ControlStates states, GraphicsContext* context, const IntRect& zoomedRect, float zoomFactor, ScrollView*) +{ + // We don't use NSStepperCell because there are no ways to draw an + // NSStepperCell with the up button highlighted. + + HIThemeButtonDrawInfo drawInfo; + drawInfo.version = 0; + drawInfo.state = convertControlStatesToThemeDrawState(kThemeIncDecButton, states); + drawInfo.adornment = kThemeAdornmentDefault; + ControlSize controlSize = controlSizeFromPixelSize(stepperSizes(), zoomedRect.size(), zoomFactor); + if (controlSize == NSSmallControlSize) + drawInfo.kind = kThemeIncDecButtonSmall; + else if (controlSize == NSMiniControlSize) + drawInfo.kind = kThemeIncDecButtonMini; + else + drawInfo.kind = kThemeIncDecButton; + + IntRect rect(zoomedRect); + context->save(); + if (zoomFactor != 1.0f) { + rect.setWidth(rect.width() / zoomFactor); + rect.setHeight(rect.height() / zoomFactor); + context->translate(rect.x(), rect.y()); + context->scale(FloatSize(zoomFactor, zoomFactor)); + context->translate(-rect.x(), -rect.y()); + } + CGRect bounds(rect); + // Adjust 'bounds' so that HIThemeDrawButton(bounds,...) draws exactly on 'rect'. + CGRect backgroundBounds; + HIThemeGetButtonBackgroundBounds(&bounds, &drawInfo, &backgroundBounds); + if (bounds.origin.x != backgroundBounds.origin.x) + bounds.origin.x += bounds.origin.x - backgroundBounds.origin.x; + if (bounds.origin.y != backgroundBounds.origin.y) + bounds.origin.y += bounds.origin.y - backgroundBounds.origin.y; + HIThemeDrawButton(&bounds, &drawInfo, context->platformContext(), kHIThemeOrientationNormal, 0); + context->restore(); +} + +// Theme overrides + +int ThemeChromiumMac::baselinePositionAdjustment(ControlPart part) const +{ + if (part == CheckboxPart || part == RadioPart) + return -2; + return Theme::baselinePositionAdjustment(part); +} + +FontDescription ThemeChromiumMac::controlFont(ControlPart part, const Font& font, float zoomFactor) const +{ + switch (part) { + case PushButtonPart: { + FontDescription fontDescription; + fontDescription.setIsAbsoluteSize(true); + fontDescription.setGenericFamily(FontDescription::SerifFamily); + + NSFont* nsFont = [NSFont systemFontOfSize:[NSFont systemFontSizeForControlSize:controlSizeForFont(font)]]; + fontDescription.firstFamily().setFamily([nsFont familyName]); + fontDescription.setComputedSize([nsFont pointSize] * zoomFactor); + fontDescription.setSpecifiedSize([nsFont pointSize] * zoomFactor); + return fontDescription; + } + default: + return Theme::controlFont(part, font, zoomFactor); + } +} + +LengthSize ThemeChromiumMac::controlSize(ControlPart part, const Font& font, const LengthSize& zoomedSize, float zoomFactor) const +{ + switch (part) { + case CheckboxPart: + return checkboxSize(font, zoomedSize, zoomFactor); + case RadioPart: + return radioSize(font, zoomedSize, zoomFactor); + case PushButtonPart: + // Height is reset to auto so that specified heights can be ignored. + return sizeFromFont(font, LengthSize(zoomedSize.width(), Length()), zoomFactor, buttonSizes()); +#if ENABLE(DATALIST) + case ListButtonPart: + return sizeFromFont(font, LengthSize(zoomedSize.width(), Length()), zoomFactor, listButtonSizes()); +#endif + case InnerSpinButtonPart: + // We don't use inner spin buttons on Mac. + return LengthSize(Length(Fixed), Length(Fixed)); + case OuterSpinButtonPart: + if (!zoomedSize.width().isIntrinsicOrAuto() && !zoomedSize.height().isIntrinsicOrAuto()) + return zoomedSize; + return sizeFromNSControlSize(stepperControlSizeForFont(font), zoomedSize, zoomFactor, stepperSizes()); + default: + return zoomedSize; + } +} + +LengthSize ThemeChromiumMac::minimumControlSize(ControlPart part, const Font& font, float zoomFactor) const +{ + switch (part) { + case SquareButtonPart: + case DefaultButtonPart: + case ButtonPart: + case ListButtonPart: + return LengthSize(Length(0, Fixed), Length(static_cast<int>(15 * zoomFactor), Fixed)); + case InnerSpinButtonPart: + // We don't use inner spin buttons on Mac. + return LengthSize(Length(Fixed), Length(Fixed)); + case OuterSpinButtonPart: { + IntSize base = stepperSizes()[NSMiniControlSize]; + return LengthSize(Length(static_cast<int>(base.width() * zoomFactor), Fixed), + Length(static_cast<int>(base.height() * zoomFactor), Fixed)); + } + default: + return Theme::minimumControlSize(part, font, zoomFactor); + } +} + +LengthBox ThemeChromiumMac::controlBorder(ControlPart part, const Font& font, const LengthBox& zoomedBox, float zoomFactor) const +{ + switch (part) { + case SquareButtonPart: + case DefaultButtonPart: + case ButtonPart: + case ListButtonPart: + return LengthBox(0, zoomedBox.right().value(), 0, zoomedBox.left().value()); + default: + return Theme::controlBorder(part, font, zoomedBox, zoomFactor); + } +} + +LengthBox ThemeChromiumMac::controlPadding(ControlPart part, const Font& font, const LengthBox& zoomedBox, float zoomFactor) const +{ + switch (part) { + case PushButtonPart: { + // Just use 8px. AppKit wants to use 11px for mini buttons, but that padding is just too large + // for real-world Web sites (creating a huge necessary minimum width for buttons whose space is + // by definition constrained, since we select mini only for small cramped environments. + // This also guarantees the HTML <button> will match our rendering by default, since we're using a consistent + // padding. + const int padding = 8 * zoomFactor; + return LengthBox(0, padding, 0, padding); + } + default: + return Theme::controlPadding(part, font, zoomedBox, zoomFactor); + } +} + +void ThemeChromiumMac::inflateControlPaintRect(ControlPart part, ControlStates states, IntRect& zoomedRect, float zoomFactor) const +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS + switch (part) { + case CheckboxPart: { + // We inflate the rect as needed to account for padding included in the cell to accommodate the checkbox + // shadow" and the check. We don't consider this part of the bounds of the control in WebKit. + NSCell *cell = checkbox(states, zoomedRect, zoomFactor); + NSControlSize controlSize = [cell controlSize]; + IntSize zoomedSize = checkboxSizes()[controlSize]; + zoomedSize.setHeight(zoomedSize.height() * zoomFactor); + zoomedSize.setWidth(zoomedSize.width() * zoomFactor); + zoomedRect = inflateRect(zoomedRect, zoomedSize, checkboxMargins(controlSize), zoomFactor); + break; + } + case RadioPart: { + // We inflate the rect as needed to account for padding included in the cell to accommodate the radio button + // shadow". We don't consider this part of the bounds of the control in WebKit. + NSCell *cell = radio(states, zoomedRect, zoomFactor); + NSControlSize controlSize = [cell controlSize]; + IntSize zoomedSize = radioSizes()[controlSize]; + zoomedSize.setHeight(zoomedSize.height() * zoomFactor); + zoomedSize.setWidth(zoomedSize.width() * zoomFactor); + zoomedRect = inflateRect(zoomedRect, zoomedSize, radioMargins(controlSize), zoomFactor); + break; + } + case PushButtonPart: + case DefaultButtonPart: + case ButtonPart: { + NSButtonCell *cell = button(part, states, zoomedRect, zoomFactor); + NSControlSize controlSize = [cell controlSize]; + + // We inflate the rect as needed to account for the Aqua button's shadow. + if ([cell bezelStyle] == NSRoundedBezelStyle) { + IntSize zoomedSize = buttonSizes()[controlSize]; + zoomedSize.setHeight(zoomedSize.height() * zoomFactor); + zoomedSize.setWidth(zoomedRect.width()); // Buttons don't ever constrain width, so the zoomed width can just be honored. + zoomedRect = inflateRect(zoomedRect, zoomedSize, buttonMargins(controlSize), zoomFactor); + } + break; + } + case OuterSpinButtonPart: { + static const int stepperMargin[4] = { 0, 0, 0, 0 }; + ControlSize controlSize = controlSizeFromPixelSize(stepperSizes(), zoomedRect.size(), zoomFactor); + IntSize zoomedSize = stepperSizes()[controlSize]; + zoomedSize.setHeight(zoomedSize.height() * zoomFactor); + zoomedSize.setWidth(zoomedSize.width() * zoomFactor); + zoomedRect = inflateRect(zoomedRect, zoomedSize, stepperMargin, zoomFactor); + break; + } + default: + break; + } + END_BLOCK_OBJC_EXCEPTIONS +} + +void ThemeChromiumMac::paint(ControlPart part, ControlStates states, GraphicsContext* context, const IntRect& zoomedRect, float zoomFactor, ScrollView* scrollView) const +{ + switch (part) { + case CheckboxPart: + paintCheckbox(states, context, zoomedRect, zoomFactor, scrollView); + break; + case RadioPart: + paintRadio(states, context, zoomedRect, zoomFactor, scrollView); + break; + case PushButtonPart: + case DefaultButtonPart: + case ButtonPart: + case SquareButtonPart: + case ListButtonPart: + paintButton(part, states, context, zoomedRect, zoomFactor, scrollView); + break; + case OuterSpinButtonPart: + paintStepper(states, context, zoomedRect, zoomFactor, scrollView); + break; + default: + break; + } +} + +} diff --git a/Source/WebCore/platform/chromium/WidgetChromium.cpp b/Source/WebCore/platform/chromium/WidgetChromium.cpp new file mode 100644 index 0000000..1b7fef4 --- /dev/null +++ b/Source/WebCore/platform/chromium/WidgetChromium.cpp @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "Widget.h" + +#include "Assertions.h" +#include "ChromiumBridge.h" + +namespace WebCore { + +Widget::Widget(PlatformWidget widget) +{ + init(widget); +} + +Widget::~Widget() +{ + ASSERT(!parent()); +} + +void Widget::show() +{ +} + +void Widget::hide() +{ +} + +void Widget::setCursor(const Cursor& cursor) +{ + ChromiumBridge::widgetSetCursor(this, cursor); +} + +void Widget::paint(GraphicsContext*, const IntRect&) +{ +} + +void Widget::setFocus(bool focused) +{ +} + +void Widget::setIsSelected(bool) +{ +} + +IntRect Widget::frameRect() const +{ + return m_frame; +} + +void Widget::setFrameRect(const IntRect& rect) +{ + m_frame = rect; +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/WindowsVersion.cpp b/Source/WebCore/platform/chromium/WindowsVersion.cpp new file mode 100644 index 0000000..a9632cb --- /dev/null +++ b/Source/WebCore/platform/chromium/WindowsVersion.cpp @@ -0,0 +1,52 @@ +// Copyright (c) 2008, Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#include "config.h" +#include "WindowsVersion.h" + +#include <windows.h> + +namespace WebCore { + +bool isVistaOrNewer() +{ + // Cache the result to avoid asking every time. + static bool haveResult = false; + static bool result = false; + if (!haveResult) { + OSVERSIONINFO versionInfo; + versionInfo.dwOSVersionInfoSize = sizeof(versionInfo); + GetVersionEx(&versionInfo); + + haveResult = true; + result = versionInfo.dwMajorVersion >= 6; + } + return result; +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/WindowsVersion.h b/Source/WebCore/platform/chromium/WindowsVersion.h new file mode 100644 index 0000000..3b2010a --- /dev/null +++ b/Source/WebCore/platform/chromium/WindowsVersion.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2008, 2009, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef WindowsVersion_h +#define WindowsVersion_h + +namespace WebCore { + + bool isVistaOrNewer(); + +} // namespace WebCore + +#endif diff --git a/Source/WebCore/platform/chromium/WritableDataObject.cpp b/Source/WebCore/platform/chromium/WritableDataObject.cpp new file mode 100644 index 0000000..7cbf42c --- /dev/null +++ b/Source/WebCore/platform/chromium/WritableDataObject.cpp @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2010 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "WritableDataObject.h" + +#include "ChromiumBridge.h" +#include "ClipboardMimeTypes.h" + +namespace WebCore { + +PassRefPtr<WritableDataObject> WritableDataObject::create(Clipboard::ClipboardType clipboardType) +{ + return adoptRef(new WritableDataObject(clipboardType)); +} + +WritableDataObject::WritableDataObject(Clipboard::ClipboardType clipboardType) + : m_clipboardType(clipboardType) +{ +} + +void WritableDataObject::clearData(const String& type) +{ + m_dataMap.remove(type); + if (type == mimeTypeTextURIList) + m_urlTitle = ""; + else if (type == mimeTypeTextHTML) + m_htmlBaseURL = KURL(); +} + +void WritableDataObject::clearAllExceptFiles() +{ + // FIXME: The spec does not provide a way to populate FileList currently. In + // fact, the spec explicitly states that dragging files can only happen from + // outside a browsing context. + clearAll(); +} + +void WritableDataObject::clearAll() +{ + m_dataMap.clear(); + m_urlTitle = ""; + m_htmlBaseURL = KURL(); + m_fileContentFilename = ""; + if (m_fileContent) + m_fileContent->clear(); + m_fileExtension = ""; +} + +bool WritableDataObject::setData(const String& type, const String& data) +{ + if (m_clipboardType == Clipboard::CopyAndPaste) { + // FIXME: This is currently unimplemented on the Chromium-side. This is + // "okay" for now since the original implementation didn't support it + // anyway. Going forward, this is something we'll need to fix though. + ChromiumBridge::clipboardWriteData(type, data, ""); + return true; + } + m_dataMap.set(type, data); + if (type == mimeTypeTextURIList) + m_urlTitle = ""; + else if (type == mimeTypeTextHTML) + m_htmlBaseURL = KURL(); + return true; +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/chromium/WritableDataObject.h b/Source/WebCore/platform/chromium/WritableDataObject.h new file mode 100644 index 0000000..c475d15 --- /dev/null +++ b/Source/WebCore/platform/chromium/WritableDataObject.h @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2010 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef WritableDataObject_h +#define WritableDataObject_h + +#include "Clipboard.h" +#include "KURL.h" +#include "PlatformString.h" +#include "SharedBuffer.h" +#include <wtf/HashMap.h> +#include <wtf/RefCounted.h> +#include <wtf/RefPtr.h> +#include <wtf/text/StringHash.h> + +namespace WebCore { + +// Used for one way communication of drag/drop and copy/paste data from the +// renderer to the browser. This is intenteded to be used in dragstart/copy/cut +// events. Due to shortcomings, writes to the pasteboard cannot be performed +// atomically. +class WritableDataObject : public RefCounted<WritableDataObject> { +public: + static PassRefPtr<WritableDataObject> create(Clipboard::ClipboardType); + + void clearData(const String& type); + void clearAllExceptFiles(); + void clearAll(); + bool setData(const String& type, const String& data); + + void setUrlTitle(const String& title) { m_urlTitle = title; } + void setHtmlBaseUrl(const KURL& baseURL) { m_htmlBaseURL = baseURL; } + + // Used for transferring drag data from the renderer to the browser. + HashMap<String, String> dataMap() const { return m_dataMap; } + String urlTitle() const { return m_urlTitle; } + KURL htmlBaseURL() const { return m_htmlBaseURL; } + + String fileExtension() const { return m_fileExtension; } + String fileContentFilename() const { return m_fileContentFilename; } + PassRefPtr<SharedBuffer> fileContent() const { return m_fileContent; } + void setFileExtension(const String& fileExtension) { m_fileExtension = fileExtension; } + void setFileContentFilename(const String& fileContentFilename) { m_fileContentFilename = fileContentFilename; } + void setFileContent(PassRefPtr<SharedBuffer> fileContent) { m_fileContent = fileContent; } + +private: + explicit WritableDataObject(Clipboard::ClipboardType); + + Clipboard::ClipboardType m_clipboardType; + + HashMap<String, String> m_dataMap; + String m_urlTitle; + KURL m_htmlBaseURL; + String m_fileExtension; + String m_fileContentFilename; + RefPtr<SharedBuffer> m_fileContent; +}; + +} // namespace WebCore + +#endif |