static inline void addGlyphToBuffer(GlyphBuffer* glyphBuffer, float advance,
    hb_direction_t direction, const SimpleFontData* fontData,
    const HarfBuzzRunGlyphData& glyphData)
{
    FloatPoint startOffset = HB_DIRECTION_IS_HORIZONTAL(direction)
        ? FloatPoint(advance, 0)
        : FloatPoint(0, advance);
    glyphBuffer->add(glyphData.glyph, fontData, startOffset + glyphData.offset);
}
// TODO crbug.com/542701: This should be a method on ShapeResult.
void HarfBuzzShaper::insertRunIntoShapeResult(ShapeResult* result,
    PassOwnPtr<ShapeResult::RunInfo> runToInsert, unsigned startGlyph, unsigned numGlyphs,
    hb_buffer_t* harfBuzzBuffer)
{
    ASSERT(numGlyphs > 0);
    OwnPtr<ShapeResult::RunInfo> run(std::move(runToInsert));
    ASSERT(numGlyphs == run->m_glyphData.size());

    const SimpleFontData* currentFontData = run->m_fontData.get();
    const hb_glyph_info_t* glyphInfos = hb_buffer_get_glyph_infos(harfBuzzBuffer, 0);
    const hb_glyph_position_t* glyphPositions = hb_buffer_get_glyph_positions(harfBuzzBuffer, 0);
    const unsigned startCluster = HB_DIRECTION_IS_FORWARD(hb_buffer_get_direction(harfBuzzBuffer))
        ? glyphInfos[startGlyph].cluster : glyphInfos[startGlyph + numGlyphs - 1].cluster;

    float totalAdvance = 0.0f;
    FloatPoint glyphOrigin;
    bool hasVerticalOffsets = !HB_DIRECTION_IS_HORIZONTAL(run->m_direction);

    // HarfBuzz returns result in visual order, no need to flip for RTL.
    for (unsigned i = 0; i < numGlyphs; ++i) {
        uint16_t glyph = glyphInfos[startGlyph + i].codepoint;
        float offsetX = harfBuzzPositionToFloat(glyphPositions[startGlyph + i].x_offset);
        float offsetY = -harfBuzzPositionToFloat(glyphPositions[startGlyph + i].y_offset);

        // One out of x_advance and y_advance is zero, depending on
        // whether the buffer direction is horizontal or vertical.
        float advance = harfBuzzPositionToFloat(glyphPositions[startGlyph + i].x_advance - glyphPositions[startGlyph + i].y_advance);
        RELEASE_ASSERT(m_normalizedBufferLength > glyphInfos[startGlyph + i].cluster);

        // The characterIndex of one ShapeResult run is normalized to the run's
        // startIndex and length.  TODO crbug.com/542703: Consider changing that
        // and instead pass the whole run to hb_buffer_t each time.
        run->m_glyphData[i].characterIndex = glyphInfos[startGlyph + i].cluster - startCluster;

        run->setGlyphAndPositions(i, glyph, advance, offsetX, offsetY);
        totalAdvance += advance;
        hasVerticalOffsets |= (offsetY != 0);

        FloatRect glyphBounds = currentFontData->boundsForGlyph(glyph);
        glyphBounds.move(glyphOrigin.x(), glyphOrigin.y());
        result->m_glyphBoundingBox.unite(glyphBounds);
        glyphOrigin += FloatSize(advance + offsetX, offsetY);
    }
    run->m_width = std::max(0.0f, totalAdvance);
    result->m_width += run->m_width;
    result->m_numGlyphs += numGlyphs;
    ASSERT(result->m_numGlyphs >= numGlyphs); // no overflow
    result->m_hasVerticalOffsets |= hasVerticalOffsets;

    // The runs are stored in result->m_runs in visual order. For LTR, we place
    // the run to be inserted before the next run with a bigger character
    // start index. For RTL, we place the run before the next run with a lower
    // character index. Otherwise, for both directions, at the end.
    if (HB_DIRECTION_IS_FORWARD(run->m_direction)) {
        for (size_t pos = 0; pos < result->m_runs.size(); ++pos) {
            if (result->m_runs.at(pos)->m_startIndex > run->m_startIndex) {
                result->m_runs.insert(pos, run.release());
                break;
            }
        }
    } else {
        for (size_t pos = 0; pos < result->m_runs.size(); ++pos) {
            if (result->m_runs.at(pos)->m_startIndex < run->m_startIndex) {
                result->m_runs.insert(pos, run.release());
                break;
            }
        }
    }
    // If we didn't find an existing slot to place it, append.
    if (run) {
        result->m_runs.append(run.release());
    }
}
int main () {
    int ptSize = 50*64;
    int device_hdpi = 72;
    int device_vdpi = 72;

    /* Init freetype */
    FT_Library ft_library;
    assert(!FT_Init_FreeType(&ft_library));

    /* Load our fonts */
    FT_Face ft_face[NUM_EXAMPLES];
    assert(!FT_New_Face(ft_library, "fonts/DejaVuSerif.ttf", 0, &ft_face[ENGLISH]));
    assert(!FT_Set_Char_Size(ft_face[ENGLISH], 0, ptSize, device_hdpi, device_vdpi ));
    ftfdump(ft_face[ENGLISH]); // wonderful world of encodings ...
    force_ucs2_charmap(ft_face[ENGLISH]); // which we ignore.

    assert(!FT_New_Face(ft_library, "fonts/amiri-0.104/amiri-regular.ttf", 0, &ft_face[ARABIC]));
    assert(!FT_Set_Char_Size(ft_face[ARABIC], 0, ptSize, device_hdpi, device_vdpi ));
    ftfdump(ft_face[ARABIC]);
    force_ucs2_charmap(ft_face[ARABIC]);

    assert(!FT_New_Face(ft_library, "fonts/fireflysung-1.3.0/fireflysung.ttf", 0, &ft_face[CHINESE]));
    assert(!FT_Set_Char_Size(ft_face[CHINESE], 0, ptSize, device_hdpi, device_vdpi ));
    ftfdump(ft_face[CHINESE]);
    force_ucs2_charmap(ft_face[CHINESE]);

    /* Get our harfbuzz font structs */
    hb_font_t *hb_ft_font[NUM_EXAMPLES];
    hb_ft_font[ENGLISH] = hb_ft_font_create(ft_face[ENGLISH], NULL);
    hb_ft_font[ARABIC]  = hb_ft_font_create(ft_face[ARABIC] , NULL);
    hb_ft_font[CHINESE] = hb_ft_font_create(ft_face[CHINESE], NULL);

    /** Setup our SDL window **/
    int width      = 800;
    int height     = 600;
    int videoFlags = SDL_SWSURFACE | SDL_RESIZABLE | SDL_DOUBLEBUF;
    int bpp        = 32;

    /* Initialize our SDL window */
    if(SDL_Init(SDL_INIT_VIDEO) < 0)   {
        fprintf(stderr, "Failed to initialize SDL");
        return -1;
    }

    SDL_WM_SetCaption("\"Simple\" SDL+FreeType+HarfBuzz Example", "\"Simple\" SDL+FreeType+HarfBuzz Example");

    SDL_Surface *screen;
    screen = SDL_SetVideoMode(width, height, bpp, videoFlags);

    /* Enable key repeat, just makes it so we don't have to worry about fancy
     * scanboard keyboard input and such */
    SDL_EnableKeyRepeat(300, 130);
    SDL_EnableUNICODE(1);

    /* Create an SDL image surface we can draw to */
    SDL_Surface *sdl_surface = SDL_CreateRGBSurface (0, width, height, 32, 0,0,0,0);

    /* Create a buffer for harfbuzz to use */
    hb_buffer_t *buf = hb_buffer_create();

    /* Our main event/draw loop */
    int done = 0;
    int resized = 1;
    while (!done) {
        /* Clear our surface */
        SDL_FillRect( sdl_surface, NULL, 0 );
        SDL_LockSurface(sdl_surface);

        for (int i=0; i < NUM_EXAMPLES; ++i) {
            hb_buffer_set_direction(buf, text_directions[i]); /* or LTR */
            hb_buffer_set_script(buf, scripts[i]); /* see hb-unicode.h */
            hb_buffer_set_language(buf, hb_language_from_string(languages[i], strlen(languages[i])));

            /* Layout the text */
            hb_buffer_add_utf8(buf, texts[i], strlen(texts[i]), 0, strlen(texts[i]));
            hb_shape(hb_ft_font[i], buf, NULL, 0);

            unsigned int         glyph_count;
            hb_glyph_info_t     *glyph_info   = hb_buffer_get_glyph_infos(buf, &glyph_count);
            hb_glyph_position_t *glyph_pos    = hb_buffer_get_glyph_positions(buf, &glyph_count);

            /* set up rendering via spanners */
            spanner_baton_t stuffbaton;

            FT_Raster_Params ftr_params;
            ftr_params.target = 0;
            ftr_params.flags = FT_RASTER_FLAG_DIRECT | FT_RASTER_FLAG_AA;
            ftr_params.user = &stuffbaton;
            ftr_params.black_spans = 0;
            ftr_params.bit_set = 0;
            ftr_params.bit_test = 0;

            /* Calculate string bounding box in pixels */
            ftr_params.gray_spans = spanner_sizer;

            /* See http://www.freetype.org/freetype2/docs/glyphs/glyphs-3.html */

            int max_x = INT_MIN; // largest coordinate a pixel has been set at, or the pen was advanced to.
            int min_x = INT_MAX; // smallest coordinate a pixel has been set at, or the pen was advanced to.
            int max_y = INT_MIN; // this is max topside bearing along the string.
            int min_y = INT_MAX; // this is max value of (height - topbearing) along the string.
            /*  Naturally, the above comments swap their meaning between horizontal and vertical scripts,
                since the pen changes the axis it is advanced along.
                However, their differences still make up the bounding box for the string.
                Also note that all this is in FT coordinate system where y axis points upwards.
             */

            int sizer_x = 0;
            int sizer_y = 0; /* in FT coordinate system. */

            FT_Error fterr;
            for (unsigned j = 0; j < glyph_count; ++j) {
                if ((fterr = FT_Load_Glyph(ft_face[i], glyph_info[j].codepoint, 0))) {
                    printf("load %08x failed fterr=%d.\n",  glyph_info[j].codepoint, fterr);
                } else {
                    if (ft_face[i]->glyph->format != FT_GLYPH_FORMAT_OUTLINE) {
                        printf("glyph->format = %4s\n", (char *)&ft_face[i]->glyph->format);
                    } else {
                        int gx = sizer_x + (glyph_pos[j].x_offset/64);
                        int gy = sizer_y + (glyph_pos[j].y_offset/64); // note how the sign differs from the rendering pass

                        stuffbaton.min_span_x = INT_MAX;
                        stuffbaton.max_span_x = INT_MIN;
                        stuffbaton.min_y = INT_MAX;
                        stuffbaton.max_y = INT_MIN;

                        if ((fterr = FT_Outline_Render(ft_library, &ft_face[i]->glyph->outline, &ftr_params)))
                            printf("FT_Outline_Render() failed err=%d\n", fterr);

                        if (stuffbaton.min_span_x != INT_MAX) {
                        /* Update values if the spanner was actually called. */
                            if (min_x > stuffbaton.min_span_x + gx)
                                min_x = stuffbaton.min_span_x + gx;

                            if (max_x < stuffbaton.max_span_x + gx)
                                max_x = stuffbaton.max_span_x + gx;

                            if (min_y > stuffbaton.min_y + gy)
                                min_y = stuffbaton.min_y + gy;

                            if (max_y < stuffbaton.max_y + gy)
                                max_y = stuffbaton.max_y + gy;
                        } else {
                        /* The spanner wasn't called at all - an empty glyph, like space. */
                            if (min_x > gx) min_x = gx;
                            if (max_x < gx) max_x = gx;
                            if (min_y > gy) min_y = gy;
                            if (max_y < gy) max_y = gy;
                        }
                    }
                }

                sizer_x += glyph_pos[j].x_advance/64;
                sizer_y += glyph_pos[j].y_advance/64; // note how the sign differs from the rendering pass
            }
            /* Still have to take into account last glyph's advance. Or not? */
            if (min_x > sizer_x) min_x = sizer_x;
            if (max_x < sizer_x) max_x = sizer_x;
            if (min_y > sizer_y) min_y = sizer_y;
            if (max_y < sizer_y) max_y = sizer_y;

            /* The bounding box */
            int bbox_w = max_x - min_x;
            int bbox_h = max_y - min_y;

            /* Two offsets below position the bounding box with respect to the 'origin',
                which is sort of origin of string's first glyph.

                baseline_offset - offset perpendecular to the baseline to the topmost (horizontal),
                                  or leftmost (vertical) pixel drawn.

                baseline_shift  - offset along the baseline, from the first drawn glyph's origin
                                  to the leftmost (horizontal), or topmost (vertical) pixel drawn.

                Thus those offsets allow positioning the bounding box to fit the rendered string,
                as they are in fact offsets from the point given to the renderer, to the top left
                corner of the bounding box.

                NB: baseline is defined as y==0 for horizontal and x==0 for vertical scripts.
                (0,0) here is where the first glyph's origin ended up after shaping, not taking
                into account glyph_pos[0].xy_offset (yeah, my head hurts too).
            */

            int baseline_offset;
            int baseline_shift;

            if (HB_DIRECTION_IS_HORIZONTAL(hb_buffer_get_direction(buf))) {
                baseline_offset = max_y;
                baseline_shift  = min_x;
            }
            if (HB_DIRECTION_IS_VERTICAL(hb_buffer_get_direction(buf))) {
                baseline_offset = min_x;
                baseline_shift  = max_y;
            }

            if (resized)
                printf("ex %d string min_x=%d max_x=%d min_y=%d max_y=%d bbox %dx%d boffs %d,%d\n",
                    i, min_x, max_x, min_y, max_y, bbox_w, bbox_h, baseline_offset, baseline_shift);

            /* The pen/baseline start coordinates in window coordinate system
                - with those text placement in the window is controlled.
                - note that for RTL scripts pen still goes LTR */
            int x = 0, y = 50 + i * 75;
            if (i == ENGLISH) { x = 20; }                  /* left justify */
            if (i == ARABIC)  { x = width - bbox_w - 20; } /* right justify */
            if (i == CHINESE) { x = width/2 - bbox_w/2; }  /* center, and for TTB script h_advance is half-width. */

            /* Draw baseline and the bounding box */
            /* The below is complicated since we simultaneously
               convert to the window coordinate system. */
            int left, right, top, bottom;

            if (HB_DIRECTION_IS_HORIZONTAL(hb_buffer_get_direction(buf))) {
                /* bounding box in window coordinates without offsets */
                left   = x;
                right  = x + bbox_w;
                top    = y - bbox_h;
                bottom = y;

                /* apply offsets */
                left   +=  baseline_shift;
                right  +=  baseline_shift;
                top    -=  baseline_offset - bbox_h;
                bottom -=  baseline_offset - bbox_h;

                /* draw the baseline */
                hline(sdl_surface, x, x + bbox_w, y, 0x0000ff00);
            }

            if (HB_DIRECTION_IS_VERTICAL(hb_buffer_get_direction(buf))) {
                left   = x;
                right  = x + bbox_w;
                top    = y;
                bottom = y + bbox_h;

                left   += baseline_offset;
                right  += baseline_offset;
                top    -= baseline_shift;
                bottom -= baseline_shift;

                vline(sdl_surface, y, y + bbox_h, x, 0x0000ff00);
            }
            if (resized)
                printf("ex %d origin %d,%d bbox l=%d r=%d t=%d b=%d\n",
                                        i, x, y, left, right, top, bottom);

            /* +1/-1 are for the bbox borders be the next pixel outside the bbox itself */
            hline(sdl_surface, left - 1, right + 1, top - 1, 0x00ff0000);
            hline(sdl_surface, left - 1, right + 1, bottom + 1, 0x00ff0000);
            vline(sdl_surface, top - 1, bottom + 1, left - 1, 0x00ff0000);
            vline(sdl_surface, top - 1, bottom + 1, right + 1, 0x00ff0000);

            /* set rendering spanner */
            ftr_params.gray_spans = spanner;

            /* initialize rendering part of the baton */
            stuffbaton.pixels = NULL;
            stuffbaton.first_pixel = sdl_surface->pixels;
            stuffbaton.last_pixel = (uint32_t *) (((uint8_t *) sdl_surface->pixels) + sdl_surface->pitch*sdl_surface->h);
            stuffbaton.pitch = sdl_surface->pitch;
            stuffbaton.rshift = sdl_surface->format->Rshift;
            stuffbaton.gshift = sdl_surface->format->Gshift;
            stuffbaton.bshift = sdl_surface->format->Bshift;

            /* render */
            for (unsigned j=0; j < glyph_count; ++j) {
                if ((fterr = FT_Load_Glyph(ft_face[i], glyph_info[j].codepoint, 0))) {
                    printf("load %08x failed fterr=%d.\n",  glyph_info[j].codepoint, fterr);
                } else {
                    if (ft_face[i]->glyph->format != FT_GLYPH_FORMAT_OUTLINE) {
                        printf("glyph->format = %4s\n", (char *)&ft_face[i]->glyph->format);
                    } else {
                        int gx = x + (glyph_pos[j].x_offset/64);
                        int gy = y - (glyph_pos[j].y_offset/64);

                        stuffbaton.pixels = (uint32_t *)(((uint8_t *) sdl_surface->pixels) + gy * sdl_surface->pitch) + gx;

                        if ((fterr = FT_Outline_Render(ft_library, &ft_face[i]->glyph->outline, &ftr_params)))
                            printf("FT_Outline_Render() failed err=%d\n", fterr);
                    }
                }

                x += glyph_pos[j].x_advance/64;
                y -= glyph_pos[j].y_advance/64;
            }

            /* clean up the buffer, but don't kill it just yet */
            hb_buffer_clear_contents(buf);

        }

        SDL_UnlockSurface(sdl_surface);

        /* Blit our new image to our visible screen */

        SDL_BlitSurface(sdl_surface, NULL, screen, NULL);
        SDL_Flip(screen);

        /* Handle SDL events */
        SDL_Event event;
        resized = resized ? !resized : resized;
        while(SDL_PollEvent(&event)) {
            switch (event.type) {
                case SDL_KEYDOWN:
                    if (event.key.keysym.sym == SDLK_ESCAPE) {
                        done = 1;
                    }
                    break;
                case SDL_QUIT:
                    done = 1;
                    break;
                case SDL_VIDEORESIZE:
                    resized = 1;
                    width = event.resize.w;
                    height = event.resize.h;
                    screen = SDL_SetVideoMode(event.resize.w, event.resize.h, bpp, videoFlags);
                    if (!screen) {
                        fprintf(stderr, "Could not get a surface after resize: %s\n", SDL_GetError( ));
                        exit(-1);
                    }
                    /*  Recreate an SDL image surface we can draw to. */
                    SDL_FreeSurface(sdl_surface);
                    sdl_surface = SDL_CreateRGBSurface(0, width, height, 32, 0, 0 ,0, 0);
                    break;
            }
        }

        SDL_Delay(150);
    }

    /* Cleanup */
    hb_buffer_destroy(buf);
    for (int i=0; i < NUM_EXAMPLES; ++i)
        hb_font_destroy(hb_ft_font[i]);

    FT_Done_FreeType(ft_library);

    SDL_FreeSurface(sdl_surface);
    SDL_Quit();

    return 0;
}
示例#4
0
void ShapeResult::insertRun(std::unique_ptr<ShapeResult::RunInfo> runToInsert,
                            unsigned startGlyph,
                            unsigned numGlyphs,
                            hb_buffer_t* harfBuzzBuffer) {
  ASSERT(numGlyphs > 0);
  std::unique_ptr<ShapeResult::RunInfo> run(std::move(runToInsert));
  ASSERT(numGlyphs == run->m_glyphData.size());

  const SimpleFontData* currentFontData = run->m_fontData.get();
  const hb_glyph_info_t* glyphInfos =
      hb_buffer_get_glyph_infos(harfBuzzBuffer, 0);
  const hb_glyph_position_t* glyphPositions =
      hb_buffer_get_glyph_positions(harfBuzzBuffer, 0);
  const unsigned startCluster =
      HB_DIRECTION_IS_FORWARD(hb_buffer_get_direction(harfBuzzBuffer))
          ? glyphInfos[startGlyph].cluster
          : glyphInfos[startGlyph + numGlyphs - 1].cluster;

  float totalAdvance = 0.0f;
  FloatPoint glyphOrigin;
  bool hasVerticalOffsets = !HB_DIRECTION_IS_HORIZONTAL(run->m_direction);

  // HarfBuzz returns result in visual order, no need to flip for RTL.
  for (unsigned i = 0; i < numGlyphs; ++i) {
    uint16_t glyph = glyphInfos[startGlyph + i].codepoint;
    hb_glyph_position_t pos = glyphPositions[startGlyph + i];

    float offsetX = harfBuzzPositionToFloat(pos.x_offset);
    float offsetY = -harfBuzzPositionToFloat(pos.y_offset);

    // One out of x_advance and y_advance is zero, depending on
    // whether the buffer direction is horizontal or vertical.
    // Convert to float and negate to avoid integer-overflow for ULONG_MAX.
    float advance;
    if (LIKELY(pos.x_advance))
      advance = harfBuzzPositionToFloat(pos.x_advance);
    else
      advance = -harfBuzzPositionToFloat(pos.y_advance);

    run->m_glyphData[i].characterIndex =
        glyphInfos[startGlyph + i].cluster - startCluster;

    run->setGlyphAndPositions(i, glyph, advance, offsetX, offsetY);
    totalAdvance += advance;
    hasVerticalOffsets |= (offsetY != 0);

    FloatRect glyphBounds = currentFontData->boundsForGlyph(glyph);
    glyphBounds.move(glyphOrigin.x(), glyphOrigin.y());
    m_glyphBoundingBox.unite(glyphBounds);
    glyphOrigin += FloatSize(advance + offsetX, offsetY);
  }

  run->m_width = std::max(0.0f, totalAdvance);
  m_width += run->m_width;
  m_numGlyphs += numGlyphs;
  ASSERT(m_numGlyphs >= numGlyphs);
  m_hasVerticalOffsets |= hasVerticalOffsets;

  // The runs are stored in result->m_runs in visual order. For LTR, we place
  // the run to be inserted before the next run with a bigger character
  // start index. For RTL, we place the run before the next run with a lower
  // character index. Otherwise, for both directions, at the end.
  if (HB_DIRECTION_IS_FORWARD(run->m_direction)) {
    for (size_t pos = 0; pos < m_runs.size(); ++pos) {
      if (m_runs.at(pos)->m_startIndex > run->m_startIndex) {
        m_runs.insert(pos, std::move(run));
        break;
      }
    }
  } else {
    for (size_t pos = 0; pos < m_runs.size(); ++pos) {
      if (m_runs.at(pos)->m_startIndex < run->m_startIndex) {
        m_runs.insert(pos, std::move(run));
        break;
      }
    }
  }
  // If we didn't find an existing slot to place it, append.
  if (run)
    m_runs.append(std::move(run));
}