blob: fd8ab5cfebb040396e091da16ebcf0f34b782cc4 [file] [log] [blame]
Ebrahim Byagowif35b3e92015-09-11 09:48:12 +04301/*
2 * Copyright © 2015 Ebrahim Byagowi
3 *
4 * This is part of HarfBuzz, a text shaping library.
5 *
6 * Permission is hereby granted, without written agreement and without
7 * license or royalty fees, to use, copy, modify, and distribute this
8 * software and its documentation for any purpose, provided that the
9 * above copyright notice and the following two paragraphs appear in
10 * all copies of this software.
11 *
12 * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
13 * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
14 * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
15 * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
16 * DAMAGE.
17 *
18 * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
19 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
20 * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
21 * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
22 * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
23 */
24
25#define HB_SHAPER directwrite
26#include "hb-shaper-impl-private.hh"
27
28#include <dwrite.h>
29
30#include "hb-directwrite.h"
31
32#include "hb-open-file-private.hh"
33#include "hb-ot-name-table.hh"
34#include "hb-ot-tag.h"
35
36
37#ifndef HB_DEBUG_DIRECTWRITE
38#define HB_DEBUG_DIRECTWRITE (HB_DEBUG+0)
39#endif
40
41HB_SHAPER_DATA_ENSURE_DECLARE(directwrite, face)
42HB_SHAPER_DATA_ENSURE_DECLARE(directwrite, font)
43
44/*
45* shaper face data
46*/
47
48struct hb_directwrite_shaper_face_data_t {
49 HANDLE fh;
50 wchar_t face_name[LF_FACESIZE];
51};
52
53/* face_name should point to a wchar_t[LF_FACESIZE] object. */
54static void
55_hb_generate_unique_face_name(wchar_t *face_name, unsigned int *plen)
56{
57 /* We'll create a private name for the font from a UUID using a simple,
58 * somewhat base64-like encoding scheme */
59 const char *enc = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-";
60 UUID id;
61 UuidCreate ((UUID*)&id);
62 ASSERT_STATIC (2 + 3 * (16 / 2) < LF_FACESIZE);
63 unsigned int name_str_len = 0;
64 face_name[name_str_len++] = 'F';
65 face_name[name_str_len++] = '_';
66 unsigned char *p = (unsigned char *)&id;
67 for (unsigned int i = 0; i < 16; i += 2)
68 {
69 /* Spread the 16 bits from two bytes of the UUID across three chars of face_name,
70 * using the bits in groups of 5,5,6 to select chars from enc.
71 * This will generate 24 characters; with the 'F_' prefix we already provided,
72 * the name will be 26 chars (plus the NUL terminator), so will always fit within
73 * face_name (LF_FACESIZE = 32). */
74 face_name[name_str_len++] = enc[p[i] >> 3];
75 face_name[name_str_len++] = enc[((p[i] << 2) | (p[i + 1] >> 6)) & 0x1f];
76 face_name[name_str_len++] = enc[p[i + 1] & 0x3f];
77 }
78 face_name[name_str_len] = 0;
79 if (plen)
80 *plen = name_str_len;
81}
82
83/* Destroys blob. */
84static hb_blob_t *
85_hb_rename_font(hb_blob_t *blob, wchar_t *new_name)
86{
87 /* Create a copy of the font data, with the 'name' table replaced by a
88 * table that names the font with our private F_* name created above.
89 * For simplicity, we just append a new 'name' table and update the
90 * sfnt directory; the original table is left in place, but unused.
91 *
92 * The new table will contain just 5 name IDs: family, style, unique,
93 * full, PS. All of them point to the same name data with our unique name.
94 */
95
96 blob = OT::Sanitizer<OT::OpenTypeFontFile>::sanitize (blob);
97
98 unsigned int length, new_length, name_str_len;
99 const char *orig_sfnt_data = hb_blob_get_data (blob, &length);
100
101 _hb_generate_unique_face_name (new_name, &name_str_len);
102
103 static const uint16_t name_IDs[] = { 1, 2, 3, 4, 6 };
104
105 unsigned int name_table_length = OT::name::min_size +
106 ARRAY_LENGTH(name_IDs) * OT::NameRecord::static_size +
107 name_str_len * 2; /* for name data in UTF16BE form */
108 unsigned int name_table_offset = (length + 3) & ~3;
109
110 new_length = name_table_offset + ((name_table_length + 3) & ~3);
111 void *new_sfnt_data = calloc(1, new_length);
112 if (!new_sfnt_data)
113 {
114 hb_blob_destroy (blob);
115 return NULL;
116 }
117
118 memcpy(new_sfnt_data, orig_sfnt_data, length);
119
120 OT::name &name = OT::StructAtOffset<OT::name> (new_sfnt_data, name_table_offset);
121 name.format.set (0);
122 name.count.set (ARRAY_LENGTH (name_IDs));
123 name.stringOffset.set (name.get_size());
124 for (unsigned int i = 0; i < ARRAY_LENGTH (name_IDs); i++)
125 {
126 OT::NameRecord &record = name.nameRecord[i];
127 record.platformID.set(3);
128 record.encodingID.set(1);
129 record.languageID.set(0x0409u); /* English */
130 record.nameID.set(name_IDs[i]);
131 record.length.set(name_str_len * 2);
132 record.offset.set(0);
133 }
134
135 /* Copy string data from new_name, converting wchar_t to UTF16BE. */
136 unsigned char *p = &OT::StructAfter<unsigned char>(name);
137 for (unsigned int i = 0; i < name_str_len; i++)
138 {
139 *p++ = new_name[i] >> 8;
140 *p++ = new_name[i] & 0xff;
141 }
142
143 /* Adjust name table entry to point to new name table */
144 const OT::OpenTypeFontFile &file = *(OT::OpenTypeFontFile *) (new_sfnt_data);
145 unsigned int face_count = file.get_face_count ();
146 for (unsigned int face_index = 0; face_index < face_count; face_index++)
147 {
148 /* Note: doing multiple edits (ie. TTC) can be unsafe. There may be
149 * toe-stepping. But we don't really care. */
150 const OT::OpenTypeFontFace &face = file.get_face (face_index);
151 unsigned int index;
152 if (face.find_table_index (HB_OT_TAG_name, &index))
153 {
154 OT::TableRecord &record = const_cast<OT::TableRecord &> (face.get_table (index));
155 record.checkSum.set_for_data (&name, name_table_length);
156 record.offset.set (name_table_offset);
157 record.length.set (name_table_length);
158 }
159 else if (face_index == 0) /* Fail if first face doesn't have 'name' table. */
160 {
161 free (new_sfnt_data);
162 hb_blob_destroy (blob);
163 return NULL;
164 }
165 }
166
167 /* The checkSumAdjustment field in the 'head' table is now wrong,
168 * but that doesn't actually seem to cause any problems so we don't
169 * bother. */
170
171 hb_blob_destroy (blob);
172 return hb_blob_create ((const char *)new_sfnt_data, new_length,
173 HB_MEMORY_MODE_WRITABLE, NULL, free);
174}
175
176hb_directwrite_shaper_face_data_t *
177_hb_directwrite_shaper_face_data_create(hb_face_t *face)
178{
179 hb_directwrite_shaper_face_data_t *data = (hb_directwrite_shaper_face_data_t *)calloc(1, sizeof (hb_directwrite_shaper_face_data_t));
180 if (unlikely (!data))
181 return NULL;
182
183 hb_blob_t *blob = hb_face_reference_blob (face);
184 if (unlikely (!hb_blob_get_length (blob)))
185 DEBUG_MSG(DIRECTWRITE, face, "Face has empty blob");
186
187 blob = _hb_rename_font (blob, data->face_name);
188 if (unlikely (!blob))
189 {
190 free(data);
191 return NULL;
192 }
193
194 DWORD num_fonts_installed;
195 data->fh = AddFontMemResourceEx ((void *)hb_blob_get_data(blob, NULL),
196 hb_blob_get_length (blob),
197 0, &num_fonts_installed);
198 if (unlikely (!data->fh))
199 {
200 DEBUG_MSG (DIRECTWRITE, face, "Face AddFontMemResourceEx() failed");
201 free (data);
202 return NULL;
203 }
204
205 return data;
206}
207
208void
209_hb_directwrite_shaper_face_data_destroy(hb_directwrite_shaper_face_data_t *data)
210{
211 RemoveFontMemResourceEx(data->fh);
212 free(data);
213}
214
215
216/*
217 * shaper font data
218 */
219
220struct hb_directwrite_shaper_font_data_t {
221 HDC hdc;
222 LOGFONTW log_font;
223 HFONT hfont;
224};
225
226static bool
227populate_log_font (LOGFONTW *lf,
228 hb_font_t *font)
229{
230 memset (lf, 0, sizeof (*lf));
231 lf->lfHeight = -font->y_scale;
232 lf->lfCharSet = DEFAULT_CHARSET;
233
234 hb_face_t *face = font->face;
235 hb_directwrite_shaper_face_data_t *face_data = HB_SHAPER_DATA_GET (face);
236
237 memcpy (lf->lfFaceName, face_data->face_name, sizeof (lf->lfFaceName));
238
239 return true;
240}
241
242hb_directwrite_shaper_font_data_t *
243_hb_directwrite_shaper_font_data_create (hb_font_t *font)
244{
245 if (unlikely (!hb_directwrite_shaper_face_data_ensure (font->face))) return NULL;
246
247 hb_directwrite_shaper_font_data_t *data = (hb_directwrite_shaper_font_data_t *) calloc (1, sizeof (hb_directwrite_shaper_font_data_t));
248 if (unlikely (!data))
249 return NULL;
250
251 data->hdc = GetDC (NULL);
252
253 if (unlikely (!populate_log_font (&data->log_font, font))) {
254 DEBUG_MSG (DIRECTWRITE, font, "Font populate_log_font() failed");
255 _hb_directwrite_shaper_font_data_destroy (data);
256 return NULL;
257 }
258
259 data->hfont = CreateFontIndirectW (&data->log_font);
260 if (unlikely (!data->hfont)) {
261 DEBUG_MSG (DIRECTWRITE, font, "Font CreateFontIndirectW() failed");
262 _hb_directwrite_shaper_font_data_destroy (data);
263 return NULL;
264 }
265
266 if (!SelectObject (data->hdc, data->hfont)) {
267 DEBUG_MSG (DIRECTWRITE, font, "Font SelectObject() failed");
268 _hb_directwrite_shaper_font_data_destroy (data);
269 return NULL;
270 }
271
272 return data;
273}
274
275void
276_hb_directwrite_shaper_font_data_destroy (hb_directwrite_shaper_font_data_t *data)
277{
278 if (data->hdc)
279 ReleaseDC (NULL, data->hdc);
280 if (data->hfont)
281 DeleteObject (data->hfont);
282 free (data);
283}
284
285LOGFONTW *
286hb_directwrite_font_get_logfontw (hb_font_t *font)
287{
288 if (unlikely (!hb_directwrite_shaper_font_data_ensure (font))) return NULL;
289 hb_directwrite_shaper_font_data_t *font_data = HB_SHAPER_DATA_GET (font);
290 return &font_data->log_font;
291}
292
293HFONT
294hb_directwrite_font_get_hfont (hb_font_t *font)
295{
296 if (unlikely (!hb_directwrite_shaper_font_data_ensure (font))) return NULL;
297 hb_directwrite_shaper_font_data_t *font_data = HB_SHAPER_DATA_GET (font);
298 return font_data->hfont;
299}
300
301
302/*
303 * shaper shape_plan data
304 */
305
306struct hb_directwrite_shaper_shape_plan_data_t {};
307
308hb_directwrite_shaper_shape_plan_data_t *
309_hb_directwrite_shaper_shape_plan_data_create (hb_shape_plan_t *shape_plan HB_UNUSED,
310 const hb_feature_t *user_features HB_UNUSED,
311 unsigned int num_user_features HB_UNUSED)
312{
313 return (hb_directwrite_shaper_shape_plan_data_t *) HB_SHAPER_DATA_SUCCEEDED;
314}
315
316void
317_hb_directwrite_shaper_shape_plan_data_destroy (hb_directwrite_shaper_shape_plan_data_t *data HB_UNUSED)
318{
319}
320
321// Most of here TextAnalysis is originally written by Bas Schouten for Mozilla project
322// but now is relicensed to MIT for HarfBuzz use
323class TextAnalysis
324 : public IDWriteTextAnalysisSource, public IDWriteTextAnalysisSink
325{
326public:
327
328 IFACEMETHOD(QueryInterface)(IID const& iid, OUT void** ppObject) { return S_OK; }
329 IFACEMETHOD_(ULONG, AddRef)() { return 1; }
330 IFACEMETHOD_(ULONG, Release)() { return 1; }
331
332 // A single contiguous run of characters containing the same analysis
333 // results.
334 struct Run
335 {
336 UINT32 mTextStart; // starting text position of this run
337 UINT32 mTextLength; // number of contiguous code units covered
338 UINT32 mGlyphStart; // starting glyph in the glyphs array
339 UINT32 mGlyphCount; // number of glyphs associated with this run of
340 // text
341 DWRITE_SCRIPT_ANALYSIS mScript;
342 UINT8 mBidiLevel;
343 bool mIsSideways;
344
345 inline bool ContainsTextPosition(UINT32 aTextPosition) const
346 {
347 return aTextPosition >= mTextStart
348 && aTextPosition < mTextStart + mTextLength;
349 }
350
351 Run *nextRun;
352 };
353
354public:
355 TextAnalysis(const wchar_t* text,
356 UINT32 textLength,
357 const wchar_t* localeName,
358 DWRITE_READING_DIRECTION readingDirection)
359 : mText(text)
360 , mTextLength(textLength)
361 , mLocaleName(localeName)
362 , mReadingDirection(readingDirection)
363 , mCurrentRun(NULL) { };
364
365 ~TextAnalysis() {
366 // delete runs, except mRunHead which is part of the TextAnalysis object
367 for (Run *run = mRunHead.nextRun; run;) {
368 Run *origRun = run;
369 run = run->nextRun;
370 delete origRun;
371 }
372 }
373
374 STDMETHODIMP GenerateResults(IDWriteTextAnalyzer* textAnalyzer,
375 Run **runHead) {
376 // Analyzes the text using the script analyzer and returns
377 // the result as a series of runs.
378
379 HRESULT hr = S_OK;
380
381 // Initially start out with one result that covers the entire range.
382 // This result will be subdivided by the analysis processes.
383 mRunHead.mTextStart = 0;
384 mRunHead.mTextLength = mTextLength;
385 mRunHead.mBidiLevel =
386 (mReadingDirection == DWRITE_READING_DIRECTION_RIGHT_TO_LEFT);
387 mRunHead.nextRun = NULL;
388 mCurrentRun = &mRunHead;
389
390 // Call each of the analyzers in sequence, recording their results.
391 if (SUCCEEDED(hr = textAnalyzer->AnalyzeScript(this,
392 0,
393 mTextLength,
394 this))) {
395 *runHead = &mRunHead;
396 }
397
398 return hr;
399 }
400
401 // IDWriteTextAnalysisSource implementation
402
403 IFACEMETHODIMP GetTextAtPosition(UINT32 textPosition,
404 OUT WCHAR const** textString,
405 OUT UINT32* textLength)
406 {
407 if (textPosition >= mTextLength) {
408 // No text at this position, valid query though.
409 *textString = NULL;
410 *textLength = 0;
411 }
412 else {
413 *textString = mText + textPosition;
414 *textLength = mTextLength - textPosition;
415 }
416 return S_OK;
417 }
418
419 IFACEMETHODIMP GetTextBeforePosition(UINT32 textPosition,
420 OUT WCHAR const** textString,
421 OUT UINT32* textLength)
422 {
423 if (textPosition == 0 || textPosition > mTextLength) {
424 // Either there is no text before here (== 0), or this
425 // is an invalid position. The query is considered valid thouh.
426 *textString = NULL;
427 *textLength = 0;
428 }
429 else {
430 *textString = mText;
431 *textLength = textPosition;
432 }
433 return S_OK;
434 }
435
436 IFACEMETHODIMP_(DWRITE_READING_DIRECTION)
437 GetParagraphReadingDirection() { return mReadingDirection; }
438
439 IFACEMETHODIMP GetLocaleName(UINT32 textPosition,
440 UINT32* textLength,
441 WCHAR const** localeName) {
442 return S_OK;
443 }
444
445 IFACEMETHODIMP
446 GetNumberSubstitution(UINT32 textPosition,
447 OUT UINT32* textLength,
448 OUT IDWriteNumberSubstitution** numberSubstitution)
449 {
450 // We do not support number substitution.
451 *numberSubstitution = NULL;
452 *textLength = mTextLength - textPosition;
453
454 return S_OK;
455 }
456
457 // IDWriteTextAnalysisSink implementation
458
459 IFACEMETHODIMP
460 SetScriptAnalysis(UINT32 textPosition,
461 UINT32 textLength,
462 DWRITE_SCRIPT_ANALYSIS const* scriptAnalysis)
463 {
464 SetCurrentRun(textPosition);
465 SplitCurrentRun(textPosition);
466 while (textLength > 0) {
467 Run *run = FetchNextRun(&textLength);
468 run->mScript = *scriptAnalysis;
469 }
470
471 return S_OK;
472 }
473
474 IFACEMETHODIMP
475 SetLineBreakpoints(UINT32 textPosition,
476 UINT32 textLength,
477 const DWRITE_LINE_BREAKPOINT* lineBreakpoints) { return S_OK; }
478
479 IFACEMETHODIMP SetBidiLevel(UINT32 textPosition,
480 UINT32 textLength,
481 UINT8 explicitLevel,
482 UINT8 resolvedLevel) { return S_OK; }
483
484 IFACEMETHODIMP
485 SetNumberSubstitution(UINT32 textPosition,
486 UINT32 textLength,
487 IDWriteNumberSubstitution* numberSubstitution) { return S_OK; }
488
489protected:
490 Run *FetchNextRun(IN OUT UINT32* textLength)
491 {
492 // Used by the sink setters, this returns a reference to the next run.
493 // Position and length are adjusted to now point after the current run
494 // being returned.
495
496 Run *origRun = mCurrentRun;
497 // Split the tail if needed (the length remaining is less than the
498 // current run's size).
499 if (*textLength < mCurrentRun->mTextLength) {
500 SplitCurrentRun(mCurrentRun->mTextStart + *textLength);
501 }
502 else {
503 // Just advance the current run.
504 mCurrentRun = mCurrentRun->nextRun;
505 }
506 *textLength -= origRun->mTextLength;
507
508 // Return a reference to the run that was just current.
509 return origRun;
510 }
511
512 void SetCurrentRun(UINT32 textPosition)
513 {
514 // Move the current run to the given position.
515 // Since the analyzers generally return results in a forward manner,
516 // this will usually just return early. If not, find the
517 // corresponding run for the text position.
518
519 if (mCurrentRun && mCurrentRun->ContainsTextPosition(textPosition)) {
520 return;
521 }
522
523 for (Run *run = &mRunHead; run; run = run->nextRun) {
524 if (run->ContainsTextPosition(textPosition)) {
525 mCurrentRun = run;
526 return;
527 }
528 }
529 //NS_NOTREACHED("We should always be able to find the text position in one \
530 // of our runs");
531 }
532
533 void SplitCurrentRun(UINT32 splitPosition)
534 {
535 if (!mCurrentRun) {
536 //NS_ASSERTION(false, "SplitCurrentRun called without current run.");
537 // Shouldn't be calling this when no current run is set!
538 return;
539 }
540 // Split the current run.
541 if (splitPosition <= mCurrentRun->mTextStart) {
542 // No need to split, already the start of a run
543 // or before it. Usually the first.
544 return;
545 }
546 Run *newRun = new Run;
547
548 *newRun = *mCurrentRun;
549
550 // Insert the new run in our linked list.
551 newRun->nextRun = mCurrentRun->nextRun;
552 mCurrentRun->nextRun = newRun;
553
554 // Adjust runs' text positions and lengths.
555 UINT32 splitPoint = splitPosition - mCurrentRun->mTextStart;
556 newRun->mTextStart += splitPoint;
557 newRun->mTextLength -= splitPoint;
558 mCurrentRun->mTextLength = splitPoint;
559 mCurrentRun = newRun;
560 }
561
562protected:
563 // Input
564 // (weak references are fine here, since this class is a transient
565 // stack-based helper that doesn't need to copy data)
566 UINT32 mTextLength;
567 const WCHAR* mText;
568 const WCHAR* mLocaleName;
569 DWRITE_READING_DIRECTION mReadingDirection;
570
571 // Current processing state.
572 Run *mCurrentRun;
573
574 // Output is a list of runs starting here
575 Run mRunHead;
576};
577
578
579/*
580 * shaper
581 */
582
583hb_bool_t
584_hb_directwrite_shape(hb_shape_plan_t *shape_plan,
585 hb_font_t *font,
586 hb_buffer_t *buffer,
587 const hb_feature_t *features,
588 unsigned int num_features)
589{
590 hb_face_t *face = font->face;
591 hb_directwrite_shaper_face_data_t *face_data = HB_SHAPER_DATA_GET (face);
592 hb_directwrite_shaper_font_data_t *font_data = HB_SHAPER_DATA_GET (font);
593
594 // factory probably should be cached
595 IDWriteFactory* dwriteFactory;
596 DWriteCreateFactory(
597 DWRITE_FACTORY_TYPE_SHARED,
598 __uuidof(IDWriteFactory),
599 reinterpret_cast<IUnknown**>(&dwriteFactory)
600 );
601
602 IDWriteGdiInterop *gdiInterop;
603 dwriteFactory->GetGdiInterop (&gdiInterop);
604 IDWriteFontFace* fontFace;
605 gdiInterop->CreateFontFaceFromHdc (font_data->hdc, &fontFace);
606
607 IDWriteTextAnalyzer* analyzer;
608 dwriteFactory->CreateTextAnalyzer (&analyzer);
609
610 unsigned int scratch_size;
611 hb_buffer_t::scratch_buffer_t *scratch = buffer->get_scratch_buffer (&scratch_size);
612#define ALLOCATE_ARRAY(Type, name, len) \
613 Type *name = (Type *) scratch; \
614 { \
615 unsigned int _consumed = DIV_CEIL ((len) * sizeof (Type), sizeof (*scratch)); \
616 assert (_consumed <= scratch_size); \
617 scratch += _consumed; \
618 scratch_size -= _consumed; \
619 }
620
621#define utf16_index() var1.u32
622
623 ALLOCATE_ARRAY(WCHAR, pchars, buffer->len * 2);
624
625 unsigned int chars_len = 0;
626 for (unsigned int i = 0; i < buffer->len; i++)
627 {
628 hb_codepoint_t c = buffer->info[i].codepoint;
629 buffer->info[i].utf16_index() = chars_len;
630 if (likely(c <= 0xFFFFu))
631 pchars[chars_len++] = c;
632 else if (unlikely(c > 0x10FFFFu))
633 pchars[chars_len++] = 0xFFFDu;
634 else {
635 pchars[chars_len++] = 0xD800u + ((c - 0x10000u) >> 10);
636 pchars[chars_len++] = 0xDC00u + ((c - 0x10000u) & ((1 << 10) - 1));
637 }
638 }
639
640 ALLOCATE_ARRAY(WORD, log_clusters, chars_len);
641 if (num_features)
642 {
643 /* Need log_clusters to assign features. */
644 chars_len = 0;
645 for (unsigned int i = 0; i < buffer->len; i++)
646 {
647 hb_codepoint_t c = buffer->info[i].codepoint;
648 unsigned int cluster = buffer->info[i].cluster;
649 log_clusters[chars_len++] = cluster;
650 if (hb_in_range(c, 0x10000u, 0x10FFFFu))
651 log_clusters[chars_len++] = cluster; /* Surrogates. */
652 }
653 }
654
655 HRESULT hr;
656 // TODO: Handle TEST_DISABLE_OPTIONAL_LIGATURES
657
658 DWRITE_READING_DIRECTION readingDirection = buffer->props.direction ?
659 DWRITE_READING_DIRECTION_RIGHT_TO_LEFT :
660 DWRITE_READING_DIRECTION_LEFT_TO_RIGHT;
661
Khaled Hosnyd7bf9d02015-12-29 02:23:24 +0400662 /*
Ebrahim Byagowif35b3e92015-09-11 09:48:12 +0430663 * There's an internal 16-bit limit on some things inside the analyzer,
664 * but we never attempt to shape a word longer than 64K characters
665 * in a single gfxShapedWord, so we cannot exceed that limit.
666 */
667 UINT32 length = buffer->len;
668
669 TextAnalysis analysis(pchars, length, NULL, readingDirection);
670 TextAnalysis::Run *runHead;
671 hr = analysis.GenerateResults(analyzer, &runHead);
672
673 if (FAILED(hr)) {
674 //NS_WARNING("Analyzer failed to generate results.");
675 return false;
676 }
677
678 UINT32 maxGlyphs = 3 * length / 2 + 16;
679
680#define INITIAL_GLYPH_SIZE 400
681 UINT16* clusters = (UINT16*)malloc(INITIAL_GLYPH_SIZE * sizeof(UINT16));
682 UINT16* glyphs = (UINT16*)malloc(INITIAL_GLYPH_SIZE * sizeof(UINT16));
683 DWRITE_SHAPING_TEXT_PROPERTIES* textProperties = (DWRITE_SHAPING_TEXT_PROPERTIES*)
684 malloc(INITIAL_GLYPH_SIZE * sizeof(DWRITE_SHAPING_TEXT_PROPERTIES));
685 DWRITE_SHAPING_GLYPH_PROPERTIES* glyphProperties = (DWRITE_SHAPING_GLYPH_PROPERTIES*)
686 malloc(INITIAL_GLYPH_SIZE * sizeof(DWRITE_SHAPING_GLYPH_PROPERTIES));
687
688 UINT32 actualGlyphs;
689
690 bool backward = HB_DIRECTION_IS_BACKWARD(buffer->props.direction);
691
692 wchar_t lang[4];
693 mbstowcs(lang, hb_language_to_string(buffer->props.language), 4);
694 hr = analyzer->GetGlyphs(pchars, length,
695 fontFace, FALSE,
696 buffer->props.direction,
697 &runHead->mScript, (const wchar_t*)lang, NULL, NULL, NULL, 0,
698 maxGlyphs, clusters, textProperties,
699 glyphs, glyphProperties, &actualGlyphs);
700
701 if (hr == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER)) {
702 free(clusters);
703 free(glyphs);
704 free(textProperties);
705 free(glyphProperties);
706
707 clusters = (UINT16*)malloc(INITIAL_GLYPH_SIZE * sizeof(UINT16));
708 glyphs = (UINT16*)malloc(INITIAL_GLYPH_SIZE * sizeof(UINT16));
709 textProperties = (DWRITE_SHAPING_TEXT_PROPERTIES*)
710 malloc(INITIAL_GLYPH_SIZE * sizeof(DWRITE_SHAPING_TEXT_PROPERTIES));
711 glyphProperties = (DWRITE_SHAPING_GLYPH_PROPERTIES*)
712 malloc(INITIAL_GLYPH_SIZE * sizeof(DWRITE_SHAPING_GLYPH_PROPERTIES));
713
714 hr = analyzer->GetGlyphs(pchars, length,
715 fontFace, FALSE,
716 buffer->props.direction,
717 &runHead->mScript, (const wchar_t*)lang, NULL, NULL, NULL, 0,
718 maxGlyphs, clusters, textProperties,
719 glyphs, glyphProperties, &actualGlyphs);
720 }
721 if (FAILED(hr)) {
722 //NS_WARNING("Analyzer failed to get glyphs.");
723 return false;
724 }
725
726 FLOAT advances[400];
727 DWRITE_GLYPH_OFFSET offsets[400];
728
729
730 /* The -2 in the following is to compensate for possible
731 * alignment needed after the WORD array. sizeof(WORD) == 2. */
732 unsigned int glyphs_size = (scratch_size * sizeof (int)-2)
733 / (sizeof (WORD) +
734 4 + // sizeof (SCRIPT_GLYPHPROP) +
735 sizeof (int) +
736 8 + // sizeof (GOFFSET) +
737 sizeof (uint32_t));
738 ALLOCATE_ARRAY(uint32_t, vis_clusters, glyphs_size);
739
740#undef ALLOCATE_ARRAY
741
Ebrahim Byagowi1c00a462016-03-30 20:15:09 +0000742 int font_size = font->face->get_upem();
743 if (font_size < 0)
744 font_size = -font_size;
745 int x_mult = (double)font->x_scale / font_size;
746
Ebrahim Byagowif35b3e92015-09-11 09:48:12 +0430747 hr = analyzer->GetGlyphPlacements(pchars,
748 clusters,
749 textProperties,
750 length,
751 glyphs,
752 glyphProperties,
753 actualGlyphs,
754 fontFace,
Ebrahim Byagowi1c00a462016-03-30 20:15:09 +0000755 font_size * x_mult,
Ebrahim Byagowif35b3e92015-09-11 09:48:12 +0430756 FALSE,
757 FALSE,
758 &runHead->mScript,
759 NULL,
760 NULL,
761 NULL,
762 0,
763 advances,
764 offsets);
765
766 if (FAILED(hr)) {
767 //NS_WARNING("Analyzer failed to get glyph placements.");
768 return false;
769 }
770
771 unsigned int glyphs_len = actualGlyphs;
772
773 /* Ok, we've got everything we need, now compose output buffer,
774 * very, *very*, carefully! */
775
776 /* Calculate visual-clusters. That's what we ship. */
777 for (unsigned int i = 0; i < glyphs_len; i++)
778 vis_clusters[i] = -1;
779 for (unsigned int i = 0; i < buffer->len; i++) {
780 uint32_t *p = &vis_clusters[log_clusters[buffer->info[i].utf16_index()]];
781 //*p = MIN (*p, buffer->info[i].cluster);
782 }
783 for (unsigned int i = 1; i < glyphs_len; i++)
784 if (vis_clusters[i] == -1)
785 vis_clusters[i] = vis_clusters[i - 1];
786
787#undef utf16_index
788
789 //if (unlikely (!buffer->ensure (glyphs_len)))
790 // FAIL ("Buffer in error");
791
792#undef FAIL
793
794 /* Set glyph infos */
795 buffer->len = 0;
796 for (unsigned int i = 0; i < glyphs_len; i++)
797 {
798 hb_glyph_info_t *info = &buffer->info[buffer->len++];
799
800 info->codepoint = glyphs[i];
801 info->cluster = vis_clusters[i];
802
803 /* The rest is crap. Let's store position info there for now. */
804 info->mask = advances[i];
805 info->var1.u32 = offsets[i].ascenderOffset;
806 info->var2.u32 = -offsets[i].advanceOffset;
807 }
808
809 free(clusters);
810 free(glyphs);
811 free(textProperties);
812 free(glyphProperties);
813
814 /* Set glyph positions */
815 buffer->clear_positions ();
816 for (unsigned int i = 0; i < glyphs_len; i++)
817 {
818 hb_glyph_info_t *info = &buffer->info[i];
819 hb_glyph_position_t *pos = &buffer->pos[i];
820
821 /* TODO vertical */
822 pos->x_advance = info->mask;
823 pos->x_offset = backward ? -info->var1.u32 : info->var1.u32;
824 pos->y_offset = info->var2.u32;
825 }
826
827 if (backward)
828 hb_buffer_reverse (buffer);
829
830 /* Wow, done! */
831 return true;
Khaled Hosnyd7bf9d02015-12-29 02:23:24 +0400832}