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

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

#include "hb-directwrite.h"


34 35 36 37 38 39 40 41 42 43 44 45 46
HB_SHAPER_DATA_ENSURE_DEFINE (directwrite, face)
HB_SHAPER_DATA_ENSURE_DEFINE (directwrite, font)


/*
 * 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 260 261 262
}


/*
 * shaper shape_plan data
 */

B
Rename  
Behdad Esfahbod 已提交
263
struct hb_directwrite_shape_plan_data_t {};
264

B
Rename  
Behdad Esfahbod 已提交
265
hb_directwrite_shape_plan_data_t *
266
_hb_directwrite_shaper_shape_plan_data_create (hb_shape_plan_t    *shape_plan HB_UNUSED,
B
Behdad Esfahbod 已提交
267 268 269 270
					       const hb_feature_t *user_features HB_UNUSED,
					       unsigned int        num_user_features HB_UNUSED,
					       const int          *coords HB_UNUSED,
					       unsigned int        num_coords HB_UNUSED)
271
{
B
Rename  
Behdad Esfahbod 已提交
272
  return (hb_directwrite_shape_plan_data_t *) HB_SHAPER_DATA_SUCCEEDED;
273 274 275
}

void
B
Rename  
Behdad Esfahbod 已提交
276
_hb_directwrite_shaper_shape_plan_data_destroy (hb_directwrite_shape_plan_data_t *data HB_UNUSED)
277 278 279
{
}

280
// Most of TextAnalysis is originally written by Bas Schouten for Mozilla project
281 282 283 284 285 286
// but now is relicensed to MIT for HarfBuzz use
class TextAnalysis
  : public IDWriteTextAnalysisSource, public IDWriteTextAnalysisSink
{
public:

287 288 289
  IFACEMETHOD (QueryInterface) (IID const& iid, OUT void** ppObject) { return S_OK; }
  IFACEMETHOD_ (ULONG, AddRef) () { return 1; }
  IFACEMETHOD_ (ULONG, Release) () { return 1; }
290

291
  // A single contiguous run of characters containing the same analysis
292 293 294
  // results.
  struct Run
  {
295 296 297
    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
298
    uint32_t mGlyphCount;  // number of glyphs associated with this run
299 300
    // text
    DWRITE_SCRIPT_ANALYSIS mScript;
301
    uint8_t mBidiLevel;
302 303
    bool mIsSideways;

304
    inline bool ContainsTextPosition (uint32_t aTextPosition) const
305
    {
306 307
      return aTextPosition >= mTextStart &&
	     aTextPosition <  mTextStart + mTextLength;
308 309 310 311 312 313
    }

    Run *nextRun;
  };

public:
314
  TextAnalysis (const wchar_t* text,
315
    uint32_t textLength,
316 317
    const wchar_t* localeName,
    DWRITE_READING_DIRECTION readingDirection)
318 319 320 321 322
    : mText (text)
    , mTextLength (textLength)
    , mLocaleName (localeName)
    , mReadingDirection (readingDirection)
    , mCurrentRun (nullptr) { };
323

E
Ebrahim Byagowi 已提交
324 325
  ~TextAnalysis ()
  {
326
    // delete runs, except mRunHead which is part of the TextAnalysis object
E
Ebrahim Byagowi 已提交
327 328
    for (Run *run = mRunHead.nextRun; run;)
    {
329 330
      Run *origRun = run;
      run = run->nextRun;
331
      delete origRun;
332 333 334
    }
  }

335
  STDMETHODIMP GenerateResults (IDWriteTextAnalyzer* textAnalyzer,
E
Ebrahim Byagowi 已提交
336 337
    Run **runHead)
  {
338 339 340 341 342 343 344 345 346 347 348
    // 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 已提交
349
    mRunHead.nextRun = nullptr;
350 351 352
    mCurrentRun = &mRunHead;

    // Call each of the analyzers in sequence, recording their results.
E
Ebrahim Byagowi 已提交
353
    if (SUCCEEDED (hr = textAnalyzer->AnalyzeScript (this, 0, mTextLength, this)))
354 355 356 357 358 359 360
      *runHead = &mRunHead;

    return hr;
  }

  // IDWriteTextAnalysisSource implementation

361
  IFACEMETHODIMP GetTextAtPosition (uint32_t textPosition,
362 363
    OUT wchar_t const** textString,
    OUT uint32_t* textLength)
364
  {
E
Ebrahim Byagowi 已提交
365 366
    if (textPosition >= mTextLength)
    {
367
      // No text at this position, valid query though.
B
Behdad Esfahbod 已提交
368
      *textString = nullptr;
369 370
      *textLength = 0;
    }
E
Ebrahim Byagowi 已提交
371 372
    else
    {
373 374 375 376 377 378
      *textString = mText + textPosition;
      *textLength = mTextLength - textPosition;
    }
    return S_OK;
  }

379
  IFACEMETHODIMP GetTextBeforePosition (uint32_t textPosition,
380 381
    OUT wchar_t const** textString,
    OUT uint32_t* textLength)
382
  {
E
Ebrahim Byagowi 已提交
383 384
    if (textPosition == 0 || textPosition > mTextLength)
    {
385
      // Either there is no text before here (== 0), or this
B
Bruce Mitchener 已提交
386
      // is an invalid position. The query is considered valid though.
B
Behdad Esfahbod 已提交
387
      *textString = nullptr;
388 389
      *textLength = 0;
    }
E
Ebrahim Byagowi 已提交
390 391
    else
    {
392 393 394 395 396 397
      *textString = mText;
      *textLength = textPosition;
    }
    return S_OK;
  }

398 399
  IFACEMETHODIMP_ (DWRITE_READING_DIRECTION)
    GetParagraphReadingDirection () { return mReadingDirection; }
400

401
  IFACEMETHODIMP GetLocaleName (uint32_t textPosition,
402
    uint32_t* textLength,
403 404
    wchar_t const** localeName)
  {
405 406 407 408
    return S_OK;
  }

  IFACEMETHODIMP
409
    GetNumberSubstitution (uint32_t textPosition,
410
    OUT uint32_t* textLength,
411 412 413
    OUT IDWriteNumberSubstitution** numberSubstitution)
  {
    // We do not support number substitution.
B
Behdad Esfahbod 已提交
414
    *numberSubstitution = nullptr;
415 416 417 418 419 420 421 422
    *textLength = mTextLength - textPosition;

    return S_OK;
  }

  // IDWriteTextAnalysisSink implementation

  IFACEMETHODIMP
423
    SetScriptAnalysis (uint32_t textPosition,
424
    uint32_t textLength,
425 426
    DWRITE_SCRIPT_ANALYSIS const* scriptAnalysis)
  {
427 428
    SetCurrentRun (textPosition);
    SplitCurrentRun (textPosition);
429 430
    while (textLength > 0)
    {
431
      Run *run = FetchNextRun (&textLength);
432 433 434 435 436 437 438
      run->mScript = *scriptAnalysis;
    }

    return S_OK;
  }

  IFACEMETHODIMP
439
    SetLineBreakpoints (uint32_t textPosition,
440
    uint32_t textLength,
441 442
    const DWRITE_LINE_BREAKPOINT* lineBreakpoints) { return S_OK; }

443
  IFACEMETHODIMP SetBidiLevel (uint32_t textPosition,
444 445 446
    uint32_t textLength,
    uint8_t explicitLevel,
    uint8_t resolvedLevel) { return S_OK; }
447 448

  IFACEMETHODIMP
449
    SetNumberSubstitution (uint32_t textPosition,
450
    uint32_t textLength,
451 452 453
    IDWriteNumberSubstitution* numberSubstitution) { return S_OK; }

protected:
454
  Run *FetchNextRun (IN OUT uint32_t* textLength)
455 456 457 458 459 460 461 462
  {
    // 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).
463 464 465
    if (*textLength < mCurrentRun->mTextLength)
      SplitCurrentRun (mCurrentRun->mTextStart + *textLength);
    else
466 467 468 469 470 471 472 473
      // Just advance the current run.
      mCurrentRun = mCurrentRun->nextRun;
    *textLength -= origRun->mTextLength;

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

474
  void SetCurrentRun (uint32_t textPosition)
475 476 477 478 479 480
  {
    // 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.

481
    if (mCurrentRun && mCurrentRun->ContainsTextPosition (textPosition))
482 483
      return;

E
Ebrahim Byagowi 已提交
484
    for (Run *run = &mRunHead; run; run = run->nextRun)
485 486
      if (run->ContainsTextPosition (textPosition))
      {
487 488
	mCurrentRun = run;
	return;
489
      }
490
    assert (0); // We should always be able to find the text position in one of our runs
491 492
  }

493
  void SplitCurrentRun (uint32_t splitPosition)
494
  {
495 496
    if (!mCurrentRun)
    {
497
      assert (0); // SplitCurrentRun called without current run
498 499 500 501
      // Shouldn't be calling this when no current run is set!
      return;
    }
    // Split the current run.
502 503
    if (splitPosition <= mCurrentRun->mTextStart)
    {
504 505 506 507
      // No need to split, already the start of a run
      // or before it. Usually the first.
      return;
    }
508
    Run *newRun = new Run;
509 510 511 512 513 514 515 516

    *newRun = *mCurrentRun;

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

    // Adjust runs' text positions and lengths.
517
    uint32_t splitPoint = splitPosition - mCurrentRun->mTextStart;
518 519 520 521 522 523 524 525 526 527
    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)
528 529 530
  uint32_t mTextLength;
  const wchar_t* mText;
  const wchar_t* mLocaleName;
531 532 533 534 535 536 537 538 539
  DWRITE_READING_DIRECTION mReadingDirection;

  // Current processing state.
  Run *mCurrentRun;

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

540
static inline uint16_t hb_uint16_swap (const uint16_t v)
541
{ return (v >> 8) | (v << 8); }
542
static inline uint32_t hb_uint32_swap (const uint32_t v)
543
{ return (hb_uint16_swap (v) << 16) | hb_uint16_swap (v >> 16); }
544 545 546 547 548

/*
 * shaper
 */

549
static hb_bool_t
550
_hb_directwrite_shape_full (hb_shape_plan_t    *shape_plan,
551 552 553
  hb_font_t          *font,
  hb_buffer_t        *buffer,
  const hb_feature_t *features,
554 555
  unsigned int        num_features,
  float               lineWidth)
556 557
{
  hb_face_t *face = font->face;
B
Rename  
Behdad Esfahbod 已提交
558 559
  hb_directwrite_face_data_t *face_data = HB_SHAPER_DATA_GET (face);
  hb_directwrite_font_data_t *font_data = HB_SHAPER_DATA_GET (font);
560 561
  IDWriteFactory *dwriteFactory = face_data->dwriteFactory;
  IDWriteFontFace *fontFace = face_data->fontFace;
562 563

  IDWriteTextAnalyzer* analyzer;
564
  dwriteFactory->CreateTextAnalyzer (&analyzer);
565 566 567 568 569 570 571 572 573 574 575 576 577 578

  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

579
  ALLOCATE_ARRAY (wchar_t, textString, buffer->len * 2);
580 581 582 583 584

  unsigned int chars_len = 0;
  for (unsigned int i = 0; i < buffer->len; i++)
  {
    hb_codepoint_t c = buffer->info[i].codepoint;
585 586
    buffer->info[i].utf16_index () = chars_len;
    if (likely (c <= 0xFFFFu))
E
Ebrahim Byagowi 已提交
587
      textString[chars_len++] = c;
588
    else if (unlikely (c > 0x10FFFFu))
E
Ebrahim Byagowi 已提交
589
      textString[chars_len++] = 0xFFFDu;
E
Ebrahim Byagowi 已提交
590 591
    else
    {
E
Ebrahim Byagowi 已提交
592
      textString[chars_len++] = 0xD800u + ((c - 0x10000u) >> 10);
B
Behdad Esfahbod 已提交
593
      textString[chars_len++] = 0xDC00u + ((c - 0x10000u) & ((1u << 10) - 1));
594 595 596
    }
  }

597
  ALLOCATE_ARRAY (WORD, log_clusters, chars_len);
E
Ebrahim Byagowi 已提交
598 599 600
  /* Need log_clusters to assign features. */
  chars_len = 0;
  for (unsigned int i = 0; i < buffer->len; i++)
601
  {
E
Ebrahim Byagowi 已提交
602 603 604 605 606
    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. */
607 608 609 610
  }

  // TODO: Handle TEST_DISABLE_OPTIONAL_LIGATURES

611
  DWRITE_READING_DIRECTION readingDirection = buffer->props.direction ?
612 613 614
    DWRITE_READING_DIRECTION_RIGHT_TO_LEFT :
    DWRITE_READING_DIRECTION_LEFT_TO_RIGHT;

K
Khaled Hosny 已提交
615
  /*
616 617 618 619
  * 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.
  */
620
  uint32_t textLength = buffer->len;
621

622
  TextAnalysis analysis (textString, textLength, nullptr, readingDirection);
623
  TextAnalysis::Run *runHead;
624
  HRESULT hr;
625
  hr = analysis.GenerateResults (analyzer, &runHead);
626

627 628
#define FAIL(...) \
  HB_STMT_START { \
B
Behdad Esfahbod 已提交
629
    DEBUG_MSG (DIRECTWRITE, nullptr, __VA_ARGS__); \
630 631 632
    return false; \
  } HB_STMT_END;

E
Ebrahim Byagowi 已提交
633
  if (FAILED (hr))
634
    FAIL ("Analyzer failed to generate results.");
635

636 637
  uint32_t maxGlyphCount = 3 * textLength / 2 + 16;
  uint32_t glyphCount;
E
Ebrahim Byagowi 已提交
638
  bool isRightToLeft = HB_DIRECTION_IS_BACKWARD (buffer->props.direction);
639

E
Ebrahim Byagowi 已提交
640
  const wchar_t localeName[20] = {0};
B
Behdad Esfahbod 已提交
641
  if (buffer->props.language != nullptr)
E
Ebrahim Byagowi 已提交
642 643 644
  {
    mbstowcs ((wchar_t*) localeName,
      hb_language_to_string (buffer->props.language), 20);
645 646
  }

E
Ebrahim Byagowi 已提交
647 648 649
  // TODO: it does work but doesn't care about ranges
  DWRITE_TYPOGRAPHIC_FEATURES typographic_features;
  typographic_features.featureCount = num_features;
E
Ebrahim Byagowi 已提交
650
  if (num_features)
651
  {
E
Ebrahim Byagowi 已提交
652
    typographic_features.features = new DWRITE_FONT_FEATURE[num_features];
653 654
    for (unsigned int i = 0; i < num_features; ++i)
    {
E
Ebrahim Byagowi 已提交
655
      typographic_features.features[i].nameTag = (DWRITE_FONT_FEATURE_TAG)
656
	hb_uint32_swap (features[i].tag);
E
Ebrahim Byagowi 已提交
657
      typographic_features.features[i].parameter = features[i].value;
658
    }
E
Ebrahim Byagowi 已提交
659 660
  }
  const DWRITE_TYPOGRAPHIC_FEATURES* dwFeatures =
E
Ebrahim Byagowi 已提交
661
    (const DWRITE_TYPOGRAPHIC_FEATURES*) &typographic_features;
662
  const uint32_t featureRangeLengths[] = { textLength };
E
Ebrahim Byagowi 已提交
663
  //
E
Ebrahim Byagowi 已提交
664

665 666 667
  uint16_t* clusterMap = new uint16_t[textLength];
  DWRITE_SHAPING_TEXT_PROPERTIES* textProperties =
    new DWRITE_SHAPING_TEXT_PROPERTIES[textLength];
E
Ebrahim Byagowi 已提交
668
retry_getglyphs:
669 670 671
  uint16_t* glyphIndices = new uint16_t[maxGlyphCount];
  DWRITE_SHAPING_GLYPH_PROPERTIES* glyphProperties =
    new DWRITE_SHAPING_GLYPH_PROPERTIES[maxGlyphCount];
E
Ebrahim Byagowi 已提交
672

B
Minor  
Behdad Esfahbod 已提交
673
  hr = analyzer->GetGlyphs (textString, textLength, fontFace, false,
B
Behdad Esfahbod 已提交
674
    isRightToLeft, &runHead->mScript, localeName, nullptr, &dwFeatures,
E
Ebrahim Byagowi 已提交
675 676 677 678 679
    featureRangeLengths, 1, maxGlyphCount, clusterMap, textProperties, glyphIndices,
    glyphProperties, &glyphCount);

  if (unlikely (hr == HRESULT_FROM_WIN32 (ERROR_INSUFFICIENT_BUFFER)))
  {
680 681
    delete [] glyphIndices;
    delete [] glyphProperties;
682

E
Ebrahim Byagowi 已提交
683
    maxGlyphCount *= 2;
684 685

    goto retry_getglyphs;
686
  }
E
Ebrahim Byagowi 已提交
687
  if (FAILED (hr))
688
    FAIL ("Analyzer failed to get glyphs.");
689

690 691
  float* glyphAdvances = new float[maxGlyphCount];
  DWRITE_GLYPH_OFFSET* glyphOffsets = new DWRITE_GLYPH_OFFSET[maxGlyphCount];
692 693

  /* The -2 in the following is to compensate for possible
694 695 696 697 698 699 700
   * 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 已提交
701
  ALLOCATE_ARRAY (uint32_t, vis_clusters, glyphs_size);
702 703 704

#undef ALLOCATE_ARRAY

705
  int fontEmSize = font->face->get_upem ();
E
Ebrahim Byagowi 已提交
706 707 708 709 710 711 712 713 714 715 716
  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 已提交
717
    false, isRightToLeft, &runHead->mScript, localeName,
E
Ebrahim Byagowi 已提交
718 719 720 721
    &dwFeatures, featureRangeLengths, 1,
    glyphAdvances, glyphOffsets);

  if (FAILED (hr))
722
    FAIL ("Analyzer failed to get glyph placements.");
723

724 725
  IDWriteTextAnalyzer1* analyzer1;
  analyzer->QueryInterface (&analyzer1);
E
Ebrahim Byagowi 已提交
726

727
  if (analyzer1 && lineWidth)
E
Ebrahim Byagowi 已提交
728 729
  {

730
    DWRITE_JUSTIFICATION_OPPORTUNITY* justificationOpportunities =
731
      new DWRITE_JUSTIFICATION_OPPORTUNITY[maxGlyphCount];
732 733 734
    hr = analyzer1->GetJustificationOpportunities (fontFace, fontEmSize,
      runHead->mScript, textLength, glyphCount, textString, clusterMap,
      glyphProperties, justificationOpportunities);
E
Ebrahim Byagowi 已提交
735

736 737
    if (FAILED (hr))
      FAIL ("Analyzer failed to get justification opportunities.");
E
Ebrahim Byagowi 已提交
738

739 740
    float* justifiedGlyphAdvances = new float[maxGlyphCount];
    DWRITE_GLYPH_OFFSET* justifiedGlyphOffsets = new DWRITE_GLYPH_OFFSET[glyphCount];
741 742
    hr = analyzer1->JustifyGlyphAdvances (lineWidth, glyphCount, justificationOpportunities,
      glyphAdvances, glyphOffsets, justifiedGlyphAdvances, justifiedGlyphOffsets);
E
Ebrahim Byagowi 已提交
743

744
    if (FAILED (hr))
745
      FAIL ("Analyzer failed to get justified glyph advances.");
746

747 748 749
    DWRITE_SCRIPT_PROPERTIES scriptProperties;
    hr = analyzer1->GetScriptProperties (runHead->mScript, &scriptProperties);
    if (FAILED (hr))
750
      FAIL ("Analyzer failed to get script properties.");
751 752 753 754 755
    uint32_t justificationCharacter = scriptProperties.justificationCharacter;

    // if a script justificationCharacter is not space, it can have GetJustifiedGlyphs
    if (justificationCharacter != 32)
    {
756
      uint16_t* modifiedClusterMap = new uint16_t[textLength];
757
    retry_getjustifiedglyphs:
758 759 760
      uint16_t* modifiedGlyphIndices = new uint16_t[maxGlyphCount];
      float* modifiedGlyphAdvances = new float[maxGlyphCount];
      DWRITE_GLYPH_OFFSET* modifiedGlyphOffsets =
761
	new DWRITE_GLYPH_OFFSET[maxGlyphCount];
762 763
      uint32_t actualGlyphsCount;
      hr = analyzer1->GetJustifiedGlyphs (fontFace, fontEmSize, runHead->mScript,
764 765 766 767
	textLength, glyphCount, maxGlyphCount, clusterMap, glyphIndices,
	glyphAdvances, justifiedGlyphAdvances, justifiedGlyphOffsets,
	glyphProperties, &actualGlyphsCount, modifiedClusterMap, modifiedGlyphIndices,
	modifiedGlyphAdvances, modifiedGlyphOffsets);
768

769 770
      if (hr == HRESULT_FROM_WIN32 (ERROR_INSUFFICIENT_BUFFER))
      {
771 772 773 774
	maxGlyphCount = actualGlyphsCount;
	delete [] modifiedGlyphIndices;
	delete [] modifiedGlyphAdvances;
	delete [] modifiedGlyphOffsets;
775

776
	maxGlyphCount = actualGlyphsCount;
777

778
	goto retry_getjustifiedglyphs;
779 780
      }
      if (FAILED (hr))
781
	FAIL ("Analyzer failed to get justified glyphs.");
782

783 784 785 786
      delete [] clusterMap;
      delete [] glyphIndices;
      delete [] glyphAdvances;
      delete [] glyphOffsets;
E
Ebrahim Byagowi 已提交
787

788 789 790 791 792
      glyphCount = actualGlyphsCount;
      clusterMap = modifiedClusterMap;
      glyphIndices = modifiedGlyphIndices;
      glyphAdvances = modifiedGlyphAdvances;
      glyphOffsets = modifiedGlyphOffsets;
E
Ebrahim Byagowi 已提交
793

794 795
      delete [] justifiedGlyphAdvances;
      delete [] justifiedGlyphOffsets;
796 797 798
    }
    else
    {
799 800
      delete [] glyphAdvances;
      delete [] glyphOffsets;
801

802 803 804
      glyphAdvances = justifiedGlyphAdvances;
      glyphOffsets = justifiedGlyphOffsets;
    }
E
Ebrahim Byagowi 已提交
805

806
    delete [] justificationOpportunities;
E
Ebrahim Byagowi 已提交
807

808
  }
E
Ebrahim Byagowi 已提交
809

810 811 812 813
  /* 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 已提交
814
  for (unsigned int i = 0; i < glyphCount; i++)
815
    vis_clusters[i] = -1;
E
Ebrahim Byagowi 已提交
816 817 818
  for (unsigned int i = 0; i < buffer->len; i++)
  {
    uint32_t *p =
819
      &vis_clusters[log_clusters[buffer->info[i].utf16_index ()]];
820
    *p = MIN (*p, buffer->info[i].cluster);
821
  }
E
Ebrahim Byagowi 已提交
822
  for (unsigned int i = 1; i < glyphCount; i++)
823 824 825 826 827
    if (vis_clusters[i] == -1)
      vis_clusters[i] = vis_clusters[i - 1];

#undef utf16_index

E
Ebrahim Byagowi 已提交
828
  if (unlikely (!buffer->ensure (glyphCount)))
829
    FAIL ("Buffer in error");
830 831 832 833 834

#undef FAIL

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

E
Ebrahim Byagowi 已提交
839
    info->codepoint = glyphIndices[i];
840 841 842
    info->cluster = vis_clusters[i];

    /* The rest is crap.  Let's store position info there for now. */
E
Ebrahim Byagowi 已提交
843 844 845
    info->mask = glyphAdvances[i];
    info->var1.i32 = glyphOffsets[i].advanceOffset;
    info->var2.i32 = glyphOffsets[i].ascenderOffset;
846 847 848 849
  }

  /* Set glyph positions */
  buffer->clear_positions ();
E
Ebrahim Byagowi 已提交
850
  for (unsigned int i = 0; i < glyphCount; i++)
851 852 853 854 855
  {
    hb_glyph_info_t *info = &buffer->info[i];
    hb_glyph_position_t *pos = &buffer->pos[i];

    /* TODO vertical */
E
Ebrahim Byagowi 已提交
856
    pos->x_advance = x_mult * (int32_t) info->mask;
E
Ebrahim Byagowi 已提交
857 858
    pos->x_offset =
      x_mult * (isRightToLeft ? -info->var1.i32 : info->var1.i32);
E
Ebrahim Byagowi 已提交
859
    pos->y_offset = y_mult * info->var2.i32;
860 861
  }

E
Ebrahim Byagowi 已提交
862
  if (isRightToLeft)
863 864
    hb_buffer_reverse (buffer);

865 866 867 868 869 870
  delete [] clusterMap;
  delete [] glyphIndices;
  delete [] textProperties;
  delete [] glyphProperties;
  delete [] glyphAdvances;
  delete [] glyphOffsets;
E
Ebrahim Byagowi 已提交
871 872

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

875 876
  /* Wow, done! */
  return true;
K
Khaled Hosny 已提交
877
}
878 879

hb_bool_t
880
_hb_directwrite_shape (hb_shape_plan_t    *shape_plan,
881 882 883 884 885
  hb_font_t          *font,
  hb_buffer_t        *buffer,
  const hb_feature_t *features,
  unsigned int        num_features)
{
886
  return _hb_directwrite_shape_full (shape_plan, font, buffer,
887 888 889 890 891 892 893 894
    features, num_features, 0);
}

/*
 * Public [experimental] API
 */

hb_bool_t
895
hb_directwrite_shape_experimental_width (hb_font_t          *font,
896 897 898 899 900
  hb_buffer_t        *buffer,
  const hb_feature_t *features,
  unsigned int        num_features,
  float               width)
{
901
  static const char *shapers = "directwrite";
902 903 904 905 906
  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);

907
  buffer->unsafe_to_break_all ();
908 909 910

  return res;
}