123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412(*---------------------------------------------------------------------------
Copyright (c) 2013 The vg programmers. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
vg v0.9.4
---------------------------------------------------------------------------*)openGgopenVgopenVgr.Private.DataopenJs_of_ocamlletstr=Format.sprintfletwarn_dash="Outline dashes unsupported in this browser"(* JS bindings, those are not in js_of_ocaml *)classtypectx_ext=objectmethodlineDashOffset:Js.float_propmethodsetLineDash:floatJs.js_arrayJs.t->unitJs.methmethodfill:Js.js_stringJs.t->unitJs.methmethodclip:Js.js_stringJs.t->unitJs.methendletdash_supportctx=Js.Optdef.test((Js.Unsafe.coercectx)##.setLineDash)(* Renderer *)typejs_font=Js.js_stringJs.t(* lovely isn't it ? *)typejs_primitive=|ColorofJs.js_stringJs.t(* even more. *)|GradientofDom_html.canvasGradientJs.t(* Oh! a datastructure. *)letdumb_prim=Color(Js.string"")typegstate=(* subset of the graphics state saved by a ctx ## save (). *){mutableg_tr:M3.t;(* current transform without view_tr. *)mutableg_outline:P.outline;(* current outline stroke. *)mutableg_stroke:js_primitive;(* current stroke color. *)mutableg_fill:js_primitive;}(* current fill color. *)letinit_gstate={g_tr=M3.id;g_outline=P.o;g_stroke=dumb_prim;g_fill=dumb_prim}typecmd=Setofgstate|DrawofVgr.Private.Data.imagetypestate={r:Vgr.Private.renderer;(* corresponding renderer. *)resize:bool;(* [true] if canvas resizes to renderable sizes. *)resolution:Gg.v2;(* resolution of the canvas. *)c:Dom_html.canvasElementJs.t;(* canvas element rendered to. *)ctx:Dom_html.canvasRenderingContext2DJs.t;(* canvas context of [c]. *)dash_support:bool;(* [true] if [ctx] has dash support. *)mutablecost:int;(* cost counter for limit. *)mutableview:Gg.box2;(* current renderable view rectangle. *)mutableview_tr:M3.t;(* view to canvas transform. *)mutabletodo:cmdlist;(* commands to perform. *)fonts:(Vg.font*float,js_font)Hashtbl.t;(* cached fonts. *)prims:(* cached primitives. *)(Vgr.Private.Data.primitive,js_primitive)Hashtbl.t;mutablegstate:gstate;}(* current graphic state. *)letsave_gstates=Set{s.gstatewithg_tr=s.gstate.g_tr}letset_gstatesg=s.gstate<-gletpartial=Vgr.Private.partialletlimits=Vgr.Private.limits.rletwarnsw=Vgr.Private.warns.rwletimagei=Vgr.Private.I.of_datailetview_rects=(* image view rect in current coordinate system. *)lettr=M3.invs.gstate.g_trinVgr.Private.Data.of_path(P.empty|>P.rect(Box2.trtrs.view))letcss_colorc=(* w3c bureaucrats are pigs. *)letsrgb=Color.to_srgbcinletr=Float.int_of_round(Color.rsrgb*.255.)inletg=Float.int_of_round(Color.gsrgb*.255.)inletb=Float.int_of_round(Color.bsrgb*.255.)inleta=Color.asrgbinifa=1.0thenJs.string(str"rgb(%d,%d,%d)"rgb)elseJs.string(str"rgba(%d,%d,%d,%g)"rgba)letcap_str=letbutt=Js.string"butt"inletround=Js.string"round"inletsquare=Js.string"square"infunction`Butt->butt|`Round->round|`Square->squareletjoin_str=letbevel=Js.string"bevel"inletround=Js.string"round"inletmiter=Js.string"miter"infunction`Bevel->bevel|`Round->round|`Miter->miterletarea_str=letnz=Js.string"nonzero"inleteo=Js.string"evenodd"infunction`Anz->nz|`Aeo->eo|`O_->assertfalseletget_primitivesp=tryHashtbl.finds.primspwith|Not_found->letadd_stopg(t,c)=g##(addColorStopt(css_colorc))inletcreate=function|Constc->Color(css_colorc)|Axial(stops,pt,pt')->letg=P2.(s.ctx##(createLinearGradient(xpt)(ypt)(xpt')(ypt')))inList.iter(add_stopg)stops;Gradientg|Radial(stops,f,c,r)->letg=P2.(s.ctx##(createRadialGradient(xf)(yf)(0.)(xc)(yc)r))inList.iter(add_stopg)stops;Gradientg|Raster_->assertfalseinletjs_prim=createpinHashtbl.adds.primspjs_prim;js_primletget_fonts(font,sizeasspec)=tryHashtbl.finds.fontsspecwith|Not_found->letjs_font=letfont={fontwithFont.size=size}inJs.string(Vgr.Private.Font.css_font~unit:"px"font)inHashtbl.adds.fontsspecjs_font;js_fontletset_dashes?(warning=true)sdashes=ifnots.dash_supportthen(ifwarningthenwarns(`Otherwarn_dash))elseletctx:ctx_extJs.t=Js.Unsafe.coerces.ctxinmatchdasheswith|None->ctx##(setLineDash(new%jsJs.array_empty))|Some(offset,dashes)->letda=new%jsJs.array_emptyinList.iteri(funiv->Js.array_setdaiv)dashes;ctx##.lineDashOffset:=offset;ctx##(setLineDashda)letinit_ctxswh=leto=s.gstate.g_outlineinletm=s.view_trin(* clear canvas *)s.ctx##(setTransform(1.)(0.)(0.)(1.)(0.)(0.));s.ctx##(clearRect(0.)(0.)wh);(* setup base state *)M3.(s.ctx##(transform(e00m)(e10m)(e01m)(e11m)(e02m)(e12m)));s.ctx##.lineWidth:=o.P.width;s.ctx##.lineCap:=cap_stro.P.cap;s.ctx##.lineJoin:=join_stro.P.join;s.ctx##.miterLimit:=(Vgr.Private.P.miter_limito);set_dashes~warning:falseso.P.dashesletpush_transformstr=letm=matchtrwith|Movev->s.ctx##(translate(V2.xv)(V2.yv));M3.move2v|Rota->s.ctx##(rotatea);M3.rot2a|Scalesv->s.ctx##(scale(V2.xsv)(V2.ysv));M3.scale2sv|Matrixm->M3.(s.ctx##(transform(e00m)(e10m)(e01m)(e11m)(e02m)(e12m)));mins.gstate.g_tr<-M3.muls.gstate.g_trmletset_outlineso=ifs.gstate.g_outline==othen()elseletold=s.gstate.g_outlineins.gstate.g_outline<-o;ifold.P.width<>o.P.widththen(s.ctx##.lineWidth:=o.P.width);ifold.P.cap<>o.P.capthen(s.ctx##.lineCap:=cap_stro.P.cap);ifold.P.join<>o.P.jointhen(s.ctx##.lineJoin:=join_stro.P.join);ifold.P.miter_angle<>o.P.miter_anglethen(s.ctx##.miterLimit:=Vgr.Private.P.miter_limito);ifold.P.dashes<>o.P.dashesthenset_dashesso.P.dashes;()letset_strokesp=letp=get_primitivespinifs.gstate.g_stroke!=pthenbeginmatchpwith|Colorc->s.ctx##.strokeStyle:=c;s.gstate.g_stroke<-p|Gradientg->s.ctx##.strokeStyle_gradient:=g;s.gstate.g_stroke<-pendletset_fillsp=letp=get_primitivespinifs.gstate.g_fill!=pthenbeginmatchpwith|Colorc->s.ctx##.fillStyle:=c;s.gstate.g_fill<-p|Gradientg->s.ctx##.fillStyle_gradient:=g;s.gstate.g_fill<-pendletset_fontsf=letf=get_fontsfins.ctx##.font:=f(* N.B. In the future, if browsers begin supporting them we could in r_path,
1) construct and cache path objects 2) use ctx ## ellipse. *)letset_pathsp=letreclooplast=function|[]->()|seg::segs->matchsegwith|`Subpt->P2.(s.ctx##(moveTo(xpt)(ypt)));loopptsegs|`Linept->P2.(s.ctx##(lineTo(xpt)(ypt)));loopptsegs|`Qcurve(c,pt)->P2.(s.ctx##(quadraticCurveTo(xc)(yc)(xpt)(ypt)));loopptsegs|`Ccurve(c,c',pt)->P2.(s.ctx##(bezierCurveTo(xc)(yc)(xc')(yc')(xpt)(ypt)));loopptsegs|`Earc(large,cw,r,a,pt)->beginmatchVgr.Private.P.earc_paramslastlargecwraptwith|None->P2.(s.ctx##(lineTo(xpt)(ypt)));loopptsegs|Some(c,m,a,a')->(s.ctx)##save;letc=V2.ltr(M2.invm)cinM2.(s.ctx##(transform(e00m)(e10m)(e01m)(e11m)(0.)(0.)));P2.(s.ctx##(arc(xc)(yc)(1.0)aa'((Js.boolcw))));(s.ctx)##restore;loopptsegsend|`Close->(s.ctx)##closePath;looplast(* we don't care *)segsin(s.ctx)##beginPath;loopP2.o(List.revp)(* The way glyph_cuts is implemented is a little bit odd because
current browsers are completly broken w.r.t. canvas text drawing:
it is impossible to specify text that is smaller than 1px which
means that the minimal size absurdly depends on the current
transformation matrix (see http://jsfiddle.net/Fk3fc/2/). Besides
we also get problems by the fact that we flip the coordinate
system. To circumvent these we extract from the current transform
the rotation, scaling and translation in the original,
untransformed, coordinate system and draw the glyphs there.
This however makes it tricky to integrate with gradients, for
now we just disallow gradient cuts. *)letrecr_cut_glyphssarun=function|Primitive(Raster_|Axial_|Radial_)|Tr_|Blend_|Cut_|Cut_glyphs_asi->warns(`Unsupported_glyph_cut(a,imagei))|Primitivepasi->beginmatchrun.textwith|None->warns(`Textless_glyph_cut(image(Cut_glyphs(a,run,i))))|Sometext->lettext=Js.stringtextin(s.ctx)##save;s.todo<-(save_gstates)::s.todo;letm=M3.muls.view_trs.gstate.g_trinleto=P2.trmrun.oinletfont_size=V2.norm(V2.trm(V2.v0.run.font.Font.size))inlety_scale=1./.V2.norm(V2.trs.gstate.g_trV2.oy)inletx_scale=(* we don't apply the view transform but still need to scale
for aspect ratio distortions. *)letsa=(floats.c##.width)/.(floats.c##.height)inletva=Box2.ws.view/.Box2.hs.viewinsa/.vainset_fonts(run.font,font_size);M3.(s.ctx##(setTransform(e00s.gstate.g_tr*.x_scale)(-.e10s.gstate.g_tr*.x_scale)(-.e01s.gstate.g_tr*.y_scale)(e11s.gstate.g_tr*.y_scale)(V2.xo)(V2.yo)));beginmatchawith|`Oo->warns(`Unsupported_glyph_cut(a,imagei))(* some work is needed here as the outline params won't
be in the right coordinate system *)(* set_outline s o; set_stroke s p;
s.ctx ## strokeText (text, 0., 0.) *)|`Aeo|`Anz->set_fillsp;s.ctx##(fillTexttext(0.)(0.))end;endletrecr_cutsa=function|Primitive(Raster_)->assertfalse|Primitivep->beginmatchawith|`Oo->set_outlineso;set_strokesp;(s.ctx)##stroke|`Aeo|`Anz->set_fillsp;(Js.Unsafe.coerces.ctx:ctx_extJs.t)##(fill(area_stra))end|Tr(tr,i)->(s.ctx)##save;s.todo<-(save_gstates)::s.todo;push_transformstr;r_cutsai|Blend_|Cut_|Cut_glyphs_asi->leta=matchawith|`O_->warns(`Unsupported_cut(a,imagei));`Anz|a->ain(s.ctx)##save;(Js.Unsafe.coerces.ctx:ctx_extJs.t)##(clip(area_stra));s.todo<-(Drawi)::(save_gstates)::s.todoletrecr_imageskr=ifs.cost>limitsthen(s.cost<-0;partial(r_imagesk)r)elsematchs.todowith|[]->Hashtbl.resets.prims;Hashtbl.resets.fonts;kr|Setgs::todo->(s.ctx)##restore;set_gstatesgs;s.todo<-todo;r_imageskr|Drawi::todo->s.cost<-s.cost+1;matchiwith|Primitive_asi->(* Uncut primitive, just cut to view. *)letp=view_rectsins.todo<-(Draw(Cut(`Anz,p,i)))::todo;r_imageskr|Cut(a,p,i)->s.todo<-todo;set_pathsp;r_cutsai;r_imageskr|Cut_glyphs(a,run,i)->s.todo<-todo;r_cut_glyphssaruni;r_imageskr|Blend(_,_,i,i')->s.todo<-(Drawi')::(Drawi)::todo;r_imageskr|Tr(tr,i)->(s.ctx)##save;s.todo<-(Drawi)::(save_gstates)::todo;push_transformstr;r_imageskrletrendersvkr=matchvwith|`End->kr|`Image(size,view,i)->letsize=ifs.resizethenbeginletto_css_mm=str"%gmm"inletnew_w=Js.string(to_css_mm(Size2.wsize))inletnew_h=Js.string(to_css_mm(Size2.hsize))inletcw_css=s.c##.style##.widthinletch_css=s.c##.style##.heightinifcw_css<>new_wthens.c##.style##.width:=new_w;ifch_css<>new_hthens.c##.style##.height:=new_h;sizeendelsebeginletr=((s.c:>Dom_html.elementJs.t))##getBoundingClientRectinletw=r##.right-.r##.leftin(* in CSS pixels *)leth=r##.bottom-.r##.topin(* in CSS pixels *)letto_mm=(2.54/.96.)*.10.inSize2.v(w*.to_mm)(h*.to_mm)endinletcw=Float.round((Size2.wsize/.1000.)*.(V2.xs.resolution))inletch=Float.round((Size2.hsize/.1000.)*.(V2.ys.resolution))inletcwi=int_of_floatcwinletchi=int_of_floatchinifs.c##.width<>cwithens.c##.width:=cwi;ifs.c##.height<>chithens.c##.height:=chi;(* Map view rect (bot-left coords) to canvas (top-left coords) *)letsx=cw/.Box2.wviewinletsy=ch/.Box2.hviewinletdx=-.Box2.oxview*.sxinletdy=ch+.Box2.oyview*.syinletview_tr=M3.vsx0.dx0.(-.sy)dy0.0.1.ins.cost<-0;s.view<-view;s.view_tr<-view_tr;s.todo<-[Drawi];s.gstate<-{init_gstatewithg_tr=init_gstate.g_tr};(* copy *)init_ctxscwch;r_imageskrletscreen_resolution=(* in pixel per meters *)letdevice_pixel_ratio=ifJs.Optdef.test((Js.Unsafe.coerceDom_html.window)##.devicePixelRatio)then(Js.Unsafe.coerceDom_html.window)##.devicePixelRatioelse1.0inletscreen=(96./.2.54)*.100.*.device_pixel_ratioinV2.vscreenscreenlettarget?(resize=true)?(resolution=screen_resolution)c=lettargetr_=letctx=c##(getContext(Dom_html._2d_))intrue,render{r;c;ctx;resize;resolution;dash_support=dash_supportctx;cost=0;view=Box2.empty;view_tr=M3.id;todo=[];fonts=Hashtbl.create20;prims=Hashtbl.create231;gstate=init_gstate;}inVgr.Private.create_targettarget(*---------------------------------------------------------------------------
Copyright (c) 2013 The vg programmers
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---------------------------------------------------------------------------*)