chmreader.pas 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862
  1. { Copyright (C) <2005> <Andrew Haines> chmreader.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,
  12. Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  13. }
  14. {
  15. See the file COPYING.modifiedLGPL, included in this distribution,
  16. for details about the copyright.
  17. }
  18. unit chmreader;
  19. {$mode delphi}
  20. //{$DEFINE CHM_DEBUG}
  21. { $DEFINE CHM_DEBUG_CHUNKS}
  22. {define binindex}
  23. {define nonumber}
  24. interface
  25. uses
  26. Generics.Collections, Classes, SysUtils, Contnrs,
  27. chmbase, paslzx, chmFIftiMain, chmsitemap;
  28. type
  29. TLZXResetTableArr = array of QWord;
  30. PContextItem = ^TContextItem;
  31. TContextItem = record
  32. Context: THelpContext;
  33. Url: String;
  34. end;
  35. TContextList = class(TList)
  36. public
  37. procedure AddContext(Context: THelpContext; Url: String);
  38. function GetURL(Context: THelpContext): String;
  39. procedure Clear; override;
  40. end;
  41. { TITSFReader }
  42. TFileEntryForEach = procedure(Name: String; Offset, UncompressedSize, Section: Integer) of object;
  43. TITSFReader = class(TObject)
  44. protected
  45. fStream: TStream;
  46. fFreeStreamOnDestroy: Boolean;
  47. fITSFHeader: TITSFHeader;
  48. fHeaderSuffix: TITSFHeaderSuffix;
  49. fDirectoryHeader: TITSPHeader;
  50. fDirectoryHeaderPos: QWord;
  51. fDirectoryHeaderLength: QWord;
  52. fDirectoryEntriesStartPos: QWord;
  53. fCachedEntry: TPMGListChunkEntry; //contains the last entry found by ObjectExists
  54. fDirectoryEntriesCount: LongWord;
  55. procedure ReadHeader; virtual;
  56. procedure ReadHeaderEntries; virtual;
  57. function GetChunkType(Stream: TMemoryStream; ChunkIndex: LongInt): TDirChunkType;
  58. procedure GetSections(out Sections: TStringList);
  59. private
  60. function GetDirectoryChunk(Index: Integer; OutStream: TStream): Integer;
  61. function ReadPMGLchunkEntryFromStream(Stream: TMemoryStream; var PMGLEntry: TPMGListChunkEntry): Boolean;
  62. function ReadPMGIchunkEntryFromStream(Stream: TMemoryStream; var PMGIEntry: TPMGIIndexChunkEntry): Boolean;
  63. procedure LookupPMGLchunk(Stream: TMemoryStream; out PMGLChunk: TPMGListChunk);
  64. procedure LookupPMGIchunk(Stream: TMemoryStream; out PMGIChunk: TPMGIIndexChunk);
  65. function GetBlockFromSection(SectionPrefix: String; StartPos: QWord; BlockLength: QWord): TMemoryStream;
  66. function FindBlocksFromUnCompressedAddr(var ResetTableEntry: TPMGListChunkEntry;
  67. out CompressedSize: QWord; out UnCompressedSize: QWord; out LZXResetTable: TLZXResetTableArr): QWord; // Returns the blocksize
  68. public
  69. constructor Create(AStream: TStream; FreeStreamOnDestroy: Boolean); virtual;
  70. destructor Destroy; override;
  71. public
  72. ChmLastError: LongInt;
  73. function IsValidFile: Boolean;
  74. procedure GetCompleteFileList(ForEach: TFileEntryForEach; AIncludeInternalFiles: Boolean = True); virtual;
  75. function ObjectExists(Name: String): QWord; virtual; // zero if no. otherwise it is the size of the object
  76. // NOTE directories will return zero size even if they exist
  77. function GetObject(Name: String): TMemoryStream; virtual; // YOU must Free the stream
  78. property CachedEntry: TPMGListChunkEntry read fCachedEntry;
  79. end;
  80. { TChmReader }
  81. TChmReader = class(TITSFReader)
  82. protected
  83. fDefaultPage: String;
  84. fIndexFile: String;
  85. fTOCFile: String;
  86. fTitle: String;
  87. fPreferedFont: String;
  88. fContextList: TContextList;
  89. fTOPICSStream,
  90. fURLSTRStream,
  91. fURLTBLStream,
  92. fStringsStream: TMemoryStream;
  93. fLocaleID: DWord;
  94. fWindowsList : TObjectList;
  95. fDefaultWindow: String;
  96. private
  97. FSearchReader: TChmSearchReader;
  98. public
  99. procedure ReadCommonData;
  100. function ReadStringsEntry(APosition: DWord): String;
  101. function ReadStringsEntryFromStream ( strm:TStream ) : String;
  102. { Return LocalUrl string from #URLSTR }
  103. function ReadURLSTR(APosition: DWord): String;
  104. function CheckCommonStreams: Boolean;
  105. procedure ReadWindows(mem:TMemoryStream);
  106. constructor Create(AStream: TStream; FreeStreamOnDestroy: Boolean); override;
  107. destructor Destroy; override;
  108. function GetContextUrl(Context: THelpContext): String;
  109. function LookupTopicByID(ATopicID: Integer; out ATitle: String): String; // returns a url
  110. function GetTOCSitemap(ForceXML:boolean=false): TChmSiteMap;
  111. function GetIndexSitemap(ForceXML:boolean=false): TChmSiteMap;
  112. function HasContextList: Boolean;
  113. property DefaultPage: String read fDefaultPage;
  114. property IndexFile: String read fIndexFile;
  115. property TOCFile: String read fTOCFile;
  116. property Title: String read fTitle write fTitle;
  117. property PreferedFont: String read fPreferedFont;
  118. property LocaleID: dword read fLocaleID;
  119. property SearchReader: TChmSearchReader read FSearchReader write FSearchReader;
  120. property contextlist : tcontextlist read fcontextlist;
  121. property Windows : TObjectlist read fWindowsList;
  122. property DefaultWindow : string read fdefaultwindow;
  123. end;
  124. { TChmFileList }
  125. TChmFileList = class;
  126. TChmFileOpenEvent = procedure(ChmFileList: TChmFileList; Index: Integer) of object;
  127. TChmFileList = class(TStringList)
  128. protected
  129. fLastChm: TChmReader;
  130. fUnNotifiedFiles: TList;
  131. fOnOpenNewFile: TChmFileOpenEvent;
  132. procedure Delete(Index: Integer); override;
  133. function GetChm(AIndex: Integer): TChmReader;
  134. function GetFileName(AIndex: Integer): String;
  135. procedure OpenNewFile(AFileName: String);
  136. function CheckOpenFile(AFileName: String): Boolean;
  137. function MetaObjectExists(var Name: String): QWord;
  138. function MetaGetObject(Name: String): TMemoryStream;
  139. procedure SetOnOpenNewFile(AValue: TChmFileOpenEvent);
  140. public
  141. constructor Create(PrimaryFileName: String);
  142. destructor Destroy; override;
  143. function GetObject(Name: String): TMemoryStream;
  144. function IsAnOpenFile(AFileName: String): Boolean;
  145. function ObjectExists(Name: String; var fChm: TChmReader): QWord;
  146. //properties
  147. property Chm[Index: Integer]: TChmReader read GetChm;
  148. property FileName[Index: Integer]: String read GetFileName;
  149. property OnOpenNewFile: TChmFileOpenEvent read fOnOpenNewFile write SetOnOpenNewFile;
  150. end;
  151. //ErrorCodes
  152. const
  153. ERR_NO_ERR = 0;
  154. ERR_STREAM_NOT_ASSIGNED = 1;
  155. ERR_NOT_SUPPORTED_VERSION = 2;
  156. ERR_NOT_VALID_FILE = 3;
  157. ERR_UNKNOWN_ERROR = 10;
  158. function ChmErrorToStr(Error: Integer): String;
  159. implementation
  160. uses ChmTypes;
  161. function ChmErrorToStr(Error: Integer): String;
  162. begin
  163. Result := '';
  164. case Error of
  165. ERR_STREAM_NOT_ASSIGNED : Result := 'ERR_STREAM_NOT_ASSIGNED';
  166. ERR_NOT_SUPPORTED_VERSION : Result := 'ERR_NOT_SUPPORTED_VERSION';
  167. ERR_NOT_VALID_FILE : Result := 'ERR_NOT_VALID_FILE';
  168. ERR_UNKNOWN_ERROR : Result := 'ERR_UNKNOWN_ERROR';
  169. end;
  170. end;
  171. function ChunkType(Stream: TMemoryStream): TDirChunkType;
  172. var
  173. ChunkID: array[0..3] of char;
  174. begin
  175. Result := ctUnknown;
  176. if Stream.Size< 4 then exit;
  177. Move(Stream.Memory^, ChunkId[0], 4);
  178. if ChunkID = 'PMGL' then Result := ctPMGL
  179. else if ChunkID = 'PMGI' then Result := ctPMGI
  180. else if ChunkID = 'AOLL' then Result := ctAOLL
  181. else if ChunkID = 'AOLI' then Result := ctAOLI;
  182. end;
  183. { TITSFReader }
  184. procedure TITSFReader.ReadHeader;
  185. begin
  186. fStream.Read(fITSFHeader,SizeOf(fITSFHeader));
  187. // Fix endian issues
  188. {$IFDEF ENDIAN_BIG}
  189. fITSFHeader.Version := LEtoN(fITSFHeader.Version);
  190. fITSFHeader.HeaderLength := LEtoN(fITSFHeader.HeaderLength);
  191. //Unknown_1
  192. fITSFHeader.TimeStamp := BEtoN(fITSFHeader.TimeStamp);//bigendian
  193. fITSFHeader.LanguageID := LEtoN(fITSFHeader.LanguageID);
  194. {$ENDIF}
  195. if fITSFHeader.Version < 4 then
  196. fStream.Seek(SizeOf(TGuid)*2, soCurrent);
  197. if not IsValidFile then Exit;
  198. ReadHeaderEntries;
  199. end;
  200. procedure TITSFReader.ReadHeaderEntries;
  201. var
  202. fHeaderEntries: array [0..1] of TITSFHeaderEntry;
  203. begin
  204. // Copy EntryData into memory
  205. fStream.Read(fHeaderEntries[0], SizeOf(fHeaderEntries));
  206. if fITSFHeader.Version = 3 then
  207. fStream.Read(fHeaderSuffix.Offset, SizeOf(QWord));
  208. fHeaderSuffix.Offset := LEtoN(fHeaderSuffix.Offset);
  209. // otherwise this is set in fill directory entries
  210. fStream.Position := LEtoN(fHeaderEntries[1].PosFromZero);
  211. fDirectoryHeaderPos := LEtoN(fHeaderEntries[1].PosFromZero);
  212. fStream.Read(fDirectoryHeader, SizeOf(fDirectoryHeader));
  213. {$IFDEF ENDIAN_BIG}
  214. with fDirectoryHeader do begin
  215. Version := LEtoN(Version);
  216. DirHeaderLength := LEtoN(DirHeaderLength);
  217. //Unknown1
  218. ChunkSize := LEtoN(ChunkSize);
  219. Density := LEtoN(Density);
  220. IndexTreeDepth := LEtoN(IndexTreeDepth);
  221. IndexOfRootChunk := LEtoN(IndexOfRootChunk);
  222. FirstPMGLChunkIndex := LEtoN(FirstPMGLChunkIndex);
  223. LastPMGLChunkIndex := LEtoN(LastPMGLChunkIndex);
  224. //Unknown2
  225. DirectoryChunkCount := LEtoN(DirectoryChunkCount);
  226. LanguageID := LEtoN(LanguageID);
  227. //GUID: TGuid;
  228. LengthAgain := LEtoN(LengthAgain);
  229. end;
  230. {$ENDIF}
  231. {$IFDEF CHM_DEBUG}
  232. WriteLn('PMGI depth = ', fDirectoryHeader.IndexTreeDepth);
  233. WriteLn('PMGI Root = ', fDirectoryHeader.IndexOfRootChunk);
  234. Writeln('DirCount = ', fDirectoryHeader.DirectoryChunkCount);
  235. {$ENDIF}
  236. fDirectoryEntriesStartPos := fStream.Position;
  237. fDirectoryHeaderLength := LEtoN(fHeaderEntries[1].Length);
  238. end;
  239. procedure TChmReader.ReadCommonData;
  240. // A little helper proc to make reading a null terminated string easier
  241. function ReadString(const Stream: TStream; StartPos: DWord; FixURL: Boolean): String;
  242. var
  243. buf: array[0..49] of char;
  244. begin
  245. Result := '';
  246. Stream.Position := StartPos;
  247. repeat
  248. Stream.Read(buf, 50);
  249. Result := Result + buf;
  250. until IndexByte(buf, 50, 0) <> -1;
  251. if FixURL then
  252. Result := StringReplace(Result, '\', '/', [rfReplaceAll]);
  253. end;
  254. procedure ReadFromSystem;
  255. var
  256. //Version: DWord;
  257. EntryType: Word;
  258. EntryLength: Word;
  259. Data: array[0..511] of char;
  260. fSystem: TMemoryStream;
  261. Tmp: String;
  262. begin
  263. fSystem := TMemoryStream(GetObject('/#SYSTEM'));
  264. if fSystem = nil then begin
  265. exit;
  266. end;
  267. fSystem.Position := 0;
  268. if fSystem.Size < SizeOf(DWord) then begin
  269. fSystem.Free;
  270. Exit;
  271. end;
  272. {Version := }LEtoN(fSystem.ReadDWord);
  273. while fSystem.Position < fSystem.Size do begin
  274. EntryType := LEtoN(fSystem.ReadWord);
  275. EntryLength := LEtoN(fSystem.ReadWord);
  276. case EntryType of
  277. 0: // Table of contents
  278. begin
  279. if EntryLength > 511 then EntryLength := 511;
  280. fSystem.Read(Data[0], EntryLength);
  281. Data[EntryLength] := #0;
  282. fTOCFile := '/'+Data;
  283. end;
  284. 1: // Index File
  285. begin
  286. if EntryLength > 511 then EntryLength := 511;
  287. fSystem.Read(Data[0], EntryLength);
  288. Data[EntryLength] := #0;
  289. fIndexFile := '/'+Data;
  290. end;
  291. 2: // DefaultPage
  292. begin
  293. if EntryLength > 511 then EntryLength := 511;
  294. fSystem.Read(Data[0], EntryLength);
  295. Data[EntryLength] := #0;
  296. fDefaultPage := '/'+Data;
  297. end;
  298. 3: // Title of chm
  299. begin
  300. if EntryLength > 511 then EntryLength := 511;
  301. fSystem.Read(Data[0], EntryLength);
  302. Data[EntryLength] := #0;
  303. fTitle := Data;
  304. end;
  305. 4: // Locale ID
  306. begin
  307. fLocaleID := LEtoN(fSystem.ReadDWord);
  308. fSystem.Position := (fSystem.Position + EntryLength) - SizeOf(DWord);
  309. end;
  310. 6: // chm file name. use this to get the index and toc name
  311. begin
  312. if EntryLength > 511 then EntryLength := 511;
  313. fSystem.Read(Data[0], EntryLength);
  314. Data[EntryLength] := #0;
  315. if (fIndexFile = '') then begin
  316. Tmp := '/'+Data+'.hhk';
  317. if (ObjectExists(Tmp) > 0) then begin
  318. fIndexFile := Tmp;
  319. end
  320. end;
  321. if (fTOCFile = '') then begin
  322. Tmp := '/'+Data+'.hhc';
  323. if (ObjectExists(Tmp) > 0) then begin
  324. fTOCFile := Tmp;
  325. end;
  326. end;
  327. end;
  328. 16: // Prefered font
  329. begin
  330. if EntryLength > 511 then EntryLength := 511;
  331. fSystem.Read(Data[0], EntryLength);
  332. Data[EntryLength] := #0;
  333. fPreferedFont := Data;
  334. end;
  335. else
  336. // Skip entries we are not interested in
  337. fSystem.Position := fSystem.Position + EntryLength;
  338. end;
  339. end;
  340. fSystem.Free;
  341. end;
  342. procedure ReadFromWindows;
  343. var
  344. fWindows,
  345. fStrings: TMemoryStream;
  346. EntryCount,
  347. EntrySize: DWord;
  348. EntryStart: QWord;
  349. X: Integer;
  350. OffSet: QWord;
  351. begin
  352. fWindows := TMemoryStream(GetObject('/#WINDOWS'));
  353. if fWindows = nil then begin
  354. exit;
  355. end;
  356. fStrings := TMemoryStream(GetObject('/#STRINGS'));
  357. if fStrings = nil then begin
  358. if fWindows <> nil then fWindows.Free;
  359. Exit;
  360. end;
  361. fWindows.Position := 0;
  362. if (fWindows.Size = 0) or (fStrings.Size = 0) then begin
  363. fWindows.Free;
  364. fStrings.Free;
  365. Exit;
  366. end;
  367. EntryCount := LEtoN(fWindows.ReadDWord);
  368. EntrySize := LEtoN(fWindows.ReadDWord);
  369. OffSet := fWindows.Position;
  370. for X := 0 to EntryCount -1 do begin
  371. EntryStart := OffSet + (X*EntrySize);
  372. if fTitle = '' then begin
  373. fWindows.Position := EntryStart + $14;
  374. fTitle := '/'+ReadString(fStrings, LEtoN(fWindows.ReadDWord), False);
  375. end;
  376. if fTOCFile = '' then begin
  377. fWindows.Position := EntryStart + $60;
  378. fTOCFile := '/'+ReadString(fStrings, LEtoN(fWindows.ReadDWord), True);
  379. end;
  380. if fIndexFile = '' then begin
  381. fWindows.Position := EntryStart + $64;
  382. fIndexFile := '/'+ReadString(fStrings, LEtoN(fWindows.ReadDWord), True);
  383. end;
  384. if fDefaultPage = '' then begin
  385. fWindows.Position := EntryStart + $68;
  386. fDefaultPage := '/'+ReadString(fStrings, LEtoN(fWindows.ReadDWord), True);
  387. end;
  388. end;
  389. ReadWindows(FWindows);
  390. fWindows.Free;
  391. fStrings.Free;
  392. end;
  393. procedure ReadContextIds;
  394. var
  395. fIVB,
  396. fStrings: TStream;
  397. Str: String;
  398. Value: DWord;
  399. OffSet: DWord;
  400. //TotalSize: DWord;
  401. begin
  402. fIVB := GetObject('/#IVB');
  403. if fIVB = nil then Exit;
  404. fStrings := GetObject('/#STRINGS');
  405. if fStrings = nil then begin
  406. fIVB.Free;
  407. Exit;
  408. end;
  409. fIVB.Position := 0;
  410. {TotalSize := }LEtoN(fIVB.ReadDWord);
  411. while fIVB.Position < fIVB.Size do begin
  412. Value := LEtoN(fIVB.ReadDWord);
  413. OffSet := LEtoN(fIVB.ReadDWord);
  414. Str := '/'+ ReadString(fStrings, Offset, True);
  415. fContextList.AddContext(Value, Str);
  416. end;
  417. fIVB.Free;
  418. fStrings.Free;
  419. end;
  420. begin
  421. ReadFromSystem;
  422. ReadFromWindows;
  423. ReadContextIds;
  424. {$IFDEF CHM_DEBUG}
  425. WriteLn('TOC=',fTocfile);
  426. WriteLn('DefaultPage=',fDefaultPage);
  427. {$ENDIF}
  428. end;
  429. function TChmReader.ReadStringsEntry ( APosition: DWord ) : String;
  430. begin
  431. Result := '';
  432. if fStringsStream = nil then
  433. fStringsStream := GetObject('/#STRINGS');
  434. if fStringsStream = nil then
  435. Exit;
  436. if APosition < fStringsStream.Size-1 then
  437. begin
  438. Result := PChar(fStringsStream.Memory+APosition);
  439. end;
  440. end;
  441. function TChmReader.ReadStringsEntryFromStream ( strm:TStream ) : String;
  442. var APosition : DWord;
  443. begin
  444. APosition:=LEtoN(strm.ReadDWord);
  445. result:=ReadStringsEntry(APosition);
  446. end;
  447. function TChmReader.ReadURLSTR ( APosition: DWord ) : String;
  448. begin
  449. result:='';
  450. if not CheckCommonStreams then
  451. Exit;
  452. fURLTBLStream.Position := APosition;
  453. fURLTBLStream.ReadDWord; // unknown
  454. fURLTBLStream.ReadDWord; // TOPIC index #
  455. fURLSTRStream.Position := LEtoN(fURLTBLStream.ReadDWord);
  456. fURLSTRStream.ReadDWord; // URL
  457. fURLSTRStream.ReadDWord; // FrameName
  458. if fURLSTRStream.Position < fURLSTRStream.Size-1 then
  459. Result := PChar(fURLSTRStream.Memory+fURLSTRStream.Position);
  460. end;
  461. function TChmReader.CheckCommonStreams: Boolean;
  462. begin
  463. if fTOPICSStream = nil then
  464. fTOPICSStream := GetObject('/#TOPICS');
  465. if fURLSTRStream = nil then
  466. fURLSTRStream := GetObject('/#URLSTR');
  467. if fURLTBLStream = nil then
  468. fURLTBLStream := GetObject('/#URLTBL');
  469. Result := (fTOPICSStream <> nil)
  470. and (fURLSTRStream <> nil)
  471. and (fURLTBLStream <> nil);
  472. end;
  473. procedure TChmReader.ReadWindows(mem:TMemoryStream);
  474. var
  475. i,cnt,
  476. version : integer;
  477. x : TChmWindow;
  478. begin
  479. if not assigned(fwindowslist) then
  480. fWindowsList.Clear;
  481. mem.Position:=0;
  482. cnt := LEtoN(mem.ReadDWord);
  483. version := LEtoN(mem.ReadDWord);
  484. while (cnt>0) do
  485. begin
  486. x:=TChmWindow.Create;
  487. version := LEtoN(mem.ReadDWord); // 0 size of entry.
  488. mem.readDWord; // 4 unknown (bool Unicodestrings?)
  489. x.window_type :=ReadStringsEntryFromStream(mem); // 8 Arg 0, name of window
  490. x.flags := TValidWindowFields(LEtoN(mem.ReadDWord)); // C valid fields
  491. x.nav_style := LEtoN(mem.ReadDWord); // 10 arg 10 navigation pane style
  492. x.title_bar_text :=ReadStringsEntryFromStream(mem); // 14 Arg 1, title bar text
  493. x.styleflags := LEtoN(mem.ReadDWord); // 18 Arg 14, style flags
  494. x.xtdstyleflags := LEtoN(mem.ReadDWord); // 1C Arg 15, xtd style flags
  495. x.left := LEtoN(mem.ReadDWord); // 20 Arg 13, rect.left
  496. x.right := LEtoN(mem.ReadDWord); // 24 Arg 13, rect.top
  497. x.top := LEtoN(mem.ReadDWord); // 28 Arg 13, rect.right
  498. x.bottom := LEtoN(mem.ReadDWord); // 2C Arg 13, rect.bottom
  499. x.window_show_state:= LEtoN(mem.ReadDWord); // 30 Arg 16, window show state
  500. mem.readdword; // 34 - , HWND hwndhelp OUT: window handle"
  501. mem.readdword; // 38 - , HWND hwndcaller OUT: who called this window"
  502. mem.readdword; // 3C - , HH_INFO_TYPE paINFO_TYPES IN: Pointer to an array of Information Types"
  503. mem.readdword; // 40 - , HWND hwndtoolbar OUT: toolbar window in tri-pane window"
  504. mem.readdword; // 44 - , HWND hwndnavigation OUT: navigation window in tri-pane window"
  505. mem.readdword; // 48 - , HWND hwndhtml OUT: window displaying HTML in tri-pane window"
  506. x.navpanewidth := LEtoN(mem.ReadDWord); // 4C Arg 11, width of nav pane
  507. mem.readdword; // 50 - , rect.left, OUT:Specifies the coordinates of the Topic pane
  508. mem.readdword; // 54 - , rect.top , OUT:Specifies the coordinates of the Topic pane
  509. mem.readdword; // 58 - , rect.right, OUT:Specifies the coordinates of the Topic pane
  510. mem.readdword; // 5C - , rect.bottom, OUT:Specifies the coordinates of the Topic pane
  511. x.toc_file :=ReadStringsEntryFromStream(mem); // 60 Arg 2, toc file
  512. x.index_file :=ReadStringsEntryFromStream(mem); // 64 Arg 3, index file
  513. x.default_file :=ReadStringsEntryFromStream(mem); // 68 Arg 4, default file
  514. x.home_button_file :=ReadStringsEntryFromStream(mem); // 6c Arg 5, home button file.
  515. x.buttons := LEtoN(mem.ReadDWord); // 70 arg 12,
  516. x.navpane_initially_closed := LEtoN(mem.ReadDWord); // 74 arg 17
  517. x.navpane_default := LEtoN(mem.ReadDWord); // 78 arg 18,
  518. x.navpane_location := LEtoN(mem.ReadDWord); // 7C arg 19,
  519. x.wm_notify_id := LEtoN(mem.ReadDWord); // 80 arg 20,
  520. for i:=0 to 4 do
  521. mem.ReadDWord; // 84 - byte[20] unknown - "BYTE tabOrder[HH_MAX_TABS + 1]; // IN/OUT: tab order: Contents, Index, Search, History, Favorites, Reserved 1-5, Custom tabs"
  522. mem.ReadDWord; // 94 - int cHistory; // IN/OUT: number of history items to keep (default is 30)
  523. x.jumpbutton_1_text:=ReadStringsEntryFromStream(mem); // 9C Arg 7, The text of the Jump 1 button.
  524. x.jumpbutton_2_text:=ReadStringsEntryFromStream(mem); // A0 Arg 9, The text of the Jump 2 button.
  525. x.jumpbutton_1_file:=ReadStringsEntryFromStream(mem); // A4 Arg 6, The file shown for Jump 1 button.
  526. x.jumpbutton_2_file:=ReadStringsEntryFromStream(mem); // A8 Arg 8, The file shown for Jump 1 button.
  527. for i:=0 to 3 do
  528. mem.ReadDWord;
  529. dec(version,188); // 1.1 specific onesf
  530. while (version>=4) do
  531. begin
  532. mem.readdword;
  533. dec(version,4);
  534. end;
  535. fWindowslist.Add(x);
  536. dec(cnt);
  537. end;
  538. end;
  539. constructor TChmReader.Create(AStream: TStream; FreeStreamOnDestroy: Boolean);
  540. begin
  541. fContextList := TContextList.Create;
  542. fWindowslist := TObjectlist.Create(True);
  543. fDefaultWindow:='';
  544. inherited Create(AStream, FreeStreamOnDestroy);
  545. if not IsValidFile then exit;
  546. ReadCommonData;
  547. end;
  548. destructor TChmReader.Destroy;
  549. begin
  550. FreeAndNil(fContextList);
  551. FreeAndNil(FWindowslist);
  552. FreeAndNil(FSearchReader);
  553. FreeAndNil(fTOPICSStream);
  554. FreeAndNil(fURLSTRStream);
  555. FreeAndNil(fURLTBLStream);
  556. FreeAndNil(fStringsStream);
  557. inherited Destroy;
  558. end;
  559. function TITSFReader.GetChunkType(Stream: TMemoryStream; ChunkIndex: LongInt): TDirChunkType;
  560. var
  561. Sig: array[0..3] of char;
  562. begin
  563. Result := ctUnknown;
  564. Stream.Position := fDirectoryEntriesStartPos + (fDirectoryHeader.ChunkSize * ChunkIndex);
  565. Stream.Read(Sig, 4);
  566. if Sig = 'PMGL' then Result := ctPMGL
  567. else if Sig = 'PMGI' then Result := ctPMGI
  568. else if Sig = 'AOLL' then Result := ctAOLL
  569. else if Sig = 'AOLI' then Result := ctAOLI;
  570. end;
  571. function TITSFReader.GetDirectoryChunk(Index: Integer; OutStream: TStream): Integer;
  572. begin
  573. Result := Index;
  574. fStream.Position := fDirectoryEntriesStartPos + (fDirectoryHeader.ChunkSize * Index);
  575. OutStream.Position := 0;
  576. OutStream.Size := fDirectoryHeader.ChunkSize;
  577. OutStream.CopyFrom(fStream, fDirectoryHeader.ChunkSize);
  578. OutStream.Position := 0;
  579. end;
  580. procedure TITSFReader.LookupPMGLchunk(Stream: TMemoryStream; out PMGLChunk: TPMGListChunk);
  581. begin
  582. //Stream.Position := fDirectoryEntriesStartPos + (fDirectoryHeader.ChunkSize * ChunkIndex);
  583. Stream.Read(PMGLChunk, SizeOf(PMGLChunk));
  584. {$IFDEF ENDIAN_BIG}
  585. with PMGLChunk do begin
  586. UnusedSpace := LEtoN(UnusedSpace);
  587. //Unknown1
  588. PreviousChunkIndex := LEtoN(PreviousChunkIndex);
  589. NextChunkIndex := LEtoN(NextChunkIndex);
  590. end;
  591. {$ENDIF}
  592. end;
  593. function TITSFReader.ReadPMGLchunkEntryFromStream(Stream: TMemoryStream; var PMGLEntry: TPMGListChunkEntry): Boolean;
  594. var
  595. Buf: array [0..1023] of char;
  596. NameLength: LongInt;
  597. begin
  598. Result := False;
  599. //Stream.Position := fDirectoryEntriesStartPos + (fDirectoryHeader.ChunkSize * ChunkIndex);
  600. NameLength := LongInt(GetCompressedInteger(Stream));
  601. if NameLength > 1022 then NameLength := 1022;
  602. Stream.Read(buf[0], NameLength);
  603. buf[NameLength] := #0;
  604. PMGLEntry.Name := buf;
  605. PMGLEntry.ContentSection := LongWord(GetCompressedInteger(Stream));
  606. PMGLEntry.ContentOffset := GetCompressedInteger(Stream);
  607. PMGLEntry.DecompressedLength := GetCompressedInteger(Stream);
  608. if NameLength = 0 then Exit; // failed GetCompressedInteger sanity check
  609. Result := True;
  610. end;
  611. procedure TITSFReader.LookupPMGIchunk(Stream: TMemoryStream; out PMGIChunk: TPMGIIndexChunk);
  612. begin
  613. //Stream.Position := fDirectoryEntriesStartPos + (fDirectoryHeader.ChunkSize * ChunkIndex);
  614. Stream.Read(PMGIChunk, SizeOf(PMGIChunk));
  615. {$IFDEF ENDIAN_BIG}
  616. with PMGIChunk do begin
  617. UnusedSpace := LEtoN(UnusedSpace);
  618. end;
  619. {$ENDIF}
  620. end;
  621. function TITSFReader.ReadPMGIchunkEntryFromStream(Stream: TMemoryStream;
  622. var PMGIEntry: TPMGIIndexChunkEntry): Boolean;
  623. var
  624. Buf: array [0..1023] of char;
  625. NameLength: LongInt;
  626. begin
  627. Result := False;
  628. //Stream.Position := fDirectoryEntriesStartPos + (fDirectoryHeader.ChunkSize * ChunkIndex);
  629. NameLength := LongInt(GetCompressedInteger(Stream));
  630. if NameLength > 1023 then NameLength := 1023;
  631. Stream.Read(buf, NameLength);
  632. buf[NameLength] := #0;
  633. PMGIEntry.Name := buf;
  634. PMGIEntry.ListingChunk := GetCompressedInteger(Stream);
  635. if NameLength = 0 then Exit; // failed GetCompressedInteger sanity check
  636. Result := True;
  637. end;
  638. constructor TITSFReader.Create(AStream: TStream; FreeStreamOnDestroy: Boolean);
  639. begin
  640. fStream := AStream;
  641. fStream.Position := 0;
  642. fFreeStreamOnDestroy := FreeStreamOnDestroy;
  643. ReadHeader;
  644. if not IsValidFile then Exit;
  645. end;
  646. destructor TITSFReader.Destroy;
  647. begin
  648. if fFreeStreamOnDestroy then FreeAndNil(fStream);
  649. inherited Destroy;
  650. end;
  651. function TITSFReader.IsValidFile: Boolean;
  652. begin
  653. if (fStream = nil) then ChmLastError := ERR_STREAM_NOT_ASSIGNED
  654. else if (fITSFHeader.ITSFsig <> 'ITSF') then ChmLastError := ERR_NOT_VALID_FILE
  655. //else if (fITSFHeader.Version <> 2) and (fITSFHeader.Version <> 3)
  656. else if not (fITSFHeader.Version in [2..4])
  657. then
  658. ChmLastError := ERR_NOT_SUPPORTED_VERSION;
  659. Result := ChmLastError = ERR_NO_ERR;
  660. end;
  661. procedure TITSFReader.GetCompleteFileList(ForEach: TFileEntryForEach; AIncludeInternalFiles: Boolean = True);
  662. var
  663. ChunkStream: TMemoryStream;
  664. I : Integer;
  665. Entry: TPMGListChunkEntry;
  666. PMGLChunk: TPMGListChunk;
  667. CutOffPoint: Integer;
  668. NameLength: Integer;
  669. {$IFDEF CHM_DEBUG_CHUNKS}
  670. PMGIChunk: TPMGIIndexChunk;
  671. PMGIndex: Integer;
  672. {$ENDIF}
  673. begin
  674. if not assigned(ForEach) then Exit;
  675. ChunkStream := TMemoryStream.Create;
  676. {$IFDEF CHM_DEBUG_CHUNKS}
  677. WriteLn('ChunkCount = ',fDirectoryHeader.DirectoryChunkCount);
  678. {$ENDIF}
  679. for I := 0 to fDirectoryHeader.DirectoryChunkCount-1 do begin
  680. GetDirectoryChunk(I, ChunkStream);
  681. case ChunkType(ChunkStream) of
  682. ctPMGL:
  683. begin
  684. LookupPMGLchunk(ChunkStream, PMGLChunk);
  685. {$IFDEF CHM_DEBUG_CHUNKS}
  686. WriteLn('PMGL: ', I, ' Prev PMGL: ', PMGLChunk.PreviousChunkIndex, ' Next PMGL: ', PMGLChunk.NextChunkIndex);
  687. {$ENDIF}
  688. CutOffPoint := ChunkStream.Size - PMGLChunk.UnusedSpace;
  689. while ChunkStream.Position < CutOffPoint do begin
  690. NameLength := GetCompressedInteger(ChunkStream);
  691. if (ChunkStream.Position > CutOffPoint) then Continue; // we have entered the quickref section
  692. SetLength(Entry.Name, NameLength);
  693. ChunkStream.ReadBuffer(Entry.Name[1], NameLength);
  694. if (Entry.Name = '') or (ChunkStream.Position > CutOffPoint) then Break; // we have entered the quickref section
  695. Entry.ContentSection := GetCompressedInteger(ChunkStream);
  696. if ChunkStream.Position > CutOffPoint then Break; // we have entered the quickref section
  697. Entry.ContentOffset := GetCompressedInteger(ChunkStream);
  698. if ChunkStream.Position > CutOffPoint then Break; // we have entered the quickref section
  699. Entry.DecompressedLength := GetCompressedInteger(ChunkStream);
  700. if ChunkStream.Position > CutOffPoint then Break; // we have entered the quickref section
  701. fCachedEntry := Entry; // if the caller trys to get this data we already know where it is :)
  702. if (Length(Entry.Name) = 1)
  703. or (AIncludeInternalFiles
  704. or
  705. ((Length(Entry.Name) > 1) and (not(Entry.Name[2] in ['#','$',':']))))
  706. then
  707. ForEach(Entry.Name, Entry.ContentOffset, Entry.DecompressedLength, Entry.ContentSection);
  708. end;
  709. end;
  710. {$IFDEF CHM_DEBUG_CHUNKS}
  711. ctPMGI:
  712. begin
  713. WriteLn('PMGI: ', I);
  714. LookupPMGIchunk(ChunkStream, PMGIChunk);
  715. CutOffPoint := ChunkStream.Size - PMGIChunk.UnusedSpace - 10;
  716. while ChunkStream.Position < CutOffPoint do begin
  717. NameLength := GetCompressedInteger(ChunkStream);
  718. SetLength(Entry.Name, NameLength);
  719. ChunkStream.ReadBuffer(Entry.Name[1], NameLength);
  720. PMGIndex := GetCompressedInteger(ChunkStream);
  721. WriteLn(Entry.Name, ' ', PMGIndex);
  722. end;
  723. end;
  724. ctUnknown: WriteLn('UNKNOWN CHUNKTYPE!' , I);
  725. {$ENDIF}
  726. end;
  727. end;
  728. end;
  729. function TITSFReader.ObjectExists(Name: String): QWord;
  730. var
  731. ChunkStream: TMemoryStream;
  732. QuickRefCount: Word;
  733. QuickRefIndex: array of Word;
  734. ItemCount: Integer;
  735. procedure ReadQuickRefSection;
  736. var
  737. OldPosn: QWord;
  738. Posn: Integer;
  739. I: Integer;
  740. begin
  741. OldPosn := ChunkStream.Position;
  742. Posn := ChunkStream.Size-SizeOf(Word);
  743. ChunkStream.Position := Posn;
  744. ItemCount := LEToN(ChunkStream.ReadWord);
  745. //WriteLn('Max ITems for next block = ', ItemCount-1);
  746. QuickRefCount := ItemCount div (1 + (1 shl fDirectoryHeader.Density));
  747. //WriteLn('QuickRefCount = ' , QuickRefCount);
  748. SetLength(QuickRefIndex, QuickRefCount+1);
  749. for I := 1 to QuickRefCount do begin
  750. Dec(Posn, SizeOf(Word));
  751. ChunkStream.Position := Posn;
  752. QuickRefIndex[I] := LEToN(ChunkStream.ReadWord);
  753. end;
  754. Inc(QuickRefCount);
  755. ChunkStream.Position := OldPosn;
  756. end;
  757. function ReadString(StreamPosition: Integer = -1): String;
  758. var
  759. NameLength: Integer;
  760. begin
  761. if StreamPosition > -1 then ChunkStream.Position := StreamPosition;
  762. NameLength := GetCompressedInteger(ChunkStream);
  763. SetLength(Result, NameLength);
  764. if NameLength>0 then
  765. ChunkStream.Read(Result[1], NameLength);
  766. end;
  767. var
  768. PMGLChunk: TPMGListChunk;
  769. PMGIChunk: TPMGIIndexChunk;
  770. //ChunkStream: TMemoryStream; declared above
  771. Entry: TPMGListChunkEntry;
  772. NextIndex: Integer;
  773. EntryName: String;
  774. CRes: Integer;
  775. I: Integer;
  776. begin
  777. Result := 0;
  778. //WriteLn('Looking for URL : ', Name);
  779. if Name = '' then Exit;
  780. if fDirectoryHeader.DirectoryChunkCount = 0 then exit;
  781. //WriteLn('Looking for ', Name);
  782. if Name = fCachedEntry.Name then
  783. Exit(fCachedEntry.DecompressedLength); // we've already looked it up
  784. ChunkStream := TMemoryStream.Create;
  785. try
  786. NextIndex := fDirectoryHeader.IndexOfRootChunk;
  787. if NextIndex < 0 then NextIndex := 0; // no PMGI chunks
  788. while NextIndex > -1 do begin
  789. GetDirectoryChunk(NextIndex, ChunkStream);
  790. NextIndex := -1;
  791. ReadQuickRefSection;
  792. {$IFDEF CHM_DEBUG}
  793. WriteLn('In Block ', NextIndex);
  794. {$endif}
  795. case ChunkType(ChunkStream) of
  796. ctUnknown: // something is wrong
  797. begin
  798. {$IFDEF CHM_DEBUG}WriteLn(NextIndex, ' << Unknown BlockType!');{$ENDIF}
  799. Break;
  800. end;
  801. ctPMGI: // we must follow the PMGI tree until we reach a PMGL block
  802. begin
  803. LookupPMGIchunk(ChunkStream, PMGIChunk);
  804. //QuickRefIndex[0] := ChunkStream.Position;
  805. I := 0;
  806. while ChunkStream.Position <= ChunkStream.Size - PMGIChunk.UnusedSpace do begin;
  807. EntryName := ReadString;
  808. if EntryName = '' then break;
  809. if ChunkStream.Position >= ChunkStream.Size - PMGIChunk.UnusedSpace then break;
  810. CRes := ChmCompareText(Name, EntryName);
  811. if CRes = 0 then begin
  812. // no more need of this block. onto the next!
  813. NextIndex := GetCompressedInteger(ChunkStream);
  814. Break;
  815. end;
  816. if CRes < 0 then begin
  817. if I = 0 then Break; // File doesn't exist
  818. // file is in previous entry
  819. Break;
  820. end;
  821. NextIndex := GetCompressedInteger(ChunkStream);
  822. Inc(I);
  823. end;
  824. end;
  825. ctPMGL:
  826. begin
  827. LookupPMGLchunk(ChunkStream, PMGLChunk);
  828. QuickRefIndex[0] := ChunkStream.Position;
  829. I := 0;
  830. while ChunkStream.Position <= ChunkStream.Size - PMGLChunk.UnusedSpace do begin
  831. // we consume the entry by reading it
  832. Entry.Name := ReadString;
  833. if Entry.Name = '' then break;
  834. if ChunkStream.Position >= ChunkStream.Size - PMGLChunk.UnusedSpace then break;
  835. Entry.ContentSection := GetCompressedInteger(ChunkStream);
  836. Entry.ContentOffset := GetCompressedInteger(ChunkStream);
  837. Entry.DecompressedLength := GetCompressedInteger(ChunkStream);
  838. CRes := ChmCompareText(Name, Entry.Name);
  839. if CRes = 0 then begin
  840. fCachedEntry := Entry;
  841. Result := Entry.DecompressedLength;
  842. Break;
  843. end;
  844. Inc(I);
  845. end;
  846. end; // case
  847. end;
  848. end;
  849. finally
  850. ChunkStream.Free;
  851. end;
  852. end;
  853. function TITSFReader.GetObject(Name: String): TMemoryStream;
  854. var
  855. SectionNames: TStringList;
  856. Entry: TPMGListChunkEntry;
  857. SectionName: String;
  858. begin
  859. Result := nil;
  860. if ObjectExists(Name) = 0 then begin
  861. //WriteLn('Object ', name,' Doesn''t exist or is zero sized.');
  862. Exit;
  863. end;
  864. Entry := fCachedEntry;
  865. if Entry.ContentSection = 0 then begin
  866. Result := TMemoryStream.Create;
  867. fStream.Position := fHeaderSuffix.Offset+ Entry.ContentOffset;
  868. Result.CopyFrom(fStream, fCachedEntry.DecompressedLength);
  869. end
  870. else begin // we have to get it from ::DataSpace/Storage/[MSCompressed,Uncompressed]/ControlData
  871. GetSections(SectionNames);
  872. FmtStr(SectionName, '::DataSpace/Storage/%s/',[SectionNames[Entry.ContentSection]]);
  873. Result := GetBlockFromSection(SectionName, Entry.ContentOffset, Entry.DecompressedLength);
  874. SectionNames.Free;
  875. end;
  876. if Result <> nil then Result.Position := 0;
  877. end;
  878. function TChmReader.GetContextUrl(Context: THelpContext): String;
  879. begin
  880. // will get '' if context not found
  881. Result := fContextList.GetURL(Context);
  882. end;
  883. function TChmReader.LookupTopicByID ( ATopicID: Integer; out ATitle: String) : String;
  884. var
  885. TopicURLTBLOffset: DWord;
  886. TopicTitleOffset: DWord;
  887. begin
  888. Result := '';
  889. ATitle := '';
  890. //WriteLn('Getting topic# ',ATopicID);
  891. if not CheckCommonStreams then
  892. Exit;
  893. fTOPICSStream.Position := ATopicID * 16;
  894. if fTOPICSStream.Position = ATopicID * 16 then
  895. begin
  896. fTOPICSStream.ReadDWord;
  897. TopicTitleOffset := LEtoN(fTOPICSStream.ReadDWord);
  898. TopicURLTBLOffset := LEtoN(fTOPICSStream.ReadDWord);
  899. {$ifdef binindex}
  900. {$ifndef nonumber}
  901. writeln('titleid:',TopicTitleOffset);
  902. writeln('urlid :',TopicURLTBLOffset);
  903. {$endif}
  904. {$endif}
  905. if TopicTitleOffset <> $FFFFFFFF then
  906. ATitle := ReadStringsEntry(TopicTitleOffset);
  907. //WriteLn('Got a title: ', ATitle);
  908. Result := ReadURLSTR(TopicURLTBLOffset);
  909. end;
  910. end;
  911. const DefBlockSize = 2048;
  912. function LoadBtreeHeader(m:TMemoryStream;var btreehdr:TBtreeHeader):boolean;
  913. begin
  914. if m.size<sizeof(TBtreeHeader) Then
  915. Exit(False);
  916. result:=true;
  917. m.read(btreeHdr,sizeof(TBtreeHeader));
  918. {$IFDEF ENDIAN_BIG}
  919. btreehdr.flags :=LEToN(btreehdr.flags);
  920. btreehdr.blocksize :=LEToN(btreehdr.blocksize);
  921. btreehdr.lastlstblock :=LEToN(btreehdr.lastlstblock);
  922. btreehdr.indexrootblock:=LEToN(btreehdr.indexrootblock);
  923. btreehdr.nrblock :=LEToN(btreehdr.nrblock);
  924. btreehdr.treedepth :=LEToN(btreehdr.treedepth);
  925. btreehdr.nrkeywords :=LEToN(btreehdr.nrkeywords);
  926. btreehdr.codepage :=LEToN(btreehdr.codepage);
  927. btreehdr.lcid :=LEToN(btreehdr.lcid);
  928. btreehdr.ischm :=LEToN(btreehdr.ischm);
  929. {$endif}
  930. end;
  931. function readwcharstring(var head:pbyte;tail:pbyte;var readv : ansistring):boolean;
  932. var pw : PWord;
  933. oldhead : PByte;
  934. ws : WideString;
  935. n : Integer;
  936. begin
  937. oldhead:=head;
  938. pw:=pword(head);
  939. while (pw<pword(tail)) and (pw^<>word(0)) do
  940. inc(pw);
  941. inc(pw); // skip #0#0.
  942. head:=pbyte(pw);
  943. result:=head<tail;
  944. n:=head-oldhead;
  945. pw:=pword(@oldhead[n]);
  946. if (n>1) and (pw[-1]=0) then
  947. dec(n,2); // remove trailing #0
  948. setlength(ws,n div sizeof(widechar));
  949. move(oldhead^,ws[1],n);
  950. for n:=1 to length(ws) do
  951. word(ws[n]):=LEToN(word(ws[n]));
  952. readv:=ws; // force conversion for now, and hope it doesn't require cwstring
  953. end;
  954. Type TLookupRec = record
  955. item : TChmSiteMapItems;
  956. depth : integer;
  957. end;
  958. TLookupDict = TDictionary<string,TLookupRec>;
  959. function TChmReader.GetIndexSitemap(ForceXML:boolean=false): TChmSiteMap;
  960. var Index : TMemoryStream;
  961. function AbortAndTryTextual:tchmsitemap;
  962. begin
  963. if Assigned(Index) Then Index.Free;
  964. // Second Try text Index
  965. Index := GetObject(IndexFile);
  966. if Index <> nil then
  967. begin
  968. Result := TChmSiteMap.Create(stIndex);
  969. Result.LoadFromStream(Index);
  970. Index.Free;
  971. end
  972. else
  973. result:=nil;
  974. end;
  975. var
  976. parentitem:TChmSiteMapItems;
  977. itemstack :TObjectList;
  978. lookup : TLookupDict;
  979. curitemdepth : integer;
  980. sitemap : TChmSiteMap;
  981. function getitem(anentrydepth:integer):Tchmsitemapitems;
  982. begin
  983. if anentrydepth<itemstack.count then
  984. result:=tchmsitemapitems(itemstack[anentrydepth])
  985. else
  986. begin
  987. {$ifdef binindex}
  988. writeln('pop from emptystack at ',anentrydepth,' ',itemstack.count);
  989. {$endif}
  990. result:=tchmsitemapitems(itemstack[itemstack.Count-1]);
  991. end;
  992. end;
  993. procedure pushitem(anentrydepth:integer;anitem:tchmsitemapitem);
  994. begin
  995. if anentrydepth<itemstack.count then
  996. itemstack[anentrydepth]:=anitem.children
  997. else
  998. if anentrydepth=itemstack.count then
  999. itemstack.add(anitem.Children)
  1000. else
  1001. begin
  1002. {$ifdef binindex}
  1003. writeln('push more than 1 larger ' ,anentrydepth,' ',itemstack.count);
  1004. {$endif}
  1005. itemstack.add(anitem.Children)
  1006. end;
  1007. end;
  1008. procedure parselistingblock(p:pbyte);
  1009. var
  1010. Item : TChmSiteMapItem;
  1011. hdr:PBTreeBlockHeader;
  1012. head,tail : pbyte;
  1013. isseealso,
  1014. entrydepth,
  1015. nrpairs : Integer;
  1016. i : integer;
  1017. PE : PBtreeBlockEntry;
  1018. title : string;
  1019. CharIndex,
  1020. ind:integer;
  1021. seealsostr,
  1022. s,
  1023. Name : AnsiString;
  1024. path,
  1025. shortname : AnsiString;
  1026. anitem:TChmSiteMapItems;
  1027. litem : TChmSiteMapItem;
  1028. lookupitem : TLookupRec;
  1029. function readvalue:string;
  1030. begin
  1031. result:='';
  1032. title:='';
  1033. if head<tail Then
  1034. begin
  1035. ind:=LEToN(plongint(head)^);
  1036. result:=lookuptopicbyid(ind,title);
  1037. {$ifdef binindex}
  1038. writeln(i:3,' topic: ' {$ifndef nonumber},' (',ind,')' {$endif});
  1039. writeln(' title: ',title);
  1040. writeln(' result: ',result);
  1041. {$endif}
  1042. inc(head,4);
  1043. end;
  1044. end;
  1045. procedure dumpstack;
  1046. var fp : TChmSiteMapItems;
  1047. ix : Integer;
  1048. begin
  1049. for ix:=0 to itemstack.Count-1 do
  1050. begin
  1051. fp :=TChmSiteMapItems(itemstack[ix]);
  1052. writeln(ix:3,' ',fp.parentname);
  1053. end;
  1054. end;
  1055. begin
  1056. //setlength (curitem,10);
  1057. hdr:=PBTreeBlockHeader(p);
  1058. hdr^.Length :=LEToN(hdr^.Length);
  1059. hdr^.NumberOfEntries :=LEToN(hdr^.NumberOfEntries);
  1060. hdr^.IndexOfPrevBlock:=LEToN(hdr^.IndexOfPrevBlock);
  1061. hdr^.IndexOfNextBlock:=LEToN(hdr^.IndexOfNextBlock);
  1062. {$ifdef binindex}
  1063. writeln('hdr:',hdr^.length);
  1064. {$endif}
  1065. tail:=p+(2048-hdr^.length);
  1066. head:=p+sizeof(TBtreeBlockHeader);
  1067. {$ifdef binindex}
  1068. {$ifndef nonumber}
  1069. writeln('previndex : ',hdr^.IndexOfPrevBlock);
  1070. writeln('nextindex : ',hdr^.IndexOfNextBlock);
  1071. {$endif}
  1072. {$endif}
  1073. while head<tail do
  1074. begin
  1075. //writeln(tail-head);
  1076. if not ReadWCharString(Head,Tail,Name) Then
  1077. Break;
  1078. {$ifdef binindex}
  1079. Writeln('name : ',name);
  1080. {$endif}
  1081. if (head+sizeof(TBtreeBlockEntry))>=tail then
  1082. break;
  1083. PE :=PBtreeBlockEntry(head);
  1084. NrPairs :=LEToN(PE^.nrpairs);
  1085. IsSeealso:=LEToN(PE^.isseealso);
  1086. EntryDepth:=LEToN(PE^.entrydepth);
  1087. CharIndex:=LEToN(PE^.CharIndex);
  1088. Path:='';
  1089. if charindex<>0 then
  1090. begin
  1091. Path:=Trim(Copy(Name,1,charindex-2));
  1092. Shortname:=trim(copy(Name,charindex,Length(Name)-Charindex+1));
  1093. end
  1094. else
  1095. shortname:=name;
  1096. {$ifdef binindex}
  1097. writeln('depth:', curitemdepth, ' ' ,entrydepth);
  1098. {$endif}
  1099. if curitemdepth=entrydepth then // same level, so of same parent
  1100. begin
  1101. item:=parentitem.newitem;
  1102. pushitem(entrydepth+1,item);
  1103. end
  1104. else
  1105. if curitemdepth=entrydepth-1 then // new child, one lower.
  1106. begin
  1107. parentitem:=getitem(entrydepth);
  1108. item:=parentitem.newitem;
  1109. pushitem(entrydepth+1,item);
  1110. end
  1111. else
  1112. if entrydepth<curitemdepth then
  1113. begin
  1114. parentitem:=getitem(entrydepth);
  1115. {$ifdef binindex}
  1116. writeln('bingo!', parentitem.parentname);
  1117. dumpstack;
  1118. {$endif}
  1119. item:=parentitem.newitem;
  1120. pushitem(entrydepth+1,item);
  1121. end;
  1122. curitemdepth:=entrydepth;
  1123. {$ifdef binindex}
  1124. writeln('lookup:', Name, ' = ', path,' = ',shortname);
  1125. {$endif}
  1126. (* if lookup.trygetvalue(path,lookupitem) then
  1127. begin
  1128. // if lookupitem.item<>parentitem then
  1129. // writeln('mismatch: ',lookupitem.item.item[0].name,' ',name);
  1130. { if curitemdepth<entrydepth then
  1131. begin
  1132. writeln('lookup ok!',curitemdepth,' ' ,entrydepth);
  1133. curitemdepth:=entrydepth;
  1134. end
  1135. else
  1136. begin
  1137. writeln('lookup odd!',curitemdepth,' ' ,entrydepth);
  1138. end;
  1139. curitemdepth:=lookupitem.depth+1;
  1140. parentitem:=lookupitem.item;}
  1141. end
  1142. else
  1143. begin
  1144. // parentitem:=sitemap.Items;
  1145. if not curitemdepth=entrydepth then
  1146. writeln('no lookup odd!',curitemdepth,' ' ,entrydepth);
  1147. end; *)
  1148. { item:=parentitem.newitem;}
  1149. lookupitem.item:=item.children;
  1150. lookupitem.depth:=entrydepth;
  1151. lookup.addorsetvalue(name,lookupitem);
  1152. item.AddName(Shortname);
  1153. {$ifdef binindex}
  1154. Writeln('seealso : ',IsSeeAlso);
  1155. Writeln('entrydepth: ',EntryDepth);
  1156. Writeln('charindex : ',charindex );
  1157. Writeln('Nrpairs : ',NrPairs);
  1158. Writeln('CharIndex : ',charindex);
  1159. {$endif}
  1160. inc(head,sizeof(TBtreeBlockEntry));
  1161. if isseealso>0 then
  1162. begin
  1163. if not ReadWCharString(Head,Tail,SeeAlsoStr) Then
  1164. Break;
  1165. // have to figure out first what to do with it.
  1166. // is See Also really mutually exclusive with pairs?
  1167. // or is the number of pairs equal to the number of seealso
  1168. // strings?
  1169. {$ifdef binindex}
  1170. writeln('seealso: ',seealsostr);
  1171. {$endif}
  1172. item.AddSeeAlso(seealsostr);
  1173. end
  1174. else
  1175. begin
  1176. if NrPairs>0 Then
  1177. begin
  1178. {$ifdef binindex}
  1179. writeln('Pairs : ');
  1180. {$endif}
  1181. for i:=0 to nrpairs-1 do
  1182. begin
  1183. s:=readvalue;
  1184. // if not ((i=0) and (title=shortname)) then
  1185. item.addname(title);
  1186. item.addlocal(s);
  1187. end;
  1188. end;
  1189. end;
  1190. inc(head,4); // always 1
  1191. {$ifdef binindex}
  1192. if head<tail then
  1193. writeln('Zero based index (13 higher than last) :',plongint(head)^);
  1194. {$endif}
  1195. inc(head,4); // zero based index (13 higher than last
  1196. end;
  1197. end;
  1198. var TryTextual : boolean;
  1199. BHdr : TBTreeHeader;
  1200. block : Array[0..2047] of Byte;
  1201. i : Integer;
  1202. begin
  1203. Result := nil; SiteMap:=Nil;
  1204. // First Try Binary
  1205. Index := GetObject('/$WWKeywordLinks/BTree');
  1206. if (Index = nil) or ForceXML then
  1207. begin
  1208. Result:=AbortAndTryTextual; // frees index if needed
  1209. Exit;
  1210. end;
  1211. if not CheckCommonStreams then
  1212. begin
  1213. index.free;
  1214. Result:=AbortAndTryTextual; // frees index if needed
  1215. Exit;
  1216. end;
  1217. lookup:=TDictionary<string,TLookupRec>.create;
  1218. SiteMap:=TChmSitemap.Create(StIndex);
  1219. itemstack :=TObjectList.create(false);
  1220. //Item :=Nil; // cached last created item, in case we need to make
  1221. // a child.
  1222. parentitem:=sitemap.Items;
  1223. itemstack.add(parentitem); // level 0
  1224. curitemdepth:=0;
  1225. TryTextual:=True;
  1226. BHdr.LastLstBlock:=0;
  1227. if LoadBtreeHeader(index,BHdr) and (BHdr.LastLstBlock>=0) Then
  1228. begin
  1229. if BHdr.BlockSize=defblocksize then
  1230. begin
  1231. for i:=0 to BHdr.lastlstblock do
  1232. begin
  1233. if (index.size-index.position)>=defblocksize then // skips last incomplete block?
  1234. begin
  1235. Index.read(block,defblocksize);
  1236. parselistingblock(@block)
  1237. end;
  1238. end;
  1239. trytextual:=false;
  1240. result:=sitemap;
  1241. end;
  1242. end;
  1243. if trytextual then
  1244. begin
  1245. sitemap.free;
  1246. Result:=AbortAndTryTextual; // frees index if needed
  1247. end
  1248. else Index.Free;
  1249. itemstack.free;
  1250. lookup.free;
  1251. end;
  1252. function TChmReader.GetTOCSitemap(ForceXML:boolean=false): TChmSiteMap;
  1253. function AddTOCItem(TOC: TStream; AItemOffset: DWord; SiteMapITems: TChmSiteMapItems): DWord;
  1254. var
  1255. Props: DWord;
  1256. Item: TChmSiteMapItem;
  1257. NextEntry: DWord;
  1258. TopicsIndex: DWord;
  1259. Title, Local : String;
  1260. begin
  1261. Toc.Position:= AItemOffset + 4;
  1262. Item := SiteMapITems.NewItem;
  1263. Props := LEtoN(TOC.ReadDWord);
  1264. if (Props and TOC_ENTRY_HAS_LOCAL) = 0 then
  1265. Item.AddName(ReadStringsEntry(LEtoN(TOC.ReadDWord)))
  1266. else
  1267. begin
  1268. TopicsIndex := LEtoN(TOC.ReadDWord);
  1269. Local:=LookupTopicByID(TopicsIndex, Title);
  1270. Item.AddName(Title);
  1271. Item.AddLocal(Local);
  1272. end;
  1273. TOC.ReadDWord;
  1274. Result := LEtoN(TOC.ReadDWord);
  1275. if Props and TOC_ENTRY_HAS_CHILDREN > 0 then
  1276. begin
  1277. NextEntry := LEtoN(TOC.ReadDWord);
  1278. repeat
  1279. NextEntry := AddTOCItem(TOC, NextEntry, Item.Children);
  1280. until NextEntry = 0;
  1281. end;
  1282. end;
  1283. var
  1284. TOC: TStream;
  1285. TOPICSOffset: DWord;
  1286. EntriesOffset: DWord;
  1287. EntryCount: DWord;
  1288. EntryInfoOffset: DWord;
  1289. NextItem: DWord;
  1290. begin
  1291. Result := nil;
  1292. // First Try Binary
  1293. TOC := GetObject('/#TOCIDX');
  1294. if (TOC = nil) or ForceXML then
  1295. begin
  1296. if Assigned(TOC) Then Toc.Free;
  1297. // Second Try text toc
  1298. TOC := GetObject(TOCFile);
  1299. if TOC <> nil then
  1300. begin
  1301. Result := TChmSiteMap.Create(stTOC);
  1302. Result.LoadFromStream(TOC);
  1303. Toc.Free;
  1304. end;
  1305. Exit;
  1306. end;
  1307. // TOPICS URLSTR URLTBL must all exist to read binary toc
  1308. // if they don't then try text file
  1309. if not CheckCommonStreams then
  1310. begin
  1311. TOC.Free;
  1312. TOC := GetObject(TOCFile);
  1313. if TOC <> nil then
  1314. begin
  1315. Result := TChmSiteMap.Create(stTOC);
  1316. Result.LoadFromStream(TOC);
  1317. Toc.Free;
  1318. end;
  1319. Exit;
  1320. end;
  1321. // Binary Toc Exists
  1322. Result := TChmSiteMap.Create(stTOC);
  1323. EntryInfoOffset := NtoLE(TOC.ReadDWord);
  1324. EntriesOffset := NtoLE(TOC.ReadDWord);
  1325. EntryCount := NtoLE(TOC.ReadDWord);
  1326. TOPICSOffset := NtoLE(TOC.ReadDWord);
  1327. if EntryCount = 0 then
  1328. begin
  1329. Toc.Free;
  1330. Exit;
  1331. end;
  1332. NextItem := EntryInfoOffset;
  1333. repeat
  1334. NextItem := AddTOCItem(Toc, NextItem, Result.Items);
  1335. until NextItem = 0;
  1336. TOC.Free;
  1337. end;
  1338. function TChmReader.HasContextList: Boolean;
  1339. begin
  1340. Result := fContextList.Count > 0;
  1341. end;
  1342. procedure TITSFReader.GetSections(out Sections: TStringList);
  1343. var
  1344. Stream: TStream;
  1345. EntryCount: Word;
  1346. X: Integer;
  1347. {$IFDEF ENDIAN_BIG}
  1348. I: Integer;
  1349. {$ENDIF}
  1350. WString: array [0..31] of WideChar;
  1351. StrLength: Word;
  1352. begin
  1353. Sections := TStringList.Create;
  1354. //WriteLn('::DataSpace/NameList Size = ', ObjectExists('::DataSpace/NameList'));
  1355. Stream := GetObject('::DataSpace/NameList');
  1356. if Stream = nil then begin
  1357. //WriteLn('Failed to get ::DataSpace/NameList!');
  1358. exit;
  1359. end;
  1360. Stream.Position := 2;
  1361. EntryCount := LEtoN(Stream.ReadWord);
  1362. for X := 0 to EntryCount -1 do begin
  1363. StrLength := LEtoN(Stream.ReadWord);
  1364. if StrLength > 31 then StrLength := 31;
  1365. Stream.Read(WString, SizeOf(WideChar)*(StrLength+1)); // the strings are stored null terminated
  1366. {$IFDEF ENDIAN_BIG}
  1367. for I := 0 to StrLength-1 do
  1368. WString[I] := WideChar(LEtoN(Ord(WString[I])));
  1369. {$ENDIF}
  1370. Sections.Add(WString);
  1371. end;
  1372. Stream.Free;
  1373. end;
  1374. function TITSFReader.GetBlockFromSection(SectionPrefix: String; StartPos: QWord;
  1375. BlockLength: QWord): TMemoryStream;
  1376. var
  1377. Compressed: Boolean;
  1378. Sig: Array [0..3] of char;
  1379. CompressionVersion: LongWord;
  1380. CompressedSize: QWord;
  1381. UnCompressedSize: QWord;
  1382. //LZXResetInterval: LongWord;
  1383. //LZXWindowSize: LongWord;
  1384. //LZXCacheSize: LongWord;
  1385. ResetTableEntry: TPMGListChunkEntry;
  1386. ResetTable: TLZXResetTableArr;
  1387. WriteCount: QWord;
  1388. BlockWriteLength: QWord;
  1389. WriteStart: LongWord;
  1390. ReadCount:LongInt;
  1391. LZXState: PLZXState;
  1392. InBuf: array of Byte;
  1393. OutBuf: PByte;
  1394. BlockSize: QWord;
  1395. X: Integer;
  1396. FirstBlock, LastBlock: LongInt;
  1397. ResultCode: LongInt;
  1398. procedure ReadBlock;
  1399. begin
  1400. if ReadCount > Length(InBuf) then
  1401. SetLength(InBuf, ReadCount);
  1402. fStream.Read(InBuf[0], ReadCount);
  1403. end;
  1404. begin
  1405. // okay now the fun stuff ;)
  1406. Result := nil;
  1407. Compressed := ObjectExists(SectionPrefix+'Transform/{7FC28940-9D31-11D0-9B27-00A0C91E9C7C}/InstanceData/ResetTable')>0;
  1408. // the easy method
  1409. if Not(Compressed) then begin
  1410. if ObjectExists(SectionPrefix+'Content') > 0 then begin
  1411. Result := TMemoryStream.Create;
  1412. fStream.Position := fHeaderSuffix.Offset + fCachedEntry.ContentOffset + StartPos;
  1413. Result.CopyFrom(fStream, BlockLength);
  1414. end;
  1415. Exit;
  1416. end
  1417. else
  1418. ResetTableEntry := fCachedEntry;
  1419. // First make sure that it is a compression we can read
  1420. if ObjectExists(SectionPrefix+'ControlData') > 0 then begin
  1421. fStream.Position := fHeaderSuffix.Offset + fCachedEntry.ContentOffset + 4;
  1422. fStream.Read(Sig, 4);
  1423. if Sig <> 'LZXC' then Exit;
  1424. CompressionVersion := LEtoN(fStream.ReadDWord);
  1425. if CompressionVersion > 2 then exit;
  1426. {LZXResetInterval := }LEtoN(fStream.ReadDWord);
  1427. {LZXWindowSize := }LEtoN(fStream.ReadDWord);
  1428. {LZXCacheSize := }LEtoN(fStream.ReadDWord);
  1429. BlockSize := FindBlocksFromUnCompressedAddr(ResetTableEntry, CompressedSize, UnCompressedSize, ResetTable);
  1430. if UncompressedSize > 0 then ; // to avoid a compiler note
  1431. if StartPos > 0 then
  1432. FirstBlock := StartPos div BlockSize
  1433. else
  1434. FirstBlock := 0;
  1435. LastBlock := (StartPos+BlockLength) div BlockSize;
  1436. if ObjectExists(SectionPrefix+'Content') = 0 then exit;
  1437. //WriteLn('Compressed Data start''s at: ', fHeaderSuffix.Offset + fCachedEntry.ContentOffset,' Size is: ', fCachedEntry.DecompressedLength);
  1438. Result := TMemoryStream.Create;
  1439. Result.Size := BlockLength;
  1440. SetLength(InBuf,BlockSize);
  1441. OutBuf := GetMem(BlockSize);
  1442. // First Init a PLZXState
  1443. LZXState := LZXinit(16);
  1444. if LZXState = nil then begin
  1445. Exit;
  1446. end;
  1447. // if FirstBlock is odd (1,3,5,7 etc) we have to read the even block before it first.
  1448. if FirstBlock and 1 = 1 then begin
  1449. fStream.Position := fHeaderSuffix.Offset + fCachedEntry.ContentOffset + (ResetTable[FirstBLock-1]);
  1450. ReadCount := ResetTable[FirstBlock] - ResetTable[FirstBlock-1];
  1451. BlockWriteLength:=BlockSize;
  1452. ReadBlock;
  1453. ResultCode := LZXdecompress(LZXState, @InBuf[0], OutBuf, ReadCount, LongInt(BlockWriteLength));
  1454. end;
  1455. // now start the actual decompression loop
  1456. for X := FirstBlock to LastBlock do begin
  1457. fStream.Position := fHeaderSuffix.Offset + fCachedEntry.ContentOffset + (ResetTable[X]);
  1458. if X = FirstBLock then
  1459. WriteStart := StartPos - (X*BlockSize)
  1460. else
  1461. WriteStart := 0;
  1462. if X = High(ResetTable) then
  1463. ReadCount := CompressedSize - ResetTable[X]
  1464. else
  1465. ReadCount := ResetTable[X+1] - ResetTable[X];
  1466. BlockWriteLength := BlockSize;
  1467. if FirstBlock = LastBlock then begin
  1468. WriteCount := BlockLength;
  1469. end
  1470. else if X = LastBlock then
  1471. WriteCount := (StartPos+BlockLength) - (X*BlockSize)
  1472. else WriteCount := BlockSize - WriteStart;
  1473. ReadBlock;
  1474. ResultCode := LZXdecompress(LZXState, @InBuf[0], OutBuf, ReadCount, LongInt(BlockWriteLength));
  1475. //now write the decompressed data to the stream
  1476. if ResultCode = DECR_OK then begin
  1477. Result.Write(OutBuf[WriteStart], QWord(WriteCount));
  1478. end
  1479. else begin
  1480. {$IFDEF CHM_DEBUG} // windows gui program will cause an exception with writeln's
  1481. WriteLn('Decompress FAILED with error code: ', ResultCode);
  1482. {$ENDIF}
  1483. Result.Free;
  1484. Result := Nil;
  1485. FreeMem(OutBuf);
  1486. SetLength(ResetTable,0);
  1487. LZXteardown(LZXState);
  1488. Exit;
  1489. end;
  1490. // if the next block is an even numbered block we have to reset the decompressor state
  1491. if (X < LastBlock) and (X and 1 = 1) then LZXreset(LZXState);
  1492. end;
  1493. FreeMem(OutBuf);
  1494. SetLength(ResetTable,0);
  1495. LZXteardown(LZXState);
  1496. end;
  1497. end;
  1498. function TITSFReader.FindBlocksFromUnCompressedAddr(var ResetTableEntry: TPMGListChunkEntry;
  1499. out CompressedSize: QWord; out UnCompressedSize: QWord; out LZXResetTable: TLZXResetTableArr): QWord;
  1500. var
  1501. BlockCount: LongWord;
  1502. {$IFDEF ENDIAN_BIG}
  1503. I: Integer;
  1504. {$ENDIF}
  1505. begin
  1506. Result := 0;
  1507. fStream.Position := fHeaderSuffix.Offset + ResetTableEntry.ContentOffset;
  1508. fStream.ReadDWord;
  1509. BlockCount := LEtoN(fStream.ReadDWord);
  1510. fStream.ReadDWord;
  1511. fStream.ReadDWord; // TableHeaderSize;
  1512. fStream.Read(UnCompressedSize, SizeOf(QWord));
  1513. UnCompressedSize := LEtoN(UnCompressedSize);
  1514. fStream.Read(CompressedSize, SizeOf(QWord));
  1515. CompressedSize := LEtoN(CompressedSize);
  1516. fStream.Read(Result, SizeOf(QWord)); // block size
  1517. Result := LEtoN(Result);
  1518. // now we are located at the first block index
  1519. SetLength(LZXResetTable, BlockCount);
  1520. fStream.Read(LZXResetTable[0], SizeOf(QWord)*BlockCount);
  1521. {$IFDEF ENDIAN_BIG}
  1522. for I := 0 to High(LZXResetTable) do
  1523. LZXResetTable[I] := LEtoN(LZXResetTable[I]);
  1524. {$ENDIF}
  1525. end;
  1526. { TContextList }
  1527. procedure TContextList.AddContext(Context: THelpContext; Url: String);
  1528. var
  1529. ContextItem: PContextItem;
  1530. begin
  1531. New(ContextItem);
  1532. Add(ContextItem);
  1533. ContextItem^.Context := Context;
  1534. ContextItem^.Url := Url;
  1535. end;
  1536. function TContextList.GetURL(Context: THelpContext): String;
  1537. var
  1538. X: Integer;
  1539. begin
  1540. Result := '';
  1541. for X := 0 to Count-1 do begin
  1542. if PContextItem(Get(X))^.Context = Context then begin
  1543. Result := PContextItem(Get(X))^.Url;
  1544. Exit;
  1545. end;
  1546. end;
  1547. end;
  1548. procedure TContextList.Clear;
  1549. var
  1550. X: Integer;
  1551. begin
  1552. for X := Count-1 downto 0 do begin
  1553. Dispose(PContextItem(Get(X)));
  1554. Delete(X);
  1555. end;
  1556. end;
  1557. { TChmFileList }
  1558. procedure TChmFileList.Delete(Index: Integer);
  1559. begin
  1560. Chm[Index].Free;
  1561. inherited Delete(Index);
  1562. end;
  1563. function TChmFileList.GetChm(AIndex: Integer): TChmReader;
  1564. begin
  1565. if AIndex = -1 then
  1566. Result := fLastChm
  1567. else
  1568. Result := TChmReader(Objects[AIndex]);
  1569. end;
  1570. function TChmFileList.GetFileName(AIndex: Integer): String;
  1571. begin
  1572. if AIndex = -1 then
  1573. AIndex := IndexOfObject(fLastChm);
  1574. Result := Strings[AIndex];
  1575. end;
  1576. procedure TChmFileList.OpenNewFile(AFileName: String);
  1577. var
  1578. AStream: TFileStream;
  1579. AChm: TChmReader;
  1580. AIndex: Integer;
  1581. begin
  1582. if not FileExists(AFileName) then exit;
  1583. AStream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite);
  1584. AChm := TChmReader.Create(AStream, True);
  1585. AIndex := AddObject(AFileName, AChm);
  1586. fLastChm := AChm;
  1587. if Assigned(fOnOpenNewFile) then fOnOpenNewFile(Self, AIndex)
  1588. else fUnNotifiedFiles.Add(AChm);
  1589. end;
  1590. function TChmFileList.CheckOpenFile(AFileName: String): Boolean;
  1591. var
  1592. X: Integer;
  1593. begin
  1594. Result := False;
  1595. for X := 0 to Count-1 do begin
  1596. if ExtractFileName(FileName[X]) = AFileName then begin
  1597. fLastChm := Chm[X];
  1598. Result := True;
  1599. Exit;
  1600. end;
  1601. end;
  1602. if not Result then begin
  1603. AFileName := ExtractFilePath(FileName[0])+AFileName;
  1604. if FileExists(AFileName) and (LowerCase(ExtractFileExt(AFileName)) = '.chm') then OpenNewFile(AFileName);
  1605. Result := True;
  1606. end;
  1607. end;
  1608. function TChmFileList.MetaObjectExists(var Name: String): QWord;
  1609. var
  1610. AFileName: String;
  1611. URL: String;
  1612. fStart, fEnd: Integer;
  1613. Found: Boolean;
  1614. begin
  1615. Found := False;
  1616. Result := 0;
  1617. //Known META file link types
  1618. // ms-its:name.chm::/topic.htm
  1619. //mk:@MSITStore:name.chm::/topic.htm
  1620. if Pos('ms-its:', Name) > 0 then begin
  1621. fStart := Pos('ms-its:', Name)+Length('ms-its:');
  1622. fEnd := Pos('::', Name)-fStart;
  1623. AFileName := Copy(Name, fStart, fEnd);
  1624. fStart := fEnd+fStart+2;
  1625. fEnd := Length(Name) - (fStart-1);
  1626. URL := Copy(Name, fStart, fEnd);
  1627. Found := True;
  1628. end
  1629. else if Pos('mk:@MSITStore:', Name) > 0 then begin
  1630. fStart := Pos('mk:@MSITStore:', Name)+Length('mk:@MSITStore:');
  1631. fEnd := Pos('::', Name)-fStart;
  1632. AFileName := Copy(Name, fStart, fEnd);
  1633. fStart := fEnd+fStart+2;
  1634. fEnd := Length(Name) - (fStart-1);
  1635. URL := Copy(Name, fStart, fEnd);
  1636. Found := True;
  1637. end;
  1638. if not Found then exit;
  1639. //WriteLn('Looking for URL ', URL, ' in ', AFileName);
  1640. if CheckOpenFile(AFileName) then
  1641. Result := fLastChm.ObjectExists(URL);
  1642. if Result > 0 then NAme := Url;
  1643. end;
  1644. function TChmFileList.MetaGetObject(Name: String): TMemoryStream;
  1645. begin
  1646. Result := nil;
  1647. if MetaObjectExists(Name) > 0 then Result := fLastChm.GetObject(Name);
  1648. end;
  1649. constructor TChmFileList.Create(PrimaryFileName: String);
  1650. begin
  1651. inherited Create;
  1652. fUnNotifiedFiles := TList.Create;
  1653. OpenNewFile(PrimaryFileName);
  1654. end;
  1655. destructor TChmFileList.Destroy;
  1656. begin
  1657. fUnNotifiedFiles.Free;
  1658. inherited Destroy;
  1659. end;
  1660. procedure TChmFileList.SetOnOpenNewFile(AValue: TChmFileOpenEvent);
  1661. var
  1662. X: Integer;
  1663. begin
  1664. fOnOpenNewFile := AValue;
  1665. if not assigned(AValue) then exit;
  1666. for X := 0 to fUnNotifiedFiles.Count-1 do
  1667. AValue(Self, X);
  1668. fUnNotifiedFiles.Clear;
  1669. end;
  1670. function TChmFileList.ObjectExists(Name: String; var fChm: TChmReader): QWord;
  1671. begin
  1672. Result := 0;
  1673. if Count = 0 then exit;
  1674. if fChm <> nil then fLastChm := fChm;
  1675. Result := fLastChm.ObjectExists(Name);
  1676. if Result = 0 then begin
  1677. Result := Chm[0].ObjectExists(Name);
  1678. if Result > 0 then fLastChm := Chm[0];
  1679. end;
  1680. if Result = 0 then begin
  1681. Result := MetaObjectExists(Name);
  1682. end;
  1683. if (Result <> 0) and (fChm = nil) then
  1684. fChm := fLastChm;
  1685. end;
  1686. function TChmFileList.GetObject(Name: String): TMemoryStream;
  1687. begin
  1688. Result := nil;
  1689. if Count = 0 then exit;
  1690. Result := fLastChm.GetObject(Name);
  1691. if Result = nil then Result := MetaGetObject(Name);
  1692. end;
  1693. function TChmFileList.IsAnOpenFile(AFileName: String): Boolean;
  1694. var
  1695. X: Integer;
  1696. begin
  1697. Result := False;
  1698. for X := 0 to Count-1 do begin
  1699. if AFileName = FileName[X] then Exit(True);
  1700. end;
  1701. end;
  1702. end.