File: Files.cpp

package info (click to toggle)
endless-sky 0.10.16-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 414,608 kB
  • sloc: cpp: 73,435; python: 893; xml: 666; sh: 271; makefile: 28
file content (500 lines) | stat: -rw-r--r-- 11,642 bytes parent folder | download
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
/* Files.cpp
Copyright (c) 2014 by Michael Zahniser

Endless Sky 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.

Endless Sky 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, see <https://www.gnu.org/licenses/>.
*/

#include "Files.h"

#include "Logger.h"
#include "ZipFile.h"

#include <SDL2/SDL.h>

#include <algorithm>
#include <fstream>
#include <iostream>
#include <map>
#include <mutex>
#include <sstream>
#include <stdexcept>

using namespace std;

namespace {
	filesystem::path resources;
	filesystem::path config;

	filesystem::path dataPath;
	filesystem::path imagePath;
	filesystem::path soundPath;
	filesystem::path savePath;
	filesystem::path userPluginPath;
	filesystem::path globalPluginPath;
	filesystem::path testPath;

	shared_ptr<iostream> errorLog;

	// Open the given folder in a separate window.
	void OpenFolder(const filesystem::path &path)
	{
		// TODO: Remove SDL version check after Ubuntu 20.04 reaches end of life
#if SDL_VERSION_ATLEAST(2, 0, 14)
		if(SDL_OpenURL(("file://" + path.string()).c_str()))
			Logger::LogError("Warning: SDL_OpenURL failed with \"" + string(SDL_GetError()) + "\"");
#elif defined(__linux__)
		// Some supported distributions do not have an up-to-date SDL.
		cout.flush();
		if(int result = WEXITSTATUS(system(("xdg-open file://" + path.string()).c_str())))
			Logger::LogError("Warning: xdg-open failed with error code " + to_string(result) + ".");
#else
#warning SDL 2.0.14 or higher is needed for opening folders!
		Logger::LogError("Warning: No handler found to open \"" + path + "\" in a new window.");
#endif
	}

	/// The open zip files per thread. Since ZLIB doesn't support multithreaded access on the same zip handle,
	/// each file is opened multiple times on demand.
	thread_local map<filesystem::path, shared_ptr<ZipFile>> OPEN_ZIP_FILES;

	shared_ptr<ZipFile> GetZipFile(const filesystem::path &filePath)
	{
		/// Check if this zip is already open on this thread.
		for(auto &[zipPath, file] : OPEN_ZIP_FILES)
			if(Files::IsParent(zipPath, filePath))
				return file;

		/// If not, open the zip file.
		filesystem::path zipPath = filePath;
		while(!exists(zipPath))
		{
			if(!zipPath.has_parent_path() || zipPath.parent_path() == zipPath)
				return {};
			zipPath = zipPath.parent_path();
		}
		if(zipPath.extension() == ".zip" && is_regular_file(zipPath))
		{
			/// Limit the number of open zip files to one per thread to avoid having too many files open.
			OPEN_ZIP_FILES.clear();
			return OPEN_ZIP_FILES.emplace(zipPath, make_shared<ZipFile>(zipPath)).first->second;
		}

		return {};
	}
}



void Files::Init(const char * const *argv)
{
	// Parse the command line arguments to see if the user has specified
	// different directories to use.
	for(const char * const *it = argv + 1; *it; ++it)
	{
		string arg = *it;
		if((arg == "-r" || arg == "--resources") && *++it)
			resources = *it;
		else if((arg == "-c" || arg == "--config") && *++it)
			config = *it;

	}

	if(resources.empty())
	{
		// Find the path to the resource directory. This will depend on the
		// operating system, and can be overridden by a command line argument.
		char *basePath = SDL_GetBasePath();
		if(!basePath)
			throw runtime_error("Unable to get path to resource directory!");
		resources = basePath;
		SDL_free(basePath);

		if(Exists(resources))
			resources = filesystem::canonical(resources);

#if defined __linux__ || defined __FreeBSD__ || defined __DragonFly__
		// Special case, for Linux: the resource files are not in the same place as
		// the executable, but are under the same prefix (/usr or /usr/local).
		// When used as an iterator, a trailing / will create an empty item at
		// the end, so parent paths do not include it.
		static const filesystem::path LOCAL_PATH = "/usr/local";
		static const filesystem::path STANDARD_PATH = "/usr";
		static const filesystem::path RESOURCE_PATH = "share/games/endless-sky/";

		if(IsParent(LOCAL_PATH, resources))
			resources = LOCAL_PATH / RESOURCE_PATH;
		else if(IsParent(STANDARD_PATH, resources))
			resources = STANDARD_PATH / RESOURCE_PATH;
#endif
	}
	// If the resources are not here, search in the directories containing this
	// one. This allows, for example, a Mac app that does not actually have the
	// resources embedded within it.
	while(!Exists(resources / "credits.txt"))
	{
		if(!resources.has_parent_path() || resources.parent_path() == resources)
			throw runtime_error("Unable to find the resource directories!");
		resources = resources.parent_path();
	}
	dataPath = resources / "data";
	imagePath = resources / "images";
	soundPath = resources / "sounds";
	globalPluginPath = resources / "plugins";

	if(config.empty())
	{
		// Create the directory for the saved games, preferences, etc., if necessary.
		char *str = SDL_GetPrefPath(nullptr, "endless-sky");
		if(!str)
			throw runtime_error("Unable to get path to config directory!");
		config = str;
		SDL_free(str);
	}

	if(!Exists(config))
		throw runtime_error("Unable to create config directory!");

	config = filesystem::canonical(config);

	savePath = config / "saves";
	CreateFolder(savePath);

	// Create the "plugins" directory if it does not yet exist, so that it is
	// clear to the user where plugins should go.
	userPluginPath = config / "plugins";
	CreateFolder(userPluginPath);

	// Check that all the directories exist.
	if(!Exists(dataPath) || !Exists(imagePath) || !Exists(soundPath))
		throw runtime_error("Unable to find the resource directories!");
	if(!Exists(savePath))
		throw runtime_error("Unable to create save directory!");
	if(!Exists(userPluginPath))
		throw runtime_error("Unable to create plugins directory!");
}



const filesystem::path &Files::Resources()
{
	return resources;
}



const filesystem::path &Files::Config()
{
	return config;
}



const filesystem::path &Files::Data()
{
	return dataPath;
}



const filesystem::path &Files::Images()
{
	return imagePath;
}



const filesystem::path &Files::Sounds()
{
	return soundPath;
}



const filesystem::path &Files::Saves()
{
	return savePath;
}



const filesystem::path &Files::UserPlugins()
{
	return userPluginPath;
}



const filesystem::path &Files::GlobalPlugins()
{
	return globalPluginPath;
}



const filesystem::path &Files::Tests()
{
	return testPath;
}



vector<filesystem::path> Files::List(const filesystem::path &directory)
{
	vector<filesystem::path> list;

	if(!Exists(directory) || !is_directory(directory))
	{
		// Check if the requested file is in a known zip.
		shared_ptr<ZipFile> zip = GetZipFile(directory);
		if(zip)
		{
			list = zip->ListFiles(directory, false, false);
			sort(list.begin(), list.end());
		}
		return list;
	}


	for(const auto &entry : filesystem::directory_iterator(directory))
		if(entry.is_regular_file())
			list.emplace_back(entry);

	sort(list.begin(), list.end());

	return list;
}



// Get a list of any directories in the given directory.
vector<filesystem::path> Files::ListDirectories(const filesystem::path &directory)
{
	vector<filesystem::path> list;

	if(!Exists(directory) || !is_directory(directory))
	{
		// Check if the requested file is in a known zip.
		shared_ptr<ZipFile> zip = GetZipFile(directory);
		if(zip)
		{
			list = zip->ListFiles(directory, false, true);
			sort(list.begin(), list.end());
		}
		return list;
	}

	for(const auto &entry : filesystem::directory_iterator(directory))
		if(entry.is_directory())
			list.emplace_back(entry);

	sort(list.begin(), list.end());
	return list;
}



vector<filesystem::path> Files::RecursiveList(const filesystem::path &directory)
{
	vector<filesystem::path> list;
	if(!Exists(directory) || !is_directory(directory))
	{
		// Check if the requested file is in a known zip.
		shared_ptr<ZipFile> zip = GetZipFile(directory);
		if(zip)
		{
			list = zip->ListFiles(directory, true, false);
			sort(list.begin(), list.end());
		}
		return list;
	}

	for(const auto &entry : filesystem::recursive_directory_iterator(directory))
		if(entry.is_regular_file())
			list.emplace_back(entry);

	sort(list.begin(), list.end());
	return list;
}



bool Files::Exists(const filesystem::path &filePath)
{
	if(exists(filePath))
		return true;

	shared_ptr<ZipFile> zip = GetZipFile(filePath);
	if(zip)
		return zip->Exists(filePath);
	return false;
}



filesystem::file_time_type Files::Timestamp(const filesystem::path &filePath)
{
	return last_write_time(filePath);
}



bool Files::Copy(const filesystem::path &from, const filesystem::path &to)
{
#ifdef _WIN32
	// Due to a mingw bug, the overwrite_existing flag is not respected on Windows.
	// TODO: remove once it is fixed.
	if(Exists(to))
		Delete(to);
#endif
	try {
		copy(from, to, filesystem::copy_options::overwrite_existing);
	}
	catch(...)
	{
		return false;
	}
	return true;
}



void Files::Move(const filesystem::path &from, const filesystem::path &to)
{
	rename(from, to);
}



void Files::Delete(const filesystem::path &filePath)
{
	remove_all(filePath);
}



// Get the filename from a path.
string Files::Name(const filesystem::path &path)
{
	return path.filename().string();
}



bool Files::IsParent(const filesystem::path &parent, const filesystem::path &child)
{
	if(distance(child.begin(), child.end()) < distance(parent.begin(), parent.end()))
		return false;
	return equal(parent.begin(), parent.end(), child.begin());
}



shared_ptr<iostream> Files::Open(const filesystem::path &path, bool write)
{
	if(!exists(path) && !write)
	{
		// Writing to a zip is not supported.
		shared_ptr<ZipFile> zip = GetZipFile(path);
		if(zip)
			return shared_ptr<iostream>(new stringstream(zip->ReadFile(path), ios::in | ios::binary));
		return {};
	}

	if(write)
#ifdef _WIN32
		return shared_ptr<iostream>{new fstream{path, ios::out}};
#else
		return shared_ptr<iostream>{new fstream{path, ios::out | ios::binary}};
#endif
	return shared_ptr<iostream>{new fstream{path, ios::in | ios::binary}};
}



string Files::Read(const filesystem::path &path)
{
	return Read(Open(path));
}



string Files::Read(shared_ptr<iostream> file)
{
	if(!file)
		return "";
	return string{istreambuf_iterator<char>{*file}, {}};
}



void Files::Write(const filesystem::path &path, const string &data)
{
	Write(Open(path, true), data);
}



void Files::Write(shared_ptr<iostream> file, const string &data)
{
	if(!file)
		return;
	*file << data;
	file->flush();
}



void Files::CreateFolder(const filesystem::path &path)
{
	if(Exists(path))
		return;

	if(filesystem::create_directory(path))
		filesystem::permissions(path, filesystem::perms(filesystem::perms::owner_all));
	else
		throw runtime_error("Error creating directory!");
}



// Open this user's plugins directory in their native file explorer.
void Files::OpenUserPluginFolder()
{
	OpenFolder(userPluginPath);
}



// Open this user's save file directory in their native file explorer.
void Files::OpenUserSavesFolder()
{
	OpenFolder(savePath);
}



void Files::LogErrorToFile(const string &message)
{
	if(!errorLog)
	{
		errorLog = Open(config / "errors.txt", true);
		if(!errorLog)
		{
			cerr << "Unable to create \"errors.txt\" " << (config.empty()
				? "in current directory" : "in \"" + config.string() + "\"") << endl;
			return;
		}
	}

	Write(errorLog, message);
	*errorLog << endl;
}