BasicExcelVC6.cpp 174 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892
  1. #include "stdafx.h"
  2. #include "BasicExcelVC6.h"
  3. namespace YCompoundFiles
  4. {
  5. /********************************** Start of Class Block *************************************/
  6. // PURPOSE: Manage a file by treating it as blocks of data of a certain size.
  7. Block::Block() :
  8. blockSize_(512), fileSize_(0), indexEnd_(0),
  9. filename_(0) {}
  10. bool Block::Create(const wchar_t* filename)
  11. // PURPOSE: Create a new block file and open it.
  12. // PURPOSE: If file is present, truncate it and then open it.
  13. // PROMISE: Return true if file is successfully created and opened, false if otherwise.
  14. {
  15. // Create new file
  16. size_t filenameLength = wcslen(filename);
  17. char* name = new char[filenameLength+1];
  18. wcstombs(name, filename, filenameLength);
  19. name[filenameLength] = 0;
  20. file_.open(name, ios_base::out | ios_base::trunc);
  21. file_.close();
  22. file_.clear();
  23. // Open the file
  24. bool ret = this->Open(filename);
  25. delete[] name;
  26. return ret;
  27. }
  28. bool Block::Open(const wchar_t* filename, ios_base::openmode mode)
  29. // PURPOSE: Open an existing block file.
  30. // PROMISE: Return true if file is successfully opened, false if otherwise.
  31. {
  32. // Open existing file for reading or writing or both
  33. size_t filenameLength = wcslen(filename);
  34. filename_.resize(filenameLength+1, 0);
  35. wcstombs(&*(filename_.begin()), filename, filenameLength);
  36. file_.open(&*(filename_.begin()), mode | ios_base::binary);
  37. if (!file_.is_open()) return false;
  38. mode_ = mode;
  39. // Calculate filesize
  40. if (mode & ios_base::in)
  41. {
  42. file_.seekg(0, ios_base::end);
  43. fileSize_ = file_.tellg();
  44. }
  45. else if (mode & ios_base::out)
  46. {
  47. file_.seekp(0, ios_base::end);
  48. fileSize_ = file_.tellp();
  49. }
  50. else
  51. {
  52. this->Close();
  53. return false;
  54. }
  55. // Calculate last index + 1
  56. indexEnd_ = fileSize_/blockSize_ + (fileSize_ % blockSize_ ? 1 : 0);
  57. return true;
  58. }
  59. bool Block::Close()
  60. // PURPOSE: Close the opened block file.
  61. // PROMISE: Return true if file is successfully closed, false if otherwise.
  62. {
  63. file_.close();
  64. file_.clear();
  65. filename_.clear();
  66. fileSize_ = 0;
  67. indexEnd_ = 0;
  68. blockSize_ = 512;
  69. return !file_.is_open();
  70. }
  71. bool Block::IsOpen()
  72. // PURPOSE: Check if the block file is still opened.
  73. // PROMISE: Return true if file is still opened, false if otherwise.
  74. {
  75. return file_.is_open();
  76. }
  77. bool Block::Read(size_t index, char* block)
  78. // PURPOSE: Read a block of data from the opened file at the index position.
  79. // EXPLAIN: index is from [0..].
  80. // PROMISE: Return true if data are successfully read, false if otherwise.
  81. {
  82. if (!(mode_ & ios_base::in)) return false;
  83. if (index < indexEnd_)
  84. {
  85. file_.seekg(index * blockSize_);
  86. file_.read(block, blockSize_);
  87. return !file_.fail();
  88. }
  89. else return false;
  90. }
  91. bool Block::Write(size_t index, const char* block)
  92. // PURPOSE: Write a block of data to the opened file at the index position.
  93. // EXPLAIN: index is from [0..].
  94. // PROMISE: Return true if data are successfully written, false if otherwise.
  95. {
  96. if (!(mode_ & ios_base::out)) return false;
  97. file_.seekp(index * blockSize_);
  98. file_.write(block, blockSize_);
  99. if (indexEnd_ <= index)
  100. {
  101. indexEnd_ = index + 1;
  102. fileSize_ += blockSize_;
  103. }
  104. file_.close();
  105. file_.clear();
  106. file_.open(&*(filename_.begin()), mode_ | ios_base::binary);
  107. return file_.is_open();
  108. }
  109. bool Block::Swap(size_t index1, size_t index2)
  110. // PURPOSE: Swap two blocks of data in the opened file at the index positions.
  111. // EXPLAIN: index1 and index2 are from [0..].
  112. // PROMISE: Return true if data are successfully swapped, false if otherwise.
  113. {
  114. if (!(mode_ & ios_base::out)) return false;
  115. if (index1 < indexEnd_ && index2 < indexEnd_)
  116. {
  117. if (index1 == index2) return true;
  118. char* block1 = new char[blockSize_];
  119. if (!this->Read(index1, block1)) return false;
  120. char* block2 = new char[blockSize_];
  121. if (!this->Read(index2, block2)) return false;
  122. if (!this->Write(index1, block2)) return false;
  123. if (!this->Write(index2, block1)) return false;
  124. delete[] block1;
  125. delete[] block2;
  126. return true;
  127. }
  128. else return false;
  129. }
  130. bool Block::Move(size_t from, size_t to)
  131. // PURPOSE: Move a block of data in the opened file from an index position to another index position.
  132. // EXPLAIN: from and to are from [0..].
  133. // PROMISE: Return true if data are successfully moved, false if otherwise.
  134. {
  135. if (!(mode_ & ios_base::out)) return false;
  136. if (from < indexEnd_ && to < indexEnd_)
  137. {
  138. if (to > from)
  139. {
  140. for (size_t i=from; i!=to; ++i)
  141. {
  142. if (!this->Swap(i, i+1)) return false;
  143. }
  144. }
  145. else
  146. {
  147. for (size_t i=from; i!=to; --i)
  148. {
  149. if (!this->Swap(i, i-1)) return false;
  150. }
  151. }
  152. return true;
  153. }
  154. else return false;
  155. }
  156. bool Block::Insert(size_t index, const char* block)
  157. // PURPOSE: Insert a new block of data in the opened file at the index position.
  158. // EXPLAIN: index is from [0..].
  159. // PROMISE: Return true if data are successfully inserted, false if otherwise.
  160. {
  161. if (!(mode_ & ios_base::out)) return false;
  162. if (index <= indexEnd_)
  163. {
  164. // Write block to end of file
  165. if (!this->Write(indexEnd_, block)) return false;
  166. // Move block to index if necessary
  167. if (index < indexEnd_-1) return this->Move(indexEnd_-1, index);
  168. else return true;
  169. }
  170. else
  171. {
  172. // Write block to index after end of file
  173. return this->Write(index, block);
  174. }
  175. }
  176. bool Block::Erase(size_t index)
  177. // PURPOSE: Erase a block of data in the opened file at the index position.
  178. // EXPLAIN: index is from [0..].
  179. // PROMISE: Return true if data are successfully erased, false if otherwise.
  180. {
  181. if (!(mode_ & ios_base::out)) return false;
  182. if (index < indexEnd_)
  183. {
  184. fileSize_ -= blockSize_;
  185. indexEnd_ -= 1;
  186. // Read entire file except the block to be deleted into memory.
  187. char* buffer = new char[fileSize_];
  188. for (size_t i=0, j=0; i!=indexEnd_+1; ++i)
  189. {
  190. file_.seekg(i*blockSize_);
  191. if (i != index)
  192. {
  193. file_.read(buffer+j*blockSize_, blockSize_);
  194. ++j;
  195. }
  196. }
  197. file_.close();
  198. file_.open(&*(filename_.begin()), ios_base::out | ios_base::trunc | ios_base::binary);
  199. file_.write(buffer, fileSize_); // Write the new file.
  200. file_.close();
  201. file_.open(&*(filename_.begin()), mode_ | ios_base::binary);
  202. delete[] buffer;
  203. return true;
  204. }
  205. else return false;
  206. }
  207. bool Block::Erase(vector<size_t>& indices)
  208. // PURPOSE: Erase blocks of data in the opened file at the index positions.
  209. // EXPLAIN: Each index in indices is from [0..].
  210. // PROMISE: Return true if data are successfully erased, false if otherwise.
  211. {
  212. if (!(mode_ & ios_base::out)) return false;
  213. // Read entire file except the blocks to be deleted into memory.
  214. size_t maxIndices = indices.size();
  215. fileSize_ -= maxIndices*blockSize_;
  216. char* buffer = new char[fileSize_];
  217. for (size_t i=0, k=0; i!=indexEnd_; ++i)
  218. {
  219. file_.seekg(i*blockSize_);
  220. bool toDelete = false;
  221. for (size_t j=0; j<maxIndices; ++j)
  222. {
  223. if (i == indices[j])
  224. {
  225. toDelete = true;
  226. break;
  227. }
  228. }
  229. if (!toDelete)
  230. {
  231. file_.read(buffer+k*blockSize_, blockSize_);
  232. ++k;
  233. }
  234. }
  235. indexEnd_ -= maxIndices;
  236. file_.close();
  237. file_.open(&*(filename_.begin()), ios_base::out | ios_base::trunc | ios_base::binary);
  238. file_.write(buffer, fileSize_); // Write the new file.
  239. file_.close();
  240. file_.open(&*(filename_.begin()), mode_ | ios_base::binary);
  241. delete[] buffer;
  242. return true;
  243. }
  244. /********************************** End of Class Block ***************************************/
  245. /********************************** Start of Class Header ************************************/
  246. // PURPOSE: Read and write data to a compound file header.
  247. CompoundFile::Header::Header() :
  248. fileType_(0xE11AB1A1E011CFD0),
  249. uk1_(0), uk2_(0), uk3_(0), uk4_(0), uk5_(0x003B), uk6_(0x0003), uk7_(-2),
  250. log2BigBlockSize_(9), log2SmallBlockSize_(6),
  251. uk8_(0), uk9_(0), uk10_(0), uk11_(0x00001000),
  252. SBATStart_(-2), SBATCount_(0),
  253. XBATStart_(-2), XBATCount_(0),
  254. BATCount_(1), propertiesStart_(1)
  255. {
  256. BATArray_[0] = 0; // Initial BAT indices at block 0 (=block 1 in Block)
  257. fill (BATArray_+1, BATArray_+109, -1); // Rest of the BATArray is empty
  258. Initialize();
  259. }
  260. void CompoundFile::Header::Write(char* block)
  261. // PURPOSE: Write header information into a block of data.
  262. // REQUIRE: Block of data must be at least 512 bytes in size.
  263. {
  264. LittleEndian::Write(block, fileType_, 0x0000, 8);
  265. LittleEndian::Write(block, uk1_, 0x0008, 4);
  266. LittleEndian::Write(block, uk2_, 0x000C, 4);
  267. LittleEndian::Write(block, uk3_, 0x0010, 4);
  268. LittleEndian::Write(block, uk4_, 0x0014, 4);
  269. LittleEndian::Write(block, uk5_, 0x0018, 2);
  270. LittleEndian::Write(block, uk6_, 0x001A, 2);
  271. LittleEndian::Write(block, uk7_, 0x001C, 2);
  272. LittleEndian::Write(block, log2BigBlockSize_, 0x001E, 2);
  273. LittleEndian::Write(block, log2SmallBlockSize_, 0x0020, 4);
  274. LittleEndian::Write(block, uk8_, 0x0024, 4);
  275. LittleEndian::Write(block, uk9_, 0x0028, 4);
  276. LittleEndian::Write(block, BATCount_, 0x002C, 4);
  277. LittleEndian::Write(block, propertiesStart_, 0x0030, 4);
  278. LittleEndian::Write(block, uk10_, 0x0034, 4);
  279. LittleEndian::Write(block, uk11_, 0x0038, 4);
  280. LittleEndian::Write(block, SBATStart_, 0x003C, 4);
  281. LittleEndian::Write(block, SBATCount_, 0x0040, 4);
  282. LittleEndian::Write(block, XBATStart_, 0x0044, 4);
  283. LittleEndian::Write(block, XBATCount_, 0x0048, 4);
  284. for (size_t i=0; i<109; ++i) LittleEndian::Write(block, BATArray_[i], 0x004C+i*4, 4);
  285. }
  286. void CompoundFile::Header::Read(char* block)
  287. // PURPOSE: Read header information from a block of data.
  288. // REQUIRE: Block of data must be at least 512 bytes in size.
  289. {
  290. LittleEndian::Read(block, fileType_, 0x0000, 8);
  291. LittleEndian::Read(block, uk1_, 0x0008, 4);
  292. LittleEndian::Read(block, uk2_, 0x000C, 4);
  293. LittleEndian::Read(block, uk3_, 0x0010, 4);
  294. LittleEndian::Read(block, uk4_, 0x0014, 4);
  295. LittleEndian::Read(block, uk5_, 0x0018, 2);
  296. LittleEndian::Read(block, uk6_, 0x001A, 2);
  297. LittleEndian::Read(block, uk7_, 0x001C, 2);
  298. LittleEndian::Read(block, log2BigBlockSize_, 0x001E, 2);
  299. LittleEndian::Read(block, log2SmallBlockSize_, 0x0020, 4);
  300. LittleEndian::Read(block, uk8_, 0x0024, 4);
  301. LittleEndian::Read(block, uk9_, 0x0028, 4);
  302. LittleEndian::Read(block, BATCount_, 0x002C, 4);
  303. LittleEndian::Read(block, propertiesStart_, 0x0030, 4);
  304. LittleEndian::Read(block, uk10_, 0x0034, 4);
  305. LittleEndian::Read(block, uk11_, 0x0038, 4);
  306. LittleEndian::Read(block, SBATStart_, 0x003C, 4);
  307. LittleEndian::Read(block, SBATCount_, 0x0040, 4);
  308. LittleEndian::Read(block, XBATStart_, 0x0044, 4);
  309. LittleEndian::Read(block, XBATCount_, 0x0048, 4);
  310. for (size_t i=0; i<109; ++i) LittleEndian::Read(block, BATArray_[i], 0x004C+i*4, 4);
  311. Initialize();
  312. }
  313. void CompoundFile::Header::Initialize()
  314. {
  315. bigBlockSize_ = (size_t)pow(2.0, log2BigBlockSize_); // Calculate each big block size.
  316. smallBlockSize_ = (size_t)pow(2.0, log2SmallBlockSize_); // Calculate each small block size.
  317. }
  318. /********************************** End of Class Header **************************************/
  319. /********************************** Start of Class Property **********************************/
  320. // PURPOSE: Read and write data to a compound file property.
  321. CompoundFile::Property::Property() :
  322. nameSize_(0),
  323. propertyType_(1), nodeColor_(1),
  324. previousProp_(-1), nextProp_(-1), childProp_(-1),
  325. uk1_(0), uk2_(0), uk3_(0), uk4_(0), uk5_(0),
  326. seconds1_(0), days1_(0), seconds2_(0), days2_(0),
  327. startBlock_(-2), size_(0)
  328. {
  329. fill (name_, name_+32, 0);
  330. }
  331. void CompoundFile::Property::Write(char* block)
  332. // PURPOSE: Write property information from a block of data.
  333. // REQUIRE: Block of data must be at least 128 bytes in size.
  334. {
  335. LittleEndian::WriteString(block, name_, 0x00, 32);
  336. LittleEndian::Write(block, nameSize_, 0x40, 2);
  337. LittleEndian::Write(block, propertyType_, 0x42, 1);
  338. LittleEndian::Write(block, nodeColor_, 0x43, 1);
  339. LittleEndian::Write(block, previousProp_, 0x44, 4);
  340. LittleEndian::Write(block, nextProp_, 0x48, 4);
  341. LittleEndian::Write(block, childProp_, 0x4C, 4);
  342. LittleEndian::Write(block, uk1_, 0x50, 4);
  343. LittleEndian::Write(block, uk2_, 0x54, 4);
  344. LittleEndian::Write(block, uk3_, 0x58, 4);
  345. LittleEndian::Write(block, uk4_, 0x5C, 4);
  346. LittleEndian::Write(block, uk5_, 0x60, 4);
  347. LittleEndian::Write(block, seconds1_, 0x64, 4);
  348. LittleEndian::Write(block, days1_, 0x68, 4);
  349. LittleEndian::Write(block, seconds2_, 0x6C, 4);
  350. LittleEndian::Write(block, days2_, 0x70, 4);
  351. LittleEndian::Write(block, startBlock_, 0x74, 4);
  352. LittleEndian::Write(block, size_, 0x78, 4);
  353. }
  354. void CompoundFile::Property::Read(char* block)
  355. // PURPOSE: Read property information from a block of data.
  356. // REQUIRE: Block of data must be at least 128 bytes in size.
  357. {
  358. LittleEndian::ReadString(block, name_, 0x00, 32);
  359. LittleEndian::Read(block, nameSize_, 0x40, 2);
  360. LittleEndian::Read(block, propertyType_, 0x42, 1);
  361. LittleEndian::Read(block, nodeColor_, 0x43, 1);
  362. LittleEndian::Read(block, previousProp_, 0x44, 4);
  363. LittleEndian::Read(block, nextProp_, 0x48, 4);
  364. LittleEndian::Read(block, childProp_, 0x4C, 4);
  365. LittleEndian::Read(block, uk1_, 0x50, 4);
  366. LittleEndian::Read(block, uk2_, 0x54, 4);
  367. LittleEndian::Read(block, uk3_, 0x58, 4);
  368. LittleEndian::Read(block, uk4_, 0x5C, 4);
  369. LittleEndian::Read(block, uk5_, 0x60, 4);
  370. LittleEndian::Read(block, seconds1_, 0x64, 4);
  371. LittleEndian::Read(block, days1_, 0x68, 4);
  372. LittleEndian::Read(block, seconds2_, 0x6C, 4);
  373. LittleEndian::Read(block, days2_, 0x70, 4);
  374. LittleEndian::Read(block, startBlock_, 0x74, 4);
  375. LittleEndian::Read(block, size_, 0x78, 4);
  376. }
  377. /********************************** End of Class Property ************************************/
  378. /********************************** Start of Class PropertyTree **********************************/
  379. CompoundFile::PropertyTree::PropertyTree() {};
  380. CompoundFile::PropertyTree::~PropertyTree()
  381. {
  382. size_t maxChildren = children_.size();
  383. for (size_t i=0; i<maxChildren; ++i) delete children_[i];
  384. }
  385. /********************************** End of Class PropertyTree ************************************/
  386. /********************************** Start of Class CompoundFile ******************************/
  387. // PURPOSE: Manage a compound file.
  388. CompoundFile::CompoundFile() :
  389. block_(512), properties_(0), propertyTrees_(0),
  390. blocksIndices_(0), sblocksIndices_(0) {};
  391. CompoundFile::~CompoundFile() {this->Close();}
  392. /************************* Compound File Functions ***************************/
  393. bool CompoundFile::Create(const wchar_t* filename)
  394. // PURPOSE: Create a new compound file and open it.
  395. // PURPOSE: If file is present, truncate it and then open it.
  396. // PROMISE: Return true if file is successfully created and opened, false if otherwise.
  397. {
  398. Close();
  399. file_.Create(filename);
  400. // Write compound file header
  401. header_ = Header();
  402. SaveHeader();
  403. // Save BAT
  404. blocksIndices_.clear();
  405. blocksIndices_.resize(128, -1);
  406. blocksIndices_[0] = -3;
  407. blocksIndices_[1] = -2;
  408. SaveBAT();
  409. // Save properties
  410. Property* root = new Property;
  411. wcscpy(root->name_, L"Root Entry");
  412. root->propertyType_ = 5;
  413. properties_.push_back(root);
  414. SaveProperties();
  415. // Set property tree
  416. propertyTrees_ = new PropertyTree;
  417. propertyTrees_->parent_ = 0;
  418. propertyTrees_->self_ = properties_[0];
  419. propertyTrees_->index_ = 0;
  420. currentDirectory_ = propertyTrees_;
  421. return true;
  422. }
  423. bool CompoundFile::Open(const wchar_t* filename, ios_base::openmode mode)
  424. // PURPOSE: Open an existing compound file.
  425. // PROMISE: Return true if file is successfully opened, false if otherwise.
  426. {
  427. Close();
  428. if (!file_.Open(filename, mode)) return false;
  429. // Load header
  430. if (!LoadHeader()) return false;
  431. // Load BAT information
  432. LoadBAT();
  433. // Load properties
  434. propertyTrees_ = new PropertyTree;
  435. LoadProperties();
  436. currentDirectory_ = propertyTrees_;
  437. return true;
  438. }
  439. bool CompoundFile::Close()
  440. // PURPOSE: Close the opened compound file.
  441. // PURPOSE: Reset BAT indices, SBAT indices, properties and properties tree information.
  442. // PROMISE: Return true if file is successfully closed, false if otherwise.
  443. {
  444. blocksIndices_.clear();
  445. sblocksIndices_.clear();
  446. size_t maxProperties = properties_.size();
  447. for (size_t i=0; i<maxProperties; ++i)
  448. {
  449. if (properties_[i]) delete properties_[i];
  450. }
  451. properties_.clear();
  452. if (propertyTrees_)
  453. {
  454. delete propertyTrees_;
  455. propertyTrees_ = 0;
  456. }
  457. previousDirectories_.clear();
  458. currentDirectory_ = 0;
  459. return file_.Close();
  460. }
  461. bool CompoundFile::IsOpen()
  462. // PURPOSE: Check if the compound file is still opened.
  463. // PROMISE: Return true if file is still opened, false if otherwise.
  464. {
  465. return file_.IsOpen();
  466. }
  467. /************************* Directory Functions ***************************/
  468. int CompoundFile::ChangeDirectory(const wchar_t* path)
  469. // PURPOSE: Change to a different directory in the compound file.
  470. // PROMISE: Current directory will not be changed if directory is not present.
  471. {
  472. previousDirectories_.push_back(currentDirectory_);
  473. // Handle special cases
  474. if (wcscmp(path, L".") == 0)
  475. {
  476. // Current directory
  477. previousDirectories_.pop_back();
  478. return SUCCESS;
  479. }
  480. if (wcscmp(path, L"..") == 0)
  481. {
  482. // Go up 1 directory
  483. if (currentDirectory_->parent_ != 0)
  484. {
  485. currentDirectory_ = currentDirectory_->parent_;
  486. }
  487. previousDirectories_.pop_back();
  488. return SUCCESS;
  489. }
  490. if (wcscmp(path, L"\\") == 0)
  491. {
  492. // Go to root directory
  493. currentDirectory_ = propertyTrees_;
  494. previousDirectories_.pop_back();
  495. return SUCCESS;
  496. }
  497. // Handle normal cases
  498. size_t ipos = 0;
  499. size_t npos = 0;
  500. size_t pathLength = wcslen(path);
  501. if (pathLength > 0 && path[0] == L'\\')
  502. {
  503. // Start from root directory
  504. currentDirectory_ = propertyTrees_;
  505. ++ipos;
  506. ++npos;
  507. }
  508. do
  509. {
  510. for (; npos<pathLength; ++npos)
  511. {
  512. if (path[npos] == L'\\') break;
  513. }
  514. wchar_t* directory = new wchar_t[npos-ipos+1];
  515. copy (path+ipos, path+npos, directory);
  516. directory[npos-ipos] = 0;
  517. currentDirectory_ = FindProperty(currentDirectory_, directory);
  518. delete[] directory;
  519. ipos = npos + 1;
  520. npos = ipos;
  521. if (currentDirectory_ == 0)
  522. {
  523. // Directory not found
  524. currentDirectory_ = previousDirectories_.back();
  525. previousDirectories_.pop_back();
  526. return DIRECTORY_NOT_FOUND;
  527. }
  528. } while (npos < pathLength);
  529. previousDirectories_.pop_back();
  530. return SUCCESS;
  531. }
  532. int CompoundFile::MakeDirectory(const wchar_t* path)
  533. // PURPOSE: Create a new directory in the compound file.
  534. // PROMISE: Directory will not be created if it is already present or
  535. // PROMISE: a file with the same name is present.
  536. {
  537. previousDirectories_.push_back(currentDirectory_);
  538. Property* property = new Property;
  539. property->propertyType_ = 1;
  540. int ret = MakeProperty(path, property);
  541. currentDirectory_ = previousDirectories_.back();
  542. previousDirectories_.pop_back();
  543. SaveHeader();
  544. SaveBAT();
  545. SaveProperties();
  546. return ret;
  547. }
  548. int CompoundFile::PresentWorkingDirectory(wchar_t* path)
  549. // PURPOSE: Get the full path of the current directory in the compound file.
  550. // REQUIRE: path must be large enough to receive the full path information.
  551. {
  552. previousDirectories_.push_back(currentDirectory_);
  553. vector<wchar_t> fullpath;
  554. do
  555. {
  556. size_t directoryLength = wcslen(currentDirectory_->self_->name_);
  557. vector<wchar_t> directory(directoryLength+1);
  558. directory[0] = L'\\';
  559. copy (currentDirectory_->self_->name_,
  560. currentDirectory_->self_->name_+directoryLength,
  561. directory.begin()+1);
  562. fullpath.insert(fullpath.begin(), directory.begin(), directory.end());
  563. } while (currentDirectory_ = currentDirectory_->parent_);
  564. fullpath.erase(fullpath.begin(), fullpath.begin()+11);
  565. if (fullpath.empty()) fullpath.push_back(L'\\');
  566. copy (fullpath.begin(), fullpath.end(), path);
  567. path[fullpath.size()] = 0;
  568. currentDirectory_ = previousDirectories_.back();
  569. previousDirectories_.pop_back();
  570. return SUCCESS;
  571. }
  572. int CompoundFile::PresentWorkingDirectory(vector<wchar_t>& path)
  573. // PURPOSE: Get the full path of the current directory in the compound file.
  574. {
  575. previousDirectories_.push_back(currentDirectory_);
  576. path.clear();
  577. do
  578. {
  579. size_t directoryLength = wcslen(currentDirectory_->self_->name_);
  580. vector<wchar_t> directory(directoryLength+1);
  581. directory[0] = L'\\';
  582. copy (currentDirectory_->self_->name_,
  583. currentDirectory_->self_->name_+directoryLength,
  584. directory.begin()+1);
  585. path.insert(path.begin(), directory.begin(), directory.end());
  586. } while (currentDirectory_ = currentDirectory_->parent_);
  587. path.erase(path.begin(), path.begin()+11);
  588. if (path.empty()) path.push_back(L'\\');
  589. currentDirectory_ = previousDirectories_.back();
  590. previousDirectories_.pop_back();
  591. return SUCCESS;
  592. }
  593. int CompoundFile::RemoveDirectory(const wchar_t* path)
  594. // PURPOSE: Remove a directory in the compound file.
  595. // PROMISE: Directory will not be removed if it has subdirectories or files under it.
  596. {
  597. PropertyTree* directory = FindProperty(path);
  598. if (directory == 0) return DIRECTORY_NOT_FOUND;
  599. if (directory->self_->childProp_ != -1) return DIRECTORY_NOT_EMPTY;
  600. DeletePropertyTree(directory);
  601. SaveHeader();
  602. SaveBAT();
  603. SaveProperties();
  604. return SUCCESS;
  605. }
  606. int CompoundFile::DelTree(const wchar_t* path)
  607. // PURPOSE: Remove everything in the path in the compound file, including
  608. // PURPOSE: any files and subdirectories.
  609. {
  610. previousDirectories_.push_back(currentDirectory_);
  611. PropertyTree* directory = FindProperty(path);
  612. if (directory == 0) return DIRECTORY_NOT_FOUND;
  613. if (directory->self_->childProp_ != -1)
  614. {
  615. size_t maxChildren = directory->children_.size();
  616. wchar_t* curpath = new wchar_t[65535];
  617. for (size_t i=0; i<maxChildren; ++i)
  618. {
  619. currentDirectory_ = directory->children_[i];
  620. PresentWorkingDirectory(curpath);
  621. if (directory->children_[i]->self_->propertyType_ == 1)
  622. {
  623. // Directory
  624. DelTree(curpath);
  625. }
  626. else if (directory->children_[i]->self_->propertyType_ == 2)
  627. {
  628. // File
  629. RemoveFile(curpath);
  630. }
  631. }
  632. directory->self_->childProp_ = -1;
  633. delete[] curpath;
  634. }
  635. if (directory->self_->propertyType_ == 1)
  636. {
  637. // Directory
  638. RemoveDirectory(path);
  639. }
  640. else if (directory->self_->propertyType_ == 2)
  641. {
  642. // File
  643. RemoveFile(path);
  644. }
  645. currentDirectory_ = previousDirectories_.back();
  646. previousDirectories_.pop_back();
  647. return SUCCESS;
  648. }
  649. int CompoundFile::DirectoryList(vector<vector<wchar_t> >& list, const wchar_t* path)
  650. {
  651. previousDirectories_.push_back(currentDirectory_);
  652. if (path != 0)
  653. {
  654. int ret = ChangeDirectory(path);
  655. if (ret != SUCCESS) return ret;
  656. }
  657. list.clear();
  658. size_t maxChildren = currentDirectory_->children_.size();
  659. vector<wchar_t> name(32);
  660. for (size_t i=0; i<maxChildren; ++i)
  661. {
  662. wcscpy(&*(name.begin()), currentDirectory_->children_[i]->self_->name_);
  663. list.push_back(name);
  664. }
  665. currentDirectory_ = previousDirectories_.back();
  666. previousDirectories_.pop_back();
  667. return SUCCESS;
  668. }
  669. /************************* File Functions ***************************/
  670. int CompoundFile::MakeFile(const wchar_t* path)
  671. // PURPOSE: Create a new file in the compound file.
  672. // PROMISE: File will not be created if it is already present or
  673. // PROMISE: a directory with the same name is present.
  674. {
  675. previousDirectories_.push_back(currentDirectory_);
  676. Property* property = new Property;
  677. property->propertyType_ = 2;
  678. int ret = MakeProperty(path, property);
  679. currentDirectory_ = previousDirectories_.back();
  680. previousDirectories_.pop_back();
  681. SaveHeader();
  682. SaveBAT();
  683. SaveProperties();
  684. return ret;
  685. }
  686. int CompoundFile::RemoveFile(const wchar_t* path)
  687. // PURPOSE: Remove a file in the compound file.
  688. {
  689. int ret = WriteFile(path, 0, 0);
  690. if (ret == SUCCESS)
  691. {
  692. DeletePropertyTree(FindProperty(path));
  693. SaveHeader();
  694. SaveBAT();
  695. SaveProperties();
  696. return SUCCESS;
  697. }
  698. else return ret;
  699. }
  700. int CompoundFile::FileSize(const wchar_t* path, size_t& size)
  701. // PURPOSE: Get the size of a file in the compound file.
  702. // PROMISE: Return the data size stored in the Root Entry if path = "\".
  703. // PROMISE: size will not be set if file is not present in the compound file.
  704. {
  705. // Special case of reading root entry
  706. if (wcscmp(path, L"\\") == 0)
  707. {
  708. size = propertyTrees_->self_->size_;
  709. return SUCCESS;
  710. }
  711. // Check to see if file is present in the specified directory.
  712. PropertyTree* property = FindProperty(path);
  713. if (property == 0) return FILE_NOT_FOUND;
  714. else
  715. {
  716. size = property->self_->size_;
  717. return SUCCESS;
  718. }
  719. }
  720. int CompoundFile::ReadFile(const wchar_t* path, char* data)
  721. // PURPOSE: Read a file's data in the compound file.
  722. // REQUIRE: data must be large enough to receive the file's data.
  723. // REQUIRE: The required data size can be obtained by using FileSize().
  724. // PROMISE: Returns the small blocks of data stored by the Root Entry if path = "\".
  725. // PROMISE: data will not be set if file is not present in the compound file.
  726. {
  727. // Special case of reading root entry
  728. char* buffer;
  729. if (wcscmp(path, L"\\") == 0)
  730. {
  731. buffer = new char[DataSize(propertyTrees_->self_->startBlock_, true)];
  732. ReadData(propertyTrees_->self_->startBlock_, buffer, true);
  733. copy (buffer, buffer+propertyTrees_->self_->size_, data);
  734. delete[] buffer;
  735. return SUCCESS;
  736. }
  737. // Check to see if file is present in the specified directory.
  738. PropertyTree* property = FindProperty(path);
  739. if (property == 0) return FILE_NOT_FOUND;
  740. if (property->self_->size_ >= 4096)
  741. {
  742. // Data stored in normal big blocks
  743. buffer = new char[DataSize(property->self_->startBlock_, true)];
  744. ReadData(property->self_->startBlock_, buffer, true);
  745. }
  746. else
  747. {
  748. // Data stored in small blocks
  749. buffer = new char[DataSize(property->self_->startBlock_, false)];
  750. ReadData(property->self_->startBlock_, buffer, false);
  751. }
  752. // Truncated the retrieved data to the actual file size.
  753. copy (buffer, buffer+property->self_->size_, data);
  754. delete[] buffer;
  755. return SUCCESS;
  756. }
  757. int CompoundFile::ReadFile(const wchar_t* path, vector<char>& data)
  758. // PURPOSE: Read a file's data in the compound file.
  759. // PROMISE: Returns the small blocks of data stored by the Root Entry if path = "\".
  760. // PROMISE: data will not be set if file is not present in the compound file.
  761. {
  762. data.clear();
  763. size_t dataSize;
  764. int ret = FileSize(path, dataSize);
  765. if (ret != SUCCESS) return ret;
  766. data.resize(dataSize);
  767. return ReadFile(path, &*(data.begin()));
  768. }
  769. int CompoundFile::WriteFile(const wchar_t* path, const char* data, size_t size)
  770. // PURPOSE: Write data to a file in the compound file.
  771. // PROMISE: The file's original data will be replaced by the new data.
  772. {
  773. PropertyTree* property = FindProperty(path);
  774. if (property == 0) return FILE_NOT_FOUND;
  775. if (property->self_->size_ >= 4096)
  776. {
  777. if (size >= 4096) property->self_->startBlock_ = WriteData(data, size, property->self_->startBlock_, true);
  778. else
  779. {
  780. property->self_->startBlock_ = WriteData(0, 0, property->self_->startBlock_, true);
  781. property->self_->startBlock_ = WriteData(data, size, property->self_->startBlock_, false);
  782. }
  783. }
  784. else
  785. {
  786. if (size < 4096) property->self_->startBlock_ = WriteData(data, size, property->self_->startBlock_, false);
  787. else
  788. {
  789. property->self_->startBlock_ = WriteData(0, 0, property->self_->startBlock_, false);
  790. property->self_->startBlock_ = WriteData(data, size, property->self_->startBlock_, true);
  791. }
  792. }
  793. property->self_->size_ = size;
  794. SaveHeader();
  795. SaveBAT();
  796. SaveProperties();
  797. return SUCCESS;
  798. }
  799. int CompoundFile::WriteFile(const wchar_t* path, const vector<char>& data, size_t size)
  800. // PURPOSE: Write data to a file in the compound file.
  801. // PROMISE: The file's original data will be replaced by the new data.
  802. {
  803. return WriteFile(path, &*(data.begin()), size);
  804. }
  805. /*************ANSI char compound file, directory and file functions******************/
  806. bool CompoundFile::Create(const char* filename)
  807. {
  808. size_t filenameLength = strlen(filename);
  809. wchar_t* wname = new wchar_t[filenameLength+1];
  810. mbstowcs(wname, filename, filenameLength);
  811. wname[filenameLength] = 0;
  812. bool ret = Create(wname);
  813. delete[] wname;
  814. return ret;
  815. }
  816. bool CompoundFile::Open(const char* filename, ios_base::openmode mode)
  817. {
  818. size_t filenameLength = strlen(filename);
  819. wchar_t* wname = new wchar_t[filenameLength+1];
  820. mbstowcs(wname, filename, filenameLength);
  821. wname[filenameLength] = 0;
  822. bool ret = Open(wname, mode);
  823. delete[] wname;
  824. return ret;
  825. }
  826. int CompoundFile::ChangeDirectory(const char* path)
  827. {
  828. size_t pathLength = strlen(path);
  829. wchar_t* wpath = new wchar_t[pathLength+1];
  830. mbstowcs(wpath, path, pathLength);
  831. wpath[pathLength] = 0;
  832. int ret = ChangeDirectory(wpath);
  833. delete[] wpath;
  834. return ret;
  835. }
  836. int CompoundFile::MakeDirectory(const char* path)
  837. {
  838. size_t pathLength = strlen(path);
  839. wchar_t* wpath = new wchar_t[pathLength+1];
  840. mbstowcs(wpath, path, pathLength);
  841. wpath[pathLength] = 0;
  842. int ret = MakeDirectory(wpath);
  843. delete[] wpath;
  844. return ret;
  845. }
  846. int CompoundFile::PresentWorkingDirectory(char* path)
  847. {
  848. size_t pathLength = strlen(path);
  849. wchar_t* wpath = new wchar_t[pathLength+1];
  850. int ret = PresentWorkingDirectory(wpath);
  851. if (ret == SUCCESS)
  852. {
  853. pathLength = wcslen(wpath);
  854. wcstombs(path, wpath, pathLength);
  855. path[pathLength] = 0;
  856. }
  857. delete[] wpath;
  858. return ret;
  859. }
  860. int CompoundFile::PresentWorkingDirectory(vector<char>& path)
  861. {
  862. vector<wchar_t> wpath;
  863. int ret = PresentWorkingDirectory(wpath);
  864. if (ret == SUCCESS)
  865. {
  866. size_t pathLength = wpath.size();
  867. path.resize(pathLength);
  868. wcstombs(&*(path.begin()), &*(wpath.begin()), pathLength);
  869. path[pathLength] = 0;
  870. }
  871. return ret;
  872. }
  873. int CompoundFile::RemoveDirectory(const char* path)
  874. {
  875. size_t pathLength = strlen(path);
  876. wchar_t* wpath = new wchar_t[pathLength+1];
  877. mbstowcs(wpath, path, pathLength);
  878. wpath[pathLength] = 0;
  879. int ret = RemoveDirectory(wpath);
  880. delete[] wpath;
  881. return ret;
  882. }
  883. int CompoundFile::DelTree(const char* path)
  884. {
  885. size_t pathLength = strlen(path);
  886. wchar_t* wpath = new wchar_t[pathLength+1];
  887. mbstowcs(wpath, path, pathLength);
  888. wpath[pathLength] = 0;
  889. int ret = DelTree(wpath);
  890. delete[] wpath;
  891. return ret;
  892. }
  893. int CompoundFile::MakeFile(const char* path)
  894. {
  895. size_t pathLength = strlen(path);
  896. wchar_t* wpath = new wchar_t[pathLength+1];
  897. mbstowcs(wpath, path, pathLength);
  898. wpath[pathLength] = 0;
  899. int ret = MakeFile(wpath);
  900. delete[] wpath;
  901. return ret;
  902. }
  903. int CompoundFile::RemoveFile(const char* path)
  904. {
  905. size_t pathLength = strlen(path);
  906. wchar_t* wpath = new wchar_t[pathLength+1];
  907. mbstowcs(wpath, path, pathLength);
  908. wpath[pathLength] = 0;
  909. int ret = RemoveFile(wpath);
  910. delete[] wpath;
  911. return ret;
  912. }
  913. int CompoundFile::FileSize(const char* path, size_t& size)
  914. {
  915. size_t pathLength = strlen(path);
  916. wchar_t* wpath = new wchar_t[pathLength+1];
  917. mbstowcs(wpath, path, pathLength);
  918. wpath[pathLength] = 0;
  919. int ret = FileSize(wpath, size);
  920. delete[] wpath;
  921. return ret;
  922. }
  923. int CompoundFile::ReadFile(const char* path, char* data)
  924. {
  925. size_t pathLength = strlen(path);
  926. wchar_t* wpath = new wchar_t[pathLength+1];
  927. mbstowcs(wpath, path, pathLength);
  928. wpath[pathLength] = 0;
  929. int ret = ReadFile(wpath, data);
  930. delete[] wpath;
  931. return ret;
  932. }
  933. int CompoundFile::ReadFile(const char* path, vector<char>& data)
  934. {
  935. size_t pathLength = strlen(path);
  936. wchar_t* wpath = new wchar_t[pathLength+1];
  937. mbstowcs(wpath, path, pathLength);
  938. wpath[pathLength] = 0;
  939. int ret = ReadFile(wpath, data);
  940. delete[] wpath;
  941. return ret;
  942. }
  943. int CompoundFile::WriteFile(const char* path, char* data, size_t size)
  944. {
  945. size_t pathLength = strlen(path);
  946. wchar_t* wpath = new wchar_t[pathLength+1];
  947. mbstowcs(wpath, path, pathLength);
  948. wpath[pathLength] = 0;
  949. int ret = WriteFile(wpath, data, size);
  950. delete[] wpath;
  951. return ret;
  952. }
  953. int CompoundFile::WriteFile(const char* path, vector<char>& data, size_t size)
  954. {
  955. size_t pathLength = strlen(path);
  956. wchar_t* wpath = new wchar_t[pathLength+1];
  957. mbstowcs(wpath, path, pathLength);
  958. wpath[pathLength] = 0;
  959. int ret = WriteFile(wpath, data, size);
  960. delete[] wpath;
  961. return ret;
  962. }
  963. /*********************** Inaccessible General Functions ***************************/
  964. void CompoundFile::IncreaseLocationReferences(vector<size_t> indices)
  965. // PURPOSE: Increase block location references in header, BAT indices and properties,
  966. // PURPOSE: which will be affected by the insertion of new indices contained in indices.
  967. // PROMISE: Block location references which are smaller than all the new indices
  968. // PROMISE: will not be affected.
  969. // PROMISE: SBAT location references will not be affected.
  970. // PROMISE: Changes will not be written to compound file.
  971. {
  972. size_t maxIndices = indices.size();
  973. // Change BAT Array references
  974. {for (size_t i=0; i<109 && header_.BATArray_[i]!=-1; ++i)
  975. {
  976. size_t count = 0;
  977. for (size_t j=0; j<maxIndices; ++j)
  978. {
  979. if (header_.BATArray_[i] >= indices[j] &&
  980. header_.BATArray_[i] != -1) ++count;
  981. }
  982. header_.BATArray_[i] += count;
  983. }}
  984. // Change XBAT start block if any
  985. if (header_.XBATCount_)
  986. {
  987. size_t count = 0;
  988. for (size_t j=0; j<maxIndices; ++j)
  989. {
  990. if (header_.XBATStart_ >= indices[j] &&
  991. header_.XBATStart_ != -2) ++count;
  992. }
  993. header_.XBATStart_ += count;
  994. }
  995. // Change SBAT start block if any
  996. if (header_.SBATCount_)
  997. {
  998. size_t count = 0;
  999. for (size_t j=0; j<maxIndices; ++j)
  1000. {
  1001. if (header_.SBATStart_ >= indices[j] &&
  1002. header_.SBATStart_ != -2) ++count;
  1003. }
  1004. header_.SBATStart_ += count;
  1005. }
  1006. // Change BAT block indices
  1007. size_t maxBATindices = blocksIndices_.size();
  1008. {for (size_t i=0; i<maxBATindices && blocksIndices_[i]!=-1; ++i)
  1009. {
  1010. size_t count = 0;
  1011. for (size_t j=0; j<maxIndices; ++j)
  1012. {
  1013. if (blocksIndices_[i] > indices[j] &&
  1014. blocksIndices_[i] != -2 &&
  1015. blocksIndices_[i] != -3) ++count;
  1016. }
  1017. blocksIndices_[i] += count;
  1018. }}
  1019. // Change properties start block
  1020. size_t count = 0;
  1021. {for (size_t i=0; i<maxIndices; ++i)
  1022. {
  1023. if (header_.propertiesStart_ >= indices[i] &&
  1024. header_.propertiesStart_ != -2) ++count;
  1025. }}
  1026. header_.propertiesStart_ += count;
  1027. // Change individual properties start block if their size is more than 4096
  1028. size_t maxProperties = properties_.size();
  1029. if (!properties_.empty())
  1030. {
  1031. size_t count = 0;
  1032. for (size_t j=0; j<maxIndices; ++j)
  1033. {
  1034. if (properties_[0]->startBlock_ >= indices[j] &&
  1035. properties_[0]->startBlock_ != -2) ++count;
  1036. }
  1037. properties_[0]->startBlock_ += count;
  1038. }
  1039. {for (size_t i=1; i<maxProperties; ++i)
  1040. {
  1041. if (properties_[i]->size_ >= 4096)
  1042. {
  1043. size_t count = 0;
  1044. for (size_t j=0; j<maxIndices; ++j)
  1045. {
  1046. if (properties_[i]->startBlock_ >= indices[j] &&
  1047. properties_[i]->startBlock_ != -2) ++count;
  1048. }
  1049. properties_[i]->startBlock_ += count;
  1050. }
  1051. }}
  1052. }
  1053. void CompoundFile::DecreaseLocationReferences(vector<size_t> indices)
  1054. // PURPOSE: Decrease block location references in header, BAT indices and properties,
  1055. // PURPOSE: which will be affected by the deletion of indices contained in indices.
  1056. // PROMISE: BAT indices pointing to a deleted index will be redirected to point to
  1057. // PROMISE: the location where the deleted index original points to.
  1058. // PROMISE: Block location references which are smaller than all the new indices
  1059. // PROMISE: will not be affected.
  1060. // PROMISE: SBAT location references will not be affected.
  1061. // PROMISE: Changes will not be written to compound file.
  1062. {
  1063. size_t maxIndices = indices.size();
  1064. // Change BAT Array references
  1065. {for (size_t i=0; i<109 && header_.BATArray_[i]!=-1; ++i)
  1066. {
  1067. size_t count = 0;
  1068. for (size_t j=0; j<maxIndices; ++j)
  1069. {
  1070. if (header_.BATArray_[i] > indices[j] &&
  1071. header_.BATArray_[i] != -1) ++count;
  1072. }
  1073. header_.BATArray_[i] -= count;
  1074. }}
  1075. // Change XBAT start block if any
  1076. if (header_.XBATCount_)
  1077. {
  1078. size_t count = 0;
  1079. for (size_t j=0; j<maxIndices; ++j)
  1080. {
  1081. if (header_.XBATStart_ > indices[j] &&
  1082. header_.XBATStart_ != -2) ++count;
  1083. }
  1084. header_.XBATStart_ -= count;
  1085. }
  1086. // Change SBAT start block if any
  1087. if (header_.SBATCount_)
  1088. {
  1089. size_t count = 0;
  1090. for (size_t j=0; j<maxIndices; ++j)
  1091. {
  1092. if (header_.SBATStart_ > indices[j] &&
  1093. header_.SBATStart_ != -2) ++count;
  1094. }
  1095. header_.SBATStart_ -= count;
  1096. }
  1097. // Change BAT block indices
  1098. // Redirect BAT indices pointing to a deleted index to point to
  1099. // the location where the deleted index original points to.
  1100. size_t maxBATindices = blocksIndices_.size();
  1101. {for (size_t i=0; i<maxBATindices && blocksIndices_[i]!=-1; ++i)
  1102. {
  1103. bool end;
  1104. do
  1105. {
  1106. end = true;
  1107. for (size_t j=0; j<maxIndices; ++j)
  1108. {
  1109. if (blocksIndices_[i] == indices[j])
  1110. {
  1111. blocksIndices_[i] = blocksIndices_[indices[j]];
  1112. end = false;
  1113. break;
  1114. }
  1115. }
  1116. } while (!end);
  1117. }}
  1118. // Erase indices to be deleted from the block indices
  1119. sort (indices.begin(), indices.end(), greater<size_t>());
  1120. {for (size_t i=0; i<maxIndices; ++i)
  1121. {
  1122. blocksIndices_.erase(blocksIndices_.begin()+indices[i]);
  1123. blocksIndices_.push_back(-1);
  1124. }}
  1125. // Decrease block location references for affected block indices.
  1126. {for (size_t i=0; i<maxBATindices && blocksIndices_[i]!=-1; ++i)
  1127. {
  1128. size_t count = 0;
  1129. for (size_t j=0; j<maxIndices; ++j)
  1130. {
  1131. if (blocksIndices_[i] > indices[j] &&
  1132. blocksIndices_[i] != -2 &&
  1133. blocksIndices_[i] != -3) ++count;
  1134. }
  1135. blocksIndices_[i] -= count;
  1136. }}
  1137. // Change properties start block
  1138. size_t count = 0;
  1139. {for (size_t i=0; i<maxIndices; ++i)
  1140. {
  1141. if (header_.propertiesStart_ > indices[i] &&
  1142. header_.propertiesStart_ != -2) ++count;
  1143. }}
  1144. header_.propertiesStart_ -= count;
  1145. size_t maxProperties = properties_.size();
  1146. // Change Root Entry start block
  1147. if (!properties_.empty())
  1148. {
  1149. size_t count = 0;
  1150. for (size_t j=0; j<maxIndices; ++j)
  1151. {
  1152. if (properties_[0]->startBlock_ > indices[j] &&
  1153. properties_[0]->startBlock_ != -2) ++count;
  1154. }
  1155. properties_[0]->startBlock_ -= count;
  1156. }
  1157. {for (size_t i=1; i<maxProperties; ++i)
  1158. {
  1159. if (properties_[i]->size_ >= 4096)
  1160. {
  1161. // Change individual properties start block if their size is more than 4096
  1162. size_t count = 0;
  1163. for (size_t j=0; j<maxIndices; ++j)
  1164. {
  1165. if (properties_[i]->startBlock_ > indices[j] &&
  1166. properties_[i]->startBlock_ != -2) ++count;
  1167. }
  1168. properties_[i]->startBlock_ -= count;
  1169. }
  1170. }}
  1171. }
  1172. void CompoundFile::SplitPath(const wchar_t* path,
  1173. wchar_t*& parentpath,
  1174. wchar_t*& propertyname)
  1175. // PURPOSE: Get a path's parent path and its name.
  1176. // EXPLAIN: E.g. path = "\\Abc\\def\\ghi => parentpath = "\\Abc\\def", propertyname = "ghi".
  1177. // REQUIRE: Calling function is responsible for deleting the memory created for
  1178. // REQUIRE: parentpath and propertyname.
  1179. {
  1180. size_t pathLength = wcslen(path);
  1181. int npos;
  1182. for (npos=pathLength-1; npos>0; --npos)
  1183. {
  1184. if (path[npos] == L'\\') break;
  1185. }
  1186. if (npos != 0)
  1187. {
  1188. // Get parent path if available
  1189. parentpath = new wchar_t[npos+1];
  1190. copy (path, path+npos, parentpath);
  1191. parentpath[npos] = 0;
  1192. ++npos;
  1193. }
  1194. // Get property name (ignore initial "\" if present)
  1195. if (npos==0 && pathLength > 0 && path[0] == L'\\') ++npos;
  1196. propertyname = new wchar_t[pathLength-npos+1];
  1197. copy (path+npos, path+pathLength, propertyname);
  1198. propertyname[pathLength-npos] = 0;
  1199. }
  1200. /*********************** Inaccessible Header Functions ***************************/
  1201. bool CompoundFile::LoadHeader()
  1202. // PURPOSE: Load header information for compound file.
  1203. // PROMISE: Return true if file header contain magic number, false if otherwise.
  1204. {
  1205. file_.Read(0, &*(block_.begin()));
  1206. header_.Read(&*(block_.begin()));
  1207. // Check magic number to see if it is a compound file
  1208. if (header_.fileType_ != 0xE11AB1A1E011CFD0) return false;
  1209. block_.resize(header_.bigBlockSize_); // Resize buffer block
  1210. file_.SetBlockSize(header_.bigBlockSize_); // Resize block array block size
  1211. return true;
  1212. }
  1213. void CompoundFile::SaveHeader()
  1214. // PURPOSE: Save header information for compound file.
  1215. {
  1216. header_.Write(&*(block_.begin()));
  1217. file_.Write(0, &*(block_.begin()));
  1218. }
  1219. /*********************** Inaccessible BAT Functions ***************************/
  1220. void CompoundFile::LoadBAT()
  1221. // PURPOSE: Load all block allocation table information for compound file.
  1222. {
  1223. // Read BAT indices
  1224. {for (size_t i=0; i<header_.BATCount_; ++i)
  1225. {
  1226. // Load blocksIndices_
  1227. blocksIndices_.resize(blocksIndices_.size()+128, -1);
  1228. file_.Read(header_.BATArray_[i]+1, &*(block_.begin()));
  1229. for (size_t j=0; j<128; ++j)
  1230. {
  1231. LittleEndian::Read(&*(block_.begin()), blocksIndices_[j+i*128], j*4, 4);
  1232. }
  1233. }}
  1234. // Read XBAT indices
  1235. {for (size_t i=0; i<header_.XBATCount_; ++i)
  1236. {
  1237. blocksIndices_.resize(blocksIndices_.size()+128, -1);
  1238. file_.Read(header_.XBATStart_+i+1, &*(block_.begin()));
  1239. for (size_t j=0; j<128; ++j)
  1240. {
  1241. LittleEndian::Read(&*(block_.begin()), blocksIndices_[j+((i+109)*128)], j*4, 4);
  1242. }
  1243. }}
  1244. // Read SBAT indices
  1245. {for (size_t i=0; i<header_.SBATCount_; ++i)
  1246. {
  1247. sblocksIndices_.resize(sblocksIndices_.size()+128, -1);
  1248. file_.Read(header_.SBATStart_+i+1, &*(block_.begin()));
  1249. for (size_t j=0; j<128; ++j)
  1250. {
  1251. LittleEndian::Read(&*(block_.begin()), sblocksIndices_[j+i*128], j*4, 4);
  1252. }
  1253. }}
  1254. }
  1255. void CompoundFile::SaveBAT()
  1256. // PURPOSE: Save all block allocation table information for compound file.
  1257. {
  1258. // Write BAT indices
  1259. {for (size_t i=0; i<header_.BATCount_; ++i)
  1260. {
  1261. for (size_t j=0; j<128; ++j)
  1262. {
  1263. LittleEndian::Write(&*(block_.begin()), blocksIndices_[j+i*128], j*4, 4);
  1264. }
  1265. file_.Write(header_.BATArray_[i]+1, &*(block_.begin()));
  1266. }}
  1267. // Write XBAT indices
  1268. {for (size_t i=0; i<header_.XBATCount_; ++i)
  1269. {
  1270. for (size_t j=0; j<128; ++j)
  1271. {
  1272. LittleEndian::Write(&*(block_.begin()), blocksIndices_[j+((i+109)*128)], j*4, 4);
  1273. }
  1274. file_.Write(header_.XBATStart_+i+1, &*(block_.begin()));
  1275. }}
  1276. // Write SBAT indices
  1277. {for (size_t i=0; i<header_.SBATCount_; ++i)
  1278. {
  1279. for (size_t j=0; j<128; ++j)
  1280. {
  1281. LittleEndian::Write(&*(block_.begin()), sblocksIndices_[j+i*128], j*4, 4);
  1282. }
  1283. file_.Write(header_.SBATStart_+i+1, &*(block_.begin()));
  1284. }}
  1285. }
  1286. size_t CompoundFile::DataSize(size_t startIndex, bool isBig)
  1287. // PURPOSE: Gets the total size occupied by a property, starting from startIndex.
  1288. // EXPLAIN: isBig is true if property uses big blocks, false if it uses small blocks.
  1289. // PROMISE: Returns the total size occupied by the property which is the total
  1290. // PROMISE: number of blocks occupied multiply by the block size.
  1291. {
  1292. vector<size_t> indices;
  1293. if (isBig)
  1294. {
  1295. GetBlockIndices(startIndex, indices, true);
  1296. return indices.size()*header_.bigBlockSize_;
  1297. }
  1298. else
  1299. {
  1300. GetBlockIndices(startIndex, indices, false);
  1301. return indices.size()*header_.smallBlockSize_;
  1302. }
  1303. }
  1304. size_t CompoundFile::ReadData(size_t startIndex, char* data, bool isBig)
  1305. // PURPOSE: Read a property's data, starting from startIndex.
  1306. // REQUIRE: data must be large enough to receive the property's data
  1307. // REQUIRE: The required data size can be obtained by using DataSize().
  1308. // EXPLAIN: isBig is true if property uses big blocks, false if it uses small blocks.
  1309. // PROMISE: Returns the total size occupied by the property which is the total
  1310. // PROMISE: number of blocks occupied multiply by the block size.
  1311. {
  1312. vector<size_t> indices;
  1313. if (isBig)
  1314. {
  1315. GetBlockIndices(startIndex, indices, true);
  1316. size_t maxIndices = indices.size();
  1317. for (size_t i=0; i<maxIndices; ++i)
  1318. {
  1319. file_.Read(indices[i]+1, data+i*header_.bigBlockSize_);
  1320. }
  1321. return maxIndices*header_.bigBlockSize_;
  1322. }
  1323. else
  1324. {
  1325. GetBlockIndices(startIndex, indices, false);
  1326. size_t minIndex = *min_element(indices.begin(), indices.end());
  1327. size_t maxIndex = *max_element(indices.begin(), indices.end());
  1328. size_t smallBlocksPerBigBlock = header_.bigBlockSize_ / header_.smallBlockSize_;
  1329. size_t minBlock = minIndex / smallBlocksPerBigBlock;
  1330. size_t maxBlock = maxIndex / smallBlocksPerBigBlock +
  1331. (maxIndex % smallBlocksPerBigBlock ? 1 : 0);
  1332. size_t totalBlocks = maxBlock - minBlock;
  1333. char* buffer = new char[DataSize(properties_[0]->startBlock_, true)];
  1334. ReadData(properties_[0]->startBlock_, buffer, true);
  1335. size_t maxIndices = indices.size();
  1336. for (size_t i=0; i<maxIndices; ++i)
  1337. {
  1338. size_t start = (indices[i] - minBlock*smallBlocksPerBigBlock)*header_.smallBlockSize_;
  1339. copy (buffer+start,
  1340. buffer+start+header_.smallBlockSize_,
  1341. data+i*header_.smallBlockSize_);
  1342. }
  1343. delete[] buffer;
  1344. return maxIndices*header_.smallBlockSize_;
  1345. }
  1346. }
  1347. size_t CompoundFile::WriteData(const char* data, size_t size, int startIndex, bool isBig)
  1348. // PURPOSE: Write data to a property, starting from startIndex.
  1349. // EXPLAIN: startIndex can be -2 if property initially has no data.
  1350. // EXPLAIN: isBig is true if property uses big blocks, false if it uses small blocks.
  1351. // PROMISE: The file's original data will be replaced by the new data.
  1352. // PROMISE: Returns the startIndex of new data for the property.
  1353. {
  1354. if (isBig)
  1355. {
  1356. if (size==0 && startIndex==-2) return startIndex;
  1357. // Get present indices
  1358. vector<size_t> indices;
  1359. GetBlockIndices(startIndex, indices, true);
  1360. size_t maxPresentBlocks = indices.size();
  1361. // Calculate how many blocks does the data need
  1362. size_t extraSize = size % header_.bigBlockSize_;
  1363. size_t maxNewBlocks = size / header_.bigBlockSize_ + (extraSize ? 1 : 0);
  1364. // Readjust indices and remove blocks if new data size is smaller than original
  1365. int extraBlocks = maxPresentBlocks - maxNewBlocks;
  1366. if (extraBlocks > 0)
  1367. {
  1368. // Place new end marker
  1369. if (maxNewBlocks != 0) blocksIndices_[indices[maxNewBlocks]-1] = -2;
  1370. else startIndex = -2;
  1371. // Get indices of blocks to delete
  1372. vector<size_t> indicesToRemove(extraBlocks);
  1373. copy (indices.begin()+maxNewBlocks, indices.end(), indicesToRemove.begin());
  1374. indices.erase(indices.begin()+maxNewBlocks, indices.end());
  1375. // Remove extra blocks and readjust indices
  1376. FreeBlocks(indicesToRemove, true);
  1377. }
  1378. // Write blocks into available space
  1379. size_t remainingFullBlocks = size / header_.bigBlockSize_;
  1380. size_t curIndex=0;
  1381. if (maxPresentBlocks != 0)
  1382. {
  1383. for (; remainingFullBlocks && curIndex<maxPresentBlocks;
  1384. --remainingFullBlocks, ++curIndex)
  1385. {
  1386. file_.Write(indices[curIndex]+1, data+curIndex*header_.bigBlockSize_);
  1387. }
  1388. }
  1389. // Check if all blocks have been written
  1390. size_t index;
  1391. if (indices.empty()) index = 0;
  1392. else if (curIndex == 0) index = indices[0];
  1393. else index = (startIndex != -2) ? indices[curIndex-1] : 0;
  1394. if (remainingFullBlocks != 0)
  1395. {
  1396. // Require extra blocks to write data (i.e. new data is larger than original data
  1397. do
  1398. {
  1399. size_t newIndex = GetFreeBlockIndex(true); // Get new free block to write data
  1400. if (startIndex == -2) startIndex = newIndex; // Get start index
  1401. else LinkBlocks(index, newIndex, true); // Link last index to new index
  1402. file_.Write(newIndex+1, data+curIndex*header_.bigBlockSize_);
  1403. ++curIndex;
  1404. index = newIndex;
  1405. } while (--remainingFullBlocks);
  1406. }
  1407. if (extraSize != 0)
  1408. {
  1409. size_t newIndex;
  1410. if (curIndex >= maxPresentBlocks)
  1411. {
  1412. // No more free blocks to write extra block data
  1413. newIndex = GetFreeBlockIndex(true); // Get new free block to write data
  1414. if (startIndex == -2) startIndex = newIndex;
  1415. else LinkBlocks(index, newIndex,true);
  1416. }
  1417. else newIndex = indices[curIndex];
  1418. // Write extra block after increasing its size to the minimum block size
  1419. vector<char> tempdata(header_.bigBlockSize_, 0);
  1420. copy (data+curIndex*header_.bigBlockSize_, data+curIndex*header_.bigBlockSize_+extraSize, tempdata.begin());
  1421. file_.Write(newIndex+1, &*(tempdata.begin()));
  1422. }
  1423. return startIndex;
  1424. }
  1425. else
  1426. {
  1427. if (size==0 && startIndex==-2) return startIndex;
  1428. if (size != 0 && properties_[0]->startBlock_ == -2)
  1429. {
  1430. size_t newIndex = GetFreeBlockIndex(true);
  1431. fill (block_.begin(), block_.end(), 0);
  1432. file_.Insert(newIndex, &*(block_.begin()));
  1433. IncreaseLocationReferences(vector<size_t>(1, newIndex));
  1434. properties_[0]->startBlock_ = newIndex;
  1435. properties_[0]->size_ = header_.bigBlockSize_;
  1436. }
  1437. // Get present indices
  1438. vector<size_t> indices;
  1439. GetBlockIndices(startIndex, indices, false);
  1440. size_t maxPresentBlocks = indices.size();
  1441. // Calculate how many blocks does the data need
  1442. size_t extraSize = size % header_.smallBlockSize_;
  1443. size_t maxNewBlocks = size / header_.smallBlockSize_ + (extraSize ? 1 : 0);
  1444. vector<char> smallBlocksData;
  1445. int extraBlocks = maxPresentBlocks - maxNewBlocks;
  1446. if (extraBlocks > 0)
  1447. {
  1448. // Readjust indices and remove blocks
  1449. // Place new end marker
  1450. if (maxNewBlocks != 0) sblocksIndices_[indices[maxNewBlocks]-1] = -2;
  1451. else startIndex = -2;
  1452. // Get indices of blocks to delete
  1453. vector<size_t> indicesToRemove(extraBlocks);
  1454. copy (indices.begin()+maxNewBlocks, indices.end(), indicesToRemove.begin());
  1455. indices.erase(indices.begin()+maxNewBlocks, indices.end());
  1456. // Remove extra blocks and readjust indices
  1457. FreeBlocks(indicesToRemove, false);
  1458. }
  1459. else if (extraBlocks < 0)
  1460. {
  1461. size_t maxBlocks = properties_[0]->size_ / header_.bigBlockSize_ +
  1462. (properties_[0]->size_ % header_.bigBlockSize_ ? 1 : 0);
  1463. size_t actualSize = maxBlocks * header_.bigBlockSize_;
  1464. smallBlocksData.resize(actualSize);
  1465. ReadData(properties_[0]->startBlock_, &*(smallBlocksData.begin()), true);
  1466. smallBlocksData.resize(properties_[0]->size_);
  1467. // Readjust indices and add blocks
  1468. size_t newBlocksNeeded = -extraBlocks;
  1469. size_t index = maxPresentBlocks - 1;
  1470. for (size_t i=0; i<newBlocksNeeded; ++i)
  1471. {
  1472. size_t newIndex = GetFreeBlockIndex(false); // Get new free block to write data
  1473. if (startIndex == -2) startIndex = newIndex; // Get start index
  1474. else LinkBlocks(index, newIndex, false); // Link last index to new index
  1475. smallBlocksData.insert(smallBlocksData.begin()+newIndex,
  1476. header_.smallBlockSize_, 0);
  1477. index = newIndex;
  1478. }
  1479. properties_[0]->size_ = newBlocksNeeded * header_.smallBlockSize_;
  1480. }
  1481. if (smallBlocksData.empty())
  1482. {
  1483. size_t maxBlocks = properties_[0]->size_ / header_.bigBlockSize_ +
  1484. (properties_[0]->size_ % header_.bigBlockSize_ ? 1 : 0);
  1485. size_t actualSize = maxBlocks * header_.bigBlockSize_;
  1486. smallBlocksData.resize(actualSize);
  1487. ReadData(properties_[0]->startBlock_, &*(smallBlocksData.begin()), true);
  1488. smallBlocksData.resize(properties_[0]->size_);
  1489. }
  1490. // Write blocks
  1491. GetBlockIndices(startIndex, indices, false);
  1492. size_t fullBlocks = size / header_.smallBlockSize_;
  1493. for (size_t i=0; i<fullBlocks; ++i)
  1494. {
  1495. copy (data+i*header_.smallBlockSize_,
  1496. data+i*header_.smallBlockSize_+header_.smallBlockSize_,
  1497. smallBlocksData.begin()+indices[i]*header_.smallBlockSize_);
  1498. }
  1499. if (extraSize != 0)
  1500. {
  1501. copy (data+fullBlocks*header_.smallBlockSize_,
  1502. data+fullBlocks*header_.smallBlockSize_+extraSize,
  1503. smallBlocksData.begin()+indices[fullBlocks]*header_.smallBlockSize_);
  1504. }
  1505. WriteData(&*(smallBlocksData.begin()), properties_[0]->size_,
  1506. properties_[0]->startBlock_, true);
  1507. return startIndex;
  1508. }
  1509. }
  1510. void CompoundFile::GetBlockIndices(size_t startIndex, vector<size_t>& indices, bool isBig)
  1511. // PURPOSE: Get the indices of blocks where data are stored, starting from startIndex.
  1512. // EXPLAIN: isBig is true if property uses big blocks, false if it uses small blocks.
  1513. {
  1514. indices.clear();
  1515. if (isBig)
  1516. {
  1517. for (size_t i=startIndex; i!=-2; i=blocksIndices_[i]) indices.push_back(i);
  1518. }
  1519. else
  1520. {
  1521. for (size_t i=startIndex; i!=-2; i=sblocksIndices_[i]) indices.push_back(i);
  1522. }
  1523. }
  1524. size_t CompoundFile::GetFreeBlockIndex(bool isBig)
  1525. // PURPOSE: Get the index of a new block where data can be stored.
  1526. // EXPLAIN: isBig is true if property uses big blocks, false if it uses small blocks.
  1527. // PROMISE: It does not physically create a new block in the compound file.
  1528. // PROMISE: It only adjust BAT arrays and indices or SBAT arrays and indices so that
  1529. // PROMISE: it gives the index of a new block where data can be inserted.
  1530. {
  1531. size_t index;
  1532. if (isBig)
  1533. {
  1534. // Find first free location
  1535. index = distance(blocksIndices_.begin(),
  1536. find(blocksIndices_.begin(),
  1537. blocksIndices_.end(), -1));
  1538. if (index == blocksIndices_.size())
  1539. {
  1540. ExpandBATArray(true);
  1541. index = distance(blocksIndices_.begin(),
  1542. find(blocksIndices_.begin(),
  1543. blocksIndices_.end(), -1));
  1544. }
  1545. blocksIndices_[index] = -2;
  1546. }
  1547. else
  1548. {
  1549. // Find first free location
  1550. index = distance(sblocksIndices_.begin(),
  1551. find(sblocksIndices_.begin(),
  1552. sblocksIndices_.end(), -1));
  1553. if (index == sblocksIndices_.size())
  1554. {
  1555. ExpandBATArray(false);
  1556. index = distance(sblocksIndices_.begin(),
  1557. find(sblocksIndices_.begin(),
  1558. sblocksIndices_.end(), -1));
  1559. }
  1560. sblocksIndices_[index] = -2;
  1561. }
  1562. return index;
  1563. }
  1564. void CompoundFile::ExpandBATArray(bool isBig)
  1565. // PURPOSE: Create a new block of BAT or SBAT indices.
  1566. // EXPLAIN: isBig is true if property uses big blocks, false if it uses small blocks.
  1567. {
  1568. size_t newIndex;
  1569. fill (block_.begin(), block_.end(), -1);
  1570. if (isBig)
  1571. {
  1572. size_t BATindex = distance(&header_.BATArray_[0],
  1573. find(header_.BATArray_,
  1574. header_.BATArray_+109, -1));
  1575. if (BATindex < 109)
  1576. {
  1577. // Set new BAT index location
  1578. newIndex = blocksIndices_.size(); // New index location
  1579. file_.Insert(newIndex+1, &*(block_.begin()));
  1580. IncreaseLocationReferences(vector<size_t>(1, newIndex));
  1581. // Update BAT array
  1582. header_.BATArray_[BATindex] = newIndex;
  1583. ++header_.BATCount_;
  1584. }
  1585. else
  1586. {
  1587. // No free BAT indices. Increment using XBAT
  1588. // Set new XBAT index location
  1589. if (header_.XBATCount_ != 0)
  1590. {
  1591. newIndex = header_.XBATStart_ + header_.XBATCount_;
  1592. file_.Insert(newIndex, &*(block_.begin()));
  1593. IncreaseLocationReferences(vector<size_t>(1, newIndex));
  1594. }
  1595. else
  1596. {
  1597. newIndex = blocksIndices_.size();
  1598. file_.Insert(newIndex, &*(block_.begin()));
  1599. IncreaseLocationReferences(vector<size_t>(1, newIndex));
  1600. header_.XBATStart_ = newIndex;
  1601. }
  1602. ++header_.XBATCount_;
  1603. }
  1604. blocksIndices_.insert(blocksIndices_.begin()+newIndex, -3);
  1605. blocksIndices_.resize(blocksIndices_.size()+127, -1);
  1606. }
  1607. else
  1608. {
  1609. // Set new SBAT index location
  1610. if (header_.SBATCount_ != 0)
  1611. {
  1612. newIndex = header_.SBATStart_ + header_.SBATCount_;
  1613. file_.Insert(newIndex, &*(block_.begin()));
  1614. IncreaseLocationReferences(vector<size_t>(1, newIndex));
  1615. }
  1616. else
  1617. {
  1618. newIndex = GetFreeBlockIndex(true);
  1619. file_.Insert(newIndex, &*(block_.begin()));
  1620. IncreaseLocationReferences(vector<size_t>(1, newIndex));
  1621. header_.SBATStart_ = newIndex;
  1622. }
  1623. ++header_.SBATCount_;
  1624. sblocksIndices_.resize(sblocksIndices_.size()+128, -1);
  1625. }
  1626. }
  1627. void CompoundFile::LinkBlocks(size_t from, size_t to, bool isBig)
  1628. // PURPOSE: Link one BAT index to another.
  1629. // EXPLAIN: isBig is true if property uses big blocks, false if it uses small blocks.
  1630. {
  1631. if (isBig) blocksIndices_[from] = to;
  1632. else sblocksIndices_[from] = to;
  1633. }
  1634. void CompoundFile::FreeBlocks(vector<size_t>& indices, bool isBig)
  1635. // PURPOSE: Delete blocks of data from compound file.
  1636. // EXPLAIN: indices contains indices to blocks of data to be deleted.
  1637. // EXPLAIN: isBig is true if property uses big blocks, false if it uses small blocks.
  1638. {
  1639. if (isBig)
  1640. {
  1641. // Decrease all location references before deleting blocks from file.
  1642. DecreaseLocationReferences(indices);
  1643. size_t maxIndices = indices.size();
  1644. {for (size_t i=0; i<maxIndices; ++i) ++indices[i];} // Increase by 1 because Block index 1 corresponds to index 0 here
  1645. file_.Erase(indices);
  1646. // Shrink BAT indices if necessary
  1647. vector<size_t> indicesToRemove;
  1648. while (distance(find(blocksIndices_.begin(),
  1649. blocksIndices_.end(),-1),
  1650. blocksIndices_.end()) >= 128)
  1651. {
  1652. blocksIndices_.resize(blocksIndices_.size()-128);
  1653. if (header_.XBATCount_ != 0)
  1654. {
  1655. // Shrink XBAT first
  1656. --header_.XBATCount_;
  1657. indicesToRemove.push_back(header_.XBATStart_+header_.XBATCount_+1); // Add 1 because Block index 1 corresponds to index 0 here
  1658. if (header_.XBATCount_ == 0) header_.XBATStart_ = -2;
  1659. }
  1660. else
  1661. {
  1662. // No XBAT, delete last occupied BAT array element
  1663. size_t BATindex = distance(&header_.BATArray_[0],
  1664. find(header_.BATArray_,
  1665. header_.BATArray_+109, -1));
  1666. if (BATindex != 109)
  1667. {
  1668. --header_.BATCount_;
  1669. indicesToRemove.push_back(header_.BATArray_[BATindex-1]+1); // Add 1 because Block index 1 corresponds to index 0 here
  1670. header_.BATArray_[BATindex-1] = -1;
  1671. }
  1672. }
  1673. }
  1674. // Erase extra BAT indices if present
  1675. if (!indicesToRemove.empty()) file_.Erase(indicesToRemove);
  1676. }
  1677. else
  1678. {
  1679. // Erase block
  1680. size_t maxIndices = indices.size();
  1681. size_t maxBlocks = properties_[0]->size_ / header_.bigBlockSize_ +
  1682. (properties_[0]->size_ % header_.bigBlockSize_ ? 1 : 0);
  1683. size_t size = maxBlocks * header_.bigBlockSize_;
  1684. char* data = new char[size];
  1685. ReadData(properties_[0]->startBlock_, data, true);
  1686. size_t maxSmallBlocks = properties_[0]->size_ / header_.smallBlockSize_;
  1687. char* newdata = new char[properties_[0]->size_-maxIndices*header_.smallBlockSize_];
  1688. {for (size_t i=0, j=0; i<maxSmallBlocks; ++i)
  1689. {
  1690. if (find(indices.begin(), indices.end(), i) == indices.end())
  1691. {
  1692. copy (data+i*header_.smallBlockSize_,
  1693. data+i*header_.smallBlockSize_+header_.smallBlockSize_,
  1694. newdata+j*header_.smallBlockSize_);
  1695. ++j;
  1696. }
  1697. }}
  1698. properties_[0]->startBlock_ = WriteData(newdata, properties_[0]->size_-maxIndices*header_.smallBlockSize_,
  1699. properties_[0]->startBlock_, true);
  1700. properties_[0]->size_ -= maxIndices*header_.smallBlockSize_;
  1701. delete[] data;
  1702. delete[] newdata;
  1703. // Change SBAT indices
  1704. size_t maxSBATindices = sblocksIndices_.size();
  1705. {for (size_t i=0; i<maxIndices; ++i)
  1706. {
  1707. for (size_t j=0; j<maxSBATindices; ++j)
  1708. {
  1709. if (j == indices[i]) continue;
  1710. if (sblocksIndices_[j] == indices[i]) sblocksIndices_[j] = sblocksIndices_[indices[i]];
  1711. if (sblocksIndices_[j] > indices[i] &&
  1712. sblocksIndices_[j] != -1 &&
  1713. sblocksIndices_[j] != -2) --sblocksIndices_[j];
  1714. }
  1715. }}
  1716. sort (indices.begin(), indices.end(), greater<size_t>());
  1717. {for (size_t i=0; i<maxIndices; ++i)
  1718. {
  1719. sblocksIndices_.erase(sblocksIndices_.begin()+indices[i]);
  1720. sblocksIndices_.push_back(-1);
  1721. }}
  1722. vector<size_t> indicesToRemove;
  1723. while (distance(find(sblocksIndices_.begin(),
  1724. sblocksIndices_.end(),-1),
  1725. sblocksIndices_.end()) >= 128)
  1726. {
  1727. // Shrink SBAT indices if necessary
  1728. sblocksIndices_.resize(sblocksIndices_.size()-128);
  1729. --header_.SBATCount_;
  1730. indicesToRemove.push_back(header_.SBATStart_+header_.SBATCount_);
  1731. if (header_.SBATCount_ == 0) header_.SBATStart_ = -2;
  1732. }
  1733. FreeBlocks(indicesToRemove, true);
  1734. }
  1735. }
  1736. /*********************** Inaccessible Properties Functions ***************************/
  1737. void CompoundFile::LoadProperties()
  1738. // PURPOSE: Load properties information for compound file.
  1739. {
  1740. // Read properties' data from compound file.
  1741. size_t propertiesSize = DataSize(header_.propertiesStart_, true);
  1742. char* buffer = new char[propertiesSize];
  1743. ReadData(header_.propertiesStart_, buffer, true);
  1744. // Split properties' data into individual property.
  1745. size_t maxPropertiesBlock = propertiesSize / header_.bigBlockSize_;
  1746. size_t propertiesPerBlock = header_.bigBlockSize_ / 128;
  1747. size_t maxProperties = maxPropertiesBlock * propertiesPerBlock;
  1748. size_t maxBlocks = maxProperties / propertiesPerBlock +
  1749. (maxProperties % propertiesPerBlock ? 1 : 0);
  1750. for (size_t i=0; i<maxBlocks; ++i)
  1751. {
  1752. for (size_t j=0; j<4; ++j)
  1753. {
  1754. // Read individual property
  1755. Property* property = new Property;
  1756. property->Read(buffer+i*512+j*128);
  1757. if (wcslen(property->name_) == 0)
  1758. {
  1759. delete property;
  1760. break;
  1761. }
  1762. properties_.push_back(property);
  1763. }
  1764. }
  1765. delete[] buffer;
  1766. // Generate property trees
  1767. propertyTrees_->parent_ = 0;
  1768. propertyTrees_->self_ = properties_[0];
  1769. propertyTrees_->index_ = 0;
  1770. InsertPropertyTree(propertyTrees_,
  1771. properties_[properties_[0]->childProp_],
  1772. properties_[0]->childProp_);
  1773. }
  1774. void CompoundFile::SaveProperties()
  1775. // PURPOSE: Save properties information for compound file.
  1776. {
  1777. // Calculate total size required by properties
  1778. size_t maxProperties = properties_.size();
  1779. size_t propertiesPerBlock = header_.bigBlockSize_ / 128;
  1780. size_t maxBlocks = maxProperties / propertiesPerBlock +
  1781. (maxProperties % propertiesPerBlock ? 1 : 0);
  1782. size_t propertiesSize = maxBlocks*header_.bigBlockSize_;
  1783. char* buffer = new char[propertiesSize];
  1784. {for (size_t i=0; i<propertiesSize; ++i) buffer[i] = 0;}
  1785. {for (size_t i=0; i<maxProperties; ++i)
  1786. {
  1787. // Save individual property
  1788. properties_[i]->Write(buffer+i*128);
  1789. }}
  1790. // Write properties' data to compound file.
  1791. WriteData(buffer, propertiesSize, header_.propertiesStart_, true);
  1792. delete[] buffer;
  1793. }
  1794. int CompoundFile::MakeProperty(const wchar_t* path, CompoundFile::Property* property)
  1795. // PURPOSE: Create a new property in the compound file.
  1796. // EXPLAIN: path is the full path name for the property.
  1797. // EXPLAIN: property contains information on the type of property to be created.
  1798. {
  1799. wchar_t* parentpath = 0;
  1800. wchar_t* propertyname = 0;
  1801. // Change to the specified directory. If specified directory is not present,
  1802. // create it.
  1803. if (wcslen(path) != 0)
  1804. {
  1805. if (path[0] == L'\\') currentDirectory_ = propertyTrees_;
  1806. }
  1807. SplitPath(path, parentpath, propertyname);
  1808. if (propertyname != 0)
  1809. {
  1810. if (parentpath != 0)
  1811. {
  1812. if (ChangeDirectory(parentpath) != SUCCESS)
  1813. {
  1814. int ret = MakeDirectory(parentpath);
  1815. if (ret != SUCCESS)
  1816. {
  1817. delete[] parentpath;
  1818. delete[] propertyname;
  1819. return ret;
  1820. }
  1821. else ChangeDirectory(parentpath);
  1822. }
  1823. delete[] parentpath;
  1824. }
  1825. // Insert property into specified directory
  1826. size_t propertynameLength = wcslen(propertyname);
  1827. if (propertynameLength >= 32)
  1828. {
  1829. delete[] propertyname;
  1830. return NAME_TOO_LONG;
  1831. }
  1832. wcscpy(property->name_, propertyname);
  1833. delete[] propertyname;
  1834. property->nameSize_ = propertynameLength*2+2;
  1835. if (FindProperty(currentDirectory_, property->name_) == 0)
  1836. {
  1837. // Find location to insert property
  1838. size_t maxProperties = properties_.size();
  1839. size_t index;
  1840. for (index=1; index<maxProperties; ++index)
  1841. {
  1842. if (*(properties_[index]) > *property) break;
  1843. }
  1844. if (index != maxProperties)
  1845. {
  1846. // Change references for all properties affected by the new property
  1847. IncreasePropertyReferences(propertyTrees_, index);
  1848. }
  1849. properties_.insert(properties_.begin()+index, property);
  1850. InsertPropertyTree(currentDirectory_, property, index);
  1851. return SUCCESS;
  1852. }
  1853. else return DUPLICATE_PROPERTY;
  1854. }
  1855. else
  1856. {
  1857. if (parentpath != 0) delete[] parentpath;
  1858. return INVALID_PATH;
  1859. }
  1860. }
  1861. CompoundFile::PropertyTree* CompoundFile::FindProperty(size_t index)
  1862. // PURPOSE: Find property in the compound file, given the index of the property.
  1863. // PROMISE: Returns a pointer to the property tree of the property if property
  1864. // PROMISE: is present, 0 if otherwise.
  1865. {
  1866. if (previousDirectories_.empty()) previousDirectories_.push_back(propertyTrees_);
  1867. PropertyTree* currentTree = previousDirectories_.back();
  1868. if (currentTree->index_ != index)
  1869. {
  1870. size_t maxChildren = currentTree->children_.size();
  1871. for (size_t i=0; i<maxChildren; ++i)
  1872. {
  1873. previousDirectories_.push_back(currentTree->children_[i]);
  1874. PropertyTree* child = FindProperty(index);
  1875. if (child != 0)
  1876. {
  1877. previousDirectories_.pop_back();
  1878. return child;
  1879. }
  1880. }
  1881. }
  1882. else
  1883. {
  1884. previousDirectories_.pop_back();
  1885. return currentTree;
  1886. }
  1887. previousDirectories_.pop_back();
  1888. return 0;
  1889. }
  1890. CompoundFile::PropertyTree* CompoundFile::FindProperty(const wchar_t* path)
  1891. // PURPOSE: Find property in the compound file, given the path of the property.
  1892. // PROMISE: Returns a pointer to the property tree of the property if property
  1893. // PROMISE: is present, 0 if otherwise.
  1894. {
  1895. previousDirectories_.push_back(currentDirectory_);
  1896. // Change to specified directory
  1897. wchar_t* parentpath = 0;
  1898. wchar_t* filename = 0;
  1899. if (wcslen(path) != 0)
  1900. {
  1901. if (path[0] == L'\\') currentDirectory_ = propertyTrees_;
  1902. }
  1903. SplitPath(path, parentpath, filename);
  1904. if (parentpath != 0)
  1905. {
  1906. int ret = ChangeDirectory(parentpath);
  1907. delete[] parentpath;
  1908. if (ret != SUCCESS)
  1909. {
  1910. // Cannot change to specified directory
  1911. if (filename != 0) delete[] filename;
  1912. currentDirectory_ = previousDirectories_.back();
  1913. previousDirectories_.pop_back();
  1914. PropertyTree* property = 0;
  1915. return property;
  1916. }
  1917. }
  1918. // Check to see if file is present in the specified directory.
  1919. PropertyTree* property = 0;
  1920. if (filename != 0)
  1921. {
  1922. property = FindProperty(currentDirectory_, filename);
  1923. delete[] filename;
  1924. }
  1925. currentDirectory_ = previousDirectories_.back();
  1926. previousDirectories_.pop_back();
  1927. return property;
  1928. }
  1929. CompoundFile::PropertyTree*
  1930. CompoundFile::FindProperty(CompoundFile::PropertyTree* parentTree,
  1931. wchar_t* name)
  1932. // PURPOSE: Find property in the compound file, given the parent property tree and its name.
  1933. // PROMISE: Returns a pointer to the property tree of the property if property
  1934. // PROMISE: is present, 0 if otherwise.
  1935. {
  1936. if (parentTree->self_->childProp_ != -1)
  1937. {
  1938. size_t maxChildren = parentTree->children_.size();
  1939. for (size_t i=0; i<maxChildren; ++i)
  1940. {
  1941. if (wcscmp(parentTree->children_[i]->self_->name_, name) == 0)
  1942. {
  1943. return parentTree->children_[i];
  1944. }
  1945. }
  1946. }
  1947. return 0;
  1948. }
  1949. void CompoundFile::InsertPropertyTree(CompoundFile::PropertyTree* parentTree,
  1950. CompoundFile::Property* property,
  1951. size_t index)
  1952. // PURPOSE: Insert a property and all its siblings and children into the property tree.
  1953. // REQUIRE: If the property is a new property and its index is already occupied by
  1954. // REQUIRE: another property, the calling function has to call IncreasePropertyReferences()
  1955. // REQUIRE: first before calling this function.
  1956. // EXPLAIN: This function is used by LoadProperty() to initialize the property trees
  1957. // EXPLAIN: and MakeProperty() thus resulting in the above requirements.
  1958. // EXPLAIN: parentTree is the parent of the new property.
  1959. // EXPLAIN: property is the property to be added.
  1960. // EXPLAIN: index is the index of the new property.
  1961. // PROMISE: The property will be added as the parent tree's child and the parent's
  1962. // PROMISE: child property and all the its children previous property and next property
  1963. // PROMISE: will be readjusted to accomodate the next property.
  1964. {
  1965. PropertyTree* tree = new PropertyTree;
  1966. tree->parent_ = parentTree;
  1967. tree->self_ = property;
  1968. tree->index_ = index;
  1969. if (property->previousProp_ != -1)
  1970. {
  1971. InsertPropertyTree(parentTree,
  1972. properties_[property->previousProp_],
  1973. property->previousProp_);
  1974. }
  1975. if (property->nextProp_ != -1)
  1976. {
  1977. InsertPropertyTree(parentTree,
  1978. properties_[property->nextProp_],
  1979. property->nextProp_);
  1980. }
  1981. if (property->childProp_ != -1)
  1982. {
  1983. InsertPropertyTree(tree,
  1984. properties_[property->childProp_],
  1985. property->childProp_);
  1986. }
  1987. // Sort children
  1988. size_t maxChildren = parentTree->children_.size();
  1989. size_t i;
  1990. for (i=0; i<maxChildren; ++i)
  1991. {
  1992. if (index < parentTree->children_[i]->index_) break;
  1993. }
  1994. parentTree->children_.insert(parentTree->children_.begin()+i, tree);
  1995. // Update children indices
  1996. UpdateChildrenIndices(parentTree);
  1997. }
  1998. void CompoundFile::DeletePropertyTree(CompoundFile::PropertyTree* tree)
  1999. // PURPOSE: Delete a property from properties.
  2000. // EXPLAIN: tree is the property tree to be deleted.
  2001. // PROMISE: The tree's parent's child property and all the its children previous property
  2002. // PROMISE: and next property will be readjusted to accomodate the deleted property.
  2003. {
  2004. // Decrease all property references
  2005. DecreasePropertyReferences(propertyTrees_, tree->index_);
  2006. // Remove property
  2007. if (properties_[tree->index_]) delete properties_[tree->index_];
  2008. properties_.erase(properties_.begin()+tree->index_);
  2009. // Remove property from property trees
  2010. size_t maxChildren = tree->parent_->children_.size();
  2011. size_t i;
  2012. for (i=0; i<maxChildren; ++i)
  2013. {
  2014. if (tree->parent_->children_[i]->index_ == tree->index_) break;
  2015. }
  2016. tree->parent_->children_.erase(tree->parent_->children_.begin()+i);
  2017. // Update children indices
  2018. UpdateChildrenIndices(tree->parent_);
  2019. }
  2020. void CompoundFile::UpdateChildrenIndices(CompoundFile::PropertyTree* parentTree)
  2021. {
  2022. // Update indices for 1st to middle child
  2023. size_t maxChildren = parentTree->children_.size();
  2024. if (maxChildren != 0)
  2025. {
  2026. vector<PropertyTree*>& children = parentTree->children_;
  2027. size_t prevChild = 0;
  2028. children[0]->self_->previousProp_ = -1;
  2029. children[0]->self_->nextProp_ = -1;
  2030. size_t curChild;
  2031. for (curChild=1; curChild<=maxChildren/2; ++curChild)
  2032. {
  2033. children[curChild]->self_->previousProp_ = children[prevChild]->index_;
  2034. children[curChild]->self_->nextProp_ = -1;
  2035. prevChild = curChild;
  2036. }
  2037. // Update middle child
  2038. --curChild;
  2039. children[curChild]->parent_->self_->childProp_ = children[curChild]->index_;
  2040. // Update from middle to last child
  2041. size_t nextChild = curChild + 1;
  2042. if (nextChild < maxChildren)
  2043. {
  2044. children[curChild]->self_->nextProp_ = children[nextChild]->index_;
  2045. for (++curChild, ++nextChild;
  2046. nextChild<maxChildren;
  2047. ++curChild, ++nextChild)
  2048. {
  2049. children[curChild]->self_->previousProp_ = -1;
  2050. children[curChild]->self_->nextProp_ = children[nextChild]->index_;
  2051. }
  2052. children[curChild]->self_->previousProp_ = -1;
  2053. children[curChild]->self_->nextProp_ = -1;
  2054. }
  2055. }
  2056. else
  2057. {
  2058. parentTree->self_->childProp_ = -1;
  2059. }
  2060. }
  2061. void CompoundFile::IncreasePropertyReferences(CompoundFile::PropertyTree* parentTree,
  2062. size_t index)
  2063. // PURPOSE: Increase all property references (previous property, next property
  2064. // PURPOSE: and child property) which will be affected by the insertion of the new index.
  2065. // EXPLAIN: The recursive method of going through each property tree is used instead of
  2066. // EXPLAIN: using the iterative method of going through each property in properties_ is
  2067. // EXPLAIN: because the index in property tree needs to be updated also.
  2068. {
  2069. if (parentTree->index_ >= index) ++parentTree->index_;
  2070. if (parentTree->self_->previousProp_ != -1)
  2071. {
  2072. if (parentTree->self_->previousProp_ >= index)
  2073. {
  2074. ++parentTree->self_->previousProp_;
  2075. }
  2076. }
  2077. if (parentTree->self_->nextProp_!= -1)
  2078. {
  2079. if (parentTree->self_->nextProp_ >= index)
  2080. {
  2081. ++parentTree->self_->nextProp_;
  2082. }
  2083. }
  2084. if (parentTree->self_->childProp_ != -1)
  2085. {
  2086. if (parentTree->self_->childProp_ >= index)
  2087. {
  2088. ++parentTree->self_->childProp_;
  2089. }
  2090. }
  2091. size_t maxChildren = parentTree->children_.size();
  2092. for (size_t i=0; i<maxChildren; ++i)
  2093. {
  2094. IncreasePropertyReferences(parentTree->children_[i], index);
  2095. }
  2096. }
  2097. void CompoundFile::DecreasePropertyReferences(CompoundFile::PropertyTree* parentTree, size_t index)
  2098. // PURPOSE: Decrease all property references (previous property, next property
  2099. // PURPOSE: and child property) which will be affected by the deletion of the index.
  2100. // EXPLAIN: The recursive method of going through each property tree is used instead of
  2101. // EXPLAIN: using the iterative method of going through each property in properties_ is
  2102. // EXPLAIN: because the index in property tree needs to be updated also.
  2103. {
  2104. if (parentTree->index_ > index) --parentTree->index_;
  2105. if (parentTree->self_->previousProp_ != -1)
  2106. {
  2107. if (parentTree->self_->previousProp_ > index)
  2108. {
  2109. --parentTree->self_->previousProp_;
  2110. }
  2111. }
  2112. if (parentTree->self_->nextProp_!= -1)
  2113. {
  2114. if (parentTree->self_->nextProp_ > index)
  2115. {
  2116. --parentTree->self_->nextProp_;
  2117. }
  2118. }
  2119. if (parentTree->self_->childProp_ != -1)
  2120. {
  2121. if (parentTree->self_->childProp_ > index)
  2122. {
  2123. --parentTree->self_->childProp_;
  2124. }
  2125. }
  2126. size_t maxChildren = parentTree->children_.size();
  2127. for (size_t i=0; i<maxChildren; ++i)
  2128. {
  2129. DecreasePropertyReferences(parentTree->children_[i], index);
  2130. }
  2131. }
  2132. } // YCompoundFiles namespace end
  2133. namespace YExcel
  2134. {
  2135. using namespace YCompoundFiles;
  2136. /************************************************************************************************************/
  2137. Record::Record() : dataSize_(0), recordSize_(4) {};
  2138. Record::~Record() {};
  2139. size_t Record::Read(const char* data)
  2140. {
  2141. LittleEndian::Read(data, code_, 0, 2); // Read operation code.
  2142. LittleEndian::Read(data, dataSize_, 2, 2); // Read size of record.
  2143. data_.assign(data+4, data+4+dataSize_);
  2144. recordSize_ = 4 + dataSize_;
  2145. // Check if next record is a continue record
  2146. continueIndices_.clear();
  2147. short code;
  2148. LittleEndian::Read(data, code, dataSize_+4, 2);
  2149. while (code == CODE::CONTINUE)
  2150. {
  2151. continueIndices_.push_back(dataSize_);
  2152. size_t size;
  2153. LittleEndian::Read(data, size, recordSize_+2, 2);
  2154. data_.insert(data_.end(), data+recordSize_+4, data+recordSize_+4+size);
  2155. dataSize_ += size;
  2156. recordSize_ += 4 + size;
  2157. LittleEndian::Read(data, code, recordSize_, 2);
  2158. };
  2159. return recordSize_;
  2160. }
  2161. size_t Record::Write(char* data)
  2162. {
  2163. LittleEndian::Write(data, code_, 0, 2); // Write operation code.
  2164. size_t npos = 2;
  2165. if (continueIndices_.empty())
  2166. {
  2167. size_t size = dataSize_;
  2168. size_t i=0;
  2169. while (size > 8224)
  2170. {
  2171. LittleEndian::Write(data, 8224, npos, 2); // Write size of record.
  2172. npos += 2;
  2173. size -= 8224;
  2174. copy (data_.begin()+i*8224, data_.begin()+(i+1)*8224, data+npos);
  2175. npos += 8224;
  2176. if (size != 0)
  2177. {
  2178. ++i;
  2179. LittleEndian::Write(data, 0x3C, npos, 2); // Write CONTINUE code.
  2180. npos += 2;
  2181. }
  2182. }
  2183. LittleEndian::Write(data, size, npos, 2); // Write size of record.
  2184. npos += 2;
  2185. copy (data_.begin()+i*8224, data_.begin()+i*8224+size, data+npos);
  2186. npos += size;
  2187. }
  2188. else
  2189. {
  2190. size_t maxContinue = continueIndices_.size();
  2191. size_t size = continueIndices_[0];
  2192. LittleEndian::Write(data, size, npos, 2); // Write size of record
  2193. npos += 2;
  2194. copy (data_.begin(), data_.begin()+size, data+npos);
  2195. npos += size;
  2196. size_t c=0;
  2197. for (c=1; c<maxContinue; ++c)
  2198. {
  2199. LittleEndian::Write(data, 0x3C, npos, 2); // Write CONTINUE code.
  2200. npos += 2;
  2201. size = continueIndices_[c] - continueIndices_[c-1];
  2202. LittleEndian::Write(data, size, npos, 2);
  2203. npos += 2;
  2204. copy (data_.begin()+continueIndices_[c-1],
  2205. data_.begin()+continueIndices_[c],
  2206. data+npos);
  2207. npos += size;
  2208. }
  2209. LittleEndian::Write(data, 0x3C, npos, 2); // Write CONTINUE code.
  2210. npos += 2;
  2211. size = data_.size() - continueIndices_[c-1];
  2212. LittleEndian::Write(data, size, npos, 2);
  2213. npos += 2;
  2214. copy (data_.begin()+continueIndices_[c-1],
  2215. data_.end(),
  2216. data+npos);
  2217. npos += size;
  2218. }
  2219. return npos;
  2220. }
  2221. size_t Record::DataSize() {return dataSize_;}
  2222. size_t Record::RecordSize() {return recordSize_;}
  2223. /************************************************************************************************************/
  2224. /************************************************************************************************************/
  2225. BOF::BOF() : Record() {code_ = CODE::BOF; dataSize_ = 16; recordSize_ = 20;}
  2226. size_t BOF::Read(const char* data)
  2227. {
  2228. Record::Read(data);
  2229. LittleEndian::Read(data_, version_, 0, 2);
  2230. LittleEndian::Read(data_, type_, 2, 2);
  2231. LittleEndian::Read(data_, buildIdentifier_, 4, 2);
  2232. LittleEndian::Read(data_, buildYear_, 6, 2);
  2233. LittleEndian::Read(data_, fileHistoryFlags_, 8, 4);
  2234. LittleEndian::Read(data_, lowestExcelVersion_, 12, 4);
  2235. return RecordSize();
  2236. }
  2237. size_t BOF::Write(char* data)
  2238. {
  2239. data_.resize(dataSize_);
  2240. LittleEndian::Write(data_, version_, 0, 2);
  2241. LittleEndian::Write(data_, type_, 2, 2);
  2242. LittleEndian::Write(data_, buildIdentifier_, 4, 2);
  2243. LittleEndian::Write(data_, buildYear_, 6, 2);
  2244. LittleEndian::Write(data_, fileHistoryFlags_, 8, 4);
  2245. LittleEndian::Write(data_, lowestExcelVersion_, 12, 4);
  2246. return Record::Write(data);
  2247. }
  2248. /************************************************************************************************************/
  2249. /************************************************************************************************************/
  2250. YEOF::YEOF() : Record() {code_ = CODE::YEOF; dataSize_ = 0; recordSize_ = 4;}
  2251. /************************************************************************************************************/
  2252. /************************************************************************************************************/
  2253. SmallString::SmallString() : name_(0), wname_(0) {};
  2254. SmallString::~SmallString() {Reset();}
  2255. SmallString::SmallString(const SmallString& s) :
  2256. name_(0), wname_(0), unicode_(s.unicode_)
  2257. {
  2258. if (s.name_)
  2259. {
  2260. size_t len = strlen(s.name_);
  2261. name_ = new char[len+1];
  2262. strcpy(name_, s.name_);
  2263. }
  2264. if (s.wname_)
  2265. {
  2266. size_t len = wcslen(s.wname_);
  2267. wname_ = new wchar_t[len+1];
  2268. wcscpy(wname_, s.wname_);
  2269. }
  2270. }
  2271. SmallString& SmallString::operator=(const SmallString& s)
  2272. {
  2273. Reset();
  2274. unicode_ = s.unicode_;
  2275. if (s.name_)
  2276. {
  2277. size_t len = strlen(s.name_);
  2278. name_ = new char[len+1];
  2279. strcpy(name_, s.name_);
  2280. }
  2281. if (s.wname_)
  2282. {
  2283. size_t len = wcslen(s.wname_);
  2284. wname_ = new wchar_t[len+1];
  2285. wcscpy(wname_, s.wname_);
  2286. }
  2287. return *this;
  2288. }
  2289. const SmallString& SmallString::operator=(const char* str)
  2290. {
  2291. unicode_ = 0;
  2292. Reset();
  2293. size_t len = strlen(str);
  2294. name_ = new char[len+1];
  2295. strcpy(name_, str);
  2296. return *this;
  2297. }
  2298. const SmallString& SmallString::operator=(const wchar_t* str)
  2299. {
  2300. unicode_ = 1;
  2301. Reset();
  2302. size_t len = wcslen(str);
  2303. wname_ = new wchar_t[len+1];
  2304. wcscpy(wname_, str);
  2305. return *this;
  2306. }
  2307. void SmallString::Reset()
  2308. {
  2309. if (name_) {delete[] name_; name_ = 0;}
  2310. if (wname_) {delete[] wname_; wname_ = 0;}
  2311. }
  2312. size_t SmallString::Read(const char* data)
  2313. {
  2314. Reset();
  2315. char stringSize;
  2316. LittleEndian::Read(data, stringSize, 0, 1);
  2317. LittleEndian::Read(data, unicode_, 1, 1);
  2318. size_t bytesRead = 2;
  2319. if (unicode_ == 0)
  2320. {
  2321. // ANSI string
  2322. name_ = new char[stringSize+1];
  2323. LittleEndian::ReadString(data, name_, 2, stringSize);
  2324. name_[stringSize] = 0;
  2325. bytesRead += stringSize;
  2326. }
  2327. else
  2328. {
  2329. // UNICODE
  2330. wname_ = new wchar_t[stringSize+1];
  2331. LittleEndian::ReadString(data, wname_, 2, stringSize);
  2332. wname_[stringSize] = 0;
  2333. bytesRead += stringSize*2;
  2334. }
  2335. return bytesRead;
  2336. }
  2337. size_t SmallString::Write(char* data)
  2338. {
  2339. size_t stringSize = 0;
  2340. size_t bytesWrite = 0;
  2341. if (unicode_ == 0)
  2342. {
  2343. // ANSI string
  2344. if (name_)
  2345. {
  2346. stringSize = strlen(name_);
  2347. LittleEndian::Write(data, stringSize, 0, 1);
  2348. LittleEndian::Write(data, unicode_, 1, 1);
  2349. LittleEndian::WriteString(data, name_, 2, stringSize);
  2350. bytesWrite = 2 + stringSize;
  2351. }
  2352. else
  2353. {
  2354. LittleEndian::Write(data, stringSize, 0, 1);
  2355. LittleEndian::Write(data, unicode_, 1, 1);
  2356. bytesWrite = 2;
  2357. }
  2358. }
  2359. else
  2360. {
  2361. // UNICODE
  2362. if (wname_)
  2363. {
  2364. stringSize = wcslen(wname_);
  2365. LittleEndian::Write(data, stringSize, 0, 1);
  2366. LittleEndian::Write(data, unicode_, 1, 1);
  2367. LittleEndian::WriteString(data, wname_, 2, stringSize);
  2368. bytesWrite = 2 + stringSize*2;
  2369. }
  2370. else
  2371. {
  2372. LittleEndian::Write(data, stringSize, 0, 1);
  2373. LittleEndian::Write(data, unicode_, 1, 1);
  2374. bytesWrite = 2;
  2375. }
  2376. }
  2377. return bytesWrite;
  2378. }
  2379. size_t SmallString::DataSize() {return (unicode_ == 0) ? StringSize()+2 : StringSize()*2+2;}
  2380. size_t SmallString::RecordSize() {return DataSize();}
  2381. size_t SmallString::StringSize()
  2382. {
  2383. if (unicode_ == 0)
  2384. {
  2385. if (name_) return strlen(name_);
  2386. }
  2387. else
  2388. {
  2389. if (wname_) return wcslen(wname_);
  2390. }
  2391. return 0;
  2392. }
  2393. /************************************************************************************************************/
  2394. /************************************************************************************************************/
  2395. LargeString::LargeString() : unicode_(-1), richtext_(0), phonetic_(0) {};
  2396. LargeString::~LargeString() {};
  2397. LargeString::LargeString(const LargeString& s) :
  2398. name_(s.name_), wname_(s.wname_),
  2399. unicode_(s.unicode_), richtext_(s.richtext_), phonetic_(s.phonetic_) {};
  2400. LargeString& LargeString::operator=(const LargeString& s)
  2401. {
  2402. unicode_ = s.unicode_;
  2403. richtext_ = s.richtext_;
  2404. phonetic_ = s.phonetic_;
  2405. name_ = s.name_;
  2406. wname_ = s.wname_;
  2407. return *this;
  2408. }
  2409. const LargeString& LargeString::operator=(const char* str)
  2410. {
  2411. unicode_ = 0;
  2412. richtext_ = 0;
  2413. phonetic_ = 0;
  2414. wname_.clear();
  2415. size_t len = strlen(str);
  2416. name_.resize(len+1);
  2417. strcpy(&*(name_.begin()), str);
  2418. return *this;
  2419. }
  2420. const LargeString& LargeString::operator=(const wchar_t* str)
  2421. {
  2422. unicode_ = 1;
  2423. richtext_ = 0;
  2424. phonetic_ = 0;
  2425. name_.clear();
  2426. size_t len = wcslen(str);
  2427. wname_.resize(len+1);
  2428. wcscpy(&*(wname_.begin()), str);
  2429. return *this;
  2430. }
  2431. size_t LargeString::Read(const char* data)
  2432. {
  2433. size_t stringSize;
  2434. LittleEndian::Read(data, stringSize, 0, 2);
  2435. LittleEndian::Read(data, unicode_, 2, 1);
  2436. size_t npos = 3;
  2437. if (unicode_ & 8)
  2438. {
  2439. LittleEndian::Read(data, richtext_, npos, 2);
  2440. npos += 2;
  2441. }
  2442. if (unicode_ & 4) LittleEndian::Read(data, phonetic_, npos, 4);
  2443. name_.clear();
  2444. wname_.clear();
  2445. size_t bytesRead = 2;
  2446. if (stringSize>0) bytesRead += ContinueRead(data+2, stringSize);
  2447. else bytesRead = 3;
  2448. return bytesRead;
  2449. }
  2450. size_t LargeString::ContinueRead(const char* data, size_t size)
  2451. {
  2452. if (size == 0) return 0;
  2453. char unicode;
  2454. LittleEndian::Read(data, unicode, 0, 1);
  2455. if (unicode_ == -1) unicode_ = unicode;
  2456. if (unicode_ & 1)
  2457. {
  2458. // Present stored string is uncompressed (16 bit)
  2459. size_t npos = 1;
  2460. if (richtext_) npos += 2;
  2461. if (phonetic_) npos += 4;
  2462. size_t strpos = wname_.size();
  2463. wname_.resize(strpos+size, 0);
  2464. if (unicode & 1)
  2465. {
  2466. LittleEndian::ReadString(data, &*(wname_.begin())+strpos, npos, size);
  2467. npos += size * SIZEOFWCHAR_T;
  2468. }
  2469. else
  2470. {
  2471. // String to be read is in ANSI
  2472. vector<char> name(size);
  2473. LittleEndian::ReadString(data, &*(name.begin()), npos, size);
  2474. mbstowcs(&*(wname_.begin())+strpos, &*(name.begin()), size);
  2475. npos += size;
  2476. }
  2477. if (richtext_) npos += 4*richtext_;
  2478. if (phonetic_) npos += phonetic_;
  2479. return npos;
  2480. }
  2481. else
  2482. {
  2483. // Present stored string has character compression (8 bit)
  2484. size_t npos = 1;
  2485. if (richtext_) npos += 2;
  2486. if (phonetic_) npos += 4;
  2487. size_t strpos = name_.size();
  2488. name_.resize(strpos+size, 0);
  2489. if (unicode & 1)
  2490. {
  2491. // String to be read is in unicode
  2492. vector<wchar_t> name(size);
  2493. LittleEndian::ReadString(data, &*(name.begin()), npos, size);
  2494. wcstombs(&*(name_.begin())+strpos, &*(name.begin()), size);
  2495. npos += size * SIZEOFWCHAR_T;
  2496. }
  2497. else
  2498. {
  2499. LittleEndian::ReadString(data, &*(name_.begin())+strpos, npos, size);
  2500. npos += size;
  2501. }
  2502. if (richtext_) npos += 4*richtext_;
  2503. if (phonetic_) npos += phonetic_;
  2504. return npos;
  2505. }
  2506. }
  2507. size_t LargeString::Write(char* data)
  2508. {
  2509. size_t stringSize = 0;
  2510. size_t bytesWrite = 0;
  2511. if (unicode_ & 1)
  2512. {
  2513. // UNICODE
  2514. unicode_ = 1; // Don't handle richtext or phonetic for now.
  2515. if (!wname_.empty())
  2516. {
  2517. stringSize = wname_.size();
  2518. LittleEndian::Write(data, stringSize, 0, 2);
  2519. LittleEndian::Write(data, unicode_, 2, 1);
  2520. LittleEndian::WriteString(data, &*(wname_.begin()), 3, stringSize);
  2521. bytesWrite = 3 + stringSize * SIZEOFWCHAR_T;
  2522. }
  2523. else
  2524. {
  2525. LittleEndian::Write(data, stringSize, 0, 2);
  2526. LittleEndian::Write(data, unicode_, 2, 1);
  2527. bytesWrite = 3;
  2528. }
  2529. }
  2530. else
  2531. {
  2532. // ANSI string
  2533. unicode_ = 0; // Don't handle richtext or phonetic for now.
  2534. if (!name_.empty())
  2535. {
  2536. stringSize = name_.size();
  2537. LittleEndian::Write(data, stringSize, 0, 2);
  2538. LittleEndian::Write(data, unicode_, 2, 1);
  2539. LittleEndian::WriteString(data, &*(name_.begin()), 3, stringSize);
  2540. bytesWrite = 3 + stringSize;
  2541. }
  2542. else
  2543. {
  2544. LittleEndian::Write(data, stringSize, 0, 2);
  2545. LittleEndian::Write(data, unicode_, 2, 1);
  2546. bytesWrite = 3;
  2547. }
  2548. }
  2549. return bytesWrite;
  2550. }
  2551. size_t LargeString::DataSize()
  2552. {
  2553. size_t dataSize = StringSize() + 3;
  2554. if (richtext_) dataSize += 2 + 4*richtext_;
  2555. if (phonetic_) dataSize += 4 + phonetic_;
  2556. return dataSize;
  2557. }
  2558. size_t LargeString::RecordSize() {return DataSize();}
  2559. size_t LargeString::StringSize()
  2560. {
  2561. if (unicode_ & 1) return wname_.size() * SIZEOFWCHAR_T;
  2562. else return name_.size();
  2563. }
  2564. /************************************************************************************************************/
  2565. /************************************************************************************************************/
  2566. Workbook::Workbook()
  2567. {
  2568. bof_.version_ = 1536;
  2569. bof_.type_ = 5;
  2570. bof_.buildIdentifier_ = 6560;
  2571. bof_.buildYear_ = 1997;
  2572. bof_.fileHistoryFlags_ = 49353;
  2573. bof_.lowestExcelVersion_ = 774;
  2574. }
  2575. size_t Workbook::Read(const char* data)
  2576. {
  2577. size_t bytesRead = 0;
  2578. short code;
  2579. LittleEndian::Read(data, code, 0, 2);
  2580. while (code != CODE::YEOF)
  2581. {
  2582. switch (code)
  2583. {
  2584. case CODE::BOF:
  2585. bytesRead += bof_.Read(data+bytesRead);
  2586. break;
  2587. case CODE::WINDOW1:
  2588. bytesRead += window1_.Read(data+bytesRead);
  2589. break;
  2590. case CODE::FONT:
  2591. fonts_.push_back(Font());
  2592. bytesRead += fonts_.back().Read(data+bytesRead);
  2593. break;
  2594. case CODE::XF:
  2595. XFs_.push_back(XF());
  2596. bytesRead += XFs_.back().Read(data+bytesRead);
  2597. break;
  2598. case CODE::STYLE:
  2599. styles_.push_back(Style());
  2600. bytesRead += styles_.back().Read(data+bytesRead);
  2601. break;
  2602. case CODE::BOUNDSHEET:
  2603. boundSheets_.push_back(BoundSheet());
  2604. bytesRead += boundSheets_.back().Read(data+bytesRead);
  2605. break;
  2606. case CODE::SST:
  2607. bytesRead += sst_.Read(data+bytesRead);
  2608. break;
  2609. // case CODE::EXTSST:
  2610. // bytesRead += extSST_.Read(data+bytesRead);
  2611. // break;
  2612. default:
  2613. Record rec;
  2614. bytesRead += rec.Read(data+bytesRead);
  2615. }
  2616. LittleEndian::Read(data, code, bytesRead, 2);
  2617. }
  2618. bytesRead += eof_.RecordSize();
  2619. return bytesRead;
  2620. }
  2621. size_t Workbook::Write(char* data)
  2622. {
  2623. size_t bytesWritten = 0;
  2624. bytesWritten += bof_.Write(data+bytesWritten);
  2625. bytesWritten += window1_.Write(data+bytesWritten);
  2626. size_t maxFonts = fonts_.size();
  2627. {for (size_t i=0; i<maxFonts; ++i) {bytesWritten += fonts_[i].Write(data+bytesWritten);}}
  2628. size_t maxXFs = XFs_.size();
  2629. {for (size_t i=0; i<maxXFs; ++i) {bytesWritten += XFs_[i].Write(data+bytesWritten);}}
  2630. size_t maxStyles = styles_.size();
  2631. {for (size_t i=0; i<maxStyles; ++i) {bytesWritten += styles_[i].Write(data+bytesWritten);}}
  2632. size_t maxBoundSheets = boundSheets_.size();
  2633. {for (size_t i=0; i<maxBoundSheets; ++i) {bytesWritten += boundSheets_[i].Write(data+bytesWritten);}}
  2634. bytesWritten += sst_.Write(data+bytesWritten);
  2635. // bytesWritten += extSST_.Write(data+bytesWritten);
  2636. bytesWritten += eof_.Write(data+bytesWritten);
  2637. return bytesWritten;
  2638. }
  2639. size_t Workbook::DataSize()
  2640. {
  2641. size_t size = 0;
  2642. size += bof_.RecordSize();
  2643. size += window1_.RecordSize();
  2644. size_t maxFonts = fonts_.size();
  2645. {for (size_t i=0; i<maxFonts; ++i) {size += fonts_[i].RecordSize();}}
  2646. size_t maxXFs = XFs_.size();
  2647. {for (size_t i=0; i<maxXFs; ++i) {size += XFs_[i].RecordSize();}}
  2648. size_t maxStyles = styles_.size();
  2649. {for (size_t i=0; i<maxStyles; ++i) {size += styles_[i].RecordSize();}}
  2650. size_t maxBoundSheets = boundSheets_.size();
  2651. {for (size_t i=0; i<maxBoundSheets; ++i) {size += boundSheets_[i].RecordSize();}}
  2652. size += sst_.RecordSize();
  2653. // size += extSST_.RecordSize();
  2654. size += eof_.RecordSize();
  2655. return size;
  2656. }
  2657. size_t Workbook::RecordSize() {return DataSize();}
  2658. /************************************************************************************************************/
  2659. /************************************************************************************************************/
  2660. Workbook::Window1::Window1() : Record(),
  2661. horizontalPos_(0x78), verticalPos_(0x78), width_(0x3B1F), height_(0x2454),
  2662. options_(0x38), activeWorksheetIndex_(0), firstVisibleTabIndex_(0), selectedWorksheetNo_(1),
  2663. worksheetTabBarWidth_(0x258) {code_ = CODE::WINDOW1; dataSize_ = 18; recordSize_ = 22;}
  2664. size_t Workbook::Window1::Read(const char* data)
  2665. {
  2666. Record::Read(data);
  2667. LittleEndian::Read(data_, horizontalPos_, 0, 2);
  2668. LittleEndian::Read(data_, verticalPos_, 2, 2);
  2669. LittleEndian::Read(data_, width_, 4, 2);
  2670. LittleEndian::Read(data_, height_, 6, 2);
  2671. LittleEndian::Read(data_, options_, 8, 2);
  2672. LittleEndian::Read(data_, activeWorksheetIndex_, 10, 2);
  2673. LittleEndian::Read(data_, firstVisibleTabIndex_, 12, 2);
  2674. LittleEndian::Read(data_, selectedWorksheetNo_, 14, 2);
  2675. LittleEndian::Read(data_, worksheetTabBarWidth_, 16, 2);
  2676. return RecordSize();
  2677. }
  2678. size_t Workbook::Window1::Write(char* data)
  2679. {
  2680. data_.resize(dataSize_);
  2681. LittleEndian::Write(data_, horizontalPos_, 0, 2);
  2682. LittleEndian::Write(data_, verticalPos_, 2, 2);
  2683. LittleEndian::Write(data_, width_, 4, 2);
  2684. LittleEndian::Write(data_, height_, 6, 2);
  2685. LittleEndian::Write(data_, options_, 8, 2);
  2686. LittleEndian::Write(data_, activeWorksheetIndex_, 10, 2);
  2687. LittleEndian::Write(data_, firstVisibleTabIndex_, 12, 2);
  2688. LittleEndian::Write(data_, selectedWorksheetNo_, 14, 2);
  2689. LittleEndian::Write(data_, worksheetTabBarWidth_, 16, 2);
  2690. return Record::Write(data);
  2691. }
  2692. /************************************************************************************************************/
  2693. /************************************************************************************************************/
  2694. Workbook::Font::Font() : Record(),
  2695. height_(200), options_(0), colourIndex_(0x7FFF), weight_(400), escapementType_(0),
  2696. underlineType_(0), family_(0), characterSet_(0), unused_(0)
  2697. {
  2698. code_ = CODE::FONT;
  2699. dataSize_ = 14;
  2700. recordSize_ = 18;
  2701. name_ = L"Arial";
  2702. name_.unicode_ = 1;
  2703. }
  2704. size_t Workbook::Font::Read(const char* data)
  2705. {
  2706. Record::Read(data);
  2707. LittleEndian::Read(data_, height_, 0, 2);
  2708. LittleEndian::Read(data_, options_, 2, 2);
  2709. LittleEndian::Read(data_, colourIndex_, 4, 2);
  2710. LittleEndian::Read(data_, weight_, 6, 2);
  2711. LittleEndian::Read(data_, escapementType_, 8, 2);
  2712. LittleEndian::Read(data_, underlineType_, 10, 1);
  2713. LittleEndian::Read(data_, family_, 11, 1);
  2714. LittleEndian::Read(data_, characterSet_, 12, 1);
  2715. LittleEndian::Read(data_, unused_, 13, 1);
  2716. name_.Read(&*(data_.begin())+14);
  2717. return RecordSize();
  2718. }
  2719. size_t Workbook::Font::Write(char* data)
  2720. {
  2721. data_.resize(DataSize());
  2722. LittleEndian::Write(data_, height_, 0, 2);
  2723. LittleEndian::Write(data_, options_, 2, 2);
  2724. LittleEndian::Write(data_, colourIndex_, 4, 2);
  2725. LittleEndian::Write(data_, weight_, 6, 2);
  2726. LittleEndian::Write(data_, escapementType_, 8, 2);
  2727. LittleEndian::Write(data_, underlineType_, 10, 1);
  2728. LittleEndian::Write(data_, family_, 11, 1);
  2729. LittleEndian::Write(data_, characterSet_, 12, 1);
  2730. LittleEndian::Write(data_, unused_, 13, 1);
  2731. name_.Write(&*(data_.begin())+14);
  2732. return Record::Write(data);
  2733. }
  2734. size_t Workbook::Font::DataSize() {return (dataSize_ = 14 + name_.RecordSize());}
  2735. size_t Workbook::Font::RecordSize() {return (recordSize_ = DataSize()+4);}
  2736. /************************************************************************************************************/
  2737. /************************************************************************************************************/
  2738. Workbook::XF::XF() : Record(),
  2739. fontRecordIndex_(0), formatRecordIndex_(0), protectionType_(0xFFF5), alignment_(0x20), rotation_(0x00),
  2740. textProperties_(0x00), usedAttributes_(0x00), borderLines_(0x0000), colour1_(0x0000), colour2_(0x20C0)
  2741. {code_ = CODE::XF; dataSize_ = 20; recordSize_ = 24;}
  2742. size_t Workbook::XF::Read(const char* data)
  2743. {
  2744. Record::Read(data);
  2745. LittleEndian::Read(data_, fontRecordIndex_, 0, 2);
  2746. LittleEndian::Read(data_, formatRecordIndex_, 2, 2);
  2747. LittleEndian::Read(data_, protectionType_, 4, 2);
  2748. LittleEndian::Read(data_, alignment_, 6, 1);
  2749. LittleEndian::Read(data_, rotation_, 7, 1);
  2750. LittleEndian::Read(data_, textProperties_, 8, 1);
  2751. LittleEndian::Read(data_, usedAttributes_, 9, 1);
  2752. LittleEndian::Read(data_, borderLines_, 10, 4);
  2753. LittleEndian::Read(data_, colour1_, 14, 4);
  2754. LittleEndian::Read(data_, colour2_, 18, 2);
  2755. return RecordSize();
  2756. }
  2757. size_t Workbook::XF::Write(char* data)
  2758. {
  2759. data_.resize(dataSize_);
  2760. LittleEndian::Write(data_, fontRecordIndex_, 0, 2);
  2761. LittleEndian::Write(data_, formatRecordIndex_, 2, 2);
  2762. LittleEndian::Write(data_, protectionType_, 4, 2);
  2763. LittleEndian::Write(data_, alignment_, 6, 1);
  2764. LittleEndian::Write(data_, rotation_, 7, 1);
  2765. LittleEndian::Write(data_, textProperties_, 8, 1);
  2766. LittleEndian::Write(data_, usedAttributes_, 9, 1);
  2767. LittleEndian::Write(data_, borderLines_, 10, 4);
  2768. LittleEndian::Write(data_, colour1_, 14, 4);
  2769. LittleEndian::Write(data_, colour2_, 18, 2);
  2770. return Record::Write(data);
  2771. }
  2772. /************************************************************************************************************/
  2773. /************************************************************************************************************/
  2774. Workbook::Style::Style() : Record(),
  2775. XFRecordIndex_(0x8000), identifier_(0), level_(0xFF)
  2776. {code_ = CODE::STYLE; dataSize_ = 2; recordSize_ = 6;}
  2777. size_t Workbook::Style::Read(const char* data)
  2778. {
  2779. Record::Read(data);
  2780. LittleEndian::Read(data_, XFRecordIndex_, 0, 2);
  2781. if (XFRecordIndex_ & 0x8000)
  2782. {
  2783. // Built-in styles
  2784. LittleEndian::Read(data_, identifier_, 2, 1);
  2785. LittleEndian::Read(data_, level_, 3, 1);
  2786. }
  2787. else
  2788. {
  2789. // User-defined styles
  2790. name_.Read(&*(data_.begin())+2);
  2791. }
  2792. return RecordSize();
  2793. }
  2794. size_t Workbook::Style::Write(char* data)
  2795. {
  2796. data_.resize(DataSize());
  2797. LittleEndian::Write(data_, XFRecordIndex_, 0, 2);
  2798. if (XFRecordIndex_ & 0x8000)
  2799. {
  2800. // Built-in styles
  2801. LittleEndian::Write(data_, identifier_, 2, 1);
  2802. LittleEndian::Write(data_, level_, 3, 1);
  2803. }
  2804. else
  2805. {
  2806. // User-defined styles
  2807. name_.Write(&*(data_.begin())+2);
  2808. }
  2809. return Record::Write(data);
  2810. }
  2811. size_t Workbook::Style::DataSize() {return (dataSize_ = (XFRecordIndex_ & 0x8000) ? 4 : 2+name_.RecordSize());}
  2812. size_t Workbook::Style::RecordSize() {return (recordSize_ = DataSize()+4);}
  2813. /************************************************************************************************************/
  2814. /************************************************************************************************************/
  2815. Workbook::BoundSheet::BoundSheet() : Record(),
  2816. BOFpos_(0x0000), visibility_(0), type_(0)
  2817. {
  2818. code_ = CODE::BOUNDSHEET;
  2819. dataSize_ = 6;
  2820. dataSize_ = 10;
  2821. name_ = "Sheet1";
  2822. name_.unicode_ = false;
  2823. }
  2824. size_t Workbook::BoundSheet::Read(const char* data)
  2825. {
  2826. Record::Read(data);
  2827. LittleEndian::Read(data_, BOFpos_, 0, 4);
  2828. LittleEndian::Read(data_, visibility_, 4, 1);
  2829. LittleEndian::Read(data_, type_, 5, 1);
  2830. name_.Read(&*(data_.begin())+6);
  2831. return RecordSize();
  2832. }
  2833. size_t Workbook::BoundSheet::Write(char* data)
  2834. {
  2835. data_.resize(DataSize());
  2836. LittleEndian::Write(data_, BOFpos_, 0, 4);
  2837. LittleEndian::Write(data_, visibility_, 4, 1);
  2838. LittleEndian::Write(data_, type_, 5, 1);
  2839. name_.Write(&*(data_.begin())+6);
  2840. return Record::Write(data);
  2841. }
  2842. size_t Workbook::BoundSheet::DataSize() {return (dataSize_ = 6+name_.RecordSize());}
  2843. size_t Workbook::BoundSheet::RecordSize() {return (recordSize_ = DataSize()+4);}
  2844. /************************************************************************************************************/
  2845. /************************************************************************************************************/
  2846. Workbook::SharedStringTable::SharedStringTable() : Record(),
  2847. stringsTotal_(0), uniqueStringsTotal_(0) {code_ = CODE::SST; dataSize_ = 8; recordSize_ = 12;}
  2848. size_t Workbook::SharedStringTable::Read(const char* data)
  2849. {
  2850. Record::Read(data);
  2851. LittleEndian::Read(data_, stringsTotal_, 0, 4);
  2852. LittleEndian::Read(data_, uniqueStringsTotal_, 4, 4);
  2853. strings_.clear();
  2854. strings_.resize(uniqueStringsTotal_);
  2855. size_t npos = 8;
  2856. if (continueIndices_.empty())
  2857. {
  2858. for (size_t i=0; i<uniqueStringsTotal_; ++i)
  2859. {
  2860. npos += strings_[i].Read(&*(data_.begin())+npos);
  2861. }
  2862. }
  2863. else
  2864. {
  2865. // Require special handling since CONTINUE records are present
  2866. size_t maxContinue = continueIndices_.size();
  2867. for (size_t i=0, c=0; i<uniqueStringsTotal_; ++i)
  2868. {
  2869. char unicode;
  2870. size_t stringSize;
  2871. LittleEndian::Read(data_, stringSize, npos, 2);
  2872. LittleEndian::Read(data_, unicode, npos+2, 1);
  2873. size_t multiplier = unicode & 1 ? 2 : 1;
  2874. if (c >= maxContinue || npos+stringSize*multiplier+3 <= continueIndices_[c])
  2875. {
  2876. // String to be read is not split into two records
  2877. npos += strings_[i].Read(&*(data_.begin())+npos);
  2878. }
  2879. else
  2880. {
  2881. // String to be read is split into two or more records
  2882. int bytesRead = 2;// Start from unicode field
  2883. int size = continueIndices_[c] - npos - 1 - bytesRead;
  2884. ++c;
  2885. if (size > 0)
  2886. {
  2887. size /= multiplier; // Number of characters available for string in current record.
  2888. bytesRead += strings_[i].ContinueRead(&*(data_.begin())+npos+bytesRead, size);
  2889. stringSize -= size;
  2890. size = 0;
  2891. }
  2892. while (c<maxContinue && npos+stringSize+1>continueIndices_[c])
  2893. {
  2894. size_t dataSize = (continueIndices_[c] - continueIndices_[c-1] - 1) / multiplier;
  2895. bytesRead += strings_[i].ContinueRead(&*(data_.begin())+npos+bytesRead, dataSize);
  2896. stringSize -= dataSize + 1;
  2897. ++c;
  2898. };
  2899. if (stringSize>0)
  2900. {
  2901. bytesRead += strings_[i].ContinueRead(&*(data_.begin())+npos+bytesRead, stringSize);
  2902. }
  2903. npos += bytesRead;
  2904. }
  2905. }
  2906. }
  2907. return npos + 4*(npos/8224 + 1);
  2908. }
  2909. size_t Workbook::SharedStringTable::Write(char* data)
  2910. {
  2911. data_.resize(DataSize());
  2912. LittleEndian::Write(data_, stringsTotal_, 0, 4);
  2913. LittleEndian::Write(data_, uniqueStringsTotal_, 4, 4);
  2914. size_t maxContinue = continueIndices_.size();
  2915. for (size_t i=0, c=0, npos=8; i<uniqueStringsTotal_; ++i)
  2916. {
  2917. npos += strings_[i].Write(&*(data_.begin())+npos);
  2918. if (c<maxContinue && npos==continueIndices_[c]) ++c;
  2919. else if (c<maxContinue && npos > continueIndices_[c])
  2920. {
  2921. // Insert unicode flag where appropriate for CONTINUE records.
  2922. data_.insert(data_.begin()+continueIndices_[c], strings_[i].unicode_);
  2923. data_.pop_back();
  2924. ++c;
  2925. ++npos;
  2926. }
  2927. }
  2928. return Record::Write(data);
  2929. }
  2930. size_t Workbook::SharedStringTable::DataSize()
  2931. {
  2932. dataSize_ = 8;
  2933. continueIndices_.clear();
  2934. size_t curMax = 8224;
  2935. for (size_t i=0; i<uniqueStringsTotal_; ++i)
  2936. {
  2937. size_t stringSize = strings_[i].StringSize();
  2938. if (dataSize_+stringSize+3 <= curMax)
  2939. {
  2940. dataSize_ += stringSize + 3;
  2941. }
  2942. else
  2943. {
  2944. // If have >= 12 bytes (2 for size, 1 for unicode and >=9 for data, can split string
  2945. // otherwise, end record and start continue record.
  2946. bool unicode = strings_[i].unicode_ & 1;
  2947. if (curMax - dataSize_ >= 12)
  2948. {
  2949. if (unicode && !((curMax-dataSize_)%2)) --curMax; // Make sure space reserved for unicode strings is even.
  2950. continueIndices_.push_back(curMax);
  2951. stringSize -= (curMax - dataSize_ - 3);
  2952. dataSize_ = curMax;
  2953. curMax += 8224;
  2954. size_t additionalContinueRecords = unicode ? stringSize/8222 : stringSize/8223; // 8222 or 8223 because the first byte is for unicode identifier
  2955. for (size_t j=0; j<additionalContinueRecords; ++j)
  2956. {
  2957. if (unicode)
  2958. {
  2959. --curMax;
  2960. continueIndices_.push_back(curMax);
  2961. curMax += 8223;
  2962. dataSize_ += 8223;
  2963. stringSize -= 8222;
  2964. }
  2965. else
  2966. {
  2967. continueIndices_.push_back(curMax);
  2968. curMax += 8224;
  2969. dataSize_ += 8224;
  2970. stringSize -= 8223;
  2971. }
  2972. }
  2973. dataSize_ += stringSize + 1;
  2974. }
  2975. else
  2976. {
  2977. continueIndices_.push_back(dataSize_);
  2978. curMax = dataSize_ + 8224;
  2979. if (dataSize_+stringSize+3 < curMax)
  2980. {
  2981. dataSize_ += stringSize + 3;
  2982. }
  2983. else
  2984. {
  2985. // If have >= 12 bytes (2 for size, 1 for unicode and >=9 for data, can split string
  2986. // otherwise, end record and start continue record.
  2987. if (curMax - dataSize_ >= 12)
  2988. {
  2989. if (unicode && !((curMax-dataSize_)%2)) --curMax; // Make sure space reserved for unicode strings is even.
  2990. continueIndices_.push_back(curMax);
  2991. stringSize -= (curMax - dataSize_ - 3);
  2992. dataSize_ = curMax;
  2993. curMax += 8224;
  2994. size_t additionalContinueRecords = unicode ? stringSize/8222 : stringSize/8223; // 8222 or 8223 because the first byte is for unicode identifier
  2995. for (size_t j=0; j<additionalContinueRecords; ++j)
  2996. {
  2997. if (unicode)
  2998. {
  2999. --curMax;
  3000. continueIndices_.push_back(curMax);
  3001. curMax += 8223;
  3002. dataSize_ += 8223;
  3003. stringSize -= 8222;
  3004. }
  3005. else
  3006. {
  3007. continueIndices_.push_back(curMax);
  3008. curMax += 8224;
  3009. dataSize_ += 8224;
  3010. stringSize -= 8223;
  3011. }
  3012. }
  3013. dataSize_ += stringSize + 1;
  3014. }
  3015. }
  3016. }
  3017. }
  3018. }
  3019. return dataSize_;
  3020. }
  3021. size_t Workbook::SharedStringTable::RecordSize()
  3022. {
  3023. size_t dataSize = DataSize();
  3024. return (recordSize_ = dataSize + 4*(dataSize/8224 + 1));
  3025. }
  3026. /************************************************************************************************************/
  3027. Workbook::ExtSST::ExtSST() : Record(),
  3028. stringsTotal_(0), streamPos_(0), firstStringPos_(0), unused_(0)
  3029. {
  3030. code_ = CODE::EXTSST;
  3031. dataSize_ = 2;
  3032. recordSize_ = 6;
  3033. }
  3034. size_t Workbook::ExtSST::Read(const char* data)
  3035. {
  3036. Record::Read(data);
  3037. LittleEndian::Read(data_, stringsTotal_, 0, 2);
  3038. size_t maxPortions = (dataSize_-2) / 8;
  3039. streamPos_.clear();
  3040. streamPos_.resize(maxPortions);
  3041. firstStringPos_.clear();
  3042. firstStringPos_.resize(maxPortions);
  3043. unused_.clear();
  3044. unused_.resize(maxPortions);
  3045. for (size_t i=0, npos=2; i<maxPortions; ++i)
  3046. {
  3047. LittleEndian::Read(data_, streamPos_[i], npos, 4);
  3048. LittleEndian::Read(data_, firstStringPos_[i], npos+4, 2);
  3049. LittleEndian::Read(data_, unused_[i], npos+6, 2);
  3050. npos += 8;
  3051. }
  3052. return RecordSize();
  3053. }
  3054. size_t Workbook::ExtSST::Write(char* data)
  3055. {
  3056. data_.resize(DataSize());
  3057. LittleEndian::Write(data_, stringsTotal_, 0, 2);
  3058. size_t maxPortions = streamPos_.size();
  3059. for (size_t i=0, npos=2; i<maxPortions; ++i)
  3060. {
  3061. LittleEndian::Write(data_, streamPos_[i], npos, 4);
  3062. LittleEndian::Write(data_, firstStringPos_[i], npos+4, 2);
  3063. LittleEndian::Write(data_, unused_[i], npos+6, 2);
  3064. npos += 8;
  3065. }
  3066. return Record::Write(data);
  3067. }
  3068. size_t Workbook::ExtSST::DataSize()
  3069. {
  3070. dataSize_ = 2 + streamPos_.size()*8;
  3071. dataSize_ += (int)(dataSize_/8224)*4;
  3072. return dataSize_;
  3073. }
  3074. size_t Workbook::ExtSST::RecordSize() {return (recordSize_ = DataSize()+(int)((2+streamPos_.size()*8)/8224)*4)+4;}
  3075. /************************************************************************************************************/
  3076. /************************************************************************************************************/
  3077. Worksheet::Worksheet()
  3078. {
  3079. bof_.version_ = 1536;
  3080. bof_.type_ = 16;
  3081. bof_.buildIdentifier_ = 6560;
  3082. bof_.buildYear_ = 1997;
  3083. bof_.fileHistoryFlags_ = 49353;
  3084. bof_.lowestExcelVersion_ = 774;
  3085. }
  3086. size_t Worksheet::Read(const char* data)
  3087. {
  3088. size_t bytesRead = 0;
  3089. short code;
  3090. LittleEndian::Read(data, code, 0, 2);
  3091. while (code != CODE::YEOF)
  3092. {
  3093. switch (code)
  3094. {
  3095. case CODE::BOF:
  3096. bytesRead += bof_.Read(data+bytesRead);
  3097. break;
  3098. case CODE::INDEX:
  3099. bytesRead += index_.Read(data+bytesRead);
  3100. break;
  3101. case CODE::DIMENSIONS:
  3102. bytesRead += dimensions_.Read(data+bytesRead);
  3103. break;
  3104. case CODE::ROW:
  3105. bytesRead += cellTable_.Read(data+bytesRead);
  3106. break;
  3107. case CODE::WINDOW2:
  3108. bytesRead += window2_.Read(data+bytesRead);
  3109. break;
  3110. default:
  3111. Record rec;
  3112. bytesRead += rec.Read(data+bytesRead);
  3113. }
  3114. LittleEndian::Read(data, code, bytesRead, 2);
  3115. }
  3116. bytesRead += eof_.RecordSize();
  3117. return bytesRead;
  3118. }
  3119. size_t Worksheet::Write(char* data)
  3120. {
  3121. size_t bytesWritten = 0;
  3122. bytesWritten += bof_.Write(data+bytesWritten);
  3123. bytesWritten += index_.Write(data+bytesWritten);
  3124. bytesWritten += dimensions_.Write(data+bytesWritten);
  3125. bytesWritten += cellTable_.Write(data+bytesWritten);
  3126. bytesWritten += window2_.Write(data+bytesWritten);
  3127. bytesWritten += eof_.Write(data+bytesWritten);
  3128. return bytesWritten;
  3129. }
  3130. size_t Worksheet::DataSize()
  3131. {
  3132. size_t dataSize = 0;
  3133. dataSize += bof_.RecordSize();
  3134. dataSize += index_.RecordSize();
  3135. dataSize += dimensions_.RecordSize();
  3136. dataSize += cellTable_.RecordSize();
  3137. dataSize += window2_.RecordSize();
  3138. dataSize += eof_.RecordSize();
  3139. return dataSize;
  3140. }
  3141. size_t Worksheet::RecordSize() {return DataSize();}
  3142. /************************************************************************************************************/
  3143. /************************************************************************************************************/
  3144. Worksheet::Index::Index() : Record(),
  3145. unused1_(0), firstUsedRowIndex_(0), firstUnusedRowIndex_(0), unused2_(0)
  3146. {code_ = CODE::INDEX; dataSize_ = 16; recordSize_ = 20; DBCellPos_.resize(1);}
  3147. size_t Worksheet::Index::Read(const char* data)
  3148. {
  3149. Record::Read(data);
  3150. LittleEndian::Read(data_, unused1_, 0, 4);
  3151. LittleEndian::Read(data_, firstUsedRowIndex_, 4, 4);
  3152. LittleEndian::Read(data_, firstUnusedRowIndex_, 8, 4);
  3153. LittleEndian::Read(data_, unused2_, 12, 4);
  3154. size_t nm = int(firstUnusedRowIndex_ - firstUsedRowIndex_ - 1) / 32 + 1;
  3155. DBCellPos_.clear();
  3156. DBCellPos_.resize(nm);
  3157. if (dataSize_>16)
  3158. {
  3159. for (size_t i=0; i<nm; ++i)
  3160. {
  3161. LittleEndian::Read(data_, DBCellPos_[i], 16+i*4, 4);
  3162. }
  3163. }
  3164. return RecordSize();
  3165. }
  3166. size_t Worksheet::Index::Write(char* data)
  3167. {
  3168. data_.resize(DataSize());
  3169. LittleEndian::Write(data_, unused1_, 0, 4);
  3170. LittleEndian::Write(data_, firstUsedRowIndex_, 4, 4);
  3171. LittleEndian::Write(data_, firstUnusedRowIndex_, 8, 4);
  3172. LittleEndian::Write(data_, unused2_, 12, 4);
  3173. size_t nm = DBCellPos_.size();
  3174. for (size_t i=0; i<nm; ++i)
  3175. {
  3176. LittleEndian::Write(data_, DBCellPos_[i], 16+i*4, 4);
  3177. }
  3178. return Record::Write(data);
  3179. }
  3180. size_t Worksheet::Index::DataSize() {return (dataSize_ = 16 + DBCellPos_.size()*4);}
  3181. size_t Worksheet::Index::RecordSize()
  3182. {
  3183. size_t dataSize = DataSize();
  3184. return (recordSize_ = dataSize + 4*(dataSize/8224 + 1));
  3185. }
  3186. /************************************************************************************************************/
  3187. /************************************************************************************************************/
  3188. Worksheet::Dimensions::Dimensions() : Record(),
  3189. firstUsedRowIndex_(0), lastUsedRowIndexPlusOne_(0),
  3190. firstUsedColIndex_(0), lastUsedColIndexPlusOne_(0),
  3191. unused_(0) {code_ = CODE::DIMENSIONS; dataSize_ = 14; recordSize_ = 18;}
  3192. size_t Worksheet::Dimensions::Read(const char* data)
  3193. {
  3194. Record::Read(data);
  3195. LittleEndian::Read(data_, firstUsedRowIndex_, 0, 4);
  3196. LittleEndian::Read(data_, lastUsedRowIndexPlusOne_, 4, 4);
  3197. LittleEndian::Read(data_, firstUsedColIndex_, 8, 2);
  3198. LittleEndian::Read(data_, lastUsedColIndexPlusOne_, 10, 2);
  3199. LittleEndian::Read(data_, unused_, 12, 2);
  3200. return RecordSize();
  3201. }
  3202. size_t Worksheet::Dimensions::Write(char* data)
  3203. {
  3204. data_.resize(DataSize());
  3205. LittleEndian::Write(data_, firstUsedRowIndex_, 0, 4);
  3206. LittleEndian::Write(data_, lastUsedRowIndexPlusOne_, 4, 4);
  3207. LittleEndian::Write(data_, firstUsedColIndex_, 8, 2);
  3208. LittleEndian::Write(data_, lastUsedColIndexPlusOne_, 10, 2);
  3209. LittleEndian::Write(data_, unused_, 12, 2);
  3210. return Record::Write(data);
  3211. }
  3212. /************************************************************************************************************/
  3213. /************************************************************************************************************/
  3214. Worksheet::CellTable::RowBlock::CellBlock::Blank::Blank() : Record(),
  3215. rowIndex_(0), colIndex_(0), XFRecordIndex_(0) {code_ = CODE::BLANK; dataSize_ = 6; recordSize_ = 10;}
  3216. size_t Worksheet::CellTable::RowBlock::CellBlock::Blank::Read(const char* data)
  3217. {
  3218. Record::Read(data);
  3219. LittleEndian::Read(data_, rowIndex_, 0, 2);
  3220. LittleEndian::Read(data_, colIndex_, 2, 2);
  3221. LittleEndian::Read(data_, XFRecordIndex_, 4, 2);
  3222. return RecordSize();
  3223. }
  3224. size_t Worksheet::CellTable::RowBlock::CellBlock::Blank::Write(char* data)
  3225. {
  3226. data_.resize(DataSize());
  3227. LittleEndian::Write(data_, rowIndex_, 0, 2);
  3228. LittleEndian::Write(data_, colIndex_, 2, 2);
  3229. LittleEndian::Write(data_, XFRecordIndex_, 4, 2);
  3230. return Record::Write(data);
  3231. }
  3232. Worksheet::CellTable::RowBlock::CellBlock::BoolErr::BoolErr() : Record(),
  3233. rowIndex_(0), colIndex_(0), XFRecordIndex_(0), value_(0), error_(0)
  3234. {code_ = CODE::BOOLERR; dataSize_ = 8; recordSize_ = 12;}
  3235. size_t Worksheet::CellTable::RowBlock::CellBlock::BoolErr::Read(const char* data)
  3236. {
  3237. Record::Read(data);
  3238. LittleEndian::Read(data_, rowIndex_, 0, 2);
  3239. LittleEndian::Read(data_, colIndex_, 2, 2);
  3240. LittleEndian::Read(data_, XFRecordIndex_, 4, 2);
  3241. LittleEndian::Read(data_, value_, 6, 1);
  3242. LittleEndian::Read(data_, error_, 7, 1);
  3243. return RecordSize();
  3244. }
  3245. size_t Worksheet::CellTable::RowBlock::CellBlock::BoolErr::Write(char* data)
  3246. {
  3247. data_.resize(DataSize());
  3248. LittleEndian::Write(data_, rowIndex_, 0, 2);
  3249. LittleEndian::Write(data_, colIndex_, 2, 2);
  3250. LittleEndian::Write(data_, XFRecordIndex_, 4, 2);
  3251. LittleEndian::Write(data_, value_, 6, 1);
  3252. LittleEndian::Write(data_, error_, 7, 1);
  3253. return Record::Write(data);
  3254. }
  3255. Worksheet::CellTable::RowBlock::CellBlock::LabelSST::LabelSST() : Record(),
  3256. rowIndex_(0), colIndex_(0), XFRecordIndex_(0), SSTRecordIndex_(0)
  3257. {code_ = CODE::LABELSST; dataSize_ = 10; recordSize_ = 14;}
  3258. size_t Worksheet::CellTable::RowBlock::CellBlock::LabelSST::Read(const char* data)
  3259. {
  3260. Record::Read(data);
  3261. LittleEndian::Read(data_, rowIndex_, 0, 2);
  3262. LittleEndian::Read(data_, colIndex_, 2, 2);
  3263. LittleEndian::Read(data_, XFRecordIndex_, 4, 2);
  3264. LittleEndian::Read(data_, SSTRecordIndex_, 6, 4);
  3265. return RecordSize();
  3266. }
  3267. size_t Worksheet::CellTable::RowBlock::CellBlock::LabelSST::Write(char* data)
  3268. {
  3269. data_.resize(DataSize());
  3270. LittleEndian::Write(data_, rowIndex_, 0, 2);
  3271. LittleEndian::Write(data_, colIndex_, 2, 2);
  3272. LittleEndian::Write(data_, XFRecordIndex_, 4, 2);
  3273. LittleEndian::Write(data_, SSTRecordIndex_, 6, 4);
  3274. return Record::Write(data);
  3275. }
  3276. Worksheet::CellTable::RowBlock::CellBlock::MulBlank::MulBlank() : Record(),
  3277. rowIndex_(0), firstColIndex_(0), lastColIndex_(0)
  3278. {code_ = CODE::MULBLANK; dataSize_ = 10; recordSize_ = 14;}
  3279. size_t Worksheet::CellTable::RowBlock::CellBlock::MulBlank::Read(const char* data)
  3280. {
  3281. Record::Read(data);
  3282. LittleEndian::Read(data_, rowIndex_, 0, 2);
  3283. LittleEndian::Read(data_, firstColIndex_, 2, 2);
  3284. LittleEndian::Read(data_, lastColIndex_, dataSize_-2, 2);
  3285. size_t nc = lastColIndex_ - firstColIndex_ + 1;
  3286. XFRecordIndices_.clear();
  3287. XFRecordIndices_.resize(nc);
  3288. for (size_t i=0; i<nc; ++i)
  3289. {
  3290. LittleEndian::Read(data_, XFRecordIndices_[i], 4+i*2, 2);
  3291. }
  3292. return RecordSize();
  3293. }
  3294. size_t Worksheet::CellTable::RowBlock::CellBlock::MulBlank::Write(char* data)
  3295. {
  3296. data_.resize(DataSize());
  3297. LittleEndian::Write(data_, rowIndex_, 0, 2);
  3298. LittleEndian::Write(data_, firstColIndex_, 2, 2);
  3299. LittleEndian::Write(data_, lastColIndex_, dataSize_-2, 2);
  3300. size_t nc = XFRecordIndices_.size();
  3301. for (size_t i=0; i<nc; ++i)
  3302. {
  3303. LittleEndian::Write(data_, XFRecordIndices_[i], 4+i*2, 2);
  3304. }
  3305. return Record::Write(data);
  3306. }
  3307. size_t Worksheet::CellTable::RowBlock::CellBlock::MulBlank::DataSize() {return (dataSize_ = 6 + XFRecordIndices_.size()*2);}
  3308. size_t Worksheet::CellTable::RowBlock::CellBlock::MulBlank::RecordSize()
  3309. {
  3310. size_t dataSize = DataSize();
  3311. return (recordSize_ = dataSize + 4*(dataSize/8224 + 1));
  3312. }
  3313. Worksheet::CellTable::RowBlock::CellBlock::MulRK::XFRK::XFRK() :
  3314. XFRecordIndex_(0), RKValue_(0) {};
  3315. void Worksheet::CellTable::RowBlock::CellBlock::MulRK::XFRK::Read(const char* data)
  3316. {
  3317. LittleEndian::Read(data, XFRecordIndex_, 0, 2);
  3318. LittleEndian::Read(data, RKValue_, 2, 4);
  3319. }
  3320. void Worksheet::CellTable::RowBlock::CellBlock::MulRK::XFRK::Write(char* data)
  3321. {
  3322. LittleEndian::Write(data, XFRecordIndex_, 0, 2);
  3323. LittleEndian::Write(data, RKValue_, 2, 4);
  3324. }
  3325. Worksheet::CellTable::RowBlock::CellBlock::MulRK::MulRK() : Record(),
  3326. rowIndex_(0), firstColIndex_(0), lastColIndex_(0) {code_ = CODE::MULRK; dataSize_ = 10; recordSize_ = 14;}
  3327. size_t Worksheet::CellTable::RowBlock::CellBlock::MulRK::Read(const char* data)
  3328. {
  3329. Record::Read(data);
  3330. LittleEndian::Read(data_, rowIndex_, 0, 2);
  3331. LittleEndian::Read(data_, firstColIndex_, 2, 2);
  3332. LittleEndian::Read(data_, lastColIndex_, dataSize_-2, 2);
  3333. size_t nc = lastColIndex_ - firstColIndex_ + 1;
  3334. XFRK_.clear();
  3335. XFRK_.resize(nc);
  3336. for (size_t i=0; i<nc; ++i)
  3337. {
  3338. XFRK_[i].Read(&*(data_.begin())+4+i*6);
  3339. }
  3340. return RecordSize();
  3341. }
  3342. size_t Worksheet::CellTable::RowBlock::CellBlock::MulRK::Write(char* data)
  3343. {
  3344. data_.resize(DataSize());
  3345. LittleEndian::Write(data_, rowIndex_, 0, 2);
  3346. LittleEndian::Write(data_, firstColIndex_, 2, 2);
  3347. LittleEndian::Write(data_, lastColIndex_, dataSize_-2, 2);
  3348. size_t nc = XFRK_.size();
  3349. for (size_t i=0; i<nc; ++i)
  3350. {
  3351. XFRK_[i].Write(&*(data_.begin())+4+i*6);
  3352. }
  3353. return Record::Write(data);
  3354. }
  3355. size_t Worksheet::CellTable::RowBlock::CellBlock::MulRK::DataSize() {return (dataSize_ = 6 + XFRK_.size()*6);}
  3356. size_t Worksheet::CellTable::RowBlock::CellBlock::MulRK::RecordSize()
  3357. {
  3358. size_t dataSize = DataSize();
  3359. return (recordSize_ = dataSize + 4*(dataSize/8224 + 1));
  3360. }
  3361. Worksheet::CellTable::RowBlock::CellBlock::Number::Number() : Record(),
  3362. rowIndex_(0), colIndex_(0), XFRecordIndex_(0), value_(0) {code_ = CODE::NUMBER; dataSize_ = 14; recordSize_ = 18;}
  3363. size_t Worksheet::CellTable::RowBlock::CellBlock::Number::Read(const char* data)
  3364. {
  3365. Record::Read(data);
  3366. LittleEndian::Read(data_, rowIndex_, 0, 2);
  3367. LittleEndian::Read(data_, colIndex_, 2, 2);
  3368. LittleEndian::Read(data_, XFRecordIndex_, 4, 2);
  3369. __int64 value;
  3370. LittleEndian::Read(data_, value, 6, 8);
  3371. intdouble_.intvalue_ = value;
  3372. value_ = intdouble_.doublevalue_;
  3373. return RecordSize();
  3374. }
  3375. size_t Worksheet::CellTable::RowBlock::CellBlock::Number::Write(char* data)
  3376. {
  3377. data_.resize(DataSize());
  3378. LittleEndian::Write(data_, rowIndex_, 0, 2);
  3379. LittleEndian::Write(data_, colIndex_, 2, 2);
  3380. LittleEndian::Write(data_, XFRecordIndex_, 4, 2);
  3381. intdouble_.doublevalue_ = value_;
  3382. __int64 value = intdouble_.intvalue_;
  3383. LittleEndian::Write(data_, value, 6, 8);
  3384. return Record::Write(data);
  3385. }
  3386. Worksheet::CellTable::RowBlock::CellBlock::RK::RK() : Record(),
  3387. rowIndex_(0), colIndex_(0), XFRecordIndex_(0), value_(0) {code_ = CODE::RK; dataSize_ = 10; recordSize_ = 14;}
  3388. size_t Worksheet::CellTable::RowBlock::CellBlock::RK::Read(const char* data)
  3389. {
  3390. Record::Read(data);
  3391. LittleEndian::Read(data_, rowIndex_, 0, 2);
  3392. LittleEndian::Read(data_, colIndex_, 2, 2);
  3393. LittleEndian::Read(data_, XFRecordIndex_, 4, 2);
  3394. LittleEndian::Read(data_, value_, 6, 4);
  3395. return RecordSize();
  3396. }
  3397. size_t Worksheet::CellTable::RowBlock::CellBlock::RK::Write(char* data)
  3398. {
  3399. data_.resize(DataSize());
  3400. LittleEndian::Write(data_, rowIndex_, 0, 2);
  3401. LittleEndian::Write(data_, colIndex_, 2, 2);
  3402. LittleEndian::Write(data_, XFRecordIndex_, 4, 2);
  3403. LittleEndian::Write(data_, value_, 6, 4);
  3404. return Record::Write(data);
  3405. }
  3406. Worksheet::CellTable::RowBlock::CellBlock::Formula::Formula() : Record(),
  3407. rowIndex_(0), colIndex_(0), XFRecordIndex_(0), options_(0), unused_(0), type_(-1)
  3408. {code_ = CODE::FORMULA; dataSize_ = 18; recordSize_ = 22;}
  3409. size_t Worksheet::CellTable::RowBlock::CellBlock::Formula::Read(const char* data)
  3410. {
  3411. Record::Read(data);
  3412. LittleEndian::Read(data_, rowIndex_, 0, 2);
  3413. LittleEndian::Read(data_, colIndex_, 2, 2);
  3414. LittleEndian::Read(data_, XFRecordIndex_, 4, 2);
  3415. LittleEndian::ReadString(data_, result_, 6, 8);
  3416. LittleEndian::Read(data_, options_, 14, 2);
  3417. LittleEndian::Read(data_, unused_, 16, 2);
  3418. RPNtoken_.clear();
  3419. RPNtoken_.resize(dataSize_-18);
  3420. LittleEndian::ReadString(data_, &*(RPNtoken_.begin()), 18, dataSize_-18);
  3421. size_t offset = dataSize_ + 4;
  3422. short code;
  3423. LittleEndian::Read(data, code, offset, 2);
  3424. switch (code)
  3425. {
  3426. case CODE::ARRAY:
  3427. type_ = code;
  3428. array_.Read(data+offset);
  3429. offset += array_.RecordSize();
  3430. break;
  3431. case CODE::SHRFMLA:
  3432. type_ = code;
  3433. shrfmla_.Read(data+offset);
  3434. offset += shrfmla_.RecordSize();
  3435. break;
  3436. case CODE::SHRFMLA1:
  3437. type_ = code;
  3438. shrfmla1_.Read(data+offset);
  3439. offset += shrfmla1_.RecordSize();
  3440. break;
  3441. case CODE::TABLE:
  3442. type_ = code;
  3443. table_.Read(data+offset);
  3444. offset += table_.RecordSize();
  3445. break;
  3446. }
  3447. LittleEndian::Read(data, code, offset, 2);
  3448. if (code == CODE::STRING) string_.Read(data+offset);
  3449. return RecordSize();
  3450. }
  3451. size_t Worksheet::CellTable::RowBlock::CellBlock::Formula::Write(char* data)
  3452. {
  3453. data_.resize(DataSize());
  3454. LittleEndian::Write(data_, rowIndex_, 0, 2);
  3455. LittleEndian::Write(data_, colIndex_, 2, 2);
  3456. LittleEndian::Write(data_, XFRecordIndex_, 4, 2);
  3457. LittleEndian::WriteString(data_, result_, 6, 8);
  3458. LittleEndian::Write(data_, options_, 14, 2);
  3459. LittleEndian::Write(data_, unused_, 16, 2);
  3460. LittleEndian::WriteString(data_, &*(RPNtoken_.begin()), 18, RPNtoken_.size());
  3461. Record::Write(data);
  3462. size_t offset = dataSize_ + 4;
  3463. switch (type_)
  3464. {
  3465. case CODE::ARRAY:
  3466. array_.Write(data+offset);
  3467. offset += array_.RecordSize();
  3468. break;
  3469. case CODE::SHRFMLA:
  3470. shrfmla_.Write(data+offset);
  3471. offset += shrfmla_.RecordSize();
  3472. break;
  3473. case CODE::SHRFMLA1:
  3474. shrfmla1_.Write(data+offset);
  3475. offset += shrfmla1_.RecordSize();
  3476. break;
  3477. case CODE::TABLE:
  3478. table_.Write(data+offset);
  3479. offset += table_.RecordSize();
  3480. break;
  3481. }
  3482. if (string_.DataSize() != 0) string_.Write(data+offset);
  3483. return RecordSize();
  3484. }
  3485. size_t Worksheet::CellTable::RowBlock::CellBlock::Formula::DataSize() {return (dataSize_ = 18 + RPNtoken_.size());}
  3486. size_t Worksheet::CellTable::RowBlock::CellBlock::Formula::RecordSize()
  3487. {
  3488. size_t dataSize = DataSize();
  3489. recordSize_ = dataSize + 4*(dataSize/8224 + 1);
  3490. switch (type_)
  3491. {
  3492. case CODE::ARRAY:
  3493. recordSize_ += array_.RecordSize();
  3494. break;
  3495. case CODE::SHRFMLA:
  3496. recordSize_ += shrfmla_.RecordSize();
  3497. break;
  3498. case CODE::SHRFMLA1:
  3499. recordSize_ += shrfmla1_.RecordSize();
  3500. break;
  3501. case CODE::TABLE:
  3502. recordSize_ += table_.RecordSize();
  3503. break;
  3504. }
  3505. if (string_.DataSize() != 0) recordSize_ += string_.RecordSize();
  3506. return (recordSize_);
  3507. }
  3508. Worksheet::CellTable::RowBlock::CellBlock::Formula::Array::Array() : Record(),
  3509. firstRowIndex_(0), lastRowIndex_(0), firstColIndex_(0), lastColIndex_(0),
  3510. options_(0), unused_(0)
  3511. {code_ = CODE::ARRAY; dataSize_ = 12; recordSize_ = 16;}
  3512. size_t Worksheet::CellTable::RowBlock::CellBlock::Formula::Array::Read(const char* data)
  3513. {
  3514. Record::Read(data);
  3515. LittleEndian::Read(data_, firstRowIndex_, 0, 2);
  3516. LittleEndian::Read(data_, lastRowIndex_, 2, 2);
  3517. LittleEndian::Read(data_, firstColIndex_, 4, 1);
  3518. LittleEndian::Read(data_, lastColIndex_, 5, 1);
  3519. LittleEndian::Read(data_, options_, 6, 2);
  3520. LittleEndian::Read(data_, unused_, 8, 4);
  3521. formula_.clear();
  3522. formula_.resize(dataSize_-12);
  3523. LittleEndian::ReadString(data_, &*(formula_.begin()), 12, dataSize_-12);
  3524. return RecordSize();
  3525. }
  3526. size_t Worksheet::CellTable::RowBlock::CellBlock::Formula::Array::Write(char* data)
  3527. {
  3528. data_.resize(DataSize());
  3529. LittleEndian::Write(data_, firstRowIndex_, 0, 2);
  3530. LittleEndian::Write(data_, lastRowIndex_, 2, 2);
  3531. LittleEndian::Write(data_, firstColIndex_, 4, 1);
  3532. LittleEndian::Write(data_, lastColIndex_, 5, 1);
  3533. LittleEndian::Write(data_, options_, 6, 2);
  3534. LittleEndian::Write(data_, unused_, 8, 4);
  3535. LittleEndian::WriteString(data_, &*(formula_.begin()), 12, formula_.size());
  3536. return Record::Write(data);
  3537. }
  3538. size_t Worksheet::CellTable::RowBlock::CellBlock::Formula::Array::DataSize() {return (dataSize_ = 12 + formula_.size());}
  3539. size_t Worksheet::CellTable::RowBlock::CellBlock::Formula::Array::RecordSize()
  3540. {
  3541. size_t dataSize = DataSize();
  3542. return (recordSize_ = dataSize + 4*(dataSize/8224 + 1));
  3543. }
  3544. Worksheet::CellTable::RowBlock::CellBlock::Formula::ShrFmla::ShrFmla() : Record(),
  3545. firstRowIndex_(0), lastRowIndex_(0), firstColIndex_(0), lastColIndex_(0),
  3546. unused_(0)
  3547. {code_ = CODE::SHRFMLA; dataSize_ = 8; recordSize_ = 12;}
  3548. size_t Worksheet::CellTable::RowBlock::CellBlock::Formula::ShrFmla::Read(const char* data)
  3549. {
  3550. Record::Read(data);
  3551. LittleEndian::Read(data_, firstRowIndex_, 0, 2);
  3552. LittleEndian::Read(data_, lastRowIndex_, 2, 2);
  3553. LittleEndian::Read(data_, firstColIndex_, 4, 1);
  3554. LittleEndian::Read(data_, lastColIndex_, 5, 1);
  3555. LittleEndian::Read(data_, unused_, 6, 2);
  3556. formula_.clear();
  3557. formula_.resize(dataSize_-8);
  3558. LittleEndian::ReadString(data_, &*(formula_.begin()), 8, dataSize_-8);
  3559. return RecordSize();
  3560. }
  3561. size_t Worksheet::CellTable::RowBlock::CellBlock::Formula::ShrFmla::Write(char* data)
  3562. {
  3563. data_.resize(DataSize());
  3564. LittleEndian::Write(data_, firstRowIndex_, 0, 2);
  3565. LittleEndian::Write(data_, lastRowIndex_, 2, 2);
  3566. LittleEndian::Write(data_, firstColIndex_, 4, 1);
  3567. LittleEndian::Write(data_, lastColIndex_, 5, 1);
  3568. LittleEndian::Write(data_, unused_, 6, 2);
  3569. LittleEndian::WriteString(data_, &*(formula_.begin()), 8, formula_.size());
  3570. return Record::Write(data);
  3571. }
  3572. size_t Worksheet::CellTable::RowBlock::CellBlock::Formula::ShrFmla::DataSize() {return (dataSize_ = 8 + formula_.size());}
  3573. size_t Worksheet::CellTable::RowBlock::CellBlock::Formula::ShrFmla::RecordSize()
  3574. {
  3575. size_t dataSize = DataSize();
  3576. return (recordSize_ = dataSize + 4*(dataSize/8224 + 1));
  3577. }
  3578. Worksheet::CellTable::RowBlock::CellBlock::Formula::ShrFmla1::ShrFmla1() : Record(),
  3579. firstRowIndex_(0), lastRowIndex_(0), firstColIndex_(0), lastColIndex_(0),
  3580. unused_(0)
  3581. {code_ = CODE::SHRFMLA1; dataSize_ = 8; recordSize_ = 12;}
  3582. size_t Worksheet::CellTable::RowBlock::CellBlock::Formula::ShrFmla1::Read(const char* data)
  3583. {
  3584. Record::Read(data);
  3585. LittleEndian::Read(data_, firstRowIndex_, 0, 2);
  3586. LittleEndian::Read(data_, lastRowIndex_, 2, 2);
  3587. LittleEndian::Read(data_, firstColIndex_, 4, 1);
  3588. LittleEndian::Read(data_, lastColIndex_, 5, 1);
  3589. LittleEndian::Read(data_, unused_, 6, 2);
  3590. formula_.clear();
  3591. formula_.resize(dataSize_-8);
  3592. LittleEndian::ReadString(data_, &*(formula_.begin()), 8, dataSize_-8);
  3593. return RecordSize();
  3594. }
  3595. size_t Worksheet::CellTable::RowBlock::CellBlock::Formula::ShrFmla1::Write(char* data)
  3596. {
  3597. data_.resize(DataSize());
  3598. LittleEndian::Write(data_, firstRowIndex_, 0, 2);
  3599. LittleEndian::Write(data_, lastRowIndex_, 2, 2);
  3600. LittleEndian::Write(data_, firstColIndex_, 4, 1);
  3601. LittleEndian::Write(data_, lastColIndex_, 5, 1);
  3602. LittleEndian::Write(data_, unused_, 6, 2);
  3603. LittleEndian::WriteString(data_, &*(formula_.begin()), 8, formula_.size());
  3604. return Record::Write(data);
  3605. }
  3606. size_t Worksheet::CellTable::RowBlock::CellBlock::Formula::ShrFmla1::DataSize() {return (dataSize_ = 8 + formula_.size());}
  3607. size_t Worksheet::CellTable::RowBlock::CellBlock::Formula::ShrFmla1::RecordSize()
  3608. {
  3609. size_t dataSize = DataSize();
  3610. return (recordSize_ = dataSize + 4*(dataSize/8224 + 1));
  3611. }
  3612. Worksheet::CellTable::RowBlock::CellBlock::Formula::Table::Table() : Record(),
  3613. firstRowIndex_(0), lastRowIndex_(0), firstColIndex_(0), lastColIndex_(0), options_(0),
  3614. inputCellRowIndex_(0), inputCellColIndex_(0),
  3615. inputCellColumnInputRowIndex_(0), inputCellColumnInputColIndex_(0)
  3616. {code_ = CODE::TABLE; dataSize_ = 16; recordSize_ = 20;}
  3617. size_t Worksheet::CellTable::RowBlock::CellBlock::Formula::Table::Read(const char* data)
  3618. {
  3619. Record::Read(data);
  3620. LittleEndian::Read(data_, firstRowIndex_, 0, 2);
  3621. LittleEndian::Read(data_, lastRowIndex_, 2, 2);
  3622. LittleEndian::Read(data_, firstColIndex_, 4, 1);
  3623. LittleEndian::Read(data_, lastColIndex_, 5, 1);
  3624. LittleEndian::Read(data_, options_, 6, 2);
  3625. LittleEndian::Read(data_, inputCellRowIndex_, 8, 2);
  3626. LittleEndian::Read(data_, inputCellColIndex_, 10, 2);
  3627. LittleEndian::Read(data_, inputCellColumnInputRowIndex_, 12, 2);
  3628. LittleEndian::Read(data_, inputCellColumnInputColIndex_, 14, 2);
  3629. return RecordSize();
  3630. }
  3631. size_t Worksheet::CellTable::RowBlock::CellBlock::Formula::Table::Write(char* data)
  3632. {
  3633. data_.resize(DataSize());
  3634. LittleEndian::Write(data_, firstRowIndex_, 0, 2);
  3635. LittleEndian::Write(data_, lastRowIndex_, 2, 2);
  3636. LittleEndian::Write(data_, firstColIndex_, 4, 1);
  3637. LittleEndian::Write(data_, lastColIndex_, 5, 1);
  3638. LittleEndian::Write(data_, options_, 6, 2);
  3639. LittleEndian::Write(data_, inputCellRowIndex_, 8, 2);
  3640. LittleEndian::Write(data_, inputCellColIndex_, 10, 2);
  3641. LittleEndian::Write(data_, inputCellColumnInputRowIndex_, 12, 2);
  3642. LittleEndian::Write(data_, inputCellColumnInputColIndex_, 14, 2);
  3643. return Record::Write(data);
  3644. }
  3645. Worksheet::CellTable::RowBlock::CellBlock::Formula::String::String() : Record()
  3646. {code_ = CODE::STRING; dataSize_ = 0; recordSize_ = 4;}
  3647. size_t Worksheet::CellTable::RowBlock::CellBlock::Formula::String::Read(const char* data)
  3648. {
  3649. Record::Read(data);
  3650. string_.clear();
  3651. string_.resize(dataSize_);
  3652. LittleEndian::ReadString(data_, &*(string_.begin()), 0, dataSize_);
  3653. return RecordSize();
  3654. }
  3655. size_t Worksheet::CellTable::RowBlock::CellBlock::Formula::String::Write(char* data)
  3656. {
  3657. data_.resize(DataSize());
  3658. LittleEndian::WriteString(data_, &*(string_.begin()), 0, string_.size());
  3659. return Record::Write(data);
  3660. }
  3661. size_t Worksheet::CellTable::RowBlock::CellBlock::Formula::String::DataSize() {return (dataSize_ = string_.size());}
  3662. size_t Worksheet::CellTable::RowBlock::CellBlock::Formula::String::RecordSize()
  3663. {
  3664. size_t dataSize = DataSize();
  3665. return (recordSize_ = dataSize + 4*(dataSize/8224 + 1));
  3666. }
  3667. /************************************************************************************************************/
  3668. /************************************************************************************************************/
  3669. Worksheet::CellTable::RowBlock::Row::Row() : Record(),
  3670. rowIndex_(0), firstCellColIndex_(0), lastCellColIndexPlusOne_(0), height_(255),
  3671. unused1_(0), unused2_(0), options_(0) {code_ = CODE::ROW; dataSize_ = 16; recordSize_ = 20;}
  3672. size_t Worksheet::CellTable::RowBlock::Row::Read(const char* data)
  3673. {
  3674. Record::Read(data);
  3675. LittleEndian::Read(data_, rowIndex_, 0, 2);
  3676. LittleEndian::Read(data_, firstCellColIndex_, 2, 2);
  3677. LittleEndian::Read(data_, lastCellColIndexPlusOne_, 4, 2);
  3678. LittleEndian::Read(data_, height_, 6, 2);
  3679. LittleEndian::Read(data_, unused1_, 8, 2);
  3680. LittleEndian::Read(data_, unused2_, 10, 2);
  3681. LittleEndian::Read(data_, options_, 12, 4);
  3682. return RecordSize();
  3683. }
  3684. size_t Worksheet::CellTable::RowBlock::Row::Write(char* data)
  3685. {
  3686. data_.resize(DataSize());
  3687. LittleEndian::Write(data_, rowIndex_, 0, 2);
  3688. LittleEndian::Write(data_, firstCellColIndex_, 2, 2);
  3689. LittleEndian::Write(data_, lastCellColIndexPlusOne_, 4, 2);
  3690. LittleEndian::Write(data_, height_, 6, 2);
  3691. LittleEndian::Write(data_, unused1_, 8, 2);
  3692. LittleEndian::Write(data_, unused2_, 10, 2);
  3693. LittleEndian::Write(data_, options_, 12, 4);
  3694. return Record::Write(data);
  3695. }
  3696. /************************************************************************************************************/
  3697. /************************************************************************************************************/
  3698. Worksheet::CellTable::RowBlock::CellBlock::CellBlock() :
  3699. type_(-1), normalType_(true) {};
  3700. Worksheet::CellTable::RowBlock::CellBlock::~CellBlock() {};
  3701. size_t Worksheet::CellTable::RowBlock::CellBlock::Read(const char* data)
  3702. {
  3703. size_t bytesRead = 0;
  3704. LittleEndian::Read(data, type_, 0, 2);
  3705. switch (type_)
  3706. {
  3707. case CODE::BLANK:
  3708. bytesRead += blank_.Read(data);
  3709. break;
  3710. case CODE::BOOLERR:
  3711. bytesRead += boolerr_.Read(data);
  3712. break;
  3713. case CODE::LABELSST:
  3714. bytesRead += labelsst_.Read(data);
  3715. break;
  3716. case CODE::MULBLANK:
  3717. bytesRead += mulblank_.Read(data);
  3718. break;
  3719. case CODE::MULRK:
  3720. bytesRead += mulrk_.Read(data);
  3721. break;
  3722. case CODE::NUMBER:
  3723. bytesRead += number_.Read(data);
  3724. break;
  3725. case CODE::RK:
  3726. bytesRead += rk_.Read(data);
  3727. break;
  3728. case CODE::FORMULA:
  3729. bytesRead += formula_.Read(data);
  3730. break;
  3731. }
  3732. return bytesRead;
  3733. }
  3734. size_t Worksheet::CellTable::RowBlock::CellBlock::Write(char* data)
  3735. {
  3736. size_t bytesWritten = 0;
  3737. switch (type_)
  3738. {
  3739. case CODE::BLANK:
  3740. bytesWritten += blank_.Write(data);
  3741. break;
  3742. case CODE::BOOLERR:
  3743. bytesWritten += boolerr_.Write(data);
  3744. break;
  3745. case CODE::LABELSST:
  3746. bytesWritten += labelsst_.Write(data);
  3747. break;
  3748. case CODE::MULBLANK:
  3749. bytesWritten += mulblank_.Write(data);
  3750. break;
  3751. case CODE::MULRK:
  3752. bytesWritten += mulrk_.Write(data);
  3753. break;
  3754. case CODE::NUMBER:
  3755. bytesWritten += number_.Write(data);
  3756. break;
  3757. case CODE::RK:
  3758. bytesWritten += rk_.Write(data);
  3759. break;
  3760. case CODE::FORMULA:
  3761. bytesWritten += formula_.Write(data);
  3762. break;
  3763. }
  3764. return bytesWritten;
  3765. }
  3766. size_t Worksheet::CellTable::RowBlock::CellBlock::DataSize()
  3767. {
  3768. switch (type_)
  3769. {
  3770. case CODE::BLANK:
  3771. return blank_.DataSize();
  3772. case CODE::BOOLERR:
  3773. return boolerr_.DataSize();
  3774. case CODE::LABELSST:
  3775. return labelsst_.DataSize();
  3776. case CODE::MULBLANK:
  3777. return mulblank_.DataSize();
  3778. case CODE::MULRK:
  3779. return mulrk_.DataSize();
  3780. case CODE::NUMBER:
  3781. return number_.DataSize();
  3782. case CODE::RK:
  3783. return rk_.DataSize();
  3784. case CODE::FORMULA:
  3785. return formula_.DataSize();
  3786. }
  3787. abort();
  3788. }
  3789. size_t Worksheet::CellTable::RowBlock::CellBlock::RecordSize()
  3790. {
  3791. switch (type_)
  3792. {
  3793. case CODE::BLANK:
  3794. return blank_.RecordSize();
  3795. case CODE::BOOLERR:
  3796. return boolerr_.RecordSize();
  3797. case CODE::LABELSST:
  3798. return labelsst_.RecordSize();
  3799. case CODE::MULBLANK:
  3800. return mulblank_.RecordSize();
  3801. case CODE::MULRK:
  3802. return mulrk_.RecordSize();
  3803. case CODE::NUMBER:
  3804. return number_.RecordSize();
  3805. case CODE::RK:
  3806. return rk_.RecordSize();
  3807. case CODE::FORMULA:
  3808. return formula_.RecordSize();
  3809. }
  3810. abort();
  3811. }
  3812. short Worksheet::CellTable::RowBlock::CellBlock::RowIndex()
  3813. {
  3814. switch (type_)
  3815. {
  3816. case CODE::BLANK:
  3817. return blank_.rowIndex_;
  3818. case CODE::BOOLERR:
  3819. return boolerr_.rowIndex_;
  3820. case CODE::LABELSST:
  3821. return labelsst_.rowIndex_;
  3822. case CODE::MULBLANK:
  3823. return mulblank_.rowIndex_;
  3824. case CODE::MULRK:
  3825. return mulrk_.rowIndex_;
  3826. case CODE::NUMBER:
  3827. return number_.rowIndex_;
  3828. case CODE::RK:
  3829. return rk_.rowIndex_;
  3830. case CODE::FORMULA:
  3831. return formula_.rowIndex_;
  3832. }
  3833. abort();
  3834. }
  3835. short Worksheet::CellTable::RowBlock::CellBlock::ColIndex()
  3836. {
  3837. switch (type_)
  3838. {
  3839. case CODE::BLANK:
  3840. return blank_.colIndex_;
  3841. case CODE::BOOLERR:
  3842. return boolerr_.colIndex_;
  3843. case CODE::LABELSST:
  3844. return labelsst_.colIndex_;
  3845. case CODE::MULBLANK:
  3846. return mulblank_.firstColIndex_;
  3847. case CODE::MULRK:
  3848. return mulrk_.firstColIndex_;
  3849. case CODE::NUMBER:
  3850. return number_.colIndex_;
  3851. case CODE::RK:
  3852. return rk_.colIndex_;
  3853. case CODE::FORMULA:
  3854. return formula_.colIndex_;
  3855. }
  3856. abort();
  3857. }
  3858. /************************************************************************************************************/
  3859. /************************************************************************************************************/
  3860. Worksheet::CellTable::RowBlock::DBCell::DBCell() : Record(),
  3861. firstRowOffset_(0) {code_ = CODE::DBCELL; dataSize_ = 4; recordSize_ = 8;}
  3862. size_t Worksheet::CellTable::RowBlock::DBCell::Read(const char* data)
  3863. {
  3864. Record::Read(data);
  3865. LittleEndian::Read(data_, firstRowOffset_, 0, 4);
  3866. size_t nm = (dataSize_-4) / 2;
  3867. offsets_.clear();
  3868. offsets_.resize(nm);
  3869. for (size_t i=0; i<nm; ++i)
  3870. {
  3871. LittleEndian::Read(data_, offsets_[i], 4+i*2, 2);
  3872. }
  3873. return RecordSize();
  3874. }
  3875. size_t Worksheet::CellTable::RowBlock::DBCell::Write(char* data)
  3876. {
  3877. data_.resize(DataSize());
  3878. LittleEndian::Write(data_, firstRowOffset_, 0, 4);
  3879. size_t nm = offsets_.size();
  3880. for (size_t i=0; i<nm; ++i)
  3881. {
  3882. LittleEndian::Write(data_, offsets_[i], 4+i*2, 2);
  3883. }
  3884. return Record::Write(data);
  3885. }
  3886. size_t Worksheet::CellTable::RowBlock::DBCell::DataSize() {return (dataSize_ = 4+offsets_.size()*2);}
  3887. size_t Worksheet::CellTable::RowBlock::DBCell::RecordSize()
  3888. {
  3889. size_t dataSize = DataSize();
  3890. return (recordSize_ = dataSize + 4*(dataSize/8224 + 1));
  3891. }
  3892. /************************************************************************************************************/
  3893. /************************************************************************************************************/
  3894. size_t Worksheet::CellTable::RowBlock::Read(const char* data)
  3895. {
  3896. size_t bytesRead = 0;
  3897. short code;
  3898. LittleEndian::Read(data, code, 0, 2);
  3899. Row row;
  3900. CellBlock cellBlock;
  3901. cellBlocks_.reserve(1000);
  3902. while (code != CODE::DBCELL)
  3903. {
  3904. switch (code)
  3905. {
  3906. case CODE::ROW:
  3907. rows_.push_back(row);
  3908. bytesRead += rows_.back().Read(data+bytesRead);
  3909. break;
  3910. case CODE::BLANK:
  3911. case CODE::BOOLERR:
  3912. case CODE::LABELSST:
  3913. case CODE::MULBLANK:
  3914. case CODE::MULRK:
  3915. case CODE::NUMBER:
  3916. case CODE::RK:
  3917. case CODE::FORMULA:
  3918. cellBlocks_.push_back(cellBlock);
  3919. if (cellBlocks_.size()%1000==0) cellBlocks_.reserve(cellBlocks_.size()+1000);
  3920. bytesRead += cellBlocks_[cellBlocks_.size()-1].Read(data+bytesRead);
  3921. break;
  3922. default:
  3923. Record rec;
  3924. bytesRead += rec.Read(data+bytesRead);
  3925. }
  3926. LittleEndian::Read(data, code, bytesRead, 2);
  3927. }
  3928. bytesRead += dbcell_.Read(data+bytesRead);
  3929. return bytesRead;
  3930. }
  3931. size_t Worksheet::CellTable::RowBlock::Write(char* data)
  3932. {
  3933. size_t bytesWritten = 0;
  3934. size_t maxRows = rows_.size();
  3935. {for (size_t i=0; i<maxRows; ++i)
  3936. {
  3937. bytesWritten += rows_[i].Write(data+bytesWritten);
  3938. }}
  3939. size_t maxCellBlocks = cellBlocks_.size();
  3940. {for (size_t i=0; i<maxCellBlocks; ++i)
  3941. {
  3942. bytesWritten += cellBlocks_[i].Write(data+bytesWritten);
  3943. }}
  3944. bytesWritten += dbcell_.Write(data+bytesWritten);
  3945. return bytesWritten;
  3946. }
  3947. size_t Worksheet::CellTable::RowBlock::DataSize()
  3948. {
  3949. size_t dataSize = 0;
  3950. size_t maxRows = rows_.size();
  3951. {for (size_t i=0; i<maxRows; ++i) dataSize += rows_[i].RecordSize();}
  3952. size_t maxCellBlocks = cellBlocks_.size();
  3953. {for (size_t i=0; i<maxCellBlocks; ++i) dataSize += cellBlocks_[i].RecordSize();}
  3954. dataSize += dbcell_.RecordSize();
  3955. return dataSize;
  3956. }
  3957. size_t Worksheet::CellTable::RowBlock::RecordSize() {return DataSize();}
  3958. /************************************************************************************************************/
  3959. /************************************************************************************************************/
  3960. size_t Worksheet::CellTable::Read(const char* data)
  3961. {
  3962. size_t bytesRead = 0;
  3963. short code;
  3964. LittleEndian::Read(data, code, 0, 2);
  3965. RowBlock rowBlock;
  3966. rowBlocks_.reserve(1000);
  3967. while (code == CODE::ROW)
  3968. {
  3969. rowBlocks_.push_back(rowBlock);
  3970. bytesRead += rowBlocks_.back().Read(data+bytesRead);
  3971. LittleEndian::Read(data, code, bytesRead, 2);
  3972. }
  3973. return bytesRead;
  3974. }
  3975. size_t Worksheet::CellTable::Write(char* data)
  3976. {
  3977. size_t bytesWritten = 0;
  3978. size_t maxRowBlocks_ = rowBlocks_.size();
  3979. for (size_t i=0; i<maxRowBlocks_; ++i)
  3980. {
  3981. bytesWritten += rowBlocks_[i].Write(data+bytesWritten);
  3982. }
  3983. return bytesWritten;
  3984. }
  3985. size_t Worksheet::CellTable::DataSize()
  3986. {
  3987. size_t dataSize = 0;
  3988. size_t maxRowBlocks_ = rowBlocks_.size();
  3989. for (size_t i=0; i<maxRowBlocks_; ++i) dataSize += rowBlocks_[i].RecordSize();
  3990. return dataSize;
  3991. }
  3992. size_t Worksheet::CellTable::RecordSize() {return DataSize();}
  3993. /************************************************************************************************************/
  3994. /************************************************************************************************************/
  3995. Worksheet::Window2::Window2() : Record(),
  3996. options_(1718), firstVisibleRowIndex_(0), firstVisibleColIndex_(0), gridLineColourIndex_(64),
  3997. unused1_(0), magnificationFactorPageBreakPreview_(0), magnificationFactorNormalView_(0), unused2_(0)
  3998. {code_ = CODE::WINDOW2; dataSize_ = 18; recordSize_ = 22;}
  3999. size_t Worksheet::Window2::Read(const char* data)
  4000. {
  4001. Record::Read(data);
  4002. LittleEndian::Read(data_, options_, 0, 2);
  4003. LittleEndian::Read(data_, firstVisibleRowIndex_, 2, 2);
  4004. LittleEndian::Read(data_, firstVisibleColIndex_, 4, 2);
  4005. LittleEndian::Read(data_, gridLineColourIndex_, 6, 2);
  4006. LittleEndian::Read(data_, unused1_, 8, 2);
  4007. LittleEndian::Read(data_, magnificationFactorPageBreakPreview_, 10, 2);
  4008. LittleEndian::Read(data_, magnificationFactorNormalView_, 12, 2);
  4009. LittleEndian::Read(data_, unused2_, 14, 4);
  4010. return RecordSize();
  4011. }
  4012. size_t Worksheet::Window2::Write(char* data)
  4013. {
  4014. data_.resize(DataSize());
  4015. LittleEndian::Write(data_, options_, 0, 2);
  4016. LittleEndian::Write(data_, firstVisibleRowIndex_, 2, 2);
  4017. LittleEndian::Write(data_, firstVisibleColIndex_, 4, 2);
  4018. LittleEndian::Write(data_, gridLineColourIndex_, 6, 2);
  4019. LittleEndian::Write(data_, unused1_, 8, 2);
  4020. LittleEndian::Write(data_, magnificationFactorPageBreakPreview_, 10, 2);
  4021. LittleEndian::Write(data_, magnificationFactorNormalView_, 12, 2);
  4022. LittleEndian::Write(data_, unused2_, 14, 4);
  4023. return Record::Write(data);
  4024. }
  4025. /************************************************************************************************************/
  4026. /************************************************************************************************************/
  4027. // Returns true if the supplied rk value contains an integer.
  4028. bool IsRKValueAnInteger(int rkValue)
  4029. {
  4030. return (rkValue & 2);
  4031. }
  4032. // Returns true if the supplied rk value contains a double.
  4033. bool IsRKValueADouble(int rkValue)
  4034. {
  4035. return !(rkValue & 2);
  4036. }
  4037. // Convert a rk value to a double.
  4038. double GetDoubleFromRKValue(int rkValue)
  4039. {
  4040. union
  4041. {
  4042. __int64 intvalue_;
  4043. double doublevalue_;
  4044. } intdouble;
  4045. bool isMultiplied = rkValue & 1;
  4046. rkValue >>= 2;
  4047. intdouble.intvalue_ = rkValue;
  4048. intdouble.intvalue_ <<= 34;
  4049. if (isMultiplied) intdouble.doublevalue_ *= 0.01;
  4050. return intdouble.doublevalue_;
  4051. }
  4052. // Convert a rk value to an integer.
  4053. int GetIntegerFromRKValue(int rkValue)
  4054. {
  4055. bool isMultiplied = rkValue & 1;
  4056. rkValue >>= 2;
  4057. if (isMultiplied) rkValue *= 0.01;
  4058. return rkValue;
  4059. }
  4060. // Convert a double to a rk value.
  4061. int GetRKValueFromDouble(double value)
  4062. {
  4063. union
  4064. {
  4065. __int64 intvalue_;
  4066. double doublevalue_;
  4067. } intdouble;
  4068. bool isMultiplied = false;
  4069. int testVal1 = value;
  4070. testVal1 *= 100;
  4071. int testVal2 = value * 100;
  4072. if (testVal1!=testVal2)
  4073. {
  4074. isMultiplied = true;
  4075. value *= 100;
  4076. }
  4077. intdouble.doublevalue_ = value;
  4078. intdouble.intvalue_ >>= 34;
  4079. int rkValue = intdouble.intvalue_;
  4080. rkValue <<= 2;
  4081. rkValue |= isMultiplied;
  4082. return rkValue;
  4083. }
  4084. // Convert an integer to a rk value.
  4085. int GetRKValueFromInteger(int value)
  4086. {
  4087. value <<= 2;
  4088. value |= 2;
  4089. return value;
  4090. }
  4091. // Returns true if the supplied double can be stored as a rk value.
  4092. bool CanStoreAsRKValue(double value)
  4093. {
  4094. int testVal1 = value * 100;
  4095. testVal1 *= 100;
  4096. int testVal2 = value * 10000;
  4097. if (testVal1!=testVal2) return false;
  4098. else return true;
  4099. }
  4100. /************************************************************************************************************/
  4101. /************************************************************************************************************/
  4102. BasicExcel::BasicExcel() {};
  4103. BasicExcel::BasicExcel(const char* filename)
  4104. {
  4105. Load(filename);
  4106. }
  4107. BasicExcel::~BasicExcel()
  4108. {
  4109. if (file_.IsOpen()) file_.Close();
  4110. }
  4111. // Create a new Excel workbook with a given number of spreadsheets (Minimum 1)
  4112. void BasicExcel::New(int sheets)
  4113. {
  4114. workbook_ = Workbook();
  4115. worksheets_.clear();
  4116. workbook_.fonts_.resize(4);
  4117. workbook_.XFs_.resize(21);
  4118. workbook_.styles_.resize(6);
  4119. workbook_.boundSheets_.resize(1);
  4120. worksheets_.resize(1);
  4121. UpdateYExcelWorksheet();
  4122. for (int i=0; i<sheets-1; ++i) AddWorksheet();
  4123. }
  4124. // Load an Excel workbook from a file.
  4125. bool BasicExcel::Load(const char* filename)
  4126. {
  4127. if (file_.IsOpen()) file_.Close();
  4128. if (file_.Open(filename))
  4129. {
  4130. workbook_ = Workbook();
  4131. worksheets_.clear();
  4132. vector<char> data;
  4133. file_.ReadFile("Workbook", data);
  4134. Read(&*(data.begin()), data.size());
  4135. UpdateYExcelWorksheet();
  4136. return true;
  4137. }
  4138. else return false;
  4139. }
  4140. // Save current Excel workbook to opened file.
  4141. bool BasicExcel::Save()
  4142. {
  4143. if (file_.IsOpen())
  4144. {
  4145. // Prepare Raw Worksheets for saving.
  4146. UpdateWorksheets();
  4147. AdjustStreamPositions();
  4148. // Calculate bytes needed for a workbook.
  4149. size_t minBytes = workbook_.RecordSize();
  4150. size_t maxWorkSheets = worksheets_.size();
  4151. for (size_t i=0; i<maxWorkSheets; ++i)
  4152. {
  4153. minBytes += worksheets_[i].RecordSize();
  4154. }
  4155. // Create new workbook.
  4156. vector<char> data(minBytes,0);
  4157. Write(&*(data).begin());
  4158. if (file_.WriteFile("Workbook", data, data.size())!=CompoundFile::SUCCESS) return false;
  4159. return true;
  4160. }
  4161. else return false;
  4162. }
  4163. // Save current Excel workbook to a file.
  4164. bool BasicExcel::SaveAs(const char* filename)
  4165. {
  4166. if (file_.IsOpen()) file_.Close();
  4167. if (!file_.Create(filename)) return false;
  4168. if (file_.MakeFile("Workbook")!=CompoundFile::SUCCESS) return false;
  4169. return Save();
  4170. }
  4171. // Total number of Excel worksheets in current Excel workbook.
  4172. size_t BasicExcel::GetTotalWorkSheets()
  4173. {
  4174. return worksheets_.size();
  4175. }
  4176. // Get a pointer to an Excel worksheet at the given index.
  4177. // Index starts from 0.
  4178. // Returns 0 if index is invalid.
  4179. BasicExcelWorksheet* BasicExcel::GetWorksheet(size_t sheetIndex)
  4180. {
  4181. return &(yesheets_[sheetIndex]);
  4182. }
  4183. // Get a pointer to an Excel worksheet that has given ANSI name.
  4184. // Returns 0 if there is no Excel worksheet with the given name.
  4185. BasicExcelWorksheet* BasicExcel::GetWorksheet(const char* name)
  4186. {
  4187. size_t maxWorksheets = yesheets_.size();
  4188. for (size_t i=0; i<maxWorksheets; ++i)
  4189. {
  4190. if (workbook_.boundSheets_[i].name_.unicode_ & 1) continue;
  4191. if (strcmp(name, workbook_.boundSheets_[i].name_.name_) == 0) return &(yesheets_[i]);
  4192. }
  4193. return 0;
  4194. }
  4195. // Get a pointer to an Excel worksheet that has given Unicode name.
  4196. // Returns 0 if there is no Excel worksheet with the given name.
  4197. BasicExcelWorksheet* BasicExcel::GetWorksheet(const wchar_t* name)
  4198. {
  4199. size_t maxWorksheets = yesheets_.size();
  4200. for (size_t i=0; i<maxWorksheets; ++i)
  4201. {
  4202. if (!(workbook_.boundSheets_[i].name_.unicode_ & 1)) continue;
  4203. if (wcscmp(name, workbook_.boundSheets_[i].name_.wname_) == 0) return &(yesheets_[i]);
  4204. }
  4205. return 0;
  4206. }
  4207. // Add a new Excel worksheet to the given index.
  4208. // Name given to worksheet is SheetX, where X is a number which starts from 1.
  4209. // Index starts from 0.
  4210. // Worksheet is added to the last position if sheetIndex == -1.
  4211. // Returns a pointer to the worksheet if successful, 0 if otherwise.
  4212. BasicExcelWorksheet* BasicExcel::AddWorksheet(int sheetIndex)
  4213. {
  4214. size_t sheetNo = yesheets_.size() + 1;
  4215. BasicExcelWorksheet* yesheet = 0;
  4216. do
  4217. {
  4218. char sname[50];
  4219. sprintf(sname, "Sheet%d", sheetNo++);
  4220. yesheet = AddWorksheet(sname, sheetIndex);
  4221. } while (!yesheet);
  4222. return yesheet;
  4223. }
  4224. // Add a new Excel worksheet with given ANSI name to the given index.
  4225. // Index starts from 0.
  4226. // Worksheet is added to the last position if sheetIndex == -1.
  4227. // Returns a pointer to the worksheet if successful, 0 if otherwise.
  4228. BasicExcelWorksheet* BasicExcel::AddWorksheet(const char* name, int sheetIndex)
  4229. {
  4230. size_t maxWorksheets = yesheets_.size();
  4231. for (size_t i=0; i<maxWorksheets; ++i)
  4232. {
  4233. if (workbook_.boundSheets_[i].name_.unicode_ & 1) continue;
  4234. if (strcmp(name, workbook_.boundSheets_[i].name_.name_) == 0) return 0;
  4235. }
  4236. Workbook::BoundSheet* boundSheet;
  4237. Worksheet* worksheet;
  4238. BasicExcelWorksheet* yesheet;
  4239. if (sheetIndex == -1)
  4240. {
  4241. workbook_.boundSheets_.push_back(Workbook::BoundSheet());
  4242. worksheets_.push_back(Worksheet());
  4243. yesheets_.push_back(BasicExcelWorksheet(this, worksheets_.size()-1));
  4244. boundSheet = &(workbook_.boundSheets_.back());
  4245. worksheet = &(worksheets_.back());
  4246. yesheet = &(yesheets_.back());
  4247. }
  4248. else
  4249. {
  4250. boundSheet = &*(workbook_.boundSheets_.insert(workbook_.boundSheets_.begin()+sheetIndex, Workbook::BoundSheet()));
  4251. worksheet = &*(worksheets_.insert(worksheets_.begin()+sheetIndex, Worksheet()));
  4252. yesheet = &*(yesheets_.insert(yesheets_.begin()+sheetIndex, BasicExcelWorksheet(this, sheetIndex)));
  4253. size_t maxSheets = worksheets_.size();
  4254. for (size_t i=sheetIndex+1; i<maxSheets; ++i)
  4255. {
  4256. yesheets_[i].sheetIndex_ = i;
  4257. }
  4258. }
  4259. boundSheet->name_ = name;
  4260. worksheet->window2_.options_ &= ~0x200;
  4261. return yesheet;
  4262. }
  4263. // Add a new Excel worksheet with given Unicode name to the given index.
  4264. // Index starts from 0.
  4265. // Worksheet is added to the last position if sheetIndex == -1.
  4266. // Returns a pointer to the worksheet if successful, 0 if otherwise.
  4267. BasicExcelWorksheet* BasicExcel::AddWorksheet(const wchar_t* name, int sheetIndex)
  4268. {
  4269. size_t maxWorksheets = yesheets_.size();
  4270. for (size_t i=0; i<maxWorksheets; ++i)
  4271. {
  4272. if (!(workbook_.boundSheets_[i].name_.unicode_ & 1)) continue;
  4273. if (wcscmp(name, workbook_.boundSheets_[i].name_.wname_) == 0) return 0;
  4274. }
  4275. Workbook::BoundSheet* boundSheet;
  4276. Worksheet* worksheet;
  4277. BasicExcelWorksheet* yesheet;
  4278. if (sheetIndex == -1)
  4279. {
  4280. workbook_.boundSheets_.push_back(Workbook::BoundSheet());
  4281. worksheets_.push_back(Worksheet());
  4282. yesheets_.push_back(BasicExcelWorksheet(this, worksheets_.size()-1));
  4283. boundSheet = &(workbook_.boundSheets_.back());
  4284. worksheet = &(worksheets_.back());
  4285. yesheet = &(yesheets_.back());
  4286. }
  4287. else
  4288. {
  4289. boundSheet = &*(workbook_.boundSheets_.insert(workbook_.boundSheets_.begin()+sheetIndex, Workbook::BoundSheet()));
  4290. worksheet = &*(worksheets_.insert(worksheets_.begin()+sheetIndex, Worksheet()));
  4291. yesheet = &*(yesheets_.insert(yesheets_.begin()+sheetIndex, BasicExcelWorksheet(this, sheetIndex)));
  4292. size_t maxSheets = worksheets_.size();
  4293. for (size_t i=sheetIndex+1; i<maxSheets; ++i)
  4294. {
  4295. yesheets_[i].sheetIndex_ = i;
  4296. }
  4297. }
  4298. boundSheet->name_ = name;
  4299. worksheet->window2_.options_ &= ~0x200;
  4300. return yesheet;
  4301. }
  4302. // Delete an Excel worksheet at the given index.
  4303. // Index starts from 0.
  4304. // Returns true if successful, false if otherwise.
  4305. bool BasicExcel::DeleteWorksheet(size_t sheetIndex)
  4306. {
  4307. if (sheetIndex<workbook_.boundSheets_.size())
  4308. {
  4309. workbook_.boundSheets_.erase(workbook_.boundSheets_.begin()+sheetIndex);
  4310. worksheets_.erase(worksheets_.begin()+sheetIndex);
  4311. yesheets_.erase(yesheets_.begin()+sheetIndex);
  4312. return true;
  4313. }
  4314. else return false;
  4315. }
  4316. // Delete an Excel worksheet that has given ANSI name.
  4317. // Returns true if successful, false if otherwise.
  4318. bool BasicExcel::DeleteWorksheet(const char* name)
  4319. {
  4320. size_t maxWorksheets = yesheets_.size();
  4321. for (size_t i=0; i<maxWorksheets; ++i)
  4322. {
  4323. if (workbook_.boundSheets_[i].name_.unicode_ & 1) continue;
  4324. if (strcmp(name, workbook_.boundSheets_[i].name_.name_) == 0) return DeleteWorksheet(i);
  4325. }
  4326. return false;
  4327. }
  4328. // Delete an Excel worksheet that has given Unicode name.
  4329. // Returns true if successful, false if otherwise.
  4330. bool BasicExcel::DeleteWorksheet(const wchar_t* name)
  4331. {
  4332. size_t maxWorksheets = worksheets_.size();
  4333. for (size_t i=0; i<maxWorksheets; ++i)
  4334. {
  4335. if (!(workbook_.boundSheets_[i].name_.unicode_ & 1)) continue;
  4336. if (wcscmp(name, workbook_.boundSheets_[i].name_.wname_) == 0) return DeleteWorksheet(i);
  4337. }
  4338. return false;
  4339. }
  4340. // Get the worksheet name at the given index.
  4341. // Index starts from 0.
  4342. // Returns 0 if name is in Unicode format.
  4343. char* BasicExcel::GetAnsiSheetName(size_t sheetIndex)
  4344. {
  4345. if (!(workbook_.boundSheets_[sheetIndex].name_.unicode_ & 1))
  4346. {
  4347. return workbook_.boundSheets_[sheetIndex].name_.name_;
  4348. }
  4349. else return 0;
  4350. }
  4351. // Get the worksheet name at the given index.
  4352. // Index starts from 0.
  4353. // Returns 0 if name is in Ansi format.
  4354. wchar_t* BasicExcel::GetUnicodeSheetName(size_t sheetIndex)
  4355. {
  4356. if (workbook_.boundSheets_[sheetIndex].name_.unicode_ & 1)
  4357. {
  4358. return workbook_.boundSheets_[sheetIndex].name_.wname_;
  4359. }
  4360. else return 0;
  4361. }
  4362. // Get the worksheet name at the given index.
  4363. // Index starts from 0.
  4364. // Returns false if name is in Unicode format.
  4365. bool BasicExcel::GetSheetName(size_t sheetIndex, char* name)
  4366. {
  4367. if (!(workbook_.boundSheets_[sheetIndex].name_.unicode_ & 1))
  4368. {
  4369. strcpy(name, workbook_.boundSheets_[sheetIndex].name_.name_);
  4370. return true;
  4371. }
  4372. else return false;
  4373. }
  4374. // Get the worksheet name at the given index.
  4375. // Index starts from 0.
  4376. // Returns false if name is in Ansi format.
  4377. bool BasicExcel::GetSheetName(size_t sheetIndex, wchar_t* name)
  4378. {
  4379. if (workbook_.boundSheets_[sheetIndex].name_.unicode_ & 1)
  4380. {
  4381. wcscpy(name, workbook_.boundSheets_[sheetIndex].name_.wname_);
  4382. return true;
  4383. }
  4384. else return false;
  4385. }
  4386. // Rename an Excel worksheet at the given index to the given ANSI name.
  4387. // Index starts from 0.
  4388. // Returns true if successful, false if otherwise.
  4389. bool BasicExcel::RenameWorksheet(size_t sheetIndex, const char* to)
  4390. {
  4391. size_t maxWorksheets = yesheets_.size();
  4392. if (sheetIndex < maxWorksheets)
  4393. {
  4394. for (size_t i=0; i<maxWorksheets; ++i)
  4395. {
  4396. if (workbook_.boundSheets_[i].name_.unicode_ & 1) continue;
  4397. if (strcmp(to, workbook_.boundSheets_[i].name_.name_) == 0) return false;
  4398. }
  4399. workbook_.boundSheets_[sheetIndex].name_ = to;
  4400. return true;
  4401. }
  4402. else return false;
  4403. }
  4404. // Rename an Excel worksheet at the given index to the given Unicode name.
  4405. // Index starts from 0.
  4406. // Returns true if successful, false if otherwise.
  4407. bool BasicExcel::RenameWorksheet(size_t sheetIndex, const wchar_t* to)
  4408. {
  4409. size_t maxWorksheets = yesheets_.size();
  4410. if (sheetIndex < maxWorksheets)
  4411. {
  4412. for (size_t i=0; i<maxWorksheets; ++i)
  4413. {
  4414. if (!(workbook_.boundSheets_[i].name_.unicode_ & 1)) continue;
  4415. if (wcscmp(to, workbook_.boundSheets_[i].name_.wname_) == 0) return false;
  4416. }
  4417. workbook_.boundSheets_[sheetIndex].name_ = to;
  4418. return true;
  4419. }
  4420. else return false;
  4421. }
  4422. // Rename an Excel worksheet that has given ANSI name to another ANSI name.
  4423. // Returns true if successful, false if otherwise.
  4424. bool BasicExcel::RenameWorksheet(const char* from, const char* to)
  4425. {
  4426. size_t maxWorksheets = yesheets_.size();
  4427. for (size_t i=0; i<maxWorksheets; ++i)
  4428. {
  4429. if (workbook_.boundSheets_[i].name_.unicode_ & 1) continue;
  4430. if (strcmp(from, workbook_.boundSheets_[i].name_.name_) == 0)
  4431. {
  4432. for (size_t j=0; j<maxWorksheets; ++j)
  4433. {
  4434. if (workbook_.boundSheets_[j].name_.unicode_ & 1) continue;
  4435. if (strcmp(to, workbook_.boundSheets_[j].name_.name_) == 0) return false;
  4436. }
  4437. workbook_.boundSheets_[i].name_ = to;
  4438. return true;
  4439. }
  4440. }
  4441. return false;
  4442. }
  4443. // Rename an Excel worksheet that has given Unicode name to another Unicode name.
  4444. // Returns true if successful, false if otherwise.
  4445. bool BasicExcel::RenameWorksheet(const wchar_t* from, const wchar_t* to)
  4446. {
  4447. size_t maxWorksheets = worksheets_.size();
  4448. for (size_t i=0; i<maxWorksheets; ++i)
  4449. {
  4450. if (!(workbook_.boundSheets_[i].name_.unicode_ & 1)) continue;
  4451. if (wcscmp(from, workbook_.boundSheets_[i].name_.wname_) == 0)
  4452. {
  4453. for (size_t j=0; j<maxWorksheets; ++j)
  4454. {
  4455. if (!(workbook_.boundSheets_[j].name_.unicode_ & 1)) continue;
  4456. if (wcscmp(to, workbook_.boundSheets_[j].name_.wname_) == 0) return false;
  4457. }
  4458. workbook_.boundSheets_[i].name_ = to;
  4459. return true;
  4460. }
  4461. }
  4462. return false;
  4463. }
  4464. size_t BasicExcel::Read(const char* data, size_t dataSize)
  4465. {
  4466. size_t bytesRead = 0;
  4467. BOF bof;
  4468. short code;
  4469. LittleEndian::Read(data, code, 0, 2);
  4470. Record rec;
  4471. while (code == CODE::BOF)
  4472. {
  4473. bof.Read(data+bytesRead);
  4474. switch (bof.type_)
  4475. {
  4476. case 0x0005:
  4477. bytesRead += workbook_.Read(data+bytesRead);
  4478. break;
  4479. case 0x0006:
  4480. bytesRead += rec.Read(data+bytesRead);
  4481. break;
  4482. case 0x0010:
  4483. worksheets_.push_back(Worksheet());
  4484. bytesRead += worksheets_.back().Read(data+bytesRead);
  4485. break;
  4486. case 0x0020:
  4487. bytesRead += rec.Read(data+bytesRead);
  4488. break;
  4489. default:
  4490. bytesRead += rec.Read(data+bytesRead);
  4491. break;
  4492. }
  4493. if (bytesRead < dataSize) LittleEndian::Read(data, code, bytesRead, 2);
  4494. else break;
  4495. }
  4496. return bytesRead;
  4497. }
  4498. size_t BasicExcel::Write(char* data)
  4499. {
  4500. size_t bytesWritten = 0;
  4501. bytesWritten += workbook_.Write(data+bytesWritten);
  4502. size_t maxWorkSheets = worksheets_.size();
  4503. for (size_t i=0; i<maxWorkSheets; ++i)
  4504. {
  4505. bytesWritten += worksheets_[i].Write(data+bytesWritten);
  4506. }
  4507. return bytesWritten;
  4508. }
  4509. void BasicExcel::AdjustStreamPositions()
  4510. {
  4511. // AdjustExtSSTPositions();
  4512. AdjustBoundSheetBOFPositions();
  4513. AdjustDBCellPositions();
  4514. }
  4515. void BasicExcel::AdjustBoundSheetBOFPositions()
  4516. {
  4517. size_t offset = workbook_.RecordSize();
  4518. size_t maxBoundSheets = workbook_.boundSheets_.size();
  4519. for (size_t i=0; i<maxBoundSheets; ++i)
  4520. {
  4521. workbook_.boundSheets_[i].BOFpos_ = offset;
  4522. offset += worksheets_[i].RecordSize();
  4523. }
  4524. }
  4525. void BasicExcel::AdjustDBCellPositions()
  4526. {
  4527. size_t offset = workbook_.RecordSize();
  4528. size_t maxSheets = worksheets_.size();
  4529. for (size_t i=0; i<maxSheets; ++i)
  4530. {
  4531. offset += worksheets_[i].bof_.RecordSize();
  4532. offset += worksheets_[i].index_.RecordSize();
  4533. offset += worksheets_[i].dimensions_.RecordSize();
  4534. size_t maxRowBlocks_ = worksheets_[i].cellTable_.rowBlocks_.size();
  4535. for (size_t j=0; j<maxRowBlocks_; ++j)
  4536. {
  4537. size_t firstRowOffset = 0;
  4538. size_t maxRows = worksheets_[i].cellTable_.rowBlocks_[j].rows_.size();
  4539. {for (size_t k=0; k<maxRows; ++k)
  4540. {
  4541. offset += worksheets_[i].cellTable_.rowBlocks_[j].rows_[k].RecordSize();
  4542. firstRowOffset += worksheets_[i].cellTable_.rowBlocks_[j].rows_[k].RecordSize();
  4543. }}
  4544. size_t cellOffset = firstRowOffset - 20; // a ROW record is 20 bytes long
  4545. size_t maxCellBlocks = worksheets_[i].cellTable_.rowBlocks_[j].cellBlocks_.size();
  4546. {for (size_t k=0; k<maxCellBlocks; ++k)
  4547. {
  4548. offset += worksheets_[i].cellTable_.rowBlocks_[j].cellBlocks_[k].RecordSize();
  4549. firstRowOffset += worksheets_[i].cellTable_.rowBlocks_[j].cellBlocks_[k].RecordSize();
  4550. }}
  4551. // Adjust Index DBCellPos_ absolute offset
  4552. worksheets_[i].index_.DBCellPos_[j] = offset;
  4553. offset += worksheets_[i].cellTable_.rowBlocks_[j].dbcell_.RecordSize();
  4554. // Adjust DBCell first row offsets
  4555. worksheets_[i].cellTable_.rowBlocks_[j].dbcell_.firstRowOffset_ = firstRowOffset;
  4556. // Adjust DBCell offsets
  4557. size_t l=0;
  4558. {for (size_t k=0; k<maxRows; ++k)
  4559. {
  4560. for (; l<maxCellBlocks; ++l)
  4561. {
  4562. if (worksheets_[i].cellTable_.rowBlocks_[j].rows_[k].rowIndex_ <=
  4563. worksheets_[i].cellTable_.rowBlocks_[j].cellBlocks_[l].RowIndex())
  4564. {
  4565. worksheets_[i].cellTable_.rowBlocks_[j].dbcell_.offsets_[k] = cellOffset;
  4566. break;
  4567. }
  4568. cellOffset += worksheets_[i].cellTable_.rowBlocks_[j].cellBlocks_[l].RecordSize();
  4569. }
  4570. cellOffset = 0;
  4571. }}
  4572. }
  4573. offset += worksheets_[i].cellTable_.RecordSize();
  4574. offset += worksheets_[i].window2_.RecordSize();
  4575. offset += worksheets_[i].eof_.RecordSize();
  4576. }
  4577. }
  4578. void BasicExcel::AdjustExtSSTPositions()
  4579. {
  4580. size_t offset = workbook_.bof_.RecordSize();
  4581. offset += workbook_.bof_.RecordSize();
  4582. offset += workbook_.window1_.RecordSize();
  4583. size_t maxFonts = workbook_.fonts_.size();
  4584. {for (size_t i=0; i<maxFonts; ++i) {offset += workbook_.fonts_[i].RecordSize();}}
  4585. size_t maxXFs = workbook_.XFs_.size();
  4586. {for (size_t i=0; i<maxXFs; ++i) {offset += workbook_.XFs_[i].RecordSize();}}
  4587. size_t maxStyles = workbook_.styles_.size();
  4588. {for (size_t i=0; i<maxStyles; ++i) {offset += workbook_.styles_[i].RecordSize();}}
  4589. size_t maxBoundSheets = workbook_.boundSheets_.size();
  4590. {for (size_t i=0; i<maxBoundSheets; ++i) {offset += workbook_.boundSheets_[i].RecordSize();}}
  4591. workbook_.extSST_.stringsTotal_ = 10;
  4592. size_t maxPortions = workbook_.sst_.uniqueStringsTotal_ / workbook_.extSST_.stringsTotal_ +
  4593. (workbook_.sst_.uniqueStringsTotal_%workbook_.extSST_.stringsTotal_ ? 1 : 0);
  4594. workbook_.extSST_.streamPos_.resize(maxPortions);
  4595. workbook_.extSST_.firstStringPos_.resize(maxPortions);
  4596. workbook_.extSST_.unused_.resize(maxPortions);
  4597. size_t relativeOffset = 8;
  4598. for (size_t i=0; i<maxPortions; ++i)
  4599. {
  4600. workbook_.extSST_.streamPos_[i] = offset + 4 + relativeOffset;
  4601. workbook_.extSST_.firstStringPos_[i] = 4 + relativeOffset;
  4602. workbook_.extSST_.unused_[i] = 0;
  4603. for (size_t j=0; j<workbook_.extSST_.stringsTotal_; ++j)
  4604. {
  4605. if (i*workbook_.extSST_.stringsTotal_+j >= workbook_.sst_.strings_.size()) break;
  4606. size_t stringSize = workbook_.sst_.strings_[i*workbook_.extSST_.stringsTotal_+j].StringSize();
  4607. if (relativeOffset+stringSize+3 < 8224)
  4608. {
  4609. relativeOffset += stringSize + 3;
  4610. }
  4611. else
  4612. {
  4613. // If have >= 12 bytes (2 for size, 1 for unicode and >=9 for data, can split string
  4614. // otherwise, end record and start continue record.
  4615. if (8224 - relativeOffset >= 12)
  4616. {
  4617. stringSize -= (8224 - relativeOffset - 3);
  4618. offset += 12 + relativeOffset;
  4619. relativeOffset = 0;
  4620. size_t additionalContinueRecords = stringSize / 8223; // 8223 because the first byte is for unicode
  4621. for (size_t k=0; k<additionalContinueRecords; ++k)
  4622. {
  4623. stringSize -= 8223;
  4624. }
  4625. relativeOffset += stringSize + 1;
  4626. }
  4627. else
  4628. {
  4629. if (relativeOffset+stringSize+3 < 8224)
  4630. {
  4631. relativeOffset += stringSize + 3;
  4632. }
  4633. else
  4634. {
  4635. // If have >= 12 bytes (2 for size, 1 for unicode and >=9 for data, can split string
  4636. // otherwise, end record and start continue record.
  4637. if (8224 - relativeOffset >= 12)
  4638. {
  4639. stringSize -= (8224 - relativeOffset - 3);
  4640. offset += 12 + relativeOffset;
  4641. relativeOffset = 0;
  4642. size_t additionalContinueRecords = stringSize / 8223; // 8223 because the first byte is for unicode
  4643. for (size_t k=0; k<additionalContinueRecords; ++k)
  4644. {
  4645. stringSize -= 8223;
  4646. }
  4647. relativeOffset += stringSize + 1;
  4648. }
  4649. }
  4650. }
  4651. }
  4652. }
  4653. }
  4654. }
  4655. // Update yesheets_ using information from worksheets_.
  4656. void BasicExcel::UpdateYExcelWorksheet()
  4657. {
  4658. size_t maxWorksheets = worksheets_.size();
  4659. yesheets_.clear();
  4660. yesheets_.reserve(maxWorksheets);
  4661. for (size_t i=0; i<maxWorksheets; ++i)
  4662. {
  4663. yesheets_.push_back(BasicExcelWorksheet(this,i));
  4664. }
  4665. }
  4666. // Update worksheets_ using information from yesheets_.
  4667. void BasicExcel::UpdateWorksheets()
  4668. {
  4669. // Constants.
  4670. const size_t maxWorksheets = yesheets_.size();
  4671. Worksheet::CellTable::RowBlock rowBlock;
  4672. Worksheet::CellTable::RowBlock::CellBlock cellBlock;
  4673. Worksheet::CellTable::RowBlock::Row row;
  4674. Worksheet::CellTable::RowBlock::CellBlock::MulRK::XFRK xfrk;
  4675. LargeString largeString;
  4676. map<vector<char>, size_t> stringMap;
  4677. map<vector<char>, size_t>::iterator stringMapIt;
  4678. map<vector<wchar_t>, size_t> wstringMap;
  4679. map<vector<wchar_t>, size_t>::iterator wstringMapIt;
  4680. // Reset worksheets and string table.
  4681. worksheets_.clear();
  4682. worksheets_.resize(maxWorksheets);
  4683. workbook_.sst_.stringsTotal_ = 0;
  4684. workbook_.sst_.uniqueStringsTotal_ = 0;
  4685. workbook_.sst_.strings_.clear();
  4686. for (size_t s=0; s<maxWorksheets; ++s)
  4687. {
  4688. size_t maxRows = yesheets_[s].GetTotalRows();
  4689. size_t maxCols = yesheets_[s].GetTotalCols();
  4690. // Modify Index
  4691. worksheets_[s].index_.firstUsedRowIndex_ = 100000; // Use 100000 to indicate that firstUsedRowIndex is not set yet since maximum allowed rows in Excel is 65535.
  4692. worksheets_[s].index_.firstUnusedRowIndex_ = maxRows;
  4693. // Modify Dimensions
  4694. worksheets_[s].dimensions_.firstUsedRowIndex_ = 100000; // Use 100000 to indicate that firstUsedRowIndex is not set yet since maximum allowed rows in Excel is 65535.
  4695. worksheets_[s].dimensions_.firstUsedColIndex_ = 1000; // Use 1000 to indicate that firstUsedColIndex is not set yet since maximum allowed columns in Excel is 255.
  4696. worksheets_[s].dimensions_.lastUsedRowIndexPlusOne_ = maxRows;
  4697. worksheets_[s].dimensions_.lastUsedColIndexPlusOne_ = maxCols;
  4698. // Make first sheet selected and other sheets unselected
  4699. if (s > 0) worksheets_[s].window2_.options_ &= ~0x200;
  4700. // References and pointers to shorten code
  4701. vector<Worksheet::CellTable::RowBlock>& rRowBlocks = worksheets_[s].cellTable_.rowBlocks_;
  4702. vector<Worksheet::CellTable::RowBlock::CellBlock>* pCellBlocks;
  4703. Worksheet::CellTable::RowBlock::CellBlock* pCell;
  4704. rRowBlocks.resize(maxRows/32 + (maxRows%32 ? 1 : 0));
  4705. for (size_t r=0, curRowBlock=0; r<maxRows; ++r)
  4706. {
  4707. if (r%32==0)
  4708. {
  4709. // New row block for every 32 rows.
  4710. pCellBlocks = &(rRowBlocks[curRowBlock++].cellBlocks_);
  4711. }
  4712. bool newRow = true; // Keep track whether current row contains data.
  4713. pCellBlocks->reserve(1000);
  4714. for (size_t c=0; c<maxCols; ++c)
  4715. {
  4716. BasicExcelCell* cell = yesheets_[s].Cell(r,c);
  4717. int cellType = cell->Type();
  4718. if (cellType != BasicExcelCell::UNDEFINED) // Current cell contains some data
  4719. {
  4720. if (worksheets_[s].index_.firstUsedRowIndex_ == 100000)
  4721. {
  4722. // Set firstUsedRowIndex.
  4723. worksheets_[s].index_.firstUsedRowIndex_ = r;
  4724. worksheets_[s].dimensions_.firstUsedRowIndex_ = r;
  4725. // Resize DBCellPos.
  4726. size_t nm = int(worksheets_[s].index_.firstUnusedRowIndex_ - worksheets_[s].index_.firstUsedRowIndex_ - 1) / 32 + 1;
  4727. worksheets_[s].index_.DBCellPos_.resize(nm);
  4728. }
  4729. if (worksheets_[s].dimensions_.firstUsedColIndex_ == 1000)
  4730. {
  4731. // Set firstUsedColIndex.
  4732. worksheets_[s].dimensions_.firstUsedColIndex_ = c;
  4733. }
  4734. if (newRow)
  4735. {
  4736. // Prepare Row and DBCell for new row with data.
  4737. Worksheet::CellTable::RowBlock& rRowBlock = rRowBlocks[curRowBlock-1];
  4738. rRowBlock.rows_.push_back(row);
  4739. rRowBlock.rows_.back().rowIndex_ = r;
  4740. rRowBlock.rows_.back().lastCellColIndexPlusOne_ = maxCols;
  4741. rRowBlock.dbcell_.offsets_.push_back(0);
  4742. newRow = false;
  4743. }
  4744. // Create new cellblock to store cell.
  4745. pCellBlocks->push_back(cellBlock);
  4746. if (pCellBlocks->size()%1000==0) pCellBlocks->reserve(pCellBlocks->size()+1000);
  4747. pCell = &(pCellBlocks->back());
  4748. // Store cell.
  4749. switch(cellType)
  4750. {
  4751. case BasicExcelCell::INT:
  4752. {
  4753. // Check whether it is a single cell or range of cells.
  4754. size_t cl = c + 1;
  4755. for (; cl<maxCols; ++cl)
  4756. {
  4757. BasicExcelCell* cellNext = yesheets_[s].Cell(r,cl);
  4758. if (cellNext->Type()==BasicExcelCell::UNDEFINED ||
  4759. cellNext->Type()!=cell->Type()) break;
  4760. }
  4761. if (cl > c+1)
  4762. {
  4763. // MULRK cells
  4764. pCell->type_ = CODE::MULRK;
  4765. pCell->normalType_ = true;
  4766. pCell->mulrk_.rowIndex_ = r;
  4767. pCell->mulrk_.firstColIndex_ = c;
  4768. pCell->mulrk_.lastColIndex_ = cl - 1;
  4769. pCell->mulrk_.XFRK_.resize(cl-c);
  4770. for (size_t i=0; c<cl; ++c, ++i)
  4771. {
  4772. cell = yesheets_[s].Cell(r,c);
  4773. pCell->mulrk_.XFRK_[i].RKValue_ = GetRKValueFromInteger(cell->GetInteger());
  4774. }
  4775. --c;
  4776. }
  4777. else
  4778. {
  4779. // Single cell
  4780. pCell->normalType_ = true;
  4781. pCell->type_ = CODE::RK;
  4782. pCell->rk_.rowIndex_ = r;
  4783. pCell->rk_.colIndex_ = c;
  4784. pCell->rk_.value_ = GetRKValueFromInteger(cell->GetInteger());
  4785. }
  4786. break;
  4787. }
  4788. case BasicExcelCell::DOUBLE:
  4789. {
  4790. // Check whether it is a single cell or range of cells.
  4791. // Double values which cannot be stored as RK values will be stored as single cells.
  4792. bool canStoreAsRKValue = CanStoreAsRKValue(cell->GetDouble());
  4793. size_t cl = c + 1;
  4794. for (; cl<maxCols; ++cl)
  4795. {
  4796. BasicExcelCell* cellNext = yesheets_[s].Cell(r,cl);
  4797. if (cellNext->Type()==BasicExcelCell::UNDEFINED ||
  4798. cellNext->Type()!=cell->Type() ||
  4799. canStoreAsRKValue!=CanStoreAsRKValue(cellNext->GetDouble())) break;
  4800. }
  4801. if (cl > c+1 && canStoreAsRKValue)
  4802. {
  4803. // MULRK cells
  4804. pCell->type_ = CODE::MULRK;
  4805. pCell->normalType_ = true;
  4806. pCell->mulrk_.rowIndex_ = r;
  4807. pCell->mulrk_.firstColIndex_ = c;
  4808. pCell->mulrk_.lastColIndex_ = cl - 1;
  4809. pCell->mulrk_.XFRK_.resize(cl-c);
  4810. for (size_t i=0; c<cl; ++c, ++i)
  4811. {
  4812. cell = yesheets_[s].Cell(r,c);
  4813. pCell->mulrk_.XFRK_[i].RKValue_ = GetRKValueFromDouble(cell->GetDouble());
  4814. }
  4815. --c;
  4816. }
  4817. else
  4818. {
  4819. // Single cell
  4820. pCell->normalType_ = true;
  4821. if (canStoreAsRKValue)
  4822. {
  4823. pCell->type_ = CODE::RK;
  4824. pCell->rk_.rowIndex_ = r;
  4825. pCell->rk_.colIndex_ = c;
  4826. pCell->rk_.value_ = GetRKValueFromDouble(cell->GetDouble());
  4827. }
  4828. else
  4829. {
  4830. pCell->type_ = CODE::NUMBER;
  4831. pCell->number_.rowIndex_ = r;
  4832. pCell->number_.colIndex_ = c;
  4833. pCell->number_.value_ = cell->GetDouble();
  4834. }
  4835. }
  4836. break;
  4837. }
  4838. case BasicExcelCell::STRING:
  4839. {
  4840. // Fill cell information
  4841. pCell->type_ = CODE::LABELSST;
  4842. pCell->normalType_ = true;
  4843. pCell->labelsst_.rowIndex_ = r;
  4844. pCell->labelsst_.colIndex_ = c;
  4845. // Get cell string
  4846. vector<char> str(cell->GetStringLength()+1);
  4847. cell->Get(&*(str.begin()));
  4848. str.pop_back(); // Remove null character because LargeString does not store null character.
  4849. // Check if string is present in Shared string table.
  4850. ++workbook_.sst_.stringsTotal_;
  4851. size_t maxUniqueStrings = workbook_.sst_.uniqueStringsTotal_;
  4852. size_t strIndex = 0;
  4853. stringMapIt = stringMap.find(str);
  4854. if (stringMapIt != stringMap.end()) strIndex = stringMapIt->second;
  4855. else strIndex = maxUniqueStrings;
  4856. if (strIndex < maxUniqueStrings)
  4857. {
  4858. // String is present in Shared string table.
  4859. pCell->labelsst_.SSTRecordIndex_ = strIndex;
  4860. }
  4861. else
  4862. {
  4863. // New unique string.
  4864. stringMap[str] = maxUniqueStrings;
  4865. workbook_.sst_.strings_.push_back(largeString);
  4866. workbook_.sst_.strings_[maxUniqueStrings].name_ = str;
  4867. workbook_.sst_.strings_[maxUniqueStrings].unicode_ = 0;
  4868. pCell->labelsst_.SSTRecordIndex_ = maxUniqueStrings;
  4869. ++workbook_.sst_.uniqueStringsTotal_;
  4870. }
  4871. break;
  4872. }
  4873. case BasicExcelCell::WSTRING:
  4874. {
  4875. // Fill cell information
  4876. pCell->type_ = CODE::LABELSST;
  4877. pCell->normalType_ = true;
  4878. pCell->labelsst_.rowIndex_ = r;
  4879. pCell->labelsst_.colIndex_ = c;
  4880. // Get cell string
  4881. vector<wchar_t> str(cell->GetStringLength()+1);
  4882. cell->Get(&*(str.begin()));
  4883. str.pop_back(); // Remove null character because LargeString does not store null character.
  4884. // Check if string is present in Shared string table.
  4885. ++workbook_.sst_.stringsTotal_;
  4886. size_t maxUniqueStrings = workbook_.sst_.strings_.size();
  4887. size_t strIndex = 0;
  4888. wstringMapIt = wstringMap.find(str);
  4889. if (wstringMapIt != wstringMap.end()) strIndex = wstringMapIt->second;
  4890. else strIndex = maxUniqueStrings;
  4891. if (strIndex < maxUniqueStrings)
  4892. {
  4893. // String is present in Shared string table.
  4894. pCell->labelsst_.SSTRecordIndex_ = strIndex;
  4895. }
  4896. else
  4897. {
  4898. // New unique string
  4899. wstringMap[str] = maxUniqueStrings;
  4900. workbook_.sst_.strings_.push_back(largeString);
  4901. workbook_.sst_.strings_[maxUniqueStrings].wname_ = str;
  4902. workbook_.sst_.strings_[maxUniqueStrings].unicode_ = 1;
  4903. pCell->labelsst_.SSTRecordIndex_ = maxUniqueStrings;
  4904. ++workbook_.sst_.uniqueStringsTotal_;
  4905. }
  4906. break;
  4907. }
  4908. }
  4909. }
  4910. }
  4911. }
  4912. // If worksheet has no data
  4913. if (worksheets_[s].index_.firstUsedRowIndex_ == 100000)
  4914. {
  4915. // Set firstUsedRowIndex.
  4916. worksheets_[s].index_.firstUsedRowIndex_ = 0;
  4917. worksheets_[s].dimensions_.firstUsedRowIndex_ = 0;
  4918. // Resize DBCellPos.
  4919. size_t nm = int(worksheets_[s].index_.firstUnusedRowIndex_ - worksheets_[s].index_.firstUsedRowIndex_ - 1) / 32 + 1;
  4920. worksheets_[s].index_.DBCellPos_.resize(nm);
  4921. }
  4922. if (worksheets_[s].dimensions_.firstUsedColIndex_ == 1000)
  4923. {
  4924. // Set firstUsedColIndex.
  4925. worksheets_[s].dimensions_.firstUsedColIndex_ = 0;
  4926. }
  4927. }
  4928. }
  4929. /************************************************************************************************************/
  4930. /************************************************************************************************************/
  4931. BasicExcelWorksheet::BasicExcelWorksheet(BasicExcel* excel, size_t sheetIndex) :
  4932. excel_(excel), sheetIndex_(sheetIndex)
  4933. {
  4934. UpdateCells();
  4935. }
  4936. // Get the current worksheet name.
  4937. // Returns 0 if name is in Unicode format.
  4938. char* BasicExcelWorksheet::GetAnsiSheetName()
  4939. {
  4940. if (!(excel_->workbook_.boundSheets_[sheetIndex_].name_.unicode_ & 1))
  4941. {
  4942. return excel_->workbook_.boundSheets_[sheetIndex_].name_.name_;
  4943. }
  4944. else return 0;
  4945. }
  4946. // Get the current worksheet name.
  4947. // Returns 0 if name is in Ansi format.
  4948. wchar_t* BasicExcelWorksheet::GetUnicodeSheetName()
  4949. {
  4950. if (excel_->workbook_.boundSheets_[sheetIndex_].name_.unicode_ & 1)
  4951. {
  4952. return excel_->workbook_.boundSheets_[sheetIndex_].name_.wname_;
  4953. }
  4954. else return 0;
  4955. }
  4956. // Get the current worksheet name.
  4957. // Returns false if name is in Unicode format.
  4958. bool BasicExcelWorksheet::GetSheetName(char* name)
  4959. {
  4960. if (!(excel_->workbook_.boundSheets_[sheetIndex_].name_.unicode_ & 1))
  4961. {
  4962. strcpy(name, excel_->workbook_.boundSheets_[sheetIndex_].name_.name_);
  4963. return true;
  4964. }
  4965. else return false;
  4966. }
  4967. // Get the current worksheet name.
  4968. // Returns false if name is in Ansi format.
  4969. bool BasicExcelWorksheet::GetSheetName(wchar_t* name)
  4970. {
  4971. if (excel_->workbook_.boundSheets_[sheetIndex_].name_.unicode_ & 1)
  4972. {
  4973. wcscpy(name, excel_->workbook_.boundSheets_[sheetIndex_].name_.wname_);
  4974. return true;
  4975. }
  4976. else return false;
  4977. }
  4978. // Rename current Excel worksheet to another ANSI name.
  4979. // Returns true if successful, false if otherwise.
  4980. bool BasicExcelWorksheet::Rename(const char* to)
  4981. {
  4982. size_t maxWorksheets = excel_->workbook_.boundSheets_.size();
  4983. for (size_t i=0; i<maxWorksheets; ++i)
  4984. {
  4985. if (excel_->workbook_.boundSheets_[i].name_.unicode_ & 1) continue;
  4986. if (strcmp(to, excel_->workbook_.boundSheets_[i].name_.name_) == 0) return false;
  4987. }
  4988. excel_->workbook_.boundSheets_[sheetIndex_].name_ = to;
  4989. return true;
  4990. }
  4991. // Rename current Excel worksheet to another Unicode name.
  4992. // Returns true if successful, false if otherwise.
  4993. bool BasicExcelWorksheet::Rename(const wchar_t* to)
  4994. {
  4995. size_t maxWorksheets = excel_->workbook_.boundSheets_.size();
  4996. for (size_t i=0; i<maxWorksheets; ++i)
  4997. {
  4998. if (!(excel_->workbook_.boundSheets_[i].name_.unicode_ & 1)) continue;
  4999. if (wcscmp(to, excel_->workbook_.boundSheets_[i].name_.wname_) == 0) return false;
  5000. }
  5001. excel_->workbook_.boundSheets_[sheetIndex_].name_ = to;
  5002. return true;
  5003. }
  5004. ///< Print entire worksheet to an output stream, separating each column with the defined delimiter and enclosing text using the defined textQualifier.
  5005. ///< Leave out the textQualifier argument if do not wish to have any text qualifiers.
  5006. void BasicExcelWorksheet::Print(ostream& os, char delimiter, char textQualifier)
  5007. {
  5008. for (size_t r=0; r<maxRows_; ++r)
  5009. {
  5010. for (size_t c=0; c<maxCols_; ++c)
  5011. {
  5012. BasicExcelCell* cell = Cell(r,c);
  5013. switch (cell->Type())
  5014. {
  5015. case BasicExcelCell::UNDEFINED:
  5016. break;
  5017. case BasicExcelCell::INT:
  5018. os << cell->GetInteger();
  5019. break;
  5020. case BasicExcelCell::DOUBLE:
  5021. os << setprecision(15) << cell->GetDouble();
  5022. break;
  5023. case BasicExcelCell::STRING:
  5024. {
  5025. if (textQualifier != '\0')
  5026. {
  5027. // Get string.
  5028. size_t maxLength = cell->GetStringLength();
  5029. vector<char> cellString(maxLength+1);
  5030. cell->Get(&*(cellString.begin()));
  5031. // Duplicate textQualifier if found in string.
  5032. vector<char>::iterator it;
  5033. size_t npos = 0;
  5034. while ((it=find(cellString.begin()+npos, cellString.end(), textQualifier)) != cellString.end())
  5035. {
  5036. npos = distance(cellString.begin(), cellString.insert(it, textQualifier)) + 2;
  5037. }
  5038. // Print out string enclosed with textQualifier.
  5039. os << textQualifier << &*(cellString.begin()) << textQualifier;
  5040. }
  5041. else os << cell->GetString();
  5042. break;
  5043. }
  5044. case BasicExcelCell::WSTRING:
  5045. {
  5046. // Print out string enclosed with textQualifier (does not work).
  5047. //os << textQualifier << cell->GetWString() << textQualifier;
  5048. break;
  5049. }
  5050. }
  5051. if (c < maxCols_-1) os << delimiter;
  5052. }
  5053. os << endl;
  5054. }
  5055. }
  5056. // Total number of rows in current Excel worksheet.
  5057. size_t BasicExcelWorksheet::GetTotalRows()
  5058. {
  5059. return maxRows_;
  5060. }
  5061. // Total number of columns in current Excel worksheet.
  5062. size_t BasicExcelWorksheet::GetTotalCols()
  5063. {
  5064. return maxCols_;
  5065. }
  5066. // Return a pointer to an Excel cell.
  5067. // row and col starts from 0.
  5068. // Returns 0 if row exceeds 65535 or col exceeds 255.
  5069. BasicExcelCell* BasicExcelWorksheet::Cell(size_t row, size_t col)
  5070. {
  5071. // Check to ensure row and col does not exceed maximum allowable range for an Excel worksheet.
  5072. if (row>65535 || col>255) return 0;
  5073. // Increase size of cells matrix if necessary
  5074. if (col>=maxCols_)
  5075. {
  5076. // Increase number of columns.
  5077. maxCols_ = col + 1;
  5078. for (size_t i=0; i<maxRows_; ++i) cells_[i].resize(maxCols_);
  5079. }
  5080. if (row>=maxRows_)
  5081. {
  5082. // Increase number of rows.
  5083. maxRows_ = row + 1;
  5084. cells_.resize(maxRows_, vector<BasicExcelCell>(maxCols_));
  5085. }
  5086. return &(cells_[row][col]);
  5087. }
  5088. // Erase content of a cell. row and col starts from 0.
  5089. // Returns true if successful, false if row or col exceeds range.
  5090. bool BasicExcelWorksheet::EraseCell(size_t row, size_t col)
  5091. {
  5092. if (row<maxRows_ && col<maxCols_)
  5093. {
  5094. cells_[row][col].EraseContents();
  5095. return true;
  5096. }
  5097. else return false;
  5098. }
  5099. // Update cells using information from BasicExcel.worksheets_.
  5100. void BasicExcelWorksheet::UpdateCells()
  5101. {
  5102. // Define some reference
  5103. Worksheet::Dimensions& dimension = excel_->worksheets_[sheetIndex_].dimensions_;
  5104. vector<Worksheet::CellTable::RowBlock>& rRowBlocks = excel_->worksheets_[sheetIndex_].cellTable_.rowBlocks_;
  5105. vector<wchar_t> wstr;
  5106. vector<char> str;
  5107. maxRows_ = dimension.lastUsedRowIndexPlusOne_;
  5108. maxCols_ = dimension.lastUsedColIndexPlusOne_;
  5109. // Resize the cells to the size of the worksheet
  5110. vector<BasicExcelCell> cellCol(maxCols_);
  5111. cells_.resize(maxRows_, cellCol);
  5112. size_t maxRowBlocks = rRowBlocks.size();
  5113. for (size_t i=0; i<maxRowBlocks; ++i)
  5114. {
  5115. vector<Worksheet::CellTable::RowBlock::CellBlock>& rCellBlocks = rRowBlocks[i].cellBlocks_;
  5116. size_t maxCells = rCellBlocks.size();
  5117. for (size_t j=0; j<maxCells; ++j)
  5118. {
  5119. size_t row = rCellBlocks[j].RowIndex();
  5120. size_t col = rCellBlocks[j].ColIndex();
  5121. switch (rCellBlocks[j].type_)
  5122. {
  5123. case CODE::BLANK:
  5124. break;
  5125. case CODE::BOOLERR:
  5126. if (rCellBlocks[j].boolerr_.error_ == 0)
  5127. {
  5128. cells_[row][col].Set(rCellBlocks[j].boolerr_.code_);
  5129. }
  5130. break;
  5131. case CODE::LABELSST:
  5132. {
  5133. vector<LargeString>& ss = excel_->workbook_.sst_.strings_;
  5134. if (ss[rCellBlocks[j].labelsst_.SSTRecordIndex_].unicode_ & 1)
  5135. {
  5136. wstr = ss[rCellBlocks[j].labelsst_.SSTRecordIndex_].wname_;
  5137. wstr.resize(wstr.size()+1);
  5138. wstr.back() = L'\0';
  5139. cells_[row][col].Set(&*(wstr.begin()));
  5140. }
  5141. else
  5142. {
  5143. str = ss[rCellBlocks[j].labelsst_.SSTRecordIndex_].name_;
  5144. str.resize(str.size()+1);
  5145. str.back() = '\0';
  5146. cells_[row][col].Set(&*(str.begin()));
  5147. }
  5148. break;
  5149. }
  5150. case CODE::MULBLANK:
  5151. break;
  5152. case CODE::MULRK:
  5153. {
  5154. size_t maxCols = rCellBlocks[j].mulrk_.lastColIndex_ - rCellBlocks[j].mulrk_.firstColIndex_ + 1;
  5155. for (size_t k=0; k<maxCols; ++k, ++col)
  5156. {
  5157. // Get values of the whole range
  5158. int rkValue = rCellBlocks[j].mulrk_.XFRK_[k].RKValue_;
  5159. if (IsRKValueAnInteger(rkValue))
  5160. {
  5161. cells_[row][col].Set(GetIntegerFromRKValue(rkValue));
  5162. }
  5163. else
  5164. {
  5165. cells_[row][col].Set(GetDoubleFromRKValue(rkValue));
  5166. }
  5167. }
  5168. break;
  5169. }
  5170. case CODE::NUMBER:
  5171. cells_[row][col].Set(rCellBlocks[j].number_.value_);
  5172. break;
  5173. case CODE::RK:
  5174. {
  5175. int rkValue = rCellBlocks[j].rk_.value_;
  5176. if (IsRKValueAnInteger(rkValue))
  5177. {
  5178. cells_[row][col].Set(GetIntegerFromRKValue(rkValue));
  5179. }
  5180. else
  5181. {
  5182. cells_[row][col].Set(GetDoubleFromRKValue(rkValue));
  5183. }
  5184. break;
  5185. }
  5186. case CODE::FORMULA:
  5187. break;
  5188. }
  5189. }
  5190. }
  5191. }
  5192. /************************************************************************************************************/
  5193. /************************************************************************************************************/
  5194. BasicExcelCell::BasicExcelCell() : type_(UNDEFINED) {};
  5195. // Get type of value stored in current Excel cell.
  5196. // Returns one of the enums.
  5197. int BasicExcelCell::Type() const {return type_;}
  5198. // Get an integer value.
  5199. // Returns false if cell does not contain an integer or a double.
  5200. bool BasicExcelCell::Get(int& val) const
  5201. {
  5202. if (type_ == INT)
  5203. {
  5204. val = ival_;
  5205. return true;
  5206. }
  5207. else if (type_ == DOUBLE)
  5208. {
  5209. val = (int)dval_;
  5210. return true;
  5211. }
  5212. else return false;
  5213. }
  5214. // Get a double value.
  5215. // Returns false if cell does not contain a double or an integer.
  5216. bool BasicExcelCell::Get(double& val) const
  5217. {
  5218. if (type_ == DOUBLE)
  5219. {
  5220. val = dval_;
  5221. return true;
  5222. }
  5223. else if (type_ == INT)
  5224. {
  5225. val = (double)ival_;
  5226. return true;
  5227. }
  5228. else return false;
  5229. }
  5230. // Get an ANSI string.
  5231. // Returns false if cell does not contain an ANSI string.
  5232. bool BasicExcelCell::Get(char* str) const
  5233. {
  5234. if (type_ == STRING)
  5235. {
  5236. if (str_.empty()) *str = '\0';
  5237. else strcpy(str, &*(str_.begin()));
  5238. return true;
  5239. }
  5240. else return false;
  5241. }
  5242. // Get an Unicode string.
  5243. // Returns false if cell does not contain an Unicode string.
  5244. bool BasicExcelCell::Get(wchar_t* str) const
  5245. {
  5246. if (type_ == WSTRING)
  5247. {
  5248. if (wstr_.empty()) *str = L'\0';
  5249. else wcscpy(str, &*(wstr_.begin()));
  5250. return true;
  5251. }
  5252. else return false;
  5253. }
  5254. // Return length of ANSI or Unicode string (excluding null character).
  5255. size_t BasicExcelCell::GetStringLength() const
  5256. {
  5257. if (type_ == STRING) return str_.size() - 1;
  5258. else return wstr_.size() - 1;
  5259. }
  5260. // Get an integer value.
  5261. // Returns 0 if cell does not contain an integer.
  5262. int BasicExcelCell::GetInteger() const
  5263. {
  5264. int val;
  5265. if (Get(val)) return val;
  5266. else return 0;
  5267. }
  5268. // Get a double value.
  5269. // Returns 0.0 if cell does not contain a double.
  5270. double BasicExcelCell::GetDouble() const
  5271. {
  5272. double val;
  5273. if (Get(val)) return val;
  5274. else return 0.0;
  5275. }
  5276. // Get an ANSI string.
  5277. // Returns 0 if cell does not contain an ANSI string.
  5278. const char* BasicExcelCell::GetString() const
  5279. {
  5280. vector<char> str(str_.size());
  5281. if (!str.empty() && Get(&*(str.begin()))) return &*(str_.begin());
  5282. else return 0;
  5283. }
  5284. // Get an Unicode string.
  5285. // Returns 0 if cell does not contain an Unicode string.
  5286. const wchar_t* BasicExcelCell::GetWString() const
  5287. {
  5288. vector<wchar_t> wstr(wstr_.size());
  5289. if (!wstr.empty() && Get(&*(wstr.begin()))) return &*(wstr_.begin());
  5290. else return 0;
  5291. }
  5292. // Set content of current Excel cell to an integer.
  5293. void BasicExcelCell::Set(int val)
  5294. {
  5295. SetInteger(val);
  5296. }
  5297. // Set content of current Excel cell to a double.
  5298. void BasicExcelCell::Set(double val)
  5299. {
  5300. SetDouble(val);
  5301. }
  5302. // Set content of current Excel cell to an ANSI string.
  5303. void BasicExcelCell::Set(const char* str)
  5304. {
  5305. SetString(str);
  5306. }
  5307. // Set content of current Excel cell to an Unicode string.
  5308. void BasicExcelCell::Set(const wchar_t* str)
  5309. {
  5310. SetWString(str);
  5311. }
  5312. // Set content of current Excel cell to an integer.
  5313. void BasicExcelCell::SetInteger(int val)
  5314. {
  5315. type_ = INT;
  5316. ival_ = val;
  5317. }
  5318. // Set content of current Excel cell to a double.
  5319. void BasicExcelCell::SetDouble(double val)
  5320. {
  5321. type_ = DOUBLE;
  5322. dval_ = val;
  5323. }
  5324. // Set content of current Excel cell to an ANSI string.
  5325. void BasicExcelCell::SetString(const char* str)
  5326. {
  5327. size_t length = strlen(str);
  5328. if (length > 0)
  5329. {
  5330. type_ = STRING;
  5331. str_ = vector<char>(length+1);
  5332. strcpy(&*(str_.begin()), str);
  5333. wstr_.clear();
  5334. }
  5335. else EraseContents();
  5336. }
  5337. // Set content of current Excel cell to an Unicode string.
  5338. void BasicExcelCell::SetWString(const wchar_t* str)
  5339. {
  5340. size_t length = wcslen(str);
  5341. if (length > 0)
  5342. {
  5343. type_ = WSTRING;
  5344. wstr_ = vector<wchar_t>(length+1);
  5345. wcscpy(&*(wstr_.begin()), str);
  5346. str_.clear();
  5347. }
  5348. else EraseContents();
  5349. }
  5350. // Erase the content of current Excel cell.
  5351. // Set type to UNDEFINED.
  5352. void BasicExcelCell::EraseContents()
  5353. {
  5354. type_ = UNDEFINED;
  5355. str_.clear();
  5356. wstr_.clear();
  5357. }
  5358. ///< Print cell to output stream.
  5359. ///< Print a null character if cell is undefined.
  5360. ostream& operator<<(ostream& os, const BasicExcelCell& cell)
  5361. {
  5362. switch (cell.Type())
  5363. {
  5364. case BasicExcelCell::UNDEFINED:
  5365. os << '\0';
  5366. break;
  5367. case BasicExcelCell::INT:
  5368. os << cell.GetInteger();
  5369. break;
  5370. case BasicExcelCell::DOUBLE:
  5371. os << cell.GetDouble();
  5372. break;
  5373. case BasicExcelCell::STRING:
  5374. os << cell.GetString();
  5375. break;
  5376. case BasicExcelCell::WSTRING:
  5377. os << cell.GetWString();
  5378. break;
  5379. }
  5380. return os;
  5381. }
  5382. } // YExcel namespace end