Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 60 additions & 14 deletions src/CanvasRenderingContext2d.cc
Original file line number Diff line number Diff line change
Expand Up @@ -2386,32 +2386,63 @@ get_text_scale(TextLayout& layout, double maxWidth) {
}
}

// HarfBuzz clusters index UTF-16 code units. Cairo counts UTF-8 bytes.
static void
showTextGlyphs(cairo_t* cr, Napi::Env env, const char16_t* text, const GlyphRun& run, const cairo_glyph_t* glyphs) {
const size_t count = run.glyphs.size();
const std::string utf8 = Napi::String::New(env, text + run.start, run.end - run.start).Utf8Value();
if (env.IsExceptionPending()) return;

std::vector<cairo_text_cluster_t> clusters;
size_t byte = 0, codeUnit = run.start;
for (size_t i = 0; i < count;) {
const size_t first = i++;
while (i < count && run.glyphs[i].cluster == run.glyphs[first].cluster) ++i;
const size_t end = i == count ? run.end : run.glyphs[i].cluster;
const size_t firstByte = byte;
while (codeUnit < end && byte < utf8.size()) {
// Four-byte UTF-8 sequences correspond to surrogate pairs in UTF-16.
codeUnit += static_cast<unsigned char>(utf8[byte]) >= 0xf0 ? 2 : 1;
++byte;
while (byte < utf8.size() && (utf8[byte] & 0xc0) == 0x80) ++byte;
}
clusters.push_back({static_cast<int>(byte - firstByte), static_cast<int>(i - first)});
}

cairo_show_text_glyphs(cr, utf8.data(), utf8.size(), glyphs, count,
clusters.data(), clusters.size(), cairo_text_cluster_flags_t(0));
}

inline void
Context2d::paintGlyphs(
cairo_glyph_t* glyphs,
size_t numGlyphs,
bool stroke
bool stroke,
const GlyphRun* textRun
) {
if (stroke) {
savePath();
cairo_glyph_path(context(), glyphs, numGlyphs);
this->stroke();
restorePath();
} else if (hasShadow()) {
return;
}

const bool shadowed = hasShadow();
if (shadowed) {
savePath();
cairo_glyph_path(context(), glyphs, numGlyphs);
bool needsRestore = setFillSource();
shadow(cairo_fill);
// TODO: use cairo_show_text_glyphs!
cairo_show_glyphs(context(), glyphs, numGlyphs);
if (needsRestore) cairo_restore(context());
restorePath();
}

bool needsRestore = setFillSource();
if (shadowed) shadow(cairo_fill);
if (textRun) {
showTextGlyphs(context(), env, textBuffer, *textRun, glyphs);
} else {
bool needsRestore = setFillSource();
// TODO: use cairo_show_text_glyphs!
cairo_show_glyphs(context(), glyphs, numGlyphs);
if (needsRestore) cairo_restore(context());
}
if (needsRestore) cairo_restore(context());
if (shadowed) restorePath();
}

void
Expand All @@ -2434,7 +2465,9 @@ Context2d::paintText(const Napi::CallbackInfo& info, bool stroke) {
InstanceData* data = env.GetInstanceData<InstanceData>();

constexpr size_t CR_GLYPH_BUF_SIZE = 1024;
cairo_glyph_t glyphs[CR_GLYPH_BUF_SIZE];
cairo_glyph_t glyphBuffer[CR_GLYPH_BUF_SIZE];
std::vector<cairo_glyph_t> longRunBuffer;
const bool embedText = !stroke && cairo_surface_has_show_text_glyphs(cairo_get_target(context()));

TextLayout layout = layoutText(textBuffer, textLength, state, data);
double x = args[0] - layout.anchorX;
Expand Down Expand Up @@ -2462,11 +2495,24 @@ Context2d::paintText(const Napi::CallbackInfo& info, bool stroke) {
cairo_get_font_matrix(context(), &m);
if (m.xx != fontSize) cairo_set_font_size(context(), fontSize);

// Cairo paints color glyphs as images. Keep the existing glyph order for
// backwards runs so PDF readers can select right-to-left text correctly.
const bool useClusters = embedText && !(run.level & 1) && !FT_HAS_COLOR(run.face->ftface.get());
const GlyphRun* textRun = useClusters ? &run : nullptr;
// The normal buffer boundary can fall inside a multi-glyph cluster.
cairo_glyph_t* glyphs = glyphBuffer;
size_t capacity = CR_GLYPH_BUF_SIZE;
if (useClusters && run.glyphs.size() > capacity) {
longRunBuffer.resize(run.glyphs.size());
glyphs = longRunBuffer.data();
capacity = longRunBuffer.size();
}

size_t hbGlyphIndex = 0;
while (hbGlyphIndex < run.glyphs.size()) {
size_t crGlyphIndex = 0;

while (crGlyphIndex < CR_GLYPH_BUF_SIZE && hbGlyphIndex < run.glyphs.size()) {
while (crGlyphIndex < capacity && hbGlyphIndex < run.glyphs.size()) {
glyphs[crGlyphIndex].index = run.glyphs[hbGlyphIndex].id;
glyphs[crGlyphIndex].x = x + run.glyphs[hbGlyphIndex].x_offset * toPx;
glyphs[crGlyphIndex].y = y + run.glyphs[hbGlyphIndex].y_offset * toPx;
Expand All @@ -2477,7 +2523,7 @@ Context2d::paintText(const Napi::CallbackInfo& info, bool stroke) {
crGlyphIndex += 1;
}

paintGlyphs(glyphs, crGlyphIndex, stroke);
paintGlyphs(glyphs, crGlyphIndex, stroke, textRun);
}

cairo_set_font_face(context(), nullptr);
Expand Down
4 changes: 3 additions & 1 deletion src/CanvasRenderingContext2d.h
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ typedef struct {
float height;
} float_rectangle;

struct GlyphRun;

class Context2d : public Napi::ObjectWrap<Context2d> {
public:
std::stack<canvas_state_t> states;
Expand Down Expand Up @@ -199,7 +201,7 @@ class Context2d : public Napi::ObjectWrap<Context2d> {
Napi::Value get_current_transform();
void _setFillColor(Napi::Value arg);
void _setStrokeColor(Napi::Value arg);
inline void paintGlyphs(cairo_glyph_t* glyphs, size_t numGlyphs, bool stroke);
inline void paintGlyphs(cairo_glyph_t* glyphs, size_t numGlyphs, bool stroke, const GlyphRun* textRun);
void paintText(const Napi::CallbackInfo&, bool);
text_align_t resolveTextAlignment();
Canvas *_canvas;
Expand Down
55 changes: 42 additions & 13 deletions test/canvas.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,23 @@ function assertApprox(actual, expected, tol) {
"Expected " + actual + " to be " + expected + " +/- " + tol);
}

function pdfStreamContents (pdf) {
const zlib = require('zlib')
const pdfStr = pdf.toString('latin1')
const streamRegex = /stream\r?\n([\s\S]*?)\r?\nendstream/g
let match
let allContent = ''
while ((match = streamRegex.exec(pdfStr)) !== null) {
try {
const compressed = Buffer.from(match[1], 'latin1')
allContent += zlib.inflateSync(compressed).toString()
} catch (e) {
// Some streams may not be zlib-compressed
}
}
return allContent
}

describe('Canvas', function () {
// Run with --expose-gc and uncomment this line to help find memory problems:
// afterEach(gc);
Expand Down Expand Up @@ -2339,8 +2356,31 @@ describe('Canvas', function () {
})
})

describe('PDF text clusters', function () {
const arimo = new FontFace('Arimo', path.join(__dirname, 'fixtures/Arimo-Regular.ttf'))

before(function () { fonts.add(arimo) })
after(function () { fonts.delete(arimo) })

function drawText (text) {
const canvas = createCanvas(14000, 40, 'pdf')
const ctx = canvas.getContext('2d')
ctx.font = '12px Arimo'
ctx.fillText(text, 2, 20)
return pdfStreamContents(canvas.toBuffer())
}

it('preserves the source letters of a composed glyph', function () {
assert.match(drawText('Cafe\u0301'), /<(?:feff)?00650301>/i)
})

it('preserves a cluster spanning the glyph buffer boundary', function () {
const text = 'a'.repeat(1023) + 'e\u0301\u0327' + 'b'
assert.match(drawText(text), /<(?:feff)?006503010327>/i)
})
})

it('PDF does not lose page content when setting width/height after addPage (#2538)', function () {
const zlib = require('zlib')
const canvas = createCanvas(100, 100, 'pdf')
const ctx = canvas.getContext('2d')

Expand All @@ -2365,18 +2405,7 @@ describe('Canvas', function () {
const pdf = canvas.toBuffer()

// Parse PDF streams to verify page 1 content is preserved
const pdfStr = pdf.toString('latin1')
const streamRegex = /stream\r?\n([\s\S]*?)\r?\nendstream/g
let match
let allContent = ''
while ((match = streamRegex.exec(pdfStr)) !== null) {
try {
const compressed = Buffer.from(match[1], 'latin1')
allContent += zlib.inflateSync(compressed).toString()
} catch (e) {
// Some streams may not be zlib-compressed
}
}
const allContent = pdfStreamContents(pdf)

// 85/255 ≈ 0.333333 - page 1 fill color
// 170/255 ≈ 0.666667 - page 2 fill color, erased
Expand Down