#include #include #include "modgmt_map.h" #include "modgmt_func.h" #include "modgmt_gsfuncs.h" struct input_runtime { std::list >::const_iterator ci,end; size_t pos; }; static int gs_bbox_callback(void *caller_handle, char *buf, int len) { struct input_runtime* r=static_cast(static_cast(caller_handle)->indata); size_t buflen=static_cast(len); size_t inbuf=0; if(r->ci==r->end) return 0; while(inbuf!=buflen) { if((*r->ci)->length()-r->pos>=buflen-inbuf) // Remainder of string greater or equal remainder of buffer { // Just copy part of string to buffer memcpy(buf+inbuf,(*r->ci)->c_str()+r->pos,buflen-inbuf); r->pos+=buflen-inbuf; inbuf=buflen; } else // Remainder of string lesser then remainder of buffer { // Copy remainder of string to buffer memcpy(buf+inbuf,(*r->ci)->c_str()+r->pos,(*r->ci)->length()-r->pos); inbuf+=(*r->ci)->length()-r->pos; // Go to next string r->ci++; r->pos=0; if(r->ci==r->end) break; // No more strings, leave. } } return inbuf; } static inline int eps2pdf(const std::string& eps, std::string* pdf, double res, uint ta=4, uint ga=4) { if(!gs_abilities.havepdf) return 1; // No pdf support return GhostRun("-r"+ToString(res)+" -dEPSCrop -dTextAlphaBits="+ToString(ta)+" -dGraphicAlphaBits="+ToString(ga)+" -dNOPLATFONT -dSubsetFonts=true -dEmbedAllFonts=true -dAutoFilterColorImages=false -dColorImageFilter=/FlateEncode -dAutoFilterGrayImages=false -dGrayImageFilter=/FlateEncode -dAutoFilterMonoImages=false -dMonoImageFilter=/CCITTFaxEncode -sDEVICE=pdfwrite -dMaxInlineImageSize=0 -c .setpdfwrite <> setdistillerparams",eps,0,0,pdf); } // Creating eps map from sequence of layers /* Input: If first argument is a string, then this string is a title of map (%%Title parameter in eps file). Other arguments are sequence of pairs and layers. Pairs can be x, y, xr, yr, xg, yg, xgr, ygr. x and y set shift for next layer in cm. This local shift overrides global (setted by xg, yg). xr and yr do the same but respect to global shift. xg and yg set global shift (for all subsequent layers). xgr and ygr add corresponding values to global shift. Resulted shift is added to own shift of layer (setted by function LayerShift). */ const ObjectBase* GMT_Map(const ObjectList* input) { const ObjectList* list=input; auto size=list->Size(); if(0==size) return 0; decltype(size) pos=0; std::string title; std::stack > lstack; bool first=true; double xg,yg,x,y; bool xislocal=false, yislocal=false; std::list > data; xg=yg=x=y=0.0; // FIXME: Workaround ghostscript bug 202735 // See http://bugs.ghostscript.com/show_bug.cgi?id=202735 data.emplace_back(new std::string("4000 4000 translate")); data.emplace_back(new std::string(header)); while(pos l(list->At(pos)); // Descending if(l) { if(0==l->Size()) goto next; lstack.push(std::make_pair(list,pos)); list=l; pos=0; size=l->Size(); continue; } } // Check if first argument is string if(first) { first=false; OBType s(list->At(pos)); if(s) { title=s->Value(); goto next; } } // Check if argument is pair { OBType p(list->At(pos)); if(p) { std::string name=p->Name(); tolower(name); Base2Double d(p->Value()); bool suc=true; double val=d(&suc); if(!suc) goto fail; // Conversion failed suc=false; if("x"==name) {suc=true; xislocal=true; x=val;} if("y"==name) {suc=true; yislocal=true; y=val;} if("xr"==name) {suc=true; xislocal=true; x=val+xg;} if("yr"==name) {suc=true; yislocal=true; y=val+yg;} if("xg"==name) {suc=true; xg=val;} if("yg"==name) {suc=true; yg=val;} if("xgr"==name) {suc=true; xg+=val;} if("ygr"==name) {suc=true; yg+=val;} if(!suc) goto fail; // Unknown name goto next; } } // Check if argument is layer { OBType l(list->At(pos)); if(l) { struct gmt_layer layer=l->Data(); layer.shiftx+=(xislocal?x:xg); layer.shifty+=(yislocal?y:yg); xislocal=yislocal=false; if(layer.Shifted()) { data.emplace_back(new std::string(layer.BeginShift())); data.emplace_back(layer.data); data.emplace_back(new std::string(layer.EndShift())); } else data.emplace_back(layer.data); goto next; } } goto fail; // Unknown type of argument next: pos++; // Ascending if(pos==size && !lstack.empty()) { list=lstack.top().first; pos=lstack.top().second; lstack.pop(); size=list->Size(); goto next; } } data.emplace_back(new std::string(footer)); // Calculate bounding box int64_t bblx,bbly,bbrx,bbry; { std::string bboxes; struct input_runtime in={data.begin(),data.end(),0}; int ret; ret=GhostRun("-sDEVICE=bbox",gs_bbox_callback,&in,0,&bboxes,0); // Bounding box is writed on stderr if(0!=ret) goto fail; // Something wrong std::smatch m; std::smatch::const_iterator ci; std::regex r("%%BoundingBox:[[:space:]]+(-?[0-9]+)[[:space:]]+(-?[0-9]+)[[:space:]]+(-?[0-9]+)[[:space:]]+(-?[0-9]+)"); bool ok=true; std::regex_search(bboxes,m,r); if(5!=m.size()) goto fail; // This is strange and scary ci=m.cbegin(); ci++; // Skip full match ok=ok && str2int(*ci++,&bblx); ok=ok && str2int(*ci++,&bbly); ok=ok && str2int(*ci++,&bbrx); ok=ok && str2int(*ci++,&bbry); if(!ok) goto fail; // Unexpected! // FIXME: Workaround ghostscript bug 202735 // We add 5 points to each margin because ghostscript does'nt count linewidths when calculate bounding box bblx-=4005; bbly-=4005; bbrx-=3995; bbry-=3995; } data.pop_front(); // Creating eps file { std::string curtime; { const size_t bufsize=1024; char buf[bufsize]; time_t sec; struct tm t; sec=time(0); localtime_r(&sec,&t); curtime.assign(buf, strftime(buf,bufsize,"%F %T %Z",&t)); } std::string* eps=new std::string("%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: "); *eps+=ToString(bblx)+" "+ToString(bbly)+" "+ToString(bbrx)+" "+ToString(bbry); *eps+="\n%%Title: "+(title.empty()?std::string("untitled"):title); *eps+="\n%%Creator: gmt_makemap\n%%CreationDate: "+curtime; *eps+="\n%%LanguageLevel: 2\n%%Orientation: Portrait\n%%EndComments\n"; for(auto d: data) *eps+=*d; return new ObjectGMTMap(eps,bblx,bbly,bbrx,bbry); } fail: return 0; } // Creating pdf from eps /* Input: One argument must be GMTMap. Optionally, resolution can be specified by pair with name resolution, res or r and double value. Default is 720. */ const ObjectBase* GMT_Convert2PDF(const ObjectList* input) { if(!gs_abilities.havepdf) return 0; // No pdf support double r; bool suc=true; const ObjectGMTMap* map=0; { SearchParameterWDefO,false,PMin<1> > res(input,"r","res","resolution"); r=res(&suc); if(!suc) goto fail; // Error } { for(ObjectList::IndexType i=0;iSize();i++) { OBType m(input->At(i)); if(m) { if(0!=map) goto fail; // Duplicate map=m; } } if(0==map) goto fail; // Map not found } { std::string* out=new std::string; int ret=eps2pdf(*(map->pValue()),out,r); if(0!=ret) { delete out; goto fail; } // Something wrong return new ObjectGMTMapPDF(out,map->Bblx(),map->Bbly(),map->Bbrx(),map->Bbry()); } fail: return 0; } // Creating png from eps or pdf /* Input: One argument must be GMTMap or GMTMapPDF. Other parameter are optional name-value pairs. resolution, res or r - output resolution (pixels/inch). Default: 300. Instead of resolution, width (width or w) or height (height or h) in pixels may be specified. Resolution, width and height are mutually exclusive. Large value of resolution may result in ghostscript error. colorspace, cspace or cs - is a string, one of "mono" or "monochrome" (black and white image), "monodiffused" or "monod" (black and white image made from grayscale by error diffusion), "16c" or "16" (16 colors), "256c" or "256" (256 colors), "gray", "grey" or "g" (256 shades of gray), "full", "8bit" or "color" (8-bit per component rgb). Some of these values may return error, this depends on ghostscript setup in system. Default: "color". For colorspaces "monod", "color" and "gray" may be also specified parameter downscale (dscale or ds) with small integer value (from 1 to 10). The image initially rendered in dscale*res resolution and downscaling to res resolution. This increase output quality (lines and contours are more "soft"), but may result in ghostscript error if rendering resolution is too high. textantialiasing or taa - is a string, can be "none" ("no"), "small" ("s") or "full" ("f"). Controls text antialiasing. Default: "full". graphicsantialiasing or gaa - is a string, can be "none", "small" or "full". Controls graphics antialiasing. Default: "full". antialiasing or aa - can be used to set graphics and text antialiasing simultaneously. */ const ObjectBase* GMT_Convert2PNG(const ObjectList* input) { if(!gs_abilities.havepdf) return 0; // No pdf support, so, no png double r; bool suc=true; const GMTMap* map=0; std::string gsdev(""); bool ispdf; uint aat=0,aag=0; std::string aats("full"),aags("full"); uint dscale=0; // Map to convert { for(ObjectList::IndexType i=0;iSize();i++) { OBType m(input->At(i)); OBType p(input->At(i)); if(m) { if(0!=map) goto fail; // Duplicate map=m; ispdf=false; } if(p) { if(0!=map) goto fail; // Duplicate map=p; ispdf=true; } } if(0==map) goto fail; // Map not found } // Determine resolution { SearchParameter > res(input,"r","res","resolution"); BaseM2Double w(input,"width","w"), h(input,"height","h"); // Check existence if( ( res.Exist() && w.Exist() ) || ( res.Exist() && h.Exist() ) || ( w.Exist() && h.Exist() )) goto fail; // Only one parameter allowed r=300; // Default value if(res.Exist()) r=res(&suc); if(w.Exist()) r=w(&suc)*72.0/(map->Bbrx()-map->Bblx()); if(h.Exist()) r=h(&suc)*72.0/(map->Bbry()-map->Bbly()); if(!suc) goto fail; // Error } // Color model { std::string cs; BaseMD2String cspace(input,"8bit","colorspace","cspace","cs"); cs=cspace(&suc); if(!suc) goto fail; // Error tolower(cs); if(("mono"==cs || "monochrome"==cs) && gs_abilities.havepngmono) gsdev="pngmono"; if(("monod"==cs || "monodiffused"==cs) && gs_abilities.havepngmonod) gsdev="pngmonod"; if(("16c"==cs || "16"==cs) && gs_abilities.havepng16) gsdev="png16"; if(("256c"==cs || "256"==cs) && gs_abilities.havepng256) gsdev="png256"; if(("gray"==cs || "grey"==cs || "g"==cs) && gs_abilities.havepnggray) gsdev="pnggray"; if(("full"==cs || "8bit"==cs || "color"==cs) && gs_abilities.havepng16m) gsdev="png16m"; if(""==gsdev) goto fail; // Incorrect value } // Antialiasing { BaseM2String aa(input,"antialiasing","aa"),taa(input,"textantialiasing","taa"),gaa(input,"graphicsantialiasing","gaa"); if(aa.Exist()) aags=aats=aa(&suc); if(taa.Exist()) aats=taa(&suc); if(gaa.Exist()) aags=gaa(&suc); if(!suc) goto fail; // Error tolower(aags); tolower(aats); if("none"==aags || "no"==aags || "n"==aags) aag=1; if("none"==aats || "no"==aats || "n"==aats) aat=1; if("small"==aags || "s"==aags) aag=2; if("small"==aats || "s"==aats) aat=2; if("full"==aags || "f"==aags) aag=4; if("full"==aats || "f"==aats) aat=4; if(0==aat || 0==aag) goto fail; // Incorrect value } // Downscale if("pngmonod"==gsdev || "pnggray"==gsdev || "png16m"==gsdev) { SearchParameterWDefO,false,PMin<1>,PMax<10>,PInt > ds(input,"downscale","dscale","ds"); dscale=static_cast(ds(&suc)); if(!suc) goto fail; // Error r*=dscale; } // Go! { std::string* pdf=0; int ret; if(!ispdf) { pdf=new std::string; ret=eps2pdf(*(map->pValue()),pdf,r,aat,aag); if(0!=ret) { delete pdf; goto fail; } // Something wrong } { std::string* out=new std::string; ret=GhostRun("-r"+ToString(r)+" -dTextAlphaBits="+ToString(aat)+" -dGraphicAlphaBits="+ToString(aag)+" -sDEVICE="+gsdev+((dscale>1)?(" -dDownScaleFactor="+ToString(dscale)):""),((0!=pdf)?*pdf:*(map->pValue())),0,0,out); if(0!=pdf) delete pdf; if(0!=ret) { delete out; goto fail; } // Something wrong return new ObjectGMTImage(out); } } fail: return 0; } // Creating jpeg from eps or pdf /* Input: One argument must be GMTMap or GMTMapPDF. Other parameter are optional name-value pairs. resolution, res or r - output resolution (pixels/inch). Default: 300. Instead of resolution, width (width or w) or height (height or h) in pixels may be specified. Resolution, width and height are mutually exclusive. Large value of resolution may result in ghostscript error. colorspace, cspace or cs - is a string, one "gray", "grey" or "g" (256 shades of gray), "full", "8bit" or "color" (8-bit per component rgb). Some of these values may return error, this depends on ghostscript setup in system. Default: "color". quality, qual or q - JPEG quality level, integer from 0 to 100. Default: 75. textantialiasing or taa - is a string, can be "none" ("no"), "small" ("s") or "full" ("f"). Controls text antialiasing. Default: "full". graphicsantialiasing or gaa - is a string, can be "none", "small" or "full". Controls graphics antialiasing. Default: "full". antialiasing or aa - can be used to set graphics and text antialiasing simultaneously. */ const ObjectBase* GMT_Convert2JPG(const ObjectList* input) { if(!gs_abilities.havepdf) return 0; // No pdf support, so, no jpeg double r; bool suc=true; const GMTMap* map=0; std::string gsdev(""); bool ispdf; uint aat=0,aag=0; std::string aats("full"),aags("full"); uint qual; // Map to convert { for(ObjectList::IndexType i=0;iSize();i++) { OBType m(input->At(i)); OBType p(input->At(i)); if(m) { if(0!=map) goto fail; // Duplicate map=m; ispdf=false; } if(p) { if(0!=map) goto fail; // Duplicate map=p; ispdf=true; } } if(0==map) goto fail; // Map not found } // Determine resolution { SearchParameter > res(input,"r","res","resolution"); BaseM2Double w(input,"width","w"), h(input,"height","h"); // Check existence if( ( res.Exist() && w.Exist() ) || ( res.Exist() && h.Exist() ) || ( w.Exist() && h.Exist() )) goto fail; // Only one parameter allowed r=300; // Default value if(res.Exist()) r=res(&suc); if(w.Exist()) r=w(&suc)*72.0/(map->Bbrx()-map->Bblx()); if(h.Exist()) r=h(&suc)*72.0/(map->Bbry()-map->Bbly()); if(!suc) goto fail; // Error } // Color model { std::string cs; BaseMD2String cspace(input,"8bit","colorspace","cspace","cs"); cs=cspace(&suc); if(!suc) goto fail; // Error tolower(cs); if(("gray"==cs || "grey"==cs || "g"==cs) && gs_abilities.havejpeggray) gsdev="jpeggray"; if(("full"==cs || "8bit"==cs || "color"==cs) && gs_abilities.havejpeg) gsdev="jpeg"; if(""==gsdev) goto fail; // Incorrect value } // Antialiasing { BaseM2String aa(input,"antialiasing","aa"),taa(input,"textantialiasing","taa"),gaa(input,"graphicsantialiasing","gaa"); if(aa.Exist()) aags=aats=aa(&suc); if(taa.Exist()) aats=taa(&suc); if(gaa.Exist()) aags=gaa(&suc); if(!suc) goto fail; // Error tolower(aags); tolower(aats); if("none"==aags || "no"==aags || "n"==aags) aag=1; if("none"==aats || "no"==aats || "n"==aats) aat=1; if("small"==aags || "s"==aags) aag=2; if("small"==aats || "s"==aats) aat=2; if("full"==aags || "f"==aags) aag=4; if("full"==aats || "f"==aats) aat=4; if(0==aat || 0==aag) goto fail; // Incorrect value } // Quality { SearchParameterWDefO,false,PMin<0>,PMax<100>,PInt > q(input,"quality","qual","q"); qual=static_cast(q(&suc)); if(!suc) goto fail; // Error } // Go! { std::string* pdf=0; int ret; if(!ispdf) { pdf=new std::string; ret=eps2pdf(*(map->pValue()),pdf,r,aat,aag); if(0!=ret) { delete pdf; goto fail; } // Something wrong } { std::string* out=new std::string; ret=GhostRun("-r"+ToString(r)+" -dTextAlphaBits="+ToString(aat)+" -dGraphicAlphaBits="+ToString(aag)+" -sDEVICE="+gsdev+" -dJPEGQ="+ToString(qual),((0!=pdf)?*pdf:*(map->pValue())),0,0,out); if(0!=pdf) delete pdf; if(0!=ret) { delete out; goto fail; } // Something wrong return new ObjectGMTImage(out); } } fail: return 0; }