File: FileManager.cpp

package info (click to toggle)
glob2 0.9.4.4-7
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 34,852 kB
  • sloc: cpp: 89,685; python: 868; ansic: 259; sh: 49; makefile: 20
file content (570 lines) | stat: -rw-r--r-- 12,718 bytes parent folder | download | duplicates (3)
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
/*
  Copyright (C) 2001-2004 Stephane Magnenat & Luc-Olivier de Charrière
  for any question or comment contact us at <stephane at magnenat dot net> or <NuageBleu at gmail dot com>

  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 3 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/

#include <FileManager.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#ifndef DX9_BACKEND	// TODO:Die!
#include <SDL_endian.h>
#else
#include <Types.h>
#endif
#include <iostream>
#include <valarray>
#include <zlib.h>
#include "BinaryStream.h"
#include "TextStream.h"

// here we handle compile time options
#ifdef HAVE_CONFIG_H
#  include "config.h"
#else
#	ifdef WIN32
#		define PACKAGE_DATA_DIR ".."
#		define PACKAGE_SOURCE_DIR "../.."
#	else
#		define PACKAGE_DATA_DIR ".."
#		define PACKAGE_SOURCE_DIR "../.."
#	endif
#endif

// include for directory listing
#ifdef WIN32
#	include <windows.h>
#	include <io.h>
#	include <direct.h>
#	include "win32_dirent.h"
#else
#	include <sys/types.h>
#	include <dirent.h>
#	include <sys/stat.h>
#endif

#ifndef WIN32
#ifndef __APPLE__
#	include "unistd.h"
#endif
#endif

namespace GAGCore
{
	FileManager::FileManager(const char *gameName)
	{
		#ifndef WIN32
		const char *homeDir = getenv("HOME");
		if (homeDir)
		{
			std::string gameLocal(homeDir);
			gameLocal  = "/.";
			gameLocal  = gameName;
			mkdir(gameLocal.c_str(), S_IRWXU);
			addDir(gameLocal.c_str());
		}
		else
			std::cerr << "FileManager::FileManager : warning, can't get home directory by using getenv(\"HOME\")" << std::endl;
		#endif
#ifdef __APPLE__
		addDir("./Contents/Resources");
#endif
		addDir(".");

		#ifndef WIN32
		#ifndef __APPLE__
		/* Find own path
		 * TODO: Make nicer */

		char link[100];
		#ifdef __FreeBSD__
		char proc[]="/proc/curproc/file";
		#else
		char proc[]="/proc/self/exe";
		#endif
		char * pch;

		int linksize = readlink(proc, link, sizeof(link));
		if (linksize < 0)
		{
			perror("readlink() error");
		}
		else
		{
			assert ((int)sizeof(link) > linksize);
			link[linksize] = '\0';

			pch = strrchr(link,'/');
			if ( (pch-link) > 0)
				link[pch-link] = '\0';
			else
				link[1] = '\0';

			pch = strrchr(link,'/');
			if ( (pch-link) > 0)
				link[pch-link] = '\0';

			if ((linksize   13) <= (int)sizeof(link))
			{
				strcat(link, "/share/games/glob2");
				addDir(link);
			}
		}
		#endif
		#endif

		addDir(PACKAGE_DATA_DIR);
		//addDir(PACKAGE_SOURCE_DIR);
		fileListIndex = -1;
	}
	
	FileManager::~FileManager()
	{
		dirList.clear();
		clearFileList();
	}
	
	void FileManager::clearFileList(void)
	{
		fileList.clear();
		fileListIndex = -1;
	}
	
	void FileManager::addDir(const char *dir)
	{
		dirList.push_back(dir);
	}
	
	void FileManager::addWriteSubdir(const char *subdir)
	{
		for (size_t i = 0; i < dirList.size(); i  )
		{
			std::string toCreate(dirList[i]);
			toCreate  = '/';
			toCreate  = subdir;
			#ifdef WIN32
			int result = _mkdir(toCreate.c_str());
			#else
			int result = mkdir(toCreate.c_str(), S_IRWXU);
			#endif
			// NOTE : We only want to create the subdir for the first index
	// 		if (result==0)
				break;
			if ((result==-1) && (errno==EEXIST))
				break;
		}
	}
	
	SDL_RWops *FileManager::openWithbackup(const char *filename, const char *mode)
	{
		if (strchr(mode, 'w'))
		{
			std::string backupName(filename);
			backupName  = '~';
			rename(filename, backupName.c_str());
		}
		return SDL_RWFromFile(filename, mode);
	}
	
	FILE *FileManager::openWithbackupFP(const char *filename, const char *mode)
	{
		if (strchr(mode, 'w'))
		{
			std::string backupName(filename);
			backupName  = '~';
			rename(filename, backupName.c_str());
		}
		return fopen(filename, mode);
	}
	
	std::ofstream *FileManager::openWithbackupOFS(const char *filename, std::ofstream::openmode mode)
	{
		if (mode & std::ios_base::out)
		{
			std::string backupName(filename);
			backupName  = '~';
			rename(filename, backupName.c_str());
		}
		std::ofstream *ofs = new std::ofstream(filename, mode);
		if (ofs->is_open())
			return ofs;
		
		delete ofs;
		return NULL;
	}
	
	StreamBackend *FileManager::openOutputStreamBackend(const char *filename)
	{
		for (size_t i = 0; i < dirList.size();   i)
		{
			std::string path(dirList[i]);
			path  = DIR_SEPARATOR;
			path  = filename;
			
			FILE *fp = fopen(path.c_str(), "wb");
			if (fp)
				return new FileStreamBackend(fp);
		}
	
		return new FileStreamBackend(NULL);
	}
	
	StreamBackend *FileManager::openInputStreamBackend(const char *filename)
	{	
	
		for (size_t i = 0; i < dirList.size();   i)
		{
			std::string path(dirList[i]);
			path  = DIR_SEPARATOR;
			path  = filename;
			
			FILE *fp = fopen(path.c_str(), "rb");
			if (fp)
				return new FileStreamBackend(fp);
		}
	
		return new FileStreamBackend(NULL);
	}
	
	StreamBackend *FileManager::openCompressedOutputStreamBackend(const char *filename)
	{
		for (size_t i = 0; i < dirList.size();   i)
		{
			std::string path(dirList[i]);
			path  = DIR_SEPARATOR;
			path  = filename;
			
			//Test if it can be opened first
			FILE *fp = fopen(path.c_str(), "wb");
			if(fp)
			{
				fclose(fp);
				return new ZLibStreamBackend(path, false);
			}
		}
	
		return new ZLibStreamBackend("", false);
	}
	
	StreamBackend *FileManager::openCompressedInputStreamBackend(const char *filename)
	{
		for (size_t i = 0; i < dirList.size();   i)
		{
			std::string path(dirList[i]);
			path  = DIR_SEPARATOR;
			path  = filename;
			
			FILE *fp = fopen(path.c_str(), "rb");
			if(fp)
			{
				fclose(fp);
				return new ZLibStreamBackend(path, true);
			}
		}
	
		return new ZLibStreamBackend("", false);
	}
	
	SDL_RWops *FileManager::open(const char *filename, const char *mode)
	{
		for (size_t i = 0; i < dirList.size();   i)
		{
			std::string path(dirList[i]);
			path  = DIR_SEPARATOR;
			path  = filename;
	
			//std::cerr << "FileManager::open trying to open " << path << " corresponding to source [" << dirList[i] << "] and filename [" << filename << "] with mode " << mode << "\n" << std::endl;
			SDL_RWops *fp = openWithbackup(path.c_str(), mode);
			if (fp)
				return fp;
		}
	
		return NULL;
	}
	
	FILE *FileManager::openFP(const char *filename, const char *mode)
	{
		for (size_t i = 0; i < dirList.size();   i)
		{
			std::string path(dirList[i]);
			path  = DIR_SEPARATOR;
			path  = filename;
			
			FILE *fp = openWithbackupFP(path.c_str(), mode);
			if (fp)
				return fp;
		}
	
		return NULL;
	}
	
	std::ifstream *FileManager::openIFStream(const std::string &fileName)
	{
		for (size_t i = 0; i < dirList.size();   i)
		{
			std::string path(dirList[i]);
			path  = DIR_SEPARATOR;
			path  = fileName;
	
			std::ifstream *fp = new std::ifstream(path.c_str());
			if (fp->good())
				return fp;
			else
				delete fp;
		}
		
		return NULL;
	}
	
	Uint32 FileManager::checksum(const char *filename)
	{
		Uint32 cs = 0;
		SDL_RWops *stream = open(filename);
		if (stream)
		{
			int length = SDL_RWseek(stream, 0, SEEK_END);
			SDL_RWseek(stream, 0, SEEK_SET);
			
			int lengthBlock = length & (~0x3);
			for (int i=0; i<(lengthBlock>>2); i  )
			{
				cs ^= SDL_ReadBE32(stream);
				cs = (cs<<31)|(cs>>1);
			}
			int lengthRest = length & 0x3;
			for (int i=0; i<lengthRest; i  )
			{
				unsigned char c;
				SDL_RWread(stream, &c, 1, 1);
				cs ^= (static_cast<Uint32>(c))<<(8*i);
			}
			SDL_RWclose(stream);
		}
		return cs;
	}
	
	time_t FileManager::mtime(const char *filename)
	{
		for (size_t i = 0; i < dirList.size();   i)
		{
			std::string path(dirList[i]);
			path  = DIR_SEPARATOR;
			path  = filename;
	
			//std::cerr << "FileManager::open trying to open " << path << " corresponding to source [" << dirList[i] << "] and filename [" << filename << "] with mode " << mode << "\n" << std::endl;
			struct stat stats;
			if (stat(path.c_str(), &stats) == 0)
				return stats.st_mtime;
		}
		return 0;
	}
	
	void FileManager::remove(const char *filename)
	{
		for (size_t i = 0; i < dirList.size();   i)
		{
			std::string path(dirList[i]);
			path  = DIR_SEPARATOR;
			path  = filename;
			std::remove(path.c_str());
		}
	}
	
	bool FileManager::isDir(const char *filename)
	{
		#ifdef WIN32
		struct _stat s;
		#else
		struct stat s;
		#endif
		s.st_mode = 0;
		int serr = 1;
		for (size_t i = 0; (serr != 0) && (i < dirList.size());   i)
		{
			std::string path(dirList[i]);
			path  = DIR_SEPARATOR;
			path  = filename;
			#ifdef WIN32
			serr = ::_stat(path.c_str(), &s);
			#else
			serr = stat(path.c_str(), &s);
			#endif
		}
		return (s.st_mode & S_IFDIR) != 0;
	}
	
	bool FileManager::gzip(const std::string &source, const std::string &dest)
	{
		// Open streams
		StreamBackend *srcStream = openInputStreamBackend(source);
		FILE *destStream = openFP(dest.c_str(), "wb");
		
		// Check
		if ((!srcStream->isValid()) || (destStream == NULL))
		{
			delete srcStream;
			return false;
		}
		
		// Preapare source
		srcStream->seekFromEnd(0);
		size_t fileLength = srcStream->getPosition();
		srcStream->seekFromStart(0);
		std::valarray<char> buffer(fileLength);
		
		// Compress
		srcStream->read(&buffer[0], fileLength);
		gzFile gzStream = gzdopen(fileno(destStream), "wb");
		gzwrite(gzStream, &buffer[0], fileLength);
		
		// Close
		gzclose(gzStream);
		delete srcStream;
		
		return true;
	}
	
	bool FileManager::gunzip(const std::string &source, const std::string &dest)
	{
		// Open streams
		FILE *srcStream = openFP(source.c_str(), "rb");
		StreamBackend *destStream = openOutputStreamBackend(dest);
		
		// Check
		if ((!destStream->isValid()) || (srcStream == NULL))
		{
			delete destStream;
			return false;
		}
		
		// Preapare source
		gzFile gzStream = gzdopen(fileno(srcStream), "rb");
		#define BLOCK_SIZE 1024*1024
		std::string buffer;
		size_t len = 0;
		size_t bufferLength = 0;
		
		// Uncompress
		while (gzeof(gzStream) == 0)
		{
			buffer.resize(bufferLength   BLOCK_SIZE);
			len  = gzread(gzStream, const_cast<void *>(static_cast<const void *>(buffer.data()   bufferLength)), BLOCK_SIZE);
			bufferLength  = BLOCK_SIZE;
		}
		
		// Write
		destStream->write(buffer.c_str(), len);
		
		// Close
		gzclose(gzStream);
		delete destStream;
		
		return true;
	}

	bool FileManager::addListingForDir(const char *realDir, const char *extension, const bool dirs)
	{
		DIR *dir = opendir(realDir);
		struct dirent *dirEntry;
	
		if (!dir)
		{
			#ifdef DBG_VPATH_LIST
			std::cerr << "GAG : Open dir failed for dir " << realDir << std::endl;
			#endif
			return false;
		}
	
		while ((dirEntry = readdir(dir))!=NULL)
		{
			#ifdef DBG_VPATH_LIST
			std::cerr << realDir << std::endl;
			#endif
			
			// there might be a way to optimize the decision of the ok
			bool ok = true;
			// hide hidden stuff
			if (dirEntry->d_name[0] == '.')
			{
				ok = false;
			}
			// take directories if asked
			else if (isDir(dirEntry->d_name)) // d_type is not portable to all systems
			{
				ok = dirs;
			}
			// check extension if provided
			else if (extension) 
			{
				size_t l, nl;
				l=strlen(extension);
				nl=strlen(dirEntry->d_name);
				ok = ((nl>l) &&
					(dirEntry->d_name[nl-l-1]=='.') &&
					(strcmp(extension,dirEntry->d_name (nl-l))==0));
			}
			if (ok)
			{
				// test if name already exists in vector
				bool alreadyIn = false;
				for (size_t i = 0; i < fileList.size();   i)
				{
					if (fileList[i] == dirEntry->d_name)
					{
						alreadyIn = true;
						break;
					}
				}
				if (!alreadyIn)
				{
					fileList.push_back(dirEntry->d_name);
				}
			}
		}
	
		closedir(dir);
		return true;
	}
	
	bool FileManager::initDirectoryListing(const char *virtualDir, const char *extension, const bool dirs)
	{
		bool result = false;
		clearFileList();
		for (size_t i = 0; i < dirList.size();   i)
		{
			std::string path(dirList[i]);
			path  = DIR_SEPARATOR;
			path  = virtualDir;
			result = addListingForDir(path.c_str(), extension, dirs) || result;
		}
		if (result)
			fileListIndex=0;
		else
			fileListIndex=-1;
		return result;
	}
	
	const char *FileManager::getNextDirectoryEntry(void)
	{
		if ((fileListIndex >= 0) && (fileListIndex < (int)fileList.size()))
		{
			return fileList[fileListIndex  ].c_str();
		}
		return NULL;
	}
}