BasicExcelVC6.cpp 182 KB

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