swift
Loading...
Searching...
No Matches
vpilotrulesreader.cpp
1// SPDX-FileCopyrightText: Copyright (C) 2015 swift Project Community / Contributors
2// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-swift-pilot-client-1
3
5
6#include <QByteArray>
7#include <QDateTime>
8#include <QDir>
9#include <QDomDocument>
10#include <QDomNamedNodeMap>
11#include <QDomNode>
12#include <QDomNodeList>
13#include <QFile>
14#include <QFileInfo>
15#include <QFileInfoList>
16#include <QIODevice>
17#include <QReadLocker>
18#include <QStandardPaths>
19#include <QTimer>
20#include <QWriteLocker>
21#include <QtGlobal>
22
23#include "misc/logmessage.h"
25#include "misc/statusmessage.h"
26#include "misc/stringutils.h"
27#include "misc/worker.h"
28
29using namespace swift::misc;
30
31namespace swift::misc::simulation::fscommon
32{
34 {
35 if (standardDirectory)
36 {
38 }
39 }
40
42
44 {
45 QReadLocker l(&m_lockData);
46 return m_fileList;
47 }
48
50 {
51 QReadLocker l(&m_lockData);
52 return !m_fileList.isEmpty();
53 }
54
56 {
57 QWriteLocker l(&m_lockData);
58 if (this->m_fileList.contains(fileName))
59 {
60 return;
61 }
62 this->m_fileList.append(fileName);
63 }
64
66 {
67 QDir dir(directory);
68 if (!dir.exists())
69 {
70 return;
71 }
72 QStringList nameFilters({ "*.vmr" });
73 QFileInfoList entries = dir.entryInfoList(nameFilters, QDir::Files | QDir::Readable);
74 for (const QFileInfo &file : entries)
75 {
76 this->addFilename(file.absoluteFilePath());
77 }
78 }
79
81 {
82 QReadLocker l(&m_lockData);
83 return m_loadedFiles;
84 }
85
87 {
88 QReadLocker l(&m_lockData);
89 return m_rules;
90 }
91
92 int CVPilotRulesReader::getModelsCount() const { return this->m_cachedVPilotModels.getThreadLocal().size(); }
93
95 {
96 // already cached?
97 CAircraftModelList vPilotModels(this->m_cachedVPilotModels.get());
98 if (!vPilotModels.isEmpty() || m_rules.isEmpty())
99 {
100 return vPilotModels;
101 }
102
103 // important: that can take a while and should normally
104 // run in background
105 const CVPilotModelRuleSet rules(getRules()); // thread safe copy
106 vPilotModels = rules.toAircraftModels(); // long lasting operation
107 this->ps_setCache(vPilotModels);
108 return vPilotModels;
109 }
110
111 CAircraftModelList CVPilotRulesReader::getAsModelsFromCache() const { return this->m_cachedVPilotModels.get(); }
112
114 {
115 QReadLocker l(&m_lockData);
116 return m_rules.size();
117 }
118
120 {
121 QWriteLocker l(&m_lockData);
122 m_shutdown = true;
123 }
124
126 {
128 static QString directory;
129 if (directory.isEmpty())
130 {
132 if (!directory.endsWith('/'))
133 {
134 directory.append('/');
135 }
136 directory.append("vPilot Files/Model Matching Rule Sets");
137 }
138 return directory;
139 }
140
141 bool CVPilotRulesReader::read(bool convertToModels)
142 {
143 int loadedFiles = 0;
144 QStringList filesWithProblems;
146 const QStringList fileList(getFiles());
147 for (const QString &fn : fileList)
148 {
149 if (m_shutdown)
150 {
151 return false;
152 }
153 loadedFiles++;
154 bool s = this->loadFile(fn, rules);
155 if (!s)
156 {
157 filesWithProblems.append(fn);
158 }
159 }
160
161 {
162 QWriteLocker l(&m_lockData);
163 this->m_loadedFiles = loadedFiles;
164 this->m_fileListWithProblems = filesWithProblems;
165 this->m_rules = rules;
166 if (m_shutdown)
167 {
168 return false;
169 }
170 }
171
172 const bool success = loadedFiles > 0;
173 if (convertToModels)
174 {
175 const CAircraftModelList vPilotModels(rules.toAircraftModels()); // long lasting operation
176 this->ps_setCache(vPilotModels);
177 }
178
179 emit readFinished(success);
180 return success;
181 }
182
184 {
185 // set a thread safe flag
186 {
187 QWriteLocker l(&m_lockData);
188 if (m_asyncLoadInProgress || m_shutdown)
189 {
190 return nullptr;
191 }
192 m_asyncLoadInProgress = true;
193 }
195 this, "CVPilotRulesReader", [this, convertToModels]() { this->read(convertToModels); });
196 worker->then(this, &CVPilotRulesReader::ps_readInBackgroundFinished);
197 return worker;
198 }
199
200 void CVPilotRulesReader::ps_readInBackgroundFinished()
201 {
202 QWriteLocker l(&m_lockData);
203 m_asyncLoadInProgress = false;
204 }
205
206 void CVPilotRulesReader::ps_onVPilotCacheChanged()
207 {
208 // void
209 }
210
211 void CVPilotRulesReader::ps_setCache(const CAircraftModelList &models)
212 {
213 if (this->m_cachedVPilotModels.isOwnerThread())
214 {
216 {
217 QWriteLocker l(&m_lockData);
218 m = this->m_cachedVPilotModels.set(models);
219 }
220 if (m.isFailure())
221 {
223 }
224 }
225 else
226 {
227 QTimer::singleShot(0, this, [this, models]() { this->ps_setCache(models); });
228 }
229 }
230
231 bool CVPilotRulesReader::loadFile(const QString &fileName, CVPilotModelRuleSet &ruleSet)
232 {
233 QFile f(fileName);
234 if (!f.exists())
235 {
236 return false;
237 }
238 if (!f.open(QFile::ReadOnly | QFile::Text))
239 {
240 return false;
241 }
242 QByteArray fc = f.readAll();
243 if (fc.isEmpty())
244 {
245 return false;
246 }
247 QDomDocument doc;
248 if (!doc.setContent(fc))
249 {
250 return false;
251 }
252 QDomNodeList rules = doc.elementsByTagName("ModelMatchRule");
253 if (rules.isEmpty())
254 {
255 return false;
256 }
257
258 QDomNodeList mmRuleSet = doc.elementsByTagName("ModelMatchRuleSet");
259 if (mmRuleSet.size() < 1)
260 {
261 return true;
262 }
263
264 const QDomNamedNodeMap attributes = mmRuleSet.at(0).attributes();
265 QString folder = attributes.namedItem("Folder").nodeValue().trimmed();
266 if (folder.isEmpty())
267 {
268 folder = QFileInfo(fileName).fileName().replace(".vmr", "");
269 }
270
271 // "2/1/2014 12:00:00 AM", "5/26/2014 2:00:00 PM"
272 const QString updated = attributes.namedItem("UpdatedOn").nodeValue();
273 QDateTime qt = fromStringUtc(updated, "M/d/yyyy h:mm:ss AP");
274 qint64 updatedTimestamp = qt.toMSecsSinceEpoch();
275
276 int rulesSize = rules.size();
277 for (int i = 0; i < rulesSize; i++)
278 {
279 const QDomNamedNodeMap ruleAttributes = rules.at(i).attributes();
280 const QString typeCode = ruleAttributes.namedItem("TypeCode").nodeValue();
281 const QString modelName = ruleAttributes.namedItem("ModelName").nodeValue();
282 // remark, callsign prefix is airline ICAO code
283 const QString callsignPrefix = ruleAttributes.namedItem("CallsignPrefix").nodeValue();
284 if (modelName.isEmpty())
285 {
286 continue;
287 }
288
289 // split if we have multiple models
290 if (modelName.contains("//"))
291 {
292 // multiple models
293 const QStringList models = modelName.split("//");
294 for (const QString &model : models)
295 {
296 if (model.isEmpty())
297 {
298 continue;
299 }
300 CVPilotModelRule rule(model, folder, typeCode, callsignPrefix, updatedTimestamp);
301 ruleSet.push_back(rule);
302 }
303 }
304 else
305 {
306 // single model
307 CVPilotModelRule rule(modelName, folder, typeCode, callsignPrefix, updatedTimestamp);
308 ruleSet.push_back(rule);
309 }
310 }
311 return true;
312 }
313
314} // namespace swift::misc::simulation::fscommon
static void preformatted(const CStatusMessage &statusMessage)
Sends a verbatim, preformatted message to the log.
bool isEmpty() const
Synonym for empty.
Definition sequence.h:285
Streamable status message, e.g.
bool isFailure() const
Operation considered unsuccessful.
void then(T *context, F functor)
Connects to a functor or method which will be called when the task is finished.
Definition worker.h:97
Class for doing some arbitrary parcel of work in its own thread.
Definition worker.h:230
static CWorker * fromTask(QObject *owner, const QString &name, F &&task)
Returns a new worker object which lives in a new thread.
Definition worker.h:243
Value object encapsulating a list of aircraft models.
Value object reading a set of vPilot rules.
simulation::CAircraftModelList toAircraftModels() const
To aircraft models.
swift::misc::simulation::CAircraftModelList getAsModels()
Get as models.
CVPilotRulesReader(bool standardDirectory=true, QObject *parent=nullptr)
Constructor.
void addFilename(const QString &fileName)
File names.
swift::misc::simulation::CAircraftModelList getAsModelsFromCache() const
Get as models from cache.
static const QString & standardMappingsDirectory()
The standard directory for vPilot mappings.
void addDirectory(const QString &directory)
Directory with .vmr files.
swift::misc::CWorker * readInBackground(bool convertToModels)
Load data in background thread.
CVPilotModelRuleSet getRules() const
Loaded rules.
Free functions in swift::misc.
SWIFT_MISC_EXPORT QDateTime fromStringUtc(const QString &dateTimeString, const QString &format)
Same as QDateTime::fromString but QDateTime will be set to UTC.
bool isEmpty() const const
qint64 toMSecsSinceEpoch() const const
QFileInfoList entryInfoList(QDir::Filters filters, QDir::SortFlags sort) const const
bool exists() const const
QDomNodeList elementsByTagName(const QString &tagname) const const
QDomDocument::ParseResult setContent(QAnyStringView text, QDomDocument::ParseOptions options)
QDomNode namedItem(const QString &name) const const
QDomNamedNodeMap attributes() const const
QString nodeValue() const const
QDomNode at(int index) const const
bool isEmpty() const const
int size() const const
void append(QList< T > &&value)
const T & constFirst() const const
QObject(QObject *parent)
QObject * parent() const const
QStringList standardLocations(QStandardPaths::StandardLocation type)
QString & append(QChar ch)
bool contains(QChar ch, Qt::CaseSensitivity cs) const const
bool endsWith(QChar c, Qt::CaseSensitivity cs) const const
bool isEmpty() const const
QString & replace(QChar before, QChar after, Qt::CaseSensitivity cs)
QStringList split(QChar sep, Qt::SplitBehavior behavior, Qt::CaseSensitivity cs) const const
QString trimmed() const const