8d60f5fe01fd38b57a2a9c452b7491d835d2b977
1 /**
2 * OpenDocument <drawing> input and output
3 *
4 * This is an an entry in the extensions mechanism to begin to enable
5 * the inputting and outputting of OpenDocument Format (ODF) files from
6 * within Inkscape. Although the initial implementations will be very lossy
7 * do to the differences in the models of SVG and ODF, they will hopefully
8 * improve greatly with time.
9 *
10 * http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/idl-definitions.html
11 *
12 * Authors:
13 * Bob Jamison
14 *
15 * Copyright (C) 2006 Bob Jamison
16 *
17 * This library is free software; you can redistribute it and/or
18 * modify it under the terms of the GNU Lesser General Public
19 * License as published by the Free Software Foundation; either
20 * version 2.1 of the License, or (at your option) any later version.
21 *
22 * This library is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
25 * Lesser General Public License for more details.
26 *
27 * You should have received a copy of the GNU Lesser General Public
28 * License along with this library; if not, write to the Free Software
29 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
30 */
34 #ifdef HAVE_CONFIG_H
35 # include <config.h>
36 #endif
38 #include "odf.h"
40 //# System includes
41 #include <stdio.h>
42 #include <time.h>
43 #include <vector>
46 //# Inkscape includes
47 #include "clear-n_.h"
48 #include "inkscape.h"
49 #include <style.h>
50 #include "display/curve.h"
51 #include "libnr/n-art-bpath.h"
52 #include "extension/system.h"
54 #include "xml/repr.h"
55 #include "xml/attribute-record.h"
56 #include "sp-image.h"
57 #include "sp-gradient.h"
58 #include "sp-linear-gradient.h"
59 #include "sp-radial-gradient.h"
60 #include "sp-path.h"
61 #include "sp-text.h"
62 #include "sp-flowtext.h"
63 #include "svg/svg.h"
64 #include "text-editing.h"
67 //# DOM-specific includes
68 #include "dom/dom.h"
69 #include "dom/util/ziptool.h"
70 #include "dom/io/domstream.h"
71 #include "dom/io/bufferstream.h"
78 namespace Inkscape
79 {
80 namespace Extension
81 {
82 namespace Internal
83 {
87 //# Shorthand notation
88 typedef org::w3c::dom::DOMString DOMString;
89 typedef org::w3c::dom::io::OutputStreamWriter OutputStreamWriter;
90 typedef org::w3c::dom::io::BufferOutputStream BufferOutputStream;
92 //########################################################################
93 //# C L A S S SingularValueDecomposition
94 //########################################################################
95 #include <math.h>
97 class SVDMatrix
98 {
99 public:
101 SVDMatrix()
102 {
103 d = (double *)0;
104 rows = cols = size = 0;
105 }
107 SVDMatrix(unsigned int rowSize, unsigned int colSize)
108 {
109 rows = rowSize;
110 cols = colSize;
111 size = rows * cols;
112 d = new double[size];
113 for (unsigned int i=0 ; i<size ; i++)
114 d[i] = 0.0;
115 }
117 SVDMatrix(double *vals, unsigned int rowSize, unsigned int colSize)
118 {
119 rows = rowSize;
120 cols = colSize;
121 size = rows * cols;
122 d = new double[size];
123 for (unsigned int i=0 ; i<size ; i++)
124 d[i] = vals[i];
125 }
127 virtual ~SVDMatrix()
128 {
129 delete d;
130 }
132 SVDMatrix(const SVDMatrix &other)
133 {
134 assign(other);
135 }
137 SVDMatrix &operator=(const SVDMatrix &other)
138 {
139 assign(other);
140 return *this;
141 }
143 double& operator() (unsigned int row, unsigned int col)
144 {
145 if (row >= rows || col >= cols)
146 return badval;
147 return d[cols*row + col];
148 }
150 double operator() (unsigned int row, unsigned int col) const
151 {
152 if (row >= rows || col >= cols)
153 return badval;
154 return d[cols*row + col];
155 }
157 unsigned int getRows()
158 {
159 return rows;
160 }
162 unsigned int getCols()
163 {
164 return cols;
165 }
167 SVDMatrix multiply(const SVDMatrix &other)
168 {
169 if (cols != other.rows)
170 {
171 SVDMatrix dummy;
172 return dummy;
173 }
174 SVDMatrix result(rows, other.cols);
175 for (unsigned int i=0 ; i<rows ; i++)
176 {
177 for (unsigned int j=0 ; j<other.cols ; j++)
178 {
179 double sum = 0.0;
180 for (unsigned int k=0 ; k<cols ; k++)
181 {
182 //sum += a[i][k] * b[k][j];
183 sum += d[i*cols +k] * other(k, j);
184 }
185 result(i, j) = sum;
186 }
188 }
189 return result;
190 }
192 SVDMatrix transpose()
193 {
194 SVDMatrix result(cols, rows);
195 for (unsigned int i=0 ; i<rows ; i++)
196 for (unsigned int j=0 ; j<cols ; j++)
197 result(j, i) = d[i*cols + j];
198 return result;
199 }
201 private:
204 void assign(const SVDMatrix &other)
205 {
206 if (d)
207 delete d;
208 rows = other.rows;
209 cols = other.cols;
210 size = other.size;
211 d = new double[size];
212 for (unsigned int i=0 ; i<size ; i++)
213 d[i] = other.d[i];
214 }
216 double badval;
218 double *d;
219 unsigned int rows;
220 unsigned int cols;
221 unsigned int size;
222 };
224 /**
225 *
226 * ====================================================
227 *
228 * NOTE:
229 * This class is ported almost verbatim from the public domain
230 * JAMA Matrix package. It is modified to handle only 3x3 matrices
231 * and our NR::Matrix affine transform class. We give full
232 * attribution to them, along with many thanks. JAMA can be found at:
233 * http://math.nist.gov/javanumerics/jama
234 *
235 * ====================================================
236 *
237 * Singular Value Decomposition.
238 * <P>
239 * For an m-by-n matrix A with m >= n, the singular value decomposition is
240 * an m-by-n orthogonal matrix U, an n-by-n diagonal matrix S, and
241 * an n-by-n orthogonal matrix V so that A = U*S*V'.
242 * <P>
243 * The singular values, sigma[k] = S[k][k], are ordered so that
244 * sigma[0] >= sigma[1] >= ... >= sigma[n-1].
245 * <P>
246 * The singular value decompostion always exists, so the constructor will
247 * never fail. The matrix condition number and the effective numerical
248 * rank can be computed from this decomposition.
249 */
250 class SingularValueDecomposition
251 {
252 public:
254 /** Construct the singular value decomposition
255 @param A Rectangular matrix
256 @return Structure to access U, S and V.
257 */
259 SingularValueDecomposition (const SVDMatrix &mat)
260 {
261 A = mat;
262 calculate();
263 }
265 virtual ~SingularValueDecomposition()
266 {
267 delete s;
268 }
270 /**
271 * Return the left singular vectors
272 * @return U
273 */
274 SVDMatrix &getU();
276 /**
277 * Return the right singular vectors
278 * @return V
279 */
280 SVDMatrix &getV();
282 /**
283 * Return the s[index] value
284 */
285 double getS(unsigned int index);
287 /**
288 * Two norm
289 * @return max(S)
290 */
291 double norm2();
293 /**
294 * Two norm condition number
295 * @return max(S)/min(S)
296 */
297 double cond();
299 /**
300 * Effective numerical matrix rank
301 * @return Number of nonnegligible singular values.
302 */
303 int rank();
305 private:
307 void calculate();
309 SVDMatrix A;
310 SVDMatrix U;
311 double *s;
312 unsigned int s_size;
313 SVDMatrix V;
315 };
318 static double svd_hypot(double a, double b)
319 {
320 double r;
322 if (fabs(a) > fabs(b))
323 {
324 r = b/a;
325 r = fabs(a) * sqrt(1+r*r);
326 }
327 else if (b != 0)
328 {
329 r = a/b;
330 r = fabs(b) * sqrt(1+r*r);
331 }
332 else
333 {
334 r = 0.0;
335 }
336 return r;
337 }
341 void SingularValueDecomposition::calculate()
342 {
343 // Initialize.
344 int m = A.getRows();
345 int n = A.getCols();
347 int nu = (m > n) ? m : n;
348 s_size = (m+1 < n) ? m+1 : n;
349 s = new double[s_size];
350 U = SVDMatrix(m, nu);
351 V = SVDMatrix(n, n);
352 double *e = new double[n];
353 double *work = new double[m];
354 bool wantu = true;
355 bool wantv = true;
357 // Reduce A to bidiagonal form, storing the diagonal elements
358 // in s and the super-diagonal elements in e.
360 int nct = (m-1<n) ? m-1 : n;
361 int nrtx = (n-2<m) ? n-2 : m;
362 int nrt = (nrtx>0) ? nrtx : 0;
363 for (int k = 0; k < 2; k++) {
364 if (k < nct) {
366 // Compute the transformation for the k-th column and
367 // place the k-th diagonal in s[k].
368 // Compute 2-norm of k-th column without under/overflow.
369 s[k] = 0;
370 for (int i = k; i < m; i++) {
371 s[k] = svd_hypot(s[k],A(i, k));
372 }
373 if (s[k] != 0.0) {
374 if (A(k, k) < 0.0) {
375 s[k] = -s[k];
376 }
377 for (int i = k; i < m; i++) {
378 A(i, k) /= s[k];
379 }
380 A(k, k) += 1.0;
381 }
382 s[k] = -s[k];
383 }
384 for (int j = k+1; j < n; j++) {
385 if ((k < nct) & (s[k] != 0.0)) {
387 // Apply the transformation.
389 double t = 0;
390 for (int i = k; i < m; i++) {
391 t += A(i, k) * A(i, j);
392 }
393 t = -t/A(k, k);
394 for (int i = k; i < m; i++) {
395 A(i, j) += t*A(i, k);
396 }
397 }
399 // Place the k-th row of A into e for the
400 // subsequent calculation of the row transformation.
402 e[j] = A(k, j);
403 }
404 if (wantu & (k < nct)) {
406 // Place the transformation in U for subsequent back
407 // multiplication.
409 for (int i = k; i < m; i++) {
410 U(i, k) = A(i, k);
411 }
412 }
413 if (k < nrt) {
415 // Compute the k-th row transformation and place the
416 // k-th super-diagonal in e[k].
417 // Compute 2-norm without under/overflow.
418 e[k] = 0;
419 for (int i = k+1; i < n; i++) {
420 e[k] = svd_hypot(e[k],e[i]);
421 }
422 if (e[k] != 0.0) {
423 if (e[k+1] < 0.0) {
424 e[k] = -e[k];
425 }
426 for (int i = k+1; i < n; i++) {
427 e[i] /= e[k];
428 }
429 e[k+1] += 1.0;
430 }
431 e[k] = -e[k];
432 if ((k+1 < m) & (e[k] != 0.0)) {
434 // Apply the transformation.
436 for (int i = k+1; i < m; i++) {
437 work[i] = 0.0;
438 }
439 for (int j = k+1; j < n; j++) {
440 for (int i = k+1; i < m; i++) {
441 work[i] += e[j]*A(i, j);
442 }
443 }
444 for (int j = k+1; j < n; j++) {
445 double t = -e[j]/e[k+1];
446 for (int i = k+1; i < m; i++) {
447 A(i, j) += t*work[i];
448 }
449 }
450 }
451 if (wantv) {
453 // Place the transformation in V for subsequent
454 // back multiplication.
456 for (int i = k+1; i < n; i++) {
457 V(i, k) = e[i];
458 }
459 }
460 }
461 }
463 // Set up the final bidiagonal matrix or order p.
465 int p = (n < m+1) ? n : m+1;
466 if (nct < n) {
467 s[nct] = A(nct, nct);
468 }
469 if (m < p) {
470 s[p-1] = 0.0;
471 }
472 if (nrt+1 < p) {
473 e[nrt] = A(nrt, p-1);
474 }
475 e[p-1] = 0.0;
477 // If required, generate U.
479 if (wantu) {
480 for (int j = nct; j < nu; j++) {
481 for (int i = 0; i < m; i++) {
482 U(i, j) = 0.0;
483 }
484 U(j, j) = 1.0;
485 }
486 for (int k = nct-1; k >= 0; k--) {
487 if (s[k] != 0.0) {
488 for (int j = k+1; j < nu; j++) {
489 double t = 0;
490 for (int i = k; i < m; i++) {
491 t += U(i, k)*U(i, j);
492 }
493 t = -t/U(k, k);
494 for (int i = k; i < m; i++) {
495 U(i, j) += t*U(i, k);
496 }
497 }
498 for (int i = k; i < m; i++ ) {
499 U(i, k) = -U(i, k);
500 }
501 U(k, k) = 1.0 + U(k, k);
502 for (int i = 0; i < k-1; i++) {
503 U(i, k) = 0.0;
504 }
505 } else {
506 for (int i = 0; i < m; i++) {
507 U(i, k) = 0.0;
508 }
509 U(k, k) = 1.0;
510 }
511 }
512 }
514 // If required, generate V.
516 if (wantv) {
517 for (int k = n-1; k >= 0; k--) {
518 if ((k < nrt) & (e[k] != 0.0)) {
519 for (int j = k+1; j < nu; j++) {
520 double t = 0;
521 for (int i = k+1; i < n; i++) {
522 t += V(i, k)*V(i, j);
523 }
524 t = -t/V(k+1, k);
525 for (int i = k+1; i < n; i++) {
526 V(i, j) += t*V(i, k);
527 }
528 }
529 }
530 for (int i = 0; i < n; i++) {
531 V(i, k) = 0.0;
532 }
533 V(k, k) = 1.0;
534 }
535 }
537 // Main iteration loop for the singular values.
539 int pp = p-1;
540 int iter = 0;
541 //double eps = pow(2.0,-52.0);
542 //double tiny = pow(2.0,-966.0);
543 //let's just calculate these now
544 //a double can be e ± 308.25, so this is safe
545 double eps = 2.22e-16;
546 double tiny = 1.6e-291;
547 while (p > 0) {
548 int k,kase;
550 // Here is where a test for too many iterations would go.
552 // This section of the program inspects for
553 // negligible elements in the s and e arrays. On
554 // completion the variables kase and k are set as follows.
556 // kase = 1 if s(p) and e[k-1] are negligible and k<p
557 // kase = 2 if s(k) is negligible and k<p
558 // kase = 3 if e[k-1] is negligible, k<p, and
559 // s(k), ..., s(p) are not negligible (qr step).
560 // kase = 4 if e(p-1) is negligible (convergence).
562 for (k = p-2; k >= -1; k--) {
563 if (k == -1) {
564 break;
565 }
566 if (fabs(e[k]) <=
567 tiny + eps*(fabs(s[k]) + fabs(s[k+1]))) {
568 e[k] = 0.0;
569 break;
570 }
571 }
572 if (k == p-2) {
573 kase = 4;
574 } else {
575 int ks;
576 for (ks = p-1; ks >= k; ks--) {
577 if (ks == k) {
578 break;
579 }
580 double t = (ks != p ? fabs(e[ks]) : 0.) +
581 (ks != k+1 ? fabs(e[ks-1]) : 0.);
582 if (fabs(s[ks]) <= tiny + eps*t) {
583 s[ks] = 0.0;
584 break;
585 }
586 }
587 if (ks == k) {
588 kase = 3;
589 } else if (ks == p-1) {
590 kase = 1;
591 } else {
592 kase = 2;
593 k = ks;
594 }
595 }
596 k++;
598 // Perform the task indicated by kase.
600 switch (kase) {
602 // Deflate negligible s(p).
604 case 1: {
605 double f = e[p-2];
606 e[p-2] = 0.0;
607 for (int j = p-2; j >= k; j--) {
608 double t = svd_hypot(s[j],f);
609 double cs = s[j]/t;
610 double sn = f/t;
611 s[j] = t;
612 if (j != k) {
613 f = -sn*e[j-1];
614 e[j-1] = cs*e[j-1];
615 }
616 if (wantv) {
617 for (int i = 0; i < n; i++) {
618 t = cs*V(i, j) + sn*V(i, p-1);
619 V(i, p-1) = -sn*V(i, j) + cs*V(i, p-1);
620 V(i, j) = t;
621 }
622 }
623 }
624 }
625 break;
627 // Split at negligible s(k).
629 case 2: {
630 double f = e[k-1];
631 e[k-1] = 0.0;
632 for (int j = k; j < p; j++) {
633 double t = svd_hypot(s[j],f);
634 double cs = s[j]/t;
635 double sn = f/t;
636 s[j] = t;
637 f = -sn*e[j];
638 e[j] = cs*e[j];
639 if (wantu) {
640 for (int i = 0; i < m; i++) {
641 t = cs*U(i, j) + sn*U(i, k-1);
642 U(i, k-1) = -sn*U(i, j) + cs*U(i, k-1);
643 U(i, j) = t;
644 }
645 }
646 }
647 }
648 break;
650 // Perform one qr step.
652 case 3: {
654 // Calculate the shift.
656 double scale = fabs(s[p-1]);
657 double d = fabs(s[p-2]);
658 if (d>scale) scale=d;
659 d = fabs(e[p-2]);
660 if (d>scale) scale=d;
661 d = fabs(s[k]);
662 if (d>scale) scale=d;
663 d = fabs(e[k]);
664 if (d>scale) scale=d;
665 double sp = s[p-1]/scale;
666 double spm1 = s[p-2]/scale;
667 double epm1 = e[p-2]/scale;
668 double sk = s[k]/scale;
669 double ek = e[k]/scale;
670 double b = ((spm1 + sp)*(spm1 - sp) + epm1*epm1)/2.0;
671 double c = (sp*epm1)*(sp*epm1);
672 double shift = 0.0;
673 if ((b != 0.0) | (c != 0.0)) {
674 shift = sqrt(b*b + c);
675 if (b < 0.0) {
676 shift = -shift;
677 }
678 shift = c/(b + shift);
679 }
680 double f = (sk + sp)*(sk - sp) + shift;
681 double g = sk*ek;
683 // Chase zeros.
685 for (int j = k; j < p-1; j++) {
686 double t = svd_hypot(f,g);
687 double cs = f/t;
688 double sn = g/t;
689 if (j != k) {
690 e[j-1] = t;
691 }
692 f = cs*s[j] + sn*e[j];
693 e[j] = cs*e[j] - sn*s[j];
694 g = sn*s[j+1];
695 s[j+1] = cs*s[j+1];
696 if (wantv) {
697 for (int i = 0; i < n; i++) {
698 t = cs*V(i, j) + sn*V(i, j+1);
699 V(i, j+1) = -sn*V(i, j) + cs*V(i, j+1);
700 V(i, j) = t;
701 }
702 }
703 t = svd_hypot(f,g);
704 cs = f/t;
705 sn = g/t;
706 s[j] = t;
707 f = cs*e[j] + sn*s[j+1];
708 s[j+1] = -sn*e[j] + cs*s[j+1];
709 g = sn*e[j+1];
710 e[j+1] = cs*e[j+1];
711 if (wantu && (j < m-1)) {
712 for (int i = 0; i < m; i++) {
713 t = cs*U(i, j) + sn*U(i, j+1);
714 U(i, j+1) = -sn*U(i, j) + cs*U(i, j+1);
715 U(i, j) = t;
716 }
717 }
718 }
719 e[p-2] = f;
720 iter = iter + 1;
721 }
722 break;
724 // Convergence.
726 case 4: {
728 // Make the singular values positive.
730 if (s[k] <= 0.0) {
731 s[k] = (s[k] < 0.0 ? -s[k] : 0.0);
732 if (wantv) {
733 for (int i = 0; i <= pp; i++) {
734 V(i, k) = -V(i, k);
735 }
736 }
737 }
739 // Order the singular values.
741 while (k < pp) {
742 if (s[k] >= s[k+1]) {
743 break;
744 }
745 double t = s[k];
746 s[k] = s[k+1];
747 s[k+1] = t;
748 if (wantv && (k < n-1)) {
749 for (int i = 0; i < n; i++) {
750 t = V(i, k+1); V(i, k+1) = V(i, k); V(i, k) = t;
751 }
752 }
753 if (wantu && (k < m-1)) {
754 for (int i = 0; i < m; i++) {
755 t = U(i, k+1); U(i, k+1) = U(i, k); U(i, k) = t;
756 }
757 }
758 k++;
759 }
760 iter = 0;
761 p--;
762 }
763 break;
764 }
765 }
767 delete e;
768 delete work;
770 }
774 /**
775 * Return the left singular vectors
776 * @return U
777 */
778 SVDMatrix &SingularValueDecomposition::getU()
779 {
780 return U;
781 }
783 /**
784 * Return the right singular vectors
785 * @return V
786 */
788 SVDMatrix &SingularValueDecomposition::getV()
789 {
790 return V;
791 }
793 /**
794 * Return the s[0] value
795 */
796 double SingularValueDecomposition::getS(unsigned int index)
797 {
798 if (index >= s_size)
799 return 0.0;
800 return s[index];
801 }
803 /**
804 * Two norm
805 * @return max(S)
806 */
807 double SingularValueDecomposition::norm2()
808 {
809 return s[0];
810 }
812 /**
813 * Two norm condition number
814 * @return max(S)/min(S)
815 */
817 double SingularValueDecomposition::cond()
818 {
819 return s[0]/s[2];
820 }
822 /**
823 * Effective numerical matrix rank
824 * @return Number of nonnegligible singular values.
825 */
826 int SingularValueDecomposition::rank()
827 {
828 double eps = pow(2.0,-52.0);
829 double tol = 3.0*s[0]*eps;
830 int r = 0;
831 for (int i = 0; i < 3; i++)
832 {
833 if (s[i] > tol)
834 r++;
835 }
836 return r;
837 }
839 //########################################################################
840 //# E N D C L A S S SingularValueDecomposition
841 //########################################################################
847 #define pi 3.14159
848 //#define pxToCm 0.0275
849 #define pxToCm 0.04
850 #define piToRad 0.0174532925
851 #define docHeightCm 22.86
854 //########################################################################
855 //# O U T P U T
856 //########################################################################
858 static std::string getAttribute( Inkscape::XML::Node *node, char *attrName)
859 {
860 std::string val;
861 char *valstr = (char *)node->attribute(attrName);
862 if (valstr)
863 val = (const char *)valstr;
864 return val;
865 }
868 static std::string getExtension(const std::string &fname)
869 {
870 std::string ext;
872 unsigned int pos = fname.rfind('.');
873 if (pos == fname.npos)
874 {
875 ext = "";
876 }
877 else
878 {
879 ext = fname.substr(pos);
880 }
881 return ext;
882 }
885 static std::string formatTransform(NR::Matrix &tf)
886 {
887 std::string str;
888 if (!tf.test_identity())
889 {
890 char buf[128];
891 snprintf(buf, 127, "matrix(%.3f %.3f %.3f %.3f %.3f %.3f)",
892 tf[0], tf[1], tf[2], tf[3], tf[4], tf[5]);
893 str = buf;
894 }
895 return str;
896 }
901 /**
902 * Get the general transform from SVG pixels to
903 * ODF cm
904 */
905 static NR::Matrix getODFTransform(const SPItem *item)
906 {
907 //### Get SVG-to-ODF transform
908 NR::Matrix tf;
909 tf = sp_item_i2d_affine(item);
910 //Flip Y into document coordinates
911 double doc_height = sp_document_height(SP_ACTIVE_DOCUMENT);
912 NR::Matrix doc2dt_tf = NR::Matrix(NR::scale(1.0, -1.0));
913 doc2dt_tf = doc2dt_tf * NR::Matrix(NR::translate(0, doc_height));
914 tf = tf * doc2dt_tf;
915 tf = tf * NR::Matrix(NR::scale(pxToCm));
916 return tf;
917 }
920 /**
921 * Get the bounding box of an item, as mapped onto
922 * an ODF document, in cm.
923 */
924 static NR::Rect getODFBoundingBox(const SPItem *item)
925 {
926 NR::Rect bbox = sp_item_bbox_desktop((SPItem *)item);
927 double doc_height = sp_document_height(SP_ACTIVE_DOCUMENT);
928 NR::Matrix doc2dt_tf = NR::Matrix(NR::scale(1.0, -1.0));
929 doc2dt_tf = doc2dt_tf * NR::Matrix(NR::translate(0, doc_height));
930 bbox = bbox * doc2dt_tf;
931 bbox = bbox * NR::Matrix(NR::scale(pxToCm));
932 return bbox;
933 }
937 /**
938 * Get the transform for an item, correcting for
939 * handedness reversal
940 */
941 static NR::Matrix getODFItemTransform(const SPItem *item)
942 {
943 NR::Matrix itemTransform = NR::Matrix(NR::scale(1, -1));
944 itemTransform = itemTransform * item->transform;
945 itemTransform = itemTransform * NR::Matrix(NR::scale(1, -1));
946 return itemTransform;
947 }
951 /**
952 * Get some fun facts from the transform
953 */
954 static void analyzeTransform(NR::Matrix &tf,
955 double &rotate, double &xskew, double &yskew,
956 double &xscale, double &yscale)
957 {
958 SVDMatrix mat(2, 2);
959 mat(0, 0) = tf[0];
960 mat(0, 1) = tf[1];
961 mat(1, 0) = tf[2];
962 mat(1, 1) = tf[3];
964 SingularValueDecomposition svd(mat);
966 SVDMatrix U = svd.getU();
967 SVDMatrix V = svd.getV();
968 SVDMatrix Vt = V.transpose();
969 SVDMatrix UVt = U.multiply(Vt);
970 double s0 = svd.getS(0);
971 double s1 = svd.getS(1);
972 xscale = s0;
973 yscale = s1;
974 //g_message("## s0:%.3f s1:%.3f", s0, s1);
975 //g_message("## u:%.3f %.3f %.3f %.3f", U(0,0), U(0,1), U(1,0), U(1,1));
976 //g_message("## v:%.3f %.3f %.3f %.3f", V(0,0), V(0,1), V(1,0), V(1,1));
977 //g_message("## vt:%.3f %.3f %.3f %.3f", Vt(0,0), Vt(0,1), Vt(1,0), Vt(1,1));
978 //g_message("## uvt:%.3f %.3f %.3f %.3f", UVt(0,0), UVt(0,1), UVt(1,0), UVt(1,1));
979 rotate = UVt(0,0);
980 }
985 /**
986 * Method descends into the repr tree, converting image and style info
987 * into forms compatible in ODF.
988 */
989 void
990 OdfOutput::preprocess(ZipFile &zf, Inkscape::XML::Node *node)
991 {
993 std::string nodeName = node->name();
994 std::string id = getAttribute(node, "id");
996 SPObject *reprobj = SP_ACTIVE_DOCUMENT->getObjectByRepr(node);
997 if (!reprobj)
998 return;
999 if (!SP_IS_ITEM(reprobj))
1000 {
1001 return;
1002 }
1003 SPItem *item = SP_ITEM(reprobj);
1004 //### Get SVG-to-ODF transform
1005 NR::Matrix tf = getODFTransform(item);
1008 if (nodeName == "image" || nodeName == "svg:image")
1009 {
1010 //g_message("image");
1011 std::string href = getAttribute(node, "xlink:href");
1012 if (href.size() > 0)
1013 {
1014 std::string oldName = href;
1015 std::string ext = getExtension(oldName);
1016 if (ext == ".jpeg")
1017 ext = ".jpg";
1018 if (imageTable.find(oldName) == imageTable.end())
1019 {
1020 char buf[64];
1021 snprintf(buf, 63, "Pictures/image%d%s",
1022 (int)imageTable.size(), ext.c_str());
1023 std::string newName = buf;
1024 imageTable[oldName] = newName;
1025 std::string comment = "old name was: ";
1026 comment.append(oldName);
1027 URI oldUri(oldName);
1028 //g_message("oldpath:%s", oldUri.getNativePath().c_str());
1029 //# if relative to the documentURI, get proper path
1030 URI resUri = documentUri.resolve(oldUri);
1031 DOMString pathName = resUri.getNativePath();
1032 //g_message("native path:%s", pathName.c_str());
1033 ZipEntry *ze = zf.addFile(pathName, comment);
1034 if (ze)
1035 {
1036 ze->setFileName(newName);
1037 }
1038 else
1039 {
1040 g_warning("Could not load image file '%s'", pathName.c_str());
1041 }
1042 }
1043 }
1044 }
1048 //###### Get style
1049 SPStyle *style = SP_OBJECT_STYLE(item);
1050 if (style && id.size()>0)
1051 {
1052 bool isGradient = false;
1054 StyleInfo si;
1055 //## FILL
1056 if (style->fill.type == SP_PAINT_TYPE_COLOR)
1057 {
1058 guint32 fillCol =
1059 sp_color_get_rgba32_ualpha(&style->fill.value.color, 0);
1060 char buf[16];
1061 int r = (fillCol >> 24) & 0xff;
1062 int g = (fillCol >> 16) & 0xff;
1063 int b = (fillCol >> 8) & 0xff;
1064 //g_message("## %s %lx", id.c_str(), (unsigned int)fillCol);
1065 snprintf(buf, 15, "#%02x%02x%02x", r, g, b);
1066 si.fillColor = buf;
1067 si.fill = "solid";
1068 double opacityPercent = 100.0 *
1069 (SP_SCALE24_TO_FLOAT(style->fill_opacity.value));
1070 snprintf(buf, 15, "%.3f%%", opacityPercent);
1071 si.fillOpacity = buf;
1072 }
1073 else if (style->fill.type == SP_PAINT_TYPE_PAINTSERVER)
1074 {
1075 //## Gradient. Look in writeStyle() below to see what info
1076 // we need to read into GradientInfo.
1077 if (!SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)))
1078 return;
1079 isGradient = true;
1080 GradientInfo gi;
1081 SPGradient *gradient = SP_GRADIENT(SP_STYLE_FILL_SERVER(style));
1082 if (SP_IS_LINEARGRADIENT(gradient))
1083 {
1084 gi.style = "linear";
1085 SPLinearGradient *linGrad = SP_LINEARGRADIENT(gradient);
1086 gi.x1 = linGrad->x1.value;
1087 gi.y1 = linGrad->y1.value;
1088 gi.x2 = linGrad->x2.value;
1089 gi.y2 = linGrad->y2.value;
1090 }
1091 else if (SP_IS_RADIALGRADIENT(gradient))
1092 {
1093 gi.style = "radial";
1094 SPRadialGradient *radGrad = SP_RADIALGRADIENT(gradient);
1095 gi.cx = radGrad->cx.computed * 100.0;//ODG cx is percentages
1096 gi.cy = radGrad->cy.computed * 100.0;
1097 }
1098 else
1099 {
1100 g_warning("not a supported gradient type");
1101 }
1103 //Look for existing identical style;
1104 bool gradientMatch = false;
1105 std::vector<GradientInfo>::iterator iter;
1106 for (iter=gradientTable.begin() ; iter!=gradientTable.end() ; iter++)
1107 {
1108 if (gi.equals(*iter))
1109 {
1110 //map to existing gradientTable entry
1111 std::string gradientName = iter->name;
1112 //g_message("found duplicate style:%s", gradientName.c_str());
1113 gradientLookupTable[id] = gradientName;
1114 gradientMatch = true;
1115 break;
1116 }
1117 }
1118 //None found, make a new pair or entries
1119 if (!gradientMatch)
1120 {
1121 char buf[16];
1122 snprintf(buf, 15, "gradient%d", (int)gradientTable.size());
1123 std::string gradientName = buf;
1124 gi.name = gradientName;
1125 gradientTable.push_back(gi);
1126 gradientLookupTable[id] = gradientName;
1127 }
1128 }
1130 //## STROKE
1131 if (style->stroke.type == SP_PAINT_TYPE_COLOR)
1132 {
1133 guint32 strokeCol =
1134 sp_color_get_rgba32_ualpha(&style->stroke.value.color, 0);
1135 char buf[16];
1136 int r = (strokeCol >> 24) & 0xff;
1137 int g = (strokeCol >> 16) & 0xff;
1138 int b = (strokeCol >> 8) & 0xff;
1139 snprintf(buf, 15, "#%02x%02x%02x", r, g, b);
1140 si.strokeColor = buf;
1141 snprintf(buf, 15, "%.3fpt", style->stroke_width.value);
1142 si.strokeWidth = buf;
1143 si.stroke = "solid";
1144 double opacityPercent = 100.0 *
1145 (SP_SCALE24_TO_FLOAT(style->stroke_opacity.value));
1146 snprintf(buf, 15, "%.3f%%", opacityPercent);
1147 si.strokeOpacity = buf;
1148 }
1150 if (!isGradient)
1151 {
1152 //Look for existing identical style;
1153 bool styleMatch = false;
1154 std::vector<StyleInfo>::iterator iter;
1155 for (iter=styleTable.begin() ; iter!=styleTable.end() ; iter++)
1156 {
1157 if (si.equals(*iter))
1158 {
1159 //map to existing styleTable entry
1160 std::string styleName = iter->name;
1161 //g_message("found duplicate style:%s", styleName.c_str());
1162 styleLookupTable[id] = styleName;
1163 styleMatch = true;
1164 break;
1165 }
1166 }
1167 //None found, make a new pair or entries
1168 if (!styleMatch)
1169 {
1170 char buf[16];
1171 snprintf(buf, 15, "style%d", (int)styleTable.size());
1172 std::string styleName = buf;
1173 si.name = styleName;
1174 styleTable.push_back(si);
1175 styleLookupTable[id] = styleName;
1176 }
1177 }
1178 }
1180 for (Inkscape::XML::Node *child = node->firstChild() ;
1181 child ; child = child->next())
1182 preprocess(zf, child);
1183 }
1187 bool OdfOutput::writeManifest(ZipFile &zf)
1188 {
1189 BufferOutputStream bouts;
1190 OutputStreamWriter outs(bouts);
1192 time_t tim;
1193 time(&tim);
1195 outs.printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1196 outs.printf("<!DOCTYPE manifest:manifest PUBLIC \"-//OpenOffice.org//DTD Manifest 1.0//EN\" \"Manifest.dtd\">\n");
1197 outs.printf("\n");
1198 outs.printf("\n");
1199 outs.printf("<!--\n");
1200 outs.printf("*************************************************************************\n");
1201 outs.printf(" file: manifest.xml\n");
1202 outs.printf(" Generated by Inkscape: %s", ctime(&tim)); //ctime has its own <cr>
1203 outs.printf(" http://www.inkscape.org\n");
1204 outs.printf("*************************************************************************\n");
1205 outs.printf("-->\n");
1206 outs.printf("\n");
1207 outs.printf("\n");
1208 outs.printf("<manifest:manifest xmlns:manifest=\"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0\">\n");
1209 outs.printf(" <manifest:file-entry manifest:media-type=\"application/vnd.oasis.opendocument.graphics\" manifest:full-path=\"/\"/>\n");
1210 outs.printf(" <manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"content.xml\"/>\n");
1211 outs.printf(" <manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"meta.xml\"/>\n");
1212 outs.printf(" <!--List our images here-->\n");
1213 std::map<std::string, std::string>::iterator iter;
1214 for (iter = imageTable.begin() ; iter!=imageTable.end() ; iter++)
1215 {
1216 std::string oldName = iter->first;
1217 std::string newName = iter->second;
1219 std::string ext = getExtension(oldName);
1220 if (ext == ".jpeg")
1221 ext = ".jpg";
1222 outs.printf(" <manifest:file-entry manifest:media-type=\"");
1223 if (ext == ".gif")
1224 outs.printf("image/gif");
1225 else if (ext == ".png")
1226 outs.printf("image/png");
1227 else if (ext == ".jpg")
1228 outs.printf("image/jpeg");
1229 outs.printf("\" manifest:full-path=\"");
1230 outs.printf((char *)newName.c_str());
1231 outs.printf("\"/>\n");
1232 }
1233 outs.printf("</manifest:manifest>\n");
1235 outs.close();
1237 //Make our entry
1238 ZipEntry *ze = zf.newEntry("META-INF/manifest.xml", "ODF file manifest");
1239 ze->setUncompressedData(bouts.getBuffer());
1240 ze->finish();
1242 return true;
1243 }
1246 bool OdfOutput::writeMeta(ZipFile &zf)
1247 {
1248 BufferOutputStream bouts;
1249 OutputStreamWriter outs(bouts);
1251 time_t tim;
1252 time(&tim);
1254 outs.printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1255 outs.printf("\n");
1256 outs.printf("\n");
1257 outs.printf("<!--\n");
1258 outs.printf("*************************************************************************\n");
1259 outs.printf(" file: meta.xml\n");
1260 outs.printf(" Generated by Inkscape: %s", ctime(&tim)); //ctime has its own <cr>
1261 outs.printf(" http://www.inkscape.org\n");
1262 outs.printf("*************************************************************************\n");
1263 outs.printf("-->\n");
1264 outs.printf("\n");
1265 outs.printf("\n");
1266 outs.printf("<office:document-meta\n");
1267 outs.printf("xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\"\n");
1268 outs.printf("xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n");
1269 outs.printf("xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n");
1270 outs.printf("xmlns:meta=\"urn:oasis:names:tc:opendocument:xmlns:meta:1.0\"\n");
1271 outs.printf("xmlns:presentation=\"urn:oasis:names:tc:opendocument:xmlns:presentation:1.0\"\n");
1272 outs.printf("xmlns:ooo=\"http://openoffice.org/2004/office\"\n");
1273 outs.printf("xmlns:smil=\"urn:oasis:names:tc:opendocument:xmlns:smil-compatible:1.0\"\n");
1274 outs.printf("xmlns:anim=\"urn:oasis:names:tc:opendocument:xmlns:animation:1.0\"\n");
1275 outs.printf("office:version=\"1.0\">\n");
1276 outs.printf("<office:meta>\n");
1277 outs.printf(" <meta:generator>Inkscape.org - 0.44</meta:generator>\n");
1278 outs.printf(" <meta:initial-creator>clark kent</meta:initial-creator>\n");
1279 outs.printf(" <meta:creation-date>2006-04-13T17:12:29</meta:creation-date>\n");
1280 outs.printf(" <dc:creator>clark kent</dc:creator>\n");
1281 outs.printf(" <dc:date>2006-04-13T17:13:20</dc:date>\n");
1282 outs.printf(" <dc:language>en-US</dc:language>\n");
1283 outs.printf(" <meta:editing-cycles>2</meta:editing-cycles>\n");
1284 outs.printf(" <meta:editing-duration>PT56S</meta:editing-duration>\n");
1285 outs.printf(" <meta:user-defined meta:name=\"Info 1\"/>\n");
1286 outs.printf(" <meta:user-defined meta:name=\"Info 2\"/>\n");
1287 outs.printf(" <meta:user-defined meta:name=\"Info 3\"/>\n");
1288 outs.printf(" <meta:user-defined meta:name=\"Info 4\"/>\n");
1289 outs.printf(" <meta:document-statistic meta:object-count=\"2\"/>\n");
1290 outs.printf("</office:meta>\n");
1291 outs.printf("</office:document-meta>\n");
1292 outs.printf("\n");
1293 outs.printf("\n");
1296 outs.close();
1298 //Make our entry
1299 ZipEntry *ze = zf.newEntry("meta.xml", "ODF info file");
1300 ze->setUncompressedData(bouts.getBuffer());
1301 ze->finish();
1303 return true;
1304 }
1307 bool OdfOutput::writeStyle(Writer &outs)
1308 {
1309 outs.printf("<office:automatic-styles>\n");
1310 outs.printf("<!-- ####### 'Standard' styles ####### -->\n");
1311 outs.printf("<style:style style:name=\"dp1\" style:family=\"drawing-page\"/>\n");
1312 outs.printf("<style:style style:name=\"gr1\" style:family=\"graphic\" style:parent-style-name=\"standard\">\n");
1313 outs.printf(" <style:graphic-properties draw:stroke=\"none\" draw:fill=\"none\"\n");
1314 outs.printf(" draw:textarea-horizontal-align=\"center\"\n");
1315 outs.printf(" draw:textarea-vertical-align=\"middle\" draw:color-mode=\"standard\"\n");
1316 outs.printf(" draw:luminance=\"0%\" draw:contrast=\"0%\" draw:gamma=\"100%\" draw:red=\"0%\"\n");
1317 outs.printf(" draw:green=\"0%\" draw:blue=\"0%\" fo:clip=\"rect(0cm 0cm 0cm 0cm)\"\n");
1318 outs.printf(" draw:image-opacity=\"100%\" style:mirror=\"none\"/>\n");
1319 outs.printf("</style:style>\n");
1320 outs.printf("<style:style style:name=\"P1\" style:family=\"paragraph\">\n");
1321 outs.printf(" <style:paragraph-properties fo:text-align=\"center\"/>\n");
1322 outs.printf("</style:style>\n");
1324 //## Dump our style table
1325 outs.printf("<!-- ####### Styles from Inkscape document ####### -->\n");
1326 std::vector<StyleInfo>::iterator iter;
1327 for (iter = styleTable.begin() ; iter != styleTable.end() ; iter++)
1328 {
1329 outs.printf("<style:style style:name=\"%s\"", iter->name.c_str());
1330 StyleInfo s(*iter);
1331 outs.printf(" style:family=\"graphic\" style:parent-style-name=\"standard\">\n");
1332 outs.printf(" <style:graphic-properties");
1333 outs.printf(" draw:fill=\"%s\" ", s.fill.c_str());
1334 if (s.fill != "none")
1335 {
1336 outs.printf(" draw:fill-color=\"%s\" ", s.fillColor.c_str());
1337 outs.printf(" draw:fill-opacity=\"%s\" ", s.fillOpacity.c_str());
1338 }
1339 outs.printf(" draw:stroke=\"%s\" ", s.stroke.c_str());
1340 if (s.stroke != "none")
1341 {
1342 outs.printf(" svg:stroke-width=\"%s\" ", s.strokeWidth.c_str());
1343 outs.printf(" svg:stroke-color=\"%s\" ", s.strokeColor.c_str());
1344 outs.printf(" svg:stroke-opacity=\"%s\" ", s.strokeOpacity.c_str());
1345 }
1346 outs.printf("/>\n");
1347 outs.printf("</style:style>\n");
1348 }
1350 //## Dump our gradient table
1351 outs.printf("\n");
1352 outs.printf("<!-- ####### Gradients from Inkscape document ####### -->\n");
1353 std::vector<GradientInfo>::iterator giter;
1354 for (giter = gradientTable.begin() ; giter != gradientTable.end() ; giter++)
1355 {
1356 GradientInfo gi(*giter);
1357 outs.printf("<draw:gradient draw:name=\"%s\" ", gi.name.c_str());
1358 outs.printf("draw:style=\"%s\" ", gi.style.c_str());
1359 if (gi.style == "linear")
1360 {
1361 /*
1362 ===================================================================
1363 LINEAR gradient. We need something that looks like this:
1364 <draw:gradient draw:name="Gradient_20_7"
1365 draw:display-name="Gradient 7"
1366 draw:style="linear"
1367 draw:start-color="#008080" draw:end-color="#993366"
1368 draw:start-intensity="100%" draw:end-intensity="100%"
1369 draw:angle="150" draw:border="0%"/>
1370 ===================================================================
1371 */
1372 outs.printf("draw:display-name=\"linear borderless\" ");
1373 }
1374 else if (gi.style == "radial")
1375 {
1376 /*
1377 ===================================================================
1378 RADIAL gradient. We need something that looks like this:
1379 <!-- radial gradient, light gray to white, centered, 0% border -->
1380 <draw:gradient draw:name="radial_20_borderless"
1381 draw:display-name="radial borderless"
1382 draw:style="radial"
1383 draw:cx="50%" draw:cy="50%"
1384 draw:start-color="#999999" draw:end-color="#ffffff"
1385 draw:border="0%"/>
1386 ===================================================================
1387 */
1388 outs.printf("draw:display-name=\"radial borderless\" ");
1389 outs.printf("draw:cx=\".2f%%\" draw:cy=\".2f%%\" ", gi.cx, gi.cy);
1390 }
1391 else
1392 {
1393 g_warning("unsupported gradient style '%s'", gi.style.c_str());
1394 }
1395 outs.printf("/>\n");
1396 }
1398 outs.printf("\n");
1399 outs.printf("</office:automatic-styles>\n");
1400 outs.printf("\n");
1402 return true;
1403 }
1407 /**
1408 * Writes an SVG path as an ODF <draw:path>
1409 */
1410 static void
1411 writePath(Writer &outs, NArtBpath const *bpath,
1412 NR::Matrix &tf, double xoff, double yoff)
1413 {
1414 bool closed = false;
1415 NArtBpath *bp = (NArtBpath *)bpath;
1416 for ( ; bp->code != NR_END; bp++)
1417 {
1418 NR::Point const p1(bp->c(1) * tf);
1419 NR::Point const p2(bp->c(2) * tf);
1420 NR::Point const p3(bp->c(3) * tf);
1421 double x1 = (p1[NR::X] - xoff) * 1000.0;
1422 double y1 = (p1[NR::Y] - yoff) * 1000.0;
1423 double x2 = (p2[NR::X] - xoff) * 1000.0;
1424 double y2 = (p2[NR::Y] - yoff) * 1000.0;
1425 double x3 = (p3[NR::X] - xoff) * 1000.0;
1426 double y3 = (p3[NR::Y] - yoff) * 1000.0;
1428 switch (bp->code)
1429 {
1430 case NR_LINETO:
1431 outs.printf("L %.3f,%.3f ", x3 , y3);
1432 break;
1434 case NR_CURVETO:
1435 outs.printf("C %.3f,%.3f %.3f,%.3f %.3f,%.3f ",
1436 x1, y1, x2, y2, x3, y3);
1437 break;
1439 case NR_MOVETO_OPEN:
1440 case NR_MOVETO:
1441 if (closed)
1442 outs.printf("z ");
1443 closed = ( bp->code == NR_MOVETO );
1444 outs.printf("M %.3f,%.3f ", x3 , y3);
1445 break;
1447 default:
1448 break;
1450 }
1452 }
1454 if (closed)
1455 outs.printf("z");;
1457 }
1461 /**
1462 * This is the main SPObject tree output to ODF. preprocess()
1463 * must be called prior to this
1464 */
1465 bool OdfOutput::writeTree(Writer &outs, Inkscape::XML::Node *node)
1466 {
1467 //# Get the SPItem, if applicable
1468 SPObject *reprobj = SP_ACTIVE_DOCUMENT->getObjectByRepr(node);
1469 if (!reprobj)
1470 return true;
1471 if (!SP_IS_ITEM(reprobj))
1472 {
1473 return true;
1474 }
1475 SPItem *item = SP_ITEM(reprobj);
1478 std::string nodeName = node->name();
1479 std::string id = getAttribute(node, "id");
1481 //### Get SVG-to-ODF transform
1482 NR::Matrix tf = getODFTransform(item);
1484 //### Get ODF bounding box params for item
1485 NR::Rect bbox = getODFBoundingBox(item);
1486 double bbox_x = bbox.min()[NR::X];
1487 double bbox_y = bbox.min()[NR::Y];
1488 double bbox_width = bbox.max()[NR::X] - bbox.min()[NR::X];
1489 double bbox_height = bbox.max()[NR::Y] - bbox.min()[NR::Y];
1491 double rotate;
1492 double xskew;
1493 double yskew;
1494 double xscale;
1495 double yscale;
1496 analyzeTransform(tf, rotate, xskew, yskew, xscale, yscale);
1498 //# Do our stuff
1499 SPCurve *curve = NULL;
1501 //g_message("##### %s #####", nodeName.c_str());
1503 if (nodeName == "svg" || nodeName == "svg:svg")
1504 {
1505 //# Iterate through the children
1506 for (Inkscape::XML::Node *child = node->firstChild() ; child ; child = child->next())
1507 {
1508 if (!writeTree(outs, child))
1509 return false;
1510 }
1511 return true;
1512 }
1513 else if (nodeName == "g" || nodeName == "svg:g")
1514 {
1515 if (id.size() > 0)
1516 outs.printf("<draw:g id=\"%s\">\n", id.c_str());
1517 else
1518 outs.printf("<draw:g>\n");
1519 //# Iterate through the children
1520 for (Inkscape::XML::Node *child = node->firstChild() ; child ; child = child->next())
1521 {
1522 if (!writeTree(outs, child))
1523 return false;
1524 }
1525 if (id.size() > 0)
1526 outs.printf("</draw:g> <!-- id=\"%s\" -->\n", id.c_str());
1527 else
1528 outs.printf("</draw:g>\n");
1529 return true;
1530 }
1531 else if (nodeName == "image" || nodeName == "svg:image")
1532 {
1533 if (!SP_IS_IMAGE(item))
1534 {
1535 g_warning("<image> is not an SPImage. Why? ;-)");
1536 return false;
1537 }
1539 SPImage *img = SP_IMAGE(item);
1540 double ix = img->x.value;
1541 double iy = img->y.value;
1542 double iwidth = img->width.value;
1543 double iheight = img->height.value;
1545 NR::Rect ibbox(NR::Point(ix, iy), NR::Point(ix+iwidth, iy+iheight));
1546 ibbox = ibbox * tf;
1547 ix = ibbox.min()[NR::X];
1548 iy = ibbox.min()[NR::Y];
1549 //iwidth = ibbox.max()[NR::X] - ibbox.min()[NR::X];
1550 //iheight = ibbox.max()[NR::Y] - ibbox.min()[NR::Y];
1551 iwidth = xscale * iwidth;
1552 iheight = yscale * iheight;
1554 NR::Matrix itemTransform = getODFItemTransform(item);
1556 std::string itemTransformString = formatTransform(itemTransform);
1558 std::string href = getAttribute(node, "xlink:href");
1559 std::map<std::string, std::string>::iterator iter = imageTable.find(href);
1560 if (iter == imageTable.end())
1561 {
1562 g_warning("image '%s' not in table", href.c_str());
1563 return false;
1564 }
1565 std::string newName = iter->second;
1567 outs.printf("<draw:frame ");
1568 if (id.size() > 0)
1569 outs.printf("id=\"%s\" ", id.c_str());
1570 outs.printf("draw:style-name=\"gr1\" draw:text-style-name=\"P1\" draw:layer=\"layout\" ");
1571 //no x or y. make them the translate transform, last one
1572 outs.printf("svg:width=\"%.3fcm\" svg:height=\"%.3fcm\" ",
1573 iwidth, iheight);
1574 if (itemTransformString.size() > 0)
1575 outs.printf("draw:transform=\"%s translate(%.3fcm, %.3fcm)\" ",
1576 itemTransformString.c_str(), ix, iy);
1578 outs.printf(">\n");
1579 outs.printf(" <draw:image xlink:href=\"%s\" xlink:type=\"simple\"\n",
1580 newName.c_str());
1581 outs.printf(" xlink:show=\"embed\" xlink:actuate=\"onLoad\">\n");
1582 outs.printf(" <text:p/>\n");
1583 outs.printf(" </draw:image>\n");
1584 outs.printf("</draw:frame>\n");
1585 return true;
1586 }
1587 else if (SP_IS_SHAPE(item))
1588 {
1589 //g_message("### %s is a shape", nodeName.c_str());
1590 curve = sp_shape_get_curve(SP_SHAPE(item));
1591 }
1592 else if (SP_IS_TEXT(item) || SP_IS_FLOWTEXT(item))
1593 {
1594 curve = te_get_layout(item)->convertToCurves();
1595 }
1597 if (curve)
1598 {
1599 //### Default <path> output
1601 outs.printf("<draw:path ");
1602 if (id.size()>0)
1603 outs.printf("id=\"%s\" ", id.c_str());
1605 std::map<std::string, std::string>::iterator siter;
1606 siter = styleLookupTable.find(id);
1607 if (siter != styleLookupTable.end())
1608 {
1609 std::string styleName = siter->second;
1610 outs.printf("draw:style-name=\"%s\" ", styleName.c_str());
1611 }
1613 std::map<std::string, std::string>::iterator giter;
1614 giter = gradientLookupTable.find(id);
1615 if (giter != gradientLookupTable.end())
1616 {
1617 std::string gradientName = giter->second;
1618 outs.printf("draw:fill-gradient-name=\"%s\" ",
1619 gradientName.c_str());
1620 }
1622 outs.printf("draw:layer=\"layout\" svg:x=\"%.3fcm\" svg:y=\"%.3fcm\" ",
1623 bbox_x, bbox_y);
1624 outs.printf("svg:width=\"%.3fcm\" svg:height=\"%.3fcm\" ",
1625 bbox_width, bbox_height);
1626 outs.printf("svg:viewBox=\"0.0 0.0 %.3f %.3f\"\n",
1627 bbox_width * 1000.0, bbox_height * 1000.0);
1629 outs.printf(" svg:d=\"");
1630 writePath(outs, curve->bpath, tf, bbox_x, bbox_y);
1631 outs.printf("\"");
1633 outs.printf(">\n");
1634 outs.printf("</draw:path>\n");
1637 sp_curve_unref(curve);
1638 }
1640 return true;
1641 }
1646 bool OdfOutput::writeContent(ZipFile &zf, Inkscape::XML::Node *node)
1647 {
1648 BufferOutputStream bouts;
1649 OutputStreamWriter outs(bouts);
1651 time_t tim;
1652 time(&tim);
1654 outs.printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1655 outs.printf("\n");
1656 outs.printf("\n");
1657 outs.printf("<!--\n");
1658 outs.printf("*************************************************************************\n");
1659 outs.printf(" file: content.xml\n");
1660 outs.printf(" Generated by Inkscape: %s", ctime(&tim)); //ctime has its own <cr>
1661 outs.printf(" http://www.inkscape.org\n");
1662 outs.printf("*************************************************************************\n");
1663 outs.printf("-->\n");
1664 outs.printf("\n");
1665 outs.printf("\n");
1666 outs.printf("<office:document-content\n");
1667 outs.printf(" xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\"\n");
1668 outs.printf(" xmlns:style=\"urn:oasis:names:tc:opendocument:xmlns:style:1.0\"\n");
1669 outs.printf(" xmlns:text=\"urn:oasis:names:tc:opendocument:xmlns:text:1.0\"\n");
1670 outs.printf(" xmlns:table=\"urn:oasis:names:tc:opendocument:xmlns:table:1.0\"\n");
1671 outs.printf(" xmlns:draw=\"urn:oasis:names:tc:opendocument:xmlns:drawing:1.0\"\n");
1672 outs.printf(" xmlns:fo=\"urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0\"\n");
1673 outs.printf(" xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n");
1674 outs.printf(" xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n");
1675 outs.printf(" xmlns:meta=\"urn:oasis:names:tc:opendocument:xmlns:meta:1.0\"\n");
1676 outs.printf(" xmlns:number=\"urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0\"\n");
1677 outs.printf(" xmlns:presentation=\"urn:oasis:names:tc:opendocument:xmlns:presentation:1.0\"\n");
1678 outs.printf(" xmlns:svg=\"urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0\"\n");
1679 outs.printf(" xmlns:chart=\"urn:oasis:names:tc:opendocument:xmlns:chart:1.0\"\n");
1680 outs.printf(" xmlns:dr3d=\"urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0\"\n");
1681 outs.printf(" xmlns:math=\"http://www.w3.org/1998/Math/MathML\"\n");
1682 outs.printf(" xmlns:form=\"urn:oasis:names:tc:opendocument:xmlns:form:1.0\"\n");
1683 outs.printf(" xmlns:script=\"urn:oasis:names:tc:opendocument:xmlns:script:1.0\"\n");
1684 outs.printf(" xmlns:ooo=\"http://openoffice.org/2004/office\"\n");
1685 outs.printf(" xmlns:ooow=\"http://openoffice.org/2004/writer\"\n");
1686 outs.printf(" xmlns:oooc=\"http://openoffice.org/2004/calc\"\n");
1687 outs.printf(" xmlns:dom=\"http://www.w3.org/2001/xml-events\"\n");
1688 outs.printf(" xmlns:xforms=\"http://www.w3.org/2002/xforms\"\n");
1689 outs.printf(" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n");
1690 outs.printf(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n");
1691 outs.printf(" xmlns:smil=\"urn:oasis:names:tc:opendocument:xmlns:smil-compatible:1.0\"\n");
1692 outs.printf(" xmlns:anim=\"urn:oasis:names:tc:opendocument:xmlns:animation:1.0\"\n");
1693 outs.printf(" office:version=\"1.0\">\n");
1694 outs.printf("\n");
1695 outs.printf("\n");
1696 outs.printf("<office:scripts/>\n");
1697 outs.printf("\n");
1698 outs.printf("\n");
1699 //AffineTransform trans = new AffineTransform();
1700 //trans.scale(12.0, 12.0);
1701 outs.printf("<!-- ######### CONVERSION FROM SVG STARTS ######## -->\n");
1702 outs.printf("<!--\n");
1703 outs.printf("*************************************************************************\n");
1704 outs.printf(" S T Y L E S\n");
1705 outs.printf(" Style entries have been pulled from the svg style and\n");
1706 outs.printf(" representation attributes in the SVG tree. The tree elements\n");
1707 outs.printf(" then refer to them by name, in the ODF manner\n");
1708 outs.printf("*************************************************************************\n");
1709 outs.printf("-->\n");
1710 outs.printf("\n");
1711 outs.printf("\n");
1713 if (!writeStyle(outs))
1714 {
1715 g_warning("Failed to write styles");
1716 return false;
1717 }
1719 outs.printf("\n");
1720 outs.printf("\n");
1721 outs.printf("\n");
1722 outs.printf("\n");
1723 outs.printf("<!--\n");
1724 outs.printf("*************************************************************************\n");
1725 outs.printf(" D R A W I N G\n");
1726 outs.printf(" This section is the heart of SVG-ODF conversion. We are\n");
1727 outs.printf(" starting with simple conversions, and will slowly evolve\n");
1728 outs.printf(" into a 'smarter' translation as time progresses. Any help\n");
1729 outs.printf(" in improving .odg export is welcome.\n");
1730 outs.printf("*************************************************************************\n");
1731 outs.printf("-->\n");
1732 outs.printf("\n");
1733 outs.printf("\n");
1734 outs.printf("<office:body>\n");
1735 outs.printf("<office:drawing>\n");
1736 outs.printf("<draw:page draw:name=\"page1\" draw:style-name=\"dp1\"\n");
1737 outs.printf(" draw:master-page-name=\"Default\">\n");
1738 outs.printf("\n");
1739 outs.printf("\n");
1741 if (!writeTree(outs, node))
1742 {
1743 g_warning("Failed to convert SVG tree");
1744 return false;
1745 }
1747 outs.printf("\n");
1748 outs.printf("\n");
1750 outs.printf("</draw:page>\n");
1751 outs.printf("</office:drawing>\n");
1753 outs.printf("\n");
1754 outs.printf("\n");
1755 outs.printf("<!-- ######### CONVERSION FROM SVG ENDS ######## -->\n");
1756 outs.printf("\n");
1757 outs.printf("\n");
1759 outs.printf("</office:body>\n");
1760 outs.printf("</office:document-content>\n");
1761 outs.printf("\n");
1762 outs.printf("\n");
1763 outs.printf("\n");
1764 outs.printf("<!--\n");
1765 outs.printf("*************************************************************************\n");
1766 outs.printf(" E N D O F F I L E\n");
1767 outs.printf(" Have a nice day - ishmal\n");
1768 outs.printf("*************************************************************************\n");
1769 outs.printf("-->\n");
1770 outs.printf("\n");
1771 outs.printf("\n");
1775 //Make our entry
1776 ZipEntry *ze = zf.newEntry("content.xml", "ODF master content file");
1777 ze->setUncompressedData(bouts.getBuffer());
1778 ze->finish();
1780 return true;
1781 }
1784 /**
1785 * Resets class to its pristine condition, ready to use again
1786 */
1787 void
1788 OdfOutput::reset()
1789 {
1790 styleTable.clear();
1791 styleLookupTable.clear();
1792 gradientTable.clear();
1793 gradientLookupTable.clear();
1794 imageTable.clear();
1797 }
1800 /**
1801 * Descends into the SVG tree, mapping things to ODF when appropriate
1802 */
1803 void
1804 OdfOutput::save(Inkscape::Extension::Output *mod, SPDocument *doc, gchar const *uri)
1805 {
1806 reset();
1808 //g_message("native file:%s\n", uri);
1809 documentUri = URI(uri);
1811 ZipFile zf;
1812 preprocess(zf, doc->rroot);
1814 if (!writeManifest(zf))
1815 {
1816 g_warning("Failed to write manifest");
1817 return;
1818 }
1820 if (!writeMeta(zf))
1821 {
1822 g_warning("Failed to write metafile");
1823 return;
1824 }
1826 if (!writeContent(zf, doc->rroot))
1827 {
1828 g_warning("Failed to write content");
1829 return;
1830 }
1832 if (!zf.writeFile(uri))
1833 {
1834 return;
1835 }
1836 }
1839 /**
1840 * This is the definition of PovRay output. This function just
1841 * calls the extension system with the memory allocated XML that
1842 * describes the data.
1843 */
1844 void
1845 OdfOutput::init()
1846 {
1847 Inkscape::Extension::build_from_mem(
1848 "<inkscape-extension>\n"
1849 "<name>" N_("OpenDocument Drawing Output") "</name>\n"
1850 "<id>org.inkscape.output.odf</id>\n"
1851 "<output>\n"
1852 "<extension>.odg</extension>\n"
1853 "<mimetype>text/x-povray-script</mimetype>\n"
1854 "<filetypename>" N_("OpenDocument drawing (*.odg)") "</filetypename>\n"
1855 "<filetypetooltip>" N_("OpenDocument drawing file") "</filetypetooltip>\n"
1856 "</output>\n"
1857 "</inkscape-extension>",
1858 new OdfOutput());
1859 }
1861 /**
1862 * Make sure that we are in the database
1863 */
1864 bool
1865 OdfOutput::check (Inkscape::Extension::Extension *module)
1866 {
1867 /* We don't need a Key
1868 if (NULL == Inkscape::Extension::db.get(SP_MODULE_KEY_OUTPUT_POV))
1869 return FALSE;
1870 */
1872 return TRUE;
1873 }
1877 //########################################################################
1878 //# I N P U T
1879 //########################################################################
1883 //#######################
1884 //# L A T E R !!! :-)
1885 //#######################
1899 } //namespace Internal
1900 } //namespace Extension
1901 } //namespace Inkscape
1904 //########################################################################
1905 //# E N D O F F I L E
1906 //########################################################################
1908 /*
1909 Local Variables:
1910 mode:c++
1911 c-file-style:"stroustrup"
1912 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1913 indent-tabs-mode:nil
1914 fill-column:99
1915 End:
1916 */
1917 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :