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