aboutsummaryrefslogtreecommitdiff
path: root/engines/sword25/package/physfspackagemanager.cpp
blob: 70b9d98578653c922da34f1ec352fce774d2a932 (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
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
// -----------------------------------------------------------------------------
// This file is part of Broken Sword 2.5
// Copyright (c) Malte Thiesen, Daniel Queteschiner and Michael Elsd�rfer
//
// Broken Sword 2.5 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.
//
// Broken Sword 2.5 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 Broken Sword 2.5; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------

#include "physfspackagemanager.h"
#include "util/physfs/physfs.h"
extern "C"
{
	#include "util/physfs/extras/globbing.h"
};

#include "kernel/memlog_off.h"
#include <vector>
#include <sstream>
#include "kernel/memlog_on.h"

using namespace std;

// -----------------------------------------------------------------------------

#define BS_LOG_PREFIX "PHYSFSPACKAGEMANAGER"

// -----------------------------------------------------------------------------
// Hilfsfunktionen
// -----------------------------------------------------------------------------

namespace
{
	const char * SafeGetLastError()
	{
		const char * ErrorMessage = PHYSFS_getLastError();
		return ErrorMessage ? ErrorMessage : "unknown";
	}

	// -------------------------------------------------------------------------

	void LogPhysfsError(const char * FunctionName)
	{
		BS_LOG_ERRORLN("%s() failed. Reason: %s.", FunctionName, SafeGetLastError());
	}

	// -------------------------------------------------------------------------

	void LogPhysfsError(const char * FunctionName, const char * FileName)
	{
		BS_LOG_ERRORLN("%s() on file \"%s\" failed. Reason: %s.", FunctionName, FileName, SafeGetLastError());
	}

	// -------------------------------------------------------------------------

	const char PATH_SEPARATOR = '/';
	const char NAVIGATION_CHARACTER = '.';

	// -------------------------------------------------------------------------

	std::string RemoveRedundantPathSeparators(const std::string & Path)
	{
		std::string Result;

		// �ber alle Zeichen des Eingabepfades iterieren.
		std::string::const_iterator It = Path.begin();
		while (It != Path.end())
		{
			if (*It == PATH_SEPARATOR)
			{
				// Verzeichnistrenner gefunden.

				// Folgen von Verzeichnistrennern �berspringen.
				while (It != Path.end() && *It == PATH_SEPARATOR) ++It;

				// Einzelnen Verzeichnistrenner ausgeben, nur am Ende des Pfades wird kein Verzeichnistrenner mehr ausgegeben.
				if (It != Path.end()) Result.push_back(PATH_SEPARATOR);
			}
			else
			{
				// Normales Zeichen gefunden, wird unver�ndert ausgegeben.
				Result.push_back(*It);
				++It;
			}
		}

		return Result;
	}

	// ---------------------------------------------------------------------

	struct PathElement
	{
	public:
		PathElement(std::string::const_iterator Begin, std::string::const_iterator End) : m_Begin(Begin), m_End(End) {}

		std::string::const_iterator GetBegin() const { return m_Begin; }
		std::string::const_iterator GetEnd() const { return m_End; }

	private:
		std::string::const_iterator m_Begin;
		std::string::const_iterator m_End;
	};

	// -------------------------------------------------------------------------

	std::string NormalizePath(const std::string & Path, const std::string & CurrentDirectory)
	{
		// Feststellen, ob der Pfad absolut (beginnt mit /) oder relativ ist und im relativen Fall dem Gesamtpfad das aktuelle Verzeichnis
		// voranstellen.
		std::string WholePath = (Path.size() >= 1 && Path[0] == PATH_SEPARATOR) ? "" : CurrentDirectory + PATH_SEPARATOR;

		// Alle gedoppelten und nachfolgende Verzeichnistrenner aus dem �bergebenen Pfad entfernen und den Gesamtpfad zusammensetzen.
		// CurrentDirectory wird nicht auf diese Weise ges�ubert. Es wird vorrausgesetzt, dass CurrentDirectory keine �berfl�ssigen
		// Verzeichnistrenner beinhaltet.
		WholePath += RemoveRedundantPathSeparators(Path);

		// Gesamtpfad parsen und in Einzelelemente aufteilen. Dabei werden Vorkommen von ".." und "." korrekt behandelt.
		vector<PathElement> PathElements;
		size_t SeparatorPos = 0;
		while (SeparatorPos < WholePath.size())
		{
			// N�chsten Verzeichnistrenner finden.
			size_t NextSeparatorPos = WholePath.find(PATH_SEPARATOR, SeparatorPos + 1);
			if (NextSeparatorPos == std::string::npos) NextSeparatorPos = WholePath.size();

			// Anfang und Ende vom Pfadelement berechnen.
			std::string::const_iterator ElementBegin = WholePath.begin() + SeparatorPos + 1;
			std::string::const_iterator ElementEnd = WholePath.begin() + NextSeparatorPos;

			if (ElementEnd - ElementBegin == 2 &&
				ElementBegin[0] == NAVIGATION_CHARACTER &&
				ElementBegin[1] == NAVIGATION_CHARACTER)
			{
				// Element ist "..", daher wird das vorangegangene Pfadelement aus dem vector entfernt.
				if (PathElements.size()) PathElements.pop_back();
			}
			else if (ElementEnd - ElementBegin == 1 &&
				ElementBegin[0] == NAVIGATION_CHARACTER)
			{
				// Element ist ".", wir tun gar nichts.
			}
			else
			{
				// Normales Element in den vector einf�gen.
				PathElements.push_back(PathElement(WholePath.begin() + SeparatorPos + 1, WholePath.begin() + NextSeparatorPos));
			}

			SeparatorPos = NextSeparatorPos;
		}

		if (PathElements.size())
		{
			// Die einzelnen Pfadelemente werden durch Verzeichnistrenner getrennt aneinandergesetzt.
			// Der so entstandene String wird als Ergebnis zur�ckgegeben.
			ostringstream PathBuilder;
			vector<PathElement>::const_iterator It = PathElements.begin();
			while (It != PathElements.end())
			{
				PathBuilder << PATH_SEPARATOR << std::string(It->GetBegin(), It->GetEnd());
				++It;
			}

			return PathBuilder.str();
		}
		else
		{
			// Nach dem Parsen sind keine Pfadelemente mehr �brig geblieben, daher wird des Root-Verzeichnis zur�ckgegeben.
			return std::string(1, PATH_SEPARATOR);
		}
	}

	// -------------------------------------------------------------------------
	// RAII-Klasse f�r PHYSFS-Filehandles.
	// -------------------------------------------------------------------------

	class PhysfsHandleHolder
	{
	public:
		PhysfsHandleHolder(PHYSFS_File * Handle) : m_Handle(Handle) {}
		~PhysfsHandleHolder()
		{
			if (m_Handle)
			{
				if (!PHYSFS_close(m_Handle)) LogPhysfsError("PHYSFS_close");
			}
		}

		PHYSFS_File * Get() { return m_Handle; }
		PHYSFS_File * Release()
		{
			PHYSFS_File * Result = m_Handle;
			m_Handle = 0;
			return Result;
		}

	private:
		PHYSFS_File * m_Handle;
	};

	// -------------------------------------------------------------------------
	// RAII-Klasse f�r PHYSFS-Listen.
	// -------------------------------------------------------------------------

	template<typename T>
	class PhysfsListHolder
	{
	public:
		PhysfsListHolder(T List) : m_List(List) {};
		~PhysfsListHolder() { if (m_List) PHYSFS_freeList(m_List); }

		T Get() { return m_List; }

	private:
		T m_List;
	};

	// -------------------------------------------------------------------------

	PHYSFS_File * OpenFileAndGetSize(const std::string & FileName, const std::string & CurrentDirectory, unsigned int & FileSize)
	{
		// Datei �ffnen.
		PhysfsHandleHolder Handle(PHYSFS_openRead(NormalizePath(FileName, CurrentDirectory).c_str()));
		if (!Handle.Get())
		{
			LogPhysfsError("PHYSFS_openRead", FileName.c_str());
			return 0;
		}

		// Dateigr��e bestimmen.
		PHYSFS_sint64 LongFileSize = PHYSFS_fileLength(Handle.Get());
		if (LongFileSize == -1)
		{
			BS_LOG_ERRORLN("Unable to determine filelength on PhysicsFS file \"%s\".", FileName.c_str());
			return 0;
		}
		if (LongFileSize >= UINT_MAX)
		{
			BS_LOG_ERRORLN("File \"%s\" is too big.", FileName.c_str());
			return 0;
		}

		// R�ckgabewerte setzen.
		FileSize = static_cast<unsigned int>(LongFileSize);
		return Handle.Release();
	}
}

// -----------------------------------------------------------------------------
// Konstruktion / Destruktion
// -----------------------------------------------------------------------------

BS_PhysfsPackageManager::BS_PhysfsPackageManager(BS_Kernel * KernelPtr) :
	BS_PackageManager(KernelPtr),
	m_CurrentDirectory(1, PATH_SEPARATOR)
{
	if (!PHYSFS_init(0)) LogPhysfsError("PHYSFS_init");
}

// -----------------------------------------------------------------------------

BS_PhysfsPackageManager::~BS_PhysfsPackageManager()
{
	if (!PHYSFS_deinit()) LogPhysfsError("PHYSFS_deinit");
}

// -----------------------------------------------------------------------------

BS_Service * BS_PhysfsPackageManager_CreateObject(BS_Kernel * KernelPtr) { return new BS_PhysfsPackageManager(KernelPtr); }

// -----------------------------------------------------------------------------

bool BS_PhysfsPackageManager::LoadPackage(const std::string & FileName, const std::string & MountPosition)
{
	if (!PHYSFS_mount(FileName.c_str(), NormalizePath(MountPosition, m_CurrentDirectory).c_str(), 0))
	{
		BS_LOG_ERRORLN("Unable to mount file \"%s\" to \"%s\". Reason: %s.", FileName.c_str(), MountPosition.c_str(), SafeGetLastError());
		return false;
	}
	else
	{
		BS_LOGLN("Package '%s' mounted as '%s'.", FileName.c_str(), MountPosition.c_str());
		return true;
	}
}

// -----------------------------------------------------------------------------

bool BS_PhysfsPackageManager::LoadDirectoryAsPackage(const std::string & DirectoryName, const std::string & MountPosition)
{
	if (!PHYSFS_mount(DirectoryName.c_str(), NormalizePath(MountPosition, m_CurrentDirectory).c_str(), 0))
	{
		BS_LOG_ERRORLN("Unable to mount directory \"%s\" to \"%s\". Reason: %s.", DirectoryName.c_str(), MountPosition.c_str(), SafeGetLastError());
		return false;
	}
	else
	{
		BS_LOGLN("Directory '%s' mounted as '%s'.", DirectoryName.c_str(), MountPosition.c_str());
		return true;
	}
}

// -----------------------------------------------------------------------------

void * BS_PhysfsPackageManager::GetFile(const std::string & FileName, unsigned int * FileSizePtr)
{
	// Datei �ffnen und deren Gr��e bestimmen.
	unsigned int FileSize;
	PhysfsHandleHolder Handle(OpenFileAndGetSize(FileName, m_CurrentDirectory, FileSize));
	if (!Handle.Get()) return 0;

	// Falls gew�nscht, die Gr��e der Datei zur�ckgeben.
	if (FileSizePtr) *FileSizePtr = FileSize;

	// Datei einlesen.
	char * Buffer = new char[FileSize];
	if (PHYSFS_read(Handle.Get(), Buffer, 1, FileSize) <= 0)
	{
		LogPhysfsError("PHYSFS_read", FileName.c_str());
		delete [] Buffer;
		return 0;
	}

	return Buffer;
}

// -----------------------------------------------------------------------------

std::string BS_PhysfsPackageManager::GetCurrentDirectory()
{
	return m_CurrentDirectory;
}

// -----------------------------------------------------------------------------

bool BS_PhysfsPackageManager::ChangeDirectory(const std::string & Directory)
{
	// Pfad normalisieren.
	std::string CleanedDirectory = NormalizePath(Directory, m_CurrentDirectory);

	// Interne Variable setzen, wenn das Verzeichnis tats�chlich existiert oder das Wurzelverzeichnis ist.
	if (CleanedDirectory == std::string(1, PATH_SEPARATOR) || PHYSFS_isDirectory(CleanedDirectory.c_str()))
	{
		m_CurrentDirectory = CleanedDirectory;
		return true;
	}
	// Fehler ausgeben, wenn das Verzeichnis nicht existiert.
	else
	{
		BS_LOG_ERRORLN("Tried to change to non-existing directory \"%s\". Call is ignored", Directory.c_str());
		return false;
	}
}

// -----------------------------------------------------------------------------

std::string BS_PhysfsPackageManager::GetAbsolutePath(const std::string & FileName)
{
	return NormalizePath(FileName, m_CurrentDirectory);
}

// -----------------------------------------------------------------------------

unsigned int BS_PhysfsPackageManager::GetFileSize(const std::string & FileName)
{
	// Datei �ffnen und deren Gr��e bestimmen.
	unsigned int FileSize;
	PhysfsHandleHolder Handle(OpenFileAndGetSize(FileName, m_CurrentDirectory, FileSize));
	if (!Handle.Get()) return 0xffffffff;

	// Gr��e der Datei zur�ckgeben.
	return FileSize;
}

// -----------------------------------------------------------------------------

unsigned int BS_PhysfsPackageManager::GetFileType(const std::string & FileName)
{
	std::string NormalizedPath = NormalizePath(FileName, m_CurrentDirectory);

	if (PHYSFS_exists(NormalizedPath.c_str()))
	{
		return PHYSFS_isDirectory(NormalizedPath.c_str()) ? BS_PackageManager::FT_DIRECTORY : BS_PackageManager::FT_FILE;
	}
	else
	{
		BS_LOG_ERRORLN("Cannot determine type of non-existant file \"%s\".", NormalizedPath.c_str());
		return 0;
	}
}

// -----------------------------------------------------------------------------

bool BS_PhysfsPackageManager::FileExists(const std::string & FileName)
{
	std::string NormalizedPath = NormalizePath(FileName, m_CurrentDirectory);
	return PHYSFS_exists(NormalizedPath.c_str()) != 0;
}

// -----------------------------------------------------------------------------
// Dateien suchen
// -----------------------------------------------------------------------------

class PhysfsFileSearch : public BS_PackageManager::FileSearch
{
public:
	// Path muss normalisiert sein.
	PhysfsFileSearch(BS_PackageManager & PackageManager, const vector<std::string> & FoundFiles) :
		m_PackageManager(PackageManager),
		m_FoundFiles(FoundFiles),
		m_FoundFilesIt(m_FoundFiles.begin())
	{
	}

	virtual std::string GetCurFileName()
	{
		return *m_FoundFilesIt;
	}

	virtual unsigned int GetCurFileType()
	{
		return m_PackageManager.GetFileType(*m_FoundFilesIt);
	}

	virtual unsigned int GetCurFileSize()
	{
		return m_PackageManager.GetFileSize(*m_FoundFilesIt);
	}

	virtual bool NextFile()
	{
		++m_FoundFilesIt;
		return m_FoundFilesIt != m_FoundFiles.end();
	}

	BS_PackageManager &					m_PackageManager;
	vector<std::string>					m_FoundFiles;
	vector<std::string>::const_iterator	m_FoundFilesIt;
};

// -----------------------------------------------------------------------------

BS_PackageManager::FileSearch * BS_PhysfsPackageManager::CreateSearch(const std::string& Filter, const std::string& Path, unsigned int TypeFilter)
{
	std::string NormalizedPath = NormalizePath(Path, m_CurrentDirectory);

	// Nach Wildcards gefilterte Ergebnisliste erstellen.
	PhysfsListHolder<char **> FilesPtr(PHYSFSEXT_enumerateFilesWildcard(NormalizedPath.c_str(), Filter.c_str(), 1));

	// Diese Liste muss nun wiederum nach den gew�nschten Dateitype gefiltert werden. Das Ergebnis wird in einem vector gespeichert, der dann
	// einem PhysfsFileSearch-Objekt �bergeben wird.
	vector<std::string> FoundFiles;
	for (char ** CurFilePtr = FilesPtr.Get(); *CurFilePtr != 0; ++CurFilePtr)
	{
		// Vollst�ndigen Pfad zur gefunden Datei konstruieren.
		std::string FullFilePath = NormalizedPath + std::string(1, PATH_SEPARATOR) + *CurFilePtr;

		// Feststellen, ob der Dateityp erw�nscht ist und nur dann den Dateinamen dem Ergebnisvektor hinzuf�gen.
		unsigned int FileType = GetFileType(FullFilePath);
		if (FileType & TypeFilter) FoundFiles.push_back(FullFilePath);
	}

	// Falls �berhaupt eine Datei gefunden wurde, wird ein FileSearch-Objekt zur�ckgegeben mit dem �ber die gefundenen Dateien iteriert werden kann.
	// Anderenfalls wird 0 zur�ckgegeben.
	if (FoundFiles.size())
	{
		return new PhysfsFileSearch(*this, FoundFiles);
	}
	else
	{
		return 0;
	}
}