Merge pull request #3329 from enquora/refactor-remove-nativehost-target

Refactor remove nativehost target and C-style preprocessor usage
This commit is contained in:
David Richardson authored and GitHub committed 2026-10-22 12:55:50 -06:00
commit 66e4d3fef6
80 files changed
+2943 -3122

No files matched your search

+25 -22
View File
@@ -37,6 +37,8 @@
@import "CPWindowController.j"
@import "_CPPopoverWindow.j"
@global CPWindowObjectList
@typedef CPModalSession
var CPMainCibFile = @"CPMainCibFile",
@@ -241,9 +243,10 @@ var CPApplicationDelegate_applicationShouldTerminate_ = 1 << 0,
// At this point we clear the window.status to eliminate Safari's "Cancelled" error message
// The message shouldn't be displayed, because only an XHR is cancelled, but it is a usability issue.
// We do it here so that applications can change it in willFinish or didFinishLaunching
#if PLATFORM(DOM)
window.status = " ";
#endif
if (CPDOMAvailable)
{
window.status = " ";
}
// We also want to set the default cursor on the body, so that buttons and things don't have an iBeam
[[CPCursor arrowCursor] set];
@@ -273,9 +276,10 @@ var CPApplicationDelegate_applicationShouldTerminate_ = 1 << 0,
var needsUntitled = !!_documentController,
URLStrings = nil;
#if PLATFORM(DOM)
URLStrings = window.cpOpeningURLStrings && window.cpOpeningURLStrings();
#endif
if (CPDOMAvailable)
{
URLStrings = window.cpOpeningURLStrings && window.cpOpeningURLStrings();
}
var index = 0,
count = [URLStrings count];
@@ -727,11 +731,10 @@ var CPApplicationDelegate_applicationShouldTerminate_ = 1 << 0,
*/
- (CPArray)orderedWindows
{
#if PLATFORM(DOM)
return CPWindowObjectList();
#else
if (CPDOMAvailable)
return CPWindowObjectList();
return [];
#endif
}
- (void)hide:(id)aSender
@@ -1304,22 +1307,22 @@ _CPRunModalLoop = function(anEvent)
function CPApplicationMain(args, namedArgs)
{
#if PLATFORM(DOM)
// hook to allow recorder, etc to manipulate things before starting AppKit
if (window.parent !== window && typeof window.parent._childAppIsStarting === "function")
if (CPDOMAvailable)
{
try
// hook to allow recorder, etc to manipulate things before starting AppKit
if (window.parent !== window && typeof window.parent._childAppIsStarting === "function")
{
window.parent._childAppIsStarting(window);
}
catch(err)
{
// This could happen if we're in an iframe without access to the parent frame.
CPLog.warn("Failed to call parent frame's _childAppIsStarting().");
try
{
window.parent._childAppIsStarting(window);
}
catch(err)
{
// This could happen if we're in an iframe without access to the parent frame.
CPLog.warn("Failed to call parent frame's _childAppIsStarting().");
}
}
}
#endif
var mainBundle = [CPBundle mainBundle],
principalClass = [mainBundle principalClass];
+4 -7
View File
@@ -563,9 +563,10 @@ var cachedBlackColor,
{
// Fix to avoid a problem when compiling a theme (missing the alpha component as theme compiler doesn't have CSS rgba capability)
var hasAlpha = YES;
#if PLATFORM(DOM)
hasAlpha = CPFeatureIsCompatible(CPCSSRGBAFeature) && _components[3] != 1.0;
#endif
if (CPDOMAvailable)
{
hasAlpha = CPFeatureIsCompatible(CPCSSRGBAFeature) && _components[3] != 1.0;
}
_cssString = (hasAlpha ? "rgba(" : "rgb(") +
parseInt(_components[0] * 255.0) + ", " +
@@ -1001,19 +1002,16 @@ url("data:image/png;base64,BASE64ENCODEDDATA") // if there is a pattern image
+ (void)restorePreviousCSSState:(CPArrayRef)aPreviousStateRef forDOMElement:(DOMElement)aDOMElement
{
#if PLATFORM(DOM)
var aPreviousState = @deref(aPreviousStateRef);
for (var i = 0, count = aPreviousState.length; i < count; i++)
aDOMElement.style[aPreviousState[i][0]] = aPreviousState[i][1];
@deref(aPreviousStateRef) = @[];
#endif
}
- (DOMElement)applyCSSColorForView:(CPView)aView onDOMElement:(DOMElement)aDOMElement styleNode:(DOMElement)aStyleNode previousState:(CPArrayRef)aPreviousStateRef
{
#if PLATFORM(DOM)
var aPreviousState = @deref(aPreviousStateRef);
[_cssDictionary enumerateKeysAndObjectsUsingBlock:function(aKey, anObject, stop)
@@ -1086,7 +1084,6 @@ url("data:image/png;base64,BASE64ENCODEDDATA") // if there is a pattern image
@deref(aPreviousStateRef) = aPreviousState;
return aStyleNode;
#endif
}
@end
+33 -30
View File
@@ -23,6 +23,7 @@
@import <Foundation/CPObject.j>
@import "CPView.j"
@import "CPCompatibility.j"
@class CPSlider
@class CPColorPanel
@@ -235,24 +236,25 @@
{
if (self = [super initWithFrame:aFrame])
{
#if PLATFORM(DOM)
var path = [[CPBundle bundleForClass:CPColorPicker] pathForResource:@"wheel.png"];
if (CPDOMAvailable)
{
var path = [[CPBundle bundleForClass:CPColorPicker] pathForResource:@"wheel.png"];
_wheelImage = new Image();
_wheelImage.src = path;
_wheelImage.style.position = "absolute";
_wheelImage = new Image();
_wheelImage.src = path;
_wheelImage.style.position = "absolute";
path = [[CPBundle bundleForClass:CPColorPicker] pathForResource:@"wheel_black.png"];
path = [[CPBundle bundleForClass:CPColorPicker] pathForResource:@"wheel_black.png"];
_blackWheelImage = new Image();
_blackWheelImage.src = path;
_blackWheelImage.style.opacity = "0";
_blackWheelImage.style.filter = "alpha(opacity=0)";
_blackWheelImage.style.position = "absolute";
_blackWheelImage = new Image();
_blackWheelImage.src = path;
_blackWheelImage.style.opacity = "0";
_blackWheelImage.style.filter = "alpha(opacity=0)";
_blackWheelImage.style.position = "absolute";
_DOMElement.appendChild(_wheelImage);
_DOMElement.appendChild(_blackWheelImage);
#endif
_DOMElement.appendChild(_wheelImage);
_DOMElement.appendChild(_blackWheelImage);
}
[self setWheelSize:aFrame.size];
@@ -272,10 +274,10 @@
- (void)setWheelBrightness:(float)brightness
{
#if PLATFORM(DOM)
if (!CPDOMAvailable) return;
_blackWheelImage.style.opacity = 1.0 - brightness;
_blackWheelImage.style.filter = "alpha(opacity=" + (1.0 - brightness) * 100 + ")"
#endif
}
- (void)setFrameSize:(CGSize)aSize
@@ -288,21 +290,22 @@
{
var min = MIN(aSize.width, aSize.height);
#if PLATFORM(DOM)
_blackWheelImage.style.width = min;
_blackWheelImage.style.height = min;
_blackWheelImage.width = min;
_blackWheelImage.height = min;
_blackWheelImage.style.top = (aSize.height - min) / 2.0 + "px";
_blackWheelImage.style.left = (aSize.width - min) / 2.0 + "px";
if (CPDOMAvailable)
{
_blackWheelImage.style.width = min;
_blackWheelImage.style.height = min;
_blackWheelImage.width = min;
_blackWheelImage.height = min;
_blackWheelImage.style.top = (aSize.height - min) / 2.0 + "px";
_blackWheelImage.style.left = (aSize.width - min) / 2.0 + "px";
_wheelImage.style.width = min;
_wheelImage.style.height = min;
_wheelImage.width = min;
_wheelImage.height = min;
_wheelImage.style.top = (aSize.height - min) / 2.0 + "px";
_wheelImage.style.left = (aSize.width - min) / 2.0 + "px";
#endif
_wheelImage.style.width = min;
_wheelImage.style.height = min;
_wheelImage.width = min;
_wheelImage.height = min;
_wheelImage.style.top = (aSize.height - min) / 2.0 + "px";
_wheelImage.style.left = (aSize.width - min) / 2.0 + "px";
}
_radius = min / 2.0;
-2
View File
@@ -839,7 +839,6 @@ var CPComboBoxTextSubview = @"text",
if (!shouldResign)
{
#if PLATFORM(DOM)
// In FireFox this needs to be done in setTimeout, otherwise there is no caret
// We have to save the input element now, when we lose focus it will change.
var element = [self _inputElement];
@@ -854,7 +853,6 @@ var CPComboBoxTextSubview = @"text",
[self _restorePreviousScrollingOrigin:previousScrollingOrigin];
} argument:nil order:0 modes:[CPDefaultRunLoopMode]];
#endif
return NO;
}
+23 -5
View File
@@ -24,6 +24,29 @@
@import "CPPlatform.j"
/*
CPDOMAvailable is the authoritative runtime predicate for DOM capability.
It replaces the former `#if PLATFORM(DOM)` preprocessor conditional, which
selected code at build time between the browser (DOM) and CommonJS (Node)
targets. It is a CAPABILITY test: YES only when a
functioning document object with createElement exists.
The predicate subsumes all direct local probing for the presence of a DOM.
YES - browsers (the only deployment target)
YES - any environment providing a working DOM (e.g. jsdom), where DOM
operations genuinely function
NO - CommonJS/Node without a DOM (legacy tooling: theme blending, nib2cib)
Rules for consumers:
- Platform-conditional code MUST test CPDOMAvailable.
- Do NOT reference `document` (or test for it) anywhere else in AppKit;
this declaration is the single environment peek.
- The preprocessor form must not return: there is no preprocessor.
*/
CPDOMAvailable = (typeof document !== "undefined") && document && (typeof document.createElement === "function");
// Browser Engines
CPUnknownBrowserEngine = 0;
CPGeckoBrowserEngine = 1 << 0;
@@ -55,8 +78,6 @@ CPJavaScriptClipboardAccessFeature = 12;
CPJavaScriptCanvasDrawFeature = 13;
CPJavaScriptCanvasTransformFeature = 14;
CPVMLFeature = 15;
CPJavaScriptRemedialKeySupport = 16;
CPJavaScriptShadowFeature = 20;
@@ -133,7 +154,6 @@ else if (typeof window !== "undefined" && (window.attachEvent || (!(window.Activ
PLATFORM_ENGINE |= CPInternetExplorerBrowserEngine;
// Features we can only be sure of with IE (no known independent tests)
PLATFORM_FEATURES[CPVMLFeature] = YES;
PLATFORM_FEATURES[CPJavaScriptRemedialKeySupport] = YES;
PLATFORM_FEATURES[CPJavaScriptShadowFeature] = YES;
@@ -388,7 +408,6 @@ function CPBrowserStyleProperty(aProperty)
{
var r = nil;
#if PLATFORM(DOM)
var testElement = document.createElement('div');
switch (lowerProperty)
@@ -455,7 +474,6 @@ function CPBrowserStyleProperty(aProperty)
break;
}
#endif
PLATFORM_STYLE_JS_PROPERTIES[lowerProperty] = r;
}
+3 -2
View File
@@ -1039,7 +1039,8 @@ var CPControlBlackColor = [CPColor blackColor];
_baseWritingDirection = writingDirection;
[self didChangeValueForKey:@"baseWritingDirection"];
#if PLATFORM(DOM)
if (CPDOMAvailable)
{
var style;
@@ -1062,7 +1063,7 @@ var CPControlBlackColor = [CPColor blackColor];
}
_DOMElement.style.direction = style;
#endif
}
}
@end
+23 -17
View File
@@ -22,6 +22,7 @@
@import <Foundation/CPObject.j>
@import <Foundation/CPString.j>
@import "CPCompatibility.j"
/*!
@@ -95,32 +96,37 @@
else
domain = "";
#if PLATFORM(DOM)
document.cookie = _cookieName + "=" + value + expires + "; path=/" + domain;
#else
_cookieValue = value;
_expires = expires;
#endif
if (CPDOMAvailable)
{
document.cookie = _cookieName + "=" + value + expires + "; path=/" + domain;
}
else
{
_cookieValue = value;
_expires = expires;
}
}
/* @ignore */
- (CPString)_readCookieValue
{
#if PLATFORM(DOM)
var nameEQ = _cookieName + "=",
ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++)
if (CPDOMAvailable)
{
var c = ca[i];
var nameEQ = _cookieName + "=",
ca = document.cookie.split(';');
while (c.charAt(0) == ' ')
c = c.substring(1, c.length);
for (var i = 0; i < ca.length; i++)
{
var c = ca[i];
if (c.indexOf(nameEQ) == 0)
return c.substring(nameEQ.length, c.length);
while (c.charAt(0) == ' ')
c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0)
return c.substring(nameEQ.length, c.length);
}
}
#endif
return "";
}
-6
View File
@@ -135,9 +135,7 @@ CPCursorPlatformBoth = 3;
currentCursor = self;
#if PLATFORM(DOM)
[[self class] _setCursorCSS:_cssString];
#endif
}
- (void)mouseEntered:(CPEvent)event
@@ -155,12 +153,10 @@ CPCursorPlatformBoth = 3;
+ (void)_setCursorCSS:(CPString)aString
{
#if PLATFORM(DOM)
var platformWindows = [[CPPlatformWindow visiblePlatformWindows] allObjects];
for (var i = 0, count = [platformWindows count]; i < count; i++)
platformWindows[i]._DOMBodyElement.style.cursor = aString;
#endif
}
// Internal method that is used to return the system cursors. Caches the system cursors for performance.
@@ -217,7 +213,6 @@ CPCursorPlatformBoth = 3;
+ (BOOL)_nativeCursorExists:(CPString)cursorCSSName
{
#if PLATFORM(DOM)
// FIXME: Trick until FF/Win & Chrome/Win correctly implement context-menu cursor
// They will answer that they implement it but they actually don't
@@ -240,7 +235,6 @@ CPCursorPlatformBoth = 3;
return doesExist;
}
#endif
return NO;
}
+6 -4
View File
@@ -30,6 +30,7 @@
@import <Foundation/CPDate.j>
@import <Foundation/CPLocale.j>
@import <Foundation/CPTimeZone.j>
@import "CPCompatibility.j"
@class CPStepper
@class CPApp
@@ -258,10 +259,11 @@ CPEraDatePickerElementFlag = 0x0100;
[_datePickerComponent setDatePickerElements:_datePickerElements];
// FIXME: Don't know why but next line will cause theme compilation to fail...
// Workaround: added "if PLATFORM(DOM)"
#if PLATFORM(DOM)
[_datePickerComponent setEnabled:[self isEnabled]];
#endif
// Workaround: guarded with CPDOMAvailable (was: "if PLATFORM(DOM)")
if (CPDOMAvailable)
{
[_datePickerComponent setEnabled:[self isEnabled]];
}
if (_isTextual)
// We need to transmit text color to the text field version (Cocoa doesn't permit adapting the calendar view text color)
+12 -9
View File
@@ -26,6 +26,7 @@
@import "CPTextField.j"
@import "CPImage.j"
@import "CALayer.j"
@import "CPCompatibility.j"
@class _CPCibCustomResource
@class CPDatePicker
@@ -194,10 +195,10 @@ _CPDatePickerClockSeconds = 3;
// Check if we have to display the hand second
// FIXME: Don't know why but next line will cause theme compilation to fail...
// Workaround: added "if PLATFORM(DOM)"
#if PLATFORM(DOM)
// Workaround: guarded with CPDOMAvailable (was: "if PLATFORM(DOM)")
if (!CPDOMAvailable) return;
[_secondHandLayer setHidden:!((_datePickerElements & CPHourMinuteSecondDatePickerElementFlag) == CPHourMinuteSecondDatePickerElementFlag)];
#endif
}
// MARK: Layout methods
@@ -381,13 +382,15 @@ _CPDatePickerClockSeconds = 3;
break;
}
#if PLATFORM(DOM)
_datePicker._invokedByUserEvent = YES;
#endif
if (CPDOMAvailable)
{
_datePicker._invokedByUserEvent = YES;
}
[_datePicker _setDateValue:dateValue timeInterval:[_datePicker timeInterval]];
#if PLATFORM(DOM)
_datePicker._invokedByUserEvent = NO;
#endif
if (CPDOMAvailable)
{
_datePicker._invokedByUserEvent = NO;
}
// We have to adapt represented values
_representedHours = dateValue.getHours();
@@ -20,6 +20,7 @@
*/
@import "CPTextField.j"
@import "CPCompatibility.j"
@class CPDatePicker
@class _CPDatePickerElementView
@@ -471,13 +472,15 @@ CPAMPMDateType = 6;
newDateValue.setSeconds(newDateValue.getSeconds() + secondsFromGMT - secondsFromGMTTimeZone);
}
#if PLATFORM(DOM)
_datePicker._invokedByUserEvent = YES;
#endif
if (CPDOMAvailable)
{
_datePicker._invokedByUserEvent = YES;
}
[_datePicker _setDateValue:newDateValue timeInterval:[_datePicker timeInterval]];
#if PLATFORM(DOM)
_datePicker._invokedByUserEvent = NO;
#endif
if (CPDOMAvailable)
{
_datePicker._invokedByUserEvent = NO;
}
}
@@ -21,6 +21,7 @@
@import "CPControl.j"
@import "_CPDatePickerElementTextField.j"
@import "CPCompatibility.j"
@class CPDatePicker
@@ -403,13 +404,15 @@
dateValue.setHours(dateValue.getHours() - 12);
}
#if PLATFORM(DOM)
_datePicker._invokedByUserEvent = YES;
#endif
if (CPDOMAvailable)
{
_datePicker._invokedByUserEvent = YES;
}
[_datePicker _setDateValue:dateValue timeInterval:[_datePicker timeInterval]];
#if PLATFORM(DOM)
_datePicker._invokedByUserEvent = NO;
#endif
if (CPDOMAvailable)
{
_datePicker._invokedByUserEvent = NO;
}
}
+17 -12
View File
@@ -23,6 +23,7 @@
@import "CPControl.j"
@import "_CPDatePickerDayView.j"
@import "CPCompatibility.j"
@class CPDatePicker
@@ -457,9 +458,10 @@
_indexDayTile = -1;
_eventDragged = nil;
#if PLATFORM(DOM)
_datePicker._invokedByUserEvent = YES;
#endif
if (CPDOMAvailable)
{
_datePicker._invokedByUserEvent = YES;
}
// Check if we have to change or not the month of the component
if ([dayTile date].getMonth() == _date.getMonth())
@@ -514,9 +516,10 @@
[_delegate _displayNextMonth];
}
#if PLATFORM(DOM)
_datePicker._invokedByUserEvent = NO;
#endif
if (CPDOMAvailable)
{
_datePicker._invokedByUserEvent = NO;
}
}
/*! Mouse dragged event
@@ -534,9 +537,10 @@
_indexDayTile = [self indexOfTileForEvent:anEvent];
_eventDragged = anEvent;
#if PLATFORM(DOM)
_datePicker._invokedByUserEvent = YES;
#endif
if (CPDOMAvailable)
{
_datePicker._invokedByUserEvent = YES;
}
if ([_datePicker datePickerMode] == CPSingleDateMode)
{
@@ -580,9 +584,10 @@
}
}
#if PLATFORM(DOM)
_datePicker._invokedByUserEvent = NO;
#endif
if (CPDOMAvailable)
{
_datePicker._invokedByUserEvent = NO;
}
}
- (void)mouseUp:(CPEvent)anEvent
+7 -5
View File
@@ -34,6 +34,7 @@
@class _CPDatePickerElementView
@import "_CPDatePickerElementView.j"
@import "CPCompatibility.j"
@global CPSingleDateMode
@global CPRangeDateMode
@@ -89,17 +90,18 @@
[self setNeedsLayout];
[self setNeedsDisplay:YES];
#if PLATFORM(DOM)
if ([_datePicker currentValueForThemeAttribute:@"uses-focus-ring"])
{
// As with overflow:hidden, views are clipping their content, in order
// to show a focus ring (which is external to a view), we need to let
// content extend outside the view.
_datePicker._DOMElement.style.overflow = "visible";
_DOMElement.style.overflow = "visible";
_datePickerElementView._DOMElement.style.overflow = "visible";
if (CPDOMAvailable)
{
_datePicker._DOMElement.style.overflow = "visible";
_DOMElement.style.overflow = "visible";
_datePickerElementView._DOMElement.style.overflow = "visible";
}
}
#endif
}
+4 -1
View File
@@ -33,7 +33,10 @@
@global CPApp
#define DRAGGING_WINDOW(anObject) ([anObject isKindOfClass:[CPWindow class]] ? anObject : [anObject window])
function DRAGGING_WINDOW(anObject)
{
return ([anObject isKindOfClass:[CPWindow class]] ? anObject : [anObject window]);
}
var CPDragServerPreviousEvent = nil,
CPDragServerPeriodicUpdateInterval = 0.05;
-6
View File
@@ -82,10 +82,8 @@ var _CPEventPeriodicEventPeriod = 0,
float _scrollingDeltaY;
BOOL _hasPreciseScrollingDeltas;
#if PLATFORM(DOM)
BOOL _suppressCappuccinoCut;
BOOL _suppressCappuccinoPaste;
#endif
CPTrackingArea _trackingArea;
}
@@ -609,11 +607,7 @@ var _CPEventPeriodicEventPeriod = 0,
*/
- (BOOL)_platformIsEffectingCutOrPaste
{
#if PLATFORM(DOM)
return _suppressCappuccinoCut || _suppressCappuccinoPaste;
#else
return NO;
#endif
}
+33 -7
View File
@@ -51,14 +51,40 @@ var _CPFontCache = {},
_CPFontSystemFontFaceSpecified = NO;
#define _CPRealFontSize(aSize) (aSize <= 0 ? _CPFontSystemFontSize : aSize)
#define _CPFontNormalizedNames(aName) _CPFontNormalizedNameArray(aName).join(", ")
#define _CPCachedFont(aName, aSize, isBold, isItalic) _CPFontCache[_CPFontCreateCSSString(_CPFontNormalizedNames(aName), aSize, isBold, isItalic)]
#define _CPUserFont(aName, aSize, isBold, isItalic) _CPCachedFont(aName, aSize, isBold, isItalic) || [[CPFont alloc] _initWithName:aName size:aSize bold:isBold italic:isItalic system:NO]
function _CPRealFontSize(aSize)
{
return (aSize <= 0 ? _CPFontSystemFontSize : aSize);
}
#define _CPSystemFontCacheKey(aSize, isBold) (String(aSize) + (isBold ? "b" : ""))
#define _CPCachedSystemFont(aSize, isBold) _CPSystemFontCache[_CPSystemFontCacheKey(aSize, isBold)]
#define _CPSystemFont(aSize, isBold) (_CPCachedSystemFont(aSize, isBold) || [[CPFont alloc] _initWithName:_CPFontSystemFacePlaceholder size:aSize bold:isBold italic:NO system:YES])
function _CPFontNormalizedNames(aName)
{
return _CPFontNormalizedNameArray(aName).join(", ");
}
function _CPCachedFont(aName, aSize, isBold, isItalic)
{
return _CPFontCache[_CPFontCreateCSSString(_CPFontNormalizedNames(aName), aSize, isBold, isItalic)];
}
function _CPUserFont(aName, aSize, isBold, isItalic)
{
return _CPCachedFont(aName, aSize, isBold, isItalic) || [[CPFont alloc] _initWithName:aName size:aSize bold:isBold italic:isItalic system:NO];
}
function _CPSystemFontCacheKey(aSize, isBold)
{
return (String(aSize) + (isBold ? "b" : ""));
}
function _CPCachedSystemFont(aSize, isBold)
{
return _CPSystemFontCache[_CPSystemFontCacheKey(aSize, isBold)];
}
function _CPSystemFont(aSize, isBold)
{
return (_CPCachedSystemFont(aSize, isBold) || [[CPFont alloc] _initWithName:_CPFontSystemFacePlaceholder size:aSize bold:isBold italic:NO system:YES]);
}
/*!
@ingroup appkit
+24 -20
View File
@@ -25,6 +25,7 @@
@import "CPControl.j"
@import "CPFont.j"
@import "CPFontDescriptor.j"
@import "CPCompatibility.j"
@global CPApp
@class CPFontPanel
@@ -132,28 +133,31 @@ CPRemoveTraitFontAction = 7;
{
_availableFonts = [];
#if PLATFORM(DOM)
_CPFontDetectSpan = document.createElement("span");
_CPFontDetectSpan.fontSize = "24px";
_CPFontDetectSpan.appendChild(document.createTextNode("mmmmmmmmmml"));
var div = document.createElement("div");
div.style.position = "absolute";
div.style.top = "-1000px";
div.appendChild(_CPFontDetectSpan);
document.getElementsByTagName("body")[0].appendChild(div);
_CPFontDetectReferenceFonts = _CPFontDetectPickTwoDifferentFonts(["monospace", "serif", "sans-serif", "cursive"]);
for (var i = 0; i < _CPFontDetectAllFonts.length; i++)
if (CPDOMAvailable)
{
var available = _CPFontDetectFontAvailable(_CPFontDetectAllFonts[i]);
if (available)
_availableFonts.push(_CPFontDetectAllFonts[i]);
_CPFontDetectSpan = document.createElement("span");
_CPFontDetectSpan.fontSize = "24px";
_CPFontDetectSpan.appendChild(document.createTextNode("mmmmmmmmmml"));
var div = document.createElement("div");
div.style.position = "absolute";
div.style.top = "-1000px";
div.appendChild(_CPFontDetectSpan);
document.getElementsByTagName("body")[0].appendChild(div);
_CPFontDetectReferenceFonts = _CPFontDetectPickTwoDifferentFonts(["monospace", "serif", "sans-serif", "cursive"]);
for (var i = 0; i < _CPFontDetectAllFonts.length; i++)
{
var available = _CPFontDetectFontAvailable(_CPFontDetectAllFonts[i]);
if (available)
_availableFonts.push(_CPFontDetectAllFonts[i]);
}
}
else
{
// If there's no font detection, just assume all fonts are available.
_availableFonts = _CPFontDetectAllFonts;
}
#else
// If there's no font detection, just assume all fonts are available.
_availableFonts = _CPFontDetectAllFonts;
#endif
}
return _availableFonts;
}
+6 -6
View File
@@ -239,7 +239,8 @@ function CPAppKitImage(aFilename, aSize)
*/
- (CPData)data
{
#if PLATFORM(DOM)
if (!CPDOMAvailable) return;
var dataURL;
if ([_filename hasPrefix:@"data:image"])
@@ -261,7 +262,6 @@ function CPAppKitImage(aFilename, aSize)
var base64 = dataURL.replace(/^data:image\/png;base64,/, "");
return [CPData dataWithBase64:base64];
#endif
}
/*!
@@ -384,7 +384,8 @@ function CPAppKitImage(aFilename, aSize)
_loadStatus = CPImageLoadStatusLoading;
#if PLATFORM(DOM)
if (!CPDOMAvailable) return;
_image = new Image();
var isSynchronous = YES;
@@ -431,7 +432,6 @@ function CPAppKitImage(aFilename, aSize)
// onload and friends may fire after this point but BEFORE the end of the run loop,
// crazy, I know. So don't set isSynchronous here, rather wait a bit longer.
window.setTimeout(function() { isSynchronous = NO; }, 0);
#endif
}
- (BOOL)isSingleImage
@@ -641,7 +641,8 @@ function CPAppKitImage(aFilename, aSize)
- (DOMElement)applyCSSImageForView:(CPView)aView onDOMElement:(DOMElement)aDOMElement styleNode:(DOMElement)aStyleNode previousState:(CPArrayRef)aPreviousStateRef
{
#if PLATFORM(DOM)
if (!CPDOMAvailable) return;
// First, restore previous CSS styling before applying the new one
var aPreviousState = @deref(aPreviousStateRef);
@@ -724,7 +725,6 @@ function CPAppKitImage(aFilename, aSize)
@deref(aPreviousStateRef) = aPreviousState;
return aStyleNode;
#endif
}
- (BOOL)_shouldBeResized
+48 -41
View File
@@ -25,6 +25,7 @@
@import "CPControl.j"
@import "CPImage.j"
@import "CPShadowView.j"
@import "CPDOMDisplayServer.j"
@global CPImagesPboardType
@global appkit_tag_dom_elements
@@ -89,9 +90,10 @@ var CPImageViewEmptyPlaceholderImage = nil;
if (self)
{
#if PLATFORM(DOM)
[self _createDOMImageElement];
#endif
if (CPDOMAvailable)
{
[self _createDOMImageElement];
}
}
return self;
@@ -99,7 +101,9 @@ var CPImageViewEmptyPlaceholderImage = nil;
- (void)_createDOMImageElement
{
#if PLATFORM(DOM)
if (!CPDOMAvailable)
return;
var image = [self objectValue],
isCSSBasedImage = [image isCSSBased],
isIMGImageElement = _DOMImageElement && (_DOMImageElement.nodeName == "IMG");
@@ -140,7 +144,6 @@ var CPImageViewEmptyPlaceholderImage = nil;
AppKitTagDOMElement(self, _DOMImageElement);
CPDOMDisplayServerAppendChild(_DOMElement, _DOMImageElement);
#endif
}
/*!
@@ -173,17 +176,18 @@ var CPImageViewEmptyPlaceholderImage = nil;
var newImage = [self objectValue];
#if PLATFORM(DOM)
[self _createDOMImageElement];
if (CPDOMAvailable)
{
[self _createDOMImageElement];
if ([newImage isCSSBased])
_cssStyleNode = [newImage applyCSSImageForView:self
onDOMElement:_DOMImageElement
styleNode:_cssStyleNode
previousState:@ref(_cssStylePreviousState)];
else
_DOMImageElement.src = newImage ? [newImage filename] : [CPImageViewEmptyPlaceholderImage filename];
#endif
if ([newImage isCSSBased])
_cssStyleNode = [newImage applyCSSImageForView:self
onDOMElement:_DOMImageElement
styleNode:_cssStyleNode
previousState:@ref(_cssStylePreviousState)];
else
_DOMImageElement.src = newImage ? [newImage filename] : [CPImageViewEmptyPlaceholderImage filename];
}
var size = [newImage size];
@@ -191,10 +195,11 @@ var CPImageViewEmptyPlaceholderImage = nil;
{
[defaultCenter addObserver:self selector:@selector(imageDidLoad:) name:CPImageDidLoadNotification object:newImage];
#if PLATFORM(DOM)
_DOMImageElement.width = 0;
_DOMImageElement.height = 0;
#endif
if (CPDOMAvailable)
{
_DOMImageElement.width = 0;
_DOMImageElement.height = 0;
}
[_shadowView setHidden:YES];
}
@@ -287,12 +292,10 @@ var CPImageViewEmptyPlaceholderImage = nil;
{
[super setImageScaling:anImageScaling];
#if PLATFORM(DOM)
if ([self currentValueForThemeAttribute:@"image-scaling"] === CPImageScaleAxesIndependently)
if (CPDOMAvailable && [self currentValueForThemeAttribute:@"image-scaling"] === CPImageScaleAxesIndependently)
{
CPDOMDisplayServerSetStyleLeftTop(_DOMImageElement, NULL, 0.0, 0.0);
}
#endif
[self setNeedsLayout];
[self setNeedsDisplay:YES];
@@ -310,16 +313,18 @@ var CPImageViewEmptyPlaceholderImage = nil;
{
if (![self image])
{
#if PLATFORM(DOM)
_DOMImageElement.style.visibility = "hidden";
#endif
if (CPDOMAvailable)
{
_DOMImageElement.style.visibility = "hidden";
}
[_shadowView setHidden:YES];
}
else
{
#if PLATFORM(DOM)
_DOMImageElement.style.visibility = "visible";
#endif
if (CPDOMAvailable)
{
_DOMImageElement.style.visibility = "visible";
}
[_shadowView setHidden:NO];
}
}
@@ -354,10 +359,11 @@ var CPImageViewEmptyPlaceholderImage = nil;
if (imageScaling === CPImageScaleAxesIndependently)
{
#if PLATFORM(DOM)
if (CPDOMAvailable)
{
_DOMImageElement.width = ROUND(width);
_DOMImageElement.height = ROUND(height);
#endif
}
}
else
{
@@ -395,10 +401,11 @@ var CPImageViewEmptyPlaceholderImage = nil;
break;
}
#if PLATFORM(DOM)
if (CPDOMAvailable)
{
_DOMImageElement.width = ROUND(width);
_DOMImageElement.height = ROUND(height);
#endif
}
var x,
y;
@@ -441,13 +448,13 @@ var CPImageViewEmptyPlaceholderImage = nil;
break;
}
#if PLATFORM(DOM)
CPDOMDisplayServerSetStyleLeftTop(_DOMImageElement, NULL, x, y);
#endif
if (CPDOMAvailable)
{
CPDOMDisplayServerSetStyleLeftTop(_DOMImageElement, NULL, x, y);
}
}
#if PLATFORM(DOM)
if ([image isCSSBased] && [image _shouldBeResized])
if (CPDOMAvailable && [image isCSSBased] && [image _shouldBeResized])
{
[image _setDisplaySize:CGSizeMake(ROUND(width), ROUND(height))];
@@ -456,7 +463,6 @@ var CPImageViewEmptyPlaceholderImage = nil;
styleNode:_cssStyleNode
previousState:@ref(_cssStylePreviousState)];
}
#endif
_imageRect = CGRectMake(x, y, width, height);
@@ -578,9 +584,10 @@ var CPImageViewImageKey = @"CPImageViewImageKey",
if (self)
{
#if PLATFORM(DOM)
[self _createDOMImageElement];
#endif
if (CPDOMAvailable)
{
[self _createDOMImageElement];
}
[self setHasShadow:[aCoder decodeBoolForKey:CPImageViewHasShadowKey]];
[self setImageAlignment:[aCoder decodeIntForKey:CPImageViewImageAlignmentKey]];
+10 -6
View File
@@ -28,6 +28,7 @@
@import "CPKeyValueBinding.j"
@import "CPMenuItem.j"
@import "CALayer.j"
@import "CPCompatibility.j"
@global CPApp
@@ -137,9 +138,10 @@ var _CPMenuBarVisible = NO,
[_CPMenuBarSharedWindow orderOut:self];
// FIXME: There must be a better way to do this.
#if PLATFORM(DOM)
[[CPPlatformWindow primaryPlatformWindow] resizeEvent:nil];
#endif
if (CPDOMAvailable)
{
[[CPPlatformWindow primaryPlatformWindow] resizeEvent:nil];
}
}
+ (void)setMenuBarTitle:(CPString)aTitle
@@ -1079,14 +1081,14 @@ var _CPMenuBarVisible = NO,
anEvent._isKeyEquivalent = YES; // prevent the menu keystroke from beeing inserted into textview
[self performActionForItemAtIndex:index];
#if PLATFORM(DOM)
// we are done with this event in cappuccino space. do not let the browser do something weird additionally (e.g. command-o).
// but we must not stop copy/paste events as these can only be handled by the browser at this time even if they are in our menu
// (until we move to CPTextView as the fieleditor)
if (characters != "c" && characters != "x" && characters != "v")
if (CPDOMAvailable && characters != "c" && characters != "x" && characters != "v")
{
_CPDOMEventStop(anEvent._DOMEvent);
#endif
}
}
else
{
@@ -1390,3 +1392,5 @@ var CPMenuTitleKey = @"CPMenuTitleKey",
@import "_CPMenuBarWindow.j"
@import "_CPMenuWindow.j"
@global _CPDOMEventStop
+11 -9
View File
@@ -22,6 +22,7 @@
@import "CPPanel.j"
@import "_CPMenuManager.j"
@import "CPCompatibility.j"
@class _CPMenuView
@class CPMenu
@@ -100,16 +101,17 @@
- (void)setTitle:(CPString)aTitle
{
#if PLATFORM(DOM)
var bundleName = [[CPBundle mainBundle] objectForInfoDictionaryKey:@"CPBundleName"];
if (CPDOMAvailable)
{
var bundleName = [[CPBundle mainBundle] objectForInfoDictionaryKey:@"CPBundleName"];
if (![bundleName length])
document.title = aTitle;
else if ([aTitle length])
document.title = aTitle + @" - " + bundleName;
else
document.title = bundleName;
#endif
if (![bundleName length])
document.title = aTitle;
else if ([aTitle length])
document.title = aTitle + @" - " + bundleName;
else
document.title = bundleName;
}
[_titleField setStringValue:aTitle];
[_titleField sizeToFit];
+26 -17
View File
@@ -895,6 +895,17 @@ CPControlKeyMask
return [super description] + @" target: " + [self target] + @" action: " + CPStringFromSelector([self action]);
}
- (id)_decodeValueForKey:(CPString)aKey defaultValue:(id)aDefaultValue coder:(CPCoder)aCoder
{
return [aCoder containsValueForKey:aKey] ? [aCoder decodeObjectForKey:aKey] : aDefaultValue;
}
- (void)_encodeValue:(id)aValue forKey:(CPString)aKey ifNotEqualTo:(id)aDefaultValue coder:(CPCoder)aCoder
{
if (aValue !== aDefaultValue)
[aCoder encodeObject:aValue forKey:aKey];
}
@end
// MARK: -
@@ -940,9 +951,6 @@ var CPMenuItemIsSeparatorKey = @"CPMenuItemIsSeparatorKey",
CPMenuItemRepresentedObjectKey = @"CPMenuItemRepresentedObjectKey",
CPMenuItemViewKey = @"CPMenuItemViewKey";
#define DEFAULT_VALUE(aKey, aDefaultValue) [aCoder containsValueForKey:(aKey)] ? [aCoder decodeObjectForKey:(aKey)] : (aDefaultValue)
#define ENCODE_IFNOT(aKey, aValue, aDefaultValue) if ((aValue) !== (aDefaultValue)) [aCoder encodeObject:(aValue) forKey:(aKey)];
@implementation CPMenuItem (CPCoding)
/*!
Initializes the menu item from a coder.
@@ -965,7 +973,7 @@ var CPMenuItemIsSeparatorKey = @"CPMenuItemIsSeparatorKey",
_target = [aCoder decodeObjectForKey:CPMenuItemTargetKey];
_action = [aCoder decodeObjectForKey:CPMenuItemActionKey];
_isEnabled = DEFAULT_VALUE(CPMenuItemIsEnabledKey, YES);
_isEnabled = [self _decodeValueForKey:CPMenuItemIsEnabledKey defaultValue:YES coder:aCoder];
_isHidden = [aCoder decodeBoolForKey:CPMenuItemIsHiddenKey];
_tag = [aCoder decodeIntForKey:CPMenuItemTagKey];
_state = [aCoder decodeIntForKey:CPMenuItemStateKey];
@@ -1012,20 +1020,20 @@ var CPMenuItemIsSeparatorKey = @"CPMenuItemIsSeparatorKey",
[aCoder encodeObject:_target forKey:CPMenuItemTargetKey];
[aCoder encodeObject:_action forKey:CPMenuItemActionKey];
ENCODE_IFNOT(CPMenuItemIsEnabledKey, _isEnabled, YES);
ENCODE_IFNOT(CPMenuItemIsHiddenKey, _isHidden, NO);
[self _encodeValue:_isEnabled forKey:CPMenuItemIsEnabledKey ifNotEqualTo:YES coder:aCoder]
[self _encodeValue:_isHidden forKey:CPMenuItemIsHiddenKey ifNotEqualTo:NO coder:aCoder]
ENCODE_IFNOT(CPMenuItemTagKey, _tag, 0);
ENCODE_IFNOT(CPMenuItemStateKey, _state, CPOffState);
[self _encodeValue:_tag forKey:CPMenuItemTagKey ifNotEqualTo:0 coder:aCoder]
[self _encodeValue:_state forKey:CPMenuItemStateKey ifNotEqualTo:CPOffState coder:aCoder]
ENCODE_IFNOT(CPMenuItemImageKey, _image, nil);
ENCODE_IFNOT(CPMenuItemAlternateImageKey, _alternateImage, nil);
ENCODE_IFNOT(CPMenuItemOnStateImageKey, _onStateImage, nil);
ENCODE_IFNOT(CPMenuItemOffStateImageKey, _offStateImage, nil);
ENCODE_IFNOT(CPMenuItemMixedStateImageKey, _mixedStateImage, nil);
[self _encodeValue:_image forKey:CPMenuItemImageKey ifNotEqualTo:nil coder:aCoder]
[self _encodeValue:_alternateImage forKey:CPMenuItemAlternateImageKey ifNotEqualTo:nil coder:aCoder]
[self _encodeValue:_onStateImage forKey:CPMenuItemOnStateImageKey ifNotEqualTo:nil coder:aCoder]
[self _encodeValue:_offStateImage forKey:CPMenuItemOffStateImageKey ifNotEqualTo:nil coder:aCoder]
[self _encodeValue:_mixedStateImage forKey:CPMenuItemMixedStateImageKey ifNotEqualTo:nil coder:aCoder]
ENCODE_IFNOT(CPMenuItemSubmenuKey, _submenu, nil);
ENCODE_IFNOT(CPMenuItemMenuKey, _menu, nil);
[self _encodeValue:_submenu forKey:CPMenuItemSubmenuKey ifNotEqualTo:nil coder:aCoder]
[self _encodeValue:_menu forKey:CPMenuItemMenuKey ifNotEqualTo:nil coder:aCoder]
if (_keyEquivalent && _keyEquivalent.length)
[aCoder encodeObject:_keyEquivalent forKey:CPMenuItemKeyEquivalentKey];
@@ -1036,8 +1044,9 @@ var CPMenuItemIsSeparatorKey = @"CPMenuItemIsSeparatorKey",
if (_indentationLevel > 0)
[aCoder encodeInt:_indentationLevel forKey:CPMenuItemIndentationLevelKey];
ENCODE_IFNOT(CPMenuItemRepresentedObjectKey, _representedObject, nil);
ENCODE_IFNOT(CPMenuItemViewKey, _view, nil);
[self _encodeValue:_representedObject forKey:CPMenuItemRepresentedObjectKey ifNotEqualTo:nil coder:aCoder]
[self _encodeValue:_view forKey:CPMenuItemViewKey ifNotEqualTo:nil coder:aCoder]
}
@end
+8 -2
View File
@@ -86,9 +86,15 @@ var CPOutlineViewCoalesceSelectionNotificationStateOff = 0,
CPOutlineViewCoalesceSelectionNotificationStateOn = 1,
CPOutlineViewCoalesceSelectionNotificationStateDid = 2;
#define SELECTION_SHOULD_CHANGE(anOutlineView) (!((anOutlineView)._implementedOutlineViewDelegateMethods & CPOutlineViewDelegate_selectionShouldChangeInOutlineView_) || [(anOutlineView)._outlineViewDelegate selectionShouldChangeInOutlineView:(anOutlineView)])
function SELECTION_SHOULD_CHANGE(anOutlineView)
{
return (!((anOutlineView)._implementedOutlineViewDelegateMethods & CPOutlineViewDelegate_selectionShouldChangeInOutlineView_) || [(anOutlineView)._outlineViewDelegate selectionShouldChangeInOutlineView:(anOutlineView)]);
}
#define SHOULD_SELECT_ITEM(anOutlineView, anItem) (!((anOutlineView)._implementedOutlineViewDelegateMethods & CPOutlineViewDelegate_outlineView_shouldSelectItem_) || [(anOutlineView)._outlineViewDelegate outlineView:(anOutlineView) shouldSelectItem:(anItem)])
function SHOULD_SELECT_ITEM(anOutlineView, anItem)
{
return (!((anOutlineView)._implementedOutlineViewDelegateMethods & CPOutlineViewDelegate_outlineView_shouldSelectItem_) || [(anOutlineView)._outlineViewDelegate outlineView:(anOutlineView) shouldSelectItem:(anItem)]);
}
@protocol CPOutlineViewDelegate <CPObject>
-3
View File
@@ -323,8 +323,6 @@ var CPPasteboards = nil;
@end
#if PLATFORM(DOM)
var DOMDataTransferPasteboard = nil;
@implementation _CPDOMDataTransferPasteboard : CPPasteboard
@@ -388,4 +386,3 @@ var DOMDataTransferPasteboard = nil;
@end
#endif
+6 -4
View File
@@ -33,6 +33,7 @@
@import "_CPRuleEditorViewSliceRow.j"
@import "_CPRuleEditorLocalizer.j"
@import "CPCompatibility.j"
@class CPCompoundPredicate
@class CPComparisonPredicate
@@ -2248,10 +2249,11 @@ TODO: implement
firstSlice = [_slices objectAtIndex:firstIndex],
dragview = [[CPView alloc] initWithFrame:[firstSlice frame]];
#if PLATFORM(DOM)
var html = firstSlice._DOMElement.innerHTML;
dragview._DOMElement.innerHTML = [html copy];
#endif
if (CPDOMAvailable)
{
var html = firstSlice._DOMElement.innerHTML;
dragview._DOMElement.innerHTML = [html copy];
}
[dragview setBackgroundColor:[firstSlice backgroundColor]];
[dragview setAlphaValue:0.7];
+3 -4
View File
@@ -42,11 +42,10 @@
*/
- (CGRect)visibleFrame
{
#if PLATFORM(DOM)
return CGRectMake(window.screen.availLeft, window.screen.availTop, window.screen.availWidth, window.screen.availHeight);
#else
if (CPDOMAvailable)
return CGRectMake(window.screen.availLeft, window.screen.availTop, window.screen.availWidth, window.screen.availHeight);
return CGRectMakeZero();
#endif
}
@end
+11 -8
View File
@@ -30,11 +30,11 @@
@import "CPScroller.j"
@import "CPView.j"
@import "CPRulerView.j"
@import "CPCompatibility.j"
@class CPTableView
@class CPRulerView
#define SHOULD_SHOW_CORNER_VIEW() (_scrollerStyle === CPScrollerStyleLegacy && _verticalScroller && ![_verticalScroller isHidden])
@protocol CPScrollViewDelegate <CPObject>
@@ -49,7 +49,8 @@
/*! @ignore */
var _isBrowserUsingOverlayScrollers = function()
{
#if PLATFORM(DOM)
if (!CPDOMAvailable) return NO;
/*
Even if the system supports overlay (Lion) scrollers,
the browser (e.g. FireFox *cough*) may not.
@@ -85,9 +86,6 @@ var _isBrowserUsingOverlayScrollers = function()
document.body.removeChild(outer);
return usingOverlayScrollers;
#else
return NO;
#endif
};
var TIMER_INTERVAL = 0.2,
@@ -1000,7 +998,7 @@ Notifies the delegate when the scroll view has finished scrolling.
if (_cornerView)
{
[_cornerView setHidden:!SHOULD_SHOW_CORNER_VIEW()];
[_cornerView setHidden:![self _shouldShowCornerView]];
[self addSubview:_cornerView];
}
}
@@ -1043,7 +1041,7 @@ Notifies the delegate when the scroll view has finished scrolling.
frame.size.height = CGRectGetHeight([headerView frame]);
if (SHOULD_SHOW_CORNER_VIEW())
if ([self _shouldShowCornerView])
frame.size.width -= CGRectGetWidth([self _cornerViewFrame]);
return frame;
@@ -1406,7 +1404,7 @@ Notifies the delegate when the scroll view has finished scrolling.
[_headerClipView setFrame:[self _headerClipViewFrame]];
[[_headerClipView documentView] setNeedsDisplay:YES];
if (SHOULD_SHOW_CORNER_VIEW())
if ([self _shouldShowCornerView])
{
[_cornerView setFrame:[self _cornerViewFrame]];
[_cornerView setHidden:NO];
@@ -1730,6 +1728,10 @@ Notifies the delegate when the scroll view has finished scrolling.
[_headerClipView scrollToPoint:CGPointMake(contentBounds.origin.x, 0)];
}
- (BOOL)_shouldShowCornerView
{
return (_scrollerStyle === CPScrollerStyleLegacy && _verticalScroller && ![_verticalScroller isHidden]);
}
@end
// MARK: -
@@ -1906,4 +1908,5 @@ var CPScrollViewContentViewKey = @"CPScrollViewContentView",
[aCoder encodeObject:_horizontalRuler forKey:CPScrollViewHRulerKey];
}
@end
+1 -3
View File
@@ -1002,15 +1002,13 @@ var AFFINITY = 5;
}
}
#if PLATFORM(DOM)
// Don't do this in nib2cib !..
if (_allowsTickMarkValuesOnly)
if (CPDOMAvailable && _allowsTickMarkValuesOnly)
{
[self setObjectValue:[self closestTickMarkValueToValue:[self doubleValue]]];
_currentTickMarkSegment = _closestTickMarkIndex;
[self sendAction:[self action] to:[self target]];
}
#endif
}
/*! @ignore */
+40 -31
View File
@@ -62,28 +62,6 @@ var CPSplitViewDelegate_splitView_canCollapseSubview_
CPSplitViewDelegate_splitViewDidResizeSubviews_ = 1 << 9,
CPSplitViewDelegate_splitViewWillResizeSubviews_ = 1 << 10;
#define SPLIT_VIEW_MAYBE_POST_WILL_RESIZE() \
if ((_suppressResizeNotificationsMask & DidPostWillResizeNotification) === 0) \
{ \
[self _postNotificationWillResize]; \
_suppressResizeNotificationsMask |= DidPostWillResizeNotification; \
}
#define SPLIT_VIEW_MAYBE_POST_DID_RESIZE() \
if ((_suppressResizeNotificationsMask & ShouldSuppressResizeNotifications) !== 0) \
_suppressResizeNotificationsMask |= DidSuppressResizeNotification; \
else \
[self _postNotificationDidResize];
#define SPLIT_VIEW_DID_SUPPRESS_RESIZE_NOTIFICATION() \
((_suppressResizeNotificationsMask & DidSuppressResizeNotification) !== 0)
#define SPLIT_VIEW_SUPPRESS_RESIZE_NOTIFICATIONS(shouldSuppress) \
if (shouldSuppress) \
_suppressResizeNotificationsMask |= ShouldSuppressResizeNotifications; \
else \
_suppressResizeNotificationsMask = 0;
CPSplitViewDidResizeSubviewsNotification = @"CPSplitViewDidResizeSubviewsNotification";
CPSplitViewWillResizeSubviewsNotification = @"CPSplitViewWillResizeSubviewsNotification";
@@ -733,7 +711,7 @@ var CPThemeStatesForSplitViewDivider = @[@"dummy one as CPSplitViewDividerStyle
*/
- (void)adjustSubviews
{
SPLIT_VIEW_MAYBE_POST_WILL_RESIZE();
[self _maybePostWillResizeNotification];
[self _postNotificationWillResize];
// 2 possibilities : we have, or not, enough flexible space to accomodate fixed size subviews
@@ -815,7 +793,7 @@ var CPThemeStatesForSplitViewDivider = @[@"dummy one as CPSplitViewDividerStyle
[self _distribute:remainingSpace amoung:fixedCount onFlexible:NO fromIndex:0 toIndex:nbSubviews-1];
}
SPLIT_VIEW_MAYBE_POST_DID_RESIZE();
[self _maybePostDidResizeNotification];
[self layoutSubviews];
}
@@ -1211,7 +1189,7 @@ var CPThemeStatesForSplitViewDivider = @[@"dummy one as CPSplitViewDividerStyle
// autosave.
_shouldRestoreFromAutosaveUnlessFrameSize = nil;
SPLIT_VIEW_SUPPRESS_RESIZE_NOTIFICATIONS(YES);
[self _setResizeNotificationsSuppressed:YES];
var realPosition = [self _realPositionForPosition:position ofDividerAtIndex:dividerIndex],
viewA = _arrangedSubviews[dividerIndex],
@@ -1228,9 +1206,9 @@ var CPThemeStatesForSplitViewDivider = @[@"dummy one as CPSplitViewDividerStyle
if (preSize !== frameA.size[_sizeComponent])
{
SPLIT_VIEW_MAYBE_POST_WILL_RESIZE();
[self _maybePostWillResizeNotification];
[_arrangedSubviews[dividerIndex] setFrame:frameA];
SPLIT_VIEW_MAYBE_POST_DID_RESIZE();
[self _maybePostDidResizeNotification];
}
preSize = frameB.size[_sizeComponent];
@@ -1245,9 +1223,9 @@ var CPThemeStatesForSplitViewDivider = @[@"dummy one as CPSplitViewDividerStyle
if (preSize !== frameB.size[_sizeComponent] || preOrigin !== frameB.origin[_originComponent])
{
SPLIT_VIEW_MAYBE_POST_WILL_RESIZE();
[self _maybePostWillResizeNotification];
[_arrangedSubviews[dividerIndex + 1] setFrame:frameB];
SPLIT_VIEW_MAYBE_POST_DID_RESIZE();
[self _maybePostDidResizeNotification];
}
if (preCollapsePosition)
@@ -1260,10 +1238,10 @@ var CPThemeStatesForSplitViewDivider = @[@"dummy one as CPSplitViewDividerStyle
[self _updateRatios];
if (SPLIT_VIEW_DID_SUPPRESS_RESIZE_NOTIFICATION())
if ([self _didSuppressResizeNotifications])
[self _postNotificationDidResize];
SPLIT_VIEW_SUPPRESS_RESIZE_NOTIFICATIONS(NO);
[self _setResizeNotificationsSuppressed:NO];
}
/*!
@@ -1486,6 +1464,36 @@ var CPThemeStatesForSplitViewDivider = @[@"dummy one as CPSplitViewDividerStyle
return @"CPSplitView Subview Precollapse Positions " + theAutosaveName;
}
- (void)_maybePostWillResizeNotification
{
if ((_suppressResizeNotificationsMask & DidPostWillResizeNotification) === 0)
{
[self _postNotificationWillResize];
_suppressResizeNotificationsMask |= DidPostWillResizeNotification;
}
}
- (void)_maybePostDidResizeNotification
{
if ((_suppressResizeNotificationsMask & ShouldSuppressResizeNotifications) !== 0)
_suppressResizeNotificationsMask |= DidSuppressResizeNotification;
else
[self _postNotificationDidResize];
}
- (BOOL)_didSuppressResizeNotifications
{
return ((_suppressResizeNotificationsMask & DidSuppressResizeNotification) !== 0);
}
- (void)_setResizeNotificationsSuppressed:(BOOL)shouldSuppress
{
if (shouldSuppress)
_suppressResizeNotificationsMask |= ShouldSuppressResizeNotifications;
else
_suppressResizeNotificationsMask = 0;
}
@end
// MARK: -
@@ -1899,4 +1907,5 @@ var CPSplitViewDelegateKey = @"CPSplitViewDelegateKey",
[self setDividerStyle:(shouldBePaneSplitter ? CPSplitViewDividerStylePaneSplitter : CPSplitViewDividerStyleThin)];
}
@end
+31 -29
View File
@@ -62,7 +62,8 @@ CPCanvasStringSizingIsFunctional = NO;
if ([self class] != [CPString class])
return;
#if PLATFORM(DOM)
if (!CPDOMAvailable) return;
if (CPFeatureIsCompatible(CPHTMLCanvasFeature))
{
if (!CPStringSizeMeasuringContext)
@@ -73,46 +74,47 @@ CPCanvasStringSizingIsFunctional = NO;
CPCanvasStringSizingIsFunctional = NO;
}
#endif
}
- (CGSize)sizeWithFont:(CPFont)aFont inWidth:(float)aWidth
{
var size;
#if PLATFORM(DOM)
var sizeCacheForFont = CPStringSizeWithFontInWidthCache[self];
if (sizeCacheForFont === undefined)
sizeCacheForFont = CPStringSizeWithFontInWidthCache[self] = [];
var cssString = [aFont cssString],
cacheKey = cssString + '_' + (aWidth ? aWidth : '0');
size = sizeCacheForFont[cacheKey];
if (size !== undefined && sizeCacheForFont.hasOwnProperty(cacheKey))
return CGSizeMakeCopy(size);
if (!CPCanvasStringSizingIsFunctional || aWidth)
size = [CPPlatformString sizeOfString:self withFont:aFont forWidth:aWidth];
else
if (CPDOMAvailable)
{
if (CPPlatformHasBug(CPTextSizingAlwaysNeedsSetFontBug) || CPStringSizeMeasuringContext.font !== cssString)
CPStringSizeMeasuringContext.font = cssString;
var sizeCacheForFont = CPStringSizeWithFontInWidthCache[self];
var fontHeight = CPStringSizeWithFontHeightCache[cssString];
if (sizeCacheForFont === undefined)
sizeCacheForFont = CPStringSizeWithFontInWidthCache[self] = [];
if (fontHeight === undefined)
fontHeight = CPStringSizeWithFontHeightCache[cssString] = [aFont defaultLineHeightForFont];
var cssString = [aFont cssString],
cacheKey = cssString + '_' + (aWidth ? aWidth : '0');
size = CGSizeMake(CPStringSizeMeasuringContext.measureText(self).width, fontHeight);
size = sizeCacheForFont[cacheKey];
if (size !== undefined && sizeCacheForFont.hasOwnProperty(cacheKey))
return CGSizeMakeCopy(size);
if (!CPCanvasStringSizingIsFunctional || aWidth)
size = [CPPlatformString sizeOfString:self withFont:aFont forWidth:aWidth];
else
{
if (CPPlatformHasBug(CPTextSizingAlwaysNeedsSetFontBug) || CPStringSizeMeasuringContext.font !== cssString)
CPStringSizeMeasuringContext.font = cssString;
var fontHeight = CPStringSizeWithFontHeightCache[cssString];
if (fontHeight === undefined)
fontHeight = CPStringSizeWithFontHeightCache[cssString] = [aFont defaultLineHeightForFont];
size = CGSizeMake(CPStringSizeMeasuringContext.measureText(self).width, fontHeight);
}
sizeCacheForFont[cacheKey] = size;
}
else
size = CGSizeMake(0, 0);
sizeCacheForFont[cacheKey] = size;
#else
size = CGSizeMake(0, 0);
#endif
return CGSizeMakeCopy(size);
}
-2
View File
@@ -982,8 +982,6 @@ var CPTabViewItemsKey = "CPTabViewItemsKey",
@end
# pragma mark -
// This subclass of CPSegmentedControl implements specific behaviour needed by CPTabView, which
// differs in some ways from normal CPSegmentedControl habits :
//
+61 -44
View File
@@ -119,15 +119,6 @@ CPTableViewReverseSequentialColumnAutoresizingStyle = 3;
CPTableViewLastColumnOnlyAutoresizingStyle = 4;
CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
#define NUMBER_OF_COLUMNS() (_tableColumns.length)
#define UPDATE_COLUMN_RANGES_IF_NECESSARY() \
if (_dirtyTableColumnRangeIndex !== CPNotFound) \
[self _recalculateTableColumnRanges];
#define FULL_ROW_HEIGHT() (_rowHeight + _intercellSpacing.height)
#define ROW_BOTTOM(__heightInfo) (__heightInfo.y + __heightInfo.height + _intercellSpacing.height)
#define HAS_VARIABLE_ROW_HEIGHTS() (_implementedDelegateMethods & CPTableViewDelegate_tableView_heightOfRow_)
@protocol CPTableViewDataSource <CPObject>
@optional
@@ -1105,9 +1096,9 @@ NOT YET IMPLEMENTED
[aTableColumn setTableView:self];
if (_dirtyTableColumnRangeIndex < 0)
_dirtyTableColumnRangeIndex = NUMBER_OF_COLUMNS() - 1;
_dirtyTableColumnRangeIndex = [self _numberOfColumns] - 1;
else
_dirtyTableColumnRangeIndex = MIN(NUMBER_OF_COLUMNS() - 1, _dirtyTableColumnRangeIndex);
_dirtyTableColumnRangeIndex = MIN([self _numberOfColumns] - 1, _dirtyTableColumnRangeIndex);
if ([[self sortDescriptors] count] > 0)
{
@@ -1280,7 +1271,7 @@ NOT YET IMPLEMENTED
- (CPInteger)columnWithIdentifier:(CPString)anIdentifier
{
var index = 0,
count = NUMBER_OF_COLUMNS();
count = [self _numberOfColumns];
for (; index < count; ++index)
if ([_tableColumns[index] identifier] === anIdentifier)
@@ -1625,7 +1616,7 @@ NOT YET IMPLEMENTED
*/
- (int)numberOfColumns
{
return NUMBER_OF_COLUMNS();
return [self _numberOfColumns];
}
/*!
@@ -1744,7 +1735,7 @@ NOT YET IMPLEMENTED
_numberOfHiddenColumns = 0;
var index = _dirtyTableColumnRangeIndex,
count = NUMBER_OF_COLUMNS(),
count = [self _numberOfColumns],
x = index === 0 ? 0.0 : CPMaxRange(_tableColumnRanges[index - 1]);
for (; index < count; ++index)
@@ -1784,13 +1775,13 @@ NOT YET IMPLEMENTED
// Coerce aColumnIndex to a number in case it is a string.
aColumnIndex = +aColumnIndex;
if (aColumnIndex < 0 || aColumnIndex >= NUMBER_OF_COLUMNS())
if (aColumnIndex < 0 || aColumnIndex >= [self _numberOfColumns])
return CGRectMakeZero();
if ([[_tableColumns objectAtIndex:aColumnIndex] isHidden])
return CGRectMakeZero();
UPDATE_COLUMN_RANGES_IF_NECESSARY();
[self _updateColumnRangesIfNecessary];
var range = _tableColumnRanges[aColumnIndex];
@@ -1819,7 +1810,7 @@ NOT YET IMPLEMENTED
height,
fixedHeightRows = 0;
if (HAS_VARIABLE_ROW_HEIGHTS())
if ([self _hasVariableRowHeights])
{
[self _populateRowHeightCacheIfNeeded];
@@ -1835,12 +1826,12 @@ NOT YET IMPLEMENTED
}
else
{
height = FULL_ROW_HEIGHT();
height = [self _fullRowHeight];
if (_numberOfRows > 0)
{
heightInfo = _cachedRowHeights[lastIndex];
y = ROW_BOTTOM(heightInfo);
y = [self _rowBottomOfHeightInfo:heightInfo];
// y is now at the top of the first row beyond the last valid row.
// Add the height of any rows beyond that.
@@ -1851,10 +1842,10 @@ NOT YET IMPLEMENTED
else
{
fixedHeightRows = aRowIndex;
height = FULL_ROW_HEIGHT();
height = [self _fullRowHeight];
}
y += fixedHeightRows * FULL_ROW_HEIGHT();
y += fixedHeightRows * [self _fullRowHeight];
return CGRectMake(0.0, y, CGRectGetWidth([self bounds]), height);
}
@@ -1921,7 +1912,7 @@ NOT YET IMPLEMENTED
if (bottomOfRealRows >= rectBottom)
return rowRange;
var numberOfSynthesizedRows = CEIL((rectBottom - bottomOfRealRows) / FULL_ROW_HEIGHT());
var numberOfSynthesizedRows = CEIL((rectBottom - bottomOfRealRows) / [self _fullRowHeight]);
rowRange.length += numberOfSynthesizedRows;
@@ -1943,7 +1934,7 @@ NOT YET IMPLEMENTED
lastColumn = [self columnAtPoint:CGPointMake(CGRectGetMaxX(aRect), 0.0)];
if (lastColumn === CPNotFound)
lastColumn = NUMBER_OF_COLUMNS() - 1;
lastColumn = [self _numberOfColumns] - 1;
// Don't bother doing the expensive removal of hidden indexes if we have no hidden columns.
if (_numberOfHiddenColumns <= 0)
@@ -1978,7 +1969,7 @@ NOT YET IMPLEMENTED
if (!CGRectContainsPoint(bounds, aPoint))
return CPNotFound;
UPDATE_COLUMN_RANGES_IF_NECESSARY();
[self _updateColumnRangesIfNecessary];
var x = aPoint.x,
low = 0,
@@ -2031,13 +2022,13 @@ NOT YET IMPLEMENTED
// aPoint.x is in bounds, now we just have to check aPoint.y
if (HAS_VARIABLE_ROW_HEIGHTS())
if ([self _hasVariableRowHeights])
{
// First make sure aPoint.y is above the bottom of the last row, otherwise we might
// search the (potentially large number of) rows for nothing.
var heightInfo = [_cachedRowHeights lastObject];
if (!heightInfo || aPoint.y >= ROW_BOTTOM(heightInfo))
if (!heightInfo || aPoint.y >= [self _rowBottomOfHeightInfo:heightInfo])
return -1;
return [_cachedRowHeights indexOfObject:aPoint
@@ -2048,7 +2039,7 @@ NOT YET IMPLEMENTED
if (aPoint.y < heightInfo.y)
return CPOrderedAscending;
if (aPoint.y > ROW_BOTTOM(heightInfo))
if (aPoint.y > [self _rowBottomOfHeightInfo:heightInfo])
return CPOrderedDescending;
return CPOrderedSame;
@@ -2056,7 +2047,7 @@ NOT YET IMPLEMENTED
}
else
{
var row = FLOOR(aPoint.y / FULL_ROW_HEIGHT());
var row = FLOOR(aPoint.y / [self _fullRowHeight]);
return row >= _numberOfRows ? -1 : row;
}
@@ -2163,7 +2154,7 @@ NOT YET IMPLEMENTED
*/
- (CGRect)frameOfDataViewAtColumn:(CPInteger)aColumn row:(CPInteger)aRow
{
UPDATE_COLUMN_RANGES_IF_NECESSARY();
[self _updateColumnRangesIfNecessary];
if (aColumn > [self numberOfColumns] || aRow > [self numberOfRows])
return CGRectMakeZero();
@@ -2225,9 +2216,9 @@ NOT YET IMPLEMENTED
if (!superview)
return;
UPDATE_COLUMN_RANGES_IF_NECESSARY();
[self _updateColumnRangesIfNecessary];
var count = NUMBER_OF_COLUMNS(),
var count = [self _numberOfColumns],
columnToResize = nil,
totalWidth = 0,
i = 0;
@@ -2271,10 +2262,10 @@ NOT YET IMPLEMENTED
if (!superview || ![superview isKindOfClass:[CPClipView class]])
return;
UPDATE_COLUMN_RANGES_IF_NECESSARY();
[self _updateColumnRangesIfNecessary];
var superviewWidth = [superview bounds].size.width,
count = NUMBER_OF_COLUMNS(),
count = [self _numberOfColumns],
resizableColumns = [CPIndexSet indexSet],
remainingSpace = 0.0,
i = 0;
@@ -2370,9 +2361,9 @@ NOT YET IMPLEMENTED
var superviewSize = [superview bounds].size;
UPDATE_COLUMN_RANGES_IF_NECESSARY();
[self _updateColumnRangesIfNecessary];
var count = NUMBER_OF_COLUMNS();
var count = [self _numberOfColumns];
// Decrement the counter until we get to the last column that's not hidden
while (count-- && [_tableColumns[count] isHidden]);
@@ -2440,7 +2431,7 @@ NOT YET IMPLEMENTED
*/
- (void)_noteHeightOfRowsWithIndexesChanged:(CPIndexSet)anIndexSet
{
if (!HAS_VARIABLE_ROW_HEIGHTS())
if (![self _hasVariableRowHeights])
return;
// Update the height of the given rows by calling the delegate. Since the row height cache also contains
@@ -2482,21 +2473,21 @@ NOT YET IMPLEMENTED
*/
- (void)tile
{
UPDATE_COLUMN_RANGES_IF_NECESSARY();
[self _updateColumnRangesIfNecessary];
var width = _tableColumnRanges.length > 0 ? CPMaxRange([_tableColumnRanges lastObject]) : 0.0,
superview = [self superview],
height = 0;
if (!HAS_VARIABLE_ROW_HEIGHTS())
height = FULL_ROW_HEIGHT() * _numberOfRows;
if (![self _hasVariableRowHeights])
height = [self _fullRowHeight] * _numberOfRows;
else if (_numberOfRows > 0)
{
[self _populateRowHeightCacheIfNeeded];
var heightInfo = _cachedRowHeights[_cachedRowHeights.length - 1];
height = ROW_BOTTOM(heightInfo);
height = [self _rowBottomOfHeightInfo:heightInfo];
}
if ([superview isKindOfClass:[CPClipView class]])
@@ -3606,7 +3597,7 @@ Your delegate can implement this method to avoid subclassing the tableview to ad
if (![rowIndexes count] || ![columnIndexes count])
return;
UPDATE_COLUMN_RANGES_IF_NECESSARY();
[self _updateColumnRangesIfNecessary];
if (_numberOfHiddenColumns > 0)
columnIndexes = [columnIndexes indexesPassingTest:function(idx, stop)
@@ -3829,9 +3820,9 @@ Your delegate can implement this method to avoid subclassing the tableview to ad
[CPException raise:CPInvalidArgumentException
reason:@"Row " + row + " out of row range [0-" + (_numberOfRows - 1) + "] for rowViewAtRow:createIfNeeded:"];
if (column > (NUMBER_OF_COLUMNS() - 1))
if (column > ([self _numberOfColumns] - 1))
[CPException raise:CPInvalidArgumentException
reason:@"Column " + column + " out of row range [0-" + (NUMBER_OF_COLUMNS ()- 1) + "] for rowViewAtRow:createIfNeeded:"];
reason:@"Column " + column + " out of row range [0-" + ([self _numberOfColumns]- 1) + "] for rowViewAtRow:createIfNeeded:"];
var dataViewsForRow = _dataViewsForRows[row],
tableColumn = _tableColumns[column],
@@ -4207,7 +4198,7 @@ Your delegate can implement this method to avoid subclassing the tableview to ad
if (_rowHeight > 0.0)
{
var rowHeight = FULL_ROW_HEIGHT(),
var rowHeight = [self _fullRowHeight],
totalHeight = CGRectGetMaxY(aRect) - lineThickness / 2;
while (rowY < totalHeight)
@@ -5615,6 +5606,31 @@ Your delegate can implement this method to avoid subclassing the tableview to ad
[self scrollRowToVisible:i];
}
- (int)_numberOfColumns
{
return _tableColumns.length;
}
- (void)_updateColumnRangesIfNecessary
{
if (_dirtyTableColumnRangeIndex !== CPNotFound)
[self _recalculateTableColumnRanges];
}
- (CGFloat)_fullRowHeight
{
return (_rowHeight + _intercellSpacing.height);
}
- (CGFloat)_rowBottomOfHeightInfo:(JSObject)heightInfo
{
return (heightInfo.y + heightInfo.height + _intercellSpacing.height);
}
- (BOOL)_hasVariableRowHeights
{
return (_implementedDelegateMethods & CPTableViewDelegate_tableView_heightOfRow_);
}
@end
@@ -6532,4 +6548,5 @@ var CPTableViewDataSourceKey = @"CPTableViewDataSourceKey",
return "<" + [self className] + " 0x" + [CPString stringWithHash:[self UID]] + " identifier=" + [self identifier] + ">";
}
@end
+206 -209
View File
@@ -279,9 +279,10 @@ CPTextFieldStatePlaceholder = CPThemeState("placeholder");
// MARK: -
#if PLATFORM(DOM)
- (DOMElement)_inputElement
{
if (!CPDOMAvailable) return nil;
if (!CPTextFieldDOMTextAreaElement)
{
CPTextFieldDOMTextAreaElement = document.createElement("textarea");
@@ -384,7 +385,6 @@ CPTextFieldStatePlaceholder = CPThemeState("placeholder");
return CPTextFieldDOMCurrentElement;
}
#endif
- (id)initWithFrame:(CGRect)aFrame
{
@@ -675,123 +675,122 @@ CPTextFieldStatePlaceholder = CPThemeState("placeholder");
_stringValue = [self stringValue];
#if PLATFORM(DOM)
[self _setCSSStyleForInputElement];
var element = [self _inputElement];
element.value = _stringValue;
if (element.parentNode !== _DOMElement)
if (CPDOMAvailable)
{
var previousOwner = CPTextFieldInputOwner;
[self _setCSSStyleForInputElement];
// Otherwise Chrome will fire the blur during appendChild (NotFoundError).
_CPTextFieldDetachInputElement(element);
var element = [self _inputElement];
element.value = _stringValue;
try
if (element.parentNode !== _DOMElement)
{
_DOMElement.appendChild(element);
}
catch (e)
{
// Race with the Blur-Handler: retry once and yield silently.
var previousOwner = CPTextFieldInputOwner;
// Otherwise Chrome will fire the blur during appendChild (NotFoundError).
_CPTextFieldDetachInputElement(element);
try
{
_DOMElement.appendChild(element);
}
catch (e2)
catch (e)
{
[self unsetThemeState:CPThemeStateEditing];
[self _updatePlaceholderState];
[self setNeedsLayout];
return NO;
// Race with the Blur-Handler: retry once and yield silently.
_CPTextFieldDetachInputElement(element);
try
{
_DOMElement.appendChild(element);
}
catch (e2)
{
[self unsetThemeState:CPThemeStateEditing];
[self _updatePlaceholderState];
[self setNeedsLayout];
return NO;
}
}
if (previousOwner && previousOwner !== self)
{
[previousOwner unsetThemeState:CPThemeStateEditing];
[previousOwner setNeedsLayout];
}
}
if (previousOwner && previousOwner !== self)
CPTextFieldInputIsActive = YES;
if (document.attachEvent)
{
[previousOwner unsetThemeState:CPThemeStateEditing];
[previousOwner setNeedsLayout];
CPTextFieldCachedSelectStartFunction = [[self window] platformWindow]._DOMBodyElement.onselectstart;
CPTextFieldCachedDragFunction = [[self window] platformWindow]._DOMBodyElement.ondrag;
[[self window] platformWindow]._DOMBodyElement.ondrag = function () {};
[[self window] platformWindow]._DOMBodyElement.onselectstart = function () {};
}
}
CPTextFieldInputIsActive = YES;
CPTextFieldInputOwner = self;
if (document.attachEvent)
{
CPTextFieldCachedSelectStartFunction = [[self window] platformWindow]._DOMBodyElement.onselectstart;
CPTextFieldCachedDragFunction = [[self window] platformWindow]._DOMBodyElement.ondrag;
[[self window] platformWindow]._DOMBodyElement.ondrag = function () {};
[[self window] platformWindow]._DOMBodyElement.onselectstart = function () {};
}
CPTextFieldInputOwner = self;
[[CPRunLoop mainRunLoop] performBlock:function()
{
if (CPTextFieldInputOwner !== self)
return;
// This will prevent to jump to the focused element
var previousScrollingOrigin = [self _scrollToVisibleRectAndReturnPreviousOrigin];
element.focus();
[self _restorePreviousScrollingOrigin:previousScrollingOrigin];
// Select the text if the textfield became first responder through keyboard interaction
if (!_willBecomeFirstResponderByClick)
[[CPRunLoop mainRunLoop] performBlock:function()
{
[self _selectText:self immediately:YES];
}
else
{
var x = [self convertPointFromBase:[[CPApp currentEvent] locationInWindow]].x,
contentInset = [self currentValueForThemeAttribute:@"content-inset"],
text = [self stringValue],
font = [self font];
if (CPTextFieldInputOwner !== self)
return;
switch ([self alignment]) {
case CPCenterTextAlignment:
// This will prevent to jump to the focused element
var previousScrollingOrigin = [self _scrollToVisibleRectAndReturnPreviousOrigin];
var contentWidth = [self bounds].size.width - contentInset.left - contentInset.right,
textWidth = [text sizeWithFont:font].width;
element.focus();
x -= (contentWidth - textWidth) / 2 + contentInset.left;
[self _restorePreviousScrollingOrigin:previousScrollingOrigin];
break;
// Select the text if the textfield became first responder through keyboard interaction
if (!_willBecomeFirstResponderByClick)
{
[self _selectText:self immediately:YES];
}
else
{
var x = [self convertPointFromBase:[[CPApp currentEvent] locationInWindow]].x,
contentInset = [self currentValueForThemeAttribute:@"content-inset"],
text = [self stringValue],
font = [self font];
case CPRightTextAlignment:
switch ([self alignment]) {
case CPCenterTextAlignment:
var contentWidth = [self bounds].size.width - contentInset.left - contentInset.right,
textWidth = [text sizeWithFont:font].width;
var contentWidth = [self bounds].size.width - contentInset.left - contentInset.right,
textWidth = [text sizeWithFont:font].width;
x -= (contentWidth - textWidth) + contentInset.left;
x -= (contentWidth - textWidth) / 2 + contentInset.left;
break;
break;
default: // CPLeftTextAlignment, CPJustifiedTextAlignment, CPNaturalTextAlignment
case CPRightTextAlignment:
x -= contentInset.left;
var contentWidth = [self bounds].size.width - contentInset.left - contentInset.right,
textWidth = [text sizeWithFont:font].width;
break;
x -= (contentWidth - textWidth) + contentInset.left;
break;
default: // CPLeftTextAlignment, CPJustifiedTextAlignment, CPNaturalTextAlignment
x -= contentInset.left;
break;
}
var position = [CPPlatformString charPositionOfString:text withFont:font forPoint:CGPointMake(x, 0)];
[self setSelectedRange:CPMakeRange(position, 0)];
}
var position = [CPPlatformString charPositionOfString:text withFont:font forPoint:CGPointMake(x, 0)];
_willBecomeFirstResponderByClick = NO;
[self setSelectedRange:CPMakeRange(position, 0)];
}
_willBecomeFirstResponderByClick = NO;
[self textDidFocus:[CPNotification notificationWithName:CPTextFieldDidFocusNotification object:self userInfo:nil]];
} argument:nil order:0 modes:[CPDefaultRunLoopMode]];
#endif
[self textDidFocus:[CPNotification notificationWithName:CPTextFieldDidFocusNotification object:self userInfo:nil]];
} argument:nil order:0 modes:[CPDefaultRunLoopMode]];
}
return YES;
}
@@ -802,13 +801,14 @@ CPTextFieldStatePlaceholder = CPThemeState("placeholder");
*/
- (void)_setEnableCSSSelection:(BOOL)shouldEnable
{
#if PLATFORM (DOM)
if (!CPDOMAvailable)
return;
if (CPTexFieldCurrentCSSSelectableField)
CPTexFieldCurrentCSSSelectableField._DOMElement.style[CPBrowserStyleProperty(@"user-select")] = @"none";
CPTexFieldCurrentCSSSelectableField = self;
_DOMElement.style[CPBrowserStyleProperty(@"user-select")] = shouldEnable ? @"text" : @"none";
#endif
}
/*!
@@ -817,7 +817,8 @@ CPTextFieldStatePlaceholder = CPThemeState("placeholder");
*/
- (void)_setCSSStyleForInputElement
{
#if PLATFORM(DOM)
if (!CPDOMAvailable)
return;
var element = [self _inputElement],
font = [self font],
@@ -886,41 +887,40 @@ CPTextFieldStatePlaceholder = CPThemeState("placeholder");
if (isTextArea)
element.style.whiteSpace = _wraps ? "pre" : "nowrap";
#endif
}
/*! @ignore */
- (BOOL)resignFirstResponder
{
#if PLATFORM(DOM)
// We might have been the first responder without actually editing.
if (_isEditing && CPTextFieldInputOwner === self)
if (CPDOMAvailable)
{
var element = [self _inputElement],
newValue = element.value,
error = @"";
if (newValue !== _stringValue)
// We might have been the first responder without actually editing.
if (_isEditing && CPTextFieldInputOwner === self)
{
[self _setStringValue:newValue];
}
var element = [self _inputElement],
newValue = element.value,
error = @"";
// If there is a formatter, always give it a chance to reject the resignation,
// even if the value has not changed.
if ([self _valueIsValid:newValue] === NO)
{
// This will prevent to jump to the focused element
var previousScrollingOrigin = [self _scrollToVisibleRectAndReturnPreviousOrigin];
if (newValue !== _stringValue)
{
[self _setStringValue:newValue];
}
element.focus();
// If there is a formatter, always give it a chance to reject the resignation,
// even if the value has not changed.
if ([self _valueIsValid:newValue] === NO)
{
// This will prevent to jump to the focused element
var previousScrollingOrigin = [self _scrollToVisibleRectAndReturnPreviousOrigin];
[self _restorePreviousScrollingOrigin:previousScrollingOrigin];
element.focus();
return NO;
[self _restorePreviousScrollingOrigin:previousScrollingOrigin];
return NO;
}
}
}
#endif
// When we are no longer the first responder we don't worry about the key status of our window anymore.
[self _setObserveWindowKeyNotifications:NO];
@@ -955,7 +955,7 @@ CPTextFieldStatePlaceholder = CPThemeState("placeholder");
[self _updatePlaceholderState];
[self setNeedsLayout];
#if PLATFORM(DOM)
if (!CPDOMAvailable) return;
var element = [self _inputElement];
@@ -998,8 +998,6 @@ CPTextFieldStatePlaceholder = CPThemeState("placeholder");
CPTextFieldCachedSelectStartFunction = nil;
CPTextFieldCachedDragFunction = nil;
}
#endif
}
- (void)_setObserveWindowKeyNotifications:(BOOL)shouldObserve
@@ -1056,42 +1054,41 @@ CPTextFieldStatePlaceholder = CPThemeState("placeholder");
- (BOOL)_valueIsValid:(CPString)aValue
{
#if PLATFORM(DOM)
var error = @"";
if ([self _setStringValue:aValue isNewValue:NO errorDescription:@ref(error)] === NO)
if (CPDOMAvailable)
{
var acceptInvalidValue = NO;
var error = @"";
if (_implementedDelegateMethods & CPTextFieldDelegate_control_didFailToFormatString_errorDescription_)
if ([self _setStringValue:aValue isNewValue:NO errorDescription:@ref(error)] === NO)
{
var currentEvent = [CPApp currentEvent];
var acceptInvalidValue = NO;
if (currentEvent &&
CPTextFieldLastValidationFailureField === self &&
CPTextFieldLastValidationFailureString === aValue &&
CPTextFieldLastValidationFailureEvent === currentEvent)
if (_implementedDelegateMethods & CPTextFieldDelegate_control_didFailToFormatString_errorDescription_)
{
acceptInvalidValue = CPTextFieldLastValidationFailureResult;
}
else
{
acceptInvalidValue = [_delegate control:self didFailToFormatString:aValue errorDescription:error];
var currentEvent = [CPApp currentEvent];
CPTextFieldLastValidationFailureField = self;
CPTextFieldLastValidationFailureString = aValue;
CPTextFieldLastValidationFailureEvent = currentEvent;
CPTextFieldLastValidationFailureResult = acceptInvalidValue;
if (currentEvent &&
CPTextFieldLastValidationFailureField === self &&
CPTextFieldLastValidationFailureString === aValue &&
CPTextFieldLastValidationFailureEvent === currentEvent)
{
acceptInvalidValue = CPTextFieldLastValidationFailureResult;
}
else
{
acceptInvalidValue = [_delegate control:self didFailToFormatString:aValue errorDescription:error];
CPTextFieldLastValidationFailureField = self;
CPTextFieldLastValidationFailureString = aValue;
CPTextFieldLastValidationFailureEvent = currentEvent;
CPTextFieldLastValidationFailureResult = acceptInvalidValue;
}
}
if (acceptInvalidValue === NO)
return NO;
}
if (acceptInvalidValue === NO)
return NO;
}
#endif
return YES;
}
@@ -1199,17 +1196,18 @@ CPTextFieldStatePlaceholder = CPThemeState("placeholder");
if (!([self isEnabled] && [self isEditable]))
return;
#if PLATFORM(DOM)
var newValue = [self _inputElement].value;
if (newValue !== _stringValue)
if (CPDOMAvailable)
{
[self _setStringValue:newValue];
[self _didEdit];
}
var newValue = [self _inputElement].value;
[[[self window] platformWindow] _propagateCurrentDOMEvent:YES];
#endif
if (newValue !== _stringValue)
{
[self _setStringValue:newValue];
[self _didEdit];
}
[[[self window] platformWindow] _propagateCurrentDOMEvent:YES];
}
}
- (void)keyDown:(CPEvent)anEvent
@@ -1306,7 +1304,8 @@ CPTextFieldStatePlaceholder = CPThemeState("placeholder");
if (!([self isEnabled] && [self isEditable]))
return;
#if PLATFORM(DOM)
if (!CPDOMAvailable)
return;
var oldValue = _stringValue,
range = [self selectedRange],
@@ -1324,8 +1323,6 @@ CPTextFieldStatePlaceholder = CPThemeState("placeholder");
{
[self _didEdit];
}
#endif
}
- (void)textDidBlur:(CPNotification)note
@@ -1478,13 +1475,9 @@ CPTextFieldStatePlaceholder = CPThemeState("placeholder");
else
_stringValue = [self stringValue];
#if PLATFORM(DOM)
if ((CPTextFieldInputOwner === self || [[self window] firstResponder] === self) && [[self window] isKeyWindow])
if (CPDOMAvailable && (CPTextFieldInputOwner === self || [[self window] firstResponder] === self) && [[self window] isKeyWindow])
[self _inputElement].value = _stringValue;
#endif
[self _updatePlaceholderState];
}
@@ -1614,31 +1607,34 @@ CPTextFieldStatePlaceholder = CPThemeState("placeholder");
{
var wind = [self window];
#if PLATFORM(DOM)
if ([self isEditable])
if (CPDOMAvailable)
{
var element = [self _inputElement];
if ([wind firstResponder] === self)
if ([self isEditable])
{
if (immediately)
element.select();
else
[[CPRunLoop mainRunLoop] performBlock:function(){ element.select(); } argument:nil order:0 modes:[CPDefaultRunLoopMode]];
var element = [self _inputElement];
if ([wind firstResponder] === self)
{
if (immediately)
element.select();
else
[[CPRunLoop mainRunLoop] performBlock:function(){ element.select(); } argument:nil order:0 modes:[CPDefaultRunLoopMode]];
}
else if (wind != nil && [wind makeFirstResponder:self])
[self _selectText:sender immediately:immediately];
}
else
{
[self setSelectedRange:CPMakeRange(0, _stringValue.length)];
}
else if (wind != nil && [wind makeFirstResponder:self])
[self _selectText:sender immediately:immediately];
}
else
{
[self setSelectedRange:CPMakeRange(0, _stringValue.length)];
// Even if we can't actually select the text we need to preserve the first
// responder side effect.
if (wind != nil && [wind firstResponder] !== self)
[wind makeFirstResponder:self];
}
#else
// Even if we can't actually select the text we need to preserve the first
// responder side effect.
if (wind != nil && [wind firstResponder] !== self)
[wind makeFirstResponder:self];
#endif
}
}
@@ -1661,9 +1657,10 @@ CPTextFieldStatePlaceholder = CPThemeState("placeholder");
{
// selectedRange won't work if we're displaying our text using a <div>. Instead we have to ask the browser
// what's selected and hope it's right in a Cappuccino context as well.
#if PLATFORM(DOM)
stringToCopy = [[[self window] platformWindow] _selectedText];
#endif
if (CPDOMAvailable)
{
stringToCopy = [[[self window] platformWindow] _selectedText];
}
}
var pasteboard = [CPPasteboard generalPasteboard];
@@ -1743,35 +1740,34 @@ CPTextFieldStatePlaceholder = CPThemeState("placeholder");
if ([[self window] firstResponder] !== self)
return CPMakeRange(0, 0);
#if PLATFORM(DOM)
// we wrap this in try catch because firefox will throw an exception in certain instances
try
if (CPDOMAvailable)
{
var inputElement = [self _inputElement],
selectionStart = inputElement.selectionStart,
selectionEnd = inputElement.selectionEnd;
if ([selectionStart isKindOfClass:CPNumber])
return CPMakeRange(selectionStart, selectionEnd - selectionStart);
// browsers which don't support selectionStart/selectionEnd (aka IE).
var theDocument = inputElement.ownerDocument || inputElement.document,
selectionRange = theDocument.selection.createRange(),
range = inputElement.createTextRange();
if (range.inRange(selectionRange))
// we wrap this in try catch because firefox will throw an exception in certain instances
try
{
range.setEndPoint('EndToStart', selectionRange);
return CPMakeRange(range.text.length, selectionRange.text.length);
var inputElement = [self _inputElement],
selectionStart = inputElement.selectionStart,
selectionEnd = inputElement.selectionEnd;
if ([selectionStart isKindOfClass:CPNumber])
return CPMakeRange(selectionStart, selectionEnd - selectionStart);
// browsers which don't support selectionStart/selectionEnd (aka IE).
var theDocument = inputElement.ownerDocument || inputElement.document,
selectionRange = theDocument.selection.createRange(),
range = inputElement.createTextRange();
if (range.inRange(selectionRange))
{
range.setEndPoint('EndToStart', selectionRange);
return CPMakeRange(range.text.length, selectionRange.text.length);
}
}
catch (e)
{
// fall through to the return
}
}
catch (e)
{
// fall through to the return
}
#endif
return CPMakeRange(0, 0);
}
@@ -1781,7 +1777,8 @@ CPTextFieldStatePlaceholder = CPThemeState("placeholder");
if (![[self window] firstResponder] === self)
return;
#if PLATFORM(DOM)
if (!CPDOMAvailable)
return;
if (![self isEditable])
{
@@ -1825,7 +1822,6 @@ CPTextFieldStatePlaceholder = CPThemeState("placeholder");
{
}
}
#endif
}
- (void)selectAll:(id)sender
@@ -1899,10 +1895,11 @@ CPTextFieldStatePlaceholder = CPThemeState("placeholder");
[self _setObjectValue:newValue useFormatter:NO];
[self setSelectedRange:CPMakeRange(range.location, 0)];
#if PLATFORM(DOM)
// Since we just performed the deletion manually, we don't need the browser to do anything else.
[[[self window] platformWindow] _propagateCurrentDOMEvent:NO];
#endif
if (CPDOMAvailable)
{
// Since we just performed the deletion manually, we don't need the browser to do anything else.
[[[self window] platformWindow] _propagateCurrentDOMEvent:NO];
}
}
[self _didEdit];
+7 -8
View File
@@ -25,10 +25,10 @@
*/
@import "CPText.j"
@import "CPTextContainer.j"
@import "CGContext.j"
@import "CPTypesetter.j"
@import "CPFont.j"
@import "CPCompatibility.j"
@global _MakeRangeFromAbs
@global document
@@ -298,9 +298,10 @@ _oncontextmenuhandler = function () { return false; };
[_typesetter layoutGlyphsInLayoutManager:self startingAtGlyphIndex:startIndex maxNumberOfLineFragments:-1 nextGlyphIndex:nil];
#if PLATFORM(DOM)
[self _cleanUpDOM];
#endif
if (CPDOMAvailable)
{
[self _cleanUpDOM];
}
_isValidatingLayoutAndGlyphs = NO;
}
@@ -1146,7 +1147,8 @@ var _objectsInRange = function(aList, aRange)
if (!aString || aString.length === 0)
return nil;
#if PLATFORM(DOM)
if (!CPDOMAvailable) return nil;
var style,
span = document.createElement("span");
@@ -1197,9 +1199,6 @@ var _objectsInRange = function(aList, aRange)
span.textContent = aString;
return span;
#else
return nil;
#endif
}
- (id)initWithRange:(CPRange)aRange textContainer:(CPTextContainer)aContainer textStorage:(CPTextStorage)textStorage
+53 -49
View File
@@ -29,14 +29,13 @@
@import "CPColorPanel.j"
@import "CPFontManager.j"
@import "CPTextStorage.j"
@import "CPTextContainer.j"
@import "CPLayoutManager.j"
@import "CPParagraphStyle.j"
@import "CPTextContainer.j"
@import "_CPRTFParser.j"
@import "_CPRTFProducer.j"
@class CPClipView;
@class CPMenu;
@class _CPSelectionBox;
@@ -149,7 +148,6 @@ var kDelegateRespondsTo_textShouldBeginEditing
int _startTrackingLocation;
_CPCaret _caret;
CPTimer _scrollingTimer;
BOOL _scrollingDownward;
CPRange _movingSelection;
@@ -242,9 +240,10 @@ var kDelegateRespondsTo_textShouldBeginEditing
- (void)_init
{
#if PLATFORM(DOM)
if (CPDOMAvailable)
{
_DOMElement.style.cursor = "text";
#endif
}
_selectionRange = CPMakeRange(0, 0);
_textContainerInset = CGSizeMake(2, 0);
@@ -882,7 +881,9 @@ var kDelegateRespondsTo_textShouldBeginEditing
- (void)drawRect:(CGRect)aRect
{
#if PLATFORM(DOM)
if (!CPDOMAvailable)
return;
var range = [_layoutManager glyphRangeForBoundingRect:aRect inTextContainer:_textContainer];
for (var i = 0; i < [_selectionSpans count]; i++)
@@ -919,7 +920,6 @@ var kDelegateRespondsTo_textShouldBeginEditing
}
else
[_caret setVisibility:NO];
#endif
}
@@ -1031,9 +1031,10 @@ Sets the selection to a range of characters in response to user action.
[_CPNativeInputManager focusForClipboardOfTextView:self];
}
#if PLATFORM(DOM)
- (CGPoint)_cumulativeOffset
{
if (!CPDOMAvailable) return CGPointMake(0, 0);
var top = 0,
left = 0,
element = self._DOMElement;
@@ -1048,7 +1049,6 @@ Sets the selection to a range of characters in response to user action.
return CGPointMake(left, top);
}
#endif
- (CPArray)selectedRanges
{
@@ -3042,8 +3042,9 @@ var CPTextViewAllowsUndoKey = @"CPTextViewAllowsUndoKey",
- (void)_createSpan
{
if (!CPDOMAvailable)
return;
#if PLATFORM(DOM)
_selectionBoxDOM = document.createElement("span");
_selectionBoxDOM.style.position = "absolute";
_selectionBoxDOM.style.visibility = "visible";
@@ -3058,8 +3059,6 @@ var CPTextViewAllowsUndoKey = @"CPTextViewAllowsUndoKey",
_selectionBoxDOM.style.height = (_rect.size.height) + "px";
_selectionBoxDOM.style.zIndex = -1000;
_selectionBoxDOM.oncontextmenu = _selectionBoxDOM.onmousedown = _selectionBoxDOM.onselectstart = function () { return false; };
#endif
}
@end
@@ -3079,36 +3078,38 @@ var CPTextViewAllowsUndoKey = @"CPTextViewAllowsUndoKey",
{
_rect = CGRectCreateCopy(aRect);
#if PLATFORM(DOM)
_caretDOM.style.left = (aRect.origin.x) + "px";
_caretDOM.style.top = (aRect.origin.y) + "px";
_caretDOM.style.height = (aRect.size.height) + "px";
#endif
if (CPDOMAvailable)
{
_caretDOM.style.left = (aRect.origin.x) + "px";
_caretDOM.style.top = (aRect.origin.y) + "px";
_caretDOM.style.height = (aRect.size.height) + "px";
}
}
- (id)initWithTextView:(CPTextView)aView
{
if (self = [super init])
{
#if PLATFORM(DOM)
var style;
if (!_caretDOM)
if (CPDOMAvailable)
{
_caretDOM = document.createElement("span");
style = _caretDOM.style;
style.position = "absolute";
style.visibility = "visible";
style.padding = "0px";
style.margin = "0px";
style.whiteSpace = "pre";
style.backgroundColor = "black";
_caretDOM.style.width = "1px";
_caretDOM.style.zIndex = 10001;
_textView = aView;
_textView._DOMElement.appendChild(_caretDOM);
var style;
if (!_caretDOM)
{
_caretDOM = document.createElement("span");
style = _caretDOM.style;
style.position = "absolute";
style.visibility = "visible";
style.padding = "0px";
style.margin = "0px";
style.whiteSpace = "pre";
style.backgroundColor = "black";
_caretDOM.style.width = "1px";
_caretDOM.style.zIndex = 10001;
_textView = aView;
_textView._DOMElement.appendChild(_caretDOM);
}
}
#endif
}
return self;
@@ -3116,10 +3117,10 @@ var CPTextViewAllowsUndoKey = @"CPTextViewAllowsUndoKey",
- (void)setVisibility:(BOOL)visibilityFlag stop:(BOOL)stopFlag
{
#if PLATFORM(DOM)
_caretDOM.style.visibility = visibilityFlag ? "visible" : "hidden";
#endif
if (CPDOMAvailable)
{
_caretDOM.style.visibility = visibilityFlag ? "visible" : "hidden";
}
if (!visibilityFlag && stopFlag)
[self stopBlinking];
@@ -3184,25 +3185,28 @@ var _CPCopyPlaceholder = '-';
+ (void)isDeadKey:(CPEvent)event
{
#if PLATFORM(DOM)
return event._DOMEvent && (event._DOMEvent.key === 'Dead' || event._DOMEvent.key === 'Process');
#endif
if (CPDOMAvailable)
return event._DOMEvent && (event._DOMEvent.key === 'Dead' || event._DOMEvent.key === 'Process');
return NO;
}
+ (void)cancelCurrentInputSessionIfNeeded
{
#if PLATFORM(DOM)
if (!CPDOMAvailable)
return;
if (_CPNativeInputField) {
_CPNativeInputField.innerHTML = '';
}
_isComposing = NO;
#endif
}
+ (void)initialize
{
#if PLATFORM(DOM)
if (!CPDOMAvailable)
return;
_CPNativeInputField = document.createElement("div");
_CPNativeInputField.contentEditable = YES;
@@ -3380,21 +3384,22 @@ var _CPCopyPlaceholder = '-';
[currentFirstResponder deleteBackward:self];
}, 20);
};
#endif
}
+ (void)focusForTextView:(CPTextView)currentFirstResponder
{
#if PLATFORM(DOM)
if (!CPDOMAvailable)
return;
if (_CPNativeInputField && document.activeElement !== _CPNativeInputField)
_CPNativeInputField.focus();
#endif
}
+ (void)focusForClipboardOfTextView:(CPTextView)textview
{
#if PLATFORM(DOM)
if (!CPDOMAvailable)
return;
var selectedRange = [textview selectedRange];
if (selectedRange.length > 0) {
// Put the selected text into the hidden div so the browser can natively copy it.
@@ -3415,7 +3420,6 @@ var _CPCopyPlaceholder = '-';
selection.removeAllRanges();
selection.addRange(range);
}
#endif
}
@end
+61 -72
View File
@@ -32,6 +32,7 @@
@import "CPText.j"
@import "CPTextField.j"
@import "CPWindow_Constants.j"
@import "CPCompatibility.j"
@class _CPTokenFieldTokenCloseButton
@class _CPTokenFieldTokenDisclosureButton
@@ -63,8 +64,6 @@ var CPTokenFieldDelegate_tokenField_hasMenuForRepresentedObject_
CPTokenFieldDelegate_tokenField_representedObjectForEditingString_ = 1 << 6;
#if PLATFORM(DOM)
var CPTokenFieldDOMInputElement = nil,
CPTokenFieldDOMPasswordInputElement = nil,
CPTokenFieldDOMStandardInputElement = nil,
@@ -79,8 +78,6 @@ var CPTokenFieldDOMInputElement = nil,
CPTokenFieldBlurHandler = nil;
#endif
var CPScrollDestinationNone = 0,
CPScrollDestinationLeft = 1,
CPScrollDestinationRight = 2;
@@ -394,10 +391,10 @@ CPTokenFieldDeleteButtonType = 1;
if (![super becomeFirstResponder])
return NO;
#if PLATFORM(DOM)
if (CPTokenFieldInputOwner && [CPTokenFieldInputOwner window] !== [self window])
if (CPDOMAvailable && CPTokenFieldInputOwner && [CPTokenFieldInputOwner window] !== [self window])
{
[[CPTokenFieldInputOwner window] makeFirstResponder:nil];
#endif
}
// As long as we are the first responder we need to monitor the key status of our window.
[self _setObserveWindowKeyNotifications:YES];
@@ -423,75 +420,74 @@ CPTokenFieldDeleteButtonType = 1;
[self setNeedsLayout];
#if PLATFORM(DOM)
var string = [self stringValue],
element = [self _inputElement],
font = [self currentValueForThemeAttribute:@"font"];
element.value = nil;
element.style.color = [[self currentValueForThemeAttribute:@"text-color"] cssString];
element.style.font = [font cssString];
element.style.zIndex = 1000;
switch ([self alignment])
if (CPDOMAvailable)
{
case CPCenterTextAlignment:
element.style.textAlign = "center";
break;
var string = [self stringValue],
element = [self _inputElement],
font = [self currentValueForThemeAttribute:@"font"];
case CPRightTextAlignment:
element.style.textAlign = "right";
break;
element.value = nil;
element.style.color = [[self currentValueForThemeAttribute:@"text-color"] cssString];
element.style.font = [font cssString];
element.style.zIndex = 1000;
default:
element.style.textAlign = "left";
}
switch ([self alignment])
{
case CPCenterTextAlignment:
element.style.textAlign = "center";
break;
var contentRect = [self contentRectForBounds:[self bounds]];
case CPRightTextAlignment:
element.style.textAlign = "right";
break;
element.style.top = CGRectGetMinY(contentRect) + "px";
element.style.left = (CGRectGetMinX(contentRect) - 1) + "px"; // <input> element effectively imposes a 1px left margin
element.style.width = CGRectGetWidth(contentRect) + "px";
element.style.height = [font defaultLineHeightForFont] + "px";
default:
element.style.textAlign = "left";
}
[[CPRunLoop mainRunLoop] performBlock:function()
{
[_tokenScrollView documentView]._DOMElement.appendChild(element);
var contentRect = [self contentRectForBounds:[self bounds]];
// Removed so CPTokenField doesn't fire the notification the moment it becomes the first responder, but instead defers to the first keystroke, just like Cocoa (see keyDown: in CPTextField).
// [self textDidBeginEditing:[CPNotification notificationWithName:CPControlTextDidBeginEditingNotification object:self userInfo:nil]];
element.style.top = CGRectGetMinY(contentRect) + "px";
element.style.left = (CGRectGetMinX(contentRect) - 1) + "px"; // <input> element effectively imposes a 1px left margin
element.style.width = CGRectGetWidth(contentRect) + "px";
element.style.height = [font defaultLineHeightForFont] + "px";
[[CPRunLoop mainRunLoop] performBlock:function()
{
// This will prevent to jump to the focused element
var previousScrollingOrigin = [self _scrollToVisibleRectAndReturnPreviousOrigin];
[_tokenScrollView documentView]._DOMElement.appendChild(element);
element.focus();
// Removed so CPTokenField doesn't fire the notification the moment it becomes the first responder, but instead defers to the first keystroke, just like Cocoa (see keyDown: in CPTextField).
// [self textDidBeginEditing:[CPNotification notificationWithName:CPControlTextDidBeginEditingNotification object:self userInfo:nil]];
[self _restorePreviousScrollingOrigin:previousScrollingOrigin];
[[CPRunLoop mainRunLoop] performBlock:function()
{
// This will prevent to jump to the focused element
var previousScrollingOrigin = [self _scrollToVisibleRectAndReturnPreviousOrigin];
CPTokenFieldInputOwner = self;
element.focus();
[self _restorePreviousScrollingOrigin:previousScrollingOrigin];
CPTokenFieldInputOwner = self;
} argument:nil order:0 modes:[CPDefaultRunLoopMode]];
[self textDidFocus:[CPNotification notificationWithName:CPTextFieldDidFocusNotification object:self userInfo:nil]];
} argument:nil order:0 modes:[CPDefaultRunLoopMode]];
[self textDidFocus:[CPNotification notificationWithName:CPTextFieldDidFocusNotification object:self userInfo:nil]];
} argument:nil order:0 modes:[CPDefaultRunLoopMode]];
[[[self window] platformWindow] _propagateCurrentDOMEvent:YES];
[[[self window] platformWindow] _propagateCurrentDOMEvent:YES];
CPTokenFieldInputIsActive = YES;
CPTokenFieldInputIsActive = YES;
if (document.attachEvent)
{
CPTokenFieldCachedSelectStartFunction = document.body.onselectstart;
CPTokenFieldCachedDragFunction = document.body.ondrag;
if (document.attachEvent)
{
CPTokenFieldCachedSelectStartFunction = document.body.onselectstart;
CPTokenFieldCachedDragFunction = document.body.ondrag;
document.body.ondrag = function () {};
document.body.onselectstart = function () {};
document.body.ondrag = function () {};
document.body.onselectstart = function () {};
}
}
#endif
return YES;
}
@@ -527,7 +523,7 @@ CPTokenFieldDeleteButtonType = 1;
[self _updatePlaceholderState];
[self setNeedsLayout];
#if PLATFORM(DOM)
if (!CPDOMAvailable) return;
var element = [self _inputElement];
@@ -561,8 +557,6 @@ CPTokenFieldDeleteButtonType = 1;
document.body.ondrag = CPTokenFieldCachedDragFunction;
document.body.onselectstart = CPTokenFieldCachedSelectStartFunction;
}
#endif
}
- (void)mouseDown:(CPEvent)anEvent
@@ -630,16 +624,12 @@ CPTokenFieldDeleteButtonType = 1;
[objectValue addObject:[token representedObject]];
}
#if PLATFORM(DOM)
if ([self _editorValue])
if (CPDOMAvailable && [self _editorValue])
{
var token = [self _representedObjectForEditingString:[self _editorValue]];
[objectValue insertObject:token atIndex:_selectedRange.location];
}
#endif
return objectValue;
}
@@ -755,9 +745,10 @@ CPTokenFieldDeleteButtonType = 1;
// =============
// = TEXTFIELD =
// =============
#if PLATFORM(DOM)
- (DOMElement)_inputElement
{
if (!CPDOMAvailable) return nil;
if (!CPTokenFieldDOMInputElement)
{
CPTokenFieldDOMInputElement = document.createElement("input");
@@ -798,7 +789,6 @@ CPTokenFieldDeleteButtonType = 1;
return CPTokenFieldDOMInputElement;
}
#endif
- (CPString)_editorValue
{
@@ -1036,9 +1026,10 @@ CPTokenFieldDeleteButtonType = 1;
- (void)keyDown:(CPEvent)anEvent
{
#if PLATFORM(DOM)
CPTokenFieldTextDidChangeValue = [self stringValue];
#endif
if (CPDOMAvailable)
{
CPTokenFieldTextDidChangeValue = [self stringValue];
}
// Has to be enabled, and it also has to be editable or selectable.
if (![self isEnabled] || !([self isEditable] || [self isSelectable]))
@@ -1062,12 +1053,10 @@ CPTokenFieldDeleteButtonType = 1;
- (void)keyUp:(CPEvent)anEvent
{
#if PLATFORM(DOM)
if ([self stringValue] !== CPTokenFieldTextDidChangeValue)
if (CPDOMAvailable && [self stringValue] !== CPTokenFieldTextDidChangeValue)
{
[self textDidChange:[CPNotification notificationWithName:CPControlTextDidChangeNotification object:self userInfo:nil]];
}
#endif
[[[self window] platformWindow] _propagateCurrentDOMEvent:YES];
}
+158 -154
View File
@@ -26,9 +26,11 @@
@import "_CPObject+Theme.j"
@import "CGAffineTransform.j"
@import "CPDOMDisplayServer.j"
@import "CGGeometry.j"
@import "CPAppearance.j"
@import "CPColor.j"
@import "CPCompatibility.j"
@import "CPGraphicsContext.j"
@import "CPResponder.j"
@import "CPTheme.j"
@@ -50,8 +52,6 @@
@typedef _CPViewFullScreenModeState
#if PLATFORM(DOM)
if (typeof(appkit_tag_dom_elements) !== "undefined" && appkit_tag_dom_elements)
{
AppKitTagDOMElement = function(owner, element)
@@ -68,8 +68,6 @@ else
}
}
#endif
/*
@global
@group CPViewAutoresizingMasks
@@ -123,7 +121,6 @@ CPViewFrameDidChangeNotification = @"CPViewFrameDidChangeNotification";
var CachedNotificationCenter = nil;
#if PLATFORM(DOM)
var DOMElementPrototype = nil,
BackgroundTrivialColor = 0,
@@ -132,7 +129,6 @@ var DOMElementPrototype = nil,
BackgroundNinePartImage = 3,
BackgroundTransparentColor = 4,
BackgroundCSSStyling = 5;
#endif
var CPViewFlags = { },
CPViewHasCustomDrawRect = 1 << 0,
@@ -189,7 +185,6 @@ var CPViewHighDPIDrawingEnabled = YES;
BOOL _inLiveResize;
BOOL _isSuperviewAClipView;
#if PLATFORM(DOM)
DOMElement _DOMElement;
DOMElement _DOMContentsElement;
@@ -201,7 +196,6 @@ var CPViewHighDPIDrawingEnabled = YES;
// CSS styling
CPArray _cssStylePreviousState;
DOMElement _cssStyleNode;
#endif
CGRect _dirtyRect;
@@ -230,7 +224,6 @@ var CPViewHighDPIDrawingEnabled = YES;
// Layout Support
BOOL _needsLayout;
JSObject _ephemeralSubviews;
JSObject _ephemeralSubviewsForNames;
CPSet _ephemeralSubviews;
@@ -270,16 +263,17 @@ var CPViewHighDPIDrawingEnabled = YES;
if (self !== [CPView class])
return;
#if PLATFORM(DOM)
DOMElementPrototype = document.createElement("div");
if (CPDOMAvailable)
{
DOMElementPrototype = document.createElement("div");
var style = DOMElementPrototype.style;
var style = DOMElementPrototype.style;
style.overflow = "hidden";
style.position = "absolute";
style.visibility = "visible";
style.zIndex = 0;
#endif
style.overflow = "hidden";
style.position = "absolute";
style.visibility = "visible";
style.zIndex = 0;
}
CachedNotificationCenter = [CPNotificationCenter defaultCenter];
}
@@ -409,18 +403,19 @@ var CPViewHighDPIDrawingEnabled = YES;
_theme = [CPTheme defaultTheme];
_themeState = CPThemeStateNormal;
#if PLATFORM(DOM)
_DOMElement = DOMElementPrototype.cloneNode(false);
AppKitTagDOMElement(self, _DOMElement);
if (CPDOMAvailable)
{
_DOMElement = DOMElementPrototype.cloneNode(false);
AppKitTagDOMElement(self, _DOMElement);
CPDOMDisplayServerSetStyleLeftTop(_DOMElement, NULL, CGRectGetMinX(aFrame), CGRectGetMinY(aFrame));
CPDOMDisplayServerSetStyleSize(_DOMElement, width, height);
CPDOMDisplayServerSetStyleLeftTop(_DOMElement, NULL, CGRectGetMinX(aFrame), CGRectGetMinY(aFrame));
CPDOMDisplayServerSetStyleSize(_DOMElement, width, height);
_DOMImageParts = [];
_DOMImageSizes = [];
_DOMImageParts = [];
_DOMImageSizes = [];
_cssStylePreviousState = @[];
#endif
_cssStylePreviousState = @[];
}
_animator = nil;
_animationsDictionary = @{};
@@ -483,20 +478,21 @@ var CPViewHighDPIDrawingEnabled = YES;
if (!_toolTipFunctionOut)
_toolTipFunctionOut = function(e) { [_CPToolTip invalidateCurrentToolTipIfNeeded]; };
#if PLATFORM(DOM)
if (_DOMElement.addEventListener)
if (CPDOMAvailable)
{
_DOMElement.addEventListener("mouseover", _toolTipFunctionIn, YES);
_DOMElement.addEventListener("keypress", _toolTipFunctionOut, YES);
_DOMElement.addEventListener("mouseout", _toolTipFunctionOut, YES);
if (_DOMElement.addEventListener)
{
_DOMElement.addEventListener("mouseover", _toolTipFunctionIn, YES);
_DOMElement.addEventListener("keypress", _toolTipFunctionOut, YES);
_DOMElement.addEventListener("mouseout", _toolTipFunctionOut, YES);
}
else if (_DOMElement.attachEvent)
{
_DOMElement.attachEvent("onmouseover", _toolTipFunctionIn);
_DOMElement.attachEvent("onkeypress", _toolTipFunctionOut);
_DOMElement.attachEvent("onmouseout", _toolTipFunctionOut);
}
}
else if (_DOMElement.attachEvent)
{
_DOMElement.attachEvent("onmouseover", _toolTipFunctionIn);
_DOMElement.attachEvent("onkeypress", _toolTipFunctionOut);
_DOMElement.attachEvent("onmouseout", _toolTipFunctionOut);
}
#endif
_toolTipInstalled = YES;
}
@@ -510,20 +506,21 @@ var CPViewHighDPIDrawingEnabled = YES;
if (!_toolTipInstalled)
return;
#if PLATFORM(DOM)
if (_DOMElement.removeEventListener)
if (CPDOMAvailable)
{
_DOMElement.removeEventListener("mouseover", _toolTipFunctionIn, YES);
_DOMElement.removeEventListener("keypress", _toolTipFunctionOut, YES);
_DOMElement.removeEventListener("mouseout", _toolTipFunctionOut, YES);
if (_DOMElement.removeEventListener)
{
_DOMElement.removeEventListener("mouseover", _toolTipFunctionIn, YES);
_DOMElement.removeEventListener("keypress", _toolTipFunctionOut, YES);
_DOMElement.removeEventListener("mouseout", _toolTipFunctionOut, YES);
}
else if (_DOMElement.detachEvent)
{
_DOMElement.detachEvent("onmouseover", _toolTipFunctionIn);
_DOMElement.detachEvent("onkeypress", _toolTipFunctionOut);
_DOMElement.detachEvent("onmouseout", _toolTipFunctionOut);
}
}
else if (_DOMElement.detachEvent)
{
_DOMElement.detachEvent("onmouseover", _toolTipFunctionIn);
_DOMElement.detachEvent("onkeypress", _toolTipFunctionOut);
_DOMElement.detachEvent("onmouseout", _toolTipFunctionOut);
}
#endif
_toolTipFunctionIn = nil;
_toolTipFunctionOut = nil;
@@ -592,10 +589,8 @@ var CPViewHighDPIDrawingEnabled = YES;
{
if (aSubview === self)
[CPException raise:CPInvalidArgumentException reason:"can't add a view as a subview of itself"];
#if DEBUG
if (!aSubview._superview && _subviews.indexOf(aSubview) !== CPNotFound)
[CPException raise:CPInvalidArgumentException reason:"can't insert a subview in duplicate (probably partially decoded)"];
#endif
// Notify the subview that it will be moving.
[aSubview viewWillMoveToSuperview:self];
@@ -619,9 +614,10 @@ var CPViewHighDPIDrawingEnabled = YES;
[_subviews removeObjectAtIndex:index];
#if PLATFORM(DOM)
CPDOMDisplayServerRemoveChild(_DOMElement, aSubview._DOMElement);
#endif
if (CPDOMAvailable)
{
CPDOMDisplayServerRemoveChild(_DOMElement, aSubview._DOMElement);
}
if (anIndex > index)
--anIndex;
@@ -647,25 +643,28 @@ var CPViewHighDPIDrawingEnabled = YES;
{
_subviews.push(aSubview);
#if PLATFORM(DOM)
// Attach the actual node.
CPDOMDisplayServerAppendChild(_DOMElement, aSubview._DOMElement);
#endif
if (CPDOMAvailable)
{
// Attach the actual node.
CPDOMDisplayServerAppendChild(_DOMElement, aSubview._DOMElement);
}
}
else
{
_subviews.splice(anIndex, 0, aSubview);
#if PLATFORM(DOM)
// Attach the actual node.
CPDOMDisplayServerInsertBefore(_DOMElement, aSubview._DOMElement, _subviews[anIndex + 1]._DOMElement);
#endif
if (CPDOMAvailable)
{
// Attach the actual node.
CPDOMDisplayServerInsertBefore(_DOMElement, aSubview._DOMElement, _subviews[anIndex + 1]._DOMElement);
}
}
#if PLATFORM(DOM)
var origin = aSubview._frame.origin;
CPDOMDisplayServerSetStyleLeftTop(aSubview._DOMElement, _boundsTransform, origin.x, origin.y);
#endif
if (CPDOMAvailable)
{
var origin = aSubview._frame.origin;
CPDOMDisplayServerSetStyleLeftTop(aSubview._DOMElement, _boundsTransform, origin.x, origin.y);
}
[aSubview setNextResponder:self];
[aSubview _scaleSizeUnitSquareToSize:[self _hierarchyScaleSize]];
@@ -737,9 +736,10 @@ var CPViewHighDPIDrawingEnabled = YES;
[_superview._subviews removeObjectIdenticalTo:self];
#if PLATFORM(DOM)
CPDOMDisplayServerRemoveChild(_superview._DOMElement, _DOMElement);
#endif
if (CPDOMAvailable)
{
CPDOMDisplayServerRemoveChild(_superview._DOMElement, _DOMElement);
}
// If the view is not hidden and one of its ancestors is hidden,
// notify the view that it is now unhidden.
@@ -822,7 +822,9 @@ var CPViewHighDPIDrawingEnabled = YES;
_subviews = [newSubviews copy];
#if PLATFORM(DOM)
if (!CPDOMAvailable)
return;
var index = 0,
count = [_subviews count];
@@ -833,7 +835,6 @@ var CPViewHighDPIDrawingEnabled = YES;
CPDOMDisplayServerRemoveChild(_DOMElement, subview._DOMElement);
CPDOMDisplayServerAppendChild(_DOMElement, subview._DOMElement);
}
#endif
}
/* @ignore */
@@ -1152,14 +1153,11 @@ var CPViewHighDPIDrawingEnabled = YES;
if (_isSuperviewAClipView && !_inhibitFrameAndBoundsChangedNotifications)
[[self superview] viewFrameChanged:[[CPNotification alloc] initWithName:CPViewFrameDidChangeNotification object:self userInfo:nil]];
#if PLATFORM(DOM)
if (!_inhibitDOMUpdates)
if (CPDOMAvailable && !_inhibitDOMUpdates)
{
var transform = _superview ? _superview._boundsTransform : NULL;
CPDOMDisplayServerSetStyleLeftTop(_DOMElement, transform, origin.x, origin.y);
}
#endif
if (_window && !_window._inhibitUpdateTrackingAreas && !_inhibitFrameAndBoundsChangedNotifications)
[self _updateTrackingAreasWithRecursion:YES];
@@ -1198,7 +1196,8 @@ var CPViewHighDPIDrawingEnabled = YES;
[self setNeedsLayout];
[self setNeedsDisplay:YES];
#if PLATFORM(DOM)
if (CPDOMAvailable)
{
[self _setDisplayServerSetStyleSize:size];
if (_backgroundType !== BackgroundTrivialColor)
@@ -1307,7 +1306,7 @@ var CPViewHighDPIDrawingEnabled = YES;
}
}
}
#endif
}
if (_postsFrameChangedNotifications && !_inhibitFrameAndBoundsChangedNotifications)
[CachedNotificationCenter postNotificationName:CPViewFrameDidChangeNotification object:self];
@@ -1326,7 +1325,9 @@ var CPViewHighDPIDrawingEnabled = YES;
*/
- (void)_setDisplayServerSetStyleSize:(CGSize)aSize
{
#if PLATFORM(DOM)
if (!CPDOMAvailable)
return;
var scale = [self scaleSize];
if (!_inhibitDOMUpdates)
@@ -1339,7 +1340,6 @@ var CPViewHighDPIDrawingEnabled = YES;
_needToSetTransformMatrix = YES;
}
#endif
}
/*!
@@ -1418,7 +1418,8 @@ var CPViewHighDPIDrawingEnabled = YES;
if (_layer)
[_layer _owningViewBoundsChanged];
#if PLATFORM(DOM)
if (CPDOMAvailable)
{
var index = _subviews.length;
while (index--)
@@ -1428,7 +1429,7 @@ var CPViewHighDPIDrawingEnabled = YES;
CPDOMDisplayServerSetStyleLeftTop(view._DOMElement, _boundsTransform, origin.x, origin.y);
}
#endif
}
if (_postsBoundsChangedNotifications && !_inhibitFrameAndBoundsChangedNotifications)
[CachedNotificationCenter postNotificationName:CPViewBoundsDidChangeNotification object:self];
@@ -1680,11 +1681,12 @@ var CPViewHighDPIDrawingEnabled = YES;
if (_isHidden === aFlag)
return;
// FIXME: Should we return to visibility? This breaks in FireFox, Opera, and IE.
// _DOMElement.style.visibility = (_isHidden = aFlag) ? "hidden" : "visible";
#if PLATFORM(DOM)
_DOMElement.style.display = aFlag ? "none" : "block";
#endif
// FIXME: Should we return to visibility? This breaks in FireFox, Opera, and IE.
// _DOMElement.style.visibility = (_isHidden = aFlag) ? "hidden" : "visible";
if (CPDOMAvailable)
{
_DOMElement.style.display = aFlag ? "none" : "block";
}
if (aFlag)
{
@@ -1779,9 +1781,10 @@ var CPViewHighDPIDrawingEnabled = YES;
_isHiddenOrHasHiddenAncestor = YES;
[_subviews enumerateObjectsUsingBlock:function(view, idx, stop)
{
[view _recursiveGainedHiddenAncestor];
}];
{
[view _recursiveGainedHiddenAncestor];
}
];
}
/*!
@@ -1799,9 +1802,10 @@ var CPViewHighDPIDrawingEnabled = YES;
_clipsToBounds = shouldClip;
#if PLATFORM(DOM)
if (!CPDOMAvailable)
return;
_DOMElement.style.overflow = _clipsToBounds ? "hidden" : "visible";
#endif
}
- (BOOL)clipsToBounds
@@ -1821,7 +1825,8 @@ var CPViewHighDPIDrawingEnabled = YES;
_opacity = anAlphaValue;
#if PLATFORM(DOM)
if (!CPDOMAvailable)
return;
if (CPFeatureIsCompatible(CPOpacityRequiresFilterFeature))
{
@@ -1832,8 +1837,6 @@ var CPViewHighDPIDrawingEnabled = YES;
}
else
_DOMElement.style.opacity = anAlphaValue;
#endif
}
/*!
@@ -2023,7 +2026,9 @@ var CPViewHighDPIDrawingEnabled = YES;
_backgroundColor = aColor;
#if PLATFORM(DOM)
if (!CPDOMAvailable)
return;
if (_backgroundType === BackgroundCSSStyling)
[CPColor restorePreviousCSSState:@ref(_cssStylePreviousState) forDOMElement:_DOMElement];
@@ -2301,7 +2306,6 @@ var CPViewHighDPIDrawingEnabled = YES;
}
}
}
#endif
}
/*!
@@ -2647,8 +2651,7 @@ setBoundsOrigin:
*/
- (void)_applyCSSScalingTranformations
{
#if PLATFORM(DOM)
if (_isScaled)
if (CPDOMAvailable && _isScaled)
{
var scale = [self scaleSize],
browserPropertyTransform = CPBrowserStyleProperty(@"transform"),
@@ -2659,7 +2662,6 @@ setBoundsOrigin:
[self _setDisplayServerSetStyleSize:[self frameSize]];
}
#endif
}
// Displaying
@@ -2742,14 +2744,15 @@ setBoundsOrigin:
if ([self isHidden])
return;
#if PLATFORM(DOM)
if (!CPDOMAvailable)
return;
[self lockFocus];
CGContextClearRect([[CPGraphicsContext currentContext] graphicsPort], aRect);
[self drawRect:aRect];
[self unlockFocus];
#endif
}
- (void)viewWillDraw
@@ -2765,42 +2768,41 @@ setBoundsOrigin:
{
var graphicsPort = CGBitmapGraphicsContextCreate();
#if PLATFORM(DOM)
var width = CGRectGetWidth(_frame),
height = CGRectGetHeight(_frame),
devicePixelRatio = window.devicePixelRatio || 1,
backingStoreRatio = CPBrowserBackingStorePixelRatio(graphicsPort);
if (CPDOMAvailable)
{
var width = CGRectGetWidth(_frame),
height = CGRectGetHeight(_frame),
devicePixelRatio = window.devicePixelRatio || 1,
backingStoreRatio = CPBrowserBackingStorePixelRatio(graphicsPort);
_highDPIRatio = CPViewHighDPIDrawingEnabled ? (devicePixelRatio / backingStoreRatio) : 1;
_highDPIRatio = CPViewHighDPIDrawingEnabled ? (devicePixelRatio / backingStoreRatio) : 1;
_DOMContentsElement = graphicsPort.DOMElement;
_DOMContentsElement = graphicsPort.DOMElement;
_DOMContentsElement.style.zIndex = -100;
_DOMContentsElement.style.zIndex = -100;
_DOMContentsElement.style.overflow = "hidden";
_DOMContentsElement.style.position = "absolute";
_DOMContentsElement.style.visibility = "visible";
_DOMContentsElement.style.overflow = "hidden";
_DOMContentsElement.style.position = "absolute";
_DOMContentsElement.style.visibility = "visible";
CPDOMDisplayServerSetSize(_DOMContentsElement, width * _highDPIRatio, height * _highDPIRatio);
CPDOMDisplayServerSetSize(_DOMContentsElement, width * _highDPIRatio, height * _highDPIRatio);
CPDOMDisplayServerSetStyleLeftTop(_DOMContentsElement, NULL, 0.0, 0.0);
CPDOMDisplayServerSetStyleSize(_DOMContentsElement, width, height);
CPDOMDisplayServerSetStyleLeftTop(_DOMContentsElement, NULL, 0.0, 0.0);
CPDOMDisplayServerSetStyleSize(_DOMContentsElement, width, height);
// The performance implications of this aren't clear, but without this subviews might not be redrawn when this
// view moves.
if (CPPlatformHasBug(CPCanvasParentDrawErrorsOnMovementBug))
_DOMElement.style.webkitTransform = 'translateX(0)';
// The performance implications of this aren't clear, but without this subviews might not be redrawn when this
// view moves.
if (CPPlatformHasBug(CPCanvasParentDrawErrorsOnMovementBug))
_DOMElement.style.webkitTransform = 'translateX(0)';
CPDOMDisplayServerAppendChild(_DOMElement, _DOMContentsElement);
#endif
CPDOMDisplayServerAppendChild(_DOMElement, _DOMContentsElement);
}
_graphicsContext = [CPGraphicsContext graphicsContextWithGraphicsPort:graphicsPort flipped:YES];
_needToSetTransformMatrix = YES;
}
#if PLATFORM(DOM)
if (_needToSetTransformMatrix && _highDPIRatio !== 1)
if (CPDOMAvailable && _needToSetTransformMatrix && _highDPIRatio !== 1)
[_graphicsContext graphicsPort].setTransform(_highDPIRatio, 0, 0 , _highDPIRatio, 0, 0);
#endif
_needToSetTransformMatrix = NO;
[CPGraphicsContext setCurrentContext:_graphicsContext];
@@ -3242,10 +3244,8 @@ setBoundsOrigin:
if (_layer)
{
_layer._owningView = nil;
#if PLATFORM(DOM)
if (_layer._DOMElement && _layer._DOMElement.parentNode === _DOMElement)
if (CPDOMAvailable && _layer._DOMElement && _layer._DOMElement.parentNode === _DOMElement)
_DOMElement.removeChild(_layer._DOMElement);
#endif
}
_layer = aLayer;
@@ -3255,10 +3255,11 @@ setBoundsOrigin:
[_layer _setOwningView:self];
[_layer setFrame:[self bounds]]; // Sync layer frame with view bounds
#if PLATFORM(DOM)
_layer._DOMElement.style.zIndex = 100;
_DOMElement.appendChild(_layer._DOMElement);
#endif
if (CPDOMAvailable)
{
_layer._DOMElement.style.zIndex = 100;
_DOMElement.appendChild(_layer._DOMElement);
}
}
}
@@ -3590,9 +3591,10 @@ setBoundsOrigin:
- (void)setDOMClassName:(CPString)aClassName
{
#if PLATFORM(DOM)
if (!CPDOMAvailable)
return;
_DOMElement.className = aClassName;
#endif
}
- (BOOL)isCSSBased
@@ -3866,10 +3868,11 @@ var CPViewAutoresizingMaskKey = @"CPViewAutoresizingMask",
// will decode our superview before we are done decoding, at which point
// we have to have an element to place in the tree. Perhaps there is
// a more "elegant" way to do this...?
#if PLATFORM(DOM)
_DOMElement = DOMElementPrototype.cloneNode(false);
AppKitTagDOMElement(self, _DOMElement);
#endif
if (CPDOMAvailable)
{
_DOMElement = DOMElementPrototype.cloneNode(false);
AppKitTagDOMElement(self, _DOMElement);
}
// Also decode these "early".
_frame = [aCoder decodeRectForKey:CPViewFrameKey];
@@ -3926,24 +3929,25 @@ var CPViewAutoresizingMaskKey = @"CPViewAutoresizingMask",
[self _installToolTipEventHandlers];
// DOM SETUP
#if PLATFORM(DOM)
_cssStylePreviousState = @[];
_DOMImageParts = [];
_DOMImageSizes = [];
CPDOMDisplayServerSetStyleLeftTop(_DOMElement, NULL, CGRectGetMinX(_frame), CGRectGetMinY(_frame));
[self _setDisplayServerSetStyleSize:_frame.size];
var index = 0,
count = _subviews.length;
for (; index < count; ++index)
if (CPDOMAvailable)
{
CPDOMDisplayServerAppendChild(_DOMElement, _subviews[index]._DOMElement);
//_subviews[index]._superview = self;
_cssStylePreviousState = @[];
_DOMImageParts = [];
_DOMImageSizes = [];
CPDOMDisplayServerSetStyleLeftTop(_DOMElement, NULL, CGRectGetMinX(_frame), CGRectGetMinY(_frame));
[self _setDisplayServerSetStyleSize:_frame.size];
var index = 0,
count = _subviews.length;
for (; index < count; ++index)
{
CPDOMDisplayServerAppendChild(_DOMElement, _subviews[index]._DOMElement);
//_subviews[index]._superview = self;
}
}
#endif
[self setHidden:[aCoder decodeBoolForKey:CPViewIsHiddenKey]];
_isHiddenOrHasHiddenAncestor = NO;
+5 -3
View File
@@ -23,6 +23,7 @@
@import <Foundation/Foundation.j>
@import "CPAppearance.j"
@import "CPView.j"
@import "CPCompatibility.j"
@typedef CPVisualEffectMaterial
CPVisualEffectMaterialAppearanceBased = 0;
@@ -126,9 +127,10 @@ CPVisualEffectStateInactive = 2;
[self setBackgroundColor:finalColor];
#if PLATFORM(DOM)
self._DOMElement.style[prop] = shouldEnable ? "blur(30px)" : nil;
#endif
if (CPDOMAvailable)
{
self._DOMElement.style[prop] = shouldEnable ? "blur(30px)" : nil;
}
}
+5 -3
View File
@@ -22,6 +22,7 @@
@import "CPView.j"
@import "CPScrollView.j"
@import "CPCompatibility.j"
@class CPWebScriptObject
@@ -1031,9 +1032,10 @@ CPWebViewAppKitScrollMaxPollCount = 3;
_forwardStack = [];
_scrollMode = CPWebViewScrollAuto;
#if PLATFORM(DOM)
[self _initDOMWithFrame:[self frame]];
#endif
if (CPDOMAvailable)
{
[self _initDOMWithFrame:[self frame]];
}
if (![self backgroundColor])
[self setBackgroundColor:[CPColor whiteColor]];
+109 -106
View File
@@ -30,9 +30,7 @@
@import "CPDragServer.j"
@import "CPEvent.j"
@import "CPPlatformWindow.j"
#if PLATFORM(BROWSER)
@import "CPPlatformWindow+DOM.j"
#endif
@import "CPResponder.j"
@import "CPScreen.j"
@import "CPText.j"
@@ -247,9 +245,7 @@ var CPWindowActionMessageKeys = [
BOOL _sharesChromeWithPlatformWindow;
// Bridge Support
#if PLATFORM(DOM)
DOMElement _DOMElement;
#endif
unsigned _autoresizingMask;
@@ -373,21 +369,22 @@ CPTexturedBackgroundWindowMask
[_windowView setNextResponder:self];
// CSS Styling
#if PLATFORM(DOM)
var radius;
if (radius = [_windowView actualValueForThemeAttribute:@"border-top-left-radius"])
_windowView._DOMElement.style.borderTopLeftRadius = radius;
if (radius = [_windowView actualValueForThemeAttribute:@"border-top-right-radius"])
_windowView._DOMElement.style.borderTopRightRadius = radius;
if (radius = [_windowView actualValueForThemeAttribute:@"border-bottom-left-radius"])
_windowView._DOMElement.style.borderBottomLeftRadius = radius;
if (radius = [_windowView actualValueForThemeAttribute:@"border-bottom-right-radius"])
_windowView._DOMElement.style.borderBottomRightRadius = radius;
#endif
if (CPDOMAvailable)
{
var radius;
if (radius = [_windowView actualValueForThemeAttribute:@"border-top-left-radius"])
_windowView._DOMElement.style.borderTopLeftRadius = radius;
if (radius = [_windowView actualValueForThemeAttribute:@"border-top-right-radius"])
_windowView._DOMElement.style.borderTopRightRadius = radius;
if (radius = [_windowView actualValueForThemeAttribute:@"border-bottom-left-radius"])
_windowView._DOMElement.style.borderBottomLeftRadius = radius;
if (radius = [_windowView actualValueForThemeAttribute:@"border-bottom-right-radius"])
_windowView._DOMElement.style.borderBottomRightRadius = radius;
}
// Size calculation needs _windowView
_minSize = [self _calculateMinSizeForProposedSize:CGSizeMake(0.0, 0.0)];
@@ -400,21 +397,22 @@ CPTexturedBackgroundWindowMask
_firstResponder = self;
#if PLATFORM(DOM)
_DOMElement = document.createElement("div");
_DOMElement.style.position = "absolute";
_DOMElement.style.visibility = "visible";
_DOMElement.style.zIndex = 0;
if (![self _sharesChromeWithPlatformWindow])
if (CPDOMAvailable)
{
CPDOMDisplayServerSetStyleLeftTop(_DOMElement, NULL, CGRectGetMinX(_frame), CGRectGetMinY(_frame));
}
_DOMElement = document.createElement("div");
CPDOMDisplayServerSetStyleSize(_DOMElement, 1, 1);
CPDOMDisplayServerAppendChild(_DOMElement, _windowView._DOMElement);
#endif
_DOMElement.style.position = "absolute";
_DOMElement.style.visibility = "visible";
_DOMElement.style.zIndex = 0;
if (![self _sharesChromeWithPlatformWindow])
{
CPDOMDisplayServerSetStyleLeftTop(_DOMElement, NULL, CGRectGetMinX(_frame), CGRectGetMinY(_frame));
}
CPDOMDisplayServerSetStyleSize(_DOMElement, 1, 1);
CPDOMDisplayServerAppendChild(_DOMElement, _windowView._DOMElement);
}
[self setNextResponder:CPApp];
@@ -580,16 +578,18 @@ CPTexturedBackgroundWindowMask
[oldWindowView _setWindow:nil];
[oldWindowView noteToolbarChanged];
#if PLATFORM(DOM)
CPDOMDisplayServerRemoveChild(_DOMElement, oldWindowView._DOMElement);
#endif
if (CPDOMAvailable)
{
CPDOMDisplayServerRemoveChild(_DOMElement, oldWindowView._DOMElement);
}
}
if (_windowView)
{
#if PLATFORM(DOM)
CPDOMDisplayServerAppendChild(_DOMElement, _windowView._DOMElement);
#endif
if (CPDOMAvailable)
{
CPDOMDisplayServerAppendChild(_DOMElement, _windowView._DOMElement);
}
var contentRect = [_contentView convertRect:[_contentView bounds] toView:nil];
@@ -785,12 +785,10 @@ CPTexturedBackgroundWindowMask
origin.x = newOrigin.x;
origin.y = newOrigin.y;
#if PLATFORM(DOM)
if (![self _sharesChromeWithPlatformWindow])
if (CPDOMAvailable && ![self _sharesChromeWithPlatformWindow])
{
CPDOMDisplayServerSetStyleLeftTop(_DOMElement, NULL, origin.x, origin.y);
}
#endif
// reposition sheet
if ([self attachedSheet])
@@ -984,25 +982,25 @@ CPTexturedBackgroundWindowMask
- (void)_orderFront
{
#if PLATFORM(DOM)
if (CPDOMAvailable)
{
if (!_isVisible)
[_platformWindow _setShouldUpdateContentRect:NO];
if (!_isVisible)
[_platformWindow _setShouldUpdateContentRect:NO];
// -dw- if a sheet is clicked, the parent window should come up too
if (_isSheet)
[_parentView orderFront:self];
// -dw- if a sheet is clicked, the parent window should come up too
if (_isSheet)
[_parentView orderFront:self];
// Save the boolean since it will be updated in the method order:window:relativeTo:
var wasVisible = _isVisible;
// Save the boolean since it will be updated in the method order:window:relativeTo:
var wasVisible = _isVisible;
[_platformWindow orderFront:self];
[_platformWindow order:CPWindowAbove window:self relativeTo:nil];
[_platformWindow orderFront:self];
[_platformWindow order:CPWindowAbove window:self relativeTo:nil];
// setFrame is set after ordering the window as this method can send some notifications
if (!wasVisible)
[self _setFrame:_frame display:YES animate:NO constrainWidth:YES constrainHeight:YES];
#endif
// setFrame is set after ordering the window as this method can send some notifications
if (!wasVisible)
[self _setFrame:_frame display:YES animate:NO constrainWidth:YES constrainHeight:YES];
}
if (!CPApp._keyWindow)
[self makeKeyWindow];
@@ -1091,15 +1089,16 @@ CPTexturedBackgroundWindowMask
if (recursive)
[_childWindows makeObjectsPerformSelector:@selector(_orderOutRecursively:) withObject:recursive];
#if PLATFORM(DOM)
if ([self _sharesChromeWithPlatformWindow])
[_platformWindow orderOut:self];
if (CPDOMAvailable)
{
if ([self _sharesChromeWithPlatformWindow])
[_platformWindow orderOut:self];
if (_isFullPlatformWindow && _platformWindow != [CPPlatformWindow primaryPlatformWindow])
[_platformWindow orderOut:self];
if (_isFullPlatformWindow && _platformWindow != [CPPlatformWindow primaryPlatformWindow])
[_platformWindow orderOut:self];
[_platformWindow order:CPWindowOut window:self relativeTo:nil];
#endif
[_platformWindow order:CPWindowOut window:self relativeTo:nil];
}
[self makeFirstResponder:nil];
[self _updateMainAndKeyWindows];
@@ -1124,10 +1123,11 @@ CPTexturedBackgroundWindowMask
[self _orderFront];
else if (orderingMode === CPWindowBelow && otherWindowNumber === 0)
[self _orderBack];
#if PLATFORM(DOM)
else
[_platformWindow order:orderingMode window:self relativeTo:CPApp._windows[otherWindowNumber]];
#endif
{
if (CPDOMAvailable)
[_platformWindow order:orderingMode window:self relativeTo:CPApp._windows[otherWindowNumber]];
}
}
/*!
@@ -1424,9 +1424,10 @@ CPTexturedBackgroundWindowMask
{
if (_shadowView)
{
#if PLATFORM(DOM)
CPDOMDisplayServerRemoveChild(_DOMElement, _shadowView._DOMElement);
#endif
if (CPDOMAvailable)
{
CPDOMDisplayServerRemoveChild(_DOMElement, _shadowView._DOMElement);
}
_shadowView = nil;
}
@@ -1440,23 +1441,24 @@ CPTexturedBackgroundWindowMask
// When using CSS theming, we get rid of _shadowView and add CSS shadowing directly
// on the _windowView
#if PLATFORM(DOM)
// We must check that _windowView exists as _updateShadow can be called by
// _setSharesChromeWithPlatformWindow whereas _windowView is not yet created
if (_windowView && _windowView._DOMElement)
if (CPDOMAvailable)
{
var currentBoxShadow = _windowView._DOMElement.style.boxShadow;
if (_hasShadow && (currentBoxShadow.length == 0))
// We must check that _windowView exists as _updateShadow can be called by
// _setSharesChromeWithPlatformWindow whereas _windowView is not yet created
if (_windowView && _windowView._DOMElement)
{
_windowView._DOMElement.style.boxShadow = [_windowView actualValueForThemeAttribute:@"window-shadow-color"];
}
else if (!_hasShadow && (currentBoxShadow.length > 0))
{
_windowView._DOMElement.style.boxShadow = "";
var currentBoxShadow = _windowView._DOMElement.style.boxShadow;
if (_hasShadow && (currentBoxShadow.length == 0))
{
_windowView._DOMElement.style.boxShadow = [_windowView actualValueForThemeAttribute:@"window-shadow-color"];
}
else if (!_hasShadow && (currentBoxShadow.length > 0))
{
_windowView._DOMElement.style.boxShadow = "";
}
}
}
#endif
}
else
{
@@ -1468,15 +1470,17 @@ CPTexturedBackgroundWindowMask
[_shadowView setAutoresizingMask:CPViewWidthSizable | CPViewHeightSizable];
[_shadowView setNeedsLayout];
#if PLATFORM(DOM)
CPDOMDisplayServerInsertBefore(_DOMElement, _shadowView._DOMElement, _windowView._DOMElement);
#endif
if (CPDOMAvailable)
{
CPDOMDisplayServerInsertBefore(_DOMElement, _shadowView._DOMElement, _windowView._DOMElement);
}
}
else if (!_hasShadow && _shadowView)
{
#if PLATFORM(DOM)
CPDOMDisplayServerRemoveChild(_DOMElement, _shadowView._DOMElement);
#endif
if (CPDOMAvailable)
{
CPDOMDisplayServerRemoveChild(_DOMElement, _shadowView._DOMElement);
}
_shadowView = nil;
}
}
@@ -1958,12 +1962,13 @@ CPTexturedBackgroundWindowMask
[self selectPreviousKeyView:self];
else
[self selectNextKeyView:self];
#if PLATFORM(DOM)
// Make sure the browser doesn't try to do its own tab handling.
// This is important or the browser might blur the shared text field or token field input field,
// even that we just moved it to a new first responder.
[[[anEvent window] platformWindow] _propagateCurrentDOMEvent:NO];
#endif
if (CPDOMAvailable)
{
// Make sure the browser doesn't try to do its own tab handling.
// This is important or the browser might blur the shared text field or token field input field,
// even that we just moved it to a new first responder.
[[[anEvent window] platformWindow] _propagateCurrentDOMEvent:NO];
}
return;
}
else if ([anEvent charactersIgnoringModifiers] === CPBackTabCharacter)
@@ -1972,13 +1977,13 @@ CPTexturedBackgroundWindowMask
if (didTabBack)
{
#if PLATFORM(DOM)
// Make sure the browser doesn't try to do its own tab handling.
// This is important or the browser might blur the shared text field or token field input field,
// even that we just moved it to a new first responder.
[[[anEvent window] platformWindow] _propagateCurrentDOMEvent:NO];
#endif
if (CPDOMAvailable)
{
// Make sure the browser doesn't try to do its own tab handling.
// This is important or the browser might blur the shared text field or token field input field,
// even that we just moved it to a new first responder.
[[[anEvent window] platformWindow] _propagateCurrentDOMEvent:NO];
}
}
return didTabBack;
}
@@ -3711,12 +3716,10 @@ var keyViewComparator = function(lhs, rhs, context)
*/
- (CGPoint)_nativeScrollOffset
{
#if PLATFORM(DOM)
return CGPointMake(_windowView._DOMElement.scrollLeft, _windowView._DOMElement.scrollTop);
#else
CGPointMake(0, 0);
#endif
if (CPDOMAvailable)
return CGPointMake(_windowView._DOMElement.scrollLeft, _windowView._DOMElement.scrollTop);
CGPointMake(0, 0);
}
/*!
@@ -21,6 +21,7 @@
*/
@import "_CPWindowView.j"
@import "CPCompatibility.j"
@implementation _CPBorderlessBridgeWindowView : _CPWindowView
{
@@ -90,10 +91,11 @@
if (_frame.size.width < theWindow._minSize.width || _frame.size.height < theWindow._minSize.height)
[theWindow._contentView setFrameSize:CGSizeMake(MAX(_frame.size.width, theWindow._minSize.width), MAX(_frame.size.height, theWindow._minSize.height))];
#if PLATFORM(DOM)
_DOMElement.style.overflowX = (_frame.size.width < theWindow._minSize.width)? "scroll":"hidden";
_DOMElement.style.overflowY = (_frame.size.height < theWindow._minSize.height)? "scroll":"hidden";
#endif
if (CPDOMAvailable)
{
_DOMElement.style.overflowX = (_frame.size.width < theWindow._minSize.width)? "scroll":"hidden";
_DOMElement.style.overflowY = (_frame.size.height < theWindow._minSize.height)? "scroll":"hidden";
}
}
@end
-2
View File
@@ -81,9 +81,7 @@ var _CPCibCustomObjectClassName = @"_CPCibCustomObjectClassName";
if (!theClass)
{
#if DEBUG
CPLog("Unknown class \"" + _className + "\" in cib file");
#endif
theClass = [CPObject class];
}
-2
View File
@@ -82,9 +82,7 @@ var _CPCibCustomViewClassNameKey = @"_CPCibCustomViewClassNameKey";
// FIXME: Should we instead throw an exception?
if (!theClass)
{
#if DEBUG
CPLog("Unknown class \"" + _className + "\" in cib file, using CPView instead.");
#endif
theClass = [CPView class];
}
-2
View File
@@ -91,9 +91,7 @@
if (!windowClass)
{
#if DEBUG
CPLog.warn("Unknown class \"%@\" in cib file, using CPWindow instead.", [self windowClass]);
#endif
windowClass = [CPWindow class];
}
+4 -1
View File
@@ -23,7 +23,10 @@
@import "CGGeometry.j"
@import "CPCompatibility.j"
#define PIXEL(pixels) pixels + "px";
function PIXEL(pixels)
{
return pixels + "px";
}
function CABackingStoreGetContext(aBackingStore)
+67 -58
View File
@@ -28,11 +28,15 @@
@import "CGContext.j"
@import "CGGeometry.j"
@import "CPColor.j"
@import "CPCompatibility.j"
@import "CPView.j"
@import "CAMediaTimingFunction.j"
#define DOM(aLayer) aLayer._DOMElement
function DOM(aLayer)
{
return aLayer._DOMElement;
}
var CALayerGeometryBoundsMask = 1,
CALayerGeometryPositionMask = 2,
@@ -166,18 +170,19 @@ var CALayerRegisteredRunLoopUpdates = nil;
_activeAnimations = [CPMutableDictionary dictionary];
#if PLATFORM(DOM)
_DOMElement = document.createElement("div");
if (CPDOMAvailable)
{
_DOMElement = document.createElement("div");
_DOMElement.style.overflow = "visible";
_DOMElement.style.position = "absolute";
_DOMElement.style.visibility = "visible";
_DOMElement.style.top = "0px";
_DOMElement.style.left = "0px";
_DOMElement.style.zIndex = 0;
_DOMElement.style.width = "0px";
_DOMElement.style.height = "0px";
#endif
_DOMElement.style.overflow = "visible";
_DOMElement.style.position = "absolute";
_DOMElement.style.visibility = "visible";
_DOMElement.style.top = "0px";
_DOMElement.style.left = "0px";
_DOMElement.style.zIndex = 0;
_DOMElement.style.width = "0px";
_DOMElement.style.height = "0px";
}
}
return self;
@@ -503,47 +508,48 @@ var CALayerRegisteredRunLoopUpdates = nil;
*/
- (void)display
{
#if PLATFORM(DOM)
if (!_context)
if (CPDOMAvailable)
{
_context = CGBitmapGraphicsContextCreate();
if (!_context)
{
_context = CGBitmapGraphicsContextCreate();
_DOMContentsElement = _context.DOMElement;
_DOMContentsElement = _context.DOMElement;
_DOMContentsElement.style.zIndex = -100;
_DOMContentsElement.style.zIndex = -100;
_DOMContentsElement.style.overflow = "hidden";
_DOMContentsElement.style.position = "absolute";
_DOMContentsElement.style.visibility = "visible";
_DOMContentsElement.style.overflow = "hidden";
_DOMContentsElement.style.position = "absolute";
_DOMContentsElement.style.visibility = "visible";
_DOMContentsElement.width = ROUND(CGRectGetWidth(_backingStoreFrame));
_DOMContentsElement.height = ROUND(CGRectGetHeight(_backingStoreFrame));
_DOMContentsElement.width = ROUND(CGRectGetWidth(_backingStoreFrame));
_DOMContentsElement.height = ROUND(CGRectGetHeight(_backingStoreFrame));
_DOMContentsElement.style.top = "0px";
_DOMContentsElement.style.left = "0px";
_DOMContentsElement.style.width = ROUND(CGRectGetWidth(_backingStoreFrame)) + "px";
_DOMContentsElement.style.height = ROUND(CGRectGetHeight(_backingStoreFrame)) + "px";
_DOMContentsElement.style.top = "0px";
_DOMContentsElement.style.left = "0px";
_DOMContentsElement.style.width = ROUND(CGRectGetWidth(_backingStoreFrame)) + "px";
_DOMContentsElement.style.height = ROUND(CGRectGetHeight(_backingStoreFrame)) + "px";
_DOMElement.appendChild(_DOMContentsElement);
_DOMElement.appendChild(_DOMContentsElement);
}
if (USE_BUFFER)
{
if (_delegateRespondsToDisplayLayerSelector)
return [_delegate displayLayer:self];
if (CGRectGetWidth(_backingStoreFrame) == 0.0 || CGRectGetHeight(_backingStoreFrame) == 0.0)
return;
if (!_contents)
_contents = CABackingStoreCreate();
CABackingStoreSetSize(_contents, _bounds.size);
[self drawInContext:CABackingStoreGetContext(_contents)];
}
}
if (USE_BUFFER)
{
if (_delegateRespondsToDisplayLayerSelector)
return [_delegate displayLayer:self];
if (CGRectGetWidth(_backingStoreFrame) == 0.0 || CGRectGetHeight(_backingStoreFrame) == 0.0)
return;
if (!_contents)
_contents = CABackingStoreCreate();
CABackingStoreSetSize(_contents, _bounds.size);
[self drawInContext:CABackingStoreGetContext(_contents)];
}
#endif
[self composite];
}
@@ -664,10 +670,6 @@ var CALayerRegisteredRunLoopUpdates = nil;
return _superlayer;
}
#define ADJUST_CONTENTS_ZINDEX(aLayer)\
if (_DOMContentsElement && aLayer._zPosition > _DOMContentsElement.style.zIndex)\
_DOMContentsElement.style.zIndex -= 100.0;\
/*!
Adds the specified layer as a sublayer of the receiver.
*/
@@ -720,16 +722,17 @@ if (_DOMContentsElement && aLayer._zPosition > _DOMContentsElement.style.zIndex)
else if (superlayer != nil)
[aLayer removeFromSuperlayer];
ADJUST_CONTENTS_ZINDEX(aLayer);
[self _adjustContentsZIndexForLayer:aLayer];
[_sublayers insertObject:aLayer atIndex:anIndex];
#if PLATFORM(DOM)
if (anIndex >= _sublayers.length - 1)
_DOMElement.appendChild(DOM(aLayer));
else
_DOMElement.insertBefore(DOM(aLayer), _sublayers[anIndex + 1]._DOMElement);
#endif
if (CPDOMAvailable)
{
if (anIndex >= _sublayers.length - 1)
_DOMElement.appendChild(DOM(aLayer));
else
_DOMElement.insertBefore(DOM(aLayer), _sublayers[anIndex + 1]._DOMElement);
}
aLayer._superlayer = self;
@@ -782,7 +785,7 @@ if (_DOMContentsElement && aLayer._zPosition > _DOMContentsElement.style.zIndex)
return;
}
ADJUST_CONTENTS_ZINDEX(aLayer);
[self _adjustContentsZIndexForLayer:aLayer];
[_sublayers replaceObjectAtIndex:[_sublayers indexOfObjectIdenticalTo:aSublayer] withObject:aLayer];
_DOMElement.replaceChild(DOM(aSublayer), DOM(aLayer));
@@ -1267,6 +1270,12 @@ if (_DOMContentsElement && aLayer._zPosition > _DOMContentsElement.style.zIndex)
window.loop = false;
}
- (void)_adjustContentsZIndexForLayer:(CALayer)aLayer
{
if (_DOMContentsElement && aLayer._zPosition > _DOMContentsElement.style.zIndex)
_DOMContentsElement.style.zIndex -= 100.0;
}
@end
function _CALayerUpdateSublayerTransformForSublayers(aLayer)
@@ -1284,7 +1293,8 @@ function _CALayerUpdateSublayerTransformForSublayers(aLayer)
function _CALayerUpdateDOM(aLayer, aMask)
{
#if PLATFORM(DOM)
if (!CPDOMAvailable) return;
var DOMElementStyle = aLayer._DOMElement.style;
if (aMask & CALayerZPositionUpdateMask)
@@ -1315,7 +1325,6 @@ function _CALayerUpdateDOM(aLayer, aMask)
DOMContentsElement.style.height = height + "px";
}
}
#endif
}
function _CALayerRecalculateGeometry(aLayer, aGeometryChange)
-34
View File
@@ -70,9 +70,6 @@ var _CPAnimationContextStack = nil,
{
if (!_animationFlushingObserver)
{
#if (DEBUG)
CPLog.debug("create new observer");
#endif
_animationFlushingObserver = CFRunLoopObserverCreate(2, true, 0, _animationFlushingObserverCallback, 0);
CFRunLoopAddObserver([CPRunLoop mainRunLoop], _animationFlushingObserver);
}
@@ -101,9 +98,6 @@ var _CPAnimationContextStack = nil,
[context _flushAnimations];
[_CPAnimationContextStack removeLastObject];
#if (DEBUG)
CPLog.debug(_cmd + "context stack =" + _CPAnimationContextStack);
#endif
return YES;
}
@@ -234,9 +228,6 @@ var _CPAnimationContextStack = nil,
{
if (_completionHandlerAgent)
{
#if (DEBUG)
CPLog.debug("No animations are scheduled. Firing completion handler");
#endif
_completionHandlerAgent.fire();
}
}
@@ -266,9 +257,6 @@ var _CPAnimationContextStack = nil,
{
if (n == 0)
{
#if (DEBUG)
CPLog.debug("Animations are not needed. Firing completion handler");
#endif
_completionHandlerAgent.fire();
}
else
@@ -278,18 +266,12 @@ var _CPAnimationContextStack = nil,
// start timers
while(k--)
{
#if (DEBUG)
CPLog.debug("START TIMER " + timers[k].description());
#endif
timers[k].start();
}
// start css animations
while(n--)
{
#if (DEBUG)
CPLog.debug("START ANIMATION " + cssAnimations[n].description());
#endif
cssAnimations[n].start();
}
}
@@ -350,9 +332,6 @@ var _CPAnimationContextStack = nil,
action.completion = function()
{
[aSubview setFrame:targetFrame];
#if (DEBUG)
CPLog.debug(aSubview + " setFrame: " + CPStringFromRect(targetFrame));
#endif
if (idx == count - 1)
[animatorClass stopUpdaterWithIdentifier:[anAction.root UID]];
};
@@ -401,9 +380,6 @@ var _CPAnimationContextStack = nil,
if (aCompletionHandler)
{
_completionHandlerAgent = new CompletionHandlerAgent(aCompletionHandler);
#if (DEBUG)
CPLog.debug("created a new completion Agent with id " + _completionHandlerAgent.id);
#endif
}
else
{
@@ -563,9 +539,6 @@ CompletionHandlerAgent.prototype.invalidate = function()
var _animationFlushingObserverCallback = function()
{
#if (DEBUG)
CPLog.debug("_animationFlushingObserverCallback");
#endif
if ([_CPAnimationContextStack count] == 1)
{
var context = [_CPAnimationContextStack lastObject];
@@ -573,15 +546,8 @@ var _animationFlushingObserverCallback = function()
[_CPAnimationContextStack removeLastObject];
}
#if (DEBUG)
CPLog.debug("_animationFlushingObserver "+_animationFlushingObserver+" stack:" + [_CPAnimationContextStack count]);
#endif
if (_animationFlushingObserver && ![_CPAnimationContextStack count])
{
#if (DEBUG)
CPLog.debug("removeObserver");
#endif
CFRunLoopObserverInvalidate([CPRunLoop mainRunLoop], _animationFlushingObserver);
_animationFlushingObserver = nil;
}
+3 -4
View File
@@ -394,11 +394,10 @@ var frameToCSSTranslationTransformMatrix = function(start, current)
- (Object)_DOMElement
{
#if PLATFORM(DOM)
return _DOMElement;
#else
if (CPDOMAvailable)
return _DOMElement;
return nil;
#endif
}
- (CPString)debug_description
+28 -22
View File
@@ -69,8 +69,10 @@ kCGColorSpaceSRGB = "CGColorSpaceSRGB";
var _CGNamedColorSpaces = {};
#define _CGColorSpaceCreateWithModel(aModel, aComponentCount, aBaseColorSpace) \
{ model:aModel, count:aComponentCount, base:aBaseColorSpace }
function _CGColorSpaceCreateWithModel(aModel, aComponentCount, aBaseColorSpace)
{
return { model:aModel, count:aComponentCount, base:aBaseColorSpace };
}
function CGColorSpaceCreateCalibratedGray(aWhitePoint, aBlackPoint, gamma)
{
@@ -208,24 +210,6 @@ function CGColorSpaceRetain(aColorSpace)
}
// FIXME: We should refer to some default values.
#define STANDARDIZE(components, index, minimum, maximum, multiplier) \
{ \
if (index > components.length) \
{ \
components[index] = maximum; \
return; \
} \
\
var component = components[index]; \
\
if (component < minimum) \
components[index] = minimum; \
else if (component > maximum) \
components[index] = maximum; \
else \
components[index] = ROUND(component * multiplier) / multiplier; \
}
function CGColorSpaceStandardizeComponents(aColorSpace, components)
{
var count = aColorSpace.count;
@@ -233,7 +217,20 @@ function CGColorSpaceStandardizeComponents(aColorSpace, components)
// Standardize the alpha value. We allow the alpha value to have a
// higher precision than other components since it is not ultimately
// bound to 256 bits like RGB.
STANDARDIZE(components, count, 0, 1, 1000);
if (count > components.length)
{
components[count] = 1;
return;
}
var component = components[count];
if (component < 0)
components[count] = 0;
else if (component > 1)
components[count] = 1;
else
components[count] = ROUND(component * 1000) / 1000;
if (aColorSpace.base)
aColorSpace = aColorSpace.base;
@@ -245,7 +242,16 @@ function CGColorSpaceStandardizeComponents(aColorSpace, components)
case kCGColorSpaceModelCMYK:
case kCGColorSpaceModelDeviceN:
while (count--)
STANDARDIZE(components, count, 0, 1, 255);
{
var standardizingComponent = components[count];
if (standardizingComponent < 0)
components[count] = 0;
else if (standardizingComponent > 1)
components[count] = 1;
else
components[count] = ROUND(standardizingComponent * 255) / 255;
}
break;
// We don't currently support these color spaces.
+650 -4
View File
@@ -730,11 +730,657 @@ function CGContextStrokeRoundedRectangleInRect(aContext, aRect, aRadius, ne, se,
*/
if (CPFeatureIsCompatible(CPHTMLCanvasFeature))
{
#include "CGContextCanvas.j"
}
else if (CPFeatureIsCompatible(CPVMLFeature))
// --- begin CoreGraphics/CGContextCanvas.j (inlined; include fragment removed for preprocessor-free build) ---
var CANVAS_LINECAP_TABLE = [ "butt", "round", "square" ],
CANVAS_LINEJOIN_TABLE = [ "miter", "round", "bevel" ],
CANVAS_COMPOSITE_TABLE = [ "source-over", "source-over", "source-over", "source-over", "darker",
"lighter", "source-over", "source-over", "source-over", "source-over",
"source-over", "source-over", "source-over", "source-over", "source-over",
"source-over", "source-over",
"copy", "source-in", "source-out", "source-atop",
"destination-over", "destination-in", "destination-out", "destination-atop",
"xor", "source-over", "source-over" ];
function _CGContextAddArcCanvas(aContext, x, y, radius, startAngle, endAngle, anticlockwise)
{
#include "CGContextVML.j"
return aContext.arc(x, y, radius, startAngle, endAngle, anticlockwise);
}
function _CGContextAddArcToPointCanvas(aContext, x1, y1, x2, y2, radius)
{
return aContext.arcTo(x1, y1, x2, y2, radius);
}
function _CGContextAddCurveToPointCanvas(aContext, cp1x, cp1y, cp2x, cp2y, x, y)
{
return aContext.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
}
function _CGContextAddQuadCurveToPointCanvas(aContext, cpx, cpy, x, y)
{
return aContext.quadraticCurveTo(cpx, cpy, x, y);
}
function _CGContextAddLineToPointCanvas(aContext, x, y)
{
return aContext.lineTo(x, y);
}
function _CGContextClosePathCanvas(aContext)
{
return aContext.closePath();
}
function _CGContextMoveToPointCanvas(aContext, x, y)
{
return aContext.moveTo(x, y);
}
function _CGContextAddRectCanvas(aContext, aRect)
{
return aContext.rect(CGRectGetMinX(aRect), CGRectGetMinY(aRect), CGRectGetWidth(aRect), CGRectGetHeight(aRect));
}
function _CGContextBeginPathCanvas(aContext)
{
return aContext.beginPath();
}
function _CGContextFillRectCanvas(aContext, aRect)
{
return aContext.fillRect(CGRectGetMinX(aRect), CGRectGetMinY(aRect), CGRectGetWidth(aRect), CGRectGetHeight(aRect));
}
function _CGContextClipCanvas(aContext)
{
return aContext.clip();
}
// In Cocoa, all primitives excepts rects and arcs cannot be added to the context's path
// until a move to point has been done, because an empty path has no current point.
var hasPath = function(aContext, methodName)
{
if (!aContext.hasPath)
CPLog.error(methodName + ": no current point");
return aContext.hasPath;
}
function CGContextSaveGState(aContext)
{
aContext.save();
}
function CGContextRestoreGState(aContext)
{
aContext.restore();
}
function CGContextSetLineCap(aContext, aLineCap)
{
aContext.lineCap = CANVAS_LINECAP_TABLE[aLineCap];
}
function CGContextSetLineDash(aContext, aPhase, someDashes)
{
if (aContext.setLineDash)
{
aContext.setLineDash(someDashes);
aContext.lineDashOffset = aPhase;
}
else if (typeof aContext['webkitLineDash'] !== 'undefined')
{
aContext.webkitLineDash = someDashes;
aContext.webkitLineDashOffset = aPhase;
}
else if (typeof aContext['mozDash'] !== 'undefined')
{
aContext.mozDash = someDashes;
aContext.mozDashOffset = aPhase;
}
else if (someDashes)
{
CPLog.warn("CGContextSetLineDash not implemented in this environment.")
}
}
function CGContextSetLineJoin(aContext, aLineJoin)
{
aContext.lineJoin = CANVAS_LINEJOIN_TABLE[aLineJoin];
}
function CGContextSetLineWidth(aContext, aLineWidth)
{
aContext.lineWidth = aLineWidth;
}
function CGContextSetMiterLimit(aContext, aMiterLimit)
{
aContext.miterLimit = aMiterLimit;
}
function CGContextSetBlendMode(aContext, aBlendMode)
{
aContext.globalCompositeOperation = CANVAS_COMPOSITE_TABLE[aBlendMode];
}
function CGContextAddArc(aContext, x, y, radius, startAngle, endAngle, clockwise)
{
// Despite the documentation saying otherwise, the last parameter is anti-clockwise not clockwise.
// http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes#Arcs
_CGContextAddArcCanvas(aContext, x, y, radius, startAngle, endAngle, !clockwise);
// AddArc implicitly starts a path
aContext.hasPath = YES;
}
function CGContextAddArcToPoint(aContext, x1, y1, x2, y2, radius)
{
if (!hasPath(aContext, "CGContextAddArcToPoint"))
return;
_CGContextAddArcToPointCanvas(aContext, x1, y1, x2, y2, radius);
}
function CGContextAddCurveToPoint(aContext, cp1x, cp1y, cp2x, cp2y, x, y)
{
if (!hasPath(aContext, "CGContextAddCurveToPoint"))
return;
_CGContextAddCurveToPointCanvas(aContext, cp1x, cp1y, cp2x, cp2y, x, y);
}
function CGContextAddLines(aContext, points, count)
{
// implementation mirrors that of CGPathAddLines()
if (count == null)
count = points.length;
if (count < 1)
return;
_CGContextMoveToPointCanvas(aContext, points[0].x, points[0].y);
for (var i = 1; i < count; ++i)
_CGContextAddLineToPointCanvas(aContext, points[i].x, points[i].y);
aContext.hasPath = YES;
}
function CGContextAddLineToPoint(aContext, x, y)
{
if (!hasPath(aContext, "CGContextAddLineToPoint"))
return;
_CGContextAddLineToPointCanvas(aContext, x, y);
}
function CGContextAddPath(aContext, aPath)
{
if (!aContext || CGPathIsEmpty(aPath))
return;
// If the context does not have a path, explicitly begin one
if (!aContext.hasPath)
_CGContextBeginPathCanvas(aContext);
// We must implicitly move to the start of the path
_CGContextMoveToPointCanvas(aContext, aPath.start.x, aPath.start.y);
var elements = aPath.elements,
i = 0,
count = aPath.count;
for (; i < count; ++i)
{
var element = elements[i],
type = element.type;
switch (type)
{
case kCGPathElementMoveToPoint:
_CGContextMoveToPointCanvas(aContext, element.x, element.y);
break;
case kCGPathElementAddLineToPoint:
_CGContextAddLineToPointCanvas(aContext, element.x, element.y);
break;
case kCGPathElementAddQuadCurveToPoint:
_CGContextAddQuadCurveToPointCanvas(aContext, element.cpx, element.cpy, element.x, element.y);
break;
case kCGPathElementAddCurveToPoint:
_CGContextAddCurveToPointCanvas(aContext, element.cp1x, element.cp1y, element.cp2x, element.cp2y, element.x, element.y);
break;
case kCGPathElementCloseSubpath:
_CGContextClosePathCanvas(aContext);
break;
case kCGPathElementAddArc:
_CGContextAddArcCanvas(aContext, element.x, element.y, element.radius, element.startAngle, element.endAngle, element.clockwise);
break;
case kCGPathElementAddArcToPoint:
_CGContextAddArcToPointCanvas(aContext, element.p1x, element.p1y, element.p2x, element.p2y, element.radius);
break;
}
}
aContext.hasPath = YES;
}
function CGContextAddRect(aContext, aRect)
{
_CGContextAddRectCanvas(aContext, aRect);
aContext.hasPath = YES;
}
function CGContextAddQuadCurveToPoint(aContext, cpx, cpy, x, y)
{
if (!hasPath(aContext, "CGContextAddQuadCurveToPoint"))
return;
_CGContextAddQuadCurveToPointCanvas(aContext, cpx, cpy, x, y);
}
function CGContextAddRects(aContext, rects, count)
{
if (count == null)
count = rects.length;
for (var i = 0; i < count; ++i)
{
var rect = rects[i];
_CGContextAddRectCanvas(aContext, rect);
}
aContext.hasPath = YES;
}
function CGContextBeginPath(aContext)
{
_CGContextBeginPathCanvas(aContext);
aContext.hasPath = NO;
}
function CGContextClosePath(aContext)
{
_CGContextClosePathCanvas(aContext);
}
function CGContextIsPathEmpty(aContext)
{
return !aContext.hasPath;
}
function CGContextMoveToPoint(aContext, x, y)
{
_CGContextMoveToPointCanvas(aContext, x, y);
aContext.hasPath = YES;
}
function CGContextClearRect(aContext, aRect)
{
aContext.clearRect(CGRectGetMinX(aRect), CGRectGetMinY(aRect), CGRectGetWidth(aRect), CGRectGetHeight(aRect));
aContext.hasPath = NO;
}
function CGContextDrawPath(aContext, aMode)
{
if (!aContext.hasPath)
return;
if (aMode === kCGPathFill || aMode === kCGPathFillStroke)
aContext.fill();
else if (aMode === kCGPathStroke || aMode === kCGPathFillStroke || aMode === kCGPathEOFillStroke)
aContext.stroke();
else if (aMode === kCGPathEOFill || aMode === kCGPathEOFillStroke)
CPLog.warn("Unimplemented fill mode in CGContextDrawPath: %d", aMode);
aContext.hasPath = NO;
}
function CGContextFillRect(aContext, aRect)
{
_CGContextFillRectCanvas(aContext, aRect);
aContext.hasPath = NO;
}
function CGContextFillRects(aContext, rects, count)
{
if (count == null)
count = rects.length;
for (var i = 0; i < count; ++i)
{
var rect = rects[i];
_CGContextFillRectCanvas(aContext, rect);
}
aContext.hasPath = NO;
}
function CGContextStrokeRect(aContext, aRect)
{
aContext.strokeRect(CGRectGetMinX(aRect), CGRectGetMinY(aRect), CGRectGetWidth(aRect), CGRectGetHeight(aRect));
aContext.hasPath = NO;
}
function CGContextClip(aContext)
{
_CGContextClipCanvas(aContext);
aContext.hasPath = NO;
}
function CGContextClipToRect(aContext, aRect)
{
_CGContextBeginPathCanvas(aContext);
_CGContextAddRectCanvas(aContext, aRect);
_CGContextClosePathCanvas(aContext);
_CGContextClipCanvas(aContext);
aContext.hasPath = NO;
}
function CGContextClipToRects(aContext, rects, count)
{
if (count == null)
count = rects.length;
_CGContextBeginPathCanvas(aContext);
CGContextAddRects(aContext, rects, count);
_CGContextClipCanvas(aContext);
aContext.hasPath = NO;
}
function CGContextSetAlpha(aContext, anAlpha)
{
aContext.globalAlpha = anAlpha;
}
function CGContextSetFillColor(aContext, aColor)
{
var patternImage = [aColor patternImage];
if ([patternImage isSingleImage])
{
var pattern = aContext.createPattern([patternImage image], "repeat");
aContext.fillStyle = pattern;
}
else
aContext.fillStyle = [aColor cssString];
}
/*!
Creates a context into which you can render a fill pattern
of the given size. Once the pattern is rendered, you can
set the fill or stroke pattern to the rendered pattern
with CGContextSetFillPattern or CGContextSetStrokePattern.
*/
function CGContextCreatePatternContext(aContext, aSize)
{
var pattern = document.createElement("canvas");
pattern.width = aSize.width;
pattern.height = aSize.height;
return pattern.getContext("2d");
}
/*!
Sets the fill pattern for aContext to the rendered pattern context
returned by CGContextCreatePatternContext.
*/
function CGContextSetFillPattern(aContext, aPatternContext)
{
var pattern = aContext.createPattern(aPatternContext.canvas, "repeat");
aContext.fillStyle = pattern;
}
/*!
Sets the stroke pattern for aContext to the rendered pattern context
returned by CGContextCreatePatternContext.
*/
function CGContextSetStrokePattern(aContext, aPatternContext)
{
var pattern = aContext.createPattern(aPatternContext.canvas, "repeat");
aContext.strokeStyle = pattern;
}
function CGContextSetStrokeColor(aContext, aColor)
{
var patternImage = [aColor patternImage];
if ([patternImage isSingleImage])
{
var pattern = aContext.createPattern([patternImage image], "repeat");
aContext.strokeStyle = pattern;
}
else
aContext.strokeStyle = [aColor cssString];
}
function CGContextSetShadow(aContext, aSize, aBlur)
{
aContext.shadowOffsetX = aSize.width;
aContext.shadowOffsetY = aSize.height;
aContext.shadowBlur = aBlur;
aContext.shadowColor = [[CPColor shadowColor] cssString];
}
function CGContextSetShadowWithColor(aContext, aSize, aBlur, aColor)
{
aContext.shadowOffsetX = aSize.width;
aContext.shadowOffsetY = aSize.height;
aContext.shadowBlur = aBlur;
aContext.shadowColor = [aColor cssString];
}
function CGContextRotateCTM(aContext, anAngle)
{
aContext.rotate(anAngle);
}
function CGContextScaleCTM(aContext, sx, sy)
{
aContext.scale(sx, sy);
}
function CGContextTranslateCTM(aContext, tx, ty)
{
aContext.translate(tx, ty);
}
var scale_rotate = function(a, b, c, d)
{
var sign = (a * d < 0.0 || b * c > 0.0) ? -1.0 : 1.0,
a2 = (ATAN2(b, d) + ATAN2(-sign * c, sign * a)) / 2.0,
cos = COS(a2),
sin = SIN(a2),
abs_cos,
abs_sin;
if (cos === 0)
{
sx = -c / sin;
sy = b / sin;
}
else if (sin === 0)
{
sx = a / cos;
sy = d / cos;
}
else
{
abs_cos = ABS(cos);
abs_sin = ABS(sin);
sx = (abs_cos * a / cos + abs_sin * -c / sin) / (abs_cos + abs_sin);
sy = (abs_cos * d / cos + abs_sin * b / sin) / (abs_cos + abs_sin);
}
};
var rotate_scale = function(a, b, c, d)
{
var sign = (a * d < 0.0 || b * c > 0.0) ? -1.0 : 1.0,
a1 = (ATAN2(sign * b, sign * a) + ATAN2(-c, d)) / 2.0,
cos = COS(a1),
sin = SIN(a1),
abs_cos,
abs_sin;
if (cos === 0)
{
sx = b / sin;
sy = -c / sin;
}
else if (sin === 0)
{
sx = a / cos;
sy = d / cos;
}
else
{
abs_cos = ABS(cos);
abs_sin = ABS(sin);
sx = (abs_cos * a / cos + abs_sin * b / sin) / (abs_cos + abs_sin);
sy = (abs_cos * d / cos + abs_sin * -c / sin) / (abs_cos + abs_sin);
}
};
function eigen(anAffineTransform)
{
CPLog.warn("Unimplemented function: eigen");
}
if (CPFeatureIsCompatible(CPJavaScriptCanvasTransformFeature))
{
CGContextConcatCTM = function(aContext, anAffineTransform)
{
aContext.transform(anAffineTransform.a, anAffineTransform.b, anAffineTransform.c, anAffineTransform.d, anAffineTransform.tx, anAffineTransform.ty);
};
}
else
{
CGContextConcatCTM = function(aContext, anAffineTransform)
{
var a = anAffineTransform.a,
b = anAffineTransform.b,
c = anAffineTransform.c,
d = anAffineTransform.d,
tx = anAffineTransform.tx,
ty = anAffineTransform.ty,
sx = 1.0,
sy = 1.0,
a1 = 0.0,
a2 = 0.0;
// Detect the simple case of just scaling.
if (b === 0.0 && c === 0.0)
{
sx = a;
sy = d;
}
// a scale followed by a rotate
else if (a * b === -c * d)
{
scale_rotate(a, b, c, d)
}
// rotate, then scale.
else if (a * c === -b * d)
{
rotate_scale(a, b, c, d)
}
else
{
var transpose = CGAffineTransformMake(a, c, b, d, 0.0, 0.0), // inline
u = eigen(CGAffineTransformConcat(anAffineTransform, transpose)),
v = eigen(CGAffineTransformConcat(transpose, anAffineTransform)),
U = CGAffineTransformMake(u.vector_1.x, u.vector_2.x, u.vector_1.y, u.vector_2.y, 0.0, 0.0), // inline
VT = CGAffineTransformMake(v.vector_1.x, v.vector_1.y, v.vector_2.x, v.vector_2.y, 0.0, 0.0),
S = CGAffineTransformConcat(CGAffineTransformConcat(CGAffineTransformInvert(U), anAffineTransform), CGAffineTransformInvert(VT));
a = VT.a;
b = VT.b;
c = VT.c;
d = VT.d;
scale_rotate(a, b, c, d);
S.a *= sx;
S.d *= sy;
a = U.a;
b = U.b;
c = U.c;
d = U.d;
rotate_scale(a, b, c, d);
sx = S.a * sx;
sy = S.d * sy;
}
if (tx != 0 || ty != 0)
CGContextTranslateCTM(aContext, tx, ty);
if (a1 != 0.0)
CGContextRotateCTM(aContext, a1);
if (sx != 1.0 || sy != 1.0)
CGContextScaleCTM(aContext, sx, sy);
if (a2 != 0.0)
CGContextRotateCTM(aContext, a2);
};
}
function CGContextDrawImage(aContext, aRect, anImage)
{
aContext.drawImage(anImage._image, CGRectGetMinX(aRect), CGRectGetMinY(aRect), CGRectGetWidth(aRect), CGRectGetHeight(aRect));
aContext.hasPath = NO;
}
function to_string(aColor)
{
return "rgba(" + ROUND(aColor.components[0] * 255) + ", " + ROUND(aColor.components[1] * 255) + ", " + ROUND(255 * aColor.components[2]) + ", " + aColor.components[3] + ")";
}
function CGContextDrawLinearGradient(aContext, aGradient, aStartPoint, anEndPoint, options)
{
var colors = aGradient.colors,
count = colors.length,
linearGradient = aContext.createLinearGradient(aStartPoint.x, aStartPoint.y, anEndPoint.x, anEndPoint.y);
while (count--)
linearGradient.addColorStop(aGradient.locations[count], to_string(colors[count]));
aContext.fillStyle = linearGradient;
aContext.fill();
aContext.hasPath = NO;
}
function CGContextDrawRadialGradient(aContext, aGradient, aStartCenter, aStartRadius, anEndCenter, anEndRadius, options)
{
var colors = aGradient.colors,
count = colors.length,
linearGradient = aContext.createRadialGradient(aStartCenter.x, aStartCenter.y, aStartRadius, anEndCenter.x, anEndCenter.y, anEndRadius);
while (count--)
linearGradient.addColorStop(aGradient.locations[count], to_string(colors[count]));
aContext.fillStyle = linearGradient;
aContext.fill();
aContext.hasPath = NO;
}
function CGBitmapGraphicsContextCreate()
{
var DOMElement = document.createElement("canvas"),
context = DOMElement.getContext("2d");
context.DOMElement = DOMElement;
// canvas gives us no way to query whether the path is empty or not, so we have to track it ourselves
context.hasPath = NO;
return context;
}
}
else
{
-639
View File
@@ -1,639 +0,0 @@
/*
* CGContextCanvas.j
* AppKit
*
* Created by Francisco Tolmasky.
* Copyright 2008, 280 North, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
var CANVAS_LINECAP_TABLE = [ "butt", "round", "square" ],
CANVAS_LINEJOIN_TABLE = [ "miter", "round", "bevel" ],
CANVAS_COMPOSITE_TABLE = [ "source-over", "source-over", "source-over", "source-over", "darker",
"lighter", "source-over", "source-over", "source-over", "source-over",
"source-over", "source-over", "source-over", "source-over", "source-over",
"source-over", "source-over",
"copy", "source-in", "source-out", "source-atop",
"destination-over", "destination-in", "destination-out", "destination-atop",
"xor", "source-over", "source-over" ];
#define _CGContextAddArcCanvas(aContext, x, y, radius, startAngle, endAngle, anticlockwise) aContext.arc(x, y, radius, startAngle, endAngle, anticlockwise)
#define _CGContextAddArcToPointCanvas(aContext, x1, y1, x2, y2, radius) aContext.arcTo(x1, y1, x2, y2, radius)
#define _CGContextAddCurveToPointCanvas(aContext, cp1x, cp1y, cp2x, cp2y, x, y) aContext.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)
#define _CGContextAddQuadCurveToPointCanvas(aContext, cpx, cpy, x, y) aContext.quadraticCurveTo(cpx, cpy, x, y)
#define _CGContextAddLineToPointCanvas(aContext, x, y) aContext.lineTo(x, y)
#define _CGContextClosePathCanvas(aContext) aContext.closePath()
#define _CGContextMoveToPointCanvas(aContext, x, y) aContext.moveTo(x, y)
#define _CGContextAddRectCanvas(aContext, aRect) aContext.rect(CGRectGetMinX(aRect), CGRectGetMinY(aRect), CGRectGetWidth(aRect), CGRectGetHeight(aRect))
#define _CGContextBeginPathCanvas(aContext) aContext.beginPath()
#define _CGContextFillRectCanvas(aContext, aRect) aContext.fillRect(CGRectGetMinX(aRect), CGRectGetMinY(aRect), CGRectGetWidth(aRect), CGRectGetHeight(aRect))
#define _CGContextClipCanvas(aContext) aContext.clip()
// In Cocoa, all primitives excepts rects and arcs cannot be added to the context's path
// until a move to point has been done, because an empty path has no current point.
var hasPath = function(aContext, methodName)
{
if (!aContext.hasPath)
CPLog.error(methodName + ": no current point");
return aContext.hasPath;
}
function CGContextSaveGState(aContext)
{
aContext.save();
}
function CGContextRestoreGState(aContext)
{
aContext.restore();
}
function CGContextSetLineCap(aContext, aLineCap)
{
aContext.lineCap = CANVAS_LINECAP_TABLE[aLineCap];
}
function CGContextSetLineDash(aContext, aPhase, someDashes)
{
if (aContext.setLineDash)
{
aContext.setLineDash(someDashes);
aContext.lineDashOffset = aPhase;
}
else if (typeof aContext['webkitLineDash'] !== 'undefined')
{
aContext.webkitLineDash = someDashes;
aContext.webkitLineDashOffset = aPhase;
}
else if (typeof aContext['mozDash'] !== 'undefined')
{
aContext.mozDash = someDashes;
aContext.mozDashOffset = aPhase;
}
else if (someDashes)
{
CPLog.warn("CGContextSetLineDash not implemented in this environment.")
}
}
function CGContextSetLineJoin(aContext, aLineJoin)
{
aContext.lineJoin = CANVAS_LINEJOIN_TABLE[aLineJoin];
}
function CGContextSetLineWidth(aContext, aLineWidth)
{
aContext.lineWidth = aLineWidth;
}
function CGContextSetMiterLimit(aContext, aMiterLimit)
{
aContext.miterLimit = aMiterLimit;
}
function CGContextSetBlendMode(aContext, aBlendMode)
{
aContext.globalCompositeOperation = CANVAS_COMPOSITE_TABLE[aBlendMode];
}
function CGContextAddArc(aContext, x, y, radius, startAngle, endAngle, clockwise)
{
// Despite the documentation saying otherwise, the last parameter is anti-clockwise not clockwise.
// http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes#Arcs
_CGContextAddArcCanvas(aContext, x, y, radius, startAngle, endAngle, !clockwise);
// AddArc implicitly starts a path
aContext.hasPath = YES;
}
function CGContextAddArcToPoint(aContext, x1, y1, x2, y2, radius)
{
if (!hasPath(aContext, "CGContextAddArcToPoint"))
return;
_CGContextAddArcToPointCanvas(aContext, x1, y1, x2, y2, radius);
}
function CGContextAddCurveToPoint(aContext, cp1x, cp1y, cp2x, cp2y, x, y)
{
if (!hasPath(aContext, "CGContextAddCurveToPoint"))
return;
_CGContextAddCurveToPointCanvas(aContext, cp1x, cp1y, cp2x, cp2y, x, y);
}
function CGContextAddLines(aContext, points, count)
{
// implementation mirrors that of CGPathAddLines()
if (count == null)
count = points.length;
if (count < 1)
return;
_CGContextMoveToPointCanvas(aContext, points[0].x, points[0].y);
for (var i = 1; i < count; ++i)
_CGContextAddLineToPointCanvas(aContext, points[i].x, points[i].y);
aContext.hasPath = YES;
}
function CGContextAddLineToPoint(aContext, x, y)
{
if (!hasPath(aContext, "CGContextAddLineToPoint"))
return;
_CGContextAddLineToPointCanvas(aContext, x, y);
}
function CGContextAddPath(aContext, aPath)
{
if (!aContext || CGPathIsEmpty(aPath))
return;
// If the context does not have a path, explicitly begin one
if (!aContext.hasPath)
_CGContextBeginPathCanvas(aContext);
// We must implicitly move to the start of the path
_CGContextMoveToPointCanvas(aContext, aPath.start.x, aPath.start.y);
var elements = aPath.elements,
i = 0,
count = aPath.count;
for (; i < count; ++i)
{
var element = elements[i],
type = element.type;
switch (type)
{
case kCGPathElementMoveToPoint:
_CGContextMoveToPointCanvas(aContext, element.x, element.y);
break;
case kCGPathElementAddLineToPoint:
_CGContextAddLineToPointCanvas(aContext, element.x, element.y);
break;
case kCGPathElementAddQuadCurveToPoint:
_CGContextAddQuadCurveToPointCanvas(aContext, element.cpx, element.cpy, element.x, element.y);
break;
case kCGPathElementAddCurveToPoint:
_CGContextAddCurveToPointCanvas(aContext, element.cp1x, element.cp1y, element.cp2x, element.cp2y, element.x, element.y);
break;
case kCGPathElementCloseSubpath:
_CGContextClosePathCanvas(aContext);
break;
case kCGPathElementAddArc:
_CGContextAddArcCanvas(aContext, element.x, element.y, element.radius, element.startAngle, element.endAngle, element.clockwise);
break;
case kCGPathElementAddArcToPoint:
_CGContextAddArcToPointCanvas(aContext, element.p1x, element.p1y, element.p2x, element.p2y, element.radius);
break;
}
}
aContext.hasPath = YES;
}
function CGContextAddRect(aContext, aRect)
{
_CGContextAddRectCanvas(aContext, aRect);
aContext.hasPath = YES;
}
function CGContextAddQuadCurveToPoint(aContext, cpx, cpy, x, y)
{
if (!hasPath(aContext, "CGContextAddQuadCurveToPoint"))
return;
_CGContextAddQuadCurveToPointCanvas(aContext, cpx, cpy, x, y);
}
function CGContextAddRects(aContext, rects, count)
{
if (count == null)
count = rects.length;
for (var i = 0; i < count; ++i)
{
var rect = rects[i];
_CGContextAddRectCanvas(aContext, rect);
}
aContext.hasPath = YES;
}
function CGContextBeginPath(aContext)
{
_CGContextBeginPathCanvas(aContext);
aContext.hasPath = NO;
}
function CGContextClosePath(aContext)
{
_CGContextClosePathCanvas(aContext);
}
function CGContextIsPathEmpty(aContext)
{
return !aContext.hasPath;
}
function CGContextMoveToPoint(aContext, x, y)
{
_CGContextMoveToPointCanvas(aContext, x, y);
aContext.hasPath = YES;
}
function CGContextClearRect(aContext, aRect)
{
aContext.clearRect(CGRectGetMinX(aRect), CGRectGetMinY(aRect), CGRectGetWidth(aRect), CGRectGetHeight(aRect));
aContext.hasPath = NO;
}
function CGContextDrawPath(aContext, aMode)
{
if (!aContext.hasPath)
return;
if (aMode === kCGPathFill || aMode === kCGPathFillStroke)
aContext.fill();
else if (aMode === kCGPathStroke || aMode === kCGPathFillStroke || aMode === kCGPathEOFillStroke)
aContext.stroke();
else if (aMode === kCGPathEOFill || aMode === kCGPathEOFillStroke)
CPLog.warn("Unimplemented fill mode in CGContextDrawPath: %d", aMode);
aContext.hasPath = NO;
}
function CGContextFillRect(aContext, aRect)
{
_CGContextFillRectCanvas(aContext, aRect);
aContext.hasPath = NO;
}
function CGContextFillRects(aContext, rects, count)
{
if (count == null)
count = rects.length;
for (var i = 0; i < count; ++i)
{
var rect = rects[i];
_CGContextFillRectCanvas(aContext, rect);
}
aContext.hasPath = NO;
}
function CGContextStrokeRect(aContext, aRect)
{
aContext.strokeRect(CGRectGetMinX(aRect), CGRectGetMinY(aRect), CGRectGetWidth(aRect), CGRectGetHeight(aRect));
aContext.hasPath = NO;
}
function CGContextClip(aContext)
{
_CGContextClipCanvas(aContext);
aContext.hasPath = NO;
}
function CGContextClipToRect(aContext, aRect)
{
_CGContextBeginPathCanvas(aContext);
_CGContextAddRectCanvas(aContext, aRect);
_CGContextClosePathCanvas(aContext);
_CGContextClipCanvas(aContext);
aContext.hasPath = NO;
}
function CGContextClipToRects(aContext, rects, count)
{
if (count == null)
count = rects.length;
_CGContextBeginPathCanvas(aContext);
CGContextAddRects(aContext, rects, count);
_CGContextClipCanvas(aContext);
aContext.hasPath = NO;
}
function CGContextSetAlpha(aContext, anAlpha)
{
aContext.globalAlpha = anAlpha;
}
function CGContextSetFillColor(aContext, aColor)
{
var patternImage = [aColor patternImage];
if ([patternImage isSingleImage])
{
var pattern = aContext.createPattern([patternImage image], "repeat");
aContext.fillStyle = pattern;
}
else
aContext.fillStyle = [aColor cssString];
}
/*!
Creates a context into which you can render a fill pattern
of the given size. Once the pattern is rendered, you can
set the fill or stroke pattern to the rendered pattern
with CGContextSetFillPattern or CGContextSetStrokePattern.
*/
function CGContextCreatePatternContext(aContext, aSize)
{
var pattern = document.createElement("canvas");
pattern.width = aSize.width;
pattern.height = aSize.height;
return pattern.getContext("2d");
}
/*!
Sets the fill pattern for aContext to the rendered pattern context
returned by CGContextCreatePatternContext.
*/
function CGContextSetFillPattern(aContext, aPatternContext)
{
var pattern = aContext.createPattern(aPatternContext.canvas, "repeat");
aContext.fillStyle = pattern;
}
/*!
Sets the stroke pattern for aContext to the rendered pattern context
returned by CGContextCreatePatternContext.
*/
function CGContextSetStrokePattern(aContext, aPatternContext)
{
var pattern = aContext.createPattern(aPatternContext.canvas, "repeat");
aContext.strokeStyle = pattern;
}
function CGContextSetStrokeColor(aContext, aColor)
{
var patternImage = [aColor patternImage];
if ([patternImage isSingleImage])
{
var pattern = aContext.createPattern([patternImage image], "repeat");
aContext.strokeStyle = pattern;
}
else
aContext.strokeStyle = [aColor cssString];
}
function CGContextSetShadow(aContext, aSize, aBlur)
{
aContext.shadowOffsetX = aSize.width;
aContext.shadowOffsetY = aSize.height;
aContext.shadowBlur = aBlur;
aContext.shadowColor = [[CPColor shadowColor] cssString];
}
function CGContextSetShadowWithColor(aContext, aSize, aBlur, aColor)
{
aContext.shadowOffsetX = aSize.width;
aContext.shadowOffsetY = aSize.height;
aContext.shadowBlur = aBlur;
aContext.shadowColor = [aColor cssString];
}
function CGContextRotateCTM(aContext, anAngle)
{
aContext.rotate(anAngle);
}
function CGContextScaleCTM(aContext, sx, sy)
{
aContext.scale(sx, sy);
}
function CGContextTranslateCTM(aContext, tx, ty)
{
aContext.translate(tx, ty);
}
var scale_rotate = function(a, b, c, d)
{
var sign = (a * d < 0.0 || b * c > 0.0) ? -1.0 : 1.0,
a2 = (ATAN2(b, d) + ATAN2(-sign * c, sign * a)) / 2.0,
cos = COS(a2),
sin = SIN(a2),
abs_cos,
abs_sin;
if (cos === 0)
{
sx = -c / sin;
sy = b / sin;
}
else if (sin === 0)
{
sx = a / cos;
sy = d / cos;
}
else
{
abs_cos = ABS(cos);
abs_sin = ABS(sin);
sx = (abs_cos * a / cos + abs_sin * -c / sin) / (abs_cos + abs_sin);
sy = (abs_cos * d / cos + abs_sin * b / sin) / (abs_cos + abs_sin);
}
};
var rotate_scale = function(a, b, c, d)
{
var sign = (a * d < 0.0 || b * c > 0.0) ? -1.0 : 1.0,
a1 = (ATAN2(sign * b, sign * a) + ATAN2(-c, d)) / 2.0,
cos = COS(a1),
sin = SIN(a1),
abs_cos,
abs_sin;
if (cos === 0)
{
sx = b / sin;
sy = -c / sin;
}
else if (sin === 0)
{
sx = a / cos;
sy = d / cos;
}
else
{
abs_cos = ABS(cos);
abs_sin = ABS(sin);
sx = (abs_cos * a / cos + abs_sin * b / sin) / (abs_cos + abs_sin);
sy = (abs_cos * d / cos + abs_sin * -c / sin) / (abs_cos + abs_sin);
}
};
function eigen(anAffineTransform)
{
CPLog.warn("Unimplemented function: eigen");
}
if (CPFeatureIsCompatible(CPJavaScriptCanvasTransformFeature))
{
CGContextConcatCTM = function(aContext, anAffineTransform)
{
aContext.transform(anAffineTransform.a, anAffineTransform.b, anAffineTransform.c, anAffineTransform.d, anAffineTransform.tx, anAffineTransform.ty);
};
}
else
{
CGContextConcatCTM = function(aContext, anAffineTransform)
{
var a = anAffineTransform.a,
b = anAffineTransform.b,
c = anAffineTransform.c,
d = anAffineTransform.d,
tx = anAffineTransform.tx,
ty = anAffineTransform.ty,
sx = 1.0,
sy = 1.0,
a1 = 0.0,
a2 = 0.0;
// Detect the simple case of just scaling.
if (b === 0.0 && c === 0.0)
{
sx = a;
sy = d;
}
// a scale followed by a rotate
else if (a * b === -c * d)
{
scale_rotate(a, b, c, d)
}
// rotate, then scale.
else if (a * c === -b * d)
{
rotate_scale(a, b, c, d)
}
else
{
var transpose = CGAffineTransformMake(a, c, b, d, 0.0, 0.0), // inline
u = eigen(CGAffineTransformConcat(anAffineTransform, transpose)),
v = eigen(CGAffineTransformConcat(transpose, anAffineTransform)),
U = CGAffineTransformMake(u.vector_1.x, u.vector_2.x, u.vector_1.y, u.vector_2.y, 0.0, 0.0), // inline
VT = CGAffineTransformMake(v.vector_1.x, v.vector_1.y, v.vector_2.x, v.vector_2.y, 0.0, 0.0),
S = CGAffineTransformConcat(CGAffineTransformConcat(CGAffineTransformInvert(U), anAffineTransform), CGAffineTransformInvert(VT));
a = VT.a;
b = VT.b;
c = VT.c;
d = VT.d;
scale_rotate(a, b, c, d);
S.a *= sx;
S.d *= sy;
a = U.a;
b = U.b;
c = U.c;
d = U.d;
rotate_scale(a, b, c, d);
sx = S.a * sx;
sy = S.d * sy;
}
if (tx != 0 || ty != 0)
CGContextTranslateCTM(aContext, tx, ty);
if (a1 != 0.0)
CGContextRotateCTM(aContext, a1);
if (sx != 1.0 || sy != 1.0)
CGContextScaleCTM(aContext, sx, sy);
if (a2 != 0.0)
CGContextRotateCTM(aContext, a2);
};
}
function CGContextDrawImage(aContext, aRect, anImage)
{
aContext.drawImage(anImage._image, CGRectGetMinX(aRect), CGRectGetMinY(aRect), CGRectGetWidth(aRect), CGRectGetHeight(aRect));
aContext.hasPath = NO;
}
function to_string(aColor)
{
return "rgba(" + ROUND(aColor.components[0] * 255) + ", " + ROUND(aColor.components[1] * 255) + ", " + ROUND(255 * aColor.components[2]) + ", " + aColor.components[3] + ")";
}
function CGContextDrawLinearGradient(aContext, aGradient, aStartPoint, anEndPoint, options)
{
var colors = aGradient.colors,
count = colors.length,
linearGradient = aContext.createLinearGradient(aStartPoint.x, aStartPoint.y, anEndPoint.x, anEndPoint.y);
while (count--)
linearGradient.addColorStop(aGradient.locations[count], to_string(colors[count]));
aContext.fillStyle = linearGradient;
aContext.fill();
aContext.hasPath = NO;
}
function CGContextDrawRadialGradient(aContext, aGradient, aStartCenter, aStartRadius, anEndCenter, anEndRadius, options)
{
var colors = aGradient.colors,
count = colors.length,
linearGradient = aContext.createRadialGradient(aStartCenter.x, aStartCenter.y, aStartRadius, anEndCenter.x, anEndCenter.y, anEndRadius);
while (count--)
linearGradient.addColorStop(aGradient.locations[count], to_string(colors[count]));
aContext.fillStyle = linearGradient;
aContext.fill();
aContext.hasPath = NO;
}
function CGBitmapGraphicsContextCreate()
{
var DOMElement = document.createElement("canvas"),
context = DOMElement.getContext("2d");
context.DOMElement = DOMElement;
// canvas gives us no way to query whether the path is empty or not, so we have to track it ourselves
context.hasPath = NO;
return context;
}
-335
View File
@@ -1,335 +0,0 @@
/*
* CGContextVML.j
* AppKit
*
* Created by Francisco Tolmasky.
* Copyright 2008, 280 North, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
var VML_TRUTH_TABLE = [ "f", "t"],
VML_LINECAP_TABLE = [ "flat", "round", "square" ],
VML_LINEJOIN_TABLE = [ "miter", "round", "bevel" ],
VML_ELEMENT_TABLE = [ " m ", " l ", "qb", " c ", " x ", [" at ", " wa "]];
var _CGBitmapGraphicsContextCreate = CGBitmapGraphicsContextCreate;
function CGBitmapGraphicsContextCreate()
{
// The first time around, we have to set up our environment to support vml.
document.namespaces.add("cg_vml_", "urn:schemas-microsoft-com:vml");
document.createStyleSheet().cssText = "cg_vml_\\:*{behavior:url(#default#VML)}";
CGBitmapGraphicsContextCreate = _CGBitmapGraphicsContextCreate;
return _CGBitmapGraphicsContextCreate();
}
function CGContextSetFillColor(aContext, aColor)
{
if ([aColor patternImage])
// Prefix a marker character to the string so we know it's a pattern image filename
aContext.gState.fillStyle = "!" + [[aColor patternImage] filename];
else
aContext.gState.fillStyle = [aColor cssString];
}
// FIXME: aRect is ignored.
function CGContextClearRect(aContext, aRect)
{
if (aContext.buffer != nil)
aContext.buffer = "";
else
aContext.DOMElement.innerHTML = "";
aContext.path = NULL;
}
var W = 10.0,
H = 10.0,
Z = 10.0,
Z_2 = Z / 2.0;
#define COORD(aCoordinate) (aCoordinate === 0.0 ? 0 : ROUND(Z * (aCoordinate) - Z_2))
function CGContextDrawImage(aContext, aRect, anImage)
{
var string = "";
if (anImage.buffer != nil)
string = anImage.buffer;
else
{
var ctm = aContext.gState.CTM,
origin = CGPointApplyAffineTransform(aRect.origin, ctm),
similarity = ctm.a == ctm.d && ctm.b == -ctm.c,
vml = ["<cg_vml_:group coordsize=\"1,1\" coordorigin=\"0,0\" style=\"width:1;height:1;position:absolute"];
/*if (similarity)
{
var angle = CGPointMake(1.0, 0.0);
angle = CGPointApplyAffineTransform(angle, ctm);
vml.push(";rotation:", ATAN2(angle.y - ctm.ty, angle.x - ctm.tx) * 180 / PI);
}*/
// Only create a filter if absolutely necessary. This actually
// turns out to only be the case if our transform matrix is not
// a similarity matrix, that is to say, the transform actually
// morphs the shape beyond scaling and rotation.
//if (!similarity && (ctm.a != 1.0 || ctm.b || ctm.c || ctm.d != 1.0))
{
var transformedRect = CGRectApplyAffineTransform(aRect, ctm);
vml.push( ";padding:0 ", ROUND(CGRectGetMaxX(transformedRect)), "px ", ROUND(CGRectGetMaxY(transformedRect)),
"px 0;filter:progid:DXImageTransform.Microsoft.Matrix(",
"M11='", ctm.a, "',M12='", ctm.c, "',M21='", ctm.b, "',M22='", ctm.d, "',",
"Dx='", ROUND(origin.x), "', Dy='", ROUND(origin.y), "', sizingmethod='clip');");
}
//else
// vml.push(";top:", ROUND(origin.y - 0.5), "px;left:", ROUND(origin.x - 0.5), "px;");
vml.push( "\"><cg_vml_:image src=\"", anImage._image.src,
"\" style=\"width:", CGRectGetWidth(aRect), "px;height:", CGRectGetHeight(aRect),
"px;\"/></g_vml_:group>");
string = vml.join("");
}
if (aContext.buffer != nil)
aContext.buffer += string;
else
aContext.DOMElement.insertAdjacentHTML("BeforeEnd", string);
}
function CGContextDrawPath(aContext, aMode)
{
if (!aContext || CGPathIsEmpty(aContext.path))
return;
var elements = aContext.path.elements,
i = 0,
count = aContext.path.count,
gState = aContext.gState,
fill = (aMode == kCGPathFill || aMode == kCGPathFillStroke) ? 1 : 0,
stroke = (aMode == kCGPathStroke || aMode == kCGPathFillStroke) ? 1 : 0,
opacity = gState.alpha,
vml = ["<cg_vml_:shape"];
if (gState.fillStyle.charAt(0) !== "!")
vml.push(" fillcolor=\"", gState.fillStyle, "\"");
vml.push( " filled=\"", VML_TRUTH_TABLE[fill],
"\" style=\"position:absolute;width:", W, ";height:", H,
";\" coordorigin=\"0 0\" coordsize=\"", Z * W, " ", Z * H,
"\" stroked=\"", VML_TRUTH_TABLE[stroke],
"\" strokeweight=\"", gState.lineWidth,
"\" strokecolor=\"", gState.strokeStyle,
"\" path=\"");
for (; i < count; ++i)
{
var element = elements[i],
type = element.type;
switch (type)
{
case kCGPathElementMoveToPoint:
case kCGPathElementAddLineToPoint: vml.push(VML_ELEMENT_TABLE[type], COORD(element.x), ',', COORD(element.y));
break;
case kCGPathElementAddQuadCurveToPoint: vml.push(VML_ELEMENT_TABLE[type],
COORD(element.cpx), ',', COORD(element.cpy), ',',
COORD(element.x), ',', COORD(element.y));
break;
case kCGPathElementAddCurveToPoint: vml.push(VML_ELEMENT_TABLE[type],
COORD(element.cp1x), ',', COORD(element.cp1y), ',',
COORD(element.cp2x), ',', COORD(element.cp2y), ',',
COORD(element.x), ',', COORD(element.y));
break;
case kCGPathElementCloseSubpath: vml.push(VML_ELEMENT_TABLE[type]);
break;
case kCGPathElementAddArc: var x = element.x,
y = element.y,
radius = element.radius,
clockwise = element.clockwise ? 1 : 0,
endAngle = element.endAngle,
startAngle = element.startAngle,
start = CGPointMake(x + radius * COS(startAngle), y + radius * SIN(startAngle));
// If the angle's are equal, then we won't actually draw an arc, but instead
// simply move to its start/end to get the proper fill.
// We only need this special case for anti-clockwise because start == end is
// interpreted as a full circle with anti-clockwise, but empty for clockwise.
if (startAngle == endAngle && !clockwise)
{
vml.push(VML_ELEMENT_TABLE[kCGPathElementMoveToPoint], COORD(start.x), ',', COORD(start.y));
continue;
}
var end = CGPointMake(x + radius * COS(endAngle), y + radius * SIN(endAngle));
// Only do the start correction if the angles aren't equal. If they are, then
// let the circle be empty.
// FIXME: Should this be |star.x - end.x| < 0.125 ?
if (clockwise && startAngle != endAngle && CGPointEqualToPoint(start, end))
if (start.x >= x)
{
if (start.y < y)
start.x += 0.125;
else
start.y += 0.125;
}
else
{
if (end.y <= y)
end.x += 0.125;
else
end.y += 0.125;
}
vml.push(VML_ELEMENT_TABLE[type][clockwise],
COORD(x - radius), ',', COORD(y - radius), " ",
COORD(x + radius), ',', COORD(y + radius), " ",
COORD(start.x), ',', COORD(start.y), " ",
COORD(end.x), ',', COORD(end.y));
break;
case kCGPathElementAddArcToPoint: break;
}
// TODO: Following is broken for curves due to
// move to proper paths.
// Figure out dimensions so we can do gradient fills
// properly
/*if(c) {
if (min.x == null || c.x < min.x) {
min.x = c.x;
}
if (max.x == null || c.x > max.x) {
max.x = c.x;
}
if (min.y == null || c.y < min.y) {
min.y = c.y;
}
if (max.y == null || c.y > max.y) {
max.y = c.y;
}
}*/
}
vml.push("\">");
if (gState.gradient)
vml.push(gState.gradient);
else if (fill)
{
if (gState.fillStyle.charAt(0) === "!")
vml.push("<cg_vml_:fill type=\"tile\" src=\"", gState.fillStyle.substring(1), "\" opacity=\"", opacity, "\" />");
else // should be a CSS color spec
vml.push("<cg_vml_:fill color=\"", gState.fillStyle, "\" opacity=\"", opacity, "\" />");
}
if (stroke)
vml.push( "<cg_vml_:stroke opacity=\"", opacity,
"\" joinstyle=\"", VML_LINEJOIN_TABLE[gState.lineJoin],
"\" miterlimit=\"", gState.miterLimit,
"\" endcap=\"", VML_LINECAP_TABLE[gState.lineCap],
"\" weight=\"", gState.lineWidth, "",
"px\" color=\"", gState.strokeStyle,"\" />");
var shadowColor = gState.shadowColor;
//\"", [shadowColor cssString], "\"
if (shadowColor)
{
var shadowOffset = gState.shadowOffset;
vml.push("<cg_vml_:shadow on=\"t\" offset=\"",
shadowOffset.width, "pt ", shadowOffset.height, "pt\" opacity=\"", [shadowColor alphaComponent], "\" color=black />");
}
vml.push("</cg_vml_:shape>");
if (aContext.buffer != nil)
aContext.buffer += vml.join("");
else
aContext.DOMElement.insertAdjacentHTML("BeforeEnd", vml.join(""));
}
function to_string(aColor)
{
return "rgb(" + ROUND(aColor.components[0] * 255) + ", " + ROUND(aColor.components[1] * 255) + ", " + ROUND(255 * aColor.components[2]) + ")";
}
function CGContextDrawLinearGradient(aContext, aGradient, aStartPoint, anEndPoint, options)
{
if (!aContext || !aGradient)
return;
var vml = nil;
if (aGradient.vml_gradient)
{
var stops = [[aGradient.vml_gradient stops] sortedArrayUsingSelector:@selector(comparePosition:)],
count = [stops count];
vml = ["<cg_vml_:fill type=\"gradient\" method=\"linear sigma\" "];
vml.push("angle=\"" + ([aGradient.vml_gradient angle] + 90) + "\" ");
vml.push("colors=\"");
for (var i = 0; i < count; i++)
{
vml.push(([stops[i] position] * 100).toFixed(0) + "% ");
vml.push([[[stops[i] color] colorForSlideBase:nil] cssString]);
if (i < count - 1)
vml.push(",");
}
vml.push("\" />");
}
else
{
var colors = aGradient.colors,
count = colors.length;
vml = ["<cg_vml_:fill type=\"gradient\" "];
vml.push("colors=\"");
for (var i = 0; i < count; i++)
vml.push((aGradient.locations[i] * 100).toFixed(0)+"% " + to_string(colors[i])+(i < count - 1 ? "," : ""));
vml.push("\" />");
}
aContext.gState.gradient = vml.join("");
// if (aContext.buffer != nil)
// aContext.buffer += vml.join("");
// else
// aContext.DOMElement.innerHTML = vml.join("");
}
+1 -4
View File
@@ -9,10 +9,7 @@ const utilsFile = ObjectiveJ.utils.file;
$BUILD_PATH = path.join($BUILD_DIR, $CONFIGURATION, 'AppKit');
AppKitFiles = new FileList("**/*.j").exclude('CoreGraphics/CGContextCanvas.j', 'CoreGraphics/CGContextVML.j', 'Themes/**/*', 'Tools/**/*', "Platform/DOM/CPPlatform.j", "Platform/DOM/CPPlatformString.j");
FIXME_fileDependency (path.join("Platform", "CPPlatform.j"), path.join("Platform", "DOM", "CPPlatform.j"));
FIXME_fileDependency (path.join("Platform", "CPPlatformString.j"), path.join("Platform", "DOM", "CPPlatformString.j"));
AppKitFiles = new FileList("**/*.j").exclude('CoreGraphics/CGContextCanvas.j', 'CoreGraphics/CGContextVML.j', 'Themes/**/*', 'Tools/**/*');
appKitTask = framework ("AppKit", function(appKitTask)
{
+162 -4
View File
@@ -70,11 +70,169 @@
@end
#if PLATFORM(DOM)
#include "DOM/CPPlatform.j"
#else
// --- begin AppKit/Platform/DOM/CPPlatform.j (inlined; file removed to resolve capp-build basename clash) ---
@global CPApp
@global document
if (typeof window["CPPlatformEnableHTMLDragAndDrop"] === "undefined")
CPPlatformEnableHTMLDragAndDrop = NO;
CPPlatformDidClearBodyElementNotification = @"CPPlatformDidClearBodyElementNotification";
CPPlatformWillClearBodyElementNotification = @"CPPlatformWillClearBodyElementNotification";
var screenNeedsInitialization = NO,
mainBodyElement = nil,
elementRemovalTest = new RegExp("\\bcpdontremove\\b", "g");
@implementation CPPlatform : CPBasePlatform
{
}
+ (void)initialize
{
if (self !== [CPPlatform class])
return;
screenNeedsInitialization = [CPPlatform isBrowser];
// We do this here because doing it later breaks IE.
if (typeof document !== 'undefined' && document.documentElement)
document.documentElement.style.overflow = "hidden";
if ([CPPlatform isBrowser])
{
// This differ from cocoa, where shouldTerminate is called in the method terminate of CPApp
// Cappuccino acts like this because we can not close a window openend by the user with a script (so not possible in terminate), and we can only prevent the action in the method onbeforeunload in js.
window.onbeforeunload = function()
{
if ([CPApp _sendDelegateApplicationShouldTerminate] != CPTerminateNow)
return [CPApp _sendDelegateApplicationShouldTerminateMessage];
};
var terminateApplication = function()
{
[self closeAllPlatformWindows];
[CPApp terminate:nil];
};
// "unload" is blocked by the permissions policy in current Chrome and prevents the
// back/forward cache. "pagehide" fires reliably instead. If event.persisted is true the
// page goes into the bfcache and may be restored, so the application must not terminate.
if ("onpagehide" in window)
{
window.addEventListener("pagehide", function(anEvent)
{
if (!anEvent.persisted)
terminateApplication();
}, NO);
}
else
window.onunload = terminateApplication;
}
}
+ (BOOL)isBrowser
{
if (!CPDOMAvailable)
return NO;
return typeof window.cpIsDesktop === "undefined";
}
+ (BOOL)supportsDragAndDrop
{
if (!CPDOMAvailable)
return NO;
return CPFeatureIsCompatible(CPHTMLDragAndDropFeature) && (CPPlatformEnableHTMLDragAndDrop || ![self isBrowser]);
}
+ (BOOL)supportsNativeMainMenu
{
return (typeof window["cpSetMainMenu"] === "function");
}
+ (void)terminateApplication
{
if (typeof window["cpTerminate"] === "function")
window.cpTerminate();
}
+ (void)activateIgnoringOtherApps:(BOOL)shouldIgnoreOtherApps
{
if (typeof window["cpActivateIgnoringOtherApps"] === "function")
window.cpActivateIgnoringOtherApps(!!shouldIgnoreOtherApps);
}
+ (void)deactivate
{
if (typeof window["cpDeactivate"] === "function")
window.cpDeactivate();
}
+ (void)hideOtherApplications:(id)aSender
{
if (typeof window["cpHideOtherApplications"] === "function")
window.cpHideOtherApplications();
}
+ (void)hide:(id)aSender
{
if (typeof window["cpHide"] === "function")
window.cpHide();
}
+ (DOMElement)mainBodyElement
{
if (!mainBodyElement)
mainBodyElement = document.getElementById("cappuccino-body") || document.body;
return mainBodyElement;
}
+ (void)initializeScreenIfNecessary
{
if (!screenNeedsInitialization)
return;
screenNeedsInitialization = NO;
[[CPNotificationCenter defaultCenter]
postNotificationName:CPPlatformWillClearBodyElementNotification
object:self];
var bodyElement = [self mainBodyElement];
// Get rid of any of the original contents of the page.
var children = bodyElement.childNodes,
length = children.length;
while (length--)
{
var element = children[length];
if (!element.className || element.className.match(elementRemovalTest) === null)
bodyElement.removeChild(element);
}
bodyElement.style.overflow = "hidden";
[[CPNotificationCenter defaultCenter]
postNotificationName:CPPlatformDidClearBodyElementNotification
object:self];
}
+ (void)closeAllPlatformWindows
{
var platformWindows = [CPPlatformWindow visiblePlatformWindows],
primaryPlatformWindow = [CPPlatformWindow primaryPlatformWindow],
platformWindowEnumerator = [platformWindows objectEnumerator],
platformWindow = nil;
while ((platformWindow = [platformWindowEnumerator nextObject]) != nil)
{
if (platformWindow != primaryPlatformWindow)
[platformWindow orderOut:self];
}
}
@end
#endif
+185 -6
View File
@@ -38,24 +38,203 @@
@end
#if PLATFORM(DOM)
#include "DOM/CPPlatformString.j"
#else
// --- begin AppKit/Platform/DOM/CPPlatformString.j (inlined; file removed to resolve capp-build basename clash) ---
@global document
var DOMFixedWidthSpanElement = nil,
DOMFlexibleWidthSpanElement = nil,
DOMMetricsDivElement = nil,
DOMMetricsImgElement = nil,
DefaultFont = nil;
@implementation CPPlatformString : CPBasePlatformString
{
}
+ (void)initialize
{
if (self !== [CPPlatformString class])
return;
DefaultFont = [CPFont systemFontOfSize:CPFontCurrentSystemSize];
}
+ (void)bootstrap
{
[self createDOMElements];
}
+ (void)createDOMElements
{
if (!CPDOMAvailable) return;
var style,
bodyElement = [CPPlatform mainBodyElement];
DOMFlexibleWidthSpanElement = document.createElement("span");
DOMFlexibleWidthSpanElement.className = "cpdontremove";
style = DOMFlexibleWidthSpanElement.style;
style.position = "absolute";
style.left = "-100000px";
style.zIndex = -10000;
style.visibility = "visible";
style.padding = "0px";
style.margin = "0px";
style.whiteSpace = "pre";
DOMFixedWidthSpanElement = document.createElement("span");
DOMFixedWidthSpanElement.className = "cpdontremove";
style = DOMFixedWidthSpanElement.style;
style.display = "block";
style.position = "absolute";
style.left = "-100000px";
style.zIndex = -10000;
style.visibility = "visible";
style.padding = "0px";
style.margin = "0px";
style.width = "1px";
style.wordWrap = "break-word";
try
{
style.whiteSpace = "pre";
style.whiteSpace = "-o-pre-wrap";
style.whiteSpace = "-pre-wrap";
style.whiteSpace = "-moz-pre-wrap";
style.whiteSpace = "pre-wrap";
}
catch(e)
{
//some versions of IE throw exceptions for unsupported properties.
style.whiteSpace = "pre";
}
bodyElement.appendChild(DOMFlexibleWidthSpanElement);
bodyElement.appendChild(DOMFixedWidthSpanElement);
}
+ (void)createDOMMetricsElements
{
if (!CPDOMAvailable) return;
var style,
bodyElement = [CPPlatform mainBodyElement];
DOMMetricsDivElement = document.createElement("div");
DOMMetricsDivElement.className = "cpdontremove";
style = DOMMetricsDivElement.style;
style.position = "absolute";
style.left = "-100000px";
style.zIndex = -10000;
style.width = "100000px";
style.whiteSpace = "nowrap";
style.lineHeight = "1em";
style.padding = "0px";
style.margin = "0px";
DOMMetricsDivElement.innerHTML = "x";
bodyElement.appendChild(DOMMetricsDivElement);
var imgPath = [[CPBundle bundleForClass:[CPView class]] pathForResource:@"empty.png"];
DOMMetricsImgElement = document.createElement("img");
DOMMetricsImgElement.className = "cpdontremove";
DOMMetricsImgElement.setAttribute("src", imgPath);
DOMMetricsImgElement.setAttribute("width", "1");
DOMMetricsImgElement.setAttribute("height", "1");
DOMMetricsImgElement.setAttribute("alt", "");
style = DOMMetricsImgElement.style;
style.zIndex = -10000;
style.visibility = "visible";
style.padding = "0px";
style.margin = "0px";
style.border = "none";
style.verticalAlign = "baseline";
DOMMetricsDivElement.appendChild(DOMMetricsImgElement);
}
+ (int)charPositionOfString:(CPString)aString withFont:(CPFont)aFont forPoint:(CGPoint)aPoint
{
if (!CPDOMAvailable) return 0;
if (!aString)
return 0;
var position = 0,
stringLength = aString.length,
currentString = "";
for (var i = 0; i < stringLength; i++)
{
var lastChar = aString[i];
currentString += lastChar;
var sizeOfString = [self sizeOfString:currentString withFont:aFont forWidth:nil].width,
sizeLastChar = [self sizeOfString:lastChar withFont:aFont forWidth:nil].width;
if (sizeOfString - sizeLastChar / 2 < aPoint.x)
position++;
else
break;
}
return position;
}
+ (CGSize)sizeOfString:(CPString)aString withFont:(CPFont)aFont forWidth:(float)aWidth
{
return CGSizeMakeZero();
if (!CPDOMAvailable) return CGSizeMakeZero();
if (!DOMFixedWidthSpanElement)
[self createDOMElements];
var span;
if (!aWidth)
span = DOMFlexibleWidthSpanElement;
else
{
span = DOMFixedWidthSpanElement;
span.style.width = ROUND(aWidth) + "px";
}
var effectiveFontCSSString = [(aFont || DefaultFont) cssString];
if (span.style.font !== effectiveFontCSSString)
span.style.font = effectiveFontCSSString;
if (CPFeatureIsCompatible(CPJavaScriptInnerTextFeature))
span.innerText = aString;
else if (CPFeatureIsCompatible(CPJavaScriptTextContentFeature))
span.textContent = aString;
return CGSizeMake(span.clientWidth, span.clientHeight);
}
+ (CPDictionary)metricsOfFont:(CPFont)aFont
{
return @{
if (!CPDOMAvailable)
return @{
@"ascender": 0,
@"descender": 0,
@"lineHeight": 0,
};
if (!DOMMetricsDivElement)
[self createDOMMetricsElements];
DOMMetricsDivElement.style.font = [(aFont || DefaultFont) cssString];
var lineHeight = DOMMetricsDivElement.offsetHeight,
baseline = DOMMetricsImgElement.offsetTop + DOMMetricsImgElement.offsetHeight,
descender = baseline - lineHeight;
return @{
@"ascender": baseline,
@"descender": descender,
@"lineHeight": lineHeight,
};
}
@end
#endif
+21 -29
View File
@@ -24,6 +24,7 @@
@import <Foundation/CPObject.j>
@import "CPKeyBinding.j"
@import "CPPlatform.j"
@import "CPCompatibility.j"
@class CPMenu
@class CPPlatformPasteboard
@@ -46,7 +47,6 @@ var PrimaryPlatformWindow = NULL;
BOOL _shouldUpdateContentRect;
BOOL _hasInitializeInstanceWithWindow;
#if PLATFORM(DOM)
DOMWindow _DOMWindow;
DOMElement _DOMBodyElement;
@@ -90,8 +90,6 @@ var PrimaryPlatformWindow = NULL;
float _lastTouchMoveTimestamp;
float _lastMomentumTimestamp;
BOOL _isTwoFingerScrolling;
#endif
}
+ (CPSet)visiblePlatformWindows
@@ -101,11 +99,10 @@ var PrimaryPlatformWindow = NULL;
+ (BOOL)supportsMultipleInstances
{
#if PLATFORM(DOM)
return !CPBrowserIsEngine(CPInternetExplorerBrowserEngine);
#else
if (CPDOMAvailable)
return !CPBrowserIsEngine(CPInternetExplorerBrowserEngine);
return NO;
#endif
}
+ (CPPlatformWindow)primaryPlatformWindow
@@ -126,14 +123,15 @@ var PrimaryPlatformWindow = NULL;
{
_contentRect = CGRectMakeCopy(aRect);
#if PLATFORM(DOM)
_windowLevels = [];
_windowLayers = @{};
if (CPDOMAvailable)
{
_windowLevels = [];
_windowLayers = @{};
_charCodes = {};
_charCodes = {};
_platformPasteboard = [CPPlatformPasteboard new];
#endif
_platformPasteboard = [CPPlatformPasteboard new];
}
}
return self;
@@ -198,9 +196,10 @@ var PrimaryPlatformWindow = NULL;
_contentRect = CGRectMakeCopy(aRect);
#if PLATFORM(DOM)
[self updateNativeContentRect];
#endif
if (CPDOMAvailable)
{
[self updateNativeContentRect];
}
}
- (void)updateFromNativeContentRect
@@ -224,11 +223,10 @@ var PrimaryPlatformWindow = NULL;
- (BOOL)isVisible
{
#if PLATFORM(DOM)
return _DOMWindow !== NULL && _DOMWindow !== undefined;
#else
if (CPDOMAvailable)
return _DOMWindow !== NULL && _DOMWindow !== undefined;
return NO;
#endif
}
- (void)deminiaturize:(id)sender
@@ -241,7 +239,8 @@ var PrimaryPlatformWindow = NULL;
- (void)moveWindow:(CPWindow)aWindow fromLevel:(int)fromLevel toLevel:(int)toLevel
{
#if PLATFORM(DOM)
if (!CPDOMAvailable) return;
if (!aWindow._isVisible)
return;
@@ -250,7 +249,6 @@ var PrimaryPlatformWindow = NULL;
[fromLayer removeWindow:aWindow];
[toLayer insertWindow:aWindow atIndex:CPNotFound];
#endif
}
- (void)setLevel:(CPInteger)aLevel
@@ -277,14 +275,10 @@ var PrimaryPlatformWindow = NULL;
{
_title = aTitle;
#if PLATFORM(DOM)
if (_DOMWindow &&
_DOMWindow.document &&
([aWindow isFullPlatformWindow]))
if (CPDOMAvailable && _DOMWindow && _DOMWindow.document && ([aWindow isFullPlatformWindow]))
{
_DOMWindow.document.title = _title;
}
#endif
}
- (CPString)title
@@ -310,6 +304,4 @@ var PrimaryPlatformWindow = NULL;
@end
#if PLATFORM(BROWSER)
//@import "CPPlatformWindow+DOM.j"
#endif
-68
View File
@@ -1,68 +0,0 @@
/*
* CPDOMDisplayServer.h
* AppKit
*
* Created by Francisco Tolmasky.
* Copyright 2008, 280 North, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#define CPDOMDisplayServerSetStyleLeftTop(aDOMElement, aTransform, aLeft, aTop) \
if (aTransform) var ____p = CGPointApplyAffineTransform(CGPointMake(aLeft, aTop), aTransform); \
else var ____p = CGPointMake(aLeft, aTop); \
aDOMElement.style.left = ROUND(____p.x) + "px";\
aDOMElement.style.top = ROUND(____p.y) + "px";
#define CPDOMDisplayServerSetStyleRightTop(aDOMElement, aTransform, aRight, aTop) \
if (aTransform) var ____p = CGPointApplyAffineTransform(CGPointMake(aRight, aTop), aTransform); \
else var ____p = CGPointMake(aRight, aTop); \
aDOMElement.style.right = ROUND(____p.x) + "px";\
aDOMElement.style.top = ROUND(____p.y) + "px";
#define CPDOMDisplayServerSetStyleLeftBottom(aDOMElement, aTransform, aLeft, aBottom) \
if (aTransform) var ____p = CGPointApplyAffineTransform(CGPointMake(aLeft, aBottom), aTransform); \
else var ____p = CGPointMake(aLeft, aBottom); \
aDOMElement.style.left = ROUND(____p.x) + "px";\
aDOMElement.style.bottom = ROUND(____p.y) + "px";
#define CPDOMDisplayServerSetStyleRightBottom(aDOMElement, aTransform, aRight, aBottom) \
if (aTransform) var ____p = CGPointApplyAffineTransform(CGPointMake(aRight, aBottom), aTransform); \
else var ____p = CGPointMake(aRight, aBottom); \
aDOMElement.style.right = ROUND(____p.x) + "px";\
aDOMElement.style.bottom = ROUND(____p.y) + "px";
#define CPDOMDisplayServerSetStyleSize(aDOMElement, aWidth, aHeight) \
aDOMElement.style.width = MAX(0.0, ROUND(aWidth)) + "px";\
aDOMElement.style.height = MAX(0.0, ROUND(aHeight)) + "px";
#define CPDOMDisplayServerSetSize(aDOMElement, aWidth, aHeight) \
aDOMElement.width = MAX(0.0, ROUND(aWidth));\
aDOMElement.height = MAX(0.0, ROUND(aHeight));
#define CPDOMDisplayServerSetStyleBackgroundSize(aDOMElement, aWidth, aHeight)\
aDOMElement.style.backgroundSize = aWidth + ' ' + aHeight;
#define CPDOMDisplayServerAppendChild(aParentElement, aChildElement) \
aParentElement.appendChild(aChildElement);
#define CPDOMDisplayServerInsertBefore(aParentElement, aChildElement, aBeforeElement) \
aParentElement.insertBefore(aChildElement, aBeforeElement);
#define CPDOMDisplayServerRemoveChild(aParentElement, aChildElement) \
aParentElement.removeChild(aChildElement);
#define PREPARE_DOM_OPTIMIZATION()
#define EXECUTE_DOM_INSTRUCTIONS()
+96
View File
@@ -0,0 +1,96 @@
/*
* CPDOMDisplayServer.j
* AppKit
*
* Created by Francisco Tolmasky.
* Copyright 2008, 280 North, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/* Formerly a force-included header of function-like macros; promoted to a
real source file for the preprocessor-free build. */
function CPDOMDisplayServerSetStyleLeftTop(aDOMElement, aTransform, aLeft, aTop)
{
if (aTransform) var ____p = CGPointApplyAffineTransform(CGPointMake(aLeft, aTop), aTransform);
else var ____p = CGPointMake(aLeft, aTop);
aDOMElement.style.left = ROUND(____p.x) + "px";
aDOMElement.style.top = ROUND(____p.y) + "px";
}
function CPDOMDisplayServerSetStyleRightTop(aDOMElement, aTransform, aRight, aTop)
{
if (aTransform) var ____p = CGPointApplyAffineTransform(CGPointMake(aRight, aTop), aTransform);
else var ____p = CGPointMake(aRight, aTop);
aDOMElement.style.right = ROUND(____p.x) + "px";
aDOMElement.style.top = ROUND(____p.y) + "px";
}
function CPDOMDisplayServerSetStyleLeftBottom(aDOMElement, aTransform, aLeft, aBottom)
{
if (aTransform) var ____p = CGPointApplyAffineTransform(CGPointMake(aLeft, aBottom), aTransform);
else var ____p = CGPointMake(aLeft, aBottom);
aDOMElement.style.left = ROUND(____p.x) + "px";
aDOMElement.style.bottom = ROUND(____p.y) + "px";
}
function CPDOMDisplayServerSetStyleRightBottom(aDOMElement, aTransform, aRight, aBottom)
{
if (aTransform) var ____p = CGPointApplyAffineTransform(CGPointMake(aRight, aBottom), aTransform);
else var ____p = CGPointMake(aRight, aBottom);
aDOMElement.style.right = ROUND(____p.x) + "px";
aDOMElement.style.bottom = ROUND(____p.y) + "px";
}
function CPDOMDisplayServerSetStyleSize(aDOMElement, aWidth, aHeight)
{
aDOMElement.style.width = MAX(0.0, ROUND(aWidth)) + "px";
aDOMElement.style.height = MAX(0.0, ROUND(aHeight)) + "px";
}
function CPDOMDisplayServerSetSize(aDOMElement, aWidth, aHeight)
{
aDOMElement.width = MAX(0.0, ROUND(aWidth));
aDOMElement.height = MAX(0.0, ROUND(aHeight));
}
function CPDOMDisplayServerSetStyleBackgroundSize(aDOMElement, aWidth, aHeight)
{
aDOMElement.style.backgroundSize = aWidth + ' ' + aHeight;
}
function CPDOMDisplayServerAppendChild(aParentElement, aChildElement)
{
aParentElement.appendChild(aChildElement);
}
function CPDOMDisplayServerInsertBefore(aParentElement, aChildElement, aBeforeElement)
{
aParentElement.insertBefore(aChildElement, aBeforeElement);
}
function CPDOMDisplayServerRemoveChild(aParentElement, aChildElement)
{
aParentElement.removeChild(aChildElement);
}
function PREPARE_DOM_OPTIMIZATION()
{
}
function EXECUTE_DOM_INSTRUCTIONS()
{
}
-180
View File
@@ -1,180 +0,0 @@
/*
* CPPlatform+DOM.j
* AppKit
*
* Created by Francisco Tolmasky.
* Copyright 2010, 280 North, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
@global CPApp
if (typeof window["CPPlatformEnableHTMLDragAndDrop"] === "undefined")
CPPlatformEnableHTMLDragAndDrop = NO;
CPPlatformDidClearBodyElementNotification = @"CPPlatformDidClearBodyElementNotification";
CPPlatformWillClearBodyElementNotification = @"CPPlatformWillClearBodyElementNotification";
var screenNeedsInitialization = NO,
mainBodyElement = nil,
elementRemovalTest = new RegExp("\\bcpdontremove\\b", "g");
@implementation CPPlatform : CPBasePlatform
{
}
+ (void)initialize
{
if (self !== [CPPlatform class])
return;
screenNeedsInitialization = [CPPlatform isBrowser];
// We do this here because doing it later breaks IE.
if (typeof document !== 'undefined' && document.documentElement)
document.documentElement.style.overflow = "hidden";
if ([CPPlatform isBrowser])
{
// This differ from cocoa, where shouldTerminate is called in the method terminate of CPApp
// Cappuccino acts like this because we can not close a window openend by the user with a script (so not possible in terminate), and we can only prevent the action in the method onbeforeunload in js.
window.onbeforeunload = function()
{
if ([CPApp _sendDelegateApplicationShouldTerminate] != CPTerminateNow)
return [CPApp _sendDelegateApplicationShouldTerminateMessage];
};
var terminateApplication = function()
{
[self closeAllPlatformWindows];
[CPApp terminate:nil];
};
// "unload" is blocked by the permissions policy in current Chrome and prevents the
// back/forward cache. "pagehide" fires reliably instead. If event.persisted is true the
// page goes into the bfcache and may be restored, so the application must not terminate.
if ("onpagehide" in window)
{
window.addEventListener("pagehide", function(anEvent)
{
if (!anEvent.persisted)
terminateApplication();
}, NO);
}
else
window.onunload = terminateApplication;
}
}
+ (BOOL)isBrowser
{
return typeof window.cpIsDesktop === "undefined";
}
+ (BOOL)supportsDragAndDrop
{
return CPFeatureIsCompatible(CPHTMLDragAndDropFeature) && (CPPlatformEnableHTMLDragAndDrop || ![self isBrowser]);
}
+ (BOOL)supportsNativeMainMenu
{
return (typeof window["cpSetMainMenu"] === "function");
}
+ (void)terminateApplication
{
if (typeof window["cpTerminate"] === "function")
window.cpTerminate();
}
+ (void)activateIgnoringOtherApps:(BOOL)shouldIgnoreOtherApps
{
if (typeof window["cpActivateIgnoringOtherApps"] === "function")
window.cpActivateIgnoringOtherApps(!!shouldIgnoreOtherApps);
}
+ (void)deactivate
{
if (typeof window["cpDeactivate"] === "function")
window.cpDeactivate();
}
+ (void)hideOtherApplications:(id)aSender
{
if (typeof window["cpHideOtherApplications"] === "function")
window.cpHideOtherApplications();
}
+ (void)hide:(id)aSender
{
if (typeof window["cpHide"] === "function")
window.cpHide();
}
+ (DOMElement)mainBodyElement
{
if (!mainBodyElement)
mainBodyElement = document.getElementById("cappuccino-body") || document.body;
return mainBodyElement;
}
+ (void)initializeScreenIfNecessary
{
if (!screenNeedsInitialization)
return;
screenNeedsInitialization = NO;
[[CPNotificationCenter defaultCenter]
postNotificationName:CPPlatformWillClearBodyElementNotification
object:self];
var bodyElement = [self mainBodyElement];
// Get rid of any of the original contents of the page.
var children = bodyElement.childNodes,
length = children.length;
while (length--)
{
var element = children[length];
if (!element.className || element.className.match(elementRemovalTest) === null)
bodyElement.removeChild(element);
}
bodyElement.style.overflow = "hidden";
[[CPNotificationCenter defaultCenter]
postNotificationName:CPPlatformDidClearBodyElementNotification
object:self];
}
+ (void)closeAllPlatformWindows
{
var platformWindows = [CPPlatformWindow visiblePlatformWindows],
primaryPlatformWindow = [CPPlatformWindow primaryPlatformWindow],
platformWindowEnumerator = [platformWindows objectEnumerator],
platformWindow = nil;
while ((platformWindow = [platformWindowEnumerator nextObject]) != nil)
{
if (platformWindow != primaryPlatformWindow)
[platformWindow orderOut:self];
}
}
@end
+4 -10
View File
@@ -35,11 +35,6 @@
// From CPPlatformWindow+DOM.j
@global _CPDOMEventStop
#if PLATFORM(DOM)
#define SUPPRESS_CAPPUCCINO_CUT_FOR_EVENT(anEvent) anEvent._suppressCappuccinoCut = YES
#define SUPPRESS_CAPPUCCINO_PASTE_FOR_EVENT(anEvent) anEvent._suppressCappuccinoPaste = YES
var hasEditableTarget = function(aDOMEvent)
{
var target = aDOMEvent.target || aDOMEvent.srcElement;
@@ -278,9 +273,9 @@ var hasEditableTarget = function(aDOMEvent)
if (!currentEventShouldBeSuppressed)
{
if (characters === "v")
SUPPRESS_CAPPUCCINO_PASTE_FOR_EVENT(anEvent);
anEvent._suppressCappuccinoPaste = YES;
else if (characters === "x")
SUPPRESS_CAPPUCCINO_CUT_FOR_EVENT(anEvent);
anEvent._suppressCappuccinoCut = YES;
}
}
@@ -479,7 +474,7 @@ Return true if the event may be a copy and paste event, but the target is not an
var anEvent = [self _fakeClipboardEvent:aDOMEvent type:"v"],
platformWindow = [[anEvent window] platformWindow];
SUPPRESS_CAPPUCCINO_PASTE_FOR_EVENT(anEvent);
anEvent._suppressCappuccinoPaste = YES;
// By default we'll stop the native handling of the event since we're handling it ourselves. However, we need to
// stop it before we send the event so that the event can overrule our choice. CPTextField for instance wants the
@@ -505,7 +500,7 @@ Return true if the event may be a copy and paste event, but the target is not an
var anEvent = [self _fakeClipboardEvent:aDOMEvent type:(aDOMEvent.type.indexOf("cut") != CPNotFound ? "x" : "c")],
platformWindow = [[anEvent window] platformWindow];
SUPPRESS_CAPPUCCINO_CUT_FOR_EVENT(anEvent);
anEvent._suppressCappuccinoCut = YES;
[platformWindow _propagateCurrentDOMEvent:NO];
@@ -539,4 +534,3 @@ Return true if the event may be a copy and paste event, but the target is not an
@end
#endif
-204
View File
@@ -1,204 +0,0 @@
/*
* CPPlatformString.j
* AppKit
*
* Created by Francisco Tolmasky.
* Copyright 2010, 280 North, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
var DOMFixedWidthSpanElement = nil,
DOMFlexibleWidthSpanElement = nil,
DOMMetricsDivElement = nil,
DOMMetricsImgElement = nil,
DefaultFont = nil;
@implementation CPPlatformString : CPBasePlatformString
{
}
+ (void)initialize
{
if (self !== [CPPlatformString class])
return;
DefaultFont = [CPFont systemFontOfSize:CPFontCurrentSystemSize];
}
+ (void)bootstrap
{
[self createDOMElements];
}
+ (void)createDOMElements
{
var style,
bodyElement = [CPPlatform mainBodyElement];
DOMFlexibleWidthSpanElement = document.createElement("span");
DOMFlexibleWidthSpanElement.className = "cpdontremove";
style = DOMFlexibleWidthSpanElement.style;
style.position = "absolute";
style.left = "-100000px";
style.zIndex = -10000;
style.visibility = "visible";
style.padding = "0px";
style.margin = "0px";
style.whiteSpace = "pre";
DOMFixedWidthSpanElement = document.createElement("span");
DOMFixedWidthSpanElement.className = "cpdontremove";
style = DOMFixedWidthSpanElement.style;
style.display = "block";
style.position = "absolute";
style.left = "-100000px";
style.zIndex = -10000;
style.visibility = "visible";
style.padding = "0px";
style.margin = "0px";
style.width = "1px";
style.wordWrap = "break-word";
try
{
style.whiteSpace = "pre";
style.whiteSpace = "-o-pre-wrap";
style.whiteSpace = "-pre-wrap";
style.whiteSpace = "-moz-pre-wrap";
style.whiteSpace = "pre-wrap";
}
catch(e)
{
//some versions of IE throw exceptions for unsupported properties.
style.whiteSpace = "pre";
}
bodyElement.appendChild(DOMFlexibleWidthSpanElement);
bodyElement.appendChild(DOMFixedWidthSpanElement);
}
+ (void)createDOMMetricsElements
{
var style,
bodyElement = [CPPlatform mainBodyElement];
DOMMetricsDivElement = document.createElement("div");
DOMMetricsDivElement.className = "cpdontremove";
style = DOMMetricsDivElement.style;
style.position = "absolute";
style.left = "-100000px";
style.zIndex = -10000;
style.width = "100000px";
style.whiteSpace = "nowrap";
style.lineHeight = "1em";
style.padding = "0px";
style.margin = "0px";
DOMMetricsDivElement.innerHTML = "x";
bodyElement.appendChild(DOMMetricsDivElement);
var imgPath = [[CPBundle bundleForClass:[CPView class]] pathForResource:@"empty.png"];
DOMMetricsImgElement = document.createElement("img");
DOMMetricsImgElement.className = "cpdontremove";
DOMMetricsImgElement.setAttribute("src", imgPath);
DOMMetricsImgElement.setAttribute("width", "1");
DOMMetricsImgElement.setAttribute("height", "1");
DOMMetricsImgElement.setAttribute("alt", "");
style = DOMMetricsImgElement.style;
style.zIndex = -10000;
style.visibility = "visible";
style.padding = "0px";
style.margin = "0px";
style.border = "none";
style.verticalAlign = "baseline";
DOMMetricsDivElement.appendChild(DOMMetricsImgElement);
}
+ (int)charPositionOfString:(CPString)aString withFont:(CPFont)aFont forPoint:(CGPoint)aPoint
{
if (!aString)
return 0;
var position = 0,
stringLength = aString.length,
currentString = "";
for (var i = 0; i < stringLength; i++)
{
var lastChar = aString[i];
currentString += lastChar;
var sizeOfString = [self sizeOfString:currentString withFont:aFont forWidth:nil].width,
sizeLastChar = [self sizeOfString:lastChar withFont:aFont forWidth:nil].width;
if (sizeOfString - sizeLastChar / 2 < aPoint.x)
position++;
else
break;
}
return position;
}
+ (CGSize)sizeOfString:(CPString)aString withFont:(CPFont)aFont forWidth:(float)aWidth
{
if (!DOMFixedWidthSpanElement)
[self createDOMElements];
var span;
if (!aWidth)
span = DOMFlexibleWidthSpanElement;
else
{
span = DOMFixedWidthSpanElement;
span.style.width = ROUND(aWidth) + "px";
}
var effectiveFontCSSString = [(aFont || DefaultFont) cssString];
if (span.style.font !== effectiveFontCSSString)
span.style.font = effectiveFontCSSString;
if (CPFeatureIsCompatible(CPJavaScriptInnerTextFeature))
span.innerText = aString;
else if (CPFeatureIsCompatible(CPJavaScriptTextContentFeature))
span.textContent = aString;
return CGSizeMake(span.clientWidth, span.clientHeight);
}
+ (CPDictionary)metricsOfFont:(CPFont)aFont
{
if (!DOMMetricsDivElement)
[self createDOMMetricsElements];
DOMMetricsDivElement.style.font = [(aFont || DefaultFont) cssString];
var lineHeight = DOMMetricsDivElement.offsetHeight,
baseline = DOMMetricsImgElement.offsetTop + DOMMetricsImgElement.offsetHeight,
descender = baseline - lineHeight;
return @{
@"ascender": baseline,
@"descender": descender,
@"lineHeight": lineHeight,
};
}
@end
+18 -11
View File
@@ -246,9 +246,7 @@ _CPPlatformWindowWillCloseNotification = @"_CPPlatformWindowWillCloseNotificatio
// When scrolling with an old-style scroll wheel with discete steps ('clicks'), the scroll amount can indicate how many "lines" to
// scroll.
#define SCROLLWHEEL_LINE_PIXELS 6.0
#if PLATFORM(DOM)
var SCROLLWHEEL_LINE_PIXELS = 6.0;
@implementation CPPlatformWindow (DOM)
@@ -258,16 +256,26 @@ _CPPlatformWindowWillCloseNotification = @"_CPPlatformWindowWillCloseNotificatio
if (self)
{
_DOMWindow = window;
_contentRect = CGRectMakeZero();
if (CPDOMAvailable)
{
_DOMWindow = window;
_contentRect = CGRectMakeZero();
_windowLevels = [];
_windowLayers = @{};
_windowLevels = [];
_windowLayers = @{};
_platformPasteboard = [CPPlatformPasteboard new];
_platformPasteboard = [CPPlatformPasteboard new];
[self registerDOMWindow];
[self updateFromNativeContentRect];
[self registerDOMWindow];
[self updateFromNativeContentRect];
}
else
{
_contentRect = CGRectMakeZero();
_windowLevels = [];
_windowLayers = @{};
}
_charCodes = {};
@@ -1928,7 +1936,6 @@ _CPPlatformWindowWillCloseNotification = @"_CPPlatformWindowWillCloseNotificatio
}
@end
#endif
var CPEventClass = [CPEvent class];
-23
View File
@@ -1,23 +0,0 @@
/*
* Platform.h
* AppKit
*
* Created by Francisco Tolmasky.
* Copyright 2008, 280 North, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#define PLATFORM(FEATURE) (defined( PLATFORM_##FEATURE ) && PLATFORM_##FEATURE)
+1
View File
@@ -21,6 +21,7 @@
*/
@import <Foundation/CPRunLoop.j>
@import "CPDOMDisplayServer.j"
PREPARE_DOM_OPTIMIZATION();
+399 -400
View File
@@ -28,6 +28,7 @@
@import "CPView.j"
@import "CPControl.j"
@import "CPPlatform.j"
@import "CPCompatibility.j"
var _CPimageAndTextViewFrameSizeChangedFlag = 1 << 0,
@@ -71,11 +72,9 @@ var _CPimageAndTextViewFrameSizeChangedFlag = 1 << 0,
unsigned _flags;
#if PLATFORM(DOM)
DOMElement _DOMImageElement;
DOMElement _DOMTextElement;
DOMElement _DOMTextShadowElement;
#endif
}
@global document
@@ -132,7 +131,8 @@ var _CPimageAndTextViewFrameSizeChangedFlag = 1 << 0,
_alignment = anAlignment;
#if PLATFORM(DOM)
if (!CPDOMAvailable) return;
switch (_alignment)
{
case CPLeftTextAlignment:
@@ -155,7 +155,6 @@ var _CPimageAndTextViewFrameSizeChangedFlag = 1 << 0,
_DOMElement.style.textAlign = "";
break;
}
#endif
}
- (CPTextAlignment)alignment
@@ -250,9 +249,10 @@ var _CPimageAndTextViewFrameSizeChangedFlag = 1 << 0,
_textColor = aTextColor;
#if PLATFORM(DOM)
_DOMElement.style.color = [_textColor cssString];
#endif
if (CPDOMAvailable)
{
_DOMElement.style.color = [_textColor cssString];
}
}
- (CPColor)textColor
@@ -330,8 +330,7 @@ var _CPimageAndTextViewFrameSizeChangedFlag = 1 << 0,
var textFrame = CGRectMakeZero();
#if PLATFORM(DOM)
if (_DOMTextElement)
if (CPDOMAvailable && _DOMTextElement)
{
var textStyle = _DOMTextElement.style;
@@ -343,7 +342,6 @@ var _CPimageAndTextViewFrameSizeChangedFlag = 1 << 0,
textFrame.size.width += _textShadowOffset.width;
textFrame.size.height += _textShadowOffset.height;
}
#endif
return textFrame;
}
@@ -422,427 +420,428 @@ var _CPimageAndTextViewFrameSizeChangedFlag = 1 << 0,
- (void)layoutSubviews
{
#if PLATFORM(DOM)
var needsDOMTextElement = _imagePosition !== CPImageOnly && ([_text length] > 0),
hasDOMTextElement = !!_DOMTextElement;
// Create or destroy the DOM Text Element as necessary
if (needsDOMTextElement !== hasDOMTextElement)
if (CPDOMAvailable)
{
if (hasDOMTextElement)
var needsDOMTextElement = _imagePosition !== CPImageOnly && ([_text length] > 0),
hasDOMTextElement = !!_DOMTextElement;
// Create or destroy the DOM Text Element as necessary
if (needsDOMTextElement !== hasDOMTextElement)
{
_DOMElement.removeChild(_DOMTextElement);
_DOMTextElement = nil;
hasDOMTextElement = NO;
}
else
{
_DOMTextElement = document.createElement("div");
var textStyle = _DOMTextElement.style;
textStyle.position = "absolute";
textStyle.whiteSpace = "pre";
textStyle.zIndex = 200;
textStyle.overflow = "hidden";
_DOMElement.appendChild(_DOMTextElement);
hasDOMTextElement = YES;
// We have to set all these values now.
_flags |= _CPImageAndTextViewTextChangedFlag | _CPImageAndTextViewFontChangedFlag | _CPImageAndTextViewLineBreakModeChangedFlag | _CPImageAndTextViewTextUnderlineChangedFlag;
}
}
var textStyle = hasDOMTextElement ? _DOMTextElement.style : nil;
// If theme is CSS based and if shadow color is a CSS dictionary, we don't need a separate DOM element,
// we simply put shadow styling on the regular text element
if (hasDOMTextElement && [[self actualTheme] isCSSBased] && [_textShadowColor cssDictionary])
{
[[_textShadowColor cssDictionary] enumerateKeysAndObjectsUsingBlock:function(aKey, anObject, stop)
{
_DOMTextElement.style[aKey] = anObject;
}];
}
else
{
// Create or destroy the DOM Text Shadow element as necessary.
// If _textShadowColor's alphaComponent is 0, don't bother drawing anything (issue #1412).
// This improves performance as we get rid of an invisible element, and makes IE <9.0 capable
// of correctly 'rendering' shadows with [CPColor clearColor].
var needsDOMTextShadowElement = hasDOMTextElement && [_textShadowColor alphaComponent] > 0.0,
hasDOMTextShadowElement = !!_DOMTextShadowElement;
if (needsDOMTextShadowElement !== hasDOMTextShadowElement)
{
if (hasDOMTextShadowElement)
if (hasDOMTextElement)
{
_DOMElement.removeChild(_DOMTextShadowElement);
_DOMTextShadowElement = nil;
hasDOMTextShadowElement = NO;
_DOMElement.removeChild(_DOMTextElement);
_DOMTextElement = nil;
hasDOMTextElement = NO;
}
else
{
_DOMTextShadowElement = document.createElement("div");
_DOMTextElement = document.createElement("div");
var shadowStyle = _DOMTextShadowElement.style,
font = (_font || [CPFont systemFontOfSize:CPFontCurrentSystemSize]);
var textStyle = _DOMTextElement.style;
textStyle.position = "absolute";
textStyle.whiteSpace = "pre";
textStyle.zIndex = 200;
textStyle.overflow = "hidden";
shadowStyle.font = [font cssString];
shadowStyle.position = "absolute";
shadowStyle.whiteSpace = textStyle.whiteSpace;
shadowStyle.wordWrap = textStyle.wordWrap;
shadowStyle.color = [_textShadowColor cssString];
shadowStyle.lineHeight = [font defaultLineHeightForFont] + "px";
_DOMElement.appendChild(_DOMTextElement);
hasDOMTextElement = YES;
shadowStyle.zIndex = 150;
shadowStyle.textOverflow = textStyle.textOverflow;
if (document.attachEvent)
{
shadowStyle.overflow = textStyle.overflow;
}
else
{
shadowStyle.overflowX = textStyle.overflowX;
shadowStyle.overflowY = textStyle.overflowY;
}
_DOMElement.appendChild(_DOMTextShadowElement);
hasDOMTextShadowElement = YES;
_flags |= _CPImageAndTextViewTextChangedFlag; //sigh...
}
}
}
var shadowStyle = hasDOMTextShadowElement ? _DOMTextShadowElement.style : nil;
if (hasDOMTextElement)
{
// Update the text contents if necessary.
if (_flags & _CPImageAndTextViewTextChangedFlag)
if (CPFeatureIsCompatible(CPJavaScriptInnerTextFeature))
{
_DOMTextElement.innerText = _text;
if (_DOMTextShadowElement)
_DOMTextShadowElement.innerText = _text;
}
else if (CPFeatureIsCompatible(CPJavaScriptTextContentFeature))
{
_DOMTextElement.textContent = _text;
if (_DOMTextShadowElement)
_DOMTextShadowElement.textContent = _text;
}
if (_flags & _CPImageAndTextViewFontChangedFlag)
{
var font = (_font || [CPFont systemFontOfSize:CPFontCurrentSystemSize]),
fontStyle = [font cssString];
textStyle.font = fontStyle;
textStyle.lineHeight = [font defaultLineHeightForFont] + "px";
if (shadowStyle)
{
shadowStyle.font = fontStyle;
shadowStyle.lineHeight = [font defaultLineHeightForFont] + "px";
// We have to set all these values now.
_flags |= _CPImageAndTextViewTextChangedFlag | _CPImageAndTextViewFontChangedFlag | _CPImageAndTextViewLineBreakModeChangedFlag | _CPImageAndTextViewTextUnderlineChangedFlag;
}
}
if (_flags & _CPImageAndTextViewTextUnderlineChangedFlag)
var textStyle = hasDOMTextElement ? _DOMTextElement.style : nil;
// If theme is CSS based and if shadow color is a CSS dictionary, we don't need a separate DOM element,
// we simply put shadow styling on the regular text element
if (hasDOMTextElement && [[self actualTheme] isCSSBased] && [_textShadowColor cssDictionary])
{
textStyle.textDecoration = _textUnderline ? "underline" : "";
}
// Update the line break mode if necessary.
if (_flags & _CPImageAndTextViewLineBreakModeChangedFlag)
{
switch (_lineBreakMode)
{
case CPLineBreakByClipping:
textStyle.overflow = "hidden";
textStyle.textOverflow = "clip";
textStyle.whiteSpace = "pre";
textStyle.wordWrap = "normal";
break;
case CPLineBreakByTruncatingHead:
case CPLineBreakByTruncatingMiddle: // Don't have support for these (yet?), so just degrade to truncating tail.
case CPLineBreakByTruncatingTail:
textStyle.textOverflow = "ellipsis";
textStyle.whiteSpace = "pre";
textStyle.overflow = "hidden";
textStyle.wordWrap = "normal";
break;
case CPLineBreakByCharWrapping:
case CPLineBreakByWordWrapping:
textStyle.wordWrap = "break-word";
try
{
textStyle.whiteSpace = "pre";
textStyle.whiteSpace = "-o-pre-wrap";
textStyle.whiteSpace = "-pre-wrap";
textStyle.whiteSpace = "-moz-pre-wrap";
textStyle.whiteSpace = "pre-wrap";
}
catch (e)
{
//internet explorer doesn't like these properties
textStyle.whiteSpace = "pre";
}
textStyle.overflow = "hidden";
textStyle.textOverflow = "clip";
break;
}
if (shadowStyle)
{
if (document.attachEvent)
{
shadowStyle.overflow = textStyle.overflow;
}
else
{
shadowStyle.overflowX = textStyle.overflowX;
shadowStyle.overflowY = textStyle.overflowY;
}
shadowStyle.wordWrap = textStyle.wordWrap;
shadowStyle.whiteSpace = textStyle.whiteSpace;
shadowStyle.textOverflow = textStyle.textOverflow;
}
}
}
var needsDOMImageElement = _image != nil && _imagePosition !== CPNoImage,
hasDOMImageElement = !!_DOMImageElement,
// For CSS theming
isCSSBasedImage = [_image isCSSBased],
isIMGImageElement = hasDOMImageElement && (_DOMImageElement.nodeName == "IMG");
// First, check if we need to destroy a current DOM image element. This is the case if :
// - we have one but don't need it anymore
// - we have one but not the right one (that is a DIV but needing an IMG, and vice versa)
if (hasDOMImageElement)
{
if (!needsDOMImageElement || (isIMGImageElement && isCSSBasedImage) || (!isIMGImageElement && !isCSSBasedImage))
{
// OK, destroy it
_DOMElement.removeChild(_DOMImageElement);
_DOMImageElement = nil;
hasDOMImageElement = NO;
// CSS styling cleaning
_cssStylePreviousState = @[];
_cssStyleNode = nil;
}
}
// Now, if we need a DOM image element and if we don't have one, create a new one
if (needsDOMImageElement && !hasDOMImageElement)
{
_DOMImageElement = document.createElement(isCSSBasedImage ? "div" : "img");
if ([CPPlatform supportsDragAndDrop])
{
_DOMImageElement.setAttribute("draggable", "true");
_DOMImageElement.style["-khtml-user-drag"] = "element";
}
var imageStyle = _DOMImageElement.style;
imageStyle.top = "0px";
imageStyle.left = "0px";
imageStyle.position = "absolute";
imageStyle.zIndex = 100;
_DOMElement.appendChild(_DOMImageElement);
hasDOMImageElement = YES;
}
var size = [self bounds].size,
textRect = CGRectMake(0.0, 0.0, size.width, size.height);
if (hasDOMImageElement)
{
if (!imageStyle)
var imageStyle = _DOMImageElement.style;
var centerX = size.width / 2.0,
centerY = size.height / 2.0,
imageSize = [_image size],
imageWidth = imageSize.width,
imageHeight = imageSize.height;
if (_imageScaling === CPImageScaleAxesIndependently)
{
imageWidth = size.width;
imageHeight = size.height;
}
else if (_imageScaling === CPImageScaleProportionallyDown)
{
var scale = MIN(MIN(size.width, imageWidth) / imageWidth, MIN(size.height, imageHeight) / imageHeight);
imageWidth *= scale;
imageHeight *= scale;
}
else if (_imageScaling === CPImageScaleProportionallyUpOrDown)
{
var scale = MIN(size.width / imageWidth, size.height / imageHeight);
imageWidth *= scale;
imageHeight *= scale;
}
if (CPFeatureIsCompatible(CPOpacityRequiresFilterFeature))
imageStyle.filter = @"alpha(opacity=" + _shouldDimImage ? 50 : 100 + ")";
else
imageStyle.opacity = _shouldDimImage ? 0.5 : 1.0;
_DOMImageElement.width = imageWidth;
_DOMImageElement.height = imageHeight;
imageStyle.width = MAX(imageWidth, 0) + "px";
imageStyle.height = MAX(imageHeight, 0) + "px";
if (_imagePosition === CPImageBelow)
{
imageStyle.left = FLOOR(centerX - imageWidth / 2.0) + "px";
imageStyle.top = FLOOR(size.height - imageHeight) + "px";
textRect.size.height = size.height - imageHeight - _imageOffset;
}
else if (_imagePosition === CPImageAbove)
{
imageStyle.left = FLOOR(centerX - imageWidth / 2.0) + "px";
imageStyle.top = 0 + "px";
textRect.origin.y += imageHeight + _imageOffset;
textRect.size.height = size.height - imageHeight - _imageOffset;
}
else if (_imagePosition === CPImageLeft)
{
imageStyle.top = _imageVerticalOffset + FLOOR(centerY - imageHeight / 2.0) + "px";
imageStyle.left = "0px";
textRect.origin.x = imageWidth + _imageOffset;
textRect.size.width -= imageWidth + _imageOffset;
}
else if (_imagePosition === CPImageRight)
{
imageStyle.top = _imageVerticalOffset + FLOOR(centerY - imageHeight / 2.0) + "px";
imageStyle.left = FLOOR(size.width - imageWidth) + "px";
textRect.size.width -= imageWidth + _imageOffset;
}
else if (_imagePosition === CPImageOnly || _imagePosition == CPImageOverlaps)
{
imageStyle.top = _imageVerticalOffset + FLOOR(centerY - imageHeight / 2.0) + "px";
imageStyle.left = FLOOR(centerX - imageWidth / 2.0) + "px";
}
if (_flags & _CPImageAndTextViewImageChangedFlag)
{
if (isCSSBasedImage)
{
// For material icons images & co.
if ([_image _shouldBeResized])
[_image _setDisplaySize:CGSizeMake(imageWidth, imageHeight)];
_cssStyleNode = [_image applyCSSImageForView:self
onDOMElement:_DOMImageElement
styleNode:_cssStyleNode
previousState:@ref(_cssStylePreviousState)];
}
else
_DOMImageElement.src = [_image filename];
}
}
if (hasDOMTextElement)
{
var textRectX = CGRectGetMinX(textRect),
textRectY = CGRectGetMinY(textRect),
textRectWidth = CGRectGetWidth(textRect),
textRectHeight = CGRectGetHeight(textRect);
if (textRectWidth <= 0 || textRectHeight <= 0)
{
// Don't bother trying to position the text in an empty rect.
textRectWidth = 0;
textRectHeight = 0;
[[_textShadowColor cssDictionary] enumerateKeysAndObjectsUsingBlock:function(aKey, anObject, stop)
{
_DOMTextElement.style[aKey] = anObject;
}];
}
else
{
if (_verticalAlignment !== CPTopVerticalTextAlignment)
{
if (!_textSize)
{
if (_lineBreakMode === CPLineBreakByCharWrapping ||
_lineBreakMode === CPLineBreakByWordWrapping)
{
_textSize = [_text sizeWithFont:_font inWidth:textRectWidth];
// Create or destroy the DOM Text Shadow element as necessary.
// If _textShadowColor's alphaComponent is 0, don't bother drawing anything (issue #1412).
// This improves performance as we get rid of an invisible element, and makes IE <9.0 capable
// of correctly 'rendering' shadows with [CPColor clearColor].
var needsDOMTextShadowElement = hasDOMTextElement && [_textShadowColor alphaComponent] > 0.0,
hasDOMTextShadowElement = !!_DOMTextShadowElement;
if (_usesSingleLineMode)
_textSize.height = [_font defaultLineHeightForFont];
if (needsDOMTextShadowElement !== hasDOMTextShadowElement)
{
if (hasDOMTextShadowElement)
{
_DOMElement.removeChild(_DOMTextShadowElement);
_DOMTextShadowElement = nil;
hasDOMTextShadowElement = NO;
}
else
{
_DOMTextShadowElement = document.createElement("div");
var shadowStyle = _DOMTextShadowElement.style,
font = (_font || [CPFont systemFontOfSize:CPFontCurrentSystemSize]);
shadowStyle.font = [font cssString];
shadowStyle.position = "absolute";
shadowStyle.whiteSpace = textStyle.whiteSpace;
shadowStyle.wordWrap = textStyle.wordWrap;
shadowStyle.color = [_textShadowColor cssString];
shadowStyle.lineHeight = [font defaultLineHeightForFont] + "px";
shadowStyle.zIndex = 150;
shadowStyle.textOverflow = textStyle.textOverflow;
if (document.attachEvent)
{
shadowStyle.overflow = textStyle.overflow;
}
else
{
_textSize = [_text sizeWithFont:_font];
// Account for possible fractional pixels at right edge
_textSize.width += 1;
shadowStyle.overflowX = textStyle.overflowX;
shadowStyle.overflowY = textStyle.overflowY;
}
// Account for possible fractional pixels at bottom edge
_textSize.height += 1;
}
_DOMElement.appendChild(_DOMTextShadowElement);
if (_verticalAlignment === CPCenterVerticalTextAlignment)
{
// Since we added +1 px height above to show fractional pixels on the bottom, we have to remove that when calculating vertical centre.
textRectY = textRectY + (textRectHeight - _textSize.height + 1.0) / 2.0;
textRectHeight = _textSize.height;
}
hasDOMTextShadowElement = YES;
else // if (_verticalAlignment === CPBottomVerticalTextAlignment)
{
textRectY = textRectY + textRectHeight - _textSize.height;
textRectHeight = _textSize.height;
_flags |= _CPImageAndTextViewTextChangedFlag; //sigh...
}
}
}
textStyle.top = ROUND(textRectY) + "px";
textStyle.left = ROUND(textRectX) + "px";
textStyle.width = MAX(CEIL(textRectWidth), 0) + "px";
textStyle.height = MAX(CEIL(textRectHeight), 0) + "px";
textStyle.verticalAlign = @"top";
var shadowStyle = hasDOMTextShadowElement ? _DOMTextShadowElement.style : nil;
if (shadowStyle)
if (hasDOMTextElement)
{
if (_flags & _CPImageAndTextViewTextShadowColorChangedFlag)
shadowStyle.color = [_textShadowColor cssString];
// Update the text contents if necessary.
if (_flags & _CPImageAndTextViewTextChangedFlag)
if (CPFeatureIsCompatible(CPJavaScriptInnerTextFeature))
{
_DOMTextElement.innerText = _text;
shadowStyle.top = ROUND(textRectY + _textShadowOffset.height) + "px";
shadowStyle.left = ROUND(textRectX + _textShadowOffset.width) + "px";
shadowStyle.width = MAX(CEIL(textRectWidth), 0) + "px";
shadowStyle.height = MAX(CEIL(textRectHeight), 0) + "px";
if (_DOMTextShadowElement)
_DOMTextShadowElement.innerText = _text;
}
else if (CPFeatureIsCompatible(CPJavaScriptTextContentFeature))
{
_DOMTextElement.textContent = _text;
if (_DOMTextShadowElement)
_DOMTextShadowElement.textContent = _text;
}
if (_flags & _CPImageAndTextViewFontChangedFlag)
{
var font = (_font || [CPFont systemFontOfSize:CPFontCurrentSystemSize]),
fontStyle = [font cssString];
textStyle.font = fontStyle;
textStyle.lineHeight = [font defaultLineHeightForFont] + "px";
if (shadowStyle)
{
shadowStyle.font = fontStyle;
shadowStyle.lineHeight = [font defaultLineHeightForFont] + "px";
}
}
if (_flags & _CPImageAndTextViewTextUnderlineChangedFlag)
{
textStyle.textDecoration = _textUnderline ? "underline" : "";
}
// Update the line break mode if necessary.
if (_flags & _CPImageAndTextViewLineBreakModeChangedFlag)
{
switch (_lineBreakMode)
{
case CPLineBreakByClipping:
textStyle.overflow = "hidden";
textStyle.textOverflow = "clip";
textStyle.whiteSpace = "pre";
textStyle.wordWrap = "normal";
break;
case CPLineBreakByTruncatingHead:
case CPLineBreakByTruncatingMiddle: // Don't have support for these (yet?), so just degrade to truncating tail.
case CPLineBreakByTruncatingTail:
textStyle.textOverflow = "ellipsis";
textStyle.whiteSpace = "pre";
textStyle.overflow = "hidden";
textStyle.wordWrap = "normal";
break;
case CPLineBreakByCharWrapping:
case CPLineBreakByWordWrapping:
textStyle.wordWrap = "break-word";
try
{
textStyle.whiteSpace = "pre";
textStyle.whiteSpace = "-o-pre-wrap";
textStyle.whiteSpace = "-pre-wrap";
textStyle.whiteSpace = "-moz-pre-wrap";
textStyle.whiteSpace = "pre-wrap";
}
catch (e)
{
//internet explorer doesn't like these properties
textStyle.whiteSpace = "pre";
}
textStyle.overflow = "hidden";
textStyle.textOverflow = "clip";
break;
}
if (shadowStyle)
{
if (document.attachEvent)
{
shadowStyle.overflow = textStyle.overflow;
}
else
{
shadowStyle.overflowX = textStyle.overflowX;
shadowStyle.overflowY = textStyle.overflowY;
}
shadowStyle.wordWrap = textStyle.wordWrap;
shadowStyle.whiteSpace = textStyle.whiteSpace;
shadowStyle.textOverflow = textStyle.textOverflow;
}
}
}
var needsDOMImageElement = _image != nil && _imagePosition !== CPNoImage,
hasDOMImageElement = !!_DOMImageElement,
// For CSS theming
isCSSBasedImage = [_image isCSSBased],
isIMGImageElement = hasDOMImageElement && (_DOMImageElement.nodeName == "IMG");
// First, check if we need to destroy a current DOM image element. This is the case if :
// - we have one but don't need it anymore
// - we have one but not the right one (that is a DIV but needing an IMG, and vice versa)
if (hasDOMImageElement)
{
if (!needsDOMImageElement || (isIMGImageElement && isCSSBasedImage) || (!isIMGImageElement && !isCSSBasedImage))
{
// OK, destroy it
_DOMElement.removeChild(_DOMImageElement);
_DOMImageElement = nil;
hasDOMImageElement = NO;
// CSS styling cleaning
_cssStylePreviousState = @[];
_cssStyleNode = nil;
}
}
// Now, if we need a DOM image element and if we don't have one, create a new one
if (needsDOMImageElement && !hasDOMImageElement)
{
_DOMImageElement = document.createElement(isCSSBasedImage ? "div" : "img");
if ([CPPlatform supportsDragAndDrop])
{
_DOMImageElement.setAttribute("draggable", "true");
_DOMImageElement.style["-khtml-user-drag"] = "element";
}
var imageStyle = _DOMImageElement.style;
imageStyle.top = "0px";
imageStyle.left = "0px";
imageStyle.position = "absolute";
imageStyle.zIndex = 100;
_DOMElement.appendChild(_DOMImageElement);
hasDOMImageElement = YES;
}
var size = [self bounds].size,
textRect = CGRectMake(0.0, 0.0, size.width, size.height);
if (hasDOMImageElement)
{
if (!imageStyle)
var imageStyle = _DOMImageElement.style;
var centerX = size.width / 2.0,
centerY = size.height / 2.0,
imageSize = [_image size],
imageWidth = imageSize.width,
imageHeight = imageSize.height;
if (_imageScaling === CPImageScaleAxesIndependently)
{
imageWidth = size.width;
imageHeight = size.height;
}
else if (_imageScaling === CPImageScaleProportionallyDown)
{
var scale = MIN(MIN(size.width, imageWidth) / imageWidth, MIN(size.height, imageHeight) / imageHeight);
imageWidth *= scale;
imageHeight *= scale;
}
else if (_imageScaling === CPImageScaleProportionallyUpOrDown)
{
var scale = MIN(size.width / imageWidth, size.height / imageHeight);
imageWidth *= scale;
imageHeight *= scale;
}
if (CPFeatureIsCompatible(CPOpacityRequiresFilterFeature))
imageStyle.filter = @"alpha(opacity=" + _shouldDimImage ? 50 : 100 + ")";
else
imageStyle.opacity = _shouldDimImage ? 0.5 : 1.0;
_DOMImageElement.width = imageWidth;
_DOMImageElement.height = imageHeight;
imageStyle.width = MAX(imageWidth, 0) + "px";
imageStyle.height = MAX(imageHeight, 0) + "px";
if (_imagePosition === CPImageBelow)
{
imageStyle.left = FLOOR(centerX - imageWidth / 2.0) + "px";
imageStyle.top = FLOOR(size.height - imageHeight) + "px";
textRect.size.height = size.height - imageHeight - _imageOffset;
}
else if (_imagePosition === CPImageAbove)
{
imageStyle.left = FLOOR(centerX - imageWidth / 2.0) + "px";
imageStyle.top = 0 + "px";
textRect.origin.y += imageHeight + _imageOffset;
textRect.size.height = size.height - imageHeight - _imageOffset;
}
else if (_imagePosition === CPImageLeft)
{
imageStyle.top = _imageVerticalOffset + FLOOR(centerY - imageHeight / 2.0) + "px";
imageStyle.left = "0px";
textRect.origin.x = imageWidth + _imageOffset;
textRect.size.width -= imageWidth + _imageOffset;
}
else if (_imagePosition === CPImageRight)
{
imageStyle.top = _imageVerticalOffset + FLOOR(centerY - imageHeight / 2.0) + "px";
imageStyle.left = FLOOR(size.width - imageWidth) + "px";
textRect.size.width -= imageWidth + _imageOffset;
}
else if (_imagePosition === CPImageOnly || _imagePosition == CPImageOverlaps)
{
imageStyle.top = _imageVerticalOffset + FLOOR(centerY - imageHeight / 2.0) + "px";
imageStyle.left = FLOOR(centerX - imageWidth / 2.0) + "px";
}
if (_flags & _CPImageAndTextViewImageChangedFlag)
{
if (isCSSBasedImage)
{
// For material icons images & co.
if ([_image _shouldBeResized])
[_image _setDisplaySize:CGSizeMake(imageWidth, imageHeight)];
_cssStyleNode = [_image applyCSSImageForView:self
onDOMElement:_DOMImageElement
styleNode:_cssStyleNode
previousState:@ref(_cssStylePreviousState)];
}
else
_DOMImageElement.src = [_image filename];
}
}
if (hasDOMTextElement)
{
var textRectX = CGRectGetMinX(textRect),
textRectY = CGRectGetMinY(textRect),
textRectWidth = CGRectGetWidth(textRect),
textRectHeight = CGRectGetHeight(textRect);
if (textRectWidth <= 0 || textRectHeight <= 0)
{
// Don't bother trying to position the text in an empty rect.
textRectWidth = 0;
textRectHeight = 0;
}
else
{
if (_verticalAlignment !== CPTopVerticalTextAlignment)
{
if (!_textSize)
{
if (_lineBreakMode === CPLineBreakByCharWrapping ||
_lineBreakMode === CPLineBreakByWordWrapping)
{
_textSize = [_text sizeWithFont:_font inWidth:textRectWidth];
if (_usesSingleLineMode)
_textSize.height = [_font defaultLineHeightForFont];
}
else
{
_textSize = [_text sizeWithFont:_font];
// Account for possible fractional pixels at right edge
_textSize.width += 1;
}
// Account for possible fractional pixels at bottom edge
_textSize.height += 1;
}
if (_verticalAlignment === CPCenterVerticalTextAlignment)
{
// Since we added +1 px height above to show fractional pixels on the bottom, we have to remove that when calculating vertical centre.
textRectY = textRectY + (textRectHeight - _textSize.height + 1.0) / 2.0;
textRectHeight = _textSize.height;
}
else // if (_verticalAlignment === CPBottomVerticalTextAlignment)
{
textRectY = textRectY + textRectHeight - _textSize.height;
textRectHeight = _textSize.height;
}
}
}
textStyle.top = ROUND(textRectY) + "px";
textStyle.left = ROUND(textRectX) + "px";
textStyle.width = MAX(CEIL(textRectWidth), 0) + "px";
textStyle.height = MAX(CEIL(textRectHeight), 0) + "px";
textStyle.verticalAlign = @"top";
if (shadowStyle)
{
if (_flags & _CPImageAndTextViewTextShadowColorChangedFlag)
shadowStyle.color = [_textShadowColor cssString];
shadowStyle.top = ROUND(textRectY + _textShadowOffset.height) + "px";
shadowStyle.left = ROUND(textRectX + _textShadowOffset.width) + "px";
shadowStyle.width = MAX(CEIL(textRectWidth), 0) + "px";
shadowStyle.height = MAX(CEIL(textRectHeight), 0) + "px";
}
}
}
#endif
_flags = 0;
}
@@ -901,10 +900,10 @@ var _CPimageAndTextViewFrameSizeChangedFlag = 1 << 0,
- (void)setSelectedRange:(CPRange)aRange
{
#if PLATFORM(DOM)
if (!CPDOMAvailable) return;
if (_DOMTextElement)
[[[self window] platformWindow] setSelectedRange:aRange inElement:_DOMTextElement];
#endif
}
@end
-18
View File
@@ -76,12 +76,8 @@ var CPViewThemeClassKey = @"CPViewThemeClassKey",
- (BOOL)hasThemeState:(ThemeState)aState
{
#if DEBUG
// TODO: To allow aState to be an array is now deprecated. An exception is thrown only in Debug version as
// the preformance cost for this check is to high. We should remove this check in a future release.
if (aState && aState.isa && [aState isKindOfClass:CPArray])
[CPException raise:CPInvalidArgumentException reason:@"aState can't be an array. Please use 'hasThemeStates: instead: " + aState];
#endif
return _themeState.hasThemeState(aState);
}
@@ -99,12 +95,8 @@ var CPViewThemeClassKey = @"CPViewThemeClassKey",
- (BOOL)setThemeState:(ThemeState)aState
{
#if DEBUG
// TODO: To allow aState to be an array is now deprecated. An exception is thrown only in Debug version as
// the preformance cost for this check is to high. We should remove this check in a future release.
if (aState && aState.isa && [aState isKindOfClass:CPArray])
[CPException raise:CPInvalidArgumentException reason:@"aState can't be an array. Please use 'setThemeStates: instead: " + aState];
#endif
if (_themeState.hasThemeState(aState))
return NO;
@@ -116,12 +108,8 @@ var CPViewThemeClassKey = @"CPViewThemeClassKey",
- (BOOL)unsetThemeState:(ThemeState)aState
{
#if DEBUG
// TODO: To allow aState to be an array is now deprecated. An exception is thrown only in Debug version as
// the preformance cost for this check is to high. We should remove this check in a future release.
if (aState && aState.isa && [aState isKindOfClass:CPArray])
[CPException raise:CPInvalidArgumentException reason:@"aState can't be an array. Please use 'unsetThemeStates: instead: " + aState];
#endif
var oldThemeState = _themeState;
@@ -318,12 +306,8 @@ var NULL_THEME = {};
- (void)setValue:(id)aValue forThemeAttribute:(CPString)aName inState:(ThemeState)aState
{
#if DEBUG
// TODO: To allow aState to be an array is now deprecated. An exception is thrown only in Debug version as
// the preformance cost for this check is to high. We should remove this check in a future release.
if (aState.isa && [aState isKindOfClass:CPArray])
[CPException raise:CPInvalidArgumentException reason:self + @": aState can't be an array. Please use 'setValue:forThemeAttribute:inStates:' instead: " + aState];
#endif
var themeAttr = _themeAttributes && _themeAttributes[aName];
@@ -361,10 +345,8 @@ var NULL_THEME = {};
- (id)valueForThemeAttribute:(CPString)aName inState:(ThemeState)aState
{
#if DEBUG
if (aState.isa && [aState isKindOfClass:CPArray])
[CPException raise:CPInvalidArgumentException reason:@"aState can't be an array. Please use 'valueForThemeAttribute:inStates:' instead: " + aState];
#endif
var themeAttr = _themeAttributes && _themeAttributes[aName];
+52 -44
View File
@@ -26,6 +26,7 @@
@import "CPMenu.j"
@import "CPPanel.j"
@import "CPAnimationContext.j"
@import "CPCompatibility.j"
// Use forward declaration because this file is imported by CPPopover
@class CPPopover
@@ -415,12 +416,12 @@ var _CPPopoverWindow_shouldClose_ = 1 << 4,
/*! @ignore */
- (void)setCSS3Property:(CPString)aProperty value:(CPString)value
{
if (!CPDOMAvailable) return;
var browserProperty = CPBrowserStyleProperty(aProperty);
#if PLATFORM(DOM)
if (browserProperty)
_DOMElement.style[browserProperty] = value;
#endif
}
/*! @ignore */
@@ -537,14 +538,16 @@ var _CPPopoverWindow_shouldClose_ = 1 << 4,
window.setTimeout(function()
{
// We are watching opacity, so this triggers the next transition
#if PLATFORM(DOM)
// We force the style to recalculate the values, this is needed to avoid a transition issue
// More information here : https://code.google.com/p/chromium/issues/detail?id=388082
[self _currentTransformMatrix];
_DOMElement.style.opacity = 1;
_DOMElement.style.height = frame.size.height + @"px";
_DOMElement.style.width = frame.size.width + @"px";
#endif
if (CPDOMAvailable)
{
// We force the style to recalculate the values, this is needed to avoid a transition issue
// More information here : https://code.google.com/p/chromium/issues/detail?id=388082
[self _currentTransformMatrix];
_DOMElement.style.opacity = 1;
_DOMElement.style.height = frame.size.height + @"px";
_DOMElement.style.width = frame.size.width + @"px";
}
// Set up the pop-out transition
[self setCSS3Property:@"Transform" value:@"scale(1.1)"];
@@ -552,9 +555,10 @@ var _CPPopoverWindow_shouldClose_ = 1 << 4,
_orderFrontTransitionFunction = function()
{
#if PLATFORM(DOM)
_DOMElement.removeEventListener(CPBrowserStyleProperty('transitionend'), _orderFrontTransitionFunction, YES);
#endif
if (CPDOMAvailable)
{
_DOMElement.removeEventListener(CPBrowserStyleProperty('transitionend'), _orderFrontTransitionFunction, YES);
}
// Now set up the pop-in to normal size transition.
// Because we are watching the -webkit-transform, it will occur now.
@@ -566,33 +570,37 @@ var _CPPopoverWindow_shouldClose_ = 1 << 4,
_transitionCompleteFunction = function()
{
#if PLATFORM(DOM)
_DOMElement.removeEventListener(CPBrowserStyleProperty('transitionend'), _transitionCompleteFunction, YES);
if (CPDOMAvailable)
{
_DOMElement.removeEventListener(CPBrowserStyleProperty('transitionend'), _transitionCompleteFunction, YES);
// Make sure to clear these properties when the animation is done. Without this,
// the window becomes blurry in Chrome, presumably because the browser composits
// a layer with a transform differently even when it's an identity transform.
[self setCSS3Property:@"Transform" value:nil];
[self setCSS3Property:@"TransformOrigin" value:nil];
[self setCSS3Property:@"Transition" value:nil];
}
// Make sure to clear these properties when the animation is done. Without this,
// the window becomes blurry in Chrome, presumably because the browser composits
// a layer with a transform differently even when it's an identity transform.
[self setCSS3Property:@"Transform" value:nil];
[self setCSS3Property:@"TransformOrigin" value:nil];
[self setCSS3Property:@"Transition" value:nil];
#endif
_isOpening = NO;
[_delegate _popoverWindowDidShow];
};
#if PLATFORM(DOM)
_DOMElement.addEventListener(CPBrowserStyleProperty('transitionend'), _transitionCompleteFunction, YES);
#endif
if (CPDOMAvailable)
{
_DOMElement.addEventListener(CPBrowserStyleProperty('transitionend'), _transitionCompleteFunction, YES);
}
}, 0); // There are some weird random conditions happening in Chrome 44. If we don't put a timeout to 0 for the end of
// the transition, the popover is blinking. It happens on Opera as well...
// When the condition is met, the popover will lag a bit when opening...nothing crazy ;)
// An issue has been opened here : https://code.google.com/p/chromium/issues/detail?id=523044&thanks=523044&ts=1440095724
};
#if PLATFORM(DOM)
_DOMElement.addEventListener(CPBrowserStyleProperty('transitionend'), _orderFrontTransitionFunction, YES);
#endif
if (CPDOMAvailable)
{
_DOMElement.addEventListener(CPBrowserStyleProperty('transitionend'), _orderFrontTransitionFunction, YES);
}
}, 10); // There are some weird race conditions happening in Chrome 34. If this is set to 0
// the transitionend is randomly not called correctly. Setting the timeout to 10ms is not noticealble for the
// user, and seems to fix the issue.
@@ -601,9 +609,11 @@ var _CPPopoverWindow_shouldClose_ = 1 << 4,
{
_isOpening = NO;
[self setCSS3Property:@"Transition" value:@""];
#if PLATFORM(DOM)
_DOMElement.style.opacity = 1;
#endif
if (CPDOMAvailable)
{
_DOMElement.style.opacity = 1;
}
}
}
@@ -639,9 +649,8 @@ var _CPPopoverWindow_shouldClose_ = 1 << 4,
if (_animates && _browserAnimates)
{
if (_isOpening)
if (CPDOMAvailable && _isOpening)
{
#if PLATFORM(DOM)
_DOMElement.removeEventListener(CPBrowserStyleProperty('transitionend'), _orderFrontTransitionFunction, YES);
_DOMElement.removeEventListener(CPBrowserStyleProperty('transitionend'), _transitionCompleteFunction, YES);
@@ -649,15 +658,16 @@ var _CPPopoverWindow_shouldClose_ = 1 << 4,
currentScale = (matrix.split('(')[1]).split(',')[0];
[self setCSS3Property:@"Transform" value:@"scale(" + currentScale + ")"];
#endif
}
// Tell the element to fade out when the opacity changes
[self setCSS3Property:@"Transition" value:@"opacity 250ms linear"];
#if PLATFORM(DOM)
_DOMElement.style.opacity = 0;
_DOMElement.addEventListener(CPBrowserStyleProperty("transitionend"), _orderOutTransitionFunction, YES);
#endif
if (CPDOMAvailable)
{
_DOMElement.style.opacity = 0;
_DOMElement.addEventListener(CPBrowserStyleProperty("transitionend"), _orderOutTransitionFunction, YES);
}
}
else
{
@@ -668,10 +678,10 @@ var _CPPopoverWindow_shouldClose_ = 1 << 4,
- (void)_orderOutRecursively:(BOOL)recursive
{
// Make absolutely sure no dangling event listeners are left
#if PLATFORM(DOM)
if (_animates && _browserAnimates)
if (CPDOMAvailable && _animates && _browserAnimates)
{
_DOMElement.removeEventListener(CPBrowserStyleProperty("transitionend"), _orderOutTransitionFunction, YES);
#endif
}
[self _removeFrameObserver];
[_parentWindow removeChildWindow:self];
@@ -702,9 +712,7 @@ var _CPPopoverWindow_shouldClose_ = 1 << 4,
- (CPString)_currentTransformMatrix
{
#if PLATFORM(DOM)
return window.getComputedStyle(_DOMElement, null)[CPBrowserStyleProperty(@"transform")];
#endif
if (CPDOMAvailable) return window.getComputedStyle(_DOMElement, null)[CPBrowserStyleProperty(@"transform")];
}
- (BOOL)_hasOnlyTransientChild:(_CPPopoverWindow)aWindow
-2
View File
@@ -53,8 +53,6 @@ foundationTask = framework ("Foundation", function(foundationTask)
return "--include \"" + aFilename + "\"";
}).join(" ");
INCLUDES = "--include \"../AppKit/Platform/Platform.h\" " + INCLUDES;
if ($CONFIGURATION === "Release")
foundationTask.setCompilerFlags("-O2 -Wno-unused-but-set-variable " + INCLUDES);
else
-2
View File
@@ -20,8 +20,6 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
//#define _IS_NUMERIC(n) (!isNaN(parseFloat(n)) && isFinite(n))
/*
Objective-J is a strict superset of JavaScript and compiles down to a shared global runtime scope.
This file (_CPFoundationUtilities.j) is the canonical place for otherwise "homeless" low-level
+29
View File
@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CPBundleIdentifier</key>
<string>com.280n.Cappuccino</string>
<key>CPBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CPBundleName</key>
<string>Cappuccino</string>
<key>CPBundlePackageType</key>
<string>CPKG</string>
<key>CPBundleVersion</key>
<string>1.3.1</string>
<key>CPBuildRuntime</key>
<string>Objective-J</string>
<key>CPBuildFrameworks</key>
<array>
<string>Foundation</string>
<string>AppKit</string>
<string>AppKit/Themes/BlendKit</string>
</array>
<key>CPBuildThemes</key>
<array>
<string>AppKit/Themes/Aristo</string>
<string>AppKit/Themes/Aristo2</string>
</array>
</dict>
</plist>
-2
View File
@@ -59,9 +59,7 @@ Environment.prototype.spritesImages = function()
exports.Environment = Environment;
exports.ObjJ = new Environment("ObjJ");
var CommonJS = new Environment("CommonJS");
CommonJS.setCompilerFlags(["-DPLATFORM_COMMONJS"]);
exports.CommonJS = CommonJS;
var Browser = new Environment("Browser");
Browser.setCompilerFlags(["-DPLATFORM_BROWSER", "-DPLATFORM_DOM"]);
Browser.setSpritesImages(true);
exports.Browser = Browser;
@@ -51,13 +51,10 @@ exports.ObjJ = new Environment("ObjJ");
var CommonJS = new Environment("CommonJS");
CommonJS.setCompilerFlags(["-DPLATFORM_COMMONJS"]);
exports.CommonJS = CommonJS;
var Browser = new Environment("Browser");
Browser.setCompilerFlags(["-DPLATFORM_BROWSER", "-DPLATFORM_DOM"]);
Browser.setSpritesImages(true);
exports.Browser = Browser;
-1
View File
@@ -19,7 +19,6 @@
//{
[self assert:YES equals:!CPFeatureIsCompatible(CPHTMLCanvasFeature)];
//}
[self assert:YES equals:!CPFeatureIsCompatible(CPVMLFeature)];
}
- (void)testGStateCreate
+65
View File
@@ -0,0 +1,65 @@
@import <Foundation/Foundation.j>
@import <AppKit/CPCompatibility.j>
var SafariUserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/27.0.1 Safari/605.1.15";
@implementation CPCompatibilityTest : OJTestCase
/*!
When CPCompatibility.j loads, it identifies the browser engine from the user
agent string. For WebKit and Blink browsers (user agent containing
"AppleWebKit/"), that detection calls +[CPPlatform isBrowser], which reads
CPDOMAvailable, so CPDOMAvailable must already be assigned at that point.
The test suite runs outside a browser, with no user agent, so this code is
never reached when the frameworks load for testing. The test reproduces a
WebKit or Blink browser load instead: it supplies an AppleWebKit user agent,
removes CPDOMAvailable, and runs CPCompatibility.j again.
*/
- (void)testLoadUnderWebKitUserAgentDoesNotReadCPDOMAvailableBeforeAssignment
{
var executable = compatibilityExecutable(),
runtimeWindow = ObjectiveJ.window,
savedNavigator = runtimeWindow.navigator,
savedDOMAvailable = CPDOMAvailable,
loadException = nil;
[self assertNotNull:executable message:@"CPCompatibility.j executable not found"];
runtimeWindow.navigator = { userAgent: SafariUserAgent };
delete global.CPDOMAvailable;
try
{
executable.execute(YES);
}
catch (anException)
{
loadException = anException;
}
// Restore the Node environment and re-run detection so later tests see it.
if (savedNavigator === undefined)
delete runtimeWindow.navigator;
else
runtimeWindow.navigator = savedNavigator;
CPDOMAvailable = savedDOMAvailable;
executable.execute(YES);
if (loadException)
[self fail:@"CPCompatibility.j threw while loading under a WebKit user agent: " + loadException];
}
@end
function compatibilityExecutable()
{
var executables = ObjectiveJ.FileExecutable.allFileExecutables();
for (var i = 0; i < executables.length; i++)
if (/\/CPCompatibility\.j$/.test(executables[i].URL().absoluteString()))
return executables[i];
return nil;
}
+1 -1
View File
@@ -1,6 +1,6 @@
@import <OJUnit/OJTestCase.j>
@import <AppKit/CPDOMDisplayServer.j>
#include "../../AppKit/Platform/DOM/CPDOMDisplayServer.h"
@implementation CPDOMDisplayServerTest : OJTestCase
{
+7 -9
View File
@@ -1,8 +1,6 @@
@import <AppKit/CPLevelIndicator.j>
// You should never do this. This is only for testing purposes.
#define GET_LEVEL_INDICATOR_SEGMENT(levelIndicator, i) [(levelIndicator) layoutEphemeralSubviewNamed:@"segment-bezel-" + (i) positioned:CPWindowAbove relativeToEphemeralSubviewNamed:"bezel"]
// You should never access a view's ephemeral layout subviews directly. This is only for testing purposes.
@implementation CPLevelIndicatorTest : OJTestCase
{
}
@@ -41,7 +39,7 @@
[levelIndicator setObjectValue:5];
[[CPRunLoop currentRunLoop] limitDateForMode:CPDefaultRunLoopMode];
[self assert:[CPColor greenColor] equals:[GET_LEVEL_INDICATOR_SEGMENT(levelIndicator, 0) backgroundColor]];
[self assert:[CPColor greenColor] equals:[[levelIndicator layoutEphemeralSubviewNamed:@"segment-bezel-0" positioned:CPWindowAbove relativeToEphemeralSubviewNamed:"bezel"] backgroundColor]];
}
- (void)testLevelIndicatorWithLowWarningAndCriticalShouldShowWarningColor
@@ -51,7 +49,7 @@
[levelIndicator setObjectValue:4];
[[CPRunLoop currentRunLoop] limitDateForMode:CPDefaultRunLoopMode];
[self assert:[CPColor yellowColor] equals:[GET_LEVEL_INDICATOR_SEGMENT(levelIndicator, 0) backgroundColor]];
[self assert:[CPColor yellowColor] equals:[[levelIndicator layoutEphemeralSubviewNamed:@"segment-bezel-0" positioned:CPWindowAbove relativeToEphemeralSubviewNamed:"bezel"] backgroundColor]];
}
- (void)testLevelIndicatorWithLowWarningAndCriticalShouldShowCriticalColor
@@ -61,7 +59,7 @@
[levelIndicator setObjectValue:2];
[[CPRunLoop currentRunLoop] limitDateForMode:CPDefaultRunLoopMode];
[self assert:[CPColor redColor] equals:[GET_LEVEL_INDICATOR_SEGMENT(levelIndicator, 0) backgroundColor]];
[self assert:[CPColor redColor] equals:[[levelIndicator layoutEphemeralSubviewNamed:@"segment-bezel-0" positioned:CPWindowAbove relativeToEphemeralSubviewNamed:"bezel"] backgroundColor]];
}
- (void)testLevelIndicatorWithHighWarningAndCriticalShouldShowNormalColor
@@ -71,7 +69,7 @@
[levelIndicator setObjectValue:5];
[[CPRunLoop currentRunLoop] limitDateForMode:CPDefaultRunLoopMode];
[self assert:[CPColor greenColor] equals:[GET_LEVEL_INDICATOR_SEGMENT(levelIndicator, 0) backgroundColor]];
[self assert:[CPColor greenColor] equals:[[levelIndicator layoutEphemeralSubviewNamed:@"segment-bezel-0" positioned:CPWindowAbove relativeToEphemeralSubviewNamed:"bezel"] backgroundColor]];
}
- (void)testLevelIndicatorWithHighWarningAndCriticalShouldShowWarningColor
@@ -81,7 +79,7 @@
[levelIndicator setObjectValue:6];
[[CPRunLoop currentRunLoop] limitDateForMode:CPDefaultRunLoopMode];
[self assert:[CPColor yellowColor] equals:[GET_LEVEL_INDICATOR_SEGMENT(levelIndicator, 0) backgroundColor]];
[self assert:[CPColor yellowColor] equals:[[levelIndicator layoutEphemeralSubviewNamed:@"segment-bezel-0" positioned:CPWindowAbove relativeToEphemeralSubviewNamed:"bezel"] backgroundColor]];
}
- (void)testLevelIndicatorWithHighWarningAndCriticalShouldShowCriticalColor
@@ -91,6 +89,6 @@
[levelIndicator setObjectValue:8];
[[CPRunLoop currentRunLoop] limitDateForMode:CPDefaultRunLoopMode];
[self assert:[CPColor redColor] equals:[GET_LEVEL_INDICATOR_SEGMENT(levelIndicator, 0) backgroundColor]];
[self assert:[CPColor redColor] equals:[[levelIndicator layoutEphemeralSubviewNamed:@"segment-bezel-0" positioned:CPWindowAbove relativeToEphemeralSubviewNamed:"bezel"] backgroundColor]];
}
@end
@@ -11,8 +11,6 @@
@import <AppKit/CAKeyframeAnimation.j>
@import <AppKit/CAAnimationGroup.j>
#define UIAssert(a) [self markTest:_cmd didPass:a];
// A new custom view class to draw the animation path.
@implementation PathView : CPView
{
@@ -300,7 +298,7 @@
[context setCompletionHandler:function()
{
[completions addObject:@"done"];
UIAssert([completions isEqualToArray:@["done"]]);
[self markTest:_cmd didPass:[completions isEqualToArray:@["done"]]];
}];
[CPAnimationContext endGrouping];
}
@@ -315,7 +313,7 @@
[context setCompletionHandler:function()
{
[completions addObject:@"done"];
UIAssert([completions isEqualToArray:@["done"]]);
[self markTest:_cmd didPass:[completions isEqualToArray:@["done"]]];
}];
[CPAnimationContext endGrouping];
}
@@ -336,7 +334,7 @@
[outerContext setCompletionHandler:function()
{
[completions addObject:@"done"];
UIAssert([completions isEqualToArray:@["done"]]);
[self markTest:_cmd didPass:[completions isEqualToArray:@["done"]]];
}];
// Inner group
@@ -356,7 +354,7 @@
[context setCompletionHandler:function()
{
[completions addObject:@"done"];
UIAssert([completions isEqualToArray:@["done"]]);
[self markTest:_cmd didPass:[completions isEqualToArray:@["done"]]];
}];
[[sender animator] setObjectValue:[sender objectValue]];
@@ -373,7 +371,7 @@
[context setCompletionHandler:function()
{
[completions addObject:@"done"];
UIAssert([completions isEqualToArray:@["done"]]);
[self markTest:_cmd didPass:[completions isEqualToArray:@["done"]]];
}];
[[sender animator] setFrame:[sender frame]];
@@ -390,14 +388,14 @@
[context setCompletionHandler:function()
{
// This handler should be replaced and never called.
UIAssert(NO);
[self markTest:_cmd didPass:NO];
}];
// Set the handler again, which should replace the first one.
[context setCompletionHandler:function()
{
[completions addObject:@"done"];
UIAssert([completions isEqualToArray:@["done"]]);
[self markTest:_cmd didPass:[completions isEqualToArray:@["done"]]];
}];
[[sender animator] setFrame:[sender frame]];
+38 -5
View File
@@ -61,16 +61,49 @@ task ("release", ["default"]);
*/
task ("configure", function()
{
var manualDir = __dirname,
releasePath = path.resolve(manualDir, "../../Build/Release"),
debugPath = path.resolve(manualDir, "../../Build/Debug");
var manualDir = __dirname;
provisionFrameworks(
manualDir,
path.resolve(manualDir, "../../Build/Release"),
path.resolve(manualDir, "../../Build/Debug"),
"build the frameworks in both configurations first"
);
});
/*
* Gives every manual test application the same Frameworks layout as configure,
* linked to the capp-build package in Build/modern/Frameworks instead of the
* legacy builds. capp-build produces a single build, so Frameworks/Debug links
* to the same package.
*/
task ("configure-modern", function()
{
var manualDir = __dirname,
modernPath = path.resolve(manualDir, "../../Build/modern/Frameworks");
provisionFrameworks(
manualDir,
modernPath,
modernPath,
"build the package with capp-build first (capp-build build . at the repository root)"
);
});
/*
* Links Frameworks/<Name> to releasePath/<Name> and Frameworks/Debug to
* debugPath in every manual test application, after checking that both hold
* every framework. An existing Frameworks link, or a Frameworks directory
* holding only links, is replaced; one holding real files is left untouched.
*/
function provisionFrameworks(manualDir, releasePath, debugPath, missingHint)
{
[releasePath, debugPath].forEach(function(buildPath)
{
ConfiguredFrameworks.forEach(function(framework)
{
if (!fs.existsSync(path.join(buildPath, framework)))
throw new Error(path.join(buildPath, framework) + " not found; build the frameworks in both configurations first");
throw new Error(path.join(buildPath, framework) + " not found; " + missingHint);
});
});
@@ -95,7 +128,7 @@ task ("configure", function()
fs.symlinkSync(debugPath, path.join(frameworksPath, "Debug"));
});
});
}
/*
* Cleans the subsidiary applications' Build directories exclusively (-mindepth 2 -maxdepth 2).
+1
View File
@@ -115,6 +115,7 @@ ConverterConversionException = @"ConverterConversionException";
- (CPData)CPCompliantNibDataAtFilePath:(CPString)aFilePath
{
var temporaryNibFilePath = "",
temporaryXibFilePath = "",
temporaryPlistFilePath = "";