File: FileReader.h

package info (click to toggle)
megaglest 3.13.0-9
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 13,416 kB
  • sloc: cpp: 144,271; ansic: 11,861; sh: 3,233; perl: 1,904; python: 1,751; objc: 142; asm: 42; makefile: 22
file content (405 lines) | stat: -rw-r--r-- 11,866 bytes parent folder | download | duplicates (5)
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
// ==============================================================
//	This file is part of MegaGlest Shared Library (www.megaglest.org)
//
//	Copyright (C) 2012 Mark Vejvoda, Titus Tscharntke
//	The MegaGlest Team, under GNU GPL v3.0
// ==============================================================

#ifndef FILE_READER_H
#define FILE_READER_H

#include "platform_util.h"
#include <map>
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <typeinfo>
#include <vector>
#include "conversion.h"
#include "leak_dumper.h"

using std::map;
using std::string;
using std::vector;
using std::ifstream;
using std::ios;
using std::runtime_error;
using namespace Shared::Util;

using Shared::PlatformCommon::extractExtension;

#define AS_STRING(...) #__VA_ARGS__

namespace Shared{

// =====================================================
//	class FileReader
// =====================================================

template <class T>
class FileReader {
public:
	//string const * extensions;
	std::vector<string> extensions;

	/**Creates a filereader being able to possibly load files
	 * from the specified extension
	 **/
	//FileReader(string const * extensions);
	FileReader(std::vector<string> extensions);

	/**Creates a low-priority filereader
	 **/
	FileReader();

public:
	/*Return the - existing and initialized - fileReadersMap
	 */
	static map<string, vector<FileReader<T> const * >* >& getFileReadersMap() {
		static map<string, vector<FileReader<T> const * >* > fileReaderByExtension;
		return fileReaderByExtension;
	}

	static vector<FileReader<T> const * >& getFileReaders() {
		static vector<FileReader<T> const*> fileReaders;
		return fileReaders;
	};

	static vector<FileReader<T> const * >& getLowPriorityFileReaders() {
		static vector<FileReader<T> const*> lowPriorityFileReaders;
		return lowPriorityFileReaders;
	};


public:

	/**Tries to read a file
	 * This method tries to read the file with the specified filepath.
	 * If it fails, either <code>null</code> is returned or an exception
         * is thrown*/
	static T* readPath(const string& filepath);

	/**Tries to read a file from an object
	 * This method tries to read the file with the specified filepath.
	 * If it fails, either <code>null</code> is returned or an exception
         * is thrown*/
	static T* readPath(const string& filepath, T* object);

	/**Gives a quick estimation of whether the specified file
         * can be read or not depending on the filename*/
	virtual bool canRead(const string& filepath) const;

	/**Gives a better estimation of whether the specified file
	 * can be read or not depending on the file content*/
	virtual bool canRead(ifstream& file) const;

	virtual void cleanupExtensions();

	/**Reads a file
	 * This method tries to read the file with the specified filepath
	 * If it fails, either <code>null</code> is returned or an exception
	 * is thrown
         */
	virtual T* read(const string& filepath) const;

	/**Reads a file to an object
	 * This method tries to read the file with the specified filepath
	 * If it fails, either <code>null</code> is returned or an exception
	 * is thrown
         */
	virtual T* read(const string& filepath, T* object) const;

	/**Reads a file
	 * This method tries to read the specified file
	 * If it failes, either <code>null</code> is returned or an exception
	 * Default implementation generates an object using T()
	 * is thrown
	 */
	virtual T* read(ifstream& file, const string& path) const {
		T* obj = new T();
		T* ret = read(file,path,obj);
		if (obj != ret) {
			delete obj;
		}
		return ret;
	}


	/**Reads a file onto the specified object
	 * This method tries to read the specified file
	 * If it failes, either <code>null</code> is returned or an exception
	 * is thrown
	 */
	virtual T* read(ifstream& file, const string& path, T* former) const = 0;

	virtual ~FileReader() {
		cleanupExtensions();
	}; //Well ... these objects aren't supposed to be destroyed
};

template <typename T>
static inline T* readFromFileReaders(vector<FileReader<T> const *>* readers, const string& filepath) {
	//try to assign file
#if defined(WIN32) && !defined(__MINGW32__)
	FILE *fp = _wfopen(utf8_decode(filepath).c_str(), L"rb");
	ifstream file(fp);
#else
	ifstream file(filepath.c_str(), ios::in | ios::binary);
#endif
	if (!file.is_open()) {
		throw megaglest_runtime_error("[#1] Could not open file " + filepath);
	}
	for (typename vector<FileReader<T> const *>::const_iterator i = readers->begin(); i != readers->end(); ++i) {
		T* ret = NULL;
		file.seekg(0, ios::beg); //Set position to first
		try {
			FileReader<T> const * reader = *i;
			ret = reader->read(file, filepath); //It is guaranteed that at least the filepath matches ...
		}
#if defined(WIN32)
		catch (megaglest_runtime_error) {
#else
		catch (megaglest_runtime_error &ex) {
#endif
			throw;
		}
		catch (...) {
			continue;
		}
		if (ret != NULL) {
			file.close();
#if defined(WIN32) && !defined(__MINGW32__)
			if(fp) fclose(fp);
#endif
			return ret;
		}
	}
	file.close();
#if defined(WIN32) && !defined(__MINGW32__)
	if(fp) fclose(fp);
#endif

	return NULL;
}

template <typename T>
static inline T* readFromFileReaders(vector<FileReader<T> const *>* readers, const string& filepath, T* object) {
	//try to assign file
#if defined(WIN32) && !defined(__MINGW32__)
	wstring wstr = utf8_decode(filepath);
	FILE *fp = _wfopen(wstr.c_str(), L"rb");
	int fileErrno = errno;
	ifstream file(fp);
#else
	ifstream file(filepath.c_str(), ios::in | ios::binary);
#endif
	if (!file.is_open()) {
#if defined(WIN32) && !defined(__MINGW32__)
		DWORD error = GetLastError();
		throw megaglest_runtime_error("[#2] Could not open file, result: " + intToStr(error) + " - " + intToStr(fileErrno) + " [" + filepath + "]");
#else
		throw megaglest_runtime_error("[#2] Could not open file [" + filepath + "]");
#endif
	}
	for (typename vector<FileReader<T> const *>::const_iterator i = readers->begin(); i != readers->end(); ++i) {
		T* ret = NULL;
		file.seekg(0, ios::beg); //Set position to first
		try {
			FileReader<T> const * reader = *i;
			ret = reader->read(file, filepath, object); //It is guaranteed that at least the filepath matches ...
		}
#if defined(WIN32)
		catch (megaglest_runtime_error) {
#else
		catch (megaglest_runtime_error &ex) {
#endif
			throw;
		}
		catch (...) {
			continue;
		}
		if (ret != NULL) {
			file.close();
#if defined(WIN32) && !defined(__MINGW32__)
			if(fp) fclose(fp);
#endif
			return ret;
		}
	}
	file.close();
#if defined(WIN32) && !defined(__MINGW32__)
	if(fp) fclose(fp);
#endif
	return NULL;
}

/**Tries to read a file
 * This method tries to read the file with the specified filepath.
 * If it fails, either <code>null</code> is returned or an exception
 * is thrown*/
template <typename T>
T* FileReader<T>::readPath(const string& filepath) {
	const string& extension = extractExtension(filepath);
	vector<FileReader<T> const * >* possibleReaders = (getFileReadersMap())[extension];
	if (possibleReaders != NULL) {
		//Search in these possible readers
		T* ret = readFromFileReaders(possibleReaders, filepath);
		if (ret != NULL) {
			return ret;
		}
	}
	T* ret = readFromFileReaders(&(getFileReaders()), filepath); //Try all other
	if (ret == NULL) {
		std::cerr << "ERROR #1 - Could not parse filepath: " << filepath << std::endl;
		throw megaglest_runtime_error(string("Could not parse ") + filepath + " as object of type " + typeid(T).name());
	}
	return ret;
}

/**Tries to read a file
 * This method tries to read the file with the specified filepath.
 * If it fails, either <code>null</code> is returned or an exception
 * is thrown*/
template <typename T>
T* FileReader<T>::readPath(const string& filepath, T* object) {
	const string& extension = extractExtension(filepath);
	vector<FileReader<T> const * >* possibleReaders = (getFileReadersMap())[extension];
	if (possibleReaders != NULL) {
		//Search in these possible readers
		T* ret = readFromFileReaders(possibleReaders, filepath, object);
		if (ret != NULL) {
			return ret;
		}
	}
	T* ret = readFromFileReaders(&(getFileReaders()), filepath, object); //Try all other
	if (ret == NULL) {
		std::cerr << "ERROR #2 - Could not parse filepath: " << filepath << std::endl;
		ret = readFromFileReaders(&(getLowPriorityFileReaders()), filepath); //Try to get dummy file
		if (ret == NULL) {
			throw megaglest_runtime_error(string("Could not parse ") + filepath + " as object of type " + typeid(T).name());
		}
	}
	return ret;
}

template <typename T>
FileReader<T>::FileReader(std::vector<string> extensions): extensions(extensions) {
	getFileReaders().push_back(this);
	std::vector<string> nextExtension = extensions;
	for(unsigned int i = 0; i < nextExtension.size(); ++i) {
		vector<FileReader<T> const* >* curPossibleReaders = (getFileReadersMap())[nextExtension[i]];
		if (curPossibleReaders == NULL) {
			(getFileReadersMap())[nextExtension[i]] = (curPossibleReaders = new vector<FileReader<T> const *>());
		}
		curPossibleReaders->push_back(this);
	}
}

template <typename T>
void FileReader<T>::cleanupExtensions() {
	std::vector<string> nextExtension = extensions;
	for(unsigned int i = 0; i < nextExtension.size(); ++i) {
		vector<FileReader<T> const* >* curPossibleReaders = (getFileReadersMap())[nextExtension[i]];
		if (curPossibleReaders != NULL) {
			delete curPossibleReaders;
			(getFileReadersMap())[nextExtension[i]] = NULL;
		}
	}
}

/**Gives a quick estimation of whether the specified file
 * can be read or not depending on the filename*/
template <typename T>
bool FileReader<T>::canRead(const string& filepath) const {
	const string& realExtension = extractExtension(filepath);
	//const string* haveExtension = extensions;
	std::vector<string> haveExtension = extensions;
	//while (*haveExtension != "") {
	for(unsigned int i = 0; i < haveExtension.size(); ++i) {
		//if (realExtension == *haveExtension) {
		if (realExtension == haveExtension[i]) {
			return true;
		}
		//++haveExtension;
	}
	return false;
}

/**Gives a better estimation of whether the specified file
 * can be read or not depending on the file content*/
template <typename T>
bool FileReader<T>::canRead(ifstream& file) const {
	try {
		T* wouldRead = read(file,"unknown file");
		bool ret = (wouldRead != NULL);
		delete wouldRead;
		return ret;
	}
#if defined(WIN32)
	catch (megaglest_runtime_error) {
#else
	catch (megaglest_runtime_error &ex) {
#endif
		throw;
	}
	catch (...) {
		return false;
	}
}

/**Reads a file
 * This method tries to read the file with the specified filepath
 * If it fails, either <code>null</code> is returned or an exception
 * is thrown
 */
template <typename T>
T* FileReader<T>::read(const string& filepath) const {
#if defined(WIN32) && !defined(__MINGW32__)
	FILE *fp = _wfopen(utf8_decode(filepath).c_str(), L"rb");
	ifstream file(fp);
#else
	ifstream file(filepath.c_str(), ios::in | ios::binary);
#endif
	if (!file.is_open()) {
		throw megaglest_runtime_error("[#3] Could not open file " + filepath);
	}
	T* ret = read(file,filepath);
	file.close();
#if defined(WIN32) && !defined(__MINGW32__)
	if(fp) fclose(fp);
#endif

	return ret;
}

/**Reads a file
 * This method tries to read the file with the specified filepath
 * If it fails, either <code>null</code> is returned or an exception
 * is thrown
 */
template <typename T>
T* FileReader<T>::read(const string& filepath, T* object) const {
#if defined(WIN32) && !defined(__MINGW32__)
	FILE *fp = _wfopen(utf8_decode(filepath).c_str(), L"rb");
	ifstream file(fp);
#else
	ifstream file(filepath.c_str(), ios::in | ios::binary);
#endif
	if (!file.is_open()) {
		throw megaglest_runtime_error("[#4] Could not open file " + filepath);
	}
	T* ret = read(file,filepath,object);
	file.close();
#if defined(WIN32) && !defined(__MINGW32__)
	if(fp) fclose(fp);
#endif

	return ret;
}


} //end namespace

#endif