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