2 * Copyright (C) 2007 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
14 * its contributors may be used to endorse or promote products derived
15 * from this software without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
18 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
21 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 #include "UniscribeController.h"
33 #include <wtf/MathExtras.h>
37 // FIXME: Rearchitect this to be more like WidthIterator in Font.cpp. Have an advance() method
38 // that does stuff in that method instead of doing everything in the constructor. Have advance()
39 // take the GlyphBuffer as an arg so that we don't have to populate the glyph buffer when
41 UniscribeController::UniscribeController(const Font* font, const TextRun& run)
45 , m_currentCharacter(0)
47 , m_computingOffsetPosition(false)
48 , m_includePartialGlyphs(false)
52 m_padding = m_run.padding();
57 for (int s = 0; s < m_run.length(); s++)
58 if (Font::treatAsSpace(m_run[s]))
64 m_padPerSpace = ceilf(m_run.padding() / numSpaces);
67 // Null out our uniscribe structs
68 resetControlAndState();
71 int UniscribeController::offsetForPosition(int x, bool includePartialGlyphs)
73 m_computingOffsetPosition = true;
74 m_includePartialGlyphs = includePartialGlyphs;
77 advance(m_run.length());
78 if (m_computingOffsetPosition) {
79 // The point is to the left or to the right of the entire run.
80 if (m_offsetX >= m_runWidthSoFar && m_run.ltr() || m_offsetX < 0 && m_run.rtl())
81 m_offsetPosition = m_end;
83 m_computingOffsetPosition = false;
84 return m_offsetPosition;
87 void UniscribeController::advance(unsigned offset, GlyphBuffer* glyphBuffer)
89 // FIXME: We really want to be using a newer version of Uniscribe that supports the new OpenType
90 // functions. Those functions would allow us to turn off kerning and ligatures. Without being able
91 // to do that, we will have buggy line breaking and metrics when simple and complex text are close
92 // together (the complex code path will narrow the text because of kerning and ligatures and then
93 // when bidi processing splits into multiple runs, the simple portions will get wider and cause us to
94 // spill off the edge of a line).
95 if (static_cast<int>(offset) > m_end)
98 // Itemize the string.
99 const UChar* cp = m_run.data(m_currentCharacter);
100 int length = offset - m_currentCharacter;
104 // We break up itemization of the string by fontData and (if needed) the use of small caps.
106 // FIXME: It's inconsistent that we use logical order when itemizing, since this
107 // does not match normal RTL.
109 // FIXME: This function should decode surrogate pairs. Currently it makes little difference that
110 // it does not because the font cache on Windows does not support non-BMP characters.
111 Vector<UChar, 256> smallCapsBuffer;
112 if (m_font.isSmallCaps())
113 smallCapsBuffer.resize(length);
115 unsigned indexOfFontTransition = m_run.rtl() ? length - 1 : 0;
116 const UChar* curr = m_run.rtl() ? cp + length - 1 : cp;
117 const UChar* end = m_run.rtl() ? cp - 1 : cp + length;
119 const FontData* fontData;
120 const FontData* nextFontData = m_font.glyphDataForCharacter(*curr, false).fontData;
125 bool nextIsSmallCaps = m_font.isSmallCaps() && !(U_GET_GC_MASK(*curr) & U_GC_M_MASK) && (newC = u_toupper(*curr)) != *curr;
128 smallCapsBuffer[curr - cp] = newC;
131 curr = m_run.rtl() ? curr - 1 : curr + 1;
135 fontData = nextFontData;
136 isSmallCaps = nextIsSmallCaps;
137 int index = curr - cp;
140 bool forceSmallCaps = isSmallCaps && (U_GET_GC_MASK(c) & U_GC_M_MASK);
141 nextFontData = m_font.glyphDataForCharacter(*curr, false, forceSmallCaps).fontData;
142 if (m_font.isSmallCaps()) {
143 nextIsSmallCaps = forceSmallCaps || (newC = u_toupper(c)) != c;
145 smallCapsBuffer[index] = forceSmallCaps ? c : newC;
148 if (nextFontData != fontData || nextIsSmallCaps != isSmallCaps) {
149 int itemStart = m_run.rtl() ? index : indexOfFontTransition;
150 int itemLength = m_run.rtl() ? indexOfFontTransition - index : index - indexOfFontTransition;
151 itemizeShapeAndPlace((isSmallCaps ? smallCapsBuffer.data() : cp) + itemStart, itemLength, fontData, glyphBuffer);
152 indexOfFontTransition = index;
156 int itemLength = m_run.rtl() ? indexOfFontTransition + 1 : length - indexOfFontTransition;
158 int itemStart = m_run.rtl() ? 0 : indexOfFontTransition;
159 itemizeShapeAndPlace((nextIsSmallCaps ? smallCapsBuffer.data() : cp) + itemStart, itemLength, nextFontData, glyphBuffer);
163 void UniscribeController::itemizeShapeAndPlace(const UChar* cp, unsigned length, const FontData* fontData, GlyphBuffer* glyphBuffer)
165 // ScriptItemize (in Windows XP versions prior to SP2) can overflow by 1. This is why there is an extra empty item
166 // hanging out at the end of the array
169 while (ScriptItemize(cp, length, m_items.size() - 1, &m_control, &m_state, m_items.data(), &numItems) == E_OUTOFMEMORY) {
170 m_items.resize(m_items.size() * 2);
171 resetControlAndState();
173 m_items.resize(numItems + 1);
176 for (int i = m_items.size() - 2; i >= 0; i--) {
177 if (!shapeAndPlaceItem(cp, i, fontData, glyphBuffer))
181 for (unsigned i = 0; i < m_items.size() - 1; i++) {
182 if (!shapeAndPlaceItem(cp, i, fontData, glyphBuffer))
187 m_currentCharacter += length;
190 void UniscribeController::resetControlAndState()
192 memset(&m_control, 0, sizeof(SCRIPT_CONTROL));
193 memset(&m_state, 0, sizeof(SCRIPT_STATE));
195 // Set up the correct direction for the run.
196 m_state.uBidiLevel = m_run.rtl();
198 // Lock the correct directional override.
199 m_state.fOverrideDirection = m_run.directionalOverride();
202 bool UniscribeController::shapeAndPlaceItem(const UChar* cp, unsigned i, const FontData* fontData, GlyphBuffer* glyphBuffer)
204 // Determine the string for this item.
205 const UChar* str = cp + m_items[i].iCharPos;
206 int len = m_items[i+1].iCharPos - m_items[i].iCharPos;
207 SCRIPT_ITEM item = m_items[i];
209 // Set up buffers to hold the results of shaping the item.
211 Vector<WORD> clusters;
212 Vector<SCRIPT_VISATTR> visualAttributes;
213 clusters.resize(len);
216 // The recommended size for the glyph buffer is 1.5 * the character length + 16 in the uniscribe docs.
217 // Apparently this is a good size to avoid having to make repeated calls to ScriptShape.
218 glyphs.resize(1.5 * len + 16);
219 visualAttributes.resize(glyphs.size());
221 if (!shape(str, len, item, fontData, glyphs, clusters, visualAttributes))
224 // We now have a collection of glyphs.
225 Vector<GOFFSET> offsets;
226 Vector<int> advances;
227 offsets.resize(glyphs.size());
228 advances.resize(glyphs.size());
230 HRESULT placeResult = ScriptPlace(0, fontData->scriptCache(), glyphs.data(), glyphs.size(), visualAttributes.data(),
231 &item.a, advances.data(), offsets.data(), 0);
232 if (placeResult == E_PENDING) {
233 // The script cache isn't primed with enough info yet. We need to select our HFONT into
234 // a DC and pass the DC in to ScriptPlace.
236 HFONT hfont = fontData->platformData().hfont();
237 HFONT oldFont = (HFONT)SelectObject(hdc, hfont);
238 placeResult = ScriptPlace(hdc, fontData->scriptCache(), glyphs.data(), glyphs.size(), visualAttributes.data(),
239 &item.a, advances.data(), offsets.data(), 0);
240 SelectObject(hdc, oldFont);
244 if (FAILED(placeResult) || glyphs.isEmpty())
247 // Convert all chars that should be treated as spaces to use the space glyph.
248 // We also create a map that allows us to quickly go from space glyphs or rounding
249 // hack glyphs back to their corresponding characters.
250 Vector<int> spaceCharacters(glyphs.size());
251 spaceCharacters.fill(-1);
252 Vector<int> roundingHackCharacters(glyphs.size());
253 roundingHackCharacters.fill(-1);
254 Vector<int> roundingHackWordBoundaries(glyphs.size());
255 roundingHackWordBoundaries.fill(-1);
256 unsigned logicalSpaceWidth = fontData->m_spaceWidth * 32.0f;
257 float roundedSpaceWidth = roundf(fontData->m_spaceWidth);
259 for (int k = 0; k < len; k++) {
260 UChar ch = *(str + k);
261 if (Font::treatAsSpace(ch)) {
262 // Substitute in the space glyph at the appropriate place in the glyphs
264 glyphs[clusters[k]] = fontData->m_spaceGlyph;
265 advances[clusters[k]] = logicalSpaceWidth;
266 spaceCharacters[clusters[k]] = m_currentCharacter + k + item.iCharPos;
269 if (Font::isRoundingHackCharacter(ch))
270 roundingHackCharacters[clusters[k]] = m_currentCharacter + k + item.iCharPos;
272 int boundary = k + m_currentCharacter + item.iCharPos;
273 if (boundary < m_run.length() &&
274 Font::isRoundingHackCharacter(*(str + k + 1)))
275 roundingHackWordBoundaries[clusters[k]] = boundary;
278 // Populate our glyph buffer with this information.
279 bool hasExtraSpacing = m_font.letterSpacing() || m_font.wordSpacing() || m_padding;
281 float leftEdge = m_runWidthSoFar;
283 for (unsigned k = 0; k < glyphs.size(); k++) {
284 Glyph glyph = glyphs[k];
285 float advance = advances[k] / 32.0f;
286 float offsetX = offsets[k].du / 32.0f;
287 float offsetY = offsets[k].dv / 32.0f;
289 // Match AppKit's rules for the integer vs. non-integer rendering modes.
290 float roundedAdvance = roundf(advance);
291 if (!m_font.isPrinterFont() && !fontData->isSystemFont()) {
292 advance = roundedAdvance;
293 offsetX = roundf(offsetX);
294 offsetY = roundf(offsetY);
297 // We special case spaces in two ways when applying word rounding.
298 // First, we round spaces to an adjusted width in all fonts.
299 // Second, in fixed-pitch fonts we ensure that all glyphs that
300 // match the width of the space glyph have the same width as the space glyph.
301 if (roundedAdvance == roundedSpaceWidth && (fontData->m_treatAsFixedPitch || glyph == fontData->m_spaceGlyph) &&
302 m_run.applyWordRounding())
303 advance = fontData->m_adjustedSpaceWidth;
305 if (hasExtraSpacing) {
306 // If we're a glyph with an advance, go ahead and add in letter-spacing.
307 // That way we weed out zero width lurkers. This behavior matches the fast text code path.
308 if (advance && m_font.letterSpacing())
309 advance += m_font.letterSpacing();
311 // Handle justification and word-spacing.
312 if (glyph == fontData->m_spaceGlyph) {
313 // Account for padding. WebCore uses space padding to justify text.
314 // We distribute the specified padding over the available spaces in the run.
316 // Use leftover padding if not evenly divisible by number of spaces.
317 if (m_padding < m_padPerSpace) {
318 advance += m_padding;
321 advance += m_padPerSpace;
322 m_padding -= m_padPerSpace;
326 // Account for word-spacing.
327 int characterIndex = spaceCharacters[k];
328 if (characterIndex > 0 && !Font::treatAsSpace(*m_run.data(characterIndex - 1)) && m_font.wordSpacing())
329 advance += m_font.wordSpacing();
333 // Deal with the float/integer impedance mismatch between CG and WebCore. "Words" (characters
334 // followed by a character defined by isRoundingHackCharacter()) are always an integer width.
335 // We adjust the width of the last character of a "word" to ensure an integer width.
336 // Force characters that are used to determine word boundaries for the rounding hack
337 // to be integer width, so the following words will start on an integer boundary.
338 int roundingHackIndex = roundingHackCharacters[k];
339 if (m_run.applyWordRounding() && roundingHackIndex != -1)
340 advance = ceilf(advance);
342 // Check to see if the next character is a "rounding hack character", if so, adjust the
343 // width so that the total run width will be on an integer boundary.
344 int position = m_currentCharacter + len;
345 bool lastGlyph = (k == glyphs.size() - 1) && (m_run.rtl() ? i == 0 : i == m_items.size() - 2) && (position >= m_end);
346 if ((m_run.applyWordRounding() && roundingHackWordBoundaries[k] != -1) ||
347 (m_run.applyRunRounding() && lastGlyph)) {
348 float totalWidth = m_runWidthSoFar + advance;
349 advance += ceilf(totalWidth) - totalWidth;
352 m_runWidthSoFar += advance;
354 // FIXME: We need to take the GOFFSETS for combining glyphs and store them in the glyph buffer
355 // as well, so that when the time comes to draw those glyphs, we can apply the appropriate
358 FloatSize size(offsetX, offsetY);
359 glyphBuffer->add(glyph, fontData, advance, &size);
362 // Mutate the glyph array to contain our altered advances.
363 if (m_computingOffsetPosition)
364 advances[k] = advance;
367 while (m_computingOffsetPosition && m_offsetX >= leftEdge && m_offsetX < m_runWidthSoFar) {
368 // The position is somewhere inside this run.
370 ScriptXtoCP(m_offsetX - leftEdge, clusters.size(), glyphs.size(), clusters.data(), visualAttributes.data(),
371 advances.data(), &item.a, &m_offsetPosition, &trailing);
372 if (trailing && m_includePartialGlyphs && m_offsetPosition < len - 1) {
373 m_offsetPosition += m_currentCharacter + m_items[i].iCharPos;
374 m_offsetX += m_run.rtl() ? -trailing : trailing;
376 m_computingOffsetPosition = false;
377 m_offsetPosition += m_currentCharacter + m_items[i].iCharPos;
378 if (trailing && m_includePartialGlyphs)
387 bool UniscribeController::shape(const UChar* str, int len, SCRIPT_ITEM item, const FontData* fontData,
388 Vector<WORD>& glyphs, Vector<WORD>& clusters,
389 Vector<SCRIPT_VISATTR>& visualAttributes)
393 HRESULT shapeResult = E_PENDING;
396 shapeResult = ScriptShape(hdc, fontData->scriptCache(), str, len, glyphs.size(), &item.a,
397 glyphs.data(), clusters.data(), visualAttributes.data(), &glyphCount);
398 if (shapeResult == E_PENDING) {
399 // The script cache isn't primed with enough info yet. We need to select our HFONT into
400 // a DC and pass the DC in to ScriptShape.
403 HFONT hfont = fontData->platformData().hfont();
404 oldFont = (HFONT)SelectObject(hdc, hfont);
405 } else if (shapeResult == E_OUTOFMEMORY) {
406 // Need to resize our buffers.
407 glyphs.resize(glyphs.size() * 2);
408 visualAttributes.resize(glyphs.size());
410 } while (shapeResult == E_PENDING || shapeResult == E_OUTOFMEMORY);
413 SelectObject(hdc, oldFont);
417 if (FAILED(shapeResult))
420 // FIXME: We need to do better than this. Falling back on the entire item is not good enough.
421 // We may still have missing glyphs even if we succeeded. We need to treat missing glyphs as
422 // a failure so that we will fall back to another font.
423 bool containsMissingGlyphs = false;
424 SCRIPT_FONTPROPERTIES* fontProperties = fontData->scriptFontProperties();
425 for (int i = 0; i < glyphCount; i++) {
426 WORD glyph = glyphs[i];
427 if (glyph == fontProperties->wgDefault) {
428 containsMissingGlyphs = true;
433 if (containsMissingGlyphs)
436 glyphs.resize(glyphCount);
437 visualAttributes.resize(glyphCount);