Code

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