| 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 |
#include <fmt/format.h> |
| 23 |
#include <utility> |
| 24 |
#include <QDir> |
| 25 |
#include <QProcessEnvironment> |
| 26 |
#include <QStandardPaths> |
| 27 |
#include <QCoreApplication> |
| 28 |
|
| 29 |
#include "ApplicationDirectories.h" |
| 30 |
|
| 31 |
#include <FCConfig.h> |
| 32 |
|
| 33 |
#if defined(FC_OS_LINUX) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) |
| 34 |
#include <pwd.h> |
| 35 |
#endif |
| 36 |
|
| 37 |
#include <Base/FileInfo.h> |
| 38 |
#include <Base/Exception.h> |
| 39 |
#include "SafeMode.h" |
| 40 |
|
| 41 |
#include <Python.h> |
| 42 |
#include <QString> |
| 43 |
|
| 44 |
#include "Base/Console.h" |
| 45 |
|
| 46 |
|
| 47 |
using namespace App; |
| 48 |
namespace fs = std::filesystem; |
| 49 |
|
| 50 |
fs::path qstringToPath(const QString& path) |
| 51 |
{ |
| 52 |
#if defined(FC_OS_WIN32) |
| 53 |
return {path.toStdWString()}; |
| 54 |
#else |
| 55 |
return {path.toStdString()}; |
| 56 |
#endif |
| 57 |
} |
| 58 |
|
| 59 |
ApplicationDirectories::ApplicationDirectories(std::map<std::string,std::string> &config) |
| 60 |
{ |
| 61 |
_currentVersion = extractVersionFromConfigMap(config); |
| 62 |
configurePaths(config); |
| 63 |
configureResourceDirectory(config); |
| 64 |
configureLibraryDirectory(config); |
| 65 |
configureHelpDirectory(config); |
| 66 |
} |
| 67 |
|
| 68 |
const fs::path& ApplicationDirectories::getHomePath() const |
| 69 |
{ |
| 70 |
return this->_home; |
| 71 |
} |
| 72 |
|
| 73 |
const fs::path& ApplicationDirectories::getUserHomePath() const |
| 74 |
{ |
| 75 |
return this->_userHome; |
| 76 |
} |
| 77 |
|
| 78 |
const fs::path& ApplicationDirectories::getTempPath() const { |
| 79 |
return this->_temp; |
| 80 |
} |
| 81 |
|
| 82 |
fs::path ApplicationDirectories::getTempFileName(const std::string & filename) const |
| 83 |
{ |
| 84 |
auto tempPath = Base::FileInfo::pathToString(getTempPath()); |
| 85 |
if (filename.empty()) { |
| 86 |
return Base::FileInfo::stringToPath(Base::FileInfo::getTempFileName(nullptr, tempPath.c_str()) |
| 87 |
); |
| 88 |
} |
| 89 |
return Base::FileInfo::stringToPath( |
| 90 |
Base::FileInfo::getTempFileName(filename.c_str(), tempPath.c_str()) |
| 91 |
); |
| 92 |
} |
| 93 |
|
| 94 |
const fs::path& ApplicationDirectories::getUserCachePath() const |
| 95 |
{ |
| 96 |
return this->_userCache; |
| 97 |
} |
| 98 |
|
| 99 |
const fs::path& ApplicationDirectories::getUserAppDataDir() const |
| 100 |
{ |
| 101 |
return this->_userAppData; |
| 102 |
} |
| 103 |
|
| 104 |
const fs::path& ApplicationDirectories::getUserMacroDir() const |
| 105 |
{ |
| 106 |
return this->_userMacro; |
| 107 |
} |
| 108 |
|
| 109 |
const fs::path& ApplicationDirectories::getResourceDir() const |
| 110 |
{ |
| 111 |
return this->_resource; |
| 112 |
} |
| 113 |
|
| 114 |
const fs::path& ApplicationDirectories::getHelpDir() const |
| 115 |
{ |
| 116 |
return this->_help; |
| 117 |
} |
| 118 |
|
| 119 |
const fs::path& ApplicationDirectories::getUserConfigPath() const { |
| 120 |
return this->_userConfig; |
| 121 |
} |
| 122 |
|
| 123 |
const fs::path& ApplicationDirectories::getLibraryDir() const { |
| 124 |
return this->_library; |
| 125 |
} |
| 126 |
|
| 127 |
|
| 128 |
/*! |
| 129 |
* \brief findPath |
| 130 |
* Returns the path where to store application files to. |
| 131 |
* If \a customHome is not empty, it will be used, otherwise a path starting from \a stdHome will be |
| 132 |
* used. |
| 133 |
*/ |
| 134 |
fs::path ApplicationDirectories::findPath(const fs::path& stdHome, const fs::path& customHome, |
| 135 |
const std::vector<std::string>& subdirs, bool create) { |
| 136 |
fs::path appData = customHome; |
| 137 |
if (appData.empty()) { |
| 138 |
appData = stdHome; |
| 139 |
} |
| 140 |
|
| 141 |
// If a custom user home path is given, then don't modify it |
| 142 |
if (customHome.empty()) { |
| 143 |
for (const auto& it : subdirs) { |
| 144 |
if (!it.empty()) { |
| 145 |
// Refuse to add an empty directory path component |
| 146 |
appData = appData / it; |
| 147 |
} |
| 148 |
} |
| 149 |
} |
| 150 |
|
| 151 |
// To write to our data path, we must create some directories, first. |
| 152 |
if (create && !fs::exists(appData) && !Py_IsInitialized()) { |
| 153 |
try { |
| 154 |
fs::create_directories(appData); |
| 155 |
} catch (const fs::filesystem_error& e) { |
| 156 |
throw Base::FileSystemError("Could not create directories. Failed with: " + e.code().message()); |
| 157 |
} |
| 158 |
} |
| 159 |
|
| 160 |
return appData; |
| 161 |
} |
| 162 |
|
| 163 |
void ApplicationDirectories::appendVersionIfPossible(const fs::path& basePath, |
| 164 |
std::vector<std::string> &subdirs, |
| 165 |
MissingDirectoryBehavior behavior) const |
| 166 |
{ |
| 167 |
fs::path pathToCheck = basePath; |
| 168 |
for (const auto& it : subdirs) { |
| 169 |
pathToCheck = pathToCheck / it; |
| 170 |
} |
| 171 |
if (isVersionedPath(pathToCheck)) { |
| 172 |
return; // Bail out if it's already versioned |
| 173 |
} |
| 174 |
if (behavior == MissingDirectoryBehavior::create) { |
| 175 |
// Always use the current version, creating the directory if needed |
| 176 |
auto [major, minor] = _currentVersion; |
| 177 |
auto versionString = versionStringForPath(major, minor); |
| 178 |
subdirs.emplace_back(versionString); |
| 179 |
auto versionedDir = pathToCheck / versionString; |
| 180 |
if (!fs::exists(versionedDir)) { |
| 181 |
fs::create_directories(versionedDir); |
| 182 |
} |
| 183 |
} else if (fs::exists(pathToCheck)) { |
| 184 |
std::string version = mostRecentAvailableConfigVersion(pathToCheck); |
| 185 |
if (!version.empty()) { |
| 186 |
subdirs.emplace_back(std::move(version)); |
| 187 |
} |
| 188 |
} else { |
| 189 |
auto [major, minor] = _currentVersion; |
| 190 |
subdirs.emplace_back(versionStringForPath(major, minor)); |
| 191 |
} |
| 192 |
} |
| 193 |
|
| 194 |
void ApplicationDirectories::configurePaths(std::map<std::string,std::string>& mConfig) |
| 195 |
{ |
| 196 |
bool keepDeprecatedPaths = mConfig.contains("KeepDeprecatedPaths"); |
| 197 |
|
| 198 |
// std paths |
| 199 |
_home = Base::FileInfo::stringToPath(mConfig.at("AppHomePath")); |
| 200 |
mConfig["BinPath"] = mConfig.at("AppHomePath") + "bin" + PATHSEP; |
| 201 |
mConfig["DocPath"] = mConfig.at("AppHomePath") + "doc" + PATHSEP; |
| 202 |
|
| 203 |
// this is to support a portable version of FreeCAD |
| 204 |
auto [customHome, customData, customTemp] = getCustomPaths(); |
| 205 |
_usingCustomDirectories = !customHome.empty() || !customData.empty(); |
| 206 |
|
| 207 |
// get the system standard paths |
| 208 |
auto [configHome, dataHome, cacheHome, tempPath] = getStandardPaths(); |
| 209 |
|
| 210 |
if (mConfig.contains("SafeMode")) { |
| 211 |
if (startSafeMode(mConfig)) { |
| 212 |
// If we're in safe mode, don't try to set any directories here, they've been overridden |
| 213 |
// by temp directories in the SafeMode setup. |
| 214 |
return; |
| 215 |
} |
| 216 |
} |
| 217 |
|
| 218 |
// User home path |
| 219 |
// |
| 220 |
fs::path homePath = findUserHomePath(customHome); |
| 221 |
mConfig["UserHomePath"] = Base::FileInfo::pathToString(homePath); |
| 222 |
_userHome = homePath; |
| 223 |
|
| 224 |
// the old path name to save config and data files |
| 225 |
std::vector<std::string> subdirs; |
| 226 |
if (keepDeprecatedPaths) { |
| 227 |
configHome = homePath; |
| 228 |
dataHome = homePath; |
| 229 |
cacheHome = homePath; |
| 230 |
getOldDataLocation(mConfig, subdirs); |
| 231 |
} |
| 232 |
else { |
| 233 |
getSubDirectories(mConfig, subdirs); |
| 234 |
} |
| 235 |
|
| 236 |
|
| 237 |
// User data path |
| 238 |
// |
| 239 |
auto dataSubdirs = subdirs; |
| 240 |
appendVersionIfPossible(dataHome, dataSubdirs, MissingDirectoryBehavior::doNotAppend); |
| 241 |
fs::path data = findPath(dataHome, customData, dataSubdirs, true); |
| 242 |
_userAppData = data; |
| 243 |
mConfig["UserAppData"] = Base::FileInfo::pathToString(data) + PATHSEP; |
| 244 |
|
| 245 |
|
| 246 |
// User config path |
| 247 |
// |
| 248 |
auto configSubdirs = subdirs; |
| 249 |
appendVersionIfPossible(configHome, configSubdirs, MissingDirectoryBehavior::doNotAppend); |
| 250 |
fs::path config = findPath(configHome, customHome, configSubdirs, true); |
| 251 |
_userConfig = config; |
| 252 |
mConfig["UserConfigPath"] = Base::FileInfo::pathToString(config) + PATHSEP; |
| 253 |
|
| 254 |
|
| 255 |
// User cache path |
| 256 |
// |
| 257 |
std::vector<std::string> cacheDirs = subdirs; |
| 258 |
appendVersionIfPossible(cacheHome, cacheDirs, MissingDirectoryBehavior::create); |
| 259 |
cacheDirs.emplace_back("Cache"); |
| 260 |
fs::path cache = findPath(cacheHome, customTemp, cacheDirs, true); |
| 261 |
_userCache = cache; |
| 262 |
mConfig["UserCachePath"] = Base::FileInfo::pathToString(cache) + PATHSEP; |
| 263 |
|
| 264 |
|
| 265 |
// Set application temporary directory |
| 266 |
// |
| 267 |
std::vector<std::string> empty; |
| 268 |
fs::path tmp = findPath(tempPath, customTemp, empty, true); |
| 269 |
_temp = tmp; |
| 270 |
mConfig["AppTempPath"] = Base::FileInfo::pathToString(tmp) + PATHSEP; |
| 271 |
|
| 272 |
|
| 273 |
// Set the default macro directory |
| 274 |
// |
| 275 |
std::vector<std::string> macrodirs{"Macro"}; |
| 276 |
fs::path macro = findPath(_userAppData, customData, macrodirs, true); |
| 277 |
_userMacro = macro; |
| 278 |
mConfig["UserMacroPath"] = Base::FileInfo::pathToString(macro) + PATHSEP; |
| 279 |
} |
| 280 |
|
| 281 |
bool ApplicationDirectories::startSafeMode(std::map<std::string,std::string>& mConfig) |
| 282 |
{ |
| 283 |
SafeMode::StartSafeMode(); |
| 284 |
if (SafeMode::SafeModeEnabled()) { |
| 285 |
_userAppData = mConfig["UserAppData"]; |
| 286 |
_userConfig = mConfig["UserConfigPath"]; |
| 287 |
_userCache = mConfig["UserCachePath"]; |
| 288 |
_temp = mConfig["AppTempPath"]; |
| 289 |
_userMacro = mConfig["UserMacroPath"]; |
| 290 |
_userHome = mConfig["UserHomePath"]; |
| 291 |
_usingCustomDirectories = true; |
| 292 |
return true; |
| 293 |
} |
| 294 |
return false; |
| 295 |
} |
| 296 |
|
| 297 |
std::filesystem::path ApplicationDirectories::sanitizePath(const std::string& pathAsString) |
| 298 |
{ |
| 299 |
size_t positionOfFirstNull = pathAsString.find('\0'); |
| 300 |
if (positionOfFirstNull != std::string::npos) { |
| 301 |
return {pathAsString.substr(0, positionOfFirstNull)}; |
| 302 |
} |
| 303 |
return {pathAsString}; |
| 304 |
} |
| 305 |
|
| 306 |
void ApplicationDirectories::configureResourceDirectory(const std::map<std::string,std::string>& mConfig) { |
| 307 |
#ifdef RESOURCEDIR |
| 308 |
// #6892: Conda may inject null characters |
| 309 |
fs::path path = sanitizePath(RESOURCEDIR); |
| 310 |
if (path.is_absolute()) { |
| 311 |
_resource = path; |
| 312 |
} else { |
| 313 |
_resource = Base::FileInfo::stringToPath(mConfig.at("AppHomePath")) / path; |
| 314 |
} |
| 315 |
#else |
| 316 |
_resource = Base::FileInfo::stringToPath(mConfig.at("AppHomePath")); |
| 317 |
#endif |
| 318 |
} |
| 319 |
|
| 320 |
void ApplicationDirectories::configureLibraryDirectory(const std::map<std::string,std::string>& mConfig) { |
| 321 |
#ifdef LIBRARYDIR |
| 322 |
// #6892: Conda may inject null characters |
| 323 |
fs::path path = sanitizePath(LIBRARYDIR); |
| 324 |
if (path.is_absolute()) { |
| 325 |
_library = path; |
| 326 |
} else { |
| 327 |
_library = Base::FileInfo::stringToPath(mConfig.at("AppHomePath")) / path; |
| 328 |
} |
| 329 |
#else |
| 330 |
_library = Base::FileInfo::stringToPath(mConfig.at("AppHomePath")) / "lib"; |
| 331 |
#endif |
| 332 |
} |
| 333 |
|
| 334 |
|
| 335 |
void ApplicationDirectories::configureHelpDirectory(const std::map<std::string,std::string>& mConfig) |
| 336 |
{ |
| 337 |
#ifdef DOCDIR |
| 338 |
// #6892: Conda may inject null characters |
| 339 |
fs::path path = sanitizePath(DOCDIR); |
| 340 |
if (path.is_absolute()) { |
| 341 |
_help = path; |
| 342 |
} else { |
| 343 |
_help = Base::FileInfo::stringToPath(mConfig.at("AppHomePath")) / path; |
| 344 |
} |
| 345 |
#else |
| 346 |
_help = Base::FileInfo::stringToPath(mConfig.at("DocPath")); |
| 347 |
#endif |
| 348 |
} |
| 349 |
|
| 350 |
|
| 351 |
fs::path ApplicationDirectories::getUserHome() |
| 352 |
{ |
| 353 |
fs::path path; |
| 354 |
#if defined(FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_BSD) || defined(FC_OS_MACOSX) |
| 355 |
// Default paths for the user-specific stuff |
| 356 |
struct passwd pwd {}; |
| 357 |
struct passwd *result {}; |
| 358 |
constexpr std::size_t bufferLength = 16384; |
| 359 |
std::vector<char> buffer(bufferLength); |
| 360 |
const int error = getpwuid_r(getuid(), &pwd, buffer.data(), buffer.size(), &result); |
| 361 |
if (!result || error != 0) { |
| 362 |
throw Base::RuntimeError("Getting HOME path from system failed!"); |
| 363 |
} |
| 364 |
std::string sanitizedPath = sanitizePath(pwd.pw_dir); |
| 365 |
path = Base::FileInfo::stringToPath(sanitizedPath); |
| 366 |
#else |
| 367 |
path = Base::FileInfo::stringToPath(QStandardPaths::writableLocation(QStandardPaths::HomeLocation).toStdString()); |
| 368 |
#endif |
| 369 |
return path; |
| 370 |
} |
| 371 |
|
| 372 |
bool ApplicationDirectories::usingCustomDirectories() const |
| 373 |
{ |
| 374 |
return _usingCustomDirectories; |
| 375 |
} |
| 376 |
|
| 377 |
#if defined(FC_OS_WIN32) // This is ONLY used on Windows now, so don't even compile it elsewhere |
| 378 |
#include <codecvt> |
| 379 |
#include "ShlObj.h" |
| 380 |
QString ApplicationDirectories::getOldGenericDataLocation() |
| 381 |
{ |
| 382 |
WCHAR szPath[MAX_PATH]; |
| 383 |
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter; |
| 384 |
if (SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_APPDATA, NULL, 0, szPath))) { |
| 385 |
return QString::fromStdString(converter.to_bytes(szPath)); |
| 386 |
} |
| 387 |
return {}; |
| 388 |
} |
| 389 |
#endif |
| 390 |
|
| 391 |
void ApplicationDirectories::getSubDirectories(const std::map<std::string,std::string>& mConfig, |
| 392 |
std::vector<std::string>& appData) |
| 393 |
{ |
| 394 |
// If 'AppDataSkipVendor' is defined, the value of 'ExeVendor' must not be part of |
| 395 |
// the path. |
| 396 |
if (!mConfig.contains("AppDataSkipVendor") && mConfig.contains("ExeVendor")) { |
| 397 |
appData.push_back(mConfig.at("ExeVendor")); |
| 398 |
} |
| 399 |
appData.push_back(mConfig.at("ExeName")); |
| 400 |
} |
| 401 |
|
| 402 |
void ApplicationDirectories::getOldDataLocation(const std::map<std::string,std::string>& mConfig, |
| 403 |
std::vector<std::string>& appData) |
| 404 |
{ |
| 405 |
// The name of the directory where the parameters are stored should be the name of |
| 406 |
// the application (for branding reasons). |
| 407 |
#if defined(FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_BSD) |
| 408 |
// If 'AppDataSkipVendor' is defined, the value of 'ExeVendor' must not be part of |
| 409 |
// the path. |
| 410 |
if (!mConfig.contains("AppDataSkipVendor")) { |
| 411 |
appData.push_back(std::string(".") + mConfig.at("ExeVendor")); |
| 412 |
appData.push_back(mConfig.at("ExeName")); |
| 413 |
} else { |
| 414 |
appData.push_back(std::string(".") + mConfig.at("ExeName")); |
| 415 |
} |
| 416 |
|
| 417 |
#elif defined(FC_OS_MACOSX) || defined(FC_OS_WIN32) |
| 418 |
getSubDirectories(mConfig, appData); |
| 419 |
#endif |
| 420 |
} |
| 421 |
|
| 422 |
fs::path ApplicationDirectories::findUserHomePath(const fs::path& userHome) |
| 423 |
{ |
| 424 |
return userHome.empty() ? getUserHome() : userHome; |
| 425 |
} |
| 426 |
|
| 427 |
std::tuple<fs::path, fs::path, fs::path> ApplicationDirectories::getCustomPaths() |
| 428 |
{ |
| 429 |
const QProcessEnvironment env(QProcessEnvironment::systemEnvironment()); |
| 430 |
QString userHome = env.value(QStringLiteral("FREECAD_USER_HOME")); |
| 431 |
QString userData = env.value(QStringLiteral("FREECAD_USER_DATA")); |
| 432 |
QString userTemp = env.value(QStringLiteral("FREECAD_USER_TEMP")); |
| 433 |
|
| 434 |
auto toNativePath = [](QString& path) { |
| 435 |
if (!path.isEmpty()) { |
| 436 |
if (const QDir dir(path); dir.exists()) { |
| 437 |
path = QDir::toNativeSeparators(dir.canonicalPath()); |
| 438 |
} |
| 439 |
else { |
| 440 |
path.clear(); |
| 441 |
} |
| 442 |
} |
| 443 |
}; |
| 444 |
|
| 445 |
// verify env. variables |
| 446 |
toNativePath(userHome); |
| 447 |
toNativePath(userData); |
| 448 |
toNativePath(userTemp); |
| 449 |
|
| 450 |
// if FREECAD_USER_HOME is set but not FREECAD_USER_DATA |
| 451 |
if (!userHome.isEmpty() && userData.isEmpty()) { |
| 452 |
userData = userHome; |
| 453 |
} |
| 454 |
|
| 455 |
// if FREECAD_USER_HOME is set but not FREECAD_USER_TEMP |
| 456 |
if (!userHome.isEmpty() && userTemp.isEmpty()) { |
| 457 |
const QDir dir(userHome); |
| 458 |
dir.mkdir(QStringLiteral("temp")); |
| 459 |
const QFileInfo fi(dir, QStringLiteral("temp")); |
| 460 |
userTemp = fi.absoluteFilePath(); |
| 461 |
} |
| 462 |
|
| 463 |
return {qstringToPath(userHome), |
| 464 |
qstringToPath(userData), |
| 465 |
qstringToPath(userTemp)}; |
| 466 |
} |
| 467 |
|
| 468 |
std::tuple<fs::path, fs::path, fs::path, fs::path> ApplicationDirectories::getStandardPaths() |
| 469 |
{ |
| 470 |
QString configHome = QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation); |
| 471 |
QString dataHome = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation); |
| 472 |
QString cacheHome = QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation); |
| 473 |
QString tempPath = QStandardPaths::writableLocation(QStandardPaths::TempLocation); |
| 474 |
|
| 475 |
// Keep the old behaviour |
| 476 |
#if defined(FC_OS_WIN32) |
| 477 |
configHome = getOldGenericDataLocation(); |
| 478 |
dataHome = configHome; |
| 479 |
|
| 480 |
// On systems with non-7-bit-ASCII application data directories, |
| 481 |
// GetTempPathW will return a path in DOS format. This path will be |
| 482 |
// accepted by boost's file_lock class. |
| 483 |
// Since boost 1.76, there is now a version that accepts a wide string. |
| 484 |
#if (BOOST_VERSION < 107600) |
| 485 |
tempPath = QString::fromStdString(Base::FileInfo::getTempPath()); |
| 486 |
cacheHome = tempPath; |
| 487 |
#endif |
| 488 |
#endif |
| 489 |
|
| 490 |
return {qstringToPath(configHome), |
| 491 |
qstringToPath(dataHome), |
| 492 |
qstringToPath(cacheHome), |
| 493 |
qstringToPath(tempPath)}; |
| 494 |
} |
| 495 |
|
| 496 |
|
| 497 |
|
| 498 |
std::string ApplicationDirectories::versionStringForPath(int major, int minor) |
| 499 |
{ |
| 500 |
// NOTE: This is intended to be stable over time, so if the format changes, a condition should be added to check for |
| 501 |
// older versions and return this format for them, even if the new format differs. |
| 502 |
return fmt::format("v{}-{}", major, minor); |
| 503 |
} |
| 504 |
|
| 505 |
bool ApplicationDirectories::isVersionedPath(const fs::path &startingPath) const { |
| 506 |
for (int major = std::get<0>(_currentVersion); major >= 1; --major) { |
| 507 |
constexpr int largestPossibleMinor = 99; // We have to start someplace |
| 508 |
int startingMinor = largestPossibleMinor; |
| 509 |
if (major == std::get<0>(_currentVersion)) { |
| 510 |
startingMinor = std::get<1>(_currentVersion); |
| 511 |
} |
| 512 |
for (int minor = startingMinor; minor >= 0; --minor) { |
| 513 |
if (startingPath.filename() == versionStringForPath(major, minor)) { |
| 514 |
return true; |
| 515 |
} |
| 516 |
} |
| 517 |
} |
| 518 |
return false; |
| 519 |
} |
| 520 |
|
| 521 |
std::string ApplicationDirectories::mostRecentAvailableConfigVersion(const fs::path &startingPath) const { |
| 522 |
for (int major = std::get<0>(_currentVersion); major >= 1; --major) { |
| 523 |
constexpr int largestPossibleMinor = 99; // We have to start someplace |
| 524 |
int startingMinor = largestPossibleMinor; |
| 525 |
if (major == std::get<0>(_currentVersion)) { |
| 526 |
startingMinor = std::get<1>(_currentVersion); |
| 527 |
} |
| 528 |
for (int minor = startingMinor; minor >= 0; --minor) { |
| 529 |
auto version = startingPath / versionStringForPath(major, minor); |
| 530 |
if (fs::is_directory(version)) { |
| 531 |
return versionStringForPath(major, minor); |
| 532 |
} |
| 533 |
} |
| 534 |
} |
| 535 |
return ""; |
| 536 |
} |
| 537 |
|
| 538 |
fs::path ApplicationDirectories::mostRecentConfigFromBase(const fs::path &startingPath) const { |
| 539 |
// Starting in FreeCAD v1.1, we switched to using a versioned config path for the three configuration |
| 540 |
// directories: |
| 541 |
// UserAppData |
| 542 |
// UserConfigPath |
| 543 |
// UserMacroPath |
| 544 |
// |
| 545 |
// Migration to the versioned structured is NOT automatic: at the App level, we just find the most |
| 546 |
// recent directory and use it, regardless of which version of the program is currently running. |
| 547 |
// It is up to user-facing code in Gui to determine whether to ask a user if they want to migrate |
| 548 |
// and to call the App-level functions that do that work. |
| 549 |
|
| 550 |
// The simplest and most common case is if the current version subfolder already exists |
| 551 |
auto current = startingPath / versionStringForPath(std::get<0>(_currentVersion), std::get<1>(_currentVersion)); |
| 552 |
if (fs::is_directory(current)) { |
| 553 |
return current; |
| 554 |
} |
| 555 |
|
| 556 |
// If the current version doesn't exist, see if a previous version does |
| 557 |
std::string bestVersion = mostRecentAvailableConfigVersion(startingPath); |
| 558 |
if (!bestVersion.empty()) { |
| 559 |
return startingPath / bestVersion; |
| 560 |
} |
| 561 |
return startingPath; // No versioned config found |
| 562 |
} |
| 563 |
|
| 564 |
bool ApplicationDirectories::usingCurrentVersionConfig(fs::path config) const { |
| 565 |
if (config.filename().empty()) { |
| 566 |
config = config.parent_path(); |
| 567 |
} |
| 568 |
auto version = Base::FileInfo::pathToString(config.filename()); |
| 569 |
return version == versionStringForPath(std::get<0>(_currentVersion), std::get<1>(_currentVersion)); |
| 570 |
} |
| 571 |
|
| 572 |
ApplicationDirectories::MigrationResult ApplicationDirectories::migrateConfig( |
| 573 |
const fs::path& oldPath, |
| 574 |
const fs::path& newPath) |
| 575 |
{ |
| 576 |
MigrationResult result; |
| 577 |
fs::create_directories(newPath); |
| 578 |
std::error_code errorCode; |
| 579 |
for (auto& file : fs::directory_iterator(oldPath, errorCode)) { |
| 580 |
if (file == newPath) { |
| 581 |
// Handle the case where newPath is a subdirectory of oldPath |
| 582 |
continue; |
| 583 |
} |
| 584 |
auto sourcePath = file.path(); |
| 585 |
auto pathString = Base::FileInfo::pathToString(sourcePath); |
| 586 |
|
| 587 |
if (file.is_symlink(errorCode)) { |
| 588 |
auto target = fs::read_symlink(sourcePath, errorCode); |
| 589 |
if (errorCode || !fs::exists(target, errorCode)) { |
| 590 |
Base::Console().warning("Migration: skipping broken symlink '%s'\n", |
| 591 |
pathString.c_str()); |
| 592 |
result.failedPaths.push_back(sourcePath); |
| 593 |
continue; |
| 594 |
} |
| 595 |
} |
| 596 |
|
| 597 |
try { |
| 598 |
fs::copy(sourcePath, |
| 599 |
newPath / sourcePath.filename(), |
| 600 |
fs::copy_options::recursive | fs::copy_options::copy_symlinks); |
| 601 |
} |
| 602 |
catch (const fs::filesystem_error& error) { |
| 603 |
Base::Console().warning("Migration: failed to copy '%s': %s\n", |
| 604 |
pathString.c_str(), |
| 605 |
error.what()); |
| 606 |
result.failedPaths.push_back(sourcePath); |
| 607 |
} |
| 608 |
} |
| 609 |
if (errorCode) { |
| 610 |
Base::Console().warning("Migration: error iterating '%s': %s\n", |
| 611 |
Base::FileInfo::pathToString(oldPath).c_str(), |
| 612 |
errorCode.message().c_str()); |
| 613 |
} |
| 614 |
return result; |
| 615 |
} |
| 616 |
|
| 617 |
ApplicationDirectories::MigrationResult ApplicationDirectories::migrateAllPaths( |
| 618 |
const std::vector<fs::path>& paths) const |
| 619 |
{ |
| 620 |
MigrationResult allResult; |
| 621 |
auto [major, minor] = _currentVersion; |
| 622 |
std::set<fs::path> uniquePaths(paths.begin(), paths.end()); |
| 623 |
for (auto path : uniquePaths) { |
| 624 |
if (path.filename().empty()) { |
| 625 |
// Handle the case where the path was constructed from a std::string with a trailing / |
| 626 |
path = path.parent_path(); |
| 627 |
} |
| 628 |
fs::path newPath; |
| 629 |
if (isVersionedPath(path)) { |
| 630 |
newPath = path.parent_path() / versionStringForPath(major, minor); |
| 631 |
} |
| 632 |
else { |
| 633 |
newPath = path / versionStringForPath(major, minor); |
| 634 |
} |
| 635 |
Base::Console().message("Migrating config from %s to %s\n", |
| 636 |
Base::FileInfo::pathToString(path), |
| 637 |
Base::FileInfo::pathToString(newPath)); |
| 638 |
if (fs::exists(newPath)) { |
| 639 |
continue; // Ignore an existing path: not an error, just a migration that was already done |
| 640 |
} |
| 641 |
fs::create_directories(newPath); |
| 642 |
auto result = migrateConfig(path, newPath); |
| 643 |
allResult.migratedPaths.emplace_back(path, newPath); |
| 644 |
allResult.failedPaths.insert(allResult.failedPaths.end(), |
| 645 |
result.failedPaths.begin(), |
| 646 |
result.failedPaths.end()); |
| 647 |
} |
| 648 |
if (!allResult.failedPaths.empty()) { |
| 649 |
Base::Console().warning("Migration completed with %d skipped file(s). " |
| 650 |
"See warnings above for details.\n", |
| 651 |
static_cast<int>(allResult.failedPaths.size())); |
| 652 |
} |
| 653 |
return allResult; |
| 654 |
} |
| 655 |
|
| 656 |
// TODO: Consider using this for all UNIX-like OSes |
| 657 |
#if defined(__OpenBSD__) |
| 658 |
#include <cstdio> |
| 659 |
#include <cstdlib> |
| 660 |
#include <sys/param.h> |
| 661 |
#include <QCoreApplication> |
| 662 |
|
| 663 |
fs::path ApplicationDirectories::findHomePath(const char* sCall) |
| 664 |
{ |
| 665 |
// We have three ways to start this application either use one of the two executables or |
| 666 |
// import the FreeCAD.so module from a running Python session. In the latter case the |
| 667 |
// Python interpreter is already initialized. |
| 668 |
std::string absPath; |
| 669 |
std::string homePath; |
| 670 |
if (Py_IsInitialized()) { |
| 671 |
// Note: `realpath` is known to cause a buffer overflow because it |
| 672 |
// expands the given path to an absolute path of unknown length. |
| 673 |
// Even setting PATH_MAX does not necessarily solve the problem |
| 674 |
// for sure, but the risk of overflow is rather small. |
| 675 |
char resolved[PATH_MAX]; |
| 676 |
char* path = realpath(sCall, resolved); |
| 677 |
if (path) |
| 678 |
absPath = path; |
| 679 |
} |
| 680 |
else { |
| 681 |
int argc = 1; |
| 682 |
QCoreApplication app(argc, (char**)(&sCall)); |
| 683 |
absPath = QCoreApplication::applicationFilePath().toStdString(); |
| 684 |
} |
| 685 |
|
| 686 |
// should be an absolute path now |
| 687 |
std::string::size_type pos = absPath.find_last_of("/"); |
| 688 |
homePath.assign(absPath,0,pos); |
| 689 |
pos = homePath.find_last_of("/"); |
| 690 |
homePath.assign(homePath,0,pos+1); |
| 691 |
|
| 692 |
return Base::FileInfo::stringToPath(homePath); |
| 693 |
} |
| 694 |
|
| 695 |
#elif defined (FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_BSD) |
| 696 |
#include <cstdio> |
| 697 |
#include <cstdlib> |
| 698 |
#include <sys/param.h> |
| 699 |
#if defined(__FreeBSD__) |
| 700 |
#include <sys/sysctl.h> |
| 701 |
#endif |
| 702 |
|
| 703 |
fs::path ApplicationDirectories::findHomePath(const char* sCall) |
| 704 |
{ |
| 705 |
// We have three ways to start this application either use one of the two executables or |
| 706 |
// import the FreeCAD.so module from a running Python session. In the latter case the |
| 707 |
// Python interpreter is already initialized. |
| 708 |
std::string absPath; |
| 709 |
std::string homePath; |
| 710 |
if (Py_IsInitialized()) { |
| 711 |
// Note: `realpath` is known to cause a buffer overflow because it |
| 712 |
// expands the given path to an absolute path of unknown length. |
| 713 |
// Even setting PATH_MAX does not necessarily solve the problem |
| 714 |
// for sure, but the risk of overflow is rather small. |
| 715 |
char resolved[PATH_MAX]; |
| 716 |
char* path = realpath(sCall, resolved); |
| 717 |
if (path) |
| 718 |
absPath = path; |
| 719 |
} |
| 720 |
else { |
| 721 |
// Find the path of the executable. Theoretically, there could occur a |
| 722 |
// race condition when using readlink, but we only use this method to |
| 723 |
// get the absolute path of the executable to compute the actual home |
| 724 |
// path. In the worst case we simply get q wrong path, and FreeCAD is not |
| 725 |
// able to load its modules. |
| 726 |
char resolved[PATH_MAX]; |
| 727 |
#if defined(FC_OS_BSD) |
| 728 |
int mib[4]; |
| 729 |
mib[0] = CTL_KERN; |
| 730 |
mib[1] = KERN_PROC; |
| 731 |
mib[2] = KERN_PROC_PATHNAME; |
| 732 |
mib[3] = -1; |
| 733 |
size_t cb = sizeof(resolved); |
| 734 |
sysctl(mib, 4, resolved, &cb, NULL, 0); |
| 735 |
int nchars = strlen(resolved); |
| 736 |
#else |
| 737 |
int nchars = readlink("/proc/self/exe", resolved, PATH_MAX); |
| 738 |
#endif |
| 739 |
if (nchars < 0 || nchars >= PATH_MAX) |
| 740 |
throw Base::FileSystemError("Cannot determine the absolute path of the executable"); |
| 741 |
resolved[nchars] = '\0'; // enforce null termination |
| 742 |
absPath = resolved; |
| 743 |
} |
| 744 |
|
| 745 |
// should be an absolute path now |
| 746 |
std::string::size_type pos = absPath.find_last_of("/"); |
| 747 |
homePath.assign(absPath,0,pos); |
| 748 |
pos = homePath.find_last_of("/"); |
| 749 |
homePath.assign(homePath,0,pos+1); |
| 750 |
|
| 751 |
return Base::FileInfo::stringToPath(homePath); |
| 752 |
} |
| 753 |
|
| 754 |
#elif defined(FC_OS_MACOSX) |
| 755 |
#include <mach-o/dyld.h> |
| 756 |
#include <string> |
| 757 |
#include <cstdlib> |
| 758 |
#include <sys/param.h> |
| 759 |
|
| 760 |
fs::path ApplicationDirectories::findHomePath(const char* sCall) |
| 761 |
{ |
| 762 |
// If Python is initialized at this point, then we're being run from |
| 763 |
// MainPy.cpp, which hopefully rewrote argv[0] to point at the |
| 764 |
// FreeCAD shared library. |
| 765 |
if (!Py_IsInitialized()) { |
| 766 |
uint32_t sz = 0; |
| 767 |
|
| 768 |
// function only returns "sz" if the first arg is too small to hold value |
| 769 |
_NSGetExecutablePath(nullptr, &sz); |
| 770 |
|
| 771 |
if (const auto buf = new char[++sz]; _NSGetExecutablePath(buf, &sz) == 0) { |
| 772 |
std::array<char, PATH_MAX> resolved{}; |
| 773 |
const char* path = realpath(buf, resolved.data()); |
| 774 |
delete [] buf; |
| 775 |
|
| 776 |
if (path) { |
| 777 |
const std::string Call(resolved.data()); |
| 778 |
std::string TempHomePath; |
| 779 |
std::string::size_type pos = Call.find_last_of(fs::path::preferred_separator); |
| 780 |
TempHomePath.assign(Call,0,pos); |
| 781 |
pos = TempHomePath.find_last_of(fs::path::preferred_separator); |
| 782 |
TempHomePath.assign(TempHomePath,0,pos+1); |
| 783 |
return Base::FileInfo::stringToPath(TempHomePath); |
| 784 |
} |
| 785 |
} else { |
| 786 |
delete [] buf; |
| 787 |
} |
| 788 |
} |
| 789 |
|
| 790 |
return Base::FileInfo::stringToPath(sCall); |
| 791 |
} |
| 792 |
|
| 793 |
#elif defined (FC_OS_WIN32) |
| 794 |
fs::path ApplicationDirectories::findHomePath(const char* sCall) |
| 795 |
{ |
| 796 |
// We have several ways to start this application: |
| 797 |
// * use one of the two executables |
| 798 |
// * import the FreeCAD.pyd module from a running Python session. In this case the |
| 799 |
// Python interpreter is already initialized. |
| 800 |
// * use a custom dll that links FreeCAD core dlls and that is loaded by its host application |
| 801 |
// In this case the calling name should be set to FreeCADBase.dll or FreeCADApp.dll in order |
| 802 |
// to locate the correct home directory |
| 803 |
wchar_t szFileName [MAX_PATH]; |
| 804 |
QString dll(QString::fromUtf8(sCall)); |
| 805 |
if (Py_IsInitialized() || dll.endsWith(QLatin1String(".dll"))) { |
| 806 |
GetModuleFileNameW(GetModuleHandleA(sCall),szFileName, MAX_PATH-1); |
| 807 |
} |
| 808 |
else { |
| 809 |
GetModuleFileNameW(0, szFileName, MAX_PATH-1); |
| 810 |
} |
| 811 |
|
| 812 |
std::wstring Call(szFileName), homePath; |
| 813 |
std::wstring::size_type pos = Call.find_last_of(fs::path::preferred_separator); |
| 814 |
homePath.assign(Call,0,pos); |
| 815 |
pos = homePath.find_last_of(fs::path::preferred_separator); |
| 816 |
homePath.assign(homePath,0,pos+1); |
| 817 |
|
| 818 |
// fixes #0001638 to avoid loading DLLs from Windows' system directories before FreeCAD's bin folder |
| 819 |
std::wstring binPath = homePath; |
| 820 |
binPath += L"bin"; |
| 821 |
SetDllDirectoryW(binPath.c_str()); |
| 822 |
|
| 823 |
// https://stackoverflow.com/questions/5625884/conversion-of-stdwstring-to-qstring-throws-linker-error |
| 824 |
#ifdef _MSC_VER |
| 825 |
QString str = QString::fromUtf16(reinterpret_cast<const ushort *>(homePath.c_str())); |
| 826 |
#else |
| 827 |
QString str = QString::fromStdWString(homePath); |
| 828 |
#endif |
| 829 |
return qstringToPath(str); |
| 830 |
} |
| 831 |
|
| 832 |
#else |
| 833 |
# error "std::string ApplicationDirectories::findHomePath(const char*) not implemented" |
| 834 |
#endif |
| 835 |
|
| 836 |
std::tuple<int, int> ApplicationDirectories::extractVersionFromConfigMap(const std::map<std::string,std::string> &config) |
| 837 |
{ |
| 838 |
try { |
| 839 |
int major = std::stoi(config.at("BuildVersionMajor")); |
| 840 |
int minor = std::stoi(config.at("BuildVersionMinor")); |
| 841 |
return std::make_tuple(major, minor); |
| 842 |
} catch (const std::exception& e) { |
| 843 |
throw Base::RuntimeError("Failed to parse version from config: " + std::string(e.what())); |
| 844 |
} |
| 845 |
} |