Code

f366a9fad76b17b6d87bc174c8cb6fe616a42a1e
[inkscape.git] / src / extension / internal / odf.cpp
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::io::OutputStreamWriter OutputStreamWriter;
94 typedef org::w3c::dom::io::BufferOutputStream BufferOutputStream;
95 typedef org::w3c::dom::io::StringOutputStream StringOutputStream;
97 //########################################################################
98 //# C L A S S    SingularValueDecomposition
99 //########################################################################
100 #include <math.h>
102 class SVDMatrix
104 public:
106     SVDMatrix()
107         {
108         init();
109         }
111     SVDMatrix(unsigned int rowSize, unsigned int colSize)
112         {
113         init();
114         rows = rowSize;
115         cols = colSize;
116         size = rows * cols;
117         d    = new double[size];
118         for (unsigned int i=0 ; i<size ; i++)
119             d[i] = 0.0;
120         }
122     SVDMatrix(double *vals, unsigned int rowSize, unsigned int colSize)
123         {
124         init();
125         rows = rowSize;
126         cols = colSize;
127         size = rows * cols;
128         d    = new double[size];
129         for (unsigned int i=0 ; i<size ; i++)
130             d[i] = vals[i];
131         }
134     SVDMatrix(const SVDMatrix &other)
135         {
136         init();
137         assign(other);
138         }
140     SVDMatrix &operator=(const SVDMatrix &other)
141         {
142         assign(other);
143         return *this;
144         }
146     virtual ~SVDMatrix()
147         {
148         delete[] d;
149         }
151      double& operator() (unsigned int row, unsigned int col)
152          {
153          if (row >= rows || col >= cols)
154              return badval;
155          return d[cols*row + col];
156          }
158      double operator() (unsigned int row, unsigned int col) const
159          {
160          if (row >= rows || col >= cols)
161              return badval;
162          return d[cols*row + col];
163          }
165      unsigned int getRows()
166          {
167          return rows;
168          }
170      unsigned int getCols()
171          {
172          return cols;
173          }
175      SVDMatrix multiply(const SVDMatrix &other)
176          {
177          if (cols != other.rows)
178              {
179              SVDMatrix dummy;
180              return dummy;
181              }
182          SVDMatrix result(rows, other.cols);
183          for (unsigned int i=0 ; i<rows ; i++)
184              {
185              for (unsigned int j=0 ; j<other.cols ; j++)
186                  {
187                  double sum = 0.0;
188                  for (unsigned int k=0 ; k<cols ; k++)
189                      {
190                      //sum += a[i][k] * b[k][j];
191                      sum += d[i*cols +k] * other(k, j);
192                      }
193                  result(i, j) = sum;
194                  }
196              }
197          return result;
198          }
200      SVDMatrix transpose()
201          {
202          SVDMatrix result(cols, rows);
203          for (unsigned int i=0 ; i<rows ; i++)
204              for (unsigned int j=0 ; j<cols ; j++)
205                  result(j, i) = d[i*cols + j];
206          return result;
207          }
209 private:
212     virtual void init()
213         {
214         badval = 0.0;
215         d      = NULL;
216         rows   = 0;
217         cols   = 0;
218         size   = 0;
219         }
221      void assign(const SVDMatrix &other)
222         {
223         if (d)
224             {
225             delete[] d;
226             d = 0;
227             }
228         rows = other.rows;
229         cols = other.cols;
230         size = other.size;
231         d = new double[size];
232         for (unsigned int i=0 ; i<size ; i++)
233             d[i] = other.d[i];
234         }
236     double badval;
238     double *d;
239     unsigned int rows;
240     unsigned int cols;
241     unsigned int size;
242 };
246 /**
247  *
248  * ====================================================
249  *
250  * NOTE:
251  * This class is ported almost verbatim from the public domain
252  * JAMA Matrix package.  It is modified to handle only 3x3 matrices
253  * and our NR::Matrix affine transform class.  We give full
254  * attribution to them, along with many thanks.  JAMA can be found at:
255  *     http://math.nist.gov/javanumerics/jama
256  *
257  * ====================================================
258  *
259  * Singular Value Decomposition.
260  * <P>
261  * For an m-by-n matrix A with m >= n, the singular value decomposition is
262  * an m-by-n orthogonal matrix U, an n-by-n diagonal matrix S, and
263  * an n-by-n orthogonal matrix V so that A = U*S*V'.
264  * <P>
265  * The singular values, sigma[k] = S[k][k], are ordered so that
266  * sigma[0] >= sigma[1] >= ... >= sigma[n-1].
267  * <P>
268  * The singular value decompostion always exists, so the constructor will
269  * never fail.  The matrix condition number and the effective numerical
270  * rank can be computed from this decomposition.
271  */
272 class SingularValueDecomposition
274 public:
276    /** Construct the singular value decomposition
277    @param A    Rectangular matrix
278    @return     Structure to access U, S and V.
279    */
281     SingularValueDecomposition (const SVDMatrix &mat)
282         {
283         A      = mat;
284         s      = NULL;
285         s_size = 0;
286         calculate();
287         }
289     virtual ~SingularValueDecomposition()
290         {
291         delete[] s;
292         }
294     /**
295      * Return the left singular vectors
296      * @return     U
297      */
298     SVDMatrix &getU();
300     /**
301      * Return the right singular vectors
302      * @return     V
303      */
304     SVDMatrix &getV();
306     /**
307      *  Return the s[index] value
308      */    double getS(unsigned int index);
310     /**
311      * Two norm
312      * @return max(S)
313      */
314     double norm2();
316     /**
317      * Two norm condition number
318      *  @return max(S)/min(S)
319      */
320     double cond();
322     /**
323      *  Effective numerical matrix rank
324      *  @return     Number of nonnegligible singular values.
325      */
326     int rank();
328 private:
330       void calculate();
332       SVDMatrix A;
333       SVDMatrix U;
334       double *s;
335       unsigned int s_size;
336       SVDMatrix V;
338 };
341 static double svd_hypot(double a, double b)
343     double r;
345     if (fabs(a) > fabs(b))
346         {
347         r = b/a;
348         r = fabs(a) * sqrt(1+r*r);
349         }
350     else if (b != 0)
351         {
352         r = a/b;
353         r = fabs(b) * sqrt(1+r*r);
354         }
355     else
356         {
357         r = 0.0;
358         }
359     return r;
364 void SingularValueDecomposition::calculate()
366       // Initialize.
367       int m = A.getRows();
368       int n = A.getCols();
370       int nu = (m > n) ? m : n;
371       s_size = (m+1 < n) ? m+1 : n;
372       s = new double[s_size];
373       U = SVDMatrix(m, nu);
374       V = SVDMatrix(n, n);
375       double *e = new double[n];
376       double *work = new double[m];
377       bool wantu = true;
378       bool wantv = true;
380       // Reduce A to bidiagonal form, storing the diagonal elements
381       // in s and the super-diagonal elements in e.
383       int nct = (m-1<n) ? m-1 : n;
384       int nrtx = (n-2<m) ? n-2 : m;
385       int nrt = (nrtx>0) ? nrtx : 0;
386       for (int k = 0; k < 2; k++) {
387          if (k < nct) {
389             // Compute the transformation for the k-th column and
390             // place the k-th diagonal in s[k].
391             // Compute 2-norm of k-th column without under/overflow.
392             s[k] = 0;
393             for (int i = k; i < m; i++) {
394                s[k] = svd_hypot(s[k],A(i, k));
395             }
396             if (s[k] != 0.0) {
397                if (A(k, k) < 0.0) {
398                   s[k] = -s[k];
399                }
400                for (int i = k; i < m; i++) {
401                   A(i, k) /= s[k];
402                }
403                A(k, k) += 1.0;
404             }
405             s[k] = -s[k];
406          }
407          for (int j = k+1; j < n; j++) {
408             if ((k < nct) & (s[k] != 0.0))  {
410             // Apply the transformation.
412                double t = 0;
413                for (int i = k; i < m; i++) {
414                   t += A(i, k) * A(i, j);
415                }
416                t = -t/A(k, k);
417                for (int i = k; i < m; i++) {
418                   A(i, j) += t*A(i, k);
419                }
420             }
422             // Place the k-th row of A into e for the
423             // subsequent calculation of the row transformation.
425             e[j] = A(k, j);
426          }
427          if (wantu & (k < nct)) {
429             // Place the transformation in U for subsequent back
430             // multiplication.
432             for (int i = k; i < m; i++) {
433                U(i, k) = A(i, k);
434             }
435          }
436          if (k < nrt) {
438             // Compute the k-th row transformation and place the
439             // k-th super-diagonal in e[k].
440             // Compute 2-norm without under/overflow.
441             e[k] = 0;
442             for (int i = k+1; i < n; i++) {
443                e[k] = svd_hypot(e[k],e[i]);
444             }
445             if (e[k] != 0.0) {
446                if (e[k+1] < 0.0) {
447                   e[k] = -e[k];
448                }
449                for (int i = k+1; i < n; i++) {
450                   e[i] /= e[k];
451                }
452                e[k+1] += 1.0;
453             }
454             e[k] = -e[k];
455             if ((k+1 < m) & (e[k] != 0.0)) {
457             // Apply the transformation.
459                for (int i = k+1; i < m; i++) {
460                   work[i] = 0.0;
461                }
462                for (int j = k+1; j < n; j++) {
463                   for (int i = k+1; i < m; i++) {
464                      work[i] += e[j]*A(i, j);
465                   }
466                }
467                for (int j = k+1; j < n; j++) {
468                   double t = -e[j]/e[k+1];
469                   for (int i = k+1; i < m; i++) {
470                      A(i, j) += t*work[i];
471                   }
472                }
473             }
474             if (wantv) {
476             // Place the transformation in V for subsequent
477             // back multiplication.
479                for (int i = k+1; i < n; i++) {
480                   V(i, k) = e[i];
481                }
482             }
483          }
484       }
486       // Set up the final bidiagonal matrix or order p.
488       int p = (n < m+1) ? n : m+1;
489       if (nct < n) {
490          s[nct] = A(nct, nct);
491       }
492       if (m < p) {
493          s[p-1] = 0.0;
494       }
495       if (nrt+1 < p) {
496          e[nrt] = A(nrt, p-1);
497       }
498       e[p-1] = 0.0;
500       // If required, generate U.
502       if (wantu) {
503          for (int j = nct; j < nu; j++) {
504             for (int i = 0; i < m; i++) {
505                U(i, j) = 0.0;
506             }
507             U(j, j) = 1.0;
508          }
509          for (int k = nct-1; k >= 0; k--) {
510             if (s[k] != 0.0) {
511                for (int j = k+1; j < nu; j++) {
512                   double t = 0;
513                   for (int i = k; i < m; i++) {
514                      t += U(i, k)*U(i, j);
515                   }
516                   t = -t/U(k, k);
517                   for (int i = k; i < m; i++) {
518                      U(i, j) += t*U(i, k);
519                   }
520                }
521                for (int i = k; i < m; i++ ) {
522                   U(i, k) = -U(i, k);
523                }
524                U(k, k) = 1.0 + U(k, k);
525                for (int i = 0; i < k-1; i++) {
526                   U(i, k) = 0.0;
527                }
528             } else {
529                for (int i = 0; i < m; i++) {
530                   U(i, k) = 0.0;
531                }
532                U(k, k) = 1.0;
533             }
534          }
535       }
537       // If required, generate V.
539       if (wantv) {
540          for (int k = n-1; k >= 0; k--) {
541             if ((k < nrt) & (e[k] != 0.0)) {
542                for (int j = k+1; j < nu; j++) {
543                   double t = 0;
544                   for (int i = k+1; i < n; i++) {
545                      t += V(i, k)*V(i, j);
546                   }
547                   t = -t/V(k+1, k);
548                   for (int i = k+1; i < n; i++) {
549                      V(i, j) += t*V(i, k);
550                   }
551                }
552             }
553             for (int i = 0; i < n; i++) {
554                V(i, k) = 0.0;
555             }
556             V(k, k) = 1.0;
557          }
558       }
560       // Main iteration loop for the singular values.
562       int pp = p-1;
563       int iter = 0;
564       //double eps = pow(2.0,-52.0);
565       //double tiny = pow(2.0,-966.0);
566       //let's just calculate these now
567       //a double can be e Â± 308.25, so this is safe
568       double eps = 2.22e-16;
569       double tiny = 1.6e-291;
570       while (p > 0) {
571          int k,kase;
573          // Here is where a test for too many iterations would go.
575          // This section of the program inspects for
576          // negligible elements in the s and e arrays.  On
577          // completion the variables kase and k are set as follows.
579          // kase = 1     if s(p) and e[k-1] are negligible and k<p
580          // kase = 2     if s(k) is negligible and k<p
581          // kase = 3     if e[k-1] is negligible, k<p, and
582          //              s(k), ..., s(p) are not negligible (qr step).
583          // kase = 4     if e(p-1) is negligible (convergence).
585          for (k = p-2; k >= -1; k--) {
586             if (k == -1) {
587                break;
588             }
589             if (fabs(e[k]) <=
590                   tiny + eps*(fabs(s[k]) + fabs(s[k+1]))) {
591                e[k] = 0.0;
592                break;
593             }
594          }
595          if (k == p-2) {
596             kase = 4;
597          } else {
598             int ks;
599             for (ks = p-1; ks >= k; ks--) {
600                if (ks == k) {
601                   break;
602                }
603                double t = (ks != p ? fabs(e[ks]) : 0.) +
604                           (ks != k+1 ? fabs(e[ks-1]) : 0.);
605                if (fabs(s[ks]) <= tiny + eps*t)  {
606                   s[ks] = 0.0;
607                   break;
608                }
609             }
610             if (ks == k) {
611                kase = 3;
612             } else if (ks == p-1) {
613                kase = 1;
614             } else {
615                kase = 2;
616                k = ks;
617             }
618          }
619          k++;
621          // Perform the task indicated by kase.
623          switch (kase) {
625             // Deflate negligible s(p).
627             case 1: {
628                double f = e[p-2];
629                e[p-2] = 0.0;
630                for (int j = p-2; j >= k; j--) {
631                   double t = svd_hypot(s[j],f);
632                   double cs = s[j]/t;
633                   double sn = f/t;
634                   s[j] = t;
635                   if (j != k) {
636                      f = -sn*e[j-1];
637                      e[j-1] = cs*e[j-1];
638                   }
639                   if (wantv) {
640                      for (int i = 0; i < n; i++) {
641                         t = cs*V(i, j) + sn*V(i, p-1);
642                         V(i, p-1) = -sn*V(i, j) + cs*V(i, p-1);
643                         V(i, j) = t;
644                      }
645                   }
646                }
647             }
648             break;
650             // Split at negligible s(k).
652             case 2: {
653                double f = e[k-1];
654                e[k-1] = 0.0;
655                for (int j = k; j < p; j++) {
656                   double t = svd_hypot(s[j],f);
657                   double cs = s[j]/t;
658                   double sn = f/t;
659                   s[j] = t;
660                   f = -sn*e[j];
661                   e[j] = cs*e[j];
662                   if (wantu) {
663                      for (int i = 0; i < m; i++) {
664                         t = cs*U(i, j) + sn*U(i, k-1);
665                         U(i, k-1) = -sn*U(i, j) + cs*U(i, k-1);
666                         U(i, j) = t;
667                      }
668                   }
669                }
670             }
671             break;
673             // Perform one qr step.
675             case 3: {
677                // Calculate the shift.
679                double scale = fabs(s[p-1]);
680                double d = fabs(s[p-2]);
681                if (d>scale) scale=d;
682                d = fabs(e[p-2]);
683                if (d>scale) scale=d;
684                d = fabs(s[k]);
685                if (d>scale) scale=d;
686                d = fabs(e[k]);
687                if (d>scale) scale=d;
688                double sp = s[p-1]/scale;
689                double spm1 = s[p-2]/scale;
690                double epm1 = e[p-2]/scale;
691                double sk = s[k]/scale;
692                double ek = e[k]/scale;
693                double b = ((spm1 + sp)*(spm1 - sp) + epm1*epm1)/2.0;
694                double c = (sp*epm1)*(sp*epm1);
695                double shift = 0.0;
696                if ((b != 0.0) | (c != 0.0)) {
697                   shift = sqrt(b*b + c);
698                   if (b < 0.0) {
699                      shift = -shift;
700                   }
701                   shift = c/(b + shift);
702                }
703                double f = (sk + sp)*(sk - sp) + shift;
704                double g = sk*ek;
706                // Chase zeros.
708                for (int j = k; j < p-1; j++) {
709                   double t = svd_hypot(f,g);
710                   double cs = f/t;
711                   double sn = g/t;
712                   if (j != k) {
713                      e[j-1] = t;
714                   }
715                   f = cs*s[j] + sn*e[j];
716                   e[j] = cs*e[j] - sn*s[j];
717                   g = sn*s[j+1];
718                   s[j+1] = cs*s[j+1];
719                   if (wantv) {
720                      for (int i = 0; i < n; i++) {
721                         t = cs*V(i, j) + sn*V(i, j+1);
722                         V(i, j+1) = -sn*V(i, j) + cs*V(i, j+1);
723                         V(i, j) = t;
724                      }
725                   }
726                   t = svd_hypot(f,g);
727                   cs = f/t;
728                   sn = g/t;
729                   s[j] = t;
730                   f = cs*e[j] + sn*s[j+1];
731                   s[j+1] = -sn*e[j] + cs*s[j+1];
732                   g = sn*e[j+1];
733                   e[j+1] = cs*e[j+1];
734                   if (wantu && (j < m-1)) {
735                      for (int i = 0; i < m; i++) {
736                         t = cs*U(i, j) + sn*U(i, j+1);
737                         U(i, j+1) = -sn*U(i, j) + cs*U(i, j+1);
738                         U(i, j) = t;
739                      }
740                   }
741                }
742                e[p-2] = f;
743                iter = iter + 1;
744             }
745             break;
747             // Convergence.
749             case 4: {
751                // Make the singular values positive.
753                if (s[k] <= 0.0) {
754                   s[k] = (s[k] < 0.0 ? -s[k] : 0.0);
755                   if (wantv) {
756                      for (int i = 0; i <= pp; i++) {
757                         V(i, k) = -V(i, k);
758                      }
759                   }
760                }
762                // Order the singular values.
764                while (k < pp) {
765                   if (s[k] >= s[k+1]) {
766                      break;
767                   }
768                   double t = s[k];
769                   s[k] = s[k+1];
770                   s[k+1] = t;
771                   if (wantv && (k < n-1)) {
772                      for (int i = 0; i < n; i++) {
773                         t = V(i, k+1); V(i, k+1) = V(i, k); V(i, k) = t;
774                      }
775                   }
776                   if (wantu && (k < m-1)) {
777                      for (int i = 0; i < m; i++) {
778                         t = U(i, k+1); U(i, k+1) = U(i, k); U(i, k) = t;
779                      }
780                   }
781                   k++;
782                }
783                iter = 0;
784                p--;
785             }
786             break;
787          }
788       }
790     delete e;
791     delete work;
797 /**
798  * Return the left singular vectors
799  * @return     U
800  */
801 SVDMatrix &SingularValueDecomposition::getU()
803     return U;
806 /**
807  * Return the right singular vectors
808  * @return     V
809  */
811 SVDMatrix &SingularValueDecomposition::getV()
813     return V;
816 /**
817  *  Return the s[0] value
818  */
819 double SingularValueDecomposition::getS(unsigned int index)
821     if (index >= s_size)
822         return 0.0;
823     return s[index];
826 /**
827  * Two norm
828  * @return     max(S)
829  */
830 double SingularValueDecomposition::norm2()
832     return s[0];
835 /**
836  * Two norm condition number
837  *  @return     max(S)/min(S)
838  */
840 double SingularValueDecomposition::cond()
842     return s[0]/s[2];
845 /**
846  *  Effective numerical matrix rank
847  *  @return     Number of nonnegligible singular values.
848  */
849 int SingularValueDecomposition::rank()
851     double eps = pow(2.0,-52.0);
852     double tol = 3.0*s[0]*eps;
853     int r = 0;
854     for (int i = 0; i < 3; i++)
855         {
856         if (s[i] > tol)
857             r++;
858         }
859     return r;
862 //########################################################################
863 //# E N D    C L A S S    SingularValueDecomposition
864 //########################################################################
870 #define pi 3.14159
871 //#define pxToCm  0.0275
872 #define pxToCm  0.03
873 #define piToRad 0.0174532925
874 #define docHeightCm 22.86
877 //########################################################################
878 //# O U T P U T
879 //########################################################################
881 /**
882  * Get the value of a node/attribute pair
883  */
884 static std::string getAttribute( Inkscape::XML::Node *node, char *attrName)
886     std::string val;
887     char *valstr = (char *)node->attribute(attrName);
888     if (valstr)
889         val = (const char *)valstr;
890     return val;
895 /**
896  * Get the extension suffix from the end of a file name
897  */
898 static std::string getExtension(const std::string &fname)
900     std::string ext;
902     unsigned int pos = fname.rfind('.');
903     if (pos == fname.npos)
904         {
905         ext = "";
906         }
907     else
908         {
909         ext = fname.substr(pos);
910         }
911     return ext;
915 static std::string formatTransform(NR::Matrix &tf)
917     std::string str;
918     if (!tf.test_identity())
919         {
920         StringOutputStream outs;
921         OutputStreamWriter out(outs);
922         out.printf("matrix(%.3f %.3f %.3f %.3f %.3f %.3f)",
923                 tf[0], tf[1], tf[2], tf[3], tf[4], tf[5]);
924         str = outs.getString();
925         }
926     return str;
933 /**
934  * Get the general transform from SVG pixels to
935  * ODF cm
936  */
937 static NR::Matrix getODFTransform(const SPItem *item)
939     //### Get SVG-to-ODF transform
940     NR::Matrix tf;
941     tf                   = sp_item_i2d_affine(item);
942     //Flip Y into document coordinates
943     double doc_height    = sp_document_height(SP_ACTIVE_DOCUMENT);
944     NR::Matrix doc2dt_tf = NR::Matrix(NR::scale(1.0, -1.0));
945     doc2dt_tf            = doc2dt_tf * NR::Matrix(NR::translate(0, doc_height));
946     tf                   = tf * doc2dt_tf;
947     tf                   = tf * NR::Matrix(NR::scale(pxToCm));
948     return tf;
954 /**
955  * Get the bounding box of an item, as mapped onto
956  * an ODF document, in cm.
957  */
958 static NR::Rect getODFBoundingBox(const SPItem *item)
960     NR::Rect bbox        = sp_item_bbox_desktop((SPItem *)item);
961     double doc_height    = sp_document_height(SP_ACTIVE_DOCUMENT);
962     NR::Matrix doc2dt_tf = NR::Matrix(NR::scale(1.0, -1.0));
963     doc2dt_tf            = doc2dt_tf * NR::Matrix(NR::translate(0, doc_height));
964     bbox                 = bbox * doc2dt_tf;
965     bbox                 = bbox * NR::Matrix(NR::scale(pxToCm));
966     return bbox;
971 /**
972  * Get the transform for an item, correcting for
973  * handedness reversal
974  */
975 static NR::Matrix getODFItemTransform(const SPItem *item)
977     NR::Matrix itemTransform = NR::Matrix(NR::scale(1, -1));
978     itemTransform = itemTransform * item->transform;
979     itemTransform = itemTransform * NR::Matrix(NR::scale(1, -1));
980     return itemTransform;
985 /**
986  * Get some fun facts from the transform
987  */
988 static void analyzeTransform(NR::Matrix &tf,
989            double &rotate, double &xskew, double &yskew,
990            double &xscale, double &yscale)
992     SVDMatrix mat(2, 2);
993     mat(0, 0) = tf[0];
994     mat(0, 1) = tf[1];
995     mat(1, 0) = tf[2];
996     mat(1, 1) = tf[3];
998     SingularValueDecomposition svd(mat);
1000     SVDMatrix U = svd.getU();
1001     SVDMatrix V = svd.getV();
1002     SVDMatrix Vt = V.transpose();
1003     SVDMatrix UVt = U.multiply(Vt);
1004     double s0 = svd.getS(0);
1005     double s1 = svd.getS(1);
1006     xscale = s0;
1007     yscale = s1;
1008     //g_message("## s0:%.3f s1:%.3f", s0, s1);
1009     //g_message("## u:%.3f %.3f %.3f %.3f", U(0,0), U(0,1), U(1,0), U(1,1));
1010     //g_message("## v:%.3f %.3f %.3f %.3f", V(0,0), V(0,1), V(1,0), V(1,1));
1011     //g_message("## vt:%.3f %.3f %.3f %.3f", Vt(0,0), Vt(0,1), Vt(1,0), Vt(1,1));
1012     //g_message("## uvt:%.3f %.3f %.3f %.3f", UVt(0,0), UVt(0,1), UVt(1,0), UVt(1,1));
1013     rotate = UVt(0,0);
1018 static void gatherText(Inkscape::XML::Node *node, std::string &buf)
1020     if (node->type() == Inkscape::XML::TEXT_NODE)
1021         {
1022         char *s = (char *)node->content();
1023         if (s)
1024             buf.append(s);
1025         }
1026     
1027     for (Inkscape::XML::Node *child = node->firstChild() ;
1028                 child != NULL; child = child->next())
1029         {
1030         gatherText(child, buf);
1031         }
1035 /**
1036  * FIRST PASS.
1037  * Method descends into the repr tree, converting image, style, and gradient info
1038  * into forms compatible in ODF.
1039  */
1040 void
1041 OdfOutput::preprocess(ZipFile &zf, Inkscape::XML::Node *node)
1044     std::string nodeName = node->name();
1045     std::string id       = getAttribute(node, "id");
1047     //### First, check for metadata
1048     if (nodeName == "metadata" || nodeName == "svg:metadata")
1049         {
1050         Inkscape::XML::Node *mchild = node->firstChild() ;
1051         if (!mchild || strcmp(mchild->name(), "rdf:RDF"))
1052             return;
1053         Inkscape::XML::Node *rchild = mchild->firstChild() ;
1054         if (!rchild || strcmp(rchild->name(), "cc:Work"))
1055             return;
1056         for (Inkscape::XML::Node *cchild = rchild->firstChild() ;
1057             cchild ; cchild = cchild->next())
1058             {
1059             std::string ccName = cchild->name();
1060             std::string ccVal;
1061             gatherText(cchild, ccVal);
1062             //g_message("ccName: %s  ccVal:%s", ccName.c_str(), ccVal.c_str());
1063             metadata[ccName] = ccVal;
1064             }
1065         return;
1066         }
1068     //Now consider items.
1069     SPObject *reprobj = SP_ACTIVE_DOCUMENT->getObjectByRepr(node);
1070     if (!reprobj)
1071         return;
1072     if (!SP_IS_ITEM(reprobj))
1073         {
1074         return;
1075         }
1076     SPItem *item  = SP_ITEM(reprobj);
1077     //### Get SVG-to-ODF transform
1078     NR::Matrix tf = getODFTransform(item);
1080     if (nodeName == "image" || nodeName == "svg:image")
1081         {
1082         //g_message("image");
1083         std::string href = getAttribute(node, "xlink:href");
1084         if (href.size() > 0)
1085             {
1086             std::string oldName = href;
1087             std::string ext = getExtension(oldName);
1088             if (ext == ".jpeg")
1089                 ext = ".jpg";
1090             if (imageTable.find(oldName) == imageTable.end())
1091                 {
1092                 char buf[64];
1093                 snprintf(buf, 63, "Pictures/image%d%s",
1094                     (int)imageTable.size(), ext.c_str());
1095                 std::string newName = buf;
1096                 imageTable[oldName] = newName;
1097                 std::string comment = "old name was: ";
1098                 comment.append(oldName);
1099                 URI oldUri(oldName);
1100                 //g_message("oldpath:%s", oldUri.getNativePath().c_str());
1101                 //# if relative to the documentURI, get proper path
1102                 URI resUri = documentUri.resolve(oldUri);
1103                 DOMString pathName = resUri.getNativePath();
1104                 //g_message("native path:%s", pathName.c_str());
1105                 ZipEntry *ze = zf.addFile(pathName, comment);
1106                 if (ze)
1107                     {
1108                     ze->setFileName(newName);
1109                     }
1110                 else
1111                     {
1112                     g_warning("Could not load image file '%s'", pathName.c_str());
1113                     }
1114                 }
1115             }
1116         }
1120     //###### Get style
1121     SPStyle *style = SP_OBJECT_STYLE(item);
1122     if (style && id.size()>0)
1123         {
1124         bool isGradient = false;
1126         StyleInfo si;
1127         //## Style.  Look in writeStyle() below to see what info
1128         //   we need to read into StyleInfo.  Note that we need to
1129         //   determine whether information goes into a style element
1130         //   or a gradient element.
1131         //## FILL
1132         if (style->fill.type == SP_PAINT_TYPE_COLOR)
1133             {
1134             guint32 fillCol =
1135                 sp_color_get_rgba32_ualpha(&style->fill.value.color, 0);
1136             char buf[16];
1137             int r = (fillCol >> 24) & 0xff;
1138             int g = (fillCol >> 16) & 0xff;
1139             int b = (fillCol >>  8) & 0xff;
1140             //g_message("## %s %lx", id.c_str(), (unsigned int)fillCol);
1141             snprintf(buf, 15, "#%02x%02x%02x", r, g, b);
1142             si.fillColor = buf;
1143             si.fill      = "solid";
1144             double opacityPercent = 100.0 *
1145                  (SP_SCALE24_TO_FLOAT(style->fill_opacity.value));
1146             snprintf(buf, 15, "%.3f%%", opacityPercent);
1147             si.fillOpacity = buf;
1148             }
1149         else if (style->fill.type == SP_PAINT_TYPE_PAINTSERVER)
1150             {
1151             //## Gradient.  Look in writeStyle() below to see what info
1152             //   we need to read into GradientInfo.
1153             if (!SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)))
1154                 return;
1155             isGradient = true;
1156             GradientInfo gi;
1157             SPGradient *gradient = SP_GRADIENT(SP_STYLE_FILL_SERVER(style));
1158             if (SP_IS_LINEARGRADIENT(gradient))
1159                 {
1160                 gi.style = "linear";
1161                 SPLinearGradient *linGrad = SP_LINEARGRADIENT(gradient);
1162                 gi.x1 = linGrad->x1.value;
1163                 gi.y1 = linGrad->y1.value;
1164                 gi.x2 = linGrad->x2.value;
1165                 gi.y2 = linGrad->y2.value;
1166                 }
1167             else if (SP_IS_RADIALGRADIENT(gradient))
1168                 {
1169                 gi.style = "radial";
1170                 SPRadialGradient *radGrad = SP_RADIALGRADIENT(gradient);
1171                 gi.cx = radGrad->cx.computed * 100.0;//ODG cx is percentages
1172                 gi.cy = radGrad->cy.computed * 100.0;
1173                 }
1174             else
1175                 {
1176                 g_warning("not a supported gradient type");
1177                 }
1179             //Look for existing identical style;
1180             bool gradientMatch = false;
1181             std::vector<GradientInfo>::iterator iter;
1182             for (iter=gradientTable.begin() ; iter!=gradientTable.end() ; iter++)
1183                 {
1184                 if (gi.equals(*iter))
1185                     {
1186                     //map to existing gradientTable entry
1187                     std::string gradientName = iter->name;
1188                     //g_message("found duplicate style:%s", gradientName.c_str());
1189                     gradientLookupTable[id] = gradientName;
1190                     gradientMatch = true;
1191                     break;
1192                     }
1193                 }
1194             //None found, make a new pair or entries
1195             if (!gradientMatch)
1196                 {
1197                 char buf[16];
1198                 snprintf(buf, 15, "gradient%d", (int)gradientTable.size());
1199                 std::string gradientName = buf;
1200                 gi.name = gradientName;
1201                 gradientTable.push_back(gi);
1202                 gradientLookupTable[id] = gradientName;
1203                 }
1204             }
1206         //## STROKE
1207         if (style->stroke.type == SP_PAINT_TYPE_COLOR)
1208             {
1209             guint32 strokeCol =
1210                 sp_color_get_rgba32_ualpha(&style->stroke.value.color, 0);
1211             char buf[16];
1212             int r = (strokeCol >> 24) & 0xff;
1213             int g = (strokeCol >> 16) & 0xff;
1214             int b = (strokeCol >>  8) & 0xff;
1215             snprintf(buf, 15, "#%02x%02x%02x", r, g, b);
1216             si.strokeColor = buf;
1217             snprintf(buf, 15, "%.3fpt", style->stroke_width.value);
1218             si.strokeWidth = buf;
1219             si.stroke      = "solid";
1220             double opacityPercent = 100.0 *
1221                  (SP_SCALE24_TO_FLOAT(style->stroke_opacity.value));
1222             snprintf(buf, 15, "%.3f%%", opacityPercent);
1223             si.strokeOpacity = buf;
1224             }
1226         if (!isGradient)
1227             {
1228             //Look for existing identical style;
1229             bool styleMatch = false;
1230             std::vector<StyleInfo>::iterator iter;
1231             for (iter=styleTable.begin() ; iter!=styleTable.end() ; iter++)
1232                 {
1233                 if (si.equals(*iter))
1234                     {
1235                     //map to existing styleTable entry
1236                     std::string styleName = iter->name;
1237                     //g_message("found duplicate style:%s", styleName.c_str());
1238                     styleLookupTable[id] = styleName;
1239                     styleMatch = true;
1240                     break;
1241                     }
1242                 }
1243             //None found, make a new pair or entries
1244             if (!styleMatch)
1245                 {
1246                 char buf[16];
1247                 snprintf(buf, 15, "style%d", (int)styleTable.size());
1248                 std::string styleName = buf;
1249                 si.name = styleName;
1250                 styleTable.push_back(si);
1251                 styleLookupTable[id] = styleName;
1252                 }
1253             }
1254         }
1256     for (Inkscape::XML::Node *child = node->firstChild() ;
1257             child ; child = child->next())
1258         preprocess(zf, child);
1263 /**
1264  * Writes the manifest.  Currently it only changes according to the
1265  * file names of images packed into the zip file.
1266  */
1267 bool OdfOutput::writeManifest(ZipFile &zf)
1269     BufferOutputStream bouts;
1270     OutputStreamWriter outs(bouts);
1272     time_t tim;
1273     time(&tim);
1275     outs.printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1276     outs.printf("<!DOCTYPE manifest:manifest PUBLIC \"-//OpenOffice.org//DTD Manifest 1.0//EN\" \"Manifest.dtd\">\n");
1277     outs.printf("\n");
1278     outs.printf("\n");
1279     outs.printf("<!--\n");
1280     outs.printf("*************************************************************************\n");
1281     outs.printf("  file:  manifest.xml\n");
1282     outs.printf("  Generated by Inkscape: %s", ctime(&tim)); //ctime has its own <cr>
1283     outs.printf("  http://www.inkscape.org\n");
1284     outs.printf("*************************************************************************\n");
1285     outs.printf("-->\n");
1286     outs.printf("\n");
1287     outs.printf("\n");
1288     outs.printf("<manifest:manifest xmlns:manifest=\"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0\">\n");
1289     outs.printf("    <manifest:file-entry manifest:media-type=\"application/vnd.oasis.opendocument.graphics\" manifest:full-path=\"/\"/>\n");
1290     outs.printf("    <manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"content.xml\"/>\n");
1291     outs.printf("    <manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"meta.xml\"/>\n");
1292     outs.printf("    <!--List our images here-->\n");
1293     std::map<std::string, std::string>::iterator iter;
1294     for (iter = imageTable.begin() ; iter!=imageTable.end() ; iter++)
1295         {
1296         std::string oldName = iter->first;
1297         std::string newName = iter->second;
1299         std::string ext = getExtension(oldName);
1300         if (ext == ".jpeg")
1301             ext = ".jpg";
1302         outs.printf("    <manifest:file-entry manifest:media-type=\"");
1303         if (ext == ".gif")
1304             outs.printf("image/gif");
1305         else if (ext == ".png")
1306             outs.printf("image/png");
1307         else if (ext == ".jpg")
1308             outs.printf("image/jpeg");
1309         outs.printf("\" manifest:full-path=\"");
1310         outs.printf((char *)newName.c_str());
1311         outs.printf("\"/>\n");
1312         }
1313     outs.printf("</manifest:manifest>\n");
1315     outs.close();
1317     //Make our entry
1318     ZipEntry *ze = zf.newEntry("META-INF/manifest.xml", "ODF file manifest");
1319     ze->setUncompressedData(bouts.getBuffer());
1320     ze->finish();
1322     return true;
1326 /**
1327  * This writes the document meta information to meta.xml
1328  */
1329 bool OdfOutput::writeMeta(ZipFile &zf)
1331     BufferOutputStream bouts;
1332     OutputStreamWriter outs(bouts);
1334     time_t tim;
1335     time(&tim);
1337     std::map<std::string, std::string>::iterator iter;
1338     std::string creator = "unknown";
1339     iter = metadata.find("dc:creator");
1340     if (iter != metadata.end())
1341         creator = iter->second;
1342     std::string date = "";
1343     iter = metadata.find("dc:date");
1344     if (iter != metadata.end())
1345         date = iter->second;
1347     outs.printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1348     outs.printf("\n");
1349     outs.printf("\n");
1350     outs.printf("<!--\n");
1351     outs.printf("*************************************************************************\n");
1352     outs.printf("  file:  meta.xml\n");
1353     outs.printf("  Generated by Inkscape: %s", ctime(&tim)); //ctime has its own <cr>
1354     outs.printf("  http://www.inkscape.org\n");
1355     outs.printf("*************************************************************************\n");
1356     outs.printf("-->\n");
1357     outs.printf("\n");
1358     outs.printf("\n");
1359     outs.printf("<office:document-meta\n");
1360     outs.printf("xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\"\n");
1361     outs.printf("xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n");
1362     outs.printf("xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n");
1363     outs.printf("xmlns:meta=\"urn:oasis:names:tc:opendocument:xmlns:meta:1.0\"\n");
1364     outs.printf("xmlns:presentation=\"urn:oasis:names:tc:opendocument:xmlns:presentation:1.0\"\n");
1365     outs.printf("xmlns:ooo=\"http://openoffice.org/2004/office\"\n");
1366     outs.printf("xmlns:smil=\"urn:oasis:names:tc:opendocument:xmlns:smil-compatible:1.0\"\n");
1367     outs.printf("xmlns:anim=\"urn:oasis:names:tc:opendocument:xmlns:animation:1.0\"\n");
1368     outs.printf("office:version=\"1.0\">\n");
1369     outs.printf("<office:meta>\n");
1370     outs.printf("    <meta:generator>Inkscape.org - 0.45</meta:generator>\n");
1371     outs.printf("    <meta:initial-creator>%s</meta:initial-creator>\n",
1372                           creator.c_str());
1373     outs.printf("    <meta:creation-date>%s</meta:creation-date>\n", date.c_str());
1374     for (iter = metadata.begin() ; iter != metadata.end() ; iter++)
1375         {
1376         std::string name  = iter->first;
1377         std::string value = iter->second;
1378         if (name.size() > 0 && value.size()>0)
1379             {
1380             outs.printf("    <%s>%s</%s>\n", 
1381                  name.c_str(), value.c_str(), name.c_str());
1382             }
1383         }
1384     outs.printf("    <meta:editing-cycles>2</meta:editing-cycles>\n");
1385     outs.printf("    <meta:editing-duration>PT56S</meta:editing-duration>\n");
1386     outs.printf("    <meta:user-defined meta:name=\"Info 1\"/>\n");
1387     outs.printf("    <meta:user-defined meta:name=\"Info 2\"/>\n");
1388     outs.printf("    <meta:user-defined meta:name=\"Info 3\"/>\n");
1389     outs.printf("    <meta:user-defined meta:name=\"Info 4\"/>\n");
1390     outs.printf("    <meta:document-statistic meta:object-count=\"2\"/>\n");
1391     outs.printf("</office:meta>\n");
1392     outs.printf("</office:document-meta>\n");
1393     outs.printf("\n");
1394     outs.printf("\n");
1397     outs.close();
1399     //Make our entry
1400     ZipEntry *ze = zf.newEntry("meta.xml", "ODF info file");
1401     ze->setUncompressedData(bouts.getBuffer());
1402     ze->finish();
1404     return true;
1410 /**
1411  * This is called just before writeTree(), since it will write style and
1412  * gradient information above the <draw> tag in the content.xml file
1413  */
1414 bool OdfOutput::writeStyle(Writer &outs)
1416     outs.printf("<office:automatic-styles>\n");
1417     outs.printf("<!-- ####### 'Standard' styles ####### -->\n");
1418     outs.printf("<style:style style:name=\"dp1\" style:family=\"drawing-page\"/>\n");
1419     outs.printf("<style:style style:name=\"gr1\" style:family=\"graphic\" style:parent-style-name=\"standard\">\n");
1420     outs.printf("  <style:graphic-properties draw:stroke=\"none\" draw:fill=\"none\"\n");
1421     outs.printf("       draw:textarea-horizontal-align=\"center\"\n");
1422     outs.printf("       draw:textarea-vertical-align=\"middle\" draw:color-mode=\"standard\"\n");
1423     outs.printf("       draw:luminance=\"0%%\" draw:contrast=\"0%%\" draw:gamma=\"100%%\" draw:red=\"0%%\"\n");
1424     outs.printf("       draw:green=\"0%%\" draw:blue=\"0%%\" fo:clip=\"rect(0cm 0cm 0cm 0cm)\"\n");
1425     outs.printf("       draw:image-opacity=\"100%%\" style:mirror=\"none\"/>\n");
1426     outs.printf("</style:style>\n");
1427     outs.printf("<style:style style:name=\"P1\" style:family=\"paragraph\">\n");
1428     outs.printf("  <style:paragraph-properties fo:text-align=\"center\"/>\n");
1429     outs.printf("</style:style>\n");
1431     /*
1432     ==========================================================
1433     Dump our style table.  Styles should have a general layout
1434     something like the following.  Look in:
1435     http://books.evc-cit.info/odbook/ch06.html#draw-style-file-section
1436     for style and gradient information.
1437     <style:style style:name="gr13"
1438       style:family="graphic" style:parent-style-name="standard">
1439         <style:graphic-properties draw:stroke="solid"
1440             svg:stroke-width="0.1cm"
1441             svg:stroke-color="#ff0000"
1442             draw:fill="solid" draw:fill-color="#e6e6ff"/>
1443     </style:style>
1444     ==========================================================
1445     */
1446     outs.printf("<!-- ####### Styles from Inkscape document ####### -->\n");
1447     std::vector<StyleInfo>::iterator iter;
1448     for (iter = styleTable.begin() ; iter != styleTable.end() ; iter++)
1449         {
1450         outs.printf("<style:style style:name=\"%s\"", iter->name.c_str());
1451         StyleInfo s(*iter);
1452         outs.printf(" style:family=\"graphic\" style:parent-style-name=\"standard\">\n");
1453         outs.printf("  <style:graphic-properties");
1454         outs.printf(" draw:fill=\"%s\" ", s.fill.c_str());
1455         if (s.fill != "none")
1456             {
1457             outs.printf(" draw:fill-color=\"%s\" ", s.fillColor.c_str());
1458             outs.printf(" draw:fill-opacity=\"%s\" ", s.fillOpacity.c_str());
1459             }
1460         outs.printf(" draw:stroke=\"%s\" ", s.stroke.c_str());
1461         if (s.stroke != "none")
1462             {
1463             outs.printf(" svg:stroke-width=\"%s\" ", s.strokeWidth.c_str());
1464             outs.printf(" svg:stroke-color=\"%s\" ", s.strokeColor.c_str());
1465             outs.printf(" svg:stroke-opacity=\"%s\" ", s.strokeOpacity.c_str());
1466             }
1467         outs.printf("/>\n");
1468         outs.printf("</style:style>\n");
1469         }
1471     //##  Dump our gradient table
1472     outs.printf("\n");
1473     outs.printf("<!-- ####### Gradients from Inkscape document ####### -->\n");
1474     std::vector<GradientInfo>::iterator giter;
1475     for (giter = gradientTable.begin() ; giter != gradientTable.end() ; giter++)
1476         {
1477         GradientInfo gi(*giter);
1478         outs.printf("<draw:gradient draw:name=\"%s\" ", gi.name.c_str());
1479         outs.printf("draw:style=\"%s\" ", gi.style.c_str());
1480         if (gi.style == "linear")
1481             {
1482             /*
1483             ===================================================================
1484             LINEAR gradient.  We need something that looks like this:
1485             <draw:gradient draw:name="Gradient_20_7"
1486                 draw:display-name="Gradient 7"
1487                 draw:style="linear"
1488                 draw:start-color="#008080" draw:end-color="#993366"
1489                 draw:start-intensity="100%" draw:end-intensity="100%"
1490                 draw:angle="150" draw:border="0%"/>
1491             ===================================================================
1492             */
1493             outs.printf("draw:display-name=\"linear borderless\" ");
1494             }
1495         else if (gi.style == "radial")
1496             {
1497             /*
1498             ===================================================================
1499             RADIAL gradient.  We need something that looks like this:
1500             <!-- radial gradient, light gray to white, centered, 0% border -->
1501             <draw:gradient draw:name="radial_20_borderless"
1502                 draw:display-name="radial borderless"
1503                 draw:style="radial"
1504                 draw:cx="50%" draw:cy="50%"
1505                 draw:start-color="#999999" draw:end-color="#ffffff"
1506                 draw:border="0%"/>
1507             ===================================================================
1508             */
1509             outs.printf("draw:display-name=\"radial borderless\" ");
1510             outs.printf("draw:cx=\".2f%%\" draw:cy=\".2f%%\" ", gi.cx, gi.cy);
1511             }
1512         else
1513             {
1514             g_warning("unsupported gradient style '%s'", gi.style.c_str());
1515             }
1516         outs.printf("/>\n");
1517         }
1519     outs.printf("\n");
1520     outs.printf("</office:automatic-styles>\n");
1521     outs.printf("\n");
1523     return true;
1528 /**
1529  * Writes an SVG path as an ODF <draw:path>
1530  */
1531 static int
1532 writePath(Writer &outs, NArtBpath const *bpath,
1533           NR::Matrix &tf, double xoff, double yoff)
1535     bool closed   = false;
1536     int nrPoints  = 0;
1537     NArtBpath *bp = (NArtBpath *)bpath;
1539     double destx = 0.0;
1540     double desty = 0.0;
1541     int code = -1;
1543     for (  ; bp->code != NR_END; bp++)
1544         {
1545         code = bp->code;
1547         NR::Point const p1(bp->c(1) * tf);
1548         NR::Point const p2(bp->c(2) * tf);
1549         NR::Point const p3(bp->c(3) * tf);
1550         double x1 = (p1[NR::X] - xoff) * 1000.0;
1551         if (fabs(x1)<1.0) x1=0.0;
1552         double y1 = (p1[NR::Y] - yoff) * 1000.0;
1553         if (fabs(y1)<1.0) y1=0.0;
1554         double x2 = (p2[NR::X] - xoff) * 1000.0;
1555         if (fabs(x2)<1.0) x2=0.0;
1556         double y2 = (p2[NR::Y] - yoff) * 1000.0;
1557         if (fabs(y2)<1.0) y2=0.0;
1558         double x3 = (p3[NR::X] - xoff) * 1000.0;
1559         if (fabs(x3)<1.0) x3=0.0;
1560         double y3 = (p3[NR::Y] - yoff) * 1000.0;
1561         if (fabs(y3)<1.0) y3=0.0;
1562         destx = x3;
1563         desty = y3;
1565         switch (code)
1566             {
1567             case NR_LINETO:
1568                 outs.printf("L %.3f %.3f ",  destx, desty);
1569                 break;
1571             case NR_CURVETO:
1572                 outs.printf("C %.3f %.3f %.3f %.3f %.3f %.3f ",
1573                               x1, y1, x2, y2, destx, desty);
1574                 break;
1576             case NR_MOVETO_OPEN:
1577             case NR_MOVETO:
1578                 if (closed)
1579                     outs.printf("Z ");
1580                 closed = ( code == NR_MOVETO );
1581                 outs.printf("M %.3f %.3f ",  destx, desty);
1582                 break;
1584             default:
1585                 break;
1587             }
1589         nrPoints++;
1590         }
1592     if (closed)
1593         {
1594         outs.printf("Z");
1595         }
1597     return nrPoints;
1602 /**
1603  * SECOND PASS.
1604  * This is the main SPObject tree output to ODF.  preprocess()
1605  * must be called prior to this, as elements will often reference
1606  * data parsed and tabled in preprocess().
1607  */
1608 bool OdfOutput::writeTree(Writer &outs, Inkscape::XML::Node *node)
1610     //# Get the SPItem, if applicable
1611     SPObject *reprobj = SP_ACTIVE_DOCUMENT->getObjectByRepr(node);
1612     if (!reprobj)
1613         return true;
1614     if (!SP_IS_ITEM(reprobj))
1615         {
1616         return true;
1617         }
1618     SPItem *item = SP_ITEM(reprobj);
1621     std::string nodeName = node->name();
1622     std::string id       = getAttribute(node, "id");
1624     //### Get SVG-to-ODF transform
1625     NR::Matrix tf        = getODFTransform(item);
1627     //### Get ODF bounding box params for item
1628     NR::Rect bbox        = getODFBoundingBox(item);
1629     double bbox_x        = bbox.min()[NR::X];
1630     double bbox_y        = bbox.min()[NR::Y];
1631     double bbox_width    = bbox.max()[NR::X] - bbox.min()[NR::X];
1632     double bbox_height   = bbox.max()[NR::Y] - bbox.min()[NR::Y];
1634     double rotate;
1635     double xskew;
1636     double yskew;
1637     double xscale;
1638     double yscale;
1639     analyzeTransform(tf, rotate, xskew, yskew, xscale, yscale);
1641     //# Do our stuff
1642     SPCurve *curve = NULL;
1644     //g_message("##### %s #####", nodeName.c_str());
1646     if (nodeName == "svg" || nodeName == "svg:svg")
1647         {
1648         //# Iterate through the children
1649         for (Inkscape::XML::Node *child = node->firstChild() ; child ; child = child->next())
1650             {
1651             if (!writeTree(outs, child))
1652                 return false;
1653             }
1654         return true;
1655         }
1656     else if (nodeName == "g" || nodeName == "svg:g")
1657         {
1658         if (id.size() > 0)
1659             outs.printf("<draw:g id=\"%s\">\n", id.c_str());
1660         else
1661             outs.printf("<draw:g>\n");
1662         //# Iterate through the children
1663         for (Inkscape::XML::Node *child = node->firstChild() ; child ; child = child->next())
1664             {
1665             if (!writeTree(outs, child))
1666                 return false;
1667             }
1668         if (id.size() > 0)
1669             outs.printf("</draw:g> <!-- id=\"%s\" -->\n", id.c_str());
1670         else
1671             outs.printf("</draw:g>\n");
1672         return true;
1673         }
1674     else if (nodeName == "image" || nodeName == "svg:image")
1675         {
1676         if (!SP_IS_IMAGE(item))
1677             {
1678             g_warning("<image> is not an SPImage.  Why?  ;-)");
1679             return false;
1680             }
1682         SPImage *img   = SP_IMAGE(item);
1683         double ix      = img->x.value;
1684         double iy      = img->y.value;
1685         double iwidth  = img->width.value;
1686         double iheight = img->height.value;
1688         NR::Rect ibbox(NR::Point(ix, iy), NR::Point(ix+iwidth, iy+iheight));
1689         ibbox = ibbox * tf;
1690         ix      = ibbox.min()[NR::X];
1691         iy      = ibbox.min()[NR::Y];
1692         //iwidth  = ibbox.max()[NR::X] - ibbox.min()[NR::X];
1693         //iheight = ibbox.max()[NR::Y] - ibbox.min()[NR::Y];
1694         iwidth  = xscale * iwidth;
1695         iheight = yscale * iheight;
1697         NR::Matrix itemTransform = getODFItemTransform(item);
1699         std::string itemTransformString = formatTransform(itemTransform);
1701         std::string href = getAttribute(node, "xlink:href");
1702         std::map<std::string, std::string>::iterator iter = imageTable.find(href);
1703         if (iter == imageTable.end())
1704             {
1705             g_warning("image '%s' not in table", href.c_str());
1706             return false;
1707             }
1708         std::string newName = iter->second;
1710         outs.printf("<draw:frame ");
1711         if (id.size() > 0)
1712             outs.printf("id=\"%s\" ", id.c_str());
1713         outs.printf("draw:style-name=\"gr1\" draw:text-style-name=\"P1\" draw:layer=\"layout\" ");
1714         //no x or y.  make them the translate transform, last one
1715         outs.printf("svg:width=\"%.3fcm\" svg:height=\"%.3fcm\" ",
1716                                   iwidth, iheight);
1717         if (itemTransformString.size() > 0)
1718             {
1719             outs.printf("draw:transform=\"%s translate(%.3fcm, %.3fcm)\" ",
1720                            itemTransformString.c_str(), ix, iy);
1721             }
1722         else
1723             {
1724             outs.printf("draw:transform=\"translate(%.3fcm, %.3fcm)\" ",
1725                                 ix, iy);
1726             }
1728         outs.printf(">\n");
1729         outs.printf("    <draw:image xlink:href=\"%s\" xlink:type=\"simple\"\n",
1730                               newName.c_str());
1731         outs.printf("        xlink:show=\"embed\" xlink:actuate=\"onLoad\">\n");
1732         outs.printf("        <text:p/>\n");
1733         outs.printf("    </draw:image>\n");
1734         outs.printf("</draw:frame>\n");
1735         return true;
1736         }
1737     else if (SP_IS_SHAPE(item))
1738         {
1739         //g_message("### %s is a shape", nodeName.c_str());
1740         curve = sp_shape_get_curve(SP_SHAPE(item));
1741         }
1742     else if (SP_IS_TEXT(item) || SP_IS_FLOWTEXT(item))
1743         {
1744         curve = te_get_layout(item)->convertToCurves();
1745         }
1747     if (curve)
1748         {
1749         //### Default <path> output
1751         outs.printf("<draw:path ");
1752         if (id.size()>0)
1753             outs.printf("id=\"%s\" ", id.c_str());
1755         std::map<std::string, std::string>::iterator siter;
1756         siter = styleLookupTable.find(id);
1757         if (siter != styleLookupTable.end())
1758             {
1759             std::string styleName = siter->second;
1760             outs.printf("draw:style-name=\"%s\" ", styleName.c_str());
1761             }
1763         std::map<std::string, std::string>::iterator giter;
1764         giter = gradientLookupTable.find(id);
1765         if (giter != gradientLookupTable.end())
1766             {
1767             std::string gradientName = giter->second;
1768             outs.printf("draw:fill-gradient-name=\"%s\" ",
1769                  gradientName.c_str());
1770             }
1772         outs.printf("draw:layer=\"layout\" svg:x=\"%.3fcm\" svg:y=\"%.3fcm\" ",
1773                        bbox_x, bbox_y);
1774         outs.printf("svg:width=\"%.3fcm\" svg:height=\"%.3fcm\" ",
1775                        bbox_width, bbox_height);
1776         outs.printf("svg:viewBox=\"0.0 0.0 %.3f %.3f\"\n",
1777                        bbox_width * 1000.0, bbox_height * 1000.0);
1779         outs.printf("    svg:d=\"");
1780         int nrPoints = writePath(outs, SP_CURVE_BPATH(curve),
1781                              tf, bbox_x, bbox_y);
1782         outs.printf("\"");
1784         outs.printf(">\n");
1785         outs.printf("    <!-- %d nodes -->\n", nrPoints);
1786         outs.printf("</draw:path>\n\n");
1789         sp_curve_unref(curve);
1790         }
1792     return true;
1797 /**
1798  * Write the content.xml file.  Writes the namesspace headers, then
1799  * calls writeStyle() and writeTree().
1800  */
1801 bool OdfOutput::writeContent(ZipFile &zf, Inkscape::XML::Node *node)
1803     BufferOutputStream bouts;
1804     OutputStreamWriter outs(bouts);
1806     time_t tim;
1807     time(&tim);
1809     outs.printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1810     outs.printf("\n");
1811     outs.printf("\n");
1812     outs.printf("<!--\n");
1813     outs.printf("*************************************************************************\n");
1814     outs.printf("  file:  content.xml\n");
1815     outs.printf("  Generated by Inkscape: %s", ctime(&tim)); //ctime has its own <cr>
1816     outs.printf("  http://www.inkscape.org\n");
1817     outs.printf("*************************************************************************\n");
1818     outs.printf("-->\n");
1819     outs.printf("\n");
1820     outs.printf("\n");
1821     outs.printf("<office:document-content\n");
1822     outs.printf("    xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\"\n");
1823     outs.printf("    xmlns:style=\"urn:oasis:names:tc:opendocument:xmlns:style:1.0\"\n");
1824     outs.printf("    xmlns:text=\"urn:oasis:names:tc:opendocument:xmlns:text:1.0\"\n");
1825     outs.printf("    xmlns:table=\"urn:oasis:names:tc:opendocument:xmlns:table:1.0\"\n");
1826     outs.printf("    xmlns:draw=\"urn:oasis:names:tc:opendocument:xmlns:drawing:1.0\"\n");
1827     outs.printf("    xmlns:fo=\"urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0\"\n");
1828     outs.printf("    xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n");
1829     outs.printf("    xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n");
1830     outs.printf("    xmlns:meta=\"urn:oasis:names:tc:opendocument:xmlns:meta:1.0\"\n");
1831     outs.printf("    xmlns:number=\"urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0\"\n");
1832     outs.printf("    xmlns:presentation=\"urn:oasis:names:tc:opendocument:xmlns:presentation:1.0\"\n");
1833     outs.printf("    xmlns:svg=\"urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0\"\n");
1834     outs.printf("    xmlns:chart=\"urn:oasis:names:tc:opendocument:xmlns:chart:1.0\"\n");
1835     outs.printf("    xmlns:dr3d=\"urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0\"\n");
1836     outs.printf("    xmlns:math=\"http://www.w3.org/1998/Math/MathML\"\n");
1837     outs.printf("    xmlns:form=\"urn:oasis:names:tc:opendocument:xmlns:form:1.0\"\n");
1838     outs.printf("    xmlns:script=\"urn:oasis:names:tc:opendocument:xmlns:script:1.0\"\n");
1839     outs.printf("    xmlns:ooo=\"http://openoffice.org/2004/office\"\n");
1840     outs.printf("    xmlns:ooow=\"http://openoffice.org/2004/writer\"\n");
1841     outs.printf("    xmlns:oooc=\"http://openoffice.org/2004/calc\"\n");
1842     outs.printf("    xmlns:dom=\"http://www.w3.org/2001/xml-events\"\n");
1843     outs.printf("    xmlns:xforms=\"http://www.w3.org/2002/xforms\"\n");
1844     outs.printf("    xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n");
1845     outs.printf("    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n");
1846     outs.printf("    xmlns:smil=\"urn:oasis:names:tc:opendocument:xmlns:smil-compatible:1.0\"\n");
1847     outs.printf("    xmlns:anim=\"urn:oasis:names:tc:opendocument:xmlns:animation:1.0\"\n");
1848     outs.printf("    office:version=\"1.0\">\n");
1849     outs.printf("\n");
1850     outs.printf("\n");
1851     outs.printf("<office:scripts/>\n");
1852     outs.printf("\n");
1853     outs.printf("\n");
1854     outs.printf("<!-- ######### CONVERSION FROM SVG STARTS ######## -->\n");
1855     outs.printf("<!--\n");
1856     outs.printf("*************************************************************************\n");
1857     outs.printf("  S T Y L E S\n");
1858     outs.printf("  Style entries have been pulled from the svg style and\n");
1859     outs.printf("  representation attributes in the SVG tree.  The tree elements\n");
1860     outs.printf("  then refer to them by name, in the ODF manner\n");
1861     outs.printf("*************************************************************************\n");
1862     outs.printf("-->\n");
1863     outs.printf("\n");
1864     outs.printf("\n");
1866     if (!writeStyle(outs))
1867         {
1868         g_warning("Failed to write styles");
1869         return false;
1870         }
1872     outs.printf("\n");
1873     outs.printf("\n");
1874     outs.printf("\n");
1875     outs.printf("\n");
1876     outs.printf("<!--\n");
1877     outs.printf("*************************************************************************\n");
1878     outs.printf("  D R A W I N G\n");
1879     outs.printf("  This section is the heart of SVG-ODF conversion.  We are\n");
1880     outs.printf("  starting with simple conversions, and will slowly evolve\n");
1881     outs.printf("  into a 'smarter' translation as time progresses.  Any help\n");
1882     outs.printf("  in improving .odg export is welcome.\n");
1883     outs.printf("*************************************************************************\n");
1884     outs.printf("-->\n");
1885     outs.printf("\n");
1886     outs.printf("\n");
1887     outs.printf("<office:body>\n");
1888     outs.printf("<office:drawing>\n");
1889     outs.printf("<draw:page draw:name=\"page1\" draw:style-name=\"dp1\"\n");
1890     outs.printf("        draw:master-page-name=\"Default\">\n");
1891     outs.printf("\n");
1892     outs.printf("\n");
1894     if (!writeTree(outs, node))
1895         {
1896         g_warning("Failed to convert SVG tree");
1897         return false;
1898         }
1900     outs.printf("\n");
1901     outs.printf("\n");
1903     outs.printf("</draw:page>\n");
1904     outs.printf("</office:drawing>\n");
1906     outs.printf("\n");
1907     outs.printf("\n");
1908     outs.printf("<!-- ######### CONVERSION FROM SVG ENDS ######## -->\n");
1909     outs.printf("\n");
1910     outs.printf("\n");
1912     outs.printf("</office:body>\n");
1913     outs.printf("</office:document-content>\n");
1914     outs.printf("\n");
1915     outs.printf("\n");
1916     outs.printf("\n");
1917     outs.printf("<!--\n");
1918     outs.printf("*************************************************************************\n");
1919     outs.printf("  E N D    O F    F I L E\n");
1920     outs.printf("  Have a nice day  - ishmal\n");
1921     outs.printf("*************************************************************************\n");
1922     outs.printf("-->\n");
1923     outs.printf("\n");
1924     outs.printf("\n");
1928     //Make our entry
1929     ZipEntry *ze = zf.newEntry("content.xml", "ODF master content file");
1930     ze->setUncompressedData(bouts.getBuffer());
1931     ze->finish();
1933     return true;
1937 /**
1938  * Resets class to its pristine condition, ready to use again
1939  */
1940 void
1941 OdfOutput::reset()
1943     metadata.clear();
1944     styleTable.clear();
1945     styleLookupTable.clear();
1946     gradientTable.clear();
1947     gradientLookupTable.clear();
1948     imageTable.clear();
1954 /**
1955  * Descends into the SVG tree, mapping things to ODF when appropriate
1956  */
1957 void
1958 OdfOutput::save(Inkscape::Extension::Output *mod, SPDocument *doc, gchar const *uri)
1960     reset();
1962     //g_message("native file:%s\n", uri);
1963     documentUri = URI(uri);
1965     ZipFile zf;
1966     preprocess(zf, doc->rroot);
1968     if (!writeManifest(zf))
1969         {
1970         g_warning("Failed to write manifest");
1971         return;
1972         }
1974     if (!writeMeta(zf))
1975         {
1976         g_warning("Failed to write metafile");
1977         return;
1978         }
1980     if (!writeContent(zf, doc->rroot))
1981         {
1982         g_warning("Failed to write content");
1983         return;
1984         }
1986     if (!zf.writeFile(uri))
1987         {
1988         return;
1989         }
1993 /**
1994  * This is the definition of PovRay output.  This function just
1995  * calls the extension system with the memory allocated XML that
1996  * describes the data.
1997 */
1998 void
1999 OdfOutput::init()
2001     Inkscape::Extension::build_from_mem(
2002         "<inkscape-extension>\n"
2003             "<name>" N_("OpenDocument Drawing Output") "</name>\n"
2004             "<id>org.inkscape.output.odf</id>\n"
2005             "<output>\n"
2006                 "<extension>.odg</extension>\n"
2007                 "<mimetype>text/x-povray-script</mimetype>\n"
2008                 "<filetypename>" N_("OpenDocument drawing (*.odg)") "</filetypename>\n"
2009                 "<filetypetooltip>" N_("OpenDocument drawing file") "</filetypetooltip>\n"
2010             "</output>\n"
2011         "</inkscape-extension>",
2012         new OdfOutput());
2015 /**
2016  * Make sure that we are in the database
2017  */
2018 bool
2019 OdfOutput::check (Inkscape::Extension::Extension *module)
2021     /* We don't need a Key
2022     if (NULL == Inkscape::Extension::db.get(SP_MODULE_KEY_OUTPUT_POV))
2023         return FALSE;
2024     */
2026     return TRUE;
2031 //########################################################################
2032 //# I N P U T
2033 //########################################################################
2037 //#######################
2038 //# L A T E R  !!!  :-)
2039 //#######################
2053 }  //namespace Internal
2054 }  //namespace Extension
2055 }  //namespace Inkscape
2058 //########################################################################
2059 //# E N D    O F    F I L E
2060 //########################################################################
2062 /*
2063   Local Variables:
2064   mode:c++
2065   c-file-style:"stroustrup"
2066   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
2067   indent-tabs-mode:nil
2068   fill-column:99
2069   End:
2070 */
2071 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :