-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathConfig.cpp
More file actions
409 lines (343 loc) · 12.5 KB
/
Copy pathConfig.cpp
File metadata and controls
409 lines (343 loc) · 12.5 KB
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
/*
MIT License
Copyright (c) 2021-2025 L. E. Spalt & Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <atomic>
#include <filesystem>
#include <algorithm>
#include "Config.h"
#include "Logger.h"
Config g_cfg;
static void configWatcher( std::atomic<bool>* m_hasChanged )
{
HANDLE dir = CreateFile( ".", FILE_LIST_DIRECTORY, FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL );
if( dir == INVALID_HANDLE_VALUE )
{
printf( "Could not start config watch thread.\n" );
return;
}
std::vector<DWORD> buf( 1024*1024 );
DWORD bytesReturned = 0;
while( true )
{
if( ReadDirectoryChangesW( dir, buf.data(), (DWORD)buf.size()/sizeof(DWORD), TRUE, FILE_NOTIFY_CHANGE_LAST_WRITE, &bytesReturned, NULL, NULL ) )
{
Sleep( 100 );
*m_hasChanged = true;
}
}
}
bool Config::load()
{
std::string json;
if( !loadFile(m_filename, json) )
{
Logger::instance().logError("Failed to load config file " + m_filename + " (loadFile returned false)");
return false;
}
picojson::value pjval;
std::string parseError = picojson::parse( pjval, json );
if( !parseError.empty() )
{
Logger::instance().logError("Config file parse error: " + parseError);
printf("Config file is not valid JSON!\n%s\n", parseError.c_str() );
return false;
}
m_pj = pjval.get<picojson::object>();
m_hasChanged = false;
return true;
}
bool Config::save()
{
const picojson::value value = picojson::value( m_pj );
const std::string json = value.serialize(true);
const bool ok = saveFile( m_filename, json );
if( !ok ) {
char s[1024];
GetCurrentDirectory( sizeof(s), s );
printf("Could not save config file! Please make sure iFL03 is started from a directory for which it has write permissions. The current directory is: %s.\n", s);
std::string msg = "Could not save config file (" + m_filename + ") from directory " + s;
Logger::instance().logError(msg);
}
return ok;
}
void Config::watchForChanges()
{
m_configWatchThread = std::thread( configWatcher, &m_hasChanged );
m_configWatchThread.detach();
}
bool Config::hasChanged()
{
return m_hasChanged;
}
bool Config::getBool( const std::string& component, const std::string& key, bool defaultVal )
{
bool existed = false;
picojson::value& value = getOrInsertValue( component, key, &existed );
if( !existed )
value.set<bool>( defaultVal );
return value.get<bool>();
}
int Config::getInt( const std::string& component, const std::string& key, int defaultVal )
{
bool existed = false;
picojson::value& value = getOrInsertValue( component, key, &existed );
if( !existed )
value.set<double>( defaultVal );
return (int)value.get<double>();
}
float Config::getFloat( const std::string& component, const std::string& key, float defaultVal )
{
bool existed = false;
picojson::value& value = getOrInsertValue( component, key, &existed );
if( !existed )
value.set<double>( defaultVal );
return (float)value.get<double>();
}
float4 Config::getFloat4( const std::string& component, const std::string& key, const float4& defaultVal )
{
bool existed = false;
picojson::value& value = getOrInsertValue( component, key, &existed );
if( !existed )
{
picojson::array arr( 4 );
arr[0].set<double>( defaultVal.x );
arr[1].set<double>( defaultVal.y );
arr[2].set<double>( defaultVal.z );
arr[3].set<double>( defaultVal.w );
value.set<picojson::array>( arr );
}
picojson::array& arr = value.get<picojson::array>();
float4 ret;
ret.x = (float)arr[0].get<double>();
ret.y = (float)arr[1].get<double>();
ret.z = (float)arr[2].get<double>();
ret.w = (float)arr[3].get<double>();
return ret;
}
std::string Config::getString( const std::string& component, const std::string& key, const std::string& defaultVal )
{
bool existed = false;
picojson::value& value = getOrInsertValue( component, key, &existed );
if( !existed )
value.set<std::string>( defaultVal );
return value.get<std::string>();
}
std::vector<std::string> Config::getStringVec( const std::string& component, const std::string& key, const std::vector<std::string>& defaultVal )
{
bool existed = false;
picojson::value& value = getOrInsertValue( component, key, &existed );
if( !existed )
{
picojson::array arr( defaultVal.size() );
for( int i=0; i<(int)defaultVal.size(); ++i )
arr[i].set<std::string>( defaultVal[i] );
value.set<picojson::array>( arr );
}
picojson::array& arr = value.get<picojson::array>();
std::vector<std::string> ret;
ret.reserve( arr.size() );
for( picojson::value& entry : arr )
ret.push_back( entry.get<std::string>() );
return ret;
}
void Config::setStringVec( const std::string& component, const std::string& key, const std::vector<std::string>& v )
{
picojson::object& pjcomp = getOrInsertComponent( component );
picojson::array arr;
arr.reserve(v.size());
for (const std::string& s : v) {
picojson::value val;
val.set<std::string>(s);
arr.push_back(val);
}
pjcomp[key].set<picojson::array>(arr);
}
void Config::setInt( const std::string& component, const std::string& key, int v )
{
picojson::object& pjcomp = getOrInsertComponent( component );
double d = double(v);
pjcomp[key].set<double>( d );
}
void Config::setBool( const std::string& component, const std::string& key, bool v )
{
picojson::object& pjcomp = getOrInsertComponent( component );
pjcomp[key].set<bool>( v );
}
void Config::setString( const std::string& component, const std::string& key, const std::string& v )
{
picojson::object& pjcomp = getOrInsertComponent( component );
pjcomp[key].set<std::string>( v );
}
void Config::setFloat( const std::string& component, const std::string& key, float v )
{
picojson::object& pjcomp = getOrInsertComponent( component );
pjcomp[key].set<double>( static_cast<double>(v) );
}
picojson::object& Config::getOrInsertComponent( const std::string& component, bool* existed )
{
auto it = m_pj.insert(std::make_pair(component,picojson::object()));
if( existed )
*existed = !it.second;
return it.first->second.get<picojson::object>();
}
picojson::value& Config::getOrInsertValue( const std::string& component, const std::string& key, bool* existed )
{
picojson::object& comp = getOrInsertComponent( component );
auto it = comp.insert(std::make_pair(key,picojson::value()));
if( existed )
*existed = !it.second;
return it.first->second;
}
std::string Config::sanitizeCarName( const std::string& carName ) const
{
std::string sanitized = carName;
// Replace spaces and invalid filename characters with underscores
std::replace_if(sanitized.begin(), sanitized.end(),
[](char c) { return c == ' ' || c == '/' || c == '\\' || c == ':' || c == '*' || c == '?' || c == '"' || c == '<' || c == '>' || c == '|'; },
'_');
return sanitized;
}
std::string Config::getCarConfigFilename( const std::string& carName ) const
{
if( carName.empty() )
return "config.json";
return "config_" + sanitizeCarName(carName) + ".json";
}
bool Config::loadCarConfig( const std::string& carName )
{
std::string carFilename = getCarConfigFilename(carName);
std::string json;
// Try to load car-specific config
if( !loadFile(carFilename, json) )
{
// If car config doesn't exist, try to load default config as base
if( !loadFile("config.json", json) )
{
Logger::instance().logError("Failed to load car config " + carFilename + " and fallback config.json");
return false;
}
}
picojson::value pjval;
std::string parseError = picojson::parse( pjval, json );
if( !parseError.empty() )
{
Logger::instance().logError("Car config parse error: " + parseError);
printf("Car config file is not valid JSON!\n%s\n", parseError.c_str() );
return false;
}
m_pj = pjval.get<picojson::object>();
m_filename = carFilename;
m_currentCarName = carName;
m_hasChanged = false;
return true;
}
bool Config::saveCarConfig( const std::string& carName )
{
std::string carFilename = getCarConfigFilename(carName);
const picojson::value value = picojson::value( m_pj );
const std::string json = value.serialize(true);
const bool ok = saveFile( carFilename, json );
if( !ok ) {
char s[1024];
GetCurrentDirectory( sizeof(s), s );
printf("Could not save car config file! Please make sure iFL03 is started from a directory for which it has write permissions. The current directory is: %s.\n", s);
}
return ok;
}
bool Config::hasCarConfig( const std::string& carName )
{
std::string carFilename = getCarConfigFilename(carName);
std::string json;
return loadFile(carFilename, json);
}
bool Config::copyConfigToCar( const std::string& fromCar, const std::string& toCar )
{
// Save current state
picojson::object currentPj = m_pj;
std::string currentFilename = m_filename;
std::string currentCarName = m_currentCarName;
// Load source config
bool loadOk = false;
if( fromCar.empty() )
{
// Copy from default config
loadOk = load();
}
else
{
loadOk = loadCarConfig(fromCar);
}
if( !loadOk )
{
Logger::instance().logError("Failed to load source config when copying from " + fromCar + " to " + toCar);
// Restore previous state
m_pj = currentPj;
m_filename = currentFilename;
m_currentCarName = currentCarName;
return false;
}
// Save to target car
bool saveOk = saveCarConfig(toCar);
// Restore previous state
m_pj = currentPj;
m_filename = currentFilename;
m_currentCarName = currentCarName;
return saveOk;
}
std::vector<std::string> Config::getAvailableCarConfigs()
{
std::vector<std::string> carConfigs;
try {
for (const auto& entry : std::filesystem::directory_iterator("."))
{
if (entry.is_regular_file())
{
std::string filename = entry.path().filename().string();
if (filename.starts_with("config_") && filename.ends_with(".json"))
{
// Extract car name from filename
std::string carName = filename.substr(7);
carName = carName.substr(0, carName.length() - 5);
// Restore spaces (reverse sanitization - basic version)
std::replace(carName.begin(), carName.end(), '_', ' ');
carConfigs.push_back(carName);
}
}
}
}
catch (const std::filesystem::filesystem_error& ex) {
printf("Error reading car configs: %s\n", ex.what());
}
std::sort(carConfigs.begin(), carConfigs.end());
return carConfigs;
}
bool Config::deleteCarConfig( const std::string& carName )
{
if( carName.empty() )
return false;
std::string carFilename = getCarConfigFilename(carName);
std::ifstream ifs(carFilename);
if (!ifs)
{
Logger::instance().logError("Failed to open car config file " + carFilename + " for delete check");
return false;
}
ifs.close();
return DeleteFileA(carFilename.c_str()) != 0;
}