swift
Loading...
Searching...
No Matches
dbautostashingcomponent.cpp
1// SPDX-FileCopyrightText: Copyright (C) 2016 swift Project Community / Contributors
2// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-swift-pilot-client-1
3
5
6#include <QCheckBox>
7#include <QDialogButtonBox>
8#include <QFlags>
9#include <QIntValidator>
10#include <QLineEdit>
11#include <QProgressBar>
12#include <QRadioButton>
13#include <QString>
14#include <QStringBuilder>
15#include <QWidget>
16#include <Qt>
17#include <QtGlobal>
18
19#include "ui_dbautostashingcomponent.h"
20
24#include "gui/guiapplication.h"
27#include "gui/views/viewbase.h"
29#include "misc/logcategories.h"
30#include "misc/sequence.h"
34
35using namespace swift::core;
36using namespace swift::misc;
37using namespace swift::misc::aviation;
38using namespace swift::misc::network;
39using namespace swift::misc::simulation;
40using namespace swift::gui::views;
41
43{
49
51 : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint),
53 {
54 ui->setupUi(this);
55 ui->tvp_StatusMessages->setResizeMode(CAircraftModelView::ResizingAuto);
56 ui->tvp_StatusMessages->menuAddItems(CAircraftModelView::MenuSave);
57 ui->le_MaxModelsStashed->setValidator(new QIntValidator(10, CDbStashComponent::MaxModelPublished, this));
58 Q_ASSERT_X(this->getMappingComponent(), Q_FUNC_INFO, "Expect mapping componet");
59
60 connect(ui->tb_ResetDescription, &QToolButton::clicked, this, &CDbAutoStashingComponent::resetDescription);
61
62 this->resetDescription();
63 }
64
66
68 {
69 switch (m_state)
70 {
71 case Running: return;
72 case Completed:
73 {
74 if (!m_modelsToStash.isEmpty())
75 {
76 // this removes previously stashed models
78 if (ui->cb_RemovedChecked->isChecked())
79 {
80 this->currentModelView()->removeModelsWithModelString(m_modelsToStash);
81 }
82 const CStatusMessage stashedMsg(this, CStatusMessage::SeverityInfo,
83 QStringLiteral("Auto stashed %1 models").arg(m_modelsToStash.size()));
84 this->addStatusMessage(stashedMsg);
85 m_modelsToStash.clear();
86 }
88 break;
89 }
90 default:
91 {
92 if (this->getSelectedOrAllCount() < 1)
93 {
94 const CStatusMessage m(this, CStatusMessage::SeverityError, u"No data, nothing to do");
95 this->addStatusMessage(m);
97 }
98 this->tryToStashModels();
99 }
100 }
101 }
102
104 {
105 this->initGui();
106 return QDialog::exec();
107 }
108
110 {
111 ui->bb_AutoStashing->setStandardButtons(QDialogButtonBox::Close);
112 this->setVisible(true);
113 }
114
115 void CDbAutoStashingComponent::resetDescription()
116 {
117 ui->rb_DescriptionEmptyOnly->setChecked(true);
118 ui->le_Description->setText(CAircraftModel::autoGenerated());
119 }
120
121 void CDbAutoStashingComponent::initGui()
122 {
123 m_state = Idle;
124 ui->bb_AutoStashing->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
125 ui->tvp_StatusMessages->clear();
126 m_noData = 0;
127 m_noValidationFailed = 0;
128 m_noStashed = 0;
130
131 if (!this->currentModelView())
132 {
133 const CStatusMessage m(this, CStatusMessage::SeverityError, u"No data for auto stashing");
134 this->addStatusMessage(m);
135 }
136 else
137 {
138 int selected = this->currentModelView()->selectedRowCount();
139 int all = this->currentModelView()->rowCount();
140 ui->le_Selected->setText(QString::number(selected));
141 QString allStr(QString::number(all));
143 {
144 allStr += u" (Max." % QString::number(CDbStashComponent::MaxModelPublished) % u")";
145 }
146 ui->le_All->setText(allStr);
147 if (ui->le_MaxModelsStashed->text().isEmpty())
148 {
149 ui->le_MaxModelsStashed->setText(all > 100 ? QStringLiteral("100") : QString());
150 }
151 if (selected > 0)
152 {
153 ui->rb_Selected->setChecked(true);
154 ui->rb_Selected->setEnabled(true);
155 }
156 else
157 {
158 ui->rb_All->setChecked(true);
159 ui->rb_Selected->setEnabled(false);
160 }
161 }
162 }
163
165 {
166 percent = std::clamp(percent, 0, 100);
167 ui->pb_StashingProgress->setValue(percent);
168 ui->le_Stashed->setText(QString::number(m_noStashed));
169 ui->le_NoData->setText(QString::number(m_noData));
170 ui->le_ValidationFailed->setText(QString::number(m_noValidationFailed));
171 }
172
173 int CDbAutoStashingComponent::getSelectedOrAllCount() const
174 {
175 if (!this->currentModelView())
176 {
177 return 0;
178 }
179 if (ui->rb_Selected->isChecked())
180 {
181 return this->currentModelView()->selectedRowCount();
182 }
183 else
184 {
185 return this->currentModelView()->rowCount();
186 }
187 }
188
189 CAircraftModelView *CDbAutoStashingComponent::currentModelView() const
190 {
191 return this->getMappingComponent()->currentModelView();
192 }
193
194 void CDbAutoStashingComponent::addStatusMessage(const CStatusMessage &msg)
195 {
196 if (msg.isEmpty())
197 {
198 return;
199 }
200 ui->tvp_StatusMessages->insert(msg);
201 }
202
203 void CDbAutoStashingComponent::addStatusMessage(const CStatusMessage &msg, const CAircraftModel &model)
204 {
205 if (msg.isEmpty())
206 {
207 return;
208 }
209 if (model.hasModelString())
210 {
211 CStatusMessage prefixMessage(msg);
212 prefixMessage.prependMessage(QString(model.getModelString() + ", " + model.getMembersDbStatus() + ": "));
213 ui->tvp_StatusMessages->insert(prefixMessage);
214 }
215 else
216 {
217 ui->tvp_StatusMessages->insert(msg);
218 }
219 }
220
221 void CDbAutoStashingComponent::tryToStashModels()
222 {
223 Q_ASSERT_X(this->currentModelView(), Q_FUNC_INFO, "No view");
224 const CAircraftModelList models(ui->rb_Selected->isChecked() ?
225 this->currentModelView()->selectedObjects() :
226 this->currentModelView()->containerOrFilteredContainer());
227 if (models.isEmpty())
228 {
229 return;
230 }
231 if (!sGui || sGui->isShuttingDown())
232 {
233 return;
234 }
235
236 // we have data and are good to go
237 m_state = Running;
238 const int all = models.size();
239
240 // maximum
242 const QString maxStr(ui->le_MaxModelsStashed->text());
243 bool okMaxStr = true;
244 if (!maxStr.isEmpty())
245 {
246 max = maxStr.toInt(&okMaxStr);
247 }
248 if (!okMaxStr || max > all)
249 {
250 max = all;
251 }
252
253 // override description
254 const QString description(ui->le_Description->text().trimmed());
255
256 // temp livery if applicable
257 const CLivery tempLivery(ui->cb_UseTempLivery->isChecked() ? getTempLivery() : CLivery());
258
259 int c = 0;
260 CAircraftModelList autoStashed;
261 for (const CAircraftModel &model : models)
262 {
263 CAircraftModel stashModel(model);
264 const bool stashed = this->tryToStashModel(stashModel, tempLivery);
265 if (stashed)
266 {
267 if (!description.isEmpty())
268 {
269 this->setModelDescription(stashModel, description);
270 }
271 autoStashed.push_back(stashModel);
272 }
273
274 c++;
275 if (c % 25 == 0)
276 {
277 Q_ASSERT_X(c <= all, Q_FUNC_INFO, "illegal numbers");
279
280 int percent = c * 100 / all;
281 if (max < all)
282 {
283 int maxPercent = autoStashed.size() * 100 / max;
284 percent = std::max(maxPercent, percent);
285 }
286 this->updateProgressIndicator(percent);
287 }
288 if (autoStashed.size() >= max)
289 {
290 break;
291 }
292 }
293
294 this->updateProgressIndicator(100);
296
297 const CStatusMessage stashedMsg(this, CStatusMessage::SeverityInfo,
298 QStringLiteral("Ready to auto stash %1 models").arg(autoStashed.size()));
299 this->addStatusMessage(stashedMsg);
300 m_modelsToStash = autoStashed;
301 m_state = Completed;
302 }
303
304 bool CDbAutoStashingComponent::tryToStashModel(CAircraftModel &model, const CLivery &tempLivery)
305 {
306 const bool useTempLivery = tempLivery.isLoadedFromDb();
307
308 // no airline and no livery, here replaced by temp livery
309 if (useTempLivery && !model.hasAirlineDesignator() && !model.getLivery().hasValidDbKey())
310 {
311 model.setLivery(tempLivery);
312 }
313
315 if (!model.hasModelString())
316 {
317 this->addStatusMessage(CStatusMessage(this, CStatusMessage::SeverityError, u"No model string"));
318 m_noData++;
319 return false;
320 }
321
322 if (!model.hasAircraftDesignator())
323 {
324 this->addStatusMessage(CStatusMessage(this, CStatusMessage::SeverityError, u"No aircraft designator"),
325 model);
326 m_noData++;
327 return false;
328 }
329
330 if (!model.hasAirlineDesignator() && !model.getLivery().hasValidDbKey())
331 {
332 // no valid airline and NO DB livery
333 // we try one fallback
334 const QString liveryCombinedCode = model.getLivery().getCombinedCode();
335 bool fallback = false;
336 if (liveryCombinedCode.length() == 3 || liveryCombinedCode.length() == 4)
337 {
338 // could we use the combined code as airline
339 if (CAirlineIcaoCode::isValidAirlineDesignator(liveryCombinedCode))
340 {
341 model.setAirlineIcaoDesignator(liveryCombinedCode);
342 fallback = true;
343 }
344 }
345
346 // if there is no livery (normal) we need an airline
347 if (!fallback)
348 {
349 this->addStatusMessage(CStatusMessage(this, CStatusMessage::SeverityError, u"No airline designator"),
350 model);
351 m_noData++;
352 return false;
353 }
354 }
355
356 // stash here consolidates with DB data and validates
357 bool stashed = false;
358 const CAircraftModel stashModel(this->getMappingComponent()->consolidateModel(model));
359 CStatusMessageList validationMsgs(stashModel.validate(true));
360 validationMsgs.removeWarningsAndBelow();
361 CStatusMessage msg = validationMsgs.toSingleMessage();
363 {
364 m_noValidationFailed++;
365 }
366 else
367 {
368 msg = CStatusMessage(this, CStatusMessage::SeverityInfo, u"Stashed succesfully");
369 stashed = true;
370 m_noStashed++;
371 model = stashModel;
372 }
373 this->addStatusMessage(msg, stashModel);
374 return stashed;
375 }
376
377 void CDbAutoStashingComponent::setModelDescription(CAircraftModel &model, const QString &description) const
378 {
379 if (description.isEmpty())
380 {
381 return;
382 }
383 if (ui->rb_All->isChecked())
384 {
385 model.setDescription(description);
386 }
387 else
388 {
389 // only for "empty" ones
390 if (model.hasDescription(true))
391 {
392 return;
393 }
394 model.setDescription(description);
395 }
396 }
397
398 swift::misc::aviation::CLivery CDbAutoStashingComponent::getTempLivery()
399 {
400 if (!sGui || !sGui->hasWebDataServices())
401 {
402 return {};
403 }
405 }
406} // namespace swift::gui::components
bool hasWebDataServices() const
Web data services available?
bool isShuttingDown() const
Is application shutting down?
CWebDataServices * getWebDataServices() const
Get the web data services.
swift::misc::aviation::CLivery getTempLiveryOrDefault() const
The temp. livery if available.
void processEventsToRefreshGui() const
Allow the GUI to refresh by processing events, call the event loop.
void updateProgressIndicator(int percent)
Update the progress indicator 0..100.
static const QStringList & getLogCategories()
Log categories.
CDbAutoStashingComponent(QWidget *parent=nullptr)
Constructor.
CDbMappingComponent * getMappingComponent() const
Get the mapping component.
void replaceStashedModelsUnvalidated(const swift::misc::simulation::CAircraftModelList &models) const
Replace models, no validation.
views::CAircraftModelView * currentModelView() const
Current model view.
static constexpr int MaxModelPublished
Number of models which can be published at once.
void insert(const ObjectType &value, bool resize=true)
Insert.
Definition viewbase.cpp:138
int rowCount() const
Elements in container.
Definition viewbase.cpp:467
@ ResizingAuto
resizing when below threshold,
Definition viewbase.h:101
int selectedRowCount() const
Number of selected rows.
static const QString & mapping()
Mapping.
static const QString & guiComponent()
GUI components.
bool isEmpty() const
Message empty.
size_type size() const
Returns number of elements in the sequence.
Definition sequence.h:273
void push_back(const T &value)
Appends an element at the end of the sequence.
Definition sequence.h:308
Streamable status message, e.g.
static constexpr auto SeverityInfo
Status severities.
static constexpr auto SeverityError
Status severities.
StatusSeverity getSeverity() const
Message severity.
static bool isValidAirlineDesignator(const QString &airline)
Valid designator?
const QString & getCombinedCode() const
Combined code.
Definition livery.h:71
bool isLoadedFromDb() const
Loaded from DB.
Definition datastore.cpp:58
bool hasValidDbKey() const
Has valid DB key.
Definition datastore.h:102
bool hasAirlineDesignator() const
Airline designator?
QString getMembersDbStatus() const
Info, which members (Livery, Aircraft ICAO, ...) are already based on DB data.
const aviation::CLivery & getLivery() const
Get livery.
bool hasAircraftDesignator() const
Has aircraft designator?
void setDescription(const QString &description)
Descriptive text.
const QString & getModelString() const
Model key, either queried or loaded from simulator model.
bool hasDescription(bool ignoreAutoGenerated=false) const
Description.
bool setAirlineIcaoDesignator(const QString &designator)
Set airline ICAO code designator.
bool hasModelString() const
Non empty model string?
void setLivery(const aviation::CLivery &livery)
Livery.
static const QString & autoGenerated()
Hint, that model was automatically generated (e.g. by auto stashing).
SWIFT_GUI_EXPORT swift::gui::CGuiApplication * sGui
Single instance of GUI application object.
Backend services of the swift project, like dealing with the network or the simulators.
Definition actionbind.cpp:7
High level reusable GUI components.
Views, mainly QTableView.
Free functions in swift::misc.
void clicked(bool checked)
QDialog(QWidget *parent, Qt::WindowFlags f)
virtual void accept()
virtual int exec()
virtual void setVisible(bool visible) override
QMetaObject::Connection connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
QObject * parent() const const
T qobject_cast(QObject *object)
bool isEmpty() const const
qsizetype length() const const
QString number(double n, char format, int precision)
QWidget(QWidget *parent, Qt::WindowFlags f)