• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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   return (hb_directwrite_font_data_t *) HB_SHAPER_DATA_SUCCEEDED;
277 }
278 
279 void
_hb_directwrite_shaper_font_data_destroy(hb_directwrite_font_data_t * data)280 _hb_directwrite_shaper_font_data_destroy (hb_directwrite_font_data_t *data)
281 {
282 }
283 
284 
285 // Most of TextAnalysis is originally written by Bas Schouten for Mozilla project
286 // but now is relicensed to MIT for HarfBuzz use
287 class TextAnalysis : public IDWriteTextAnalysisSource, public IDWriteTextAnalysisSink
288 {
289 public:
290 
IFACEMETHOD(QueryInterface)291   IFACEMETHOD (QueryInterface) (IID const& iid, OUT void** ppObject)
292   { return S_OK; }
IFACEMETHOD_(ULONG,AddRef)293   IFACEMETHOD_ (ULONG, AddRef) () { return 1; }
IFACEMETHOD_(ULONG,Release)294   IFACEMETHOD_ (ULONG, Release) () { return 1; }
295 
296   // A single contiguous run of characters containing the same analysis
297   // results.
298   struct Run
299   {
300     uint32_t mTextStart;   // starting text position of this run
301     uint32_t mTextLength;  // number of contiguous code units covered
302     uint32_t mGlyphStart;  // starting glyph in the glyphs array
303     uint32_t mGlyphCount;  // number of glyphs associated with this run
304     // text
305     DWRITE_SCRIPT_ANALYSIS mScript;
306     uint8_t mBidiLevel;
307     bool mIsSideways;
308 
ContainsTextPositionTextAnalysis::Run309     bool ContainsTextPosition (uint32_t aTextPosition) const
310     {
311       return aTextPosition >= mTextStart &&
312 	     aTextPosition <  mTextStart + mTextLength;
313     }
314 
315     Run *nextRun;
316   };
317 
318 public:
TextAnalysis(const wchar_t * text,uint32_t textLength,const wchar_t * localeName,DWRITE_READING_DIRECTION readingDirection)319   TextAnalysis (const wchar_t* text, uint32_t textLength,
320 		const wchar_t* localeName, DWRITE_READING_DIRECTION readingDirection)
321 	       : mTextLength (textLength), mText (text), mLocaleName (localeName),
322 		 mReadingDirection (readingDirection), mCurrentRun (nullptr) {}
~TextAnalysis()323   ~TextAnalysis ()
324   {
325     // delete runs, except mRunHead which is part of the TextAnalysis object
326     for (Run *run = mRunHead.nextRun; run;)
327     {
328       Run *origRun = run;
329       run = run->nextRun;
330       delete origRun;
331     }
332   }
333 
334   STDMETHODIMP
GenerateResults(IDWriteTextAnalyzer * textAnalyzer,Run ** runHead)335   GenerateResults (IDWriteTextAnalyzer* textAnalyzer, Run **runHead)
336   {
337     // Analyzes the text using the script analyzer and returns
338     // the result as a series of runs.
339 
340     HRESULT hr = S_OK;
341 
342     // Initially start out with one result that covers the entire range.
343     // This result will be subdivided by the analysis processes.
344     mRunHead.mTextStart = 0;
345     mRunHead.mTextLength = mTextLength;
346     mRunHead.mBidiLevel =
347       (mReadingDirection == DWRITE_READING_DIRECTION_RIGHT_TO_LEFT);
348     mRunHead.nextRun = nullptr;
349     mCurrentRun = &mRunHead;
350 
351     // Call each of the analyzers in sequence, recording their results.
352     if (SUCCEEDED (hr = textAnalyzer->AnalyzeScript (this, 0, mTextLength, this)))
353       *runHead = &mRunHead;
354 
355     return hr;
356   }
357 
358   // IDWriteTextAnalysisSource implementation
359 
360   IFACEMETHODIMP
GetTextAtPosition(uint32_t textPosition,OUT wchar_t const ** textString,OUT uint32_t * textLength)361   GetTextAtPosition (uint32_t textPosition,
362 		     OUT wchar_t const** textString,
363 		     OUT uint32_t* textLength)
364   {
365     if (textPosition >= mTextLength)
366     {
367       // No text at this position, valid query though.
368       *textString = nullptr;
369       *textLength = 0;
370     }
371     else
372     {
373       *textString = mText + textPosition;
374       *textLength = mTextLength - textPosition;
375     }
376     return S_OK;
377   }
378 
379   IFACEMETHODIMP
GetTextBeforePosition(uint32_t textPosition,OUT wchar_t const ** textString,OUT uint32_t * textLength)380   GetTextBeforePosition (uint32_t textPosition,
381 			 OUT wchar_t const** textString,
382 			 OUT uint32_t* textLength)
383   {
384     if (textPosition == 0 || textPosition > mTextLength)
385     {
386       // Either there is no text before here (== 0), or this
387       // is an invalid position. The query is considered valid though.
388       *textString = nullptr;
389       *textLength = 0;
390     }
391     else
392     {
393       *textString = mText;
394       *textLength = textPosition;
395     }
396     return S_OK;
397   }
398 
399   IFACEMETHODIMP_ (DWRITE_READING_DIRECTION)
GetParagraphReadingDirection()400   GetParagraphReadingDirection () { return mReadingDirection; }
401 
GetLocaleName(uint32_t textPosition,uint32_t * textLength,wchar_t const ** localeName)402   IFACEMETHODIMP GetLocaleName (uint32_t textPosition, uint32_t* textLength,
403 				wchar_t const** localeName)
404   { return S_OK; }
405 
406   IFACEMETHODIMP
GetNumberSubstitution(uint32_t textPosition,OUT uint32_t * textLength,OUT IDWriteNumberSubstitution ** numberSubstitution)407   GetNumberSubstitution (uint32_t textPosition,
408 			 OUT uint32_t* textLength,
409 			 OUT IDWriteNumberSubstitution** numberSubstitution)
410   {
411     // We do not support number substitution.
412     *numberSubstitution = nullptr;
413     *textLength = mTextLength - textPosition;
414 
415     return S_OK;
416   }
417 
418   // IDWriteTextAnalysisSink implementation
419 
420   IFACEMETHODIMP
SetScriptAnalysis(uint32_t textPosition,uint32_t textLength,DWRITE_SCRIPT_ANALYSIS const * scriptAnalysis)421   SetScriptAnalysis (uint32_t textPosition, uint32_t textLength,
422 		     DWRITE_SCRIPT_ANALYSIS const* scriptAnalysis)
423   {
424     SetCurrentRun (textPosition);
425     SplitCurrentRun (textPosition);
426     while (textLength > 0)
427     {
428       Run *run = FetchNextRun (&textLength);
429       run->mScript = *scriptAnalysis;
430     }
431 
432     return S_OK;
433   }
434 
435   IFACEMETHODIMP
SetLineBreakpoints(uint32_t textPosition,uint32_t textLength,const DWRITE_LINE_BREAKPOINT * lineBreakpoints)436   SetLineBreakpoints (uint32_t textPosition,
437 		      uint32_t textLength,
438 		      const DWRITE_LINE_BREAKPOINT* lineBreakpoints)
439   { return S_OK; }
440 
SetBidiLevel(uint32_t textPosition,uint32_t textLength,uint8_t explicitLevel,uint8_t resolvedLevel)441   IFACEMETHODIMP SetBidiLevel (uint32_t textPosition, uint32_t textLength,
442 			       uint8_t explicitLevel, uint8_t resolvedLevel)
443   { return S_OK; }
444 
445   IFACEMETHODIMP
SetNumberSubstitution(uint32_t textPosition,uint32_t textLength,IDWriteNumberSubstitution * numberSubstitution)446   SetNumberSubstitution (uint32_t textPosition, uint32_t textLength,
447 			 IDWriteNumberSubstitution* numberSubstitution)
448   { return S_OK; }
449 
450 protected:
FetchNextRun(IN OUT uint32_t * textLength)451   Run *FetchNextRun (IN OUT uint32_t* textLength)
452   {
453     // Used by the sink setters, this returns a reference to the next run.
454     // Position and length are adjusted to now point after the current run
455     // being returned.
456 
457     Run *origRun = mCurrentRun;
458     // Split the tail if needed (the length remaining is less than the
459     // current run's size).
460     if (*textLength < mCurrentRun->mTextLength)
461       SplitCurrentRun (mCurrentRun->mTextStart + *textLength);
462     else
463       // Just advance the current run.
464       mCurrentRun = mCurrentRun->nextRun;
465     *textLength -= origRun->mTextLength;
466 
467     // Return a reference to the run that was just current.
468     return origRun;
469   }
470 
SetCurrentRun(uint32_t textPosition)471   void SetCurrentRun (uint32_t textPosition)
472   {
473     // Move the current run to the given position.
474     // Since the analyzers generally return results in a forward manner,
475     // this will usually just return early. If not, find the
476     // corresponding run for the text position.
477 
478     if (mCurrentRun && mCurrentRun->ContainsTextPosition (textPosition))
479       return;
480 
481     for (Run *run = &mRunHead; run; run = run->nextRun)
482       if (run->ContainsTextPosition (textPosition))
483       {
484 	mCurrentRun = run;
485 	return;
486       }
487     assert (0); // We should always be able to find the text position in one of our runs
488   }
489 
SplitCurrentRun(uint32_t splitPosition)490   void SplitCurrentRun (uint32_t splitPosition)
491   {
492     if (!mCurrentRun)
493     {
494       assert (0); // SplitCurrentRun called without current run
495       // Shouldn't be calling this when no current run is set!
496       return;
497     }
498     // Split the current run.
499     if (splitPosition <= mCurrentRun->mTextStart)
500     {
501       // No need to split, already the start of a run
502       // or before it. Usually the first.
503       return;
504     }
505     Run *newRun = new Run;
506 
507     *newRun = *mCurrentRun;
508 
509     // Insert the new run in our linked list.
510     newRun->nextRun = mCurrentRun->nextRun;
511     mCurrentRun->nextRun = newRun;
512 
513     // Adjust runs' text positions and lengths.
514     uint32_t splitPoint = splitPosition - mCurrentRun->mTextStart;
515     newRun->mTextStart += splitPoint;
516     newRun->mTextLength -= splitPoint;
517     mCurrentRun->mTextLength = splitPoint;
518     mCurrentRun = newRun;
519   }
520 
521 protected:
522   // Input
523   // (weak references are fine here, since this class is a transient
524   //  stack-based helper that doesn't need to copy data)
525   uint32_t mTextLength;
526   const wchar_t* mText;
527   const wchar_t* mLocaleName;
528   DWRITE_READING_DIRECTION mReadingDirection;
529 
530   // Current processing state.
531   Run *mCurrentRun;
532 
533   // Output is a list of runs starting here
534   Run  mRunHead;
535 };
536 
537 /*
538  * shaper
539  */
540 
541 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)542 _hb_directwrite_shape (hb_shape_plan_t    *shape_plan,
543 		       hb_font_t          *font,
544 		       hb_buffer_t        *buffer,
545 		       const hb_feature_t *features,
546 		       unsigned int        num_features)
547 {
548   hb_face_t *face = font->face;
549   const hb_directwrite_face_data_t *face_data = face->data.directwrite;
550   IDWriteFactory *dwriteFactory = face_data->dwriteFactory;
551   IDWriteFontFace *fontFace = face_data->fontFace;
552 
553   IDWriteTextAnalyzer* analyzer;
554   dwriteFactory->CreateTextAnalyzer (&analyzer);
555 
556   unsigned int scratch_size;
557   hb_buffer_t::scratch_buffer_t *scratch = buffer->get_scratch_buffer (&scratch_size);
558 #define ALLOCATE_ARRAY(Type, name, len) \
559   Type *name = (Type *) scratch; \
560   do { \
561     unsigned int _consumed = DIV_CEIL ((len) * sizeof (Type), sizeof (*scratch)); \
562     assert (_consumed <= scratch_size); \
563     scratch += _consumed; \
564     scratch_size -= _consumed; \
565   } while (0)
566 
567 #define utf16_index() var1.u32
568 
569   ALLOCATE_ARRAY (wchar_t, textString, buffer->len * 2);
570 
571   unsigned int chars_len = 0;
572   for (unsigned int i = 0; i < buffer->len; i++)
573   {
574     hb_codepoint_t c = buffer->info[i].codepoint;
575     buffer->info[i].utf16_index () = chars_len;
576     if (likely (c <= 0xFFFFu))
577       textString[chars_len++] = c;
578     else if (unlikely (c > 0x10FFFFu))
579       textString[chars_len++] = 0xFFFDu;
580     else
581     {
582       textString[chars_len++] = 0xD800u + ((c - 0x10000u) >> 10);
583       textString[chars_len++] = 0xDC00u + ((c - 0x10000u) & ((1u << 10) - 1));
584     }
585   }
586 
587   ALLOCATE_ARRAY (WORD, log_clusters, chars_len);
588   /* Need log_clusters to assign features. */
589   chars_len = 0;
590   for (unsigned int i = 0; i < buffer->len; i++)
591   {
592     hb_codepoint_t c = buffer->info[i].codepoint;
593     unsigned int cluster = buffer->info[i].cluster;
594     log_clusters[chars_len++] = cluster;
595     if (hb_in_range (c, 0x10000u, 0x10FFFFu))
596       log_clusters[chars_len++] = cluster; /* Surrogates. */
597   }
598 
599   DWRITE_READING_DIRECTION readingDirection;
600   readingDirection = buffer->props.direction ?
601 		     DWRITE_READING_DIRECTION_RIGHT_TO_LEFT :
602 		     DWRITE_READING_DIRECTION_LEFT_TO_RIGHT;
603 
604   /*
605   * There's an internal 16-bit limit on some things inside the analyzer,
606   * but we never attempt to shape a word longer than 64K characters
607   * in a single gfxShapedWord, so we cannot exceed that limit.
608   */
609   uint32_t textLength = chars_len;
610 
611   TextAnalysis analysis (textString, textLength, nullptr, readingDirection);
612   TextAnalysis::Run *runHead;
613   HRESULT hr;
614   hr = analysis.GenerateResults (analyzer, &runHead);
615 
616 #define FAIL(...) \
617   HB_STMT_START { \
618     DEBUG_MSG (DIRECTWRITE, nullptr, __VA_ARGS__); \
619     return false; \
620   } HB_STMT_END
621 
622   if (FAILED (hr))
623     FAIL ("Analyzer failed to generate results.");
624 
625   uint32_t maxGlyphCount = 3 * textLength / 2 + 16;
626   uint32_t glyphCount;
627   bool isRightToLeft = HB_DIRECTION_IS_BACKWARD (buffer->props.direction);
628 
629   const wchar_t localeName[20] = {0};
630   if (buffer->props.language)
631     mbstowcs ((wchar_t*) localeName,
632 	      hb_language_to_string (buffer->props.language), 20);
633 
634   /*
635    * Set up features.
636    */
637   static_assert ((sizeof (DWRITE_TYPOGRAPHIC_FEATURES) == sizeof (hb_ms_features_t)), "");
638   static_assert ((sizeof (DWRITE_FONT_FEATURE) == sizeof (hb_ms_feature_t)), "");
639   hb_vector_t<hb_ms_features_t *> range_features;
640   hb_vector_t<uint32_t> range_char_counts;
641   if (num_features)
642   {
643     hb_vector_t<hb_ms_feature_t> feature_records;
644     hb_vector_t<hb_ms_range_record_t> range_records;
645     if (hb_ms_setup_features (features, num_features, feature_records, range_records))
646       hb_ms_make_feature_ranges (feature_records,
647 				 range_records,
648 				 0,
649 				 chars_len,
650 				 log_clusters,
651 				 range_features,
652 				 range_char_counts);
653   }
654 
655   uint16_t* clusterMap;
656   clusterMap = new uint16_t[textLength];
657   DWRITE_SHAPING_TEXT_PROPERTIES* textProperties;
658   textProperties = new DWRITE_SHAPING_TEXT_PROPERTIES[textLength];
659 
660 retry_getglyphs:
661   uint16_t* glyphIndices = new uint16_t[maxGlyphCount];
662   DWRITE_SHAPING_GLYPH_PROPERTIES* glyphProperties;
663   glyphProperties = new DWRITE_SHAPING_GLYPH_PROPERTIES[maxGlyphCount];
664 
665   hr = analyzer->GetGlyphs (textString,
666 			    chars_len,
667 			    fontFace,
668 			    false,
669 			    isRightToLeft,
670 			    &runHead->mScript,
671 			    localeName,
672 			    nullptr,
673 			    (const DWRITE_TYPOGRAPHIC_FEATURES**) range_features.arrayZ,
674 			    range_char_counts.arrayZ,
675 			    range_features.length,
676 			    maxGlyphCount,
677 			    clusterMap,
678 			    textProperties,
679 			    glyphIndices,
680 			    glyphProperties,
681 			    &glyphCount);
682 
683   if (unlikely (hr == HRESULT_FROM_WIN32 (ERROR_INSUFFICIENT_BUFFER)))
684   {
685     delete [] glyphIndices;
686     delete [] glyphProperties;
687 
688     maxGlyphCount *= 2;
689 
690     goto retry_getglyphs;
691   }
692   if (FAILED (hr))
693     FAIL ("Analyzer failed to get glyphs.");
694 
695   float* glyphAdvances = new float[maxGlyphCount];
696   DWRITE_GLYPH_OFFSET* glyphOffsets = new DWRITE_GLYPH_OFFSET[maxGlyphCount];
697 
698   /* The -2 in the following is to compensate for possible
699    * alignment needed after the WORD array.  sizeof (WORD) == 2. */
700   unsigned int glyphs_size = (scratch_size * sizeof (int) - 2)
701 			     / (sizeof (WORD) +
702 				sizeof (DWRITE_SHAPING_GLYPH_PROPERTIES) +
703 				sizeof (int) +
704 				sizeof (DWRITE_GLYPH_OFFSET) +
705 				sizeof (uint32_t));
706   ALLOCATE_ARRAY (uint32_t, vis_clusters, glyphs_size);
707 
708 #undef ALLOCATE_ARRAY
709 
710   int fontEmSize = font->face->get_upem ();
711   if (fontEmSize < 0) fontEmSize = -fontEmSize;
712 
713   if (fontEmSize < 0) fontEmSize = -fontEmSize;
714   double x_mult = (double) font->x_scale / fontEmSize;
715   double y_mult = (double) font->y_scale / fontEmSize;
716 
717   hr = analyzer->GetGlyphPlacements (textString,
718 				     clusterMap,
719 				     textProperties,
720 				     chars_len,
721 				     glyphIndices,
722 				     glyphProperties,
723 				     glyphCount,
724 				     fontFace,
725 				     fontEmSize,
726 				     false,
727 				     isRightToLeft,
728 				     &runHead->mScript,
729 				     localeName,
730 				     (const DWRITE_TYPOGRAPHIC_FEATURES**) range_features.arrayZ,
731 				     range_char_counts.arrayZ,
732 				     range_features.length,
733 				     glyphAdvances,
734 				     glyphOffsets);
735 
736   if (FAILED (hr))
737     FAIL ("Analyzer failed to get glyph placements.");
738 
739   /* Ok, we've got everything we need, now compose output buffer,
740    * very, *very*, carefully! */
741 
742   /* Calculate visual-clusters.  That's what we ship. */
743   for (unsigned int i = 0; i < glyphCount; i++)
744     vis_clusters[i] = (uint32_t) -1;
745   for (unsigned int i = 0; i < buffer->len; i++)
746   {
747     uint32_t *p =
748       &vis_clusters[log_clusters[buffer->info[i].utf16_index ()]];
749     *p = hb_min (*p, buffer->info[i].cluster);
750   }
751   for (unsigned int i = 1; i < glyphCount; i++)
752     if (vis_clusters[i] == (uint32_t) -1)
753       vis_clusters[i] = vis_clusters[i - 1];
754 
755 #undef utf16_index
756 
757   if (unlikely (!buffer->ensure (glyphCount)))
758     FAIL ("Buffer in error");
759 
760 #undef FAIL
761 
762   /* Set glyph infos */
763   buffer->len = 0;
764   for (unsigned int i = 0; i < glyphCount; i++)
765   {
766     hb_glyph_info_t *info = &buffer->info[buffer->len++];
767 
768     info->codepoint = glyphIndices[i];
769     info->cluster = vis_clusters[i];
770 
771     /* The rest is crap.  Let's store position info there for now. */
772     info->mask = glyphAdvances[i];
773     info->var1.i32 = glyphOffsets[i].advanceOffset;
774     info->var2.i32 = glyphOffsets[i].ascenderOffset;
775   }
776 
777   /* Set glyph positions */
778   buffer->clear_positions ();
779   for (unsigned int i = 0; i < glyphCount; i++)
780   {
781     hb_glyph_info_t *info = &buffer->info[i];
782     hb_glyph_position_t *pos = &buffer->pos[i];
783 
784     /* TODO vertical */
785     pos->x_advance = x_mult * (int32_t) info->mask;
786     pos->x_offset = x_mult * (isRightToLeft ? -info->var1.i32 : info->var1.i32);
787     pos->y_offset = y_mult * info->var2.i32;
788   }
789 
790   if (isRightToLeft) hb_buffer_reverse (buffer);
791 
792   buffer->clear_glyph_flags ();
793   buffer->unsafe_to_break ();
794 
795   delete [] clusterMap;
796   delete [] glyphIndices;
797   delete [] textProperties;
798   delete [] glyphProperties;
799   delete [] glyphAdvances;
800   delete [] glyphOffsets;
801 
802   /* Wow, done! */
803   return true;
804 }
805 
806 struct _hb_directwrite_font_table_context {
807   IDWriteFontFace *face;
808   void *table_context;
809 };
810 
811 static void
_hb_directwrite_table_data_release(void * data)812 _hb_directwrite_table_data_release (void *data)
813 {
814   _hb_directwrite_font_table_context *context = (_hb_directwrite_font_table_context *) data;
815   context->face->ReleaseFontTable (context->table_context);
816   hb_free (context);
817 }
818 
819 static hb_blob_t *
_hb_directwrite_reference_table(hb_face_t * face HB_UNUSED,hb_tag_t tag,void * user_data)820 _hb_directwrite_reference_table (hb_face_t *face HB_UNUSED, hb_tag_t tag, void *user_data)
821 {
822   IDWriteFontFace *dw_face = ((IDWriteFontFace *) user_data);
823   const void *data;
824   uint32_t length;
825   void *table_context;
826   BOOL exists;
827   if (!dw_face || FAILED (dw_face->TryGetFontTable (hb_uint32_swap (tag), &data,
828 						    &length, &table_context, &exists)))
829     return nullptr;
830 
831   if (!data || !exists || !length)
832   {
833     dw_face->ReleaseFontTable (table_context);
834     return nullptr;
835   }
836 
837   _hb_directwrite_font_table_context *context = (_hb_directwrite_font_table_context *) hb_malloc (sizeof (_hb_directwrite_font_table_context));
838   context->face = dw_face;
839   context->table_context = table_context;
840 
841   return hb_blob_create ((const char *) data, length, HB_MEMORY_MODE_READONLY,
842 			 context, _hb_directwrite_table_data_release);
843 }
844 
845 static void
_hb_directwrite_font_release(void * data)846 _hb_directwrite_font_release (void *data)
847 {
848   if (data)
849     ((IDWriteFontFace *) data)->Release ();
850 }
851 
852 /**
853  * hb_directwrite_face_create:
854  * @font_face: a DirectWrite IDWriteFontFace object.
855  *
856  * Constructs a new face object from the specified DirectWrite IDWriteFontFace.
857  *
858  * Return value: #hb_face_t object corresponding to the given input
859  *
860  * Since: 2.4.0
861  **/
862 hb_face_t *
hb_directwrite_face_create(IDWriteFontFace * font_face)863 hb_directwrite_face_create (IDWriteFontFace *font_face)
864 {
865   if (font_face)
866     font_face->AddRef ();
867   return hb_face_create_for_tables (_hb_directwrite_reference_table, font_face,
868 				    _hb_directwrite_font_release);
869 }
870 
871 /**
872 * hb_directwrite_face_get_font_face:
873 * @face: a #hb_face_t object
874 *
875 * Gets the DirectWrite IDWriteFontFace associated with @face.
876 *
877 * Return value: DirectWrite IDWriteFontFace object corresponding to the given input
878 *
879 * Since: 2.5.0
880 **/
881 IDWriteFontFace *
hb_directwrite_face_get_font_face(hb_face_t * face)882 hb_directwrite_face_get_font_face (hb_face_t *face)
883 {
884   return face->data.directwrite->fontFace;
885 }
886 
887 
888 #endif
889