Remove NativeHost platform target; require CommonJS/Node for tooling

Cappuccino previously supported three platform contexts behind the
PLATFORM() preprocessor macro: Browser, CommonJS/Node, and a NativeHost
target. NativeHost is no longer supported; this removes it and
consolidates on Browser (for the app) and CommonJS/Node (still needed
by the toolchain itself, for theme compilation and testing).

PLATFORM(DOM) conditionals throughout AppKit governed both distinctions
at once - Browser vs NativeHost, and separately, DOM-dependent code vs
the CommonJS/Node build. Each conditional was reviewed individually:
NativeHost-only branches were removed, while branches needed for
CommonJS/Node were kept intact rather than collapsed to Browser-only.

Also included, found in the course of this work:
- Fixed two pre-existing duplicate instance-variable declarations
  (_ephemeralSubviews in CPView, _scrollingTimer in CPTextView)
- Added a missing @import for CPTextContainer.j in CPTextView.j so
  it resolves when compiled outside the full framework bundle
- Merged two Platform/DOM/*.j files into their parents to resolve a
  build-tool basename collision, preserving the CommonJS fallback path
This commit is contained in:
David Richardson committed 2026-08-12 13:25:52 -06:00
1 parent bbdc7e1fe1
commit e5c34e3dd7
19 files changed
+340 -410

No files matched your search

-4
View File
@@ -1001,19 +1001,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 +1083,6 @@ url("data:image/png;base64,BASE64ENCODEDDATA") // if there is a pattern image
@deref(aPreviousStateRef) = aPreviousState;
return aStyleNode;
#endif
}
@end
-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;
}
-2
View File
@@ -388,7 +388,6 @@ function CPBrowserStyleProperty(aProperty)
{
var r = nil;
#if PLATFORM(DOM)
var testElement = document.createElement('div');
switch (lowerProperty)
@@ -455,7 +454,6 @@ function CPBrowserStyleProperty(aProperty)
break;
}
#endif
PLATFORM_STYLE_JS_PROPERTIES[lowerProperty] = r;
}
-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;
}
+2 -2
View File
@@ -89,17 +89,17 @@
[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.
#if PLATFORM(DOM)
_datePicker._DOMElement.style.overflow = "visible";
_DOMElement.style.overflow = "visible";
_datePickerElementView._DOMElement.style.overflow = "visible";
}
#endif
}
}
-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
}
+4 -4
View File
@@ -354,10 +354,10 @@ var CPImageViewEmptyPlaceholderImage = nil;
if (imageScaling === CPImageScaleAxesIndependently)
{
#if PLATFORM(DOM)
#if PLATFORM(DOM)
_DOMImageElement.width = ROUND(width);
_DOMImageElement.height = ROUND(height);
#endif
#endif
}
else
{
@@ -395,10 +395,10 @@ var CPImageViewEmptyPlaceholderImage = nil;
break;
}
#if PLATFORM(DOM)
#if PLATFORM(DOM)
_DOMImageElement.width = ROUND(width);
_DOMImageElement.height = ROUND(height);
#endif
#endif
var x,
y;
+1
View File
@@ -389,3 +389,4 @@ var DOMDataTransferPasteboard = nil;
@end
#endif
-1
View File
@@ -25,7 +25,6 @@
*/
@import "CPText.j"
@import "CPTextContainer.j"
@import "CGContext.j"
@import "CPTypesetter.j"
@import "CPFont.j"
+1 -3
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;
+2 -1
View File
@@ -19,10 +19,11 @@
*/
@import "CPView.j"
@import "CPTextView.j"
@import "CPTextField.j"
@import <Foundation/CPAttributedString.j>
@class CPTextView;
@implementation _CPTableTextAttachment : CPView
{
CPArray _headers;
-1
View File
@@ -230,7 +230,6 @@ var CPViewHighDPIDrawingEnabled = YES;
// Layout Support
BOOL _needsLayout;
JSObject _ephemeralSubviews;
JSObject _ephemeralSubviewsForNames;
CPSet _ephemeralSubviews;
+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)
{
+145 -1
View File
@@ -71,7 +71,151 @@
@end
#if PLATFORM(DOM)
#include "DOM/CPPlatform.j"
// --- begin AppKit/Platform/DOM/CPPlatform.j (inlined; file removed to resolve capp-build basename clash) ---
@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];
};
window.onunload = function()
{
[self closeAllPlatformWindows];
[CPApp terminate:nil];
};
}
}
+ (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
#else
@implementation CPPlatform : CPBasePlatform
{
+183 -1
View File
@@ -39,7 +39,189 @@
@end
#if PLATFORM(DOM)
#include "DOM/CPPlatformString.j"
// --- begin AppKit/Platform/DOM/CPPlatformString.j (inlined; file removed to resolve capp-build basename clash) ---
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
#else
@implementation CPPlatformString : CPBasePlatformString
-2
View File
@@ -310,6 +310,4 @@ var PrimaryPlatformWindow = NULL;
@end
#if PLATFORM(BROWSER)
//@import "CPPlatformWindow+DOM.j"
#endif
-166
View File
@@ -1,166 +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];
};
window.onunload = function()
{
[self closeAllPlatformWindows];
[CPApp terminate:nil];
};
}
}
+ (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
@@ -528,3 +528,4 @@ 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