summaryrefslogtreecommitdiffstats
path: root/fbreader/src/formats/pdb/EReaderStream.cpp
blob: 97757732f1b6ba5a95cb1b07f0b047b88e74bd56 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
/*
 * Copyright (C) 2004-2012 Geometer Plus <[email protected]>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */

#include <algorithm>
#include <cctype>

#include <ZLFile.h>
#include <ZLResource.h>
#include <ZLZDecompressor.h>

#include "EReaderStream.h"
#include "DocDecompressor.h"


EReaderStream::EReaderStream(const ZLFile &file) : PalmDocLikeStream(file) {
	myDestination = TEXT;
}

EReaderStream::~EReaderStream() {
	close();
}

bool EReaderStream::switchStreamDestination(StreamDestination destination, const std::string& id) {
	bool result = true;
	switch(destination) {
		case TEXT:
			myDestination = TEXT; 
			myRecordIndex = 1;
			break;
		case FOOTNOTE:
			std::map<std::string, unsigned short>::const_iterator footnoteIt = myFootnotes.find(id);
			if (footnoteIt != myFootnotes.end()) {
				myDestination = FOOTNOTE; 
				myRecordIndex = footnoteIt->second;
			} else {
				result = false;
			}
			break;
	}
	return result;
}

bool EReaderStream::fillBuffer() {
	if (myDestination == TEXT) {
	 	return PalmDocLikeStream::fillBuffer();
	} else {
		while (myBufferOffset == myBufferLength) {
			if (!processRecord()) {
				return false;
			}
		}
		return true;
	}
}

bool EReaderStream::processRecord() {
	const std::size_t currentOffset = recordOffset(myRecordIndex);
	if (currentOffset < myBase->offset()) {
		return false;
	}
	myBase->seek(currentOffset, true);
	const std::size_t nextOffset = recordOffset(myRecordIndex + 1);
	if (nextOffset < currentOffset) {
		return false;
	}

	unsigned short myCompressedSize = nextOffset - currentOffset;
 
	switch (myCompressionVersion) {
		case 10:			// Inflate compression
			myBase->seek(2, false);
			myBufferLength = ZLZDecompressor(myCompressedSize - 2).decompress(*myBase, myBuffer, myMaxRecordSize); 
			break;
		case 2:				// PalmDoc compression
			myBufferLength = DocDecompressor().decompress(*myBase, myBuffer, myCompressedSize, myMaxRecordSize);
			break;
	}
	clearBuffer('\0');
	myBufferOffset = 0;
	return true;
}

bool EReaderStream::processZeroRecord() {
	// Use it with offset presetting to zero record offset value
	PdbUtil::readUnsignedShort(*myBase, myCompressionVersion); 			// myBase offset: ^ + 2
	if (myCompressionVersion > 255) {
		myErrorCode = ERROR_ENCRYPTION;
		return false;
	} else {
		switch (myCompressionVersion) {
			case 2:
			case 10:
				break;
			default:
				myErrorCode = ERROR_COMPRESSION;
				return false;
		}
	}
	myBase->seek(10, false);											// myBase offset: ^ + 12
	PdbUtil::readUnsignedShort(*myBase, myNonTextOffset); 				// myBase offset: ^ + 14
	PdbUtil::readUnsignedShort(*myBase, myNonTextOffsetReserved); 		// myBase offset: ^ + 16
	myBase->seek(12, false);											// myBase offset: ^ + 28
	PdbUtil::readUnsignedShort(*myBase, myFootnoteRecords); 			// myBase offset: ^ + 30
	PdbUtil::readUnsignedShort(*myBase, mySidebarRecords); 				// myBase offset: ^ + 32
	PdbUtil::readUnsignedShort(*myBase, myBookmarksOffset); 			// myBase offset: ^ + 34
	myBase->seek(2, false);												// myBase offset: ^ + 36
	PdbUtil::readUnsignedShort(*myBase, myNonTextOffsetExtraReserved); 	// myBase offset: ^ + 38
	myBase->seek(2, false);												// myBase offset: ^ + 40
	PdbUtil::readUnsignedShort(*myBase, myImagedataOffset); 			// myBase offset: ^ + 42
	PdbUtil::readUnsignedShort(*myBase, myImagedataOffsetReserved); 	// myBase offset: ^ + 44
	PdbUtil::readUnsignedShort(*myBase, myMetadataOffset); 				// myBase offset: ^ + 46
	PdbUtil::readUnsignedShort(*myBase, myMetadataOffsetReserved); 		// myBase offset: ^ + 48
	PdbUtil::readUnsignedShort(*myBase, myFootnoteOffset); 				// myBase offset: ^ + 50
	PdbUtil::readUnsignedShort(*myBase, mySidebarOffset); 				// myBase offset: ^ + 52
	PdbUtil::readUnsignedShort(*myBase, myLastdataOffset); 				// myBase offset: ^ + 54

	unsigned short endSectionIndex = header().Offsets.size();
	myMaxRecordIndex = std::min((unsigned short) (myNonTextOffset - 1), (unsigned short) (endSectionIndex - 1));

	myMaxRecordSize = 65535;	// Maximum size of addressable space in PalmOS 
								// not more than 8192 bytes happens in the tested examples
 
	if (myFootnoteRecords) {
		bool isSuccess = processFootnoteIdsRecord(); 
		if (!isSuccess) {
			//TODO take in account returned bool value
			//false if wrong footnotes amount anounced in zero record
			//or corrupted or wrong footnote ids record
		} 
	}

	if (myImagedataOffset != myMetadataOffset) {
		bool isSuccess = processImageHeaders(); 
		if (!isSuccess) {
			//TODO take in account returned bool value
			//false if one of image record is corrupted
		} 
	}

	myBase->seek(header().Offsets[1], true);

	/*
 	std::cerr << "EReaderStream::processZeroRecord():\n";
	std::cerr << "PDB header indentificator				: " << header().Id << "\n";
	std::cerr << "PDB file system: sizeof opened		: " << myBaseSize << "\n";
	std::cerr << "PDB header/record[0] max index		: " << myMaxRecordIndex << "\n";
	std::cerr << "PDB record[0][0..2] compression	 	: " << myCompressionVersion << "\n";
	std::cerr << "EReader record[0] myNonTextOffset 	: " << myNonTextOffset << std::endl;
	std::cerr << "EReader record[0] myNonTextOffset2 	: " << myNonTextOffsetReserved << std::endl;
	std::cerr << "EReader record[0] myFootnoteRecords 	: " << myFootnoteRecords << std::endl;
	std::cerr << "EReader record[0] mySidebarRecords 	: " << mySidebarRecords << std::endl;
	std::cerr << "EReader record[0] myBookmarksOffset 	: " << myBookmarksOffset << std::endl;
	std::cerr << "EReader record[0] myNonTextOffset3 	: " << myNonTextOffsetExtraReserved << std::endl;
	std::cerr << "EReader record[0] myImagedataOffset 	: " << myImagedataOffset << std::endl;
	std::cerr << "EReader record[0] myImagedataOffset2 	: " << myImagedataOffsetReserved << std::endl;
	std::cerr << "EReader record[0] myMetadataOffset 	: " << myMetadataOffset << std::endl;
	std::cerr << "EReader record[0] myMetadataOffset2 	: " << myMetadataOffsetReserved << std::endl;
	std::cerr << "EReader record[0] myFootnoteOffset 	: " << myFootnoteOffset << std::endl;
	std::cerr << "EReader record[0] mySidebarOffset 	: " << mySidebarOffset << std::endl;
	std::cerr << "EReader record[0] myLastdataOffset 	: " << myLastdataOffset << std::endl;
	std::cerr << "PDB header lastSectionIndex			: " << endSectionIndex - 1 << "\n";
	*/
	return true;
}

void EReaderStream::clearBuffer(unsigned char symbol) {
	myBufferLength = std::remove(myBuffer, myBuffer + myBufferLength, symbol) - myBuffer;
}

bool EReaderStream::processFootnoteIdsRecord() {
	char* footnoteIdBuffer = new char[myMaxRecordSize];
	myBase->seek(header().Offsets[myFootnoteOffset], true);
	const std::size_t currentOffset = recordOffset(myFootnoteOffset);
	const std::size_t nextOffset = recordOffset(myFootnoteOffset + 1);
	const std::size_t length = nextOffset - currentOffset;
	myBase->read(footnoteIdBuffer, length);
	std::string footnoteIdStr(footnoteIdBuffer, length);
	unsigned short footnoteIndex = myFootnoteOffset + 1;
	while (!footnoteIdStr.empty() && (footnoteIndex < myLastdataOffset)) {
		std::string id = findFootnoteId(footnoteIdStr);
		if (!id.empty()) {
			myFootnotes[id] = footnoteIndex;
			++footnoteIndex;
		}
	}
	delete[] footnoteIdBuffer;
	return (myFootnoteRecords - 1 == (unsigned short)myFootnotes.size());
}

std::string EReaderStream::findFootnoteId(std::string &footnoteIdStr) const {
	std::string resultStr;
	if (!footnoteIdStr.empty()) {
		std::size_t counter = 0;
		for (; counter < footnoteIdStr.length(); ++counter) {
			if (std::isalnum(footnoteIdStr[counter])) {
				break;
			}
		}
		const std::size_t startIdIndex = counter;
		for (; counter < footnoteIdStr.length(); ++counter) {
			if (footnoteIdStr[counter] == '\0') {
				break;
			}
		}
		const std::size_t endIdIndex = counter;
		resultStr = footnoteIdStr.substr(startIdIndex, endIdIndex - startIdIndex);
		footnoteIdStr = footnoteIdStr.substr(endIdIndex);
	}
	return resultStr;
}

const std::map<std::string, unsigned short>& EReaderStream::footnotes() const {
	return myFootnotes;
}

bool EReaderStream::processImageHeaders() {
	unsigned short recordIndex = myImagedataOffset;
	bool result = true;
	myBase->seek(header().Offsets[recordIndex], true);
	while (recordIndex < myMetadataOffset && recordIndex < myLastdataOffset) {
		result = result && addImageInfo(recordIndex);
		++recordIndex;
	}
	return result;
}

bool EReaderStream::addImageInfo(const unsigned short recordIndex) {
	const std::size_t bufferLength = 128;
	char *buffer = new char[bufferLength]; //TODO may be it's needed here more bytes
	ImageInfo image;
	const std::size_t currentOffset = recordOffset(recordIndex);
	const std::size_t nextOffset = recordOffset(recordIndex + 1);

	myBase->read(buffer, bufferLength);
	std::string header(buffer, bufferLength);
	delete[] buffer;

	image.Offset = currentOffset + header.find("\x89PNG"); //TODO treat situation when there isn't PNG in first 128 bytes
	image.Size = nextOffset - image.Offset;
	const int endType = header.find(' ');
	image.Type = ZLMimeType::get(header.substr(0, endType));
	header = header.substr(endType + 1);
	const int endId = header.find('\0');
	const std::string id = header.substr(0, endId);
	myBase->seek(nextOffset - currentOffset - bufferLength, false);
	if (id.empty()) {
		return false;
	}
	myImages[id] = image;
	return true;
}


/*bool EReaderStream::hasExtraSections() const {
	return false;
	//return myMaxRecordIndex < header().Offsets.size() - 1;
}*/

EReaderStream::ImageInfo EReaderStream::imageLocation(const std::string& id) {
	if (myImagedataOffset != myMetadataOffset && myImages.empty()) {
		processImageHeaders();
	}
	const std::map<std::string, ImageInfo>::const_iterator it = myImages.find(id);
	if (it != myImages.end()) {
		return it->second;
	} else {
		return ImageInfo();
	}
}

const std::map<std::string, EReaderStream::ImageInfo>& EReaderStream::images() const {
	return myImages;
}