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 /*
227 bool translated = false;
228 SPUse *use = SP_USE(item);
230 if ((use->x._set && use->x.computed != 0) || (use->y._set && use->y.computed != 0)) {
231 Geom::Matrix tp(Geom::Translate(use->x.computed, use->y.computed));
232 push_transform(tp);
233 translated = true;
234 }
236 if (use->child && SP_IS_ITEM(use->child)) {
237 renderItem(SP_ITEM(use->child));
238 }
240 if (translated) {
241 pop_transform();
242 }
243 */
244 }
246 void
247 LaTeXTextRenderer::sp_text_render(SPItem *item)
248 {
249 SPText *textobj = SP_TEXT (item);
251 gchar *str = sp_te_get_string_multiline(item);
253 // get position and alignment
254 Geom::Point pos;
255 gchar *alignment = NULL;
256 Geom::OptRect bbox = item->getBounds(transform());
257 Geom::Interval bbox_x = (*bbox)[Geom::X];
258 Geom::Interval bbox_y = (*bbox)[Geom::Y];
259 SPStyle *style = SP_OBJECT_STYLE (SP_OBJECT(item));
260 switch (style->text_anchor.computed) {
261 case SP_CSS_TEXT_ANCHOR_START:
262 pos = Geom::Point( bbox_x.min() , bbox_y.middle() );
263 alignment = "[l]";
264 break;
265 case SP_CSS_TEXT_ANCHOR_END:
266 pos = Geom::Point( bbox_x.max() , bbox_y.middle() );
267 alignment = "[r]";
268 break;
269 case SP_CSS_TEXT_ANCHOR_MIDDLE:
270 default:
271 pos = bbox->midpoint();
272 alignment = "";
273 break;
274 }
276 // get rotation
277 Geom::Matrix i2doc = sp_item_i2doc_affine(item);
278 Geom::Matrix wotransl = i2doc.without_translation();
279 double degrees = -180/M_PI * Geom::atan2(wotransl.xAxis());
280 bool has_rotation = !Geom::are_near(degrees,0.);
282 // write to LaTeX
283 Inkscape::SVGOStringStream os;
285 os << " \\put(" << pos[Geom::X] << "," << pos[Geom::Y] << "){";
286 os << "\\makebox(0,0)" << alignment << "{";
287 if (has_rotation) {
288 os << "\\rotatebox{" << degrees << "}{";
289 }
290 os << str;
291 if (has_rotation) {
292 os << "}"; // rotatebox end
293 }
294 os << "}"; //makebox end
295 os << "}%\n"; // put end
297 fprintf(_stream, "%s", os.str().c_str());
298 }
300 void
301 LaTeXTextRenderer::sp_flowtext_render(SPItem *item)
302 {
303 /* SPFlowtext *group = SP_FLOWTEXT(item);
305 // write to LaTeX
306 Inkscape::SVGOStringStream os;
308 os << " \\begin{picture}(" << _width << "," << _height << ")%%\n";
309 os << " \\gplgaddtomacro\\gplbacktext{%%\n";
310 os << " \\csname LTb\\endcsname%%\n";
311 os << "\\put(0,0){\\makebox(0,0)[lb]{\\strut{}Position}}%%\n";
313 fprintf(_stream, "%s", os.str().c_str());
314 */
315 }
317 void
318 LaTeXTextRenderer::sp_root_render(SPItem *item)
319 {
320 SPRoot *root = SP_ROOT(item);
322 push_transform(root->c2p);
323 sp_group_render(item);
324 pop_transform();
325 }
327 void
328 LaTeXTextRenderer::sp_item_invoke_render(SPItem *item)
329 {
330 // Check item's visibility
331 if (item->isHidden()) {
332 return;
333 }
335 if (SP_IS_ROOT(item)) {
336 return sp_root_render(item);
337 } else if (SP_IS_GROUP(item)) {
338 return sp_group_render(item);
339 } else if (SP_IS_USE(item)) {
340 sp_use_render(item);
341 } else if (SP_IS_TEXT(item)) {
342 return sp_text_render(item);
343 } else if (SP_IS_FLOWTEXT(item)) {
344 return sp_flowtext_render(item);
345 }
346 // We are not interested in writing the other SPItem types to LaTeX
347 }
349 void
350 LaTeXTextRenderer::renderItem(SPItem *item)
351 {
352 push_transform(item->transform);
353 sp_item_invoke_render(item);
354 pop_transform();
355 }
357 bool
358 LaTeXTextRenderer::setupDocument(SPDocument *doc, bool pageBoundingBox, SPItem *base)
359 {
360 // The boundingbox calculation here should be exactly the same as the one by CairoRenderer::setupDocument !
362 if (!base)
363 base = SP_ITEM(sp_document_root(doc));
365 Geom::OptRect d;
366 if (pageBoundingBox) {
367 d = Geom::Rect( Geom::Point(0,0),
368 Geom::Point(sp_document_width(doc), sp_document_height(doc)) );
369 } else {
370 sp_item_invoke_bbox(base, d, sp_item_i2d_affine(base), TRUE, SPItem::RENDERING_BBOX);
371 }
373 // scale all coordinates, such that the width of the image is 1, this is convenient for scaling the image in LaTeX
374 double scale = 1/(d->width());
375 double _width = d->width() * scale;
376 double _height = d->height() * scale;
377 push_transform( Geom::Scale(scale, scale) );
379 if (!pageBoundingBox)
380 {
381 double high = sp_document_height(doc);
383 push_transform( Geom::Translate( - d->min() ) );
384 }
386 // flip y-axis
387 push_transform( Geom::Scale(1,-1) * Geom::Translate(0, sp_document_height(doc)) );
389 // write the info to LaTeX
390 Inkscape::SVGOStringStream os;
392 os << " \\begin{picture}(" << _width << "," << _height << ")%\n";
393 // strip pathname, as it is probably desired. Having a specific path in the TeX file is not convenient.
394 os << " \\put(0,0){\\includegraphics[width=\\unitlength]{" << _filename << "}}%\n";
396 fprintf(_stream, "%s", os.str().c_str());
398 return true;
399 }
401 Geom::Matrix const &
402 LaTeXTextRenderer::transform()
403 {
404 return _transform_stack.top();
405 }
407 void
408 LaTeXTextRenderer::push_transform(Geom::Matrix const &tr)
409 {
410 if(_transform_stack.size()){
411 Geom::Matrix tr_top = _transform_stack.top();
412 _transform_stack.push(tr * tr_top);
413 } else {
414 _transform_stack.push(tr);
415 }
416 }
418 void
419 LaTeXTextRenderer::pop_transform()
420 {
421 _transform_stack.pop();
422 }
424 } /* namespace Internal */
425 } /* namespace Extension */
426 } /* namespace Inkscape */
428 /*
429 Local Variables:
430 mode:c++
431 c-file-style:"stroustrup"
432 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
433 indent-tabs-mode:nil
434 fill-column:99
435 End:
436 */
437 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :