diff options
author | Upstream <upstream-import@none> | 1970-01-12 13:46:40 +0000 |
---|---|---|
committer | Upstream <upstream-import@none> | 1970-01-12 13:46:40 +0000 |
commit | d8543bb6618c17b12da906afa77d216f58cf4058 (patch) | |
tree | c58dc05ed86825bd0ef8d305d58c8205106b540f /WebCore/platform/mac | |
download | external_webkit-d8543bb6618c17b12da906afa77d216f58cf4058.zip external_webkit-d8543bb6618c17b12da906afa77d216f58cf4058.tar.gz external_webkit-d8543bb6618c17b12da906afa77d216f58cf4058.tar.bz2 |
external/webkit r30707
Diffstat (limited to 'WebCore/platform/mac')
58 files changed, 7458 insertions, 0 deletions
diff --git a/WebCore/platform/mac/AutodrainedPool.mm b/WebCore/platform/mac/AutodrainedPool.mm new file mode 100644 index 0000000..6febaef --- /dev/null +++ b/WebCore/platform/mac/AutodrainedPool.mm @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2007 Apple 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. + * 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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 "AutodrainedPool.h" + +namespace WebCore { + +AutodrainedPool::AutodrainedPool(int iterationLimit) + : m_iterationLimit(iterationLimit) + , m_iterationCount(0) + , m_pool([[NSAutoreleasePool alloc] init]) +{ +} + +AutodrainedPool::~AutodrainedPool() +{ + [m_pool drain]; +} + +void AutodrainedPool::cycle() +{ + if (++m_iterationCount == m_iterationLimit) { + [m_pool drain]; + m_pool = [[NSAutoreleasePool alloc] init]; + m_iterationCount = 0; + } +} + +} // namespace WebCore diff --git a/WebCore/platform/mac/BlockExceptions.h b/WebCore/platform/mac/BlockExceptions.h new file mode 100644 index 0000000..a3016d2 --- /dev/null +++ b/WebCore/platform/mac/BlockExceptions.h @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2003 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. + */ + +#import <Foundation/NSException.h> + +void ReportBlockedObjCException(NSException *); + +#define BEGIN_BLOCK_OBJC_EXCEPTIONS @try { +#define END_BLOCK_OBJC_EXCEPTIONS } @catch(NSException *localException) { ReportBlockedObjCException(localException); } + diff --git a/WebCore/platform/mac/BlockExceptions.mm b/WebCore/platform/mac/BlockExceptions.mm new file mode 100644 index 0000000..f2dc1ec --- /dev/null +++ b/WebCore/platform/mac/BlockExceptions.mm @@ -0,0 +1,38 @@ +/* + * Copyright (C) 2003, 2007 Apple 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. + */ + +#import "config.h" +#import "BlockExceptions.h" + +#import <wtf/Assertions.h> + +void ReportBlockedObjCException(NSException *exception) +{ +#if ASSERT_DISABLED + NSLog(@"*** WebKit discarding exception: <%@> %@", [exception name], [exception reason]); +#else + ASSERT_WITH_MESSAGE(0, "Uncaught exception - %@", exception); +#endif +} diff --git a/WebCore/platform/mac/ClipboardMac.h b/WebCore/platform/mac/ClipboardMac.h new file mode 100644 index 0000000..480d828 --- /dev/null +++ b/WebCore/platform/mac/ClipboardMac.h @@ -0,0 +1,86 @@ +/* + * Copyright (C) 2004, 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. + */ + +// An implementation of the clipboard class from IE that talks to the Cocoa Pasteboard + +#ifndef ClipboardMac_h +#define ClipboardMac_h + +#include "IntPoint.h" +#include "Clipboard.h" +#include "ClipboardAccessPolicy.h" +#include "CachedResourceClient.h" +#include <wtf/RetainPtr.h> + +#ifdef __OBJC__ +@class NSImage; +@class NSPasteboard; +#else +class NSImage; +class NSPasteboard; +typedef unsigned NSDragOperation; +#endif + +namespace WebCore { + +class Frame; + +class ClipboardMac : public Clipboard, public CachedResourceClient { +public: + ClipboardMac(bool forDragging, NSPasteboard *, ClipboardAccessPolicy, Frame* = 0); + virtual ~ClipboardMac(); + + void clearData(const String& type); + void clearAllData(); + String getData(const String& type, bool& success) const; + bool setData(const String& type, const String& data); + + virtual bool hasData(); + + // extensions beyond IE's API + virtual HashSet<String> types() const; + + void setDragImage(CachedImage*, const IntPoint&); + void setDragImageElement(Node *, const IntPoint&); + + virtual DragImageRef createDragImage(IntPoint& dragLoc) const; + virtual void declareAndWriteDragImage(Element*, const KURL&, const String& title, Frame*); + virtual void writeRange(Range*, Frame* frame); + virtual void writeURL(const KURL&, const String&, Frame* frame); + + // Methods for getting info in Cocoa's type system + NSImage *dragNSImage(NSPoint&) const; // loc converted from dragLoc, based on whole image size + NSPasteboard *pasteboard() { return m_pasteboard.get(); } +private: + void setDragImage(CachedImage*, Node*, const IntPoint&); + + RetainPtr<NSPasteboard> m_pasteboard; + int m_changeCount; + Frame* m_frame; // used on the source side to generate dragging images +}; + +} + +#endif diff --git a/WebCore/platform/mac/ClipboardMac.mm b/WebCore/platform/mac/ClipboardMac.mm new file mode 100644 index 0000000..efd1fcf --- /dev/null +++ b/WebCore/platform/mac/ClipboardMac.mm @@ -0,0 +1,359 @@ +/* + * Copyright (C) 2004, 2005, 2006, 2008 Apple 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. + */ + +#import "config.h" +#import "ClipboardMac.h" + +#import "DOMElementInternal.h" +#import "DragClient.h" +#import "DragController.h" +#import "Editor.h" +#import "FoundationExtras.h" +#import "Image.h" +#import "Page.h" +#import "Pasteboard.h" +#import "RenderImage.h" +#import "WebCoreSystemInterface.h" + +namespace WebCore { + +ClipboardMac::ClipboardMac(bool forDragging, NSPasteboard *pasteboard, ClipboardAccessPolicy policy, Frame *frame) + : Clipboard(policy, forDragging) + , m_pasteboard(pasteboard) + , m_frame(frame) +{ + m_changeCount = [m_pasteboard.get() changeCount]; +} + +ClipboardMac::~ClipboardMac() +{ +} + +bool ClipboardMac::hasData() +{ + return m_pasteboard && [m_pasteboard.get() types] && [[m_pasteboard.get() types] count] > 0; +} + +static NSString *cocoaTypeFromMIMEType(const String& type) +{ + String qType = type.stripWhiteSpace(); + + // two special cases for IE compatibility + if (qType == "Text") + return NSStringPboardType; + if (qType == "URL") + return NSURLPboardType; + + // Ignore any trailing charset - JS strings are Unicode, which encapsulates the charset issue + if (qType == "text/plain" || qType.startsWith("text/plain;")) + return NSStringPboardType; + if (qType == "text/uri-list") + // special case because UTI doesn't work with Cocoa's URL type + return NSURLPboardType; // note special case in getData to read NSFilenamesType + + // Try UTI now + NSString *mimeType = qType; + CFStringRef UTIType = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, (CFStringRef)mimeType, NULL); + if (UTIType) { + CFStringRef pbType = UTTypeCopyPreferredTagWithClass(UTIType, kUTTagClassNSPboardType); + CFRelease(UTIType); + if (pbType) + return HardAutorelease(pbType); + } + + // No mapping, just pass the whole string though + return qType; +} + +static String MIMETypeFromCocoaType(NSString *type) +{ + // UTI may not do these right, so make sure we get the right, predictable result + if ([type isEqualToString:NSStringPboardType]) + return "text/plain"; + if ([type isEqualToString:NSURLPboardType] || [type isEqualToString:NSFilenamesPboardType]) + return "text/uri-list"; + + // Now try the general UTI mechanism + CFStringRef UTIType = UTTypeCreatePreferredIdentifierForTag(kUTTagClassNSPboardType, (CFStringRef)type, NULL); + if (UTIType) { + CFStringRef mimeType = UTTypeCopyPreferredTagWithClass(UTIType, kUTTagClassMIMEType); + CFRelease(UTIType); + if (mimeType) { + String result = mimeType; + CFRelease(mimeType); + return result; + } + } + + // No mapping, just pass the whole string though + return type; +} + +void ClipboardMac::clearData(const String& type) +{ + if (policy() != ClipboardWritable) + return; + + // note NSPasteboard enforces changeCount itself on writing - can't write if not the owner + + NSString *cocoaType = cocoaTypeFromMIMEType(type); + if (cocoaType) { + [m_pasteboard.get() setString:@"" forType:cocoaType]; + } +} + +void ClipboardMac::clearAllData() +{ + if (policy() != ClipboardWritable) + return; + + // note NSPasteboard enforces changeCount itself on writing - can't write if not the owner + + [m_pasteboard.get() declareTypes:[NSArray array] owner:nil]; +} + +String ClipboardMac::getData(const String& type, bool& success) const +{ + success = false; + if (policy() != ClipboardReadable) + return String(); + + NSString *cocoaType = cocoaTypeFromMIMEType(type); + NSString *cocoaValue = nil; + NSArray *availableTypes = [m_pasteboard.get() types]; + + // Fetch the data in different ways for the different Cocoa types + + if ([cocoaType isEqualToString:NSURLPboardType]) { + // When both URL and filenames are present, filenames is superior since it can contain a list. + // must check this or we get a printf from CF when there's no data of this type + if ([availableTypes containsObject:NSFilenamesPboardType]) { + NSArray *fileList = [m_pasteboard.get() propertyListForType:NSFilenamesPboardType]; + if (fileList && [fileList isKindOfClass:[NSArray class]]) { + unsigned count = [fileList count]; + if (count > 0) { + if (type != "text/uri-list") + count = 1; + NSMutableString *urls = [NSMutableString string]; + unsigned i; + for (i = 0; i < count; i++) { + if (i > 0) { + [urls appendString:@"\n"]; + } + NSString *string = [fileList objectAtIndex:i]; + if (![string isKindOfClass:[NSString class]]) + break; + NSURL *url = [NSURL fileURLWithPath:string]; + [urls appendString:[url absoluteString]]; + } + if (i == count) + cocoaValue = urls; + } + } + } + if (!cocoaValue) { + // must check this or we get a printf from CF when there's no data of this type + if ([availableTypes containsObject:NSURLPboardType]) { + NSURL *url = [NSURL URLFromPasteboard:m_pasteboard.get()]; + if (url) { + cocoaValue = [url absoluteString]; + } + } + } + } else if (cocoaType) { + cocoaValue = [m_pasteboard.get() stringForType:cocoaType]; + } + + // Enforce changeCount ourselves for security. We check after reading instead of before to be + // sure it doesn't change between our testing the change count and accessing the data. + if (cocoaValue && m_changeCount == [m_pasteboard.get() changeCount]) { + success = true; + return cocoaValue; + } + + return String(); +} + +bool ClipboardMac::setData(const String &type, const String &data) +{ + if (policy() != ClipboardWritable) + return false; + // note NSPasteboard enforces changeCount itself on writing - can't write if not the owner + + NSString *cocoaType = cocoaTypeFromMIMEType(type); + NSString *cocoaData = data; + + if ([cocoaType isEqualToString:NSURLPboardType]) { + [m_pasteboard.get() addTypes:[NSArray arrayWithObject:NSURLPboardType] owner:nil]; + NSURL *url = [[NSURL alloc] initWithString:cocoaData]; + [url writeToPasteboard:m_pasteboard.get()]; + + if ([url isFileURL]) { + [m_pasteboard.get() addTypes:[NSArray arrayWithObject:NSFilenamesPboardType] owner:nil]; + NSArray *fileList = [NSArray arrayWithObject:[url path]]; + [m_pasteboard.get() setPropertyList:fileList forType:NSFilenamesPboardType]; + } + + [url release]; + return true; + } + + if (cocoaType) { + // everything else we know of goes on the pboard as a string + [m_pasteboard.get() addTypes:[NSArray arrayWithObject:cocoaType] owner:nil]; + return [m_pasteboard.get() setString:cocoaData forType:cocoaType]; + } + + return false; +} + +HashSet<String> ClipboardMac::types() const +{ + if (policy() != ClipboardReadable && policy() != ClipboardTypesReadable) + return HashSet<String>(); + + NSArray *types = [m_pasteboard.get() types]; + + // Enforce changeCount ourselves for security. We check after reading instead of before to be + // sure it doesn't change between our testing the change count and accessing the data. + if (m_changeCount != [m_pasteboard.get() changeCount]) + return HashSet<String>(); + + HashSet<String> result; + if (types) { + unsigned count = [types count]; + unsigned i; + for (i = 0; i < count; i++) { + NSString *pbType = [types objectAtIndex:i]; + if ([pbType isEqualToString:@"NeXT plain ascii pasteboard type"]) + continue; // skip this ancient type that gets auto-supplied by some system conversion + + String str = MIMETypeFromCocoaType(pbType); + if (!result.contains(str)) + result.add(str); + } + } + return result; +} + +// The rest of these getters don't really have any impact on security, so for now make no checks + +void ClipboardMac::setDragImage(CachedImage* img, const IntPoint &loc) +{ + setDragImage(img, 0, loc); +} + +void ClipboardMac::setDragImageElement(Node *node, const IntPoint &loc) +{ + setDragImage(0, node, loc); +} + +void ClipboardMac::setDragImage(CachedImage* image, Node *node, const IntPoint &loc) +{ + if (policy() == ClipboardImageWritable || policy() == ClipboardWritable) { + if (m_dragImage) + m_dragImage->deref(this); + m_dragImage = image; + if (m_dragImage) + m_dragImage->ref(this); + + m_dragLoc = loc; + m_dragImageElement = node; + + if (dragStarted() && m_changeCount == [m_pasteboard.get() changeCount]) { + NSPoint cocoaLoc; + NSImage* cocoaImage = dragNSImage(cocoaLoc); + if (cocoaImage) { + // Dashboard wants to be able to set the drag image during dragging, but Cocoa does not allow this. + // Instead we must drop down to the CoreGraphics API. + wkSetDragImage(cocoaImage, cocoaLoc); + + // Hack: We must post an event to wake up the NSDragManager, which is sitting in a nextEvent call + // up the stack from us because the CoreFoundation drag manager does not use the run loop by itself. + // This is the most innocuous event to use, per Kristen Forster. + NSEvent* ev = [NSEvent mouseEventWithType:NSMouseMoved location:NSZeroPoint + modifierFlags:0 timestamp:0 windowNumber:0 context:nil eventNumber:0 clickCount:0 pressure:0]; + [NSApp postEvent:ev atStart:YES]; + } + } + // Else either 1) we haven't started dragging yet, so we rely on the part to install this drag image + // as part of getting the drag kicked off, or 2) Someone kept a ref to the clipboard and is trying to + // set the image way too late. + } +} + +void ClipboardMac::writeRange(Range* range, Frame* frame) +{ + ASSERT(range); + ASSERT(frame); + Pasteboard::writeSelection(m_pasteboard.get(), range, frame->editor()->smartInsertDeleteEnabled() && frame->selectionGranularity() == WordGranularity, frame); +} + +void ClipboardMac::writeURL(const KURL& url, const String& title, Frame* frame) +{ + ASSERT(frame); + ASSERT(m_pasteboard); + Pasteboard::writeURL(m_pasteboard.get(), nil, url, title, frame); +} + +void ClipboardMac::declareAndWriteDragImage(Element* element, const KURL& url, const String& title, Frame* frame) +{ + ASSERT(frame); + if (Page* page = frame->page()) + page->dragController()->client()->declareAndWriteDragImage(m_pasteboard.get(), [DOMElement _wrapElement:element], url, title, frame); +} + +DragImageRef ClipboardMac::createDragImage(IntPoint& loc) const +{ + NSPoint nsloc = {loc.x(), loc.y()}; + DragImageRef result = dragNSImage(nsloc); + loc = (IntPoint)nsloc; + return result; +} + +NSImage *ClipboardMac::dragNSImage(NSPoint& loc) const +{ + NSImage *result = nil; + if (m_dragImageElement) { + if (m_frame) { + NSRect imageRect; + NSRect elementRect; + result = m_frame->snapshotDragImage(m_dragImageElement.get(), &imageRect, &elementRect); + // Client specifies point relative to element, not the whole image, which may include child + // layers spread out all over the place. + loc.x = elementRect.origin.x - imageRect.origin.x + m_dragLoc.x(); + loc.y = elementRect.origin.y - imageRect.origin.y + m_dragLoc.y(); + loc.y = imageRect.size.height - loc.y; + } + } else if (m_dragImage) { + result = m_dragImage->image()->getNSImage(); + + loc = m_dragLoc; + loc.y = [result size].height - loc.y; + } + return result; +} + +} diff --git a/WebCore/platform/mac/ContextMenuItemMac.mm b/WebCore/platform/mac/ContextMenuItemMac.mm new file mode 100644 index 0000000..c5e2942 --- /dev/null +++ b/WebCore/platform/mac/ContextMenuItemMac.mm @@ -0,0 +1,155 @@ +/* + * 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 "ContextMenuItem.h" + +#include "ContextMenu.h" + +namespace WebCore { + +static NSMutableArray* menuToArray(NSMenu* menu) +{ + NSMutableArray* itemsArray = [NSMutableArray array]; + int total = [menu numberOfItems]; + for (int i = 0; i < total; i++) + [itemsArray addObject:[menu itemAtIndex:i]]; + + return itemsArray; +} + +ContextMenuItem::ContextMenuItem(NSMenuItem* item) +{ + m_platformDescription = item; +} + +ContextMenuItem::ContextMenuItem(ContextMenu* subMenu) +{ + NSMenuItem* item = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""]; + m_platformDescription = item; + [item release]; + + [m_platformDescription.get() setTag:ContextMenuItemTagNoAction]; + if (subMenu) + setSubMenu(subMenu); +} + +ContextMenuItem::ContextMenuItem(ContextMenuItemType type, ContextMenuAction action, const String& title, ContextMenu* subMenu) +{ + if (type == SeparatorType) { + m_platformDescription = [NSMenuItem separatorItem]; + return; + } + + NSMenuItem* item = [[NSMenuItem alloc] initWithTitle:title action:nil keyEquivalent:@""]; + m_platformDescription = item; + [item release]; + + [m_platformDescription.get() setTag:action]; + if (subMenu) + setSubMenu(subMenu); +} + +ContextMenuItem::~ContextMenuItem() +{ +} + +NSMenuItem* ContextMenuItem::releasePlatformDescription() +{ + NSMenuItem* item = [m_platformDescription.get() retain]; + m_platformDescription = 0; + return item; +} + +ContextMenuItemType ContextMenuItem::type() const +{ + if ([m_platformDescription.get() isSeparatorItem]) + return SeparatorType; + if ([m_platformDescription.get() hasSubmenu]) + return SubmenuType; + return ActionType; +} + +ContextMenuAction ContextMenuItem::action() const +{ + return static_cast<ContextMenuAction>([m_platformDescription.get() tag]); +} + +String ContextMenuItem::title() const +{ + return [m_platformDescription.get() title]; +} + +NSMutableArray* ContextMenuItem::platformSubMenu() const +{ + return menuToArray([m_platformDescription.get() submenu]); +} + +void ContextMenuItem::setType(ContextMenuItemType type) +{ + if (type == SeparatorType) + m_platformDescription = [NSMenuItem separatorItem]; +} + +void ContextMenuItem::setAction(ContextMenuAction action) +{ + [m_platformDescription.get() setTag:action]; +} + +void ContextMenuItem::setTitle(const String& title) +{ + [m_platformDescription.get() setTitle:title]; +} + +void ContextMenuItem::setSubMenu(ContextMenu* menu) +{ + NSArray* subMenuArray = menu->platformDescription(); + NSMenu* subMenu = [[NSMenu alloc] init]; + [subMenu setAutoenablesItems:NO]; + for (unsigned i = 0; i < [subMenuArray count]; i++) + [subMenu insertItem:[subMenuArray objectAtIndex:i] atIndex:i]; + [m_platformDescription.get() setSubmenu:subMenu]; + [subMenu release]; +} + +void ContextMenuItem::setChecked(bool checked) +{ + if (checked) + [m_platformDescription.get() setState:NSOnState]; + else + [m_platformDescription.get() setState:NSOffState]; +} + +void ContextMenuItem::setEnabled(bool enable) +{ + [m_platformDescription.get() setEnabled:enable]; +} + +bool ContextMenuItem::enabled() const +{ + return [m_platformDescription.get() isEnabled]; +} + +} diff --git a/WebCore/platform/mac/ContextMenuMac.mm b/WebCore/platform/mac/ContextMenuMac.mm new file mode 100644 index 0000000..b56d0b9 --- /dev/null +++ b/WebCore/platform/mac/ContextMenuMac.mm @@ -0,0 +1,154 @@ +/* + * 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 "ContextMenu.h" + +#include "ContextMenuController.h" + +@interface WebCoreMenuTarget : NSObject { + WebCore::ContextMenuController* _menuController; +} ++ (WebCoreMenuTarget*)sharedMenuTarget; +- (WebCore::ContextMenuController*)menuController; +- (void)setMenuController:(WebCore::ContextMenuController*)menuController; +- (void)forwardContextMenuAction:(id)sender; +- (BOOL)validateMenuItem:(NSMenuItem *)item; +@end + +static WebCoreMenuTarget* target; + +@implementation WebCoreMenuTarget + ++ (WebCoreMenuTarget*)sharedMenuTarget +{ + if (!target) + target = [[WebCoreMenuTarget alloc] init]; + return target; +} + +- (WebCore::ContextMenuController*)menuController +{ + return _menuController; +} + +- (void)setMenuController:(WebCore::ContextMenuController*)menuController +{ + _menuController = menuController; +} + +- (void)forwardContextMenuAction:(id)sender +{ + WebCore::ContextMenuItem item(WebCore::ActionType, static_cast<WebCore::ContextMenuAction>([sender tag]), [sender title]); + _menuController->contextMenuItemSelected(&item); +} + +- (BOOL)validateMenuItem:(NSMenuItem *)item +{ + WebCore::ContextMenuItem coreItem(item); + ASSERT(_menuController->contextMenu()); + _menuController->contextMenu()->checkOrEnableIfNeeded(coreItem); + return coreItem.enabled(); +} + +@end + +namespace WebCore { + +ContextMenu::ContextMenu(const HitTestResult& result) + : m_hitTestResult(result) +{ + NSMutableArray* array = [[NSMutableArray alloc] init]; + m_platformDescription = array; + [array release]; + + [[WebCoreMenuTarget sharedMenuTarget] setMenuController:controller()]; +} + +ContextMenu::ContextMenu(const HitTestResult& result, const PlatformMenuDescription menu) + : m_hitTestResult(result) + , m_platformDescription(menu) +{ + [[WebCoreMenuTarget sharedMenuTarget] setMenuController:controller()]; +} + +ContextMenu::~ContextMenu() +{ +} + +static void setMenuItemTarget(NSMenuItem* menuItem) +{ + [menuItem setTarget:[WebCoreMenuTarget sharedMenuTarget]]; + [menuItem setAction:@selector(forwardContextMenuAction:)]; +} + +void ContextMenu::appendItem(ContextMenuItem& item) +{ + checkOrEnableIfNeeded(item); + + ContextMenuItemType type = item.type(); + NSMenuItem* platformItem = item.releasePlatformDescription(); + if (type == ActionType) + setMenuItemTarget(platformItem); + + [m_platformDescription.get() addObject:platformItem]; + [platformItem release]; +} + +void ContextMenu::insertItem(unsigned position, ContextMenuItem& item) +{ + checkOrEnableIfNeeded(item); + + ContextMenuItemType type = item.type(); + NSMenuItem* platformItem = item.releasePlatformDescription(); + if (type == ActionType) + setMenuItemTarget(platformItem); + + [m_platformDescription.get() insertObject:platformItem atIndex:position]; + [platformItem release]; +} + +unsigned ContextMenu::itemCount() const +{ + return [m_platformDescription.get() count]; +} + +void ContextMenu::setPlatformDescription(NSMutableArray* menu) +{ + if (m_platformDescription.get() != menu) + m_platformDescription = menu; +} + +NSMutableArray* ContextMenu::platformDescription() const +{ + return m_platformDescription.get(); +} + +NSMutableArray* ContextMenu::releasePlatformDescription() +{ + return m_platformDescription.releaseRef(); +} + +} diff --git a/WebCore/platform/mac/CookieJar.mm b/WebCore/platform/mac/CookieJar.mm new file mode 100644 index 0000000..5fe7a63 --- /dev/null +++ b/WebCore/platform/mac/CookieJar.mm @@ -0,0 +1,94 @@ +/* + * Copyright (C) 2003, 2006, 2008 Apple 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. + */ + +#import "config.h" +#import "CookieJar.h" + +#import "BlockExceptions.h" +#import "KURL.h" +#import <wtf/RetainPtr.h> + +#ifdef BUILDING_ON_TIGER +typedef unsigned NSUInteger; +#endif + +namespace WebCore { + +String cookies(const Document* /*document*/, const KURL& url) +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + + NSURL *cookieURL = url; + NSArray *cookiesForURL = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:cookieURL]; + + // <rdar://problem/5632883> On 10.5, NSHTTPCookieStorage would happily store an empty cookie, which would be sent as "Cookie: =". + // We have a workaround in setCookies() to prevent that, but we also need to avoid sending cookies that were previously stored. + NSUInteger count = [cookiesForURL count]; + RetainPtr<NSMutableArray> cookiesForURLFilteredCopy(AdoptNS, [[NSMutableArray alloc] initWithCapacity:count]); + for (NSUInteger i = 0; i < count; ++i) { + NSHTTPCookie *cookie = (NSHTTPCookie *)[cookiesForURL objectAtIndex:i]; + if ([[cookie name] length] != 0) + [cookiesForURLFilteredCopy.get() addObject:cookie]; + } + + NSDictionary *header = [NSHTTPCookie requestHeaderFieldsWithCookies:cookiesForURLFilteredCopy.get()]; + return [header objectForKey:@"Cookie"]; + + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +void setCookies(Document* /*document*/, const KURL& url, const KURL& policyBaseURL, const String& cookieStr) +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + + // <rdar://problem/5632883> On 10.5, NSHTTPCookieStorage would happily store an empty cookie, which would be sent as "Cookie: =". + if (cookieStr.isEmpty()) + return; + + NSURL *cookieURL = url; + + // <http://bugs.webkit.org/show_bug.cgi?id=6531>, <rdar://4409034> + // cookiesWithResponseHeaderFields doesn't parse cookies without a value + String cookieString = cookieStr.contains('=') ? cookieStr : cookieStr + "="; + + NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:[NSDictionary dictionaryWithObject:cookieString forKey:@"Set-Cookie"] forURL:cookieURL]; + [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:cookies forURL:cookieURL mainDocumentURL:policyBaseURL]; + + END_BLOCK_OBJC_EXCEPTIONS; +} + +bool cookiesEnabled(const Document* /*document*/) +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + + NSHTTPCookieAcceptPolicy cookieAcceptPolicy = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookieAcceptPolicy]; + return cookieAcceptPolicy == NSHTTPCookieAcceptPolicyAlways || cookieAcceptPolicy == NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain; + + END_BLOCK_OBJC_EXCEPTIONS; + return false; +} + +} diff --git a/WebCore/platform/mac/CursorMac.mm b/WebCore/platform/mac/CursorMac.mm new file mode 100644 index 0000000..fe8680f --- /dev/null +++ b/WebCore/platform/mac/CursorMac.mm @@ -0,0 +1,298 @@ +/* + * Copyright (C) 2004, 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. + */ + +#import "config.h" +#import "Cursor.h" + +#import "BlockExceptions.h" +#import "FoundationExtras.h" +#import "Image.h" +#import "IntPoint.h" + +@interface WebCoreCursorBundle : NSObject { } +@end + +@implementation WebCoreCursorBundle +@end + +namespace WebCore { + +// Simple NSCursor calls shouldn't need protection, +// but creating a cursor with a bad image might throw. + +static NSCursor* createCustomCursor(Image* image, const IntPoint& hotspot) +{ + // FIXME: The cursor won't animate. Not sure if that's a big deal. + NSImage* img = image->getNSImage(); + if (!img) + return 0; + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[NSCursor alloc] initWithImage:img hotSpot:hotspot]; + END_BLOCK_OBJC_EXCEPTIONS; + return 0; +} + +// Leak these cursors intentionally, that way we won't waste time trying to clean them +// up at process exit time. +static NSCursor* leakNamedCursor(const char* name, int x, int y) +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + NSString* resourceName = [[NSString alloc] initWithUTF8String:name]; + NSImage* cursorImage = [[NSImage alloc] initWithContentsOfFile: + [[NSBundle bundleForClass:[WebCoreCursorBundle class]] + pathForResource:resourceName ofType:@"png"]]; + [resourceName release]; + NSCursor* cursor = 0; + if (cursorImage) { + NSPoint hotSpotPoint = {x, y}; // workaround for 4213314 + cursor = [[NSCursor alloc] initWithImage:cursorImage hotSpot:hotSpotPoint]; + [cursorImage release]; + } + return cursor; + END_BLOCK_OBJC_EXCEPTIONS; + return 0; +} + +Cursor::Cursor(Image* image, const IntPoint& hotspot) + : m_impl(HardRetainWithNSRelease(createCustomCursor(image, hotspot))) +{ +} + +Cursor::Cursor(const Cursor& other) + : m_impl(HardRetain(other.m_impl)) +{ +} + +Cursor::~Cursor() +{ + HardRelease(m_impl); +} + +Cursor& Cursor::operator=(const Cursor& other) +{ + HardRetain(other.m_impl); + HardRelease(m_impl); + m_impl = other.m_impl; + return *this; +} + +Cursor::Cursor(NSCursor* c) + : m_impl(HardRetain(c)) +{ +} + +const Cursor& pointerCursor() +{ + static Cursor c = [NSCursor arrowCursor]; + return c; +} + +const Cursor& crossCursor() +{ + static Cursor c = leakNamedCursor("crossHairCursor", 11, 11); + return c; +} + +const Cursor& handCursor() +{ + static Cursor c = leakNamedCursor("linkCursor", 6, 1); + return c; +} + +const Cursor& moveCursor() +{ + static Cursor c = leakNamedCursor("moveCursor", 7, 7); + return c; +} + +const Cursor& verticalTextCursor() +{ + static Cursor c = leakNamedCursor("verticalTextCursor", 7, 7); + return c; +} + +const Cursor& cellCursor() +{ + static Cursor c = leakNamedCursor("cellCursor", 7, 7); + return c; +} + +const Cursor& contextMenuCursor() +{ + static Cursor c = leakNamedCursor("contextMenuCursor", 3, 2); + return c; +} + +const Cursor& aliasCursor() +{ + static Cursor c = leakNamedCursor("aliasCursor", 11, 3); + return c; +} + +const Cursor& zoomInCursor() +{ + static Cursor c = leakNamedCursor("zoomInCursor", 7, 7); + return c; +} + +const Cursor& zoomOutCursor() +{ + static Cursor c = leakNamedCursor("zoomOutCursor", 7, 7); + return c; +} + +const Cursor& copyCursor() +{ + static Cursor c = leakNamedCursor("copyCursor", 3, 2); + return c; +} + +const Cursor& noneCursor() +{ + static Cursor c = leakNamedCursor("noneCursor", 7, 7); + return c; +} + +const Cursor& progressCursor() +{ + static Cursor c = leakNamedCursor("progressCursor", 3, 2); + return c; +} + +const Cursor& noDropCursor() +{ + static Cursor c = leakNamedCursor("noDropCursor", 3, 1); + return c; +} + +const Cursor& notAllowedCursor() +{ + static Cursor c = leakNamedCursor("notAllowedCursor", 11, 11); + return c; +} + +const Cursor& iBeamCursor() +{ + static Cursor c = [NSCursor IBeamCursor]; + return c; +} + +const Cursor& waitCursor() +{ + static Cursor c = leakNamedCursor("waitCursor", 7, 7); + return c; +} + +const Cursor& helpCursor() +{ + static Cursor c = leakNamedCursor("helpCursor", 8, 8); + return c; +} + +const Cursor& eastResizeCursor() +{ + static Cursor c = leakNamedCursor("eastResizeCursor", 14, 7); + return c; +} + +const Cursor& northResizeCursor() +{ + static Cursor c = leakNamedCursor("northResizeCursor", 7, 1); + return c; +} + +const Cursor& northEastResizeCursor() +{ + static Cursor c = leakNamedCursor("northEastResizeCursor", 14, 1); + return c; +} + +const Cursor& northWestResizeCursor() +{ + static Cursor c = leakNamedCursor("northWestResizeCursor", 0, 0); + return c; +} + +const Cursor& southResizeCursor() +{ + static Cursor c = leakNamedCursor("southResizeCursor", 7, 14); + return c; +} + +const Cursor& southEastResizeCursor() +{ + static Cursor c = leakNamedCursor("southEastResizeCursor", 14, 14); + return c; +} + +const Cursor& southWestResizeCursor() +{ + static Cursor c = leakNamedCursor("southWestResizeCursor", 1, 14); + return c; +} + +const Cursor& westResizeCursor() +{ + static Cursor c = leakNamedCursor("westResizeCursor", 1, 7); + return c; +} + +const Cursor& northSouthResizeCursor() +{ + static Cursor c = leakNamedCursor("northSouthResizeCursor", 7, 7); + return c; +} + +const Cursor& eastWestResizeCursor() +{ + static Cursor c = leakNamedCursor("eastWestResizeCursor", 7, 7); + return c; +} + +const Cursor& northEastSouthWestResizeCursor() +{ + static Cursor c = leakNamedCursor("northEastSouthWestResizeCursor", 7, 7); + return c; +} + +const Cursor& northWestSouthEastResizeCursor() +{ + static Cursor c = leakNamedCursor("northWestSouthEastResizeCursor", 7, 7); + return c; +} + +const Cursor& columnResizeCursor() +{ + static Cursor c = [NSCursor resizeLeftRightCursor]; + return c; +} + +const Cursor& rowResizeCursor() +{ + static Cursor c = [NSCursor resizeUpDownCursor]; + return c; +} + +} diff --git a/WebCore/platform/mac/DragDataMac.mm b/WebCore/platform/mac/DragDataMac.mm new file mode 100644 index 0000000..73170d7 --- /dev/null +++ b/WebCore/platform/mac/DragDataMac.mm @@ -0,0 +1,133 @@ +/* + * Copyright (C) 2007 Apple 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. + */ + +#import "config.h" +#import "DragData.h" + +#import "ClipboardMac.h" +#import "ClipboardAccessPolicy.h" +#import "Document.h" +#import "DocumentFragment.h" +#import "DOMDocumentFragment.h" +#import "DOMDocumentFragmentInternal.h" +#import "MIMETypeRegistry.h" +#import "Pasteboard.h" +#import "PasteboardHelper.h" + +namespace WebCore { + +DragData::DragData(DragDataRef data, const IntPoint& clientPosition, const IntPoint& globalPosition, + DragOperation sourceOperationMask, PasteboardHelper* pasteboardHelper) + : m_clientPosition(clientPosition) + , m_globalPosition(globalPosition) + , m_platformDragData(data) + , m_draggingSourceOperationMask(sourceOperationMask) + , m_pasteboardHelper(pasteboardHelper) +{ + ASSERT(pasteboardHelper); +} + +bool DragData::canSmartReplace() const +{ + //Need to call this so that the various Pasteboard type strings are intialised + Pasteboard::generalPasteboard(); + return [[[m_platformDragData draggingPasteboard] types] containsObject:WebSmartPastePboardType]; +} + +bool DragData::containsColor() const +{ + return [[[m_platformDragData draggingPasteboard] types] containsObject:NSColorPboardType]; +} + +bool DragData::containsFiles() const +{ + return [[[m_platformDragData draggingPasteboard] types] containsObject:NSFilenamesPboardType]; +} + +void DragData::asFilenames(Vector<String>& result) const +{ + NSArray *filenames = [[m_platformDragData draggingPasteboard] propertyListForType:NSFilenamesPboardType]; + NSEnumerator *fileEnumerator = [filenames objectEnumerator]; + + while (NSString *filename = [fileEnumerator nextObject]) + result.append(filename); +} + +bool DragData::containsPlainText() const +{ + NSPasteboard *pasteboard = [m_platformDragData draggingPasteboard]; + NSArray *types = [pasteboard types]; + + return [types containsObject:NSStringPboardType] + || [types containsObject:NSRTFDPboardType] + || [types containsObject:NSRTFPboardType] + || [types containsObject:NSFilenamesPboardType] + || [NSURL URLFromPasteboard:pasteboard]; +} + +String DragData::asPlainText() const +{ + return m_pasteboardHelper->plainTextFromPasteboard([m_platformDragData draggingPasteboard]); +} + +Color DragData::asColor() const +{ + NSColor *color = [NSColor colorFromPasteboard:[m_platformDragData draggingPasteboard]]; + return makeRGBA((int)([color redComponent] * 255.0 + 0.5), (int)([color greenComponent] * 255.0 + 0.5), + (int)([color blueComponent] * 255.0 + 0.5), (int)([color alphaComponent] * 255.0 + 0.5)); +} + +Clipboard* DragData::createClipboard(ClipboardAccessPolicy policy) const +{ + return new ClipboardMac(true, [m_platformDragData draggingPasteboard], policy); +} + +bool DragData::containsCompatibleContent() const +{ + + NSPasteboard *pasteboard = [m_platformDragData draggingPasteboard]; + NSMutableSet *types = [NSMutableSet setWithArray:[pasteboard types]]; + [types intersectSet:[NSSet setWithArray:m_pasteboardHelper->insertablePasteboardTypes()]]; + return [types count] != 0; +} + +bool DragData::containsURL() const +{ + return !asURL().isEmpty(); +} + +String DragData::asURL(String* title) const +{ + return m_pasteboardHelper->urlFromPasteboard([m_platformDragData draggingPasteboard], title); +} + + +PassRefPtr<DocumentFragment> DragData::asFragment(Document* doc) const +{ + return [m_pasteboardHelper->fragmentFromPasteboard([m_platformDragData draggingPasteboard]) _documentFragment]; +} + +} + diff --git a/WebCore/platform/mac/DragImageMac.mm b/WebCore/platform/mac/DragImageMac.mm new file mode 100644 index 0000000..098a548 --- /dev/null +++ b/WebCore/platform/mac/DragImageMac.mm @@ -0,0 +1,103 @@ +/* + * Copyright (C) 2007 Apple 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. + */ +#import "config.h" +#import "DragImage.h" + +#import "CachedImage.h" +#import "Image.h" +#import "KURL.h" +#import "PlatformString.h" +#import "ResourceResponse.h" +#import <FoundationExtras.h> + +namespace WebCore { + + + +IntSize dragImageSize(DragImageRef image) +{ + return (IntSize)[image.get() size]; +} + +void deleteDragImage(DragImageRef image) +{ + //DragImageRef is a RetainPtr, so we don't need to explicitly delete it +} + +DragImageRef scaleDragImage(DragImageRef image, FloatSize scale) +{ + NSSize originalSize = [image.get() size]; + NSSize newSize = NSMakeSize((originalSize.width * scale.width()), (originalSize.height * scale.height())); + newSize.width = roundf(newSize.width); + newSize.height = roundf(newSize.height); + [image.get() setScalesWhenResized:YES]; + [image.get() setSize:newSize]; + return image; +} + +DragImageRef dissolveDragImageToFraction(DragImageRef image, float delta) +{ + RetainPtr<NSImage> dissolvedImage(AdoptNS, [[NSImage alloc] initWithSize:[image.get() size]]); + + NSPoint point = [image.get() isFlipped] ? NSMakePoint(0, [image.get() size].height) : NSZeroPoint; + + // In this case the dragging image is always correct. + [dissolvedImage.get() setFlipped:[image.get() isFlipped]]; + + [dissolvedImage.get() lockFocus]; + [image.get() dissolveToPoint:point fraction: delta]; + [dissolvedImage.get() unlockFocus]; + + [image.get() lockFocus]; + [dissolvedImage.get() compositeToPoint:point operation:NSCompositeCopy]; + [image.get() unlockFocus]; + + return image; +} + +DragImageRef createDragImageFromImage(Image* image) +{ + DragImageRef dragImage(AdoptNS, [image->getNSImage() copy]); + [dragImage.get() setSize:(NSSize)(image->size())]; + return dragImage; +} + +DragImageRef createDragImageIconForCachedImage(CachedImage* image) +{ + const String& filename = image->response().suggestedFilename(); + NSString *extension = nil; + int dotIndex = filename.reverseFind('.'); + + if (dotIndex > 0 && dotIndex < (int)(filename.length() - 1)) // require that a . exists after the first character and before the last + extension = filename.substring(dotIndex + 1); + else + //It might be worth doing a further look up to pull the extension from the mimetype + extension = @""; + + return DragImageRef([[NSWorkspace sharedWorkspace] iconForFileType:extension]); + +} + +} diff --git a/WebCore/platform/mac/FileChooserMac.mm b/WebCore/platform/mac/FileChooserMac.mm new file mode 100644 index 0000000..a83418c --- /dev/null +++ b/WebCore/platform/mac/FileChooserMac.mm @@ -0,0 +1,129 @@ +/* + * Copyright (C) 2006, 2007 Apple 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. + * 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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 "FileChooser.h" + +#import "Document.h" +#import "SimpleFontData.h" +#import "Frame.h" +#import "Icon.h" +#import "LocalizedStrings.h" +#import "StringTruncator.h" +#import "WebCoreFrameBridge.h" + +using namespace WebCore; + +@interface WebCoreOpenPanelController : NSObject <WebCoreOpenPanelResultListener> { + FileChooser *_fileChooser; + WebCoreFrameBridge *_bridge; +} +- (id)initWithFileChooser:(FileChooser *)fileChooser; +- (void)disconnectFileChooser; +- (void)beginSheetWithFrame:(Frame*)frame; +@end + +@implementation WebCoreOpenPanelController + +- (id)initWithFileChooser:(FileChooser *)fileChooser +{ + self = [super init]; + if (!self) + return nil; + + _fileChooser = fileChooser; + return self; +} + +- (void)disconnectFileChooser +{ + _fileChooser = 0; +} + +- (void)beginSheetWithFrame:(Frame*)frame +{ + if (!_fileChooser) + return; + + _bridge = frame->bridge(); + [_bridge retain]; + [_bridge runOpenPanelForFileButtonWithResultListener:self]; +} + +- (void)chooseFilename:(NSString *)filename +{ + if (_fileChooser) + _fileChooser->chooseFile(filename); + [_bridge release]; +} + +- (void)cancel +{ + [_bridge release]; +} + +@end + +namespace WebCore { + +FileChooser::FileChooser(FileChooserClient* client, const String& filename) + : RefCounted<FileChooser>(0) + , m_client(client) + , m_filename(filename) + , m_icon(chooseIcon(filename)) + , m_controller(AdoptNS, [[WebCoreOpenPanelController alloc] initWithFileChooser:this]) +{ +} + +FileChooser::~FileChooser() +{ + [m_controller.get() disconnectFileChooser]; +} + +void FileChooser::openFileChooser(Document* document) +{ + if (Frame* frame = document->frame()) + [m_controller.get() beginSheetWithFrame:frame]; +} + +String FileChooser::basenameForWidth(const Font& font, int width) const +{ + if (width <= 0) + return String(); + + String strToTruncate; + if (m_filename.isEmpty()) + strToTruncate = fileButtonNoFileSelectedLabel(); + else + strToTruncate = [[NSFileManager defaultManager] displayNameAtPath:m_filename]; + + return StringTruncator::centerTruncate(strToTruncate, width, font, false); +} + +} diff --git a/WebCore/platform/mac/FileSystemMac.mm b/WebCore/platform/mac/FileSystemMac.mm new file mode 100644 index 0000000..98f85bb --- /dev/null +++ b/WebCore/platform/mac/FileSystemMac.mm @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2007 Apple 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. + * 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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 "FileSystem.h" + +#import "PlatformString.h" + +namespace WebCore { + +String homeDirectoryPath() +{ + return NSHomeDirectory(); +} + +} // namespace WebCore diff --git a/WebCore/platform/mac/FoundationExtras.h b/WebCore/platform/mac/FoundationExtras.h new file mode 100644 index 0000000..51a7df0 --- /dev/null +++ b/WebCore/platform/mac/FoundationExtras.h @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2004 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. + */ + +// nil-checked CFRetain/CFRelease covers for Objective-C ids + +// Use CFRetain, CFRelease, HardRetain, or HardRelease instead of +// -[NSObject retain] and -[NSObject release] if you want to store +// a pointer to an Objective-C object into memory that won't +// be scanned for GC, like a C++ object. + +static inline id HardRetain(id obj) +{ + if (obj) CFRetain(obj); + return obj; +} + +static inline void HardRelease(id obj) +{ + if (obj) CFRelease(obj); +} + +// As if CF and Foundation had logically separate reference counts, +// this function first increments the CF retain count, and then +// decrements the NS retain count. This is needed to handle cases where +// -retain/-release aren't equivalent to CFRetain/HardRelease, such as +// when GC is used. + +// Use HardRetainWithNSRelease after allocating and initializing a NSObject +// if you want to store a pointer to that object into memory that won't +// be scanned for GC, like a C++ object. + +static inline id HardRetainWithNSRelease(id obj) +{ + HardRetain(obj); + [obj release]; + return obj; +} + +// Use HardAutorelease to return an object made by a CoreFoundation +// "create" or "copy" function as an autoreleased and garbage collected +// object. CF objects need to be "made collectable" for autorelease to work +// properly under GC. + +static inline id HardAutorelease(CFTypeRef obj) +{ + if (obj) + CFMakeCollectable(obj); + [(id)obj autorelease]; + return (id)obj; +} diff --git a/WebCore/platform/mac/KURLMac.mm b/WebCore/platform/mac/KURLMac.mm new file mode 100644 index 0000000..c913ab4 --- /dev/null +++ b/WebCore/platform/mac/KURLMac.mm @@ -0,0 +1,71 @@ +/* + * Copyright (C) 2004, 2008 Apple 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. + */ + +#import "config.h" +#import "KURL.h" + +#import "FoundationExtras.h" + +namespace WebCore { + +KURL::KURL(NSURL *url) +{ + if (!url) { + parse(0, 0); + return; + } + + CFIndex bytesLength = CFURLGetBytes(reinterpret_cast<CFURLRef>(url), 0, 0); + Vector<char, 512> buffer(bytesLength + 6); // 5 for "file:", 1 for null character to end C string + char* bytes = &buffer[5]; + CFURLGetBytes(reinterpret_cast<CFURLRef>(url), reinterpret_cast<UInt8*>(bytes), bytesLength); + bytes[bytesLength] = '\0'; + if (bytes[0] != '/') { + parse(bytes, 0); + return; + } + + buffer[0] = 'f'; + buffer[1] = 'i'; + buffer[2] = 'l'; + buffer[3] = 'e'; + buffer[4] = ':'; + + parse(buffer.data(), 0); +} + +KURL::operator NSURL *() const +{ + if (isNull()) + return nil; + + // CFURL can't hold an empty URL, unlike NSURL. + if (isEmpty()) + return [NSURL URLWithString:@""]; + + return HardAutorelease(createCFURL()); +} + +} diff --git a/WebCore/platform/mac/KeyEventMac.mm b/WebCore/platform/mac/KeyEventMac.mm new file mode 100644 index 0000000..9aa6d8b --- /dev/null +++ b/WebCore/platform/mac/KeyEventMac.mm @@ -0,0 +1,875 @@ +/* + * Copyright (C) 2004, 2006, 2007 Apple 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. + */ + +#import "config.h" +#import "PlatformKeyboardEvent.h" + +#import "Logging.h" +#import <Carbon/Carbon.h> +#import <wtf/ASCIICType.h> + +using namespace WTF; + +namespace WebCore { + +static String keyIdentifierForKeyEvent(NSEvent* event) +{ + if ([event type] == NSFlagsChanged) + switch ([event keyCode]) { + case 54: // Right Command + case 55: // Left Command + return "Meta"; + + case 57: // Capslock + return "CapsLock"; + + case 56: // Left Shift + case 60: // Right Shift + return "Shift"; + + case 58: // Left Alt + case 61: // Right Alt + return "Alt"; + + case 59: // Left Ctrl + case 62: // Right Ctrl + return "Control"; + + default: + ASSERT_NOT_REACHED(); + return ""; + } + + NSString *s = [event charactersIgnoringModifiers]; + if ([s length] != 1) { + LOG(Events, "received an unexpected number of characters in key event: %u", [s length]); + return "Unidentified"; + } + unichar c = [s characterAtIndex:0]; + switch (c) { + // Each identifier listed in the DOM spec is listed here. + // Many are simply commented out since they do not appear on standard Macintosh keyboards + // or are on a key that doesn't have a corresponding character. + + // "Accept" + // "AllCandidates" + + // "Alt" + case NSMenuFunctionKey: + return "Alt"; + + // "Apps" + // "BrowserBack" + // "BrowserForward" + // "BrowserHome" + // "BrowserRefresh" + // "BrowserSearch" + // "BrowserStop" + // "CapsLock" + + // "Clear" + case NSClearLineFunctionKey: + return "Clear"; + + // "CodeInput" + // "Compose" + // "Control" + // "Crsel" + // "Convert" + // "Copy" + // "Cut" + + // "Down" + case NSDownArrowFunctionKey: + return "Down"; + // "End" + case NSEndFunctionKey: + return "End"; + // "Enter" + case 0x3: case 0xA: case 0xD: // Macintosh calls the one on the main keyboard Return, but Windows calls it Enter, so we'll do the same for the DOM + return "Enter"; + + // "EraseEof" + + // "Execute" + case NSExecuteFunctionKey: + return "Execute"; + + // "Exsel" + + // "F1" + case NSF1FunctionKey: + return "F1"; + // "F2" + case NSF2FunctionKey: + return "F2"; + // "F3" + case NSF3FunctionKey: + return "F3"; + // "F4" + case NSF4FunctionKey: + return "F4"; + // "F5" + case NSF5FunctionKey: + return "F5"; + // "F6" + case NSF6FunctionKey: + return "F6"; + // "F7" + case NSF7FunctionKey: + return "F7"; + // "F8" + case NSF8FunctionKey: + return "F8"; + // "F9" + case NSF9FunctionKey: + return "F9"; + // "F10" + case NSF10FunctionKey: + return "F10"; + // "F11" + case NSF11FunctionKey: + return "F11"; + // "F12" + case NSF12FunctionKey: + return "F12"; + // "F13" + case NSF13FunctionKey: + return "F13"; + // "F14" + case NSF14FunctionKey: + return "F14"; + // "F15" + case NSF15FunctionKey: + return "F15"; + // "F16" + case NSF16FunctionKey: + return "F16"; + // "F17" + case NSF17FunctionKey: + return "F17"; + // "F18" + case NSF18FunctionKey: + return "F18"; + // "F19" + case NSF19FunctionKey: + return "F19"; + // "F20" + case NSF20FunctionKey: + return "F20"; + // "F21" + case NSF21FunctionKey: + return "F21"; + // "F22" + case NSF22FunctionKey: + return "F22"; + // "F23" + case NSF23FunctionKey: + return "F23"; + // "F24" + case NSF24FunctionKey: + return "F24"; + + // "FinalMode" + + // "Find" + case NSFindFunctionKey: + return "Find"; + + // "FullWidth" + // "HalfWidth" + // "HangulMode" + // "HanjaMode" + + // "Help" + case NSHelpFunctionKey: + return "Help"; + + // "Hiragana" + + // "Home" + case NSHomeFunctionKey: + return "Home"; + // "Insert" + case NSInsertFunctionKey: + return "Insert"; + + // "JapaneseHiragana" + // "JapaneseKatakana" + // "JapaneseRomaji" + // "JunjaMode" + // "KanaMode" + // "KanjiMode" + // "Katakana" + // "LaunchApplication1" + // "LaunchApplication2" + // "LaunchMail" + + // "Left" + case NSLeftArrowFunctionKey: + return "Left"; + + // "Meta" + // "MediaNextTrack" + // "MediaPlayPause" + // "MediaPreviousTrack" + // "MediaStop" + + // "ModeChange" + case NSModeSwitchFunctionKey: + return "ModeChange"; + + // "Nonconvert" + // "NumLock" + + // "PageDown" + case NSPageDownFunctionKey: + return "PageDown"; + // "PageUp" + case NSPageUpFunctionKey: + return "PageUp"; + + // "Paste" + + // "Pause" + case NSPauseFunctionKey: + return "Pause"; + + // "Play" + // "PreviousCandidate" + + // "PrintScreen" + case NSPrintScreenFunctionKey: + return "PrintScreen"; + + // "Process" + // "Props" + + // "Right" + case NSRightArrowFunctionKey: + return "Right"; + + // "RomanCharacters" + + // "Scroll" + case NSScrollLockFunctionKey: + return "Scroll"; + // "Select" + case NSSelectFunctionKey: + return "Select"; + + // "SelectMedia" + // "Shift" + + // "Stop" + case NSStopFunctionKey: + return "Stop"; + // "Up" + case NSUpArrowFunctionKey: + return "Up"; + // "Undo" + case NSUndoFunctionKey: + return "Undo"; + + // "VolumeDown" + // "VolumeMute" + // "VolumeUp" + // "Win" + // "Zoom" + + // More function keys, not in the key identifier specification. + case NSF25FunctionKey: + return "F25"; + case NSF26FunctionKey: + return "F26"; + case NSF27FunctionKey: + return "F27"; + case NSF28FunctionKey: + return "F28"; + case NSF29FunctionKey: + return "F29"; + case NSF30FunctionKey: + return "F30"; + case NSF31FunctionKey: + return "F31"; + case NSF32FunctionKey: + return "F32"; + case NSF33FunctionKey: + return "F33"; + case NSF34FunctionKey: + return "F34"; + case NSF35FunctionKey: + return "F35"; + + // Turn 0x7F into 0x08, because backspace needs to always be 0x08. + case 0x7F: + return "U+0008"; + // Standard says that DEL becomes U+007F. + case NSDeleteFunctionKey: + return "U+007F"; + + // Always use 0x09 for tab instead of AppKit's backtab character. + case NSBackTabCharacter: + return "U+0009"; + + case NSBeginFunctionKey: + case NSBreakFunctionKey: + case NSClearDisplayFunctionKey: + case NSDeleteCharFunctionKey: + case NSDeleteLineFunctionKey: + case NSInsertCharFunctionKey: + case NSInsertLineFunctionKey: + case NSNextFunctionKey: + case NSPrevFunctionKey: + case NSPrintFunctionKey: + case NSRedoFunctionKey: + case NSResetFunctionKey: + case NSSysReqFunctionKey: + case NSSystemFunctionKey: + case NSUserFunctionKey: + // FIXME: We should use something other than the vendor-area Unicode values for the above keys. + // For now, just fall through to the default. + default: + return String::format("U+%04X", toASCIIUpper(c)); + } +} + +static bool isKeypadEvent(NSEvent* event) +{ + // Check that this is the type of event that has a keyCode. + switch ([event type]) { + case NSKeyDown: + case NSKeyUp: + case NSFlagsChanged: + break; + default: + return false; + } + + switch ([event keyCode]) { + case 71: // Clear + case 81: // = + case 75: // / + case 67: // * + case 78: // - + case 69: // + + case 76: // Enter + case 65: // . + case 82: // 0 + case 83: // 1 + case 84: // 2 + case 85: // 3 + case 86: // 4 + case 87: // 5 + case 88: // 6 + case 89: // 7 + case 91: // 8 + case 92: // 9 + return true; + } + + return false; +} + +static int windowsKeyCodeForKeyEvent(NSEvent* event) +{ + switch ([event keyCode]) { + // VK_TAB (09) TAB key + case 48: return 0x09; + + // VK_APPS (5D) Right windows/meta key + case 54: // Right Command + return 0x5D; + + // VK_LWIN (5B) Left windows/meta key + case 55: // Left Command + return 0x5B; + + // VK_CAPITAL (14) caps locks key + case 57: // Capslock + return 0x14; + + // VK_SHIFT (10) either shift key + case 56: // Left Shift + case 60: // Right Shift + return 0x10; + + // VK_MENU (12) either alt key + case 58: // Left Alt + case 61: // Right Alt + return 0x12; + + // VK_CONTROL (11) either ctrl key + case 59: // Left Ctrl + case 62: // Right Ctrl + return 0x11; + + // VK_CLEAR (0C) CLEAR key + case 71: return 0x0C; + + // VK_NUMPAD0 (60) Numeric keypad 0 key + case 82: return 0x60; + // VK_NUMPAD1 (61) Numeric keypad 1 key + case 83: return 0x61; + // VK_NUMPAD2 (62) Numeric keypad 2 key + case 84: return 0x62; + // VK_NUMPAD3 (63) Numeric keypad 3 key + case 85: return 0x63; + // VK_NUMPAD4 (64) Numeric keypad 4 key + case 86: return 0x64; + // VK_NUMPAD5 (65) Numeric keypad 5 key + case 87: return 0x65; + // VK_NUMPAD6 (66) Numeric keypad 6 key + case 88: return 0x66; + // VK_NUMPAD7 (67) Numeric keypad 7 key + case 89: return 0x67; + // VK_NUMPAD8 (68) Numeric keypad 8 key + case 91: return 0x68; + // VK_NUMPAD9 (69) Numeric keypad 9 key + case 92: return 0x69; + // VK_MULTIPLY (6A) Multiply key + case 67: return 0x6A; + // VK_ADD (6B) Add key + case 69: return 0x6B; + + // VK_SUBTRACT (6D) Subtract key + case 78: return 0x6D; + // VK_DECIMAL (6E) Decimal key + case 65: return 0x6E; + // VK_DIVIDE (6F) Divide key + case 75: return 0x6F; + } + + NSString* s = [event charactersIgnoringModifiers]; + if ([s length] != 1) + return 0; + + switch ([s characterAtIndex:0]) { + // VK_LBUTTON (01) Left mouse button + // VK_RBUTTON (02) Right mouse button + // VK_CANCEL (03) Control-break processing + // VK_MBUTTON (04) Middle mouse button (three-button mouse) + // VK_XBUTTON1 (05) + // VK_XBUTTON2 (06) + + // VK_BACK (08) BACKSPACE key + case 8: case 0x7F: return 0x08; + // VK_TAB (09) TAB key + case 9: return 0x09; + + // VK_CLEAR (0C) CLEAR key + // handled by key code above + + // VK_RETURN (0D) + case 0xD: case 3: return 0x0D; + + // VK_SHIFT (10) SHIFT key + // VK_CONTROL (11) CTRL key + // VK_MENU (12) ALT key + + // VK_PAUSE (13) PAUSE key + case NSPauseFunctionKey: return 0x13; + + // VK_CAPITAL (14) CAPS LOCK key + // VK_KANA (15) Input Method Editor (IME) Kana mode + // VK_HANGUEL (15) IME Hanguel mode (maintained for compatibility; use VK_HANGUL) + // VK_HANGUL (15) IME Hangul mode + // VK_JUNJA (17) IME Junja mode + // VK_FINAL (18) IME final mode + // VK_HANJA (19) IME Hanja mode + // VK_KANJI (19) IME Kanji mode + + // VK_ESCAPE (1B) ESC key + case 0x1B: return 0x1B; + + // VK_CONVERT (1C) IME convert + // VK_NONCONVERT (1D) IME nonconvert + // VK_ACCEPT (1E) IME accept + // VK_MODECHANGE (1F) IME mode change request + + // VK_SPACE (20) SPACEBAR + case ' ': return 0x20; + // VK_PRIOR (21) PAGE UP key + case NSPageUpFunctionKey: return 0x21; + // VK_NEXT (22) PAGE DOWN key + case NSPageDownFunctionKey: return 0x22; + // VK_END (23) END key + case NSEndFunctionKey: return 0x23; + // VK_HOME (24) HOME key + case NSHomeFunctionKey: return 0x24; + // VK_LEFT (25) LEFT ARROW key + case NSLeftArrowFunctionKey: return 0x25; + // VK_UP (26) UP ARROW key + case NSUpArrowFunctionKey: return 0x26; + // VK_RIGHT (27) RIGHT ARROW key + case NSRightArrowFunctionKey: return 0x27; + // VK_DOWN (28) DOWN ARROW key + case NSDownArrowFunctionKey: return 0x28; + // VK_SELECT (29) SELECT key + case NSSelectFunctionKey: return 0x29; + // VK_PRINT (2A) PRINT key + case NSPrintFunctionKey: return 0x2A; + // VK_EXECUTE (2B) EXECUTE key + case NSExecuteFunctionKey: return 0x2B; + // VK_SNAPSHOT (2C) PRINT SCREEN key + case NSPrintScreenFunctionKey: return 0x2C; + // VK_INSERT (2D) INS key + case NSInsertFunctionKey: case NSHelpFunctionKey: return 0x2D; + // VK_DELETE (2E) DEL key + case NSDeleteFunctionKey: return 0x2E; + + // VK_HELP (2F) HELP key + + // (30) 0 key + case '0': case ')': return 0x30; + // (31) 1 key + case '1': case '!': return 0x31; + // (32) 2 key + case '2': case '@': return 0x32; + // (33) 3 key + case '3': case '#': return 0x33; + // (34) 4 key + case '4': case '$': return 0x34; + // (35) 5 key + case '5': case '%': return 0x35; + // (36) 6 key + case '6': case '^': return 0x36; + // (37) 7 key + case '7': case '&': return 0x37; + // (38) 8 key + case '8': case '*': return 0x38; + // (39) 9 key + case '9': case '(': return 0x39; + // (41) A key + case 'a': case 'A': return 0x41; + // (42) B key + case 'b': case 'B': return 0x42; + // (43) C key + case 'c': case 'C': return 0x43; + // (44) D key + case 'd': case 'D': return 0x44; + // (45) E key + case 'e': case 'E': return 0x45; + // (46) F key + case 'f': case 'F': return 0x46; + // (47) G key + case 'g': case 'G': return 0x47; + // (48) H key + case 'h': case 'H': return 0x48; + // (49) I key + case 'i': case 'I': return 0x49; + // (4A) J key + case 'j': case 'J': return 0x4A; + // (4B) K key + case 'k': case 'K': return 0x4B; + // (4C) L key + case 'l': case 'L': return 0x4C; + // (4D) M key + case 'm': case 'M': return 0x4D; + // (4E) N key + case 'n': case 'N': return 0x4E; + // (4F) O key + case 'o': case 'O': return 0x4F; + // (50) P key + case 'p': case 'P': return 0x50; + // (51) Q key + case 'q': case 'Q': return 0x51; + // (52) R key + case 'r': case 'R': return 0x52; + // (53) S key + case 's': case 'S': return 0x53; + // (54) T key + case 't': case 'T': return 0x54; + // (55) U key + case 'u': case 'U': return 0x55; + // (56) V key + case 'v': case 'V': return 0x56; + // (57) W key + case 'w': case 'W': return 0x57; + // (58) X key + case 'x': case 'X': return 0x58; + // (59) Y key + case 'y': case 'Y': return 0x59; + // (5A) Z key + case 'z': case 'Z': return 0x5A; + + // VK_LWIN (5B) Left Windows key (Microsoft Natural keyboard) + // VK_RWIN (5C) Right Windows key (Natural keyboard) + // VK_APPS (5D) Applications key (Natural keyboard) + // VK_SLEEP (5F) Computer Sleep key + + // VK_NUMPAD0 (60) Numeric keypad 0 key + // VK_NUMPAD1 (61) Numeric keypad 1 key + // VK_NUMPAD2 (62) Numeric keypad 2 key + // VK_NUMPAD3 (63) Numeric keypad 3 key + // VK_NUMPAD4 (64) Numeric keypad 4 key + // VK_NUMPAD5 (65) Numeric keypad 5 key + // VK_NUMPAD6 (66) Numeric keypad 6 key + // VK_NUMPAD7 (67) Numeric keypad 7 key + // VK_NUMPAD8 (68) Numeric keypad 8 key + // VK_NUMPAD9 (69) Numeric keypad 9 key + // VK_MULTIPLY (6A) Multiply key + // VK_ADD (6B) Add key + // handled by key code above + + // VK_SEPARATOR (6C) Separator key + + // VK_SUBTRACT (6D) Subtract key + // VK_DECIMAL (6E) Decimal key + // VK_DIVIDE (6F) Divide key + // handled by key code above + + // VK_F1 (70) F1 key + case NSF1FunctionKey: return 0x70; + // VK_F2 (71) F2 key + case NSF2FunctionKey: return 0x71; + // VK_F3 (72) F3 key + case NSF3FunctionKey: return 0x72; + // VK_F4 (73) F4 key + case NSF4FunctionKey: return 0x73; + // VK_F5 (74) F5 key + case NSF5FunctionKey: return 0x74; + // VK_F6 (75) F6 key + case NSF6FunctionKey: return 0x75; + // VK_F7 (76) F7 key + case NSF7FunctionKey: return 0x76; + // VK_F8 (77) F8 key + case NSF8FunctionKey: return 0x77; + // VK_F9 (78) F9 key + case NSF9FunctionKey: return 0x78; + // VK_F10 (79) F10 key + case NSF10FunctionKey: return 0x79; + // VK_F11 (7A) F11 key + case NSF11FunctionKey: return 0x7A; + // VK_F12 (7B) F12 key + case NSF12FunctionKey: return 0x7B; + // VK_F13 (7C) F13 key + case NSF13FunctionKey: return 0x7C; + // VK_F14 (7D) F14 key + case NSF14FunctionKey: return 0x7D; + // VK_F15 (7E) F15 key + case NSF15FunctionKey: return 0x7E; + // VK_F16 (7F) F16 key + case NSF16FunctionKey: return 0x7F; + // VK_F17 (80H) F17 key + case NSF17FunctionKey: return 0x80; + // VK_F18 (81H) F18 key + case NSF18FunctionKey: return 0x81; + // VK_F19 (82H) F19 key + case NSF19FunctionKey: return 0x82; + // VK_F20 (83H) F20 key + case NSF20FunctionKey: return 0x83; + // VK_F21 (84H) F21 key + case NSF21FunctionKey: return 0x84; + // VK_F22 (85H) F22 key + case NSF22FunctionKey: return 0x85; + // VK_F23 (86H) F23 key + case NSF23FunctionKey: return 0x86; + // VK_F24 (87H) F24 key + case NSF24FunctionKey: return 0x87; + + // VK_NUMLOCK (90) NUM LOCK key + + // VK_SCROLL (91) SCROLL LOCK key + case NSScrollLockFunctionKey: return 0x91; + + // VK_LSHIFT (A0) Left SHIFT key + // VK_RSHIFT (A1) Right SHIFT key + // VK_LCONTROL (A2) Left CONTROL key + // VK_RCONTROL (A3) Right CONTROL key + // VK_LMENU (A4) Left MENU key + // VK_RMENU (A5) Right MENU key + // VK_BROWSER_BACK (A6) Windows 2000/XP: Browser Back key + // VK_BROWSER_FORWARD (A7) Windows 2000/XP: Browser Forward key + // VK_BROWSER_REFRESH (A8) Windows 2000/XP: Browser Refresh key + // VK_BROWSER_STOP (A9) Windows 2000/XP: Browser Stop key + // VK_BROWSER_SEARCH (AA) Windows 2000/XP: Browser Search key + // VK_BROWSER_FAVORITES (AB) Windows 2000/XP: Browser Favorites key + // VK_BROWSER_HOME (AC) Windows 2000/XP: Browser Start and Home key + // VK_VOLUME_MUTE (AD) Windows 2000/XP: Volume Mute key + // VK_VOLUME_DOWN (AE) Windows 2000/XP: Volume Down key + // VK_VOLUME_UP (AF) Windows 2000/XP: Volume Up key + // VK_MEDIA_NEXT_TRACK (B0) Windows 2000/XP: Next Track key + // VK_MEDIA_PREV_TRACK (B1) Windows 2000/XP: Previous Track key + // VK_MEDIA_STOP (B2) Windows 2000/XP: Stop Media key + // VK_MEDIA_PLAY_PAUSE (B3) Windows 2000/XP: Play/Pause Media key + // VK_LAUNCH_MAIL (B4) Windows 2000/XP: Start Mail key + // VK_LAUNCH_MEDIA_SELECT (B5) Windows 2000/XP: Select Media key + // VK_LAUNCH_APP1 (B6) Windows 2000/XP: Start Application 1 key + // VK_LAUNCH_APP2 (B7) Windows 2000/XP: Start Application 2 key + + // VK_OEM_1 (BA) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the ';:' key + case ';': case ':': return 0xBA; + // VK_OEM_PLUS (BB) Windows 2000/XP: For any country/region, the '+' key + case '=': case '+': return 0xBB; + // VK_OEM_COMMA (BC) Windows 2000/XP: For any country/region, the ',' key + case ',': case '<': return 0xBC; + // VK_OEM_MINUS (BD) Windows 2000/XP: For any country/region, the '-' key + case '-': case '_': return 0xBD; + // VK_OEM_PERIOD (BE) Windows 2000/XP: For any country/region, the '.' key + case '.': case '>': return 0xBE; + // VK_OEM_2 (BF) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '/?' key + case '/': case '?': return 0xBF; + // VK_OEM_3 (C0) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '`~' key + case '`': case '~': return 0xC0; + // VK_OEM_4 (DB) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '[{' key + case '[': case '{': return 0xDB; + // VK_OEM_5 (DC) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '\|' key + case '\\': case '|': return 0xDC; + // VK_OEM_6 (DD) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the ']}' key + case ']': case '}': return 0xDD; + // VK_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 '\'': case '"': return 0xDE; + + // VK_OEM_8 (DF) Used for miscellaneous characters; it can vary by keyboard. + // VK_OEM_102 (E2) Windows 2000/XP: Either the angle bracket key or the backslash key on the RT 102-key keyboard + // VK_PROCESSKEY (E5) Windows 95/98/Me, Windows NT 4.0, Windows 2000/XP: IME PROCESS key + // VK_PACKET (E7) Windows 2000/XP: Used to pass Unicode characters as if they were keystrokes. The VK_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 + // VK_ATTN (F6) Attn key + // VK_CRSEL (F7) CrSel key + // VK_EXSEL (F8) ExSel key + // VK_EREOF (F9) Erase EOF key + // VK_PLAY (FA) Play key + // VK_ZOOM (FB) Zoom key + // VK_NONAME (FC) Reserved for future use + // VK_PA1 (FD) PA1 key + // VK_OEM_CLEAR (FE) Clear key + } + + return 0; +} + +static inline bool isKeyUpEvent(NSEvent *event) +{ + if ([event type] != NSFlagsChanged) + return [event type] == NSKeyUp; + // FIXME: This logic fails if the user presses both Shift keys at once, for example: + // we treat releasing one of them as keyDown. + switch ([event keyCode]) { + case 54: // Right Command + case 55: // Left Command + return ([event modifierFlags] & NSCommandKeyMask) == 0; + + case 57: // Capslock + return ([event modifierFlags] & NSAlphaShiftKeyMask) == 0; + + case 56: // Left Shift + case 60: // Right Shift + return ([event modifierFlags] & NSShiftKeyMask) == 0; + + case 58: // Left Alt + case 61: // Right Alt + return ([event modifierFlags] & NSAlternateKeyMask) == 0; + + case 59: // Left Ctrl + case 62: // Right Ctrl + return ([event modifierFlags] & NSControlKeyMask) == 0; + + case 63: // Function + return ([event modifierFlags] & NSFunctionKeyMask) == 0; + } + return false; +} + +static inline String textFromEvent(NSEvent* event) +{ + if ([event type] == NSFlagsChanged) + return ""; + return [event characters]; +} + + +static inline String unmodifiedTextFromEvent(NSEvent* event) +{ + if ([event type] == NSFlagsChanged) + return ""; + return [event charactersIgnoringModifiers]; +} + +PlatformKeyboardEvent::PlatformKeyboardEvent(NSEvent *event) + : m_type(isKeyUpEvent(event) ? PlatformKeyboardEvent::KeyUp : PlatformKeyboardEvent::KeyDown) + , m_text(textFromEvent(event)) + , m_unmodifiedText(unmodifiedTextFromEvent(event)) + , m_keyIdentifier(keyIdentifierForKeyEvent(event)) + , m_autoRepeat(([event type] != NSFlagsChanged) && [event isARepeat]) + , m_windowsVirtualKeyCode(windowsKeyCodeForKeyEvent(event)) + , m_isKeypad(isKeypadEvent(event)) + , m_shiftKey([event modifierFlags] & NSShiftKeyMask) + , m_ctrlKey([event modifierFlags] & NSControlKeyMask) + , m_altKey([event modifierFlags] & NSAlternateKeyMask) + , m_metaKey([event modifierFlags] & NSCommandKeyMask) + , m_macEvent(event) +{ + // Always use 13 for Enter/Return -- we don't want to use AppKit's different character for Enter. + if (m_windowsVirtualKeyCode == '\r') { + m_text = "\r"; + m_unmodifiedText = "\r"; + } + + // The adjustments below are only needed in backward compatibility mode, but we cannot tell what mode we are in from here. + + // Turn 0x7F into 8, because backspace needs to always be 8. + if (m_text == "\x7F") + m_text = "\x8"; + if (m_unmodifiedText == "\x7F") + m_unmodifiedText = "\x8"; + // Always use 9 for tab -- we don't want to use AppKit's different character for shift-tab. + if (m_windowsVirtualKeyCode == 9) { + m_text = "\x9"; + m_unmodifiedText = "\x9"; + } +} + +void PlatformKeyboardEvent::disambiguateKeyDownEvent(Type type, bool backwardCompatibilityMode) +{ + // 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 (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(); + } + } +} + +bool PlatformKeyboardEvent::currentCapsLockState() +{ + return GetCurrentKeyModifiers() & alphaLock; +} + +} diff --git a/WebCore/platform/mac/Language.mm b/WebCore/platform/mac/Language.mm new file mode 100644 index 0000000..96caaa6 --- /dev/null +++ b/WebCore/platform/mac/Language.mm @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2003, 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. + */ + +#import "config.h" +#import "Language.h" + +#import "BlockExceptions.h" +#import "PlatformString.h" +#import "WebCoreViewFactory.h" + +namespace WebCore { + +String defaultLanguage() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] defaultLanguageCode]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +} diff --git a/WebCore/platform/mac/LocalCurrentGraphicsContext.h b/WebCore/platform/mac/LocalCurrentGraphicsContext.h new file mode 100644 index 0000000..856cf52 --- /dev/null +++ b/WebCore/platform/mac/LocalCurrentGraphicsContext.h @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2006 Apple Computer, Inc. + * + * 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. + */ + +#include <wtf/Noncopyable.h> + +class NSGraphicsContext; + +namespace WebCore { + +class GraphicsContext; + +// This class automatically saves and restores the current NSGraphicsContext for +// functions which call out into AppKit and rely on the currentContext being set +class LocalCurrentGraphicsContext : Noncopyable { +public: + LocalCurrentGraphicsContext(GraphicsContext* graphicsContext); + ~LocalCurrentGraphicsContext(); + +private: + GraphicsContext* m_savedGraphicsContext; + NSGraphicsContext* m_savedNSGraphicsContext; +}; + +} diff --git a/WebCore/platform/mac/LocalCurrentGraphicsContext.mm b/WebCore/platform/mac/LocalCurrentGraphicsContext.mm new file mode 100644 index 0000000..756d353 --- /dev/null +++ b/WebCore/platform/mac/LocalCurrentGraphicsContext.mm @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2006 Apple Computer, Inc. + * + * 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. + */ + +#include "config.h" +#include "LocalCurrentGraphicsContext.h" + +#include "GraphicsContext.h" +#include <AppKit/NSGraphicsContext.h> + +namespace WebCore { + +LocalCurrentGraphicsContext::LocalCurrentGraphicsContext(GraphicsContext* graphicsContext) +{ + m_savedGraphicsContext = graphicsContext; + graphicsContext->save(); + + if (graphicsContext->platformContext() == [[NSGraphicsContext currentContext] graphicsPort]) { + m_savedNSGraphicsContext = 0; + return; + } + + m_savedNSGraphicsContext = [[NSGraphicsContext currentContext] retain]; + NSGraphicsContext* newContext = [NSGraphicsContext graphicsContextWithGraphicsPort:graphicsContext->platformContext() flipped:YES]; + [NSGraphicsContext setCurrentContext:newContext]; +} + +LocalCurrentGraphicsContext::~LocalCurrentGraphicsContext() +{ + m_savedGraphicsContext->restore(); + + if (m_savedNSGraphicsContext) { + [NSGraphicsContext setCurrentContext:m_savedNSGraphicsContext]; + [m_savedNSGraphicsContext release]; + } +} + +} diff --git a/WebCore/platform/mac/LocalizedStringsMac.mm b/WebCore/platform/mac/LocalizedStringsMac.mm new file mode 100644 index 0000000..d4af7cd --- /dev/null +++ b/WebCore/platform/mac/LocalizedStringsMac.mm @@ -0,0 +1,516 @@ +/* + * Copyright (C) 2003, 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. + */ + +#import "config.h" +#import "LocalizedStrings.h" + +#import "BlockExceptions.h" +#import "IntSize.h" +#import "PlatformString.h" +#import "WebCoreViewFactory.h" + +namespace WebCore { + +String inputElementAltText() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] inputElementAltText]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String resetButtonDefaultLabel() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] resetButtonDefaultLabel]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String searchableIndexIntroduction() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] searchableIndexIntroduction]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String submitButtonDefaultLabel() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] submitButtonDefaultLabel]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String fileButtonChooseFileLabel() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] fileButtonChooseFileLabel]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String fileButtonNoFileSelectedLabel() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] fileButtonNoFileSelectedLabel]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String copyImageUnknownFileLabel() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] copyImageUnknownFileLabel]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagOpenLinkInNewWindow() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagOpenLinkInNewWindow]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagDownloadLinkToDisk() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagDownloadLinkToDisk]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagCopyLinkToClipboard() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagCopyLinkToClipboard]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagOpenImageInNewWindow() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagOpenImageInNewWindow]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagDownloadImageToDisk() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagDownloadImageToDisk]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagCopyImageToClipboard() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagCopyImageToClipboard]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagOpenFrameInNewWindow() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagOpenFrameInNewWindow]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagCopy() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagCopy]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagGoBack() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagGoBack]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagGoForward() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagGoForward]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagStop() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagStop]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagReload() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagReload]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagCut() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagCut]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagPaste() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagPaste]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagNoGuessesFound() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagNoGuessesFound]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagIgnoreSpelling() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagIgnoreSpelling]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagLearnSpelling() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagLearnSpelling]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagSearchInSpotlight() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagSearchInSpotlight]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagSearchWeb() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagSearchWeb]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagLookUpInDictionary() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagLookUpInDictionary]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagOpenLink() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagOpenLink]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagIgnoreGrammar() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagIgnoreGrammar]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagSpellingMenu() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagSpellingMenu]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagShowSpellingPanel(bool show) +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagShowSpellingPanel:show]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagCheckSpelling() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagCheckSpelling]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagCheckSpellingWhileTyping() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagCheckSpellingWhileTyping]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagCheckGrammarWithSpelling() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagCheckGrammarWithSpelling]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagFontMenu() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagFontMenu]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagShowFonts() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagShowFonts]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagBold() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagBold]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagItalic() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagItalic]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagUnderline() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagUnderline]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagOutline() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagOutline]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagStyles() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagStyles]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagShowColors() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagShowColors]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagSpeechMenu() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagSpeechMenu]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagStartSpeaking() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagStartSpeaking]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagStopSpeaking() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagStopSpeaking]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagWritingDirectionMenu() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagWritingDirectionMenu]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagDefaultDirection() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagDefaultDirection]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagLeftToRight() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagLeftToRight]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagRightToLeft() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagRightToLeft]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String contextMenuItemTagInspectElement() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] contextMenuItemTagInspectElement]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String searchMenuNoRecentSearchesText() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] searchMenuNoRecentSearchesText]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String searchMenuRecentSearchesText () +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] searchMenuRecentSearchesText]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String searchMenuClearRecentSearchesText() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] searchMenuClearRecentSearchesText]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String AXWebAreaText() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] AXWebAreaText]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String AXLinkText() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] AXLinkText]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String AXListMarkerText() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] AXListMarkerText]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String AXImageMapText() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] AXImageMapText]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String AXHeadingText() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] AXHeadingText]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String unknownFileSizeText() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] unknownFileSizeText]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +String imageTitle(const String& filename, const IntSize& size) +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] imageTitleForFilename:filename size:size]; + END_BLOCK_OBJC_EXCEPTIONS; + return String(); +} + +} diff --git a/WebCore/platform/mac/LoggingMac.mm b/WebCore/platform/mac/LoggingMac.mm new file mode 100644 index 0000000..bb7a2be --- /dev/null +++ b/WebCore/platform/mac/LoggingMac.mm @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2003, 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 "Logging.h" + +namespace WebCore { + +static inline void initializeWithUserDefault(WTFLogChannel& channel) +{ + NSString *logLevelString = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithUTF8String:channel.defaultName]]; + if (logLevelString) { + unsigned logLevel; + if (![[NSScanner scannerWithString:logLevelString] scanHexInt:&logLevel]) + NSLog(@"unable to parse hex value for %s (%@), logging is off", channel.defaultName, logLevelString); + if ((logLevel & channel.mask) == channel.mask) + channel.state = WTFLogChannelOn; + else + channel.state = WTFLogChannelOff; + } +} + +void InitializeLoggingChannelsIfNecessary() +{ + static bool haveInitializedLoggingChannels = false; + if (haveInitializedLoggingChannels) + return; + haveInitializedLoggingChannels = true; + + initializeWithUserDefault(LogNotYetImplemented); + initializeWithUserDefault(LogFrames); + initializeWithUserDefault(LogLoading); + initializeWithUserDefault(LogPopupBlocking); + initializeWithUserDefault(LogEvents); + initializeWithUserDefault(LogEditing); + initializeWithUserDefault(LogTextConversion); + initializeWithUserDefault(LogIconDatabase); + initializeWithUserDefault(LogSQLDatabase); + initializeWithUserDefault(LogSpellingAndGrammar); + initializeWithUserDefault(LogBackForward); + initializeWithUserDefault(LogHistory); + initializeWithUserDefault(LogPageCache); + initializeWithUserDefault(LogPlatformLeaks); + initializeWithUserDefault(LogNetwork); + initializeWithUserDefault(LogFTP); + initializeWithUserDefault(LogThreading); + initializeWithUserDefault(LogStorageAPI); + initializeWithUserDefault(LogMedia); + initializeWithUserDefault(LogPlugin); +} + +} diff --git a/WebCore/platform/mac/MIMETypeRegistryMac.mm b/WebCore/platform/mac/MIMETypeRegistryMac.mm new file mode 100644 index 0000000..36474cc --- /dev/null +++ b/WebCore/platform/mac/MIMETypeRegistryMac.mm @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2006 Apple Computer, Inc. All rights reserved. + * Copyright (C) 2007 Trolltech ASA + * + * 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 "MIMETypeRegistry.h" + +#include "WebCoreSystemInterface.h" + +namespace WebCore +{ +String getMIMETypeForUTI(const String & uti) +{ + CFStringRef utiref = uti.createCFString(); + CFStringRef mime = UTTypeCopyPreferredTagWithClass(utiref, kUTTagClassMIMEType); + String mimeType = mime; + if (mime) + CFRelease(mime); + CFRelease(utiref); + return mimeType; +} + +String MIMETypeRegistry::getMIMETypeForExtension(const String &ext) +{ + return wkGetMIMETypeForExtension(ext); +} + +Vector<String> MIMETypeRegistry::getExtensionsForMIMEType(const String& type) +{ + NSArray *stringsArray = wkGetExtensionsForMIMEType(type); + Vector<String> stringsVector = Vector<String>(); + unsigned count = [stringsArray count]; + if (count > 0) { + NSEnumerator* enumerator = [stringsArray objectEnumerator]; + NSString* string; + while ((string = [enumerator nextObject]) != nil) + stringsVector.append(string); + } + return stringsVector; +} + +String MIMETypeRegistry::getPreferredExtensionForMIMEType(const String& type) +{ + return wkGetPreferredExtensionForMIMEType(type); +} + +} diff --git a/WebCore/platform/mac/MainThreadMac.mm b/WebCore/platform/mac/MainThreadMac.mm new file mode 100644 index 0000000..47329ef --- /dev/null +++ b/WebCore/platform/mac/MainThreadMac.mm @@ -0,0 +1,66 @@ +/* + * Copyright (C) 2007, 2008 Apple 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. + * 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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 "MainThread.h" + +@interface WebCoreFunctionWrapper : NSObject { + WebCore::MainThreadFunction* m_function; + void* m_context; +} +- (id)initWithFunction:(WebCore::MainThreadFunction*)function context:(void*)context; +- (void)invoke; +@end + +@implementation WebCoreFunctionWrapper + +- (id)initWithFunction:(WebCore::MainThreadFunction*)function context:(void*)context; +{ + [super init]; + m_function = function; + m_context = context; + return self; +} + +- (void)invoke +{ + m_function(m_context); +} + +@end // implementation WebCoreFunctionWrapper + +namespace WebCore { + +void callOnMainThread(MainThreadFunction* function, void* context) +{ + WebCoreFunctionWrapper *wrapper = [[WebCoreFunctionWrapper alloc] initWithFunction:function context:context]; + [wrapper performSelectorOnMainThread:@selector(invoke) withObject:nil waitUntilDone:NO]; + [wrapper release]; +} + +} // namespace WebCore diff --git a/WebCore/platform/mac/PasteboardHelper.h b/WebCore/platform/mac/PasteboardHelper.h new file mode 100644 index 0000000..4ae964d --- /dev/null +++ b/WebCore/platform/mac/PasteboardHelper.h @@ -0,0 +1,60 @@ +/* + * Copyright (C) 2007 Apple 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. + */ + +#ifndef PasteboardHelper_h +#define PasteboardHelper_h + +/* FIXME: This is a helper class used to provide access to functionality inside + * WebKit. The required functionality should eventually be migrated to WebCore + * so that this class can be removed. + */ +#if PLATFORM(MAC) + +#import <wtf/Forward.h> + +#ifdef __OBJC__ +@class DOMDocumentFragment; +#else +class DOMDocumentFragment; +#endif + +namespace WebCore { + + class String; + class Document; + + class PasteboardHelper { + public: + virtual ~PasteboardHelper() {} + virtual String urlFromPasteboard(const NSPasteboard*, String* title) const = 0; + virtual String plainTextFromPasteboard(const NSPasteboard*) const = 0; + virtual DOMDocumentFragment* fragmentFromPasteboard(const NSPasteboard*) const = 0; + virtual NSArray* insertablePasteboardTypes() const = 0; + }; + +} +#endif // PLATFORM(MAC) + +#endif // !PasteboardHelper_h diff --git a/WebCore/platform/mac/PasteboardMac.mm b/WebCore/platform/mac/PasteboardMac.mm new file mode 100644 index 0000000..1433dbd --- /dev/null +++ b/WebCore/platform/mac/PasteboardMac.mm @@ -0,0 +1,370 @@ +/* + * 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. + */ + +#import "config.h" +#import "Pasteboard.h" + +#import "CachedResource.h" +#import "CharacterNames.h" +#import "DOMRangeInternal.h" +#import "Document.h" +#import "DocumentFragment.h" +#import "Editor.h" +#import "EditorClient.h" +#import "HitTestResult.h" +#import "Image.h" +#import "KURL.h" +#import "LoaderNSURLExtras.h" +#import "MIMETypeRegistry.h" +#import "RenderImage.h" +#import "WebCoreNSStringExtras.h" +#import "markup.h" + +#import <wtf/RetainPtr.h> + +@interface NSAttributedString (AppKitSecretsIKnowAbout) +- (id)_initWithDOMRange:(DOMRange *)domRange; +@end + +namespace WebCore { + +// FIXME: It's not great to have these both here and in WebKit. +NSString *WebArchivePboardType = @"Apple Web Archive pasteboard type"; +NSString *WebSmartPastePboardType = @"NeXT smart paste pasteboard type"; +NSString *WebURLNamePboardType = @"public.url-name"; +NSString *WebURLPboardType = @"public.url"; +NSString *WebURLsWithTitlesPboardType = @"WebURLsWithTitlesPboardType"; + +#ifndef BUILDING_ON_TIGER +static NSArray* selectionPasteboardTypes(bool canSmartCopyOrDelete, bool selectionContainsAttachments) +{ + if (selectionContainsAttachments) { + if (canSmartCopyOrDelete) + return [NSArray arrayWithObjects:WebSmartPastePboardType, WebArchivePboardType, NSRTFDPboardType, NSRTFPboardType, NSStringPboardType, nil]; + else + return [NSArray arrayWithObjects:WebArchivePboardType, NSRTFDPboardType, NSRTFPboardType, NSStringPboardType, nil]; + } else { // Don't write RTFD to the pasteboard when the copied attributed string has no attachments. + if (canSmartCopyOrDelete) + return [NSArray arrayWithObjects:WebSmartPastePboardType, WebArchivePboardType, NSRTFPboardType, NSStringPboardType, nil]; + else + return [NSArray arrayWithObjects:WebArchivePboardType, NSRTFPboardType, NSStringPboardType, nil]; + } +} +#endif + +static NSArray* writableTypesForURL() +{ + static RetainPtr<NSArray> types = nil; + if (!types) { + types = [[NSArray alloc] initWithObjects: + WebURLsWithTitlesPboardType, + NSURLPboardType, + WebURLPboardType, + WebURLNamePboardType, + NSStringPboardType, + nil]; + } + return types.get(); +} + +static NSArray* writableTypesForImage() +{ + static RetainPtr<NSMutableArray> types = nil; + if (!types) { + types = [[NSMutableArray alloc] initWithObjects:NSTIFFPboardType, nil]; + [types.get() addObjectsFromArray:writableTypesForURL()]; + [types.get() addObject:NSRTFDPboardType]; + } + return types.get(); +} + +Pasteboard* Pasteboard::generalPasteboard() +{ + static Pasteboard* pasteboard = new Pasteboard([NSPasteboard generalPasteboard]); + return pasteboard; +} + +Pasteboard::Pasteboard(NSPasteboard* pboard) + : m_pasteboard(pboard) +{ +} + +void Pasteboard::clear() +{ + [m_pasteboard.get() declareTypes:[NSArray array] owner:nil]; +} + +static NSAttributedString *stripAttachmentCharacters(NSAttributedString *string) +{ + const unichar attachmentCharacter = NSAttachmentCharacter; + static RetainPtr<NSString> attachmentCharacterString = [NSString stringWithCharacters:&attachmentCharacter length:1]; + NSMutableAttributedString *result = [[string mutableCopy] autorelease]; + NSRange attachmentRange = [[result string] rangeOfString:attachmentCharacterString.get()]; + while (attachmentRange.location != NSNotFound) { + [result replaceCharactersInRange:attachmentRange withString:@""]; + attachmentRange = [[result string] rangeOfString:attachmentCharacterString.get()]; + } + return result; +} + +void Pasteboard::writeSelection(NSPasteboard* pasteboard, Range* selectedRange, bool canSmartCopyOrDelete, Frame* frame) +{ + if (WebArchivePboardType == nil) + Pasteboard::generalPasteboard(); //Initialises pasteboard types + ASSERT(selectedRange); + + NSAttributedString *attributedString = [[[NSAttributedString alloc] _initWithDOMRange:[DOMRange _wrapRange:selectedRange]] autorelease]; +#ifdef BUILDING_ON_TIGER + // 4930197: Mail overrides [WebHTMLView pasteboardTypesForSelection] in order to add another type to the pasteboard + // after WebKit does. On Tiger we must call this function so that Mail code will be executed, meaning that + // we can't call WebCore::Pasteboard's method for setting types. + + NSArray *types = frame->editor()->client()->pasteboardTypesForSelection(frame); + // Don't write RTFD to the pasteboard when the copied attributed string has no attachments. + NSMutableArray *mutableTypes = nil; + if (![attributedString containsAttachments]) { + mutableTypes = [[types mutableCopy] autorelease]; + [mutableTypes removeObject:NSRTFDPboardType]; + types = mutableTypes; + } + [pasteboard declareTypes:types owner:nil]; +#else + NSArray *types = selectionPasteboardTypes(canSmartCopyOrDelete, [attributedString containsAttachments]); + [pasteboard declareTypes:types owner:nil]; + frame->editor()->client()->didSetSelectionTypesForPasteboard(); +#endif + + // Put HTML on the pasteboard. + if ([types containsObject:WebArchivePboardType]) { + [pasteboard setData:frame->editor()->client()->dataForArchivedSelection(frame) forType:WebArchivePboardType]; + } + + // Put the attributed string on the pasteboard (RTF/RTFD format). + if ([types containsObject:NSRTFDPboardType]) { + NSData *RTFDData = [attributedString RTFDFromRange:NSMakeRange(0, [attributedString length]) documentAttributes:nil]; + [pasteboard setData:RTFDData forType:NSRTFDPboardType]; + } + if ([types containsObject:NSRTFPboardType]) { + if ([attributedString containsAttachments]) + attributedString = stripAttachmentCharacters(attributedString); + NSData *RTFData = [attributedString RTFFromRange:NSMakeRange(0, [attributedString length]) documentAttributes:nil]; + [pasteboard setData:RTFData forType:NSRTFPboardType]; + } + + // Put plain string on the pasteboard. + if ([types containsObject:NSStringPboardType]) { + // Map to a plain old space because this is better for source code, other browsers do it, + // and because HTML forces you to do this any time you want two spaces in a row. + String text = selectedRange->text(); + text.replace('\\', frame->backslashAsCurrencySymbol()); + NSMutableString *s = [[[(NSString*)text copy] autorelease] mutableCopy]; + + NSString *NonBreakingSpaceString = [NSString stringWithCharacters:&noBreakSpace length:1]; + [s replaceOccurrencesOfString:NonBreakingSpaceString withString:@" " options:0 range:NSMakeRange(0, [s length])]; + [pasteboard setString:s forType:NSStringPboardType]; + [s release]; + } + + if ([types containsObject:WebSmartPastePboardType]) { + [pasteboard setData:nil forType:WebSmartPastePboardType]; + } +} + +void Pasteboard::writeSelection(Range* selectedRange, bool canSmartCopyOrDelete, Frame* frame) +{ + Pasteboard::writeSelection(m_pasteboard.get(), selectedRange, canSmartCopyOrDelete, frame); +} + +void Pasteboard::writeURL(NSPasteboard* pasteboard, NSArray* types, const KURL& url, const String& titleStr, Frame* frame) +{ + if (WebArchivePboardType == nil) + Pasteboard::generalPasteboard(); //Initialises pasteboard types + + if (types == nil) { + types = writableTypesForURL(); + [pasteboard declareTypes:types owner:nil]; + } + + ASSERT(!url.isEmpty()); + + NSURL *cocoaURL = url; + NSString *userVisibleString = frame->editor()->client()->userVisibleString(cocoaURL); + + NSString *title = (NSString*)titleStr; + if ([title length] == 0) { + title = [[cocoaURL path] lastPathComponent]; + if ([title length] == 0) + title = userVisibleString; + } + + if ([types containsObject:WebURLsWithTitlesPboardType]) + [pasteboard setPropertyList:[NSArray arrayWithObjects:[NSArray arrayWithObject:userVisibleString], + [NSArray arrayWithObject:(NSString*)titleStr.stripWhiteSpace()], + nil] + forType:WebURLsWithTitlesPboardType]; + if ([types containsObject:NSURLPboardType]) + [cocoaURL writeToPasteboard:pasteboard]; + if ([types containsObject:WebURLPboardType]) + [pasteboard setString:userVisibleString forType:WebURLPboardType]; + if ([types containsObject:WebURLNamePboardType]) + [pasteboard setString:title forType:WebURLNamePboardType]; + if ([types containsObject:NSStringPboardType]) + [pasteboard setString:userVisibleString forType:NSStringPboardType]; +} + +void Pasteboard::writeURL(const KURL& url, const String& titleStr, Frame* frame) +{ + Pasteboard::writeURL(m_pasteboard.get(), nil, url, titleStr, frame); +} + +static NSFileWrapper* fileWrapperForImage(CachedResource* resource, NSURL *url) +{ + SharedBuffer* coreData = resource->data(); + NSData *data = [[[NSData alloc] initWithBytes:coreData->platformData() + length:coreData->platformDataSize()] autorelease]; + NSFileWrapper *wrapper = [[[NSFileWrapper alloc] initRegularFileWithContents:data] autorelease]; + String coreMIMEType = resource->response().mimeType(); + NSString *MIMEType = nil; + if (!coreMIMEType.isNull()) + MIMEType = coreMIMEType; + [wrapper setPreferredFilename:suggestedFilenameWithMIMEType(url, MIMEType)]; + return wrapper; +} + +void Pasteboard::writeFileWrapperAsRTFDAttachment(NSFileWrapper* wrapper) +{ + NSTextAttachment *attachment = [[NSTextAttachment alloc] initWithFileWrapper:wrapper]; + + NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attachment]; + [attachment release]; + + NSData *RTFDData = [string RTFDFromRange:NSMakeRange(0, [string length]) documentAttributes:nil]; + [m_pasteboard.get() setData:RTFDData forType:NSRTFDPboardType]; +} + +void Pasteboard::writeImage(Node* node, const KURL& url, const String& title) +{ + ASSERT(node); + Frame* frame = node->document()->frame(); + + NSURL *cocoaURL = url; + ASSERT(cocoaURL); + + NSArray* types = writableTypesForImage(); + [m_pasteboard.get() declareTypes:types owner:nil]; + writeURL(m_pasteboard.get(), types, cocoaURL, nsStringNilIfEmpty(title), frame); + + ASSERT(node->renderer() && node->renderer()->isImage()); + RenderImage* renderer = static_cast<RenderImage*>(node->renderer()); + CachedImage* cachedImage = static_cast<CachedImage*>(renderer->cachedImage()); + ASSERT(cachedImage); + Image* image = cachedImage->image(); + ASSERT(image); + + [m_pasteboard.get() setData:[image->getNSImage() TIFFRepresentation] forType:NSTIFFPboardType]; + + String MIMEType = cachedImage->response().mimeType(); + ASSERT(MIMETypeRegistry::isSupportedImageResourceMIMEType(MIMEType)); + + writeFileWrapperAsRTFDAttachment(fileWrapperForImage(cachedImage, cocoaURL)); +} + +bool Pasteboard::canSmartReplace() +{ + return [[m_pasteboard.get() types] containsObject:WebSmartPastePboardType]; +} + +String Pasteboard::plainText(Frame* frame) +{ + NSArray *types = [m_pasteboard.get() types]; + + if ([types containsObject:NSStringPboardType]) + return [m_pasteboard.get() stringForType:NSStringPboardType]; + + NSAttributedString *attributedString = nil; + NSString *string; + + if ([types containsObject:NSRTFDPboardType]) + attributedString = [[NSAttributedString alloc] initWithRTFD:[m_pasteboard.get() dataForType:NSRTFDPboardType] documentAttributes:NULL]; + if (attributedString == nil && [types containsObject:NSRTFPboardType]) + attributedString = [[NSAttributedString alloc] initWithRTF:[m_pasteboard.get() dataForType:NSRTFPboardType] documentAttributes:NULL]; + if (attributedString != nil) { + string = [[attributedString string] copy]; + [attributedString release]; + return [string autorelease]; + } + + if ([types containsObject:NSFilenamesPboardType]) { + string = [[m_pasteboard.get() propertyListForType:NSFilenamesPboardType] componentsJoinedByString:@"\n"]; + if (string != nil) + return string; + } + + + if (NSURL *url = [NSURL URLFromPasteboard:m_pasteboard.get()]) { + // FIXME: using the editorClient to call into webkit, for now, since + // calling _web_userVisibleString from WebCore involves migrating a sizable web of + // helper code that should either be done in a separate patch or figured out in another way. + string = frame->editor()->client()->userVisibleString(url); + if ([string length] > 0) + return string; + } + + + return String(); +} + +PassRefPtr<DocumentFragment> Pasteboard::documentFragment(Frame* frame, PassRefPtr<Range> context, bool allowPlainText, bool& chosePlainText) +{ + NSArray *types = [m_pasteboard.get() types]; + chosePlainText = false; + + if ([types containsObject:NSHTMLPboardType]) { + NSString *HTMLString = [m_pasteboard.get() stringForType:NSHTMLPboardType]; + // This is a hack to make Microsoft's HTML pasteboard data work. See 3778785. + if ([HTMLString hasPrefix:@"Version:"]) { + NSRange range = [HTMLString rangeOfString:@"<html" options:NSCaseInsensitiveSearch]; + if (range.location != NSNotFound) { + HTMLString = [HTMLString substringFromIndex:range.location]; + } + } + if ([HTMLString length] != 0) { + RefPtr<DocumentFragment> fragment = createFragmentFromMarkup(frame->document(), HTMLString, ""); + if (fragment) + return fragment.release(); + } + } + + if (allowPlainText && [types containsObject:NSStringPboardType]) { + chosePlainText = true; + RefPtr<DocumentFragment> fragment = createFragmentFromText(context.get(), [m_pasteboard.get() stringForType:NSStringPboardType]); + if (fragment) + return fragment.release(); + } + + return 0; +} + +} diff --git a/WebCore/platform/mac/PlatformMouseEventMac.mm b/WebCore/platform/mac/PlatformMouseEventMac.mm new file mode 100644 index 0000000..af7415d --- /dev/null +++ b/WebCore/platform/mac/PlatformMouseEventMac.mm @@ -0,0 +1,177 @@ +/* + * Copyright (C) 2004, 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. + */ + +#import "config.h" +#import "PlatformMouseEvent.h" + +#import "PlatformScreen.h" + +namespace WebCore { + +static MouseButton mouseButtonForEvent(NSEvent *event) +{ + switch ([event type]) { + case NSLeftMouseDown: + case NSLeftMouseUp: + case NSLeftMouseDragged: + return LeftButton; + case NSRightMouseDown: + case NSRightMouseUp: + case NSRightMouseDragged: + return RightButton; + case NSOtherMouseDown: + case NSOtherMouseUp: + case NSOtherMouseDragged: + return MiddleButton; + default: + return NoButton; + } +} + +static int clickCountForEvent(NSEvent *event) +{ + switch ([event type]) { + case NSLeftMouseDown: + case NSLeftMouseUp: + case NSLeftMouseDragged: + case NSRightMouseDown: + case NSRightMouseUp: + case NSRightMouseDragged: + case NSOtherMouseDown: + case NSOtherMouseUp: + case NSOtherMouseDragged: + return [event clickCount]; + default: + return 0; + } +} + +IntPoint globalPoint(const NSPoint& windowPoint, NSWindow* window) +{ + return IntPoint(flipScreenPoint([window convertBaseToScreen:windowPoint], screenForWindow(window))); +} + +IntPoint pointForEvent(NSEvent *event) +{ + switch ([event type]) { + case NSLeftMouseDown: + case NSLeftMouseUp: + case NSLeftMouseDragged: + case NSRightMouseDown: + case NSRightMouseUp: + case NSRightMouseDragged: + case NSOtherMouseDown: + case NSOtherMouseUp: + case NSOtherMouseDragged: + case NSMouseMoved: + case NSScrollWheel: + // Note: This has its origin at the bottom left of the window. + // The Y coordinate gets flipped by ScrollView::viewportToContents. + // We should probably change both this and that to not use "bottom left origin" coordinates at all. + return IntPoint([event locationInWindow]); + default: + return IntPoint(); + } +} + +IntPoint globalPointForEvent(NSEvent *event) +{ + switch ([event type]) { + case NSLeftMouseDown: + case NSLeftMouseUp: + case NSLeftMouseDragged: + case NSRightMouseDown: + case NSRightMouseUp: + case NSRightMouseDragged: + case NSOtherMouseDown: + case NSOtherMouseUp: + case NSOtherMouseDragged: + case NSMouseMoved: + case NSScrollWheel: + return globalPoint([event locationInWindow], [event window]); + default: + return IntPoint(); + } +} + +int eventNumberForEvent(NSEvent *event) +{ + switch ([event type]) { + case NSLeftMouseDown: + case NSLeftMouseUp: + case NSLeftMouseDragged: + case NSRightMouseDown: + case NSRightMouseUp: + case NSRightMouseDragged: + case NSOtherMouseDown: + case NSOtherMouseUp: + case NSOtherMouseDragged: + case NSMouseMoved: + return [event eventNumber]; + default: + return 0; + } +} + +static MouseEventType mouseEventForNSEvent(NSEvent* event) +{ + switch ([event type]) { + case NSScrollWheel: + return MouseEventScroll; + case NSLeftMouseDragged: + case NSRightMouseDragged: + case NSOtherMouseDragged: + case NSMouseMoved: + return MouseEventMoved; + case NSLeftMouseDown: + case NSRightMouseDown: + case NSOtherMouseDown: + return MouseEventPressed; + case NSLeftMouseUp: + case NSRightMouseUp: + case NSOtherMouseUp: + return MouseEventReleased; + default: + return MouseEventMoved; + } +} + +PlatformMouseEvent::PlatformMouseEvent(NSEvent* event) + : m_position(pointForEvent(event)) + , m_globalPosition(globalPointForEvent(event)) + , m_button(mouseButtonForEvent(event)) + , m_eventType(mouseEventForNSEvent(event)) + , m_clickCount(clickCountForEvent(event)) + , m_shiftKey([event modifierFlags] & NSShiftKeyMask) + , m_ctrlKey([event modifierFlags] & NSControlKeyMask) + , m_altKey([event modifierFlags] & NSAlternateKeyMask) + , m_metaKey([event modifierFlags] & NSCommandKeyMask) + , m_timestamp([event timestamp]) + , m_modifierFlags([event modifierFlags]) + , m_eventNumber([event eventNumber]) +{ +} + +} diff --git a/WebCore/platform/mac/PlatformScreenMac.mm b/WebCore/platform/mac/PlatformScreenMac.mm new file mode 100644 index 0000000..e98ff25 --- /dev/null +++ b/WebCore/platform/mac/PlatformScreenMac.mm @@ -0,0 +1,108 @@ +/* + * 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. + */ + +#import "config.h" +#import "PlatformScreen.h" + +#import "FloatRect.h" +#import "Frame.h" +#import "FrameView.h" +#import "Page.h" + +namespace WebCore { + +int screenDepth(Widget*) +{ + return NSBitsPerPixelFromDepth([[NSScreen deepestScreen] depth]); +} + +int screenDepthPerComponent(Widget*) +{ + return NSBitsPerSampleFromDepth([[NSScreen deepestScreen] depth]); +} + +bool screenIsMonochrome(Widget*) +{ + NSString *colorSpace = NSColorSpaceFromDepth([[NSScreen deepestScreen] depth]); + return colorSpace == NSCalibratedWhiteColorSpace + || colorSpace == NSCalibratedBlackColorSpace + || colorSpace == NSDeviceWhiteColorSpace + || colorSpace == NSDeviceBlackColorSpace; +} + +// These functions scale between screen and page coordinates because JavaScript/DOM operations +// assume that the screen and the page share the same coordinate system. + +FloatRect screenRect(Widget* widget) +{ + NSWindow *window = widget ? [widget->getView() window] : nil; + return toUserSpace([screenForWindow(window) frame], window); +} + +FloatRect screenAvailableRect(Widget* widget) +{ + NSWindow *window = widget ? [widget->getView() window] : nil; + return toUserSpace([screenForWindow(window) visibleFrame], window); +} + +NSScreen *screenForWindow(NSWindow *window) +{ + NSScreen *screen = [window screen]; // nil if the window is off-screen + if (screen) + return screen; + + NSArray *screens = [NSScreen screens]; + if ([screens count] > 0) + return [screens objectAtIndex:0]; // screen containing the menubar + + return nil; +} + +FloatRect toUserSpace(const NSRect& rect, NSWindow *destination) +{ + FloatRect userRect = rect; + userRect.setY(NSMaxY([screenForWindow(destination) frame]) - (userRect.y() + userRect.height())); // flip + if (destination) + userRect.scale(1 / [destination userSpaceScaleFactor]); // scale down + return userRect; +} + +NSRect toDeviceSpace(const FloatRect& rect, NSWindow *source) +{ + FloatRect deviceRect = rect; + if (source) + deviceRect.scale([source userSpaceScaleFactor]); // scale up + deviceRect.setY(NSMaxY([screenForWindow(source) frame]) - (deviceRect.y() + deviceRect.height())); // flip + return deviceRect; +} + +NSPoint flipScreenPoint(const NSPoint& screenPoint, NSScreen *screen) +{ + NSPoint flippedPoint = screenPoint; + flippedPoint.y = NSMaxY([screen frame]) - flippedPoint.y; + return flippedPoint; +} + +} // namespace WebCore diff --git a/WebCore/platform/mac/PlatformScrollBar.h b/WebCore/platform/mac/PlatformScrollBar.h new file mode 100644 index 0000000..36e9ade --- /dev/null +++ b/WebCore/platform/mac/PlatformScrollBar.h @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2004, 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. + */ + +#ifndef PlatformScrollBar_h +#define PlatformScrollBar_h + +#include "Widget.h" +#include "ScrollBar.h" + +#ifdef __OBJC__ +@class NSScroller; +#else +class NSScroller; +typedef int NSScrollerPart; +#endif + +namespace WebCore { + +class PlatformScrollbar : public Widget, public Scrollbar { +public: + PlatformScrollbar(ScrollbarClient*, ScrollbarOrientation, ScrollbarControlSize); + virtual ~PlatformScrollbar(); + + virtual bool isWidget() const { return true; } + + virtual int width() const; + virtual int height() const; + virtual void setRect(const IntRect&); + virtual void setEnabled(bool); + virtual void paint(GraphicsContext*, const IntRect& damageRect); + + bool scrollbarHit(NSScrollerPart); + + static int horizontalScrollbarHeight() { return 15; } + static int verticalScrollbarWidth() { return 15; } + +protected: + virtual void updateThumbPosition(); + virtual void updateThumbProportion(); +}; + +} + +#endif // PlatformScrollBar_h + diff --git a/WebCore/platform/mac/PlatformScrollBarMac.mm b/WebCore/platform/mac/PlatformScrollBarMac.mm new file mode 100644 index 0000000..b07e055 --- /dev/null +++ b/WebCore/platform/mac/PlatformScrollBarMac.mm @@ -0,0 +1,208 @@ +/* + * Copyright (C) 2004, 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. + */ + +#import "config.h" +#import "PlatformScrollBar.h" + +#import "BlockExceptions.h" + +using namespace WebCore; + +@interface WebCoreScrollBar : NSScroller +{ + PlatformScrollbar* scrollbar; +} + +- (id)initWithPlatformScrollbar:(PlatformScrollbar*)s; +- (void)detachPlatformScrollbar; + +@end + +@implementation WebCoreScrollBar + +static NSControlSize NSControlSizeForScrollBarControlSize(ScrollbarControlSize size) +{ + if (size == SmallScrollbar) + return NSSmallControlSize; + if (size == MiniScrollbar) + return NSMiniControlSize; + return NSRegularControlSize; +} + +- (id)initWithPlatformScrollbar:(PlatformScrollbar*)s +{ + // Cocoa scrollbars just set their orientation by examining their own + // dimensions, so we have to do this unsavory hack. + NSRect orientation; + NSControlSize controlSize = NSControlSizeForScrollBarControlSize(s->controlSize()); + orientation.origin.x = orientation.origin.y = 0; + if (s->orientation() == VerticalScrollbar) { + orientation.size.width = [NSScroller scrollerWidthForControlSize:controlSize]; + orientation.size.height = 100; + } else { + orientation.size.width = 100; + orientation.size.height = [NSScroller scrollerWidthForControlSize:controlSize]; + } + self = [self initWithFrame:orientation]; + + scrollbar = s; + + [self setEnabled:YES]; + [self setTarget:self]; + [self setAction:@selector(scroll:)]; + [self setControlSize:controlSize]; + + return self; +} + +- (void)detachPlatformScrollbar +{ + [self setTarget:nil]; + scrollbar = 0; +} + +- (IBAction)scroll:(NSScroller*)sender +{ + if (scrollbar) + scrollbar->scrollbarHit([sender hitPart]); +} + +- (void)mouseDown:(NSEvent *)event +{ + Widget::beforeMouseDown(self, scrollbar); + [super mouseDown:event]; + Widget::afterMouseDown(self, scrollbar); +} + +@end + +namespace WebCore +{ + +PlatformScrollbar::PlatformScrollbar(ScrollbarClient* client, ScrollbarOrientation orientation, ScrollbarControlSize controlSize) + : Scrollbar(client, orientation, controlSize) +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + + WebCoreScrollBar *bar = [[WebCoreScrollBar alloc] initWithPlatformScrollbar:this]; + setView(bar); + [bar release]; + + END_BLOCK_OBJC_EXCEPTIONS; +} + +PlatformScrollbar::~PlatformScrollbar() +{ + WebCoreScrollBar* bar = (WebCoreScrollBar*)getView(); + [bar detachPlatformScrollbar]; + + // Widget should probably do this for all widgets. + // But we don't need it for form elements, and for frames it doesn't work + // well because of the way the NSViews are created in WebKit. So for now, + // we'll just do it explictly for Scrollbar. + removeFromSuperview(); +} + +void PlatformScrollbar::updateThumbPosition() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + WebCoreScrollBar *bar = (WebCoreScrollBar *)getView(); + [bar setFloatValue:(float)m_currentPos / (m_totalSize - m_visibleSize) + knobProportion:[bar knobProportion]]; + END_BLOCK_OBJC_EXCEPTIONS; +} + +void PlatformScrollbar::updateThumbProportion() +{ + float val = static_cast<float>(m_visibleSize) / m_totalSize; + + BEGIN_BLOCK_OBJC_EXCEPTIONS; + WebCoreScrollBar *bar = (WebCoreScrollBar *)getView(); + if (val != [bar knobProportion] && val >= 0) + [bar setFloatValue:static_cast<float>(m_currentPos) / (m_totalSize - m_visibleSize) knobProportion:val]; + END_BLOCK_OBJC_EXCEPTIONS; +} + +bool PlatformScrollbar::scrollbarHit(NSScrollerPart hitPart) +{ + int maxPos = m_totalSize - m_visibleSize; + if (maxPos <= 0) + return false; // Impossible to scroll anywhere. + + WebCoreScrollBar *bar = (WebCoreScrollBar *)getView(); + int newPos = value(); + switch (hitPart) { + case NSScrollerDecrementLine: + newPos -= m_lineStep; + break; + case NSScrollerIncrementLine: + newPos += m_lineStep; + break; + case NSScrollerDecrementPage: + newPos -= m_pageStep; + break; + case NSScrollerIncrementPage: + newPos += m_pageStep; + break; + + // If the thumb is hit, then the scrollbar changed its value for us. + case NSScrollerKnob: + case NSScrollerKnobSlot: + newPos = (int)([bar floatValue] * maxPos); + break; + + case NSScrollerNoPart: + break; + } + + return setValue(newPos); +} + +int PlatformScrollbar::width() const +{ + return Widget::width(); +} + +int PlatformScrollbar::height() const +{ + return Widget::height(); +} + +void PlatformScrollbar::setRect(const IntRect& rect) +{ + setFrameGeometry(rect); +} + +void PlatformScrollbar::setEnabled(bool enabled) +{ + Widget::setEnabled(enabled); +} + +void PlatformScrollbar::paint(GraphicsContext* graphicsContext, const IntRect& damageRect) +{ + Widget::paint(graphicsContext, damageRect); +} + +} diff --git a/WebCore/platform/mac/PlugInInfoStoreMac.mm b/WebCore/platform/mac/PlugInInfoStoreMac.mm new file mode 100644 index 0000000..2776eae --- /dev/null +++ b/WebCore/platform/mac/PlugInInfoStoreMac.mm @@ -0,0 +1,99 @@ +/* + * Copyright (C) 2004 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. + */ + +#import "config.h" +#import "PluginInfoStore.h" + +#import "BlockExceptions.h" +#import "Logging.h" +#import "WebCoreViewFactory.h" + +namespace WebCore { + +String PluginInfoStore::pluginNameForMIMEType(const String& mimeType) +{ + return [[WebCoreViewFactory sharedFactory] pluginNameForMIMEType:mimeType]; +} + +PluginInfo *PluginInfoStore::createPluginInfoForPluginAtIndex(unsigned index) +{ + PluginInfo *pluginInfo = new PluginInfo; + + BEGIN_BLOCK_OBJC_EXCEPTIONS; + + id <WebCorePluginInfo> plugin = [[[WebCoreViewFactory sharedFactory] pluginsInfo] objectAtIndex:index]; + + pluginInfo->name = [plugin name]; + pluginInfo->file = [plugin filename]; + pluginInfo->desc = [plugin pluginDescription]; + + NSEnumerator *MIMETypeEnumerator = [plugin MIMETypeEnumerator]; + while (NSString *MIME = [MIMETypeEnumerator nextObject]) { + MimeClassInfo *mime = new MimeClassInfo; + pluginInfo->mimes.append(mime); + mime->type = String(MIME).lower(); + mime->suffixes = [[plugin extensionsForMIMEType:MIME] componentsJoinedByString:@","]; + mime->desc = [plugin descriptionForMIMEType:MIME]; + mime->plugin = pluginInfo; + } + + return pluginInfo; + + END_BLOCK_OBJC_EXCEPTIONS; + + if (pluginInfo && !pluginInfo->mimes.isEmpty()) + deleteAllValues(pluginInfo->mimes); + delete pluginInfo; + + return 0; +} + +unsigned PluginInfoStore::pluginCount() const +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[[WebCoreViewFactory sharedFactory] pluginsInfo] count]; + END_BLOCK_OBJC_EXCEPTIONS; + + return 0; +} + +bool PluginInfoStore::supportsMIMEType(const String& mimeType) +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return [[WebCoreViewFactory sharedFactory] pluginSupportsMIMEType:mimeType]; + END_BLOCK_OBJC_EXCEPTIONS; + + return NO; +} + +void refreshPlugins(bool reloadOpenPages) +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + [[WebCoreViewFactory sharedFactory] refreshPlugins:reloadOpenPages]; + END_BLOCK_OBJC_EXCEPTIONS; +} + +} + diff --git a/WebCore/platform/mac/PopupMenuMac.mm b/WebCore/platform/mac/PopupMenuMac.mm new file mode 100644 index 0000000..16cbe75 --- /dev/null +++ b/WebCore/platform/mac/PopupMenuMac.mm @@ -0,0 +1,193 @@ +/* + * Copyright (C) 2006 Apple Computer, Inc. + * + * 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. + */ + +#import "config.h" +#import "PopupMenu.h" + +#import "EventHandler.h" +#import "SimpleFontData.h" +#import "Frame.h" +#import "FrameView.h" +#import "HTMLNames.h" +#import "HTMLOptGroupElement.h" +#import "HTMLOptionElement.h" +#import "HTMLSelectElement.h" +#import "WebCoreSystemInterface.h" + +namespace WebCore { + +using namespace HTMLNames; + +PopupMenu::PopupMenu(PopupMenuClient* client) + : RefCounted<PopupMenu>(0) + , m_popupClient(client) +{ +} + +PopupMenu::~PopupMenu() +{ + if (m_popup) + [m_popup.get() setControlView:nil]; +} + +void PopupMenu::clear() +{ + if (m_popup) + [m_popup.get() removeAllItems]; +} + +void PopupMenu::populate() +{ + if (m_popup) + clear(); + else { + m_popup = [[NSPopUpButtonCell alloc] initTextCell:@"" pullsDown:!client()->shouldPopOver()]; + [m_popup.get() release]; // release here since the RetainPtr has retained the object already + [m_popup.get() setUsesItemFromMenu:NO]; + [m_popup.get() setAutoenablesItems:NO]; + } + + BOOL messagesEnabled = [[m_popup.get() menu] menuChangedMessagesEnabled]; + [[m_popup.get() menu] setMenuChangedMessagesEnabled:NO]; + + // For pullDown menus the first item is hidden. + if (!client()->shouldPopOver()) + [m_popup.get() addItemWithTitle:@""]; + + ASSERT(client()); + int size = client()->listSize(); + + for (int i = 0; i < size; i++) { + if (client()->itemIsSeparator(i)) + [[m_popup.get() menu] addItem:[NSMenuItem separatorItem]]; + else { + RenderStyle* style = client()->itemStyle(i); + NSMutableDictionary* attributes = [[NSMutableDictionary alloc] init]; + if (style->font() != Font()) + [attributes setObject:style->font().primaryFont()->getNSFont() forKey:NSFontAttributeName]; + // FIXME: Add support for styling the foreground and background colors. + // FIXME: Find a way to customize text color when an item is highlighted. + NSAttributedString* string = [[NSAttributedString alloc] initWithString:client()->itemText(i) attributes:attributes]; + [attributes release]; + + [m_popup.get() addItemWithTitle:@""]; + NSMenuItem* menuItem = [m_popup.get() lastItem]; + [menuItem setAttributedTitle:string]; + [menuItem setEnabled:client()->itemIsEnabled(i)]; + [string release]; + } + } + + [[m_popup.get() menu] setMenuChangedMessagesEnabled:messagesEnabled]; +} + +void PopupMenu::show(const IntRect& r, FrameView* v, int index) +{ + populate(); + int numItems = [m_popup.get() numberOfItems]; + if (numItems <= 0) { + if (client()) + client()->hidePopup(); + return; + } + ASSERT(numItems > index); + + // Workaround for crazy bug where a selected index of -1 for a menu with only 1 item will cause a blank menu. + if (index == -1 && numItems == 2 && !client()->shouldPopOver() && ![[m_popup.get() itemAtIndex:1] isEnabled]) + index = 0; + + NSView* view = v->getDocumentView(); + + [m_popup.get() attachPopUpWithFrame:r inView:view]; + [m_popup.get() selectItemAtIndex:index]; + + NSMenu* menu = [m_popup.get() menu]; + + NSPoint location; + NSFont* font = client()->clientStyle()->font().primaryFont()->getNSFont(); + + // These values were borrowed from AppKit to match their placement of the menu. + const int popOverHorizontalAdjust = -10; + const int popUnderHorizontalAdjust = 6; + const int popUnderVerticalAdjust = 6; + if (client()->shouldPopOver()) { + NSRect titleFrame = [m_popup.get() titleRectForBounds:r]; + if (titleFrame.size.width <= 0 || titleFrame.size.height <= 0) + titleFrame = r; + float vertOffset = roundf((NSMaxY(r) - NSMaxY(titleFrame)) + NSHeight(titleFrame)); + // Adjust for fonts other than the system font. + NSFont* defaultFont = [NSFont systemFontOfSize:[font pointSize]]; + vertOffset += [font descender] - [defaultFont descender]; + vertOffset = fminf(NSHeight(r), vertOffset); + + location = NSMakePoint(NSMinX(r) + popOverHorizontalAdjust, NSMaxY(r) - vertOffset); + } else + location = NSMakePoint(NSMinX(r) + popUnderHorizontalAdjust, NSMaxY(r) + popUnderVerticalAdjust); + + // Save the current event that triggered the popup, so we can clean up our event + // state after the NSMenu goes away. + RefPtr<Frame> frame = v->frame(); + NSEvent* event = [frame->eventHandler()->currentNSEvent() retain]; + + RefPtr<PopupMenu> protector(this); + + RetainPtr<NSView> dummyView(AdoptNS, [[NSView alloc] initWithFrame:r]); + [view addSubview:dummyView.get()]; + location = [dummyView.get() convertPoint:location fromView:view]; + + frame->willPopupMenu(menu); + wkPopupMenu(menu, location, roundf(NSWidth(r)), dummyView.get(), index, font); + + [m_popup.get() dismissPopUp]; + [dummyView.get() removeFromSuperview]; + + if (client()) { + int newIndex = [m_popup.get() indexOfSelectedItem]; + client()->hidePopup(); + + // Adjust newIndex for hidden first item. + if (!client()->shouldPopOver()) + newIndex--; + + if (index != newIndex && newIndex >= 0) + client()->valueChanged(newIndex); + + // Give the frame a chance to fix up its event state, since the popup eats all the + // events during tracking. + frame->eventHandler()->sendFakeEventsAfterWidgetTracking(event); + } + + [event release]; +} + +void PopupMenu::hide() +{ + [m_popup.get() dismissPopUp]; +} + +void PopupMenu::updateFromElement() +{ +} + +bool PopupMenu::itemWritingDirectionIsNatural() +{ + return true; +} + +} diff --git a/WebCore/platform/mac/SSLKeyGeneratorMac.mm b/WebCore/platform/mac/SSLKeyGeneratorMac.mm new file mode 100644 index 0000000..2b1190b --- /dev/null +++ b/WebCore/platform/mac/SSLKeyGeneratorMac.mm @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2003, 2008 Apple 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. + */ + +#import "config.h" +#import "SSLKeyGenerator.h" + +#import "KURL.h" +#import "WebCoreKeyGenerator.h" + +namespace WebCore { + +Vector<String> supportedKeySizes() +{ + NSEnumerator *enumerator = [[[WebCoreKeyGenerator sharedGenerator] strengthMenuItemTitles] objectEnumerator]; + Vector<String> supportedKeySizes; + NSString *string; + while ((string = [enumerator nextObject]) != nil) { + supportedKeySizes.append(string); + } + return supportedKeySizes; +} + +String signedPublicKeyAndChallengeString(unsigned keySizeIndex, const String& challengeString, const KURL& url) +{ + return [[WebCoreKeyGenerator sharedGenerator] signedPublicKeyAndChallengeStringWithStrengthIndex:keySizeIndex + challenge:challengeString + pageURL:url]; +} + +} diff --git a/WebCore/platform/mac/ScrollViewMac.mm b/WebCore/platform/mac/ScrollViewMac.mm new file mode 100644 index 0000000..1caa433 --- /dev/null +++ b/WebCore/platform/mac/ScrollViewMac.mm @@ -0,0 +1,501 @@ +/* + * Copyright (C) 2004, 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. + */ + +#import "config.h" +#import "ScrollView.h" + +#import "FloatRect.h" +#import "IntRect.h" +#import "BlockExceptions.h" +#import "Logging.h" +#import "WebCoreFrameView.h" + +/* + This class implementation does NOT actually emulate the Qt ScrollView. + It does provide an implementation that khtml will use to interact with + WebKit's WebFrameView documentView and our NSScrollView subclass. + + ScrollView's view is a NSScrollView (or subclass of NSScrollView) + in most cases. That scrollview is a subview of an + WebCoreFrameView. The WebCoreFrameView's documentView will also be + the scroll view's documentView. + + The WebCoreFrameView's size is the frame size. The WebCoreFrameView's documentView + corresponds to the frame content size. The scrollview itself is autosized to the + WebCoreFrameView's size (see Widget::resize). +*/ + +namespace WebCore { + +int ScrollView::visibleWidth() const +{ + NSScrollView *view = (NSScrollView *)getView(); + + BEGIN_BLOCK_OBJC_EXCEPTIONS; + if ([view isKindOfClass:[NSScrollView class]]) + return (int)[view documentVisibleRect].size.width; + else + return (int)[view bounds].size.width; + END_BLOCK_OBJC_EXCEPTIONS; + + return 0; +} + +int ScrollView::visibleHeight() const +{ + NSScrollView *view = (NSScrollView *)getView(); + + BEGIN_BLOCK_OBJC_EXCEPTIONS; + if ([view isKindOfClass:[NSScrollView class]]) + return (int)[view documentVisibleRect].size.height; + else + return (int)[view bounds].size.height; + END_BLOCK_OBJC_EXCEPTIONS; + + return 0; +} + +FloatRect ScrollView::visibleContentRect() const +{ + NSScrollView *view = (NSScrollView *)getView(); + + BEGIN_BLOCK_OBJC_EXCEPTIONS; + if ([view isKindOfClass:[NSScrollView class]]) + return [view documentVisibleRect]; + else + return [view visibleRect]; + END_BLOCK_OBJC_EXCEPTIONS; + + return FloatRect(); +} + +FloatRect ScrollView::visibleContentRectConsideringExternalScrollers() const +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + if (NSView *docView = getDocumentView()) + return [docView visibleRect]; + END_BLOCK_OBJC_EXCEPTIONS; + + return FloatRect(); +} + + +int ScrollView::contentsWidth() const +{ + NSView *docView, *view = getView(); + docView = getDocumentView(); + + BEGIN_BLOCK_OBJC_EXCEPTIONS; + if (docView) + return (int)[docView bounds].size.width; + else + return (int)[view bounds].size.width; + END_BLOCK_OBJC_EXCEPTIONS; + + return 0; +} + +int ScrollView::contentsHeight() const +{ + NSView *docView, *view = getView(); + docView = getDocumentView(); + + BEGIN_BLOCK_OBJC_EXCEPTIONS; + if (docView) + return (int)[docView bounds].size.height; + else + return (int)[view bounds].size.height; + END_BLOCK_OBJC_EXCEPTIONS; + + return 0; +} + +int ScrollView::contentsX() const +{ + NSView *view = getView(); + + BEGIN_BLOCK_OBJC_EXCEPTIONS; + if ([view isKindOfClass:[NSScrollView class]]) + return (int)[(NSScrollView *)view documentVisibleRect].origin.x; + else + return (int)[view visibleRect].origin.x; + END_BLOCK_OBJC_EXCEPTIONS; + + return 0; +} + +int ScrollView::contentsY() const +{ + NSView *view = getView(); + + BEGIN_BLOCK_OBJC_EXCEPTIONS; + if ([view isKindOfClass:[NSScrollView class]]) + return (int)[(NSScrollView *)view documentVisibleRect].origin.y; + else + return (int)[view visibleRect].origin.y; + END_BLOCK_OBJC_EXCEPTIONS; + + return 0; +} + +IntSize ScrollView::scrollOffset() const +{ + NSView *view = getView(); + + BEGIN_BLOCK_OBJC_EXCEPTIONS; + if ([view isKindOfClass:[NSScrollView class]]) + return IntPoint([[(NSScrollView *)view contentView] visibleRect].origin) - IntPoint(); + END_BLOCK_OBJC_EXCEPTIONS; + return IntSize(); +} + +void ScrollView::scrollBy(int dx, int dy) +{ + setContentsPos(contentsX() + dx, contentsY() + dy); +} + +void ScrollView::scrollRectIntoViewRecursively(const IntRect& r) +{ + NSRect rect = r; + + BEGIN_BLOCK_OBJC_EXCEPTIONS; + NSView *docView; + NSView *view = getView(); + docView = getDocumentView(); + if (docView) + view = docView; + + NSView *originalView = view; + while (view) { + if ([view isKindOfClass:[NSClipView class]]) { + NSClipView *clipView = (NSClipView *)view; + NSView *documentView = [clipView documentView]; + [documentView scrollRectToVisible:[documentView convertRect:rect fromView:originalView]]; + } + + view = [view superview]; + } + + END_BLOCK_OBJC_EXCEPTIONS; +} + +void ScrollView::setContentsPos(int x, int y) +{ + x = (x < 0) ? 0 : x; + y = (y < 0) ? 0 : y; + NSPoint p = NSMakePoint(x,y); + + BEGIN_BLOCK_OBJC_EXCEPTIONS; + NSView *docView; + NSView *view = getView(); + docView = getDocumentView(); + if (docView) + view = docView; + [view scrollPoint:p]; + END_BLOCK_OBJC_EXCEPTIONS; +} + +void ScrollView::setVScrollbarMode(ScrollbarMode vMode) +{ + NSView* view = getView(); + + BEGIN_BLOCK_OBJC_EXCEPTIONS; + if ([view conformsToProtocol:@protocol(WebCoreFrameView)]) { + NSView<WebCoreFrameView>* frameView = (NSView<WebCoreFrameView>*)view; + [frameView setVerticalScrollingMode: (WebCoreScrollbarMode)vMode]; + } + END_BLOCK_OBJC_EXCEPTIONS; +} + +void ScrollView::setHScrollbarMode(ScrollbarMode hMode) +{ + NSView* view = getView(); + + BEGIN_BLOCK_OBJC_EXCEPTIONS; + if ([view conformsToProtocol:@protocol(WebCoreFrameView)]) { + NSView<WebCoreFrameView>* frameView = (NSView<WebCoreFrameView>*)view; + [frameView setHorizontalScrollingMode: (WebCoreScrollbarMode)hMode]; + } + END_BLOCK_OBJC_EXCEPTIONS; +} + +void ScrollView::setScrollbarsMode(ScrollbarMode mode) +{ + NSView* view = getView(); + + BEGIN_BLOCK_OBJC_EXCEPTIONS; + if ([view conformsToProtocol:@protocol(WebCoreFrameView)]) { + NSView<WebCoreFrameView>* frameView = (NSView<WebCoreFrameView>*)view; + [frameView setScrollingMode: (WebCoreScrollbarMode)mode]; + } + END_BLOCK_OBJC_EXCEPTIONS; +} + +ScrollbarMode ScrollView::vScrollbarMode() const +{ + NSView* view = getView(); + + BEGIN_BLOCK_OBJC_EXCEPTIONS; + if ([view conformsToProtocol:@protocol(WebCoreFrameView)]) { + NSView<WebCoreFrameView>* frameView = (NSView<WebCoreFrameView>*)view; + return (ScrollbarMode)[frameView verticalScrollingMode]; + } + END_BLOCK_OBJC_EXCEPTIONS; + + return ScrollbarAuto; +} + +ScrollbarMode ScrollView::hScrollbarMode() const +{ + NSView* view = getView(); + + BEGIN_BLOCK_OBJC_EXCEPTIONS; + if ([view conformsToProtocol:@protocol(WebCoreFrameView)]) { + NSView<WebCoreFrameView>* frameView = (NSView<WebCoreFrameView>*)view; + return (ScrollbarMode)[frameView horizontalScrollingMode]; + } + END_BLOCK_OBJC_EXCEPTIONS; + + return ScrollbarAuto; +} + +void ScrollView::suppressScrollbars(bool suppressed, bool repaintOnUnsuppress) +{ + NSView* view = getView(); + + BEGIN_BLOCK_OBJC_EXCEPTIONS; + if ([view conformsToProtocol:@protocol(WebCoreFrameView)]) { + NSView<WebCoreFrameView>* frameView = (NSView<WebCoreFrameView>*)view; + [frameView setScrollBarsSuppressed: suppressed + repaintOnUnsuppress: repaintOnUnsuppress]; + } + END_BLOCK_OBJC_EXCEPTIONS; +} + +void ScrollView::addChild(Widget* child) +{ + ASSERT(child != this); + + NSView *thisView = getView(); + NSView *thisDocView = getDocumentView(); + if (thisDocView) + thisView = thisDocView; + +#ifndef NDEBUG + NSView *subview = child->getOuterView(); + + LOG(Frames, "Adding %p %@ with size w %d h %d\n", subview, + [(id)[subview class] className], (int)[subview frame].size.width, (int)[subview frame].size.height); +#endif + child->addToSuperview(thisView); +} + +void ScrollView::removeChild(Widget* child) +{ + child->removeFromSuperview(); +} + +void ScrollView::resizeContents(int w, int h) +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + int _w = w; + int _h = h; + + LOG(Frames, "%p %@ at w %d h %d\n", getView(), [(id)[getView() class] className], w, h); + NSView *view = getView(); + if ([view isKindOfClass:[NSScrollView class]]){ + view = getDocumentView(); + + LOG(Frames, "%p %@ at w %d h %d\n", view, [(id)[view class] className], w, h); + if (_w < 0) + _w = 0; + if (_h < 0) + _h = 0; + + NSSize tempSize = { _w, _h }; // workaround for 4213314 + [view setFrameSize:tempSize]; + } else { + resize (_w, _h); + } + END_BLOCK_OBJC_EXCEPTIONS; +} + +void ScrollView::updateContents(const IntRect &rect, bool now) +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + + NSView *view = getView(); + + if ([view isKindOfClass:[NSScrollView class]]) + view = getDocumentView(); + + NSRect visibleRect = visibleContentRect(); + + // Checking for rect visibility is an important optimization for the case of + // Select All of a large document. AppKit does not do this check, and so ends + // up building a large complicated NSRegion if we don't perform the check. + NSRect dirtyRect = NSIntersectionRect(rect, visibleRect); + if (!NSIsEmptyRect(dirtyRect)) { + [view setNeedsDisplayInRect:dirtyRect]; + if (now) { + [[view window] displayIfNeeded]; + [[view window] flushWindowIfNeeded]; + } + } + + END_BLOCK_OBJC_EXCEPTIONS; +} + +void ScrollView::update() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + + NSView *view = getView(); + [[view window] displayIfNeeded]; + [[view window] flushWindowIfNeeded]; + + END_BLOCK_OBJC_EXCEPTIONS; +} + +// "Containing Window" means the NSWindow's coord system, which is origin lower left + +IntPoint ScrollView::contentsToWindow(const IntPoint& contentsPoint) const +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + + NSView *docView; + NSView *view = getView(); + + docView = getDocumentView(); + if (docView) + view = docView; + + NSPoint tempPoint = { contentsPoint.x(), contentsPoint.y() }; // workaround for 4213314 + NSPoint np = [view convertPoint:tempPoint toView: nil]; + return IntPoint(np); + + END_BLOCK_OBJC_EXCEPTIONS; + + return IntPoint(); +} + +IntPoint ScrollView::windowToContents(const IntPoint& point) const +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + + NSView *docView; + NSView *view = getView(); + + docView = getDocumentView(); + if (docView) + view = docView; + + NSPoint tempPoint = { point.x(), point.y() }; // workaround for 4213314 + NSPoint np = [view convertPoint:tempPoint fromView: nil]; + + return IntPoint(np); + + END_BLOCK_OBJC_EXCEPTIONS; + + return IntPoint(); +} + +IntRect ScrollView::contentsToWindow(const IntRect& contentsRect) const +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + + NSView* docView; + NSView* view = getView(); + + docView = getDocumentView(); + if (docView) + view = docView; + + NSRect nr = [view convertRect:contentsRect toView: nil]; + return IntRect(nr); + + END_BLOCK_OBJC_EXCEPTIONS; + + return IntRect(); +} + +IntRect ScrollView::windowToContents(const IntRect& rect) const +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + + NSView* docView; + NSView* view = getView(); + + docView = getDocumentView(); + if (docView) + view = docView; + + NSRect nr = [view convertRect:rect fromView: nil]; + + return IntRect(nr); + + END_BLOCK_OBJC_EXCEPTIONS; + + return IntRect(); +} + +void ScrollView::setStaticBackground(bool b) +{ + NSScrollView *view = (NSScrollView *)getView(); + BEGIN_BLOCK_OBJC_EXCEPTIONS; + if ([view isKindOfClass:[NSScrollView class]]) + [[view contentView] setCopiesOnScroll: !b]; + END_BLOCK_OBJC_EXCEPTIONS; +} + +NSView *ScrollView::getDocumentView() const +{ + id view = getView(); + + BEGIN_BLOCK_OBJC_EXCEPTIONS; + if ([view respondsToSelector:@selector(documentView)]) + return [view documentView]; + END_BLOCK_OBJC_EXCEPTIONS; + + return nil; +} + +PlatformScrollbar* ScrollView::scrollbarUnderMouse(const PlatformMouseEvent& mouseEvent) +{ + // On Mac, the ScrollView is really the "document", so events will never flow into it to get to the scrollers. + return 0; +} + +bool ScrollView::inWindow() const +{ + return [getView() window]; +} + +void ScrollView::wheelEvent(PlatformWheelEvent&) +{ + // Do nothing. NSScrollView handles doing the scroll for us. +} + +} diff --git a/WebCore/platform/mac/SearchPopupMenuMac.mm b/WebCore/platform/mac/SearchPopupMenuMac.mm new file mode 100644 index 0000000..262734d --- /dev/null +++ b/WebCore/platform/mac/SearchPopupMenuMac.mm @@ -0,0 +1,74 @@ +/* + * Copyright (C) 2006 Apple Computer, Inc. + * + * 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. + */ + +#import "config.h" +#import "SearchPopupMenu.h" + +#import "AtomicString.h" + +namespace WebCore { + +SearchPopupMenu::SearchPopupMenu(PopupMenuClient* client) + : PopupMenu(client) +{ +} + +static NSString* autosaveKey(const String& name) +{ + return [@"com.apple.WebKit.searchField:" stringByAppendingString:name]; +} + +bool SearchPopupMenu::enabled() +{ + return true; +} + +void SearchPopupMenu::saveRecentSearches(const AtomicString& name, const Vector<String>& searchItems) +{ + if (name.isEmpty()) + return; + + size_t size = searchItems.size(); + if (size == 0) + [[NSUserDefaults standardUserDefaults] removeObjectForKey:autosaveKey(name)]; + else { + NSMutableArray* items = [[NSMutableArray alloc] initWithCapacity:size]; + for (size_t i = 0; i < size; ++i) + [items addObject:searchItems[i]]; + [[NSUserDefaults standardUserDefaults] setObject:items forKey:autosaveKey(name)]; + [items release]; + } +} + +void SearchPopupMenu::loadRecentSearches(const AtomicString& name, Vector<String>& searchItems) +{ + if (name.isEmpty()) + return; + + searchItems.clear(); + NSArray* items = [[NSUserDefaults standardUserDefaults] arrayForKey:autosaveKey(name)]; + size_t size = [items count]; + for (size_t i = 0; i < size; ++i) { + NSString* item = [items objectAtIndex:i]; + if ([item isKindOfClass:[NSString class]]) + searchItems.append(item); + } +} + +} diff --git a/WebCore/platform/mac/SharedBufferMac.mm b/WebCore/platform/mac/SharedBufferMac.mm new file mode 100644 index 0000000..d241eaf --- /dev/null +++ b/WebCore/platform/mac/SharedBufferMac.mm @@ -0,0 +1,154 @@ +/* + * 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 "FoundationExtras.h" +#include "SharedBuffer.h" +#include "WebCoreObjCExtras.h" +#include <string.h> +#include <wtf/PassRefPtr.h> + +using namespace WebCore; + +@interface WebCoreSharedBufferData : NSData +{ + SharedBuffer* sharedBuffer; +} + +- (id)initWithSharedBuffer:(SharedBuffer*)buffer; +@end + +@implementation WebCoreSharedBufferData + +#ifndef BUILDING_ON_TIGER ++ (void)initialize +{ + WebCoreObjCFinalizeOnMainThread(self); +} +#endif + +- (void)dealloc +{ + sharedBuffer->deref(); + + [super dealloc]; +} + +- (void)finalize +{ + sharedBuffer->deref(); + + [super finalize]; +} + +- (id)initWithSharedBuffer:(SharedBuffer*)buffer +{ + self = [super init]; + + if (self) { + sharedBuffer = buffer; + sharedBuffer->ref(); + } + + return self; +} + +- (unsigned)length +{ + return sharedBuffer->size(); +} + +- (const void *)bytes +{ + return reinterpret_cast<const void*>(sharedBuffer->data()); +} + +@end + +namespace WebCore { + +PassRefPtr<SharedBuffer> SharedBuffer::wrapNSData(NSData *nsData) +{ + return new SharedBuffer(nsData); +} + +SharedBuffer::SharedBuffer(NSData *nsData) + : RefCounted<SharedBuffer>(0) + , m_nsData(nsData) +{ +} + +NSData *SharedBuffer::createNSData() +{ + return [[WebCoreSharedBufferData alloc] initWithSharedBuffer:this]; +} + +CFDataRef SharedBuffer::createCFData() +{ + return (CFDataRef)HardRetainWithNSRelease([[WebCoreSharedBufferData alloc] initWithSharedBuffer:this]); +} + +bool SharedBuffer::hasPlatformData() const +{ + return m_nsData; +} + +const char* SharedBuffer::platformData() const +{ + return (const char*)[m_nsData.get() bytes]; +} + +unsigned SharedBuffer::platformDataSize() const +{ + return [m_nsData.get() length]; +} + +void SharedBuffer::maybeTransferPlatformData() +{ + if (!m_nsData) + return; + + ASSERT(m_buffer.size() == 0); + + m_buffer.append(reinterpret_cast<const char*>([m_nsData.get() bytes]), [m_nsData.get() length]); + + m_nsData = nil; +} + +void SharedBuffer::clearPlatformData() +{ + m_nsData = 0; +} + +PassRefPtr<SharedBuffer> SharedBuffer::createWithContentsOfFile(const String& filePath) +{ + NSData *resourceData = [NSData dataWithContentsOfFile:filePath]; + if (resourceData) + return SharedBuffer::wrapNSData(resourceData); + return 0; +} + +} + diff --git a/WebCore/platform/mac/SharedTimerMac.cpp b/WebCore/platform/mac/SharedTimerMac.cpp new file mode 100644 index 0000000..991f527 --- /dev/null +++ b/WebCore/platform/mac/SharedTimerMac.cpp @@ -0,0 +1,117 @@ +/* + * 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. + */ + +#import "config.h" +#import "SharedTimer.h" + +#include <Foundation/Foundation.h> +#include <wtf/Assertions.h> + +@class WebCorePowerNotifier; + +namespace WebCore { + +static WebCorePowerNotifier *powerNotifier; +static CFRunLoopTimerRef sharedTimer; +static void (*sharedTimerFiredFunction)(); +static void timerFired(CFRunLoopTimerRef, void*); + +} + +@interface WebCorePowerNotifier : NSObject +@end + +@implementation WebCorePowerNotifier + +- (id)init +{ + self = [super init]; + + if (self) + [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self + selector:@selector(didWake:) + name:NSWorkspaceDidWakeNotification + object:nil]; + + return self; +} + +- (void)didWake:(NSNotification *)notification +{ + if (WebCore::sharedTimer) { + WebCore::stopSharedTimer(); + WebCore::timerFired(0, 0); + } +} + +@end + +namespace WebCore { + +void setSharedTimerFiredFunction(void (*f)()) +{ + ASSERT(!sharedTimerFiredFunction || sharedTimerFiredFunction == f); + + sharedTimerFiredFunction = f; +} + +static void timerFired(CFRunLoopTimerRef, void*) +{ + // FIXME: We can remove this global catch-all if we fix <rdar://problem/5299018>. + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + sharedTimerFiredFunction(); + [pool drain]; +} + +void setSharedTimerFireTime(double fireTime) +{ + ASSERT(sharedTimerFiredFunction); + + if (sharedTimer) { + CFRunLoopTimerInvalidate(sharedTimer); + CFRelease(sharedTimer); + } + + CFAbsoluteTime fireDate = fireTime - kCFAbsoluteTimeIntervalSince1970; + sharedTimer = CFRunLoopTimerCreate(0, fireDate, 0, 0, 0, timerFired, 0); + CFRunLoopAddTimer(CFRunLoopGetCurrent(), sharedTimer, kCFRunLoopCommonModes); + + if (!powerNotifier) { + powerNotifier = [[WebCorePowerNotifier alloc] init]; + CFRetain(powerNotifier); + [powerNotifier release]; + } +} + +void stopSharedTimer() +{ + if (sharedTimer) { + CFRunLoopTimerInvalidate(sharedTimer); + CFRelease(sharedTimer); + sharedTimer = 0; + } +} + +} diff --git a/WebCore/platform/mac/SoftLinking.h b/WebCore/platform/mac/SoftLinking.h new file mode 100644 index 0000000..d470b29 --- /dev/null +++ b/WebCore/platform/mac/SoftLinking.h @@ -0,0 +1,100 @@ +/* + * Copyright (C) 2007 Apple 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. + * 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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 <wtf/Assertions.h> +#import <dlfcn.h> + +#define SOFT_LINK_LIBRARY(lib) \ + static void* lib##Library() \ + { \ + static void* dylib = dlopen("/usr/lib/" #lib ".dylib", RTLD_NOW); \ + ASSERT(dylib); \ + return dylib; \ + } + +#define SOFT_LINK_FRAMEWORK(framework) \ + static void* framework##Library() \ + { \ + static void* frameworkLibrary = dlopen("/System/Library/Frameworks/" #framework ".framework/" #framework, RTLD_NOW); \ + ASSERT(frameworkLibrary); \ + return frameworkLibrary; \ + } + +#define SOFT_LINK(framework, functionName, resultType, parameterDeclarations, parameterNames) \ + static resultType init##functionName parameterDeclarations; \ + static resultType (*softLink##functionName) parameterDeclarations = init##functionName; \ + \ + static resultType init##functionName parameterDeclarations \ + { \ + softLink##functionName = (resultType (*) parameterDeclarations) dlsym(framework##Library(), #functionName); \ + ASSERT(softLink##functionName); \ + return softLink##functionName parameterNames; \ + }\ + \ + inline resultType functionName parameterDeclarations \ + {\ + return softLink##functionName parameterNames; \ + } + +#define SOFT_LINK_CLASS(framework, className) \ + static Class init##className(); \ + static Class (*get##className##Class)() = init##className; \ + static Class class##className; \ + \ + static Class className##Function() \ + { \ + return class##className; \ + }\ + \ + static Class init##className() \ + { \ + framework##Library(); \ + class##className = objc_getClass(#className); \ + ASSERT(class##className); \ + get##className##Class = className##Function; \ + return class##className; \ + } + +#define SOFT_LINK_POINTER(framework, name, type) \ + static type init##name(); \ + static type (*get##name)() = init##name; \ + static type pointer##name; \ + \ + static type name##Function() \ + { \ + return pointer##name; \ + }\ + \ + static type init##name() \ + { \ + void** pointer = static_cast<void**>(dlsym(framework##Library(), #name)); \ + ASSERT(pointer); \ + pointer##name = static_cast<type>(*pointer); \ + get##name = name##Function; \ + return pointer##name; \ + } diff --git a/WebCore/platform/mac/SoundMac.mm b/WebCore/platform/mac/SoundMac.mm new file mode 100644 index 0000000..ced14b8 --- /dev/null +++ b/WebCore/platform/mac/SoundMac.mm @@ -0,0 +1,33 @@ +/* + * 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. + */ + +#import "config.h" +#import "Sound.h" + +namespace WebCore { + +void systemBeep() { NSBeep(); } + +} // namespace WebCore diff --git a/WebCore/platform/mac/SystemTimeMac.cpp b/WebCore/platform/mac/SystemTimeMac.cpp new file mode 100644 index 0000000..dd5e500 --- /dev/null +++ b/WebCore/platform/mac/SystemTimeMac.cpp @@ -0,0 +1,44 @@ +/* + * 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 "SystemTime.h" + +#include <CoreGraphics/CGEventSource.h> +#include <CoreFoundation/CFDate.h> + +namespace WebCore { + +double currentTime() +{ + return CFAbsoluteTimeGetCurrent() + kCFAbsoluteTimeIntervalSince1970; +} + +float userIdleTime() +{ + return static_cast<float>(CGEventSourceSecondsSinceLastEventType(kCGEventSourceStateCombinedSessionState, kCGAnyInputEventType)); +} + +} diff --git a/WebCore/platform/mac/ThreadCheck.mm b/WebCore/platform/mac/ThreadCheck.mm new file mode 100644 index 0000000..92fcd44 --- /dev/null +++ b/WebCore/platform/mac/ThreadCheck.mm @@ -0,0 +1,99 @@ +/* + * Copyright (C) 2007 Apple 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. + */ + +#import "config.h" +#import "ThreadCheck.h" + +#import "StringHash.h" +#import <JavaScriptCore/HashSet.h> + +namespace WebCore { + +static ThreadViolationBehavior defaultThreadViolationBehavior = RaiseExceptionOnThreadViolation; + +static bool didReadThreadViolationBehaviorFromUserDefaults = false; +static bool threadViolationBehaviorIsDefault; +static ThreadViolationBehavior threadViolationBehavior; + +static void readThreadViolationBehaviorFromUserDefaults() +{ + NSString *threadCheckLevel = [[NSUserDefaults standardUserDefaults] stringForKey:@"WebCoreThreadCheck"]; + if ([threadCheckLevel isEqualToString:@"None"]) + threadViolationBehavior = NoThreadCheck; + else if ([threadCheckLevel isEqualToString:@"Exception"]) + threadViolationBehavior = RaiseExceptionOnThreadViolation; + else if ([threadCheckLevel isEqualToString:@"Log"]) + threadViolationBehavior = LogOnThreadViolation; + else if ([threadCheckLevel isEqualToString:@"LogOnce"]) + threadViolationBehavior = LogOnFirstThreadViolation; + else { + threadViolationBehavior = defaultThreadViolationBehavior; + threadViolationBehaviorIsDefault = true; + } + didReadThreadViolationBehaviorFromUserDefaults = true; +} + +void setDefaultThreadViolationBehavior(ThreadViolationBehavior behavior) +{ + defaultThreadViolationBehavior = behavior; + if (threadViolationBehaviorIsDefault) + threadViolationBehavior = behavior; +} + +void reportThreadViolation(const char* function) +{ + if (!didReadThreadViolationBehaviorFromUserDefaults) + readThreadViolationBehaviorFromUserDefaults(); + if (threadViolationBehavior == NoThreadCheck) + return; + if (pthread_main_np()) + return; + WebCoreReportThreadViolation(function); +} + +} // namespace WebCore + +// Split out the actual reporting of the thread violation to make it easier to set a breakpoint +void WebCoreReportThreadViolation(const char* function) +{ + using namespace WebCore; + static HashSet<String> loggedFunctions; + switch (threadViolationBehavior) { + case NoThreadCheck: + break; + case LogOnFirstThreadViolation: + if (loggedFunctions.add(function).second) { + NSLog(@"WebKit Threading Violation - %s called from secondary thread", function); + NSLog(@"Additional threading violations for this function will not be logged."); + } + break; + case LogOnThreadViolation: + NSLog(@"WebKit Threading Violation - %s called from secondary thread", function); + break; + case RaiseExceptionOnThreadViolation: + [NSException raise:@"WebKitThreadingException" format:@"%s was called from a secondary thread", function]; + break; + } +} diff --git a/WebCore/platform/mac/WebCoreHistory.h b/WebCore/platform/mac/WebCoreHistory.h new file mode 100644 index 0000000..d99e9b1 --- /dev/null +++ b/WebCore/platform/mac/WebCoreHistory.h @@ -0,0 +1,35 @@ +/* + * Copyright (C) 2003, 2007 Apple 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. + */ + +@protocol WebCoreHistoryProvider <NSObject> +- (BOOL)containsURL:(const UniChar*)unicode length:(unsigned)length; +@end + +@interface WebCoreHistory : NSObject + ++ (void)setHistoryProvider:(id<WebCoreHistoryProvider>)h; ++ (id<WebCoreHistoryProvider>)historyProvider; + +@end diff --git a/WebCore/platform/mac/WebCoreHistory.m b/WebCore/platform/mac/WebCoreHistory.m new file mode 100644 index 0000000..e1d7f38 --- /dev/null +++ b/WebCore/platform/mac/WebCoreHistory.m @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2003 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. + */ + +#import "config.h" + +#import "WebCoreHistory.h" + +@implementation WebCoreHistory + +static id<WebCoreHistoryProvider> _historyProvider = nil; + ++ (void)setHistoryProvider: (id<WebCoreHistoryProvider>)h +{ + if (_historyProvider != h){ + [_historyProvider release]; + _historyProvider = [h retain]; + } +} + ++ (id<WebCoreHistoryProvider>)historyProvider +{ + return _historyProvider; +} + +@end diff --git a/WebCore/platform/mac/WebCoreKeyGenerator.h b/WebCore/platform/mac/WebCoreKeyGenerator.h new file mode 100644 index 0000000..c9260e1 --- /dev/null +++ b/WebCore/platform/mac/WebCoreKeyGenerator.h @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2003 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. + */ + +@interface WebCoreKeyGenerator : NSObject + ++ (WebCoreKeyGenerator *)sharedGenerator; +- (NSArray *)strengthMenuItemTitles; +- (NSString *)signedPublicKeyAndChallengeStringWithStrengthIndex:(unsigned)index challenge:(NSString *)challenge pageURL:(NSURL *)pageURL; + +@end diff --git a/WebCore/platform/mac/WebCoreKeyGenerator.m b/WebCore/platform/mac/WebCoreKeyGenerator.m new file mode 100644 index 0000000..c1004a7 --- /dev/null +++ b/WebCore/platform/mac/WebCoreKeyGenerator.m @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2003 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. + */ + +#import "config.h" +#import "WebCoreKeyGenerator.h" + +#import <wtf/Assertions.h> + +static WebCoreKeyGenerator *sharedGenerator; + +@implementation WebCoreKeyGenerator + ++ (WebCoreKeyGenerator *)sharedGenerator +{ + return sharedGenerator; +} + +- init +{ + ASSERT(!sharedGenerator); + [super init]; + sharedGenerator = [self retain]; + return self; +} + +- (NSArray *)strengthMenuItemTitles +{ + return nil; +} + +- (NSString *)signedPublicKeyAndChallengeStringWithStrengthIndex:(unsigned)index challenge:(NSString *)challenge pageURL:(NSURL *)pageURL +{ + return nil; +} + +@end diff --git a/WebCore/platform/mac/WebCoreNSStringExtras.h b/WebCore/platform/mac/WebCoreNSStringExtras.h new file mode 100644 index 0000000..95d2031 --- /dev/null +++ b/WebCore/platform/mac/WebCoreNSStringExtras.h @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2005, 2007 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. + * 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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 <Cocoa/Cocoa.h> + +#ifdef __cplusplus +extern "C" { +#endif + +BOOL hasCaseInsensitiveSuffix(NSString *string, NSString *suffix); +BOOL hasCaseInsensitiveSubstring(NSString *string, NSString *substring); +NSString *filenameByFixingIllegalCharacters(NSString *string); + +#ifdef __cplusplus +} +#endif diff --git a/WebCore/platform/mac/WebCoreNSStringExtras.mm b/WebCore/platform/mac/WebCoreNSStringExtras.mm new file mode 100644 index 0000000..a2b0a28 --- /dev/null +++ b/WebCore/platform/mac/WebCoreNSStringExtras.mm @@ -0,0 +1,62 @@ +/* + * Copyright (C) 2005, 2007 Apple 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. + * 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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 "WebCoreNSStringExtras.h" + +BOOL hasCaseInsensitiveSuffix(NSString *string, NSString *suffix) +{ + return [string rangeOfString:suffix options:(NSCaseInsensitiveSearch | NSBackwardsSearch | NSAnchoredSearch)].location != NSNotFound; +} + +BOOL hasCaseInsensitiveSubstring(NSString *string, NSString *substring) +{ + return [string rangeOfString:substring options:NSCaseInsensitiveSearch].location != NSNotFound; +} + +NSString *filenameByFixingIllegalCharacters(NSString *string) +{ + NSMutableString *filename = [[string mutableCopy] autorelease]; + + // Strip null characters. + unichar nullChar = 0; + [filename replaceOccurrencesOfString:[NSString stringWithCharacters:&nullChar length:0] withString:@"" options:0 range:NSMakeRange(0, [filename length])]; + + // Replace "/" with "-". + [filename replaceOccurrencesOfString:@"/" withString:@"-" options:0 range:NSMakeRange(0, [filename length])]; + + // Replace ":" with "-". + [filename replaceOccurrencesOfString:@":" withString:@"-" options:0 range:NSMakeRange(0, [filename length])]; + + // Strip leading dots. + while ([filename hasPrefix:@"."]) { + [filename deleteCharactersInRange:NSMakeRange(0,1)]; + } + + return filename; +} diff --git a/WebCore/platform/mac/WebCoreObjCExtras.c b/WebCore/platform/mac/WebCoreObjCExtras.c new file mode 100644 index 0000000..cac1116 --- /dev/null +++ b/WebCore/platform/mac/WebCoreObjCExtras.c @@ -0,0 +1,38 @@ +/* + * Copyright (C) 2007 Apple 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. + * 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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 "WebCoreObjCExtras.h" + +#include <objc/objc-auto.h> + +void WebCoreObjCFinalizeOnMainThread(Class cls) +{ +#if !defined(BUILDING_ON_TIGER) && !defined(DONT_FINALIZE_ON_MAIN_THREAD) + objc_finalizeOnMainThread(cls); +#endif +} diff --git a/WebCore/platform/mac/WebCoreObjCExtras.h b/WebCore/platform/mac/WebCoreObjCExtras.h new file mode 100644 index 0000000..a30702e --- /dev/null +++ b/WebCore/platform/mac/WebCoreObjCExtras.h @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2007 Apple 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. + * 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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 <objc/objc.h> + +#ifdef __cplusplus +extern "C" { +#endif + +void WebCoreObjCFinalizeOnMainThread(Class cls); + +#ifdef __cplusplus +} +#endif diff --git a/WebCore/platform/mac/WebCoreSystemInterface.h b/WebCore/platform/mac/WebCoreSystemInterface.h new file mode 100644 index 0000000..873d3bf --- /dev/null +++ b/WebCore/platform/mac/WebCoreSystemInterface.h @@ -0,0 +1,148 @@ +/* + * Copyright 2006, 2007, 2008 Apple 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. + */ + +#ifndef WebCoreSystemInterface_h +#define WebCoreSystemInterface_h + +#include <ApplicationServices/ApplicationServices.h> +#include <objc/objc.h> + +typedef struct _NSRange NSRange; + +#ifdef NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES +typedef struct CGPoint NSPoint; +typedef struct CGRect NSRect; +#else +typedef struct _NSPoint NSPoint; +typedef struct _NSRect NSRect; +#endif + +#ifdef __OBJC__ +@class NSData; +@class NSEvent; +@class NSFont; +@class NSMutableURLRequest; +@class NSURLRequest; +@class QTMovie; +@class QTMovieView; +#else +typedef struct NSArray NSArray; +typedef struct NSData NSData; +typedef struct NSDate NSDate; +typedef struct NSEvent NSEvent; +typedef struct NSFont NSFont; +typedef struct NSImage NSImage; +typedef struct NSMenu NSMenu; +typedef struct NSMutableURLRequest NSMutableURLRequest; +typedef struct NSURLRequest NSURLRequest; +typedef struct NSString NSString; +typedef struct NSTextFieldCell NSTextFieldCell; +typedef struct NSURLConnection NSURLConnection; +typedef struct NSURLResponse NSURLResponse; +typedef struct NSView NSView; +typedef struct objc_object *id; +typedef struct QTMovie QTMovie; +typedef struct QTMovieView QTMovieView; +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#define GLYPH_VECTOR_SIZE (50 * 32) + +// In alphabetical order. + +extern BOOL (*wkCGContextGetShouldSmoothFonts)(CGContextRef); +extern void (*wkClearGlyphVector)(void* glyphs); +extern CFReadStreamRef (*wkCreateCustomCFReadStream)(void *(*formCreate)(CFReadStreamRef, void *), + void (*formFinalize)(CFReadStreamRef, void *), + Boolean (*formOpen)(CFReadStreamRef, CFStreamError *, Boolean *, void *), + CFIndex (*formRead)(CFReadStreamRef, UInt8 *, CFIndex, CFStreamError *, Boolean *, void *), + Boolean (*formCanRead)(CFReadStreamRef, void *), + void (*formClose)(CFReadStreamRef, void *), + void (*formSchedule)(CFReadStreamRef, CFRunLoopRef, CFStringRef, void *), + void (*formUnschedule)(CFReadStreamRef, CFRunLoopRef, CFStringRef, void *), + void *context); +extern OSStatus (*wkConvertCharToGlyphs)(void* styleGroup, const UniChar*, unsigned numCharacters, void* glyphs); +extern id (*wkCreateNSURLConnectionDelegateProxy)(void); +extern void (*wkDrawBezeledTextFieldCell)(NSRect, BOOL enabled); +extern void (*wkDrawTextFieldCellFocusRing)(NSTextFieldCell*, NSRect); +extern void (*wkDrawCapsLockIndicator)(CGContextRef, CGRect); +extern void (*wkDrawBezeledTextArea)(NSRect, BOOL enabled); +extern void (*wkDrawFocusRing)(CGContextRef, CGColorRef, int radius); +extern BOOL (*wkFontSmoothingModeIsLCD)(int mode); +extern OSStatus (*wkGetATSStyleGroup)(ATSUStyle, void** styleGroup); +extern CGFontRef (*wkGetCGFontFromNSFont)(NSFont*); +extern NSFont* (*wkGetFontInLanguageForRange)(NSFont*, NSString*, NSRange); +extern NSFont* (*wkGetFontInLanguageForCharacter)(NSFont*, UniChar); +extern BOOL (*wkGetGlyphTransformedAdvances)(CGFontRef, NSFont*, CGAffineTransform*, ATSGlyphRef*, CGSize* advance); +extern ATSLayoutRecord* (*wkGetGlyphVectorFirstRecord)(void* glyphVector); +extern int (*wkGetGlyphVectorNumGlyphs)(void* glyphVector); +extern size_t (*wkGetGlyphVectorRecordSize)(void* glyphVector); +extern void (*wkDrawMediaFullscreenButton)(CGContextRef context, CGRect rect, BOOL active); +extern void (*wkDrawMediaMuteButton)(CGContextRef context, CGRect rect, BOOL active); +extern void (*wkDrawMediaPauseButton)(CGContextRef context, CGRect rect, BOOL active); +extern void (*wkDrawMediaPlayButton)(CGContextRef context, CGRect rect, BOOL active); +extern void (*wkDrawMediaSeekBackButton)(CGContextRef context, CGRect rect, BOOL active); +extern void (*wkDrawMediaSeekForwardButton)(CGContextRef context, CGRect rect, BOOL active); +extern void (*wkDrawMediaSliderTrack)(CGContextRef context, CGRect rect, float percentLoaded); +extern void (*wkDrawMediaSliderThumb)(CGContextRef context, CGRect rect, BOOL active); +extern void (*wkDrawMediaUnMuteButton)(CGContextRef context, CGRect rect, BOOL active); +extern NSString* (*wkGetPreferredExtensionForMIMEType)(NSString*); +extern NSArray* (*wkGetExtensionsForMIMEType)(NSString*); +extern NSString* (*wkGetMIMETypeForExtension)(NSString*); +extern ATSUFontID (*wkGetNSFontATSUFontId)(NSFont*); +extern double (*wkGetNSURLResponseCalculatedExpiration)(NSURLResponse *response); +extern NSDate *(*wkGetNSURLResponseLastModifiedDate)(NSURLResponse *response); +extern BOOL (*wkGetNSURLResponseMustRevalidate)(NSURLResponse *response); +extern void (*wkGetWheelEventDeltas)(NSEvent*, float* deltaX, float* deltaY, BOOL* continuous); +extern OSStatus (*wkInitializeGlyphVector)(int count, void* glyphs); +extern void (*wkPopupMenu)(NSMenu*, NSPoint location, float width, NSView*, int selectedItem, NSFont*); +extern int (*wkQTMovieDataRate)(QTMovie*); +extern float (*wkQTMovieMaxTimeLoaded)(QTMovie*); +extern void (*wkQTMovieViewSetDrawSynchronously)(QTMovieView*, BOOL); +extern void (*wkReleaseStyleGroup)(void* group); +extern void (*wkSetCGFontRenderingMode)(CGContextRef, NSFont*); +extern void (*wkSetDragImage)(NSImage*, NSPoint offset); +extern void (*wkSetNSURLConnectionDefersCallbacks)(NSURLConnection *, BOOL); +extern void (*wkSetNSURLRequestShouldContentSniff)(NSMutableURLRequest *, BOOL); +extern void (*wkSetPatternBaseCTM)(CGContextRef, CGAffineTransform); +extern void (*wkSetPatternPhaseInUserSpace)(CGContextRef, CGPoint); +extern void (*wkSetUpFontCache)(size_t); +extern void (*wkSignalCFReadStreamEnd)(CFReadStreamRef stream); +extern void (*wkSignalCFReadStreamError)(CFReadStreamRef stream, CFStreamError *error); +extern void (*wkSignalCFReadStreamHasBytes)(CFReadStreamRef stream); + +#ifdef BUILDING_ON_TIGER +extern void (*wkGetFontMetrics)(CGFontRef, int* ascent, int* descent, int* lineGap, unsigned* unitsPerEm); +extern BOOL (*wkSupportsMultipartXMixedReplace)(NSMutableURLRequest *); +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/WebCore/platform/mac/WebCoreSystemInterface.mm b/WebCore/platform/mac/WebCoreSystemInterface.mm new file mode 100644 index 0000000..6fea621 --- /dev/null +++ b/WebCore/platform/mac/WebCoreSystemInterface.mm @@ -0,0 +1,95 @@ +/* + * Copyright 2006, 2007, 2008 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. + */ + +#import "config.h" +#import "WebCoreSystemInterface.h" + +BOOL (*wkCGContextGetShouldSmoothFonts)(CGContextRef); +void (*wkClearGlyphVector)(void* glyphs); +OSStatus (*wkConvertCharToGlyphs)(void* styleGroup, const UniChar*, unsigned numCharacters, void* glyphs); +NSString* (*wkCreateURLPasteboardFlavorTypeName)(void); +NSString* (*wkCreateURLNPasteboardFlavorTypeName)(void); +void (*wkDrawBezeledTextFieldCell)(NSRect, BOOL enabled); +void (*wkDrawTextFieldCellFocusRing)(NSTextFieldCell*, NSRect); +void (*wkDrawCapsLockIndicator)(CGContextRef, CGRect); +void (*wkDrawBezeledTextArea)(NSRect, BOOL enabled); +void (*wkDrawFocusRing)(CGContextRef, CGColorRef, int radius); +BOOL (*wkFontSmoothingModeIsLCD)(int mode); +OSStatus (*wkGetATSStyleGroup)(ATSUStyle, void** styleGroup); +CGFontRef (*wkGetCGFontFromNSFont)(NSFont*); +NSFont* (*wkGetFontInLanguageForRange)(NSFont*, NSString*, NSRange); +NSFont* (*wkGetFontInLanguageForCharacter)(NSFont*, UniChar); +BOOL (*wkGetGlyphTransformedAdvances)(CGFontRef, NSFont*, CGAffineTransform*, ATSGlyphRef*, CGSize* advance); +ATSLayoutRecord* (*wkGetGlyphVectorFirstRecord)(void* glyphVector); +int (*wkGetGlyphVectorNumGlyphs)(void* glyphVector); +size_t (*wkGetGlyphVectorRecordSize)(void* glyphVector); +void (*wkDrawMediaFullscreenButton)(CGContextRef context, CGRect rect, BOOL active); +void (*wkDrawMediaMuteButton)(CGContextRef context, CGRect rect, BOOL active); +void (*wkDrawMediaPauseButton)(CGContextRef context, CGRect rect, BOOL active); +void (*wkDrawMediaPlayButton)(CGContextRef context, CGRect rect, BOOL active); +void (*wkDrawMediaSeekBackButton)(CGContextRef context, CGRect rect, BOOL active); +void (*wkDrawMediaSeekForwardButton)(CGContextRef context, CGRect rect, BOOL active); +void (*wkDrawMediaSliderTrack)(CGContextRef context, CGRect rect, float percentLoaded); +void (*wkDrawMediaSliderThumb)(CGContextRef context, CGRect rect, BOOL active); +void (*wkDrawMediaUnMuteButton)(CGContextRef context, CGRect rect, BOOL active); +NSString* (*wkGetPreferredExtensionForMIMEType)(NSString*); +NSArray* (*wkGetExtensionsForMIMEType)(NSString*); +NSString* (*wkGetMIMETypeForExtension)(NSString*); +ATSUFontID (*wkGetNSFontATSUFontId)(NSFont*); +NSTimeInterval (*wkGetNSURLResponseCalculatedExpiration)(NSURLResponse *response); +NSDate *(*wkGetNSURLResponseLastModifiedDate)(NSURLResponse *response); +BOOL (*wkGetNSURLResponseMustRevalidate)(NSURLResponse *response); +void (*wkGetWheelEventDeltas)(NSEvent*, float* deltaX, float* deltaY, BOOL* continuous); +OSStatus (*wkInitializeGlyphVector)(int count, void* glyphs); +void (*wkPopupMenu)(NSMenu*, NSPoint location, float width, NSView*, int selectedItem, NSFont*); +int (*wkQTMovieDataRate)(QTMovie*); +float (*wkQTMovieMaxTimeLoaded)(QTMovie*); +void (*wkQTMovieViewSetDrawSynchronously)(QTMovieView*, BOOL); +void (*wkReleaseStyleGroup)(void* group); +void (*wkSetCGFontRenderingMode)(CGContextRef, NSFont*); +void (*wkSetDragImage)(NSImage*, NSPoint offset); +void (*wkSetPatternBaseCTM)(CGContextRef, CGAffineTransform); +void (*wkSetPatternPhaseInUserSpace)(CGContextRef, CGPoint point); +void (*wkSetUpFontCache)(size_t); +void (*wkSignalCFReadStreamEnd)(CFReadStreamRef stream); +void (*wkSignalCFReadStreamHasBytes)(CFReadStreamRef stream); +void (*wkSignalCFReadStreamError)(CFReadStreamRef stream, CFStreamError *error); +CFReadStreamRef (*wkCreateCustomCFReadStream)(void *(*formCreate)(CFReadStreamRef, void *), + void (*formFinalize)(CFReadStreamRef, void *), + Boolean (*formOpen)(CFReadStreamRef, CFStreamError *, Boolean *, void *), + CFIndex (*formRead)(CFReadStreamRef, UInt8 *, CFIndex, CFStreamError *, Boolean *, void *), + Boolean (*formCanRead)(CFReadStreamRef, void *), + void (*formClose)(CFReadStreamRef, void *), + void (*formSchedule)(CFReadStreamRef, CFRunLoopRef, CFStringRef, void *), + void (*formUnschedule)(CFReadStreamRef, CFRunLoopRef, CFStringRef, void *), + void *context); +void (*wkSetNSURLConnectionDefersCallbacks)(NSURLConnection *, BOOL); +void (*wkSetNSURLRequestShouldContentSniff)(NSMutableURLRequest *, BOOL); +id (*wkCreateNSURLConnectionDelegateProxy)(void); + +#ifdef BUILDING_ON_TIGER +void (*wkGetFontMetrics)(CGFontRef, int* ascent, int* descent, int* lineGap, unsigned* unitsPerEm); +BOOL (*wkSupportsMultipartXMixedReplace)(NSMutableURLRequest *); +#endif diff --git a/WebCore/platform/mac/WebCoreTextRenderer.h b/WebCore/platform/mac/WebCoreTextRenderer.h new file mode 100644 index 0000000..dc1de8c --- /dev/null +++ b/WebCore/platform/mac/WebCoreTextRenderer.h @@ -0,0 +1,39 @@ +/* + * 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. + */ + +#ifdef __cplusplus +extern "C" { +#endif + +extern void WebCoreDrawTextAtPoint(const UniChar*, unsigned length, NSPoint, NSFont*, NSColor*); +extern float WebCoreTextFloatWidth(const UniChar*, unsigned length, NSFont*); +extern void WebCoreSetShouldUseFontSmoothing(bool); +extern bool WebCoreShouldUseFontSmoothing(); +extern void WebCoreSetAlwaysUseATSU(bool); +extern NSFont* WebCoreFindFont(NSString* familyName, NSFontTraitMask, int size); + +#ifdef __cplusplus +} +#endif diff --git a/WebCore/platform/mac/WebCoreTextRenderer.mm b/WebCore/platform/mac/WebCoreTextRenderer.mm new file mode 100644 index 0000000..51ddf8e --- /dev/null +++ b/WebCore/platform/mac/WebCoreTextRenderer.mm @@ -0,0 +1,88 @@ +/* + * 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. + */ + +#import "config.h" +#import "WebCoreTextRenderer.h" + +#import "Font.h" +#import "SimpleFontData.h" +#import "GraphicsContext.h" +#import "IntPoint.h" +#import "WebFontCache.h" + +using namespace WebCore; + +void WebCoreDrawTextAtPoint(const UniChar* buffer, unsigned length, NSPoint point, NSFont* font, NSColor* textColor) +{ + NSGraphicsContext *nsContext = [NSGraphicsContext currentContext]; + CGContextRef cgContext = (CGContextRef)[nsContext graphicsPort]; + GraphicsContext graphicsContext(cgContext); + // Safari doesn't flip the NSGraphicsContext before calling WebKit, yet WebCore requires a flipped graphics context. + BOOL flipped = [nsContext isFlipped]; + if (!flipped) + CGContextScaleCTM(cgContext, 1.0f, -1.0f); + + FontPlatformData f(font); + Font renderer(f, ![[NSGraphicsContext currentContext] isDrawingToScreen]); + TextRun run(buffer, length); + run.disableRoundingHacks(); + CGFloat red, green, blue, alpha; + [[textColor colorUsingColorSpaceName:NSDeviceRGBColorSpace] getRed:&red green:&green blue:&blue alpha:&alpha]; + graphicsContext.setFillColor(makeRGBA((int)(red * 255), (int)(green * 255), (int)(blue * 255), (int)(alpha * 255))); + renderer.drawText(&graphicsContext, run, FloatPoint(point.x, (flipped ? point.y : (-1.0f * point.y)))); + if (!flipped) + CGContextScaleCTM(cgContext, 1.0f, -1.0f); +} + +float WebCoreTextFloatWidth(const UniChar* buffer, unsigned length , NSFont* font) +{ + FontPlatformData f(font); + Font renderer(f, ![[NSGraphicsContext currentContext] isDrawingToScreen]); + TextRun run(buffer, length); + run.disableRoundingHacks(); + return renderer.floatWidth(run); +} + +static bool gShouldUseFontSmoothing = true; + +void WebCoreSetShouldUseFontSmoothing(bool smooth) +{ + gShouldUseFontSmoothing = smooth; +} + +bool WebCoreShouldUseFontSmoothing() +{ + return gShouldUseFontSmoothing; +} + +void WebCoreSetAlwaysUseATSU(bool useATSU) +{ + Font::setCodePath(useATSU ? Font::Complex : Font::Auto); +} + +NSFont* WebCoreFindFont(NSString* familyName, NSFontTraitMask traits, int size) +{ + return [WebFontCache fontWithFamily:familyName traits:traits size:size]; +} diff --git a/WebCore/platform/mac/WebCoreView.h b/WebCore/platform/mac/WebCoreView.h new file mode 100644 index 0000000..15d5b13 --- /dev/null +++ b/WebCore/platform/mac/WebCoreView.h @@ -0,0 +1,28 @@ +/* + * Copyright (C) 2003 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. + */ + +@interface NSView (WebCoreView) +- (NSView *)_webcore_effectiveFirstResponder; +@end diff --git a/WebCore/platform/mac/WebCoreView.m b/WebCore/platform/mac/WebCoreView.m new file mode 100644 index 0000000..e2f11fa --- /dev/null +++ b/WebCore/platform/mac/WebCoreView.m @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2003 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. + */ + +#import "config.h" +#import "WebCoreView.h" + +@interface NSClipView (WebCoreView) +- (NSView *)_webcore_effectiveFirstResponder; +@end + +@interface NSScrollView (WebCoreView) +- (NSView *)_webcore_effectiveFirstResponder; +@end + +@implementation NSView (WebCoreView) + +- (NSView *)_webcore_effectiveFirstResponder +{ + return self; +} + +@end + +@implementation NSClipView (WebCoreView) + +- (NSView *)_webcore_effectiveFirstResponder +{ + NSView *view = [self documentView]; + return view ? [view _webcore_effectiveFirstResponder] : [super _webcore_effectiveFirstResponder]; +} + +@end + +@implementation NSScrollView (WebCoreView) + +- (NSView *)_webcore_effectiveFirstResponder +{ + NSView *view = [self contentView]; + return view ? [view _webcore_effectiveFirstResponder] : [super _webcore_effectiveFirstResponder]; +} + +@end + diff --git a/WebCore/platform/mac/WebFontCache.h b/WebCore/platform/mac/WebFontCache.h new file mode 100644 index 0000000..b45cff3 --- /dev/null +++ b/WebCore/platform/mac/WebFontCache.h @@ -0,0 +1,29 @@ +/* + * 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. + */ + +// This interface exists so that third party products (like Silk) can patch in to an Obj-C method to manipulate WebKit's font caching/substitution. +@interface WebFontCache : NSObject ++ (NSFont *)fontWithFamily:(NSString *)desiredFamily traits:(NSFontTraitMask)desiredTraits size:(float)size; +@end diff --git a/WebCore/platform/mac/WebFontCache.mm b/WebCore/platform/mac/WebFontCache.mm new file mode 100644 index 0000000..1fcceb5 --- /dev/null +++ b/WebCore/platform/mac/WebFontCache.mm @@ -0,0 +1,233 @@ +/* + * Copyright (C) 2006, 2007 Apple 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. + * 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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 "WebFontCache.h" + +#import <math.h> + +#define SYNTHESIZED_FONT_TRAITS (NSBoldFontMask | NSItalicFontMask) + +#define IMPORTANT_FONT_TRAITS (0 \ + | NSBoldFontMask \ + | NSCompressedFontMask \ + | NSCondensedFontMask \ + | NSExpandedFontMask \ + | NSItalicFontMask \ + | NSNarrowFontMask \ + | NSPosterFontMask \ + | NSSmallCapsFontMask \ +) + +#define DESIRED_WEIGHT 5 + +static BOOL acceptableChoice(NSFontTraitMask desiredTraits, int desiredWeight, + NSFontTraitMask candidateTraits, int candidateWeight) +{ + desiredTraits &= ~SYNTHESIZED_FONT_TRAITS; + return (candidateTraits & desiredTraits) == desiredTraits; +} + +static BOOL betterChoice(NSFontTraitMask desiredTraits, int desiredWeight, + NSFontTraitMask chosenTraits, int chosenWeight, + NSFontTraitMask candidateTraits, int candidateWeight) +{ + if (!acceptableChoice(desiredTraits, desiredWeight, candidateTraits, candidateWeight)) { + return NO; + } + + // A list of the traits we care about. + // The top item in the list is the worst trait to mismatch; if a font has this + // and we didn't ask for it, we'd prefer any other font in the family. + const NSFontTraitMask masks[] = { + NSPosterFontMask, + NSSmallCapsFontMask, + NSItalicFontMask, + NSCompressedFontMask, + NSCondensedFontMask, + NSExpandedFontMask, + NSNarrowFontMask, + NSBoldFontMask, + 0 }; + int i = 0; + NSFontTraitMask mask; + while ((mask = masks[i++])) { + BOOL desired = (desiredTraits & mask) != 0; + BOOL chosenHasUnwantedTrait = desired != ((chosenTraits & mask) != 0); + BOOL candidateHasUnwantedTrait = desired != ((candidateTraits & mask) != 0); + if (!candidateHasUnwantedTrait && chosenHasUnwantedTrait) + return YES; + if (!chosenHasUnwantedTrait && candidateHasUnwantedTrait) + return NO; + } + + int chosenWeightDelta = chosenWeight - desiredWeight; + int candidateWeightDelta = candidateWeight - desiredWeight; + + int chosenWeightDeltaMagnitude = abs(chosenWeightDelta); + int candidateWeightDeltaMagnitude = abs(candidateWeightDelta); + + // Smaller magnitude wins. + // If both have same magnitude, tie breaker is that the smaller weight wins. + // Otherwise, first font in the array wins (should almost never happen). + if (candidateWeightDeltaMagnitude < chosenWeightDeltaMagnitude) { + return YES; + } + if (candidateWeightDeltaMagnitude == chosenWeightDeltaMagnitude && candidateWeight < chosenWeight) { + return YES; + } + + return NO; +} + +@implementation WebFontCache + +// Family name is somewhat of a misnomer here. We first attempt to find an exact match +// comparing the desiredFamily to the PostScript name of the installed fonts. If that fails +// we then do a search based on the family names of the installed fonts. ++ (NSFont *)internalFontWithFamily:(NSString *)desiredFamily traits:(NSFontTraitMask)desiredTraits size:(float)size +{ + NSFontManager *fontManager = [NSFontManager sharedFontManager]; + + // Look for an exact match first. + NSEnumerator *availableFonts = [[fontManager availableFonts] objectEnumerator]; + NSString *availableFont; + NSFont *nameMatchedFont = nil; + while ((availableFont = [availableFonts nextObject])) { + if ([desiredFamily caseInsensitiveCompare:availableFont] == NSOrderedSame) { + nameMatchedFont = [NSFont fontWithName:availableFont size:size]; + + // Special case Osaka-Mono. According to <rdar://problem/3999467>, we need to + // treat Osaka-Mono as fixed pitch. + if ([desiredFamily caseInsensitiveCompare:@"Osaka-Mono"] == NSOrderedSame && desiredTraits == 0) + return nameMatchedFont; + + NSFontTraitMask traits = [fontManager traitsOfFont:nameMatchedFont]; + if ((traits & desiredTraits) == desiredTraits) + return [fontManager convertFont:nameMatchedFont toHaveTrait:desiredTraits]; + break; + } + } + + // Do a simple case insensitive search for a matching font family. + // NSFontManager requires exact name matches. + // This addresses the problem of matching arial to Arial, etc., but perhaps not all the issues. + NSEnumerator *e = [[fontManager availableFontFamilies] objectEnumerator]; + NSString *availableFamily; + while ((availableFamily = [e nextObject])) { + if ([desiredFamily caseInsensitiveCompare:availableFamily] == NSOrderedSame) + break; + } + + if (!availableFamily) + availableFamily = [nameMatchedFont familyName]; + + // Found a family, now figure out what weight and traits to use. + BOOL choseFont = false; + int chosenWeight = 0; + NSFontTraitMask chosenTraits = 0; + + NSArray *fonts = [fontManager availableMembersOfFontFamily:availableFamily]; + unsigned n = [fonts count]; + unsigned i; + for (i = 0; i < n; i++) { + NSArray *fontInfo = [fonts objectAtIndex:i]; + + // Array indices must be hard coded because of lame AppKit API. + int fontWeight = [[fontInfo objectAtIndex:2] intValue]; + NSFontTraitMask fontTraits = [[fontInfo objectAtIndex:3] unsignedIntValue]; + + BOOL newWinner; + if (!choseFont) + newWinner = acceptableChoice(desiredTraits, DESIRED_WEIGHT, fontTraits, fontWeight); + else + newWinner = betterChoice(desiredTraits, DESIRED_WEIGHT, chosenTraits, chosenWeight, fontTraits, fontWeight); + + if (newWinner) { + choseFont = YES; + chosenWeight = fontWeight; + chosenTraits = fontTraits; + + if (chosenWeight == DESIRED_WEIGHT && (chosenTraits & IMPORTANT_FONT_TRAITS) == (desiredTraits & IMPORTANT_FONT_TRAITS)) + break; + } + } + + if (!choseFont) + return nil; + + NSFont *font = [fontManager fontWithFamily:availableFamily traits:chosenTraits weight:chosenWeight size:size]; + + if (!font) + return nil; + + NSFontTraitMask actualTraits = 0; + if (desiredTraits & (NSItalicFontMask | NSBoldFontMask)) + actualTraits = [[NSFontManager sharedFontManager] traitsOfFont:font]; + + bool syntheticBold = (desiredTraits & NSBoldFontMask) && !(actualTraits & NSBoldFontMask); + bool syntheticOblique = (desiredTraits & NSItalicFontMask) && !(actualTraits & NSItalicFontMask); + + // There are some malformed fonts that will be correctly returned by -fontWithFamily:traits:weight:size: as a match for a particular trait, + // though -[NSFontManager traitsOfFont:] incorrectly claims the font does not have the specified trait. This could result in applying + // synthetic bold on top of an already-bold font, as reported in <http://bugs.webkit.org/show_bug.cgi?id=6146>. To work around this + // problem, if we got an apparent exact match, but the requested traits aren't present in the matched font, we'll try to get a font from + // the same family without those traits (to apply the synthetic traits to later). + NSFontTraitMask nonSyntheticTraits = desiredTraits; + + if (syntheticBold) + nonSyntheticTraits &= ~NSBoldFontMask; + + if (syntheticOblique) + nonSyntheticTraits &= ~NSItalicFontMask; + + if (nonSyntheticTraits != desiredTraits) { + NSFont *fontWithoutSyntheticTraits = [fontManager fontWithFamily:availableFamily traits:nonSyntheticTraits weight:chosenWeight size:size]; + if (fontWithoutSyntheticTraits) + font = fontWithoutSyntheticTraits; + } + + return font; +} + ++ (NSFont *)fontWithFamily:(NSString *)desiredFamily traits:(NSFontTraitMask)desiredTraits size:(float)size +{ +#ifndef BUILDING_ON_TIGER + NSFont *font = [self internalFontWithFamily:desiredFamily traits:desiredTraits size:size]; + if (font) + return font; + + // Auto activate the font before looking for it a second time. + // Ignore the result because we want to use our own algorithm to actually find the font. + [NSFont fontWithName:desiredFamily size:size]; +#endif + + return [self internalFontWithFamily:desiredFamily traits:desiredTraits size:size]; +} + +@end diff --git a/WebCore/platform/mac/WheelEventMac.mm b/WebCore/platform/mac/WheelEventMac.mm new file mode 100644 index 0000000..558bc5f --- /dev/null +++ b/WebCore/platform/mac/WheelEventMac.mm @@ -0,0 +1,50 @@ +/* + * Copyright (C) 2004, 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. + */ + +#import "config.h" +#import "PlatformWheelEvent.h" + +#import "PlatformMouseEvent.h" +#import "WebCoreSystemInterface.h" + +namespace WebCore { + +PlatformWheelEvent::PlatformWheelEvent(NSEvent* event) + : m_position(pointForEvent(event)) + , m_globalPosition(globalPointForEvent(event)) + , m_deltaX([event deltaX]) + , m_deltaY([event deltaY]) + , m_isAccepted(false) + , m_shiftKey([event modifierFlags] & NSShiftKeyMask) + , m_ctrlKey([event modifierFlags] & NSControlKeyMask) + , m_altKey([event modifierFlags] & NSAlternateKeyMask) + , m_metaKey([event modifierFlags] & NSCommandKeyMask) +{ + BOOL continuous; + wkGetWheelEventDeltas(event, &m_continuousDeltaX, &m_continuousDeltaY, &continuous); + m_isContinuous = continuous; +} + +} // namespace WebCore diff --git a/WebCore/platform/mac/WidgetMac.mm b/WebCore/platform/mac/WidgetMac.mm new file mode 100644 index 0000000..533f721 --- /dev/null +++ b/WebCore/platform/mac/WidgetMac.mm @@ -0,0 +1,321 @@ +/* + * Copyright (C) 2004, 2005, 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. + */ + +#import "config.h" +#import "Widget.h" + +#import "BlockExceptions.h" +#import "Cursor.h" +#import "Document.h" +#import "Font.h" +#import "Frame.h" +#import "GraphicsContext.h" +#import "Page.h" +#import "PlatformMouseEvent.h" +#import "WebCoreFrameBridge.h" +#import "WebCoreFrameView.h" +#import "WebCoreView.h" +#import "WidgetClient.h" + +#import <wtf/RetainPtr.h> + +@interface NSWindow (WindowPrivate) +- (BOOL) _needsToResetDragMargins; +- (void) _setNeedsToResetDragMargins:(BOOL)s; +@end + +namespace WebCore { + +class WidgetPrivate { +public: + RetainPtr<NSView> view; + WidgetClient* client; + bool visible; + bool mustStayInWindow; + bool removeFromSuperviewSoon; +}; + +static void safeRemoveFromSuperview(NSView *view) +{ + // If the the view is the first responder, then set the window's first responder to nil so + // we don't leave the window pointing to a view that's no longer in it. + NSWindow *window = [view window]; + NSResponder *firstResponder = [window firstResponder]; + if ([firstResponder isKindOfClass:[NSView class]] && [(NSView *)firstResponder isDescendantOf:view]) + [window makeFirstResponder:nil]; + + // Suppress the resetting of drag margins since we know we can't affect them. + BOOL resetDragMargins = [window _needsToResetDragMargins]; + [window _setNeedsToResetDragMargins:NO]; + [view removeFromSuperview]; + [window _setNeedsToResetDragMargins:resetDragMargins]; +} + +Widget::Widget() : data(new WidgetPrivate) +{ + data->view = nil; + data->client = 0; + data->visible = true; + data->mustStayInWindow = false; + data->removeFromSuperviewSoon = false; +} + +Widget::Widget(NSView* view) : data(new WidgetPrivate) +{ + data->view = view; + data->client = 0; + data->visible = true; + data->mustStayInWindow = false; + data->removeFromSuperviewSoon = false; +} + +Widget::~Widget() +{ + delete data; +} + +void Widget::setEnabled(bool enabled) +{ + id view = data->view.get(); + BEGIN_BLOCK_OBJC_EXCEPTIONS; + if ([view respondsToSelector:@selector(setEnabled:)]) { + [view setEnabled:enabled]; + } + END_BLOCK_OBJC_EXCEPTIONS; +} + +bool Widget::isEnabled() const +{ + id view = data->view.get(); + + BEGIN_BLOCK_OBJC_EXCEPTIONS; + if ([view respondsToSelector:@selector(isEnabled)]) { + return [view isEnabled]; + } + END_BLOCK_OBJC_EXCEPTIONS; + + return true; +} + +IntRect Widget::frameGeometry() const +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + return enclosingIntRect([getOuterView() frame]); + END_BLOCK_OBJC_EXCEPTIONS; + return IntRect(); +} + +// FIXME: Should move this to Chrome; bad layering that this knows about Frame. +void Widget::setFocus() +{ + Frame* frame = Frame::frameForWidget(this); + if (!frame) + return; + + BEGIN_BLOCK_OBJC_EXCEPTIONS; + + NSView *view = [getView() _webcore_effectiveFirstResponder]; + if (Page* page = frame->page()) + page->chrome()->focusNSView(view); + + END_BLOCK_OBJC_EXCEPTIONS; +} + + void Widget::setCursor(const Cursor& cursor) + { + if ([NSCursor currentCursor] == cursor.impl()) + return; + [cursor.impl() set]; +} + +void Widget::show() +{ + if (!data || data->visible) + return; + + data->visible = true; + + BEGIN_BLOCK_OBJC_EXCEPTIONS; + [getOuterView() setHidden:NO]; + END_BLOCK_OBJC_EXCEPTIONS; +} + +void Widget::hide() +{ + if (!data || !data->visible) + return; + + data->visible = false; + + BEGIN_BLOCK_OBJC_EXCEPTIONS; + [getOuterView() setHidden:YES]; + END_BLOCK_OBJC_EXCEPTIONS; +} + +void Widget::setFrameGeometry(const IntRect &rect) +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + NSView *v = getOuterView(); + NSRect f = rect; + if (!NSEqualRects(f, [v frame])) { + [v setFrame:f]; + [v setNeedsDisplay: NO]; + } + END_BLOCK_OBJC_EXCEPTIONS; +} + +NSView* Widget::getView() const +{ + return data->view.get(); +} + +void Widget::setView(NSView* view) +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + data->view = view; + END_BLOCK_OBJC_EXCEPTIONS; +} + +NSView* Widget::getOuterView() const +{ + // If this widget's view is a WebCoreFrameView the we resize its containing view, a WebFrameView. + + NSView* view = data->view.get(); + if ([view conformsToProtocol:@protocol(WebCoreFrameView)]) { + view = [view superview]; + ASSERT(view); + } + + return view; +} + +void Widget::paint(GraphicsContext* p, const IntRect& r) +{ + if (p->paintingDisabled()) + return; + NSView *view = getOuterView(); + BEGIN_BLOCK_OBJC_EXCEPTIONS; + [view displayRectIgnoringOpacity:[view convertRect:r fromView:[view superview]]]; + END_BLOCK_OBJC_EXCEPTIONS; +} + +void Widget::invalidate() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + [getView() setNeedsDisplay: YES]; + END_BLOCK_OBJC_EXCEPTIONS; +} + +void Widget::invalidateRect(const IntRect& r) +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + [getView() setNeedsDisplayInRect: r]; + END_BLOCK_OBJC_EXCEPTIONS; +} + +// FIXME: Should move this to Chrome; bad layering that this knows about Frame. +void Widget::setIsSelected(bool isSelected) +{ + if (Frame* frame = Frame::frameForWidget(this)) + [frame->bridge() setIsSelected:isSelected forView:getView()]; +} + +void Widget::addToSuperview(NSView *view) +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + + ASSERT(view); + NSView *subview = getOuterView(); + ASSERT(![view isDescendantOf:subview]); + + // Suppress the resetting of drag margins since we know we can't affect them. + NSWindow* window = [view window]; + BOOL resetDragMargins = [window _needsToResetDragMargins]; + [window _setNeedsToResetDragMargins:NO]; + if ([subview superview] != view) + [view addSubview:subview]; + data->removeFromSuperviewSoon = false; + [window _setNeedsToResetDragMargins:resetDragMargins]; + + END_BLOCK_OBJC_EXCEPTIONS; +} + +void Widget::removeFromSuperview() +{ + if (data->mustStayInWindow) + data->removeFromSuperviewSoon = true; + else { + data->removeFromSuperviewSoon = false; + BEGIN_BLOCK_OBJC_EXCEPTIONS; + safeRemoveFromSuperview(getOuterView()); + END_BLOCK_OBJC_EXCEPTIONS; + } +} + +void Widget::beforeMouseDown(NSView *view, Widget* widget) +{ + if (widget) { + ASSERT(view == widget->getOuterView()); + ASSERT(!widget->data->mustStayInWindow); + widget->data->mustStayInWindow = true; + } +} + +void Widget::afterMouseDown(NSView *view, Widget* widget) +{ + if (!widget) { + BEGIN_BLOCK_OBJC_EXCEPTIONS; + safeRemoveFromSuperview(view); + END_BLOCK_OBJC_EXCEPTIONS; + } else { + ASSERT(widget->data->mustStayInWindow); + widget->data->mustStayInWindow = false; + if (widget->data->removeFromSuperviewSoon) + widget->removeFromSuperview(); + } +} + +void Widget::setClient(WidgetClient* c) +{ + data->client = c; +} + +WidgetClient* Widget::client() const +{ + return data->client; +} + +void Widget::removeFromParent() +{ +} + +IntPoint Widget::convertToScreenCoordinate(NSView *view, const IntPoint& point) +{ + NSPoint conversionPoint = { point.x(), point.y() }; + conversionPoint = [view convertPoint:conversionPoint toView:nil]; + return globalPoint(conversionPoint, [view window]); +} + +} |