OpenTTD
string_osx.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of OpenTTD.
3  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4  * OpenTTD 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.
5  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6  */
7 
10 #include "../../stdafx.h"
11 #include "string_osx.h"
12 #include "../../string_func.h"
13 #include "../../strings_func.h"
14 #include "../../table/control_codes.h"
15 #include "../../fontcache.h"
16 #include "macos.h"
17 
18 #include <CoreFoundation/CoreFoundation.h>
19 
20 
21 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
22 
26 
27 
32 private:
34  ptrdiff_t length;
35  const FontMap& font_map;
36 
38 
39  CFIndex cur_offset = 0;
40 
41 public:
44  private:
45  std::vector<GlyphID> glyphs;
46  std::vector<float> positions;
47  std::vector<int> glyph_to_char;
48 
49  int total_advance = 0;
50  Font *font;
51 
52  public:
53  CoreTextVisualRun(CTRunRef run, Font *font, const CoreTextParagraphLayoutFactory::CharType *buff);
54  CoreTextVisualRun(CoreTextVisualRun &&other) = default;
55 
56  const GlyphID *GetGlyphs() const override { return &this->glyphs[0]; }
57  const float *GetPositions() const override { return &this->positions[0]; }
58  const int *GetGlyphToCharMap() const override { return &this->glyph_to_char[0]; }
59 
60  const Font *GetFont() const override { return this->font; }
61  int GetLeading() const override { return this->font->fc->GetHeight(); }
62  int GetGlyphCount() const override { return (int)this->glyphs.size(); }
63  int GetAdvance() const { return this->total_advance; }
64  };
65 
67  class CoreTextLine : public std::vector<CoreTextVisualRun>, public ParagraphLayouter::Line {
68  public:
70  {
71  CFArrayRef runs = CTLineGetGlyphRuns(line.get());
72  for (CFIndex i = 0; i < CFArrayGetCount(runs); i++) {
73  CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(runs, i);
74 
75  /* Extract font information for this run. */
76  CFRange chars = CTRunGetStringRange(run);
77  auto map = fontMapping.begin();
78  while (map < fontMapping.end() - 1 && map->first <= chars.location) map++;
79 
80  this->emplace_back(run, map->second, buff);
81  }
82  }
83 
84  int GetLeading() const override;
85  int GetWidth() const override;
86  int CountRuns() const override { return this->size(); }
87  const VisualRun &GetVisualRun(int run) const override { return this->at(run); }
88 
89  int GetInternalCharLength(WChar c) const override
90  {
91  /* CoreText uses UTF-16 internally which means we need to account for surrogate pairs. */
92  return c >= 0x010000U ? 2 : 1;
93  }
94  };
95 
96  CoreTextParagraphLayout(CFAutoRelease<CTTypesetterRef> typesetter, const CoreTextParagraphLayoutFactory::CharType *buffer, ptrdiff_t len, const FontMap &fontMapping) : text_buffer(buffer), length(len), font_map(fontMapping), typesetter(std::move(typesetter))
97  {
98  this->Reflow();
99  }
100 
101  void Reflow() override
102  {
103  this->cur_offset = 0;
104  }
105 
106  std::unique_ptr<const Line> NextLine(int max_width) override;
107 };
108 
109 
111 static CGFloat SpriteFontGetWidth(void *ref_con)
112 {
113  FontSize fs = (FontSize)((size_t)ref_con >> 24);
114  WChar c = (WChar)((size_t)ref_con & 0xFFFFFF);
115 
116  return GetGlyphWidth(fs, c);
117 }
118 
119 static CTRunDelegateCallbacks _sprite_font_callback = {
120  kCTRunDelegateCurrentVersion, nullptr, nullptr, nullptr,
122 };
123 
125 {
126  if (!MacOSVersionIsAtLeast(10, 5, 0)) return nullptr;
127 
128  /* Can't layout an empty string. */
129  ptrdiff_t length = buff_end - buff;
130  if (length == 0) return nullptr;
131 
132  /* Can't layout our in-built sprite fonts. */
133  for (const auto &i : fontMapping) {
134  if (i.second->fc->IsBuiltInFont()) return nullptr;
135  }
136 
137  /* Make attributed string with embedded font information. */
138  CFAutoRelease<CFMutableAttributedStringRef> str(CFAttributedStringCreateMutable(kCFAllocatorDefault, 0));
139  CFAttributedStringBeginEditing(str.get());
140 
141  CFAutoRelease<CFStringRef> base(CFStringCreateWithCharactersNoCopy(kCFAllocatorDefault, buff, length, kCFAllocatorNull));
142  CFAttributedStringReplaceString(str.get(), CFRangeMake(0, 0), base.get());
143 
144  /* Apply font and colour ranges to our string. This is important to make sure
145  * that we get proper glyph boundaries on style changes. */
146  int last = 0;
147  for (const auto &i : fontMapping) {
148  if (i.first - last == 0) continue;
149 
150  if (!_font_cache[i.second->fc->GetSize()]) {
151  /* Cache font information. */
152  CFAutoRelease<CFStringRef> font_name(CFStringCreateWithCString(kCFAllocatorDefault, i.second->fc->GetFontName(), kCFStringEncodingUTF8));
153  _font_cache[i.second->fc->GetSize()].reset(CTFontCreateWithName(font_name.get(), i.second->fc->GetFontSize(), nullptr));
154  }
155  CFAttributedStringSetAttribute(str.get(), CFRangeMake(last, i.first - last), kCTFontAttributeName, _font_cache[i.second->fc->GetSize()].get());
156 
157  CGColorRef color = CGColorCreateGenericGray((uint8)i.second->colour / 255.0f, 1.0f); // We don't care about the real colours, just that they are different.
158  CFAttributedStringSetAttribute(str.get(), CFRangeMake(last, i.first - last), kCTForegroundColorAttributeName, color);
159  CGColorRelease(color);
160 
161  /* Install a size callback for our special sprite glyphs. */
162  for (ssize_t c = last; c < i.first; c++) {
163  if (buff[c] >= SCC_SPRITE_START && buff[c] <= SCC_SPRITE_END) {
164  CFAutoRelease<CTRunDelegateRef> del(CTRunDelegateCreate(&_sprite_font_callback, (void *)(size_t)(buff[c] | (i.second->fc->GetSize() << 24))));
165  CFAttributedStringSetAttribute(str.get(), CFRangeMake(c, 1), kCTRunDelegateAttributeName, del.get());
166  }
167  }
168 
169  last = i.first;
170  }
171  CFAttributedStringEndEditing(str.get());
172 
173  /* Create and return typesetter for the string. */
174  CFAutoRelease<CTTypesetterRef> typesetter(CTTypesetterCreateWithAttributedString(str.get()));
175 
176  return typesetter ? new CoreTextParagraphLayout(std::move(typesetter), buff, length, fontMapping) : nullptr;
177 }
178 
179 /* virtual */ std::unique_ptr<const ParagraphLayouter::Line> CoreTextParagraphLayout::NextLine(int max_width)
180 {
181  if (this->cur_offset >= this->length) return nullptr;
182 
183  /* Get line break position, trying word breaking first and breaking somewhere if that doesn't work. */
184  CFIndex len = CTTypesetterSuggestLineBreak(this->typesetter.get(), this->cur_offset, max_width);
185  if (len <= 0) len = CTTypesetterSuggestClusterBreak(this->typesetter.get(), this->cur_offset, max_width);
186 
187  /* Create line. */
188  CFAutoRelease<CTLineRef> line(CTTypesetterCreateLine(this->typesetter.get(), CFRangeMake(this->cur_offset, len)));
189  this->cur_offset += len;
190 
191  return std::unique_ptr<const Line>(line ? new CoreTextLine(std::move(line), this->font_map, this->text_buffer) : nullptr);
192 }
193 
194 CoreTextParagraphLayout::CoreTextVisualRun::CoreTextVisualRun(CTRunRef run, Font *font, const CoreTextParagraphLayoutFactory::CharType *buff) : font(font)
195 {
196  this->glyphs.resize(CTRunGetGlyphCount(run));
197 
198  /* Query map of glyphs to source string index. */
199  CFIndex map[this->glyphs.size()];
200  CTRunGetStringIndices(run, CFRangeMake(0, 0), map);
201 
202  this->glyph_to_char.resize(this->glyphs.size());
203  for (size_t i = 0; i < this->glyph_to_char.size(); i++) this->glyph_to_char[i] = (int)map[i];
204 
205  CGPoint pts[this->glyphs.size()];
206  CTRunGetPositions(run, CFRangeMake(0, 0), pts);
207  this->positions.resize(this->glyphs.size() * 2 + 2);
208 
209  /* Convert glyph array to our data type. At the same time, substitute
210  * the proper glyphs for our private sprite glyphs. */
211  CGGlyph gl[this->glyphs.size()];
212  CTRunGetGlyphs(run, CFRangeMake(0, 0), gl);
213  for (size_t i = 0; i < this->glyphs.size(); i++) {
214  if (buff[this->glyph_to_char[i]] >= SCC_SPRITE_START && buff[this->glyph_to_char[i]] <= SCC_SPRITE_END) {
215  this->glyphs[i] = font->fc->MapCharToGlyph(buff[this->glyph_to_char[i]]);
216  this->positions[i * 2 + 0] = pts[i].x;
217  this->positions[i * 2 + 1] = font->fc->GetAscender() - font->fc->GetGlyph(this->glyphs[i])->height - 1; // Align sprite glyphs to font baseline.
218  } else {
219  this->glyphs[i] = gl[i];
220  this->positions[i * 2 + 0] = pts[i].x;
221  this->positions[i * 2 + 1] = pts[i].y;
222  }
223  }
224  this->total_advance = (int)CTRunGetTypographicBounds(run, CFRangeMake(0, 0), nullptr, nullptr, nullptr);
225  this->positions[this->glyphs.size() * 2] = this->positions[0] + this->total_advance;
226 }
227 
233 {
234  int leading = 0;
235  for (const auto &run : *this) {
236  leading = max(leading, run.GetLeading());
237  }
238 
239  return leading;
240 }
241 
247 {
248  if (this->size() == 0) return 0;
249 
250  int total_width = 0;
251  for (const auto &run : *this) {
252  total_width += run.GetAdvance();
253  }
254 
255  return total_width;
256 }
257 
258 
261 {
262  _font_cache[size].reset();
263 }
264 
266 void MacOSSetCurrentLocaleName(const char *iso_code)
267 {
268  if (!MacOSVersionIsAtLeast(10, 5, 0)) return;
269 
270  CFAutoRelease<CFStringRef> iso(CFStringCreateWithCString(kCFAllocatorDefault, iso_code, kCFStringEncodingUTF8));
271  _osx_locale.reset(CFLocaleCreate(kCFAllocatorDefault, iso.get()));
272 }
273 
281 int MacOSStringCompare(const char *s1, const char *s2)
282 {
283  static bool supported = MacOSVersionIsAtLeast(10, 5, 0);
284  if (!supported) return 0;
285 
286  CFStringCompareFlags flags = kCFCompareCaseInsensitive | kCFCompareNumerically | kCFCompareLocalized | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
287 
288  CFAutoRelease<CFStringRef> cf1(CFStringCreateWithCString(kCFAllocatorDefault, s1, kCFStringEncodingUTF8));
289  CFAutoRelease<CFStringRef> cf2(CFStringCreateWithCString(kCFAllocatorDefault, s2, kCFStringEncodingUTF8));
290 
291  /* If any CFString could not be created (e.g., due to UTF8 invalid chars), return OS unsupported functionality */
292  if (cf1 == nullptr || cf2 == nullptr) return 0;
293 
294  return (int)CFStringCompareWithOptionsAndLocale(cf1.get(), cf2.get(), CFRangeMake(0, CFStringGetLength(cf1.get())), flags, _osx_locale.get()) + 2;
295 }
296 
297 
298 /* virtual */ void OSXStringIterator::SetString(const char *s)
299 {
300  const char *string_base = s;
301 
302  this->utf16_to_utf8.clear();
303  this->str_info.clear();
304  this->cur_pos = 0;
305 
306  /* CoreText operates on UTF-16, thus we have to convert the input string.
307  * To be able to return proper offsets, we have to create a mapping at the same time. */
308  std::vector<UniChar> utf16_str;
309  while (*s != '\0') {
310  size_t idx = s - string_base;
311 
312  WChar c = Utf8Consume(&s);
313  if (c < 0x10000) {
314  utf16_str.push_back((UniChar)c);
315  } else {
316  /* Make a surrogate pair. */
317  utf16_str.push_back((UniChar)(0xD800 + ((c - 0x10000) >> 10)));
318  utf16_str.push_back((UniChar)(0xDC00 + ((c - 0x10000) & 0x3FF)));
319  this->utf16_to_utf8.push_back(idx);
320  }
321  this->utf16_to_utf8.push_back(idx);
322  }
323  this->utf16_to_utf8.push_back(s - string_base);
324 
325  /* Query CoreText for word and cluster break information. */
326  this->str_info.resize(utf16_to_utf8.size());
327 
328  if (utf16_str.size() > 0) {
329  CFAutoRelease<CFStringRef> str(CFStringCreateWithCharactersNoCopy(kCFAllocatorDefault, &utf16_str[0], utf16_str.size(), kCFAllocatorNull));
330 
331  /* Get cluster breaks. */
332  for (CFIndex i = 0; i < CFStringGetLength(str.get()); ) {
333  CFRange r = CFStringGetRangeOfComposedCharactersAtIndex(str.get(), i);
334  this->str_info[r.location].char_stop = true;
335 
336  i += r.length;
337  }
338 
339  /* Get word breaks. */
340  CFAutoRelease<CFStringTokenizerRef> tokenizer(CFStringTokenizerCreate(kCFAllocatorDefault, str.get(), CFRangeMake(0, CFStringGetLength(str.get())), kCFStringTokenizerUnitWordBoundary, _osx_locale.get()));
341 
342  CFStringTokenizerTokenType tokenType = kCFStringTokenizerTokenNone;
343  while ((tokenType = CFStringTokenizerAdvanceToNextToken(tokenizer.get())) != kCFStringTokenizerTokenNone) {
344  /* Skip tokens that are white-space or punctuation tokens. */
345  if ((tokenType & kCFStringTokenizerTokenHasNonLettersMask) != kCFStringTokenizerTokenHasNonLettersMask) {
346  CFRange r = CFStringTokenizerGetCurrentTokenRange(tokenizer.get());
347  this->str_info[r.location].word_stop = true;
348  }
349  }
350  }
351 
352  /* End-of-string is always a valid stopping point. */
353  this->str_info.back().char_stop = true;
354  this->str_info.back().word_stop = true;
355 }
356 
357 /* virtual */ size_t OSXStringIterator::SetCurPosition(size_t pos)
358 {
359  /* Convert incoming position to an UTF-16 string index. */
360  size_t utf16_pos = 0;
361  for (size_t i = 0; i < this->utf16_to_utf8.size(); i++) {
362  if (this->utf16_to_utf8[i] == pos) {
363  utf16_pos = i;
364  break;
365  }
366  }
367 
368  /* Sanitize in case we get a position inside a grapheme cluster. */
369  while (utf16_pos > 0 && !this->str_info[utf16_pos].char_stop) utf16_pos--;
370  this->cur_pos = utf16_pos;
371 
372  return this->utf16_to_utf8[this->cur_pos];
373 }
374 
375 /* virtual */ size_t OSXStringIterator::Next(IterType what)
376 {
377  assert(this->cur_pos <= this->utf16_to_utf8.size());
379 
380  if (this->cur_pos == this->utf16_to_utf8.size()) return END;
381 
382  do {
383  this->cur_pos++;
384  } while (this->cur_pos < this->utf16_to_utf8.size() && (what == ITER_WORD ? !this->str_info[this->cur_pos].word_stop : !this->str_info[this->cur_pos].char_stop));
385 
386  return this->cur_pos == this->utf16_to_utf8.size() ? END : this->utf16_to_utf8[this->cur_pos];
387 }
388 
389 /* virtual */ size_t OSXStringIterator::Prev(IterType what)
390 {
391  assert(this->cur_pos <= this->utf16_to_utf8.size());
393 
394  if (this->cur_pos == 0) return END;
395 
396  do {
397  this->cur_pos--;
398  } while (this->cur_pos > 0 && (what == ITER_WORD ? !this->str_info[this->cur_pos].word_stop : !this->str_info[this->cur_pos].char_stop));
399 
400  return this->utf16_to_utf8[this->cur_pos];
401 }
402 
403 /* static */ StringIterator *OSXStringIterator::Create()
404 {
405  if (!MacOSVersionIsAtLeast(10, 5, 0)) return nullptr;
406 
407  return new OSXStringIterator();
408 }
409 
410 #else
411 void MacOSResetScriptCache(FontSize size) {}
412 void MacOSSetCurrentLocaleName(const char *iso_code) {}
413 
414 int MacOSStringCompare(const char *s1, const char *s2)
415 {
416  return 0;
417 }
418 
419 /* static */ StringIterator *OSXStringIterator::Create()
420 {
421  return nullptr;
422 }
423 
424 /* static */ ParagraphLayouter *CoreTextParagraphLayoutFactory::GetParagraphLayout(CharType *buff, CharType *buff_end, FontMap &fontMapping)
425 {
426  return nullptr;
427 }
428 #endif /* (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5) */
void SetString(const char *s) override
Set a new iteration string.
Definition: string_osx.cpp:298
Wrapper for doing layouts with CoreText.
Definition: string_osx.cpp:31
int GetLeading() const override
Get the height of the line.
Definition: string_osx.cpp:232
int MacOSStringCompare(const char *s1, const char *s2)
Compares two strings using case insensitive natural sort.
Definition: string_osx.cpp:281
Implementation of simple mapping class.
String iterator using CoreText as a backend.
Definition: string_osx.h:18
static bool MacOSVersionIsAtLeast(long major, long minor, long bugfix)
Check if we are at least running on the specified version of Mac OS.
Definition: macos.h:25
static CFAutoRelease< CTFontRef > _font_cache[FS_END]
CoreText cache for font information, cleared when OTTD changes fonts.
Definition: string_osx.cpp:25
Visual run contains data about the bit of text with the same font.
Definition: gfx_layout.h:120
void MacOSResetScriptCache(FontSize size)
Delete CoreText font reference for a specific font size.
Definition: string_osx.cpp:260
static T max(const T a, const T b)
Returns the maximum of two values.
Definition: math_func.hpp:24
static uint GetGlyphWidth(FontSize size, WChar key)
Get the width of a glyph.
Definition: fontcache.h:201
Iterate over characters (or more exactly grapheme clusters).
Definition: string_base.h:18
Visual run contains data about the bit of text with the same font.
Definition: string_osx.cpp:43
A single line worth of VisualRuns.
Definition: gfx_layout.h:132
static CFAutoRelease< CFLocaleRef > _osx_locale
Cached current locale.
Definition: string_osx.cpp:23
A single line worth of VisualRuns.
Definition: string_osx.cpp:67
Interface to glue fallback and normal layouter into one.
Definition: gfx_layout.h:115
size_t Prev(IterType what) override
Move the cursor back by one iteration unit.
Definition: string_osx.cpp:389
CFIndex cur_offset
Offset from the start of the current run from where to output.
Definition: string_osx.cpp:39
IterType
Type of the iterator.
Definition: string_base.h:17
Functions related to localized text support on OSX.
size_t Next(IterType what) override
Advance the cursor by one iteration unit.
Definition: string_osx.cpp:375
Iterate over words.
Definition: string_base.h:19
std::unique_ptr< typename std::remove_pointer< T >::type, CFDeleter< typename std::remove_pointer< T >::type > > CFAutoRelease
Specialisation of std::unique_ptr for CoreFoundation objects.
Definition: macos.h:52
FontSize
Available font sizes.
Definition: gfx_type.h:201
Functions related to MacOS support.
Class for iterating over different kind of parts of a string.
Definition: string_base.h:14
static ParagraphLayouter * GetParagraphLayout(CharType *buff, CharType *buff_end, FontMap &fontMapping)
Get the actual ParagraphLayout for the given buffer.
Definition: string_osx.cpp:124
UniChar CharType
Helper for GetLayouter, to get the right type.
Definition: string_osx.h:45
int GetWidth() const override
Get the width of this line.
Definition: string_osx.cpp:246
static CGFloat SpriteFontGetWidth(void *ref_con)
Get the width of an encoded sprite font character.
Definition: string_osx.cpp:111
uint32 GlyphID
Glyphs are characters from a font.
Definition: fontcache.h:17
size_t SetCurPosition(size_t pos) override
Change the current string cursor.
Definition: string_osx.cpp:357
uint32 WChar
Type for wide characters, i.e.
Definition: string_type.h:35
void MacOSSetCurrentLocaleName(const char *iso_code)
Store current language locale as a CoreFounation locale.
Definition: string_osx.cpp:266