Debian Codegraph @

src/engine/system.cpp

raw symbols SCIP
1 /***************************************************************************
2 * fheroes2: https://github.com/ihhub/fheroes2 *
3 * Copyright (C) 2019 - 2025 *
4 * *
5 * Free Heroes2 Engine: http://sourceforge.net/projects/fheroes2 *
6 * Copyright (C) 2009 by Andrey Afletdinov <[email protected]> *
7 * *
8 * This program is free software; you can redistribute it and/or modify *
9 * it under the terms of the GNU General Public License as published by *
10 * the Free Software Foundation; either version 2 of the License, or *
11 * (at your option) any later version. *
12 * *
13 * This program is distributed in the hope that it will be useful, *
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16 * GNU General Public License for more details. *
17 * *
18 * You should have received a copy of the GNU General Public License *
19 * along with this program; if not, write to the *
20 * Free Software Foundation, Inc., *
21 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
22 ***************************************************************************/
23
24 #include "system.h"
25
26 #include <cassert>
27 #include <cstdlib>
28 #include <functional>
29 #include <map>
30 #include <memory>
31 #include <system_error>
32 #include <utility>
33
34 #if defined( _WIN32 )
35 #include <tuple>
36
37 #include "tools.h"
38
39 #define WIN32_LEAN_AND_MEAN
40 #include <windows.h>
41 #elif defined( TARGET_PS_VITA )
42 #include <algorithm>
43 #endif
44
45 #if !defined( _WIN32 ) && !defined( ANDROID ) && !defined( TARGET_PS_VITA )
46 #include <dirent.h>
47 #include <strings.h>
48 #endif
49
50 // Managing compiler warnings for SDL headers
51 #if defined( __GNUC__ )
52 #pragma GCC diagnostic push
53
54 #pragma GCC diagnostic ignored "-Wdouble-promotion"
55 #pragma GCC diagnostic ignored "-Wold-style-cast"
56 #pragma GCC diagnostic ignored "-Wswitch-default"
57 #endif
58
59 #include <SDL_touch.h>
60 #include <SDL_version.h>
61
62 #if defined( ANDROID )
63 #include <SDL_error.h>
64 #include <SDL_system.h>
65 #endif
66
67 #if SDL_VERSION_ATLEAST( 2, 0, 1 ) && ( !defined( __linux__ ) || defined( ANDROID ) )
68 #include <SDL_filesystem.h>
69 #include <SDL_stdinc.h>
70 #endif
71
72 // Managing compiler warnings for SDL headers
73 #if defined( __GNUC__ )
74 #pragma GCC diagnostic pop
75 #endif
76
77 namespace
78 {
79 #if !defined( __linux__ ) || defined( ANDROID )
80 std::string GetHomeDirectory( const std::string_view appName )
81 {
82 #if defined( TARGET_PS_VITA )
83 return System::concatPath( "ux0:data", appName );
84 #elif defined( TARGET_NINTENDO_SWITCH )
85 return System::concatPath( "/switch", appName );
86 #elif defined( ANDROID )
87 (void)appName;
88
89 if ( const char * storagePath = SDL_AndroidGetExternalStoragePath(); storagePath != nullptr ) {
90 return storagePath;
91 }
92
93 return {};
94 #endif
95 {
96 const char * homeEnvPath = getenv( "HOME" );
97
98 #if defined( MACOS_APP_BUNDLE ) || defined( __IPHONEOS__ )
99 if ( homeEnvPath != nullptr ) {
100 return System::concatPath( System::concatPath( homeEnvPath, "Library/Preferences" ), appName );
101 }
102
103 return {};
104 #endif
105
106 if ( homeEnvPath != nullptr ) {
107 return System::concatPath( homeEnvPath, std::string( "." ).append( appName ) );
108 }
109 }
110
111 if ( const char * dataEnvPath = getenv( "APPDATA" ); dataEnvPath != nullptr ) {
112 return System::concatPath( dataEnvPath, appName );
113 }
114
115 #if SDL_VERSION_ATLEAST( 2, 0, 1 )
116 if ( const std::unique_ptr<char, void ( * )( void * )> path( SDL_GetPrefPath( "", System::encLocalToUTF8( std::string{ appName } ).c_str() ), SDL_free ); path ) {
117 return System::encUTF8ToLocal( path.get() );
118 }
119 #endif
120
121 return {};
122 }
123 #endif
124
125 bool globMatch( const std::string_view string, const std::string_view wildcard )
126 {
127 size_t stringIdx = 0;
128 size_t wildcardIdx = 0;
129
130 size_t fallbackStringIdx = std::string_view::npos;
131 size_t fallbackWildcardIdx = std::string_view::npos;
132
133 while ( stringIdx < string.length() ) {
134 const bool isWildcardNotEnded = ( wildcardIdx < wildcard.length() );
135
136 if ( isWildcardNotEnded && wildcard[wildcardIdx] == '*' ) {
137 ++wildcardIdx;
138
139 fallbackStringIdx = stringIdx;
140 fallbackWildcardIdx = wildcardIdx;
141 }
142 else if ( isWildcardNotEnded && ( wildcard[wildcardIdx] == '?' || wildcard[wildcardIdx] == string[stringIdx] ) ) {
143 ++stringIdx;
144 ++wildcardIdx;
145 }
146 else {
147 if ( fallbackWildcardIdx == std::string_view::npos ) {
148 return false;
149 }
150
151 assert( fallbackStringIdx != std::string_view::npos );
152
153 ++fallbackStringIdx;
154
155 stringIdx = fallbackStringIdx;
156 wildcardIdx = fallbackWildcardIdx;
157 }
158 }
159
160 for ( ; wildcardIdx < wildcard.length(); ++wildcardIdx ) {
161 if ( wildcard[wildcardIdx] != '*' ) {
162 break;
163 }
164 }
165
166 return wildcardIdx == wildcard.length();
167 }
168
169 #if defined( _WIN32 )
170 enum class EncodingConversionDirection
171 {
172 ACPToUTF8,
173 UTF8ToACP
174 };
175
176 std::string convertBetweenACPAndUTF8( const std::string_view str, const EncodingConversionDirection dir )
177 {
178 if ( str.empty() ) {
179 return {};
180 }
181
182 thread_local std::map<EncodingConversionDirection, std::map<std::string, std::string, std::less<>>> resultsCache;
183
184 if ( const auto dirIter = resultsCache.find( dir ); dirIter != resultsCache.end() ) {
185 const auto & strMap = dirIter->second;
186
187 if ( const auto strIter = strMap.find( str ); strIter != strMap.end() ) {
188 return strIter->second;
189 }
190 }
191
192 // In case of any issues, the original string will be returned, so let's put it to the cache right away
193 const auto [resultIter, inserted] = resultsCache[dir].try_emplace( std::string{ str }, str );
194 if ( !inserted ) {
195 assert( 0 );
196 }
197
198 const auto strLen = fheroes2::checkedCast<int>( str.size() );
199 if ( !strLen ) {
200 // The size of this string does not fit into an int, so this string cannot be safely converted
201 #ifdef WITH_DEBUG
202 assert( 0 );
203 #endif
204 return std::string{ str };
205 }
206
207 const auto [mbCodePage, mbFlags, wcCodePage, wcFlags] = [dir]() -> std::tuple<UINT, DWORD, UINT, DWORD> {
208 switch ( dir ) {
209 case EncodingConversionDirection::ACPToUTF8:
210 return { CP_ACP, MB_ERR_INVALID_CHARS, CP_UTF8, WC_ERR_INVALID_CHARS };
211 case EncodingConversionDirection::UTF8ToACP:
212 return { CP_UTF8, MB_ERR_INVALID_CHARS, CP_ACP, WC_NO_BEST_FIT_CHARS };
213 default:
214 assert( 0 );
215 break;
216 }
217
218 return { CP_ACP, MB_ERR_INVALID_CHARS, CP_ACP, WC_NO_BEST_FIT_CHARS };
219 }();
220
221 const int wcLen = MultiByteToWideChar( mbCodePage, mbFlags, str.data(), *strLen, nullptr, 0 );
222 if ( wcLen <= 0 ) {
223 #ifdef WITH_DEBUG
224 assert( 0 );
225 #endif
226 return std::string{ str };
227 }
228
229 // The contents of this buffer will not be zero-terminated
230 const std::unique_ptr<wchar_t[]> wcStr( new wchar_t[wcLen] );
231
232 if ( MultiByteToWideChar( mbCodePage, mbFlags, str.data(), *strLen, wcStr.get(), wcLen ) != wcLen ) {
233 #ifdef WITH_DEBUG
234 assert( 0 );
235 #endif
236 return std::string{ str };
237 }
238
239 const int mbLen = WideCharToMultiByte( wcCodePage, wcFlags, wcStr.get(), wcLen, nullptr, 0, nullptr, nullptr );
240 if ( mbLen <= 0 ) {
241 #ifdef WITH_DEBUG
242 assert( 0 );
243 #endif
244 return std::string{ str };
245 }
246
247 // The contents of this buffer will not be zero-terminated
248 const std::unique_ptr<char[]> mbStr( new char[mbLen] );
249
250 if ( WideCharToMultiByte( wcCodePage, wcFlags, wcStr.get(), wcLen, mbStr.get(), mbLen, nullptr, nullptr ) != mbLen ) {
251 #ifdef WITH_DEBUG
252 assert( 0 );
253 #endif
254 return std::string{ str };
255 }
256
257 // The contents of this buffer is not zero-terminated
258 std::string result( mbStr.get(), mbLen );
259
260 // Put the final result to the cache
261 resultIter->second = result;
262
263 return result;
264 }
265 #endif
266 }
267
268 bool System::isHandheldDevice()
269 {
270 #if defined( ANDROID ) || defined( __IPHONEOS__ )
271 return true;
272 #else
273 return false;
274 #endif
275 }
276
277 bool System::isTouchInputAvailable()
278 {
279 return SDL_GetNumTouchDevices() > 0;
280 }
281
282 bool System::isVirtualKeyboardSupported()
283 {
284 #if defined( ANDROID ) || defined( TARGET_PS_VITA ) || defined( TARGET_NINTENDO_SWITCH ) || defined( __IPHONEOS__ )
285 return true;
286 #else
287 return false;
288 #endif
289 }
290
291 bool System::isShellLevelGlobbingSupported()
292 {
293 #if defined( _WIN32 )
294 return false;
295 #else
296 return true;
297 #endif
298 }
299
300 bool System::MakeDirectory( const std::string_view path )
301 {
302 std::error_code ec;
303
304 // Using the non-throwing overload
305 return std::filesystem::create_directories( path, ec );
306 }
307
308 bool System::Unlink( const std::string_view path )
309 {
310 std::error_code ec;
311
312 // Using the non-throwing overload
313 return std::filesystem::remove( path, ec );
314 }
315
316 std::string System::concatPath( const std::string_view left, const std::string_view right )
317 {
318 return fsPathToString( std::filesystem::path{ left }.append( right ) );
319 }
320
321 void System::appendOSSpecificDirectories( std::vector<std::string> & directories )
322 {
323 #if defined( TARGET_PS_VITA )
324 const char * path = "ux0:app/FHOMM0002";
325 if ( std::find( directories.begin(), directories.end(), path ) == directories.end() ) {
326 directories.emplace_back( path );
327 }
328 #else
329 (void)directories;
330 #endif
331 }
332
333 std::string System::GetConfigDirectory( const std::string_view appName )
334 {
335 // Location of the app config directory, in theory, should not change while the app is running and can be cached
336 thread_local std::map<std::string, std::string, std::less<>> resultsCache;
337
338 if ( const auto iter = resultsCache.find( appName ); iter != resultsCache.end() ) {
339 return iter->second;
340 }
341
342 std::string result = [&appName]() -> std::string {
343 #if defined( __linux__ ) && !defined( ANDROID )
344 if ( const char * configEnv = getenv( "XDG_CONFIG_HOME" ); configEnv != nullptr ) {
345 return concatPath( configEnv, appName );
346 }
347
348 if ( const char * homeEnv = getenv( "HOME" ); homeEnv != nullptr ) {
349 return concatPath( concatPath( homeEnv, ".config" ), appName );
350 }
351
352 return {};
353 #else
354 return GetHomeDirectory( appName );
355 #endif
356 }();
357
358 if ( const auto [dummy, inserted] = resultsCache.try_emplace( std::string{ appName }, result ); !inserted ) {
359 assert( 0 );
360 }
361
362 return result;
363 }
364
365 std::string System::GetDataDirectory( const std::string_view appName )
366 {
367 // Location of the app data directory, in theory, should not change while the app is running and can be cached
368 thread_local std::map<std::string, std::string, std::less<>> resultsCache;
369
370 if ( const auto iter = resultsCache.find( appName ); iter != resultsCache.end() ) {
371 return iter->second;
372 }
373
374 std::string result = [&appName]() -> std::string {
375 #if defined( __linux__ ) && !defined( ANDROID )
376 if ( const char * dataEnv = getenv( "XDG_DATA_HOME" ); dataEnv != nullptr ) {
377 return concatPath( dataEnv, appName );
378 }
379
380 if ( const char * homeEnv = getenv( "HOME" ); homeEnv != nullptr ) {
381 return concatPath( concatPath( homeEnv, ".local/share" ), appName );
382 }
383
384 return {};
385 #elif defined( MACOS_APP_BUNDLE ) || defined( __IPHONEOS__ )
386 if ( const char * homeEnv = getenv( "HOME" ); homeEnv != nullptr ) {
387 return concatPath( concatPath( homeEnv, "Library/Application Support" ), appName );
388 }
389
390 return {};
391 #else
392 return GetHomeDirectory( appName );
393 #endif
394 }();
395
396 if ( const auto [dummy, inserted] = resultsCache.try_emplace( std::string{ appName }, result ); !inserted ) {
397 assert( 0 );
398 }
399
400 return result;
401 }
402
403 std::string System::GetParentDirectory( std::string_view path )
404 {
405 return fsPathToString( std::filesystem::path{ path }.parent_path() );
406 }
407
408 std::string System::GetFileName( std::string_view path )
409 {
410 return fsPathToString( std::filesystem::path{ path }.filename() );
411 }
412
413 std::string System::GetStem( const std::string_view path )
414 {
415 return fsPathToString( std::filesystem::path{ path }.stem() );
416 }
417
418 bool System::IsFile( const std::string_view path )
419 {
420 if ( path.empty() ) {
421 // An empty path cannot be a file.
422 return false;
423 }
424
425 std::string correctedPath;
426 if ( !GetCaseInsensitivePath( path, correctedPath ) ) {
427 return false;
428 }
429
430 std::error_code ec;
431
432 // Using the non-throwing overload
433 return std::filesystem::is_regular_file( correctedPath, ec );
434 }
435
436 bool System::IsDirectory( const std::string_view path )
437 {
438 if ( path.empty() ) {
439 // An empty path cannot be a directory.
440 return false;
441 }
442
443 std::string correctedPath;
444 if ( !GetCaseInsensitivePath( path, correctedPath ) ) {
445 return false;
446 }
447
448 std::error_code ec;
449
450 // Using the non-throwing overload
451 return std::filesystem::is_directory( correctedPath, ec );
452 }
453
454 bool System::GetCaseInsensitivePath( const std::string_view path, std::string & correctedPath )
455 {
456 #if !defined( _WIN32 ) && !defined( ANDROID ) && !defined( TARGET_PS_VITA ) && !defined( __IPHONEOS__ )
457 // The following code is based on https://github.com/OneSadCookie/fcaseopen and assumes the use of POSIX IEEE Std 1003.1-2001 pathnames
458 correctedPath.clear();
459
460 if ( path.empty() ) {
461 return false;
462 }
463
464 constexpr char dirSep{ '/' };
465
466 std::unique_ptr<DIR, int ( * )( DIR * )> dir( path.front() == dirSep ? opendir( "/" ) : opendir( "." ), closedir );
467
468 for ( const std::filesystem::path & pathItem : std::filesystem::path{ path } ) {
469 if ( !dir ) {
470 return false;
471 }
472
473 if ( !correctedPath.empty() && correctedPath.back() != dirSep ) {
474 correctedPath += dirSep;
475 }
476
477 // Avoid directory traversal and try to probe directory name directly.
478 // Speeds up file lookup when intermediate directories have a lot of
479 // files. Example is NixOS where file layout is:
480 // /nix/store/...-fheroes2-${ver}/share/fheroes2/files/lang
481 // /nix/store/...-other-package-1/...
482 // /nix/store/...-other-package-2/...
483 // It's not uncommon for /nix/store to have tens of thousands files.
484 // GetCaseInsensitivePath() calls become very expensive on such systems.
485 //
486 // The idea is to try to open the current path item as a directory and
487 // avoid directory traversal altogether. Otherwise fall back to linear
488 // case-insensitive search.
489 {
490 std::string tmpPath = correctedPath + pathItem.string();
491
492 if ( std::unique_ptr<DIR, int ( * )( DIR * )> tmpDir( opendir( tmpPath.c_str() ), closedir ); tmpDir ) {
493 correctedPath = std::move( tmpPath );
494 dir = std::move( tmpDir );
495
496 continue;
497 }
498 }
499
500 const struct dirent * entry = readdir( dir.get() );
501 while ( entry != nullptr ) {
502 if ( strcasecmp( pathItem.c_str(), entry->d_name ) == 0 ) {
503 correctedPath += entry->d_name;
504
505 dir.reset( opendir( correctedPath.c_str() ) );
506
507 break;
508 }
509
510 entry = readdir( dir.get() );
511 }
512
513 if ( entry == nullptr ) {
514 return false;
515 }
516 }
517 #else
518 correctedPath = path;
519 #endif
520
521 return !correctedPath.empty();
522 }
523
524 void System::globFiles( const std::string_view glob, std::vector<std::string> & fileNames )
525 {
526 const std::filesystem::path globPath( glob );
527
528 std::filesystem::path dirPath = globPath.parent_path();
529 if ( dirPath.empty() ) {
530 dirPath = std::filesystem::path{ "." };
531 }
532
533 std::error_code ec;
534
535 // Using the non-throwing overload
536 if ( !std::filesystem::is_directory( dirPath, ec ) ) {
537 fileNames.emplace_back( glob );
538 return;
539 }
540
541 const std::string pattern = globPath.filename().string();
542
543 if ( pattern.find( '*' ) == std::string_view::npos && pattern.find( '?' ) == std::string_view::npos ) {
544 fileNames.emplace_back( glob );
545 return;
546 }
547
548 bool isNoMatches = true;
549
550 // Using the non-throwing overload
551 for ( const std::filesystem::directory_entry & entry : std::filesystem::directory_iterator( dirPath, ec ) ) {
552 const std::filesystem::path & entryPath = entry.path();
553
554 if ( !globMatch( fsPathToString( entryPath.filename() ), pattern ) ) {
555 continue;
556 }
557
558 fileNames.emplace_back( fsPathToString( entryPath ) );
559
560 isNoMatches = false;
561 }
562
563 if ( isNoMatches ) {
564 fileNames.emplace_back( glob );
565 }
566 }
567
568 std::string System::encLocalToUTF8( const std::string_view str )
569 {
570 #if defined( _WIN32 )
571 return convertBetweenACPAndUTF8( str, EncodingConversionDirection::ACPToUTF8 );
572 #else
573 return std::string{ str };
574 #endif
575 }
576
577 std::string System::encUTF8ToLocal( const std::string_view str )
578 {
579 #if defined( _WIN32 )
580 return convertBetweenACPAndUTF8( str, EncodingConversionDirection::UTF8ToACP );
581 #else
582 return std::string{ str };
583 #endif
584 }
585
586 std::string System::fsPathToString( const std::filesystem::path & path )
587 {
588 #if defined( _WIN32 )
589 // On Windows, std::filesystem::path::string() can throw an exception if path contains UTF-16 characters that
590 // are non-representable in CP_ACP. However, converting a well-formed UTF-16 string to UTF-8 is always safe,
591 // so we perform this conversion first, and then convert the resulting UTF-8 to CP_ACP using our conversion
592 // function, which can never throw an exception.
593 return encUTF8ToLocal( path.u8string() );
594 #else
595 return path.string();
596 #endif
597 }
598
599 tm System::GetTM( const time_t time )
600 {
601 tm result = {};
602
603 #if defined( _WIN32 )
604 errno_t res = localtime_s( &result, &time );
605
606 if ( res != 0 ) {
607 assert( 0 );
608 }
609 #else
610 const tm * res = localtime_r( &time, &result );
611
612 if ( res == nullptr ) {
613 assert( 0 );
614 }
615 #endif
616
617 return result;
618 }