20#include <CoreFoundation/CoreFoundation.h>
45 std::vector<GlyphID> glyphs;
46 std::vector<Position> positions;
47 std::vector<int> glyph_to_char;
49 int total_advance = 0;
56 std::span<const GlyphID>
GetGlyphs()
const override {
return this->glyphs; }
57 std::span<const Position>
GetPositions()
const override {
return this->positions; }
63 int GetAdvance()
const {
return this->total_advance; }
71 CFArrayRef runs = CTLineGetGlyphRuns(line.get());
72 for (CFIndex i = 0; i < CFArrayGetCount(runs); i++) {
73 CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(runs, i);
76 CFRange chars = CTRunGetStringRange(run);
77 auto map = std::ranges::upper_bound(font_mapping, chars.location, std::less{}, &std::pair<int, Font>::first);
79 this->emplace_back(run, map->second, buff);
85 size_t CountRuns()
const override {
return this->size(); }
91 return c >= 0x010000U ? 2 : 1;
102 this->cur_offset = 0;
105 std::unique_ptr<const Line>
NextLine(
int max_width)
override;
117 char32_t c = (char32_t)((
size_t)ref_con & 0xFFFFFF);
122static const CTRunDelegateCallbacks _sprite_font_callback = {
123 kCTRunDelegateCurrentVersion,
nullptr,
nullptr,
nullptr,
130 ptrdiff_t length = buff_end - buff;
131 if (length == 0)
return nullptr;
134 for (
const auto &[position, font] : font_mapping) {
135 if (font.GetFontCache().IsBuiltInFont())
return nullptr;
140 CFAttributedStringBeginEditing(str.get());
143 CFAttributedStringReplaceString(str.get(), CFRangeMake(0, 0), base.get());
145 const UniChar replacement_char = 0xFFFC;
151 for (
const auto &[position, font] : font_mapping) {
152 if (position - last == 0)
continue;
156 CTFontRef font_handle =
static_cast<CTFontRef
>(fc.
GetOSHandle());
157 CFAttributedStringSetAttribute(str.get(), CFRangeMake(last, position - last), kCTFontAttributeName, font_handle);
159 CGColorRef colour = CGColorCreateGenericGray(
to_underlying(font.colour.colour) / 255.0f, 1.0f);
160 CFAttributedStringSetAttribute(str.get(), CFRangeMake(last, position - last), kCTForegroundColorAttributeName, colour);
161 CGColorRelease(colour);
164 for (
int c = last; c < position; c++) {
165 if (buff[c] >= SCC_SPRITE_START && buff[c] <= SCC_SPRITE_END && fc.
MapCharToGlyph(buff[c],
false) == 0) {
168 CFAttributedStringReplaceString(str.get(), CFRangeMake(c, 1), replacement_str.get());
169 CFAttributedStringSetAttribute(str.get(), CFRangeMake(c, 1), kCTRunDelegateAttributeName, del.get());
175 CFAttributedStringEndEditing(str.get());
180 return typesetter ? std::make_unique<CoreTextParagraphLayout>(std::move(typesetter), buff, length, font_mapping) :
nullptr;
185 if (this->
cur_offset >= this->length)
return nullptr;
188 CFIndex len = CTTypesetterSuggestLineBreak(this->typesetter.get(), this->cur_offset, max_width);
189 if (len <= 0) len = CTTypesetterSuggestClusterBreak(this->typesetter.get(), this->cur_offset, max_width);
195 if (!line)
return nullptr;
196 return std::make_unique<CoreTextLine>(std::move(line), this->font_map, this->text_buffer);
207 this->glyphs.resize(CTRunGetGlyphCount(run));
210 auto map = std::make_unique<CFIndex[]>(this->glyphs.size());
211 CTRunGetStringIndices(run, CFRangeMake(0, 0), map.get());
213 this->glyph_to_char.resize(this->glyphs.size());
214 for (
size_t i = 0; i < this->glyph_to_char.size(); i++) this->glyph_to_char[i] = (
int)map[i];
216 auto pts = std::make_unique<CGPoint[]>(this->glyphs.size());
217 CTRunGetPositions(run, CFRangeMake(0, 0), pts.get());
218 auto advs = std::make_unique<CGSize[]>(this->glyphs.size());
219 CTRunGetAdvances(run, CFRangeMake(0, 0), advs.get());
220 this->positions.reserve(this->glyphs.size());
224 auto gl = std::make_unique<CGGlyph[]>(this->glyphs.size());
225 CTRunGetGlyphs(run, CFRangeMake(0, 0), gl.get());
226 for (
size_t i = 0; i < this->glyphs.size(); i++) {
227 if (buff[this->glyph_to_char[i]] >= SCC_SPRITE_START && buff[this->glyph_to_char[i]] <= SCC_SPRITE_END && (gl[i] == 0 || gl[i] == 3)) {
230 this->glyphs[i] = fc.
MapCharToGlyph(buff[this->glyph_to_char[i]]);
231 this->positions.emplace_back(pts[i].x, pts[i].x + advs[i].width - 1, (fc.
GetHeight() -
ScaleSpriteTrad(FontCache::GetDefaultFontHeight(fc.
GetSize()))) / 2);
233 this->glyphs[i] = gl[i];
234 this->positions.emplace_back(pts[i].x, pts[i].x + advs[i].width - 1, pts[i].y);
237 this->total_advance = (int)std::ceil(CTRunGetTypographicBounds(run, CFRangeMake(0, 0),
nullptr,
nullptr,
nullptr));
247 for (
const auto &run : *
this) {
248 leading = std::max(leading, run.GetLeading());
260 if (this->empty())
return 0;
263 for (
const auto &run : *
this) {
264 total_width += run.GetAdvance();
276 CFAutoRelease<CFStringRef> path(CFStringCreateWithBytes(kCFAllocatorDefault,
reinterpret_cast<const UInt8 *
>(file_path.data()), file_path.size(), kCFStringEncodingUTF8,
false));
277 CFAutoRelease<CFURLRef> url(CFURLCreateWithFileSystemPath(kCFAllocatorDefault, path.get(), kCFURLPOSIXPathStyle,
false));
279 CTFontManagerRegisterFontsForURL(url.get(), kCTFontManagerScopeProcess,
nullptr);
288 CFAutoRelease<CFStringRef> iso(CFStringCreateWithBytes(kCFAllocatorDefault,
reinterpret_cast<const UInt8 *
>(iso_code.data()), iso_code.size(), kCFStringEncodingUTF8,
false));
289 _osx_locale.reset(CFLocaleCreate(kCFAllocatorDefault, iso.get()));
301 CFStringCompareFlags flags = kCFCompareCaseInsensitive | kCFCompareNumerically | kCFCompareLocalized | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
303 CFAutoRelease<CFStringRef> cf1(CFStringCreateWithBytes(kCFAllocatorDefault, (
const UInt8 *)s1.data(), s1.size(), kCFStringEncodingUTF8,
false));
304 CFAutoRelease<CFStringRef> cf2(CFStringCreateWithBytes(kCFAllocatorDefault, (
const UInt8 *)s2.data(), s2.size(), kCFStringEncodingUTF8,
false));
307 if (cf1 ==
nullptr || cf2 ==
nullptr)
return 0;
309 return (
int)CFStringCompareWithOptionsAndLocale(cf1.get(), cf2.get(), CFRangeMake(0, CFStringGetLength(cf1.get())), flags,
_osx_locale.get()) + 2;
322 CFStringCompareFlags flags = kCFCompareLocalized | kCFCompareWidthInsensitive;
323 if (case_insensitive) flags |= kCFCompareCaseInsensitive;
325 CFAutoRelease<CFStringRef> cf_str(CFStringCreateWithBytes(kCFAllocatorDefault, (
const UInt8 *)str.data(), str.size(), kCFStringEncodingUTF8,
false));
326 CFAutoRelease<CFStringRef> cf_value(CFStringCreateWithBytes(kCFAllocatorDefault, (
const UInt8 *)value.data(), value.size(), kCFStringEncodingUTF8,
false));
329 if (cf_str ==
nullptr || cf_value ==
nullptr)
return -1;
331 return CFStringFindWithOptionsAndLocale(cf_str.get(), cf_value.get(), CFRangeMake(0, CFStringGetLength(cf_str.get())), flags,
_osx_locale.get(),
nullptr) ? 1 : 0;
343 std::vector<UniChar> utf16_str;
345 for (
auto it = view.begin(), end = view.end(); it != end; ++it) {
346 size_t idx = it.GetByteOffset();
349 utf16_str.push_back((UniChar)c);
352 utf16_str.push_back((UniChar)(0xD800 + ((c - 0x10000) >> 10)));
353 utf16_str.push_back((UniChar)(0xDC00 + ((c - 0x10000) & 0x3FF)));
363 if (!utf16_str.empty()) {
364 CFAutoRelease<CFStringRef> str(CFStringCreateWithCharactersNoCopy(kCFAllocatorDefault, &utf16_str[0], utf16_str.size(), kCFAllocatorNull));
367 for (CFIndex i = 0; i < CFStringGetLength(str.get()); ) {
368 CFRange r = CFStringGetRangeOfComposedCharactersAtIndex(str.get(), i);
369 this->
str_info[r.location].char_stop =
true;
377 CFStringTokenizerTokenType tokenType = kCFStringTokenizerTokenNone;
378 while ((tokenType = CFStringTokenizerAdvanceToNextToken(tokenizer.get())) != kCFStringTokenizerTokenNone) {
380 if ((tokenType & kCFStringTokenizerTokenHasNonLettersMask) != kCFStringTokenizerTokenHasNonLettersMask) {
381 CFRange r = CFStringTokenizerGetCurrentTokenRange(tokenizer.get());
382 this->
str_info[r.location].word_stop =
true;
388 this->
str_info.back().char_stop =
true;
389 this->
str_info.back().word_stop =
true;
395 size_t utf16_pos = 0;
404 while (utf16_pos > 0 && !this->
str_info[utf16_pos].char_stop) utf16_pos--;
419 }
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));
440 return std::make_unique<OSXStringIterator>();
UniChar CharType
Helper for GetLayouter, to get the right type.
static std::unique_ptr< ParagraphLayouter > GetParagraphLayout(CharType *buff, CharType *buff_end, FontMap &font_mapping)
Get the actual ParagraphLayout for the given buffer.
const VisualRun & GetVisualRun(size_t run) const override
Get a reference to the given run.
int GetWidth() const override
Get the width of this line.
size_t CountRuns() const override
Get the number of runs in this line.
int GetLeading() const override
Get the height of the line.
int GetInternalCharLength(char32_t c) const override
Get the number of elements the given character occupies in the underlying text buffer of the Layouter...
std::span< const int > GetGlyphToCharMap() const override
The offset for each of the glyphs to the character run that was passed to the Layouter.
const Font & GetFont() const override
Get the font.
int GetLeading() const override
Get the font leading, or distance between the baselines of consecutive lines.
CoreTextVisualRun(CTRunRef run, const Font &font, const CoreTextParagraphLayoutFactory::CharType *buff)
Construct a new Core Text Visual Run object.
size_t GetGlyphCount() const override
Get the number of glyphs.
std::span< const Position > GetPositions() const override
Get the positions for each of the glyphs.
std::span< const GlyphID > GetGlyphs() const override
Get the glyphs to draw.
Wrapper for doing layouts with CoreText.
std::unique_ptr< const Line > NextLine(int max_width) override
Construct a new line with a maximum width.
CFIndex cur_offset
Offset from the start of the current run from where to output.
void Reflow() override
Reset the position to the start of the paragraph.
Font cache for basic fonts.
int GetHeight() const
Get the height of the font.
virtual const void * GetOSHandle()
Get the native OS font handle, if there is one.
virtual GlyphID MapCharToGlyph(char32_t key, bool fallback=true)=0
Map a character into a glyph.
FontSize GetSize() const
Get the FontSize of the font.
Container with information about a font.
FontCache & GetFontCache() const
Get the font cache of this font.
size_t Prev(IterType what) override
Move the cursor back by one iteration unit.
size_t Next(IterType what) override
Advance the cursor by one iteration unit.
std::vector< CharInfo > str_info
Break information for each code point.
size_t SetCurPosition(size_t pos) override
Change the current string cursor.
size_t cur_pos
Current iteration position.
std::vector< size_t > utf16_to_utf8
Mapping from UTF-16 code point position to index in the UTF-8 source string.
void SetString(std::string_view s) override
Set a new iteration string.
A single line worth of VisualRuns.
Visual run contains data about the bit of text with the same font.
Interface to glue fallback and normal layouter into one.
static const size_t END
Sentinel to indicate end-of-iteration.
static std::unique_ptr< StringIterator > Create()
Create a new iterator instance.
IterType
Type of the iterator.
@ ITER_WORD
Iterate over words.
@ ITER_CHARACTER
Iterate over characters (or more exactly grapheme clusters).
Constant span of UTF-8 encoded data.
Control codes that are embedded in the translation strings.
constexpr std::underlying_type_t< enum_type > to_underlying(enum_type e)
Implementation of std::to_underlying (from C++23).
Functions to read fonts from files and cache them.
uint GetGlyphWidth(FontSize size, char32_t key)
Get the width of a glyph.
std::vector< std::pair< int, Font > > FontMap
Mapping from index to font.
FontSize
Available font sizes.
Functions related to MacOS support.
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.
A number of safeguards to prevent using unsafe methods.
Definition of base types and functions in a cross-platform compatible way.
Functions related to low-level strings.
void MacOSRegisterExternalFont(std::string_view file_path)
Register an external font file with the CoreText system.
int MacOSStringCompare(std::string_view s1, std::string_view s2)
Compares two strings using case insensitive natural sort.
void MacOSSetCurrentLocaleName(std::string_view iso_code)
Store current language locale as a CoreFoundation locale.
static CGFloat SpriteFontGetWidth(void *ref_con)
Get the width of an encoded sprite font character.
int MacOSStringContains(std::string_view str, std::string_view value, bool case_insensitive)
Search if a string is contained in another string using the current locale.
static CFAutoRelease< CFLocaleRef > _osx_locale
Cached current locale.
Functions related to localized text support on OSX.
Functions related to OTTD's strings.
Handling of UTF-8 encoded data.
Functions related to zooming.
int ScaleSpriteTrad(int value)
Scale traditional pixel dimensions to GUI zoom level, for drawing sprites.