hb-directwrite.cc 25.7 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 38 39 40 41
/*
 * 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); }
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
  {
58
    mFontFileStream = fontFileStream;
59 60
  }

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

66
  // IDWriteFontFileLoader methods
67
  virtual HRESULT STDMETHODCALLTYPE CreateStreamFromKey (void const* fontFileReferenceKey,
E
Ebrahim Byagowi 已提交
68
    uint32_t fontFileReferenceKeySize,
69 70 71 72 73 74
    OUT IDWriteFontFileStream** fontFileStream)
  {
    *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
  IFACEMETHOD (QueryInterface) (IID const& iid, OUT void** ppObject) { return S_OK; }
  IFACEMETHOD_ (ULONG, AddRef) () { return 1; }
  IFACEMETHOD_ (ULONG, Release) () { return 1; }
92

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

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

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

112
  virtual void STDMETHODCALLTYPE ReleaseFileFragment (void* fragmentContext) { }
113

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

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


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

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

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

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

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

162
  DWriteFontFileLoader *fontFileLoader = new DWriteFontFileLoader (fontFileStream);
163 164 165 166 167 168 169 170 171
  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 已提交
172
    DEBUG_MSG (DIRECTWRITE, nullptr, __VA_ARGS__); \
173
    return nullptr; \
174 175
  } HB_STMT_END;

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

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

187 188 189 190 191 192 193 194
#undef FAIL

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

  data->dwriteFactory = dwriteFactory;
  data->fontFile = fontFile;
195
  data->fontFileStream = fontFileStream;
196 197
  data->fontFileLoader = fontFileLoader;
  data->fontFace = fontFace;
198
  data->faceBlob = blob;
199

200 201 202 203
  return data;
}

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


/*
 * shaper font data
 */

B
Rename  
Behdad Esfahbod 已提交
231
struct hb_directwrite_font_data_t
E
Ebrahim Byagowi 已提交
232
{
233 234
};

B
Rename  
Behdad Esfahbod 已提交
235
hb_directwrite_font_data_t *
236 237
_hb_directwrite_shaper_font_data_create (hb_font_t *font)
{
B
Behdad Esfahbod 已提交
238
  if (unlikely (!hb_directwrite_shaper_face_data_ensure (font->face))) return nullptr;
239

B
Rename  
Behdad Esfahbod 已提交
240
  hb_directwrite_font_data_t *data = new hb_directwrite_font_data_t;
241
  if (unlikely (!data))
B
Behdad Esfahbod 已提交
242
    return nullptr;
243 244 245 246 247

  return data;
}

void
B
Rename  
Behdad Esfahbod 已提交
248
_hb_directwrite_shaper_font_data_destroy (hb_directwrite_font_data_t *data)
249
{
250
  delete data;
251 252 253
}


254
// Most of TextAnalysis is originally written by Bas Schouten for Mozilla project
255 256 257 258 259 260
// but now is relicensed to MIT for HarfBuzz use
class TextAnalysis
  : public IDWriteTextAnalysisSource, public IDWriteTextAnalysisSink
{
public:

261 262 263
  IFACEMETHOD (QueryInterface) (IID const& iid, OUT void** ppObject) { return S_OK; }
  IFACEMETHOD_ (ULONG, AddRef) () { return 1; }
  IFACEMETHOD_ (ULONG, Release) () { return 1; }
264

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

278
    inline bool ContainsTextPosition (uint32_t aTextPosition) const
279
    {
280 281
      return aTextPosition >= mTextStart &&
	     aTextPosition <  mTextStart + mTextLength;
282 283 284 285 286 287
    }

    Run *nextRun;
  };

public:
288
  TextAnalysis (const wchar_t* text,
289
    uint32_t textLength,
290 291
    const wchar_t* localeName,
    DWRITE_READING_DIRECTION readingDirection)
292 293 294 295 296
    : mText (text)
    , mTextLength (textLength)
    , mLocaleName (localeName)
    , mReadingDirection (readingDirection)
    , mCurrentRun (nullptr) { };
297

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

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

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

    return hr;
  }

  // IDWriteTextAnalysisSource implementation

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

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

372 373
  IFACEMETHODIMP_ (DWRITE_READING_DIRECTION)
    GetParagraphReadingDirection () { return mReadingDirection; }
374

375
  IFACEMETHODIMP GetLocaleName (uint32_t textPosition,
376
    uint32_t* textLength,
377 378
    wchar_t const** localeName)
  {
379 380 381 382
    return S_OK;
  }

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

    return S_OK;
  }

  // IDWriteTextAnalysisSink implementation

  IFACEMETHODIMP
397
    SetScriptAnalysis (uint32_t textPosition,
398
    uint32_t textLength,
399 400
    DWRITE_SCRIPT_ANALYSIS const* scriptAnalysis)
  {
401 402
    SetCurrentRun (textPosition);
    SplitCurrentRun (textPosition);
403 404
    while (textLength > 0)
    {
405
      Run *run = FetchNextRun (&textLength);
406 407 408 409 410 411 412
      run->mScript = *scriptAnalysis;
    }

    return S_OK;
  }

  IFACEMETHODIMP
413
    SetLineBreakpoints (uint32_t textPosition,
414
    uint32_t textLength,
415 416
    const DWRITE_LINE_BREAKPOINT* lineBreakpoints) { return S_OK; }

417
  IFACEMETHODIMP SetBidiLevel (uint32_t textPosition,
418 419 420
    uint32_t textLength,
    uint8_t explicitLevel,
    uint8_t resolvedLevel) { return S_OK; }
421 422

  IFACEMETHODIMP
423
    SetNumberSubstitution (uint32_t textPosition,
424
    uint32_t textLength,
425 426 427
    IDWriteNumberSubstitution* numberSubstitution) { return S_OK; }

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

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

448
  void SetCurrentRun (uint32_t textPosition)
449 450 451 452 453 454
  {
    // 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.

455
    if (mCurrentRun && mCurrentRun->ContainsTextPosition (textPosition))
456 457
      return;

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

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

    *newRun = *mCurrentRun;

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

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

  // Current processing state.
  Run *mCurrentRun;

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

514
static inline uint16_t hb_uint16_swap (const uint16_t v)
515
{ return (v >> 8) | (v << 8); }
516
static inline uint32_t hb_uint32_swap (const uint32_t v)
517
{ return (hb_uint16_swap (v) << 16) | hb_uint16_swap (v >> 16); }
518 519 520 521 522

/*
 * shaper
 */

523
static hb_bool_t
524
_hb_directwrite_shape_full (hb_shape_plan_t    *shape_plan,
525 526 527
  hb_font_t          *font,
  hb_buffer_t        *buffer,
  const hb_feature_t *features,
528 529
  unsigned int        num_features,
  float               lineWidth)
530 531
{
  hb_face_t *face = font->face;
532 533
  const hb_directwrite_face_data_t *face_data = face->data.directwrite;
  const hb_directwrite_font_data_t *font_data = font->data.directwrite;
534 535
  IDWriteFactory *dwriteFactory = face_data->dwriteFactory;
  IDWriteFontFace *fontFace = face_data->fontFace;
536 537

  IDWriteTextAnalyzer* analyzer;
538
  dwriteFactory->CreateTextAnalyzer (&analyzer);
539 540 541 542 543 544 545 546 547 548 549 550 551 552

  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

553
  ALLOCATE_ARRAY (wchar_t, textString, buffer->len * 2);
554 555 556 557 558

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

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

  // TODO: Handle TEST_DISABLE_OPTIONAL_LIGATURES

585
  DWRITE_READING_DIRECTION readingDirection = buffer->props.direction ?
586 587 588
    DWRITE_READING_DIRECTION_RIGHT_TO_LEFT :
    DWRITE_READING_DIRECTION_LEFT_TO_RIGHT;

K
Khaled Hosny 已提交
589
  /*
590 591 592 593
  * 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.
  */
594
  uint32_t textLength = buffer->len;
595

596
  TextAnalysis analysis (textString, textLength, nullptr, readingDirection);
597
  TextAnalysis::Run *runHead;
598
  HRESULT hr;
599
  hr = analysis.GenerateResults (analyzer, &runHead);
600

601 602
#define FAIL(...) \
  HB_STMT_START { \
B
Behdad Esfahbod 已提交
603
    DEBUG_MSG (DIRECTWRITE, nullptr, __VA_ARGS__); \
604 605 606
    return false; \
  } HB_STMT_END;

E
Ebrahim Byagowi 已提交
607
  if (FAILED (hr))
608
    FAIL ("Analyzer failed to generate results.");
609

610 611
  uint32_t maxGlyphCount = 3 * textLength / 2 + 16;
  uint32_t glyphCount;
E
Ebrahim Byagowi 已提交
612
  bool isRightToLeft = HB_DIRECTION_IS_BACKWARD (buffer->props.direction);
613

E
Ebrahim Byagowi 已提交
614
  const wchar_t localeName[20] = {0};
B
Behdad Esfahbod 已提交
615
  if (buffer->props.language != nullptr)
E
Ebrahim Byagowi 已提交
616 617 618
  {
    mbstowcs ((wchar_t*) localeName,
      hb_language_to_string (buffer->props.language), 20);
619 620
  }

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

639 640 641
  uint16_t* clusterMap = new uint16_t[textLength];
  DWRITE_SHAPING_TEXT_PROPERTIES* textProperties =
    new DWRITE_SHAPING_TEXT_PROPERTIES[textLength];
E
Ebrahim Byagowi 已提交
642
retry_getglyphs:
643 644 645
  uint16_t* glyphIndices = new uint16_t[maxGlyphCount];
  DWRITE_SHAPING_GLYPH_PROPERTIES* glyphProperties =
    new DWRITE_SHAPING_GLYPH_PROPERTIES[maxGlyphCount];
E
Ebrahim Byagowi 已提交
646

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

  if (unlikely (hr == HRESULT_FROM_WIN32 (ERROR_INSUFFICIENT_BUFFER)))
  {
654 655
    delete [] glyphIndices;
    delete [] glyphProperties;
656

E
Ebrahim Byagowi 已提交
657
    maxGlyphCount *= 2;
658 659

    goto retry_getglyphs;
660
  }
E
Ebrahim Byagowi 已提交
661
  if (FAILED (hr))
662
    FAIL ("Analyzer failed to get glyphs.");
663

664 665
  float* glyphAdvances = new float[maxGlyphCount];
  DWRITE_GLYPH_OFFSET* glyphOffsets = new DWRITE_GLYPH_OFFSET[maxGlyphCount];
666 667

  /* The -2 in the following is to compensate for possible
668 669 670 671 672 673 674
   * 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 已提交
675
  ALLOCATE_ARRAY (uint32_t, vis_clusters, glyphs_size);
676 677 678

#undef ALLOCATE_ARRAY

679
  int fontEmSize = font->face->get_upem ();
E
Ebrahim Byagowi 已提交
680 681 682 683 684 685 686 687 688 689 690
  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 已提交
691
    false, isRightToLeft, &runHead->mScript, localeName,
E
Ebrahim Byagowi 已提交
692 693 694 695
    &dwFeatures, featureRangeLengths, 1,
    glyphAdvances, glyphOffsets);

  if (FAILED (hr))
696
    FAIL ("Analyzer failed to get glyph placements.");
697

698 699
  IDWriteTextAnalyzer1* analyzer1;
  analyzer->QueryInterface (&analyzer1);
E
Ebrahim Byagowi 已提交
700

701
  if (analyzer1 && lineWidth)
E
Ebrahim Byagowi 已提交
702 703
  {

704
    DWRITE_JUSTIFICATION_OPPORTUNITY* justificationOpportunities =
705
      new DWRITE_JUSTIFICATION_OPPORTUNITY[maxGlyphCount];
706 707 708
    hr = analyzer1->GetJustificationOpportunities (fontFace, fontEmSize,
      runHead->mScript, textLength, glyphCount, textString, clusterMap,
      glyphProperties, justificationOpportunities);
E
Ebrahim Byagowi 已提交
709

710 711
    if (FAILED (hr))
      FAIL ("Analyzer failed to get justification opportunities.");
E
Ebrahim Byagowi 已提交
712

713 714
    float* justifiedGlyphAdvances = new float[maxGlyphCount];
    DWRITE_GLYPH_OFFSET* justifiedGlyphOffsets = new DWRITE_GLYPH_OFFSET[glyphCount];
715 716
    hr = analyzer1->JustifyGlyphAdvances (lineWidth, glyphCount, justificationOpportunities,
      glyphAdvances, glyphOffsets, justifiedGlyphAdvances, justifiedGlyphOffsets);
E
Ebrahim Byagowi 已提交
717

718
    if (FAILED (hr))
719
      FAIL ("Analyzer failed to get justified glyph advances.");
720

721 722 723
    DWRITE_SCRIPT_PROPERTIES scriptProperties;
    hr = analyzer1->GetScriptProperties (runHead->mScript, &scriptProperties);
    if (FAILED (hr))
724
      FAIL ("Analyzer failed to get script properties.");
725 726 727 728 729
    uint32_t justificationCharacter = scriptProperties.justificationCharacter;

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

743 744
      if (hr == HRESULT_FROM_WIN32 (ERROR_INSUFFICIENT_BUFFER))
      {
745 746 747 748
	maxGlyphCount = actualGlyphsCount;
	delete [] modifiedGlyphIndices;
	delete [] modifiedGlyphAdvances;
	delete [] modifiedGlyphOffsets;
749

750
	maxGlyphCount = actualGlyphsCount;
751

752
	goto retry_getjustifiedglyphs;
753 754
      }
      if (FAILED (hr))
755
	FAIL ("Analyzer failed to get justified glyphs.");
756

757 758 759 760
      delete [] clusterMap;
      delete [] glyphIndices;
      delete [] glyphAdvances;
      delete [] glyphOffsets;
E
Ebrahim Byagowi 已提交
761

762 763 764 765 766
      glyphCount = actualGlyphsCount;
      clusterMap = modifiedClusterMap;
      glyphIndices = modifiedGlyphIndices;
      glyphAdvances = modifiedGlyphAdvances;
      glyphOffsets = modifiedGlyphOffsets;
E
Ebrahim Byagowi 已提交
767

768 769
      delete [] justifiedGlyphAdvances;
      delete [] justifiedGlyphOffsets;
770 771 772
    }
    else
    {
773 774
      delete [] glyphAdvances;
      delete [] glyphOffsets;
775

776 777 778
      glyphAdvances = justifiedGlyphAdvances;
      glyphOffsets = justifiedGlyphOffsets;
    }
E
Ebrahim Byagowi 已提交
779

780
    delete [] justificationOpportunities;
E
Ebrahim Byagowi 已提交
781

782
  }
E
Ebrahim Byagowi 已提交
783

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

#undef utf16_index

E
Ebrahim Byagowi 已提交
802
  if (unlikely (!buffer->ensure (glyphCount)))
803
    FAIL ("Buffer in error");
804 805 806 807 808

#undef FAIL

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

E
Ebrahim Byagowi 已提交
813
    info->codepoint = glyphIndices[i];
814 815 816
    info->cluster = vis_clusters[i];

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

  /* Set glyph positions */
  buffer->clear_positions ();
E
Ebrahim Byagowi 已提交
824
  for (unsigned int i = 0; i < glyphCount; i++)
825 826 827 828 829
  {
    hb_glyph_info_t *info = &buffer->info[i];
    hb_glyph_position_t *pos = &buffer->pos[i];

    /* TODO vertical */
E
Ebrahim Byagowi 已提交
830
    pos->x_advance = x_mult * (int32_t) info->mask;
E
Ebrahim Byagowi 已提交
831 832
    pos->x_offset =
      x_mult * (isRightToLeft ? -info->var1.i32 : info->var1.i32);
E
Ebrahim Byagowi 已提交
833
    pos->y_offset = y_mult * info->var2.i32;
834 835
  }

E
Ebrahim Byagowi 已提交
836
  if (isRightToLeft)
837 838
    hb_buffer_reverse (buffer);

839 840 841 842 843 844
  delete [] clusterMap;
  delete [] glyphIndices;
  delete [] textProperties;
  delete [] glyphProperties;
  delete [] glyphAdvances;
  delete [] glyphOffsets;
E
Ebrahim Byagowi 已提交
845 846

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

849 850
  /* Wow, done! */
  return true;
K
Khaled Hosny 已提交
851
}
852 853

hb_bool_t
854
_hb_directwrite_shape (hb_shape_plan_t    *shape_plan,
855 856 857 858 859
  hb_font_t          *font,
  hb_buffer_t        *buffer,
  const hb_feature_t *features,
  unsigned int        num_features)
{
860
  return _hb_directwrite_shape_full (shape_plan, font, buffer,
861 862 863 864 865 866 867 868
    features, num_features, 0);
}

/*
 * Public [experimental] API
 */

hb_bool_t
869
hb_directwrite_shape_experimental_width (hb_font_t          *font,
870 871 872 873 874
  hb_buffer_t        *buffer,
  const hb_feature_t *features,
  unsigned int        num_features,
  float               width)
{
875
  static const char *shapers = "directwrite";
876 877 878 879 880
  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);

881
  buffer->unsafe_to_break_all ();
882 883 884

  return res;
}