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