Debian Codegraph @

src/GUI/LocalAircraftCache.cxx

raw symbols SCIP
1 // Written by James Turner, started October 2017
2 //
3 // Copyright (C) 2017 James Turner <[email protected]>
4 //
5 // This program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License as
7 // published by the Free Software Foundation; either version 2 of the
8 // License, or (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful, but
11 // WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 // General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18
19 #include "config.h"
20
21 #include "LocalAircraftCache.hxx"
22
23 #include <cassert>
24
25 #include <QDir>
26 #include <QThread>
27 #include <QMutex>
28 #include <QMutexLocker>
29 #include <QDataStream>
30 #include <QMap>
31 #include <QSettings>
32 #include <QDebug>
33
34 #include <Main/globals.hxx>
35 #include <Main/locale.hxx>
36 #include <Main/sentryIntegration.hxx>
37
38 #include <simgear/misc/ResourceManager.hxx>
39 #include <simgear/props/props_io.hxx>
40 #include <simgear/structure/exception.hxx>
41
42 #include "SettingsWrapper.hxx"
43
44 static quint32 CACHE_VERSION = 13;
45
46 const std::vector<QByteArray> static_localizedStringTags = {"name", "desc"};
47
48 QDataStream& operator<<(QDataStream& ds, const AircraftItem::LocalizedStrings& ls)
49 {
50 ds << ls.locale << ls.strings;
51 return ds;
52 }
53
54 QDataStream& operator>>(QDataStream& ds, AircraftItem::LocalizedStrings& ls)
55 {
56 ds >> ls.locale >> ls.strings;
57 return ds;
58 }
59
60 bool AircraftItem::initFromFile(QDir dir, QString filePath)
61 {
62 SGPropertyNode root;
63 readProperties(filePath.toStdString(), &root);
64
65 if (!root.hasChild("sim")) {
66 qWarning() << "-set.xml has no <sim> element" << filePath;
67 return false;
68 }
69
70 SGPropertyNode_ptr sim = root.getNode("sim");
71
72 path = filePath;
73 pathModTime = QFileInfo(path).lastModified();
74 if (sim->getBoolValue("exclude-from-gui", false)) {
75 excluded = true;
76 return false;
77 }
78
79 LocalizedStrings ls;
80 ls.locale = "en";
81 ls.strings["name"] = QString::fromStdString(sim->getStringValue("description")).trimmed();
82 authors = QString::fromStdString(sim->getStringValue("author"));
83
84 if (sim->hasChild("rating")) {
85 SGPropertyNode_ptr ratingsNode = sim->getNode("rating");
86 for (int i=0; i< 4; ++i) {
87 ratings[i] = LocalAircraftCache::ratingFromProperties(ratingsNode, i);
88 }
89 }
90
91 if (sim->hasChild("long-description")) {
92 // clean up any XML whitspace in the text.
93 ls.strings["desc"] = QString::fromStdString(sim->getStringValue("long-description")).simplified();
94 }
95
96 if (sim->hasChild("variant-of")) {
97 variantOf = QString::fromStdString(sim->getStringValue("variant-of"));
98 } else {
99 isPrimary = true;
100 }
101
102 if (sim->hasChild("primary-set")) {
103 isPrimary = sim->getBoolValue("primary-set");
104 }
105
106 if (sim->hasChild("tags")) {
107 SGPropertyNode_ptr tagsNode = sim->getChild("tags");
108 int nChildren = tagsNode->nChildren();
109 for (int i = 0; i < nChildren; i++) {
110 const SGPropertyNode* c = tagsNode->getChild(i);
111 if (c->getNameString() == "tag") {
112 std::string tagName = c->getStringValue();
113 usesHeliports |= (tagName == "helicopter");
114 // could also consider vtol tag?
115 usesSeaports |= (tagName == "seaplane");
116 usesSeaports |= (tagName == "floats");
117 needsMaintenance |= (tagName == "needs-maintenance");
118
119 // and actually store the tags
120 tags.push_back(QString::fromStdString(tagName));
121 }
122 } // of tags iteration
123 } // of set-xml has tags
124
125 if (sim->hasChild("previews")) {
126 SGPropertyNode_ptr previewsNode = sim->getChild("previews");
127 const QString aircraftPrefix = "Aircraft/" + dir.dirName() + "/";
128
129 for (auto previewNode : previewsNode->getChildren("preview")) {
130 // add file path as url
131 QString pathInXml = QString::fromStdString(previewNode->getStringValue("path"));
132
133 // https://sourceforge.net/p/flightgear/codetickets/2644/
134 // allow Aircraft/ prefixed paths in previews; what we're actually doing here
135 // is trimming them back to the style we expect
136 if (pathInXml.startsWith(aircraftPrefix)) {
137 pathInXml = pathInXml.mid(aircraftPrefix.length());
138 }
139
140 QString previewPath = dir.absoluteFilePath(pathInXml);
141
142 if (!QFile::exists(previewPath)) {
143 qWarning() << "Missing local preview file" << previewPath;
144 continue;
145 }
146
147 previews.append(QUrl::fromLocalFile(previewPath));
148
149 }
150 }
151
152 if (sim->hasChild("thumbnail")) {
153 thumbnailPath = QString::fromStdString(sim->getStringValue("thumbnail"));
154 } else {
155 thumbnailPath = "thumbnail.jpg";
156 }
157
158 if (sim->hasChild("minimum-fg-version")) {
159 minFGVersion = QString::fromStdString(sim->getStringValue("minimum-fg-version"));
160 }
161
162 homepageUrl = QUrl(QString::fromStdString(sim->getStringValue("urls/home-page")));
163 supportUrl = QUrl(QString::fromStdString(sim->getStringValue("urls/support")));
164 wikipediaUrl = QUrl(QString::fromStdString(sim->getStringValue("urls/wikipedia")));
165
166 _localized.push_front(ls);
167 readLocalizedStrings(sim);
168 doLocalizeStrings();
169
170 return true;
171 }
172
173 void AircraftItem::readLocalizedStrings(SGPropertyNode_ptr simNode)
174 {
175 if (!simNode->hasChild("localized"))
176 return;
177
178 auto localeNode = simNode->getChild("localized");
179 const auto num = localeNode->nChildren();
180 for (int i = 0; i < num; i++) {
181 const SGPropertyNode* c = localeNode->getChild(i);
182
183 LocalizedStrings ls;
184 ls.locale = QString::fromStdString(c->getNameString());
185 if (c->hasChild("description")) {
186 ls.strings["name"] = QString::fromStdString(c->getStringValue("description"));
187 }
188 if (c->hasChild("long-description")) {
189 ls.strings["desc"] = QString::fromStdString(c->getStringValue("long-description")).simplified();
190 }
191
192 _localized.push_back(ls);
193 }
194 }
195
196 void AircraftItem::doLocalizeStrings()
197 {
198 // default strings are always at the front
199 _currentStrings = _localized.front().strings;
200
201 const auto lang = QString::fromStdString(globals->get_locale()->getPreferredLanguage());
202 // find the matching locale
203 auto it = std::find_if(_localized.begin(), _localized.end(), [lang](const LocalizedStrings& ls) {
204 return ls.locale == lang;
205 });
206
207 if (it == _localized.end())
208 return; // nothing else to do
209
210 for (auto t : static_localizedStringTags) {
211 if (it->strings.contains(t)) {
212 // copy the value we found
213 _currentStrings[t] = it->strings.value(t);
214 }
215 } // of strings iteration
216 }
217
218 QString AircraftItem::name() const
219 {
220 return _currentStrings.value("name");
221 }
222
223 QString AircraftItem::description() const
224 {
225 return _currentStrings.value("desc");
226 }
227
228 QString AircraftItem::baseName() const
229 {
230 QString fn = QFileInfo(path).fileName();
231 fn.truncate(fn.size() - 8);
232 return fn;
233 }
234
235 void AircraftItem::fromDataStream(QDataStream& ds)
236 {
237 ds >> path >> pathModTime >> excluded;
238 if (excluded) {
239 return;
240 }
241
242 ds >> authors >> variantOf >> isPrimary;
243 for (int i=0; i<4; ++i) ds >> ratings[i];
244 ds >> previews;
245 ds >> thumbnailPath;
246 ds >> minFGVersion;
247 ds >> needsMaintenance >> usesHeliports >> usesSeaports;
248 ds >> homepageUrl >> supportUrl >> wikipediaUrl;
249 ds >> tags;
250 ds >> _localized;
251
252 doLocalizeStrings();
253 }
254
255 void AircraftItem::toDataStream(QDataStream& ds) const
256 {
257 ds << path << pathModTime << excluded;
258 if (excluded) {
259 return;
260 }
261
262 ds << authors << variantOf << isPrimary;
263 for (int i=0; i<4; ++i) ds << ratings[i];
264 ds << previews;
265 ds << thumbnailPath;
266 ds << minFGVersion;
267 ds << needsMaintenance << usesHeliports << usesSeaports;
268 ds << homepageUrl << supportUrl << wikipediaUrl;
269 ds << tags;
270 ds << _localized;
271 }
272
273 int AircraftItem::indexOfVariant(QUrl uri) const
274 {
275 const QString path = uri.toLocalFile();
276 for (int i=0; i< variants.size(); ++i) {
277 if (variants.at(i)->path == path) {
278 return i;
279 }
280 }
281
282 return -1;
283 }
284
285 QVariant AircraftItem::status(int variant)
286 {
287 Q_UNUSED(variant)
288 if (needsMaintenance) {
289 return LocalAircraftCache::AircraftUnmaintained;
290 }
291
292 if (minFGVersion.isEmpty()) {
293 return LocalAircraftCache::AircraftOk;
294 }
295
296 const int c = simgear::strutils::compare_versions(FLIGHTGEAR_VERSION,
297 minFGVersion.toStdString(), 2);
298 return (c < 0) ? LocalAircraftCache::AircraftNeedsNewerSimulator
299 : LocalAircraftCache::AircraftOk;
300
301 }
302
303 namespace {
304
305 static std::unique_ptr<LocalAircraftCache> static_cacheInstance;
306
307
308 // ensure references to Aircraft/foo and <my-aircraft-dir>/foo are resolved. This happens when
309 // aircraft reference a path (probably to themselves) in their -set.xml
310 class ScanDirProvider : public simgear::ResourceProvider
311 {
312 public:
313 ScanDirProvider() : simgear::ResourceProvider(simgear::ResourceManager::PRIORITY_NORMAL) {}
314
315 ~ScanDirProvider() = default;
316
317 SGPath resolve(const std::string& aResource, SGPath& aContext) const override
318 {
319 Q_UNUSED(aContext)
320
321 SGPath ap = _currentAircraftPath / aResource;
322 if (ap.exists())
323 return ap;
324
325 string_list pieces(sgPathBranchSplit(aResource));
326 if ((pieces.size() < 3) || (pieces.front() != "Aircraft")) {
327 return SGPath{}; // not an Aircraft path
328 }
329
330 const std::string res(aResource, 9); // resource path with 'Aircraft/' removed
331 SGPath p = _currentScanPath / res;
332 if (p.exists())
333 return p;
334
335 return SGPath{};
336 }
337
338 void setCurrentPath(const SGPath& p)
339 {
340 _currentScanPath = p;
341 }
342
343 void setCurrentAircraftPath(const SGPath& p)
344 {
345 _currentAircraftPath = p;
346 }
347
348 private:
349 SGPath _currentScanPath;
350 SGPath _currentAircraftPath;
351 };
352
353 class OtherAircraftDirsProvider : public simgear::ResourceProvider
354 {
355 public:
356 OtherAircraftDirsProvider() : simgear::ResourceProvider(simgear::ResourceManager::PRIORITY_NORMAL) {}
357
358 ~OtherAircraftDirsProvider() = default;
359
360 SGPath resolve(const std::string& aResource, SGPath& aContext) const override
361 {
362 if (aResource.find("Aircraft/") != 0) {
363 return SGPath{}; // not an aircraft path
364 }
365
366 const std::string res(aResource, 9); // resource path with 'Aircraft/' removed
367
368 Q_UNUSED(aContext)
369 QStringList paths = LocalAircraftCache::instance()->paths();
370 Q_FOREACH(auto p, paths) {
371 const auto sp = SGPath::fromUtf8(p.toUtf8().toStdString()) / res;
372 // qWarning() << "OADP: trying:" << QString::fromStdString(sp.utf8Str());
373 if (sp.exists())
374 return sp;
375 }
376
377 return SGPath{};
378 }
379 };
380
381 class AircraftScanThread : public QThread
382 {
383 Q_OBJECT
384 public:
385 AircraftScanThread(QStringList dirsToScan) :
386 m_dirs(dirsToScan),
387 m_done(false)
388 {
389 auto rm = simgear::ResourceManager::instance();
390 m_currentScanDir.reset(new ScanDirProvider);
391 rm->addProvider(m_currentScanDir.get());
392 }
393
394 ~AircraftScanThread()
395 {
396 simgear::ResourceManager::instance()->removeProvider(m_currentScanDir.get());
397 }
398
399 /** thread-safe access to items already scanned */
400 QVector<AircraftItemPtr> items()
401 {
402 QVector<AircraftItemPtr> result;
403 QMutexLocker g(&m_lock);
404 result.swap(m_items);
405 Q_ASSERT(m_items.empty());
406 g.unlock();
407 return result;
408 }
409
410 void setDone()
411 {
412 m_done = true;
413 }
414
415 Q_SIGNALS:
416 void addedItems();
417
418 protected:
419 void run() override
420 {
421 flightgear::addSentryBreadcrumb("AircraftScan started", "info");
422 readCache();
423
424 Q_FOREACH(QString d, m_dirs) {
425 const auto p = SGPath::fromUtf8(d.toUtf8().toStdString());
426 m_currentScanDir->setCurrentPath(p);
427 scanAircraftDir(QDir(d));
428 if (m_done) {
429 return;
430 }
431 }
432
433 writeCache();
434 flightgear::addSentryBreadcrumb("AircraftScan finished", "info");
435 }
436
437 private:
438 void readCache()
439 {
440 auto settings = flightgear::getQSettings();
441 QByteArray cacheData = settings.value("aircraft-cache").toByteArray();
442 if (!cacheData.isEmpty()) {
443 QDataStream ds(cacheData);
444 quint32 count, cacheVersion;
445 ds >> cacheVersion >> count;
446
447 if (cacheVersion != CACHE_VERSION) {
448 return; // mis-matched cache, version, drop
449 }
450
451 for (quint32 i=0; i<count; ++i) {
452 AircraftItemPtr item(new AircraftItem);
453 item->fromDataStream(ds);
454
455 QFileInfo finfo(item->path);
456 if (finfo.exists() && (finfo.lastModified() == item->pathModTime)) {
457 // corresponding -set.xml file still exists and is
458 // unmodified
459 m_cachedItems[item->path] = item;
460 }
461 } // of cached item iteration
462 }
463 }
464
465 void writeCache()
466 {
467 auto settings = flightgear::getQSettings();
468 QByteArray cacheData;
469 {
470 QDataStream ds(&cacheData, QIODevice::WriteOnly);
471 quint32 count = static_cast<quint32>(m_nextCache.count());
472 ds << CACHE_VERSION << count;
473
474 Q_FOREACH(AircraftItemPtr item, m_nextCache.values()) {
475 item->toDataStream(ds);
476 }
477 }
478
479 settings.setValue("aircraft-cache", cacheData);
480 }
481
482 void scanAircraftDir(QDir path)
483 {
484 //QTime t;
485 //t.start();
486
487 QStringList filters;
488 filters << "*-set.xml";
489 Q_FOREACH(QFileInfo child, path.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot)) {
490 if (m_done) { // thread termination bail-out
491 return;
492 }
493
494 QDir childDir(child.absoluteFilePath());
495 QMap<QString, AircraftItemPtr> baseAircraft;
496 QList<AircraftItemPtr> variants;
497
498 // ensure aircraft dir is available to simgear::ResourceProvider
499 // otherwise some aircraft -set.xml includes fail
500 const auto p = SGPath::fromUtf8(child.absoluteFilePath().toUtf8().toStdString());
501 m_currentScanDir->setCurrentAircraftPath(p);
502
503 Q_FOREACH(QFileInfo xmlChild, childDir.entryInfoList(filters, QDir::Files)) {
504 try {
505 QString absolutePath = xmlChild.absoluteFilePath();
506 AircraftItemPtr item;
507
508 // should we re-stat here? But we already did so when loading
509 // the cache and dropped any non-valid entries
510 if (m_cachedItems.contains(absolutePath)) {
511 item = m_cachedItems.value(absolutePath);
512 } else {
513 // scan the cached item
514 item = AircraftItemPtr(new AircraftItem);
515 bool ok = item->initFromFile(childDir, absolutePath);
516 if (!ok) {
517 continue;
518 }
519 }
520
521 m_nextCache[absolutePath] = item;
522
523 if (item->excluded) {
524 continue;
525 }
526
527 if (item->isPrimary) {
528 baseAircraft.insert(item->baseName(), item);
529 } else {
530 variants.append(item);
531 }
532 } catch (sg_exception& e) {
533 qWarning() << "Problems occurred while parsing" << xmlChild.absoluteFilePath() << "(skipping)"
534 << "\n\t" << QString::fromStdString(e.what());
535 continue;
536 }
537
538 if (m_done) { // thread termination bail-out
539 return;
540 }
541 } // of set.xml iteration
542
543 // bind variants to their principals
544 Q_FOREACH(AircraftItemPtr item, variants) {
545 if (!baseAircraft.contains(item->variantOf)) {
546 qWarning() << "can't find principal aircraft " << item->variantOf << " for variant:" << item->path;
547 continue;
548 }
549
550 baseAircraft.value(item->variantOf)->variants.append(item);
551 }
552
553 // lock mutex while we modify the items array
554 bool didAddItems = false;
555 {
556 QMutexLocker g(&m_lock);
557 m_items+=(baseAircraft.values().toVector());
558 didAddItems = !m_items.isEmpty();
559 }
560
561 if (didAddItems) {
562 emit addedItems();
563 }
564 } // of subdir iteration
565
566 //qInfo() << "scanning" << path.absolutePath() << "took" << t.elapsed();
567 }
568
569 QMutex m_lock;
570 QStringList m_dirs;
571 QVector<AircraftItemPtr> m_items;
572
573 QMap<QString, AircraftItemPtr > m_cachedItems;
574 QMap<QString, AircraftItemPtr > m_nextCache;
575
576 bool m_done;
577 std::unique_ptr<ScanDirProvider> m_currentScanDir;
578 };
579
580 } // of anonymous namespace
581
582
583 class LocalAircraftCache::AircraftCachePrivate
584 {
585 public:
586 QStringList m_paths;
587 std::unique_ptr<AircraftScanThread> m_scanThread;
588 QVector<AircraftItemPtr> m_items;
589 std::unique_ptr<OtherAircraftDirsProvider> m_otherDirsProvider;
590 };
591
592 LocalAircraftCache* LocalAircraftCache::instance()
593 {
594 if (!static_cacheInstance) {
595 static_cacheInstance.reset(new LocalAircraftCache);
596 }
597
598 return static_cacheInstance.get();
599 }
600
601 void LocalAircraftCache::reset()
602 {
603 static_cacheInstance.reset();
604 }
605
606 LocalAircraftCache::LocalAircraftCache() :
607 d(new AircraftCachePrivate)
608 {
609 d->m_otherDirsProvider.reset(new OtherAircraftDirsProvider);
610 auto rm = simgear::ResourceManager::instance();
611 rm->addProvider(d->m_otherDirsProvider.get());
612 }
613
614 LocalAircraftCache::~LocalAircraftCache()
615 {
616 abandonCurrentScan();
617 if (simgear::ResourceManager::haveInstance()) {
618 simgear::ResourceManager::instance()->removeProvider(d->m_otherDirsProvider.get());
619 } else {
620 // resource manager will already have destroyed the provider. Awkward
621 // ownership model :(
622 d->m_otherDirsProvider.release();
623 }
624 }
625
626 void LocalAircraftCache::setPaths(QStringList paths)
627 {
628 if (paths == d->m_paths) {
629 return;
630 }
631
632 d->m_items.clear();
633 emit cleared();
634 d->m_paths = paths;
635 }
636
637 QStringList LocalAircraftCache::paths() const
638 {
639 return d->m_paths;
640 }
641
642 void LocalAircraftCache::scanDirs()
643 {
644 abandonCurrentScan();
645 d->m_items.clear();
646
647 QStringList dirs = d->m_paths;
648
649 for (SGPath ap : globals->get_aircraft_paths()) {
650 dirs << QString::fromStdString(ap.utf8Str());
651 }
652
653 SGPath rootAircraft = globals->get_fg_root() / "Aircraft";
654 dirs << QString::fromStdString(rootAircraft.utf8Str());
655
656 d->m_scanThread.reset(new AircraftScanThread(dirs));
657 connect(d->m_scanThread.get(), &AircraftScanThread::finished, this,
658 &LocalAircraftCache::onScanFinished);
659 // force a queued connection here since we the scan thread object still
660 // belongs to the same thread as us, and hence this would otherwise be
661 // a direct connection
662 connect(d->m_scanThread.get(), &AircraftScanThread::addedItems,
663 this, &LocalAircraftCache::onScanResults,
664 Qt::QueuedConnection);
665 d->m_scanThread->start();
666
667 emit scanStarted();
668 }
669
670 int LocalAircraftCache::itemCount() const
671 {
672 return d->m_items.size();
673 }
674
675 QVector<AircraftItemPtr> LocalAircraftCache::allItems() const
676 {
677 return d->m_items;
678 }
679
680 AircraftItemPtr LocalAircraftCache::itemAt(int index) const
681 {
682 return d->m_items.at(index);
683 }
684
685 int LocalAircraftCache::findIndexWithUri(QUrl aircraftUri) const
686 {
687 QString path = aircraftUri.toLocalFile();
688 for (int row=0; row < d->m_items.size(); ++row) {
689 const AircraftItemPtr item(d->m_items.at(row));
690 if (item->path == path) {
691 return row;
692 }
693
694 // check variants too
695 for (int vr=0; vr < item->variants.size(); ++vr) {
696 if (item->variants.at(vr)->path == path) {
697 return row;
698 }
699 }
700 }
701
702 return -1;
703 }
704
705 AircraftItemPtr LocalAircraftCache::primaryItemFor(AircraftItemPtr item) const
706 {
707 if (!item || item->variantOf.isEmpty())
708 return item;
709
710 for (int row=0; row < d->m_items.size(); ++row) {
711 const AircraftItemPtr p(d->m_items.at(row));
712 if (p->baseName() == item->variantOf) {
713 return p;
714 }
715 }
716
717 return {};
718 }
719
720 AircraftItemPtr LocalAircraftCache::findItemWithUri(QUrl aircraftUri) const
721 {
722 int index = findIndexWithUri(aircraftUri);
723 if (index >= 0) {
724 return d->m_items.at(index);
725 }
726
727 return {};
728 }
729
730 void LocalAircraftCache::abandonCurrentScan()
731 {
732 if (d->m_scanThread) {
733 // don't fire onScanFinished when the thread ends
734 disconnect(d->m_scanThread.get(), &AircraftScanThread::finished, this,
735 &LocalAircraftCache::onScanFinished);
736
737 d->m_scanThread->setDone();
738 if (!d->m_scanThread->wait(32000)) {
739 qWarning() << Q_FUNC_INFO << "scan thread failed to terminate";
740 }
741 d->m_scanThread.reset();
742 }
743 }
744
745
746 void LocalAircraftCache::onScanResults()
747 {
748 if (!d->m_scanThread) {
749 return;
750 }
751
752 QVector<AircraftItemPtr> newItems = d->m_scanThread->items();
753 if (newItems.isEmpty())
754 return;
755
756 d->m_items+=newItems;
757 emit addedItems(newItems.size());
758 }
759
760 void LocalAircraftCache::onScanFinished()
761 {
762 d->m_scanThread.reset();
763 emit scanCompleted();
764 }
765
766 bool LocalAircraftCache::isCandidateAircraftPath(QString path)
767 {
768 QStringList filters;
769 filters << "*-set.xml";
770 // count of child dirs, if we visited more than ten children without
771 // finding a -set.xml file, let's assume we are done. This avoids an
772 // exhaustive search of huge directory trees
773 int dirCount = 0,
774 setXmlCount = 0;
775
776 QDir d(path);
777 Q_FOREACH(QFileInfo child, d.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot)) {
778 QDir childDir(child.absoluteFilePath());
779 ++dirCount;
780 Q_FOREACH(QFileInfo xmlChild, childDir.entryInfoList(filters, QDir::Files)) {
781 ++setXmlCount;
782 }
783
784 if ((setXmlCount > 0) || (dirCount > 10)) {
785 break;
786 }
787 }
788
789 return (setXmlCount > 0);
790 }
791
792 int LocalAircraftCache::ratingFromProperties(SGPropertyNode* node, int ratingIndex)
793 {
794 const char* names[] = {"FDM", "systems", "cockpit", "model"};
795 assert((ratingIndex >= 0) && (ratingIndex < 4));
796 return node->getIntValue(names[ratingIndex]);
797 }
798
799 LocalAircraftCache::ParseSetXMLResult
800 LocalAircraftCache::readAircraftProperties(const SGPath &setPath, SGPropertyNode_ptr props)
801 {
802 // it woudld be race-y to touch the reosurce provider while the scan thread is running
803 // and our provider would confuse current-aircraft-dir lookups as well. Since we
804 // can't do thread-specific reosurce providers, we just bail here.
805 if (d->m_scanThread) {
806 return ParseSetXMLResult::Retry;
807 }
808
809 auto rm = simgear::ResourceManager::instance();
810
811 // ensure aircraft relative paths in the -set.xml parsing work
812
813 std::unique_ptr<ScanDirProvider> dp{new ScanDirProvider};
814 rm->addProvider(dp.get());
815
816 // we want to know the aircraft directory the aircraft lives in. This might
817 // be a manually added path (for local aircraft) or the install dir for the
818 // hangar (for packaged aircraft). Becuase -set.xml files are always found at
819 // /some/path/foobarAircraft/<aircraft-name>/some-set.xml, and the path we
820 // we want here is /some/path/foodbarAircraft, we use dirPath twice, and this
821 // works any kind of installed aircraft
822 const SGPath aircraftDirPath = setPath.dirPath().dirPath();
823 dp->setCurrentPath(aircraftDirPath);
824
825 dp->setCurrentAircraftPath(setPath);
826
827 ParseSetXMLResult result = ParseSetXMLResult::Failed;
828
829 try {
830 readProperties(setPath, props);
831 result = ParseSetXMLResult::Ok;
832 } catch (sg_exception& e) {
833 // malformed include or XML
834 qWarning() << "Problems occurred while parsing" << QString::fromStdString(setPath.utf8Str())
835 << "\n\t" << QString::fromStdString(e.getFormattedMessage());
836 }
837
838 rm->removeProvider(dp.get());
839 return result;
840 }
841
842 #include "LocalAircraftCache.moc"