hb-directwrite.cc 25.9 KB
Newer Older
1
/*
2
 * Copyright © 2015-2018  Ebrahim Byagowi
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 *
 *  This is part of HarfBuzz, a text shaping library.
 *
 * Permission is hereby granted, without written agreement and without
 * license or royalty fees, to use, copy, modify, and distribute this
 * software and its documentation for any purpose, provided that the
 * above copyright notice and the following two paragraphs appear in
 * all copies of this software.
 *
 * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
 * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
 * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
 * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
 * DAMAGE.
 *
 * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
 * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
 * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
 */

25 26
#include "hb.hh"
#include "hb-shaper-impl.hh"
27

28
#include <DWrite_1.h>
29 30 31 32

#include "hb-directwrite.h"


33 34 35 36 37
/*
 * hb-directwrite uses new/delete syntatically but as we let users
 * to override malloc/free, we will redefine new/delete so users
 * won't need to do that by their own.
 */
38 39 40
void* operator new (size_t size)        { return malloc (size); }
void* operator new [] (size_t size)     { return malloc (size); }
void operator delete (void* pointer)    { free (pointer); }
41
void operator delete [] (void* pointer) { free (pointer); }
42 43


44 45 46
/*
 * DirectWrite font stream helpers
 */
47

48 49 50 51
// This is a font loader which provides only one font (unlike its original design).
// For a better implementation which was also source of this
// and DWriteFontFileStream, have a look at to NativeFontResourceDWrite.cpp in Mozilla
class DWriteFontFileLoader : public IDWriteFontFileLoader
52
{
53 54 55
private:
  IDWriteFontFileStream *mFontFileStream;
public:
56
  DWriteFontFileLoader (IDWriteFontFileStream *fontFileStream)
57
  { mFontFileStream = fontFileStream; }
58

59
  // IUnknown interface
60 61 62 63
  IFACEMETHOD (QueryInterface) (IID const& iid, OUT void** ppObject)
  { return S_OK; }
  IFACEMETHOD_ (ULONG, AddRef) (void)  { return 1; }
  IFACEMETHOD_ (ULONG, Release) (void) { return 1; }
64

65
  // IDWriteFontFileLoader methods
66 67 68 69
  virtual HRESULT STDMETHODCALLTYPE
  CreateStreamFromKey (void const* fontFileReferenceKey,
		       uint32_t fontFileReferenceKeySize,
		       OUT IDWriteFontFileStream** fontFileStream)
70 71 72 73 74
  {
    *fontFileStream = mFontFileStream;
    return S_OK;
  }
};
75

76 77 78 79 80 81
class DWriteFontFileStream : public IDWriteFontFileStream
{
private:
  uint8_t *mData;
  uint32_t mSize;
public:
82
  DWriteFontFileStream (uint8_t *aData, uint32_t aSize)
83 84 85 86
  {
    mData = aData;
    mSize = aSize;
  }
87

88
  // IUnknown interface
89 90 91 92
  IFACEMETHOD (QueryInterface) (IID const& iid, OUT void** ppObject)
  { return S_OK; }
  IFACEMETHOD_ (ULONG, AddRef) (void)  { return 1; }
  IFACEMETHOD_ (ULONG, Release) (void) { return 1; }
93

94
  // IDWriteFontFileStream methods
95 96 97 98 99
  virtual HRESULT STDMETHODCALLTYPE
  ReadFileFragment (void const** fragmentStart,
		    UINT64 fileOffset,
		    UINT64 fragmentSize,
		    OUT void** fragmentContext)
100 101
  {
    // We are required to do bounds checking.
102
    if (fileOffset + fragmentSize > mSize) return E_FAIL;
103

104 105
    // truncate the 64 bit fileOffset to size_t sized index into mData
    size_t index = static_cast<size_t> (fileOffset);
106

107 108 109 110
    // We should be alive for the duration of this.
    *fragmentStart = &mData[index];
    *fragmentContext = nullptr;
    return S_OK;
111 112
  }

113 114
  virtual void STDMETHODCALLTYPE
  ReleaseFileFragment (void* fragmentContext) {}
115

116 117
  virtual HRESULT STDMETHODCALLTYPE
  GetFileSize (OUT UINT64* fileSize)
118
  {
119 120
    *fileSize = mSize;
    return S_OK;
121 122
  }

123 124
  virtual HRESULT STDMETHODCALLTYPE
  GetLastWriteTime (OUT UINT64* lastWriteTime) { return E_NOTIMPL; }
125
};
126 127


128 129 130
/*
* shaper face data
*/
131

B
Rename  
Behdad Esfahbod 已提交
132
struct hb_directwrite_face_data_t
E
Ebrahim Byagowi 已提交
133
{
134 135 136 137 138 139
  IDWriteFactory *dwriteFactory;
  IDWriteFontFile *fontFile;
  IDWriteFontFileStream *fontFileStream;
  IDWriteFontFileLoader *fontFileLoader;
  IDWriteFontFace *fontFace;
  hb_blob_t *faceBlob;
140
};
141

B
Rename  
Behdad Esfahbod 已提交
142
hb_directwrite_face_data_t *
143
_hb_directwrite_shaper_face_data_create (hb_face_t *face)
144
{
B
Rename  
Behdad Esfahbod 已提交
145
  hb_directwrite_face_data_t *data = new hb_directwrite_face_data_t;
146
  if (unlikely (!data))
B
Behdad Esfahbod 已提交
147
    return nullptr;
148

149 150
  // TODO: factory and fontFileLoader should be cached separately
  IDWriteFactory* dwriteFactory;
151 152
  DWriteCreateFactory (DWRITE_FACTORY_TYPE_SHARED, __uuidof (IDWriteFactory),
		       (IUnknown**) &dwriteFactory);
153 154

  HRESULT hr;
155
  hb_blob_t *blob = hb_face_reference_blob (face);
156 157 158
  DWriteFontFileStream *fontFileStream;
  fontFileStream = new DWriteFontFileStream ((uint8_t *) hb_blob_get_data (blob, nullptr),
					     hb_blob_get_length (blob));
159

160
  DWriteFontFileLoader *fontFileLoader = new DWriteFontFileLoader (fontFileStream);
161 162 163 164 165
  dwriteFactory->RegisterFontFileLoader (fontFileLoader);

  IDWriteFontFile *fontFile;
  uint64_t fontFileKey = 0;
  hr = dwriteFactory->CreateCustomFontFileReference (&fontFileKey, sizeof (fontFileKey),
166
						     fontFileLoader, &fontFile);
167 168 169

#define FAIL(...) \
  HB_STMT_START { \
B
Behdad Esfahbod 已提交
170
    DEBUG_MSG (DIRECTWRITE, nullptr, __VA_ARGS__); \
171
    return nullptr; \
172 173
  } HB_STMT_END;

E
Ebrahim Byagowi 已提交
174
  if (FAILED (hr))
175
    FAIL ("Failed to load font file from data!");
176

177 178 179
  BOOL isSupported;
  DWRITE_FONT_FILE_TYPE fileType;
  DWRITE_FONT_FACE_TYPE faceType;
E
Ebrahim Byagowi 已提交
180
  uint32_t numberOfFaces;
181
  hr = fontFile->Analyze (&isSupported, &fileType, &faceType, &numberOfFaces);
E
Ebrahim Byagowi 已提交
182
  if (FAILED (hr) || !isSupported)
183
    FAIL ("Font file is not supported.");
184

185 186 187 188
#undef FAIL

  IDWriteFontFace *fontFace;
  dwriteFactory->CreateFontFace (faceType, 1, &fontFile, 0,
189
				 DWRITE_FONT_SIMULATIONS_NONE, &fontFace);
190 191 192

  data->dwriteFactory = dwriteFactory;
  data->fontFile = fontFile;
193
  data->fontFileStream = fontFileStream;
194 195
  data->fontFileLoader = fontFileLoader;
  data->fontFace = fontFace;
196
  data->faceBlob = blob;
197

198 199 200 201
  return data;
}

void
B
Rename  
Behdad Esfahbod 已提交
202
_hb_directwrite_shaper_face_data_destroy (hb_directwrite_face_data_t *data)
203
{
204 205 206 207
  if (data->fontFace)
    data->fontFace->Release ();
  if (data->fontFile)
    data->fontFile->Release ();
E
Ebrahim Byagowi 已提交
208 209
  if (data->dwriteFactory)
  {
210
    if (data->fontFileLoader)
211 212
      data->dwriteFactory->UnregisterFontFileLoader (data->fontFileLoader);
    data->dwriteFactory->Release ();
213 214
  }
  if (data->fontFileLoader)
215
    delete data->fontFileLoader;
216
  if (data->fontFileStream)
217
    delete data->fontFileStream;
218 219 220
  if (data->faceBlob)
    hb_blob_destroy (data->faceBlob);
  if (data)
221
    delete data;
222 223 224 225 226 227 228
}


/*
 * shaper font data
 */

229
struct hb_directwrite_font_data_t {};
230

B
Rename  
Behdad Esfahbod 已提交
231
hb_directwrite_font_data_t *
232 233
_hb_directwrite_shaper_font_data_create (hb_font_t *font)
{
B
Rename  
Behdad Esfahbod 已提交
234
  hb_directwrite_font_data_t *data = new hb_directwrite_font_data_t;
235
  if (unlikely (!data))
B
Behdad Esfahbod 已提交
236
    return nullptr;
237 238 239 240 241

  return data;
}

void
B
Rename  
Behdad Esfahbod 已提交
242
_hb_directwrite_shaper_font_data_destroy (hb_directwrite_font_data_t *data)
243
{
244
  delete data;
245 246 247
}


248
// Most of TextAnalysis is originally written by Bas Schouten for Mozilla project
249
// but now is relicensed to MIT for HarfBuzz use
250
class TextAnalysis : public IDWriteTextAnalysisSource, public IDWriteTextAnalysisSink
251 252 253
{
public:

254 255 256 257
  IFACEMETHOD (QueryInterface) (IID const& iid, OUT void** ppObject)
  { return S_OK; }
  IFACEMETHOD_ (ULONG, AddRef) (void) { return 1; }
  IFACEMETHOD_ (ULONG, Release) (void) { return 1; }
258

259
  // A single contiguous run of characters containing the same analysis
260 261 262
  // results.
  struct Run
  {
263 264 265
    uint32_t mTextStart;   // starting text position of this run
    uint32_t mTextLength;  // number of contiguous code units covered
    uint32_t mGlyphStart;  // starting glyph in the glyphs array
266
    uint32_t mGlyphCount;  // number of glyphs associated with this run
267 268
    // text
    DWRITE_SCRIPT_ANALYSIS mScript;
269
    uint8_t mBidiLevel;
270 271
    bool mIsSideways;

272
    bool ContainsTextPosition (uint32_t aTextPosition) const
273
    {
274 275
      return aTextPosition >= mTextStart &&
	     aTextPosition <  mTextStart + mTextLength;
276 277 278 279 280 281
    }

    Run *nextRun;
  };

public:
282 283 284 285 286
  TextAnalysis (const wchar_t* text, uint32_t textLength,
		const wchar_t* localeName, DWRITE_READING_DIRECTION readingDirection)
	       : mText (text), mTextLength (textLength), mLocaleName (localeName),
		 mReadingDirection (readingDirection), mCurrentRun (nullptr) {}
  ~TextAnalysis (void)
E
Ebrahim Byagowi 已提交
287
  {
288
    // delete runs, except mRunHead which is part of the TextAnalysis object
E
Ebrahim Byagowi 已提交
289 290
    for (Run *run = mRunHead.nextRun; run;)
    {
291 292
      Run *origRun = run;
      run = run->nextRun;
293
      delete origRun;
294 295 296
    }
  }

297 298
  STDMETHODIMP
  GenerateResults (IDWriteTextAnalyzer* textAnalyzer, Run **runHead)
E
Ebrahim Byagowi 已提交
299
  {
300 301 302 303 304 305 306 307 308 309 310
    // Analyzes the text using the script analyzer and returns
    // the result as a series of runs.

    HRESULT hr = S_OK;

    // Initially start out with one result that covers the entire range.
    // This result will be subdivided by the analysis processes.
    mRunHead.mTextStart = 0;
    mRunHead.mTextLength = mTextLength;
    mRunHead.mBidiLevel =
      (mReadingDirection == DWRITE_READING_DIRECTION_RIGHT_TO_LEFT);
B
Behdad Esfahbod 已提交
311
    mRunHead.nextRun = nullptr;
312 313 314
    mCurrentRun = &mRunHead;

    // Call each of the analyzers in sequence, recording their results.
E
Ebrahim Byagowi 已提交
315
    if (SUCCEEDED (hr = textAnalyzer->AnalyzeScript (this, 0, mTextLength, this)))
316 317 318 319 320 321 322
      *runHead = &mRunHead;

    return hr;
  }

  // IDWriteTextAnalysisSource implementation

323 324 325 326
  IFACEMETHODIMP
  GetTextAtPosition (uint32_t textPosition,
		     OUT wchar_t const** textString,
		     OUT uint32_t* textLength)
327
  {
E
Ebrahim Byagowi 已提交
328 329
    if (textPosition >= mTextLength)
    {
330
      // No text at this position, valid query though.
B
Behdad Esfahbod 已提交
331
      *textString = nullptr;
332 333
      *textLength = 0;
    }
E
Ebrahim Byagowi 已提交
334 335
    else
    {
336 337 338 339 340 341
      *textString = mText + textPosition;
      *textLength = mTextLength - textPosition;
    }
    return S_OK;
  }

342 343 344 345
  IFACEMETHODIMP
  GetTextBeforePosition (uint32_t textPosition,
			 OUT wchar_t const** textString,
			 OUT uint32_t* textLength)
346
  {
E
Ebrahim Byagowi 已提交
347 348
    if (textPosition == 0 || textPosition > mTextLength)
    {
349
      // Either there is no text before here (== 0), or this
B
Bruce Mitchener 已提交
350
      // is an invalid position. The query is considered valid though.
B
Behdad Esfahbod 已提交
351
      *textString = nullptr;
352 353
      *textLength = 0;
    }
E
Ebrahim Byagowi 已提交
354 355
    else
    {
356 357 358 359 360 361
      *textString = mText;
      *textLength = textPosition;
    }
    return S_OK;
  }

362
  IFACEMETHODIMP_ (DWRITE_READING_DIRECTION)
363
  GetParagraphReadingDirection (void) { return mReadingDirection; }
364

365 366 367
  IFACEMETHODIMP GetLocaleName (uint32_t textPosition, uint32_t* textLength,
				wchar_t const** localeName)
  { return S_OK; }
368 369

  IFACEMETHODIMP
370 371 372
  GetNumberSubstitution (uint32_t textPosition,
			 OUT uint32_t* textLength,
			 OUT IDWriteNumberSubstitution** numberSubstitution)
373 374
  {
    // We do not support number substitution.
B
Behdad Esfahbod 已提交
375
    *numberSubstitution = nullptr;
376 377 378 379 380 381 382 383
    *textLength = mTextLength - textPosition;

    return S_OK;
  }

  // IDWriteTextAnalysisSink implementation

  IFACEMETHODIMP
384 385
  SetScriptAnalysis (uint32_t textPosition, uint32_t textLength,
		     DWRITE_SCRIPT_ANALYSIS const* scriptAnalysis)
386
  {
387 388
    SetCurrentRun (textPosition);
    SplitCurrentRun (textPosition);
389 390
    while (textLength > 0)
    {
391
      Run *run = FetchNextRun (&textLength);
392 393 394 395 396 397 398
      run->mScript = *scriptAnalysis;
    }

    return S_OK;
  }

  IFACEMETHODIMP
399 400 401 402
  SetLineBreakpoints (uint32_t textPosition,
		      uint32_t textLength,
		      const DWRITE_LINE_BREAKPOINT* lineBreakpoints)
  { return S_OK; }
403

404 405 406
  IFACEMETHODIMP SetBidiLevel (uint32_t textPosition, uint32_t textLength,
			       uint8_t explicitLevel, uint8_t resolvedLevel)
  { return S_OK; }
407 408

  IFACEMETHODIMP
409 410 411
  SetNumberSubstitution (uint32_t textPosition, uint32_t textLength,
			 IDWriteNumberSubstitution* numberSubstitution)
  { return S_OK; }
412 413

protected:
414
  Run *FetchNextRun (IN OUT uint32_t* textLength)
415 416 417 418 419 420 421 422
  {
    // Used by the sink setters, this returns a reference to the next run.
    // Position and length are adjusted to now point after the current run
    // being returned.

    Run *origRun = mCurrentRun;
    // Split the tail if needed (the length remaining is less than the
    // current run's size).
423 424 425
    if (*textLength < mCurrentRun->mTextLength)
      SplitCurrentRun (mCurrentRun->mTextStart + *textLength);
    else
426 427 428 429 430 431 432 433
      // Just advance the current run.
      mCurrentRun = mCurrentRun->nextRun;
    *textLength -= origRun->mTextLength;

    // Return a reference to the run that was just current.
    return origRun;
  }

434
  void SetCurrentRun (uint32_t textPosition)
435 436 437 438 439 440
  {
    // Move the current run to the given position.
    // Since the analyzers generally return results in a forward manner,
    // this will usually just return early. If not, find the
    // corresponding run for the text position.

441
    if (mCurrentRun && mCurrentRun->ContainsTextPosition (textPosition))
442 443
      return;

E
Ebrahim Byagowi 已提交
444
    for (Run *run = &mRunHead; run; run = run->nextRun)
445 446
      if (run->ContainsTextPosition (textPosition))
      {
447 448
	mCurrentRun = run;
	return;
449
      }
450
    assert (0); // We should always be able to find the text position in one of our runs
451 452
  }

453
  void SplitCurrentRun (uint32_t splitPosition)
454
  {
455 456
    if (!mCurrentRun)
    {
457
      assert (0); // SplitCurrentRun called without current run
458 459 460 461
      // Shouldn't be calling this when no current run is set!
      return;
    }
    // Split the current run.
462 463
    if (splitPosition <= mCurrentRun->mTextStart)
    {
464 465 466 467
      // No need to split, already the start of a run
      // or before it. Usually the first.
      return;
    }
468
    Run *newRun = new Run;
469 470 471 472 473 474 475 476

    *newRun = *mCurrentRun;

    // Insert the new run in our linked list.
    newRun->nextRun = mCurrentRun->nextRun;
    mCurrentRun->nextRun = newRun;

    // Adjust runs' text positions and lengths.
477
    uint32_t splitPoint = splitPosition - mCurrentRun->mTextStart;
478 479 480 481 482 483 484 485 486 487
    newRun->mTextStart += splitPoint;
    newRun->mTextLength -= splitPoint;
    mCurrentRun->mTextLength = splitPoint;
    mCurrentRun = newRun;
  }

protected:
  // Input
  // (weak references are fine here, since this class is a transient
  //  stack-based helper that doesn't need to copy data)
488 489 490
  uint32_t mTextLength;
  const wchar_t* mText;
  const wchar_t* mLocaleName;
491 492 493 494 495 496 497 498 499
  DWRITE_READING_DIRECTION mReadingDirection;

  // Current processing state.
  Run *mCurrentRun;

  // Output is a list of runs starting here
  Run  mRunHead;
};

500
static inline uint16_t hb_uint16_swap (const uint16_t v)
501
{ return (v >> 8) | (v << 8); }
502
static inline uint32_t hb_uint32_swap (const uint32_t v)
503
{ return (hb_uint16_swap (v) << 16) | hb_uint16_swap (v >> 16); }
504 505 506 507 508

/*
 * shaper
 */

509
static hb_bool_t
510
_hb_directwrite_shape_full (hb_shape_plan_t    *shape_plan,
511 512 513 514 515
			    hb_font_t          *font,
			    hb_buffer_t        *buffer,
			    const hb_feature_t *features,
			    unsigned int        num_features,
			    float               lineWidth)
516 517
{
  hb_face_t *face = font->face;
518 519
  const hb_directwrite_face_data_t *face_data = face->data.directwrite;
  const hb_directwrite_font_data_t *font_data = font->data.directwrite;
520 521
  IDWriteFactory *dwriteFactory = face_data->dwriteFactory;
  IDWriteFontFace *fontFace = face_data->fontFace;
522 523

  IDWriteTextAnalyzer* analyzer;
524
  dwriteFactory->CreateTextAnalyzer (&analyzer);
525 526 527 528 529 530 531 532 533 534 535 536 537 538

  unsigned int scratch_size;
  hb_buffer_t::scratch_buffer_t *scratch = buffer->get_scratch_buffer (&scratch_size);
#define ALLOCATE_ARRAY(Type, name, len) \
  Type *name = (Type *) scratch; \
  { \
    unsigned int _consumed = DIV_CEIL ((len) * sizeof (Type), sizeof (*scratch)); \
    assert (_consumed <= scratch_size); \
    scratch += _consumed; \
    scratch_size -= _consumed; \
  }

#define utf16_index() var1.u32

539
  ALLOCATE_ARRAY (wchar_t, textString, buffer->len * 2);
540 541 542 543 544

  unsigned int chars_len = 0;
  for (unsigned int i = 0; i < buffer->len; i++)
  {
    hb_codepoint_t c = buffer->info[i].codepoint;
545 546
    buffer->info[i].utf16_index () = chars_len;
    if (likely (c <= 0xFFFFu))
E
Ebrahim Byagowi 已提交
547
      textString[chars_len++] = c;
548
    else if (unlikely (c > 0x10FFFFu))
E
Ebrahim Byagowi 已提交
549
      textString[chars_len++] = 0xFFFDu;
E
Ebrahim Byagowi 已提交
550 551
    else
    {
E
Ebrahim Byagowi 已提交
552
      textString[chars_len++] = 0xD800u + ((c - 0x10000u) >> 10);
B
Behdad Esfahbod 已提交
553
      textString[chars_len++] = 0xDC00u + ((c - 0x10000u) & ((1u << 10) - 1));
554 555 556
    }
  }

557
  ALLOCATE_ARRAY (WORD, log_clusters, chars_len);
E
Ebrahim Byagowi 已提交
558 559 560
  /* Need log_clusters to assign features. */
  chars_len = 0;
  for (unsigned int i = 0; i < buffer->len; i++)
561
  {
E
Ebrahim Byagowi 已提交
562 563 564 565 566
    hb_codepoint_t c = buffer->info[i].codepoint;
    unsigned int cluster = buffer->info[i].cluster;
    log_clusters[chars_len++] = cluster;
    if (hb_in_range (c, 0x10000u, 0x10FFFFu))
      log_clusters[chars_len++] = cluster; /* Surrogates. */
567 568 569 570
  }

  // TODO: Handle TEST_DISABLE_OPTIONAL_LIGATURES

571 572 573 574
  DWRITE_READING_DIRECTION readingDirection;
  readingDirection = buffer->props.direction ?
		     DWRITE_READING_DIRECTION_RIGHT_TO_LEFT :
		     DWRITE_READING_DIRECTION_LEFT_TO_RIGHT;
575

K
Khaled Hosny 已提交
576
  /*
577 578 579 580
  * There's an internal 16-bit limit on some things inside the analyzer,
  * but we never attempt to shape a word longer than 64K characters
  * in a single gfxShapedWord, so we cannot exceed that limit.
  */
581
  uint32_t textLength = buffer->len;
582

583
  TextAnalysis analysis (textString, textLength, nullptr, readingDirection);
584
  TextAnalysis::Run *runHead;
585
  HRESULT hr;
586
  hr = analysis.GenerateResults (analyzer, &runHead);
587

588 589
#define FAIL(...) \
  HB_STMT_START { \
B
Behdad Esfahbod 已提交
590
    DEBUG_MSG (DIRECTWRITE, nullptr, __VA_ARGS__); \
591 592 593
    return false; \
  } HB_STMT_END;

E
Ebrahim Byagowi 已提交
594
  if (FAILED (hr))
595
    FAIL ("Analyzer failed to generate results.");
596

597 598
  uint32_t maxGlyphCount = 3 * textLength / 2 + 16;
  uint32_t glyphCount;
E
Ebrahim Byagowi 已提交
599
  bool isRightToLeft = HB_DIRECTION_IS_BACKWARD (buffer->props.direction);
600

E
Ebrahim Byagowi 已提交
601
  const wchar_t localeName[20] = {0};
B
Behdad Esfahbod 已提交
602
  if (buffer->props.language != nullptr)
E
Ebrahim Byagowi 已提交
603
    mbstowcs ((wchar_t*) localeName,
604
	      hb_language_to_string (buffer->props.language), 20);
605

E
Ebrahim Byagowi 已提交
606 607 608
  // TODO: it does work but doesn't care about ranges
  DWRITE_TYPOGRAPHIC_FEATURES typographic_features;
  typographic_features.featureCount = num_features;
E
Ebrahim Byagowi 已提交
609
  if (num_features)
610
  {
E
Ebrahim Byagowi 已提交
611
    typographic_features.features = new DWRITE_FONT_FEATURE[num_features];
612 613
    for (unsigned int i = 0; i < num_features; ++i)
    {
E
Ebrahim Byagowi 已提交
614
      typographic_features.features[i].nameTag = (DWRITE_FONT_FEATURE_TAG)
615
						 hb_uint32_swap (features[i].tag);
E
Ebrahim Byagowi 已提交
616
      typographic_features.features[i].parameter = features[i].value;
617
    }
E
Ebrahim Byagowi 已提交
618
  }
619 620
  const DWRITE_TYPOGRAPHIC_FEATURES* dwFeatures;
  dwFeatures = (const DWRITE_TYPOGRAPHIC_FEATURES*) &typographic_features;
621
  const uint32_t featureRangeLengths[] = { textLength };
E
Ebrahim Byagowi 已提交
622
  //
E
Ebrahim Byagowi 已提交
623

624 625 626 627
  uint16_t* clusterMap;
  clusterMap = new uint16_t[textLength];
  DWRITE_SHAPING_TEXT_PROPERTIES* textProperties;
  textProperties = new DWRITE_SHAPING_TEXT_PROPERTIES[textLength];
E
Ebrahim Byagowi 已提交
628
retry_getglyphs:
629
  uint16_t* glyphIndices = new uint16_t[maxGlyphCount];
630 631
  DWRITE_SHAPING_GLYPH_PROPERTIES* glyphProperties;
  glyphProperties = new DWRITE_SHAPING_GLYPH_PROPERTIES[maxGlyphCount];
E
Ebrahim Byagowi 已提交
632

B
Minor  
Behdad Esfahbod 已提交
633
  hr = analyzer->GetGlyphs (textString, textLength, fontFace, false,
634 635 636 637
			    isRightToLeft, &runHead->mScript, localeName,
			    nullptr, &dwFeatures, featureRangeLengths, 1,
			    maxGlyphCount, clusterMap, textProperties,
			    glyphIndices, glyphProperties, &glyphCount);
E
Ebrahim Byagowi 已提交
638 639 640

  if (unlikely (hr == HRESULT_FROM_WIN32 (ERROR_INSUFFICIENT_BUFFER)))
  {
641 642
    delete [] glyphIndices;
    delete [] glyphProperties;
643

E
Ebrahim Byagowi 已提交
644
    maxGlyphCount *= 2;
645 646

    goto retry_getglyphs;
647
  }
E
Ebrahim Byagowi 已提交
648
  if (FAILED (hr))
649
    FAIL ("Analyzer failed to get glyphs.");
650

651 652
  float* glyphAdvances = new float[maxGlyphCount];
  DWRITE_GLYPH_OFFSET* glyphOffsets = new DWRITE_GLYPH_OFFSET[maxGlyphCount];
653 654

  /* The -2 in the following is to compensate for possible
655 656
   * alignment needed after the WORD array.  sizeof (WORD) == 2. */
  unsigned int glyphs_size = (scratch_size * sizeof (int) - 2)
657 658 659 660 661
			     / (sizeof (WORD) +
			        sizeof (DWRITE_SHAPING_GLYPH_PROPERTIES) +
			        sizeof (int) +
			        sizeof (DWRITE_GLYPH_OFFSET) +
			        sizeof (uint32_t));
E
Ebrahim Byagowi 已提交
662
  ALLOCATE_ARRAY (uint32_t, vis_clusters, glyphs_size);
663 664 665

#undef ALLOCATE_ARRAY

666
  int fontEmSize = font->face->get_upem ();
667
  if (fontEmSize < 0) fontEmSize = -fontEmSize;
E
Ebrahim Byagowi 已提交
668

669
  if (fontEmSize < 0) fontEmSize = -fontEmSize;
E
Ebrahim Byagowi 已提交
670 671 672
  double x_mult = (double) font->x_scale / fontEmSize;
  double y_mult = (double) font->y_scale / fontEmSize;

673 674 675 676 677 678
  hr = analyzer->GetGlyphPlacements (textString, clusterMap, textProperties,
				     textLength, glyphIndices, glyphProperties,
				     glyphCount, fontFace, fontEmSize,
				     false, isRightToLeft, &runHead->mScript, localeName,
				     &dwFeatures, featureRangeLengths, 1,
				     glyphAdvances, glyphOffsets);
E
Ebrahim Byagowi 已提交
679 680

  if (FAILED (hr))
681
    FAIL ("Analyzer failed to get glyph placements.");
682

683 684
  IDWriteTextAnalyzer1* analyzer1;
  analyzer->QueryInterface (&analyzer1);
E
Ebrahim Byagowi 已提交
685

686
  if (analyzer1 && lineWidth)
E
Ebrahim Byagowi 已提交
687
  {
688
    DWRITE_JUSTIFICATION_OPPORTUNITY* justificationOpportunities =
689
      new DWRITE_JUSTIFICATION_OPPORTUNITY[maxGlyphCount];
690 691 692 693
    hr = analyzer1->GetJustificationOpportunities (fontFace, fontEmSize, runHead->mScript,
						   textLength, glyphCount, textString,
						   clusterMap, glyphProperties,
						   justificationOpportunities);
E
Ebrahim Byagowi 已提交
694

695 696
    if (FAILED (hr))
      FAIL ("Analyzer failed to get justification opportunities.");
E
Ebrahim Byagowi 已提交
697

698 699
    float* justifiedGlyphAdvances = new float[maxGlyphCount];
    DWRITE_GLYPH_OFFSET* justifiedGlyphOffsets = new DWRITE_GLYPH_OFFSET[glyphCount];
700
    hr = analyzer1->JustifyGlyphAdvances (lineWidth, glyphCount, justificationOpportunities,
701 702
					  glyphAdvances, glyphOffsets, justifiedGlyphAdvances,
					  justifiedGlyphOffsets);
E
Ebrahim Byagowi 已提交
703

704
    if (FAILED (hr)) FAIL ("Analyzer failed to get justify glyph advances.");
705

706 707
    DWRITE_SCRIPT_PROPERTIES scriptProperties;
    hr = analyzer1->GetScriptProperties (runHead->mScript, &scriptProperties);
708
    if (FAILED (hr)) FAIL ("Analyzer failed to get script properties.");
709 710 711 712 713
    uint32_t justificationCharacter = scriptProperties.justificationCharacter;

    // if a script justificationCharacter is not space, it can have GetJustifiedGlyphs
    if (justificationCharacter != 32)
    {
714
      uint16_t* modifiedClusterMap = new uint16_t[textLength];
715
    retry_getjustifiedglyphs:
716 717
      uint16_t* modifiedGlyphIndices = new uint16_t[maxGlyphCount];
      float* modifiedGlyphAdvances = new float[maxGlyphCount];
718
      DWRITE_GLYPH_OFFSET* modifiedGlyphOffsets = new DWRITE_GLYPH_OFFSET[maxGlyphCount];
719 720
      uint32_t actualGlyphsCount;
      hr = analyzer1->GetJustifiedGlyphs (fontFace, fontEmSize, runHead->mScript,
721 722 723 724 725 726
					  textLength, glyphCount, maxGlyphCount,
					  clusterMap, glyphIndices, glyphAdvances,
					  justifiedGlyphAdvances, justifiedGlyphOffsets,
					  glyphProperties, &actualGlyphsCount,
					  modifiedClusterMap, modifiedGlyphIndices,
					  modifiedGlyphAdvances, modifiedGlyphOffsets);
727

728 729
      if (hr == HRESULT_FROM_WIN32 (ERROR_INSUFFICIENT_BUFFER))
      {
730 731 732 733
	maxGlyphCount = actualGlyphsCount;
	delete [] modifiedGlyphIndices;
	delete [] modifiedGlyphAdvances;
	delete [] modifiedGlyphOffsets;
734

735
	maxGlyphCount = actualGlyphsCount;
736

737
	goto retry_getjustifiedglyphs;
738 739
      }
      if (FAILED (hr))
740
	FAIL ("Analyzer failed to get justified glyphs.");
741

742 743 744 745
      delete [] clusterMap;
      delete [] glyphIndices;
      delete [] glyphAdvances;
      delete [] glyphOffsets;
E
Ebrahim Byagowi 已提交
746

747 748 749 750 751
      glyphCount = actualGlyphsCount;
      clusterMap = modifiedClusterMap;
      glyphIndices = modifiedGlyphIndices;
      glyphAdvances = modifiedGlyphAdvances;
      glyphOffsets = modifiedGlyphOffsets;
E
Ebrahim Byagowi 已提交
752

753 754
      delete [] justifiedGlyphAdvances;
      delete [] justifiedGlyphOffsets;
755 756 757
    }
    else
    {
758 759
      delete [] glyphAdvances;
      delete [] glyphOffsets;
760

761 762 763
      glyphAdvances = justifiedGlyphAdvances;
      glyphOffsets = justifiedGlyphOffsets;
    }
E
Ebrahim Byagowi 已提交
764

765
    delete [] justificationOpportunities;
766
  }
E
Ebrahim Byagowi 已提交
767

768 769 770 771
  /* Ok, we've got everything we need, now compose output buffer,
   * very, *very*, carefully! */

  /* Calculate visual-clusters.  That's what we ship. */
E
Ebrahim Byagowi 已提交
772
  for (unsigned int i = 0; i < glyphCount; i++)
773
    vis_clusters[i] = -1;
E
Ebrahim Byagowi 已提交
774 775 776
  for (unsigned int i = 0; i < buffer->len; i++)
  {
    uint32_t *p =
777
      &vis_clusters[log_clusters[buffer->info[i].utf16_index ()]];
778
    *p = MIN (*p, buffer->info[i].cluster);
779
  }
E
Ebrahim Byagowi 已提交
780
  for (unsigned int i = 1; i < glyphCount; i++)
781 782 783 784 785
    if (vis_clusters[i] == -1)
      vis_clusters[i] = vis_clusters[i - 1];

#undef utf16_index

E
Ebrahim Byagowi 已提交
786
  if (unlikely (!buffer->ensure (glyphCount)))
787
    FAIL ("Buffer in error");
788 789 790 791 792

#undef FAIL

  /* Set glyph infos */
  buffer->len = 0;
E
Ebrahim Byagowi 已提交
793
  for (unsigned int i = 0; i < glyphCount; i++)
794 795 796
  {
    hb_glyph_info_t *info = &buffer->info[buffer->len++];

E
Ebrahim Byagowi 已提交
797
    info->codepoint = glyphIndices[i];
798 799 800
    info->cluster = vis_clusters[i];

    /* The rest is crap.  Let's store position info there for now. */
E
Ebrahim Byagowi 已提交
801 802 803
    info->mask = glyphAdvances[i];
    info->var1.i32 = glyphOffsets[i].advanceOffset;
    info->var2.i32 = glyphOffsets[i].ascenderOffset;
804 805 806 807
  }

  /* Set glyph positions */
  buffer->clear_positions ();
E
Ebrahim Byagowi 已提交
808
  for (unsigned int i = 0; i < glyphCount; i++)
809 810 811 812 813
  {
    hb_glyph_info_t *info = &buffer->info[i];
    hb_glyph_position_t *pos = &buffer->pos[i];

    /* TODO vertical */
E
Ebrahim Byagowi 已提交
814
    pos->x_advance = x_mult * (int32_t) info->mask;
815
    pos->x_offset = x_mult * (isRightToLeft ? -info->var1.i32 : info->var1.i32);
E
Ebrahim Byagowi 已提交
816
    pos->y_offset = y_mult * info->var2.i32;
817 818
  }

819
  if (isRightToLeft) hb_buffer_reverse (buffer);
820

821 822 823 824 825 826
  delete [] clusterMap;
  delete [] glyphIndices;
  delete [] textProperties;
  delete [] glyphProperties;
  delete [] glyphAdvances;
  delete [] glyphOffsets;
E
Ebrahim Byagowi 已提交
827 828

  if (num_features)
E
Ebrahim Byagowi 已提交
829
    delete [] typographic_features.features;
E
Ebrahim Byagowi 已提交
830

831 832
  /* Wow, done! */
  return true;
K
Khaled Hosny 已提交
833
}
834 835

hb_bool_t
836
_hb_directwrite_shape (hb_shape_plan_t    *shape_plan,
837 838 839 840
		       hb_font_t          *font,
		       hb_buffer_t        *buffer,
		       const hb_feature_t *features,
		       unsigned int        num_features)
841
{
842
  return _hb_directwrite_shape_full (shape_plan, font, buffer,
843
				     features, num_features, 0);
844 845 846 847 848 849 850
}

/*
 * Public [experimental] API
 */

hb_bool_t
851
hb_directwrite_shape_experimental_width (hb_font_t          *font,
852 853 854 855
					 hb_buffer_t        *buffer,
					 const hb_feature_t *features,
					 unsigned int        num_features,
					 float               width)
856
{
857
  static const char *shapers = "directwrite";
858 859 860
  hb_shape_plan_t *shape_plan;
  shape_plan = hb_shape_plan_create_cached (font->face, &buffer->props,
					    features, num_features, &shapers);
861
  hb_bool_t res = _hb_directwrite_shape_full (shape_plan, font, buffer,
862
					      features, num_features, width);
863

864
  buffer->unsafe_to_break_all ();
865 866 867

  return res;
}