forked from organicmaps/organicmaps
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplatform.cpp
418 lines (362 loc) · 10.7 KB
/
platform.cpp
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
#include "platform/platform.hpp"
#include "coding/internal/file_data.hpp"
#include "base/file_name_utils.hpp"
#include "base/logging.hpp"
#include "base/random.hpp"
#include "base/string_utils.hpp"
#include <algorithm>
#include <thread>
#include "private.h"
#include <cerrno>
namespace
{
std::string RandomString(size_t length)
{
/// @todo Used for temp file name, so lower-upper case is strange here, no?
static std::string_view constexpr kCharset =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
base::UniformRandom<size_t> rand(0, kCharset.size() - 1);
std::string str(length, 0);
std::generate_n(str.begin(), length, [&rand]() { return kCharset[rand()]; });
return str;
}
bool IsSpecialDirName(std::string const & dirName)
{
return dirName == "." || dirName == "..";
}
bool GetFileTypeChecked(std::string const & path, Platform::EFileType & type)
{
Platform::EError const ret = Platform::GetFileType(path, type);
if (ret != Platform::ERR_OK)
{
LOG(LERROR, ("Can't determine file type for", path, ":", ret));
return false;
}
return true;
}
} // namespace
// static
Platform::EError Platform::ErrnoToError()
{
switch (errno)
{
case ENOENT:
return ERR_FILE_DOES_NOT_EXIST;
case EACCES:
return ERR_ACCESS_FAILED;
case ENOTEMPTY:
return ERR_DIRECTORY_NOT_EMPTY;
case EEXIST:
return ERR_FILE_ALREADY_EXISTS;
case ENAMETOOLONG:
return ERR_NAME_TOO_LONG;
case ENOTDIR:
return ERR_NOT_A_DIRECTORY;
case ELOOP:
return ERR_SYMLINK_LOOP;
case EIO:
return ERR_IO_ERROR;
default:
return ERR_UNKNOWN;
}
}
// static
bool Platform::RmDirRecursively(std::string const & dirName)
{
if (dirName.empty() || IsSpecialDirName(dirName))
return false;
bool res = true;
FilesList allFiles;
GetFilesByRegExp(dirName, ".*", allFiles);
for (std::string const & file : allFiles)
{
std::string const path = base::JoinPath(dirName, file);
EFileType type;
if (GetFileType(path, type) != ERR_OK)
continue;
if (type == EFileType::Directory)
{
if (!IsSpecialDirName(file) && !RmDirRecursively(path))
res = false;
}
else
{
if (!base::DeleteFileX(path))
res = false;
}
}
if (RmDir(dirName) != ERR_OK)
res = false;
return res;
}
void Platform::SetSettingsDir(std::string const & path)
{
m_settingsDir = base::AddSlashIfNeeded(path);
}
std::string Platform::SettingsPathForFile(std::string const & file) const
{
return base::JoinPath(SettingsDir(), file);
}
std::string Platform::WritablePathForFile(std::string const & file) const
{
return base::JoinPath(WritableDir(), file);
}
std::string Platform::ReadPathForFile(std::string const & file, std::string searchScope) const
{
if (searchScope.empty())
searchScope = "wrf";
std::string fullPath;
for (size_t i = 0; i < searchScope.size(); ++i)
{
switch (searchScope[i])
{
case 'w':
ASSERT(!m_writableDir.empty(), ());
fullPath = base::JoinPath(m_writableDir, file);
break;
case 'r':
ASSERT(!m_resourcesDir.empty(), ());
fullPath = base::JoinPath(m_resourcesDir, file);
break;
case 's':
ASSERT(!m_settingsDir.empty(), ());
fullPath = base::JoinPath(m_settingsDir, file);
break;
case 'f':
fullPath = file;
break;
default :
CHECK(false, ("Unsupported searchScope:", searchScope));
break;
}
if (IsFileExistsByFullPath(fullPath))
return fullPath;
}
MYTHROW(FileAbsentException, ("File", file, "doesn't exist in the scope", searchScope,
"\nw: ", m_writableDir, "\nr: ", m_resourcesDir, "\ns: ", m_settingsDir));
}
std::string Platform::MetaServerUrl() const
{
return METASERVER_URL;
}
std::string Platform::DefaultUrlsJSON() const
{
return DEFAULT_URLS_JSON;
}
bool Platform::RemoveFileIfExists(std::string const & filePath)
{
return IsFileExistsByFullPath(filePath) ? base::DeleteFileX(filePath) : true;
}
std::string Platform::TmpPathForFile() const
{
size_t constexpr kNameLen = 32;
return base::JoinPath(TmpDir(), RandomString(kNameLen));
}
std::string Platform::TmpPathForFile(std::string const & prefix, std::string const & suffix) const
{
size_t constexpr kRandomLen = 8;
return base::JoinPath(TmpDir(), prefix + RandomString(kRandomLen) + suffix);
}
void Platform::GetFontNames(FilesList & res) const
{
ASSERT(res.empty(), ());
/// @todo Actually, this list should present once in all our code.
char constexpr const * arrDef[] = {
"00_NotoNaskhArabic-Regular.ttf",
"00_NotoSansBengali-Regular.ttf",
"00_NotoSansHebrew-Regular.ttf",
"00_NotoSansMalayalam-Regular.ttf",
"00_NotoSansThai-Regular.ttf",
"00_NotoSerifDevanagari-Regular.ttf",
"01_dejavusans.ttf",
"02_droidsans-fallback.ttf",
"03_jomolhari-id-a3d.ttf",
"04_padauk.ttf",
"05_khmeros.ttf",
"06_code2000.ttf",
"07_roboto_medium.ttf",
};
res.insert(res.end(), arrDef, arrDef + ARRAY_SIZE(arrDef));
GetSystemFontNames(res);
LOG(LINFO, ("Available font files:", (res)));
}
void Platform::GetFilesByExt(std::string const & directory, std::string_view ext, FilesList & outFiles)
{
// Transform extension mask to regexp (.mwm -> \.mwm$)
ASSERT ( !ext.empty(), () );
ASSERT_EQUAL ( ext[0], '.' , () );
std::string regexp = "\\";
GetFilesByRegExp(directory, regexp.append(ext).append("$"), outFiles);
}
// static
void Platform::GetFilesByType(std::string const & directory, unsigned typeMask,
TFilesWithType & outFiles)
{
FilesList allFiles;
GetFilesByRegExp(directory, ".*", allFiles);
for (auto const & file : allFiles)
{
EFileType type;
if (GetFileType(base::JoinPath(directory, file), type) != ERR_OK)
continue;
if (typeMask & type)
outFiles.emplace_back(file, type);
}
}
// static
bool Platform::IsDirectory(std::string const & path)
{
EFileType fileType;
if (GetFileType(path, fileType) != ERR_OK)
return false;
return fileType == EFileType::Directory;
}
// static
void Platform::GetFilesRecursively(std::string const & directory, FilesList & filesList)
{
TFilesWithType files;
GetFilesByType(directory, EFileType::Regular, files);
for (auto const & p : files)
{
auto const & file = p.first;
CHECK_EQUAL(p.second, EFileType::Regular, ("dir:", directory, "file:", file));
filesList.push_back(base::JoinPath(directory, file));
}
TFilesWithType subdirs;
GetFilesByType(directory, EFileType::Directory, subdirs);
for (auto const & p : subdirs)
{
auto const & subdir = p.first;
CHECK_EQUAL(p.second, EFileType::Directory, ("dir:", directory, "subdir:", subdir));
if (subdir == "." || subdir == "..")
continue;
GetFilesRecursively(base::JoinPath(directory, subdir), filesList);
}
}
void Platform::SetWritableDirForTests(std::string const & path)
{
m_writableDir = base::AddSlashIfNeeded(path);
}
void Platform::SetResourceDir(std::string const & path)
{
m_resourcesDir = base::AddSlashIfNeeded(path);
}
// static
bool Platform::MkDirChecked(std::string const & dirName)
{
switch (EError const ret = MkDir(dirName))
{
case ERR_OK: return true;
case ERR_FILE_ALREADY_EXISTS:
{
EFileType type;
if (!GetFileTypeChecked(dirName, type))
return false;
if (type != Directory)
{
LOG(LERROR, (dirName, "exists, but not a dirName:", type));
return false;
}
return true;
}
default: LOG(LERROR, (dirName, "can't be created:", ret)); return false;
}
}
// static
bool Platform::MkDirRecursively(std::string const & dirName)
{
CHECK(!dirName.empty(), ());
std::string::value_type const sep[] = { base::GetNativeSeparator(), 0};
std::string path = dirName.starts_with(sep[0]) ? sep : ".";
for (auto const & t : strings::Tokenize(dirName, sep))
{
path = base::JoinPath(path, std::string{t});
if (!IsFileExistsByFullPath(path))
{
switch (MkDir(path))
{
case ERR_OK: break;
case ERR_FILE_ALREADY_EXISTS:
{
if (!IsDirectory(path))
return false;
break;
}
default: return false;
}
}
}
return true;
}
unsigned Platform::CpuCores()
{
unsigned const cores = std::thread::hardware_concurrency();
return cores > 0 ? cores : 1;
}
void Platform::ShutdownThreads()
{
ASSERT(m_networkThread && m_fileThread && m_backgroundThread, ());
ASSERT(!m_networkThread->IsShutDown(), ());
ASSERT(!m_fileThread->IsShutDown(), ());
ASSERT(!m_backgroundThread->IsShutDown(), ());
m_batteryTracker.UnsubscribeAll();
m_networkThread->ShutdownAndJoin();
m_fileThread->ShutdownAndJoin();
m_backgroundThread->ShutdownAndJoin();
}
void Platform::RunThreads()
{
ASSERT(!m_networkThread || m_networkThread->IsShutDown(), ());
ASSERT(!m_fileThread || m_fileThread->IsShutDown(), ());
ASSERT(!m_backgroundThread || m_backgroundThread->IsShutDown(), ());
m_networkThread = std::make_unique<base::DelayedThreadPool>();
m_fileThread = std::make_unique<base::DelayedThreadPool>();
m_backgroundThread = std::make_unique<base::DelayedThreadPool>();
}
void Platform::SetGuiThread(std::unique_ptr<base::TaskLoop> guiThread)
{
m_guiThread = std::move(guiThread);
}
void Platform::CancelTask(Thread thread, base::TaskLoop::TaskId id)
{
ASSERT(m_networkThread && m_fileThread && m_backgroundThread, ());
switch (thread)
{
case Thread::File: m_fileThread->Cancel(id); return;
case Thread::Network: m_networkThread->Cancel(id); return;
case Thread::Gui: CHECK(false, ("Task cancelling for gui thread is not supported yet")); return;
case Thread::Background: m_backgroundThread->Cancel(id); return;
}
}
std::string DebugPrint(Platform::EError err)
{
switch (err)
{
case Platform::ERR_OK: return "Ok";
case Platform::ERR_FILE_DOES_NOT_EXIST: return "File does not exist.";
case Platform::ERR_ACCESS_FAILED: return "Access failed.";
case Platform::ERR_DIRECTORY_NOT_EMPTY: return "Directory not empty.";
case Platform::ERR_FILE_ALREADY_EXISTS: return "File already exists.";
case Platform::ERR_NAME_TOO_LONG:
return "The length of a component of path exceeds {NAME_MAX} characters.";
case Platform::ERR_NOT_A_DIRECTORY:
return "A component of the path prefix of Path is not a directory.";
case Platform::ERR_SYMLINK_LOOP:
return "Too many symbolic links were encountered in translating path.";
case Platform::ERR_IO_ERROR: return "An I/O error occurred.";
case Platform::ERR_UNKNOWN: return "Unknown";
}
UNREACHABLE();
}
std::string DebugPrint(Platform::ChargingStatus status)
{
switch (status)
{
case Platform::ChargingStatus::Unknown: return "Unknown";
case Platform::ChargingStatus::Plugged: return "Plugged";
case Platform::ChargingStatus::Unplugged: return "Unplugged";
}
UNREACHABLE();
}