Code

Pot and Dutch translation update
[inkscape.git] / src / extension / internal / latex-text-renderer.cpp
1 #define EXTENSION_INTERNAL_LATEX_TEXT_RENDERER_CPP
3 /** \file
4  * Rendering LaTeX file (pdf/eps/ps+latex output)
5  *
6  * The idea stems from GNUPlot's epslatex terminal output :-)
7  */
8 /*
9  * Authors:
10  *   Johan Engelen <goejendaagh@zonnet.nl>
11  *   Miklos Erdelyi <erdelyim@gmail.com>
12  *
13  * Copyright (C) 2006-2010 Authors
14  *
15  * Licensed under GNU GPL
16  */
18 #ifdef HAVE_CONFIG_H
19 # include "config.h"
20 #endif
22 #include "latex-text-renderer.h"
24 #include <signal.h>
25 #include <errno.h>
27 #include "libnrtype/Layout-TNG.h"
28 #include <2geom/transforms.h>
29 #include <2geom/rect.h>
31 #include <glibmm/i18n.h>
32 #include "sp-item.h"
33 #include "sp-item-group.h"
34 #include "style.h"
35 #include "sp-root.h"
36 #include "sp-use.h"
37 #include "sp-text.h"
38 #include "sp-flowtext.h"
39 #include "sp-rect.h"
40 #include "text-editing.h"
42 #include <unit-constants.h>
44 #include "extension/system.h"
46 #include "io/sys.h"
48 namespace Inkscape {
49 namespace Extension {
50 namespace Internal {
52 /**
53  * This method is called by the PDF, EPS and PS output extensions.
54  * @param filename This should be the filename without '_tex' extension to which the tex code should be written. Output goes to <filename>_tex, note the underscore instead of period.
55  */
56 bool
57 latex_render_document_text_to_file( SPDocument *doc, gchar const *filename,
58                                     const gchar * const exportId, bool exportDrawing, bool exportCanvas,
59                                     bool pdflatex)
60 {
61     sp_document_ensure_up_to_date(doc);
63     SPItem *base = NULL;
65     bool pageBoundingBox = true;
66     if (exportId && strcmp(exportId, "")) {
67         // we want to export the given item only
68         base = SP_ITEM(doc->getObjectById(exportId));
69         pageBoundingBox = exportCanvas;
70     }
71     else {
72         // we want to export the entire document from root
73         base = SP_ITEM(sp_document_root(doc));
74         pageBoundingBox = !exportDrawing;
75     }
77     if (!base)
78         return false;
80     /* Create renderer */
81     LaTeXTextRenderer *renderer = new LaTeXTextRenderer(pdflatex);
83     bool ret = renderer->setTargetFile(filename);
84     if (ret) {
85         /* Render document */
86         bool ret = renderer->setupDocument(doc, pageBoundingBox, base);
87         if (ret) {
88             renderer->renderItem(base);
89         }
90     }
92     delete renderer;
94     return ret;
95 }
97 LaTeXTextRenderer::LaTeXTextRenderer(bool pdflatex)
98   : _stream(NULL),
99     _filename(NULL),
100     _pdflatex(pdflatex)
102     push_transform(Geom::identity());
105 LaTeXTextRenderer::~LaTeXTextRenderer(void)
107     if (_stream) {
108         writePostamble();
110         fclose(_stream);
111     }
113     /* restore default signal handling for SIGPIPE */
114 #if !defined(_WIN32) && !defined(__WIN32__)
115     (void) signal(SIGPIPE, SIG_DFL);
116 #endif
118     if (_filename) {
119         g_free(_filename);
120     }
122     return;
125 /** This should create the output LaTeX file, and assign it to _stream.
126  * @return Returns true when succesfull
127  */
128 bool
129 LaTeXTextRenderer::setTargetFile(gchar const *filename) {
130     if (filename != NULL) {
131         while (isspace(*filename)) filename += 1;
133         _filename = g_path_get_basename(filename);
135         gchar *filename_ext = g_strdup_printf("%s_tex", filename);
136         Inkscape::IO::dump_fopen_call(filename_ext, "K");
137         FILE *osf = Inkscape::IO::fopen_utf8name(filename_ext, "w+");
138         if (!osf) {
139             fprintf(stderr, "inkscape: fopen(%s): %s\n",
140                     filename_ext, strerror(errno));
141             return false;
142         }
143         _stream = osf;
144         g_free(filename_ext);
145     }
147     if (_stream) {
148         /* fixme: this is kinda icky */
149 #if !defined(_WIN32) && !defined(__WIN32__)
150         (void) signal(SIGPIPE, SIG_IGN);
151 #endif
152     }
154     fprintf(_stream, "%%%% Creator: Inkscape %s, www.inkscape.org\n", PACKAGE_STRING);
155     fprintf(_stream, "%%%% PDF/EPS/PS + LaTeX output extension by Johan Engelen, 2010\n");
156     fprintf(_stream, "%%%% Accompanies image file '%s' (pdf, eps, ps)\n", _filename);
157     fprintf(_stream, "%%%%\n");
158     /* flush this to test output stream as early as possible */
159     if (fflush(_stream)) {
160         if (ferror(_stream)) {
161             g_print("Error %d on LaTeX file output stream: %s\n", errno,
162                     g_strerror(errno));
163         }
164         g_print("Output to LaTeX file failed\n");
165         /* fixme: should use pclose() for pipes */
166         fclose(_stream);
167         _stream = NULL;
168         fflush(stdout);
169         return false;
170     }
172     writePreamble();
174     return true;
177 static char const preamble[] =
178 "%% To include the image in your LaTeX document, write\n"
179 "%%   \\input{<filename>.pdf_tex}\n"
180 "%%  instead of\n"
181 "%%   \\includegraphics{<filename>.pdf}\n"
182 "%% To scale the image, write\n"
183 "%%   \\def\\svgwidth{<desired width>}\n"
184 "%%   \\input{<filename>.pdf_tex}\n"
185 "%%  instead of\n"
186 "%%   \\includegraphics[width=<desired width>]{<filename>.pdf}\n"
187 "%%\n"
188 "%% Images with a different path to the parent latex file can\n"
189 "%% be accessed with the `import' package (which may need to be\n"
190 "%% installed) using\n"
191 "%%   \\usepackage{import}\n"
192 "%% in the preamble, and then including the image with\n"
193 "%%   \\import{<path to file>}{<filename>.pdf_tex}\n"
194 "%% Alternatively, one can specify\n"
195 "%%   \\graphicspath{{<path to file>/}}\n"
196 "%% \n"
197 "%% For more information, please see info/svg-inkscape on CTAN:\n"
198 "%%   http://tug.ctan.org/tex-archive/info/svg-inkscape\n"
199 "\n"
200 "\\begingroup\n"
201 "  \\makeatletter\n"
202 "  \\providecommand\\color[2][]{%\n"
203 "    \\errmessage{(Inkscape) Color is used for the text in Inkscape, but the package \'color.sty\' is not loaded}\n"
204 "    \\renewcommand\\color[2][]{}%\n"
205 "  }\n"
206 "  \\providecommand\\transparent[1]{%\n"
207 "    \\errmessage{(Inkscape) Transparency is used (non-zero) for the text in Inkscape, but the package \'transparent.sty\' is not loaded}\n"
208 "    \\renewcommand\\transparent[1]{}%\n"
209 "  }\n"
210 "  \\providecommand\\rotatebox[2]{#2}\n";
212 static char const postamble[] =
213 "  \\end{picture}%\n"
214 "\\endgroup\n";
216 void
217 LaTeXTextRenderer::writePreamble()
219     fprintf(_stream, "%s", preamble);
221 void
222 LaTeXTextRenderer::writePostamble()
224     fprintf(_stream, "%s", postamble);
227 void
228 LaTeXTextRenderer::sp_group_render(SPItem *item)
230     SPGroup *group = SP_GROUP(item);
232     GSList *l = g_slist_reverse(group->childList(false));
233     while (l) {
234         SPObject *o = SP_OBJECT (l->data);
235         if (SP_IS_ITEM(o)) {
236             renderItem (SP_ITEM (o));
237         }
238         l = g_slist_remove (l, o);
239     }
242 void
243 LaTeXTextRenderer::sp_use_render(SPItem *item)
245     bool translated = false;
246     SPUse *use = SP_USE(item);
248     if ((use->x._set && use->x.computed != 0) || (use->y._set && use->y.computed != 0)) {
249         Geom::Matrix tp(Geom::Translate(use->x.computed, use->y.computed));
250         push_transform(tp);
251         translated = true;
252     }
254     if (use->child && SP_IS_ITEM(use->child)) {
255         renderItem(SP_ITEM(use->child));
256     }
258     if (translated) {
259         pop_transform();
260     }
263 void
264 LaTeXTextRenderer::sp_text_render(SPItem *item)
266     SPText *textobj = SP_TEXT (item);
267     SPStyle *style = SP_OBJECT_STYLE (SP_OBJECT(item));
269     gchar *str = sp_te_get_string_multiline(item);
270     if (!str) {
271         return;
272     }
274     // get position and alignment
275     // Align vertically on the baseline of the font (retreived from the anchor point)
276     // Align horizontally on anchorpoint
277     gchar const *alignment = NULL;
278     switch (style->text_anchor.computed) {
279     case SP_CSS_TEXT_ANCHOR_START:
280         alignment = "[lb]";
281         break;
282     case SP_CSS_TEXT_ANCHOR_END:
283         alignment = "[rb]";
284         break;
285     case SP_CSS_TEXT_ANCHOR_MIDDLE:
286     default:
287         alignment = "[b]";
288         break;
289     }
290     Geom::Point anchor = textobj->attributes.firstXY() * transform();
291     Geom::Point pos(anchor);
293     // determine color and transparency (for now, use rgb color model as it is most native to Inkscape)
294     bool has_color = false; // if the item has no color set, don't force black color
295     bool has_transparency = false;
296     // TODO: how to handle ICC colors?
297     // give priority to fill color
298     guint32 rgba = 0;
299     float opacity = SP_SCALE24_TO_FLOAT(style->opacity.value);
300     if (style->fill.set && style->fill.isColor()) {
301         has_color = true;
302         rgba = style->fill.value.color.toRGBA32(1.);
303         opacity *= SP_SCALE24_TO_FLOAT(style->fill_opacity.value);
304     } else if (style->stroke.set && style->stroke.isColor()) {
305         has_color = true;
306         rgba = style->stroke.value.color.toRGBA32(1.);
307         opacity *= SP_SCALE24_TO_FLOAT(style->stroke_opacity.value);
308     }
309     if (opacity < 1.0) {
310         has_transparency = true;
311     }
313     // get rotation
314     Geom::Matrix i2doc = sp_item_i2doc_affine(item);
315     Geom::Matrix wotransl = i2doc.without_translation();
316     double degrees = -180/M_PI * Geom::atan2(wotransl.xAxis());
317     bool has_rotation = !Geom::are_near(degrees,0.);
319     // write to LaTeX
320     Inkscape::SVGOStringStream os;
321     os.setf(std::ios::fixed); // don't use scientific notation
323     os << "    \\put(" << pos[Geom::X] << "," << pos[Geom::Y] << "){";
324     if (has_color) {
325         os << "\\color[rgb]{" << SP_RGBA32_R_F(rgba) << "," << SP_RGBA32_G_F(rgba) << "," << SP_RGBA32_B_F(rgba) << "}";
326     }
327     if (_pdflatex && has_transparency) {
328         os << "\\transparent{" << opacity << "}";
329     }
330     if (has_rotation) {
331         os << "\\rotatebox{" << degrees << "}{";
332     }
333     os << "\\makebox(0,0)" << alignment << "{";
334     os << "\\smash{" << str << "}";  // smash the text, to be able to put the makebox coordinates at the baseline
335     if (has_rotation) {
336         os << "}"; // rotatebox end
337     }
338     os << "}"; //makebox end
339     os << "}%\n"; // put end
341     fprintf(_stream, "%s", os.str().c_str());
344 void
345 LaTeXTextRenderer::sp_flowtext_render(SPItem * item)
347 /*
348 Flowtext is possible by using a minipage! :)
349 Flowing in rectangle is possible, not in arb shape.
350 */
352     SPFlowtext *flowtext = SP_FLOWTEXT(item);
353     SPStyle *style = SP_OBJECT_STYLE (SP_OBJECT(item));
355     gchar *strtext = sp_te_get_string_multiline(item);
356     if (!strtext) {
357         return;
358     }
359     // replace carriage return with double slash
360     gchar ** splitstr = g_strsplit(strtext, "\n", -1);
361     gchar *str = g_strjoinv("\\\\ ", splitstr);
362     g_free(strtext);
363     g_strfreev(splitstr);
365     SPItem *frame_item = flowtext->get_frame(NULL);
366     if (!frame_item || !SP_IS_RECT(frame_item)) {
367         g_warning("LaTeX export: non-rectangular flowed text shapes are not supported, skipping text.");
368         return; // don't know how to handle non-rect frames yet. is quite uncommon for latex users i think
369     }
371     SPRect *frame = SP_RECT(frame_item);
372     Geom::Rect framebox = sp_rect_get_rect(frame) * transform();
374     // get position and alignment
375     // Align on topleft corner.
376     gchar const *alignment = "[lt]";
377     gchar const *justification = "";
378     switch (flowtext->layout.paragraphAlignment(flowtext->layout.begin())) {
379     case Inkscape::Text::Layout::LEFT:
380         justification = "\\raggedright ";
381         break;
382     case Inkscape::Text::Layout::RIGHT:
383         justification = "\\raggedleft ";
384         break;
385     case Inkscape::Text::Layout::CENTER:
386         justification = "\\centering ";
387     case Inkscape::Text::Layout::FULL:
388     default:
389         // no need to add LaTeX code for standard justified output :)
390         break;
391     }
392     Geom::Point pos(framebox.corner(3)); //topleft corner
394     // determine color and transparency (for now, use rgb color model as it is most native to Inkscape)
395     bool has_color = false; // if the item has no color set, don't force black color
396     bool has_transparency = false;
397     // TODO: how to handle ICC colors?
398     // give priority to fill color
399     guint32 rgba = 0;
400     float opacity = SP_SCALE24_TO_FLOAT(style->opacity.value);
401     if (style->fill.set && style->fill.isColor()) {
402         has_color = true;
403         rgba = style->fill.value.color.toRGBA32(1.);
404         opacity *= SP_SCALE24_TO_FLOAT(style->fill_opacity.value);
405     } else if (style->stroke.set && style->stroke.isColor()) {
406         has_color = true;
407         rgba = style->stroke.value.color.toRGBA32(1.);
408         opacity *= SP_SCALE24_TO_FLOAT(style->stroke_opacity.value);
409     }
410     if (opacity < 1.0) {
411         has_transparency = true;
412     }
414     // get rotation
415     Geom::Matrix i2doc = sp_item_i2doc_affine(item);
416     Geom::Matrix wotransl = i2doc.without_translation();
417     double degrees = -180/M_PI * Geom::atan2(wotransl.xAxis());
418     bool has_rotation = !Geom::are_near(degrees,0.);
420     // write to LaTeX
421     Inkscape::SVGOStringStream os;
422     os.setf(std::ios::fixed); // don't use scientific notation
424     os << "    \\put(" << pos[Geom::X] << "," << pos[Geom::Y] << "){";
425     if (has_color) {
426         os << "\\color[rgb]{" << SP_RGBA32_R_F(rgba) << "," << SP_RGBA32_G_F(rgba) << "," << SP_RGBA32_B_F(rgba) << "}";
427     }
428     if (_pdflatex && has_transparency) {
429         os << "\\transparent{" << opacity << "}";
430     }
431     if (has_rotation) {
432         os << "\\rotatebox{" << degrees << "}{";
433     }
434     os << "\\makebox(0,0)" << alignment << "{";
435     os << "\\begin{minipage}{" << framebox.width() << "\\unitlength}";
436     os << justification;
437     os << str;
438     os << "\\end{minipage}";
439     if (has_rotation) {
440         os << "}"; // rotatebox end
441     }
442     os << "}"; //makebox end
443     os << "}%\n"; // put end
445     fprintf(_stream, "%s", os.str().c_str());
448 void
449 LaTeXTextRenderer::sp_root_render(SPItem *item)
451     SPRoot *root = SP_ROOT(item);
453     push_transform(root->c2p);
454     sp_group_render(item);
455     pop_transform();
458 void
459 LaTeXTextRenderer::sp_item_invoke_render(SPItem *item)
461     // Check item's visibility
462     if (item->isHidden()) {
463         return;
464     }
466     if (SP_IS_ROOT(item)) {
467         return sp_root_render(item);
468     } else if (SP_IS_GROUP(item)) {
469         return sp_group_render(item);
470     } else if (SP_IS_USE(item)) {
471         sp_use_render(item);
472     } else if (SP_IS_TEXT(item)) {
473         return sp_text_render(item);
474     } else if (SP_IS_FLOWTEXT(item)) {
475         return sp_flowtext_render(item);
476     }
477     // We are not interested in writing the other SPItem types to LaTeX
480 void
481 LaTeXTextRenderer::renderItem(SPItem *item)
483     push_transform(item->transform);
484     sp_item_invoke_render(item);
485     pop_transform();
488 bool
489 LaTeXTextRenderer::setupDocument(SPDocument *doc, bool pageBoundingBox, SPItem *base)
491 // The boundingbox calculation here should be exactly the same as the one by CairoRenderer::setupDocument !
493     if (!base)
494         base = SP_ITEM(sp_document_root(doc));
496     Geom::OptRect d;
497     if (pageBoundingBox) {
498         d = Geom::Rect( Geom::Point(0,0),
499                         Geom::Point(sp_document_width(doc), sp_document_height(doc)) );
500     } else {
501         sp_item_invoke_bbox(base, d, sp_item_i2d_affine(base), TRUE, SPItem::RENDERING_BBOX);
502     }
503     if (!d) {
504         g_message("LaTeXTextRenderer: could not retrieve boundingbox.");
505         return false;
506     }
508     // scale all coordinates, such that the width of the image is 1, this is convenient for scaling the image in LaTeX
509     double scale = 1/(d->width());
510     double _width = d->width() * scale;
511     double _height = d->height() * scale;
512     push_transform( Geom::Scale(scale, scale) );
514     if (!pageBoundingBox)
515     {
516         push_transform( Geom::Translate( - d->min() ) );
517     }
519     // flip y-axis
520     push_transform( Geom::Scale(1,-1) * Geom::Translate(0, sp_document_height(doc)) );
522     // write the info to LaTeX
523     Inkscape::SVGOStringStream os;
524     os.setf(std::ios::fixed); // no scientific notation
526     // scaling of the image when including it in LaTeX
528     os << "  \\ifx\\svgwidth\\undefined\n";
529     os << "    \\setlength{\\unitlength}{" << d->width() * PT_PER_PX << "pt}\n";
530     os << "  \\else\n";
531     os << "    \\setlength{\\unitlength}{\\svgwidth}\n";
532     os << "  \\fi\n";
533     os << "  \\global\\let\\svgwidth\\undefined\n";
534     os << "  \\makeatother\n";
536     os << "  \\begin{picture}(" << _width << "," << _height << ")%\n";
537     // strip pathname, as it is probably desired. Having a specific path in the TeX file is not convenient.
538     os << "    \\put(0,0){\\includegraphics[width=\\unitlength]{" << _filename << "}}%\n";
540     fprintf(_stream, "%s", os.str().c_str());
542     return true;
545 Geom::Matrix const &
546 LaTeXTextRenderer::transform()
548     return _transform_stack.top();
551 void
552 LaTeXTextRenderer::push_transform(Geom::Matrix const &tr)
554     if(_transform_stack.size()){
555         Geom::Matrix tr_top = _transform_stack.top();
556         _transform_stack.push(tr * tr_top);
557     } else {
558         _transform_stack.push(tr);
559     }
562 void
563 LaTeXTextRenderer::pop_transform()
565     _transform_stack.pop();
568 }  /* namespace Internal */
569 }  /* namespace Extension */
570 }  /* namespace Inkscape */
572 /*
573   Local Variables:
574   mode:c++
575   c-file-style:"stroustrup"
576   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
577   indent-tabs-mode:nil
578   fill-column:99
579   End:
580 */
581 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :