Debian Codegraph @

src/App/ApplicationDirectories.h

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2 /***************************************************************************************************
3 * *
4 * Copyright (c) 2002 Jürgen Riegel <[email protected]> *
5 * Copyright (c) 2025 The FreeCAD project association AISBL *
6 * *
7 * This file is part of FreeCAD. *
8 * *
9 * FreeCAD is free software: you can redistribute it and/or modify it under the terms of the *
10 * GNU Lesser General Public License as published by the Free Software Foundation, either *
11 * version 2.1 of the License, or (at your option) any later version. *
12 * *
13 * FreeCAD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without *
14 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
15 * GNU Lesser General Public License for more details. *
16 * *
17 * You should have received a copy of the GNU Lesser General Public License along with FreeCAD. *
18 * If not, see <https://www.gnu.org/licenses/>. *
19 * *
20 **************************************************************************************************/
21
22 #ifndef SRC_APP_APPLICATIONDIRECTORIES_H_
23 #define SRC_APP_APPLICATIONDIRECTORIES_H_
24
25 #include "FCConfig.h"
26 #include "FCGlobal.h"
27
28 #include <filesystem>
29 #include <map>
30 #include <string>
31 #include <vector>
32
33 #ifdef FC_OS_WIN32
34 #include <QString>
35 #endif
36
37 namespace App {
38
39 /// A helper class to handle application-wide directory management on behalf of the main
40 /// App::Application class. Most of this class's methods were originally in Application, and
41 /// were extracted here to be more easily testable (and to better follow the single-
42 /// responsibility principle, though further work is required in that area).
43 class AppExport ApplicationDirectories {
44
45 public:
46
47 /// Constructor
48 /// \param config The base configuration dictionary. Used to create the appropriate
49 /// directories, and updated to reflect their locations. New code should not directly access
50 /// elements of this dictionary to determine directory locations, but should instead use
51 /// the public methods of this class to determine the locations needed.
52 explicit ApplicationDirectories(std::map<std::string,std::string> &config);
53
54 /// Given argv[0], figure out the home path. Used to initialize the AppHomePath element of
55 /// the configuration map prior to instantiating this class.
56 static std::filesystem::path findHomePath(const char* sCall);
57
58 /// "Home" here is the parent directory of the actual executable file being run. It is
59 /// exposed here primarily for historical compatibility reasons, and new code should almost
60 /// certainly NOT use this path for anything. See alternatives in the
61 /// `App::ApplicationDirectories` class.
62 const std::filesystem::path& getHomePath() const;
63
64 /// Get the user's home directory. This should not be used for many things, use caution when
65 /// deciding to use it for anything, there are usually better places.
66 const std::filesystem::path& getUserHomePath() const;
67
68 /// Temp path is the location of all temporary files: it is not guaranteed to preserve
69 /// information between runs of the program, but *is* guaranteed to exist for the duration
70 /// of a single program execution (that is, files are not deleted from it *during* the run).
71 const std::filesystem::path& getTempPath() const;
72
73 /// Get a file in the temp directory. WARNING: NOT THREAD-SAFE! Currently just forwards to
74 /// the FileInfo class. TODO: Rewrite to be thread safe
75 std::filesystem::path getTempFileName(const std::string & filename = "") const;
76
77 /// The user cache path can be used to store files that the program *prefers* not be deleted
78 /// between runs, but that will be recreated or otherwise handled if they do not exist due
79 /// to the cache being cleared. There is no guarantee that the files will exist from
80 /// run-to-run, but an effort is made to preserve them (unlike the temp directory, which
81 /// should never be used to save data between runs).
82 const std::filesystem::path& getUserCachePath() const;
83
84 /// The primary directory used to store per-user application data. This is the parent
85 /// directory of all installed addons, per-user configuration files, etc. Developers looking
86 /// for a place to put per-user data should begin here. Common subdirectories include "Mod",
87 /// "Macros", "Materials" and many others that don't begin with the letter "M". This is
88 /// typically a versioned directory, though users may choose to use a single path for
89 /// multiple versions of the software.
90 const std::filesystem::path& getUserAppDataDir() const;
91
92 /// Historically, a single directory was used to store user-created (or user-installed)
93 /// macro files. This is the path to that directory. Note that going forward it should *not*
94 /// be assumed that all installed macros are located in this directory. This is typically a
95 /// versioned directory, though users may choose to use a single path for multiple versions
96 /// of the software.
97 const std::filesystem::path& getUserMacroDir() const;
98
99 /// The "resource" directory should be used to store non-ephemeral resources such as icons,
100 /// templates, hardware setup, etc. -- items that should be preserved from run-to-run of the
101 /// program, and between versions. This is *not* a versioned directory, and multiple
102 /// versions of the software may access the same data.
103 const std::filesystem::path& getResourceDir() const;
104
105 /// Nominally, this is the directory where "help" files are stored, though for historical
106 /// reasons several other informational files are stored here as well. It should only be
107 /// used for user-facing informational files.
108 const std::filesystem::path& getHelpDir() const;
109
110 /// The root path of user config files `user.cfg` and `system.cfg`.
111 const std::filesystem::path& getUserConfigPath() const;
112
113 /// The directory of all extension modules. Added to `sys.path` during Python
114 /// initialization.
115 const std::filesystem::path& getLibraryDir() const;
116
117 /// Get the user's home directory
118 static std::filesystem::path getUserHome();
119
120 /// Returns true if the current active directory set is custom, and false if it's the
121 /// standard system default.
122 bool usingCustomDirectories() const;
123
124
125 // Versioned-Path Management Methods:
126
127 /// Determine if a given config path is for the current version of the program
128 /// \param config The path to check
129 bool usingCurrentVersionConfig(std::filesystem::path config) const;
130
131 struct MigrationResult
132 {
133 std::vector<std::filesystem::path> failedPaths;
134 std::vector<std::pair<std::filesystem::path, std::filesystem::path>> migratedPaths;
135 };
136
137 /// Migrate a set of versionable configuration directories from the given path to a new
138 /// version. The new version's directories cannot exist yet, and the old ones *must* exist.
139 /// If the old paths are themselves versioned, then the new paths will be placed at the same
140 /// level in the directory structure (e.g., they will be siblings of each entry in paths).
141 /// If paths are NOT versioned, the new (versioned) copies will be placed *inside* the
142 /// original paths. Returns the paths of entries that could not be copied.
143 MigrationResult migrateAllPaths(const std::vector<std::filesystem::path>& paths) const;
144
145 /// A utility method to generate the versioned directory name for a given version. This only
146 /// returns the version string, not an entire path. As of FreeCAD 1.1, the string is of the
147 /// form "vX-Y" where X is the major version and Y is the minor, but external code should
148 /// not assume that is always the form, and should instead use this method, which is
149 /// guaranteed stable (that is, given "1" and "1" as the major and minor, it will always
150 /// return the string "v1-1", even if in later versions the format changes.
151 static std::string versionStringForPath(int major, int minor);
152
153 /// Given an arbitrary path, determine if it has the correct form to be a versioned path
154 /// (e.g. is the last component a recognized version of the code). DOES NOT recognize
155 /// versions *newer* than the current version, even if the directory name matches the path
156 /// naming convention used by the previous version.
157 bool isVersionedPath(const std::filesystem::path &startingPath) const;
158
159 /// Given a base path that is expected to contained versioned subdirectories, locate the
160 /// directory name (*not* the path, only the final component, the version string itself)
161 /// corresponding to the most recent version of the software, up to and including the
162 /// current version, but NOT exceeding it.
163 std::string mostRecentAvailableConfigVersion(const std::filesystem::path &startingPath) const;
164
165 /// Given a base path that is expected to contained versioned subdirectories, locate the
166 /// directory corresponding to the most recent version of the software, up to and including
167 /// the current version, but NOT exceeding it.
168 std::filesystem::path mostRecentConfigFromBase(const std::filesystem::path &startingPath) const;
169
170 /// A utility method to copy all files and directories from oldPath to newPath, handling the
171 /// case where newPath might itself be a subdirectory of oldPath (and *not* attempting that
172 /// otherwise-recursive copy). Returns the paths of entries that could not be copied.
173 static MigrationResult migrateConfig(const std::filesystem::path& oldPath,
174 const std::filesystem::path& newPath);
175
176 #ifdef FC_OS_WIN32
177 /// On Windows, gets the location of the user's "AppData" directory. Invalid on other OSes.
178 QString getOldGenericDataLocation();
179 #endif
180 /// Adds subdirectory information to the appData vector for use in constructing full paths to config files, etc.
181 static void getSubDirectories(const std::map<std::string,std::string>& mConfig,
182 std::vector<std::string>& appData);
183 /// To a given path it adds the subdirectories where to store application-specific files.
184 /// On Linux or BSD a hidden directory (i.e. starting with a dot) is added.
185 static void getOldDataLocation(const std::map<std::string,std::string>& mConfig,
186 std::vector<std::string>& appData);
187 /// If the passed path name is not empty, it will be returned, otherwise the user home path of the system will
188 /// be returned.
189 static std::filesystem::path findUserHomePath(const std::filesystem::path& userHome);
190
191 protected:
192
193 /// Override all application directories with temp directories. Returns true on success and
194 /// false if the temp directory creation failed.
195 bool startSafeMode(std::map<std::string,std::string>& mConfig);
196
197 enum class MissingDirectoryBehavior : uint8_t {
198 create,
199 doNotAppend
200 };
201
202 /// Take a path and add a version to it, if it's possible to do so. When \a behavior is
203 /// `doNotAppend`, no directories are created: the most recent existing versioned
204 /// subdirectory is appended if one is found, or the current version is appended if the
205 /// base path does not yet exist. When \a behavior is `create`, the current version is
206 /// always appended and the directory is created on disk if it does not already exist.
207 void appendVersionIfPossible(const std::filesystem::path& basePath,
208 std::vector<std::string> &subdirs,
209 MissingDirectoryBehavior behavior) const;
210
211 static std::filesystem::path findPath(
212 const std::filesystem::path& stdHome,
213 const std::filesystem::path& customHome,
214 const std::vector<std::string>& paths,
215 bool create);
216
217 void configurePaths(std::map<std::string,std::string> &config);
218 void configureResourceDirectory(const std::map<std::string,std::string>& mConfig);
219 void configureLibraryDirectory(const std::map<std::string,std::string>& mConfig);
220 void configureHelpDirectory(const std::map<std::string,std::string>& mConfig);
221
222 /*!
223 * Returns a tuple of path names where to store config, data, and temp. files.
224 * The method therefore reads the environment variables:
225 * \list
226 * \li FREECAD_USER_HOME
227 * \li FREECAD_USER_DATA
228 * \li FREECAD_USER_TEMP
229 * \endlist
230 */
231 static std::tuple<std::filesystem::path, std::filesystem::path, std::filesystem::path> getCustomPaths();
232
233 /*!
234 * Returns a tuple of XDG-compliant standard paths names where to store config, data and cached files.
235 * The method therefore reads the environment variables:
236 * \list
237 * \li XDG_CONFIG_HOME
238 * \li XDG_DATA_HOME
239 * \li XDG_CACHE_HOME
240 * \endlist
241 */
242 std::tuple<std::filesystem::path, std::filesystem::path, std::filesystem::path, std::filesystem::path> getStandardPaths();
243
244 /// Find the BuildVersionMajor, BuildVersionMinor pair in the config map, convert them to an int tuple, and
245 /// return it. If the pair is not found, or cannot be converted to integers, a RuntimeError is raised.
246 /// \param config The config map to search.
247 /// \return The version tuple.
248 static std::tuple<int, int> extractVersionFromConfigMap(const std::map<std::string,std::string> &config);
249
250 /// A utility method to remove any stray null characters from a path (Conda sometimes
251 /// injects these for unknown reasons -- see #6892 in the bug tracker).
252 /// \param pathAsString The std::string path to sanitize
253 /// \returns A path with any stray nulls removed
254 static std::filesystem::path sanitizePath(const std::string& pathAsString);
255
256 private:
257 std::tuple<int, int> _currentVersion;
258 std::filesystem::path _home;
259 std::filesystem::path _temp;
260 std::filesystem::path _userCache;
261 std::filesystem::path _userConfig;
262 std::filesystem::path _userAppData;
263 std::filesystem::path _userMacro;
264 std::filesystem::path _userHome;
265 std::filesystem::path _resource;
266 std::filesystem::path _library;
267 std::filesystem::path _help;
268
269 bool _usingCustomDirectories {false};
270 };
271
272 } // App
273
274 #endif //SRC_APP_APPLICATIONDIRECTORIES_H_