1 /*
2 * Copyright © 2015-2019 Ebrahim Byagowi
3 *
4 * This is part of HarfBuzz, a text shaping library.
5 *
6 * Permission is hereby granted, without written agreement and without
7 * license or royalty fees, to use, copy, modify, and distribute this
8 * software and its documentation for any purpose, provided that the
9 * above copyright notice and the following two paragraphs appear in
10 * all copies of this software.
11 *
12 * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
13 * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
14 * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
15 * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
16 * DAMAGE.
17 *
18 * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
19 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
20 * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
21 * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
22 * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
23 */
24
25 #include "hb.hh"
26
27 #ifdef HAVE_DIRECTWRITE
28
29 #include "hb-shaper-impl.hh"
30
31 #include <dwrite_1.h>
32
33 #include "hb-directwrite.h"
34
35 #include "hb-ms-feature-ranges.hh"
36
37 /**
38 * SECTION:hb-directwrite
39 * @title: hb-directwrite
40 * @short_description: DirectWrite integration
41 * @include: hb-directwrite.h
42 *
43 * Functions for using HarfBuzz with DirectWrite fonts.
44 **/
45
46 /* Declare object creator for dynamic support of DWRITE */
47 typedef HRESULT (* WINAPI t_DWriteCreateFactory)(
48 DWRITE_FACTORY_TYPE factoryType,
49 REFIID iid,
50 IUnknown **factory
51 );
52
53
54 /*
55 * DirectWrite font stream helpers
56 */
57
58 // This is a font loader which provides only one font (unlike its original design).
59 // For a better implementation which was also source of this
60 // and DWriteFontFileStream, have a look at to NativeFontResourceDWrite.cpp in Mozilla
61 class DWriteFontFileLoader : public IDWriteFontFileLoader
62 {
63 private:
64 IDWriteFontFileStream *mFontFileStream;
65 public:
DWriteFontFileLoader(IDWriteFontFileStream * fontFileStream)66 DWriteFontFileLoader (IDWriteFontFileStream *fontFileStream)
67 { mFontFileStream = fontFileStream; }
68
69 // IUnknown interface
IFACEMETHOD(QueryInterface)70 IFACEMETHOD (QueryInterface) (IID const& iid, OUT void** ppObject)
71 { return S_OK; }
IFACEMETHOD_(ULONG,AddRef)72 IFACEMETHOD_ (ULONG, AddRef) () { return 1; }
IFACEMETHOD_(ULONG,Release)73 IFACEMETHOD_ (ULONG, Release) () { return 1; }
74
75 // IDWriteFontFileLoader methods
76 virtual HRESULT STDMETHODCALLTYPE
CreateStreamFromKey(void const * fontFileReferenceKey,uint32_t fontFileReferenceKeySize,OUT IDWriteFontFileStream ** fontFileStream)77 CreateStreamFromKey (void const* fontFileReferenceKey,
78 uint32_t fontFileReferenceKeySize,
79 OUT IDWriteFontFileStream** fontFileStream)
80 {
81 *fontFileStream = mFontFileStream;
82 return S_OK;
83 }
84
~DWriteFontFileLoader()85 virtual ~DWriteFontFileLoader() {}
86 };
87
88 class DWriteFontFileStream : public IDWriteFontFileStream
89 {
90 private:
91 uint8_t *mData;
92 uint32_t mSize;
93 public:
DWriteFontFileStream(uint8_t * aData,uint32_t aSize)94 DWriteFontFileStream (uint8_t *aData, uint32_t aSize)
95 {
96 mData = aData;
97 mSize = aSize;
98 }
99
100 // IUnknown interface
IFACEMETHOD(QueryInterface)101 IFACEMETHOD (QueryInterface) (IID const& iid, OUT void** ppObject)
102 { return S_OK; }
IFACEMETHOD_(ULONG,AddRef)103 IFACEMETHOD_ (ULONG, AddRef) () { return 1; }
IFACEMETHOD_(ULONG,Release)104 IFACEMETHOD_ (ULONG, Release) () { return 1; }
105
106 // IDWriteFontFileStream methods
107 virtual HRESULT STDMETHODCALLTYPE
ReadFileFragment(void const ** fragmentStart,UINT64 fileOffset,UINT64 fragmentSize,OUT void ** fragmentContext)108 ReadFileFragment (void const** fragmentStart,
109 UINT64 fileOffset,
110 UINT64 fragmentSize,
111 OUT void** fragmentContext)
112 {
113 // We are required to do bounds checking.
114 if (fileOffset + fragmentSize > mSize) return E_FAIL;
115
116 // truncate the 64 bit fileOffset to size_t sized index into mData
117 size_t index = static_cast<size_t> (fileOffset);
118
119 // We should be alive for the duration of this.
120 *fragmentStart = &mData[index];
121 *fragmentContext = nullptr;
122 return S_OK;
123 }
124
125 virtual void STDMETHODCALLTYPE
ReleaseFileFragment(void * fragmentContext)126 ReleaseFileFragment (void* fragmentContext) {}
127
128 virtual HRESULT STDMETHODCALLTYPE
GetFileSize(OUT UINT64 * fileSize)129 GetFileSize (OUT UINT64* fileSize)
130 {
131 *fileSize = mSize;
132 return S_OK;
133 }
134
135 virtual HRESULT STDMETHODCALLTYPE
GetLastWriteTime(OUT UINT64 * lastWriteTime)136 GetLastWriteTime (OUT UINT64* lastWriteTime) { return E_NOTIMPL; }
137
~DWriteFontFileStream()138 virtual ~DWriteFontFileStream() {}
139 };
140
141
142 /*
143 * shaper face data
144 */
145
146 struct hb_directwrite_face_data_t
147 {
148 HMODULE dwrite_dll;
149 IDWriteFactory *dwriteFactory;
150 IDWriteFontFile *fontFile;
151 DWriteFontFileStream *fontFileStream;
152 DWriteFontFileLoader *fontFileLoader;
153 IDWriteFontFace *fontFace;
154 hb_blob_t *faceBlob;
155 };
156
157 hb_directwrite_face_data_t *
_hb_directwrite_shaper_face_data_create(hb_face_t * face)158 _hb_directwrite_shaper_face_data_create (hb_face_t *face)
159 {
160 hb_directwrite_face_data_t *data = new hb_directwrite_face_data_t;
161 if (unlikely (!data))
162 return nullptr;
163
164 #define FAIL(...) \
165 HB_STMT_START { \
166 DEBUG_MSG (DIRECTWRITE, nullptr, __VA_ARGS__); \
167 return nullptr; \
168 } HB_STMT_END
169
170 data->dwrite_dll = LoadLibrary (TEXT ("DWRITE"));
171 if (unlikely (!data->dwrite_dll))
172 FAIL ("Cannot find DWrite.DLL");
173
174 t_DWriteCreateFactory p_DWriteCreateFactory;
175
176 #if defined(__GNUC__)
177 #pragma GCC diagnostic push
178 #pragma GCC diagnostic ignored "-Wcast-function-type"
179 #endif
180
181 p_DWriteCreateFactory = (t_DWriteCreateFactory)
182 GetProcAddress (data->dwrite_dll, "DWriteCreateFactory");
183
184 #if defined(__GNUC__)
185 #pragma GCC diagnostic pop
186 #endif
187
188 if (unlikely (!p_DWriteCreateFactory))
189 FAIL ("Cannot find DWriteCreateFactory().");
190
191 HRESULT hr;
192
193 // TODO: factory and fontFileLoader should be cached separately
194 IDWriteFactory* dwriteFactory;
195 hr = p_DWriteCreateFactory (DWRITE_FACTORY_TYPE_SHARED, __uuidof (IDWriteFactory),
196 (IUnknown**) &dwriteFactory);
197
198 if (unlikely (hr != S_OK))
199 FAIL ("Failed to run DWriteCreateFactory().");
200
201 hb_blob_t *blob = hb_face_reference_blob (face);
202 DWriteFontFileStream *fontFileStream;
203 fontFileStream = new DWriteFontFileStream ((uint8_t *) hb_blob_get_data (blob, nullptr),
204 hb_blob_get_length (blob));
205
206 DWriteFontFileLoader *fontFileLoader = new DWriteFontFileLoader (fontFileStream);
207 dwriteFactory->RegisterFontFileLoader (fontFileLoader);
208
209 IDWriteFontFile *fontFile;
210 uint64_t fontFileKey = 0;
211 hr = dwriteFactory->CreateCustomFontFileReference (&fontFileKey, sizeof (fontFileKey),
212 fontFileLoader, &fontFile);
213
214 if (FAILED (hr))
215 FAIL ("Failed to load font file from data!");
216
217 BOOL isSupported;
218 DWRITE_FONT_FILE_TYPE fileType;
219 DWRITE_FONT_FACE_TYPE faceType;
220 uint32_t numberOfFaces;
221 hr = fontFile->Analyze (&isSupported, &fileType, &faceType, &numberOfFaces);
222 if (FAILED (hr) || !isSupported)
223 FAIL ("Font file is not supported.");
224
225 #undef FAIL
226
227 IDWriteFontFace *fontFace;
228 dwriteFactory->CreateFontFace (faceType, 1, &fontFile, 0,
229 DWRITE_FONT_SIMULATIONS_NONE, &fontFace);
230
231 data->dwriteFactory = dwriteFactory;
232 data->fontFile = fontFile;
233 data->fontFileStream = fontFileStream;
234 data->fontFileLoader = fontFileLoader;
235 data->fontFace = fontFace;
236 data->faceBlob = blob;
237
238 return data;
239 }
240
241 void
_hb_directwrite_shaper_face_data_destroy(hb_directwrite_face_data_t * data)242 _hb_directwrite_shaper_face_data_destroy (hb_directwrite_face_data_t *data)
243 {
244 if (data->fontFace)
245 data->fontFace->Release ();
246 if (data->fontFile)
247 data->fontFile->Release ();
248 if (data->dwriteFactory)
249 {
250 if (data->fontFileLoader)
251 data->dwriteFactory->UnregisterFontFileLoader (data->fontFileLoader);
252 data->dwriteFactory->Release ();
253 }
254 if (data->fontFileLoader)
255 delete data->fontFileLoader;
256 if (data->fontFileStream)
257 delete data->fontFileStream;
258 if (data->faceBlob)
259 hb_blob_destroy (data->faceBlob);
260 if (data->dwrite_dll)
261 FreeLibrary (data->dwrite_dll);
262 if (data)
263 delete data;
264 }
265
266
267 /*
268 * shaper font data
269 */
270
271 struct hb_directwrite_font_data_t {};
272
273 hb_directwrite_font_data_t *
_hb_directwrite_shaper_font_data_create(hb_font_t * font)274 _hb_directwrite_shaper_font_data_create (hb_font_t *font)
275 {
276 hb_directwrite_font_data_t *data = new hb_directwrite_font_data_t;
277 if (unlikely (!data))
278 return nullptr;
279
280 return data;
281 }
282
283 void
_hb_directwrite_shaper_font_data_destroy(hb_directwrite_font_data_t * data)284 _hb_directwrite_shaper_font_data_destroy (hb_directwrite_font_data_t *data)
285 {
286 delete data;
287 }
288
289
290 // Most of TextAnalysis is originally written by Bas Schouten for Mozilla project
291 // but now is relicensed to MIT for HarfBuzz use
292 class TextAnalysis : public IDWriteTextAnalysisSource, public IDWriteTextAnalysisSink
293 {
294 public:
295
IFACEMETHOD(QueryInterface)296 IFACEMETHOD (QueryInterface) (IID const& iid, OUT void** ppObject)
297 { return S_OK; }
IFACEMETHOD_(ULONG,AddRef)298 IFACEMETHOD_ (ULONG, AddRef) () { return 1; }
IFACEMETHOD_(ULONG,Release)299 IFACEMETHOD_ (ULONG, Release) () { return 1; }
300
301 // A single contiguous run of characters containing the same analysis
302 // results.
303 struct Run
304 {
305 uint32_t mTextStart; // starting text position of this run
306 uint32_t mTextLength; // number of contiguous code units covered
307 uint32_t mGlyphStart; // starting glyph in the glyphs array
308 uint32_t mGlyphCount; // number of glyphs associated with this run
309 // text
310 DWRITE_SCRIPT_ANALYSIS mScript;
311 uint8_t mBidiLevel;
312 bool mIsSideways;
313
ContainsTextPositionTextAnalysis::Run314 bool ContainsTextPosition (uint32_t aTextPosition) const
315 {
316 return aTextPosition >= mTextStart &&
317 aTextPosition < mTextStart + mTextLength;
318 }
319
320 Run *nextRun;
321 };
322
323 public:
TextAnalysis(const wchar_t * text,uint32_t textLength,const wchar_t * localeName,DWRITE_READING_DIRECTION readingDirection)324 TextAnalysis (const wchar_t* text, uint32_t textLength,
325 const wchar_t* localeName, DWRITE_READING_DIRECTION readingDirection)
326 : mTextLength (textLength), mText (text), mLocaleName (localeName),
327 mReadingDirection (readingDirection), mCurrentRun (nullptr) {}
~TextAnalysis()328 ~TextAnalysis ()
329 {
330 // delete runs, except mRunHead which is part of the TextAnalysis object
331 for (Run *run = mRunHead.nextRun; run;)
332 {
333 Run *origRun = run;
334 run = run->nextRun;
335 delete origRun;
336 }
337 }
338
339 STDMETHODIMP
GenerateResults(IDWriteTextAnalyzer * textAnalyzer,Run ** runHead)340 GenerateResults (IDWriteTextAnalyzer* textAnalyzer, Run **runHead)
341 {
342 // Analyzes the text using the script analyzer and returns
343 // the result as a series of runs.
344
345 HRESULT hr = S_OK;
346
347 // Initially start out with one result that covers the entire range.
348 // This result will be subdivided by the analysis processes.
349 mRunHead.mTextStart = 0;
350 mRunHead.mTextLength = mTextLength;
351 mRunHead.mBidiLevel =
352 (mReadingDirection == DWRITE_READING_DIRECTION_RIGHT_TO_LEFT);
353 mRunHead.nextRun = nullptr;
354 mCurrentRun = &mRunHead;
355
356 // Call each of the analyzers in sequence, recording their results.
357 if (SUCCEEDED (hr = textAnalyzer->AnalyzeScript (this, 0, mTextLength, this)))
358 *runHead = &mRunHead;
359
360 return hr;
361 }
362
363 // IDWriteTextAnalysisSource implementation
364
365 IFACEMETHODIMP
GetTextAtPosition(uint32_t textPosition,OUT wchar_t const ** textString,OUT uint32_t * textLength)366 GetTextAtPosition (uint32_t textPosition,
367 OUT wchar_t const** textString,
368 OUT uint32_t* textLength)
369 {
370 if (textPosition >= mTextLength)
371 {
372 // No text at this position, valid query though.
373 *textString = nullptr;
374 *textLength = 0;
375 }
376 else
377 {
378 *textString = mText + textPosition;
379 *textLength = mTextLength - textPosition;
380 }
381 return S_OK;
382 }
383
384 IFACEMETHODIMP
GetTextBeforePosition(uint32_t textPosition,OUT wchar_t const ** textString,OUT uint32_t * textLength)385 GetTextBeforePosition (uint32_t textPosition,
386 OUT wchar_t const** textString,
387 OUT uint32_t* textLength)
388 {
389 if (textPosition == 0 || textPosition > mTextLength)
390 {
391 // Either there is no text before here (== 0), or this
392 // is an invalid position. The query is considered valid though.
393 *textString = nullptr;
394 *textLength = 0;
395 }
396 else
397 {
398 *textString = mText;
399 *textLength = textPosition;
400 }
401 return S_OK;
402 }
403
404 IFACEMETHODIMP_ (DWRITE_READING_DIRECTION)
GetParagraphReadingDirection()405 GetParagraphReadingDirection () { return mReadingDirection; }
406
GetLocaleName(uint32_t textPosition,uint32_t * textLength,wchar_t const ** localeName)407 IFACEMETHODIMP GetLocaleName (uint32_t textPosition, uint32_t* textLength,
408 wchar_t const** localeName)
409 { return S_OK; }
410
411 IFACEMETHODIMP
GetNumberSubstitution(uint32_t textPosition,OUT uint32_t * textLength,OUT IDWriteNumberSubstitution ** numberSubstitution)412 GetNumberSubstitution (uint32_t textPosition,
413 OUT uint32_t* textLength,
414 OUT IDWriteNumberSubstitution** numberSubstitution)
415 {
416 // We do not support number substitution.
417 *numberSubstitution = nullptr;
418 *textLength = mTextLength - textPosition;
419
420 return S_OK;
421 }
422
423 // IDWriteTextAnalysisSink implementation
424
425 IFACEMETHODIMP
SetScriptAnalysis(uint32_t textPosition,uint32_t textLength,DWRITE_SCRIPT_ANALYSIS const * scriptAnalysis)426 SetScriptAnalysis (uint32_t textPosition, uint32_t textLength,
427 DWRITE_SCRIPT_ANALYSIS const* scriptAnalysis)
428 {
429 SetCurrentRun (textPosition);
430 SplitCurrentRun (textPosition);
431 while (textLength > 0)
432 {
433 Run *run = FetchNextRun (&textLength);
434 run->mScript = *scriptAnalysis;
435 }
436
437 return S_OK;
438 }
439
440 IFACEMETHODIMP
SetLineBreakpoints(uint32_t textPosition,uint32_t textLength,const DWRITE_LINE_BREAKPOINT * lineBreakpoints)441 SetLineBreakpoints (uint32_t textPosition,
442 uint32_t textLength,
443 const DWRITE_LINE_BREAKPOINT* lineBreakpoints)
444 { return S_OK; }
445
SetBidiLevel(uint32_t textPosition,uint32_t textLength,uint8_t explicitLevel,uint8_t resolvedLevel)446 IFACEMETHODIMP SetBidiLevel (uint32_t textPosition, uint32_t textLength,
447 uint8_t explicitLevel, uint8_t resolvedLevel)
448 { return S_OK; }
449
450 IFACEMETHODIMP
SetNumberSubstitution(uint32_t textPosition,uint32_t textLength,IDWriteNumberSubstitution * numberSubstitution)451 SetNumberSubstitution (uint32_t textPosition, uint32_t textLength,
452 IDWriteNumberSubstitution* numberSubstitution)
453 { return S_OK; }
454
455 protected:
FetchNextRun(IN OUT uint32_t * textLength)456 Run *FetchNextRun (IN OUT uint32_t* textLength)
457 {
458 // Used by the sink setters, this returns a reference to the next run.
459 // Position and length are adjusted to now point after the current run
460 // being returned.
461
462 Run *origRun = mCurrentRun;
463 // Split the tail if needed (the length remaining is less than the
464 // current run's size).
465 if (*textLength < mCurrentRun->mTextLength)
466 SplitCurrentRun (mCurrentRun->mTextStart + *textLength);
467 else
468 // Just advance the current run.
469 mCurrentRun = mCurrentRun->nextRun;
470 *textLength -= origRun->mTextLength;
471
472 // Return a reference to the run that was just current.
473 return origRun;
474 }
475
SetCurrentRun(uint32_t textPosition)476 void SetCurrentRun (uint32_t textPosition)
477 {
478 // Move the current run to the given position.
479 // Since the analyzers generally return results in a forward manner,
480 // this will usually just return early. If not, find the
481 // corresponding run for the text position.
482
483 if (mCurrentRun && mCurrentRun->ContainsTextPosition (textPosition))
484 return;
485
486 for (Run *run = &mRunHead; run; run = run->nextRun)
487 if (run->ContainsTextPosition (textPosition))
488 {
489 mCurrentRun = run;
490 return;
491 }
492 assert (0); // We should always be able to find the text position in one of our runs
493 }
494
SplitCurrentRun(uint32_t splitPosition)495 void SplitCurrentRun (uint32_t splitPosition)
496 {
497 if (!mCurrentRun)
498 {
499 assert (0); // SplitCurrentRun called without current run
500 // Shouldn't be calling this when no current run is set!
501 return;
502 }
503 // Split the current run.
504 if (splitPosition <= mCurrentRun->mTextStart)
505 {
506 // No need to split, already the start of a run
507 // or before it. Usually the first.
508 return;
509 }
510 Run *newRun = new Run;
511
512 *newRun = *mCurrentRun;
513
514 // Insert the new run in our linked list.
515 newRun->nextRun = mCurrentRun->nextRun;
516 mCurrentRun->nextRun = newRun;
517
518 // Adjust runs' text positions and lengths.
519 uint32_t splitPoint = splitPosition - mCurrentRun->mTextStart;
520 newRun->mTextStart += splitPoint;
521 newRun->mTextLength -= splitPoint;
522 mCurrentRun->mTextLength = splitPoint;
523 mCurrentRun = newRun;
524 }
525
526 protected:
527 // Input
528 // (weak references are fine here, since this class is a transient
529 // stack-based helper that doesn't need to copy data)
530 uint32_t mTextLength;
531 const wchar_t* mText;
532 const wchar_t* mLocaleName;
533 DWRITE_READING_DIRECTION mReadingDirection;
534
535 // Current processing state.
536 Run *mCurrentRun;
537
538 // Output is a list of runs starting here
539 Run mRunHead;
540 };
541
542 /*
543 * shaper
544 */
545
546 hb_bool_t
_hb_directwrite_shape(hb_shape_plan_t * shape_plan,hb_font_t * font,hb_buffer_t * buffer,const hb_feature_t * features,unsigned int num_features)547 _hb_directwrite_shape (hb_shape_plan_t *shape_plan,
548 hb_font_t *font,
549 hb_buffer_t *buffer,
550 const hb_feature_t *features,
551 unsigned int num_features)
552 {
553 hb_face_t *face = font->face;
554 const hb_directwrite_face_data_t *face_data = face->data.directwrite;
555 IDWriteFactory *dwriteFactory = face_data->dwriteFactory;
556 IDWriteFontFace *fontFace = face_data->fontFace;
557
558 IDWriteTextAnalyzer* analyzer;
559 dwriteFactory->CreateTextAnalyzer (&analyzer);
560
561 unsigned int scratch_size;
562 hb_buffer_t::scratch_buffer_t *scratch = buffer->get_scratch_buffer (&scratch_size);
563 #define ALLOCATE_ARRAY(Type, name, len) \
564 Type *name = (Type *) scratch; \
565 do { \
566 unsigned int _consumed = DIV_CEIL ((len) * sizeof (Type), sizeof (*scratch)); \
567 assert (_consumed <= scratch_size); \
568 scratch += _consumed; \
569 scratch_size -= _consumed; \
570 } while (0)
571
572 #define utf16_index() var1.u32
573
574 ALLOCATE_ARRAY (wchar_t, textString, buffer->len * 2);
575
576 unsigned int chars_len = 0;
577 for (unsigned int i = 0; i < buffer->len; i++)
578 {
579 hb_codepoint_t c = buffer->info[i].codepoint;
580 buffer->info[i].utf16_index () = chars_len;
581 if (likely (c <= 0xFFFFu))
582 textString[chars_len++] = c;
583 else if (unlikely (c > 0x10FFFFu))
584 textString[chars_len++] = 0xFFFDu;
585 else
586 {
587 textString[chars_len++] = 0xD800u + ((c - 0x10000u) >> 10);
588 textString[chars_len++] = 0xDC00u + ((c - 0x10000u) & ((1u << 10) - 1));
589 }
590 }
591
592 ALLOCATE_ARRAY (WORD, log_clusters, chars_len);
593 /* Need log_clusters to assign features. */
594 chars_len = 0;
595 for (unsigned int i = 0; i < buffer->len; i++)
596 {
597 hb_codepoint_t c = buffer->info[i].codepoint;
598 unsigned int cluster = buffer->info[i].cluster;
599 log_clusters[chars_len++] = cluster;
600 if (hb_in_range (c, 0x10000u, 0x10FFFFu))
601 log_clusters[chars_len++] = cluster; /* Surrogates. */
602 }
603
604 DWRITE_READING_DIRECTION readingDirection;
605 readingDirection = buffer->props.direction ?
606 DWRITE_READING_DIRECTION_RIGHT_TO_LEFT :
607 DWRITE_READING_DIRECTION_LEFT_TO_RIGHT;
608
609 /*
610 * There's an internal 16-bit limit on some things inside the analyzer,
611 * but we never attempt to shape a word longer than 64K characters
612 * in a single gfxShapedWord, so we cannot exceed that limit.
613 */
614 uint32_t textLength = chars_len;
615
616 TextAnalysis analysis (textString, textLength, nullptr, readingDirection);
617 TextAnalysis::Run *runHead;
618 HRESULT hr;
619 hr = analysis.GenerateResults (analyzer, &runHead);
620
621 #define FAIL(...) \
622 HB_STMT_START { \
623 DEBUG_MSG (DIRECTWRITE, nullptr, __VA_ARGS__); \
624 return false; \
625 } HB_STMT_END
626
627 if (FAILED (hr))
628 FAIL ("Analyzer failed to generate results.");
629
630 uint32_t maxGlyphCount = 3 * textLength / 2 + 16;
631 uint32_t glyphCount;
632 bool isRightToLeft = HB_DIRECTION_IS_BACKWARD (buffer->props.direction);
633
634 const wchar_t localeName[20] = {0};
635 if (buffer->props.language)
636 mbstowcs ((wchar_t*) localeName,
637 hb_language_to_string (buffer->props.language), 20);
638
639 /*
640 * Set up features.
641 */
642 static_assert ((sizeof (DWRITE_TYPOGRAPHIC_FEATURES) == sizeof (hb_ms_features_t)), "");
643 static_assert ((sizeof (DWRITE_FONT_FEATURE) == sizeof (hb_ms_feature_t)), "");
644 hb_vector_t<hb_ms_features_t *> range_features;
645 hb_vector_t<uint32_t> range_char_counts;
646 if (num_features)
647 {
648 hb_vector_t<hb_ms_feature_t> feature_records;
649 hb_vector_t<hb_ms_range_record_t> range_records;
650 if (hb_ms_setup_features (features, num_features, feature_records, range_records))
651 hb_ms_make_feature_ranges (feature_records,
652 range_records,
653 0,
654 chars_len,
655 log_clusters,
656 range_features,
657 range_char_counts);
658 }
659
660 uint16_t* clusterMap;
661 clusterMap = new uint16_t[textLength];
662 DWRITE_SHAPING_TEXT_PROPERTIES* textProperties;
663 textProperties = new DWRITE_SHAPING_TEXT_PROPERTIES[textLength];
664
665 retry_getglyphs:
666 uint16_t* glyphIndices = new uint16_t[maxGlyphCount];
667 DWRITE_SHAPING_GLYPH_PROPERTIES* glyphProperties;
668 glyphProperties = new DWRITE_SHAPING_GLYPH_PROPERTIES[maxGlyphCount];
669
670 hr = analyzer->GetGlyphs (textString,
671 chars_len,
672 fontFace,
673 false,
674 isRightToLeft,
675 &runHead->mScript,
676 localeName,
677 nullptr,
678 (const DWRITE_TYPOGRAPHIC_FEATURES**) range_features.arrayZ,
679 range_char_counts.arrayZ,
680 range_features.length,
681 maxGlyphCount,
682 clusterMap,
683 textProperties,
684 glyphIndices,
685 glyphProperties,
686 &glyphCount);
687
688 if (unlikely (hr == HRESULT_FROM_WIN32 (ERROR_INSUFFICIENT_BUFFER)))
689 {
690 delete [] glyphIndices;
691 delete [] glyphProperties;
692
693 maxGlyphCount *= 2;
694
695 goto retry_getglyphs;
696 }
697 if (FAILED (hr))
698 FAIL ("Analyzer failed to get glyphs.");
699
700 float* glyphAdvances = new float[maxGlyphCount];
701 DWRITE_GLYPH_OFFSET* glyphOffsets = new DWRITE_GLYPH_OFFSET[maxGlyphCount];
702
703 /* The -2 in the following is to compensate for possible
704 * alignment needed after the WORD array. sizeof (WORD) == 2. */
705 unsigned int glyphs_size = (scratch_size * sizeof (int) - 2)
706 / (sizeof (WORD) +
707 sizeof (DWRITE_SHAPING_GLYPH_PROPERTIES) +
708 sizeof (int) +
709 sizeof (DWRITE_GLYPH_OFFSET) +
710 sizeof (uint32_t));
711 ALLOCATE_ARRAY (uint32_t, vis_clusters, glyphs_size);
712
713 #undef ALLOCATE_ARRAY
714
715 int fontEmSize = font->face->get_upem ();
716 if (fontEmSize < 0) fontEmSize = -fontEmSize;
717
718 if (fontEmSize < 0) fontEmSize = -fontEmSize;
719 double x_mult = (double) font->x_scale / fontEmSize;
720 double y_mult = (double) font->y_scale / fontEmSize;
721
722 hr = analyzer->GetGlyphPlacements (textString,
723 clusterMap,
724 textProperties,
725 chars_len,
726 glyphIndices,
727 glyphProperties,
728 glyphCount,
729 fontFace,
730 fontEmSize,
731 false,
732 isRightToLeft,
733 &runHead->mScript,
734 localeName,
735 (const DWRITE_TYPOGRAPHIC_FEATURES**) range_features.arrayZ,
736 range_char_counts.arrayZ,
737 range_features.length,
738 glyphAdvances,
739 glyphOffsets);
740
741 if (FAILED (hr))
742 FAIL ("Analyzer failed to get glyph placements.");
743
744 /* Ok, we've got everything we need, now compose output buffer,
745 * very, *very*, carefully! */
746
747 /* Calculate visual-clusters. That's what we ship. */
748 for (unsigned int i = 0; i < glyphCount; i++)
749 vis_clusters[i] = (uint32_t) -1;
750 for (unsigned int i = 0; i < buffer->len; i++)
751 {
752 uint32_t *p =
753 &vis_clusters[log_clusters[buffer->info[i].utf16_index ()]];
754 *p = hb_min (*p, buffer->info[i].cluster);
755 }
756 for (unsigned int i = 1; i < glyphCount; i++)
757 if (vis_clusters[i] == (uint32_t) -1)
758 vis_clusters[i] = vis_clusters[i - 1];
759
760 #undef utf16_index
761
762 if (unlikely (!buffer->ensure (glyphCount)))
763 FAIL ("Buffer in error");
764
765 #undef FAIL
766
767 /* Set glyph infos */
768 buffer->len = 0;
769 for (unsigned int i = 0; i < glyphCount; i++)
770 {
771 hb_glyph_info_t *info = &buffer->info[buffer->len++];
772
773 info->codepoint = glyphIndices[i];
774 info->cluster = vis_clusters[i];
775
776 /* The rest is crap. Let's store position info there for now. */
777 info->mask = glyphAdvances[i];
778 info->var1.i32 = glyphOffsets[i].advanceOffset;
779 info->var2.i32 = glyphOffsets[i].ascenderOffset;
780 }
781
782 /* Set glyph positions */
783 buffer->clear_positions ();
784 for (unsigned int i = 0; i < glyphCount; i++)
785 {
786 hb_glyph_info_t *info = &buffer->info[i];
787 hb_glyph_position_t *pos = &buffer->pos[i];
788
789 /* TODO vertical */
790 pos->x_advance = x_mult * (int32_t) info->mask;
791 pos->x_offset = x_mult * (isRightToLeft ? -info->var1.i32 : info->var1.i32);
792 pos->y_offset = y_mult * info->var2.i32;
793 }
794
795 if (isRightToLeft) hb_buffer_reverse (buffer);
796
797 delete [] clusterMap;
798 delete [] glyphIndices;
799 delete [] textProperties;
800 delete [] glyphProperties;
801 delete [] glyphAdvances;
802 delete [] glyphOffsets;
803
804 /* Wow, done! */
805 return true;
806 }
807
808 struct _hb_directwrite_font_table_context {
809 IDWriteFontFace *face;
810 void *table_context;
811 };
812
813 static void
_hb_directwrite_table_data_release(void * data)814 _hb_directwrite_table_data_release (void *data)
815 {
816 _hb_directwrite_font_table_context *context = (_hb_directwrite_font_table_context *) data;
817 context->face->ReleaseFontTable (context->table_context);
818 hb_free (context);
819 }
820
821 static hb_blob_t *
_hb_directwrite_reference_table(hb_face_t * face HB_UNUSED,hb_tag_t tag,void * user_data)822 _hb_directwrite_reference_table (hb_face_t *face HB_UNUSED, hb_tag_t tag, void *user_data)
823 {
824 IDWriteFontFace *dw_face = ((IDWriteFontFace *) user_data);
825 const void *data;
826 uint32_t length;
827 void *table_context;
828 BOOL exists;
829 if (!dw_face || FAILED (dw_face->TryGetFontTable (hb_uint32_swap (tag), &data,
830 &length, &table_context, &exists)))
831 return nullptr;
832
833 if (!data || !exists || !length)
834 {
835 dw_face->ReleaseFontTable (table_context);
836 return nullptr;
837 }
838
839 _hb_directwrite_font_table_context *context = (_hb_directwrite_font_table_context *) hb_malloc (sizeof (_hb_directwrite_font_table_context));
840 context->face = dw_face;
841 context->table_context = table_context;
842
843 return hb_blob_create ((const char *) data, length, HB_MEMORY_MODE_READONLY,
844 context, _hb_directwrite_table_data_release);
845 }
846
847 static void
_hb_directwrite_font_release(void * data)848 _hb_directwrite_font_release (void *data)
849 {
850 if (data)
851 ((IDWriteFontFace *) data)->Release ();
852 }
853
854 /**
855 * hb_directwrite_face_create:
856 * @font_face: a DirectWrite IDWriteFontFace object.
857 *
858 * Constructs a new face object from the specified DirectWrite IDWriteFontFace.
859 *
860 * Return value: #hb_face_t object corresponding to the given input
861 *
862 * Since: 2.4.0
863 **/
864 hb_face_t *
hb_directwrite_face_create(IDWriteFontFace * font_face)865 hb_directwrite_face_create (IDWriteFontFace *font_face)
866 {
867 if (font_face)
868 font_face->AddRef ();
869 return hb_face_create_for_tables (_hb_directwrite_reference_table, font_face,
870 _hb_directwrite_font_release);
871 }
872
873 /**
874 * hb_directwrite_face_get_font_face:
875 * @face: a #hb_face_t object
876 *
877 * Gets the DirectWrite IDWriteFontFace associated with @face.
878 *
879 * Return value: DirectWrite IDWriteFontFace object corresponding to the given input
880 *
881 * Since: 2.5.0
882 **/
883 IDWriteFontFace *
hb_directwrite_face_get_font_face(hb_face_t * face)884 hb_directwrite_face_get_font_face (hb_face_t *face)
885 {
886 return face->data.directwrite->fontFace;
887 }
888
889
890 #endif
891