LibreOffice Module vcl (master)  1
CommonSalLayout.cxx
Go to the documentation of this file.
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3  * This file is part of the LibreOffice project.
4  *
5  * This Source Code Form is subject to the terms of the Mozilla Public
6  * License, v. 2.0. If a copy of the MPL was not distributed with this
7  * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8  *
9  * This file incorporates work covered by the following license notice:
10  *
11  * Licensed to the Apache Software Foundation (ASF) under one or more
12  * contributor license agreements. See the NOTICE file distributed
13  * with this work for additional information regarding copyright
14  * ownership. The ASF licenses this file to you under the Apache
15  * License, Version 2.0 (the "License"); you may not use this file
16  * except in compliance with the License. You may obtain a copy of
17  * the License at http://www.apache.org/licenses/LICENSE-2.0 .
18  */
19 
20 #include <sal/config.h>
21 
22 #include <sal/log.hxx>
23 #include <unotools/configmgr.hxx>
24 #include <o3tl/temporary.hxx>
25 
26 #include <vcl/unohelp.hxx>
27 #include <vcl/font/Feature.hxx>
29 
30 #include <ImplLayoutArgs.hxx>
31 #include <TextLayoutCache.hxx>
32 #include <fontselect.hxx>
33 #include <salgdi.hxx>
34 #include <sallayout.hxx>
35 
36 #include <com/sun/star/i18n/CharacterIteratorMode.hpp>
37 
38 #include <unicode/uchar.h>
39 #include <hb-ot.h>
40 #include <hb-graphite2.h>
41 
42 #include <memory>
43 
44 #if !HB_VERSION_ATLEAST(1, 1, 0)
45 // Disabled Unicode compatibility decomposition, see fdo#66715
46 static unsigned int unicodeDecomposeCompatibility(hb_unicode_funcs_t* /*ufuncs*/,
47  hb_codepoint_t /*u*/,
48  hb_codepoint_t* /*decomposed*/,
49  void* /*user_data*/)
50 {
51  return 0;
52 }
53 
54 static hb_unicode_funcs_t* getUnicodeFuncs()
55 {
56  static hb_unicode_funcs_t* ufuncs = hb_unicode_funcs_create(hb_icu_get_unicode_funcs());
57  hb_unicode_funcs_set_decompose_compatibility_func(ufuncs, unicodeDecomposeCompatibility, nullptr, nullptr);
58  return ufuncs;
59 }
60 #endif
61 
63  : m_GlyphItems(rFont)
64  , mpVertGlyphs(nullptr)
65  , mbFuzzing(utl::ConfigManager::IsFuzzing())
66 {
67 }
68 
70 {
71 }
72 
73 void GenericSalLayout::ParseFeatures(const OUString& aName)
74 {
75  vcl::font::FeatureParser aParser(aName);
76  const OUString& sLanguage = aParser.getLanguage();
77  if (!sLanguage.isEmpty())
78  msLanguage = OUStringToOString(sLanguage, RTL_TEXTENCODING_ASCII_US);
79 
80  for (auto const &rFeat : aParser.getFeatures())
81  {
82  hb_feature_t aFeature { rFeat.m_nTag, rFeat.m_nValue, rFeat.m_nStart, rFeat.m_nEnd };
83  maFeatures.push_back(aFeature);
84  }
85 }
86 
87 namespace {
88 
89 struct SubRun
90 {
91  int32_t mnMin;
92  int32_t mnEnd;
93  hb_script_t maScript;
94  hb_direction_t maDirection;
95 };
96 
97 }
98 
99 namespace {
100 #if U_ICU_VERSION_MAJOR_NUM >= 63
101  enum class VerticalOrientation {
102  Upright = U_VO_UPRIGHT,
103  Rotated = U_VO_ROTATED,
104  TransformedUpright = U_VO_TRANSFORMED_UPRIGHT,
105  TransformedRotated = U_VO_TRANSFORMED_ROTATED
106  };
107 #else
108  #include "VerticalOrientationData.cxx"
109 
110  // These must match the values in the file included above.
111  enum class VerticalOrientation {
112  Upright = 0,
113  Rotated = 1,
114  TransformedUpright = 2,
115  TransformedRotated = 3
116  };
117 #endif
118 
119  VerticalOrientation GetVerticalOrientation(sal_UCS4 cCh, const LanguageTag& rTag)
120  {
121  // Override orientation of fullwidth colon , semi-colon,
122  // and Bopomofo tonal marks.
123  if ((cCh == 0xff1a || cCh == 0xff1b
124  || cCh == 0x2ca || cCh == 0x2cb || cCh == 0x2c7 || cCh == 0x2d9)
125  && rTag.getLanguage() == "zh")
126  return VerticalOrientation::TransformedUpright;
127 
128 #if U_ICU_VERSION_MAJOR_NUM >= 63
129  int32_t nRet = u_getIntPropertyValue(cCh, UCHAR_VERTICAL_ORIENTATION);
130 #else
131  uint8_t nRet = 1;
132 
133  if (cCh < 0x10000)
134  {
136  [cCh & ((1 << kVerticalOrientationCharBits) - 1)];
137  }
138  else if (cCh < (kVerticalOrientationMaxPlane + 1) * 0x10000)
139  {
141  [(cCh & 0xffff) >> kVerticalOrientationCharBits]]
142  [cCh & ((1 << kVerticalOrientationCharBits) - 1)];
143  }
144  else
145  {
146  // Default value for unassigned
147  SAL_WARN("vcl.gdi", "Getting VerticalOrientation for codepoint outside Unicode range");
148  }
149 #endif
150 
151  return VerticalOrientation(nRet);
152  }
153 
154 } // namespace
155 
156 std::shared_ptr<vcl::text::TextLayoutCache> GenericSalLayout::CreateTextLayoutCache(OUString const& rString)
157 {
158  return std::make_shared<vcl::text::TextLayoutCache>(rString.getStr(), rString.getLength());
159 }
160 
162 {
163  SalLayoutGlyphs glyphs;
164  glyphs.AppendImpl(m_GlyphItems.clone());
165  return glyphs;
166 }
167 
168 void GenericSalLayout::SetNeedFallback(vcl::text::ImplLayoutArgs& rArgs, sal_Int32 nCharPos, bool bRightToLeft)
169 {
170  if (nCharPos < 0 || mbFuzzing)
171  return;
172 
173  using namespace ::com::sun::star;
174 
175  if (!mxBreak.is())
177 
178  lang::Locale aLocale(rArgs.maLanguageTag.getLocale());
179 
180  //if position nCharPos is missing in the font, grab the entire grapheme and
181  //mark all glyphs as missing so the whole thing is rendered with the same
182  //font
183  sal_Int32 nDone;
184  sal_Int32 nGraphemeEndPos =
185  mxBreak->nextCharacters(rArgs.mrStr, nCharPos, aLocale,
186  i18n::CharacterIteratorMode::SKIPCELL, 1, nDone);
187  // Safely advance nCharPos in case it is a non-BMP character.
188  rArgs.mrStr.iterateCodePoints(&nCharPos);
189  sal_Int32 nGraphemeStartPos =
190  mxBreak->previousCharacters(rArgs.mrStr, nCharPos, aLocale,
191  i18n::CharacterIteratorMode::SKIPCELL, 1, nDone);
192 
193  rArgs.AddFallbackRun(nGraphemeStartPos, nGraphemeEndPos, bRightToLeft);
194 }
195 
197 {
199 
200  if (rArgs.mpDXArray)
201  ApplyDXArray(rArgs.mpDXArray, rArgs.mnFlags);
202  else if (rArgs.mnLayoutWidth)
203  Justify(rArgs.mnLayoutWidth);
204  // apply asian kerning if the glyphs are not already formatted
205  else if ((rArgs.mnFlags & SalLayoutFlags::KerningAsian)
206  && !(rArgs.mnFlags & SalLayoutFlags::Vertical))
207  ApplyAsianKerning(rArgs.mrStr);
208 }
209 
210 void GenericSalLayout::DrawText(SalGraphics& rSalGraphics) const
211 {
212  //call platform dependent DrawText functions
213  rSalGraphics.DrawTextLayout( *this );
214 }
215 
216 // Find if the nominal glyph of the character is an input to “vert” feature.
217 // We don’t check for a specific script or language as it shouldn’t matter
218 // here; if the glyph would be the result from applying “vert” for any
219 // script/language then we want to always treat it as upright glyph.
221 {
222  hb_codepoint_t nGlyphIndex = 0;
223  hb_font_t *pHbFont = GetFont().GetHbFont();
224  if (!hb_font_get_glyph(pHbFont, aChar, aVariationSelector, &nGlyphIndex))
225  return false;
226 
227  if (!mpVertGlyphs)
228  {
229  hb_face_t* pHbFace = hb_font_get_face(pHbFont);
230  mpVertGlyphs = hb_set_create();
231 
232  // Find all GSUB lookups for “vert” feature.
233  hb_set_t* pLookups = hb_set_create();
234  hb_tag_t const pFeatures[] = { HB_TAG('v','e','r','t'), HB_TAG_NONE };
235  hb_ot_layout_collect_lookups(pHbFace, HB_OT_TAG_GSUB, nullptr, nullptr, pFeatures, pLookups);
236  if (!hb_set_is_empty(pLookups))
237  {
238  // Find the output glyphs in each lookup (i.e. the glyphs that
239  // would result from applying this lookup).
240  hb_codepoint_t nIdx = HB_SET_VALUE_INVALID;
241  while (hb_set_next(pLookups, &nIdx))
242  {
243  hb_set_t* pGlyphs = hb_set_create();
244  hb_ot_layout_lookup_collect_glyphs(pHbFace, HB_OT_TAG_GSUB, nIdx,
245  nullptr, // glyphs before
246  pGlyphs, // glyphs input
247  nullptr, // glyphs after
248  nullptr); // glyphs out
249  hb_set_union(mpVertGlyphs, pGlyphs);
250  }
251  }
252  }
253 
254  return hb_set_has(mpVertGlyphs, nGlyphIndex) != 0;
255 }
256 
258 {
259  // No need to touch m_GlyphItems at all for an empty string.
260  if (rArgs.mnEndCharPos - rArgs.mnMinCharPos <= 0)
261  return true;
262 
263  if (pGlyphs)
264  {
265  // Work with pre-computed glyph items.
266  m_GlyphItems = *pGlyphs;
267  for(const GlyphItem& item : m_GlyphItems)
268  if(!item.glyphId())
269  SetNeedFallback(rArgs, item.charPos(), item.IsRTLGlyph());
270  // Some flags are set as a side effect of text layout, restore them here.
271  rArgs.mnFlags |= pGlyphs->mnFlags;
272  return true;
273  }
274 
275  hb_font_t *pHbFont = GetFont().GetHbFont();
276  bool isGraphite = GetFont().IsGraphiteFont();
277 
278  int nGlyphCapacity = 2 * (rArgs.mnEndCharPos - rArgs.mnMinCharPos);
279  m_GlyphItems.reserve(nGlyphCapacity);
280 
281  const int nLength = rArgs.mrStr.getLength();
282  const sal_Unicode *pStr = rArgs.mrStr.getStr();
283 
284  std::optional<vcl::text::TextLayoutCache> oNewScriptRun;
285  vcl::text::TextLayoutCache const* pTextLayout;
286  if (rArgs.m_pTextLayoutCache)
287  {
288  pTextLayout = rArgs.m_pTextLayoutCache; // use cache!
289  }
290  else
291  {
292  oNewScriptRun.emplace(pStr, rArgs.mnEndCharPos);
293  pTextLayout = &*oNewScriptRun;
294  }
295 
296  // nBaseOffset is used to align vertical text to the center of rotated
297  // horizontal text. That is the offset from original baseline to
298  // the center of EM box. Maybe we can use OpenType base table to improve this
299  // in the future.
300  DeviceCoordinate nBaseOffset = 0;
301  if (rArgs.mnFlags & SalLayoutFlags::Vertical)
302  {
303  hb_font_extents_t extents;
304  if (hb_font_get_h_extents(pHbFont, &extents))
305  nBaseOffset = ( extents.ascender + extents.descender ) / 2;
306  }
307 
308  hb_buffer_t* pHbBuffer = hb_buffer_create();
309  hb_buffer_pre_allocate(pHbBuffer, nGlyphCapacity);
310 #if !HB_VERSION_ATLEAST(1, 1, 0)
311  static hb_unicode_funcs_t* pHbUnicodeFuncs = getUnicodeFuncs();
312  hb_buffer_set_unicode_funcs(pHbBuffer, pHbUnicodeFuncs);
313 #endif
314 
315  const FontSelectPattern& rFontSelData = GetFont().GetFontSelectPattern();
317  {
318  SAL_INFO("vcl.harfbuzz", "Disabling kerning for font: " << rFontSelData.maTargetName);
319  maFeatures.push_back({ HB_TAG('k','e','r','n'), 0, 0, static_cast<unsigned int>(-1) });
320  }
321 
322  if (rFontSelData.GetPitch() == PITCH_FIXED)
323  {
324  SAL_INFO("vcl.harfbuzz", "Disabling ligatures for font: " << rFontSelData.maTargetName);
325  maFeatures.push_back({ HB_TAG('l','i','g','a'), 0, 0, static_cast<unsigned int>(-1) });
326  }
327 
328  ParseFeatures(rFontSelData.maTargetName);
329 
330  double nXScale = 0;
331  double nYScale = 0;
332  GetFont().GetScale(&nXScale, &nYScale);
333 
334  Point aCurrPos(0, 0);
335  while (true)
336  {
337  int nBidiMinRunPos, nBidiEndRunPos;
338  bool bRightToLeft;
339  if (!rArgs.GetNextRun(&nBidiMinRunPos, &nBidiEndRunPos, &bRightToLeft))
340  break;
341 
342  // Find script subruns.
343  std::vector<SubRun> aSubRuns;
344  int nCurrentPos = nBidiMinRunPos;
345  size_t k = 0;
346  for (; k < pTextLayout->runs.size(); ++k)
347  {
348  vcl::text::Run const& rRun(pTextLayout->runs[k]);
349  if (rRun.nStart <= nCurrentPos && nCurrentPos < rRun.nEnd)
350  {
351  break;
352  }
353  }
354 
355  if (isGraphite)
356  {
357  hb_script_t aScript = hb_icu_script_to_script(pTextLayout->runs[k].nCode);
358  aSubRuns.push_back({ nBidiMinRunPos, nBidiEndRunPos, aScript, bRightToLeft ? HB_DIRECTION_RTL : HB_DIRECTION_LTR });
359  }
360  else
361  {
362  while (nCurrentPos < nBidiEndRunPos && k < pTextLayout->runs.size())
363  {
364  int32_t nMinRunPos = nCurrentPos;
365  int32_t nEndRunPos = std::min(pTextLayout->runs[k].nEnd, nBidiEndRunPos);
366  hb_direction_t aDirection = bRightToLeft ? HB_DIRECTION_RTL : HB_DIRECTION_LTR;
367  hb_script_t aScript = hb_icu_script_to_script(pTextLayout->runs[k].nCode);
368  // For vertical text, further divide the runs based on character
369  // orientation.
370  if (rArgs.mnFlags & SalLayoutFlags::Vertical)
371  {
372  sal_Int32 nIdx = nMinRunPos;
373  while (nIdx < nEndRunPos)
374  {
375  sal_Int32 nPrevIdx = nIdx;
376  sal_UCS4 aChar = rArgs.mrStr.iterateCodePoints(&nIdx);
377  VerticalOrientation aVo = GetVerticalOrientation(aChar, rArgs.maLanguageTag);
378 
379  sal_UCS4 aVariationSelector = 0;
380  if (nIdx < nEndRunPos)
381  {
382  sal_Int32 nNextIdx = nIdx;
383  sal_UCS4 aNextChar = rArgs.mrStr.iterateCodePoints(&nNextIdx);
384  if (u_hasBinaryProperty(aNextChar, UCHAR_VARIATION_SELECTOR))
385  {
386  nIdx = nNextIdx;
387  aVariationSelector = aNextChar;
388  }
389  }
390 
391  // Charters with U and Tu vertical orientation should
392  // be shaped in vertical direction. But characters
393  // with Tr should be shaped in vertical direction
394  // only if they have vertical alternates, otherwise
395  // they should be shaped in horizontal direction
396  // and then rotated.
397  // See http://unicode.org/reports/tr50/#vo
398  if (aVo == VerticalOrientation::Upright ||
399  aVo == VerticalOrientation::TransformedUpright ||
400  (aVo == VerticalOrientation::TransformedRotated &&
401  HasVerticalAlternate(aChar, aVariationSelector)))
402  {
403  aDirection = HB_DIRECTION_TTB;
404  }
405  else
406  {
407  aDirection = bRightToLeft ? HB_DIRECTION_RTL : HB_DIRECTION_LTR;
408  }
409 
410  if (aSubRuns.empty() || aSubRuns.back().maDirection != aDirection)
411  aSubRuns.push_back({ nPrevIdx, nIdx, aScript, aDirection });
412  else
413  aSubRuns.back().mnEnd = nIdx;
414  }
415  }
416  else
417  {
418  aSubRuns.push_back({ nMinRunPos, nEndRunPos, aScript, aDirection });
419  }
420 
421  nCurrentPos = nEndRunPos;
422  ++k;
423  }
424  }
425 
426  // RTL subruns should be reversed to ensure that final glyph order is
427  // correct.
428  if (bRightToLeft)
429  std::reverse(aSubRuns.begin(), aSubRuns.end());
430 
431  for (const auto& aSubRun : aSubRuns)
432  {
433  hb_buffer_clear_contents(pHbBuffer);
434 
435  const int nMinRunPos = aSubRun.mnMin;
436  const int nEndRunPos = aSubRun.mnEnd;
437  const int nRunLen = nEndRunPos - nMinRunPos;
438 
439  OString sLanguage = msLanguage;
440  if (sLanguage.isEmpty())
441  sLanguage = OUStringToOString(rArgs.maLanguageTag.getBcp47(), RTL_TEXTENCODING_ASCII_US);
442 
443  int nHbFlags = HB_BUFFER_FLAGS_DEFAULT;
444  if (nMinRunPos == 0)
445  nHbFlags |= HB_BUFFER_FLAG_BOT; /* Beginning-of-text */
446  if (nEndRunPos == nLength)
447  nHbFlags |= HB_BUFFER_FLAG_EOT; /* End-of-text */
448 
449  hb_buffer_set_direction(pHbBuffer, aSubRun.maDirection);
450  hb_buffer_set_script(pHbBuffer, aSubRun.maScript);
451  hb_buffer_set_language(pHbBuffer, hb_language_from_string(sLanguage.getStr(), -1));
452  hb_buffer_set_flags(pHbBuffer, static_cast<hb_buffer_flags_t>(nHbFlags));
453  hb_buffer_add_utf16(
454  pHbBuffer, reinterpret_cast<uint16_t const *>(pStr), nLength,
455  nMinRunPos, nRunLen);
456  hb_buffer_set_cluster_level(pHbBuffer, HB_BUFFER_CLUSTER_LEVEL_MONOTONE_CHARACTERS);
457 
458  // The shapers that we want HarfBuzz to use, in the order of
459  // preference. The coretext_aat shaper is available only on macOS,
460  // but there is no harm in always including it, HarfBuzz will
461  // ignore unavailable shapers.
462  const char*const pHbShapers[] = { "graphite2", "coretext_aat", "ot", "fallback", nullptr };
463  bool ok = hb_shape_full(pHbFont, pHbBuffer, maFeatures.data(), maFeatures.size(), pHbShapers);
464  assert(ok);
465  (void) ok;
466 
467  int nRunGlyphCount = hb_buffer_get_length(pHbBuffer);
468  hb_glyph_info_t *pHbGlyphInfos = hb_buffer_get_glyph_infos(pHbBuffer, nullptr);
469  hb_glyph_position_t *pHbPositions = hb_buffer_get_glyph_positions(pHbBuffer, nullptr);
470 
471  for (int i = 0; i < nRunGlyphCount; ++i) {
472  int32_t nGlyphIndex = pHbGlyphInfos[i].codepoint;
473  int32_t nCharPos = pHbGlyphInfos[i].cluster;
474  int32_t nCharCount = 0;
475  bool bInCluster = false;
476  bool bClusterStart = false;
477 
478  // Find the number of characters that make up this glyph.
479  if (!bRightToLeft)
480  {
481  // If the cluster is the same as previous glyph, then this
482  // already consumed, skip.
483  if (i > 0 && pHbGlyphInfos[i].cluster == pHbGlyphInfos[i - 1].cluster)
484  {
485  nCharCount = 0;
486  bInCluster = true;
487  }
488  else
489  {
490  // Find the next glyph with a different cluster, or the
491  // end of text.
492  int j = i;
493  int32_t nNextCharPos = nCharPos;
494  while (nNextCharPos == nCharPos && j < nRunGlyphCount)
495  nNextCharPos = pHbGlyphInfos[j++].cluster;
496 
497  if (nNextCharPos == nCharPos)
498  nNextCharPos = nEndRunPos;
499  nCharCount = nNextCharPos - nCharPos;
500  if ((i == 0 || pHbGlyphInfos[i].cluster != pHbGlyphInfos[i - 1].cluster) &&
501  (i < nRunGlyphCount - 1 && pHbGlyphInfos[i].cluster == pHbGlyphInfos[i + 1].cluster))
502  bClusterStart = true;
503  }
504  }
505  else
506  {
507  // If the cluster is the same as previous glyph, then this
508  // will be consumed later, skip.
509  if (i < nRunGlyphCount - 1 && pHbGlyphInfos[i].cluster == pHbGlyphInfos[i + 1].cluster)
510  {
511  nCharCount = 0;
512  bInCluster = true;
513  }
514  else
515  {
516  // Find the previous glyph with a different cluster, or
517  // the end of text.
518  int j = i;
519  int32_t nNextCharPos = nCharPos;
520  while (nNextCharPos == nCharPos && j >= 0)
521  nNextCharPos = pHbGlyphInfos[j--].cluster;
522 
523  if (nNextCharPos == nCharPos)
524  nNextCharPos = nEndRunPos;
525  nCharCount = nNextCharPos - nCharPos;
526  if ((i == nRunGlyphCount - 1 || pHbGlyphInfos[i].cluster != pHbGlyphInfos[i + 1].cluster) &&
527  (i > 0 && pHbGlyphInfos[i].cluster == pHbGlyphInfos[i - 1].cluster))
528  bClusterStart = true;
529  }
530  }
531 
532  // if needed request glyph fallback by updating LayoutArgs
533  if (!nGlyphIndex)
534  {
535  SetNeedFallback(rArgs, nCharPos, bRightToLeft);
537  continue;
538  }
539 
540  GlyphItemFlags nGlyphFlags = GlyphItemFlags::NONE;
541  if (bRightToLeft)
542  nGlyphFlags |= GlyphItemFlags::IS_RTL_GLYPH;
543 
544  if (bClusterStart)
545  nGlyphFlags |= GlyphItemFlags::IS_CLUSTER_START;
546 
547  if (bInCluster)
548  nGlyphFlags |= GlyphItemFlags::IS_IN_CLUSTER;
549 
550  sal_UCS4 aChar
551  = rArgs.mrStr.iterateCodePoints(&o3tl::temporary(sal_Int32(nCharPos)), 0);
552 
553  if (u_getIntPropertyValue(aChar, UCHAR_GENERAL_CATEGORY) == U_NON_SPACING_MARK)
554  nGlyphFlags |= GlyphItemFlags::IS_DIACRITIC;
555 
556  if (u_isUWhiteSpace(aChar))
557  nGlyphFlags |= GlyphItemFlags::IS_SPACING;
558 
559  if (aSubRun.maScript == HB_SCRIPT_ARABIC &&
560  HB_DIRECTION_IS_BACKWARD(aSubRun.maDirection) &&
561  !(nGlyphFlags & GlyphItemFlags::IS_SPACING))
562  {
563  nGlyphFlags |= GlyphItemFlags::ALLOW_KASHIDA;
565  }
566 
567  DeviceCoordinate nAdvance, nXOffset, nYOffset;
568  if (aSubRun.maDirection == HB_DIRECTION_TTB)
569  {
570  nGlyphFlags |= GlyphItemFlags::IS_VERTICAL;
571 
572  nAdvance = -pHbPositions[i].y_advance;
573  nXOffset = -pHbPositions[i].y_offset;
574  nYOffset = -pHbPositions[i].x_offset - nBaseOffset;
575  }
576  else
577  {
578  nAdvance = pHbPositions[i].x_advance;
579  nXOffset = pHbPositions[i].x_offset;
580  nYOffset = -pHbPositions[i].y_offset;
581  }
582 
583  nAdvance = std::lround(nAdvance * nXScale);
584  nXOffset = std::lround(nXOffset * nXScale);
585  nYOffset = std::lround(nYOffset * nYScale);
586 
587  Point aNewPos(aCurrPos.X() + nXOffset, aCurrPos.Y() + nYOffset);
588  const GlyphItem aGI(nCharPos, nCharCount, nGlyphIndex, aNewPos, nGlyphFlags,
589  nAdvance, nXOffset);
590  m_GlyphItems.push_back(aGI);
591 
592  aCurrPos.AdjustX(nAdvance );
593  }
594  }
595  }
596 
597  hb_buffer_destroy(pHbBuffer);
598 
599  // Some flags are set as a side effect of text layout, save them here.
601  m_GlyphItems.mnFlags = rArgs.mnFlags;
602 
603  return true;
604 }
605 
606 void GenericSalLayout::GetCharWidths(std::vector<DeviceCoordinate>& rCharWidths) const
607 {
608  const int nCharCount = mnEndCharPos - mnMinCharPos;
609 
610  rCharWidths.clear();
611  rCharWidths.resize(nCharCount, 0);
612 
613  for (auto const& aGlyphItem : m_GlyphItems)
614  {
615  const int nIndex = aGlyphItem.charPos() - mnMinCharPos;
616  if (nIndex >= nCharCount)
617  continue;
618  rCharWidths[nIndex] += aGlyphItem.m_nNewWidth;
619  }
620 }
621 
622 // A note on how Kashida justification is implemented (because it took me 5
623 // years to figure it out):
624 // The decision to insert Kashidas, where and how much is taken by Writer.
625 // This decision is communicated to us in a very indirect way; by increasing
626 // the width of the character after which Kashidas should be inserted by the
627 // desired amount.
628 //
629 // Writer eventually calls IsKashidaPosValid() to check whether it can insert a
630 // Kashida between two characters or not.
631 //
632 // Here we do:
633 // - In LayoutText() set KashidaJustification flag based on text script.
634 // - In ApplyDXArray():
635 // * Check the above flag to decide whether to insert Kashidas or not.
636 // * For any RTL glyph that has DX adjustment, insert enough Kashidas to
637 // fill in the added space.
638 
640 {
641  int nCharCount = mnEndCharPos - mnMinCharPos;
642  std::vector<DeviceCoordinate> aOldCharWidths;
643  std::unique_ptr<DeviceCoordinate[]> const pNewCharWidths(new DeviceCoordinate[nCharCount]);
644 
645  // Get the natural character widths (i.e. before applying DX adjustments).
646  GetCharWidths(aOldCharWidths);
647 
648  // Calculate the character widths after DX adjustments.
649  for (int i = 0; i < nCharCount; ++i)
650  {
651  if (i == 0)
652  pNewCharWidths[i] = pDXArray[i];
653  else
654  pNewCharWidths[i] = pDXArray[i] - pDXArray[i - 1];
655  }
656 
657  bool bKashidaJustify = false;
658  DeviceCoordinate nKashidaWidth = 0;
659  hb_codepoint_t nKashidaIndex = 0;
660  if (nLayoutFlags & SalLayoutFlags::KashidaJustification)
661  {
662  hb_font_t *pHbFont = GetFont().GetHbFont();
663  // Find Kashida glyph width and index.
664  if (hb_font_get_glyph(pHbFont, 0x0640, 0, &nKashidaIndex))
665  nKashidaWidth = GetFont().GetKashidaWidth();
666  bKashidaJustify = nKashidaWidth != 0;
667  }
668 
669  // Map of Kashida insertion points (in the glyph items vector) and the
670  // requested width.
671  std::map<size_t, DeviceCoordinate> pKashidas;
672 
673  // The accumulated difference in X position.
674  DeviceCoordinate nDelta = 0;
675 
676  // Apply the DX adjustments to glyph positions and widths.
677  size_t i = 0;
678  while (i < m_GlyphItems.size())
679  {
680  // Accumulate the width difference for all characters corresponding to
681  // this glyph.
682  int nCharPos = m_GlyphItems[i].charPos() - mnMinCharPos;
683  DeviceCoordinate nDiff = 0;
684  for (int j = 0; j < m_GlyphItems[i].charCount(); j++)
685  nDiff += pNewCharWidths[nCharPos + j] - aOldCharWidths[nCharPos + j];
686 
687  if (!m_GlyphItems[i].IsRTLGlyph())
688  {
689  // Adjust the width and position of the first (leftmost) glyph in
690  // the cluster.
691  m_GlyphItems[i].m_nNewWidth += nDiff;
692  m_GlyphItems[i].m_aLinearPos.AdjustX(nDelta);
693 
694  // Adjust the position of the rest of the glyphs in the cluster.
695  while (++i < m_GlyphItems.size())
696  {
697  if (!m_GlyphItems[i].IsInCluster())
698  break;
699  m_GlyphItems[i].m_aLinearPos.AdjustX(nDelta);
700  }
701  }
702  else if (m_GlyphItems[i].IsInCluster())
703  {
704  // RTL glyph in the middle of the cluster, will be handled in the
705  // loop below.
706  i++;
707  }
708  else
709  {
710  // Adjust the width and position of the first (rightmost) glyph in
711  // the cluster.
712  // For RTL, we put all the adjustment to the left of the glyph.
713  m_GlyphItems[i].m_nNewWidth += nDiff;
714  m_GlyphItems[i].m_aLinearPos.AdjustX(nDelta + nDiff);
715 
716  // Adjust the X position of all glyphs in the cluster.
717  size_t j = i;
718  while (j > 0)
719  {
720  --j;
721  if (!m_GlyphItems[j].IsInCluster())
722  break;
723  m_GlyphItems[j].m_aLinearPos.AdjustX(nDelta + nDiff);
724  }
725 
726  // If this glyph is Kashida-justifiable, then mark this as a
727  // Kashida position. Since this must be a RTL glyph, we mark the
728  // last glyph in the cluster not the first as this would be the
729  // base glyph.
730  if (bKashidaJustify && m_GlyphItems[i].AllowKashida() &&
731  nDiff > m_GlyphItems[i].charCount()) // Rounding errors, 1 pixel per character!
732  {
733  pKashidas[i] = nDiff;
734  // Move any non-spacing marks attached to this cluster as well.
735  // Looping backward because this is RTL glyph.
736  while (j > 0)
737  {
738  if (!m_GlyphItems[j].IsDiacritic())
739  break;
740  m_GlyphItems[j--].m_aLinearPos.AdjustX(nDiff);
741  }
742  }
743  i++;
744  }
745 
746  // Increment the delta, the loop above makes sure we do so only once
747  // for every character (cluster) not for every glyph (otherwise we
748  // would apply it multiple times for each glyphs belonging to the same
749  // character which is wrong since DX adjustments are character based).
750  nDelta += nDiff;
751  }
752 
753  // Insert Kashida glyphs.
754  if (!bKashidaJustify || pKashidas.empty())
755  return;
756 
757  size_t nInserted = 0;
758  for (auto const& pKashida : pKashidas)
759  {
760  auto pGlyphIter = m_GlyphItems.begin() + nInserted + pKashida.first;
761 
762  // The total Kashida width.
763  DeviceCoordinate nTotalWidth = pKashida.second;
764 
765  // Number of times to repeat each Kashida.
766  int nCopies = 1;
767  if (nTotalWidth > nKashidaWidth)
768  nCopies = nTotalWidth / nKashidaWidth;
769 
770  // See if we can improve the fit by adding an extra Kashidas and
771  // squeezing them together a bit.
772  DeviceCoordinate nOverlap = 0;
773  DeviceCoordinate nShortfall = nTotalWidth - nKashidaWidth * nCopies;
774  if (nShortfall > 0)
775  {
776  ++nCopies;
777  DeviceCoordinate nExcess = nCopies * nKashidaWidth - nTotalWidth;
778  if (nExcess > 0)
779  nOverlap = nExcess / (nCopies - 1);
780  }
781 
782  Point aPos(pGlyphIter->m_aLinearPos.getX() - nTotalWidth, 0);
783  int nCharPos = pGlyphIter->charPos();
785  while (nCopies--)
786  {
787  GlyphItem aKashida(nCharPos, 0, nKashidaIndex, aPos, nFlags, nKashidaWidth, 0);
788  pGlyphIter = m_GlyphItems.insert(pGlyphIter, aKashida);
789  aPos.AdjustX(nKashidaWidth );
790  aPos.AdjustX( -nOverlap );
791  ++pGlyphIter;
792  ++nInserted;
793  }
794  }
795 }
796 
797 bool GenericSalLayout::IsKashidaPosValid(int nCharPos) const
798 {
799  for (auto pIter = m_GlyphItems.begin(); pIter != m_GlyphItems.end(); ++pIter)
800  {
801  if (pIter->charPos() == nCharPos)
802  {
803  // The position is the first glyph, this would happen if we
804  // changed the text styling in the middle of a word. Since we don’t
805  // do ligatures across layout engine instances, this can’t be a
806  // ligature so it should be fine.
807  if (pIter == m_GlyphItems.begin())
808  return true;
809 
810  // If the character is not supported by this layout, return false
811  // so that fallback layouts would be checked for it.
812  if (pIter->glyphId() == 0)
813  break;
814 
815  // Search backwards for previous glyph belonging to a different
816  // character. We are looking backwards because we are dealing with
817  // RTL glyphs, which will be in visual order.
818  for (auto pPrev = pIter - 1; pPrev != m_GlyphItems.begin(); --pPrev)
819  {
820  if (pPrev->charPos() != nCharPos)
821  {
822  // Check if the found glyph belongs to the next character,
823  // otherwise the current glyph will be a ligature which is
824  // invalid kashida position.
825  if (pPrev->charPos() == (nCharPos + 1))
826  return true;
827  break;
828  }
829  }
830  }
831  }
832 
833  return false;
834 }
835 
836 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
GenericSalLayout(LogicalFontInstance &)
OUString const & getLanguage() const
sal_Int32 nIndex
void GetCharWidths(std::vector< DeviceCoordinate > &rCharWidths) const
static hb_unicode_funcs_t * getUnicodeFuncs()
vcl::text::TextLayoutCache const * m_pTextLayoutCache
std::vector< vcl::text::Run > runs
virtual void DrawTextLayout(const GenericSalLayout &)=0
hb_set_t * mpVertGlyphs
Definition: sallayout.hxx:154
sal_uInt32 sal_UCS4
Definition: vclenum.hxx:192
size_t mnEnd
static const uint8_t sVerticalOrientationValues[34][128]
bool LayoutText(vcl::text::ImplLayoutArgs &, const SalLayoutGlyphsImpl *) final override
const OUString & getBcp47(bool bResolveSystem=true) const
void Justify(DeviceCoordinate nNewWidth)
Definition: sallayout.cxx:281
hb_font_t * GetHbFont()
bool GetNextRun(int *nMinRunPos, int *nEndRunPos, bool *bRTL)
LogicalFontInstance & GetFont() const
Definition: sallayout.hxx:117
const css::lang::Locale & getLocale(bool bResolveSystem=true) const
void AppendImpl(SalLayoutGlyphsImpl *pImpl)
SalLayoutFlags mnFlags
const DeviceCoordinate * mpDXArray
GlyphItemFlags
sal_uInt16 sal_Unicode
bool HasVerticalAlternate(sal_UCS4 aChar, sal_UCS4 aNextChar)
OUString getLanguage() const
void GetScale(double *nXScale, double *nYScale)
~GenericSalLayout() override
void ApplyDXArray(const DeviceCoordinate *, SalLayoutFlags nLayoutFlags)
OString OUStringToOString(std::u16string_view str, ConnectionSettings const *settings)
void ApplyAsianKerning(const OUString &rStr)
Definition: sallayout.cxx:400
VerticalOrientation
SalLayoutGlyphsImpl m_GlyphItems
Definition: sallayout.hxx:149
virtual void AdjustLayout(vcl::text::ImplLayoutArgs &)
Definition: sallayout.cxx:144
int mnEndCharPos
Definition: vcllayout.hxx:112
int i
css::drawing::Direction3D aDirection
PITCH_FIXED
OString msLanguage
Definition: sallayout.hxx:151
static const uint8_t sVerticalOrientationPages[4][512]
tools::Long DeviceCoordinate
static std::shared_ptr< vcl::text::TextLayoutCache > CreateTextLayoutCache(OUString const &)
static const uint8_t sVerticalOrientationPlanes[16]
std::vector< FeatureSetting > const & getFeatures() const
static unsigned int unicodeDecomposeCompatibility(hb_unicode_funcs_t *, hb_codepoint_t, hb_codepoint_t *, void *)
constexpr T & temporary(T &&x)
const FontSelectPattern & GetFontSelectPattern() const
void AdjustLayout(vcl::text::ImplLayoutArgs &) final override
SalLayoutGlyphs GetGlyphs() const final override
std::vector< hb_feature_t > maFeatures
Definition: sallayout.hxx:152
const bool mbFuzzing
Definition: sallayout.hxx:155
#define kVerticalOrientationMaxPlane
#define SAL_INFO(area, stream)
void SetNeedFallback(vcl::text::ImplLayoutArgs &, sal_Int32, bool)
void DrawText(SalGraphics &) const final override
css::uno::Reference< css::i18n::XBreakIterator > mxBreak
Definition: sallayout.hxx:147
bool IsKashidaPosValid(int nCharPos) const final override
#define SAL_WARN(area, stream)
void AddFallbackRun(int nMinRunPos, int nEndRunPos, bool bRTL)
int mnMinCharPos
Definition: vcllayout.hxx:111
sal_Int32 nLength
FontPitch GetPitch() const
VCL_DLLPUBLIC css::uno::Reference< css::i18n::XBreakIterator > CreateBreakIterator()
Definition: unohelp.cxx:37
SalLayoutGlyphsImpl * clone() const
DeviceCoordinate mnLayoutWidth
void ParseFeatures(const OUString &name)
OUString maTargetName
Definition: fontselect.hxx:57
#define kVerticalOrientationCharBits
SalLayoutFlags
typedef void(CALLTYPE *GetFuncDataPtr)(sal_uInt16 &nNo