Code

Initial commit of native poppler-based PDF import.
[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, 2007 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     std::string::size_type 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::Maybe<NR::Rect> getODFBoundingBox(const SPItem *item)
963     NR::Maybe<NR::Rect> bbox = sp_item_bbox_desktop((SPItem *)item);
964     if (bbox) {
965         double doc_height    = sp_document_height(SP_ACTIVE_DOCUMENT);
966         NR::Matrix doc2dt_tf = NR::Matrix(NR::scale(1.0, -1.0));
967         doc2dt_tf            = doc2dt_tf * NR::Matrix(NR::translate(0, doc_height));
968         bbox                 = *bbox * doc2dt_tf;
969         bbox                 = *bbox * NR::Matrix(NR::scale(pxToCm));
970     }
971     return bbox;
976 /**
977  * Get the transform for an item, correcting for
978  * handedness reversal
979  */
980 static NR::Matrix getODFItemTransform(const SPItem *item)
982     NR::Matrix itemTransform = NR::Matrix(NR::scale(1, -1));
983     itemTransform = itemTransform * item->transform;
984     itemTransform = itemTransform * NR::Matrix(NR::scale(1, -1));
985     return itemTransform;
990 /**
991  * Get some fun facts from the transform
992  */
993 static void analyzeTransform(NR::Matrix &tf,
994            double &rotate, double &xskew, double &yskew,
995            double &xscale, double &yscale)
997     SVDMatrix mat(2, 2);
998     mat(0, 0) = tf[0];
999     mat(0, 1) = tf[1];
1000     mat(1, 0) = tf[2];
1001     mat(1, 1) = tf[3];
1003     SingularValueDecomposition svd(mat);
1005     SVDMatrix U = svd.getU();
1006     SVDMatrix V = svd.getV();
1007     SVDMatrix Vt = V.transpose();
1008     SVDMatrix UVt = U.multiply(Vt);
1009     double s0 = svd.getS(0);
1010     double s1 = svd.getS(1);
1011     xscale = s0;
1012     yscale = s1;
1013     //g_message("## s0:%.3f s1:%.3f", s0, s1);
1014     //g_message("## u:%.3f %.3f %.3f %.3f", U(0,0), U(0,1), U(1,0), U(1,1));
1015     //g_message("## v:%.3f %.3f %.3f %.3f", V(0,0), V(0,1), V(1,0), V(1,1));
1016     //g_message("## vt:%.3f %.3f %.3f %.3f", Vt(0,0), Vt(0,1), Vt(1,0), Vt(1,1));
1017     //g_message("## uvt:%.3f %.3f %.3f %.3f", UVt(0,0), UVt(0,1), UVt(1,0), UVt(1,1));
1018     rotate = UVt(0,0);
1023 static void gatherText(Inkscape::XML::Node *node, Glib::ustring &buf)
1025     if (node->type() == Inkscape::XML::TEXT_NODE)
1026         {
1027         char *s = (char *)node->content();
1028         if (s)
1029             buf.append(s);
1030         }
1031     
1032     for (Inkscape::XML::Node *child = node->firstChild() ;
1033                 child != NULL; child = child->next())
1034         {
1035         gatherText(child, buf);
1036         }
1040 /**
1041  * FIRST PASS.
1042  * Method descends into the repr tree, converting image, style, and gradient info
1043  * into forms compatible in ODF.
1044  */
1045 void
1046 OdfOutput::preprocess(ZipFile &zf, Inkscape::XML::Node *node)
1049     Glib::ustring nodeName = node->name();
1050     Glib::ustring id       = getAttribute(node, "id");
1052     //### First, check for metadata
1053     if (nodeName == "metadata" || nodeName == "svg:metadata")
1054         {
1055         Inkscape::XML::Node *mchild = node->firstChild() ;
1056         if (!mchild || strcmp(mchild->name(), "rdf:RDF"))
1057             return;
1058         Inkscape::XML::Node *rchild = mchild->firstChild() ;
1059         if (!rchild || strcmp(rchild->name(), "cc:Work"))
1060             return;
1061         for (Inkscape::XML::Node *cchild = rchild->firstChild() ;
1062             cchild ; cchild = cchild->next())
1063             {
1064             Glib::ustring ccName = cchild->name();
1065             Glib::ustring ccVal;
1066             gatherText(cchild, ccVal);
1067             //g_message("ccName: %s  ccVal:%s", ccName.c_str(), ccVal.c_str());
1068             metadata[ccName] = ccVal;
1069             }
1070         return;
1071         }
1073     //Now consider items.
1074     SPObject *reprobj = SP_ACTIVE_DOCUMENT->getObjectByRepr(node);
1075     if (!reprobj)
1076         return;
1077     if (!SP_IS_ITEM(reprobj))
1078         {
1079         return;
1080         }
1081     SPItem *item  = SP_ITEM(reprobj);
1082     //### Get SVG-to-ODF transform
1083     NR::Matrix tf = getODFTransform(item);
1085     if (nodeName == "image" || nodeName == "svg:image")
1086         {
1087         //g_message("image");
1088         Glib::ustring href = getAttribute(node, "xlink:href");
1089         if (href.size() > 0)
1090             {
1091             Glib::ustring oldName = href;
1092             Glib::ustring ext = getExtension(oldName);
1093             if (ext == ".jpeg")
1094                 ext = ".jpg";
1095             if (imageTable.find(oldName) == imageTable.end())
1096                 {
1097                 char buf[64];
1098                 snprintf(buf, 63, "Pictures/image%d%s",
1099                     (int)imageTable.size(), ext.c_str());
1100                 Glib::ustring newName = buf;
1101                 imageTable[oldName] = newName;
1102                 Glib::ustring comment = "old name was: ";
1103                 comment.append(oldName);
1104                 URI oldUri(oldName);
1105                 //g_message("oldpath:%s", oldUri.getNativePath().c_str());
1106                 //# if relative to the documentURI, get proper path
1107                 URI resUri = documentUri.resolve(oldUri);
1108                 DOMString pathName = resUri.getNativePath();
1109                 //g_message("native path:%s", pathName.c_str());
1110                 ZipEntry *ze = zf.addFile(pathName, comment);
1111                 if (ze)
1112                     {
1113                     ze->setFileName(newName);
1114                     }
1115                 else
1116                     {
1117                     g_warning("Could not load image file '%s'", pathName.c_str());
1118                     }
1119                 }
1120             }
1121         }
1123     for (Inkscape::XML::Node *child = node->firstChild() ;
1124             child ; child = child->next())
1125         preprocess(zf, child);
1130 /**
1131  * Writes the manifest.  Currently it only changes according to the
1132  * file names of images packed into the zip file.
1133  */
1134 bool OdfOutput::writeManifest(ZipFile &zf)
1136     BufferOutputStream bouts;
1137     OutputStreamWriter outs(bouts);
1139     time_t tim;
1140     time(&tim);
1142     outs.printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1143     outs.printf("<!DOCTYPE manifest:manifest PUBLIC \"-//OpenOffice.org//DTD Manifest 1.0//EN\" \"Manifest.dtd\">\n");
1144     outs.printf("\n");
1145     outs.printf("\n");
1146     outs.printf("<!--\n");
1147     outs.printf("*************************************************************************\n");
1148     outs.printf("  file:  manifest.xml\n");
1149     outs.printf("  Generated by Inkscape: %s", ctime(&tim)); //ctime has its own <cr>
1150     outs.printf("  http://www.inkscape.org\n");
1151     outs.printf("*************************************************************************\n");
1152     outs.printf("-->\n");
1153     outs.printf("\n");
1154     outs.printf("\n");
1155     outs.printf("<manifest:manifest xmlns:manifest=\"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0\">\n");
1156     outs.printf("    <manifest:file-entry manifest:media-type=\"application/vnd.oasis.opendocument.graphics\" manifest:full-path=\"/\"/>\n");
1157     outs.printf("    <manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"content.xml\"/>\n");
1158     outs.printf("    <manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"styles.xml\"/>\n");
1159     outs.printf("    <manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"meta.xml\"/>\n");
1160     outs.printf("    <!--List our images here-->\n");
1161     std::map<Glib::ustring, Glib::ustring>::iterator iter;
1162     for (iter = imageTable.begin() ; iter!=imageTable.end() ; iter++)
1163         {
1164         Glib::ustring oldName = iter->first;
1165         Glib::ustring newName = iter->second;
1167         Glib::ustring ext = getExtension(oldName);
1168         if (ext == ".jpeg")
1169             ext = ".jpg";
1170         outs.printf("    <manifest:file-entry manifest:media-type=\"");
1171         if (ext == ".gif")
1172             outs.printf("image/gif");
1173         else if (ext == ".png")
1174             outs.printf("image/png");
1175         else if (ext == ".jpg")
1176             outs.printf("image/jpeg");
1177         outs.printf("\" manifest:full-path=\"");
1178         outs.printf((char *)newName.c_str());
1179         outs.printf("\"/>\n");
1180         }
1181     outs.printf("</manifest:manifest>\n");
1183     outs.close();
1185     //Make our entry
1186     ZipEntry *ze = zf.newEntry("META-INF/manifest.xml", "ODF file manifest");
1187     ze->setUncompressedData(bouts.getBuffer());
1188     ze->finish();
1190     return true;
1194 /**
1195  * This writes the document meta information to meta.xml
1196  */
1197 bool OdfOutput::writeMeta(ZipFile &zf)
1199     BufferOutputStream bouts;
1200     OutputStreamWriter outs(bouts);
1202     time_t tim;
1203     time(&tim);
1205     std::map<Glib::ustring, Glib::ustring>::iterator iter;
1206     Glib::ustring creator = "unknown";
1207     iter = metadata.find("dc:creator");
1208     if (iter != metadata.end())
1209         creator = iter->second;
1210     Glib::ustring date = "";
1211     iter = metadata.find("dc:date");
1212     if (iter != metadata.end())
1213         date = iter->second;
1215     outs.printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1216     outs.printf("\n");
1217     outs.printf("\n");
1218     outs.printf("<!--\n");
1219     outs.printf("*************************************************************************\n");
1220     outs.printf("  file:  meta.xml\n");
1221     outs.printf("  Generated by Inkscape: %s", ctime(&tim)); //ctime has its own <cr>
1222     outs.printf("  http://www.inkscape.org\n");
1223     outs.printf("*************************************************************************\n");
1224     outs.printf("-->\n");
1225     outs.printf("\n");
1226     outs.printf("\n");
1227     outs.printf("<office:document-meta\n");
1228     outs.printf("xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\"\n");
1229     outs.printf("xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n");
1230     outs.printf("xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n");
1231     outs.printf("xmlns:meta=\"urn:oasis:names:tc:opendocument:xmlns:meta:1.0\"\n");
1232     outs.printf("xmlns:presentation=\"urn:oasis:names:tc:opendocument:xmlns:presentation:1.0\"\n");
1233     outs.printf("xmlns:ooo=\"http://openoffice.org/2004/office\"\n");
1234     outs.printf("xmlns:smil=\"urn:oasis:names:tc:opendocument:xmlns:smil-compatible:1.0\"\n");
1235     outs.printf("xmlns:anim=\"urn:oasis:names:tc:opendocument:xmlns:animation:1.0\"\n");
1236     outs.printf("office:version=\"1.0\">\n");
1237     outs.printf("<office:meta>\n");
1238     outs.printf("    <meta:generator>Inkscape.org - 0.45</meta:generator>\n");
1239     outs.printf("    <meta:initial-creator>%#s</meta:initial-creator>\n",
1240                                   creator.c_str());
1241     outs.printf("    <meta:creation-date>%#s</meta:creation-date>\n", date.c_str());
1242     for (iter = metadata.begin() ; iter != metadata.end() ; iter++)
1243         {
1244         Glib::ustring name  = iter->first;
1245         Glib::ustring value = iter->second;
1246         if (name.size() > 0 && value.size()>0)
1247             {
1248             outs.printf("    <%#s>%#s</%#s>\n", 
1249                       name.c_str(), value.c_str(), name.c_str());
1250             }
1251         }
1252     outs.printf("    <meta:editing-cycles>2</meta:editing-cycles>\n");
1253     outs.printf("    <meta:editing-duration>PT56S</meta:editing-duration>\n");
1254     outs.printf("    <meta:user-defined meta:name=\"Info 1\"/>\n");
1255     outs.printf("    <meta:user-defined meta:name=\"Info 2\"/>\n");
1256     outs.printf("    <meta:user-defined meta:name=\"Info 3\"/>\n");
1257     outs.printf("    <meta:user-defined meta:name=\"Info 4\"/>\n");
1258     outs.printf("    <meta:document-statistic meta:object-count=\"2\"/>\n");
1259     outs.printf("</office:meta>\n");
1260     outs.printf("</office:document-meta>\n");
1261     outs.printf("\n");
1262     outs.printf("\n");
1265     outs.close();
1267     //Make our entry
1268     ZipEntry *ze = zf.newEntry("meta.xml", "ODF info file");
1269     ze->setUncompressedData(bouts.getBuffer());
1270     ze->finish();
1272     return true;
1278 /**
1279  * This is called just before writeTree(), since it will write style and
1280  * gradient information above the <draw> tag in the content.xml file
1281  */
1282 bool OdfOutput::writeStyle(ZipFile &zf)
1284     BufferOutputStream bouts;
1285     OutputStreamWriter outs(bouts);
1287     /*
1288     ==========================================================
1289     Dump our style table.  Styles should have a general layout
1290     something like the following.  Look in:
1291     http://books.evc-cit.info/odbook/ch06.html#draw-style-file-section
1292     for style and gradient information.
1293     <style:style style:name="gr13"
1294       style:family="graphic" style:parent-style-name="standard">
1295         <style:graphic-properties draw:stroke="solid"
1296             svg:stroke-width="0.1cm"
1297             svg:stroke-color="#ff0000"
1298             draw:fill="solid" draw:fill-color="#e6e6ff"/>
1299     </style:style>
1300     ==========================================================
1301     */
1302     outs.printf("<!-- ####### Styles from Inkscape document ####### -->\n");
1303     std::vector<StyleInfo>::iterator iter;
1304     for (iter = styleTable.begin() ; iter != styleTable.end() ; iter++)
1305         {
1306         outs.printf("<style:style style:name=\"%s\"", iter->name.c_str());
1307         StyleInfo s(*iter);
1308         outs.printf(" style:family=\"graphic\" style:parent-style-name=\"standard\">\n");
1309         outs.printf("  <style:graphic-properties");
1310         outs.printf(" draw:fill=\"%s\" ", s.fill.c_str());
1311         if (s.fill != "none")
1312             {
1313             outs.printf(" draw:fill-color=\"%s\" ", s.fillColor.c_str());
1314             outs.printf(" draw:fill-opacity=\"%s\" ", s.fillOpacity.c_str());
1315             }
1316         outs.printf(" draw:stroke=\"%s\" ", s.stroke.c_str());
1317         if (s.stroke != "none")
1318             {
1319             outs.printf(" svg:stroke-width=\"%s\" ", s.strokeWidth.c_str());
1320             outs.printf(" svg:stroke-color=\"%s\" ", s.strokeColor.c_str());
1321             outs.printf(" svg:stroke-opacity=\"%s\" ", s.strokeOpacity.c_str());
1322             }
1323         outs.printf("/>\n");
1324         outs.printf("</style:style>\n");
1325         }
1327     //##  Dump our gradient table
1328     int gradientCount = 0;
1329     outs.printf("\n");
1330     outs.printf("<!-- ####### Gradients from Inkscape document ####### -->\n");
1331     std::vector<GradientInfo>::iterator giter;
1332     for (giter = gradientTable.begin() ; giter != gradientTable.end() ; giter++)
1333         {
1334         GradientInfo gi(*giter);
1335         if (gi.style == "linear")
1336             {
1337             /*
1338             ===================================================================
1339             LINEAR gradient.  We need something that looks like this:
1340             <draw:gradient draw:name="Gradient_20_7"
1341                 draw:display-name="Gradient 7"
1342                 draw:style="linear"
1343                 draw:start-color="#008080" draw:end-color="#993366"
1344                 draw:start-intensity="100%" draw:end-intensity="100%"
1345                 draw:angle="150" draw:border="0%"/>
1346             ===================================================================
1347             */
1348             if (gi.stops.size() < 2)
1349                 {
1350                 g_warning("Need at least 2 tops for a linear gradient");
1351                 continue;
1352                 }
1353             outs.printf("<svg:linearGradient ");
1354             outs.printf("id=\"%#s_g\" ", gi.name.c_str());
1355             outs.printf("draw:name=\"%#s_g\"\n", gi.name.c_str());
1356             outs.printf("    draw:display-name=\"imported linear %d\"\n",
1357                         gradientCount);
1358             outs.printf("    svg:x1=\"%05.3fcm\" svg:y1=\"%05.3fcm\"\n",
1359                         gi.x1, gi.y1);
1360             outs.printf("    svg:x2=\"%05.3fcm\" svg:y2=\"%05.3fcm\"\n",
1361                         gi.x2, gi.y2);
1362             outs.printf("    svg:gradientUnits=\"objectBoundingBox\">\n");
1363             outs.printf("    <svg:stop\n");
1364             outs.printf("        svg:stop-color=\"#%06lx\"\n",
1365                         gi.stops[0].rgb);
1366             outs.printf("        svg:stop-opacity=\"%f%%\"\n",
1367                         gi.stops[0].opacity * 100.0);
1368             outs.printf("        svg:offset=\"0\"/>\n");
1369             outs.printf("    <svg:stop\n");
1370             outs.printf("        svg:stop-color=\"#%06lx\"\n",
1371                         gi.stops[1].rgb);
1372             outs.printf("        svg:stop-opacity=\"%f%%\"\n",
1373                         gi.stops[1].opacity * 100.0);
1374             outs.printf("        svg:offset=\"1\"/>\n");
1375             outs.printf("</svg:linearGradient>\n");
1376             }
1377         else if (gi.style == "radial")
1378             {
1379             /*
1380             ===================================================================
1381             RADIAL gradient.  We need something that looks like this:
1382             <!-- radial gradient, light gray to white, centered, 0% border -->
1383             <draw:gradient draw:name="radial_20_borderless"
1384                 draw:display-name="radial borderless"
1385                 draw:style="radial"
1386                 draw:cx="50%" draw:cy="50%"
1387                 draw:start-color="#999999" draw:end-color="#ffffff"
1388                 draw:border="0%"/>
1389             ===================================================================
1390             */
1391             if (gi.stops.size() < 2)
1392                 {
1393                 g_warning("Need at least 2 tops for a radial gradient");
1394                 continue;
1395                 }
1396             outs.printf("<svg:radialGradient ");
1397             outs.printf("id=\"%#s_g\" ", gi.name.c_str());
1398             outs.printf("draw:name=\"%#s_g\"\n", gi.name.c_str());
1399             outs.printf("    draw:display-name=\"imported radial %d\"\n",
1400                         gradientCount);
1401             outs.printf("    svg:cx=\"%05.3f\" svg:cy=\"%05.3f\"\n",
1402                         gi.cx, gi.cy);
1403             outs.printf("    svg:fx=\"%05.3f\" svg:fy=\"%05.3f\"\n",
1404                         gi.fx, gi.fy);
1405             outs.printf("    svg:r=\"%05.3f\"\n",
1406                         gi.r);
1407             outs.printf("    svg:gradientUnits=\"objectBoundingBox\">\n");
1408             outs.printf("    <svg:stop\n");
1409             outs.printf("        svg:stop-color=\"#%06lx\"\n",
1410                         gi.stops[0].rgb);
1411             outs.printf("        svg:stop-opacity=\"%f%%\"\n",
1412                         gi.stops[0].opacity * 100.0);
1413             outs.printf("        svg:offset=\"0\"/>\n");
1414             outs.printf("    <svg:stop\n");
1415             outs.printf("        svg:stop-color=\"#%06lx\"\n",
1416                         gi.stops[1].rgb);
1417             outs.printf("        svg:stop-opacity=\"%f%%\"\n",
1418                         gi.stops[1].opacity * 100.0);
1419             outs.printf("        svg:offset=\"1\"/>\n");
1420             outs.printf("</svg:radialGradient>\n");
1421             }
1422         else
1423             {
1424             g_warning("unsupported gradient style '%s'", gi.style.c_str());
1425             }
1426         outs.printf("<style:style style:name=\"%#s\" style:family=\"graphic\" ",
1427                   gi.name.c_str());
1428         outs.printf("style:parent-style-name=\"standard\">\n");
1429         outs.printf("    <style:graphic-properties draw:fill=\"gradient\" ");
1430         outs.printf("draw:fill-gradient-name=\"%#s_g\"\n",
1431                   gi.name.c_str());
1432         outs.printf("        draw:textarea-horizontal-align=\"center\" ");
1433         outs.printf("draw:textarea-vertical-align=\"middle\"/>\n");
1434         outs.printf("</style:style>\n\n");
1436         gradientCount++;
1437         }
1439     outs.printf("\n");
1440     outs.printf("</office:automatic-styles>\n");
1441     outs.printf("\n");
1442     outs.printf("\n");
1443     outs.printf("<office:master-styles>\n");
1444     outs.printf("<draw:layer-set>\n");
1445     outs.printf("    <draw:layer draw:name=\"layout\"/>\n");
1446     outs.printf("    <draw:layer draw:name=\"background\"/>\n");
1447     outs.printf("    <draw:layer draw:name=\"backgroundobjects\"/>\n");
1448     outs.printf("    <draw:layer draw:name=\"controls\"/>\n");
1449     outs.printf("    <draw:layer draw:name=\"measurelines\"/>\n");
1450     outs.printf("</draw:layer-set>\n");
1451     outs.printf("\n");
1452     outs.printf("<style:master-page style:name=\"Default\"\n");
1453     outs.printf("    style:page-master-name=\"PM1\" draw:style-name=\"dp1\"/>\n");
1454     outs.printf("</office:master-styles>\n");
1455     outs.printf("\n");
1456     outs.printf("\n");
1457     outs.printf("\n");
1458     outs.printf("</office:document-styles>\n");
1459     outs.printf("\n");
1460     outs.printf("<!--\n");
1461     outs.printf("*************************************************************************\n");
1462     outs.printf("  E N D    O F    F I L E\n");
1463     outs.printf("  Have a nice day  - ishmal\n");
1464     outs.printf("*************************************************************************\n");
1465     outs.printf("-->\n");
1466     outs.printf("\n");
1468     //Make our entry
1469     ZipEntry *ze = zf.newEntry("styles.xml", "ODF style file");
1470     ze->setUncompressedData(bouts.getBuffer());
1471     ze->finish();
1473     return true;
1478 /**
1479  * Writes an SVG path as an ODF <draw:path>
1480  */
1481 static int
1482 writePath(Writer &outs, NArtBpath const *bpath,
1483           NR::Matrix &tf, double xoff, double yoff)
1485     bool closed   = false;
1486     int nrPoints  = 0;
1487     NArtBpath *bp = (NArtBpath *)bpath;
1489     double destx = 0.0;
1490     double desty = 0.0;
1491     int code = -1;
1493     for (  ; bp->code != NR_END; bp++)
1494         {
1495         code = bp->code;
1497         NR::Point const p1(bp->c(1) * tf);
1498         NR::Point const p2(bp->c(2) * tf);
1499         NR::Point const p3(bp->c(3) * tf);
1500         double x1 = (p1[NR::X] - xoff) * 1000.0;
1501         if (fabs(x1)<1.0) x1=0.0;
1502         double y1 = (p1[NR::Y] - yoff) * 1000.0;
1503         if (fabs(y1)<1.0) y1=0.0;
1504         double x2 = (p2[NR::X] - xoff) * 1000.0;
1505         if (fabs(x2)<1.0) x2=0.0;
1506         double y2 = (p2[NR::Y] - yoff) * 1000.0;
1507         if (fabs(y2)<1.0) y2=0.0;
1508         double x3 = (p3[NR::X] - xoff) * 1000.0;
1509         if (fabs(x3)<1.0) x3=0.0;
1510         double y3 = (p3[NR::Y] - yoff) * 1000.0;
1511         if (fabs(y3)<1.0) y3=0.0;
1512         destx = x3;
1513         desty = y3;
1515         switch (code)
1516             {
1517             case NR_LINETO:
1518                 outs.printf("L %.3f %.3f ",  destx, desty);
1519                 break;
1521             case NR_CURVETO:
1522                 outs.printf("C %.3f %.3f %.3f %.3f %.3f %.3f ",
1523                               x1, y1, x2, y2, destx, desty);
1524                 break;
1526             case NR_MOVETO_OPEN:
1527             case NR_MOVETO:
1528                 if (closed)
1529                     outs.printf("Z ");
1530                 closed = ( code == NR_MOVETO );
1531                 outs.printf("M %.3f %.3f ",  destx, desty);
1532                 break;
1534             default:
1535                 break;
1537             }
1539         nrPoints++;
1540         }
1542     if (closed)
1543         {
1544         outs.printf("Z");
1545         }
1547     return nrPoints;
1552 bool OdfOutput::processStyle(Writer &outs, SPItem *item,
1553                              const Glib::ustring &id)
1555     SPStyle *style = item->style;
1557     StyleInfo si;
1559     //## FILL
1560     if (style->fill.type == SP_PAINT_TYPE_COLOR)
1561         {
1562         guint32 fillCol =
1563             sp_color_get_rgba32_ualpha(&style->fill.value.color, 0);
1564         char buf[16];
1565         int r = (fillCol >> 24) & 0xff;
1566         int g = (fillCol >> 16) & 0xff;
1567         int b = (fillCol >>  8) & 0xff;
1568         //g_message("## %s %lx", id.c_str(), (unsigned int)fillCol);
1569         snprintf(buf, 15, "#%02x%02x%02x", r, g, b);
1570         si.fillColor = buf;
1571         si.fill      = "solid";
1572         double opacityPercent = 100.0 *
1573              (SP_SCALE24_TO_FLOAT(style->fill_opacity.value));
1574         snprintf(buf, 15, "%.3f%%", opacityPercent);
1575         si.fillOpacity = buf;
1576         }
1578     //## STROKE
1579     if (style->stroke.type == SP_PAINT_TYPE_COLOR)
1580         {
1581         guint32 strokeCol =
1582             sp_color_get_rgba32_ualpha(&style->stroke.value.color, 0);
1583         char buf[16];
1584         int r = (strokeCol >> 24) & 0xff;
1585         int g = (strokeCol >> 16) & 0xff;
1586         int b = (strokeCol >>  8) & 0xff;
1587         snprintf(buf, 15, "#%02x%02x%02x", r, g, b);
1588         si.strokeColor = buf;
1589         snprintf(buf, 15, "%.3fpt", style->stroke_width.value);
1590         si.strokeWidth = buf;
1591         si.stroke      = "solid";
1592         double opacityPercent = 100.0 *
1593              (SP_SCALE24_TO_FLOAT(style->stroke_opacity.value));
1594         snprintf(buf, 15, "%.3f%%", opacityPercent);
1595         si.strokeOpacity = buf;
1596         }
1598     //Look for existing identical style;
1599     bool styleMatch = false;
1600     std::vector<StyleInfo>::iterator iter;
1601     for (iter=styleTable.begin() ; iter!=styleTable.end() ; iter++)
1602         {
1603         if (si.equals(*iter))
1604             {
1605             //map to existing styleTable entry
1606             Glib::ustring styleName = iter->name;
1607             //g_message("found duplicate style:%s", styleName.c_str());
1608             styleLookupTable[id] = styleName;
1609             styleMatch = true;
1610             break;
1611             }
1612         }
1614     //## Dont need a new style
1615     if (styleMatch)
1616         return false;
1618     char buf[16];
1619     snprintf(buf, 15, "style%d", (int)styleTable.size());
1620     Glib::ustring styleName = buf;
1621     si.name = styleName;
1622     styleTable.push_back(si);
1623     styleLookupTable[id] = styleName;
1625     outs.printf("<style:style style:name=\"%s\"", si.name.c_str());
1626     outs.printf(" style:family=\"graphic\" style:parent-style-name=\"standard\">\n");
1627     outs.printf("  <style:graphic-properties");
1628     outs.printf(" draw:fill=\"%s\" ", si.fill.c_str());
1629     if (si.fill != "none")
1630         {
1631         outs.printf(" draw:fill-color=\"%s\" ", si.fillColor.c_str());
1632         outs.printf(" draw:fill-opacity=\"%s\" ", si.fillOpacity.c_str());
1633         }
1634     outs.printf(" draw:stroke=\"%s\" ", si.stroke.c_str());
1635     if (si.stroke != "none")
1636         {
1637         outs.printf(" svg:stroke-width=\"%s\" ", si.strokeWidth.c_str());
1638         outs.printf(" svg:stroke-color=\"%s\" ", si.strokeColor.c_str());
1639         outs.printf(" svg:stroke-opacity=\"%s\" ", si.strokeOpacity.c_str());
1640         }
1641     outs.printf("/>\n");
1642     outs.printf("</style:style>\n");
1644     return true;
1650 bool OdfOutput::processGradient(Writer &outs, SPItem *item,
1651                                 const Glib::ustring &id, NR::Matrix &tf)
1653     if (!item)
1654         return false;
1656     SPStyle *style = item->style;
1658     if (!style)
1659         return false;
1661     if (style->fill.type != SP_PAINT_TYPE_PAINTSERVER)
1662         return false;
1664     //## Gradient.  Look in writeStyle() below to see what info
1665     //   we need to read into GradientInfo.
1666     if (!SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)))
1667         return false;
1669     SPGradient *gradient = SP_GRADIENT(SP_STYLE_FILL_SERVER(style));
1671     GradientInfo gi;
1673     SPGradient *grvec = sp_gradient_get_vector(gradient, FALSE);
1674     for (SPStop *stop = sp_first_stop(grvec) ;
1675           stop ; stop = sp_next_stop(stop))
1676         {
1677         unsigned long rgba = sp_stop_get_rgba32(stop);
1678         unsigned long rgb  = (rgba >> 8) & 0xffffff;
1679         double opacity     = ((double)(rgba & 0xff)) / 256.0;
1680         GradientStop gs(rgb, opacity);
1681         gi.stops.push_back(gs);
1682         }
1684     if (SP_IS_LINEARGRADIENT(gradient))
1685         {
1686         gi.style = "linear";
1687         SPLinearGradient *linGrad = SP_LINEARGRADIENT(gradient);
1688         /*
1689         NR::Point p1(linGrad->x1.value, linGrad->y1.value);
1690         p1 = p1 * tf;
1691         gi.x1 = p1[NR::X];
1692         gi.y1 = p1[NR::Y];
1693         NR::Point p2(linGrad->x2.value, linGrad->y2.value);
1694         p2 = p2 * tf;
1695         gi.x2 = p2[NR::X];
1696         gi.y2 = p2[NR::Y];
1697         */
1698         gi.x1 = linGrad->x1.value;
1699         gi.y1 = linGrad->y1.value;
1700         gi.x2 = linGrad->x2.value;
1701         gi.y2 = linGrad->y2.value;
1702         }
1703     else if (SP_IS_RADIALGRADIENT(gradient))
1704         {
1705         gi.style = "radial";
1706         SPRadialGradient *radGrad = SP_RADIALGRADIENT(gradient);
1707         gi.cx = radGrad->cx.computed * 100.0;//ODG cx is percentages
1708         gi.cy = radGrad->cy.computed * 100.0;
1709         }
1710     else
1711         {
1712         g_warning("not a supported gradient type");
1713         return false;
1714         }
1716     //Look for existing identical style;
1717     bool gradientMatch = false;
1718     std::vector<GradientInfo>::iterator iter;
1719     for (iter=gradientTable.begin() ; iter!=gradientTable.end() ; iter++)
1720         {
1721         if (gi.equals(*iter))
1722             {
1723             //map to existing gradientTable entry
1724             Glib::ustring gradientName = iter->name;
1725             //g_message("found duplicate style:%s", gradientName.c_str());
1726             gradientLookupTable[id] = gradientName;
1727             gradientMatch = true;
1728             break;
1729             }
1730         }
1732     if (gradientMatch)
1733         return true;
1735     //## No match, let us write a new entry
1736     char buf[16];
1737     snprintf(buf, 15, "gradient%d", (int)gradientTable.size());
1738     Glib::ustring gradientName = buf;
1739     gi.name = gradientName;
1740     gradientTable.push_back(gi);
1741     gradientLookupTable[id] = gradientName;
1743     int gradientCount = gradientTable.size();
1745     if (gi.style == "linear")
1746         {
1747         /*
1748         ===================================================================
1749         LINEAR gradient.  We need something that looks like this:
1750         <draw:gradient draw:name="Gradient_20_7"
1751             draw:display-name="Gradient 7"
1752             draw:style="linear"
1753             draw:start-color="#008080" draw:end-color="#993366"
1754             draw:start-intensity="100%" draw:end-intensity="100%"
1755             draw:angle="150" draw:border="0%"/>
1756         ===================================================================
1757         */
1758         if (gi.stops.size() < 2)
1759             {
1760             g_warning("Need at least 2 stops for a linear gradient");
1761             return false;;
1762             }
1763         outs.printf("<svg:linearGradient ");
1764         outs.printf("id=\"%#s_g\" ", gi.name.c_str());
1765         outs.printf("draw:name=\"%#s_g\"\n", gi.name.c_str());
1766         outs.printf("    draw:display-name=\"imported linear %d\"\n",
1767                     gradientCount);
1768         outs.printf("    svg:gradientUnits=\"objectBoundingBox\"\n");
1769         outs.printf("    svg:x1=\"%05.3fcm\" svg:y1=\"%05.3fcm\"\n",
1770                     gi.x1 * pxToCm, gi.y1 * pxToCm);
1771         outs.printf("    svg:x2=\"%05.3fcm\" svg:y2=\"%05.3fcm\">\n",
1772                     gi.x2 * pxToCm, gi.y2 * pxToCm);
1773         outs.printf("    <svg:stop\n");
1774         outs.printf("        svg:stop-color=\"#%06lx\"\n",
1775                     gi.stops[0].rgb);
1776         outs.printf("        svg:stop-opacity=\"%f%%\"\n",
1777                     gi.stops[0].opacity * 100.0);
1778         outs.printf("        svg:offset=\"0\"/>\n");
1779         outs.printf("    <svg:stop\n");
1780         outs.printf("        svg:stop-color=\"#%06lx\"\n",
1781                     gi.stops[1].rgb);
1782         outs.printf("        svg:stop-opacity=\"%f%%\"\n",
1783                     gi.stops[1].opacity * 100.0);
1784         outs.printf("        svg:offset=\"1\"/>\n");
1785         outs.printf("</svg:linearGradient>\n");
1786         }
1787     else if (gi.style == "radial")
1788         {
1789         /*
1790         ===================================================================
1791         RADIAL gradient.  We need something that looks like this:
1792         <!-- radial gradient, light gray to white, centered, 0% border -->
1793         <draw:gradient draw:name="radial_20_borderless"
1794             draw:display-name="radial borderless"
1795             draw:style="radial"
1796             draw:cx="50%" draw:cy="50%"
1797             draw:start-color="#999999" draw:end-color="#ffffff"
1798             draw:border="0%"/>
1799         ===================================================================
1800         */
1801         if (gi.stops.size() < 2)
1802             {
1803             g_warning("Need at least 2 stops for a radial gradient");
1804             return false;
1805             }
1806         outs.printf("<svg:radialGradient ");
1807         outs.printf("id=\"%#s_g\" ", gi.name.c_str());
1808         outs.printf("draw:name=\"%#s_g\"\n", gi.name.c_str());
1809         outs.printf("    draw:display-name=\"imported radial %d\"\n",
1810                     gradientCount);
1811         outs.printf("    svg:gradientUnits=\"objectBoundingBox\"\n");
1812         outs.printf("    svg:cx=\"%05.3f\" svg:cy=\"%05.3f\"\n",
1813                     gi.cx, gi.cy);
1814         outs.printf("    svg:fx=\"%05.3f\" svg:fy=\"%05.3f\"\n",
1815                     gi.fx, gi.fy);
1816         outs.printf("    svg:r=\"%05.3f\">\n",
1817                     gi.r);
1818         outs.printf("    <svg:stop\n");
1819         outs.printf("        svg:stop-color=\"#%06lx\"\n",
1820                     gi.stops[0].rgb);
1821         outs.printf("        svg:stop-opacity=\"%f%%\"\n",
1822                     gi.stops[0].opacity * 100.0);
1823         outs.printf("        svg:offset=\"0\"/>\n");
1824         outs.printf("    <svg:stop\n");
1825         outs.printf("        svg:stop-color=\"#%06lx\"\n",
1826                     gi.stops[1].rgb);
1827         outs.printf("        svg:stop-opacity=\"%f%%\"\n",
1828                     gi.stops[1].opacity * 100.0);
1829         outs.printf("        svg:offset=\"1\"/>\n");
1830         outs.printf("</svg:radialGradient>\n");
1831         }
1832     else
1833         {
1834         g_warning("unsupported gradient style '%s'", gi.style.c_str());
1835         return false;
1836         }
1837     outs.printf("<style:style style:name=\"%#s\" style:family=\"graphic\" ",
1838               gi.name.c_str());
1839     outs.printf("style:parent-style-name=\"standard\">\n");
1840     outs.printf("    <style:graphic-properties draw:fill=\"gradient\" ");
1841     outs.printf("draw:fill-gradient-name=\"%#s_g\"\n",
1842               gi.name.c_str());
1843     outs.printf("        draw:textarea-horizontal-align=\"center\" ");
1844     outs.printf("draw:textarea-vertical-align=\"middle\"/>\n");
1845     outs.printf("</style:style>\n\n");
1846  
1847     return true;
1853 /**
1854  * SECOND PASS.
1855  * This is the main SPObject tree output to ODF.  preprocess()
1856  * must be called prior to this, as elements will often reference
1857  * data parsed and tabled in preprocess().
1858  */
1859 bool OdfOutput::writeTree(Writer &couts, Writer &souts,
1860                           Inkscape::XML::Node *node)
1862     //# Get the SPItem, if applicable
1863     SPObject *reprobj = SP_ACTIVE_DOCUMENT->getObjectByRepr(node);
1864     if (!reprobj)
1865         return true;
1866     if (!SP_IS_ITEM(reprobj))
1867         {
1868         return true;
1869         }
1870     SPItem *item = SP_ITEM(reprobj);
1873     Glib::ustring nodeName = node->name();
1874     Glib::ustring id       = getAttribute(node, "id");
1876     //### Get SVG-to-ODF transform
1877     NR::Matrix tf        = getODFTransform(item);
1879     //### Get ODF bounding box params for item
1880     NR::Maybe<NR::Rect> bbox = getODFBoundingBox(item);
1881     if (!bbox) {
1882         return true;
1883     }
1885     double bbox_x        = bbox->min()[NR::X];
1886     double bbox_y        = bbox->min()[NR::Y];
1887     double bbox_width    = bbox->extent(NR::X);
1888     double bbox_height   = bbox->extent(NR::Y);
1890     double rotate;
1891     double xskew;
1892     double yskew;
1893     double xscale;
1894     double yscale;
1895     analyzeTransform(tf, rotate, xskew, yskew, xscale, yscale);
1897     //# Do our stuff
1898     SPCurve *curve = NULL;
1902     if (nodeName == "svg" || nodeName == "svg:svg")
1903         {
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         return true;
1912         }
1913     else if (nodeName == "g" || nodeName == "svg:g")
1914         {
1915         if (id.size() > 0)
1916             couts.printf("<draw:g id=\"%s\">\n", id.c_str());
1917         else
1918             couts.printf("<draw:g>\n");
1919         //# Iterate through the children
1920         for (Inkscape::XML::Node *child = node->firstChild() ;
1921                child ; child = child->next())
1922             {
1923             if (!writeTree(couts, souts, child))
1924                 return false;
1925             }
1926         if (id.size() > 0)
1927             couts.printf("</draw:g> <!-- id=\"%s\" -->\n", id.c_str());
1928         else
1929             couts.printf("</draw:g>\n");
1930         return true;
1931         }
1933     //######################################
1934     //# S T Y L E
1935     //######################################
1936     processStyle(souts, item, id);
1938     //######################################
1939     //# G R A D I E N T
1940     //######################################
1941     processGradient(souts, item, id, tf);
1946     //######################################
1947     //# I T E M    D A T A
1948     //######################################
1949     //g_message("##### %s #####", nodeName.c_str());
1950     if (nodeName == "image" || nodeName == "svg:image")
1951         {
1952         if (!SP_IS_IMAGE(item))
1953             {
1954             g_warning("<image> is not an SPImage.  Why?  ;-)");
1955             return false;
1956             }
1958         SPImage *img   = SP_IMAGE(item);
1959         double ix      = img->x.value;
1960         double iy      = img->y.value;
1961         double iwidth  = img->width.value;
1962         double iheight = img->height.value;
1964         NR::Rect ibbox(NR::Point(ix, iy), NR::Point(ix+iwidth, iy+iheight));
1965         ibbox = ibbox * tf;
1966         ix      = ibbox.min()[NR::X];
1967         iy      = ibbox.min()[NR::Y];
1968         //iwidth  = ibbox.max()[NR::X] - ibbox.min()[NR::X];
1969         //iheight = ibbox.max()[NR::Y] - ibbox.min()[NR::Y];
1970         iwidth  = xscale * iwidth;
1971         iheight = yscale * iheight;
1973         NR::Matrix itemTransform = getODFItemTransform(item);
1975         Glib::ustring itemTransformString = formatTransform(itemTransform);
1977         Glib::ustring href = getAttribute(node, "xlink:href");
1978         std::map<Glib::ustring, Glib::ustring>::iterator iter = imageTable.find(href);
1979         if (iter == imageTable.end())
1980             {
1981             g_warning("image '%s' not in table", href.c_str());
1982             return false;
1983             }
1984         Glib::ustring newName = iter->second;
1986         couts.printf("<draw:frame ");
1987         if (id.size() > 0)
1988             couts.printf("id=\"%s\" ", id.c_str());
1989         couts.printf("draw:style-name=\"gr1\" draw:text-style-name=\"P1\" draw:layer=\"layout\" ");
1990         //no x or y.  make them the translate transform, last one
1991         couts.printf("svg:width=\"%.3fcm\" svg:height=\"%.3fcm\" ",
1992                                   iwidth, iheight);
1993         if (itemTransformString.size() > 0)
1994             {
1995             couts.printf("draw:transform=\"%s translate(%.3fcm, %.3fcm)\" ",
1996                            itemTransformString.c_str(), ix, iy);
1997             }
1998         else
1999             {
2000             couts.printf("draw:transform=\"translate(%.3fcm, %.3fcm)\" ",
2001                                 ix, iy);
2002             }
2004         couts.printf(">\n");
2005         couts.printf("    <draw:image xlink:href=\"%s\" xlink:type=\"simple\"\n",
2006                               newName.c_str());
2007         couts.printf("        xlink:show=\"embed\" xlink:actuate=\"onLoad\">\n");
2008         couts.printf("        <text:p/>\n");
2009         couts.printf("    </draw:image>\n");
2010         couts.printf("</draw:frame>\n");
2011         return true;
2012         }
2013     else if (SP_IS_SHAPE(item))
2014         {
2015         //g_message("### %s is a shape", nodeName.c_str());
2016         curve = sp_shape_get_curve(SP_SHAPE(item));
2017         }
2018     else if (SP_IS_TEXT(item) || SP_IS_FLOWTEXT(item))
2019         {
2020         curve = te_get_layout(item)->convertToCurves();
2021         }
2023     if (curve)
2024         {
2025         //### Default <path> output
2027         couts.printf("<draw:path ");
2028         if (id.size()>0)
2029             couts.printf("id=\"%s\" ", id.c_str());
2031         std::map<Glib::ustring, Glib::ustring>::iterator siter;
2032         siter = styleLookupTable.find(id);
2033         if (siter != styleLookupTable.end())
2034             {
2035             Glib::ustring styleName = siter->second;
2036             couts.printf("draw:style-name=\"%s\" ", styleName.c_str());
2037             }
2039         std::map<Glib::ustring, Glib::ustring>::iterator giter;
2040         giter = gradientLookupTable.find(id);
2041         if (giter != gradientLookupTable.end())
2042             {
2043             Glib::ustring gradientName = giter->second;
2044             couts.printf("draw:fill-gradient-name=\"%s\" ",
2045                  gradientName.c_str());
2046             }
2048         couts.printf("draw:layer=\"layout\" svg:x=\"%.3fcm\" svg:y=\"%.3fcm\" ",
2049                        bbox_x, bbox_y);
2050         couts.printf("svg:width=\"%.3fcm\" svg:height=\"%.3fcm\" ",
2051                        bbox_width, bbox_height);
2052         couts.printf("svg:viewBox=\"0.0 0.0 %.3f %.3f\"\n",
2053                        bbox_width * 1000.0, bbox_height * 1000.0);
2055         couts.printf("    svg:d=\"");
2056         int nrPoints = writePath(couts, SP_CURVE_BPATH(curve),
2057                              tf, bbox_x, bbox_y);
2058         couts.printf("\"");
2060         couts.printf(">\n");
2061         couts.printf("    <!-- %d nodes -->\n", nrPoints);
2062         couts.printf("</draw:path>\n\n");
2065         sp_curve_unref(curve);
2066         }
2068     return true;
2073 /**
2074  * Write the header for the content.xml file
2075  */
2076 bool OdfOutput::writeStyleHeader(Writer &outs)
2078     time_t tim;
2079     time(&tim);
2081     outs.printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
2082     outs.printf("\n");
2083     outs.printf("\n");
2084     outs.printf("<!--\n");
2085     outs.printf("*************************************************************************\n");
2086     outs.printf("  file:  styles.xml\n");
2087     outs.printf("  Generated by Inkscape: %s", ctime(&tim)); //ctime has its own <cr>
2088     outs.printf("  http://www.inkscape.org\n");
2089     outs.printf("*************************************************************************\n");
2090     outs.printf("-->\n");
2091     outs.printf("\n");
2092     outs.printf("\n");
2093     outs.printf("<office:document-styles\n");
2094     outs.printf("    xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\"\n");
2095     outs.printf("    xmlns:style=\"urn:oasis:names:tc:opendocument:xmlns:style:1.0\"\n");
2096     outs.printf("    xmlns:text=\"urn:oasis:names:tc:opendocument:xmlns:text:1.0\"\n");
2097     outs.printf("    xmlns:table=\"urn:oasis:names:tc:opendocument:xmlns:table:1.0\"\n");
2098     outs.printf("    xmlns:draw=\"urn:oasis:names:tc:opendocument:xmlns:drawing:1.0\"\n");
2099     outs.printf("    xmlns:fo=\"urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0\"\n");
2100     outs.printf("    xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n");
2101     outs.printf("    xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n");
2102     outs.printf("    xmlns:meta=\"urn:oasis:names:tc:opendocument:xmlns:meta:1.0\"\n");
2103     outs.printf("    xmlns:number=\"urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0\"\n");
2104     outs.printf("    xmlns:presentation=\"urn:oasis:names:tc:opendocument:xmlns:presentation:1.0\"\n");
2105     outs.printf("    xmlns:svg=\"urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0\"\n");
2106     outs.printf("    xmlns:chart=\"urn:oasis:names:tc:opendocument:xmlns:chart:1.0\"\n");
2107     outs.printf("    xmlns:dr3d=\"urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0\"\n");
2108     outs.printf("    xmlns:math=\"http://www.w3.org/1998/Math/MathML\"\n");
2109     outs.printf("    xmlns:form=\"urn:oasis:names:tc:opendocument:xmlns:form:1.0\"\n");
2110     outs.printf("    xmlns:script=\"urn:oasis:names:tc:opendocument:xmlns:script:1.0\"\n");
2111     outs.printf("    xmlns:ooo=\"http://openoffice.org/2004/office\"\n");
2112     outs.printf("    xmlns:ooow=\"http://openoffice.org/2004/writer\"\n");
2113     outs.printf("    xmlns:oooc=\"http://openoffice.org/2004/calc\"\n");
2114     outs.printf("    xmlns:dom=\"http://www.w3.org/2001/xml-events\"\n");
2115     outs.printf("    xmlns:xforms=\"http://www.w3.org/2002/xforms\"\n");
2116     outs.printf("    xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n");
2117     outs.printf("    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n");
2118     outs.printf("    xmlns:smil=\"urn:oasis:names:tc:opendocument:xmlns:smil-compatible:1.0\"\n");
2119     outs.printf("    xmlns:anim=\"urn:oasis:names:tc:opendocument:xmlns:animation:1.0\"\n");
2120     outs.printf("    office:version=\"1.0\">\n");
2121     outs.printf("\n");
2122     outs.printf("\n");
2123     outs.printf("<!--\n");
2124     outs.printf("*************************************************************************\n");
2125     outs.printf("  S T Y L E S\n");
2126     outs.printf("  Style entries have been pulled from the svg style and\n");
2127     outs.printf("  representation attributes in the SVG tree.  The tree elements\n");
2128     outs.printf("  then refer to them by name, in the ODF manner\n");
2129     outs.printf("*************************************************************************\n");
2130     outs.printf("-->\n");
2131     outs.printf("\n");
2132     outs.printf("<office:styles>\n");
2133     outs.printf("\n");
2135     return true;
2139 /**
2140  * Write the footer for the style.xml file
2141  */
2142 bool OdfOutput::writeStyleFooter(Writer &outs)
2144     outs.printf("\n");
2145     outs.printf("</office:styles>\n");
2146     outs.printf("\n");
2147     outs.printf("\n");
2148     outs.printf("<office:automatic-styles>\n");
2149     outs.printf("<!-- ####### 'Standard' styles ####### -->\n");
2150     outs.printf("<style:style style:name=\"dp1\" style:family=\"drawing-page\"/>\n");
2151     outs.printf("<style:style style:name=\"gr1\" style:family=\"graphic\" style:parent-style-name=\"standard\">\n");
2152     outs.printf("  <style:graphic-properties draw:stroke=\"none\" draw:fill=\"none\"\n");
2153     outs.printf("       draw:textarea-horizontal-align=\"center\"\n");
2154     outs.printf("       draw:textarea-vertical-align=\"middle\" draw:color-mode=\"standard\"\n");
2155     outs.printf("       draw:luminance=\"0%%\" draw:contrast=\"0%%\" draw:gamma=\"100%%\" draw:red=\"0%%\"\n");
2156     outs.printf("       draw:green=\"0%%\" draw:blue=\"0%%\" fo:clip=\"rect(0cm 0cm 0cm 0cm)\"\n");
2157     outs.printf("       draw:image-opacity=\"100%%\" style:mirror=\"none\"/>\n");
2158     outs.printf("</style:style>\n");
2159     outs.printf("<style:style style:name=\"P1\" style:family=\"paragraph\">\n");
2160     outs.printf("  <style:paragraph-properties fo:text-align=\"center\"/>\n");
2161     outs.printf("</style:style>\n");
2162     outs.printf("</office:automatic-styles>\n");
2163     outs.printf("\n");
2164     outs.printf("\n");
2165     outs.printf("<office:master-styles>\n");
2166     outs.printf("<draw:layer-set>\n");
2167     outs.printf("    <draw:layer draw:name=\"layout\"/>\n");
2168     outs.printf("    <draw:layer draw:name=\"background\"/>\n");
2169     outs.printf("    <draw:layer draw:name=\"backgroundobjects\"/>\n");
2170     outs.printf("    <draw:layer draw:name=\"controls\"/>\n");
2171     outs.printf("    <draw:layer draw:name=\"measurelines\"/>\n");
2172     outs.printf("</draw:layer-set>\n");
2173     outs.printf("\n");
2174     outs.printf("<style:master-page style:name=\"Default\"\n");
2175     outs.printf("    style:page-master-name=\"PM1\" draw:style-name=\"dp1\"/>\n");
2176     outs.printf("</office:master-styles>\n");
2177     outs.printf("\n");
2178     outs.printf("\n");
2179     outs.printf("\n");
2180     outs.printf("</office:document-styles>\n");
2181     outs.printf("\n");
2182     outs.printf("<!--\n");
2183     outs.printf("*************************************************************************\n");
2184     outs.printf("  E N D    O F    F I L E\n");
2185     outs.printf("  Have a nice day  - ishmal\n");
2186     outs.printf("*************************************************************************\n");
2187     outs.printf("-->\n");
2188     outs.printf("\n");
2190     return true;
2196 /**
2197  * Write the header for the content.xml file
2198  */
2199 bool OdfOutput::writeContentHeader(Writer &outs)
2201     time_t tim;
2202     time(&tim);
2204     outs.printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
2205     outs.printf("\n");
2206     outs.printf("\n");
2207     outs.printf("<!--\n");
2208     outs.printf("*************************************************************************\n");
2209     outs.printf("  file:  content.xml\n");
2210     outs.printf("  Generated by Inkscape: %s", ctime(&tim)); //ctime has its own <cr>
2211     outs.printf("  http://www.inkscape.org\n");
2212     outs.printf("*************************************************************************\n");
2213     outs.printf("-->\n");
2214     outs.printf("\n");
2215     outs.printf("\n");
2216     outs.printf("<office:document-content\n");
2217     outs.printf("    xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\"\n");
2218     outs.printf("    xmlns:style=\"urn:oasis:names:tc:opendocument:xmlns:style:1.0\"\n");
2219     outs.printf("    xmlns:text=\"urn:oasis:names:tc:opendocument:xmlns:text:1.0\"\n");
2220     outs.printf("    xmlns:table=\"urn:oasis:names:tc:opendocument:xmlns:table:1.0\"\n");
2221     outs.printf("    xmlns:draw=\"urn:oasis:names:tc:opendocument:xmlns:drawing:1.0\"\n");
2222     outs.printf("    xmlns:fo=\"urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0\"\n");
2223     outs.printf("    xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n");
2224     outs.printf("    xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n");
2225     outs.printf("    xmlns:meta=\"urn:oasis:names:tc:opendocument:xmlns:meta:1.0\"\n");
2226     outs.printf("    xmlns:number=\"urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0\"\n");
2227     outs.printf("    xmlns:presentation=\"urn:oasis:names:tc:opendocument:xmlns:presentation:1.0\"\n");
2228     outs.printf("    xmlns:svg=\"urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0\"\n");
2229     outs.printf("    xmlns:chart=\"urn:oasis:names:tc:opendocument:xmlns:chart:1.0\"\n");
2230     outs.printf("    xmlns:dr3d=\"urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0\"\n");
2231     outs.printf("    xmlns:math=\"http://www.w3.org/1998/Math/MathML\"\n");
2232     outs.printf("    xmlns:form=\"urn:oasis:names:tc:opendocument:xmlns:form:1.0\"\n");
2233     outs.printf("    xmlns:script=\"urn:oasis:names:tc:opendocument:xmlns:script:1.0\"\n");
2234     outs.printf("    xmlns:ooo=\"http://openoffice.org/2004/office\"\n");
2235     outs.printf("    xmlns:ooow=\"http://openoffice.org/2004/writer\"\n");
2236     outs.printf("    xmlns:oooc=\"http://openoffice.org/2004/calc\"\n");
2237     outs.printf("    xmlns:dom=\"http://www.w3.org/2001/xml-events\"\n");
2238     outs.printf("    xmlns:xforms=\"http://www.w3.org/2002/xforms\"\n");
2239     outs.printf("    xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n");
2240     outs.printf("    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n");
2241     outs.printf("    xmlns:smil=\"urn:oasis:names:tc:opendocument:xmlns:smil-compatible:1.0\"\n");
2242     outs.printf("    xmlns:anim=\"urn:oasis:names:tc:opendocument:xmlns:animation:1.0\"\n");
2243     outs.printf("    office:version=\"1.0\">\n");
2244     outs.printf("\n");
2245     outs.printf("\n");
2246     outs.printf("<office:scripts/>\n");
2247     outs.printf("\n");
2248     outs.printf("\n");
2249     outs.printf("<!--\n");
2250     outs.printf("*************************************************************************\n");
2251     outs.printf("  D R A W I N G\n");
2252     outs.printf("  This section is the heart of SVG-ODF conversion.  We are\n");
2253     outs.printf("  starting with simple conversions, and will slowly evolve\n");
2254     outs.printf("  into a 'smarter' translation as time progresses.  Any help\n");
2255     outs.printf("  in improving .odg export is welcome.\n");
2256     outs.printf("*************************************************************************\n");
2257     outs.printf("-->\n");
2258     outs.printf("\n");
2259     outs.printf("\n");
2260     outs.printf("<office:body>\n");
2261     outs.printf("<office:drawing>\n");
2262     outs.printf("<draw:page draw:name=\"page1\" draw:style-name=\"dp1\"\n");
2263     outs.printf("        draw:master-page-name=\"Default\">\n");
2264     outs.printf("\n");
2265     outs.printf("\n");
2267     return true;
2271 /**
2272  * Write the footer for the content.xml file
2273  */
2274 bool OdfOutput::writeContentFooter(Writer &outs)
2276     outs.printf("\n");
2277     outs.printf("\n");
2279     outs.printf("</draw:page>\n");
2280     outs.printf("</office:drawing>\n");
2282     outs.printf("\n");
2283     outs.printf("\n");
2284     outs.printf("<!-- ######### CONVERSION FROM SVG ENDS ######## -->\n");
2285     outs.printf("\n");
2286     outs.printf("\n");
2288     outs.printf("</office:body>\n");
2289     outs.printf("</office:document-content>\n");
2290     outs.printf("\n");
2291     outs.printf("\n");
2292     outs.printf("\n");
2293     outs.printf("<!--\n");
2294     outs.printf("*************************************************************************\n");
2295     outs.printf("  E N D    O F    F I L E\n");
2296     outs.printf("  Have a nice day  - ishmal\n");
2297     outs.printf("*************************************************************************\n");
2298     outs.printf("-->\n");
2299     outs.printf("\n");
2300     outs.printf("\n");
2302     return true;
2307 /**
2308  * Write the content.xml file.  Writes the namesspace headers, then
2309  * calls writeTree().
2310  */
2311 bool OdfOutput::writeContent(ZipFile &zf, Inkscape::XML::Node *node)
2313     //Content.xml stream
2314     BufferOutputStream cbouts;
2315     OutputStreamWriter couts(cbouts);
2317     if (!writeContentHeader(couts))
2318         return false;
2320     //Style.xml stream
2321     BufferOutputStream sbouts;
2322     OutputStreamWriter souts(sbouts);
2324     if (!writeStyleHeader(souts))
2325         return false;
2328     //# Descend into the tree, doing all of our conversions
2329     //# to both files as the same time
2330     if (!writeTree(couts, souts, node))
2331         {
2332         g_warning("Failed to convert SVG tree");
2333         return false;
2334         }
2338     //# Finish content file
2339     if (!writeContentFooter(couts))
2340         return false;
2342     ZipEntry *ze = zf.newEntry("content.xml", "ODF master content file");
2343     ze->setUncompressedData(cbouts.getBuffer());
2344     ze->finish();
2348     //# Finish style file
2349     if (!writeStyleFooter(souts))
2350         return false;
2352     ze = zf.newEntry("styles.xml", "ODF style file");
2353     ze->setUncompressedData(sbouts.getBuffer());
2354     ze->finish();
2356     return true;
2360 /**
2361  * Resets class to its pristine condition, ready to use again
2362  */
2363 void
2364 OdfOutput::reset()
2366     metadata.clear();
2367     styleTable.clear();
2368     styleLookupTable.clear();
2369     gradientTable.clear();
2370     gradientLookupTable.clear();
2371     imageTable.clear();
2377 /**
2378  * Descends into the SVG tree, mapping things to ODF when appropriate
2379  */
2380 void
2381 OdfOutput::save(Inkscape::Extension::Output *mod, SPDocument *doc, gchar const *uri)
2383     reset();
2385     //g_message("native file:%s\n", uri);
2386     documentUri = URI(uri);
2388     ZipFile zf;
2389     preprocess(zf, doc->rroot);
2391     if (!writeManifest(zf))
2392         {
2393         g_warning("Failed to write manifest");
2394         return;
2395         }
2397     if (!writeContent(zf, doc->rroot))
2398         {
2399         g_warning("Failed to write content");
2400         return;
2401         }
2403     if (!writeMeta(zf))
2404         {
2405         g_warning("Failed to write metafile");
2406         return;
2407         }
2409     if (!zf.writeFile(uri))
2410         {
2411         return;
2412         }
2416 /**
2417  * This is the definition of PovRay output.  This function just
2418  * calls the extension system with the memory allocated XML that
2419  * describes the data.
2420 */
2421 void
2422 OdfOutput::init()
2424     Inkscape::Extension::build_from_mem(
2425         "<inkscape-extension>\n"
2426             "<name>" N_("OpenDocument Drawing Output") "</name>\n"
2427             "<id>org.inkscape.output.odf</id>\n"
2428             "<output>\n"
2429                 "<extension>.odg</extension>\n"
2430                 "<mimetype>text/x-povray-script</mimetype>\n"
2431                 "<filetypename>" N_("OpenDocument drawing (*.odg)") "</filetypename>\n"
2432                 "<filetypetooltip>" N_("OpenDocument drawing file") "</filetypetooltip>\n"
2433             "</output>\n"
2434         "</inkscape-extension>",
2435         new OdfOutput());
2438 /**
2439  * Make sure that we are in the database
2440  */
2441 bool
2442 OdfOutput::check (Inkscape::Extension::Extension *module)
2444     /* We don't need a Key
2445     if (NULL == Inkscape::Extension::db.get(SP_MODULE_KEY_OUTPUT_POV))
2446         return FALSE;
2447     */
2449     return TRUE;
2454 //########################################################################
2455 //# I N P U T
2456 //########################################################################
2460 //#######################
2461 //# L A T E R  !!!  :-)
2462 //#######################
2476 }  //namespace Internal
2477 }  //namespace Extension
2478 }  //namespace Inkscape
2481 //########################################################################
2482 //# E N D    O F    F I L E
2483 //########################################################################
2485 /*
2486   Local Variables:
2487   mode:c++
2488   c-file-style:"stroustrup"
2489   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
2490   indent-tabs-mode:nil
2491   fill-column:99
2492   End:
2493 */
2494 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :