Markup.cpp 173 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495
  1. // Markup.cpp: implementation of the CMarkup class.
  2. //
  3. // Markup Release 11.5
  4. // Copyright (C) 2011 First Objective Software, Inc. All rights reserved
  5. // Go to www.firstobject.com for the latest CMarkup and EDOM documentation
  6. // Use in commercial applications requires written permission
  7. // This software is provided "as is", with no warranty.
  8. //
  9. #include <stdio.h>
  10. #include "Markup.h"
  11. #if defined(MCD_STRERROR) // C error routine
  12. #include <errno.h>
  13. #endif // C error routine
  14. #if defined (MARKUP_ICONV)
  15. #include <iconv.h>
  16. #endif
  17. #define x_ATTRIBQUOTE '\"' // can be double or single quote
  18. #if defined(MARKUP_STL) && ( defined(MARKUP_WINCONV) || (! defined(MCD_STRERROR)))
  19. #include <windows.h> // for MultiByteToWideChar, WideCharToMultiByte, FormatMessage
  20. #endif // need windows.h when STL and (not setlocale or not strerror), MFC afx.h includes it already
  21. #if defined(MARKUP_MBCS) // MBCS/double byte
  22. #pragma message( "Note: MBCS build (not UTF-8)" )
  23. // For UTF-8, remove MBCS from project settings C/C++ preprocessor definitions
  24. #if defined (MARKUP_WINCONV)
  25. #include <mbstring.h> // for VC++ _mbclen
  26. #endif // WINCONV
  27. #endif // MBCS/double byte
  28. #if defined(_DEBUG) && _MSC_VER > 1000 // VC++ DEBUG
  29. #undef THIS_FILE
  30. static char THIS_FILE[]=__FILE__;
  31. #if defined(DEBUG_NEW)
  32. #define new DEBUG_NEW
  33. #endif // DEBUG_NEW
  34. #endif // VC++ DEBUG
  35. // Disable "while ( 1 )" warning in VC++ 2002
  36. #if _MSC_VER >= 1300 // VC++ 2002 (7.0)
  37. #pragma warning(disable:4127)
  38. #endif // VC++ 2002 (7.0)
  39. //////////////////////////////////////////////////////////////////////
  40. // Internal static utility functions
  41. //
  42. void x_StrInsertReplace( MCD_STR& str, int nLeft, int nReplace, const MCD_STR& strInsert )
  43. {
  44. // Insert strInsert into str at nLeft replacing nReplace chars
  45. // Reduce reallocs on growing string by reserving string space
  46. // If realloc needed, allow for 1.5 times the new length
  47. //
  48. int nStrLength = MCD_STRLENGTH(str);
  49. int nInsLength = MCD_STRLENGTH(strInsert);
  50. int nNewLength = nInsLength + nStrLength - nReplace;
  51. int nAllocLen = MCD_STRCAPACITY(str);
  52. #if defined(MCD_STRINSERTREPLACE) // STL, replace method
  53. if ( nNewLength > nAllocLen )
  54. MCD_BLDRESERVE( str, (nNewLength + nNewLength/2 + 128) );
  55. MCD_STRINSERTREPLACE( str, nLeft, nReplace, strInsert );
  56. #else // MFC, no replace method
  57. int nBufferLen = nNewLength;
  58. if ( nNewLength > nAllocLen )
  59. nBufferLen += nBufferLen/2 + 128;
  60. MCD_CHAR* pDoc = MCD_GETBUFFER( str, nBufferLen );
  61. if ( nInsLength != nReplace && nLeft+nReplace < nStrLength )
  62. memmove( &pDoc[nLeft+nInsLength], &pDoc[nLeft+nReplace], (nStrLength-nLeft-nReplace)*sizeof(MCD_CHAR) );
  63. if ( nInsLength )
  64. memcpy( &pDoc[nLeft], strInsert, nInsLength*sizeof(MCD_CHAR) );
  65. MCD_RELEASEBUFFER( str, pDoc, nNewLength );
  66. #endif // MFC, no replace method
  67. }
  68. int x_Hash( MCD_PCSZ p, int nSize )
  69. {
  70. unsigned int n=0;
  71. while (*p)
  72. n += (unsigned int)(*p++);
  73. return n % nSize;
  74. }
  75. MCD_STR x_IntToStr( int n )
  76. {
  77. MCD_CHAR sz[25];
  78. MCD_SPRINTF(MCD_SSZ(sz),MCD_T("%d"),n);
  79. MCD_STR s=sz;
  80. return s;
  81. }
  82. int x_StrNCmp( MCD_PCSZ p1, MCD_PCSZ p2, int n, int bIgnoreCase = 0 )
  83. {
  84. // Fast string compare to determine equality
  85. if ( bIgnoreCase )
  86. {
  87. bool bNonAsciiFound = false;
  88. MCD_CHAR c1, c2;
  89. while ( n-- )
  90. {
  91. c1 = *p1++;
  92. c2 = *p2++;
  93. if ( c1 != c2 )
  94. {
  95. if ( bNonAsciiFound )
  96. return c1 - c2;
  97. if ( c1 >= 'a' && c1 <= 'z' )
  98. c1 = (MCD_CHAR)( c1 - ('a'-'A') );
  99. if ( c2 >= 'a' && c2 <= 'z' )
  100. c2 = (MCD_CHAR)( c2 - ('a'-'A') );
  101. if ( c1 != c2 )
  102. return c1 - c2;
  103. }
  104. else if ( (unsigned int)c1 > 127 )
  105. bNonAsciiFound = true;
  106. }
  107. }
  108. else
  109. {
  110. while ( n-- )
  111. {
  112. if ( *p1 != *p2 )
  113. return *p1 - *p2;
  114. p1++;
  115. p2++;
  116. }
  117. }
  118. return 0;
  119. }
  120. enum MarkupResultCode
  121. {
  122. MRC_COUNT = 1,
  123. MRC_TYPE = 2,
  124. MRC_NUMBER = 4,
  125. MRC_ENCODING = 8,
  126. MRC_LENGTH = 16,
  127. MRC_MODIFY = 32,
  128. MRC_MSG = 64
  129. };
  130. void x_AddResult( MCD_STR& strResult, MCD_CSTR pszID, MCD_CSTR pszVal = NULL, int nResultCode = 0, int n = -1, int n2 = -1 )
  131. {
  132. // Call this to append an error result to strResult, discard if accumulating too large
  133. if ( MCD_STRLENGTH(strResult) < 1000 )
  134. {
  135. // Use a temporary CMarkup object but keep strResult in a string to minimize memory footprint
  136. CMarkup mResult( strResult );
  137. if ( nResultCode & MRC_MODIFY )
  138. mResult.FindElem( pszID );
  139. else
  140. mResult.AddElem( pszID, MCD_T(""), CMarkup::MNF_WITHNOLINES );
  141. if ( pszVal.pcsz )
  142. {
  143. if ( nResultCode & MRC_TYPE )
  144. mResult.SetAttrib( MCD_T("type"), pszVal );
  145. else if ( nResultCode & MRC_ENCODING )
  146. mResult.SetAttrib( MCD_T("encoding"), pszVal );
  147. else if ( nResultCode & MRC_MSG )
  148. mResult.SetAttrib( MCD_T("msg"), pszVal );
  149. else
  150. mResult.SetAttrib( MCD_T("tagname"), pszVal );
  151. }
  152. if ( nResultCode & MRC_NUMBER )
  153. mResult.SetAttrib( MCD_T("n"), n );
  154. else if ( nResultCode & MRC_COUNT )
  155. mResult.SetAttrib( MCD_T("count"), n );
  156. else if ( nResultCode & MRC_LENGTH )
  157. mResult.SetAttrib( MCD_T("length"), n );
  158. else if ( n != -1 )
  159. mResult.SetAttrib( MCD_T("offset"), n );
  160. if ( n2 != -1 )
  161. mResult.SetAttrib( MCD_T("offset2"), n2 );
  162. strResult = mResult.GetDoc();
  163. }
  164. }
  165. //////////////////////////////////////////////////////////////////////
  166. // Encoding conversion struct and methods
  167. //
  168. struct TextEncoding
  169. {
  170. TextEncoding( MCD_CSTR pszFromEncoding, const void* pFromBuffer, int nFromBufferLen )
  171. {
  172. m_strFromEncoding = pszFromEncoding;
  173. m_pFrom = pFromBuffer;
  174. m_nFromLen = nFromBufferLen;
  175. m_nFailedChars = 0;
  176. m_nToCount = 0;
  177. };
  178. int PerformConversion( void* pTo, MCD_CSTR pszToEncoding = NULL );
  179. bool FindRaggedEnd( int& nTruncBeforeBytes );
  180. #if defined(MARKUP_ICONV)
  181. static const char* IConvName( char* szEncoding, MCD_CSTR pszEncoding );
  182. int IConv( void* pTo, int nToCharSize, int nFromCharSize );
  183. #endif // ICONV
  184. #if ! defined(MARKUP_WCHAR)
  185. static bool CanConvert( MCD_CSTR pszToEncoding, MCD_CSTR pszFromEncoding );
  186. #endif // WCHAR
  187. MCD_STR m_strToEncoding;
  188. MCD_STR m_strFromEncoding;
  189. const void* m_pFrom;
  190. int m_nFromLen;
  191. int m_nToCount;
  192. int m_nFailedChars;
  193. };
  194. // Encoding names
  195. // This is a precompiled ASCII hash table for speed and minimum memory requirement
  196. // Each entry consists of a 2 digit name length, 5 digit code page, and the encoding name
  197. // Each table slot can have multiple entries, table size 155 was chosen for even distribution
  198. //
  199. MCD_PCSZ EncodingNameTable[155] =
  200. {
  201. MCD_T("0800949ksc_5601"),MCD_T("1920932cseucpkdfmtjapanese0920003x-cp20003"),
  202. MCD_T("1250221_iso-2022-jp0228591l10920004x-cp20004"),
  203. MCD_T("0228592l20920005x-cp20005"),
  204. MCD_T("0228593l30600850ibm8501000858ccsid00858"),
  205. MCD_T("0228594l40600437ibm4370701201ucs-2be0600860ibm860"),
  206. MCD_T("0600852ibm8520501250ms-ee0600861ibm8610228599l50751932cp51932"),
  207. MCD_T("0600862ibm8620620127ibm3670700858cp008581010021x-mac-thai0920261x-cp20261"),
  208. MCD_T("0600737ibm7370500869cp-gr1057003x-iscii-be0600863ibm863"),
  209. MCD_T("0750221ms502210628591ibm8190600855ibm8550600864ibm864"),
  210. MCD_T("0600775ibm7751057002x-iscii-de0300949uhc0228605l91028591iso-ir-1000600865ibm865"),
  211. MCD_T("1028594iso-ir-1101028592iso-ir-1010600866ibm8660500861cp-is0600857ibm857"),
  212. MCD_T("0950227x-cp50227"),
  213. MCD_T("0320866koi1628598csisolatinhebrew1057008x-iscii-ka"),
  214. MCD_T("1000950big5-hkscs1220106x-ia5-german0600869ibm869"),
  215. MCD_T("1057009x-iscii-ma0701200ucs-2le0712001utf32be0920269x-cp20269"),
  216. MCD_T("0800708asmo-7080500437cspc81765000unicode-1-1-utf-70612000utf-320920936x-cp20936"),
  217. MCD_T("1200775ebcdic-cp-be0628598hebrew0701201utf16be1765001unicode-1-1-utf-81765001unicode-2-0-utf-80551932x-euc"),
  218. MCD_T("1028595iso-ir-1441028597iso-ir-1260728605latin-90601200utf-161057011x-iscii-pa"),
  219. MCD_T("1028596iso-ir-1271028593iso-ir-1090751932ms51932"),
  220. MCD_T("0801253ms-greek0600949korean1050225iso2022-kr1128605iso_8859-150920949x-cp20949"),
  221. MCD_T("1200775ebcdic-cp-ch1028598iso-ir-1381057006x-iscii-as1450221iso-2022-jp-ms"),
  222. MCD_T("1057004x-iscii-ta1028599iso-ir-148"),
  223. MCD_T("1000949iso-ir-1490820127us-ascii"),MCD_T(""),
  224. MCD_T("1000936gb_2312-801900850cspc850multilingual0712000utf32le"),
  225. MCD_T("1057005x-iscii-te1300949csksc560119871965000x-unicode-2-0-utf-7"),
  226. MCD_T("0701200utf16le1965001x-unicode-2-0-utf-80928591iso8859-1"),
  227. MCD_T("0928592iso8859-21420002x_chinese-eten0520866koi8r1000932x-ms-cp932"),
  228. MCD_T("1320000x-chinese-cns1138598iso8859-8-i1057010x-iscii-gu0928593iso8859-3"),
  229. MCD_T("0928594iso8859-4"),MCD_T("0928595iso8859-51150221csiso2022jp"),
  230. MCD_T("0928596iso8859-60900154csptcp154"),
  231. MCD_T("0928597iso8859-70900932shift_jis1400154cyrillic-asian"),
  232. MCD_T("0928598iso8859-81057007x-iscii-or1150225csiso2022kr"),
  233. MCD_T("0721866koi8-ru0928599iso8859-9"),MCD_T("0910000macintosh"),MCD_T(""),
  234. MCD_T(""),MCD_T(""),
  235. MCD_T("1210004x-mac-arabic0800936gb2312800628598visual1520108x-ia5-norwegian"),
  236. MCD_T(""),MCD_T("0829001x-europa"),MCD_T(""),MCD_T("1510079x-mac-icelandic"),
  237. MCD_T("0800932sjis-win1128591csisolatin1"),MCD_T("1128592csisolatin2"),
  238. MCD_T("1400949ks_c_5601-19871128593csisolatin3"),MCD_T("1128594csisolatin4"),
  239. MCD_T("0400950big51128595csisolatin51400949ks_c_5601-1989"),
  240. MCD_T("0500775cp5001565000csunicode11utf7"),MCD_T("0501361johab"),
  241. MCD_T("1100932windows-9321100437codepage437"),
  242. MCD_T("1800862cspc862latinhebrew1310081x-mac-turkish"),MCD_T(""),
  243. MCD_T("0701256ms-arab0800775csibm5000500154cp154"),
  244. MCD_T("1100936windows-9360520127ascii"),
  245. MCD_T("1528597csisolatingreek1100874windows-874"),MCD_T("0500850cp850"),
  246. MCD_T("0700720dos-7200500950cp9500500932cp9320500437cp4370500860cp8601650222_iso-2022-jp$sio"),
  247. MCD_T("0500852cp8520500861cp8610700949ksc56010812001utf-32be"),
  248. MCD_T("0528597greek0500862cp8620520127cp3670500853cp853"),
  249. MCD_T("0500737cp7371150220iso-2022-jp0801201utf-16be0500863cp863"),
  250. MCD_T("0500936cp9360528591cp8194520932extended_unix_code_packed_format_for_japanese0500855cp8550500864cp864"),
  251. MCD_T("0500775cp7750500874cp8740800860csibm8600500865cp865"),
  252. MCD_T("0500866cp8660800861csibm8611150225iso-2022-kr0500857cp8571101201unicodefffe"),
  253. MCD_T("0700862dos-8620701255ms-hebr0500858cp858"),
  254. MCD_T("1210005x-mac-hebrew0500949cp9490800863csibm863"),
  255. MCD_T("0500869cp8691600437cspc8codepage4370700874tis-6200800855csibm8550800864csibm864"),
  256. MCD_T("0800950x-x-big50420866koi80800932ms_kanji0700874dos-8740800865csibm865"),
  257. MCD_T("0800866csibm8661210003x-mac-korean0800857csibm8570812000utf-32le"),
  258. MCD_T(""),MCD_T("0500932ms9320801200utf-16le1028591iso-8859-10500154pt154"),
  259. MCD_T("1028592iso-8859-20620866koi8-r0800869csibm869"),
  260. MCD_T("1500936csiso58gb2312800828597elot_9281238598iso-8859-8-i1028593iso-8859-30820127iso-ir-6"),
  261. MCD_T("1028594iso-8859-4"),
  262. MCD_T("0800852cspcp8520500936ms9361028595iso-8859-50621866koi8-u0701252ms-ansi"),
  263. MCD_T("1028596iso-8859-60220127us2400858pc-multilingual-850+euro"),
  264. MCD_T("1028597iso-8859-71028603iso8859-13"),
  265. MCD_T("1320000x-chinese_cns1028598iso-8859-8"),
  266. MCD_T("1828595csisolatincyrillic1028605iso8859-151028599iso-8859-9"),
  267. MCD_T("0465001utf8"),MCD_T("1510017x-mac-ukrainian"),MCD_T(""),
  268. MCD_T("0828595cyrillic"),MCD_T("0900936gb2312-80"),MCD_T(""),
  269. MCD_T("0720866cskoi8r1528591iso_8859-1:1987"),MCD_T("1528592iso_8859-2:1987"),
  270. MCD_T("1354936iso-4873:1986"),MCD_T("0700932sjis-ms1528593iso_8859-3:1988"),
  271. MCD_T("1528594iso_8859-4:19880600936gb23120701251ms-cyrl"),
  272. MCD_T("1528596iso_8859-6:19871528595iso_8859-5:1988"),
  273. MCD_T("1528597iso_8859-7:1987"),
  274. MCD_T("1201250windows-12501300932shifft_jis-ms"),
  275. MCD_T("0810029x-mac-ce1201251windows-12511528598iso_8859-8:19880900949ks_c_56011110000csmacintosh"),
  276. MCD_T("0601200cp12001201252windows-1252"),
  277. MCD_T("1052936hz-gb-23121201253windows-12531400949ks_c_5601_19871528599iso_8859-9:19890601201cp1201"),
  278. MCD_T("1201254windows-1254"),MCD_T("1000936csgb2312801201255windows-1255"),
  279. MCD_T("1201256windows-12561100932windows-31j"),
  280. MCD_T("1201257windows-12570601250cp12500601133cp1133"),
  281. MCD_T("0601251cp12511201258windows-12580601125cp1125"),
  282. MCD_T("0701254ms-turk0601252cp1252"),MCD_T("0601253cp12530601361cp1361"),
  283. MCD_T("0800949ks-c56010601254cp1254"),MCD_T("0651936euc-cn0601255cp1255"),
  284. MCD_T("0601256cp1256"),MCD_T("0601257cp12570600950csbig50800858ibm00858"),
  285. MCD_T("0601258cp1258"),MCD_T("0520105x-ia5"),
  286. MCD_T("0801250x-cp12501110006x-mac-greek0738598logical"),
  287. MCD_T("0801251x-cp1251"),MCD_T(""),
  288. MCD_T("1410001x-mac-japanese1200932cswindows31j"),
  289. MCD_T("0700936chinese0720127csascii0620932euc-jp"),
  290. MCD_T("0851936x-euc-cn0501200ucs-2"),MCD_T("0628597greek8"),
  291. MCD_T("0651949euc-kr"),MCD_T(""),MCD_T("0628591latin1"),
  292. MCD_T("0628592latin21100874iso-8859-11"),
  293. MCD_T("0628593latin31420127ansi_x3.4-19681420127ansi_x3.4-19861028591iso_8859-1"),
  294. MCD_T("0628594latin41028592iso_8859-20701200unicode1128603iso-8859-13"),
  295. MCD_T("1028593iso_8859-30628599latin51410082x-mac-croatian"),
  296. MCD_T("1028594iso_8859-41128605iso-8859-150565000utf-70851932x-euc-jp"),
  297. MCD_T("1300775cspc775baltic1028595iso_8859-50565001utf-80512000utf32"),
  298. MCD_T("1028596iso_8859-61710002x-mac-chinesetrad0601252x-ansi"),
  299. MCD_T("1028597iso_8859-70628605latin90501200utf160700154ptcp1541410010x-mac-romanian"),
  300. MCD_T("0900936iso-ir-581028598iso_8859-8"),MCD_T("1028599iso_8859-9"),
  301. MCD_T("1350221iso2022-jp-ms0400932sjis"),MCD_T("0751949cseuckr"),
  302. MCD_T("1420002x-chinese-eten"),MCD_T("1410007x-mac-cyrillic"),
  303. MCD_T("1000932shifft_jis"),MCD_T("0828596ecma-114"),MCD_T(""),
  304. MCD_T("0900932shift-jis"),MCD_T("0701256cp1256 1320107x-ia5-swedish"),
  305. MCD_T("0828597ecma-118"),
  306. MCD_T("1628596csisolatinarabic1710008x-mac-chinesesimp0600932x-sjis"),MCD_T(""),
  307. MCD_T("0754936gb18030"),MCD_T("1350221windows-502210712000cp12000"),
  308. MCD_T("0628596arabic0500936cn-gb0900932sjis-open0712001cp12001"),MCD_T(""),
  309. MCD_T(""),MCD_T("0700950cn-big50920127iso646-us1001133ibm-cp1133"),MCD_T(""),
  310. MCD_T("0800936csgb23120900949ks-c-56010310000mac"),
  311. MCD_T("1001257winbaltrim0750221cp502211020127iso-ir-6us"),
  312. MCD_T("1000932csshiftjis"),MCD_T("0300936gbk0765001cp65001"),
  313. MCD_T("1620127iso_646.irv:19911351932windows-519320920001x-cp20001")
  314. };
  315. int x_GetEncodingCodePage( MCD_CSTR pszEncoding )
  316. {
  317. // redo for completeness, the iconv set, UTF-32, and uppercase
  318. // Lookup strEncoding in EncodingNameTable and return Windows code page
  319. int nCodePage = -1;
  320. int nEncLen = MCD_PSZLEN( pszEncoding );
  321. if ( ! nEncLen )
  322. nCodePage = MCD_ACP;
  323. else if ( x_StrNCmp(pszEncoding,MCD_T("UTF-32"),6) == 0 )
  324. nCodePage = MCD_UTF32;
  325. else if ( nEncLen < 100 )
  326. {
  327. MCD_CHAR szEncodingLower[100];
  328. for ( int nEncChar=0; nEncChar<nEncLen; ++nEncChar )
  329. {
  330. MCD_CHAR cEncChar = pszEncoding[nEncChar];
  331. szEncodingLower[nEncChar] = (cEncChar>='A' && cEncChar<='Z')? (MCD_CHAR)(cEncChar+('a'-'A')) : cEncChar;
  332. }
  333. szEncodingLower[nEncLen] = '\0';
  334. MCD_PCSZ pEntry = EncodingNameTable[x_Hash(szEncodingLower,sizeof(EncodingNameTable)/sizeof(MCD_PCSZ))];
  335. while ( *pEntry )
  336. {
  337. // e.g. entry: 0565001utf-8 means length 05, code page 65001, encoding name utf-8
  338. int nEntryLen = (*pEntry - '0') * 10;
  339. ++pEntry;
  340. nEntryLen += (*pEntry - '0');
  341. ++pEntry;
  342. MCD_PCSZ pCodePage = pEntry;
  343. pEntry += 5;
  344. if ( nEntryLen == nEncLen && x_StrNCmp(szEncodingLower,pEntry,nEntryLen) == 0 )
  345. {
  346. // Convert digits to integer up to code name which always starts with alpha
  347. nCodePage = MCD_PSZTOL( pCodePage, NULL, 10 );
  348. break;
  349. }
  350. pEntry += nEntryLen;
  351. }
  352. }
  353. return nCodePage;
  354. }
  355. #if ! defined(MARKUP_WCHAR)
  356. bool TextEncoding::CanConvert( MCD_CSTR pszToEncoding, MCD_CSTR pszFromEncoding )
  357. {
  358. // Return true if MB to MB conversion is possible
  359. #if defined(MARKUP_ICONV)
  360. // iconv_open should fail if either encoding not supported or one is alias for other
  361. char szTo[100], szFrom[100];
  362. iconv_t cd = iconv_open( IConvName(szTo,pszToEncoding), IConvName(szFrom,pszFromEncoding) );
  363. if ( cd == (iconv_t)-1 )
  364. return false;
  365. iconv_close(cd);
  366. #else
  367. int nToCP = x_GetEncodingCodePage( pszToEncoding );
  368. int nFromCP = x_GetEncodingCodePage( pszFromEncoding );
  369. if ( nToCP == -1 || nFromCP == -1 )
  370. return false;
  371. #if defined(MARKUP_WINCONV)
  372. if ( nToCP == MCD_ACP || nFromCP == MCD_ACP ) // either ACP ANSI?
  373. {
  374. int nACP = GetACP();
  375. if ( nToCP == MCD_ACP )
  376. nToCP = nACP;
  377. if ( nFromCP == MCD_ACP )
  378. nFromCP = nACP;
  379. }
  380. #else // no conversion API, but we can do AToUTF8 and UTF8ToA
  381. if ( nToCP != MCD_UTF8 && nFromCP != MCD_UTF8 ) // either UTF-8?
  382. return false;
  383. #endif // no conversion API
  384. if ( nToCP == nFromCP )
  385. return false;
  386. #endif // not ICONV
  387. return true;
  388. }
  389. #endif // not WCHAR
  390. #if defined(MARKUP_ICONV)
  391. const char* TextEncoding::IConvName( char* szEncoding, MCD_CSTR pszEncoding )
  392. {
  393. // Make upper case char-based name from strEncoding which consists only of characters in the ASCII range
  394. int nEncChar = 0;
  395. while ( pszEncoding[nEncChar] )
  396. {
  397. char cEncChar = (char)pszEncoding[nEncChar];
  398. szEncoding[nEncChar] = (cEncChar>='a' && cEncChar<='z')? (cEncChar-('a'-'A')) : cEncChar;
  399. ++nEncChar;
  400. }
  401. if ( nEncChar == 6 && x_StrNCmp(szEncoding,"UTF-16",6) == 0 )
  402. {
  403. szEncoding[nEncChar++] = 'B';
  404. szEncoding[nEncChar++] = 'E';
  405. }
  406. szEncoding[nEncChar] = '\0';
  407. return szEncoding;
  408. }
  409. int TextEncoding::IConv( void* pTo, int nToCharSize, int nFromCharSize )
  410. {
  411. // Converts from m_pFrom to pTo
  412. char szTo[100], szFrom[100];
  413. iconv_t cd = iconv_open( IConvName(szTo,m_strToEncoding), IConvName(szFrom,m_strFromEncoding) );
  414. int nToLenBytes = 0;
  415. if ( cd != (iconv_t)-1 )
  416. {
  417. size_t nFromLenRemaining = (size_t)m_nFromLen * nFromCharSize;
  418. size_t nToCountRemaining = (size_t)m_nToCount * nToCharSize;
  419. size_t nToCountRemainingBefore;
  420. char* pToChar = (char*)pTo;
  421. char* pFromChar = (char*)m_pFrom;
  422. char* pToTempBuffer = NULL;
  423. const size_t nTempBufferSize = 2048;
  424. size_t nResult;
  425. if ( ! pTo )
  426. {
  427. pToTempBuffer = new char[nTempBufferSize];
  428. pToChar = pToTempBuffer;
  429. nToCountRemaining = nTempBufferSize;
  430. }
  431. while ( nFromLenRemaining )
  432. {
  433. nToCountRemainingBefore = nToCountRemaining;
  434. nResult = iconv( cd, &pFromChar, &nFromLenRemaining, &pToChar, &nToCountRemaining );
  435. nToLenBytes += (int)(nToCountRemainingBefore - nToCountRemaining);
  436. if ( nResult == (size_t)-1 )
  437. {
  438. int nErrno = errno;
  439. if ( nErrno == EILSEQ )
  440. {
  441. // Bypass bad char, question mark denotes problem in source string
  442. pFromChar += nFromCharSize;
  443. nFromLenRemaining -= nFromCharSize;
  444. if ( nToCharSize == 1 )
  445. *pToChar = '?';
  446. else if ( nToCharSize == 2 )
  447. *((unsigned short*)pToChar) = (unsigned short)'?';
  448. else if ( nToCharSize == 4 )
  449. *((unsigned int*)pToChar) = (unsigned int)'?';
  450. pToChar += nToCharSize;
  451. nToCountRemaining -= nToCharSize;
  452. nToLenBytes += nToCharSize;
  453. size_t nInitFromLen = 0, nInitToCount = 0;
  454. iconv(cd, NULL, &nInitFromLen ,NULL, &nInitToCount );
  455. }
  456. else if ( nErrno == EINVAL )
  457. break; // incomplete character or shift sequence at end of input
  458. else if ( nErrno == E2BIG && !pToTempBuffer )
  459. break; // output buffer full should only happen when using a temp buffer
  460. }
  461. else
  462. m_nFailedChars += nResult;
  463. if ( pToTempBuffer && nToCountRemaining < 10 )
  464. {
  465. nToCountRemaining = nTempBufferSize;
  466. pToChar = pToTempBuffer;
  467. }
  468. }
  469. if ( pToTempBuffer )
  470. delete[] pToTempBuffer;
  471. iconv_close(cd);
  472. }
  473. return nToLenBytes / nToCharSize;
  474. }
  475. #endif
  476. #if defined(MARKUP_WINCONV)
  477. bool x_NoDefaultChar( int nCP )
  478. {
  479. // WideCharToMultiByte fails if lpUsedDefaultChar is non-NULL for these code pages:
  480. return (bool)(nCP == 65000 || nCP == 65001 || nCP == 50220 || nCP == 50221 || nCP == 50222 || nCP == 50225 ||
  481. nCP == 50227 || nCP == 50229 || nCP == 52936 || nCP == 54936 || (nCP >= 57002 && nCP <= 57011) );
  482. }
  483. #endif
  484. int TextEncoding::PerformConversion( void* pTo, MCD_CSTR pszToEncoding/*=NULL*/ )
  485. {
  486. // If pTo is not NULL, it must be large enough to hold result, length of result is returned
  487. // m_nFailedChars will be set to >0 if characters not supported in strToEncoding
  488. int nToLen = 0;
  489. if ( pszToEncoding.pcsz )
  490. m_strToEncoding = pszToEncoding;
  491. int nToCP = x_GetEncodingCodePage( m_strToEncoding );
  492. if ( nToCP == -1 )
  493. nToCP = MCD_ACP;
  494. int nFromCP = x_GetEncodingCodePage( m_strFromEncoding );
  495. if ( nFromCP == -1 )
  496. nFromCP = MCD_ACP;
  497. m_nFailedChars = 0;
  498. #if ! defined(MARKUP_WINCONV) && ! defined(MARKUP_ICONV)
  499. // Only non-Unicode encoding supported is locale charset, must call setlocale
  500. if ( nToCP != MCD_UTF8 && nToCP != MCD_UTF16 && nToCP != MCD_UTF32 )
  501. nToCP = MCD_ACP;
  502. if ( nFromCP != MCD_UTF8 && nFromCP != MCD_UTF16 && nFromCP != MCD_UTF32 )
  503. nFromCP = MCD_ACP;
  504. if ( nFromCP == MCD_ACP )
  505. {
  506. const char* pA = (const char*)m_pFrom;
  507. int nALenRemaining = m_nFromLen;
  508. int nCharLen;
  509. wchar_t wcChar;
  510. char* pU = (char*)pTo;
  511. while ( nALenRemaining )
  512. {
  513. nCharLen = mbtowc( &wcChar, pA, nALenRemaining );
  514. if ( nCharLen < 1 )
  515. {
  516. wcChar = (wchar_t)'?';
  517. nCharLen = 1;
  518. }
  519. pA += nCharLen;
  520. nALenRemaining -= nCharLen;
  521. if ( nToCP == MCD_UTF8 )
  522. CMarkup::EncodeCharUTF8( (int)wcChar, pU, nToLen );
  523. else if ( nToCP == MCD_UTF16 )
  524. CMarkup::EncodeCharUTF16( (int)wcChar, (unsigned short*)pU, nToLen );
  525. else // UTF32
  526. {
  527. if ( pU )
  528. ((unsigned int*)pU)[nToLen] = (unsigned int)wcChar;
  529. ++nToLen;
  530. }
  531. }
  532. }
  533. else if ( nToCP == MCD_ACP )
  534. {
  535. union pUnicodeUnion { const char* p8; const unsigned short* p16; const unsigned int* p32; } pU;
  536. pU.p8 = (const char*)m_pFrom;
  537. const char* pUEnd = pU.p8 + m_nFromLen;
  538. if ( nFromCP == MCD_UTF16 )
  539. pUEnd = (char*)( pU.p16 + m_nFromLen );
  540. else if ( nFromCP == MCD_UTF32 )
  541. pUEnd = (char*)( pU.p32 + m_nFromLen );
  542. int nCharLen;
  543. char* pA = (char*)pTo;
  544. char szA[8];
  545. int nUChar;
  546. while ( pU.p8 != pUEnd )
  547. {
  548. if ( nFromCP == MCD_UTF8 )
  549. nUChar = CMarkup::DecodeCharUTF8( pU.p8, pUEnd );
  550. else if ( nFromCP == MCD_UTF16 )
  551. nUChar = CMarkup::DecodeCharUTF16( pU.p16, (const unsigned short*)pUEnd );
  552. else // UTF32
  553. nUChar = *(pU.p32)++;
  554. if ( nUChar == -1 )
  555. nCharLen = -2;
  556. else if ( nUChar & ~0xffff )
  557. nCharLen = -1;
  558. else
  559. nCharLen = wctomb( pA?pA:szA, (wchar_t)nUChar );
  560. if ( nCharLen < 0 )
  561. {
  562. if ( nCharLen == -1 )
  563. ++m_nFailedChars;
  564. nCharLen = 1;
  565. if ( pA )
  566. *pA = '?';
  567. }
  568. if ( pA )
  569. pA += nCharLen;
  570. nToLen += nCharLen;
  571. }
  572. }
  573. #endif // not WINCONV and not ICONV
  574. if ( nFromCP == MCD_UTF32 )
  575. {
  576. const unsigned int* p32 = (const unsigned int*)m_pFrom;
  577. const unsigned int* p32End = p32 + m_nFromLen;
  578. if ( nToCP == MCD_UTF8 )
  579. {
  580. char* p8 = (char*)pTo;
  581. while ( p32 != p32End )
  582. CMarkup::EncodeCharUTF8( *p32++, p8, nToLen );
  583. }
  584. else if ( nToCP == MCD_UTF16 )
  585. {
  586. unsigned short* p16 = (unsigned short*)pTo;
  587. while ( p32 != p32End )
  588. CMarkup::EncodeCharUTF16( (int)*p32++, p16, nToLen );
  589. }
  590. else // to ANSI
  591. {
  592. // WINCONV not supported for 32To8, since only used for sizeof(wchar_t) == 4
  593. #if defined(MARKUP_ICONV)
  594. nToLen = IConv( pTo, 1, 4 );
  595. #endif // ICONV
  596. }
  597. }
  598. else if ( nFromCP == MCD_UTF16 )
  599. {
  600. // UTF16To8 will be deprecated since weird output buffer size sensitivity not worth implementing here
  601. const unsigned short* p16 = (const unsigned short*)m_pFrom;
  602. const unsigned short* p16End = p16 + m_nFromLen;
  603. int nUChar;
  604. if ( nToCP == MCD_UTF32 )
  605. {
  606. unsigned int* p32 = (unsigned int*)pTo;
  607. while ( p16 != p16End )
  608. {
  609. nUChar = CMarkup::DecodeCharUTF16( p16, p16End );
  610. if ( nUChar == -1 )
  611. nUChar = '?';
  612. if ( p32 )
  613. p32[nToLen] = (unsigned int)nUChar;
  614. ++nToLen;
  615. }
  616. }
  617. #if defined(MARKUP_WINCONV)
  618. else // to UTF-8 or other multi-byte
  619. {
  620. nToLen = WideCharToMultiByte(nToCP,0,(const wchar_t*)m_pFrom,m_nFromLen,(char*)pTo,
  621. m_nToCount?m_nToCount+1:0,NULL,x_NoDefaultChar(nToCP)?NULL:&m_nFailedChars);
  622. }
  623. #else // not WINCONV
  624. else if ( nToCP == MCD_UTF8 )
  625. {
  626. char* p8 = (char*)pTo;
  627. while ( p16 != p16End )
  628. {
  629. nUChar = CMarkup::DecodeCharUTF16( p16, p16End );
  630. if ( nUChar == -1 )
  631. nUChar = '?';
  632. CMarkup::EncodeCharUTF8( nUChar, p8, nToLen );
  633. }
  634. }
  635. else // to ANSI
  636. {
  637. #if defined(MARKUP_ICONV)
  638. nToLen = IConv( pTo, 1, 2 );
  639. #endif // ICONV
  640. }
  641. #endif // not WINCONV
  642. }
  643. else if ( nToCP == MCD_UTF16 ) // to UTF-16 from UTF-8/ANSI
  644. {
  645. #if defined(MARKUP_WINCONV)
  646. nToLen = MultiByteToWideChar(nFromCP,0,(const char*)m_pFrom,m_nFromLen,(wchar_t*)pTo,m_nToCount);
  647. #else // not WINCONV
  648. if ( nFromCP == MCD_UTF8 )
  649. {
  650. const char* p8 = (const char*)m_pFrom;
  651. const char* p8End = p8 + m_nFromLen;
  652. int nUChar;
  653. unsigned short* p16 = (unsigned short*)pTo;
  654. while ( p8 != p8End )
  655. {
  656. nUChar = CMarkup::DecodeCharUTF8( p8, p8End );
  657. if ( nUChar == -1 )
  658. nUChar = '?';
  659. if ( p16 )
  660. p16[nToLen] = (unsigned short)nUChar;
  661. ++nToLen;
  662. }
  663. }
  664. else // from ANSI
  665. {
  666. #if defined(MARKUP_ICONV)
  667. nToLen = IConv( pTo, 2, 1 );
  668. #endif // ICONV
  669. }
  670. #endif // not WINCONV
  671. }
  672. else if ( nToCP == MCD_UTF32 ) // to UTF-32 from UTF-8/ANSI
  673. {
  674. if ( nFromCP == MCD_UTF8 )
  675. {
  676. const char* p8 = (const char*)m_pFrom;
  677. const char* p8End = p8 + m_nFromLen;
  678. int nUChar;
  679. unsigned int* p32 = (unsigned int*)pTo;
  680. while ( p8 != p8End )
  681. {
  682. nUChar = CMarkup::DecodeCharUTF8( p8, p8End );
  683. if ( nUChar == -1 )
  684. nUChar = '?';
  685. if ( p32 )
  686. p32[nToLen] = (unsigned int)nUChar;
  687. ++nToLen;
  688. }
  689. }
  690. else // from ANSI
  691. {
  692. // WINCONV not supported for ATo32, since only used for sizeof(wchar_t) == 4
  693. #if defined(MARKUP_ICONV)
  694. // nToLen = IConv( pTo, 4, 1 );
  695. // Linux: had trouble getting IConv to leave the BOM off of the UTF-32 output stream
  696. // So converting via UTF-16 with native endianness
  697. unsigned short* pwszUTF16 = new unsigned short[m_nFromLen];
  698. MCD_STR strToEncoding = m_strToEncoding;
  699. m_strToEncoding = MCD_T("UTF-16BE");
  700. short nEndianTest = 1;
  701. if ( ((char*)&nEndianTest)[0] ) // Little-endian?
  702. m_strToEncoding = MCD_T("UTF-16LE");
  703. m_nToCount = m_nFromLen;
  704. int nUTF16Len = IConv( pwszUTF16, 2, 1 );
  705. m_strToEncoding = strToEncoding;
  706. const unsigned short* p16 = (const unsigned short*)pwszUTF16;
  707. const unsigned short* p16End = p16 + nUTF16Len;
  708. int nUChar;
  709. unsigned int* p32 = (unsigned int*)pTo;
  710. while ( p16 != p16End )
  711. {
  712. nUChar = CMarkup::DecodeCharUTF16( p16, p16End );
  713. if ( nUChar == -1 )
  714. nUChar = '?';
  715. if ( p32 )
  716. *p32++ = (unsigned int)nUChar;
  717. ++nToLen;
  718. }
  719. delete[] pwszUTF16;
  720. #endif // ICONV
  721. }
  722. }
  723. else
  724. {
  725. #if defined(MARKUP_ICONV)
  726. nToLen = IConv( pTo, 1, 1 );
  727. #elif defined(MARKUP_WINCONV)
  728. wchar_t* pwszUTF16 = new wchar_t[m_nFromLen];
  729. int nUTF16Len = MultiByteToWideChar(nFromCP,0,(const char*)m_pFrom,m_nFromLen,pwszUTF16,m_nFromLen);
  730. nToLen = WideCharToMultiByte(nToCP,0,pwszUTF16,nUTF16Len,(char*)pTo,m_nToCount,NULL,
  731. x_NoDefaultChar(nToCP)?NULL:&m_nFailedChars);
  732. delete[] pwszUTF16;
  733. #endif // WINCONV
  734. }
  735. // Store the length in case this is called again after allocating output buffer to fit
  736. m_nToCount = nToLen;
  737. return nToLen;
  738. }
  739. bool TextEncoding::FindRaggedEnd( int& nTruncBeforeBytes )
  740. {
  741. // Check for ragged end UTF-16 or multi-byte according to m_strToEncoding, expects at least 40 bytes to work with
  742. bool bSuccess = true;
  743. nTruncBeforeBytes = 0;
  744. int nCP = x_GetEncodingCodePage( m_strFromEncoding );
  745. if ( nCP == MCD_UTF16 )
  746. {
  747. unsigned short* pUTF16Buffer = (unsigned short*)m_pFrom;
  748. const unsigned short* pUTF16Last = &pUTF16Buffer[m_nFromLen-1];
  749. if ( CMarkup::DecodeCharUTF16(pUTF16Last,&pUTF16Buffer[m_nFromLen]) == -1 )
  750. nTruncBeforeBytes = 2;
  751. }
  752. else // UTF-8, SBCS DBCS
  753. {
  754. if ( nCP == MCD_UTF8 )
  755. {
  756. char* pUTF8Buffer = (char*)m_pFrom;
  757. char* pUTF8End = &pUTF8Buffer[m_nFromLen];
  758. int nLast = m_nFromLen - 1;
  759. const char* pUTF8Last = &pUTF8Buffer[nLast];
  760. while ( nLast > 0 && CMarkup::DecodeCharUTF8(pUTF8Last,pUTF8End) == -1 )
  761. pUTF8Last = &pUTF8Buffer[--nLast];
  762. nTruncBeforeBytes = (int)(pUTF8End - pUTF8Last);
  763. }
  764. else
  765. {
  766. // Do a conversion-based test unless we can determine it is not multi-byte
  767. // If m_strEncoding="" default code page then GetACP can tell us the code page, otherwise just do the test
  768. #if defined(MARKUP_WINCONV)
  769. if ( nCP == 0 )
  770. nCP = GetACP();
  771. #endif
  772. int nMultibyteCharsToTest = 2;
  773. switch ( nCP )
  774. {
  775. case 54936:
  776. nMultibyteCharsToTest = 4;
  777. case 932: case 51932: case 20932: case 50220: case 50221: case 50222: case 10001: // Japanese
  778. case 949: case 51949: case 50225: case 1361: case 10003: case 20949: // Korean
  779. case 874: case 20001: case 20004: case 10021: case 20003: // Taiwan
  780. case 50930: case 50939: case 50931: case 50933: case 20833: case 50935: case 50937: // EBCDIC
  781. case 936: case 51936: case 20936: case 52936: // Chinese
  782. case 950: case 50227: case 10008: case 20000: case 20002: case 10002: // Chinese
  783. nCP = 0;
  784. break;
  785. }
  786. if ( nMultibyteCharsToTest > m_nFromLen )
  787. nMultibyteCharsToTest = m_nFromLen;
  788. if ( nCP == 0 && nMultibyteCharsToTest )
  789. {
  790. /*
  791. 1. convert the piece to Unicode with MultiByteToWideChar
  792. 2. Identify at least two Unicode code point boundaries at the end of
  793. the converted piece by stepping backwards from the end and re-
  794. converting the final 2 bytes, 3 bytes, 4 bytes etc, comparing the
  795. converted end string to the end of the entire converted piece to find
  796. a valid code point boundary.
  797. 3. Upon finding a code point boundary, I still want to make sure it
  798. will convert the same separately on either side of the divide as it
  799. does together, so separately convert the first byte and the remaining
  800. bytes and see if the result together is the same as the whole end, if
  801. not try the first two bytes and the remaining bytes. etc., until I
  802. find a useable dividing point. If none found, go back to step 2 and
  803. get a longer end string to try.
  804. */
  805. m_strToEncoding = MCD_T("UTF-16");
  806. m_nToCount = m_nFromLen*2;
  807. unsigned short* pUTF16Buffer = new unsigned short[m_nToCount];
  808. int nUTF16Len = PerformConversion( (void*)pUTF16Buffer );
  809. int nOriginalByteLen = m_nFromLen;
  810. // Guaranteed to have at least MARKUP_FILEBLOCKSIZE/2 bytes to work with
  811. const int nMaxBytesToTry = 40;
  812. unsigned short wsz16End[nMaxBytesToTry*2];
  813. unsigned short wsz16EndDivided[nMaxBytesToTry*2];
  814. const char* pszOriginalBytes = (const char*)m_pFrom;
  815. int nBoundariesFound = 0;
  816. bSuccess = false;
  817. while ( nTruncBeforeBytes < nMaxBytesToTry && ! bSuccess )
  818. {
  819. ++nTruncBeforeBytes;
  820. m_pFrom = &pszOriginalBytes[nOriginalByteLen-nTruncBeforeBytes];
  821. m_nFromLen = nTruncBeforeBytes;
  822. m_nToCount = nMaxBytesToTry*2;
  823. int nEndUTF16Len = PerformConversion( (void*)wsz16End );
  824. if ( nEndUTF16Len && memcmp(wsz16End,&pUTF16Buffer[nUTF16Len-nEndUTF16Len],nEndUTF16Len*2) == 0 )
  825. {
  826. ++nBoundariesFound;
  827. if ( nBoundariesFound > 2 )
  828. {
  829. int nDivideAt = 1;
  830. while ( nDivideAt < nTruncBeforeBytes )
  831. {
  832. m_pFrom = &pszOriginalBytes[nOriginalByteLen-nTruncBeforeBytes];
  833. m_nFromLen = nDivideAt;
  834. m_nToCount = nMaxBytesToTry*2;
  835. int nDividedUTF16Len = PerformConversion( (void*)wsz16EndDivided );
  836. if ( nDividedUTF16Len )
  837. {
  838. m_pFrom = &pszOriginalBytes[nOriginalByteLen-nTruncBeforeBytes+nDivideAt];
  839. m_nFromLen = nTruncBeforeBytes-nDivideAt;
  840. m_nToCount = nMaxBytesToTry*2-nDividedUTF16Len;
  841. nDividedUTF16Len += PerformConversion( (void*)&wsz16EndDivided[nDividedUTF16Len] );
  842. if ( m_nToCount && nEndUTF16Len == nDividedUTF16Len && memcmp(wsz16End,wsz16EndDivided,nEndUTF16Len) == 0 )
  843. {
  844. nTruncBeforeBytes -= nDivideAt;
  845. bSuccess = true;
  846. break;
  847. }
  848. }
  849. ++nDivideAt;
  850. }
  851. }
  852. }
  853. }
  854. delete [] pUTF16Buffer;
  855. }
  856. }
  857. }
  858. return bSuccess;
  859. }
  860. bool x_EndianSwapRequired( int nDocFlags )
  861. {
  862. short nWord = 1;
  863. char cFirstByte = ((char*)&nWord)[0];
  864. if ( cFirstByte ) // LE
  865. {
  866. if ( nDocFlags & CMarkup::MDF_UTF16BEFILE )
  867. return true;
  868. }
  869. else if ( nDocFlags & CMarkup::MDF_UTF16LEFILE )
  870. return true;
  871. return false;
  872. }
  873. void x_EndianSwapUTF16( unsigned short* pBuffer, int nCharLen )
  874. {
  875. unsigned short cChar;
  876. while ( nCharLen-- )
  877. {
  878. cChar = pBuffer[nCharLen];
  879. pBuffer[nCharLen] = (unsigned short)((cChar<<8) | (cChar>>8));
  880. }
  881. }
  882. //////////////////////////////////////////////////////////////////////
  883. // Element position indexes
  884. // This is the primary means of storing the layout of the document
  885. //
  886. struct ElemPos
  887. {
  888. ElemPos() {};
  889. ElemPos( const ElemPos& pos ) { *this = pos; };
  890. int StartTagLen() const { return nStartTagLen; };
  891. void SetStartTagLen( int n ) { nStartTagLen = n; };
  892. void AdjustStartTagLen( int n ) { nStartTagLen += n; };
  893. int EndTagLen() const { return nEndTagLen; };
  894. void SetEndTagLen( int n ) { nEndTagLen = n; };
  895. bool IsEmptyElement() { return (StartTagLen()==nLength)?true:false; };
  896. int StartContent() const { return nStart + StartTagLen(); };
  897. int ContentLen() const { return nLength - StartTagLen() - EndTagLen(); };
  898. int StartAfter() const { return nStart + nLength; };
  899. int Level() const { return nFlags & 0xffff; };
  900. void SetLevel( int nLev ) { nFlags = (nFlags & ~0xffff) | nLev; };
  901. void ClearVirtualParent() { memset(this,0,sizeof(ElemPos)); };
  902. void SetEndTagLenUnparsed() { SetEndTagLen(1); };
  903. bool IsUnparsed() { return EndTagLen() == 1; };
  904. // Memory size: 8 32-bit integers == 32 bytes
  905. int nStart;
  906. int nLength;
  907. unsigned int nStartTagLen : 22; // 4MB limit for start tag
  908. unsigned int nEndTagLen : 10; // 1K limit for end tag
  909. int nFlags; // 16 bits flags, 16 bits level 65536 depth limit
  910. int iElemParent;
  911. int iElemChild; // first child
  912. int iElemNext; // next sibling
  913. int iElemPrev; // if this is first, iElemPrev points to last
  914. };
  915. enum MarkupNodeFlagsInternal2
  916. {
  917. MNF_REPLACE = 0x001000,
  918. MNF_QUOTED = 0x008000,
  919. MNF_EMPTY = 0x010000,
  920. MNF_DELETED = 0x020000,
  921. MNF_FIRST = 0x080000,
  922. MNF_PUBLIC = 0x300000,
  923. MNF_ILLFORMED = 0x800000,
  924. MNF_USER = 0xf000000
  925. };
  926. struct ElemPosTree
  927. {
  928. ElemPosTree() { Clear(); };
  929. ~ElemPosTree() { Release(); };
  930. enum { PA_SEGBITS = 16, PA_SEGMASK = 0xffff };
  931. void ReleaseElemPosTree() { Release(); Clear(); };
  932. void Release() { for (int n=0;n<SegsUsed();++n) delete[] (char*)m_pSegs[n]; if (m_pSegs) delete[] (char*)m_pSegs; };
  933. void Clear() { m_nSegs=0; m_nSize=0; m_pSegs=NULL; };
  934. int GetSize() const { return m_nSize; };
  935. int SegsUsed() const { return ((m_nSize-1)>>PA_SEGBITS) + 1; };
  936. ElemPos& GetRefElemPosAt(int i) const { return m_pSegs[i>>PA_SEGBITS][i&PA_SEGMASK]; };
  937. void CopyElemPosTree( ElemPosTree* pOtherTree, int n );
  938. void GrowElemPosTree( int nNewSize );
  939. private:
  940. ElemPos** m_pSegs;
  941. int m_nSize;
  942. int m_nSegs;
  943. };
  944. void ElemPosTree::CopyElemPosTree( ElemPosTree* pOtherTree, int n )
  945. {
  946. ReleaseElemPosTree();
  947. m_nSize = n;
  948. if ( m_nSize < 8 )
  949. m_nSize = 8;
  950. m_nSegs = SegsUsed();
  951. if ( m_nSegs )
  952. {
  953. m_pSegs = (ElemPos**)(new char[m_nSegs*sizeof(char*)]);
  954. int nSegSize = 1 << PA_SEGBITS;
  955. for ( int nSeg=0; nSeg < m_nSegs; ++nSeg )
  956. {
  957. if ( nSeg + 1 == m_nSegs )
  958. nSegSize = m_nSize - (nSeg << PA_SEGBITS);
  959. m_pSegs[nSeg] = (ElemPos*)(new char[nSegSize*sizeof(ElemPos)]);
  960. memcpy( m_pSegs[nSeg], pOtherTree->m_pSegs[nSeg], nSegSize*sizeof(ElemPos) );
  961. }
  962. }
  963. }
  964. void ElemPosTree::GrowElemPosTree( int nNewSize )
  965. {
  966. // Called by x_AllocElemPos when the document is created or the array is filled
  967. // The ElemPosTree class is implemented using segments to reduce contiguous memory requirements
  968. // It reduces reallocations (copying of memory) since this only occurs within one segment
  969. // The "Grow By" algorithm ensures there are no reallocations after 2 segments
  970. //
  971. // Grow By: new size can be at most one more complete segment
  972. int nSeg = (m_nSize?m_nSize-1:0) >> PA_SEGBITS;
  973. int nNewSeg = (nNewSize-1) >> PA_SEGBITS;
  974. if ( nNewSeg > nSeg + 1 )
  975. {
  976. nNewSeg = nSeg + 1;
  977. nNewSize = (nNewSeg+1) << PA_SEGBITS;
  978. }
  979. // Allocate array of segments
  980. if ( m_nSegs <= nNewSeg )
  981. {
  982. int nNewSegments = 4 + nNewSeg * 2;
  983. char* pNewSegments = new char[nNewSegments*sizeof(char*)];
  984. if ( SegsUsed() )
  985. memcpy( pNewSegments, m_pSegs, SegsUsed()*sizeof(char*) );
  986. if ( m_pSegs )
  987. delete[] (char*)m_pSegs;
  988. m_pSegs = (ElemPos**)pNewSegments;
  989. m_nSegs = nNewSegments;
  990. }
  991. // Calculate segment sizes
  992. int nSegSize = m_nSize - (nSeg << PA_SEGBITS);
  993. int nNewSegSize = nNewSize - (nNewSeg << PA_SEGBITS);
  994. // Complete first segment
  995. int nFullSegSize = 1 << PA_SEGBITS;
  996. if ( nSeg < nNewSeg && nSegSize < nFullSegSize )
  997. {
  998. char* pNewFirstSeg = new char[ nFullSegSize * sizeof(ElemPos) ];
  999. if ( nSegSize )
  1000. {
  1001. // Reallocate
  1002. memcpy( pNewFirstSeg, m_pSegs[nSeg], nSegSize * sizeof(ElemPos) );
  1003. delete[] (char*)m_pSegs[nSeg];
  1004. }
  1005. m_pSegs[nSeg] = (ElemPos*)pNewFirstSeg;
  1006. }
  1007. // New segment
  1008. char* pNewSeg = new char[ nNewSegSize * sizeof(ElemPos) ];
  1009. if ( nNewSeg == nSeg && nSegSize )
  1010. {
  1011. // Reallocate
  1012. memcpy( pNewSeg, m_pSegs[nSeg], nSegSize * sizeof(ElemPos) );
  1013. delete[] (char*)m_pSegs[nSeg];
  1014. }
  1015. m_pSegs[nNewSeg] = (ElemPos*)pNewSeg;
  1016. m_nSize = nNewSize;
  1017. }
  1018. #define ELEM(i) m_pElemPosTree->GetRefElemPosAt(i)
  1019. //////////////////////////////////////////////////////////////////////
  1020. // NodePos stores information about an element or node during document creation and parsing
  1021. //
  1022. struct NodePos
  1023. {
  1024. NodePos() {};
  1025. NodePos( int n ) { nNodeFlags=n; nNodeType=0; nStart=0; nLength=0; };
  1026. int nNodeType;
  1027. int nStart;
  1028. int nLength;
  1029. int nNodeFlags;
  1030. MCD_STR strMeta;
  1031. };
  1032. //////////////////////////////////////////////////////////////////////
  1033. // "Is Char" defines
  1034. // Quickly determine if a character matches a limited set
  1035. //
  1036. #define x_ISONEOF(c,f,l,s) ((c>=f&&c<=l)?(int)(s[c-f]):0)
  1037. // classic whitespace " \t\n\r"
  1038. #define x_ISWHITESPACE(c) x_ISONEOF(c,9,32,"\2\3\0\0\4\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1")
  1039. // end of word in a path " =/[]"
  1040. #define x_ISENDPATHWORD(c) x_ISONEOF(c,32,93,"\1\0\0\0\0\0\0\0\0\0\0\0\0\0\0\3\0\0\0\0\0\0\0\0\0\0\0\0\0\2\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\4\0\5")
  1041. // end of a name " \t\n\r/>"
  1042. #define x_ISENDNAME(c) x_ISONEOF(c,9,62,"\2\3\0\0\4\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1\0\0\0\0\0\0\0\0\0\0\0\0\0\0\5\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1")
  1043. // a small set of chars cannot be second last in attribute value " \t\n\r\"\'"
  1044. #define x_ISNOTSECONDLASTINVAL(c) x_ISONEOF(c,9,39,"\2\3\0\0\4\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1\0\5\0\0\0\0\1")
  1045. // first char of doc type tag name "EAN"
  1046. #define x_ISDOCTYPESTART(c) x_ISONEOF(c,65,78,"\2\0\0\0\1\0\0\0\0\0\0\0\0\3")
  1047. // attrib special char "<&>\"\'"
  1048. #define x_ISATTRIBSPECIAL(c) x_ISONEOF(c,34,62,"\4\0\0\0\2\5\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1\0\3")
  1049. // parsed text special char "<&>"
  1050. #define x_ISSPECIAL(c) x_ISONEOF(c,38,62,"\2\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1\0\3")
  1051. // end of any name " \t\n\r<>=\\/?!\"';"
  1052. #define x_ISENDANYNAME(c) x_ISONEOF(c,9,92,"\2\3\0\0\4\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1\1\1\0\0\0\0\1\0\0\0\0\0\0\0\1\0\0\0\0\0\0\0\0\0\0\0\1\5\1\1\1\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1")
  1053. // end of unquoted attrib value " \t\n\r>"
  1054. #define x_ISENDUNQUOTED(c) x_ISONEOF(c,9,62,"\2\3\0\0\4\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\5")
  1055. // end of attrib name "= \t\n\r>/?"
  1056. #define x_ISENDATTRIBNAME(c) x_ISONEOF(c,9,63,"\3\4\0\0\5\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\2\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1\0\0\0\0\0\0\0\0\0\0\0\0\0\1\1\1")
  1057. // start of entity reference "A-Za-Z#_:"
  1058. #define x_ISSTARTENTREF(c) x_ISONEOF(c,35,122,"\1\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1\0\0\0\0\0\0\1\2\3\4\5\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\0\0\0\0\1\0\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1")
  1059. // within entity reference "A-Za-Z0-9_:-."
  1060. #define x_ISINENTREF(c) x_ISONEOF(c,45,122,"\1\1\0\1\1\1\1\1\1\1\1\1\1\1\0\0\0\0\0\0\1\2\3\4\5\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\0\0\0\0\1\0\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1")
  1061. //////////////////////////////////////////////////////////////////////
  1062. // Token struct and tokenizing functions
  1063. // TokenPos handles parsing operations on a constant text pointer
  1064. //
  1065. struct TokenPos
  1066. {
  1067. TokenPos( MCD_CSTR sz, int n, FilePos* p=NULL ) { Clear(); m_pDocText=sz; m_nTokenFlags=n; m_pReaderFilePos=p; };
  1068. void Clear() { m_nL=0; m_nR=-1; m_nNext=0; };
  1069. int Length() const { return m_nR - m_nL + 1; };
  1070. MCD_PCSZ GetTokenPtr() const { return &m_pDocText[m_nL]; };
  1071. MCD_STR GetTokenText() const { return MCD_STR( GetTokenPtr(), Length() ); };
  1072. MCD_CHAR NextChar() { m_nNext += MCD_CLEN(&m_pDocText[m_nNext]); return m_pDocText[m_nNext]; };
  1073. int WhitespaceToTag( int n ) { m_nNext = n; if (FindAny()&&m_pDocText[m_nNext]!='<') { m_nNext=n; m_nR=n-1; } return m_nNext; };
  1074. bool FindAny()
  1075. {
  1076. // Go to non-whitespace or end
  1077. MCD_CHAR cNext = m_pDocText[m_nNext];
  1078. while ( cNext && x_ISWHITESPACE(cNext) )
  1079. cNext = m_pDocText[++m_nNext];
  1080. m_nL = m_nNext;
  1081. m_nR = m_nNext-1;
  1082. return m_pDocText[m_nNext]!='\0';
  1083. };
  1084. bool FindName()
  1085. {
  1086. if ( ! FindAny() ) // go to first non-whitespace
  1087. return false;
  1088. MCD_CHAR cNext = m_pDocText[m_nNext];
  1089. while ( cNext && ! x_ISENDANYNAME(cNext) )
  1090. cNext = NextChar();
  1091. if ( m_nNext == m_nL )
  1092. ++m_nNext; // it is a special char
  1093. m_nR = m_nNext - 1;
  1094. return true;
  1095. }
  1096. bool Match( MCD_CSTR szName )
  1097. {
  1098. int nLen = Length();
  1099. return ( (x_StrNCmp( GetTokenPtr(), szName, nLen, m_nTokenFlags & CMarkup::MDF_IGNORECASE ) == 0)
  1100. && ( szName[nLen] == '\0' || x_ISENDPATHWORD(szName[nLen]) ) );
  1101. };
  1102. bool FindAttrib( MCD_PCSZ pAttrib, int n = 0, MCD_STR* pstrAttrib = NULL );
  1103. int ParseNode( NodePos& node );
  1104. int m_nL;
  1105. int m_nR;
  1106. int m_nNext;
  1107. MCD_PCSZ m_pDocText;
  1108. int m_nTokenFlags;
  1109. int m_nPreSpaceStart;
  1110. int m_nPreSpaceLength;
  1111. FilePos* m_pReaderFilePos;
  1112. };
  1113. bool TokenPos::FindAttrib( MCD_PCSZ pAttrib, int n/*=0*/, MCD_STR* pstrAttrib/*=NULL*/ )
  1114. {
  1115. // Return true if found, otherwise false and token.m_nNext is new insertion point
  1116. // If pAttrib is NULL find attrib n and leave token at attrib name
  1117. // If pAttrib is given, find matching attrib and leave token at value
  1118. // support non-well-formed attributes e.g. href=/advanced_search?hl=en, nowrap
  1119. // token also holds start and length of preceeding whitespace to support remove
  1120. //
  1121. int nTempPreSpaceStart;
  1122. int nTempPreSpaceLength;
  1123. MCD_CHAR cFirstChar, cNext;
  1124. int nAttrib = -1; // starts at tag name
  1125. int nFoundAttribNameR = 0;
  1126. bool bAfterEqual = false;
  1127. while ( 1 )
  1128. {
  1129. // Starting at m_nNext, bypass whitespace and find the next token
  1130. nTempPreSpaceStart = m_nNext;
  1131. if ( ! FindAny() )
  1132. break;
  1133. nTempPreSpaceLength = m_nNext - nTempPreSpaceStart;
  1134. // Is it an opening quote?
  1135. cFirstChar = m_pDocText[m_nNext];
  1136. if ( cFirstChar == '\"' || cFirstChar == '\'' )
  1137. {
  1138. m_nTokenFlags |= MNF_QUOTED;
  1139. // Move past opening quote
  1140. ++m_nNext;
  1141. m_nL = m_nNext;
  1142. // Look for closing quote
  1143. cNext = m_pDocText[m_nNext];
  1144. while ( cNext && cNext != cFirstChar )
  1145. cNext = NextChar();
  1146. // Set right to before closing quote
  1147. m_nR = m_nNext - 1;
  1148. // Set m_nNext past closing quote unless at end of document
  1149. if ( cNext )
  1150. ++m_nNext;
  1151. }
  1152. else
  1153. {
  1154. m_nTokenFlags &= ~MNF_QUOTED;
  1155. // Go until special char or whitespace
  1156. m_nL = m_nNext;
  1157. cNext = m_pDocText[m_nNext];
  1158. if ( bAfterEqual )
  1159. {
  1160. while ( cNext && ! x_ISENDUNQUOTED(cNext) )
  1161. cNext = NextChar();
  1162. }
  1163. else
  1164. {
  1165. while ( cNext && ! x_ISENDATTRIBNAME(cNext) )
  1166. cNext = NextChar();
  1167. }
  1168. // Adjust end position if it is one special char
  1169. if ( m_nNext == m_nL )
  1170. ++m_nNext; // it is a special char
  1171. m_nR = m_nNext - 1;
  1172. }
  1173. if ( ! bAfterEqual && ! (m_nTokenFlags&MNF_QUOTED) )
  1174. {
  1175. // Is it an equal sign?
  1176. MCD_CHAR cChar = m_pDocText[m_nL];
  1177. if ( cChar == '=' )
  1178. {
  1179. bAfterEqual = true;
  1180. continue;
  1181. }
  1182. // Is it the end of the tag?
  1183. if ( cChar == '>' || cChar == '/' || cChar == '?' )
  1184. {
  1185. m_nNext = nTempPreSpaceStart;
  1186. break; // attrib not found
  1187. }
  1188. if ( nFoundAttribNameR )
  1189. break;
  1190. // Attribute name
  1191. if ( nAttrib != -1 )
  1192. {
  1193. if ( ! pAttrib )
  1194. {
  1195. if ( nAttrib == n )
  1196. {
  1197. // found by number
  1198. if ( pstrAttrib )
  1199. {
  1200. *pstrAttrib = GetTokenText();
  1201. nFoundAttribNameR = m_nR;
  1202. }
  1203. else
  1204. return true;
  1205. }
  1206. }
  1207. else if ( Match(pAttrib) )
  1208. {
  1209. // Matched attrib name, go forward to value
  1210. nFoundAttribNameR = m_nR;
  1211. }
  1212. if ( nFoundAttribNameR ) // either by n or name match
  1213. {
  1214. m_nPreSpaceStart = nTempPreSpaceStart;
  1215. m_nPreSpaceLength = nTempPreSpaceLength;
  1216. }
  1217. }
  1218. ++nAttrib;
  1219. }
  1220. else if ( nFoundAttribNameR )
  1221. break;
  1222. bAfterEqual = false;
  1223. }
  1224. if ( nFoundAttribNameR )
  1225. {
  1226. if ( ! bAfterEqual )
  1227. {
  1228. // when attribute has no value the value is the attribute name
  1229. m_nL = m_nPreSpaceStart + m_nPreSpaceLength;
  1230. m_nR = nFoundAttribNameR;
  1231. m_nNext = nFoundAttribNameR + 1;
  1232. }
  1233. return true; // found by name
  1234. }
  1235. return false; // not found
  1236. }
  1237. //////////////////////////////////////////////////////////////////////
  1238. // Element tag stack: an array of TagPos structs to track nested elements
  1239. // This is used during parsing to match end tags with corresponding start tags
  1240. // For x_ParseElem only ElemStack::iTop is used with PushIntoLevel, PopOutOfLevel, and Current
  1241. // For file mode then the full capabilities are used to track counts of sibling tag names for path support
  1242. //
  1243. struct TagPos
  1244. {
  1245. TagPos() { Init(); };
  1246. void SetTagName( MCD_PCSZ pName, int n ) { MCD_STRASSIGN(strTagName,pName,n); };
  1247. void Init( int i=0, int n=1 ) { nCount=1; nTagNames=n; iNext=i; iPrev=0; nSlot=-1; iSlotPrev=0; iSlotNext=0; };
  1248. void IncCount() { if (nCount) ++nCount; };
  1249. MCD_STR strTagName;
  1250. int nCount;
  1251. int nTagNames;
  1252. int iParent;
  1253. int iNext;
  1254. int iPrev;
  1255. int nSlot;
  1256. int iSlotNext;
  1257. int iSlotPrev;
  1258. };
  1259. struct ElemStack
  1260. {
  1261. enum { LS_TABLESIZE = 23 };
  1262. ElemStack() { iTop=0; iUsed=0; iPar=0; nLevel=0; nSize=0; pL=NULL; Alloc(7); pL[0].Init(); InitTable(); };
  1263. ~ElemStack() { if (pL) delete [] pL; };
  1264. TagPos& Current() { return pL[iTop]; };
  1265. void InitTable() { memset(anTable,0,sizeof(int)*LS_TABLESIZE); };
  1266. TagPos& NextParent( int& i ) { int iCur=i; i=pL[i].iParent; return pL[iCur]; };
  1267. TagPos& GetRefTagPosAt( int i ) { return pL[i]; };
  1268. void Push( MCD_PCSZ pName, int n ) { ++iUsed; if (iUsed==nSize) Alloc(nSize*2); pL[iUsed].SetTagName(pName,n); pL[iUsed].iParent=iPar; iTop=iUsed; };
  1269. void IntoLevel() { iPar = iTop; ++nLevel; };
  1270. void OutOfLevel() { if (iPar!=iTop) Pop(); iPar = pL[iTop].iParent; --nLevel; };
  1271. void PushIntoLevel( MCD_PCSZ pName, int n ) { ++iTop; if (iTop==nSize) Alloc(nSize*2); pL[iTop].SetTagName(pName,n); };
  1272. void PopOutOfLevel() { --iTop; };
  1273. void Pop() { iTop = iPar; while (iUsed && pL[iUsed].iParent==iPar) { if (pL[iUsed].nSlot!=-1) Unslot(pL[iUsed]); --iUsed; } };
  1274. void Slot( int n ) { pL[iUsed].nSlot=n; int i=anTable[n]; anTable[n]=iUsed; pL[iUsed].iSlotNext=i; if (i) pL[i].iSlotPrev=iUsed; };
  1275. void Unslot( TagPos& lp ) { int n=lp.iSlotNext,p=lp.iSlotPrev; if (n) pL[n].iSlotPrev=p; if (p) pL[p].iSlotNext=n; else anTable[lp.nSlot]=n; };
  1276. static int CalcSlot( MCD_PCSZ pName, int n, bool bIC );
  1277. void PushTagAndCount( TokenPos& token );
  1278. int iTop;
  1279. int nLevel;
  1280. int iPar;
  1281. protected:
  1282. void Alloc( int nNewSize ) { TagPos* pLNew = new TagPos[nNewSize]; Copy(pLNew); nSize=nNewSize; };
  1283. void Copy( TagPos* pLNew ) { for(int n=0;n<nSize;++n) pLNew[n]=pL[n]; if (pL) delete [] pL; pL=pLNew; };
  1284. TagPos* pL;
  1285. int iUsed;
  1286. int nSize;
  1287. int anTable[LS_TABLESIZE];
  1288. };
  1289. int ElemStack::CalcSlot( MCD_PCSZ pName, int n, bool bIC )
  1290. {
  1291. // If bIC (ASCII ignore case) then return an ASCII case insensitive hash
  1292. unsigned int nHash = 0;
  1293. MCD_PCSZ pEnd = pName + n;
  1294. while ( pName != pEnd )
  1295. {
  1296. nHash += (unsigned int)(*pName);
  1297. if ( bIC && *pName >= 'A' && *pName <= 'Z' )
  1298. nHash += ('a'-'A');
  1299. ++pName;
  1300. }
  1301. return nHash%LS_TABLESIZE;
  1302. }
  1303. void ElemStack::PushTagAndCount( TokenPos& token )
  1304. {
  1305. // Check for a matching tag name at the top level and set current if found or add new one
  1306. // Calculate hash of tag name, support ignore ASCII case for MDF_IGNORECASE
  1307. int nSlot = -1;
  1308. int iNext = 0;
  1309. MCD_PCSZ pTagName = token.GetTokenPtr();
  1310. if ( iTop != iPar )
  1311. {
  1312. // See if tag name is already used, first try previous sibling (almost always)
  1313. iNext = iTop;
  1314. if ( token.Match(Current().strTagName) )
  1315. {
  1316. iNext = -1;
  1317. Current().IncCount();
  1318. }
  1319. else
  1320. {
  1321. nSlot = CalcSlot( pTagName, token.Length(), (token.m_nTokenFlags & CMarkup::MDF_IGNORECASE)?true:false );
  1322. int iLookup = anTable[nSlot];
  1323. while ( iLookup )
  1324. {
  1325. TagPos& tag = pL[iLookup];
  1326. if ( tag.iParent == iPar && token.Match(tag.strTagName) )
  1327. {
  1328. pL[tag.iPrev].iNext = tag.iNext;
  1329. if ( tag.iNext )
  1330. pL[tag.iNext].iPrev = tag.iPrev;
  1331. tag.nTagNames = Current().nTagNames;
  1332. tag.iNext = iTop;
  1333. tag.IncCount();
  1334. iTop = iLookup;
  1335. iNext = -1;
  1336. break;
  1337. }
  1338. iLookup = tag.iSlotNext;
  1339. }
  1340. }
  1341. }
  1342. if ( iNext != -1 )
  1343. {
  1344. // Turn off in the rare case where a document uses unique tag names like record1, record2, etc, more than 256
  1345. int nTagNames = 0;
  1346. if ( iNext )
  1347. nTagNames = Current().nTagNames;
  1348. if ( nTagNames == 256 )
  1349. {
  1350. MCD_STRASSIGN( (Current().strTagName), pTagName, (token.Length()) );
  1351. Current().nCount = 0;
  1352. Unslot( Current() );
  1353. }
  1354. else
  1355. {
  1356. Push( pTagName, token.Length() );
  1357. Current().Init( iNext, nTagNames+1 );
  1358. }
  1359. if ( nSlot == -1 )
  1360. nSlot = CalcSlot( pTagName, token.Length(), (token.m_nTokenFlags & CMarkup::MDF_IGNORECASE)?true:false );
  1361. Slot( nSlot );
  1362. }
  1363. }
  1364. //////////////////////////////////////////////////////////////////////
  1365. // FilePos is created for a file while it is open
  1366. // In file mode the file stays open between CMarkup calls and is stored in m_pFilePos
  1367. //
  1368. struct FilePos
  1369. {
  1370. FilePos()
  1371. {
  1372. m_fp=NULL; m_nDocFlags=0; m_nFileByteLen=0; m_nFileByteOffset=0; m_nOpFileByteLen=0; m_nBlockSizeBasis=MARKUP_FILEBLOCKSIZE;
  1373. m_nFileCharUnitSize=0; m_nOpFileTextLen=0; m_pstrBuffer=NULL; m_nReadBufferStart=0; m_nReadBufferRemoved=0; m_nReadGatherStart=-1;
  1374. };
  1375. bool FileOpen( MCD_CSTR_FILENAME szFileName );
  1376. bool FileRead( void* pBuffer );
  1377. bool FileReadText( MCD_STR& strDoc );
  1378. bool FileCheckRaggedEnd( void* pBuffer );
  1379. bool FileReadNextBuffer();
  1380. void FileGatherStart( int nStart );
  1381. int FileGatherEnd( MCD_STR& strSubDoc );
  1382. bool FileWrite( void* pBuffer, const void* pConstBuffer = NULL );
  1383. bool FileWriteText( const MCD_STR& strDoc, int nWriteStrLen = -1 );
  1384. bool FileFlush( MCD_STR& strBuffer, int nWriteStrLen = -1, bool bFflush = false );
  1385. bool FileClose();
  1386. void FileSpecifyEncoding( MCD_STR* pstrEncoding );
  1387. bool FileAtTop();
  1388. bool FileErrorAddResult();
  1389. FILE* m_fp;
  1390. int m_nDocFlags;
  1391. int m_nOpFileByteLen;
  1392. int m_nBlockSizeBasis;
  1393. MCD_INTFILEOFFSET m_nFileByteLen;
  1394. MCD_INTFILEOFFSET m_nFileByteOffset;
  1395. int m_nFileCharUnitSize;
  1396. int m_nOpFileTextLen;
  1397. MCD_STR m_strIOResult;
  1398. MCD_STR m_strEncoding;
  1399. MCD_STR* m_pstrBuffer;
  1400. ElemStack m_elemstack;
  1401. int m_nReadBufferStart;
  1402. int m_nReadBufferRemoved;
  1403. int m_nReadGatherStart;
  1404. MCD_STR m_strReadGatherMarkup;
  1405. };
  1406. struct BomTableStruct { const char* pszBom; int nBomLen; MCD_PCSZ pszBomEnc; int nBomFlag; } BomTable[] =
  1407. {
  1408. { "\xef\xbb\xbf", 3, MCD_T("UTF-8"), CMarkup::MDF_UTF8PREAMBLE },
  1409. { "\xff\xfe", 2, MCD_T("UTF-16LE"), CMarkup::MDF_UTF16LEFILE },
  1410. { "\xfe\xff", 2, MCD_T("UTF-16BE"), CMarkup::MDF_UTF16BEFILE },
  1411. { NULL,0,NULL,0 }
  1412. };
  1413. bool FilePos::FileErrorAddResult()
  1414. {
  1415. // strerror has difficulties cross-platform
  1416. // VC++ leaves MCD_STRERROR undefined and uses FormatMessage
  1417. // Non-VC++ use strerror (even for MARKUP_WCHAR and convert)
  1418. // additional notes:
  1419. // _WIN32_WCE (Windows CE) has no strerror (Embedded VC++ uses FormatMessage)
  1420. // _MSC_VER >= 1310 (VC++ 2003/7.1) has _wcserror (but not used)
  1421. //
  1422. const int nErrorBufferSize = 100;
  1423. int nErr = 0;
  1424. MCD_CHAR szError[nErrorBufferSize+1];
  1425. #if defined(MCD_STRERROR) // C error routine
  1426. nErr = (int)errno;
  1427. #if defined(MARKUP_WCHAR)
  1428. char szMBError[nErrorBufferSize+1];
  1429. strncpy( szMBError, MCD_STRERROR, nErrorBufferSize );
  1430. szMBError[nErrorBufferSize] = '\0';
  1431. TextEncoding textencoding( MCD_T(""), (const void*)szMBError, strlen(szMBError) );
  1432. textencoding.m_nToCount = nErrorBufferSize;
  1433. int nWideLen = textencoding.PerformConversion( (void*)szError, MCD_ENC );
  1434. szError[nWideLen] = '\0';
  1435. #else
  1436. MCD_PSZNCPY( szError, MCD_STRERROR, nErrorBufferSize );
  1437. szError[nErrorBufferSize] = '\0';
  1438. #endif
  1439. #else // no C error routine, use Windows API
  1440. DWORD dwErr = ::GetLastError();
  1441. if ( ::FormatMessage(0x1200,0,dwErr,0,szError,nErrorBufferSize,0) < 1 )
  1442. szError[0] = '\0';
  1443. nErr = (int)dwErr;
  1444. #endif // no C error routine
  1445. MCD_STR strError = szError;
  1446. for ( int nChar=0; nChar<MCD_STRLENGTH(strError); ++nChar )
  1447. if ( strError[nChar] == '\r' || strError[nChar] == '\n' )
  1448. {
  1449. strError = MCD_STRMID( strError, 0, nChar ); // no trailing newline
  1450. break;
  1451. }
  1452. x_AddResult( m_strIOResult, MCD_T("file_error"), strError, MRC_MSG|MRC_NUMBER, nErr );
  1453. return false;
  1454. }
  1455. void FilePos::FileSpecifyEncoding( MCD_STR* pstrEncoding )
  1456. {
  1457. // In ReadTextFile, WriteTextFile and Open, the pstrEncoding argument can override or return the detected encoding
  1458. if ( pstrEncoding && m_strEncoding != *pstrEncoding )
  1459. {
  1460. if ( m_nFileCharUnitSize == 1 && *pstrEncoding != MCD_T("") )
  1461. m_strEncoding = *pstrEncoding; // override the encoding
  1462. else // just report the encoding
  1463. *pstrEncoding = m_strEncoding;
  1464. }
  1465. }
  1466. bool FilePos::FileAtTop()
  1467. {
  1468. // Return true if in the first block of file mode, max BOM < 5 bytes
  1469. if ( ((m_nDocFlags & CMarkup::MDF_READFILE) && m_nFileByteOffset < (MCD_INTFILEOFFSET)m_nOpFileByteLen + 5 )
  1470. || ((m_nDocFlags & CMarkup::MDF_WRITEFILE) && m_nFileByteOffset < 5) )
  1471. return true;
  1472. return false;
  1473. }
  1474. bool FilePos::FileOpen( MCD_CSTR_FILENAME szFileName )
  1475. {
  1476. MCD_STRCLEAR( m_strIOResult );
  1477. // Open file
  1478. MCD_PCSZ_FILENAME pMode = MCD_T_FILENAME("rb");
  1479. if ( m_nDocFlags & CMarkup::MDF_APPENDFILE )
  1480. pMode = MCD_T_FILENAME("ab");
  1481. else if ( m_nDocFlags & CMarkup::MDF_WRITEFILE )
  1482. pMode = MCD_T_FILENAME("wb");
  1483. m_fp = NULL;
  1484. MCD_FOPEN( m_fp, szFileName, pMode );
  1485. if ( ! m_fp )
  1486. return FileErrorAddResult();
  1487. // Prepare file
  1488. bool bSuccess = true;
  1489. int nBomLen = 0;
  1490. m_nFileCharUnitSize = 1; // unless UTF-16 BOM
  1491. if ( m_nDocFlags & CMarkup::MDF_READFILE )
  1492. {
  1493. // Get file length
  1494. MCD_FSEEK( m_fp, 0, SEEK_END );
  1495. m_nFileByteLen = MCD_FTELL( m_fp );
  1496. MCD_FSEEK( m_fp, 0, SEEK_SET );
  1497. // Read the top of the file to check BOM and encoding
  1498. int nReadTop = 1024;
  1499. if ( m_nFileByteLen < nReadTop )
  1500. nReadTop = (int)m_nFileByteLen;
  1501. if ( nReadTop )
  1502. {
  1503. char* pFileTop = new char[nReadTop];
  1504. if ( nReadTop )
  1505. bSuccess = ( fread( pFileTop, nReadTop, 1, m_fp ) == 1 );
  1506. if ( bSuccess )
  1507. {
  1508. // Check for Byte Order Mark (preamble)
  1509. int nBomCheck = 0;
  1510. m_nDocFlags &= ~( CMarkup::MDF_UTF16LEFILE | CMarkup::MDF_UTF8PREAMBLE );
  1511. while ( BomTable[nBomCheck].pszBom )
  1512. {
  1513. while ( nBomLen < BomTable[nBomCheck].nBomLen )
  1514. {
  1515. if ( nBomLen >= nReadTop || pFileTop[nBomLen] != BomTable[nBomCheck].pszBom[nBomLen] )
  1516. break;
  1517. ++nBomLen;
  1518. }
  1519. if ( nBomLen == BomTable[nBomCheck].nBomLen )
  1520. {
  1521. m_nDocFlags |= BomTable[nBomCheck].nBomFlag;
  1522. if ( nBomLen == 2 )
  1523. m_nFileCharUnitSize = 2;
  1524. m_strEncoding = BomTable[nBomCheck].pszBomEnc;
  1525. break;
  1526. }
  1527. ++nBomCheck;
  1528. nBomLen = 0;
  1529. }
  1530. if ( nReadTop > nBomLen )
  1531. MCD_FSEEK( m_fp, nBomLen, SEEK_SET );
  1532. // Encoding check
  1533. if ( ! nBomLen )
  1534. {
  1535. MCD_STR strDeclCheck;
  1536. #if defined(MARKUP_WCHAR) // WCHAR
  1537. TextEncoding textencoding( MCD_T("UTF-8"), (const void*)pFileTop, nReadTop );
  1538. MCD_CHAR* pWideBuffer = MCD_GETBUFFER(strDeclCheck,nReadTop);
  1539. textencoding.m_nToCount = nReadTop;
  1540. int nDeclWideLen = textencoding.PerformConversion( (void*)pWideBuffer, MCD_ENC );
  1541. MCD_RELEASEBUFFER(strDeclCheck,pWideBuffer,nDeclWideLen);
  1542. #else // not WCHAR
  1543. MCD_STRASSIGN(strDeclCheck,pFileTop,nReadTop);
  1544. #endif // not WCHAR
  1545. m_strEncoding = CMarkup::GetDeclaredEncoding( strDeclCheck );
  1546. }
  1547. // Assume markup files starting with < sign are UTF-8 if otherwise unknown
  1548. if ( MCD_STRISEMPTY(m_strEncoding) && pFileTop[0] == '<' )
  1549. m_strEncoding = MCD_T("UTF-8");
  1550. }
  1551. delete [] pFileTop;
  1552. }
  1553. }
  1554. else if ( m_nDocFlags & CMarkup::MDF_WRITEFILE )
  1555. {
  1556. if ( m_nDocFlags & CMarkup::MDF_APPENDFILE )
  1557. {
  1558. // fopen for append does not move the file pointer to the end until first I/O operation
  1559. MCD_FSEEK( m_fp, 0, SEEK_END );
  1560. m_nFileByteLen = MCD_FTELL( m_fp );
  1561. }
  1562. int nBomCheck = 0;
  1563. while ( BomTable[nBomCheck].pszBom )
  1564. {
  1565. if ( m_nDocFlags & BomTable[nBomCheck].nBomFlag )
  1566. {
  1567. nBomLen = BomTable[nBomCheck].nBomLen;
  1568. if ( nBomLen == 2 )
  1569. m_nFileCharUnitSize = 2;
  1570. m_strEncoding = BomTable[nBomCheck].pszBomEnc;
  1571. if ( m_nFileByteLen ) // append
  1572. nBomLen = 0;
  1573. else // write BOM
  1574. bSuccess = ( fwrite(BomTable[nBomCheck].pszBom,nBomLen,1,m_fp) == 1 );
  1575. break;
  1576. }
  1577. ++nBomCheck;
  1578. }
  1579. }
  1580. if ( ! bSuccess )
  1581. return FileErrorAddResult();
  1582. if ( m_nDocFlags & CMarkup::MDF_APPENDFILE )
  1583. m_nFileByteOffset = m_nFileByteLen;
  1584. else
  1585. m_nFileByteOffset = (MCD_INTFILEOFFSET)nBomLen;
  1586. if ( nBomLen )
  1587. x_AddResult( m_strIOResult, MCD_T("bom") );
  1588. return bSuccess;
  1589. }
  1590. bool FilePos::FileRead( void* pBuffer )
  1591. {
  1592. bool bSuccess = ( fread( pBuffer,m_nOpFileByteLen,1,m_fp) == 1 );
  1593. m_nOpFileTextLen = m_nOpFileByteLen / m_nFileCharUnitSize;
  1594. if ( bSuccess )
  1595. {
  1596. m_nFileByteOffset += m_nOpFileByteLen;
  1597. x_AddResult( m_strIOResult, MCD_T("read"), m_strEncoding, MRC_ENCODING|MRC_LENGTH, m_nOpFileTextLen );
  1598. // Microsoft components can produce apparently valid docs with some nulls at ends of values
  1599. int nNullCount = 0;
  1600. int nNullCheckCharsRemaining = m_nOpFileTextLen;
  1601. char* pAfterNull = NULL;
  1602. char* pNullScan = (char*)pBuffer;
  1603. bool bSingleByteChar = m_nFileCharUnitSize == 1;
  1604. while ( nNullCheckCharsRemaining-- )
  1605. {
  1606. if ( bSingleByteChar? (! *pNullScan) : (! (*(unsigned short*)pNullScan)) )
  1607. {
  1608. if ( pAfterNull && pNullScan != pAfterNull )
  1609. memmove( pAfterNull - (nNullCount*m_nFileCharUnitSize), pAfterNull, pNullScan - pAfterNull );
  1610. pAfterNull = pNullScan + m_nFileCharUnitSize;
  1611. ++nNullCount;
  1612. }
  1613. pNullScan += m_nFileCharUnitSize;
  1614. }
  1615. if ( pAfterNull && pNullScan != pAfterNull )
  1616. memmove( pAfterNull - (nNullCount*m_nFileCharUnitSize), pAfterNull, pNullScan - pAfterNull );
  1617. if ( nNullCount )
  1618. {
  1619. x_AddResult( m_strIOResult, MCD_T("nulls_removed"), NULL, MRC_COUNT, nNullCount );
  1620. m_nOpFileTextLen -= nNullCount;
  1621. }
  1622. // Big endian/little endian conversion
  1623. if ( m_nFileCharUnitSize > 1 && x_EndianSwapRequired(m_nDocFlags) )
  1624. {
  1625. x_EndianSwapUTF16( (unsigned short*)pBuffer, m_nOpFileTextLen );
  1626. x_AddResult( m_strIOResult, MCD_T("endian_swap") );
  1627. }
  1628. }
  1629. if ( ! bSuccess )
  1630. FileErrorAddResult();
  1631. return bSuccess;
  1632. }
  1633. bool FilePos::FileCheckRaggedEnd( void* pBuffer )
  1634. {
  1635. // In file read mode, piece of file text in memory must end on a character boundary
  1636. // This check must happen after the encoding has been decided, so after UTF-8 autodetection
  1637. // If ragged, adjust file position, m_nOpFileTextLen and m_nOpFileByteLen
  1638. int nTruncBeforeBytes = 0;
  1639. TextEncoding textencoding( m_strEncoding, pBuffer, m_nOpFileTextLen );
  1640. if ( ! textencoding.FindRaggedEnd(nTruncBeforeBytes) )
  1641. {
  1642. // Input must be garbled? decoding error before potentially ragged end, add error result and continue
  1643. MCD_STR strEncoding = m_strEncoding;
  1644. if ( MCD_STRISEMPTY(strEncoding) )
  1645. strEncoding = MCD_T("ANSI");
  1646. x_AddResult( m_strIOResult, MCD_T("truncation_error"), strEncoding, MRC_ENCODING );
  1647. }
  1648. else if ( nTruncBeforeBytes )
  1649. {
  1650. nTruncBeforeBytes *= -1;
  1651. m_nFileByteOffset += nTruncBeforeBytes;
  1652. MCD_FSEEK( m_fp, m_nFileByteOffset, SEEK_SET );
  1653. m_nOpFileByteLen += nTruncBeforeBytes;
  1654. m_nOpFileTextLen += nTruncBeforeBytes / m_nFileCharUnitSize;
  1655. x_AddResult( m_strIOResult, MCD_T("read"), NULL, MRC_MODIFY|MRC_LENGTH, m_nOpFileTextLen );
  1656. }
  1657. return true;
  1658. }
  1659. bool FilePos::FileReadText( MCD_STR& strDoc )
  1660. {
  1661. bool bSuccess = true;
  1662. MCD_STRCLEAR( m_strIOResult );
  1663. if ( ! m_nOpFileByteLen )
  1664. {
  1665. x_AddResult( m_strIOResult, MCD_T("read"), m_strEncoding, MRC_ENCODING|MRC_LENGTH, 0 );
  1666. return bSuccess;
  1667. }
  1668. // Only read up to end of file (a single read byte length cannot be over the capacity of int)
  1669. bool bCheckRaggedEnd = true;
  1670. MCD_INTFILEOFFSET nBytesRemaining = m_nFileByteLen - m_nFileByteOffset;
  1671. if ( (MCD_INTFILEOFFSET)m_nOpFileByteLen >= nBytesRemaining )
  1672. {
  1673. m_nOpFileByteLen = (int)nBytesRemaining;
  1674. bCheckRaggedEnd = false;
  1675. }
  1676. if ( m_nDocFlags & (CMarkup::MDF_UTF16LEFILE | CMarkup::MDF_UTF16BEFILE) )
  1677. {
  1678. int nUTF16Len = m_nOpFileByteLen / 2;
  1679. #if defined(MARKUP_WCHAR) // WCHAR
  1680. int nBufferSizeForGrow = nUTF16Len + nUTF16Len/100; // extra 1%
  1681. #if MARKUP_SIZEOFWCHAR == 4 // sizeof(wchar_t) == 4
  1682. unsigned short* pUTF16Buffer = new unsigned short[nUTF16Len+1];
  1683. bSuccess = FileRead( pUTF16Buffer );
  1684. if ( bSuccess )
  1685. {
  1686. if ( bCheckRaggedEnd )
  1687. FileCheckRaggedEnd( (void*)pUTF16Buffer );
  1688. TextEncoding textencoding( MCD_T("UTF-16"), (const void*)pUTF16Buffer, m_nOpFileTextLen );
  1689. textencoding.m_nToCount = nBufferSizeForGrow;
  1690. MCD_CHAR* pUTF32Buffer = MCD_GETBUFFER(strDoc,nBufferSizeForGrow);
  1691. int nUTF32Len = textencoding.PerformConversion( (void*)pUTF32Buffer, MCD_T("UTF-32") );
  1692. MCD_RELEASEBUFFER(strDoc,pUTF32Buffer,nUTF32Len);
  1693. x_AddResult( m_strIOResult, MCD_T("converted_to"), MCD_T("UTF-32"), MRC_ENCODING|MRC_LENGTH, nUTF32Len );
  1694. }
  1695. #else // sizeof(wchar_t) == 2
  1696. MCD_CHAR* pUTF16Buffer = MCD_GETBUFFER(strDoc,nBufferSizeForGrow);
  1697. bSuccess = FileRead( pUTF16Buffer );
  1698. if ( bSuccess && bCheckRaggedEnd )
  1699. FileCheckRaggedEnd( (void*)pUTF16Buffer );
  1700. MCD_RELEASEBUFFER(strDoc,pUTF16Buffer,m_nOpFileTextLen);
  1701. #endif // sizeof(wchar_t) == 2
  1702. #else // not WCHAR
  1703. // Convert file from UTF-16; it needs to be in memory as UTF-8 or MBCS
  1704. unsigned short* pUTF16Buffer = new unsigned short[nUTF16Len+1];
  1705. bSuccess = FileRead( pUTF16Buffer );
  1706. if ( bSuccess && bCheckRaggedEnd )
  1707. FileCheckRaggedEnd( (void*)pUTF16Buffer );
  1708. TextEncoding textencoding( MCD_T("UTF-16"), (const void*)pUTF16Buffer, m_nOpFileTextLen );
  1709. int nMBLen = textencoding.PerformConversion( NULL, MCD_ENC );
  1710. int nBufferSizeForGrow = nMBLen + nMBLen/100; // extra 1%
  1711. MCD_CHAR* pMBBuffer = MCD_GETBUFFER(strDoc,nBufferSizeForGrow);
  1712. textencoding.PerformConversion( (void*)pMBBuffer );
  1713. delete [] pUTF16Buffer;
  1714. MCD_RELEASEBUFFER(strDoc,pMBBuffer,nMBLen);
  1715. x_AddResult( m_strIOResult, MCD_T("converted_to"), MCD_ENC, MRC_ENCODING|MRC_LENGTH, nMBLen );
  1716. if ( textencoding.m_nFailedChars )
  1717. x_AddResult( m_strIOResult, MCD_T("conversion_loss") );
  1718. #endif // not WCHAR
  1719. }
  1720. else // single or multibyte file (i.e. not UTF-16)
  1721. {
  1722. #if defined(MARKUP_WCHAR) // WCHAR
  1723. char* pBuffer = new char[m_nOpFileByteLen];
  1724. bSuccess = FileRead( pBuffer );
  1725. if ( MCD_STRISEMPTY(m_strEncoding) )
  1726. {
  1727. int nNonASCII;
  1728. bool bErrorAtEnd;
  1729. if ( CMarkup::DetectUTF8(pBuffer,m_nOpFileByteLen,&nNonASCII,&bErrorAtEnd) || (bCheckRaggedEnd && bErrorAtEnd) )
  1730. {
  1731. m_strEncoding = MCD_T("UTF-8");
  1732. x_AddResult( m_strIOResult, MCD_T("read"), m_strEncoding, MRC_MODIFY|MRC_ENCODING );
  1733. }
  1734. x_AddResult( m_strIOResult, MCD_T("utf8_detection") );
  1735. }
  1736. if ( bSuccess && bCheckRaggedEnd )
  1737. FileCheckRaggedEnd( (void*)pBuffer );
  1738. TextEncoding textencoding( m_strEncoding, (const void*)pBuffer, m_nOpFileTextLen );
  1739. int nWideLen = textencoding.PerformConversion( NULL, MCD_ENC );
  1740. int nBufferSizeForGrow = nWideLen + nWideLen/100; // extra 1%
  1741. MCD_CHAR* pWideBuffer = MCD_GETBUFFER(strDoc,nBufferSizeForGrow);
  1742. textencoding.PerformConversion( (void*)pWideBuffer );
  1743. MCD_RELEASEBUFFER( strDoc, pWideBuffer, nWideLen );
  1744. delete [] pBuffer;
  1745. x_AddResult( m_strIOResult, MCD_T("converted_to"), MCD_ENC, MRC_ENCODING|MRC_LENGTH, nWideLen );
  1746. #else // not WCHAR
  1747. // After loading a file with unknown multi-byte encoding
  1748. bool bAssumeUnknownIsNative = false;
  1749. if ( MCD_STRISEMPTY(m_strEncoding) )
  1750. {
  1751. bAssumeUnknownIsNative = true;
  1752. m_strEncoding = MCD_ENC;
  1753. }
  1754. if ( TextEncoding::CanConvert(MCD_ENC,m_strEncoding) )
  1755. {
  1756. char* pBuffer = new char[m_nOpFileByteLen];
  1757. bSuccess = FileRead( pBuffer );
  1758. if ( bSuccess && bCheckRaggedEnd )
  1759. FileCheckRaggedEnd( (void*)pBuffer );
  1760. TextEncoding textencoding( m_strEncoding, (const void*)pBuffer, m_nOpFileTextLen );
  1761. int nMBLen = textencoding.PerformConversion( NULL, MCD_ENC );
  1762. int nBufferSizeForGrow = nMBLen + nMBLen/100; // extra 1%
  1763. MCD_CHAR* pMBBuffer = MCD_GETBUFFER(strDoc,nBufferSizeForGrow);
  1764. textencoding.PerformConversion( (void*)pMBBuffer );
  1765. MCD_RELEASEBUFFER( strDoc, pMBBuffer, nMBLen );
  1766. delete [] pBuffer;
  1767. x_AddResult( m_strIOResult, MCD_T("converted_to"), MCD_ENC, MRC_ENCODING|MRC_LENGTH, nMBLen );
  1768. if ( textencoding.m_nFailedChars )
  1769. x_AddResult( m_strIOResult, MCD_T("conversion_loss") );
  1770. }
  1771. else // load directly into string
  1772. {
  1773. int nBufferSizeForGrow = m_nOpFileByteLen + m_nOpFileByteLen/100; // extra 1%
  1774. MCD_CHAR* pBuffer = MCD_GETBUFFER(strDoc,nBufferSizeForGrow);
  1775. bSuccess = FileRead( pBuffer );
  1776. bool bConvertMB = false;
  1777. if ( bAssumeUnknownIsNative )
  1778. {
  1779. // Might need additional conversion if we assumed an encoding
  1780. int nNonASCII;
  1781. bool bErrorAtEnd;
  1782. bool bIsUTF8 = CMarkup::DetectUTF8( pBuffer, m_nOpFileByteLen, &nNonASCII, &bErrorAtEnd ) || (bCheckRaggedEnd && bErrorAtEnd);
  1783. MCD_STR strDetectedEncoding = bIsUTF8? MCD_T("UTF-8"): MCD_T("");
  1784. if ( nNonASCII && m_strEncoding != strDetectedEncoding ) // only need to convert non-ASCII
  1785. bConvertMB = true;
  1786. m_strEncoding = strDetectedEncoding;
  1787. if ( bIsUTF8 )
  1788. x_AddResult( m_strIOResult, MCD_T("read"), m_strEncoding, MRC_MODIFY|MRC_ENCODING );
  1789. }
  1790. if ( bSuccess && bCheckRaggedEnd )
  1791. FileCheckRaggedEnd( (void*)pBuffer );
  1792. MCD_RELEASEBUFFER( strDoc, pBuffer, m_nOpFileTextLen );
  1793. if ( bConvertMB )
  1794. {
  1795. TextEncoding textencoding( m_strEncoding, MCD_2PCSZ(strDoc), m_nOpFileTextLen );
  1796. int nMBLen = textencoding.PerformConversion( NULL, MCD_ENC );
  1797. nBufferSizeForGrow = nMBLen + nMBLen/100; // extra 1%
  1798. MCD_STR strConvDoc;
  1799. pBuffer = MCD_GETBUFFER(strConvDoc,nBufferSizeForGrow);
  1800. textencoding.PerformConversion( (void*)pBuffer );
  1801. MCD_RELEASEBUFFER( strConvDoc, pBuffer, nMBLen );
  1802. strDoc = strConvDoc;
  1803. x_AddResult( m_strIOResult, MCD_T("converted_to"), MCD_ENC, MRC_ENCODING|MRC_LENGTH, nMBLen );
  1804. if ( textencoding.m_nFailedChars )
  1805. x_AddResult( m_strIOResult, MCD_T("conversion_loss") );
  1806. }
  1807. if ( bAssumeUnknownIsNative )
  1808. x_AddResult( m_strIOResult, MCD_T("utf8_detection") );
  1809. }
  1810. #endif // not WCHAR
  1811. }
  1812. return bSuccess;
  1813. }
  1814. bool FilePos::FileWrite( void* pBuffer, const void* pConstBuffer /*=NULL*/ )
  1815. {
  1816. m_nOpFileByteLen = m_nOpFileTextLen * m_nFileCharUnitSize;
  1817. if ( ! pConstBuffer )
  1818. pConstBuffer = pBuffer;
  1819. unsigned short* pTempEndianBuffer = NULL;
  1820. if ( x_EndianSwapRequired(m_nDocFlags) )
  1821. {
  1822. if ( ! pBuffer )
  1823. {
  1824. pTempEndianBuffer = new unsigned short[m_nOpFileTextLen];
  1825. memcpy( pTempEndianBuffer, pConstBuffer, m_nOpFileTextLen * 2 );
  1826. pBuffer = pTempEndianBuffer;
  1827. pConstBuffer = pTempEndianBuffer;
  1828. }
  1829. x_EndianSwapUTF16( (unsigned short*)pBuffer, m_nOpFileTextLen );
  1830. x_AddResult( m_strIOResult, MCD_T("endian_swap") );
  1831. }
  1832. bool bSuccess = ( fwrite( pConstBuffer, m_nOpFileByteLen, 1, m_fp ) == 1 );
  1833. if ( pTempEndianBuffer )
  1834. delete [] pTempEndianBuffer;
  1835. if ( bSuccess )
  1836. {
  1837. m_nFileByteOffset += m_nOpFileByteLen;
  1838. x_AddResult( m_strIOResult, MCD_T("write"), m_strEncoding, MRC_ENCODING|MRC_LENGTH, m_nOpFileTextLen );
  1839. }
  1840. else
  1841. FileErrorAddResult();
  1842. return bSuccess;
  1843. }
  1844. bool FilePos::FileWriteText( const MCD_STR& strDoc, int nWriteStrLen/*=-1*/ )
  1845. {
  1846. bool bSuccess = true;
  1847. MCD_STRCLEAR( m_strIOResult );
  1848. MCD_PCSZ pDoc = MCD_2PCSZ(strDoc);
  1849. if ( nWriteStrLen == -1 )
  1850. nWriteStrLen = MCD_STRLENGTH(strDoc);
  1851. if ( ! nWriteStrLen )
  1852. {
  1853. x_AddResult( m_strIOResult, MCD_T("write"), m_strEncoding, MRC_ENCODING|MRC_LENGTH, 0 );
  1854. return bSuccess;
  1855. }
  1856. if ( m_nDocFlags & (CMarkup::MDF_UTF16LEFILE | CMarkup::MDF_UTF16BEFILE) )
  1857. {
  1858. #if defined(MARKUP_WCHAR) // WCHAR
  1859. #if MARKUP_SIZEOFWCHAR == 4 // sizeof(wchar_t) == 4
  1860. TextEncoding textencoding( MCD_T("UTF-32"), (const void*)pDoc, nWriteStrLen );
  1861. m_nOpFileTextLen = textencoding.PerformConversion( NULL, MCD_T("UTF-16") );
  1862. unsigned short* pUTF16Buffer = new unsigned short[m_nOpFileTextLen];
  1863. textencoding.PerformConversion( (void*)pUTF16Buffer );
  1864. x_AddResult( m_strIOResult, MCD_T("converted_from"), MCD_T("UTF-32"), MRC_ENCODING|MRC_LENGTH, nWriteStrLen );
  1865. bSuccess = FileWrite( pUTF16Buffer );
  1866. delete [] pUTF16Buffer;
  1867. #else // sizeof(wchar_t) == 2
  1868. m_nOpFileTextLen = nWriteStrLen;
  1869. bSuccess = FileWrite( NULL, pDoc );
  1870. #endif
  1871. #else // not WCHAR
  1872. TextEncoding textencoding( MCD_ENC, (const void*)pDoc, nWriteStrLen );
  1873. m_nOpFileTextLen = textencoding.PerformConversion( NULL, MCD_T("UTF-16") );
  1874. unsigned short* pUTF16Buffer = new unsigned short[m_nOpFileTextLen];
  1875. textencoding.PerformConversion( (void*)pUTF16Buffer );
  1876. x_AddResult( m_strIOResult, MCD_T("converted_from"), MCD_ENC, MRC_ENCODING|MRC_LENGTH, nWriteStrLen );
  1877. bSuccess = FileWrite( pUTF16Buffer );
  1878. delete [] pUTF16Buffer;
  1879. #endif // not WCHAR
  1880. }
  1881. else // single or multibyte file (i.e. not UTF-16)
  1882. {
  1883. #if ! defined(MARKUP_WCHAR) // not WCHAR
  1884. if ( ! TextEncoding::CanConvert(m_strEncoding,MCD_ENC) )
  1885. {
  1886. // Same or unsupported multi-byte to multi-byte, so save directly from string
  1887. m_nOpFileTextLen = nWriteStrLen;
  1888. bSuccess = FileWrite( NULL, pDoc );
  1889. return bSuccess;
  1890. }
  1891. #endif // not WCHAR
  1892. TextEncoding textencoding( MCD_ENC, (const void*)pDoc, nWriteStrLen );
  1893. m_nOpFileTextLen = textencoding.PerformConversion( NULL, m_strEncoding );
  1894. char* pMBBuffer = new char[m_nOpFileTextLen];
  1895. textencoding.PerformConversion( (void*)pMBBuffer );
  1896. x_AddResult( m_strIOResult, MCD_T("converted_from"), MCD_ENC, MRC_ENCODING|MRC_LENGTH, nWriteStrLen );
  1897. if ( textencoding.m_nFailedChars )
  1898. x_AddResult( m_strIOResult, MCD_T("conversion_loss") );
  1899. bSuccess = FileWrite( pMBBuffer );
  1900. delete [] pMBBuffer;
  1901. }
  1902. return bSuccess;
  1903. }
  1904. bool FilePos::FileClose()
  1905. {
  1906. if ( m_fp )
  1907. {
  1908. if ( fclose(m_fp) )
  1909. FileErrorAddResult();
  1910. m_fp = NULL;
  1911. m_nDocFlags &= ~(CMarkup::MDF_WRITEFILE|CMarkup::MDF_READFILE|CMarkup::MDF_APPENDFILE);
  1912. return true;
  1913. }
  1914. return false;
  1915. }
  1916. bool FilePos::FileReadNextBuffer()
  1917. {
  1918. // If not end of file, returns amount to subtract from offsets
  1919. if ( m_nFileByteOffset < m_nFileByteLen )
  1920. {
  1921. // Prepare to put this node at beginning
  1922. MCD_STR& str = *m_pstrBuffer;
  1923. int nDocLength = MCD_STRLENGTH( str );
  1924. int nRemove = m_nReadBufferStart;
  1925. m_nReadBufferRemoved = nRemove;
  1926. // Gather
  1927. if ( m_nReadGatherStart != -1 )
  1928. {
  1929. if ( m_nReadBufferStart > m_nReadGatherStart )
  1930. {
  1931. // In case it is a large subdoc, reduce reallocs by using x_StrInsertReplace
  1932. MCD_STR strAppend = MCD_STRMID( str, m_nReadGatherStart, m_nReadBufferStart - m_nReadGatherStart );
  1933. x_StrInsertReplace( m_strReadGatherMarkup, MCD_STRLENGTH(m_strReadGatherMarkup), 0, strAppend );
  1934. }
  1935. m_nReadGatherStart = 0;
  1936. }
  1937. // Increase capacity if keeping more than half of nDocLength
  1938. int nKeepLength = nDocLength - nRemove;
  1939. if ( nKeepLength > nDocLength / 2 )
  1940. m_nBlockSizeBasis *= 2;
  1941. if ( nRemove )
  1942. x_StrInsertReplace( str, 0, nRemove, MCD_STR() );
  1943. MCD_STR strRead;
  1944. m_nOpFileByteLen = m_nBlockSizeBasis - nKeepLength;
  1945. m_nOpFileByteLen += 4 - m_nOpFileByteLen % 4; // round up to 4-byte offset
  1946. FileReadText( strRead );
  1947. x_StrInsertReplace( str, nKeepLength, 0, strRead );
  1948. m_nReadBufferStart = 0; // next time just elongate/increase capacity
  1949. return true;
  1950. }
  1951. return false;
  1952. }
  1953. void FilePos::FileGatherStart( int nStart )
  1954. {
  1955. m_nReadGatherStart = nStart;
  1956. }
  1957. int FilePos::FileGatherEnd( MCD_STR& strMarkup )
  1958. {
  1959. int nStart = m_nReadGatherStart;
  1960. m_nReadGatherStart = -1;
  1961. strMarkup = m_strReadGatherMarkup;
  1962. MCD_STRCLEAR( m_strReadGatherMarkup );
  1963. return nStart;
  1964. }
  1965. bool FilePos::FileFlush( MCD_STR& strBuffer, int nWriteStrLen/*=-1*/, bool bFflush/*=false*/ )
  1966. {
  1967. bool bSuccess = true;
  1968. MCD_STRCLEAR( m_strIOResult );
  1969. if ( nWriteStrLen == -1 )
  1970. nWriteStrLen = MCD_STRLENGTH( strBuffer );
  1971. if ( nWriteStrLen )
  1972. {
  1973. if ( (! m_nFileByteOffset) && MCD_STRISEMPTY(m_strEncoding) && ! MCD_STRISEMPTY(strBuffer) )
  1974. {
  1975. m_strEncoding = CMarkup::GetDeclaredEncoding( strBuffer );
  1976. if ( MCD_STRISEMPTY(m_strEncoding) )
  1977. m_strEncoding = MCD_T("UTF-8");
  1978. }
  1979. bSuccess = FileWriteText( strBuffer, nWriteStrLen );
  1980. if ( bSuccess )
  1981. x_StrInsertReplace( strBuffer, 0, nWriteStrLen, MCD_STR() );
  1982. }
  1983. if ( bFflush && bSuccess )
  1984. {
  1985. if ( fflush(m_fp) )
  1986. bSuccess = FileErrorAddResult();
  1987. }
  1988. return bSuccess;
  1989. }
  1990. //////////////////////////////////////////////////////////////////////
  1991. // PathPos encapsulates parsing of the path string used in Find methods
  1992. //
  1993. struct PathPos
  1994. {
  1995. PathPos( MCD_PCSZ pszPath, bool b ) { p=pszPath; bReader=b; i=0; iPathAttribName=0; iSave=0; nPathType=0; if (!ParsePath()) nPathType=-1; };
  1996. int GetTypeAndInc() { i=-1; if (p) { if (p[0]=='/') { if (p[1]=='/') i=2; else i=1; } else if (p[0]) i=0; } nPathType=i+1; return nPathType; };
  1997. int GetNumAndInc() { int n=0; while (p[i]>='0'&&p[i]<='9') n=n*10+(int)p[i++]-(int)'0'; return n; };
  1998. MCD_PCSZ GetValAndInc() { ++i; MCD_CHAR cEnd=']'; if (p[i]=='\''||p[i]=='\"') cEnd=p[i++]; int iVal=i; IncWord(cEnd); nLen=i-iVal; if (cEnd!=']') ++i; return &p[iVal]; };
  1999. int GetValOrWordLen() { return nLen; };
  2000. MCD_CHAR GetChar() { return p[i]; };
  2001. bool IsAtPathEnd() { return ((!p[i])||(iPathAttribName&&i+2>=iPathAttribName))?true:false; };
  2002. MCD_PCSZ GetPtr() { return &p[i]; };
  2003. void SaveOffset() { iSave=i; };
  2004. void RevertOffset() { i=iSave; };
  2005. void RevertOffsetAsName() { i=iSave; nPathType=1; };
  2006. MCD_PCSZ GetWordAndInc() { int iWord=i; IncWord(); nLen=i-iWord; return &p[iWord]; };
  2007. void IncWord() { while (p[i]&&!x_ISENDPATHWORD(p[i])) i+=MCD_CLEN(&p[i]); };
  2008. void IncWord( MCD_CHAR c ) { while (p[i]&&p[i]!=c) i+=MCD_CLEN(&p[i]); };
  2009. void IncChar() { ++i; };
  2010. void Inc( int n ) { i+=n; };
  2011. bool IsAnywherePath() { return nPathType == 3; };
  2012. bool IsAbsolutePath() { return nPathType == 2; };
  2013. bool IsPath() { return nPathType > 0; };
  2014. bool ValidPath() { return nPathType != -1; };
  2015. MCD_PCSZ GetPathAttribName() { if (iPathAttribName) return &p[iPathAttribName]; return NULL; };
  2016. bool AttribPredicateMatch( TokenPos& token );
  2017. private:
  2018. bool ParsePath();
  2019. int nPathType; // -1 invalid, 0 empty, 1 name, 2 absolute path, 3 anywhere path
  2020. bool bReader;
  2021. MCD_PCSZ p;
  2022. int i;
  2023. int iPathAttribName;
  2024. int iSave;
  2025. int nLen;
  2026. };
  2027. bool PathPos::ParsePath()
  2028. {
  2029. // Determine if the path seems to be in a valid format before attempting to find
  2030. if ( GetTypeAndInc() )
  2031. {
  2032. SaveOffset();
  2033. while ( 1 )
  2034. {
  2035. if ( ! GetChar() )
  2036. return false;
  2037. IncWord(); // Tag name
  2038. if ( GetChar() == '[' ) // predicate
  2039. {
  2040. IncChar(); // [
  2041. if ( GetChar() >= '1' && GetChar() <= '9' )
  2042. GetNumAndInc();
  2043. else // attrib or child tag name
  2044. {
  2045. if ( GetChar() == '@' )
  2046. {
  2047. IncChar(); // @
  2048. IncWord(); // attrib name
  2049. if ( GetChar() == '=' )
  2050. GetValAndInc();
  2051. }
  2052. else
  2053. {
  2054. if ( bReader )
  2055. return false;
  2056. IncWord();
  2057. }
  2058. }
  2059. if ( GetChar() != ']' )
  2060. return false;
  2061. IncChar(); // ]
  2062. }
  2063. // Another level of path
  2064. if ( GetChar() == '/' )
  2065. {
  2066. if ( IsAnywherePath() )
  2067. return false; // multiple levels not supported for // path
  2068. IncChar();
  2069. if ( GetChar() == '@' )
  2070. {
  2071. // FindGetData and FindSetData support paths ending in attribute
  2072. IncChar(); // @
  2073. iPathAttribName = i;
  2074. IncWord(); // attrib name
  2075. if ( GetChar() )
  2076. return false; // it should have ended with attribute name
  2077. break;
  2078. }
  2079. }
  2080. else
  2081. {
  2082. if ( GetChar() )
  2083. return false; // not a slash, so it should have ended here
  2084. break;
  2085. }
  2086. }
  2087. RevertOffset();
  2088. }
  2089. return true;
  2090. }
  2091. bool PathPos::AttribPredicateMatch( TokenPos& token )
  2092. {
  2093. // Support attribute predicate matching in regular and file read mode
  2094. // token.m_nNext must already be set to node.nStart + 1 or ELEM(i).nStart + 1
  2095. IncChar(); // @
  2096. if ( token.FindAttrib(GetPtr()) )
  2097. {
  2098. IncWord();
  2099. if ( GetChar() == '=' )
  2100. {
  2101. MCD_PCSZ pszVal = GetValAndInc();
  2102. MCD_STR strPathValue = CMarkup::UnescapeText( pszVal, GetValOrWordLen() );
  2103. MCD_STR strAttribValue = CMarkup::UnescapeText( token.GetTokenPtr(), token.Length(), token.m_nTokenFlags );
  2104. if ( strPathValue != strAttribValue )
  2105. return false;
  2106. }
  2107. return true;
  2108. }
  2109. return false;
  2110. }
  2111. //////////////////////////////////////////////////////////////////////
  2112. // A map is a table of SavedPos structs
  2113. //
  2114. struct SavedPos
  2115. {
  2116. // SavedPos is an entry in the SavedPosMap hash table
  2117. SavedPos() { nSavedPosFlags=0; iPos=0; };
  2118. MCD_STR strName;
  2119. int iPos;
  2120. enum { SPM_MAIN = 1, SPM_CHILD = 2, SPM_USED = 4, SPM_LAST = 8 };
  2121. int nSavedPosFlags;
  2122. };
  2123. struct SavedPosMap
  2124. {
  2125. // SavedPosMap is only created if SavePos/RestorePos are used
  2126. SavedPosMap( int nSize ) { nMapSize=nSize; pTable = new SavedPos*[nSize]; memset(pTable,0,nSize*sizeof(SavedPos*)); };
  2127. ~SavedPosMap() { if (pTable) { for (int n=0;n<nMapSize;++n) if (pTable[n]) delete[] pTable[n]; delete[] pTable; } };
  2128. SavedPos** pTable;
  2129. int nMapSize;
  2130. };
  2131. struct SavedPosMapArray
  2132. {
  2133. // SavedPosMapArray keeps pointers to SavedPosMap instances
  2134. SavedPosMapArray() { m_pMaps = NULL; };
  2135. ~SavedPosMapArray() { ReleaseMaps(); };
  2136. void ReleaseMaps() { SavedPosMap**p = m_pMaps; if (p) { while (*p) delete *p++; delete[] m_pMaps; m_pMaps=NULL; } };
  2137. bool GetMap( SavedPosMap*& pMap, int nMap, int nMapSize = 7 );
  2138. void CopySavedPosMaps( SavedPosMapArray* pOtherMaps );
  2139. SavedPosMap** m_pMaps; // NULL terminated array
  2140. };
  2141. bool SavedPosMapArray::GetMap( SavedPosMap*& pMap, int nMap, int nMapSize /*=7*/ )
  2142. {
  2143. // Find or create map, returns true if map(s) created
  2144. SavedPosMap** pMapsExisting = m_pMaps;
  2145. int nMapIndex = 0;
  2146. if ( pMapsExisting )
  2147. {
  2148. // Length of array is unknown, so loop through maps
  2149. while ( nMapIndex <= nMap )
  2150. {
  2151. pMap = pMapsExisting[nMapIndex];
  2152. if ( ! pMap )
  2153. break;
  2154. if ( nMapIndex == nMap )
  2155. return false; // not created
  2156. ++nMapIndex;
  2157. }
  2158. nMapIndex = 0;
  2159. }
  2160. // Create map(s)
  2161. // If you access map 1 before map 0 created, then 2 maps will be created
  2162. m_pMaps = new SavedPosMap*[nMap+2];
  2163. if ( pMapsExisting )
  2164. {
  2165. while ( pMapsExisting[nMapIndex] )
  2166. {
  2167. m_pMaps[nMapIndex] = pMapsExisting[nMapIndex];
  2168. ++nMapIndex;
  2169. }
  2170. delete[] pMapsExisting;
  2171. }
  2172. while ( nMapIndex <= nMap )
  2173. {
  2174. m_pMaps[nMapIndex] = new SavedPosMap( nMapSize );
  2175. ++nMapIndex;
  2176. }
  2177. m_pMaps[nMapIndex] = NULL;
  2178. pMap = m_pMaps[nMap];
  2179. return true; // map(s) created
  2180. }
  2181. void SavedPosMapArray::CopySavedPosMaps( SavedPosMapArray* pOtherMaps )
  2182. {
  2183. ReleaseMaps();
  2184. if ( pOtherMaps->m_pMaps )
  2185. {
  2186. int nMap = 0;
  2187. SavedPosMap* pMap = NULL;
  2188. while ( pOtherMaps->m_pMaps[nMap] )
  2189. {
  2190. SavedPosMap* pMapSrc = pOtherMaps->m_pMaps[nMap];
  2191. GetMap( pMap, nMap, pMapSrc->nMapSize );
  2192. for ( int nSlot=0; nSlot < pMap->nMapSize; ++nSlot )
  2193. {
  2194. SavedPos* pCopySavedPos = pMapSrc->pTable[nSlot];
  2195. if ( pCopySavedPos )
  2196. {
  2197. int nCount = 0;
  2198. while ( pCopySavedPos[nCount].nSavedPosFlags & SavedPos::SPM_USED )
  2199. {
  2200. ++nCount;
  2201. if ( pCopySavedPos[nCount-1].nSavedPosFlags & SavedPos::SPM_LAST )
  2202. break;
  2203. }
  2204. if ( nCount )
  2205. {
  2206. SavedPos* pNewSavedPos = new SavedPos[nCount];
  2207. for ( int nCopy=0; nCopy<nCount; ++nCopy )
  2208. pNewSavedPos[nCopy] = pCopySavedPos[nCopy];
  2209. pNewSavedPos[nCount-1].nSavedPosFlags |= SavedPos::SPM_LAST;
  2210. pMap->pTable[nSlot] = pNewSavedPos;
  2211. }
  2212. }
  2213. }
  2214. ++nMap;
  2215. }
  2216. }
  2217. }
  2218. //////////////////////////////////////////////////////////////////////
  2219. // Core parser function
  2220. //
  2221. int TokenPos::ParseNode( NodePos& node )
  2222. {
  2223. // Call this with m_nNext set to the start of the node or tag
  2224. // Upon return m_nNext points to the char after the node or tag
  2225. // m_nL and m_nR are set to name location if it is a tag with a name
  2226. // node members set to node location, strMeta used for parse error
  2227. //
  2228. // <!--...--> comment
  2229. // <!DOCTYPE ...> dtd
  2230. // <?target ...?> processing instruction
  2231. // <![CDATA[...]]> cdata section
  2232. // <NAME ...> element start tag
  2233. // </NAME ...> element end tag
  2234. //
  2235. // returns the nodetype or
  2236. // 0 for end tag
  2237. // -1 for bad node
  2238. // -2 for end of document
  2239. //
  2240. enum ParseBits
  2241. {
  2242. PD_OPENTAG = 1,
  2243. PD_BANG = 2,
  2244. PD_DASH = 4,
  2245. PD_BRACKET = 8,
  2246. PD_TEXTORWS = 16,
  2247. PD_DOCTYPE = 32,
  2248. PD_INQUOTE_S = 64,
  2249. PD_INQUOTE_D = 128,
  2250. PD_EQUALS = 256,
  2251. PD_NOQUOTEVAL = 512
  2252. };
  2253. int nParseFlags = 0;
  2254. MCD_PCSZ pFindEnd = NULL;
  2255. int nNodeType = -1;
  2256. int nEndLen = 0;
  2257. int nName = 0;
  2258. int nNameLen = 0;
  2259. unsigned int cDminus1 = 0, cDminus2 = 0;
  2260. #define FINDNODETYPE(e,t) { pFindEnd=e; nEndLen=(sizeof(e)-1)/sizeof(MCD_CHAR); nNodeType=t; }
  2261. #define FINDNODETYPENAME(e,t,n) { FINDNODETYPE(e,t) nName=(int)(pD-m_pDocText)+n; }
  2262. #define FINDNODEBAD(e) { pFindEnd=MCD_T(">"); nEndLen=1; x_AddResult(node.strMeta,e,NULL,0,m_nNext); nNodeType=-1; }
  2263. node.nStart = m_nNext;
  2264. node.nNodeFlags = 0;
  2265. MCD_PCSZ pD = &m_pDocText[m_nNext];
  2266. unsigned int cD;
  2267. while ( 1 )
  2268. {
  2269. cD = (unsigned int)*pD;
  2270. if ( ! cD )
  2271. {
  2272. m_nNext = (int)(pD - m_pDocText);
  2273. if ( m_pReaderFilePos ) // read file mode
  2274. {
  2275. // Read buffer may only be removed on the first FileReadNextBuffer in this node
  2276. int nRemovedAlready = m_pReaderFilePos->m_nReadBufferRemoved;
  2277. if ( m_pReaderFilePos->FileReadNextBuffer() ) // more text in file?
  2278. {
  2279. int nNodeLength = m_nNext - node.nStart;
  2280. int nRemove = m_pReaderFilePos->m_nReadBufferRemoved;
  2281. if ( nRemove )
  2282. {
  2283. node.nStart -= nRemove;
  2284. if ( nName )
  2285. nName -= nRemove;
  2286. else if ( nNameLen )
  2287. {
  2288. m_nL -= nRemove;
  2289. m_nR -= nRemove;
  2290. }
  2291. m_nNext -= nRemove;
  2292. }
  2293. int nNewOffset = node.nStart + nNodeLength;
  2294. MCD_STR& str = *m_pReaderFilePos->m_pstrBuffer;
  2295. m_pDocText = MCD_2PCSZ( str );
  2296. pD = &m_pDocText[nNewOffset];
  2297. cD = (unsigned int)*pD; // loaded char replaces null terminator
  2298. }
  2299. if (nRemovedAlready) // preserve m_nReadBufferRemoved for caller of ParseNode
  2300. m_pReaderFilePos->m_nReadBufferRemoved = nRemovedAlready;
  2301. }
  2302. if ( ! cD )
  2303. {
  2304. if ( m_nNext == node.nStart )
  2305. {
  2306. node.nLength = 0;
  2307. node.nNodeType = 0;
  2308. return -2; // end of document
  2309. }
  2310. if ( nNodeType != CMarkup::MNT_WHITESPACE && nNodeType != CMarkup::MNT_TEXT )
  2311. {
  2312. MCD_PCSZ pType = MCD_T("tag");
  2313. if ( (nParseFlags & PD_DOCTYPE) || nNodeType == CMarkup::MNT_DOCUMENT_TYPE )
  2314. pType = MCD_T("document_type");
  2315. else if ( nNodeType == CMarkup::MNT_ELEMENT )
  2316. pType = MCD_T("start_tag");
  2317. else if ( nNodeType == 0 )
  2318. pType = MCD_T("end_tag");
  2319. else if ( nNodeType == CMarkup::MNT_CDATA_SECTION )
  2320. pType = MCD_T("cdata_section");
  2321. else if ( nNodeType == CMarkup::MNT_PROCESSING_INSTRUCTION )
  2322. pType = MCD_T("processing_instruction");
  2323. else if ( nNodeType == CMarkup::MNT_COMMENT )
  2324. pType = MCD_T("comment");
  2325. nNodeType = -1;
  2326. x_AddResult(node.strMeta,MCD_T("unterminated_tag_syntax"),pType,MRC_TYPE,node.nStart);
  2327. }
  2328. break;
  2329. }
  2330. }
  2331. if ( nName )
  2332. {
  2333. if ( x_ISENDNAME(cD) )
  2334. {
  2335. nNameLen = (int)(pD - m_pDocText) - nName;
  2336. m_nL = nName;
  2337. m_nR = nName + nNameLen - 1;
  2338. nName = 0;
  2339. cDminus2 = 0;
  2340. cDminus1 = 0;
  2341. }
  2342. else
  2343. {
  2344. pD += MCD_CLEN( pD );
  2345. continue;
  2346. }
  2347. }
  2348. if ( pFindEnd )
  2349. {
  2350. if ( cD == '>' && ! (nParseFlags & (PD_INQUOTE_S|PD_INQUOTE_D)) )
  2351. {
  2352. m_nNext = (int)(pD - m_pDocText) + 1;
  2353. if ( nEndLen == 1 )
  2354. {
  2355. pFindEnd = NULL;
  2356. if ( nNodeType == CMarkup::MNT_ELEMENT && cDminus1 == '/' )
  2357. {
  2358. if ( (! cDminus2) || (!(nParseFlags&PD_NOQUOTEVAL)) || x_ISNOTSECONDLASTINVAL(cDminus2) )
  2359. node.nNodeFlags |= MNF_EMPTY;
  2360. }
  2361. }
  2362. else if ( m_nNext - 1 > nEndLen )
  2363. {
  2364. // Test for end of PI or comment
  2365. MCD_PCSZ pEnd = pD - nEndLen + 1;
  2366. MCD_PCSZ pInFindEnd = pFindEnd;
  2367. int nLen = nEndLen;
  2368. while ( --nLen && *pEnd++ == *pInFindEnd++ );
  2369. if ( nLen == 0 )
  2370. pFindEnd = NULL;
  2371. }
  2372. nParseFlags &= ~PD_NOQUOTEVAL; // make sure PD_NOQUOTEVAL is off
  2373. if ( ! pFindEnd && ! (nParseFlags & PD_DOCTYPE) )
  2374. break;
  2375. }
  2376. else if ( cD == '<' && (nNodeType == CMarkup::MNT_TEXT || nNodeType == -1) )
  2377. {
  2378. m_nNext = (int)(pD - m_pDocText);
  2379. break;
  2380. }
  2381. else if ( nNodeType & CMarkup::MNT_ELEMENT )
  2382. {
  2383. if ( (nParseFlags & (PD_INQUOTE_S|PD_INQUOTE_D|PD_NOQUOTEVAL)) )
  2384. {
  2385. if ( cD == '\"' && (nParseFlags&PD_INQUOTE_D) )
  2386. nParseFlags ^= PD_INQUOTE_D; // off
  2387. else if ( cD == '\'' && (nParseFlags&PD_INQUOTE_S) )
  2388. nParseFlags ^= PD_INQUOTE_S; // off
  2389. else if ( (nParseFlags&PD_NOQUOTEVAL) && x_ISWHITESPACE(cD) )
  2390. nParseFlags ^= PD_NOQUOTEVAL; // off
  2391. }
  2392. else // not in attrib value
  2393. {
  2394. // Only set INQUOTE status when preceeded by equal sign
  2395. if ( cD == '\"' && (nParseFlags&PD_EQUALS) )
  2396. nParseFlags ^= PD_INQUOTE_D|PD_EQUALS; // D on, equals off
  2397. else if ( cD == '\'' && (nParseFlags&PD_EQUALS) )
  2398. nParseFlags ^= PD_INQUOTE_S|PD_EQUALS; // S on, equals off
  2399. else if ( cD == '=' && cDminus1 != '=' && ! (nParseFlags&PD_EQUALS) )
  2400. nParseFlags ^= PD_EQUALS; // on
  2401. else if ( (nParseFlags&PD_EQUALS) && ! x_ISWHITESPACE(cD) )
  2402. nParseFlags ^= PD_NOQUOTEVAL|PD_EQUALS; // no quote val on, equals off
  2403. }
  2404. cDminus2 = cDminus1;
  2405. cDminus1 = cD;
  2406. }
  2407. else if ( nNodeType & CMarkup::MNT_DOCUMENT_TYPE )
  2408. {
  2409. if ( cD == '\"' && ! (nParseFlags&PD_INQUOTE_S) )
  2410. nParseFlags ^= PD_INQUOTE_D; // toggle
  2411. else if ( cD == '\'' && ! (nParseFlags&PD_INQUOTE_D) )
  2412. nParseFlags ^= PD_INQUOTE_S; // toggle
  2413. }
  2414. }
  2415. else if ( nParseFlags )
  2416. {
  2417. if ( nParseFlags & PD_TEXTORWS )
  2418. {
  2419. if ( cD == '<' )
  2420. {
  2421. m_nNext = (int)(pD - m_pDocText);
  2422. nNodeType = CMarkup::MNT_WHITESPACE;
  2423. break;
  2424. }
  2425. else if ( ! x_ISWHITESPACE(cD) )
  2426. {
  2427. nParseFlags ^= PD_TEXTORWS;
  2428. FINDNODETYPE( MCD_T("<"), CMarkup::MNT_TEXT )
  2429. }
  2430. }
  2431. else if ( nParseFlags & PD_OPENTAG )
  2432. {
  2433. nParseFlags ^= PD_OPENTAG;
  2434. if ( cD > 0x60 || ( cD > 0x40 && cD < 0x5b ) || cD == 0x5f || cD == 0x3a )
  2435. FINDNODETYPENAME( MCD_T(">"), CMarkup::MNT_ELEMENT, 0 )
  2436. else if ( cD == '/' )
  2437. FINDNODETYPENAME( MCD_T(">"), 0, 1 )
  2438. else if ( cD == '!' )
  2439. nParseFlags |= PD_BANG;
  2440. else if ( cD == '?' )
  2441. FINDNODETYPENAME( MCD_T("?>"), CMarkup::MNT_PROCESSING_INSTRUCTION, 1 )
  2442. else
  2443. FINDNODEBAD( MCD_T("first_tag_syntax") )
  2444. }
  2445. else if ( nParseFlags & PD_BANG )
  2446. {
  2447. nParseFlags ^= PD_BANG;
  2448. if ( cD == '-' )
  2449. nParseFlags |= PD_DASH;
  2450. else if ( nParseFlags & PD_DOCTYPE )
  2451. {
  2452. if ( x_ISDOCTYPESTART(cD) ) // <!ELEMENT ATTLIST ENTITY NOTATION
  2453. FINDNODETYPE( MCD_T(">"), CMarkup::MNT_DOCUMENT_TYPE )
  2454. else
  2455. FINDNODEBAD( MCD_T("doctype_tag_syntax") )
  2456. }
  2457. else
  2458. {
  2459. if ( cD == '[' )
  2460. nParseFlags |= PD_BRACKET;
  2461. else if ( cD == 'D' )
  2462. nParseFlags |= PD_DOCTYPE;
  2463. else
  2464. FINDNODEBAD( MCD_T("exclamation_tag_syntax") )
  2465. }
  2466. }
  2467. else if ( nParseFlags & PD_DASH )
  2468. {
  2469. nParseFlags ^= PD_DASH;
  2470. if ( cD == '-' )
  2471. FINDNODETYPE( MCD_T("-->"), CMarkup::MNT_COMMENT )
  2472. else
  2473. FINDNODEBAD( MCD_T("comment_tag_syntax") )
  2474. }
  2475. else if ( nParseFlags & PD_BRACKET )
  2476. {
  2477. nParseFlags ^= PD_BRACKET;
  2478. if ( cD == 'C' )
  2479. FINDNODETYPE( MCD_T("]]>"), CMarkup::MNT_CDATA_SECTION )
  2480. else
  2481. FINDNODEBAD( MCD_T("cdata_section_syntax") )
  2482. }
  2483. else if ( nParseFlags & PD_DOCTYPE )
  2484. {
  2485. if ( cD == '<' )
  2486. nParseFlags |= PD_OPENTAG;
  2487. else if ( cD == '>' )
  2488. {
  2489. m_nNext = (int)(pD - m_pDocText) + 1;
  2490. nNodeType = CMarkup::MNT_DOCUMENT_TYPE;
  2491. break;
  2492. }
  2493. }
  2494. }
  2495. else if ( cD == '<' )
  2496. {
  2497. nParseFlags |= PD_OPENTAG;
  2498. }
  2499. else
  2500. {
  2501. nNodeType = CMarkup::MNT_WHITESPACE;
  2502. if ( x_ISWHITESPACE(cD) )
  2503. nParseFlags |= PD_TEXTORWS;
  2504. else
  2505. FINDNODETYPE( MCD_T("<"), CMarkup::MNT_TEXT )
  2506. }
  2507. pD += MCD_CLEN( pD );
  2508. }
  2509. node.nLength = m_nNext - node.nStart;
  2510. node.nNodeType = nNodeType;
  2511. return nNodeType;
  2512. }
  2513. //////////////////////////////////////////////////////////////////////
  2514. // CMarkup public methods
  2515. //
  2516. CMarkup::~CMarkup()
  2517. {
  2518. delete m_pSavedPosMaps;
  2519. delete m_pElemPosTree;
  2520. }
  2521. void CMarkup::operator=( const CMarkup& markup )
  2522. {
  2523. // Copying not supported during file mode because of file pointer
  2524. if ( (m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE)) || (markup.m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE)) )
  2525. return;
  2526. m_iPosParent = markup.m_iPosParent;
  2527. m_iPos = markup.m_iPos;
  2528. m_iPosChild = markup.m_iPosChild;
  2529. m_iPosFree = markup.m_iPosFree;
  2530. m_iPosDeleted = markup.m_iPosDeleted;
  2531. m_nNodeType = markup.m_nNodeType;
  2532. m_nNodeOffset = markup.m_nNodeOffset;
  2533. m_nNodeLength = markup.m_nNodeLength;
  2534. m_strDoc = markup.m_strDoc;
  2535. m_strResult = markup.m_strResult;
  2536. m_nDocFlags = markup.m_nDocFlags;
  2537. m_pElemPosTree->CopyElemPosTree( markup.m_pElemPosTree, m_iPosFree );
  2538. m_pSavedPosMaps->CopySavedPosMaps( markup.m_pSavedPosMaps );
  2539. MARKUP_SETDEBUGSTATE;
  2540. }
  2541. bool CMarkup::SetDoc( MCD_PCSZ pDoc )
  2542. {
  2543. // pDoc is markup text, not a filename!
  2544. if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
  2545. return false;
  2546. // Set document text
  2547. if ( pDoc )
  2548. m_strDoc = pDoc;
  2549. else
  2550. {
  2551. MCD_STRCLEARSIZE( m_strDoc );
  2552. m_pElemPosTree->ReleaseElemPosTree();
  2553. }
  2554. MCD_STRCLEAR(m_strResult);
  2555. return x_ParseDoc();
  2556. }
  2557. bool CMarkup::SetDoc( const MCD_STR& strDoc )
  2558. {
  2559. // strDoc is markup text, not a filename!
  2560. if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
  2561. return false;
  2562. m_strDoc = strDoc;
  2563. MCD_STRCLEAR(m_strResult);
  2564. return x_ParseDoc();
  2565. }
  2566. bool CMarkup::IsWellFormed()
  2567. {
  2568. if ( m_nDocFlags & MDF_WRITEFILE )
  2569. return true;
  2570. if ( m_nDocFlags & MDF_READFILE )
  2571. {
  2572. if ( ! (ELEM(0).nFlags & MNF_ILLFORMED) )
  2573. return true;
  2574. }
  2575. else if ( m_pElemPosTree->GetSize()
  2576. && ! (ELEM(0).nFlags & MNF_ILLFORMED)
  2577. && ELEM(0).iElemChild
  2578. && ! ELEM(ELEM(0).iElemChild).iElemNext )
  2579. return true;
  2580. return false;
  2581. }
  2582. MCD_STR CMarkup::GetError() const
  2583. {
  2584. // For backwards compatibility, return a readable English string built from m_strResult
  2585. // In release 11.0 you can use GetResult and examine result in XML format
  2586. CMarkup mResult( m_strResult );
  2587. MCD_STR strError;
  2588. int nSyntaxErrors = 0;
  2589. while ( mResult.FindElem() )
  2590. {
  2591. MCD_STR strItem;
  2592. MCD_STR strID = mResult.GetTagName();
  2593. // Parse result
  2594. if ( strID == MCD_T("root_has_sibling") )
  2595. strItem = MCD_T("root element has sibling");
  2596. else if ( strID == MCD_T("no_root_element") )
  2597. strItem = MCD_T("no root element");
  2598. else if ( strID == MCD_T("lone_end_tag") )
  2599. strItem = MCD_T("lone end tag '") + mResult.GetAttrib(MCD_T("tagname")) + MCD_T("' at offset ")
  2600. + mResult.GetAttrib(MCD_T("offset"));
  2601. else if ( strID == MCD_T("unended_start_tag") )
  2602. strItem = MCD_T("start tag '") + mResult.GetAttrib(MCD_T("tagname")) + MCD_T("' at offset ")
  2603. + mResult.GetAttrib(MCD_T("offset")) + MCD_T(" expecting end tag at offset ") + mResult.GetAttrib(MCD_T("offset2"));
  2604. else if ( strID == MCD_T("first_tag_syntax") )
  2605. strItem = MCD_T("tag syntax error at offset ") + mResult.GetAttrib(MCD_T("offset"))
  2606. + MCD_T(" expecting tag name / ! or ?");
  2607. else if ( strID == MCD_T("exclamation_tag_syntax") )
  2608. strItem = MCD_T("tag syntax error at offset ") + mResult.GetAttrib(MCD_T("offset"))
  2609. + MCD_T(" expecting 'DOCTYPE' [ or -");
  2610. else if ( strID == MCD_T("doctype_tag_syntax") )
  2611. strItem = MCD_T("tag syntax error at offset ") + mResult.GetAttrib(MCD_T("offset"))
  2612. + MCD_T(" expecting markup declaration"); // ELEMENT ATTLIST ENTITY NOTATION
  2613. else if ( strID == MCD_T("comment_tag_syntax") )
  2614. strItem = MCD_T("tag syntax error at offset ") + mResult.GetAttrib(MCD_T("offset"))
  2615. + MCD_T(" expecting - to begin comment");
  2616. else if ( strID == MCD_T("cdata_section_syntax") )
  2617. strItem = MCD_T("tag syntax error at offset ") + mResult.GetAttrib(MCD_T("offset"))
  2618. + MCD_T(" expecting 'CDATA'");
  2619. else if ( strID == MCD_T("unterminated_tag_syntax") )
  2620. strItem = MCD_T("unterminated tag at offset ") + mResult.GetAttrib(MCD_T("offset"));
  2621. // Report only the first syntax or well-formedness error
  2622. if ( ! MCD_STRISEMPTY(strItem) )
  2623. {
  2624. ++nSyntaxErrors;
  2625. if ( nSyntaxErrors > 1 )
  2626. continue;
  2627. }
  2628. // I/O results
  2629. if ( strID == MCD_T("file_error") )
  2630. strItem = mResult.GetAttrib(MCD_T("msg"));
  2631. else if ( strID == MCD_T("bom") )
  2632. strItem = MCD_T("BOM +");
  2633. else if ( strID == MCD_T("read") || strID == MCD_T("write") || strID == MCD_T("converted_to") || strID == MCD_T("converted_from") )
  2634. {
  2635. if ( strID == MCD_T("converted_to") )
  2636. strItem = MCD_T("to ");
  2637. MCD_STR strEncoding = mResult.GetAttrib( MCD_T("encoding") );
  2638. if ( ! MCD_STRISEMPTY(strEncoding) )
  2639. strItem += strEncoding + MCD_T(" ");
  2640. strItem += MCD_T("length ") + mResult.GetAttrib(MCD_T("length"));
  2641. if ( strID == MCD_T("converted_from") )
  2642. strItem += MCD_T(" to");
  2643. }
  2644. else if ( strID == MCD_T("nulls_removed") )
  2645. strItem = MCD_T("removed ") + mResult.GetAttrib(MCD_T("count")) + MCD_T(" nulls");
  2646. else if ( strID == MCD_T("conversion_loss") )
  2647. strItem = MCD_T("(chars lost in conversion!)");
  2648. else if ( strID == MCD_T("utf8_detection") )
  2649. strItem = MCD_T("(used UTF-8 detection)");
  2650. else if ( strID == MCD_T("endian_swap") )
  2651. strItem = MCD_T("endian swap");
  2652. else if ( strID == MCD_T("truncation_error") )
  2653. strItem = MCD_T("encoding ") + mResult.GetAttrib(MCD_T("encoding")) + MCD_T(" adjustment error");
  2654. // Concatenate result item to error string
  2655. if ( ! MCD_STRISEMPTY(strItem) )
  2656. {
  2657. if ( ! MCD_STRISEMPTY(strError) )
  2658. strError += MCD_T(" ");
  2659. strError += strItem;
  2660. }
  2661. }
  2662. return strError;
  2663. }
  2664. bool CMarkup::Load( MCD_CSTR_FILENAME szFileName )
  2665. {
  2666. if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
  2667. return false;
  2668. if ( ! ReadTextFile(szFileName, m_strDoc, &m_strResult, &m_nDocFlags) )
  2669. return false;
  2670. return x_ParseDoc();
  2671. }
  2672. bool CMarkup::ReadTextFile( MCD_CSTR_FILENAME szFileName, MCD_STR& strDoc, MCD_STR* pstrResult, int* pnDocFlags, MCD_STR* pstrEncoding )
  2673. {
  2674. // Static utility method to load text file into strDoc
  2675. //
  2676. FilePos file;
  2677. file.m_nDocFlags = (pnDocFlags?*pnDocFlags:0) | MDF_READFILE;
  2678. bool bSuccess = file.FileOpen( szFileName );
  2679. if ( pstrResult )
  2680. *pstrResult = file.m_strIOResult;
  2681. MCD_STRCLEAR(strDoc);
  2682. if ( bSuccess )
  2683. {
  2684. file.FileSpecifyEncoding( pstrEncoding );
  2685. file.m_nOpFileByteLen = (int)((MCD_INTFILEOFFSET)(file.m_nFileByteLen - file.m_nFileByteOffset));
  2686. bSuccess = file.FileReadText( strDoc );
  2687. file.FileClose();
  2688. if ( pstrResult )
  2689. *pstrResult += file.m_strIOResult;
  2690. if ( pnDocFlags )
  2691. *pnDocFlags = file.m_nDocFlags;
  2692. }
  2693. return bSuccess;
  2694. }
  2695. bool CMarkup::Save( MCD_CSTR_FILENAME szFileName )
  2696. {
  2697. if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
  2698. return false;
  2699. return WriteTextFile( szFileName, m_strDoc, &m_strResult, &m_nDocFlags );
  2700. }
  2701. bool CMarkup::WriteTextFile( MCD_CSTR_FILENAME szFileName, const MCD_STR& strDoc, MCD_STR* pstrResult, int* pnDocFlags, MCD_STR* pstrEncoding )
  2702. {
  2703. // Static utility method to save strDoc to text file
  2704. //
  2705. FilePos file;
  2706. file.m_nDocFlags = (pnDocFlags?*pnDocFlags:0) | MDF_WRITEFILE;
  2707. bool bSuccess = file.FileOpen( szFileName );
  2708. if ( pstrResult )
  2709. *pstrResult = file.m_strIOResult;
  2710. if ( bSuccess )
  2711. {
  2712. if ( MCD_STRISEMPTY(file.m_strEncoding) && ! MCD_STRISEMPTY(strDoc) )
  2713. {
  2714. file.m_strEncoding = GetDeclaredEncoding( strDoc );
  2715. if ( MCD_STRISEMPTY(file.m_strEncoding) )
  2716. file.m_strEncoding = MCD_T("UTF-8"); // to do: MDF_ANSIFILE
  2717. }
  2718. file.FileSpecifyEncoding( pstrEncoding );
  2719. bSuccess = file.FileWriteText( strDoc );
  2720. file.FileClose();
  2721. if ( pstrResult )
  2722. *pstrResult += file.m_strIOResult;
  2723. if ( pnDocFlags )
  2724. *pnDocFlags = file.m_nDocFlags;
  2725. }
  2726. return bSuccess;
  2727. }
  2728. bool CMarkup::FindElem( MCD_CSTR szName )
  2729. {
  2730. if ( m_nDocFlags & MDF_WRITEFILE )
  2731. return false;
  2732. if ( m_pElemPosTree->GetSize() )
  2733. {
  2734. // Change current position only if found
  2735. PathPos path( szName, false );
  2736. int iPos = x_FindElem( m_iPosParent, m_iPos, path );
  2737. if ( iPos )
  2738. {
  2739. // Assign new position
  2740. x_SetPos( ELEM(iPos).iElemParent, iPos, 0 );
  2741. return true;
  2742. }
  2743. }
  2744. return false;
  2745. }
  2746. bool CMarkup::FindChildElem( MCD_CSTR szName )
  2747. {
  2748. if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
  2749. return false;
  2750. // Shorthand: if no current main position, find first child under parent element
  2751. if ( ! m_iPos )
  2752. FindElem();
  2753. // Change current child position only if found
  2754. PathPos path( szName, false );
  2755. int iPosChild = x_FindElem( m_iPos, m_iPosChild, path );
  2756. if ( iPosChild )
  2757. {
  2758. // Assign new position
  2759. int iPos = ELEM(iPosChild).iElemParent;
  2760. x_SetPos( ELEM(iPos).iElemParent, iPos, iPosChild );
  2761. return true;
  2762. }
  2763. return false;
  2764. }
  2765. MCD_STR CMarkup::EscapeText( MCD_CSTR szText, int nFlags )
  2766. {
  2767. // Convert text as seen outside XML document to XML friendly
  2768. // replacing special characters with ampersand escape codes
  2769. // E.g. convert "6>7" to "6&gt;7"
  2770. //
  2771. // &lt; less than
  2772. // &amp; ampersand
  2773. // &gt; greater than
  2774. //
  2775. // and for attributes:
  2776. //
  2777. // &apos; apostrophe or single quote
  2778. // &quot; double quote
  2779. //
  2780. static MCD_PCSZ apReplace[] = { NULL,MCD_T("&lt;"),MCD_T("&amp;"),MCD_T("&gt;"),MCD_T("&quot;"),MCD_T("&apos;") };
  2781. MCD_STR strText;
  2782. MCD_PCSZ pSource = szText;
  2783. int nDestSize = MCD_PSZLEN(pSource);
  2784. nDestSize += nDestSize / 10 + 7;
  2785. MCD_BLDRESERVE(strText,nDestSize);
  2786. MCD_CHAR cSource = *pSource;
  2787. int nFound;
  2788. int nCharLen;
  2789. while ( cSource )
  2790. {
  2791. MCD_BLDCHECK(strText,nDestSize,6);
  2792. nFound = ((nFlags&MNF_ESCAPEQUOTES)?x_ISATTRIBSPECIAL(cSource):x_ISSPECIAL(cSource));
  2793. if ( nFound )
  2794. {
  2795. bool bIgnoreAmpersand = false;
  2796. if ( (nFlags&MNF_WITHREFS) && cSource == '&' )
  2797. {
  2798. // Do not replace ampersand if it is start of any entity reference
  2799. // &[#_:A-Za-zU][_:-.A-Za-z0-9U]*; where U is > 0x7f
  2800. MCD_PCSZ pCheckEntity = pSource;
  2801. ++pCheckEntity;
  2802. MCD_CHAR c = *pCheckEntity;
  2803. if ( x_ISSTARTENTREF(c) || ((unsigned int)c)>0x7f )
  2804. {
  2805. while ( 1 )
  2806. {
  2807. pCheckEntity += MCD_CLEN( pCheckEntity );
  2808. c = *pCheckEntity;
  2809. if ( c == ';' )
  2810. {
  2811. int nEntityLen = (int)(pCheckEntity - pSource) + 1;
  2812. MCD_BLDAPPENDN(strText,pSource,nEntityLen);
  2813. pSource = pCheckEntity;
  2814. bIgnoreAmpersand = true;
  2815. }
  2816. else if ( x_ISINENTREF(c) || ((unsigned int)c)>0x7f )
  2817. continue;
  2818. break;
  2819. }
  2820. }
  2821. }
  2822. if ( ! bIgnoreAmpersand )
  2823. {
  2824. MCD_BLDAPPEND(strText,apReplace[nFound]);
  2825. }
  2826. ++pSource; // ASCII, so 1 byte
  2827. }
  2828. else
  2829. {
  2830. nCharLen = MCD_CLEN( pSource );
  2831. MCD_BLDAPPENDN(strText,pSource,nCharLen);
  2832. pSource += nCharLen;
  2833. }
  2834. cSource = *pSource;
  2835. }
  2836. MCD_BLDRELEASE(strText);
  2837. return strText;
  2838. }
  2839. // Predefined character entities
  2840. // By default UnescapeText will decode standard HTML entities as well as the 5 in XML
  2841. // To unescape only the 5 standard XML entities, use this short table instead:
  2842. // MCD_PCSZ PredefEntityTable[4] =
  2843. // { MCD_T("20060lt"),MCD_T("40034quot"),MCD_T("30038amp"),MCD_T("20062gt40039apos") };
  2844. //
  2845. // This is a precompiled ASCII hash table for speed and minimum memory requirement
  2846. // Each entry consists of a 1 digit code name length, 4 digit code point, and the code name
  2847. // Each table slot can have multiple entries, table size 130 was chosen for even distribution
  2848. //
  2849. MCD_PCSZ PredefEntityTable[130] =
  2850. {
  2851. MCD_T("60216oslash60217ugrave60248oslash60249ugrave"),
  2852. MCD_T("50937omega60221yacute58968lceil50969omega60253yacute"),
  2853. MCD_T("50916delta50206icirc50948delta50238icirc68472weierp"),MCD_T("40185sup1"),
  2854. MCD_T("68970lfloor40178sup2"),
  2855. MCD_T("50922kappa60164curren50954kappa58212mdash40179sup3"),
  2856. MCD_T("59830diams58211ndash"),MCD_T("68855otimes58969rceil"),
  2857. MCD_T("50338oelig50212ocirc50244ocirc50339oelig58482trade"),
  2858. MCD_T("50197aring50931sigma50229aring50963sigma"),
  2859. MCD_T("50180acute68971rfloor50732tilde"),MCD_T("68249lsaquo"),
  2860. MCD_T("58734infin68201thinsp"),MCD_T("50161iexcl"),
  2861. MCD_T("50920theta50219ucirc50952theta50251ucirc"),MCD_T("58254oline"),
  2862. MCD_T("58260frasl68727lowast"),MCD_T("59827clubs60191iquest68250rsaquo"),
  2863. MCD_T("58629crarr50181micro"),MCD_T("58222bdquo"),MCD_T(""),
  2864. MCD_T("58243prime60177plusmn58242prime"),MCD_T("40914beta40946beta"),MCD_T(""),
  2865. MCD_T(""),MCD_T(""),MCD_T("50171laquo50215times"),MCD_T("40710circ"),
  2866. MCD_T("49001lang"),MCD_T("58220ldquo40175macr"),
  2867. MCD_T("40182para50163pound48476real"),MCD_T(""),MCD_T("58713notin50187raquo"),
  2868. MCD_T("48773cong50223szlig50978upsih"),
  2869. MCD_T("58776asymp58801equiv49002rang58218sbquo"),
  2870. MCD_T("50222thorn48659darr48595darr40402fnof58221rdquo50254thorn"),
  2871. MCD_T("40162cent58722minus"),MCD_T("58707exist40170ordf"),MCD_T(""),
  2872. MCD_T("40921iota58709empty48660harr48596harr40953iota"),MCD_T(""),
  2873. MCD_T("40196auml40228auml48226bull40167sect48838sube"),MCD_T(""),
  2874. MCD_T("48656larr48592larr58853oplus"),MCD_T("30176deg58216lsquo40186ordm"),
  2875. MCD_T("40203euml40039apos40235euml48712isin40160nbsp"),
  2876. MCD_T("40918zeta40950zeta"),MCD_T("38743and48195emsp48719prod"),
  2877. MCD_T("30935chi38745cap30967chi48194ensp"),
  2878. MCD_T("40207iuml40239iuml48706part48869perp48658rarr48594rarr"),
  2879. MCD_T("38736ang48836nsub58217rsquo"),MCD_T(""),
  2880. MCD_T("48901sdot48657uarr48593uarr"),MCD_T("40169copy48364euro"),
  2881. MCD_T("30919eta30951eta"),MCD_T("40214ouml40246ouml48839supe"),MCD_T(""),
  2882. MCD_T(""),MCD_T("30038amp30174reg"),MCD_T("48733prop"),MCD_T(""),
  2883. MCD_T("30208eth30934phi40220uuml30240eth30966phi40252uuml"),MCD_T(""),MCD_T(""),
  2884. MCD_T(""),MCD_T("40376yuml40255yuml"),MCD_T(""),MCD_T("40034quot48204zwnj"),
  2885. MCD_T("38746cup68756there4"),MCD_T("30929rho30961rho38764sim"),
  2886. MCD_T("30932tau38834sub30964tau"),MCD_T("38747int38206lrm38207rlm"),
  2887. MCD_T("30936psi30968psi30165yen"),MCD_T(""),MCD_T("28805ge30168uml"),
  2888. MCD_T("30982piv"),MCD_T(""),MCD_T("30172not"),MCD_T(""),MCD_T("28804le"),
  2889. MCD_T("30173shy"),MCD_T("39674loz28800ne38721sum"),MCD_T(""),MCD_T(""),
  2890. MCD_T("38835sup"),MCD_T("28715ni"),MCD_T(""),MCD_T("20928pi20960pi38205zwj"),
  2891. MCD_T(""),MCD_T("60923lambda20062gt60955lambda"),MCD_T(""),MCD_T(""),
  2892. MCD_T("60199ccedil60231ccedil"),MCD_T(""),MCD_T("20060lt"),
  2893. MCD_T("20926xi28744or20958xi"),MCD_T("20924mu20956mu"),MCD_T("20925nu20957nu"),
  2894. MCD_T("68225dagger68224dagger"),MCD_T("80977thetasym"),MCD_T(""),MCD_T(""),
  2895. MCD_T(""),MCD_T("78501alefsym"),MCD_T(""),MCD_T(""),MCD_T(""),
  2896. MCD_T("60193aacute60195atilde60225aacute60227atilde"),MCD_T(""),
  2897. MCD_T("70927omicron60247divide70959omicron"),MCD_T("60192agrave60224agrave"),
  2898. MCD_T("60201eacute60233eacute60962sigmaf"),MCD_T("70917epsilon70949epsilon"),
  2899. MCD_T(""),MCD_T("60200egrave60232egrave"),MCD_T("60205iacute60237iacute"),
  2900. MCD_T(""),MCD_T(""),MCD_T("60204igrave68230hellip60236igrave"),
  2901. MCD_T("60166brvbar"),
  2902. MCD_T("60209ntilde68704forall58711nabla60241ntilde69824spades"),
  2903. MCD_T("60211oacute60213otilde60189frac1260183middot60243oacute60245otilde"),
  2904. MCD_T(""),MCD_T("50184cedil60188frac14"),
  2905. MCD_T("50198aelig50194acirc60210ograve50226acirc50230aelig60242ograve"),
  2906. MCD_T("50915gamma60190frac3450947gamma58465image58730radic"),
  2907. MCD_T("60352scaron60353scaron"),MCD_T("60218uacute69829hearts60250uacute"),
  2908. MCD_T("50913alpha50202ecirc70933upsilon50945alpha50234ecirc70965upsilon"),
  2909. MCD_T("68240permil")
  2910. };
  2911. MCD_STR CMarkup::UnescapeText( MCD_CSTR szText, int nTextLength /*=-1*/, int nFlags /*=0*/ )
  2912. {
  2913. // Convert XML friendly text to text as seen outside XML document
  2914. // ampersand escape codes replaced with special characters e.g. convert "6&gt;7" to "6>7"
  2915. // ampersand numeric codes replaced with character e.g. convert &#60; to <
  2916. // Conveniently the result is always the same or shorter in byte length
  2917. //
  2918. MCD_STR strText;
  2919. MCD_PCSZ pSource = szText;
  2920. if ( nTextLength == -1 )
  2921. nTextLength = MCD_PSZLEN(szText);
  2922. MCD_BLDRESERVE(strText,nTextLength);
  2923. MCD_CHAR szCodeName[10];
  2924. bool bAlterWhitespace = (nFlags & (MDF_TRIMWHITESPACE|MDF_COLLAPSEWHITESPACE))?true:false;
  2925. bool bCollapseWhitespace = (nFlags & MDF_COLLAPSEWHITESPACE)?true:false;
  2926. int nCharWhitespace = -1; // start of string
  2927. int nCharLen;
  2928. int nChar = 0;
  2929. while ( nChar < nTextLength )
  2930. {
  2931. if ( pSource[nChar] == '&' )
  2932. {
  2933. if ( bAlterWhitespace )
  2934. nCharWhitespace = 0;
  2935. // Get corresponding unicode code point
  2936. int nUnicode = 0;
  2937. // Look for terminating semi-colon within 9 ASCII characters
  2938. int nCodeLen = 0;
  2939. MCD_CHAR cCodeChar = pSource[nChar+1];
  2940. while ( nCodeLen < 9 && ((unsigned int)cCodeChar) < 128 && cCodeChar != ';' )
  2941. {
  2942. if ( cCodeChar >= 'A' && cCodeChar <= 'Z') // upper case?
  2943. cCodeChar += ('a' - 'A'); // make lower case
  2944. szCodeName[nCodeLen] = cCodeChar;
  2945. ++nCodeLen;
  2946. cCodeChar = pSource[nChar+1+nCodeLen];
  2947. }
  2948. if ( cCodeChar == ';' ) // found semi-colon?
  2949. {
  2950. // Decode szCodeName
  2951. szCodeName[nCodeLen] = '\0';
  2952. if ( *szCodeName == '#' ) // numeric character reference?
  2953. {
  2954. // Is it a hex number?
  2955. int nBase = 10; // decimal
  2956. int nNumberOffset = 1; // after #
  2957. if ( szCodeName[1] == 'x' )
  2958. {
  2959. nNumberOffset = 2; // after #x
  2960. nBase = 16; // hex
  2961. }
  2962. nUnicode = MCD_PSZTOL( &szCodeName[nNumberOffset], NULL, nBase );
  2963. }
  2964. else // does not start with #
  2965. {
  2966. // Look for matching code name in PredefEntityTable
  2967. MCD_PCSZ pEntry = PredefEntityTable[x_Hash(szCodeName,sizeof(PredefEntityTable)/sizeof(MCD_PCSZ))];
  2968. while ( *pEntry )
  2969. {
  2970. // e.g. entry: 40039apos means length 4, code point 0039, code name apos
  2971. int nEntryLen = (*pEntry - '0');
  2972. ++pEntry;
  2973. MCD_PCSZ pCodePoint = pEntry;
  2974. pEntry += 4;
  2975. if ( nEntryLen == nCodeLen && x_StrNCmp(szCodeName,pEntry,nEntryLen) == 0 )
  2976. {
  2977. // Convert digits to integer up to code name which always starts with alpha
  2978. nUnicode = MCD_PSZTOL( pCodePoint, NULL, 10 );
  2979. break;
  2980. }
  2981. pEntry += nEntryLen;
  2982. }
  2983. }
  2984. }
  2985. // If a code point found, encode it into text
  2986. if ( nUnicode )
  2987. {
  2988. MCD_CHAR szChar[5];
  2989. nCharLen = 0;
  2990. #if defined(MARKUP_WCHAR) // WCHAR
  2991. #if MARKUP_SIZEOFWCHAR == 4 // sizeof(wchar_t) == 4
  2992. szChar[0] = (MCD_CHAR)nUnicode;
  2993. nCharLen = 1;
  2994. #else // sizeof(wchar_t) == 2
  2995. EncodeCharUTF16( nUnicode, (unsigned short*)szChar, nCharLen );
  2996. #endif
  2997. #elif defined(MARKUP_MBCS) // MBCS/double byte
  2998. #if defined(MARKUP_WINCONV)
  2999. int nUsedDefaultChar = 0;
  3000. wchar_t wszUTF16[2];
  3001. EncodeCharUTF16( nUnicode, (unsigned short*)wszUTF16, nCharLen );
  3002. nCharLen = WideCharToMultiByte( CP_ACP, 0, wszUTF16, nCharLen, szChar, 5, NULL, &nUsedDefaultChar );
  3003. if ( nUsedDefaultChar || nCharLen <= 0 )
  3004. nUnicode = 0;
  3005. #else // not WINCONV
  3006. wchar_t wcUnicode = (wchar_t)nUnicode;
  3007. nCharLen = wctomb( szChar, wcUnicode );
  3008. if ( nCharLen <= 0 )
  3009. nUnicode = 0;
  3010. #endif // not WINCONV
  3011. #else // not WCHAR and not MBCS/double byte
  3012. EncodeCharUTF8( nUnicode, szChar, nCharLen );
  3013. #endif // not WCHAR and not MBCS/double byte
  3014. // Increment index past ampersand semi-colon
  3015. if ( nUnicode ) // must check since MBCS case can clear it
  3016. {
  3017. MCD_BLDAPPENDN(strText,szChar,nCharLen);
  3018. nChar += nCodeLen + 2;
  3019. }
  3020. }
  3021. if ( ! nUnicode )
  3022. {
  3023. // If the code is not converted, leave it as is
  3024. MCD_BLDAPPEND1(strText,'&');
  3025. ++nChar;
  3026. }
  3027. }
  3028. else if ( bAlterWhitespace && x_ISWHITESPACE(pSource[nChar]) )
  3029. {
  3030. if ( nCharWhitespace == 0 && bCollapseWhitespace )
  3031. {
  3032. nCharWhitespace = MCD_BLDLEN(strText);
  3033. MCD_BLDAPPEND1(strText,' ');
  3034. }
  3035. else if ( nCharWhitespace != -1 && ! bCollapseWhitespace )
  3036. {
  3037. if ( nCharWhitespace == 0 )
  3038. nCharWhitespace = MCD_BLDLEN(strText);
  3039. MCD_BLDAPPEND1(strText,pSource[nChar]);
  3040. }
  3041. ++nChar;
  3042. }
  3043. else // not &
  3044. {
  3045. if ( bAlterWhitespace )
  3046. nCharWhitespace = 0;
  3047. nCharLen = MCD_CLEN(&pSource[nChar]);
  3048. MCD_BLDAPPENDN(strText,&pSource[nChar],nCharLen);
  3049. nChar += nCharLen;
  3050. }
  3051. }
  3052. if ( bAlterWhitespace && nCharWhitespace > 0 )
  3053. {
  3054. MCD_BLDTRUNC(strText,nCharWhitespace);
  3055. }
  3056. MCD_BLDRELEASE(strText);
  3057. return strText;
  3058. }
  3059. bool CMarkup::DetectUTF8( const char* pText, int nTextLen, int* pnNonASCII/*=NULL*/, bool* bErrorAtEnd/*=NULL*/ )
  3060. {
  3061. // return true if ASCII or all non-ASCII byte sequences are valid UTF-8 pattern:
  3062. // ASCII 0xxxxxxx
  3063. // 2-byte 110xxxxx 10xxxxxx
  3064. // 3-byte 1110xxxx 10xxxxxx 10xxxxxx
  3065. // 4-byte 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  3066. // *pnNonASCII is set (if pnNonASCII is not NULL) to the number of non-ASCII UTF-8 sequences
  3067. // or if an invalid UTF-8 sequence is found, to 1 + the valid non-ASCII sequences up to the invalid sequence
  3068. // *bErrorAtEnd is set (if bErrorAtEnd is not NULL) to true if the UTF-8 was cut off at the end in mid valid sequence
  3069. int nUChar;
  3070. if ( pnNonASCII )
  3071. *pnNonASCII = 0;
  3072. const char* pTextEnd = pText + nTextLen;
  3073. while ( *pText && pText != pTextEnd )
  3074. {
  3075. if ( (unsigned char)(*pText) & 0x80 )
  3076. {
  3077. if ( pnNonASCII )
  3078. ++(*pnNonASCII);
  3079. nUChar = DecodeCharUTF8( pText, pTextEnd );
  3080. if ( nUChar == -1 )
  3081. {
  3082. if ( bErrorAtEnd )
  3083. *bErrorAtEnd = (pTextEnd == pText)? true:false;
  3084. return false;
  3085. }
  3086. }
  3087. else
  3088. ++pText;
  3089. }
  3090. if ( bErrorAtEnd )
  3091. *bErrorAtEnd = false;
  3092. return true;
  3093. }
  3094. int CMarkup::DecodeCharUTF8( const char*& pszUTF8, const char* pszUTF8End/*=NULL*/ )
  3095. {
  3096. // Return Unicode code point and increment pszUTF8 past 1-4 bytes
  3097. // pszUTF8End can be NULL if pszUTF8 is null terminated
  3098. int nUChar = (unsigned char)*pszUTF8;
  3099. ++pszUTF8;
  3100. if ( nUChar & 0x80 )
  3101. {
  3102. int nExtraChars;
  3103. if ( ! (nUChar & 0x20) )
  3104. {
  3105. nExtraChars = 1;
  3106. nUChar &= 0x1f;
  3107. }
  3108. else if ( ! (nUChar & 0x10) )
  3109. {
  3110. nExtraChars = 2;
  3111. nUChar &= 0x0f;
  3112. }
  3113. else if ( ! (nUChar & 0x08) )
  3114. {
  3115. nExtraChars = 3;
  3116. nUChar &= 0x07;
  3117. }
  3118. else
  3119. return -1;
  3120. while ( nExtraChars-- )
  3121. {
  3122. if ( pszUTF8 == pszUTF8End || ! (*pszUTF8 & 0x80) )
  3123. return -1;
  3124. nUChar = nUChar<<6;
  3125. nUChar |= *pszUTF8 & 0x3f;
  3126. ++pszUTF8;
  3127. }
  3128. }
  3129. return nUChar;
  3130. }
  3131. void CMarkup::EncodeCharUTF16( int nUChar, unsigned short* pwszUTF16, int& nUTF16Len )
  3132. {
  3133. // Write UTF-16 sequence to pwszUTF16 for Unicode code point nUChar and update nUTF16Len
  3134. // Be sure pwszUTF16 has room for up to 2 wide chars
  3135. if ( nUChar & ~0xffff )
  3136. {
  3137. if ( pwszUTF16 )
  3138. {
  3139. // Surrogate pair
  3140. nUChar -= 0x10000;
  3141. pwszUTF16[nUTF16Len++] = (unsigned short)(((nUChar>>10) & 0x3ff) | 0xd800); // W1
  3142. pwszUTF16[nUTF16Len++] = (unsigned short)((nUChar & 0x3ff) | 0xdc00); // W2
  3143. }
  3144. else
  3145. nUTF16Len += 2;
  3146. }
  3147. else
  3148. {
  3149. if ( pwszUTF16 )
  3150. pwszUTF16[nUTF16Len++] = (unsigned short)nUChar;
  3151. else
  3152. ++nUTF16Len;
  3153. }
  3154. }
  3155. int CMarkup::DecodeCharUTF16( const unsigned short*& pwszUTF16, const unsigned short* pszUTF16End/*=NULL*/ )
  3156. {
  3157. // Return Unicode code point and increment pwszUTF16 past 1 or 2 (if surrogrates) UTF-16 code points
  3158. // pszUTF16End can be NULL if pszUTF16 is zero terminated
  3159. int nUChar = *pwszUTF16;
  3160. ++pwszUTF16;
  3161. if ( (nUChar & ~0x000007ff) == 0xd800 ) // W1
  3162. {
  3163. if ( pwszUTF16 == pszUTF16End || ! (*pwszUTF16) ) // W2
  3164. return -1; // incorrect UTF-16
  3165. nUChar = (((nUChar & 0x3ff) << 10) | (*pwszUTF16 & 0x3ff)) + 0x10000;
  3166. ++pwszUTF16;
  3167. }
  3168. return nUChar;
  3169. }
  3170. void CMarkup::EncodeCharUTF8( int nUChar, char* pszUTF8, int& nUTF8Len )
  3171. {
  3172. // Write UTF-8 sequence to pszUTF8 for Unicode code point nUChar and update nUTF8Len
  3173. // Be sure pszUTF8 has room for up to 4 bytes
  3174. if ( ! (nUChar & ~0x0000007f) ) // < 0x80
  3175. {
  3176. if ( pszUTF8 )
  3177. pszUTF8[nUTF8Len++] = (char)nUChar;
  3178. else
  3179. ++nUTF8Len;
  3180. }
  3181. else if ( ! (nUChar & ~0x000007ff) ) // < 0x800
  3182. {
  3183. if ( pszUTF8 )
  3184. {
  3185. pszUTF8[nUTF8Len++] = (char)(((nUChar&0x7c0)>>6)|0xc0);
  3186. pszUTF8[nUTF8Len++] = (char)((nUChar&0x3f)|0x80);
  3187. }
  3188. else
  3189. nUTF8Len += 2;
  3190. }
  3191. else if ( ! (nUChar & ~0x0000ffff) ) // < 0x10000
  3192. {
  3193. if ( pszUTF8 )
  3194. {
  3195. pszUTF8[nUTF8Len++] = (char)(((nUChar&0xf000)>>12)|0xe0);
  3196. pszUTF8[nUTF8Len++] = (char)(((nUChar&0xfc0)>>6)|0x80);
  3197. pszUTF8[nUTF8Len++] = (char)((nUChar&0x3f)|0x80);
  3198. }
  3199. else
  3200. nUTF8Len += 3;
  3201. }
  3202. else // < 0x110000
  3203. {
  3204. if ( pszUTF8 )
  3205. {
  3206. pszUTF8[nUTF8Len++] = (char)(((nUChar&0x1c0000)>>18)|0xf0);
  3207. pszUTF8[nUTF8Len++] = (char)(((nUChar&0x3f000)>>12)|0x80);
  3208. pszUTF8[nUTF8Len++] = (char)(((nUChar&0xfc0)>>6)|0x80);
  3209. pszUTF8[nUTF8Len++] = (char)((nUChar&0x3f)|0x80);
  3210. }
  3211. else
  3212. nUTF8Len += 4;
  3213. }
  3214. }
  3215. int CMarkup::UTF16To8( char* pszUTF8, const unsigned short* pwszUTF16, int nUTF8Count )
  3216. {
  3217. // Supports the same arguments as wcstombs
  3218. // the pwszUTF16 source must be a NULL-terminated UTF-16 string
  3219. // if pszUTF8 is NULL, the number of bytes required is returned and nUTF8Count is ignored
  3220. // otherwise pszUTF8 is filled with the result string and NULL-terminated if nUTF8Count allows
  3221. // nUTF8Count is the byte size of pszUTF8 and must be large enough for the NULL if NULL desired
  3222. // and the number of bytes (excluding NULL) is returned
  3223. //
  3224. int nUChar, nUTF8Len = 0;
  3225. while ( *pwszUTF16 )
  3226. {
  3227. // Decode UTF-16
  3228. nUChar = DecodeCharUTF16( pwszUTF16, NULL );
  3229. if ( nUChar == -1 )
  3230. nUChar = '?';
  3231. // Encode UTF-8
  3232. if ( pszUTF8 && nUTF8Len + 4 > nUTF8Count )
  3233. {
  3234. int nUTF8LenSoFar = nUTF8Len;
  3235. EncodeCharUTF8( nUChar, NULL, nUTF8Len );
  3236. if ( nUTF8Len > nUTF8Count )
  3237. return nUTF8LenSoFar;
  3238. nUTF8Len = nUTF8LenSoFar;
  3239. }
  3240. EncodeCharUTF8( nUChar, pszUTF8, nUTF8Len );
  3241. }
  3242. if ( pszUTF8 && nUTF8Len < nUTF8Count )
  3243. pszUTF8[nUTF8Len] = 0;
  3244. return nUTF8Len;
  3245. }
  3246. int CMarkup::UTF8To16( unsigned short* pwszUTF16, const char* pszUTF8, int nUTF8Count )
  3247. {
  3248. // Supports the same arguments as mbstowcs
  3249. // the pszUTF8 source must be a UTF-8 string which will be processed up to NULL-terminator or nUTF8Count
  3250. // if pwszUTF16 is NULL, the number of UTF-16 chars required is returned
  3251. // nUTF8Count is maximum UTF-8 bytes to convert and should include NULL if NULL desired in result
  3252. // if pwszUTF16 is not NULL it is filled with the result string and it must be large enough
  3253. // result will be NULL-terminated if NULL encountered in pszUTF8 before nUTF8Count
  3254. // and the number of UTF-8 bytes converted is returned
  3255. //
  3256. const char* pszPosUTF8 = pszUTF8;
  3257. const char* pszUTF8End = pszUTF8 + nUTF8Count;
  3258. int nUChar, nUTF8Len = 0, nUTF16Len = 0;
  3259. while ( pszPosUTF8 != pszUTF8End )
  3260. {
  3261. nUChar = DecodeCharUTF8( pszPosUTF8, pszUTF8End );
  3262. if ( ! nUChar )
  3263. {
  3264. if ( pwszUTF16 )
  3265. pwszUTF16[nUTF16Len] = 0;
  3266. break;
  3267. }
  3268. else if ( nUChar == -1 )
  3269. nUChar = '?';
  3270. // Encode UTF-16
  3271. EncodeCharUTF16( nUChar, pwszUTF16, nUTF16Len );
  3272. }
  3273. nUTF8Len = (int)(pszPosUTF8 - pszUTF8);
  3274. if ( ! pwszUTF16 )
  3275. return nUTF16Len;
  3276. return nUTF8Len;
  3277. }
  3278. #if ! defined(MARKUP_WCHAR) // not WCHAR
  3279. MCD_STR CMarkup::UTF8ToA( MCD_CSTR pszUTF8, int* pnFailed/*=NULL*/ )
  3280. {
  3281. // Converts from UTF-8 to locale ANSI charset
  3282. MCD_STR strANSI;
  3283. int nMBLen = (int)MCD_PSZLEN( pszUTF8 );
  3284. if ( pnFailed )
  3285. *pnFailed = 0;
  3286. if ( nMBLen )
  3287. {
  3288. TextEncoding textencoding( MCD_T("UTF-8"), (const void*)pszUTF8, nMBLen );
  3289. textencoding.m_nToCount = nMBLen;
  3290. MCD_CHAR* pANSIBuffer = MCD_GETBUFFER(strANSI,textencoding.m_nToCount);
  3291. nMBLen = textencoding.PerformConversion( (void*)pANSIBuffer );
  3292. MCD_RELEASEBUFFER(strANSI,pANSIBuffer,nMBLen);
  3293. if ( pnFailed )
  3294. *pnFailed = textencoding.m_nFailedChars;
  3295. }
  3296. return strANSI;
  3297. }
  3298. MCD_STR CMarkup::AToUTF8( MCD_CSTR pszANSI )
  3299. {
  3300. // Converts locale ANSI charset to UTF-8
  3301. MCD_STR strUTF8;
  3302. int nMBLen = (int)MCD_PSZLEN( pszANSI );
  3303. if ( nMBLen )
  3304. {
  3305. TextEncoding textencoding( MCD_T(""), (const void*)pszANSI, nMBLen );
  3306. textencoding.m_nToCount = nMBLen * 4;
  3307. MCD_CHAR* pUTF8Buffer = MCD_GETBUFFER(strUTF8,textencoding.m_nToCount);
  3308. nMBLen = textencoding.PerformConversion( (void*)pUTF8Buffer, MCD_T("UTF-8") );
  3309. MCD_RELEASEBUFFER(strUTF8,pUTF8Buffer,nMBLen);
  3310. }
  3311. return strUTF8;
  3312. }
  3313. #endif // not WCHAR
  3314. MCD_STR CMarkup::GetDeclaredEncoding( MCD_CSTR szDoc )
  3315. {
  3316. // Extract encoding attribute from XML Declaration, or HTML meta charset
  3317. MCD_STR strEncoding;
  3318. TokenPos token( szDoc, MDF_IGNORECASE );
  3319. NodePos node;
  3320. bool bHtml = false;
  3321. int nTypeFound = 0;
  3322. while ( nTypeFound >= 0 )
  3323. {
  3324. nTypeFound = token.ParseNode( node );
  3325. int nNext = token.m_nNext;
  3326. if ( nTypeFound == MNT_PROCESSING_INSTRUCTION && node.nStart == 0 )
  3327. {
  3328. token.m_nNext = node.nStart + 2; // after <?
  3329. if ( token.FindName() && token.Match(MCD_T("xml")) )
  3330. {
  3331. // e.g. <?xml version="1.0" encoding="UTF-8"?>
  3332. if ( token.FindAttrib(MCD_T("encoding")) )
  3333. strEncoding = token.GetTokenText();
  3334. break;
  3335. }
  3336. }
  3337. else if ( nTypeFound == 0 ) // end tag
  3338. {
  3339. // Check for end of HTML head
  3340. token.m_nNext = node.nStart + 2; // after </
  3341. if ( token.FindName() && token.Match(MCD_T("head")) )
  3342. break;
  3343. }
  3344. else if ( nTypeFound == MNT_ELEMENT )
  3345. {
  3346. token.m_nNext = node.nStart + 1; // after <
  3347. token.FindName();
  3348. if ( ! bHtml )
  3349. {
  3350. if ( ! token.Match(MCD_T("html")) )
  3351. break;
  3352. bHtml = true;
  3353. }
  3354. else if ( token.Match(MCD_T("meta")) )
  3355. {
  3356. // e.g. <META http-equiv=Content-Type content="text/html; charset=UTF-8">
  3357. int nAttribOffset = node.nStart + 1;
  3358. token.m_nNext = nAttribOffset;
  3359. if ( token.FindAttrib(MCD_T("http-equiv")) && token.Match(MCD_T("Content-Type")) )
  3360. {
  3361. token.m_nNext = nAttribOffset;
  3362. if ( token.FindAttrib(MCD_T("content")) )
  3363. {
  3364. int nContentEndOffset = token.m_nNext;
  3365. token.m_nNext = token.m_nL;
  3366. while ( token.m_nNext < nContentEndOffset && token.FindName() )
  3367. {
  3368. if ( token.Match(MCD_T("charset")) && token.FindName() && token.Match(MCD_T("=")) )
  3369. {
  3370. token.FindName();
  3371. strEncoding = token.GetTokenText();
  3372. break;
  3373. }
  3374. }
  3375. }
  3376. break;
  3377. }
  3378. }
  3379. }
  3380. token.m_nNext = nNext;
  3381. }
  3382. return strEncoding;
  3383. }
  3384. int CMarkup::GetEncodingCodePage( MCD_CSTR pszEncoding )
  3385. {
  3386. return x_GetEncodingCodePage( pszEncoding );
  3387. }
  3388. int CMarkup::FindNode( int nType )
  3389. {
  3390. // Change current node position only if a node is found
  3391. // If nType is 0 find any node, otherwise find node of type nType
  3392. // Return type of node or 0 if not found
  3393. // Determine where in document to start scanning for node
  3394. int nNodeOffset = m_nNodeOffset;
  3395. if ( m_nNodeType > MNT_ELEMENT )
  3396. {
  3397. // By-pass current node
  3398. nNodeOffset += m_nNodeLength;
  3399. }
  3400. else // element or no current main position
  3401. {
  3402. // Set position to begin looking for node
  3403. if ( m_iPos )
  3404. {
  3405. // After element
  3406. nNodeOffset = ELEM(m_iPos).StartAfter();
  3407. }
  3408. else if ( m_iPosParent )
  3409. {
  3410. // Immediately after start tag of parent
  3411. if ( ELEM(m_iPosParent).IsEmptyElement() )
  3412. return 0;
  3413. else
  3414. nNodeOffset = ELEM(m_iPosParent).StartContent();
  3415. }
  3416. }
  3417. // Get nodes until we find what we're looking for
  3418. int nTypeFound = 0;
  3419. int iPosNew = m_iPos;
  3420. TokenPos token( m_strDoc, m_nDocFlags );
  3421. NodePos node;
  3422. token.m_nNext = nNodeOffset;
  3423. do
  3424. {
  3425. nNodeOffset = token.m_nNext;
  3426. nTypeFound = token.ParseNode( node );
  3427. if ( nTypeFound == 0 )
  3428. {
  3429. // Check if we have reached the end of the parent element
  3430. if ( m_iPosParent && nNodeOffset == ELEM(m_iPosParent).StartContent()
  3431. + ELEM(m_iPosParent).ContentLen() )
  3432. return 0;
  3433. nTypeFound = MNT_LONE_END_TAG; // otherwise it is a lone end tag
  3434. }
  3435. else if ( nTypeFound < 0 )
  3436. {
  3437. if ( nTypeFound == -2 ) // end of document
  3438. return 0;
  3439. // -1 is node error
  3440. nTypeFound = MNT_NODE_ERROR;
  3441. }
  3442. else if ( nTypeFound == MNT_ELEMENT )
  3443. {
  3444. if ( iPosNew )
  3445. iPosNew = ELEM(iPosNew).iElemNext;
  3446. else
  3447. iPosNew = ELEM(m_iPosParent).iElemChild;
  3448. if ( ! iPosNew )
  3449. return 0;
  3450. if ( ! nType || (nType & nTypeFound) )
  3451. {
  3452. // Found element node, move position to this element
  3453. x_SetPos( m_iPosParent, iPosNew, 0 );
  3454. return m_nNodeType;
  3455. }
  3456. token.m_nNext = ELEM(iPosNew).StartAfter();
  3457. }
  3458. }
  3459. while ( nType && ! (nType & nTypeFound) );
  3460. m_iPos = iPosNew;
  3461. m_iPosChild = 0;
  3462. m_nNodeOffset = node.nStart;
  3463. m_nNodeLength = node.nLength;
  3464. m_nNodeType = nTypeFound;
  3465. MARKUP_SETDEBUGSTATE;
  3466. return m_nNodeType;
  3467. }
  3468. bool CMarkup::RemoveNode()
  3469. {
  3470. if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
  3471. return false;
  3472. if ( m_iPos || m_nNodeLength )
  3473. {
  3474. x_RemoveNode( m_iPosParent, m_iPos, m_nNodeType, m_nNodeOffset, m_nNodeLength );
  3475. m_iPosChild = 0;
  3476. MARKUP_SETDEBUGSTATE;
  3477. return true;
  3478. }
  3479. return false;
  3480. }
  3481. MCD_STR CMarkup::GetTagName() const
  3482. {
  3483. // Return the tag name at the current main position
  3484. MCD_STR strTagName;
  3485. // This method is primarily for elements, however
  3486. // it does return something for certain other nodes
  3487. if ( m_nNodeLength )
  3488. {
  3489. switch ( m_nNodeType )
  3490. {
  3491. case MNT_PROCESSING_INSTRUCTION:
  3492. case MNT_LONE_END_TAG:
  3493. {
  3494. // <?target or </tagname
  3495. TokenPos token( m_strDoc, m_nDocFlags );
  3496. token.m_nNext = m_nNodeOffset + 2;
  3497. if ( token.FindName() )
  3498. strTagName = token.GetTokenText();
  3499. }
  3500. break;
  3501. case MNT_COMMENT:
  3502. strTagName = MCD_T("#comment");
  3503. break;
  3504. case MNT_CDATA_SECTION:
  3505. strTagName = MCD_T("#cdata-section");
  3506. break;
  3507. case MNT_DOCUMENT_TYPE:
  3508. {
  3509. // <!DOCTYPE name
  3510. TokenPos token( m_strDoc, m_nDocFlags );
  3511. token.m_nNext = m_nNodeOffset + 2;
  3512. if ( token.FindName() && token.FindName() )
  3513. strTagName = token.GetTokenText();
  3514. }
  3515. break;
  3516. case MNT_TEXT:
  3517. case MNT_WHITESPACE:
  3518. strTagName = MCD_T("#text");
  3519. break;
  3520. }
  3521. return strTagName;
  3522. }
  3523. if ( m_iPos )
  3524. strTagName = x_GetTagName( m_iPos );
  3525. return strTagName;
  3526. }
  3527. bool CMarkup::IntoElem()
  3528. {
  3529. // Make current element the parent
  3530. if ( m_iPos && m_nNodeType == MNT_ELEMENT )
  3531. {
  3532. x_SetPos( m_iPos, m_iPosChild, 0 );
  3533. return true;
  3534. }
  3535. return false;
  3536. }
  3537. bool CMarkup::OutOfElem()
  3538. {
  3539. // Go to parent element
  3540. if ( m_iPosParent )
  3541. {
  3542. x_SetPos( ELEM(m_iPosParent).iElemParent, m_iPosParent, m_iPos );
  3543. return true;
  3544. }
  3545. return false;
  3546. }
  3547. bool CMarkup::GetNthAttrib( int n, MCD_STR& strAttrib, MCD_STR& strValue ) const
  3548. {
  3549. // Return nth attribute name and value from main position
  3550. TokenPos token( m_strDoc, m_nDocFlags );
  3551. if ( m_iPos && m_nNodeType == MNT_ELEMENT )
  3552. token.m_nNext = ELEM(m_iPos).nStart + 1;
  3553. else if ( m_nNodeLength && m_nNodeType == MNT_PROCESSING_INSTRUCTION )
  3554. token.m_nNext = m_nNodeOffset + 2;
  3555. else
  3556. return false;
  3557. if ( token.FindAttrib(NULL,n,&strAttrib) )
  3558. {
  3559. strValue = UnescapeText( token.GetTokenPtr(), token.Length(), m_nDocFlags );
  3560. return true;
  3561. }
  3562. return false;
  3563. }
  3564. MCD_STR CMarkup::GetAttribName( int n ) const
  3565. {
  3566. // Return nth attribute name of main position
  3567. TokenPos token( m_strDoc, m_nDocFlags );
  3568. if ( m_iPos && m_nNodeType == MNT_ELEMENT )
  3569. token.m_nNext = ELEM(m_iPos).nStart + 1;
  3570. else if ( m_nNodeLength && m_nNodeType == MNT_PROCESSING_INSTRUCTION )
  3571. token.m_nNext = m_nNodeOffset + 2;
  3572. else
  3573. return MCD_T("");
  3574. if ( token.FindAttrib(NULL,n) )
  3575. return token.GetTokenText();
  3576. return MCD_T("");
  3577. }
  3578. bool CMarkup::SavePos( MCD_CSTR szPosName /*=""*/, int nMap /*=0*/ )
  3579. {
  3580. if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
  3581. return false;
  3582. // Save current element position in saved position map
  3583. if ( szPosName )
  3584. {
  3585. SavedPosMap* pMap;
  3586. m_pSavedPosMaps->GetMap( pMap, nMap );
  3587. SavedPos savedpos;
  3588. if ( szPosName )
  3589. savedpos.strName = szPosName;
  3590. if ( m_iPosChild )
  3591. {
  3592. savedpos.iPos = m_iPosChild;
  3593. savedpos.nSavedPosFlags |= SavedPos::SPM_CHILD;
  3594. }
  3595. else if ( m_iPos )
  3596. {
  3597. savedpos.iPos = m_iPos;
  3598. savedpos.nSavedPosFlags |= SavedPos::SPM_MAIN;
  3599. }
  3600. else
  3601. {
  3602. savedpos.iPos = m_iPosParent;
  3603. }
  3604. savedpos.nSavedPosFlags |= SavedPos::SPM_USED;
  3605. int nSlot = x_Hash( szPosName, pMap->nMapSize);
  3606. SavedPos* pSavedPos = pMap->pTable[nSlot];
  3607. int nOffset = 0;
  3608. if ( ! pSavedPos )
  3609. {
  3610. pSavedPos = new SavedPos[2];
  3611. pSavedPos[1].nSavedPosFlags = SavedPos::SPM_LAST;
  3612. pMap->pTable[nSlot] = pSavedPos;
  3613. }
  3614. else
  3615. {
  3616. while ( pSavedPos[nOffset].nSavedPosFlags & SavedPos::SPM_USED )
  3617. {
  3618. if ( pSavedPos[nOffset].strName == (MCD_PCSZ)szPosName )
  3619. break;
  3620. if ( pSavedPos[nOffset].nSavedPosFlags & SavedPos::SPM_LAST )
  3621. {
  3622. int nNewSize = (nOffset + 6) * 2;
  3623. SavedPos* pNewSavedPos = new SavedPos[nNewSize];
  3624. for ( int nCopy=0; nCopy<=nOffset; ++nCopy )
  3625. pNewSavedPos[nCopy] = pSavedPos[nCopy];
  3626. pNewSavedPos[nOffset].nSavedPosFlags ^= SavedPos::SPM_LAST;
  3627. pNewSavedPos[nNewSize-1].nSavedPosFlags = SavedPos::SPM_LAST;
  3628. delete [] pSavedPos;
  3629. pSavedPos = pNewSavedPos;
  3630. pMap->pTable[nSlot] = pSavedPos;
  3631. ++nOffset;
  3632. break;
  3633. }
  3634. ++nOffset;
  3635. }
  3636. }
  3637. if ( pSavedPos[nOffset].nSavedPosFlags & SavedPos::SPM_LAST )
  3638. savedpos.nSavedPosFlags |= SavedPos::SPM_LAST;
  3639. pSavedPos[nOffset] = savedpos;
  3640. /*
  3641. // To review hash table balance, uncomment and watch strBalance
  3642. MCD_STR strBalance, strSlot;
  3643. for ( nSlot=0; nSlot < pMap->nMapSize; ++nSlot )
  3644. {
  3645. pSavedPos = pMap->pTable[nSlot];
  3646. int nCount = 0;
  3647. while ( pSavedPos && pSavedPos->nSavedPosFlags & SavedPos::SPM_USED )
  3648. {
  3649. ++nCount;
  3650. if ( pSavedPos->nSavedPosFlags & SavedPos::SPM_LAST )
  3651. break;
  3652. ++pSavedPos;
  3653. }
  3654. strSlot.Format( MCD_T("%d "), nCount );
  3655. strBalance += strSlot;
  3656. }
  3657. */
  3658. return true;
  3659. }
  3660. return false;
  3661. }
  3662. bool CMarkup::RestorePos( MCD_CSTR szPosName /*=""*/, int nMap /*=0*/ )
  3663. {
  3664. if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
  3665. return false;
  3666. // Restore element position if found in saved position map
  3667. if ( szPosName )
  3668. {
  3669. SavedPosMap* pMap;
  3670. m_pSavedPosMaps->GetMap( pMap, nMap );
  3671. int nSlot = x_Hash( szPosName, pMap->nMapSize );
  3672. SavedPos* pSavedPos = pMap->pTable[nSlot];
  3673. if ( pSavedPos )
  3674. {
  3675. int nOffset = 0;
  3676. while ( pSavedPos[nOffset].nSavedPosFlags & SavedPos::SPM_USED )
  3677. {
  3678. if ( pSavedPos[nOffset].strName == (MCD_PCSZ)szPosName )
  3679. {
  3680. int i = pSavedPos[nOffset].iPos;
  3681. if ( pSavedPos[nOffset].nSavedPosFlags & SavedPos::SPM_CHILD )
  3682. x_SetPos( ELEM(ELEM(i).iElemParent).iElemParent, ELEM(i).iElemParent, i );
  3683. else if ( pSavedPos[nOffset].nSavedPosFlags & SavedPos::SPM_MAIN )
  3684. x_SetPos( ELEM(i).iElemParent, i, 0 );
  3685. else
  3686. x_SetPos( i, 0, 0 );
  3687. return true;
  3688. }
  3689. if ( pSavedPos[nOffset].nSavedPosFlags & SavedPos::SPM_LAST )
  3690. break;
  3691. ++nOffset;
  3692. }
  3693. }
  3694. }
  3695. return false;
  3696. }
  3697. bool CMarkup::SetMapSize( int nSize, int nMap /*=0*/ )
  3698. {
  3699. if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
  3700. return false;
  3701. // Set saved position map hash table size before using it
  3702. // Returns false if map already exists
  3703. // Some prime numbers: 53, 101, 211, 503, 1009, 2003, 10007, 20011, 50021, 100003, 200003, 500009
  3704. SavedPosMap* pNewMap;
  3705. return m_pSavedPosMaps->GetMap( pNewMap, nMap, nSize );
  3706. }
  3707. bool CMarkup::RemoveElem()
  3708. {
  3709. if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
  3710. return false;
  3711. // Remove current main position element
  3712. if ( m_iPos && m_nNodeType == MNT_ELEMENT )
  3713. {
  3714. int iPos = x_RemoveElem( m_iPos );
  3715. x_SetPos( m_iPosParent, iPos, 0 );
  3716. return true;
  3717. }
  3718. return false;
  3719. }
  3720. bool CMarkup::RemoveChildElem()
  3721. {
  3722. if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
  3723. return false;
  3724. // Remove current child position element
  3725. if ( m_iPosChild )
  3726. {
  3727. int iPosChild = x_RemoveElem( m_iPosChild );
  3728. x_SetPos( m_iPosParent, m_iPos, iPosChild );
  3729. return true;
  3730. }
  3731. return false;
  3732. }
  3733. //////////////////////////////////////////////////////////////////////
  3734. // CMarkup private methods
  3735. //
  3736. void CMarkup::x_InitMarkup()
  3737. {
  3738. // Only called from CMarkup constructors
  3739. m_pFilePos = NULL;
  3740. m_pSavedPosMaps = new SavedPosMapArray;
  3741. m_pElemPosTree = new ElemPosTree;
  3742. // To always ignore case, define MARKUP_IGNORECASE
  3743. #if defined(MARKUP_IGNORECASE) // ignore case
  3744. m_nDocFlags = MDF_IGNORECASE;
  3745. #else // not ignore case
  3746. m_nDocFlags = 0;
  3747. #endif // not ignore case
  3748. }
  3749. int CMarkup::x_GetParent( int i )
  3750. {
  3751. return ELEM(i).iElemParent;
  3752. }
  3753. void CMarkup::x_SetPos( int iPosParent, int iPos, int iPosChild )
  3754. {
  3755. m_iPosParent = iPosParent;
  3756. m_iPos = iPos;
  3757. m_iPosChild = iPosChild;
  3758. m_nNodeOffset = 0;
  3759. m_nNodeLength = 0;
  3760. m_nNodeType = iPos?MNT_ELEMENT:0;
  3761. MARKUP_SETDEBUGSTATE;
  3762. }
  3763. #if defined(_DEBUG) // DEBUG
  3764. void CMarkup::x_SetDebugState()
  3765. {
  3766. // Set m_pDebugCur and m_pDebugPos to point into document
  3767. MCD_PCSZ pD = MCD_2PCSZ(m_strDoc);
  3768. // Node (non-element) position is determined differently in file mode
  3769. if ( m_nNodeLength || (m_nNodeOffset && !m_pFilePos)
  3770. || (m_pFilePos && (!m_iPos) && (!m_iPosParent) && ! m_pFilePos->FileAtTop()) )
  3771. {
  3772. if ( ! m_nNodeLength )
  3773. m_pDebugCur = MCD_T("main position offset"); // file mode only
  3774. else
  3775. m_pDebugCur = MCD_T("main position node");
  3776. m_pDebugPos = &pD[m_nNodeOffset];
  3777. }
  3778. else
  3779. {
  3780. if ( m_iPosChild )
  3781. {
  3782. m_pDebugCur = MCD_T("child position element");
  3783. m_pDebugPos = &pD[ELEM(m_iPosChild).nStart];
  3784. }
  3785. else if ( m_iPos )
  3786. {
  3787. m_pDebugCur = MCD_T("main position element");
  3788. m_pDebugPos = &pD[ELEM(m_iPos).nStart];
  3789. }
  3790. else if ( m_iPosParent )
  3791. {
  3792. m_pDebugCur = MCD_T("parent position element");
  3793. m_pDebugPos = &pD[ELEM(m_iPosParent).nStart];
  3794. }
  3795. else
  3796. {
  3797. m_pDebugCur = MCD_T("top of document");
  3798. m_pDebugPos = pD;
  3799. }
  3800. }
  3801. }
  3802. #endif // DEBUG
  3803. int CMarkup::x_GetFreePos()
  3804. {
  3805. if ( m_iPosFree == m_pElemPosTree->GetSize() )
  3806. x_AllocElemPos();
  3807. return m_iPosFree++;
  3808. }
  3809. bool CMarkup::x_AllocElemPos( int nNewSize /*=0*/ )
  3810. {
  3811. // Resize m_aPos when the document is created or the array is filled
  3812. if ( ! nNewSize )
  3813. nNewSize = m_iPosFree + (m_iPosFree>>1); // Grow By: multiply size by 1.5
  3814. if ( m_pElemPosTree->GetSize() < nNewSize )
  3815. m_pElemPosTree->GrowElemPosTree( nNewSize );
  3816. return true;
  3817. }
  3818. bool CMarkup::x_ParseDoc()
  3819. {
  3820. // Reset indexes
  3821. ResetPos();
  3822. m_pSavedPosMaps->ReleaseMaps();
  3823. // Starting size of position array: 1 element per 64 bytes of document
  3824. // Tight fit when parsing small doc, only 0 to 2 reallocs when parsing large doc
  3825. // Start at 8 when creating new document
  3826. int nDocLen = MCD_STRLENGTH(m_strDoc);
  3827. m_iPosFree = 1;
  3828. x_AllocElemPos( nDocLen / 64 + 8 );
  3829. m_iPosDeleted = 0;
  3830. // Parse document
  3831. ELEM(0).ClearVirtualParent();
  3832. if ( nDocLen )
  3833. {
  3834. TokenPos token( m_strDoc, m_nDocFlags );
  3835. int iPos = x_ParseElem( 0, token );
  3836. ELEM(0).nLength = nDocLen;
  3837. if ( iPos > 0 )
  3838. {
  3839. ELEM(0).iElemChild = iPos;
  3840. if ( ELEM(iPos).iElemNext )
  3841. x_AddResult( m_strResult, MCD_T("root_has_sibling") );
  3842. }
  3843. else
  3844. x_AddResult( m_strResult, MCD_T("no_root_element") );
  3845. }
  3846. ResetPos();
  3847. return IsWellFormed();
  3848. }
  3849. int CMarkup::x_ParseElem( int iPosParent, TokenPos& token )
  3850. {
  3851. // This is either called by x_ParseDoc or x_AddSubDoc or x_SetElemContent
  3852. // Returns index of the first element encountered or zero if no elements
  3853. //
  3854. int iPosRoot = 0;
  3855. int iPos = iPosParent;
  3856. int iVirtualParent = iPosParent;
  3857. int nRootDepth = ELEM(iPos).Level();
  3858. int nMatchLevel;
  3859. int iPosMatch;
  3860. int iTag;
  3861. int nTypeFound;
  3862. int iPosFirst;
  3863. int iPosLast;
  3864. ElemPos* pElem;
  3865. ElemPos* pElemParent;
  3866. ElemPos* pElemChild;
  3867. // Loop through the nodes of the document
  3868. ElemStack elemstack;
  3869. NodePos node;
  3870. token.m_nNext = 0;
  3871. while ( 1 )
  3872. {
  3873. nTypeFound = token.ParseNode( node );
  3874. nMatchLevel = 0;
  3875. if ( nTypeFound == MNT_ELEMENT ) // start tag
  3876. {
  3877. iPos = x_GetFreePos();
  3878. if ( ! iPosRoot )
  3879. iPosRoot = iPos;
  3880. pElem = &ELEM(iPos);
  3881. pElem->iElemParent = iPosParent;
  3882. pElem->iElemNext = 0;
  3883. pElemParent = &ELEM(iPosParent);
  3884. if ( pElemParent->iElemChild )
  3885. {
  3886. iPosFirst = pElemParent->iElemChild;
  3887. pElemChild = &ELEM(iPosFirst);
  3888. iPosLast = pElemChild->iElemPrev;
  3889. ELEM(iPosLast).iElemNext = iPos;
  3890. pElem->iElemPrev = iPosLast;
  3891. pElemChild->iElemPrev = iPos;
  3892. pElem->nFlags = 0;
  3893. }
  3894. else
  3895. {
  3896. pElemParent->iElemChild = iPos;
  3897. pElem->iElemPrev = iPos;
  3898. pElem->nFlags = MNF_FIRST;
  3899. }
  3900. pElem->SetLevel( nRootDepth + elemstack.iTop );
  3901. pElem->iElemChild = 0;
  3902. pElem->nStart = node.nStart;
  3903. pElem->SetStartTagLen( node.nLength );
  3904. if ( node.nNodeFlags & MNF_EMPTY )
  3905. {
  3906. iPos = iPosParent;
  3907. pElem->SetEndTagLen( 0 );
  3908. pElem->nLength = node.nLength;
  3909. }
  3910. else
  3911. {
  3912. iPosParent = iPos;
  3913. elemstack.PushIntoLevel( token.GetTokenPtr(), token.Length() );
  3914. }
  3915. }
  3916. else if ( nTypeFound == 0 ) // end tag
  3917. {
  3918. iPosMatch = iPos;
  3919. iTag = elemstack.iTop;
  3920. nMatchLevel = iTag;
  3921. while ( nMatchLevel && ! token.Match(elemstack.GetRefTagPosAt(iTag--).strTagName) )
  3922. {
  3923. --nMatchLevel;
  3924. iPosMatch = ELEM(iPosMatch).iElemParent;
  3925. }
  3926. if ( nMatchLevel == 0 )
  3927. {
  3928. // Not matched at all, it is a lone end tag, a non-element node
  3929. ELEM(iVirtualParent).nFlags |= MNF_ILLFORMED;
  3930. ELEM(iPos).nFlags |= MNF_ILLDATA;
  3931. x_AddResult( m_strResult, MCD_T("lone_end_tag"), token.GetTokenText(), 0, node.nStart );
  3932. }
  3933. else
  3934. {
  3935. pElem = &ELEM(iPosMatch);
  3936. pElem->nLength = node.nStart - pElem->nStart + node.nLength;
  3937. pElem->SetEndTagLen( node.nLength );
  3938. }
  3939. }
  3940. else if ( nTypeFound == -1 )
  3941. {
  3942. ELEM(iVirtualParent).nFlags |= MNF_ILLFORMED;
  3943. ELEM(iPos).nFlags |= MNF_ILLDATA;
  3944. m_strResult += node.strMeta;
  3945. }
  3946. // Matched end tag, or end of document
  3947. if ( nMatchLevel || nTypeFound == -2 )
  3948. {
  3949. if ( elemstack.iTop > nMatchLevel )
  3950. ELEM(iVirtualParent).nFlags |= MNF_ILLFORMED;
  3951. // Process any non-ended elements
  3952. while ( elemstack.iTop > nMatchLevel )
  3953. {
  3954. // Element with no end tag
  3955. pElem = &ELEM(iPos);
  3956. int iPosChild = pElem->iElemChild;
  3957. iPosParent = pElem->iElemParent;
  3958. pElem->SetEndTagLen( 0 );
  3959. pElem->nFlags |= MNF_NONENDED;
  3960. pElem->iElemChild = 0;
  3961. pElem->nLength = pElem->StartTagLen();
  3962. if ( pElem->nFlags & MNF_ILLDATA )
  3963. {
  3964. pElem->nFlags ^= MNF_ILLDATA;
  3965. ELEM(iPosParent).nFlags |= MNF_ILLDATA;
  3966. }
  3967. while ( iPosChild )
  3968. {
  3969. ELEM(iPosChild).iElemParent = iPosParent;
  3970. ELEM(iPosChild).iElemPrev = iPos;
  3971. ELEM(iPos).iElemNext = iPosChild;
  3972. iPos = iPosChild;
  3973. iPosChild = ELEM(iPosChild).iElemNext;
  3974. }
  3975. // If end tag did not match, top node is end tag that did not match pElem
  3976. // if end of document, any nodes below top have no end tag
  3977. // second offset represents location where end tag was expected but end of document or other end tag was found
  3978. // end tag that was found is token.GetTokenText() but not reported in error
  3979. int nOffset2 = (nTypeFound==0)? token.m_nL-1: MCD_STRLENGTH(m_strDoc);
  3980. x_AddResult( m_strResult, MCD_T("unended_start_tag"), elemstack.Current().strTagName, 0, pElem->nStart, nOffset2 );
  3981. iPos = iPosParent;
  3982. elemstack.PopOutOfLevel();
  3983. }
  3984. if ( nTypeFound == -2 )
  3985. break;
  3986. iPosParent = ELEM(iPos).iElemParent;
  3987. iPos = iPosParent;
  3988. elemstack.PopOutOfLevel();
  3989. }
  3990. }
  3991. return iPosRoot;
  3992. }
  3993. int CMarkup::x_FindElem( int iPosParent, int iPos, PathPos& path ) const
  3994. {
  3995. // If pPath is NULL or empty, go to next sibling element
  3996. // Otherwise go to next sibling element with matching path
  3997. //
  3998. if ( ! path.ValidPath() )
  3999. return 0;
  4000. // Paths other than simple tag name are only supported in the developer version
  4001. if ( path.IsAnywherePath() || path.IsAbsolutePath() )
  4002. return 0;
  4003. if ( iPos )
  4004. iPos = ELEM(iPos).iElemNext;
  4005. else
  4006. iPos = ELEM(iPosParent).iElemChild;
  4007. // Finished here if pPath not specified
  4008. if ( ! path.IsPath() )
  4009. return iPos;
  4010. // Search
  4011. TokenPos token( m_strDoc, m_nDocFlags );
  4012. while ( iPos )
  4013. {
  4014. // Compare tag name
  4015. token.m_nNext = ELEM(iPos).nStart + 1;
  4016. token.FindName(); // Locate tag name
  4017. if ( token.Match(path.GetPtr()) )
  4018. return iPos;
  4019. iPos = ELEM(iPos).iElemNext;
  4020. }
  4021. return 0;
  4022. }
  4023. MCD_STR CMarkup::x_GetPath( int iPos ) const
  4024. {
  4025. // In file mode, iPos is an index into m_pFilePos->m_elemstack or zero
  4026. MCD_STR strPath;
  4027. while ( iPos )
  4028. {
  4029. MCD_STR strTagName;
  4030. int iPosParent;
  4031. int nCount = 0;
  4032. if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
  4033. {
  4034. TagPos& tag = m_pFilePos->m_elemstack.GetRefTagPosAt(iPos);
  4035. strTagName = tag.strTagName;
  4036. nCount = tag.nCount;
  4037. iPosParent = tag.iParent;
  4038. }
  4039. else
  4040. {
  4041. strTagName = x_GetTagName( iPos );
  4042. PathPos path( MCD_2PCSZ(strTagName), false );
  4043. iPosParent = ELEM(iPos).iElemParent;
  4044. int iPosSib = 0;
  4045. while ( iPosSib != iPos )
  4046. {
  4047. path.RevertOffset();
  4048. iPosSib = x_FindElem( iPosParent, iPosSib, path );
  4049. ++nCount;
  4050. }
  4051. }
  4052. if ( nCount == 1 )
  4053. strPath = MCD_T("/") + strTagName + strPath;
  4054. else
  4055. {
  4056. MCD_CHAR szPred[25];
  4057. MCD_SPRINTF( MCD_SSZ(szPred), MCD_T("[%d]"), nCount );
  4058. strPath = MCD_T("/") + strTagName + szPred + strPath;
  4059. }
  4060. iPos = iPosParent;
  4061. }
  4062. return strPath;
  4063. }
  4064. MCD_STR CMarkup::x_GetTagName( int iPos ) const
  4065. {
  4066. // Return the tag name at specified element
  4067. TokenPos token( m_strDoc, m_nDocFlags );
  4068. token.m_nNext = ELEM(iPos).nStart + 1;
  4069. if ( ! iPos || ! token.FindName() )
  4070. return MCD_T("");
  4071. // Return substring of document
  4072. return token.GetTokenText();
  4073. }
  4074. MCD_STR CMarkup::x_GetAttrib( int iPos, MCD_PCSZ pAttrib ) const
  4075. {
  4076. // Return the value of the attrib
  4077. TokenPos token( m_strDoc, m_nDocFlags );
  4078. if ( iPos && m_nNodeType == MNT_ELEMENT )
  4079. token.m_nNext = ELEM(iPos).nStart + 1;
  4080. else if ( iPos == m_iPos && m_nNodeLength && m_nNodeType == MNT_PROCESSING_INSTRUCTION )
  4081. token.m_nNext = m_nNodeOffset + 2;
  4082. else
  4083. return MCD_T("");
  4084. if ( pAttrib && token.FindAttrib(pAttrib) )
  4085. return UnescapeText( token.GetTokenPtr(), token.Length(), m_nDocFlags );
  4086. return MCD_T("");
  4087. }
  4088. bool CMarkup::x_SetAttrib( int iPos, MCD_PCSZ pAttrib, int nValue, int nFlags /*=0*/ )
  4089. {
  4090. // Convert integer to string
  4091. MCD_CHAR szVal[25];
  4092. MCD_SPRINTF( MCD_SSZ(szVal), MCD_T("%d"), nValue );
  4093. return x_SetAttrib( iPos, pAttrib, szVal, nFlags );
  4094. }
  4095. bool CMarkup::x_SetAttrib( int iPos, MCD_PCSZ pAttrib, MCD_PCSZ pValue, int nFlags /*=0*/ )
  4096. {
  4097. if ( m_nDocFlags & MDF_READFILE )
  4098. return false;
  4099. int nNodeStart = 0;
  4100. if ( iPos && m_nNodeType == MNT_ELEMENT )
  4101. nNodeStart = ELEM(iPos).nStart;
  4102. else if ( iPos == m_iPos && m_nNodeLength && m_nNodeType == MNT_PROCESSING_INSTRUCTION )
  4103. nNodeStart = m_nNodeOffset;
  4104. else
  4105. return false;
  4106. // Create insertion text depending on whether attribute already exists
  4107. // Decision: for empty value leaving attrib="" instead of removing attrib
  4108. TokenPos token( m_strDoc, m_nDocFlags );
  4109. token.m_nNext = nNodeStart + ((m_nNodeType == MNT_ELEMENT)?1:2);
  4110. int nReplace = 0;
  4111. int nInsertAt;
  4112. MCD_STR strEscapedValue = EscapeText( pValue, MNF_ESCAPEQUOTES|nFlags );
  4113. int nEscapedValueLen = MCD_STRLENGTH( strEscapedValue );
  4114. MCD_STR strInsert;
  4115. if ( token.FindAttrib(pAttrib) )
  4116. {
  4117. // Replace value
  4118. MCD_BLDRESERVE( strInsert, nEscapedValueLen + 2 );
  4119. MCD_BLDAPPEND1( strInsert, x_ATTRIBQUOTE );
  4120. MCD_BLDAPPENDN( strInsert, MCD_2PCSZ(strEscapedValue), nEscapedValueLen );
  4121. MCD_BLDAPPEND1( strInsert, x_ATTRIBQUOTE );
  4122. MCD_BLDRELEASE( strInsert );
  4123. nInsertAt = token.m_nL - ((token.m_nTokenFlags&MNF_QUOTED)?1:0);
  4124. nReplace = token.Length() + ((token.m_nTokenFlags&MNF_QUOTED)?2:0);
  4125. }
  4126. else
  4127. {
  4128. // Insert string name value pair
  4129. int nAttribNameLen = MCD_PSZLEN( pAttrib );
  4130. MCD_BLDRESERVE( strInsert, nAttribNameLen + nEscapedValueLen + 4 );
  4131. MCD_BLDAPPEND1( strInsert, ' ' );
  4132. MCD_BLDAPPENDN( strInsert, pAttrib, nAttribNameLen );
  4133. MCD_BLDAPPEND1( strInsert, '=' );
  4134. MCD_BLDAPPEND1( strInsert, x_ATTRIBQUOTE );
  4135. MCD_BLDAPPENDN( strInsert, MCD_2PCSZ(strEscapedValue), nEscapedValueLen );
  4136. MCD_BLDAPPEND1( strInsert, x_ATTRIBQUOTE );
  4137. MCD_BLDRELEASE( strInsert );
  4138. nInsertAt = token.m_nNext;
  4139. }
  4140. int nAdjust = MCD_STRLENGTH(strInsert) - nReplace;
  4141. if ( m_nDocFlags & MDF_WRITEFILE )
  4142. {
  4143. int nNewDocLength = MCD_STRLENGTH(m_strDoc) + nAdjust;
  4144. MCD_STRCLEAR( m_strResult );
  4145. if ( nNodeStart && nNewDocLength > m_pFilePos->m_nBlockSizeBasis )
  4146. {
  4147. int nDocCapacity = MCD_STRCAPACITY(m_strDoc);
  4148. if ( nNewDocLength > nDocCapacity )
  4149. {
  4150. m_pFilePos->FileFlush( *m_pFilePos->m_pstrBuffer, nNodeStart );
  4151. m_strResult = m_pFilePos->m_strIOResult;
  4152. nInsertAt -= nNodeStart;
  4153. m_nNodeOffset = 0;
  4154. if ( m_nNodeType == MNT_ELEMENT )
  4155. ELEM(iPos).nStart = 0;
  4156. }
  4157. }
  4158. }
  4159. x_DocChange( nInsertAt, nReplace, strInsert );
  4160. if ( m_nNodeType == MNT_PROCESSING_INSTRUCTION )
  4161. {
  4162. x_AdjustForNode( m_iPosParent, m_iPos, nAdjust );
  4163. m_nNodeLength += nAdjust;
  4164. }
  4165. else
  4166. {
  4167. ELEM(iPos).AdjustStartTagLen( nAdjust );
  4168. ELEM(iPos).nLength += nAdjust;
  4169. x_Adjust( iPos, nAdjust );
  4170. }
  4171. MARKUP_SETDEBUGSTATE;
  4172. return true;
  4173. }
  4174. bool CMarkup::x_CreateNode( MCD_STR& strNode, int nNodeType, MCD_PCSZ pText )
  4175. {
  4176. // Set strNode based on nNodeType and szData
  4177. // Return false if szData would jeopardize well-formed document
  4178. //
  4179. switch ( nNodeType )
  4180. {
  4181. case MNT_PROCESSING_INSTRUCTION:
  4182. strNode = MCD_T("<?");
  4183. strNode += pText;
  4184. strNode += MCD_T("?>");
  4185. break;
  4186. case MNT_COMMENT:
  4187. strNode = MCD_T("<!--");
  4188. strNode += pText;
  4189. strNode += MCD_T("-->");
  4190. break;
  4191. case MNT_ELEMENT:
  4192. strNode = MCD_T("<");
  4193. strNode += pText;
  4194. strNode += MCD_T("/>");
  4195. break;
  4196. case MNT_TEXT:
  4197. case MNT_WHITESPACE:
  4198. strNode = EscapeText( pText );
  4199. break;
  4200. case MNT_DOCUMENT_TYPE:
  4201. strNode = pText;
  4202. break;
  4203. case MNT_LONE_END_TAG:
  4204. strNode = MCD_T("</");
  4205. strNode += pText;
  4206. strNode += MCD_T(">");
  4207. break;
  4208. case MNT_CDATA_SECTION:
  4209. if ( MCD_PSZSTR(pText,MCD_T("]]>")) != NULL )
  4210. return false;
  4211. strNode = MCD_T("<![CDATA[");
  4212. strNode += pText;
  4213. strNode += MCD_T("]]>");
  4214. break;
  4215. }
  4216. return true;
  4217. }
  4218. MCD_STR CMarkup::x_EncodeCDATASection( MCD_PCSZ szData )
  4219. {
  4220. // Split CDATA Sections if there are any end delimiters
  4221. MCD_STR strData = MCD_T("<![CDATA[");
  4222. MCD_PCSZ pszNextStart = szData;
  4223. MCD_PCSZ pszEnd = MCD_PSZSTR( szData, MCD_T("]]>") );
  4224. while ( pszEnd )
  4225. {
  4226. strData += MCD_STR( pszNextStart, (int)(pszEnd - pszNextStart) );
  4227. strData += MCD_T("]]]]><![CDATA[>");
  4228. pszNextStart = pszEnd + 3;
  4229. pszEnd = MCD_PSZSTR( pszNextStart, MCD_T("]]>") );
  4230. }
  4231. strData += pszNextStart;
  4232. strData += MCD_T("]]>");
  4233. return strData;
  4234. }
  4235. bool CMarkup::x_SetData( int iPos, int nValue )
  4236. {
  4237. // Convert integer to string
  4238. MCD_CHAR szVal[25];
  4239. MCD_SPRINTF( MCD_SSZ(szVal), MCD_T("%d"), nValue );
  4240. return x_SetData( iPos, szVal, 0 );
  4241. }
  4242. bool CMarkup::x_SetData( int iPos, MCD_PCSZ szData, int nFlags )
  4243. {
  4244. if ( m_nDocFlags & MDF_READFILE )
  4245. return false;
  4246. MCD_STR strInsert;
  4247. if ( m_nDocFlags & MDF_WRITEFILE )
  4248. {
  4249. if ( ! iPos || m_nNodeType != 1 || ! ELEM(iPos).IsEmptyElement() )
  4250. return false; // only set data on current empty element (no other kinds of nodes)
  4251. }
  4252. if ( iPos == m_iPos && m_nNodeLength )
  4253. {
  4254. // Not an element
  4255. if ( ! x_CreateNode(strInsert, m_nNodeType, szData) )
  4256. return false;
  4257. x_DocChange( m_nNodeOffset, m_nNodeLength, strInsert );
  4258. x_AdjustForNode( m_iPosParent, iPos, MCD_STRLENGTH(strInsert) - m_nNodeLength );
  4259. m_nNodeLength = MCD_STRLENGTH(strInsert);
  4260. MARKUP_SETDEBUGSTATE;
  4261. return true;
  4262. }
  4263. // Set data in iPos element
  4264. if ( ! iPos || ELEM(iPos).iElemChild )
  4265. return false;
  4266. // Build strInsert from szData based on nFlags
  4267. if ( nFlags & MNF_WITHCDATA )
  4268. strInsert = x_EncodeCDATASection( szData );
  4269. else
  4270. strInsert = EscapeText( szData, nFlags );
  4271. // Insert
  4272. NodePos node( MNF_WITHNOLINES|MNF_REPLACE );
  4273. node.strMeta = strInsert;
  4274. int iPosBefore = 0;
  4275. int nReplace = x_InsertNew( iPos, iPosBefore, node );
  4276. int nAdjust = MCD_STRLENGTH(node.strMeta) - nReplace;
  4277. x_Adjust( iPos, nAdjust );
  4278. ELEM(iPos).nLength += nAdjust;
  4279. if ( ELEM(iPos).nFlags & MNF_ILLDATA )
  4280. ELEM(iPos).nFlags &= ~MNF_ILLDATA;
  4281. MARKUP_SETDEBUGSTATE;
  4282. return true;
  4283. }
  4284. MCD_STR CMarkup::x_GetData( int iPos )
  4285. {
  4286. if ( iPos == m_iPos && m_nNodeLength )
  4287. {
  4288. if ( m_nNodeType == MNT_COMMENT )
  4289. return MCD_STRMID( m_strDoc, m_nNodeOffset+4, m_nNodeLength-7 );
  4290. else if ( m_nNodeType == MNT_PROCESSING_INSTRUCTION )
  4291. return MCD_STRMID( m_strDoc, m_nNodeOffset+2, m_nNodeLength-4 );
  4292. else if ( m_nNodeType == MNT_CDATA_SECTION )
  4293. return MCD_STRMID( m_strDoc, m_nNodeOffset+9, m_nNodeLength-12 );
  4294. else if ( m_nNodeType == MNT_TEXT )
  4295. return UnescapeText( &(MCD_2PCSZ(m_strDoc))[m_nNodeOffset], m_nNodeLength, m_nDocFlags );
  4296. else if ( m_nNodeType == MNT_LONE_END_TAG )
  4297. return MCD_STRMID( m_strDoc, m_nNodeOffset+2, m_nNodeLength-3 );
  4298. return MCD_STRMID( m_strDoc, m_nNodeOffset, m_nNodeLength );
  4299. }
  4300. // Return a string representing data between start and end tag
  4301. // Return empty string if there are any children elements
  4302. MCD_STR strData;
  4303. if ( iPos && ! ELEM(iPos).IsEmptyElement() )
  4304. {
  4305. ElemPos* pElem = &ELEM(iPos);
  4306. int nStartContent = pElem->StartContent();
  4307. if ( pElem->IsUnparsed() )
  4308. {
  4309. TokenPos token( m_strDoc, m_nDocFlags, m_pFilePos );
  4310. token.m_nNext = nStartContent;
  4311. NodePos node;
  4312. m_pFilePos->m_nReadBufferStart = pElem->nStart;
  4313. while ( 1 )
  4314. {
  4315. m_pFilePos->m_nReadBufferRemoved = 0; // will be non-zero after ParseNode if read buffer shifted
  4316. token.ParseNode( node );
  4317. if ( m_pFilePos->m_nReadBufferRemoved )
  4318. {
  4319. pElem->nStart = 0;
  4320. MARKUP_SETDEBUGSTATE;
  4321. }
  4322. if ( node.nNodeType == MNT_TEXT )
  4323. strData += UnescapeText( &token.m_pDocText[node.nStart], node.nLength, m_nDocFlags );
  4324. else if ( node.nNodeType == MNT_CDATA_SECTION )
  4325. strData += MCD_STRMID( m_strDoc, node.nStart+9, node.nLength-12 );
  4326. else if ( node.nNodeType == MNT_ELEMENT )
  4327. {
  4328. MCD_STRCLEAR(strData);
  4329. break;
  4330. }
  4331. else if ( node.nNodeType == 0 )
  4332. {
  4333. if ( token.Match(m_pFilePos->m_elemstack.Current().strTagName) )
  4334. {
  4335. pElem->SetEndTagLen( node.nLength );
  4336. pElem->nLength = node.nStart + node.nLength - pElem->nStart;
  4337. m_pFilePos->m_elemstack.OutOfLevel();
  4338. }
  4339. else
  4340. {
  4341. MCD_STRCLEAR(strData);
  4342. }
  4343. break;
  4344. }
  4345. }
  4346. }
  4347. else if ( ! pElem->iElemChild )
  4348. {
  4349. // Quick scan for any tags inside content
  4350. int nContentLen = pElem->ContentLen();
  4351. MCD_PCSZ pszContent = &(MCD_2PCSZ(m_strDoc))[nStartContent];
  4352. MCD_PCSZ pszTag = MCD_PSZCHR( pszContent, '<' );
  4353. if ( pszTag && ((int)(pszTag-pszContent) < nContentLen) )
  4354. {
  4355. // Concatenate all CDATA Sections and text nodes, ignore other nodes
  4356. TokenPos token( m_strDoc, m_nDocFlags );
  4357. token.m_nNext = nStartContent;
  4358. NodePos node;
  4359. while ( token.m_nNext < nStartContent + nContentLen )
  4360. {
  4361. token.ParseNode( node );
  4362. if ( node.nNodeType == MNT_TEXT )
  4363. strData += UnescapeText( &token.m_pDocText[node.nStart], node.nLength, m_nDocFlags );
  4364. else if ( node.nNodeType == MNT_CDATA_SECTION )
  4365. strData += MCD_STRMID( m_strDoc, node.nStart+9, node.nLength-12 );
  4366. }
  4367. }
  4368. else // no tags
  4369. strData = UnescapeText( &(MCD_2PCSZ(m_strDoc))[nStartContent], nContentLen, m_nDocFlags );
  4370. }
  4371. }
  4372. return strData;
  4373. }
  4374. MCD_STR CMarkup::x_GetElemContent( int iPos ) const
  4375. {
  4376. if ( ! (m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE)) )
  4377. {
  4378. ElemPos* pElem = &ELEM(iPos);
  4379. if ( iPos && pElem->ContentLen() )
  4380. return MCD_STRMID( m_strDoc, pElem->StartContent(), pElem->ContentLen() );
  4381. }
  4382. return MCD_T("");
  4383. }
  4384. bool CMarkup::x_SetElemContent( MCD_PCSZ szContent )
  4385. {
  4386. MCD_STRCLEAR(m_strResult);
  4387. if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
  4388. return false;
  4389. // Set data in iPos element only
  4390. if ( ! m_iPos )
  4391. return false;
  4392. if ( m_nNodeLength )
  4393. return false; // not an element
  4394. // Unlink all children
  4395. int iPos = m_iPos;
  4396. int iPosChild = ELEM(iPos).iElemChild;
  4397. bool bHadChild = (iPosChild != 0);
  4398. while ( iPosChild )
  4399. iPosChild = x_ReleaseSubDoc( iPosChild );
  4400. if ( bHadChild )
  4401. x_CheckSavedPos();
  4402. // Parse content
  4403. bool bWellFormed = true;
  4404. TokenPos token( szContent, m_nDocFlags );
  4405. int iPosVirtual = x_GetFreePos();
  4406. ELEM(iPosVirtual).ClearVirtualParent();
  4407. ELEM(iPosVirtual).SetLevel( ELEM(iPos).Level() + 1 );
  4408. iPosChild = x_ParseElem( iPosVirtual, token );
  4409. if ( ELEM(iPosVirtual).nFlags & MNF_ILLFORMED )
  4410. bWellFormed = false;
  4411. ELEM(iPos).nFlags = (ELEM(iPos).nFlags & ~MNF_ILLDATA) | (ELEM(iPosVirtual).nFlags & MNF_ILLDATA);
  4412. // Prepare insert and adjust offsets
  4413. NodePos node( MNF_WITHNOLINES|MNF_REPLACE );
  4414. node.strMeta = szContent;
  4415. int iPosBefore = 0;
  4416. int nReplace = x_InsertNew( iPos, iPosBefore, node );
  4417. // Adjust and link in the inserted elements
  4418. x_Adjust( iPosChild, node.nStart );
  4419. ELEM(iPosChild).nStart += node.nStart;
  4420. ELEM(iPos).iElemChild = iPosChild;
  4421. while ( iPosChild )
  4422. {
  4423. ELEM(iPosChild).iElemParent = iPos;
  4424. iPosChild = ELEM(iPosChild).iElemNext;
  4425. }
  4426. x_ReleasePos( iPosVirtual );
  4427. int nAdjust = MCD_STRLENGTH(node.strMeta) - nReplace;
  4428. x_Adjust( iPos, nAdjust, true );
  4429. ELEM(iPos).nLength += nAdjust;
  4430. x_SetPos( m_iPosParent, m_iPos, 0 );
  4431. return bWellFormed;
  4432. }
  4433. void CMarkup::x_DocChange( int nLeft, int nReplace, const MCD_STR& strInsert )
  4434. {
  4435. x_StrInsertReplace( m_strDoc, nLeft, nReplace, strInsert );
  4436. }
  4437. void CMarkup::x_Adjust( int iPos, int nShift, bool bAfterPos /*=false*/ )
  4438. {
  4439. // Loop through affected elements and adjust indexes
  4440. // Algorithm:
  4441. // 1. update children unless bAfterPos
  4442. // (if no children or bAfterPos is true, length of iPos not affected)
  4443. // 2. update starts of next siblings and their children
  4444. // 3. go up until there is a next sibling of a parent and update starts
  4445. // 4. step 2
  4446. int iPosTop = ELEM(iPos).iElemParent;
  4447. bool bPosFirst = bAfterPos; // mark as first to skip its children
  4448. // Stop when we've reached the virtual parent (which has no tags)
  4449. while ( ELEM(iPos).StartTagLen() )
  4450. {
  4451. // Were we at containing parent of affected position?
  4452. bool bPosTop = false;
  4453. if ( iPos == iPosTop )
  4454. {
  4455. // Move iPosTop up one towards root
  4456. iPosTop = ELEM(iPos).iElemParent;
  4457. bPosTop = true;
  4458. }
  4459. // Traverse to the next update position
  4460. if ( ! bPosTop && ! bPosFirst && ELEM(iPos).iElemChild )
  4461. {
  4462. // Depth first
  4463. iPos = ELEM(iPos).iElemChild;
  4464. }
  4465. else if ( ELEM(iPos).iElemNext )
  4466. {
  4467. iPos = ELEM(iPos).iElemNext;
  4468. }
  4469. else
  4470. {
  4471. // Look for next sibling of a parent of iPos
  4472. // When going back up, parents have already been done except iPosTop
  4473. while ( 1 )
  4474. {
  4475. iPos = ELEM(iPos).iElemParent;
  4476. if ( iPos == iPosTop )
  4477. break;
  4478. if ( ELEM(iPos).iElemNext )
  4479. {
  4480. iPos = ELEM(iPos).iElemNext;
  4481. break;
  4482. }
  4483. }
  4484. }
  4485. bPosFirst = false;
  4486. // Shift indexes at iPos
  4487. if ( iPos != iPosTop )
  4488. ELEM(iPos).nStart += nShift;
  4489. else
  4490. ELEM(iPos).nLength += nShift;
  4491. }
  4492. }
  4493. int CMarkup::x_InsertNew( int iPosParent, int& iPosRel, NodePos& node )
  4494. {
  4495. // Parent empty tag or tags with no content?
  4496. bool bEmptyParentTag = iPosParent && ELEM(iPosParent).IsEmptyElement();
  4497. bool bNoContentParentTags = iPosParent && ! ELEM(iPosParent).ContentLen();
  4498. if ( iPosRel && ! node.nLength ) // current position element?
  4499. {
  4500. node.nStart = ELEM(iPosRel).nStart;
  4501. if ( ! (node.nNodeFlags & MNF_INSERT) ) // follow iPosRel
  4502. node.nStart += ELEM(iPosRel).nLength;
  4503. }
  4504. else if ( bEmptyParentTag ) // parent has no separate end tag?
  4505. {
  4506. // Split empty parent element
  4507. if ( ELEM(iPosParent).nFlags & MNF_NONENDED )
  4508. node.nStart = ELEM(iPosParent).StartContent();
  4509. else
  4510. node.nStart = ELEM(iPosParent).StartContent() - 1;
  4511. }
  4512. else if ( node.nLength || (m_nDocFlags&MDF_WRITEFILE) ) // non-element node or a file mode zero length position?
  4513. {
  4514. if ( ! (node.nNodeFlags & MNF_INSERT) )
  4515. node.nStart += node.nLength; // after node or file mode position
  4516. }
  4517. else // no current node
  4518. {
  4519. // Insert relative to parent's content
  4520. if ( node.nNodeFlags & (MNF_INSERT|MNF_REPLACE) )
  4521. node.nStart = ELEM(iPosParent).StartContent(); // beginning of parent's content
  4522. else // in front of parent's end tag
  4523. node.nStart = ELEM(iPosParent).StartAfter() - ELEM(iPosParent).EndTagLen();
  4524. }
  4525. // Go up to start of next node, unless its splitting an empty element
  4526. if ( ! (node.nNodeFlags&(MNF_WITHNOLINES|MNF_REPLACE)) && ! bEmptyParentTag )
  4527. {
  4528. TokenPos token( m_strDoc, m_nDocFlags );
  4529. node.nStart = token.WhitespaceToTag( node.nStart );
  4530. }
  4531. // Is insert relative to element position? (i.e. not other kind of node)
  4532. if ( ! node.nLength )
  4533. {
  4534. // Modify iPosRel to reflect position before
  4535. if ( iPosRel )
  4536. {
  4537. if ( node.nNodeFlags & MNF_INSERT )
  4538. {
  4539. if ( ! (ELEM(iPosRel).nFlags & MNF_FIRST) )
  4540. iPosRel = ELEM(iPosRel).iElemPrev;
  4541. else
  4542. iPosRel = 0;
  4543. }
  4544. }
  4545. else if ( ! (node.nNodeFlags & MNF_INSERT) )
  4546. {
  4547. // If parent has a child, add after last child
  4548. if ( ELEM(iPosParent).iElemChild )
  4549. iPosRel = ELEM(ELEM(iPosParent).iElemChild).iElemPrev;
  4550. }
  4551. }
  4552. // Get node length (needed for x_AddNode and x_AddSubDoc in file write mode)
  4553. node.nLength = MCD_STRLENGTH(node.strMeta);
  4554. // Prepare end of lines
  4555. if ( (! (node.nNodeFlags & MNF_WITHNOLINES)) && (bEmptyParentTag || bNoContentParentTags) )
  4556. node.nStart += MCD_EOLLEN;
  4557. if ( ! (node.nNodeFlags & MNF_WITHNOLINES) )
  4558. node.strMeta += MCD_EOL;
  4559. // Calculate insert offset and replace length
  4560. int nReplace = 0;
  4561. int nInsertAt = node.nStart;
  4562. if ( bEmptyParentTag )
  4563. {
  4564. MCD_STR strTagName = x_GetTagName( iPosParent );
  4565. MCD_STR strFormat;
  4566. if ( node.nNodeFlags & MNF_WITHNOLINES )
  4567. strFormat = MCD_T(">");
  4568. else
  4569. strFormat = MCD_T(">") MCD_EOL;
  4570. strFormat += node.strMeta;
  4571. strFormat += MCD_T("</");
  4572. strFormat += strTagName;
  4573. node.strMeta = strFormat;
  4574. if ( ELEM(iPosParent).nFlags & MNF_NONENDED )
  4575. {
  4576. nInsertAt = ELEM(iPosParent).StartAfter() - 1;
  4577. nReplace = 0;
  4578. ELEM(iPosParent).nFlags ^= MNF_NONENDED;
  4579. }
  4580. else
  4581. {
  4582. nInsertAt = ELEM(iPosParent).StartAfter() - 2;
  4583. nReplace = 1;
  4584. ELEM(iPosParent).AdjustStartTagLen( -1 );
  4585. }
  4586. ELEM(iPosParent).SetEndTagLen( 3 + MCD_STRLENGTH(strTagName) );
  4587. }
  4588. else
  4589. {
  4590. if ( node.nNodeFlags & MNF_REPLACE )
  4591. {
  4592. nInsertAt = ELEM(iPosParent).StartContent();
  4593. nReplace = ELEM(iPosParent).ContentLen();
  4594. }
  4595. else if ( bNoContentParentTags )
  4596. {
  4597. node.strMeta = MCD_EOL + node.strMeta;
  4598. nInsertAt = ELEM(iPosParent).StartContent();
  4599. }
  4600. }
  4601. if ( m_nDocFlags & MDF_WRITEFILE )
  4602. {
  4603. // Check if buffer is full
  4604. int nNewDocLength = MCD_STRLENGTH(m_strDoc) + MCD_STRLENGTH(node.strMeta) - nReplace;
  4605. int nFlushTo = node.nStart;
  4606. MCD_STRCLEAR( m_strResult );
  4607. if ( bEmptyParentTag )
  4608. nFlushTo = ELEM(iPosParent).nStart;
  4609. if ( nFlushTo && nNewDocLength > m_pFilePos->m_nBlockSizeBasis )
  4610. {
  4611. int nDocCapacity = MCD_STRCAPACITY(m_strDoc);
  4612. if ( nNewDocLength > nDocCapacity )
  4613. {
  4614. if ( bEmptyParentTag )
  4615. ELEM(iPosParent).nStart = 0;
  4616. node.nStart -= nFlushTo;
  4617. nInsertAt -= nFlushTo;
  4618. m_pFilePos->FileFlush( m_strDoc, nFlushTo );
  4619. m_strResult = m_pFilePos->m_strIOResult;
  4620. }
  4621. }
  4622. }
  4623. x_DocChange( nInsertAt, nReplace, node.strMeta );
  4624. return nReplace;
  4625. }
  4626. bool CMarkup::x_AddElem( MCD_PCSZ pName, int nValue, int nFlags )
  4627. {
  4628. // Convert integer to string
  4629. MCD_CHAR szVal[25];
  4630. MCD_SPRINTF( MCD_SSZ(szVal), MCD_T("%d"), nValue );
  4631. return x_AddElem( pName, szVal, nFlags );
  4632. }
  4633. bool CMarkup::x_AddElem( MCD_PCSZ pName, MCD_PCSZ pValue, int nFlags )
  4634. {
  4635. if ( m_nDocFlags & MDF_READFILE )
  4636. return false;
  4637. if ( nFlags & MNF_CHILD )
  4638. {
  4639. // Adding a child element under main position
  4640. if ( ! m_iPos || (m_nDocFlags & MDF_WRITEFILE) )
  4641. return false;
  4642. }
  4643. // Cannot have data in non-ended element
  4644. if ( (nFlags&MNF_WITHNOEND) && pValue && pValue[0] )
  4645. return false;
  4646. // Node and element structures
  4647. NodePos node( nFlags );
  4648. int iPosParent = 0, iPosBefore = 0;
  4649. int iPos = x_GetFreePos();
  4650. ElemPos* pElem = &ELEM(iPos);
  4651. // Locate where to add element relative to current node
  4652. if ( nFlags & MNF_CHILD )
  4653. {
  4654. iPosParent = m_iPos;
  4655. iPosBefore = m_iPosChild;
  4656. }
  4657. else
  4658. {
  4659. iPosParent = m_iPosParent;
  4660. iPosBefore = m_iPos;
  4661. node.nStart = m_nNodeOffset;
  4662. node.nLength = m_nNodeLength;
  4663. }
  4664. // Create string for insert
  4665. // If no pValue is specified, an empty element is created
  4666. // i.e. either <NAME>value</NAME> or <NAME/>
  4667. //
  4668. int nLenName = MCD_PSZLEN(pName);
  4669. if ( ! pValue || ! pValue[0] )
  4670. {
  4671. // <NAME/> empty element
  4672. MCD_BLDRESERVE( node.strMeta, nLenName + 4 );
  4673. MCD_BLDAPPEND1( node.strMeta, '<' );
  4674. MCD_BLDAPPENDN( node.strMeta, pName, nLenName );
  4675. if ( nFlags & MNF_WITHNOEND )
  4676. {
  4677. MCD_BLDAPPEND1( node.strMeta, '>' );
  4678. }
  4679. else
  4680. {
  4681. if ( nFlags & MNF_WITHXHTMLSPACE )
  4682. {
  4683. MCD_BLDAPPENDN( node.strMeta, MCD_T(" />"), 3 );
  4684. }
  4685. else
  4686. {
  4687. MCD_BLDAPPENDN( node.strMeta, MCD_T("/>"), 2 );
  4688. }
  4689. }
  4690. MCD_BLDRELEASE( node.strMeta );
  4691. pElem->nLength = MCD_STRLENGTH( node.strMeta );
  4692. pElem->SetStartTagLen( pElem->nLength );
  4693. pElem->SetEndTagLen( 0 );
  4694. }
  4695. else
  4696. {
  4697. // <NAME>value</NAME>
  4698. MCD_STR strValue;
  4699. if ( nFlags & MNF_WITHCDATA )
  4700. strValue = x_EncodeCDATASection( pValue );
  4701. else
  4702. strValue = EscapeText( pValue, nFlags );
  4703. int nLenValue = MCD_STRLENGTH(strValue);
  4704. pElem->nLength = nLenName * 2 + nLenValue + 5;
  4705. MCD_BLDRESERVE( node.strMeta, pElem->nLength );
  4706. MCD_BLDAPPEND1( node.strMeta, '<' );
  4707. MCD_BLDAPPENDN( node.strMeta, pName, nLenName );
  4708. MCD_BLDAPPEND1( node.strMeta, '>' );
  4709. MCD_BLDAPPENDN( node.strMeta, MCD_2PCSZ(strValue), nLenValue );
  4710. MCD_BLDAPPENDN( node.strMeta, MCD_T("</"), 2 );
  4711. MCD_BLDAPPENDN( node.strMeta, pName, nLenName );
  4712. MCD_BLDAPPEND1( node.strMeta, '>' );
  4713. MCD_BLDRELEASE( node.strMeta );
  4714. pElem->SetEndTagLen( nLenName + 3 );
  4715. pElem->SetStartTagLen( nLenName + 2 );
  4716. }
  4717. // Insert
  4718. int nReplace = x_InsertNew( iPosParent, iPosBefore, node );
  4719. pElem->nStart = node.nStart;
  4720. pElem->iElemChild = 0;
  4721. if ( nFlags & MNF_WITHNOEND )
  4722. pElem->nFlags = MNF_NONENDED;
  4723. else
  4724. pElem->nFlags = 0;
  4725. if ( m_nDocFlags & MDF_WRITEFILE )
  4726. {
  4727. iPosParent = x_UnlinkPrevElem( iPosParent, iPosBefore, iPos );
  4728. TokenPos token( m_strDoc, m_nDocFlags );
  4729. token.m_nL = pElem->nStart + 1;
  4730. token.m_nR = pElem->nStart + nLenName;
  4731. m_pFilePos->m_elemstack.PushTagAndCount( token );
  4732. }
  4733. else
  4734. {
  4735. x_LinkElem( iPosParent, iPosBefore, iPos );
  4736. x_Adjust( iPos, MCD_STRLENGTH(node.strMeta) - nReplace );
  4737. }
  4738. if ( nFlags & MNF_CHILD )
  4739. x_SetPos( m_iPosParent, iPosParent, iPos );
  4740. else
  4741. x_SetPos( iPosParent, iPos, 0 );
  4742. return true;
  4743. }
  4744. MCD_STR CMarkup::x_GetSubDoc( int iPos )
  4745. {
  4746. if ( iPos && ! (m_nDocFlags&MDF_WRITEFILE) )
  4747. {
  4748. if ( ! (m_nDocFlags&MDF_READFILE) )
  4749. {
  4750. TokenPos token( m_strDoc, m_nDocFlags );
  4751. token.WhitespaceToTag( ELEM(iPos).StartAfter() );
  4752. token.m_nL = ELEM(iPos).nStart;
  4753. return token.GetTokenText();
  4754. }
  4755. }
  4756. return MCD_T("");
  4757. }
  4758. bool CMarkup::x_AddSubDoc( MCD_PCSZ pSubDoc, int nFlags )
  4759. {
  4760. if ( m_nDocFlags & MDF_READFILE || ((nFlags & MNF_CHILD) && (m_nDocFlags & MDF_WRITEFILE)) )
  4761. return false;
  4762. MCD_STRCLEAR(m_strResult);
  4763. NodePos node( nFlags );
  4764. int iPosParent, iPosBefore;
  4765. if ( nFlags & MNF_CHILD )
  4766. {
  4767. // Add a subdocument under main position, before or after child
  4768. if ( ! m_iPos )
  4769. return false;
  4770. iPosParent = m_iPos;
  4771. iPosBefore = m_iPosChild;
  4772. }
  4773. else
  4774. {
  4775. // Add a subdocument under parent position, before or after main
  4776. iPosParent = m_iPosParent;
  4777. iPosBefore = m_iPos;
  4778. node.nStart = m_nNodeOffset;
  4779. node.nLength = m_nNodeLength;
  4780. }
  4781. // Parse subdocument, generating indexes based on the subdocument string to be offset later
  4782. bool bWellFormed = true;
  4783. TokenPos token( pSubDoc, m_nDocFlags );
  4784. int iPosVirtual = x_GetFreePos();
  4785. ELEM(iPosVirtual).ClearVirtualParent();
  4786. ELEM(iPosVirtual).SetLevel( ELEM(iPosParent).Level() + 1 );
  4787. int iPos = x_ParseElem( iPosVirtual, token );
  4788. if ( (!iPos) || ELEM(iPosVirtual).nFlags & MNF_ILLFORMED )
  4789. bWellFormed = false;
  4790. if ( ELEM(iPosVirtual).nFlags & MNF_ILLDATA )
  4791. ELEM(iPosParent).nFlags |= MNF_ILLDATA;
  4792. // File write mode handling
  4793. bool bBypassSubDoc = false;
  4794. if ( m_nDocFlags & MDF_WRITEFILE )
  4795. {
  4796. // Current position will bypass subdoc unless well-formed single element
  4797. if ( (! bWellFormed) || ELEM(iPos).iElemChild || ELEM(iPos).iElemNext )
  4798. bBypassSubDoc = true;
  4799. // Count tag names of top level elements (usually one) in given markup
  4800. int iPosTop = iPos;
  4801. while ( iPosTop )
  4802. {
  4803. token.m_nNext = ELEM(iPosTop).nStart + 1;
  4804. token.FindName();
  4805. m_pFilePos->m_elemstack.PushTagAndCount( token );
  4806. iPosTop = ELEM(iPosTop).iElemNext;
  4807. }
  4808. }
  4809. // Extract subdocument without leading/trailing nodes
  4810. int nExtractStart = 0;
  4811. int iPosLast = ELEM(iPos).iElemPrev;
  4812. if ( bWellFormed )
  4813. {
  4814. nExtractStart = ELEM(iPos).nStart;
  4815. int nExtractLength = ELEM(iPos).nLength;
  4816. if ( iPos != iPosLast )
  4817. {
  4818. nExtractLength = ELEM(iPosLast).nStart - nExtractStart + ELEM(iPosLast).nLength;
  4819. bWellFormed = false; // treat as subdoc here, but return not well-formed
  4820. }
  4821. MCD_STRASSIGN(node.strMeta,&pSubDoc[nExtractStart],nExtractLength);
  4822. }
  4823. else
  4824. {
  4825. node.strMeta = pSubDoc;
  4826. node.nNodeFlags |= MNF_WITHNOLINES;
  4827. }
  4828. // Insert
  4829. int nReplace = x_InsertNew( iPosParent, iPosBefore, node );
  4830. // Clean up indexes
  4831. if ( m_nDocFlags & MDF_WRITEFILE )
  4832. {
  4833. if ( bBypassSubDoc )
  4834. {
  4835. // Release indexes used in parsing the subdocument
  4836. m_iPosParent = x_UnlinkPrevElem( iPosParent, iPosBefore, 0 );
  4837. m_iPosFree = 1;
  4838. m_iPosDeleted = 0;
  4839. m_iPos = 0;
  4840. m_nNodeOffset = node.nStart + node.nLength;
  4841. m_nNodeLength = 0;
  4842. m_nNodeType = 0;
  4843. MARKUP_SETDEBUGSTATE;
  4844. return bWellFormed;
  4845. }
  4846. else // single element added
  4847. {
  4848. m_iPos = iPos;
  4849. ElemPos* pElem = &ELEM(iPos);
  4850. pElem->nStart = node.nStart;
  4851. m_iPosParent = x_UnlinkPrevElem( iPosParent, iPosBefore, iPos );
  4852. x_ReleasePos( iPosVirtual );
  4853. }
  4854. }
  4855. else
  4856. {
  4857. // Adjust and link in the inserted elements
  4858. // iPosVirtual will stop it from affecting rest of document
  4859. int nAdjust = node.nStart - nExtractStart;
  4860. if ( iPos && nAdjust )
  4861. {
  4862. x_Adjust( iPos, nAdjust );
  4863. ELEM(iPos).nStart += nAdjust;
  4864. }
  4865. int iPosChild = iPos;
  4866. while ( iPosChild )
  4867. {
  4868. int iPosNext = ELEM(iPosChild).iElemNext;
  4869. x_LinkElem( iPosParent, iPosBefore, iPosChild );
  4870. iPosBefore = iPosChild;
  4871. iPosChild = iPosNext;
  4872. }
  4873. x_ReleasePos( iPosVirtual );
  4874. // Now adjust remainder of document
  4875. x_Adjust( iPosLast, MCD_STRLENGTH(node.strMeta) - nReplace, true );
  4876. }
  4877. // Set position to top element of subdocument
  4878. if ( nFlags & MNF_CHILD )
  4879. x_SetPos( m_iPosParent, iPosParent, iPos );
  4880. else // Main
  4881. x_SetPos( m_iPosParent, iPos, 0 );
  4882. return bWellFormed;
  4883. }
  4884. int CMarkup::x_RemoveElem( int iPos )
  4885. {
  4886. // Determine whether any whitespace up to next tag
  4887. TokenPos token( m_strDoc, m_nDocFlags );
  4888. int nAfterEnd = token.WhitespaceToTag( ELEM(iPos).StartAfter() );
  4889. // Remove from document, adjust affected indexes, and unlink
  4890. int nLen = nAfterEnd - ELEM(iPos).nStart;
  4891. x_DocChange( ELEM(iPos).nStart, nLen, MCD_STR() );
  4892. x_Adjust( iPos, - nLen, true );
  4893. int iPosPrev = x_UnlinkElem( iPos );
  4894. x_CheckSavedPos();
  4895. return iPosPrev; // new position
  4896. }
  4897. void CMarkup::x_LinkElem( int iPosParent, int iPosBefore, int iPos )
  4898. {
  4899. // Update links between elements and initialize nFlags
  4900. ElemPos* pElem = &ELEM(iPos);
  4901. if ( m_nDocFlags & MDF_WRITEFILE )
  4902. {
  4903. // In file write mode, only keep virtual parent 0 plus one element
  4904. if ( iPosParent )
  4905. x_ReleasePos( iPosParent );
  4906. else if ( iPosBefore )
  4907. x_ReleasePos( iPosBefore );
  4908. iPosParent = 0;
  4909. ELEM(iPosParent).iElemChild = iPos;
  4910. pElem->iElemParent = iPosParent;
  4911. pElem->iElemPrev = iPos;
  4912. pElem->iElemNext = 0;
  4913. pElem->nFlags |= MNF_FIRST;
  4914. }
  4915. else
  4916. {
  4917. pElem->iElemParent = iPosParent;
  4918. if ( iPosBefore )
  4919. {
  4920. // Link in after iPosBefore
  4921. pElem->nFlags &= ~MNF_FIRST;
  4922. pElem->iElemNext = ELEM(iPosBefore).iElemNext;
  4923. if ( pElem->iElemNext )
  4924. ELEM(pElem->iElemNext).iElemPrev = iPos;
  4925. else
  4926. ELEM(ELEM(iPosParent).iElemChild).iElemPrev = iPos;
  4927. ELEM(iPosBefore).iElemNext = iPos;
  4928. pElem->iElemPrev = iPosBefore;
  4929. }
  4930. else
  4931. {
  4932. // Link in as first child
  4933. pElem->nFlags |= MNF_FIRST;
  4934. if ( ELEM(iPosParent).iElemChild )
  4935. {
  4936. pElem->iElemNext = ELEM(iPosParent).iElemChild;
  4937. pElem->iElemPrev = ELEM(pElem->iElemNext).iElemPrev;
  4938. ELEM(pElem->iElemNext).iElemPrev = iPos;
  4939. ELEM(pElem->iElemNext).nFlags ^= MNF_FIRST;
  4940. }
  4941. else
  4942. {
  4943. pElem->iElemNext = 0;
  4944. pElem->iElemPrev = iPos;
  4945. }
  4946. ELEM(iPosParent).iElemChild = iPos;
  4947. }
  4948. if ( iPosParent )
  4949. pElem->SetLevel( ELEM(iPosParent).Level() + 1 );
  4950. }
  4951. }
  4952. int CMarkup::x_UnlinkElem( int iPos )
  4953. {
  4954. // Fix links to remove element and mark as deleted
  4955. // return previous position or zero if none
  4956. ElemPos* pElem = &ELEM(iPos);
  4957. // Find previous sibling and bypass removed element
  4958. int iPosPrev = 0;
  4959. if ( pElem->nFlags & MNF_FIRST )
  4960. {
  4961. if ( pElem->iElemNext ) // set next as first child
  4962. {
  4963. ELEM(pElem->iElemParent).iElemChild = pElem->iElemNext;
  4964. ELEM(pElem->iElemNext).iElemPrev = pElem->iElemPrev;
  4965. ELEM(pElem->iElemNext).nFlags |= MNF_FIRST;
  4966. }
  4967. else // no children remaining
  4968. ELEM(pElem->iElemParent).iElemChild = 0;
  4969. }
  4970. else
  4971. {
  4972. iPosPrev = pElem->iElemPrev;
  4973. ELEM(iPosPrev).iElemNext = pElem->iElemNext;
  4974. if ( pElem->iElemNext )
  4975. ELEM(pElem->iElemNext).iElemPrev = iPosPrev;
  4976. else
  4977. ELEM(ELEM(pElem->iElemParent).iElemChild).iElemPrev = iPosPrev;
  4978. }
  4979. x_ReleaseSubDoc( iPos );
  4980. return iPosPrev;
  4981. }
  4982. int CMarkup::x_UnlinkPrevElem( int iPosParent, int iPosBefore, int iPos )
  4983. {
  4984. // In file write mode, only keep virtual parent 0 plus one element if currently at element
  4985. if ( iPosParent )
  4986. {
  4987. x_ReleasePos( iPosParent );
  4988. iPosParent = 0;
  4989. }
  4990. else if ( iPosBefore )
  4991. x_ReleasePos( iPosBefore );
  4992. ELEM(iPosParent).iElemChild = iPos;
  4993. ELEM(iPosParent).nLength = MCD_STRLENGTH(m_strDoc);
  4994. if ( iPos )
  4995. {
  4996. ElemPos* pElem = &ELEM(iPos);
  4997. pElem->iElemParent = iPosParent;
  4998. pElem->iElemPrev = iPos;
  4999. pElem->iElemNext = 0;
  5000. pElem->nFlags |= MNF_FIRST;
  5001. }
  5002. return iPosParent;
  5003. }
  5004. int CMarkup::x_ReleasePos( int iPos )
  5005. {
  5006. int iPosNext = ELEM(iPos).iElemNext;
  5007. ELEM(iPos).iElemNext = m_iPosDeleted;
  5008. ELEM(iPos).nFlags = MNF_DELETED;
  5009. m_iPosDeleted = iPos;
  5010. return iPosNext;
  5011. }
  5012. int CMarkup::x_ReleaseSubDoc( int iPos )
  5013. {
  5014. // Mark position structures as deleted by depth first traversal
  5015. // Tricky because iElemNext used in traversal is overwritten for linked list of deleted
  5016. // Return value is what iElemNext was before being overwritten
  5017. //
  5018. int iPosNext = 0, iPosTop = iPos;
  5019. while ( 1 )
  5020. {
  5021. if ( ELEM(iPos).iElemChild )
  5022. iPos = ELEM(iPos).iElemChild;
  5023. else
  5024. {
  5025. while ( 1 )
  5026. {
  5027. iPosNext = x_ReleasePos( iPos );
  5028. if ( iPosNext || iPos == iPosTop )
  5029. break;
  5030. iPos = ELEM(iPos).iElemParent;
  5031. }
  5032. if ( iPos == iPosTop )
  5033. break;
  5034. iPos = iPosNext;
  5035. }
  5036. }
  5037. return iPosNext;
  5038. }
  5039. void CMarkup::x_CheckSavedPos()
  5040. {
  5041. // Remove any saved positions now pointing to deleted elements
  5042. // Must be done as part of element removal before position reassigned
  5043. if ( m_pSavedPosMaps->m_pMaps )
  5044. {
  5045. int nMap = 0;
  5046. while ( m_pSavedPosMaps->m_pMaps[nMap] )
  5047. {
  5048. SavedPosMap* pMap = m_pSavedPosMaps->m_pMaps[nMap];
  5049. for ( int nSlot = 0; nSlot < pMap->nMapSize; ++nSlot )
  5050. {
  5051. SavedPos* pSavedPos = pMap->pTable[nSlot];
  5052. if ( pSavedPos )
  5053. {
  5054. int nOffset = 0;
  5055. int nSavedPosCount = 0;
  5056. while ( 1 )
  5057. {
  5058. if ( pSavedPos[nOffset].nSavedPosFlags & SavedPos::SPM_USED )
  5059. {
  5060. int iPos = pSavedPos[nOffset].iPos;
  5061. if ( ! (ELEM(iPos).nFlags & MNF_DELETED) )
  5062. {
  5063. if ( nSavedPosCount < nOffset )
  5064. {
  5065. pSavedPos[nSavedPosCount] = pSavedPos[nOffset];
  5066. pSavedPos[nSavedPosCount].nSavedPosFlags &= ~SavedPos::SPM_LAST;
  5067. }
  5068. ++nSavedPosCount;
  5069. }
  5070. }
  5071. if ( pSavedPos[nOffset].nSavedPosFlags & SavedPos::SPM_LAST )
  5072. {
  5073. while ( nSavedPosCount <= nOffset )
  5074. pSavedPos[nSavedPosCount++].nSavedPosFlags &= ~SavedPos::SPM_USED;
  5075. break;
  5076. }
  5077. ++nOffset;
  5078. }
  5079. }
  5080. }
  5081. ++nMap;
  5082. }
  5083. }
  5084. }
  5085. void CMarkup::x_AdjustForNode( int iPosParent, int iPos, int nShift )
  5086. {
  5087. // Adjust affected indexes
  5088. bool bAfterPos = true;
  5089. if ( ! iPos )
  5090. {
  5091. // Change happened before or at first element under iPosParent
  5092. // If there are any children of iPosParent, adjust from there
  5093. // otherwise start at parent and adjust from there
  5094. iPos = ELEM(iPosParent).iElemChild;
  5095. if ( iPos )
  5096. {
  5097. ELEM(iPos).nStart += nShift;
  5098. bAfterPos = false;
  5099. }
  5100. else
  5101. {
  5102. iPos = iPosParent;
  5103. ELEM(iPos).nLength += nShift;
  5104. }
  5105. }
  5106. x_Adjust( iPos, nShift, bAfterPos );
  5107. }
  5108. bool CMarkup::x_AddNode( int nNodeType, MCD_PCSZ pText, int nNodeFlags )
  5109. {
  5110. if ( m_nDocFlags & MDF_READFILE )
  5111. return false;
  5112. // Comments, DTDs, and processing instructions are followed by CRLF
  5113. // Other nodes are usually concerned with mixed content, so no CRLF
  5114. if ( ! (nNodeType & (MNT_PROCESSING_INSTRUCTION|MNT_COMMENT|MNT_DOCUMENT_TYPE)) )
  5115. nNodeFlags |= MNF_WITHNOLINES;
  5116. // Add node of nNodeType after current node position
  5117. NodePos node( nNodeFlags );
  5118. if ( ! x_CreateNode(node.strMeta, nNodeType, pText) )
  5119. return false;
  5120. // Insert the new node relative to current node
  5121. node.nStart = m_nNodeOffset;
  5122. node.nLength = m_nNodeLength;
  5123. node.nNodeType = nNodeType;
  5124. int iPosBefore = m_iPos;
  5125. int nReplace = x_InsertNew( m_iPosParent, iPosBefore, node );
  5126. // If its a new element, create an ElemPos
  5127. int iPos = iPosBefore;
  5128. ElemPos* pElem = NULL;
  5129. if ( nNodeType == MNT_ELEMENT )
  5130. {
  5131. // Set indexes
  5132. iPos = x_GetFreePos();
  5133. pElem = &ELEM(iPos);
  5134. pElem->nStart = node.nStart;
  5135. pElem->SetStartTagLen( node.nLength );
  5136. pElem->SetEndTagLen( 0 );
  5137. pElem->nLength = node.nLength;
  5138. node.nStart = 0;
  5139. node.nLength = 0;
  5140. pElem->iElemChild = 0;
  5141. pElem->nFlags = 0;
  5142. x_LinkElem( m_iPosParent, iPosBefore, iPos );
  5143. }
  5144. if ( m_nDocFlags & MDF_WRITEFILE )
  5145. {
  5146. m_iPosParent = x_UnlinkPrevElem( m_iPosParent, iPosBefore, iPos );
  5147. if ( nNodeType == MNT_ELEMENT )
  5148. {
  5149. TokenPos token( m_strDoc, m_nDocFlags );
  5150. token.m_nL = pElem->nStart + 1;
  5151. token.m_nR = pElem->nStart + pElem->nLength - 3;
  5152. m_pFilePos->m_elemstack.PushTagAndCount( token );
  5153. }
  5154. }
  5155. else // need to adjust element positions after iPos
  5156. x_AdjustForNode( m_iPosParent, iPos, MCD_STRLENGTH(node.strMeta) - nReplace );
  5157. // Store current position
  5158. m_iPos = iPos;
  5159. m_iPosChild = 0;
  5160. m_nNodeOffset = node.nStart;
  5161. m_nNodeLength = node.nLength;
  5162. m_nNodeType = nNodeType;
  5163. MARKUP_SETDEBUGSTATE;
  5164. return true;
  5165. }
  5166. void CMarkup::x_RemoveNode( int iPosParent, int& iPos, int& nNodeType, int& nNodeOffset, int& nNodeLength )
  5167. {
  5168. int iPosPrev = iPos;
  5169. // Removing an element?
  5170. if ( nNodeType == MNT_ELEMENT )
  5171. {
  5172. nNodeOffset = ELEM(iPos).nStart;
  5173. nNodeLength = ELEM(iPos).nLength;
  5174. iPosPrev = x_UnlinkElem( iPos );
  5175. x_CheckSavedPos();
  5176. }
  5177. // Find previous node type, offset and length
  5178. int nPrevOffset = 0;
  5179. if ( iPosPrev )
  5180. nPrevOffset = ELEM(iPosPrev).StartAfter();
  5181. else if ( iPosParent )
  5182. nPrevOffset = ELEM(iPosParent).StartContent();
  5183. TokenPos token( m_strDoc, m_nDocFlags );
  5184. NodePos node;
  5185. token.m_nNext = nPrevOffset;
  5186. int nPrevType = 0;
  5187. while ( token.m_nNext < nNodeOffset )
  5188. {
  5189. nPrevOffset = token.m_nNext;
  5190. nPrevType = token.ParseNode( node );
  5191. }
  5192. int nPrevLength = nNodeOffset - nPrevOffset;
  5193. if ( ! nPrevLength )
  5194. {
  5195. // Previous node is iPosPrev element
  5196. nPrevOffset = 0;
  5197. if ( iPosPrev )
  5198. nPrevType = MNT_ELEMENT;
  5199. }
  5200. // Remove node from document
  5201. x_DocChange( nNodeOffset, nNodeLength, MCD_STR() );
  5202. x_AdjustForNode( iPosParent, iPosPrev, - nNodeLength );
  5203. // Was removed node a lone end tag?
  5204. if ( nNodeType == MNT_LONE_END_TAG )
  5205. {
  5206. // See if we can unset parent MNF_ILLDATA flag
  5207. token.m_nNext = ELEM(iPosParent).StartContent();
  5208. int nEndOfContent = token.m_nNext + ELEM(iPosParent).ContentLen();
  5209. int iPosChild = ELEM(iPosParent).iElemChild;
  5210. while ( token.m_nNext < nEndOfContent )
  5211. {
  5212. if ( token.ParseNode(node) <= 0 )
  5213. break;
  5214. if ( node.nNodeType == MNT_ELEMENT )
  5215. {
  5216. token.m_nNext = ELEM(iPosChild).StartAfter();
  5217. iPosChild = ELEM(iPosChild).iElemNext;
  5218. }
  5219. }
  5220. if ( token.m_nNext == nEndOfContent )
  5221. ELEM(iPosParent).nFlags &= ~MNF_ILLDATA;
  5222. }
  5223. nNodeType = nPrevType;
  5224. nNodeOffset = nPrevOffset;
  5225. nNodeLength = nPrevLength;
  5226. iPos = iPosPrev;
  5227. }