chmwriter.pas 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567
  1. { Copyright (C) <2005> <Andrew Haines> chmwriter.pas
  2. This library is free software; you can redistribute it and/or modify it
  3. under the terms of the GNU Library General Public License as published by
  4. the Free Software Foundation; either version 2 of the License, or (at your
  5. option) any later version.
  6. This program is distributed in the hope that it will be useful, but WITHOUT
  7. ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  8. FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
  9. for more details.
  10. You should have received a copy of the GNU Library General Public License
  11. along with this library; if not, write to the Free Software Foundation, Inc.,
  12. 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301, USA.
  13. }
  14. {
  15. See the file COPYING.FPC, included in this distribution,
  16. for details about the copyright.
  17. }
  18. unit chmwriter;
  19. {$MODE OBJFPC}{$H+}
  20. interface
  21. uses Generics.Collections,Classes, ChmBase, chmtypes, chmspecialfiles, HtmlIndexer, chmsitemap, contnrs, StreamEx, Avl_Tree, lzxcompressthread;
  22. Const
  23. DefaultHHC = 'Default.hhc';
  24. DefaultHHK = 'Default.hhk';
  25. Type
  26. TGetDataFunc = function (const DataName: String; out PathInChm: String; out FileName: String; var Stream: TStream): Boolean of object;
  27. // DataName : A FileName or whatever so that the getter can find and open the file to add
  28. // PathInChm: This is the absolute path in the archive. i.e. /home/user/helpstuff/
  29. // becomes '/' and /home/user/helpstuff/subfolder/ > /subfolder/
  30. // FileName : /home/user/helpstuff/index.html > index.html
  31. // Stream : the file opened with DataName should be written to this stream
  32. Type
  33. TStringIndex = Class // AVLTree needs wrapping in non automated reference type also used in filewriter.
  34. TheString : String;
  35. StrId : Integer;
  36. end;
  37. TUrlStrIndex = Class
  38. UrlStr : String;
  39. UrlStrId : Integer;
  40. end;
  41. { TITSFWriter }
  42. TITSFWriter = class(TObject)
  43. FOnLastFile: TNotifyEvent;
  44. private
  45. ForceExit: Boolean;
  46. FInternalFiles: TFileEntryList; // Contains a complete list of files in the chm including
  47. FFrameSize: LongWord; // uncompressed files and special internal files of the chm
  48. FCurrentStream: TStream; // used to buffer the files that are to be compressed
  49. FCurrentIndex: Integer;
  50. FOnGetFileData: TGetDataFunc;
  51. FSection0: TMemoryStream;
  52. FSection1: TStream; // Compressed Stream
  53. FSection1Size: QWord;
  54. FSection1ResetTable: TMemoryStream; // has a list of frame positions NOT window positions
  55. FDirectoryListings: TStream;
  56. FOutStream: TStream;
  57. FFileNames: TStrings;
  58. FDestroyStream: Boolean;
  59. FTempStream: TStream;
  60. FPostStream: TStream;
  61. FWindowSize: LongWord;
  62. FReadCompressedSize: QWord; // Current Size of Uncompressed data that went in Section1 (compressed)
  63. FPostStreamActive: Boolean;
  64. // Linear order of file
  65. ITSFHeader: TITSFHeader;
  66. HeaderSection0Table: TITSFHeaderEntry; // points to HeaderSection0
  67. HeaderSection1Table: TITSFHeaderEntry; // points to HeaderSection1
  68. HeaderSuffix: TITSFHeaderSuffix; //contains the offset of CONTENTSection0 from zero
  69. HeaderSection0: TITSPHeaderPrefix;
  70. HeaderSection1: TITSPHeader; // DirectoryListings header
  71. FReadmeMessage : String;
  72. FCores : integer;
  73. // DirectoryListings
  74. // CONTENT Section 0 (section 1 is contained in section 0)
  75. // EOF
  76. // end linear header parts
  77. procedure InitITSFHeader;
  78. procedure InitHeaderSectionTable;
  79. procedure SetTempRawStream(const AValue: TStream);
  80. procedure WriteHeader(Stream: TStream);
  81. procedure CreateDirectoryListings;
  82. procedure WriteDirectoryListings(Stream: TStream);
  83. procedure WriteInternalFilesBefore; virtual;
  84. procedure WriteInternalFilesAfter; virtual;
  85. procedure StartCompressingStream;
  86. procedure WriteREADMEFile;
  87. procedure WriteFinalCompressedFiles; virtual;
  88. procedure WriteSection0;
  89. procedure WriteSection1;
  90. procedure WriteDataSpaceFiles(const AStream: TStream);
  91. procedure FileAdded(AStream: TStream; const AEntry: TFileEntryRec); virtual;
  92. // callbacks for lzxcomp
  93. function AtEndOfData: Longbool;
  94. function GetData(Count: LongInt; Buffer: PByte): LongInt;
  95. function WriteCompressedData(Count: Longint; Buffer: Pointer): LongInt;
  96. procedure MarkFrame(UnCompressedTotal, CompressedTotal: LongWord);
  97. // end callbacks
  98. // callbacks for lzx compress threads
  99. function LTGetData(Sender: TLZXCompressor; WantedByteCount: Integer; Buffer: Pointer): Integer;
  100. function LTIsEndOfFile(Sender: TLZXCompressor): Boolean;
  101. procedure LTChunkDone(Sender: TLZXCompressor; CompressedSize: Integer; UncompressedSize: Integer; Buffer: Pointer);
  102. procedure LTMarkFrame(Sender: TLZXCompressor; CompressedTotal: Integer; UncompressedTotal: Integer);
  103. // end callbacks
  104. public
  105. constructor Create(AOutStream: TStream; FreeStreamOnDestroy: Boolean); virtual;
  106. destructor Destroy; override;
  107. procedure Execute;
  108. procedure AddStreamToArchive(AFileName, APath: String; AStream: TStream; Compress: Boolean = True);
  109. procedure PostAddStreamToArchive(AFileName, APath: String; AStream: TStream; Compress: Boolean = True);
  110. procedure LocaleToLanguageID(Locale: LongWord);
  111. function LocaleFromLanguageID: LongWord;
  112. property WindowSize: LongWord read FWindowSize write FWindowSize default 2; // in $8000 blocks
  113. property FrameSize: LongWord read FFrameSize write FFrameSize default 1; // in $8000 blocks
  114. property FilesToCompress: TStrings read FFileNames;
  115. property OnGetFileData: TGetDataFunc read FOnGetFileData write FOnGetFileData;
  116. property OnLastFile: TNotifyEvent read FOnLastFile write FOnLastFile;
  117. property OutStream: TStream read FOutStream;
  118. property TempRawStream: TStream read FTempStream write SetTempRawStream;
  119. property ReadmeMessage : String read fReadmeMessage write fReadmeMessage;
  120. property Cores : integer read fcores write fcores;
  121. { MS Locale ID code }
  122. property LocaleID: LongWord read LocaleFromLanguageID write LocaleToLanguageID;
  123. end;
  124. { TChmWriter }
  125. TChmWriter = class(TITSFWriter)
  126. private
  127. FHasBinaryTOC: Boolean;
  128. FHasBinaryIndex: Boolean;
  129. FDefaultFont: String;
  130. FDefaultPage: String;
  131. FFullTextSearch: Boolean;
  132. FFullTextSearchAvailable: Boolean;
  133. FSearchTitlesOnly: Boolean;
  134. FStringsStream: TMemoryStream; // the #STRINGS file
  135. FTopicsStream: TMemoryStream; // the #TOPICS file
  136. FURLTBLStream: TMemoryStream; // the #URLTBL file. has offsets of strings in URLSTR
  137. FURLSTRStream: TMemoryStream; // the #URLSTR file
  138. FFiftiMainStream: TMemoryStream;
  139. FContextStream: TMemoryStream; // the #IVB file
  140. FIDXHdrStream : TMemoryStream; // the #IDXHDR and chunk 13 in #SYSTEM
  141. FTitle: String;
  142. FHasTOC: Boolean;
  143. FHasIndex: Boolean;
  144. FIndexedFiles: TIndexedWordList;
  145. FAvlStrings : TAVLTree; // dedupe strings
  146. FAVLTopicdedupe : TAVlTree; // Topic deduping, if we load it both from hhp and TOC
  147. FAvlURLStr : TAVLTree; // dedupe urltbl + binindex must resolve URL to topicid
  148. FDictTopicsUrlInd : specialize TDictionary<string,integer>; // if url exists reuse topic.
  149. SpareString : TStringIndex;
  150. SpareUrlStr : TUrlStrIndex;
  151. FWindows : TObjectList;
  152. FDefaultWindow: String;
  153. FTocName : String;
  154. FIndexName : String;
  155. FMergeFiles : TStringList;
  156. FTocSM : TCHMSitemap;
  157. FHasKLinks : Boolean;
  158. FNrTopics : Integer;
  159. protected
  160. procedure FileAdded(AStream: TStream; const AEntry: TFileEntryRec); override;
  161. private
  162. procedure WriteInternalFilesBefore; override;
  163. procedure WriteInternalFilesAfter; override;
  164. procedure WriteFinalCompressedFiles; override;
  165. procedure WriteSYSTEM;
  166. procedure WriteITBITS;
  167. procedure WriteSTRINGS;
  168. procedure WriteTOPICS;
  169. procedure WriteIVB; // context ids
  170. procedure CreateIDXHDRStream;
  171. procedure WriteIDXHDR;
  172. procedure WriteURL_STR_TBL;
  173. procedure WriteOBJINST;
  174. procedure WriteFiftiMain;
  175. procedure WriteWindows;
  176. function AddString(AString: String): LongWord;
  177. function AddURL(AURL: String; TopicsIndex: DWord): LongWord;
  178. procedure CheckFileMakeSearchable(AStream: TStream; AFileEntry: TFileEntryRec);
  179. function AddTopic(ATitle,AnUrl:AnsiString;code:integer=-1):integer;
  180. function AddTopicindex(ATitle,AnUrl:AnsiString;code:integer=-1):integer;
  181. procedure ScanSitemap(asitemap:TCHMSiteMap);
  182. function NextTopicIndex: Integer;
  183. procedure Setwindows (AWindowList:TObjectList);
  184. procedure SetMergefiles(src:TStringList);
  185. public
  186. constructor Create(AOutStream: TStream; FreeStreamOnDestroy: Boolean); override;
  187. destructor Destroy; override;
  188. procedure AppendTOC(AStream: TStream);
  189. procedure AppendBinaryTOCFromSiteMap(ASiteMap: TChmSiteMap);
  190. procedure AppendBinaryIndexFromSiteMap(ASiteMap: TChmSiteMap;chw:boolean);
  191. procedure AppendBinaryTOCStream(AStream: TStream);
  192. procedure AppendBinaryIndexStream(IndexStream,DataStream,MapStream,Propertystream: TStream;chw:boolean);
  193. procedure AppendIndex(AStream: TStream);
  194. procedure AppendSearchDB(AName: String; AStream: TStream);
  195. procedure AddContext(AContext: DWord; ATopic: String);
  196. procedure AddDummyALink;
  197. property Title: String read FTitle write FTitle;
  198. property FullTextSearch: Boolean read FFullTextSearch write FFullTextSearch;
  199. property SearchTitlesOnly: Boolean read FSearchTitlesOnly write FSearchTitlesOnly;
  200. property HasBinaryTOC: Boolean read FHasBinaryTOC write FHasBinaryTOC;
  201. property HasBinaryIndex: Boolean read FHasBinaryIndex write FHasBinaryIndex;
  202. property DefaultFont: String read FDefaultFont write FDefaultFont;
  203. property DefaultPage: String read FDefaultPage write FDefaultPage;
  204. property Windows : TObjectlist read fwindows write setwindows;
  205. property TOCName : String read FTocName write FTocName;
  206. property IndexName : String read FIndexName write FIndexName;
  207. property DefaultWindow : string read fdefaultwindow write fdefaultwindow;
  208. property MergeFiles :TStringList read FMergeFiles write setmergefiles;
  209. property Tocsitemap :TChmSitemap read ftocsm write ftocsm;
  210. end;
  211. Function CompareStrings(Node1, Node2: Pointer): integer; // also used in filewriter
  212. implementation
  213. uses dateutils, sysutils, paslzxcomp, chmFiftiMain;
  214. const
  215. LZX_WINDOW_SIZE = 16; // 16 = 2 frames = 1 shl 16
  216. LZX_FRAME_SIZE = $8000;
  217. {$ifdef binindex}
  218. procedure logentry(s:string);
  219. begin
  220. Writeln(s);
  221. flush(stdout);
  222. end;
  223. {$endif}
  224. {$I chmobjinstconst.inc}
  225. Function CompareStrings(Node1, Node2: Pointer): integer;
  226. var n1,n2 : TStringIndex;
  227. begin
  228. n1:=TStringIndex(Node1); n2:=TStringIndex(Node2);
  229. Result := CompareText(n1.TheString, n2.TheString);
  230. if Result < 0 then Result := -1
  231. else if Result > 0 then Result := 1;
  232. end;
  233. Function CompareUrlStrs(Node1, Node2: Pointer): integer;
  234. var n1,n2 : TUrlStrIndex;
  235. begin
  236. n1:=TUrlStrIndex(Node1); n2:=TUrlStrIndex(Node2);
  237. Result := CompareText(n1.UrlStr, n2.UrlStr);
  238. if Result < 0 then Result := -1
  239. else if Result > 0 then Result := 1;
  240. end;
  241. { TChmWriter }
  242. procedure TITSFWriter.InitITSFHeader;
  243. begin
  244. with ITSFHeader do begin
  245. ITSFsig := ITSFFileSig;
  246. Version := NToLE(DWord(3));
  247. // we fix endian order when this is written to the stream
  248. HeaderLength := NToLE(DWord(SizeOf(TITSFHeader) + (SizeOf(TGuid)*2)+ (SizeOf(TITSFHeaderEntry)*2) + SizeOf(TITSFHeaderSuffix)));
  249. Unknown_1 := NToLE(DWord(1));
  250. TimeStamp:= NToBE(MilliSecondOfTheDay(Now)); //bigendian
  251. LanguageID := NToLE(DWord($0409)); // English / English_US
  252. end;
  253. end;
  254. procedure TITSFWriter.LocaleToLanguageID(Locale: LongWord);
  255. begin
  256. ITSFHeader.LanguageID := NToLE(Locale);
  257. end;
  258. function TITSFWriter.LocaleFromLanguageID: LongWord;
  259. begin
  260. Result := LEToN(ITSFHeader.LanguageID);
  261. end;
  262. procedure TITSFWriter.InitHeaderSectionTable;
  263. begin
  264. // header section 0
  265. HeaderSection0Table.PosFromZero := LEToN(ITSFHeader.HeaderLength);
  266. HeaderSection0Table.Length := SizeOf(TITSPHeaderPrefix);
  267. // header section 1
  268. HeaderSection1Table.PosFromZero := HeaderSection0Table.PosFromZero + HeaderSection0Table.Length;
  269. HeaderSection1Table.Length := SizeOf(TITSPHeader)+FDirectoryListings.Size;
  270. //contains the offset of CONTENT Section0 from zero
  271. HeaderSuffix.Offset := HeaderSection1Table.PosFromZero + HeaderSection1Table.Length;
  272. // now fix endian stuff
  273. HeaderSection0Table.PosFromZero := NToLE(HeaderSection0Table.PosFromZero);
  274. HeaderSection0Table.Length := NToLE(HeaderSection0Table.Length);
  275. HeaderSection1Table.PosFromZero := NToLE(HeaderSection1Table.PosFromZero);
  276. HeaderSection1Table.Length := NToLE(HeaderSection1Table.Length);
  277. with HeaderSection0 do begin // TITSPHeaderPrefix;
  278. Unknown1 := NToLE(DWord($01FE));
  279. Unknown2 := 0;
  280. // at this point we are putting together the headers. content sections 0 and 1 are complete
  281. FileSize := NToLE(HeaderSuffix.Offset + FSection0.Size + FSection1Size);
  282. Unknown3 := 0;
  283. Unknown4 := 0;
  284. end;
  285. with HeaderSection1 do begin // TITSPHeader; // DirectoryListings header
  286. ITSPsig := ITSPHeaderSig;
  287. Version := NToLE(DWord(1));
  288. DirHeaderLength := NToLE(DWord(SizeOf(TITSPHeader))); // Length of the directory header
  289. Unknown1 := NToLE(DWord($0A));
  290. ChunkSize := NToLE(DWord($1000));
  291. Density := NToLE(DWord(2));
  292. // updated when directory listings were created
  293. //IndexTreeDepth := 1 ; // 1 if there is no index 2 if there is one level of PMGI chunks. will update as
  294. //IndexOfRootChunk := -1;// if no root chunk
  295. //FirstPMGLChunkIndex,
  296. //LastPMGLChunkIndex: LongWord;
  297. Unknown2 := NToLE(Longint(-1));
  298. //DirectoryChunkCount: LongWord;
  299. LanguageID := ITSFHeader.LanguageID;
  300. GUID := ITSPHeaderGUID;
  301. LengthAgain := NToLE(DWord($54));
  302. Unknown3 := NToLE(Longint(-1));
  303. Unknown4 := NToLE(Longint(-1));
  304. Unknown5 := NToLE(Longint(-1));
  305. end;
  306. // more endian stuff
  307. HeaderSuffix.Offset := NToLE(HeaderSuffix.Offset);
  308. end;
  309. procedure TITSFWriter.SetTempRawStream(const AValue: TStream);
  310. begin
  311. if (FCurrentStream.Size > 0) or (FSection1.Size > 0) then
  312. raise Exception.Create('Cannot set the TempRawStream once data has been written to it!');
  313. if AValue = nil then
  314. raise Exception.Create('TempRawStream cannot be nil!');
  315. if FCurrentStream = AValue then
  316. exit;
  317. FCurrentStream.Free;
  318. FCurrentStream := AValue;
  319. end;
  320. procedure TITSFWriter.WriteHeader(Stream: TStream);
  321. begin
  322. Stream.Write(ITSFHeader, SizeOf(TITSFHeader));
  323. if ITSFHeader.Version < 4 then
  324. begin
  325. Stream.Write(ITSFHeaderGUID, SizeOf(TGuid));
  326. Stream.Write(ITSFHeaderGUID, SizeOf(TGuid));
  327. end;
  328. Stream.Write(HeaderSection0Table, SizeOf(TITSFHeaderEntry));
  329. Stream.Write(HeaderSection1Table, SizeOf(TITSFHeaderEntry));
  330. Stream.Write(HeaderSuffix, SizeOf(TITSFHeaderSuffix));
  331. Stream.Write(HeaderSection0, SizeOf(TITSPHeaderPrefix));
  332. end;
  333. procedure TITSFWriter.CreateDirectoryListings;
  334. type
  335. TFirstListEntry = record
  336. Entry: array[0..511] of byte;
  337. Size: Integer;
  338. end;
  339. var
  340. Buffer: array [0..511] of Byte;
  341. IndexBlock: TPMGIDirectoryChunk;
  342. ListingBlock: TDirectoryChunk;
  343. I: Integer;
  344. Size: Integer;
  345. FESize: Integer;
  346. FileName: String;
  347. FileNameSize: Integer;
  348. LastListIndex: Integer;
  349. FirstListEntry: TFirstListEntry;
  350. ChunkIndex: Integer;
  351. ListHeader: TPMGListChunk;
  352. const
  353. PMGL = 'PMGL';
  354. PMGI = 'PMGI';
  355. procedure UpdateLastListChunk;
  356. var
  357. Tmp: QWord;
  358. begin
  359. if ChunkIndex < 1 then begin
  360. Exit;
  361. end;
  362. Tmp := FDirectoryListings.Position;
  363. FDirectoryListings.Position := (LastListIndex) * $1000;
  364. FDirectoryListings.Read(ListHeader, SizeOf(TPMGListChunk));
  365. FDirectoryListings.Position := (LastListIndex) * $1000;
  366. ListHeader.NextChunkIndex := NToLE(ChunkIndex);
  367. FDirectoryListings.Write(ListHeader, SizeOf(TPMGListChunk));
  368. FDirectoryListings.Position := Tmp;
  369. end;
  370. procedure WriteIndexChunk(ShouldFinish: Boolean = False);
  371. var
  372. IndexHeader: TPMGIIndexChunk;
  373. ParentIndex,
  374. TmpIndex: TPMGIDirectoryChunk;
  375. begin
  376. with IndexHeader do
  377. begin
  378. PMGIsig := PMGI;
  379. UnusedSpace := NToLE(IndexBlock.FreeSpace);
  380. end;
  381. IndexBlock.WriteHeader(@IndexHeader);
  382. IndexBlock.WriteChunkToStream(FDirectoryListings, ChunkIndex, ShouldFinish);
  383. IndexBlock.Clear;
  384. if HeaderSection1.IndexOfRootChunk < 0 then HeaderSection1.IndexOfRootChunk := ChunkIndex;
  385. if ShouldFinish then
  386. begin
  387. HeaderSection1.IndexTreeDepth := 2;
  388. ParentIndex := IndexBlock.ParentChunk;
  389. if ParentIndex <> nil then
  390. repeat // the parent index is notified by our child index when to write
  391. HeaderSection1.IndexOfRootChunk := ChunkIndex;
  392. TmpIndex := ParentIndex;
  393. ParentIndex := ParentIndex.ParentChunk;
  394. TmpIndex.Free;
  395. Inc(HeaderSection1.IndexTreeDepth);
  396. Inc(ChunkIndex);
  397. until ParentIndex = nil;
  398. end;
  399. Inc(ChunkIndex);
  400. end;
  401. procedure WriteListChunk;
  402. begin
  403. with ListHeader do begin
  404. PMGLsig := PMGL;
  405. UnusedSpace := NToLE(ListingBlock.FreeSpace);
  406. Unknown1 := 0;
  407. PreviousChunkIndex := NToLE(LastListIndex);
  408. NextChunkIndex := NToLE(Longint(-1)); // we update this when we write the next chunk
  409. end;
  410. if HeaderSection1.FirstPMGLChunkIndex <= 0 then
  411. HeaderSection1.FirstPMGLChunkIndex := NToLE(ChunkIndex);
  412. HeaderSection1.LastPMGLChunkIndex := NToLE(ChunkIndex);
  413. ListingBlock.WriteHeader(@ListHeader);
  414. ListingBlock.WriteChunkToStream(FDirectoryListings);
  415. ListingBlock.Clear;
  416. UpdateLastListChunk;
  417. LastListIndex := ChunkIndex;
  418. Inc(ChunkIndex);
  419. // now add to index
  420. if not IndexBlock.CanHold(FirstListEntry.Size) then
  421. WriteIndexChunk;
  422. IndexBlock.WriteEntry(FirstListEntry.Size, @FirstListEntry.Entry[0])
  423. end;
  424. begin
  425. // first sort the listings
  426. FInternalFiles.Sort;
  427. HeaderSection1.IndexTreeDepth := 1;
  428. HeaderSection1.IndexOfRootChunk := -1;
  429. ChunkIndex := 0;
  430. IndexBlock := TPMGIDirectoryChunk.Create(SizeOf(TPMGIIndexChunk));
  431. ListingBlock := TDirectoryChunk.Create(SizeOf(TPMGListChunk));
  432. LastListIndex := -1;
  433. // add files to a pmgl block until it is full.
  434. // after the block is full make a pmgi block and add the first entry of the pmgl block
  435. // repeat until the index block is full and start another.
  436. // the pmgi chunks take care of needed parent chunks in the tree
  437. for I := 0 to FInternalFiles.Count-1 do begin
  438. Size := 0;
  439. FileName := FInternalFiles.FileEntry[I].Path + FInternalFiles.FileEntry[I].Name;
  440. FileNameSize := Length(FileName);
  441. // filename length
  442. Inc(Size, WriteCompressedInteger(@Buffer[Size], FileNameSize));
  443. // filename
  444. Move(FileName[1], Buffer[Size], FileNameSize);
  445. Inc(Size, FileNameSize);
  446. FESize := Size;
  447. // File is compressed...
  448. Inc(Size, WriteCompressedInteger(@Buffer[Size], Ord(FInternalFiles.FileEntry[I].Compressed)));
  449. // Offset from section start
  450. Inc(Size, WriteCompressedInteger(@Buffer[Size], FInternalFiles.FileEntry[I].DecompressedOffset));
  451. // Size when uncompressed
  452. Inc(Size, WriteCompressedInteger(@Buffer[Size], FInternalFiles.FileEntry[I].DecompressedSize));
  453. if not ListingBlock.CanHold(Size) then
  454. WriteListChunk;
  455. ListingBlock.WriteEntry(Size, @Buffer[0]);
  456. if ListingBlock.ItemCount = 1 then begin // add the first list item to the index
  457. Move(Buffer[0], FirstListEntry.Entry[0], FESize);
  458. FirstListEntry.Size := FESize + WriteCompressedInteger(@FirstListEntry.Entry[FESize], ChunkIndex);
  459. end;
  460. end;
  461. if ListingBlock.ItemCount > 0 then WriteListChunk;
  462. if ChunkIndex > 1 then begin
  463. if (IndexBlock.ItemCount > 1)
  464. or ( (IndexBlock.ItemCount > 0) and (HeaderSection1.IndexOfRootChunk > -1) )
  465. then WriteIndexChunk(True);
  466. end;
  467. HeaderSection1.DirectoryChunkCount := NToLE(DWord(FDirectoryListings.Size div $1000));
  468. IndexBlock.Free;
  469. ListingBlock.Free;
  470. //now fix some endian stuff
  471. HeaderSection1.IndexOfRootChunk := NToLE(HeaderSection1.IndexOfRootChunk);
  472. HeaderSection1.IndexTreeDepth := NtoLE(HeaderSection1.IndexTreeDepth);
  473. end;
  474. procedure TITSFWriter.WriteDirectoryListings(Stream: TStream);
  475. begin
  476. Stream.Write(HeaderSection1, SizeOf(HeaderSection1));
  477. FDirectoryListings.Position := 0;
  478. Stream.CopyFrom(FDirectoryListings, FDirectoryListings.Size);
  479. FDirectoryListings.Position := 0;
  480. //TMemoryStream(FDirectoryListings).SaveToFile('dirlistings.pmg');
  481. end;
  482. procedure TITSFWriter.WriteInternalFilesBefore;
  483. begin
  484. // written to Section0 (uncompressed)
  485. WriteREADMEFile;
  486. end;
  487. procedure TITSFWriter.WriteInternalFilesAfter;
  488. begin
  489. end;
  490. procedure IterateWord(aword:TIndexedWord;State:pointer);
  491. var i,cnt : integer;
  492. begin
  493. cnt:=pinteger(state)^;
  494. for i := 0 to AWord.DocumentCount-1 do
  495. Inc(cnt, AWord.GetLogicalDocument(i).NumberOfIndexEntries);
  496. // was commented in original procedure, seems to list index entries per doc.
  497. //WriteLn(AWord.TheWord,' documents = ', AWord.DocumentCount, ' h
  498. pinteger(state)^:=cnt;
  499. end;
  500. procedure TITSFWriter.WriteREADMEFile;
  501. const DISCLAIMER_STR = 'This archive was not made by the MS HTML Help Workshop(r)(tm) program, but by Free Pascal''s chm package '+chmpackageversion+'.'#13#10;
  502. var
  503. Entry: TFileEntryRec;
  504. begin
  505. // This procedure puts a file in the archive that says it wasn't compiled with the MS compiler
  506. Entry.Compressed := False;
  507. Entry.DecompressedOffset := FSection0.Position;
  508. FSection0.Write(DISCLAIMER_STR, SizeOf(DISCLAIMER_STR));
  509. if length(FReadmeMessage)>0 then
  510. FSection0.Write(FReadmeMessage[1], length(FReadmeMessage));
  511. Entry.DecompressedSize := FSection0.Position - Entry.DecompressedOffset;
  512. Entry.Path := '/';
  513. Entry.Name := '_#_README_#_'; //try to use a name that won't conflict with normal names
  514. FInternalFiles.AddEntry(Entry);
  515. end;
  516. procedure TITSFWriter.WriteFinalCompressedFiles;
  517. begin
  518. end;
  519. procedure TITSFWriter.WriteSection0;
  520. begin
  521. FSection0.Position := 0;
  522. FOutStream.CopyFrom(FSection0, FSection0.Size);
  523. end;
  524. procedure TITSFWriter.WriteSection1;
  525. begin
  526. WriteContentToStream(FOutStream, FSection1);
  527. end;
  528. procedure TITSFWriter.WriteDataSpaceFiles(const AStream: TStream);
  529. var
  530. Entry: TFileEntryRec;
  531. begin
  532. // This procedure will write all files starting with ::
  533. Entry.Compressed := False; // None of these files are compressed
  534. // ::DataSpace/NameList
  535. Entry.DecompressedOffset := FSection0.Position;
  536. Entry.DecompressedSize := WriteNameListToStream(FSection0, [snUnCompressed,snMSCompressed]);
  537. Entry.Path := '::DataSpace/';
  538. Entry.Name := 'NameList';
  539. FInternalFiles.AddEntry(Entry, False);
  540. // ::DataSpace/Storage/MSCompressed/ControlData
  541. Entry.DecompressedOffset := FSection0.Position;
  542. Entry.DecompressedSize := WriteControlDataToStream(FSection0, 2, 2, 1);
  543. Entry.Path := '::DataSpace/Storage/MSCompressed/';
  544. Entry.Name := 'ControlData';
  545. FInternalFiles.AddEntry(Entry, False);
  546. // ::DataSpace/Storage/MSCompressed/SpanInfo
  547. Entry.DecompressedOffset := FSection0.Position;
  548. Entry.DecompressedSize := WriteSpanInfoToStream(FSection0, FReadCompressedSize);
  549. Entry.Path := '::DataSpace/Storage/MSCompressed/';
  550. Entry.Name := 'SpanInfo';
  551. FInternalFiles.AddEntry(Entry, False);
  552. // ::DataSpace/Storage/MSCompressed/Transform/List
  553. Entry.DecompressedOffset := FSection0.Position;
  554. Entry.DecompressedSize := WriteTransformListToStream(FSection0);
  555. Entry.Path := '::DataSpace/Storage/MSCompressed/Transform/';
  556. Entry.Name := 'List';
  557. FInternalFiles.AddEntry(Entry, False);
  558. // ::DataSpace/Storage/MSCompressed/Transform/{7FC28940-9D31-11D0-9B27-00A0C91E9C7C}/
  559. // ::DataSpace/Storage/MSCompressed/Transform/{7FC28940-9D31-11D0-9B27-00A0C91E9C7C}/InstanceData/ResetTable
  560. Entry.DecompressedOffset := FSection0.Position;
  561. Entry.DecompressedSize := WriteResetTableToStream(FSection0, FSection1ResetTable);
  562. Entry.Path := '::DataSpace/Storage/MSCompressed/Transform/{7FC28940-9D31-11D0-9B27-00A0C91E9C7C}/InstanceData/';
  563. Entry.Name := 'ResetTable';
  564. FInternalFiles.AddEntry(Entry, True);
  565. // ::DataSpace/Storage/MSCompressed/Content do this last
  566. Entry.DecompressedOffset := FSection0.Position;
  567. Entry.DecompressedSize := FSection1Size; // we will write it directly to FOutStream later
  568. Entry.Path := '::DataSpace/Storage/MSCompressed/';
  569. Entry.Name := 'Content';
  570. FInternalFiles.AddEntry(Entry, False);
  571. end;
  572. procedure TITSFWriter.FileAdded(AStream: TStream; const AEntry: TFileEntryRec);
  573. begin
  574. // do nothing here
  575. end;
  576. function _AtEndOfData(arg: pointer): LongBool; cdecl;
  577. begin
  578. Result := TITSFWriter(arg).AtEndOfData;
  579. end;
  580. function TITSFWriter.AtEndOfData: LongBool;
  581. begin
  582. Result := ForceExit or (FCurrentIndex >= FFileNames.Count-1);
  583. if Result then
  584. Result := Integer(FCurrentStream.Position) >= Integer(FCurrentStream.Size)-1;
  585. end;
  586. function _GetData(arg: pointer; Count: LongInt; Buffer: Pointer): LongInt; cdecl;
  587. begin
  588. Result := TITSFWriter(arg).GetData(Count, PByte(Buffer));
  589. end;
  590. function TITSFWriter.GetData(Count: LongInt; Buffer: PByte): LongInt;
  591. var
  592. FileEntry: TFileEntryRec;
  593. begin
  594. Result := 0;
  595. while (Result < Count) and (not AtEndOfData) do begin
  596. Inc(Result, FCurrentStream.Read(Buffer[Result], Count-Result));
  597. if (Result < Count) and (not AtEndOfData)
  598. then begin
  599. // the current file has been read. move to the next file in the list
  600. FCurrentStream.Position := 0;
  601. FCurrentStream.Size:=0;
  602. Inc(FCurrentIndex);
  603. ForceExit := OnGetFileData(FFileNames[FCurrentIndex], FileEntry.Path, FileEntry.Name, FCurrentStream);
  604. FileEntry.DecompressedSize := FCurrentStream.Size;
  605. FileEntry.DecompressedOffset := FReadCompressedSize; //269047723;//to test writing really large numbers
  606. FileEntry.Compressed := True;
  607. FileAdded(FCurrentStream, FileEntry);
  608. FInternalFiles.AddEntry(FileEntry);
  609. // So the next file knows it's offset
  610. Inc(FReadCompressedSize, FileEntry.DecompressedSize);
  611. FCurrentStream.Position := 0;
  612. end;
  613. // this is intended for programs to add perhaps a file
  614. // after all the other files have been added.
  615. if (AtEndOfData)
  616. and (FCurrentStream <> FPostStream) then
  617. begin
  618. FPostStreamActive := True;
  619. if Assigned(FOnLastFile) then
  620. FOnLastFile(Self);
  621. FCurrentStream.Free;
  622. WriteFinalCompressedFiles;
  623. FCurrentStream := FPostStream;
  624. FCurrentStream.Position := 0;
  625. Inc(FReadCompressedSize, FCurrentStream.Size);
  626. end;
  627. end;
  628. end;
  629. function _WriteCompressedData(arg: pointer; Count: LongInt; Buffer: Pointer): LongInt; cdecl;
  630. begin
  631. Result := TITSFWriter(arg).WriteCompressedData(Count, Buffer);
  632. end;
  633. function TITSFWriter.WriteCompressedData(Count: Longint; Buffer: Pointer): LongInt;
  634. begin
  635. // we allocate a MB at a time to limit memory reallocation since this
  636. // writes usually 2 bytes at a time
  637. if (FSection1 is TMemoryStream) and (FSection1.Position >= FSection1.Size-1) then begin
  638. FSection1.Size := FSection1.Size+$100000;
  639. end;
  640. Result := FSection1.Write(Buffer^, Count);
  641. Inc(FSection1Size, Result);
  642. end;
  643. procedure _MarkFrame(arg: pointer; UncompressedTotal, CompressedTotal: LongWord); cdecl;
  644. begin
  645. TITSFWriter(arg).MarkFrame(UncompressedTotal, CompressedTotal);
  646. end;
  647. procedure TITSFWriter.MarkFrame(UnCompressedTotal, CompressedTotal: LongWord);
  648. procedure WriteQWord(Value: QWord);
  649. begin
  650. FSection1ResetTable.Write(NToLE(Value), 8);
  651. end;
  652. procedure IncEntryCount;
  653. var
  654. OldPos: QWord;
  655. Value: DWord;
  656. begin
  657. OldPos := FSection1ResetTable.Position;
  658. FSection1ResetTable.Position := $4;
  659. Value := LeToN(FSection1ResetTable.ReadDWord)+1;
  660. FSection1ResetTable.Position := $4;
  661. FSection1ResetTable.WriteDWord(NToLE(Value));
  662. FSection1ResetTable.Position := OldPos;
  663. end;
  664. procedure UpdateTotalSizes;
  665. var
  666. OldPos: QWord;
  667. begin
  668. OldPos := FSection1ResetTable.Position;
  669. FSection1ResetTable.Position := $10;
  670. WriteQWord(FReadCompressedSize); // size of read data that has been compressed
  671. WriteQWord(CompressedTotal);
  672. FSection1ResetTable.Position := OldPos;
  673. end;
  674. begin
  675. if FSection1ResetTable.Size = 0 then begin
  676. // Write the header
  677. FSection1ResetTable.WriteDWord(NtoLE(DWord(2)));
  678. FSection1ResetTable.WriteDWord(0); // number of entries. we will correct this with IncEntryCount
  679. FSection1ResetTable.WriteDWord(NtoLE(DWord(8))); // Size of Entries (qword)
  680. FSection1ResetTable.WriteDWord(NtoLE(DWord($28))); // Size of this header
  681. WriteQWord(0); // Total Uncompressed Size
  682. WriteQWord(0); // Total Compressed Size
  683. WriteQWord(NtoLE($8000)); // Block Size
  684. WriteQWord(0); // First Block start
  685. end;
  686. IncEntryCount;
  687. UpdateTotalSizes;
  688. WriteQWord(CompressedTotal); // Next Block Start
  689. // We have to trim the last entry off when we are done because there is no next block in that case
  690. end;
  691. function TITSFWriter.LTGetData(Sender: TLZXCompressor; WantedByteCount: Integer;
  692. Buffer: Pointer): Integer;
  693. begin
  694. Result := GetData(WantedByteCount, Buffer);
  695. //WriteLn('Wanted ', WantedByteCount, ' got ', Result);
  696. end;
  697. function TITSFWriter.LTIsEndOfFile(Sender: TLZXCompressor): Boolean;
  698. begin
  699. Result := AtEndOfData;
  700. end;
  701. procedure TITSFWriter.LTChunkDone(Sender: TLZXCompressor;
  702. CompressedSize: Integer; UncompressedSize: Integer; Buffer: Pointer);
  703. begin
  704. WriteCompressedData(CompressedSize, Buffer);
  705. end;
  706. procedure TITSFWriter.LTMarkFrame(Sender: TLZXCompressor;
  707. CompressedTotal: Integer; UncompressedTotal: Integer);
  708. begin
  709. MarkFrame(UncompressedTotal, CompressedTotal);
  710. //WriteLn('Mark Frame C = ', CompressedTotal, ' U = ', UncompressedTotal);
  711. end;
  712. constructor TITSFWriter.Create(AOutStream: TStream; FreeStreamOnDestroy: Boolean);
  713. begin
  714. if AOutStream = nil then Raise Exception.Create('TITSFWriter.OutStream Cannot be nil!');
  715. FOutStream := AOutStream;
  716. FCurrentIndex := -1;
  717. FCurrentStream := TMemoryStream.Create;
  718. FInternalFiles := TFileEntryList.Create;
  719. FSection0 := TMemoryStream.Create;
  720. FSection1 := TMemoryStream.Create;
  721. FSection1ResetTable := TMemoryStream.Create;
  722. FDirectoryListings := TMemoryStream.Create;
  723. FPostStream := TMemoryStream.Create;;
  724. FDestroyStream := FreeStreamOnDestroy;
  725. FFileNames := TStringList.Create;
  726. InitITSFHeader;
  727. end;
  728. destructor TITSFWriter.Destroy;
  729. begin
  730. if FDestroyStream then FOutStream.Free;
  731. FInternalFiles.Free;
  732. FCurrentStream.Free;
  733. FSection0.Free;
  734. FSection1.Free;
  735. FSection1ResetTable.Free;
  736. FDirectoryListings.Free;
  737. FFileNames.Free;
  738. inherited Destroy;
  739. end;
  740. procedure TITSFWriter.Execute;
  741. begin
  742. FOutStream.Position := 0;
  743. FSection1Size := 0;
  744. // write any internal files to FCurrentStream that we want in the compressed section
  745. WriteInternalFilesBefore;
  746. // move back to zero so that we can start reading from zero :)
  747. FReadCompressedSize := FCurrentStream.Size;
  748. FCurrentStream.Position := 0; // when compressing happens, first the FCurrentStream is read
  749. // before loading user files. So we can fill FCurrentStream with
  750. // internal files first.
  751. // this gathers ALL files that should be in section1 (the compressed section)
  752. StartCompressingStream;
  753. FSection1.Size := FSection1Size;
  754. WriteInternalFilesAfter;
  755. //this creates all special files in the archive that start with ::DataSpace
  756. WriteDataSpaceFiles(FSection0);
  757. // creates all directory listings including header
  758. CreateDirectoryListings;
  759. // do this after we have compressed everything so that we know the values that must be written
  760. InitHeaderSectionTable;
  761. // Now we can write everything to FOutStream
  762. WriteHeader(FOutStream);
  763. WriteDirectoryListings(FOutStream);
  764. WriteSection0; //does NOT include section 1 even though section0.content IS section1
  765. WriteSection1; // writes section 1 to FOutStream
  766. end;
  767. // this procedure is used to manually add files to compress to an internal stream that is
  768. // processed before FileToCompress is called. Files added this way should not be
  769. // duplicated in the FilesToCompress property.
  770. procedure TITSFWriter.AddStreamToArchive(AFileName, APath: String; AStream: TStream; Compress: Boolean = True);
  771. var
  772. TargetStream: TStream;
  773. Entry: TFileEntryRec;
  774. begin
  775. // in case AddStreamToArchive is used after we should be writing to the post stream
  776. if FPostStreamActive then
  777. begin
  778. PostAddStreamToArchive(AFileName, APath, AStream, Compress);
  779. Exit;
  780. end;
  781. if AStream = nil then Exit;
  782. if Compress then
  783. TargetStream := FCurrentStream
  784. else
  785. TargetStream := FSection0;
  786. Entry.Name := AFileName;
  787. Entry.Path := APath;
  788. Entry.Compressed := Compress;
  789. Entry.DecompressedOffset := TargetStream.Position;
  790. Entry.DecompressedSize := AStream.Size;
  791. FileAdded(AStream,Entry);
  792. FInternalFiles.AddEntry(Entry);
  793. AStream.Position := 0;
  794. TargetStream.CopyFrom(AStream, AStream.Size);
  795. end;
  796. procedure TITSFWriter.PostAddStreamToArchive(AFileName, APath: String;
  797. AStream: TStream; Compress: Boolean);
  798. var
  799. TargetStream: TStream;
  800. Entry: TFileEntryRec;
  801. begin
  802. if AStream = nil then Exit;
  803. if Compress then
  804. TargetStream := FPostStream
  805. else
  806. TargetStream := FSection0;
  807. Entry.Name := AFileName;
  808. Entry.Path := APath;
  809. Entry.Compressed := Compress;
  810. if not Compress then
  811. Entry.DecompressedOffset := TargetStream.Position
  812. else
  813. Entry.DecompressedOffset := FReadCompressedSize + TargetStream.Position;
  814. Entry.DecompressedSize := AStream.Size;
  815. FInternalFiles.AddEntry(Entry);
  816. AStream.Position := 0;
  817. TargetStream.CopyFrom(AStream, AStream.Size);
  818. FileAdded(AStream, Entry);
  819. end;
  820. procedure TITSFWriter.StartCompressingStream;
  821. var
  822. LZXdata: Plzx_data;
  823. WSize: LongInt;
  824. Compressor: TLZXCompressor;
  825. begin
  826. if fcores=0 then
  827. begin
  828. lzx_init(@LZXdata, LZX_WINDOW_SIZE, @_GetData, Self, @_AtEndOfData,
  829. @_WriteCompressedData, Self, @_MarkFrame, Self);
  830. WSize := 1 shl LZX_WINDOW_SIZE;
  831. while not AtEndOfData do begin
  832. lzx_reset(LZXdata);
  833. lzx_compress_block(LZXdata, WSize, True);
  834. end;
  835. //we have to mark the last frame manually
  836. MarkFrame(LZXdata^.len_uncompressed_input, LZXdata^.len_compressed_output);
  837. lzx_finish(LZXdata, nil);
  838. end
  839. else
  840. begin
  841. if fcores=0 then fcores:=4;
  842. Compressor := TLZXCompressor.Create(fcores);
  843. Compressor.OnChunkDone :=@LTChunkDone;
  844. Compressor.OnGetData :=@LTGetData;
  845. Compressor.OnIsEndOfFile:=@LTIsEndOfFile;
  846. Compressor.OnMarkFrame :=@LTMarkFrame;
  847. Compressor.Execute(True);
  848. //Sleep(20000);
  849. Compressor.Free;
  850. end;
  851. end;
  852. procedure TChmWriter.WriteSYSTEM;
  853. var
  854. Entry: TFileEntryRec;
  855. TmpStr: String;
  856. TmpTitle: String;
  857. const
  858. VersionStr = 'HHA Version 4.74.8702'; // does this matter?
  859. begin
  860. // this creates the /#SYSTEM file
  861. Entry.Name := '#SYSTEM';
  862. Entry.Path := '/';
  863. Entry.Compressed := False;
  864. Entry.DecompressedOffset := FSection0.Position;
  865. { if FileExists('#SYSTEM') then
  866. begin
  867. TmpStream := TMemoryStream.Create;
  868. TmpStream.LoadFromFile('#SYSTEM');
  869. TmpStream.Position := 0;
  870. FSection0.CopyFrom(TmpStream, TmpStream.Size);
  871. end; }
  872. // EntryCodeOrder: 10 9 4 2 3 16 6 0 1 5
  873. FSection0.WriteDWord(NToLE(Word(3))); // Version
  874. if Title <> '' then
  875. TmpTitle := Title
  876. else
  877. TmpTitle := 'default';
  878. // Code -> Length -> Data
  879. // 10
  880. FSection0.WriteWord(NToLE(Word(10)));
  881. FSection0.WriteWord(NToLE(Word(SizeOf(DWord))));
  882. FSection0.WriteDWord(NToLE(MilliSecondOfTheDay(Now)));
  883. // 9
  884. FSection0.WriteWord(NToLE(Word(9)));
  885. FSection0.WriteWord(NToLE(Word(SizeOf(VersionStr)+1)));
  886. FSection0.Write(VersionStr, SizeOf(VersionStr));
  887. FSection0.WriteByte(0);
  888. // 4 A struct that is only needed to set if full text search is on.
  889. FSection0.WriteWord(NToLE(Word(4)));
  890. FSection0.WriteWord(NToLE(Word(36))); // size
  891. FSection0.WriteDWord(ITSFHeader.LanguageID);
  892. FSection0.WriteDWord(0);
  893. FSection0.WriteDWord(NToLE(DWord(Ord(FFullTextSearch and FFullTextSearchAvailable))));
  894. FSection0.WriteDWord(NToLE(Dword(Ord(FHasKLinks))) ); // klinks
  895. FSection0.WriteDWord(0); // alinks
  896. // two for a QWord
  897. FSection0.WriteDWord(0);
  898. FSection0.WriteDWord(0);
  899. FSection0.WriteDWord(0);
  900. FSection0.WriteDWord(0);
  901. ////////////////////////<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  902. // 2 default page to load
  903. if FDefaultPage <> '' then begin
  904. FSection0.WriteWord(NToLE(Word(2)));
  905. FSection0.WriteWord(NToLE(Word(Length(FDefaultPage)+1)));
  906. FSection0.Write(FDefaultPage[1], Length(FDefaultPage));
  907. FSection0.WriteByte(0);
  908. end;
  909. // 3 Title
  910. if FTitle <> '' then begin
  911. FSection0.WriteWord(NToLE(Word(3)));
  912. FSection0.WriteWord(NToLE(Word(Length(FTitle)+1)));
  913. FSection0.Write(FTitle[1], Length(FTitle));
  914. FSection0.WriteByte(0);
  915. end;
  916. // 16 Default Font
  917. if FDefaultFont <> '' then begin
  918. FSection0.WriteWord(NToLE(Word(16)));
  919. FSection0.WriteWord(NToLE(Word(Length(FDefaultFont)+1)));
  920. FSection0.Write(FDefaultFont[1], Length(FDefaultFont));
  921. FSection0.WriteByte(0);
  922. end;
  923. // 6
  924. // unneeded. if output file is : /somepath/OutFile.chm the value here is outfile(lowercase)
  925. {FSection0.WriteWord(6);
  926. FSection0.WriteWord(Length('test1')+1);
  927. Fsection0.Write('test1', 5);
  928. FSection0.WriteByte(0);}
  929. // 0 Table of contents filename
  930. if FHasTOC then begin
  931. if fTocName ='' then
  932. TmpStr := DefaultHHC
  933. else
  934. TmpStr := fTocName;
  935. FSection0.WriteWord(0);
  936. FSection0.WriteWord(NToLE(Word(Length(TmpStr)+1)));
  937. FSection0.Write(TmpStr[1], Length(TmpStr));
  938. FSection0.WriteByte(0);
  939. end;
  940. // 1
  941. // hhk Index
  942. if FHasIndex then begin
  943. if fIndexName='' then
  944. TmpStr := DefaultHHK
  945. else
  946. TmpStr := fIndexName;
  947. FSection0.WriteWord(NToLE(Word(1)));
  948. FSection0.WriteWord(NToLE(Word(Length(TmpStr)+1)));
  949. FSection0.Write(TmpStr[1], Length(TmpStr));
  950. FSection0.WriteByte(0);
  951. end;
  952. // 5 Default Window
  953. if FDefaultWindow<>'' then
  954. begin
  955. FSection0.WriteWord(NTOLE(Word(5)));
  956. tmpstr:=FDefaultWindow;
  957. FSection0.WriteWord(NToLE(Word(Length(TmpStr)+1)));
  958. FSection0.Write(TmpStr[1], Length(TmpStr));
  959. FSection0.WriteByte(0);
  960. end;
  961. // 7 Binary Index
  962. if FHasBinaryIndex then
  963. begin
  964. {$ifdef binindex}
  965. logentry('binary index!');
  966. {$endif}
  967. FSection0.WriteWord(NToLE(Word(7)));
  968. FSection0.WriteWord(NToLE(Word(4)));
  969. FSection0.WriteDWord(DWord(0)); // what is this number to be?
  970. end;
  971. // 11 Binary TOC
  972. if FHasBinaryTOC then
  973. begin
  974. FSection0.WriteWord(NToLE(Word(11)));
  975. FSection0.WriteWord(NToLE(Word(4)));
  976. FSection0.WriteDWord(DWord(0)); // what is this number to be?
  977. end;
  978. // 13
  979. if FIDXHdrStream.size>0 then
  980. begin
  981. FSection0.WriteWord(NToLE(Word(13)));
  982. FSection0.WriteWord(NToLE(Word(FIDXHdrStream.size)));
  983. FSection0.copyfrom(FIDXHdrStream,0);
  984. end;
  985. Entry.DecompressedSize := FSection0.Position - Entry.DecompressedOffset;
  986. FInternalFiles.AddEntry(Entry);
  987. end;
  988. procedure TChmWriter.WriteITBITS;
  989. var
  990. Entry: TFileEntryRec;
  991. begin
  992. // This is an empty and useless file
  993. Entry.Name := '#ITBITS';
  994. Entry.Path := '/';
  995. Entry.Compressed := False;
  996. Entry.DecompressedOffset :=0;// FSection0.Position;
  997. Entry.DecompressedSize := 0;
  998. FInternalFiles.AddEntry(Entry);
  999. end;
  1000. procedure TChmWriter.WriteSTRINGS;
  1001. begin
  1002. if FStringsStream.Size = 0 then;
  1003. FStringsStream.WriteByte(0);
  1004. FStringsStream.Position := 0;
  1005. PostAddStreamToArchive('#STRINGS', '/', FStringsStream);
  1006. end;
  1007. procedure TChmWriter.WriteTOPICS;
  1008. begin
  1009. if FTopicsStream.Size = 0 then
  1010. Exit;
  1011. if tocname<>'' then
  1012. AddTopic('',self.TOCName,2);
  1013. if indexname<>'' then
  1014. AddTopic('',self.IndexName,2);
  1015. FTopicsStream.Position := 0;
  1016. PostAddStreamToArchive('#TOPICS', '/', FTopicsStream);
  1017. // I commented the code below since the result seemed unused
  1018. // FHits:=0;
  1019. // FIndexedFiles.ForEach(@IterateWord,FHits);
  1020. end;
  1021. procedure TChmWriter.WriteIDXHDR;
  1022. begin
  1023. if FIDXHdrStream.Size = 0 then
  1024. Exit;
  1025. FIDXHdrStream.Position := 0;
  1026. PostAddStreamToArchive('#IDXHDR', '/', FIDXHdrStream);
  1027. end;
  1028. procedure TChmWriter.WriteIVB;
  1029. begin
  1030. if FContextStream = nil then exit;
  1031. FContextStream.Position := 0;
  1032. // the size of all the entries
  1033. FContextStream.WriteDWord(NToLE(DWord(FContextStream.Size-SizeOf(dword))));
  1034. FContextStream.Position := 0;
  1035. AddStreamToArchive('#IVB', '/', FContextStream);
  1036. end;
  1037. const idxhdrmagic ='T#SM';
  1038. procedure TChmWriter.CreateIDXHDRStream;
  1039. var i : Integer;
  1040. begin
  1041. if (fmergefiles.count=0) and not HasBinaryIndex then // I assume text/site properties could also trigger idxhdr
  1042. exit;
  1043. FIDXHdrStream.setsize(4096);
  1044. FIDXHdrStream.position:=0;
  1045. FIDXHdrStream.write(idxhdrmagic[1],4); // 0 Magic
  1046. FIDXHdrStream.writedword(ntole(0)); // 4 Unknown timestamp/checksum
  1047. FIDXHdrStream.writedword(ntole(1)); // 8 1 (unknown)
  1048. FIDXHdrStream.writedword(ntole(FNrTopics)); // C Number of topic nodes including the contents & index files
  1049. FIDXHdrStream.writedword(ntole(0)); // 10 0 (unknown)
  1050. // 14 Offset in the #STRINGS file of the ImageList param of the "text/site properties" object of the sitemap contents (0/-1 = none)
  1051. if assigned(ftocsm) and (ftocsm.ImageList<>'') then
  1052. FIDXHdrStream.writedwordLE(addstring(ftocsm.ImageList))
  1053. else
  1054. FIDXHdrStream.writedwordLE($FFFFFFFF);
  1055. // 18 0 (unknown)
  1056. FIDXHdrStream.writedwordLE(0);
  1057. // 1C 1 if the value of the ImageType param of the "text/site properties" object of the sitemap contents is Folder. 0 otherwise.
  1058. if assigned(ftocsm) and (ftocsm.UseFolderImages) then
  1059. FIDXHdrStream.writedwordLE(1)
  1060. else
  1061. FIDXHdrStream.writedwordLE(0);
  1062. // 20 The value of the Background param of the "text/site properties" object of the sitemap contents
  1063. if assigned(ftocsm) then
  1064. FIDXHdrStream.writedwordLE(ftocsm.Backgroundcolor)
  1065. else
  1066. FIDXHdrStream.writedwordLE($FFFFFFFF);
  1067. // 24 The value of the Foreground param of the "text/site properties" object of the sitemap contents
  1068. if assigned(ftocsm) then
  1069. FIDXHdrStream.writedwordLE(ftocsm.Foregroundcolor)
  1070. else
  1071. FIDXHdrStream.writedwordLE($FFFFFFFF);
  1072. // 28 Offset in the #STRINGS file of the Font param of the "text/site properties" object of the sitemap contents (0/-1 = none)
  1073. if assigned(ftocsm) and (ftocsm.Font<>'') then
  1074. FIDXHdrStream.writedwordLE(addstring(ftocsm.font))
  1075. else
  1076. FIDXHdrStream.writedwordLE($FFFFFFFF);
  1077. // 2C The value of the Window Styles param of the "text/site properties" object of the sitemap contents
  1078. if assigned(ftocsm) then
  1079. FIDXHdrStream.writedwordLE(FTocsm.WindowStyles)
  1080. else
  1081. FIDXHdrStream.writedwordLE($FFFFFFFF);
  1082. // 30 The value of the EXWindow Styles param of the "text/site properties" object of the sitemap contents
  1083. if assigned(ftocsm) then
  1084. FIDXHdrStream.writedwordLE(FTocSm.ExWindowStyles)
  1085. else
  1086. FIDXHdrStream.writedwordLE(0);
  1087. // 34 Unknown. Often -1. Sometimes 0.
  1088. FIDXHdrStream.writedwordLE($FFFFFFFF);
  1089. // 38 Offset in the #STRINGS file of the FrameName param of the "text/site properties" object of the sitemap contents (0/-1 = none)
  1090. if assigned(ftocsm) and (ftocsm.framename<>'') then
  1091. FIDXHdrStream.writedwordLE(addstring(FTocsm.Framename))
  1092. else
  1093. FIDXHdrStream.writedwordLE(0);
  1094. // 3C Offset in the #STRINGS file of the WindowName param of the "text/site properties" object of the sitemap contents (0/-1 = none)
  1095. if assigned(ftocsm) and (ftocsm.windowname<>'') then
  1096. FIDXHdrStream.writedwordLE(addstring(FTocsm.windowname))
  1097. else
  1098. FIDXHdrStream.writedwordLE($FFFFFFFF);
  1099. FIDXHdrStream.writedword(ntole(0)); // 40 Number of information types.
  1100. FIDXHdrStream.writedword(ntole(1)); // 44 Unknown. Often 1. Also 0, 3.
  1101. FIDXHdrStream.writedword(ntole(fmergefiles.count)); // 48 Number of files in the [MERGE FILES] list.
  1102. // 4C Unknown. Often 0. Non-zero mostly in files with some files in the merge files list.
  1103. if fmergefiles.count>0 then
  1104. FIDXHdrStream.writedwordLE(1)
  1105. else
  1106. FIDXHdrStream.writedwordLE(0);
  1107. for i:=0 to FMergefiles.count-1 do
  1108. FIDXHdrStream.WriteDword(addstring(fmergefiles[i]));
  1109. for i:=0 to 1004-fmergefiles.count-1 do
  1110. FIDXHdrStream.WriteDword(0);
  1111. end;
  1112. procedure TChmWriter.WriteURL_STR_TBL;
  1113. begin
  1114. if FURLSTRStream.Size <> 0 then begin
  1115. FURLSTRStream.Position := 0;
  1116. PostAddStreamToArchive('#URLSTR', '/', FURLSTRStream);
  1117. end;
  1118. if FURLTBLStream.Size <> 0 then begin
  1119. FURLTBLStream.Position := 0;
  1120. PostAddStreamToArchive('#URLTBL', '/', FURLTBLStream);
  1121. end;
  1122. end;
  1123. procedure TChmWriter.WriteOBJINST;
  1124. var
  1125. i: Integer;
  1126. ObjStream: TMemoryStream;
  1127. //Flags: Word;
  1128. begin
  1129. ObjStream := TMemorystream.Create;
  1130. // this file is needed to enable searches for the ms reader
  1131. ObjStream.WriteDWord(NtoLE($04000000));
  1132. ObjStream.WriteDWord(NtoLE(Dword(2))); // two entries
  1133. ObjStream.WriteDWord(NtoLE(DWord(24))); // offset into file of entry
  1134. ObjStream.WriteDWord(NtoLE(DWord(2691))); // size
  1135. ObjStream.WriteDWord(NtoLE(DWord(2715))); // offset into file of entry
  1136. ObjStream.WriteDWord(NtoLE(DWord(36))); // size
  1137. // first entry
  1138. // write guid 4662DAAF-D393-11D0-9A56-00C04FB68BF7
  1139. ObjStream.WriteDWord(NtoLE($4662DAAF));
  1140. ObjStream.WriteWord(NtoLE($D393));
  1141. ObjStream.WriteWord(NtoLE(word($11D0)));
  1142. ObjStream.WriteWord(NtoLE(word($569A)));
  1143. ObjStream.WriteByte($00);
  1144. ObjStream.WriteByte($C0);
  1145. ObjStream.WriteByte($4F);
  1146. ObjStream.WriteByte($B6);
  1147. ObjStream.WriteByte($8B);
  1148. ObjStream.WriteByte($F7);
  1149. ObjStream.WriteDWord(NtoLE($04000000));
  1150. ObjStream.WriteDWord(NtoLE(11)); // bit flags
  1151. ObjStream.WriteDWord(NtoLE(DWord(1252)));
  1152. ObjStream.WriteDWord(NtoLE(DWord(1033)));
  1153. ObjStream.WriteDWord(NtoLE($00000000));
  1154. ObjStream.WriteDWord(NtoLE($00000000));
  1155. ObjStream.WriteDWord(NtoLE($00145555));
  1156. ObjStream.WriteDWord(NtoLE($00000A0F));
  1157. ObjStream.WriteWord(NtoLE($0100));
  1158. ObjStream.WriteDWord(NtoLE($00030005));
  1159. for i := 0 to 5 do
  1160. ObjStream.WriteDWord($00000000);
  1161. ObjStream.WriteWord($0000);
  1162. // okay now the fun stuff
  1163. for i := 0 to $FF do
  1164. ObjStream.Write(ObjInstEntries[i], SizeOF(TObjInstEntry));
  1165. {begin
  1166. if i = 1 then
  1167. Flags := 7
  1168. else
  1169. Flags := 0;
  1170. if (i >= $41) and (i <= $5A) then
  1171. Flags := Flags or 2;
  1172. if (i >= $61) and (i <= $7A) then
  1173. Flags := Flags or 1;
  1174. if i = $27 then
  1175. Flags := Flags or 6;
  1176. ObjStream.WriteWord(NtoLE(Flags));
  1177. ObjStream.WriteWord(NtoLE(Word(i)));
  1178. if (i >= $41) and (i <= $5A) then
  1179. ObjStream.WriteByte(NtoLE(i+$20))
  1180. else
  1181. ObjStream.WriteByte(NtoLE(i));
  1182. ObjStream.WriteByte(NtoLE(i));
  1183. ObjStream.WriteByte(NtoLE(i));
  1184. ObjStream.WriteByte(NtoLE(i));
  1185. ObjStream.WriteWord(NtoLE($0000));
  1186. end;}
  1187. ObjStream.WriteDWord(NtoLE($E66561C6));
  1188. ObjStream.WriteDWord(NtoLE($73DF6561));
  1189. ObjStream.WriteDWord(NtoLE($656F8C73));
  1190. ObjStream.WriteWord(NtoLE(word($6F9C)));
  1191. ObjStream.WriteByte($65);
  1192. // third bit of second entry
  1193. // write guid 8FA0D5A8-DEDF-11D0-9A61-00C04FB68BF7
  1194. ObjStream.WriteDWord(NtoLE($8FA0D5A8));
  1195. ObjStream.WriteWord(NtoLE($DEDF));
  1196. ObjStream.WriteWord(NtoLE(word($11D0)));
  1197. ObjStream.WriteWord(NtoLE(word($619A)));
  1198. ObjStream.WriteByte($00);
  1199. ObjStream.WriteByte($C0);
  1200. ObjStream.WriteByte($4F);
  1201. ObjStream.WriteByte($B6);
  1202. ObjStream.WriteByte($8B);
  1203. ObjStream.WriteByte($F7);
  1204. ObjStream.WriteDWord(NtoLE($04000000));
  1205. ObjStream.WriteDWord(NtoLE(DWord(1)));
  1206. ObjStream.WriteDWord(NtoLE(DWord(1252)));
  1207. ObjStream.WriteDWord(NtoLE(DWord(1033)));
  1208. ObjStream.WriteDWord(NtoLE(DWord(0)));
  1209. // second entry
  1210. // write guid 4662DAB0-D393-11D0-9A56-00C04FB68B66
  1211. ObjStream.WriteDWord(NtoLE($4662DAB0));
  1212. ObjStream.WriteWord(NtoLE($D393));
  1213. ObjStream.WriteWord(NtoLE(word($11D0)));
  1214. ObjStream.WriteWord(NtoLE(word($569A)));
  1215. ObjStream.WriteByte($00);
  1216. ObjStream.WriteByte($C0);
  1217. ObjStream.WriteByte($4F);
  1218. ObjStream.WriteByte($B6);
  1219. ObjStream.WriteByte($8B);
  1220. ObjStream.WriteByte($66);
  1221. ObjStream.WriteDWord(NtoLE(DWord(666))); // not kidding
  1222. ObjStream.WriteDWord(NtoLE(DWord(1252)));
  1223. ObjStream.WriteDWord(NtoLE(DWord(1033)));
  1224. ObjStream.WriteDWord(NtoLE(DWord(10031)));
  1225. ObjStream.WriteDWord(NtoLE(DWord(0)));
  1226. ObjStream.Position := 0;
  1227. AddStreamToArchive('$OBJINST', '/', ObjStream, True);
  1228. ObjStream.Free;
  1229. end;
  1230. procedure TChmWriter.WriteFiftiMain;
  1231. var
  1232. SearchWriter: TChmSearchWriter;
  1233. begin
  1234. if FTopicsStream.Size = 0 then
  1235. Exit;
  1236. SearchWriter := TChmSearchWriter.Create(FFiftiMainStream, FIndexedFiles);
  1237. // do not add an empty $FIftiMain
  1238. if not SearchWriter.HasData then
  1239. begin
  1240. FFullTextSearchAvailable := False;
  1241. SearchWriter.Free;
  1242. Exit;
  1243. end;
  1244. FFullTextSearchAvailable := True;
  1245. SearchWriter.WriteToStream;
  1246. SearchWriter.Free;
  1247. if FFiftiMainStream.Size = 0 then
  1248. Exit;
  1249. FFiftiMainStream.Position := 0;
  1250. PostAddStreamToArchive('$FIftiMain', '/', FFiftiMainStream);
  1251. end;
  1252. procedure TChmWriter.WriteWindows;
  1253. Var WindowStream : TMemoryStream;
  1254. i,j : Integer;
  1255. win : TChmWindow;
  1256. begin
  1257. if FWindows.Count>0 then
  1258. begin
  1259. WindowStream:=TMemoryStream.Create;
  1260. WindowStream.WriteDword(NToLE(dword(FWindows.Count)));
  1261. WindowStream.WriteDword(NToLE(dword(196))); // 1.1 or later. 188 is old style.
  1262. for i:=0 to FWindows.Count-1 Do
  1263. begin
  1264. Win:=TChmWindow(FWindows[i]);
  1265. WindowStream.WriteDwordLE (196); // 0 size of entry.
  1266. WindowStream.WriteDwordLE (0); // 4 unknown (bool Unicodestrings?)
  1267. WindowStream.WriteDword(NToLE(addstring(win.window_type ))); // 8 Arg 0, name of window
  1268. WindowStream.WriteDword(NToLE(dword(win.flags ))); // C valid fields
  1269. WindowStream.WriteDword(NToLE(dword(win.nav_style))); // 10 arg 10 navigation pane style
  1270. WindowStream.WriteDword(NToLE(addstring(win.title_bar_text))); // 14 Arg 1, title bar text
  1271. WindowStream.WriteDword(NToLE(dword(win.styleflags))); // 18 Arg 14, style flags
  1272. WindowStream.WriteDword(NToLE(dword(win.xtdstyleflags))); // 1C Arg 15, xtd style flags
  1273. WindowStream.WriteDword(NToLE(dword(win.left))); // 20 Arg 13, rect.left
  1274. WindowStream.WriteDword(NToLE(dword(win.top))); // 24 Arg 13, rect.top
  1275. WindowStream.WriteDword(NToLE(dword(win.right))); // 28 Arg 13, rect.right
  1276. WindowStream.WriteDword(NToLE(dword(win.bottom))); // 2C Arg 13, rect.bottom
  1277. WindowStream.WriteDword(NToLE(dword(win.window_show_state))); // 30 Arg 16, window show state
  1278. WindowStream.WriteDword(NToLE(dword(0))); // 34 - , HWND hwndhelp OUT: window handle"
  1279. WindowStream.WriteDword(NToLE(dword(0))); // 38 - , HWND hwndcaller OUT: who called this window"
  1280. WindowStream.WriteDword(NToLE(dword(0))); // 3C - , HH_INFO_TYPE paINFO_TYPES IN: Pointer to an array of Information Types"
  1281. WindowStream.WriteDword(NToLE(dword(0))); // 40 - , HWND hwndtoolbar OUT: toolbar window in tri-pane window"
  1282. WindowStream.WriteDword(NToLE(dword(0))); // 44 - , HWND hwndnavigation OUT: navigation window in tri-pane window"
  1283. WindowStream.WriteDword(NToLE(dword(0))); // 48 - , HWND hwndhtml OUT: window displaying HTML in tri-pane window"
  1284. WindowStream.WriteDword(NToLE(dword(win.navpanewidth))); // 4C Arg 11, width of nav pane
  1285. WindowStream.WriteDword(NToLE(dword(0))); // 50 - , rect.left, OUT:Specifies the coordinates of the Topic pane
  1286. WindowStream.WriteDword(NToLE(dword(0))); // 54 - , rect.top , OUT:Specifies the coordinates of the Topic pane
  1287. WindowStream.WriteDword(NToLE(dword(0))); // 58 - , rect.right, OUT:Specifies the coordinates of the Topic pane
  1288. WindowStream.WriteDword(NToLE(dword(0))); // 5C - , rect.bottom, OUT:Specifies the coordinates of the Topic pane
  1289. WindowStream.WriteDword(NToLE(addstring(win.toc_file))); // 60 Arg 2, toc file
  1290. WindowStream.WriteDword(NToLE(addstring(win.index_file))); // 64 Arg 3, index file
  1291. WindowStream.WriteDword(NToLE(addstring(win.default_file))); // 68 Arg 4, default file
  1292. WindowStream.WriteDword(NToLE(addstring(win.home_button_file))); // 6c Arg 5, home button file.
  1293. WindowStream.WriteDword(NToLE(dword(win.buttons))); // 70 arg 12,
  1294. WindowStream.WriteDword(NToLE(dword(win.navpane_initially_closed))); // 74 arg 17
  1295. WindowStream.WriteDword(NToLE(dword(win.navpane_default))); // 78 arg 18,
  1296. WindowStream.WriteDword(NToLE(dword(win.navpane_location))); // 7C arg 19,
  1297. WindowStream.WriteDword(NToLE(dword(win.wm_notify_id))); // 80 arg 20,
  1298. for j:=0 to 4 do
  1299. WindowStream.WriteDword(NToLE(dword(0))); // 84 - byte[20] unknown - "BYTE tabOrder[HH_MAX_TABS + 1]; // IN/OUT: tab order: Contents, Index, Search, History, Favorites, Reserved 1-5, Custom tabs"
  1300. WindowStream.WriteDword(NToLE(dword(0))); // 94 - int cHistory; // IN/OUT: number of history items to keep (default is 30)
  1301. WindowStream.WriteDword(NToLE(addstring(win.Jumpbutton_1_Text))); // 9C Arg 7, The text of the Jump 1 button.
  1302. WindowStream.WriteDword(NToLE(addstring(win.Jumpbutton_2_Text))); // A0 Arg 9, The text of the Jump 2 button.
  1303. WindowStream.WriteDword(NToLE(addstring(win.Jumpbutton_1_File))); // A4 Arg 6, The file shown for Jump 1 button.
  1304. WindowStream.WriteDword(NToLE(addstring(win.Jumpbutton_2_File))); // A8 Arg 8, The file shown for Jump 1 button.
  1305. for j:=0 to 3 do
  1306. WindowStream.WriteDword(NToLE(dword(0))); // AA - byte[16] (TRECT) "RECT rcMinSize; // Minimum size for window (ignored in version 1)"
  1307. // 1.1+ fields
  1308. WindowStream.WriteDword(NToLE(dword(0))); // BC - int cbInfoTypes; // size of paInfoTypes;
  1309. WindowStream.WriteDword(NToLE(dword(0))); // C0 - LPCTSTR pszCustomTabs; // multiple zero-terminated strings
  1310. end;
  1311. WindowStream.Position := 0;
  1312. AddStreamToArchive('#WINDOWS', '/', WindowStream, True);
  1313. WindowStream.Free;
  1314. end;
  1315. end;
  1316. procedure TChmWriter.WriteInternalFilesAfter;
  1317. begin
  1318. // This creates and writes the #ITBITS (empty) file to section0
  1319. WriteITBITS;
  1320. // This creates and writes the #SYSTEM file to section0
  1321. WriteSystem;
  1322. if Assigned(FTocSM) then
  1323. Scansitemap(FTocSM);
  1324. end;
  1325. procedure TChmWriter.WriteFinalCompressedFiles;
  1326. begin
  1327. inherited WriteFinalCompressedFiles;
  1328. WriteTOPICS;
  1329. WriteURL_STR_TBL;
  1330. WriteWINDOWS;
  1331. CreateIDXHDRStream;
  1332. WriteIDXHDR;
  1333. WriteSTRINGS;
  1334. WriteFiftiMain;
  1335. end;
  1336. procedure TChmWriter.FileAdded(AStream: TStream; const AEntry: TFileEntryRec);
  1337. begin
  1338. inherited FileAdded(AStream, AEntry);
  1339. if FullTextSearch then
  1340. CheckFileMakeSearchable(AStream, AEntry);
  1341. end;
  1342. procedure TChmWriter.WriteInternalFilesBefore;
  1343. begin
  1344. inherited WriteInternalFilesBefore;
  1345. WriteIVB;
  1346. WriteOBJINST;
  1347. end;
  1348. constructor TChmWriter.Create(AOutStream: TStream; FreeStreamOnDestroy: Boolean);
  1349. begin
  1350. inherited Create(AOutStream, FreeStreamOnDestroy);
  1351. FStringsStream := TmemoryStream.Create;
  1352. FTopicsStream := TMemoryStream.Create;
  1353. FURLSTRStream := TMemoryStream.Create;
  1354. FURLTBLStream := TMemoryStream.Create;
  1355. FFiftiMainStream := TMemoryStream.Create;
  1356. FIndexedFiles := TIndexedWordList.Create;
  1357. FAVLTopicdedupe :=TAVLTree.Create(@CompareStrings); // dedupe filenames in topics.
  1358. FAvlStrings := TAVLTree.Create(@CompareStrings); // dedupe strings
  1359. FAvlURLStr := TAVLTree.Create(@CompareUrlStrs); // dedupe urltbl + binindex must resolve URL to topicid
  1360. SpareString := TStringIndex.Create; // We need an object to search in avltree
  1361. SpareUrlStr := TUrlStrIndex.Create; // to avoid create/free circles we keep one in spare
  1362. FIDXHdrStream := TMemoryStream.Create; // the #IDXHDR and chunk 13 in #SYSTEM
  1363. // for searching purposes
  1364. FWindows := TObjectlist.Create(True);
  1365. FDefaultWindow:= '';
  1366. FMergeFiles :=TStringList.Create;
  1367. FNrTopics :=0;
  1368. FDictTopicsUrlInd :=specialize TDictionary<string,integer>.Create;
  1369. end;
  1370. destructor TChmWriter.Destroy;
  1371. begin
  1372. if Assigned(FContextStream) then FContextStream.Free;
  1373. FMergeFiles.Free;
  1374. FIndexedFiles.Free;
  1375. FStringsStream.Free;
  1376. FTopicsStream.Free;
  1377. FURLSTRStream.Free;
  1378. FURLTBLStream.Free;
  1379. FFiftiMainStream.Free;
  1380. FIDXHdrStream.Free;
  1381. SpareString.free;
  1382. SpareUrlStr.free;
  1383. FAvlUrlStr.FreeAndClear;
  1384. FAvlUrlStr.Free;
  1385. FAvlStrings.FreeAndClear;
  1386. FAvlStrings.Free;
  1387. FAVLTopicdedupe.FreeAndClear;
  1388. FAVLTopicdedupe.free;
  1389. FWindows.Free;
  1390. FDictTopicsUrlInd.Free;
  1391. inherited Destroy;
  1392. end;
  1393. function TChmWriter.AddString(AString: String): LongWord;
  1394. var
  1395. NextBlock: DWord;
  1396. Pos: DWord;
  1397. n : TAVLTreeNode;
  1398. StrRec : TStringIndex;
  1399. begin
  1400. // #STRINGS starts with a null char
  1401. if FStringsStream.Size = 0 then FStringsStream.WriteByte(0);
  1402. SpareString.TheString:=AString;
  1403. n:=fAvlStrings.FindKey(SpareString,@CompareStrings);
  1404. if assigned(n) then
  1405. exit(TStringIndex(n.data).strid);
  1406. // each entry is a null terminated string
  1407. Pos := DWord(FStringsStream.Position);
  1408. // Strings are contained in $1000 byte blocks and cannot cross blocks
  1409. NextBlock := ($0000F000 and Pos) + $00001000;
  1410. if Length(AString) + 1 > NextBlock then
  1411. begin
  1412. FStringsStream.Size:= NextBlock;
  1413. FStringsStream.Position := NextBlock;
  1414. end;
  1415. Result := FStringsStream.Position;
  1416. if length(AString)>0 Then
  1417. FStringsStream.WriteBuffer(AString[1], Length(AString));
  1418. FStringsStream.WriteByte(0);
  1419. StrRec:=TStringIndex.Create;
  1420. StrRec.TheString:=AString;
  1421. StrRec.Strid :=Result;
  1422. fAvlStrings.Add(StrRec);
  1423. end;
  1424. function TChmWriter.AddURL ( AURL: String; TopicsIndex: DWord ) : LongWord;
  1425. procedure CheckURLStrBlockCanHold(Const AString: String);
  1426. var
  1427. Rem: LongWord;
  1428. Len: LongWord;
  1429. begin
  1430. Rem := $4000 - (FURLSTRStream.Size mod $4000);
  1431. Len := 9 + Length(AString); // 2 dwords the string and NT
  1432. if Rem < Len then
  1433. while Rem > 0 do
  1434. begin
  1435. FURLSTRStream.WriteByte(0);
  1436. Dec(Rem);
  1437. end;
  1438. end;
  1439. function AddURLString(Const AString: String): DWord;
  1440. var urlstrrec : TUrlStrIndex;
  1441. begin
  1442. CheckURLStrBlockCanHold(AString);
  1443. if FURLSTRStream.Size mod $4000 = 0 then
  1444. FURLSTRStream.WriteByte(0);
  1445. Result := FURLSTRStream.Position;
  1446. UrlStrRec:=TUrlStrIndex.Create;
  1447. UrlStrRec.UrlStr:=AString;
  1448. UrlStrRec.UrlStrid:=result;
  1449. FAvlUrlStr.Add(UrlStrRec);
  1450. FURLSTRStream.WriteDWord(NToLE(DWord(0))); // URL Offset for topic after the the "Local" value
  1451. FURLSTRStream.WriteDWord(NToLE(DWord(0))); // Offset of FrameName??
  1452. if Length(AString) > 0 then
  1453. FURLSTRStream.Write(AString[1], Length(AString));
  1454. FURLSTRStream.WriteByte(0); //NT
  1455. end;
  1456. function LookupUrlString(const AUrl : String):DWord;
  1457. var n :TAvlTreeNode;
  1458. begin
  1459. SpareUrlStr.UrlStr:=AUrl;
  1460. n:=FAvlUrlStr.FindKey(SpareUrlStr,@CompareUrlStrs);
  1461. if assigned(n) Then
  1462. result:=TUrlStrIndex(n.data).UrlStrId
  1463. else
  1464. result:=AddUrlString(AUrl);
  1465. end;
  1466. var UrlIndex : Integer;
  1467. begin
  1468. if (Length(AURL) > 0) and (AURL[1] = '/') then Delete(AURL,1,1);
  1469. UrlIndex:=LookupUrlString(AUrl);
  1470. //if $1000 - (FURLTBLStream.Size mod $1000) = 4 then // we are at 4092
  1471. if FURLTBLStream.Size and $FFC = $FFC then // faster :)
  1472. FURLTBLStream.WriteDWord(0);
  1473. Result := FURLTBLStream.Position;
  1474. FURLTBLStream.WriteDWord(0);//($231e9f5c); //unknown
  1475. FURLTBLStream.WriteDWord(NtoLE(TopicsIndex)); // Index of topic in #TOPICS
  1476. FURLTBLStream.WriteDWord(NtoLE(UrlIndex));
  1477. end;
  1478. procedure TChmWriter.CheckFileMakeSearchable(AStream: TStream; AFileEntry: TFileEntryRec);
  1479. var
  1480. TopicEntry: TTopicEntry;
  1481. ATitle: String;
  1482. begin
  1483. if Pos('.ht', AFileEntry.Name) > 0 then
  1484. begin
  1485. ATitle := FIndexedFiles.IndexFile(AStream, NextTopicIndex, FSearchTitlesOnly);
  1486. AddTopic(ATitle,AFileEntry.Path+AFileEntry.Name,-1);
  1487. end;
  1488. end;
  1489. function TChmWriter.AddTopic(ATitle,AnUrl:AnsiString;code:integer=-1):integer;
  1490. var
  1491. TopicEntry: TTopicEntry;
  1492. begin
  1493. ATitle :=StringReplace(Atitle, '&x27;', '', [rfReplaceAll]);
  1494. anurl:=StringReplace(anurl, '\', '/', [rfReplaceAll]);
  1495. if ATitle <> '' then
  1496. TopicEntry.StringsOffset := AddString(ATitle)
  1497. else
  1498. TopicEntry.StringsOffset := $FFFFFFFF;
  1499. result:=NextTopicIndex;
  1500. TopicEntry.URLTableOffset := AddURL(AnUrl, Result);
  1501. if code=-1 then
  1502. begin
  1503. if ATitle<>'' then
  1504. TopicEntry.InContents := 6
  1505. else
  1506. TopicEntry.InContents := 2;
  1507. if pos('#',AnUrl)>0 then
  1508. TopicEntry.InContents := 0;
  1509. end
  1510. else
  1511. TopicEntry.InContents := code;
  1512. inc(FNrTopics);
  1513. TopicEntry.Unknown := 0;
  1514. TopicEntry.TocOffset := 0;
  1515. FTopicsStream.WriteDWord(LEtoN(TopicEntry.TocOffset));
  1516. FTopicsStream.WriteDWord(LEtoN(TopicEntry.StringsOffset));
  1517. FTopicsStream.WriteDWord(LEtoN(TopicEntry.URLTableOffset));
  1518. FTopicsStream.WriteWord(LEtoN(TopicEntry.InContents));
  1519. FTopicsStream.WriteWord(LEtoN(TopicEntry.Unknown));
  1520. {$ifdef binindex}
  1521. writeln('topout:',result, ' ' , TopicEntry.StringsOffset,' ' ,TopicEntry.URLTableOffset, ' ',atitle,' - ', anurl);
  1522. {$endif}
  1523. end;
  1524. function TChmWriter.AddTopicindex(ATitle, AnUrl: AnsiString; code: integer
  1525. ): integer;
  1526. begin
  1527. ATitle :=StringReplace(Atitle, '&x27;', '', [rfReplaceAll]);
  1528. // adhoc subsitutions. Replace with real code if exact behaviour is known.
  1529. { Atitle:=StringReplace(atitle, '&x27;', '''', [rfReplaceAll]);
  1530. if length(atitle)>0 then
  1531. atitle[1]:=uppercase(atitle[1])[1];}
  1532. {$ifdef binindex}
  1533. writeln('Enter ',ATitle,' ',AnUrl);
  1534. {$endif}
  1535. if FDictTopicsUrlInd.trygetvalue(anurl,result) then
  1536. begin
  1537. {$ifdef binindex}
  1538. writeln('found:',result);
  1539. {$endif}
  1540. end
  1541. else
  1542. begin
  1543. result:=addtopic(atitle,anurl);
  1544. FDictTopicsUrlInd.add(anurl,result);
  1545. end;
  1546. end;
  1547. procedure TChmWriter.ScanSitemap(asitemap:TCHMSiteMap);
  1548. procedure scanitems(it:TChmSiteMapItems);
  1549. var i : integer;
  1550. x : TChmSiteMapItem;
  1551. s : string;
  1552. strrec : TStringIndex;
  1553. begin
  1554. for i:=0 to it.count -1 do
  1555. begin
  1556. x:=it.item[i];
  1557. // if sanitizeurl(fbasepath,x.local,S) then // sanitize, remove stuff etc.
  1558. // begin
  1559. // writeln(x.text,' : ',x.local,' ',x.url,' ' ,x.merge);
  1560. if assigned(x.children) and (x.children.count>0) then
  1561. scanitems(x.children);
  1562. end;
  1563. end;
  1564. begin
  1565. scanitems(asitemap.items);
  1566. end;
  1567. function TChmWriter.NextTopicIndex: Integer;
  1568. begin
  1569. Result := FTopicsStream.Size div 16;
  1570. end;
  1571. procedure TChmWriter.AppendTOC(AStream: TStream);
  1572. var tmpstr : string;
  1573. begin
  1574. fHasTOC := True;
  1575. if fTocName = '' then
  1576. tmpstr := defaulthhc
  1577. else
  1578. tmpstr := fTocName;
  1579. PostAddStreamToArchive(tmpstr, '/', AStream, True);
  1580. end;
  1581. procedure TChmWriter.AppendBinaryTOCFromSiteMap(ASiteMap: TChmSiteMap);
  1582. var
  1583. Header: TTOCIdxHeader;
  1584. Entry: TTocEntry;
  1585. EntryInfo: TTOCEntryPageBookInfo;
  1586. EntryInfoStream,
  1587. EntryTopicOffsetStream,
  1588. EntryStream: TMemoryStream;
  1589. TOCIDXStream: TMemoryStream;
  1590. NextLevelItems,
  1591. CurrentLevelItems: TFPList;
  1592. i,j: Integer;
  1593. MenuItem: TChmSiteMapItem;
  1594. MenuItems: TChmSiteMapItems;
  1595. TopicEntry: TTopicEntry;
  1596. EntryCount: DWord = $29A;
  1597. procedure FixParentBookFirstChildOffset(AChildOffset: DWord);
  1598. var
  1599. ParentEntry: TTOCEntryPageBookInfo;
  1600. begin
  1601. // read parent entry
  1602. EntryInfoStream.Position := MenuItems.InternalData;
  1603. EntryInfoStream.Read(ParentEntry, SizeOf(ParentEntry));
  1604. // update child offset
  1605. ParentEntry.FirstChildOffset:= NtoLE(DWord(4096 + AChildOffset));
  1606. // write back to stream
  1607. EntryInfoStream.Position := MenuItems.InternalData;
  1608. EntryInfoStream.Write(ParentEntry, SizeOf(ParentEntry));
  1609. // move to end of stream
  1610. EntryInfoStream.Position := AChildOffset;
  1611. end;
  1612. begin
  1613. FillChar(Header, 4096, 0);
  1614. // create streams
  1615. TOCIDXStream := TMemoryStream.Create;
  1616. EntryInfoStream := TMemoryStream.Create;
  1617. EntryTopicOffsetStream := TMemoryStream.Create;
  1618. EntryStream := TMemoryStream.Create;
  1619. NextLevelItems := TFPList.Create;
  1620. NextLevelItems.Add(ASiteMap.Items);
  1621. if NextLevelItems.Count = 0 then
  1622. FreeAndNil(NextLevelItems);
  1623. while NextLevelItems <> nil do
  1624. begin
  1625. CurrentLevelItems := NextLevelItems;
  1626. NextLevelItems := TFPList.Create;
  1627. for i := 0 to CurrentLevelItems.Count-1 do
  1628. begin
  1629. MenuItems := TChmSiteMapItems(CurrentLevelItems.Items[i]);
  1630. for j := 0 to MenuItems.Count-1 do
  1631. begin
  1632. MenuItem := MenuItems.Item[j];
  1633. // first figure out the props
  1634. EntryInfo.Props := 0;
  1635. if MenuItem.Children.Count > 0 then
  1636. EntryInfo.Props := EntryInfo.Props or TOC_ENTRY_HAS_CHILDREN;
  1637. if Length(MenuItem.Local) > 0 then
  1638. EntryInfo.Props := EntryInfo.Props or TOC_ENTRY_HAS_LOCAL;
  1639. if EntryInfo.Props and TOC_ENTRY_HAS_LOCAL > 0 then
  1640. begin
  1641. // Write #TOPICS entry
  1642. TopicEntry.TocOffset := NtoLE(DWord(4096 + EntryInfoStream.Position));
  1643. TopicEntry.StringsOffset := NtoLE(AddString(MenuItem.Text));
  1644. TopicEntry.URLTableOffset := NtoLE(AddURL(MenuItem.Local, NextTopicIndex));
  1645. TopicEntry.InContents := NtoLE(Word( 2 ));
  1646. TopicEntry.Unknown := 0;
  1647. EntryInfo.TopicsIndexOrStringsOffset := NtoLE(Dword(NextTopicIndex));;
  1648. FTopicsStream.Write(TopicEntry, SizeOf(TopicEntry));
  1649. EntryTopicOffsetStream.WriteDWord(EntryInfo.TopicsIndexOrStringsOffset);
  1650. // write TOCEntry
  1651. Entry.PageBookInfoOffset:= NtoLE(4096 + EntryInfoStream.Position);
  1652. Entry.IncrementedInt := NtoLE(EntryCount);
  1653. EntryStream.Write(Entry, SizeOf(Entry));
  1654. Inc(EntryCount);
  1655. end
  1656. else
  1657. begin
  1658. EntryInfo.TopicsIndexOrStringsOffset := NtoLE(AddString(MenuItem.Text));
  1659. end;
  1660. // write TOCEntryInfo
  1661. EntryInfo.Unknown1 := 0;
  1662. EntryInfo.EntryIndex := NtoLE(Word(EntryCount - $29A)); //who knows how useful any of this is
  1663. if MenuItems.InternalData <> maxLongint then
  1664. EntryInfo.ParentPageBookInfoOffset := MenuItems.InternalData
  1665. else
  1666. EntryInfo.ParentPageBookInfoOffset := 0;
  1667. if j = MenuItems.Count-1 then
  1668. EntryInfo.NextPageBookOffset := 0
  1669. else if (EntryInfo.Props and TOC_ENTRY_HAS_CHILDREN) > 0 then
  1670. EntryInfo.NextPageBookOffset := 4096 + EntryInfoStream.Position + 28
  1671. else
  1672. EntryInfo.NextPageBookOffset := 4096 + EntryInfoStream.Position + 20;
  1673. // Only if TOC_ENTRY_HAS_CHILDREN is set are these written
  1674. EntryInfo.FirstChildOffset := 0; // we will update this when the child is written
  1675. // in fact lets update the *parent* of this item now if needed
  1676. if (j = 0) and (MenuItems.InternalData <> maxLongint) then
  1677. FixParentBookFirstChildOffset(EntryInfoStream.Position);
  1678. EntryInfo.Unknown3 := 0;
  1679. // fix endian order
  1680. EntryInfo.Props := NtoLE(EntryInfo.Props);
  1681. EntryInfo.ParentPageBookInfoOffset := NtoLE(EntryInfo.ParentPageBookInfoOffset);
  1682. EntryInfo.NextPageBookOffset := NtoLE(EntryInfo.NextPageBookOffset);
  1683. if MenuItem.Children.Count > 0 then
  1684. begin
  1685. NextLevelItems.Add(MenuItem.Children);
  1686. MenuItem.Children.InternalData := EntryInfoStream.Position;
  1687. end;
  1688. // write to stream
  1689. EntryInfoStream.Write(EntryInfo, PageBookInfoRecordSize(@EntryInfo));
  1690. end;
  1691. end;
  1692. FreeAndNil(CurrentLevelItems);
  1693. if NextLevelItems.Count = 0 then
  1694. FreeAndNil(NextLevelItems);
  1695. end;
  1696. // write all streams to TOCIdxStream and free everything
  1697. EntryInfoStream.Position:=0;
  1698. EntryTopicOffsetStream.Position:=0;
  1699. EntryStream.Position:=0;
  1700. Header.BlockSize := NtoLE(DWord(4096));
  1701. Header.EntriesCount := NtoLE(DWord(EntryCount - $29A));
  1702. Header.EntriesOffset := NtoLE(DWord(4096 + EntryInfoStream.Size + EntryTopicOffsetStream.Size));
  1703. Header.TopicsOffset := NtoLE(DWord(4096 + EntryInfoStream.Size));
  1704. TOCIDXStream.Write(Header, SizeOf(Header));
  1705. TOCIDXStream.CopyFrom(EntryInfoStream, EntryInfoStream.Size);
  1706. EntryInfoStream.Free;
  1707. TOCIDXStream.CopyFrom(EntryTopicOffsetStream, EntryTopicOffsetStream.Size);
  1708. EntryTopicOffsetStream.Free;
  1709. TOCIDXStream.CopyFrom(EntryStream, EntryStream.Size);
  1710. EntryStream.Free;
  1711. TOCIDXStream.Position := 0;
  1712. AppendBinaryTOCStream(TOCIDXStream);
  1713. TOCIDXStream.Free;
  1714. end;
  1715. Const
  1716. BinIndexIdent : array[0..1] of char = (CHR($3B),CHR($29));
  1717. AlwaysX44 : Array[0..15] of char = ('X','4','4',#0,#0,#0,#0,#0,
  1718. #0,#0,#0,#0,#0,#0,#0,#0);
  1719. DataEntry : Array[0..12] of Byte = ($00,$00,$00,$00,$05,$00,$00,$00,$80,$00,$00,$00,$00);
  1720. {
  1721. IndexStream:=TMemoryStream.Create;
  1722. IndexStream.Write(BinIndexIdent,2);
  1723. IndexStream.Write(NToLE(word(2)),2);
  1724. IndexStream.Write(NToLE(word(2048)),2);
  1725. IndexStream.Write(AlwaysX44,sizeof(AlwaysX44));
  1726. IndexStrem.Write (dword(0),2);
  1727. }
  1728. Const DefBlockSize = 2048;
  1729. Type TIndexBlock = Array[0..DefBlockSize-1] of Byte;
  1730. procedure writeword(var p:pbyte;w:word); inline;
  1731. begin
  1732. pword(p)^:=NToLE(w);
  1733. inc(pword(p));
  1734. end;
  1735. procedure writedword(var p:pbyte;d:dword); inline;
  1736. begin
  1737. pdword(p)^:=NToLE(d);
  1738. inc(pdword(p));
  1739. end;
  1740. procedure TChmWriter.AppendBinaryIndexFromSiteMap(ASiteMap: TChmSiteMap;chw:boolean);
  1741. Var
  1742. IndexStream : TMemoryStream;
  1743. //n : Integer;
  1744. curblock : TIndexBlock; // current listing block being built
  1745. TestBlock : TIndexBlock; // each entry is first built here. then moved to curblock
  1746. curind : integer; // next byte to write in testblock.
  1747. blocknr : Integer; // blocknr of block in testblock;
  1748. lastblock : Integer; // blocknr of last block.
  1749. Entries : Integer; // Number of entries in this block so far
  1750. TotalEntries: Integer; // Total number of entries
  1751. MapEntries : Integer;
  1752. MapIndex : Integer;
  1753. indexblocknr: Integer;
  1754. blockind : Integer; // next byte to write in blockn[blocknr]
  1755. blockentries: Integer; // entries so far ins blockn[blocknr]
  1756. blockn : Array Of TIndexBlock;
  1757. BlockNPlus1 : Array of TIndexBlock;
  1758. Mod13value : integer; // A value that is increased by 13 for each entry. (?!?!)
  1759. EntryToIndex: boolean; // helper var to make sure the first block is always indexed.
  1760. blocknplusindex : Integer; // blocks in level n+1 (second part)
  1761. blocknplusentries : Integer; // The other blocks indexed on creation.
  1762. datastream,mapstream,propertystream : TMemoryStream;
  1763. procedure preparecurrentblock(force:boolean);
  1764. var p: PBTreeBlockHeader;
  1765. begin
  1766. {$ifdef binindex}
  1767. writeln('prepcurblock ' ,Entries,' ',lastblock,' ' ,blocknr,' ',indexstream.position);
  1768. {$endif}
  1769. p:=@curblock[0];
  1770. fillchar(p^,sizeof(TBtreeBlockHeader),#0);
  1771. p^.Length:=NToLE(Defblocksize-curind);
  1772. p^.NumberOfEntries:=Entries;
  1773. p^.IndexOfPrevBlock:=cardinal(lastblock); // lastblock can be -1, avoid rangecheck
  1774. p^.IndexOfNextBlock:=Blocknr;
  1775. if force and (blocknr=0) then // only one listblock -> no indexblocks.
  1776. p^.IndexOfNextBlock:=dword(-1);
  1777. IndexStream.Write(curblock[0],Defblocksize);
  1778. fillchar(curblock[0],DefBlockSize,#0);
  1779. MapStream.Write(NToLE(MapEntries),sizeof(dword));
  1780. MapStream.Write(NToLE(BlockNr),Sizeof(DWord));
  1781. MapEntries:=TotalEntries;
  1782. curind:=sizeof(TBtreeBlockHeader); // index into current block;
  1783. lastblock:=blocknr;
  1784. inc(blocknr);
  1785. Entries:=0;
  1786. {$ifdef binindex}
  1787. writeln('prepcurblock post' , indexstream.position);
  1788. {$endif}
  1789. end;
  1790. procedure prepareindexblockn(listingblocknr:integer);
  1791. var p:PBTreeIndexBlockHeader;
  1792. begin
  1793. {$ifdef binindex}
  1794. writeln('prepindexblockn');
  1795. {$endif}
  1796. p:=@Blockn[IndexBlockNr];
  1797. p^.Length:=defblocksize-BlockInd;
  1798. p^.NumberOfEntries:=BlockEntries;
  1799. // p^.IndexOfChildBlock // already entered on block creation, since of first entry, not last.
  1800. inc(Indexblocknr);
  1801. BlockEntries:=0;
  1802. BlockInd:=0;
  1803. if Indexblocknr>=length(blockn) then
  1804. begin
  1805. setlength(blockn,length(blockn)+1); // larger increments also possible. #blocks is kept independantly.
  1806. fillchar(blockn[0][0],sizeof(blockn[0]),#0);
  1807. end;
  1808. p:=@Blockn[IndexBlockNr];
  1809. p^.IndexOfChildBlock:=ListingBlockNr;
  1810. blockind:=sizeof(TBTreeIndexBlockHeader);
  1811. end;
  1812. procedure finalizeindexblockn(p:pbyte;var ind:integer;xEntries:integer);
  1813. var ph:PBTreeIndexBlockHeader;
  1814. begin
  1815. ph:=PBTreeIndexBlockHeader(p);
  1816. ph^.Length:=defblocksize-Ind;
  1817. ph^.NumberOfEntries:=xEntries;
  1818. // p^.IndexOfChildBlock // already entered on block creation, since of first entry, not last.
  1819. // inc(Ind);
  1820. end;
  1821. procedure CurEntryToIndex(entrysize:integer);
  1822. var p,pentry : pbyte;
  1823. indexentrysize : integer;
  1824. begin
  1825. {$ifdef binindex}
  1826. writeln('curentrytoindex ', entrysize);
  1827. {$endif}
  1828. indexentrysize:=entrysize-sizeof(dword); // index entry is 4 bytes shorter, and only the last dword differs
  1829. if (blockind+indexentrysize)>=Defblocksize then
  1830. prepareindexblockn(blocknr);
  1831. p:=@blockn[Indexblocknr][blockind];
  1832. move(testblock[0],p^,indexentrysize);
  1833. pentry:=@p[indexentrysize-sizeof(dword)]; // ptr to last dword
  1834. writedword(pentry,blocknr); // patch up the "index of child field"
  1835. inc(blockind,indexentrysize);
  1836. end;
  1837. procedure WritestrNT(var p:pbyte;const str:Unicodestring);
  1838. var i : integer;
  1839. p2 : pbyte;
  1840. begin
  1841. p2:=p;
  1842. for i:=1 to Length(str) do
  1843. WriteWord(p2,Word(str[i])); // write the wstr in little endian
  1844. WriteWord(p2,0); // NT
  1845. p:=p2;
  1846. end;
  1847. procedure CreateEntry(Item:TChmSiteMapItem;const Str:UnicodeString;commaatposition,level:integer);
  1848. var p : pbyte;
  1849. topicid: integer;
  1850. seealso: Integer;
  1851. entrysize:Integer;
  1852. i : Integer;
  1853. sb :TChmSiteMapSubItem;
  1854. begin
  1855. inc(TotalEntries);
  1856. fillchar(testblock[0],DefBlockSize,#0);
  1857. p:=@TestBlock[0];
  1858. WritestrNT(p,Str);
  1859. if item.seealso='' then // no seealso for now
  1860. seealso:=0
  1861. else
  1862. seealso:=2;
  1863. WriteWord(p,seealso); // =0 not a see also 2 =seealso
  1864. WriteWord(p,level); // Entrydepth. We can't know it, so write 2.
  1865. WriteDword(p,commaatposition); // position of the comma
  1866. WriteDword(p,0); // unused 0
  1867. if seealso=2 then
  1868. begin
  1869. {$ifdef binindex}
  1870. write('!seealso');
  1871. {$endif}
  1872. WriteDword(p,1);
  1873. WritestrNT(p,item.seealso)
  1874. end
  1875. else
  1876. begin
  1877. WriteDword(p,item.SubItemcount);
  1878. for i:=0 to item.SubItemcount-1 do
  1879. begin
  1880. sb:=item.SubItem[i];
  1881. if sb.name='' then
  1882. sb.name:=item.name;
  1883. {$ifdef binindex}
  1884. writeln('---',sb.name,' ',sb.local);
  1885. {$endif}
  1886. TopicId:=AddTopicIndex(sb.Name,sb.Local);
  1887. WriteDword(p,TopicId);
  1888. end;
  1889. end;
  1890. WriteDword(p,1); // always 1 (unknown);
  1891. WriteDword(p,mod13value); //a value that increments with 13.
  1892. mod13value:=mod13value+13;
  1893. entrysize:=p-pbyte(@testblock[0]);
  1894. {$ifdef binindex}
  1895. writeln(curind, ' ',entrysize, ' ',defblocksize);
  1896. writeln('curstr ',str,' ',commaatposition);
  1897. {$endif}
  1898. if (curind+entrysize)>=Defblocksize then
  1899. begin
  1900. {$ifdef binindex}
  1901. writeln('larger!');
  1902. {$endif}
  1903. preparecurrentblock(False);
  1904. EntrytoIndex:=true;
  1905. end;
  1906. if EntryToIndex Then
  1907. begin
  1908. {$ifdef binindex}
  1909. writeln('entrytoindex');
  1910. {$endif}
  1911. CurEntryToIndex(entrysize);
  1912. EntryToIndex:=False;
  1913. end;
  1914. move(testblock[0],curblock[curind],entrysize);
  1915. inc(curind,entrysize);
  1916. datastream.write(DataEntry,Sizeof(DataEntry));
  1917. inc(Entries);
  1918. end;
  1919. procedure MoveIndexEntry(nr:integer;bytes:integer;childblock:integer);
  1920. var
  1921. pscr,pdest : pbyte;
  1922. begin
  1923. {$ifdef binindex}
  1924. writeln(' moveindexentry ',nr,' bytes:',bytes,' childblock:',childblock);
  1925. flush(stdout);
  1926. {$endif}
  1927. if ((blockind+bytes)>=defblocksize) then
  1928. begin
  1929. {$ifdef binindex}
  1930. writeln(' in scalecheck ',blockind);
  1931. flush(stdout);
  1932. {$endif}
  1933. FinalizeIndexBlockn(@blocknplus1[blocknplusindex][0],blockind,blocknplusentries);
  1934. inc(blocknplusindex);
  1935. if blocknplusindex>=length(blocknplus1) then
  1936. begin
  1937. setlength(blocknplus1,length(blocknplus1)+1);
  1938. fillchar(blocknplus1[length(blocknplus1)-1][0],sizeof(blocknplus1[0]),#0);
  1939. end;
  1940. blockInd:=Sizeof(TBTreeIndexBlockHeader);
  1941. pdword(@blocknplus1[blocknplusindex][0])[4]:=NToLE(ChildBlock); /// init 2nd level index to first 1st level index block
  1942. end;
  1943. {$ifdef binindex}
  1944. writeln(' len:',length(blocknplus1),' blockind:',blockind,' index:',blocknplusindex);
  1945. flush(stdout);
  1946. {$endif}
  1947. // copy entry from one indexblock to another
  1948. pscr:=@blockn[nr][sizeof(TBtreeIndexBlockHeader)];
  1949. pdest:=@blocknplus1[blocknplusindex][blockind];
  1950. move(pscr^,pdest^,bytes);
  1951. pdword(@pdest[bytes-sizeof(dword)])^:=NToLE(childblock); // correcting the childindex
  1952. inc (blockind,bytes);
  1953. inc(blocknplusentries); // not needed for writing, but used to check if something has been written. End condition
  1954. end;
  1955. function ScanIndexBlock(blk:Pbyte):Integer;
  1956. var start : pbyte;
  1957. n : Integer;
  1958. i : Integer;
  1959. begin
  1960. start:=@blk[sizeof(TBtreeIndexBlockHeader)];
  1961. blk:=start;
  1962. while pword(blk)^<>0 do // skip wchar
  1963. inc(pword(blk));
  1964. inc(pword(blk)); // skip NT
  1965. inc(pword(blk)); // skip see also
  1966. inc(pword(blk)); // skip depth
  1967. inc(pdword(blk)); // skip Character Index.
  1968. inc(pdword(blk)); // skip always 0
  1969. n:=LEToN(pdword(blk)^);
  1970. inc(pdword(blk)); // skip nr of pairs.
  1971. for i:= 1 to n do
  1972. inc(pdword(blk)); // skip <n> topicids
  1973. inc(pdword(blk)); // skip childindex
  1974. Result:=blk-start;
  1975. end;
  1976. procedure CombineWithChildren(ParentItem:TChmSiteMapItem;Str:UnicodeString;commaatposition:integer;level:integer);
  1977. var i : Integer;
  1978. llItem : TChmSiteMapItem;
  1979. begin
  1980. str:=StringReplace(str, '&x27;', '', [rfReplaceAll]);
  1981. {$ifdef binindex}
  1982. writeln('i:',level,' ',str);
  1983. {$endif}
  1984. // if ParentItem.Children.Count = 0 Then
  1985. // Begin
  1986. // comment/fix next
  1987. // if commatposition=length(str) then commaatposition:=0;
  1988. if level=0 then
  1989. CreateEntry(ParentItem,Str,0,level)
  1990. else
  1991. CreateEntry(ParentItem,Str,commaatposition,level);
  1992. // End
  1993. // Else
  1994. for i:=0 to ParentItem.Children.Count-1 do
  1995. begin
  1996. llitem := TChmSiteMapItem(ParentItem.Children.Item[i]);
  1997. { if level=0 Then
  1998. CombineWithChildren(Item,str+', '+item.text,0,level+1)
  1999. else}
  2000. CombineWithChildren(llItem,Str+', '+llitem.text,length(str)+2,level+1);
  2001. end;
  2002. end;
  2003. Var i : Integer;
  2004. Key : UnicodeString;
  2005. Item : TChmSiteMapItem;
  2006. ListingBlocks : Integer;
  2007. EntryBytes : Integer;
  2008. Hdr : TBTreeHeader;
  2009. TreeDepth : Integer;
  2010. {$ifdef binindex}
  2011. procedure printloopvars(i:integer);
  2012. begin
  2013. Writeln('location :' ,i, ' blocknr :', blocknr,' level:',TreeDepth);
  2014. Writeln('blockn length: ',length(blockn),' indexblocknr: ',indexblocknr,' blockind ',blockind);
  2015. Writeln('blocknplus1 length: ',length(blocknplus1),' blocknplusindex:',blocknplusindex,' entries:',blocknplusentries);
  2016. flush(stdout);
  2017. end;
  2018. {$endif}
  2019. begin
  2020. {$ifdef binindex}
  2021. writeln('starting index');
  2022. {$endif}
  2023. ASiteMap.sort(@indexitemcompare);
  2024. IndexStream:=TMemoryStream.Create;
  2025. indexstream.size:=sizeof(TBTreeHeader);
  2026. IndexStream.position:=Sizeof(TBTreeHeader);
  2027. datastream:=TMemoryStream.Create;
  2028. mapstream :=TMemoryStream.Create;
  2029. mapstream.size:=2;
  2030. mapstream.position:=2;
  2031. propertystream :=TMemoryStream.Create;
  2032. propertystream.write(NToLE(0),sizeof(longint));
  2033. // we iterate over all entries and write listingblocks directly to the stream.
  2034. // and the first (and maybe last) level is written to blockn.
  2035. // we can't do higher levels yet because we don't know how many listblocks we get
  2036. BlockNr :=0; // current block number
  2037. Lastblock :=-1; // previous block nr or -1 if none.
  2038. Entries :=0; // entries in this block
  2039. TotalEntries:=0; // entries so far.
  2040. Mod13value :=0; // value that increments by 13 entirely.
  2041. indexblocknr:=0; // nr of first index block.
  2042. BlockEntries:=0; // entries into current block;
  2043. MapEntries :=0; // entries before the current listing block, for MAP file
  2044. TreeDepth :=0;
  2045. fillchar(testblock[0],DefBlockSize,#0);
  2046. fillchar(curblock[0],DefBlockSize,#0);
  2047. curind :=sizeof(TBTreeBlockHeader); // index into current listing block;
  2048. blockind :=sizeof(TBtreeIndexBlockHeader); // index into current index block
  2049. Setlength(blockn,1);
  2050. fillchar(blockn[0][0],sizeof(blockn[0]),#0);
  2051. pdword(@blockn[0][4])^:=NToLE(0); /// init first listingblock nr to 0 in the first index block
  2052. EntryToIndex := True;
  2053. {$ifdef binindex}
  2054. writeln('items:',asitemap.items.count);
  2055. {$endif}
  2056. for i:=0 to ASiteMap.Items.Count-1 do
  2057. begin
  2058. item := TChmSiteMapItem(ASiteMap.Items.Item[i]);
  2059. key :=Item.Text;
  2060. {$ifdef binindex}
  2061. writeln('item: ',i,' ',key);
  2062. {$endif}
  2063. {$ifdef chm_windowsbinindex}
  2064. // append 2 to all index level 0 entries. This
  2065. // so we can see if Windows loads the binary or textual index.
  2066. CombineWithChildren(Item,Key+'2',length(key)+1,true);
  2067. {$else}
  2068. CombineWithChildren(Item,Key,length(key),0);
  2069. {$endif}
  2070. end;
  2071. PrepareCurrentBlock(True); // flush last listing block.
  2072. Listingblocks:=blocknr; // blocknr is from now on the number of the first block in blockn.
  2073. // we still need the # of listingblocks for the header though
  2074. {$ifdef binindex}
  2075. writeln('binindex: listingblocks : '+inttostr(listingblocks),' indexblocks: ',indexblocknr,' entries:',blockentries);
  2076. {$endif}
  2077. // we have now created and written the listing blocks, and created the first level of index in <blockn>
  2078. // the following loop uses <blockn> to calculate the next level (in blocknplus1), then write out blockn,
  2079. // and repeat until we have no entries left.
  2080. // First we finalize the current set of blocks
  2081. if blocknr>1 then
  2082. begin
  2083. if Blockind<>sizeof(TBtreeIndexBlockHeader) Then
  2084. begin
  2085. {$ifdef binindex}
  2086. writeln('finalizing level 1 index');
  2087. {$endif}
  2088. FinalizeIndexBlockN(@blockn[indexblocknr][0],blockind,blockentries); // also increasing indexblocknr
  2089. inc(IndexBlockNr);
  2090. end;
  2091. {$ifdef binindex}
  2092. writeln('binindex: listingblocks : '+inttostr(listingblocks),' indexblocks: ',indexblocknr,' entries:',blockentries);
  2093. {$endif}
  2094. while (Indexblocknr>1) do
  2095. begin
  2096. {$ifdef binindex}
  2097. printloopvars(1);
  2098. {$endif}
  2099. blockind :=sizeof(TBtreeIndexBlockHeader);
  2100. pdword(@blockn[0][4])^:=NToLE(Listingblocks); /// init 2nd level index to first 1st level index block
  2101. blocknplusindex :=0;
  2102. blocknplusentries :=0;
  2103. if length(blocknplus1)<1 then
  2104. begin
  2105. Setlength(blocknplus1,1);
  2106. fillchar(blocknplus1[0][0],sizeof(blocknplus1[0]),#0);
  2107. end;
  2108. EntryToIndex :=True;
  2109. {$ifdef binindex}
  2110. printloopvars(2);
  2111. {$endif}
  2112. for i:=0 to Indexblocknr-1 do
  2113. begin
  2114. Entrybytes:=ScanIndexBlock(@blockn[i][0]);
  2115. // writeln('after scan ,',i, ' bytes: ',entrybytes,' blocknr:',blocknr,' indexblocknr:',indexblocknr,' to:',blocknr+i);
  2116. MoveIndexEntry(i,Entrybytes,blocknr+i);
  2117. indexStream.Write(blockn[i][0],defblocksize);
  2118. end;
  2119. {$ifdef binindex}
  2120. printloopvars(3);
  2121. {$endif}
  2122. If Blockind<>sizeof(TBtreeIndexBlockHeader) Then
  2123. begin
  2124. {$ifdef binindex}
  2125. logentry('finalizing');
  2126. {$endif}
  2127. FinalizeIndexBlockn(@blocknplus1[blocknplusindex][0],blockind,blocknplusentries);
  2128. inc(blocknplusindex);
  2129. end;
  2130. inc(blocknr,indexblocknr);
  2131. indexblocknr:=blocknplusindex;
  2132. blockn:=copy(blocknplus1); setlength(blocknplus1,1);
  2133. {$ifdef binindex}
  2134. printloopvars(5);
  2135. {$endif}
  2136. inc(TreeDepth);
  2137. end;
  2138. indexStream.Write(blockn[0][0],defblocksize);
  2139. inc(blocknr);
  2140. end;
  2141. // Fixup header.
  2142. hdr.ident[0]:=chr($3B); hdr.ident[1]:=chr($29);
  2143. hdr.flags :=NToLE(word($2)); // bit $2 is always 1, bit $0400 1 if dir? (always on)
  2144. hdr.blocksize :=NToLE(word(defblocksize)); // size of blocks (2048)
  2145. hdr.dataformat :=AlwaysX44; // "X44" always the same, see specs.
  2146. hdr.unknown0 :=NToLE(0); // always 0
  2147. hdr.lastlstblock :=NToLE(dword(ListingBlocks-1)); // index of last listing block in the file;
  2148. hdr.indexrootblock :=NToLE(dword(blocknr-1)); // Index of the root block in the file.
  2149. hdr.unknown1 :=NToLE(dword(-1)); // always -1
  2150. hdr.nrblock :=NToLE(blocknr); // Number of blocks
  2151. hdr.treedepth :=NToLE(word(TreeDepth)); // The depth of the tree of blocks (1 if no index blocks, 2 one level of index blocks, ...)
  2152. hdr.nrkeywords :=NToLE(Totalentries); // number of keywords in the file.
  2153. hdr.codepage :=NToLE(dword(1252)); // Windows code page identifier (usually 1252 - Windows 3.1 US (ANSI))
  2154. hdr.lcid :=NToLE(0); // ???? LCID from the HHP file.
  2155. if not chw then
  2156. hdr.ischm :=NToLE(dword(1)) // 0 if this a BTREE and is part of a CHW file, 1 if it is a BTree and is part of a CHI or CHM file
  2157. else
  2158. hdr.ischm :=NToLE(0);
  2159. hdr.unknown2 :=NToLE(dword(10031)); // Unknown. Almost always 10031. Also 66631 (accessib.chm, ieeula.chm, iesupp.chm, iexplore.chm, msoe.chm, mstask.chm, ratings.chm, wab.chm).
  2160. hdr.unknown3 :=NToLE(0); // unknown 0
  2161. hdr.unknown4 :=NToLE(0); // unknown 0
  2162. hdr.unknown5 :=NToLE(0); // unknown 0
  2163. if totalentries<>0 then
  2164. begin
  2165. // If there are no links of this type in the CHM then this will be a zero DWORD. Othewise it contains the following DWORDs: 0, 0, 0, 0xC, 1, 1, 0, 0. AFAICS this file is pretty much useless.
  2166. // we already have written the first 0 dword
  2167. propertystream.write(NToLE(0),sizeof(longint));
  2168. propertystream.write(NToLE(0),sizeof(longint));
  2169. propertystream.write(NToLE($C),sizeof(longint));
  2170. propertystream.write(NToLE(1),sizeof(longint));
  2171. propertystream.write(NToLE(1),sizeof(longint));
  2172. propertystream.write(NToLE(0),sizeof(longint));
  2173. propertystream.write(NToLE(0),sizeof(longint));
  2174. end;
  2175. IndexStream.Position:=0;
  2176. IndexStream.write(hdr,sizeof(hdr));
  2177. {$ifdef binindex}
  2178. logentry('before append '+inttostr(indexstream.size));
  2179. {$endif}
  2180. AppendBinaryIndexStream(IndexStream,datastream,MapStream,PropertyStream,chw);
  2181. IndexStream.Free;
  2182. PropertyStream.Free;
  2183. MapStream.Free;
  2184. DataStream.Free;
  2185. FHasKLinks:=TotalEntries>0;
  2186. {$ifdef binindex}
  2187. writeln('end index');
  2188. {$endif}
  2189. end;
  2190. procedure TChmWriter.AppendBinaryTOCStream(AStream: TStream);
  2191. begin
  2192. AddStreamToArchive('#TOCIDX', '/', AStream, True);
  2193. end;
  2194. procedure TChmWriter.AppendBinaryIndexStream(IndexStream,DataStream,MapStream,Propertystream: TStream;chw:boolean);
  2195. procedure stadd(fn:string;stream:TStream);
  2196. begin
  2197. Stream.Position:=0;
  2198. if CHW then
  2199. fn:=uppercase(fn);
  2200. {$ifdef binindex}
  2201. logentry('before append '+fn);
  2202. {$endif}
  2203. AddStreamToArchive(fn,'/$WWKeywordLinks/',stream,True);
  2204. end;
  2205. begin
  2206. AddDummyALink;
  2207. stadd('BTree',IndexStream);
  2208. stadd('Data', DataStream);
  2209. stadd('Map' , MapStream);
  2210. stadd('Property', PropertyStream);
  2211. end;
  2212. procedure TChmWriter.AppendIndex(AStream: TStream);
  2213. var tmpstr : string;
  2214. begin
  2215. FHasIndex := True;
  2216. if fIndexName = '' then
  2217. tmpstr:=defaulthhk
  2218. else
  2219. tmpstr:=fIndexName;
  2220. PostAddStreamToArchive(tmpstr, '/', AStream, True);
  2221. end;
  2222. procedure TChmWriter.AppendSearchDB(AName: String; AStream: TStream);
  2223. begin
  2224. PostAddStreamToArchive(AName, '/', AStream);
  2225. end;
  2226. procedure TChmWriter.AddContext(AContext: DWord; ATopic: String);
  2227. var
  2228. Offset: DWord;
  2229. begin
  2230. if FContextStream = nil then begin
  2231. FContextStream:=TMemoryStream.Create;
  2232. // #IVB starts with a dword which is the size of the stream - sizeof(dword)
  2233. FContextStream.WriteDWord(0);
  2234. // we will update this when we write the file to the final stream
  2235. end;
  2236. // an entry is a context id and then the offset of the name of the topic in the strings file
  2237. FContextStream.WriteDWord(NToLE(AContext));
  2238. Offset := NToLE(AddString(ATopic));
  2239. FContextStream.WriteDWord(Offset);
  2240. end;
  2241. procedure TChmWriter.AddDummyALink;
  2242. var stream : TMemoryStream;
  2243. begin
  2244. stream:=tmemorystream.create;
  2245. stream.WriteDWord(0);
  2246. stream.position:=0;
  2247. AddStreamToArchive('Property','/$WWAssociativeLinks/',stream,True);
  2248. stream.free;
  2249. end;
  2250. procedure TChmWriter.Setwindows(AWindowList: TObjectList);
  2251. var i : integer;
  2252. x : TCHMWindow;
  2253. begin
  2254. FWindows.Clear;
  2255. for i:=0 to AWindowList.count -1 do
  2256. begin
  2257. x:=TChmWindow.Create;
  2258. x.assign(TChmWindow(AWindowList[i]));
  2259. Fwindows.Add(x);
  2260. end;
  2261. end;
  2262. procedure TChmWriter.SetMergefiles(src:TStringList);
  2263. var i : integer;
  2264. begin
  2265. FMergeFiles.Clear;
  2266. for i:=0 to Src.count -1 do
  2267. FMergefiles.add(src[i]);
  2268. end;
  2269. end.