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. People should consider this to be a framework
9 * that can be continously upgraded for ever improving fidelity. Potential
10 * developers should especially look in preprocess() and writeTree() to see how
11 * the SVG tree is scanned, read, translated, and then written to ODF.
12 *
13 * http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/idl-definitions.html
14 *
15 * Authors:
16 * Bob Jamison
17 *
18 * Copyright (C) 2006 Bob Jamison
19 *
20 * This library is free software; you can redistribute it and/or
21 * modify it under the terms of the GNU Lesser General Public
22 * License as published by the Free Software Foundation; either
23 * version 2.1 of the License, or (at your option) any later version.
24 *
25 * This library is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
28 * Lesser General Public License for more details.
29 *
30 * You should have received a copy of the GNU Lesser General Public
31 * License along with this library; if not, write to the Free Software
32 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
33 */
37 #ifdef HAVE_CONFIG_H
38 # include <config.h>
39 #endif
41 #include "odf.h"
43 //# System includes
44 #include <stdio.h>
45 #include <time.h>
46 #include <vector>
49 //# Inkscape includes
50 #include "clear-n_.h"
51 #include "inkscape.h"
52 #include <style.h>
53 #include "display/curve.h"
54 #include "libnr/n-art-bpath.h"
55 #include "extension/system.h"
57 #include "xml/repr.h"
58 #include "xml/attribute-record.h"
59 #include "sp-image.h"
60 #include "sp-gradient.h"
61 #include "sp-linear-gradient.h"
62 #include "sp-radial-gradient.h"
63 #include "sp-path.h"
64 #include "sp-text.h"
65 #include "sp-flowtext.h"
66 #include "svg/svg.h"
67 #include "text-editing.h"
70 //# DOM-specific includes
71 #include "dom/dom.h"
72 #include "dom/util/ziptool.h"
73 #include "dom/io/domstream.h"
74 #include "dom/io/bufferstream.h"
75 #include "dom/io/stringstream.h"
82 namespace Inkscape
83 {
84 namespace Extension
85 {
86 namespace Internal
87 {
91 //# Shorthand notation
92 typedef org::w3c::dom::DOMString DOMString;
93 typedef org::w3c::dom::XMLCh XMLCh;
94 typedef org::w3c::dom::io::OutputStreamWriter OutputStreamWriter;
95 typedef org::w3c::dom::io::BufferOutputStream BufferOutputStream;
96 typedef org::w3c::dom::io::StringOutputStream StringOutputStream;
98 //########################################################################
99 //# C L A S S SingularValueDecomposition
100 //########################################################################
101 #include <math.h>
103 class SVDMatrix
104 {
105 public:
107 SVDMatrix()
108 {
109 init();
110 }
112 SVDMatrix(unsigned int rowSize, unsigned int colSize)
113 {
114 init();
115 rows = rowSize;
116 cols = colSize;
117 size = rows * cols;
118 d = new double[size];
119 for (unsigned int i=0 ; i<size ; i++)
120 d[i] = 0.0;
121 }
123 SVDMatrix(double *vals, unsigned int rowSize, unsigned int colSize)
124 {
125 init();
126 rows = rowSize;
127 cols = colSize;
128 size = rows * cols;
129 d = new double[size];
130 for (unsigned int i=0 ; i<size ; i++)
131 d[i] = vals[i];
132 }
135 SVDMatrix(const SVDMatrix &other)
136 {
137 init();
138 assign(other);
139 }
141 SVDMatrix &operator=(const SVDMatrix &other)
142 {
143 assign(other);
144 return *this;
145 }
147 virtual ~SVDMatrix()
148 {
149 delete[] d;
150 }
152 double& operator() (unsigned int row, unsigned int col)
153 {
154 if (row >= rows || col >= cols)
155 return badval;
156 return d[cols*row + col];
157 }
159 double operator() (unsigned int row, unsigned int col) const
160 {
161 if (row >= rows || col >= cols)
162 return badval;
163 return d[cols*row + col];
164 }
166 unsigned int getRows()
167 {
168 return rows;
169 }
171 unsigned int getCols()
172 {
173 return cols;
174 }
176 SVDMatrix multiply(const SVDMatrix &other)
177 {
178 if (cols != other.rows)
179 {
180 SVDMatrix dummy;
181 return dummy;
182 }
183 SVDMatrix result(rows, other.cols);
184 for (unsigned int i=0 ; i<rows ; i++)
185 {
186 for (unsigned int j=0 ; j<other.cols ; j++)
187 {
188 double sum = 0.0;
189 for (unsigned int k=0 ; k<cols ; k++)
190 {
191 //sum += a[i][k] * b[k][j];
192 sum += d[i*cols +k] * other(k, j);
193 }
194 result(i, j) = sum;
195 }
197 }
198 return result;
199 }
201 SVDMatrix transpose()
202 {
203 SVDMatrix result(cols, rows);
204 for (unsigned int i=0 ; i<rows ; i++)
205 for (unsigned int j=0 ; j<cols ; j++)
206 result(j, i) = d[i*cols + j];
207 return result;
208 }
210 private:
213 virtual void init()
214 {
215 badval = 0.0;
216 d = NULL;
217 rows = 0;
218 cols = 0;
219 size = 0;
220 }
222 void assign(const SVDMatrix &other)
223 {
224 if (d)
225 {
226 delete[] d;
227 d = 0;
228 }
229 rows = other.rows;
230 cols = other.cols;
231 size = other.size;
232 d = new double[size];
233 for (unsigned int i=0 ; i<size ; i++)
234 d[i] = other.d[i];
235 }
237 double badval;
239 double *d;
240 unsigned int rows;
241 unsigned int cols;
242 unsigned int size;
243 };
247 /**
248 *
249 * ====================================================
250 *
251 * NOTE:
252 * This class is ported almost verbatim from the public domain
253 * JAMA Matrix package. It is modified to handle only 3x3 matrices
254 * and our NR::Matrix affine transform class. We give full
255 * attribution to them, along with many thanks. JAMA can be found at:
256 * http://math.nist.gov/javanumerics/jama
257 *
258 * ====================================================
259 *
260 * Singular Value Decomposition.
261 * <P>
262 * For an m-by-n matrix A with m >= n, the singular value decomposition is
263 * an m-by-n orthogonal matrix U, an n-by-n diagonal matrix S, and
264 * an n-by-n orthogonal matrix V so that A = U*S*V'.
265 * <P>
266 * The singular values, sigma[k] = S[k][k], are ordered so that
267 * sigma[0] >= sigma[1] >= ... >= sigma[n-1].
268 * <P>
269 * The singular value decompostion always exists, so the constructor will
270 * never fail. The matrix condition number and the effective numerical
271 * rank can be computed from this decomposition.
272 */
273 class SingularValueDecomposition
274 {
275 public:
277 /** Construct the singular value decomposition
278 @param A Rectangular matrix
279 @return Structure to access U, S and V.
280 */
282 SingularValueDecomposition (const SVDMatrix &mat)
283 {
284 A = mat;
285 s = NULL;
286 s_size = 0;
287 calculate();
288 }
290 virtual ~SingularValueDecomposition()
291 {
292 delete[] s;
293 }
295 /**
296 * Return the left singular vectors
297 * @return U
298 */
299 SVDMatrix &getU();
301 /**
302 * Return the right singular vectors
303 * @return V
304 */
305 SVDMatrix &getV();
307 /**
308 * Return the s[index] value
309 */ double getS(unsigned int index);
311 /**
312 * Two norm
313 * @return max(S)
314 */
315 double norm2();
317 /**
318 * Two norm condition number
319 * @return max(S)/min(S)
320 */
321 double cond();
323 /**
324 * Effective numerical matrix rank
325 * @return Number of nonnegligible singular values.
326 */
327 int rank();
329 private:
331 void calculate();
333 SVDMatrix A;
334 SVDMatrix U;
335 double *s;
336 unsigned int s_size;
337 SVDMatrix V;
339 };
342 static double svd_hypot(double a, double b)
343 {
344 double r;
346 if (fabs(a) > fabs(b))
347 {
348 r = b/a;
349 r = fabs(a) * sqrt(1+r*r);
350 }
351 else if (b != 0)
352 {
353 r = a/b;
354 r = fabs(b) * sqrt(1+r*r);
355 }
356 else
357 {
358 r = 0.0;
359 }
360 return r;
361 }
365 void SingularValueDecomposition::calculate()
366 {
367 // Initialize.
368 int m = A.getRows();
369 int n = A.getCols();
371 int nu = (m > n) ? m : n;
372 s_size = (m+1 < n) ? m+1 : n;
373 s = new double[s_size];
374 U = SVDMatrix(m, nu);
375 V = SVDMatrix(n, n);
376 double *e = new double[n];
377 double *work = new double[m];
378 bool wantu = true;
379 bool wantv = true;
381 // Reduce A to bidiagonal form, storing the diagonal elements
382 // in s and the super-diagonal elements in e.
384 int nct = (m-1<n) ? m-1 : n;
385 int nrtx = (n-2<m) ? n-2 : m;
386 int nrt = (nrtx>0) ? nrtx : 0;
387 for (int k = 0; k < 2; k++) {
388 if (k < nct) {
390 // Compute the transformation for the k-th column and
391 // place the k-th diagonal in s[k].
392 // Compute 2-norm of k-th column without under/overflow.
393 s[k] = 0;
394 for (int i = k; i < m; i++) {
395 s[k] = svd_hypot(s[k],A(i, k));
396 }
397 if (s[k] != 0.0) {
398 if (A(k, k) < 0.0) {
399 s[k] = -s[k];
400 }
401 for (int i = k; i < m; i++) {
402 A(i, k) /= s[k];
403 }
404 A(k, k) += 1.0;
405 }
406 s[k] = -s[k];
407 }
408 for (int j = k+1; j < n; j++) {
409 if ((k < nct) & (s[k] != 0.0)) {
411 // Apply the transformation.
413 double t = 0;
414 for (int i = k; i < m; i++) {
415 t += A(i, k) * A(i, j);
416 }
417 t = -t/A(k, k);
418 for (int i = k; i < m; i++) {
419 A(i, j) += t*A(i, k);
420 }
421 }
423 // Place the k-th row of A into e for the
424 // subsequent calculation of the row transformation.
426 e[j] = A(k, j);
427 }
428 if (wantu & (k < nct)) {
430 // Place the transformation in U for subsequent back
431 // multiplication.
433 for (int i = k; i < m; i++) {
434 U(i, k) = A(i, k);
435 }
436 }
437 if (k < nrt) {
439 // Compute the k-th row transformation and place the
440 // k-th super-diagonal in e[k].
441 // Compute 2-norm without under/overflow.
442 e[k] = 0;
443 for (int i = k+1; i < n; i++) {
444 e[k] = svd_hypot(e[k],e[i]);
445 }
446 if (e[k] != 0.0) {
447 if (e[k+1] < 0.0) {
448 e[k] = -e[k];
449 }
450 for (int i = k+1; i < n; i++) {
451 e[i] /= e[k];
452 }
453 e[k+1] += 1.0;
454 }
455 e[k] = -e[k];
456 if ((k+1 < m) & (e[k] != 0.0)) {
458 // Apply the transformation.
460 for (int i = k+1; i < m; i++) {
461 work[i] = 0.0;
462 }
463 for (int j = k+1; j < n; j++) {
464 for (int i = k+1; i < m; i++) {
465 work[i] += e[j]*A(i, j);
466 }
467 }
468 for (int j = k+1; j < n; j++) {
469 double t = -e[j]/e[k+1];
470 for (int i = k+1; i < m; i++) {
471 A(i, j) += t*work[i];
472 }
473 }
474 }
475 if (wantv) {
477 // Place the transformation in V for subsequent
478 // back multiplication.
480 for (int i = k+1; i < n; i++) {
481 V(i, k) = e[i];
482 }
483 }
484 }
485 }
487 // Set up the final bidiagonal matrix or order p.
489 int p = (n < m+1) ? n : m+1;
490 if (nct < n) {
491 s[nct] = A(nct, nct);
492 }
493 if (m < p) {
494 s[p-1] = 0.0;
495 }
496 if (nrt+1 < p) {
497 e[nrt] = A(nrt, p-1);
498 }
499 e[p-1] = 0.0;
501 // If required, generate U.
503 if (wantu) {
504 for (int j = nct; j < nu; j++) {
505 for (int i = 0; i < m; i++) {
506 U(i, j) = 0.0;
507 }
508 U(j, j) = 1.0;
509 }
510 for (int k = nct-1; k >= 0; k--) {
511 if (s[k] != 0.0) {
512 for (int j = k+1; j < nu; j++) {
513 double t = 0;
514 for (int i = k; i < m; i++) {
515 t += U(i, k)*U(i, j);
516 }
517 t = -t/U(k, k);
518 for (int i = k; i < m; i++) {
519 U(i, j) += t*U(i, k);
520 }
521 }
522 for (int i = k; i < m; i++ ) {
523 U(i, k) = -U(i, k);
524 }
525 U(k, k) = 1.0 + U(k, k);
526 for (int i = 0; i < k-1; i++) {
527 U(i, k) = 0.0;
528 }
529 } else {
530 for (int i = 0; i < m; i++) {
531 U(i, k) = 0.0;
532 }
533 U(k, k) = 1.0;
534 }
535 }
536 }
538 // If required, generate V.
540 if (wantv) {
541 for (int k = n-1; k >= 0; k--) {
542 if ((k < nrt) & (e[k] != 0.0)) {
543 for (int j = k+1; j < nu; j++) {
544 double t = 0;
545 for (int i = k+1; i < n; i++) {
546 t += V(i, k)*V(i, j);
547 }
548 t = -t/V(k+1, k);
549 for (int i = k+1; i < n; i++) {
550 V(i, j) += t*V(i, k);
551 }
552 }
553 }
554 for (int i = 0; i < n; i++) {
555 V(i, k) = 0.0;
556 }
557 V(k, k) = 1.0;
558 }
559 }
561 // Main iteration loop for the singular values.
563 int pp = p-1;
564 int iter = 0;
565 //double eps = pow(2.0,-52.0);
566 //double tiny = pow(2.0,-966.0);
567 //let's just calculate these now
568 //a double can be e ± 308.25, so this is safe
569 double eps = 2.22e-16;
570 double tiny = 1.6e-291;
571 while (p > 0) {
572 int k,kase;
574 // Here is where a test for too many iterations would go.
576 // This section of the program inspects for
577 // negligible elements in the s and e arrays. On
578 // completion the variables kase and k are set as follows.
580 // kase = 1 if s(p) and e[k-1] are negligible and k<p
581 // kase = 2 if s(k) is negligible and k<p
582 // kase = 3 if e[k-1] is negligible, k<p, and
583 // s(k), ..., s(p) are not negligible (qr step).
584 // kase = 4 if e(p-1) is negligible (convergence).
586 for (k = p-2; k >= -1; k--) {
587 if (k == -1) {
588 break;
589 }
590 if (fabs(e[k]) <=
591 tiny + eps*(fabs(s[k]) + fabs(s[k+1]))) {
592 e[k] = 0.0;
593 break;
594 }
595 }
596 if (k == p-2) {
597 kase = 4;
598 } else {
599 int ks;
600 for (ks = p-1; ks >= k; ks--) {
601 if (ks == k) {
602 break;
603 }
604 double t = (ks != p ? fabs(e[ks]) : 0.) +
605 (ks != k+1 ? fabs(e[ks-1]) : 0.);
606 if (fabs(s[ks]) <= tiny + eps*t) {
607 s[ks] = 0.0;
608 break;
609 }
610 }
611 if (ks == k) {
612 kase = 3;
613 } else if (ks == p-1) {
614 kase = 1;
615 } else {
616 kase = 2;
617 k = ks;
618 }
619 }
620 k++;
622 // Perform the task indicated by kase.
624 switch (kase) {
626 // Deflate negligible s(p).
628 case 1: {
629 double f = e[p-2];
630 e[p-2] = 0.0;
631 for (int j = p-2; j >= k; j--) {
632 double t = svd_hypot(s[j],f);
633 double cs = s[j]/t;
634 double sn = f/t;
635 s[j] = t;
636 if (j != k) {
637 f = -sn*e[j-1];
638 e[j-1] = cs*e[j-1];
639 }
640 if (wantv) {
641 for (int i = 0; i < n; i++) {
642 t = cs*V(i, j) + sn*V(i, p-1);
643 V(i, p-1) = -sn*V(i, j) + cs*V(i, p-1);
644 V(i, j) = t;
645 }
646 }
647 }
648 }
649 break;
651 // Split at negligible s(k).
653 case 2: {
654 double f = e[k-1];
655 e[k-1] = 0.0;
656 for (int j = k; j < p; j++) {
657 double t = svd_hypot(s[j],f);
658 double cs = s[j]/t;
659 double sn = f/t;
660 s[j] = t;
661 f = -sn*e[j];
662 e[j] = cs*e[j];
663 if (wantu) {
664 for (int i = 0; i < m; i++) {
665 t = cs*U(i, j) + sn*U(i, k-1);
666 U(i, k-1) = -sn*U(i, j) + cs*U(i, k-1);
667 U(i, j) = t;
668 }
669 }
670 }
671 }
672 break;
674 // Perform one qr step.
676 case 3: {
678 // Calculate the shift.
680 double scale = fabs(s[p-1]);
681 double d = fabs(s[p-2]);
682 if (d>scale) scale=d;
683 d = fabs(e[p-2]);
684 if (d>scale) scale=d;
685 d = fabs(s[k]);
686 if (d>scale) scale=d;
687 d = fabs(e[k]);
688 if (d>scale) scale=d;
689 double sp = s[p-1]/scale;
690 double spm1 = s[p-2]/scale;
691 double epm1 = e[p-2]/scale;
692 double sk = s[k]/scale;
693 double ek = e[k]/scale;
694 double b = ((spm1 + sp)*(spm1 - sp) + epm1*epm1)/2.0;
695 double c = (sp*epm1)*(sp*epm1);
696 double shift = 0.0;
697 if ((b != 0.0) | (c != 0.0)) {
698 shift = sqrt(b*b + c);
699 if (b < 0.0) {
700 shift = -shift;
701 }
702 shift = c/(b + shift);
703 }
704 double f = (sk + sp)*(sk - sp) + shift;
705 double g = sk*ek;
707 // Chase zeros.
709 for (int j = k; j < p-1; j++) {
710 double t = svd_hypot(f,g);
711 double cs = f/t;
712 double sn = g/t;
713 if (j != k) {
714 e[j-1] = t;
715 }
716 f = cs*s[j] + sn*e[j];
717 e[j] = cs*e[j] - sn*s[j];
718 g = sn*s[j+1];
719 s[j+1] = cs*s[j+1];
720 if (wantv) {
721 for (int i = 0; i < n; i++) {
722 t = cs*V(i, j) + sn*V(i, j+1);
723 V(i, j+1) = -sn*V(i, j) + cs*V(i, j+1);
724 V(i, j) = t;
725 }
726 }
727 t = svd_hypot(f,g);
728 cs = f/t;
729 sn = g/t;
730 s[j] = t;
731 f = cs*e[j] + sn*s[j+1];
732 s[j+1] = -sn*e[j] + cs*s[j+1];
733 g = sn*e[j+1];
734 e[j+1] = cs*e[j+1];
735 if (wantu && (j < m-1)) {
736 for (int i = 0; i < m; i++) {
737 t = cs*U(i, j) + sn*U(i, j+1);
738 U(i, j+1) = -sn*U(i, j) + cs*U(i, j+1);
739 U(i, j) = t;
740 }
741 }
742 }
743 e[p-2] = f;
744 iter = iter + 1;
745 }
746 break;
748 // Convergence.
750 case 4: {
752 // Make the singular values positive.
754 if (s[k] <= 0.0) {
755 s[k] = (s[k] < 0.0 ? -s[k] : 0.0);
756 if (wantv) {
757 for (int i = 0; i <= pp; i++) {
758 V(i, k) = -V(i, k);
759 }
760 }
761 }
763 // Order the singular values.
765 while (k < pp) {
766 if (s[k] >= s[k+1]) {
767 break;
768 }
769 double t = s[k];
770 s[k] = s[k+1];
771 s[k+1] = t;
772 if (wantv && (k < n-1)) {
773 for (int i = 0; i < n; i++) {
774 t = V(i, k+1); V(i, k+1) = V(i, k); V(i, k) = t;
775 }
776 }
777 if (wantu && (k < m-1)) {
778 for (int i = 0; i < m; i++) {
779 t = U(i, k+1); U(i, k+1) = U(i, k); U(i, k) = t;
780 }
781 }
782 k++;
783 }
784 iter = 0;
785 p--;
786 }
787 break;
788 }
789 }
791 delete e;
792 delete work;
794 }
798 /**
799 * Return the left singular vectors
800 * @return U
801 */
802 SVDMatrix &SingularValueDecomposition::getU()
803 {
804 return U;
805 }
807 /**
808 * Return the right singular vectors
809 * @return V
810 */
812 SVDMatrix &SingularValueDecomposition::getV()
813 {
814 return V;
815 }
817 /**
818 * Return the s[0] value
819 */
820 double SingularValueDecomposition::getS(unsigned int index)
821 {
822 if (index >= s_size)
823 return 0.0;
824 return s[index];
825 }
827 /**
828 * Two norm
829 * @return max(S)
830 */
831 double SingularValueDecomposition::norm2()
832 {
833 return s[0];
834 }
836 /**
837 * Two norm condition number
838 * @return max(S)/min(S)
839 */
841 double SingularValueDecomposition::cond()
842 {
843 return s[0]/s[2];
844 }
846 /**
847 * Effective numerical matrix rank
848 * @return Number of nonnegligible singular values.
849 */
850 int SingularValueDecomposition::rank()
851 {
852 double eps = pow(2.0,-52.0);
853 double tol = 3.0*s[0]*eps;
854 int r = 0;
855 for (int i = 0; i < 3; i++)
856 {
857 if (s[i] > tol)
858 r++;
859 }
860 return r;
861 }
863 //########################################################################
864 //# E N D C L A S S SingularValueDecomposition
865 //########################################################################
871 #define pi 3.14159
872 //#define pxToCm 0.0275
873 #define pxToCm 0.03
874 #define piToRad 0.0174532925
875 #define docHeightCm 22.86
878 //########################################################################
879 //# O U T P U T
880 //########################################################################
882 /**
883 * Get the value of a node/attribute pair
884 */
885 static Glib::ustring getAttribute( Inkscape::XML::Node *node, char *attrName)
886 {
887 Glib::ustring val;
888 char *valstr = (char *)node->attribute(attrName);
889 if (valstr)
890 val = (const char *)valstr;
891 return val;
892 }
896 /**
897 * Get the extension suffix from the end of a file name
898 */
899 static Glib::ustring getExtension(const Glib::ustring &fname)
900 {
901 Glib::ustring ext;
903 unsigned int pos = fname.rfind('.');
904 if (pos == fname.npos)
905 {
906 ext = "";
907 }
908 else
909 {
910 ext = fname.substr(pos);
911 }
912 return ext;
913 }
916 static Glib::ustring formatTransform(NR::Matrix &tf)
917 {
918 Glib::ustring str;
919 if (!tf.test_identity())
920 {
921 StringOutputStream outs;
922 OutputStreamWriter out(outs);
923 out.printf("matrix(%.3f %.3f %.3f %.3f %.3f %.3f)",
924 tf[0], tf[1], tf[2], tf[3], tf[4], tf[5]);
925 str = outs.getString();
926 }
927 return str;
928 }
931 /**
932 * Encode a string, checking for XML entities, to
933 * make an XML string safe for output
934 */
935 static Glib::ustring toXml(const Glib::ustring &str)
936 {
937 Glib::ustring outbuf;
938 for (unsigned int i=0 ; i<str.size() ; i++)
939 {
940 XMLCh ch = (XMLCh) str[i];
941 if (ch == '&')
942 outbuf.append("&r;");
943 else if (ch == '<')
944 outbuf.append("<");
945 else if (ch == '>')
946 outbuf.append(">");
947 else if (ch == '"')
948 outbuf.append(""");
949 else if (ch == '\'')
950 outbuf.append("'");
951 else
952 outbuf.push_back(ch);
953 }
954 return outbuf;
955 }
961 /**
962 * Get the general transform from SVG pixels to
963 * ODF cm
964 */
965 static NR::Matrix getODFTransform(const SPItem *item)
966 {
967 //### Get SVG-to-ODF transform
968 NR::Matrix tf;
969 tf = sp_item_i2d_affine(item);
970 //Flip Y into document coordinates
971 double doc_height = sp_document_height(SP_ACTIVE_DOCUMENT);
972 NR::Matrix doc2dt_tf = NR::Matrix(NR::scale(1.0, -1.0));
973 doc2dt_tf = doc2dt_tf * NR::Matrix(NR::translate(0, doc_height));
974 tf = tf * doc2dt_tf;
975 tf = tf * NR::Matrix(NR::scale(pxToCm));
976 return tf;
977 }
982 /**
983 * Get the bounding box of an item, as mapped onto
984 * an ODF document, in cm.
985 */
986 static NR::Rect getODFBoundingBox(const SPItem *item)
987 {
988 NR::Rect bbox = sp_item_bbox_desktop((SPItem *)item);
989 double doc_height = sp_document_height(SP_ACTIVE_DOCUMENT);
990 NR::Matrix doc2dt_tf = NR::Matrix(NR::scale(1.0, -1.0));
991 doc2dt_tf = doc2dt_tf * NR::Matrix(NR::translate(0, doc_height));
992 bbox = bbox * doc2dt_tf;
993 bbox = bbox * NR::Matrix(NR::scale(pxToCm));
994 return bbox;
995 }
999 /**
1000 * Get the transform for an item, correcting for
1001 * handedness reversal
1002 */
1003 static NR::Matrix getODFItemTransform(const SPItem *item)
1004 {
1005 NR::Matrix itemTransform = NR::Matrix(NR::scale(1, -1));
1006 itemTransform = itemTransform * item->transform;
1007 itemTransform = itemTransform * NR::Matrix(NR::scale(1, -1));
1008 return itemTransform;
1009 }
1013 /**
1014 * Get some fun facts from the transform
1015 */
1016 static void analyzeTransform(NR::Matrix &tf,
1017 double &rotate, double &xskew, double &yskew,
1018 double &xscale, double &yscale)
1019 {
1020 SVDMatrix mat(2, 2);
1021 mat(0, 0) = tf[0];
1022 mat(0, 1) = tf[1];
1023 mat(1, 0) = tf[2];
1024 mat(1, 1) = tf[3];
1026 SingularValueDecomposition svd(mat);
1028 SVDMatrix U = svd.getU();
1029 SVDMatrix V = svd.getV();
1030 SVDMatrix Vt = V.transpose();
1031 SVDMatrix UVt = U.multiply(Vt);
1032 double s0 = svd.getS(0);
1033 double s1 = svd.getS(1);
1034 xscale = s0;
1035 yscale = s1;
1036 //g_message("## s0:%.3f s1:%.3f", s0, s1);
1037 //g_message("## u:%.3f %.3f %.3f %.3f", U(0,0), U(0,1), U(1,0), U(1,1));
1038 //g_message("## v:%.3f %.3f %.3f %.3f", V(0,0), V(0,1), V(1,0), V(1,1));
1039 //g_message("## vt:%.3f %.3f %.3f %.3f", Vt(0,0), Vt(0,1), Vt(1,0), Vt(1,1));
1040 //g_message("## uvt:%.3f %.3f %.3f %.3f", UVt(0,0), UVt(0,1), UVt(1,0), UVt(1,1));
1041 rotate = UVt(0,0);
1042 }
1046 static void gatherText(Inkscape::XML::Node *node, Glib::ustring &buf)
1047 {
1048 if (node->type() == Inkscape::XML::TEXT_NODE)
1049 {
1050 char *s = (char *)node->content();
1051 if (s)
1052 buf.append(s);
1053 }
1055 for (Inkscape::XML::Node *child = node->firstChild() ;
1056 child != NULL; child = child->next())
1057 {
1058 gatherText(child, buf);
1059 }
1061 }
1063 /**
1064 * FIRST PASS.
1065 * Method descends into the repr tree, converting image, style, and gradient info
1066 * into forms compatible in ODF.
1067 */
1068 void
1069 OdfOutput::preprocess(ZipFile &zf, Inkscape::XML::Node *node)
1070 {
1072 Glib::ustring nodeName = node->name();
1073 Glib::ustring id = getAttribute(node, "id");
1075 //### First, check for metadata
1076 if (nodeName == "metadata" || nodeName == "svg:metadata")
1077 {
1078 Inkscape::XML::Node *mchild = node->firstChild() ;
1079 if (!mchild || strcmp(mchild->name(), "rdf:RDF"))
1080 return;
1081 Inkscape::XML::Node *rchild = mchild->firstChild() ;
1082 if (!rchild || strcmp(rchild->name(), "cc:Work"))
1083 return;
1084 for (Inkscape::XML::Node *cchild = rchild->firstChild() ;
1085 cchild ; cchild = cchild->next())
1086 {
1087 Glib::ustring ccName = cchild->name();
1088 Glib::ustring ccVal;
1089 gatherText(cchild, ccVal);
1090 //g_message("ccName: %s ccVal:%s", ccName.c_str(), ccVal.c_str());
1091 metadata[ccName] = ccVal;
1092 }
1093 return;
1094 }
1096 //Now consider items.
1097 SPObject *reprobj = SP_ACTIVE_DOCUMENT->getObjectByRepr(node);
1098 if (!reprobj)
1099 return;
1100 if (!SP_IS_ITEM(reprobj))
1101 {
1102 return;
1103 }
1104 SPItem *item = SP_ITEM(reprobj);
1105 //### Get SVG-to-ODF transform
1106 NR::Matrix tf = getODFTransform(item);
1108 if (nodeName == "image" || nodeName == "svg:image")
1109 {
1110 //g_message("image");
1111 Glib::ustring href = getAttribute(node, "xlink:href");
1112 if (href.size() > 0)
1113 {
1114 Glib::ustring oldName = href;
1115 Glib::ustring ext = getExtension(oldName);
1116 if (ext == ".jpeg")
1117 ext = ".jpg";
1118 if (imageTable.find(oldName) == imageTable.end())
1119 {
1120 char buf[64];
1121 snprintf(buf, 63, "Pictures/image%d%s",
1122 (int)imageTable.size(), ext.c_str());
1123 Glib::ustring newName = buf;
1124 imageTable[oldName] = newName;
1125 Glib::ustring comment = "old name was: ";
1126 comment.append(oldName);
1127 URI oldUri(oldName);
1128 //g_message("oldpath:%s", oldUri.getNativePath().c_str());
1129 //# if relative to the documentURI, get proper path
1130 URI resUri = documentUri.resolve(oldUri);
1131 DOMString pathName = resUri.getNativePath();
1132 //g_message("native path:%s", pathName.c_str());
1133 ZipEntry *ze = zf.addFile(pathName, comment);
1134 if (ze)
1135 {
1136 ze->setFileName(newName);
1137 }
1138 else
1139 {
1140 g_warning("Could not load image file '%s'", pathName.c_str());
1141 }
1142 }
1143 }
1144 }
1148 //###### Get style
1149 SPStyle *style = SP_OBJECT_STYLE(item);
1150 if (style && id.size()>0)
1151 {
1152 bool isGradient = false;
1154 StyleInfo si;
1155 //## Style. Look in writeStyle() below to see what info
1156 // we need to read into StyleInfo. Note that we need to
1157 // determine whether information goes into a style element
1158 // or a gradient element.
1159 //## FILL
1160 if (style->fill.type == SP_PAINT_TYPE_COLOR)
1161 {
1162 guint32 fillCol =
1163 sp_color_get_rgba32_ualpha(&style->fill.value.color, 0);
1164 char buf[16];
1165 int r = (fillCol >> 24) & 0xff;
1166 int g = (fillCol >> 16) & 0xff;
1167 int b = (fillCol >> 8) & 0xff;
1168 //g_message("## %s %lx", id.c_str(), (unsigned int)fillCol);
1169 snprintf(buf, 15, "#%02x%02x%02x", r, g, b);
1170 si.fillColor = buf;
1171 si.fill = "solid";
1172 double opacityPercent = 100.0 *
1173 (SP_SCALE24_TO_FLOAT(style->fill_opacity.value));
1174 snprintf(buf, 15, "%.3f%%", opacityPercent);
1175 si.fillOpacity = buf;
1176 }
1177 else if (style->fill.type == SP_PAINT_TYPE_PAINTSERVER)
1178 {
1179 //## Gradient. Look in writeStyle() below to see what info
1180 // we need to read into GradientInfo.
1181 if (!SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)))
1182 return;
1183 isGradient = true;
1184 GradientInfo gi;
1185 SPGradient *gradient = SP_GRADIENT(SP_STYLE_FILL_SERVER(style));
1186 if (SP_IS_LINEARGRADIENT(gradient))
1187 {
1188 gi.style = "linear";
1189 SPLinearGradient *linGrad = SP_LINEARGRADIENT(gradient);
1190 gi.x1 = linGrad->x1.value;
1191 gi.y1 = linGrad->y1.value;
1192 gi.x2 = linGrad->x2.value;
1193 gi.y2 = linGrad->y2.value;
1194 }
1195 else if (SP_IS_RADIALGRADIENT(gradient))
1196 {
1197 gi.style = "radial";
1198 SPRadialGradient *radGrad = SP_RADIALGRADIENT(gradient);
1199 gi.cx = radGrad->cx.computed * 100.0;//ODG cx is percentages
1200 gi.cy = radGrad->cy.computed * 100.0;
1201 }
1202 else
1203 {
1204 g_warning("not a supported gradient type");
1205 }
1207 //Look for existing identical style;
1208 bool gradientMatch = false;
1209 std::vector<GradientInfo>::iterator iter;
1210 for (iter=gradientTable.begin() ; iter!=gradientTable.end() ; iter++)
1211 {
1212 if (gi.equals(*iter))
1213 {
1214 //map to existing gradientTable entry
1215 Glib::ustring gradientName = iter->name;
1216 //g_message("found duplicate style:%s", gradientName.c_str());
1217 gradientLookupTable[id] = gradientName;
1218 gradientMatch = true;
1219 break;
1220 }
1221 }
1222 //None found, make a new pair or entries
1223 if (!gradientMatch)
1224 {
1225 char buf[16];
1226 snprintf(buf, 15, "gradient%d", (int)gradientTable.size());
1227 Glib::ustring gradientName = buf;
1228 gi.name = gradientName;
1229 gradientTable.push_back(gi);
1230 gradientLookupTable[id] = gradientName;
1231 }
1232 }
1234 //## STROKE
1235 if (style->stroke.type == SP_PAINT_TYPE_COLOR)
1236 {
1237 guint32 strokeCol =
1238 sp_color_get_rgba32_ualpha(&style->stroke.value.color, 0);
1239 char buf[16];
1240 int r = (strokeCol >> 24) & 0xff;
1241 int g = (strokeCol >> 16) & 0xff;
1242 int b = (strokeCol >> 8) & 0xff;
1243 snprintf(buf, 15, "#%02x%02x%02x", r, g, b);
1244 si.strokeColor = buf;
1245 snprintf(buf, 15, "%.3fpt", style->stroke_width.value);
1246 si.strokeWidth = buf;
1247 si.stroke = "solid";
1248 double opacityPercent = 100.0 *
1249 (SP_SCALE24_TO_FLOAT(style->stroke_opacity.value));
1250 snprintf(buf, 15, "%.3f%%", opacityPercent);
1251 si.strokeOpacity = buf;
1252 }
1254 if (!isGradient)
1255 {
1256 //Look for existing identical style;
1257 bool styleMatch = false;
1258 std::vector<StyleInfo>::iterator iter;
1259 for (iter=styleTable.begin() ; iter!=styleTable.end() ; iter++)
1260 {
1261 if (si.equals(*iter))
1262 {
1263 //map to existing styleTable entry
1264 Glib::ustring styleName = iter->name;
1265 //g_message("found duplicate style:%s", styleName.c_str());
1266 styleLookupTable[id] = styleName;
1267 styleMatch = true;
1268 break;
1269 }
1270 }
1271 //None found, make a new pair or entries
1272 if (!styleMatch)
1273 {
1274 char buf[16];
1275 snprintf(buf, 15, "style%d", (int)styleTable.size());
1276 Glib::ustring styleName = buf;
1277 si.name = styleName;
1278 styleTable.push_back(si);
1279 styleLookupTable[id] = styleName;
1280 }
1281 }
1282 }
1284 for (Inkscape::XML::Node *child = node->firstChild() ;
1285 child ; child = child->next())
1286 preprocess(zf, child);
1287 }
1291 /**
1292 * Writes the manifest. Currently it only changes according to the
1293 * file names of images packed into the zip file.
1294 */
1295 bool OdfOutput::writeManifest(ZipFile &zf)
1296 {
1297 BufferOutputStream bouts;
1298 OutputStreamWriter outs(bouts);
1300 time_t tim;
1301 time(&tim);
1303 outs.printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1304 outs.printf("<!DOCTYPE manifest:manifest PUBLIC \"-//OpenOffice.org//DTD Manifest 1.0//EN\" \"Manifest.dtd\">\n");
1305 outs.printf("\n");
1306 outs.printf("\n");
1307 outs.printf("<!--\n");
1308 outs.printf("*************************************************************************\n");
1309 outs.printf(" file: manifest.xml\n");
1310 outs.printf(" Generated by Inkscape: %s", ctime(&tim)); //ctime has its own <cr>
1311 outs.printf(" http://www.inkscape.org\n");
1312 outs.printf("*************************************************************************\n");
1313 outs.printf("-->\n");
1314 outs.printf("\n");
1315 outs.printf("\n");
1316 outs.printf("<manifest:manifest xmlns:manifest=\"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0\">\n");
1317 outs.printf(" <manifest:file-entry manifest:media-type=\"application/vnd.oasis.opendocument.graphics\" manifest:full-path=\"/\"/>\n");
1318 outs.printf(" <manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"content.xml\"/>\n");
1319 outs.printf(" <manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"meta.xml\"/>\n");
1320 outs.printf(" <!--List our images here-->\n");
1321 std::map<Glib::ustring, Glib::ustring>::iterator iter;
1322 for (iter = imageTable.begin() ; iter!=imageTable.end() ; iter++)
1323 {
1324 Glib::ustring oldName = iter->first;
1325 Glib::ustring newName = iter->second;
1327 Glib::ustring ext = getExtension(oldName);
1328 if (ext == ".jpeg")
1329 ext = ".jpg";
1330 outs.printf(" <manifest:file-entry manifest:media-type=\"");
1331 if (ext == ".gif")
1332 outs.printf("image/gif");
1333 else if (ext == ".png")
1334 outs.printf("image/png");
1335 else if (ext == ".jpg")
1336 outs.printf("image/jpeg");
1337 outs.printf("\" manifest:full-path=\"");
1338 outs.printf((char *)newName.c_str());
1339 outs.printf("\"/>\n");
1340 }
1341 outs.printf("</manifest:manifest>\n");
1343 outs.close();
1345 //Make our entry
1346 ZipEntry *ze = zf.newEntry("META-INF/manifest.xml", "ODF file manifest");
1347 ze->setUncompressedData(bouts.getBuffer());
1348 ze->finish();
1350 return true;
1351 }
1354 /**
1355 * This writes the document meta information to meta.xml
1356 */
1357 bool OdfOutput::writeMeta(ZipFile &zf)
1358 {
1359 BufferOutputStream bouts;
1360 OutputStreamWriter outs(bouts);
1362 time_t tim;
1363 time(&tim);
1365 std::map<Glib::ustring, Glib::ustring>::iterator iter;
1366 Glib::ustring creator = "unknown";
1367 iter = metadata.find("dc:creator");
1368 if (iter != metadata.end())
1369 creator = iter->second;
1370 Glib::ustring date = "";
1371 iter = metadata.find("dc:date");
1372 if (iter != metadata.end())
1373 date = iter->second;
1375 outs.printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1376 outs.printf("\n");
1377 outs.printf("\n");
1378 outs.printf("<!--\n");
1379 outs.printf("*************************************************************************\n");
1380 outs.printf(" file: meta.xml\n");
1381 outs.printf(" Generated by Inkscape: %s", ctime(&tim)); //ctime has its own <cr>
1382 outs.printf(" http://www.inkscape.org\n");
1383 outs.printf("*************************************************************************\n");
1384 outs.printf("-->\n");
1385 outs.printf("\n");
1386 outs.printf("\n");
1387 outs.printf("<office:document-meta\n");
1388 outs.printf("xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\"\n");
1389 outs.printf("xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n");
1390 outs.printf("xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n");
1391 outs.printf("xmlns:meta=\"urn:oasis:names:tc:opendocument:xmlns:meta:1.0\"\n");
1392 outs.printf("xmlns:presentation=\"urn:oasis:names:tc:opendocument:xmlns:presentation:1.0\"\n");
1393 outs.printf("xmlns:ooo=\"http://openoffice.org/2004/office\"\n");
1394 outs.printf("xmlns:smil=\"urn:oasis:names:tc:opendocument:xmlns:smil-compatible:1.0\"\n");
1395 outs.printf("xmlns:anim=\"urn:oasis:names:tc:opendocument:xmlns:animation:1.0\"\n");
1396 outs.printf("office:version=\"1.0\">\n");
1397 outs.printf("<office:meta>\n");
1398 outs.printf(" <meta:generator>Inkscape.org - 0.45</meta:generator>\n");
1399 outs.printf(" <meta:initial-creator>%s</meta:initial-creator>\n",
1400 toXml(creator).c_str());
1401 outs.printf(" <meta:creation-date>%s</meta:creation-date>\n", date.c_str());
1402 for (iter = metadata.begin() ; iter != metadata.end() ; iter++)
1403 {
1404 Glib::ustring name = iter->first;
1405 Glib::ustring value = iter->second;
1406 if (name.size() > 0 && value.size()>0)
1407 {
1408 outs.printf(" <%s>%s</%s>\n",
1409 toXml(name).c_str(), toXml(value).c_str(), toXml(name).c_str());
1410 }
1411 }
1412 outs.printf(" <meta:editing-cycles>2</meta:editing-cycles>\n");
1413 outs.printf(" <meta:editing-duration>PT56S</meta:editing-duration>\n");
1414 outs.printf(" <meta:user-defined meta:name=\"Info 1\"/>\n");
1415 outs.printf(" <meta:user-defined meta:name=\"Info 2\"/>\n");
1416 outs.printf(" <meta:user-defined meta:name=\"Info 3\"/>\n");
1417 outs.printf(" <meta:user-defined meta:name=\"Info 4\"/>\n");
1418 outs.printf(" <meta:document-statistic meta:object-count=\"2\"/>\n");
1419 outs.printf("</office:meta>\n");
1420 outs.printf("</office:document-meta>\n");
1421 outs.printf("\n");
1422 outs.printf("\n");
1425 outs.close();
1427 //Make our entry
1428 ZipEntry *ze = zf.newEntry("meta.xml", "ODF info file");
1429 ze->setUncompressedData(bouts.getBuffer());
1430 ze->finish();
1432 return true;
1433 }
1438 /**
1439 * This is called just before writeTree(), since it will write style and
1440 * gradient information above the <draw> tag in the content.xml file
1441 */
1442 bool OdfOutput::writeStyle(Writer &outs)
1443 {
1444 outs.printf("<office:automatic-styles>\n");
1445 outs.printf("<!-- ####### 'Standard' styles ####### -->\n");
1446 outs.printf("<style:style style:name=\"dp1\" style:family=\"drawing-page\"/>\n");
1447 outs.printf("<style:style style:name=\"gr1\" style:family=\"graphic\" style:parent-style-name=\"standard\">\n");
1448 outs.printf(" <style:graphic-properties draw:stroke=\"none\" draw:fill=\"none\"\n");
1449 outs.printf(" draw:textarea-horizontal-align=\"center\"\n");
1450 outs.printf(" draw:textarea-vertical-align=\"middle\" draw:color-mode=\"standard\"\n");
1451 outs.printf(" draw:luminance=\"0%%\" draw:contrast=\"0%%\" draw:gamma=\"100%%\" draw:red=\"0%%\"\n");
1452 outs.printf(" draw:green=\"0%%\" draw:blue=\"0%%\" fo:clip=\"rect(0cm 0cm 0cm 0cm)\"\n");
1453 outs.printf(" draw:image-opacity=\"100%%\" style:mirror=\"none\"/>\n");
1454 outs.printf("</style:style>\n");
1455 outs.printf("<style:style style:name=\"P1\" style:family=\"paragraph\">\n");
1456 outs.printf(" <style:paragraph-properties fo:text-align=\"center\"/>\n");
1457 outs.printf("</style:style>\n");
1459 /*
1460 ==========================================================
1461 Dump our style table. Styles should have a general layout
1462 something like the following. Look in:
1463 http://books.evc-cit.info/odbook/ch06.html#draw-style-file-section
1464 for style and gradient information.
1465 <style:style style:name="gr13"
1466 style:family="graphic" style:parent-style-name="standard">
1467 <style:graphic-properties draw:stroke="solid"
1468 svg:stroke-width="0.1cm"
1469 svg:stroke-color="#ff0000"
1470 draw:fill="solid" draw:fill-color="#e6e6ff"/>
1471 </style:style>
1472 ==========================================================
1473 */
1474 outs.printf("<!-- ####### Styles from Inkscape document ####### -->\n");
1475 std::vector<StyleInfo>::iterator iter;
1476 for (iter = styleTable.begin() ; iter != styleTable.end() ; iter++)
1477 {
1478 outs.printf("<style:style style:name=\"%s\"", iter->name.c_str());
1479 StyleInfo s(*iter);
1480 outs.printf(" style:family=\"graphic\" style:parent-style-name=\"standard\">\n");
1481 outs.printf(" <style:graphic-properties");
1482 outs.printf(" draw:fill=\"%s\" ", s.fill.c_str());
1483 if (s.fill != "none")
1484 {
1485 outs.printf(" draw:fill-color=\"%s\" ", s.fillColor.c_str());
1486 outs.printf(" draw:fill-opacity=\"%s\" ", s.fillOpacity.c_str());
1487 }
1488 outs.printf(" draw:stroke=\"%s\" ", s.stroke.c_str());
1489 if (s.stroke != "none")
1490 {
1491 outs.printf(" svg:stroke-width=\"%s\" ", s.strokeWidth.c_str());
1492 outs.printf(" svg:stroke-color=\"%s\" ", s.strokeColor.c_str());
1493 outs.printf(" svg:stroke-opacity=\"%s\" ", s.strokeOpacity.c_str());
1494 }
1495 outs.printf("/>\n");
1496 outs.printf("</style:style>\n");
1497 }
1499 //## Dump our gradient table
1500 outs.printf("\n");
1501 outs.printf("<!-- ####### Gradients from Inkscape document ####### -->\n");
1502 std::vector<GradientInfo>::iterator giter;
1503 for (giter = gradientTable.begin() ; giter != gradientTable.end() ; giter++)
1504 {
1505 GradientInfo gi(*giter);
1506 outs.printf("<draw:gradient draw:name=\"%s\" ", gi.name.c_str());
1507 outs.printf("draw:style=\"%s\" ", gi.style.c_str());
1508 if (gi.style == "linear")
1509 {
1510 /*
1511 ===================================================================
1512 LINEAR gradient. We need something that looks like this:
1513 <draw:gradient draw:name="Gradient_20_7"
1514 draw:display-name="Gradient 7"
1515 draw:style="linear"
1516 draw:start-color="#008080" draw:end-color="#993366"
1517 draw:start-intensity="100%" draw:end-intensity="100%"
1518 draw:angle="150" draw:border="0%"/>
1519 ===================================================================
1520 */
1521 outs.printf("draw:display-name=\"linear borderless\" ");
1522 }
1523 else if (gi.style == "radial")
1524 {
1525 /*
1526 ===================================================================
1527 RADIAL gradient. We need something that looks like this:
1528 <!-- radial gradient, light gray to white, centered, 0% border -->
1529 <draw:gradient draw:name="radial_20_borderless"
1530 draw:display-name="radial borderless"
1531 draw:style="radial"
1532 draw:cx="50%" draw:cy="50%"
1533 draw:start-color="#999999" draw:end-color="#ffffff"
1534 draw:border="0%"/>
1535 ===================================================================
1536 */
1537 outs.printf("draw:display-name=\"radial borderless\" ");
1538 outs.printf("draw:cx=\".2f%%\" draw:cy=\".2f%%\" ", gi.cx, gi.cy);
1539 }
1540 else
1541 {
1542 g_warning("unsupported gradient style '%s'", gi.style.c_str());
1543 }
1544 outs.printf("/>\n");
1545 }
1547 outs.printf("\n");
1548 outs.printf("</office:automatic-styles>\n");
1549 outs.printf("\n");
1551 return true;
1552 }
1556 /**
1557 * Writes an SVG path as an ODF <draw:path>
1558 */
1559 static int
1560 writePath(Writer &outs, NArtBpath const *bpath,
1561 NR::Matrix &tf, double xoff, double yoff)
1562 {
1563 bool closed = false;
1564 int nrPoints = 0;
1565 NArtBpath *bp = (NArtBpath *)bpath;
1567 double destx = 0.0;
1568 double desty = 0.0;
1569 int code = -1;
1571 for ( ; bp->code != NR_END; bp++)
1572 {
1573 code = bp->code;
1575 NR::Point const p1(bp->c(1) * tf);
1576 NR::Point const p2(bp->c(2) * tf);
1577 NR::Point const p3(bp->c(3) * tf);
1578 double x1 = (p1[NR::X] - xoff) * 1000.0;
1579 if (fabs(x1)<1.0) x1=0.0;
1580 double y1 = (p1[NR::Y] - yoff) * 1000.0;
1581 if (fabs(y1)<1.0) y1=0.0;
1582 double x2 = (p2[NR::X] - xoff) * 1000.0;
1583 if (fabs(x2)<1.0) x2=0.0;
1584 double y2 = (p2[NR::Y] - yoff) * 1000.0;
1585 if (fabs(y2)<1.0) y2=0.0;
1586 double x3 = (p3[NR::X] - xoff) * 1000.0;
1587 if (fabs(x3)<1.0) x3=0.0;
1588 double y3 = (p3[NR::Y] - yoff) * 1000.0;
1589 if (fabs(y3)<1.0) y3=0.0;
1590 destx = x3;
1591 desty = y3;
1593 switch (code)
1594 {
1595 case NR_LINETO:
1596 outs.printf("L %.3f %.3f ", destx, desty);
1597 break;
1599 case NR_CURVETO:
1600 outs.printf("C %.3f %.3f %.3f %.3f %.3f %.3f ",
1601 x1, y1, x2, y2, destx, desty);
1602 break;
1604 case NR_MOVETO_OPEN:
1605 case NR_MOVETO:
1606 if (closed)
1607 outs.printf("Z ");
1608 closed = ( code == NR_MOVETO );
1609 outs.printf("M %.3f %.3f ", destx, desty);
1610 break;
1612 default:
1613 break;
1615 }
1617 nrPoints++;
1618 }
1620 if (closed)
1621 {
1622 outs.printf("Z");
1623 }
1625 return nrPoints;
1626 }
1630 /**
1631 * SECOND PASS.
1632 * This is the main SPObject tree output to ODF. preprocess()
1633 * must be called prior to this, as elements will often reference
1634 * data parsed and tabled in preprocess().
1635 */
1636 bool OdfOutput::writeTree(Writer &outs, Inkscape::XML::Node *node)
1637 {
1638 //# Get the SPItem, if applicable
1639 SPObject *reprobj = SP_ACTIVE_DOCUMENT->getObjectByRepr(node);
1640 if (!reprobj)
1641 return true;
1642 if (!SP_IS_ITEM(reprobj))
1643 {
1644 return true;
1645 }
1646 SPItem *item = SP_ITEM(reprobj);
1649 Glib::ustring nodeName = node->name();
1650 Glib::ustring id = getAttribute(node, "id");
1652 //### Get SVG-to-ODF transform
1653 NR::Matrix tf = getODFTransform(item);
1655 //### Get ODF bounding box params for item
1656 NR::Rect bbox = getODFBoundingBox(item);
1657 double bbox_x = bbox.min()[NR::X];
1658 double bbox_y = bbox.min()[NR::Y];
1659 double bbox_width = bbox.max()[NR::X] - bbox.min()[NR::X];
1660 double bbox_height = bbox.max()[NR::Y] - bbox.min()[NR::Y];
1662 double rotate;
1663 double xskew;
1664 double yskew;
1665 double xscale;
1666 double yscale;
1667 analyzeTransform(tf, rotate, xskew, yskew, xscale, yscale);
1669 //# Do our stuff
1670 SPCurve *curve = NULL;
1672 //g_message("##### %s #####", nodeName.c_str());
1674 if (nodeName == "svg" || nodeName == "svg:svg")
1675 {
1676 //# Iterate through the children
1677 for (Inkscape::XML::Node *child = node->firstChild() ; child ; child = child->next())
1678 {
1679 if (!writeTree(outs, child))
1680 return false;
1681 }
1682 return true;
1683 }
1684 else if (nodeName == "g" || nodeName == "svg:g")
1685 {
1686 if (id.size() > 0)
1687 outs.printf("<draw:g id=\"%s\">\n", id.c_str());
1688 else
1689 outs.printf("<draw:g>\n");
1690 //# Iterate through the children
1691 for (Inkscape::XML::Node *child = node->firstChild() ; child ; child = child->next())
1692 {
1693 if (!writeTree(outs, child))
1694 return false;
1695 }
1696 if (id.size() > 0)
1697 outs.printf("</draw:g> <!-- id=\"%s\" -->\n", id.c_str());
1698 else
1699 outs.printf("</draw:g>\n");
1700 return true;
1701 }
1702 else if (nodeName == "image" || nodeName == "svg:image")
1703 {
1704 if (!SP_IS_IMAGE(item))
1705 {
1706 g_warning("<image> is not an SPImage. Why? ;-)");
1707 return false;
1708 }
1710 SPImage *img = SP_IMAGE(item);
1711 double ix = img->x.value;
1712 double iy = img->y.value;
1713 double iwidth = img->width.value;
1714 double iheight = img->height.value;
1716 NR::Rect ibbox(NR::Point(ix, iy), NR::Point(ix+iwidth, iy+iheight));
1717 ibbox = ibbox * tf;
1718 ix = ibbox.min()[NR::X];
1719 iy = ibbox.min()[NR::Y];
1720 //iwidth = ibbox.max()[NR::X] - ibbox.min()[NR::X];
1721 //iheight = ibbox.max()[NR::Y] - ibbox.min()[NR::Y];
1722 iwidth = xscale * iwidth;
1723 iheight = yscale * iheight;
1725 NR::Matrix itemTransform = getODFItemTransform(item);
1727 Glib::ustring itemTransformString = formatTransform(itemTransform);
1729 Glib::ustring href = getAttribute(node, "xlink:href");
1730 std::map<Glib::ustring, Glib::ustring>::iterator iter = imageTable.find(href);
1731 if (iter == imageTable.end())
1732 {
1733 g_warning("image '%s' not in table", href.c_str());
1734 return false;
1735 }
1736 Glib::ustring newName = iter->second;
1738 outs.printf("<draw:frame ");
1739 if (id.size() > 0)
1740 outs.printf("id=\"%s\" ", id.c_str());
1741 outs.printf("draw:style-name=\"gr1\" draw:text-style-name=\"P1\" draw:layer=\"layout\" ");
1742 //no x or y. make them the translate transform, last one
1743 outs.printf("svg:width=\"%.3fcm\" svg:height=\"%.3fcm\" ",
1744 iwidth, iheight);
1745 if (itemTransformString.size() > 0)
1746 {
1747 outs.printf("draw:transform=\"%s translate(%.3fcm, %.3fcm)\" ",
1748 itemTransformString.c_str(), ix, iy);
1749 }
1750 else
1751 {
1752 outs.printf("draw:transform=\"translate(%.3fcm, %.3fcm)\" ",
1753 ix, iy);
1754 }
1756 outs.printf(">\n");
1757 outs.printf(" <draw:image xlink:href=\"%s\" xlink:type=\"simple\"\n",
1758 newName.c_str());
1759 outs.printf(" xlink:show=\"embed\" xlink:actuate=\"onLoad\">\n");
1760 outs.printf(" <text:p/>\n");
1761 outs.printf(" </draw:image>\n");
1762 outs.printf("</draw:frame>\n");
1763 return true;
1764 }
1765 else if (SP_IS_SHAPE(item))
1766 {
1767 //g_message("### %s is a shape", nodeName.c_str());
1768 curve = sp_shape_get_curve(SP_SHAPE(item));
1769 }
1770 else if (SP_IS_TEXT(item) || SP_IS_FLOWTEXT(item))
1771 {
1772 curve = te_get_layout(item)->convertToCurves();
1773 }
1775 if (curve)
1776 {
1777 //### Default <path> output
1779 outs.printf("<draw:path ");
1780 if (id.size()>0)
1781 outs.printf("id=\"%s\" ", id.c_str());
1783 std::map<Glib::ustring, Glib::ustring>::iterator siter;
1784 siter = styleLookupTable.find(id);
1785 if (siter != styleLookupTable.end())
1786 {
1787 Glib::ustring styleName = siter->second;
1788 outs.printf("draw:style-name=\"%s\" ", styleName.c_str());
1789 }
1791 std::map<Glib::ustring, Glib::ustring>::iterator giter;
1792 giter = gradientLookupTable.find(id);
1793 if (giter != gradientLookupTable.end())
1794 {
1795 Glib::ustring gradientName = giter->second;
1796 outs.printf("draw:fill-gradient-name=\"%s\" ",
1797 gradientName.c_str());
1798 }
1800 outs.printf("draw:layer=\"layout\" svg:x=\"%.3fcm\" svg:y=\"%.3fcm\" ",
1801 bbox_x, bbox_y);
1802 outs.printf("svg:width=\"%.3fcm\" svg:height=\"%.3fcm\" ",
1803 bbox_width, bbox_height);
1804 outs.printf("svg:viewBox=\"0.0 0.0 %.3f %.3f\"\n",
1805 bbox_width * 1000.0, bbox_height * 1000.0);
1807 outs.printf(" svg:d=\"");
1808 int nrPoints = writePath(outs, SP_CURVE_BPATH(curve),
1809 tf, bbox_x, bbox_y);
1810 outs.printf("\"");
1812 outs.printf(">\n");
1813 outs.printf(" <!-- %d nodes -->\n", nrPoints);
1814 outs.printf("</draw:path>\n\n");
1817 sp_curve_unref(curve);
1818 }
1820 return true;
1821 }
1825 /**
1826 * Write the content.xml file. Writes the namesspace headers, then
1827 * calls writeStyle() and writeTree().
1828 */
1829 bool OdfOutput::writeContent(ZipFile &zf, Inkscape::XML::Node *node)
1830 {
1831 BufferOutputStream bouts;
1832 OutputStreamWriter outs(bouts);
1834 time_t tim;
1835 time(&tim);
1837 outs.printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1838 outs.printf("\n");
1839 outs.printf("\n");
1840 outs.printf("<!--\n");
1841 outs.printf("*************************************************************************\n");
1842 outs.printf(" file: content.xml\n");
1843 outs.printf(" Generated by Inkscape: %s", ctime(&tim)); //ctime has its own <cr>
1844 outs.printf(" http://www.inkscape.org\n");
1845 outs.printf("*************************************************************************\n");
1846 outs.printf("-->\n");
1847 outs.printf("\n");
1848 outs.printf("\n");
1849 outs.printf("<office:document-content\n");
1850 outs.printf(" xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\"\n");
1851 outs.printf(" xmlns:style=\"urn:oasis:names:tc:opendocument:xmlns:style:1.0\"\n");
1852 outs.printf(" xmlns:text=\"urn:oasis:names:tc:opendocument:xmlns:text:1.0\"\n");
1853 outs.printf(" xmlns:table=\"urn:oasis:names:tc:opendocument:xmlns:table:1.0\"\n");
1854 outs.printf(" xmlns:draw=\"urn:oasis:names:tc:opendocument:xmlns:drawing:1.0\"\n");
1855 outs.printf(" xmlns:fo=\"urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0\"\n");
1856 outs.printf(" xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n");
1857 outs.printf(" xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n");
1858 outs.printf(" xmlns:meta=\"urn:oasis:names:tc:opendocument:xmlns:meta:1.0\"\n");
1859 outs.printf(" xmlns:number=\"urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0\"\n");
1860 outs.printf(" xmlns:presentation=\"urn:oasis:names:tc:opendocument:xmlns:presentation:1.0\"\n");
1861 outs.printf(" xmlns:svg=\"urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0\"\n");
1862 outs.printf(" xmlns:chart=\"urn:oasis:names:tc:opendocument:xmlns:chart:1.0\"\n");
1863 outs.printf(" xmlns:dr3d=\"urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0\"\n");
1864 outs.printf(" xmlns:math=\"http://www.w3.org/1998/Math/MathML\"\n");
1865 outs.printf(" xmlns:form=\"urn:oasis:names:tc:opendocument:xmlns:form:1.0\"\n");
1866 outs.printf(" xmlns:script=\"urn:oasis:names:tc:opendocument:xmlns:script:1.0\"\n");
1867 outs.printf(" xmlns:ooo=\"http://openoffice.org/2004/office\"\n");
1868 outs.printf(" xmlns:ooow=\"http://openoffice.org/2004/writer\"\n");
1869 outs.printf(" xmlns:oooc=\"http://openoffice.org/2004/calc\"\n");
1870 outs.printf(" xmlns:dom=\"http://www.w3.org/2001/xml-events\"\n");
1871 outs.printf(" xmlns:xforms=\"http://www.w3.org/2002/xforms\"\n");
1872 outs.printf(" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n");
1873 outs.printf(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n");
1874 outs.printf(" xmlns:smil=\"urn:oasis:names:tc:opendocument:xmlns:smil-compatible:1.0\"\n");
1875 outs.printf(" xmlns:anim=\"urn:oasis:names:tc:opendocument:xmlns:animation:1.0\"\n");
1876 outs.printf(" office:version=\"1.0\">\n");
1877 outs.printf("\n");
1878 outs.printf("\n");
1879 outs.printf("<office:scripts/>\n");
1880 outs.printf("\n");
1881 outs.printf("\n");
1882 outs.printf("<!-- ######### CONVERSION FROM SVG STARTS ######## -->\n");
1883 outs.printf("<!--\n");
1884 outs.printf("*************************************************************************\n");
1885 outs.printf(" S T Y L E S\n");
1886 outs.printf(" Style entries have been pulled from the svg style and\n");
1887 outs.printf(" representation attributes in the SVG tree. The tree elements\n");
1888 outs.printf(" then refer to them by name, in the ODF manner\n");
1889 outs.printf("*************************************************************************\n");
1890 outs.printf("-->\n");
1891 outs.printf("\n");
1892 outs.printf("\n");
1894 if (!writeStyle(outs))
1895 {
1896 g_warning("Failed to write styles");
1897 return false;
1898 }
1900 outs.printf("\n");
1901 outs.printf("\n");
1902 outs.printf("\n");
1903 outs.printf("\n");
1904 outs.printf("<!--\n");
1905 outs.printf("*************************************************************************\n");
1906 outs.printf(" D R A W I N G\n");
1907 outs.printf(" This section is the heart of SVG-ODF conversion. We are\n");
1908 outs.printf(" starting with simple conversions, and will slowly evolve\n");
1909 outs.printf(" into a 'smarter' translation as time progresses. Any help\n");
1910 outs.printf(" in improving .odg export is welcome.\n");
1911 outs.printf("*************************************************************************\n");
1912 outs.printf("-->\n");
1913 outs.printf("\n");
1914 outs.printf("\n");
1915 outs.printf("<office:body>\n");
1916 outs.printf("<office:drawing>\n");
1917 outs.printf("<draw:page draw:name=\"page1\" draw:style-name=\"dp1\"\n");
1918 outs.printf(" draw:master-page-name=\"Default\">\n");
1919 outs.printf("\n");
1920 outs.printf("\n");
1922 if (!writeTree(outs, node))
1923 {
1924 g_warning("Failed to convert SVG tree");
1925 return false;
1926 }
1928 outs.printf("\n");
1929 outs.printf("\n");
1931 outs.printf("</draw:page>\n");
1932 outs.printf("</office:drawing>\n");
1934 outs.printf("\n");
1935 outs.printf("\n");
1936 outs.printf("<!-- ######### CONVERSION FROM SVG ENDS ######## -->\n");
1937 outs.printf("\n");
1938 outs.printf("\n");
1940 outs.printf("</office:body>\n");
1941 outs.printf("</office:document-content>\n");
1942 outs.printf("\n");
1943 outs.printf("\n");
1944 outs.printf("\n");
1945 outs.printf("<!--\n");
1946 outs.printf("*************************************************************************\n");
1947 outs.printf(" E N D O F F I L E\n");
1948 outs.printf(" Have a nice day - ishmal\n");
1949 outs.printf("*************************************************************************\n");
1950 outs.printf("-->\n");
1951 outs.printf("\n");
1952 outs.printf("\n");
1956 //Make our entry
1957 ZipEntry *ze = zf.newEntry("content.xml", "ODF master content file");
1958 ze->setUncompressedData(bouts.getBuffer());
1959 ze->finish();
1961 return true;
1962 }
1965 /**
1966 * Resets class to its pristine condition, ready to use again
1967 */
1968 void
1969 OdfOutput::reset()
1970 {
1971 metadata.clear();
1972 styleTable.clear();
1973 styleLookupTable.clear();
1974 gradientTable.clear();
1975 gradientLookupTable.clear();
1976 imageTable.clear();
1979 }
1982 /**
1983 * Descends into the SVG tree, mapping things to ODF when appropriate
1984 */
1985 void
1986 OdfOutput::save(Inkscape::Extension::Output *mod, SPDocument *doc, gchar const *uri)
1987 {
1988 reset();
1990 //g_message("native file:%s\n", uri);
1991 documentUri = URI(uri);
1993 ZipFile zf;
1994 preprocess(zf, doc->rroot);
1996 if (!writeManifest(zf))
1997 {
1998 g_warning("Failed to write manifest");
1999 return;
2000 }
2002 if (!writeMeta(zf))
2003 {
2004 g_warning("Failed to write metafile");
2005 return;
2006 }
2008 if (!writeContent(zf, doc->rroot))
2009 {
2010 g_warning("Failed to write content");
2011 return;
2012 }
2014 if (!zf.writeFile(uri))
2015 {
2016 return;
2017 }
2018 }
2021 /**
2022 * This is the definition of PovRay output. This function just
2023 * calls the extension system with the memory allocated XML that
2024 * describes the data.
2025 */
2026 void
2027 OdfOutput::init()
2028 {
2029 Inkscape::Extension::build_from_mem(
2030 "<inkscape-extension>\n"
2031 "<name>" N_("OpenDocument Drawing Output") "</name>\n"
2032 "<id>org.inkscape.output.odf</id>\n"
2033 "<output>\n"
2034 "<extension>.odg</extension>\n"
2035 "<mimetype>text/x-povray-script</mimetype>\n"
2036 "<filetypename>" N_("OpenDocument drawing (*.odg)") "</filetypename>\n"
2037 "<filetypetooltip>" N_("OpenDocument drawing file") "</filetypetooltip>\n"
2038 "</output>\n"
2039 "</inkscape-extension>",
2040 new OdfOutput());
2041 }
2043 /**
2044 * Make sure that we are in the database
2045 */
2046 bool
2047 OdfOutput::check (Inkscape::Extension::Extension *module)
2048 {
2049 /* We don't need a Key
2050 if (NULL == Inkscape::Extension::db.get(SP_MODULE_KEY_OUTPUT_POV))
2051 return FALSE;
2052 */
2054 return TRUE;
2055 }
2059 //########################################################################
2060 //# I N P U T
2061 //########################################################################
2065 //#######################
2066 //# L A T E R !!! :-)
2067 //#######################
2081 } //namespace Internal
2082 } //namespace Extension
2083 } //namespace Inkscape
2086 //########################################################################
2087 //# E N D O F F I L E
2088 //########################################################################
2090 /*
2091 Local Variables:
2092 mode:c++
2093 c-file-style:"stroustrup"
2094 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
2095 indent-tabs-mode:nil
2096 fill-column:99
2097 End:
2098 */
2099 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :