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