From: miklosh Date: Sat, 21 Jul 2007 17:59:49 +0000 (+0000) Subject: Further development of the PDF import module: continued pruning of PdfParser.cpp... X-Git-Url: https://git.tokkee.org/?a=commitdiff_plain;h=3711b3e25395437ee0a09dbbb2a76d999c4ef322;p=inkscape.git Further development of the PDF import module: continued pruning of PdfParser.cpp, added basic text and image support and did some coding style adjustments. --- diff --git a/src/extension/internal/pdfinput/pdf-input.cpp b/src/extension/internal/pdfinput/pdf-input.cpp index b9e616025..db401731f 100644 --- a/src/extension/internal/pdfinput/pdf-input.cpp +++ b/src/extension/internal/pdfinput/pdf-input.cpp @@ -44,7 +44,6 @@ PdfInput::open(::Inkscape::Extension::Input * mod, const gchar * uri) { // Initialize the globalParams variable for poppler if (!globalParams) { globalParams = new GlobalParams(); - g_message("Created globalParams"); } GooString *filename_goo = new GooString(uri); PDFDoc *pdf_doc = new PDFDoc(filename_goo, NULL, NULL, NULL); // TODO: Could ask for password @@ -65,23 +64,13 @@ PdfInput::open(::Inkscape::Extension::Input * mod, const gchar * uri) { Catalog *catalog = pdf_doc->getCatalog(); Page *page = catalog->getPage(page_num); - double width, height; - int rotate = page->getRotate(); - if (rotate == 90 || rotate == 270) { - width = page->getCropHeight(); - height = page->getCropWidth(); - } else { - width = page->getCropWidth(); - height = page->getCropHeight(); - } - SPDocument *doc = sp_document_new(NULL, TRUE, TRUE); bool saved = sp_document_get_undo_sensitive(doc); sp_document_set_undo_sensitive(doc, false); // No need to undo in this temporary document // Create builder and parser SvgBuilder *builder = new SvgBuilder(doc); - PdfParser *pdf_parser = new PdfParser(pdf_doc->getXRef(), builder, page_num-1, + PdfParser *pdf_parser = new PdfParser(pdf_doc->getXRef(), builder, page_num-1, page->getRotate(), page->getResourceDict(), page->getCropBox()); // Parse the document structure @@ -97,6 +86,7 @@ PdfInput::open(::Inkscape::Extension::Input * mod, const gchar * uri) { obj.free(); delete pdf_parser; delete builder; + delete pdf_doc; // Restore undo sp_document_set_undo_sensitive(doc, saved); diff --git a/src/extension/internal/pdfinput/pdf-parser.cpp b/src/extension/internal/pdfinput/pdf-parser.cpp index b8804ac00..c64f5de06 100644 --- a/src/extension/internal/pdfinput/pdf-parser.cpp +++ b/src/extension/internal/pdfinput/pdf-parser.cpp @@ -93,7 +93,7 @@ extern "C" { #define patchColorDelta (dblToCol(1 / 256.0)) // Max number of operators kept in the history list. -#define maxOperatorHistoryDepth 5 +#define maxOperatorHistoryDepth 16 //------------------------------------------------------------------------ // Operator table @@ -283,9 +283,8 @@ PdfOperator PdfParser::opTab[] = { //------------------------------------------------------------------------ PdfParser::PdfParser(XRef *xrefA, Inkscape::Extension::Internal::SvgBuilder *builderA, - int pageNum, Dict *resDict, PDFRectangle *cropBox, - GBool (*abortCheckCbkA)(void *data), - void *abortCheckCbkDataA) { + int pageNum, int rotate, Dict *resDict, PDFRectangle *cropBox) { + int i; xref = xrefA; @@ -296,7 +295,7 @@ PdfParser::PdfParser(XRef *xrefA, Inkscape::Extension::Internal::SvgBuilder *bui res = new GfxResources(xref, resDict, NULL); // initialize - state = new GfxState(72.0, 72.0, cropBox, 0, gFalse); + state = new GfxState(72.0, 72.0, cropBox, rotate, gTrue); fontChanged = gFalse; clip = clipNone; ignoreUndef = 0; @@ -304,16 +303,15 @@ PdfParser::PdfParser(XRef *xrefA, Inkscape::Extension::Internal::SvgBuilder *bui builder = builderA; builder->setDocumentSize(state->getPageWidth()*PX_PER_PT, state->getPageHeight()*PX_PER_PT); - + + double *ctm = state->getCTM(); + double scaledCTM[6]; for (i = 0; i < 6; ++i) { - baseMatrix[i] = state->getCTM()[i]; + baseMatrix[i] = ctm[i]; + scaledCTM[i] = PX_PER_PT * ctm[i]; } - // scale by PX_PER_PT and flip by the y axis - builder->setTransform(PX_PER_PT, 0.0, 0.0, -PX_PER_PT, 0.0, - state->getPageHeight()*PX_PER_PT); + builder->setTransform((double*)&scaledCTM); formDepth = 0; - abortCheckCbk = abortCheckCbkA; - abortCheckCbkData = abortCheckCbkDataA; // set crop box if (cropBox) { @@ -382,7 +380,6 @@ void PdfParser::go(GBool topLevel) { int lastAbortCheck; // scan a sequence of objects - updateLevel = lastAbortCheck = 0; numArgs = 0; parser->getObj(&obj); while (!obj.isEOF()) { @@ -407,16 +404,6 @@ void PdfParser::go(GBool topLevel) { args[i].free(); numArgs = 0; - // check for an abort - if (abortCheckCbk) { - if (updateLevel - lastAbortCheck > 10) { - if ((*abortCheckCbk)(abortCheckCbkData)) { - break; - } - lastAbortCheck = updateLevel; - } - } - // got an argument - save it } else if (numArgs < maxArgs) { args[numArgs++] = obj; @@ -481,10 +468,13 @@ void PdfParser::pushOperator(const char *name) { } } -const char *PdfParser::getPreviousOperator() { +const char *PdfParser::getPreviousOperator(unsigned int look_back) { OpHistoryEntry *prev = NULL; - if (operatorHistory != NULL) { + if (operatorHistory != NULL && look_back > 0) { prev = operatorHistory->next; + while (--look_back > 0 && prev != NULL) { + prev = prev->next; + } } if (prev != NULL) { return prev->name; @@ -608,14 +598,20 @@ void PdfParser::opConcat(Object args[], int numArgs) { double a5 = args[5].getNum(); if (!strcmp(prevOp, "q")) { builder->setTransform(a0, a1, a2, a3, a4, a5); - } else if (!strcmp(prevOp, "startPage")) { - // multiply it with the current baseMatrix - double c0 = baseMatrix[0]*a0 + baseMatrix[1]*a2; - double c1 = baseMatrix[0]*a1 + baseMatrix[1]*a3; - double c2 = baseMatrix[2]*a0 + baseMatrix[3]*a2; - double c3 = baseMatrix[2]*a1 + baseMatrix[3]*a3; - double c4 = baseMatrix[4]*a0 + baseMatrix[5]*a2 + a4; - double c5 = baseMatrix[4]*a1 + baseMatrix[5]*a3 + a5; + } else if (!strcmp(prevOp, "cm")) { + // multiply it with the previous transform + double otherMatrix[6]; + if (!builder->getTransform((double*)&otherMatrix)) { // invalid transform + // construct identity matrix + otherMatrix[0] = otherMatrix[3] = 1.0; + otherMatrix[1] = otherMatrix[2] = otherMatrix[4] = otherMatrix[5] = 0.0; + } + double c0 = otherMatrix[0]*a0 + otherMatrix[1]*a2; + double c1 = otherMatrix[0]*a1 + otherMatrix[1]*a3; + double c2 = otherMatrix[2]*a0 + otherMatrix[3]*a2; + double c3 = otherMatrix[2]*a1 + otherMatrix[3]*a3; + double c4 = otherMatrix[4]*a0 + otherMatrix[5]*a2 + a4; + double c5 = otherMatrix[4]*a1 + otherMatrix[5]*a3 + a5; builder->setTransform(c0, c1, c2, c3, c4, c5); } else { builder->pushGroup(); @@ -643,6 +639,7 @@ void PdfParser::opSetDash(Object args[], int numArgs) { } } state->setLineDash(dash, length, args[1].getNum()); + builder->updateStyle(state); } void PdfParser::opSetFlat(Object args[], int numArgs) { @@ -651,18 +648,22 @@ void PdfParser::opSetFlat(Object args[], int numArgs) { void PdfParser::opSetLineJoin(Object args[], int numArgs) { state->setLineJoin(args[0].getInt()); + builder->updateStyle(state); } void PdfParser::opSetLineCap(Object args[], int numArgs) { state->setLineCap(args[0].getInt()); + builder->updateStyle(state); } void PdfParser::opSetMiterLimit(Object args[], int numArgs) { state->setMiterLimit(args[0].getNum()); + builder->updateStyle(state); } void PdfParser::opSetLineWidth(Object args[], int numArgs) { state->setLineWidth(args[0].getNum()); + builder->updateStyle(state); } void PdfParser::opSetExtGState(Object args[], int numArgs) { @@ -926,6 +927,7 @@ void PdfParser::opSetFillGray(Object args[], int numArgs) { state->setFillColorSpace(new GfxDeviceGrayColorSpace()); color.c[0] = dblToCol(args[0].getNum()); state->setFillColor(&color); + builder->updateStyle(state); } void PdfParser::opSetStrokeGray(Object args[], int numArgs) { @@ -935,6 +937,7 @@ void PdfParser::opSetStrokeGray(Object args[], int numArgs) { state->setStrokeColorSpace(new GfxDeviceGrayColorSpace()); color.c[0] = dblToCol(args[0].getNum()); state->setStrokeColor(&color); + builder->updateStyle(state); } void PdfParser::opSetFillCMYKColor(Object args[], int numArgs) { @@ -947,6 +950,7 @@ void PdfParser::opSetFillCMYKColor(Object args[], int numArgs) { color.c[i] = dblToCol(args[i].getNum()); } state->setFillColor(&color); + builder->updateStyle(state); } void PdfParser::opSetStrokeCMYKColor(Object args[], int numArgs) { @@ -959,6 +963,7 @@ void PdfParser::opSetStrokeCMYKColor(Object args[], int numArgs) { color.c[i] = dblToCol(args[i].getNum()); } state->setStrokeColor(&color); + builder->updateStyle(state); } void PdfParser::opSetFillRGBColor(Object args[], int numArgs) { @@ -971,6 +976,7 @@ void PdfParser::opSetFillRGBColor(Object args[], int numArgs) { color.c[i] = dblToCol(args[i].getNum()); } state->setFillColor(&color); + builder->updateStyle(state); } void PdfParser::opSetStrokeRGBColor(Object args[], int numArgs) { @@ -983,6 +989,7 @@ void PdfParser::opSetStrokeRGBColor(Object args[], int numArgs) { color.c[i] = dblToCol(args[i].getNum()); } state->setStrokeColor(&color); + builder->updateStyle(state); } void PdfParser::opSetFillColorSpace(Object args[], int numArgs) { @@ -1002,6 +1009,7 @@ void PdfParser::opSetFillColorSpace(Object args[], int numArgs) { state->setFillColorSpace(colorSpace); colorSpace->getDefaultColor(&color); state->setFillColor(&color); + builder->updateStyle(state); } else { error(getPos(), "Bad color space (fill)"); } @@ -1024,6 +1032,7 @@ void PdfParser::opSetStrokeColorSpace(Object args[], int numArgs) { state->setStrokeColorSpace(colorSpace); colorSpace->getDefaultColor(&color); state->setStrokeColor(&color); + builder->updateStyle(state); } else { error(getPos(), "Bad color space (stroke)"); } @@ -1042,6 +1051,7 @@ void PdfParser::opSetFillColor(Object args[], int numArgs) { color.c[i] = dblToCol(args[i].getNum()); } state->setFillColor(&color); + builder->updateStyle(state); } void PdfParser::opSetStrokeColor(Object args[], int numArgs) { @@ -1057,6 +1067,7 @@ void PdfParser::opSetStrokeColor(Object args[], int numArgs) { color.c[i] = dblToCol(args[i].getNum()); } state->setStrokeColor(&color); + builder->updateStyle(state); } void PdfParser::opSetFillColorN(Object args[], int numArgs) { @@ -1078,6 +1089,7 @@ void PdfParser::opSetFillColorN(Object args[], int numArgs) { } } state->setFillColor(&color); + builder->updateStyle(state); } if (args[numArgs-1].isName() && (pattern = res->lookupPattern(args[numArgs-1].getName()))) { @@ -1096,6 +1108,7 @@ void PdfParser::opSetFillColorN(Object args[], int numArgs) { } } state->setFillColor(&color); + builder->updateStyle(state); } } @@ -1119,6 +1132,7 @@ void PdfParser::opSetStrokeColorN(Object args[], int numArgs) { } } state->setStrokeColor(&color); + builder->updateStyle(state); } if (args[numArgs-1].isName() && (pattern = res->lookupPattern(args[numArgs-1].getName()))) { @@ -1137,6 +1151,7 @@ void PdfParser::opSetStrokeColorN(Object args[], int numArgs) { } } state->setStrokeColor(&color); + builder->updateStyle(state); } } @@ -1922,10 +1937,11 @@ void PdfParser::opBeginText(Object args[], int numArgs) { state->setTextMat(1, 0, 0, 1, 0, 0); state->textMoveTo(0, 0); fontChanged = gTrue; + builder->beginTextObject(state); } void PdfParser::opEndText(Object args[], int numArgs) { - //NEEDED out->endTextObject(state); + builder->endTextObject(state); } //------------------------------------------------------------------------ @@ -1961,6 +1977,7 @@ void PdfParser::opSetTextLeading(Object args[], int numArgs) { void PdfParser::opSetTextRender(Object args[], int numArgs) { state->setRender(args[0].getInt()); + builder->updateStyle(state); } void PdfParser::opSetTextRise(Object args[], int numArgs) { @@ -1969,12 +1986,10 @@ void PdfParser::opSetTextRise(Object args[], int numArgs) { void PdfParser::opSetWordSpacing(Object args[], int numArgs) { state->setWordSpace(args[0].getNum()); - //out->updateWordSpace(state); } void PdfParser::opSetHorizScaling(Object args[], int numArgs) { state->setHorizScaling(args[0].getNum()); - //out->updateHorizScaling(state); fontChanged = gTrue; } @@ -2026,12 +2041,10 @@ void PdfParser::opShowText(Object args[], int numArgs) { return; } if (fontChanged) { - //NEEDED out->updateFont(state); + builder->updateFont(state); fontChanged = gFalse; } - //out->beginStringOp(state); doShowText(args[0].getString()); - //out->endStringOp(state); } void PdfParser::opMoveShowText(Object args[], int numArgs) { @@ -2042,15 +2055,13 @@ void PdfParser::opMoveShowText(Object args[], int numArgs) { return; } if (fontChanged) { - //out->updateFont(state); + builder->updateFont(state); fontChanged = gFalse; } tx = state->getLineX(); ty = state->getLineY() - state->getLeading(); state->textMoveTo(tx, ty); - //out->beginStringOp(state); doShowText(args[0].getString()); - //out->endStringOp(state); } void PdfParser::opMoveSetShowText(Object args[], int numArgs) { @@ -2061,7 +2072,7 @@ void PdfParser::opMoveSetShowText(Object args[], int numArgs) { return; } if (fontChanged) { - //out->updateFont(state); + builder->updateFont(state); fontChanged = gFalse; } state->setWordSpace(args[0].getNum()); @@ -2069,9 +2080,7 @@ void PdfParser::opMoveSetShowText(Object args[], int numArgs) { tx = state->getLineX(); ty = state->getLineY() - state->getLeading(); state->textMoveTo(tx, ty); - //out->beginStringOp(state); doShowText(args[2].getString()); - //out->endStringOp(state); } void PdfParser::opShowSpaceText(Object args[], int numArgs) { @@ -2085,10 +2094,9 @@ void PdfParser::opShowSpaceText(Object args[], int numArgs) { return; } if (fontChanged) { - //out->updateFont(state); + builder->updateFont(state); fontChanged = gFalse; } - //out->beginStringOp(state); wMode = state->getFont()->getWMode(); a = args[0].getArray(); for (i = 0; i < a->getLength(); ++i) { @@ -2110,37 +2118,8 @@ void PdfParser::opShowSpaceText(Object args[], int numArgs) { } obj.free(); } - //out->endStringOp(state); -} - -#include -#include - -static gchar * -unicode_to_char (Unicode *unicode, - int len) -{ - static UnicodeMap *uMap = NULL; - if (uMap == NULL) { - GooString *enc = new GooString("UTF-8"); - uMap = globalParams->getUnicodeMap(enc); - uMap->incRefCnt (); - delete enc; - } - - GooString gstr; - gchar buf[8]; /* 8 is enough for mapping an unicode char to a string */ - int i, n; - - for (i = 0; i < len; ++i) { - n = uMap->mapUnicode(unicode[i], buf, sizeof(buf)); - gstr.append(buf, n); - } - - return g_strdup (gstr.getCString ()); } - void PdfParser::doShowText(GooString *s) { GfxFont *font; int wMode; @@ -2159,10 +2138,8 @@ void PdfParser::doShowText(GooString *s) { font = state->getFont(); wMode = font->getWMode(); -printf("doShowText() called\n"); -// if (out->useDrawChar()) { -// out->beginString(state, s); -// } + + builder->beginString(state, s); // handle a Type 3 char if (font->getType() == fontType3 && 0) {//out->interpretType3Chars()) { @@ -2239,7 +2216,7 @@ printf("doShowText() called\n"); } parser = oldParser; - } else if (1){//out->useDrawChar()) { + } else { state->textTransformDelta(0, state->getRise(), &riseX, &riseY); p = s->getCString(); len = s->getLength(); @@ -2248,11 +2225,6 @@ printf("doShowText() called\n"); u, (int)(sizeof(u) / sizeof(Unicode)), &uLen, &dx, &dy, &originX, &originY); - if (uLen > 0) { - gchar *sc = unicode_to_char((Unicode*)&u, uLen); - printf("%s", sc); - g_free(sc); - } if (wMode) { dx *= state->getFontSize(); dy = dy * state->getFontSize() + state->getCharSpace(); @@ -2271,53 +2243,15 @@ printf("doShowText() called\n"); originX *= state->getFontSize(); originY *= state->getFontSize(); state->textTransformDelta(originX, originY, &tOriginX, &tOriginY); -// out->drawChar(state, state->getCurX() + riseX, state->getCurY() + riseY, -// tdx, tdy, tOriginX, tOriginY, code, n, u, uLen); + builder->addChar(state, state->getCurX() + riseX, state->getCurY() + riseY, + tdx, tdy, tOriginX, tOriginY, code, n, u, uLen); state->shift(tdx, tdy); p += n; len -= n; } - - } else { - dx = dy = 0; - p = s->getCString(); - len = s->getLength(); - nChars = nSpaces = 0; - while (len > 0) { - n = font->getNextChar(p, len, &code, - u, (int)(sizeof(u) / sizeof(Unicode)), &uLen, - &dx2, &dy2, &originX, &originY); - dx += dx2; - dy += dy2; - if (n == 1 && *p == ' ') { - ++nSpaces; - } - ++nChars; - p += n; - len -= n; - } - if (wMode) { - dx *= state->getFontSize(); - dy = dy * state->getFontSize() - + nChars * state->getCharSpace() - + nSpaces * state->getWordSpace(); - } else { - dx = dx * state->getFontSize() - + nChars * state->getCharSpace() - + nSpaces * state->getWordSpace(); - dx *= state->getHorizScaling(); - dy *= state->getFontSize(); - } - state->textTransformDelta(dx, dy, &tdx, &tdy); -// out->drawString(state, s); - state->shift(tdx, tdy); } -// if (out->useDrawChar()) { -// out->endString(state); -// } - - updateLevel += 10 * s->getLength(); + builder->endString(state); } //------------------------------------------------------------------------ @@ -2659,8 +2593,8 @@ void PdfParser::doImage(Object *ref, Stream *str, GBool inlineImg) { /* out->drawMaskedImage(state, ref, str, width, height, colorMap, maskStr, maskWidth, maskHeight, maskInvert);*/ } else { -/* out->drawImage(state, ref, str, width, height, colorMap, - haveColorKeyMask ? maskColors : (int *)NULL, inlineImg);*/ + builder->addImage(state, str, width, height, colorMap, + haveColorKeyMask ? maskColors : (int *)NULL); } delete colorMap; @@ -2668,11 +2602,6 @@ void PdfParser::doImage(Object *ref, Stream *str, GBool inlineImg) { smaskObj.free(); } - if ((i = width * height) > 1000) { - i = 1000; - } - updateLevel += i; - return; err2: diff --git a/src/extension/internal/pdfinput/pdf-parser.h b/src/extension/internal/pdfinput/pdf-parser.h index 4c6676999..394c9ca83 100644 --- a/src/extension/internal/pdfinput/pdf-parser.h +++ b/src/extension/internal/pdfinput/pdf-parser.h @@ -109,10 +109,8 @@ class PdfParser { public: // Constructor for regular output. - PdfParser(XRef *xrefA, SvgBuilder *builderA, - int pageNum, Dict *resDict, PDFRectangle *cropBox, - GBool (*abortCheckCbkA)(void *data) = NULL, - void *abortCheckCbkDataA = NULL); + PdfParser(XRef *xrefA, SvgBuilder *builderA, int pageNum, int rotate, + Dict *resDict, PDFRectangle *cropBox); ~PdfParser(); @@ -135,7 +133,6 @@ private: GBool subPage; // is this a sub-page object? GBool printCommands; // print the drawing commands (for debugging) GfxResources *res; // resource stack - int updateLevel; GfxState *state; // current graphics state GBool fontChanged; // set if font or text matrix has changed @@ -147,16 +144,12 @@ private: Parser *parser; // parser for page content stream(s) - GBool // callback to check for an abort - (*abortCheckCbk)(void *data); - void *abortCheckCbkData; - static PdfOperator opTab[]; // table of operators OpHistoryEntry *operatorHistory; // list containing the last N operators void pushOperator(const char *name); OpHistoryEntry *popOperator(); - const char *getPreviousOperator(); // returns the previous operator's name + const char *getPreviousOperator(unsigned int look_back=1); // returns the nth previous operator's name void go(GBool topLevel); void execOp(Object *cmd, Object args[], int numArgs); diff --git a/src/extension/internal/pdfinput/svg-builder.cpp b/src/extension/internal/pdfinput/svg-builder.cpp index 9457d2254..c67b191e1 100644 --- a/src/extension/internal/pdfinput/svg-builder.cpp +++ b/src/extension/internal/pdfinput/svg-builder.cpp @@ -19,6 +19,8 @@ #include "svg-builder.h" #include "pdf-parser.h" +#include + #include "document-private.h" #include "xml/document.h" #include "xml/node.h" @@ -29,77 +31,99 @@ #include "svg/svg-color.h" #include "color.h" #include "unit-constants.h" +#include "io/stringstream.h" +#include "io/base64stream.h" +#include "libnr/nr-matrix-ops.h" +#include "libnrtype/font-instance.h" #include "Function.h" #include "GfxState.h" +#include "GfxFont.h" +#include "Stream.h" +#include "UnicodeMap.h" +#include "GlobalParams.h" namespace Inkscape { namespace Extension { namespace Internal { -#define LOG(expr) ( expr ); +//#define IFTRACE(_code) _code +#define IFTRACE(_code) + +#define TRACE(_args) IFTRACE(g_print _args) + /** * \class SvgBuilder * */ +SvgBuilder::SvgBuilder() { + _in_text_object = false; + _need_font_update = true; + _invalidated_style = true; + _font_style = NULL; + _current_font = NULL; + _current_state = NULL; +} + SvgBuilder::SvgBuilder(SPDocument *document) { - doc = document; - xml_doc = sp_document_repr_doc(doc); - container = root = doc->rroot; + _doc = document; + _xml_doc = sp_document_repr_doc(_doc); + _container = _root = _doc->rroot; + SvgBuilder(); } SvgBuilder::SvgBuilder(SvgBuilder *parent, Inkscape::XML::Node *root) { - doc = parent->doc; - xml_doc = parent->xml_doc; - container = this->root = root; + _doc = parent->_doc; + _xml_doc = parent->_xml_doc; + _container = this->_root = root; + SvgBuilder(); } SvgBuilder::~SvgBuilder() { } void SvgBuilder::setDocumentSize(double width, double height) { - sp_repr_set_svg_double(root, "width", width); - sp_repr_set_svg_double(root, "height", height); - this->width = width; - this->height = height; + sp_repr_set_svg_double(_root, "width", width); + sp_repr_set_svg_double(_root, "height", height); + this->_width = width; + this->_height = height; } void SvgBuilder::saveState() { - groupDepth.push_back(0); + _group_depth.push_back(0); pushGroup(); } void SvgBuilder::restoreState() { - int depth = groupDepth.back(); - while (groupDepth.back() > 0) { + while (_group_depth.back() > 0) { popGroup(); } - groupDepth.pop_back(); + _group_depth.pop_back(); } Inkscape::XML::Node *SvgBuilder::pushGroup() { - Inkscape::XML::Node *node = xml_doc->createElement("svg:g"); - container->appendChild(node); - container = node; + Inkscape::XML::Node *node = _xml_doc->createElement("svg:g"); + _container->appendChild(node); + _container = node; Inkscape::GC::release(node); - groupDepth.back()++; + _group_depth.back()++; - return container; + return _container; } Inkscape::XML::Node *SvgBuilder::popGroup() { - if (container != root) { // Pop if the current container isn't root - container = container->parent(); - groupDepth[groupDepth.size()-1] = --groupDepth.back(); + if (_container != _root) { // Pop if the current container isn't root + _container = _container->parent(); + _group_depth[_group_depth.size()-1] = --_group_depth.back(); } - return container; + return _container; } Inkscape::XML::Node *SvgBuilder::getContainer() { - return container; + return _container; } static gchar *svgConvertRGBToText(double r, double g, double b) { @@ -109,7 +133,7 @@ static gchar *svgConvertRGBToText(double r, double g, double b) { SP_COLOR_F_TO_U(r), SP_COLOR_F_TO_U(g), SP_COLOR_F_TO_U(b)); - return (gchar*)&tmp; + return (gchar *)&tmp; } static gchar *svgConvertGfxRGB(GfxRGB *color) { @@ -119,22 +143,27 @@ static gchar *svgConvertGfxRGB(GfxRGB *color) { return svgConvertRGBToText(r, g, b); } -static gchar *svgInterpretTransform(double c0, double c1, double c2, double c3, - double c4, double c5) { +static void svgSetTransform(Inkscape::XML::Node *node, double c0, double c1, + double c2, double c3, double c4, double c5) { NR::Matrix matrix(c0, c1, c2, c3, c4, c5); - return sp_svg_transform_write(matrix); + gchar *transform_text = sp_svg_transform_write(matrix); + node->setAttribute("transform", transform_text); + g_free(transform_text); } -static gchar *svgInterpretTransform(double *transform) { - return svgInterpretTransform(transform[0], transform[1], transform[2], - transform[3], transform[4], transform[5]); +static void svgSetTransform(Inkscape::XML::Node *node, double *transform) { + svgSetTransform(node, transform[0], transform[1], transform[2], transform[3], + transform[4], transform[5]); } +/** + * \brief Generates a SVG path string from poppler's data structure + */ static gchar *svgInterpretPath(GfxPath *path) { GfxSubpath *subpath; Inkscape::SVG::PathString pathString; int i, j; - for (i = 0; i < path->getNumSubpaths(); ++i) { + for ( i = 0 ; i < path->getNumSubpaths() ; ++i ) { subpath = path->getSubpath(i); if (subpath->getNumPoints() > 0) { pathString.moveTo(subpath->getX(0), subpath->getY(0)); @@ -164,17 +193,18 @@ static gchar *svgInterpretPath(GfxPath *path) { * \brief Sets stroke style from poppler's GfxState data structure * Uses the given SPCSSAttr for storing the style properties */ -void SvgBuilder::setStrokeStyle(SPCSSAttr *css, GfxState *state) { +void SvgBuilder::_setStrokeStyle(SPCSSAttr *css, GfxState *state) { // Check line width - if (state->getLineWidth() <= 0.0) { + if ( state->getLineWidth() <= 0.0 ) { // Ignore stroke + sp_repr_css_set_property(css, "stroke", "none"); return; } // Stroke color/pattern - if (state->getStrokeColorSpace()->getMode() == csPattern) { - gchar *urltext = createPattern(state->getStrokePattern()); + if ( state->getStrokeColorSpace()->getMode() == csPattern ) { + gchar *urltext = _createPattern(state->getStrokePattern()); sp_repr_css_set_property(css, "stroke", urltext); if (urltext) { g_free(urltext); @@ -231,15 +261,14 @@ void SvgBuilder::setStrokeStyle(SPCSSAttr *css, GfxState *state) { int dash_length; double dash_start; state->getLineDash(&dash_pattern, &dash_length, &dash_start); - if (dash_length > 0) { + if ( dash_length > 0 ) { Inkscape::CSSOStringStream os_array; - for (int i = 0; i < dash_length; i++) { + for ( int i = 0 ; i < dash_length ; i++ ) { os_array << dash_pattern[i]; if (i < (dash_length - 1)) { os_array << ","; } } - printf("aaaa %s\n", os_array.str().c_str()); sp_repr_css_set_property(css, "stroke-dasharray", os_array.str().c_str()); Inkscape::CSSOStringStream os_offset; @@ -255,11 +284,11 @@ void SvgBuilder::setStrokeStyle(SPCSSAttr *css, GfxState *state) { * \brief Sets fill style from poppler's GfxState data structure * Uses the given SPCSSAttr for storing the style properties. */ -void SvgBuilder::setFillStyle(SPCSSAttr *css, GfxState *state, bool even_odd) { +void SvgBuilder::_setFillStyle(SPCSSAttr *css, GfxState *state, bool even_odd) { // Fill color/pattern - if (state->getFillColorSpace()->getMode() == csPattern) { - gchar *urltext = createPattern(state->getFillPattern()); + if ( state->getFillColorSpace()->getMode() == csPattern ) { + gchar *urltext = _createPattern(state->getFillPattern()); sp_repr_css_set_property(css, "fill", urltext); if (urltext) { g_free(urltext); @@ -283,16 +312,16 @@ void SvgBuilder::setFillStyle(SPCSSAttr *css, GfxState *state, bool even_odd) { * \brief Sets style properties from poppler's GfxState data structure * \return SPCSSAttr with all the relevant properties set */ -SPCSSAttr *SvgBuilder::setStyle(GfxState *state, bool fill, bool stroke, bool even_odd) { +SPCSSAttr *SvgBuilder::_setStyle(GfxState *state, bool fill, bool stroke, bool even_odd) { SPCSSAttr *css = sp_repr_css_attr_new(); if (fill) { - setFillStyle(css, state, even_odd); + _setFillStyle(css, state, even_odd); } else { sp_repr_css_set_property(css, "fill", "none"); } if (stroke) { - setStrokeStyle(css, state); + _setStrokeStyle(css, state); } else { sp_repr_css_set_property(css, "stroke", "none"); } @@ -309,20 +338,25 @@ SPCSSAttr *SvgBuilder::setStyle(GfxState *state, bool fill, bool stroke, bool ev * \param even_odd whether the even-odd rule should be used when filling the path */ void SvgBuilder::addPath(GfxState *state, bool fill, bool stroke, bool even_odd) { - Inkscape::XML::Node *path = xml_doc->createElement("svg:path"); + Inkscape::XML::Node *path = _xml_doc->createElement("svg:path"); gchar *pathtext = svgInterpretPath(state->getPath()); path->setAttribute("d", pathtext); g_free(pathtext); // Set style - SPCSSAttr *css = setStyle(state, fill, stroke, even_odd); + SPCSSAttr *css = _setStyle(state, fill, stroke, even_odd); sp_repr_css_change(path, css, "style"); sp_repr_css_attr_unref(css); - container->appendChild(path); + _container->appendChild(path); Inkscape::GC::release(path); } +/** + * \brief Clips to the current path set in GfxState + * \param state poppler's data structure + * \param even_odd whether the even-odd rule should be applied + */ void SvgBuilder::clip(GfxState *state, bool even_odd) { pushGroup(); setClipPath(state, even_odd); @@ -330,29 +364,34 @@ void SvgBuilder::clip(GfxState *state, bool even_odd) { void SvgBuilder::setClipPath(GfxState *state, bool even_odd) { // Create the clipPath repr - Inkscape::XML::Node *clip_path = xml_doc->createElement("svg:clipPath"); + Inkscape::XML::Node *clip_path = _xml_doc->createElement("svg:clipPath"); clip_path->setAttribute("clipPathUnits", "userSpaceOnUse"); // Create the path - Inkscape::XML::Node *path = xml_doc->createElement("svg:path"); + Inkscape::XML::Node *path = _xml_doc->createElement("svg:path"); gchar *pathtext = svgInterpretPath(state->getPath()); path->setAttribute("d", pathtext); g_free(pathtext); clip_path->appendChild(path); Inkscape::GC::release(path); // Append clipPath to defs and get id - SP_OBJECT_REPR (SP_DOCUMENT_DEFS (doc))->appendChild(clip_path); + SP_OBJECT_REPR (SP_DOCUMENT_DEFS (_doc))->appendChild(clip_path); gchar *urltext = g_strdup_printf ("url(#%s)", clip_path->attribute("id")); Inkscape::GC::release(clip_path); - container->setAttribute("clip-path", urltext); + _container->setAttribute("clip-path", urltext); g_free(urltext); } +/** + * \brief Fills the given array with the current container's transform, if set + * \param transform array of doubles to be filled + * \return true on success; false on invalid transformation + */ bool SvgBuilder::getTransform(double *transform) { NR::Matrix svd; - gchar const *tr = container->attribute("transform"); + gchar const *tr = _container->attribute("transform"); bool valid = sp_svg_transform_read(tr, &svd); if (valid) { - for (unsigned i = 0; i < 6; i++) { + for ( int i = 0 ; i < 6 ; i++ ) { transform[i] = svd[i]; } return true; @@ -361,13 +400,14 @@ bool SvgBuilder::getTransform(double *transform) { } } +/** + * \brief Sets the transformation matrix of the current container + */ void SvgBuilder::setTransform(double c0, double c1, double c2, double c3, double c4, double c5) { - gchar *transform_text = svgInterpretTransform(c0, c1, c2, c3, c4, c5); - LOG(g_message("setTransform: %f %f %f %f %f %f", c0, c1, c2, c3, c4, c5)); - container->setAttribute("transform", transform_text); - g_free(transform_text); + TRACE(("setTransform: %f %f %f %f %f %f\n", c0, c1, c2, c3, c4, c5)); + svgSetTransform(_container, c0, c1, c2, c3, c4, c5); } void SvgBuilder::setTransform(double *transform) { @@ -380,16 +420,16 @@ void SvgBuilder::setTransform(double *transform) { * Used by PdfParser to decide when to do fallback operations. */ bool SvgBuilder::isPatternTypeSupported(GfxPattern *pattern) { - if (pattern != NULL) { - if (pattern->getType() == 2) { // shading pattern + if ( pattern != NULL ) { + if ( pattern->getType() == 2 ) { // shading pattern GfxShading *shading = ((GfxShadingPattern *)pattern)->getShading(); int shadingType = shading->getType(); - if (shadingType == 2 || // axial shading - shadingType == 3) { // radial shading + if ( shadingType == 2 || // axial shading + shadingType == 3 ) { // radial shading return true; } return false; - } else if (pattern->getType() == 1) { // tiling pattern + } else if ( pattern->getType() == 1 ) { // tiling pattern return true; } } @@ -403,13 +443,13 @@ bool SvgBuilder::isPatternTypeSupported(GfxPattern *pattern) { * build a tiling pattern. * \return an url pointing to the created pattern */ -gchar *SvgBuilder::createPattern(GfxPattern *pattern) { +gchar *SvgBuilder::_createPattern(GfxPattern *pattern) { gchar *id = NULL; - if (pattern != NULL) { - if (pattern->getType() == 2) { // Shading pattern - id = createGradient((GfxShadingPattern*)pattern); - } else if (pattern->getType() == 1) { // Tiling pattern - id = createTilingPattern((GfxTilingPattern*)pattern); + if ( pattern != NULL ) { + if ( pattern->getType() == 2 ) { // Shading pattern + id = _createGradient((GfxShadingPattern*)pattern); + } else if ( pattern->getType() == 1 ) { // Tiling pattern + id = _createTilingPattern((GfxTilingPattern*)pattern); } } else { return NULL; @@ -419,7 +459,7 @@ gchar *SvgBuilder::createPattern(GfxPattern *pattern) { return urltext; } -gchar *SvgBuilder::createTilingPattern(GfxTilingPattern *tiling_pattern) { +gchar *SvgBuilder::_createTilingPattern(GfxTilingPattern *tiling_pattern) { return NULL; } @@ -427,14 +467,15 @@ gchar *SvgBuilder::createTilingPattern(GfxTilingPattern *tiling_pattern) { * \brief Creates a linear or radial gradient from poppler's data structure * \return id of the created object */ -gchar *SvgBuilder::createGradient(GfxShadingPattern *shading_pattern) { +gchar *SvgBuilder::_createGradient(GfxShadingPattern *shading_pattern) { GfxShading *shading = shading_pattern->getShading(); Inkscape::XML::Node *gradient; Function *func; int num_funcs; bool extend0, extend1; - if (shading->getType() == 2) { // Axial shading - gradient = xml_doc->createElement("svg:linearGradient"); + + if ( shading->getType() == 2 ) { // Axial shading + gradient = _xml_doc->createElement("svg:linearGradient"); GfxAxialShading *axial_shading = (GfxAxialShading*)shading; double x1, y1, x2, y2; axial_shading->getCoords(&x1, &y1, &x2, &y2); @@ -447,7 +488,7 @@ gchar *SvgBuilder::createGradient(GfxShadingPattern *shading_pattern) { num_funcs = axial_shading->getNFuncs(); func = axial_shading->getFunc(0); } else if (shading->getType() == 3) { // Radial shading - gradient = xml_doc->createElement("svg:radialGradient"); + gradient = _xml_doc->createElement("svg:radialGradient"); GfxRadialShading *radial_shading = (GfxRadialShading*)shading; double x1, y1, r1, x2, y2, r2; radial_shading->getCoords(&x1, &y1, &r1, &x2, &y2, &r2); @@ -468,19 +509,22 @@ gchar *SvgBuilder::createGradient(GfxShadingPattern *shading_pattern) { // Flip the gradient transform around the y axis double *p2u = shading_pattern->getMatrix(); NR::Matrix pat_matrix(p2u[0], p2u[1], p2u[2], p2u[3], p2u[4], p2u[5]); - NR::Matrix flip(1.0, 0.0, 0.0, -1.0, 0.0, height*PT_PER_PX); + NR::Matrix flip(1.0, 0.0, 0.0, -1.0, 0.0, _height * PT_PER_PX); pat_matrix *= flip; - gradient->setAttribute("gradientTransform", sp_svg_transform_write(pat_matrix)); + gchar *transform_text = sp_svg_transform_write(pat_matrix); + gradient->setAttribute("gradientTransform", transform_text); + g_free(transform_text); - if (extend0 && extend1) { + if ( extend0 && extend1 ) { gradient->setAttribute("spreadMethod", "pad"); } - if (num_funcs > 1 || !addStopsToGradient(gradient, func, 1.0)) { + + if ( num_funcs > 1 || !_addStopsToGradient(gradient, func, 1.0) ) { Inkscape::GC::release(gradient); return NULL; } - Inkscape::XML::Node *defs = SP_OBJECT_REPR (SP_DOCUMENT_DEFS (doc)); + Inkscape::XML::Node *defs = SP_OBJECT_REPR (SP_DOCUMENT_DEFS (_doc)); defs->appendChild(gradient); gchar *id = g_strdup(gradient->attribute("id")); Inkscape::GC::release(gradient); @@ -489,64 +533,57 @@ gchar *SvgBuilder::createGradient(GfxShadingPattern *shading_pattern) { } #define EPSILON 0.0001 -bool SvgBuilder::addSamplesToGradient(Inkscape::XML::Node *gradient, - SampledFunction *func, double offset0, - double offset1, double opacity) { +bool SvgBuilder::_addSamplesToGradient(Inkscape::XML::Node *gradient, + SampledFunction *func, double offset0, + double offset1, double opacity) { // Check whether this sampled function can be converted to color stops int sample_size = func->getSampleSize(0); - if (sample_size != 2) + if ( sample_size != 2 ) return false; int num_comps = func->getOutputSize(); - if (num_comps != 3) + if ( num_comps != 3 ) return false; double *samples = func->getSamples(); - // See if this is the continuation of the previous sampled function - bool is_continuation = false; unsigned stop_count = gradient->childCount(); - if (stop_count > 0) { + bool is_continuation = false; + // Check if this sampled function is the continuation of the previous one + if ( stop_count > 0 ) { // Get previous stop Inkscape::XML::Node *prev_stop = gradient->nthChild(stop_count-1); - // Read its properties - double offset; - sp_repr_get_double(prev_stop, "offset", &offset); + double prev_offset; + sp_repr_get_double(prev_stop, "offset", &prev_offset); SPCSSAttr *css = sp_repr_css_attr(prev_stop, "style"); - guint32 prev_color = sp_svg_read_color(sp_repr_css_property(css, "stop-color", NULL), 0); - double alpha = sp_repr_css_double_property(css, "stop-opacity", 1.0); + guint32 prev_stop_color = sp_svg_read_color(sp_repr_css_property(css, "stop-color", NULL), 0); sp_repr_css_attr_unref(css); // Convert colors - double r = SP_RGBA32_R_F(prev_color); - double g = SP_RGBA32_G_F(prev_color); - double b = SP_RGBA32_B_F(prev_color); - - if (fabs(offset - offset0) < EPSILON && - fabs(samples[0] - r) < EPSILON && - fabs(samples[1] - g) < EPSILON && - fabs(samples[2] - b) < EPSILON && - fabs(alpha - opacity) < EPSILON) { // Identical + double r = SP_RGBA32_R_F (prev_stop_color); + double g = SP_RGBA32_G_F (prev_stop_color); + double b = SP_RGBA32_B_F (prev_stop_color); + if ( fabs(prev_offset - offset0) < EPSILON && + fabs(samples[0] - r) < EPSILON && + fabs(samples[1] - g) < EPSILON && + fabs(samples[2] - b) < EPSILON ) { is_continuation = true; - LOG(g_message("gradient offsets merged")); } } - int i = 0; - if (is_continuation) - i = num_comps; + int i = is_continuation ? num_comps : 0; while (i < sample_size*num_comps) { - Inkscape::XML::Node *stop = xml_doc->createElement("svg:stop"); + Inkscape::XML::Node *stop = _xml_doc->createElement("svg:stop"); SPCSSAttr *css = sp_repr_css_attr_new(); Inkscape::CSSOStringStream os_opacity; os_opacity << opacity; sp_repr_css_set_property(css, "stop-opacity", os_opacity.str().c_str()); - sp_repr_css_set_property(css, "stop-color", - svgConvertRGBToText(samples[i], samples[i+1], - samples[i+2])); + gchar c[64]; + sp_svg_write_color (c, 64, SP_RGBA32_F_COMPOSE (samples[i], samples[i+1], samples[i+2], 1.0)); + sp_repr_css_set_property(css, "stop-color", c); sp_repr_css_change(stop, css, "style"); sp_repr_css_attr_unref(css); - sp_repr_set_css_double(stop, "offset", (i < num_comps) ? offset0 : offset1); + sp_repr_set_css_double(stop, "offset", ( i < num_comps ) ? offset0 : offset1); gradient->appendChild(stop); Inkscape::GC::release(stop); @@ -556,34 +593,26 @@ bool SvgBuilder::addSamplesToGradient(Inkscape::XML::Node *gradient, return true; } -bool SvgBuilder::addStopsToGradient(Inkscape::XML::Node *gradient, Function *func, - double opacity) { +bool SvgBuilder::_addStopsToGradient(Inkscape::XML::Node *gradient, Function *func, + double opacity) { int type = func->getType(); - if (type == 0) { // Sampled + if ( type == 0 ) { // Sampled SampledFunction *sampledFunc = (SampledFunction*)func; - addSamplesToGradient(gradient, sampledFunc, 0.0, 1.0, opacity); - } else if (type == 3) { // Stitching + _addSamplesToGradient(gradient, sampledFunc, 0.0, 1.0, opacity); + } else if ( type == 3 ) { // Stitching StitchingFunction *stitchingFunc = (StitchingFunction*)func; double *bounds = stitchingFunc->getBounds(); - // bounds might be outside of [0..1]!!!! - double *encode = stitchingFunc->getEncode(); - // should check whether all of them are [0..1] int num_funcs = stitchingFunc->getNumFuncs(); // Add samples from all the stitched functions - for (int i=0; igetFunc(i); - if (func->getType() != 0) // Only sampled functions are supported + if ( func->getType() != 0 ) // Only sampled functions are supported continue; - - LOG(g_message("t%i i%i o%i m%f m%f", - func->getType(), - func->getInputSize(), func->getOutputSize(), - func->getDomainMin(0), func->getDomainMax(0))); - + SampledFunction *sampledFunc = (SampledFunction*)func; - addSamplesToGradient(gradient, sampledFunc, bounds[i], - bounds[i+1], opacity); + _addSamplesToGradient(gradient, sampledFunc, bounds[i], + bounds[i+1], opacity); } } else { // Unsupported function type return false; @@ -592,7 +621,568 @@ bool SvgBuilder::addStopsToGradient(Inkscape::XML::Node *gradient, Function *fun return true; } -} } } /* namespace Inkscape, Extension, Internal, PdfInput */ +/** + * \brief Sets _invalidated_style to true to indicate that styles have to be updated + * Used for text output when glyphs are buffered till a font change + */ +void SvgBuilder::updateStyle(GfxState *state) { + if (_in_text_object) { + _invalidated_style = true; + _current_state = state; + } +} + +/** + * \brief Updates _font_style according to the font set in parameter state + */ +void SvgBuilder::updateFont(GfxState *state) { + + TRACE(("updateFont()\n")); + _need_font_update = false; + // Flush buffered text before resetting matrices and font style + _flushText(); + + if (_font_style) { + //sp_repr_css_attr_unref(_font_style); + } + _font_style = sp_repr_css_attr_new(); + GfxFont *font = state->getFont(); + // Store original name + if (font->getOrigName()) { + _font_specification = font->getOrigName()->getCString(); + } else { + _font_specification = font->getName()->getCString(); + } + + // Prune the font name to get the correct font family name + // In a PDF font names can look like this: IONIPB+MetaPlusBold-Italic + char *font_family = NULL; + char *font_style = NULL; + char *plus_sign = strstr(_font_specification, "+"); + if (plus_sign) { + font_family = g_strdup(plus_sign + 1); + _font_specification = plus_sign + 1; + } else { + font_family = g_strdup(_font_specification); + } + char *minus_sign = g_strrstr(font_family, "-"); + if (minus_sign) { + font_style = minus_sign + 1; + minus_sign[0] = 0; + } + + // Font family + if (font->getFamily()) { + const gchar *family = font->getFamily()->getCString(); + sp_repr_css_set_property(_font_style, "font-family", font->getFamily()->getCString()); + } else { + sp_repr_css_set_property(_font_style, "font-family", font_family); + } + g_free(font_family); + + // Font style + if (font->isItalic()) { + sp_repr_css_set_property(_font_style, "font-style", "italic"); + } + + // Font variant -- default 'normal' value + sp_repr_css_set_property(_font_style, "font-variant", "normal"); + + // Font weight + GfxFont::Weight font_weight = font->getWeight(); + if ( font_weight != GfxFont::WeightNotDefined ) { + if ( font_weight == GfxFont::W400 ) { + sp_repr_css_set_property(_font_style, "font-weight", "normal"); + } else if ( font_weight == GfxFont::W700 ) { + sp_repr_css_set_property(_font_style, "font-weight", "bold"); + } else { + gchar weight_num[4] = "100"; + weight_num[0] = (gchar)( '1' + (font_weight - GfxFont::W100) ); + sp_repr_css_set_property(_font_style, "font-weight", (gchar *)&weight_num); + } + } + + // Font stretch + GfxFont::Stretch font_stretch = font->getStretch(); + gchar *stretch_value = NULL; + switch (font_stretch) { + case GfxFont::UltraCondensed: + stretch_value = "ultra-condensed"; + break; + case GfxFont::ExtraCondensed: + stretch_value = "extra-condensed"; + break; + case GfxFont::Condensed: + stretch_value = "condensed"; + break; + case GfxFont::SemiCondensed: + stretch_value = "semi-condensed"; + break; + case GfxFont::Normal: + stretch_value = "normal"; + break; + case GfxFont::SemiExpanded: + stretch_value = "semi-expanded"; + break; + case GfxFont::Expanded: + stretch_value = "expanded"; + break; + case GfxFont::ExtraExpanded: + stretch_value = "extra-expanded"; + break; + case GfxFont::UltraExpanded: + stretch_value = "ultra-expanded"; + break; + default: + break; + } + if ( stretch_value != NULL ) { + sp_repr_css_set_property(_font_style, "font-stretch", stretch_value); + } + + // Font size + Inkscape::CSSOStringStream os_font_size; + double *text_matrix = state->getTextMat(); + double font_size = sqrt( text_matrix[0] * text_matrix[3] - text_matrix[1] * text_matrix[2] ); + font_size *= state->getFontSize() * state->getHorizScaling(); + os_font_size << font_size; + sp_repr_css_set_property(_font_style, "font-size", os_font_size.str().c_str()); + + // Writing mode + if ( font->getWMode() == 0 ) { + sp_repr_css_set_property(_font_style, "writing-mode", "lr"); + } else { + sp_repr_css_set_property(_font_style, "writing-mode", "tb"); + } + + // Calculate new text matrix + double *font_matrix = font->getFontMatrix(); + NR::Matrix nr_font_matrix(font_matrix[0], font_matrix[1], font_matrix[2], + font_matrix[3], font_matrix[4], font_matrix[5]); + NR::Matrix new_text_matrix(text_matrix[0], text_matrix[1], + -text_matrix[2], -text_matrix[3], + 0.0, 0.0); + new_text_matrix *= NR::scale( 1.0 / font_size, 1.0 / font_size ); + _text_matrix = nr_font_matrix * new_text_matrix; + + _current_font = font; +} + +/** + * \brief Writes the buffered characters to the SVG document + */ +void SvgBuilder::_flushText() { + // Ignore empty strings + if ( _glyphs.size() < 1 ) { + _glyphs.clear(); + return; + } + const SvgGlyph& first_glyph = _glyphs[0]; + int render_mode = first_glyph.render_mode; + // Ignore invisible characters + if ( render_mode == 3 ) { + _glyphs.clear(); + return; + } + + Inkscape::XML::Node *text_node = _xml_doc->createElement("svg:text"); + // Set current text position + sp_repr_set_svg_double(text_node, "x", first_glyph.transformed_position[0]); + sp_repr_set_svg_double(text_node, "y", first_glyph.transformed_position[1]); + // Set style + sp_repr_css_change(text_node, first_glyph.style, "style"); + text_node->setAttribute("inkscape:font-specification", _font_specification); + // Set text matrix + gchar *transform = sp_svg_transform_write(_text_matrix); + text_node->setAttribute("transform", transform); + g_free(transform); + + bool new_tspan = true; + Inkscape::XML::Node *tspan_node = NULL; + Glib::ustring x_coords; + Glib::ustring y_coords; + Glib::ustring text_buffer; + bool is_vertical = !strcmp(sp_repr_css_property(_font_style, "writing-mode", "lr"), "tb"); // FIXME + + // Output all buffered glyphs + std::vector::iterator i = _glyphs.begin(); + while (1) { + const SvgGlyph& glyph = (*i); + std::vector::iterator prev_iterator = i - 1; + // Check if we need to make a new tspan + if (glyph.style_changed) { + new_tspan = true; + } else if ( i != _glyphs.begin() ) { + const SvgGlyph& prev_glyph = (*prev_iterator); + if ( ( is_vertical && prev_glyph.transformed_position[0] != glyph.transformed_position[0] ) || + ( !is_vertical && prev_glyph.transformed_position[1] != glyph.transformed_position[1] ) ) { + new_tspan = true; + } + } + // Create tspan node if needed + if ( new_tspan || i == _glyphs.end() ) { + if (tspan_node) { + // Set the x and y coordinate arrays + tspan_node->setAttribute("x", x_coords.c_str()); + tspan_node->setAttribute("y", y_coords.c_str()); + TRACE(("tspan content: %s\n", text_buffer.c_str())); + // Add text content node to tspan + Inkscape::XML::Node *text_content = _xml_doc->createTextNode(text_buffer.c_str()); + tspan_node->appendChild(text_content); + Inkscape::GC::release(text_content); + text_node->appendChild(tspan_node); + // Clear temporary buffers + x_coords.clear(); + y_coords.clear(); + text_buffer.clear(); + Inkscape::GC::release(tspan_node); + } + if ( i == _glyphs.end() ) { + sp_repr_css_attr_unref((*prev_iterator).style); + break; + } else { + tspan_node = _xml_doc->createElement("svg:tspan"); + // Set style and unref SPCSSAttr if it won't be needed anymore + if ( i != _glyphs.begin() ) { + sp_repr_css_change(tspan_node, glyph.style, "style"); + if (glyph.style_changed) { // Free previous style + sp_repr_css_attr_unref((*prev_iterator).style); + } + } + } + new_tspan = false; + } + if ( x_coords.length() > 0 ) { + x_coords.append(" "); + y_coords.append(" "); + } + // Append the coordinates to their respective strings + Inkscape::CSSOStringStream os_x; + os_x << glyph.transformed_position[0]; + x_coords.append(os_x.str()); + Inkscape::CSSOStringStream os_y; + os_y << glyph.transformed_position[1]; + y_coords.append(os_y.str()); + + // Append the character to the text buffer + text_buffer.append((char *)&glyph.code, 1); + + i++; + } + _container->appendChild(text_node); + Inkscape::GC::release(text_node); + + _glyphs.clear(); +} + +void SvgBuilder::beginString(GfxState *state, GooString *s) { + if (_need_font_update) { + updateFont(state); + } + IFTRACE(double *m = state->getTextMat()); + TRACE(("tm: %f %f %f %f %f %f\n",m[0], m[1],m[2], m[3], m[4], m[5])); + IFTRACE(m = _current_font->getFontMatrix()); + TRACE(("fm: %f %f %f %f %f %f\n",m[0], m[1],m[2], m[3], m[4], m[5])); + IFTRACE(m = state->getCTM()); + TRACE(("ctm: %f %f %f %f %f %f\n",m[0], m[1],m[2], m[3], m[4], m[5])); +} + +/** + * \brief Adds the specified character to the text buffer + * Takes care of converting it to UTF-8 and generates a new style repr if style + * has changed since the last call. + */ +void SvgBuilder::addChar(GfxState *state, double x, double y, + double dx, double dy, + double originX, double originY, + CharCode code, int nBytes, Unicode *u, int uLen) { + + + bool is_space = ( uLen == 1 && u[0] == 32 ); + // Skip beginning space + if ( is_space && _glyphs.size() < 1 ) { + return; + } + // Allow only one space in a row + if ( is_space && _glyphs[_glyphs.size() - 1].code_size == 1 && + _glyphs[_glyphs.size() - 1].code[0] == 32 ) { + return; + } + + SvgGlyph new_glyph; + new_glyph.is_space = is_space; + new_glyph.position = NR::Point( x - originX, y - originY ); + new_glyph.transformed_position = new_glyph.position * _text_matrix; + new_glyph.dx = dx; + new_glyph.dy = dy; + + // Convert the character to UTF-8 since that's our SVG document's encoding + static UnicodeMap *u_map = NULL; + if ( u_map == NULL ) { + GooString *enc = new GooString("UTF-8"); + u_map = globalParams->getUnicodeMap(enc); + u_map->incRefCnt(); + delete enc; + } + int code_size = 0; + for ( int i = 0 ; i < uLen ; i++ ) { + code_size += u_map->mapUnicode(u[i], (char *)&new_glyph.code[code_size], sizeof(new_glyph.code) - code_size); + } + new_glyph.code_size = code_size; + + // Copy current style if it has changed since the previous glyph + if (_invalidated_style || _glyphs.size() == 0 ) { + new_glyph.style_changed = true; + int render_mode = state->getRender(); + // Set style + bool has_fill = !( render_mode & 1 ); + bool has_stroke = ( render_mode & 3 ) == 1 || ( render_mode & 3 ) == 2; + new_glyph.style = _setStyle(state, has_fill, has_stroke); + new_glyph.render_mode = render_mode; + sp_repr_css_merge(new_glyph.style, _font_style); // Merge with font style + _invalidated_style = false; + } else { + new_glyph.style_changed = false; + // Point to previous glyph's style information + const SvgGlyph& prev_glyph = _glyphs.back(); + new_glyph.style = prev_glyph.style; + new_glyph.render_mode = prev_glyph.render_mode; + } + _glyphs.push_back(new_glyph); +} + +void SvgBuilder::endString(GfxState *state) { +} + +void SvgBuilder::beginTextObject(GfxState *state) { + _in_text_object = true; + _invalidated_style = true; // Force copying of current state + _current_state = state; +} + +void SvgBuilder::endTextObject(GfxState *state) { + _flushText(); + // TODO: clip if render_mode >= 4 + _in_text_object = false; +} + +/** + * Helper functions for supporting direct PNG output into a base64 encoded stream + */ +void png_write_base64stream(png_structp png_ptr, png_bytep data, png_size_t length) +{ + Inkscape::IO::Base64OutputStream *stream = + (Inkscape::IO::Base64OutputStream*)png_get_io_ptr(png_ptr); // Get pointer to stream + for ( unsigned i = 0 ; i < length ; i++ ) { + stream->put((int)data[i]); + } +} + +void png_flush_base64stream(png_structp png_ptr) +{ + Inkscape::IO::Base64OutputStream *stream = + (Inkscape::IO::Base64OutputStream*)png_get_io_ptr(png_ptr); // Get pointer to stream + stream->flush(); +} + +/** + * \brief Creates an element containing the given ImageStream as a PNG + * + */ +Inkscape::XML::Node *SvgBuilder::_createImage(Stream *str, int width, int height, + GfxImageColorMap *color_map, int *mask_colors, bool alpha_only, bool invert_alpha) { + + // Create PNG write struct + png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); + if ( png_ptr == NULL ) { + return NULL; + } + // Create PNG info struct + png_infop info_ptr = png_create_info_struct(png_ptr); + if ( info_ptr == NULL ) { + png_destroy_write_struct(&png_ptr, NULL); + return NULL; + } + // Set error handler + if (setjmp(png_ptr->jmpbuf)) { + png_destroy_write_struct(&png_ptr, &info_ptr); + return NULL; + } + + // Set read/write functions + Inkscape::IO::StringOutputStream base64_string; + Inkscape::IO::Base64OutputStream base64_stream(base64_string); + FILE *fp; + gchar *file_name; + bool embed_image = true; + if (embed_image) { + base64_stream.setColumnWidth(0); // Disable line breaks + png_set_write_fn(png_ptr, &base64_stream, png_write_base64stream, png_flush_base64stream); + } else { + static int counter = 0; + file_name = g_strdup_printf("createImage%d.png", counter++); + fp = fopen(file_name, "wb"); + if ( fp == NULL ) { + png_destroy_write_struct(&png_ptr, &info_ptr); + g_free(file_name); + return NULL; + } + png_init_io(png_ptr, fp); + } + + // Set header data + if (!invert_alpha) { + png_set_invert_alpha(png_ptr); + } + png_color_8 sig_bit; + if (alpha_only) { + png_set_IHDR(png_ptr, info_ptr, + width, + height, + 8, /* bit_depth */ + PNG_COLOR_TYPE_GRAY, + PNG_INTERLACE_NONE, + PNG_COMPRESSION_TYPE_BASE, + PNG_FILTER_TYPE_BASE); + sig_bit.red = 0; + sig_bit.green = 0; + sig_bit.blue = 0; + sig_bit.gray = 8; + sig_bit.alpha = 0; + } else { + png_set_IHDR(png_ptr, info_ptr, + width, + height, + 8, /* bit_depth */ + PNG_COLOR_TYPE_RGB_ALPHA, + PNG_INTERLACE_NONE, + PNG_COMPRESSION_TYPE_BASE, + PNG_FILTER_TYPE_BASE); + sig_bit.red = 8; + sig_bit.green = 8; + sig_bit.blue = 8; + sig_bit.alpha = 8; + } + png_set_sBIT(png_ptr, info_ptr, &sig_bit); + png_set_bgr(png_ptr); + // Write the file header + png_write_info(png_ptr, info_ptr); + + // Convert pixels + ImageStream *image_stream; + if (alpha_only) { + if (color_map) { + image_stream = new ImageStream(str, width, color_map->getNumPixelComps(), + color_map->getBits()); + } else { + image_stream = new ImageStream(str, width, 1, 1); + } + image_stream->reset(); + + // Convert grayscale values + if (color_map) { + unsigned char *buffer = new unsigned char[width]; + for ( int y = 0 ; y < height ; y++ ) { + unsigned char *row = image_stream->getLine(); + color_map->getGrayLine(row, buffer, width); + png_write_row(png_ptr, (png_bytep)buffer); + } + delete buffer; + } else { + for ( int y = 0 ; y < height ; y++ ) { + unsigned char *row = image_stream->getLine(); + png_write_row(png_ptr, (png_bytep)row); + } + } + } else if (color_map) { + image_stream = new ImageStream(str, width, + color_map->getNumPixelComps(), + color_map->getBits()); + image_stream->reset(); + + // Convert RGB values + unsigned int *buffer = new unsigned int[width]; + if (mask_colors) { + for ( int y = 0 ; y < height ; y++ ) { + unsigned char *row = image_stream->getLine(); + color_map->getRGBLine(row, buffer, width); + + unsigned int *dest = buffer; + for ( int x = 0 ; x < width ; x++ ) { + // Check each color component against the mask + for ( int i = 0; i < color_map->getNumPixelComps() ; i++) { + if ( row[i] < mask_colors[2*i] * 255 || + row[i] > mask_colors[2*i + 1] * 255 ) { + *dest = *dest | 0xff000000; + break; + } + } + // Advance to the next pixel + row += color_map->getNumPixelComps(); + dest++; + } + // Write it to the PNG + png_write_row(png_ptr, (png_bytep)buffer); + } + } else { + for ( int i = 0 ; i < height ; i++ ) { + unsigned char *row = image_stream->getLine(); + memset((void*)buffer, 0xff, sizeof(int) * width); + color_map->getRGBLine(row, buffer, width); + png_write_row(png_ptr, (png_bytep)buffer); + } + } + delete buffer; + + } else { // A colormap must be provided, so quit + png_destroy_write_struct(&png_ptr, &info_ptr); + if (!embed_image) { + fclose(fp); + g_free(file_name); + } + return NULL; + } + delete image_stream; + str->close(); + // Close PNG + png_write_end(png_ptr, info_ptr); + png_destroy_write_struct(&png_ptr, &info_ptr); + base64_stream.close(); + + // Create repr + Inkscape::XML::Node *image_node = _xml_doc->createElement("svg:image"); + sp_repr_set_svg_double(image_node, "width", width); + sp_repr_set_svg_double(image_node, "height", height); + // Set transformation + svgSetTransform(image_node, 1.0/(double)width, 0.0, 0.0, -1.0/(double)height, 0.0, 1.0); + + // Create href + if (embed_image) { + // Append format specification to the URI + Glib::ustring& png_data = base64_string.getString(); + png_data.insert(0, "data:image/png;base64,"); + image_node->setAttribute("xlink:href", png_data.c_str()); + } else { + fclose(fp); + image_node->setAttribute("xlink:href", file_name); + g_free(file_name); + } + + return image_node; +} + +void SvgBuilder::addImage(GfxState *state, Stream *str, int width, int height, + GfxImageColorMap *color_map, int *mask_colors) { + + Inkscape::XML::Node *image_node = _createImage(str, width, height, color_map, mask_colors); + if (image_node) { + _container->appendChild(image_node); + Inkscape::GC::release(image_node); + } +} + + +} } } /* namespace Inkscape, Extension, Internal */ #endif /* HAVE_POPPLER */ diff --git a/src/extension/internal/pdfinput/svg-builder.h b/src/extension/internal/pdfinput/svg-builder.h index 042218413..8145a4522 100644 --- a/src/extension/internal/pdfinput/svg-builder.h +++ b/src/extension/internal/pdfinput/svg-builder.h @@ -26,12 +26,20 @@ namespace Inkscape { } } +#include "libnr/nr-point.h" +#include "libnr/nr-matrix.h" + +#include "CharTypes.h" +class GooString; class Function; class SampledFunction; struct GfxState; class GfxPattern; class GfxShadingPattern; class GfxTilingPattern; +class GfxFont; +class GfxImageColorMap; +class Stream; class SPCSSAttr; @@ -42,6 +50,24 @@ namespace Inkscape { namespace Extension { namespace Internal { +/** + * \struct SvgGlyph + * Holds information about glyphs added by PdfParser which haven't been added + * to the document yet. + */ +struct SvgGlyph { + NR::Point position; // Absolute glyph coords + NR::Point transformed_position; // Glyph coords transformed by text matrix + double dx, dy; // Advance values + char code[8]; // UTF-8 coded character + int code_size; + bool is_space; + + bool style_changed; // Set to true if style has to be reset + SPCSSAttr *style; + int render_mode; // Text render mode +}; + /** * \class SvgBuilder * @@ -65,11 +91,27 @@ public: // Path adding void addPath(GfxState *state, bool fill, bool stroke, bool even_odd=false); + // Image handling + void addImage(GfxState *state, Stream *str, int width, int height, + GfxImageColorMap *color_map, int *mask_colors); + + // Text handling + void beginString(GfxState *state, GooString *s); + void endString(GfxState *state); + void addChar(GfxState *state, double x, double y, + double dx, double dy, + double originX, double originY, + CharCode code, int nBytes, Unicode *u, int uLen); + void beginTextObject(GfxState *state); + void endTextObject(GfxState *state); + bool isPatternTypeSupported(GfxPattern *pattern); // State manipulation void saveState(); void restoreState(); + void updateStyle(GfxState *state); + void updateFont(GfxState *state); // Clipping void clip(GfxState *state, bool even_odd=false); @@ -82,29 +124,47 @@ public: bool getTransform(double *transform); private: + SvgBuilder(); + // Pattern creation - gchar *createPattern(GfxPattern *pattern); - gchar *createGradient(GfxShadingPattern *shading_pattern); - bool addStopsToGradient(Inkscape::XML::Node *gradient, Function *func, double opacity); - bool addSamplesToGradient(Inkscape::XML::Node *gradient, SampledFunction *func, + gchar *_createPattern(GfxPattern *pattern); + gchar *_createGradient(GfxShadingPattern *shading_pattern); + bool _addStopsToGradient(Inkscape::XML::Node *gradient, Function *func, double opacity); + bool _addSamplesToGradient(Inkscape::XML::Node *gradient, SampledFunction *func, double offset0, double offset1, double opacity); - gchar *createTilingPattern(GfxTilingPattern *tiling_pattern); + gchar *_createTilingPattern(GfxTilingPattern *tiling_pattern); + // Image/mask creation + Inkscape::XML::Node *_createImage(Stream *str, int width, int height, + GfxImageColorMap *color_map, int *mask_colors, + bool alpha_only=false, bool invert_alpha=false); // Style setting - SPCSSAttr *setStyle(GfxState *state, bool fill, bool stroke, bool even_odd); - void setStrokeStyle(SPCSSAttr *css, GfxState *state); - void setFillStyle(SPCSSAttr *css, GfxState *state, bool even_odd); - - std::vector groupDepth; // Depth of nesting groups - - SPDocument *doc; - Inkscape::XML::Document *xml_doc; - Inkscape::XML::Node *root; // Root node from the point of view of this SvgBuilder - Inkscape::XML::Node *container; // Current container (group/pattern/mask) - double width, height; // Document size in px + SPCSSAttr *_setStyle(GfxState *state, bool fill, bool stroke, bool even_odd=false); + void _setStrokeStyle(SPCSSAttr *css, GfxState *state); + void _setFillStyle(SPCSSAttr *css, GfxState *state, bool even_odd); + + void _flushText(); // Write buffered text into doc + + std::vector _group_depth; // Depth of nesting groups + + SPCSSAttr *_font_style; // Current font style + GfxFont *_current_font; + char *_font_specification; + bool _need_font_update; + NR::Matrix _text_matrix; + std::vector _glyphs; // Added characters + bool _in_text_object; // Whether we are inside a text object + bool _invalidated_style; + GfxState *_current_state; + + SPDocument *_doc; + Inkscape::XML::Document *_xml_doc; + Inkscape::XML::Node *_root; // Root node from the point of view of this SvgBuilder + Inkscape::XML::Node *_container; // Current container (group/pattern/mask) + double _width, _height; // Document size in px }; -} } } /* namespace Inkscape, Extension, Internal, PdfInput */ +} } } /* namespace Inkscape, Extension, Internal */ #endif /* HAVE_POPPLER */