BasicExcel.cpp 196 KB

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