hb-directwrite.cc 25.8 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
#include "hb.hh"
26
#define HB_SHAPER directwrite
27
#include "hb-shaper-impl.hh"
28

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

#include "hb-directwrite.h"


B
Minor  
Behdad Esfahbod 已提交
34 35
HB_SHAPER_DATA_ENSURE_DEFINE (directwrite, face);
HB_SHAPER_DATA_ENSURE_DEFINE (directwrite, font);
36 37 38 39 40 41 42 43 44 45 46


/*
 * 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.
 */
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); }
void operator delete [] (void* pointer) { free (pointer); }
47 48


49 50 51
/*
 * DirectWrite font stream helpers
 */
52

53 54 55 56
// 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
57
{
58 59 60
private:
  IDWriteFontFileStream *mFontFileStream;
public:
61
  DWriteFontFileLoader (IDWriteFontFileStream *fontFileStream)
62
  {
63
    mFontFileStream = fontFileStream;
64 65
  }

66
  // IUnknown interface
67 68 69
  IFACEMETHOD (QueryInterface) (IID const& iid, OUT void** ppObject) { return S_OK; }
  IFACEMETHOD_ (ULONG, AddRef) () { return 1; }
  IFACEMETHOD_ (ULONG, Release) () { return 1; }
70

71
  // IDWriteFontFileLoader methods
72
  virtual HRESULT STDMETHODCALLTYPE CreateStreamFromKey (void const* fontFileReferenceKey,
E
Ebrahim Byagowi 已提交
73
    uint32_t fontFileReferenceKeySize,
74 75 76 77 78 79
    OUT IDWriteFontFileStream** fontFileStream)
  {
    *fontFileStream = mFontFileStream;
    return S_OK;
  }
};
80

81 82 83 84 85 86
class DWriteFontFileStream : public IDWriteFontFileStream
{
private:
  uint8_t *mData;
  uint32_t mSize;
public:
87
  DWriteFontFileStream (uint8_t *aData, uint32_t aSize)
88 89 90 91
  {
    mData = aData;
    mSize = aSize;
  }
92

93
  // IUnknown interface
94 95 96
  IFACEMETHOD (QueryInterface) (IID const& iid, OUT void** ppObject) { return S_OK; }
  IFACEMETHOD_ (ULONG, AddRef) () { return 1; }
  IFACEMETHOD_ (ULONG, Release) () { return 1; }
97

98
  // IDWriteFontFileStream methods
99
  virtual HRESULT STDMETHODCALLTYPE ReadFileFragment (void const** fragmentStart,
100 101 102 103 104
    UINT64 fileOffset,
    UINT64 fragmentSize,
    OUT void** fragmentContext)
  {
    // We are required to do bounds checking.
E
Ebrahim Byagowi 已提交
105
    if (fileOffset + fragmentSize > mSize)
106
      return E_FAIL;
107

108 109
    // truncate the 64 bit fileOffset to size_t sized index into mData
    size_t index = static_cast<size_t> (fileOffset);
110

111 112 113 114
    // We should be alive for the duration of this.
    *fragmentStart = &mData[index];
    *fragmentContext = nullptr;
    return S_OK;
115 116
  }

117
  virtual void STDMETHODCALLTYPE ReleaseFileFragment (void* fragmentContext) { }
118

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

125
  virtual HRESULT STDMETHODCALLTYPE GetLastWriteTime (OUT UINT64* lastWriteTime)
126
  {
127
    return E_NOTIMPL;
128
  }
129
};
130 131


132 133 134
/*
* shaper face data
*/
135

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

B
Rename  
Behdad Esfahbod 已提交
146
hb_directwrite_face_data_t *
147
_hb_directwrite_shaper_face_data_create (hb_face_t *face)
148
{
B
Rename  
Behdad Esfahbod 已提交
149
  hb_directwrite_face_data_t *data = new hb_directwrite_face_data_t;
150
  if (unlikely (!data))
B
Behdad Esfahbod 已提交
151
    return nullptr;
152

153 154 155 156 157 158 159 160 161
  // TODO: factory and fontFileLoader should be cached separately
  IDWriteFactory* dwriteFactory;
  DWriteCreateFactory (
    DWRITE_FACTORY_TYPE_SHARED,
    __uuidof (IDWriteFactory),
    (IUnknown**) &dwriteFactory
  );

  HRESULT hr;
162
  hb_blob_t *blob = hb_face_reference_blob (face);
163 164
  DWriteFontFileStream *fontFileStream = new DWriteFontFileStream (
    (uint8_t *) hb_blob_get_data (blob, nullptr),
165 166
    hb_blob_get_length (blob));

167
  DWriteFontFileLoader *fontFileLoader = new DWriteFontFileLoader (fontFileStream);
168 169 170 171 172 173 174 175 176
  dwriteFactory->RegisterFontFileLoader (fontFileLoader);

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

#define FAIL(...) \
  HB_STMT_START { \
B
Behdad Esfahbod 已提交
177
    DEBUG_MSG (DIRECTWRITE, nullptr, __VA_ARGS__); \
178
    return nullptr; \
179 180
  } HB_STMT_END;

E
Ebrahim Byagowi 已提交
181
  if (FAILED (hr))
182
    FAIL ("Failed to load font file from data!");
183

184 185 186
  BOOL isSupported;
  DWRITE_FONT_FILE_TYPE fileType;
  DWRITE_FONT_FACE_TYPE faceType;
E
Ebrahim Byagowi 已提交
187
  uint32_t numberOfFaces;
188
  hr = fontFile->Analyze (&isSupported, &fileType, &faceType, &numberOfFaces);
E
Ebrahim Byagowi 已提交
189
  if (FAILED (hr) || !isSupported)
190
    FAIL ("Font file is not supported.");
191

192 193 194 195 196 197 198 199
#undef FAIL

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

  data->dwriteFactory = dwriteFactory;
  data->fontFile = fontFile;
200
  data->fontFileStream = fontFileStream;
201 202
  data->fontFileLoader = fontFileLoader;
  data->fontFace = fontFace;
203
  data->faceBlob = blob;
204

205 206 207 208
  return data;
}

void
B
Rename  
Behdad Esfahbod 已提交
209
_hb_directwrite_shaper_face_data_destroy (hb_directwrite_face_data_t *data)
210
{
211 212 213 214
  if (data->fontFace)
    data->fontFace->Release ();
  if (data->fontFile)
    data->fontFile->Release ();
E
Ebrahim Byagowi 已提交
215 216
  if (data->dwriteFactory)
  {
217
    if (data->fontFileLoader)
218 219
      data->dwriteFactory->UnregisterFontFileLoader (data->fontFileLoader);
    data->dwriteFactory->Release ();
220 221
  }
  if (data->fontFileLoader)
222
    delete data->fontFileLoader;
223
  if (data->fontFileStream)
224
    delete data->fontFileStream;
225 226 227
  if (data->faceBlob)
    hb_blob_destroy (data->faceBlob);
  if (data)
228
    delete data;
229 230 231 232 233 234 235
}


/*
 * shaper font data
 */

B
Rename  
Behdad Esfahbod 已提交
236
struct hb_directwrite_font_data_t
E
Ebrahim Byagowi 已提交
237
{
238 239
};

B
Rename  
Behdad Esfahbod 已提交
240
hb_directwrite_font_data_t *
241 242
_hb_directwrite_shaper_font_data_create (hb_font_t *font)
{
B
Behdad Esfahbod 已提交
243
  if (unlikely (!hb_directwrite_shaper_face_data_ensure (font->face))) return nullptr;
244

B
Rename  
Behdad Esfahbod 已提交
245
  hb_directwrite_font_data_t *data = new hb_directwrite_font_data_t;
246
  if (unlikely (!data))
B
Behdad Esfahbod 已提交
247
    return nullptr;
248 249 250 251 252

  return data;
}

void
B
Rename  
Behdad Esfahbod 已提交
253
_hb_directwrite_shaper_font_data_destroy (hb_directwrite_font_data_t *data)
254
{
255
  delete data;
256 257 258
}


259
// Most of TextAnalysis is originally written by Bas Schouten for Mozilla project
260 261 262 263 264 265
// but now is relicensed to MIT for HarfBuzz use
class TextAnalysis
  : public IDWriteTextAnalysisSource, public IDWriteTextAnalysisSink
{
public:

266 267 268
  IFACEMETHOD (QueryInterface) (IID const& iid, OUT void** ppObject) { return S_OK; }
  IFACEMETHOD_ (ULONG, AddRef) () { return 1; }
  IFACEMETHOD_ (ULONG, Release) () { return 1; }
269

270
  // A single contiguous run of characters containing the same analysis
271 272 273
  // results.
  struct Run
  {
274 275 276
    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
277
    uint32_t mGlyphCount;  // number of glyphs associated with this run
278 279
    // text
    DWRITE_SCRIPT_ANALYSIS mScript;
280
    uint8_t mBidiLevel;
281 282
    bool mIsSideways;

283
    inline bool ContainsTextPosition (uint32_t aTextPosition) const
284
    {
285 286
      return aTextPosition >= mTextStart &&
	     aTextPosition <  mTextStart + mTextLength;
287 288 289 290 291 292
    }

    Run *nextRun;
  };

public:
293
  TextAnalysis (const wchar_t* text,
294
    uint32_t textLength,
295 296
    const wchar_t* localeName,
    DWRITE_READING_DIRECTION readingDirection)
297 298 299 300 301
    : mText (text)
    , mTextLength (textLength)
    , mLocaleName (localeName)
    , mReadingDirection (readingDirection)
    , mCurrentRun (nullptr) { };
302

E
Ebrahim Byagowi 已提交
303 304
  ~TextAnalysis ()
  {
305
    // delete runs, except mRunHead which is part of the TextAnalysis object
E
Ebrahim Byagowi 已提交
306 307
    for (Run *run = mRunHead.nextRun; run;)
    {
308 309
      Run *origRun = run;
      run = run->nextRun;
310
      delete origRun;
311 312 313
    }
  }

314
  STDMETHODIMP GenerateResults (IDWriteTextAnalyzer* textAnalyzer,
E
Ebrahim Byagowi 已提交
315 316
    Run **runHead)
  {
317 318 319 320 321 322 323 324 325 326 327
    // 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 已提交
328
    mRunHead.nextRun = nullptr;
329 330 331
    mCurrentRun = &mRunHead;

    // Call each of the analyzers in sequence, recording their results.
E
Ebrahim Byagowi 已提交
332
    if (SUCCEEDED (hr = textAnalyzer->AnalyzeScript (this, 0, mTextLength, this)))
333 334 335 336 337 338 339
      *runHead = &mRunHead;

    return hr;
  }

  // IDWriteTextAnalysisSource implementation

340
  IFACEMETHODIMP GetTextAtPosition (uint32_t textPosition,
341 342
    OUT wchar_t const** textString,
    OUT uint32_t* textLength)
343
  {
E
Ebrahim Byagowi 已提交
344 345
    if (textPosition >= mTextLength)
    {
346
      // No text at this position, valid query though.
B
Behdad Esfahbod 已提交
347
      *textString = nullptr;
348 349
      *textLength = 0;
    }
E
Ebrahim Byagowi 已提交
350 351
    else
    {
352 353 354 355 356 357
      *textString = mText + textPosition;
      *textLength = mTextLength - textPosition;
    }
    return S_OK;
  }

358
  IFACEMETHODIMP GetTextBeforePosition (uint32_t textPosition,
359 360
    OUT wchar_t const** textString,
    OUT uint32_t* textLength)
361
  {
E
Ebrahim Byagowi 已提交
362 363
    if (textPosition == 0 || textPosition > mTextLength)
    {
364
      // Either there is no text before here (== 0), or this
B
Bruce Mitchener 已提交
365
      // is an invalid position. The query is considered valid though.
B
Behdad Esfahbod 已提交
366
      *textString = nullptr;
367 368
      *textLength = 0;
    }
E
Ebrahim Byagowi 已提交
369 370
    else
    {
371 372 373 374 375 376
      *textString = mText;
      *textLength = textPosition;
    }
    return S_OK;
  }

377 378
  IFACEMETHODIMP_ (DWRITE_READING_DIRECTION)
    GetParagraphReadingDirection () { return mReadingDirection; }
379

380
  IFACEMETHODIMP GetLocaleName (uint32_t textPosition,
381
    uint32_t* textLength,
382 383
    wchar_t const** localeName)
  {
384 385 386 387
    return S_OK;
  }

  IFACEMETHODIMP
388
    GetNumberSubstitution (uint32_t textPosition,
389
    OUT uint32_t* textLength,
390 391 392
    OUT IDWriteNumberSubstitution** numberSubstitution)
  {
    // We do not support number substitution.
B
Behdad Esfahbod 已提交
393
    *numberSubstitution = nullptr;
394 395 396 397 398 399 400 401
    *textLength = mTextLength - textPosition;

    return S_OK;
  }

  // IDWriteTextAnalysisSink implementation

  IFACEMETHODIMP
402
    SetScriptAnalysis (uint32_t textPosition,
403
    uint32_t textLength,
404 405
    DWRITE_SCRIPT_ANALYSIS const* scriptAnalysis)
  {
406 407
    SetCurrentRun (textPosition);
    SplitCurrentRun (textPosition);
408 409
    while (textLength > 0)
    {
410
      Run *run = FetchNextRun (&textLength);
411 412 413 414 415 416 417
      run->mScript = *scriptAnalysis;
    }

    return S_OK;
  }

  IFACEMETHODIMP
418
    SetLineBreakpoints (uint32_t textPosition,
419
    uint32_t textLength,
420 421
    const DWRITE_LINE_BREAKPOINT* lineBreakpoints) { return S_OK; }

422
  IFACEMETHODIMP SetBidiLevel (uint32_t textPosition,
423 424 425
    uint32_t textLength,
    uint8_t explicitLevel,
    uint8_t resolvedLevel) { return S_OK; }
426 427

  IFACEMETHODIMP
428
    SetNumberSubstitution (uint32_t textPosition,
429
    uint32_t textLength,
430 431 432
    IDWriteNumberSubstitution* numberSubstitution) { return S_OK; }

protected:
433
  Run *FetchNextRun (IN OUT uint32_t* textLength)
434 435 436 437 438 439 440 441
  {
    // 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).
442 443 444
    if (*textLength < mCurrentRun->mTextLength)
      SplitCurrentRun (mCurrentRun->mTextStart + *textLength);
    else
445 446 447 448 449 450 451 452
      // Just advance the current run.
      mCurrentRun = mCurrentRun->nextRun;
    *textLength -= origRun->mTextLength;

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

453
  void SetCurrentRun (uint32_t textPosition)
454 455 456 457 458 459
  {
    // 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.

460
    if (mCurrentRun && mCurrentRun->ContainsTextPosition (textPosition))
461 462
      return;

E
Ebrahim Byagowi 已提交
463
    for (Run *run = &mRunHead; run; run = run->nextRun)
464 465
      if (run->ContainsTextPosition (textPosition))
      {
466 467
	mCurrentRun = run;
	return;
468
      }
469
    assert (0); // We should always be able to find the text position in one of our runs
470 471
  }

472
  void SplitCurrentRun (uint32_t splitPosition)
473
  {
474 475
    if (!mCurrentRun)
    {
476
      assert (0); // SplitCurrentRun called without current run
477 478 479 480
      // Shouldn't be calling this when no current run is set!
      return;
    }
    // Split the current run.
481 482
    if (splitPosition <= mCurrentRun->mTextStart)
    {
483 484 485 486
      // No need to split, already the start of a run
      // or before it. Usually the first.
      return;
    }
487
    Run *newRun = new Run;
488 489 490 491 492 493 494 495

    *newRun = *mCurrentRun;

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

    // Adjust runs' text positions and lengths.
496
    uint32_t splitPoint = splitPosition - mCurrentRun->mTextStart;
497 498 499 500 501 502 503 504 505 506
    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)
507 508 509
  uint32_t mTextLength;
  const wchar_t* mText;
  const wchar_t* mLocaleName;
510 511 512 513 514 515 516 517 518
  DWRITE_READING_DIRECTION mReadingDirection;

  // Current processing state.
  Run *mCurrentRun;

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

519
static inline uint16_t hb_uint16_swap (const uint16_t v)
520
{ return (v >> 8) | (v << 8); }
521
static inline uint32_t hb_uint32_swap (const uint32_t v)
522
{ return (hb_uint16_swap (v) << 16) | hb_uint16_swap (v >> 16); }
523 524 525 526 527

/*
 * shaper
 */

528
static hb_bool_t
529
_hb_directwrite_shape_full (hb_shape_plan_t    *shape_plan,
530 531 532
  hb_font_t          *font,
  hb_buffer_t        *buffer,
  const hb_feature_t *features,
533 534
  unsigned int        num_features,
  float               lineWidth)
535 536
{
  hb_face_t *face = font->face;
B
Rename  
Behdad Esfahbod 已提交
537 538
  hb_directwrite_face_data_t *face_data = HB_SHAPER_DATA_GET (face);
  hb_directwrite_font_data_t *font_data = HB_SHAPER_DATA_GET (font);
539 540
  IDWriteFactory *dwriteFactory = face_data->dwriteFactory;
  IDWriteFontFace *fontFace = face_data->fontFace;
541 542

  IDWriteTextAnalyzer* analyzer;
543
  dwriteFactory->CreateTextAnalyzer (&analyzer);
544 545 546 547 548 549 550 551 552 553 554 555 556 557

  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

558
  ALLOCATE_ARRAY (wchar_t, textString, buffer->len * 2);
559 560 561 562 563

  unsigned int chars_len = 0;
  for (unsigned int i = 0; i < buffer->len; i++)
  {
    hb_codepoint_t c = buffer->info[i].codepoint;
564 565
    buffer->info[i].utf16_index () = chars_len;
    if (likely (c <= 0xFFFFu))
E
Ebrahim Byagowi 已提交
566
      textString[chars_len++] = c;
567
    else if (unlikely (c > 0x10FFFFu))
E
Ebrahim Byagowi 已提交
568
      textString[chars_len++] = 0xFFFDu;
E
Ebrahim Byagowi 已提交
569 570
    else
    {
E
Ebrahim Byagowi 已提交
571
      textString[chars_len++] = 0xD800u + ((c - 0x10000u) >> 10);
B
Behdad Esfahbod 已提交
572
      textString[chars_len++] = 0xDC00u + ((c - 0x10000u) & ((1u << 10) - 1));
573 574 575
    }
  }

576
  ALLOCATE_ARRAY (WORD, log_clusters, chars_len);
E
Ebrahim Byagowi 已提交
577 578 579
  /* Need log_clusters to assign features. */
  chars_len = 0;
  for (unsigned int i = 0; i < buffer->len; i++)
580
  {
E
Ebrahim Byagowi 已提交
581 582 583 584 585
    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. */
586 587 588 589
  }

  // TODO: Handle TEST_DISABLE_OPTIONAL_LIGATURES

590
  DWRITE_READING_DIRECTION readingDirection = buffer->props.direction ?
591 592 593
    DWRITE_READING_DIRECTION_RIGHT_TO_LEFT :
    DWRITE_READING_DIRECTION_LEFT_TO_RIGHT;

K
Khaled Hosny 已提交
594
  /*
595 596 597 598
  * 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.
  */
599
  uint32_t textLength = buffer->len;
600

601
  TextAnalysis analysis (textString, textLength, nullptr, readingDirection);
602
  TextAnalysis::Run *runHead;
603
  HRESULT hr;
604
  hr = analysis.GenerateResults (analyzer, &runHead);
605

606 607
#define FAIL(...) \
  HB_STMT_START { \
B
Behdad Esfahbod 已提交
608
    DEBUG_MSG (DIRECTWRITE, nullptr, __VA_ARGS__); \
609 610 611
    return false; \
  } HB_STMT_END;

E
Ebrahim Byagowi 已提交
612
  if (FAILED (hr))
613
    FAIL ("Analyzer failed to generate results.");
614

615 616
  uint32_t maxGlyphCount = 3 * textLength / 2 + 16;
  uint32_t glyphCount;
E
Ebrahim Byagowi 已提交
617
  bool isRightToLeft = HB_DIRECTION_IS_BACKWARD (buffer->props.direction);
618

E
Ebrahim Byagowi 已提交
619
  const wchar_t localeName[20] = {0};
B
Behdad Esfahbod 已提交
620
  if (buffer->props.language != nullptr)
E
Ebrahim Byagowi 已提交
621 622 623
  {
    mbstowcs ((wchar_t*) localeName,
      hb_language_to_string (buffer->props.language), 20);
624 625
  }

E
Ebrahim Byagowi 已提交
626 627 628
  // TODO: it does work but doesn't care about ranges
  DWRITE_TYPOGRAPHIC_FEATURES typographic_features;
  typographic_features.featureCount = num_features;
E
Ebrahim Byagowi 已提交
629
  if (num_features)
630
  {
E
Ebrahim Byagowi 已提交
631
    typographic_features.features = new DWRITE_FONT_FEATURE[num_features];
632 633
    for (unsigned int i = 0; i < num_features; ++i)
    {
E
Ebrahim Byagowi 已提交
634
      typographic_features.features[i].nameTag = (DWRITE_FONT_FEATURE_TAG)
635
	hb_uint32_swap (features[i].tag);
E
Ebrahim Byagowi 已提交
636
      typographic_features.features[i].parameter = features[i].value;
637
    }
E
Ebrahim Byagowi 已提交
638 639
  }
  const DWRITE_TYPOGRAPHIC_FEATURES* dwFeatures =
E
Ebrahim Byagowi 已提交
640
    (const DWRITE_TYPOGRAPHIC_FEATURES*) &typographic_features;
641
  const uint32_t featureRangeLengths[] = { textLength };
E
Ebrahim Byagowi 已提交
642
  //
E
Ebrahim Byagowi 已提交
643

644 645 646
  uint16_t* clusterMap = new uint16_t[textLength];
  DWRITE_SHAPING_TEXT_PROPERTIES* textProperties =
    new DWRITE_SHAPING_TEXT_PROPERTIES[textLength];
E
Ebrahim Byagowi 已提交
647
retry_getglyphs:
648 649 650
  uint16_t* glyphIndices = new uint16_t[maxGlyphCount];
  DWRITE_SHAPING_GLYPH_PROPERTIES* glyphProperties =
    new DWRITE_SHAPING_GLYPH_PROPERTIES[maxGlyphCount];
E
Ebrahim Byagowi 已提交
651

B
Minor  
Behdad Esfahbod 已提交
652
  hr = analyzer->GetGlyphs (textString, textLength, fontFace, false,
B
Behdad Esfahbod 已提交
653
    isRightToLeft, &runHead->mScript, localeName, nullptr, &dwFeatures,
E
Ebrahim Byagowi 已提交
654 655 656 657 658
    featureRangeLengths, 1, maxGlyphCount, clusterMap, textProperties, glyphIndices,
    glyphProperties, &glyphCount);

  if (unlikely (hr == HRESULT_FROM_WIN32 (ERROR_INSUFFICIENT_BUFFER)))
  {
659 660
    delete [] glyphIndices;
    delete [] glyphProperties;
661

E
Ebrahim Byagowi 已提交
662
    maxGlyphCount *= 2;
663 664

    goto retry_getglyphs;
665
  }
E
Ebrahim Byagowi 已提交
666
  if (FAILED (hr))
667
    FAIL ("Analyzer failed to get glyphs.");
668

669 670
  float* glyphAdvances = new float[maxGlyphCount];
  DWRITE_GLYPH_OFFSET* glyphOffsets = new DWRITE_GLYPH_OFFSET[maxGlyphCount];
671 672

  /* The -2 in the following is to compensate for possible
673 674 675 676 677 678 679
   * alignment needed after the WORD array.  sizeof (WORD) == 2. */
  unsigned int glyphs_size = (scratch_size * sizeof (int) - 2)
         / (sizeof (WORD) +
            sizeof (DWRITE_SHAPING_GLYPH_PROPERTIES) +
            sizeof (int) +
            sizeof (DWRITE_GLYPH_OFFSET) +
            sizeof (uint32_t));
E
Ebrahim Byagowi 已提交
680
  ALLOCATE_ARRAY (uint32_t, vis_clusters, glyphs_size);
681 682 683

#undef ALLOCATE_ARRAY

684
  int fontEmSize = font->face->get_upem ();
E
Ebrahim Byagowi 已提交
685 686 687 688 689 690 691 692 693 694 695
  if (fontEmSize < 0)
    fontEmSize = -fontEmSize;

  if (fontEmSize < 0)
    fontEmSize = -fontEmSize;
  double x_mult = (double) font->x_scale / fontEmSize;
  double y_mult = (double) font->y_scale / fontEmSize;

  hr = analyzer->GetGlyphPlacements (textString,
    clusterMap, textProperties, textLength, glyphIndices,
    glyphProperties, glyphCount, fontFace, fontEmSize,
B
Minor  
Behdad Esfahbod 已提交
696
    false, isRightToLeft, &runHead->mScript, localeName,
E
Ebrahim Byagowi 已提交
697 698 699 700
    &dwFeatures, featureRangeLengths, 1,
    glyphAdvances, glyphOffsets);

  if (FAILED (hr))
701
    FAIL ("Analyzer failed to get glyph placements.");
702

703 704
  IDWriteTextAnalyzer1* analyzer1;
  analyzer->QueryInterface (&analyzer1);
E
Ebrahim Byagowi 已提交
705

706
  if (analyzer1 && lineWidth)
E
Ebrahim Byagowi 已提交
707 708
  {

709
    DWRITE_JUSTIFICATION_OPPORTUNITY* justificationOpportunities =
710
      new DWRITE_JUSTIFICATION_OPPORTUNITY[maxGlyphCount];
711 712 713
    hr = analyzer1->GetJustificationOpportunities (fontFace, fontEmSize,
      runHead->mScript, textLength, glyphCount, textString, clusterMap,
      glyphProperties, justificationOpportunities);
E
Ebrahim Byagowi 已提交
714

715 716
    if (FAILED (hr))
      FAIL ("Analyzer failed to get justification opportunities.");
E
Ebrahim Byagowi 已提交
717

718 719
    float* justifiedGlyphAdvances = new float[maxGlyphCount];
    DWRITE_GLYPH_OFFSET* justifiedGlyphOffsets = new DWRITE_GLYPH_OFFSET[glyphCount];
720 721
    hr = analyzer1->JustifyGlyphAdvances (lineWidth, glyphCount, justificationOpportunities,
      glyphAdvances, glyphOffsets, justifiedGlyphAdvances, justifiedGlyphOffsets);
E
Ebrahim Byagowi 已提交
722

723
    if (FAILED (hr))
724
      FAIL ("Analyzer failed to get justified glyph advances.");
725

726 727 728
    DWRITE_SCRIPT_PROPERTIES scriptProperties;
    hr = analyzer1->GetScriptProperties (runHead->mScript, &scriptProperties);
    if (FAILED (hr))
729
      FAIL ("Analyzer failed to get script properties.");
730 731 732 733 734
    uint32_t justificationCharacter = scriptProperties.justificationCharacter;

    // if a script justificationCharacter is not space, it can have GetJustifiedGlyphs
    if (justificationCharacter != 32)
    {
735
      uint16_t* modifiedClusterMap = new uint16_t[textLength];
736
    retry_getjustifiedglyphs:
737 738 739
      uint16_t* modifiedGlyphIndices = new uint16_t[maxGlyphCount];
      float* modifiedGlyphAdvances = new float[maxGlyphCount];
      DWRITE_GLYPH_OFFSET* modifiedGlyphOffsets =
740
	new DWRITE_GLYPH_OFFSET[maxGlyphCount];
741 742
      uint32_t actualGlyphsCount;
      hr = analyzer1->GetJustifiedGlyphs (fontFace, fontEmSize, runHead->mScript,
743 744 745 746
	textLength, glyphCount, maxGlyphCount, clusterMap, glyphIndices,
	glyphAdvances, justifiedGlyphAdvances, justifiedGlyphOffsets,
	glyphProperties, &actualGlyphsCount, modifiedClusterMap, modifiedGlyphIndices,
	modifiedGlyphAdvances, modifiedGlyphOffsets);
747

748 749
      if (hr == HRESULT_FROM_WIN32 (ERROR_INSUFFICIENT_BUFFER))
      {
750 751 752 753
	maxGlyphCount = actualGlyphsCount;
	delete [] modifiedGlyphIndices;
	delete [] modifiedGlyphAdvances;
	delete [] modifiedGlyphOffsets;
754

755
	maxGlyphCount = actualGlyphsCount;
756

757
	goto retry_getjustifiedglyphs;
758 759
      }
      if (FAILED (hr))
760
	FAIL ("Analyzer failed to get justified glyphs.");
761

762 763 764 765
      delete [] clusterMap;
      delete [] glyphIndices;
      delete [] glyphAdvances;
      delete [] glyphOffsets;
E
Ebrahim Byagowi 已提交
766

767 768 769 770 771
      glyphCount = actualGlyphsCount;
      clusterMap = modifiedClusterMap;
      glyphIndices = modifiedGlyphIndices;
      glyphAdvances = modifiedGlyphAdvances;
      glyphOffsets = modifiedGlyphOffsets;
E
Ebrahim Byagowi 已提交
772

773 774
      delete [] justifiedGlyphAdvances;
      delete [] justifiedGlyphOffsets;
775 776 777
    }
    else
    {
778 779
      delete [] glyphAdvances;
      delete [] glyphOffsets;
780

781 782 783
      glyphAdvances = justifiedGlyphAdvances;
      glyphOffsets = justifiedGlyphOffsets;
    }
E
Ebrahim Byagowi 已提交
784

785
    delete [] justificationOpportunities;
E
Ebrahim Byagowi 已提交
786

787
  }
E
Ebrahim Byagowi 已提交
788

789 790 791 792
  /* 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 已提交
793
  for (unsigned int i = 0; i < glyphCount; i++)
794
    vis_clusters[i] = -1;
E
Ebrahim Byagowi 已提交
795 796 797
  for (unsigned int i = 0; i < buffer->len; i++)
  {
    uint32_t *p =
798
      &vis_clusters[log_clusters[buffer->info[i].utf16_index ()]];
799
    *p = MIN (*p, buffer->info[i].cluster);
800
  }
E
Ebrahim Byagowi 已提交
801
  for (unsigned int i = 1; i < glyphCount; i++)
802 803 804 805 806
    if (vis_clusters[i] == -1)
      vis_clusters[i] = vis_clusters[i - 1];

#undef utf16_index

E
Ebrahim Byagowi 已提交
807
  if (unlikely (!buffer->ensure (glyphCount)))
808
    FAIL ("Buffer in error");
809 810 811 812 813

#undef FAIL

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

E
Ebrahim Byagowi 已提交
818
    info->codepoint = glyphIndices[i];
819 820 821
    info->cluster = vis_clusters[i];

    /* The rest is crap.  Let's store position info there for now. */
E
Ebrahim Byagowi 已提交
822 823 824
    info->mask = glyphAdvances[i];
    info->var1.i32 = glyphOffsets[i].advanceOffset;
    info->var2.i32 = glyphOffsets[i].ascenderOffset;
825 826 827 828
  }

  /* Set glyph positions */
  buffer->clear_positions ();
E
Ebrahim Byagowi 已提交
829
  for (unsigned int i = 0; i < glyphCount; i++)
830 831 832 833 834
  {
    hb_glyph_info_t *info = &buffer->info[i];
    hb_glyph_position_t *pos = &buffer->pos[i];

    /* TODO vertical */
E
Ebrahim Byagowi 已提交
835
    pos->x_advance = x_mult * (int32_t) info->mask;
E
Ebrahim Byagowi 已提交
836 837
    pos->x_offset =
      x_mult * (isRightToLeft ? -info->var1.i32 : info->var1.i32);
E
Ebrahim Byagowi 已提交
838
    pos->y_offset = y_mult * info->var2.i32;
839 840
  }

E
Ebrahim Byagowi 已提交
841
  if (isRightToLeft)
842 843
    hb_buffer_reverse (buffer);

844 845 846 847 848 849
  delete [] clusterMap;
  delete [] glyphIndices;
  delete [] textProperties;
  delete [] glyphProperties;
  delete [] glyphAdvances;
  delete [] glyphOffsets;
E
Ebrahim Byagowi 已提交
850 851

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

854 855
  /* Wow, done! */
  return true;
K
Khaled Hosny 已提交
856
}
857 858

hb_bool_t
859
_hb_directwrite_shape (hb_shape_plan_t    *shape_plan,
860 861 862 863 864
  hb_font_t          *font,
  hb_buffer_t        *buffer,
  const hb_feature_t *features,
  unsigned int        num_features)
{
865
  return _hb_directwrite_shape_full (shape_plan, font, buffer,
866 867 868 869 870 871 872 873
    features, num_features, 0);
}

/*
 * Public [experimental] API
 */

hb_bool_t
874
hb_directwrite_shape_experimental_width (hb_font_t          *font,
875 876 877 878 879
  hb_buffer_t        *buffer,
  const hb_feature_t *features,
  unsigned int        num_features,
  float               width)
{
880
  static const char *shapers = "directwrite";
881 882 883 884 885
  hb_shape_plan_t *shape_plan = hb_shape_plan_create_cached (font->face,
    &buffer->props, features, num_features, &shapers);
  hb_bool_t res = _hb_directwrite_shape_full (shape_plan, font, buffer,
    features, num_features, width);

886
  buffer->unsafe_to_break_all ();
887 888 889

  return res;
}