chmwriter.pas 85 KB

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