game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
lutris_config.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// lutris_config.cpp
4// ==============================================================================
5// Lutris game configuration parser implementation
6// ==============================================================================
7
8#include "lutris_config.h"
9#include "logger.h"
10
11#include <cstdlib>
12#include <filesystem>
13#include <fstream>
14
15namespace fs = std::filesystem;
16
17// ==============================================================================
18// LutrisGameConfig Implementation
19// ==============================================================================
20
22{
23 if (prefix.empty() || exe.empty())
24 return "";
25
26 fs::path fullPath = fs::path(prefix) / exe;
27 return fullPath.string();
28}
29
31{
32 // Priority: game-specific winePath > custom wine path from runner config
33 if (!winePath.empty())
34 return winePath;
35 if (!customWinePath.empty())
36 return customWinePath;
37 return "";
38}
39
40// ==============================================================================
41// LutrisConfigParser Implementation
42// ==============================================================================
43
45{
46 const char* home = std::getenv("HOME");
47 if (!home)
48 return "";
49
50 // Check native Lutris first
51 std::string nativePath = (fs::path(home) / ".local" / "share" / "lutris" / "games").string();
52 if (fs::exists(nativePath))
53 return nativePath;
54
55 // Check Flatpak Lutris
56 std::string flatpakPath =
57 (fs::path(home) / ".var" / "app" / "net.lutris.Lutris" / "data" / "lutris" / "games")
58 .string();
59 if (fs::exists(flatpakPath))
60 return flatpakPath;
61
62 // Return native path as default even if it doesn't exist yet
63 return nativePath;
64}
65
67{
68 const char* home = std::getenv("HOME");
69 if (!home)
70 return "";
71 return (fs::path(home) / ".local" / "share" / "lutris" / "runners").string();
72}
73
74std::string LutrisConfigParser::findConfigForExecutable(const std::string& executablePath)
75{
76 std::string gamesDir = getGamesDirectory();
77 if (gamesDir.empty() || !fs::exists(gamesDir))
78 {
79 return "";
80 }
81
82 // Normalize the executable path for comparison
83 fs::path exePath;
84 try
85 {
86 exePath = fs::canonical(executablePath);
87 }
88 catch (...)
89 {
90 exePath = executablePath;
91 }
92 std::string exePathStr = exePath.string();
93
94 Logger::info("[LutrisConfig] Searching for config matching: {}", exePathStr);
95
96 // Iterate through all .yml files in the games directory
97 try
98 {
99 for (const auto& entry : fs::directory_iterator(gamesDir))
100 {
101 if (!entry.is_regular_file())
102 continue;
103
104 std::string filename = entry.path().filename().string();
105 if (filename.size() < 4 || filename.substr(filename.size() - 4) != ".yml")
106 continue;
107
108 // Quick parse to check if this config matches
109 LutrisGameConfig config = parseConfigFile(entry.path().string());
110 if (!config.isValid())
111 continue;
112
113 std::string configExe = config.getFullExecutablePath();
114 if (configExe.empty())
115 continue;
116
117 // Normalize the config executable path
118 fs::path configExePath;
119 try
120 {
121 configExePath = fs::canonical(configExe);
122 }
123 catch (...)
124 {
125 configExePath = configExe;
126 }
127
128 // Check for match
129 if (configExePath == exePath)
130 {
131 Logger::info("[LutrisConfig] Found matching config: {}", entry.path().string());
132 return entry.path().string();
133 }
134 }
135 }
136 catch (const std::exception& e)
137 {
138 Logger::warn("[LutrisConfig] Error searching configs: {}", e.what());
139 }
140
141 return "";
142}
143
145{
146 LutrisGameConfig config;
147
148 std::ifstream file(configPath);
149 if (!file.is_open())
150 {
151 Logger::warn("[LutrisConfig] Failed to open config: {}", configPath);
152 return config;
153 }
154
155 std::string line;
156 bool inEnvSection = false;
157 bool inOverridesSection = false;
158
159 // State machine for parsing nested YAML
160 // We track: game.*, system.env.*, wine.*
161 enum class Section
162 {
163 Root,
164 Game,
165 System,
166 SystemEnv,
167 Wine,
168 WineOverrides
169 };
170 Section section = Section::Root;
171
172 // Track which field might have a continuation line
173 std::string* continuationTarget = nullptr;
174 int continuationIndent = 0;
175
176 while (std::getline(file, line))
177 {
178 // Skip empty lines and comments
179 std::string trimmedLine = trim(line);
180 if (trimmedLine.empty() || trimmedLine[0] == '#')
181 continue;
182
183 int indent = countIndent(line);
184
185 // Handle YAML continuation lines (folded values that span multiple lines)
186 // If we have a continuation target and the current line is more indented,
187 // append this line to the previous value
188 if (continuationTarget != nullptr && indent > continuationIndent)
189 {
190 // This is a continuation of the previous value
191 // Append with a space (YAML folding semantics)
192 *continuationTarget += " " + trimmedLine;
193 continue;
194 }
195 else
196 {
197 // Not a continuation, clear the target
198 continuationTarget = nullptr;
199 continuationIndent = 0;
200 }
201
202 // Handle section transitions based on indent
203 if (indent == 0)
204 {
205 section = Section::Root;
206 inEnvSection = false;
207 inOverridesSection = false;
208
209 if (trimmedLine == "game:")
210 {
211 section = Section::Game;
212 }
213 else if (trimmedLine == "system:")
214 {
215 section = Section::System;
216 }
217 else if (trimmedLine == "wine:")
218 {
219 section = Section::Wine;
220 }
221 else
222 {
223 // Root level key:value. C++17 init-statement form keeps the
224 // captured value scoped to its branch and avoids the
225 // bugprone-assignment-in-if-condition pattern of mixing
226 // assignment with the test in the same expression.
227 if (auto v1 = extractYamlValue(trimmedLine, "name"); !v1.empty())
228 config.name = v1;
229 else if (auto v2 = extractYamlValue(trimmedLine, "slug"); !v2.empty())
230 config.slug = v2;
231 else if (auto v3 = extractYamlValue(trimmedLine, "game_slug"); !v3.empty())
232 config.gameSlug = v3;
233 }
234 }
235 else if (indent == 2)
236 {
237 // First level under a section
238 if (section == Section::Game)
239 {
240 if (auto v1 = extractYamlValue(trimmedLine, "exe"); !v1.empty())
241 {
242 config.exe = v1;
243 // Set up for potential continuation (paths with spaces often fold)
244 continuationTarget = &config.exe;
245 continuationIndent = indent;
246 }
247 else if (auto v2 = extractYamlValue(trimmedLine, "prefix"); !v2.empty())
248 config.prefix = v2;
249 else if (auto v3 = extractYamlValue(trimmedLine, "arch"); !v3.empty())
250 config.arch = v3;
251 else if (auto v4 = extractYamlValue(trimmedLine, "args"); !v4.empty())
252 {
253 config.arguments = v4;
254 // Arguments might also span lines
255 continuationTarget = &config.arguments;
256 continuationIndent = indent;
257 }
258 else if (auto v5 = extractYamlValue(trimmedLine, "working_dir"); !v5.empty())
259 {
260 config.workingDir = v5;
261 continuationTarget = &config.workingDir;
262 continuationIndent = indent;
263 }
264 }
265 else if (section == Section::System)
266 {
267 if (trimmedLine == "env:")
268 {
269 inEnvSection = true;
270 }
271 else
272 {
273 inEnvSection = false;
274
275 // Parse exclude_processes: "Process1.exe" "Process2.exe" or Process1.exe
276 // Process2.exe
277 if (auto value = extractYamlValue(trimmedLine, "exclude_processes");
278 !value.empty())
279 {
280 // Parse space-separated process names (may be quoted)
281 std::string current;
282 bool inQuotes = false;
283 for (char c : value)
284 {
285 if (c == '"')
286 {
287 inQuotes = !inQuotes;
288 }
289 else if (c == ' ' && !inQuotes)
290 {
291 if (!current.empty())
292 {
293 config.excludeProcesses.push_back(current);
294 current.clear();
295 }
296 }
297 else
298 {
299 current += c;
300 }
301 }
302 if (!current.empty())
303 {
304 config.excludeProcesses.push_back(current);
305 }
306 }
307 }
308 }
309 else if (section == Section::Wine)
310 {
311 if (auto v1 = extractYamlValue(trimmedLine, "version"); !v1.empty())
312 config.wineVersion = v1;
313 else if (auto v2 = extractYamlValue(trimmedLine, "custom_wine_path"); !v2.empty())
314 config.customWinePath = v2;
315 else if (trimmedLine == "overrides:")
316 {
317 inOverridesSection = true;
318 }
319 else
320 {
321 inOverridesSection = false;
322 }
323 }
324 }
325 else if (indent == 4)
326 {
327 // Second level (env vars or dll overrides)
328 if (section == Section::System && inEnvSection)
329 {
330 // Parse environment variable: KEY: value
331 size_t colonPos = trimmedLine.find(':');
332 if (colonPos != std::string::npos)
333 {
334 std::string key = trim(trimmedLine.substr(0, colonPos));
335 std::string value = trim(trimmedLine.substr(colonPos + 1));
336 value = unquote(value);
337
338 // Replace $GAMEDIR with prefix (advance past replaced text to avoid infinite
339 // loop if prefix itself contains the literal "$GAMEDIR")
340 if (!config.prefix.empty())
341 {
342 size_t pos = 0;
343 while ((pos = value.find("$GAMEDIR", pos)) != std::string::npos)
344 {
345 value.replace(pos, 8, config.prefix);
346 pos += config.prefix.size();
347 }
348 }
349
350 if (!key.empty())
351 {
352 config.environmentVariables[key] = value;
353 }
354 }
355 }
356 else if (section == Section::Wine && inOverridesSection)
357 {
358 // Parse DLL override: dllname: override_type
359 size_t colonPos = trimmedLine.find(':');
360 if (colonPos != std::string::npos)
361 {
362 std::string dll = trim(trimmedLine.substr(0, colonPos));
363 std::string override = trim(trimmedLine.substr(colonPos + 1));
364 override = unquote(override);
365
366 if (!dll.empty())
367 {
368 config.dllOverrides[dll] = override;
369 }
370 }
371 }
372 }
373 }
374
375 // Read custom wine path from runner config if not set in game config
376 if (config.customWinePath.empty())
377 {
378 config.customWinePath = readWineRunnerConfig();
379 }
380
381 if (config.isValid())
382 {
383 Logger::info("[LutrisConfig] Parsed config for: {} (prefix: {}, exe: {})", config.name,
384 config.prefix, config.exe);
385 Logger::info("[LutrisConfig] Wine path: {}", config.getEffectiveWinePath().empty()
386 ? "(system default)"
387 : config.getEffectiveWinePath());
388 Logger::info("[LutrisConfig] Environment variables: {}",
389 config.environmentVariables.size());
390 if (!config.excludeProcesses.empty())
391 {
392 Logger::info("[LutrisConfig] Exclude processes: {}", config.excludeProcesses.size());
393 }
394 }
395 else
396 {
397 Logger::debug("[LutrisConfig] Invalid config (name: {}, prefix: {}, exe: {})", config.name,
398 config.prefix, config.exe);
399 }
400
401 return config;
402}
403
404std::string LutrisConfigParser::readWineRunnerConfig()
405{
406 std::string runnersDir = getRunnersDirectory();
407 if (runnersDir.empty())
408 return "";
409
410 fs::path wineConfigPath = fs::path(runnersDir) / "wine.yml";
411 if (!fs::exists(wineConfigPath))
412 return "";
413
414 std::ifstream file(wineConfigPath);
415 if (!file.is_open())
416 return "";
417
418 std::string line;
419 bool inWineSection = false;
420
421 while (std::getline(file, line))
422 {
423 std::string trimmedLine = trim(line);
424 if (trimmedLine.empty() || trimmedLine[0] == '#')
425 continue;
426
427 int indent = countIndent(line);
428
429 if (indent == 0 && trimmedLine == "wine:")
430 {
431 inWineSection = true;
432 continue;
433 }
434 else if (indent == 0)
435 {
436 inWineSection = false;
437 }
438
439 if (inWineSection && indent == 2)
440 {
441 std::string value = extractYamlValue(trimmedLine, "custom_wine_path");
442 if (!value.empty())
443 {
444 Logger::info("[LutrisConfig] Found custom wine path in runner config: {}", value);
445 return value;
446 }
447 }
448 }
449
450 return "";
451}
452
453std::string LutrisConfigParser::extractYamlValue(const std::string& line, const std::string& key,
454 int /*indent*/)
455{
456 std::string trimmedLine = trim(line);
457
458 // Check if line starts with key:
459 std::string keyPattern = key + ":";
460 if (trimmedLine.find(keyPattern) != 0)
461 return "";
462
463 // Extract value after colon
464 std::string value = trimmedLine.substr(keyPattern.size());
465 value = trim(value);
466 value = unquote(value);
467
468 return value;
469}
470
471int LutrisConfigParser::countIndent(const std::string& line)
472{
473 int count = 0;
474 for (char c : line)
475 {
476 if (c == ' ')
477 count++;
478 else
479 break;
480 }
481 return count;
482}
483
484std::string LutrisConfigParser::trim(const std::string& str)
485{
486 size_t first = str.find_first_not_of(" \t\r\n");
487 if (first == std::string::npos)
488 return "";
489 size_t last = str.find_last_not_of(" \t\r\n");
490 return str.substr(first, last - first + 1);
491}
492
493std::string LutrisConfigParser::unquote(const std::string& str)
494{
495 if (str.size() < 2)
496 return str;
497
498 char first = str.front();
499 char last = str.back();
500
501 if ((first == '"' && last == '"') || (first == '\'' && last == '\''))
502 {
503 return str.substr(1, str.size() - 2);
504 }
505
506 return str;
507}
Complete representation of a game in the library.
Definition game.h:767
static void info(const std::string &message, Args &&... args)
Log info message (general information).
Definition logger.h:108
static void debug(const std::string &message, Args &&... args)
Log debug message (verbose development info).
Definition logger.h:100
static void warn(const std::string &message, Args &&... args)
Log warning message (non-critical issue).
Definition logger.h:116
static std::string findConfigForExecutable(const std::string &executablePath)
Find Lutris config file for a given executable.
static std::string getGamesDirectory()
Get the Lutris games directory.
static std::string getRunnersDirectory()
Get the Lutris runners directory.
static LutrisGameConfig parseConfigFile(const std::string &configPath)
Parse a Lutris game config file.
@ Wine
Windows game via Wine compatibility layer.
Definition game.h:63
Parsed configuration for a Lutris-managed game.
std::string workingDir
Working directory (optional).
std::string gameSlug
Game slug from lutris.net.
std::string name
Game display name.
std::string getFullExecutablePath() const
Get the full path to the executable.
std::map< std::string, std::string > dllOverrides
std::string prefix
Wine prefix path.
std::map< std::string, std::string > environmentVariables
std::string exe
Relative path to executable (from prefix).
std::vector< std::string > excludeProcesses
std::string wineVersion
Wine version name (e.g., "Proton - Experimental").
std::string slug
Game slug (unique identifier).
std::string arguments
Command line arguments (optional).
bool isValid() const
Check if config is valid and usable.
std::string arch
Wine architecture: "win32" or "win64".
std::string winePath
Full path to wine executable.
std::string customWinePath
Custom wine path from runner config.
std::string getEffectiveWinePath() const
Get the effective wine path to use.