| 1 | |
| 2 | /** |
| 3 | * |
| 4 | * @file xdg.cpp |
| 5 | * |
| 6 | * Part of the OpenJazz project |
| 7 | * |
| 8 | * @par Licence: |
| 9 | * Copyright (c) 2015-2026 Carsten Teibes |
| 10 | * |
| 11 | * OpenJazz is distributed under the terms of |
| 12 | * the GNU General Public License, version 2.0 |
| 13 | * |
| 14 | */ |
| 15 | |
| 16 | #include "xdg.h" |
| 17 | |
| 18 | #if __unix__ |
| 19 | |
| 20 | #include <cstring> |
| 21 | #include <sys/stat.h> |
| 22 | #include <cstdlib> |
| 23 | |
| 24 | #include "util.h" |
| 25 | #include "io/file.h" |
| 26 | #include "io/log.h" |
| 27 | |
| 28 | namespace { |
| 29 | struct { |
| 30 | const char *env; |
| 31 | const char *relPath; |
| 32 | int type; |
| 33 | bool create; |
| 34 | } xdgSpec[] = { |
| 35 | {"XDG_CONFIG_HOME", "/.config", PATH_TYPE_CONFIG, true}, |
| 36 | {"XDG_CACHE_HOME", "/.cache", PATH_TYPE_TEMP, true}, |
| 37 | {"XDG_DATA_HOME", "/.local/share", PATH_TYPE_GAME, false} |
| 38 | }; |
| 39 | } |
| 40 | |
| 41 | void XDGPlatform::AddGamePaths() { |
| 42 | // first get home directory, will be useful later and serves as sanity check |
| 43 | const char *homeDir = getenv("HOME"); |
| 44 | if (!homeDir) { |
| 45 | LOG_WARN("No $HOME found, this might break something."); |
| 46 | return; |
| 47 | } |
| 48 | |
| 49 | // define our subdirectory |
| 50 | const char *appDir = "/openjazz"; |
| 51 | |
| 52 | // check all needed XDG directories from spec |
| 53 | for(auto const &entry : xdgSpec) { |
| 54 | // length of final path |
| 55 | size_t xdgLen = 0; |
| 56 | |
| 57 | // check for user override |
| 58 | const char *env = getenv(entry.env); |
| 59 | if (env) { |
| 60 | xdgLen = strlen(env); |
| 61 | } else { |
| 62 | // use fallback directory |
| 63 | xdgLen = strlen(homeDir) + strlen(entry.relPath); |
| 64 | } |
| 65 | |
| 66 | // concatenate path |
| 67 | char *xdgPath = new char[xdgLen + strlen(appDir) + 1]; |
| 68 | if(env) { |
| 69 | strcpy(xdgPath, env); |
| 70 | } else { |
| 71 | strcpy(xdgPath, homeDir); |
| 72 | strcat(xdgPath, entry.relPath); |
| 73 | } |
| 74 | strcat(xdgPath, appDir); |
| 75 | |
| 76 | // create if needed |
| 77 | if(entry.create) { |
| 78 | LOG_TRACE("Trying to create '%s' directory", xdgPath); |
| 79 | mkdir(xdgPath, 0777); |
| 80 | } |
| 81 | |
| 82 | gamePaths.add(xdgPath, entry.type); |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | #endif |