| 1 |
/****************************************************************************** |
| 2 |
This source file is part of the Avogadro project. |
| 3 |
This source code is released under the 3-Clause BSD License, (see "LICENSE"). |
| 4 |
******************************************************************************/ |
| 5 |
|
| 6 |
#include "packagemanager.h" |
| 7 |
#include "tomlparse.h" |
| 8 |
#include "utilities.h" |
| 9 |
|
| 10 |
#include <QtCore/QCryptographicHash> |
| 11 |
#include <QtCore/QDebug> |
| 12 |
#include <QtCore/QDir> |
| 13 |
#include <QtCore/QFile> |
| 14 |
#include <QtCore/QFileInfo> |
| 15 |
#include <QtCore/QProcess> |
| 16 |
#include <QtCore/QStandardPaths> |
| 17 |
#include <QtCore/QThread> |
| 18 |
#include <QtCore/QJsonArray> |
| 19 |
#include <QtCore/QJsonDocument> |
| 20 |
#include <QtCore/QJsonObject> |
| 21 |
#include <QtCore/QJsonParseError> |
| 22 |
#include <QtCore/QSettings> |
| 23 |
|
| 24 |
using namespace Qt::StringLiterals; |
| 25 |
|
| 26 |
namespace Avogadro::QtGui { |
| 27 |
|
| 28 |
PackageManager::PackageManager(QObject* parent) : QObject(parent) {} |
| 29 |
|
| 30 |
PackageManager* PackageManager::instance() |
| 31 |
{ |
| 32 |
static PackageManager instance; |
| 33 |
return &instance; |
| 34 |
} |
| 35 |
|
| 36 |
QStringList PackageManager::featureTypes() |
| 37 |
{ |
| 38 |
return { QStringLiteral("menu-commands"), |
| 39 |
QStringLiteral("electrostatic-models"), |
| 40 |
QStringLiteral("energy-models"), QStringLiteral("file-formats"), |
| 41 |
QStringLiteral("input-generators") }; |
| 42 |
} |
| 43 |
|
| 44 |
QString PackageManager::packageFeatureKey(const QString& packageDir, |
| 45 |
const QString& command, |
| 46 |
const QString& identifier) |
| 47 |
{ |
| 48 |
return packageDir + QLatin1Char('\n') + command + QLatin1Char('\n') + |
| 49 |
identifier; |
| 50 |
} |
| 51 |
|
| 52 |
QJsonObject PackageManager::loadOptionsFromFile(const QString& userOptionsPath) |
| 53 |
{ |
| 54 |
QFile optFile(userOptionsPath); |
| 55 |
if (!optFile.open(QIODevice::ReadOnly)) { |
| 56 |
qWarning() << "PackageManager: could not open user-options file:" |
| 57 |
<< userOptionsPath; |
| 58 |
return {}; |
| 59 |
} |
| 60 |
|
| 61 |
const QByteArray optContent = optFile.readAll(); |
| 62 |
if (userOptionsPath.endsWith(QLatin1String(".toml"), Qt::CaseInsensitive)) { |
| 63 |
bool ok = false; |
| 64 |
const QJsonObject opts = parseTomlToJson(optContent, &ok); |
| 65 |
if (!ok) { |
| 66 |
qWarning() << "PackageManager: failed to parse TOML user-options file:" |
| 67 |
<< userOptionsPath; |
| 68 |
return {}; |
| 69 |
} |
| 70 |
return opts; |
| 71 |
} |
| 72 |
|
| 73 |
QJsonParseError err; |
| 74 |
const QJsonDocument doc = QJsonDocument::fromJson(optContent, &err); |
| 75 |
if (err.error != QJsonParseError::NoError) { |
| 76 |
qWarning() << "PackageManager: failed to parse user-options JSON:" |
| 77 |
<< userOptionsPath << err.errorString(); |
| 78 |
return {}; |
| 79 |
} |
| 80 |
// Accept either a bare array (new style, multiple tabs) or a wrapping |
| 81 |
// object (old style, with a "userOptions" key). A bare array is normalised |
| 82 |
// to {"userOptions": <array>} so the rest of the code sees a uniform object. |
| 83 |
if (doc.isArray()) { |
| 84 |
QJsonObject wrapped; |
| 85 |
wrapped.insert(QStringLiteral("userOptions"), doc.array()); |
| 86 |
return wrapped; |
| 87 |
} else if (doc.isObject()) { |
| 88 |
QJsonObject wrapped; |
| 89 |
wrapped.insert(QStringLiteral("userOptions"), doc.object()); |
| 90 |
return wrapped; |
| 91 |
} |
| 92 |
|
| 93 |
if (!doc.isObject()) { |
| 94 |
qWarning() << "PackageManager: user-options JSON root is not an object or" |
| 95 |
" array:" |
| 96 |
<< userOptionsPath; |
| 97 |
return {}; |
| 98 |
} |
| 99 |
|
| 100 |
return doc.object(); |
| 101 |
} |
| 102 |
|
| 103 |
void PackageManager::mergeOptionsFromFile(QJsonObject& opts, |
| 104 |
const QString& userOptionsPath) |
| 105 |
{ |
| 106 |
const QJsonObject fileOpts = loadOptionsFromFile(userOptionsPath); |
| 107 |
for (auto it = fileOpts.constBegin(); it != fileOpts.constEnd(); ++it) |
| 108 |
opts.insert(it.key(), it.value()); |
| 109 |
} |
| 110 |
|
| 111 |
// Locate an installed console script inside a pixi or venv environment. |
| 112 |
static QString findInstalledScript(const QString& packageDir, |
| 113 |
const QString& scriptName, bool isPixi) |
| 114 |
{ |
| 115 |
#ifdef Q_OS_WIN |
| 116 |
const QString binDir = |
| 117 |
packageDir + (isPixi ? QStringLiteral("/.pixi/envs/default/Scripts") |
| 118 |
: QStringLiteral("/.venv/Scripts")); |
| 119 |
const QStringList exeSuffixes = { QStringLiteral(".exe"), QString() }; |
| 120 |
#else |
| 121 |
const QString binDir = |
| 122 |
packageDir + (isPixi ? QStringLiteral("/.pixi/envs/default/bin") |
| 123 |
: QStringLiteral("/.venv/bin")); |
| 124 |
const QStringList exeSuffixes = { QString() }; |
| 125 |
#endif |
| 126 |
|
| 127 |
for (const QString& suffix : exeSuffixes) { |
| 128 |
const QString candidate = binDir + QLatin1Char('/') + scriptName + suffix; |
| 129 |
if (QFileInfo(candidate).isExecutable()) |
| 130 |
return candidate; |
| 131 |
} |
| 132 |
return {}; |
| 133 |
} |
| 134 |
|
| 135 |
QJsonObject PackageManager::loadOptionsFromScript(const QString& packageDir, |
| 136 |
const QString& command, |
| 137 |
const QString& identifier) |
| 138 |
{ |
| 139 |
// Locate pixi or the venv-installed script. |
| 140 |
#ifdef Q_OS_WIN |
| 141 |
QString pixiName = QStringLiteral("pixi.exe"); |
| 142 |
#else |
| 143 |
QString pixiName = QStringLiteral("pixi"); |
| 144 |
#endif |
| 145 |
QString pixiDir = Utilities::findExecutablePath(pixiName); |
| 146 |
QString pixiExe = pixiDir.isEmpty() ? QString() : pixiDir + '/' + pixiName; |
| 147 |
QProcess proc; |
| 148 |
proc.setWorkingDirectory(packageDir); |
| 149 |
|
| 150 |
QStringList userOptsArgs; |
| 151 |
if (!identifier.isEmpty()) |
| 152 |
userOptsArgs << identifier; |
| 153 |
userOptsArgs << QStringLiteral("--user-options"); |
| 154 |
|
| 155 |
if (!pixiExe.isEmpty()) { |
| 156 |
QStringList pixiArgs = { QStringLiteral("run"), QStringLiteral("--as-is"), |
| 157 |
command }; |
| 158 |
pixiArgs << userOptsArgs; |
| 159 |
proc.start(pixiExe, pixiArgs); |
| 160 |
} else { |
| 161 |
// Try the venv-installed script directly. |
| 162 |
QString scriptExe = findInstalledScript(packageDir, command, false); |
| 163 |
if (scriptExe.isEmpty()) { |
| 164 |
qWarning() << "PackageManager: cannot find pixi or venv script for" |
| 165 |
<< command << "in" << packageDir; |
| 166 |
return {}; |
| 167 |
} |
| 168 |
proc.start(scriptExe, userOptsArgs); |
| 169 |
} |
| 170 |
|
| 171 |
// Plugins may always expect some valid JSON as input over stdin, even if it's |
| 172 |
// just an empty object |
| 173 |
QByteArray scriptStdin = "{}"_ba; |
| 174 |
proc.write(scriptStdin); |
| 175 |
// Python |
| 176 |
proc.closeWriteChannel(); |
| 177 |
|
| 178 |
constexpr int timeoutMs = 30000; // 30 seconds |
| 179 |
if (!proc.waitForStarted(timeoutMs)) { |
| 180 |
qWarning() << "PackageManager: --user-options script could not start:" |
| 181 |
<< proc.errorString(); |
| 182 |
return {}; |
| 183 |
} |
| 184 |
if (!proc.waitForFinished(timeoutMs)) { |
| 185 |
qWarning() << "PackageManager: --user-options script timed out for" |
| 186 |
<< packageDir; |
| 187 |
proc.kill(); |
| 188 |
return {}; |
| 189 |
} |
| 190 |
if (proc.exitCode() != 0) { |
| 191 |
qWarning() << "PackageManager: --user-options script failed for" |
| 192 |
<< packageDir << ":" |
| 193 |
<< QString::fromUtf8(proc.readAllStandardError()); |
| 194 |
return {}; |
| 195 |
} |
| 196 |
|
| 197 |
const QByteArray output = proc.readAllStandardOutput(); |
| 198 |
QJsonParseError err; |
| 199 |
const QJsonDocument doc = QJsonDocument::fromJson(output, &err); |
| 200 |
if (err.error != QJsonParseError::NoError) { |
| 201 |
qWarning() << "PackageManager: failed to parse --user-options JSON from" |
| 202 |
<< command << ":" << err.errorString(); |
| 203 |
return {}; |
| 204 |
} |
| 205 |
|
| 206 |
if (doc.isArray()) { |
| 207 |
QJsonObject wrapped; |
| 208 |
wrapped.insert(QStringLiteral("userOptions"), doc.array()); |
| 209 |
return wrapped; |
| 210 |
} |
| 211 |
|
| 212 |
if (!doc.isObject()) { |
| 213 |
qWarning() << "PackageManager: --user-options output is not an object or" |
| 214 |
" array from" |
| 215 |
<< command; |
| 216 |
return {}; |
| 217 |
} |
| 218 |
|
| 219 |
return doc.object(); |
| 220 |
} |
| 221 |
|
| 222 |
QJsonObject PackageManager::resolveUserOptions(const QString& userOptionsValue, |
| 223 |
const QString& packageDir, |
| 224 |
const QString& command, |
| 225 |
const QString& identifier) |
| 226 |
{ |
| 227 |
if (userOptionsValue.isEmpty()) |
| 228 |
return {}; |
| 229 |
|
| 230 |
QJsonObject result; |
| 231 |
if (userOptionsValue == QLatin1String("dynamic")) |
| 232 |
result = loadOptionsFromScript(packageDir, command, identifier); |
| 233 |
else |
| 234 |
result = loadOptionsFromFile(packageDir + '/' + userOptionsValue); |
| 235 |
|
| 236 |
// Both loadOptionsFromFile() and loadOptionsFromScript() may wrap a bare |
| 237 |
// array under "userOptions". Unwrap so callers can insert under their own |
| 238 |
// key without double-nesting. |
| 239 |
if (result.contains(QStringLiteral("userOptions"))) { |
| 240 |
QJsonValue val = result.value(QStringLiteral("userOptions")); |
| 241 |
if (val.isObject()) |
| 242 |
return val.toObject(); |
| 243 |
// Value is an array; return wrapped form for caller to handle. |
| 244 |
return result; |
| 245 |
} |
| 246 |
|
| 247 |
return result; |
| 248 |
} |
| 249 |
|
| 250 |
static bool hasNonExecutablePixiPython(const QString& packageDir) |
| 251 |
{ |
| 252 |
#ifdef Q_OS_WIN |
| 253 |
const QStringList pythonDirs = { |
| 254 |
packageDir + QStringLiteral("/.pixi/envs/default/Scripts"), |
| 255 |
packageDir + QStringLiteral("/.pixi/envs/default/bin") |
| 256 |
}; |
| 257 |
#else |
| 258 |
const QStringList pythonDirs = { packageDir + |
| 259 |
QStringLiteral("/.pixi/envs/default/bin") }; |
| 260 |
#endif |
| 261 |
|
| 262 |
for (const QString& dirPath : pythonDirs) { |
| 263 |
QDir dir(dirPath); |
| 264 |
if (!dir.exists()) |
| 265 |
continue; |
| 266 |
|
| 267 |
const QFileInfoList candidates = |
| 268 |
dir.entryInfoList(QStringList() << QStringLiteral("python*"), |
| 269 |
QDir::Files | QDir::NoDotAndDotDot); |
| 270 |
if (candidates.isEmpty()) |
| 271 |
continue; |
| 272 |
|
| 273 |
for (const QFileInfo& candidate : candidates) { |
| 274 |
if (!candidate.isExecutable()) |
| 275 |
return true; |
| 276 |
} |
| 277 |
} |
| 278 |
|
| 279 |
return false; |
| 280 |
} |
| 281 |
|
| 282 |
// --------------------------------------------------------------------------- |
| 283 |
// QSettings serialisation helpers (features stored as JSON) |
| 284 |
// --------------------------------------------------------------------------- |
| 285 |
|
| 286 |
QJsonObject PackageManager::featureEntryToJson(const FeatureEntry& entry) |
| 287 |
{ |
| 288 |
QJsonObject obj; |
| 289 |
obj[QStringLiteral("type")] = entry.type; |
| 290 |
obj[QStringLiteral("identifier")] = entry.identifier; |
| 291 |
obj[QStringLiteral("metadata")] = QJsonObject::fromVariantMap(entry.metadata); |
| 292 |
return obj; |
| 293 |
} |
| 294 |
|
| 295 |
PackageManager::FeatureEntry PackageManager::featureEntryFromJson( |
| 296 |
const QJsonObject& obj) |
| 297 |
{ |
| 298 |
FeatureEntry entry; |
| 299 |
entry.type = obj[QStringLiteral("type")].toString(); |
| 300 |
entry.identifier = obj[QStringLiteral("identifier")].toString(); |
| 301 |
entry.metadata = obj[QStringLiteral("metadata")].toObject().toVariantMap(); |
| 302 |
return entry; |
| 303 |
} |
| 304 |
|
| 305 |
// --------------------------------------------------------------------------- |
| 306 |
// Installation |
| 307 |
// --------------------------------------------------------------------------- |
| 308 |
|
| 309 |
// Read the *-setup script name from [project.scripts], if any. |
| 310 |
static QString readSetupCommand(const QString& packageDir) |
| 311 |
{ |
| 312 |
QString tomlPath = packageDir + QStringLiteral("/pyproject.toml"); |
| 313 |
QFile tomlFile(tomlPath); |
| 314 |
if (!tomlFile.open(QIODevice::ReadOnly)) |
| 315 |
return {}; |
| 316 |
const QByteArray content = tomlFile.readAll(); |
| 317 |
|
| 318 |
bool ok = false; |
| 319 |
const QVariantMap root = |
| 320 |
parseTomlString(std::string_view(content.constData(), content.size()), &ok); |
| 321 |
if (!ok) |
| 322 |
return {}; |
| 323 |
|
| 324 |
const QVariantMap scripts = root.value(QStringLiteral("project")) |
| 325 |
.toMap() |
| 326 |
.value(QStringLiteral("scripts")) |
| 327 |
.toMap(); |
| 328 |
// Only allow script names with safe characters (letters, digits, hyphen, |
| 329 |
// underscore) to prevent path traversal when the name is used to build |
| 330 |
// an executable path. |
| 331 |
auto isSafeScriptName = [](const QString& name) { |
| 332 |
for (const QChar ch : name) { |
| 333 |
const ushort u = ch.unicode(); |
| 334 |
if (!((u >= 'a' && u <= 'z') || (u >= 'A' && u <= 'Z') || |
| 335 |
(u >= '0' && u <= '9') || u == '-' || u == '_')) |
| 336 |
return false; |
| 337 |
} |
| 338 |
return !name.isEmpty(); |
| 339 |
}; |
| 340 |
|
| 341 |
for (auto it = scripts.constBegin(); it != scripts.constEnd(); ++it) { |
| 342 |
if (it.key().startsWith(QStringLiteral("avogadro-")) && |
| 343 |
it.key().endsWith(QStringLiteral("-setup")) && |
| 344 |
isSafeScriptName(it.key())) |
| 345 |
return it.key(); |
| 346 |
} |
| 347 |
return {}; |
| 348 |
} |
| 349 |
|
| 350 |
// Run a package's *-setup script (e.g. to download ML model weights). |
| 351 |
static void runSetupScript(const QString& packageDir, const QString& setupCmd, |
| 352 |
bool isPixi, int timeoutMs) |
| 353 |
{ |
| 354 |
if (setupCmd.isEmpty()) |
| 355 |
return; |
| 356 |
const QString setupExe = findInstalledScript(packageDir, setupCmd, isPixi); |
| 357 |
if (setupExe.isEmpty()) |
| 358 |
return; |
| 359 |
|
| 360 |
QProcess proc; |
| 361 |
proc.setWorkingDirectory(packageDir); |
| 362 |
proc.start(setupExe, {}); |
| 363 |
if (!proc.waitForStarted(timeoutMs)) { |
| 364 |
qWarning() << "setup script could not be started for" << packageDir << ":" |
| 365 |
<< proc.errorString(); |
| 366 |
return; |
| 367 |
} |
| 368 |
if (!proc.waitForFinished(timeoutMs)) { |
| 369 |
qWarning() << "setup script timed out for" << packageDir; |
| 370 |
proc.kill(); |
| 371 |
} else if (proc.exitCode() != 0) { |
| 372 |
qWarning() << "setup script failed for" << packageDir << ":" |
| 373 |
<< QString::fromUtf8(proc.readAllStandardError()); |
| 374 |
} |
| 375 |
} |
| 376 |
|
| 377 |
void PackageManager::installPackages(const QStringList& packageDirs) |
| 378 |
{ |
| 379 |
#ifdef Q_OS_WIN |
| 380 |
const QString pixiName = QStringLiteral("pixi.exe"); |
| 381 |
const QStringList pythonNames = { QStringLiteral("python.exe"), |
| 382 |
QStringLiteral("python3.exe") }; |
| 383 |
#else |
| 384 |
const QString pixiName = QStringLiteral("pixi"); |
| 385 |
const QStringList pythonNames = { QStringLiteral("python3"), |
| 386 |
QStringLiteral("python") }; |
| 387 |
#endif |
| 388 |
QString pixiDir = Utilities::findExecutablePath(pixiName); |
| 389 |
QString pixiExe = pixiDir.isEmpty() ? QString() : pixiDir + '/' + pixiName; |
| 390 |
QString pythonExe; |
| 391 |
if (pixiExe.isEmpty()) { |
| 392 |
for (const QString& pythonName : pythonNames) { |
| 393 |
const QString pythonDir = Utilities::findExecutablePath(pythonName); |
| 394 |
if (!pythonDir.isEmpty()) { |
| 395 |
pythonExe = pythonDir + '/' + pythonName; |
| 396 |
break; |
| 397 |
} |
| 398 |
} |
| 399 |
} |
| 400 |
|
| 401 |
// Pre-read setup commands on the main thread so the install thread doesn't |
| 402 |
// need to re-parse pyproject.toml (parsePackage() will read it again later). |
| 403 |
QMap<QString, QString> setupCommands; |
| 404 |
for (const QString& dir : packageDirs) |
| 405 |
setupCommands[dir] = readSetupCommand(dir); |
| 406 |
|
| 407 |
QThread* installThread = |
| 408 |
QThread::create([pixiExe, pythonExe, packageDirs, setupCommands]() { |
| 409 |
constexpr int installTimeoutMs = 10 * 60 * 1000; // 10 minutes |
| 410 |
for (const QString& packageDir : packageDirs) { |
| 411 |
if (pixiExe.isEmpty() && pythonExe.isEmpty()) |
| 412 |
continue; // TODO - give a warning to the user that they need pixi |
| 413 |
|
| 414 |
if (!pixiExe.isEmpty()) { |
| 415 |
// If a copied package includes a non-executable .pixi environment, |
| 416 |
// pixi install fails querying its interpreter. Remove it and |
| 417 |
// recreate. |
| 418 |
const QString pixiDir = packageDir + QStringLiteral("/.pixi"); |
| 419 |
if (hasNonExecutablePixiPython(packageDir)) { |
| 420 |
if (!QDir(pixiDir).removeRecursively()) { |
| 421 |
qWarning() << "Could not remove invalid .pixi directory in" |
| 422 |
<< packageDir; |
| 423 |
} |
| 424 |
} |
| 425 |
|
| 426 |
// Pixi install |
| 427 |
QProcess installProc; |
| 428 |
installProc.setWorkingDirectory(packageDir); |
| 429 |
installProc.start(pixiExe, { QStringLiteral("install") }); |
| 430 |
if (!installProc.waitForFinished(installTimeoutMs)) { |
| 431 |
qWarning() << "pixi install timed out for" << packageDir; |
| 432 |
installProc.kill(); |
| 433 |
continue; |
| 434 |
} |
| 435 |
if (installProc.exitCode() != 0) { |
| 436 |
qWarning() << "pixi install failed for" << packageDir << ":" |
| 437 |
<< QString::fromUtf8(installProc.readAllStandardError()); |
| 438 |
} else { |
| 439 |
// Run the *-setup script if one is declared (e.g. to download ML |
| 440 |
// model weights). |
| 441 |
runSetupScript(packageDir, setupCommands.value(packageDir), true, |
| 442 |
installTimeoutMs); |
| 443 |
} |
| 444 |
} else { |
| 445 |
// Step 1: create a venv |
| 446 |
QProcess venvProc; |
| 447 |
venvProc.setWorkingDirectory(packageDir); |
| 448 |
venvProc.start(pythonExe, |
| 449 |
{ QStringLiteral("-m"), QStringLiteral("venv"), |
| 450 |
QStringLiteral(".venv") }); |
| 451 |
if (!venvProc.waitForFinished(installTimeoutMs)) { |
| 452 |
qWarning() << "venv creation timed out for" << packageDir; |
| 453 |
venvProc.kill(); |
| 454 |
continue; |
| 455 |
} |
| 456 |
if (venvProc.exitCode() != 0) { |
| 457 |
qWarning() << "venv creation failed for" << packageDir << ":" |
| 458 |
<< venvProc.readAllStandardError(); |
| 459 |
continue; |
| 460 |
} |
| 461 |
|
| 462 |
// Step 2: pip install . using the venv's pip |
| 463 |
#ifdef Q_OS_WIN |
| 464 |
QString venvPip = |
| 465 |
packageDir + QStringLiteral("/.venv/Scripts/pip.exe"); |
| 466 |
#else |
| 467 |
QString venvPip = packageDir + QStringLiteral("/.venv/bin/pip"); |
| 468 |
#endif |
| 469 |
QProcess installProc; |
| 470 |
installProc.setWorkingDirectory(packageDir); |
| 471 |
installProc.start(venvPip, |
| 472 |
{ QStringLiteral("install"), QStringLiteral(".") }); |
| 473 |
if (!installProc.waitForFinished(installTimeoutMs)) { |
| 474 |
qWarning() << "pip install timed out for" << packageDir; |
| 475 |
installProc.kill(); |
| 476 |
continue; |
| 477 |
} |
| 478 |
if (installProc.exitCode() != 0) { |
| 479 |
qWarning() << "pip install failed for" << packageDir << ":" |
| 480 |
<< installProc.readAllStandardError(); |
| 481 |
} else { |
| 482 |
// Run the *-setup script if one is declared. |
| 483 |
runSetupScript(packageDir, setupCommands.value(packageDir), false, |
| 484 |
installTimeoutMs); |
| 485 |
} |
| 486 |
} |
| 487 |
} |
| 488 |
}); |
| 489 |
|
| 490 |
connect( |
| 491 |
installThread, &QThread::finished, this, |
| 492 |
[this, packageDirs, installThread]() { |
| 493 |
for (const QString& packageDir : packageDirs) |
| 494 |
registerPackage(packageDir); |
| 495 |
emit packagesInstalled(); |
| 496 |
installThread->deleteLater(); |
| 497 |
}, |
| 498 |
Qt::QueuedConnection); |
| 499 |
|
| 500 |
installThread->start(); |
| 501 |
} |
| 502 |
|
| 503 |
// --------------------------------------------------------------------------- |
| 504 |
// Registration |
| 505 |
// --------------------------------------------------------------------------- |
| 506 |
|
| 507 |
bool PackageManager::registerPackage(const QString& packageDir) |
| 508 |
{ |
| 509 |
PackageInfo info; |
| 510 |
QList<FeatureEntry> features; |
| 511 |
|
| 512 |
if (!parsePackage(packageDir, info, features)) |
| 513 |
return false; |
| 514 |
|
| 515 |
// If already registered, remove old features first |
| 516 |
if (registeredPackages().contains(info.name)) |
| 517 |
unregisterPackage(info.name); |
| 518 |
|
| 519 |
saveToCache(info, features); |
| 520 |
emitFeatures(info, features); |
| 521 |
return true; |
| 522 |
} |
| 523 |
|
| 524 |
bool PackageManager::unregisterPackage(const QString& packageName) |
| 525 |
{ |
| 526 |
PackageInfo info; |
| 527 |
QList<FeatureEntry> features; |
| 528 |
|
| 529 |
if (!loadFromCache(packageName, info, features)) |
| 530 |
return false; |
| 531 |
|
| 532 |
// Notify consumers so they can clean up |
| 533 |
for (const auto& f : features) |
| 534 |
emit featureRemoved(f.type, info.directory, info.command, f.identifier); |
| 535 |
|
| 536 |
removeFromCache(packageName); |
| 537 |
return true; |
| 538 |
} |
| 539 |
|
| 540 |
// --------------------------------------------------------------------------- |
| 541 |
// Directory scanning |
| 542 |
// --------------------------------------------------------------------------- |
| 543 |
|
| 544 |
QStringList PackageManager::scanDirectory(const QString& directoryPath) |
| 545 |
{ |
| 546 |
QStringList result; |
| 547 |
|
| 548 |
QDir dir(directoryPath); |
| 549 |
if (!dir.exists()) { |
| 550 |
#ifndef NDEBUG |
| 551 |
qWarning() << "PackageManager::scanDirectory: directory does not exist:" |
| 552 |
<< directoryPath; |
| 553 |
#endif |
| 554 |
return result; |
| 555 |
} |
| 556 |
|
| 557 |
const QStringList subdirs = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot); |
| 558 |
|
| 559 |
for (const QString& subdir : subdirs) { |
| 560 |
QString packageDir = dir.absoluteFilePath(subdir); |
| 561 |
QString tomlPath = packageDir + QStringLiteral("/pyproject.toml"); |
| 562 |
|
| 563 |
QFile tomlFile(tomlPath); |
| 564 |
if (!tomlFile.exists()) |
| 565 |
continue; |
| 566 |
|
| 567 |
// Compute hash of the current pyproject.toml |
| 568 |
if (!tomlFile.open(QIODevice::ReadOnly)) |
| 569 |
continue; |
| 570 |
QByteArray currentHash = |
| 571 |
QCryptographicHash::hash(tomlFile.readAll(), QCryptographicHash::Sha256) |
| 572 |
.toHex(); |
| 573 |
tomlFile.close(); |
| 574 |
|
| 575 |
// Check if we already have this package with the same hash |
| 576 |
// We need to find the package name — check all registered packages |
| 577 |
bool needsRegistration = true; |
| 578 |
const QStringList known = registeredPackages(); |
| 579 |
for (const QString& name : known) { |
| 580 |
PackageInfo info = packageInfo(name); |
| 581 |
if (QDir(info.directory) == QDir(packageDir)) { |
| 582 |
// Same directory — check the cached hash |
| 583 |
QSettings settings; |
| 584 |
QString prefix = QStringLiteral("plugins/") + name + '/'; |
| 585 |
QByteArray cachedHash = |
| 586 |
settings.value(prefix + "tomlHash").toByteArray(); |
| 587 |
if (cachedHash == currentHash) { |
| 588 |
needsRegistration = false; |
| 589 |
} |
| 590 |
break; |
| 591 |
} |
| 592 |
} |
| 593 |
|
| 594 |
if (needsRegistration) { |
| 595 |
result.append(packageDir); |
| 596 |
} |
| 597 |
} |
| 598 |
|
| 599 |
return result; |
| 600 |
} |
| 601 |
|
| 602 |
// --------------------------------------------------------------------------- |
| 603 |
// Startup |
| 604 |
// --------------------------------------------------------------------------- |
| 605 |
|
| 606 |
void PackageManager::loadRegisteredPackages(const QString& typeFilter) |
| 607 |
{ |
| 608 |
QSettings settings; |
| 609 |
settings.beginGroup(QStringLiteral("plugins")); |
| 610 |
const QStringList names = settings.childGroups(); |
| 611 |
settings.endGroup(); |
| 612 |
|
| 613 |
for (const QString& name : names) { |
| 614 |
PackageInfo info; |
| 615 |
QList<FeatureEntry> features; |
| 616 |
if (!loadFromCache(name, info, features)) |
| 617 |
continue; |
| 618 |
|
| 619 |
if (typeFilter.isEmpty()) { |
| 620 |
emitFeatures(info, features); |
| 621 |
continue; |
| 622 |
} |
| 623 |
|
| 624 |
QList<FeatureEntry> filtered; |
| 625 |
for (const auto& feature : features) { |
| 626 |
if (feature.type == typeFilter) |
| 627 |
filtered.append(feature); |
| 628 |
} |
| 629 |
if (!filtered.isEmpty()) |
| 630 |
emitFeatures(info, filtered); |
| 631 |
} |
| 632 |
} |
| 633 |
|
| 634 |
// --------------------------------------------------------------------------- |
| 635 |
// Queries |
| 636 |
// --------------------------------------------------------------------------- |
| 637 |
|
| 638 |
QStringList PackageManager::registeredPackages() const |
| 639 |
{ |
| 640 |
QSettings settings; |
| 641 |
settings.beginGroup(QStringLiteral("plugins")); |
| 642 |
QStringList names = settings.childGroups(); |
| 643 |
settings.endGroup(); |
| 644 |
return names; |
| 645 |
} |
| 646 |
|
| 647 |
QStringList PackageManager::packageFeatureTypes( |
| 648 |
const QString& packageName) const |
| 649 |
{ |
| 650 |
QSettings settings; |
| 651 |
QString prefix = QStringLiteral("plugins/") + packageName + '/'; |
| 652 |
QByteArray json = settings.value(prefix + "features").toByteArray(); |
| 653 |
QJsonDocument doc = QJsonDocument::fromJson(json); |
| 654 |
if (!doc.isArray()) |
| 655 |
return {}; |
| 656 |
|
| 657 |
QStringList types; |
| 658 |
const QJsonArray arr = doc.array(); |
| 659 |
for (const auto& val : arr) { |
| 660 |
if (!val.isObject()) |
| 661 |
continue; |
| 662 |
const QString type = |
| 663 |
val.toObject().value(QStringLiteral("type")).toString(); |
| 664 |
if (!type.isEmpty() && !types.contains(type)) |
| 665 |
types.append(type); |
| 666 |
} |
| 667 |
return types; |
| 668 |
} |
| 669 |
|
| 670 |
PackageManager::PackageInfo PackageManager::packageInfo( |
| 671 |
const QString& packageName) const |
| 672 |
{ |
| 673 |
PackageInfo info; |
| 674 |
QSettings settings; |
| 675 |
QString prefix = QStringLiteral("plugins/") + packageName + '/'; |
| 676 |
info.name = packageName; |
| 677 |
info.version = settings.value(prefix + "version").toString(); |
| 678 |
info.directory = settings.value(prefix + "directory").toString(); |
| 679 |
info.command = settings.value(prefix + "command").toString(); |
| 680 |
// not really crucial |
| 681 |
info.description = settings.value(prefix + "description").toString(); |
| 682 |
return info; |
| 683 |
} |
| 684 |
|
| 685 |
// --------------------------------------------------------------------------- |
| 686 |
// TOML parsing |
| 687 |
// --------------------------------------------------------------------------- |
| 688 |
|
| 689 |
bool PackageManager::parsePackage(const QString& packageDir, PackageInfo& info, |
| 690 |
QList<FeatureEntry>& features) |
| 691 |
{ |
| 692 |
QString tomlPath = packageDir + QStringLiteral("/pyproject.toml"); |
| 693 |
QFileInfo fi(tomlPath); |
| 694 |
if (!fi.exists() || !fi.isReadable()) { |
| 695 |
qWarning() << "PackageManager: pyproject.toml not found in" << packageDir; |
| 696 |
return false; |
| 697 |
} |
| 698 |
|
| 699 |
QFile tomlFile(tomlPath); |
| 700 |
if (!tomlFile.open(QIODevice::ReadOnly | QIODevice::Text)) |
| 701 |
return false; |
| 702 |
QByteArray content = tomlFile.readAll(); |
| 703 |
|
| 704 |
bool ok = false; |
| 705 |
QVariantMap root = |
| 706 |
parseTomlString(std::string_view(content.constData(), content.size()), &ok); |
| 707 |
if (!ok) { |
| 708 |
qWarning() << "PackageManager: TOML parse error in" << tomlPath; |
| 709 |
return false; |
| 710 |
} |
| 711 |
|
| 712 |
// --- [project] --- |
| 713 |
QVariantMap project = root.value(QStringLiteral("project")).toMap(); |
| 714 |
if (project.isEmpty()) { |
| 715 |
qWarning() << "PackageManager: missing [project] table in" << tomlPath; |
| 716 |
return false; |
| 717 |
} |
| 718 |
|
| 719 |
info.directory = QDir(packageDir).absolutePath(); |
| 720 |
info.name = project.value(QStringLiteral("name")).toString(); |
| 721 |
info.version = project.value(QStringLiteral("version")).toString(); |
| 722 |
// not really crucial |
| 723 |
info.description = project.value(QStringLiteral("description")).toString(); |
| 724 |
|
| 725 |
if (info.name.isEmpty()) { |
| 726 |
qWarning() << "PackageManager: [project.name] is required in" << tomlPath; |
| 727 |
return false; |
| 728 |
} |
| 729 |
|
| 730 |
// --- [project.scripts] → find the avogadro- entry point --- |
| 731 |
// Skip *-setup scripts; those are post-install helpers, not the main command. |
| 732 |
QVariantMap scripts = project.value(QStringLiteral("scripts")).toMap(); |
| 733 |
for (auto it = scripts.constBegin(); it != scripts.constEnd(); ++it) { |
| 734 |
if (it.key().startsWith(QStringLiteral("avogadro-")) && |
| 735 |
!it.key().endsWith(QStringLiteral("-setup"))) { |
| 736 |
if (info.command.isEmpty()) |
| 737 |
info.command = it.key(); |
| 738 |
// in principle we should break, but check for multiple entries |
| 739 |
// and warn about them |
| 740 |
else |
| 741 |
qWarning() << "PackageManager: multiple avogadro-* entry points in" |
| 742 |
<< tomlPath; |
| 743 |
} |
| 744 |
} |
| 745 |
if (info.command.isEmpty()) { |
| 746 |
qWarning() << "PackageManager: no avogadro-* entry in [project.scripts]" |
| 747 |
<< "in" << tomlPath; |
| 748 |
return false; |
| 749 |
} |
| 750 |
|
| 751 |
// --- [tool.avogadro.*] feature arrays --- |
| 752 |
QVariantMap toolAvogadro = root.value(QStringLiteral("tool")) |
| 753 |
.toMap() |
| 754 |
.value(QStringLiteral("avogadro")) |
| 755 |
.toMap(); |
| 756 |
if (toolAvogadro.isEmpty()) { |
| 757 |
qWarning() << "PackageManager: missing [tool.avogadro] in" << tomlPath; |
| 758 |
return false; |
| 759 |
} |
| 760 |
|
| 761 |
const QStringList types = featureTypes(); |
| 762 |
for (const QString& type : types) { |
| 763 |
const QVariantList arr = toolAvogadro.value(type).toList(); |
| 764 |
for (const QVariant& element : arr) { |
| 765 |
QVariantMap table = element.toMap(); |
| 766 |
if (table.isEmpty()) |
| 767 |
continue; |
| 768 |
|
| 769 |
FeatureEntry entry; |
| 770 |
entry.type = type; |
| 771 |
entry.identifier = table.value(QStringLiteral("identifier")).toString(); |
| 772 |
|
| 773 |
if (entry.identifier.isEmpty()) { |
| 774 |
qWarning() << "PackageManager: feature in" << type |
| 775 |
<< "missing identifier, skipping"; |
| 776 |
continue; |
| 777 |
} |
| 778 |
|
| 779 |
// Store the entire table as metadata (identifier is kept for |
| 780 |
// convenience) |
| 781 |
entry.metadata = table; |
| 782 |
features.append(entry); |
| 783 |
} |
| 784 |
} |
| 785 |
|
| 786 |
return true; |
| 787 |
} |
| 788 |
|
| 789 |
// --------------------------------------------------------------------------- |
| 790 |
// Signal emission |
| 791 |
// --------------------------------------------------------------------------- |
| 792 |
|
| 793 |
void PackageManager::emitFeatures(const PackageInfo& info, |
| 794 |
const QList<FeatureEntry>& features) |
| 795 |
{ |
| 796 |
for (const auto& f : features) { |
| 797 |
emit featureRegistered(f.type, info.directory, info.command, f.identifier, |
| 798 |
f.metadata); |
| 799 |
} |
| 800 |
} |
| 801 |
|
| 802 |
// --------------------------------------------------------------------------- |
| 803 |
// QSettings cache |
| 804 |
// --------------------------------------------------------------------------- |
| 805 |
|
| 806 |
void PackageManager::saveToCache(const PackageInfo& info, |
| 807 |
const QList<FeatureEntry>& features) |
| 808 |
{ |
| 809 |
QSettings settings; |
| 810 |
QString prefix = QStringLiteral("plugins/") + info.name + '/'; |
| 811 |
|
| 812 |
settings.setValue(prefix + "directory", info.directory); |
| 813 |
settings.setValue(prefix + "command", info.command); |
| 814 |
settings.setValue(prefix + "version", info.version); |
| 815 |
// not really crucial |
| 816 |
settings.setValue(prefix + "description", info.description); |
| 817 |
|
| 818 |
// Store a hash of pyproject.toml so scanDirectory() can detect changes |
| 819 |
QString tomlPath = info.directory + QStringLiteral("/pyproject.toml"); |
| 820 |
QFile tomlFile(tomlPath); |
| 821 |
if (tomlFile.open(QIODevice::ReadOnly)) { |
| 822 |
QByteArray hash = |
| 823 |
QCryptographicHash::hash(tomlFile.readAll(), QCryptographicHash::Sha256); |
| 824 |
settings.setValue(prefix + "tomlHash", hash.toHex()); |
| 825 |
} |
| 826 |
|
| 827 |
// Serialize features as a JSON array string |
| 828 |
QJsonArray arr; |
| 829 |
for (const auto& f : features) |
| 830 |
arr.append(featureEntryToJson(f)); |
| 831 |
|
| 832 |
settings.setValue(prefix + "features", |
| 833 |
QJsonDocument(arr).toJson(QJsonDocument::Compact)); |
| 834 |
settings.sync(); |
| 835 |
} |
| 836 |
|
| 837 |
void PackageManager::removeFromCache(const QString& packageName) |
| 838 |
{ |
| 839 |
QSettings settings; |
| 840 |
settings.beginGroup(QStringLiteral("plugins")); |
| 841 |
settings.remove(packageName); |
| 842 |
settings.endGroup(); |
| 843 |
settings.sync(); |
| 844 |
} |
| 845 |
|
| 846 |
bool PackageManager::loadFromCache(const QString& packageName, |
| 847 |
PackageInfo& info, |
| 848 |
QList<FeatureEntry>& features) |
| 849 |
{ |
| 850 |
QSettings settings; |
| 851 |
QString prefix = QStringLiteral("plugins/") + packageName + '/'; |
| 852 |
|
| 853 |
info.name = packageName; |
| 854 |
info.directory = settings.value(prefix + "directory").toString(); |
| 855 |
info.command = settings.value(prefix + "command").toString(); |
| 856 |
info.version = settings.value(prefix + "version").toString(); |
| 857 |
info.description = settings.value(prefix + "description").toString(); |
| 858 |
|
| 859 |
if (info.directory.isEmpty() || info.command.isEmpty()) |
| 860 |
return false; |
| 861 |
|
| 862 |
// Verify the package directory still exists and has a pyproject.toml |
| 863 |
QFileInfo pyproject(info.directory + QLatin1String("/pyproject.toml")); |
| 864 |
if (!pyproject.isFile()) { |
| 865 |
removeFromCache(packageName); |
| 866 |
return false; |
| 867 |
} |
| 868 |
|
| 869 |
QByteArray json = settings.value(prefix + "features").toByteArray(); |
| 870 |
QJsonDocument doc = QJsonDocument::fromJson(json); |
| 871 |
if (!doc.isArray()) |
| 872 |
return false; |
| 873 |
|
| 874 |
const QJsonArray arr = doc.array(); |
| 875 |
for (const auto& val : arr) { |
| 876 |
if (val.isObject()) |
| 877 |
features.append(featureEntryFromJson(val.toObject())); |
| 878 |
} |
| 879 |
|
| 880 |
return true; |
| 881 |
} |
| 882 |
|
| 883 |
} // namespace Avogadro::QtGui |