Debian Codegraph @

avogadro/qtplugins/packageinstaller/packagemodel.cpp

raw
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 "packagemodel.h"
7
8 #include <avogadro/core/version.h>
9 #include <avogadro/qtgui/packagemanager.h>
10
11 #include <QtCore/QDateTime>
12 #include <QtCore/QFileInfo>
13 #include <QtCore/QHash>
14 #include <QtCore/QLocale>
15 #include <QtCore/QRegularExpression>
16 #include <QtCore/QStringList>
17 #include <QtGui/QColor>
18
19 #include <nlohmann/json.hpp>
20
21 #include <algorithm>
22
23 using json = nlohmann::json;
24
25 namespace Avogadro::QtPlugins {
26
27 PackageModel::PackageModel(QObject* parent) : QAbstractTableModel(parent) {}
28
29 // ---------------------------------------------------------------------------
30 // QAbstractTableModel interface
31 // ---------------------------------------------------------------------------
32
33 int PackageModel::rowCount(const QModelIndex& parent) const
34 {
35 return parent.isValid() ? 0 : static_cast<int>(m_entries.size());
36 }
37
38 int PackageModel::columnCount(const QModelIndex& parent) const
39 {
40 return parent.isValid() ? 0 : ColumnCount;
41 }
42
43 QVariant PackageModel::data(const QModelIndex& index, int role) const
44 {
45 if (!index.isValid() || index.row() >= m_entries.size())
46 return {};
47
48 const PackageEntry& e = m_entries[index.row()];
49
50 if (role == Qt::TextAlignmentRole && index.column() == StatusColumn)
51 return static_cast<int>(Qt::AlignCenter);
52
53 if (role == Qt::DisplayRole && index.column() == StatusColumn)
54 return statusIcon(e.status);
55
56 if (role == Qt::ToolTipRole && index.column() == StatusColumn) {
57 switch (e.status) {
58 case PackageStatus::NotInstalled:
59 return tr("Not installed");
60 case PackageStatus::Installed:
61 return tr("Installed (up to date)");
62 case PackageStatus::UpdateAvailable:
63 return tr("Update available");
64 case PackageStatus::LocalOnly:
65 return tr("Installed locally (not in online catalog)");
66 }
67 }
68
69 if (role == Qt::ToolTipRole && index.column() == NameColumn) {
70 if (!versionCompatible(e))
71 return tr("Requires Avogadro %1 or later (running %2)")
72 .arg(e.minimumAvogadroVersion,
73 QString::fromLatin1(Avogadro::version()));
74 return {};
75 }
76
77 if (role == Qt::ToolTipRole && index.column() == FeaturesColumn) {
78 if (e.featureTypes.isEmpty())
79 return {};
80 // Build one line per feature to clearly map displayed glyphs to labels.
81 QStringList labels;
82 for (const QString& ft : e.featureTypes) {
83 const QString label = featureTypeLabel(ft);
84 const QString glyph = featureGlyph(ft);
85 if (!glyph.isEmpty())
86 labels.append(QStringLiteral("%1\t%2").arg(glyph, label));
87 else
88 labels.append(label);
89 }
90 return labels.join(QLatin1Char('\n'));
91 }
92
93 // Red foreground for version-incompatible packages
94 if (role == Qt::ForegroundRole && !versionCompatible(e))
95 return QColor(Qt::red);
96
97 if (role == Qt::DisplayRole) {
98 switch (index.column()) {
99 case StatusColumn:
100 return {};
101 case NameColumn:
102 return displayName(e.name);
103 case AvailableColumn:
104 if (e.status == PackageStatus::LocalOnly)
105 return e.installedVersion;
106 return e.hasRelease ? e.onlineVersion : e.updatedAt;
107 case FeaturesColumn: {
108 if (e.featureTypes.isEmpty())
109 return {};
110 QStringList glyphs;
111 for (const QString& ft : e.featureTypes) {
112 const QString g = featureGlyph(ft);
113 if (!g.isEmpty())
114 glyphs.append(g);
115 }
116 return glyphs.join(QLatin1Char(' '));
117 }
118 case DescriptionColumn:
119 return e.description;
120 default:
121 return {};
122 }
123 }
124
125 return {};
126 }
127
128 bool PackageModel::setData(const QModelIndex& index, const QVariant& value,
129 int role)
130 {
131 if (!index.isValid() || index.row() >= m_entries.size())
132 return false;
133
134 return false;
135 }
136
137 QVariant PackageModel::headerData(int section, Qt::Orientation orientation,
138 int role) const
139 {
140 if (orientation != Qt::Horizontal)
141 return {};
142
143 if (role == Qt::ToolTipRole && section == FeaturesColumn) {
144 const QStringList featureTypes = { QStringLiteral("electrostatic-models"),
145 QStringLiteral("energy-models"),
146 QStringLiteral("file-formats"),
147 QStringLiteral("input-generators"),
148 QStringLiteral("menu-commands") };
149 QStringList lines;
150 for (const QString& featureType : featureTypes) {
151 const QString label = featureTypeLabel(featureType);
152 const QString glyph = featureGlyph(featureType);
153 if (!glyph.isEmpty())
154 lines.append(QStringLiteral("%1\t%2").arg(glyph, label));
155 else
156 lines.append(label);
157 }
158 return tr("Feature icons:\n%1").arg(lines.join(QLatin1Char('\n')));
159 }
160
161 if (role != Qt::DisplayRole)
162 return {};
163
164 switch (section) {
165 case StatusColumn:
166 return tr("Status");
167 case NameColumn:
168 return tr("Name");
169 case AvailableColumn:
170 return tr("Version");
171 case FeaturesColumn:
172 return tr("Features");
173 case DescriptionColumn:
174 return tr("Description");
175 default:
176 return {};
177 }
178 }
179
180 Qt::ItemFlags PackageModel::flags(const QModelIndex& index) const
181 {
182 if (!index.isValid())
183 return Qt::NoItemFlags;
184
185 return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
186 }
187
188 // ---------------------------------------------------------------------------
189 // Data loading
190 // ---------------------------------------------------------------------------
191
192 void PackageModel::loadOnlineCatalog(const QByteArray& jsonBytes)
193 {
194 beginResetModel();
195 m_entries.clear();
196
197 json root =
198 json::parse(jsonBytes.data(), nullptr, /*allow_exceptions=*/false);
199 if (root.is_discarded() || !root.is_array()) {
200 endResetModel();
201 return;
202 }
203
204 for (const auto& item : root) {
205 if (!item.is_object())
206 continue;
207
208 PackageEntry e;
209 auto get = [&](const char* key, QString& out) {
210 auto it = item.find(key);
211 if (it != item.end() && it->is_string())
212 out = QString::fromStdString(it->get<std::string>());
213 };
214
215 get("name", e.name);
216 get("description", e.description);
217 get("version", e.onlineVersion);
218 get("minimum-avogadro-version", e.minimumAvogadroVersion);
219
220 // git.repo is a clone URL; strip .git suffix for a web base URL
221 auto gitIt = item.find("git");
222 if (gitIt != item.end() && gitIt->is_object()) {
223 auto repoIt = gitIt->find("repo");
224 if (repoIt != gitIt->end() && repoIt->is_string()) {
225 e.baseUrl = QString::fromStdString(repoIt->get<std::string>());
226 if (e.baseUrl.endsWith(QStringLiteral(".git")))
227 e.baseUrl.chop(4);
228 }
229 }
230
231 // src may be either:
232 // - object: {url, sha256}
233 // - array: [{url, sha256}, ...] (legacy)
234 // Use the first available url.
235 auto srcIt = item.find("src");
236 const auto setSrcUrl = [&](const json& srcObj) {
237 auto urlIt = srcObj.find("url");
238 if (urlIt != srcObj.end() && urlIt->is_string()) {
239 e.zipballUrl = QString::fromStdString(urlIt->get<std::string>());
240 e.hasRelease = true;
241 }
242 };
243 if (srcIt != item.end()) {
244 if (srcIt->is_object()) {
245 setSrcUrl(*srcIt);
246 } else if (srcIt->is_array() && !srcIt->empty() &&
247 srcIt->front().is_object()) {
248 setSrcUrl(srcIt->front());
249 }
250 }
251
252 // readme-url is a GitHub blob page URL; convert to raw for fetching
253 get("readme-url", e.readmeUrl);
254 if (!e.readmeUrl.isEmpty()) {
255 e.readmeUrl.replace(QStringLiteral("github.com"),
256 QStringLiteral("raw.githubusercontent.com"));
257 e.readmeUrl.replace(QStringLiteral("/blob/"), QStringLiteral("/"));
258 }
259
260 auto featIt = item.find("feature-types");
261 if (featIt != item.end() && featIt->is_array()) {
262 for (const auto& f : *featIt) {
263 if (f.is_string())
264 e.featureTypes.append(QString::fromStdString(f.get<std::string>()));
265 }
266 }
267
268 auto dateIt = item.find("last-update");
269 if (dateIt != item.end() && dateIt->is_string()) {
270 QString raw = QString::fromStdString(dateIt->get<std::string>());
271 e.onlineUpdatedAt = QDateTime::fromString(raw, Qt::ISODate);
272 e.updatedAt =
273 QLocale().toString(e.onlineUpdatedAt.date(), QLocale::ShortFormat);
274 }
275
276 e.status = PackageStatus::NotInstalled;
277 if (!e.name.isEmpty())
278 m_entries.append(e);
279 }
280
281 std::sort(m_entries.begin(), m_entries.end(),
282 [](const PackageEntry& a, const PackageEntry& b) {
283 return a.name.compare(b.name, Qt::CaseInsensitive) < 0;
284 });
285
286 endResetModel();
287 }
288
289 void PackageModel::mergeInstalledPackages()
290 {
291 // Use a full model reset because we may be adding or removing LocalOnly rows.
292 beginResetModel();
293
294 // First, clear any previously set installed state from catalog entries
295 for (PackageEntry& e : m_entries) {
296 if (e.status != PackageStatus::LocalOnly) {
297 e.installedVersion.clear();
298 e.packageKey.clear();
299 e.installedDir.clear();
300 e.isSymlink = false;
301 e.status = PackageStatus::NotInstalled;
302 }
303 }
304 // Remove any previously added LocalOnly entries
305 m_entries.removeIf(
306 [](const PackageEntry& e) { return e.status == PackageStatus::LocalOnly; });
307
308 QtGui::PackageManager* pm = QtGui::PackageManager::instance();
309 const QStringList installed = pm->registeredPackages();
310
311 // Build a single lookup map keyed on the normalised package name.
312 // Each catalog entry is indexed by its name and its repo-slug (last segment
313 // of baseUrl), both normalised, so "avogenerators" == "generators", etc.
314 QHash<QString, int> byNormName;
315 for (int i = 0; i < m_entries.size(); ++i) {
316 const PackageEntry& e = m_entries[i];
317 if (!e.name.isEmpty())
318 byNormName.insert(normalizePackageName(e.name), i);
319 if (!e.baseUrl.isEmpty()) {
320 const QString slug = e.baseUrl.split('/').last();
321 if (!slug.isEmpty())
322 byNormName.insert(normalizePackageName(slug), i);
323 }
324 }
325
326 for (const QString& pkgName : installed) {
327 QtGui::PackageManager::PackageInfo info = pm->packageInfo(pkgName);
328
329 // Determine if the installed directory is a symlink
330 bool symlink = QFileInfo(info.directory).isSymLink();
331
332 // Try to find a matching entry in the online catalog using normalised
333 // names.
334 int idx = byNormName.value(normalizePackageName(pkgName), -1);
335
336 // Also try the directory base name (handles cases where pkgName != repo
337 // name)
338 if (idx == -1) {
339 const QString dirBase = QFileInfo(info.directory).fileName();
340 idx = byNormName.value(normalizePackageName(dirBase), -1);
341 }
342
343 if (idx != -1) {
344 PackageEntry& e = m_entries[idx];
345 e.installedVersion = info.version;
346 e.packageKey = pkgName;
347 e.installedDir = info.directory;
348 e.isSymlink = symlink;
349 e.status = computeStatus(e);
350 } else {
351 // LocalOnly — installed but not in the online catalog
352 PackageEntry e;
353 e.name = pkgName;
354 e.description = info.description;
355 e.installedVersion = info.version;
356 e.packageKey = pkgName;
357 e.installedDir = info.directory;
358 e.isSymlink = symlink;
359 e.featureTypes = pm->packageFeatureTypes(pkgName);
360 e.status = PackageStatus::LocalOnly;
361 m_entries.append(e);
362 }
363 }
364
365 std::sort(m_entries.begin(), m_entries.end(),
366 [](const PackageEntry& a, const PackageEntry& b) {
367 return a.name.compare(b.name, Qt::CaseInsensitive) < 0;
368 });
369
370 endResetModel();
371 }
372
373 // ---------------------------------------------------------------------------
374 // Accessors
375 // ---------------------------------------------------------------------------
376
377 QString PackageModel::readmeUrl(int row) const
378 {
379 if (row < 0 || row >= m_entries.size())
380 return {};
381 return m_entries[row].readmeUrl;
382 }
383
384 // ---------------------------------------------------------------------------
385 // Helpers
386 // ---------------------------------------------------------------------------
387
388 PackageModel::PackageStatus PackageModel::computeStatus(const PackageEntry& e)
389 {
390 if (e.installedDir.isEmpty())
391 return PackageStatus::NotInstalled;
392 if (e.status == PackageStatus::LocalOnly)
393 return PackageStatus::LocalOnly;
394
395 // Prefer semantic version ordering when both versions parse cleanly.
396 if (!e.installedVersion.isEmpty() && !e.onlineVersion.isEmpty()) {
397 bool semverComparable = false;
398 const int cmp =
399 compareSemVer(e.installedVersion, e.onlineVersion, semverComparable);
400 if (semverComparable)
401 return cmp < 0 ? PackageStatus::UpdateAvailable
402 : PackageStatus::Installed;
403 }
404
405 // Fallback: if the online catalog update timestamp is newer than the local
406 // package metadata file, treat it as an available update.
407 if (isOnlineNewerByDate(e))
408 return PackageStatus::UpdateAvailable;
409
410 return PackageStatus::Installed;
411 }
412
413 bool PackageModel::isOnlineNewerByDate(const PackageEntry& e)
414 {
415 if (!e.onlineUpdatedAt.isValid() || e.installedDir.isEmpty())
416 return false;
417
418 QDateTime localModified;
419 const QFileInfo pyproject(e.installedDir + QStringLiteral("/pyproject.toml"));
420 if (pyproject.exists())
421 localModified = pyproject.lastModified();
422 if (!localModified.isValid())
423 localModified = QFileInfo(e.installedDir).lastModified();
424 if (!localModified.isValid())
425 return false;
426
427 return e.onlineUpdatedAt > localModified;
428 }
429
430 bool PackageModel::parseSemVer(const QString& version, int& major, int& minor,
431 int& patch)
432 {
433 static const QRegularExpression re(
434 QStringLiteral("^v?(\\d+)\\.(\\d+)(?:\\.(\\d+))?(?:[-+].*)?$"));
435 const QRegularExpressionMatch match = re.match(version.trimmed());
436 if (!match.hasMatch())
437 return false;
438
439 bool okMajor = false;
440 bool okMinor = false;
441 bool okPatch = true;
442 major = match.captured(1).toInt(&okMajor);
443 minor = match.captured(2).toInt(&okMinor);
444 patch = match.captured(3).isEmpty() ? 0 : match.captured(3).toInt(&okPatch);
445 return okMajor && okMinor && okPatch;
446 }
447
448 int PackageModel::compareSemVer(const QString& lhs, const QString& rhs,
449 bool& ok)
450 {
451 int lhsMajor = 0;
452 int lhsMinor = 0;
453 int lhsPatch = 0;
454 int rhsMajor = 0;
455 int rhsMinor = 0;
456 int rhsPatch = 0;
457
458 const bool lhsValid = parseSemVer(lhs, lhsMajor, lhsMinor, lhsPatch);
459 const bool rhsValid = parseSemVer(rhs, rhsMajor, rhsMinor, rhsPatch);
460 ok = lhsValid && rhsValid;
461 if (!ok)
462 return 0;
463
464 if (lhsMajor != rhsMajor)
465 return lhsMajor < rhsMajor ? -1 : 1;
466 if (lhsMinor != rhsMinor)
467 return lhsMinor < rhsMinor ? -1 : 1;
468 if (lhsPatch != rhsPatch)
469 return lhsPatch < rhsPatch ? -1 : 1;
470 return 0;
471 }
472
473 QString PackageModel::statusIcon(PackageStatus status)
474 {
475 switch (status) {
476 case PackageStatus::NotInstalled:
477 return QStringLiteral("\u2795"); // ➕ heavy plus sign
478 case PackageStatus::Installed:
479 return QStringLiteral("\u2705"); // ✅ white check mark
480 case PackageStatus::UpdateAvailable:
481 return QStringLiteral("\u2757"); // ❗ red exclamation mark
482 case PackageStatus::LocalOnly:
483 return QStringLiteral("\U0001F4C1"); // 📁 file folder
484 }
485 return {};
486 }
487
488 // Common Avogadro prefixes, longest first to avoid partial matches.
489 static const char* s_avoPrefixes[] = { "avogadro-", "avogadro_", "avogadro",
490 "avo-", "avo_", "avo" };
491
492 /// Return the length of the first matching prefix, or 0 if none match.
493 static int avoPrefixLength(const QString& name, Qt::CaseSensitivity cs)
494 {
495 for (const char* prefix : s_avoPrefixes) {
496 const QLatin1String p(prefix);
497 if (name.startsWith(p, cs))
498 return p.size();
499 }
500 return 0;
501 }
502
503 QString PackageModel::normalizePackageName(const QString& name)
504 {
505 QString n = name.toLower();
506 int len = avoPrefixLength(n, Qt::CaseSensitive);
507 if (len > 0)
508 n = n.mid(len);
509 // Fold hyphens and underscores so "my-plugin" == "my_plugin".
510 n.replace('-', '_');
511 return n;
512 }
513
514 QString PackageModel::displayName(const QString& name)
515 {
516 int len = avoPrefixLength(name, Qt::CaseInsensitive);
517 if (len > 0)
518 return name.mid(len);
519 return name;
520 }
521
522 QString PackageModel::featureTypeLabel(const QString& featureType)
523 {
524 if (featureType == QLatin1String("electrostatic-models"))
525 return tr("Electrostatics");
526 if (featureType == QLatin1String("energy-models"))
527 return tr("Energy Models");
528 if (featureType == QLatin1String("file-formats"))
529 return tr("File Formats");
530 if (featureType == QLatin1String("input-generators"))
531 return tr("Input Generators");
532 if (featureType == QLatin1String("menu-commands"))
533 return tr("Commands");
534 // Unknown feature type — return as-is (capitalised for readability)
535 if (featureType.isEmpty())
536 return {};
537 QString label = featureType;
538 label[0] = label[0].toUpper();
539 return label.replace('-', ' ');
540 }
541
542 QString PackageModel::featureGlyph(const QString& featureType)
543 {
544 if (featureType == QLatin1String("electrostatic-models"))
545 return QStringLiteral("\u26A1"); // ⚡ LIGHTNING BOLT
546 if (featureType == QLatin1String("energy-models"))
547 return QStringLiteral("E");
548 if (featureType == QLatin1String("file-formats"))
549 return QStringLiteral("\U0001F4C4"); // 📄 PAGE FACING UP
550 if (featureType == QLatin1String("input-generators"))
551 return QStringLiteral("\u269B"); // ⚛ ATOM SYMBOL
552 if (featureType == QLatin1String("menu-commands"))
553 return QStringLiteral("\u2630"); // ☰ TRIGRAM / HAMBURGER MENU
554 return {};
555 }
556
557 bool PackageModel::versionCompatible(const PackageEntry& e)
558 {
559 if (e.minimumAvogadroVersion.isEmpty())
560 return true;
561 bool ok = false;
562 const int cmp = compareSemVer(QString::fromLatin1(Avogadro::version()),
563 e.minimumAvogadroVersion, ok);
564 // If either string didn't parse as semver, assume compatible.
565 return !ok || cmp >= 0;
566 }
567
568 } // namespace Avogadro::QtPlugins