tvgSvgLoader.cpp 126 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777
  1. /*
  2. * Copyright (c) 2020 - 2024 the ThorVG project. All rights reserved.
  3. * Permission is hereby granted, free of charge, to any person obtaining a copy
  4. * of this software and associated documentation files (the "Software"), to deal
  5. * in the Software without restriction, including without limitation the rights
  6. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. * copies of the Software, and to permit persons to whom the Software is
  8. * furnished to do so, subject to the following conditions:
  9. * The above copyright notice and this permission notice shall be included in all
  10. * copies or substantial portions of the Software.
  11. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  13. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  17. * SOFTWARE.
  18. */
  19. /*
  20. * Copyright notice for the EFL:
  21. * Copyright (C) EFL developers (see AUTHORS)
  22. * All rights reserved.
  23. * Redistribution and use in source and binary forms, with or without
  24. * modification, are permitted provided that the following conditions are met:
  25. * 1. Redistributions of source code must retain the above copyright
  26. * notice, this list of conditions and the following disclaimer.
  27. * 2. Redistributions in binary form must reproduce the above copyright
  28. * notice, this list of conditions and the following disclaimer in the
  29. * documentation and/or other materials provided with the distribution.
  30. * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  32. * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  33. * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  34. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  35. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  36. * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  37. * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  38. * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  39. * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  40. */
  41. #include <cstring>
  42. #include <fstream>
  43. #include <float.h>
  44. #include "tvgLoader.h"
  45. #include "tvgXmlParser.h"
  46. #include "tvgSvgLoader.h"
  47. #include "tvgSvgSceneBuilder.h"
  48. #include "tvgStr.h"
  49. #include "tvgSvgCssStyle.h"
  50. #include "tvgMath.h"
  51. /************************************************************************/
  52. /* Internal Class Implementation */
  53. /************************************************************************/
  54. /*
  55. * According to: https://www.w3.org/TR/SVG2/coords.html#Units
  56. * and: https://www.w3.org/TR/css-values-4/#absolute-lengths
  57. */
  58. #define PX_PER_IN 96 //1 in = 96 px
  59. #define PX_PER_PC 16 //1 pc = 1/6 in -> PX_PER_IN/6
  60. #define PX_PER_PT 1.333333f //1 pt = 1/72 in -> PX_PER_IN/72
  61. #define PX_PER_MM 3.779528f //1 in = 25.4 mm -> PX_PER_IN/25.4
  62. #define PX_PER_CM 37.79528f //1 in = 2.54 cm -> PX_PER_IN/2.54
  63. typedef bool (*parseAttributes)(const char* buf, unsigned bufLength, simpleXMLAttributeCb func, const void* data);
  64. typedef SvgNode* (*FactoryMethod)(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func);
  65. typedef SvgStyleGradient* (*GradientFactoryMethod)(SvgLoaderData* loader, const char* buf, unsigned bufLength);
  66. static char* _skipSpace(const char* str, const char* end)
  67. {
  68. while (((end && str < end) || (!end && *str != '\0')) && isspace(*str)) {
  69. ++str;
  70. }
  71. return (char*) str;
  72. }
  73. static char* _copyId(const char* str)
  74. {
  75. if (!str) return nullptr;
  76. if (strlen(str) == 0) return nullptr;
  77. return strdup(str);
  78. }
  79. static const char* _skipComma(const char* content)
  80. {
  81. content = _skipSpace(content, nullptr);
  82. if (*content == ',') return content + 1;
  83. return content;
  84. }
  85. static bool _parseNumber(const char** content, float* number)
  86. {
  87. char* end = nullptr;
  88. *number = strToFloat(*content, &end);
  89. //If the start of string is not number
  90. if ((*content) == end) return false;
  91. //Skip comma if any
  92. *content = _skipComma(end);
  93. return true;
  94. }
  95. static constexpr struct
  96. {
  97. AspectRatioAlign align;
  98. const char* tag;
  99. } alignTags[] = {
  100. { AspectRatioAlign::XMinYMin, "xMinYMin" },
  101. { AspectRatioAlign::XMidYMin, "xMidYMin" },
  102. { AspectRatioAlign::XMaxYMin, "xMaxYMin" },
  103. { AspectRatioAlign::XMinYMid, "xMinYMid" },
  104. { AspectRatioAlign::XMidYMid, "xMidYMid" },
  105. { AspectRatioAlign::XMaxYMid, "xMaxYMid" },
  106. { AspectRatioAlign::XMinYMax, "xMinYMax" },
  107. { AspectRatioAlign::XMidYMax, "xMidYMax" },
  108. { AspectRatioAlign::XMaxYMax, "xMaxYMax" },
  109. };
  110. static void _parseAspectRatio(const char** content, AspectRatioAlign* align, AspectRatioMeetOrSlice* meetOrSlice)
  111. {
  112. if (!strcmp(*content, "none")) {
  113. *align = AspectRatioAlign::None;
  114. return;
  115. }
  116. for (unsigned int i = 0; i < sizeof(alignTags) / sizeof(alignTags[0]); i++) {
  117. if (!strncmp(*content, alignTags[i].tag, 8)) {
  118. *align = alignTags[i].align;
  119. *content += 8;
  120. *content = _skipSpace(*content, nullptr);
  121. break;
  122. }
  123. }
  124. if (!strcmp(*content, "meet")) {
  125. *meetOrSlice = AspectRatioMeetOrSlice::Meet;
  126. } else if (!strcmp(*content, "slice")) {
  127. *meetOrSlice = AspectRatioMeetOrSlice::Slice;
  128. }
  129. }
  130. /**
  131. * According to https://www.w3.org/TR/SVG/coords.html#Units
  132. */
  133. static float _toFloat(const SvgParser* svgParse, const char* str, SvgParserLengthType type)
  134. {
  135. float parsedValue = strToFloat(str, nullptr);
  136. if (strstr(str, "cm")) parsedValue *= PX_PER_CM;
  137. else if (strstr(str, "mm")) parsedValue *= PX_PER_MM;
  138. else if (strstr(str, "pt")) parsedValue *= PX_PER_PT;
  139. else if (strstr(str, "pc")) parsedValue *= PX_PER_PC;
  140. else if (strstr(str, "in")) parsedValue *= PX_PER_IN;
  141. else if (strstr(str, "%")) {
  142. if (type == SvgParserLengthType::Vertical) parsedValue = (parsedValue / 100.0) * svgParse->global.h;
  143. else if (type == SvgParserLengthType::Horizontal) parsedValue = (parsedValue / 100.0) * svgParse->global.w;
  144. else //if other then it's radius
  145. {
  146. float max = svgParse->global.w;
  147. if (max < svgParse->global.h)
  148. max = svgParse->global.h;
  149. parsedValue = (parsedValue / 100.0) * max;
  150. }
  151. }
  152. //TODO: Implement 'em', 'ex' attributes
  153. return parsedValue;
  154. }
  155. static float _gradientToFloat(const SvgParser* svgParse, const char* str, bool& isPercentage)
  156. {
  157. char* end = nullptr;
  158. float parsedValue = strToFloat(str, &end);
  159. isPercentage = false;
  160. if (strstr(str, "%")) {
  161. parsedValue = parsedValue / 100.0;
  162. isPercentage = true;
  163. }
  164. else if (strstr(str, "cm")) parsedValue *= PX_PER_CM;
  165. else if (strstr(str, "mm")) parsedValue *= PX_PER_MM;
  166. else if (strstr(str, "pt")) parsedValue *= PX_PER_PT;
  167. else if (strstr(str, "pc")) parsedValue *= PX_PER_PC;
  168. else if (strstr(str, "in")) parsedValue *= PX_PER_IN;
  169. //TODO: Implement 'em', 'ex' attributes
  170. return parsedValue;
  171. }
  172. static float _toOffset(const char* str)
  173. {
  174. char* end = nullptr;
  175. auto strEnd = str + strlen(str);
  176. float parsedValue = strToFloat(str, &end);
  177. end = _skipSpace(end, nullptr);
  178. auto ptr = strstr(str, "%");
  179. if (ptr) {
  180. parsedValue = parsedValue / 100.0;
  181. if (end != ptr || (end + 1) != strEnd) return 0;
  182. } else if (end != strEnd) return 0;
  183. return parsedValue;
  184. }
  185. static int _toOpacity(const char* str)
  186. {
  187. char* end = nullptr;
  188. float opacity = strToFloat(str, &end);
  189. if (end) {
  190. if (end[0] == '%' && end[1] == '\0') return lrint(opacity * 2.55f);
  191. else if (*end == '\0') return lrint(opacity * 255);
  192. }
  193. return 255;
  194. }
  195. static SvgMaskType _toMaskType(const char* str)
  196. {
  197. if (!strcmp(str, "Alpha")) return SvgMaskType::Alpha;
  198. return SvgMaskType::Luminance;
  199. }
  200. //The default rendering order: fill, stroke, markers
  201. //If any is omitted, will be rendered in its default order after the specified ones.
  202. static bool _toPaintOrder(const char* str)
  203. {
  204. uint8_t position = 1;
  205. uint8_t strokePosition = 0;
  206. uint8_t fillPosition = 0;
  207. while (*str != '\0') {
  208. str = _skipSpace(str, nullptr);
  209. if (!strncmp(str, "fill", 4)) {
  210. fillPosition = position++;
  211. str += 4;
  212. } else if (!strncmp(str, "stroke", 6)) {
  213. strokePosition = position++;
  214. str += 6;
  215. } else if (!strncmp(str, "markers", 7)) {
  216. str += 7;
  217. } else {
  218. return _toPaintOrder("fill stroke");
  219. }
  220. }
  221. if (fillPosition == 0) fillPosition = position++;
  222. if (strokePosition == 0) strokePosition = position++;
  223. return fillPosition < strokePosition;
  224. }
  225. #define _PARSE_TAG(Type, Name, Name1, Tags_Array, Default) \
  226. static Type _to##Name1(const char* str) \
  227. { \
  228. unsigned int i; \
  229. \
  230. for (i = 0; i < sizeof(Tags_Array) / sizeof(Tags_Array[0]); i++) { \
  231. if (!strcmp(str, Tags_Array[i].tag)) return Tags_Array[i].Name; \
  232. } \
  233. return Default; \
  234. }
  235. /* parse the line cap used during stroking a path.
  236. * Value: butt | round | square | inherit
  237. * Initial: butt
  238. * https://www.w3.org/TR/SVG/painting.html
  239. */
  240. static constexpr struct
  241. {
  242. StrokeCap lineCap;
  243. const char* tag;
  244. } lineCapTags[] = {
  245. { StrokeCap::Butt, "butt" },
  246. { StrokeCap::Round, "round" },
  247. { StrokeCap::Square, "square" }
  248. };
  249. _PARSE_TAG(StrokeCap, lineCap, LineCap, lineCapTags, StrokeCap::Butt)
  250. /* parse the line join used during stroking a path.
  251. * Value: miter | round | bevel | inherit
  252. * Initial: miter
  253. * https://www.w3.org/TR/SVG/painting.html
  254. */
  255. static constexpr struct
  256. {
  257. StrokeJoin lineJoin;
  258. const char* tag;
  259. } lineJoinTags[] = {
  260. { StrokeJoin::Miter, "miter" },
  261. { StrokeJoin::Round, "round" },
  262. { StrokeJoin::Bevel, "bevel" }
  263. };
  264. _PARSE_TAG(StrokeJoin, lineJoin, LineJoin, lineJoinTags, StrokeJoin::Miter)
  265. /* parse the fill rule used during filling a path.
  266. * Value: nonzero | evenodd | inherit
  267. * Initial: nonzero
  268. * https://www.w3.org/TR/SVG/painting.html
  269. */
  270. static constexpr struct
  271. {
  272. FillRule fillRule;
  273. const char* tag;
  274. } fillRuleTags[] = {
  275. { FillRule::EvenOdd, "evenodd" }
  276. };
  277. _PARSE_TAG(FillRule, fillRule, FillRule, fillRuleTags, FillRule::Winding)
  278. /* parse the dash pattern used during stroking a path.
  279. * Value: none | <dasharray> | inherit
  280. * Initial: none
  281. * https://www.w3.org/TR/SVG/painting.html
  282. */
  283. static void _parseDashArray(SvgLoaderData* loader, const char *str, SvgDash* dash)
  284. {
  285. if (!strncmp(str, "none", 4)) return;
  286. char *end = nullptr;
  287. while (*str) {
  288. str = _skipComma(str);
  289. float parsedValue = strToFloat(str, &end);
  290. if (str == end) break;
  291. if (parsedValue <= 0.0f) break;
  292. if (*end == '%') {
  293. ++end;
  294. //Refers to the diagonal length of the viewport.
  295. //https://www.w3.org/TR/SVG2/coords.html#Units
  296. parsedValue = (sqrtf(powf(loader->svgParse->global.w, 2) + powf(loader->svgParse->global.h, 2)) / sqrtf(2.0f)) * (parsedValue / 100.0f);
  297. }
  298. (*dash).array.push(parsedValue);
  299. str = end;
  300. }
  301. //If dash array size is 1, it means that dash and gap size are the same.
  302. if ((*dash).array.count == 1) (*dash).array.push((*dash).array[0]);
  303. }
  304. static char* _idFromUrl(const char* url)
  305. {
  306. auto open = strchr(url, '(');
  307. auto close = strchr(url, ')');
  308. if (!open || !close || open >= close) return nullptr;
  309. open = strchr(url, '#');
  310. if (!open || open >= close) return nullptr;
  311. ++open;
  312. --close;
  313. //trim the rest of the spaces if any
  314. while (open < close && *close == ' ') --close;
  315. //quick verification
  316. for (auto id = open; id < close; id++) {
  317. if (*id == ' ' || *id == '\'') return nullptr;
  318. }
  319. return strDuplicate(open, (close - open + 1));
  320. }
  321. static unsigned char _parseColor(const char* value, char** end)
  322. {
  323. float r;
  324. r = strToFloat(value, end);
  325. *end = _skipSpace(*end, nullptr);
  326. if (**end == '%') {
  327. r = 255 * r / 100;
  328. (*end)++;
  329. }
  330. *end = _skipSpace(*end, nullptr);
  331. if (r < 0 || r > 255) {
  332. *end = nullptr;
  333. return 0;
  334. }
  335. return lrint(r);
  336. }
  337. static constexpr struct
  338. {
  339. const char* name;
  340. unsigned int value;
  341. } colors[] = {
  342. { "aliceblue", 0xfff0f8ff },
  343. { "antiquewhite", 0xfffaebd7 },
  344. { "aqua", 0xff00ffff },
  345. { "aquamarine", 0xff7fffd4 },
  346. { "azure", 0xfff0ffff },
  347. { "beige", 0xfff5f5dc },
  348. { "bisque", 0xffffe4c4 },
  349. { "black", 0xff000000 },
  350. { "blanchedalmond", 0xffffebcd },
  351. { "blue", 0xff0000ff },
  352. { "blueviolet", 0xff8a2be2 },
  353. { "brown", 0xffa52a2a },
  354. { "burlywood", 0xffdeb887 },
  355. { "cadetblue", 0xff5f9ea0 },
  356. { "chartreuse", 0xff7fff00 },
  357. { "chocolate", 0xffd2691e },
  358. { "coral", 0xffff7f50 },
  359. { "cornflowerblue", 0xff6495ed },
  360. { "cornsilk", 0xfffff8dc },
  361. { "crimson", 0xffdc143c },
  362. { "cyan", 0xff00ffff },
  363. { "darkblue", 0xff00008b },
  364. { "darkcyan", 0xff008b8b },
  365. { "darkgoldenrod", 0xffb8860b },
  366. { "darkgray", 0xffa9a9a9 },
  367. { "darkgrey", 0xffa9a9a9 },
  368. { "darkgreen", 0xff006400 },
  369. { "darkkhaki", 0xffbdb76b },
  370. { "darkmagenta", 0xff8b008b },
  371. { "darkolivegreen", 0xff556b2f },
  372. { "darkorange", 0xffff8c00 },
  373. { "darkorchid", 0xff9932cc },
  374. { "darkred", 0xff8b0000 },
  375. { "darksalmon", 0xffe9967a },
  376. { "darkseagreen", 0xff8fbc8f },
  377. { "darkslateblue", 0xff483d8b },
  378. { "darkslategray", 0xff2f4f4f },
  379. { "darkslategrey", 0xff2f4f4f },
  380. { "darkturquoise", 0xff00ced1 },
  381. { "darkviolet", 0xff9400d3 },
  382. { "deeppink", 0xffff1493 },
  383. { "deepskyblue", 0xff00bfff },
  384. { "dimgray", 0xff696969 },
  385. { "dimgrey", 0xff696969 },
  386. { "dodgerblue", 0xff1e90ff },
  387. { "firebrick", 0xffb22222 },
  388. { "floralwhite", 0xfffffaf0 },
  389. { "forestgreen", 0xff228b22 },
  390. { "fuchsia", 0xffff00ff },
  391. { "gainsboro", 0xffdcdcdc },
  392. { "ghostwhite", 0xfff8f8ff },
  393. { "gold", 0xffffd700 },
  394. { "goldenrod", 0xffdaa520 },
  395. { "gray", 0xff808080 },
  396. { "grey", 0xff808080 },
  397. { "green", 0xff008000 },
  398. { "greenyellow", 0xffadff2f },
  399. { "honeydew", 0xfff0fff0 },
  400. { "hotpink", 0xffff69b4 },
  401. { "indianred", 0xffcd5c5c },
  402. { "indigo", 0xff4b0082 },
  403. { "ivory", 0xfffffff0 },
  404. { "khaki", 0xfff0e68c },
  405. { "lavender", 0xffe6e6fa },
  406. { "lavenderblush", 0xfffff0f5 },
  407. { "lawngreen", 0xff7cfc00 },
  408. { "lemonchiffon", 0xfffffacd },
  409. { "lightblue", 0xffadd8e6 },
  410. { "lightcoral", 0xfff08080 },
  411. { "lightcyan", 0xffe0ffff },
  412. { "lightgoldenrodyellow", 0xfffafad2 },
  413. { "lightgray", 0xffd3d3d3 },
  414. { "lightgrey", 0xffd3d3d3 },
  415. { "lightgreen", 0xff90ee90 },
  416. { "lightpink", 0xffffb6c1 },
  417. { "lightsalmon", 0xffffa07a },
  418. { "lightseagreen", 0xff20b2aa },
  419. { "lightskyblue", 0xff87cefa },
  420. { "lightslategray", 0xff778899 },
  421. { "lightslategrey", 0xff778899 },
  422. { "lightsteelblue", 0xffb0c4de },
  423. { "lightyellow", 0xffffffe0 },
  424. { "lime", 0xff00ff00 },
  425. { "limegreen", 0xff32cd32 },
  426. { "linen", 0xfffaf0e6 },
  427. { "magenta", 0xffff00ff },
  428. { "maroon", 0xff800000 },
  429. { "mediumaquamarine", 0xff66cdaa },
  430. { "mediumblue", 0xff0000cd },
  431. { "mediumorchid", 0xffba55d3 },
  432. { "mediumpurple", 0xff9370d8 },
  433. { "mediumseagreen", 0xff3cb371 },
  434. { "mediumslateblue", 0xff7b68ee },
  435. { "mediumspringgreen", 0xff00fa9a },
  436. { "mediumturquoise", 0xff48d1cc },
  437. { "mediumvioletred", 0xffc71585 },
  438. { "midnightblue", 0xff191970 },
  439. { "mintcream", 0xfff5fffa },
  440. { "mistyrose", 0xffffe4e1 },
  441. { "moccasin", 0xffffe4b5 },
  442. { "navajowhite", 0xffffdead },
  443. { "navy", 0xff000080 },
  444. { "oldlace", 0xfffdf5e6 },
  445. { "olive", 0xff808000 },
  446. { "olivedrab", 0xff6b8e23 },
  447. { "orange", 0xffffa500 },
  448. { "orangered", 0xffff4500 },
  449. { "orchid", 0xffda70d6 },
  450. { "palegoldenrod", 0xffeee8aa },
  451. { "palegreen", 0xff98fb98 },
  452. { "paleturquoise", 0xffafeeee },
  453. { "palevioletred", 0xffd87093 },
  454. { "papayawhip", 0xffffefd5 },
  455. { "peachpuff", 0xffffdab9 },
  456. { "peru", 0xffcd853f },
  457. { "pink", 0xffffc0cb },
  458. { "plum", 0xffdda0dd },
  459. { "powderblue", 0xffb0e0e6 },
  460. { "purple", 0xff800080 },
  461. { "red", 0xffff0000 },
  462. { "rosybrown", 0xffbc8f8f },
  463. { "royalblue", 0xff4169e1 },
  464. { "saddlebrown", 0xff8b4513 },
  465. { "salmon", 0xfffa8072 },
  466. { "sandybrown", 0xfff4a460 },
  467. { "seagreen", 0xff2e8b57 },
  468. { "seashell", 0xfffff5ee },
  469. { "sienna", 0xffa0522d },
  470. { "silver", 0xffc0c0c0 },
  471. { "skyblue", 0xff87ceeb },
  472. { "slateblue", 0xff6a5acd },
  473. { "slategray", 0xff708090 },
  474. { "slategrey", 0xff708090 },
  475. { "snow", 0xfffffafa },
  476. { "springgreen", 0xff00ff7f },
  477. { "steelblue", 0xff4682b4 },
  478. { "tan", 0xffd2b48c },
  479. { "teal", 0xff008080 },
  480. { "thistle", 0xffd8bfd8 },
  481. { "tomato", 0xffff6347 },
  482. { "turquoise", 0xff40e0d0 },
  483. { "violet", 0xffee82ee },
  484. { "wheat", 0xfff5deb3 },
  485. { "white", 0xffffffff },
  486. { "whitesmoke", 0xfff5f5f5 },
  487. { "yellow", 0xffffff00 },
  488. { "yellowgreen", 0xff9acd32 }
  489. };
  490. static void _toColor(const char* str, uint8_t* r, uint8_t* g, uint8_t* b, char** ref)
  491. {
  492. unsigned int len = strlen(str);
  493. char *red, *green, *blue;
  494. unsigned char tr, tg, tb;
  495. if (len == 4 && str[0] == '#') {
  496. //Case for "#456" should be interprete as "#445566"
  497. if (isxdigit(str[1]) && isxdigit(str[2]) && isxdigit(str[3])) {
  498. char tmp[3] = { '\0', '\0', '\0' };
  499. tmp[0] = str[1];
  500. tmp[1] = str[1];
  501. *r = strtol(tmp, nullptr, 16);
  502. tmp[0] = str[2];
  503. tmp[1] = str[2];
  504. *g = strtol(tmp, nullptr, 16);
  505. tmp[0] = str[3];
  506. tmp[1] = str[3];
  507. *b = strtol(tmp, nullptr, 16);
  508. }
  509. } else if (len == 7 && str[0] == '#') {
  510. if (isxdigit(str[1]) && isxdigit(str[2]) && isxdigit(str[3]) && isxdigit(str[4]) && isxdigit(str[5]) && isxdigit(str[6])) {
  511. char tmp[3] = { '\0', '\0', '\0' };
  512. tmp[0] = str[1];
  513. tmp[1] = str[2];
  514. *r = strtol(tmp, nullptr, 16);
  515. tmp[0] = str[3];
  516. tmp[1] = str[4];
  517. *g = strtol(tmp, nullptr, 16);
  518. tmp[0] = str[5];
  519. tmp[1] = str[6];
  520. *b = strtol(tmp, nullptr, 16);
  521. }
  522. } else if (len >= 10 && (str[0] == 'r' || str[0] == 'R') && (str[1] == 'g' || str[1] == 'G') && (str[2] == 'b' || str[2] == 'B') && str[3] == '(' && str[len - 1] == ')') {
  523. tr = _parseColor(str + 4, &red);
  524. if (red && *red == ',') {
  525. tg = _parseColor(red + 1, &green);
  526. if (green && *green == ',') {
  527. tb = _parseColor(green + 1, &blue);
  528. if (blue && blue[0] == ')' && blue[1] == '\0') {
  529. *r = tr;
  530. *g = tg;
  531. *b = tb;
  532. }
  533. }
  534. }
  535. } else if (ref && len >= 3 && !strncmp(str, "url", 3)) {
  536. if (*ref) free(*ref);
  537. *ref = _idFromUrl((const char*)(str + 3));
  538. } else {
  539. //Handle named color
  540. for (unsigned int i = 0; i < (sizeof(colors) / sizeof(colors[0])); i++) {
  541. if (!strcasecmp(colors[i].name, str)) {
  542. *r = (((uint8_t*)(&(colors[i].value)))[2]);
  543. *g = (((uint8_t*)(&(colors[i].value)))[1]);
  544. *b = (((uint8_t*)(&(colors[i].value)))[0]);
  545. return;
  546. }
  547. }
  548. }
  549. }
  550. static char* _parseNumbersArray(char* str, float* points, int* ptCount, int len)
  551. {
  552. int count = 0;
  553. char* end = nullptr;
  554. str = _skipSpace(str, nullptr);
  555. while ((count < len) && (isdigit(*str) || *str == '-' || *str == '+' || *str == '.')) {
  556. points[count++] = strToFloat(str, &end);
  557. str = end;
  558. str = _skipSpace(str, nullptr);
  559. if (*str == ',') ++str;
  560. //Eat the rest of space
  561. str = _skipSpace(str, nullptr);
  562. }
  563. *ptCount = count;
  564. return str;
  565. }
  566. enum class MatrixState {
  567. Unknown,
  568. Matrix,
  569. Translate,
  570. Rotate,
  571. Scale,
  572. SkewX,
  573. SkewY
  574. };
  575. #define MATRIX_DEF(Name, Value) \
  576. { \
  577. #Name, sizeof(#Name), Value \
  578. }
  579. static constexpr struct
  580. {
  581. const char* tag;
  582. int sz;
  583. MatrixState state;
  584. } matrixTags[] = {
  585. MATRIX_DEF(matrix, MatrixState::Matrix),
  586. MATRIX_DEF(translate, MatrixState::Translate),
  587. MATRIX_DEF(rotate, MatrixState::Rotate),
  588. MATRIX_DEF(scale, MatrixState::Scale),
  589. MATRIX_DEF(skewX, MatrixState::SkewX),
  590. MATRIX_DEF(skewY, MatrixState::SkewY)
  591. };
  592. /* parse transform attribute
  593. * https://www.w3.org/TR/SVG/coords.html#TransformAttribute
  594. */
  595. static Matrix* _parseTransformationMatrix(const char* value)
  596. {
  597. const int POINT_CNT = 8;
  598. auto matrix = (Matrix*)malloc(sizeof(Matrix));
  599. if (!matrix) return nullptr;
  600. *matrix = {1, 0, 0, 0, 1, 0, 0, 0, 1};
  601. float points[POINT_CNT];
  602. int ptCount = 0;
  603. char* str = (char*)value;
  604. char* end = str + strlen(str);
  605. while (str < end) {
  606. auto state = MatrixState::Unknown;
  607. if (isspace(*str) || (*str == ',')) {
  608. ++str;
  609. continue;
  610. }
  611. for (unsigned int i = 0; i < sizeof(matrixTags) / sizeof(matrixTags[0]); i++) {
  612. if (!strncmp(matrixTags[i].tag, str, matrixTags[i].sz - 1)) {
  613. state = matrixTags[i].state;
  614. str += (matrixTags[i].sz - 1);
  615. break;
  616. }
  617. }
  618. if (state == MatrixState::Unknown) goto error;
  619. str = _skipSpace(str, end);
  620. if (*str != '(') goto error;
  621. ++str;
  622. str = _parseNumbersArray(str, points, &ptCount, POINT_CNT);
  623. if (*str != ')') goto error;
  624. ++str;
  625. if (state == MatrixState::Matrix) {
  626. if (ptCount != 6) goto error;
  627. Matrix tmp = {points[0], points[2], points[4], points[1], points[3], points[5], 0, 0, 1};
  628. *matrix = mathMultiply(matrix, &tmp);
  629. } else if (state == MatrixState::Translate) {
  630. if (ptCount == 1) {
  631. Matrix tmp = {1, 0, points[0], 0, 1, 0, 0, 0, 1};
  632. *matrix = mathMultiply(matrix, &tmp);
  633. } else if (ptCount == 2) {
  634. Matrix tmp = {1, 0, points[0], 0, 1, points[1], 0, 0, 1};
  635. *matrix = mathMultiply(matrix, &tmp);
  636. } else goto error;
  637. } else if (state == MatrixState::Rotate) {
  638. //Transform to signed.
  639. points[0] = fmodf(points[0], 360.0f);
  640. if (points[0] < 0) points[0] += 360.0f;
  641. auto c = cosf(points[0] * (MATH_PI / 180.0f));
  642. auto s = sinf(points[0] * (MATH_PI / 180.0f));
  643. if (ptCount == 1) {
  644. Matrix tmp = { c, -s, 0, s, c, 0, 0, 0, 1 };
  645. *matrix = mathMultiply(matrix, &tmp);
  646. } else if (ptCount == 3) {
  647. Matrix tmp = { 1, 0, points[1], 0, 1, points[2], 0, 0, 1 };
  648. *matrix = mathMultiply(matrix, &tmp);
  649. tmp = { c, -s, 0, s, c, 0, 0, 0, 1 };
  650. *matrix = mathMultiply(matrix, &tmp);
  651. tmp = { 1, 0, -points[1], 0, 1, -points[2], 0, 0, 1 };
  652. *matrix = mathMultiply(matrix, &tmp);
  653. } else {
  654. goto error;
  655. }
  656. } else if (state == MatrixState::Scale) {
  657. if (ptCount < 1 || ptCount > 2) goto error;
  658. auto sx = points[0];
  659. auto sy = sx;
  660. if (ptCount == 2) sy = points[1];
  661. Matrix tmp = { sx, 0, 0, 0, sy, 0, 0, 0, 1 };
  662. *matrix = mathMultiply(matrix, &tmp);
  663. } else if (state == MatrixState::SkewX) {
  664. if (ptCount != 1) goto error;
  665. auto deg = tanf(points[0] * (MATH_PI / 180.0f));
  666. Matrix tmp = { 1, deg, 0, 0, 1, 0, 0, 0, 1 };
  667. *matrix = mathMultiply(matrix, &tmp);
  668. } else if (state == MatrixState::SkewY) {
  669. if (ptCount != 1) goto error;
  670. auto deg = tanf(points[0] * (MATH_PI / 180.0f));
  671. Matrix tmp = { 1, 0, 0, deg, 1, 0, 0, 0, 1 };
  672. *matrix = mathMultiply(matrix, &tmp);
  673. }
  674. }
  675. return matrix;
  676. error:
  677. if (matrix) free(matrix);
  678. return nullptr;
  679. }
  680. #define LENGTH_DEF(Name, Value) \
  681. { \
  682. #Name, sizeof(#Name), Value \
  683. }
  684. static void _postpone(Array<SvgNodeIdPair>& nodes, SvgNode *node, char* id)
  685. {
  686. nodes.push({node, id});
  687. }
  688. /*
  689. // TODO - remove?
  690. static constexpr struct
  691. {
  692. const char* tag;
  693. int sz;
  694. SvgLengthType type;
  695. } lengthTags[] = {
  696. LENGTH_DEF(%, SvgLengthType::Percent),
  697. LENGTH_DEF(px, SvgLengthType::Px),
  698. LENGTH_DEF(pc, SvgLengthType::Pc),
  699. LENGTH_DEF(pt, SvgLengthType::Pt),
  700. LENGTH_DEF(mm, SvgLengthType::Mm),
  701. LENGTH_DEF(cm, SvgLengthType::Cm),
  702. LENGTH_DEF(in, SvgLengthType::In)
  703. };
  704. static float _parseLength(const char* str, SvgLengthType* type)
  705. {
  706. float value;
  707. int sz = strlen(str);
  708. *type = SvgLengthType::Px;
  709. for (unsigned int i = 0; i < sizeof(lengthTags) / sizeof(lengthTags[0]); i++) {
  710. if (lengthTags[i].sz - 1 == sz && !strncmp(lengthTags[i].tag, str, sz)) *type = lengthTags[i].type;
  711. }
  712. value = svgUtilStrtof(str, nullptr);
  713. return value;
  714. }
  715. */
  716. static bool _parseStyleAttr(void* data, const char* key, const char* value);
  717. static bool _parseStyleAttr(void* data, const char* key, const char* value, bool style);
  718. static bool _attrParseSvgNode(void* data, const char* key, const char* value)
  719. {
  720. SvgLoaderData* loader = (SvgLoaderData*)data;
  721. SvgNode* node = loader->svgParse->node;
  722. SvgDocNode* doc = &(node->node.doc);
  723. if (!strcmp(key, "width")) {
  724. doc->w = _toFloat(loader->svgParse, value, SvgParserLengthType::Horizontal);
  725. if (strstr(value, "%") && !(doc->viewFlag & SvgViewFlag::Viewbox)) {
  726. doc->viewFlag = (doc->viewFlag | SvgViewFlag::WidthInPercent);
  727. } else {
  728. doc->viewFlag = (doc->viewFlag | SvgViewFlag::Width);
  729. }
  730. } else if (!strcmp(key, "height")) {
  731. doc->h = _toFloat(loader->svgParse, value, SvgParserLengthType::Vertical);
  732. if (strstr(value, "%") && !(doc->viewFlag & SvgViewFlag::Viewbox)) {
  733. doc->viewFlag = (doc->viewFlag | SvgViewFlag::HeightInPercent);
  734. } else {
  735. doc->viewFlag = (doc->viewFlag | SvgViewFlag::Height);
  736. }
  737. } else if (!strcmp(key, "viewBox")) {
  738. if (_parseNumber(&value, &doc->vx)) {
  739. if (_parseNumber(&value, &doc->vy)) {
  740. if (_parseNumber(&value, &doc->vw)) {
  741. if (_parseNumber(&value, &doc->vh)) {
  742. doc->viewFlag = (doc->viewFlag | SvgViewFlag::Viewbox);
  743. loader->svgParse->global.h = doc->vh;
  744. }
  745. loader->svgParse->global.w = doc->vw;
  746. }
  747. loader->svgParse->global.y = doc->vy;
  748. }
  749. loader->svgParse->global.x = doc->vx;
  750. }
  751. if ((doc->viewFlag & SvgViewFlag::Viewbox) && (doc->vw < 0.0f || doc->vh < 0.0f)) {
  752. doc->viewFlag = (SvgViewFlag)((uint32_t)doc->viewFlag & ~(uint32_t)SvgViewFlag::Viewbox);
  753. TVGLOG("SVG", "Negative values of the <viewBox> width and/or height - the attribute invalidated.");
  754. }
  755. if (!(doc->viewFlag & SvgViewFlag::Viewbox)) {
  756. loader->svgParse->global.x = loader->svgParse->global.y = 0.0f;
  757. loader->svgParse->global.w = loader->svgParse->global.h = 1.0f;
  758. }
  759. } else if (!strcmp(key, "preserveAspectRatio")) {
  760. _parseAspectRatio(&value, &doc->align, &doc->meetOrSlice);
  761. } else if (!strcmp(key, "style")) {
  762. return simpleXmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
  763. #ifdef THORVG_LOG_ENABLED
  764. } else if ((!strcmp(key, "x") || !strcmp(key, "y")) && fabsf(strToFloat(value, nullptr)) > FLT_EPSILON) {
  765. TVGLOG("SVG", "Unsupported attributes used [Elements type: Svg][Attribute: %s][Value: %s]", key, value);
  766. #endif
  767. } else {
  768. return _parseStyleAttr(loader, key, value, false);
  769. }
  770. return true;
  771. }
  772. //https://www.w3.org/TR/SVGTiny12/painting.html#SpecifyingPaint
  773. static void _handlePaintAttr(SvgPaint* paint, const char* value)
  774. {
  775. if (!strcmp(value, "none")) {
  776. //No paint property
  777. paint->none = true;
  778. return;
  779. }
  780. paint->none = false;
  781. if (!strcmp(value, "currentColor")) {
  782. paint->curColor = true;
  783. return;
  784. }
  785. _toColor(value, &paint->color.r, &paint->color.g, &paint->color.b, &paint->url);
  786. }
  787. static void _handleColorAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
  788. {
  789. SvgStyleProperty* style = node->style;
  790. style->curColorSet = true;
  791. _toColor(value, &style->color.r, &style->color.g, &style->color.b, nullptr);
  792. }
  793. static void _handleFillAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
  794. {
  795. SvgStyleProperty* style = node->style;
  796. style->fill.flags = (style->fill.flags | SvgFillFlags::Paint);
  797. _handlePaintAttr(&style->fill.paint, value);
  798. }
  799. static void _handleStrokeAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
  800. {
  801. SvgStyleProperty* style = node->style;
  802. style->stroke.flags = (style->stroke.flags | SvgStrokeFlags::Paint);
  803. _handlePaintAttr(&style->stroke.paint, value);
  804. }
  805. static void _handleStrokeOpacityAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
  806. {
  807. node->style->stroke.flags = (node->style->stroke.flags | SvgStrokeFlags::Opacity);
  808. node->style->stroke.opacity = _toOpacity(value);
  809. }
  810. static void _handleStrokeDashArrayAttr(SvgLoaderData* loader, SvgNode* node, const char* value)
  811. {
  812. node->style->stroke.flags = (node->style->stroke.flags | SvgStrokeFlags::Dash);
  813. _parseDashArray(loader, value, &node->style->stroke.dash);
  814. }
  815. static void _handleStrokeDashOffsetAttr(SvgLoaderData* loader, SvgNode* node, const char* value)
  816. {
  817. node->style->stroke.flags = (node->style->stroke.flags | SvgStrokeFlags::DashOffset);
  818. node->style->stroke.dash.offset = _toFloat(loader->svgParse, value, SvgParserLengthType::Horizontal);
  819. }
  820. static void _handleStrokeWidthAttr(SvgLoaderData* loader, SvgNode* node, const char* value)
  821. {
  822. node->style->stroke.flags = (node->style->stroke.flags | SvgStrokeFlags::Width);
  823. node->style->stroke.width = _toFloat(loader->svgParse, value, SvgParserLengthType::Horizontal);
  824. }
  825. static void _handleStrokeLineCapAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
  826. {
  827. node->style->stroke.flags = (node->style->stroke.flags | SvgStrokeFlags::Cap);
  828. node->style->stroke.cap = _toLineCap(value);
  829. }
  830. static void _handleStrokeLineJoinAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
  831. {
  832. node->style->stroke.flags = (node->style->stroke.flags | SvgStrokeFlags::Join);
  833. node->style->stroke.join = _toLineJoin(value);
  834. }
  835. static void _handleStrokeMiterlimitAttr(SvgLoaderData* loader, SvgNode* node, const char* value)
  836. {
  837. char* end = nullptr;
  838. const float miterlimit = strToFloat(value, &end);
  839. // https://www.w3.org/TR/SVG2/painting.html#LineJoin
  840. // - A negative value for stroke-miterlimit must be treated as an illegal value.
  841. if (miterlimit < 0.0f) {
  842. TVGERR("SVG", "A stroke-miterlimit change (%f <- %f) with a negative value is omitted.",
  843. node->style->stroke.miterlimit, miterlimit);
  844. return;
  845. }
  846. node->style->stroke.flags = (node->style->stroke.flags | SvgStrokeFlags::Miterlimit);
  847. node->style->stroke.miterlimit = miterlimit;
  848. }
  849. static void _handleFillRuleAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
  850. {
  851. node->style->fill.flags = (node->style->fill.flags | SvgFillFlags::FillRule);
  852. node->style->fill.fillRule = _toFillRule(value);
  853. }
  854. static void _handleOpacityAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
  855. {
  856. node->style->opacity = _toOpacity(value);
  857. }
  858. static void _handleFillOpacityAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
  859. {
  860. node->style->fill.flags = (node->style->fill.flags | SvgFillFlags::Opacity);
  861. node->style->fill.opacity = _toOpacity(value);
  862. }
  863. static void _handleTransformAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
  864. {
  865. node->transform = _parseTransformationMatrix(value);
  866. }
  867. static void _handleClipPathAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
  868. {
  869. SvgStyleProperty* style = node->style;
  870. int len = strlen(value);
  871. if (len >= 3 && !strncmp(value, "url", 3)) {
  872. if (style->clipPath.url) free(style->clipPath.url);
  873. style->clipPath.url = _idFromUrl((const char*)(value + 3));
  874. }
  875. }
  876. static void _handleMaskAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
  877. {
  878. SvgStyleProperty* style = node->style;
  879. int len = strlen(value);
  880. if (len >= 3 && !strncmp(value, "url", 3)) {
  881. if (style->mask.url) free(style->mask.url);
  882. style->mask.url = _idFromUrl((const char*)(value + 3));
  883. }
  884. }
  885. static void _handleMaskTypeAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
  886. {
  887. node->node.mask.type = _toMaskType(value);
  888. }
  889. static void _handleDisplayAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
  890. {
  891. //TODO : The display attribute can have various values as well as "none".
  892. // The default is "inline" which means visible and "none" means invisible.
  893. // Depending on the type of node, additional functionality may be required.
  894. // refer to https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/display
  895. if (!strcmp(value, "none")) node->display = false;
  896. else node->display = true;
  897. }
  898. static void _handlePaintOrderAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
  899. {
  900. node->style->flags = (node->style->flags | SvgStyleFlags::PaintOrder);
  901. node->style->paintOrder = _toPaintOrder(value);
  902. }
  903. static void _handleCssClassAttr(SvgLoaderData* loader, SvgNode* node, const char* value)
  904. {
  905. auto cssClass = &node->style->cssClass;
  906. if (*cssClass && value) free(*cssClass);
  907. *cssClass = _copyId(value);
  908. bool cssClassFound = false;
  909. //css styling: tag.name has higher priority than .name
  910. if (auto cssNode = cssFindStyleNode(loader->cssStyle, *cssClass, node->type)) {
  911. cssClassFound = true;
  912. cssCopyStyleAttr(node, cssNode);
  913. }
  914. if (auto cssNode = cssFindStyleNode(loader->cssStyle, *cssClass)) {
  915. cssClassFound = true;
  916. cssCopyStyleAttr(node, cssNode);
  917. }
  918. if (!cssClassFound) _postpone(loader->nodesToStyle, node, *cssClass);
  919. }
  920. typedef void (*styleMethod)(SvgLoaderData* loader, SvgNode* node, const char* value);
  921. #define STYLE_DEF(Name, Name1, Flag) { #Name, sizeof(#Name), _handle##Name1##Attr, Flag }
  922. static constexpr struct
  923. {
  924. const char* tag;
  925. int sz;
  926. styleMethod tagHandler;
  927. SvgStyleFlags flag;
  928. } styleTags[] = {
  929. STYLE_DEF(color, Color, SvgStyleFlags::Color),
  930. STYLE_DEF(fill, Fill, SvgStyleFlags::Fill),
  931. STYLE_DEF(fill-rule, FillRule, SvgStyleFlags::FillRule),
  932. STYLE_DEF(fill-opacity, FillOpacity, SvgStyleFlags::FillOpacity),
  933. STYLE_DEF(opacity, Opacity, SvgStyleFlags::Opacity),
  934. STYLE_DEF(stroke, Stroke, SvgStyleFlags::Stroke),
  935. STYLE_DEF(stroke-width, StrokeWidth, SvgStyleFlags::StrokeWidth),
  936. STYLE_DEF(stroke-linejoin, StrokeLineJoin, SvgStyleFlags::StrokeLineJoin),
  937. STYLE_DEF(stroke-miterlimit, StrokeMiterlimit, SvgStyleFlags::StrokeMiterlimit),
  938. STYLE_DEF(stroke-linecap, StrokeLineCap, SvgStyleFlags::StrokeLineCap),
  939. STYLE_DEF(stroke-opacity, StrokeOpacity, SvgStyleFlags::StrokeOpacity),
  940. STYLE_DEF(stroke-dasharray, StrokeDashArray, SvgStyleFlags::StrokeDashArray),
  941. STYLE_DEF(stroke-dashoffset, StrokeDashOffset, SvgStyleFlags::StrokeDashOffset),
  942. STYLE_DEF(transform, Transform, SvgStyleFlags::Transform),
  943. STYLE_DEF(clip-path, ClipPath, SvgStyleFlags::ClipPath),
  944. STYLE_DEF(mask, Mask, SvgStyleFlags::Mask),
  945. STYLE_DEF(mask-type, MaskType, SvgStyleFlags::MaskType),
  946. STYLE_DEF(display, Display, SvgStyleFlags::Display),
  947. STYLE_DEF(paint-order, PaintOrder, SvgStyleFlags::PaintOrder)
  948. };
  949. static bool _parseStyleAttr(void* data, const char* key, const char* value, bool style)
  950. {
  951. SvgLoaderData* loader = (SvgLoaderData*)data;
  952. SvgNode* node = loader->svgParse->node;
  953. int sz;
  954. if (!key || !value) return false;
  955. //Trim the white space
  956. key = _skipSpace(key, nullptr);
  957. value = _skipSpace(value, nullptr);
  958. sz = strlen(key);
  959. for (unsigned int i = 0; i < sizeof(styleTags) / sizeof(styleTags[0]); i++) {
  960. if (styleTags[i].sz - 1 == sz && !strncmp(styleTags[i].tag, key, sz)) {
  961. bool importance = false;
  962. if (auto ptr = strstr(value, "!important")) {
  963. size_t size = ptr - value;
  964. while (size > 0 && isspace(value[size - 1])) {
  965. size--;
  966. }
  967. value = strDuplicate(value, size);
  968. importance = true;
  969. }
  970. if (style) {
  971. if (importance || !(node->style->flagsImportance & styleTags[i].flag)) {
  972. styleTags[i].tagHandler(loader, node, value);
  973. node->style->flags = (node->style->flags | styleTags[i].flag);
  974. }
  975. } else if (!(node->style->flags & styleTags[i].flag)) {
  976. styleTags[i].tagHandler(loader, node, value);
  977. }
  978. if (importance) {
  979. node->style->flagsImportance = (node->style->flags | styleTags[i].flag);
  980. free(const_cast<char*>(value));
  981. }
  982. return true;
  983. }
  984. }
  985. return false;
  986. }
  987. static bool _parseStyleAttr(void* data, const char* key, const char* value)
  988. {
  989. return _parseStyleAttr(data, key, value, true);
  990. }
  991. /* parse g node
  992. * https://www.w3.org/TR/SVG/struct.html#Groups
  993. */
  994. static bool _attrParseGNode(void* data, const char* key, const char* value)
  995. {
  996. SvgLoaderData* loader = (SvgLoaderData*)data;
  997. SvgNode* node = loader->svgParse->node;
  998. if (!strcmp(key, "style")) {
  999. return simpleXmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
  1000. } else if (!strcmp(key, "transform")) {
  1001. node->transform = _parseTransformationMatrix(value);
  1002. } else if (!strcmp(key, "id")) {
  1003. if (node->id && value) free(node->id);
  1004. node->id = _copyId(value);
  1005. } else if (!strcmp(key, "class")) {
  1006. _handleCssClassAttr(loader, node, value);
  1007. } else if (!strcmp(key, "clip-path")) {
  1008. _handleClipPathAttr(loader, node, value);
  1009. } else if (!strcmp(key, "mask")) {
  1010. _handleMaskAttr(loader, node, value);
  1011. } else {
  1012. return _parseStyleAttr(loader, key, value, false);
  1013. }
  1014. return true;
  1015. }
  1016. /* parse clipPath node
  1017. * https://www.w3.org/TR/SVG/struct.html#Groups
  1018. */
  1019. static bool _attrParseClipPathNode(void* data, const char* key, const char* value)
  1020. {
  1021. SvgLoaderData* loader = (SvgLoaderData*)data;
  1022. SvgNode* node = loader->svgParse->node;
  1023. SvgClipNode* clip = &(node->node.clip);
  1024. if (!strcmp(key, "style")) {
  1025. return simpleXmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
  1026. } else if (!strcmp(key, "transform")) {
  1027. node->transform = _parseTransformationMatrix(value);
  1028. } else if (!strcmp(key, "id")) {
  1029. if (node->id && value) free(node->id);
  1030. node->id = _copyId(value);
  1031. } else if (!strcmp(key, "class")) {
  1032. _handleCssClassAttr(loader, node, value);
  1033. } else if (!strcmp(key, "clipPathUnits")) {
  1034. if (!strcmp(value, "objectBoundingBox")) clip->userSpace = false;
  1035. } else {
  1036. return _parseStyleAttr(loader, key, value, false);
  1037. }
  1038. return true;
  1039. }
  1040. static bool _attrParseMaskNode(void* data, const char* key, const char* value)
  1041. {
  1042. SvgLoaderData* loader = (SvgLoaderData*)data;
  1043. SvgNode* node = loader->svgParse->node;
  1044. SvgMaskNode* mask = &(node->node.mask);
  1045. if (!strcmp(key, "style")) {
  1046. return simpleXmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
  1047. } else if (!strcmp(key, "transform")) {
  1048. node->transform = _parseTransformationMatrix(value);
  1049. } else if (!strcmp(key, "id")) {
  1050. if (node->id && value) free(node->id);
  1051. node->id = _copyId(value);
  1052. } else if (!strcmp(key, "class")) {
  1053. _handleCssClassAttr(loader, node, value);
  1054. } else if (!strcmp(key, "maskContentUnits")) {
  1055. if (!strcmp(value, "objectBoundingBox")) mask->userSpace = false;
  1056. } else if (!strcmp(key, "mask-type")) {
  1057. mask->type = _toMaskType(value);
  1058. } else {
  1059. return _parseStyleAttr(loader, key, value, false);
  1060. }
  1061. return true;
  1062. }
  1063. static bool _attrParseCssStyleNode(void* data, const char* key, const char* value)
  1064. {
  1065. SvgLoaderData* loader = (SvgLoaderData*)data;
  1066. SvgNode* node = loader->svgParse->node;
  1067. if (!strcmp(key, "id")) {
  1068. if (node->id && value) free(node->id);
  1069. node->id = _copyId(value);
  1070. } else {
  1071. return _parseStyleAttr(loader, key, value, false);
  1072. }
  1073. return true;
  1074. }
  1075. static bool _attrParseSymbolNode(void* data, const char* key, const char* value)
  1076. {
  1077. SvgLoaderData* loader = (SvgLoaderData*)data;
  1078. SvgNode* node = loader->svgParse->node;
  1079. SvgSymbolNode* symbol = &(node->node.symbol);
  1080. if (!strcmp(key, "viewBox")) {
  1081. if (!_parseNumber(&value, &symbol->vx) || !_parseNumber(&value, &symbol->vy)) return false;
  1082. if (!_parseNumber(&value, &symbol->vw) || !_parseNumber(&value, &symbol->vh)) return false;
  1083. symbol->hasViewBox = true;
  1084. } else if (!strcmp(key, "width")) {
  1085. symbol->w = _toFloat(loader->svgParse, value, SvgParserLengthType::Horizontal);
  1086. symbol->hasWidth = true;
  1087. } else if (!strcmp(key, "height")) {
  1088. symbol->h = _toFloat(loader->svgParse, value, SvgParserLengthType::Vertical);
  1089. symbol->hasHeight = true;
  1090. } else if (!strcmp(key, "preserveAspectRatio")) {
  1091. _parseAspectRatio(&value, &symbol->align, &symbol->meetOrSlice);
  1092. } else if (!strcmp(key, "overflow")) {
  1093. if (!strcmp(value, "visible")) symbol->overflowVisible = true;
  1094. } else {
  1095. return _attrParseGNode(data, key, value);
  1096. }
  1097. return true;
  1098. }
  1099. static SvgNode* _createNode(SvgNode* parent, SvgNodeType type)
  1100. {
  1101. SvgNode* node = (SvgNode*)calloc(1, sizeof(SvgNode));
  1102. if (!node) return nullptr;
  1103. //Default fill property
  1104. node->style = (SvgStyleProperty*)calloc(1, sizeof(SvgStyleProperty));
  1105. if (!node->style) {
  1106. free(node);
  1107. return nullptr;
  1108. }
  1109. //Update the default value of stroke and fill
  1110. //https://www.w3.org/TR/SVGTiny12/painting.html#SpecifyingPaint
  1111. node->style->fill.paint.none = false;
  1112. //Default fill opacity is 1
  1113. node->style->fill.opacity = 255;
  1114. node->style->opacity = 255;
  1115. //Default current color is not set
  1116. node->style->fill.paint.curColor = false;
  1117. node->style->curColorSet = false;
  1118. //Default fill rule is nonzero
  1119. node->style->fill.fillRule = FillRule::Winding;
  1120. //Default stroke is none
  1121. node->style->stroke.paint.none = true;
  1122. //Default stroke opacity is 1
  1123. node->style->stroke.opacity = 255;
  1124. //Default stroke current color is not set
  1125. node->style->stroke.paint.curColor = false;
  1126. //Default stroke width is 1
  1127. node->style->stroke.width = 1;
  1128. //Default line cap is butt
  1129. node->style->stroke.cap = StrokeCap::Butt;
  1130. //Default line join is miter
  1131. node->style->stroke.join = StrokeJoin::Miter;
  1132. node->style->stroke.miterlimit = 4.0f;
  1133. node->style->stroke.scale = 1.0;
  1134. node->style->paintOrder = _toPaintOrder("fill stroke");
  1135. //Default display is true("inline").
  1136. node->display = true;
  1137. node->parent = parent;
  1138. node->type = type;
  1139. if (parent) parent->child.push(node);
  1140. return node;
  1141. }
  1142. static SvgNode* _createDefsNode(TVG_UNUSED SvgLoaderData* loader, TVG_UNUSED SvgNode* parent, const char* buf, unsigned bufLength, TVG_UNUSED parseAttributes func)
  1143. {
  1144. if (loader->def && loader->doc->node.doc.defs) return loader->def;
  1145. SvgNode* node = _createNode(nullptr, SvgNodeType::Defs);
  1146. loader->def = node;
  1147. loader->doc->node.doc.defs = node;
  1148. return node;
  1149. }
  1150. static SvgNode* _createGNode(TVG_UNUSED SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
  1151. {
  1152. loader->svgParse->node = _createNode(parent, SvgNodeType::G);
  1153. if (!loader->svgParse->node) return nullptr;
  1154. func(buf, bufLength, _attrParseGNode, loader);
  1155. return loader->svgParse->node;
  1156. }
  1157. static SvgNode* _createSvgNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
  1158. {
  1159. loader->svgParse->node = _createNode(parent, SvgNodeType::Doc);
  1160. if (!loader->svgParse->node) return nullptr;
  1161. SvgDocNode* doc = &(loader->svgParse->node->node.doc);
  1162. loader->svgParse->global.w = 1.0f;
  1163. loader->svgParse->global.h = 1.0f;
  1164. doc->align = AspectRatioAlign::XMidYMid;
  1165. doc->meetOrSlice = AspectRatioMeetOrSlice::Meet;
  1166. doc->viewFlag = SvgViewFlag::None;
  1167. func(buf, bufLength, _attrParseSvgNode, loader);
  1168. if (!(doc->viewFlag & SvgViewFlag::Viewbox)) {
  1169. if (doc->viewFlag & SvgViewFlag::Width) {
  1170. loader->svgParse->global.w = doc->w;
  1171. }
  1172. if (doc->viewFlag & SvgViewFlag::Height) {
  1173. loader->svgParse->global.h = doc->h;
  1174. }
  1175. }
  1176. return loader->svgParse->node;
  1177. }
  1178. static SvgNode* _createMaskNode(SvgLoaderData* loader, SvgNode* parent, TVG_UNUSED const char* buf, TVG_UNUSED unsigned bufLength, parseAttributes func)
  1179. {
  1180. loader->svgParse->node = _createNode(parent, SvgNodeType::Mask);
  1181. if (!loader->svgParse->node) return nullptr;
  1182. loader->svgParse->node->node.mask.userSpace = true;
  1183. loader->svgParse->node->node.mask.type = SvgMaskType::Luminance;
  1184. func(buf, bufLength, _attrParseMaskNode, loader);
  1185. return loader->svgParse->node;
  1186. }
  1187. static SvgNode* _createClipPathNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
  1188. {
  1189. loader->svgParse->node = _createNode(parent, SvgNodeType::ClipPath);
  1190. if (!loader->svgParse->node) return nullptr;
  1191. loader->svgParse->node->display = false;
  1192. loader->svgParse->node->node.clip.userSpace = true;
  1193. func(buf, bufLength, _attrParseClipPathNode, loader);
  1194. return loader->svgParse->node;
  1195. }
  1196. static SvgNode* _createCssStyleNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
  1197. {
  1198. loader->svgParse->node = _createNode(parent, SvgNodeType::CssStyle);
  1199. if (!loader->svgParse->node) return nullptr;
  1200. func(buf, bufLength, _attrParseCssStyleNode, loader);
  1201. return loader->svgParse->node;
  1202. }
  1203. static SvgNode* _createSymbolNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
  1204. {
  1205. loader->svgParse->node = _createNode(parent, SvgNodeType::Symbol);
  1206. if (!loader->svgParse->node) return nullptr;
  1207. loader->svgParse->node->display = false;
  1208. loader->svgParse->node->node.symbol.align = AspectRatioAlign::XMidYMid;
  1209. loader->svgParse->node->node.symbol.meetOrSlice = AspectRatioMeetOrSlice::Meet;
  1210. loader->svgParse->node->node.symbol.overflowVisible = false;
  1211. loader->svgParse->node->node.symbol.hasViewBox = false;
  1212. loader->svgParse->node->node.symbol.hasWidth = false;
  1213. loader->svgParse->node->node.symbol.hasHeight = false;
  1214. loader->svgParse->node->node.symbol.vx = 0.0f;
  1215. loader->svgParse->node->node.symbol.vy = 0.0f;
  1216. func(buf, bufLength, _attrParseSymbolNode, loader);
  1217. return loader->svgParse->node;
  1218. }
  1219. static bool _attrParsePathNode(void* data, const char* key, const char* value)
  1220. {
  1221. SvgLoaderData* loader = (SvgLoaderData*)data;
  1222. SvgNode* node = loader->svgParse->node;
  1223. SvgPathNode* path = &(node->node.path);
  1224. if (!strcmp(key, "d")) {
  1225. if (path->path) free(path->path);
  1226. //Temporary: need to copy
  1227. path->path = _copyId(value);
  1228. } else if (!strcmp(key, "style")) {
  1229. return simpleXmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
  1230. } else if (!strcmp(key, "clip-path")) {
  1231. _handleClipPathAttr(loader, node, value);
  1232. } else if (!strcmp(key, "mask")) {
  1233. _handleMaskAttr(loader, node, value);
  1234. } else if (!strcmp(key, "id")) {
  1235. if (node->id && value) free(node->id);
  1236. node->id = _copyId(value);
  1237. } else if (!strcmp(key, "class")) {
  1238. _handleCssClassAttr(loader, node, value);
  1239. } else {
  1240. return _parseStyleAttr(loader, key, value, false);
  1241. }
  1242. return true;
  1243. }
  1244. static SvgNode* _createPathNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
  1245. {
  1246. loader->svgParse->node = _createNode(parent, SvgNodeType::Path);
  1247. if (!loader->svgParse->node) return nullptr;
  1248. func(buf, bufLength, _attrParsePathNode, loader);
  1249. return loader->svgParse->node;
  1250. }
  1251. static constexpr struct
  1252. {
  1253. const char* tag;
  1254. SvgParserLengthType type;
  1255. int sz;
  1256. size_t offset;
  1257. } circleTags[] = {
  1258. {"cx", SvgParserLengthType::Horizontal, sizeof("cx"), offsetof(SvgCircleNode, cx)},
  1259. {"cy", SvgParserLengthType::Vertical, sizeof("cy"), offsetof(SvgCircleNode, cy)},
  1260. {"r", SvgParserLengthType::Other, sizeof("r"), offsetof(SvgCircleNode, r)}
  1261. };
  1262. /* parse the attributes for a circle element.
  1263. * https://www.w3.org/TR/SVG/shapes.html#CircleElement
  1264. */
  1265. static bool _attrParseCircleNode(void* data, const char* key, const char* value)
  1266. {
  1267. SvgLoaderData* loader = (SvgLoaderData*)data;
  1268. SvgNode* node = loader->svgParse->node;
  1269. SvgCircleNode* circle = &(node->node.circle);
  1270. unsigned char* array;
  1271. int sz = strlen(key);
  1272. array = (unsigned char*)circle;
  1273. for (unsigned int i = 0; i < sizeof(circleTags) / sizeof(circleTags[0]); i++) {
  1274. if (circleTags[i].sz - 1 == sz && !strncmp(circleTags[i].tag, key, sz)) {
  1275. *((float*)(array + circleTags[i].offset)) = _toFloat(loader->svgParse, value, circleTags[i].type);
  1276. return true;
  1277. }
  1278. }
  1279. if (!strcmp(key, "style")) {
  1280. return simpleXmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
  1281. } else if (!strcmp(key, "clip-path")) {
  1282. _handleClipPathAttr(loader, node, value);
  1283. } else if (!strcmp(key, "mask")) {
  1284. _handleMaskAttr(loader, node, value);
  1285. } else if (!strcmp(key, "id")) {
  1286. if (node->id && value) free(node->id);
  1287. node->id = _copyId(value);
  1288. } else if (!strcmp(key, "class")) {
  1289. _handleCssClassAttr(loader, node, value);
  1290. } else {
  1291. return _parseStyleAttr(loader, key, value, false);
  1292. }
  1293. return true;
  1294. }
  1295. static SvgNode* _createCircleNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
  1296. {
  1297. loader->svgParse->node = _createNode(parent, SvgNodeType::Circle);
  1298. if (!loader->svgParse->node) return nullptr;
  1299. func(buf, bufLength, _attrParseCircleNode, loader);
  1300. return loader->svgParse->node;
  1301. }
  1302. static constexpr struct
  1303. {
  1304. const char* tag;
  1305. SvgParserLengthType type;
  1306. int sz;
  1307. size_t offset;
  1308. } ellipseTags[] = {
  1309. {"cx", SvgParserLengthType::Horizontal, sizeof("cx"), offsetof(SvgEllipseNode, cx)},
  1310. {"cy", SvgParserLengthType::Vertical, sizeof("cy"), offsetof(SvgEllipseNode, cy)},
  1311. {"rx", SvgParserLengthType::Horizontal, sizeof("rx"), offsetof(SvgEllipseNode, rx)},
  1312. {"ry", SvgParserLengthType::Vertical, sizeof("ry"), offsetof(SvgEllipseNode, ry)}
  1313. };
  1314. /* parse the attributes for an ellipse element.
  1315. * https://www.w3.org/TR/SVG/shapes.html#EllipseElement
  1316. */
  1317. static bool _attrParseEllipseNode(void* data, const char* key, const char* value)
  1318. {
  1319. SvgLoaderData* loader = (SvgLoaderData*)data;
  1320. SvgNode* node = loader->svgParse->node;
  1321. SvgEllipseNode* ellipse = &(node->node.ellipse);
  1322. unsigned char* array;
  1323. int sz = strlen(key);
  1324. array = (unsigned char*)ellipse;
  1325. for (unsigned int i = 0; i < sizeof(ellipseTags) / sizeof(ellipseTags[0]); i++) {
  1326. if (ellipseTags[i].sz - 1 == sz && !strncmp(ellipseTags[i].tag, key, sz)) {
  1327. *((float*)(array + ellipseTags[i].offset)) = _toFloat(loader->svgParse, value, ellipseTags[i].type);
  1328. return true;
  1329. }
  1330. }
  1331. if (!strcmp(key, "id")) {
  1332. if (node->id && value) free(node->id);
  1333. node->id = _copyId(value);
  1334. } else if (!strcmp(key, "class")) {
  1335. _handleCssClassAttr(loader, node, value);
  1336. } else if (!strcmp(key, "style")) {
  1337. return simpleXmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
  1338. } else if (!strcmp(key, "clip-path")) {
  1339. _handleClipPathAttr(loader, node, value);
  1340. } else if (!strcmp(key, "mask")) {
  1341. _handleMaskAttr(loader, node, value);
  1342. } else {
  1343. return _parseStyleAttr(loader, key, value, false);
  1344. }
  1345. return true;
  1346. }
  1347. static SvgNode* _createEllipseNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
  1348. {
  1349. loader->svgParse->node = _createNode(parent, SvgNodeType::Ellipse);
  1350. if (!loader->svgParse->node) return nullptr;
  1351. func(buf, bufLength, _attrParseEllipseNode, loader);
  1352. return loader->svgParse->node;
  1353. }
  1354. static bool _attrParsePolygonPoints(const char* str, SvgPolygonNode* polygon)
  1355. {
  1356. float num;
  1357. while (_parseNumber(&str, &num)) polygon->pts.push(num);
  1358. return true;
  1359. }
  1360. /* parse the attributes for a polygon element.
  1361. * https://www.w3.org/TR/SVG/shapes.html#PolylineElement
  1362. */
  1363. static bool _attrParsePolygonNode(void* data, const char* key, const char* value)
  1364. {
  1365. SvgLoaderData* loader = (SvgLoaderData*)data;
  1366. SvgNode* node = loader->svgParse->node;
  1367. SvgPolygonNode* polygon = nullptr;
  1368. if (node->type == SvgNodeType::Polygon) polygon = &(node->node.polygon);
  1369. else polygon = &(node->node.polyline);
  1370. if (!strcmp(key, "points")) {
  1371. return _attrParsePolygonPoints(value, polygon);
  1372. } else if (!strcmp(key, "style")) {
  1373. return simpleXmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
  1374. } else if (!strcmp(key, "clip-path")) {
  1375. _handleClipPathAttr(loader, node, value);
  1376. } else if (!strcmp(key, "mask")) {
  1377. _handleMaskAttr(loader, node, value);
  1378. } else if (!strcmp(key, "id")) {
  1379. if (node->id && value) free(node->id);
  1380. node->id = _copyId(value);
  1381. } else if (!strcmp(key, "class")) {
  1382. _handleCssClassAttr(loader, node, value);
  1383. } else {
  1384. return _parseStyleAttr(loader, key, value, false);
  1385. }
  1386. return true;
  1387. }
  1388. static SvgNode* _createPolygonNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
  1389. {
  1390. loader->svgParse->node = _createNode(parent, SvgNodeType::Polygon);
  1391. if (!loader->svgParse->node) return nullptr;
  1392. func(buf, bufLength, _attrParsePolygonNode, loader);
  1393. return loader->svgParse->node;
  1394. }
  1395. static SvgNode* _createPolylineNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
  1396. {
  1397. loader->svgParse->node = _createNode(parent, SvgNodeType::Polyline);
  1398. if (!loader->svgParse->node) return nullptr;
  1399. func(buf, bufLength, _attrParsePolygonNode, loader);
  1400. return loader->svgParse->node;
  1401. }
  1402. static constexpr struct
  1403. {
  1404. const char* tag;
  1405. SvgParserLengthType type;
  1406. int sz;
  1407. size_t offset;
  1408. } rectTags[] = {
  1409. {"x", SvgParserLengthType::Horizontal, sizeof("x"), offsetof(SvgRectNode, x)},
  1410. {"y", SvgParserLengthType::Vertical, sizeof("y"), offsetof(SvgRectNode, y)},
  1411. {"width", SvgParserLengthType::Horizontal, sizeof("width"), offsetof(SvgRectNode, w)},
  1412. {"height", SvgParserLengthType::Vertical, sizeof("height"), offsetof(SvgRectNode, h)},
  1413. {"rx", SvgParserLengthType::Horizontal, sizeof("rx"), offsetof(SvgRectNode, rx)},
  1414. {"ry", SvgParserLengthType::Vertical, sizeof("ry"), offsetof(SvgRectNode, ry)}
  1415. };
  1416. /* parse the attributes for a rect element.
  1417. * https://www.w3.org/TR/SVG/shapes.html#RectElement
  1418. */
  1419. static bool _attrParseRectNode(void* data, const char* key, const char* value)
  1420. {
  1421. SvgLoaderData* loader = (SvgLoaderData*)data;
  1422. SvgNode* node = loader->svgParse->node;
  1423. SvgRectNode* rect = &(node->node.rect);
  1424. unsigned char* array;
  1425. bool ret = true;
  1426. int sz = strlen(key);
  1427. array = (unsigned char*)rect;
  1428. for (unsigned int i = 0; i < sizeof(rectTags) / sizeof(rectTags[0]); i++) {
  1429. if (rectTags[i].sz - 1 == sz && !strncmp(rectTags[i].tag, key, sz)) {
  1430. *((float*)(array + rectTags[i].offset)) = _toFloat(loader->svgParse, value, rectTags[i].type);
  1431. //Case if only rx or ry is declared
  1432. if (!strncmp(rectTags[i].tag, "rx", sz)) rect->hasRx = true;
  1433. if (!strncmp(rectTags[i].tag, "ry", sz)) rect->hasRy = true;
  1434. if ((rect->rx >= FLT_EPSILON) && (rect->ry < FLT_EPSILON) && rect->hasRx && !rect->hasRy) rect->ry = rect->rx;
  1435. if ((rect->ry >= FLT_EPSILON) && (rect->rx < FLT_EPSILON) && !rect->hasRx && rect->hasRy) rect->rx = rect->ry;
  1436. return ret;
  1437. }
  1438. }
  1439. if (!strcmp(key, "id")) {
  1440. if (node->id && value) free(node->id);
  1441. node->id = _copyId(value);
  1442. } else if (!strcmp(key, "class")) {
  1443. _handleCssClassAttr(loader, node, value);
  1444. } else if (!strcmp(key, "style")) {
  1445. ret = simpleXmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
  1446. } else if (!strcmp(key, "clip-path")) {
  1447. _handleClipPathAttr(loader, node, value);
  1448. } else if (!strcmp(key, "mask")) {
  1449. _handleMaskAttr(loader, node, value);
  1450. } else {
  1451. ret = _parseStyleAttr(loader, key, value, false);
  1452. }
  1453. return ret;
  1454. }
  1455. static SvgNode* _createRectNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
  1456. {
  1457. loader->svgParse->node = _createNode(parent, SvgNodeType::Rect);
  1458. if (!loader->svgParse->node) return nullptr;
  1459. loader->svgParse->node->node.rect.hasRx = loader->svgParse->node->node.rect.hasRy = false;
  1460. func(buf, bufLength, _attrParseRectNode, loader);
  1461. return loader->svgParse->node;
  1462. }
  1463. static constexpr struct
  1464. {
  1465. const char* tag;
  1466. SvgParserLengthType type;
  1467. int sz;
  1468. size_t offset;
  1469. } lineTags[] = {
  1470. {"x1", SvgParserLengthType::Horizontal, sizeof("x1"), offsetof(SvgLineNode, x1)},
  1471. {"y1", SvgParserLengthType::Vertical, sizeof("y1"), offsetof(SvgLineNode, y1)},
  1472. {"x2", SvgParserLengthType::Horizontal, sizeof("x2"), offsetof(SvgLineNode, x2)},
  1473. {"y2", SvgParserLengthType::Vertical, sizeof("y2"), offsetof(SvgLineNode, y2)}
  1474. };
  1475. /* parse the attributes for a line element.
  1476. * https://www.w3.org/TR/SVG/shapes.html#LineElement
  1477. */
  1478. static bool _attrParseLineNode(void* data, const char* key, const char* value)
  1479. {
  1480. SvgLoaderData* loader = (SvgLoaderData*)data;
  1481. SvgNode* node = loader->svgParse->node;
  1482. SvgLineNode* line = &(node->node.line);
  1483. unsigned char* array;
  1484. int sz = strlen(key);
  1485. array = (unsigned char*)line;
  1486. for (unsigned int i = 0; i < sizeof(lineTags) / sizeof(lineTags[0]); i++) {
  1487. if (lineTags[i].sz - 1 == sz && !strncmp(lineTags[i].tag, key, sz)) {
  1488. *((float*)(array + lineTags[i].offset)) = _toFloat(loader->svgParse, value, lineTags[i].type);
  1489. return true;
  1490. }
  1491. }
  1492. if (!strcmp(key, "id")) {
  1493. if (node->id && value) free(node->id);
  1494. node->id = _copyId(value);
  1495. } else if (!strcmp(key, "class")) {
  1496. _handleCssClassAttr(loader, node, value);
  1497. } else if (!strcmp(key, "style")) {
  1498. return simpleXmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
  1499. } else if (!strcmp(key, "clip-path")) {
  1500. _handleClipPathAttr(loader, node, value);
  1501. } else if (!strcmp(key, "mask")) {
  1502. _handleMaskAttr(loader, node, value);
  1503. } else {
  1504. return _parseStyleAttr(loader, key, value, false);
  1505. }
  1506. return true;
  1507. }
  1508. static SvgNode* _createLineNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
  1509. {
  1510. loader->svgParse->node = _createNode(parent, SvgNodeType::Line);
  1511. if (!loader->svgParse->node) return nullptr;
  1512. func(buf, bufLength, _attrParseLineNode, loader);
  1513. return loader->svgParse->node;
  1514. }
  1515. static char* _idFromHref(const char* href)
  1516. {
  1517. href = _skipSpace(href, nullptr);
  1518. if ((*href) == '#') href++;
  1519. return strdup(href);
  1520. }
  1521. static constexpr struct
  1522. {
  1523. const char* tag;
  1524. SvgParserLengthType type;
  1525. int sz;
  1526. size_t offset;
  1527. } imageTags[] = {
  1528. {"x", SvgParserLengthType::Horizontal, sizeof("x"), offsetof(SvgRectNode, x)},
  1529. {"y", SvgParserLengthType::Vertical, sizeof("y"), offsetof(SvgRectNode, y)},
  1530. {"width", SvgParserLengthType::Horizontal, sizeof("width"), offsetof(SvgRectNode, w)},
  1531. {"height", SvgParserLengthType::Vertical, sizeof("height"), offsetof(SvgRectNode, h)},
  1532. };
  1533. /* parse the attributes for a image element.
  1534. * https://www.w3.org/TR/SVG/embedded.html#ImageElement
  1535. */
  1536. static bool _attrParseImageNode(void* data, const char* key, const char* value)
  1537. {
  1538. SvgLoaderData* loader = (SvgLoaderData*)data;
  1539. SvgNode* node = loader->svgParse->node;
  1540. SvgImageNode* image = &(node->node.image);
  1541. unsigned char* array;
  1542. int sz = strlen(key);
  1543. array = (unsigned char*)image;
  1544. for (unsigned int i = 0; i < sizeof(imageTags) / sizeof(imageTags[0]); i++) {
  1545. if (imageTags[i].sz - 1 == sz && !strncmp(imageTags[i].tag, key, sz)) {
  1546. *((float*)(array + imageTags[i].offset)) = _toFloat(loader->svgParse, value, imageTags[i].type);
  1547. return true;
  1548. }
  1549. }
  1550. if (!strcmp(key, "href") || !strcmp(key, "xlink:href")) {
  1551. if (image->href && value) free(image->href);
  1552. image->href = _idFromHref(value);
  1553. } else if (!strcmp(key, "id")) {
  1554. if (node->id && value) free(node->id);
  1555. node->id = _copyId(value);
  1556. } else if (!strcmp(key, "class")) {
  1557. _handleCssClassAttr(loader, node, value);
  1558. } else if (!strcmp(key, "style")) {
  1559. return simpleXmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
  1560. } else if (!strcmp(key, "clip-path")) {
  1561. _handleClipPathAttr(loader, node, value);
  1562. } else if (!strcmp(key, "mask")) {
  1563. _handleMaskAttr(loader, node, value);
  1564. } else if (!strcmp(key, "transform")) {
  1565. node->transform = _parseTransformationMatrix(value);
  1566. } else {
  1567. return _parseStyleAttr(loader, key, value);
  1568. }
  1569. return true;
  1570. }
  1571. static SvgNode* _createImageNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
  1572. {
  1573. loader->svgParse->node = _createNode(parent, SvgNodeType::Image);
  1574. if (!loader->svgParse->node) return nullptr;
  1575. func(buf, bufLength, _attrParseImageNode, loader);
  1576. return loader->svgParse->node;
  1577. }
  1578. static SvgNode* _getDefsNode(SvgNode* node)
  1579. {
  1580. if (!node) return nullptr;
  1581. while (node->parent != nullptr) {
  1582. node = node->parent;
  1583. }
  1584. if (node->type == SvgNodeType::Doc) return node->node.doc.defs;
  1585. if (node->type == SvgNodeType::Defs) return node;
  1586. return nullptr;
  1587. }
  1588. static SvgNode* _findNodeById(SvgNode *node, const char* id)
  1589. {
  1590. if (!node) return nullptr;
  1591. SvgNode* result = nullptr;
  1592. if (node->id && !strcmp(node->id, id)) return node;
  1593. if (node->child.count > 0) {
  1594. auto child = node->child.data;
  1595. for (uint32_t i = 0; i < node->child.count; ++i, ++child) {
  1596. result = _findNodeById(*child, id);
  1597. if (result) break;
  1598. }
  1599. }
  1600. return result;
  1601. }
  1602. static SvgNode* _findParentById(SvgNode* node, char* id, SvgNode* doc)
  1603. {
  1604. SvgNode *parent = node->parent;
  1605. while (parent != nullptr && parent != doc) {
  1606. if (parent->id && !strcmp(parent->id, id)) {
  1607. return parent;
  1608. }
  1609. parent = parent->parent;
  1610. }
  1611. return nullptr;
  1612. }
  1613. static constexpr struct
  1614. {
  1615. const char* tag;
  1616. SvgParserLengthType type;
  1617. int sz;
  1618. size_t offset;
  1619. } useTags[] = {
  1620. {"x", SvgParserLengthType::Horizontal, sizeof("x"), offsetof(SvgUseNode, x)},
  1621. {"y", SvgParserLengthType::Vertical, sizeof("y"), offsetof(SvgUseNode, y)},
  1622. {"width", SvgParserLengthType::Horizontal, sizeof("width"), offsetof(SvgUseNode, w)},
  1623. {"height", SvgParserLengthType::Vertical, sizeof("height"), offsetof(SvgUseNode, h)}
  1624. };
  1625. static void _cloneNode(SvgNode* from, SvgNode* parent, int depth);
  1626. static bool _attrParseUseNode(void* data, const char* key, const char* value)
  1627. {
  1628. SvgLoaderData* loader = (SvgLoaderData*)data;
  1629. SvgNode *defs, *nodeFrom, *node = loader->svgParse->node;
  1630. char* id;
  1631. SvgUseNode* use = &(node->node.use);
  1632. int sz = strlen(key);
  1633. unsigned char* array = (unsigned char*)use;
  1634. for (unsigned int i = 0; i < sizeof(useTags) / sizeof(useTags[0]); i++) {
  1635. if (useTags[i].sz - 1 == sz && !strncmp(useTags[i].tag, key, sz)) {
  1636. *((float*)(array + useTags[i].offset)) = _toFloat(loader->svgParse, value, useTags[i].type);
  1637. if (useTags[i].offset == offsetof(SvgUseNode, w)) use->isWidthSet = true;
  1638. else if (useTags[i].offset == offsetof(SvgUseNode, h)) use->isHeightSet = true;
  1639. return true;
  1640. }
  1641. }
  1642. if (!strcmp(key, "href") || !strcmp(key, "xlink:href")) {
  1643. id = _idFromHref(value);
  1644. defs = _getDefsNode(node);
  1645. nodeFrom = _findNodeById(defs, id);
  1646. if (nodeFrom) {
  1647. if (!_findParentById(node, id, loader->doc)) {
  1648. _cloneNode(nodeFrom, node, 0);
  1649. if (nodeFrom->type == SvgNodeType::Symbol) use->symbol = nodeFrom;
  1650. } else {
  1651. TVGLOG("SVG", "%s is ancestor element. This reference is invalid.", id);
  1652. }
  1653. free(id);
  1654. } else {
  1655. //some svg export software include <defs> element at the end of the file
  1656. //if so the 'from' element won't be found now and we have to repeat finding
  1657. //after the whole file is parsed
  1658. _postpone(loader->cloneNodes, node, id);
  1659. }
  1660. } else {
  1661. return _attrParseGNode(data, key, value);
  1662. }
  1663. return true;
  1664. }
  1665. static SvgNode* _createUseNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
  1666. {
  1667. loader->svgParse->node = _createNode(parent, SvgNodeType::Use);
  1668. if (!loader->svgParse->node) return nullptr;
  1669. loader->svgParse->node->node.use.isWidthSet = false;
  1670. loader->svgParse->node->node.use.isHeightSet = false;
  1671. func(buf, bufLength, _attrParseUseNode, loader);
  1672. return loader->svgParse->node;
  1673. }
  1674. //TODO: Implement 'text' primitive
  1675. static constexpr struct
  1676. {
  1677. const char* tag;
  1678. int sz;
  1679. FactoryMethod tagHandler;
  1680. } graphicsTags[] = {
  1681. {"use", sizeof("use"), _createUseNode},
  1682. {"circle", sizeof("circle"), _createCircleNode},
  1683. {"ellipse", sizeof("ellipse"), _createEllipseNode},
  1684. {"path", sizeof("path"), _createPathNode},
  1685. {"polygon", sizeof("polygon"), _createPolygonNode},
  1686. {"rect", sizeof("rect"), _createRectNode},
  1687. {"polyline", sizeof("polyline"), _createPolylineNode},
  1688. {"line", sizeof("line"), _createLineNode},
  1689. {"image", sizeof("image"), _createImageNode}
  1690. };
  1691. static constexpr struct
  1692. {
  1693. const char* tag;
  1694. int sz;
  1695. FactoryMethod tagHandler;
  1696. } groupTags[] = {
  1697. {"defs", sizeof("defs"), _createDefsNode},
  1698. {"g", sizeof("g"), _createGNode},
  1699. {"svg", sizeof("svg"), _createSvgNode},
  1700. {"mask", sizeof("mask"), _createMaskNode},
  1701. {"clipPath", sizeof("clipPath"), _createClipPathNode},
  1702. {"style", sizeof("style"), _createCssStyleNode},
  1703. {"symbol", sizeof("symbol"), _createSymbolNode}
  1704. };
  1705. #define FIND_FACTORY(Short_Name, Tags_Array) \
  1706. static FactoryMethod \
  1707. _find##Short_Name##Factory(const char* name) \
  1708. { \
  1709. unsigned int i; \
  1710. int sz = strlen(name); \
  1711. \
  1712. for (i = 0; i < sizeof(Tags_Array) / sizeof(Tags_Array[0]); i++) { \
  1713. if (Tags_Array[i].sz - 1 == sz && !strncmp(Tags_Array[i].tag, name, sz)) { \
  1714. return Tags_Array[i].tagHandler; \
  1715. } \
  1716. } \
  1717. return nullptr; \
  1718. }
  1719. FIND_FACTORY(Group, groupTags)
  1720. FIND_FACTORY(Graphics, graphicsTags)
  1721. FillSpread _parseSpreadValue(const char* value)
  1722. {
  1723. auto spread = FillSpread::Pad;
  1724. if (!strcmp(value, "reflect")) {
  1725. spread = FillSpread::Reflect;
  1726. } else if (!strcmp(value, "repeat")) {
  1727. spread = FillSpread::Repeat;
  1728. }
  1729. return spread;
  1730. }
  1731. static void _handleRadialCxAttr(SvgLoaderData* loader, SvgRadialGradient* radial, const char* value)
  1732. {
  1733. radial->cx = _gradientToFloat(loader->svgParse, value, radial->isCxPercentage);
  1734. if (!loader->svgParse->gradient.parsedFx) {
  1735. radial->fx = radial->cx;
  1736. radial->isFxPercentage = radial->isCxPercentage;
  1737. }
  1738. }
  1739. static void _handleRadialCyAttr(SvgLoaderData* loader, SvgRadialGradient* radial, const char* value)
  1740. {
  1741. radial->cy = _gradientToFloat(loader->svgParse, value, radial->isCyPercentage);
  1742. if (!loader->svgParse->gradient.parsedFy) {
  1743. radial->fy = radial->cy;
  1744. radial->isFyPercentage = radial->isCyPercentage;
  1745. }
  1746. }
  1747. static void _handleRadialFxAttr(SvgLoaderData* loader, SvgRadialGradient* radial, const char* value)
  1748. {
  1749. radial->fx = _gradientToFloat(loader->svgParse, value, radial->isFxPercentage);
  1750. loader->svgParse->gradient.parsedFx = true;
  1751. }
  1752. static void _handleRadialFyAttr(SvgLoaderData* loader, SvgRadialGradient* radial, const char* value)
  1753. {
  1754. radial->fy = _gradientToFloat(loader->svgParse, value, radial->isFyPercentage);
  1755. loader->svgParse->gradient.parsedFy = true;
  1756. }
  1757. static void _handleRadialFrAttr(SvgLoaderData* loader, SvgRadialGradient* radial, const char* value)
  1758. {
  1759. radial->fr = _gradientToFloat(loader->svgParse, value, radial->isFrPercentage);
  1760. }
  1761. static void _handleRadialRAttr(SvgLoaderData* loader, SvgRadialGradient* radial, const char* value)
  1762. {
  1763. radial->r = _gradientToFloat(loader->svgParse, value, radial->isRPercentage);
  1764. }
  1765. static void _recalcRadialCxAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
  1766. {
  1767. if (userSpace && !radial->isCxPercentage) radial->cx = radial->cx / loader->svgParse->global.w;
  1768. }
  1769. static void _recalcRadialCyAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
  1770. {
  1771. if (userSpace && !radial->isCyPercentage) radial->cy = radial->cy / loader->svgParse->global.h;
  1772. }
  1773. static void _recalcRadialFxAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
  1774. {
  1775. if (userSpace && !radial->isFxPercentage) radial->fx = radial->fx / loader->svgParse->global.w;
  1776. }
  1777. static void _recalcRadialFyAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
  1778. {
  1779. if (userSpace && !radial->isFyPercentage) radial->fy = radial->fy / loader->svgParse->global.h;
  1780. }
  1781. static void _recalcRadialFrAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
  1782. {
  1783. // scaling factor based on the Units paragraph from : https://www.w3.org/TR/2015/WD-SVG2-20150915/coords.html
  1784. if (userSpace && !radial->isFrPercentage) radial->fr = radial->fr / (sqrtf(powf(loader->svgParse->global.h, 2) + powf(loader->svgParse->global.w, 2)) / sqrtf(2.0));
  1785. }
  1786. static void _recalcRadialRAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
  1787. {
  1788. // scaling factor based on the Units paragraph from : https://www.w3.org/TR/2015/WD-SVG2-20150915/coords.html
  1789. if (userSpace && !radial->isRPercentage) radial->r = radial->r / (sqrtf(powf(loader->svgParse->global.h, 2) + powf(loader->svgParse->global.w, 2)) / sqrtf(2.0));
  1790. }
  1791. static void _recalcInheritedRadialCxAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
  1792. {
  1793. if (!radial->isCxPercentage) {
  1794. if (userSpace) radial->cx /= loader->svgParse->global.w;
  1795. else radial->cx *= loader->svgParse->global.w;
  1796. }
  1797. }
  1798. static void _recalcInheritedRadialCyAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
  1799. {
  1800. if (!radial->isCyPercentage) {
  1801. if (userSpace) radial->cy /= loader->svgParse->global.h;
  1802. else radial->cy *= loader->svgParse->global.h;
  1803. }
  1804. }
  1805. static void _recalcInheritedRadialFxAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
  1806. {
  1807. if (!radial->isFxPercentage) {
  1808. if (userSpace) radial->fx /= loader->svgParse->global.w;
  1809. else radial->fx *= loader->svgParse->global.w;
  1810. }
  1811. }
  1812. static void _recalcInheritedRadialFyAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
  1813. {
  1814. if (!radial->isFyPercentage) {
  1815. if (userSpace) radial->fy /= loader->svgParse->global.h;
  1816. else radial->fy *= loader->svgParse->global.h;
  1817. }
  1818. }
  1819. static void _recalcInheritedRadialFrAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
  1820. {
  1821. if (!radial->isFrPercentage) {
  1822. if (userSpace) radial->fr /= sqrtf(powf(loader->svgParse->global.h, 2) + powf(loader->svgParse->global.w, 2)) / sqrtf(2.0);
  1823. else radial->fr *= sqrtf(powf(loader->svgParse->global.h, 2) + powf(loader->svgParse->global.w, 2)) / sqrtf(2.0);
  1824. }
  1825. }
  1826. static void _recalcInheritedRadialRAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
  1827. {
  1828. if (!radial->isRPercentage) {
  1829. if (userSpace) radial->r /= sqrtf(powf(loader->svgParse->global.h, 2) + powf(loader->svgParse->global.w, 2)) / sqrtf(2.0);
  1830. else radial->r *= sqrtf(powf(loader->svgParse->global.h, 2) + powf(loader->svgParse->global.w, 2)) / sqrtf(2.0);
  1831. }
  1832. }
  1833. static void _inheritRadialCxAttr(SvgStyleGradient* to, SvgStyleGradient* from)
  1834. {
  1835. to->radial->cx = from->radial->cx;
  1836. to->radial->isCxPercentage = from->radial->isCxPercentage;
  1837. to->flags = (to->flags | SvgGradientFlags::Cx);
  1838. }
  1839. static void _inheritRadialCyAttr(SvgStyleGradient* to, SvgStyleGradient* from)
  1840. {
  1841. to->radial->cy = from->radial->cy;
  1842. to->radial->isCyPercentage = from->radial->isCyPercentage;
  1843. to->flags = (to->flags | SvgGradientFlags::Cy);
  1844. }
  1845. static void _inheritRadialFxAttr(SvgStyleGradient* to, SvgStyleGradient* from)
  1846. {
  1847. to->radial->fx = from->radial->fx;
  1848. to->radial->isFxPercentage = from->radial->isFxPercentage;
  1849. to->flags = (to->flags | SvgGradientFlags::Fx);
  1850. }
  1851. static void _inheritRadialFyAttr(SvgStyleGradient* to, SvgStyleGradient* from)
  1852. {
  1853. to->radial->fy = from->radial->fy;
  1854. to->radial->isFyPercentage = from->radial->isFyPercentage;
  1855. to->flags = (to->flags | SvgGradientFlags::Fy);
  1856. }
  1857. static void _inheritRadialFrAttr(SvgStyleGradient* to, SvgStyleGradient* from)
  1858. {
  1859. to->radial->fr = from->radial->fr;
  1860. to->radial->isFrPercentage = from->radial->isFrPercentage;
  1861. to->flags = (to->flags | SvgGradientFlags::Fr);
  1862. }
  1863. static void _inheritRadialRAttr(SvgStyleGradient* to, SvgStyleGradient* from)
  1864. {
  1865. to->radial->r = from->radial->r;
  1866. to->radial->isRPercentage = from->radial->isRPercentage;
  1867. to->flags = (to->flags | SvgGradientFlags::R);
  1868. }
  1869. typedef void (*radialMethod)(SvgLoaderData* loader, SvgRadialGradient* radial, const char* value);
  1870. typedef void (*radialInheritMethod)(SvgStyleGradient* to, SvgStyleGradient* from);
  1871. typedef void (*radialMethodRecalc)(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace);
  1872. #define RADIAL_DEF(Name, Name1, Flag) \
  1873. { \
  1874. #Name, sizeof(#Name), _handleRadial##Name1##Attr, _inheritRadial##Name1##Attr, _recalcRadial##Name1##Attr, _recalcInheritedRadial##Name1##Attr, Flag \
  1875. }
  1876. static constexpr struct
  1877. {
  1878. const char* tag;
  1879. int sz;
  1880. radialMethod tagHandler;
  1881. radialInheritMethod tagInheritHandler;
  1882. radialMethodRecalc tagRecalc;
  1883. radialMethodRecalc tagInheritedRecalc;
  1884. SvgGradientFlags flag;
  1885. } radialTags[] = {
  1886. RADIAL_DEF(cx, Cx, SvgGradientFlags::Cx),
  1887. RADIAL_DEF(cy, Cy, SvgGradientFlags::Cy),
  1888. RADIAL_DEF(fx, Fx, SvgGradientFlags::Fx),
  1889. RADIAL_DEF(fy, Fy, SvgGradientFlags::Fy),
  1890. RADIAL_DEF(r, R, SvgGradientFlags::R),
  1891. RADIAL_DEF(fr, Fr, SvgGradientFlags::Fr)
  1892. };
  1893. static bool _attrParseRadialGradientNode(void* data, const char* key, const char* value)
  1894. {
  1895. SvgLoaderData* loader = (SvgLoaderData*)data;
  1896. SvgStyleGradient* grad = loader->svgParse->styleGrad;
  1897. SvgRadialGradient* radial = grad->radial;
  1898. int sz = strlen(key);
  1899. for (unsigned int i = 0; i < sizeof(radialTags) / sizeof(radialTags[0]); i++) {
  1900. if (radialTags[i].sz - 1 == sz && !strncmp(radialTags[i].tag, key, sz)) {
  1901. radialTags[i].tagHandler(loader, radial, value);
  1902. grad->flags = (grad->flags | radialTags[i].flag);
  1903. return true;
  1904. }
  1905. }
  1906. if (!strcmp(key, "id")) {
  1907. if (grad->id && value) free(grad->id);
  1908. grad->id = _copyId(value);
  1909. } else if (!strcmp(key, "spreadMethod")) {
  1910. grad->spread = _parseSpreadValue(value);
  1911. grad->flags = (grad->flags | SvgGradientFlags::SpreadMethod);
  1912. } else if (!strcmp(key, "href") || !strcmp(key, "xlink:href")) {
  1913. if (grad->ref && value) free(grad->ref);
  1914. grad->ref = _idFromHref(value);
  1915. } else if (!strcmp(key, "gradientUnits")) {
  1916. if (!strcmp(value, "userSpaceOnUse")) grad->userSpace = true;
  1917. grad->flags = (grad->flags | SvgGradientFlags::GradientUnits);
  1918. } else if (!strcmp(key, "gradientTransform")) {
  1919. grad->transform = _parseTransformationMatrix(value);
  1920. } else {
  1921. return false;
  1922. }
  1923. return true;
  1924. }
  1925. static SvgStyleGradient* _createRadialGradient(SvgLoaderData* loader, const char* buf, unsigned bufLength)
  1926. {
  1927. auto grad = (SvgStyleGradient*)(calloc(1, sizeof(SvgStyleGradient)));
  1928. loader->svgParse->styleGrad = grad;
  1929. grad->flags = SvgGradientFlags::None;
  1930. grad->type = SvgGradientType::Radial;
  1931. grad->userSpace = false;
  1932. grad->radial = (SvgRadialGradient*)calloc(1, sizeof(SvgRadialGradient));
  1933. if (!grad->radial) {
  1934. grad->clear();
  1935. free(grad);
  1936. return nullptr;
  1937. }
  1938. /**
  1939. * Default values of gradient transformed into global percentage
  1940. */
  1941. grad->radial->cx = 0.5f;
  1942. grad->radial->cy = 0.5f;
  1943. grad->radial->fx = 0.5f;
  1944. grad->radial->fy = 0.5f;
  1945. grad->radial->r = 0.5f;
  1946. grad->radial->isCxPercentage = true;
  1947. grad->radial->isCyPercentage = true;
  1948. grad->radial->isFxPercentage = true;
  1949. grad->radial->isFyPercentage = true;
  1950. grad->radial->isRPercentage = true;
  1951. grad->radial->isFrPercentage = true;
  1952. loader->svgParse->gradient.parsedFx = false;
  1953. loader->svgParse->gradient.parsedFy = false;
  1954. simpleXmlParseAttributes(buf, bufLength,
  1955. _attrParseRadialGradientNode, loader);
  1956. for (unsigned int i = 0; i < sizeof(radialTags) / sizeof(radialTags[0]); i++) {
  1957. radialTags[i].tagRecalc(loader, grad->radial, grad->userSpace);
  1958. }
  1959. return loader->svgParse->styleGrad;
  1960. }
  1961. static bool _attrParseStopsStyle(void* data, const char* key, const char* value)
  1962. {
  1963. SvgLoaderData* loader = (SvgLoaderData*)data;
  1964. auto stop = &loader->svgParse->gradStop;
  1965. if (!strcmp(key, "stop-opacity")) {
  1966. stop->a = _toOpacity(value);
  1967. loader->svgParse->flags = (loader->svgParse->flags | SvgStopStyleFlags::StopOpacity);
  1968. } else if (!strcmp(key, "stop-color")) {
  1969. _toColor(value, &stop->r, &stop->g, &stop->b, nullptr);
  1970. loader->svgParse->flags = (loader->svgParse->flags | SvgStopStyleFlags::StopColor);
  1971. } else {
  1972. return false;
  1973. }
  1974. return true;
  1975. }
  1976. static bool _attrParseStops(void* data, const char* key, const char* value)
  1977. {
  1978. SvgLoaderData* loader = (SvgLoaderData*)data;
  1979. auto stop = &loader->svgParse->gradStop;
  1980. if (!strcmp(key, "offset")) {
  1981. stop->offset = _toOffset(value);
  1982. } else if (!strcmp(key, "stop-opacity")) {
  1983. if (!(loader->svgParse->flags & SvgStopStyleFlags::StopOpacity)) {
  1984. stop->a = _toOpacity(value);
  1985. }
  1986. } else if (!strcmp(key, "stop-color")) {
  1987. if (!(loader->svgParse->flags & SvgStopStyleFlags::StopColor)) {
  1988. _toColor(value, &stop->r, &stop->g, &stop->b, nullptr);
  1989. }
  1990. } else if (!strcmp(key, "style")) {
  1991. simpleXmlParseW3CAttribute(value, strlen(value), _attrParseStopsStyle, data);
  1992. } else {
  1993. return false;
  1994. }
  1995. return true;
  1996. }
  1997. static void _handleLinearX1Attr(SvgLoaderData* loader, SvgLinearGradient* linear, const char* value)
  1998. {
  1999. linear->x1 = _gradientToFloat(loader->svgParse, value, linear->isX1Percentage);
  2000. }
  2001. static void _handleLinearY1Attr(SvgLoaderData* loader, SvgLinearGradient* linear, const char* value)
  2002. {
  2003. linear->y1 = _gradientToFloat(loader->svgParse, value, linear->isY1Percentage);
  2004. }
  2005. static void _handleLinearX2Attr(SvgLoaderData* loader, SvgLinearGradient* linear, const char* value)
  2006. {
  2007. linear->x2 = _gradientToFloat(loader->svgParse, value, linear->isX2Percentage);
  2008. }
  2009. static void _handleLinearY2Attr(SvgLoaderData* loader, SvgLinearGradient* linear, const char* value)
  2010. {
  2011. linear->y2 = _gradientToFloat(loader->svgParse, value, linear->isY2Percentage);
  2012. }
  2013. static void _recalcLinearX1Attr(SvgLoaderData* loader, SvgLinearGradient* linear, bool userSpace)
  2014. {
  2015. if (userSpace && !linear->isX1Percentage) linear->x1 = linear->x1 / loader->svgParse->global.w;
  2016. }
  2017. static void _recalcLinearY1Attr(SvgLoaderData* loader, SvgLinearGradient* linear, bool userSpace)
  2018. {
  2019. if (userSpace && !linear->isY1Percentage) linear->y1 = linear->y1 / loader->svgParse->global.h;
  2020. }
  2021. static void _recalcLinearX2Attr(SvgLoaderData* loader, SvgLinearGradient* linear, bool userSpace)
  2022. {
  2023. if (userSpace && !linear->isX2Percentage) linear->x2 = linear->x2 / loader->svgParse->global.w;
  2024. }
  2025. static void _recalcLinearY2Attr(SvgLoaderData* loader, SvgLinearGradient* linear, bool userSpace)
  2026. {
  2027. if (userSpace && !linear->isY2Percentage) linear->y2 = linear->y2 / loader->svgParse->global.h;
  2028. }
  2029. static void _recalcInheritedLinearX1Attr(SvgLoaderData* loader, SvgLinearGradient* linear, bool userSpace)
  2030. {
  2031. if (!linear->isX1Percentage) {
  2032. if (userSpace) linear->x1 /= loader->svgParse->global.w;
  2033. else linear->x1 *= loader->svgParse->global.w;
  2034. }
  2035. }
  2036. static void _recalcInheritedLinearX2Attr(SvgLoaderData* loader, SvgLinearGradient* linear, bool userSpace)
  2037. {
  2038. if (!linear->isX2Percentage) {
  2039. if (userSpace) linear->x2 /= loader->svgParse->global.w;
  2040. else linear->x2 *= loader->svgParse->global.w;
  2041. }
  2042. }
  2043. static void _recalcInheritedLinearY1Attr(SvgLoaderData* loader, SvgLinearGradient* linear, bool userSpace)
  2044. {
  2045. if (!linear->isY1Percentage) {
  2046. if (userSpace) linear->y1 /= loader->svgParse->global.h;
  2047. else linear->y1 *= loader->svgParse->global.h;
  2048. }
  2049. }
  2050. static void _recalcInheritedLinearY2Attr(SvgLoaderData* loader, SvgLinearGradient* linear, bool userSpace)
  2051. {
  2052. if (!linear->isY2Percentage) {
  2053. if (userSpace) linear->y2 /= loader->svgParse->global.h;
  2054. else linear->y2 *= loader->svgParse->global.h;
  2055. }
  2056. }
  2057. static void _inheritLinearX1Attr(SvgStyleGradient* to, SvgStyleGradient* from)
  2058. {
  2059. to->linear->x1 = from->linear->x1;
  2060. to->linear->isX1Percentage = from->linear->isX1Percentage;
  2061. to->flags = (to->flags | SvgGradientFlags::X1);
  2062. }
  2063. static void _inheritLinearX2Attr(SvgStyleGradient* to, SvgStyleGradient* from)
  2064. {
  2065. to->linear->x2 = from->linear->x2;
  2066. to->linear->isX2Percentage = from->linear->isX2Percentage;
  2067. to->flags = (to->flags | SvgGradientFlags::X2);
  2068. }
  2069. static void _inheritLinearY1Attr(SvgStyleGradient* to, SvgStyleGradient* from)
  2070. {
  2071. to->linear->y1 = from->linear->y1;
  2072. to->linear->isY1Percentage = from->linear->isY1Percentage;
  2073. to->flags = (to->flags | SvgGradientFlags::Y1);
  2074. }
  2075. static void _inheritLinearY2Attr(SvgStyleGradient* to, SvgStyleGradient* from)
  2076. {
  2077. to->linear->y2 = from->linear->y2;
  2078. to->linear->isY2Percentage = from->linear->isY2Percentage;
  2079. to->flags = (to->flags | SvgGradientFlags::Y2);
  2080. }
  2081. typedef void (*Linear_Method)(SvgLoaderData* loader, SvgLinearGradient* linear, const char* value);
  2082. typedef void (*Linear_Inherit_Method)(SvgStyleGradient* to, SvgStyleGradient* from);
  2083. typedef void (*Linear_Method_Recalc)(SvgLoaderData* loader, SvgLinearGradient* linear, bool userSpace);
  2084. #define LINEAR_DEF(Name, Name1, Flag) \
  2085. { \
  2086. #Name, sizeof(#Name), _handleLinear##Name1##Attr, _inheritLinear##Name1##Attr, _recalcLinear##Name1##Attr, _recalcInheritedLinear##Name1##Attr, Flag \
  2087. }
  2088. static constexpr struct
  2089. {
  2090. const char* tag;
  2091. int sz;
  2092. Linear_Method tagHandler;
  2093. Linear_Inherit_Method tagInheritHandler;
  2094. Linear_Method_Recalc tagRecalc;
  2095. Linear_Method_Recalc tagInheritedRecalc;
  2096. SvgGradientFlags flag;
  2097. } linear_tags[] = {
  2098. LINEAR_DEF(x1, X1, SvgGradientFlags::X1),
  2099. LINEAR_DEF(y1, Y1, SvgGradientFlags::Y1),
  2100. LINEAR_DEF(x2, X2, SvgGradientFlags::X2),
  2101. LINEAR_DEF(y2, Y2, SvgGradientFlags::Y2)
  2102. };
  2103. static bool _attrParseLinearGradientNode(void* data, const char* key, const char* value)
  2104. {
  2105. SvgLoaderData* loader = (SvgLoaderData*)data;
  2106. SvgStyleGradient* grad = loader->svgParse->styleGrad;
  2107. SvgLinearGradient* linear = grad->linear;
  2108. int sz = strlen(key);
  2109. for (unsigned int i = 0; i < sizeof(linear_tags) / sizeof(linear_tags[0]); i++) {
  2110. if (linear_tags[i].sz - 1 == sz && !strncmp(linear_tags[i].tag, key, sz)) {
  2111. linear_tags[i].tagHandler(loader, linear, value);
  2112. grad->flags = (grad->flags | linear_tags[i].flag);
  2113. return true;
  2114. }
  2115. }
  2116. if (!strcmp(key, "id")) {
  2117. if (grad->id && value) free(grad->id);
  2118. grad->id = _copyId(value);
  2119. } else if (!strcmp(key, "spreadMethod")) {
  2120. grad->spread = _parseSpreadValue(value);
  2121. grad->flags = (grad->flags | SvgGradientFlags::SpreadMethod);
  2122. } else if (!strcmp(key, "href") || !strcmp(key, "xlink:href")) {
  2123. if (grad->ref && value) free(grad->ref);
  2124. grad->ref = _idFromHref(value);
  2125. } else if (!strcmp(key, "gradientUnits")) {
  2126. if (!strcmp(value, "userSpaceOnUse")) grad->userSpace = true;
  2127. grad->flags = (grad->flags | SvgGradientFlags::GradientUnits);
  2128. } else if (!strcmp(key, "gradientTransform")) {
  2129. grad->transform = _parseTransformationMatrix(value);
  2130. } else {
  2131. return false;
  2132. }
  2133. return true;
  2134. }
  2135. static SvgStyleGradient* _createLinearGradient(SvgLoaderData* loader, const char* buf, unsigned bufLength)
  2136. {
  2137. auto grad = (SvgStyleGradient*)(calloc(1, sizeof(SvgStyleGradient)));
  2138. loader->svgParse->styleGrad = grad;
  2139. grad->flags = SvgGradientFlags::None;
  2140. grad->type = SvgGradientType::Linear;
  2141. grad->userSpace = false;
  2142. grad->linear = (SvgLinearGradient*)calloc(1, sizeof(SvgLinearGradient));
  2143. if (!grad->linear) {
  2144. grad->clear();
  2145. free(grad);
  2146. return nullptr;
  2147. }
  2148. /**
  2149. * Default value of x2 is 100% - transformed to the global percentage
  2150. */
  2151. grad->linear->x2 = 1.0f;
  2152. grad->linear->isX2Percentage = true;
  2153. simpleXmlParseAttributes(buf, bufLength, _attrParseLinearGradientNode, loader);
  2154. for (unsigned int i = 0; i < sizeof(linear_tags) / sizeof(linear_tags[0]); i++) {
  2155. linear_tags[i].tagRecalc(loader, grad->linear, grad->userSpace);
  2156. }
  2157. return loader->svgParse->styleGrad;
  2158. }
  2159. #define GRADIENT_DEF(Name, Name1) \
  2160. { \
  2161. #Name, sizeof(#Name), _create##Name1 \
  2162. }
  2163. /**
  2164. * In the case when the gradients lengths are given as numbers (not percentages)
  2165. * in the current user coordinate system, they are recalculated into percentages
  2166. * related to the canvas width and height.
  2167. */
  2168. static constexpr struct
  2169. {
  2170. const char* tag;
  2171. int sz;
  2172. GradientFactoryMethod tagHandler;
  2173. } gradientTags[] = {
  2174. GRADIENT_DEF(linearGradient, LinearGradient),
  2175. GRADIENT_DEF(radialGradient, RadialGradient)
  2176. };
  2177. static GradientFactoryMethod _findGradientFactory(const char* name)
  2178. {
  2179. int sz = strlen(name);
  2180. for (unsigned int i = 0; i < sizeof(gradientTags) / sizeof(gradientTags[0]); i++) {
  2181. if (gradientTags[i].sz - 1 == sz && !strncmp(gradientTags[i].tag, name, sz)) {
  2182. return gradientTags[i].tagHandler;
  2183. }
  2184. }
  2185. return nullptr;
  2186. }
  2187. static void _cloneGradStops(Array<Fill::ColorStop>& dst, const Array<Fill::ColorStop>& src)
  2188. {
  2189. for (uint32_t i = 0; i < src.count; ++i) {
  2190. dst.push(src[i]);
  2191. }
  2192. }
  2193. static void _inheritGradient(SvgLoaderData* loader, SvgStyleGradient* to, SvgStyleGradient* from)
  2194. {
  2195. if (!to || !from) return;
  2196. if (!(to->flags & SvgGradientFlags::SpreadMethod) && (from->flags & SvgGradientFlags::SpreadMethod)) {
  2197. to->spread = from->spread;
  2198. to->flags = (to->flags | SvgGradientFlags::SpreadMethod);
  2199. }
  2200. bool gradUnitSet = (to->flags & SvgGradientFlags::GradientUnits);
  2201. if (!(to->flags & SvgGradientFlags::GradientUnits) && (from->flags & SvgGradientFlags::GradientUnits)) {
  2202. to->userSpace = from->userSpace;
  2203. to->flags = (to->flags | SvgGradientFlags::GradientUnits);
  2204. }
  2205. if (!to->transform && from->transform) {
  2206. to->transform = (Matrix*)malloc(sizeof(Matrix));
  2207. if (to->transform) memcpy(to->transform, from->transform, sizeof(Matrix));
  2208. }
  2209. if (to->type == SvgGradientType::Linear) {
  2210. for (unsigned int i = 0; i < sizeof(linear_tags) / sizeof(linear_tags[0]); i++) {
  2211. bool coordSet = to->flags & linear_tags[i].flag;
  2212. if (!(to->flags & linear_tags[i].flag) && (from->flags & linear_tags[i].flag)) {
  2213. linear_tags[i].tagInheritHandler(to, from);
  2214. }
  2215. //GradUnits not set directly, coord set
  2216. if (!gradUnitSet && coordSet) {
  2217. linear_tags[i].tagRecalc(loader, to->linear, to->userSpace);
  2218. }
  2219. //GradUnits set, coord not set directly
  2220. if (to->userSpace == from->userSpace) continue;
  2221. if (gradUnitSet && !coordSet) {
  2222. linear_tags[i].tagInheritedRecalc(loader, to->linear, to->userSpace);
  2223. }
  2224. }
  2225. } else if (to->type == SvgGradientType::Radial) {
  2226. for (unsigned int i = 0; i < sizeof(radialTags) / sizeof(radialTags[0]); i++) {
  2227. bool coordSet = (to->flags & radialTags[i].flag);
  2228. if (!(to->flags & radialTags[i].flag) && (from->flags & radialTags[i].flag)) {
  2229. radialTags[i].tagInheritHandler(to, from);
  2230. }
  2231. //GradUnits not set directly, coord set
  2232. if (!gradUnitSet && coordSet) {
  2233. radialTags[i].tagRecalc(loader, to->radial, to->userSpace);
  2234. //If fx and fy are not set, set cx and cy.
  2235. if (!strcmp(radialTags[i].tag, "cx") && !(to->flags & SvgGradientFlags::Fx)) to->radial->fx = to->radial->cx;
  2236. if (!strcmp(radialTags[i].tag, "cy") && !(to->flags & SvgGradientFlags::Fy)) to->radial->fy = to->radial->cy;
  2237. }
  2238. //GradUnits set, coord not set directly
  2239. if (to->userSpace == from->userSpace) continue;
  2240. if (gradUnitSet && !coordSet) {
  2241. //If fx and fx are not set, do not call recalc.
  2242. if (!strcmp(radialTags[i].tag, "fx") && !(to->flags & SvgGradientFlags::Fx)) continue;
  2243. if (!strcmp(radialTags[i].tag, "fy") && !(to->flags & SvgGradientFlags::Fy)) continue;
  2244. radialTags[i].tagInheritedRecalc(loader, to->radial, to->userSpace);
  2245. }
  2246. }
  2247. }
  2248. if (to->stops.empty()) _cloneGradStops(to->stops, from->stops);
  2249. }
  2250. static SvgStyleGradient* _cloneGradient(SvgStyleGradient* from)
  2251. {
  2252. if (!from) return nullptr;
  2253. auto grad = (SvgStyleGradient*)(calloc(1, sizeof(SvgStyleGradient)));
  2254. if (!grad) return nullptr;
  2255. grad->type = from->type;
  2256. grad->id = from->id ? _copyId(from->id) : nullptr;
  2257. grad->ref = from->ref ? _copyId(from->ref) : nullptr;
  2258. grad->spread = from->spread;
  2259. grad->userSpace = from->userSpace;
  2260. grad->flags = from->flags;
  2261. if (from->transform) {
  2262. grad->transform = (Matrix*)calloc(1, sizeof(Matrix));
  2263. if (grad->transform) memcpy(grad->transform, from->transform, sizeof(Matrix));
  2264. }
  2265. if (grad->type == SvgGradientType::Linear) {
  2266. grad->linear = (SvgLinearGradient*)calloc(1, sizeof(SvgLinearGradient));
  2267. if (!grad->linear) goto error_grad_alloc;
  2268. memcpy(grad->linear, from->linear, sizeof(SvgLinearGradient));
  2269. } else if (grad->type == SvgGradientType::Radial) {
  2270. grad->radial = (SvgRadialGradient*)calloc(1, sizeof(SvgRadialGradient));
  2271. if (!grad->radial) goto error_grad_alloc;
  2272. memcpy(grad->radial, from->radial, sizeof(SvgRadialGradient));
  2273. }
  2274. _cloneGradStops(grad->stops, from->stops);
  2275. return grad;
  2276. error_grad_alloc:
  2277. if (grad) {
  2278. grad->clear();
  2279. free(grad);
  2280. }
  2281. return nullptr;
  2282. }
  2283. static void _styleInherit(SvgStyleProperty* child, const SvgStyleProperty* parent)
  2284. {
  2285. if (parent == nullptr) return;
  2286. //Inherit the property of parent if not present in child.
  2287. if (!child->curColorSet) {
  2288. child->color = parent->color;
  2289. child->curColorSet = parent->curColorSet;
  2290. }
  2291. if (!(child->flags & SvgStyleFlags::PaintOrder)) {
  2292. child->paintOrder = parent->paintOrder;
  2293. }
  2294. //Fill
  2295. if (!(child->fill.flags & SvgFillFlags::Paint)) {
  2296. child->fill.paint.color = parent->fill.paint.color;
  2297. child->fill.paint.none = parent->fill.paint.none;
  2298. child->fill.paint.curColor = parent->fill.paint.curColor;
  2299. if (parent->fill.paint.url) {
  2300. if (child->fill.paint.url) free(child->fill.paint.url);
  2301. child->fill.paint.url = _copyId(parent->fill.paint.url);
  2302. }
  2303. }
  2304. if (!(child->fill.flags & SvgFillFlags::Opacity)) {
  2305. child->fill.opacity = parent->fill.opacity;
  2306. }
  2307. if (!(child->fill.flags & SvgFillFlags::FillRule)) {
  2308. child->fill.fillRule = parent->fill.fillRule;
  2309. }
  2310. //Stroke
  2311. if (!(child->stroke.flags & SvgStrokeFlags::Paint)) {
  2312. child->stroke.paint.color = parent->stroke.paint.color;
  2313. child->stroke.paint.none = parent->stroke.paint.none;
  2314. child->stroke.paint.curColor = parent->stroke.paint.curColor;
  2315. if (parent->stroke.paint.url) {
  2316. if (child->stroke.paint.url) free(child->stroke.paint.url);
  2317. child->stroke.paint.url = _copyId(parent->stroke.paint.url);
  2318. }
  2319. }
  2320. if (!(child->stroke.flags & SvgStrokeFlags::Opacity)) {
  2321. child->stroke.opacity = parent->stroke.opacity;
  2322. }
  2323. if (!(child->stroke.flags & SvgStrokeFlags::Width)) {
  2324. child->stroke.width = parent->stroke.width;
  2325. }
  2326. if (!(child->stroke.flags & SvgStrokeFlags::Dash)) {
  2327. if (parent->stroke.dash.array.count > 0) {
  2328. child->stroke.dash.array.clear();
  2329. child->stroke.dash.array.reserve(parent->stroke.dash.array.count);
  2330. for (uint32_t i = 0; i < parent->stroke.dash.array.count; ++i) {
  2331. child->stroke.dash.array.push(parent->stroke.dash.array[i]);
  2332. }
  2333. }
  2334. }
  2335. if (!(child->stroke.flags & SvgStrokeFlags::DashOffset)) {
  2336. child->stroke.dash.offset = parent->stroke.dash.offset;
  2337. }
  2338. if (!(child->stroke.flags & SvgStrokeFlags::Cap)) {
  2339. child->stroke.cap = parent->stroke.cap;
  2340. }
  2341. if (!(child->stroke.flags & SvgStrokeFlags::Join)) {
  2342. child->stroke.join = parent->stroke.join;
  2343. }
  2344. if (!(child->stroke.flags & SvgStrokeFlags::Miterlimit)) {
  2345. child->stroke.miterlimit = parent->stroke.miterlimit;
  2346. }
  2347. }
  2348. static void _styleCopy(SvgStyleProperty* to, const SvgStyleProperty* from)
  2349. {
  2350. if (from == nullptr) return;
  2351. //Copy the properties of 'from' only if they were explicitly set (not the default ones).
  2352. if (from->curColorSet) {
  2353. to->color = from->color;
  2354. to->curColorSet = true;
  2355. }
  2356. if (from->flags & SvgStyleFlags::PaintOrder) {
  2357. to->paintOrder = from->paintOrder;
  2358. }
  2359. //Fill
  2360. to->fill.flags = (to->fill.flags | from->fill.flags);
  2361. if (from->fill.flags & SvgFillFlags::Paint) {
  2362. to->fill.paint.color = from->fill.paint.color;
  2363. to->fill.paint.none = from->fill.paint.none;
  2364. to->fill.paint.curColor = from->fill.paint.curColor;
  2365. if (from->fill.paint.url) {
  2366. if (to->fill.paint.url) free(to->fill.paint.url);
  2367. to->fill.paint.url = _copyId(from->fill.paint.url);
  2368. }
  2369. }
  2370. if (from->fill.flags & SvgFillFlags::Opacity) {
  2371. to->fill.opacity = from->fill.opacity;
  2372. }
  2373. if (from->fill.flags & SvgFillFlags::FillRule) {
  2374. to->fill.fillRule = from->fill.fillRule;
  2375. }
  2376. //Stroke
  2377. to->stroke.flags = (to->stroke.flags | from->stroke.flags);
  2378. if (from->stroke.flags & SvgStrokeFlags::Paint) {
  2379. to->stroke.paint.color = from->stroke.paint.color;
  2380. to->stroke.paint.none = from->stroke.paint.none;
  2381. to->stroke.paint.curColor = from->stroke.paint.curColor;
  2382. if (from->stroke.paint.url) {
  2383. if (to->stroke.paint.url) free(to->stroke.paint.url);
  2384. to->stroke.paint.url = _copyId(from->stroke.paint.url);
  2385. }
  2386. }
  2387. if (from->stroke.flags & SvgStrokeFlags::Opacity) {
  2388. to->stroke.opacity = from->stroke.opacity;
  2389. }
  2390. if (from->stroke.flags & SvgStrokeFlags::Width) {
  2391. to->stroke.width = from->stroke.width;
  2392. }
  2393. if (from->stroke.flags & SvgStrokeFlags::Dash) {
  2394. if (from->stroke.dash.array.count > 0) {
  2395. to->stroke.dash.array.clear();
  2396. to->stroke.dash.array.reserve(from->stroke.dash.array.count);
  2397. for (uint32_t i = 0; i < from->stroke.dash.array.count; ++i) {
  2398. to->stroke.dash.array.push(from->stroke.dash.array[i]);
  2399. }
  2400. }
  2401. }
  2402. if (from->stroke.flags & SvgStrokeFlags::DashOffset) {
  2403. to->stroke.dash.offset = from->stroke.dash.offset;
  2404. }
  2405. if (from->stroke.flags & SvgStrokeFlags::Cap) {
  2406. to->stroke.cap = from->stroke.cap;
  2407. }
  2408. if (from->stroke.flags & SvgStrokeFlags::Join) {
  2409. to->stroke.join = from->stroke.join;
  2410. }
  2411. if (from->stroke.flags & SvgStrokeFlags::Miterlimit) {
  2412. to->stroke.miterlimit = from->stroke.miterlimit;
  2413. }
  2414. }
  2415. static void _copyAttr(SvgNode* to, const SvgNode* from)
  2416. {
  2417. //Copy matrix attribute
  2418. if (from->transform) {
  2419. to->transform = (Matrix*)malloc(sizeof(Matrix));
  2420. if (to->transform) *to->transform = *from->transform;
  2421. }
  2422. //Copy style attribute
  2423. _styleCopy(to->style, from->style);
  2424. to->style->flags = (to->style->flags | from->style->flags);
  2425. if (from->style->clipPath.url) {
  2426. if (to->style->clipPath.url) free(to->style->clipPath.url);
  2427. to->style->clipPath.url = strdup(from->style->clipPath.url);
  2428. }
  2429. if (from->style->mask.url) {
  2430. if (to->style->mask.url) free(to->style->mask.url);
  2431. to->style->mask.url = strdup(from->style->mask.url);
  2432. }
  2433. //Copy node attribute
  2434. switch (from->type) {
  2435. case SvgNodeType::Circle: {
  2436. to->node.circle.cx = from->node.circle.cx;
  2437. to->node.circle.cy = from->node.circle.cy;
  2438. to->node.circle.r = from->node.circle.r;
  2439. break;
  2440. }
  2441. case SvgNodeType::Ellipse: {
  2442. to->node.ellipse.cx = from->node.ellipse.cx;
  2443. to->node.ellipse.cy = from->node.ellipse.cy;
  2444. to->node.ellipse.rx = from->node.ellipse.rx;
  2445. to->node.ellipse.ry = from->node.ellipse.ry;
  2446. break;
  2447. }
  2448. case SvgNodeType::Rect: {
  2449. to->node.rect.x = from->node.rect.x;
  2450. to->node.rect.y = from->node.rect.y;
  2451. to->node.rect.w = from->node.rect.w;
  2452. to->node.rect.h = from->node.rect.h;
  2453. to->node.rect.rx = from->node.rect.rx;
  2454. to->node.rect.ry = from->node.rect.ry;
  2455. to->node.rect.hasRx = from->node.rect.hasRx;
  2456. to->node.rect.hasRy = from->node.rect.hasRy;
  2457. break;
  2458. }
  2459. case SvgNodeType::Line: {
  2460. to->node.line.x1 = from->node.line.x1;
  2461. to->node.line.y1 = from->node.line.y1;
  2462. to->node.line.x2 = from->node.line.x2;
  2463. to->node.line.y2 = from->node.line.y2;
  2464. break;
  2465. }
  2466. case SvgNodeType::Path: {
  2467. if (from->node.path.path) {
  2468. if (to->node.path.path) free(to->node.path.path);
  2469. to->node.path.path = strdup(from->node.path.path);
  2470. }
  2471. break;
  2472. }
  2473. case SvgNodeType::Polygon: {
  2474. if ((to->node.polygon.pts.count = from->node.polygon.pts.count)) {
  2475. to->node.polygon.pts = from->node.polygon.pts;
  2476. }
  2477. break;
  2478. }
  2479. case SvgNodeType::Polyline: {
  2480. if ((to->node.polyline.pts.count = from->node.polyline.pts.count)) {
  2481. to->node.polyline.pts = from->node.polyline.pts;
  2482. }
  2483. break;
  2484. }
  2485. case SvgNodeType::Image: {
  2486. to->node.image.x = from->node.image.x;
  2487. to->node.image.y = from->node.image.y;
  2488. to->node.image.w = from->node.image.w;
  2489. to->node.image.h = from->node.image.h;
  2490. if (from->node.image.href) {
  2491. if (to->node.image.href) free(to->node.image.href);
  2492. to->node.image.href = strdup(from->node.image.href);
  2493. }
  2494. break;
  2495. }
  2496. case SvgNodeType::Use: {
  2497. to->node.use.x = from->node.use.x;
  2498. to->node.use.y = from->node.use.y;
  2499. to->node.use.w = from->node.use.w;
  2500. to->node.use.h = from->node.use.h;
  2501. to->node.use.isWidthSet = from->node.use.isWidthSet;
  2502. to->node.use.isHeightSet = from->node.use.isHeightSet;
  2503. to->node.use.symbol = from->node.use.symbol;
  2504. break;
  2505. }
  2506. default: {
  2507. break;
  2508. }
  2509. }
  2510. }
  2511. static void _cloneNode(SvgNode* from, SvgNode* parent, int depth)
  2512. {
  2513. /* Exception handling: Prevent invalid SVG data input.
  2514. The size is the arbitrary value, we need an experimental size. */
  2515. if (depth == 8192) {
  2516. TVGERR("SVG", "Infinite recursive call - stopped after %d calls! Svg file may be incorrectly formatted.", depth);
  2517. return;
  2518. }
  2519. SvgNode* newNode;
  2520. if (!from || !parent || from == parent) return;
  2521. newNode = _createNode(parent, from->type);
  2522. if (!newNode) return;
  2523. _styleInherit(newNode->style, parent->style);
  2524. _copyAttr(newNode, from);
  2525. auto child = from->child.data;
  2526. for (uint32_t i = 0; i < from->child.count; ++i, ++child) {
  2527. _cloneNode(*child, newNode, depth + 1);
  2528. }
  2529. }
  2530. static void _clonePostponedNodes(Array<SvgNodeIdPair>* cloneNodes, SvgNode* doc)
  2531. {
  2532. for (uint32_t i = 0; i < cloneNodes->count; ++i) {
  2533. auto nodeIdPair = (*cloneNodes)[i];
  2534. auto defs = _getDefsNode(nodeIdPair.node);
  2535. auto nodeFrom = _findNodeById(defs, nodeIdPair.id);
  2536. if (!nodeFrom) nodeFrom = _findNodeById(doc, nodeIdPair.id);
  2537. if (!_findParentById(nodeIdPair.node, nodeIdPair.id, doc)) {
  2538. _cloneNode(nodeFrom, nodeIdPair.node, 0);
  2539. if (nodeFrom && nodeFrom->type == SvgNodeType::Symbol && nodeIdPair.node->type == SvgNodeType::Use) {
  2540. nodeIdPair.node->node.use.symbol = nodeFrom;
  2541. }
  2542. } else {
  2543. TVGLOG("SVG", "%s is ancestor element. This reference is invalid.", nodeIdPair.id);
  2544. }
  2545. free(nodeIdPair.id);
  2546. }
  2547. }
  2548. static constexpr struct
  2549. {
  2550. const char* tag;
  2551. size_t sz;
  2552. } popArray[] = {
  2553. {"g", sizeof("g")},
  2554. {"svg", sizeof("svg")},
  2555. {"defs", sizeof("defs")},
  2556. {"mask", sizeof("mask")},
  2557. {"clipPath", sizeof("clipPath")},
  2558. {"style", sizeof("style")},
  2559. {"symbol", sizeof("symbol")}
  2560. };
  2561. static void _svgLoaderParserXmlClose(SvgLoaderData* loader, const char* content)
  2562. {
  2563. content = _skipSpace(content, nullptr);
  2564. for (unsigned int i = 0; i < sizeof(popArray) / sizeof(popArray[0]); i++) {
  2565. if (!strncmp(content, popArray[i].tag, popArray[i].sz - 1)) {
  2566. loader->stack.pop();
  2567. break;
  2568. }
  2569. }
  2570. loader->level--;
  2571. }
  2572. static void _svgLoaderParserXmlOpen(SvgLoaderData* loader, const char* content, unsigned int length, bool empty)
  2573. {
  2574. const char* attrs = nullptr;
  2575. int attrsLength = 0;
  2576. int sz = length;
  2577. char tagName[20] = "";
  2578. FactoryMethod method;
  2579. GradientFactoryMethod gradientMethod;
  2580. SvgNode *node = nullptr, *parent = nullptr;
  2581. loader->level++;
  2582. attrs = simpleXmlFindAttributesTag(content, length);
  2583. if (!attrs) {
  2584. //Parse the empty tag
  2585. attrs = content;
  2586. while ((attrs != nullptr) && *attrs != '>') attrs++;
  2587. if (empty) attrs--;
  2588. }
  2589. if (attrs) {
  2590. //Find out the tag name starting from content till sz length
  2591. sz = attrs - content;
  2592. while ((sz > 0) && (isspace(content[sz - 1]))) sz--;
  2593. if ((unsigned)sz >= sizeof(tagName)) return;
  2594. strncpy(tagName, content, sz);
  2595. tagName[sz] = '\0';
  2596. attrsLength = length - sz;
  2597. }
  2598. if ((method = _findGroupFactory(tagName))) {
  2599. //Group
  2600. if (empty) return;
  2601. if (!loader->doc) {
  2602. if (strcmp(tagName, "svg")) return; //Not a valid svg document
  2603. node = method(loader, nullptr, attrs, attrsLength, simpleXmlParseAttributes);
  2604. loader->doc = node;
  2605. } else {
  2606. if (!strcmp(tagName, "svg")) return; //Already loaded <svg>(SvgNodeType::Doc) tag
  2607. if (loader->stack.count > 0) parent = loader->stack.last();
  2608. else parent = loader->doc;
  2609. if (!strcmp(tagName, "style")) {
  2610. // TODO: For now only the first style node is saved. After the css id selector
  2611. // is introduced this if condition shouldin't be necessary any more
  2612. if (!loader->cssStyle) {
  2613. node = method(loader, nullptr, attrs, attrsLength, simpleXmlParseAttributes);
  2614. loader->cssStyle = node;
  2615. loader->doc->node.doc.style = node;
  2616. loader->style = true;
  2617. }
  2618. } else {
  2619. node = method(loader, parent, attrs, attrsLength, simpleXmlParseAttributes);
  2620. }
  2621. }
  2622. if (!node) return;
  2623. if (node->type != SvgNodeType::Defs || !empty) {
  2624. loader->stack.push(node);
  2625. }
  2626. } else if ((method = _findGraphicsFactory(tagName))) {
  2627. if (loader->stack.count > 0) parent = loader->stack.last();
  2628. else parent = loader->doc;
  2629. node = method(loader, parent, attrs, attrsLength, simpleXmlParseAttributes);
  2630. } else if ((gradientMethod = _findGradientFactory(tagName))) {
  2631. SvgStyleGradient* gradient;
  2632. gradient = gradientMethod(loader, attrs, attrsLength);
  2633. //FIXME: The current parsing structure does not distinguish end tags.
  2634. // There is no way to know if the currently parsed gradient is in defs.
  2635. // If a gradient is declared outside of defs after defs is set, it is included in the gradients of defs.
  2636. // But finally, the loader has a gradient style list regardless of defs.
  2637. // This is only to support this when multiple gradients are declared, even if no defs are declared.
  2638. // refer to: https://developer.mozilla.org/en-US/docs/Web/SVG/Element/defs
  2639. if (loader->def && loader->doc->node.doc.defs) {
  2640. loader->def->node.defs.gradients.push(gradient);
  2641. } else {
  2642. loader->gradients.push(gradient);
  2643. }
  2644. loader->latestGradient = gradient;
  2645. } else if (!strcmp(tagName, "stop")) {
  2646. if (!loader->latestGradient) {
  2647. TVGLOG("SVG", "Stop element is used outside of the Gradient element");
  2648. return;
  2649. }
  2650. /* default value for opacity */
  2651. loader->svgParse->gradStop = {0.0f, 0, 0, 0, 255};
  2652. loader->svgParse->flags = SvgStopStyleFlags::StopDefault;
  2653. simpleXmlParseAttributes(attrs, attrsLength, _attrParseStops, loader);
  2654. loader->latestGradient->stops.push(loader->svgParse->gradStop);
  2655. } else if (!isIgnoreUnsupportedLogElements(tagName)) {
  2656. TVGLOG("SVG", "Unsupported elements used [Elements: %s]", tagName);
  2657. }
  2658. }
  2659. static void _svgLoaderParserXmlCssStyle(SvgLoaderData* loader, const char* content, unsigned int length)
  2660. {
  2661. char* tag;
  2662. char* name;
  2663. const char* attrs = nullptr;
  2664. unsigned int attrsLength = 0;
  2665. FactoryMethod method;
  2666. GradientFactoryMethod gradientMethod;
  2667. SvgNode *node = nullptr;
  2668. while (auto next = simpleXmlParseCSSAttribute(content, length, &tag, &name, &attrs, &attrsLength)) {
  2669. if ((method = _findGroupFactory(tag))) {
  2670. if ((node = method(loader, loader->cssStyle, attrs, attrsLength, simpleXmlParseW3CAttribute))) node->id = _copyId(name);
  2671. } else if ((method = _findGraphicsFactory(tag))) {
  2672. if ((node = method(loader, loader->cssStyle, attrs, attrsLength, simpleXmlParseW3CAttribute))) node->id = _copyId(name);
  2673. } else if ((gradientMethod = _findGradientFactory(tag))) {
  2674. TVGLOG("SVG", "Unsupported elements used in the internal CSS style sheets [Elements: %s]", tag);
  2675. } else if (!strcmp(tag, "stop")) {
  2676. TVGLOG("SVG", "Unsupported elements used in the internal CSS style sheets [Elements: %s]", tag);
  2677. } else if (!strcmp(tag, "all")) {
  2678. if ((node = _createCssStyleNode(loader, loader->cssStyle, attrs, attrsLength, simpleXmlParseW3CAttribute))) node->id = _copyId(name);
  2679. } else if (!isIgnoreUnsupportedLogElements(tag)) {
  2680. TVGLOG("SVG", "Unsupported elements used in the internal CSS style sheets [Elements: %s]", tag);
  2681. }
  2682. length -= next - content;
  2683. content = next;
  2684. free(tag);
  2685. free(name);
  2686. }
  2687. loader->style = false;
  2688. }
  2689. static bool _svgLoaderParser(void* data, SimpleXMLType type, const char* content, unsigned int length)
  2690. {
  2691. SvgLoaderData* loader = (SvgLoaderData*)data;
  2692. switch (type) {
  2693. case SimpleXMLType::Open: {
  2694. _svgLoaderParserXmlOpen(loader, content, length, false);
  2695. break;
  2696. }
  2697. case SimpleXMLType::OpenEmpty: {
  2698. _svgLoaderParserXmlOpen(loader, content, length, true);
  2699. break;
  2700. }
  2701. case SimpleXMLType::Close: {
  2702. _svgLoaderParserXmlClose(loader, content);
  2703. break;
  2704. }
  2705. case SimpleXMLType::Data:
  2706. case SimpleXMLType::CData: {
  2707. if (loader->style) _svgLoaderParserXmlCssStyle(loader, content, length);
  2708. break;
  2709. }
  2710. case SimpleXMLType::DoctypeChild: {
  2711. break;
  2712. }
  2713. case SimpleXMLType::Ignored:
  2714. case SimpleXMLType::Comment:
  2715. case SimpleXMLType::Doctype: {
  2716. break;
  2717. }
  2718. default: {
  2719. break;
  2720. }
  2721. }
  2722. return true;
  2723. }
  2724. static void _inefficientNodeCheck(TVG_UNUSED SvgNode* node)
  2725. {
  2726. #ifdef THORVG_LOG_ENABLED
  2727. auto type = simpleXmlNodeTypeToString(node->type);
  2728. if (!node->display && node->type != SvgNodeType::ClipPath && node->type != SvgNodeType::Symbol) TVGLOG("SVG", "Inefficient elements used [Display is none][Node Type : %s]", type);
  2729. if (node->style->opacity == 0) TVGLOG("SVG", "Inefficient elements used [Opacity is zero][Node Type : %s]", type);
  2730. if (node->style->fill.opacity == 0 && node->style->stroke.opacity == 0) TVGLOG("SVG", "Inefficient elements used [Fill opacity and stroke opacity are zero][Node Type : %s]", type);
  2731. switch (node->type) {
  2732. case SvgNodeType::Path: {
  2733. if (!node->node.path.path) TVGLOG("SVG", "Inefficient elements used [Empty path][Node Type : %s]", type);
  2734. break;
  2735. }
  2736. case SvgNodeType::Ellipse: {
  2737. if (node->node.ellipse.rx == 0 && node->node.ellipse.ry == 0) TVGLOG("SVG", "Inefficient elements used [Size is zero][Node Type : %s]", type);
  2738. break;
  2739. }
  2740. case SvgNodeType::Polygon:
  2741. case SvgNodeType::Polyline: {
  2742. if (node->node.polygon.pts.count < 2) TVGLOG("SVG", "Inefficient elements used [Invalid Polygon][Node Type : %s]", type);
  2743. break;
  2744. }
  2745. case SvgNodeType::Circle: {
  2746. if (node->node.circle.r == 0) TVGLOG("SVG", "Inefficient elements used [Size is zero][Node Type : %s]", type);
  2747. break;
  2748. }
  2749. case SvgNodeType::Rect: {
  2750. if (node->node.rect.w == 0 && node->node.rect.h) TVGLOG("SVG", "Inefficient elements used [Size is zero][Node Type : %s]", type);
  2751. break;
  2752. }
  2753. case SvgNodeType::Line: {
  2754. if (node->node.line.x1 == node->node.line.x2 && node->node.line.y1 == node->node.line.y2) TVGLOG("SVG", "Inefficient elements used [Size is zero][Node Type : %s]", type);
  2755. break;
  2756. }
  2757. default: break;
  2758. }
  2759. #endif
  2760. }
  2761. static void _updateStyle(SvgNode* node, SvgStyleProperty* parentStyle)
  2762. {
  2763. _styleInherit(node->style, parentStyle);
  2764. _inefficientNodeCheck(node);
  2765. auto child = node->child.data;
  2766. for (uint32_t i = 0; i < node->child.count; ++i, ++child) {
  2767. _updateStyle(*child, node->style);
  2768. }
  2769. }
  2770. static SvgStyleGradient* _gradientDup(SvgLoaderData* loader, Array<SvgStyleGradient*>* gradients, const char* id)
  2771. {
  2772. SvgStyleGradient* result = nullptr;
  2773. auto gradList = gradients->data;
  2774. for (uint32_t i = 0; i < gradients->count; ++i) {
  2775. if ((*gradList)->id && !strcmp((*gradList)->id, id)) {
  2776. result = _cloneGradient(*gradList);
  2777. break;
  2778. }
  2779. ++gradList;
  2780. }
  2781. if (result && result->ref) {
  2782. gradList = gradients->data;
  2783. for (uint32_t i = 0; i < gradients->count; ++i) {
  2784. if ((*gradList)->id && !strcmp((*gradList)->id, result->ref)) {
  2785. _inheritGradient(loader, result, *gradList);
  2786. break;
  2787. }
  2788. ++gradList;
  2789. }
  2790. }
  2791. return result;
  2792. }
  2793. static void _updateGradient(SvgLoaderData* loader, SvgNode* node, Array<SvgStyleGradient*>* gradients)
  2794. {
  2795. if (node->child.count > 0) {
  2796. auto child = node->child.data;
  2797. for (uint32_t i = 0; i < node->child.count; ++i, ++child) {
  2798. _updateGradient(loader, *child, gradients);
  2799. }
  2800. } else {
  2801. if (node->style->fill.paint.url) {
  2802. auto newGrad = _gradientDup(loader, gradients, node->style->fill.paint.url);
  2803. if (newGrad) {
  2804. if (node->style->fill.paint.gradient) {
  2805. node->style->fill.paint.gradient->clear();
  2806. free(node->style->fill.paint.gradient);
  2807. }
  2808. node->style->fill.paint.gradient = newGrad;
  2809. }
  2810. }
  2811. if (node->style->stroke.paint.url) {
  2812. auto newGrad = _gradientDup(loader, gradients, node->style->stroke.paint.url);
  2813. if (newGrad) {
  2814. if (node->style->stroke.paint.gradient) {
  2815. node->style->stroke.paint.gradient->clear();
  2816. free(node->style->stroke.paint.gradient);
  2817. }
  2818. node->style->stroke.paint.gradient = newGrad;
  2819. }
  2820. }
  2821. }
  2822. }
  2823. static void _updateComposite(SvgNode* node, SvgNode* root)
  2824. {
  2825. if (node->style->clipPath.url && !node->style->clipPath.node) {
  2826. SvgNode* findResult = _findNodeById(root, node->style->clipPath.url);
  2827. if (findResult) node->style->clipPath.node = findResult;
  2828. }
  2829. if (node->style->mask.url && !node->style->mask.node) {
  2830. SvgNode* findResult = _findNodeById(root, node->style->mask.url);
  2831. if (findResult) node->style->mask.node = findResult;
  2832. }
  2833. if (node->child.count > 0) {
  2834. auto child = node->child.data;
  2835. for (uint32_t i = 0; i < node->child.count; ++i, ++child) {
  2836. _updateComposite(*child, root);
  2837. }
  2838. }
  2839. }
  2840. static void _freeNodeStyle(SvgStyleProperty* style)
  2841. {
  2842. if (!style) return;
  2843. //style->clipPath.node and style->mask.node has only the addresses of node. Therefore, node is released from _freeNode.
  2844. free(style->clipPath.url);
  2845. free(style->mask.url);
  2846. free(style->cssClass);
  2847. if (style->fill.paint.gradient) {
  2848. style->fill.paint.gradient->clear();
  2849. free(style->fill.paint.gradient);
  2850. }
  2851. if (style->stroke.paint.gradient) {
  2852. style->stroke.paint.gradient->clear();
  2853. free(style->stroke.paint.gradient);
  2854. }
  2855. free(style->fill.paint.url);
  2856. free(style->stroke.paint.url);
  2857. style->stroke.dash.array.reset();
  2858. free(style);
  2859. }
  2860. static void _freeNode(SvgNode* node)
  2861. {
  2862. if (!node) return;
  2863. auto child = node->child.data;
  2864. for (uint32_t i = 0; i < node->child.count; ++i, ++child) {
  2865. _freeNode(*child);
  2866. }
  2867. node->child.reset();
  2868. free(node->id);
  2869. free(node->transform);
  2870. _freeNodeStyle(node->style);
  2871. switch (node->type) {
  2872. case SvgNodeType::Path: {
  2873. free(node->node.path.path);
  2874. break;
  2875. }
  2876. case SvgNodeType::Polygon: {
  2877. free(node->node.polygon.pts.data);
  2878. break;
  2879. }
  2880. case SvgNodeType::Polyline: {
  2881. free(node->node.polyline.pts.data);
  2882. break;
  2883. }
  2884. case SvgNodeType::Doc: {
  2885. _freeNode(node->node.doc.defs);
  2886. _freeNode(node->node.doc.style);
  2887. break;
  2888. }
  2889. case SvgNodeType::Defs: {
  2890. auto gradients = node->node.defs.gradients.data;
  2891. for (size_t i = 0; i < node->node.defs.gradients.count; ++i) {
  2892. (*gradients)->clear();
  2893. free(*gradients);
  2894. ++gradients;
  2895. }
  2896. node->node.defs.gradients.reset();
  2897. break;
  2898. }
  2899. case SvgNodeType::Image: {
  2900. free(node->node.image.href);
  2901. break;
  2902. }
  2903. default: {
  2904. break;
  2905. }
  2906. }
  2907. free(node);
  2908. }
  2909. static bool _svgLoaderParserForValidCheckXmlOpen(SvgLoaderData* loader, const char* content, unsigned int length)
  2910. {
  2911. const char* attrs = nullptr;
  2912. int sz = length;
  2913. char tagName[20] = "";
  2914. FactoryMethod method;
  2915. SvgNode *node = nullptr;
  2916. int attrsLength = 0;
  2917. loader->level++;
  2918. attrs = simpleXmlFindAttributesTag(content, length);
  2919. if (!attrs) {
  2920. //Parse the empty tag
  2921. attrs = content;
  2922. while ((attrs != nullptr) && *attrs != '>') attrs++;
  2923. }
  2924. if (attrs) {
  2925. sz = attrs - content;
  2926. while ((sz > 0) && (isspace(content[sz - 1]))) sz--;
  2927. if ((unsigned)sz >= sizeof(tagName)) return false;
  2928. strncpy(tagName, content, sz);
  2929. tagName[sz] = '\0';
  2930. attrsLength = length - sz;
  2931. }
  2932. if ((method = _findGroupFactory(tagName))) {
  2933. if (!loader->doc) {
  2934. if (strcmp(tagName, "svg")) return true; //Not a valid svg document
  2935. node = method(loader, nullptr, attrs, attrsLength, simpleXmlParseAttributes);
  2936. loader->doc = node;
  2937. loader->stack.push(node);
  2938. return false;
  2939. }
  2940. }
  2941. return true;
  2942. }
  2943. static bool _svgLoaderParserForValidCheck(void* data, SimpleXMLType type, const char* content, unsigned int length)
  2944. {
  2945. SvgLoaderData* loader = (SvgLoaderData*)data;
  2946. bool res = true;;
  2947. switch (type) {
  2948. case SimpleXMLType::Open:
  2949. case SimpleXMLType::OpenEmpty: {
  2950. //If 'res' is false, it means <svg> tag is found.
  2951. res = _svgLoaderParserForValidCheckXmlOpen(loader, content, length);
  2952. break;
  2953. }
  2954. default: {
  2955. break;
  2956. }
  2957. }
  2958. return res;
  2959. }
  2960. void SvgLoader::clear(bool all)
  2961. {
  2962. //flush out the intermediate data
  2963. free(loaderData.svgParse);
  2964. loaderData.svgParse = nullptr;
  2965. for (auto gradient = loaderData.gradients.begin(); gradient < loaderData.gradients.end(); ++gradient) {
  2966. (*gradient)->clear();
  2967. free(*gradient);
  2968. }
  2969. loaderData.gradients.reset();
  2970. _freeNode(loaderData.doc);
  2971. loaderData.doc = nullptr;
  2972. loaderData.stack.reset();
  2973. if (!all) return;
  2974. for (auto p = loaderData.images.begin(); p < loaderData.images.end(); ++p) {
  2975. free(*p);
  2976. }
  2977. loaderData.images.reset();
  2978. if (copy) free((char*)content);
  2979. delete(root);
  2980. root = nullptr;
  2981. size = 0;
  2982. content = nullptr;
  2983. copy = false;
  2984. }
  2985. /************************************************************************/
  2986. /* External Class Implementation */
  2987. /************************************************************************/
  2988. SvgLoader::SvgLoader() : ImageLoader(FileType::Svg)
  2989. {
  2990. }
  2991. SvgLoader::~SvgLoader()
  2992. {
  2993. this->done();
  2994. clear();
  2995. }
  2996. void SvgLoader::run(unsigned tid)
  2997. {
  2998. //According to the SVG standard the value of the width/height of the viewbox set to 0 disables rendering
  2999. if ((viewFlag & SvgViewFlag::Viewbox) && (fabsf(vw) <= FLT_EPSILON || fabsf(vh) <= FLT_EPSILON)) {
  3000. TVGLOG("SVG", "The <viewBox> width and/or height set to 0 - rendering disabled.");
  3001. root = Scene::gen().release();
  3002. return;
  3003. }
  3004. if (!simpleXmlParse(content, size, true, _svgLoaderParser, &(loaderData))) return;
  3005. if (loaderData.doc) {
  3006. auto defs = loaderData.doc->node.doc.defs;
  3007. if (loaderData.nodesToStyle.count > 0) cssApplyStyleToPostponeds(loaderData.nodesToStyle, loaderData.cssStyle);
  3008. if (loaderData.cssStyle) cssUpdateStyle(loaderData.doc, loaderData.cssStyle);
  3009. if (loaderData.cloneNodes.count > 0) _clonePostponedNodes(&loaderData.cloneNodes, loaderData.doc);
  3010. _updateComposite(loaderData.doc, loaderData.doc);
  3011. if (defs) _updateComposite(loaderData.doc, defs);
  3012. _updateStyle(loaderData.doc, nullptr);
  3013. if (defs) _updateStyle(defs, nullptr);
  3014. if (loaderData.gradients.count > 0) _updateGradient(&loaderData, loaderData.doc, &loaderData.gradients);
  3015. if (defs) _updateGradient(&loaderData, loaderData.doc, &defs->node.defs.gradients);
  3016. }
  3017. root = svgSceneBuild(loaderData, {vx, vy, vw, vh}, w, h, align, meetOrSlice, svgPath, viewFlag);
  3018. //In case no viewbox and width/height data is provided the completion of loading
  3019. //has to be forced, in order to establish this data based on the whole picture.
  3020. if (!(viewFlag & SvgViewFlag::Viewbox)) {
  3021. //Override viewbox & size again after svg loading.
  3022. vx = loaderData.doc->node.doc.vx;
  3023. vy = loaderData.doc->node.doc.vy;
  3024. vw = loaderData.doc->node.doc.vw;
  3025. vh = loaderData.doc->node.doc.vh;
  3026. w = loaderData.doc->node.doc.w;
  3027. h = loaderData.doc->node.doc.h;
  3028. }
  3029. clear(false);
  3030. }
  3031. bool SvgLoader::header()
  3032. {
  3033. //For valid check, only <svg> tag is parsed first.
  3034. //If the <svg> tag is found, the loaded file is valid and stores viewbox information.
  3035. //After that, the remaining content data is parsed in order with async.
  3036. loaderData.svgParse = (SvgParser*)malloc(sizeof(SvgParser));
  3037. if (!loaderData.svgParse) return false;
  3038. loaderData.svgParse->flags = SvgStopStyleFlags::StopDefault;
  3039. viewFlag = SvgViewFlag::None;
  3040. simpleXmlParse(content, size, true, _svgLoaderParserForValidCheck, &(loaderData));
  3041. if (loaderData.doc && loaderData.doc->type == SvgNodeType::Doc) {
  3042. viewFlag = loaderData.doc->node.doc.viewFlag;
  3043. align = loaderData.doc->node.doc.align;
  3044. meetOrSlice = loaderData.doc->node.doc.meetOrSlice;
  3045. if (viewFlag & SvgViewFlag::Viewbox) {
  3046. vx = loaderData.doc->node.doc.vx;
  3047. vy = loaderData.doc->node.doc.vy;
  3048. vw = loaderData.doc->node.doc.vw;
  3049. vh = loaderData.doc->node.doc.vh;
  3050. if (viewFlag & SvgViewFlag::Width) w = loaderData.doc->node.doc.w;
  3051. else {
  3052. w = loaderData.doc->node.doc.vw;
  3053. if (viewFlag & SvgViewFlag::WidthInPercent) {
  3054. w *= loaderData.doc->node.doc.w;
  3055. viewFlag = (viewFlag ^ SvgViewFlag::WidthInPercent);
  3056. }
  3057. viewFlag = (viewFlag | SvgViewFlag::Width);
  3058. }
  3059. if (viewFlag & SvgViewFlag::Height) h = loaderData.doc->node.doc.h;
  3060. else {
  3061. h = loaderData.doc->node.doc.vh;
  3062. if (viewFlag & SvgViewFlag::HeightInPercent) {
  3063. h *= loaderData.doc->node.doc.h;
  3064. viewFlag = (viewFlag ^ SvgViewFlag::HeightInPercent);
  3065. }
  3066. viewFlag = (viewFlag | SvgViewFlag::Height);
  3067. }
  3068. //In case no viewbox and width/height data is provided the completion of loading
  3069. //has to be forced, in order to establish this data based on the whole picture.
  3070. } else {
  3071. //Before loading, set default viewbox & size if they are empty
  3072. vx = vy = 0.0f;
  3073. if (viewFlag & SvgViewFlag::Width) {
  3074. vw = w = loaderData.doc->node.doc.w;
  3075. } else {
  3076. vw = 1.0f;
  3077. if (viewFlag & SvgViewFlag::WidthInPercent) {
  3078. w = loaderData.doc->node.doc.w;
  3079. } else w = 1.0f;
  3080. }
  3081. if (viewFlag & SvgViewFlag::Height) {
  3082. vh = h = loaderData.doc->node.doc.h;
  3083. } else {
  3084. vh = 1.0f;
  3085. if (viewFlag & SvgViewFlag::HeightInPercent) {
  3086. h = loaderData.doc->node.doc.h;
  3087. } else h = 1.0f;
  3088. }
  3089. run(0);
  3090. }
  3091. return true;
  3092. }
  3093. TVGLOG("SVG", "No SVG File. There is no <svg/>");
  3094. return false;
  3095. }
  3096. bool SvgLoader::open(const char* data, uint32_t size, bool copy)
  3097. {
  3098. clear();
  3099. if (copy) {
  3100. content = (char*)malloc(size);
  3101. if (!content) return false;
  3102. memcpy((char*)content, data, size);
  3103. } else content = data;
  3104. this->size = size;
  3105. this->copy = copy;
  3106. return header();
  3107. }
  3108. bool SvgLoader::open(const string& path)
  3109. {
  3110. clear();
  3111. ifstream f;
  3112. f.open(path);
  3113. if (!f.is_open()) return false;
  3114. svgPath = path;
  3115. getline(f, filePath, '\0');
  3116. f.close();
  3117. if (filePath.empty()) return false;
  3118. content = filePath.c_str();
  3119. size = filePath.size();
  3120. return header();
  3121. }
  3122. bool SvgLoader::resize(Paint* paint, float w, float h)
  3123. {
  3124. if (!paint) return false;
  3125. auto sx = w / this->w;
  3126. auto sy = h / this->h;
  3127. Matrix m = {sx, 0, 0, 0, sy, 0, 0, 0, 1};
  3128. paint->transform(m);
  3129. return true;
  3130. }
  3131. bool SvgLoader::read()
  3132. {
  3133. if (!content || size == 0) return false;
  3134. //the loading has been already completed in header()
  3135. if (root || !LoadModule::read()) return true;
  3136. TaskScheduler::request(this);
  3137. return true;
  3138. }
  3139. bool SvgLoader::close()
  3140. {
  3141. if (!LoadModule::close()) return false;
  3142. this->done();
  3143. clear();
  3144. return true;
  3145. }
  3146. Paint* SvgLoader::paint()
  3147. {
  3148. this->done();
  3149. auto ret = root;
  3150. root = nullptr;
  3151. return ret;
  3152. }