Commit message: Fix for #4084 Use-after-free (heap) in the SFD_GetFontMetaData() function
Fix for #4086 NULL pointer dereference in the SFDGetSpiros() function
Fix for #4088 NULL pointer dereference in the SFD_AssignLookups() function
Add empty sf->fontname string if it isn't set, fixing #4089 #4090 and many
  other potential issues (many downstream calls to strlen() on the value).
CVE: CVE-2020-5395
CWE: CWE-416
Vulnerability description: FontForge 20190801 has a use-after-free in SFD_GetFontMetaData in sfd.c.

Project: fontforge
File: sfd.c

static SplineChar *SFDGetChar(FILE *sfd,SplineFont *sf, int had_sf_layer_cnt) {
    SplineChar *sc;
    char tok[2000], ch;
    RefChar *lastr=NULL, *ref;
    ImageList *lasti=NULL, *img;
    AnchorPoint *lastap = NULL;
    GuidelineSet *lastgl = NULL;
    int isliga = 0, ispos, issubs, ismult, islcar, ispair, temp, i;
    PST *last = NULL;
    uint32 script = 0;
    int current_layer = ly_fore;
    int multilayer = sf->multilayer;
    int had_old_dstems = false;
    SplineFont *sli_sf = sf->cidmaster ? sf->cidmaster : sf;
    struct altuni *altuni;
    int oldback = false;

    if ( getname(sfd,tok)!=1 )
return( NULL );
    if ( strcmp(tok,"StartChar:")!=0 )
return( NULL );
    while ( isspace(ch=nlgetc(sfd)));
    ungetc(ch,sfd);
    sc = SFSplineCharCreate(sf);
    if ( ch!='"' ) {
	if ( getname(sfd,tok)!=1 ) {
	    SplineCharFree(sc);
return( NULL );
	}
	sc->name = copy(tok);
    } else {
	sc->name = SFDReadUTF7Str(sfd);
	if ( sc->name==NULL ) {
	    SplineCharFree(sc);
return( NULL );
	}
    }
    sc->vwidth = sf->ascent+sf->descent;
    sc->parent = sf;
    while ( 1 ) {
	if ( getname(sfd,tok)!=1 ) {
	    SplineCharFree(sc);
return( NULL );
	}
	if ( strmatch(tok,"Encoding:")==0 ) {
	    int enc;
	    getint(sfd,&enc);
	    getint(sfd,&sc->unicodeenc);
	    while ( (ch=nlgetc(sfd))==' ' || ch=='\t' );
	    ungetc(ch,sfd);
	    if ( ch!='\n' && ch!='\r' ) {
		getint(sfd,&sc->orig_pos);
		if ( sc->orig_pos==65535 )
		    sc->orig_pos = orig_pos++;
		    /* An old mark meaning: "I don't know" */
		if ( sc->orig_pos<sf->glyphcnt && sf->glyphs[sc->orig_pos]!=NULL )
		    sc->orig_pos = sf->glyphcnt;
		if ( sc->orig_pos>=sf->glyphcnt ) {
		    if ( sc->orig_pos>=sf->glyphmax )
			sf->glyphs = realloc(sf->glyphs,(sf->glyphmax = sc->orig_pos+10)*sizeof(SplineChar *));
		    memset(sf->glyphs+sf->glyphcnt,0,(sc->orig_pos+1-sf->glyphcnt)*sizeof(SplineChar *));
		    sf->glyphcnt = sc->orig_pos+1;
		}
		if ( sc->orig_pos+1 > orig_pos )
		    orig_pos = sc->orig_pos+1;
	    } else if ( sf->cidmaster!=NULL ) {		/* In cid fonts the orig_pos is just the cid */
		sc->orig_pos = enc;
	    } else {
		sc->orig_pos = orig_pos++;
	    }
	    SFDSetEncMap(sf,sc->orig_pos,enc);
	} else if ( strmatch(tok,"AltUni:")==0 ) {
	    int uni;
	    while ( getint(sfd,&uni)==1 ) {
		altuni = chunkalloc(sizeof(struct altuni));
		altuni->unienc = uni;
		altuni->vs = -1;
		altuni->fid = 0;
		altuni->next = sc->altuni;
		sc->altuni = altuni;
	    }
	} else if ( strmatch(tok,"AltUni2:")==0 ) {
	    uint32 uni[3];
	    while ( gethexints(sfd,uni,3) ) {
		altuni = chunkalloc(sizeof(struct altuni));
		altuni->unienc = uni[0];
		altuni->vs = uni[1];
		altuni->fid = uni[2];
		altuni->next = sc->altuni;
		sc->altuni = altuni;
	    }
	} else if ( strmatch(tok,"OldEncoding:")==0 ) {
	    int old_enc;		/* Obsolete info */
	    getint(sfd,&old_enc);
        } else if ( strmatch(tok,"Script:")==0 ) {
	    /* Obsolete. But still used for parsing obsolete ligature/subs tags */
            while ( (ch=nlgetc(sfd))==' ' || ch=='\t' );
            if ( ch=='\n' || ch=='\r' )
                script = 0;
            else {
		ungetc(ch,sfd);
		script = gettag(sfd);
            }
	} else if ( strmatch(tok,"GlifName:")==0 ) {
            while ( isspace(ch=nlgetc(sfd)));
            ungetc(ch,sfd);
            if ( ch!='"' ) {
              if ( getname(sfd,tok)!=1 ) {
                LogError(_("Invalid glif name.\n"));
              }
	      sc->glif_name = copy(tok);
            } else {
	      sc->glif_name = SFDReadUTF7Str(sfd);
	      if ( sc->glif_name==NULL ) {
                LogError(_("Invalid glif name.\n"));
	      }
            }
	} else if ( strmatch(tok,"Width:")==0 ) {
	    getsint(sfd,&sc->width);
	} else if ( strmatch(tok,"VWidth:")==0 ) {
	    getsint(sfd,&sc->vwidth);
	} else if ( strmatch(tok,"GlyphClass:")==0 ) {
	    getint(sfd,&temp);
	    sc->glyph_class = temp;
	} else if ( strmatch(tok,"UnlinkRmOvrlpSave:")==0 ) {
	    getint(sfd,&temp);
	    sc->unlink_rm_ovrlp_save_undo = temp;
	} else if ( strmatch(tok,"InSpiro:")==0 ) {
	    getint(sfd,&temp);
	    sc->inspiro = temp;
	} else if ( strmatch(tok,"LigCaretCntFixed:")==0 ) {
	    getint(sfd,&temp);
	    sc->lig_caret_cnt_fixed = temp;
	} else if ( strmatch(tok,"Flags:")==0 ) {
	    while ( isspace(ch=nlgetc(sfd)) && ch!='\n' && ch!='\r');
	    while ( ch!='\n' && ch!='\r' ) {
		if ( ch=='H' ) sc->changedsincelasthinted=true;
		else if ( ch=='M' ) sc->manualhints = true;
		else if ( ch=='W' ) sc->widthset = true;
		else if ( ch=='O' ) sc->wasopen = true;
		else if ( ch=='I' ) sc->instructions_out_of_date = true;
		ch = nlgetc(sfd);
	    }
	    if ( sf->multilayer || sf->onlybitmaps || sf->strokedfont || sc->layers[ly_fore].order2 )
		sc->changedsincelasthinted = false;
	} else if ( strmatch(tok,"TeX:")==0 ) {
	    getsint(sfd,&sc->tex_height);
	    getsint(sfd,&sc->tex_depth);
	    while ( isspace(ch=nlgetc(sfd)) && ch!='\n' && ch!='\r');
	    ungetc(ch,sfd);
	    if ( ch!='\n' && ch!='\r' ) {
		int16 old_tex;
		/* Used to store two extra values here */
		getsint(sfd,&old_tex);
		getsint(sfd,&old_tex);
		if ( sc->tex_height==0 && sc->tex_depth==0 )		/* Fixup old bug */
		    sc->tex_height = sc->tex_depth = TEX_UNDEF;
	    }
	} else if ( strmatch(tok,"ItalicCorrection:")==0 ) {
	    SFDParseMathValueRecord(sfd,&sc->italic_correction,&sc->italic_adjusts);
	} else if ( strmatch(tok,"TopAccentHorizontal:")==0 ) {
	    SFDParseMathValueRecord(sfd,&sc->top_accent_horiz,&sc->top_accent_adjusts);
	} else if ( strmatch(tok,"GlyphCompositionVerticalIC:")==0 ) {
	    if ( sc->vert_variants==NULL )
		sc->vert_variants = chunkalloc(sizeof(struct glyphvariants));
	    SFDParseMathValueRecord(sfd,&sc->vert_variants->italic_correction,&sc->vert_variants->italic_adjusts);
	} else if ( strmatch(tok,"GlyphCompositionHorizontalIC:")==0 ) {
	    if ( sc->horiz_variants==NULL )
		sc->horiz_variants = chunkalloc(sizeof(struct glyphvariants));
	    SFDParseMathValueRecord(sfd,&sc->horiz_variants->italic_correction,&sc->horiz_variants->italic_adjusts);
	} else if ( strmatch(tok,"IsExtendedShape:")==0 ) {
	    int temp;
	    getint(sfd,&temp);
	    sc->is_extended_shape = temp;
	} else if ( strmatch(tok,"GlyphVariantsVertical:")==0 ) {
	    if ( sc->vert_variants==NULL )
		sc->vert_variants = chunkalloc(sizeof(struct glyphvariants));
	    geteol(sfd,tok);
	    sc->vert_variants->variants = copy(tok);
	} else if ( strmatch(tok,"GlyphVariantsHorizontal:")==0 ) {
	    if ( sc->horiz_variants==NULL )
		sc->horiz_variants = chunkalloc(sizeof(struct glyphvariants));
	    geteol(sfd,tok);
	    sc->horiz_variants->variants = copy(tok);
	} else if ( strmatch(tok,"GlyphCompositionVertical:")==0 ) {
	    sc->vert_variants = SFDParseGlyphComposition(sfd, sc->vert_variants,tok);
	} else if ( strmatch(tok,"GlyphCompositionHorizontal:")==0 ) {
	    sc->horiz_variants = SFDParseGlyphComposition(sfd, sc->horiz_variants,tok);
	} else if ( strmatch(tok,"TopRightVertex:")==0 ) {
	    if ( sc->mathkern==NULL )
		sc->mathkern = chunkalloc(sizeof(struct mathkern));
	    SFDParseVertexKern(sfd, &sc->mathkern->top_right);
	} else if ( strmatch(tok,"TopLeftVertex:")==0 ) {
	    if ( sc->mathkern==NULL )
		sc->mathkern = chunkalloc(sizeof(struct mathkern));
	    SFDParseVertexKern(sfd, &sc->mathkern->top_left);
	} else if ( strmatch(tok,"BottomRightVertex:")==0 ) {
	    if ( sc->mathkern==NULL )
		sc->mathkern = chunkalloc(sizeof(struct mathkern));
	    SFDParseVertexKern(sfd, &sc->mathkern->bottom_right);
	} else if ( strmatch(tok,"BottomLeftVertex:")==0 ) {
	    if ( sc->mathkern==NULL )
		sc->mathkern = chunkalloc(sizeof(struct mathkern));
	    SFDParseVertexKern(sfd, &sc->mathkern->bottom_left);
#if HANYANG
	} else if ( strmatch(tok,"CompositionUnit:")==0 ) {
	    getsint(sfd,&sc->jamo);
	    getsint(sfd,&sc->varient);
	    sc->compositionunit = true;
#endif
	} else if ( strmatch(tok,"HStem:")==0 ) {
	    sc->hstem = SFDReadHints(sfd);
	    sc->hconflicts = StemListAnyConflicts(sc->hstem);
	} else if ( strmatch(tok,"VStem:")==0 ) {
	    sc->vstem = SFDReadHints(sfd);
	    sc->vconflicts = StemListAnyConflicts(sc->vstem);
	} else if ( strmatch(tok,"DStem:")==0 ) {
	    sc->dstem = SFDReadDHints( sc->parent,sfd,true );
            had_old_dstems = true;
	} else if ( strmatch(tok,"DStem2:")==0 ) {
	    sc->dstem = SFDReadDHints( sc->parent,sfd,false );
	} else if ( strmatch(tok,"CounterMasks:")==0 ) {
	    getsint(sfd,&sc->countermask_cnt);
	    sc->countermasks = calloc(sc->countermask_cnt,sizeof(HintMask));
	    for ( i=0; i<sc->countermask_cnt; ++i ) {
		int ch;
		while ( (ch=nlgetc(sfd))==' ' );
		ungetc(ch,sfd);
		SFDGetHintMask(sfd,&sc->countermasks[i]);
	    }
	} else if ( strmatch(tok,"AnchorPoint:")==0 ) {
	    lastap = SFDReadAnchorPoints(sfd,sc,&sc->anchor,lastap);
	} else if ( strmatch(tok,"Fore")==0 ) {
	    while ( isspace(ch = nlgetc(sfd)));
	    ungetc(ch,sfd);
	    if ( ch!='I' && ch!='R' && ch!='S' && ch!='V' && ch!=' ' && ch!='\n' && 
	         !PeekMatch(sfd, "Pickled") && !PeekMatch(sfd, "EndChar") &&
	         !PeekMatch(sfd, "Fore") && !PeekMatch(sfd, "Back") && !PeekMatch(sfd, "Layer") ) {
		/* Old format, without a SplineSet token */
		sc->layers[ly_fore].splines = SFDGetSplineSet(sfd,sc->layers[ly_fore].order2);
	    }
	    current_layer = ly_fore;
	    lastgl = NULL;
	} else if ( strmatch(tok,"MinimumDistance:")==0 ) {
	    SFDGetMinimumDistances(sfd,sc);
	} else if ( strmatch(tok,"Validated:")==0 ) {
	    getsint(sfd,(int16 *) &sc->layers[current_layer].validation_state);
	} else if ( strmatch(tok,"Back")==0 ) {
	    while ( isspace(ch=nlgetc(sfd)));
	    ungetc(ch,sfd);
	    if ( ch!='I' && ch!='R' && ch!='S' && ch!='V' && ch!=' ' && ch!='\n' &&
	         !PeekMatch(sfd, "Pickled") && !PeekMatch(sfd, "EndChar") &&
	         !PeekMatch(sfd, "Fore") && !PeekMatch(sfd, "Back") && !PeekMatch(sfd, "Layer") ) {
		/* Old format, without a SplineSet token */
		sc->layers[ly_back].splines = SFDGetSplineSet(sfd,sc->layers[ly_back].order2);
		oldback = true;
	    }
	    current_layer = ly_back;
	    lastgl = NULL;
	} else if ( strmatch(tok,"LayerCount:")==0 ) {
	    getint(sfd,&temp);
	    if ( temp>sc->layer_cnt ) {
		sc->layers = realloc(sc->layers,temp*sizeof(Layer));
		memset(sc->layers+sc->layer_cnt,0,(temp-sc->layer_cnt)*sizeof(Layer));
	    }
	    sc->layer_cnt = temp;
	    current_layer = ly_fore;
	} else if ( strmatch(tok,"Layer:")==0 ) {
	    int layer;
	    int dofill, dostroke, fillfirst, linejoin, linecap;
	    uint32 fillcol, strokecol;
	    real fillopacity, strokeopacity, strokewidth, trans[4];
	    DashType dashes[DASH_MAX];
	    int i;
	    getint(sfd,&layer);
	    if ( layer>=sc->layer_cnt ) {
		sc->layers = realloc(sc->layers,(layer+1)*sizeof(Layer));
		memset(sc->layers+sc->layer_cnt,0,(layer+1-sc->layer_cnt)*sizeof(Layer));
	    }
	    if ( sc->parent->multilayer ) {
		getint(sfd,&dofill);
		getint(sfd,&dostroke);
		getint(sfd,&fillfirst);
		gethex(sfd,&fillcol);
		getreal(sfd,&fillopacity);
		gethex(sfd,&strokecol);
		getreal(sfd,&strokeopacity);
		getreal(sfd,&strokewidth);
		getname(sfd,tok);
		for ( i=0; joins[i]!=NULL; ++i )
		    if ( strmatch(joins[i],tok)==0 )
		break;
		if ( joins[i]==NULL ) --i;
		linejoin = i;
		getname(sfd,tok);
		for ( i=0; caps[i]!=NULL; ++i )
		    if ( strmatch(caps[i],tok)==0 )
		break;
		if ( caps[i]==NULL ) --i;
		linecap = i;
		while ( (ch=nlgetc(sfd))==' ' || ch=='[' );
		ungetc(ch,sfd);
		getreal(sfd,&trans[0]);
		getreal(sfd,&trans[1]);
		getreal(sfd,&trans[2]);
		getreal(sfd,&trans[3]);
		while ( (ch=nlgetc(sfd))==' ' || ch==']' );
		if ( ch=='[' ) {
		    for ( i=0;; ++i ) { int temp;
			if ( !getint(sfd,&temp) )
		    break;
			else if ( i<DASH_MAX )
			    dashes[i] = temp;
		    }
		    if ( i<DASH_MAX )
			dashes[i] = 0;
		} else {
		    ungetc(ch,sfd);
		    memset(dashes,0,sizeof(dashes));
		}
		sc->layers[layer].dofill = dofill;
		sc->layers[layer].dostroke = dostroke;
		sc->layers[layer].fillfirst = fillfirst;
		sc->layers[layer].fill_brush.col = fillcol;
		sc->layers[layer].fill_brush.opacity = fillopacity;
		sc->layers[layer].stroke_pen.brush.col = strokecol;
		sc->layers[layer].stroke_pen.brush.opacity = strokeopacity;
		sc->layers[layer].stroke_pen.width = strokewidth;
		sc->layers[layer].stroke_pen.linejoin = linejoin;
		sc->layers[layer].stroke_pen.linecap = linecap;
		memcpy(sc->layers[layer].stroke_pen.dashes,dashes,sizeof(dashes));
		memcpy(sc->layers[layer].stroke_pen.trans,trans,sizeof(trans));
	    }
	    current_layer = layer;
	    lasti = NULL;
	    lastr = NULL;
	    lastgl = NULL;
	} else if ( strmatch(tok,"FillGradient:")==0 ) {
	    sc->layers[current_layer].fill_brush.gradient = SFDParseGradient(sfd,tok);
	} else if ( strmatch(tok,"FillPattern:")==0 ) {
	    sc->layers[current_layer].fill_brush.pattern = SFDParsePattern(sfd,tok);
	} else if ( strmatch(tok,"StrokeGradient:")==0 ) {
	    sc->layers[current_layer].stroke_pen.brush.gradient = SFDParseGradient(sfd,tok);
	} else if ( strmatch(tok,"StrokePattern:")==0 ) {
	    sc->layers[current_layer].stroke_pen.brush.pattern = SFDParsePattern(sfd,tok);
	} else if ( strmatch(tok,"UndoRedoHistory")==0 ) {

	    getname(sfd,tok);
	    if ( !strmatch(tok,"Layer:") ) {
		int layer;
		getint(sfd,&layer);
	    }

	    int limit;
	    Undoes *undo = 0;
	    struct undoes *last = 0;

	    getname(sfd,tok);
	    if ( !strmatch(tok,"Undoes") ) {
		undo = 0;
		limit = UndoRedoLimitToLoad;
		last = sc->layers[current_layer].undoes;
		while((undo = SFDGetUndo( sfd, sc, "UndoOperation", current_layer )))
		{
		    // push to back
		    if( last ) last->next = undo;
		    else       sc->layers[current_layer].undoes = undo;
		    last = undo;

		    if( limit != -1 ) {
			limit--;
			if( limit <= 0 ) {
			    // we have hit our load limit, so lets just chuck everything away
			    // until we hit the EndUndoes/EndRedoes magic line and then start
			    // actually processing again.
			    const char* terminators[] = { "EndUndoes", "EndRedoes", 0 };
			    SFDConsumeUntil( sfd, terminators );
			}
		    }
		}
	    }
	    getname(sfd,tok);
	    if ( !strmatch(tok,"Redoes") ) {
		undo = 0;
		limit = UndoRedoLimitToLoad;
		last = sc->layers[current_layer].redoes;
		while((undo = SFDGetUndo( sfd, sc, "RedoOperation", current_layer )))
		{
		    // push to back
		    if( last ) last->next = undo;
		    else       sc->layers[current_layer].redoes = undo;
		    last = undo;

		    if( limit != -1 ) {
			limit--;
			if( limit <= 0 ) {
			    // we have hit our load limit, so lets just chuck everything away
			    // until we hit the EndUndoes/EndRedoes magic line and then start
			    // actually processing again.
			    const char* terminators[] = { "EndUndoes", "EndRedoes", 0 };
			    SFDConsumeUntil( sfd, terminators );
			}
		    }
		}
	    }
	} else if ( strmatch(tok,"SplineSet")==0 ) {
	    sc->layers[current_layer].splines = SFDGetSplineSet(sfd,sc->layers[current_layer].order2);
	} else if ( strmatch(tok,"Guideline:")==0 ) {
	    lastgl = SFDReadGuideline(sfd, &sc->layers[current_layer].guidelines, lastgl);
	} else if ( strmatch(tok,"Ref:")==0 || strmatch(tok,"Refer:")==0 ) {
	    /* I should be depending on the version number here, but I made */
	    /*  a mistake and bumped the version too late. So the version is */
	    /*  not an accurate mark, but the presence of a LayerCount keyword*/
	    /*  in the font is an good mark. Before the LayerCount was added */
	    /*  (version 2) only the foreground layer could have references */
	    /*  after that (eventually version 3) any layer could. */
	    if ( oldback || !had_sf_layer_cnt ) current_layer = ly_fore;
	    ref = SFDGetRef(sfd,strmatch(tok,"Ref:")==0);
	    if ( sc->layers[current_layer].refs==NULL )
		sc->layers[current_layer].refs = ref;
	    else
		lastr->next = ref;
	    lastr = ref;
	} else if ( strmatch(tok,"Image:")==0 ) {
	    int ly = current_layer;
	    if ( !multilayer && !sc->layers[ly].background ) ly = ly_back;
	    img = SFDGetImage(sfd);
	    if (img != NULL) {
	    if ( sc->layers[ly].images==NULL )
		sc->layers[ly].images = img;
	    else
		lasti->next = img;
	    lasti = img;
	    }
	} else if ( strmatch(tok,"Image2:")==0 ) {
#ifndef _NO_LIBPNG
	    enum MIME mime = SFDGetImage2MIME(sfd);
	    if (mime == PNG) {
		int ly = current_layer;
		if ( !multilayer && !sc->layers[ly].background ) ly = ly_back;
		img = SFDGetImagePNG(sfd);
		if (img != NULL) {
		    if ( sc->layers[ly].images==NULL )
			sc->layers[ly].images = img;
		    else
			lasti->next = img;
		    lasti = img;
		}
	    } else
#endif
	    {
	    LogError(_("Image2 skipped as it uses an unsupported image type"));
	    const char* im2_terminator[] = { "EndImage2", 0 };
	    SFDConsumeUntil(sfd, im2_terminator);
	    }
	} else if ( strmatch(tok,"PickledData:")==0 ) {
	    if (current_layer < sc->layer_cnt) {
	      sc->layers[current_layer].python_persistent = SFDUnPickle(sfd, 0);
	      sc->layers[current_layer].python_persistent_has_lists = 0;
	    }
	} else if ( strmatch(tok,"PickledDataWithLists:")==0 ) {
	    if (current_layer < sc->layer_cnt) {
	      sc->layers[current_layer].python_persistent = SFDUnPickle(sfd, 1);
	      sc->layers[current_layer].python_persistent_has_lists = 1;
	    }
	} else if ( strmatch(tok,"OrigType1:")==0 ) {	/* Accept, slurp, ignore contents */
	    SFDGetType1(sfd);
	} else if ( strmatch(tok,"TtfInstrs:")==0 ) {	/* Binary format */
	    SFDGetTtfInstrs(sfd,sc);
	} else if ( strmatch(tok,"TtInstrs:")==0 ) {	/* ASCII format */
	    SFDGetTtInstrs(sfd,sc);
	} else if ( strmatch(tok,"Kerns2:")==0 ||
		strmatch(tok,"VKerns2:")==0 ) {
	    KernPair *kp, *last=NULL;
	    int isv = *tok=='V';
	    int off, index;
	    struct lookup_subtable *sub;

	    if ( sf->sfd_version<2 )
		LogError(_("Found an new style kerning pair inside a version 1 (or lower) sfd file.\n") );
	    while ( fscanf(sfd,"%d %d", &index, &off )==2 ) {
		sub = SFFindLookupSubtableAndFreeName(sf,SFDReadUTF7Str(sfd));
		if ( sub==NULL ) {
		    LogError(_("KernPair with no subtable name.\n"));
	    break;
		}
		kp = chunkalloc(sizeof(KernPair1));
		kp->sc = (SplineChar *) (intpt) index;
		kp->kcid = true;
		kp->off = off;
		kp->subtable = sub;
		kp->next = NULL;
		while ( (ch=nlgetc(sfd))==' ' );
		ungetc(ch,sfd);
		if ( ch=='{' ) {
		    kp->adjust = SFDReadDeviceTable(sfd, NULL);
		}
		if ( last != NULL )
		    last->next = kp;
		else if ( isv )
		    sc->vkerns = kp;
		else
		    sc->kerns = kp;
		last = kp;
	    }
	} else if ( strmatch(tok,"Kerns:")==0 ||
		strmatch(tok,"KernsSLI:")==0 ||
		strmatch(tok,"KernsSLIF:")==0 ||
		strmatch(tok,"VKernsSLIF:")==0 ||
		strmatch(tok,"KernsSLIFO:")==0 ||
		strmatch(tok,"VKernsSLIFO:")==0 ) {
	    KernPair1 *kp, *last=NULL;
	    int index, off, sli, flags=0;
	    int hassli = (strmatch(tok,"KernsSLI:")==0);
	    int isv = *tok=='V';
	    int has_orig = strstr(tok,"SLIFO:")!=NULL;
	    if ( sf->sfd_version>=2 ) {
		IError( "Found an old style kerning pair inside a version 2 (or higher) sfd file." );
exit(1);
	    }
	    if ( strmatch(tok,"KernsSLIF:")==0 || strmatch(tok,"KernsSLIFO:")==0 ||
		    strmatch(tok,"VKernsSLIF:")==0 || strmatch(tok,"VKernsSLIFO:")==0 )
		hassli=2;
	    while ( (hassli==1 && fscanf(sfd,"%d %d %d", &index, &off, &sli )==3) ||
		    (hassli==2 && fscanf(sfd,"%d %d %d %d", &index, &off, &sli, &flags )==4) ||
		    (hassli==0 && fscanf(sfd,"%d %d", &index, &off )==2) ) {
		if ( !hassli )
		    sli = SFFindBiggestScriptLangIndex(sli_sf,
			    script!=0?script:SCScriptFromUnicode(sc),DEFAULT_LANG);
		if ( sli>=((SplineFont1 *) sli_sf)->sli_cnt && sli!=SLI_NESTED) {
		    static int complained=false;
		    if ( !complained )
			IError("'%s' in %s has a script index out of bounds: %d",
				isv ? "vkrn" : "kern",
				sc->name, sli );
		    sli = SFFindBiggestScriptLangIndex(sli_sf,
			    SCScriptFromUnicode(sc),DEFAULT_LANG);
		    complained = true;
		}
		kp = chunkalloc(sizeof(KernPair1));
		kp->kp.sc = (SplineChar *) (intpt) index;
		kp->kp.kcid = has_orig;
		kp->kp.off = off;
		kp->sli = sli;
		kp->flags = flags;
		kp->kp.next = NULL;
		while ( (ch=nlgetc(sfd))==' ' );
		ungetc(ch,sfd);
		if ( ch=='{' ) {
		    kp->kp.adjust = SFDReadDeviceTable(sfd, NULL);
		}
		if ( last != NULL )
		    last->kp.next = (KernPair *) kp;
		else if ( isv )
		    sc->vkerns = (KernPair *) kp;
		else
		    sc->kerns = (KernPair *) kp;
		last = kp;
	    }
	} else if ( (ispos = (strmatch(tok,"Position:")==0)) ||
		( ispos  = (strmatch(tok,"Position2:")==0)) ||
		( ispair = (strmatch(tok,"PairPos:")==0)) ||
		( ispair = (strmatch(tok,"PairPos2:")==0)) ||
		( islcar = (strmatch(tok,"LCarets:")==0)) ||
		( islcar = (strmatch(tok,"LCarets2:")==0)) ||
		( isliga = (strmatch(tok,"Ligature:")==0)) ||
		( isliga = (strmatch(tok,"Ligature2:")==0)) ||
		( issubs = (strmatch(tok,"Substitution:")==0)) ||
		( issubs = (strmatch(tok,"Substitution2:")==0)) ||
		( ismult = (strmatch(tok,"MultipleSubs:")==0)) ||
		( ismult = (strmatch(tok,"MultipleSubs2:")==0)) ||
		strmatch(tok,"AlternateSubs:")==0 ||
		strmatch(tok,"AlternateSubs2:")==0 ) {
	    PST *pst;
	    int old, type;
	    type = ispos ? pst_position :
			 ispair ? pst_pair :
			 islcar ? pst_lcaret :
			 isliga ? pst_ligature :
			 issubs ? pst_substitution :
			 ismult ? pst_multiple :
			 pst_alternate;
	    if ( strchr(tok,'2')!=NULL ) {
		old = false;
		pst = chunkalloc(sizeof(PST));
		if ( type!=pst_lcaret )
		    pst->subtable = SFFindLookupSubtableAndFreeName(sf,SFDReadUTF7Str(sfd));
	    } else {
		old = true;
		pst = chunkalloc(sizeof(PST1));
		((PST1 *) pst)->tag = CHR('l','i','g','a');
		((PST1 *) pst)->script_lang_index = 0xffff;
		while ( (ch=nlgetc(sfd))==' ' || ch=='\t' );
		if ( isdigit(ch)) {
		    int temp;
		    ungetc(ch,sfd);
		    getint(sfd,&temp);
		    ((PST1 *) pst)->flags = temp;
		    while ( (ch=nlgetc(sfd))==' ' || ch=='\t' );
		} else
		    ((PST1 *) pst)->flags = 0 /*PSTDefaultFlags(type,sc)*/;
		if ( isdigit(ch)) {
		    ungetc(ch,sfd);
		    getusint(sfd,&((PST1 *) pst)->script_lang_index);
		    while ( (ch=nlgetc(sfd))==' ' || ch=='\t' );
		} else
		    ((PST1 *) pst)->script_lang_index = SFFindBiggestScriptLangIndex(sf,
			    script!=0?script:SCScriptFromUnicode(sc),DEFAULT_LANG);
		if ( ch=='\'' ) {
		    ungetc(ch,sfd);
		    ((PST1 *) pst)->tag = gettag(sfd);
		} else if ( ch=='<' ) {
		    getint(sfd,&temp);
		    ((PST1 *) pst)->tag = temp<<16;
		    nlgetc(sfd);	/* comma */
		    getint(sfd,&temp);
		    ((PST1 *) pst)->tag |= temp;
		    nlgetc(sfd);	/* close '>' */
		    ((PST1 *) pst)->macfeature = true;
		} else
		    ungetc(ch,sfd);
		if ( type==pst_lcaret ) {
		/* These are meaningless for lcarets, set them to innocuous values */
		    ((PST1 *) pst)->script_lang_index = SLI_UNKNOWN;
		    ((PST1 *) pst)->tag = CHR(' ',' ',' ',' ');
		} else if ( ((PST1 *) pst)->script_lang_index>=((SplineFont1 *) sli_sf)->sli_cnt && ((PST1 *) pst)->script_lang_index!=SLI_NESTED ) {
		    static int complained=false;
		    if ( !complained )
			IError("'%c%c%c%c' in %s has a script index out of bounds: %d",
				(((PST1 *) pst)->tag>>24), (((PST1 *) pst)->tag>>16)&0xff, (((PST1 *) pst)->tag>>8)&0xff, ((PST1 *) pst)->tag&0xff,
				sc->name, ((PST1 *) pst)->script_lang_index );
		    else
			IError( "'%c%c%c%c' in %s has a script index out of bounds: %d\n",
				(((PST1 *) pst)->tag>>24), (((PST1 *) pst)->tag>>16)&0xff, (((PST1 *) pst)->tag>>8)&0xff, ((PST1 *) pst)->tag&0xff,
				sc->name, ((PST1 *) pst)->script_lang_index );
		    ((PST1 *) pst)->script_lang_index = SFFindBiggestScriptLangIndex(sli_sf,
			    SCScriptFromUnicode(sc),DEFAULT_LANG);
		    complained = true;
		}
	    }
	    if ( (sf->sfd_version<2)!=old ) {
		IError( "Version mixup in PST of sfd file." );
exit(1);
	    }
	    if ( last==NULL )
		sc->possub = pst;
	    else
		last->next = pst;
	    last = pst;
	    pst->type = type;
	    if ( pst->type==pst_position ) {
		fscanf( sfd, " dx=%hd dy=%hd dh=%hd dv=%hd",
			&pst->u.pos.xoff, &pst->u.pos.yoff,
			&pst->u.pos.h_adv_off, &pst->u.pos.v_adv_off);
		pst->u.pos.adjust = SFDReadValDevTab(sfd);
		ch = nlgetc(sfd);		/* Eat new line */
	    } else if ( pst->type==pst_pair ) {
		getname(sfd,tok);
		pst->u.pair.paired = copy(tok);
		pst->u.pair.vr = chunkalloc(sizeof(struct vr [2]));
		fscanf( sfd, " dx=%hd dy=%hd dh=%hd dv=%hd",
			&pst->u.pair.vr[0].xoff, &pst->u.pair.vr[0].yoff,
			&pst->u.pair.vr[0].h_adv_off, &pst->u.pair.vr[0].v_adv_off);
		pst->u.pair.vr[0].adjust = SFDReadValDevTab(sfd);
		fscanf( sfd, " dx=%hd dy=%hd dh=%hd dv=%hd",
			&pst->u.pair.vr[1].xoff, &pst->u.pair.vr[1].yoff,
			&pst->u.pair.vr[1].h_adv_off, &pst->u.pair.vr[1].v_adv_off);
		pst->u.pair.vr[0].adjust = SFDReadValDevTab(sfd);
		ch = nlgetc(sfd);
	    } else if ( pst->type==pst_lcaret ) {
		int i;
		fscanf( sfd, " %d", &pst->u.lcaret.cnt );
		pst->u.lcaret.carets = malloc(pst->u.lcaret.cnt*sizeof(int16));
		for ( i=0; i<pst->u.lcaret.cnt; ++i )
		    fscanf( sfd, " %hd", &pst->u.lcaret.carets[i]);
		geteol(sfd,tok);
	    } else {
		geteol(sfd,tok);
		pst->u.lig.components = copy(tok);	/* it's in the same place for all formats */
		if ( isliga ) {
		    pst->u.lig.lig = sc;
		    if ( old )
			last = (PST *) LigaCreateFromOldStyleMultiple((PST1 *) pst);
		}
	    }
#ifdef FONTFORGE_CONFIG_CVT_OLD_MAC_FEATURES
	    if ( old )
		CvtOldMacFeature((PST1 *) pst);
#endif
	} else if ( strmatch(tok,"Colour:")==0 ) {
	    uint32 temp;
	    gethex(sfd,&temp);
	    sc->color = temp;
	} else if ( strmatch(tok,"Comment:")==0 ) {
	    sc->comment = SFDReadUTF7Str(sfd);
	} else if ( strmatch(tok,"Decomposition:")==0 ) {
	    char* decomp = SFDReadUTF7Str(sfd);
	    sc->user_decomp = utf82u_copy(decomp);
	    free(decomp);
	} else if ( strmatch(tok,"TileMargin:")==0 ) {
	    getreal(sfd,&sc->tile_margin);
	} else if ( strmatch(tok,"TileBounds:")==0 ) {
	    getreal(sfd,&sc->tile_bounds.minx);
	    getreal(sfd,&sc->tile_bounds.miny);
	    getreal(sfd,&sc->tile_bounds.maxx);
	    getreal(sfd,&sc->tile_bounds.maxy);
	} else if ( strmatch(tok,"EndChar")==0 ) {
	    if ( sc->orig_pos<sf->glyphcnt )
		sf->glyphs[sc->orig_pos] = sc;
            /* Recalculating hint active zones may be needed for old .sfd files. */
            /* Do this when we have finished with other glyph components, */
            /* so that splines are already available */
	    if ( sf->sfd_version<2 )
                SCGuessHintInstancesList( sc,ly_fore,sc->hstem,sc->vstem,sc->dstem,false,false );
            else if ( had_old_dstems && sc->layers[ly_fore].splines != NULL )
                SCGuessHintInstancesList( sc,ly_fore,NULL,NULL,sc->dstem,false,true );
	    if ( sc->layers[ly_fore].order2 )
		SCDefaultInterpolation(sc);
return( sc );
	} else {
	    geteol(sfd,tok);
	}
    }
}

Project: fontforge
File: sfd.c

char* FileToAllocatedString( FILE *f ) {
    char *ret, *buf;
    long fsize = 0;
    size_t bread = 0;

    /* get approximate file size, and allocate some memory */
    if ( fseek(f,0,SEEK_END)==0 && \
	 (fsize=ftell(f))!=-1   && \
	 fseek(f,0,SEEK_SET)==0 && \
	 (buf=calloc(fsize+30001,1))!=NULL ) {
	/* fread in file, size=non-exact, then resize memory smaller */
	bread=fread(buf,1,fsize+30000,f);
	if ( bread<=0 || bread >=(size_t)fsize+30000 || (ret=realloc(buf,bread+1))==NULL ) {
	    free( buf );
	} else {
	    ret[bread] = '\0';
	    return( ret );
	}
    }

    /* error occurred reading in file */
    fprintf(stderr,_("Failed to read a file. Bytes read:%ld file size:%ld\n"),(long)(bread),fsize );
    return( 0 );
}

Project: fontforge
File: sfd.c

static void SFDDumpImagePNG(FILE *sfd,ImageList *img) {
    struct enc85 enc = {0};
    char* pngbuf;
    size_t pnglen, i;

    if (!GImageWritePngBuf(img->image, &pngbuf, &pnglen, 1, false)) {
        IError("Failed to serialise PNG image");
        return;
    }

    fprintf(sfd, "Image2: image/png %d %g %g %g %g\n",
        (int)pnglen, (double) img->xoff, (double) img->yoff, (double) img->xscale, (double) img->yscale );

    enc.sfd = sfd;
    for (i = 0; i<pnglen; ++i) {
        SFDEnc85(&enc, pngbuf[i]);
    }
    free(pngbuf);

    SFDEnc85EndEnc(&enc);
    fprintf(sfd,"\nEndImage2\n" );
}

Project: fontforge
File: sfd.c

static void SFDDumpMathVertex(FILE *sfd,struct mathkernvertex *vert,const char *name) {
    int i;

    if ( vert==NULL || vert->cnt==0 )
return;

    fprintf( sfd, "%s %d ", name, vert->cnt );
    for ( i=0; i<vert->cnt; ++i ) {
	fprintf( sfd, " %d", vert->mkd[i].height );
	SFDDumpDeviceTable(sfd,vert->mkd[i].height_adjusts );
	fprintf( sfd, ",%d", vert->mkd[i].kern );
	SFDDumpDeviceTable(sfd,vert->mkd[i].kern_adjusts );
    }
    putc('\n',sfd );
}

Project: fontforge
File: sfd.c

char* SFDMoveToNextStartChar( FILE* sfd ) {
    char ret[2000];

    memset( ret, '\0', 2000 );
    char* line = 0;
    while((line = getquotedeol( sfd ))) {
	if( !strnmatch( line, "StartChar:", strlen( "StartChar:" ))) {
	    // FIXME: use the getname()/SFDReadUTF7Str() combo
	    // from SFDGetChar
	    int len = strlen("StartChar:");
	    while( line[len] && line[len] == ' ' )
		len++;
	    strcpy( ret, line+len );
	    free(line);
	    return copy(ret);
	}
	free(line);
	if(feof( sfd ))
	    break;

    }
    return 0;
}

Project: fontforge
File: sfd.c

void SFDFixupRefs(SplineFont *sf) {
    int i, isv;
    RefChar *refs, *rnext, *rprev;
    /*int isautorecovery = sf->changed;*/
    KernPair *kp, *prev, *next;
    EncMap *map = sf->map;
    int layer;
    int k,l;
    SplineFont *cidmaster = sf, *ksf;

    k = 1;
    if ( sf->subfontcnt!=0 )
	sf = sf->subfonts[0];

    ff_progress_change_line2(_("Interpreting Glyphs"));
    for (;;) {
	for ( i=0; i<sf->glyphcnt; ++i ) if ( sf->glyphs[i]!=NULL ) {
	    SplineChar *sc = sf->glyphs[i];
	    /* A changed character is one that has just been recovered */
	    /*  unchanged characters will already have been fixed up */
	    /* Er... maybe not. If the character being recovered is refered to */
	    /*  by another character then we need to fix up that other char too*/
	    /*if ( isautorecovery && !sc->changed )*/
	/*continue;*/
	    for ( layer = 0; layer<sc->layer_cnt; ++layer ) {
		rprev = NULL;
		for ( refs = sc->layers[layer].refs; refs!=NULL; refs=rnext ) {
		    rnext = refs->next;
		    if ( refs->encoded ) {		/* Old sfd format */
			if ( refs->orig_pos<map->encmax && map->map[refs->orig_pos]!=-1 )
			    refs->orig_pos = map->map[refs->orig_pos];
			else
			    refs->orig_pos = sf->glyphcnt;
			refs->encoded = false;
		    }
		    if ( refs->orig_pos<sf->glyphcnt && refs->orig_pos>=0 )
			refs->sc = sf->glyphs[refs->orig_pos];
		    if ( refs->sc!=NULL ) {
			refs->unicode_enc = refs->sc->unicodeenc;
			refs->adobe_enc = getAdobeEnc(refs->sc->name);
			rprev = refs;
			if ( refs->use_my_metrics ) {
			    if ( sc->width != refs->sc->width ) {
				LogError(_("Bad sfd file. Glyph %s has width %d even though it should be\n  bound to the width of %s which is %d.\n"),
					sc->name, sc->width, refs->sc->name, refs->sc->width );
				sc->width = refs->sc->width;
			    }
			}
		    } else {
			RefCharFree(refs);
			if ( rprev!=NULL )
			    rprev->next = rnext;
			else
			    sc->layers[layer].refs = rnext;
		    }
		}
	    }
	    /* In old sfd files we used a peculiar idiom to represent a multiply */
	    /*  encoded glyph. Fix it up now. Remove the fake glyph and adjust the*/
	    /*  map */
	    /*if ( isautorecovery && !sc->changed )*/
	/*continue;*/
	    for ( isv=0; isv<2; ++isv ) {
		for ( prev = NULL, kp=isv?sc->vkerns : sc->kerns; kp!=NULL; kp=next ) {
		    int index = (intpt) (kp->sc);

		    next = kp->next;
		    // be impotent if the reference is already to the correct location
                    if ( !kp->kcid ) {	/* It's encoded (old sfds), else orig */
                        if ( index>=map->encmax || map->map[index]==-1 )
                            index = sf->glyphcnt;
                        else
                            index = map->map[index];
                    }
                    kp->kcid = false;
                    ksf = sf;
                    if ( cidmaster!=sf ) {
                        for ( l=0; l<cidmaster->subfontcnt; ++l ) {
                            ksf = cidmaster->subfonts[l];
                            if ( index<ksf->glyphcnt && ksf->glyphs[index]!=NULL )
                                break;
                        }
                    }
                    if ( index>=ksf->glyphcnt || ksf->glyphs[index]==NULL ) {
                        IError( "Bad kerning information in glyph %s\n", sc->name );
                        kp->sc = NULL;
                    } else {
                        kp->sc = ksf->glyphs[index];
                    }

		    if ( kp->sc!=NULL )
			prev = kp;
		    else{
			if ( prev!=NULL )
			    prev->next = next;
			else if ( isv )
			    sc->vkerns = next;
			else
			    sc->kerns = next;
			chunkfree(kp,sizeof(KernPair));
		    }
		}
	    }
	    if ( SCDuplicate(sc)!=sc ) {
		SplineChar *base = SCDuplicate(sc);
		int orig = sc->orig_pos, enc = sf->map->backmap[orig], uni = sc->unicodeenc;
		SplineCharFree(sc);
		sf->glyphs[i]=NULL;
		sf->map->backmap[orig] = -1;
		sf->map->map[enc] = base->orig_pos;
		AltUniAdd(base,uni);
	    }
	}
	for ( i=0; i<sf->glyphcnt; ++i ) if ( sf->glyphs[i]!=NULL ) {
	    SplineChar *sc = sf->glyphs[i];
	    for ( layer=0; layer<sc->layer_cnt; ++layer ) {
		for ( refs = sf->glyphs[i]->layers[layer].refs; refs!=NULL; refs=refs->next ) {
		    SFDFixupRef(sf->glyphs[i],refs,layer);
		}
	    }
	    ff_progress_next();
	}
	if ( sf->cidmaster==NULL )
	    for ( i=sf->glyphcnt-1; i>=0 && sf->glyphs[i]==NULL; --i )
		sf->glyphcnt = i;
	if ( k>=cidmaster->subfontcnt )
    break;
	sf = cidmaster->subfonts[k++];
    }
}

Project: fontforge
File: sfd.c

static uint32 gettag(FILE *sfd) {
    int ch, quoted;
    uint32 tag;

    while ( (ch=nlgetc(sfd))==' ' );
    if ( (quoted = (ch=='\'')) ) ch = nlgetc(sfd);
    tag = (ch<<24)|(nlgetc(sfd)<<16);
    tag |= nlgetc(sfd)<<8;
    tag |= nlgetc(sfd);
    if ( quoted ) (void) nlgetc(sfd);
return( tag );
}

Project: fontforge
File: sfd.c

static void SFD_DoAltUnis(SplineFont *sf) {
    int i;
    struct altuni *alt;
    SplineChar *sc;

    for ( i=0; i<sf->glyphcnt; ++i ) if ( (sc = sf->glyphs[i])!=NULL ) {
	for ( alt = sc->altuni; alt!=NULL; alt = alt->next ) {
	    if ( alt->vs==-1 && alt->fid==0 ) {
		int enc = EncFromUni(alt->unienc,sf->map->enc);
		if ( enc!=-1 )
		    SFDSetEncMap(sf,sc->orig_pos,enc);
	    }
	}
    }
}

Project: fontforge
File: sfd1.c

static void ACDisassociateLigatures(SplineFont1 *sf,AnchorClass1 *ac) {
    int gid,k;
    SplineFont1 *subsf;
    SplineChar *sc;
    AnchorPoint *ap, *lap;
    AnchorClass1 *lac;
    char *format;

    lac = chunkalloc(sizeof(AnchorClass1));
    *lac = *ac;
    lac->ac.type = act_mklg;
    ac->ac.next = (AnchorClass *) lac;

  /* GT: Need to split some AnchorClasses into two classes, one for normal */
  /* GT:  base letters, and one for ligatures. So create a new AnchorClass */
  /* GT:  name for the ligature version */
    format = _("Ligature %s");
    lac->ac.name = malloc(strlen(ac->ac.name)+strlen(format)+1);
    sprintf( lac->ac.name, format, ac->ac.name );

    k=0;
    do {
	subsf = sf->sf.subfontcnt==0 ? sf : (SplineFont1 *) (sf->sf.subfonts[k]);
	for ( gid=0; gid<subsf->sf.glyphcnt; ++gid ) if ( (sc=subsf->sf.glyphs[gid])!=NULL ) {
	    for ( ap=sc->anchor; ap!=NULL; ap=ap->next ) {
		if ( ap->anchor!=(AnchorClass *) ac )
	    continue;
		if ( ap->type==at_mark ) {
		    lap = chunkalloc(sizeof(AnchorPoint));
		    *lap = *ap;
		    ap->next = lap;
		    lap->anchor = (AnchorClass *) lac;
		} else if ( ap->type==at_baselig ) {
		    ap->anchor = (AnchorClass *) lac;
		}
	    }
	}
	++k;
    } while ( k<sf->sf.subfontcnt );
}

Project: fontforge
File: sfd.c

static void SFDDumpDHintList( FILE *sfd,const char *key, DStemInfo *d ) {
    HintInstance *hi;

    if ( d==NULL )
return;
    fprintf(sfd, "%s", key );
    for ( ; d!=NULL; d=d->next ) {
	fprintf(sfd, "%g %g %g %g %g %g",
		(double) d->left.x, (double) d->left.y,
		(double) d->right.x, (double) d->right.y,
		(double) d->unit.x, (double) d->unit.y );
	if ( d->where!=NULL ) {
	    putc('<',sfd);
	    for ( hi=d->where; hi!=NULL; hi=hi->next )
		fprintf(sfd, "%g %g%c", (double) hi->begin, (double) hi->end, hi->next?' ':'>');
	}
	putc(d->next?' ':'\n',sfd);
    }
}

Project: fontforge
File: sfd.c

static int SFDGetBitmapReference(FILE *sfd,BDFFont *bdf) {
    BDFChar *bc;
    BDFRefChar *ref, *head;
    int gid, rgid, xoff, yoff;
    char ch;

    /* 'BDFRefChar:' elements should not occur in the file before the corresponding */
    /* 'BDFChar:'. However it is possible that the glyphs they refer to are not yet */
    /* available. So we will find them later */
    if ( getint(sfd,&gid)!=1 || gid<=0 || gid >= bdf->glyphcnt || ( bc = bdf->glyphs[gid] ) == NULL )
return( 0 );
    if ( getint(sfd,&rgid)!=1 || rgid<0 )
return( 0 );
    if ( getint(sfd,&xoff)!=1 )
return( 0 );
    if ( getint(sfd,&yoff)!=1 )
return( 0 );
    while ( isspace( ch=nlgetc( sfd )) && ch!='\r' && ch!='\n' );

    ref = calloc( 1,sizeof( BDFRefChar ));
    ref->gid = rgid; ref->xoff = xoff, ref->yoff = yoff;
    if ( ch == 'S' ) ref->selected = true;
    for ( head = bc->refs; head != NULL && head->next!=NULL; head = head->next );
    if ( head == NULL ) bc->refs = ref;
    else head->next = ref;
return( 1 );
}

Project: fontforge
File: sfd1.c

static int SFAddScriptLangIndex(SplineFont *_sf,uint32 script,uint32 lang) {
    int i;
    SplineFont1 *sf;

    if ( _sf->cidmaster ) _sf = _sf->cidmaster;
    else if ( _sf->mm!=NULL ) _sf=_sf->mm->normal;

    if ( _sf->sfd_version>=2 )
	IError( "SFFindBiggestScriptLangIndex called with bad version number.\n" );

    sf = (SplineFont1 *) _sf;

    if ( script==0 ) script=DEFAULT_SCRIPT;
    if ( lang==0 ) lang=DEFAULT_LANG;
    if ( sf->script_lang==NULL )
	sf->script_lang = calloc(2,sizeof(struct script_record *));
    for ( i=0; sf->script_lang[i]!=NULL; ++i ) {
	if ( sf->script_lang[i][0].script==script && sf->script_lang[i][1].script==0 &&
		sf->script_lang[i][0].langs[0]==lang &&
		sf->script_lang[i][0].langs[1]==0 )
return( i );
    }
    sf->script_lang = realloc(sf->script_lang,(i+2)*sizeof(struct script_record *));
    sf->script_lang[i] = calloc(2,sizeof(struct script_record));
    sf->script_lang[i][0].script = script;
    sf->script_lang[i][0].langs = malloc(2*sizeof(uint32));
    sf->script_lang[i][0].langs[0] = lang;
    sf->script_lang[i][0].langs[1] = 0;
    sf->script_lang[i+1] = NULL;
    sf->sli_cnt = i+1;
return( i );
}

Project: fontforge
File: sfd1.c

static FeatureScriptLangList *FeaturesFromTagSli(uint32 tag,int sli,SplineFont1 *sf) {
    FeatureScriptLangList *fl;
    struct script_record *sr;
    struct scriptlanglist *cur, *last;
    int i;

    fl = chunkalloc(sizeof(FeatureScriptLangList));
    fl->featuretag = tag;
    if ( sli==SLI_NESTED || sli<0 || sli>=sf->sli_cnt )
return( fl );
    last = NULL;
    for ( sr = sf->script_lang[sli]; sr->script!=0; ++sr ) {
	cur = chunkalloc(sizeof(struct scriptlanglist));
	cur->script = sr->script;
	for ( i=0; sr->langs[i]!=0; ++i );
	cur->lang_cnt = i;
	if ( i>MAX_LANG )
	    cur->morelangs = malloc((i-MAX_LANG) * sizeof(uint32));
	for ( i=0; sr->langs[i]!=0; ++i ) {
	    if ( i<MAX_LANG )
		cur->langs[i] = sr->langs[i];
	    else
		cur->morelangs[i-MAX_LANG] = sr->langs[i];
	}
	if ( last==NULL )
	    fl->scripts = cur;
	else
	    last->next = cur;
	last = cur;
    }
return( fl );
}

Project: fontforge
File: sfd.c

static void SFFinalDirClean(char *filename) {
    DIR *dir;
    struct dirent *ent;
    char *buffer, *markerfile, *pt;

    /* we did not unlink sub-directories in case they contained version control */
    /*  files. We did remove all our files from them, however.  If the user */
    /*  removed a bitmap strike or a cid-subfont those sub-dirs will now be */
    /*  empty. If the user didn't remove them then they will contain our marker */
    /*  files. So if we find a subdir with no marker files in it, remove it */
    dir = opendir(filename);
    if ( dir==NULL )
return;
    buffer = malloc(strlen(filename)+1+NAME_MAX+1);
    markerfile = malloc(strlen(filename)+2+2*NAME_MAX+1);
    while ( (ent = readdir(dir))!=NULL ) {
	if ( strcmp(ent->d_name,".")==0 || strcmp(ent->d_name,"..")==0 )
    continue;
	pt = strrchr(ent->d_name,EXT_CHAR);
	if ( pt==NULL )
    continue;
	sprintf( buffer,"%s/%s", filename, ent->d_name );
	if ( strcmp(pt,".strike")==0 ||
		strcmp(pt,SUBFONT_EXT)==0 ||
		strcmp(pt,INSTANCE_EXT)==0 ) {
	    if ( strcmp(pt,".strike")==0 )
		sprintf( markerfile,"%s/" STRIKE_PROPS, buffer );
	    else
		sprintf( markerfile,"%s/" FONT_PROPS, buffer );
	    if ( !GFileExists(markerfile)) {
		GFileRemove(buffer, false);
	    }
	}
    }
    free(buffer);
    free(markerfile);
    closedir(dir);
}

Project: fontforge
File: sfd.c

static struct ttflangname *SFDGetLangName(FILE *sfd,struct ttflangname *old) {
    struct ttflangname *cur = chunkalloc(sizeof(struct ttflangname)), *prev;
    int i;

    getint(sfd,&cur->lang);
    for ( i=0; i<ttf_namemax; ++i )
	cur->names[i] = SFDReadUTF7Str(sfd);
    if ( old==NULL )
return( cur );
    for ( prev = old; prev->next !=NULL; prev = prev->next );
    prev->next = cur;
return( old );
}

Project: fontforge
File: sfd.c

static ValDevTab *SFDReadValDevTab(FILE *sfd) {
    int i, j, ch;
    ValDevTab vdt;
    char buf[4];

    memset(&vdt,0,sizeof(vdt));
    buf[3] = '\0';
    while ( (ch=nlgetc(sfd))==' ' );
    if ( ch=='[' ) {
	for ( i=0; i<4; ++i ) {
	    while ( (ch=nlgetc(sfd))==' ' );
	    if ( ch==']' )
	break;
	    buf[0]=ch;
	    for ( j=1; j<3; ++j ) buf[j]=nlgetc(sfd);
	    while ( (ch=nlgetc(sfd))==' ' );
	    if ( ch!='=' ) ungetc(ch,sfd);
	    SFDReadDeviceTable(sfd,
		    strcmp(buf,"ddx")==0 ? &vdt.xadjust :
		    strcmp(buf,"ddy")==0 ? &vdt.yadjust :
		    strcmp(buf,"ddh")==0 ? &vdt.xadv :
		    strcmp(buf,"ddv")==0 ? &vdt.yadv :
			(&vdt.xadjust) + i );
	    while ( (ch=nlgetc(sfd))==' ' );
	    if ( ch!=']' ) ungetc(ch,sfd);
	    else
	break;
	}
	if ( vdt.xadjust.corrections!=NULL || vdt.yadjust.corrections!=NULL ||
		vdt.xadv.corrections!=NULL || vdt.yadv.corrections!=NULL ) {
	    ValDevTab *v = chunkalloc(sizeof(ValDevTab));
	    *v = vdt;
return( v );
	}
    } else
	ungetc(ch,sfd);
return( NULL );
}

Project: fontforge
File: sfd.c

static void SFDGetType1(FILE *sfd) {
    /* We've read the OrigType1 token (this is now obselete, but parse it in case there are any old sfds) */
    int len;
    struct enc85 dec;

    memset(&dec,'\0', sizeof(dec)); dec.pos = -1;
    dec.sfd = sfd;

    getint(sfd,&len);
    while ( --len >= 0 )
	Dec85(&dec);
}

Project: fontforge
File: sfd.c

static void SFDDumpSplineSet(FILE *sfd, SplineSet *spl, int want_order2) {
    SplinePoint *first, *sp;
    // If there's no spline structure there should just be a single point,
    // which is compatible with either order and therefore want_order2
    int order2 = spl->first->next!=NULL ? spl->first->next->order2 : want_order2;
    int reduce = (want_order2 && !order2);
    if (order2 && !want_order2)
	IError("Asked for cubic when had quadratic");
    SplineSet *nspl;

    for ( ; spl!=NULL; spl=spl->next ) {
	if (reduce) {
	    nspl = SSttfApprox(spl);
	    order2 = true;
	} else {
	    nspl = spl;
	}
	first = NULL;
	for ( sp = nspl->first; ; sp=sp->next->to ) {
#ifndef FONTFORGE_CONFIG_USE_DOUBLE
	    if ( first==NULL )
		fprintf( sfd, "%g %g m ", (double) sp->me.x, (double) sp->me.y );
	    else if ( sp->prev->islinear && sp->noprevcp )		/* Don't use known linear here. save control points if there are any */
		fprintf( sfd, " %g %g l ", (double) sp->me.x, (double) sp->me.y );
	    else
		fprintf( sfd, " %g %g %g %g %g %g c ",
			(double) sp->prev->from->nextcp.x, (double) sp->prev->from->nextcp.y,
			(double) sp->prevcp.x, (double) sp->prevcp.y,
			(double) sp->me.x, (double) sp->me.y );
#else
	    if ( first==NULL )
		fprintf( sfd, "%.12g %.12g m ", (double) sp->me.x, (double) sp->me.y );
	    else if ( sp->prev->islinear && sp->noprevcp )		/* Don't use known linear here. save control points if there are any */
		fprintf( sfd, " %.12g %.12g l ", (double) sp->me.x, (double) sp->me.y );
	    else
		fprintf( sfd, " %.12g %.12g %.12g %.12g %.12g %.12g c ",
			(double) sp->prev->from->nextcp.x, (double) sp->prev->from->nextcp.y,
			(double) sp->prevcp.x, (double) sp->prevcp.y,
			(double) sp->me.x, (double) sp->me.y );
#endif
	    int ptflags = 0;
	    ptflags = sp->pointtype|(sp->selected<<2)|
		(sp->nextcpdef<<3)|(sp->prevcpdef<<4)|
		(sp->roundx<<5)|(sp->roundy<<6)|
		(sp->ttfindex==0xffff?(1<<7):0)|
		(sp->dontinterpolate<<8)|
		((sp->prev && sp->prev->acceptableextrema)<<9);

	    // Last point in the splineset, and we are an open path.
	    if( !sp->next
		&& spl->first && !spl->first->prev )
	    {
		ptflags |= SFD_PTFLAG_FORCE_OPEN_PATH;
	    }


	    fprintf(sfd, "%d", ptflags );
	    if ( order2 ) {
		if ( sp->ttfindex!=0xfffe && sp->nextcpindex!=0xfffe ) {
		    putc(',',sfd);
		    if ( sp->ttfindex==0xffff )
			fprintf(sfd,"-1");
		    else if ( sp->ttfindex!=0xfffe )
			fprintf(sfd,"%d",sp->ttfindex);
		    if ( sp->nextcpindex==0xffff )
			fprintf(sfd,",-1");
		    else if ( sp->nextcpindex!=0xfffe )
			fprintf(sfd,",%d",sp->nextcpindex);
		}
	    } else {
		if ( sp->hintmask!=NULL ) {
		    putc('x',sfd);
		    SFDDumpHintMask(sfd, sp->hintmask);
		}
	    }
	    putc('\n',sfd);
	    if (sp->name != NULL) {
		fputs("NamedP: ", sfd);
		SFDDumpUTF7Str(sfd, sp->name);
		putc('\n', sfd);
	    }
	    if ( sp==first )
	break;
	    if ( first==NULL ) first = sp;
	    if ( sp->next==NULL )
	break;
	}
	if ( spl->spiro_cnt!=0 ) {
	    int i;
	    fprintf( sfd, "  Spiro\n" );
	    for ( i=0; i<spl->spiro_cnt; ++i ) {
		fprintf( sfd, "    %g %g %c\n", spl->spiros[i].x, spl->spiros[i].y,
			    spl->spiros[i].ty&0x7f);
	    }
	    fprintf( sfd, "  EndSpiro\n" );
	}
	if ( spl->contour_name!=NULL ) {
	    fprintf( sfd, "  Named: " );
	    SFDDumpUTF7Str(sfd,spl->contour_name);
	    putc('\n',sfd);
	}
	if ( spl->is_clip_path ) {
	    fprintf( sfd, "  PathFlags: %d\n", spl->is_clip_path );
	}
	if ( spl->start_offset ) {
	    fprintf( sfd, "  PathStart: %d\n", spl->start_offset );
	}
    if (reduce) SplinePointListFree(nspl);
    }
    fprintf( sfd, "EndSplineSet\n" );
}

Project: fontforge
File: sfd.c

static int getusint(FILE *sfd, uint16 *val) {
    int val2;
    int ret = getint(sfd,&val2);
    *val = val2;
return( ret );
}

Project: fontforge
File: sfd.c

static StemInfo *SFDReadHints(FILE *sfd) {
    StemInfo *head=NULL, *last=NULL, *cur;
    real start, width;

    while ( getreal(sfd,&start)==1 && getreal(sfd,&width)) {
	cur = chunkalloc(sizeof(StemInfo));
	cur->start = start;
	cur->width = width;
	cur->where = SFDReadHintInstances(sfd,cur);
	if ( head == NULL )
	    head = cur;
	else
	    last->next = cur;
	last = cur;
    }
return( head );
}

Project: fontforge
File: sfd.c

static void CvtOldMacFeature(PST1 *pst) {
    int i;

    if ( pst->macfeature )
return;
    for ( i=0; formertags[i].feature!=-1 ; ++i ) {
	if ( pst->tag == formertags[i].tag ) {
	    pst->macfeature = true;
	    pst->tag = (formertags[i].feature<<16) | formertags[i].setting;
return;
	}
    }
}

Project: fontforge
File: sfd.c

void SFTimesFromFile(SplineFont *sf,FILE *file) {
    struct stat b;
    if ( fstat(fileno(file),&b)!=-1 ) {
	sf->modificationtime = GetST_MTime(b);
	sf->creationtime = GetST_MTime(b);
    }
}

Project: fontforge
File: sfd.c

static AnchorPoint *SFDReadAnchorPoints(FILE *sfd,SplineChar *sc,AnchorPoint** alist, AnchorPoint *lastap)
{
    AnchorPoint *ap = chunkalloc(sizeof(AnchorPoint));
    AnchorClass *an;
    char *name;
    char tok[200];
    int ch;

    name = SFDReadUTF7Str(sfd);
    if ( name==NULL ) {
	LogError(_("Anchor Point with no class name: %s"), sc->name );
	AnchorPointsFree(ap);
return( lastap );
    }
    for ( an=sc->parent->anchor; an!=NULL && strcmp(an->name,name)!=0; an=an->next );
    free(name);
    ap->anchor = an;
    getreal(sfd,&ap->me.x);
    getreal(sfd,&ap->me.y);
    ap->type = -1;
    if ( getname(sfd,tok)==1 ) {
	if ( strcmp(tok,"mark")==0 )
	    ap->type = at_mark;
	else if ( strcmp(tok,"basechar")==0 )
	    ap->type = at_basechar;
	else if ( strcmp(tok,"baselig")==0 )
	    ap->type = at_baselig;
	else if ( strcmp(tok,"basemark")==0 )
	    ap->type = at_basemark;
	else if ( strcmp(tok,"entry")==0 )
	    ap->type = at_centry;
	else if ( strcmp(tok,"exit")==0 )
	    ap->type = at_cexit;
    }
    getsint(sfd,&ap->lig_index);
    ch = nlgetc(sfd);
    ungetc(ch,sfd);
    if ( ch==' ' ) {
	SFDReadDeviceTable(sfd,&ap->xadjust);
	SFDReadDeviceTable(sfd,&ap->yadjust);
	ch = nlgetc(sfd);
	ungetc(ch,sfd);
	if ( isdigit(ch)) {
	    getsint(sfd,(int16 *) &ap->ttf_pt_index);
	    ap->has_ttf_pt = true;
	}
    }
    if ( ap->anchor==NULL || ap->type==-1 ) {
	LogError(_("Bad Anchor Point: %s"), sc->name );
	AnchorPointsFree(ap);
return( lastap );
    }
    if ( lastap==NULL )
	(*alist) = ap;
    else
	lastap->next = ap;

    return( ap );
}

Project: fontforge
File: sfd.c

static char *SFDReadUTF7Str(FILE *sfd) {
    char *buffer = NULL, *pt, *end = NULL;
    int ch1, ch2, ch3, ch4, done, c;
    int prev_cnt=0, prev=0, in=0;

    ch1 = nlgetc(sfd);
    while ( isspace(ch1) && ch1!='\n' && ch1!='\r') ch1 = nlgetc(sfd);
    if ( ch1=='\n' || ch1=='\r' )
	ungetc(ch1,sfd);
    if ( ch1!='"' )
return( NULL );
    pt = 0;
    while ( (ch1=nlgetc(sfd))!=EOF && ch1!='"' ) {
	done = 0;
	if ( !done && !in ) {
	    if ( ch1=='+' ) {
		ch1 = nlgetc(sfd);
		if ( ch1=='-' ) {
		    ch1 = '+';
		    done = true;
		} else {
		    in = true;
		    prev_cnt = 0;
		}
	    } else
		done = true;
	}
	if ( !done ) {
	    if ( ch1=='-' ) {
		in = false;
	    } else if ( inbase64[ch1]==-1 ) {
		in = false;
		done = true;
	    } else {
		ch1 = inbase64[ch1];
		ch2 = inbase64[c = nlgetc(sfd)];
		if ( ch2==-1 ) {
		    ungetc(c, sfd);
		    ch2 = ch3 = ch4 = 0;
		} else {
		    ch3 = inbase64[c = nlgetc(sfd)];
		    if ( ch3==-1 ) {
			ungetc(c, sfd);
			ch3 = ch4 = 0;
		    } else {
			ch4 = inbase64[c = nlgetc(sfd)];
			if ( ch4==-1 ) {
			    ungetc(c, sfd);
			    ch4 = 0;
			}
		    }
		}
		ch1 = (ch1<<18) | (ch2<<12) | (ch3<<6) | ch4;
		if ( prev_cnt==0 ) {
		    prev = ch1&0xff;
		    ch1 >>= 8;
		    prev_cnt = 1;
		} else /* if ( prev_cnt == 1 ) */ {
		    ch1 |= (prev<<24);
		    prev = (ch1&0xffff);
		    ch1 = (ch1>>16)&0xffff;
		    prev_cnt = 2;
		}
		done = true;
	    }
	}
	if ( pt+10>=end ) {
	    if ( buffer==NULL ) {
		pt = buffer = malloc(400);
		end = buffer+400;
	    } else if (pt) {
		char *temp = realloc(buffer,end-buffer+400);
		pt = temp+(pt-buffer);
		end = temp+(end-buffer+400);
		buffer = temp;
	    }
	}
	if ( pt && done )
	    pt = utf8_idpb(pt,ch1,0);
	if ( prev_cnt==2 ) {
	    prev_cnt = 0;
	    if ( pt && prev!=0 )
		pt = utf8_idpb(pt,prev,0);
	}
	if ( pt==0 ) {
	    free(buffer);
	    return( NULL );
	}
    }
    if ( buffer==NULL )
return( NULL );
    *pt = '\0';
    pt = copy(buffer);
    free(buffer );
return( pt );
}

Project: fontforge
File: sfd.c

FILE* MakeTemporaryFile(void) {
    FILE *ret = NULL;

#ifndef __MINGW32__
    gchar *loc;
    int fd = g_file_open_tmp("fontforge-XXXXXX", &loc, NULL);

    if (fd != -1) {
        ret = fdopen(fd, "w+");
        g_unlink(loc);
        g_free(loc);
    }
#else
    HANDLE hFile = INVALID_HANDLE_VALUE;
    for (int retries = 0; hFile == INVALID_HANDLE_VALUE && retries < 10; retries++) {
        wchar_t *temp = _wtempnam(NULL, L"FontForge");
        hFile = CreateFileW(temp, GENERIC_READ|GENERIC_WRITE, 0, NULL,
            CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE, NULL);
        free(temp);
    }
    ret = _fdopen(_open_osfhandle((intptr_t)hFile, 0), "wb+");
    if (ret == NULL && hFile != INVALID_HANDLE_VALUE) {
        CloseHandle(hFile);
    }
#endif
    return ret;
}

Project: fontforge
File: sfd.c

static int SFD_MMDump(FILE *sfd,SplineFont *sf,EncMap *map,EncMap *normal,
	int todir, char *dirname) {
    MMSet *mm = sf->mm;
    int max, i, j;
    int err = false;

    fprintf( sfd, "MMCounts: %d %d %d %d\n", mm->instance_count, mm->axis_count,
	    mm->apple, mm->named_instance_count );
    fprintf( sfd, "MMAxis:" );
    for ( i=0; i<mm->axis_count; ++i )
	fprintf( sfd, " %s", mm->axes[i]);
    putc('\n',sfd);
    fprintf( sfd, "MMPositions:" );
    for ( i=0; i<mm->axis_count*mm->instance_count; ++i )
	fprintf( sfd, " %g", (double) mm->positions[i]);
    putc('\n',sfd);
    fprintf( sfd, "MMWeights:" );
    for ( i=0; i<mm->instance_count; ++i )
	fprintf( sfd, " %g", (double) mm->defweights[i]);
    putc('\n',sfd);
    for ( i=0; i<mm->axis_count; ++i ) {
	fprintf( sfd, "MMAxisMap: %d %d", i, mm->axismaps[i].points );
	for ( j=0; j<mm->axismaps[i].points; ++j )
	    fprintf( sfd, " %g=>%g", (double) mm->axismaps[i].blends[j], (double) mm->axismaps[i].designs[j]);
	fputc('\n',sfd);
	SFDDumpMacName(sfd,mm->axismaps[i].axisnames);
    }
    if ( mm->cdv!=NULL ) {
	fprintf( sfd, "MMCDV:\n" );
	fputs(mm->cdv,sfd);
	fprintf( sfd, "\nEndMMSubroutine\n" );
    }
    if ( mm->ndv!=NULL ) {
	fprintf( sfd, "MMNDV:\n" );
	fputs(mm->ndv,sfd);
	fprintf( sfd, "\nEndMMSubroutine\n" );
    }
    for ( i=0; i<mm->named_instance_count; ++i ) {
	fprintf( sfd, "MMNamedInstance: %d ", i );
	for ( j=0; j<mm->axis_count; ++j )
	    fprintf( sfd, " %g", (double) mm->named_instances[i].coords[j]);
	fputc('\n',sfd);
	SFDDumpMacName(sfd,mm->named_instances[i].names);
    }

    if ( todir ) {
	for ( i=0; i<mm->instance_count; ++i )
	    err |= SFD_MIDump(mm->instances[i],map,dirname,i+1);
	err |= SFD_MIDump(mm->normal,map,dirname,0);
    } else {
	for ( i=max=0; i<mm->instance_count; ++i )
	    if ( max<mm->instances[i]->glyphcnt )
		max = mm->instances[i]->glyphcnt;
	fprintf(sfd, "BeginMMFonts: %d %d\n", mm->instance_count+1, max );
	for ( i=0; i<mm->instance_count; ++i )
	    SFD_Dump(sfd,mm->instances[i],map,normal,todir,dirname);
	SFD_Dump(sfd,mm->normal,map,normal,todir,dirname);
    }
    fprintf(sfd, "EndMMFonts\n" );
return( err );
}

Project: fontforge
File: sfd.c

static int Dec85(struct enc85 *dec) {
    int ch1, ch2, ch3, ch4, ch5;
    unsigned int val;

    if ( dec->pos<0 ) {
	while ( isspace(ch1=getc(dec->sfd)));
	if ( ch1=='z' ) {
	    dec->sofar[0] = dec->sofar[1] = dec->sofar[2] = dec->sofar[3] = 0;
	    dec->pos = 3;
	} else {
	    while ( isspace(ch2=getc(dec->sfd)));
	    while ( isspace(ch3=getc(dec->sfd)));
	    while ( isspace(ch4=getc(dec->sfd)));
	    while ( isspace(ch5=getc(dec->sfd)));
	    val = ((((ch1-'!')*85+ ch2-'!')*85 + ch3-'!')*85 + ch4-'!')*85 + ch5-'!';
	    dec->sofar[3] = val>>24;
	    dec->sofar[2] = val>>16;
	    dec->sofar[1] = val>>8;
	    dec->sofar[0] = val;
	    dec->pos = 3;
	}
    }
return( dec->sofar[dec->pos--] );
}

Project: fontforge
File: sfd.c

static void SFDFixupBitmapRefs( BDFFont *bdf ) {
    BDFChar *bc, *rbc;
    BDFRefChar *head, *next, *prev;
    int i;

    for ( i=0; i<bdf->glyphcnt; i++ ) if (( bc = bdf->glyphs[i] ) != NULL ) {
	prev = NULL;
	for ( head = bc->refs; head != NULL; head = next ) {
	    next = head->next;
	    if (( rbc = bdf->glyphs[head->gid] ) != NULL ) {
		head->bdfc = rbc;
		BCMakeDependent( bc,rbc );
		prev = head;
	    } else {
		LogError(_("Glyph %d in bitmap strike %d pixels refers to a missing glyph (%d)"),
		    bc->orig_pos, bdf->pixelsize, head->gid );
		if ( prev == NULL ) bc->refs = next;
		else prev->next = next;
	    }
	}
    }

}

Project: fontforge
File: sfd.c

MacFeat *SFDParseMacFeatures(FILE *sfd, char *tok) {
    MacFeat *cur, *head=NULL, *last=NULL;
    struct macsetting *slast, *scur;
    int feat, ism, def, set;

    while ( strcmp(tok,"MacFeat:")==0 ) {
	cur = chunkalloc(sizeof(MacFeat));
	if ( last==NULL )
	    head = cur;
	else
	    last->next = cur;
	last = cur;

	getint(sfd,&feat); getint(sfd,&ism); getint(sfd, &def);
	cur->feature = feat; cur->ismutex = ism; cur->default_setting = def;
	getname(sfd,tok);
	cur->featname = SFDParseMacNames(sfd,tok);
	slast = NULL;
	while ( strcmp(tok,"MacSetting:")==0 ) {
	    scur = chunkalloc(sizeof(struct macsetting));
	    if ( slast==NULL )
		cur->settings = scur;
	    else
		slast->next = scur;
	    slast = scur;

	    getint(sfd,&set);
	    scur->setting = set;
	    getname(sfd,tok);
	    scur->setname = SFDParseMacNames(sfd,tok);
	}
    }
return( head );
}

Project: fontforge
File: sfd.c

static void SFDDumpHintList(FILE *sfd,const char *key, StemInfo *h) {
    HintInstance *hi;

    if ( h==NULL )
return;
    fprintf(sfd, "%s", key );
    for ( ; h!=NULL; h=h->next ) {
	fprintf(sfd, "%g %g", (double) h->start,(double) h->width );
	if ( h->ghost ) putc('G',sfd);
	if ( h->where!=NULL ) {
	    putc('<',sfd);
	    for ( hi=h->where; hi!=NULL; hi=hi->next )
		fprintf(sfd, "%g %g%c", (double) hi->begin, (double) hi->end, hi->next?' ':'>');
	}
	putc(h->next?' ':'\n',sfd);
    }
}

Project: fontforge
File: sfd.c

char *getquotedeol(FILE *sfd) {
    char *pt, *str, *end;
    int ch;

    pt = str = malloc(101); end = str+100;
    while ( isspace(ch = nlgetc(sfd)) && ch!='\r' && ch!='\n' );
    while ( ch!='\n' && ch!='\r' && ch!=EOF ) {
	if ( ch=='\\' ) {
	    /* We can't use nlgetc() here, because it would misinterpret */
	    /* double backslash at the end of line. Multiline strings,   */
	    /* broken with backslash + newline, are just handled above.  */
	    ch = getc(sfd);
	    if ( ch=='n' ) ch='\n';
	    /* else if ( ch=='\\' ) ch=='\\'; */ /* second backslash of '\\' */

	    /* FontForge doesn't write other escape sequences in this context. */
	    /* So any other value of ch is assumed impossible. */
	}
	if ( pt>=end ) {
	    pt = realloc(str,end-str+101);
	    end = pt+(end-str)+100;
	    str = pt;
	    pt = end-100;
	}
	*pt++ = ch;
	ch = nlgetc(sfd);
    }
    *pt='\0';
    /* these strings should be in utf8 now, but some old sfd files might have */
    /* latin1. Not a severe problems because they SHOULD be in ASCII. So any */
    /* non-ascii strings are erroneous anyway */
    if ( !utf8_valid(str) ) {
	pt = latin1_2_utf8_copy(str);
	free(str);
	str = pt;
    }
return( str );
}

Project: fontforge
File: sfd.c

static void SFRemoveDependencies(SplineFont *sf) {
    int i;
    struct splinecharlist *dlist, *dnext;
    KernPair *kp;

    for ( i=0; i<sf->glyphcnt; ++i ) if ( sf->glyphs[i]!=NULL ) {
	for ( dlist = sf->glyphs[i]->dependents; dlist!=NULL; dlist = dnext ) {
	    dnext = dlist->next;
	    chunkfree(dlist,sizeof(*dlist));
	}
	sf->glyphs[i]->dependents = NULL;
	for ( kp=sf->glyphs[i]->kerns; kp!=NULL; kp=kp->next ) {
	    kp->sc = (SplineChar *) (intpt) (kp->sc->orig_pos);
	    kp->kcid = true;		/* flag */
	}
	for ( kp=sf->glyphs[i]->vkerns; kp!=NULL; kp=kp->next ) {
	    kp->sc = (SplineChar *) (intpt) (kp->sc->orig_pos);
	    kp->kcid = true;
	}
    }
}

Project: fontforge
File: sfd.c

static void SFDSizeMap(EncMap *map,int glyphcnt,int enccnt) {
    if ( glyphcnt>map->backmax ) {
	map->backmap = realloc(map->backmap,glyphcnt*sizeof(int));
	memset(map->backmap+map->backmax,-1,(glyphcnt-map->backmax)*sizeof(int));
	map->backmax = glyphcnt;
    }
    if ( enccnt>map->encmax ) {
	map->map = realloc(map->map,enccnt*sizeof(int));
	memset(map->map+map->backmax,-1,(enccnt-map->encmax)*sizeof(int));
	map->encmax = map->enccount = enccnt;
    }
}

Project: fontforge
File: sfd1.c

static void SFGuessScriptList(SplineFont1 *sf) {
    uint32 scripts[32], script;
    int i, scnt=0, j;

    for ( i=0; i<sf->sf.glyphcnt; ++i ) if ( sf->sf.glyphs[i]!=NULL ) {
	script = SCScriptFromUnicode(sf->sf.glyphs[i]);
	if ( script!=0 && script!=DEFAULT_SCRIPT ) {
	    for ( j=scnt-1; j>=0 ; --j )
		if ( scripts[j]==script )
	    break;
	    if ( j<0 ) {
		scripts[scnt++] = script;
		if ( scnt>=32 )
    break;
	    }
	}
    }
    if ( scnt==0 )
	scripts[scnt++] = CHR('l','a','t','n');

    /* order scripts */
    for ( i=0; i<scnt-1; ++i ) for ( j=i+1; j<scnt; ++j ) {
	if ( scripts[i]>scripts[j] ) {
	    script = scripts[i];
	    scripts[i] = scripts[j];
	    scripts[j] = script;
	}
    }

    if ( sf->sf.cidmaster ) sf = (SplineFont1 *) sf->sf.cidmaster;
    else if ( sf->sf.mm!=NULL ) sf=(SplineFont1 *) sf->sf.mm->normal;
    if ( sf->script_lang!=NULL )
return;
    sf->script_lang = calloc(2,sizeof(struct script_record *));
    sf->script_lang[0] = calloc(scnt+1,sizeof(struct script_record));
    sf->sli_cnt = 1;
    for ( j=0; j<scnt; ++j ) {
	sf->script_lang[0][j].script = scripts[j];
	sf->script_lang[0][j].langs = malloc(2*sizeof(uint32));
	sf->script_lang[0][j].langs[0] = DEFAULT_LANG;
	sf->script_lang[0][j].langs[1] = 0;
    }
    sf->script_lang[1] = NULL;
}

Project: fontforge
File: sfd.c

static GuidelineSet *SFDReadGuideline(FILE *sfd, GuidelineSet **gll, GuidelineSet *lastgl)
{
    GuidelineSet *gl = chunkalloc(sizeof(GuidelineSet));
    gl->name = SFDReadUTF7Str(sfd);
    gl->identifier = SFDReadUTF7Str(sfd);
    getreal(sfd,&gl->point.x);
    getreal(sfd,&gl->point.y);
    getreal(sfd,&gl->angle);
    getint(sfd,&gl->color);
    getint(sfd,&gl->flags);
    if ( lastgl!=NULL )
	lastgl->next = gl;
    else if (gll)
        *gll = gl;
    return( gl );
}

Project: fontforge
File: sfd1.c

static int SLCount(struct script_record *sr) {
    int sl_cnt = 0;
    int i,j;

    for ( i=0; sr[i].script!=0; ++i ) {
	for ( j=0; sr[i].langs[j]!=0; ++j )
	    ++sl_cnt;
    }
return( sl_cnt );
}

Project: fontforge
File: sfd1.c

static void FPSTReplaceTagsWithLookups(FPST *fpst,SplineFont1 *sf) {
    int i,j,k;

    if ( fpst->type == pst_reversesub )
return;
    for ( i=0; i<fpst->rule_cnt; ++i ) {
	for ( j=0; j<fpst->rules[i].lookup_cnt; ++j ) {
	    OTLookup *otl = FindNestedLookupByTag(sf,(uint32) (intpt) (fpst->rules[i].lookups[j].lookup) );
	    if ( otl!=NULL )
		fpst->rules[i].lookups[j].lookup = otl;
	    else {
		for ( k=j+1; k<fpst->rules[i].lookup_cnt; ++k )
		    fpst->rules[i].lookups[k-1] = fpst->rules[i].lookups[k];
		--fpst->rules[i].lookup_cnt;
	    }
	}
    }
}

Project: fontforge
File: sfd.c

static struct ttf_table *SFDGetShortTable(FILE *sfd, SplineFont *sf,struct ttf_table *lasttab[2]) {
    /* We've read the ShortTable token, it is followed by a tag and a word count */
    /* and then the (text) values of the words that make up the cvt table */
    int i,len, ch;
    uint8 *pt;
    int which, iscvt, started;
    struct ttf_table *tab = chunkalloc(sizeof(struct ttf_table));

    tab->tag = gettag(sfd);

    if ( tab->tag==CHR('f','p','g','m') || tab->tag==CHR('p','r','e','p') ||
	    tab->tag==CHR('c','v','t',' ') || tab->tag==CHR('m','a','x','p'))
	which = 0;
    else
	which = 1;
    iscvt = tab->tag==CHR('c','v','t',' ');

    getint(sfd,&len);
    pt = tab->data = malloc(2*len);
    tab->len = 2*len;
    started = false;
    for ( i=0; i<len; ++i ) {
	int num;
	getint(sfd,&num);
	*pt++ = num>>8;
	*pt++ = num&0xff;
	if ( iscvt ) {
	    ch = nlgetc(sfd);
	    if ( ch==' ' ) {
		if ( !started ) {
		    sf->cvt_names = calloc(len+1,sizeof(char *));
		    sf->cvt_names[len] = END_CVT_NAMES;
		    started = true;
		}
		sf->cvt_names[i] = SFDReadUTF7Str(sfd);
	    } else
		ungetc(ch,sfd);
	}
    }

    if ( lasttab[which]!=NULL )
	lasttab[which]->next = tab;
    else if ( which==0 )
	sf->ttf_tables = tab;
    else
	sf->ttf_tab_saved = tab;
    lasttab[which] = tab;
return( tab );
}

Project: fontforge
File: sfd.c

void SFD_DumpKerns( FILE *sfd, SplineChar *sc, int *newgids ) {
    KernPair *kp;
    int v;

    for ( v=0; v<2; ++v ) {
	kp = v ? sc->vkerns : sc->kerns;
	if ( kp!=NULL ) {
	    fprintf( sfd, v ? "VKerns2:" : "Kerns2:" );
	    for ( ; kp!=NULL; kp=kp->next )
		if ( !SFDOmit(kp->sc)) {
		    fprintf( sfd, " %d %d ",
			    newgids!=NULL?newgids[kp->sc->orig_pos]:kp->sc->orig_pos,
			    kp->off );
		    SFDDumpUTF7Str(sfd,kp->subtable->subtable_name);
		    if ( kp->adjust!=NULL ) putc(' ',sfd);
		    SFDDumpDeviceTable(sfd,kp->adjust);
		}
	    fprintf(sfd, "\n" );
	}
    }
}

Project: fontforge
File: sfd.c

void SFDDumpMacFeat(FILE *sfd,MacFeat *mf) {
    struct macsetting *ms;

    if ( mf==NULL )
return;

    while ( mf!=NULL ) {
	if ( mf->featname!=NULL ) {
	    fprintf( sfd, "MacFeat: %d %d %d\n", mf->feature, mf->ismutex, mf->default_setting );
	    SFDDumpMacName(sfd,mf->featname);
	    for ( ms=mf->settings; ms!=NULL; ms=ms->next ) {
		if ( ms->setname!=NULL ) {
		    fprintf( sfd, "MacSetting: %d\n", ms->setting );
		    SFDDumpMacName(sfd,ms->setname);
		}
	    }
	}
	mf = mf->next;
    }
    fprintf( sfd,"EndMacFeatures\n" );
}

Project: fontforge
File: sfd.c

int SFDWriteBak(char *filename,SplineFont *sf,EncMap *map,EncMap *normal) {
    char *buf=0, *buf2=NULL;
    int ret;

    if ( sf->save_to_dir )
    {
	ret = SFDWrite(filename,sf,map,normal,true);
	return(ret);
    }

    if ( sf->cidmaster!=NULL )
	sf=sf->cidmaster;
    buf = malloc(strlen(filename)+10);
    if ( sf->compression!=0 )
    {
	buf2 = malloc(strlen(filename)+10);
	strcpy(buf2,filename);
	strcat(buf2,compressors[sf->compression-1].ext);
	strcpy(buf,buf2);
	strcat(buf,"~");
	if ( rename(buf2,buf)==0 )
	    sf->backedup = bs_backedup;
    }
    else
    {
	sf->backedup = bs_dontknow;

	if( prefRevisionsToRetain )
	{
	    char path[PATH_MAX];
	    char pathnew[PATH_MAX];
	    int idx = 0;

	    snprintf( path,    PATH_MAX, "%s", filename );
	    snprintf( pathnew, PATH_MAX, "%s-%02d", filename, idx );
	    (void)rename( path, pathnew );

	    for( idx=prefRevisionsToRetain; idx > 0; idx-- )
	    {
		snprintf( path, PATH_MAX, "%s-%02d", filename, idx-1 );
		snprintf( pathnew, PATH_MAX, "%s-%02d", filename, idx );

		int rc = rename( path, pathnew );
		if( !idx && !rc )
		    sf->backedup = bs_backedup;
	    }
	    idx = prefRevisionsToRetain+1;
	    snprintf( path, PATH_MAX, "%s-%02d", filename, idx );
	    unlink(path);
	}

    }
    free(buf);

    ret = SFDWrite(filename,sf,map,normal,false);
    if ( ret && sf->compression!=0 ) {
	unlink(buf2);
	buf = malloc(strlen(filename)+40);
	sprintf( buf, "%s %s", compressors[sf->compression-1].recomp, filename );
	if ( system( buf )!=0 )
	    sf->compression = 0;
	free(buf);
    }
    free(buf2);
    return( ret );
}

Project: fontforge
File: sfd.c

void SFDDumpUndo(FILE *sfd,SplineChar *sc,Undoes *u, const char* keyPrefix, int idx ) {
    fprintf(sfd, "%sOperation\n",      keyPrefix );
    fprintf(sfd, "Index: %d\n",        idx );
    fprintf(sfd, "Type: %d\n",         u->undotype );
    fprintf(sfd, "WasModified: %d\n",  u->was_modified );
    fprintf(sfd, "WasOrder2: %d\n",    u->was_order2 );
    if( u->layer != UNDO_LAYER_UNKNOWN )
    {
	fprintf(sfd, "Layer: %d\n",    u->layer );
    }

    switch( u->undotype )
    {
        case ut_tstate:
        case ut_state:
            fprintf(sfd, "Width: %d\n",           u->u.state.width );
            fprintf(sfd, "VWidth: %d\n",          u->u.state.vwidth );
            fprintf(sfd, "LBearingChange: %d\n",  u->u.state.lbearingchange );
            fprintf(sfd, "UnicodeEnc: %d\n",      u->u.state.unicodeenc );
            if( u->u.state.charname )
                fprintf(sfd, "Charname: \"%s\"\n", u->u.state.charname );
            if( u->u.state.comment )
                fprintf(sfd, "Comment: \"%s\"\n", u->u.state.comment );
            if( u->u.state.refs ) {
                SFDDumpRefs( sfd, u->u.state.refs, 0 );
            }
	    if( u->u.state.images ) {
#ifndef _NO_LIBPNG
                if (WritePNGInSFD)
                    SFDDumpImagePNG( sfd, u->u.state.images );
                else
#endif
                    SFDDumpImage( sfd, u->u.state.images );
            }
            fprintf(sfd, "InstructionsLength: %d\n", u->u.state.instrs_len );
            if( u->u.state.anchor ) {
                SFDDumpAnchorPoints( sfd, u->u.state.anchor );
            }
	    if( u->u.state.splines ) {
                fprintf(sfd, "SplineSet\n" );
                SFDDumpSplineSet( sfd, u->u.state.splines, u->was_order2 );
            }
            break;

        case ut_statehint:
        {
            SplineChar* tsc = 0;
            tsc = SplineCharCopy( sc, 0, 0 );
            ExtractHints( tsc, u->u.state.hints, 1 );
            SFDDumpHintList(  sfd, "HStem: ",  tsc->hstem);
            SFDDumpHintList(  sfd, "VStem: ",  tsc->vstem);
            SFDDumpDHintList( sfd, "DStem2: ", tsc->dstem);
            SplineCharFree( tsc );

	    if( u->u.state.instrs_len )
                SFDDumpTtfInstrsExplicit( sfd, u->u.state.instrs, u->u.state.instrs_len );
            break;
        }

        case ut_hints:
        {
            SplineChar* tsc = 0;
            tsc = SplineCharCopy( sc, 0, 0 );
            tsc->ttf_instrs = 0;
            ExtractHints( tsc, u->u.state.hints, 1 );
            SFDDumpHintList(  sfd, "HStem: ",  tsc->hstem);
            SFDDumpHintList(  sfd, "VStem: ",  tsc->vstem);
            SFDDumpDHintList( sfd, "DStem2: ", tsc->dstem);
            SplineCharFree( tsc );

            if( u->u.state.instrs_len )
                SFDDumpTtfInstrsExplicit( sfd, u->u.state.instrs, u->u.state.instrs_len );
            if( u->copied_from && u->copied_from->fullname )
                fprintf(sfd, "CopiedFrom: %s\n", u->copied_from->fullname );
            break;
        }

        case ut_width:
        case ut_vwidth:
        {
            fprintf(sfd, "Width: %d\n", u->u.width );
            break;
        }

        default:
        break;
    }

    fprintf(sfd, "End%sOperation\n", keyPrefix );
}

Project: fontforge
File: sfd.c

static int getlonglong(FILE *sfd, long long *val) {
    char tokbuf[100]; int ch;
    char *pt=tokbuf, *end = tokbuf+100-2;

    while ( isspace(ch = nlgetc(sfd)));
    if ( ch=='-' || ch=='+' ) {
	*pt++ = ch;
	ch = nlgetc(sfd);
    }
    while ( isdigit(ch)) {
	if ( pt<end ) *pt++ = ch;
	ch = nlgetc(sfd);
    }
    *pt='\0';
    ungetc(ch,sfd);
    *val = strtoll(tokbuf,NULL,10);
return( pt!=tokbuf?1:ch==EOF?-1: 0 );
}

Project: fontforge
File: sfd.c

static void SFDEnc85EndEnc(struct enc85 *enc) {
    int i;
    int ch2, ch3, ch4, ch5;
    unsigned val;
    if ( enc->pos==0 )
return;
    for ( i=enc->pos; i<4; ++i )
	enc->sofar[i] = 0;
    val = (enc->sofar[0]<<24)|(enc->sofar[1]<<16)|(enc->sofar[2]<<8)|enc->sofar[3];
    if ( val==0 ) {
	fputc('z',enc->sfd);
    } else {
	ch5 = val%85;
	val /= 85;
	ch4 = val%85;
	val /= 85;
	ch3 = val%85;
	val /= 85;
	ch2 = val%85;
	val /= 85;
	fputc('!'+val,enc->sfd);
	fputc('!'+ch2,enc->sfd);
	fputc('!'+ch3,enc->sfd);
	fputc('!'+ch4,enc->sfd);
	fputc('!'+ch5,enc->sfd);
    }
    enc->pos = 0;
}

Project: fontforge
File: sfd.c

static int SFDOmit(SplineChar *sc) {
    int layer;
    BDFFont *bdf;

    if ( sc==NULL )
return( true );
    if ( sc->comment!=NULL || sc->color!=COLOR_DEFAULT )
return( false );
    for ( layer = ly_back; layer<sc->layer_cnt; ++layer ) {
	if ( sc->layers[layer].splines!=NULL ||
		sc->layers[layer].refs!=NULL ||
		sc->layers[layer].images!=NULL )
return( false );
    }
    if ( sc->parent->onlybitmaps ) {
	for ( bdf = sc->parent->bitmaps; bdf!=NULL; bdf=bdf->next ) {
	    if ( sc->orig_pos<bdf->glyphcnt && bdf->glyphs[sc->orig_pos]!=NULL )
return( false );
	}
    }
    if ( !sc->widthset )
return(true);

return( false );
}

Project: fontforge
File: sfd.c

static SplineFont *SFD_FigureDirType(SplineFont *sf,char *tok, char *dirname,
	Encoding *enc, struct remap *remap,int had_layer_cnt) {
    /* In a sfdir a directory will either contain glyph files */
    /*                                            subfont dirs */
    /*                                            instance dirs */
    /* (or bitmap files, but we don't care about them here */
    /* It will not contain some glyph and some subfont nor instance files */
    int gc=0, sc=0, ic=0, bc=0;
    DIR *dir;
    struct dirent *ent;
    char *name, *props, *pt;

    dir = opendir(dirname);
    if ( dir==NULL )
return( sf );
    sf->save_to_dir = true;
    while ( (ent=readdir(dir))!=NULL ) {
	pt = strrchr(ent->d_name,EXT_CHAR);
	if ( pt==NULL )
	    /* Nothing interesting */;
	else if ( strcmp(pt,GLYPH_EXT)==0 )
	    ++gc;
	else if ( strcmp(pt,SUBFONT_EXT)==0 )
	    ++sc;
	else if ( strcmp(pt,INSTANCE_EXT)==0 )
	    ++ic;
	else if ( strcmp(pt,STRIKE_EXT)==0 )
	    ++bc;
    }
    rewinddir(dir);
    name = malloc(strlen(dirname)+NAME_MAX+3);
    props = malloc(strlen(dirname)+2*NAME_MAX+4);
    if ( gc!=0 ) {
	sf->glyphcnt = 0;
	sf->glyphmax = gc;
	sf->glyphs = calloc(gc,sizeof(SplineChar *));
	ff_progress_change_total(gc);
	if ( sf->cidmaster!=NULL ) {
	    sf->map = sf->cidmaster->map;
	} else {
	    sf->map = EncMapNew(enc->char_cnt>gc?enc->char_cnt:gc,gc,enc);
	    sf->map->remap = remap;
	}
	SFDSizeMap(sf->map,sf->glyphcnt,enc->char_cnt>gc?enc->char_cnt:gc);

	while ( (ent=readdir(dir))!=NULL ) {
	    pt = strrchr(ent->d_name,EXT_CHAR);
	    if ( pt==NULL )
		/* Nothing interesting */;
	    else if ( strcmp(pt,GLYPH_EXT)==0 ) {
		FILE *gsfd;
		sprintf(name,"%s/%s", dirname, ent->d_name);
		gsfd = fopen(name,"r");
		if ( gsfd!=NULL ) {
		    SFDGetChar(gsfd,sf,had_layer_cnt);
		    ff_progress_next();
		    fclose(gsfd);
		}
	    }
	}
	ff_progress_next_stage();
    } else if ( sc!=0 ) {
	int i=0;
	sf->subfontcnt = sc;
	sf->subfonts = calloc(sf->subfontcnt,sizeof(SplineFont *));
	sf->map = EncMap1to1(1000);
	ff_progress_change_stages(2*sc);

	while ( (ent=readdir(dir))!=NULL ) {
	    pt = strrchr(ent->d_name,EXT_CHAR);
	    if ( pt==NULL )
		/* Nothing interesting */;
	    else if ( strcmp(pt,SUBFONT_EXT)==0 && i<sc ) {
		FILE *ssfd;
		sprintf(name,"%s/%s", dirname, ent->d_name);
		sprintf(props,"%s/" FONT_PROPS, name);
		ssfd = fopen(props,"r");
		if ( ssfd!=NULL ) {
		    if ( i!=0 )
			ff_progress_next_stage();
		    sf->subfonts[i++] = SFD_GetFont(ssfd,sf,tok,true,name,sf->sfd_version);
		    fclose(ssfd);
		}
	    }
	}
    } else if ( ic!=0 ) {
	MMSet *mm = sf->mm;
	int ipos, i=0;

	MMInferStuff(sf->mm);
	ff_progress_change_stages(2*(mm->instance_count+1));
	while ( (ent=readdir(dir))!=NULL ) {
	    pt = strrchr(ent->d_name,EXT_CHAR);
	    if ( pt==NULL )
		/* Nothing interesting */;
	    else if ( strcmp(pt,INSTANCE_EXT)==0 && sscanf( ent->d_name, "mm%d", &ipos)==1 ) {
		FILE *ssfd;
		if ( i!=0 )
		    ff_progress_next_stage();
		sprintf(name,"%s/%s", dirname, ent->d_name);
		sprintf(props,"%s/" FONT_PROPS, name);
		ssfd = fopen(props,"r");
		if ( ssfd!=NULL ) {
		    SplineFont *mmsf;
		    mmsf = SFD_GetFont(ssfd,NULL,tok,true,name,sf->sfd_version);
		    if ( ipos!=0 ) {
			EncMapFree(mmsf->map);
			mmsf->map=NULL;
		    }
		    mmsf->mm = mm;
		    if ( ipos == 0 )
			mm->normal = mmsf;
		    else
			mm->instances[ipos-1] = mmsf;
		    fclose(ssfd);
		}
	    }
	}
	ff_progress_next_stage();
	sf->mm = NULL;
	SplineFontFree(sf);
	sf = mm->normal;
	if ( sf->map->enc!=&custom ) {
	    EncMap *map;
	    MMMatchGlyphs(mm);		/* sfd files from before the encoding change can have mismatched orig pos */
	    map = EncMapFromEncoding(sf,sf->map->enc);
	    EncMapFree(sf->map);
	    sf->map = map;
	}
    }

    if ( bc!=0 ) {
	rewinddir(dir);
	while ( (ent=readdir(dir))!=NULL ) {
	    pt = strrchr(ent->d_name,EXT_CHAR);
	    if ( pt==NULL )
		/* Nothing interesting */;
	    else if ( strcmp(pt,STRIKE_EXT)==0 ) {
		FILE *ssfd;
		sprintf(name,"%s/%s", dirname, ent->d_name);
		sprintf(props,"%s/" STRIKE_PROPS, name);
		ssfd = fopen(props,"r");
		if ( ssfd!=NULL ) {
		    if ( getname(ssfd,tok)==1 && strcmp(tok,"BitmapFont:")==0 )
			SFDGetBitmapFont(ssfd,sf,true,name);
		    fclose(ssfd);
		}
	    }
	}
	SFOrderBitmapList(sf);
    }
    closedir(dir);
    free(name);
    free(props);
return( sf );
}

Project: fontforge
File: sfd.c

static void SFDFixupUndoRefsUndoList(SplineFont *sf,Undoes *undo) {
    for( ; undo; undo = undo->next ) {
	if( undo->undotype == ut_state && undo->u.state.refs ) {
	    RefChar *ref=NULL;
	    for ( ref=undo->u.state.refs; ref!=NULL; ref=ref->next ) {

		ref->sc = sf->glyphs[ ref->orig_pos ];
	    }
	}
    }
}

Project: fontforge
File: sfd.c

static void SFDDumpGuidelines(FILE *sfd, GuidelineSet *gl) {
    if (gl==NULL) {
	return;
    }

    for ( ; gl!=NULL; gl=gl->next )
    {
	fprintf( sfd, "Guideline: " );
	SFDDumpUTF7Str(sfd,gl->name);
	putc(' ',sfd);
	SFDDumpUTF7Str(sfd,gl->identifier);
	putc(' ',sfd);
	fprintf( sfd, "%g %g %g %u %d",
		(double) gl->point.x, (double) gl->point.y,
		(double) gl->angle, gl->color, gl->flags);
	putc('\n',sfd);
    }
}

Project: fontforge
File: sfd.c

static int SFDGetBitmapFont(FILE *sfd,SplineFont *sf,int fromdir,char *dirname) {
    BDFFont *bdf, *prev;
    char tok[2000];
    int pixelsize, ascent, descent, depth=1;
    int ch, enccount;

    if ( getint(sfd,&pixelsize)!=1 || pixelsize<=0 )
return( 0 );
    if ( getint(sfd,&enccount)!=1 || enccount<0 )
return( 0 );
    if ( getint(sfd,&ascent)!=1 || ascent<0 )
return( 0 );
    if ( getint(sfd,&descent)!=1 || descent<0 )
return( 0 );
    if ( getint(sfd,&depth)!=1 )
	depth = 1;	/* old sfds don't have a depth here */
    else if ( depth!=1 && depth!=2 && depth!=4 && depth!=8 )
return( 0 );
    while ( (ch = nlgetc(sfd))==' ' );
    ungetc(ch,sfd);		/* old sfds don't have a foundry */

    bdf = calloc(1,sizeof(BDFFont));
    if (bdf == NULL)
        return 0;

    if ( ch!='\n' && ch!='\r' ) {
	getname(sfd,tok);
	bdf->foundry = copy(tok);
    }
    bdf->pixelsize = pixelsize;
    bdf->ascent = ascent;
    bdf->descent = descent;
    if ( depth!=1 )
	BDFClut(bdf,(1<<(depth/2)));

    if ( sf->bitmaps==NULL )
	sf->bitmaps = bdf;
    else {
	for ( prev=sf->bitmaps; prev->next!=NULL; prev=prev->next );
	prev->next = bdf;
    }
    bdf->sf = sf;
    bdf->glyphcnt = bdf->glyphmax = sf->glyphcnt;
    bdf->glyphs = calloc(bdf->glyphcnt,sizeof(BDFChar *));

    while ( getname(sfd,tok)==1 ) {
	if ( strcmp(tok,"BDFStartProperties:")==0 )
	    SFDGetBitmapProps(sfd,bdf,tok);
	else if ( strcmp(tok,"BDFEndProperties")==0 )
	    /* Do Nothing */;
	else if ( strcmp(tok,"Resolution:")==0 )
	    getint(sfd,&bdf->res);
	else if ( strcmp(tok,"BDFChar:")==0 )
	    SFDGetBitmapChar(sfd,bdf);
	else if ( strcmp(tok,"BDFRefChar:")==0 )
	    SFDGetBitmapReference(sfd,bdf);
	else if ( strcmp(tok,"EndBitmapFont")==0 )
    break;
    }
    if ( fromdir ) {
	DIR *dir;
	struct dirent *ent;
	char *name;

	dir = opendir(dirname);
	if ( dir==NULL )
return( 0 );
	name = malloc(strlen(dirname)+NAME_MAX+3);

	while ( (ent=readdir(dir))!=NULL ) {
	    char *pt = strrchr(ent->d_name,EXT_CHAR);
	    if ( pt==NULL )
		/* Nothing interesting */;
	    else if ( strcmp(pt,BITMAP_EXT)==0 ) {
		FILE *gsfd;
		sprintf(name,"%s/%s", dirname, ent->d_name);
		gsfd = fopen(name,"r");
		if ( gsfd!=NULL ) {
		    if ( getname(gsfd,tok) && strcmp(tok,"BDFChar:")==0)
			SFDGetBitmapChar(gsfd,bdf);
		    fclose(gsfd);
		    ff_progress_next();
		}
	    }
	}
	free(name);
	closedir(dir);
    }
    SFDFixupBitmapRefs( bdf );
return( 1 );
}

Project: fontforge
File: sfd.c

static struct pattern *SFDParsePattern(FILE *sfd,char *tok) {
    struct pattern *pat = chunkalloc(sizeof(struct pattern));
    int ch;

    getname(sfd,tok);
    pat->pattern = copy(tok);

    getreal(sfd,&pat->width);
    while ( isspace(ch=nlgetc(sfd)));
    if ( ch!=';' ) ungetc(ch,sfd);
    getreal(sfd,&pat->height);

    while ( isspace(ch=nlgetc(sfd)));
    if ( ch!='[' ) ungetc(ch,sfd);
    getreal(sfd,&pat->transform[0]);
    getreal(sfd,&pat->transform[1]);
    getreal(sfd,&pat->transform[2]);
    getreal(sfd,&pat->transform[3]);
    getreal(sfd,&pat->transform[4]);
    getreal(sfd,&pat->transform[5]);
    while ( isspace(ch=nlgetc(sfd)));
    if ( ch!=']' ) ungetc(ch,sfd);
return( pat );
}

Project: fontforge
File: sfd.c

static void SFDGetSpiros(FILE *sfd,SplineSet *cur) {
    int ch;
    spiro_cp cp;

    ch = nlgetc(sfd);		/* S */
    ch = nlgetc(sfd);		/* p */
    ch = nlgetc(sfd);		/* i */
    ch = nlgetc(sfd);		/* r */
    ch = nlgetc(sfd);		/* o */
    while ( fscanf(sfd,"%lg %lg %c", &cp.x, &cp.y, &cp.ty )==3 ) {
	if ( cur!=NULL ) {
	    if ( cur->spiro_cnt>=cur->spiro_max )
		cur->spiros = realloc(cur->spiros,
		                      (cur->spiro_max+=10)*sizeof(spiro_cp));
	    cur->spiros[cur->spiro_cnt++] = cp;
	}
    }
    if (    cur!=NULL && cur->spiro_cnt>0
         && (cur->spiros[cur->spiro_cnt-1].ty&0x7f)!=SPIRO_END ) {
	if ( cur->spiro_cnt>=cur->spiro_max )
	    cur->spiros = realloc(cur->spiros,
	                          (cur->spiro_max+=1)*sizeof(spiro_cp));
	memset(&cur->spiros[cur->spiro_cnt],0,sizeof(spiro_cp));
	cur->spiros[cur->spiro_cnt++].ty = SPIRO_END;
    }
    ch = nlgetc(sfd);
    if ( ch=='E' ) {
	ch = nlgetc(sfd);		/* n */
	ch = nlgetc(sfd);		/* d */
	ch = nlgetc(sfd);		/* S */
	ch = nlgetc(sfd);		/* p */
	ch = nlgetc(sfd);		/* i */
	ch = nlgetc(sfd);		/* r */
	ch = nlgetc(sfd);		/* o */
    } else
	ungetc(ch,sfd);
}

Project: fontforge
File: sfd.c

static void SFDDumpOtfFeatNames(FILE *sfd, SplineFont *sf) {
    struct otffeatname *fn;
    struct otfname *on;

    for ( fn=sf->feat_names; fn!=NULL; fn=fn->next ) {
	fprintf( sfd, "OtfFeatName: '%c%c%c%c' ",
		fn->tag>>24, fn->tag>>16, fn->tag>>8, fn->tag );
	for ( on=fn->names; on!=NULL; on=on->next ) {
	    fprintf( sfd, "%d ", on->lang );
	    SFDDumpUTF7Str(sfd, on->name);
	    if ( on->next!=NULL ) putc(' ',sfd);
	}
	putc('\n',sfd);
    }
}

Project: fontforge
File: sfd.c

static void SFDFpstClassNamesOut(FILE *sfd,int class_cnt,char **classnames,const char *keyword) {
    char buffer[20];
    int i;

    if ( class_cnt>0 && classnames!=NULL ) {
	fprintf( sfd, "  %s: ", keyword );
	for ( i=0; i<class_cnt; ++i ) {
	    if ( classnames[i]==NULL ) {
		sprintf( buffer,"%d", i );
		SFDDumpUTF7Str(sfd,buffer);
	    } else
		SFDDumpUTF7Str(sfd,classnames[i]);
	    if ( i<class_cnt-1 ) putc(' ',sfd);
	}
	putc('\n',sfd);
    }
}

Project: fontforge
File: sfd.c

int SFD_DumpSplineFontMetadata( FILE *sfd, SplineFont *sf )
{
    int i, j;
    struct ttflangname *ln;
    struct ttf_table *tab;
    KernClass *kc;
    FPST *fpst;
    ASM *sm;
    int isv;
    int err = false;
    int isgpos;
    OTLookup *otl;
    struct lookup_subtable *sub;
    FeatureScriptLangList *fl;
    struct scriptlanglist *sl;

    fprintf(sfd, "FontName: %s\n", sf->fontname );
    if ( sf->fullname!=NULL )
	fprintf(sfd, "FullName: %s\n", sf->fullname );
    if ( sf->familyname!=NULL )
	fprintf(sfd, "FamilyName: %s\n", sf->familyname );
    if ( sf->weight!=NULL )
	fprintf(sfd, "Weight: %s\n", sf->weight );
    if ( sf->copyright!=NULL )
	putstring(sfd, "Copyright: ", sf->copyright );
    if ( sf->comments!=NULL ) {
	fprintf( sfd, "UComments: " );
	SFDDumpUTF7Str(sfd,sf->comments);
	putc('\n',sfd);
    }
    if ( sf->fontlog!=NULL ) {
	fprintf( sfd, "FontLog: " );
	SFDDumpUTF7Str(sfd,sf->fontlog);
	putc('\n',sfd);
    }

    if ( sf->version!=NULL )
	fprintf(sfd, "Version: %s\n", sf->version );
    if ( sf->styleMapFamilyName!=NULL )
	fprintf(sfd, "StyleMapFamilyName: %s\n", sf->styleMapFamilyName );
    if ( sf->fondname!=NULL )
	fprintf(sfd, "FONDName: %s\n", sf->fondname );
    if ( sf->defbasefilename!=NULL )
	fprintf(sfd, "DefaultBaseFilename: %s\n", sf->defbasefilename );
    if ( sf->strokewidth!=0 )
	fprintf(sfd, "StrokeWidth: %g\n", (double) sf->strokewidth );
    fprintf(sfd, "ItalicAngle: %g\n", (double) sf->italicangle );
    fprintf(sfd, "UnderlinePosition: %g\n", (double) sf->upos );
    fprintf(sfd, "UnderlineWidth: %g\n", (double) sf->uwidth );
    fprintf(sfd, "Ascent: %d\n", sf->ascent );
    fprintf(sfd, "Descent: %d\n", sf->descent );
    fprintf(sfd, "InvalidEm: %d\n", sf->invalidem );
    if ( sf->sfntRevision!=sfntRevisionUnset )
	fprintf(sfd, "sfntRevision: 0x%08x\n", sf->sfntRevision );
    if ( sf->woffMajor!=woffUnset ) {
	fprintf(sfd, "woffMajor: %d\n", sf->woffMajor );
	fprintf(sfd, "woffMinor: %d\n", sf->woffMinor );
    }
    if ( sf->woffMetadata!=NULL ) {
	fprintf( sfd, "woffMetadata: " );
	SFDDumpUTF7Str(sfd,sf->woffMetadata);
	putc('\n',sfd);
    }
    if ( sf->ufo_ascent!=0 )
	fprintf(sfd, "UFOAscent: %g\n", (double) sf->ufo_ascent );
    if ( sf->ufo_descent!=0 )
	fprintf(sfd, "UFODescent: %g\n", (double) sf->ufo_descent );
    fprintf(sfd, "LayerCount: %d\n", sf->layer_cnt );
    for ( i=0; i<sf->layer_cnt; ++i ) {
	fprintf( sfd, "Layer: %d %d ", i, sf->layers[i].order2/*, sf->layers[i].background*/ );
	SFDDumpUTF7Str(sfd,sf->layers[i].name);
	fprintf( sfd, " %d", sf->layers[i].background );
	if (sf->layers[i].ufo_path != NULL) { putc(' ',sfd); SFDDumpUTF7Str(sfd,sf->layers[i].ufo_path); }
	putc('\n',sfd);
    }
    // TODO: Output U. F. O. layer path.
    if (sf->preferred_kerning != 0) fprintf(sfd, "PreferredKerning: %d\n", sf->preferred_kerning);
    if ( sf->strokedfont )
	fprintf(sfd, "StrokedFont: %d\n", sf->strokedfont );
    else if ( sf->multilayer )
	fprintf(sfd, "MultiLayer: %d\n", sf->multilayer );
    if ( sf->hasvmetrics )
	fprintf(sfd, "HasVMetrics: %d\n", sf->hasvmetrics );
    if ( sf->use_xuid && sf->changed_since_xuidchanged )
	fprintf(sfd, "NeedsXUIDChange: 1\n" );
    if ( sf->xuid!=NULL )
	fprintf(sfd, "XUID: %s\n", sf->xuid );
    if ( sf->uniqueid!=0 )
	fprintf(sfd, "UniqueID: %d\n", sf->uniqueid );
    if ( sf->use_xuid )
	fprintf(sfd, "UseXUID: 1\n" );
    if ( sf->use_uniqueid )
	fprintf(sfd, "UseUniqueID: 1\n" );
    if ( sf->horiz_base!=NULL )
	SFDDumpBase(sfd,"BaseHoriz:",sf->horiz_base);
    if ( sf->vert_base!=NULL )
	SFDDumpBase(sfd,"BaseVert:",sf->vert_base);
    if ( sf->pfminfo.stylemap!=-1 )
	fprintf(sfd, "StyleMap: 0x%04x\n", sf->pfminfo.stylemap );
    if ( sf->pfminfo.fstype!=-1 )
	fprintf(sfd, "FSType: %d\n", sf->pfminfo.fstype );
    fprintf(sfd, "OS2Version: %d\n", sf->os2_version );
    fprintf(sfd, "OS2_WeightWidthSlopeOnly: %d\n", sf->weight_width_slope_only );
    fprintf(sfd, "OS2_UseTypoMetrics: %d\n", sf->use_typo_metrics );
    fprintf(sfd, "CreationTime: %lld\n", sf->creationtime );
    fprintf(sfd, "ModificationTime: %lld\n", sf->modificationtime );
    if ( sf->pfminfo.pfmset ) {
	fprintf(sfd, "PfmFamily: %d\n", sf->pfminfo.pfmfamily );
	fprintf(sfd, "TTFWeight: %d\n", sf->pfminfo.weight );
	fprintf(sfd, "TTFWidth: %d\n", sf->pfminfo.width );
	fprintf(sfd, "LineGap: %d\n", sf->pfminfo.linegap );
	fprintf(sfd, "VLineGap: %d\n", sf->pfminfo.vlinegap );
	/*putc('\n',sfd);*/
    }
    if ( sf->pfminfo.panose_set ) {
	fprintf(sfd, "Panose:" );
	for ( i=0; i<10; ++i )
	    fprintf( sfd, " %d", sf->pfminfo.panose[i]);
	putc('\n',sfd);
    }
    fprintf(sfd, "OS2TypoAscent: %d\n", sf->pfminfo.os2_typoascent );
    fprintf(sfd, "OS2TypoAOffset: %d\n", sf->pfminfo.typoascent_add );
    fprintf(sfd, "OS2TypoDescent: %d\n", sf->pfminfo.os2_typodescent );
    fprintf(sfd, "OS2TypoDOffset: %d\n", sf->pfminfo.typodescent_add );
    fprintf(sfd, "OS2TypoLinegap: %d\n", sf->pfminfo.os2_typolinegap );
    fprintf(sfd, "OS2WinAscent: %d\n", sf->pfminfo.os2_winascent );
    fprintf(sfd, "OS2WinAOffset: %d\n", sf->pfminfo.winascent_add );
    fprintf(sfd, "OS2WinDescent: %d\n", sf->pfminfo.os2_windescent );
    fprintf(sfd, "OS2WinDOffset: %d\n", sf->pfminfo.windescent_add );
    fprintf(sfd, "HheadAscent: %d\n", sf->pfminfo.hhead_ascent );
    fprintf(sfd, "HheadAOffset: %d\n", sf->pfminfo.hheadascent_add );
    fprintf(sfd, "HheadDescent: %d\n", sf->pfminfo.hhead_descent );
    fprintf(sfd, "HheadDOffset: %d\n", sf->pfminfo.hheaddescent_add );
    if ( sf->pfminfo.subsuper_set ) {
	fprintf(sfd, "OS2SubXSize: %d\n", sf->pfminfo.os2_subxsize );
	fprintf(sfd, "OS2SubYSize: %d\n", sf->pfminfo.os2_subysize );
	fprintf(sfd, "OS2SubXOff: %d\n", sf->pfminfo.os2_subxoff );
	fprintf(sfd, "OS2SubYOff: %d\n", sf->pfminfo.os2_subyoff );
	fprintf(sfd, "OS2SupXSize: %d\n", sf->pfminfo.os2_supxsize );
	fprintf(sfd, "OS2SupYSize: %d\n", sf->pfminfo.os2_supysize );
	fprintf(sfd, "OS2SupXOff: %d\n", sf->pfminfo.os2_supxoff );
	fprintf(sfd, "OS2SupYOff: %d\n", sf->pfminfo.os2_supyoff );
	fprintf(sfd, "OS2StrikeYSize: %d\n", sf->pfminfo.os2_strikeysize );
	fprintf(sfd, "OS2StrikeYPos: %d\n", sf->pfminfo.os2_strikeypos );
    }
    if ( sf->pfminfo.os2_capheight!=0 )
    fprintf(sfd, "OS2CapHeight: %d\n", sf->pfminfo.os2_capheight );
    if ( sf->pfminfo.os2_xheight!=0 )
    fprintf(sfd, "OS2XHeight: %d\n", sf->pfminfo.os2_xheight );
    if ( sf->pfminfo.os2_family_class!=0 )
	fprintf(sfd, "OS2FamilyClass: %d\n", sf->pfminfo.os2_family_class );
    if ( sf->pfminfo.os2_vendor[0]!='\0' ) {
	fprintf(sfd, "OS2Vendor: '%c%c%c%c'\n",
		sf->pfminfo.os2_vendor[0], sf->pfminfo.os2_vendor[1],
		sf->pfminfo.os2_vendor[2], sf->pfminfo.os2_vendor[3] );
    }
    if ( sf->pfminfo.hascodepages )
	fprintf(sfd, "OS2CodePages: %08x.%08x\n", sf->pfminfo.codepages[0], sf->pfminfo.codepages[1]);
    if ( sf->pfminfo.hasunicoderanges )
	fprintf(sfd, "OS2UnicodeRanges: %08x.%08x.%08x.%08x\n",
		sf->pfminfo.unicoderanges[0], sf->pfminfo.unicoderanges[1],
		sf->pfminfo.unicoderanges[2], sf->pfminfo.unicoderanges[3] );
    if ( sf->macstyle!=-1 )
	fprintf(sfd, "MacStyle: %d\n", sf->macstyle );
    /* Must come before any kerning classes, anchor classes, conditional psts */
    /* state machines, psts, kerning pairs, etc. */
    for ( isgpos=0; isgpos<2; ++isgpos ) {
	for ( otl = isgpos ? sf->gpos_lookups : sf->gsub_lookups; otl!=NULL; otl = otl->next ) {
	    fprintf( sfd, "Lookup: %d %d %d ", otl->lookup_type, otl->lookup_flags, otl->store_in_afm );
	    SFDDumpUTF7Str(sfd,otl->lookup_name);
	    fprintf( sfd, " { " );
	    for ( sub=otl->subtables; sub!=NULL; sub=sub->next ) {
		SFDDumpUTF7Str(sfd,sub->subtable_name);
		putc(' ',sfd);
		if ( otl->lookup_type==gsub_single && sub->suffix!=NULL ) {
		    putc('(',sfd);
		    SFDDumpUTF7Str(sfd,sub->suffix);
		    putc(')',sfd);
		} else if ( otl->lookup_type==gpos_pair && sub->vertical_kerning )
		    fprintf(sfd,"(1)");
		if ( otl->lookup_type==gpos_pair && (sub->separation!=0 || sub->kerning_by_touch))
		    fprintf(sfd,"[%d,%d,%d]", sub->separation, sub->minkern, sub->kerning_by_touch+2*sub->onlyCloser+4*sub->dontautokern );
		putc(' ',sfd);
	    }
	    fprintf( sfd, "} [" );
	    for ( fl=otl->features; fl!=NULL; fl=fl->next ) {
		if ( fl->ismac )
		    fprintf( sfd, "<%d,%d> (",
			    (int) (fl->featuretag>>16),
			    (int) (fl->featuretag&0xffff));
		else
		    fprintf( sfd, "'%c%c%c%c' (",
			    (int) (fl->featuretag>>24), (int) ((fl->featuretag>>16)&0xff),
			    (int) ((fl->featuretag>>8)&0xff), (int) (fl->featuretag&0xff) );
		for ( sl= fl->scripts; sl!=NULL; sl = sl->next ) {
		    fprintf( sfd, "'%c%c%c%c' <",
			    (int) (sl->script>>24), (int) ((sl->script>>16)&0xff),
			    (int) ((sl->script>>8)&0xff), (int) (sl->script&0xff) );
		    for ( i=0; i<sl->lang_cnt; ++i ) {
			uint32 lang = i<MAX_LANG ? sl->langs[i] : sl->morelangs[i-MAX_LANG];
			fprintf( sfd, "'%c%c%c%c' ",
				(int) (lang>>24), (int) ((lang>>16)&0xff),
				(int) ((lang>>8)&0xff), (int) (lang&0xff) );
		    }
		    fprintf( sfd, "> " );
		}
		fprintf( sfd, ") " );
	    }
	    fprintf( sfd, "]\n" );
	}
    }

    if ( sf->mark_class_cnt!=0 ) {
	fprintf( sfd, "MarkAttachClasses: %d\n", sf->mark_class_cnt );
	for ( i=1; i<sf->mark_class_cnt; ++i ) {	/* Class 0 is unused */
	    SFDDumpUTF7Str(sfd, sf->mark_class_names[i]);
	    putc(' ',sfd);
	    if ( sf->mark_classes[i]!=NULL )
		fprintf( sfd, "%d %s\n", (int) strlen(sf->mark_classes[i]),
			sf->mark_classes[i] );
	    else
		fprintf( sfd, "0 \n" );
	}
    }
    if ( sf->mark_set_cnt!=0 ) {
	fprintf( sfd, "MarkAttachSets: %d\n", sf->mark_set_cnt );
	for ( i=0; i<sf->mark_set_cnt; ++i ) {	/* Set 0 is used */
	    SFDDumpUTF7Str(sfd, sf->mark_set_names[i]);
	    putc(' ',sfd);
	    if ( sf->mark_sets[i]!=NULL )
		fprintf( sfd, "%d %s\n", (int) strlen(sf->mark_sets[i]),
			sf->mark_sets[i] );
	    else
		fprintf( sfd, "0 \n" );
	}
    }

    fprintf( sfd, "DEI: 91125\n" );
    for ( isv=0; isv<2; ++isv ) {
	for ( kc=isv ? sf->vkerns : sf->kerns; kc!=NULL; kc = kc->next ) {
	  if (kc->firsts_names == NULL && kc->seconds_names == NULL && kc->firsts_flags == NULL && kc->seconds_flags == NULL) {
	    fprintf( sfd, "%s: %d%s %d ", isv ? "VKernClass2" : "KernClass2",
		    kc->first_cnt, kc->firsts[0]!=NULL?"+":"",
		    kc->second_cnt );
	    SFDDumpUTF7Str(sfd,kc->subtable->subtable_name);
	    putc('\n',sfd);
	    if ( kc->firsts[0]!=NULL )
	      fprintf( sfd, " %d %s\n", (int)strlen(kc->firsts[0]),
		       kc->firsts[0]);
	    for ( i=1; i<kc->first_cnt; ++i )
	      fprintf( sfd, " %d %s\n", (int)strlen(kc->firsts[i]),
		       kc->firsts[i]);
	    for ( i=1; i<kc->second_cnt; ++i )
	      fprintf( sfd, " %d %s\n", (int)strlen(kc->seconds[i]),
		       kc->seconds[i]);
	    for ( i=0; i<kc->first_cnt*kc->second_cnt; ++i ) {
		fprintf( sfd, " %d", kc->offsets[i]);
		putc(' ',sfd);
		SFDDumpDeviceTable(sfd,&kc->adjusts[i]);
	    }
	    fprintf( sfd, "\n" );
	  } else {
	    fprintf( sfd, "%s: %d%s %d ", isv ? "VKernClass3" : "KernClass3",
		    kc->first_cnt, kc->firsts[0]!=NULL?"+":"",
		    kc->second_cnt );
	    SFDDumpUTF7Str(sfd,kc->subtable->subtable_name);
	    putc('\n',sfd);
	    if ( kc->firsts[0]!=NULL ) {
	      fprintf( sfd, " %d ", ((kc->firsts_flags && kc->firsts_flags[0]) ? kc->firsts_flags[0] : 0));
	      SFDDumpUTF7Str(sfd, ((kc->firsts_names && kc->firsts_names[0]) ? kc->firsts_names[0] : ""));
	      fprintf( sfd, " " );
	      SFDDumpUTF7Str(sfd,kc->firsts[0]);
	      fprintf( sfd, "\n" );
	    }
	    for ( i=1; i<kc->first_cnt; ++i ) {
	      fprintf( sfd, " %d ", ((kc->firsts_flags && kc->firsts_flags[i]) ? kc->firsts_flags[i] : 0));
	      SFDDumpUTF7Str(sfd, ((kc->firsts_names && kc->firsts_names[i]) ? kc->firsts_names[i] : ""));
	      fprintf( sfd, " " );
	      SFDDumpUTF7Str(sfd,kc->firsts[i]);
	      fprintf( sfd, "\n" );
	    }
	    for ( i=1; i<kc->second_cnt; ++i ) {
	      fprintf( sfd, " %d ", ((kc->seconds_flags && kc->seconds_flags[i]) ? kc->seconds_flags[i] : 0));
	      SFDDumpUTF7Str(sfd, ((kc->seconds_names && kc->seconds_names[i]) ? kc->seconds_names[i] : ""));
	      fprintf( sfd, " " );
	      SFDDumpUTF7Str(sfd,kc->seconds[i]);
	      fprintf( sfd, "\n" );
	    }
	    for ( i=0; i<kc->first_cnt*kc->second_cnt; ++i ) {
		fprintf( sfd, " %d %d", ((kc->offsets_flags && kc->offsets_flags[i]) ? kc->offsets_flags[i] : 0), kc->offsets[i]);
		putc(' ',sfd);
		SFDDumpDeviceTable(sfd,&kc->adjusts[i]);
	    }
	    fprintf( sfd, "\n" );
	  }
	}
    }
    for ( fpst=sf->possub; fpst!=NULL; fpst=fpst->next ) {
	static const char *keywords[] = { "ContextPos2:", "ContextSub2:", "ChainPos2:", "ChainSub2:", "ReverseChain2:", NULL };
	static const char *formatkeys[] = { "glyph", "class", "coverage", "revcov", NULL };
	fprintf( sfd, "%s %s ", keywords[fpst->type-pst_contextpos],
		formatkeys[fpst->format] );
	SFDDumpUTF7Str(sfd,fpst->subtable->subtable_name);
	fprintf( sfd, " %d %d %d %d\n",
		fpst->nccnt, fpst->bccnt, fpst->fccnt, fpst->rule_cnt );
	if ( fpst->nccnt>0 && fpst->nclass[0]!=NULL )
	  fprintf( sfd, "  Class0: %d %s\n", (int)strlen(fpst->nclass[0]),
		   fpst->nclass[0]);
	for ( i=1; i<fpst->nccnt; ++i )
	  fprintf( sfd, "  Class: %d %s\n", (int)strlen(fpst->nclass[i]),
		   fpst->nclass[i]);
	for ( i=1; i<fpst->bccnt; ++i )
	  fprintf( sfd, "  BClass: %d %s\n", (int)strlen(fpst->bclass[i]),
		   fpst->bclass[i]);
	for ( i=1; i<fpst->fccnt; ++i )
	  fprintf( sfd, "  FClass: %d %s\n", (int)strlen(fpst->fclass[i]),
		   fpst->fclass[i]);
	for ( i=0; i<fpst->rule_cnt; ++i ) {
	    switch ( fpst->format ) {
	      case pst_glyphs:
		fprintf( sfd, " String: %d %s\n",
			 (int)strlen(fpst->rules[i].u.glyph.names),
			 fpst->rules[i].u.glyph.names);
		if ( fpst->rules[i].u.glyph.back!=NULL )
		  fprintf( sfd, " BString: %d %s\n",
			   (int)strlen(fpst->rules[i].u.glyph.back),
			   fpst->rules[i].u.glyph.back);
		else
		    fprintf( sfd, " BString: 0\n");
		if ( fpst->rules[i].u.glyph.fore!=NULL )
		  fprintf( sfd, " FString: %d %s\n",
			   (int)strlen(fpst->rules[i].u.glyph.fore),
			   fpst->rules[i].u.glyph.fore);
		else
		    fprintf( sfd, " FString: 0\n");
	      break;
	      case pst_class:
		fprintf( sfd, " %d %d %d\n  ClsList:", fpst->rules[i].u.class.ncnt, fpst->rules[i].u.class.bcnt, fpst->rules[i].u.class.fcnt );
		for ( j=0; j<fpst->rules[i].u.class.ncnt; ++j )
		    fprintf( sfd, " %d", fpst->rules[i].u.class.nclasses[j]);
		fprintf( sfd, "\n  BClsList:" );
		for ( j=0; j<fpst->rules[i].u.class.bcnt; ++j )
		    fprintf( sfd, " %d", fpst->rules[i].u.class.bclasses[j]);
		fprintf( sfd, "\n  FClsList:" );
		for ( j=0; j<fpst->rules[i].u.class.fcnt; ++j )
		    fprintf( sfd, " %d", fpst->rules[i].u.class.fclasses[j]);
		fprintf( sfd, "\n" );
	      break;
	      case pst_coverage:
	      case pst_reversecoverage:
		fprintf( sfd, " %d %d %d\n", fpst->rules[i].u.coverage.ncnt, fpst->rules[i].u.coverage.bcnt, fpst->rules[i].u.coverage.fcnt );
		for ( j=0; j<fpst->rules[i].u.coverage.ncnt; ++j )
		  fprintf( sfd, "  Coverage: %d %s\n",
			   (int)strlen(fpst->rules[i].u.coverage.ncovers[j]),
			   fpst->rules[i].u.coverage.ncovers[j]);
		for ( j=0; j<fpst->rules[i].u.coverage.bcnt; ++j )
		  fprintf( sfd, "  BCoverage: %d %s\n",
			   (int)strlen(fpst->rules[i].u.coverage.bcovers[j]),
			   fpst->rules[i].u.coverage.bcovers[j]);
		for ( j=0; j<fpst->rules[i].u.coverage.fcnt; ++j )
		  fprintf( sfd, "  FCoverage: %d %s\n",
			   (int)strlen(fpst->rules[i].u.coverage.fcovers[j]),
			   fpst->rules[i].u.coverage.fcovers[j]);
	      break;
	      default:
	      break;
	    }
	    switch ( fpst->format ) {
	      case pst_glyphs:
	      case pst_class:
	      case pst_coverage:
		fprintf( sfd, " %d\n", fpst->rules[i].lookup_cnt );
		for ( j=0; j<fpst->rules[i].lookup_cnt; ++j ) {
		    fprintf( sfd, "  SeqLookup: %d ",
			    fpst->rules[i].lookups[j].seq );
		    SFDDumpUTF7Str(sfd,fpst->rules[i].lookups[j].lookup->lookup_name);
		    putc('\n',sfd);
		}
	      break;
	      case pst_reversecoverage:
		fprintf( sfd, "  Replace: %d %s\n",
			 (int)strlen(fpst->rules[i].u.rcoverage.replacements),
			 fpst->rules[i].u.rcoverage.replacements);
	      break;
	      default:
	      break;
	    }
	}
	/* It would make more sense to output these up near the classes */
	/*  but that would break backwards compatibility (old parsers will */
	/*  ignore these entries if they are at the end, new parsers will */
	/*  read them */
	SFDFpstClassNamesOut(sfd,fpst->nccnt,fpst->nclassnames,"ClassNames");
	SFDFpstClassNamesOut(sfd,fpst->bccnt,fpst->bclassnames,"BClassNames");
	SFDFpstClassNamesOut(sfd,fpst->fccnt,fpst->fclassnames,"FClassNames");
	fprintf( sfd, "EndFPST\n" );
    }
    struct ff_glyphclasses *grouptmp;
    for ( grouptmp = sf->groups; grouptmp != NULL; grouptmp = grouptmp->next ) {
      fprintf(sfd, "Group: ");
      SFDDumpUTF7Str(sfd, grouptmp->classname); fprintf(sfd, " ");
      SFDDumpUTF7Str(sfd, grouptmp->glyphs); fprintf(sfd, "\n");
    }
    struct ff_rawoffsets *groupkerntmp;
    for ( groupkerntmp = sf->groupkerns; groupkerntmp != NULL; groupkerntmp = groupkerntmp->next ) {
      fprintf(sfd, "GroupKern: ");
      SFDDumpUTF7Str(sfd, groupkerntmp->left); fprintf(sfd, " ");
      SFDDumpUTF7Str(sfd, groupkerntmp->right); fprintf(sfd, " ");
      fprintf(sfd, "%d\n", groupkerntmp->offset);
    }
    for ( groupkerntmp = sf->groupvkerns; groupkerntmp != NULL; groupkerntmp = groupkerntmp->next ) {
      fprintf(sfd, "GroupVKern: ");
      SFDDumpUTF7Str(sfd, groupkerntmp->left); fprintf(sfd, " ");
      SFDDumpUTF7Str(sfd, groupkerntmp->right); fprintf(sfd, " ");
      fprintf(sfd, "%d\n", groupkerntmp->offset);
    }
    for ( sm=sf->sm; sm!=NULL; sm=sm->next ) {
	static const char *keywords[] = { "MacIndic2:", "MacContext2:", "MacLigature2:", "unused", "MacSimple2:", "MacInsert2:",
	    "unused", "unused", "unused", "unused", "unused", "unused",
	    "unused", "unused", "unused", "unused", "unused", "MacKern2:",
	    NULL };
	fprintf( sfd, "%s ", keywords[sm->type-asm_indic] );
	SFDDumpUTF7Str(sfd,sm->subtable->subtable_name);
	fprintf( sfd, " %d %d %d\n", sm->flags, sm->class_cnt, sm->state_cnt );
	for ( i=4; i<sm->class_cnt; ++i )
	  fprintf( sfd, "  Class: %d %s\n", (int)strlen(sm->classes[i]),
		   sm->classes[i]);
	for ( i=0; i<sm->class_cnt*sm->state_cnt; ++i ) {
	    fprintf( sfd, " %d %d ", sm->state[i].next_state, sm->state[i].flags );
	    if ( sm->type==asm_context ) {
		if ( sm->state[i].u.context.mark_lookup==NULL )
		    putc('~',sfd);
		else
		    SFDDumpUTF7Str(sfd,sm->state[i].u.context.mark_lookup->lookup_name);
		putc(' ',sfd);
		if ( sm->state[i].u.context.cur_lookup==0 )
		    putc('~',sfd);
		else
		    SFDDumpUTF7Str(sfd,sm->state[i].u.context.cur_lookup->lookup_name);
		putc(' ',sfd);
	    } else if ( sm->type == asm_insert ) {
		if ( sm->state[i].u.insert.mark_ins==NULL )
		    fprintf( sfd, "0 ");
		else
		  fprintf( sfd, "%d %s ",
			   (int)strlen(sm->state[i].u.insert.mark_ins),
			   sm->state[i].u.insert.mark_ins );
		if ( sm->state[i].u.insert.cur_ins==NULL )
		    fprintf( sfd, "0 ");
		else
		  fprintf( sfd, "%d %s ",
			   (int)strlen(sm->state[i].u.insert.cur_ins),
			   sm->state[i].u.insert.cur_ins );
	    } else if ( sm->type == asm_kern ) {
		fprintf( sfd, "%d ", sm->state[i].u.kern.kcnt );
		for ( j=0; j<sm->state[i].u.kern.kcnt; ++j )
		    fprintf( sfd, "%d ", sm->state[i].u.kern.kerns[j]);
	    }
	    putc('\n',sfd);
	}
	fprintf( sfd, "EndASM\n" );
    }
    SFDDumpMacFeat(sfd,sf->features);
    SFDDumpJustify(sfd,sf);
    for ( tab = sf->ttf_tables; tab!=NULL ; tab = tab->next )
	SFDDumpTtfTable(sfd,tab,sf);
    for ( tab = sf->ttf_tab_saved; tab!=NULL ; tab = tab->next )
	SFDDumpTtfTable(sfd,tab,sf);
    for ( ln = sf->names; ln!=NULL; ln=ln->next )
	SFDDumpLangName(sfd,ln);
    if ( sf->gasp_cnt!=0 )
	SFDDumpGasp(sfd,sf);
    if ( sf->design_size!=0 )
	SFDDumpDesignSize(sfd,sf);
    if ( sf->feat_names!=NULL )
	SFDDumpOtfFeatNames(sfd,sf);

return( err );
}

Project: fontforge
File: sfd.c

static void SFDDumpGasp(FILE *sfd, SplineFont *sf) {
    int i;

    if ( sf->gasp_cnt==0 )
return;

    fprintf( sfd, "GaspTable: %d", sf->gasp_cnt );
    for ( i=0; i<sf->gasp_cnt; ++i )
	fprintf( sfd, " %d %d", sf->gasp[i].ppem, sf->gasp[i].flags );
    fprintf( sfd, " %d", sf->gasp_version);
    putc('\n',sfd);
}

Project: fontforge
File: sfd.c

static void SFDParseVertexKern(FILE *sfd, struct mathkernvertex *vertex) {
    int i,ch;

    getint(sfd,&vertex->cnt);
    vertex->mkd = calloc(vertex->cnt,sizeof(struct mathkerndata));
    for ( i=0; i<vertex->cnt; ++i ) {
	SFDParseMathValueRecord(sfd,&vertex->mkd[i].height,&vertex->mkd[i].height_adjusts);
	while ( (ch=nlgetc(sfd))==' ' );
	if ( ch!=EOF && ch!=',' )
	    ungetc(ch,sfd);
	SFDParseMathValueRecord(sfd,&vertex->mkd[i].kern,&vertex->mkd[i].kern_adjusts);
    }
}

Project: fontforge
File: sfd.c

static void SFDParseChainContext(FILE *sfd,SplineFont *sf,FPST *fpst, char *tok, int old) {
    int ch, i, j, k, temp;
    SplineFont *sli_sf = sf->cidmaster ? sf->cidmaster : sf;

    fpst->type = strnmatch(tok,"ContextPos",10)==0 ? pst_contextpos :
		strnmatch(tok,"ContextSub",10)==0 ? pst_contextsub :
		strnmatch(tok,"ChainPos",8)==0 ? pst_chainpos :
		strnmatch(tok,"ChainSub",8)==0 ? pst_chainsub : pst_reversesub;
    getname(sfd,tok);
    fpst->format = strmatch(tok,"glyph")==0 ? pst_glyphs :
		    strmatch(tok,"class")==0 ? pst_class :
		    strmatch(tok,"coverage")==0 ? pst_coverage : pst_reversecoverage;
    if ( old ) {
	fscanf(sfd, "%hu %hu", &((FPST1 *) fpst)->flags, &((FPST1 *) fpst)->script_lang_index );
	if ( ((FPST1 *) fpst)->script_lang_index>=((SplineFont1 *) sli_sf)->sli_cnt && ((FPST1 *) fpst)->script_lang_index!=SLI_NESTED ) {
	    static int complained=false;
	    if ( ((SplineFont1 *) sli_sf)->sli_cnt==0 )
		IError("'%c%c%c%c' has a script index out of bounds: %d\nYou MUST fix this manually",
			(((FPST1 *) fpst)->tag>>24), (((FPST1 *) fpst)->tag>>16)&0xff, (((FPST1 *) fpst)->tag>>8)&0xff, ((FPST1 *) fpst)->tag&0xff,
			((FPST1 *) fpst)->script_lang_index );
	    else if ( !complained )
		IError("'%c%c%c%c' has a script index out of bounds: %d",
			(((FPST1 *) fpst)->tag>>24), (((FPST1 *) fpst)->tag>>16)&0xff, (((FPST1 *) fpst)->tag>>8)&0xff, ((FPST1 *) fpst)->tag&0xff,
			((FPST1 *) fpst)->script_lang_index );
	    else
		IError("'%c%c%c%c' has a script index out of bounds: %d\n",
			(((FPST1 *) fpst)->tag>>24), (((FPST1 *) fpst)->tag>>16)&0xff, (((FPST1 *) fpst)->tag>>8)&0xff, ((FPST1 *) fpst)->tag&0xff,
			((FPST1 *) fpst)->script_lang_index );
	    if ( ((SplineFont1 *) sli_sf)->sli_cnt!=0 )
		((FPST1 *) fpst)->script_lang_index = ((SplineFont1 *) sli_sf)->sli_cnt-1;
	    complained = true;
	}
	while ( (ch=nlgetc(sfd))==' ' || ch=='\t' );
	if ( ch=='\'' ) {
	    ungetc(ch,sfd);
	    ((FPST1 *) fpst)->tag = gettag(sfd);
	} else
	    ungetc(ch,sfd);
    } else {
	fpst->subtable = SFFindLookupSubtableAndFreeName(sf,SFDReadUTF7Str(sfd));
        if ( !fpst->subtable )
            LogError(_("Missing Subtable definition found in chained context"));
        else
	    fpst->subtable->fpst = fpst;
    }
    fscanf(sfd, "%hu %hu %hu %hu", &fpst->nccnt, &fpst->bccnt, &fpst->fccnt, &fpst->rule_cnt );
    if ( fpst->nccnt!=0 || fpst->bccnt!=0 || fpst->fccnt!=0 ) {
	fpst->nclass = malloc(fpst->nccnt*sizeof(char *));
	fpst->nclassnames = calloc(fpst->nccnt,sizeof(char *));
	if ( fpst->nccnt!=0 ) fpst->nclass[0] = NULL;
	if ( fpst->bccnt!=0 || fpst->fccnt!=0 ) {
	    fpst->bclass = malloc(fpst->bccnt*sizeof(char *));
	    fpst->bclassnames = calloc(fpst->bccnt,sizeof(char *));
	    if (fpst->bccnt!=0 ) fpst->bclass[0] = NULL;
	    fpst->fclass = malloc(fpst->fccnt*sizeof(char *));
	    fpst->fclassnames = calloc(fpst->fccnt,sizeof(char *));
	    if (fpst->fccnt!=0 ) fpst->fclass[0] = NULL;
	}
    }

    for ( j=0; j<3; ++j ) {
	for ( i=1; i<(&fpst->nccnt)[j]; ++i ) {
	    getname(sfd,tok);
	    if ( i==1 && j==0 && strcmp(tok,"Class0:")==0 )
		i=0;
	    getint(sfd,&temp);
	    (&fpst->nclass)[j][i] = malloc(temp+1); (&fpst->nclass)[j][i][temp] = '\0';
	    nlgetc(sfd);	/* skip space */
	    fread((&fpst->nclass)[j][i],1,temp,sfd);
	}
    }

    fpst->rules = calloc(fpst->rule_cnt,sizeof(struct fpst_rule));
    for ( i=0; i<fpst->rule_cnt; ++i ) {
	switch ( fpst->format ) {
	  case pst_glyphs:
	    for ( j=0; j<3; ++j ) {
		getname(sfd,tok);
		getint(sfd,&temp);
		(&fpst->rules[i].u.glyph.names)[j] = malloc(temp+1);
		(&fpst->rules[i].u.glyph.names)[j][temp] = '\0';
		nlgetc(sfd);	/* skip space */
		fread((&fpst->rules[i].u.glyph.names)[j],1,temp,sfd);
	    }
	  break;
	  case pst_class:
	    fscanf( sfd, "%d %d %d", &fpst->rules[i].u.class.ncnt, &fpst->rules[i].u.class.bcnt, &fpst->rules[i].u.class.fcnt );
	    for ( j=0; j<3; ++j ) {
		getname(sfd,tok);
		(&fpst->rules[i].u.class.nclasses)[j] = malloc((&fpst->rules[i].u.class.ncnt)[j]*sizeof(uint16));
		for ( k=0; k<(&fpst->rules[i].u.class.ncnt)[j]; ++k ) {
		    getusint(sfd,&(&fpst->rules[i].u.class.nclasses)[j][k]);
		}
	    }
	  break;
	  case pst_coverage:
	  case pst_reversecoverage:
	    fscanf( sfd, "%d %d %d", &fpst->rules[i].u.coverage.ncnt, &fpst->rules[i].u.coverage.bcnt, &fpst->rules[i].u.coverage.fcnt );
	    for ( j=0; j<3; ++j ) {
		(&fpst->rules[i].u.coverage.ncovers)[j] = malloc((&fpst->rules[i].u.coverage.ncnt)[j]*sizeof(char *));
		for ( k=0; k<(&fpst->rules[i].u.coverage.ncnt)[j]; ++k ) {
		    getname(sfd,tok);
		    getint(sfd,&temp);
		    (&fpst->rules[i].u.coverage.ncovers)[j][k] = malloc(temp+1);
		    (&fpst->rules[i].u.coverage.ncovers)[j][k][temp] = '\0';
		    nlgetc(sfd);	/* skip space */
		    fread((&fpst->rules[i].u.coverage.ncovers)[j][k],1,temp,sfd);
		}
	    }
	  break;
	  default:
	  break;
	}
	switch ( fpst->format ) {
	  case pst_glyphs:
	  case pst_class:
	  case pst_coverage:
	    getint(sfd,&fpst->rules[i].lookup_cnt);
	    fpst->rules[i].lookups = malloc(fpst->rules[i].lookup_cnt*sizeof(struct seqlookup));
	    for ( j=k=0; j<fpst->rules[i].lookup_cnt; ++j ) {
		getname(sfd,tok);
		getint(sfd,&fpst->rules[i].lookups[j].seq);
		fpst->rules[i].lookups[k].lookup = SFD_ParseNestedLookup(sfd,sf,old);
		if ( fpst->rules[i].lookups[k].lookup!=NULL )
		    ++k;
	    }
	    fpst->rules[i].lookup_cnt = k;
	  break;
	  case pst_reversecoverage:
	    getname(sfd,tok);
	    getint(sfd,&temp);
	    fpst->rules[i].u.rcoverage.replacements = malloc(temp+1);
	    fpst->rules[i].u.rcoverage.replacements[temp] = '\0';
	    nlgetc(sfd);	/* skip space */
	    fread(fpst->rules[i].u.rcoverage.replacements,1,temp,sfd);
	  break;
	  default:
	  break;
	}
    }
    getname(sfd,tok);	/* EndFPST, or one of the ClassName tokens (in newer sfds) */
    while ( strcmp(tok,"ClassNames:")==0 || strcmp(tok,"BClassNames:")==0 ||
	    strcmp(tok,"FClassNames:")==0 ) {
	int which = strcmp(tok,"ClassNames:")==0 ? 0 :
		    strcmp(tok,"BClassNames:")==0 ? 1 : 2;
	int cnt = (&fpst->nccnt)[which];
	char **classnames = (&fpst->nclassnames)[which];
	int i;

	for ( i=0; i<cnt; ++i )
	    classnames[i] = SFDReadUTF7Str(sfd);
	getname(sfd,tok);	/* EndFPST, or one of the ClassName tokens (in newer sfds) */
    }

}

Project: fontforge
File: sfd.c

static int SFD_Dump( FILE *sfd, SplineFont *sf, EncMap *map, EncMap *normal,
		     int todir, char *dirname)
{
    int i, realcnt;
    BDFFont *bdf;
    int *newgids = NULL;
    int err = false;

    if ( normal!=NULL )
	map = normal;

    SFD_DumpSplineFontMetadata( sfd, sf ); //, map, normal, todir, dirname );

    if ( sf->MATH!=NULL ) {
	struct MATH *math = sf->MATH;
	for ( i=0; math_constants_descriptor[i].script_name!=NULL; ++i ) {
	    fprintf( sfd, "MATH:%s: %d", math_constants_descriptor[i].script_name,
		    *((int16 *) (((char *) (math)) + math_constants_descriptor[i].offset)) );
	    if ( math_constants_descriptor[i].devtab_offset>=0 ) {
		DeviceTable **devtab = (DeviceTable **) (((char *) (math)) + math_constants_descriptor[i].devtab_offset );
		putc(' ',sfd);
		SFDDumpDeviceTable(sfd,*devtab);
	    }
	    putc('\n',sfd);
	}
    }
    if ( sf->python_persistent!=NULL )
	SFDPickleMe(sfd,sf->python_persistent, sf->python_persistent_has_lists);
    if ( sf->subfontcnt!=0 ) {
	/* CID fonts have no encodings, they have registry info instead */
	fprintf(sfd, "Registry: %s\n", sf->cidregistry );
	fprintf(sfd, "Ordering: %s\n", sf->ordering );
	fprintf(sfd, "Supplement: %d\n", sf->supplement );
	fprintf(sfd, "CIDVersion: %g\n", (double) sf->cidversion );	/* This is a number whereas "version" is a string */
    } else
	SFDDumpEncoding(sfd,map->enc,"Encoding");
    if ( normal!=NULL )
	fprintf(sfd, "Compacted: 1\n" );
    fprintf( sfd, "UnicodeInterp: %s\n", unicode_interp_names[sf->uni_interp]);
    fprintf( sfd, "NameList: %s\n", sf->for_new_glyphs->title );

    if ( map->remap!=NULL ) {
	struct remap *remap;
	int n;
	for ( n=0,remap = map->remap; remap->infont!=-1; ++n, ++remap );
	fprintf( sfd, "RemapN: %d\n", n );
	for ( remap = map->remap; remap->infont!=-1; ++remap )
	    fprintf(sfd, "Remap: %x %x %d\n", (int) remap->firstenc, (int) remap->lastenc, (int) remap->infont );
    }
    if ( sf->display_size!=0 )
	fprintf( sfd, "DisplaySize: %d\n", sf->display_size );
    if ( sf->display_layer!=ly_fore )
	fprintf( sfd, "DisplayLayer: %d\n", sf->display_layer );
    fprintf( sfd, "AntiAlias: %d\n", sf->display_antialias );
    fprintf( sfd, "FitToEm: %d\n", sf->display_bbsized );
    if ( sf->extrema_bound!=0 )
	fprintf( sfd, "ExtremaBound: %d\n", sf->extrema_bound );
    if ( sf->width_separation!=0 )
	fprintf( sfd, "WidthSeparation: %d\n", sf->width_separation );
    {
	int rc, cc, te;
	if ( (te = FVWinInfo(sf->fv,&cc,&rc))!= -1 )
	    fprintf( sfd, "WinInfo: %d %d %d\n", te, cc, rc );
	else if ( sf->top_enc!=-1 )
	    fprintf( sfd, "WinInfo: %d %d %d\n", sf->top_enc, sf->desired_col_cnt,
		sf->desired_row_cnt);
    }
    if ( sf->onlybitmaps!=0 )
	fprintf( sfd, "OnlyBitmaps: %d\n", sf->onlybitmaps );
    if ( sf->private!=NULL )
	SFDDumpPrivate(sfd,sf->private);
#if HANYANG
    if ( sf->rules!=NULL )
	SFDDumpCompositionRules(sfd,sf->rules);
#endif
    if ( sf->grid.splines!=NULL ) {
	if ( sf->grid.order2 )
	    fprintf(sfd, "GridOrder2: %d\n", sf->grid.order2 );
	fprintf(sfd, "Grid\n" );
	SFDDumpSplineSet(sfd,sf->grid.splines,sf->grid.order2);
    }
    if ( sf->texdata.type!=tex_unset ) {
	fprintf(sfd, "TeXData: %d %d", (int) sf->texdata.type, (int) ((sf->design_size<<19)+2)/5 );
	for ( i=0; i<22; ++i )
	    fprintf(sfd, " %d", (int) sf->texdata.params[i]);
	putc('\n',sfd);
    }
    if ( sf->anchor!=NULL ) {
	AnchorClass *an;
	fprintf(sfd, "AnchorClass2:");
	for ( an=sf->anchor; an!=NULL; an=an->next ) {
	    putc(' ',sfd);
	    SFDDumpUTF7Str(sfd,an->name);
            if ( an->subtable!=NULL ) {
	        putc(' ',sfd);
	        SFDDumpUTF7Str(sfd,an->subtable->subtable_name);
            }
            else
                fprintf(sfd, "\"\" ");
	}
	putc('\n',sfd);
    }

    if ( sf->subfontcnt!=0 ) {
	if ( todir ) {
	    for ( i=0; i<sf->subfontcnt; ++i ) {
		char *subfont = malloc(strlen(dirname)+1+strlen(sf->subfonts[i]->fontname)+20);
		char *fontprops;
		FILE *ssfd;
		sprintf( subfont,"%s/%s" SUBFONT_EXT, dirname, sf->subfonts[i]->fontname );
		GFileMkDir(subfont, 0755);
		fontprops = malloc(strlen(subfont)+strlen("/" FONT_PROPS)+1);
		strcpy(fontprops,subfont); strcat(fontprops,"/" FONT_PROPS);
		ssfd = fopen( fontprops,"w");
		if ( ssfd!=NULL ) {
		    err |= SFD_Dump(ssfd,sf->subfonts[i],map,NULL,todir,subfont);
		    if ( ferror(ssfd) ) err = true;
		    if ( fclose(ssfd)) err = true;
		} else
		    err = true;
		free(fontprops);
		free(subfont);
	    }
	} else {
	    int max;
	    for ( i=max=0; i<sf->subfontcnt; ++i )
		if ( max<sf->subfonts[i]->glyphcnt )
		    max = sf->subfonts[i]->glyphcnt;
	    fprintf(sfd, "BeginSubFonts: %d %d\n", sf->subfontcnt, max );
	    for ( i=0; i<sf->subfontcnt; ++i )
		SFD_Dump(sfd,sf->subfonts[i],map,NULL,false, NULL);
	    fprintf(sfd, "EndSubFonts\n" );
	}
    } else {
	int enccount = map->enccount;
	if ( sf->cidmaster!=NULL ) {
	    realcnt = -1;
	    enccount = sf->glyphcnt;
	} else {
	    realcnt = 0;
	    for ( i=0; i<sf->glyphcnt; ++i ) if ( !SFDOmit(sf->glyphs[i]) )
		++realcnt;
	    if ( realcnt!=sf->glyphcnt ) {
		newgids = malloc(sf->glyphcnt*sizeof(int));
		realcnt = 0;
		for ( i=0; i<sf->glyphcnt; ++i )
		    if ( SFDOmit(sf->glyphs[i]) )
			newgids[i] = -1;
		    else
			newgids[i] = realcnt++;
	    }
	}
	if ( !todir )
	    fprintf(sfd, "BeginChars: %d %d\n",
	        enccount<map->enc->char_cnt? map->enc->char_cnt : enccount,
	        realcnt );
	for ( i=0; i<sf->glyphcnt; ++i ) {
	    if ( !SFDOmit(sf->glyphs[i]) ) {
		if ( !todir )
		SFDDumpChar(sfd,sf->glyphs[i],map,newgids,todir,1);
		else {
		    char *glyphfile = malloc(strlen(dirname)+2*strlen(sf->glyphs[i]->name)+20);
		    FILE *gsfd;
		    appendnames(glyphfile,dirname,"/",sf->glyphs[i]->name,GLYPH_EXT );
		    gsfd = fopen(glyphfile,"w");
		    if ( gsfd!=NULL ) {
			SFDDumpChar(gsfd,sf->glyphs[i],map,newgids,todir,1);
			if ( ferror(gsfd)) err = true;
			if ( fclose(gsfd)) err = true;
		    } else
			err = true;
		    free(glyphfile);
		}
	    }
	    ff_progress_next();
	}
	if ( !todir )
	    fprintf(sfd, "EndChars\n" );
    }

    if ( sf->bitmaps!=NULL )
	ff_progress_change_line2(_("Saving Bitmaps"));
    for ( bdf = sf->bitmaps; bdf!=NULL; bdf=bdf->next ) {
	if ( todir ) {
	    char *strike = malloc(strlen(dirname)+1+20+20);
	    char *strikeprops;
	    FILE *ssfd;
	    sprintf( strike,"%s/%d" STRIKE_EXT, dirname, bdf->pixelsize );
	    GFileMkDir(strike, 0755);
	    strikeprops = malloc(strlen(strike)+strlen("/" STRIKE_PROPS)+1);
	    strcpy(strikeprops,strike); strcat(strikeprops,"/" STRIKE_PROPS);
	    ssfd = fopen( strikeprops,"w");
	    if ( ssfd!=NULL ) {
		err |= SFDDumpBitmapFont(ssfd,bdf,map,newgids,todir,strike);
		if ( ferror(ssfd) ) err = true;
		if ( fclose(ssfd)) err = true;
	    } else
		err = true;
	    free(strikeprops);
	    free(strike);
	} else
	    SFDDumpBitmapFont(sfd,bdf,map,newgids,todir,dirname);
    }
    fprintf(sfd, sf->cidmaster==NULL?"EndSplineFont\n":"EndSubSplineFont\n" );
    free(newgids);
return( err );
}

Project: fontforge
File: sfd.c

static void SFDDumpTtfInstrsExplicit(FILE *sfd,uint8 *ttf_instrs, int16 ttf_instrs_len )
{
    char *instrs = _IVUnParseInstrs( ttf_instrs, ttf_instrs_len );
    char *pt;
    fprintf( sfd, "TtInstrs:\n" );
    for ( pt=instrs; *pt!='\0'; ++pt )
	putc(*pt,sfd);
    if ( pt[-1]!='\n' )
	putc('\n',sfd);
    free(instrs);
    fprintf( sfd, "%s\n", end_tt_instrs );
}

Project: fontforge
File: sfd.c

static int getreal(FILE *sfd, real *val) {
    char tokbuf[100];
    int ch;
    char *pt=tokbuf, *end = tokbuf+100-2, *nend;

    while ( isspace(ch = nlgetc(sfd)));
    if ( ch!='e' && ch!='E' )		/* real's can't begin with exponants */
	while ( isdigit(ch) || ch=='-' || ch=='+' || ch=='e' || ch=='E' || ch=='.' || ch==',' ) {
	    if ( pt<end ) *pt++ = ch;
	    ch = nlgetc(sfd);
	}
    *pt='\0';
    ungetc(ch,sfd);
    *val = strtod(tokbuf,&nend);
    /* Beware of different locals! */
    if ( *nend!='\0' ) {
	if ( *nend=='.' )
	    *nend = ',';
	else if ( *nend==',' )
	    *nend = '.';
	*val = strtod(tokbuf,&nend);
    }
return( pt!=tokbuf && *nend=='\0'?1:ch==EOF?-1: 0 );
}

Project: fontforge
File: sfd.c

static void SFDDumpGradient(FILE *sfd, const char *keyword, struct gradient *gradient) {
    int i;

    /* Use ";" as a coord separator because we treat "," as a potential decimal point */
    fprintf( sfd, "%s %g;%g %g;%g %g %s %d ", keyword,
	    (double) gradient->start.x, (double) gradient->start.y,
	    (double) gradient->stop.x, (double) gradient->stop.y,
	    (double) gradient->radius,
	    spreads[gradient->sm],
	    gradient->stop_cnt );
    for ( i=0 ; i<gradient->stop_cnt; ++i ) {
	fprintf( sfd, "{%g #%06x %g} ", (double) gradient->grad_stops[i].offset,
		gradient->grad_stops[i].col, (double) gradient->grad_stops[i].opacity );
    }
    putc('\n',sfd);
}

Project: fontforge
File: sfd.c

static struct ttf_table *SFDGetTtTable(FILE *sfd, SplineFont *sf,struct ttf_table *lasttab[2]) {
    /* We've read the TtTable token, it is followed by a tag */
    /* and then the instructions in text format */
    int ch;
    int which;
    struct ttf_table *tab = chunkalloc(sizeof(struct ttf_table));
    char *buf=NULL, *pt=buf, *end=buf;
    int backlen = strlen(end_tt_instrs);

    tab->tag = gettag(sfd);

    if ( tab->tag==CHR('f','p','g','m') || tab->tag==CHR('p','r','e','p') ||
	    tab->tag==CHR('c','v','t',' ') || tab->tag==CHR('m','a','x','p'))
	which = 0;
    else
	which = 1;

    while ( (ch=nlgetc(sfd))!=EOF ) {
	if ( pt>=end ) {
	    char *newbuf = realloc(buf,(end-buf+200));
	    pt = newbuf+(pt-buf);
	    end = newbuf+(end+200-buf);
	    buf = newbuf;
	}
	*pt++ = ch;
	if ( pt-buf>backlen && strncmp(pt-backlen,end_tt_instrs,backlen)==0 ) {
	    pt -= backlen;
    break;
	}
    }
    *pt = '\0';
    tab->data = _IVParse(sf,buf,&tab->len,tterr,NULL);
    free(buf);

    if ( lasttab[which]!=NULL )
	lasttab[which]->next = tab;
    else if ( which==0 )
	sf->ttf_tables = tab;
    else
	sf->ttf_tab_saved = tab;
    lasttab[which] = tab;
return( tab );
}

Project: fontforge
File: sfd.c

static DStemInfo *SFDReadDHints( SplineFont *sf,FILE *sfd,int old ) {
    DStemInfo *head=NULL, *last=NULL, *cur;
    int i;
    BasePoint bp[4], *bpref[4], left, right, unit;
    double rstartoff, rendoff, lendoff;

    if ( old ) {
        for ( i=0 ; i<4 ; i++ ) bpref[i] = &bp[i];

        while ( getreal( sfd,&bp[0].x ) && getreal( sfd,&bp[0].y ) &&
	        getreal( sfd,&bp[1].x ) && getreal( sfd,&bp[1].y ) &&
	        getreal( sfd,&bp[2].x ) && getreal( sfd,&bp[2].y ) &&
	        getreal( sfd,&bp[3].x ) && getreal( sfd,&bp[3].y )) {

            /* Ensure point coordinates specified in the sfd file do */
            /* form a diagonal line */
            if ( PointsDiagonalable( sf,bpref,&unit )) {
	        cur = chunkalloc( sizeof( DStemInfo ));
	        cur->left = *bpref[0];
	        cur->right = *bpref[1];
                cur->unit = unit;
                /* Generate a temporary hint instance, so that the hint can */
                /* be visible in charview even if subsequent rebuilding instances */
                /* fails (e. g. for composite characters) */
                cur->where = chunkalloc( sizeof( HintInstance ));
                rstartoff = ( cur->right.x - cur->left.x ) * cur->unit.x +
                            ( cur->right.y - cur->left.y ) * cur->unit.y;
                rendoff =   ( bpref[2]->x - cur->left.x ) * cur->unit.x +
                            ( bpref[2]->y - cur->left.y ) * cur->unit.y;
                lendoff =   ( bpref[3]->x - cur->left.x ) * cur->unit.x +
                            ( bpref[3]->y - cur->left.y ) * cur->unit.y;
                cur->where->begin = ( rstartoff > 0 ) ? rstartoff : 0;
                cur->where->end   = ( rendoff > lendoff ) ? lendoff : rendoff;
                MergeDStemInfo( sf,&head,cur );
            }
        }
    } else {
        while ( getreal( sfd,&left.x ) && getreal( sfd,&left.y ) &&
                getreal( sfd,&right.x ) && getreal( sfd,&right.y ) &&
                getreal( sfd,&unit.x ) && getreal( sfd,&unit.y )) {
	    cur = chunkalloc( sizeof( DStemInfo ));
	    cur->left = left;
	    cur->right = right;
            cur->unit = unit;
	    cur->where = SFDReadHintInstances( sfd,NULL );
	    if ( head == NULL )
	        head = cur;
	    else
	        last->next = cur;
	    last = cur;
        }
    }
return( head );
}

Project: fontforge
File: sfd.c

static void SFDSetEncMap(SplineFont *sf,int orig_pos,int enc) {
    EncMap *map = sf->map;

    if ( map==NULL )
return;

    if ( orig_pos>=map->backmax ) {
	int old = map->backmax;
	map->backmax = orig_pos+10;
	map->backmap = realloc(map->backmap,map->backmax*sizeof(int));
	memset(map->backmap+old,-1,(map->backmax-old)*sizeof(int));
    }
    if ( map->backmap[orig_pos] == -1 )		/* backmap will not be unique if multiple encodings come from same glyph */
	map->backmap[orig_pos] = enc;
    if ( enc>=map->encmax ) {
	int old = map->encmax;
	map->encmax = enc+10;
	map->map = realloc(map->map,map->encmax*sizeof(int));
	memset(map->map+old,-1,(map->encmax-old)*sizeof(int));
    }
    if ( enc>=map->enccount )
	map->enccount = enc+1;
    if ( enc!=-1 )
	map->map[enc] = orig_pos;
}

Project: fontforge
File: sfd.c

static void SFDDumpAnchorPoints(FILE *sfd,AnchorPoint *ap) {
    if (ap==NULL) {
	return;
    }

    for ( ; ap!=NULL; ap=ap->next )
    {
	fprintf( sfd, "AnchorPoint: " );
	SFDDumpUTF7Str(sfd,ap->anchor->name);
	putc(' ',sfd);
	fprintf( sfd, "%g %g %s %d",
		(double) ap->me.x, (double) ap->me.y,
		ap->type==at_centry ? "entry" :
		ap->type==at_cexit ? "exit" :
		ap->type==at_mark ? "mark" :
		ap->type==at_basechar ? "basechar" :
		ap->type==at_baselig ? "baselig" : "basemark",
		ap->lig_index );
	if ( ap->xadjust.corrections!=NULL || ap->yadjust.corrections!=NULL ) {
	    putc(' ',sfd);
	    SFDDumpDeviceTable(sfd,&ap->xadjust);
	    putc(' ',sfd);
	    SFDDumpDeviceTable(sfd,&ap->yadjust);
	} else
	if ( ap->has_ttf_pt )
	    fprintf( sfd, " %d", ap->ttf_pt_index );
	putc('\n',sfd);
    }
}

Project: fontforge
File: sfd.c

static ImageList *SFDGetImagePNG(FILE *sfd) {
    int pnglen;
    ImageList *img;
    struct enc85 dec = {0};
    int i, ch;

    img = calloc(1,sizeof(ImageList));
    dec.pos = -1;
    dec.sfd = sfd;

    getint(sfd,&pnglen);
    getreal(sfd,&img->xoff);
    getreal(sfd,&img->yoff);
    getreal(sfd,&img->xscale);
    getreal(sfd,&img->yscale);

    while ( (ch=nlgetc(sfd))==' ' || ch=='\t' )
        /* skip */;

    char* pngbuf = malloc(pnglen * sizeof(char));
    if (pngbuf == NULL) {
        IError("Failed to allocate buffer to read PNG in SFD file");
        return NULL;
    }

    for (i = 0; i<pnglen; ++i) {
        pngbuf[i] = Dec85(&dec);
    }

    img->image = GImageReadPngBuf(pngbuf, pnglen);
    free(pngbuf);

    if (img->image == NULL) {
        IError("Failed to read PNG in SFD file, skipping it.");
        free(img);
        return NULL;
    }

    img->bb.minx = img->xoff; img->bb.maxy = img->yoff;
    img->bb.maxx = img->xoff + GImageGetWidth(img->image)*img->xscale;
    img->bb.miny = img->yoff - GImageGetHeight(img->image)*img->yscale;
    return img;
}

Project: fontforge
File: sfd.c

void SFDGetPSTs( FILE *sfd, SplineChar *sc, char* ttok ) {
    struct splinefont * sf = sc->parent;
    char tok[2001], ch;
    int isliga = 0, ispos, issubs, ismult, islcar, ispair, temp;
    PST *last = NULL;
    uint32 script = 0;
    SplineFont *sli_sf = sf->cidmaster ? sf->cidmaster : sf;

    strncpy(tok,ttok,sizeof(tok)-1);

    if ( strmatch(tok,"Script:")==0 ) {
	/* Obsolete. But still used for parsing obsolete ligature/subs tags */
	while ( (ch=nlgetc(sfd))==' ' || ch=='\t' );
	if ( ch=='\n' || ch=='\r' )
	    script = 0;
	else {
	    ungetc(ch,sfd);
	    script = gettag(sfd);
	}
    } else if ( (ispos = (strmatch(tok,"Position:")==0)) ||
		( ispos  = (strmatch(tok,"Position2:")==0)) ||
		( ispair = (strmatch(tok,"PairPos:")==0)) ||
		( ispair = (strmatch(tok,"PairPos2:")==0)) ||
		( islcar = (strmatch(tok,"LCarets:")==0)) ||
		( islcar = (strmatch(tok,"LCarets2:")==0)) ||
		( isliga = (strmatch(tok,"Ligature:")==0)) ||
		( isliga = (strmatch(tok,"Ligature2:")==0)) ||
		( issubs = (strmatch(tok,"Substitution:")==0)) ||
		( issubs = (strmatch(tok,"Substitution2:")==0)) ||
		( ismult = (strmatch(tok,"MultipleSubs:")==0)) ||
		( ismult = (strmatch(tok,"MultipleSubs2:")==0)) ||
		strmatch(tok,"AlternateSubs:")==0 ||
		strmatch(tok,"AlternateSubs2:")==0 ) {
	    PST *pst;
	    int old, type;
	    type = ispos ? pst_position :
			 ispair ? pst_pair :
			 islcar ? pst_lcaret :
			 isliga ? pst_ligature :
			 issubs ? pst_substitution :
			 ismult ? pst_multiple :
			 pst_alternate;
	    if ( strchr(tok,'2')!=NULL ) {
		old = false;
		pst = chunkalloc(sizeof(PST));
		if ( type!=pst_lcaret )
		    pst->subtable = SFFindLookupSubtableAndFreeName(sf,SFDReadUTF7Str(sfd));
	    } else {
		old = true;
		pst = chunkalloc(sizeof(PST1));
		((PST1 *) pst)->tag = CHR('l','i','g','a');
		((PST1 *) pst)->script_lang_index = 0xffff;
		while ( (ch=nlgetc(sfd))==' ' || ch=='\t' );
		if ( isdigit(ch)) {
		    int temp;
		    ungetc(ch,sfd);
		    getint(sfd,&temp);
		    ((PST1 *) pst)->flags = temp;
		    while ( (ch=nlgetc(sfd))==' ' || ch=='\t' );
		} else
		    ((PST1 *) pst)->flags = 0 /*PSTDefaultFlags(type,sc)*/;
		if ( isdigit(ch)) {
		    ungetc(ch,sfd);
		    getusint(sfd,&((PST1 *) pst)->script_lang_index);
		    while ( (ch=nlgetc(sfd))==' ' || ch=='\t' );
		} else
		    ((PST1 *) pst)->script_lang_index = SFFindBiggestScriptLangIndex(sf,
			    script!=0?script:SCScriptFromUnicode(sc),DEFAULT_LANG);
		if ( ch=='\'' ) {
		    ungetc(ch,sfd);
		    ((PST1 *) pst)->tag = gettag(sfd);
		} else if ( ch=='<' ) {
		    getint(sfd,&temp);
		    ((PST1 *) pst)->tag = temp<<16;
		    nlgetc(sfd);	/* comma */
		    getint(sfd,&temp);
		    ((PST1 *) pst)->tag |= temp;
		    nlgetc(sfd);	/* close '>' */
		    ((PST1 *) pst)->macfeature = true;
		} else
		    ungetc(ch,sfd);
		if ( type==pst_lcaret ) {
		/* These are meaningless for lcarets, set them to innocuous values */
		    ((PST1 *) pst)->script_lang_index = SLI_UNKNOWN;
		    ((PST1 *) pst)->tag = CHR(' ',' ',' ',' ');
		} else if ( ((PST1 *) pst)->script_lang_index>=((SplineFont1 *) sli_sf)->sli_cnt && ((PST1 *) pst)->script_lang_index!=SLI_NESTED ) {
		    static int complained=false;
		    if ( !complained )
			IError("'%c%c%c%c' in %s has a script index out of bounds: %d",
				(((PST1 *) pst)->tag>>24), (((PST1 *) pst)->tag>>16)&0xff, (((PST1 *) pst)->tag>>8)&0xff, ((PST1 *) pst)->tag&0xff,
				sc->name, ((PST1 *) pst)->script_lang_index );
		    else
			IError( "'%c%c%c%c' in %s has a script index out of bounds: %d\n",
				(((PST1 *) pst)->tag>>24), (((PST1 *) pst)->tag>>16)&0xff, (((PST1 *) pst)->tag>>8)&0xff, ((PST1 *) pst)->tag&0xff,
				sc->name, ((PST1 *) pst)->script_lang_index );
		    ((PST1 *) pst)->script_lang_index = SFFindBiggestScriptLangIndex(sli_sf,
			    SCScriptFromUnicode(sc),DEFAULT_LANG);
		    complained = true;
		}
	    }
	    if ( (sf->sfd_version<2)!=old ) {
		IError( "Version mixup in PST of sfd file." );
exit(1);
	    }
	    if ( last==NULL )
		sc->possub = pst;
	    else
		last->next = pst;
	    last = pst;
	    pst->type = type;
	    if ( pst->type==pst_position ) {
		fscanf( sfd, " dx=%hd dy=%hd dh=%hd dv=%hd",
			&pst->u.pos.xoff, &pst->u.pos.yoff,
			&pst->u.pos.h_adv_off, &pst->u.pos.v_adv_off);
		pst->u.pos.adjust = SFDReadValDevTab(sfd);
		ch = nlgetc(sfd);		/* Eat new line */
	    } else if ( pst->type==pst_pair ) {
		getname(sfd,tok);
		pst->u.pair.paired = copy(tok);
		pst->u.pair.vr = chunkalloc(sizeof(struct vr [2]));
		fscanf( sfd, " dx=%hd dy=%hd dh=%hd dv=%hd",
			&pst->u.pair.vr[0].xoff, &pst->u.pair.vr[0].yoff,
			&pst->u.pair.vr[0].h_adv_off, &pst->u.pair.vr[0].v_adv_off);
		pst->u.pair.vr[0].adjust = SFDReadValDevTab(sfd);
		fscanf( sfd, " dx=%hd dy=%hd dh=%hd dv=%hd",
			&pst->u.pair.vr[1].xoff, &pst->u.pair.vr[1].yoff,
			&pst->u.pair.vr[1].h_adv_off, &pst->u.pair.vr[1].v_adv_off);
		pst->u.pair.vr[0].adjust = SFDReadValDevTab(sfd);
		ch = nlgetc(sfd);
	    } else if ( pst->type==pst_lcaret ) {
		int i;
		fscanf( sfd, " %d", &pst->u.lcaret.cnt );
		pst->u.lcaret.carets = malloc(pst->u.lcaret.cnt*sizeof(int16));
		for ( i=0; i<pst->u.lcaret.cnt; ++i )
		    fscanf( sfd, " %hd", &pst->u.lcaret.carets[i]);
		geteol(sfd,tok);
	    } else {
		geteol(sfd,tok);
		pst->u.lig.components = copy(tok);	/* it's in the same place for all formats */
		if ( isliga ) {
		    pst->u.lig.lig = sc;
		    if ( old )
			last = (PST *) LigaCreateFromOldStyleMultiple((PST1 *) pst);
		}
	    }
#ifdef FONTFORGE_CONFIG_CVT_OLD_MAC_FEATURES
	    if ( old )
		CvtOldMacFeature((PST1 *) pst);
#endif
    } else {
	return;
    }

    // we matched something, grab the next top level token to ttok
    getname( sfd, ttok );
}

Project: fontforge
File: sfd.c

static void SFDDumpJustify(FILE *sfd,SplineFont *sf) {
    Justify *jscript;
    struct jstf_lang *jlang;
    int i;

    for ( jscript = sf->justify; jscript!=NULL; jscript=jscript->next ) {
	fprintf( sfd, "Justify: '%c%c%c%c'\n",
		jscript->script>>24,
		jscript->script>>16,
		jscript->script>>8,
		jscript->script);
	if ( jscript->extenders!=NULL )
	    fprintf( sfd, "JstfExtender: %s\n", jscript->extenders );
	for ( jlang = jscript->langs; jlang!=NULL; jlang = jlang->next ) {
	    fprintf( sfd, "JstfLang: '%c%c%c%c' %d\n",
		jlang->lang>>24,
		jlang->lang>>16,
		jlang->lang>>8,
		jlang->lang, jlang->cnt );
	    for ( i=0; i<jlang->cnt; ++i ) {
		fprintf( sfd, "JstfPrio:\n" );
		SFDDumpJSTFLookups(sfd,"JstfEnableShrink:", jlang->prios[i].enableShrink );
		SFDDumpJSTFLookups(sfd,"JstfDisableShrink:", jlang->prios[i].disableShrink );
		SFDDumpJSTFLookups(sfd,"JstfMaxShrink:", jlang->prios[i].maxShrink );
		SFDDumpJSTFLookups(sfd,"JstfEnableExtend:", jlang->prios[i].enableExtend );
		SFDDumpJSTFLookups(sfd,"JstfDisableExtend:", jlang->prios[i].disableExtend );
		SFDDumpJSTFLookups(sfd,"JstfMaxExtend:", jlang->prios[i].maxExtend );
	    }
	}
    }
    if ( sf->justify!=NULL )
	fprintf( sfd, "EndJustify\n" );
}

Project: fontforge
File: sfd.c

static void SFDGetSubrs(FILE *sfd) {
    /* Obselete, parse it in case there are any old sfds */
    int i, cnt, tot, len;
    struct enc85 dec;

    getint(sfd,&cnt);
    tot = 0;
    for ( i=0; i<cnt; ++i ) {
	getint(sfd,&len);
	tot += len;
    }

    memset(&dec,'\0', sizeof(dec)); dec.pos = -1;
    dec.sfd = sfd;
    for ( i=0; i<tot; ++i )
	Dec85(&dec);
}

Project: fontforge
File: sfd.c

SplineFont *SFRecoverFile(char *autosavename,int inquire,int *state) {
    FILE *asfd;
    SplineFont *ret;
    char tok[1025];

    if (!inquire) {
        *state = 1; //Default to recover all
    }
    if (!ask_about_file(autosavename, state, &asfd)) {
return( NULL );
    }
    locale_t tmplocale; locale_t oldlocale; // Declare temporary locale storage.
    switch_to_c_locale(&tmplocale, &oldlocale); // Switch to the C locale temporarily and cache the old locale.
    ret = SlurpRecovery(asfd,tok,sizeof(tok));
    if ( ret==NULL ) {
	const char *buts[3];
	buts[0] = "_Forget It"; buts[1] = "_Try Again"; buts[2] = NULL;
	if ( ff_ask(_("Recovery Failed"),(const char **) buts,0,1,_("Automagic recovery of changes to %.80s failed.\nShould FontForge try again to recover next time you start it?"),tok)==0 )
	    unlink(autosavename);
    }
    switch_to_old_locale(&tmplocale, &oldlocale); // Switch to the cached locale.
    fclose(asfd);
    if ( ret )
	ret->autosavename = copy(autosavename);
return( ret );
}

Project: fontforge
File: sfd1.c

static void SFDCleanupAnchorClasses(SplineFont *sf) {
    AnchorClass *ac;
    AnchorPoint *ap;
    int i, j, scnt;
#define S_MAX	100
    uint32 scripts[S_MAX];
    int merge=0;

    for ( ac = sf->anchor; ac!=NULL; ac=ac->next ) {
	if ( ((AnchorClass1 *) ac)->script_lang_index==0xffff ) {
	    scnt = 0;
	    for ( i=0; i<sf->glyphcnt; ++i ) if ( sf->glyphs[i]!=NULL ) {
		for ( ap = sf->glyphs[i]->anchor; ap!=NULL && ap->anchor!=ac; ap=ap->next );
		if ( ap!=NULL && scnt<S_MAX ) {
		    uint32 script = SCScriptFromUnicode(sf->glyphs[i]);
		    if ( script==0 )
	    continue;
		    for ( j=0; j<scnt; ++j )
			if ( scripts[j]==script )
		    break;
		    if ( j==scnt )
			scripts[scnt++] = script;
		}
	    }
	    ((AnchorClass1 *) ac)->script_lang_index = SFAddScriptIndex((SplineFont1 *) sf,scripts,scnt);
	}
	if ( ((AnchorClass1 *) ac)->merge_with == 0xffff )
	    ((AnchorClass1 *) ac)->merge_with = ++merge;
    }
#undef S_MAX
}

Project: fontforge
File: sfd.c

static void SFDDumpImage(FILE *sfd,ImageList *img) {
    GImage *image = img->image;
    struct _GImage *base = image->list_len==0?image->u.image:image->u.images[0];
    struct enc85 enc;
    int rlelen;
    uint8 *rle;
    int i;

    rle = image2rle(base,&rlelen);
    fprintf(sfd, "Image: %d %d %d %d %d %x %g %g %g %g %d\n",
	    (int) base->width, (int) base->height, base->image_type,
	    (int) (base->image_type==it_true?3*base->width:base->bytes_per_line),
	    base->clut==NULL?0:base->clut->clut_len,(int) base->trans,
	    (double) img->xoff, (double) img->yoff, (double) img->xscale, (double) img->yscale, rlelen );
    memset(&enc,'\0',sizeof(enc));
    enc.sfd = sfd;
    if ( base->clut!=NULL ) {
	for ( i=0; i<base->clut->clut_len; ++i ) {
	    SFDEnc85(&enc,base->clut->clut[i]>>16);
	    SFDEnc85(&enc,(base->clut->clut[i]>>8)&0xff);
	    SFDEnc85(&enc,base->clut->clut[i]&0xff);
	}
    }
    if ( rle!=NULL ) {
	uint8 *pt=rle, *end=rle+rlelen;
	while ( pt<end )
	    SFDEnc85(&enc,*pt++);
	free( rle );
    } else {
	for ( i=0; i<base->height; ++i ) {
	    if ( base->image_type==it_rgba ) {
		uint32 *ipt = (uint32 *) (base->data + i*base->bytes_per_line);
		uint32 *iend = (uint32 *) (base->data + (i+1)*base->bytes_per_line);
		while ( ipt<iend ) {
		    SFDEnc85(&enc,*ipt>>24);
		    SFDEnc85(&enc,(*ipt>>16)&0xff);
		    SFDEnc85(&enc,(*ipt>>8)&0xff);
		    SFDEnc85(&enc,*ipt&0xff);
		    ++ipt;
		}
	    } else if ( base->image_type==it_true ) {
		int *ipt = (int *) (base->data + i*base->bytes_per_line);
		int *iend = (int *) (base->data + (i+1)*base->bytes_per_line);
		while ( ipt<iend ) {
		    SFDEnc85(&enc,*ipt>>16);
		    SFDEnc85(&enc,(*ipt>>8)&0xff);
		    SFDEnc85(&enc,*ipt&0xff);
		    ++ipt;
		}
	    } else {
		uint8 *pt = (uint8 *) (base->data + i*base->bytes_per_line);
		uint8 *end = (uint8 *) (base->data + (i+1)*base->bytes_per_line);
		while ( pt<end ) {
		    SFDEnc85(&enc,*pt);
		    ++pt;
		}
	    }
	}
    }
    SFDEnc85EndEnc(&enc);
    fprintf(sfd,"\nEndImage\n" );
}

Project: fontforge
File: sfd.c

static void tterr(void *UNUSED(rubbish), char *message, int UNUSED(pos)) {
    LogError(_("When loading tt instrs from sfd: %s\n"), message );
}

Project: fontforge
File: sfd.c

static void SFDGetHintMask(FILE *sfd,HintMask *hintmask) {
    int nibble = 0, ch;

    memset(hintmask,0,sizeof(HintMask));
    for (;;) {
	ch = nlgetc(sfd);
	if ( isdigit(ch))
	    ch -= '0';
	else if ( ch>='a' && ch<='f' )
	    ch -= 'a'-10;
	else if ( ch>='A' && ch<='F' )
	    ch -= 'A'-10;
	else {
	    ungetc(ch,sfd);
    break;
	}
	if ( nibble<2*HntMax/8 )
	    (*hintmask)[nibble>>1] |= ch<<(4*(1-(nibble&1)));
	++nibble;
    }
}