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 "text-editing.h"
41 #include <unit-constants.h>
43 #include "extension/system.h"
45 #include "io/sys.h"
47 namespace Inkscape {
48 namespace Extension {
49 namespace Internal {
51 /**
52 * This method is called by the PDF, EPS and PS output extensions.
53 * @param filename This should be the filename without extension to which the tex code should be written. Output goes to <filename>.tex.
54 */
55 bool
56 latex_render_document_text_to_file( SPDocument *doc, gchar const *filename,
57 const gchar * const exportId, bool exportDrawing, bool exportCanvas)
58 {
59 sp_document_ensure_up_to_date(doc);
61 SPItem *base = NULL;
63 bool pageBoundingBox = true;
64 if (exportId && strcmp(exportId, "")) {
65 // we want to export the given item only
66 base = SP_ITEM(doc->getObjectById(exportId));
67 pageBoundingBox = exportCanvas;
68 }
69 else {
70 // we want to export the entire document from root
71 base = SP_ITEM(sp_document_root(doc));
72 pageBoundingBox = !exportDrawing;
73 }
75 if (!base)
76 return false;
78 /* Create renderer */
79 LaTeXTextRenderer *renderer = new LaTeXTextRenderer();
81 bool ret = renderer->setTargetFile(filename);
82 if (ret) {
83 /* Render document */
84 bool ret = renderer->setupDocument(doc, pageBoundingBox, base);
85 if (ret) {
86 renderer->renderItem(base);
87 }
88 }
90 delete renderer;
92 return ret;
93 }
95 LaTeXTextRenderer::LaTeXTextRenderer(void)
96 : _stream(NULL),
97 _filename(NULL)
98 {
99 push_transform(Geom::identity());
100 }
102 LaTeXTextRenderer::~LaTeXTextRenderer(void)
103 {
104 if (_stream) {
105 writePostamble();
107 fclose(_stream);
108 }
110 /* restore default signal handling for SIGPIPE */
111 #if !defined(_WIN32) && !defined(__WIN32__)
112 (void) signal(SIGPIPE, SIG_DFL);
113 #endif
115 if (_filename) {
116 g_free(_filename);
117 }
119 return;
120 }
122 /** This should create the output LaTeX file, and assign it to _stream.
123 * @return Returns true when succesfull
124 */
125 bool
126 LaTeXTextRenderer::setTargetFile(gchar const *filename) {
127 if (filename != NULL) {
128 while (isspace(*filename)) filename += 1;
130 _filename = g_path_get_basename(filename);
132 gchar *filename_ext = g_strdup_printf("%s.tex", filename);
133 Inkscape::IO::dump_fopen_call(filename_ext, "K");
134 FILE *osf = Inkscape::IO::fopen_utf8name(filename_ext, "w+");
135 if (!osf) {
136 fprintf(stderr, "inkscape: fopen(%s): %s\n",
137 filename_ext, strerror(errno));
138 return false;
139 }
140 _stream = osf;
141 g_free(filename_ext);
142 }
144 if (_stream) {
145 /* fixme: this is kinda icky */
146 #if !defined(_WIN32) && !defined(__WIN32__)
147 (void) signal(SIGPIPE, SIG_IGN);
148 #endif
149 }
151 fprintf(_stream, "%%%% Creator: Inkscape %s, www.inkscape.org\n", PACKAGE_STRING);
152 fprintf(_stream, "%%%% PDF/EPS/PS + LaTeX output extension by Johan Engelen, 2010\n");
153 fprintf(_stream, "%%%% Accompanies image file '%s' (pdf, eps, ps)\n", _filename);
154 fprintf(_stream, "%%%%");
155 /* flush this to test output stream as early as possible */
156 if (fflush(_stream)) {
157 if (ferror(_stream)) {
158 g_print("Error %d on LaTeX file output stream: %s\n", errno,
159 g_strerror(errno));
160 }
161 g_print("Output to LaTeX file failed\n");
162 /* fixme: should use pclose() for pipes */
163 fclose(_stream);
164 _stream = NULL;
165 fflush(stdout);
166 return false;
167 }
169 writePreamble();
171 return true;
172 }
174 static char const preamble[] =
175 "%% To include the image in your LaTeX document, write\n"
176 "%% \\setlength{\\unitlength}{<desired width>}\n"
177 "%% \\input{<filename>.tex}\n"
178 "%% instead of\n"
179 "%% \\includegraphics[width=<desired width>]{<filename>.pdf}\n"
180 "\n"
181 "\\begingroup \n"
182 " \\makeatletter \n"
183 " \\providecommand\\color[2][]{% \n"
184 " \\GenericError{(Inkscape) \\space\\space\\@spaces}{% \n"
185 " Color is used for the text in Inkscape, but the color package color is not loaded. \n"
186 " }{Either use black text in Inkscape or load the package \n"
187 " color.sty in LaTeX.}% \n"
188 " \\renewcommand\\color[2][]{}% \n"
189 " }%% \n"
190 " \\providecommand\\rotatebox[2]{#2}% \n"
191 " \\makeatother \n";
193 static char const postamble[] =
194 " \\end{picture}% \n"
195 "\\endgroup \n";
197 void
198 LaTeXTextRenderer::writePreamble()
199 {
200 fprintf(_stream, "%s", preamble);
201 }
202 void
203 LaTeXTextRenderer::writePostamble()
204 {
205 fprintf(_stream, "%s", postamble);
206 }
208 void
209 LaTeXTextRenderer::sp_group_render(SPItem *item)
210 {
211 SPGroup *group = SP_GROUP(item);
213 GSList *l = g_slist_reverse(group->childList(false));
214 while (l) {
215 SPObject *o = SP_OBJECT (l->data);
216 if (SP_IS_ITEM(o)) {
217 renderItem (SP_ITEM (o));
218 }
219 l = g_slist_remove (l, o);
220 }
221 }
223 void
224 LaTeXTextRenderer::sp_use_render(SPItem *item)
225 {
226 bool translated = false;
227 SPUse *use = SP_USE(item);
229 if ((use->x._set && use->x.computed != 0) || (use->y._set && use->y.computed != 0)) {
230 Geom::Matrix tp(Geom::Translate(use->x.computed, use->y.computed));
231 push_transform(tp);
232 translated = true;
233 }
235 if (use->child && SP_IS_ITEM(use->child)) {
236 renderItem(SP_ITEM(use->child));
237 }
239 if (translated) {
240 pop_transform();
241 }
242 }
244 void
245 LaTeXTextRenderer::sp_text_render(SPItem *item)
246 {
247 SPText *textobj = SP_TEXT (item);
248 SPStyle *style = SP_OBJECT_STYLE (SP_OBJECT(item));
250 gchar *str = sp_te_get_string_multiline(item);
252 // get position and alignment
253 Geom::Point pos;
254 gchar *alignment = NULL;
255 Geom::OptRect bbox = item->getBounds(transform());
256 Geom::Interval bbox_x = (*bbox)[Geom::X];
257 Geom::Interval bbox_y = (*bbox)[Geom::Y];
258 switch (style->text_anchor.computed) {
259 case SP_CSS_TEXT_ANCHOR_START:
260 pos = Geom::Point( bbox_x.min() , bbox_y.middle() );
261 alignment = "[l]";
262 break;
263 case SP_CSS_TEXT_ANCHOR_END:
264 pos = Geom::Point( bbox_x.max() , bbox_y.middle() );
265 alignment = "[r]";
266 break;
267 case SP_CSS_TEXT_ANCHOR_MIDDLE:
268 default:
269 pos = bbox->midpoint();
270 alignment = "";
271 break;
272 }
274 // determine color (for now, use rgb color model as it is most native to Inkscape)
275 bool has_color = false; // if the item has no color set, don't force black color
276 // TODO: how to handle ICC colors?
277 // give priority to fill color
278 guint32 rgba = 0;
279 if (style->fill.set && style->fill.isColor()) {
280 has_color = true;
281 rgba = style->fill.value.color.toRGBA32(1.);
282 } else if (style->stroke.set && style->stroke.isColor()) {
283 has_color = true;
284 rgba = style->stroke.value.color.toRGBA32(1.);
285 }
288 // get rotation
289 Geom::Matrix i2doc = sp_item_i2doc_affine(item);
290 Geom::Matrix wotransl = i2doc.without_translation();
291 double degrees = -180/M_PI * Geom::atan2(wotransl.xAxis());
292 bool has_rotation = !Geom::are_near(degrees,0.);
294 // write to LaTeX
295 Inkscape::SVGOStringStream os;
297 os << " \\put(" << pos[Geom::X] << "," << pos[Geom::Y] << "){";
298 if (has_color) {
299 os << "\\color[rgb]{" << SP_RGBA32_R_F(rgba) << "," << SP_RGBA32_G_F(rgba) << "," << SP_RGBA32_B_F(rgba) << "}";
300 }
301 os << "\\makebox(0,0)" << alignment << "{";
302 if (has_rotation) {
303 os << "\\rotatebox{" << degrees << "}{";
304 }
305 os << str;
306 if (has_rotation) {
307 os << "}"; // rotatebox end
308 }
309 os << "}"; //makebox end
310 os << "}%\n"; // put end
312 fprintf(_stream, "%s", os.str().c_str());
313 }
315 void
316 LaTeXTextRenderer::sp_flowtext_render(SPItem *item)
317 {
318 /* SPFlowtext *group = SP_FLOWTEXT(item);
320 // write to LaTeX
321 Inkscape::SVGOStringStream os;
323 os << " \\begin{picture}(" << _width << "," << _height << ")%%\n";
324 os << " \\gplgaddtomacro\\gplbacktext{%%\n";
325 os << " \\csname LTb\\endcsname%%\n";
326 os << "\\put(0,0){\\makebox(0,0)[lb]{\\strut{}Position}}%%\n";
328 fprintf(_stream, "%s", os.str().c_str());
329 */
330 }
332 void
333 LaTeXTextRenderer::sp_root_render(SPItem *item)
334 {
335 SPRoot *root = SP_ROOT(item);
337 push_transform(root->c2p);
338 sp_group_render(item);
339 pop_transform();
340 }
342 void
343 LaTeXTextRenderer::sp_item_invoke_render(SPItem *item)
344 {
345 // Check item's visibility
346 if (item->isHidden()) {
347 return;
348 }
350 if (SP_IS_ROOT(item)) {
351 return sp_root_render(item);
352 } else if (SP_IS_GROUP(item)) {
353 return sp_group_render(item);
354 } else if (SP_IS_USE(item)) {
355 sp_use_render(item);
356 } else if (SP_IS_TEXT(item)) {
357 return sp_text_render(item);
358 } else if (SP_IS_FLOWTEXT(item)) {
359 return sp_flowtext_render(item);
360 }
361 // We are not interested in writing the other SPItem types to LaTeX
362 }
364 void
365 LaTeXTextRenderer::renderItem(SPItem *item)
366 {
367 push_transform(item->transform);
368 sp_item_invoke_render(item);
369 pop_transform();
370 }
372 bool
373 LaTeXTextRenderer::setupDocument(SPDocument *doc, bool pageBoundingBox, SPItem *base)
374 {
375 // The boundingbox calculation here should be exactly the same as the one by CairoRenderer::setupDocument !
377 if (!base)
378 base = SP_ITEM(sp_document_root(doc));
380 Geom::OptRect d;
381 if (pageBoundingBox) {
382 d = Geom::Rect( Geom::Point(0,0),
383 Geom::Point(sp_document_width(doc), sp_document_height(doc)) );
384 } else {
385 sp_item_invoke_bbox(base, d, sp_item_i2d_affine(base), TRUE, SPItem::RENDERING_BBOX);
386 }
388 // scale all coordinates, such that the width of the image is 1, this is convenient for scaling the image in LaTeX
389 double scale = 1/(d->width());
390 double _width = d->width() * scale;
391 double _height = d->height() * scale;
392 push_transform( Geom::Scale(scale, scale) );
394 if (!pageBoundingBox)
395 {
396 double high = sp_document_height(doc);
398 push_transform( Geom::Translate( - d->min() ) );
399 }
401 // flip y-axis
402 push_transform( Geom::Scale(1,-1) * Geom::Translate(0, sp_document_height(doc)) );
404 // write the info to LaTeX
405 Inkscape::SVGOStringStream os;
407 // also write original width to LaTeX
408 // TODO: add \ifdef statements to be able to choose between specifying width or not to specify it!
409 os << " %\\setlength{\\unitlength}{" << d->width() * PT_PER_PX << "pt}\n";
411 os << " \\begin{picture}(" << _width << "," << _height << ")%\n";
412 // strip pathname, as it is probably desired. Having a specific path in the TeX file is not convenient.
413 os << " \\put(0,0){\\includegraphics[width=\\unitlength]{" << _filename << "}}%\n";
415 fprintf(_stream, "%s", os.str().c_str());
417 return true;
418 }
420 Geom::Matrix const &
421 LaTeXTextRenderer::transform()
422 {
423 return _transform_stack.top();
424 }
426 void
427 LaTeXTextRenderer::push_transform(Geom::Matrix const &tr)
428 {
429 if(_transform_stack.size()){
430 Geom::Matrix tr_top = _transform_stack.top();
431 _transform_stack.push(tr * tr_top);
432 } else {
433 _transform_stack.push(tr);
434 }
435 }
437 void
438 LaTeXTextRenderer::pop_transform()
439 {
440 _transform_stack.pop();
441 }
443 } /* namespace Internal */
444 } /* namespace Extension */
445 } /* namespace Inkscape */
447 /*
448 Local Variables:
449 mode:c++
450 c-file-style:"stroustrup"
451 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
452 indent-tabs-mode:nil
453 fill-column:99
454 End:
455 */
456 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :