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