Debian Codegraph @

fontforge/svg.c

raw symbols SCIP
1 /* Copyright (C) 2003-2012 by George Williams */
2 /*
3 * Redistribution and use in source and binary forms, with or without
4 * modification, are permitted provided that the following conditions are met:
5
6 * Redistributions of source code must retain the above copyright notice, this
7 * list of conditions and the following disclaimer.
8
9 * Redistributions in binary form must reproduce the above copyright notice,
10 * this list of conditions and the following disclaimer in the documentation
11 * and/or other materials provided with the distribution.
12
13 * The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28 #include <fontforge-config.h>
29
30 #include "svg.h"
31
32 #include "autohint.h"
33 #include "cvimages.h"
34 #include "dumppfa.h"
35 #include "encoding.h"
36 #include "ffglib_compat.h"
37 #include "fontforgevw.h"
38 #include "fvfonts.h"
39 #include "gfile.h"
40 #include "gutils.h"
41 #include "lookups.h"
42 #include "namelist.h"
43 #include "parsettf.h"
44 #include "psread.h"
45 #include "sd.h"
46 #include "splineorder2.h"
47 #include "splinesaveafm.h"
48 #include "splinestroke.h"
49 #include "splineutil.h"
50 #include "splineutil2.h"
51 #include "tottf.h"
52 #include "tottfgpos.h"
53 #include "ustring.h"
54 #include "utanvec.h"
55 #include "utype.h"
56
57 #include <locale.h>
58 #include <math.h>
59 #include <sys/stat.h>
60 #include <sys/types.h>
61 #include <time.h>
62 #include "ffunistd.h"
63
64 /* ************************************************************************** */
65 /* **************************** SVG Output **************************** */
66 /* ************************************************************************** */
67
68 static void latin1ToUtf8Out(FILE *file,char *str) {
69 /* beware of characters above 0x80, also &, <, > (things that are magic for xml) */
70 while ( *str ) {
71 if ( *str=='&' || *str=='<' || *str=='>' || (*str&0x80) )
72 fprintf( file, "&#%d;", (uint8_t) *str);
73 else
74 putc(*str,file);
75 ++str;
76 }
77 }
78
79 static int svg_outfontheader(FILE *file, SplineFont *sf,int layer) {
80 int defwid = SFFigureDefWidth(sf,NULL);
81 struct pfminfo info;
82 static const char *condexp[] = { "squinchy", "ultra-condensed", "extra-condensed",
83 "condensed", "semi-condensed", "normal", "semi-expanded", "expanded",
84 "extra-expanded", "ultra-expanded", "broad" };
85 DBounds bb;
86 BlueData bd;
87 char *hash, *hasv, ch;
88 int minu, maxu, i;
89 const char *author = GetAuthor();
90
91 memset(&info,0,sizeof(info));
92 SFDefaultOS2Info(&info,sf,sf->fontname);
93 SplineFontLayerFindBounds(sf,layer,&bb);
94 QuickBlues(sf,layer,&bd);
95
96 fprintf( file, "<?xml version=\"1.0\" standalone=\"no\"?>\n" );
97 fprintf( file, "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\" >\n" );
98 if ( sf->comments!=NULL ) {
99 fprintf( file, "<!--\n" );
100 latin1ToUtf8Out(file,sf->comments);
101 fprintf( file, "\n-->\n" );
102 }
103 fprintf( file, "<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" version=\"1.1\">\n" );
104 fprintf( file, "<metadata>\nCreated by FontForge %s at %s",
105 FONTFORGE_VERSION, ctime((time_t*)&sf->modificationtime) );
106 if ( author!=NULL )
107 fprintf(file," By %s\n", author);
108 else
109 fprintf(file,"\n" );
110 if ( sf->copyright!=NULL ) {
111 latin1ToUtf8Out(file,sf->copyright);
112 putc('\n',file);
113 }
114 fprintf( file, "</metadata>\n" );
115 fprintf( file, "<defs>\n" );
116 fprintf( file, "<font id=\"");
117 latin1ToUtf8Out(file, sf->fontname);
118 fprintf(file, "\" horiz-adv-x=\"%d\" ", defwid );
119 if ( sf->hasvmetrics )
120 fprintf( file, "vert-adv-y=\"%d\" ", sf->ascent+sf->descent );
121 putc('>',file); putc('\n',file);
122 fprintf( file, " <font-face \n" );
123 if (sf->familyname_with_timestamp != NULL || sf->familyname != NULL) {
124 fprintf( file, " font-family=\"");
125 latin1ToUtf8Out(file, sf->familyname_with_timestamp ? sf->familyname_with_timestamp : sf->familyname );
126 fprintf( file, "\"\n");
127 } else {
128 LogError(_("An SVG font without a familyname value might not be usable."));
129 }
130 fprintf( file, " font-weight=\"%d\"\n", info.weight );
131 if ( strstrmatch(sf->fontname,"obli") || strstrmatch(sf->fontname,"slanted") )
132 fprintf( file, " font-style=\"oblique\"\n" );
133 else if ( MacStyleCode(sf,NULL)&sf_italic )
134 fprintf( file, " font-style=\"italic\"\n" );
135 if ( strstrmatch(sf->fontname,"small") || strstrmatch(sf->fontname,"cap") )
136 fprintf( file, " font-variant=\"small-caps\"\n" );
137 fprintf( file, " font-stretch=\"%s\"\n", condexp[info.width]);
138 fprintf( file, " units-per-em=\"%d\"\n", sf->ascent+sf->descent );
139 fprintf( file, " panose-1=\"%d %d %d %d %d %d %d %d %d %d\"\n", info.panose[0],
140 info.panose[1], info.panose[2], info.panose[3], info.panose[4], info.panose[5],
141 info.panose[6], info.panose[7], info.panose[8], info.panose[9]);
142 fprintf( file, " ascent=\"%d\"\n", sf->ascent );
143 fprintf( file, " descent=\"%d\"\n", -sf->descent );
144 if ( bd.xheight>0 )
145 fprintf( file, " x-height=\"%g\"\n", (double) bd.xheight );
146 if ( bd.caph>0 )
147 fprintf( file, " cap-height=\"%g\"\n", (double) bd.caph );
148 fprintf( file, " bbox=\"%g %g %g %g\"\n", (double) bb.minx, (double) bb.miny, (double) bb.maxx, (double) bb.maxy );
149 fprintf( file, " underline-thickness=\"%g\"\n", (double) sf->uwidth );
150 fprintf( file, " underline-position=\"%g\"\n", (double) sf->upos );
151 if ( sf->italicangle!=0 )
152 fprintf(file, " slope=\"%g\"\n", (double) sf->italicangle );
153 hash = PSDictHasEntry(sf->private_dict,"StdHW");
154 hasv = PSDictHasEntry(sf->private_dict,"StdVW");
155 if ( hash!=NULL ) {
156 if ( *hash=='[' ) ++hash;
157 ch = hash[strlen(hash)-1];
158 if ( ch==']' ) hash[strlen(hash)-1] = '\0';
159 fprintf(file, " stemh=\"%s\"\n", hash );
160 if ( ch==']' ) hash[strlen(hash)] = ch;
161 }
162 if ( hasv!=NULL ) {
163 if ( *hasv=='[' ) ++hasv;
164 ch = hasv[strlen(hasv)-1];
165 if ( ch==']' ) hasv[strlen(hasv)-1] = '\0';
166 fprintf(file, " stemv=\"%s\"\n", hasv );
167 if ( ch==']' ) hasv[strlen(hasv)] = ch;
168 }
169 minu = 0x7fffff; maxu = 0;
170 for ( i=0; i<sf->glyphcnt; ++i ) if ( sf->glyphs[i]!=NULL && sf->glyphs[i]->unicodeenc>0 ) {
171 if ( sf->glyphs[i]->unicodeenc<minu ) minu = sf->glyphs[i]->unicodeenc;
172 if ( sf->glyphs[i]->unicodeenc>maxu ) maxu = sf->glyphs[i]->unicodeenc;
173 }
174 if ( maxu!=0 )
175 fprintf(file, " unicode-range=\"U+%04X-%04X\"\n", minu, maxu );
176 fprintf( file, " />\n" );
177 return( defwid );
178 }
179
180 static int svg_pathdump(FILE *file, SplineSet *spl, int lineout,
181 int forceclosed, int do_clips) {
182 BasePoint last;
183 char buffer[85];
184 int closed=false;
185 Spline *sp, *first;
186 /* as I see it there is nothing to be gained by optimizing out the */
187 /* command characters, since they just have to be replaced by spaces */
188 /* so I don't bother to */
189
190 last.x = last.y = 0;
191 while ( spl!=NULL ) {
192 if ( (do_clips && spl->is_clip_path) || (!do_clips && !spl->is_clip_path)) {
193 sprintf( buffer, "M%g %g", (double) spl->first->me.x, (double) spl->first->me.y );
194 if ( lineout+strlen(buffer)>=255 ) { putc('\n',file); lineout = 0; }
195 fputs( buffer,file );
196 lineout += strlen( buffer );
197 last = spl->first->me;
198 closed = false;
199
200 first = NULL;
201 for ( sp = spl->first->next; sp!=NULL && sp!=first; sp = sp->to->next ) {
202 if ( first==NULL ) first=sp;
203 if ( sp->knownlinear ) {
204 if ( sp->to->me.x==sp->from->me.x )
205 sprintf( buffer,"v%g", (double) (sp->to->me.y-last.y) );
206 else if ( sp->to->me.y==sp->from->me.y )
207 sprintf( buffer,"h%g", (double) (sp->to->me.x-last.x) );
208 else if ( sp->to->next==first ) {
209 strcpy( buffer, "z");
210 closed = true;
211 } else
212 sprintf( buffer,"l%g %g", (double) (sp->to->me.x-last.x), (double) (sp->to->me.y-last.y) );
213 } else if ( sp->order2 ) {
214 if ( sp->from->prev!=NULL && sp->from!=spl->first &&
215 sp->from->me.x-sp->from->prevcp.x == sp->from->nextcp.x-sp->from->me.x &&
216 sp->from->me.y-sp->from->prevcp.y == sp->from->nextcp.y-sp->from->me.y )
217 sprintf( buffer,"t%g %g", (double) (sp->to->me.x-last.x), (double) (sp->to->me.y-last.y) );
218 else
219 sprintf( buffer,"q%g %g %g %g",
220 (double) (sp->to->prevcp.x-last.x), (double) (sp->to->prevcp.y-last.y),
221 (double) (sp->to->me.x-last.x),(double) (sp->to->me.y-last.y));
222 } else {
223 if ( sp->from->prev!=NULL && sp->from!=spl->first &&
224 sp->from->me.x-sp->from->prevcp.x == sp->from->nextcp.x-sp->from->me.x &&
225 sp->from->me.y-sp->from->prevcp.y == sp->from->nextcp.y-sp->from->me.y )
226 sprintf( buffer,"s%g %g %g %g",
227 (double) (sp->to->prevcp.x-last.x), (double) (sp->to->prevcp.y-last.y),
228 (double) (sp->to->me.x-last.x),(double) (sp->to->me.y-last.y));
229 else
230 sprintf( buffer,"c%g %g %g %g %g %g",
231 (double) (sp->from->nextcp.x-last.x), (double) (sp->from->nextcp.y-last.y),
232 (double) (sp->to->prevcp.x-last.x), (double) (sp->to->prevcp.y-last.y),
233 (double) (sp->to->me.x-last.x),(double) (sp->to->me.y-last.y));
234 }
235 if ( lineout+strlen(buffer)>=255 ) { putc('\n',file); lineout = 0; }
236 fputs( buffer,file );
237 lineout += strlen( buffer );
238 last = sp->to->me;
239 }
240 if ( !closed && (forceclosed || spl->first->prev!=NULL) ) {
241 if ( lineout>=254 ) { putc('\n',file); lineout=0; }
242 putc('z',file);
243 ++lineout;
244 }
245 }
246 spl = spl->next;
247 }
248 return( lineout );
249 }
250
251 static void svg_dumpstroke(FILE *file, struct pen *cpen, struct pen *fallback,
252 const char *scname, SplineChar *nested, int layer, int istop) {
253 static const char *joins[] = { "miter", "round", "bevel", "inherit", NULL };
254 static const char *caps[] = { "butt", "round", "square", "inherit", NULL };
255 struct pen pen;
256
257 pen = *cpen;
258 if ( fallback!=NULL ) {
259 if ( pen.brush.col == COLOR_INHERITED ) pen.brush.col = fallback->brush.col;
260 if ( pen.brush.opacity <0 ) pen.brush.opacity = fallback->brush.opacity;
261 if ( pen.width == WIDTH_INHERITED ) pen.width = fallback->width;
262 if ( pen.linecap == lc_inherited ) pen.linecap = fallback->linecap;
263 if ( pen.linejoin == lj_inherited ) pen.linejoin = fallback->linejoin;
264 if ( pen.dashes[0]==0 && pen.dashes[1]==DASH_INHERITED )
265 memcpy(pen.dashes,fallback->dashes,sizeof(pen.dashes));
266 }
267
268 if ( pen.brush.gradient!=NULL ) {
269 fprintf( file, "stroke=\"url(#%s", scname );
270 if ( nested!=NULL )
271 fprintf( file, "-%s", nested->name );
272 fprintf( file, "-ly%d-stroke-grad)\" ", layer );
273 } else if ( pen.brush.pattern!=NULL && istop ) {
274 fprintf( file, "stroke=\"url(#%s", scname );
275 if ( nested!=NULL )
276 fprintf( file, "-%s", nested->name );
277 fprintf( file, "-ly%d-stroke-pattern)\" ", layer );
278 } else {
279 if ( pen.brush.col!=COLOR_INHERITED )
280 fprintf( file, "stroke=\"#%02x%02x%02x\" ",
281 COLOR_RED(pen.brush.col), COLOR_GREEN(pen.brush.col), COLOR_BLUE(pen.brush.col));
282 else
283 fprintf( file, "stroke=\"currentColor\" " );
284 if ( pen.brush.opacity>=0 )
285 fprintf( file, "stroke-opacity=\"%g\" ", (double)pen.brush.opacity);
286 }
287 if ( pen.width!=WIDTH_INHERITED )
288 fprintf( file, "stroke-width=\"%g\" ", (double)pen.width );
289 if ( pen.linecap!=lc_inherited )
290 fprintf( file, "stroke-linecap=\"%s\" ", caps[pen.linecap] );
291 if ( pen.linejoin!=lc_inherited )
292 fprintf( file, "stroke-linejoin=\"%s\" ", joins[pen.linejoin] );
293 /* the current transformation matrix will not affect the fill, but it will */
294 /* affect the way stroke looks. So we must include it here. BUT the spline */
295 /* set has already been transformed, so we must apply the inverse transform */
296 /* to the splineset before outputting it, so that applying the transform */
297 /* will give us the splines we desire. */
298 if ( pen.trans[0]!=1.0 || pen.trans[3]!=1.0 || pen.trans[1]!=0 || pen.trans[2]!=0 )
299 fprintf( file, "transform=\"matrix(%g, %g, %g, %g, 0, 0)\" ",
300 (double) pen.trans[0], (double) pen.trans[1], (double) pen.trans[2], (double) pen.trans[3] );
301 if ( pen.dashes[0]==0 && pen.dashes[1]==DASH_INHERITED ) {
302 fprintf( file, "stroke-dasharray=\"inherit\" " );
303 } else if ( pen.dashes[0]!=0 ) {
304 int i;
305 fprintf( file, "stroke-dasharray=\"" );
306 for ( i=0; i<DASH_MAX && pen.dashes[i]!=0; ++i )
307 fprintf( file, "%d ", pen.dashes[i]);
308 fprintf( file,"\" ");
309 } else {
310 /* That's the default, don't need to say it */
311 /* fprintf( file, "stroke-dasharray=\"none\" " )*/
312 ;
313 }
314 }
315
316 static void svg_dumpfill(FILE *file, struct brush *cbrush, struct brush *fallback,
317 int dofill, const char *scname, SplineChar *nested, int layer, int istop ) {
318 struct brush brush;
319
320 if ( !dofill ) {
321 fprintf( file, "fill=\"none\" " );
322 return;
323 }
324
325 brush = *cbrush;
326 if ( fallback!=NULL ) {
327 if ( brush.col==COLOR_INHERITED ) brush.col = fallback->col;
328 if ( brush.opacity<0 ) brush.opacity = fallback->opacity;
329 }
330
331 if ( brush.gradient!=NULL ) {
332 fprintf( file, "fill=\"url(#%s", scname );
333 if ( nested!=NULL )
334 fprintf( file, "-%s", nested->name );
335 fprintf( file, "-ly%d-fill-grad)\" ", layer );
336 } else if ( brush.pattern!=NULL && istop ) {
337 fprintf( file, "fill=\"url(#%s", scname );
338 if ( nested!=NULL )
339 fprintf( file, "-%s", nested->name );
340 fprintf( file, "-ly%d-fill-pattern)\" ", layer );
341 } else {
342 if ( brush.col!=COLOR_INHERITED )
343 fprintf( file, "fill=\"#%02x%02x%02x\" ",
344 COLOR_RED(brush.col), COLOR_GREEN(brush.col), COLOR_BLUE(brush.col));
345 else
346 fprintf( file, "fill=\"currentColor\" " );
347 if ( brush.opacity>=0 )
348 fprintf( file, "fill-opacity=\"%g\" ", (double)brush.opacity);
349 }
350 }
351
352 static SplineSet *TransBy(SplineSet *ss, real trans[4] ) {
353 real inversetrans[6], transform[6];
354
355 if ( trans[0]==1.0 && trans[3]==1.0 && trans[1]==0 && trans[2]==0 )
356 return( ss );
357 memcpy(transform,trans,4*sizeof(real));
358 transform[4] = transform[5] = 0;
359 MatInverse(inversetrans,transform);
360 return( SplinePointListTransform(SplinePointListCopy(
361 ss),inversetrans,tpt_AllPoints));
362 }
363
364 static int svg_sc_any(SplineChar *sc,int layer) {
365 int i,j;
366 int any;
367 RefChar *ref;
368 int first, last;
369
370 first = last = layer;
371 if ( sc->parent!=NULL && sc->parent->multilayer )
372 last = sc->layer_cnt-1;
373 any = false;
374 for ( i=first; i<=last && !any; ++i ) {
375 any = sc->layers[i].splines!=NULL || sc->layers[i].images!=NULL;
376 for ( ref=sc->layers[i].refs ; ref!=NULL && !any; ref = ref->next )
377 for ( j=0; j<ref->layer_cnt && !any; ++j )
378 any = ref->layers[j].splines!=NULL;
379 }
380 return( any );
381 }
382
383 static int base64tab[] = {
384 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
385 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
386 '0','1','2','3','4','5','6','7','8','9','+', '/'
387 };
388
389 static void DataURI_ImageDump(FILE *file,struct gimage *img) {
390 const char *mimetype=NULL;
391 FILE *imgf;
392 int done = false;
393 int threechars[3], fourchars[4], i, ch, ch_on_line;
394 #if !defined( _NO_LIBJPEG)
395 struct _GImage *base = img->list_len==0 ? img->u.image : img->u.images[0];
396 #endif
397
398 /* Technically we can only put a file into an URI if the whole thing is */
399 /* less than 1024 bytes long. But I shall ignore that issue */
400 imgf = GFileTmpfile();
401 #if !defined(_NO_LIBJPEG)
402 if ( base->image_type == it_true ) {
403 done = GImageWrite_Jpeg(img,imgf,78,false);
404 mimetype = "image/jpeg";
405 }
406 #endif
407 #ifndef _NO_LIBPNG
408 if ( !done ) {
409 done = GImageWrite_Png(img,imgf,false);
410 mimetype = "image/png";
411 }
412 #endif
413 if ( !done ) {
414 GImageWrite_Bmp(img,imgf);
415 mimetype = "image/bmp";
416 }
417
418 fprintf( file,"%s;base64,", mimetype );
419 rewind(imgf);
420
421 /* Now do base64 output conversion */
422
423 rewind(imgf);
424 ch = getc(imgf);
425 ch_on_line = 0;
426 while ( ch!=EOF ) {
427 threechars[0] = threechars[1] = threechars[2] = 0;
428 for ( i=0; i<3 && ch!=EOF ; ++i ) {
429 threechars[i] = ch;
430 ch = getc(imgf);
431 }
432 if ( i>0 ) {
433 fourchars[0] = base64tab[threechars[0]>>2];
434 fourchars[1] = base64tab[((threechars[0]&0x3)<<4)|(threechars[1]>>4)];
435 fourchars[2] = base64tab[((threechars[1]&0xf)<<2)|(threechars[2]>>6)];
436 fourchars[3] = base64tab[threechars[2]&0x3f];
437 if ( i<3 )
438 fourchars[3] = '=';
439 if ( i<2 )
440 fourchars[2] = '=';
441 putc(fourchars[0],file);
442 putc(fourchars[1],file);
443 putc(fourchars[2],file);
444 putc(fourchars[3],file);
445 ch_on_line += 4;
446 if ( ch_on_line>=72 ) {
447 putc('\n',file);
448 ch_on_line = 0;
449 }
450 }
451 }
452 fclose(imgf);
453 }
454
455 static void svg_dumpgradient(FILE *file,struct gradient *gradient,
456 const char *scname,SplineChar *nested,int layer,int is_fill) {
457 int i;
458 Color csame; float osame;
459
460 fprintf( file, " <%s ", gradient->radius==0 ? "linearGradient" : "radialGradient" );
461 if ( nested==NULL )
462 fprintf( file, " id=\"%s-ly%d-%s-grad\"", scname, layer, is_fill ? "fill" : "stroke" );
463 else
464 fprintf( file, " id=\"%s-%s-ly%d-%s-grad\"", scname, nested->name, layer, is_fill ? "fill" : "stroke" );
465 fprintf(file, "\n\tgradientUnits=\"userSpaceOnUse\"" );
466 if ( gradient->radius==0 ) {
467 fprintf( file, "\n\tx1=\"%g\" y1=\"%g\" x2=\"%g\" y2=\"%g\"",
468 (double) gradient->start.x, (double) gradient->start.y,
469 (double) gradient->stop.x, (double) gradient->stop.y );
470 } else {
471 if ( gradient->start.x==gradient->stop.x && gradient->start.y==gradient->stop.y )
472 fprintf( file, "\n\tcx=\"%g\" cy=\"%g\" r=\"%g\"",
473 (double) gradient->stop.x, (double) gradient->stop.y,
474 (double) gradient->radius );
475 else
476 fprintf( file, "\n\tfx=\"%g\" fy=\"%g\" cx=\"%g\" cy=\"%g\" r=\"%g\"",
477 (double) gradient->start.x, (double) gradient->start.y,
478 (double) gradient->stop.x, (double) gradient->stop.y,
479 (double) gradient->radius );
480 }
481 fprintf(file, "\n\tspreadMethod=\"%s\">\n",
482 gradient->sm == sm_pad ? "pad" :
483 gradient->sm == sm_reflect ? "reflect" :
484 "repeat" );
485
486 csame = (Color)-1; osame = -1;
487 for ( i=0; i<gradient->stop_cnt; ++i ) {
488 if ( csame==(Color)-1 )
489 csame = gradient->grad_stops[i].col;
490 else if ( csame!=gradient->grad_stops[i].col )
491 csame = (Color)-2;
492 if ( osame== -1 )
493 osame = gradient->grad_stops[i].opacity;
494 else if ( (double)osame!=gradient->grad_stops[i].opacity )
495 osame = -2;
496 }
497 for ( i=0; i<gradient->stop_cnt; ++i ) {
498 fprintf( file, " <stop offset=\"%g\"", (double) gradient->grad_stops[i].offset );
499 if ( csame==(Color)-2 ) {
500 if ( gradient->grad_stops[i].col==COLOR_INHERITED )
501 fprintf( file, " stop-color=\"inherit\"" );
502 else
503 fprintf( file, " stop-color=\"#%06x\"", gradient->grad_stops[i].col );
504 }
505 if ( osame<0 ) {
506 if ( gradient->grad_stops[i].opacity==COLOR_INHERITED )
507 fprintf( file, " stop-opacity=\"inherit\"" );
508 else
509 fprintf( file, " stop-opacity=\"%g\"", (double) gradient->grad_stops[i].opacity );
510 }
511 fprintf( file, "/>\n" );
512 }
513 fprintf( file, " </%s>\n", gradient->radius==0 ? "linearGradient" : "radialGradient" );
514 }
515
516 static void svg_dumpscdefs(FILE *file,SplineChar *sc,const char *name,int istop);
517 static void svg_dumptype3(FILE *file,SplineChar *sc,const char *name,int istop);
518
519 static void svg_dumppattern(FILE *file,struct pattern *pattern,
520 const char *scname, SplineChar *base,SplineChar *nested,int layer,int is_fill) {
521 SplineChar *pattern_sc = SFGetChar(base->parent,-1,pattern->pattern);
522 char *patsubname = NULL;
523
524 if ( pattern_sc!=NULL ) {
525 patsubname = strconcat3(scname,"-",pattern->pattern);
526 svg_dumpscdefs(file,pattern_sc,patsubname,false);
527 } else
528 LogError(_("No glyph named %s, used as a pattern in %s"), pattern->pattern, scname);
529
530 fprintf( file, " <pattern " );
531 if ( nested==NULL )
532 fprintf( file, " id=\"%s-ly%d-%s-pattern\"", scname, layer, is_fill ? "fill" : "stroke" );
533 else
534 fprintf( file, " id=\"%s-%s-ly%d-%s-pattern\"", scname, nested->name, layer, is_fill ? "fill" : "stroke" );
535 fprintf(file, "\n\tpatternUnits=\"userSpaceOnUse\"" );
536 if ( pattern_sc!=NULL ) {
537 DBounds b;
538 PatternSCBounds(pattern_sc,&b);
539 fprintf( file, "\n\tviewBox=\"%g %g %g %g\"",
540 (double) b.minx, (double) b.miny,
541 (double) (b.maxx-b.minx), (double) (b.maxy-b.miny) );
542 }
543 fprintf( file, "\n\twidth=\"%g\" height=\"%g\"",
544 (double) pattern->width, (double) pattern->height );
545 if ( pattern->transform[0]!=1 || pattern->transform[1]!=0 ||
546 pattern->transform[2]!=0 || pattern->transform[3]!=1 ||
547 pattern->transform[4]!=0 || pattern->transform[5]!=0 ) {
548 fprintf( file, "\n\tpatternTransform=\"matrix(%g %g %g %g %g %g)\"",
549 (double) pattern->transform[0], (double) pattern->transform[1],
550 (double) pattern->transform[2], (double) pattern->transform[3],
551 (double) pattern->transform[4], (double) pattern->transform[5] );
552 }
553 if ( pattern_sc!=NULL )
554 svg_dumpscdefs(file,pattern_sc,patsubname,false);
555 fprintf( file, " </pattern>\n" );
556 free(patsubname);
557 }
558
559 static void svg_layer_defs(FILE *file, SplineSet *splines,struct brush *fill_brush,struct pen *stroke_pen,
560 SplineChar *sc, const char *scname, SplineChar *nested, int layer, int istop ) {
561 if ( SSHasClip(splines)) {
562 if ( nested==NULL )
563 fprintf( file, " <clipPath id=\"%s-ly%d-clip\">\n", scname, layer );
564 else
565 fprintf( file, " <clipPath id=\"%s-%s-ly%d-clip\">\n", scname, nested->name, layer );
566 fprintf(file, " <path d=\"\n");
567 svg_pathdump(file,sc->layers[layer].splines,16,true,true);
568 fprintf(file, "\"/>\n" );
569 fprintf( file, " </clipPath>\n" );
570 }
571 if ( fill_brush->gradient!=NULL )
572 svg_dumpgradient(file,fill_brush->gradient,scname,nested,layer,true);
573 else if ( fill_brush->pattern!=NULL && istop )
574 svg_dumppattern(file,fill_brush->pattern,scname,sc,nested,layer,true);
575 if ( stroke_pen->brush.gradient!=NULL )
576 svg_dumpgradient(file,stroke_pen->brush.gradient,scname,nested,layer,false);
577 else if ( stroke_pen->brush.pattern!=NULL && istop )
578 svg_dumppattern(file,stroke_pen->brush.pattern,scname,sc,nested,layer,false);
579 }
580
581 static void svg_dumpscdefs(FILE *file,SplineChar *sc,const char *name,int istop) {
582 int i, j;
583 RefChar *ref;
584
585 for ( i=ly_fore; i<sc->layer_cnt ; ++i ) {
586 svg_layer_defs(file,sc->layers[i].splines,&sc->layers[i].fill_brush,&sc->layers[i].stroke_pen,
587 sc,name,NULL,i,istop);
588 for ( ref=sc->layers[i].refs ; ref!=NULL; ref = ref->next ) {
589 for ( j=0; j<ref->layer_cnt; ++j ) if ( ref->layers[j].splines!=NULL ) {
590 svg_layer_defs(file,ref->layers[j].splines,&ref->layers[j].fill_brush,&ref->layers[j].stroke_pen,
591 sc,name,ref->sc,j,istop);
592 }
593 }
594 }
595 }
596
597 static char* svg_sc_name(SplineChar *sc) {
598 return sc->glif_name ? sc->glif_name : sc->name;
599 }
600
601 static void svg_dumptype3(FILE *file,SplineChar *sc,const char *name,int istop) {
602 int i, j;
603 RefChar *ref;
604 ImageList *images;
605 SplineSet *transed;
606
607 for ( i=ly_fore; i<sc->layer_cnt ; ++i ) {
608 if ( SSHasDrawn(sc->layers[i].splines) ) {
609 fprintf(file, " <g " );
610 if ( SSHasClip(sc->layers[i].splines))
611 fprintf( file, "clip-path=\"url(#%s-ly%d-clip)\" ", name, i );
612 transed = sc->layers[i].splines;
613 if ( sc->layers[i].dostroke ) {
614 svg_dumpstroke(file,&sc->layers[i].stroke_pen,NULL,name,NULL,i,istop);
615 transed = TransBy(transed,sc->layers[i].stroke_pen.trans);
616 }
617 svg_dumpfill(file,&sc->layers[i].fill_brush,NULL,sc->layers[i].dofill,name,NULL,i,istop);
618 fprintf( file, ">\n" );
619 fprintf(file, " <path d=\"\n");
620 svg_pathdump(file,transed,12,!sc->layers[i].dostroke,false);
621 fprintf(file, "\"/>\n" );
622 if ( transed!=sc->layers[i].splines )
623 SplinePointListsFree(transed);
624 fprintf(file, " </g>\n" );
625 }
626 for ( ref=sc->layers[i].refs ; ref!=NULL; ref = ref->next ) {
627 for ( j=0; j<ref->layer_cnt; ++j ) if ( ref->layers[j].splines!=NULL ) {
628 fprintf(file, " <g " );
629 transed = ref->layers[j].splines;
630 if ( SSHasClip(transed))
631 fprintf( file, "clip-path=\"url(#%s-%s-ly%d-clip)\" ", name, svg_sc_name(ref->sc), j );
632 if ( ref->layers[j].dostroke ) {
633 svg_dumpstroke(file,&ref->layers[j].stroke_pen,&sc->layers[i].stroke_pen,svg_sc_name(sc),ref->sc,j,istop);
634 transed = TransBy(transed,ref->layers[j].stroke_pen.trans);
635 }
636 svg_dumpfill(file,&ref->layers[j].fill_brush,&sc->layers[i].fill_brush,ref->layers[j].dofill,svg_sc_name(sc),ref->sc,j,istop);
637 fprintf( file, ">\n" );
638 fprintf(file, " <path d=\"\n");
639 svg_pathdump(file,transed,12,!ref->layers[j].dostroke,false);
640 fprintf(file, "\"/>\n" );
641 if ( transed!=ref->layers[j].splines )
642 SplinePointListsFree(transed);
643 fprintf(file, " </g>\n" );
644 }
645 }
646 for ( images=sc->layers[i].images ; images!=NULL; images = images->next ) {
647 struct _GImage *base;
648 fprintf(file, " <image\n" );
649 base = images->image->list_len==0 ? images->image->u.image :
650 images->image->u.images[0];
651 fprintf(file, "\twidth=\"%g\"\n\theight=\"%g\"\n",
652 (double) (base->width*images->xscale), (double) (base->height*images->yscale) );
653 fprintf(file, "\tx=\"%g\"\n\ty=\"%g\"\n", (double) images->xoff, (double) images->yoff );
654 fprintf(file, "\txlink:href=\"data:" );
655 DataURI_ImageDump(file,images->image);
656 fprintf(file, "\" />\n" );
657 }
658 }
659 }
660
661 static void svg_scpathdump(FILE *file, SplineChar *sc,const char *endpath,int layer) {
662 RefChar *ref;
663 int lineout;
664 int i,j;
665 int needs_defs=0;
666
667 if ( !svg_sc_any(sc,layer) ) {
668 /* I think a space is represented by leaving out the d (path) entirely*/
669 /* rather than having d="" */
670 fputs(" />\n",file);
671 } else if ( sc->parent!=NULL && sc->parent->strokedfont ) {
672 /* Can't be done with a path, requires nested elements (I think) */
673 fprintf(file,">\n <g stroke=\"currentColor\" stroke-width=\"%g\" fill=\"none\">\n", (double) sc->parent->strokewidth );
674 fprintf( file," <path d=\"");
675 lineout = svg_pathdump(file,sc->layers[layer].splines,3,false,false);
676 for ( ref= sc->layers[layer].refs; ref!=NULL; ref=ref->next )
677 lineout = svg_pathdump(file,ref->layers[0].splines,lineout,false,false);
678 if ( lineout>=255-4 ) putc('\n',file );
679 putc('"',file);
680 fputs(" />\n </g>\n",file);
681 fputs(endpath,file);
682 } else if ( sc->parent==NULL || !sc->parent->multilayer ) {
683 fprintf( file,"d=\"");
684 lineout = svg_pathdump(file,sc->layers[layer].splines,3,true,false);
685 for ( ref= sc->layers[layer].refs; ref!=NULL; ref=ref->next )
686 lineout = svg_pathdump(file,ref->layers[0].splines,lineout,true,false);
687 if ( lineout>=255-4 ) putc('\n',file );
688 putc('"',file);
689 fputs(" />\n",file);
690 } else {
691 fputs(">\n",file);
692 for ( i=ly_fore; i<sc->layer_cnt && !needs_defs ; ++i ) {
693 if ( SSHasClip(sc->layers[i].splines))
694 needs_defs = true;
695 else if ( sc->layers[i].fill_brush.pattern!=NULL ||
696 sc->layers[i].fill_brush.gradient!=NULL ||
697 sc->layers[i].stroke_pen.brush.pattern!=NULL ||
698 sc->layers[i].stroke_pen.brush.gradient!=NULL )
699 needs_defs = true;
700 for ( ref=sc->layers[i].refs ; ref!=NULL; ref = ref->next ) {
701 for ( j=0; j<ref->layer_cnt; ++j ) if ( ref->layers[j].splines!=NULL ) {
702 if ( SSHasClip(ref->layers[j].splines))
703 needs_defs = true;
704 else if ( ref->layers[j].fill_brush.pattern!=NULL ||
705 ref->layers[j].fill_brush.gradient!=NULL ||
706 ref->layers[j].stroke_pen.brush.pattern!=NULL ||
707 ref->layers[j].stroke_pen.brush.gradient!=NULL )
708 needs_defs = true;
709 }
710 }
711 }
712 if ( needs_defs ) {
713 fprintf(file, " <defs>\n" );
714 svg_dumpscdefs(file,sc,svg_sc_name(sc),true);
715 fprintf(file, " </defs>\n" );
716 }
717 svg_dumptype3(file,sc,svg_sc_name(sc),true);
718 fputs(endpath,file);
719 }
720 }
721
722 static int LigCnt(SplineFont *sf,PST *lig,int32_t *univals,int max) {
723 char *pt, *end;
724 int c=0;
725 SplineChar *sc;
726
727 if ( lig->type!=pst_ligature )
728 return( 0 );
729 else if ( !lig->subtable->lookup->store_in_afm )
730 return( 0 );
731 pt = lig->u.lig.components;
732 for (;;) {
733 end = strchr(pt,' ');
734 if ( end!=NULL ) *end='\0';
735 sc = SFGetChar(sf,-1,pt);
736 if ( end!=NULL ) *end=' ';
737 if ( sc==NULL || sc->unicodeenc==-1 )
738 return( 0 );
739 if ( c>=max )
740 return( 0 );
741 univals[c++] = sc->unicodeenc;
742 if ( end==NULL )
743 return( c );
744 pt = end+1;
745 while ( *pt==' ' ) ++pt;
746 }
747 }
748
749 static PST *HasLigature(SplineChar *sc) {
750 PST *pst, *best=NULL;
751 int bestc=0,c;
752 int32_t univals[50];
753
754 for ( pst=sc->possub; pst!=NULL; pst=pst->next ) {
755 if ( pst->type==pst_ligature ) {
756 c = LigCnt(sc->parent,pst,univals,sizeof(univals)/sizeof(univals[0]));
757 if ( c>1 && c>bestc ) {
758 c = bestc;
759 best = pst;
760 }
761 }
762 }
763 return( best );
764 }
765
766 SplineChar *SCHasSubs(SplineChar *sc, uint32_t tag) {
767 PST *pst;
768
769 for ( pst=sc->possub; pst!=NULL; pst=pst->next ) {
770 if ( pst->type==pst_substitution &&
771 FeatureTagInFeatureScriptList(tag,pst->subtable->lookup->features) )
772 return( SFGetChar(sc->parent,-1,pst->u.subs.variant));
773 }
774 return( NULL );
775 }
776
777 static void svg_scdump(FILE *file, SplineChar *sc,int defwid, int encuni, int vs,int layer) {
778 PST *best=NULL;
779 const unichar_t *alt;
780 int32_t univals[50];
781 int i, c;
782
783 best = HasLigature(sc);
784 if ( sc->comment!=NULL ) {
785 fprintf( file, "\n<!--\n%s\n-->\n",sc->comment );
786 }
787 fprintf(file," <glyph glyph-name=\"%s\" ",svg_sc_name(sc) );
788 if ( best!=NULL ) {
789 c = LigCnt(sc->parent,best,univals,sizeof(univals)/sizeof(univals[0]));
790 fputs("unicode=\"",file);
791 for ( i=0; i<c; ++i )
792 if ( univals[i]>='A' && univals[i]<='z' )
793 putc(univals[i],file);
794 else
795 fprintf(file,"&#x%x;", (unsigned int) univals[i]);
796 fputs("\" ",file);
797 } else if ( encuni!=-1 && encuni<0x110000 ) {
798 if ( encuni!=0x9 &&
799 encuni!=0xa &&
800 encuni!=0xd &&
801 !(encuni>=0x20 && encuni<=0xd7ff) &&
802 !(encuni>=0xe000 && encuni<=0xfffd) &&
803 !(encuni>=0x10000 && encuni<=0x10ffff) )
804 /* Not allowed in XML */;
805 else if ( (encuni>=0x7f && encuni<=0x84) ||
806 (encuni>=0x86 && encuni<=0x9f) ||
807 (encuni>=0xfdd0 && encuni<=0xfddf) ||
808 (encuni&0xffff)==0xfffe ||
809 (encuni&0xffff)==0xffff )
810 /* Not recommended in XML */;
811 else if ( encuni>=32 && encuni<127 &&
812 encuni!='"' && encuni!='&' &&
813 encuni!='<' && encuni!='>' )
814 fprintf( file, "unicode=\"%c\" ", encuni);
815 else if (( isarabisolated(encuni) || isarabinitial(encuni) || isarabmedial(encuni) || isarabfinal(encuni) ) &&
816 (alt = unialt(encuni))!=NULL && alt[1]=='\0' )
817 /* For arabic forms use the base representation in the 0600 block */
818 fprintf( file, "unicode=\"&#x%x;\" ", alt[0]);
819 else if ( vs!=-1 )
820 fprintf( file, "unicode=\"&#x%x;\" ", vs);
821 else
822 fprintf( file, "unicode=\"&#x%x;\" ", encuni);
823 }
824 if ( sc->width!=defwid )
825 fprintf( file, "horiz-adv-x=\"%d\" ", sc->width );
826 if ( sc->parent->hasvmetrics && sc->vwidth!=sc->parent->ascent+sc->parent->descent )
827 fprintf( file, "vert-adv-y=\"%d\" ", sc->vwidth );
828 if ( strstr(sc->name,".vert")!=NULL || strstr(sc->name,".vrt2")!=NULL )
829 fprintf( file, "orientation=\"v\" " );
830 if ( encuni!=-1 ) {
831 if ( isarabinitial(encuni))
832 fprintf( file,"arabic-form=\"initial\" " );
833 else if ( isarabmedial(encuni))
834 fprintf( file,"arabic-form=\"medial\" ");
835 else if ( isarabfinal(encuni))
836 fprintf( file,"arabic-form=\"final\" ");
837 else if ( isarabisolated(encuni))
838 fprintf( file,"arabic-form=\"isolated\" ");
839 }
840 putc('\n',file);
841 svg_scpathdump(file,sc," </glyph>\n",layer);
842 sc->ticked = true;
843 }
844
845 static void svg_notdefdump(FILE *file, SplineFont *sf,int defwid,int layer) {
846 int notdefpos;
847
848 notdefpos = SFFindNotdef(sf,-2);
849
850 if ( notdefpos!=-1 ) {
851 SplineChar *sc = sf->glyphs[notdefpos];
852
853 fprintf(file, "<missing-glyph ");
854 if ( sc->width!=defwid )
855 fprintf( file, "horiz-adv-x=\"%d\" ", sc->width );
856 if ( sc->parent->hasvmetrics && sc->vwidth!=sc->parent->ascent+sc->parent->descent )
857 fprintf( file, "vert-adv-y=\"%d\" ", sc->vwidth );
858 putc('\n',file);
859 svg_scpathdump(file,sc," </glyph>\n",layer);
860 } else {
861 /* We'll let both the horiz and vert advances default to the values */
862 /* specified by the font, and I think a space is done by omitting */
863 /* d (the path) altogether */
864 fprintf(file," <missing-glyph />\n"); /* Is this a blank space? */
865 }
866 }
867
868 static void fputkerns( FILE *file, char *names) {
869 while ( *names ) {
870 if ( *names==' ' ) {
871 putc(',',file);
872 while ( names[1]==' ' ) ++names;
873 } else
874 putc(*names,file);
875 ++names;
876 }
877 }
878
879 static void svg_dumpkerns(FILE *file,SplineFont *sf,int isv) {
880 int i,j;
881 KernPair *kp;
882 KernClass *kc;
883
884 for ( i=0; i<sf->glyphcnt; ++i ) if ( SCWorthOutputting(sf->glyphs[i]) ) {
885 for ( kp = isv ? sf->glyphs[i]->vkerns : sf->glyphs[i]->kerns;
886 kp!=NULL; kp = kp->next )
887 if ( kp->off!=0 && SCWorthOutputting(kp->sc)) {
888 fprintf( file, isv ? " <vkern " : " <hkern " );
889 if ( sf->glyphs[i]->unicodeenc==-1 || HasLigature(sf->glyphs[i]))
890 fprintf( file, "g1=\"%s\" ", sf->glyphs[i]->name );
891 else if ( sf->glyphs[i]->unicodeenc>='A' && sf->glyphs[i]->unicodeenc<='z' )
892 fprintf( file, "u1=\"%c\" ", sf->glyphs[i]->unicodeenc );
893 else
894 fprintf( file, "u1=\"&#x%x;\" ", sf->glyphs[i]->unicodeenc );
895 if ( kp->sc->unicodeenc==-1 || HasLigature(kp->sc))
896 fprintf( file, "g2=\"%s\" ", svg_sc_name(kp->sc) );
897 else if ( kp->sc->unicodeenc>='A' && kp->sc->unicodeenc<='z' )
898 fprintf( file, "u2=\"%c\" ", kp->sc->unicodeenc );
899 else
900 fprintf( file, "u2=\"&#x%x;\" ", kp->sc->unicodeenc );
901 fprintf( file, "k=\"%d\" />\n", -kp->off );
902 }
903 }
904
905 for ( kc=isv ? sf->vkerns : sf->kerns; kc!=NULL; kc=kc->next ) {
906 for ( i=0; i<kc->first_cnt; ++i ) {
907 if ( kc->firsts[i] && *kc->firsts[i]!='\0' ) {
908 for ( j=0; j<kc->second_cnt; ++j ) {
909 if ( kc->seconds[j] && *kc->seconds[j]!='\0' &&
910 kc->offsets[i*kc->second_cnt+j]!=0 ) {
911 fprintf( file, isv ? " <vkern g1=\"" : " <hkern g1=\"" );
912 fputkerns( file, kc->firsts[i]);
913 fprintf( file, "\"\n\tg2=\"" );
914 fputkerns( file, kc->seconds[j]);
915 fprintf( file, "\"\n\tk=\"%d\" />\n",
916 -kc->offsets[i*kc->second_cnt+j]);
917 }
918 }
919 }
920 }
921 }
922 }
923
924 static void svg_outfonttrailer(FILE *file) {
925 fprintf(file," </font>\n");
926 fprintf(file,"</defs></svg>\n" );
927 }
928
929 static int AnyArabicForm( SplineChar *sc ) {
930 struct altuni *altuni;
931
932 if ( sc->unicodeenc!=-1 &&
933 (isarabinitial(sc->unicodeenc) ||
934 isarabmedial(sc->unicodeenc) ||
935 isarabfinal(sc->unicodeenc) ||
936 isarabisolated(sc->unicodeenc)))
937 return( sc->unicodeenc );
938 for ( altuni = sc->altuni; altuni!=NULL; altuni = altuni->next )
939 if ( altuni->unienc!=-1 &&
940 altuni->vs==-1 && altuni->fid==0 &&
941 (isarabinitial(altuni->unienc) ||
942 isarabmedial(altuni->unienc) ||
943 isarabfinal(altuni->unienc) ||
944 isarabisolated(altuni->unienc)))
945 return( altuni->unienc );
946
947 return( -1 );
948 }
949
950 static int UnformedUni(int uni) {
951 return( uni==-1 || uni>=0x10000 ||
952 !(isarabinitial(uni) ||
953 isarabmedial(uni) ||
954 isarabfinal(uni) ||
955 isarabisolated(uni)));
956 }
957
958 static void svg_sfdump(FILE *file,SplineFont *sf,int layer) {
959 int defwid, i, formeduni;
960 struct altuni *altuni;
961
962 locale_t tmplocale; locale_t oldlocale; // Declare temporary locale storage.
963 switch_to_c_locale(&tmplocale, &oldlocale); // Switch to the C locale temporarily and cache the old locale.
964
965 for ( i=0; i<sf->glyphcnt; ++i ) if ( sf->glyphs[i]!=NULL )
966 sf->glyphs[i]->ticked = false;
967
968 defwid = svg_outfontheader(file,sf,layer);
969 svg_notdefdump(file,sf,defwid,layer);
970
971 /* Ligatures must be output before their initial components */
972 for ( i=0; i<sf->glyphcnt; ++i ) {
973 if ( SCWorthOutputting(sf->glyphs[i]) ) {
974 if ( HasLigature(sf->glyphs[i]))
975 svg_scdump(file, sf->glyphs[i],defwid,sf->glyphs[i]->unicodeenc,-1,layer);
976 /* Variation selectors should probably be treated as ligatures */
977 for ( altuni = sf->glyphs[i]->altuni; altuni!=NULL; altuni = altuni->next )
978 if ( altuni->vs!=-1 && altuni->fid==0 )
979 svg_scdump(file, sf->glyphs[i],defwid,altuni->unienc,altuni->vs,layer);
980 }
981 }
982 /* And formed arabic before unformed */
983 for ( i=0; i<sf->glyphcnt; ++i ) {
984 SplineChar *sc = sf->glyphs[i];
985 if ( SCWorthOutputting(sc) && !sc->ticked ) {
986 if ( (formeduni = AnyArabicForm(sc))!=-1 )
987 svg_scdump(file, sc,defwid,formeduni,-1,layer);
988 else if ( sc->unicodeenc>=0x0600 && sc->unicodeenc<=0x06ff ) {
989 /* The conventions now (as I understand them) suggest that */
990 /* fonts not use the unicode encodings for formed arabic */
991 /* but should use simple substitutions instead */
992 const struct arabicforms* form = arabicform(sc->unicodeenc);
993 SplineChar *formed;
994 formed = SCHasSubs(sc,CHR('i','n','i','t'));
995 if ( SCWorthOutputting(formed) && formed->unicodeenc==-1 &&
996 !formed->ticked && form->initial!=0 )
997 svg_scdump(file,formed,defwid,form->initial,-1,layer);
998 formed = SCHasSubs(sc,CHR('m','e','d','i'));
999 if ( SCWorthOutputting(formed) && formed->unicodeenc==-1 &&
1000 !formed->ticked && form->medial!=0 )
1001 svg_scdump(file,formed,defwid,form->medial,-1,layer);
1002 formed = SCHasSubs(sc,CHR('f','i','n','a'));
1003 if ( SCWorthOutputting(formed) && formed->unicodeenc==-1 &&
1004 !formed->ticked && form->final!=0 )
1005 svg_scdump(file,formed,defwid,form->final,-1,layer);
1006 formed = SCHasSubs(sc,CHR('i','s','o','l'));
1007 if ( SCWorthOutputting(formed) && formed->unicodeenc==-1 &&
1008 !formed->ticked && form->isolated!=0 )
1009 svg_scdump(file,formed,defwid,form->isolated,-1,layer);
1010 }
1011 }
1012 }
1013 for ( i=0; i<sf->glyphcnt; ++i ) {
1014 if ( SCWorthOutputting(sf->glyphs[i]) && !sf->glyphs[i]->ticked ) {
1015 if ( UnformedUni(sf->glyphs[i]->unicodeenc) )
1016 svg_scdump(file, sf->glyphs[i],defwid,sf->glyphs[i]->unicodeenc,-1,layer);
1017 for ( altuni = sf->glyphs[i]->altuni; altuni!=NULL; altuni = altuni->next )
1018 if ( altuni->vs==-1 && altuni->fid==0 )
1019 svg_scdump(file, sf->glyphs[i],defwid,altuni->unienc,altuni->vs,layer);
1020 }
1021 }
1022 svg_dumpkerns(file,sf,false);
1023 svg_dumpkerns(file,sf,true);
1024 svg_outfonttrailer(file);
1025 switch_to_old_locale(&tmplocale, &oldlocale); // Switch to the cached locale.
1026 }
1027
1028 int _WriteSVGFont(FILE *file,SplineFont *sf,int flags,
1029 EncMap *map,int layer) {
1030 int ret;
1031
1032 svg_sfdump(file,sf,layer);
1033 ret = true;
1034 if ( ferror(file))
1035 ret = false;
1036 return( ret );
1037 }
1038
1039 int WriteSVGFont(const char *fontname,SplineFont *sf,enum fontformat format,int flags,
1040 EncMap *map,int layer) {
1041 FILE *file;
1042 int ret;
1043
1044 if (( file=fopen(fontname,"w+"))==NULL )
1045 return( 0 );
1046 svg_sfdump(file,sf,layer);
1047 ret = true;
1048 if ( ferror(file))
1049 ret = false;
1050 if ( fclose(file)==-1 )
1051 return( 0 );
1052 return( ret );
1053 }
1054
1055 #define SVGMINLRPAD 10
1056
1057 int _ExportSVG(FILE *svg,SplineChar *sc,int layer,ExportParams *ep) {
1058 char *end;
1059 int em_size, xstart, xend, ascent;
1060 real trans[6] = { 1.0, 0.0, 0.0, 1.0, 0.0, 0.0 };
1061 DBounds b;
1062 SplineChar *scc;
1063 SplineSet *orig;
1064 RefChar *rf = NULL, *next = NULL;
1065
1066 SplineCharLayerFindBounds(sc,layer,&b);
1067 if ( sc->parent!=NULL ) {
1068 ascent = sc->parent->ascent;
1069 em_size = ascent+sc->parent->descent;
1070 if ( b.minx>0 ) b.minx=0;
1071 if ( b.miny>-sc->parent->descent ) b.miny = -sc->parent->descent;
1072 if ( b.maxy<em_size ) b.maxy = em_size;
1073 } else {
1074 ascent = b.maxy;
1075 em_size = b.maxy-b.miny;
1076 }
1077
1078 locale_t tmplocale; locale_t oldlocale; // Declare temporary locale storage.
1079 switch_to_c_locale(&tmplocale, &oldlocale); // Switch to the C locale temporarily and cache the old locale.
1080 fprintf(svg, "<?xml version=\"1.0\" standalone=\"no\"?>\n" );
1081 fprintf(svg, "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\" >\n" );
1082 // Adjust horizontal ViewBox to display entire glyph
1083 xstart = floor(b.minx);
1084 if (xstart > SVGMINLRPAD)
1085 xstart = 0; // Start from origin when sufficiently past it
1086 else
1087 xstart -= SVGMINLRPAD; // Give glyphs starting near or before the origin some extra space
1088 xend = ceil(b.maxx);
1089 if (xend < ceil(sc->width) - SVGMINLRPAD)
1090 xend = ceil(sc->width); // End at the advance width when sufficiently short of it
1091 else
1092 xend += SVGMINLRPAD; // Give glyphs ending near or past the advance width some extra space
1093 fprintf(svg, "<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" version=\"1.1\" viewBox=\"%d 0 %d %d\">\n",
1094 xstart, xend - xstart, (int) ceil(em_size));
1095 if ( ep->use_transform ) {
1096 fprintf(svg, " <g transform=\"matrix(1 0 0 -1 0 %d)\">\n", ascent );
1097 scc = sc;
1098 } else {
1099 trans[3] = -1;
1100 trans[5] = ascent;
1101 if (sc->parent!=NULL) {
1102 scc = SplineCharCopy(sc, sc->parent, NULL);
1103 /* Unlink references before transforming the splines */
1104 for ( rf=scc->layers[layer].refs; rf!=NULL ; rf=next ) {
1105 next = rf->next;
1106 SCReinstanciateRefChar(scc,rf,layer);
1107 SCRefToSplines(scc,rf,layer);
1108 }
1109 FVTrans(scc->parent->fv,scc,trans,NULL,
1110 fvt_nopreserve|fvt_dontmovewidth|fvt_noupdate);
1111 } else {
1112 // This is probably an isolated layer, so just transform the splines
1113 // there and back
1114 orig = sc->layers[layer].splines;
1115 scc = sc;
1116 sc->layers[layer].splines = SplinePointListTransformExtended(
1117 SplinePointListCopy(scc->layers[layer].splines),
1118 trans, tpt_AllPoints, tpmask_dontTrimValues);
1119 }
1120 }
1121 if ( scc->parent!=NULL
1122 && ( scc->parent->multilayer
1123 || scc->parent->strokedfont
1124 || !svg_sc_any(scc,layer)) ) {
1125 fprintf(svg, " <g ");
1126 end = " </g>\n";
1127 } else {
1128 fprintf(svg, " <path fill=\"currentColor\"\n");
1129 end = " </path>\n";
1130 }
1131 svg_scpathdump(svg,scc,end,layer);
1132 if ( ep->use_transform )
1133 fprintf(svg, " </g>\n\n" );
1134 else {
1135 if ( sc->parent )
1136 SplineCharFree(scc);
1137 else {
1138 SplinePointListFree(sc->layers[layer].splines);
1139 sc->layers[layer].splines = orig;
1140 }
1141 }
1142 fprintf(svg, "</svg>\n" );
1143
1144 switch_to_old_locale(&tmplocale, &oldlocale); // Switch to the cached locale.
1145 return( !ferror(svg));
1146 }
1147
1148 /* ************************************************************************** */
1149 /* ***************************** SVG Input **************************** */
1150 /* ************************************************************************** */
1151
1152 #undef extended /* used in xlink.h */
1153 #include <libxml/parser.h>
1154
1155 /* Find a node with the given id */
1156 static xmlNodePtr XmlFindID(xmlNodePtr xml, char *name) {
1157 xmlChar *id;
1158 xmlNodePtr child, ret;
1159
1160 id = xmlGetProp(xml,(xmlChar *) "id");
1161 if ( id!=NULL && xmlStrcmp(id,(xmlChar *) name)==0 ) {
1162 xmlFree(id);
1163 return( xml );
1164 }
1165 if ( id!=NULL )
1166 xmlFree(id);
1167
1168 for ( child = xml->children; child!=NULL; child=child->next ) {
1169 ret = XmlFindID(child,name);
1170 if ( ret!=NULL )
1171 return( ret );
1172 }
1173 return( NULL );
1174 }
1175
1176 static xmlNodePtr XmlFindURI(xmlNodePtr xml, char *name) {
1177 xmlNodePtr ret;
1178 char *pt, ch;
1179
1180 if ( strncmp(name,"url(#",5)!=0 )
1181 return( NULL );
1182 name += 5;
1183 for ( pt=name; *pt!=')' && *pt!='\0'; ++pt );
1184 ch = *pt; *pt = '\0';
1185 ret = XmlFindID(xml,name);
1186 *pt = ch;
1187 return( ret );
1188 }
1189
1190 /* We want to look for "font" nodes within "svg" nodes. Since "svg" nodes may */
1191 /* be embedded within another xml/html document there may be several of them */
1192 /* and there may be several fonts within each */
1193 static int _FindSVGFontNodes(xmlNodePtr node,xmlNodePtr *fonts,int cnt, int max,
1194 char *nodename) {
1195 if ( xmlStrcmp(node->name,(const xmlChar *) nodename)==0 ) {
1196 if ( strcmp(nodename,"svg")==0 )
1197 nodename = "font";
1198 else {
1199 fonts[cnt++] = node;
1200 if ( cnt>=max )
1201 return( cnt );
1202 }
1203 }
1204
1205 for ( node=node->children; node!=NULL; node=node->next ) {
1206 cnt = _FindSVGFontNodes(node,fonts,cnt,max,nodename);
1207 if ( cnt>=max )
1208 return( cnt );
1209 }
1210 return( cnt );
1211 }
1212
1213 static xmlNodePtr *FindSVGFontNodes(xmlDocPtr doc) {
1214 xmlNodePtr *fonts=NULL;
1215 int cnt;
1216
1217 fonts = calloc(100,sizeof(xmlNodePtr)); /* If the file has more than 100 fonts in it then it's foolish to expect the user to pick out one, so let's limit ourselves to 100 */
1218 cnt = _FindSVGFontNodes(xmlDocGetRootElement(doc),fonts,0,100,"svg");
1219 if ( cnt==0 ) {
1220 free(fonts);
1221 return( NULL );
1222 }
1223 return( fonts );
1224 }
1225
1226 static xmlNodePtr SVGPickFont(xmlNodePtr *fonts,char *filename) {
1227 int cnt;
1228 char **names;
1229 xmlChar *name;
1230 char *pt, *lparen;
1231 int choice;
1232
1233 for ( cnt=0; fonts[cnt]!=NULL; ++cnt);
1234 names = malloc((cnt+1)*sizeof(char *));
1235 for ( cnt=0; fonts[cnt]!=NULL; ++cnt) {
1236 name = xmlGetProp(fonts[cnt],(xmlChar *) "id");
1237 if ( name==NULL ) {
1238 names[cnt] = copy("nameless-font");
1239 } else {
1240 names[cnt] = copy((char *) name);
1241 xmlFree(name);
1242 }
1243 }
1244 names[cnt] = NULL;
1245
1246 choice = -1;
1247 pt = NULL;
1248 if ( filename!=NULL )
1249 pt = strrchr(filename,'/');
1250 if ( pt==NULL ) pt = filename;
1251 if ( pt!=NULL && (lparen = strchr(pt,'('))!=NULL && strchr(lparen,')')!=NULL ) {
1252 char *find = copy(lparen+1);
1253 pt = strchr(find,')');
1254 if ( pt!=NULL ) *pt='\0';
1255 for ( choice=cnt-1; choice>=0; --choice )
1256 if ( strcmp(names[choice],find)==0 )
1257 break;
1258 if ( choice==-1 ) {
1259 char *fn = copy(filename);
1260 fn[lparen-filename] = '\0';
1261 ff_post_error(_("Not in Collection"),_("%s is not in %.100s"),find,fn);
1262 free(fn);
1263 }
1264 free(find);
1265 } else if ( no_windowing_ui )
1266 choice = 0;
1267 else
1268 choice = ff_choose(_("Pick a font, any font..."),(const char **) names,cnt,0,_("There are multiple fonts in this file, pick one"));
1269 for ( cnt=0; names[cnt]!=NULL; ++cnt )
1270 free(names[cnt]);
1271 free(names);
1272 if ( choice!=-1 )
1273 return( fonts[choice] );
1274
1275 return( NULL );
1276 }
1277
1278 /* I don't see where the spec says that the separator between numbers is */
1279 /* comma or whitespace (both is ok too) */
1280 /* But the style sheet spec says it, so I probably just missed it */
1281 static char *skipcomma(char *pt) {
1282 while ( isspace(*pt))++pt;
1283 if ( *pt==',' ) ++pt;
1284 return( pt );
1285 }
1286
1287 static void SVGTraceArc(SplineSet *cur,BasePoint *current,
1288 double x,double y,double rx,double ry,double axisrot,
1289 int large_arc,int sweep) {
1290 BasePoint ang, ut_fm, ut_to, c, foc1, foc2, tmp;
1291 double x1p, y1p, sqdiff;
1292 double lambda, factor;
1293 double cxp, cyp;
1294
1295 if ( rx < 0 ) rx = -rx;
1296 if ( ry < 0 ) ry = -ry;
1297 if ( rx!=0 && ry!=0 ) {
1298 /* Page 647 in the SVG 1.1 spec describes how to do this */
1299 /* This is Appendix F (Implementation notes) section 6.5 */
1300 ang = (BasePoint) { cos(axisrot), sin(axisrot) };
1301 x1p = ang.x*(current->x-x)/2 + ang.y*(current->y-y)/2;
1302 y1p =-ang.y*(current->x-x)/2 + ang.x*(current->y-y)/2;
1303 /* Correct for bad radii */
1304 lambda = x1p*x1p/(rx*rx) + y1p*y1p/(ry*ry);
1305 if ( lambda>=1 ) {
1306 lambda = sqrt(lambda);
1307 rx *= lambda;
1308 ry *= lambda;
1309 cxp = cyp = 0;
1310 } else {
1311 factor = rx*rx*ry*ry - rx*rx*y1p*y1p - ry*ry*x1p*x1p;
1312 factor = factor/(rx*rx*y1p*y1p+ry*ry*x1p*x1p);
1313 if (factor < 0) // Ideally the lambda check will prevent this, but ...
1314 factor = 0;
1315 else
1316 factor = sqrt(factor);
1317 // This part of the center calculation deals with large_arc
1318 // leaving sweep as a parameter to SSAppendArc
1319 if ( large_arc==sweep )
1320 factor = -factor;
1321 cxp = factor*(rx*y1p)/ry;
1322 cyp =-factor*(ry*x1p)/rx;
1323 }
1324 c = (BasePoint) { ang.x*cxp - ang.y*cyp + (current->x+x)/2,
1325 ang.y*cxp + ang.x*cyp + (current->y+y)/2 };
1326 // SSAppendArc is parameterized by start and end tangent angle
1327 // To convert start and end points to tangent angles it is easiest
1328 // to average the angles from the foci to the point. That average
1329 // is normal to the curve and therefore the tangent is 90 degrees
1330 // CW for a CW contour.
1331 sqdiff = rx*rx - ry*ry;
1332 if ( sqdiff > 0 )
1333 tmp = BPScale(ang, sqrt(sqdiff));
1334 else
1335 tmp = BPScale(BP90CW(ang), sqrt(-sqdiff));
1336 foc1 = BPAdd(c, tmp);
1337 foc2 = BPSub(c, tmp);
1338
1339 tmp = *current;
1340 ut_fm = BP90CW(NormVec(BPAdd(NormVec(BPSub(tmp, foc1)),
1341 NormVec(BPSub(tmp, foc2)))));
1342 tmp = (BasePoint) { x, y };
1343 ut_to = BP90CW(NormVec(BPAdd(NormVec(BPSub(tmp, foc1)),
1344 NormVec(BPSub(tmp, foc2)))));
1345 SSAppendArc(cur, rx, ry, ang, ut_fm, ut_to, sweep, false);
1346 SplineStrokeSimpleFixup(cur->last, tmp);
1347 } else {
1348 SplinePoint *sp = SplinePointCreate(x, y);
1349 SplineMake3(cur->last, sp);
1350 cur->last = sp;
1351 }
1352 *current = cur->last->me;
1353 }
1354
1355 static SplineSet *SVGParsePath(xmlChar *path) {
1356 BasePoint current;
1357 SplineSet *head=NULL, *last=NULL, *cur=NULL;
1358 SplinePoint *sp;
1359 int type = 'M';
1360 double x1,x2,x,y1,y2,y,rx,ry,axisrot;
1361 int large_arc,sweep;
1362 int order2 = 0;
1363 char *end;
1364
1365 current.x = current.y = 0;
1366
1367 while ( *path ) {
1368 while ( *path==' ' ) ++path;
1369 if ( isalpha(*path)) {
1370 type = *path++;
1371 }
1372 if ( *path=='\0' && type!='z' && type!='Z' )
1373 break;
1374 if ( type=='m' || type=='M' ) {
1375 if ( cur!=NULL && cur->last!=cur->first ) {
1376 // XXX Ugh -- who knows what scale we're at here
1377 // possibly buried in transforms
1378 if ( RealNear(cur->last->me.x,cur->first->me.x) &&
1379 RealNear(cur->last->me.y,cur->first->me.y) ) {
1380 cur->first->prevcp = cur->last->prevcp;
1381 cur->first->prev = cur->last->prev;
1382 cur->first->prev->to = cur->first;
1383 SplinePointFree(cur->last);
1384 SplineRefigure(cur->first->prev);
1385 cur->last = cur->first;
1386 }
1387 }
1388 x = strtod((char *) path,&end);
1389 end = skipcomma(end);
1390 y = strtod(end,&end);
1391 if ( type=='m' ) {
1392 x += current.x; y += current.y;
1393 }
1394 sp = SplinePointCreate(x,y);
1395 current = sp->me;
1396 cur = chunkalloc(sizeof(SplineSet));
1397 if ( head==NULL )
1398 head = cur;
1399 else
1400 last->next = cur;
1401 last = cur;
1402 cur->first = cur->last = sp;
1403 /* If you omit a command after a moveto then it defaults to lineto */
1404 if ( type=='m' ) type='l';
1405 else type = 'L';
1406 } else if ( type=='z' || type=='Z' ) {
1407 if ( cur!=NULL && cur->last!=cur->first ) {
1408 if ( RealNear(cur->last->me.x,cur->first->me.x) &&
1409 RealNear(cur->last->me.y,cur->first->me.y) ) {
1410 cur->first->prevcp = cur->last->prevcp;
1411 cur->first->prev = cur->last->prev;
1412 cur->first->prev->to = cur->first;
1413 SplineRefigure(cur->first->prev);
1414 SplinePointFree(cur->last);
1415 } else
1416 SplineMake(cur->last,cur->first,order2);
1417 cur->last = cur->first;
1418 current = cur->first->me;
1419 }
1420 type = ' ';
1421 end = (char *) path;
1422 } else {
1423 if ( cur==NULL ) {
1424 sp = SplinePointCreate(current.x,current.y);
1425 cur = chunkalloc(sizeof(SplineSet));
1426 if ( head==NULL )
1427 head = cur;
1428 else
1429 last->next = cur;
1430 last = cur;
1431 cur->first = cur->last = sp;
1432 }
1433 switch ( type ) {
1434 case 'l': case'L':
1435 x = strtod((char *) path,&end);
1436 end = skipcomma(end);
1437 y = strtod(end,&end);
1438 if ( type=='l' ) {
1439 x += current.x; y += current.y;
1440 }
1441 sp = SplinePointCreate(x,y);
1442 current = sp->me;
1443 SplineMake(cur->last,sp,order2);
1444 cur->last = sp;
1445 break;
1446 case 'h': case'H':
1447 x = strtod((char *) path,&end);
1448 y = current.y;
1449 if ( type=='h' ) {
1450 x += current.x;
1451 }
1452 sp = SplinePointCreate(x,y);
1453 current = sp->me;
1454 SplineMake(cur->last,sp,order2);
1455 cur->last = sp;
1456 break;
1457 case 'v': case 'V':
1458 x = current.x;
1459 y = strtod((char *) path,&end);
1460 if ( type=='v' ) {
1461 y += current.y;
1462 }
1463 sp = SplinePointCreate(x,y);
1464 current = sp->me;
1465 SplineMake(cur->last,sp,order2);
1466 cur->last = sp;
1467 break;
1468 case 'c': case 'C':
1469 x1 = strtod((char *) path,&end);
1470 end = skipcomma(end);
1471 y1 = strtod(end,&end);
1472 end = skipcomma(end);
1473 x2 = strtod(end,&end);
1474 end = skipcomma(end);
1475 y2 = strtod(end,&end);
1476 end = skipcomma(end);
1477 x = strtod(end,&end);
1478 end = skipcomma(end);
1479 y = strtod(end,&end);
1480 if ( type=='c' ) {
1481 x1 += current.x; y1 += current.y;
1482 x2 += current.x; y2 += current.y;
1483 x += current.x; y += current.y;
1484 }
1485 sp = SplinePointCreate(x,y);
1486 sp->prevcp.x = x2; sp->prevcp.y = y2;
1487 cur->last->nextcp.x = x1; cur->last->nextcp.y = y1;
1488 current = sp->me;
1489 SplineMake(cur->last,sp,false);
1490 cur->last = sp;
1491 break;
1492 case 's': case 'S':
1493 x1 = 2*cur->last->me.x - cur->last->prevcp.x;
1494 y1 = 2*cur->last->me.y - cur->last->prevcp.y;
1495 x2 = strtod((char *) path,&end);
1496 end = skipcomma(end);
1497 y2 = strtod(end,&end);
1498 end = skipcomma(end);
1499 x = strtod(end,&end);
1500 end = skipcomma(end);
1501 y = strtod(end,&end);
1502 if ( type=='s' ) {
1503 x2 += current.x; y2 += current.y;
1504 x += current.x; y += current.y;
1505 }
1506 sp = SplinePointCreate(x,y);
1507 sp->prevcp.x = x2; sp->prevcp.y = y2;
1508 cur->last->nextcp.x = x1; cur->last->nextcp.y = y1;
1509 current = sp->me;
1510 SplineMake(cur->last,sp,false);
1511 cur->last = sp;
1512 break;
1513 case 'Q': case 'q':
1514 x1 = strtod((char *) path,&end);
1515 end = skipcomma(end);
1516 y1 = strtod(end,&end);
1517 end = skipcomma(end);
1518 x = strtod(end,&end);
1519 end = skipcomma(end);
1520 y = strtod(end,&end);
1521 if ( type=='q' ) {
1522 x1 += current.x; y1 += current.y;
1523 x += current.x; y += current.y;
1524 }
1525 sp = SplinePointCreate(x,y);
1526 sp->prevcp.x = x1; sp->prevcp.y = y1;
1527 cur->last->nextcp.x = x1; cur->last->nextcp.y = y1;
1528 current = sp->me;
1529 SplineMake(cur->last,sp,true);
1530 cur->last = sp;
1531 order2 = true;
1532 break;
1533 case 'T': case 't':
1534 x = strtod((char *) path,&end);
1535 end = skipcomma(end);
1536 y = strtod(end,&end);
1537 if ( type=='t' ) {
1538 x += current.x; y += current.y;
1539 }
1540 x1 = 2*cur->last->me.x - cur->last->prevcp.x;
1541 y1 = 2*cur->last->me.y - cur->last->prevcp.y;
1542 sp = SplinePointCreate(x,y);
1543 sp->prevcp.x = x1; sp->prevcp.y = y1;
1544 cur->last->nextcp.x = x1; cur->last->nextcp.y = y1;
1545 current = sp->me;
1546 SplineMake(cur->last,sp,true);
1547 cur->last = sp;
1548 order2 = true;
1549 break;
1550 case 'A': case 'a':
1551 rx = strtod((char *) path,&end);
1552 end = skipcomma(end);
1553 ry = strtod(end,&end);
1554 end = skipcomma(end);
1555 axisrot = strtod(end,&end)*FF_PI/180;
1556 end = skipcomma(end);
1557 while (isspace(*end)) ++end;
1558 large_arc = *end != '0';
1559 end++;
1560 end = skipcomma(end);
1561 while (isspace(*end)) ++end;
1562 sweep = *end != '0';
1563 end++;
1564 end = skipcomma(end);
1565 x = strtod(end,&end);
1566 end = skipcomma(end);
1567 y = strtod(end,&end);
1568 if ( type=='a' ) {
1569 x += current.x; y += current.y;
1570 }
1571 if ( x!=current.x || y!=current.y )
1572 SVGTraceArc(cur,&current,x,y,rx,ry,axisrot,large_arc,sweep);
1573 break;
1574 default:
1575 LogError( _("Unknown type '%c' found in path specification"), type );
1576 break;
1577 }
1578 }
1579 path = (xmlChar *) skipcomma(end);
1580 }
1581 return( head );
1582 }
1583
1584 static SplineSet *SVGParseExtendedPath(xmlNodePtr svg, xmlNodePtr top) {
1585 /* Inkscape exends paths by allowing a sprio representation */
1586 /* But their representation looks nothing like spiros and I can't guess at it */
1587 xmlChar *outline/*, *effect, *spirooutline*/;
1588 SplineSet *head = NULL;
1589
1590 outline = xmlGetProp(svg,(xmlChar *) "d");
1591 if ( outline!=NULL ) {
1592 head = SVGParsePath(outline);
1593 xmlFree(outline);
1594 }
1595 return( head );
1596 }
1597
1598 static SplineSet *SVGParseRect(xmlNodePtr rect) {
1599 /* x,y,width,height,rx,ry */
1600 double x,y,width,height,rx,ry;
1601 char *num;
1602 SplinePoint *sp;
1603 SplineSet *cur;
1604
1605 num = (char *) xmlGetProp(rect,(xmlChar *) "x");
1606 if ( num!=NULL ) {
1607 x = strtod((char *) num,NULL);
1608 xmlFree(num);
1609 } else
1610 x = 0;
1611 num = (char *) xmlGetProp(rect,(xmlChar *) "width");
1612 if ( num!=NULL ) {
1613 width = strtod((char *) num,NULL);
1614 xmlFree(num);
1615 } else
1616 return( NULL );
1617 num = (char *) xmlGetProp(rect,(xmlChar *) "y");
1618 if ( num!=NULL ) {
1619 y = strtod((char *) num,NULL);
1620 xmlFree(num);
1621 } else
1622 y = 0;
1623 num = (char *) xmlGetProp(rect,(xmlChar *) "height");
1624 if ( num!=NULL ) {
1625 height = strtod((char *) num,NULL);
1626 xmlFree(num);
1627 } else
1628 return( NULL );
1629
1630 rx = ry = 0;
1631 num = (char *) xmlGetProp(rect,(xmlChar *) "rx");
1632 if ( num!=NULL ) {
1633 ry = rx = strtod((char *) num,NULL);
1634 xmlFree(num);
1635 }
1636 num = (char *) xmlGetProp(rect,(xmlChar *) "ry");
1637 if ( num!=NULL ) {
1638 ry = strtod((char *) num,NULL);
1639 if ( rx==0 ) ry = rx;
1640 xmlFree(num);
1641 }
1642
1643 if ( 2*rx>width ) rx = width/2;
1644 if ( 2*ry>height ) ry = height/2;
1645
1646 cur = chunkalloc(sizeof(SplineSet));
1647 if ( rx==0 ) {
1648 cur->first = SplinePointCreate(x,y+height);
1649 cur->last = SplinePointCreate(x+width,y+height);
1650 SplineMake(cur->first,cur->last,true);
1651 sp = SplinePointCreate(x+width,y);
1652 SplineMake(cur->last,sp,true);
1653 cur->last = sp;
1654 sp = SplinePointCreate(x,y);
1655 SplineMake(cur->last,sp,true);
1656 SplineMake(sp,cur->first,true);
1657 cur->last = cur->first;
1658 return( cur );
1659 } else {
1660 cur->first = SplinePointCreate(x,y+height-ry);
1661 cur->last = SplinePointCreate(x+rx,y+height);
1662 cur->first->nextcp.x = x; cur->first->nextcp.y = y+height;
1663 cur->last->prevcp = cur->first->nextcp;
1664 SplineMake(cur->first,cur->last,false);
1665 if ( rx<2*width ) {
1666 sp = SplinePointCreate(x+width-rx,y+height);
1667 SplineMake(cur->last,sp,true);
1668 cur->last = sp;
1669 }
1670 sp = SplinePointCreate(x+width,y+height-ry);
1671 sp->prevcp.x = x+width; sp->prevcp.y = y+height;
1672 cur->last->nextcp = sp->prevcp;
1673 SplineMake(cur->last,sp,false);
1674 cur->last = sp;
1675 if ( ry<2*height ) {
1676 sp = SplinePointCreate(x+width,y+ry);
1677 SplineMake(cur->last,sp,false);
1678 cur->last = sp;
1679 }
1680 sp = SplinePointCreate(x+width-rx,y);
1681 sp->prevcp.x = x+width; sp->prevcp.y = y;
1682 cur->last->nextcp = sp->prevcp;
1683 SplineMake(cur->last,sp,false);
1684 cur->last = sp;
1685 if ( rx<2*width ) {
1686 sp = SplinePointCreate(x+rx,y);
1687 SplineMake(cur->last,sp,false);
1688 cur->last = sp;
1689 }
1690 cur->last->nextcp.x = x; cur->last->nextcp.y = y;
1691 if ( ry>=2*height ) {
1692 cur->first->prevcp = cur->last->nextcp;
1693 } else {
1694 sp = SplinePointCreate(x,y+ry);
1695 sp->prevcp = cur->last->nextcp;
1696 SplineMake(cur->last,sp,false);
1697 cur->last = sp;
1698 }
1699 SplineMake(cur->last,cur->first,false);
1700 cur->first = cur->last;
1701 return( cur );
1702 }
1703 }
1704
1705 static SplineSet *SVGParseLine(xmlNodePtr line) {
1706 /* x1,y1, x2,y2 */
1707 double x,y, x2,y2;
1708 char *num;
1709 SplinePoint *sp1, *sp2;
1710 SplineSet *cur;
1711
1712 num = (char *) xmlGetProp(line,(xmlChar *) "x1");
1713 if ( num!=NULL ) {
1714 x = strtod((char *) num,NULL);
1715 xmlFree(num);
1716 } else
1717 x = 0;
1718 num = (char *) xmlGetProp(line,(xmlChar *) "x2");
1719 if ( num!=NULL ) {
1720 x2 = strtod((char *) num,NULL);
1721 xmlFree(num);
1722 } else
1723 x2 = 0;
1724 num = (char *) xmlGetProp(line,(xmlChar *) "y1");
1725 if ( num!=NULL ) {
1726 y = strtod((char *) num,NULL);
1727 xmlFree(num);
1728 } else
1729 y = 0;
1730 num = (char *) xmlGetProp(line,(xmlChar *) "y2");
1731 if ( num!=NULL ) {
1732 y2 = strtod((char *) num,NULL);
1733 xmlFree(num);
1734 } else
1735 y2 = 0;
1736
1737 sp1 = SplinePointCreate(x,y);
1738 sp2 = SplinePointCreate(x2,y2);
1739 SplineMake(sp1,sp2,false);
1740 cur = chunkalloc(sizeof(SplineSet));
1741 cur->first = sp1;
1742 cur->last = sp2;
1743 return( cur );
1744 }
1745
1746 static SplineSet *SVGParseEllipse(xmlNodePtr ellipse, int iscircle) {
1747 /* cx,cy,rx,ry */
1748 /* cx,cy,r */
1749 double cx,cy,rx,ry;
1750 char *num;
1751 SplinePoint *sp;
1752 SplineSet *cur;
1753
1754 num = (char *) xmlGetProp(ellipse,(xmlChar *) "cx");
1755 if ( num!=NULL ) {
1756 cx = strtod((char *) num,NULL);
1757 xmlFree(num);
1758 } else
1759 cx = 0;
1760 num = (char *) xmlGetProp(ellipse,(xmlChar *) "cy");
1761 if ( num!=NULL ) {
1762 cy = strtod((char *) num,NULL);
1763 xmlFree(num);
1764 } else
1765 cy = 0;
1766 if ( iscircle ) {
1767 num = (char *) xmlGetProp(ellipse,(xmlChar *) "r");
1768 if ( num!=NULL ) {
1769 rx = ry = strtod((char *) num,NULL);
1770 xmlFree(num);
1771 } else
1772 return( NULL );
1773 } else {
1774 num = (char *) xmlGetProp(ellipse,(xmlChar *) "rx");
1775 if ( num!=NULL ) {
1776 rx = strtod((char *) num,NULL);
1777 xmlFree(num);
1778 } else
1779 return( NULL );
1780 num = (char *) xmlGetProp(ellipse,(xmlChar *) "ry");
1781 if ( num!=NULL ) {
1782 ry = strtod((char *) num,NULL);
1783 xmlFree(num);
1784 } else
1785 return( NULL );
1786 }
1787 if ( rx<0 ) rx = -rx;
1788 if ( ry<0 ) ry = -ry;
1789
1790 /* a magic number to make cubic beziers approximate ellipses */
1791 /* 4/3 * ( sqrt(2) - 1 ) = 0.55228... */
1792 /* also 4/3 * tan(t/4) where t = 90 b/c we do 4 curves */
1793 double magic = 0.5522847498307933984022516322796;
1794 /* offset from on-curve point to control points */
1795 double drx = rx * magic;
1796 double dry = ry * magic;
1797 cur = chunkalloc(sizeof(SplineSet));
1798 cur->first = SplinePointCreate(cx-rx,cy);
1799 cur->first->nextcp.x = cx-rx; cur->first->nextcp.y = cy+dry;
1800 cur->first->prevcp.x = cx-rx; cur->first->prevcp.y = cy-dry;
1801 cur->last = SplinePointCreate(cx,cy+ry);
1802 cur->last->prevcp.x = cx-drx; cur->last->prevcp.y = cy+ry;
1803 cur->last->nextcp.x = cx+drx; cur->last->nextcp.y = cy+ry;
1804 SplineMake(cur->first,cur->last,false);
1805 sp = SplinePointCreate(cx+rx,cy);
1806 sp->prevcp.x = cx+rx; sp->prevcp.y = cy+dry;
1807 sp->nextcp.x = cx+rx; sp->nextcp.y = cy-dry;
1808 SplineMake(cur->last,sp,false);
1809 cur->last = sp;
1810 sp = SplinePointCreate(cx,cy-ry);
1811 sp->prevcp.x = cx+drx; sp->prevcp.y = cy-ry;
1812 sp->nextcp.x = cx-drx; sp->nextcp.y = cy-ry;
1813 SplineMake(cur->last,sp,false);
1814 SplineMake(sp,cur->first,false);
1815 cur->last = cur->first;
1816 return( cur );
1817 }
1818
1819 static SplineSet *SVGParsePoly(xmlNodePtr poly, int isgon) {
1820 /* points */
1821 double x,y;
1822 char *pts, *end;
1823 SplinePoint *sp;
1824 SplineSet *cur;
1825
1826 pts = (char *) xmlGetProp(poly,(xmlChar *) "points");
1827 if ( pts==NULL )
1828 return( NULL );
1829
1830 x = strtod(pts,&end);
1831 while ( isspace(*end) || *end==',' ) ++end;
1832 y = strtod(end,&end);
1833 while ( isspace(*end)) ++end;
1834
1835 cur = chunkalloc(sizeof(SplineSet));
1836 cur->first = cur->last = SplinePointCreate(x,y);
1837 while ( *end ) {
1838 x = strtod(end,&end);
1839 while ( isspace(*end) || *end==',' ) ++end;
1840 y = strtod(end,&end);
1841 while ( isspace(*end)) ++end;
1842 sp = SplinePointCreate(x,y);
1843 SplineMake(cur->last,sp,false);
1844 cur->last = sp;
1845 }
1846 if ( isgon ) {
1847 if ( RealNear(cur->last->me.x,cur->first->me.x) &&
1848 RealNear(cur->last->me.y,cur->first->me.y) ) {
1849 cur->first->prev = cur->last->prev;
1850 cur->first->prev->to = cur->first;
1851 SplinePointFree(cur->last);
1852 } else
1853 SplineMake(cur->last,cur->first,false);
1854 cur->last = cur->first;
1855 }
1856 return( cur );
1857 }
1858
1859 struct svg_state {
1860 double linewidth;
1861 double miterlimit;
1862 int dofill, dostroke;
1863 uint32_t fillcol, strokecol;
1864 float fillopacity, strokeopacity;
1865 int isvisible;
1866 enum linecap lc;
1867 enum linejoin lj;
1868 real transform[6];
1869 DashType dashes[DASH_MAX];
1870 SplineSet *clippath;
1871 uint8_t free_clip;
1872 uint32_t currentColor;
1873 uint32_t stopColor;
1874 float stopOpacity;
1875 };
1876
1877 static void SVGFigureTransform(struct svg_state *st,char *name) {
1878 real trans[6], res[6];
1879 double a, cx,cy;
1880 char *pt, *paren, *end;
1881 /* matrix(a,b,c,d,e,f)
1882 rotate(theta[,cx,cy])
1883 scale(sx[,sy])
1884 translate(x,y)
1885 skewX(theta)
1886 skewY(theta)
1887 */
1888
1889 for ( pt = (char *)name; isspace(*pt); ++pt );
1890 while ( *pt ) {
1891 paren = strchr(pt,'(');
1892 if ( paren==NULL )
1893 break;
1894 if ( strncmp(pt,"matrix",paren-pt)==0 ) {
1895 trans[0] = strtod(paren+1,&end);
1896 trans[1] = strtod(skipcomma(end),&end);
1897 trans[2] = strtod(skipcomma(end),&end);
1898 trans[3] = strtod(skipcomma(end),&end);
1899 trans[4] = strtod(skipcomma(end),&end);
1900 trans[5] = strtod(skipcomma(end),&end);
1901 } else if ( strncmp(pt,"rotate",paren-pt)==0 ) {
1902 trans[4] = trans[5] = 0;
1903 a = strtod(paren+1,&end)*FF_PI/180;
1904 trans[0] = trans[3] = cos(a);
1905 trans[1] = sin(a);
1906 trans[2] = -trans[1];
1907 while ( isspace(*end)) ++end;
1908 if ( *end!=')' ) {
1909 cx = strtod(skipcomma(end),&end);
1910 cy = strtod(skipcomma(end),&end);
1911 res[0] = res[3] = 1;
1912 res[1] = res[2] = 0;
1913 res[4] = cx; res[5] = cy;
1914 MatMultiply(res,trans,res);
1915 trans[0] = trans[3] = 1;
1916 trans[1] = trans[2] = 0;
1917 trans[4] = -cx; trans[5] = -cy;
1918 MatMultiply(res,trans,res);
1919 memcpy(trans,res,sizeof(res));
1920 }
1921 } else if ( strncmp(pt,"scale",paren-pt)==0 ) {
1922 trans[1] = trans[2] = trans[4] = trans[5] = 0;
1923 trans[0] = trans[3] = strtod(paren+1,&end);
1924 while ( isspace(*end)) ++end;
1925 if ( *end!=')' )
1926 trans[3] = strtod(skipcomma(end),&end);
1927 } else if ( strncmp(pt,"translate",paren-pt)==0 ) {
1928 trans[0] = trans[3] = 1;
1929 trans[1] = trans[2] = trans[5] = 0;
1930 trans[4] = strtod(paren+1,&end);
1931 while ( isspace(*end)) ++end;
1932 if ( *end!=')' )
1933 trans[5] = strtod(skipcomma(end),&end);
1934 } else if ( strncmp(pt,"skewX",paren-pt)==0 ) {
1935 trans[0] = trans[3] = 1;
1936 trans[1] = trans[2] = trans[4] = trans[5] = 0;
1937 trans[2] = tan(strtod(paren+1,&end)*FF_PI/180);
1938 } else if ( strncmp(pt,"skewY",paren-pt)==0 ) {
1939 trans[0] = trans[3] = 1;
1940 trans[1] = trans[2] = trans[4] = trans[5] = 0;
1941 trans[1] = tan(strtod(paren+1,&end)*FF_PI/180);
1942 } else
1943 break;
1944 while ( isspace(*end)) ++end;
1945 if ( *end!=')')
1946 break;
1947 MatMultiply(trans,st->transform,st->transform);
1948 pt = end+1;
1949 while ( isspace(*pt)) ++pt;
1950 }
1951 }
1952
1953 static void SVGuseTransform(struct svg_state *st,xmlNodePtr use, xmlNodePtr symbol) {
1954 double x,y,uwid,uheight,swid,sheight;
1955 char *num, *end;
1956 real trans[6];
1957
1958 num = (char *) xmlGetProp(use,(xmlChar *) "x");
1959 if ( num!=NULL ) {
1960 x = strtod((char *) num,NULL);
1961 xmlFree(num);
1962 } else
1963 x = 0;
1964 num = (char *) xmlGetProp(use,(xmlChar *) "y");
1965 if ( num!=NULL ) {
1966 y = strtod((char *) num,NULL);
1967 xmlFree(num);
1968 } else
1969 y = 0;
1970 if ( x!=0 || y!=0 ) {
1971 trans[0] = trans[3] = 1;
1972 trans[1] = trans[2] = 0;
1973 trans[4] = x; trans[5] = y;
1974 MatMultiply(trans,st->transform,st->transform);
1975 }
1976 num = (char *) xmlGetProp(use,(xmlChar *) "width");
1977 if ( num!=NULL ) {
1978 uwid = strtod((char *) num,NULL);
1979 xmlFree(num);
1980 } else
1981 uwid = 0;
1982 num = (char *) xmlGetProp(use,(xmlChar *) "height");
1983 if ( num!=NULL ) {
1984 uheight = strtod((char *) num,NULL);
1985 xmlFree(num);
1986 } else
1987 uheight = 0;
1988 num = (char *) xmlGetProp(symbol,(xmlChar *) "viewBox");
1989 if ( num!=NULL ) {
1990 x = strtod((char *) num,&end);
1991 y = strtod((char *) end+1,&end);
1992 swid = strtod((char *) end+1,&end);
1993 sheight = strtod((char *) end+1,&end);
1994 xmlFree(num);
1995 } else
1996 return;
1997 if ( uwid != 0 || uheight != 0 ) {
1998 trans[0] = trans[3] = 1;
1999 trans[1] = trans[2] = trans[4] = trans[5] = 0;
2000 if ( uwid != 0 && swid!=0 ) trans[0] = uwid/swid;
2001 if ( uheight != 0 && sheight!=0 ) trans[3] = uheight/sheight;
2002 MatMultiply(trans,st->transform,st->transform);
2003 }
2004 }
2005
2006 static real parseGCoord(xmlChar *prop,int bb_units,real bb_low, real bb_high) {
2007 char *end;
2008 double val = strtod((char *) prop,&end);
2009
2010 if ( *end=='%' )
2011 val /= 100.0;
2012
2013 if ( bb_units )
2014 val = bb_low + val*(bb_high-bb_low);
2015 return( val );
2016 }
2017
2018 static int xmlParseColor(xmlChar *name,uint32_t *color, char **url,struct svg_state *st);
2019
2020 static void xmlParseColorSource(xmlNodePtr top,char *name,DBounds *bbox,
2021 struct svg_state *st,struct gradient **_grad,struct epattern **_epat) {
2022 xmlNodePtr colour_source = XmlFindURI(top,name);
2023 int islinear;
2024 xmlChar *prop;
2025 xmlNodePtr kid;
2026 int scnt;
2027
2028 *_grad = NULL; *_epat = NULL;
2029 if ( colour_source==NULL )
2030 LogError(_("Could not find Color Source with id %s."), name );
2031 else if ( (islinear = (xmlStrcmp(colour_source->name,(xmlChar *) "linearGradient")==0)) ||
2032 xmlStrcmp(colour_source->name,(xmlChar *) "radialGradient")==0 ) {
2033 struct gradient *grad = chunkalloc(sizeof(struct gradient));
2034 int bbox_units;
2035 *_grad = grad;
2036
2037 prop = xmlGetProp(colour_source,(xmlChar *) "gradientUnits");
2038 if ( prop!=NULL ) {
2039 bbox_units = xmlStrcmp(prop,(xmlChar *) "userSpaceOnUse")!=0;
2040 xmlFree(prop);
2041 } else
2042 bbox_units = true;
2043
2044 prop = xmlGetProp(colour_source,(xmlChar *) "gradientTransform");
2045 /* I don't support this currently */
2046 if ( prop!=NULL )
2047 xmlFree(prop);
2048
2049 grad->sm = sm_pad;
2050 prop = xmlGetProp(colour_source,(xmlChar *) "spreadMethod");
2051 if ( prop!=NULL ) {
2052 if ( xmlStrcmp(prop,(xmlChar *) "reflect")==0 )
2053 grad->sm = sm_reflect;
2054 else if ( xmlStrcmp(prop,(xmlChar *) "repeat")==0 )
2055 grad->sm = sm_repeat;
2056 xmlFree(prop);
2057 }
2058
2059 if ( islinear ) {
2060 grad->start.x = bbox->minx; grad->start.y = bbox->miny;
2061 grad->stop.x = bbox->maxx; grad->stop.y = bbox->maxy;
2062
2063 prop = xmlGetProp(colour_source,(xmlChar *) "x1");
2064 if ( prop!=NULL ) {
2065 grad->start.x = parseGCoord( prop,bbox_units,bbox->minx,bbox->maxx);
2066 xmlFree(prop);
2067 }
2068
2069 prop = xmlGetProp(colour_source,(xmlChar *) "x2");
2070 if ( prop!=NULL ) {
2071 grad->stop.x = parseGCoord( prop,bbox_units,bbox->minx,bbox->maxx);
2072 xmlFree(prop);
2073 }
2074
2075 prop = xmlGetProp(colour_source,(xmlChar *) "y1");
2076 if ( prop!=NULL ) {
2077 grad->start.y = parseGCoord( prop,bbox_units,bbox->miny,bbox->maxy);
2078 xmlFree(prop);
2079 }
2080
2081 prop = xmlGetProp(colour_source,(xmlChar *) "y2");
2082 if ( prop!=NULL ) {
2083 grad->stop.y = parseGCoord( prop,bbox_units,bbox->miny,bbox->maxy);
2084 xmlFree(prop);
2085 }
2086
2087 grad->radius = 0;
2088 } else {
2089 double offx = (bbox->maxx-bbox->minx)/2;
2090 double offy = (bbox->maxy-bbox->miny)/2;
2091 grad->stop.x = (bbox->minx+bbox->maxx)/2;
2092 grad->stop.y = (bbox->minx+bbox->maxy)/2;
2093 grad->radius = sqrt(offx*offx + offy*offy);
2094
2095 prop = xmlGetProp(colour_source,(xmlChar *) "cx");
2096 if ( prop!=NULL ) {
2097 grad->stop.x = parseGCoord( prop,bbox_units,bbox->minx,bbox->maxx);
2098 xmlFree(prop);
2099 }
2100
2101 prop = xmlGetProp(colour_source,(xmlChar *) "cy");
2102 if ( prop!=NULL ) {
2103 grad->stop.y = parseGCoord( prop,bbox_units,bbox->miny,bbox->maxy);
2104 xmlFree(prop);
2105 }
2106
2107 prop = xmlGetProp(colour_source,(xmlChar *) "radius");
2108 if ( prop!=NULL ) {
2109 grad->radius = parseGCoord( prop,bbox_units,0,sqrt(4*(offx*offx + offy*offy)));
2110 xmlFree(prop);
2111 }
2112
2113 grad->start = grad->stop;
2114 prop = xmlGetProp(colour_source,(xmlChar *) "fx");
2115 if ( prop!=NULL ) {
2116 grad->start.x = parseGCoord( prop,bbox_units,bbox->minx,bbox->maxx);
2117 xmlFree(prop);
2118 }
2119
2120 prop = xmlGetProp(colour_source,(xmlChar *) "fy");
2121 if ( prop!=NULL ) {
2122 grad->start.y = parseGCoord( prop,bbox_units,bbox->miny,bbox->maxy);
2123 xmlFree(prop);
2124 }
2125 }
2126
2127 scnt = 0;
2128 for ( kid = colour_source->children; kid!=NULL; kid=kid->next ) if ( xmlStrcmp(kid->name,(xmlChar *) "stop")==0 )
2129 ++scnt;
2130
2131 if ( scnt==0 ) {
2132 /* I'm not sure how to use the style stop-color, but I'm guessing */
2133 /* this might be it */
2134 grad->stop_cnt = 1;
2135 grad->grad_stops = calloc(1,sizeof(struct grad_stops));
2136 grad->grad_stops[scnt].offset = 1;
2137 grad->grad_stops[scnt].col = st->stopColor;
2138 grad->grad_stops[scnt].opacity = st->stopOpacity;
2139 ++scnt;
2140 } else {
2141 grad->stop_cnt = scnt;
2142 grad->grad_stops = calloc(scnt,sizeof(struct grad_stops));
2143 scnt = 0;
2144 for ( kid = colour_source->children; kid!=NULL; kid=kid->next ) if ( xmlStrcmp(kid->name,(xmlChar *) "stop")==0 ) {
2145 grad->grad_stops[scnt].col = st->stopColor;
2146 grad->grad_stops[scnt].opacity = st->stopOpacity;
2147
2148 prop = xmlGetProp(kid,(xmlChar *) "offset");
2149 if ( prop!=NULL ) {
2150 grad->grad_stops[scnt].offset = parseGCoord( prop,false,0,1.0);
2151 xmlFree(prop);
2152 }
2153
2154 prop = xmlGetProp(kid,(xmlChar *) "stop-color");
2155 if ( prop!=NULL ) {
2156 xmlParseColor(BAD_CAST prop, &grad->grad_stops[scnt].col, NULL, st);
2157 xmlFree(prop);
2158 }
2159
2160 prop = xmlGetProp(kid,(xmlChar *) "stop-opacity");
2161 if ( prop!=NULL ) {
2162 grad->grad_stops[scnt].opacity = strtod((char *) prop,NULL);
2163 xmlFree(prop);
2164 } else
2165 grad->grad_stops[scnt].opacity = 1.0;
2166
2167 ++scnt;
2168 }
2169 }
2170 } else if ( xmlStrcmp(colour_source->name,(xmlChar *) "pattern")==0 ) {
2171 LogError(_("FontForge does not currently parse pattern Color Sources (%s)."),
2172 name );
2173 } else {
2174 LogError(_("Color Source with id %s had an unexpected type %s."),
2175 name, (char *) colour_source->name );
2176 }
2177 }
2178
2179 /* Annoyingly we can't parse the colour source until we have parsed the contents */
2180 /* because the colour source needs to know the bounding box of the total item */
2181 /* This means that for something like <g> we must now go back and figure out */
2182 /* which components get this gradient/pattern, and which have their own source*/
2183 /* that overrides the inherited one */
2184 static void xmlApplyColourSources(xmlNodePtr top,Entity *head,
2185 struct svg_state *st,
2186 char *fill_colour_source,char *stroke_colour_source) {
2187 DBounds b, ssb;
2188 Entity *e;
2189 struct gradient *grad;
2190 struct epattern *epat;
2191
2192 memset(&b,0,sizeof(b));
2193 for ( e=head; e!=NULL; e=e->next ) if ( e->type==et_splines ) {
2194 SplineSetFindBounds(e->u.splines.splines,&ssb);
2195 if ( b.minx==0 && b.miny==0 && b.maxx==0 && b.maxy==0 )
2196 b = ssb;
2197 else {
2198 if ( b.minx>ssb.minx ) b.minx = ssb.minx;
2199 if ( b.maxx>ssb.maxx ) b.maxx = ssb.maxx;
2200 if ( b.miny>ssb.miny ) b.miny = ssb.miny;
2201 if ( b.maxy>ssb.maxy ) b.maxy = ssb.maxy;
2202 }
2203 }
2204 if ( b.minx==b.maxx ) b.maxx = b.minx+1;
2205 if ( b.miny==b.maxy ) b.maxy = b.maxy+1;
2206
2207 if ( fill_colour_source!=NULL ) {
2208 xmlParseColorSource(top,fill_colour_source,&b,st,&grad,&epat);
2209 free(fill_colour_source);
2210 for ( e=head; e!=NULL; e=e->next ) if ( e->type==et_splines ) {
2211 if ( e->u.splines.fill.grad==NULL && e->u.splines.fill.tile==NULL &&
2212 e->u.splines.fill.col == COLOR_INHERITED ) {
2213 e->u.splines.fill.grad = GradientCopy(grad,NULL);
2214 /*e->u.splines.fill.tile = EPatternCopy(epat,NULL);*/
2215 }
2216 }
2217 GradientFree(grad);
2218 /*EPatternFree(epat);*/
2219 }
2220
2221 if ( stroke_colour_source!=NULL ) {
2222 xmlParseColorSource(top,stroke_colour_source,&b,st,&grad,&epat);
2223 free(stroke_colour_source);
2224 for ( e=head; e!=NULL; e=e->next ) if ( e->type==et_splines ) {
2225 if ( e->u.splines.stroke.grad==NULL && e->u.splines.stroke.tile==NULL &&
2226 e->u.splines.stroke.col == COLOR_INHERITED ) {
2227 e->u.splines.stroke.grad = GradientCopy(grad,NULL);
2228 /*e->u.splines.stroke.tile = EPatternCopy(epat,NULL);*/
2229 }
2230 }
2231 GradientFree(grad);
2232 /*EPatternFree(epat);*/
2233 }
2234 }
2235
2236 static int xmlParseColor(xmlChar *name,uint32_t *color, char **url,struct svg_state *st) {
2237 int doit, i;
2238 static struct { char *name; uint32_t col; } stdcols[] = {
2239 { "red", 0xff0000 },
2240 { "green", 0x008000 },
2241 { "blue", 0x0000ff },
2242 { "cyan", 0x00ffff },
2243 { "magenta", 0xff00ff },
2244 { "yellow", 0xffff00 },
2245 { "black", 0x000000 },
2246 { "darkgray", 0x404040 },
2247 { "darkgrey", 0x404040 },
2248 { "gray", 0x808080 },
2249 { "grey", 0x808080 },
2250 { "lightgray", 0xc0c0c0 },
2251 { "lightgrey", 0xc0c0c0 },
2252 { "white", 0xffffff },
2253 { "maroon", 0x800000 },
2254 { "olive", 0x808000 },
2255 { "navy", 0x000080 },
2256 { "purple", 0x800080 },
2257 { "lime", 0x00ff00 },
2258 { "aqua", 0x00ffff },
2259 { "teal", 0x008080 },
2260 { "fuchsia", 0xff0080 },
2261 { "silver", 0xc0c0c0 },
2262 { NULL, 0 }
2263 };
2264
2265 doit = xmlStrcmp(name,(xmlChar *) "none")!=0;
2266 if ( doit ) {
2267 for ( i=0; stdcols[i].name!=NULL; ++i )
2268 if ( xmlStrcmp(name,(xmlChar *) stdcols[i].name)==0 )
2269 break;
2270 if ( stdcols[i].name!=NULL )
2271 *color = stdcols[i].col;
2272 else if ( xmlStrcmp(name,(xmlChar *) "currentColor")==0 )
2273 *color = st->currentColor;
2274 else if ( name[0]=='#' ) {
2275 unsigned int temp=0;
2276 if ( sscanf( (char *) name, "#%x", &temp )!=1 )
2277 LogError( _("Bad hex color spec: %s"), (char *) name );
2278 if ( strlen( (char *) name)==4 ) {
2279 *color = (((temp&0xf00)*0x11)<<8) |
2280 (((temp&0x0f0)*0x11)<<4) |
2281 (((temp&0x00f)*0x11) );
2282 } else if ( strlen( (char *) name)==7 ) {
2283 *color = temp;
2284 } else
2285 *color = COLOR_INHERITED;
2286 } else if ( strncmp( (char *) name, "rgb(",4)==0 ) {
2287 float r=0,g=0,b=0;
2288 if ( sscanf((char *)name + 4, "%g,%g,%g", &r, &g, &b )!=3 )
2289 LogError( _("Bad RGB color spec: %s"), (char *) name );
2290 if ( strchr((char *) name,'.')!=NULL ) {
2291 if ( r>=1 ) r = 1; else if ( r<0 ) r=0;
2292 if ( g>=1 ) g = 1; else if ( g<0 ) g=0;
2293 if ( b>=1 ) b = 1; else if ( b<0 ) b=0;
2294 *color = ( ((int) rint(r*255))<<16 ) |
2295 ( ((int) rint(g*255))<<8 ) |
2296 ( ((int) rint(b*255)) );
2297 } else {
2298 if ( r>=255 ) r = 255; else if ( r<0 ) r=0;
2299 if ( g>=255 ) g = 255; else if ( g<0 ) g=0;
2300 if ( b>=255 ) b = 255; else if ( b<0 ) b=0;
2301 *color = ( ((int) r)<<16 ) |
2302 ( ((int) g)<<8 ) |
2303 ( ((int) b) );
2304 }
2305 } else if ( url!=NULL && strncmp( (char *) name, "url(#",5)==0 ) {
2306 *url = copy( (char *) name);
2307 *color = COLOR_INHERITED;
2308 } else {
2309 LogError( _("Failed to parse color %s"), (char *) name );
2310 *color = COLOR_INHERITED;
2311 }
2312 }
2313 return( doit );
2314 }
2315
2316 static int base64ch(int ch) {
2317 if ( ch>='A' && ch<='Z' )
2318 return( ch-'A' );
2319 if ( ch>='a' && ch<='z' )
2320 return( ch-'a'+26 );
2321 if ( ch>='0' && ch<='9' )
2322 return( ch-'0'+52 );
2323 if ( ch=='+' )
2324 return( 62 );
2325 if ( ch=='/' )
2326 return( 63 );
2327 if ( ch=='=' )
2328 return( 64 );
2329
2330 return( -1 );
2331 }
2332
2333 static void DecodeBase64ToFile(FILE *tmp,char *str) {
2334 char fourchars[4];
2335 int i;
2336
2337 while ( *str ) {
2338 fourchars[0] = fourchars[1] = fourchars[2] = fourchars[3] = 64;
2339 for ( i=0; i<4; ++i ) {
2340 while ( *str!='\0' && ( isspace(*str) || base64ch(*str)==-1 ) ) ++str;
2341 if ( *str=='\0' )
2342 break;
2343 fourchars[i] = base64ch(*str++);
2344 }
2345 if ( fourchars[0]<64 && fourchars[1]<64 ) {
2346 putc((fourchars[0]<<2)|(fourchars[1]>>4), tmp);
2347 if ( fourchars[2]<64 ) {
2348 putc((fourchars[1]<<4)|(fourchars[2]>>2), tmp);
2349 if ( fourchars[3]<64 )
2350 putc((fourchars[2]<<6)|fourchars[3], tmp);
2351 }
2352 }
2353 }
2354 }
2355
2356 static GImage *GImageFromDataURI(char *uri) {
2357 char *mimetype;
2358 int is_base64=false, ch;
2359 FILE *tmp;
2360 GImage *img;
2361
2362 if ( uri==NULL )
2363 return( NULL );
2364 if ( strncmp(uri,"data:",5)!=0 )
2365 return( NULL );
2366 uri += 5;
2367
2368 mimetype = uri;
2369 while ( *uri!=',' && *uri!=';' && *uri!='\0' ) ++uri;
2370 if ( *uri=='\0' )
2371 return( NULL );
2372 ch = *uri;
2373 *uri='\0';
2374 if ( ch==';' && strncmp(uri+1,"base64,",7)==0 ) {
2375 is_base64=true;
2376 uri += 6;
2377 ch = ',';
2378 } else if ( ch==';' ) /* Can't deal with other encoding methods */
2379 return( NULL );
2380
2381 ++uri;
2382 if ( strcmp(mimetype,"image/png")==0 ||
2383 strcmp(mimetype,"image/jpeg")==0 ||
2384 strcmp(mimetype,"image/bmp")==0 )
2385 /* These we support (if we've got the libraries) */;
2386 else {
2387 LogError(_("Unsupported mime type in data URI: %s"), mimetype );
2388 return( NULL );
2389 }
2390 tmp = GFileTmpfile();
2391 if ( is_base64 )
2392 DecodeBase64ToFile(tmp,uri);
2393 else {
2394 while ( *uri ) {
2395 putc(*uri,tmp);
2396 ++uri;
2397 }
2398 }
2399 rewind(tmp);
2400 #ifndef _NO_LIBPNG
2401 if ( strcmp(mimetype,"image/png")==0 )
2402 img = GImageRead_Png(tmp);
2403 else
2404 #endif
2405 #ifndef _NO_LIBJPEG
2406 if ( strcmp(mimetype,"image/jpeg")==0 )
2407 img = GImageRead_Jpeg(tmp);
2408 else
2409 #endif
2410 if ( strcmp(mimetype,"image/bmp")==0 )
2411 img = GImageRead_Bmp(tmp);
2412 else
2413 img = NULL;
2414 fclose(tmp);
2415 return( img );
2416 }
2417
2418 static Entity *SVGParseImage(xmlNodePtr svg) {
2419 double x=0,y=0,width=1,height=1;
2420 GImage *img;
2421 struct _GImage *base;
2422 Entity *ent;
2423 xmlChar *val;
2424
2425 val = xmlGetProp(svg,(xmlChar *) "x");
2426 if ( val!=NULL ) {
2427 x = strtod((char *) val,NULL);
2428 free(val);
2429 }
2430 val = xmlGetProp(svg,(xmlChar *) "y");
2431 if ( val!=NULL ) {
2432 y = strtod((char *) val,NULL);
2433 free(val);
2434 }
2435
2436 val = xmlGetProp(svg,(xmlChar *) "width");
2437 if ( val!=NULL ) {
2438 width = strtod((char *) val,NULL);
2439 free(val);
2440 }
2441 val = xmlGetProp(svg,(xmlChar *) "height");
2442 if ( val!=NULL ) {
2443 height = strtod((char *) val,NULL);
2444 free(val);
2445 }
2446
2447 val = xmlGetProp(svg,(xmlChar *) /*"xlink:href"*/ "href");
2448 if ( val==NULL )
2449 return( NULL );
2450 if ( strncmp((char *) val,"data:",5)!=0 ) {
2451 LogError(_("FontForge only supports embedded images in data: URIs"));
2452 free(val);
2453 return( NULL ); /* I can only handle data URIs */
2454 }
2455 img = GImageFromDataURI((char *) val);
2456 free(val);
2457 if ( img==NULL )
2458 return( NULL );
2459 base = img->list_len==0 ? img->u.image : img->u.images[0];
2460
2461 ent = chunkalloc(sizeof(Entity));
2462 ent->type = et_image;
2463 ent->u.image.image = img;
2464 ent->u.image.transform[1] = ent->u.image.transform[2] = 0;
2465 ent->u.image.transform[0] = width/base->width;
2466 ent->u.image.transform[3] = height/base->height;
2467 ent->u.image.transform[4] = x;
2468 ent->u.image.transform[5] = y;
2469 ent->u.image.col = 0xffffffff;
2470 return( ent );
2471 }
2472
2473 static Entity *EntityCreate(SplinePointList *head,struct svg_state *state) {
2474 Entity *ent = calloc(1,sizeof(Entity));
2475 ent->type = et_splines;
2476 ent->u.splines.splines = head;
2477 ent->u.splines.cap = state->lc;
2478 ent->u.splines.join = state->lj;
2479 ent->u.splines.stroke_width = state->linewidth;
2480 ent->u.splines.miterlimit = state->miterlimit;
2481 ent->u.splines.fill.col = state->dofill ? state->fillcol : state->dostroke ? 0xffffffff : COLOR_INHERITED;
2482 ent->u.splines.stroke.col = state->dostroke ? state->strokecol : 0xffffffff;
2483 ent->u.splines.fill.opacity = state->fillopacity;
2484 ent->u.splines.stroke.opacity = state->strokeopacity;
2485 memcpy(ent->u.splines.transform,state->transform,6*sizeof(real));
2486 ent->clippath = SplinePointListCopy(state->clippath);
2487 return( ent );
2488 }
2489
2490 static void SvgStateFree(struct svg_state *st) {
2491 if ( st->free_clip )
2492 SplinePointListFree(st->clippath);
2493 }
2494
2495 static void SVGFigureStyle(struct svg_state *st,char *name,
2496 char **fill_colour_source,char **stroke_colour_source) {
2497 char *pt;
2498 char namebuf[200], propbuf[400];
2499
2500 for (;;) {
2501 while ( isspace(*name)) ++name;
2502 if ( *name==':' ) {
2503 /* Missing prop name, skip the value */
2504 while ( *name!=';' && *name!='\0' ) ++name;
2505 if ( *name==';' ) ++name;
2506 } else if ( *name!='\0' && *name!=';' ) {
2507 pt = namebuf;
2508 while ( *name!='\0' && *name!=':' && *name!=';' && !isspace(*name) ) {
2509 if ( pt<namebuf+sizeof(namebuf)-1 )
2510 *pt++ = *name;
2511 ++name;
2512 }
2513 *pt = '\0';
2514 while ( *name!=':' && *name!=';' && *name!='\0' ) ++name;
2515 if ( *name==':' ) ++name;
2516
2517 /* fetch prop value */
2518 while ( isspace(*name) ) ++name;
2519 propbuf[0] = '\0';
2520 if ( *name!='\0' && *name!=';' ) {
2521 pt = propbuf;
2522 while ( *name!='\0' && *name!=';' && !isspace(*name) ) {
2523 if ( pt<propbuf+sizeof(propbuf)-1 )
2524 *pt++ = *name;
2525 ++name;
2526 }
2527 *pt = '\0';
2528 }
2529 while ( *name!=';' && *name!='\0' ) ++name;
2530 if ( *name==';' ) ++name;
2531
2532 if ( strcmp(namebuf,"color")==0 )
2533 xmlParseColor(BAD_CAST propbuf,&st->currentColor,NULL,st);
2534 else if ( strcmp(namebuf,"fill")==0 )
2535 st->dofill = xmlParseColor(BAD_CAST propbuf,&st->fillcol,fill_colour_source,st);
2536 else if ( strcmp(namebuf,"visibility")==0 )
2537 st->isvisible = strcmp(propbuf,"hidden")!=0 &&
2538 strcmp(propbuf,"colapse")!=0;
2539 else if ( strcmp(namebuf,"fill-opacity")==0 )
2540 st->fillopacity = strtod(propbuf,NULL);
2541 else if ( strcmp(namebuf,"stroke")==0 )
2542 st->dostroke = xmlParseColor(BAD_CAST propbuf,&st->strokecol,stroke_colour_source,st);
2543 else if ( strcmp(namebuf,"stroke-opacity")==0 )
2544 st->strokeopacity = strtod((char *)propbuf,NULL);
2545 else if ( strcmp(namebuf,"stroke-width")==0 )
2546 st->linewidth = strtod((char *)propbuf,NULL);
2547 else if ( strcmp(namebuf,"stroke-linecap")==0 )
2548 st->lc = strcmp(propbuf,"butt")==0 ? lc_butt :
2549 strcmp(propbuf,"round")==0 ? lc_round :
2550 lc_square;
2551 else if ( strcmp(namebuf,"stroke-linejoin")==0 )
2552 st->lj = strcmp(propbuf,"miter-clip")==0 ? lj_miterclip :
2553 strcmp(propbuf,"miter")==0 ? lj_miter :
2554 strcmp(propbuf,"round")==0 ? lj_round :
2555 strcmp(propbuf,"arcs")==0 ? lj_arcs :
2556 lj_bevel;
2557 else if ( strcmp(namebuf,"stroke-miterlimit")==0 )
2558 st->miterlimit = strtod((char *)propbuf,NULL);
2559 else if ( strcmp(namebuf,"stroke-dasharray")==0 ) {
2560 if ( strcmp(propbuf,"inherit")==0 ) {
2561 st->dashes[0] = 0; st->dashes[1] = DASH_INHERITED;
2562 } else if ( strcmp(propbuf,"none")==0 ) {
2563 st->dashes[0] = 0; st->dashes[1] = 0;
2564 } else {
2565 int i;
2566 char *pt, *end;
2567 pt = propbuf;
2568 for ( i=0; i<DASH_MAX && *pt!='\0'; ++i ) {
2569 st->dashes[i] = strtol( pt, &end,10);
2570 pt = end;
2571 }
2572 if ( i<DASH_MAX ) st->dashes[i] = 0;
2573 }
2574 } else if ( strcmp(namebuf,"stop-color")==0 )
2575 xmlParseColor(BAD_CAST propbuf,&st->stopColor,NULL,st);
2576 else if ( strcmp(namebuf,"stop-opacity")==0 )
2577 st->stopOpacity = strtod(propbuf,NULL);
2578 else {
2579 /* Lots of props we ignore */
2580 ;
2581 }
2582 } else if ( *name==';' )
2583 ++name;
2584 if ( *name=='\0' )
2585 break;
2586 }
2587 }
2588
2589 static Entity *_SVGParseSVG(xmlNodePtr svg, xmlNodePtr top,
2590 struct svg_state *inherit) {
2591 struct svg_state st;
2592 xmlChar *name;
2593 xmlNodePtr kid;
2594 Entity *ehead, *elast, *eret;
2595 SplineSet *head;
2596 int treat_symbol_as_g = false;
2597 char *fill_colour_source = NULL, *stroke_colour_source = NULL;
2598
2599 if ( svg==NULL )
2600 return( NULL );
2601
2602 st = *inherit;
2603 st.free_clip = false;
2604 tail_recurse:
2605 name = xmlGetProp(svg,(xmlChar *) "display");
2606 if ( name!=NULL ) {
2607 int hide = xmlStrcmp(name,(xmlChar *) "none")==0;
2608 xmlFree(name);
2609 if ( hide )
2610 return( NULL );
2611 }
2612 name = xmlGetProp(svg,(xmlChar *) "visibility");
2613 if ( name!=NULL ) {
2614 st.isvisible = xmlStrcmp(name,(xmlChar *) "hidden")!=0 &&
2615 xmlStrcmp(name,(xmlChar *) "colapse")!=0;
2616 xmlFree(name);
2617 }
2618 name = xmlGetProp(svg,(xmlChar *) "fill");
2619 if ( name!=NULL ) {
2620 st.dofill = xmlParseColor(BAD_CAST name,&st.fillcol,&fill_colour_source,&st);
2621 xmlFree(name);
2622 }
2623 name = xmlGetProp(svg,(xmlChar *) "fill-opacity");
2624 if ( name!=NULL ) {
2625 st.fillopacity = strtod((char *)name,NULL);
2626 xmlFree(name);
2627 }
2628 name = xmlGetProp(svg,(xmlChar *) "stroke");
2629 if ( name!=NULL ) {
2630 st.dostroke = xmlParseColor(BAD_CAST name,&st.strokecol,&stroke_colour_source,&st);
2631 xmlFree(name);
2632 }
2633 name = xmlGetProp(svg,(xmlChar *) "stroke-opacity");
2634 if ( name!=NULL ) {
2635 st.strokeopacity = strtod((char *)name,NULL);
2636 xmlFree(name);
2637 }
2638 name = xmlGetProp(svg,(xmlChar *) "stroke-width");
2639 if ( name!=NULL ) {
2640 st.linewidth = strtod((char *)name,NULL);
2641 xmlFree(name);
2642 }
2643 name = xmlGetProp(svg,(xmlChar *) "stroke-linecap");
2644 if ( name!=NULL ) {
2645 st.lc = xmlStrcmp(name,(xmlChar *) "butt")==0 ? lc_butt :
2646 xmlStrcmp(name,(xmlChar *) "round")==0 ? lc_round :
2647 lc_square;
2648 xmlFree(name);
2649 }
2650 name = xmlGetProp(svg,(xmlChar *) "stroke-linejoin");
2651 if ( name!=NULL ) {
2652 st.lj = xmlStrcmp(name,(xmlChar *) "miter-clip")==0 ? lj_miterclip :
2653 xmlStrcmp(name,(xmlChar *) "miter")==0 ? lj_miter :
2654 xmlStrcmp(name,(xmlChar *) "round")==0 ? lj_round :
2655 xmlStrcmp(name,(xmlChar *) "arcs")==0 ? lj_arcs :
2656 lj_bevel;
2657 xmlFree(name);
2658 }
2659 name = xmlGetProp(svg,(xmlChar *) "stroke-miterlimit");
2660 if ( name!=NULL ) {
2661 st.miterlimit = strtod((char *)name,NULL);
2662 xmlFree(name);
2663 }
2664 name = xmlGetProp(svg,(xmlChar *) "stroke-dasharray");
2665 if ( name!=NULL ) {
2666 if ( xmlStrcmp(name,(xmlChar *) "inherit")==0 ) {
2667 st.dashes[0] = 0; st.dashes[1] = DASH_INHERITED;
2668 } else if ( xmlStrcmp(name,(xmlChar *) "none")==0 ) {
2669 st.dashes[0] = 0; st.dashes[1] = 0;
2670 } else {
2671 int i;
2672 xmlChar *pt, *end;
2673 pt = name;
2674 for ( i=0; i<DASH_MAX && *pt!='\0'; ++i ) {
2675 st.dashes[i] = strtol((char *) pt,(char **) &end,10);
2676 pt = end;
2677 }
2678 if ( i<DASH_MAX ) st.dashes[i] = 0;
2679 }
2680 xmlFree(name);
2681 }
2682 name = xmlGetProp(svg,(xmlChar *) "style");
2683 if ( name!=NULL ) {
2684 SVGFigureStyle(&st,(char *) name, &fill_colour_source, &stroke_colour_source);
2685 xmlFree(name);
2686 }
2687 name = xmlGetProp(svg,(xmlChar *) "transform");
2688 if ( name!=NULL ) {
2689 SVGFigureTransform(&st,(char *) name);
2690 xmlFree(name);
2691 }
2692 name = xmlGetProp(svg,(xmlChar *) "clip-path");
2693 if ( name!=NULL ) {
2694 xmlNodePtr clip = XmlFindURI(top,(char *) name);
2695 if ( clip!=NULL && xmlStrcmp(clip->name,(xmlChar *) "clipPath")==0) {
2696 const xmlChar *temp = clip->name;
2697 struct svg_state null_state;
2698 memset(&null_state,0,sizeof(null_state));
2699 null_state.isvisible = true;
2700 null_state.transform[0] = null_state.transform[3] = 1;
2701 clip->name = (xmlChar *) "g";
2702 eret = _SVGParseSVG(clip,top,&null_state);
2703 clip->name = temp;
2704 if ( eret!=NULL && eret->type == et_splines ) {
2705 st.clippath = eret->u.splines.splines;
2706 eret->u.splines.splines = NULL;
2707 }
2708 free(eret);
2709 } else
2710 LogError(_("Could not find clippath named %s."), name );
2711 xmlFree(name);
2712 }
2713
2714 if ( (treat_symbol_as_g && xmlStrcmp(svg->name,(xmlChar *) "symbol")==0) ||
2715 xmlStrcmp(svg->name,(xmlChar *) "svg")==0 ||
2716 xmlStrcmp(svg->name,(xmlChar *) "glyph")==0 ||
2717 xmlStrcmp(svg->name,(xmlChar *) "pattern")==0 ||
2718 xmlStrcmp(svg->name,(xmlChar *) "g")==0 ) {
2719 ehead = elast = NULL;
2720 for ( kid = svg->children; kid!=NULL; kid=kid->next ) {
2721 eret = _SVGParseSVG(kid,top,&st);
2722 if ( eret!=NULL ) {
2723 if ( elast==NULL )
2724 ehead = eret;
2725 else
2726 elast->next = eret;
2727 while ( eret->next!=NULL ) eret = eret->next;
2728 elast = eret;
2729 }
2730 }
2731 SvgStateFree(&st);
2732 if ( fill_colour_source!=NULL || stroke_colour_source!=NULL )
2733 xmlApplyColourSources(top,ehead,&st,fill_colour_source,stroke_colour_source);
2734 return( ehead );
2735 } else if ( xmlStrcmp(svg->name,(xmlChar *) "use")==0 ) {
2736 name = xmlGetProp(svg,(xmlChar *) "href");
2737 kid = NULL;
2738 if ( name!=NULL && *name=='#' ) { /* Within this file */
2739 kid = XmlFindID(top,(char *) name+1);
2740 treat_symbol_as_g = true;
2741 }
2742 SVGuseTransform(&st,svg,kid);
2743 svg = kid;
2744 if ( name!=NULL )
2745 xmlFree(name);
2746 if ( svg!=NULL )
2747 goto tail_recurse;
2748 SvgStateFree(&st);
2749 return( NULL );
2750 }
2751
2752 if ( !st.isvisible ) {
2753 SvgStateFree(&st);
2754 return( NULL );
2755 }
2756
2757 /* basic shapes */
2758 head = NULL;
2759 if ( xmlStrcmp(svg->name,(xmlChar *) "path")==0 ) {
2760 head = SVGParseExtendedPath(svg,top);
2761 } else if ( xmlStrcmp(svg->name,(xmlChar *) "rect")==0 ) {
2762 head = SVGParseRect(svg); /* x,y,width,height,rx,ry */
2763 } else if ( xmlStrcmp(svg->name,(xmlChar *) "circle")==0 ) {
2764 head = SVGParseEllipse(svg,true); /* cx,cy, r */
2765 } else if ( xmlStrcmp(svg->name,(xmlChar *) "ellipse")==0 ) {
2766 head = SVGParseEllipse(svg,false); /* cx,cy, rx,ry */
2767 } else if ( xmlStrcmp(svg->name,(xmlChar *) "line")==0 ) {
2768 head = SVGParseLine(svg); /* x1,y1, x2,y2 */
2769 } else if ( xmlStrcmp(svg->name,(xmlChar *) "polyline")==0 ) {
2770 head = SVGParsePoly(svg,0); /* points */
2771 } else if ( xmlStrcmp(svg->name,(xmlChar *) "polygon")==0 ) {
2772 head = SVGParsePoly(svg,1); /* points */
2773 } else if ( xmlStrcmp(svg->name,(xmlChar *) "image")==0 ) {
2774 eret = SVGParseImage(svg);
2775 if (eret!=NULL)
2776 eret->clippath = st.clippath;
2777 return( eret );
2778 } else
2779 return( NULL );
2780 if ( head==NULL )
2781 return( NULL );
2782
2783 SPLCategorizePoints(head);
2784
2785 eret = EntityCreate(SplinePointListTransform(head,st.transform,tpt_AllPoints), &st);
2786 if ( fill_colour_source!=NULL || stroke_colour_source!=NULL )
2787 xmlApplyColourSources(top,eret,&st,fill_colour_source,stroke_colour_source);
2788 SvgStateFree(&st);
2789 return( eret );
2790 }
2791
2792 void SCDimensionFromSVG(xmlNodePtr svg, SplineChar *sc, bool vert) {
2793 char *num;
2794 char *end;
2795 double width, height;
2796 num = (char *) xmlGetProp(svg,(xmlChar *) "width");
2797 if ( num!=NULL ) {
2798 width = strtod(num, &end);
2799 if (sc && (*end == '\0' || *end == ' ') && !vert)
2800 sc->width = width;
2801 xmlFree(num);
2802 }
2803 num = (char *) xmlGetProp(svg,(xmlChar *) "height");
2804 if ( num!=NULL ) {
2805 height = strtod(num, &end);
2806 if (sc && (*end == '\0' || *end == ' ') && vert)
2807 sc->vwidth = height;
2808 xmlFree(num);
2809 }
2810 return;
2811 }
2812
2813 void SCDimensionFromSVGFile(const char *path, SplineChar *sc, bool vert) {
2814 xmlDocPtr doc;
2815 xmlNodePtr svg = NULL;
2816 doc = xmlParseFile(path);
2817 if (doc != NULL)
2818 svg = xmlDocGetRootElement(doc);
2819 if (svg != NULL)
2820 SCDimensionFromSVG(svg, sc, vert);
2821 return;
2822 }
2823
2824 static Entity *SVGParseSVG(xmlNodePtr svg,int em_size,int ascent,bool scale,SplineChar *sc,bool vert) {
2825 struct svg_state st;
2826 char *num, *end;
2827 double swidth,sheight,width=1,height=1;
2828
2829 memset(&st,0,sizeof(st));
2830 st.lc = lc_inherited;
2831 st.lj = lj_inherited;
2832 st.linewidth = WIDTH_INHERITED;
2833 st.miterlimit = JLIMIT_INHERITED;
2834 st.fillcol = COLOR_INHERITED;
2835 st.strokecol = COLOR_INHERITED;
2836 st.currentColor = COLOR_INHERITED;
2837 st.stopColor = COLOR_INHERITED;
2838 st.isvisible = true;
2839 st.transform[0] = 1;
2840 st.transform[3] = -1; /* The SVG coord system has y increasing down */
2841 /* Font coords have y increasing up */
2842 st.transform[5] = ascent;
2843 st.strokeopacity = st.fillopacity = 1.0;
2844
2845 num = (char *) xmlGetProp(svg,(xmlChar *) "width");
2846 if ( num!=NULL ) {
2847 width = strtod(num, &end);
2848 if (sc && (*end == '\0' || *end == ' ') && !vert)
2849 sc->width = width;
2850 xmlFree(num);
2851 }
2852 num = (char *) xmlGetProp(svg,(xmlChar *) "height");
2853 if ( num!=NULL ) {
2854 height = strtod(num, &end);
2855 if (sc && (*end == '\0' || *end == ' ') && vert)
2856 sc->vwidth = height;
2857 xmlFree(num);
2858 }
2859 if ( height<=0 ) height = 1;
2860 if ( width<=0 ) width = 1;
2861 num = (char *) xmlGetProp(svg,(xmlChar *) "viewBox");
2862 if ( num!=NULL ) {
2863 /* x = */strtod((char *) num,&end);
2864 /* y = */strtod((char *) end+1,&end);
2865 swidth = strtod((char *) end+1,&end);
2866 sheight = strtod((char *) end+1,&end);
2867 xmlFree(num);
2868 if ( width>height ) {
2869 if ( scale && swidth!=0 ) {
2870 st.transform[0] *= em_size/swidth;
2871 st.transform[3] *= em_size/swidth;
2872 }
2873 } else {
2874 if ( scale && sheight!=0 ) {
2875 st.transform[0] *= em_size/sheight;
2876 st.transform[3] *= em_size/sheight;
2877 }
2878 }
2879 }
2880 return( _SVGParseSVG(svg,svg,&st));
2881 }
2882
2883 static void SVGParseGlyphBody(SplineChar *sc, xmlNodePtr glyph,
2884 ImportParams *ip) {
2885 xmlChar *path;
2886
2887 path = xmlGetProp(glyph,(xmlChar *) "d");
2888 if ( path!=NULL ) {
2889 sc->layers[ly_fore].splines = SVGParseExtendedPath(glyph,glyph);
2890 xmlFree(path);
2891 } else {
2892 Entity *ent = SVGParseSVG(glyph,sc->parent->ascent+sc->parent->descent,
2893 sc->parent->ascent,ip->scale,ip->dimensions ? sc : NULL,false);
2894 sc->layer_cnt = 1;
2895 SCAppendEntityLayers(sc,ent,ip);
2896 if ( sc->layer_cnt==1 ) ++sc->layer_cnt;
2897 else sc->parent->multilayer = true;
2898 }
2899
2900 SCCategorizePoints(sc);
2901 }
2902
2903 static int SVGGetUnicodeEnc(xmlChar *unicode, xmlChar *arabic_form, xmlChar *glyphname) {
2904 int unicodeenc = -1;
2905 if (unicode != NULL && unicode[0] != '\0') {
2906 uint32_t *u = utf82u_copy((char *) unicode);
2907 if ( u[1]=='\0' ) {
2908 unicodeenc = u[0];
2909 if ( arabic_form!=NULL && u[0]>=0x600 && u[0]<=0x6ff ) {
2910 const struct arabicforms* aform = arabicform(u[0]);
2911 if ( xmlStrcmp(arabic_form,(xmlChar *) "initial")==0 )
2912 unicodeenc = aform->initial;
2913 else if ( xmlStrcmp(arabic_form,(xmlChar *) "medial")==0 )
2914 unicodeenc = aform->medial;
2915 else if ( xmlStrcmp(arabic_form,(xmlChar *) "final")==0 )
2916 unicodeenc = aform->final;
2917 else if ( xmlStrcmp(arabic_form,(xmlChar *) "isolated")==0 )
2918 unicodeenc = aform->isolated;
2919 }
2920 }
2921 free(u);
2922 }
2923 if (unicodeenc == -1 && glyphname != NULL)
2924 unicodeenc = UniFromName((char *) glyphname,ui_none,&custom);
2925
2926 return unicodeenc;
2927 }
2928
2929 /* This function should never return NULL or empty string. */
2930 static char* SVGGetGlyphName(xmlChar *glyphname, xmlChar *orientation,
2931 int unicodeenc, unsigned int glyph_idx, bool* glyphname_valid) {
2932 char* name = NULL;
2933 bool has_vert_suffix = false;
2934 unsigned int name_len = 0, vert_len = 0;
2935 *glyphname_valid = false;
2936
2937 if ( glyphname!=NULL ) {
2938 /* Check name validity. */
2939 unichar_t *uname = utf82u_copy((char *) glyphname);
2940 if (SCNameCheck(uname, NULL) == NULL) {
2941 name = copy((char *) glyphname);
2942 *glyphname_valid = true;
2943 }
2944 free(uname);
2945 }
2946
2947 /* Get name from unicode value. */
2948 if (name == NULL) {
2949 char buffer[40];
2950 if (unicodeenc == -1)
2951 name = smprintf("glyph%d", glyph_idx);
2952 else
2953 name = copy(StdGlyphName(buffer,unicodeenc,ui_none,NULL));
2954 }
2955
2956 name_len = strlen(name);
2957 vert_len = strlen(".vert");
2958 has_vert_suffix = (name_len >= vert_len) &&
2959 (strcmp(".vert", name + name_len - vert_len) == 0);
2960 if (!has_vert_suffix && orientation != NULL && *orientation == 'v') {
2961 char* new_name = smprintf("%s.vert", name);
2962 free(name);
2963 name = new_name;
2964 }
2965
2966 return name;
2967 }
2968
2969 static SplineChar *SVGParseGlyphArgs(xmlNodePtr glyph,int defh, int defv,
2970 SplineFont *sf, unsigned int glyph_idx) {
2971 SplineChar *sc = SFSplineCharCreate(sf);
2972 xmlChar *name, *form, *glyphname, *unicode, *orientation;
2973 bool glyphname_valid = false;
2974
2975 name = xmlGetProp(glyph,(xmlChar *) "horiz-adv-x");
2976 if ( name!=NULL ) {
2977 sc->width = strtod((char *) name,NULL);
2978 sc->widthset = true;
2979 xmlFree(name);
2980 } else
2981 sc->width = defh;
2982 name = xmlGetProp(glyph,(xmlChar *) "vert-adv-y");
2983 if ( name!=NULL ) {
2984 sc->vwidth = strtod((char *) name,NULL);
2985 xmlFree(name);
2986 } else
2987 sc->vwidth = defv;
2988 name = xmlGetProp(glyph,(xmlChar *) "vert-adv-y");
2989 if ( name!=NULL ) {
2990 sc->vwidth = strtod((char *) name,NULL);
2991 xmlFree(name);
2992 } else
2993 sc->vwidth = defv;
2994
2995 form = xmlGetProp(glyph,(xmlChar *) "arabic-form");
2996 unicode = xmlGetProp(glyph,(xmlChar *) "unicode");
2997 glyphname = xmlGetProp(glyph,(xmlChar *) "glyph-name");
2998 orientation = xmlGetProp(glyph,(xmlChar *) "orientation");
2999
3000 sc->unicodeenc = SVGGetUnicodeEnc(unicode, form, glyphname);
3001 sc->name = SVGGetGlyphName(glyphname, orientation, sc->unicodeenc, glyph_idx, &glyphname_valid);
3002 if (!glyphname_valid && glyphname && glyphname[0] != '\0') {
3003 /* Preserve the original glyph name and use it for SVG export. */
3004 free(sc->glif_name);
3005 sc->glif_name = copy((char *) glyphname);
3006 }
3007
3008 xmlFree(form);
3009 xmlFree(unicode);
3010 xmlFree(glyphname);
3011 xmlFree(orientation);
3012 return sc;
3013 }
3014
3015 static SplineChar *SVGParseMissing(SplineFont *sf,xmlNodePtr notdef,int defh,
3016 int defv, int enc, ImportParams *ip) {
3017 SplineChar *sc = SVGParseGlyphArgs(notdef,defh,defv,sf,enc);
3018 sc->parent = sf;
3019 free(sc->name);
3020 sc->name = copy(".notdef");
3021 sc->unicodeenc = 0;
3022 SVGParseGlyphBody(sc,notdef,ip);
3023 return( sc );
3024 }
3025
3026 static SplineChar *SVGParseGlyph(SplineFont *sf,xmlNodePtr glyph,int defh,
3027 int defv, int enc, ImportParams *ip) {
3028 SplineChar *sc = SVGParseGlyphArgs(glyph,defh,defv,sf,enc);
3029 sc->parent = sf;
3030 SVGParseGlyphBody(sc,glyph,ip);
3031 return( sc );
3032 }
3033
3034 static void SVGLigatureFixupCheck(SplineChar *sc,xmlNodePtr glyph) {
3035 xmlChar *unicode;
3036 uint32_t *u;
3037 int len, len2;
3038 SplineChar **chars, *any = NULL;
3039 char *comp, *pt;
3040
3041 unicode = xmlGetProp(glyph,(xmlChar *) "unicode");
3042 if (unicode != NULL && unicode[0] != '\0') {
3043 u = utf82u_copy((char *) unicode);
3044 xmlFree(unicode);
3045 if ( u[1]!='\0' && u[2]=='\0' &&
3046 ((u[1]>=0x180B && u[1]<=0x180D) || /* Mongolian VS */
3047 (u[1]>=0xfe00 && u[1]<=0xfe0f) || /* First VS block */
3048 (u[1]>=0xE0100 && u[1]<=0xE01EF)) ) { /* Second VS block */
3049 /* Probably a variant glyph marked with a variation selector */
3050 /* ... not a true ligature at all */
3051 /* http://babelstone.blogspot.com/2007/06/secret-life-of-variation-selectors.html */
3052 struct altuni *altuni = chunkalloc(sizeof(struct altuni));
3053 altuni->unienc = u[0];
3054 altuni->vs = u[1];
3055 altuni->fid = 0;
3056 altuni->next = sc->altuni;
3057 sc->altuni = altuni;
3058 } else if ( u[1]!='\0' ) {
3059 /* Normal ligature */
3060 for ( len=0; u[len]!=0; ++len );
3061 chars = malloc(len*sizeof(SplineChar *));
3062 for ( len=len2=0; u[len]!=0; ++len ) {
3063 chars[len] = SFGetChar(sc->parent,u[len],NULL);
3064 if ( chars[len]==NULL )
3065 len2 += 9;
3066 else {
3067 len2 += strlen(chars[len]->name)+1;
3068 if ( any==NULL ) any = chars[len];
3069 }
3070 }
3071 if ( any==NULL ) any=sc;
3072 comp = pt = malloc(len2+1);
3073 *pt = '\0';
3074 for ( len=0; u[len]!=0; ++len ) {
3075 if ( chars[len]!=NULL )
3076 strcpy(pt,chars[len]->name);
3077 else if ( u[len]<0x10000 )
3078 sprintf(pt,"uni%04X", (unsigned int) u[len]);
3079 else
3080 sprintf(pt,"u%04X", (unsigned int) u[len]);
3081 pt += strlen(pt);
3082 if ( u[len+1]!='\0' )
3083 *pt++ = ' ';
3084 }
3085 SubsNew(sc,pst_ligature,CHR('l','i','g','a'),comp,any);
3086 /* Understand the unicode latin ligatures. There are too many */
3087 /* arabic ones */
3088 if ( u[0]=='f' ) {
3089 if ( u[1]=='f' && u[2]==0 )
3090 sc->unicodeenc = 0xfb00;
3091 else if ( u[1]=='i' && u[2]==0 )
3092 sc->unicodeenc = 0xfb01;
3093 else if ( u[1]=='l' && u[2]==0 )
3094 sc->unicodeenc = 0xfb02;
3095 else if ( u[1]=='f' && u[2]=='i' && u[3]==0 )
3096 sc->unicodeenc = 0xfb03;
3097 else if ( u[1]=='f' && u[2]=='l' && u[3]==0 )
3098 sc->unicodeenc = 0xfb04;
3099 else if ( u[1]=='t' && u[2]==0 )
3100 sc->unicodeenc = 0xfb05;
3101 } else if ( u[0]=='s' && u[1]=='t' && u[2]==0 )
3102 sc->unicodeenc = 0xfb06;
3103 if ( strncmp(sc->name,"glyph",5)==0 && isdigit(sc->name[5])) {
3104 /* It's a default name, we can do better */
3105 free(sc->name);
3106 sc->name = copy(comp);
3107 for ( pt = sc->name; *pt; ++pt )
3108 if ( *pt==' ' ) *pt = '_';
3109 }
3110 }
3111 free(u);
3112 }
3113 }
3114
3115 static char *SVGGetNames(SplineFont *sf,xmlChar *g,xmlChar *utf8,SplineChar **sc) {
3116 uint32_t *u=NULL;
3117 char *names;
3118 int len, i, ch;
3119 SplineChar *temp;
3120 char *pt, *gpt;
3121
3122 *sc = NULL;
3123 len = 0;
3124 if ( utf8!=NULL ) {
3125 u = utf82u_copy((char *) utf8);
3126 for ( i=0; u[i]!=0; ++i ) {
3127 temp = SFGetChar(sf,u[i],NULL);
3128 if ( temp!=NULL ) {
3129 if ( *sc==NULL ) *sc = temp;
3130 len += strlen(temp->name)+1;
3131 }
3132 }
3133 }
3134 names = pt = malloc(len+(g!=NULL?strlen((char *)g):0)+1);
3135 if ( utf8!=NULL ) {
3136 for ( i=0; u[i]!=0; ++i ) {
3137 temp = SFGetChar(sf,u[i],NULL);
3138 if ( temp!=NULL ) {
3139 strcpy(pt,temp->name);
3140 pt += strlen( pt );
3141 *pt++ = ' ';
3142 }
3143 }
3144 free(u);
3145 }
3146 if ( g!=NULL ) {
3147 for ( gpt=(char *) g; *gpt; ) {
3148 if ( *gpt==',' || isspace(*gpt)) {
3149 while ( *gpt==',' || isspace(*gpt)) ++gpt;
3150 *pt++ = ' ';
3151 } else {
3152 *pt++ = *gpt++;
3153 }
3154 }
3155 if ( *sc==NULL ) {
3156 for ( gpt = (char *) g; *gpt!='\0' && *gpt!=',' && !isspace(*gpt); ++gpt );
3157 ch = *gpt; *gpt = '\0';
3158 *sc = SFGetChar(sf,-1,(char *) g);
3159 *gpt = ch;
3160 }
3161 }
3162 if ( pt>names && pt[-1]==' ' ) --pt;
3163 *pt = '\0';
3164 return( names );
3165 }
3166
3167 static void SVGParseKern(SplineFont *sf,xmlNodePtr kern,int isv) {
3168 xmlChar *k, *g1, *u1, *g2, *u2;
3169 double off;
3170 char *c1, *c2;
3171 char *pt1, *pt2, *end1, *end2;
3172 SplineChar *sc1, *sc2;
3173 uint32_t script;
3174 struct lookup_subtable *subtable;
3175
3176 k = xmlGetProp(kern,(xmlChar *) "k");
3177 if ( k==NULL )
3178 return;
3179 off = -strtod((char *)k, NULL);
3180 xmlFree(k);
3181 if ( off==0 )
3182 return;
3183
3184 g1 = xmlGetProp(kern,(xmlChar *) "g1");
3185 u1 = xmlGetProp(kern,(xmlChar *) "u1");
3186 if ( g1==NULL && u1==NULL )
3187 return;
3188 c1 = SVGGetNames(sf,g1,u1,&sc1);
3189 if ( g1!=NULL ) xmlFree(g1);
3190 if ( u1!=NULL ) xmlFree(u1);
3191
3192 g2 = xmlGetProp(kern,(xmlChar *) "g2");
3193 u2 = xmlGetProp(kern,(xmlChar *) "u2");
3194 if ( g2==NULL && u2==NULL ) {
3195 free(c1);
3196 return;
3197 }
3198 c2 = SVGGetNames(sf,g2,u2,&sc2);
3199 if ( g2!=NULL ) xmlFree(g2);
3200 if ( u2!=NULL ) xmlFree(u2);
3201
3202 script = DEFAULT_SCRIPT;
3203 if ( sc1!=NULL )
3204 script = SCScriptFromUnicode(sc1);
3205 if ( script==DEFAULT_SCRIPT && sc2!=NULL )
3206 script = SCScriptFromUnicode(sc2);
3207 /* It is tempting to use a kern class... but it doesn't work. No guarantees */
3208 /* that either of our two "classes" will ever show again. We could do the */
3209 /* complex shinanigans we do in parsing feature files, but it's a lot easier */
3210 /* just to make kernpairs. */
3211 subtable = SFSubTableFindOrMake(sf,
3212 isv?CHR('v','k','r','n'):CHR('k','e','r','n'),
3213 script, gpos_pair);
3214 subtable->lookup->lookup_flags = ((sc1!=NULL && SCRightToLeft(sc1)) ||
3215 (sc1==NULL && sc2!=NULL && SCRightToLeft(sc2)))? pst_r2l : 0;
3216 for ( pt1=c1 ; ; ) {
3217 while ( *pt1==' ' ) ++pt1;
3218 if ( *pt1=='\0' )
3219 break;
3220 end1 = strchr(pt1,' ');
3221 if ( end1!=NULL ) *end1 = '\0';
3222 sc1 = SFGetChar(sf,-1,pt1);
3223 if ( sc1!=NULL ) for ( pt2=c2 ; ; ) {
3224 while ( *pt2==' ' ) ++pt2;
3225 if ( *pt2=='\0' )
3226 break;
3227 end2 = strchr(pt2,' ');
3228 if ( end2!=NULL ) *end2 = '\0';
3229 sc2 = SFGetChar(sf,-1,pt2);
3230 if ( sc2!=NULL ) {
3231 KernPair *kp = chunkalloc(sizeof(KernPair));
3232 kp->sc = sc2;
3233 kp->off = off;
3234 if ( isv ) {
3235 kp->next = sc1->vkerns;
3236 sc1->vkerns = kp;
3237 } else {
3238 kp->next = sc1->kerns;
3239 sc1->kerns = kp;
3240 }
3241 kp->subtable = subtable;
3242 }
3243 if ( end2==NULL )
3244 break;
3245 *end2 = ' ';
3246 pt2 = end2+1;
3247 }
3248 if ( end1==NULL )
3249 break;
3250 *end1 = ' ';
3251 pt1 = end1+1;
3252 }
3253 free(c1); free(c2);
3254 }
3255
3256 static SplineFont *SVGParseFont(xmlNodePtr font) {
3257 int cnt;
3258 xmlNodePtr kids;
3259 int defh=0, defv=0;
3260 int has_font_face = false;
3261 xmlChar *name;
3262 SplineFont *sf;
3263 EncMap *map;
3264 ImportParams *ip = ImportParamsState();
3265 bigreal tmpjl = ip->default_joinlimit;
3266 int i;
3267
3268 if ( tmpjl==JLIMIT_INHERITED )
3269 ip->default_joinlimit = 4.0; // SVG default
3270
3271 sf = SplineFontEmpty();
3272 name = xmlGetProp(font,(xmlChar *) "horiz-adv-x");
3273 if ( name!=NULL ) {
3274 defh = strtod((char *) name,NULL);
3275 xmlFree(name);
3276 }
3277 name = xmlGetProp(font,(xmlChar *) "vert-adv-y");
3278 if ( name!=NULL ) {
3279 defv = strtod((char *) name,NULL);
3280 xmlFree(name);
3281 sf->hasvmetrics = true;
3282 }
3283 name = xmlGetProp(font,(xmlChar *) "id");
3284 if ( name!=NULL ) {
3285 sf->fontname = copy( (char *) name);
3286 xmlFree(name);
3287 }
3288
3289 cnt = 0;
3290 for ( kids = font->children; kids!=NULL; kids=kids->next ) {
3291 int ascent=0, descent=0;
3292 if ( xmlStrcmp(kids->name,(const xmlChar *) "font-face")==0 ) {
3293 has_font_face = true;
3294 name = xmlGetProp(kids,(xmlChar *) "units-per-em");
3295 if ( name!=NULL ) {
3296 int val = rint(strtod((char *) name,NULL));
3297 xmlFree(name);
3298 if ( val<0 ) val = 0;
3299 sf->ascent = val*800/1000;
3300 sf->descent = val - sf->ascent;
3301 if ( defv==0 ) defv = val;
3302 if ( defh==0 ) defh = val;
3303 SFDefaultOS2Simple(&sf->pfminfo,sf);
3304 } else {
3305 LogError( _("This font does not specify units-per-em") );
3306 SplineFontFree(sf);
3307 ip->default_joinlimit = tmpjl;
3308 return( NULL );
3309 }
3310 name = xmlGetProp(kids,(xmlChar *) "font-family");
3311 if ( name!=NULL ) {
3312 if ( strchr((char *) name,',')!=NULL )
3313 *strchr((char *) name,',') ='\0';
3314 sf->familyname = copy( (char *) name);
3315 xmlFree(name);
3316 }
3317 name = xmlGetProp(kids,(xmlChar *) "font-weight");
3318 if ( name!=NULL ) {
3319 if ( strnmatch((char *) name,"normal",6)==0 ) {
3320 sf->pfminfo.weight = 400;
3321 sf->weight = copy("Regular");
3322 sf->pfminfo.panose[2] = 5;
3323 } else if ( strnmatch((char *) name,"bold",4)==0 ) {
3324 sf->pfminfo.weight = 700;
3325 sf->weight = copy("Bold");
3326 sf->pfminfo.panose[2] = 8;
3327 } else {
3328 sf->pfminfo.weight = strtod((char *) name,NULL);
3329 if ( sf->pfminfo.weight <= 100 ) {
3330 sf->weight = copy("Thin");
3331 sf->pfminfo.panose[2] = 2;
3332 } else if ( sf->pfminfo.weight <= 200 ) {
3333 sf->weight = copy("Extra-Light");
3334 sf->pfminfo.panose[2] = 3;
3335 } else if ( sf->pfminfo.weight <= 300 ) {
3336 sf->weight = copy("Light");
3337 sf->pfminfo.panose[2] = 4;
3338 } else if ( sf->pfminfo.weight <= 400 ) {
3339 sf->weight = copy("Regular");
3340 sf->pfminfo.panose[2] = 5;
3341 } else if ( sf->pfminfo.weight <= 500 ) {
3342 sf->weight = copy("Medium");
3343 sf->pfminfo.panose[2] = 6;
3344 } else if ( sf->pfminfo.weight <= 600 ) {
3345 sf->weight = copy("DemiBold");
3346 sf->pfminfo.panose[2] = 7;
3347 } else if ( sf->pfminfo.weight <= 700 ) {
3348 sf->weight = copy("Bold");
3349 sf->pfminfo.panose[2] = 8;
3350 } else if ( sf->pfminfo.weight <= 800 ) {
3351 sf->weight = copy("Heavy");
3352 sf->pfminfo.panose[2] = 9;
3353 } else {
3354 sf->weight = copy("Black");
3355 sf->pfminfo.panose[2] = 10;
3356 }
3357 }
3358 sf->pfminfo.panose_set = true;
3359 sf->pfminfo.pfmset = true;
3360 xmlFree(name);
3361 }
3362 name = xmlGetProp(kids,(xmlChar *) "font-stretch");
3363 if ( name!=NULL ) {
3364 if ( strnmatch((char *) name,"normal",6)==0 ) {
3365 sf->pfminfo.panose[3] = 3;
3366 sf->pfminfo.width = 5;
3367 } else if ( strmatch((char *) name,"ultra-condensed")==0 ) {
3368 sf->pfminfo.panose[3] = 8;
3369 sf->pfminfo.width = 1;
3370 } else if ( strmatch((char *) name,"extra-condensed")==0 ) {
3371 sf->pfminfo.panose[3] = 8;
3372 sf->pfminfo.width = 2;
3373 } else if ( strmatch((char *) name,"condensed")==0 ) {
3374 sf->pfminfo.panose[3] = 6;
3375 sf->pfminfo.width = 3;
3376 } else if ( strmatch((char *) name,"semi-condensed")==0 ) {
3377 sf->pfminfo.panose[3] = 6;
3378 sf->pfminfo.width = 4;
3379 } else if ( strmatch((char *) name,"ultra-expanded")==0 ) {
3380 sf->pfminfo.panose[3] = 7;
3381 sf->pfminfo.width = 9;
3382 } else if ( strmatch((char *) name,"extra-expanded")==0 ) {
3383 sf->pfminfo.panose[3] = 7;
3384 sf->pfminfo.width = 8;
3385 } else if ( strmatch((char *) name,"expanded")==0 ) {
3386 sf->pfminfo.panose[3] = 5;
3387 sf->pfminfo.width = 7;
3388 } else if ( strmatch((char *) name,"semi-expanded")==0 ) {
3389 sf->pfminfo.panose[3] = 5;
3390 sf->pfminfo.width = 6;
3391 }
3392 sf->pfminfo.panose_set = true;
3393 sf->pfminfo.pfmset = true;
3394 xmlFree(name);
3395 }
3396 name = xmlGetProp(kids,(xmlChar *) "panose-1");
3397 if ( name!=NULL ) {
3398 char *pt, *end;
3399 int i;
3400 for ( i=0, pt=(char *) name; i<10 && *pt; pt = end, ++i ) {
3401 sf->pfminfo.panose[i] = strtol(pt,&end,10);
3402 }
3403 sf->pfminfo.panose_set = true;
3404 xmlFree(name);
3405 }
3406 name = xmlGetProp(kids,(xmlChar *) "slope");
3407 if ( name!=NULL ) {
3408 sf->italicangle = strtod((char *) name,NULL);
3409 xmlFree(name);
3410 }
3411 name = xmlGetProp(kids,(xmlChar *) "underline-position");
3412 if ( name!=NULL ) {
3413 sf->upos = strtod((char *) name,NULL);
3414 xmlFree(name);
3415 }
3416 name = xmlGetProp(kids,(xmlChar *) "underline-thickness");
3417 if ( name!=NULL ) {
3418 sf->uwidth = strtod((char *) name,NULL);
3419 xmlFree(name);
3420 }
3421 name = xmlGetProp(kids,(xmlChar *) "ascent");
3422 if ( name!=NULL ) {
3423 ascent = strtod((char *) name,NULL);
3424 xmlFree(name);
3425 }
3426 name = xmlGetProp(kids,(xmlChar *) "descent");
3427 if ( name!=NULL ) {
3428 descent = strtod((char *) name,NULL);
3429 xmlFree(name);
3430 }
3431 if ( ascent+descent==sf->ascent+sf->descent ) {
3432 sf->ascent = ascent;
3433 sf->descent = descent;
3434 }
3435 sf->pfminfo.pfmset = true;
3436 } else if ( xmlStrcmp(kids->name,(const xmlChar *) "glyph")==0 ||
3437 xmlStrcmp(kids->name,(const xmlChar *) "missing-glyph")==0 )
3438 ++cnt;
3439 }
3440 if ( !has_font_face ) {
3441 LogError( _("This font does not specify font-face") );
3442 SplineFontFree(sf);
3443 ip->default_joinlimit = tmpjl;
3444 return( NULL );
3445 }
3446 if ( sf->weight==NULL )
3447 sf->weight = copy("Regular");
3448 if ( sf->fontname==NULL && sf->familyname==NULL )
3449 sf->fontname = GetNextUntitledName();
3450 if ( sf->familyname==NULL )
3451 sf->familyname = copy(sf->fontname);
3452 if ( sf->fontname==NULL )
3453 sf->fontname = EnforcePostScriptName(sf->familyname);
3454 sf->fullname = copy(sf->fontname);
3455
3456 /* Give ourselves an xuid, just in case they want to convert to PostScript*/
3457 if ( xuid!=NULL ) {
3458 sf->xuid = malloc(strlen(xuid)+20);
3459 sprintf(sf->xuid,"[%s %d]", xuid, (ff_random_int()&0xffffff));
3460 }
3461
3462 ff_progress_change_total(cnt);
3463 sf->glyphcnt = sf->glyphmax = cnt;
3464 sf->glyphs = malloc(cnt*sizeof(SplineChar *));
3465
3466 cnt = 0;
3467 for ( kids = font->children; kids!=NULL; kids=kids->next ) {
3468 if ( xmlStrcmp(kids->name,(const xmlChar *) "missing-glyph")==0 ) {
3469 sf->glyphs[cnt] = SVGParseMissing(sf,kids,defh,defv,cnt,ip);
3470 if ( sf->glyphs[cnt]!=NULL ) {
3471 sf->glyphs[cnt]->orig_pos = cnt;
3472 cnt++;
3473 }
3474 ff_progress_next();
3475 } else if ( xmlStrcmp(kids->name,(const xmlChar *) "glyph")==0 ) {
3476 sf->glyphs[cnt] = SVGParseGlyph(sf,kids,defh,defv,cnt,ip);
3477 if ( sf->glyphs[cnt]!=NULL ) {
3478 sf->glyphs[cnt]->orig_pos = cnt;
3479 cnt++;
3480 }
3481 ff_progress_next();
3482 }
3483 }
3484 cnt = 0;
3485 for ( kids = font->children; kids!=NULL; kids=kids->next ) {
3486 if ( xmlStrcmp(kids->name,(const xmlChar *) "hkern")==0 ) {
3487 SVGParseKern(sf,kids,false);
3488 } else if ( xmlStrcmp(kids->name,(const xmlChar *) "vkern")==0 ) {
3489 SVGParseKern(sf,kids,true);
3490 } else if ( xmlStrcmp(kids->name,(const xmlChar *) "glyph")==0 ) {
3491 SVGLigatureFixupCheck(sf->glyphs[cnt++],kids);
3492 } else if ( xmlStrcmp(kids->name,(const xmlChar *) "missing-glyph")==0 ) {
3493 ++cnt;
3494 }
3495 }
3496
3497 map = chunkalloc(sizeof(EncMap));
3498 map->enccount = map->encmax = map->backmax = sf->glyphcnt;
3499 map->enc = FindOrMakeEncoding("Original");
3500 map->map = malloc(sf->glyphcnt*sizeof(int));
3501 map->backmap = malloc(sf->glyphcnt*sizeof(int));
3502 for ( i=0; i<sf->glyphcnt; ++i )
3503 map->map[i] = map->backmap[i] = i;
3504 sf->map = map;
3505 ip->default_joinlimit = tmpjl;
3506 return( sf );
3507 }
3508
3509 static int SPLFindOrder(SplineSet *ss) {
3510 Spline *s, *first;
3511
3512 while ( ss!=NULL ) {
3513 first = NULL;
3514 for ( s = ss->first->next; s!=NULL && s!=first ; s = s->to->next ) {
3515 if ( first==NULL ) first = s;
3516 if ( !s->knownlinear )
3517 return( s->order2 );
3518 }
3519 ss = ss->next;
3520 }
3521 return( -1 );
3522 }
3523
3524 static int EntFindOrder(Entity *ent) {
3525 int ret;
3526
3527 while ( ent!=NULL ) {
3528 if ( ent->type == et_splines ) {
3529 ret = SPLFindOrder(ent->u.splines.splines);
3530 if ( ret!=-1 )
3531 return( ret );
3532 }
3533 ent = ent->next;
3534 }
3535 return( -1 );
3536 }
3537
3538 int SFFindOrder(SplineFont *sf) {
3539 int i, ret;
3540
3541 for ( i=0; i<sf->glyphcnt; ++i ) if ( sf->glyphs[i]!=NULL ) {
3542 ret = SPLFindOrder(sf->glyphs[i]->layers[ly_fore].splines);
3543 if ( ret!=-1 )
3544 return( ret );
3545 }
3546 return( 0 );
3547 }
3548
3549 int SFLFindOrder(SplineFont *sf, int layerdest) {
3550 int i, ret;
3551
3552 for ( i=0; i<sf->glyphcnt; ++i ) if ( sf->glyphs[i]!=NULL ) {
3553 if (layerdest >= sf->glyphs[i]->layer_cnt)
3554 continue;
3555 ret = SPLFindOrder(sf->glyphs[i]->layers[layerdest].splines);
3556 if ( ret!=-1 )
3557 return( ret );
3558 }
3559 return( 0 );
3560 }
3561
3562 static void SPLSetOrder(SplineSet *ss,int order2) {
3563 Spline *s, *first;
3564 SplinePoint *from, *to;
3565
3566 while ( ss!=NULL ) {
3567 first = NULL;
3568 for ( s = ss->first->next; s!=NULL && s!=first ; s = s->to->next ) {
3569 if ( first==NULL ) first = s;
3570 if ( s->order2!=order2 ) {
3571 if ( s->knownlinear ) {
3572 s->from->nextcp = s->from->me;
3573 s->to->prevcp = s->to->me;
3574 s->from->nonextcp = s->to->noprevcp = true;
3575 s->order2 = order2;
3576 } else if ( order2 ) {
3577 from = SplineTtfApprox(s);
3578 s->from->nextcp = from->nextcp;
3579 s->from->nonextcp = from->nonextcp;
3580 s->from->next = from->next;
3581 from->next->from = s->from;
3582 SplinePointFree(from);
3583 for ( to = s->from->next->to; to->next!=NULL; to=to->next->to );
3584 s->to->prevcp = to->prevcp;
3585 s->to->noprevcp = to->noprevcp;
3586 s->to->prev = to->prev;
3587 to->prev->to = s->to;
3588 SplinePointFree(to);
3589 to = s->to;
3590 from = s->from;
3591 SplineFree(s);
3592 if ( first==s ) first = from->next;
3593 s = to->prev;
3594 } else {
3595 s->from->nextcp.x = s->splines[0].c/3 + s->from->me.x;
3596 s->from->nextcp.y = s->splines[1].c/3 + s->from->me.y;
3597 s->to->prevcp.x = s->from->nextcp.x+ (s->splines[0].b+s->splines[0].c)/3;
3598 s->to->prevcp.y = s->from->nextcp.y+ (s->splines[1].b+s->splines[1].c)/3;
3599 s->order2 = false;
3600 SplineRefigure(s);
3601 }
3602 }
3603 }
3604 ss = ss->next;
3605 }
3606 }
3607
3608 static void EntSetOrder(Entity *ent,int order2) {
3609 while ( ent!=NULL ) {
3610 if ( ent->type == et_splines )
3611 SPLSetOrder(ent->u.splines.splines,order2);
3612 SPLSetOrder(ent->clippath,order2);
3613 ent = ent->next;
3614 }
3615 }
3616
3617 void SFSetOrder(SplineFont *sf,int order2) {
3618 int i,j;
3619
3620 for ( i=0; i<sf->glyphcnt; ++i ) if ( sf->glyphs[i]!=NULL ) {
3621 for ( j=ly_fore; j<sf->glyphs[i]->layer_cnt; ++j ) {
3622 SPLSetOrder(sf->glyphs[i]->layers[j].splines,order2);
3623 sf->glyphs[i]->layers[j].order2 = order2;
3624 }
3625 }
3626 }
3627
3628 void SFLSetOrder(SplineFont *sf, int layerdest, int order2) {
3629 int i;
3630
3631 for ( i=0; i<sf->glyphcnt; ++i )
3632 if ( sf->glyphs[i]!=NULL && layerdest < sf->glyphs[i]->layer_cnt) {
3633 if (sf->glyphs[i]->layers[layerdest].splines != NULL)
3634 SPLSetOrder(sf->glyphs[i]->layers[layerdest].splines,order2);
3635 sf->glyphs[i]->layers[layerdest].order2 = order2;
3636 }
3637 }
3638
3639 static SplineFont *_SFReadSVG(xmlDocPtr doc, char *filename) {
3640 xmlNodePtr *fonts, font;
3641 SplineFont *sf;
3642 char *chosenname = NULL;
3643
3644 fonts = FindSVGFontNodes(doc);
3645 if ( fonts==NULL || fonts[0]==NULL ) {
3646 LogError( _("This file contains no SVG fonts.") );
3647 xmlFreeDoc(doc);
3648 return( NULL );
3649 }
3650 font = fonts[0];
3651 if ( fonts[1]!=NULL ) {
3652 xmlChar *name;
3653 font = SVGPickFont(fonts,filename);
3654 name = xmlGetProp(font,(xmlChar *) "id");
3655 if ( name!=NULL ) {
3656 chosenname = cu_copy(utf82u_copy((char *) name));
3657 xmlFree(name);
3658 }
3659 }
3660 free(fonts);
3661 locale_t tmplocale; locale_t oldlocale; // Declare temporary locale storage.
3662 switch_to_c_locale(&tmplocale, &oldlocale); // Switch to the C locale temporarily and cache the old locale.
3663 sf = SVGParseFont(font);
3664 switch_to_old_locale(&tmplocale, &oldlocale); // Switch to the cached locale.
3665 xmlFreeDoc(doc);
3666
3667 if ( sf!=NULL ) {
3668 time_t mtime;
3669 sf->layers[ly_fore].order2 = sf->layers[ly_back].order2 = sf->grid.order2 =
3670 SFFindOrder(sf);
3671 SFSetOrder(sf,sf->layers[ly_fore].order2);
3672 sf->chosenname = chosenname;
3673 mtime = GFileGetMTime(filename);
3674 if ( mtime != 0 ) {
3675 sf->modificationtime = mtime;
3676 sf->creationtime = mtime;
3677 }
3678 }
3679 return( sf );
3680 }
3681
3682 SplineFont *SFReadSVG(char *filename, int flags) {
3683 xmlDocPtr doc;
3684 char *temp=filename, *pt, *lparen;
3685
3686 pt = strrchr(filename,'/');
3687 if ( pt==NULL ) pt = filename;
3688 if ( (lparen=strchr(pt,'('))!=NULL && strchr(lparen,')')!=NULL ) {
3689 temp = copy(filename);
3690 pt = temp + (lparen-filename);
3691 *pt = '\0';
3692 }
3693
3694 doc = xmlParseFile(temp);
3695 if ( temp!=filename ) free(temp);
3696 if ( doc==NULL ) {
3697 /* Can I get an error message from libxml? */
3698 return( NULL );
3699 }
3700 return( _SFReadSVG(doc,filename));
3701 }
3702
3703 SplineFont *SFReadSVGMem(char *data, int flags) {
3704 xmlDocPtr doc;
3705
3706 doc = xmlParseMemory(data,strlen(data));
3707 if ( doc==NULL ) {
3708 /* Can I get an error message from libxml? */
3709 return( NULL );
3710 }
3711 return( _SFReadSVG(doc,NULL));
3712 }
3713
3714 char **NamesReadSVG(char *filename) {
3715 xmlNodePtr *fonts;
3716 xmlDocPtr doc;
3717 char **ret=NULL;
3718 int cnt;
3719 xmlChar *name;
3720
3721 doc = xmlParseFile(filename);
3722 if ( doc==NULL ) {
3723 /* Can I get an error message from libxml? */
3724 return( NULL );
3725 }
3726
3727 fonts = FindSVGFontNodes(doc);
3728 if ( fonts==NULL || fonts[0]==NULL ) {
3729 xmlFreeDoc(doc);
3730 return( NULL );
3731 }
3732
3733 for ( cnt=0; fonts[cnt]!=NULL; ++cnt);
3734 ret = malloc((cnt+1)*sizeof(char *));
3735 for ( cnt=0; fonts[cnt]!=NULL; ++cnt) {
3736 name = xmlGetProp(fonts[cnt],(xmlChar *) "id");
3737 if ( name==NULL ) {
3738 ret[cnt] = copy("nameless-font");
3739 } else {
3740 ret[cnt] = copy((char *) name);
3741 xmlFree(name);
3742 }
3743 }
3744 ret[cnt] = NULL;
3745
3746 free(fonts);
3747 xmlFreeDoc(doc);
3748
3749 return( ret );
3750 }
3751
3752 Entity *EntityInterpretSVG(char *filename, char *memory, int memlen,
3753 int em_size, int ascent, bool scale) {
3754 xmlDocPtr doc;
3755 xmlNodePtr top;
3756 char oldloc[25];
3757 Entity *ret;
3758 int order2;
3759
3760 if ( filename!=NULL )
3761 doc = xmlParseFile(filename);
3762 else
3763 doc = xmlParseMemory(memory,memlen);
3764 if ( doc==NULL ) {
3765 /* Can I get an error message from libxml???? */
3766 return( NULL );
3767 }
3768
3769 top = xmlDocGetRootElement(doc);
3770 if ( xmlStrcmp(top->name,(xmlChar *) "svg")!=0 ) {
3771 LogError( _("%s does not contain an <svg> element at the top"), filename);
3772 xmlFreeDoc(doc);
3773 return( NULL );
3774 }
3775
3776 strncpy( oldloc,setlocale(LC_NUMERIC,NULL),24 );
3777 oldloc[24]=0;
3778 setlocale(LC_NUMERIC,"C");
3779 ret = SVGParseSVG(top,em_size,ascent,scale,NULL,false);
3780 setlocale(LC_NUMERIC,oldloc);
3781 xmlFreeDoc(doc);
3782
3783 if ( loaded_fonts_same_as_new )
3784 order2 = new_fonts_are_order2;
3785 else
3786 order2 = EntFindOrder(ret);
3787 if ( order2==-1 ) order2 = 0;
3788 EntSetOrder(ret,order2);
3789
3790 return( ret );
3791 }
3792
3793 SplineSet *SplinePointListInterpretSVG(char *filename,char *memory, int memlen,int em_size,int ascent,int is_stroked, ImportParams *ip) {
3794 bigreal tmpjl = ip->default_joinlimit;
3795 if ( tmpjl==JLIMIT_INHERITED )
3796 ip->default_joinlimit = 4.0; // SVG default
3797 Entity *ret = EntityInterpretSVG(filename, memory, memlen, em_size, ascent,
3798 ip->scale);
3799 SplineSet *r = SplinesFromEntities(ret, ip, is_stroked);
3800 ip->default_joinlimit = tmpjl;
3801 return r;
3802 }