Code

Fixed crash when draw height was zero.
[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-stop.h"
62 #include "gradient-chemistry.h"
63 #include "sp-linear-gradient.h"
64 #include "sp-radial-gradient.h"
65 #include "sp-path.h"
66 #include "sp-text.h"
67 #include "sp-flowtext.h"
68 #include "svg/svg.h"
69 #include "text-editing.h"
72 //# DOM-specific includes
73 #include "dom/dom.h"
74 #include "dom/util/ziptool.h"
75 #include "dom/io/domstream.h"
76 #include "dom/io/bufferstream.h"
77 #include "dom/io/stringstream.h"
84 namespace Inkscape
85 {
86 namespace Extension
87 {
88 namespace Internal
89 {
93 //# Shorthand notation
94 typedef org::w3c::dom::DOMString DOMString;
95 typedef org::w3c::dom::XMLCh XMLCh;
96 typedef org::w3c::dom::io::OutputStreamWriter OutputStreamWriter;
97 typedef org::w3c::dom::io::BufferOutputStream BufferOutputStream;
98 typedef org::w3c::dom::io::StringOutputStream StringOutputStream;
100 //########################################################################
101 //# C L A S S    SingularValueDecomposition
102 //########################################################################
103 #include <math.h>
105 class SVDMatrix
107 public:
109     SVDMatrix()
110         {
111         init();
112         }
114     SVDMatrix(unsigned int rowSize, unsigned int colSize)
115         {
116         init();
117         rows = rowSize;
118         cols = colSize;
119         size = rows * cols;
120         d    = new double[size];
121         for (unsigned int i=0 ; i<size ; i++)
122             d[i] = 0.0;
123         }
125     SVDMatrix(double *vals, unsigned int rowSize, unsigned int colSize)
126         {
127         init();
128         rows = rowSize;
129         cols = colSize;
130         size = rows * cols;
131         d    = new double[size];
132         for (unsigned int i=0 ; i<size ; i++)
133             d[i] = vals[i];
134         }
137     SVDMatrix(const SVDMatrix &other)
138         {
139         init();
140         assign(other);
141         }
143     SVDMatrix &operator=(const SVDMatrix &other)
144         {
145         assign(other);
146         return *this;
147         }
149     virtual ~SVDMatrix()
150         {
151         delete[] d;
152         }
154      double& operator() (unsigned int row, unsigned int col)
155          {
156          if (row >= rows || col >= cols)
157              return badval;
158          return d[cols*row + col];
159          }
161      double operator() (unsigned int row, unsigned int col) const
162          {
163          if (row >= rows || col >= cols)
164              return badval;
165          return d[cols*row + col];
166          }
168      unsigned int getRows()
169          {
170          return rows;
171          }
173      unsigned int getCols()
174          {
175          return cols;
176          }
178      SVDMatrix multiply(const SVDMatrix &other)
179          {
180          if (cols != other.rows)
181              {
182              SVDMatrix dummy;
183              return dummy;
184              }
185          SVDMatrix result(rows, other.cols);
186          for (unsigned int i=0 ; i<rows ; i++)
187              {
188              for (unsigned int j=0 ; j<other.cols ; j++)
189                  {
190                  double sum = 0.0;
191                  for (unsigned int k=0 ; k<cols ; k++)
192                      {
193                      //sum += a[i][k] * b[k][j];
194                      sum += d[i*cols +k] * other(k, j);
195                      }
196                  result(i, j) = sum;
197                  }
199              }
200          return result;
201          }
203      SVDMatrix transpose()
204          {
205          SVDMatrix result(cols, rows);
206          for (unsigned int i=0 ; i<rows ; i++)
207              for (unsigned int j=0 ; j<cols ; j++)
208                  result(j, i) = d[i*cols + j];
209          return result;
210          }
212 private:
215     virtual void init()
216         {
217         badval = 0.0;
218         d      = NULL;
219         rows   = 0;
220         cols   = 0;
221         size   = 0;
222         }
224      void assign(const SVDMatrix &other)
225         {
226         if (d)
227             {
228             delete[] d;
229             d = 0;
230             }
231         rows = other.rows;
232         cols = other.cols;
233         size = other.size;
234         d = new double[size];
235         for (unsigned int i=0 ; i<size ; i++)
236             d[i] = other.d[i];
237         }
239     double badval;
241     double *d;
242     unsigned int rows;
243     unsigned int cols;
244     unsigned int size;
245 };
249 /**
250  *
251  * ====================================================
252  *
253  * NOTE:
254  * This class is ported almost verbatim from the public domain
255  * JAMA Matrix package.  It is modified to handle only 3x3 matrices
256  * and our NR::Matrix affine transform class.  We give full
257  * attribution to them, along with many thanks.  JAMA can be found at:
258  *     http://math.nist.gov/javanumerics/jama
259  *
260  * ====================================================
261  *
262  * Singular Value Decomposition.
263  * <P>
264  * For an m-by-n matrix A with m >= n, the singular value decomposition is
265  * an m-by-n orthogonal matrix U, an n-by-n diagonal matrix S, and
266  * an n-by-n orthogonal matrix V so that A = U*S*V'.
267  * <P>
268  * The singular values, sigma[k] = S[k][k], are ordered so that
269  * sigma[0] >= sigma[1] >= ... >= sigma[n-1].
270  * <P>
271  * The singular value decompostion always exists, so the constructor will
272  * never fail.  The matrix condition number and the effective numerical
273  * rank can be computed from this decomposition.
274  */
275 class SingularValueDecomposition
277 public:
279    /** Construct the singular value decomposition
280    @param A    Rectangular matrix
281    @return     Structure to access U, S and V.
282    */
284     SingularValueDecomposition (const SVDMatrix &mat)
285         {
286         A      = mat;
287         s      = NULL;
288         s_size = 0;
289         calculate();
290         }
292     virtual ~SingularValueDecomposition()
293         {
294         delete[] s;
295         }
297     /**
298      * Return the left singular vectors
299      * @return     U
300      */
301     SVDMatrix &getU();
303     /**
304      * Return the right singular vectors
305      * @return     V
306      */
307     SVDMatrix &getV();
309     /**
310      *  Return the s[index] value
311      */    double getS(unsigned int index);
313     /**
314      * Two norm
315      * @return max(S)
316      */
317     double norm2();
319     /**
320      * Two norm condition number
321      *  @return max(S)/min(S)
322      */
323     double cond();
325     /**
326      *  Effective numerical matrix rank
327      *  @return     Number of nonnegligible singular values.
328      */
329     int rank();
331 private:
333       void calculate();
335       SVDMatrix A;
336       SVDMatrix U;
337       double *s;
338       unsigned int s_size;
339       SVDMatrix V;
341 };
344 static double svd_hypot(double a, double b)
346     double r;
348     if (fabs(a) > fabs(b))
349         {
350         r = b/a;
351         r = fabs(a) * sqrt(1+r*r);
352         }
353     else if (b != 0)
354         {
355         r = a/b;
356         r = fabs(b) * sqrt(1+r*r);
357         }
358     else
359         {
360         r = 0.0;
361         }
362     return r;
367 void SingularValueDecomposition::calculate()
369       // Initialize.
370       int m = A.getRows();
371       int n = A.getCols();
373       int nu = (m > n) ? m : n;
374       s_size = (m+1 < n) ? m+1 : n;
375       s = new double[s_size];
376       U = SVDMatrix(m, nu);
377       V = SVDMatrix(n, n);
378       double *e = new double[n];
379       double *work = new double[m];
380       bool wantu = true;
381       bool wantv = true;
383       // Reduce A to bidiagonal form, storing the diagonal elements
384       // in s and the super-diagonal elements in e.
386       int nct = (m-1<n) ? m-1 : n;
387       int nrtx = (n-2<m) ? n-2 : m;
388       int nrt = (nrtx>0) ? nrtx : 0;
389       for (int k = 0; k < 2; k++) {
390          if (k < nct) {
392             // Compute the transformation for the k-th column and
393             // place the k-th diagonal in s[k].
394             // Compute 2-norm of k-th column without under/overflow.
395             s[k] = 0;
396             for (int i = k; i < m; i++) {
397                s[k] = svd_hypot(s[k],A(i, k));
398             }
399             if (s[k] != 0.0) {
400                if (A(k, k) < 0.0) {
401                   s[k] = -s[k];
402                }
403                for (int i = k; i < m; i++) {
404                   A(i, k) /= s[k];
405                }
406                A(k, k) += 1.0;
407             }
408             s[k] = -s[k];
409          }
410          for (int j = k+1; j < n; j++) {
411             if ((k < nct) & (s[k] != 0.0))  {
413             // Apply the transformation.
415                double t = 0;
416                for (int i = k; i < m; i++) {
417                   t += A(i, k) * A(i, j);
418                }
419                t = -t/A(k, k);
420                for (int i = k; i < m; i++) {
421                   A(i, j) += t*A(i, k);
422                }
423             }
425             // Place the k-th row of A into e for the
426             // subsequent calculation of the row transformation.
428             e[j] = A(k, j);
429          }
430          if (wantu & (k < nct)) {
432             // Place the transformation in U for subsequent back
433             // multiplication.
435             for (int i = k; i < m; i++) {
436                U(i, k) = A(i, k);
437             }
438          }
439          if (k < nrt) {
441             // Compute the k-th row transformation and place the
442             // k-th super-diagonal in e[k].
443             // Compute 2-norm without under/overflow.
444             e[k] = 0;
445             for (int i = k+1; i < n; i++) {
446                e[k] = svd_hypot(e[k],e[i]);
447             }
448             if (e[k] != 0.0) {
449                if (e[k+1] < 0.0) {
450                   e[k] = -e[k];
451                }
452                for (int i = k+1; i < n; i++) {
453                   e[i] /= e[k];
454                }
455                e[k+1] += 1.0;
456             }
457             e[k] = -e[k];
458             if ((k+1 < m) & (e[k] != 0.0)) {
460             // Apply the transformation.
462                for (int i = k+1; i < m; i++) {
463                   work[i] = 0.0;
464                }
465                for (int j = k+1; j < n; j++) {
466                   for (int i = k+1; i < m; i++) {
467                      work[i] += e[j]*A(i, j);
468                   }
469                }
470                for (int j = k+1; j < n; j++) {
471                   double t = -e[j]/e[k+1];
472                   for (int i = k+1; i < m; i++) {
473                      A(i, j) += t*work[i];
474                   }
475                }
476             }
477             if (wantv) {
479             // Place the transformation in V for subsequent
480             // back multiplication.
482                for (int i = k+1; i < n; i++) {
483                   V(i, k) = e[i];
484                }
485             }
486          }
487       }
489       // Set up the final bidiagonal matrix or order p.
491       int p = (n < m+1) ? n : m+1;
492       if (nct < n) {
493          s[nct] = A(nct, nct);
494       }
495       if (m < p) {
496          s[p-1] = 0.0;
497       }
498       if (nrt+1 < p) {
499          e[nrt] = A(nrt, p-1);
500       }
501       e[p-1] = 0.0;
503       // If required, generate U.
505       if (wantu) {
506          for (int j = nct; j < nu; j++) {
507             for (int i = 0; i < m; i++) {
508                U(i, j) = 0.0;
509             }
510             U(j, j) = 1.0;
511          }
512          for (int k = nct-1; k >= 0; k--) {
513             if (s[k] != 0.0) {
514                for (int j = k+1; j < nu; j++) {
515                   double t = 0;
516                   for (int i = k; i < m; i++) {
517                      t += U(i, k)*U(i, j);
518                   }
519                   t = -t/U(k, k);
520                   for (int i = k; i < m; i++) {
521                      U(i, j) += t*U(i, k);
522                   }
523                }
524                for (int i = k; i < m; i++ ) {
525                   U(i, k) = -U(i, k);
526                }
527                U(k, k) = 1.0 + U(k, k);
528                for (int i = 0; i < k-1; i++) {
529                   U(i, k) = 0.0;
530                }
531             } else {
532                for (int i = 0; i < m; i++) {
533                   U(i, k) = 0.0;
534                }
535                U(k, k) = 1.0;
536             }
537          }
538       }
540       // If required, generate V.
542       if (wantv) {
543          for (int k = n-1; k >= 0; k--) {
544             if ((k < nrt) & (e[k] != 0.0)) {
545                for (int j = k+1; j < nu; j++) {
546                   double t = 0;
547                   for (int i = k+1; i < n; i++) {
548                      t += V(i, k)*V(i, j);
549                   }
550                   t = -t/V(k+1, k);
551                   for (int i = k+1; i < n; i++) {
552                      V(i, j) += t*V(i, k);
553                   }
554                }
555             }
556             for (int i = 0; i < n; i++) {
557                V(i, k) = 0.0;
558             }
559             V(k, k) = 1.0;
560          }
561       }
563       // Main iteration loop for the singular values.
565       int pp = p-1;
566       int iter = 0;
567       //double eps = pow(2.0,-52.0);
568       //double tiny = pow(2.0,-966.0);
569       //let's just calculate these now
570       //a double can be e Â± 308.25, so this is safe
571       double eps = 2.22e-16;
572       double tiny = 1.6e-291;
573       while (p > 0) {
574          int k,kase;
576          // Here is where a test for too many iterations would go.
578          // This section of the program inspects for
579          // negligible elements in the s and e arrays.  On
580          // completion the variables kase and k are set as follows.
582          // kase = 1     if s(p) and e[k-1] are negligible and k<p
583          // kase = 2     if s(k) is negligible and k<p
584          // kase = 3     if e[k-1] is negligible, k<p, and
585          //              s(k), ..., s(p) are not negligible (qr step).
586          // kase = 4     if e(p-1) is negligible (convergence).
588          for (k = p-2; k >= -1; k--) {
589             if (k == -1) {
590                break;
591             }
592             if (fabs(e[k]) <=
593                   tiny + eps*(fabs(s[k]) + fabs(s[k+1]))) {
594                e[k] = 0.0;
595                break;
596             }
597          }
598          if (k == p-2) {
599             kase = 4;
600          } else {
601             int ks;
602             for (ks = p-1; ks >= k; ks--) {
603                if (ks == k) {
604                   break;
605                }
606                double t = (ks != p ? fabs(e[ks]) : 0.) +
607                           (ks != k+1 ? fabs(e[ks-1]) : 0.);
608                if (fabs(s[ks]) <= tiny + eps*t)  {
609                   s[ks] = 0.0;
610                   break;
611                }
612             }
613             if (ks == k) {
614                kase = 3;
615             } else if (ks == p-1) {
616                kase = 1;
617             } else {
618                kase = 2;
619                k = ks;
620             }
621          }
622          k++;
624          // Perform the task indicated by kase.
626          switch (kase) {
628             // Deflate negligible s(p).
630             case 1: {
631                double f = e[p-2];
632                e[p-2] = 0.0;
633                for (int j = p-2; j >= k; j--) {
634                   double t = svd_hypot(s[j],f);
635                   double cs = s[j]/t;
636                   double sn = f/t;
637                   s[j] = t;
638                   if (j != k) {
639                      f = -sn*e[j-1];
640                      e[j-1] = cs*e[j-1];
641                   }
642                   if (wantv) {
643                      for (int i = 0; i < n; i++) {
644                         t = cs*V(i, j) + sn*V(i, p-1);
645                         V(i, p-1) = -sn*V(i, j) + cs*V(i, p-1);
646                         V(i, j) = t;
647                      }
648                   }
649                }
650             }
651             break;
653             // Split at negligible s(k).
655             case 2: {
656                double f = e[k-1];
657                e[k-1] = 0.0;
658                for (int j = k; j < p; j++) {
659                   double t = svd_hypot(s[j],f);
660                   double cs = s[j]/t;
661                   double sn = f/t;
662                   s[j] = t;
663                   f = -sn*e[j];
664                   e[j] = cs*e[j];
665                   if (wantu) {
666                      for (int i = 0; i < m; i++) {
667                         t = cs*U(i, j) + sn*U(i, k-1);
668                         U(i, k-1) = -sn*U(i, j) + cs*U(i, k-1);
669                         U(i, j) = t;
670                      }
671                   }
672                }
673             }
674             break;
676             // Perform one qr step.
678             case 3: {
680                // Calculate the shift.
682                double scale = fabs(s[p-1]);
683                double d = fabs(s[p-2]);
684                if (d>scale) scale=d;
685                d = fabs(e[p-2]);
686                if (d>scale) scale=d;
687                d = fabs(s[k]);
688                if (d>scale) scale=d;
689                d = fabs(e[k]);
690                if (d>scale) scale=d;
691                double sp = s[p-1]/scale;
692                double spm1 = s[p-2]/scale;
693                double epm1 = e[p-2]/scale;
694                double sk = s[k]/scale;
695                double ek = e[k]/scale;
696                double b = ((spm1 + sp)*(spm1 - sp) + epm1*epm1)/2.0;
697                double c = (sp*epm1)*(sp*epm1);
698                double shift = 0.0;
699                if ((b != 0.0) | (c != 0.0)) {
700                   shift = sqrt(b*b + c);
701                   if (b < 0.0) {
702                      shift = -shift;
703                   }
704                   shift = c/(b + shift);
705                }
706                double f = (sk + sp)*(sk - sp) + shift;
707                double g = sk*ek;
709                // Chase zeros.
711                for (int j = k; j < p-1; j++) {
712                   double t = svd_hypot(f,g);
713                   double cs = f/t;
714                   double sn = g/t;
715                   if (j != k) {
716                      e[j-1] = t;
717                   }
718                   f = cs*s[j] + sn*e[j];
719                   e[j] = cs*e[j] - sn*s[j];
720                   g = sn*s[j+1];
721                   s[j+1] = cs*s[j+1];
722                   if (wantv) {
723                      for (int i = 0; i < n; i++) {
724                         t = cs*V(i, j) + sn*V(i, j+1);
725                         V(i, j+1) = -sn*V(i, j) + cs*V(i, j+1);
726                         V(i, j) = t;
727                      }
728                   }
729                   t = svd_hypot(f,g);
730                   cs = f/t;
731                   sn = g/t;
732                   s[j] = t;
733                   f = cs*e[j] + sn*s[j+1];
734                   s[j+1] = -sn*e[j] + cs*s[j+1];
735                   g = sn*e[j+1];
736                   e[j+1] = cs*e[j+1];
737                   if (wantu && (j < m-1)) {
738                      for (int i = 0; i < m; i++) {
739                         t = cs*U(i, j) + sn*U(i, j+1);
740                         U(i, j+1) = -sn*U(i, j) + cs*U(i, j+1);
741                         U(i, j) = t;
742                      }
743                   }
744                }
745                e[p-2] = f;
746                iter = iter + 1;
747             }
748             break;
750             // Convergence.
752             case 4: {
754                // Make the singular values positive.
756                if (s[k] <= 0.0) {
757                   s[k] = (s[k] < 0.0 ? -s[k] : 0.0);
758                   if (wantv) {
759                      for (int i = 0; i <= pp; i++) {
760                         V(i, k) = -V(i, k);
761                      }
762                   }
763                }
765                // Order the singular values.
767                while (k < pp) {
768                   if (s[k] >= s[k+1]) {
769                      break;
770                   }
771                   double t = s[k];
772                   s[k] = s[k+1];
773                   s[k+1] = t;
774                   if (wantv && (k < n-1)) {
775                      for (int i = 0; i < n; i++) {
776                         t = V(i, k+1); V(i, k+1) = V(i, k); V(i, k) = t;
777                      }
778                   }
779                   if (wantu && (k < m-1)) {
780                      for (int i = 0; i < m; i++) {
781                         t = U(i, k+1); U(i, k+1) = U(i, k); U(i, k) = t;
782                      }
783                   }
784                   k++;
785                }
786                iter = 0;
787                p--;
788             }
789             break;
790          }
791       }
793     delete e;
794     delete work;
800 /**
801  * Return the left singular vectors
802  * @return     U
803  */
804 SVDMatrix &SingularValueDecomposition::getU()
806     return U;
809 /**
810  * Return the right singular vectors
811  * @return     V
812  */
814 SVDMatrix &SingularValueDecomposition::getV()
816     return V;
819 /**
820  *  Return the s[0] value
821  */
822 double SingularValueDecomposition::getS(unsigned int index)
824     if (index >= s_size)
825         return 0.0;
826     return s[index];
829 /**
830  * Two norm
831  * @return     max(S)
832  */
833 double SingularValueDecomposition::norm2()
835     return s[0];
838 /**
839  * Two norm condition number
840  *  @return     max(S)/min(S)
841  */
843 double SingularValueDecomposition::cond()
845     return s[0]/s[2];
848 /**
849  *  Effective numerical matrix rank
850  *  @return     Number of nonnegligible singular values.
851  */
852 int SingularValueDecomposition::rank()
854     double eps = pow(2.0,-52.0);
855     double tol = 3.0*s[0]*eps;
856     int r = 0;
857     for (int i = 0; i < 3; i++)
858         {
859         if (s[i] > tol)
860             r++;
861         }
862     return r;
865 //########################################################################
866 //# E N D    C L A S S    SingularValueDecomposition
867 //########################################################################
873 #define pi 3.14159
874 //#define pxToCm  0.0275
875 #define pxToCm  0.03
876 #define piToRad 0.0174532925
877 #define docHeightCm 22.86
880 //########################################################################
881 //# O U T P U T
882 //########################################################################
884 /**
885  * Get the value of a node/attribute pair
886  */
887 static Glib::ustring getAttribute( Inkscape::XML::Node *node, char *attrName)
889     Glib::ustring val;
890     char *valstr = (char *)node->attribute(attrName);
891     if (valstr)
892         val = (const char *)valstr;
893     return val;
898 /**
899  * Get the extension suffix from the end of a file name
900  */
901 static Glib::ustring getExtension(const Glib::ustring &fname)
903     Glib::ustring ext;
905     unsigned int pos = fname.rfind('.');
906     if (pos == fname.npos)
907         {
908         ext = "";
909         }
910     else
911         {
912         ext = fname.substr(pos);
913         }
914     return ext;
918 static Glib::ustring formatTransform(NR::Matrix &tf)
920     Glib::ustring str;
921     if (!tf.test_identity())
922         {
923         StringOutputStream outs;
924         OutputStreamWriter out(outs);
925         out.printf("matrix(%.3f %.3f %.3f %.3f %.3f %.3f)",
926                 tf[0], tf[1], tf[2], tf[3], tf[4], tf[5]);
927         str = outs.getString();
928         }
929     return str;
936 /**
937  * Get the general transform from SVG pixels to
938  * ODF cm
939  */
940 static NR::Matrix getODFTransform(const SPItem *item)
942     //### Get SVG-to-ODF transform
943     NR::Matrix tf;
944     tf                   = sp_item_i2d_affine(item);
945     //Flip Y into document coordinates
946     double doc_height    = sp_document_height(SP_ACTIVE_DOCUMENT);
947     NR::Matrix doc2dt_tf = NR::Matrix(NR::scale(1.0, -1.0));
948     doc2dt_tf            = doc2dt_tf * NR::Matrix(NR::translate(0, doc_height));
949     tf                   = tf * doc2dt_tf;
950     tf                   = tf * NR::Matrix(NR::scale(pxToCm));
951     return tf;
957 /**
958  * Get the bounding box of an item, as mapped onto
959  * an ODF document, in cm.
960  */
961 static NR::Rect getODFBoundingBox(const SPItem *item)
963     NR::Rect bbox        = sp_item_bbox_desktop((SPItem *)item);
964     double doc_height    = sp_document_height(SP_ACTIVE_DOCUMENT);
965     NR::Matrix doc2dt_tf = NR::Matrix(NR::scale(1.0, -1.0));
966     doc2dt_tf            = doc2dt_tf * NR::Matrix(NR::translate(0, doc_height));
967     bbox                 = bbox * doc2dt_tf;
968     bbox                 = bbox * NR::Matrix(NR::scale(pxToCm));
969     return bbox;
974 /**
975  * Get the transform for an item, correcting for
976  * handedness reversal
977  */
978 static NR::Matrix getODFItemTransform(const SPItem *item)
980     NR::Matrix itemTransform = NR::Matrix(NR::scale(1, -1));
981     itemTransform = itemTransform * item->transform;
982     itemTransform = itemTransform * NR::Matrix(NR::scale(1, -1));
983     return itemTransform;
988 /**
989  * Get some fun facts from the transform
990  */
991 static void analyzeTransform(NR::Matrix &tf,
992            double &rotate, double &xskew, double &yskew,
993            double &xscale, double &yscale)
995     SVDMatrix mat(2, 2);
996     mat(0, 0) = tf[0];
997     mat(0, 1) = tf[1];
998     mat(1, 0) = tf[2];
999     mat(1, 1) = tf[3];
1001     SingularValueDecomposition svd(mat);
1003     SVDMatrix U = svd.getU();
1004     SVDMatrix V = svd.getV();
1005     SVDMatrix Vt = V.transpose();
1006     SVDMatrix UVt = U.multiply(Vt);
1007     double s0 = svd.getS(0);
1008     double s1 = svd.getS(1);
1009     xscale = s0;
1010     yscale = s1;
1011     //g_message("## s0:%.3f s1:%.3f", s0, s1);
1012     //g_message("## u:%.3f %.3f %.3f %.3f", U(0,0), U(0,1), U(1,0), U(1,1));
1013     //g_message("## v:%.3f %.3f %.3f %.3f", V(0,0), V(0,1), V(1,0), V(1,1));
1014     //g_message("## vt:%.3f %.3f %.3f %.3f", Vt(0,0), Vt(0,1), Vt(1,0), Vt(1,1));
1015     //g_message("## uvt:%.3f %.3f %.3f %.3f", UVt(0,0), UVt(0,1), UVt(1,0), UVt(1,1));
1016     rotate = UVt(0,0);
1021 static void gatherText(Inkscape::XML::Node *node, Glib::ustring &buf)
1023     if (node->type() == Inkscape::XML::TEXT_NODE)
1024         {
1025         char *s = (char *)node->content();
1026         if (s)
1027             buf.append(s);
1028         }
1029     
1030     for (Inkscape::XML::Node *child = node->firstChild() ;
1031                 child != NULL; child = child->next())
1032         {
1033         gatherText(child, buf);
1034         }
1038 /**
1039  * FIRST PASS.
1040  * Method descends into the repr tree, converting image, style, and gradient info
1041  * into forms compatible in ODF.
1042  */
1043 void
1044 OdfOutput::preprocess(ZipFile &zf, Inkscape::XML::Node *node)
1047     Glib::ustring nodeName = node->name();
1048     Glib::ustring id       = getAttribute(node, "id");
1050     //### First, check for metadata
1051     if (nodeName == "metadata" || nodeName == "svg:metadata")
1052         {
1053         Inkscape::XML::Node *mchild = node->firstChild() ;
1054         if (!mchild || strcmp(mchild->name(), "rdf:RDF"))
1055             return;
1056         Inkscape::XML::Node *rchild = mchild->firstChild() ;
1057         if (!rchild || strcmp(rchild->name(), "cc:Work"))
1058             return;
1059         for (Inkscape::XML::Node *cchild = rchild->firstChild() ;
1060             cchild ; cchild = cchild->next())
1061             {
1062             Glib::ustring ccName = cchild->name();
1063             Glib::ustring ccVal;
1064             gatherText(cchild, ccVal);
1065             //g_message("ccName: %s  ccVal:%s", ccName.c_str(), ccVal.c_str());
1066             metadata[ccName] = ccVal;
1067             }
1068         return;
1069         }
1071     //Now consider items.
1072     SPObject *reprobj = SP_ACTIVE_DOCUMENT->getObjectByRepr(node);
1073     if (!reprobj)
1074         return;
1075     if (!SP_IS_ITEM(reprobj))
1076         {
1077         return;
1078         }
1079     SPItem *item  = SP_ITEM(reprobj);
1080     //### Get SVG-to-ODF transform
1081     NR::Matrix tf = getODFTransform(item);
1083     if (nodeName == "image" || nodeName == "svg:image")
1084         {
1085         //g_message("image");
1086         Glib::ustring href = getAttribute(node, "xlink:href");
1087         if (href.size() > 0)
1088             {
1089             Glib::ustring oldName = href;
1090             Glib::ustring ext = getExtension(oldName);
1091             if (ext == ".jpeg")
1092                 ext = ".jpg";
1093             if (imageTable.find(oldName) == imageTable.end())
1094                 {
1095                 char buf[64];
1096                 snprintf(buf, 63, "Pictures/image%d%s",
1097                     (int)imageTable.size(), ext.c_str());
1098                 Glib::ustring newName = buf;
1099                 imageTable[oldName] = newName;
1100                 Glib::ustring comment = "old name was: ";
1101                 comment.append(oldName);
1102                 URI oldUri(oldName);
1103                 //g_message("oldpath:%s", oldUri.getNativePath().c_str());
1104                 //# if relative to the documentURI, get proper path
1105                 URI resUri = documentUri.resolve(oldUri);
1106                 DOMString pathName = resUri.getNativePath();
1107                 //g_message("native path:%s", pathName.c_str());
1108                 ZipEntry *ze = zf.addFile(pathName, comment);
1109                 if (ze)
1110                     {
1111                     ze->setFileName(newName);
1112                     }
1113                 else
1114                     {
1115                     g_warning("Could not load image file '%s'", pathName.c_str());
1116                     }
1117                 }
1118             }
1119         }
1121     for (Inkscape::XML::Node *child = node->firstChild() ;
1122             child ; child = child->next())
1123         preprocess(zf, child);
1128 /**
1129  * Writes the manifest.  Currently it only changes according to the
1130  * file names of images packed into the zip file.
1131  */
1132 bool OdfOutput::writeManifest(ZipFile &zf)
1134     BufferOutputStream bouts;
1135     OutputStreamWriter outs(bouts);
1137     time_t tim;
1138     time(&tim);
1140     outs.printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1141     outs.printf("<!DOCTYPE manifest:manifest PUBLIC \"-//OpenOffice.org//DTD Manifest 1.0//EN\" \"Manifest.dtd\">\n");
1142     outs.printf("\n");
1143     outs.printf("\n");
1144     outs.printf("<!--\n");
1145     outs.printf("*************************************************************************\n");
1146     outs.printf("  file:  manifest.xml\n");
1147     outs.printf("  Generated by Inkscape: %s", ctime(&tim)); //ctime has its own <cr>
1148     outs.printf("  http://www.inkscape.org\n");
1149     outs.printf("*************************************************************************\n");
1150     outs.printf("-->\n");
1151     outs.printf("\n");
1152     outs.printf("\n");
1153     outs.printf("<manifest:manifest xmlns:manifest=\"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0\">\n");
1154     outs.printf("    <manifest:file-entry manifest:media-type=\"application/vnd.oasis.opendocument.graphics\" manifest:full-path=\"/\"/>\n");
1155     outs.printf("    <manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"content.xml\"/>\n");
1156     outs.printf("    <manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"styles.xml\"/>\n");
1157     outs.printf("    <manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"meta.xml\"/>\n");
1158     outs.printf("    <!--List our images here-->\n");
1159     std::map<Glib::ustring, Glib::ustring>::iterator iter;
1160     for (iter = imageTable.begin() ; iter!=imageTable.end() ; iter++)
1161         {
1162         Glib::ustring oldName = iter->first;
1163         Glib::ustring newName = iter->second;
1165         Glib::ustring ext = getExtension(oldName);
1166         if (ext == ".jpeg")
1167             ext = ".jpg";
1168         outs.printf("    <manifest:file-entry manifest:media-type=\"");
1169         if (ext == ".gif")
1170             outs.printf("image/gif");
1171         else if (ext == ".png")
1172             outs.printf("image/png");
1173         else if (ext == ".jpg")
1174             outs.printf("image/jpeg");
1175         outs.printf("\" manifest:full-path=\"");
1176         outs.printf((char *)newName.c_str());
1177         outs.printf("\"/>\n");
1178         }
1179     outs.printf("</manifest:manifest>\n");
1181     outs.close();
1183     //Make our entry
1184     ZipEntry *ze = zf.newEntry("META-INF/manifest.xml", "ODF file manifest");
1185     ze->setUncompressedData(bouts.getBuffer());
1186     ze->finish();
1188     return true;
1192 /**
1193  * This writes the document meta information to meta.xml
1194  */
1195 bool OdfOutput::writeMeta(ZipFile &zf)
1197     BufferOutputStream bouts;
1198     OutputStreamWriter outs(bouts);
1200     time_t tim;
1201     time(&tim);
1203     std::map<Glib::ustring, Glib::ustring>::iterator iter;
1204     Glib::ustring creator = "unknown";
1205     iter = metadata.find("dc:creator");
1206     if (iter != metadata.end())
1207         creator = iter->second;
1208     Glib::ustring date = "";
1209     iter = metadata.find("dc:date");
1210     if (iter != metadata.end())
1211         date = iter->second;
1213     outs.printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1214     outs.printf("\n");
1215     outs.printf("\n");
1216     outs.printf("<!--\n");
1217     outs.printf("*************************************************************************\n");
1218     outs.printf("  file:  meta.xml\n");
1219     outs.printf("  Generated by Inkscape: %s", ctime(&tim)); //ctime has its own <cr>
1220     outs.printf("  http://www.inkscape.org\n");
1221     outs.printf("*************************************************************************\n");
1222     outs.printf("-->\n");
1223     outs.printf("\n");
1224     outs.printf("\n");
1225     outs.printf("<office:document-meta\n");
1226     outs.printf("xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\"\n");
1227     outs.printf("xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n");
1228     outs.printf("xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n");
1229     outs.printf("xmlns:meta=\"urn:oasis:names:tc:opendocument:xmlns:meta:1.0\"\n");
1230     outs.printf("xmlns:presentation=\"urn:oasis:names:tc:opendocument:xmlns:presentation:1.0\"\n");
1231     outs.printf("xmlns:ooo=\"http://openoffice.org/2004/office\"\n");
1232     outs.printf("xmlns:smil=\"urn:oasis:names:tc:opendocument:xmlns:smil-compatible:1.0\"\n");
1233     outs.printf("xmlns:anim=\"urn:oasis:names:tc:opendocument:xmlns:animation:1.0\"\n");
1234     outs.printf("office:version=\"1.0\">\n");
1235     outs.printf("<office:meta>\n");
1236     outs.printf("    <meta:generator>Inkscape.org - 0.45</meta:generator>\n");
1237     outs.printf("    <meta:initial-creator>%#s</meta:initial-creator>\n",
1238                                   creator.c_str());
1239     outs.printf("    <meta:creation-date>%#s</meta:creation-date>\n", date.c_str());
1240     for (iter = metadata.begin() ; iter != metadata.end() ; iter++)
1241         {
1242         Glib::ustring name  = iter->first;
1243         Glib::ustring value = iter->second;
1244         if (name.size() > 0 && value.size()>0)
1245             {
1246             outs.printf("    <%#s>%#s</%#s>\n", 
1247                       name.c_str(), value.c_str(), name.c_str());
1248             }
1249         }
1250     outs.printf("    <meta:editing-cycles>2</meta:editing-cycles>\n");
1251     outs.printf("    <meta:editing-duration>PT56S</meta:editing-duration>\n");
1252     outs.printf("    <meta:user-defined meta:name=\"Info 1\"/>\n");
1253     outs.printf("    <meta:user-defined meta:name=\"Info 2\"/>\n");
1254     outs.printf("    <meta:user-defined meta:name=\"Info 3\"/>\n");
1255     outs.printf("    <meta:user-defined meta:name=\"Info 4\"/>\n");
1256     outs.printf("    <meta:document-statistic meta:object-count=\"2\"/>\n");
1257     outs.printf("</office:meta>\n");
1258     outs.printf("</office:document-meta>\n");
1259     outs.printf("\n");
1260     outs.printf("\n");
1263     outs.close();
1265     //Make our entry
1266     ZipEntry *ze = zf.newEntry("meta.xml", "ODF info file");
1267     ze->setUncompressedData(bouts.getBuffer());
1268     ze->finish();
1270     return true;
1276 /**
1277  * This is called just before writeTree(), since it will write style and
1278  * gradient information above the <draw> tag in the content.xml file
1279  */
1280 bool OdfOutput::writeStyle(ZipFile &zf)
1282     BufferOutputStream bouts;
1283     OutputStreamWriter outs(bouts);
1285     /*
1286     ==========================================================
1287     Dump our style table.  Styles should have a general layout
1288     something like the following.  Look in:
1289     http://books.evc-cit.info/odbook/ch06.html#draw-style-file-section
1290     for style and gradient information.
1291     <style:style style:name="gr13"
1292       style:family="graphic" style:parent-style-name="standard">
1293         <style:graphic-properties draw:stroke="solid"
1294             svg:stroke-width="0.1cm"
1295             svg:stroke-color="#ff0000"
1296             draw:fill="solid" draw:fill-color="#e6e6ff"/>
1297     </style:style>
1298     ==========================================================
1299     */
1300     outs.printf("<!-- ####### Styles from Inkscape document ####### -->\n");
1301     std::vector<StyleInfo>::iterator iter;
1302     for (iter = styleTable.begin() ; iter != styleTable.end() ; iter++)
1303         {
1304         outs.printf("<style:style style:name=\"%s\"", iter->name.c_str());
1305         StyleInfo s(*iter);
1306         outs.printf(" style:family=\"graphic\" style:parent-style-name=\"standard\">\n");
1307         outs.printf("  <style:graphic-properties");
1308         outs.printf(" draw:fill=\"%s\" ", s.fill.c_str());
1309         if (s.fill != "none")
1310             {
1311             outs.printf(" draw:fill-color=\"%s\" ", s.fillColor.c_str());
1312             outs.printf(" draw:fill-opacity=\"%s\" ", s.fillOpacity.c_str());
1313             }
1314         outs.printf(" draw:stroke=\"%s\" ", s.stroke.c_str());
1315         if (s.stroke != "none")
1316             {
1317             outs.printf(" svg:stroke-width=\"%s\" ", s.strokeWidth.c_str());
1318             outs.printf(" svg:stroke-color=\"%s\" ", s.strokeColor.c_str());
1319             outs.printf(" svg:stroke-opacity=\"%s\" ", s.strokeOpacity.c_str());
1320             }
1321         outs.printf("/>\n");
1322         outs.printf("</style:style>\n");
1323         }
1325     //##  Dump our gradient table
1326     int gradientCount = 0;
1327     outs.printf("\n");
1328     outs.printf("<!-- ####### Gradients from Inkscape document ####### -->\n");
1329     std::vector<GradientInfo>::iterator giter;
1330     for (giter = gradientTable.begin() ; giter != gradientTable.end() ; giter++)
1331         {
1332         GradientInfo gi(*giter);
1333         if (gi.style == "linear")
1334             {
1335             /*
1336             ===================================================================
1337             LINEAR gradient.  We need something that looks like this:
1338             <draw:gradient draw:name="Gradient_20_7"
1339                 draw:display-name="Gradient 7"
1340                 draw:style="linear"
1341                 draw:start-color="#008080" draw:end-color="#993366"
1342                 draw:start-intensity="100%" draw:end-intensity="100%"
1343                 draw:angle="150" draw:border="0%"/>
1344             ===================================================================
1345             */
1346             if (gi.stops.size() < 2)
1347                 {
1348                 g_warning("Need at least 2 tops for a linear gradient");
1349                 continue;
1350                 }
1351             outs.printf("<svg:linearGradient ");
1352             outs.printf("id=\"%#s_g\" ", gi.name.c_str());
1353             outs.printf("draw:name=\"%#s_g\"\n", gi.name.c_str());
1354             outs.printf("    draw:display-name=\"imported linear %d\"\n",
1355                         gradientCount);
1356             outs.printf("    svg:x1=\"%05.3fcm\" svg:y1=\"%05.3fcm\"\n",
1357                         gi.x1, gi.y1);
1358             outs.printf("    svg:x2=\"%05.3fcm\" svg:y2=\"%05.3fcm\"\n",
1359                         gi.x2, gi.y2);
1360             outs.printf("    svg:gradientUnits=\"objectBoundingBox\">\n");
1361             outs.printf("    <svg:stop\n");
1362             outs.printf("        svg:stop-color=\"#%06lx\"\n",
1363                         gi.stops[0].rgb);
1364             outs.printf("        svg:stop-opacity=\"%f%%\"\n",
1365                         gi.stops[0].opacity * 100.0);
1366             outs.printf("        svg:offset=\"0\"/>\n");
1367             outs.printf("    <svg:stop\n");
1368             outs.printf("        svg:stop-color=\"#%06lx\"\n",
1369                         gi.stops[1].rgb);
1370             outs.printf("        svg:stop-opacity=\"%f%%\"\n",
1371                         gi.stops[1].opacity * 100.0);
1372             outs.printf("        svg:offset=\"1\"/>\n");
1373             outs.printf("</svg:linearGradient>\n");
1374             }
1375         else if (gi.style == "radial")
1376             {
1377             /*
1378             ===================================================================
1379             RADIAL gradient.  We need something that looks like this:
1380             <!-- radial gradient, light gray to white, centered, 0% border -->
1381             <draw:gradient draw:name="radial_20_borderless"
1382                 draw:display-name="radial borderless"
1383                 draw:style="radial"
1384                 draw:cx="50%" draw:cy="50%"
1385                 draw:start-color="#999999" draw:end-color="#ffffff"
1386                 draw:border="0%"/>
1387             ===================================================================
1388             */
1389             if (gi.stops.size() < 2)
1390                 {
1391                 g_warning("Need at least 2 tops for a radial gradient");
1392                 continue;
1393                 }
1394             outs.printf("<svg:radialGradient ");
1395             outs.printf("id=\"%#s_g\" ", gi.name.c_str());
1396             outs.printf("draw:name=\"%#s_g\"\n", gi.name.c_str());
1397             outs.printf("    draw:display-name=\"imported radial %d\"\n",
1398                         gradientCount);
1399             outs.printf("    svg:cx=\"%05.3f\" svg:cy=\"%05.3f\"\n",
1400                         gi.cx, gi.cy);
1401             outs.printf("    svg:fx=\"%05.3f\" svg:fy=\"%05.3f\"\n",
1402                         gi.fx, gi.fy);
1403             outs.printf("    svg:r=\"%05.3f\"\n",
1404                         gi.r);
1405             outs.printf("    svg:gradientUnits=\"objectBoundingBox\">\n");
1406             outs.printf("    <svg:stop\n");
1407             outs.printf("        svg:stop-color=\"#%06lx\"\n",
1408                         gi.stops[0].rgb);
1409             outs.printf("        svg:stop-opacity=\"%f%%\"\n",
1410                         gi.stops[0].opacity * 100.0);
1411             outs.printf("        svg:offset=\"0\"/>\n");
1412             outs.printf("    <svg:stop\n");
1413             outs.printf("        svg:stop-color=\"#%06lx\"\n",
1414                         gi.stops[1].rgb);
1415             outs.printf("        svg:stop-opacity=\"%f%%\"\n",
1416                         gi.stops[1].opacity * 100.0);
1417             outs.printf("        svg:offset=\"1\"/>\n");
1418             outs.printf("</svg:radialGradient>\n");
1419             }
1420         else
1421             {
1422             g_warning("unsupported gradient style '%s'", gi.style.c_str());
1423             }
1424         outs.printf("<style:style style:name=\"%#s\" style:family=\"graphic\" ",
1425                   gi.name.c_str());
1426         outs.printf("style:parent-style-name=\"standard\">\n");
1427         outs.printf("    <style:graphic-properties draw:fill=\"gradient\" ");
1428         outs.printf("draw:fill-gradient-name=\"%#s_g\"\n",
1429                   gi.name.c_str());
1430         outs.printf("        draw:textarea-horizontal-align=\"center\" ");
1431         outs.printf("draw:textarea-vertical-align=\"middle\"/>\n");
1432         outs.printf("</style:style>\n\n");
1434         gradientCount++;
1435         }
1437     outs.printf("\n");
1438     outs.printf("</office:automatic-styles>\n");
1439     outs.printf("\n");
1440     outs.printf("\n");
1441     outs.printf("<office:master-styles>\n");
1442     outs.printf("<draw:layer-set>\n");
1443     outs.printf("    <draw:layer draw:name=\"layout\"/>\n");
1444     outs.printf("    <draw:layer draw:name=\"background\"/>\n");
1445     outs.printf("    <draw:layer draw:name=\"backgroundobjects\"/>\n");
1446     outs.printf("    <draw:layer draw:name=\"controls\"/>\n");
1447     outs.printf("    <draw:layer draw:name=\"measurelines\"/>\n");
1448     outs.printf("</draw:layer-set>\n");
1449     outs.printf("\n");
1450     outs.printf("<style:master-page style:name=\"Default\"\n");
1451     outs.printf("    style:page-master-name=\"PM1\" draw:style-name=\"dp1\"/>\n");
1452     outs.printf("</office:master-styles>\n");
1453     outs.printf("\n");
1454     outs.printf("\n");
1455     outs.printf("\n");
1456     outs.printf("</office:document-styles>\n");
1457     outs.printf("\n");
1458     outs.printf("<!--\n");
1459     outs.printf("*************************************************************************\n");
1460     outs.printf("  E N D    O F    F I L E\n");
1461     outs.printf("  Have a nice day  - ishmal\n");
1462     outs.printf("*************************************************************************\n");
1463     outs.printf("-->\n");
1464     outs.printf("\n");
1466     //Make our entry
1467     ZipEntry *ze = zf.newEntry("styles.xml", "ODF style file");
1468     ze->setUncompressedData(bouts.getBuffer());
1469     ze->finish();
1471     return true;
1476 /**
1477  * Writes an SVG path as an ODF <draw:path>
1478  */
1479 static int
1480 writePath(Writer &outs, NArtBpath const *bpath,
1481           NR::Matrix &tf, double xoff, double yoff)
1483     bool closed   = false;
1484     int nrPoints  = 0;
1485     NArtBpath *bp = (NArtBpath *)bpath;
1487     double destx = 0.0;
1488     double desty = 0.0;
1489     int code = -1;
1491     for (  ; bp->code != NR_END; bp++)
1492         {
1493         code = bp->code;
1495         NR::Point const p1(bp->c(1) * tf);
1496         NR::Point const p2(bp->c(2) * tf);
1497         NR::Point const p3(bp->c(3) * tf);
1498         double x1 = (p1[NR::X] - xoff) * 1000.0;
1499         if (fabs(x1)<1.0) x1=0.0;
1500         double y1 = (p1[NR::Y] - yoff) * 1000.0;
1501         if (fabs(y1)<1.0) y1=0.0;
1502         double x2 = (p2[NR::X] - xoff) * 1000.0;
1503         if (fabs(x2)<1.0) x2=0.0;
1504         double y2 = (p2[NR::Y] - yoff) * 1000.0;
1505         if (fabs(y2)<1.0) y2=0.0;
1506         double x3 = (p3[NR::X] - xoff) * 1000.0;
1507         if (fabs(x3)<1.0) x3=0.0;
1508         double y3 = (p3[NR::Y] - yoff) * 1000.0;
1509         if (fabs(y3)<1.0) y3=0.0;
1510         destx = x3;
1511         desty = y3;
1513         switch (code)
1514             {
1515             case NR_LINETO:
1516                 outs.printf("L %.3f %.3f ",  destx, desty);
1517                 break;
1519             case NR_CURVETO:
1520                 outs.printf("C %.3f %.3f %.3f %.3f %.3f %.3f ",
1521                               x1, y1, x2, y2, destx, desty);
1522                 break;
1524             case NR_MOVETO_OPEN:
1525             case NR_MOVETO:
1526                 if (closed)
1527                     outs.printf("Z ");
1528                 closed = ( code == NR_MOVETO );
1529                 outs.printf("M %.3f %.3f ",  destx, desty);
1530                 break;
1532             default:
1533                 break;
1535             }
1537         nrPoints++;
1538         }
1540     if (closed)
1541         {
1542         outs.printf("Z");
1543         }
1545     return nrPoints;
1550 bool OdfOutput::processStyle(Writer &outs, SPItem *item,
1551                              const Glib::ustring &id)
1553     SPStyle *style = item->style;
1555     StyleInfo si;
1557     //## FILL
1558     if (style->fill.type == SP_PAINT_TYPE_COLOR)
1559         {
1560         guint32 fillCol =
1561             sp_color_get_rgba32_ualpha(&style->fill.value.color, 0);
1562         char buf[16];
1563         int r = (fillCol >> 24) & 0xff;
1564         int g = (fillCol >> 16) & 0xff;
1565         int b = (fillCol >>  8) & 0xff;
1566         //g_message("## %s %lx", id.c_str(), (unsigned int)fillCol);
1567         snprintf(buf, 15, "#%02x%02x%02x", r, g, b);
1568         si.fillColor = buf;
1569         si.fill      = "solid";
1570         double opacityPercent = 100.0 *
1571              (SP_SCALE24_TO_FLOAT(style->fill_opacity.value));
1572         snprintf(buf, 15, "%.3f%%", opacityPercent);
1573         si.fillOpacity = buf;
1574         }
1576     //## STROKE
1577     if (style->stroke.type == SP_PAINT_TYPE_COLOR)
1578         {
1579         guint32 strokeCol =
1580             sp_color_get_rgba32_ualpha(&style->stroke.value.color, 0);
1581         char buf[16];
1582         int r = (strokeCol >> 24) & 0xff;
1583         int g = (strokeCol >> 16) & 0xff;
1584         int b = (strokeCol >>  8) & 0xff;
1585         snprintf(buf, 15, "#%02x%02x%02x", r, g, b);
1586         si.strokeColor = buf;
1587         snprintf(buf, 15, "%.3fpt", style->stroke_width.value);
1588         si.strokeWidth = buf;
1589         si.stroke      = "solid";
1590         double opacityPercent = 100.0 *
1591              (SP_SCALE24_TO_FLOAT(style->stroke_opacity.value));
1592         snprintf(buf, 15, "%.3f%%", opacityPercent);
1593         si.strokeOpacity = buf;
1594         }
1596     //Look for existing identical style;
1597     bool styleMatch = false;
1598     std::vector<StyleInfo>::iterator iter;
1599     for (iter=styleTable.begin() ; iter!=styleTable.end() ; iter++)
1600         {
1601         if (si.equals(*iter))
1602             {
1603             //map to existing styleTable entry
1604             Glib::ustring styleName = iter->name;
1605             //g_message("found duplicate style:%s", styleName.c_str());
1606             styleLookupTable[id] = styleName;
1607             styleMatch = true;
1608             break;
1609             }
1610         }
1612     //## Dont need a new style
1613     if (styleMatch)
1614         return false;
1616     char buf[16];
1617     snprintf(buf, 15, "style%d", (int)styleTable.size());
1618     Glib::ustring styleName = buf;
1619     si.name = styleName;
1620     styleTable.push_back(si);
1621     styleLookupTable[id] = styleName;
1623     outs.printf("<style:style style:name=\"%s\"", si.name.c_str());
1624     outs.printf(" style:family=\"graphic\" style:parent-style-name=\"standard\">\n");
1625     outs.printf("  <style:graphic-properties");
1626     outs.printf(" draw:fill=\"%s\" ", si.fill.c_str());
1627     if (si.fill != "none")
1628         {
1629         outs.printf(" draw:fill-color=\"%s\" ", si.fillColor.c_str());
1630         outs.printf(" draw:fill-opacity=\"%s\" ", si.fillOpacity.c_str());
1631         }
1632     outs.printf(" draw:stroke=\"%s\" ", si.stroke.c_str());
1633     if (si.stroke != "none")
1634         {
1635         outs.printf(" svg:stroke-width=\"%s\" ", si.strokeWidth.c_str());
1636         outs.printf(" svg:stroke-color=\"%s\" ", si.strokeColor.c_str());
1637         outs.printf(" svg:stroke-opacity=\"%s\" ", si.strokeOpacity.c_str());
1638         }
1639     outs.printf("/>\n");
1640     outs.printf("</style:style>\n");
1642     return true;
1648 bool OdfOutput::processGradient(Writer &outs, SPItem *item,
1649                                 const Glib::ustring &id, NR::Matrix &tf)
1651     SPStyle *style = item->style;
1653     //## Gradient.  Look in writeStyle() below to see what info
1654     //   we need to read into GradientInfo.
1655     if (!SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)))
1656         return false;
1658     SPGradient *gradient = SP_GRADIENT(SP_STYLE_FILL_SERVER(style));
1660     GradientInfo gi;
1662     SPGradient *grvec = sp_gradient_get_vector(gradient, FALSE);
1663     for (SPStop *stop = sp_first_stop(grvec) ;
1664           stop ; stop = sp_next_stop(stop))
1665         {
1666         unsigned long rgba = sp_stop_get_rgba32(stop);
1667         unsigned long rgb  = (rgba >> 8) & 0xffffff;
1668         double opacity     = ((double)(rgba & 0xff)) / 256.0;
1669         GradientStop gs(rgb, opacity);
1670         gi.stops.push_back(gs);
1671         }
1673     if (SP_IS_LINEARGRADIENT(gradient))
1674         {
1675         gi.style = "linear";
1676         SPLinearGradient *linGrad = SP_LINEARGRADIENT(gradient);
1677         /*
1678         NR::Point p1(linGrad->x1.value, linGrad->y1.value);
1679         p1 = p1 * tf;
1680         gi.x1 = p1[NR::X];
1681         gi.y1 = p1[NR::Y];
1682         NR::Point p2(linGrad->x2.value, linGrad->y2.value);
1683         p2 = p2 * tf;
1684         gi.x2 = p2[NR::X];
1685         gi.y2 = p2[NR::Y];
1686         */
1687         gi.x1 = linGrad->x1.value;
1688         gi.y1 = linGrad->y1.value;
1689         gi.x2 = linGrad->x2.value;
1690         gi.y2 = linGrad->y2.value;
1691         }
1692     else if (SP_IS_RADIALGRADIENT(gradient))
1693         {
1694         gi.style = "radial";
1695         SPRadialGradient *radGrad = SP_RADIALGRADIENT(gradient);
1696         gi.cx = radGrad->cx.computed * 100.0;//ODG cx is percentages
1697         gi.cy = radGrad->cy.computed * 100.0;
1698         }
1699     else
1700         {
1701         g_warning("not a supported gradient type");
1702         return false;
1703         }
1705     //Look for existing identical style;
1706     bool gradientMatch = false;
1707     std::vector<GradientInfo>::iterator iter;
1708     for (iter=gradientTable.begin() ; iter!=gradientTable.end() ; iter++)
1709         {
1710         if (gi.equals(*iter))
1711             {
1712             //map to existing gradientTable entry
1713             Glib::ustring gradientName = iter->name;
1714             //g_message("found duplicate style:%s", gradientName.c_str());
1715             gradientLookupTable[id] = gradientName;
1716             gradientMatch = true;
1717             break;
1718             }
1719         }
1721     if (gradientMatch)
1722         return true;
1724     //## No match, let us write a new entry
1725     char buf[16];
1726     snprintf(buf, 15, "gradient%d", (int)gradientTable.size());
1727     Glib::ustring gradientName = buf;
1728     gi.name = gradientName;
1729     gradientTable.push_back(gi);
1730     gradientLookupTable[id] = gradientName;
1732     int gradientCount = gradientTable.size();
1734     if (gi.style == "linear")
1735         {
1736         /*
1737         ===================================================================
1738         LINEAR gradient.  We need something that looks like this:
1739         <draw:gradient draw:name="Gradient_20_7"
1740             draw:display-name="Gradient 7"
1741             draw:style="linear"
1742             draw:start-color="#008080" draw:end-color="#993366"
1743             draw:start-intensity="100%" draw:end-intensity="100%"
1744             draw:angle="150" draw:border="0%"/>
1745         ===================================================================
1746         */
1747         if (gi.stops.size() < 2)
1748             {
1749             g_warning("Need at least 2 stops for a linear gradient");
1750             return false;;
1751             }
1752         outs.printf("<svg:linearGradient ");
1753         outs.printf("id=\"%#s_g\" ", gi.name.c_str());
1754         outs.printf("draw:name=\"%#s_g\"\n", gi.name.c_str());
1755         outs.printf("    draw:display-name=\"imported linear %d\"\n",
1756                     gradientCount);
1757         outs.printf("    svg:gradientUnits=\"objectBoundingBox\"\n");
1758         outs.printf("    svg:x1=\"%05.3fcm\" svg:y1=\"%05.3fcm\"\n",
1759                     gi.x1 * pxToCm, gi.y1 * pxToCm);
1760         outs.printf("    svg:x2=\"%05.3fcm\" svg:y2=\"%05.3fcm\">\n",
1761                     gi.x2 * pxToCm, gi.y2 * pxToCm);
1762         outs.printf("    <svg:stop\n");
1763         outs.printf("        svg:stop-color=\"#%06lx\"\n",
1764                     gi.stops[0].rgb);
1765         outs.printf("        svg:stop-opacity=\"%f%%\"\n",
1766                     gi.stops[0].opacity * 100.0);
1767         outs.printf("        svg:offset=\"0\"/>\n");
1768         outs.printf("    <svg:stop\n");
1769         outs.printf("        svg:stop-color=\"#%06lx\"\n",
1770                     gi.stops[1].rgb);
1771         outs.printf("        svg:stop-opacity=\"%f%%\"\n",
1772                     gi.stops[1].opacity * 100.0);
1773         outs.printf("        svg:offset=\"1\"/>\n");
1774         outs.printf("</svg:linearGradient>\n");
1775         }
1776     else if (gi.style == "radial")
1777         {
1778         /*
1779         ===================================================================
1780         RADIAL gradient.  We need something that looks like this:
1781         <!-- radial gradient, light gray to white, centered, 0% border -->
1782         <draw:gradient draw:name="radial_20_borderless"
1783             draw:display-name="radial borderless"
1784             draw:style="radial"
1785             draw:cx="50%" draw:cy="50%"
1786             draw:start-color="#999999" draw:end-color="#ffffff"
1787             draw:border="0%"/>
1788         ===================================================================
1789         */
1790         if (gi.stops.size() < 2)
1791             {
1792             g_warning("Need at least 2 stops for a radial gradient");
1793             return false;
1794             }
1795         outs.printf("<svg:radialGradient ");
1796         outs.printf("id=\"%#s_g\" ", gi.name.c_str());
1797         outs.printf("draw:name=\"%#s_g\"\n", gi.name.c_str());
1798         outs.printf("    draw:display-name=\"imported radial %d\"\n",
1799                     gradientCount);
1800         outs.printf("    svg:gradientUnits=\"objectBoundingBox\"\n");
1801         outs.printf("    svg:cx=\"%05.3f\" svg:cy=\"%05.3f\"\n",
1802                     gi.cx, gi.cy);
1803         outs.printf("    svg:fx=\"%05.3f\" svg:fy=\"%05.3f\"\n",
1804                     gi.fx, gi.fy);
1805         outs.printf("    svg:r=\"%05.3f\">\n",
1806                     gi.r);
1807         outs.printf("    <svg:stop\n");
1808         outs.printf("        svg:stop-color=\"#%06lx\"\n",
1809                     gi.stops[0].rgb);
1810         outs.printf("        svg:stop-opacity=\"%f%%\"\n",
1811                     gi.stops[0].opacity * 100.0);
1812         outs.printf("        svg:offset=\"0\"/>\n");
1813         outs.printf("    <svg:stop\n");
1814         outs.printf("        svg:stop-color=\"#%06lx\"\n",
1815                     gi.stops[1].rgb);
1816         outs.printf("        svg:stop-opacity=\"%f%%\"\n",
1817                     gi.stops[1].opacity * 100.0);
1818         outs.printf("        svg:offset=\"1\"/>\n");
1819         outs.printf("</svg:radialGradient>\n");
1820         }
1821     else
1822         {
1823         g_warning("unsupported gradient style '%s'", gi.style.c_str());
1824         return false;
1825         }
1826     outs.printf("<style:style style:name=\"%#s\" style:family=\"graphic\" ",
1827               gi.name.c_str());
1828     outs.printf("style:parent-style-name=\"standard\">\n");
1829     outs.printf("    <style:graphic-properties draw:fill=\"gradient\" ");
1830     outs.printf("draw:fill-gradient-name=\"%#s_g\"\n",
1831               gi.name.c_str());
1832     outs.printf("        draw:textarea-horizontal-align=\"center\" ");
1833     outs.printf("draw:textarea-vertical-align=\"middle\"/>\n");
1834     outs.printf("</style:style>\n\n");
1835  
1836     return true;
1842 /**
1843  * SECOND PASS.
1844  * This is the main SPObject tree output to ODF.  preprocess()
1845  * must be called prior to this, as elements will often reference
1846  * data parsed and tabled in preprocess().
1847  */
1848 bool OdfOutput::writeTree(Writer &couts, Writer &souts,
1849                           Inkscape::XML::Node *node)
1851     //# Get the SPItem, if applicable
1852     SPObject *reprobj = SP_ACTIVE_DOCUMENT->getObjectByRepr(node);
1853     if (!reprobj)
1854         return true;
1855     if (!SP_IS_ITEM(reprobj))
1856         {
1857         return true;
1858         }
1859     SPItem *item = SP_ITEM(reprobj);
1862     Glib::ustring nodeName = node->name();
1863     Glib::ustring id       = getAttribute(node, "id");
1865     //### Get SVG-to-ODF transform
1866     NR::Matrix tf        = getODFTransform(item);
1868     //### Get ODF bounding box params for item
1869     NR::Rect bbox        = getODFBoundingBox(item);
1870     double bbox_x        = bbox.min()[NR::X];
1871     double bbox_y        = bbox.min()[NR::Y];
1872     double bbox_width    = bbox.max()[NR::X] - bbox.min()[NR::X];
1873     double bbox_height   = bbox.max()[NR::Y] - bbox.min()[NR::Y];
1875     double rotate;
1876     double xskew;
1877     double yskew;
1878     double xscale;
1879     double yscale;
1880     analyzeTransform(tf, rotate, xskew, yskew, xscale, yscale);
1882     //# Do our stuff
1883     SPCurve *curve = NULL;
1887     if (nodeName == "svg" || nodeName == "svg:svg")
1888         {
1889         //# Iterate through the children
1890         for (Inkscape::XML::Node *child = node->firstChild() ;
1891                child ; child = child->next())
1892             {
1893             if (!writeTree(couts, souts, child))
1894                 return false;
1895             }
1896         return true;
1897         }
1898     else if (nodeName == "g" || nodeName == "svg:g")
1899         {
1900         if (id.size() > 0)
1901             couts.printf("<draw:g id=\"%s\">\n", id.c_str());
1902         else
1903             couts.printf("<draw:g>\n");
1904         //# Iterate through the children
1905         for (Inkscape::XML::Node *child = node->firstChild() ;
1906                child ; child = child->next())
1907             {
1908             if (!writeTree(couts, souts, child))
1909                 return false;
1910             }
1911         if (id.size() > 0)
1912             couts.printf("</draw:g> <!-- id=\"%s\" -->\n", id.c_str());
1913         else
1914             couts.printf("</draw:g>\n");
1915         return true;
1916         }
1918     //######################################
1919     //# S T Y L E
1920     //######################################
1921     processStyle(souts, item, id);
1923     //######################################
1924     //# G R A D I E N T
1925     //######################################
1926     processGradient(souts, item, id, tf);
1931     //######################################
1932     //# I T E M    D A T A
1933     //######################################
1934     //g_message("##### %s #####", nodeName.c_str());
1935     if (nodeName == "image" || nodeName == "svg:image")
1936         {
1937         if (!SP_IS_IMAGE(item))
1938             {
1939             g_warning("<image> is not an SPImage.  Why?  ;-)");
1940             return false;
1941             }
1943         SPImage *img   = SP_IMAGE(item);
1944         double ix      = img->x.value;
1945         double iy      = img->y.value;
1946         double iwidth  = img->width.value;
1947         double iheight = img->height.value;
1949         NR::Rect ibbox(NR::Point(ix, iy), NR::Point(ix+iwidth, iy+iheight));
1950         ibbox = ibbox * tf;
1951         ix      = ibbox.min()[NR::X];
1952         iy      = ibbox.min()[NR::Y];
1953         //iwidth  = ibbox.max()[NR::X] - ibbox.min()[NR::X];
1954         //iheight = ibbox.max()[NR::Y] - ibbox.min()[NR::Y];
1955         iwidth  = xscale * iwidth;
1956         iheight = yscale * iheight;
1958         NR::Matrix itemTransform = getODFItemTransform(item);
1960         Glib::ustring itemTransformString = formatTransform(itemTransform);
1962         Glib::ustring href = getAttribute(node, "xlink:href");
1963         std::map<Glib::ustring, Glib::ustring>::iterator iter = imageTable.find(href);
1964         if (iter == imageTable.end())
1965             {
1966             g_warning("image '%s' not in table", href.c_str());
1967             return false;
1968             }
1969         Glib::ustring newName = iter->second;
1971         couts.printf("<draw:frame ");
1972         if (id.size() > 0)
1973             couts.printf("id=\"%s\" ", id.c_str());
1974         couts.printf("draw:style-name=\"gr1\" draw:text-style-name=\"P1\" draw:layer=\"layout\" ");
1975         //no x or y.  make them the translate transform, last one
1976         couts.printf("svg:width=\"%.3fcm\" svg:height=\"%.3fcm\" ",
1977                                   iwidth, iheight);
1978         if (itemTransformString.size() > 0)
1979             {
1980             couts.printf("draw:transform=\"%s translate(%.3fcm, %.3fcm)\" ",
1981                            itemTransformString.c_str(), ix, iy);
1982             }
1983         else
1984             {
1985             couts.printf("draw:transform=\"translate(%.3fcm, %.3fcm)\" ",
1986                                 ix, iy);
1987             }
1989         couts.printf(">\n");
1990         couts.printf("    <draw:image xlink:href=\"%s\" xlink:type=\"simple\"\n",
1991                               newName.c_str());
1992         couts.printf("        xlink:show=\"embed\" xlink:actuate=\"onLoad\">\n");
1993         couts.printf("        <text:p/>\n");
1994         couts.printf("    </draw:image>\n");
1995         couts.printf("</draw:frame>\n");
1996         return true;
1997         }
1998     else if (SP_IS_SHAPE(item))
1999         {
2000         //g_message("### %s is a shape", nodeName.c_str());
2001         curve = sp_shape_get_curve(SP_SHAPE(item));
2002         }
2003     else if (SP_IS_TEXT(item) || SP_IS_FLOWTEXT(item))
2004         {
2005         curve = te_get_layout(item)->convertToCurves();
2006         }
2008     if (curve)
2009         {
2010         //### Default <path> output
2012         couts.printf("<draw:path ");
2013         if (id.size()>0)
2014             couts.printf("id=\"%s\" ", id.c_str());
2016         std::map<Glib::ustring, Glib::ustring>::iterator siter;
2017         siter = styleLookupTable.find(id);
2018         if (siter != styleLookupTable.end())
2019             {
2020             Glib::ustring styleName = siter->second;
2021             couts.printf("draw:style-name=\"%s\" ", styleName.c_str());
2022             }
2024         std::map<Glib::ustring, Glib::ustring>::iterator giter;
2025         giter = gradientLookupTable.find(id);
2026         if (giter != gradientLookupTable.end())
2027             {
2028             Glib::ustring gradientName = giter->second;
2029             couts.printf("draw:fill-gradient-name=\"%s\" ",
2030                  gradientName.c_str());
2031             }
2033         couts.printf("draw:layer=\"layout\" svg:x=\"%.3fcm\" svg:y=\"%.3fcm\" ",
2034                        bbox_x, bbox_y);
2035         couts.printf("svg:width=\"%.3fcm\" svg:height=\"%.3fcm\" ",
2036                        bbox_width, bbox_height);
2037         couts.printf("svg:viewBox=\"0.0 0.0 %.3f %.3f\"\n",
2038                        bbox_width * 1000.0, bbox_height * 1000.0);
2040         couts.printf("    svg:d=\"");
2041         int nrPoints = writePath(couts, SP_CURVE_BPATH(curve),
2042                              tf, bbox_x, bbox_y);
2043         couts.printf("\"");
2045         couts.printf(">\n");
2046         couts.printf("    <!-- %d nodes -->\n", nrPoints);
2047         couts.printf("</draw:path>\n\n");
2050         sp_curve_unref(curve);
2051         }
2053     return true;
2058 /**
2059  * Write the header for the content.xml file
2060  */
2061 bool OdfOutput::writeStyleHeader(Writer &outs)
2063     time_t tim;
2064     time(&tim);
2066     outs.printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
2067     outs.printf("\n");
2068     outs.printf("\n");
2069     outs.printf("<!--\n");
2070     outs.printf("*************************************************************************\n");
2071     outs.printf("  file:  styles.xml\n");
2072     outs.printf("  Generated by Inkscape: %s", ctime(&tim)); //ctime has its own <cr>
2073     outs.printf("  http://www.inkscape.org\n");
2074     outs.printf("*************************************************************************\n");
2075     outs.printf("-->\n");
2076     outs.printf("\n");
2077     outs.printf("\n");
2078     outs.printf("<office:document-styles\n");
2079     outs.printf("    xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\"\n");
2080     outs.printf("    xmlns:style=\"urn:oasis:names:tc:opendocument:xmlns:style:1.0\"\n");
2081     outs.printf("    xmlns:text=\"urn:oasis:names:tc:opendocument:xmlns:text:1.0\"\n");
2082     outs.printf("    xmlns:table=\"urn:oasis:names:tc:opendocument:xmlns:table:1.0\"\n");
2083     outs.printf("    xmlns:draw=\"urn:oasis:names:tc:opendocument:xmlns:drawing:1.0\"\n");
2084     outs.printf("    xmlns:fo=\"urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0\"\n");
2085     outs.printf("    xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n");
2086     outs.printf("    xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n");
2087     outs.printf("    xmlns:meta=\"urn:oasis:names:tc:opendocument:xmlns:meta:1.0\"\n");
2088     outs.printf("    xmlns:number=\"urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0\"\n");
2089     outs.printf("    xmlns:presentation=\"urn:oasis:names:tc:opendocument:xmlns:presentation:1.0\"\n");
2090     outs.printf("    xmlns:svg=\"urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0\"\n");
2091     outs.printf("    xmlns:chart=\"urn:oasis:names:tc:opendocument:xmlns:chart:1.0\"\n");
2092     outs.printf("    xmlns:dr3d=\"urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0\"\n");
2093     outs.printf("    xmlns:math=\"http://www.w3.org/1998/Math/MathML\"\n");
2094     outs.printf("    xmlns:form=\"urn:oasis:names:tc:opendocument:xmlns:form:1.0\"\n");
2095     outs.printf("    xmlns:script=\"urn:oasis:names:tc:opendocument:xmlns:script:1.0\"\n");
2096     outs.printf("    xmlns:ooo=\"http://openoffice.org/2004/office\"\n");
2097     outs.printf("    xmlns:ooow=\"http://openoffice.org/2004/writer\"\n");
2098     outs.printf("    xmlns:oooc=\"http://openoffice.org/2004/calc\"\n");
2099     outs.printf("    xmlns:dom=\"http://www.w3.org/2001/xml-events\"\n");
2100     outs.printf("    xmlns:xforms=\"http://www.w3.org/2002/xforms\"\n");
2101     outs.printf("    xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n");
2102     outs.printf("    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n");
2103     outs.printf("    xmlns:smil=\"urn:oasis:names:tc:opendocument:xmlns:smil-compatible:1.0\"\n");
2104     outs.printf("    xmlns:anim=\"urn:oasis:names:tc:opendocument:xmlns:animation:1.0\"\n");
2105     outs.printf("    office:version=\"1.0\">\n");
2106     outs.printf("\n");
2107     outs.printf("\n");
2108     outs.printf("<!--\n");
2109     outs.printf("*************************************************************************\n");
2110     outs.printf("  S T Y L E S\n");
2111     outs.printf("  Style entries have been pulled from the svg style and\n");
2112     outs.printf("  representation attributes in the SVG tree.  The tree elements\n");
2113     outs.printf("  then refer to them by name, in the ODF manner\n");
2114     outs.printf("*************************************************************************\n");
2115     outs.printf("-->\n");
2116     outs.printf("\n");
2117     outs.printf("<office:styles>\n");
2118     outs.printf("\n");
2120     return true;
2124 /**
2125  * Write the footer for the style.xml file
2126  */
2127 bool OdfOutput::writeStyleFooter(Writer &outs)
2129     outs.printf("\n");
2130     outs.printf("</office:styles>\n");
2131     outs.printf("\n");
2132     outs.printf("\n");
2133     outs.printf("<office:automatic-styles>\n");
2134     outs.printf("<!-- ####### 'Standard' styles ####### -->\n");
2135     outs.printf("<style:style style:name=\"dp1\" style:family=\"drawing-page\"/>\n");
2136     outs.printf("<style:style style:name=\"gr1\" style:family=\"graphic\" style:parent-style-name=\"standard\">\n");
2137     outs.printf("  <style:graphic-properties draw:stroke=\"none\" draw:fill=\"none\"\n");
2138     outs.printf("       draw:textarea-horizontal-align=\"center\"\n");
2139     outs.printf("       draw:textarea-vertical-align=\"middle\" draw:color-mode=\"standard\"\n");
2140     outs.printf("       draw:luminance=\"0%%\" draw:contrast=\"0%%\" draw:gamma=\"100%%\" draw:red=\"0%%\"\n");
2141     outs.printf("       draw:green=\"0%%\" draw:blue=\"0%%\" fo:clip=\"rect(0cm 0cm 0cm 0cm)\"\n");
2142     outs.printf("       draw:image-opacity=\"100%%\" style:mirror=\"none\"/>\n");
2143     outs.printf("</style:style>\n");
2144     outs.printf("<style:style style:name=\"P1\" style:family=\"paragraph\">\n");
2145     outs.printf("  <style:paragraph-properties fo:text-align=\"center\"/>\n");
2146     outs.printf("</style:style>\n");
2147     outs.printf("</office:automatic-styles>\n");
2148     outs.printf("\n");
2149     outs.printf("\n");
2150     outs.printf("<office:master-styles>\n");
2151     outs.printf("<draw:layer-set>\n");
2152     outs.printf("    <draw:layer draw:name=\"layout\"/>\n");
2153     outs.printf("    <draw:layer draw:name=\"background\"/>\n");
2154     outs.printf("    <draw:layer draw:name=\"backgroundobjects\"/>\n");
2155     outs.printf("    <draw:layer draw:name=\"controls\"/>\n");
2156     outs.printf("    <draw:layer draw:name=\"measurelines\"/>\n");
2157     outs.printf("</draw:layer-set>\n");
2158     outs.printf("\n");
2159     outs.printf("<style:master-page style:name=\"Default\"\n");
2160     outs.printf("    style:page-master-name=\"PM1\" draw:style-name=\"dp1\"/>\n");
2161     outs.printf("</office:master-styles>\n");
2162     outs.printf("\n");
2163     outs.printf("\n");
2164     outs.printf("\n");
2165     outs.printf("</office:document-styles>\n");
2166     outs.printf("\n");
2167     outs.printf("<!--\n");
2168     outs.printf("*************************************************************************\n");
2169     outs.printf("  E N D    O F    F I L E\n");
2170     outs.printf("  Have a nice day  - ishmal\n");
2171     outs.printf("*************************************************************************\n");
2172     outs.printf("-->\n");
2173     outs.printf("\n");
2175     return true;
2181 /**
2182  * Write the header for the content.xml file
2183  */
2184 bool OdfOutput::writeContentHeader(Writer &outs)
2186     time_t tim;
2187     time(&tim);
2189     outs.printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
2190     outs.printf("\n");
2191     outs.printf("\n");
2192     outs.printf("<!--\n");
2193     outs.printf("*************************************************************************\n");
2194     outs.printf("  file:  content.xml\n");
2195     outs.printf("  Generated by Inkscape: %s", ctime(&tim)); //ctime has its own <cr>
2196     outs.printf("  http://www.inkscape.org\n");
2197     outs.printf("*************************************************************************\n");
2198     outs.printf("-->\n");
2199     outs.printf("\n");
2200     outs.printf("\n");
2201     outs.printf("<office:document-content\n");
2202     outs.printf("    xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\"\n");
2203     outs.printf("    xmlns:style=\"urn:oasis:names:tc:opendocument:xmlns:style:1.0\"\n");
2204     outs.printf("    xmlns:text=\"urn:oasis:names:tc:opendocument:xmlns:text:1.0\"\n");
2205     outs.printf("    xmlns:table=\"urn:oasis:names:tc:opendocument:xmlns:table:1.0\"\n");
2206     outs.printf("    xmlns:draw=\"urn:oasis:names:tc:opendocument:xmlns:drawing:1.0\"\n");
2207     outs.printf("    xmlns:fo=\"urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0\"\n");
2208     outs.printf("    xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n");
2209     outs.printf("    xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n");
2210     outs.printf("    xmlns:meta=\"urn:oasis:names:tc:opendocument:xmlns:meta:1.0\"\n");
2211     outs.printf("    xmlns:number=\"urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0\"\n");
2212     outs.printf("    xmlns:presentation=\"urn:oasis:names:tc:opendocument:xmlns:presentation:1.0\"\n");
2213     outs.printf("    xmlns:svg=\"urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0\"\n");
2214     outs.printf("    xmlns:chart=\"urn:oasis:names:tc:opendocument:xmlns:chart:1.0\"\n");
2215     outs.printf("    xmlns:dr3d=\"urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0\"\n");
2216     outs.printf("    xmlns:math=\"http://www.w3.org/1998/Math/MathML\"\n");
2217     outs.printf("    xmlns:form=\"urn:oasis:names:tc:opendocument:xmlns:form:1.0\"\n");
2218     outs.printf("    xmlns:script=\"urn:oasis:names:tc:opendocument:xmlns:script:1.0\"\n");
2219     outs.printf("    xmlns:ooo=\"http://openoffice.org/2004/office\"\n");
2220     outs.printf("    xmlns:ooow=\"http://openoffice.org/2004/writer\"\n");
2221     outs.printf("    xmlns:oooc=\"http://openoffice.org/2004/calc\"\n");
2222     outs.printf("    xmlns:dom=\"http://www.w3.org/2001/xml-events\"\n");
2223     outs.printf("    xmlns:xforms=\"http://www.w3.org/2002/xforms\"\n");
2224     outs.printf("    xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n");
2225     outs.printf("    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n");
2226     outs.printf("    xmlns:smil=\"urn:oasis:names:tc:opendocument:xmlns:smil-compatible:1.0\"\n");
2227     outs.printf("    xmlns:anim=\"urn:oasis:names:tc:opendocument:xmlns:animation:1.0\"\n");
2228     outs.printf("    office:version=\"1.0\">\n");
2229     outs.printf("\n");
2230     outs.printf("\n");
2231     outs.printf("<office:scripts/>\n");
2232     outs.printf("\n");
2233     outs.printf("\n");
2234     outs.printf("<!--\n");
2235     outs.printf("*************************************************************************\n");
2236     outs.printf("  D R A W I N G\n");
2237     outs.printf("  This section is the heart of SVG-ODF conversion.  We are\n");
2238     outs.printf("  starting with simple conversions, and will slowly evolve\n");
2239     outs.printf("  into a 'smarter' translation as time progresses.  Any help\n");
2240     outs.printf("  in improving .odg export is welcome.\n");
2241     outs.printf("*************************************************************************\n");
2242     outs.printf("-->\n");
2243     outs.printf("\n");
2244     outs.printf("\n");
2245     outs.printf("<office:body>\n");
2246     outs.printf("<office:drawing>\n");
2247     outs.printf("<draw:page draw:name=\"page1\" draw:style-name=\"dp1\"\n");
2248     outs.printf("        draw:master-page-name=\"Default\">\n");
2249     outs.printf("\n");
2250     outs.printf("\n");
2252     return true;
2256 /**
2257  * Write the footer for the content.xml file
2258  */
2259 bool OdfOutput::writeContentFooter(Writer &outs)
2261     outs.printf("\n");
2262     outs.printf("\n");
2264     outs.printf("</draw:page>\n");
2265     outs.printf("</office:drawing>\n");
2267     outs.printf("\n");
2268     outs.printf("\n");
2269     outs.printf("<!-- ######### CONVERSION FROM SVG ENDS ######## -->\n");
2270     outs.printf("\n");
2271     outs.printf("\n");
2273     outs.printf("</office:body>\n");
2274     outs.printf("</office:document-content>\n");
2275     outs.printf("\n");
2276     outs.printf("\n");
2277     outs.printf("\n");
2278     outs.printf("<!--\n");
2279     outs.printf("*************************************************************************\n");
2280     outs.printf("  E N D    O F    F I L E\n");
2281     outs.printf("  Have a nice day  - ishmal\n");
2282     outs.printf("*************************************************************************\n");
2283     outs.printf("-->\n");
2284     outs.printf("\n");
2285     outs.printf("\n");
2287     return true;
2292 /**
2293  * Write the content.xml file.  Writes the namesspace headers, then
2294  * calls writeTree().
2295  */
2296 bool OdfOutput::writeContent(ZipFile &zf, Inkscape::XML::Node *node)
2298     //Content.xml stream
2299     BufferOutputStream cbouts;
2300     OutputStreamWriter couts(cbouts);
2302     if (!writeContentHeader(couts))
2303         return false;
2305     //Style.xml stream
2306     BufferOutputStream sbouts;
2307     OutputStreamWriter souts(sbouts);
2309     if (!writeStyleHeader(souts))
2310         return false;
2313     //# Descend into the tree, doing all of our conversions
2314     //# to both files as the same time
2315     if (!writeTree(couts, souts, node))
2316         {
2317         g_warning("Failed to convert SVG tree");
2318         return false;
2319         }
2323     //# Finish content file
2324     if (!writeContentFooter(couts))
2325         return false;
2327     ZipEntry *ze = zf.newEntry("content.xml", "ODF master content file");
2328     ze->setUncompressedData(cbouts.getBuffer());
2329     ze->finish();
2333     //# Finish style file
2334     if (!writeStyleFooter(souts))
2335         return false;
2337     ze = zf.newEntry("styles.xml", "ODF style file");
2338     ze->setUncompressedData(sbouts.getBuffer());
2339     ze->finish();
2341     return true;
2345 /**
2346  * Resets class to its pristine condition, ready to use again
2347  */
2348 void
2349 OdfOutput::reset()
2351     metadata.clear();
2352     styleTable.clear();
2353     styleLookupTable.clear();
2354     gradientTable.clear();
2355     gradientLookupTable.clear();
2356     imageTable.clear();
2362 /**
2363  * Descends into the SVG tree, mapping things to ODF when appropriate
2364  */
2365 void
2366 OdfOutput::save(Inkscape::Extension::Output *mod, SPDocument *doc, gchar const *uri)
2368     reset();
2370     //g_message("native file:%s\n", uri);
2371     documentUri = URI(uri);
2373     ZipFile zf;
2374     preprocess(zf, doc->rroot);
2376     if (!writeManifest(zf))
2377         {
2378         g_warning("Failed to write manifest");
2379         return;
2380         }
2382     if (!writeContent(zf, doc->rroot))
2383         {
2384         g_warning("Failed to write content");
2385         return;
2386         }
2388     if (!writeMeta(zf))
2389         {
2390         g_warning("Failed to write metafile");
2391         return;
2392         }
2394     if (!zf.writeFile(uri))
2395         {
2396         return;
2397         }
2401 /**
2402  * This is the definition of PovRay output.  This function just
2403  * calls the extension system with the memory allocated XML that
2404  * describes the data.
2405 */
2406 void
2407 OdfOutput::init()
2409     Inkscape::Extension::build_from_mem(
2410         "<inkscape-extension>\n"
2411             "<name>" N_("OpenDocument Drawing Output") "</name>\n"
2412             "<id>org.inkscape.output.odf</id>\n"
2413             "<output>\n"
2414                 "<extension>.odg</extension>\n"
2415                 "<mimetype>text/x-povray-script</mimetype>\n"
2416                 "<filetypename>" N_("OpenDocument drawing (*.odg)") "</filetypename>\n"
2417                 "<filetypetooltip>" N_("OpenDocument drawing file") "</filetypetooltip>\n"
2418             "</output>\n"
2419         "</inkscape-extension>",
2420         new OdfOutput());
2423 /**
2424  * Make sure that we are in the database
2425  */
2426 bool
2427 OdfOutput::check (Inkscape::Extension::Extension *module)
2429     /* We don't need a Key
2430     if (NULL == Inkscape::Extension::db.get(SP_MODULE_KEY_OUTPUT_POV))
2431         return FALSE;
2432     */
2434     return TRUE;
2439 //########################################################################
2440 //# I N P U T
2441 //########################################################################
2445 //#######################
2446 //# L A T E R  !!!  :-)
2447 //#######################
2461 }  //namespace Internal
2462 }  //namespace Extension
2463 }  //namespace Inkscape
2466 //########################################################################
2467 //# E N D    O F    F I L E
2468 //########################################################################
2470 /*
2471   Local Variables:
2472   mode:c++
2473   c-file-style:"stroustrup"
2474   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
2475   indent-tabs-mode:nil
2476   fill-column:99
2477   End:
2478 */
2479 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :