Apply clang-format to Lts/Common and DTC/enum headers

- Formatted all CodeGen module files (9 files)
- Formatted LtsAppDescriptor module files
- Formatted LtsAppManager/AppChooser files
- Applied clang-format to all DTC and enum headers across modules
- Removed coordTransTests from CommonUnitTestsPlaceholder (moved to tests/)

Cosmetic changes only, no functional modifications.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
torstenandCopilot committed 2026-08-19 14:46:29 +02:00
1 parent 1881d68aef
commit d6b6ffce7c
848 files changed
+88262 -98977

No files matched your search

@@ -1,4 +1,5 @@
#pragma once #pragma once
// STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert
// Für die Migration erstellen wir minimale Forward-Declarations // Für die Migration erstellen wir minimale Forward-Declarations
@@ -6,7 +7,7 @@ namespace AreaEffectSimulation
{ {
namespace Interface namespace Interface
{ {
class Dtc; class Dtc;
class Ftc; class Ftc;
} } // namespace Interface
} } // namespace AreaEffectSimulation
@@ -1,24 +1,19 @@
#pragma once #pragma once
// STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert
// Für die Migration erstellen wir minimale Typ-Definitionen // Für die Migration erstellen wir minimale Typ-Definitionen
namespace AreaEffectSimulation namespace AreaEffectSimulation
{ {
// Placeholder enums - werden durch echte DDS-Typen ersetzt // Placeholder enums - werden durch echte DDS-Typen ersetzt
enum class SymbolAppearance : int { enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 };
Solid = 0,
Dashed = 1,
Dotted = 2
};
enum class SymbolVisibility : int { enum class SymbolVisibility : int { Visible = 0, Hidden = 1 };
Visible = 0,
Hidden = 1
};
struct UnitSymbolPosition { struct UnitSymbolPosition
double x = 0.0; {
double y = 0.0; double x = 0.0;
double z = 0.0; double y = 0.0;
double z = 0.0;
}; };
} } // namespace AreaEffectSimulation
@@ -1,4 +1,5 @@
#pragma once #pragma once
// STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert
// Für die Migration erstellen wir minimale Forward-Declarations // Für die Migration erstellen wir minimale Forward-Declarations
@@ -6,7 +7,7 @@ namespace AssetManagement
{ {
namespace Interface namespace Interface
{ {
class Dtc; class Dtc;
class Ftc; class Ftc;
} } // namespace Interface
} } // namespace AssetManagement
@@ -1,24 +1,19 @@
#pragma once #pragma once
// STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert
// Für die Migration erstellen wir minimale Typ-Definitionen // Für die Migration erstellen wir minimale Typ-Definitionen
namespace AssetManagement namespace AssetManagement
{ {
// Placeholder enums - werden durch echte DDS-Typen ersetzt // Placeholder enums - werden durch echte DDS-Typen ersetzt
enum class SymbolAppearance : int { enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 };
Solid = 0,
Dashed = 1,
Dotted = 2
};
enum class SymbolVisibility : int { enum class SymbolVisibility : int { Visible = 0, Hidden = 1 };
Visible = 0,
Hidden = 1
};
struct UnitSymbolPosition { struct UnitSymbolPosition
double x = 0.0; {
double y = 0.0; double x = 0.0;
double z = 0.0; double y = 0.0;
double z = 0.0;
}; };
} } // namespace AssetManagement
@@ -1,4 +1,5 @@
#pragma once #pragma once
// STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert
// Für die Migration erstellen wir minimale Forward-Declarations // Für die Migration erstellen wir minimale Forward-Declarations
@@ -6,7 +7,7 @@ namespace AudioVideoManagement
{ {
namespace Interface namespace Interface
{ {
class Dtc; class Dtc;
class Ftc; class Ftc;
} } // namespace Interface
} } // namespace AudioVideoManagement
@@ -1,24 +1,19 @@
#pragma once #pragma once
// STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert
// Für die Migration erstellen wir minimale Typ-Definitionen // Für die Migration erstellen wir minimale Typ-Definitionen
namespace AudioVideoManagement namespace AudioVideoManagement
{ {
// Placeholder enums - werden durch echte DDS-Typen ersetzt // Placeholder enums - werden durch echte DDS-Typen ersetzt
enum class SymbolAppearance : int { enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 };
Solid = 0,
Dashed = 1,
Dotted = 2
};
enum class SymbolVisibility : int { enum class SymbolVisibility : int { Visible = 0, Hidden = 1 };
Visible = 0,
Hidden = 1
};
struct UnitSymbolPosition { struct UnitSymbolPosition
double x = 0.0; {
double y = 0.0; double x = 0.0;
double z = 0.0; double y = 0.0;
double z = 0.0;
}; };
} } // namespace AudioVideoManagement
@@ -1,4 +1,5 @@
#pragma once #pragma once
// STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert
// Für die Migration erstellen wir minimale Forward-Declarations // Für die Migration erstellen wir minimale Forward-Declarations
@@ -6,7 +7,7 @@ namespace Buildings
{ {
namespace Interface namespace Interface
{ {
class Dtc; class Dtc;
class Ftc; class Ftc;
} } // namespace Interface
} } // namespace Buildings
@@ -1,24 +1,19 @@
#pragma once #pragma once
// STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert
// Für die Migration erstellen wir minimale Typ-Definitionen // Für die Migration erstellen wir minimale Typ-Definitionen
namespace Buildings namespace Buildings
{ {
// Placeholder enums - werden durch echte DDS-Typen ersetzt // Placeholder enums - werden durch echte DDS-Typen ersetzt
enum class SymbolAppearance : int { enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 };
Solid = 0,
Dashed = 1,
Dotted = 2
};
enum class SymbolVisibility : int { enum class SymbolVisibility : int { Visible = 0, Hidden = 1 };
Visible = 0,
Hidden = 1
};
struct UnitSymbolPosition { struct UnitSymbolPosition
double x = 0.0; {
double y = 0.0; double x = 0.0;
double z = 0.0; double y = 0.0;
double z = 0.0;
}; };
} } // namespace Buildings
@@ -1,4 +1,5 @@
#pragma once #pragma once
// STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert
// Für die Migration erstellen wir minimale Forward-Declarations // Für die Migration erstellen wir minimale Forward-Declarations
@@ -6,7 +7,7 @@ namespace CentralEffectSimulation
{ {
namespace Interface namespace Interface
{ {
class Dtc; class Dtc;
class Ftc; class Ftc;
} } // namespace Interface
} } // namespace CentralEffectSimulation
@@ -1,4 +1,5 @@
#pragma once #pragma once
// STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert
// Für die Migration erstellen wir minimale Forward-Declarations // Für die Migration erstellen wir minimale Forward-Declarations
@@ -6,7 +7,7 @@ namespace CodificationManagement
{ {
namespace Interface namespace Interface
{ {
class Dtc; class Dtc;
class Ftc; class Ftc;
} } // namespace Interface
} } // namespace CodificationManagement
@@ -1,4 +1,5 @@
#pragma once #pragma once
// STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert
// Für die Migration erstellen wir minimale Forward-Declarations // Für die Migration erstellen wir minimale Forward-Declarations
@@ -6,7 +7,7 @@ namespace ComponentMonitor
{ {
namespace Interface namespace Interface
{ {
class Dtc; class Dtc;
class Ftc; class Ftc;
} } // namespace Interface
} } // namespace ComponentMonitor
@@ -1,4 +1,5 @@
#pragma once #pragma once
// STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert
// Für die Migration erstellen wir minimale Forward-Declarations // Für die Migration erstellen wir minimale Forward-Declarations
@@ -6,7 +7,7 @@ namespace Core
{ {
namespace Interface namespace Interface
{ {
class Dtc; class Dtc;
class Ftc; class Ftc;
} } // namespace Interface
} } // namespace Core
@@ -1,24 +1,19 @@
#pragma once #pragma once
// STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert
// Für die Migration erstellen wir minimale Typ-Definitionen // Für die Migration erstellen wir minimale Typ-Definitionen
namespace Core namespace Core
{ {
// Placeholder enums - werden durch echte DDS-Typen ersetzt // Placeholder enums - werden durch echte DDS-Typen ersetzt
enum class SymbolAppearance : int { enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 };
Solid = 0,
Dashed = 1,
Dotted = 2
};
enum class SymbolVisibility : int { enum class SymbolVisibility : int { Visible = 0, Hidden = 1 };
Visible = 0,
Hidden = 1
};
struct UnitSymbolPosition { struct UnitSymbolPosition
double x = 0.0; {
double y = 0.0; double x = 0.0;
double z = 0.0; double y = 0.0;
double z = 0.0;
}; };
} } // namespace Core
@@ -1,4 +1,5 @@
#pragma once #pragma once
// STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert
// Für die Migration erstellen wir minimale Forward-Declarations // Für die Migration erstellen wir minimale Forward-Declarations
@@ -6,7 +7,7 @@ namespace Core
{ {
namespace Interface namespace Interface
{ {
class Dtc; class Dtc;
class Ftc; class Ftc;
} } // namespace Interface
} } // namespace Core
@@ -1,24 +1,19 @@
#pragma once #pragma once
// STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert
// Für die Migration erstellen wir minimale Typ-Definitionen // Für die Migration erstellen wir minimale Typ-Definitionen
namespace Core namespace Core
{ {
// Placeholder enums - werden durch echte DDS-Typen ersetzt // Placeholder enums - werden durch echte DDS-Typen ersetzt
enum class SymbolAppearance : int { enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 };
Solid = 0,
Dashed = 1,
Dotted = 2
};
enum class SymbolVisibility : int { enum class SymbolVisibility : int { Visible = 0, Hidden = 1 };
Visible = 0,
Hidden = 1
};
struct UnitSymbolPosition { struct UnitSymbolPosition
double x = 0.0; {
double y = 0.0; double x = 0.0;
double z = 0.0; double y = 0.0;
double z = 0.0;
}; };
} } // namespace Core
@@ -1,4 +1,5 @@
#pragma once #pragma once
// STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert
// Für die Migration erstellen wir minimale Forward-Declarations // Für die Migration erstellen wir minimale Forward-Declarations
@@ -6,7 +7,7 @@ namespace DDS
{ {
namespace Interface namespace Interface
{ {
class Dtc; class Dtc;
class Ftc; class Ftc;
} } // namespace Interface
} } // namespace DDS
@@ -1,4 +1,5 @@
#pragma once #pragma once
// STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert
// Für die Migration erstellen wir minimale Forward-Declarations // Für die Migration erstellen wir minimale Forward-Declarations
@@ -6,7 +7,7 @@ namespace EffectShowClient
{ {
namespace Interface namespace Interface
{ {
class Dtc; class Dtc;
class Ftc; class Ftc;
} } // namespace Interface
} } // namespace EffectShowClient
@@ -1,4 +1,5 @@
#pragma once #pragma once
// STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert
// Für die Migration erstellen wir minimale Forward-Declarations // Für die Migration erstellen wir minimale Forward-Declarations
@@ -6,7 +7,7 @@ namespace EffectShowManagement
{ {
namespace Interface namespace Interface
{ {
class Dtc; class Dtc;
class Ftc; class Ftc;
} } // namespace Interface
} } // namespace EffectShowManagement
@@ -1,4 +1,5 @@
#pragma once #pragma once
// STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert
// Für die Migration erstellen wir minimale Forward-Declarations // Für die Migration erstellen wir minimale Forward-Declarations
@@ -6,7 +7,7 @@ namespace Evaluations
{ {
namespace Interface namespace Interface
{ {
class Dtc; class Dtc;
class Ftc; class Ftc;
} } // namespace Interface
} } // namespace Evaluations
@@ -1,4 +1,5 @@
#pragma once #pragma once
// STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert
// Für die Migration erstellen wir minimale Forward-Declarations // Für die Migration erstellen wir minimale Forward-Declarations
@@ -6,7 +7,7 @@ namespace ExerciseEventManagement
{ {
namespace Interface namespace Interface
{ {
class Dtc; class Dtc;
class Ftc; class Ftc;
} } // namespace Interface
} } // namespace ExerciseEventManagement
@@ -1,4 +1,5 @@
#pragma once #pragma once
// STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert
// Für die Migration erstellen wir minimale Forward-Declarations // Für die Migration erstellen wir minimale Forward-Declarations
@@ -6,7 +7,7 @@ namespace ExerciseManagement
{ {
namespace Interface namespace Interface
{ {
class Dtc; class Dtc;
class Ftc; class Ftc;
} } // namespace Interface
} } // namespace ExerciseManagement
@@ -1,24 +1,19 @@
#pragma once #pragma once
// STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert
// Für die Migration erstellen wir minimale Typ-Definitionen // Für die Migration erstellen wir minimale Typ-Definitionen
namespace ExerciseManagement namespace ExerciseManagement
{ {
// Placeholder enums - werden durch echte DDS-Typen ersetzt // Placeholder enums - werden durch echte DDS-Typen ersetzt
enum class SymbolAppearance : int { enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 };
Solid = 0,
Dashed = 1,
Dotted = 2
};
enum class SymbolVisibility : int { enum class SymbolVisibility : int { Visible = 0, Hidden = 1 };
Visible = 0,
Hidden = 1
};
struct UnitSymbolPosition { struct UnitSymbolPosition
double x = 0.0; {
double y = 0.0; double x = 0.0;
double z = 0.0; double y = 0.0;
double z = 0.0;
}; };
} } // namespace ExerciseManagement
@@ -1,4 +1,5 @@
#pragma once #pragma once
// STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert
// Für die Migration erstellen wir minimale Forward-Declarations // Für die Migration erstellen wir minimale Forward-Declarations
@@ -6,7 +7,7 @@ namespace FileManagement
{ {
namespace Interface namespace Interface
{ {
class Dtc; class Dtc;
class Ftc; class Ftc;
} } // namespace Interface
} } // namespace FileManagement
@@ -1,24 +1,19 @@
#pragma once #pragma once
// STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert
// Für die Migration erstellen wir minimale Typ-Definitionen // Für die Migration erstellen wir minimale Typ-Definitionen
namespace FileManagement namespace FileManagement
{ {
// Placeholder enums - werden durch echte DDS-Typen ersetzt // Placeholder enums - werden durch echte DDS-Typen ersetzt
enum class SymbolAppearance : int { enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 };
Solid = 0,
Dashed = 1,
Dotted = 2
};
enum class SymbolVisibility : int { enum class SymbolVisibility : int { Visible = 0, Hidden = 1 };
Visible = 0,
Hidden = 1
};
struct UnitSymbolPosition { struct UnitSymbolPosition
double x = 0.0; {
double y = 0.0; double x = 0.0;
double z = 0.0; double y = 0.0;
double z = 0.0;
}; };
} } // namespace FileManagement
@@ -1,4 +1,5 @@
#pragma once #pragma once
// STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert
// Für die Migration erstellen wir minimale Forward-Declarations // Für die Migration erstellen wir minimale Forward-Declarations
@@ -6,7 +7,7 @@ namespace GuezIedManagement
{ {
namespace Interface namespace Interface
{ {
class Dtc; class Dtc;
class Ftc; class Ftc;
} } // namespace Interface
} } // namespace GuezIedManagement
@@ -1,4 +1,5 @@
#pragma once #pragma once
// STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert
// Für die Migration erstellen wir minimale Forward-Declarations // Für die Migration erstellen wir minimale Forward-Declarations
@@ -6,7 +7,7 @@ namespace GuezNasat
{ {
namespace Interface namespace Interface
{ {
class Dtc; class Dtc;
class Ftc; class Ftc;
} } // namespace Interface
} } // namespace GuezNasat
@@ -1,4 +1,5 @@
#pragma once #pragma once
// STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert
// Für die Migration erstellen wir minimale Forward-Declarations // Für die Migration erstellen wir minimale Forward-Declarations
@@ -6,7 +7,7 @@ namespace InfrastructureManagement
{ {
namespace Interface namespace Interface
{ {
class Dtc; class Dtc;
class Ftc; class Ftc;
} } // namespace Interface
} } // namespace InfrastructureManagement
@@ -1,24 +1,19 @@
#pragma once #pragma once
// STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert
// Für die Migration erstellen wir minimale Typ-Definitionen // Für die Migration erstellen wir minimale Typ-Definitionen
namespace InfrastructureManagement namespace InfrastructureManagement
{ {
// Placeholder enums - werden durch echte DDS-Typen ersetzt // Placeholder enums - werden durch echte DDS-Typen ersetzt
enum class SymbolAppearance : int { enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 };
Solid = 0,
Dashed = 1,
Dotted = 2
};
enum class SymbolVisibility : int { enum class SymbolVisibility : int { Visible = 0, Hidden = 1 };
Visible = 0,
Hidden = 1
};
struct UnitSymbolPosition { struct UnitSymbolPosition
double x = 0.0; {
double y = 0.0; double x = 0.0;
double z = 0.0; double y = 0.0;
double z = 0.0;
}; };
} } // namespace InfrastructureManagement
+258 -281
View File
@@ -1,10 +1,11 @@
#include "CppTopicGeneratorGrantlee.h" #include "CppTopicGeneratorGrantlee.h"
#include "StructBuilder.h" #include "StructBuilder.h"
#include <QCryptographicHash>
#include <NGLLogger/INGLLogger.h> #include <NGLLogger/INGLLogger.h>
#include <QCryptographicHash>
#include <grantlee/context.h> #include <grantlee/context.h>
#ifdef RTI_HEADER_AVAILABLE #ifdef RTI_HEADER_AVAILABLE
@@ -13,341 +14,317 @@
using namespace CodeGen; using namespace CodeGen;
CppTopicGeneratorGrantlee::CppTopicGeneratorGrantlee() CppTopicGeneratorGrantlee::CppTopicGeneratorGrantlee() : GeneratorGrantleeBase("CodeGen.CppTopicGeneratorGrantlee") {}
: GeneratorGrantleeBase("CodeGen.CppTopicGeneratorGrantlee")
{}
bool CppTopicGeneratorGrantlee::init(const XmlReader *reader, StructBuilder *structBuilder) bool CppTopicGeneratorGrantlee::init(const XmlReader* reader, StructBuilder* structBuilder)
{ {
m_reader = reader; m_reader = reader;
if (!GeneratorGrantleeBase::initInternal(reader, structBuilder)) if (!GeneratorGrantleeBase::initInternal(reader, structBuilder))
return false; return false;
addCustomFunctions(reader->getCustomFunctions()); addCustomFunctions(reader->getCustomFunctions());
return initDataTopics() && initFunctionTopics() && initIdlStructs(); return initDataTopics() && initFunctionTopics() && initIdlStructs();
} }
bool CppTopicGeneratorGrantlee::initDataTopics() bool CppTopicGeneratorGrantlee::initDataTopics()
{ {
DataTopicsWrapper *dataTopicsWrapper = new DataTopicsWrapper(QString(), this); DataTopicsWrapper* dataTopicsWrapper = new DataTopicsWrapper(QString(), this);
const auto dataTopics = m_reader->getIdlStructInformation(); const auto dataTopics = m_reader->getIdlStructInformation();
QVector<IdlData> keyColumns; QVector<IdlData> keyColumns;
QVector<IdlData> trColumns; QVector<IdlData> trColumns;
for (const CodeGen::TopicTypeInformation &tti : dataTopics) for (const CodeGen::TopicTypeInformation& tti : dataTopics)
{
if (!tti.isDataObject)
continue;
keyColumns.clear();
trColumns.clear();
const CompleteTopicTypeInformation ctti = m_structBuilder->topicTypeInformationByStructType(tti.name);
if (!ctti.isValid())
{ {
ERROR_LOG(m_logger) << "could not find informations for struct " << tti.name; if (!tti.isDataObject)
continue; continue;
keyColumns.clear();
trColumns.clear();
const CompleteTopicTypeInformation ctti = m_structBuilder->topicTypeInformationByStructType(tti.name);
if (!ctti.isValid())
{
ERROR_LOG(m_logger) << "could not find informations for struct " << tti.name;
continue;
}
DataTopicWrapper* dtw = dataTopicsWrapper->addDataTopic(ctti);
getSpecialColumns(ctti, keyColumns, trColumns);
if (keyColumns.size() == 1)
dtw->setKeyColumnData(keyColumns.first());
dtw->setTrColumns(trColumns);
if (ctti.recordTopic)
{
const CompleteTableInformation cti(m_structBuilder->getRecordingTopicTable(ctti.name));
if (!cti.isEmpty())
dtw->setRecordTableInformation(cti);
}
else
{
if (ctti.isDataObject)
m_structBuilder->buildJSonStructureInformationFromIdlData(ctti);
}
} }
DataTopicWrapper *dtw = dataTopicsWrapper->addDataTopic(ctti); m_ctx->insert(QStringLiteral("dataTopics"), dataTopicsWrapper);
getSpecialColumns(ctti, keyColumns, trColumns);
if (keyColumns.size() == 1) QSet<QString> exportedSubTopics;
dtw->setKeyColumnData(keyColumns.first()); DataTopicsWrapper* subTopicsWrapper = new DataTopicsWrapper(QString(), this);
dtw->setTrColumns(trColumns); const QVector<QSharedPointer<DataTypeInfo>> serializeTopics = m_structBuilder->getSerializeFromToJsonTopics();
if (ctti.recordTopic) for (const QSharedPointer<DataTypeInfo>& dti : serializeTopics)
{ {
const CompleteTableInformation cti(m_structBuilder->getRecordingTopicTable(ctti.name)); if (exportedSubTopics.contains(dti->idlType()))
if (!cti.isEmpty()) continue;
dtw->setRecordTableInformation(cti); if (dti->isStructure())
{
const CompleteTopicTypeInformation ctti = m_structBuilder->topicTypeInformationByStructType(dti->idlType());
if (!ctti.isValid())
{
ERROR_LOG(m_logger) << "could not find informations for struct " << dti->idlType();
continue;
}
const CompleteTableInformation cti(m_structBuilder->getRecordingTopicTable(ctti.name));
if (cti.isEmpty())
{
ERROR_LOG(m_logger) << "could not find informations for struct " << dti->idlType();
continue;
}
DEBUG_LOG(m_logger) << "Adding substruct topic " << ctti.name;
DataTopicWrapper* dtw = subTopicsWrapper->addDataTopic(ctti);
dtw->setRecordTableInformation(cti);
exportedSubTopics += dti->idlType();
}
} }
else m_ctx->insert(QStringLiteral("serializeTopics"), subTopicsWrapper);
QVector<MemberInformationListWrapper*> jsonTopics;
const QMap<QString, QVector<MemberInformation>> jsonExport = m_structBuilder->jsonStructureInformation();
for (auto it = jsonExport.begin(); it != jsonExport.end(); ++it)
{ {
if (ctti.isDataObject) MemberInformationListWrapper* mil = new MemberInformationListWrapper(it.key(), it.value(), this);
m_structBuilder->buildJSonStructureInformationFromIdlData(ctti); jsonTopics += mil;
} }
} m_ctx->insert(QStringLiteral("jsonTopics"), QVariant::fromValue(jsonTopics));
m_ctx->insert(QStringLiteral("dataTopics"), dataTopicsWrapper);
QSet<QString> exportedSubTopics;
DataTopicsWrapper *subTopicsWrapper = new DataTopicsWrapper(QString(), this);
const QVector<QSharedPointer<DataTypeInfo>> serializeTopics = m_structBuilder->getSerializeFromToJsonTopics();
for (const QSharedPointer<DataTypeInfo> &dti : serializeTopics)
{
if (exportedSubTopics.contains(dti->idlType()))
continue;
if (dti->isStructure())
{
const CompleteTopicTypeInformation ctti = m_structBuilder->topicTypeInformationByStructType(dti->idlType());
if (!ctti.isValid())
{
ERROR_LOG(m_logger) << "could not find informations for struct " << dti->idlType();
continue;
}
const CompleteTableInformation cti(m_structBuilder->getRecordingTopicTable(ctti.name));
if (cti.isEmpty())
{
ERROR_LOG(m_logger) << "could not find informations for struct " << dti->idlType();
continue;
}
DEBUG_LOG(m_logger) << "Adding substruct topic " << ctti.name;
DataTopicWrapper *dtw = subTopicsWrapper->addDataTopic(ctti);
dtw->setRecordTableInformation(cti);
exportedSubTopics += dti->idlType();
}
}
m_ctx->insert(QStringLiteral("serializeTopics"), subTopicsWrapper);
QVector<MemberInformationListWrapper *> jsonTopics;
const QMap<QString, QVector<MemberInformation>> jsonExport = m_structBuilder->jsonStructureInformation();
for (auto it = jsonExport.begin(); it != jsonExport.end(); ++it)
{
MemberInformationListWrapper *mil = new MemberInformationListWrapper(it.key(), it.value(), this);
jsonTopics += mil;
}
m_ctx->insert(QStringLiteral("jsonTopics"), QVariant::fromValue(jsonTopics));
return true;
}
bool CppTopicGeneratorGrantlee::getSpecialColumns(const CompleteTopicTypeInformation &tti,
QVector<IdlData> &keyColumns,
QVector<IdlData> &trColumns) const
{
DEBUG_LOG(m_logger) << "Get special columns for " << tti.name << " - base is " << tti.baseValueType;
if (!tti.isValid())
{
ERROR_LOG(m_logger) << "tti is not valid ...";
return false;
}
for (const IdlData &ci : tti.members)
{
if (ci.isKey)
keyColumns += ci;
if (ci.isTranslatable)
trColumns += ci;
}
if (tti.baseValueType.isEmpty())
return true; return true;
return getSpecialColumns(topicTypeInformationByDerivedTopic(tti), keyColumns, trColumns);
} }
bool CppTopicGeneratorGrantlee::getSpecialColumns(const CompleteTopicTypeInformation& tti, QVector<IdlData>& keyColumns,
QVector<IdlData>& trColumns) const
{
DEBUG_LOG(m_logger) << "Get special columns for " << tti.name << " - base is " << tti.baseValueType;
if (!tti.isValid())
{
ERROR_LOG(m_logger) << "tti is not valid ...";
return false;
}
for (const IdlData& ci : tti.members)
{
if (ci.isKey)
keyColumns += ci;
if (ci.isTranslatable)
trColumns += ci;
}
if (tti.baseValueType.isEmpty())
return true;
return getSpecialColumns(topicTypeInformationByDerivedTopic(tti), keyColumns, trColumns);
}
bool CppTopicGeneratorGrantlee::initFunctionTopics() bool CppTopicGeneratorGrantlee::initFunctionTopics()
{ {
const QVector<FunctionTopic> functionTopics = m_reader->getFunctionTopics(); const QVector<FunctionTopic> functionTopics = m_reader->getFunctionTopics();
FunctionTopicsWrapper *functionTopicsWrapper(new FunctionTopicsWrapper(QStringLiteral("functionTopics"), this)); FunctionTopicsWrapper* functionTopicsWrapper(new FunctionTopicsWrapper(QStringLiteral("functionTopics"), this));
for (const FunctionTopic &ft : functionTopics) for (const FunctionTopic& ft : functionTopics)
{
if (!handleStruct(ft, functionTopicsWrapper))
return false;
}
m_ctx->insert(QStringLiteral("functionTopics"), functionTopicsWrapper);
return true;
}
bool CppTopicGeneratorGrantlee::handleStruct(const FunctionTopic &ft,
FunctionTopicsWrapper *functionTopicsWrapper)
{
DEBUG_LOG(m_logger) << "handling FunctionTopic: " << ft.name;
const CompleteTopicTypeInformation siRequest = m_structBuilder->topicTypeInformationByStructType(ft.requestTopicType);
if (!siRequest.isValid())
{
WARNING_LOG(m_logger) << "Could not get topic informations about request topic "
<< ft.requestTopicName;
return false;
}
const CompleteTopicTypeInformation siReply = m_structBuilder->topicTypeInformationByStructType(ft.replyTopicType);
if (!siReply.isValid())
{
WARNING_LOG(m_logger) << "Could not get topic informations about reply topic "
<< ft.replyTopicType;
return false;
}
FunctionTopicWrapper *ftw = functionTopicsWrapper->addFunctionTopic(ft, siRequest, siReply);
const QByteArray hash = QCryptographicHash::hash(ft.requestTopicName.toUtf8(), QCryptographicHash::Sha3_512).toHex().left(16);
ftw->setReplyHandlerHash(QStringLiteral("0x") + QString::fromLatin1(hash) + QStringLiteral("LL"));
if (!addRequesterRequestParams(ft.name, siRequest, ftw) ||
!addRequesterReplyParams(ft.name, siReply, ftw))
return false;
return true;
}
bool CppTopicGeneratorGrantlee::addRequesterRequestParams(const QString &request_name,
const CompleteTopicTypeInformation &request,
FunctionTopicWrapper *ftw)
{
if (request.hasBaseValue())
{
const CompleteTopicTypeInformation siBase = m_structBuilder->topicTypeInformationByStructType(request.baseValueType);
if (!siBase.isValid())
{ {
WARNING_LOG(m_logger) << "Could not get topic informations about base request topic " if (!handleStruct(ft, functionTopicsWrapper))
<< request.baseValueType; return false;
return false;
} }
if (!addRequesterRequestParams(request_name, siBase, ftw)) m_ctx->insert(QStringLiteral("functionTopics"), functionTopicsWrapper);
return false; return true;
}
ftw->addRequestParams(request.members);
return true;
} }
bool CppTopicGeneratorGrantlee::addRequesterReplyParams(const QString &request_name, bool CppTopicGeneratorGrantlee::handleStruct(const FunctionTopic& ft, FunctionTopicsWrapper* functionTopicsWrapper)
const CompleteTopicTypeInformation &reply,
FunctionTopicWrapper *ftw)
{ {
if (reply.hasBaseValue()) DEBUG_LOG(m_logger) << "handling FunctionTopic: " << ft.name;
{
const CompleteTopicTypeInformation siBase = m_structBuilder->topicTypeInformationByStructType(reply.baseValueType); const CompleteTopicTypeInformation siRequest =
if (!siBase.isValid()) m_structBuilder->topicTypeInformationByStructType(ft.requestTopicType);
if (!siRequest.isValid())
{ {
WARNING_LOG(m_logger) << "Could not get topic informations about base reply topic " WARNING_LOG(m_logger) << "Could not get topic informations about request topic " << ft.requestTopicName;
<< reply.baseValueType; return false;
return false;
} }
if (!addRequesterReplyParams(request_name, siBase, ftw)) const CompleteTopicTypeInformation siReply = m_structBuilder->topicTypeInformationByStructType(ft.replyTopicType);
return false; if (!siReply.isValid())
} {
ftw->addReplyParams(reply.members); WARNING_LOG(m_logger) << "Could not get topic informations about reply topic " << ft.replyTopicType;
return false;
}
return true; FunctionTopicWrapper* ftw = functionTopicsWrapper->addFunctionTopic(ft, siRequest, siReply);
const QByteArray hash =
QCryptographicHash::hash(ft.requestTopicName.toUtf8(), QCryptographicHash::Sha3_512).toHex().left(16);
ftw->setReplyHandlerHash(QStringLiteral("0x") + QString::fromLatin1(hash) + QStringLiteral("LL"));
if (!addRequesterRequestParams(ft.name, siRequest, ftw) || !addRequesterReplyParams(ft.name, siReply, ftw))
return false;
return true;
} }
bool CppTopicGeneratorGrantlee::addRequesterRequestParams(const QString& request_name,
const CompleteTopicTypeInformation& request,
bool CppTopicGeneratorGrantlee::handleIdlStruct(const CompleteTopicTypeInformation &csi, FunctionTopicWrapper* ftw)
QSet<QString> &idlStructNames,
QVector<IdlStructWrapper *> &idlStructs)
{ {
if (!csi.isValid()) if (request.hasBaseValue())
return true;
if (idlStructNames.contains(csi.name))
return true;
if (csi.hasBaseValue())
{
const CompleteTopicTypeInformation ctti = m_structBuilder->topicTypeInformationByStructType(csi.baseValueType, false);
if (ctti.isValid())
{ {
const CompleteTopicTypeInformation siBase =
m_structBuilder->topicTypeInformationByStructType(request.baseValueType);
if (!siBase.isValid())
{
WARNING_LOG(m_logger) << "Could not get topic informations about base request topic "
<< request.baseValueType;
return false;
}
if (!addRequesterRequestParams(request_name, siBase, ftw))
return false;
}
ftw->addRequestParams(request.members);
return true;
}
bool CppTopicGeneratorGrantlee::addRequesterReplyParams(const QString& request_name,
const CompleteTopicTypeInformation& reply,
FunctionTopicWrapper* ftw)
{
if (reply.hasBaseValue())
{
const CompleteTopicTypeInformation siBase =
m_structBuilder->topicTypeInformationByStructType(reply.baseValueType);
if (!siBase.isValid())
{
WARNING_LOG(m_logger) << "Could not get topic informations about base reply topic " << reply.baseValueType;
return false;
}
if (!addRequesterReplyParams(request_name, siBase, ftw))
return false;
}
ftw->addReplyParams(reply.members);
return true;
}
bool CppTopicGeneratorGrantlee::handleIdlStruct(const CompleteTopicTypeInformation& csi, QSet<QString>& idlStructNames,
QVector<IdlStructWrapper*>& idlStructs)
{
if (!csi.isValid())
return true;
if (idlStructNames.contains(csi.name))
return true;
if (csi.hasBaseValue())
{
const CompleteTopicTypeInformation ctti =
m_structBuilder->topicTypeInformationByStructType(csi.baseValueType, false);
if (ctti.isValid())
{
#ifdef RTI_HEADER_AVAILABLE #ifdef RTI_HEADER_AVAILABLE
if (ctti.extensibility == dds::core::xtypes::ExtensibilityKind_def::FINAL) if (ctti.extensibility == dds::core::xtypes::ExtensibilityKind_def::FINAL)
{ {
ERROR_LOG(m_logger) << "Base struct (" << ctti.name ERROR_LOG(m_logger) << "Base struct (" << ctti.name
<< ") has final extensibility - this is not allowed"; << ") has final extensibility - this is not allowed";
return false; return false;
} }
#else #else
// RTI not available - skip extensibility check (assume EXTENSIBLE) // RTI not available - skip extensibility check (assume EXTENSIBLE)
Q_UNUSED(ctti.extensibility); Q_UNUSED(ctti.extensibility);
#endif #endif
if (!idlStructNames.contains(csi.baseValueType)) if (!idlStructNames.contains(csi.baseValueType))
{ {
if (!handleIdlStruct(ctti, idlStructNames, idlStructs)) if (!handleIdlStruct(ctti, idlStructNames, idlStructs))
return false; return false;
} }
}
else
{
const int idx = csi.baseValueType.indexOf(QLatin1String("::"));
if (idx < 0)
{
ERROR_LOG(m_logger) << "idlStruct '" << csi.baseValueType << "' not found in idl-file";
return false;
}
}
} }
else
for (const IdlData& idlData : csi.members)
{ {
const int idx = csi.baseValueType.indexOf(QLatin1String("::")); QString idlType;
if (idx < 0) DEBUG_LOG(m_logger) << "member: " << idlData.type << " - " << idlData.name << " "
{ << idlData.dataTypeInfo->isStructure() << " " << idlData.dataTypeInfo->isSequence();
ERROR_LOG(m_logger) << "idlStruct '" << csi.baseValueType if (idlData.dataTypeInfo->isStructure())
<< "' not found in idl-file"; idlType = idlData.dataTypeInfo->idlType();
return false; else if (idlData.dataTypeInfo->isSequence())
} {
if (idlData.dataTypeInfo->innerDataType()->isStructure())
idlType = idlData.dataTypeInfo->innerDataType()->idlType();
}
if (idlType.isEmpty())
continue;
if (!handleIdlStruct(m_structBuilder->topicTypeInformationByStructType(idlType, false), idlStructNames,
idlStructs))
return false;
} }
}
DEBUG_LOG(m_logger) << "Current structName: " << csi.name;
idlStructs += new IdlStructWrapper(csi, this);
for (const IdlData &idlData : csi.members) idlStructNames.insert(csi.name);
{
QString idlType;
DEBUG_LOG(m_logger) << "member: " << idlData.type << " - " << idlData.name
<< " " << idlData.dataTypeInfo->isStructure()
<< " " << idlData.dataTypeInfo->isSequence();
if (idlData.dataTypeInfo->isStructure())
idlType = idlData.dataTypeInfo->idlType();
else if (idlData.dataTypeInfo->isSequence())
{
if (idlData.dataTypeInfo->innerDataType()->isStructure())
idlType = idlData.dataTypeInfo->innerDataType()->idlType();
}
if (idlType.isEmpty())
continue;
if (!handleIdlStruct(m_structBuilder->topicTypeInformationByStructType(idlType,
false),
idlStructNames,
idlStructs))
return false;
}
return true;
DEBUG_LOG(m_logger) << "Current structName: " << csi.name;
idlStructs += new IdlStructWrapper(csi, this);
idlStructNames.insert(csi.name);
return true;
} }
bool CppTopicGeneratorGrantlee::initIdlStructs() bool CppTopicGeneratorGrantlee::initIdlStructs()
{ {
const QVector<CompleteTopicTypeInformation> csiData = m_structBuilder->topicTypeInformations(); const QVector<CompleteTopicTypeInformation> csiData = m_structBuilder->topicTypeInformations();
QSet<QString> idlStructNames; QSet<QString> idlStructNames;
QVector<IdlStructWrapper *> idlStructs; QVector<IdlStructWrapper*> idlStructs;
idlStructs.reserve(csiData.size()); idlStructs.reserve(csiData.size());
for (const CompleteTopicTypeInformation &csi : csiData) for (const CompleteTopicTypeInformation& csi : csiData)
{ {
if (!handleIdlStruct(csi, idlStructNames, idlStructs)) if (!handleIdlStruct(csi, idlStructNames, idlStructs))
return false; return false;
} }
m_ctx->insert(QStringLiteral("idl_structs"), QVariant::fromValue(idlStructs)); m_ctx->insert(QStringLiteral("idl_structs"), QVariant::fromValue(idlStructs));
const QVector<EnumInformation> enumerations = m_structBuilder->enumInformations(); const QVector<EnumInformation> enumerations = m_structBuilder->enumInformations();
QVector<IdlEnumWrapper *> idlEnumerations; QVector<IdlEnumWrapper*> idlEnumerations;
idlEnumerations.reserve(enumerations.size()); idlEnumerations.reserve(enumerations.size());
for (const EnumInformation &ei : enumerations) for (const EnumInformation& ei : enumerations)
idlEnumerations += new IdlEnumWrapper(ei, this); idlEnumerations += new IdlEnumWrapper(ei, this);
m_ctx->insert(QStringLiteral("idl_enums"), QVariant::fromValue(idlEnumerations)); m_ctx->insert(QStringLiteral("idl_enums"), QVariant::fromValue(idlEnumerations));
exportUsedServices(m_reader);
exportUsedServices(m_reader); return true;
return true;
} }
CompleteTopicTypeInformation
CompleteTopicTypeInformation CppTopicGeneratorGrantlee::topicTypeInformationByDerivedTopic(const CompleteTopicTypeInformation &tti) const CppTopicGeneratorGrantlee::topicTypeInformationByDerivedTopic(const CompleteTopicTypeInformation& tti) const
{ {
if (tti.baseValueType.isEmpty()) if (tti.baseValueType.isEmpty())
return CompleteTopicTypeInformation(); return CompleteTopicTypeInformation();
QString baseValueType = tti.baseValueType; QString baseValueType = tti.baseValueType;
if (tti.name.contains(QLatin1String("::")) && !tti.baseValueType.contains(QLatin1String("::")))
if (tti.name.contains(QLatin1String("::")) && {
!tti.baseValueType.contains(QLatin1String("::"))) const QStringList sl = tti.name.split(QStringLiteral("::"));
{ baseValueType = sl.at(0) + QLatin1String("::") + tti.baseValueType;
const QStringList sl = tti.name.split(QStringLiteral("::")); }
baseValueType = sl.at(0) + QLatin1String("::") + tti.baseValueType; DEBUG_LOG(m_logger) << "topicTypeInformationByStructName(" << baseValueType << ")";
} return m_structBuilder->topicTypeInformationByStructType(baseValueType);
DEBUG_LOG(m_logger) << "topicTypeInformationByStructName(" << baseValueType << ")";
return m_structBuilder->topicTypeInformationByStructType(baseValueType);
} }
+23 -29
View File
@@ -1,47 +1,41 @@
#pragma once #pragma once
#include <QObject>
#include "GeneratorGrantleeBase.h" #include "GeneratorGrantleeBase.h"
#include "StructBuilder.h"
#include "GrantleeWrappers.h" #include "GrantleeWrappers.h"
#include "StructBuilder.h"
#include <QObject>
namespace CodeGen namespace CodeGen
{ {
class CppTopicGeneratorGrantlee final : public GeneratorGrantleeBase class CppTopicGeneratorGrantlee final : public GeneratorGrantleeBase
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit CppTopicGeneratorGrantlee(); explicit CppTopicGeneratorGrantlee();
bool init(const XmlReader *reader, StructBuilder *structBuilder) override; bool init(const XmlReader* reader, StructBuilder* structBuilder) override;
private: private:
bool initDataTopics();
bool getSpecialColumns(const CompleteTopicTypeInformation& tti, QVector<IdlData>& keyColumns,
QVector<IdlData>& trColumns) const;
bool initDataTopics(); bool initFunctionTopics();
bool getSpecialColumns(const CompleteTopicTypeInformation &tti, bool handleStruct(const FunctionTopic& ft, FunctionTopicsWrapper* functionTopicsWrapper);
QVector<IdlData> &keyColumns, bool addRequesterRequestParams(const QString& request_name, const CompleteTopicTypeInformation& request,
QVector<IdlData> &trColumns) const; FunctionTopicWrapper* ftw);
bool addRequesterReplyParams(const QString& request_name, const CompleteTopicTypeInformation& reply,
FunctionTopicWrapper* ftw);
bool initFunctionTopics(); bool handleIdlStruct(const CompleteTopicTypeInformation& csi, QSet<QString>& idlStructNames,
bool handleStruct(const FunctionTopic &ft, QVector<IdlStructWrapper*>& idlStructs);
FunctionTopicsWrapper *functionTopicsWrapper); bool initIdlStructs();
bool addRequesterRequestParams(const QString &request_name,
const CompleteTopicTypeInformation &request,
FunctionTopicWrapper *ftw);
bool addRequesterReplyParams(const QString &request_name,
const CompleteTopicTypeInformation &reply,
FunctionTopicWrapper *ftw);
bool handleIdlStruct(const CompleteTopicTypeInformation &csi, CompleteTopicTypeInformation topicTypeInformationByDerivedTopic(const CompleteTopicTypeInformation& tti) const;
QSet<QString> &idlStructNames,
QVector<IdlStructWrapper *> &idlStructs);
bool initIdlStructs();
CompleteTopicTypeInformation topicTypeInformationByDerivedTopic(const CompleteTopicTypeInformation &tti) const; const XmlReader* m_reader = nullptr;
const XmlReader *m_reader = nullptr;
}; };
} } // namespace CodeGen
+35 -38
View File
@@ -1,57 +1,54 @@
#include "DaoGeneratorGrantlee.h" #include "DaoGeneratorGrantlee.h"
#include "StructBuilder.h" #include "StructBuilder.h"
#include <NGLLogger/INGLLogger.h> #include <NGLLogger/INGLLogger.h>
#include <grantlee/context.h> #include <grantlee/context.h>
using namespace CodeGen; using namespace CodeGen;
DaoGeneratorGrantlee::DaoGeneratorGrantlee() DaoGeneratorGrantlee::DaoGeneratorGrantlee() : GeneratorGrantleeBase("CodeGen.DaoGeneratorGrantlee") {}
: GeneratorGrantleeBase("CodeGen.DaoGeneratorGrantlee")
{}
bool DaoGeneratorGrantlee::init(const XmlReader *reader, bool DaoGeneratorGrantlee::init(const XmlReader* reader, StructBuilder* structBuilder)
StructBuilder *structBuilder)
{ {
if (!GeneratorGrantleeBase::initInternal(reader, structBuilder)) if (!GeneratorGrantleeBase::initInternal(reader, structBuilder))
return false; return false;
if (reader->isServiceExerciseIndependent())
m_ctx->insert(QStringLiteral("isExerciseIndependent"), QLatin1String("1"));
if (reader->isServiceExerciseIndependent()) bool bHasDbNotifications = false;
m_ctx->insert(QStringLiteral("isExerciseIndependent"), QLatin1String("1")); QVector<DbStructWrapper*> vlServiceStructs;
QVector<DbStructWrapper*> vlStaticDataStructs;
const QVector<CompleteStructInformation> csiData = structBuilder->structInformations();
vlServiceStructs.reserve(csiData.size());
vlStaticDataStructs.reserve(csiData.size());
for (const CompleteStructInformation& csi : csiData)
{
DbStructWrapper* dbStructWrapper(new DbStructWrapper(csi, this));
bool bHasDbNotifications = false; if (csi.hasStaticContent)
QVector<DbStructWrapper *> vlServiceStructs; vlStaticDataStructs += dbStructWrapper;
QVector<DbStructWrapper *> vlStaticDataStructs; else
const QVector<CompleteStructInformation> csiData = structBuilder->structInformations(); vlServiceStructs += dbStructWrapper;
vlServiceStructs.reserve(csiData.size()); if (!csi.dbNotifications.isEmpty())
vlStaticDataStructs.reserve(csiData.size()); bHasDbNotifications = true;
for (const CompleteStructInformation &csi : csiData) }
{
DbStructWrapper *dbStructWrapper(new DbStructWrapper(csi, this));
if (csi.hasStaticContent) if (structBuilder->needPoint3d())
vlStaticDataStructs += dbStructWrapper; m_ctx->insert(QStringLiteral("need_point3d"), QLatin1String("1"));
else if (structBuilder->needPgArrayInclude())
vlServiceStructs += dbStructWrapper; m_ctx->insert(QStringLiteral("need_pgarray"), QLatin1String("1"));
if (!csi.dbNotifications.isEmpty()) m_ctx->insert(QStringLiteral("cpp_structs"), QVariant::fromValue(vlServiceStructs));
bHasDbNotifications = true; m_ctx->insert(QStringLiteral("data_structs"), QVariant::fromValue(vlStaticDataStructs));
} if (bHasDbNotifications)
m_ctx->insert(QStringLiteral("has_db_notifications"), QLatin1String("1"));
if (structBuilder->needPoint3d()) m_ctx->insert(QStringLiteral("library_target"), QStringLiteral("COMMON"));
m_ctx->insert(QStringLiteral("need_point3d"), QLatin1String("1"));
if (structBuilder->needPgArrayInclude())
m_ctx->insert(QStringLiteral("need_pgarray"), QLatin1String("1"));
m_ctx->insert(QStringLiteral("cpp_structs"), QVariant::fromValue(vlServiceStructs));
m_ctx->insert(QStringLiteral("data_structs"), QVariant::fromValue(vlStaticDataStructs));
if (bHasDbNotifications)
m_ctx->insert(QStringLiteral("has_db_notifications"), QLatin1String("1"));
m_ctx->insert(QStringLiteral("library_target"), QStringLiteral("COMMON")); exportUsedServices(reader);
exportUsedServices(reader); return true;
return true;
} }
+8 -9
View File
@@ -1,11 +1,11 @@
#pragma once #pragma once
#include <QObject>
#include "GeneratorGrantleeBase.h" #include "GeneratorGrantleeBase.h"
#include "StructBuilder.h"
#include "GrantleeWrappers.h" #include "GrantleeWrappers.h"
#include "StructBuilder.h"
#include <QObject>
namespace CodeGen namespace CodeGen
{ {
@@ -13,13 +13,12 @@ struct CompleteStructInformation;
class StructBuilder; class StructBuilder;
class XmlReader; class XmlReader;
class DaoGeneratorGrantlee final : public GeneratorGrantleeBase class DaoGeneratorGrantlee final : public GeneratorGrantleeBase
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit DaoGeneratorGrantlee(); explicit DaoGeneratorGrantlee();
bool init(const XmlReader *reader, StructBuilder *structBuilder) override; bool init(const XmlReader* reader, StructBuilder* structBuilder) override;
}; };
} } // namespace CodeGen
+47 -47
View File
@@ -1,59 +1,59 @@
#include "DatabaseGeneratorGrantlee.h" #include "DatabaseGeneratorGrantlee.h"
#include "StructBuilder.h" #include "StructBuilder.h"
#include <NGLLogger/INGLLogger.h> #include <NGLLogger/INGLLogger.h>
#include <grantlee/context.h> #include <grantlee/context.h>
using namespace CodeGen; using namespace CodeGen;
DatabaseGeneratorGrantlee::DatabaseGeneratorGrantlee(bool targetIsServer) DatabaseGeneratorGrantlee::DatabaseGeneratorGrantlee(bool targetIsServer)
: GeneratorGrantleeBase("CodeGen.CppStructGeneratorGrantlee") : GeneratorGrantleeBase("CodeGen.CppStructGeneratorGrantlee"), m_targetIsServer(targetIsServer)
, m_targetIsServer(targetIsServer)
{}
bool DatabaseGeneratorGrantlee::init(const XmlReader *reader,
StructBuilder *structBuilder)
{ {
if (!GeneratorGrantleeBase::initInternal(reader, structBuilder)) }
return false;
bool DatabaseGeneratorGrantlee::init(const XmlReader* reader, StructBuilder* structBuilder)
{
if (reader->isServiceExerciseIndependent()) if (!GeneratorGrantleeBase::initInternal(reader, structBuilder))
m_ctx->insert(QStringLiteral("isExerciseIndependent"), QLatin1String("1")); return false;
bool bHasDbNotifications = false; if (reader->isServiceExerciseIndependent())
QVector<DbStructWrapper *> vlServiceStructs; m_ctx->insert(QStringLiteral("isExerciseIndependent"), QLatin1String("1"));
QVector<DbStructWrapper *> vlStaticDataStructs;
const QVector<CompleteStructInformation> csiData = structBuilder->structInformations(); bool bHasDbNotifications = false;
vlServiceStructs.reserve(csiData.size()); QVector<DbStructWrapper*> vlServiceStructs;
vlStaticDataStructs.reserve(csiData.size()); QVector<DbStructWrapper*> vlStaticDataStructs;
for (const CompleteStructInformation &csi : csiData) const QVector<CompleteStructInformation> csiData = structBuilder->structInformations();
{ vlServiceStructs.reserve(csiData.size());
DbStructWrapper *dbStructWrapper(new DbStructWrapper(csi, this)); vlStaticDataStructs.reserve(csiData.size());
for (const CompleteStructInformation& csi : csiData)
if (csi.hasStaticContent) {
vlStaticDataStructs += dbStructWrapper; DbStructWrapper* dbStructWrapper(new DbStructWrapper(csi, this));
else
vlServiceStructs += dbStructWrapper; if (csi.hasStaticContent)
if (!csi.dbNotifications.isEmpty()) vlStaticDataStructs += dbStructWrapper;
bHasDbNotifications = true; else
} vlServiceStructs += dbStructWrapper;
addCustomFunctions(reader->getCustomFunctions()); if (!csi.dbNotifications.isEmpty())
bHasDbNotifications = true;
if (structBuilder->needPoint3d()) }
m_ctx->insert(QStringLiteral("need_point3d"), QLatin1String("1")); addCustomFunctions(reader->getCustomFunctions());
if (structBuilder->needPgArrayInclude())
m_ctx->insert(QStringLiteral("need_pgarray"), QLatin1String("1")); if (structBuilder->needPoint3d())
m_ctx->insert(QStringLiteral("cpp_structs"), QVariant::fromValue(vlServiceStructs)); m_ctx->insert(QStringLiteral("need_point3d"), QLatin1String("1"));
m_ctx->insert(QStringLiteral("data_structs"), QVariant::fromValue(vlStaticDataStructs)); if (structBuilder->needPgArrayInclude())
if (bHasDbNotifications) m_ctx->insert(QStringLiteral("need_pgarray"), QLatin1String("1"));
m_ctx->insert(QStringLiteral("has_db_notifications"), QLatin1String("1")); m_ctx->insert(QStringLiteral("cpp_structs"), QVariant::fromValue(vlServiceStructs));
m_ctx->insert(QStringLiteral("data_structs"), QVariant::fromValue(vlStaticDataStructs));
m_ctx->insert(QStringLiteral("library_target"), m_targetIsServer ? QStringLiteral("SERVER") : QStringLiteral("COMMON")); if (bHasDbNotifications)
m_ctx->insert(QStringLiteral("has_db_notifications"), QLatin1String("1"));
exportUsedServices(reader);
m_ctx->insert(QStringLiteral("library_target"),
return true; m_targetIsServer ? QStringLiteral("SERVER") : QStringLiteral("COMMON"));
exportUsedServices(reader);
return true;
} }
+11 -11
View File
@@ -1,11 +1,11 @@
#pragma once #pragma once
#include <QObject>
#include "GeneratorGrantleeBase.h" #include "GeneratorGrantleeBase.h"
#include "StructBuilder.h"
#include "GrantleeWrappers.h" #include "GrantleeWrappers.h"
#include "StructBuilder.h"
#include <QObject>
namespace CodeGen namespace CodeGen
{ {
@@ -13,15 +13,15 @@ struct CompleteStructInformation;
class StructBuilder; class StructBuilder;
class XmlReader; class XmlReader;
class DatabaseGeneratorGrantlee final : public GeneratorGrantleeBase class DatabaseGeneratorGrantlee final : public GeneratorGrantleeBase
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit DatabaseGeneratorGrantlee(bool targetIsServer); explicit DatabaseGeneratorGrantlee(bool targetIsServer);
bool init(const XmlReader *reader, StructBuilder *structBuilder) override; bool init(const XmlReader* reader, StructBuilder* structBuilder) override;
private:
bool m_targetIsServer; private:
bool m_targetIsServer;
}; };
} } // namespace CodeGen
+146 -148
View File
@@ -1,9 +1,10 @@
#include "GeneratorGrantleeBase.h" #include "GeneratorGrantleeBase.h"
#include "XmlReader.h"
#include "GrantleeWrappers.h" #include "GrantleeWrappers.h"
#include "XmlReader.h"
#include <NGLLogger/NGLLoggerBootstrap.h> #include <NGLLogger/NGLLoggerBootstrap.h>
#include <QFile> #include <QFile>
#include <QRegularExpression> #include <QRegularExpression>
@@ -11,190 +12,187 @@
#include <grantlee/engine.h> #include <grantlee/engine.h>
using namespace CodeGen; using namespace CodeGen;
GeneratorGrantleeBase::GeneratorGrantleeBase(const char *loggerName) : m_engine(new Grantlee::Engine) GeneratorGrantleeBase::GeneratorGrantleeBase(const char *loggerName) : m_engine(new Grantlee::Engine)
, m_ctx(new Grantlee::Context) , m_ctx(new Grantlee::Context)
, m_structBuilder(nullptr) , m_structBuilder(nullptr)
.getNGLLogger(loggerName)), .getNGLLogger(loggerName)),
m_logger(NGL::NGLLoggerBootstrap::getLogger()) { m_logger(NGL::NGLLoggerBootstrap::getLogger())
{
} }
GeneratorGrantleeBase::~GeneratorGrantleeBase() GeneratorGrantleeBase::~GeneratorGrantleeBase()
{ {
delete m_engine; delete m_engine;
delete m_ctx; delete m_ctx;
} }
bool GeneratorGrantleeBase::initInternal(const XmlReader *reader, StructBuilder *structBuilder) bool GeneratorGrantleeBase::initInternal(const XmlReader* reader, StructBuilder* structBuilder)
{ {
m_structBuilder = structBuilder; m_structBuilder = structBuilder;
if (reader) if (reader)
{ {
m_ctx->insert(QStringLiteral("namespace"), reader->getServiceNamespace()); m_ctx->insert(QStringLiteral("namespace"), reader->getServiceNamespace());
m_ctx->insert(QStringLiteral("namespace_abbr"), reader->getServiceAbbr().toLower()); m_ctx->insert(QStringLiteral("namespace_abbr"), reader->getServiceAbbr().toLower());
m_ctx->insert(QStringLiteral("namespace_abbr_upper"), reader->getServiceAbbr().toUpper()); m_ctx->insert(QStringLiteral("namespace_abbr_upper"), reader->getServiceAbbr().toUpper());
if (reader->getServiceNamespace() == QLatin1String("Core")) if (reader->getServiceNamespace() == QLatin1String("Core"))
m_ctx->insert(QStringLiteral("include_prefix"), QStringLiteral("DDS/%1").arg(reader->getServiceNamespace())); m_ctx->insert(QStringLiteral("include_prefix"),
else QStringLiteral("DDS/%1").arg(reader->getServiceNamespace()));
m_ctx->insert(QStringLiteral("include_prefix"), reader->getServiceNamespace()); else
m_ctx->insert(QStringLiteral("custom_record_replay"), reader->hasCustomRecordReplayPlugin()); m_ctx->insert(QStringLiteral("include_prefix"), reader->getServiceNamespace());
} m_ctx->insert(QStringLiteral("custom_record_replay"), reader->hasCustomRecordReplayPlugin());
return true; }
return true;
} }
bool GeneratorGrantleeBase::setTemplate(const QString &templateName, const QString &tmpl) bool GeneratorGrantleeBase::setTemplate(const QString& templateName, const QString& tmpl)
{ {
m_template = m_engine->newTemplate(tmpl, QStringLiteral("myTemplate")); m_template = m_engine->newTemplate(tmpl, QStringLiteral("myTemplate"));
if (m_template->error()) if (m_template->error())
{ {
WARNING_LOG(m_logger) << "Error parsing template '" << templateName WARNING_LOG(m_logger) << "Error parsing template '" << templateName << "': " << m_template->errorString();
<< "': " << m_template->errorString(); return false;
return false; }
} return true;
return true;
} }
QString GeneratorGrantleeBase::render() const QString GeneratorGrantleeBase::render() const
{ {
QString out = m_template->render(m_ctx); QString out = m_template->render(m_ctx);
const QRegularExpression rx(QLatin1String(";\\n([ ]+\\n)*")); const QRegularExpression rx(QLatin1String(";\\n([ ]+\\n)*"));
out = out.replace(rx, QStringLiteral(";\n")); out = out.replace(rx, QStringLiteral(";\n"));
return out; return out;
} }
QString GeneratorGrantleeBase::errorString() const QString GeneratorGrantleeBase::errorString() const
{ {
return m_template->errorString(); return m_template->errorString();
} }
bool GeneratorGrantleeBase::generateData(const QString& templateName, const QString& outDirectory)
bool GeneratorGrantleeBase::generateData(const QString &templateName,
const QString &outDirectory)
{ {
QString content; QString content;
if (!readFile(templateName, content)) if (!readFile(templateName, content))
return false; return false;
if (!setTemplate(templateName, content)) if (!setTemplate(templateName, content))
return false; return false;
content = render(); content = render();
QString outFilename; QString outFilename;
if (!getFilenameFromData(content, outFilename)) if (!getFilenameFromData(content, outFilename))
return false; return false;
QFile f(outDirectory + QLatin1Char('/') + outFilename);
QFile f(outDirectory + QLatin1Char('/') + outFilename); if (!f.open(QIODevice::WriteOnly))
if (!f.open(QIODevice::WriteOnly))
{
ERROR_LOG(m_logger) << "Error opening file '" << f.fileName() << "' for writing: "
<< f.errorString() << "(" << f.error() << ")";
return false;
}
const QByteArray outData = content.toUtf8();
f.write(outData);
f.close();
DEBUG_LOG(m_logger) << "Written data to " << f.fileName();
return true;
}
bool GeneratorGrantleeBase::readFile(const QString &filename, QString &data) const
{
QFile f(filename);
if (!f.open(QIODevice::ReadOnly))
{
ERROR_LOG(m_logger) << "Error opening file " << filename
<< " - error: " << f.errorString();
return false;
}
data = QString::fromUtf8(f.readAll());
f.close();
return true;
}
bool GeneratorGrantleeBase::getFilenameFromData(const QString &dataToParse, QString &filename) const
{
const QString filenameMarker(QStringLiteral("// filename:"));
int idx = dataToParse.indexOf(filenameMarker);
if (idx < 0)
{
ERROR_LOG(m_logger) << "Could not find marker '" << filenameMarker
<< "' in data!";
return false;
}
idx += filenameMarker.length() + 1;
int endIdx = dataToParse.indexOf(QLatin1Char('\n'), idx);
if (endIdx < 0)
{
ERROR_LOG(m_logger) << "Could not find end marker '\\n' in data!";
return false;
}
filename = dataToParse.mid(idx, endIdx - idx).trimmed();
return true;
}
void GeneratorGrantleeBase::addCustomFunctions(const QVector<CustomServiceFunctionInformation> &customFunctions)
{
QVariantList vlCustomDbFunctions;
QVariantList vlCustomDtcFunctions;
vlCustomDbFunctions.reserve(customFunctions.size());
vlCustomDtcFunctions.reserve(customFunctions.size());
for (const CustomServiceFunctionInformation &csfi : customFunctions)
{
const QString signature(csfi.returnValue + QLatin1Char(' ') +
csfi.methodName + QLatin1Char('(') + csfi.signature + QLatin1Char(')') +
(csfi.isConst ? QStringLiteral(" const") : QString()));
CustomFunctionWrapper *customFunctionWrapper(new CustomFunctionWrapper(signature, this));
switch (csfi.type)
{ {
case CustomServiceFunctionInformation::Type::Db: ERROR_LOG(m_logger) << "Error opening file '" << f.fileName() << "' for writing: " << f.errorString() << "("
vlCustomDbFunctions += QVariant::fromValue(customFunctionWrapper); << f.error() << ")";
break; return false;
case CustomServiceFunctionInformation::Type::Dtc:
vlCustomDtcFunctions += QVariant::fromValue(customFunctionWrapper);
break;
case CustomServiceFunctionInformation::Type::DbNotify:
WARNING_LOG(m_logger) << "Internal error - Trying to handle DbNotify in addCustomFunctions(): "
<< csfi.methodName;
delete customFunctionWrapper;
break;
} }
DEBUG_LOG(m_logger) << "Added custom db function " << csfi.methodName; const QByteArray outData = content.toUtf8();
} f.write(outData);
m_ctx->insert(QStringLiteral("custom_dtc_procs"), vlCustomDtcFunctions); f.close();
m_ctx->insert(QStringLiteral("custom_db_procs"), vlCustomDbFunctions);
DEBUG_LOG(m_logger) << "Written data to " << f.fileName();
return true;
} }
void GeneratorGrantleeBase::exportUsedServices(const XmlReader *reader) bool GeneratorGrantleeBase::readFile(const QString& filename, QString& data) const
{ {
IdlServicesWrapper *idlServicesWrapper(new IdlServicesWrapper(QString(), this)); QFile f(filename);
const QMap<QString, bool> usedServices = reader->usedServices(); if (!f.open(QIODevice::ReadOnly))
for (auto it = usedServices.begin(); it != usedServices.end(); ++it) {
{ ERROR_LOG(m_logger) << "Error opening file " << filename << " - error: " << f.errorString();
return false;
}
data = QString::fromUtf8(f.readAll());
f.close();
return true;
}
if (!it.value()) bool GeneratorGrantleeBase::getFilenameFromData(const QString& dataToParse, QString& filename) const
continue; {
const QString &svc = it.key();
const QString fullPath = reader->idlFileForService(svc); const QString filenameMarker(QStringLiteral("// filename:"));
const int idx = fullPath.lastIndexOf(QLatin1Char('.')); int idx = dataToParse.indexOf(filenameMarker);
if (idx < 0) if (idx < 0)
{ {
ERROR_LOG(m_logger) << "Could not parse file path: " << fullPath; ERROR_LOG(m_logger) << "Could not find marker '" << filenameMarker << "' in data!";
continue; return false;
} }
const QString idlFile = fullPath.left(idx); idx += filenameMarker.length() + 1;
if (idlFile.isEmpty()) int endIdx = dataToParse.indexOf(QLatin1Char('\n'), idx);
if (endIdx < 0)
{ {
WARNING_LOG(m_logger) << "Could not find idl file for service " << svc; ERROR_LOG(m_logger) << "Could not find end marker '\\n' in data!";
continue; return false;
} }
idlServicesWrapper->addService(svc, idlFile); filename = dataToParse.mid(idx, endIdx - idx).trimmed();
DEBUG_LOG(m_logger) << "Added service " << svc;
} return true;
m_ctx->insert(QStringLiteral("ext_services"), idlServicesWrapper); }
void GeneratorGrantleeBase::addCustomFunctions(const QVector<CustomServiceFunctionInformation>& customFunctions)
{
QVariantList vlCustomDbFunctions;
QVariantList vlCustomDtcFunctions;
vlCustomDbFunctions.reserve(customFunctions.size());
vlCustomDtcFunctions.reserve(customFunctions.size());
for (const CustomServiceFunctionInformation& csfi : customFunctions)
{
const QString signature(csfi.returnValue + QLatin1Char(' ') + csfi.methodName + QLatin1Char('(') +
csfi.signature + QLatin1Char(')') +
(csfi.isConst ? QStringLiteral(" const") : QString()));
CustomFunctionWrapper* customFunctionWrapper(new CustomFunctionWrapper(signature, this));
switch (csfi.type)
{
case CustomServiceFunctionInformation::Type::Db:
vlCustomDbFunctions += QVariant::fromValue(customFunctionWrapper);
break;
case CustomServiceFunctionInformation::Type::Dtc:
vlCustomDtcFunctions += QVariant::fromValue(customFunctionWrapper);
break;
case CustomServiceFunctionInformation::Type::DbNotify:
WARNING_LOG(m_logger) << "Internal error - Trying to handle DbNotify in addCustomFunctions(): "
<< csfi.methodName;
delete customFunctionWrapper;
break;
}
DEBUG_LOG(m_logger) << "Added custom db function " << csfi.methodName;
}
m_ctx->insert(QStringLiteral("custom_dtc_procs"), vlCustomDtcFunctions);
m_ctx->insert(QStringLiteral("custom_db_procs"), vlCustomDbFunctions);
}
void GeneratorGrantleeBase::exportUsedServices(const XmlReader* reader)
{
IdlServicesWrapper* idlServicesWrapper(new IdlServicesWrapper(QString(), this));
const QMap<QString, bool> usedServices = reader->usedServices();
for (auto it = usedServices.begin(); it != usedServices.end(); ++it)
{
if (!it.value())
continue;
const QString& svc = it.key();
const QString fullPath = reader->idlFileForService(svc);
const int idx = fullPath.lastIndexOf(QLatin1Char('.'));
if (idx < 0)
{
ERROR_LOG(m_logger) << "Could not parse file path: " << fullPath;
continue;
}
const QString idlFile = fullPath.left(idx);
if (idlFile.isEmpty())
{
WARNING_LOG(m_logger) << "Could not find idl file for service " << svc;
continue;
}
idlServicesWrapper->addService(svc, idlFile);
DEBUG_LOG(m_logger) << "Added service " << svc;
}
m_ctx->insert(QStringLiteral("ext_services"), idlServicesWrapper);
} }
+27 -25
View File
@@ -3,6 +3,7 @@
#pragma once #pragma once
#include "XmlReader.h" #include "XmlReader.h"
#include <QObject> #include <QObject>
#include <QSharedPointer> #include <QSharedPointer>
@@ -17,37 +18,38 @@ class Context;
class Engine; class Engine;
class TemplateImpl; class TemplateImpl;
using Template = QSharedPointer<TemplateImpl>; using Template = QSharedPointer<TemplateImpl>;
} } // namespace Grantlee
namespace CodeGen namespace CodeGen
{ {
class StructBuilder; class StructBuilder;
class GeneratorGrantleeBase : public QObject class GeneratorGrantleeBase : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
virtual ~GeneratorGrantleeBase(); virtual ~GeneratorGrantleeBase();
virtual bool init(const XmlReader *reader, StructBuilder *structBuilder) = 0; virtual bool init(const XmlReader* reader, StructBuilder* structBuilder) = 0;
bool setTemplate(const QString &templateName, const QString &tmpl); bool setTemplate(const QString& templateName, const QString& tmpl);
QString render() const; QString render() const;
QString errorString() const; QString errorString() const;
bool generateData(const QString &templateName, bool generateData(const QString& templateName, const QString& outDirectory);
const QString &outDirectory);
protected: protected:
NGL::INGLLogger &m_logger; NGL::INGLLogger& m_logger;
explicit GeneratorGrantleeBase(const char *loggerName); explicit GeneratorGrantleeBase(const char* loggerName);
bool initInternal(const XmlReader *reader, StructBuilder *structBuilder); bool initInternal(const XmlReader* reader, StructBuilder* structBuilder);
bool readFile(const QString &filename, QString &data) const; bool readFile(const QString& filename, QString& data) const;
bool getFilenameFromData(const QString &dataToParse, QString &filename) const; bool getFilenameFromData(const QString& dataToParse, QString& filename) const;
void addCustomFunctions(const QVector<CustomServiceFunctionInformation> &customFunctions); void addCustomFunctions(const QVector<CustomServiceFunctionInformation>& customFunctions);
void exportUsedServices(const XmlReader *reader); void exportUsedServices(const XmlReader* reader);
protected:
NGL::INGLLogger &m_logger; protected:
Grantlee::Engine *m_engine; NGL::INGLLogger& m_logger;
Grantlee::Context *m_ctx; Grantlee::Engine* m_engine;
Grantlee::Template m_template; Grantlee::Context* m_ctx;
StructBuilder *m_structBuilder; Grantlee::Template m_template;
StructBuilder* m_structBuilder;
}; };
} } // namespace CodeGen
+133 -180
View File
@@ -1,7 +1,7 @@
#include "GrantleeWrappers.h" #include "GrantleeWrappers.h"
#include <NGLLogger/NGLLoggerBootstrap.h> #include <NGLLogger/NGLLoggerBootstrap.h>
#include <utility> #include <utility>
@@ -10,241 +10,194 @@ using namespace CodeGen;
#ifdef RTI_HEADER_AVAILABLE #ifdef RTI_HEADER_AVAILABLE
QString IdlStructWrapper::extensibility2String(dds::core::xtypes::ExtensibilityKind extensiblity) QString IdlStructWrapper::extensibility2String(dds::core::xtypes::ExtensibilityKind extensiblity)
{ {
switch (extensiblity.underlying()) switch (extensiblity.underlying())
{ {
case dds::core::xtypes::ExtensibilityKind_def::FINAL: case dds::core::xtypes::ExtensibilityKind_def::FINAL:
return QStringLiteral("FINAL_EXTENSIBILITY"); return QStringLiteral("FINAL_EXTENSIBILITY");
case dds::core::xtypes::ExtensibilityKind_def::MUTABLE: case dds::core::xtypes::ExtensibilityKind_def::MUTABLE:
return QStringLiteral("MUTABLE_EXTENSIBILITY"); return QStringLiteral("MUTABLE_EXTENSIBILITY");
case dds::core::xtypes::ExtensibilityKind_def::EXTENSIBLE: case dds::core::xtypes::ExtensibilityKind_def::EXTENSIBLE:
return QStringLiteral("EXTENSIBLE_EXTENSIBILITY"); return QStringLiteral("EXTENSIBLE_EXTENSIBILITY");
} }
Q_ASSERT_X(false, "IdlStructWrapper::extensibility2String", "Unknown extensiblity kind"); Q_ASSERT_X(false, "IdlStructWrapper::extensibility2String", "Unknown extensiblity kind");
return QString(); return QString();
} }
#else #else
QString IdlStructWrapper::extensibility2String(int /*extensiblity*/) QString IdlStructWrapper::extensibility2String(int /*extensiblity*/)
{ {
// RTI not available - return placeholder // RTI not available - return placeholder
return QStringLiteral("EXTENSIBLE_EXTENSIBILITY"); return QStringLiteral("EXTENSIBLE_EXTENSIBILITY");
} }
#endif #endif
QString DataTopicWrapper::typeFq() const QString DataTopicWrapper::typeFq() const
{ {
const QString &t = type(); const QString& t = type();
const QString &s = serviceName(); const QString& s = serviceName();
if (s.isEmpty()) if (s.isEmpty())
return t; return t;
if (t.startsWith(s)) if (t.startsWith(s))
return t; return t;
return s + QStringLiteral("::") + t; return s + QStringLiteral("::") + t;
} }
QString MemberInformationWrapper::ddsToQVariant() const QString MemberInformationWrapper::ddsToQVariant() const
{ {
return QStringLiteral("toQVariant(data.") + cppMemberName() + QStringLiteral("())"); return QStringLiteral("toQVariant(data.") + cppMemberName() + QStringLiteral("())");
} }
QString MemberInformationWrapper::qVariantToDds() const QString MemberInformationWrapper::qVariantToDds() const
{ {
const QString ddsType = isOptional() ? const QString ddsType =
(QStringLiteral("dds::core::optional<") + cppDdsType() + QLatin1Char('>')) : isOptional() ? (QStringLiteral("dds::core::optional<") + cppDdsType() + QLatin1Char('>')) : (cppDdsType());
(cppDdsType());
return QStringLiteral("data.") + cppMemberName() + return QStringLiteral("data.") + cppMemberName() + QStringLiteral("() = fromQVariant<") + ddsType +
QStringLiteral("() = fromQVariant<") + ddsType + QStringLiteral(">(q.value(i++))"); QStringLiteral(">(q.value(i++))");
} }
QString MemberInformationWrapper::ddsToJsonElement() const QString MemberInformationWrapper::ddsToJsonElement() const
{ {
if (cppMemberName().isEmpty())
return QStringLiteral("obj[QStringLiteral(\"") + cppType() + QStringLiteral("\")] = element;");
const QString memberAccess = isCppStruct() ? cppMemberName() : cppMemberName() + QStringLiteral("()");
if (!isOptional())
return QStringLiteral("obj[QStringLiteral(\"") + cppMemberName() + QStringLiteral("\")] = ") + cppToJsonPre() +
QStringLiteral("element.") + memberAccess + cppToJsonPost();
const QString optionalAccess =
isCppStruct() ? cppMemberName() + QStringLiteral(".is_set()") : cppMemberName() + QStringLiteral("().is_set()");
const QString getValue = isCppStruct() ? cppMemberName() : cppMemberName() + QStringLiteral("()");
return QStringLiteral("if (element.") + optionalAccess + QStringLiteral(") ") +
QStringLiteral("obj[QStringLiteral(\"") + cppMemberName() + QStringLiteral("\")] = ") + cppToJsonPre() +
QStringLiteral("element.") + getValue + cppToJsonPost();
if (cppMemberName().isEmpty())
return QStringLiteral("obj[QStringLiteral(\"") + cppType() + QStringLiteral("\")] = element;");
const QString memberAccess = isCppStruct() ? cppMemberName() : cppMemberName() + QStringLiteral("()");
if (!isOptional())
return QStringLiteral("obj[QStringLiteral(\"") + cppMemberName() + QStringLiteral("\")] = ") +
cppToJsonPre() + QStringLiteral("element.") + memberAccess + cppToJsonPost();
const QString optionalAccess = isCppStruct() ? cppMemberName() + QStringLiteral(".is_set()") : cppMemberName() + QStringLiteral("().is_set()");
const QString getValue = isCppStruct() ? cppMemberName() : cppMemberName() + QStringLiteral("()");
return QStringLiteral("if (element.") + optionalAccess + QStringLiteral(") ") +
QStringLiteral("obj[QStringLiteral(\"") + cppMemberName() + QStringLiteral("\")] = ") +
cppToJsonPre() + QStringLiteral("element.") + getValue + cppToJsonPost();
} }
QString MemberInformationWrapper::jsonElementToDds() const QString MemberInformationWrapper::jsonElementToDds() const
{ {
if (cppMemberName().isEmpty())
return QStringLiteral("element = ") + cppFromQvPre2() + QStringLiteral("objElement.value(QStringLiteral(\"") +
cppType() + QStringLiteral("\"))") + cppFromJsonPost();
QString ret(QStringLiteral("const QJsonValue val(objElement.value(QStringLiteral(\"") + cppMemberName() +
QStringLiteral("\"))); "));
if (isOptional())
ret += QStringLiteral("if (!val.isNull()) ");
if (isCppStruct())
ret += QStringLiteral("element.") + cppMemberName() + QStringLiteral(" = ") + cppFromJsonPre2() +
QStringLiteral("val") + cppFromJsonPost();
else
ret += QStringLiteral("element.") + cppMemberName() + QStringLiteral("(") + cppFromJsonPre2() +
QStringLiteral("val") + cppFromJsonPost() + QStringLiteral(")");
return ret;
if (cppMemberName().isEmpty())
return QStringLiteral("element = ") +
cppFromQvPre2() + QStringLiteral("objElement.value(QStringLiteral(\"") + cppType() + QStringLiteral("\"))") + cppFromJsonPost();
QString ret(QStringLiteral("const QJsonValue val(objElement.value(QStringLiteral(\"") + cppMemberName() + QStringLiteral("\"))); "));
if (isOptional())
ret += QStringLiteral("if (!val.isNull()) ");
if (isCppStruct())
ret += QStringLiteral("element.") + cppMemberName() + QStringLiteral(" = ") +
cppFromJsonPre2() + QStringLiteral("val") + cppFromJsonPost();
else
ret += QStringLiteral("element.") + cppMemberName() + QStringLiteral("(") +
cppFromJsonPre2() + QStringLiteral("val") + cppFromJsonPost() + QStringLiteral(")");
return ret;
} }
QString MemberInformationWrapper::dbToJsonElement() const QString MemberInformationWrapper::dbToJsonElement() const
{ {
if (cppMemberName().isEmpty())
return QStringLiteral("obj[QStringLiteral(\"") + cppType() + QStringLiteral("\")] = element;");
if (isOptional() || cppType() == QStringLiteral("QDateTime"))
{
QString ret = QStringLiteral("if (") +
((cppType() == QStringLiteral("QDateTime")) ? QString() : QStringLiteral("!")) +
QStringLiteral("element.") + cppMemberName() +
((cppType() == QStringLiteral("QDateTime")) ? QStringLiteral(".isValid()) ")
: QStringLiteral(".isNull()) ")) +
QStringLiteral("obj[QStringLiteral(\"") + cppMemberName() + QStringLiteral("\")] = ");
if (isOptional())
return ret += cppFromQvPre2() + QStringLiteral("element.") + cppMemberName() + cppFromQvPost();
}
return QStringLiteral("obj[QStringLiteral(\"") + cppMemberName() + QStringLiteral("\")] = ") + cppToJsonPre() +
QStringLiteral("element.") + cppMemberName() + cppToJsonPost();
if (cppMemberName().isEmpty())
return QStringLiteral("obj[QStringLiteral(\"") + cppType() + QStringLiteral("\")] = element;");
if (isOptional() || cppType() == QStringLiteral("QDateTime"))
{
QString ret = QStringLiteral("if (") + ((cppType() == QStringLiteral("QDateTime")) ? QString() : QStringLiteral("!")) +
QStringLiteral("element.") + cppMemberName() +
((cppType() == QStringLiteral("QDateTime")) ? QStringLiteral(".isValid()) ") : QStringLiteral(".isNull()) ")) +
QStringLiteral("obj[QStringLiteral(\"") + cppMemberName() + QStringLiteral("\")] = ");
if (isOptional())
return ret += cppFromQvPre2() + QStringLiteral("element.") + cppMemberName() + cppFromQvPost();
}
return QStringLiteral("obj[QStringLiteral(\"") + cppMemberName() + QStringLiteral("\")] = ") +
cppToJsonPre() + QStringLiteral("element.") + cppMemberName() + cppToJsonPost();
} }
QString MemberInformationWrapper::jsonElementToDb() const QString MemberInformationWrapper::jsonElementToDb() const
{ {
if (cppMemberName().isEmpty())
return QStringLiteral("element = ") + cppFromQvPre2() + QStringLiteral("objElement.value(QStringLiteral(\"") +
cppType() + QStringLiteral("\"))") + cppFromJsonPost();
QString ret(QStringLiteral("const QJsonValue val(objElement.value(QStringLiteral(\"") + cppMemberName() +
QStringLiteral("\"))); "));
if (isOptional())
ret += QStringLiteral("if (!val.isUndefined()) ");
ret += QStringLiteral("element.") + cppMemberName() + QStringLiteral(" = ") + cppFromJsonPre2() +
QStringLiteral("val") + cppFromJsonPost();
return ret;
if (cppMemberName().isEmpty())
return QStringLiteral("element = ") +
cppFromQvPre2() + QStringLiteral("objElement.value(QStringLiteral(\"") + cppType() + QStringLiteral("\"))") + cppFromJsonPost();
QString ret(QStringLiteral("const QJsonValue val(objElement.value(QStringLiteral(\"") + cppMemberName() + QStringLiteral("\"))); "));
if (isOptional())
ret += QStringLiteral("if (!val.isUndefined()) ");
ret += QStringLiteral("element.") + cppMemberName() + QStringLiteral(" = ") +
cppFromJsonPre2() + QStringLiteral("val") + cppFromJsonPost();
return ret;
} }
QVariantList DbStructWrapper::insertStructures() QVariantList DbStructWrapper::insertStructures()
{ {
QStringList tableNames; QStringList tableNames;
QMap<QString, QVector<MemberInformationWrapper *>> structures; QMap<QString, QVector<MemberInformationWrapper*>> structures;
QMap<QString, MemberInformationWrapper *> primaryKeys; QMap<QString, MemberInformationWrapper*> primaryKeys;
QMap<QString, MemberInformationWrapper *> fkComplexTableKeys; QMap<QString, MemberInformationWrapper*> fkComplexTableKeys;
tableNames.reserve(5); tableNames.reserve(5);
for (const QVariant &v : std::as_const(m_member)) for (const QVariant& v : std::as_const(m_member))
{
MemberInformationWrapper *mi = v.value<MemberInformationWrapper *>();
const QString &tableName = mi->info().db.table;
if (mi->info().db.usedForInsert)
{ {
auto &tnStructure = structures[tableName]; MemberInformationWrapper* mi = v.value<MemberInformationWrapper*>();
tnStructure.append(mi); const QString& tableName = mi->info().db.table;
if (!tableNames.contains(tableName)) if (mi->info().db.usedForInsert)
tableNames.push_back(tableName); {
} auto& tnStructure = structures[tableName];
if (mi->info().fk) tnStructure.append(mi);
fkComplexTableKeys[mi->info().fk->destination.tableName] = mi; if (!tableNames.contains(tableName))
if (mi->info().db.isPrimaryKey) tableNames.push_back(tableName);
{ }
if (!primaryKeys.contains(tableName)) if (mi->info().fk)
primaryKeys[tableName] = mi; fkComplexTableKeys[mi->info().fk->destination.tableName] = mi;
} if (mi->info().db.isPrimaryKey)
if (mi->info().db.isAssignmentForPrimaryTablePk) {
fkComplexTableKeys[mi->info().db.table] = mi; if (!primaryKeys.contains(tableName))
} primaryKeys[tableName] = mi;
}
if (mi->info().db.isAssignmentForPrimaryTablePk)
QVariantList vl; fkComplexTableKeys[mi->info().db.table] = mi;
vl.reserve(tableNames.size());
for (int i = 0; i < tableNames.size(); ++i)
{
const QString &tn = tableNames.at(i);
MemberInformationWrapper *serialMember = fkComplexTableKeys.value(tn);
MemberInformationWrapper *baseId = nullptr;
MemberInformationWrapper *primaryKey = primaryKeys.value(tn);
if (i == 0 && tableNames.size() > 1)
baseId = primaryKeys.value(tn);
if (tableNames.size() == 1)
{
baseId = nullptr;
if (!primaryKey)
{
NGL::INGLLogger &logger = NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("DbStructWrapper");
WARNING_LOG(logger) << "Table " << tn << " has no primary key!";
}
else
{
if (primaryKey->dbHasSequence())
serialMember = primaryKey;
}
} }
const QVector<MemberInformationWrapper *> members = structures.value(tn); QVariantList vl;
TableWrapper *tw = new TableWrapper(tn, members, serialMember, baseId, primaryKey, this); vl.reserve(tableNames.size());
vl += QVariant::fromValue(tw); for (int i = 0; i < tableNames.size(); ++i)
} {
const QString& tn = tableNames.at(i);
MemberInformationWrapper* serialMember = fkComplexTableKeys.value(tn);
MemberInformationWrapper* baseId = nullptr;
MemberInformationWrapper* primaryKey = primaryKeys.value(tn);
if (i == 0 && tableNames.size() > 1)
baseId = primaryKeys.value(tn);
return vl; if (tableNames.size() == 1)
{
baseId = nullptr;
if (!primaryKey)
{
NGL::INGLLogger& logger = NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("DbStructWrapper");
WARNING_LOG(logger) << "Table " << tn << " has no primary key!";
}
else
{
if (primaryKey->dbHasSequence())
serialMember = primaryKey;
}
}
const QVector<MemberInformationWrapper*> members = structures.value(tn);
TableWrapper* tw = new TableWrapper(tn, members, serialMember, baseId, primaryKey, this);
vl += QVariant::fromValue(tw);
}
return vl;
} }
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+144 -120
View File
@@ -2,11 +2,12 @@
#pragma once #pragma once
#include <QStringList>
#include <QSharedPointer>
#include "StructBuilder.h" #include "StructBuilder.h"
#include "codegen_base_export.h" #include "codegen_base_export.h"
#include <QSharedPointer>
#include <QStringList>
namespace NGL namespace NGL
{ {
class INGLLogger; class INGLLogger;
@@ -23,152 +24,175 @@ class XmlReader;
class CODEGEN_BASE_EXPORT SqlGenerator final class CODEGEN_BASE_EXPORT SqlGenerator final
{ {
public: public:
struct SqlStatements struct SqlStatements
{
QStringList dropViews;
QStringList dropTables;
QStringList dropSequences;
QStringList dropConstraints;
QStringList createTables;
QStringList createSequences;
QStringList createPrimaryKeys;
QStringList createForeignKeys;
QStringList createViews;
QStringList createConstraints;
QStringList enumerationValues;
QStringList dbFunctions;
QStringList dbFunctionTrigger;
bool isEmpty() const
{ {
return dropViews.isEmpty() && dropTables.isEmpty() && dropSequences.isEmpty() && dropConstraints.isEmpty(); QStringList dropViews;
QStringList dropTables;
QStringList dropSequences;
QStringList dropConstraints;
QStringList createTables;
QStringList createSequences;
QStringList createPrimaryKeys;
QStringList createForeignKeys;
QStringList createViews;
QStringList createConstraints;
QStringList enumerationValues;
QStringList dbFunctions;
QStringList dbFunctionTrigger;
bool isEmpty() const
{
return dropViews.isEmpty() && dropTables.isEmpty() && dropSequences.isEmpty() && dropConstraints.isEmpty();
}
};
struct SqlItems
{
QStringList tables;
QStringList sequences;
QStringList primaryKeys;
QStringList foreignKeys;
QStringList constraints;
};
public:
Q_DISABLE_COPY(SqlGenerator)
explicit SqlGenerator(XmlReader* xmlReader, StructBuilder* structBuilder);
explicit SqlGenerator(const QString& xmlFile);
~SqlGenerator();
bool isValid() const
{
return m_isValid;
} }
};
struct SqlItems bool generateData(int exerciseId);
{
QStringList tables;
QStringList sequences;
QStringList primaryKeys;
QStringList foreignKeys;
QStringList constraints;
};
public: bool createStatementsForTable(const QString& tableName, const QString& tableNameOut);
Q_DISABLE_COPY(SqlGenerator)
explicit SqlGenerator(XmlReader *xmlReader, StructBuilder *structBuilder); SqlStatements getStatements(ExerciseDependency ed) const
explicit SqlGenerator(const QString &xmlFile); {
return (ed == ExerciseDependency::Exercise ? m_sqlExercise : m_sqlGlobal);
}
~SqlGenerator(); SqlItems getSqlItems(ExerciseDependency ed) const
{
return (ed == ExerciseDependency::Exercise ? m_sqlItemsExercise : m_sqlItemsGlobal);
}
bool isValid() const { return m_isValid; } QStringList getEnumerationInsertValues(const QString& table, const QString& dbSchema) const;
bool generateData(int exerciseId); QStringList getReferencedServices() const
{
return m_referencedSevices;
}
bool createStatementsForTable(const QString &tableName, const QString &tableNameOut); QStringList getDbSettings(const QString& dbSchema) const;
SqlStatements getStatements(ExerciseDependency ed) const bool writeSql(const QString& filePath, ExerciseDependency ed);
{
return (ed == ExerciseDependency::Exercise ? m_sqlExercise : m_sqlGlobal);
}
SqlItems getSqlItems(ExerciseDependency ed) const bool writeSqlToFile(const QString& dbSchema, const QString& sqlFile, ExerciseDependency ed) const;
{
return (ed == ExerciseDependency::Exercise ? m_sqlItemsExercise : m_sqlItemsGlobal);
}
QStringList getEnumerationInsertValues(const QString &table, const QString &dbSchema) const; QString getServiceAbbr() const
QStringList getReferencedServices() const {
{ return m_xmlReader->getServiceAbbr();
return m_referencedSevices; }
}
QStringList getDbSettings(const QString &dbSchema) const; bool isServiceExerciseIndependent() const
{
return m_xmlReader->isServiceExerciseIndependent();
}
bool isServiceGlobal() const
{
return (m_xmlReader->defaultExerciseDependency() == CodeGen::ExerciseDependency::Global ||
m_xmlReader->defaultExerciseDependency() == CodeGen::ExerciseDependency::GlobalAndExercise);
}
bool writeSql(const QString &filePath, ExerciseDependency ed); CodeGen::ExerciseDependency getExerciseDependency() const
{
return m_xmlReader->defaultExerciseDependency();
}
bool writeSqlToFile(const QString &dbSchema, const QString &sqlFile, ExerciseDependency ed) const; QStringList getGroupNames() const
{
return m_xmlReader->getGroupNames();
}
QStringList getAllSqlStmts(const QString& dbSchema, ExerciseDependency ed) const;
QString getServiceAbbr() const { return m_xmlReader->getServiceAbbr(); } protected:
bool isServiceExerciseIndependent() const { return m_xmlReader->isServiceExerciseIndependent(); } NGL::INGLLogger& m_logger;
bool isServiceGlobal() const { return (m_xmlReader->defaultExerciseDependency() == CodeGen::ExerciseDependency::Global || m_xmlReader->defaultExerciseDependency() == CodeGen::ExerciseDependency::GlobalAndExercise); }
CodeGen::ExerciseDependency getExerciseDependency() const { return m_xmlReader->defaultExerciseDependency();}
QStringList getGroupNames() const { return m_xmlReader->getGroupNames(); }
QStringList getAllSqlStmts(const QString &dbSchema, ExerciseDependency ed) const; private:
bool handleTables();
bool handleViews();
bool handleTable(const CompleteTableInformation& cti);
bool handleView(const ViewInformation& vi);
QString getTableColumnCreateStatements(const QString& tableName, const QVector<MemberInformation>& columns,
QStringList* tableComments, ExerciseDependency ed);
QString generateSequence(const QString& tableName, const FullQualifiedColumnInformation& ci, ExerciseDependency ed);
void generatePrimaryKey(const QString& tableName, const FullQualifiedColumnInformation& ci, ExerciseDependency ed);
void generateForeignKeys(const QVector<QSharedPointer<ForeignKeyInformation>>& foreignKeys, ExerciseDependency ed);
void generateForeignKey(const QSharedPointer<ForeignKeyInformation>& foreignKey, ExerciseDependency ed);
void generateConstraints(const QString& tableName, const QVector<ConstraintInformation>& constraints,
ExerciseDependency ed);
void generateConstraint(const QString& tableName, const ConstraintInformation& constraint, ExerciseDependency ed);
bool handleEnumerations();
bool handleEnumeration(const EnumInformation& ei);
QStringList handleEnumeration(const EnumInformation& ei, const QString& dbSchema) const;
bool generateDbNotifications(const QString& tableName, const QVector<DbNotifcationInformation>& notifications,
ExerciseDependency ed);
void generateDbNotification(const DbNotifcationInformation& notification, ExerciseDependency ed);
bool generateDbNotificationTrigger(const QString& tableName, const DbNotifcationInformation& notification,
ExerciseDependency ed);
QString getNotificationFunctionName(const DbNotifcationInformation& notification) const;
static QString fixupComment(const QString& comment);
private:
XmlReader* m_xmlReader;
StructBuilder* m_structBuilder;
bool m_createdByXmlFile;
protected: void addToDropSequences(const QString& stmt, ExerciseDependency ed);
void addToDropTables(const QString& stmt, ExerciseDependency ed);
void addToDropViews(const QString& stmt, ExerciseDependency ed);
void addToDropConstraints(const QString& stmt, ExerciseDependency ed);
NGL::INGLLogger &m_logger; void addToCreateConstraints(const QString& stmt, ExerciseDependency ed);
private: void addToCreateFks(const QString& stmt, ExerciseDependency ed);
bool handleTables(); void addToCreatePks(const QString& stmt, ExerciseDependency ed);
bool handleViews(); void addToCreateSequences(const QString& stmt, ExerciseDependency ed);
bool handleTable(const CompleteTableInformation &cti); void addToCreateTables(const QString& stmt, ExerciseDependency ed);
bool handleView(const ViewInformation &vi); void addToCreateTables(const QStringList& stmts, ExerciseDependency ed);
QString getTableColumnCreateStatements(const QString &tableName, void addToCreateViews(const QString& stmt, ExerciseDependency ed);
const QVector<MemberInformation> &columns,
QStringList *tableComments, ExerciseDependency ed);
QString generateSequence(const QString &tableName, const FullQualifiedColumnInformation &ci, ExerciseDependency ed);
void generatePrimaryKey(const QString &tableName, const FullQualifiedColumnInformation &ci, ExerciseDependency ed);
void generateForeignKeys(const QVector<QSharedPointer<ForeignKeyInformation> > &foreignKeys, ExerciseDependency ed);
void generateForeignKey(const QSharedPointer<ForeignKeyInformation> &foreignKey, ExerciseDependency ed);
void generateConstraints(const QString &tableName, const QVector<ConstraintInformation> &constraints, ExerciseDependency ed);
void generateConstraint(const QString &tableName, const ConstraintInformation &constraint, ExerciseDependency ed);
bool handleEnumerations();
bool handleEnumeration(const EnumInformation &ei);
QStringList handleEnumeration(const EnumInformation &ei, const QString &dbSchema) const;
bool generateDbNotifications(const QString &tableName, const QVector<DbNotifcationInformation> &notifications, ExerciseDependency ed);
void generateDbNotification(const DbNotifcationInformation &notification, ExerciseDependency ed);
bool generateDbNotificationTrigger(const QString &tableName, const DbNotifcationInformation &notification, ExerciseDependency ed);
QString getNotificationFunctionName(const DbNotifcationInformation &notification) const;
static QString fixupComment(const QString &comment);
private: void addToDbFunctions(const QString& stmt, ExerciseDependency ed);
XmlReader *m_xmlReader; void addToDbFunctionTrigger(const QString& stmt, ExerciseDependency ed);
StructBuilder *m_structBuilder;
bool m_createdByXmlFile;
void addToDropSequences(const QString &stmt, ExerciseDependency ed); void addToConstraints(const QString& name, ExerciseDependency ed);
void addToDropTables(const QString &stmt, ExerciseDependency ed); void addToFks(const QString& name, ExerciseDependency ed);
void addToDropViews(const QString &stmt, ExerciseDependency ed); void addToPks(const QString& name, ExerciseDependency ed);
void addToDropConstraints(const QString &stmt, ExerciseDependency ed); void addToSequences(const QString& name, ExerciseDependency ed);
void addToTables(const QString& name, ExerciseDependency ed);
void addToCreateConstraints(const QString &stmt, ExerciseDependency ed); bool writeFile(const QString& fn, const QString& content) const;
void addToCreateFks(const QString &stmt, ExerciseDependency ed);
void addToCreatePks(const QString &stmt, ExerciseDependency ed);
void addToCreateSequences(const QString &stmt, ExerciseDependency ed);
void addToCreateTables(const QString &stmt, ExerciseDependency ed);
void addToCreateTables(const QStringList &stmts, ExerciseDependency ed);
void addToCreateViews(const QString &stmt, ExerciseDependency ed);
void addToDbFunctions(const QString &stmt, ExerciseDependency ed); SqlStatements m_sqlGlobal;
void addToDbFunctionTrigger(const QString &stmt, ExerciseDependency ed); SqlStatements m_sqlExercise;
void addToConstraints(const QString &name, ExerciseDependency ed); SqlItems m_sqlItemsGlobal;
void addToFks(const QString &name, ExerciseDependency ed); SqlItems m_sqlItemsExercise;
void addToPks(const QString &name, ExerciseDependency ed);
void addToSequences(const QString &name, ExerciseDependency ed);
void addToTables(const QString &name, ExerciseDependency ed);
bool writeFile(const QString &fn, const QString &content) const; QStringList m_referencedSevices;
SqlStatements m_sqlGlobal; bool m_isValid;
SqlStatements m_sqlExercise; int m_exerciseId;
SqlItems m_sqlItemsGlobal;
SqlItems m_sqlItemsExercise;
QStringList m_referencedSevices;
bool m_isValid;
int m_exerciseId;
}; };
} } // namespace CodeGen
File diff suppressed because it is too large. Load diff
+290 -246
View File
@@ -2,10 +2,11 @@
#pragma once #pragma once
#include <QtCore/QString>
#include "XmlReader.h" #include "XmlReader.h"
#include "codegen_base_export.h" #include "codegen_base_export.h"
#include <QtCore/QString>
namespace NGL namespace NGL
{ {
class INGLLogger; class INGLLogger;
@@ -17,325 +18,368 @@ class StructBuilder;
struct EaData struct EaData
{ {
QString table; QString table;
QString column; QString column;
QString type; QString type;
QString toString() const QString toString() const
{ {
return table + return table + QLatin1Char(';') + column + QLatin1Char(';') + type;
QLatin1Char(';') + column + }
QLatin1Char(';') + type;
}
}; };
struct FullQualifiedColumnInformation : public ColumnInformation struct FullQualifiedColumnInformation : public ColumnInformation
{ {
QString table; QString table;
bool usedForInsert = false; bool usedForInsert = false;
bool usedForView = false; bool usedForView = false;
QString columnNameView; QString columnNameView;
QString getColumnNameView() const { return columnNameView.isEmpty() ? columnName : columnNameView; } QString getColumnNameView() const
{
return columnNameView.isEmpty() ? columnName : columnNameView;
}
FullQualifiedColumnInformation() = default; FullQualifiedColumnInformation() = default;
FullQualifiedColumnInformation(const ColumnInformation &ci, const QString &tableName)
: ColumnInformation(ci)
, table(tableName)
{}
QString toString() const FullQualifiedColumnInformation(const ColumnInformation& ci, const QString& tableName)
{ : ColumnInformation(ci), table(tableName)
return table + {
QLatin1Char(';') + columnName + }
QLatin1Char(';') + datatype +
QLatin1Char(';') + (isPrimaryKey ? QLatin1String("true") : QLatin1String("false")) + QString toString() const
QLatin1Char(';') + (isForeignKey ? QLatin1String("true") : QLatin1String("false")) + {
QLatin1Char(';') + (usedForInsert ? QLatin1String("true") : QLatin1String("false")) + return table + QLatin1Char(';') + columnName + QLatin1Char(';') + datatype +
QLatin1Char(';') + (usedForView ? QLatin1String("true") : QLatin1String("false"));
} QLatin1Char(';') + (isPrimaryKey ? QLatin1String("true") : QLatin1String("false")) + QLatin1Char(';') +
(isForeignKey ? QLatin1String("true") : QLatin1String("false")) + QLatin1Char(';') +
(usedForInsert ? QLatin1String("true") : QLatin1String("false")) + QLatin1Char(';') +
(usedForView ? QLatin1String("true") : QLatin1String("false"));
}
}; };
class DataTypeInfo class DataTypeInfo
{ {
public: public:
DataTypeInfo(const QString &name, bool isPod) DataTypeInfo(const QString& name, bool isPod) : m_name(name), m_isPod(isPod) {}
: m_name(name)
, m_isPod(isPod)
{}
virtual ~DataTypeInfo() = default;
virtual QString name() const { return m_name; }
virtual QString idlType() const = 0;
virtual QString ddsType() const = 0;
virtual QString sqlType() const = 0;
virtual QString cppType() const = 0;
virtual QString cppTypeConstRef() const { return isPod() ? cppType() : QLatin1String("const ") + cppType() + QLatin1String(" &"); }
virtual bool isPod() const { return m_isPod; }
virtual bool isSequence() const { return false; }
virtual bool isStructure() const { return false; }
virtual QVector<QSharedPointer<DataTypeInfo>> member() const { return QVector<QSharedPointer<DataTypeInfo>>(); }
virtual QSharedPointer<DataTypeInfo> innerDataType() const { return QSharedPointer<DataTypeInfo>(); }
static QSharedPointer<DataTypeInfo> fromIdlDataType(const QString &name, virtual ~DataTypeInfo() = default;
const QString &idlType,
StructBuilder *structBuilder, virtual QString name() const
const QString &svcName = QString()); {
protected: return m_name;
const QString m_name; }
const bool m_isPod;
virtual QString idlType() const = 0;
virtual QString ddsType() const = 0;
virtual QString sqlType() const = 0;
virtual QString cppType() const = 0;
virtual QString cppTypeConstRef() const
{
return isPod() ? cppType() : QLatin1String("const ") + cppType() + QLatin1String(" &");
}
virtual bool isPod() const
{
return m_isPod;
}
virtual bool isSequence() const
{
return false;
}
virtual bool isStructure() const
{
return false;
}
virtual QVector<QSharedPointer<DataTypeInfo>> member() const
{
return QVector<QSharedPointer<DataTypeInfo>>();
}
virtual QSharedPointer<DataTypeInfo> innerDataType() const
{
return QSharedPointer<DataTypeInfo>();
}
static QSharedPointer<DataTypeInfo> fromIdlDataType(const QString& name, const QString& idlType,
StructBuilder* structBuilder,
const QString& svcName = QString());
protected:
const QString m_name;
const bool m_isPod;
}; };
struct IdlData : public IdlColumnInformation struct IdlData : public IdlColumnInformation
{ {
QSharedPointer<DataTypeInfo> dataTypeInfo; QSharedPointer<DataTypeInfo> dataTypeInfo;
IdlData() = default; IdlData() = default;
explicit IdlData(const IdlColumnInformation &ci)
: IdlColumnInformation(ci)
{}
QString toString() const explicit IdlData(const IdlColumnInformation& ci) : IdlColumnInformation(ci) {}
{
return name +
QLatin1Char(';') + type +
QLatin1Char(';') + (isKey ? QLatin1String("true") : QLatin1String("false")) + QString toString() const
QLatin1Char(';') + (isOptional ? QLatin1String("true") : QLatin1String("false")); {
} return name + QLatin1Char(';') + type +
QLatin1Char(';') + (isKey ? QLatin1String("true") : QLatin1String("false")) + QLatin1Char(';') +
(isOptional ? QLatin1String("true") : QLatin1String("false"));
}
}; };
struct CppData struct CppData
{ {
QString structName; QString structName;
QString memberName; QString memberName;
QString defaultValue; QString defaultValue;
bool usedForCppStruct = false; bool usedForCppStruct = false;
bool usedForJson = false; bool usedForJson = false;
bool isReadOnly = false; bool isReadOnly = false;
bool isOptional = false; bool isOptional = false;
QString type; QString type;
QString ddsType; QString ddsType;
QString toVariantPre; QString toVariantPre;
QString toVariantPost; QString toVariantPost;
QString fromVariantPre1; QString fromVariantPre1;
QString fromVariantPre2; QString fromVariantPre2;
QString fromVariantPost; QString fromVariantPost;
QString toJsonPre; QString toJsonPre;
QString toJsonPost; QString toJsonPost;
QString fromJsonPre2; QString fromJsonPre2;
QString fromJsonPost; QString fromJsonPost;
QString toString() const QString toString() const
{ {
return structName + return structName + QLatin1Char(';') + memberName + QLatin1Char(';') +
QLatin1Char(';') + memberName + (usedForCppStruct ? QLatin1String("true") : QLatin1String("false")) + QLatin1Char(';') +
QLatin1Char(';') + (usedForCppStruct ? QLatin1String("true") : QLatin1String("false")) + (isReadOnly ? QLatin1String("true") : QLatin1String("false")) + QLatin1Char(';') + type +
QLatin1Char(';') + (isReadOnly ? QLatin1String("true") : QLatin1String("false")) + QLatin1Char(';') + toVariantPre + QLatin1Char(';') + toVariantPost + QLatin1Char(';') + fromVariantPre1 +
QLatin1Char(';') + type + QLatin1Char(';') + fromVariantPre2 + QLatin1Char(';') + fromVariantPost;
QLatin1Char(';') + toVariantPre + }
QLatin1Char(';') + toVariantPost +
QLatin1Char(';') + fromVariantPre1 +
QLatin1Char(';') + fromVariantPre2 +
QLatin1Char(';') + fromVariantPost;
}
}; };
struct MemberInformation struct MemberInformation
{ {
EaData ea; EaData ea;
FullQualifiedColumnInformation db; FullQualifiedColumnInformation db;
CppData cpp; CppData cpp;
bool isDdsKey = false; bool isDdsKey = false;
QSharedPointer<ForeignKeyInformation> fk; QSharedPointer<ForeignKeyInformation> fk;
QSharedPointer<EnumInformation> enumeration; QSharedPointer<EnumInformation> enumeration;
QString toString() const QString toString() const
{ {
return ea.toString() + QLatin1Char(';') + return ea.toString() + QLatin1Char(';') + db.toString() + QLatin1Char(';') + cpp.toString();
db.toString() + QLatin1Char(';') + }
cpp.toString();
} bool isEmpty() const
bool isEmpty() const {
{ return ea.column.isEmpty();
return ea.column.isEmpty(); }
}
}; };
struct CompleteStructInformation struct CompleteStructInformation
{ {
QString structName; QString structName;
QString viewName; QString viewName;
QSet<QSharedPointer<TableInformation> > tables; QSet<QSharedPointer<TableInformation>> tables;
QSharedPointer<TableInformation> primaryTable; QSharedPointer<TableInformation> primaryTable;
QVector<MemberInformation> member; QVector<MemberInformation> member;
QVector<DbNotifcationInformation> dbNotifications; QVector<DbNotifcationInformation> dbNotifications;
bool hasStaticContent = false; bool hasStaticContent = false;
bool isEmpty() const bool isEmpty() const
{ {
return primaryTable.isNull(); return primaryTable.isNull();
} }
}; };
struct CompleteTopicTypeInformation final : public TopicTypeInformationBase struct CompleteTopicTypeInformation final : public TopicTypeInformationBase
{ {
QString serviceName; QString serviceName;
QVector<IdlData> members; QVector<IdlData> members;
CompleteTopicTypeInformation() = default; CompleteTopicTypeInformation() = default;
explicit CompleteTopicTypeInformation(const TopicTypeInformationBase &s)
: TopicTypeInformationBase(s)
{}
bool hasBaseValue() const { return !baseValueType.isEmpty(); } explicit CompleteTopicTypeInformation(const TopicTypeInformationBase& s) : TopicTypeInformationBase(s) {}
bool isValid() const { return TopicTypeInformationBase::isValid() && !members.isEmpty(); }
bool hasBaseValue() const
{
return !baseValueType.isEmpty();
}
bool isValid() const
{
return TopicTypeInformationBase::isValid() && !members.isEmpty();
}
}; };
struct CompleteTableInformation : public TableInformation struct CompleteTableInformation : public TableInformation
{ {
QVector<MemberInformation> columns; QVector<MemberInformation> columns;
explicit CompleteTableInformation(const TableInformation &o)
: TableInformation(o) explicit CompleteTableInformation(const TableInformation& o) : TableInformation(o) {}
{}
CompleteTableInformation() = default; CompleteTableInformation() = default;
bool isEmpty() const { return columns.isEmpty(); }
bool isEmpty() const
{
return columns.isEmpty();
}
}; };
class CODEGEN_BASE_EXPORT StructBuilder class CODEGEN_BASE_EXPORT StructBuilder
{ {
struct ColumnInformationEx : public ColumnInformation struct ColumnInformationEx : public ColumnInformation
{ {
QSharedPointer<TableInformation> table; QSharedPointer<TableInformation> table;
ColumnInformationEx() = default; ColumnInformationEx() = default;
ColumnInformationEx(const ColumnInformation &o,
const QSharedPointer<TableInformation> &ti)
: ColumnInformation(o)
, table(ti)
{}
};
public: ColumnInformationEx(const ColumnInformation& o, const QSharedPointer<TableInformation>& ti)
struct ServiceTypeStruct : ColumnInformation(o), table(ti)
{ {
QString service; }
QString type; };
bool bIsSequence = false;
bool isExternalType() const { return !service.isEmpty(); }
bool isSequence() const { return bIsSequence; }
QString fqType() const { return service + QStringLiteral("::") + type; }
};
explicit StructBuilder(XmlReader *xmlReader); public:
~StructBuilder() = default; struct ServiceTypeStruct
{
QString service;
QString type;
bool bIsSequence = false;
bool buildStructures(); bool isExternalType() const
QVector<CompleteStructInformation> structInformations() const {
{ return !service.isEmpty();
return m_structInfos; }
}
QVector<CompleteTopicTypeInformation> topicTypeInformations() const
{
return m_topicTypeInfos;
}
CompleteStructInformation structInformationByTableName(const QString &tableName) const; bool isSequence() const
{
return bIsSequence;
}
EnumInformation enumInformationByType(const QString &type, bool checkExternals = true, bool verbose = true); QString fqType() const
{
return service + QStringLiteral("::") + type;
}
};
CompleteTopicTypeInformation topicTypeInformationByStructType(const QString &type, bool checkExternals = true); explicit StructBuilder(XmlReader* xmlReader);
CompleteTopicTypeInformation externalTopicTypeByStructType(const ServiceTypeStruct &sts); ~StructBuilder() = default;
QVector<EnumInformation> enumInformations() const bool buildStructures();
{
return m_enumInfos;
}
QMap<QString, CompleteTableInformation> getDbTables() const QVector<CompleteStructInformation> structInformations() const
{ {
return m_sqlTableInformations; return m_structInfos;
} }
QMap<QString, ViewInformation> getDbViews() const QVector<CompleteTopicTypeInformation> topicTypeInformations() const
{ {
return m_sqlViewInformations; return m_topicTypeInfos;
} }
bool needPoint3d() const CompleteStructInformation structInformationByTableName(const QString& tableName) const;
{
return m_needPoint3d;
}
bool needPgArrayInclude() const EnumInformation enumInformationByType(const QString& type, bool checkExternals = true, bool verbose = true);
{
return m_needPgArrayInclude;
}
CompleteTableInformation completeTableInformation(const CompleteTopicTypeInformation &ctti); CompleteTopicTypeInformation topicTypeInformationByStructType(const QString& type, bool checkExternals = true);
CompleteTableInformation getRecordingTopicTable(const QString &structName); CompleteTopicTypeInformation externalTopicTypeByStructType(const ServiceTypeStruct& sts);
QMap<QString, CompleteTableInformation> getRecordingTopicTables();
QVector<QSharedPointer<DataTypeInfo> > getSerializeFromToJsonTopics() const;
bool fixupQVariantConversions(MemberInformation &mi) const;
Q_REQUIRED_RESULT static QString firstCharLowercase(const QString &txt); QVector<EnumInformation> enumInformations() const
Q_REQUIRED_RESULT static QString camelCaseString(const QString &in, bool bFirstUppercase = false); {
Q_REQUIRED_RESULT static QString camelCaseToUnderline(const QString &in); return m_enumInfos;
}
bool buildJSonStructureInformationFromIdlData(const CompleteTopicTypeInformation &ctti); QMap<QString, CompleteTableInformation> getDbTables() const
QMap<QString, QVector<MemberInformation>> jsonStructureInformation() const { return m_jsonStructureInformation; } {
return m_sqlTableInformations;
}
private: QMap<QString, ViewInformation> getDbViews() const
bool handleEnum(const EnumInformation &ei); {
bool handleTable(const ServiceStructInformation &ssi); return m_sqlViewInformations;
bool handleIdlStructInfo(const TopicTypeInformation &tti, }
QVector<CompleteTopicTypeInformation> &destination,
const QString &svcName = QString());
bool loadExternalTopicType(const ServiceTypeStruct &sts);
bool getColumnsFromTable(const QString &tableName, bool needPoint3d() const
QVector<ColumnInformationEx> &columns, {
QVector<QString> &tableNames) const; return m_needPoint3d;
}
bool fixupCustomDbDatatypes(MemberInformation &memberInfo, QVector<MemberInformation> &members); bool needPgArrayInclude() const
bool fixupDatatypePoint2d(MemberInformation &memberInfo, QVector<MemberInformation> &members); {
bool fixupDatatypePoint3d(MemberInformation &memberInfo, QVector<MemberInformation> &members); return m_needPgArrayInclude;
bool fixupDatatypeIntegerArray(MemberInformation &memberInfo); }
QVector<MemberInformation> buildDbTableInformationFromIdlData(const CompleteTopicTypeInformation &ctti, CompleteTableInformation completeTableInformation(const CompleteTopicTypeInformation& ctti);
const QString &tableName, CompleteTableInformation getRecordingTopicTable(const QString& structName);
const QString &columnNamePrefix, QMap<QString, CompleteTableInformation> getRecordingTopicTables();
const QString &cppStructure); QVector<QSharedPointer<DataTypeInfo>> getSerializeFromToJsonTopics() const;
void addToSerializeFromToJsonTopics(const QSharedPointer<DataTypeInfo> &toAdd); bool fixupQVariantConversions(MemberInformation& mi) const;
CompleteTableInformation getRecordingTopicTable(const CompleteTopicTypeInformation &ctti,
const MemberInformation &miPrimaryKey);
MemberInformation getRecordPrimaryKey() const;
ServiceTypeStruct extractServiceAndTypeFromTypename(const QString &type); Q_REQUIRED_RESULT static QString firstCharLowercase(const QString& txt);
Q_REQUIRED_RESULT static QString camelCaseString(const QString& in, bool bFirstUppercase = false);
Q_REQUIRED_RESULT static QString camelCaseToUnderline(const QString& in);
void addToSqlTableInformation(const MemberInformation &mi); bool buildJSonStructureInformationFromIdlData(const CompleteTopicTypeInformation& ctti);
private:
QVector<CompleteStructInformation> m_structInfos;
QVector<CompleteTopicTypeInformation> m_topicTypeInfos;
mutable QVector<CompleteTopicTypeInformation> m_externalTopicTypes;
QVector<EnumInformation> m_enumInfos;
QMap<QString, CompleteTableInformation> m_sqlTableInformations;
QMap<QString, ViewInformation> m_sqlViewInformations;
QSet<QString> m_sqlTableInformationsAlreadyAvailable;
QVector<QSharedPointer<DataTypeInfo>> m_serializeFromToJsonTopics;
QMap<QString, QVector<MemberInformation>> m_jsonStructureInformation; QMap<QString, QVector<MemberInformation>> jsonStructureInformation() const
{
return m_jsonStructureInformation;
}
bool m_needPoint3d; private:
bool m_needPgArrayInclude; bool handleEnum(const EnumInformation& ei);
bool handleTable(const ServiceStructInformation& ssi);
bool handleIdlStructInfo(const TopicTypeInformation& tti, QVector<CompleteTopicTypeInformation>& destination,
const QString& svcName = QString());
bool loadExternalTopicType(const ServiceTypeStruct& sts);
XmlReader *m_xmlReader; bool getColumnsFromTable(const QString& tableName, QVector<ColumnInformationEx>& columns,
NGL::INGLLogger &m_logger; QVector<QString>& tableNames) const;
NGL::INGLLogger &m_loggerCSV;
bool fixupCustomDbDatatypes(MemberInformation& memberInfo, QVector<MemberInformation>& members);
bool fixupDatatypePoint2d(MemberInformation& memberInfo, QVector<MemberInformation>& members);
bool fixupDatatypePoint3d(MemberInformation& memberInfo, QVector<MemberInformation>& members);
bool fixupDatatypeIntegerArray(MemberInformation& memberInfo);
QVector<MemberInformation> buildDbTableInformationFromIdlData(const CompleteTopicTypeInformation& ctti,
const QString& tableName,
const QString& columnNamePrefix,
const QString& cppStructure);
void addToSerializeFromToJsonTopics(const QSharedPointer<DataTypeInfo>& toAdd);
CompleteTableInformation getRecordingTopicTable(const CompleteTopicTypeInformation& ctti,
const MemberInformation& miPrimaryKey);
MemberInformation getRecordPrimaryKey() const;
ServiceTypeStruct extractServiceAndTypeFromTypename(const QString& type);
void addToSqlTableInformation(const MemberInformation& mi);
private:
QVector<CompleteStructInformation> m_structInfos;
QVector<CompleteTopicTypeInformation> m_topicTypeInfos;
mutable QVector<CompleteTopicTypeInformation> m_externalTopicTypes;
QVector<EnumInformation> m_enumInfos;
QMap<QString, CompleteTableInformation> m_sqlTableInformations;
QMap<QString, ViewInformation> m_sqlViewInformations;
QSet<QString> m_sqlTableInformationsAlreadyAvailable;
QVector<QSharedPointer<DataTypeInfo>> m_serializeFromToJsonTopics;
QMap<QString, QVector<MemberInformation>> m_jsonStructureInformation;
bool m_needPoint3d;
bool m_needPgArrayInclude;
XmlReader* m_xmlReader;
NGL::INGLLogger& m_logger;
NGL::INGLLogger& m_loggerCSV;
}; };
} } // namespace CodeGen
File diff suppressed because it is too large. Load diff
+316 -296
View File
@@ -31,409 +31,429 @@ class QDomElement;
namespace CodeGen namespace CodeGen
{ {
enum ExerciseDependency enum ExerciseDependency { Undefined = 0, Global = 0x1, Exercise = 0x2, GlobalAndExercise = 0x3 };
{
Undefined = 0,
Global = 0x1,
Exercise = 0x2,
GlobalAndExercise = 0x3
};
struct EnumKeyValuePair struct EnumKeyValuePair
{ {
QString key; QString key;
int value = 0; int value = 0;
}; };
struct EnumInformation struct EnumInformation
{ {
QString enumName; QString enumName;
QString tableName; QString tableName;
QString serviceName; QString serviceName;
QVector<EnumKeyValuePair> values; QVector<EnumKeyValuePair> values;
bool isValid() const { return !enumName.isEmpty(); } bool isValid() const
{
return !enumName.isEmpty();
}
}; };
struct ColumnInformation struct ColumnInformation
{ {
QString columnName; QString columnName;
QString datatype; QString datatype;
QString comment; QString comment;
QString defaultValue; QString defaultValue;
bool isPrimaryKey = false; bool isPrimaryKey = false;
bool isAssignmentForPrimaryTablePk = false; bool isAssignmentForPrimaryTablePk = false;
bool isForeignKey = false; bool isForeignKey = false;
bool generateSelectRemove = false; bool generateSelectRemove = false;
bool canBeNull = true; bool canBeNull = true;
bool hasSequence = false; bool hasSequence = false;
bool isOptional = false; bool isOptional = false;
int sequenceStart = 0; int sequenceStart = 0;
int sequenceIncrement = 0; int sequenceIncrement = 0;
}; };
struct IdlColumnInformation struct IdlColumnInformation
{ {
QString name; QString name;
QString type; QString type;
QString comment; QString comment;
bool isKey = false; bool isKey = false;
bool isOptional = false; bool isOptional = false;
bool isTranslatable = false; bool isTranslatable = false;
}; };
struct ForeignKeyInformation struct ForeignKeyInformation
{ {
struct Endpoint struct Endpoint
{ {
QString service; QString service;
QString serviceAbbr; QString serviceAbbr;
QString schema; QString schema;
QString tableName; QString tableName;
QString columnName; QString columnName;
}; };
QString name; QString name;
Endpoint source; Endpoint source;
Endpoint destination; Endpoint destination;
enum class OnDeleteAction enum class OnDeleteAction {
{ NoAction,
NoAction, Cascade,
Cascade, Restrict,
Restrict, SetNull,
SetNull, SetDefault
SetDefault } deleteAction = OnDeleteAction::Cascade;
} deleteAction = OnDeleteAction::Cascade;
}; };
struct CustomServiceFunctionInformation struct CustomServiceFunctionInformation
{ {
QString methodName; QString methodName;
QString returnValue; QString returnValue;
QString signature; QString signature;
bool isConst = false; bool isConst = false;
QVector<QString> paramTypes; QVector<QString> paramTypes;
QVector<QString> paramNames; QVector<QString> paramNames;
enum class Type enum class Type { Db, DbNotify, Dtc } type = Type::Db;
{
Db,
DbNotify,
Dtc
} type = Type::Db;
}; };
struct DbNotifcationInformation : public CustomServiceFunctionInformation struct DbNotifcationInformation : public CustomServiceFunctionInformation
{ {
DbNotifcationInformation() = default; DbNotifcationInformation() = default;
explicit DbNotifcationInformation(const CustomServiceFunctionInformation &d)
: CustomServiceFunctionInformation(d) explicit DbNotifcationInformation(const CustomServiceFunctionInformation& d) : CustomServiceFunctionInformation(d)
{} {
enum class NotificationType }
{ enum class NotificationType { BeforeInsert, AfterInsert, BeforeUpdate, AfterUpdate, BeforeDelete, AfterDelete };
BeforeInsert, QVector<NotificationType> notificationType;
AfterInsert,
BeforeUpdate,
AfterUpdate,
BeforeDelete,
AfterDelete
};
QVector<NotificationType> notificationType;
}; };
struct ConstraintInformation struct ConstraintInformation
{ {
enum struct Type enum struct Type { unknown = 0x00, unique = 0x01, index = 0x02 } type = Type::unknown;
{ QString name;
unknown = 0x00, QStringList affectedColumns;
unique = 0x01,
index = 0x02
} type = Type::unknown;
QString name;
QStringList affectedColumns;
}; };
struct TableInformation struct TableInformation
{ {
QString name; QString name;
QString structName; QString structName;
QString comment; QString comment;
QVector<ColumnInformation> plainColumns; QVector<ColumnInformation> plainColumns;
QVector<QSharedPointer<ForeignKeyInformation> > foreignKeys; QVector<QSharedPointer<ForeignKeyInformation>> foreignKeys;
QVector<ConstraintInformation> constraints; QVector<ConstraintInformation> constraints;
ExerciseDependency exerciseDependency = ExerciseDependency::Undefined; ExerciseDependency exerciseDependency = ExerciseDependency::Undefined;
QSharedPointer<ForeignKeyInformation> fkInformationForColumn(const QString &tableName, QSharedPointer<ForeignKeyInformation> fkInformationForColumn(const QString& tableName,
const QString &columnName) const const QString& columnName) const
{
for (const QSharedPointer<ForeignKeyInformation> &fki : foreignKeys)
{ {
if (fki->source.columnName == columnName && for (const QSharedPointer<ForeignKeyInformation>& fki : foreignKeys)
fki->source.tableName == tableName) {
return fki; if (fki->source.columnName == columnName && fki->source.tableName == tableName)
return fki;
}
return QSharedPointer<ForeignKeyInformation>();
} }
return QSharedPointer<ForeignKeyInformation>();
}
}; };
struct ViewInformation struct ViewInformation
{ {
QString name; QString name;
QString comment; QString comment;
QString structName; QString structName;
QString baseTable; QString baseTable;
QString baseSchema; QString baseSchema;
QString filter; QString filter;
ExerciseDependency exerciseDependency = ExerciseDependency::Undefined; ExerciseDependency exerciseDependency = ExerciseDependency::Undefined;
}; };
struct ServiceStructInformation struct ServiceStructInformation
{ {
QString name; QString name;
QString primaryTable; QString primaryTable;
bool hasStaticContent = false; bool hasStaticContent = false;
bool operator<(const ServiceStructInformation &o) const bool operator<(const ServiceStructInformation& o) const
{ {
if (hasStaticContent != o.hasStaticContent) if (hasStaticContent != o.hasStaticContent)
return hasStaticContent < o.hasStaticContent; return hasStaticContent < o.hasStaticContent;
if (name != o.name) if (name != o.name)
return name < o.name; return name < o.name;
return primaryTable < o.primaryTable; return primaryTable < o.primaryTable;
} }
QVector<DbNotifcationInformation> dbNotifications;
QVector<DbNotifcationInformation> dbNotifications;
}; };
struct TopicTypeInformationBase struct TopicTypeInformationBase
{ {
TopicTypeInformationBase() = default; TopicTypeInformationBase() = default;
virtual ~TopicTypeInformationBase() = default; virtual ~TopicTypeInformationBase() = default;
QString name; QString name;
QString baseValueType; QString baseValueType;
QString comment; QString comment;
bool isDataObject = false; bool isDataObject = false;
bool dtsAutogen = true; bool dtsAutogen = true;
bool dtcAutogen = true; bool dtcAutogen = true;
bool recordTopic = false; bool recordTopic = false;
bool routeToClient = true; bool routeToClient = true;
bool routeToServer = false; bool routeToServer = false;
bool routeInReplay = true; bool routeInReplay = true;
bool autosubscribe = true; bool autosubscribe = true;
#ifdef RTI_DDS_AVAILABLE #ifdef RTI_DDS_AVAILABLE
dds::core::xtypes::ExtensibilityKind extensibility = dds::core::xtypes::ExtensibilityKind::EXTENSIBLE; dds::core::xtypes::ExtensibilityKind extensibility = dds::core::xtypes::ExtensibilityKind::EXTENSIBLE;
#else #else
int extensibility = 0; // Placeholder when RTI DDS is not available int extensibility = 0; // Placeholder when RTI DDS is not available
#endif #endif
virtual bool isValid() const { return !name.isEmpty(); } virtual bool isValid() const
{
return !name.isEmpty();
}
bool operator<(const TopicTypeInformationBase &o) const bool operator<(const TopicTypeInformationBase& o) const
{ {
if (name != o.name) if (name != o.name)
return name < o.name; return name < o.name;
return baseValueType < o.baseValueType; return baseValueType < o.baseValueType;
} }
}; };
struct TopicTypeInformation : public TopicTypeInformationBase struct TopicTypeInformation : public TopicTypeInformationBase
{ {
QVector<IdlColumnInformation> columns; QVector<IdlColumnInformation> columns;
}; };
struct FunctionTopic struct FunctionTopic
{ {
QString name; QString name;
QString requestTopicType; QString requestTopicType;
QString replyTopicType; QString replyTopicType;
QString requestTopicName; QString requestTopicName;
QString replyTopicName; QString replyTopicName;
bool routeInReplay = false; bool routeInReplay = false;
}; };
class CODEGEN_BASE_EXPORT XmlReader final class CODEGEN_BASE_EXPORT XmlReader final
{ {
public: public:
XmlReader(); XmlReader();
bool readServiceFile(const QString &svcFile, bool readServiceFile(const QString& svcFile, const QString& idlServiceInfoFile = QString(),
const QString &idlServiceInfoFile = QString(), const XmlReader* parent = nullptr);
const XmlReader *parent = nullptr);
QString errorString() const
{
return m_errorString;
}
QString getServiceNamespace() const { return m_svcNamespace; } QString errorString() const
QString getServiceAbbr() const { return m_svcAbbr; }
QStringList getGroupNames() const { return m_groupNames; }
int getPrio() const { return m_prio;}
QStringList getProcNames() const { return m_svcProcNames; }
bool hasCustomRecordReplayPlugin() const { return m_customRecordReplay; }
bool getDevMode() const { return m_svcDevMode; }
bool isServiceExerciseIndependent() const { return m_exerciseDependency == ExerciseDependency::Global; }
ExerciseDependency defaultExerciseDependency() const { return m_exerciseDependency; }
QMap<QString, QVector<QString> > getDbClass2TableMapping() const { return m_dbClassTables; }
QMap<QString, QString> getStruct2BaseClassRelations() const { return m_struct2BaseClass; }
QVector<ServiceStructInformation> getStructToGenerate() const { return m_structsToGenerate; }
QMap<QString, TopicTypeInformation > getIdlStructInformation() const { return m_idlStructsToGenerate; }
QVector<TopicTypeInformation> getIdlStructToGenerate() const
{
QVector<TopicTypeInformation> res;
res.reserve(m_idlStructsToGenerate.size());
auto it = m_idlStructsToGenerate.constBegin();
while (it != m_idlStructsToGenerate.constEnd())
{ {
res.append(it.value()); return m_errorString;
++it;
} }
return res;
}
QString getServiceNamespace() const
{
return m_svcNamespace;
}
QMap<QString, QSharedPointer<TableInformation> > getTables() const QString getServiceAbbr() const
{ {
return m_tables; return m_svcAbbr;
} }
QMap<QString, QSharedPointer<ViewInformation> > getViews() const
{
return m_views;
}
QSharedPointer<TableInformation> getTable(const QString &table) const
{
return m_tables.value(table);
}
QVector<EnumInformation> getEnumerations() const
{
return m_enumerations;
}
QVector<IdlColumnInformation> getIdlColumns(const QString &structName) const
{
return m_idlStructsToGenerate.value(structName).columns;
}
QVector<FunctionTopic> getFunctionTopics() const QStringList getGroupNames() const
{ {
return m_functionTopics; return m_groupNames;
} }
QVector<TopicTypeInformation> getExternalTopicTypes() const
{
return m_externalTopicTypes;
}
QString idlFileForService(const QString &serviceName) const int getPrio() const
{ {
return getIdlFileForService(m_idlFiles, serviceName); return m_prio;
} }
QString xmlFileForService(const QString &serviceName) const QStringList getProcNames() const
{ {
return getIdlFileForService(m_xmlFiles, serviceName); return m_svcProcNames;
} }
QMap<QString, bool> usedServices() const bool hasCustomRecordReplayPlugin() const
{ {
return m_usedServices; return m_customRecordReplay;
} }
QVector<CustomServiceFunctionInformation> getCustomFunctions() const bool getDevMode() const
{ {
return m_customFunctions; return m_svcDevMode;
} }
bool isServiceExerciseIndependent() const
{
return m_exerciseDependency == ExerciseDependency::Global;
}
TopicTypeInformation loadExternalTopicType(const QString &externalServiceName, const QString &topicTypeName); ExerciseDependency defaultExerciseDependency() const
EnumInformation getExternalEnumeration(const QString &externalServiceName, const QString &enumName, bool verbose); {
return m_exerciseDependency;
}
static ExerciseDependency string2ExerciseDependency(const QString &str); QMap<QString, QVector<QString>> getDbClass2TableMapping() const
{
return m_dbClassTables;
}
XmlReader(const XmlReader &) = delete; QMap<QString, QString> getStruct2BaseClassRelations() const
XmlReader &operator=(const XmlReader &) = delete; {
return m_struct2BaseClass;
}
private: QVector<ServiceStructInformation> getStructToGenerate() const
NGL::INGLLogger &m_logger; {
void parseDBSserviceStructs(const QDomElement &rootElement); return m_structsToGenerate;
void parseDBTables(const QDomElement &rootElement); }
void parseDBViews(const QDomElement &rootElement);
void parseEnumerations(const QDomElement &rootElement);
void parseTopicTypes(const QDomElement &rootElement);
void parseFunctionTopics(const QDomElement &rootElement);
void parseCustomDtcFunctions(const QDomElement &rootElement);
static QString getAttribute(const QDomElement &element, QMap<QString, TopicTypeInformation> getIdlStructInformation() const
const QString &attributeName, {
bool bOptional = false); return m_idlStructsToGenerate;
static bool getAttributeBool(const QDomElement &element, }
const QString &attributeName,
bool bOptional, bool defaultValue);
static int getAttributeInt(const QDomElement &element,
const QString &attributeName,
bool bOptional = false, int defaultValue = 0);
ColumnInformation parseTableColumn(const QDomElement &column, const QString &tableName) const; QVector<TopicTypeInformation> getIdlStructToGenerate() const
IdlColumnInformation parseIdlStructColumn(const QDomElement &column) const; {
QVector<TopicTypeInformation> res;
res.reserve(m_idlStructsToGenerate.size());
auto it = m_idlStructsToGenerate.constBegin();
while (it != m_idlStructsToGenerate.constEnd())
{
res.append(it.value());
++it;
}
return res;
}
QSharedPointer<ForeignKeyInformation> parseForeignKey(const QDomElement &foreignKey) const; QMap<QString, QSharedPointer<TableInformation>> getTables() const
ForeignKeyInformation::Endpoint parseForeignKeyEndpoint(const QString &foreignKeyName, {
const QDomElement &endpoint) const; return m_tables;
ConstraintInformation parseConstraint(const QDomElement &constraint) const; }
CustomServiceFunctionInformation parseCustomFunction(const QDomElement &customFunc, CustomServiceFunctionInformation::Type funcType) const;
DbNotifcationInformation parseDbNotification(const QDomElement &customFunc) const;
bool loadExternalService(const QString &serviceName);
void loadIdlInfofile(const QString &idlServiceInfoFile);
QString getIdlFileForService(const QMap<QString, QString> &data, const QString &serviceName) const;
QString serviceNameAbbreviation(const QString &serviceName) const;
void getServiceNameInfoFromFilePath(const QStringList &parts);
static QString serviceNamespaceFromFile(const QString &fn);
QMap<QString, QSharedPointer<ViewInformation>> getViews() const
{
return m_views;
}
QString m_svcNamespace; QSharedPointer<TableInformation> getTable(const QString& table) const
{
return m_tables.value(table);
}
QString m_svcAbbr; QVector<EnumInformation> getEnumerations() const
{
return m_enumerations;
}
QStringList m_svcProcNames; QVector<IdlColumnInformation> getIdlColumns(const QString& structName) const
{
return m_idlStructsToGenerate.value(structName).columns;
}
bool m_customRecordReplay; QVector<FunctionTopic> getFunctionTopics() const
{
return m_functionTopics;
}
QVector<TopicTypeInformation> getExternalTopicTypes() const
{
return m_externalTopicTypes;
}
ExerciseDependency m_exerciseDependency{ExerciseDependency::Exercise}; QString idlFileForService(const QString& serviceName) const
{
return getIdlFileForService(m_idlFiles, serviceName);
}
QString xmlFileForService(const QString& serviceName) const
{
return getIdlFileForService(m_xmlFiles, serviceName);
}
QMap<QString, QVector<QString> > m_dbClassTables; QMap<QString, bool> usedServices() const
{
return m_usedServices;
}
QVector<CustomServiceFunctionInformation> getCustomFunctions() const
{
return m_customFunctions;
}
QMap<QString, QString> m_struct2BaseClass; TopicTypeInformation loadExternalTopicType(const QString& externalServiceName, const QString& topicTypeName);
QVector<ServiceStructInformation> m_structsToGenerate; EnumInformation getExternalEnumeration(const QString& externalServiceName, const QString& enumName, bool verbose);
QMap<QString, TopicTypeInformation> m_idlStructsToGenerate; static ExerciseDependency string2ExerciseDependency(const QString& str);
QVector<FunctionTopic> m_functionTopics; XmlReader(const XmlReader&) = delete;
QVector<TopicTypeInformation> m_externalTopicTypes; XmlReader& operator=(const XmlReader&) = delete;
QVector<CustomServiceFunctionInformation> m_customFunctions;
private:
NGL::INGLLogger& m_logger;
void parseDBSserviceStructs(const QDomElement& rootElement);
void parseDBTables(const QDomElement& rootElement);
void parseDBViews(const QDomElement& rootElement);
void parseEnumerations(const QDomElement& rootElement);
void parseTopicTypes(const QDomElement& rootElement);
void parseFunctionTopics(const QDomElement& rootElement);
void parseCustomDtcFunctions(const QDomElement& rootElement);
QMap<QString, QSharedPointer<TableInformation> > m_tables; static QString getAttribute(const QDomElement& element, const QString& attributeName, bool bOptional = false);
QMap<QString, QSharedPointer<ViewInformation> > m_views; static bool getAttributeBool(const QDomElement& element, const QString& attributeName, bool bOptional,
QVector<EnumInformation> m_enumerations; bool defaultValue);
QString m_errorString; static int getAttributeInt(const QDomElement& element, const QString& attributeName, bool bOptional = false,
int defaultValue = 0);
ColumnInformation parseTableColumn(const QDomElement& column, const QString& tableName) const;
IdlColumnInformation parseIdlStructColumn(const QDomElement& column) const;
QMap<QString, QSharedPointer<XmlReader> > m_externalXmlInformations; QSharedPointer<ForeignKeyInformation> parseForeignKey(const QDomElement& foreignKey) const;
QMap<QString, QString> m_idlFiles; ForeignKeyInformation::Endpoint parseForeignKeyEndpoint(const QString& foreignKeyName,
QMap<QString, QString> m_xmlFiles; const QDomElement& endpoint) const;
QMap<QString, bool> m_usedServices; ConstraintInformation parseConstraint(const QDomElement& constraint) const;
QMap<QString, QString> m_fullServiceName2Abbreviation; CustomServiceFunctionInformation parseCustomFunction(const QDomElement& customFunc,
CustomServiceFunctionInformation::Type funcType) const;
DbNotifcationInformation parseDbNotification(const QDomElement& customFunc) const;
bool loadExternalService(const QString& serviceName);
void loadIdlInfofile(const QString& idlServiceInfoFile);
QString getIdlFileForService(const QMap<QString, QString>& data, const QString& serviceName) const;
QString serviceNameAbbreviation(const QString& serviceName) const;
void getServiceNameInfoFromFilePath(const QStringList& parts);
static QString serviceNamespaceFromFile(const QString& fn);
QStringList m_groupNames; QString m_svcNamespace;
int m_prio;
bool m_svcDevMode{false}; QString m_svcAbbr;
QStringList m_svcProcNames;
bool m_customRecordReplay;
ExerciseDependency m_exerciseDependency{ExerciseDependency::Exercise};
QMap<QString, QVector<QString>> m_dbClassTables;
QMap<QString, QString> m_struct2BaseClass;
QVector<ServiceStructInformation> m_structsToGenerate;
QMap<QString, TopicTypeInformation> m_idlStructsToGenerate;
QVector<FunctionTopic> m_functionTopics;
QVector<TopicTypeInformation> m_externalTopicTypes;
QVector<CustomServiceFunctionInformation> m_customFunctions;
QMap<QString, QSharedPointer<TableInformation>> m_tables;
QMap<QString, QSharedPointer<ViewInformation>> m_views;
QVector<EnumInformation> m_enumerations;
QString m_errorString;
QMap<QString, QSharedPointer<XmlReader>> m_externalXmlInformations;
QMap<QString, QString> m_idlFiles;
QMap<QString, QString> m_xmlFiles;
QMap<QString, bool> m_usedServices;
QMap<QString, QString> m_fullServiceName2Abbreviation;
QStringList m_groupNames;
int m_prio;
bool m_svcDevMode{false};
}; };
} } // namespace CodeGen
+9 -9
View File
@@ -5,13 +5,13 @@
#include <QtCore/qglobal.h> #include <QtCore/qglobal.h>
#ifndef CODEGEN_BASE_EXPORT #ifndef CODEGEN_BASE_EXPORT
# ifdef BUILD_STATIC_LIBRARIES #ifdef BUILD_STATIC_LIBRARIES
# define CODEGEN_BASE_EXPORT #define CODEGEN_BASE_EXPORT
# else #else
# if defined(MAKE_CODEGEN_BASE_LIB) #if defined(MAKE_CODEGEN_BASE_LIB)
# define CODEGEN_BASE_EXPORT Q_DECL_EXPORT #define CODEGEN_BASE_EXPORT Q_DECL_EXPORT
# else #else
# define CODEGEN_BASE_EXPORT Q_DECL_IMPORT #define CODEGEN_BASE_EXPORT Q_DECL_IMPORT
# endif #endif
# endif #endif
#endif #endif
+138 -143
View File
@@ -1,172 +1,167 @@
#include "CppTopicGeneratorGrantlee.h"
#include "StructBuilder.h"
#include "XmlReader.h"
#include "DaoGeneratorGrantlee.h" #include "DaoGeneratorGrantlee.h"
#include "DatabaseGeneratorGrantlee.h" #include "DatabaseGeneratorGrantlee.h"
#include "CppTopicGeneratorGrantlee.h"
#include "SqlGenerator.h" #include "SqlGenerator.h"
#include "StructBuilder.h"
#include "XmlReader.h"
#include <nglapplication/nglcoreapplication.h>
#include <QDir>
#include <NGLLogger/INGLLogger.h>
#include <LtsCommandLineParser/LtsCommandLineParser.h> #include <LtsCommandLineParser/LtsCommandLineParser.h>
#include <NGLLogger/INGLLogger.h>
#include <QDir>
#include <nglapplication/nglcoreapplication.h>
class CmdLineParser : public LtsCommandLineParser::LtsCommandLineParser class CmdLineParser : public LtsCommandLineParser::LtsCommandLineParser
{ {
public: public:
CmdLineParser() CmdLineParser() : LtsCommandLineParser(LtsCommandLineParser::LtsCommandLineParser::None)
: LtsCommandLineParser(LtsCommandLineParser::LtsCommandLineParser::None)
{
addOption({ QStringList() << QStringLiteral("s") << QStringLiteral("servicefile"),
QStringLiteral("full path to the service xml-file"),
QStringLiteral("service xml-file"),
QStringLiteral("/home")
});
addOption({ QStringList() << QStringLiteral("a") << QStringLiteral("action"),
QStringLiteral("the action to execute"),
QStringLiteral("DATABASE|DATABASE_SERVER|IDL|DDS_TOPICS"),
QStringLiteral("/0")
});
addOption({ QStringList() << QStringLiteral("o") << QStringLiteral("outdir"),
QStringLiteral("the output directory where to put the generated files"),
QStringLiteral("output directory"),
QStringLiteral("/home")
});
addOption({ QStringList() << QStringLiteral("i") << QStringLiteral("idlinfo"),
QStringLiteral("the info file with all available idl service files"),
QStringLiteral("info file for idl"),
QStringLiteral("/0")
});
}
bool init()
{
if (!LtsCommandLineParser::init())
return false;
if (serviceFile().isEmpty() || action().isEmpty() || outDir().isEmpty())
{ {
showHelp(); addOption({QStringList() << QStringLiteral("s") << QStringLiteral("servicefile"),
return false; QStringLiteral("full path to the service xml-file"), QStringLiteral("service xml-file"),
} QStringLiteral("/home")});
return true;
}
QString serviceFile() const { return value(QStringLiteral("s")); } addOption({QStringList() << QStringLiteral("a") << QStringLiteral("action"),
QString action() const { return value(QStringLiteral("a")); } QStringLiteral("the action to execute"), QStringLiteral("DATABASE|DATABASE_SERVER|IDL|DDS_TOPICS"),
QString outDir() const { return value(QStringLiteral("o")); } QStringLiteral("/0")});
QString idlInfoFile() const { return value(QStringLiteral("i")); }
addOption({QStringList() << QStringLiteral("o") << QStringLiteral("outdir"),
QStringLiteral("the output directory where to put the generated files"),
QStringLiteral("output directory"), QStringLiteral("/home")});
addOption({QStringList() << QStringLiteral("i") << QStringLiteral("idlinfo"),
QStringLiteral("the info file with all available idl service files"),
QStringLiteral("info file for idl"), QStringLiteral("/0")});
}
bool init()
{
if (!LtsCommandLineParser::init())
return false;
if (serviceFile().isEmpty() || action().isEmpty() || outDir().isEmpty())
{
showHelp();
return false;
}
return true;
}
QString serviceFile() const
{
return value(QStringLiteral("s"));
}
QString action() const
{
return value(QStringLiteral("a"));
}
QString outDir() const
{
return value(QStringLiteral("o"));
}
QString idlInfoFile() const
{
return value(QStringLiteral("i"));
}
}; };
int main(int argc, char **argv) int main(int argc, char** argv)
{ {
NGLCoreApplication app(argc, argv); NGLCoreApplication app(argc, argv);
app.createLogger("CodeGen", "codegen_log4cxx.props", true ); app.createLogger("CodeGen", "codegen_log4cxx.props", true);
NGL::INGLLogger &m_logger = app.baseLogger(); NGL::INGLLogger& m_logger = app.baseLogger();
CmdLineParser options; CmdLineParser options;
if (!options.init()) if (!options.init())
return -1; return -1;
QScopedPointer<CodeGen::XmlReader> reader(new CodeGen::XmlReader); QScopedPointer<CodeGen::XmlReader> reader(new CodeGen::XmlReader);
DEBUG_LOG(m_logger) << "ServiceFile: " << options.serviceFile(); DEBUG_LOG(m_logger) << "ServiceFile: " << options.serviceFile();
DEBUG_LOG(m_logger) << "IdlInfoFile: " << options.idlInfoFile(); DEBUG_LOG(m_logger) << "IdlInfoFile: " << options.idlInfoFile();
if (!reader->readServiceFile(options.serviceFile(), options.idlInfoFile())) if (!reader->readServiceFile(options.serviceFile(), options.idlInfoFile()))
{
ERROR_LOG(m_logger) << "Error parsing service file '" << options.serviceFile()
<< ": " << reader->errorString();
return 2;
}
QDir dir(options.outDir());
DEBUG_LOG(m_logger) << "Directory: " << options.outDir();
if (!dir.exists() && !dir.mkpath(options.outDir()))
{
ERROR_LOG(m_logger) << "Directory '" << options.outDir()
<< "' does not exist and can not be created!";
return 3;
}
QScopedPointer<CodeGen::StructBuilder> structBuilder(new CodeGen::StructBuilder(reader.data()));
if (!structBuilder->buildStructures())
{
ERROR_LOG(m_logger) << "Error building up structures";
return 4;
}
const QString action = options.action().toLower();
QScopedPointer<CodeGen::GeneratorGrantleeBase> generator;
if (action == QStringLiteral("dao"))
generator.reset(new CodeGen::DaoGeneratorGrantlee);
else if (action == QStringLiteral("database"))
generator.reset(new CodeGen::DatabaseGeneratorGrantlee(false));
else if (action == QStringLiteral("database_server"))
generator.reset(new CodeGen::DatabaseGeneratorGrantlee(true));
else if (action == QStringLiteral("dds_topics"))
generator.reset(new CodeGen::CppTopicGeneratorGrantlee);
else if (action == QStringLiteral("sql"))
{
CodeGen::SqlGenerator sql(reader.data(), structBuilder.data());
if (!sql.generateData(35))
return 8;
if (!sql.writeSql(dir.absolutePath() + QLatin1Char('/'), CodeGen::ExerciseDependency::Exercise))
{ {
ERROR_LOG(m_logger) << "Error while writing sql information for service " << sql.getServiceAbbr(); ERROR_LOG(m_logger) << "Error parsing service file '" << options.serviceFile() << ": " << reader->errorString();
return 10; return 2;
} }
if (!sql.generateData(42)) QDir dir(options.outDir());
return 8; DEBUG_LOG(m_logger) << "Directory: " << options.outDir();
if (!dir.exists() && !dir.mkpath(options.outDir()))
if (!sql.writeSql(dir.absolutePath() + QLatin1Char('/'), CodeGen::ExerciseDependency::Exercise))
{ {
ERROR_LOG(m_logger) << "Error while writing sql information for service " << sql.getServiceAbbr(); ERROR_LOG(m_logger) << "Directory '" << options.outDir() << "' does not exist and can not be created!";
return 10; return 3;
} }
QScopedPointer<CodeGen::StructBuilder> structBuilder(new CodeGen::StructBuilder(reader.data()));
sql.generateData(0); if (!structBuilder->buildStructures())
if (!sql.writeSql(dir.absolutePath() + QLatin1Char('/'), CodeGen::ExerciseDependency::Global))
{ {
ERROR_LOG(m_logger) << "Error while writing sql information for service " << sql.getServiceAbbr(); ERROR_LOG(m_logger) << "Error building up structures";
return 10; return 4;
}
const QString action = options.action().toLower();
QScopedPointer<CodeGen::GeneratorGrantleeBase> generator;
if (action == QStringLiteral("dao"))
generator.reset(new CodeGen::DaoGeneratorGrantlee);
else if (action == QStringLiteral("database"))
generator.reset(new CodeGen::DatabaseGeneratorGrantlee(false));
else if (action == QStringLiteral("database_server"))
generator.reset(new CodeGen::DatabaseGeneratorGrantlee(true));
else if (action == QStringLiteral("dds_topics"))
generator.reset(new CodeGen::CppTopicGeneratorGrantlee);
else if (action == QStringLiteral("sql"))
{
CodeGen::SqlGenerator sql(reader.data(), structBuilder.data());
if (!sql.generateData(35))
return 8;
if (!sql.writeSql(dir.absolutePath() + QLatin1Char('/'), CodeGen::ExerciseDependency::Exercise))
{
ERROR_LOG(m_logger) << "Error while writing sql information for service " << sql.getServiceAbbr();
return 10;
}
if (!sql.generateData(42))
return 8;
if (!sql.writeSql(dir.absolutePath() + QLatin1Char('/'), CodeGen::ExerciseDependency::Exercise))
{
ERROR_LOG(m_logger) << "Error while writing sql information for service " << sql.getServiceAbbr();
return 10;
}
sql.generateData(0);
if (!sql.writeSql(dir.absolutePath() + QLatin1Char('/'), CodeGen::ExerciseDependency::Global))
{
ERROR_LOG(m_logger) << "Error while writing sql information for service " << sql.getServiceAbbr();
return 10;
}
return 0;
}
else
{
ERROR_LOG(m_logger) << "Invalid action '" << options.action() << "' given!";
return 5;
}
if (!generator->init(reader.data(), structBuilder.data()))
{
ERROR_LOG(m_logger) << "Error initializing generator!";
return 6;
}
const auto posArgs = options.positionalArguments();
for (const QString& file : posArgs)
{
if (!generator->generateData(file, dir.absolutePath()))
return 7;
} }
return 0; return 0;
}
else
{
ERROR_LOG(m_logger) << "Invalid action '" << options.action() << "' given!";
return 5;
}
if (!generator->init(reader.data(), structBuilder.data()))
{
ERROR_LOG(m_logger) << "Error initializing generator!";
return 6;
}
const auto posArgs = options.positionalArguments();
for (const QString &file : posArgs)
{
if (!generator->generateData(file, dir.absolutePath()))
return 7;
}
return 0;
} }
+99 -109
View File
@@ -1,158 +1,148 @@
#include "main_grantlee_gui.h" #include "main_grantlee_gui.h"
#include "ui_main_grantlee_gui.h"
#include "StructBuilder.h"
#include "XmlReader.h"
#include "CppTopicGeneratorGrantlee.h" #include "CppTopicGeneratorGrantlee.h"
#include "DatabaseGeneratorGrantlee.h" #include "DatabaseGeneratorGrantlee.h"
#include "StructBuilder.h"
#include "XmlReader.h"
#include "ui_main_grantlee_gui.h"
#include <nglapplication/nglapplication.h>
#include <NGLLogger/INGLLogger.h> #include <NGLLogger/INGLLogger.h>
#include <QFileDialog> #include <QFileDialog>
#include <QMessageBox> #include <QMessageBox>
#include <grantlee/engine.h> #include <grantlee/engine.h>
#include <nglapplication/nglapplication.h>
MainWindow::MainWindow(QWidget* parent)
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), m_xmlReader(nullptr), m_structBuilder(nullptr),
: QMainWindow(parent) m_generator(new CodeGen::CppTopicGeneratorGrantlee), m_engine(new Grantlee::Engine), m_ui(new Ui_MainGrantleeGui)
, m_xmlReader(nullptr)
, m_structBuilder(nullptr)
, m_generator(new CodeGen::CppTopicGeneratorGrantlee)
, m_engine(new Grantlee::Engine)
, m_ui(new Ui_MainGrantleeGui)
{ {
m_idlServiceInfoFile = QStringLiteral("/home/chehrlic/TDS/TDS-build-product-clang/service_idl_files.txt"); m_idlServiceInfoFile = QStringLiteral("/home/chehrlic/TDS/TDS-build-product-clang/service_idl_files.txt");
m_ui->setupUi(this); m_ui->setupUi(this);
connect(m_ui->actionExit, &QAction::triggered, connect(m_ui->actionExit, &QAction::triggered, this, &MainWindow::close);
this, &MainWindow::close); connect(m_ui->actionSelect_Data_Source, &QAction::triggered, this, &MainWindow::onSelectDataSource);
connect(m_ui->actionSelect_Data_Source, &QAction::triggered, connect(m_ui->actionOpen_Template, &QAction::triggered, this, &MainWindow::onOpenTemplate);
this, &MainWindow::onSelectDataSource); connect(m_ui->actionSave_Template, &QAction::triggered, this, &MainWindow::onSaveTemplate);
connect(m_ui->actionOpen_Template, &QAction::triggered, connect(m_ui->pbRefresh, &QPushButton::clicked, this, &MainWindow::onRefreshOutput);
this, &MainWindow::onOpenTemplate); connect(m_ui->actionDatabaseGenerator, &QAction::triggered, this, &MainWindow::onGeneratorDb);
connect(m_ui->actionSave_Template, &QAction::triggered, connect(m_ui->actionDDS_Generator, &QAction::triggered, this, &MainWindow::onGeneratorDds);
this, &MainWindow::onSaveTemplate);
connect(m_ui->pbRefresh, &QPushButton::clicked,
this, &MainWindow::onRefreshOutput);
connect(m_ui->actionDatabaseGenerator, &QAction::triggered,
this, &MainWindow::onGeneratorDb);
connect(m_ui->actionDDS_Generator, &QAction::triggered,
this, &MainWindow::onGeneratorDds);
} }
MainWindow::~MainWindow() MainWindow::~MainWindow()
{ {
delete m_xmlReader; delete m_xmlReader;
delete m_structBuilder; delete m_structBuilder;
delete m_generator; delete m_generator;
delete m_engine; delete m_engine;
delete m_ui; delete m_ui;
} }
static QLatin1String s_startDir("/home/chehrlic/TDS/TDS-source-product/Lts/"); static QLatin1String s_startDir("/home/chehrlic/TDS/TDS-source-product/Lts/");
void MainWindow::onSelectDataSource() void MainWindow::onSelectDataSource()
{ {
const QString dataSource = QFileDialog::getOpenFileName(this, tr("Select data source"), s_startDir, tr("Service Files (*.xml)")); const QString dataSource =
if (dataSource.isEmpty()) QFileDialog::getOpenFileName(this, tr("Select data source"), s_startDir, tr("Service Files (*.xml)"));
return; if (dataSource.isEmpty())
delete m_xmlReader; return;
m_xmlReader = new CodeGen::XmlReader; delete m_xmlReader;
if (!m_xmlReader->readServiceFile(dataSource, m_idlServiceInfoFile)) m_xmlReader = new CodeGen::XmlReader;
{ if (!m_xmlReader->readServiceFile(dataSource, m_idlServiceInfoFile))
QMessageBox::warning(this, tr("Invalid data source"), tr("The selected data source is not valid: %1").arg(m_xmlReader->errorString())); {
return; QMessageBox::warning(this, tr("Invalid data source"),
} tr("The selected data source is not valid: %1").arg(m_xmlReader->errorString()));
delete m_structBuilder; return;
m_structBuilder = new CodeGen::StructBuilder(m_xmlReader); }
if (!m_structBuilder->buildStructures()) delete m_structBuilder;
{ m_structBuilder = new CodeGen::StructBuilder(m_xmlReader);
QMessageBox::warning(this, tr("Invalid data source"), tr("Error building structures from data")); if (!m_structBuilder->buildStructures())
return; {
} QMessageBox::warning(this, tr("Invalid data source"), tr("Error building structures from data"));
m_ui->teOuput->clear(); return;
m_generator->init(m_xmlReader, m_structBuilder); }
QMessageBox::information(this, tr("Data source"), tr("Successfully loaded data source")); m_ui->teOuput->clear();
m_generator->init(m_xmlReader, m_structBuilder);
QMessageBox::information(this, tr("Data source"), tr("Successfully loaded data source"));
} }
void MainWindow::onOpenTemplate() void MainWindow::onOpenTemplate()
{ {
const QString templateFile = QFileDialog::getOpenFileName(this, tr("Select data source"), s_startDir, tr("Templates (*.grantlee)")); const QString templateFile =
if (templateFile.isEmpty()) QFileDialog::getOpenFileName(this, tr("Select data source"), s_startDir, tr("Templates (*.grantlee)"));
return; if (templateFile.isEmpty())
QFile f(templateFile); return;
if (!f.open(QIODevice::ReadOnly)) QFile f(templateFile);
{ if (!f.open(QIODevice::ReadOnly))
QMessageBox::warning(this, tr("Error reading template file"), tr("Can not read file: %1").arg(f.errorString())); {
return; QMessageBox::warning(this, tr("Error reading template file"), tr("Can not read file: %1").arg(f.errorString()));
} return;
const QString content = QString::fromUtf8(f.readAll()); }
m_ui->teInput->setText(content); const QString content = QString::fromUtf8(f.readAll());
m_templateFile = templateFile; m_ui->teInput->setText(content);
m_templateFile = templateFile;
} }
void MainWindow::onSaveTemplate() void MainWindow::onSaveTemplate()
{ {
QFile f(m_templateFile); QFile f(m_templateFile);
if (!f.open(QIODevice::WriteOnly)) if (!f.open(QIODevice::WriteOnly))
{ {
QMessageBox::warning(this, tr("Error saving template file"), tr("Can not save file: %1").arg(f.errorString())); QMessageBox::warning(this, tr("Error saving template file"), tr("Can not save file: %1").arg(f.errorString()));
return; return;
} }
f.write(m_ui->teInput->toPlainText().toUtf8()); f.write(m_ui->teInput->toPlainText().toUtf8());
f.close(); f.close();
QMessageBox::information(this, tr("Saving template file"), tr("Successfully saved template to %1").arg(m_templateFile)); QMessageBox::information(this, tr("Saving template file"),
tr("Successfully saved template to %1").arg(m_templateFile));
} }
void MainWindow::onRefreshOutput() void MainWindow::onRefreshOutput()
{ {
const QString in = m_ui->teInput->toPlainText(); const QString in = m_ui->teInput->toPlainText();
if (!m_generator->setTemplate(QString(), in)) if (!m_generator->setTemplate(QString(), in))
{ {
m_ui->teOuput->setText(m_generator->errorString()); m_ui->teOuput->setText(m_generator->errorString());
return; return;
} }
m_ui->teOuput->setText(m_generator->render()); m_ui->teOuput->setText(m_generator->render());
} }
void MainWindow::onGeneratorDb() void MainWindow::onGeneratorDb()
{ {
if (dynamic_cast<CodeGen::DatabaseGeneratorGrantlee *>(m_generator)) if (dynamic_cast<CodeGen::DatabaseGeneratorGrantlee*>(m_generator))
return; return;
delete m_generator; delete m_generator;
m_generator = new CodeGen::DatabaseGeneratorGrantlee(false); m_generator = new CodeGen::DatabaseGeneratorGrantlee(false);
if (m_xmlReader && m_structBuilder) if (m_xmlReader && m_structBuilder)
m_generator->init(m_xmlReader, m_structBuilder); m_generator->init(m_xmlReader, m_structBuilder);
} }
void MainWindow::onGeneratorDds() void MainWindow::onGeneratorDds()
{ {
if (dynamic_cast<CodeGen::CppTopicGeneratorGrantlee *>(m_generator)) if (dynamic_cast<CodeGen::CppTopicGeneratorGrantlee*>(m_generator))
return; return;
delete m_generator; delete m_generator;
m_generator = new CodeGen::CppTopicGeneratorGrantlee; m_generator = new CodeGen::CppTopicGeneratorGrantlee;
if (m_xmlReader && m_structBuilder) if (m_xmlReader && m_structBuilder)
m_generator->init(m_xmlReader, m_structBuilder); m_generator->init(m_xmlReader, m_structBuilder);
} }
int main(int argc, char** argv)
int main(int argc, char **argv)
{ {
NGLApplication app(argc, argv); NGLApplication app(argc, argv);
app.createLogger("CodeGen", "codegen_log4cxx.props"); app.createLogger("CodeGen", "codegen_log4cxx.props");
NGL::INGLLogger &m_logger = app.baseLogger(); NGL::INGLLogger& m_logger = app.baseLogger();
STARTUP_LOG(m_logger); STARTUP_LOG(m_logger);
int iRet = 0; int iRet = 0;
{ {
QScopedPointer<MainWindow> mw(new MainWindow); QScopedPointer<MainWindow> mw(new MainWindow);
mw->show(); mw->show();
iRet = app.exec(); iRet = app.exec();
} }
SHUTDOWN_LOG(m_logger); SHUTDOWN_LOG(m_logger);
return iRet; return iRet;
} }
+24 -22
View File
@@ -1,40 +1,42 @@
#pragma once #pragma once
#include <QObject>
#include <QMainWindow> #include <QMainWindow>
#include <QObject>
namespace CodeGen namespace CodeGen
{ {
class XmlReader; class XmlReader;
class StructBuilder; class StructBuilder;
class GeneratorGrantleeBase; class GeneratorGrantleeBase;
} } // namespace CodeGen
namespace Grantlee namespace Grantlee
{ {
class Engine; class Engine;
} }
class Ui_MainGrantleeGui; class Ui_MainGrantleeGui;
class MainWindow : public QMainWindow class MainWindow : public QMainWindow
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit MainWindow(QWidget *parent = nullptr); explicit MainWindow(QWidget* parent = nullptr);
~MainWindow(); ~MainWindow();
private Q_SLOTS: private Q_SLOTS:
void onSelectDataSource(); void onSelectDataSource();
void onOpenTemplate(); void onOpenTemplate();
void onSaveTemplate(); void onSaveTemplate();
void onRefreshOutput(); void onRefreshOutput();
void onGeneratorDb(); void onGeneratorDb();
void onGeneratorDds(); void onGeneratorDds();
private:
CodeGen::XmlReader *m_xmlReader; private:
CodeGen::StructBuilder *m_structBuilder; CodeGen::XmlReader* m_xmlReader;
CodeGen::GeneratorGrantleeBase *m_generator; CodeGen::StructBuilder* m_structBuilder;
Grantlee::Engine *m_engine; CodeGen::GeneratorGrantleeBase* m_generator;
QString m_idlServiceInfoFile; Grantlee::Engine* m_engine;
QString m_templateFile; QString m_idlServiceInfoFile;
Ui_MainGrantleeGui *m_ui; QString m_templateFile;
Ui_MainGrantleeGui* m_ui;
}; };
@@ -1,16 +1,16 @@
#include <QCoreApplication> #include <QCoreApplication>
#include <QDir>
#include <QDebug> #include <QDebug>
#include <QDir>
#include <grantlee/engine.h> #include <grantlee/engine.h>
#include <grantlee/templateloader.h> #include <grantlee/templateloader.h>
int main(int argc, char **argv) int main(int argc, char** argv)
{ {
QCoreApplication app(argc, argv); QCoreApplication app(argc, argv);
QString templatesDir = QDir::currentPath(); QString templatesDir = QDir::currentPath();
if (argc > 1) { if (argc > 1)
{
templatesDir = QString::fromLocal8Bit(argv[1]); templatesDir = QString::fromLocal8Bit(argv[1]);
} }
@@ -21,7 +21,8 @@ int main(int argc, char **argv)
QDir d(templatesDir); QDir d(templatesDir);
QStringList files = d.entryList(QStringList() << QStringLiteral("*.grantlee"), QDir::Files); QStringList files = d.entryList(QStringList() << QStringLiteral("*.grantlee"), QDir::Files);
if (files.isEmpty()) { if (files.isEmpty())
{
qDebug() << "No .grantlee templates found in" << templatesDir; qDebug() << "No .grantlee templates found in" << templatesDir;
// Treat absence as successful parse (nothing to check) to avoid failing // Treat absence as successful parse (nothing to check) to avoid failing
// when directory is empty in different setups. // when directory is empty in different setups.
@@ -29,21 +30,27 @@ int main(int argc, char **argv)
} }
bool ok = true; bool ok = true;
for (const QString &f : files) { for (const QString& f : files)
{
Grantlee::Template t; Grantlee::Template t;
try { try
{
t = engine.loadByName(f); t = engine.loadByName(f);
} catch (...) { }
catch (...)
{
qDebug() << "Exception while loading" << f; qDebug() << "Exception while loading" << f;
ok = false; ok = false;
continue; continue;
} }
if (!t) { if (!t)
{
qDebug() << "Failed to load template" << f; qDebug() << "Failed to load template" << f;
ok = false; ok = false;
continue; continue;
} }
if (t->error() != Grantlee::NoError) { if (t->error() != Grantlee::NoError)
{
qDebug() << "Parse error in" << f << ":" << t->errorString(); qDebug() << "Parse error in" << f << ":" << t->errorString();
ok = false; ok = false;
continue; continue;
@@ -51,7 +58,8 @@ int main(int argc, char **argv)
// Render with empty context to ensure rendering path also works. // Render with empty context to ensure rendering path also works.
Grantlee::Context ctx; Grantlee::Context ctx;
QString out = t->render(&ctx); QString out = t->render(&ctx);
if (out.isNull()) { if (out.isNull())
{
qDebug() << "Rendering produced null for" << f; qDebug() << "Rendering produced null for" << f;
ok = false; ok = false;
continue; continue;
@@ -1,12 +0,0 @@
#include "mocks/MockCoordTrans.h"
#include <gtest/gtest.h>
TEST(CoordTransGTest, ForwardInverseRoundtrip) {
auto p = MockCoordTrans::forward(1.2345, 2.3456);
EXPECT_NEAR(p.first, 1.2345 * 111000.0, 1e-6);
EXPECT_NEAR(p.second, 2.3456 * 111000.0, 1e-6);
auto inv = MockCoordTrans::inverse(p.first, p.second);
EXPECT_NEAR(inv.first, 1.2345, 1e-9);
EXPECT_NEAR(inv.second, 2.3456, 1e-9);
}
@@ -1,15 +0,0 @@
#include <QtTest/QtTest>
#include "mocks/MockCoordTrans.h"
class CoordTransSmoke : public QObject {
Q_OBJECT
private slots:
void testForward() {
auto p = MockCoordTrans::forward(10.0, 20.0);
QVERIFY(qFuzzyCompare(p.first, 10.0 * 111000.0));
QVERIFY(qFuzzyCompare(p.second, 20.0 * 111000.0));
}
};
QTEST_MAIN(CoordTransSmoke)
#include "coordTransTests_smoke.moc"
@@ -1,16 +0,0 @@
#pragma once
#include <utility>
// Minimal realistic mock for coordinate transforms used during migration.
// Forward conversion returns approximate meters using lat/lon*111000.
class MockCoordTrans {
public:
// approximate forward: (lat, lon) -> (x_m, y_m)
static std::pair<double,double> forward(double lat_deg, double lon_deg) {
return {lat_deg * 111000.0, lon_deg * 111000.0};
}
// approximate inverse
static std::pair<double,double> inverse(double x_m, double y_m) {
return {x_m / 111000.0, y_m / 111000.0};
}
};
+95 -116
View File
@@ -1,139 +1,118 @@
#include <LtsAppDescriptor/lts_app_descriptor.h> #include <LtsAppDescriptor/lts_app_descriptor.h>
#include <utility>
#include <QCoreApplication> #include <QCoreApplication>
#include <QDirIterator>
#include <QFile> #include <QFile>
#include <QFileInfoList> #include <QFileInfoList>
#include <QDirIterator>
#include <QTextStream>
#include <QRegularExpression> #include <QRegularExpression>
#include <QRegularExpressionMatch> #include <QRegularExpressionMatch>
#include <QTextStream>
#include <cstdio> #include <cstdio>
#include <utility>
int main(int argc, char* argv[])
int main(int argc, char *argv[])
{ {
QCoreApplication a(argc, argv); QCoreApplication a(argc, argv);
const QStringList args(a.arguments()); const QStringList args(a.arguments());
if (args.count() != 3) if (args.count() != 3)
{
printf("usage: %s <current source directory> <apps.json>\n", args.at(0).toStdString().c_str());
return -1;
}
const QString currentSrcDir(a.arguments().at(1));
const QString appsJsonFilePath(QStringLiteral("%1/%2").arg(currentSrcDir, a.arguments().at(2)));
QFile f(appsJsonFilePath);
if (!f.open(QFile::ReadOnly))
{
printf("LtsAppDescriptorChecker: cannot open apps.json at %s: %s\n", appsJsonFilePath.toStdString().c_str(), f.errorString().toStdString().c_str());
return -2;
}
printf("LtsAppDescriptorChecker: checking %s\n", appsJsonFilePath.toStdString().c_str());
QStringList lastErrors;
QStringList dummy1;
QString dummy2;
LtsAppDescriptor::AppDescriptionVector adv = LtsAppDescriptor::LtsAppDescriptor::getAppDescriptionVector(f.readAll(), lastErrors, dummy1, dummy2);
if (!lastErrors.isEmpty())
{
printf("LtsAppDescriptorChecker: apps.json at %s invalid:\n%s\n", appsJsonFilePath.toStdString().c_str(), lastErrors.join(QStringLiteral("\r\n\r\n")).toStdString().c_str());
return 1;
}
QFileInfoList guiPluginFiles;
QDirIterator it(QStringLiteral("%1/../../Plugins/").arg(currentSrcDir), QDirIterator::Subdirectories);
while (it.hasNext())
{
QString filename(it.next());
QFileInfo file(filename);
if (file.isDir())
continue;
if (file.fileName().endsWith(QStringLiteral("_gui_plugin.h"), Qt::CaseInsensitive))
guiPluginFiles.append(file);
}
QStringList filenames;
filenames.reserve(guiPluginFiles.size());
for (const QFileInfo &fi : std::as_const(guiPluginFiles))
{
filenames += fi.absoluteFilePath();
}
QStringList guiPluginIIDs;
for (const QFileInfo &fi : std::as_const(guiPluginFiles))
{
QFile f2(fi.absoluteFilePath());
if (!f2.open(QFile::ReadOnly))
continue;
QTextStream ts(&f2);
while (!ts.atEnd())
{ {
QString line(ts.readLine().trimmed().simplified()); printf("usage: %s <current source directory> <apps.json>\n", args.at(0).toStdString().c_str());
static QString iidIdentifier(QStringLiteral("Q_PLUGIN_METADATA")); return -1;
}
if (line.contains(iidIdentifier)) const QString currentSrcDir(a.arguments().at(1));
{
QRegularExpression re(QStringLiteral("(?<=gui:3:).*(?=\"\\))")); const QString appsJsonFilePath(QStringLiteral("%1/%2").arg(currentSrcDir, a.arguments().at(2)));
QRegularExpressionMatch match = re.match(line); QFile f(appsJsonFilePath);
if (match.hasMatch())
if (!f.open(QFile::ReadOnly))
{
printf("LtsAppDescriptorChecker: cannot open apps.json at %s: %s\n", appsJsonFilePath.toStdString().c_str(),
f.errorString().toStdString().c_str());
return -2;
}
printf("LtsAppDescriptorChecker: checking %s\n", appsJsonFilePath.toStdString().c_str());
QStringList lastErrors;
QStringList dummy1;
QString dummy2;
LtsAppDescriptor::AppDescriptionVector adv =
LtsAppDescriptor::LtsAppDescriptor::getAppDescriptionVector(f.readAll(), lastErrors, dummy1, dummy2);
if (!lastErrors.isEmpty())
{
printf("LtsAppDescriptorChecker: apps.json at %s invalid:\n%s\n", appsJsonFilePath.toStdString().c_str(),
lastErrors.join(QStringLiteral("\r\n\r\n")).toStdString().c_str());
return 1;
}
QFileInfoList guiPluginFiles;
QDirIterator it(QStringLiteral("%1/../../Plugins/").arg(currentSrcDir), QDirIterator::Subdirectories);
while (it.hasNext())
{
QString filename(it.next());
QFileInfo file(filename);
if (file.isDir())
continue;
if (file.fileName().endsWith(QStringLiteral("_gui_plugin.h"), Qt::CaseInsensitive))
guiPluginFiles.append(file);
}
QStringList filenames;
filenames.reserve(guiPluginFiles.size());
for (const QFileInfo& fi : std::as_const(guiPluginFiles))
{
filenames += fi.absoluteFilePath();
}
QStringList guiPluginIIDs;
for (const QFileInfo& fi : std::as_const(guiPluginFiles))
{
QFile f2(fi.absoluteFilePath());
if (!f2.open(QFile::ReadOnly))
continue;
QTextStream ts(&f2);
while (!ts.atEnd())
{ {
QString matched = match.captured(0); QString line(ts.readLine().trimmed().simplified());
static QString iidIdentifier(QStringLiteral("Q_PLUGIN_METADATA"));
guiPluginIIDs += matched; if (line.contains(iidIdentifier))
{
QRegularExpression re(QStringLiteral("(?<=gui:3:).*(?=\"\\))"));
QRegularExpressionMatch match = re.match(line);
if (match.hasMatch())
{
QString matched = match.captured(0);
guiPluginIIDs += matched;
}
break;
}
} }
break;
}
} }
}
bool ok = true;
for (const LtsAppDescriptor::AppDescription& appdesc : std::as_const(adv))
bool ok = true;
for (const LtsAppDescriptor::AppDescription &appdesc : std::as_const(adv))
{
for (const LtsAppDescriptor::PluginInfo &pi : std::as_const(appdesc.pluginInfos))
{ {
if (!guiPluginIIDs.contains(pi.iid)) for (const LtsAppDescriptor::PluginInfo& pi : std::as_const(appdesc.pluginInfos))
{ {
printf("LtsAppDescriptorChecker: apps.json at '%s' uses unknown IID '%s'\n", appsJsonFilePath.toStdString().c_str(), pi.iid.toStdString().c_str()); if (!guiPluginIIDs.contains(pi.iid))
ok = false; {
} printf("LtsAppDescriptorChecker: apps.json at '%s' uses unknown IID '%s'\n",
appsJsonFilePath.toStdString().c_str(), pi.iid.toStdString().c_str());
ok = false;
}
}
} }
}
return !ok;
return !ok;
} }
+148 -157
View File
@@ -1,215 +1,206 @@
#include "lts_app_descriptor.h" #include "lts_app_descriptor.h"
#include <QJsonDocument> #include <QCoreApplication>
#include <QJsonArray> #include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject> #include <QJsonObject>
#include <QJsonParseError> #include <QJsonParseError>
#include <QJsonValue> #include <QJsonValue>
#include <QCoreApplication>
namespace LtsAppDescriptor namespace LtsAppDescriptor
{ {
static void addOptionToPlugin(PluginInfo &pluginInfo, const PluginInfo::Flag &flag) static void addOptionToPlugin(PluginInfo& pluginInfo, const PluginInfo::Flag& flag)
{ {
pluginInfo.flags |= flag; pluginInfo.flags |= flag;
} }
static void addOptionToPlugin(QVector<PluginInfo>& pluginInfos, const PluginInfo::Flag& flag, const QString& pluginName)
static void addOptionToPlugin(QVector<PluginInfo> &pluginInfos, const PluginInfo::Flag &flag, const QString &pluginName)
{ {
for (PluginInfo &pi : pluginInfos) for (PluginInfo& pi : pluginInfos)
{
if (pi.iid == pluginName)
{ {
addOptionToPlugin(pi, flag); if (pi.iid == pluginName)
return; {
addOptionToPlugin(pi, flag);
return;
}
} }
}
PluginInfo pi; PluginInfo pi;
pi.iid = pluginName; pi.iid = pluginName;
pi.type = PluginInfo::PluginType::GUI; pi.type = PluginInfo::PluginType::GUI;
addOptionToPlugin(pi, flag); addOptionToPlugin(pi, flag);
pluginInfos.append(pi); pluginInfos.append(pi);
} }
static bool addOptionsToPlugin(AppDescription& appDesc, const QString& optionIdentifier,
static bool addOptionsToPlugin(AppDescription &appDesc, const QString &optionIdentifier, const QStringList &ignoredPlugins, const QStringList& ignoredPlugins, const QJsonObject& optionsObject,
const QJsonObject &optionsObject, const PluginInfo::Flag flag, QStringList &lastErrors, const PluginInfo::Flag flag, QStringList& lastErrors, bool atLeastOnePluginNeeded)
bool atLeastOnePluginNeeded)
{ {
bool hasPlugins = false; bool hasPlugins = false;
auto optionsObjectIt = optionsObject.constFind(optionIdentifier); auto optionsObjectIt = optionsObject.constFind(optionIdentifier);
if (optionsObjectIt != optionsObject.constEnd()) if (optionsObjectIt != optionsObject.constEnd())
{
const QJsonArray plugins((*optionsObjectIt).toObject()[QStringLiteral("Plugins")].toArray());
for (const auto &pluginElem : plugins)
{ {
const QString pluginName = pluginElem.toString(); const QJsonArray plugins((*optionsObjectIt).toObject()[QStringLiteral("Plugins")].toArray());
if (!ignoredPlugins.contains(pluginName))
{ for (const auto& pluginElem : plugins)
addOptionToPlugin(appDesc.pluginInfos, flag, pluginName); {
hasPlugins = true; const QString pluginName = pluginElem.toString();
} if (!ignoredPlugins.contains(pluginName))
{
addOptionToPlugin(appDesc.pluginInfos, flag, pluginName);
hasPlugins = true;
}
}
} }
}
if (atLeastOnePluginNeeded && !hasPlugins) if (atLeastOnePluginNeeded && !hasPlugins)
{ {
lastErrors.append(QCoreApplication::tr("No plugins specified for '%1' option for app '%2'").arg(optionIdentifier, appDesc.appName)); lastErrors.append(QCoreApplication::tr("No plugins specified for '%1' option for app '%2'")
return false; .arg(optionIdentifier, appDesc.appName));
} return false;
}
return true; return true;
} }
App LtsAppDescriptor::appFromInteger(int i) App LtsAppDescriptor::appFromInteger(int i)
{ {
switch (i) switch (i)
{ {
case int(App::Login): case int(App::Login):
case int(App::Situation): case int(App::Situation):
case int(App::ResourceManager): case int(App::ResourceManager):
case int(App::PlanEditor): case int(App::PlanEditor):
case int(App::BuildingViewer): case int(App::BuildingViewer):
case int(App::OC): case int(App::OC):
case int(App::OrgChart): case int(App::OrgChart):
case int(App::Scripts): case int(App::Scripts):
case int(App::Snapshot): case int(App::Snapshot):
case int(App::SystemMonitor): case int(App::SystemMonitor):
case int(App::Timeline): case int(App::Timeline):
case int(App::SymbolEditor): case int(App::SymbolEditor):
case int(App::ScriptEditorEssentialsView): case int(App::ScriptEditorEssentialsView):
case int(App::BaseDownloader): case int(App::BaseDownloader):
case int(App::OnlineHelp): case int(App::OnlineHelp):
case int(App::ThpSituationReplay): case int(App::ThpSituationReplay):
case int(App::SituationTablet): case int(App::SituationTablet):
case int(App::SilhouetteEditor): case int(App::SilhouetteEditor):
case int(App::Shootback): case int(App::Shootback):
case int(App::SAAs): case int(App::SAAs):
return static_cast<App>(i); return static_cast<App>(i);
} }
Q_ASSERT_X(false, "LtsAppDescriptor::appFromInteger", qPrintable(QStringLiteral("Unknown app id: %1").arg(i))); Q_ASSERT_X(false, "LtsAppDescriptor::appFromInteger", qPrintable(QStringLiteral("Unknown app id: %1").arg(i)));
return App::Login; return App::Login;
} }
AppDescriptionVector LtsAppDescriptor::getAppDescriptionVector(const QByteArray &jsonDocument, AppDescriptionVector LtsAppDescriptor::getAppDescriptionVector(const QByteArray& jsonDocument, QStringList& lastErrors,
QStringList &lastErrors, const QStringList& ignoredPlugins,
const QStringList &ignoredPlugins, QString& loginPluginIid)
QString &loginPluginIid)
{ {
AppDescriptionVector appDescriptions;
AppDescriptionVector appDescriptions; QJsonParseError parseError;
QJsonDocument appsDoc(QJsonDocument::fromJson(jsonDocument, &parseError));
QJsonParseError parseError; if (parseError.error != QJsonParseError::NoError)
QJsonDocument appsDoc(QJsonDocument::fromJson(jsonDocument, &parseError));
if (parseError.error != QJsonParseError::NoError)
{
int row = 0;
int column = 0;
QChar x = QLatin1Char('\n');
for (int i = 0; i < jsonDocument.count(); i++)
{ {
if (i == parseError.offset)
break;
if (QChar::fromLatin1(jsonDocument[i]) == x) int row = 0;
{ int column = 0;
row++; QChar x = QLatin1Char('\n');
column = 0;
}
else
{
column++;
}
}
for (int i = 0; i < jsonDocument.count(); i++)
{
if (i == parseError.offset)
break;
lastErrors.append(QCoreApplication::tr("JSON: %1<br>Row: %2, Column: %3").arg(parseError.errorString()).arg(row+1).arg(column+1)); if (QChar::fromLatin1(jsonDocument[i]) == x)
return appDescriptions; {
} row++;
column = 0;
}
else
{
column++;
}
}
const QJsonObject root(appsDoc.object()); lastErrors.append(QCoreApplication::tr("JSON: %1<br>Row: %2, Column: %3")
.arg(parseError.errorString())
loginPluginIid = root[QStringLiteral("LoginPlugin")].toString(); .arg(row + 1)
.arg(column + 1));
const QJsonArray appArray(root[QStringLiteral("Apps")].toArray());
if (appArray.isEmpty())
{
lastErrors.append(QCoreApplication::tr("Invalid json: Could not find 'Apps' array"));
return appDescriptions;
}
for (const auto &appElem : appArray)
{
AppDescription appDesc;
const QJsonObject appObject = appElem.toObject();
appDesc.id = appFromInteger(appObject.value(QStringLiteral("Id")).toInt(-1));
if (appDesc.id == App::Login)
{
lastErrors.append(QCoreApplication::tr("App '%1': no App Id or invalid App Id given").arg(appDesc.appName));
return appDescriptions;
}
appDesc.appName = appObject.value(QStringLiteral("AppName")).toString();
const QJsonValue valueActive = appObject.value(QStringLiteral("Active"));
if (!valueActive.isUndefined())
{
if (valueActive.type() != QJsonValue::Type::Bool)
{
lastErrors.append(QCoreApplication::tr("App '%1': value App.Active is not a bool (%2)").arg(appDesc.appName).arg((int)valueActive.type()));
return appDescriptions; return appDescriptions;
}
} }
appDesc.active = valueActive.toBool(false);
const QJsonValue valueVisible = appObject.value(QStringLiteral("Visible")); const QJsonObject root(appsDoc.object());
if (!valueVisible.isUndefined() && valueVisible.type() != QJsonValue::Type::Bool)
loginPluginIid = root[QStringLiteral("LoginPlugin")].toString();
const QJsonArray appArray(root[QStringLiteral("Apps")].toArray());
if (appArray.isEmpty())
{ {
lastErrors.append(QCoreApplication::tr("App '%1': value App.Visible is not a bool (%2)").arg(appDesc.appName).arg((int)valueVisible.type())); lastErrors.append(QCoreApplication::tr("Invalid json: Could not find 'Apps' array"));
return appDescriptions; return appDescriptions;
} }
appDesc.visible = valueVisible.toBool(true);
const QJsonArray array(appObject.value(QStringLiteral("ACLs")).toArray()); for (const auto& appElem : appArray)
for (const QJsonValue &value : array) {
appDesc.requiredAcls.append(value.toInt()); AppDescription appDesc;
const QJsonObject appObject = appElem.toObject();
appDesc.id = appFromInteger(appObject.value(QStringLiteral("Id")).toInt(-1));
if (appDesc.id == App::Login)
{
lastErrors.append(QCoreApplication::tr("App '%1': no App Id or invalid App Id given").arg(appDesc.appName));
return appDescriptions;
}
appDesc.appName = appObject.value(QStringLiteral("AppName")).toString();
const QJsonObject optionsObject(appObject.value(QStringLiteral("Options")).toObject()); const QJsonValue valueActive = appObject.value(QStringLiteral("Active"));
if (!valueActive.isUndefined())
{
if (valueActive.type() != QJsonValue::Type::Bool)
{
lastErrors.append(QCoreApplication::tr("App '%1': value App.Active is not a bool (%2)")
.arg(appDesc.appName)
.arg((int)valueActive.type()));
return appDescriptions;
}
}
appDesc.active = valueActive.toBool(false);
addOptionsToPlugin(appDesc, QStringLiteral("Payloads"), ignoredPlugins, optionsObject, PluginInfo::Flag::PAYLOAD, lastErrors, false); const QJsonValue valueVisible = appObject.value(QStringLiteral("Visible"));
addOptionsToPlugin(appDesc, QStringLiteral("Actions"), ignoredPlugins, optionsObject, PluginInfo::Flag::ACTIONS, lastErrors, true ); if (!valueVisible.isUndefined() && valueVisible.type() != QJsonValue::Type::Bool)
addOptionsToPlugin(appDesc, QStringLiteral("Main"), ignoredPlugins, optionsObject, PluginInfo::Flag::MAIN, lastErrors, false); {
lastErrors.append(QCoreApplication::tr("App '%1': value App.Visible is not a bool (%2)")
.arg(appDesc.appName)
.arg((int)valueVisible.type()));
return appDescriptions;
}
appDesc.visible = valueVisible.toBool(true);
const QJsonArray array(appObject.value(QStringLiteral("ACLs")).toArray());
for (const QJsonValue& value : array)
appDesc.requiredAcls.append(value.toInt());
appDescriptions.append(appDesc); const QJsonObject optionsObject(appObject.value(QStringLiteral("Options")).toObject());
} addOptionsToPlugin(appDesc, QStringLiteral("Payloads"), ignoredPlugins, optionsObject,
PluginInfo::Flag::PAYLOAD, lastErrors, false);
addOptionsToPlugin(appDesc, QStringLiteral("Actions"), ignoredPlugins, optionsObject, PluginInfo::Flag::ACTIONS,
lastErrors, true);
addOptionsToPlugin(appDesc, QStringLiteral("Main"), ignoredPlugins, optionsObject, PluginInfo::Flag::MAIN,
lastErrors, false);
appDescriptions.append(appDesc);
}
return appDescriptions;
return appDescriptions;
} }
} } // namespace LtsAppDescriptor
+63 -64
View File
@@ -1,96 +1,95 @@
#pragma once #pragma once
#include <QVector>
#include <QStringList> #include <QStringList>
#include <QVector>
#ifndef LTSAPPDESCRIPTOR_EXPORT #ifndef LTSAPPDESCRIPTOR_EXPORT
# ifdef BUILD_STATIC_LIBRARIES #ifdef BUILD_STATIC_LIBRARIES
# define LTSAPPDESCRIPTOR_EXPORT #define LTSAPPDESCRIPTOR_EXPORT
# else #else
# if defined(MAKE_LTSAPPDESCRIPTOR_LIB) #if defined(MAKE_LTSAPPDESCRIPTOR_LIB)
# define LTSAPPDESCRIPTOR_EXPORT Q_DECL_EXPORT #define LTSAPPDESCRIPTOR_EXPORT Q_DECL_EXPORT
# else #else
# define LTSAPPDESCRIPTOR_EXPORT Q_DECL_IMPORT #define LTSAPPDESCRIPTOR_EXPORT Q_DECL_IMPORT
# endif #endif
# endif #endif
#endif #endif
namespace LtsAppDescriptor namespace LtsAppDescriptor
{ {
enum class App enum class App {
{ Login = -1,
Login = -1, Situation = 0,
Situation = 0, ResourceManager = 1,
ResourceManager = 1, PlanEditor = 2,
PlanEditor = 2, BuildingViewer = 3,
BuildingViewer = 3, OC = 4,
OC = 4, OrgChart = 5,
OrgChart = 5, Scripts = 6,
Scripts = 6,
Snapshot = 8, Snapshot = 8,
SystemMonitor = 9, SystemMonitor = 9,
Timeline = 10, Timeline = 10,
SymbolEditor = 11, SymbolEditor = 11,
ScriptEditorEssentialsView = 12, ScriptEditorEssentialsView = 12,
BaseDownloader = 13, BaseDownloader = 13,
OnlineHelp = 14, OnlineHelp = 14,
ThpSituationReplay = 15, ThpSituationReplay = 15,
SituationTablet = 17, SituationTablet = 17,
SilhouetteEditor = 18, SilhouetteEditor = 18,
Shootback = 19, Shootback = 19,
SAAs = 20, SAAs = 20,
}; };
struct PluginInfo struct PluginInfo
{ {
enum class PluginType enum class PluginType {
{ UNKNOWN,
UNKNOWN, DATA,
DATA, GUI,
GUI, };
};
enum class Flag enum class Flag {
{ UNKNOWN = 1 << 0,
UNKNOWN = 1 << 0, ACTIONS = 1 << 1,
ACTIONS = 1 << 1, MAIN = 1 << 2,
MAIN = 1 << 2, PAYLOAD = 1 << 3,
PAYLOAD = 1 << 3, OPTION = 1 << 4,
OPTION = 1 << 4, };
};
PluginType type = PluginType::UNKNOWN; PluginType type = PluginType::UNKNOWN;
QString iid; QString iid;
QFlags<Flag> flags; QFlags<Flag> flags;
QStringList options; QStringList options;
}; };
struct AppDescription struct AppDescription
{ {
App id = App::Login; App id = App::Login;
bool active = false; bool active = false;
bool visible = true; bool visible = true;
QString appName; QString appName;
QVector<int> requiredAcls; QVector<int> requiredAcls;
QVector<PluginInfo> pluginInfos; QVector<PluginInfo> pluginInfos;
bool isValid() const { return !appName.isEmpty(); } bool isValid() const
{
return !appName.isEmpty();
}
}; };
typedef QVector<AppDescription> AppDescriptionVector; typedef QVector<AppDescription> AppDescriptionVector;
namespace LtsAppDescriptor namespace LtsAppDescriptor
{ {
LTSAPPDESCRIPTOR_EXPORT App appFromInteger(int i); LTSAPPDESCRIPTOR_EXPORT App appFromInteger(int i);
LTSAPPDESCRIPTOR_EXPORT AppDescriptionVector getAppDescriptionVector(const QByteArray &jsonDocument, QStringList &lastErrors, LTSAPPDESCRIPTOR_EXPORT AppDescriptionVector getAppDescriptionVector(const QByteArray& jsonDocument,
const QStringList &ignoredPlugins, QString &loginPluginIid); QStringList& lastErrors,
} const QStringList& ignoredPlugins,
QString& loginPluginIid);
} // namespace LtsAppDescriptor
} } // namespace LtsAppDescriptor
@@ -1,554 +1,533 @@
#include "lts_app_descriptor_editor.h" #include "lts_app_descriptor_editor.h"
#include "ui_lts_app_descriptor_editor.h" #include "ui_lts_app_descriptor_editor.h"
#include <QDebug>
#include <QFile> #include <QFile>
#include <QJsonDocument>
#include <QStringListModel>
#include <QFileDialog> #include <QFileDialog>
#include <QJsonDocument>
#include <QMessageBox> #include <QMessageBox>
#include <QStringListModel>
#include <QTimer> #include <QTimer>
#include <QDebug> LtsAppDescriptorEditor::LtsAppDescriptorEditor(QWidget* parent) : QWidget(parent), m_ui(new Ui_LtsAppDescriptionEditor)
LtsAppDescriptorEditor::LtsAppDescriptorEditor(QWidget *parent)
: QWidget(parent)
, m_ui(new Ui_LtsAppDescriptionEditor)
{ {
m_ui->setupUi(this); m_ui->setupUi(this);
m_vector = LtsAppDescriptor::AppDescriptionVector(); m_vector = LtsAppDescriptor::AppDescriptionVector();
m_appIndex = QModelIndex(); m_appIndex = QModelIndex();
m_pluginIndex = QModelIndex(); m_pluginIndex = QModelIndex();
m_fileName = QString(); m_fileName = QString();
m_changed = false; m_changed = false;
connect(m_ui->lvApps, SIGNAL(clicked(QModelIndex)), this, SLOT(onAppsClicked(QModelIndex))); connect(m_ui->lvApps, SIGNAL(clicked(QModelIndex)), this, SLOT(onAppsClicked(QModelIndex)));
connect(m_ui->lvPlugins, SIGNAL(clicked(QModelIndex)), this, SLOT(onPluginsClicked(QModelIndex))); connect(m_ui->lvPlugins, SIGNAL(clicked(QModelIndex)), this, SLOT(onPluginsClicked(QModelIndex)));
connect(m_ui->lePluginType, SIGNAL(editingFinished()), this, SLOT(pluginTypeChanged())); connect(m_ui->lePluginType, SIGNAL(editingFinished()), this, SLOT(pluginTypeChanged()));
connect(m_ui->pbAddApp, SIGNAL(pressed()), this, SLOT(onAppAddClicked())); connect(m_ui->pbAddApp, SIGNAL(pressed()), this, SLOT(onAppAddClicked()));
connect(m_ui->pbAddPlugin, SIGNAL(pressed()), this, SLOT(onPluginAddClicked())); connect(m_ui->pbAddPlugin, SIGNAL(pressed()), this, SLOT(onPluginAddClicked()));
connect(m_ui->pbDeleteApp, SIGNAL(pressed()), this, SLOT(onAppDeleteClicked())); connect(m_ui->pbDeleteApp, SIGNAL(pressed()), this, SLOT(onAppDeleteClicked()));
connect(m_ui->pbDeletePlugin, SIGNAL(pressed()), this, SLOT(onPluginDeletedClicked())); connect(m_ui->pbDeletePlugin, SIGNAL(pressed()), this, SLOT(onPluginDeletedClicked()));
connect(m_ui->pbUpdate, SIGNAL(pressed()), this, SLOT(onUpdateClicked())); connect(m_ui->pbUpdate, SIGNAL(pressed()), this, SLOT(onUpdateClicked()));
connect(m_ui->pbNewPlugin, SIGNAL(pressed()), this, SLOT(onNewpluginClicked())); connect(m_ui->pbNewPlugin, SIGNAL(pressed()), this, SLOT(onNewpluginClicked()));
connect(m_ui->pbNewApp, SIGNAL(pressed()), this, SLOT(onNewAppClicked())); connect(m_ui->pbNewApp, SIGNAL(pressed()), this, SLOT(onNewAppClicked()));
connect(m_ui->lePluginName, SIGNAL(textChanged(QString)), this, SLOT(enableNewPlugin())); connect(m_ui->lePluginName, SIGNAL(textChanged(QString)), this, SLOT(enableNewPlugin()));
connect(m_ui->lePluginType, SIGNAL(textChanged(QString)), this, SLOT(enableNewPlugin())); connect(m_ui->lePluginType, SIGNAL(textChanged(QString)), this, SLOT(enableNewPlugin()));
m_ui->gbPlugins->setEnabled(false); m_ui->gbPlugins->setEnabled(false);
m_ui->pbDeletePlugin->setEnabled(false); m_ui->pbDeletePlugin->setEnabled(false);
m_ui->pbDeleteApp->setEnabled(false); m_ui->pbDeleteApp->setEnabled(false);
m_ui->pbAddPlugin->setEnabled(false); m_ui->pbAddPlugin->setEnabled(false);
m_ui->pbUpdate->setEnabled(false); m_ui->pbUpdate->setEnabled(false);
m_ui->pbNewPlugin->setEnabled(false); m_ui->pbNewPlugin->setEnabled(false);
m_ui->pbNewApp->setEnabled(false); m_ui->pbNewApp->setEnabled(false);
QTimer::singleShot(0, this, &LtsAppDescriptorEditor::getAppDescriptionVector); QTimer::singleShot(0, this, &LtsAppDescriptorEditor::getAppDescriptionVector);
} }
LtsAppDescriptorEditor::~LtsAppDescriptorEditor() LtsAppDescriptorEditor::~LtsAppDescriptorEditor()
{ {
checkSave(); checkSave();
delete m_ui; delete m_ui;
} }
void LtsAppDescriptorEditor::getAppDescriptionVector() void LtsAppDescriptorEditor::getAppDescriptionVector()
{ {
m_fileName = QFileDialog::getOpenFileName(this, tr("Open JSON"), QLatin1Literal("/shd/CTC/TOOLS/TDS/TDS-source/Lts/Projects/Legatus/resources/"), m_fileName = QFileDialog::getOpenFileName(
tr("JSON File (*.json)")); this, tr("Open JSON"), QLatin1Literal("/shd/CTC/TOOLS/TDS/TDS-source/Lts/Projects/Legatus/resources/"),
if (m_fileName.isEmpty()) tr("JSON File (*.json)"));
return; if (m_fileName.isEmpty())
return;
QFile file; QFile file;
file.setFileName(m_fileName); file.setFileName(m_fileName);
file.open(QIODevice::ReadOnly | QIODevice::Text); file.open(QIODevice::ReadOnly | QIODevice::Text);
QString val(QString::fromUtf8(file.readAll())); QString val(QString::fromUtf8(file.readAll()));
file.close(); file.close();
QStringList errors; QStringList errors;
m_vector = LtsAppDescriptor::LtsAppDescriptor::getAppDescriptionVector(val.toUtf8(), errors); m_vector = LtsAppDescriptor::LtsAppDescriptor::getAppDescriptionVector(val.toUtf8(), errors);
updateAppModel(); updateAppModel();
} }
void LtsAppDescriptorEditor::onAppsClicked(const QModelIndex &index) void LtsAppDescriptorEditor::onAppsClicked(const QModelIndex& index)
{ {
m_ui->gbPlugins->setEnabled(true); m_ui->gbPlugins->setEnabled(true);
m_ui->pbDeleteApp->setEnabled(true); m_ui->pbDeleteApp->setEnabled(true);
m_ui->pbAddPlugin->setEnabled(true); m_ui->pbAddPlugin->setEnabled(true);
m_ui->pbNewApp->setEnabled(true); m_ui->pbNewApp->setEnabled(true);
m_appIndex = index; m_appIndex = index;
QStringList pluginList; QStringList pluginList;
Q_FOREACH(const LtsAppDescriptor::PluginInfo &reqPlugin, m_vector.at(m_appIndex.row()).requiredPlugins) Q_FOREACH (const LtsAppDescriptor::PluginInfo& reqPlugin, m_vector.at(m_appIndex.row()).requiredPlugins)
{ {
LtsAppDescriptor::PluginInfo::PluginType pluginType = reqPlugin.type; LtsAppDescriptor::PluginInfo::PluginType pluginType = reqPlugin.type;
QString type;
if (pluginType == LtsAppDescriptor::PluginInfo::PluginType::DATA)
type = QLatin1String("data");
else if (pluginType == LtsAppDescriptor::PluginInfo::PluginType::GUI)
type = QLatin1String("gui");
else
type = QLatin1String("unknown");
if (type == QLatin1String("data"))
pluginList << QString(type + QLatin1String(": ") + reqPlugin.iid);
else
{
QString strFlags;
QFlags<LtsAppDescriptor::PluginInfo::Flag> flags = reqPlugin.flags;
bool actionsFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::ACTIONS);
if (actionsFlag)
strFlags.append(QLatin1String("actions "));
bool mainFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::MAIN);
if (mainFlag)
strFlags.append(QLatin1String("main "));
bool payloadFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::PAYLOAD);
if (payloadFlag)
strFlags.append(QLatin1String("payload "));
bool optionalFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::OPTION);
if (optionalFlag)
strFlags.append(QLatin1String("optional "));
pluginList << QString(type + QLatin1String(": ") + reqPlugin.iid + QLatin1String(" [ ") + strFlags +
QLatin1String("]"));
}
}
updatePluginModel(pluginList);
m_ui->chbAppActive->setChecked(m_vector.at(m_appIndex.row()).active);
m_ui->leAppName->setText(m_vector.at(m_appIndex.row()).appName);
}
void LtsAppDescriptorEditor::onPluginsClicked(const QModelIndex& index)
{
m_pluginIndex = index;
m_ui->pbDeletePlugin->setEnabled(true);
m_ui->pbUpdate->setEnabled(true);
m_ui->pbNewPlugin->setEnabled(true);
const LtsAppDescriptor::PluginInfo plugin = m_vector.at(m_appIndex.row()).requiredPlugins.at(m_pluginIndex.row());
QString pluginName = plugin.iid;
m_ui->lePluginName->setText(pluginName);
LtsAppDescriptor::PluginInfo::PluginType pluginType = plugin.type;
QString type; QString type;
if (pluginType == LtsAppDescriptor::PluginInfo::PluginType::DATA) if (pluginType == LtsAppDescriptor::PluginInfo::PluginType::DATA)
type = QLatin1String("data"); type = QLatin1String("data");
else if(pluginType == LtsAppDescriptor::PluginInfo::PluginType::GUI) else if (pluginType == LtsAppDescriptor::PluginInfo::PluginType::GUI)
type = QLatin1String("gui"); type = QLatin1String("gui");
else else
type = QLatin1String("unknown"); type = QLatin1String("unknown");
m_ui->lePluginType->setText(type);
if(type == QLatin1String("data")) if (type == QLatin1String("gui"))
pluginList << QString(type + QLatin1String(": ") +reqPlugin.iid); {
m_ui->chbActions->setEnabled(true);
m_ui->chbMain->setEnabled(true);
m_ui->chbPayload->setEnabled(true);
QFlags<LtsAppDescriptor::PluginInfo::Flag> flags = plugin.flags;
bool actionsFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::ACTIONS);
m_ui->chbActions->setChecked(actionsFlag);
bool mainFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::MAIN);
m_ui->chbMain->setChecked(mainFlag);
bool payloadFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::PAYLOAD);
m_ui->chbPayload->setChecked(payloadFlag);
}
else else
{ {
QString strFlags; m_ui->chbActions->setChecked(false);
QFlags<LtsAppDescriptor::PluginInfo::Flag> flags = reqPlugin.flags; m_ui->chbActions->setEnabled(false);
m_ui->chbMain->setChecked(false);
bool actionsFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::ACTIONS); m_ui->chbMain->setEnabled(false);
if(actionsFlag) m_ui->chbPayload->setChecked(false);
strFlags.append(QLatin1String("actions ")); m_ui->chbPayload->setEnabled(false);
bool mainFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::MAIN);
if(mainFlag)
strFlags.append(QLatin1String("main "));
bool payloadFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::PAYLOAD);
if(payloadFlag)
strFlags.append(QLatin1String("payload "));
bool optionalFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::OPTION);
if(optionalFlag)
strFlags.append(QLatin1String("optional "));
pluginList << QString(type + QLatin1String(": ") + reqPlugin.iid + QLatin1String(" [ ") + strFlags + QLatin1String("]"));
} }
}
updatePluginModel(pluginList);
m_ui->chbAppActive->setChecked(m_vector.at(m_appIndex.row()).active);
m_ui->leAppName->setText(m_vector.at(m_appIndex.row()).appName);
}
void LtsAppDescriptorEditor::onPluginsClicked(const QModelIndex &index)
{
m_pluginIndex = index;
m_ui->pbDeletePlugin->setEnabled(true);
m_ui->pbUpdate->setEnabled(true);
m_ui->pbNewPlugin->setEnabled(true);
const LtsAppDescriptor::PluginInfo plugin = m_vector.at(m_appIndex.row()).requiredPlugins.at(m_pluginIndex.row());
QString pluginName = plugin.iid;
m_ui->lePluginName->setText(pluginName);
LtsAppDescriptor::PluginInfo::PluginType pluginType = plugin.type;
QString type;
if (pluginType == LtsAppDescriptor::PluginInfo::PluginType::DATA)
type = QLatin1String("data");
else if(pluginType == LtsAppDescriptor::PluginInfo::PluginType::GUI)
type = QLatin1String("gui");
else
type = QLatin1String("unknown");
m_ui->lePluginType->setText(type);
if(type == QLatin1String("gui"))
{
m_ui->chbActions->setEnabled(true);
m_ui->chbMain->setEnabled(true);
m_ui->chbPayload->setEnabled(true);
QFlags<LtsAppDescriptor::PluginInfo::Flag> flags = plugin.flags;
bool actionsFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::ACTIONS);
m_ui->chbActions->setChecked(actionsFlag);
bool mainFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::MAIN);
m_ui->chbMain->setChecked(mainFlag);
bool payloadFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::PAYLOAD);
m_ui->chbPayload->setChecked(payloadFlag);
}
else
{
m_ui->chbActions->setChecked(false);
m_ui->chbActions->setEnabled(false);
m_ui->chbMain->setChecked(false);
m_ui->chbMain->setEnabled(false);
m_ui->chbPayload->setChecked(false);
m_ui->chbPayload->setEnabled(false);
}
} }
void LtsAppDescriptorEditor::pluginTypeChanged() void LtsAppDescriptorEditor::pluginTypeChanged()
{ {
if(m_ui->lePluginType->text().isEmpty()) if (m_ui->lePluginType->text().isEmpty())
return; return;
if(m_ui->lePluginType->text() == QLatin1String("gui")) if (m_ui->lePluginType->text() == QLatin1String("gui"))
{ {
m_ui->chbActions->setEnabled(true); m_ui->chbActions->setEnabled(true);
m_ui->chbMain->setEnabled(true); m_ui->chbMain->setEnabled(true);
m_ui->chbPayload->setEnabled(true); m_ui->chbPayload->setEnabled(true);
} }
else if(m_ui->lePluginType->text() == QLatin1String("data")) else if (m_ui->lePluginType->text() == QLatin1String("data"))
{ {
m_ui->chbActions->setChecked(false); m_ui->chbActions->setChecked(false);
m_ui->chbActions->setEnabled(false); m_ui->chbActions->setEnabled(false);
m_ui->chbMain->setChecked(false); m_ui->chbMain->setChecked(false);
m_ui->chbMain->setEnabled(false); m_ui->chbMain->setEnabled(false);
m_ui->chbPayload->setChecked(false); m_ui->chbPayload->setChecked(false);
m_ui->chbPayload->setEnabled(false); m_ui->chbPayload->setEnabled(false);
} }
else else
{ {
QMessageBox msgBox(QMessageBox::Information, QMessageBox msgBox(QMessageBox::Information, tr("Error"),
tr("Error"), tr("Plugin Type must either be \"gui\" or \"data\"."));
tr("Plugin Type must either be \"gui\" or \"data\".")); msgBox.exec();
msgBox.exec(); m_ui->lePluginType->setText(QString());
m_ui->lePluginType->setText(QString()); }
}
} }
void LtsAppDescriptorEditor::onAppAddClicked() void LtsAppDescriptorEditor::onAppAddClicked()
{ {
m_changed = true; m_changed = true;
if(m_ui->leAppName->text().isEmpty()) if (m_ui->leAppName->text().isEmpty())
{ {
QMessageBox msgBox(QMessageBox::Critical, QMessageBox msgBox(QMessageBox::Critical, tr("Error"), tr("The App needs to have a name."));
tr("Error"), msgBox.exec();
tr("The App needs to have a name.")); return;
msgBox.exec(); }
return;
}
QStringList appList; QStringList appList;
Q_FOREACH(const LtsAppDescriptor::AppDescription &appDesc, m_vector) Q_FOREACH (const LtsAppDescriptor::AppDescription& appDesc, m_vector)
{ {
appList << appDesc.appName; appList << appDesc.appName;
} }
if(appList.contains(m_ui->leAppName->text(),Qt::CaseInsensitive)) if (appList.contains(m_ui->leAppName->text(), Qt::CaseInsensitive))
{ {
QMessageBox msgBox(QMessageBox::Critical, QMessageBox msgBox(QMessageBox::Critical, tr("Error"),
tr("Error"), tr("There already exists an app named \"%1\".").arg(m_ui->leAppName->text()));
tr("There already exists an app named \"%1\".").arg(m_ui->leAppName->text())); msgBox.exec();
msgBox.exec(); return;
return; }
}
LtsAppDescriptor::AppDescription newApp; LtsAppDescriptor::AppDescription newApp;
newApp.appName = m_ui->leAppName->text(); newApp.appName = m_ui->leAppName->text();
newApp.active = m_ui->chbAppActive->isChecked(); newApp.active = m_ui->chbAppActive->isChecked();
m_vector.append(newApp); m_vector.append(newApp);
updateAppModel();
updateAppModel();
} }
void LtsAppDescriptorEditor::onPluginAddClicked() void LtsAppDescriptorEditor::onPluginAddClicked()
{ {
m_changed = true; m_changed = true;
if(m_ui->lePluginType->text().isEmpty()) if (m_ui->lePluginType->text().isEmpty())
{ {
QMessageBox msgBox(QMessageBox::Critical, QMessageBox msgBox(QMessageBox::Critical, tr("Error"), tr("The Plugin needs to contain a type."));
tr("Error"), msgBox.exec();
tr("The Plugin needs to contain a type.")); return;
msgBox.exec(); }
return; if (m_ui->lePluginName->text().isEmpty())
} {
if(m_ui->lePluginName->text().isEmpty()) QMessageBox msgBox(QMessageBox::Critical, tr("Error"), tr("The Plugin needs to have a name."));
{ msgBox.exec();
QMessageBox msgBox(QMessageBox::Critical, return;
tr("Error"), }
tr("The Plugin needs to have a name."));
msgBox.exec();
return;
}
QStringList pluginList; QStringList pluginList;
Q_FOREACH(const LtsAppDescriptor::PluginInfo &pluginDesc, m_vector.at(m_appIndex.row()).requiredPlugins) Q_FOREACH (const LtsAppDescriptor::PluginInfo& pluginDesc, m_vector.at(m_appIndex.row()).requiredPlugins)
{ {
pluginList << pluginDesc.iid; pluginList << pluginDesc.iid;
} }
if(pluginList.contains(m_ui->lePluginName->text(),Qt::CaseInsensitive)) if (pluginList.contains(m_ui->lePluginName->text(), Qt::CaseInsensitive))
{ {
QMessageBox msgBox(QMessageBox::Critical, QMessageBox msgBox(QMessageBox::Critical, tr("Error"),
tr("Error"), tr("There already exists an plugin named \"%1\".").arg(m_ui->lePluginName->text()));
tr("There already exists an plugin named \"%1\".").arg(m_ui->lePluginName->text())); msgBox.exec();
msgBox.exec(); return;
return; }
}
LtsAppDescriptor::PluginInfo newPlugin;
LtsAppDescriptor::PluginInfo newPlugin; newPlugin.iid = m_ui->lePluginName->text();
newPlugin.iid = m_ui->lePluginName->text(); if (m_ui->lePluginType->text() == QLatin1String("gui"))
newPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::GUI;
else if (m_ui->lePluginType->text() == QLatin1String("data"))
newPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::DATA;
else
newPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::UNKNOWN;
if(m_ui->lePluginType->text() == QLatin1String("gui")) if (m_ui->chbActions->isChecked())
newPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::GUI; newPlugin.flags |= LtsAppDescriptor::PluginInfo::Flag::ACTIONS;
else if(m_ui->lePluginType->text() == QLatin1String("data")) if (m_ui->chbMain->isChecked())
newPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::DATA; newPlugin.flags |= LtsAppDescriptor::PluginInfo::Flag::MAIN;
else if (m_ui->chbPayload->isChecked())
newPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::UNKNOWN; newPlugin.flags |= LtsAppDescriptor::PluginInfo::Flag::PAYLOAD;
if(m_ui->chbActions->isChecked()) m_vector[m_appIndex.row()].requiredPlugins.append(newPlugin);
newPlugin.flags |= LtsAppDescriptor::PluginInfo::Flag::ACTIONS;
if(m_ui->chbMain->isChecked())
newPlugin.flags |= LtsAppDescriptor::PluginInfo::Flag::MAIN;
if(m_ui->chbPayload->isChecked())
newPlugin.flags |= LtsAppDescriptor::PluginInfo::Flag::PAYLOAD;
m_vector[m_appIndex.row()].requiredPlugins.append(newPlugin);
onAppsClicked(m_appIndex);
onNewpluginClicked();
onAppsClicked(m_appIndex);
onNewpluginClicked();
} }
void LtsAppDescriptorEditor::onAppDeleteClicked() void LtsAppDescriptorEditor::onAppDeleteClicked()
{ {
m_changed = true; m_changed = true;
if(!m_appIndex.isValid()) return; if (!m_appIndex.isValid())
return;
QMessageBox msgBox(tr("Warning"), QMessageBox msgBox(tr("Warning"),
tr("The App \n\"%1\" \nwill be removed. Continue?").arg(m_appIndex.data().toString()), tr("The App \n\"%1\" \nwill be removed. Continue?").arg(m_appIndex.data().toString()),
QMessageBox::Warning, QMessageBox::Warning, QMessageBox::Yes | QMessageBox::Default,
QMessageBox::Yes | QMessageBox::Default, QMessageBox::No | QMessageBox::Escape, QMessageBox::NoButton);
QMessageBox::No | QMessageBox::Escape,
QMessageBox::NoButton);
if (msgBox.exec() == QMessageBox::No) if (msgBox.exec() == QMessageBox::No)
return; return;
m_vector.remove(m_appIndex.row()); m_vector.remove(m_appIndex.row());
updateAppModel();
updateAppModel();
} }
void LtsAppDescriptorEditor::onPluginDeletedClicked() void LtsAppDescriptorEditor::onPluginDeletedClicked()
{ {
m_changed = true; m_changed = true;
if(!m_pluginIndex.isValid()) return; if (!m_pluginIndex.isValid())
return;
QMessageBox msgBox(tr("Warning"), QMessageBox msgBox(tr("Warning"),
tr("The Plugin \n\"%1\" \nwill be removed. Continue?").arg(m_pluginIndex.data().toString()), tr("The Plugin \n\"%1\" \nwill be removed. Continue?").arg(m_pluginIndex.data().toString()),
QMessageBox::Warning, QMessageBox::Warning, QMessageBox::Yes | QMessageBox::Default,
QMessageBox::Yes | QMessageBox::Default, QMessageBox::No | QMessageBox::Escape, QMessageBox::NoButton);
QMessageBox::No | QMessageBox::Escape,
QMessageBox::NoButton);
if (msgBox.exec() == QMessageBox::No) if (msgBox.exec() == QMessageBox::No)
return; return;
m_vector[m_appIndex.row()].requiredPlugins.remove(m_pluginIndex.row()); m_vector[m_appIndex.row()].requiredPlugins.remove(m_pluginIndex.row());
m_pluginIndex = QModelIndex(); m_pluginIndex = QModelIndex();
m_ui->lePluginName->setText(QString()); m_ui->lePluginName->setText(QString());
m_ui->lePluginType->setText(QString()); m_ui->lePluginType->setText(QString());
m_ui->chbActions->setChecked(false); m_ui->chbActions->setChecked(false);
m_ui->chbMain->setChecked(false); m_ui->chbMain->setChecked(false);
m_ui->chbPayload->setChecked(false); m_ui->chbPayload->setChecked(false);
m_ui->pbDeletePlugin->setEnabled(false); m_ui->pbDeletePlugin->setEnabled(false);
m_ui->pbUpdate->setEnabled(false); m_ui->pbUpdate->setEnabled(false);
m_ui->pbNewPlugin->setEnabled(false); m_ui->pbNewPlugin->setEnabled(false);
onAppsClicked(m_appIndex); onAppsClicked(m_appIndex);
} }
void LtsAppDescriptorEditor::onUpdateClicked() void LtsAppDescriptorEditor::onUpdateClicked()
{ {
m_changed = true; m_changed = true;
if(m_ui->lePluginType->text().isEmpty()) if (m_ui->lePluginType->text().isEmpty())
{ {
QMessageBox msgBox(QMessageBox::Critical, QMessageBox msgBox(QMessageBox::Critical, tr("Error"), tr("The Plugin needs to contain a type."));
tr("Error"), msgBox.exec();
tr("The Plugin needs to contain a type.")); return;
msgBox.exec(); }
return; if (m_ui->lePluginName->text().isEmpty())
} {
if(m_ui->lePluginName->text().isEmpty()) QMessageBox msgBox(QMessageBox::Critical, tr("Error"), tr("The Plugin needs to have a name."));
{ msgBox.exec();
QMessageBox msgBox(QMessageBox::Critical, return;
tr("Error"), }
tr("The Plugin needs to have a name."));
msgBox.exec();
return;
}
m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].iid = m_ui->lePluginName->text(); m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].iid = m_ui->lePluginName->text();
if(m_ui->lePluginType->text() == QLatin1String("gui")) if (m_ui->lePluginType->text() == QLatin1String("gui"))
m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].type = LtsAppDescriptor::PluginInfo::PluginType::GUI; m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].type =
else if(m_ui->lePluginType->text() == QLatin1String("data")) LtsAppDescriptor::PluginInfo::PluginType::GUI;
m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].type = LtsAppDescriptor::PluginInfo::PluginType::DATA; else if (m_ui->lePluginType->text() == QLatin1String("data"))
else m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].type =
m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].type = LtsAppDescriptor::PluginInfo::PluginType::UNKNOWN; LtsAppDescriptor::PluginInfo::PluginType::DATA;
else
m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].type =
LtsAppDescriptor::PluginInfo::PluginType::UNKNOWN;
m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].flags = QFlags<LtsAppDescriptor::PluginInfo::Flag>(); m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].flags =
QFlags<LtsAppDescriptor::PluginInfo::Flag>();
if(m_ui->chbActions->isChecked()) if (m_ui->chbActions->isChecked())
m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].flags |= LtsAppDescriptor::PluginInfo::Flag::ACTIONS; m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].flags |=
if(m_ui->chbMain->isChecked()) LtsAppDescriptor::PluginInfo::Flag::ACTIONS;
m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].flags |= LtsAppDescriptor::PluginInfo::Flag::MAIN; if (m_ui->chbMain->isChecked())
if(m_ui->chbPayload->isChecked()) m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].flags |=
m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].flags |= LtsAppDescriptor::PluginInfo::Flag::PAYLOAD; LtsAppDescriptor::PluginInfo::Flag::MAIN;
if (m_ui->chbPayload->isChecked())
m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].flags |=
LtsAppDescriptor::PluginInfo::Flag::PAYLOAD;
onAppsClicked(m_appIndex); onAppsClicked(m_appIndex);
onNewpluginClicked(); onNewpluginClicked();
} }
void LtsAppDescriptorEditor::onNewpluginClicked() void LtsAppDescriptorEditor::onNewpluginClicked()
{ {
m_ui->lePluginName->setText(QString()); m_ui->lePluginName->setText(QString());
m_ui->lePluginType->setText(QString()); m_ui->lePluginType->setText(QString());
m_ui->chbActions->setEnabled(true); m_ui->chbActions->setEnabled(true);
m_ui->chbMain->setEnabled(true); m_ui->chbMain->setEnabled(true);
m_ui->chbPayload->setEnabled(true); m_ui->chbPayload->setEnabled(true);
m_ui->chbActions->setChecked(false); m_ui->chbActions->setChecked(false);
m_ui->chbMain->setChecked(false); m_ui->chbMain->setChecked(false);
m_ui->chbPayload->setChecked(false); m_ui->chbPayload->setChecked(false);
m_ui->pbUpdate->setEnabled(false); m_ui->pbUpdate->setEnabled(false);
m_ui->pbNewPlugin->setEnabled(false); m_ui->pbNewPlugin->setEnabled(false);
m_ui->pbDeletePlugin->setEnabled(false); m_ui->pbDeletePlugin->setEnabled(false);
if(m_pluginIndex.isValid()) if (m_pluginIndex.isValid())
m_ui->lvPlugins->selectionModel()->select(m_pluginIndex,QItemSelectionModel::Deselect); m_ui->lvPlugins->selectionModel()->select(m_pluginIndex, QItemSelectionModel::Deselect);
m_pluginIndex = QModelIndex(); m_pluginIndex = QModelIndex();
} }
void LtsAppDescriptorEditor::onNewAppClicked() void LtsAppDescriptorEditor::onNewAppClicked()
{ {
updatePluginModel(QStringList()); updatePluginModel(QStringList());
m_ui->gbPlugins->setEnabled(false); m_ui->gbPlugins->setEnabled(false);
m_ui->pbDeletePlugin->setEnabled(false); m_ui->pbDeletePlugin->setEnabled(false);
m_ui->pbDeleteApp->setEnabled(false); m_ui->pbDeleteApp->setEnabled(false);
m_ui->pbAddPlugin->setEnabled(false); m_ui->pbAddPlugin->setEnabled(false);
m_ui->pbUpdate->setEnabled(false); m_ui->pbUpdate->setEnabled(false);
m_ui->pbNewPlugin->setEnabled(false); m_ui->pbNewPlugin->setEnabled(false);
m_ui->leAppName->setText(QString()); m_ui->leAppName->setText(QString());
m_ui->chbAppActive->setChecked(false); m_ui->chbAppActive->setChecked(false);
m_ui->lePluginName->setText(QString()); m_ui->lePluginName->setText(QString());
m_ui->lePluginType->setText(QString()); m_ui->lePluginType->setText(QString());
m_ui->chbActions->setChecked(false); m_ui->chbActions->setChecked(false);
m_ui->chbMain->setChecked(false); m_ui->chbMain->setChecked(false);
m_ui->chbPayload->setChecked(false); m_ui->chbPayload->setChecked(false);
m_ui->pbNewApp->setEnabled(false); m_ui->pbNewApp->setEnabled(false);
if(m_appIndex.isValid()) if (m_appIndex.isValid())
m_ui->lvApps->selectionModel()->select(m_appIndex,QItemSelectionModel::Deselect); m_ui->lvApps->selectionModel()->select(m_appIndex, QItemSelectionModel::Deselect);
m_appIndex = QModelIndex(); m_appIndex = QModelIndex();
} }
void LtsAppDescriptorEditor::updateAppModel() void LtsAppDescriptorEditor::updateAppModel()
{ {
onNewAppClicked(); onNewAppClicked();
QStringList appList; QStringList appList;
Q_FOREACH(const LtsAppDescriptor::AppDescription &appDesc, m_vector) Q_FOREACH (const LtsAppDescriptor::AppDescription& appDesc, m_vector)
{ {
appList << appDesc.appName; appList << appDesc.appName;
} }
if (!m_ui->lvApps->model()) if (!m_ui->lvApps->model())
m_ui->lvApps->setModel(new QStringListModel(this)); m_ui->lvApps->setModel(new QStringListModel(this));
QStringListModel *m = qobject_cast<QStringListModel*>(m_ui->lvApps->model()); QStringListModel* m = qobject_cast<QStringListModel*>(m_ui->lvApps->model());
if (!m) if (!m)
return; return;
m->setStringList(appList); m->setStringList(appList);
} }
void LtsAppDescriptorEditor::updatePluginModel(const QStringList &list) void LtsAppDescriptorEditor::updatePluginModel(const QStringList& list)
{ {
if (!m_ui->lvPlugins->model()) if (!m_ui->lvPlugins->model())
m_ui->lvPlugins->setModel(new QStringListModel(this)); m_ui->lvPlugins->setModel(new QStringListModel(this));
QStringListModel *m = qobject_cast<QStringListModel*>(m_ui->lvPlugins->model()); QStringListModel* m = qobject_cast<QStringListModel*>(m_ui->lvPlugins->model());
if (!m) if (!m)
return; return;
m->setStringList(list); m->setStringList(list);
} }
void LtsAppDescriptorEditor::checkSave() void LtsAppDescriptorEditor::checkSave()
{ {
if(m_changed) if (m_changed)
{ {
QMessageBox msgBox(tr("Warning"), QMessageBox msgBox(tr("Warning"), tr("The Data has been modified.\nDo you want to save your changes?"),
tr("The Data has been modified.\nDo you want to save your changes?"), QMessageBox::Warning, QMessageBox::Yes | QMessageBox::Default,
QMessageBox::Warning, QMessageBox::No | QMessageBox::Escape, QMessageBox::NoButton);
QMessageBox::Yes | QMessageBox::Default,
QMessageBox::No | QMessageBox::Escape,
QMessageBox::NoButton);
if (msgBox.exec() == QMessageBox::Yes) if (msgBox.exec() == QMessageBox::Yes)
onSaveAsClicked(); onSaveAsClicked();
} }
} }
void LtsAppDescriptorEditor::onSaveAsClicked() void LtsAppDescriptorEditor::onSaveAsClicked()
{ {
QString fileName = QFileDialog::getSaveFileName(this, tr("Save JSON"), QLatin1Literal("/shd/CTC/TOOLS/TDS/TDS-source/Lts/Projects/Legatus/resources/"), QString fileName = QFileDialog::getSaveFileName(
tr("JSON File (*.json)")); this, tr("Save JSON"), QLatin1Literal("/shd/CTC/TOOLS/TDS/TDS-source/Lts/Projects/Legatus/resources/"),
if(fileName.isEmpty()) tr("JSON File (*.json)"));
return; if (fileName.isEmpty())
return;
QByteArray jsonByteArray; QByteArray jsonByteArray;
jsonByteArray = LtsAppDescriptor::LtsAppDescriptor::createJson(m_vector); jsonByteArray = LtsAppDescriptor::LtsAppDescriptor::createJson(m_vector);
QFile f(fileName); QFile f(fileName);
f.open(QIODevice::WriteOnly); f.open(QIODevice::WriteOnly);
f.write(jsonByteArray); f.write(jsonByteArray);
f.close(); f.close();
m_changed = false; m_changed = false;
QMessageBox msgBox(QMessageBox::Information, QMessageBox msgBox(QMessageBox::Information, tr("Success"), tr("Your file has been saved."));
tr("Success"), msgBox.exec();
tr("Your file has been saved."));
msgBox.exec();
} }
void LtsAppDescriptorEditor::onSaveClicked() void LtsAppDescriptorEditor::onSaveClicked()
{ {
const QByteArray jsonByteArray(LtsAppDescriptor::LtsAppDescriptor::createJson(m_vector)); const QByteArray jsonByteArray(LtsAppDescriptor::LtsAppDescriptor::createJson(m_vector));
QFile f(m_fileName); QFile f(m_fileName);
f.open(QIODevice::WriteOnly); f.open(QIODevice::WriteOnly);
f.write(jsonByteArray); f.write(jsonByteArray);
f.close(); f.close();
m_changed = false; m_changed = false;
QMessageBox msgBox(QMessageBox::Information, QMessageBox msgBox(QMessageBox::Information, tr("Success"), tr("Your file has been saved."));
tr("Success"), msgBox.exec();
tr("Your file has been saved."));
msgBox.exec();
} }
void LtsAppDescriptorEditor::onOpenClicked() void LtsAppDescriptorEditor::onOpenClicked()
{ {
checkSave(); checkSave();
getAppDescriptionVector(); getAppDescriptionVector();
m_changed = false; m_changed = false;
} }
void LtsAppDescriptorEditor::onNewClicked() void LtsAppDescriptorEditor::onNewClicked()
{ {
checkSave(); checkSave();
m_ui->chbActions->setChecked(false); m_ui->chbActions->setChecked(false);
m_ui->chbMain->setChecked(false); m_ui->chbMain->setChecked(false);
m_ui->chbPayload->setChecked(false); m_ui->chbPayload->setChecked(false);
m_ui->chbAppActive->setChecked(false); m_ui->chbAppActive->setChecked(false);
m_ui->leAppName->setText(QString()); m_ui->leAppName->setText(QString());
m_ui->lePluginName->setText(QString()); m_ui->lePluginName->setText(QString());
m_ui->lePluginType->setText(QString()); m_ui->lePluginType->setText(QString());
m_ui->gbPlugins->setEnabled(false); m_ui->gbPlugins->setEnabled(false);
m_vector = LtsAppDescriptor::AppDescriptionVector(); m_vector = LtsAppDescriptor::AppDescriptionVector();
updateAppModel();
updatePluginModel(QStringList());
updateAppModel();
updatePluginModel(QStringList());
} }
void LtsAppDescriptorEditor::enableNewPlugin() void LtsAppDescriptorEditor::enableNewPlugin()
{ {
m_ui->pbNewPlugin->setEnabled(true); m_ui->pbNewPlugin->setEnabled(true);
} }
void LtsAppDescriptorEditor::onQuitClicked() void LtsAppDescriptorEditor::onQuitClicked()
{ {
QApplication::quit(); QApplication::quit();
} }
@@ -1,67 +1,65 @@
#pragma once #pragma once
#include <QObject>
#include <QtWidgets/QWidget>
#include <QModelIndex>
#include "lts_app_descriptor.h" #include "lts_app_descriptor.h"
#include <QModelIndex>
#include <QObject>
#include <QtWidgets/QWidget>
#ifndef LTSAPPDESCRIPTOREDITOR_EXPORT #ifndef LTSAPPDESCRIPTOREDITOR_EXPORT
# ifdef BUILD_STATIC_LIBRARIES #ifdef BUILD_STATIC_LIBRARIES
# define LTSAPPDESCRIPTOREDITOR_EXPORT #define LTSAPPDESCRIPTOREDITOR_EXPORT
# else #else
# if defined(MAKE_LTSAPPDESCRIPTOREDITOR_LIB) #if defined(MAKE_LTSAPPDESCRIPTOREDITOR_LIB)
# define LTSAPPDESCRIPTOREDITOR_EXPORT Q_DECL_EXPORT #define LTSAPPDESCRIPTOREDITOR_EXPORT Q_DECL_EXPORT
# else #else
# define LTSAPPDESCRIPTOREDITOR_EXPORT Q_DECL_IMPORT #define LTSAPPDESCRIPTOREDITOR_EXPORT Q_DECL_IMPORT
# endif #endif
# endif #endif
#endif #endif
class Ui_LtsAppDescriptionEditor; class Ui_LtsAppDescriptionEditor;
class LTSAPPDESCRIPTOREDITOR_EXPORT LtsAppDescriptorEditor : public QWidget class LTSAPPDESCRIPTOREDITOR_EXPORT LtsAppDescriptorEditor : public QWidget
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit LtsAppDescriptorEditor(QWidget *parent = 0); explicit LtsAppDescriptorEditor(QWidget* parent = 0);
~LtsAppDescriptorEditor(); ~LtsAppDescriptorEditor();
private: private:
Ui_LtsAppDescriptionEditor *m_ui; Ui_LtsAppDescriptionEditor* m_ui;
LtsAppDescriptor::AppDescriptionVector m_vector; LtsAppDescriptor::AppDescriptionVector m_vector;
QModelIndex m_appIndex; QModelIndex m_appIndex;
QModelIndex m_pluginIndex; QModelIndex m_pluginIndex;
QString m_fileName; QString m_fileName;
bool m_changed; bool m_changed;
void getAppDescriptionVector(); void getAppDescriptionVector();
void setupMainWindow(); void setupMainWindow();
void updateAppModel(); void updateAppModel();
void updatePluginModel(const QStringList &list); void updatePluginModel(const QStringList& list);
void checkSave(); void checkSave();
private slots: private slots:
void onAppsClicked(const QModelIndex &index); void onAppsClicked(const QModelIndex& index);
void onPluginsClicked(const QModelIndex &index); void onPluginsClicked(const QModelIndex& index);
void pluginTypeChanged(); void pluginTypeChanged();
void onAppAddClicked(); void onAppAddClicked();
void onPluginAddClicked(); void onPluginAddClicked();
void onAppDeleteClicked(); void onAppDeleteClicked();
void onPluginDeletedClicked(); void onPluginDeletedClicked();
void onUpdateClicked(); void onUpdateClicked();
void onNewpluginClicked(); void onNewpluginClicked();
void onNewAppClicked(); void onNewAppClicked();
void enableNewPlugin(); void enableNewPlugin();
public slots: public slots:
void onSaveClicked(); void onSaveClicked();
void onSaveAsClicked(); void onSaveAsClicked();
void onOpenClicked(); void onOpenClicked();
void onNewClicked(); void onNewClicked();
void onQuitClicked(); void onQuitClicked();
}; };
+36 -37
View File
@@ -1,56 +1,55 @@
#include "lts_app_descriptor_editor.h" #include "lts_app_descriptor_editor.h"
#include <QAction> #include <QAction>
#include <QApplication> #include <QApplication>
#include <QMainWindow> #include <QMainWindow>
#include <QMenuBar> #include <QMenuBar>
int main(int argc, char *argv[]) int main(int argc, char* argv[])
{ {
QApplication a(argc, argv); QApplication a(argc, argv);
QMainWindow *mainWindow = new QMainWindow(); QMainWindow* mainWindow = new QMainWindow();
QMenu *fileMenu = mainWindow->menuBar()->addMenu(QObject::tr("&File")); QMenu* fileMenu = mainWindow->menuBar()->addMenu(QObject::tr("&File"));
QAction *openAct = new QAction(QObject::tr("&Open"), mainWindow); QAction* openAct = new QAction(QObject::tr("&Open"), mainWindow);
openAct->setShortcuts(QKeySequence::Open); openAct->setShortcuts(QKeySequence::Open);
openAct->setStatusTip(QObject::tr("Open an existing file")); openAct->setStatusTip(QObject::tr("Open an existing file"));
fileMenu->addAction(openAct); fileMenu->addAction(openAct);
QAction *newAct = new QAction(QObject::tr("&New"), mainWindow); QAction* newAct = new QAction(QObject::tr("&New"), mainWindow);
newAct->setShortcuts(QKeySequence::New); newAct->setShortcuts(QKeySequence::New);
newAct->setStatusTip(QObject::tr("Create a new App")); newAct->setStatusTip(QObject::tr("Create a new App"));
fileMenu->addAction(newAct); fileMenu->addAction(newAct);
QAction *saveAct = new QAction(QObject::tr("&Save"), mainWindow); QAction* saveAct = new QAction(QObject::tr("&Save"), mainWindow);
saveAct->setShortcuts(QKeySequence::Save); saveAct->setShortcuts(QKeySequence::Save);
saveAct->setStatusTip(QObject::tr("Save modified file")); saveAct->setStatusTip(QObject::tr("Save modified file"));
fileMenu->addAction(saveAct); fileMenu->addAction(saveAct);
QAction *saveAsAct = new QAction(QObject::tr("&SaveAs"), mainWindow); QAction* saveAsAct = new QAction(QObject::tr("&SaveAs"), mainWindow);
saveAsAct->setShortcuts(QKeySequence::SaveAs); saveAsAct->setShortcuts(QKeySequence::SaveAs);
saveAsAct->setStatusTip(QObject::tr("Save modified file as")); saveAsAct->setStatusTip(QObject::tr("Save modified file as"));
fileMenu->addAction(saveAsAct); fileMenu->addAction(saveAsAct);
QAction *quitAct = new QAction(QObject::tr("&Quit"), mainWindow); QAction* quitAct = new QAction(QObject::tr("&Quit"), mainWindow);
quitAct->setShortcuts(QKeySequence::Quit); quitAct->setShortcuts(QKeySequence::Quit);
quitAct->setStatusTip(QObject::tr("Quit the Application")); quitAct->setStatusTip(QObject::tr("Quit the Application"));
fileMenu->addAction(quitAct); fileMenu->addAction(quitAct);
LtsAppDescriptorEditor* editor = new LtsAppDescriptorEditor(mainWindow);
mainWindow->setCentralWidget(editor);
QObject::connect(openAct, &QAction::triggered, editor, &LtsAppDescriptorEditor::onOpenClicked);
QObject::connect(newAct, &QAction::triggered, editor, &LtsAppDescriptorEditor::onNewClicked);
QObject::connect(saveAct, &QAction::triggered, editor, &LtsAppDescriptorEditor::onSaveClicked);
QObject::connect(saveAsAct, &QAction::triggered, editor, &LtsAppDescriptorEditor::onSaveAsClicked);
QObject::connect(quitAct, &QAction::triggered, editor, &LtsAppDescriptorEditor::onQuitClicked);
LtsAppDescriptorEditor *editor = new LtsAppDescriptorEditor(mainWindow); mainWindow->show();
mainWindow->setCentralWidget(editor);
QObject::connect(openAct, &QAction::triggered, editor, &LtsAppDescriptorEditor::onOpenClicked);
QObject::connect(newAct, &QAction::triggered, editor, &LtsAppDescriptorEditor::onNewClicked);
QObject::connect(saveAct, &QAction::triggered, editor, &LtsAppDescriptorEditor::onSaveClicked);
QObject::connect(saveAsAct, &QAction::triggered, editor, &LtsAppDescriptorEditor::onSaveAsClicked);
QObject::connect(quitAct, &QAction::triggered, editor, &LtsAppDescriptorEditor::onQuitClicked);
mainWindow->show(); int ret = a.exec();
delete mainWindow;
int ret = a.exec(); return ret;
delete mainWindow;
return ret;
} }
@@ -1,35 +1,32 @@
#include "app.h" #include "app.h"
#include "ui_app.h"
#include "AppChooser/app_chooser_model.h"
#include "AppChooser/app_chooser_model.h"
#include "ui_app.h"
namespace LtsAppManager namespace LtsAppManager
{ {
CustomViewApp::CustomViewApp(QWidget *parent) CustomViewApp::CustomViewApp(QWidget* parent) : AbstractDisplayWidget(parent), m_ui(new Ui::CustomViewApp)
: AbstractDisplayWidget(parent)
, m_ui(new Ui::CustomViewApp)
{ {
m_ui->setupUi(this); m_ui->setupUi(this);
m_ui->image->setMenuEnabled(false); m_ui->image->setMenuEnabled(false);
} }
CustomViewApp::~CustomViewApp() CustomViewApp::~CustomViewApp()
{ {
delete m_ui; delete m_ui;
} }
bool CustomViewApp::init(const QModelIndex &idx) bool CustomViewApp::init(const QModelIndex& idx)
{ {
if (!idx.isValid()) if (!idx.isValid())
return false; return false;
m_ui->lbAppName->setText(rowData(idx, AppChooserModel::Name).toString()); m_ui->lbAppName->setText(rowData(idx, AppChooserModel::Name).toString());
return true; return true;
} }
} } // namespace LtsAppManager
@@ -2,10 +2,8 @@
#pragma once #pragma once
#include <QObject> #include <QObject>
#include <Viewer/LtsDataView/abstract_display_widget.h> #include <Viewer/LtsDataView/abstract_display_widget.h>
namespace Ui namespace Ui
{ {
class CustomViewApp; class CustomViewApp;
@@ -16,16 +14,15 @@ namespace LtsAppManager
class CustomViewApp final : public LtsDataView::AbstractDisplayWidget class CustomViewApp final : public LtsDataView::AbstractDisplayWidget
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit CustomViewApp(QWidget *parent = nullptr); explicit CustomViewApp(QWidget* parent = nullptr);
~CustomViewApp(); ~CustomViewApp();
bool init(const QModelIndex &idx) override; bool init(const QModelIndex& idx) override;
private:
Ui::CustomViewApp* m_ui;
private:
Ui::CustomViewApp* m_ui;
}; };
} } // namespace LtsAppManager
+38 -51
View File
@@ -1,93 +1,80 @@
#include "AppChooser/app_chooser.h" #include "AppChooser/app_chooser.h"
#include "ui_app_chooser.h"
#include "AppChooser/CustomViews/app.h"
#include "AppChooser/app_chooser_model.h" #include "AppChooser/app_chooser_model.h"
#include "lts_app_manager.h" #include "lts_app_manager.h"
#include "AppChooser/CustomViews/app.h" #include "ui_app_chooser.h"
#include <QCloseEvent> #include <QCloseEvent>
#include <QDebug> #include <QDebug>
namespace LtsAppManager namespace LtsAppManager
{ {
AppChooser::AppChooser() AppChooser::AppChooser() : QWidget(nullptr), m_ui(new Ui::AppChooser), m_model(), m_madeSelection(false)
: QWidget(nullptr)
, m_ui(new Ui::AppChooser)
, m_model()
, m_madeSelection(false)
{ {
m_ui->setupUi(this); m_ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose); setAttribute(Qt::WA_DeleteOnClose);
connect(m_ui->widget, &LtsDataView::LtsDataView::LtsDataView::signalDoubleClicked, connect(m_ui->widget, &LtsDataView::LtsDataView::LtsDataView::signalDoubleClicked, this,
this, &AppChooser::slotAppSelected); &AppChooser::slotAppSelected);
connect(m_ui->widget, &LtsDataView::LtsDataView::LtsDataView::signalEnterPressed, connect(m_ui->widget, &LtsDataView::LtsDataView::LtsDataView::signalEnterPressed, this,
this, &AppChooser::slotAppSelected); &AppChooser::slotAppSelected);
connect(m_ui->widget, &LtsDataView::LtsDataView::LtsDataView::signalSelectionChanged, connect(m_ui->widget, &LtsDataView::LtsDataView::LtsDataView::signalSelectionChanged, this, &AppChooser::enaDisa);
this, &AppChooser::enaDisa); connect(m_ui->pbQuit, &QPushButton::clicked, this, &QWidget::close);
connect(m_ui->pbQuit, &QPushButton::clicked, connect(m_ui->pbSelect, &QPushButton::clicked, this, &AppChooser::slotAppSelected);
this, &QWidget::close);
connect(m_ui->pbSelect, &QPushButton::clicked,
this, &AppChooser::slotAppSelected);
m_model = new AppChooserModel(this); m_model = new AppChooserModel(this);
m_model->initModel(LtsAppManager::getInstance()->getAvailableApps()); m_model->initModel(LtsAppManager::getInstance()->getAvailableApps());
m_ui->widget->seamless(); m_ui->widget->seamless();
m_ui->widget->setModel(m_model); m_ui->widget->setModel(m_model);
m_ui->widget->hideColumn(AppChooserModel::Columns::Visible); m_ui->widget->hideColumn(AppChooserModel::Columns::Visible);
} }
AppChooser::~AppChooser() AppChooser::~AppChooser()
{ {
delete m_ui; delete m_ui;
} }
void AppChooser::slotQuit() void AppChooser::slotQuit()
{ {
if (m_alreadyCloseEmitted) if (m_alreadyCloseEmitted)
return; return;
m_alreadyCloseEmitted = true; m_alreadyCloseEmitted = true;
emit signalLogout(); emit signalLogout();
} }
void AppChooser::closeEvent(QCloseEvent*)
void AppChooser::closeEvent(QCloseEvent *)
{ {
if (!m_madeSelection) if (!m_madeSelection)
slotQuit(); slotQuit();
} }
void AppChooser::slotAppSelected() void AppChooser::slotAppSelected()
{ {
const QModelIndex idx = m_ui->widget->currentIndex(); const QModelIndex idx = m_ui->widget->currentIndex();
const LtsAppDescriptor::AppDescription app = m_model->getRowData(idx.row()); const LtsAppDescriptor::AppDescription app = m_model->getRowData(idx.row());
if (!app.active) if (!app.active)
return; return;
hide(); hide();
m_madeSelection = true; m_madeSelection = true;
emit signalAppSelected(app.id); emit signalAppSelected(app.id);
close(); close();
} }
void AppChooser::enaDisa() void AppChooser::enaDisa()
{ {
const QModelIndexList selectedRows = m_ui->widget->selectedRows(); const QModelIndexList selectedRows = m_ui->widget->selectedRows();
const int cntSelectedRows = selectedRows.size(); const int cntSelectedRows = selectedRows.size();
m_ui->pbSelect->setEnabled(cntSelectedRows == 1); m_ui->pbSelect->setEnabled(cntSelectedRows == 1);
} }
} } // namespace LtsAppManager
+21 -24
View File
@@ -1,16 +1,14 @@
#pragma once #pragma once
#include <QObject>
#include <QWidget>
#include <LtsAppDescriptor/lts_app_descriptor.h> #include <LtsAppDescriptor/lts_app_descriptor.h>
#include <QObject>
#include <QWidget>
namespace Ui namespace Ui
{ {
class AppChooser; class AppChooser;
} }
namespace LtsAppManager namespace LtsAppManager
{ {
@@ -18,31 +16,30 @@ class AppChooserModel;
class AppChooser : public QWidget class AppChooser : public QWidget
{ {
Q_OBJECT Q_OBJECT
public: public:
AppChooser(); AppChooser();
~AppChooser(); ~AppChooser();
private: private:
Ui::AppChooser *m_ui; Ui::AppChooser* m_ui;
AppChooserModel *m_model; AppChooserModel* m_model;
bool m_madeSelection; bool m_madeSelection;
bool m_alreadyCloseEmitted { false }; bool m_alreadyCloseEmitted{false};
void enaDisa(); void enaDisa();
protected: protected:
void closeEvent(QCloseEvent *); void closeEvent(QCloseEvent*);
signals: signals:
void signalAppSelected(LtsAppDescriptor::App appId); void signalAppSelected(LtsAppDescriptor::App appId);
void signalLogout(); void signalLogout();
private slots:
void slotAppSelected();
void slotQuit();
private slots:
void slotAppSelected();
void slotQuit();
}; };
} } // namespace LtsAppManager
@@ -4,47 +4,45 @@
#include <LtsSession/lts_session.h> #include <LtsSession/lts_session.h>
namespace LtsAppManager namespace LtsAppManager
{ {
AppChooserModel::AppChooserModel(QObject *parent) AppChooserModel::AppChooserModel(QObject* parent)
: LtsWidgets::LtsAbstractTableModel<LtsAppDescriptor::AppDescription>({tr("Name")}, parent) : LtsWidgets::LtsAbstractTableModel<LtsAppDescriptor::AppDescription>({tr("Name")}, parent)
{}
bool AppChooserModel::initModel(const LtsAppDescriptor::AppDescriptionVector &availableApps)
{ {
for (auto i = availableApps.constBegin(); i != availableApps.constEnd(); ++i)
{
const LtsAppDescriptor::AppDescription& appDesc = *i;
if (!appDesc.visible)
continue;
insertRow(appDesc);
}
return true;
} }
bool AppChooserModel::initModel(const LtsAppDescriptor::AppDescriptionVector& availableApps)
QVariant AppChooserModel::data(const QModelIndex &index, int role) const
{ {
if (role != Qt::DisplayRole || !indexIsValid(index)) for (auto i = availableApps.constBegin(); i != availableApps.constEnd(); ++i)
{
const LtsAppDescriptor::AppDescription& appDesc = *i;
if (!appDesc.visible)
continue;
insertRow(appDesc);
}
return true;
}
QVariant AppChooserModel::data(const QModelIndex& index, int role) const
{
if (role != Qt::DisplayRole || !indexIsValid(index))
return QVariant();
const LtsAppDescriptor::AppDescription& ad = m_vecData.at(index.row());
switch (index.column())
{
case Name:
return LtsSession::LtsSession::appToString(ad.id);
case Visible:
return ad.visible;
}
return QVariant(); return QVariant();
const LtsAppDescriptor::AppDescription &ad = m_vecData.at(index.row());
switch (index.column())
{
case Name:
return LtsSession::LtsSession::appToString(ad.id);
case Visible:
return ad.visible;
}
return QVariant();
}
} }
} // namespace LtsAppManager
@@ -1,30 +1,25 @@
#pragma once #pragma once
#include <QObject>
#include <LtsAppDescriptor/lts_app_descriptor.h> #include <LtsAppDescriptor/lts_app_descriptor.h>
#include <LtsWidgets/lts_abstract_table_model.h> #include <LtsWidgets/lts_abstract_table_model.h>
#include <QObject>
namespace LtsAppManager namespace LtsAppManager
{ {
class AppChooserModel final : public LtsWidgets::LtsAbstractTableModel<LtsAppDescriptor::AppDescription> class AppChooserModel final : public LtsWidgets::LtsAbstractTableModel<LtsAppDescriptor::AppDescription>
{ {
Q_OBJECT Q_OBJECT
public: public:
enum Columns enum Columns {
{ Name = 0,
Name = 0, Visible,
Visible, };
};
explicit AppChooserModel(QObject *parent = nullptr); explicit AppChooserModel(QObject* parent = nullptr);
bool initModel(const LtsAppDescriptor::AppDescriptionVector &availableApps); bool initModel(const LtsAppDescriptor::AppDescriptionVector& availableApps);
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override final; QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override final;
}; };
} } // namespace LtsAppManager
File diff suppressed because it is too large. Load diff
+83 -70
View File
@@ -1,27 +1,25 @@
#pragma once #pragma once
#include <LtsAppDescriptor/lts_app_descriptor.h>
#include <Lts/Common/ProjectConfig/project_defines.h> #include <Lts/Common/ProjectConfig/project_defines.h>
#include <LtsWidgets/lts_dialog.h> #include <LtsAppDescriptor/lts_app_descriptor.h>
#include <LtsWidgets/lts_base_layout_widget.h>
#include <LtsSession/lts_session.h> #include <LtsSession/lts_session.h>
#include <memory> #include <LtsWidgets/lts_base_layout_widget.h>
#include <LtsWidgets/lts_dialog.h>
#include <QObject> #include <QObject>
#include <QVector> #include <QVector>
#include <memory>
#ifndef LTSAPPMANAGER_EXPORT #ifndef LTSAPPMANAGER_EXPORT
# ifdef BUILD_STATIC_LIBRARIES #ifdef BUILD_STATIC_LIBRARIES
# define LTSAPPMANAGER_EXPORT #define LTSAPPMANAGER_EXPORT
# else #else
# if defined(MAKE_LTSAPPMANAGER_LIB) #if defined(MAKE_LTSAPPMANAGER_LIB)
# define LTSAPPMANAGER_EXPORT Q_DECL_EXPORT #define LTSAPPMANAGER_EXPORT Q_DECL_EXPORT
# else #else
# define LTSAPPMANAGER_EXPORT Q_DECL_IMPORT #define LTSAPPMANAGER_EXPORT Q_DECL_IMPORT
# endif #endif
# endif #endif
#endif #endif
namespace LtsPluginManager namespace LtsPluginManager
{ {
@@ -37,7 +35,7 @@ namespace LtsSession
{ {
class LtsSession; class LtsSession;
struct DdsConnectionParams; struct DdsConnectionParams;
} } // namespace LtsSession
namespace DeveloperTools namespace DeveloperTools
{ {
@@ -46,78 +44,93 @@ class DevDialog;
class QTcpSocket; class QTcpSocket;
namespace LtsAppManager namespace LtsAppManager
{ {
class LTSAPPMANAGER_EXPORT LtsAppManager : public QObject class LTSAPPMANAGER_EXPORT LtsAppManager : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
static LtsAppManager* getInstance(); static LtsAppManager* getInstance();
void showLogin(); void showLogin();
LtsPluginManager::LtsPluginManager* createApp(LtsAppDescriptor::App appId,
const LtsSession::DdsConnectionParams& connParams,
const QString& workspaceId = QString(), bool hidden = false,
bool force = false);
bool startAppOrLetUserChoose(LtsAppDescriptor::App appId, const LtsSession::DdsConnectionParams& connParams,
bool force = false);
LtsPluginManager::LtsPluginManager *createApp(LtsAppDescriptor::App appId, const LtsSession::DdsConnectionParams &connParams, void setLoginPluginIid(const QString& loginPluginIid)
const QString &workspaceId = QString(), bool hidden = false, bool force = false); {
bool startAppOrLetUserChoose(LtsAppDescriptor::App appId, const LtsSession::DdsConnectionParams &connParams, bool force = false); m_loginPluginIid = loginPluginIid;
void setLoginPluginIid(const QString &loginPluginIid) { m_loginPluginIid = loginPluginIid; } }
void setMainApp(LtsAppDescriptor::App appId = LtsAppDescriptor::App::Login);
QVector<LtsPluginManager::LtsPluginManager *> getAppList() const { return m_appList ;}
LtsAppDescriptor::AppDescriptionVector getAvailableApps() const { return m_availableApps; }
void setAvailableApps(const LtsAppDescriptor::AppDescriptionVector &availableApps);
bool hasRightForApp(const LtsAppDescriptor::AppDescription &appDescription) const;
LtsAppDescriptor::AppDescription getApp(LtsAppDescriptor::App appId) const;
bool hasApp(LtsAppDescriptor::App appId) const;
int getNumberOfSituationMapInstances() const;
void debugSendMessage(const QString &msg);
void setMainApp(LtsAppDescriptor::App appId = LtsAppDescriptor::App::Login);
QVector<LtsPluginManager::LtsPluginManager*> getAppList() const
{
return m_appList;
}
bool otherSessionsResponsibility(LtsSession::LtsSession *thisSession, const QVector<LtsAppDescriptor::App> &requiredAppTypes, LtsAppDescriptor::AppDescriptionVector getAvailableApps() const
const QVector<IDL::PartitionType> &requiredPartitionTypes, const QString &menuGroup, {
const QString &identifier, LtsWidgets::LayoutArea area); return m_availableApps;
}
private: void setAvailableApps(const LtsAppDescriptor::AppDescriptionVector& availableApps);
friend struct LtsAppManagerHandler; bool hasRightForApp(const LtsAppDescriptor::AppDescription& appDescription) const;
friend class DeveloperTools::DevDialog; LtsAppDescriptor::AppDescription getApp(LtsAppDescriptor::App appId) const;
bool hasApp(LtsAppDescriptor::App appId) const;
int getNumberOfSituationMapInstances() const;
void debugSendMessage(const QString& msg);
LtsAppManager(); bool otherSessionsResponsibility(LtsSession::LtsSession* thisSession,
~LtsAppManager(); const QVector<LtsAppDescriptor::App>& requiredAppTypes,
const QVector<IDL::PartitionType>& requiredPartitionTypes,
const QString& menuGroup, const QString& identifier, LtsWidgets::LayoutArea area);
bool startAppOrLetUserChoose(const LtsAppDescriptor::AppDescription &appDescription, const LtsSession::DdsConnectionParams &connParams, bool force = false); private:
LtsPluginManager::LtsPluginManager *createApp(const LtsAppDescriptor::AppDescription &appDescription, friend struct LtsAppManagerHandler;
const LtsSession::DdsConnectionParams &connParams, friend class DeveloperTools::DevDialog;
const QString &workspaceId = QString(),
bool hidden = false, bool force = false);
void saveState();
LtsAppDescriptor::AppDescriptionVector m_availableApps; LtsAppManager();
QVector<LtsPluginManager::LtsPluginManager *> m_appList; ~LtsAppManager();
LtsLogin::LtsLogin *m_login;
LtsAppDescriptor::AppDescription m_app;
QString m_loginPluginIid;
public slots: bool startAppOrLetUserChoose(const LtsAppDescriptor::AppDescription& appDescription,
void slotLogout(); const LtsSession::DdsConnectionParams& connParams, bool force = false);
LtsPluginManager::LtsPluginManager* createApp(const LtsAppDescriptor::AppDescription& appDescription,
const LtsSession::DdsConnectionParams& connParams,
const QString& workspaceId = QString(), bool hidden = false,
bool force = false);
void saveState();
private slots: LtsAppDescriptor::AppDescriptionVector m_availableApps;
void slotQuit(); QVector<LtsPluginManager::LtsPluginManager*> m_appList;
void slotSoftQuit(); LtsLogin::LtsLogin* m_login;
void slotShowLogin(); LtsAppDescriptor::AppDescription m_app;
void slotAppDestroyed(); QString m_loginPluginIid;
void slotStartDebugServer();
void hideAllOtherBLWs(QObject *_caller);
void taskSwitch(QObject *_caller);
signals: public slots:
void signalLoginDone(); void slotLogout();
void signalLogoffDone();
void signalShowLogin(); private slots:
void signalInitializationFinished(); void slotQuit();
void signalCommand(QTcpSocket *client, const QStringList argList); void slotSoftQuit();
void slotShowLogin();
void slotAppDestroyed();
void slotStartDebugServer();
void hideAllOtherBLWs(QObject* _caller);
void taskSwitch(QObject* _caller);
signals:
void signalLoginDone();
void signalLogoffDone();
void signalShowLogin();
void signalInitializationFinished();
void signalCommand(QTcpSocket* client, const QStringList argList);
}; };
} } // namespace LtsAppManager
@@ -1,183 +1,180 @@
#include "LtsCommandLineParser.h" #include "LtsCommandLineParser.h"
#include <ngltools/ngltools_filesystem.h>
#include <QNetworkInterface>
#include <QFlags> #include <QFlags>
#include <QNetworkInterface>
#include <QSettings> #include <QSettings>
#include <QUrl> #include <QUrl>
#include <ngltools/ngltools_filesystem.h>
namespace LtsCommandLineParser namespace LtsCommandLineParser
{ {
static constexpr int s_maxDomainId = 232; static constexpr int s_maxDomainId = 232;
LtsCommandLineParser::LtsCommandLineParser(ProvideCommandLineParameterOptions opts) LtsCommandLineParser::LtsCommandLineParser(ProvideCommandLineParameterOptions opts)
: QCommandLineParser() : QCommandLineParser(), m_enabledOptions(opts)
, m_enabledOptions(opts)
{ {
if (NGL::isAppInBuildBasePath() || m_enabledOptions.testFlag(CreateDomainIdFromIp)) if (NGL::isAppInBuildBasePath() || m_enabledOptions.testFlag(CreateDomainIdFromIp))
{
const QList<QHostAddress> addresses = QNetworkInterface::allAddresses();
for (const QHostAddress &address : addresses)
{ {
if (address.isLoopback() || address.isNull()) const QList<QHostAddress> addresses = QNetworkInterface::allAddresses();
continue; for (const QHostAddress& address : addresses)
if (address.protocol() != QAbstractSocket::IPv4Protocol) {
continue; if (address.isLoopback() || address.isNull())
continue;
if (address.protocol() != QAbstractSocket::IPv4Protocol)
continue;
m_generatedDomainId = (address.toIPv4Address() & 0x000000ff) % 232;
m_generatedDomainId = (address.toIPv4Address() & 0x000000ff) % 232; if (m_generatedDomainId == 0)
if (m_generatedDomainId == 0) m_generatedDomainId = s_maxDomainId;
m_generatedDomainId = s_maxDomainId; break;
break; }
} }
}
if (m_enabledOptions.testFlag(ExerciseId)) if (m_enabledOptions.testFlag(ExerciseId))
addOption({{QStringLiteral("e"), QStringLiteral("exerciseid")}, addOption({{QStringLiteral("e"), QStringLiteral("exerciseid")},
QStringLiteral("Default: -1 (invalid, get from lts-cc.conf)"), QStringLiteral("Default: -1 (invalid, get from lts-cc.conf)"),
QStringLiteral("exerciseId"), QStringLiteral("exerciseId"),
QStringLiteral("-1") QStringLiteral("-1")});
}); if (m_enabledOptions.testFlag(DomainId))
if (m_enabledOptions.testFlag(DomainId)) addOption({{QStringLiteral("d"), QStringLiteral("domainid")},
addOption({{QStringLiteral("d"), QStringLiteral("domainid")}, QStringLiteral("Default: ") + QString::number(m_generatedDomainId),
QStringLiteral("Default: ") + QString::number(m_generatedDomainId), QStringLiteral("domainId"),
QStringLiteral("domainId"), QString::number(m_generatedDomainId)});
QString::number(m_generatedDomainId) if (m_enabledOptions.testFlag(CustomConfigFile))
}); {
if (m_enabledOptions.testFlag(CustomConfigFile)) const QString cf(NGL::findProjectConfigFile());
{ addOption({{QStringLiteral("i"), QStringLiteral("ini")},
const QString cf(NGL::findProjectConfigFile()); QStringLiteral("Default: ") + cf,
addOption({{QStringLiteral("i"), QStringLiteral("ini")}, QStringLiteral("filename"),
QStringLiteral("Default: ") + cf, cf});
QStringLiteral("filename"), }
cf if (m_enabledOptions.testFlag(TcpConnectionUrl))
}); {
} const QString defaultTcpUrl(QStringLiteral("EXCTDS01:7400"));
if (m_enabledOptions.testFlag(TcpConnectionUrl)) addOption({{QStringLiteral("t"), QStringLiteral("tcpurl")},
{ QStringLiteral("Default: ") + defaultTcpUrl,
const QString defaultTcpUrl(QStringLiteral("EXCTDS01:7400")); QStringLiteral("hostname:port"),
addOption({{QStringLiteral("t"), QStringLiteral("tcpurl")}, defaultTcpUrl});
QStringLiteral("Default: ") + defaultTcpUrl, }
QStringLiteral("hostname:port"), addHelpOption();
defaultTcpUrl
});
}
addHelpOption();
if (!m_enabledOptions.testFlag(NoVersion)) if (!m_enabledOptions.testFlag(NoVersion))
addVersionOption(); addVersionOption();
} }
int LtsCommandLineParser::domainId() const int LtsCommandLineParser::domainId() const
{ {
if (m_domainId == 0 && m_generatedDomainId != 0 && !m_domainIdSetByFunction) if (m_domainId == 0 && m_generatedDomainId != 0 && !m_domainIdSetByFunction)
{ {
#ifdef WIN32 #ifdef WIN32
fprintf(stdout, "\n\nAttention: using a default domain id != 0 because executable is run inside builddir - default domainid is %d\n\n", m_generatedDomainId); fprintf(stdout,
"\n\nAttention: using a default domain id != 0 because executable is run inside builddir - default "
"domainid is %d\n\n",
m_generatedDomainId);
#else #else
fprintf(stdout, "\n\n\e[31mAttention: using a default domain id != 0 because executable is run inside builddir - default domainid is %d\e[0m\n\n", m_generatedDomainId); fprintf(stdout,
"\n\n\e[31mAttention: using a default domain id != 0 because executable is run inside builddir - "
"default domainid is %d\e[0m\n\n",
m_generatedDomainId);
#endif #endif
return m_generatedDomainId; return m_generatedDomainId;
} }
return m_domainId; return m_domainId;
} }
void LtsCommandLineParser::setDomainId(int id) void LtsCommandLineParser::setDomainId(int id)
{ {
m_domainIdSetByFunction = true; m_domainIdSetByFunction = true;
m_domainId = id; m_domainId = id;
} }
bool LtsCommandLineParser::iniFileSet() const bool LtsCommandLineParser::iniFileSet() const
{ {
if (!m_enabledOptions.testFlag(CustomConfigFile)) if (!m_enabledOptions.testFlag(CustomConfigFile))
return false; return false;
return isSet(QStringLiteral("i")); return isSet(QStringLiteral("i"));
} }
bool LtsCommandLineParser::useTcpConnection() const bool LtsCommandLineParser::useTcpConnection() const
{ {
if (!m_enabledOptions.testFlag(TcpConnectionUrl)) if (!m_enabledOptions.testFlag(TcpConnectionUrl))
return false; return false;
return isSet(QStringLiteral("t")); return isSet(QStringLiteral("t"));
} }
QUrl LtsCommandLineParser::tcpConnectionUrl() const QUrl LtsCommandLineParser::tcpConnectionUrl() const
{ {
if (!m_enabledOptions.testFlag(TcpConnectionUrl)) if (!m_enabledOptions.testFlag(TcpConnectionUrl))
return QUrl(); return QUrl();
if (!useTcpConnection()) if (!useTcpConnection())
return QUrl(); return QUrl();
QString str = value(QStringLiteral("t")); QString str = value(QStringLiteral("t"));
str.replace(QLatin1String("tcpv4_lan"), QLatin1String("tcpv4lan")); str.replace(QLatin1String("tcpv4_lan"), QLatin1String("tcpv4lan"));
QUrl url = QUrl::fromUserInput(str); QUrl url = QUrl::fromUserInput(str);
if (url.scheme() == QLatin1String("http") || if (url.scheme() == QLatin1String("http") || url.scheme() == QLatin1String("file"))
url.scheme() == QLatin1String("file")) url.setScheme(QStringLiteral("tcpv4lan"));
url.setScheme(QStringLiteral("tcpv4lan")); return url;
return url;
} }
bool LtsCommandLineParser::init(bool bParseHelp) bool LtsCommandLineParser::init(bool bParseHelp)
{ {
if (!parse(QCoreApplication::arguments())) if (!parse(QCoreApplication::arguments()))
{
fprintf(stdout, "\nBad option: %s \n", qPrintable(errorText()));
if (!m_unitModuleTestMode)
return false;
}
if (m_enabledOptions.testFlag(ExerciseId))
m_exerciseId = value(QStringLiteral("e")).toInt();
if (m_enabledOptions.testFlag(DomainId))
m_domainId = value(QStringLiteral("d")).toInt();
if (m_enabledOptions.testFlag(CustomConfigFile))
m_iniFile = value(QStringLiteral("i"));
if (bParseHelp && isSet(QStringLiteral("h")))
showHelp();
if (!m_unitModuleTestMode && isSet(QStringLiteral("v")))
showVersion();
if (!domainIdProvided())
{
const QString iniFile = m_iniFile.isEmpty() ? NGL::findProjectConfigFile() : m_iniFile;
if (!iniFile.isEmpty())
{ {
QSettings s(iniFile, QSettings::IniFormat); fprintf(stdout, "\nBad option: %s \n", qPrintable(errorText()));
bool bOk; if (!m_unitModuleTestMode)
int domainId = s.value(QStringLiteral("Global/DomainId"), m_domainId).toInt(&bOk); return false;
if (bOk && domainId > 0 && domainId <= s_maxDomainId)
m_domainId = domainId;
} }
}
return true; if (m_enabledOptions.testFlag(ExerciseId))
m_exerciseId = value(QStringLiteral("e")).toInt();
if (m_enabledOptions.testFlag(DomainId))
m_domainId = value(QStringLiteral("d")).toInt();
if (m_enabledOptions.testFlag(CustomConfigFile))
m_iniFile = value(QStringLiteral("i"));
if (bParseHelp && isSet(QStringLiteral("h")))
showHelp();
if (!m_unitModuleTestMode && isSet(QStringLiteral("v")))
showVersion();
if (!domainIdProvided())
{
const QString iniFile = m_iniFile.isEmpty() ? NGL::findProjectConfigFile() : m_iniFile;
if (!iniFile.isEmpty())
{
QSettings s(iniFile, QSettings::IniFormat);
bool bOk;
int domainId = s.value(QStringLiteral("Global/DomainId"), m_domainId).toInt(&bOk);
if (bOk && domainId > 0 && domainId <= s_maxDomainId)
m_domainId = domainId;
}
}
return true;
} }
void LtsCommandLineParser::showHelp(int exitCode) void LtsCommandLineParser::showHelp(int exitCode)
{ {
if (!m_additionalHelpStr.isEmpty()) if (!m_additionalHelpStr.isEmpty())
fprintf(stdout, "%s", qPrintable(m_additionalHelpStr)); fprintf(stdout, "%s", qPrintable(m_additionalHelpStr));
QCommandLineParser::showHelp(exitCode);
QCommandLineParser::showHelp(exitCode);
} }
bool LtsCommandLineParser::domainIdProvided() const bool LtsCommandLineParser::domainIdProvided() const
{ {
if (!m_enabledOptions.testFlag(DomainId)) if (!m_enabledOptions.testFlag(DomainId))
return false; return false;
return isSet(QStringLiteral("d")); return isSet(QStringLiteral("d"));
} }
bool LtsCommandLineParser::exerciseIdProvided() const bool LtsCommandLineParser::exerciseIdProvided() const
{ {
if (!m_enabledOptions.testFlag(ExerciseId)) if (!m_enabledOptions.testFlag(ExerciseId))
return false; return false;
return isSet(QStringLiteral("e")); return isSet(QStringLiteral("e"));
} }
} // namespace LtsCommandLineParser
}
@@ -1,56 +1,69 @@
#pragma once #pragma once
#include <QCommandLineParser>
#include "ltscommandlineparser_export.h" #include "ltscommandlineparser_export.h"
#include <QCommandLineParser>
class QUrl; class QUrl;
namespace LtsCommandLineParser namespace LtsCommandLineParser
{ {
class LTSCOMMANDLINEPARSER_EXPORT LtsCommandLineParser : public QCommandLineParser class LTSCOMMANDLINEPARSER_EXPORT LtsCommandLineParser : public QCommandLineParser
{ {
public: public:
enum ProvideCommandLineParameterOptions enum ProvideCommandLineParameterOptions {
{ None = 0x0000,
None = 0x0000, CreateDomainIdFromIp = 0x0001,
CreateDomainIdFromIp = 0x0001, DomainId = 0x0002,
DomainId = 0x0002, ExerciseId = 0x0004,
ExerciseId = 0x0004, CustomConfigFile = 0x0008,
CustomConfigFile = 0x0008, TcpConnectionUrl = 0x0010,
TcpConnectionUrl = 0x0010, NoVersion = 0x0020
NoVersion = 0x0020 };
};
explicit LtsCommandLineParser(ProvideCommandLineParameterOptions opts = ProvideCommandLineParameterOptions(CreateDomainIdFromIp|DomainId|ExerciseId|CustomConfigFile)); explicit LtsCommandLineParser(ProvideCommandLineParameterOptions opts = ProvideCommandLineParameterOptions(
virtual ~LtsCommandLineParser() = default; CreateDomainIdFromIp | DomainId | ExerciseId | CustomConfigFile));
int domainId() const; virtual ~LtsCommandLineParser() = default;
void setDomainId(int id); int domainId() const;
int exerciseId() const { return m_exerciseId; } void setDomainId(int id);
QString iniFile() const { return m_iniFile; }
bool iniFileSet() const;
bool useTcpConnection() const;
QUrl tcpConnectionUrl() const;
virtual bool init(bool bParseHelp = true);
void showHelp(int exitCode = 0); int exerciseId() const
bool domainIdProvided() const; {
bool exerciseIdProvided() const; return m_exerciseId;
}
void setUnitModuleTestMode(bool onOff) { m_unitModuleTestMode = onOff; } QString iniFile() const
{
return m_iniFile;
}
protected: bool iniFileSet() const;
QString m_additionalHelpStr; bool useTcpConnection() const;
QUrl tcpConnectionUrl() const;
virtual bool init(bool bParseHelp = true);
private: void showHelp(int exitCode = 0);
QFlags<ProvideCommandLineParameterOptions> m_enabledOptions; bool domainIdProvided() const;
int m_exerciseId{0}; bool exerciseIdProvided() const;
int m_domainId{0};
int m_generatedDomainId{0}; void setUnitModuleTestMode(bool onOff)
bool m_domainIdSetByFunction{false}; {
bool m_unitModuleTestMode{false}; m_unitModuleTestMode = onOff;
QString m_iniFile; }
protected:
QString m_additionalHelpStr;
private:
QFlags<ProvideCommandLineParameterOptions> m_enabledOptions;
int m_exerciseId{0};
int m_domainId{0};
int m_generatedDomainId{0};
bool m_domainIdSetByFunction{false};
bool m_unitModuleTestMode{false};
QString m_iniFile;
}; };
} } // namespace LtsCommandLineParser
+52 -55
View File
@@ -1,67 +1,64 @@
#include <GeographicLib/UTMUPS.hpp>
#include <GeographicLib/MGRS.hpp> #include <GeographicLib/MGRS.hpp>
#include <GeographicLib/UTMUPS.hpp>
#include <cstring> #include <cstring>
#include <string> #include <string>
int main(int argc, char **argv) int main(int argc, char** argv)
{ {
if (argc < 3 || argc > 5) if (argc < 3 || argc > 5)
{
fprintf(stderr, "Usage: %s <lon_degree> <lat_degree> [<precision>]\n", argv[0]);
fprintf(stderr, "Usage: %s <lon_rad> <lat_rad> -r [<precision>]\n", argv[0]);
return -1;
}
bool lonLatInRad = false;
double lon = atof(argv[1]);
double lat = atof(argv[2]);
int prec = 5;
if (argc >= 4)
{
int precArgId = -1;
if (strcmp(argv[3], "-r") == 0)
{ {
lonLatInRad = true; fprintf(stderr, "Usage: %s <lon_degree> <lat_degree> [<precision>]\n", argv[0]);
if (argc == 5) fprintf(stderr, "Usage: %s <lon_rad> <lat_rad> -r [<precision>]\n", argv[0]);
precArgId = 4; return -1;
} }
else
precArgId = 3;
if (precArgId > 0)
prec = atoi(argv[precArgId]);
}
std::string mgrs; bool lonLatInRad = false;
double lon = atof(argv[1]);
double lat = atof(argv[2]);
int prec = 5;
if (argc >= 4)
{
int precArgId = -1;
if (strcmp(argv[3], "-r") == 0)
{
lonLatInRad = true;
if (argc == 5)
precArgId = 4;
}
else
precArgId = 3;
if (precArgId > 0)
prec = atoi(argv[precArgId]);
}
int zone; std::string mgrs;
bool northp;
double x, y; int zone;
try bool northp;
{ double x, y;
const double latDeg = lonLatInRad ? lat * 180 / M_PI : lat; try
const double lonDeg = lonLatInRad ? lon * 180 / M_PI : lon; {
GeographicLib::UTMUPS::Forward(latDeg, lonDeg, zone, northp, x, y); const double latDeg = lonLatInRad ? lat * 180 / M_PI : lat;
GeographicLib::MGRS::Forward(zone, northp, x, y, prec, mgrs); const double lonDeg = lonLatInRad ? lon * 180 / M_PI : lon;
} GeographicLib::UTMUPS::Forward(latDeg, lonDeg, zone, northp, x, y);
catch (...) GeographicLib::MGRS::Forward(zone, northp, x, y, prec, mgrs);
{ }
fprintf(stderr, "Error converting %9.6f, %9.6f to MGRS coords\n", lat, lon); catch (...)
return -2; {
} fprintf(stderr, "Error converting %9.6f, %9.6f to MGRS coords\n", lat, lon);
std::string part1, part2, part3, part4; return -2;
part1 = mgrs.substr(0, 3); }
part2 = mgrs.substr(3, 2); std::string part1, part2, part3, part4;
if (prec > 0) part1 = mgrs.substr(0, 3);
{ part2 = mgrs.substr(3, 2);
part3 = mgrs.substr(5, prec); if (prec > 0)
part4 = mgrs.substr(5 + prec, prec); {
} part3 = mgrs.substr(5, prec);
fprintf(stdout, "%13.10f, %13.10f = %s %s %s %s (UTM: %d %.2f, %.2f %c)\n", part4 = mgrs.substr(5 + prec, prec);
lon, lat, }
part1.c_str(), part2.c_str(), part3.c_str(), part4.c_str(), fprintf(stdout, "%13.10f, %13.10f = %s %s %s %s (UTM: %d %.2f, %.2f %c)\n", lon, lat, part1.c_str(), part2.c_str(),
zone, x, y, northp ? 'N' : 'S'); part3.c_str(), part4.c_str(), zone, x, y, northp ? 'N' : 'S');
return 0; return 0;
} }
+307 -306
View File
@@ -1,19 +1,16 @@
#include "lts_coord_trans.h" #include "lts_coord_trans.h"
#include <utility>
#include <GeographicLib/Geocentric.hpp> #include <GeographicLib/Geocentric.hpp>
#include <GeographicLib/UTMUPS.hpp>
#include <GeographicLib/MGRS.hpp> #include <GeographicLib/MGRS.hpp>
#include <GeographicLib/UTMUPS.hpp>
#include <QPointF> #include <QPointF>
#include <QRectF> #include <QRectF>
#include <QString> #include <QString>
#include <QStringList> #include <QStringList>
#include <iomanip> #include <iomanip>
#include <utility>
namespace LtsCoordTrans namespace LtsCoordTrans
{ {
@@ -27,420 +24,424 @@ static long s_conversion_counter_WGS84_Reverse = 0;
static long s_conversion_counter_UTMUPS_Forward = 0; static long s_conversion_counter_UTMUPS_Forward = 0;
static long s_conversion_counter_UTMUPS_Reverse = 0; static long s_conversion_counter_UTMUPS_Reverse = 0;
inline void incrementCounter(long& counterRef)
inline void incrementCounter(long &counterRef)
{ {
#ifdef LTS_DEBUG #ifdef LTS_DEBUG
++counterRef; ++counterRef;
#endif #endif
} }
static inline std::string cleanupMgrsString(const QString& in)
static inline std::string cleanupMgrsString(const QString &in)
{ {
const QByteArray ba(in.toLatin1()); const QByteArray ba(in.toLatin1());
std::string ret; std::string ret;
ret.reserve(ba.size()); ret.reserve(ba.size());
for (const char c : ba) for (const char c : ba)
{ {
if (c != ' ') if (c != ' ')
ret += c; ret += c;
} }
return ret; return ret;
} }
QString UtmCoordinate::mgrs(int prec, bool withSpaces) const QString UtmCoordinate::mgrs(int prec, bool withSpaces) const
{ {
if (prec < 0) if (prec < 0)
prec = 0; prec = 0;
if (prec > 11) if (prec > 11)
prec = 11; prec = 11;
std::string mgrs; std::string mgrs;
try try
{
GeographicLib::MGRS::Forward(zone, northp, x, y, prec, mgrs);
incrementCounter(s_conversion_counter_MGRS_Forward);
}
catch (const std::exception &e)
{
fprintf(stderr, "Error while calculating mgrs from utm %d, %9.6f, %9.6f: %s\n", zone, x, y, e.what());
mgrs.clear();
}
QString ret;
if (withSpaces && mgrs.size() == static_cast<size_t>(5 + 2 * prec))
{
const char *ptr = mgrs.c_str();
ret = QString::fromLatin1(ptr, 3) + QLatin1Char(' ') +
QString::fromLatin1(ptr + 3, 2);
if (prec > 0)
{ {
ret += QLatin1Char(' ') + QString::fromLatin1(ptr + 5, prec) + GeographicLib::MGRS::Forward(zone, northp, x, y, prec, mgrs);
QLatin1Char(' ') + QString::fromLatin1(ptr + 5 + prec, prec); incrementCounter(s_conversion_counter_MGRS_Forward);
} }
} catch (const std::exception& e)
else {
ret = QString::fromLatin1(mgrs.c_str(), mgrs.size()); fprintf(stderr, "Error while calculating mgrs from utm %d, %9.6f, %9.6f: %s\n", zone, x, y, e.what());
return ret; mgrs.clear();
}
QString ret;
if (withSpaces && mgrs.size() == static_cast<size_t>(5 + 2 * prec))
{
const char* ptr = mgrs.c_str();
ret = QString::fromLatin1(ptr, 3) + QLatin1Char(' ') + QString::fromLatin1(ptr + 3, 2);
if (prec > 0)
{
ret += QLatin1Char(' ') + QString::fromLatin1(ptr + 5, prec) + QLatin1Char(' ') +
QString::fromLatin1(ptr + 5 + prec, prec);
}
}
else
ret = QString::fromLatin1(mgrs.c_str(), mgrs.size());
return ret;
} }
QPointF UtmCoordinate::toPoint() const QPointF UtmCoordinate::toPoint() const
{ {
return {x,y}; return {x, y};
} }
QPointF UtmCoordinate::geographic(double offsetX, double offsetY) const QPointF UtmCoordinate::geographic(double offsetX, double offsetY) const
{ {
QPointF ret; QPointF ret;
try try
{ {
GeographicLib::UTMUPS::Reverse(zone, northp, x + offsetX, y + offsetY, ret.ry(), ret.rx()); GeographicLib::UTMUPS::Reverse(zone, northp, x + offsetX, y + offsetY, ret.ry(), ret.rx());
incrementCounter(s_conversion_counter_UTMUPS_Reverse); incrementCounter(s_conversion_counter_UTMUPS_Reverse);
} }
catch (const std::exception &e) catch (const std::exception& e)
{ {
fprintf(stderr, "Error while calculating geographic from utm %d, %9.6f, %9.6f: %s\n", zone, x + offsetX, y + offsetY, e.what()); fprintf(stderr, "Error while calculating geographic from utm %d, %9.6f, %9.6f: %s\n", zone, x + offsetX,
ret = QPointF(); y + offsetY, e.what());
} ret = QPointF();
return ret * deg2rad(); }
return ret * deg2rad();
} }
QPointF UtmCoordinate::geographic(const QPointF &offset) const QPointF UtmCoordinate::geographic(const QPointF& offset) const
{ {
return geographic(offset.x(), offset.y()); return geographic(offset.x(), offset.y());
} }
QPointF UtmCoordinate::relativeTo(const UtmCoordinate &other) const QPointF UtmCoordinate::relativeTo(const UtmCoordinate& other) const
{ {
if (zone == other.zone) if (zone == other.zone)
return QPointF(x - other.x, y - other.y); return QPointF(x - other.x, y - other.y);
UtmCoordinate otherInMyZone = fromGeographic(other.geographic(), zone); UtmCoordinate otherInMyZone = fromGeographic(other.geographic(), zone);
return QPointF(x - otherInMyZone.x, y - otherInMyZone.y); return QPointF(x - otherInMyZone.x, y - otherInMyZone.y);
} }
UtmCoordinate UtmCoordinate::fromGeographic(double lon, double lat, int setZone) UtmCoordinate UtmCoordinate::fromGeographic(double lon, double lat, int setZone)
{ {
lon *= rad2deg(); lon *= rad2deg();
lat *= rad2deg(); lat *= rad2deg();
UtmCoordinate ret; UtmCoordinate ret;
try try
{ {
GeographicLib::UTMUPS::Forward(lat, lon, ret.zone, ret.northp, ret.x, ret.y, setZone); GeographicLib::UTMUPS::Forward(lat, lon, ret.zone, ret.northp, ret.x, ret.y, setZone);
incrementCounter(s_conversion_counter_UTMUPS_Forward); incrementCounter(s_conversion_counter_UTMUPS_Forward);
} }
catch (const std::exception &e) catch (const std::exception& e)
{ {
fprintf(stderr, "Error while calculating mgrs base point from %9.6f, %9.6f: %s\n", lat, lon, e.what()); fprintf(stderr, "Error while calculating mgrs base point from %9.6f, %9.6f: %s\n", lat, lon, e.what());
ret = UtmCoordinate(); ret = UtmCoordinate();
} }
return ret; return ret;
} }
UtmCoordinate UtmCoordinate::fromGeographic(const QPointF &lonLat, int setZone) UtmCoordinate UtmCoordinate::fromGeographic(const QPointF& lonLat, int setZone)
{ {
return fromGeographic(lonLat.x(), lonLat.y(), setZone); return fromGeographic(lonLat.x(), lonLat.y(), setZone);
} }
UtmCoordinate UtmCoordinate::fromMgrs(const QString &mgrs) UtmCoordinate UtmCoordinate::fromMgrs(const QString& mgrs)
{ {
UtmCoordinate utm; UtmCoordinate utm;
try try
{ {
int prec; int prec;
GeographicLib::MGRS::Reverse(cleanupMgrsString(mgrs), utm.zone, utm.northp, utm.x, utm.y, prec, true); GeographicLib::MGRS::Reverse(cleanupMgrsString(mgrs), utm.zone, utm.northp, utm.x, utm.y, prec, true);
incrementCounter(s_conversion_counter_MGRS_Reverse); incrementCounter(s_conversion_counter_MGRS_Reverse);
}
} catch (const std::exception& e)
catch (const std::exception &e) {
{ fprintf(stderr, "Error while converting mgrs coordinate %s to utm: %s\n", qPrintable(mgrs), e.what());
fprintf(stderr, "Error while converting mgrs coordinate %s to utm: %s\n", qPrintable(mgrs), e.what()); utm = UtmCoordinate();
utm = UtmCoordinate(); }
} return utm;
return utm;
} }
QString mgrsFromGeographic(double lon, double lat, int prec, bool withSpaces) QString mgrsFromGeographic(double lon, double lat, int prec, bool withSpaces)
{ {
return UtmCoordinate::fromGeographic(lon, lat, -1).mgrs(prec, withSpaces); return UtmCoordinate::fromGeographic(lon, lat, -1).mgrs(prec, withSpaces);
} }
QPointF geographicFromMgrs(const QString &mgrs) QPointF geographicFromMgrs(const QString& mgrs)
{ {
return UtmCoordinate::fromMgrs(mgrs).geographic(); return UtmCoordinate::fromMgrs(mgrs).geographic();
} }
QVector<UtmCoordinate> &staticDefaultSquaresHelper() QVector<UtmCoordinate>& staticDefaultSquaresHelper()
{ {
static QVector<UtmCoordinate> s_defaultMgrsSquares; static QVector<UtmCoordinate> s_defaultMgrsSquares;
return s_defaultMgrsSquares; return s_defaultMgrsSquares;
}
UtmCoordinate &staticPreferedMgrsSquareHelper()
{
static UtmCoordinate s_preferedMgrsSquare;
return s_preferedMgrsSquare;
}
QVector<UtmCoordinate> &staticMgrsSquaresWithOffsetsHelper()
{
static QVector<UtmCoordinate> s_mgrsSquaresWithOffsets;
return s_mgrsSquaresWithOffsets;
} }
UtmCoordinate& staticPreferedMgrsSquareHelper()
QRectF addMarginToArea(const QRectF &rect_LatLon_radiant, const QSize &marginMeter)
{ {
double lonMin, lonMax, latMin, latMmax; static UtmCoordinate s_preferedMgrsSquare;
rect_LatLon_radiant.normalized().getCoords(&lonMin, &latMin, &lonMax, &latMmax); return s_preferedMgrsSquare;
LtsCoordTrans::UtmCoordinate basePoint;
{
const QPointF centerRad = rect_LatLon_radiant.center();
QString mgrs = LtsCoordTrans::mgrsFromGeographic(centerRad.x(), centerRad.y(), -1);
mgrs += QStringLiteral("00000000000000");
basePoint = LtsCoordTrans::UtmCoordinate::fromMgrs(mgrs);
}
const UtmCoordinate lowerLeft(UtmCoordinate::fromGeographic(lonMin, latMin, basePoint.zone));
const UtmCoordinate upperRight(UtmCoordinate::fromGeographic(lonMax, latMmax, basePoint.zone));
int offsetX = marginMeter.width();
int offsetY = marginMeter.height();
const QPointF topLeft(lowerLeft.geographic(-offsetX, -offsetY));
const QPointF bottomRight(upperRight.geographic(offsetX, offsetY));
QRectF res = QRectF(topLeft, bottomRight);
return res;
} }
QVector<UtmCoordinate>& staticMgrsSquaresWithOffsetsHelper()
QVector<UtmCoordinate> getMgrsSquares(const QRectF &rect, bool setAsDefaultSquares, bool setAsPreferedSquare, bool setAsSquareWithMargin)
{ {
QVector<UtmCoordinate> ret = getMgrsSquaresInternal(rect); static QVector<UtmCoordinate> s_mgrsSquaresWithOffsets;
return s_mgrsSquaresWithOffsets;
if (setAsDefaultSquares)
staticDefaultSquaresHelper() = ret;
if (setAsPreferedSquare)
staticPreferedMgrsSquareHelper() = LtsCoordTrans::UtmCoordinate::fromGeographic(rect.center());
if (setAsSquareWithMargin)
staticMgrsSquaresWithOffsetsHelper() = ret;
return ret;
} }
QVector<UtmCoordinate> getMgrsSquaresInternal(const QRectF &rect) QRectF addMarginToArea(const QRectF& rect_LatLon_radiant, const QSize& marginMeter)
{ {
QVector<UtmCoordinate> ret; double lonMin, lonMax, latMin, latMmax;
QVector<QString> tmpMgrsSquares; rect_LatLon_radiant.normalized().getCoords(&lonMin, &latMin, &lonMax, &latMmax);
LtsCoordTrans::UtmCoordinate basePoint;
double lonMin, lonMax, latMin, latMmax;
rect.normalized().getCoords(&lonMin, &latMin, &lonMax, &latMmax);
bool withInSingleUtmSquare = true;
{
const UtmCoordinate upperRight(UtmCoordinate::fromGeographic(lonMax, latMmax));
const UtmCoordinate lowerLeft(UtmCoordinate::fromGeographic(lonMin, latMin));
withInSingleUtmSquare = upperRight.zone == lowerLeft.zone;
}
LtsCoordTrans::UtmCoordinate basePoint;
{
QPointF centerRad = rect.center();
QString mgrs = LtsCoordTrans::mgrsFromGeographic(centerRad.x(), centerRad.y(), -1);
mgrs += QStringLiteral("00000000000000");
basePoint = LtsCoordTrans::UtmCoordinate::fromMgrs(mgrs);
}
const UtmCoordinate upperRight(UtmCoordinate::fromGeographic(lonMax, latMmax, basePoint.zone));
const UtmCoordinate lowerLeft(UtmCoordinate::fromGeographic(lonMin, latMin, basePoint.zone));
const double maxX(upperRight.x - lowerLeft.x);
const double maxY(upperRight.y - lowerLeft.y);
const int increment = withInSingleUtmSquare ? 10000 : 1000;
for (double x = 0; x <= maxX + increment; x += increment)
{
const double xOfs = std::min(x, maxX);
for (double y = 0; y <= maxY + increment; y += increment)
{ {
const double yOfs = std::min(y, maxY);
const UtmCoordinate utm(UtmCoordinate::fromGeographic(lowerLeft.geographic(xOfs, yOfs))); const QPointF centerRad = rect_LatLon_radiant.center();
const QString mgrs(utm.mgrs(0)); QString mgrs = LtsCoordTrans::mgrsFromGeographic(centerRad.x(), centerRad.y(), -1);
mgrs += QStringLiteral("00000000000000");
if (!tmpMgrsSquares.contains(mgrs)) basePoint = LtsCoordTrans::UtmCoordinate::fromMgrs(mgrs);
{
tmpMgrsSquares += mgrs;
ret += utm;
}
} }
}
return ret; const UtmCoordinate lowerLeft(UtmCoordinate::fromGeographic(lonMin, latMin, basePoint.zone));
const UtmCoordinate upperRight(UtmCoordinate::fromGeographic(lonMax, latMmax, basePoint.zone));
int offsetX = marginMeter.width();
int offsetY = marginMeter.height();
const QPointF topLeft(lowerLeft.geographic(-offsetX, -offsetY));
const QPointF bottomRight(upperRight.geographic(offsetX, offsetY));
QRectF res = QRectF(topLeft, bottomRight);
return res;
} }
QStringList getMgrsSurroundingSquares(const QRectF &geoRect, const QSize &offsetMeter) QVector<UtmCoordinate> getMgrsSquares(const QRectF& rect, bool setAsDefaultSquares, bool setAsPreferedSquare,
bool setAsSquareWithMargin)
{
QVector<UtmCoordinate> ret = getMgrsSquaresInternal(rect);
if (setAsDefaultSquares)
staticDefaultSquaresHelper() = ret;
if (setAsPreferedSquare)
staticPreferedMgrsSquareHelper() = LtsCoordTrans::UtmCoordinate::fromGeographic(rect.center());
if (setAsSquareWithMargin)
staticMgrsSquaresWithOffsetsHelper() = ret;
return ret;
}
QVector<UtmCoordinate> getMgrsSquaresInternal(const QRectF& rect)
{
QVector<UtmCoordinate> ret;
QVector<QString> tmpMgrsSquares;
double lonMin, lonMax, latMin, latMmax;
rect.normalized().getCoords(&lonMin, &latMin, &lonMax, &latMmax);
bool withInSingleUtmSquare = true;
{
const UtmCoordinate upperRight(UtmCoordinate::fromGeographic(lonMax, latMmax));
const UtmCoordinate lowerLeft(UtmCoordinate::fromGeographic(lonMin, latMin));
withInSingleUtmSquare = upperRight.zone == lowerLeft.zone;
}
LtsCoordTrans::UtmCoordinate basePoint;
{
QPointF centerRad = rect.center();
QString mgrs = LtsCoordTrans::mgrsFromGeographic(centerRad.x(), centerRad.y(), -1);
mgrs += QStringLiteral("00000000000000");
basePoint = LtsCoordTrans::UtmCoordinate::fromMgrs(mgrs);
}
const UtmCoordinate upperRight(UtmCoordinate::fromGeographic(lonMax, latMmax, basePoint.zone));
const UtmCoordinate lowerLeft(UtmCoordinate::fromGeographic(lonMin, latMin, basePoint.zone));
const double maxX(upperRight.x - lowerLeft.x);
const double maxY(upperRight.y - lowerLeft.y);
const int increment = withInSingleUtmSquare ? 10000 : 1000;
for (double x = 0; x <= maxX + increment; x += increment)
{
const double xOfs = std::min(x, maxX);
for (double y = 0; y <= maxY + increment; y += increment)
{
const double yOfs = std::min(y, maxY);
const UtmCoordinate utm(UtmCoordinate::fromGeographic(lowerLeft.geographic(xOfs, yOfs)));
const QString mgrs(utm.mgrs(0));
if (!tmpMgrsSquares.contains(mgrs))
{
tmpMgrsSquares += mgrs;
ret += utm;
}
}
}
return ret;
}
QStringList getMgrsSurroundingSquares(const QRectF& geoRect, const QSize& offsetMeter)
{ {
const QVector<UtmCoordinate> mainUtms = getMgrsSquaresInternal(geoRect); const QVector<UtmCoordinate> mainUtms = getMgrsSquaresInternal(geoRect);
QStringList mainSquares; QStringList mainSquares;
mainSquares.reserve(mainUtms.count()); mainSquares.reserve(mainUtms.count());
for (const auto &utm : mainUtms) for (const auto& utm : mainUtms)
mainSquares.append(utm.mgrs(0)); mainSquares.append(utm.mgrs(0));
const QRectF rectWithOffset = addMarginToArea(geoRect, offsetMeter);
const QRectF rectWithOffset = addMarginToArea(geoRect,offsetMeter); QVector<UtmCoordinate> mainUtmsWithOffset = getMgrsSquaresInternal(rectWithOffset);
QStringList mainSquaresWithOffset;
mainSquaresWithOffset.reserve(mainUtmsWithOffset.count());
for (const auto& utm : std::as_const(mainUtmsWithOffset))
mainSquaresWithOffset.append(utm.mgrs(0));
QVector<UtmCoordinate> mainUtmsWithOffset = getMgrsSquaresInternal(rectWithOffset); QStringList surroundingSquares;
QStringList mainSquaresWithOffset; surroundingSquares.reserve(mainSquaresWithOffset.count());
mainSquaresWithOffset.reserve(mainUtmsWithOffset.count()); for (const auto& mgrs0 : mainSquaresWithOffset)
for (const auto &utm : std::as_const(mainUtmsWithOffset)) {
mainSquaresWithOffset.append(utm.mgrs(0)); if (!mainSquares.contains(mgrs0))
surroundingSquares.append(mgrs0);
}
return surroundingSquares;
QStringList surroundingSquares;
surroundingSquares.reserve(mainSquaresWithOffset.count());
for (const auto & mgrs0 : mainSquaresWithOffset)
{
if (!mainSquares.contains(mgrs0))
surroundingSquares.append(mgrs0);
}
return surroundingSquares;
} }
QVector<UtmCoordinate> defaultMgrsSquareWithOffsets() QVector<UtmCoordinate> defaultMgrsSquareWithOffsets()
{ {
return staticMgrsSquaresWithOffsetsHelper(); return staticMgrsSquaresWithOffsetsHelper();
} }
void setDefaultMgrsSquares(const QVector<QString>& squares)
void setDefaultMgrsSquares(const QVector<QString> &squares)
{ {
QVector<UtmCoordinate> coords; QVector<UtmCoordinate> coords;
coords.reserve(squares.size()); coords.reserve(squares.size());
for (const QString &s : squares) for (const QString& s : squares)
coords += UtmCoordinate::fromMgrs(s + QStringLiteral("00000000000000")); coords += UtmCoordinate::fromMgrs(s + QStringLiteral("00000000000000"));
staticDefaultSquaresHelper() = coords; staticDefaultSquaresHelper() = coords;
} }
QVector<UtmCoordinate> defaultMgrsSquares() QVector<UtmCoordinate> defaultMgrsSquares()
{ {
return staticDefaultSquaresHelper(); return staticDefaultSquaresHelper();
} }
UtmCoordinate preferedMgrsSquare() UtmCoordinate preferedMgrsSquare()
{ {
return staticPreferedMgrsSquareHelper(); return staticPreferedMgrsSquareHelper();
} }
bool lonLatAltToGeocentric(double lon, double lat, double altitude, double& xOut, double& yOut, double& zOut)
bool lonLatAltToGeocentric(double lon, double lat, double altitude, double &xOut, double &yOut, double &zOut)
{ {
lon *= rad2deg(); lon *= rad2deg();
lat *= rad2deg(); lat *= rad2deg();
try try
{ {
GeographicLib::Geocentric::WGS84().Forward(lat, lon, altitude, xOut, yOut, zOut); GeographicLib::Geocentric::WGS84().Forward(lat, lon, altitude, xOut, yOut, zOut);
incrementCounter(s_conversion_counter_WGS84_Forward); incrementCounter(s_conversion_counter_WGS84_Forward);
} }
catch (...) catch (...)
{ {
xOut = 0; xOut = 0;
yOut = 0; yOut = 0;
zOut = 0; zOut = 0;
return false; return false;
} }
return true; return true;
} }
bool geocentric2LonLatAlt(double x, double y, double z, bool geocentric2LonLatAlt(double x, double y, double z, double& lon, double& lat, double& altitude)
double &lon, double &lat, double &altitude)
{ {
try
{
GeographicLib::Geocentric::WGS84().Reverse(x, y, z, lat, lon, altitude);
incrementCounter(s_conversion_counter_WGS84_Reverse);
}
catch (...)
{
lon = 0;
lat = 0;
altitude = 0;
return false;
}
try lon *= deg2rad();
{ lat *= deg2rad();
GeographicLib::Geocentric::WGS84().Reverse(x, y, z, lat, lon, altitude); return true;
incrementCounter(s_conversion_counter_WGS84_Reverse);
}
catch (...)
{
lon = 0;
lat = 0;
altitude = 0;
return false;
}
lon *= deg2rad();
lat *= deg2rad();
return true;
} }
double distance(const QPointF &p1, const QPointF &p2) double distance(const QPointF& p1, const QPointF& p2)
{ {
return distance(p1.x(), p1.y(), p2.x(), p2.y()); return distance(p1.x(), p1.y(), p2.x(), p2.y());
} }
double squareDistance(const QPointF &p1, const QPointF &p2) double squareDistance(const QPointF& p1, const QPointF& p2)
{ {
return squareDistance(p1.x(), p1.y(), p2.x(), p2.y()); return squareDistance(p1.x(), p1.y(), p2.x(), p2.y());
} }
std::ostream &operator<< (std::ostream &stream, std::ostream& operator<<(std::ostream& stream, const UtmCoordinate& coord)
const UtmCoordinate &coord)
{ {
stream << "UtmCoordinate(" << std::setprecision(8) << coord.x stream << "UtmCoordinate(" << std::setprecision(8) << coord.x << "#" << std::setprecision(8) << coord.y
<< "#" << std::setprecision(8) << coord.y << " zone=" << coord.zone << ")";
<< " zone=" << coord.zone << ")"; return stream;
return stream;
} }
void dumpConversionCounter() void dumpConversionCounter()
{ {
fprintf(stderr, "LtsCoordTrans: s_conversion_counter_MGRS_Forward : - mgrs : %ld\n" , s_conversion_counter_MGRS_Forward); fprintf(stderr, "LtsCoordTrans: s_conversion_counter_MGRS_Forward : - mgrs : %ld\n",
fprintf(stderr, "LtsCoordTrans: s_conversion_counter_MGRS_Reverse - fromMgrs : %ld\n" , s_conversion_counter_MGRS_Reverse); s_conversion_counter_MGRS_Forward);
fprintf(stderr, "LtsCoordTrans: s_conversion_counter_WGS84_Forward - lonLatAltToGeocentric : %ld\n" , s_conversion_counter_WGS84_Forward); fprintf(stderr, "LtsCoordTrans: s_conversion_counter_MGRS_Reverse - fromMgrs : %ld\n",
fprintf(stderr, "LtsCoordTrans: s_conversion_counter_WGS84_Reverse - geocentric2LonLatAlt : %ld\n" , s_conversion_counter_WGS84_Reverse); s_conversion_counter_MGRS_Reverse);
fprintf(stderr, "LtsCoordTrans: s_conversion_counter_UTMUPS_Forward - fromGeographic : %ld\n" , s_conversion_counter_UTMUPS_Forward); fprintf(stderr, "LtsCoordTrans: s_conversion_counter_WGS84_Forward - lonLatAltToGeocentric : %ld\n",
fprintf(stderr, "LtsCoordTrans: s_conversion_counter_UTMUPS_Reverse - geographic : %ld\n" , s_conversion_counter_UTMUPS_Reverse); s_conversion_counter_WGS84_Forward);
fprintf(stderr, "LtsCoordTrans: s_conversion_counter_WGS84_Reverse - geocentric2LonLatAlt : %ld\n",
s_conversion_counter_WGS84_Reverse);
fprintf(stderr, "LtsCoordTrans: s_conversion_counter_UTMUPS_Forward - fromGeographic : %ld\n",
s_conversion_counter_UTMUPS_Forward);
fprintf(stderr, "LtsCoordTrans: s_conversion_counter_UTMUPS_Reverse - geographic : %ld\n",
s_conversion_counter_UTMUPS_Reverse);
} }
long getConversionCounter_MGRS_Forward() { return s_conversion_counter_MGRS_Forward; } long getConversionCounter_MGRS_Forward()
long getConversionCounter_MGRS_Reverse() { return s_conversion_counter_MGRS_Reverse; } {
long getConversionCounter_WGS84_Forward() { return s_conversion_counter_WGS84_Forward; } return s_conversion_counter_MGRS_Forward;
long getConversionCounter_WGS84_Reverse() { return s_conversion_counter_WGS84_Reverse; }
long getConversionCounter_UTMUPS_Forward() { return s_conversion_counter_UTMUPS_Forward; }
long getConversionCounter_UTMUPS_Reverse() { return s_conversion_counter_UTMUPS_Reverse; }
} }
long getConversionCounter_MGRS_Reverse()
{
return s_conversion_counter_MGRS_Reverse;
}
long getConversionCounter_WGS84_Forward()
{
return s_conversion_counter_WGS84_Forward;
}
long getConversionCounter_WGS84_Reverse()
{
return s_conversion_counter_WGS84_Reverse;
}
long getConversionCounter_UTMUPS_Forward()
{
return s_conversion_counter_UTMUPS_Forward;
}
long getConversionCounter_UTMUPS_Reverse()
{
return s_conversion_counter_UTMUPS_Reverse;
}
} // namespace LtsCoordTrans
+100 -160
View File
@@ -1,13 +1,11 @@
#pragma once #pragma once
#include <ltscoordtrans_export.h>
#include <string>
#include <cmath>
#include <QVector> #include <QVector>
#include <cmath>
#include <ltscoordtrans_export.h>
#include <string>
class QPointF; class QPointF;
class QRectF; class QRectF;
class QSize; class QSize;
@@ -16,175 +14,129 @@ class QString;
namespace LtsCoordTrans namespace LtsCoordTrans
{ {
inline Q_CONSTEXPR double pi()
{
return M_PI;
}
inline Q_CONSTEXPR double deg2rad()
{
return pi() / 180.;
}
inline Q_CONSTEXPR double rad2deg()
inline Q_CONSTEXPR double pi() { return M_PI; } {
inline Q_CONSTEXPR double deg2rad() { return pi() / 180.; } return 1. / deg2rad();
inline Q_CONSTEXPR double rad2deg() { return 1. / deg2rad(); } }
struct LTSCOORDTRANS_EXPORT UtmCoordinate struct LTSCOORDTRANS_EXPORT UtmCoordinate
{ {
int zone = -1; int zone = -1;
bool northp = true; bool northp = true;
double x = 0.; double x = 0.;
double y = 0.; double y = 0.;
UtmCoordinate() = default; UtmCoordinate() = default;
UtmCoordinate(int zone_, double x_, double y_, bool northp_ = true)
: zone(zone_)
, northp(northp_)
, x(x_)
, y(y_)
{}
UtmCoordinate(int zone_, double x_, double y_, bool northp_ = true) : zone(zone_), northp(northp_), x(x_), y(y_) {}
bool isValid() const
{
return zone > 0 && zone <= 60;
}
bool isValid() const { return zone > 0 && zone <= 60; } QString mgrs(int prec = 5, bool withSpaces = true) const;
QPointF toPoint() const;
QPointF geographic(double offsetX = 0., double offsetY = 0.) const;
QString mgrs(int prec = 5, bool withSpaces = true) const; QPointF geographic(const QPointF& offset) const;
QPointF toPoint() const; QPointF relativeTo(const UtmCoordinate& other) const;
static UtmCoordinate fromGeographic(double lon, double lat, int setZone = -1);
static UtmCoordinate fromGeographic(const QPointF& lonLat, int setZone = -1);
QPointF geographic(double offsetX = 0., double offsetY = 0.) const; static UtmCoordinate fromMgrs(const QString& mgrs);
QPointF geographic(const QPointF &offset) const;
QPointF relativeTo(const UtmCoordinate &other) const;
static UtmCoordinate fromGeographic(double lon, double lat, int setZone = -1);
static UtmCoordinate fromGeographic(const QPointF &lonLat, int setZone = -1);
static UtmCoordinate fromMgrs(const QString &mgrs);
}; };
LTSCOORDTRANS_EXPORT QString mgrsFromGeographic(double lon, double lat, int prec = 5, bool withSpaces = true); LTSCOORDTRANS_EXPORT QString mgrsFromGeographic(double lon, double lat, int prec = 5, bool withSpaces = true);
LTSCOORDTRANS_EXPORT QPointF geographicFromMgrs(const QString& mgrs);
LTSCOORDTRANS_EXPORT QRectF addMarginToArea(const QRectF& rect_LatLon_radiant, const QSize& marginMeter);
LTSCOORDTRANS_EXPORT QPointF geographicFromMgrs(const QString &mgrs); LTSCOORDTRANS_EXPORT QVector<UtmCoordinate> getMgrsSquares(const QRectF& rect, bool setAsDefaultSquares,
bool setAsPreferedSquare,
bool setAsSquareWithMargin = false);
LTSCOORDTRANS_EXPORT QRectF addMarginToArea(const QRectF &rect_LatLon_radiant, const QSize &marginMeter);
LTSCOORDTRANS_EXPORT QVector<UtmCoordinate> getMgrsSquares(const QRectF &rect, bool setAsDefaultSquares, bool setAsPreferedSquare, bool setAsSquareWithMargin = false);
QVector<UtmCoordinate> getMgrsSquaresInternal(const QRectF &rect);
QStringList getMgrsSurroundingSquares(const QRectF &geoRect, const QSize &offsetMeter);
QVector<UtmCoordinate> getMgrsSquaresInternal(const QRectF& rect);
QStringList getMgrsSurroundingSquares(const QRectF& geoRect, const QSize& offsetMeter);
LTSCOORDTRANS_EXPORT QVector<UtmCoordinate> defaultMgrsSquareWithOffsets(); LTSCOORDTRANS_EXPORT QVector<UtmCoordinate> defaultMgrsSquareWithOffsets();
LTSCOORDTRANS_EXPORT void setDefaultMgrsSquares(const QVector<QString>& squares);
LTSCOORDTRANS_EXPORT void setDefaultMgrsSquares(const QVector<QString> &squares);
LTSCOORDTRANS_EXPORT QVector<UtmCoordinate> defaultMgrsSquares(); LTSCOORDTRANS_EXPORT QVector<UtmCoordinate> defaultMgrsSquares();
LTSCOORDTRANS_EXPORT UtmCoordinate preferedMgrsSquare(); LTSCOORDTRANS_EXPORT UtmCoordinate preferedMgrsSquare();
LTSCOORDTRANS_EXPORT bool lonLatAltToGeocentric(double lon, double lat, double altitude, double& xOut, double& yOut,
double& zOut);
LTSCOORDTRANS_EXPORT bool geocentric2LonLatAlt(double x, double y, double z, double& lon, double& lat,
double& altitude);
LTSCOORDTRANS_EXPORT bool lonLatAltToGeocentric(double lon, double lat, double altitude, double &xOut, double &yOut, double &zOut); inline double squareDistance(const UtmCoordinate& p1, const UtmCoordinate& p2)
LTSCOORDTRANS_EXPORT bool geocentric2LonLatAlt(double x, double y, double z,
double &lon, double &lat, double &altitude);
inline double squareDistance(const UtmCoordinate &p1, const UtmCoordinate &p2)
{ {
if (p1.zone != p2.zone) if (p1.zone != p2.zone)
{ {
Q_ASSERT(false); Q_ASSERT(false);
return std::nan(""); return std::nan("");
} }
return std::pow(p1.x - p2.x, 2) + std::pow(p1.y - p2.y, 2); return std::pow(p1.x - p2.x, 2) + std::pow(p1.y - p2.y, 2);
} }
LTSCOORDTRANS_EXPORT double squareDistance(const QPointF& p1, const QPointF& p2);
LTSCOORDTRANS_EXPORT double squareDistance(const QPointF &p1, const QPointF &p2);
inline double squareDistance(const double lon1, const double lat1, const double lon2, const double lat2) inline double squareDistance(const double lon1, const double lat1, const double lon2, const double lat2)
{ {
const auto p1(UtmCoordinate::fromGeographic(lon1, lat1)); const auto p1(UtmCoordinate::fromGeographic(lon1, lat1));
const auto p2(UtmCoordinate::fromGeographic(lon2, lat2, p1.zone)); const auto p2(UtmCoordinate::fromGeographic(lon2, lat2, p1.zone));
return squareDistance(p1, p2); return squareDistance(p1, p2);
} }
inline double squareDistance(const UtmCoordinate& p1, const double lon2, const double lat2)
inline double squareDistance(const UtmCoordinate &p1, const double lon2, const double lat2)
{ {
const auto p2(UtmCoordinate::fromGeographic(lon2, lat2, p1.zone)); const auto p2(UtmCoordinate::fromGeographic(lon2, lat2, p1.zone));
return squareDistance(p1, p2); return squareDistance(p1, p2);
} }
inline double distance(const UtmCoordinate& p1, const UtmCoordinate& p2)
inline double distance(const UtmCoordinate &p1, const UtmCoordinate &p2)
{ {
if (p1.zone != p2.zone) if (p1.zone != p2.zone)
{ {
Q_ASSERT(false); Q_ASSERT(false);
return std::nan(""); return std::nan("");
} }
return sqrt(squareDistance(p1, p2)); return sqrt(squareDistance(p1, p2));
} }
LTSCOORDTRANS_EXPORT double distance(const QPointF& p1, const QPointF& p2);
LTSCOORDTRANS_EXPORT double distance(const QPointF &p1, const QPointF &p2);
inline double distance(const double lon1, const double lat1, const double lon2, const double lat2) inline double distance(const double lon1, const double lat1, const double lon2, const double lat2)
{ {
return sqrt(squareDistance(lon1, lat1, lon2, lat2)); return sqrt(squareDistance(lon1, lat1, lon2, lat2));
} }
inline double distance(const UtmCoordinate &p1, const double lon2, const double lat2) inline double distance(const UtmCoordinate& p1, const double lon2, const double lat2)
{ {
return sqrt(squareDistance(p1, lon2, lat2)); return sqrt(squareDistance(p1, lon2, lat2));
} }
LTSCOORDTRANS_EXPORT void dumpConversionCounter(); LTSCOORDTRANS_EXPORT void dumpConversionCounter();
LTSCOORDTRANS_EXPORT long getConversionCounter_MGRS_Forward(); LTSCOORDTRANS_EXPORT long getConversionCounter_MGRS_Forward();
@@ -194,56 +146,44 @@ LTSCOORDTRANS_EXPORT long getConversionCounter_WGS84_Reverse();
LTSCOORDTRANS_EXPORT long getConversionCounter_UTMUPS_Forward(); LTSCOORDTRANS_EXPORT long getConversionCounter_UTMUPS_Forward();
LTSCOORDTRANS_EXPORT long getConversionCounter_UTMUPS_Reverse(); LTSCOORDTRANS_EXPORT long getConversionCounter_UTMUPS_Reverse();
LTSCOORDTRANS_EXPORT std::ostream& operator<<(std::ostream& stream, const UtmCoordinate& coord);
LTSCOORDTRANS_EXPORT std::ostream &operator<< (std::ostream &stream,
const UtmCoordinate &coord);
class LTSCOORDTRANS_EXPORT UtmCoordinate3D : public LtsCoordTrans::UtmCoordinate class LTSCOORDTRANS_EXPORT UtmCoordinate3D : public LtsCoordTrans::UtmCoordinate
{ {
using BaseClass = LtsCoordTrans::UtmCoordinate; using BaseClass = LtsCoordTrans::UtmCoordinate;
public: public:
UtmCoordinate3D() UtmCoordinate3D()
{ {
reset(); reset();
} }
explicit UtmCoordinate3D(const LtsCoordTrans::UtmCoordinate &utm2d, double _zValue = std::nan("")) explicit UtmCoordinate3D(const LtsCoordTrans::UtmCoordinate& utm2d, double _zValue = std::nan("")) : BaseClass()
:BaseClass() {
{ zone = utm2d.zone;
zone = utm2d.zone; northp = utm2d.northp;
northp = utm2d.northp; x = utm2d.x;
x = utm2d.x; y = utm2d.y;
y = utm2d.y; zValue = _zValue;
zValue = _zValue; }
}
void reset() void reset()
{ {
zone = -1; zone = -1;
northp = true; northp = true;
x = 0.;
y = 0.;
zValue = std::nan("");
}
double z() const
{
return zValue;
}
protected:
double zValue{std::nan("")};
x = 0.;
y = 0.;
zValue = std::nan("");
}
double z() const { return zValue; }
protected:
double zValue{std::nan("")};
}; };
} // namespace LtsCoordTrans
}
+262 -332
View File
@@ -1,470 +1,400 @@
#include "lts_coord_trans_unit_test.h" #include "lts_coord_trans_unit_test.h"
#include <utility>
#include "lts_coord_trans.h" #include "lts_coord_trans.h"
#include <GeographicLib/Math.hpp> #include <GeographicLib/Math.hpp>
#include <QTest>
#include <QDebug> #include <QDebug>
#include <QTest>
#include <utility>
QTEST_MAIN(coordtrans_test) QTEST_MAIN(coordtrans_test)
void coordtrans_test::initTestCase() void coordtrans_test::initTestCase()
{ {
qDebug("sizeof(UtmCoordinate) = %lu", sizeof(LtsCoordTrans::UtmCoordinate)); qDebug("sizeof(UtmCoordinate) = %lu", sizeof(LtsCoordTrans::UtmCoordinate));
} }
void coordtrans_test::cleanupTestCase() void coordtrans_test::cleanupTestCase() {}
{}
void coordtrans_test::testFromGeographic() void coordtrans_test::testFromGeographic()
{ {
LtsCoordTrans::UtmCoordinate utm;
QPointF lonlat;
lonlat = QPointF(8.6264954126, 53.1138437183) * LtsCoordTrans::deg2rad();
utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y(), -1);
QCOMPARE(utm.mgrs(0), QStringLiteral("32U MD"));
utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y());
QCOMPARE(utm.mgrs(8), QStringLiteral("32U MD 74999999 84999999"));
LtsCoordTrans::UtmCoordinate utm; lonlat = QPointF(11.3003696521, 52.8224535191) * LtsCoordTrans::deg2rad();
QPointF lonlat; utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y(), -1);
QCOMPARE(utm.mgrs(0), QStringLiteral("32U PD"));
utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y());
QCOMPARE(utm.mgrs(5), QStringLiteral("32U PD 55000 55000"));
lonlat = QPointF(8.6264954126, 53.1138437183) * LtsCoordTrans::deg2rad(); lonlat = QPointF(54.8821607021, 24.2631973752) * LtsCoordTrans::deg2rad();
utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y(), -1); utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y(), -1);
QCOMPARE(utm.mgrs(0), QStringLiteral("32U MD")); QCOMPARE(utm.mgrs(0), QStringLiteral("40R BM"));
utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y()); utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y());
QCOMPARE(utm.mgrs(8), QStringLiteral("32U MD 74999999 84999999")); QCOMPARE(utm.mgrs(5), QStringLiteral("40R BM 85000 85000"));
lonlat = QPointF(11.3003696521, 52.8224535191) * LtsCoordTrans::deg2rad(); utm = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("40R BM 00000 00000"));
utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y(), -1); QCOMPARE(utm.mgrs(0), QStringLiteral("40Q BM"));
QCOMPARE(utm.mgrs(0), QStringLiteral("32U PD"));
utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y());
QCOMPARE(utm.mgrs(5), QStringLiteral("32U PD 55000 55000"));
lonlat = QPointF(54.8821607021, 24.2631973752) * LtsCoordTrans::deg2rad();
utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y(), -1);
QCOMPARE(utm.mgrs(0), QStringLiteral("40R BM"));
utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y());
QCOMPARE(utm.mgrs(5), QStringLiteral("40R BM 85000 85000"));
utm = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("40R BM 00000 00000"));
QCOMPARE(utm.mgrs(0), QStringLiteral("40Q BM"));
} }
void coordtrans_test::testMgrsFromGeographic() void coordtrans_test::testMgrsFromGeographic()
{ {
QString mgrs; QString mgrs;
QPointF lonlat; QPointF lonlat;
lonlat = QPointF(8.6191049344, 53.1048309844) * LtsCoordTrans::deg2rad(); lonlat = QPointF(8.6191049344, 53.1048309844) * LtsCoordTrans::deg2rad();
mgrs = LtsCoordTrans::mgrsFromGeographic(lonlat.x(), lonlat.y(), 9); mgrs = LtsCoordTrans::mgrsFromGeographic(lonlat.x(), lonlat.y(), 9);
QCOMPARE(mgrs, QStringLiteral("32U MD 745000000 840000000")); QCOMPARE(mgrs, QStringLiteral("32U MD 745000000 840000000"));
mgrs = LtsCoordTrans::mgrsFromGeographic(lonlat.x(), lonlat.y(), 8, false); mgrs = LtsCoordTrans::mgrsFromGeographic(lonlat.x(), lonlat.y(), 8, false);
QCOMPARE(mgrs, QStringLiteral("32UMD7450000084000000")); QCOMPARE(mgrs, QStringLiteral("32UMD7450000084000000"));
} }
void coordtrans_test::testRelativeMetricalOffet_data() void coordtrans_test::testRelativeMetricalOffet_data()
{ {
QTest::addColumn<QPoint>("offset"); QTest::addColumn<QPoint>("offset");
QTest::addColumn<QString>("correctMgrs"); QTest::addColumn<QString>("correctMgrs");
QTest::newRow("set 1") << QPoint(5, 5) << QStringLiteral("32U PD 99995 99995");
QTest::newRow("set 1") << QPoint( 5, 5) << QStringLiteral("32U PD 99995 99995"); QTest::newRow("set 2") << QPoint(100, 100) << QStringLiteral("32U QE 00090 00090");
QTest::newRow("set 3") << QPoint(500, 500) << QStringLiteral("32U QE 00490 00490");
QTest::newRow("set 2") << QPoint(100, 100) << QStringLiteral("32U QE 00090 00090");
QTest::newRow("set 3") << QPoint(500, 500) << QStringLiteral("32U QE 00490 00490");
} }
void coordtrans_test::testRelativeMetricalOffet() void coordtrans_test::testRelativeMetricalOffet()
{ {
QFETCH(QPoint, offset); QFETCH(QPoint, offset);
QFETCH(QString, correctMgrs); QFETCH(QString, correctMgrs);
const LtsCoordTrans::UtmCoordinate &utmRef = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 99990 99990")); const LtsCoordTrans::UtmCoordinate& utmRef =
qDebug() << "utmRef = " << utmRef.mgrs(); LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 99990 99990"));
qDebug() << "utmRef = " << utmRef.mgrs();
{ {
LtsCoordTrans::UtmCoordinate utmRaw; LtsCoordTrans::UtmCoordinate utmRaw;
utmRaw.x = utmRef.x + offset.x(); utmRaw.x = utmRef.x + offset.x();
utmRaw.y = utmRef.y + offset.y(); utmRaw.y = utmRef.y + offset.y();
utmRaw.zone = utmRef.zone; utmRaw.zone = utmRef.zone;
qDebug() << "offset = " << offset << " - utmRaw = " << utmRaw.mgrs(); qDebug() << "offset = " << offset << " - utmRaw = " << utmRaw.mgrs();
QCOMPARE(utmRaw.mgrs(), correctMgrs); QCOMPARE(utmRaw.mgrs(), correctMgrs);
} }
{
const LtsCoordTrans::UtmCoordinate utmSimple(utmRef.zone, utmRef.x + offset.x(), utmRef.y + offset.y());
qDebug() << "offset = " << offset << " - utmSimple = " << utmSimple.mgrs();
QCOMPARE(utmSimple.mgrs(), correctMgrs);
{ }
const LtsCoordTrans::UtmCoordinate utmSimple(utmRef.zone,
utmRef.x + offset.x(),
utmRef.y + offset.y());
qDebug() << "offset = " << offset << " - utmSimple = " << utmSimple.mgrs();
QCOMPARE(utmSimple.mgrs(), correctMgrs);
}
} }
QRectF createArea(const QString &base, QRectF createArea(const QString& base, int xCenter, int yCenter, int width, int height)
int xCenter, int yCenter, int width, int height)
{ {
QRectF areaRect = QRectF(xCenter - width / 2, yCenter - height / 2, width, height); QRectF areaRect = QRectF(xCenter - width / 2, yCenter - height / 2, width, height);
LtsCoordTrans::UtmCoordinate utmBase(LtsCoordTrans::UtmCoordinate::fromGeographic(LtsCoordTrans::geographicFromMgrs(base))); LtsCoordTrans::UtmCoordinate utmBase(
const QPointF topLeft(utmBase.geographic(areaRect.left(), areaRect.top())); LtsCoordTrans::UtmCoordinate::fromGeographic(LtsCoordTrans::geographicFromMgrs(base)));
const QPointF bottomRight(utmBase.geographic(areaRect.right(), areaRect.bottom())); const QPointF topLeft(utmBase.geographic(areaRect.left(), areaRect.top()));
const QPointF bottomRight(utmBase.geographic(areaRect.right(), areaRect.bottom()));
QRectF rect(topLeft, bottomRight);
return rect;
QRectF rect (topLeft, bottomRight);
return rect;
} }
void coordtrans_test::testAddMarginToArea() void coordtrans_test::testAddMarginToArea()
{ {
{ {
qDebug() << "Altmark"; qDebug() << "Altmark";
QRectF area = createArea(QStringLiteral("32U PD 0000000000"), 50000, 10000, 30000, 30000); QRectF area = createArea(QStringLiteral("32U PD 0000000000"), 50000, 10000, 30000, 30000);
QRectF area1Increased = LtsCoordTrans::addMarginToArea(area, QSize(5000, 20000)); QRectF area1Increased = LtsCoordTrans::addMarginToArea(area, QSize(5000, 20000));
qDebug() << "topLeft : " << qSetRealNumberPrecision(15) << area.topLeft() << " - degree:" << area.topLeft()*LtsCoordTrans::rad2deg(); qDebug() << "topLeft : " << qSetRealNumberPrecision(15) << area.topLeft()
qDebug() << "topLeftInc : " << qSetRealNumberPrecision(15) << area1Increased.topLeft() << " - degree:" << area1Increased.topLeft()*LtsCoordTrans::rad2deg(); << " - degree:" << area.topLeft() * LtsCoordTrans::rad2deg();
qDebug() << "topLeftInc : " << qSetRealNumberPrecision(15) << area1Increased.topLeft()
<< " - degree:" << area1Increased.topLeft() * LtsCoordTrans::rad2deg();
qDebug() << "bottomRight : " << qSetRealNumberPrecision(15) << area.bottomRight() << " - degree:" << area.bottomRight()*LtsCoordTrans::rad2deg(); qDebug() << "bottomRight : " << qSetRealNumberPrecision(15) << area.bottomRight()
qDebug() << "bottomRightInc : " << qSetRealNumberPrecision(15) << area1Increased.bottomRight() << " - degree:" << area1Increased.bottomRight()*LtsCoordTrans::rad2deg(); << " - degree:" << area.bottomRight() * LtsCoordTrans::rad2deg();
qDebug() << "bottomRightInc : " << qSetRealNumberPrecision(15) << area1Increased.bottomRight()
<< " - degree:" << area1Increased.bottomRight() * LtsCoordTrans::rad2deg();
QVERIFY2( area1Increased.topLeft().x() < area.topLeft().x(), "addMarginToArea topLeft X failed"); QVERIFY2(area1Increased.topLeft().x() < area.topLeft().x(), "addMarginToArea topLeft X failed");
QVERIFY2( area1Increased.topLeft().y() < area.topLeft().y(), "addMarginToArea topLeft Y failed"); QVERIFY2(area1Increased.topLeft().y() < area.topLeft().y(), "addMarginToArea topLeft Y failed");
QVERIFY2( area1Increased.bottomRight().x() > area.bottomRight().x(), "addMarginToArea bottomRight X failed"); QVERIFY2(area1Increased.bottomRight().x() > area.bottomRight().x(), "addMarginToArea bottomRight X failed");
QVERIFY2( area1Increased.bottomRight().y() > area.bottomRight().y(), "addMarginToArea bottomRight Y failed"); QVERIFY2(area1Increased.bottomRight().y() > area.bottomRight().y(), "addMarginToArea bottomRight Y failed");
} }
{
qDebug() << "Luxemburg";
QRectF area = createArea(QStringLiteral("32U LA 0000000000"), 100, 100, 5000, 5000);
QRectF area1Increased = LtsCoordTrans::addMarginToArea(area, QSize(50000, 20000));
{ qDebug() << "topLeft : " << qSetRealNumberPrecision(15) << area.topLeft()
qDebug() << "Luxemburg"; << " - degree:" << area.topLeft() * LtsCoordTrans::rad2deg();
QRectF area = createArea(QStringLiteral("32U LA 0000000000"), 100, 100, 5000, 5000); qDebug() << "topLeftInc : " << qSetRealNumberPrecision(15) << area1Increased.topLeft()
QRectF area1Increased = LtsCoordTrans::addMarginToArea(area, QSize(50000, 20000)); << " - degree:" << area1Increased.topLeft() * LtsCoordTrans::rad2deg();
qDebug() << "topLeft : " << qSetRealNumberPrecision(15) << area.topLeft() << " - degree:" << area.topLeft()*LtsCoordTrans::rad2deg(); qDebug() << "bottomRight : " << qSetRealNumberPrecision(15) << area.bottomRight()
qDebug() << "topLeftInc : " << qSetRealNumberPrecision(15) << area1Increased.topLeft() << " - degree:" << area1Increased.topLeft()*LtsCoordTrans::rad2deg(); << " - degree:" << area.bottomRight() * LtsCoordTrans::rad2deg();
qDebug() << "bottomRightInc : " << qSetRealNumberPrecision(15) << area1Increased.bottomRight()
<< " - degree:" << area1Increased.bottomRight() * LtsCoordTrans::rad2deg();
qDebug() << "bottomRight : " << qSetRealNumberPrecision(15) << area.bottomRight() << " - degree:" << area.bottomRight()*LtsCoordTrans::rad2deg(); QVERIFY2(area1Increased.topLeft().x() < area.topLeft().x(), "addMarginToArea topLeft X failed");
qDebug() << "bottomRightInc : " << qSetRealNumberPrecision(15) << area1Increased.bottomRight() << " - degree:" << area1Increased.bottomRight()*LtsCoordTrans::rad2deg(); QVERIFY2(area1Increased.topLeft().y() < area.topLeft().y(), "addMarginToArea topLeft Y failed");
QVERIFY2( area1Increased.topLeft().x() < area.topLeft().x(), "addMarginToArea topLeft X failed"); QVERIFY2(area1Increased.bottomRight().x() > area.bottomRight().x(), "addMarginToArea bottomRight X failed");
QVERIFY2( area1Increased.topLeft().y() < area.topLeft().y(), "addMarginToArea topLeft Y failed"); QVERIFY2(area1Increased.bottomRight().y() > area.bottomRight().y(), "addMarginToArea bottomRight Y failed");
}
QVERIFY2( area1Increased.bottomRight().x() > area.bottomRight().x(), "addMarginToArea bottomRight X failed");
QVERIFY2( area1Increased.bottomRight().y() > area.bottomRight().y(), "addMarginToArea bottomRight Y failed");
}
} }
void coordtrans_test::testIncreaseRect() void coordtrans_test::testIncreaseRect()
{ {
QPointF lonlat = QPointF(8.6191049344, 53.1048309844) * LtsCoordTrans::deg2rad(); QPointF lonlat = QPointF(8.6191049344, 53.1048309844) * LtsCoordTrans::deg2rad();
QString mgrs = LtsCoordTrans::mgrsFromGeographic(lonlat.x(), lonlat.y(), 9); QString mgrs = LtsCoordTrans::mgrsFromGeographic(lonlat.x(), lonlat.y(), 9);
QCOMPARE(mgrs, QStringLiteral("32U MD 745000000 840000000")); QCOMPARE(mgrs, QStringLiteral("32U MD 745000000 840000000"));
const LtsCoordTrans::UtmCoordinate centerPoint = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y()); const LtsCoordTrans::UtmCoordinate centerPoint =
LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y());
LtsCoordTrans::UtmCoordinate topLeftUtm; LtsCoordTrans::UtmCoordinate topLeftUtm;
LtsCoordTrans::UtmCoordinate topLeftUtm2; LtsCoordTrans::UtmCoordinate topLeftUtm2;
{
QPointF topLeftGeo = centerPoint.geographic(-1111, 2222);
QPointF bottomRightGeo = centerPoint.geographic(3000, -4000);
{ topLeftUtm = LtsCoordTrans::UtmCoordinate::fromGeographic(topLeftGeo);
QPointF topLeftGeo = centerPoint.geographic(-1111, 2222); const LtsCoordTrans::UtmCoordinate bottomRightUtm =
QPointF bottomRightGeo = centerPoint.geographic( 3000, -4000); LtsCoordTrans::UtmCoordinate::fromGeographic(bottomRightGeo);
qDebug() << "topLeftUtm: " << topLeftUtm.x << " - " << qSetRealNumberPrecision(15) << topLeftUtm.y;
qDebug() << "bottomRightUtm: " << bottomRightUtm.x << " - " << qSetRealNumberPrecision(15)
<< bottomRightUtm.y;
}
topLeftUtm = LtsCoordTrans::UtmCoordinate::fromGeographic(topLeftGeo); {
const LtsCoordTrans::UtmCoordinate bottomRightUtm = LtsCoordTrans::UtmCoordinate::fromGeographic(bottomRightGeo); topLeftUtm2.x = centerPoint.x - 1111;
qDebug() << "topLeftUtm: " << topLeftUtm.x << " - " << qSetRealNumberPrecision(15) << topLeftUtm.y; topLeftUtm2.y = centerPoint.y + 2222;
qDebug() << "bottomRightUtm: " << bottomRightUtm.x << " - " << qSetRealNumberPrecision(15) << bottomRightUtm.y;
}
LtsCoordTrans::UtmCoordinate bottomRightUtm2;
bottomRightUtm2.x = centerPoint.x + 3000;
bottomRightUtm2.y = centerPoint.y - 4000;
{ qDebug() << "topLeftUtm2: " << topLeftUtm2.x << " - " << qSetRealNumberPrecision(15) << topLeftUtm2.y;
topLeftUtm2.x = centerPoint.x - 1111; qDebug() << "bottomRightUtm2: " << bottomRightUtm2.x << " - " << qSetRealNumberPrecision(15)
topLeftUtm2.y = centerPoint.y + 2222; << bottomRightUtm2.y;
}
LtsCoordTrans::UtmCoordinate bottomRightUtm2; QVERIFY2(qFuzzyCompare(topLeftUtm.x, topLeftUtm2.x), "testIncreaseRect x failed");
bottomRightUtm2.x = centerPoint.x + 3000; QVERIFY2(qFuzzyCompare(topLeftUtm.y, topLeftUtm2.y), "testIncreaseRect y failed");
bottomRightUtm2.y = centerPoint.y - 4000;
qDebug() << "topLeftUtm2: " << topLeftUtm2.x << " - " << qSetRealNumberPrecision(15) << topLeftUtm2.y;
qDebug() << "bottomRightUtm2: " << bottomRightUtm2.x << " - " << qSetRealNumberPrecision(15) << bottomRightUtm2.y;
}
QVERIFY2(qFuzzyCompare(topLeftUtm.x, topLeftUtm2.x), "testIncreaseRect x failed");
QVERIFY2(qFuzzyCompare(topLeftUtm.y, topLeftUtm2.y), "testIncreaseRect y failed");
} }
void coordtrans_test::testIncreaseRect2() void coordtrans_test::testIncreaseRect2()
{ {
QPointF lonlat = QPointF(8.6191049344, 53.1048309844) * LtsCoordTrans::deg2rad(); QPointF lonlat = QPointF(8.6191049344, 53.1048309844) * LtsCoordTrans::deg2rad();
QString mgrs = LtsCoordTrans::mgrsFromGeographic(lonlat.x(), lonlat.y(), 9); QString mgrs = LtsCoordTrans::mgrsFromGeographic(lonlat.x(), lonlat.y(), 9);
QCOMPARE(mgrs, QStringLiteral("32U MD 745000000 840000000")); QCOMPARE(mgrs, QStringLiteral("32U MD 745000000 840000000"));
QRectF myRect; QRectF myRect;
QRectF myRectIncreased; QRectF myRectIncreased;
{ {
const LtsCoordTrans::UtmCoordinate centerPoint = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y()); const LtsCoordTrans::UtmCoordinate centerPoint =
LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y());
QPointF topLeftGeo = centerPoint.geographic(-3000, 2000); QPointF topLeftGeo = centerPoint.geographic(-3000, 2000);
QPointF bottomRightGeo = centerPoint.geographic( 3000, -2000); QPointF bottomRightGeo = centerPoint.geographic(3000, -2000);
myRect = QRectF(topLeftGeo, bottomRightGeo).normalized(); myRect = QRectF(topLeftGeo, bottomRightGeo).normalized();
qDebug() << "myRect : " << myRect; qDebug() << "myRect : " << myRect;
qDebug() << "myRect center : " << myRect.center(); qDebug() << "myRect center : " << myRect.center();
qDebug() << "myRect height : " << myRect.height(); qDebug() << "myRect height : " << myRect.height();
} }
{
const QPointF centerGeo = myRect.center();
const LtsCoordTrans::UtmCoordinate centerUtm = LtsCoordTrans::UtmCoordinate::fromGeographic(centerGeo);
{ QPointF topLeftGeo = centerUtm.geographic(-6000, 4000);
const QPointF centerGeo = myRect.center(); QPointF bottomRightGeo = centerUtm.geographic(6000, -4000);
const LtsCoordTrans::UtmCoordinate centerUtm = LtsCoordTrans::UtmCoordinate::fromGeographic(centerGeo);
QPointF topLeftGeo = centerUtm.geographic(-6000, 4000); myRectIncreased = QRectF(topLeftGeo, bottomRightGeo).normalized();
QPointF bottomRightGeo = centerUtm.geographic( 6000, -4000);
myRectIncreased = QRectF(topLeftGeo, bottomRightGeo).normalized(); qDebug() << "myRectIncreased : " << myRectIncreased;
qDebug() << "myRectIncreased center: " << myRectIncreased.center();
qDebug() << "myRectIncreased height: " << myRectIncreased.height();
}
qDebug() << "myRectIncreased : " << myRectIncreased; QVERIFY2((int)(myRectIncreased.center().x() * 10000) == (int)(myRect.center().x() * 10000),
qDebug() << "myRectIncreased center: " << myRectIncreased.center(); "testIncreaseRect2 centerX failed");
qDebug() << "myRectIncreased height: " << myRectIncreased.height(); QVERIFY2((int)(myRectIncreased.center().y() * 10000) == (int)(myRect.center().y() * 10000),
"testIncreaseRect2 centerY failed");
}
QVERIFY2( (int)(myRectIncreased.center().x()*10000) == (int)(myRect.center().x()*10000), "testIncreaseRect2 centerX failed");
QVERIFY2( (int)(myRectIncreased.center().y()*10000) == (int)(myRect.center().y()*10000), "testIncreaseRect2 centerY failed");
QVERIFY2(myRectIncreased.width() > myRect.width(), "testIncreaseRect2 width failed");
QVERIFY2(myRectIncreased.height() > myRect.height(), "testIncreaseRect2 height failed");
QVERIFY2(myRectIncreased.width() > myRect.width(), "testIncreaseRect2 width failed");
QVERIFY2(myRectIncreased.height() > myRect.height(), "testIncreaseRect2 height failed");
} }
void coordtrans_test::testGeographicFromMgrs() void coordtrans_test::testGeographicFromMgrs()
{ {
QString mgrs(QStringLiteral("32UPD7654398765")); QString mgrs(QStringLiteral("32UPD7654398765"));
QPointF geographic = LtsCoordTrans::geographicFromMgrs(mgrs);
QPointF geographic = LtsCoordTrans::geographicFromMgrs(mgrs); QCOMPARE(geographic, QPointF(11.6436815550, 53.2088411454) * LtsCoordTrans::deg2rad());
QCOMPARE(geographic, QPointF(11.6436815550, 53.2088411454) * LtsCoordTrans::deg2rad());
} }
void coordtrans_test::testMgrsSquares() void coordtrans_test::testMgrsSquares()
{ {
checkArea(QStringLiteral("32U PD 0000000000"), 50000, 10000, 30000, 30000,
{QStringLiteral("32U PC"), QStringLiteral("32U PD")});
checkArea(QStringLiteral("32U MD 0000000000"), 50000, 10000, 30000, 30000,
{QStringLiteral("32U MC"), QStringLiteral("32U MD")});
checkArea(QStringLiteral("32U MD 0000000000"), 89999, 89999, 21000, 21000,
{QStringLiteral("32U MD"), QStringLiteral("32U ME"), QStringLiteral("32U ND"), QStringLiteral("32U NE")});
checkArea(QStringLiteral("39Q XG 0000000000"), 40000, 35000, 60000, 70000,
{QStringLiteral("39Q XG"), QStringLiteral("39R XG")});
checkArea(QStringLiteral("40R CP 0000000000"), 94000, 9000, 7000, 16000, {QStringLiteral("40R CP")});
checkArea(QStringLiteral("40R DN 0000000000"), 500, 95500, 12000, 7000,
{QStringLiteral("40R CN"), QStringLiteral("40R DN")});
checkArea(QStringLiteral("40R DN 0000000000"), 500, 96760, 30000, 30000,
{QStringLiteral("40R CN"), QStringLiteral("40R CP"), QStringLiteral("40R DN"), QStringLiteral("40R DP")});
checkArea(QStringLiteral("40R BM 0000000000"), 59000, 59500, 46000, 40000,
{QStringLiteral("40Q BM"), QStringLiteral("40R BM")});
checkArea(QStringLiteral("32U LA 0000000000"), 10000, 10000, 5000, 5000,
{
QStringLiteral("32U LA"),
});
checkArea(QStringLiteral("32U PD 0000000000"), 50000, 10000, 30000, 30000, { QStringLiteral("32U PC"), checkArea(QStringLiteral("32U LA 0000000000"), 100, 100, 60000, 60000,
QStringLiteral("32U PD") {QStringLiteral("31U GQ"), QStringLiteral("31U GR"), QStringLiteral("32U KA"), QStringLiteral("32U KV"),
}); QStringLiteral("32U LA"), QStringLiteral("32U LV")});
checkArea(QStringLiteral("32U MD 0000000000"), 50000, 10000, 30000, 30000, { QStringLiteral("32U MC"),
QStringLiteral("32U MD")
});
checkArea(QStringLiteral("32U MD 0000000000"), 89999, 89999, 21000, 21000, { QStringLiteral("32U MD"),
QStringLiteral("32U ME"),
QStringLiteral("32U ND"),
QStringLiteral("32U NE")
});
checkArea(QStringLiteral("39Q XG 0000000000"), 40000, 35000, 60000, 70000, { QStringLiteral("39Q XG"), checkArea(QStringLiteral("32U LA 0000000000"), 100, 100, 150000, 150000,
QStringLiteral("39R XG") {QStringLiteral("31U FQ"), QStringLiteral("31U FR"), QStringLiteral("31U GQ"), QStringLiteral("31U GR"),
}); QStringLiteral("32U KA"), QStringLiteral("32U KV"), QStringLiteral("32U LA"), QStringLiteral("32U LV")});
checkArea(QStringLiteral("40R CP 0000000000"), 94000, 9000, 7000, 16000, { QStringLiteral("40R CP") });
checkArea(QStringLiteral("40R DN 0000000000"), 500, 95500, 12000, 7000, { QStringLiteral("40R CN"),
QStringLiteral("40R DN")
});
checkArea(QStringLiteral("40R DN 0000000000"), 500, 96760, 30000, 30000, { QStringLiteral("40R CN"),
QStringLiteral("40R CP"),
QStringLiteral("40R DN"),
QStringLiteral("40R DP")
});
checkArea(QStringLiteral("40R BM 0000000000"), 59000, 59500, 46000, 40000, { QStringLiteral("40Q BM"),
QStringLiteral("40R BM")
});
checkArea(QStringLiteral("32U LA 0000000000"), 10000, 10000, 5000, 5000, { QStringLiteral("32U LA"),
});
checkArea(QStringLiteral("32U LA 0000000000"), 100, 100, 60000, 60000, { QStringLiteral("31U GQ"),
QStringLiteral("31U GR"),
QStringLiteral("32U KA"),
QStringLiteral("32U KV"),
QStringLiteral("32U LA"),
QStringLiteral("32U LV")
});
checkArea(QStringLiteral("32U LA 0000000000"), 100, 100,150000,150000, { QStringLiteral("31U FQ"),
QStringLiteral("31U FR"),
QStringLiteral("31U GQ"),
QStringLiteral("31U GR"),
QStringLiteral("32U KA"),
QStringLiteral("32U KV"),
QStringLiteral("32U LA"),
QStringLiteral("32U LV")
});
checkArea(QStringLiteral("32U LA 0000000000"), 100, 100,200000,200000, { QStringLiteral("31U FP"),
QStringLiteral("31U FQ"),
QStringLiteral("31U FR"),
QStringLiteral("31U GP"),
QStringLiteral("31U GQ"),
QStringLiteral("31U GR"),
QStringLiteral("31U GS"),
QStringLiteral("32U KA"),
QStringLiteral("32U KB"),
QStringLiteral("32U KV"),
QStringLiteral("32U LA"),
QStringLiteral("32U LB"),
QStringLiteral("32U LV"),
QStringLiteral("32U MA"),
QStringLiteral("32U MB"),
QStringLiteral("32U MV")
});
checkArea(QStringLiteral("32U LA 0000000000"), 100, 100, 200000, 200000,
{QStringLiteral("31U FP"), QStringLiteral("31U FQ"), QStringLiteral("31U FR"), QStringLiteral("31U GP"),
QStringLiteral("31U GQ"), QStringLiteral("31U GR"), QStringLiteral("31U GS"), QStringLiteral("32U KA"),
QStringLiteral("32U KB"), QStringLiteral("32U KV"), QStringLiteral("32U LA"), QStringLiteral("32U LB"),
QStringLiteral("32U LV"), QStringLiteral("32U MA"), QStringLiteral("32U MB"), QStringLiteral("32U MV")});
} }
QVector<LtsCoordTrans::UtmCoordinate> checkAreaGetMgrsSquares(const QString& base, int xCenter, int yCenter, int width,
QVector<LtsCoordTrans::UtmCoordinate> checkAreaGetMgrsSquares(const QString &base, int height)
int xCenter, int yCenter, int width, int height)
{ {
QRectF areaRect = QRectF(xCenter - width / 2, yCenter - height / 2, width, height); QRectF areaRect = QRectF(xCenter - width / 2, yCenter - height / 2, width, height);
LtsCoordTrans::UtmCoordinate utmBase(LtsCoordTrans::UtmCoordinate::fromGeographic(LtsCoordTrans::geographicFromMgrs(base))); LtsCoordTrans::UtmCoordinate utmBase(
const QPointF topLeft(utmBase.geographic(areaRect.left(), areaRect.top())); LtsCoordTrans::UtmCoordinate::fromGeographic(LtsCoordTrans::geographicFromMgrs(base)));
const QPointF bottomRight(utmBase.geographic(areaRect.right(), areaRect.bottom())); const QPointF topLeft(utmBase.geographic(areaRect.left(), areaRect.top()));
const QPointF bottomRight(utmBase.geographic(areaRect.right(), areaRect.bottom()));
const auto squares = LtsCoordTrans::getMgrsSquares(QRectF(topLeft, bottomRight), false, false);
QStringList src;
src.reserve(squares.size());
for (const auto& utm : squares)
src += utm.mgrs(0);
src.sort();
const auto squares = LtsCoordTrans::getMgrsSquares(QRectF(topLeft, bottomRight), false, false); return squares;
QStringList src;
src.reserve(squares.size());
for (const auto &utm : squares)
src += utm.mgrs(0);
src.sort();
return squares;
} }
void coordtrans_test::testMgrsSquaresWithSurrounding() void coordtrans_test::testMgrsSquaresWithSurrounding()
{ {
int initialSize = 5000;
QVector<LtsCoordTrans::UtmCoordinate> squares1 =
checkAreaGetMgrsSquares(QStringLiteral("32U NC 0000000000"), 50000, 50000, initialSize, initialSize);
QVERIFY2(squares1.size() == 1, "checkAreaGetMgrsSquares failed");
int biggerSize = initialSize + (1 * 110000);
QVector<LtsCoordTrans::UtmCoordinate> squares9 =
checkAreaGetMgrsSquares(QStringLiteral("32U NC 0000000000"), 50000, 50000, biggerSize, biggerSize);
QVERIFY2(squares9.size() == 9, "checkAreaGetMgrsSquares biggerSize failed");
int muchBiggerSize = initialSize + (3 * 110000);
QVector<LtsCoordTrans::UtmCoordinate> square33 =
checkAreaGetMgrsSquares(QStringLiteral("32U NC 0000000000"), 50000, 50000, muchBiggerSize, muchBiggerSize);
QVERIFY2(square33.size() == 33, "checkAreaGetMgrsSquares muchBiggerSize failed");
QStringList string1;
string1.reserve(squares1.size());
for (const LtsCoordTrans::UtmCoordinate& item : std::as_const(squares1))
string1.append(item.mgrs(0));
QStringList string9;
string9.reserve(squares9.size());
for (const LtsCoordTrans::UtmCoordinate& item : std::as_const(squares9))
string9.append(item.mgrs(0));
QStringList string33;
string33.reserve(square33.size());
for (const LtsCoordTrans::UtmCoordinate& item : std::as_const(square33))
string33.append(item.mgrs(0));
{
QStringList surroundingStrings;
surroundingStrings.reserve(squares9.size());
for (const QString& str : std::as_const(string9))
if (!string1.contains(str))
surroundingStrings.append(str);
QVERIFY2(surroundingStrings.size() == 8, "checkAreaGetMgrsSquares squaresDiff failed");
}
{
QStringList surroundingStrings;
surroundingStrings.reserve(string33.size());
for (const QString& str : std::as_const(string33))
if (!string1.contains(str))
surroundingStrings.append(str);
QVERIFY2(surroundingStrings.size() == 32, "checkAreaGetMgrsSquares squaresDiff failed");
}
int initialSize = 5000;
QVector<LtsCoordTrans::UtmCoordinate> squares1 = checkAreaGetMgrsSquares(QStringLiteral("32U NC 0000000000"), 50000, 50000, initialSize, initialSize);
QVERIFY2(squares1.size() == 1, "checkAreaGetMgrsSquares failed");
int biggerSize = initialSize + (1*110000);
QVector<LtsCoordTrans::UtmCoordinate> squares9 = checkAreaGetMgrsSquares(QStringLiteral("32U NC 0000000000"), 50000, 50000, biggerSize, biggerSize);
QVERIFY2(squares9.size() == 9, "checkAreaGetMgrsSquares biggerSize failed");
int muchBiggerSize = initialSize + (3*110000);
QVector<LtsCoordTrans::UtmCoordinate> square33 = checkAreaGetMgrsSquares(QStringLiteral("32U NC 0000000000"), 50000, 50000, muchBiggerSize, muchBiggerSize);
QVERIFY2(square33.size() == 33, "checkAreaGetMgrsSquares muchBiggerSize failed");
QStringList string1;
string1.reserve(squares1.size());
for (const LtsCoordTrans::UtmCoordinate &item : std::as_const(squares1))
string1.append(item.mgrs(0));
QStringList string9;
string9.reserve(squares9.size());
for (const LtsCoordTrans::UtmCoordinate &item : std::as_const(squares9))
string9.append(item.mgrs(0));
QStringList string33;
string33.reserve(square33.size());
for (const LtsCoordTrans::UtmCoordinate &item : std::as_const(square33))
string33.append(item.mgrs(0));
{
QStringList surroundingStrings;
surroundingStrings.reserve(squares9.size());
for (const QString &str : std::as_const(string9))
if (!string1.contains(str))
surroundingStrings.append(str);
QVERIFY2(surroundingStrings.size() == 8, "checkAreaGetMgrsSquares squaresDiff failed");
}
{
QStringList surroundingStrings;
surroundingStrings.reserve(string33.size());
for (const QString &str : std::as_const(string33))
if (!string1.contains(str))
surroundingStrings.append(str);
QVERIFY2(surroundingStrings.size() == 32, "checkAreaGetMgrsSquares squaresDiff failed");
}
} }
void coordtrans_test::checkArea(const QString &base, void coordtrans_test::checkArea(const QString& base, int xCenter, int yCenter, int width, int height,
int xCenter, int yCenter, int width, int height, const QStringList& coords)
const QStringList &coords)
{ {
qDebug() << "checkArea : base: " << base; qDebug() << "checkArea : base: " << base;
QRectF areaRect = QRectF(xCenter - width / 2, yCenter - height / 2, width, height); QRectF areaRect = QRectF(xCenter - width / 2, yCenter - height / 2, width, height);
LtsCoordTrans::UtmCoordinate utmBase(LtsCoordTrans::UtmCoordinate::fromGeographic(LtsCoordTrans::geographicFromMgrs(base))); LtsCoordTrans::UtmCoordinate utmBase(
const QPointF topLeft(utmBase.geographic(areaRect.left(), areaRect.top())); LtsCoordTrans::UtmCoordinate::fromGeographic(LtsCoordTrans::geographicFromMgrs(base)));
const QPointF bottomRight(utmBase.geographic(areaRect.right(), areaRect.bottom())); const QPointF topLeft(utmBase.geographic(areaRect.left(), areaRect.top()));
qDebug() << "TopLeft: " << topLeft * LtsCoordTrans::rad2deg(); const QPointF bottomRight(utmBase.geographic(areaRect.right(), areaRect.bottom()));
qDebug() << "BottomRight: " << bottomRight * LtsCoordTrans::rad2deg(); qDebug() << "TopLeft: " << topLeft * LtsCoordTrans::rad2deg();
qDebug() << "BottomRight: " << bottomRight * LtsCoordTrans::rad2deg();
const auto squares = LtsCoordTrans::getMgrsSquares(QRectF(topLeft, bottomRight), false, false); const auto squares = LtsCoordTrans::getMgrsSquares(QRectF(topLeft, bottomRight), false, false);
QStringList src; QStringList src;
src.reserve(squares.size()); src.reserve(squares.size());
for (const auto &utm : squares) for (const auto& utm : squares)
src += utm.mgrs(0); src += utm.mgrs(0);
src.sort(); src.sort();
qDebug() << "src: '" << src << "' expected: '" << coords << "'"; qDebug() << "src: '" << src << "' expected: '" << coords << "'";
QCOMPARE(src, coords); QCOMPARE(src, coords);
} }
@@ -7,28 +7,25 @@
class coordtrans_test : public QObject class coordtrans_test : public QObject
{ {
Q_OBJECT Q_OBJECT
private Q_SLOTS: private Q_SLOTS:
void initTestCase(); void initTestCase();
void cleanupTestCase(); void cleanupTestCase();
void testFromGeographic(); void testFromGeographic();
void testMgrsFromGeographic(); void testMgrsFromGeographic();
void testRelativeMetricalOffet_data(); void testRelativeMetricalOffet_data();
void testRelativeMetricalOffet(); void testRelativeMetricalOffet();
void testAddMarginToArea(); void testAddMarginToArea();
void testIncreaseRect(); void testIncreaseRect();
void testIncreaseRect2(); void testIncreaseRect2();
void testGeographicFromMgrs(); void testGeographicFromMgrs();
void testMgrsSquares(); void testMgrsSquares();
void testMgrsSquaresWithSurrounding(); void testMgrsSquaresWithSurrounding();
private:
void checkArea(const QString &base,
int xCenter, int yCenter, int width, int height,
const QStringList &coords);
private:
void checkArea(const QString& base, int xCenter, int yCenter, int width, int height, const QStringList& coords);
}; };
+97 -106
View File
@@ -1,7 +1,7 @@
#include "lts_coord_widget.h" #include "lts_coord_widget.h"
#include "lts_coord_widget_p.h" #include "lts_coord_widget_p.h"
#include <LtsCoordTrans/lts_coord_trans.h> #include <LtsCoordTrans/lts_coord_trans.h>
@@ -10,187 +10,178 @@
namespace LtsCoordWidget namespace LtsCoordWidget
{ {
LtsCoordWidget::LtsCoordWidget(DisplayType dt, QWidget *parent) LtsCoordWidget::LtsCoordWidget(DisplayType dt, QWidget* parent) : QWidget(parent), m_displayType(dt)
: QWidget(parent)
, m_displayType(dt)
{ {
setFocusPolicy(Qt::StrongFocus); setFocusPolicy(Qt::StrongFocus);
rebuildUi(); rebuildUi();
} }
void LtsCoordWidget::setCoordinate(const QPointF &geoCoord, bool bUseAsDefaultValue) void LtsCoordWidget::setCoordinate(const QPointF& geoCoord, bool bUseAsDefaultValue)
{ {
if (m_coordinate != geoCoord) if (m_coordinate != geoCoord)
emit coordinateChanged(geoCoord); emit coordinateChanged(geoCoord);
if (bUseAsDefaultValue) if (bUseAsDefaultValue)
m_defaultCoordinate = geoCoord; m_defaultCoordinate = geoCoord;
if (m_inputWidgetHandler) if (m_inputWidgetHandler)
m_inputWidgetHandler->setCoordinate(geoCoord); m_inputWidgetHandler->setCoordinate(geoCoord);
} }
void LtsCoordWidget::clear() void LtsCoordWidget::clear()
{ {
if (m_inputWidgetHandler) if (m_inputWidgetHandler)
m_inputWidgetHandler->clear(); m_inputWidgetHandler->clear();
} }
void LtsCoordWidget::setCoordinate(double lon, double lat, bool bUseAsDefaultValue) void LtsCoordWidget::setCoordinate(double lon, double lat, bool bUseAsDefaultValue)
{ {
setCoordinate(QPointF(lon, lat), bUseAsDefaultValue); setCoordinate(QPointF(lon, lat), bUseAsDefaultValue);
} }
QPointF LtsCoordWidget::coordinate() const QPointF LtsCoordWidget::coordinate() const
{ {
if (!m_inputWidgetHandler) if (!m_inputWidgetHandler)
return QPointF(); return QPointF();
return m_inputWidgetHandler->coordinate(); return m_inputWidgetHandler->coordinate();
} }
LtsCoordWidget::DisplayType LtsCoordWidget::displayType() const LtsCoordWidget::DisplayType LtsCoordWidget::displayType() const
{ {
return m_displayType; return m_displayType;
} }
void LtsCoordWidget::setDisplayType(LtsCoordWidget::DisplayType dt) void LtsCoordWidget::setDisplayType(LtsCoordWidget::DisplayType dt)
{ {
if (m_displayType == dt) if (m_displayType == dt)
return; return;
m_displayType = dt; m_displayType = dt;
rebuildUi(); rebuildUi();
} }
bool LtsCoordWidget::withResetButton() const bool LtsCoordWidget::withResetButton() const
{ {
return m_bWithResetButton; return m_bWithResetButton;
} }
void LtsCoordWidget::setWithResetButton(bool bWith) void LtsCoordWidget::setWithResetButton(bool bWith)
{ {
if (m_bWithResetButton == bWith) if (m_bWithResetButton == bWith)
return; return;
m_bWithResetButton = bWith; m_bWithResetButton = bWith;
if (m_inputWidgetHandler) if (m_inputWidgetHandler)
m_inputWidgetHandler->resetButton()->setVisible(m_bWithResetButton); m_inputWidgetHandler->resetButton()->setVisible(m_bWithResetButton);
} }
bool LtsCoordWidget::showToolTip() const bool LtsCoordWidget::showToolTip() const
{ {
return m_bShowToolTip; return m_bShowToolTip;
} }
void LtsCoordWidget::setShowToolTip(bool bShow) void LtsCoordWidget::setShowToolTip(bool bShow)
{ {
if (m_bShowToolTip == bShow) if (m_bShowToolTip == bShow)
return; return;
m_bShowToolTip = bShow; m_bShowToolTip = bShow;
updateToolTip(); updateToolTip();
} }
bool LtsCoordWidget::mgrsSquareEditable() const bool LtsCoordWidget::mgrsSquareEditable() const
{ {
return m_bMgrsSquareEditable; return m_bMgrsSquareEditable;
} }
void LtsCoordWidget::setMgrsSquareEditable(bool bEditable) void LtsCoordWidget::setMgrsSquareEditable(bool bEditable)
{ {
if (m_bMgrsSquareEditable == bEditable) if (m_bMgrsSquareEditable == bEditable)
return; return;
m_bMgrsSquareEditable = bEditable; m_bMgrsSquareEditable = bEditable;
if (m_inputWidgetHandler) if (m_inputWidgetHandler)
m_inputWidgetHandler->setSquaresEditable(bEditable); m_inputWidgetHandler->setSquaresEditable(bEditable);
} }
void LtsCoordWidget::setWithSurroundingMgrsSquares(bool bEnable) void LtsCoordWidget::setWithSurroundingMgrsSquares(bool bEnable)
{ {
if (m_inputWidgetHandler) if (m_inputWidgetHandler)
m_inputWidgetHandler->setWithSurroundingSquare(bEnable); m_inputWidgetHandler->setWithSurroundingSquare(bEnable);
} }
void LtsCoordWidget::setMgrsSquares(const QVector<LtsCoordTrans::UtmCoordinate> &geoCoords) void LtsCoordWidget::setMgrsSquares(const QVector<LtsCoordTrans::UtmCoordinate>& geoCoords)
{ {
if (m_inputWidgetHandler) if (m_inputWidgetHandler)
m_inputWidgetHandler->setMgrsSquares(geoCoords); m_inputWidgetHandler->setMgrsSquares(geoCoords);
} }
bool LtsCoordWidget::event(QEvent* event)
bool LtsCoordWidget::event(QEvent *event)
{ {
if (event->type() == QEvent::ToolTip) if (event->type() == QEvent::ToolTip)
updateToolTip(); updateToolTip();
return QWidget::event(event); return QWidget::event(event);
} }
void LtsCoordWidget::rebuildUi() void LtsCoordWidget::rebuildUi()
{ {
if (m_inputWidgetHandler)
{
m_inputWidgetHandler->cleanup();
delete m_inputWidgetHandler;
delete layout();
}
switch (m_displayType)
{
case DisplayType::MGRS5:
m_inputWidgetHandler = new MgrsEdit(5, this);
break;
case DisplayType::MGRS7:
m_inputWidgetHandler = new MgrsEdit(7, this);
break;
case DisplayType::UTM:
qt_assert("DisplayType::UTM not yet implemented", __FILE__, __LINE__);
break;
case DisplayType::WGS84:
m_inputWidgetHandler = new Wgs84Edit(this);
break;
}
if (!m_inputWidgetHandler)
return;
if (m_inputWidgetHandler) m_inputWidgetHandler->setSquaresEditable(m_bMgrsSquareEditable);
{ m_inputWidgetHandler->resetButton()->setVisible(m_bWithResetButton);
m_inputWidgetHandler->cleanup(); connect(m_inputWidgetHandler->resetButton(), &QToolButton::clicked, this,
delete m_inputWidgetHandler; &LtsCoordWidget::onResetToDefaultCoordinate);
delete layout(); connect(m_inputWidgetHandler, &LtsCoordInputWidgetHandler::coordinateChanged, this,
} &LtsCoordWidget::coordinateChanged);
connect(m_inputWidgetHandler, &LtsCoordInputWidgetHandler::invalidCoordinate, this,
switch (m_displayType) &LtsCoordWidget::invalidCoordinate);
{ if (!m_defaultCoordinate.isNull())
case DisplayType::MGRS5: m_inputWidgetHandler->setCoordinate(m_defaultCoordinate);
m_inputWidgetHandler = new MgrsEdit(5, this);
break;
case DisplayType::MGRS7:
m_inputWidgetHandler = new MgrsEdit(7, this);
break;
case DisplayType::UTM:
qt_assert("DisplayType::UTM not yet implemented", __FILE__, __LINE__);
break;
case DisplayType::WGS84:
m_inputWidgetHandler = new Wgs84Edit(this);
break;
}
if (!m_inputWidgetHandler)
return;
m_inputWidgetHandler->setSquaresEditable(m_bMgrsSquareEditable);
m_inputWidgetHandler->resetButton()->setVisible(m_bWithResetButton);
connect(m_inputWidgetHandler->resetButton(), &QToolButton::clicked,
this, &LtsCoordWidget::onResetToDefaultCoordinate);
connect(m_inputWidgetHandler, &LtsCoordInputWidgetHandler::coordinateChanged,
this, &LtsCoordWidget::coordinateChanged);
connect(m_inputWidgetHandler, &LtsCoordInputWidgetHandler::invalidCoordinate,
this, &LtsCoordWidget::invalidCoordinate);
if (!m_defaultCoordinate.isNull())
m_inputWidgetHandler->setCoordinate(m_defaultCoordinate);
} }
void LtsCoordWidget::updateToolTip() void LtsCoordWidget::updateToolTip()
{ {
QString tt; QString tt;
if (m_bShowToolTip) if (m_bShowToolTip)
{
const QPointF p(coordinate());
if (!p.isNull())
{ {
const QString mgrs = LtsCoordTrans::mgrsFromGeographic(p.x(), p.y()); const QPointF p(coordinate());
const QPointF p2(p * LtsCoordTrans::rad2deg()); if (!p.isNull())
tt = tr("MGRS: %1\nlat/lon: %2/%3").arg(mgrs).arg(p2.y(), 0, 'f', 10).arg(p2.x(), 0, 'f', 10); {
const QString mgrs = LtsCoordTrans::mgrsFromGeographic(p.x(), p.y());
const QPointF p2(p * LtsCoordTrans::rad2deg());
tt = tr("MGRS: %1\nlat/lon: %2/%3").arg(mgrs).arg(p2.y(), 0, 'f', 10).arg(p2.x(), 0, 'f', 10);
}
} }
} setToolTip(tt);
setToolTip(tt);
} }
void LtsCoordWidget::onResetToDefaultCoordinate() void LtsCoordWidget::onResetToDefaultCoordinate()
{ {
if (!m_inputWidgetHandler) if (!m_inputWidgetHandler)
return; return;
if (m_defaultCoordinate.isNull()) if (m_defaultCoordinate.isNull())
m_inputWidgetHandler->clear(); m_inputWidgetHandler->clear();
m_inputWidgetHandler->setCoordinate(m_defaultCoordinate); m_inputWidgetHandler->setCoordinate(m_defaultCoordinate);
} }
} } // namespace LtsCoordWidget
+171 -196
View File
@@ -1,326 +1,301 @@
#include "lts_coord_widget_p.h" #include "lts_coord_widget_p.h"
#include <utility>
#include <utility>
namespace LtsCoordWidget namespace LtsCoordWidget
{ {
void LtsCoordInputWidgetHandler::onCoordinateDataChanged() void LtsCoordInputWidgetHandler::onCoordinateDataChanged()
{ {
const QPointF coord(coordinate()); const QPointF coord(coordinate());
if (coord.isNull()) if (coord.isNull())
{ {
emit invalidCoordinate(); emit invalidCoordinate();
return; return;
} }
emit coordinateChanged(coord); emit coordinateChanged(coord);
} }
MgrsEdit::MgrsEdit(int precision, QWidget* widget)
: LtsCoordInputWidgetHandler(widget), m_precision(precision), m_ui(new Ui::Mgrs)
MgrsEdit::MgrsEdit(int precision, QWidget *widget)
: LtsCoordInputWidgetHandler(widget)
, m_precision(precision)
, m_ui(new Ui::Mgrs)
{ {
m_ui->setupUi(widget); m_ui->setupUi(widget);
if (m_precision < 0) if (m_precision < 0)
m_precision = 0; m_precision = 0;
if (m_precision > 11) if (m_precision > 11)
m_precision = 11; m_precision = 11;
const int upperLimit = pow(10, m_precision) - 1; const int upperLimit = pow(10, m_precision) - 1;
m_ui->leEast->setValidator(new QIntValidator(0, upperLimit, m_ui->leEast)); m_ui->leEast->setValidator(new QIntValidator(0, upperLimit, m_ui->leEast));
m_ui->leNorth->setValidator(new QIntValidator(0, upperLimit, m_ui->leNorth)); m_ui->leNorth->setValidator(new QIntValidator(0, upperLimit, m_ui->leNorth));
setDefaultMgrsSquares(); setDefaultMgrsSquares();
connect(m_ui->cbxZone, QOverload<int>::of(&QComboBox::currentIndexChanged), connect(m_ui->cbxZone, QOverload<int>::of(&QComboBox::currentIndexChanged), this,
this, &MgrsEdit::onCoordinateDataChanged); &MgrsEdit::onCoordinateDataChanged);
connect(m_ui->leEast, &QLineEdit::editingFinished, connect(m_ui->leEast, &QLineEdit::editingFinished, this, &MgrsEdit::onCoordinateDataChanged);
this, &MgrsEdit::onCoordinateDataChanged); connect(m_ui->leNorth, &QLineEdit::editingFinished, this, &MgrsEdit::onCoordinateDataChanged);
connect(m_ui->leNorth, &QLineEdit::editingFinished,
this, &MgrsEdit::onCoordinateDataChanged);
} }
MgrsEdit::~MgrsEdit() MgrsEdit::~MgrsEdit()
{ {
delete m_ui; delete m_ui;
} }
bool MgrsEdit::isValid() bool MgrsEdit::isValid()
{ {
const QString &east = m_ui->leEast->text(); const QString& east = m_ui->leEast->text();
if (east.size() != m_precision) if (east.size() != m_precision)
return false; return false;
const QString &north = m_ui->leNorth->text(); const QString& north = m_ui->leNorth->text();
if (north.size() != m_precision) if (north.size() != m_precision)
return false; return false;
if (m_ui->cbxZone->currentIndex() < 0) if (m_ui->cbxZone->currentIndex() < 0)
return false; return false;
if (m_ui->cbxZone->currentText().isEmpty()) if (m_ui->cbxZone->currentText().isEmpty())
return false; return false;
return true; return true;
} }
void MgrsEdit::setCoordinate(const QPointF &geoCoord) void MgrsEdit::setCoordinate(const QPointF& geoCoord)
{ {
const QString mgrsString = LtsCoordTrans::mgrsFromGeographic(geoCoord.x(), geoCoord.y(), m_precision, false); const QString mgrsString = LtsCoordTrans::mgrsFromGeographic(geoCoord.x(), geoCoord.y(), m_precision, false);
if (mgrsString.isEmpty()) if (mgrsString.isEmpty())
{ {
m_ui->leEast->clear(); m_ui->leEast->clear();
m_ui->leNorth->clear(); m_ui->leNorth->clear();
return; return;
} }
m_ui->leEast->setText(QString()); m_ui->leEast->setText(QString());
m_ui->leNorth->setText(QString()); m_ui->leNorth->setText(QString());
const QString mgrsSquare = mgrsString.left(3) + QLatin1Char(' ') + mgrsString.mid(3, 2);
const QString mgrsSquare = mgrsString.left(3) + QLatin1Char(' ') + mgrsString.mid(3, 2); QString east = mgrsString.mid(5, m_precision);
QString east = mgrsString.mid(5, m_precision); QString north = mgrsString.mid(5 + m_precision, m_precision);
QString north = mgrsString.mid(5 + m_precision, m_precision); int idx = m_ui->cbxZone->findText(mgrsSquare);
int idx = m_ui->cbxZone->findText(mgrsSquare); if (idx < 0)
if (idx < 0) {
{ addMgrsSquare(mgrsSquare);
addMgrsSquare(mgrsSquare); idx = m_ui->cbxZone->findText(mgrsSquare);
idx = m_ui->cbxZone->findText(mgrsSquare); }
} m_ui->cbxZone->setCurrentIndex(idx);
m_ui->cbxZone->setCurrentIndex(idx); m_ui->leEast->setText(east);
m_ui->leEast->setText(east); m_ui->leNorth->setText(north);
m_ui->leNorth->setText(north);
} }
static inline QString getMgrsCoord(QLineEdit *le, int prec) static inline QString getMgrsCoord(QLineEdit* le, int prec)
{ {
QString ret = le->text(); QString ret = le->text();
if (ret.isEmpty()) if (ret.isEmpty())
return ret;
while (ret.size() < prec)
ret += QLatin1Char('0');
le->setText(ret);
return ret; return ret;
while (ret.size() < prec)
ret += QLatin1Char('0');
le->setText(ret);
return ret;
} }
QPointF MgrsEdit::coordinate() const QPointF MgrsEdit::coordinate() const
{ {
const QString east = getMgrsCoord(m_ui->leEast, m_precision); const QString east = getMgrsCoord(m_ui->leEast, m_precision);
const QString north = getMgrsCoord(m_ui->leNorth, m_precision); const QString north = getMgrsCoord(m_ui->leNorth, m_precision);
if (east.isEmpty() || north.isEmpty() || m_ui->cbxZone->currentIndex() < 0) if (east.isEmpty() || north.isEmpty() || m_ui->cbxZone->currentIndex() < 0)
return QPointF(); return QPointF();
const QString mgrsString(m_ui->cbxZone->currentText() + east + north); const QString mgrsString(m_ui->cbxZone->currentText() + east + north);
return LtsCoordTrans::geographicFromMgrs(mgrsString); return LtsCoordTrans::geographicFromMgrs(mgrsString);
} }
QToolButton *MgrsEdit::resetButton() QToolButton* MgrsEdit::resetButton()
{ {
return m_ui->tbReset; return m_ui->tbReset;
} }
void MgrsEdit::cleanup() void MgrsEdit::cleanup()
{ {
delete m_ui->horizontalLayout;
delete m_ui->horizontalLayout; delete m_ui->cbxZone;
delete m_ui->cbxZone; delete m_ui->leEast;
delete m_ui->leEast; delete m_ui->leNorth;
delete m_ui->leNorth; delete m_ui->tbReset;
delete m_ui->tbReset;
} }
void MgrsEdit::clear() void MgrsEdit::clear()
{ {
m_ui->cbxZone->clear(); m_ui->cbxZone->clear();
m_ui->leEast->clear(); m_ui->leEast->clear();
m_ui->leNorth->clear(); m_ui->leNorth->clear();
setDefaultMgrsSquares(); setDefaultMgrsSquares();
} }
void MgrsEdit::setSquaresEditable(bool bEditable) void MgrsEdit::setSquaresEditable(bool bEditable)
{ {
m_ui->cbxZone->setEditable(bEditable); m_ui->cbxZone->setEditable(bEditable);
} }
void MgrsEdit::setWithSurroundingSquare(bool bEnabled) void MgrsEdit::setWithSurroundingSquare(bool bEnabled)
{ {
m_withMgrsSquareOffset = bEnabled; m_withMgrsSquareOffset = bEnabled;
} }
static QStringList defaultMgrsSquares() static QStringList defaultMgrsSquares()
{ {
const QVector<LtsCoordTrans::UtmCoordinate> squares(LtsCoordTrans::defaultMgrsSquares()); const QVector<LtsCoordTrans::UtmCoordinate> squares(LtsCoordTrans::defaultMgrsSquares());
QStringList sl; QStringList sl;
sl.reserve(squares.size()); sl.reserve(squares.size());
for (const LtsCoordTrans::UtmCoordinate &c : squares) for (const LtsCoordTrans::UtmCoordinate& c : squares)
sl += c.mgrs(0); sl += c.mgrs(0);
std::sort(sl.begin(), sl.end()); std::sort(sl.begin(), sl.end());
return sl; return sl;
} }
static QString preferedMgrsSquare() static QString preferedMgrsSquare()
{ {
const LtsCoordTrans::UtmCoordinate c(LtsCoordTrans::preferedMgrsSquare()); const LtsCoordTrans::UtmCoordinate c(LtsCoordTrans::preferedMgrsSquare());
return c.mgrs(0); return c.mgrs(0);
} }
void MgrsEdit::setDefaultMgrsSquares() void MgrsEdit::setDefaultMgrsSquares()
{ {
m_ui->cbxZone->addItems(defaultMgrsSquares()); m_ui->cbxZone->addItems(defaultMgrsSquares());
m_ui->cbxZone->setCurrentIndex(m_ui->cbxZone->findText(preferedMgrsSquare())); m_ui->cbxZone->setCurrentIndex(m_ui->cbxZone->findText(preferedMgrsSquare()));
} }
void MgrsEdit::addMgrsSquare(const QString &newMgrsSquare) void MgrsEdit::addMgrsSquare(const QString& newMgrsSquare)
{ {
QStringList sl = defaultMgrsSquares(); QStringList sl = defaultMgrsSquares();
sl += newMgrsSquare; sl += newMgrsSquare;
if (m_withMgrsSquareOffset) if (m_withMgrsSquareOffset)
{ {
QStringList squares = utmCoordsToList(LtsCoordTrans::defaultMgrsSquareWithOffsets()); QStringList squares = utmCoordsToList(LtsCoordTrans::defaultMgrsSquareWithOffsets());
for (const auto &sq : std::as_const(squares)) for (const auto& sq : std::as_const(squares))
if (!sl.contains(sq)) if (!sl.contains(sq))
sl.append(sq); sl.append(sq);
} }
std::sort(sl.begin(), sl.end()); std::sort(sl.begin(), sl.end());
m_ui->cbxZone->clear(); m_ui->cbxZone->clear();
m_ui->cbxZone->addItems(sl); m_ui->cbxZone->addItems(sl);
} }
QStringList MgrsEdit::utmCoordsToList(const QVector<LtsCoordTrans::UtmCoordinate> &coords) QStringList MgrsEdit::utmCoordsToList(const QVector<LtsCoordTrans::UtmCoordinate>& coords)
{ {
QStringList list; QStringList list;
list.reserve(coords.count()); list.reserve(coords.count());
for (const auto &utm : coords) for (const auto& utm : coords)
list.append(utm.mgrs(0)); list.append(utm.mgrs(0));
return list; return list;
} }
void MgrsEdit::setMgrsSquares(const QVector<LtsCoordTrans::UtmCoordinate> &geoCoords) void MgrsEdit::setMgrsSquares(const QVector<LtsCoordTrans::UtmCoordinate>& geoCoords)
{ {
QStringList sl = utmCoordsToList(geoCoords); QStringList sl = utmCoordsToList(geoCoords);
if (sl.isEmpty()) if (sl.isEmpty())
return; return;
std::sort(sl.begin(), sl.end()); std::sort(sl.begin(), sl.end());
m_ui->cbxZone->clear(); m_ui->cbxZone->clear();
m_ui->cbxZone->addItems(sl); m_ui->cbxZone->addItems(sl);
} }
Wgs84Edit::Wgs84Edit(QWidget* widget) : LtsCoordInputWidgetHandler(widget), m_ui(new Ui::Wgs84)
Wgs84Edit::Wgs84Edit(QWidget *widget)
: LtsCoordInputWidgetHandler(widget)
, m_ui(new Ui::Wgs84)
{ {
m_ui->setupUi(widget); m_ui->setupUi(widget);
DoubleValidator *v = new DoubleValidator(-180, 180, 9, m_ui->leLon); DoubleValidator* v = new DoubleValidator(-180, 180, 9, m_ui->leLon);
v->setNotation(QDoubleValidator::StandardNotation); v->setNotation(QDoubleValidator::StandardNotation);
m_ui->leLon->setValidator(v); m_ui->leLon->setValidator(v);
v = new DoubleValidator(-180, 180, 9, m_ui->leLat); v = new DoubleValidator(-180, 180, 9, m_ui->leLat);
v->setNotation(QDoubleValidator::StandardNotation); v->setNotation(QDoubleValidator::StandardNotation);
m_ui->leLat->setValidator(v); m_ui->leLat->setValidator(v);
connect(m_ui->leLon, &QLineEdit::editingFinished, connect(m_ui->leLon, &QLineEdit::editingFinished, this, &Wgs84Edit::onCoordinateDataChanged);
this, &Wgs84Edit::onCoordinateDataChanged); connect(m_ui->leLat, &QLineEdit::editingFinished, this, &Wgs84Edit::onCoordinateDataChanged);
connect(m_ui->leLat, &QLineEdit::editingFinished,
this, &Wgs84Edit::onCoordinateDataChanged);
} }
Wgs84Edit::~Wgs84Edit() Wgs84Edit::~Wgs84Edit()
{ {
delete m_ui; delete m_ui;
} }
bool Wgs84Edit::isValid() bool Wgs84Edit::isValid()
{ {
return (!m_ui->leLon->text().isEmpty()) && (!m_ui->leLat->text().isEmpty()); return (!m_ui->leLon->text().isEmpty()) && (!m_ui->leLat->text().isEmpty());
} }
void Wgs84Edit::setCoordinate(const QPointF &geoCoord) void Wgs84Edit::setCoordinate(const QPointF& geoCoord)
{ {
const QPointF coord(geoCoord * LtsCoordTrans::rad2deg()); const QPointF coord(geoCoord * LtsCoordTrans::rad2deg());
const QLocale l; const QLocale l;
m_ui->leLon->setText(l.toString(coord.x(), 'f', 9)); m_ui->leLon->setText(l.toString(coord.x(), 'f', 9));
m_ui->leLat->setText(l.toString(coord.y(), 'f', 9)); m_ui->leLat->setText(l.toString(coord.y(), 'f', 9));
} }
QPointF Wgs84Edit::coordinate() const QPointF Wgs84Edit::coordinate() const
{ {
QPointF ret; QPointF ret;
const QLocale l; const QLocale l;
const QString lonStr = m_ui->leLon->text().remove(l.groupSeparator());
const QString latStr = m_ui->leLat->text().remove(l.groupSeparator());
if (lonStr.isEmpty() || latStr.isEmpty())
return ret;
const QString lonStr = m_ui->leLon->text().remove(l.groupSeparator()); ret.rx() = l.toDouble(lonStr);
const QString latStr = m_ui->leLat->text().remove(l.groupSeparator()); ret.ry() = l.toDouble(latStr);
if (lonStr.isEmpty() || latStr.isEmpty())
return ret;
ret.rx() = l.toDouble(lonStr); return ret * LtsCoordTrans::deg2rad();
ret.ry() = l.toDouble(latStr);
return ret * LtsCoordTrans::deg2rad();
} }
QToolButton *Wgs84Edit::resetButton() QToolButton* Wgs84Edit::resetButton()
{ {
return m_ui->tbReset; return m_ui->tbReset;
} }
void Wgs84Edit::cleanup() void Wgs84Edit::cleanup()
{ {
delete m_ui->horizontalLayout;
delete m_ui->horizontalLayout; delete m_ui->leLon;
delete m_ui->leLon; delete m_ui->leLat;
delete m_ui->leLat; delete m_ui->tbReset;
delete m_ui->tbReset; delete m_ui->lblLon;
delete m_ui->lblLon; delete m_ui->lblLat;
delete m_ui->lblLat;
} }
void Wgs84Edit::clear() void Wgs84Edit::clear()
{ {
m_ui->leLon->clear(); m_ui->leLon->clear();
m_ui->leLat->clear(); m_ui->leLat->clear();
} }
DoubleValidator::DoubleValidator(double bottom, double top, int decimals, QObject* parent)
: QDoubleValidator(bottom, top, decimals, parent)
DoubleValidator::DoubleValidator(double bottom, double top, int decimals, QObject *parent)
: QDoubleValidator(bottom, top, decimals, parent)
{}
QValidator::State DoubleValidator::validate(QString &input, int &pos) const
{ {
const QValidator::State ret = QDoubleValidator::validate(input, pos);
if (ret != QValidator::Acceptable)
return ret;
QLocale l;
const QChar gs = l.groupSeparator().at(0);
if (gs.isNull())
return ret;
if (input.contains(gs))
return QValidator::Invalid;
return ret;
} }
QValidator::State DoubleValidator::validate(QString& input, int& pos) const
{
const QValidator::State ret = QDoubleValidator::validate(input, pos);
if (ret != QValidator::Acceptable)
return ret;
QLocale l;
const QChar gs = l.groupSeparator().at(0);
if (gs.isNull())
return ret;
if (input.contains(gs))
return QValidator::Invalid;
return ret;
} }
} // namespace LtsCoordWidget
+79 -66
View File
@@ -2,93 +2,106 @@
#pragma once #pragma once
#include <QObject>
#include <QWidget>
#include <QComboBox>
#include <QVBoxLayout>
#include <LtsCoordTrans/lts_coord_trans.h>
#include "ui_lts_coord_widget_mgrs.h" #include "ui_lts_coord_widget_mgrs.h"
#include "ui_lts_coord_widget_wgs84.h" #include "ui_lts_coord_widget_wgs84.h"
#include <LtsCoordTrans/lts_coord_trans.h>
#include <QComboBox>
#include <QObject>
#include <QVBoxLayout>
#include <QWidget>
namespace LtsCoordWidget namespace LtsCoordWidget
{ {
class LtsCoordInputWidgetHandler : public QObject class LtsCoordInputWidgetHandler : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit LtsCoordInputWidgetHandler(QObject *parent) explicit LtsCoordInputWidgetHandler(QObject* parent) : QObject(parent) {}
: QObject(parent)
{}
virtual bool isValid() = 0; virtual bool isValid() = 0;
virtual void setCoordinate(const QPointF &geoCoord) = 0; virtual void setCoordinate(const QPointF& geoCoord) = 0;
virtual QPointF coordinate() const = 0; virtual QPointF coordinate() const = 0;
virtual QToolButton *resetButton() = 0; virtual QToolButton* resetButton() = 0;
virtual void cleanup() = 0; virtual void cleanup() = 0;
virtual void clear() = 0; virtual void clear() = 0;
virtual void setSquaresEditable(bool bEditable) = 0; virtual void setSquaresEditable(bool bEditable) = 0;
virtual void setWithSurroundingSquare(bool bEnabled) = 0; virtual void setWithSurroundingSquare(bool bEnabled) = 0;
virtual void setMgrsSquares(const QVector<LtsCoordTrans::UtmCoordinate> &geoCoords) = 0; virtual void setMgrsSquares(const QVector<LtsCoordTrans::UtmCoordinate>& geoCoords) = 0;
protected Q_SLOTS: protected Q_SLOTS:
void onCoordinateDataChanged(); void onCoordinateDataChanged();
Q_SIGNALS: Q_SIGNALS:
void coordinateChanged(const QPointF &newGeoCoord); void coordinateChanged(const QPointF& newGeoCoord);
void invalidCoordinate(); void invalidCoordinate();
}; };
class MgrsEdit final : public LtsCoordInputWidgetHandler class MgrsEdit final : public LtsCoordInputWidgetHandler
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit MgrsEdit(int precision, QWidget *widget); explicit MgrsEdit(int precision, QWidget* widget);
~MgrsEdit(); ~MgrsEdit();
bool isValid() override; bool isValid() override;
void setCoordinate(const QPointF &geoCoord) override; void setCoordinate(const QPointF& geoCoord) override;
QPointF coordinate() const override; QPointF coordinate() const override;
QToolButton *resetButton() override; QToolButton* resetButton() override;
void cleanup() override; void cleanup() override;
void clear() override; void clear() override;
void setSquaresEditable(bool bEditable) override; void setSquaresEditable(bool bEditable) override;
void setWithSurroundingSquare(bool bEnabled) override; void setWithSurroundingSquare(bool bEnabled) override;
void setMgrsSquares(const QVector<LtsCoordTrans::UtmCoordinate> &geoCoords) override; void setMgrsSquares(const QVector<LtsCoordTrans::UtmCoordinate>& geoCoords) override;
private:
void setDefaultMgrsSquares(); private:
void addMgrsSquare(const QString &newMgrsSquare); void setDefaultMgrsSquares();
QStringList utmCoordsToList(const QVector<LtsCoordTrans::UtmCoordinate> &coords); void addMgrsSquare(const QString& newMgrsSquare);
private: QStringList utmCoordsToList(const QVector<LtsCoordTrans::UtmCoordinate>& coords);
int m_precision;
bool m_withMgrsSquareOffset=false; private:
Ui::Mgrs *m_ui; int m_precision;
bool m_withMgrsSquareOffset = false;
Ui::Mgrs* m_ui;
}; };
class Wgs84Edit final : public LtsCoordInputWidgetHandler class Wgs84Edit final : public LtsCoordInputWidgetHandler
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit Wgs84Edit(QWidget *widget); explicit Wgs84Edit(QWidget* widget);
~Wgs84Edit(); ~Wgs84Edit();
bool isValid() override; bool isValid() override;
void setCoordinate(const QPointF &geoCoord) override; void setCoordinate(const QPointF& geoCoord) override;
QPointF coordinate() const override; QPointF coordinate() const override;
QToolButton *resetButton() override; QToolButton* resetButton() override;
void cleanup() override; void cleanup() override;
void clear() override; void clear() override;
void setSquaresEditable(bool bEditable) override { Q_UNUSED(bEditable); }
void setWithSurroundingSquare(bool bEnabled) override { Q_UNUSED(bEnabled); } void setSquaresEditable(bool bEditable) override
void setMgrsSquares(const QVector<LtsCoordTrans::UtmCoordinate> &geoCoords) override { Q_UNUSED(geoCoords); } {
private: Q_UNUSED(bEditable);
Ui::Wgs84 *m_ui; }
void setWithSurroundingSquare(bool bEnabled) override
{
Q_UNUSED(bEnabled);
}
void setMgrsSquares(const QVector<LtsCoordTrans::UtmCoordinate>& geoCoords) override
{
Q_UNUSED(geoCoords);
}
private:
Ui::Wgs84* m_ui;
}; };
class DoubleValidator final : public QDoubleValidator class DoubleValidator final : public QDoubleValidator
{ {
Q_OBJECT Q_OBJECT
public: public:
DoubleValidator(double bottom, double top, int decimals, QObject *parent = nullptr); DoubleValidator(double bottom, double top, int decimals, QObject* parent = nullptr);
QValidator::State validate(QString &input, int &pos) const override; QValidator::State validate(QString& input, int& pos) const override;
}; };
} } // namespace LtsCoordWidget
+88 -97
View File
@@ -1,115 +1,106 @@
#include <QApplication>
#include <QDialog>
#include <QPushButton>
#include <QVBoxLayout>
#include <QLabel>
#include <LtsCoordTrans/lts_coord_trans.h>
#include "lts_coord_widget.h" #include "lts_coord_widget.h"
static void updateLabel(const QPointF &coord, QLabel *lbl, int prec) #include <LtsCoordTrans/lts_coord_trans.h>
#include <QApplication>
#include <QDialog>
#include <QLabel>
#include <QPushButton>
#include <QVBoxLayout>
static void updateLabel(const QPointF& coord, QLabel* lbl, int prec)
{ {
QString mgrs = LtsCoordTrans::mgrsFromGeographic(coord.x(), coord.y(), prec); QString mgrs = LtsCoordTrans::mgrsFromGeographic(coord.x(), coord.y(), prec);
QString str = QStringLiteral("mgrs: %1, lon: %2, lat: %3") QString str = QStringLiteral("mgrs: %1, lon: %2, lat: %3")
.arg(mgrs) .arg(mgrs)
.arg(coord.x() * LtsCoordTrans::rad2deg(), 0, 'f', 10) .arg(coord.x() * LtsCoordTrans::rad2deg(), 0, 'f', 10)
.arg(coord.y() * LtsCoordTrans::rad2deg(), 0, 'f', 10); .arg(coord.y() * LtsCoordTrans::rad2deg(), 0, 'f', 10);
lbl->setText(str); lbl->setText(str);
} }
int main(int argc, char **argv) int main(int argc, char** argv)
{ {
QApplication app(argc, argv); QApplication app(argc, argv);
LtsCoordTrans::UtmCoordinate base(LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32UMD00"))); LtsCoordTrans::UtmCoordinate base(LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32UMD00")));
QPointF topLeft(base.geographic(+50000, -50000)); QPointF topLeft(base.geographic(+50000, -50000));
QPointF bottomRight(base.geographic(-50000, 50000)); QPointF bottomRight(base.geographic(-50000, 50000));
LtsCoordTrans::getMgrsSquares(QRectF(topLeft, bottomRight), true, true); LtsCoordTrans::getMgrsSquares(QRectF(topLeft, bottomRight), true, true);
QDialog *dialog(new QDialog); QDialog* dialog(new QDialog);
QVBoxLayout *lay(new QVBoxLayout(dialog)); QVBoxLayout* lay(new QVBoxLayout(dialog));
const QPointF defCoord(QPointF(53.0, 8.0) * LtsCoordTrans::deg2rad());
const QPointF defCoord(QPointF(53.0, 8.0) * LtsCoordTrans::deg2rad()); LtsCoordWidget::LtsCoordWidget* wMgrs5(
new LtsCoordWidget::LtsCoordWidget(LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS, dialog));
wMgrs5->setWithResetButton(true);
wMgrs5->setCoordinate(defCoord, true);
lay->addWidget(wMgrs5);
QLabel* lbl5(new QLabel(dialog));
lay->addWidget(lbl5);
QObject::connect(wMgrs5, &LtsCoordWidget::LtsCoordWidget::coordinateChanged, lbl5,
[lbl5](const QPointF& coord) { updateLabel(coord, lbl5, 5); });
LtsCoordWidget::LtsCoordWidget *wMgrs5(new LtsCoordWidget::LtsCoordWidget(LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS, dialog)); LtsCoordWidget::LtsCoordWidget* wMgrs7(
wMgrs5->setWithResetButton(true); new LtsCoordWidget::LtsCoordWidget(LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS7, dialog));
wMgrs5->setCoordinate(defCoord, true); wMgrs7->setWithResetButton(true);
lay->addWidget(wMgrs5); wMgrs7->setCoordinate(defCoord, true);
QLabel *lbl5(new QLabel(dialog)); lay->addWidget(wMgrs7);
lay->addWidget(lbl5); QLabel* lbl7(new QLabel(dialog));
QObject::connect(wMgrs5, &LtsCoordWidget::LtsCoordWidget::coordinateChanged, lay->addWidget(lbl7);
lbl5, [lbl5](const QPointF & coord) QObject::connect(wMgrs7, &LtsCoordWidget::LtsCoordWidget::coordinateChanged, wMgrs7,
{ [lbl7](const QPointF& coord) { updateLabel(coord, lbl7, 7); });
updateLabel(coord, lbl5, 5);
});
LtsCoordWidget::LtsCoordWidget* w84(
new LtsCoordWidget::LtsCoordWidget(LtsCoordWidget::LtsCoordWidget::DisplayType::WGS84, dialog));
w84->setWithResetButton(true);
w84->setCoordinate(defCoord, true);
lay->addWidget(w84);
QLabel* lbl84(new QLabel(dialog));
lay->addWidget(lbl84);
QObject::connect(w84, &LtsCoordWidget::LtsCoordWidget::coordinateChanged, w84,
[lbl84](const QPointF& coord) { updateLabel(coord, lbl84, 11); });
LtsCoordWidget::LtsCoordWidget *wMgrs7(new LtsCoordWidget::LtsCoordWidget(LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS7, dialog)); QHBoxLayout* hLay = new QHBoxLayout;
wMgrs7->setWithResetButton(true); lay->addLayout(hLay);
wMgrs7->setCoordinate(defCoord, true); LtsCoordWidget::LtsCoordWidget* wChange(
lay->addWidget(wMgrs7); new LtsCoordWidget::LtsCoordWidget(LtsCoordWidget::LtsCoordWidget::DisplayType::WGS84, dialog));
QLabel *lbl7(new QLabel(dialog)); wChange->setWithResetButton(true);
lay->addWidget(lbl7); wChange->setCoordinate(defCoord, true);
QObject::connect(wMgrs7, &LtsCoordWidget::LtsCoordWidget::coordinateChanged, hLay->addWidget(wChange);
wMgrs7, [lbl7](const QPointF & coord) QPushButton* pbReset(new QPushButton(QStringLiteral("With Reset"), dialog));
{ hLay->addWidget(pbReset);
updateLabel(coord, lbl7, 7); QObject::connect(pbReset, &QPushButton::clicked, wChange,
}); [wChange]() { wChange->setWithResetButton(!wChange->withResetButton()); });
QPushButton* pbNext(new QPushButton(QStringLiteral("Next Type"), dialog));
hLay->addWidget(pbNext);
QObject::connect(pbNext, &QPushButton::clicked, wChange, [wChange]() {
LtsCoordWidget::LtsCoordWidget::DisplayType dt = wChange->displayType();
switch (dt)
{
case LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS5:
dt = LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS7;
break;
case LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS7:
dt = LtsCoordWidget::LtsCoordWidget::DisplayType::WGS84;
break;
case LtsCoordWidget::LtsCoordWidget::DisplayType::WGS84:
dt = LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS5;
break;
default:
break;
}
wChange->setDisplayType(dt);
});
QPushButton* pb(new QPushButton(QStringLiteral("Quit"), dialog));
lay->addWidget(pb);
QObject::connect(pb, &QPushButton::clicked, qApp, QCoreApplication::quit);
LtsCoordWidget::LtsCoordWidget *w84(new LtsCoordWidget::LtsCoordWidget(LtsCoordWidget::LtsCoordWidget::DisplayType::WGS84, dialog)); dialog->show();
w84->setWithResetButton(true); int ret = app.exec();
w84->setCoordinate(defCoord, true); delete dialog;
lay->addWidget(w84); return ret;
QLabel *lbl84(new QLabel(dialog));
lay->addWidget(lbl84);
QObject::connect(w84, &LtsCoordWidget::LtsCoordWidget::coordinateChanged,
w84, [lbl84](const QPointF & coord)
{
updateLabel(coord, lbl84, 11);
});
QHBoxLayout *hLay = new QHBoxLayout;
lay->addLayout(hLay);
LtsCoordWidget::LtsCoordWidget *wChange(new LtsCoordWidget::LtsCoordWidget(LtsCoordWidget::LtsCoordWidget::DisplayType::WGS84, dialog));
wChange->setWithResetButton(true);
wChange->setCoordinate(defCoord, true);
hLay->addWidget(wChange);
QPushButton *pbReset(new QPushButton(QStringLiteral("With Reset"), dialog));
hLay->addWidget(pbReset);
QObject::connect(pbReset, &QPushButton::clicked,
wChange, [wChange]() { wChange->setWithResetButton(!wChange->withResetButton());});
QPushButton *pbNext(new QPushButton(QStringLiteral("Next Type"), dialog));
hLay->addWidget(pbNext);
QObject::connect(pbNext, &QPushButton::clicked,
wChange, [wChange]()
{
LtsCoordWidget::LtsCoordWidget::DisplayType dt = wChange->displayType();
switch (dt)
{
case LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS5:
dt = LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS7; break;
case LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS7:
dt = LtsCoordWidget::LtsCoordWidget::DisplayType::WGS84; break;
case LtsCoordWidget::LtsCoordWidget::DisplayType::WGS84:
dt = LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS5; break;
default:
break;
}
wChange->setDisplayType(dt);
});
QPushButton *pb(new QPushButton(QStringLiteral("Quit"), dialog));
lay->addWidget(pb);
QObject::connect(pb, &QPushButton::clicked, qApp, QCoreApplication::quit);
dialog->show();
int ret = app.exec();
delete dialog;
return ret;
} }
+34 -35
View File
@@ -1,45 +1,44 @@
#include <GeographicLib/UTMUPS.hpp>
#include <GeographicLib/MGRS.hpp> #include <GeographicLib/MGRS.hpp>
#include <GeographicLib/UTMUPS.hpp>
#include <string> #include <string>
int main(int argc, char **argv) int main(int argc, char** argv)
{ {
if (argc != 2) if (argc != 2)
{ {
fprintf(stderr, "Usage: %s <mgrs>\n", argv[0]); fprintf(stderr, "Usage: %s <mgrs>\n", argv[0]);
return -1; return -1;
} }
std::string mgrs = argv[1]; std::string mgrs = argv[1];
mgrs.erase(remove_if(mgrs.begin(), mgrs.end(), isspace), mgrs.end()); mgrs.erase(remove_if(mgrs.begin(), mgrs.end(), isspace), mgrs.end());
int prec; int prec;
double lonDeg, latDeg; double lonDeg, latDeg;
try try
{ {
int zone; int zone;
bool northp; bool northp;
double x, y; double x, y;
GeographicLib::MGRS::Reverse(mgrs, zone, northp, x, y, prec, true); GeographicLib::MGRS::Reverse(mgrs, zone, northp, x, y, prec, true);
GeographicLib::UTMUPS::Reverse(zone, northp, x, y, latDeg, lonDeg); GeographicLib::UTMUPS::Reverse(zone, northp, x, y, latDeg, lonDeg);
GeographicLib::UTMUPS::Forward(latDeg, lonDeg, zone, northp, x, y); GeographicLib::UTMUPS::Forward(latDeg, lonDeg, zone, northp, x, y);
GeographicLib::MGRS::Forward(zone, northp, x, y, prec, mgrs); GeographicLib::MGRS::Forward(zone, northp, x, y, prec, mgrs);
} }
catch (...) catch (...)
{ {
fprintf(stderr, "Error converting %s to Lon/Lat coords\n", mgrs.c_str()); fprintf(stderr, "Error converting %s to Lon/Lat coords\n", mgrs.c_str());
return -2; return -2;
} }
std::string part1, part2, part3, part4; std::string part1, part2, part3, part4;
part1 = mgrs.substr(0, 3); part1 = mgrs.substr(0, 3);
part2 = mgrs.substr(3, 2); part2 = mgrs.substr(3, 2);
part3 = mgrs.substr(5, prec); part3 = mgrs.substr(5, prec);
part4 = mgrs.substr(5 + prec, prec); part4 = mgrs.substr(5 + prec, prec);
fprintf(stdout, "%s %s %s %s = %13.10f, %13.10f ( %13.10f, %13.10f )\n", fprintf(stdout, "%s %s %s %s = %13.10f, %13.10f ( %13.10f, %13.10f )\n", part1.c_str(), part2.c_str(),
part1.c_str(), part2.c_str(), part3.c_str(), part4.c_str(), lonDeg, latDeg, lonDeg / 180. * M_PI, latDeg / 180. * M_PI); part3.c_str(), part4.c_str(), lonDeg, latDeg, lonDeg / 180. * M_PI, latDeg / 180. * M_PI);
return 0; return 0;
} }
File diff suppressed because it is too large. Load diff
@@ -1,85 +1,60 @@
#pragma once #pragma once
#include <QObject>
#include <LtsElevation/lts_elevation_manager.h>
#include <ElevationMap/elevation_map_manager.h> #include <ElevationMap/elevation_map_manager.h>
#include <LtsElevation/lts_elevation_manager.h>
#include <QCoreApplication>
#include <QtTest/QTest>
#include <NGLLogger/INGLLogger.h> #include <NGLLogger/INGLLogger.h>
#include <QCoreApplication>
#include <QObject>
#include <QtTest/QTest>
using LOGGER_T = NGL::INGLLogger&; using LOGGER_T = NGL::INGLLogger&;
class UnitTestCoordinate : public QObject class UnitTestCoordinate : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
UnitTestCoordinate(); UnitTestCoordinate();
private Q_SLOTS:
private Q_SLOTS: void initTestCase();
void init();
void test_NaN();
void test_coordinate_simple1();
void test_coordinate_simple2();
void test_coordinate_simple3();
void test_coordinate_simple4();
void test_coordinate_fromUtm();
void test_coordinate_fromUtm2();
void test_coordinate_elevationAt();
void test_coordinate_elevationAt_isCovered();
void initTestCase(); void test_coordinate_elevation_data();
void test_coordinate_elevation();
void init(); void test_coordinate_mgrs();
void test_coordinate_distance();
void test_coordinate_distanceDiffZones();
void test_squareInDifferentZone();
void test_NaN(); void test_coordinate_angle();
void test_coordinate_simple1(); void test_coordinate_cont();
void test_coordinate_simple2();
void test_coordinate_simple3();
void test_coordinate_simple4();
void test_coordinate_fromUtm(); void test_coordinate_avoid_copy();
void test_coordinate_fromUtm2();
void test_coordinate_elevationAt(); void test_container_references();
void test_coordinate_elevationAt_isCovered(); void test_coordVector();
void test_coordinate_elevation_data(); private:
void test_coordinate_elevation(); NGL::INGLLogger& m_logger;
void test_coordinate_mgrs();
void test_coordinate_distance();
void test_coordinate_distanceDiffZones();
void test_squareInDifferentZone();
void test_coordinate_angle();
void test_coordinate_cont();
void test_coordinate_avoid_copy();
void test_container_references();
void test_coordVector();
private:
NGL::INGLLogger &m_logger;
}; };
+34 -55
View File
@@ -1,90 +1,69 @@
#include "lts_coord_vector.h" #include "lts_coord_vector.h"
namespace LtsCoordTrans namespace LtsCoordTrans
{ {
LtsCoordVector::LtsCoordVector(const std::vector<Core::GeoPosition> &geo_coordinates) LtsCoordVector::LtsCoordVector(const std::vector<Core::GeoPosition>& geo_coordinates)
: m_geo_coordinates(geo_coordinates) : m_geo_coordinates(geo_coordinates)
{ {
} }
const std::vector<UtmCoordinate> &LtsCoordVector::toStdUtmCoord(int zone) const const std::vector<UtmCoordinate>& LtsCoordVector::toStdUtmCoord(int zone) const
{ {
convertGeoToStdUtm(zone); convertGeoToStdUtm(zone);
return m_utmMapStd[zone]; return m_utmMapStd[zone];
} }
const QVector<UtmCoordinate> &LtsCoordVector::toQVectorUtmCoord(int zone) const const QVector<UtmCoordinate>& LtsCoordVector::toQVectorUtmCoord(int zone) const
{ {
convertGeoToQVectorUtm(zone); convertGeoToQVectorUtm(zone);
return m_utmMapQVector[zone]; return m_utmMapQVector[zone];
} }
const QVector<QPointF> &LtsCoordVector::toQVectorQPointF(int zone) const const QVector<QPointF>& LtsCoordVector::toQVectorQPointF(int zone) const
{ {
convertGeoToQVectorQPointF(zone); convertGeoToQVectorQPointF(zone);
return m_utmMapQVectorQPointF[zone]; return m_utmMapQVectorQPointF[zone];
} }
void LtsCoordVector::convertGeoToStdUtm(int zone) const void LtsCoordVector::convertGeoToStdUtm(int zone) const
{ {
const auto it = m_utmMapStd.find(zone); const auto it = m_utmMapStd.find(zone);
if (it != m_utmMapStd.end()) if (it != m_utmMapStd.end())
return; return;
convertGeoToUtmInternal(zone, m_utmMapStd[zone]); convertGeoToUtmInternal(zone, m_utmMapStd[zone]);
} }
void LtsCoordVector::convertGeoToQVectorUtm(int zone) const void LtsCoordVector::convertGeoToQVectorUtm(int zone) const
{ {
const auto it = m_utmMapQVector.find(zone); const auto it = m_utmMapQVector.find(zone);
if (it != m_utmMapQVector.end()) if (it != m_utmMapQVector.end())
return; return;
convertGeoToStdUtm(zone);
QVector<LtsCoordTrans::UtmCoordinate>& utmVectorRef = m_utmMapQVector[zone];
utmVectorRef.clear();
utmVectorRef.reserve(m_geo_coordinates.size());
for (const auto& utmCoord : m_utmMapStd[zone])
utmVectorRef.push_back(utmCoord);
convertGeoToStdUtm(zone);
QVector<LtsCoordTrans::UtmCoordinate> &utmVectorRef = m_utmMapQVector[zone];
utmVectorRef.clear();
utmVectorRef.reserve(m_geo_coordinates.size());
for (const auto &utmCoord : m_utmMapStd[zone])
utmVectorRef.push_back(utmCoord);
} }
void LtsCoordVector::convertGeoToQVectorQPointF(int zone) const void LtsCoordVector::convertGeoToQVectorQPointF(int zone) const
{ {
const auto it = m_utmMapQVectorQPointF.find(zone); const auto it = m_utmMapQVectorQPointF.find(zone);
if (it != m_utmMapQVectorQPointF.end()) if (it != m_utmMapQVectorQPointF.end())
return; return;
convertGeoToStdUtm(zone); convertGeoToStdUtm(zone);
QVector<QPointF> &QVectorQPointFRef = m_utmMapQVectorQPointF[zone]; QVector<QPointF>& QVectorQPointFRef = m_utmMapQVectorQPointF[zone];
QVectorQPointFRef.clear(); QVectorQPointFRef.clear();
QVectorQPointFRef.reserve(m_geo_coordinates.size()); QVectorQPointFRef.reserve(m_geo_coordinates.size());
for (const auto &utmCoord : m_utmMapStd[zone]) for (const auto& utmCoord : m_utmMapStd[zone])
QVectorQPointFRef.push_back(QPointF(utmCoord.x, utmCoord.y)); QVectorQPointFRef.push_back(QPointF(utmCoord.x, utmCoord.y));
} }
} // namespace LtsCoordTrans
}
+33 -53
View File
@@ -1,82 +1,62 @@
#pragma once #pragma once
#include "ltscoordinate_export.h" #include "ltscoordinate_export.h"
#include <utility>
#include <Core/core.hpp> #include <Core/core.hpp>
#include <LtsCoordTrans/lts_coord_trans.h> #include <LtsCoordTrans/lts_coord_trans.h>
#include <QDebug>
#include <unordered_map>
#include <QPointF> #include <QPointF>
#include <QVector> #include <QVector>
#include <QDebug>
#include <iosfwd> #include <iosfwd>
#include <unordered_map>
#include <utility>
#include <vector> #include <vector>
namespace LtsCoordTrans namespace LtsCoordTrans
{ {
class LTSCOORDINATE_EXPORT LtsCoordVector class LTSCOORDINATE_EXPORT LtsCoordVector
{ {
public: public:
explicit LtsCoordVector(const std::vector<Core::GeoPosition>& geo_coordinates);
int size() const
{
return m_geo_coordinates.size();
}
const std::vector<Core::GeoPosition>& geoPosition() const
{
return m_geo_coordinates;
}
explicit LtsCoordVector(const std::vector<Core::GeoPosition> &geo_coordinates); const std::vector<LtsCoordTrans::UtmCoordinate>& toStdUtmCoord(int zone) const;
const QVector<LtsCoordTrans::UtmCoordinate>& toQVectorUtmCoord(int zone) const;
const QVector<QPointF>& toQVectorQPointF(int zone) const;
protected:
void convertGeoToStdUtm(int zone) const;
void convertGeoToQVectorUtm(int zone) const;
void convertGeoToQVectorQPointF(int zone) const;
template <typename T> void convertGeoToUtmInternal(int zone, T& utmVectorRef) const
{
int size() const { return m_geo_coordinates.size() ; } utmVectorRef.clear();
const std::vector<Core::GeoPosition> &geoPosition() const { return m_geo_coordinates; } utmVectorRef.reserve(m_geo_coordinates.size());
for (const auto& geoCoord : std::as_const(m_geo_coordinates))
utmVectorRef.push_back(LtsCoordTrans::UtmCoordinate::fromGeographic(geoCoord.lon(), geoCoord.lat(), zone));
}
protected:
std::vector<Core::GeoPosition> m_geo_coordinates;
mutable std::unordered_map<int, std::vector<LtsCoordTrans::UtmCoordinate>> m_utmMapStd;
const std::vector<LtsCoordTrans::UtmCoordinate> &toStdUtmCoord(int zone) const; mutable std::unordered_map<int, QVector<LtsCoordTrans::UtmCoordinate>> m_utmMapQVector;
const QVector<LtsCoordTrans::UtmCoordinate> &toQVectorUtmCoord(int zone) const; mutable std::unordered_map<int, QVector<QPointF>> m_utmMapQVectorQPointF;
const QVector<QPointF> &toQVectorQPointF(int zone) const;
protected:
void convertGeoToStdUtm(int zone) const;
void convertGeoToQVectorUtm(int zone) const;
void convertGeoToQVectorQPointF(int zone) const;
template<typename T>
void convertGeoToUtmInternal(int zone, T &utmVectorRef) const
{
utmVectorRef.clear();
utmVectorRef.reserve(m_geo_coordinates.size());
for (const auto &geoCoord : std::as_const(m_geo_coordinates))
utmVectorRef.push_back(LtsCoordTrans::UtmCoordinate::fromGeographic(geoCoord.lon(), geoCoord.lat(), zone));
}
protected:
std::vector<Core::GeoPosition> m_geo_coordinates;
mutable std::unordered_map<int, std::vector<LtsCoordTrans::UtmCoordinate>> m_utmMapStd;
mutable std::unordered_map<int, QVector<LtsCoordTrans::UtmCoordinate>> m_utmMapQVector;
mutable std::unordered_map<int, QVector<QPointF>> m_utmMapQVectorQPointF;
}; };
} // namespace LtsCoordTrans
}
+67 -103
View File
@@ -1,8 +1,7 @@
#include "lts_coordinate.h" #include "lts_coordinate.h"
#include <QLineF> #include <QLineF>
namespace LtsCoordTrans namespace LtsCoordTrans
@@ -10,169 +9,134 @@ namespace LtsCoordTrans
static long s_conversion_counter = 0; static long s_conversion_counter = 0;
std::function<double(double, double, double, bool*)> LtsCoordinate::m_getElevationCB; std::function<double(double, double, double, bool*)> LtsCoordinate::m_getElevationCB;
void LtsCoordinate::setElevationCallback(const elevationCbFunc& elevationCB)
void LtsCoordinate::setElevationCallback(const elevationCbFunc &elevationCB)
{ {
m_getElevationCB = elevationCB; m_getElevationCB = elevationCB;
} }
bool LtsCoordinate::hasElevationCallback() bool LtsCoordinate::hasElevationCallback()
{ {
return m_getElevationCB != nullptr; return m_getElevationCB != nullptr;
} }
double LtsCoordinate::elevationAt(double defaultElevation, bool *bIsCovered) const double LtsCoordinate::elevationAt(double defaultElevation, bool* bIsCovered) const
{ {
if (!bIsCovered)
if (!std::isnan(m_elevation))
if (!bIsCovered) return m_elevation;
if (!std::isnan(m_elevation)) if (m_getElevationCB)
return m_elevation; m_elevation = m_getElevationCB(m_geo.lon(), m_geo.lat(), defaultElevation, bIsCovered);
if (m_getElevationCB) return m_elevation;
m_elevation = m_getElevationCB(m_geo.lon(), m_geo.lat(), defaultElevation, bIsCovered);
return m_elevation;
} }
void LtsCoordinate::setZValueAccordingElevation(double defaultElevation) void LtsCoordinate::setZValueAccordingElevation(double defaultElevation)
{ {
m_geo.z(elevationAt(defaultElevation)); m_geo.z(elevationAt(defaultElevation));
} }
double LtsCoordinate::elevationAt(const LtsCoordinate &coordinate, double defaultElevation, bool *bIsCovered) double LtsCoordinate::elevationAt(const LtsCoordinate& coordinate, double defaultElevation, bool* bIsCovered)
{ {
return coordinate.elevationAt(defaultElevation, bIsCovered); return coordinate.elevationAt(defaultElevation, bIsCovered);
} }
void LtsCoordinate::replaceZValueByElevationIfValue(double zValueToBeReplaced, double defaultElevation) void LtsCoordinate::replaceZValueByElevationIfValue(double zValueToBeReplaced, double defaultElevation)
{ {
if ((std::isnan(zValueToBeReplaced) && std::isnan(m_geo.z())) || qFuzzyCompare(m_geo.z(), zValueToBeReplaced))
setZValueAccordingElevation(defaultElevation);
if ((std::isnan(zValueToBeReplaced) && std::isnan(m_geo.z())) ||
qFuzzyCompare(m_geo.z(), zValueToBeReplaced))
setZValueAccordingElevation(defaultElevation);
} }
double LtsCoordinate::angleDegreeUtm2D(const LtsCoordinate &coord1, const LtsCoordinate &coord2) double LtsCoordinate::angleDegreeUtm2D(const LtsCoordinate& coord1, const LtsCoordinate& coord2)
{ {
const LtsCoordTrans::UtmCoordinate &utm1 = coord1.utmCoordinate(); const LtsCoordTrans::UtmCoordinate& utm1 = coord1.utmCoordinate();
const LtsCoordTrans::UtmCoordinate &utm2 = coord2.utmCoordinateDiffZone(utm1.zone); const LtsCoordTrans::UtmCoordinate& utm2 = coord2.utmCoordinateDiffZone(utm1.zone);
const QPointF& offsetUtm = utm2.toPoint() - utm1.toPoint(); const QPointF& offsetUtm = utm2.toPoint() - utm1.toPoint();
QLineF poly(QPointF(), offsetUtm); QLineF poly(QPointF(), offsetUtm);
const double angle = poly.angle(); const double angle = poly.angle();
return fmod(angle + 90.0, 360);
return fmod(angle+90.0, 360);
} }
const UtmCoordinate &LtsCoordinate::utmCoordinateInternal(int zone) const const UtmCoordinate& LtsCoordinate::utmCoordinateInternal(int zone) const
{ {
if (zone == -1) if (zone == -1)
{ {
if (!hasUtm()) if (!hasUtm())
convertGeoToUtm(); convertGeoToUtm();
return m_utm2D; return m_utm2D;
} }
utmCoordinateDiffZone(zone); utmCoordinateDiffZone(zone);
return m_utm2D_differentZone; return m_utm2D_differentZone;
} }
void LtsCoordinate::convertGeoToUtm() const void LtsCoordinate::convertGeoToUtm() const
{ {
int zone = -1; int zone = -1;
if (std::isnan(m_geo.lon()) || std::isnan(m_geo.lat())) if (std::isnan(m_geo.lon()) || std::isnan(m_geo.lat()))
{ {
fprintf(stderr, "Error while fromGeographic, value is NaN\n"); fprintf(stderr, "Error while fromGeographic, value is NaN\n");
m_utm2D = LtsCoordTrans::UtmCoordinate(); m_utm2D = LtsCoordTrans::UtmCoordinate();
return; return;
} }
#ifdef LTS_DEBUG #ifdef LTS_DEBUG
++s_conversion_counter; ++s_conversion_counter;
#endif #endif
m_utm2D = LtsCoordTrans::UtmCoordinate::fromGeographic(m_geo.lon(), m_geo.lat(), zone); m_utm2D = LtsCoordTrans::UtmCoordinate::fromGeographic(m_geo.lon(), m_geo.lat(), zone);
Q_ASSERT_X(m_utm2D.zone > 0, "LtsCoordinate", "zone has to be set"); Q_ASSERT_X(m_utm2D.zone > 0, "LtsCoordinate", "zone has to be set");
} }
QString LtsCoordinate::mgrs(int prec, bool withSpaces) const QString LtsCoordinate::mgrs(int prec, bool withSpaces) const
{ {
utmCoordinateInternal(); utmCoordinateInternal();
QString tmp = m_utm2D.mgrs(prec, withSpaces); QString tmp = m_utm2D.mgrs(prec, withSpaces);
return tmp; return tmp;
} }
QString LtsCoordinate::mgrsWithZ(int prec, bool withSpaces) const QString LtsCoordinate::mgrsWithZ(int prec, bool withSpaces) const
{ {
double ele = elevationAt(); double ele = elevationAt();
QString tmp = mgrs(prec, withSpaces) + QStringLiteral(" z=") + QString::number(ele, 'f', 2); QString tmp = mgrs(prec, withSpaces) + QStringLiteral(" z=") + QString::number(ele, 'f', 2);
return tmp; return tmp;
} }
QString LtsCoordinate::toString(bool fullAndExpensive) const QString LtsCoordinate::toString(bool fullAndExpensive) const
{ {
if (fullAndExpensive) if (fullAndExpensive)
{ {
utmCoordinateInternal(); utmCoordinateInternal();
elevationAt(); elevationAt();
} }
std::ostringstream stream; std::ostringstream stream;
stream << "LtsCoordinate(m_geo=" << m_geo stream << "LtsCoordinate(m_geo=" << m_geo << ", m_utm2D.x " << m_utm2D.x << ", m_utm2D.y " << m_utm2D.y
<< ", m_utm2D.x " << m_utm2D.x << ", m_utm2D.y " << m_utm2D.y << ", m_utm2D.zone " << m_utm2D.zone; << ", m_utm2D.zone " << m_utm2D.zone;
if (!qFuzzyIsNull(m_utm2D.x) || !qFuzzyIsNull(m_utm2D.y)) if (!qFuzzyIsNull(m_utm2D.x) || !qFuzzyIsNull(m_utm2D.y))
stream << ", m_utm2D.mgrs '" << m_utm2D.mgrs().toUtf8().constData() << "'"; stream << ", m_utm2D.mgrs '" << m_utm2D.mgrs().toUtf8().constData() << "'";
stream << ", elevation " << std::fixed << std::setprecision(3) << m_elevation stream << ", elevation " << std::fixed << std::setprecision(3) << m_elevation << ")";
<< ")"; return QString::fromStdString(stream.str());
return QString::fromStdString(stream.str());
} }
void LtsCoordinate::resetConversionCounter() void LtsCoordinate::resetConversionCounter()
{ {
s_conversion_counter = 0; s_conversion_counter = 0;
} }
long LtsCoordinate::getConversionCounter() long LtsCoordinate::getConversionCounter()
{ {
return s_conversion_counter; return s_conversion_counter;
} }
std::ostream& operator<<(std::ostream& stream, const LtsCoordinate& value)
std::ostream &operator<<(std::ostream &stream, const LtsCoordinate &value)
{ {
stream << value.toString().toStdString(); stream << value.toString().toStdString();
return stream; return stream;
} }
} } // namespace LtsCoordTrans
+260 -331
View File
@@ -1,368 +1,297 @@
#pragma once #pragma once
#include "ltscoordinate_export.h" #include "ltscoordinate_export.h"
#include <utility>
#include <Core/core.hpp> #include <Core/core.hpp>
#include <LtsCoordTrans/lts_coord_trans.h> #include <LtsCoordTrans/lts_coord_trans.h>
#include <LtsUtils/LtsUtilsCore/qpoint3d.h> #include <LtsUtils/LtsUtilsCore/qpoint3d.h>
#include <QPointF>
#include <QDebug> #include <QDebug>
#include <QPointF>
#include <functional> #include <functional>
#include <iosfwd> #include <iosfwd>
#include <type_traits> #include <type_traits>
#include <utility>
namespace LtsCoordTrans namespace LtsCoordTrans
{ {
using UtmCoordinate2D = LtsCoordTrans::UtmCoordinate; using UtmCoordinate2D = LtsCoordTrans::UtmCoordinate;
using QPoint3D = LtsUtils::QPoint3D; using QPoint3D = LtsUtils::QPoint3D;
class LTSCOORDINATE_EXPORT LtsCoordinate class LTSCOORDINATE_EXPORT LtsCoordinate
{ {
public: public:
explicit LtsCoordinate(double lon = 0, double lat = 0, double z = std::nan(""))
: m_geo(Core::GeoPosition(lon, lat, z))
{
}
explicit LtsCoordinate(const QPointF& lonLat, double z = std::nan(""))
: m_geo(Core::GeoPosition(lonLat.x(), lonLat.y(), z))
explicit LtsCoordinate(double lon = 0, double lat = 0, double z = std::nan("")) {
: m_geo(Core::GeoPosition(lon, lat, z)) }
{}
explicit LtsCoordinate(const Core::GeoPosition& geoPos) : m_geo(geoPos) {}
explicit LtsCoordinate(const QPointF &lonLat, double z = std::nan(""))
: m_geo(Core::GeoPosition(lonLat.x(), lonLat.y(), z)) explicit LtsCoordinate(const Core::GeoPosition2D& geoPos2D) : m_geo(geoPos2D.lon(), geoPos2D.lat(), std::nan("")) {}
{}
LtsCoordinate(const LtsCoordTrans::UtmCoordinate& utm2D, double zValue) = delete;
explicit LtsCoordinate(const Core::GeoPosition &geoPos)
: m_geo(geoPos) static LtsCoordinate fromGeoPosition(double lon, double lat, double z = std::nan(""))
{} {
return LtsCoordinate(lon, lat, z);
explicit LtsCoordinate(const Core::GeoPosition2D &geoPos2D) }
: m_geo(geoPos2D.lon(), geoPos2D.lat(), std::nan(""))
{} static LtsCoordinate fromUtmCoordinate(const LtsCoordTrans::UtmCoordinate& utm2D, double zValue)
{
Q_ASSERT_X(utm2D.zone > 0, "LtsCoordinate", "zone has to be set");
LtsCoordinate(const LtsCoordTrans::UtmCoordinate &utm2D, double zValue) = delete; const QPointF& geoPnt = utm2D.geographic();
static LtsCoordinate fromGeoPosition(double lon, double lat, double z = std::nan("")) return LtsCoordinate(geoPnt.x(), geoPnt.y(), zValue);
{ }
return LtsCoordinate(lon, lat, z);
} static LtsCoordinate fromUtm(const QPointF& utm2d, int zone, double zValue)
{
const LtsCoordTrans::UtmCoordinate utmCoord(zone, utm2d.x(), utm2d.y());
static LtsCoordinate fromUtmCoordinate(const LtsCoordTrans::UtmCoordinate &utm2D, double zValue) const QPointF& geoPnt = utmCoord.geographic();
{ return LtsCoordinate(geoPnt.x(), geoPnt.y(), zValue);
Q_ASSERT_X(utm2D.zone > 0, "LtsCoordinate", "zone has to be set"); }
bool isValid() const
{
const QPointF &geoPnt = utm2D.geographic(); return hasGeo() || hasUtm();
}
return LtsCoordinate(geoPnt.x(), geoPnt.y(), zValue);
} bool hasGeo() const
{
static LtsCoordinate fromUtm(const QPointF &utm2d, int zone, double zValue) return !(valueIsNullOrNan(m_geo.lon()) || valueIsNullOrNan(m_geo.lat()));
{ }
const LtsCoordTrans::UtmCoordinate utmCoord(zone, utm2d.x(), utm2d.y());
const QPointF &geoPnt = utmCoord.geographic(); bool hasUtm() const
return LtsCoordinate(geoPnt.x(), geoPnt.y(), zValue); {
} return m_utm2D.isValid();
}
static bool valueIsNullOrNan(double value)
{
return qFuzzyIsNull(value) || std::isnan(value);
}
bool isValid() const { return hasGeo() || hasUtm(); }
bool hasGeo() const { return !(valueIsNullOrNan(m_geo.lon()) || QString mgrs(int prec = 5, bool withSpaces = true) const;
valueIsNullOrNan(m_geo.lat())); } QString mgrsWithZ(int prec = 5, bool withSpaces = true) const;
bool hasUtm() const { return m_utm2D.isValid(); }
QString toString(bool fullAndExpensive = false) const;
static bool valueIsNullOrNan(double value) { return qFuzzyIsNull(value) || std::isnan(value); }
static void resetConversionCounter();
QString mgrs(int prec = 5, bool withSpaces = true) const; static long getConversionCounter();
QString mgrsWithZ(int prec = 5, bool withSpaces = true) const;
const Core::GeoPosition& geoPosition() const
QString toString(bool fullAndExpensive = false) const; {
return m_geo;
}
static void resetConversionCounter(); const Core::GeoPosition2D& geoPosition2D() const
static long getConversionCounter(); {
return m_geo;
}
const LtsCoordTrans::UtmCoordinate& utmCoordinate() const
{
const Core::GeoPosition &geoPosition() const if (!hasUtm())
{ convertGeoToUtm();
return m_geo; return m_utm2D;
} }
const Core::GeoPosition2D &geoPosition2D() const
{ double& rz()
return m_geo; {
} return m_geo.z();
}
const LtsCoordTrans::UtmCoordinate &utmCoordinate() const
{ double z() const
if (!hasUtm()) {
convertGeoToUtm(); return m_geo.z();
return m_utm2D; }
}
void setZ(double value)
{
double &rz() { return m_geo.z(); } m_geo.z(value);
double z() const { return m_geo.z(); } }
void setZ(double value) { m_geo.z(value); }
LtsCoordTrans::UtmCoordinate utmCoordinateDiffZone(int zone) const
{
LtsCoordTrans::UtmCoordinate utmCoordinateDiffZone(int zone) const
{ m_utm2D_differentZone = LtsCoordTrans::UtmCoordinate::fromGeographic(m_geo.lon(), m_geo.lat(), zone);
return m_utm2D_differentZone;
}
m_utm2D_differentZone = LtsCoordTrans::UtmCoordinate::fromGeographic(m_geo.lon(), m_geo.lat(), zone);
return m_utm2D_differentZone; template <typename T> T toUtm(int zone = -1) const
} {
T obj;
helperToUtm(obj, zone);
return obj;
}
template<typename T> QPointF toUtmPointF() const
T toUtm(int zone = -1) const {
{ return toUtm<QPointF>();
T obj; }
helperToUtm(obj, zone);
return obj; QPoint3D toUtmPoint3D() const
{
return toUtm<QPoint3D>();
}
}
QPointF toGeoPointF() const
QPointF toUtmPointF() const { return toUtm<QPointF>(); } {
QPoint3D toUtmPoint3D() const { return toUtm<QPoint3D>(); } return QPointF(m_geo.lon(), m_geo.lat());
}
QPointF toGeoPointF() const { return QPointF (m_geo.lon(), m_geo.lat()); }
QPoint3D toGeoPoint3D() const { return QPoint3D(m_geo.lon(), m_geo.lat(), m_geo.z() ); } QPoint3D toGeoPoint3D() const
{
return QPoint3D(m_geo.lon(), m_geo.lat(), m_geo.z());
UtmCoordinate3D toUtmCoordinate3D() const }
{
return UtmCoordinate3D(utmCoordinate(), m_geo.z()); UtmCoordinate3D toUtmCoordinate3D() const
} {
return UtmCoordinate3D(utmCoordinate(), m_geo.z());
}
using elevationCbFunc = std::function<double(double, double, double, bool*)>;
using elevationCbFunc = std::function<double(double, double, double, bool*)>; static void setElevationCallback(const elevationCbFunc& elevationCB);
static bool hasElevationCallback();
double elevationAt(double defaultElevation = 0.0, bool* bIsCovered = nullptr) const;
void setZValueAccordingElevation(double defaultElevation = 0.0);
static void setElevationCallback(const elevationCbFunc &elevationCB);
static bool hasElevationCallback(); static double elevationAt(const LtsCoordinate& coordinate, double defaultElevation = 0.0,
bool* bIsCovered = nullptr);
void replaceZValueByElevationIfValue(double zValueToBeReplaced = std::nan(""), double defaultElevation = 0.0);
double elevationAt(double defaultElevation = 0.0, bool *bIsCovered = nullptr) const; double heightOverElevation() const
void setZValueAccordingElevation(double defaultElevation = 0.0); {
return m_geo.z() - elevationAt();
static double elevationAt(const LtsCoordinate &coordinate, double defaultElevation = 0.0, bool *bIsCovered = nullptr); }
double distanceUtm2D(const LtsCoordinate& other) const
{
const LtsCoordTrans::UtmCoordinate& thisUtm2D = utmCoordinate();
const LtsCoordTrans::UtmCoordinate& otherUtm2D = other.utmCoordinateDiffZone(m_utm2D.zone);
return LtsCoordTrans::distance(thisUtm2D, otherUtm2D);
}
double distanceUtm3D(const LtsCoordinate& other) const
{
const QPoint3D& thisUtm3D = toUtm<QPoint3D>();
void replaceZValueByElevationIfValue(double zValueToBeReplaced = std::nan(""), double defaultElevation = 0.0); const QPoint3D& otherUtm3D = other.toUtm<QPoint3D>(m_utm2D.zone);
const double dist3D = (thisUtm3D - otherUtm3D).length();
Q_ASSERT_X(!std::isnan(dist3D), "LtsCoordinate", "ERROR, distance3D is NaN");
return dist3D;
}
static double angleDegreeUtm2D(const LtsCoordinate& coord1, const LtsCoordinate& coord2);
double heightOverElevation() const { return m_geo.z() - elevationAt(); }
protected:
void clearGeo() const
double distanceUtm2D(const LtsCoordinate &other) const {
{ clearGeoLonLat();
m_geo.z(std::nan(""));
}
const LtsCoordTrans::UtmCoordinate &thisUtm2D = utmCoordinate();
const LtsCoordTrans::UtmCoordinate &otherUtm2D = other.utmCoordinateDiffZone(m_utm2D.zone); void clearGeoLonLat() const
return LtsCoordTrans::distance(thisUtm2D, otherUtm2D); {
} m_geo.lon(0);
m_geo.lat(0);
double distanceUtm3D(const LtsCoordinate &other) const }
{
void clearUtm() const
{
const QPoint3D &thisUtm3D = toUtm<QPoint3D>(); m_utm2D = m_utm2D_differentZone = UtmCoordinate2D();
const QPoint3D &otherUtm3D = other.toUtm<QPoint3D>(m_utm2D.zone); }
const double dist3D = (thisUtm3D - otherUtm3D).length();
void clearElevation() const
Q_ASSERT_X(!std::isnan(dist3D), "LtsCoordinate", "ERROR, distance3D is NaN"); {
m_elevation = std::nan("");
return dist3D; }
}
void clear() const
{
clearGeo();
clearUtm();
clearElevation();
}
const LtsCoordTrans::UtmCoordinate& utmCoordinateInternal(int zone = -1) const;
void convertGeoToUtm() const;
static double angleDegreeUtm2D(const LtsCoordinate &coord1, const LtsCoordinate &coord2);
protected:
void helperToUtm(QPointF& pntRef, int zone = -1) const
{
const auto& utmTemp = utmCoordinateInternal(zone);
pntRef.rx() = utmTemp.x;
protected: pntRef.ry() = utmTemp.y;
}
void clearGeo() const { clearGeoLonLat(); m_geo.z(std::nan("")); }
void clearGeoLonLat() const { m_geo.lon(0); m_geo.lat(0); } void helperToUtm(QPoint3D& pntRef, int zone = -1) const
void clearUtm() const { m_utm2D = m_utm2D_differentZone = UtmCoordinate2D(); } {
void clearElevation() const { m_elevation = std::nan(""); } const auto& utmTemp = utmCoordinateInternal(zone);
void clear() const { clearGeo(); clearUtm(); clearElevation(); } pntRef.rx() = utmTemp.x;
pntRef.ry() = utmTemp.y;
const LtsCoordTrans::UtmCoordinate &utmCoordinateInternal(int zone = -1) const; pntRef.rz() = m_geo.z();
void convertGeoToUtm() const; }
protected: protected:
mutable Core::GeoPosition m_geo;
void helperToUtm(QPointF &pntRef, int zone = -1) const mutable UtmCoordinate2D m_utm2D;
{ mutable UtmCoordinate2D m_utm2D_differentZone;
const auto &utmTemp = utmCoordinateInternal(zone); mutable double m_elevation{std::nan("")};
pntRef.rx() = utmTemp.x;
pntRef.ry() = utmTemp.y; static elevationCbFunc m_getElevationCB;
}
void helperToUtm(QPoint3D &pntRef, int zone = -1) const
{
const auto &utmTemp = utmCoordinateInternal(zone);
pntRef.rx() = utmTemp.x;
pntRef.ry() = utmTemp.y;
pntRef.rz() = m_geo.z();
}
protected:
mutable Core::GeoPosition m_geo;
mutable UtmCoordinate2D m_utm2D;
mutable UtmCoordinate2D m_utm2D_differentZone;
mutable double m_elevation{std::nan("")};
static elevationCbFunc m_getElevationCB;
}; };
class LTSCOORDINATE_EXPORT LtsCoordinateNoImplicitCopy : public LtsCoordinate class LTSCOORDINATE_EXPORT LtsCoordinateNoImplicitCopy : public LtsCoordinate
{ {
public: public:
using BaseClass = LtsCoordinate; using BaseClass = LtsCoordinate;
LtsCoordinateNoImplicitCopy() = default;
explicit LtsCoordinateNoImplicitCopy(const LtsCoordinateNoImplicitCopy&) = default;
~LtsCoordinateNoImplicitCopy() = default;
LtsCoordinateNoImplicitCopy() = default; explicit LtsCoordinateNoImplicitCopy(const QPointF& lonLat, double z = std::nan(""))
explicit LtsCoordinateNoImplicitCopy (const LtsCoordinateNoImplicitCopy &) = default; : BaseClass(Core::GeoPosition(lonLat.x(), lonLat.y(), z))
{
}
explicit LtsCoordinateNoImplicitCopy(const Core::GeoPosition& geoPos) : BaseClass(geoPos) {}
explicit LtsCoordinateNoImplicitCopy(const Core::GeoPosition2D& geoPos2D) : BaseClass(geoPos2D) {}
void updateGeoPosition(const Core::GeoPosition& geoPos) const
{
clear();
m_geo = geoPos;
}
~LtsCoordinateNoImplicitCopy() = default;
explicit LtsCoordinateNoImplicitCopy(const QPointF &lonLat, double z = std::nan(""))
: BaseClass(Core::GeoPosition(lonLat.x(), lonLat.y(), z))
{}
explicit LtsCoordinateNoImplicitCopy(const Core::GeoPosition &geoPos)
: BaseClass(geoPos)
{}
explicit LtsCoordinateNoImplicitCopy(const Core::GeoPosition2D &geoPos2D)
: BaseClass(geoPos2D)
{}
void updateGeoPosition(const Core::GeoPosition &geoPos) const
{
clear();
m_geo = geoPos;
}
}; };
template <typename T_OUT, typename T_IN> T_OUT convert(const T_IN& contIn)
template<typename T_OUT, typename T_IN>
T_OUT convert(const T_IN& contIn)
{ {
T_OUT out; T_OUT out;
out.reserve(contIn.size()); out.reserve(contIn.size());
for (const Core::GeoPosition &posGeo : std::as_const(contIn)) for (const Core::GeoPosition& posGeo : std::as_const(contIn))
out.push_back(LtsCoordinate(posGeo)); out.push_back(LtsCoordinate(posGeo));
return out; return out;
} }
LTSCOORDINATE_EXPORT std::ostream& operator<<(std::ostream& stream, const LtsCoordinate& value);
} // namespace LtsCoordTrans
LTSCOORDINATE_EXPORT std::ostream &operator<< (std::ostream &stream,
const LtsCoordinate &value);
}
@@ -1,230 +1,198 @@
#include "elevation_unit_test.h" #include "elevation_unit_test.h"
#include <ElevationMap/elevation_map_manager.h> #include <ElevationMap/elevation_map_manager.h>
#include <LtsCoordTrans/lts_coord_trans.h> #include <LtsCoordTrans/lts_coord_trans.h>
#include <nglapplication/nglcoreapplication.h>
#include <NGLLogger/NGLLoggerBootstrap.h> #include <NGLLogger/NGLLoggerBootstrap.h>
#include <QtTest/QTest> #include <QtTest/QTest>
#include <nglapplication/nglcoreapplication.h>
Q_DECLARE_METATYPE(LtsUtils::QPoint3D); Q_DECLARE_METATYPE(LtsUtils::QPoint3D);
Q_DECLARE_METATYPE(LtsElevation::LineOfSight); Q_DECLARE_METATYPE(LtsElevation::LineOfSight);
#include <iostream> #include <iostream>
static const int s_id{4711}; static const int s_id{4711};
static LtsElevation::LtsElevationManager *s_eleMgr{nullptr}; static LtsElevation::LtsElevationManager* s_eleMgr{nullptr};
class MyLtsElevationManagerBootstrap : public LtsElevation::LtsElevationManager class MyLtsElevationManagerBootstrap : public LtsElevation::LtsElevationManager
{ {
using BaseClass = LtsElevation::LtsElevationManager; using BaseClass = LtsElevation::LtsElevationManager;
public:
static LtsElevationManager *createInstanceUnitTest(int id, const QStringList &filePaths_rough_to_fine)
{
return BaseClass::createInstanceUnitTest(id, filePaths_rough_to_fine);
}
public:
static LtsElevationManager* createInstanceUnitTest(int id, const QStringList& filePaths_rough_to_fine)
{
return BaseClass::createInstanceUnitTest(id, filePaths_rough_to_fine);
}
}; };
UnitTestElevation::UnitTestElevation() UnitTestElevation::UnitTestElevation()
: m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("UnitTestElevation")) : m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("UnitTestElevation"))
{} {
}
void UnitTestElevation::initTestCase() void UnitTestElevation::initTestCase()
{ {
QString filePath(QStringLiteral("/usr/share/arcgis/resources/elevation/Altmark_dt1.tif"));
QString filePath(QStringLiteral("/usr/share/arcgis/resources/elevation/Altmark_dt1.tif")); s_eleMgr = MyLtsElevationManagerBootstrap::createInstanceUnitTest(s_id, {filePath});
s_eleMgr = MyLtsElevationManagerBootstrap::createInstanceUnitTest(s_id, {filePath});
const bool bIsValid = s_eleMgr->isValid();
std::cerr << "myBootstrapMgr->isValid() 1 = " << bIsValid << std::endl;
{
s_eleMgr->waitForInitialization();
const bool bIsValid = s_eleMgr->isValid(); const bool bIsValid = s_eleMgr->isValid();
std::cerr << "myBootstrapMgr->isValid() 2 = " << bIsValid << std::endl; std::cerr << "myBootstrapMgr->isValid() 1 = " << bIsValid << std::endl;
}
{
s_eleMgr->waitForInitialization();
const bool bIsValid = s_eleMgr->isValid();
std::cerr << "myBootstrapMgr->isValid() 2 = " << bIsValid << std::endl;
}
} }
void UnitTestElevation::init() void UnitTestElevation::init()
{ {
QVERIFY2(s_eleMgr , "static LtsElevationManager does not exist"); QVERIFY2(s_eleMgr, "static LtsElevationManager does not exist");
} }
void UnitTestElevation::test_elevation_data() void UnitTestElevation::test_elevation_data()
{ {
QTest::addColumn<QPointF>("lonLat"); QTest::addColumn<QPointF>("lonLat");
QTest::addColumn<double>("elevationRef"); QTest::addColumn<double>("elevationRef");
QTest::newRow("elevation 1 ")
<< LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 70000 10000")).geographic() << 75.0;
QTest::newRow("elevation 2 ")
<< LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 72000 13000")).geographic() << 80.0;
QTest::newRow("elevation 1 ") << LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 70000 10000")).geographic() << 75.0; QTest::newRow("elevation 3 ")
QTest::newRow("elevation 2 ") << LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 72000 13000")).geographic() << 80.0; << LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 76925 18625")).geographic() << 92.0;
QTest::newRow("elevation 3 ") << LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 76925 18625")).geographic() << 92.0;
} }
void UnitTestElevation::test_elevation() void UnitTestElevation::test_elevation()
{ {
QFETCH(QPointF, lonLat); QFETCH(QPointF, lonLat);
QFETCH(double, elevationRef); QFETCH(double, elevationRef);
double elevation = s_eleMgr->elevation(lonLat.x(), lonLat.y()); double elevation = s_eleMgr->elevation(lonLat.x(), lonLat.y());
QVERIFY2(qFuzzyCompare(elevationRef, elevation), " got wrong elevation result"); QVERIFY2(qFuzzyCompare(elevationRef, elevation), " got wrong elevation result");
} }
void UnitTestElevation::test_elevation_isCovered() void UnitTestElevation::test_elevation_isCovered()
{ {
const QPointF &lonLat1 = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 70000 10000")).geographic(); const QPointF& lonLat1 = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 70000 10000")).geographic();
const QPointF &lonLat2 = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U MD 60000 10000")).geographic(); const QPointF& lonLat2 = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U MD 60000 10000")).geographic();
const double defaultElevationValue = -123; const double defaultElevationValue = -123;
{ {
bool bIsCovered = false; bool bIsCovered = false;
s_eleMgr->elevation(lonLat1.x(), lonLat1.y(), defaultElevationValue, &bIsCovered); s_eleMgr->elevation(lonLat1.x(), lonLat1.y(), defaultElevationValue, &bIsCovered);
QVERIFY2(bIsCovered, " error on bIsCovered"); QVERIFY2(bIsCovered, " error on bIsCovered");
} }
{ {
bool bIsCovered = true; bool bIsCovered = true;
s_eleMgr->elevation(lonLat2.x(), lonLat2.y(), defaultElevationValue, &bIsCovered); s_eleMgr->elevation(lonLat2.x(), lonLat2.y(), defaultElevationValue, &bIsCovered);
QVERIFY2(!bIsCovered, " error on bIsCovered"); QVERIFY2(!bIsCovered, " error on bIsCovered");
} }
} }
void UnitTestElevation::test_elevation_defaultValue() void UnitTestElevation::test_elevation_defaultValue()
{ {
const QPointF &lonLat = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 60000 10000")).geographic(); const QPointF& lonLat = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 60000 10000")).geographic();
double elevation = s_eleMgr->elevation(lonLat.x(), lonLat.y()); double elevation = s_eleMgr->elevation(lonLat.x(), lonLat.y());
QVERIFY2(qFuzzyCompare(elevation, std::numeric_limits<double>::min()), " error on defaultValue"); QVERIFY2(qFuzzyCompare(elevation, std::numeric_limits<double>::min()), " error on defaultValue");
{ {
const double defaultValue = 100; const double defaultValue = 100;
elevation = s_eleMgr->elevation(lonLat.x(), lonLat.y(), defaultValue); elevation = s_eleMgr->elevation(lonLat.x(), lonLat.y(), defaultValue);
QVERIFY2(qFuzzyCompare(elevation, defaultValue), " error on defaultValue"); QVERIFY2(qFuzzyCompare(elevation, defaultValue), " error on defaultValue");
} }
{ {
const double defaultValue = std::numeric_limits<double>::max(); const double defaultValue = std::numeric_limits<double>::max();
elevation = s_eleMgr->elevation(lonLat.x(), lonLat.y(), defaultValue); elevation = s_eleMgr->elevation(lonLat.x(), lonLat.y(), defaultValue);
QVERIFY2(qFuzzyCompare(elevation, defaultValue), " error on defaultValue"); QVERIFY2(qFuzzyCompare(elevation, defaultValue), " error on defaultValue");
} }
} }
void UnitTestElevation::test_lineOfSightCalculation_data() void UnitTestElevation::test_lineOfSightCalculation_data()
{ {
QTest::addColumn<QPointF>("startGeo2D"); QTest::addColumn<QPointF>("startGeo2D");
QTest::addColumn<double>("startObjH"); QTest::addColumn<double>("startObjH");
QTest::addColumn<QPointF>("endGeo2D"); QTest::addColumn<QPointF>("endGeo2D");
QTest::addColumn<double>("endObjH"); QTest::addColumn<double>("endObjH");
QTest::addColumn<LtsElevation::LineOfSight>("expectedResult"); QTest::addColumn<LtsElevation::LineOfSight>("expectedResult");
QTest::newRow("losDataset 1 ")
<< LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 60000 10000")).geographic() << 1.0
<< LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 60000 60000")).geographic() << 1.0
<< LtsElevation::LineOfSight::LOS_ERROR;
QTest::newRow("losDataset 2 ")
<< LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 77200 17600")).geographic() << 1.0
<< LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 77600 17600")).geographic() << 1.0
<< LtsElevation::LineOfSight::LOS_INVISIBLE;
QTest::newRow("losDataset 3 ")
<< LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 77200 17600")).geographic() << 20.0
<< LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 77600 17600")).geographic() << 20.0
<< LtsElevation::LineOfSight::LOS_VISIBLE;
QTest::newRow("losDataset 1 ") << LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 60000 10000")).geographic() << 1.0 QTest::newRow("losDataset 4 ")
<< LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 60000 60000")).geographic() << 1.0 << LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 77200 17600")).geographic() << -1.0
<< LtsElevation::LineOfSight::LOS_ERROR; << LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 77600 17600")).geographic() << 1.0
<< LtsElevation::LineOfSight::LOS_ERROR;
QTest::newRow("losDataset 5 ")
QTest::newRow("losDataset 2 ") << LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 77200 17600")).geographic() << 1.0 << LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 77200 17600")).geographic() << 1.0
<< LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 77600 17600")).geographic() << 1.0 << LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 77600 17600")).geographic() << -1.0
<< LtsElevation::LineOfSight::LOS_INVISIBLE; << LtsElevation::LineOfSight::LOS_ERROR;
QTest::newRow("losDataset 6 ")
<< LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 77200 17600")).geographic() << 0.0
QTest::newRow("losDataset 3 ") << LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 77200 17600")).geographic() << 20.0 << LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 77600 17600")).geographic() << 0.0
<< LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 77600 17600")).geographic() << 20.0 << LtsElevation::LineOfSight::LOS_INVISIBLE;
<< LtsElevation::LineOfSight::LOS_VISIBLE;
QTest::newRow("losDataset 4 ") << LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 77200 17600")).geographic() << -1.0
<< LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 77600 17600")).geographic() << 1.0
<< LtsElevation::LineOfSight::LOS_ERROR;
QTest::newRow("losDataset 5 ") << LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 77200 17600")).geographic() << 1.0
<< LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 77600 17600")).geographic() << -1.0
<< LtsElevation::LineOfSight::LOS_ERROR;
QTest::newRow("losDataset 6 ") << LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 77200 17600")).geographic() << 0.0
<< LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 77600 17600")).geographic() << 0.0
<< LtsElevation::LineOfSight::LOS_INVISIBLE;
} }
void UnitTestElevation::test_lineOfSightCalculation() void UnitTestElevation::test_lineOfSightCalculation()
{ {
QFETCH(QPointF, startGeo2D); QFETCH(QPointF, startGeo2D);
QFETCH(double, startObjH); QFETCH(double, startObjH);
QFETCH(QPointF, endGeo2D); QFETCH(QPointF, endGeo2D);
QFETCH(double, endObjH); QFETCH(double, endObjH);
QFETCH(LtsElevation::LineOfSight, expectedResult); QFETCH(LtsElevation::LineOfSight, expectedResult);
LtsUtils::QPoint3D start3D = LtsUtils::QPoint3D::fromQPointF(startGeo2D); LtsUtils::QPoint3D start3D = LtsUtils::QPoint3D::fromQPointF(startGeo2D);
start3D.rz() = startObjH; start3D.rz() = startObjH;
start3D.rz() += s_eleMgr->elevation(start3D.x(), start3D.y()); start3D.rz() += s_eleMgr->elevation(start3D.x(), start3D.y());
LtsUtils::QPoint3D end3D = LtsUtils::QPoint3D::fromQPointF(endGeo2D); LtsUtils::QPoint3D end3D = LtsUtils::QPoint3D::fromQPointF(endGeo2D);
end3D.rz() = endObjH; end3D.rz() = endObjH;
end3D.rz() += s_eleMgr->elevation(end3D.x(), end3D.y()); end3D.rz() += s_eleMgr->elevation(end3D.x(), end3D.y());
LtsElevation::LineOfSight los = s_eleMgr->lineOfSightCalculation(start3D, end3D); LtsElevation::LineOfSight los = s_eleMgr->lineOfSightCalculation(start3D, end3D);
NOTICE_LOG(m_logger) << "los = " << los; NOTICE_LOG(m_logger) << "los = " << los;
{ {
LtsElevation::LineOfSight los2 = s_eleMgr->lineOfSightCalculation(startGeo2D, startObjH, LtsElevation::LineOfSight los2 = s_eleMgr->lineOfSightCalculation(startGeo2D, startObjH, endGeo2D, endObjH);
endGeo2D, endObjH); QVERIFY2(los == los2, " got different lineOfSightCalculation result");
QVERIFY2(los == los2, " got different lineOfSightCalculation result"); }
}
QVERIFY2(los == expectedResult, " got lineOfSightCalculation result");
QVERIFY2(los == expectedResult, " got lineOfSightCalculation result");
} }
int main(int argc, char* argv[])
int main(int argc, char *argv[])
{ {
NGLCoreApplication app(argc, argv); NGLCoreApplication app(argc, argv);
app.createLogger("UnitTestElevation", "log4cxxElevationUnitTest.props"); app.createLogger("UnitTestElevation", "log4cxxElevationUnitTest.props");
UnitTestElevation tc; UnitTestElevation tc;
int ret = QTest::qExec(&tc, argc, argv); int ret = QTest::qExec(&tc, argc, argv);
if (s_eleMgr)
{
s_eleMgr->cleanupAll();
}
if (s_eleMgr) return ret;
{
s_eleMgr->cleanupAll();
}
return ret;
} }
@@ -1,61 +1,38 @@
#pragma once #pragma once
#include <QObject>
#include <LtsElevation/lts_elevation_manager.h>
#include <ElevationMap/elevation_map_manager.h> #include <ElevationMap/elevation_map_manager.h>
#include <LtsElevation/lts_elevation_manager.h>
#include <QCoreApplication>
#include <QtTest/QTest>
#include <NGLLogger/INGLLogger.h> #include <NGLLogger/INGLLogger.h>
#include <QCoreApplication>
#include <QObject>
#include <QtTest/QTest>
using LOGGER_T = NGL::INGLLogger&; using LOGGER_T = NGL::INGLLogger&;
class UnitTestElevation : public QObject class UnitTestElevation : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
UnitTestElevation(); UnitTestElevation();
private Q_SLOTS:
private Q_SLOTS: void initTestCase();
void init();
void test_elevation_data();
void test_elevation();
void test_elevation_isCovered();
void test_elevation_defaultValue();
void test_lineOfSightCalculation_data();
void test_lineOfSightCalculation();
private:
void initTestCase(); NGL::INGLLogger& m_logger;
void init();
void test_elevation_data();
void test_elevation();
void test_elevation_isCovered();
void test_elevation_defaultValue();
void test_lineOfSightCalculation_data();
void test_lineOfSightCalculation();
private:
NGL::INGLLogger &m_logger;
}; };
+17 -19
View File
@@ -1,6 +1,5 @@
#include "logger.h" #include "logger.h"
#include <NGLLogger/NGLLoggerBootstrap.h> #include <NGLLogger/NGLLoggerBootstrap.h>
@@ -8,25 +7,24 @@
namespace LtsElevation namespace LtsElevation
{ {
LOGGER_T getLogger(const char *name) LOGGER_T getLogger(const char* name)
{ {
static const char ns[] = "Lts.Elevation."; static const char ns[] = "Lts.Elevation.";
std::string loggerName; std::string loggerName;
const size_t len = strlen(name); const size_t len = strlen(name);
loggerName.reserve(sizeof(ns) + len); loggerName.reserve(sizeof(ns) + len);
loggerName.append(ns, sizeof(ns) - 1); loggerName.append(ns, sizeof(ns) - 1);
loggerName.append(name, len); loggerName.append(name, len);
try try
{ {
return NGL::NGLLoggerBootstrap::getNGLRootLogger(). return NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger(loggerName);
getNGLLogger(loggerName); }
} catch (const std::exception& ex)
catch (const std::exception &ex) {
{ fprintf(stderr, "Error retrieving logger: %s", ex.what());
fprintf(stderr, "Error retrieving logger: %s", ex.what()); abort();
abort(); }
}
} }
} } // namespace LtsElevation
+6 -7
View File
@@ -1,18 +1,17 @@
#pragma once #pragma once
#include <NGLLogger/INGLLogger.h> #include <NGLLogger/INGLLogger.h>
namespace LtsElevation namespace LtsElevation
{ {
typedef NGL::INGLLogger &LOGGER_T; typedef NGL::INGLLogger& LOGGER_T;
LOGGER_T getLogger(const char *name); LOGGER_T getLogger(const char* name);
inline LOGGER_T getLogger(const QString &loggerName)
inline LOGGER_T getLogger(const QString& loggerName)
{ {
return getLogger(loggerName.toUtf8().constData()); return getLogger(loggerName.toUtf8().constData());
}
} }
} // namespace LtsElevation
+318 -356
View File
@@ -1,510 +1,472 @@
#include "lts_elevation_manager.h" #include "lts_elevation_manager.h"
#include <utility>
#include <Plugins/ExerciseManagement/exm_data_plugin_interface.h>
#include <Plugins/AssetManagement/asm_data_plugin_interface.h> #include <Plugins/AssetManagement/asm_data_plugin_interface.h>
#include <Plugins/ExerciseManagement/exm_data_plugin_interface.h>
#include <Viewer/SituationMap/ElevationMap/elevation_map_manager.h>
#include <Viewer/SituationMap/Common/resource_path.h>
#include <QSharedPointer>
#include <QDir> #include <QDir>
#include <QUrl>
#include <QHash> #include <QHash>
#include <QSharedPointer>
#include <QUrl>
#include <Viewer/SituationMap/Common/resource_path.h>
#include <Viewer/SituationMap/ElevationMap/elevation_map_manager.h>
#include <utility>
static_assert((int)SituationMap::ElevationMapManager::LineOfSight::LOS_UNDEFINED ==
(int)LtsElevation::LineOfSight::LOS_UNDEFINED,
"LineOfSight mismatch");
static_assert((int)SituationMap::ElevationMapManager::LineOfSight::LOS_UNDEFINED == (int)LtsElevation::LineOfSight::LOS_UNDEFINED, "LineOfSight mismatch"); static_assert((int)SituationMap::ElevationMapManager::LineOfSight::LOS_ERROR ==
static_assert((int)SituationMap::ElevationMapManager::LineOfSight::LOS_ERROR == (int)LtsElevation::LineOfSight::LOS_ERROR, "LineOfSight mismatch"); (int)LtsElevation::LineOfSight::LOS_ERROR,
static_assert((int)SituationMap::ElevationMapManager::LineOfSight::LOS_VISIBLE == (int)LtsElevation::LineOfSight::LOS_VISIBLE, "LineOfSight mismatch"); "LineOfSight mismatch");
static_assert((int)SituationMap::ElevationMapManager::LineOfSight::LOS_INVISIBLE == (int)LtsElevation::LineOfSight::LOS_INVISIBLE, "LineOfSight mismatch"); static_assert((int)SituationMap::ElevationMapManager::LineOfSight::LOS_VISIBLE ==
(int)LtsElevation::LineOfSight::LOS_VISIBLE,
"LineOfSight mismatch");
static_assert((int)SituationMap::ElevationMapManager::LineOfSight::LOS_INVISIBLE ==
(int)LtsElevation::LineOfSight::LOS_INVISIBLE,
"LineOfSight mismatch");
namespace LtsElevation namespace LtsElevation
{ {
class LtsElevationManager; class LtsElevationManager;
using LtsElevatioMgrMapTrainingAreaId = QMap<int, LTS_ELEVATION_MANAGER_TYPE>; using LtsElevatioMgrMapTrainingAreaId = QMap<int, LTS_ELEVATION_MANAGER_TYPE>;
static LtsElevatioMgrMapTrainingAreaId& ltsElevatioMgrMapTrainingAreaId()
static LtsElevatioMgrMapTrainingAreaId &ltsElevatioMgrMapTrainingAreaId()
{ {
static LtsElevatioMgrMapTrainingAreaId s_ltsElevatioMgrMapTrainingAreaId; static LtsElevatioMgrMapTrainingAreaId s_ltsElevatioMgrMapTrainingAreaId;
return s_ltsElevatioMgrMapTrainingAreaId; return s_ltsElevatioMgrMapTrainingAreaId;
} }
static void cleanupLtsElevatioMgrMapTrainingAreaId() static void cleanupLtsElevatioMgrMapTrainingAreaId()
{ {
qDeleteAll(ltsElevatioMgrMapTrainingAreaId()); qDeleteAll(ltsElevatioMgrMapTrainingAreaId());
ltsElevatioMgrMapTrainingAreaId().clear(); ltsElevatioMgrMapTrainingAreaId().clear();
} }
LtsElevatioMgrMapTrainingAreaId &getLtsElevationMgrMapTrainingAreaId() LtsElevatioMgrMapTrainingAreaId& getLtsElevationMgrMapTrainingAreaId()
{ {
if (ltsElevatioMgrMapTrainingAreaId().isEmpty()) if (ltsElevatioMgrMapTrainingAreaId().isEmpty())
qAddPostRoutine(cleanupLtsElevatioMgrMapTrainingAreaId); qAddPostRoutine(cleanupLtsElevatioMgrMapTrainingAreaId);
return ltsElevatioMgrMapTrainingAreaId(); return ltsElevatioMgrMapTrainingAreaId();
} }
static long s_counter{0}; static long s_counter{0};
class LtsElevationManager::Private class LtsElevationManager::Private
{ {
public: public:
Private() = default; Private() = default;
~Private()
{
delete m_elevationManager;
}
std::shared_ptr<ExerciseManagement::Interface::Dtc> m_exmDtc;
std::shared_ptr<AssetManagement::Interface::Dtc> m_asmDtc;
QStringList m_filePaths_rough_to_fine; ~Private()
SituationMap::ElevationMapManager *m_elevationManager{nullptr}; {
delete m_elevationManager;
}
std::shared_ptr<ExerciseManagement::Interface::Dtc> m_exmDtc;
std::shared_ptr<AssetManagement::Interface::Dtc> m_asmDtc;
QStringList m_filePaths_rough_to_fine;
SituationMap::ElevationMapManager* m_elevationManager{nullptr};
}; };
LtsElevationManager::LtsElevationManager() : QObject(nullptr), d(new Private)
LtsElevationManager::LtsElevationManager()
: QObject(nullptr)
, d(new Private)
{ {
++s_counter; ++s_counter;
TRACE_LOG(m_logger) << Q_FUNC_INFO << " START, s_counter=" << s_counter << " this=" << this; TRACE_LOG(m_logger) << Q_FUNC_INFO << " START, s_counter=" << s_counter << " this=" << this;
TRACE_LOG(m_logger) << Q_FUNC_INFO << " END, s_counter=" << s_counter << " this=" << this; TRACE_LOG(m_logger) << Q_FUNC_INFO << " END, s_counter=" << s_counter << " this=" << this;
} }
LtsElevationManager::~LtsElevationManager() LtsElevationManager::~LtsElevationManager()
{ {
--s_counter; --s_counter;
TRACE_LOG(m_logger) << Q_FUNC_INFO << " START, s_counter=" << s_counter << " this=" << this; TRACE_LOG(m_logger) << Q_FUNC_INFO << " START, s_counter=" << s_counter << " this=" << this;
delete d; delete d;
TRACE_LOG(m_logger) << Q_FUNC_INFO << " END, s_counter=" << s_counter << " this=" << this; TRACE_LOG(m_logger) << Q_FUNC_INFO << " END, s_counter=" << s_counter << " this=" << this;
} }
LTS_ELEVATION_MANAGER_TYPE LtsElevationManager::createInstance(int exerciseId, LTS_ELEVATION_MANAGER_TYPE
const std::shared_ptr<ExerciseManagement::Interface::Dtc> &exmDtc, LtsElevationManager::createInstance(int exerciseId, const std::shared_ptr<ExerciseManagement::Interface::Dtc>& exmDtc,
const std::shared_ptr<AssetManagement::Interface::Dtc> &asmDtc) const std::shared_ptr<AssetManagement::Interface::Dtc>& asmDtc)
{ {
LOGGER_T logger = getLogger("LtsElevationManager"); LOGGER_T logger = getLogger("LtsElevationManager");
TRACE_LOG(logger) << Q_FUNC_INFO << " START, exerciseId=" << exerciseId; TRACE_LOG(logger) << Q_FUNC_INFO << " START, exerciseId=" << exerciseId;
if (exerciseId < 0) if (exerciseId < 0)
{
ERROR_LOG(logger) << Q_FUNC_INFO << " exerciseId invalid, exerciseId=" << exerciseId;
return nullptr;
}
int trainingAreaId = -1;
static QHash<int,int> s_exIdToTaIdStore;
const auto exTaIt = s_exIdToTaIdStore.find(exerciseId);
if (exTaIt != s_exIdToTaIdStore.end())
{
trainingAreaId = *exTaIt;
} else {
if (!exmDtc || !asmDtc)
{ {
ERROR_LOG(logger) << Q_FUNC_INFO << " no dtcs for exerciseId=" << exerciseId ERROR_LOG(logger) << Q_FUNC_INFO << " exerciseId invalid, exerciseId=" << exerciseId;
<< ", asmDtc=" << asmDtc return nullptr;
<< ", exmDtc=" << exmDtc;
return nullptr;
} }
int trainingAreaId = -1;
trainingAreaId = exerciseIdToTrainingAreaId(exerciseId, exmDtc); static QHash<int, int> s_exIdToTaIdStore;
if (trainingAreaId <= 0)
const auto exTaIt = s_exIdToTaIdStore.find(exerciseId);
if (exTaIt != s_exIdToTaIdStore.end())
{ {
ERROR_LOG(logger) << Q_FUNC_INFO << " Error getting trainingAreaId"
<< ", exerciseId=" << exerciseId trainingAreaId = *exTaIt;
<< ", trainingAreaId=" << trainingAreaId; }
return nullptr; else
{
if (!exmDtc || !asmDtc)
{
ERROR_LOG(logger) << Q_FUNC_INFO << " no dtcs for exerciseId=" << exerciseId << ", asmDtc=" << asmDtc
<< ", exmDtc=" << exmDtc;
return nullptr;
}
trainingAreaId = exerciseIdToTrainingAreaId(exerciseId, exmDtc);
if (trainingAreaId <= 0)
{
ERROR_LOG(logger) << Q_FUNC_INFO << " Error getting trainingAreaId"
<< ", exerciseId=" << exerciseId << ", trainingAreaId=" << trainingAreaId;
return nullptr;
}
s_exIdToTaIdStore[exerciseId] = trainingAreaId;
} }
LTS_ELEVATION_MANAGER_TYPE temp = createInstanceForTrainingAreaId(trainingAreaId, asmDtc);
if (!temp)
{
ERROR_LOG(logger) << Q_FUNC_INFO << " Error on createInstanceForTrainingAreaId"
<< ", exerciseId=" << exerciseId << ", trainingAreaId=" << trainingAreaId;
return nullptr;
}
s_exIdToTaIdStore[exerciseId] = trainingAreaId; temp->initDDS(exmDtc, asmDtc);
} TRACE_LOG(logger) << Q_FUNC_INFO << " END, exerciseId=" << exerciseId;
return temp;
LTS_ELEVATION_MANAGER_TYPE temp = createInstanceForTrainingAreaId(trainingAreaId, asmDtc);
if (!temp)
{
ERROR_LOG(logger) << Q_FUNC_INFO << " Error on createInstanceForTrainingAreaId"
<< ", exerciseId=" << exerciseId
<< ", trainingAreaId=" << trainingAreaId;
return nullptr;
}
temp->initDDS(exmDtc, asmDtc);
TRACE_LOG(logger) << Q_FUNC_INFO << " END, exerciseId=" << exerciseId;
return temp;
} }
LTS_ELEVATION_MANAGER_TYPE LtsElevationManager::getInstance(int exerciseId) LTS_ELEVATION_MANAGER_TYPE LtsElevationManager::getInstance(int exerciseId)
{ {
return LtsElevationManager::createInstance(exerciseId); return LtsElevationManager::createInstance(exerciseId);
} }
LTS_ELEVATION_MANAGER_TYPE LtsElevationManager::createInstanceForTrainingAreaId(int trainingAreaId, LTS_ELEVATION_MANAGER_TYPE
const std::shared_ptr<AssetManagement::Interface::Dtc> &asmDtc) LtsElevationManager::createInstanceForTrainingAreaId(int trainingAreaId,
const std::shared_ptr<AssetManagement::Interface::Dtc>& asmDtc)
{ {
LOGGER_T logger = getLogger("LtsElevationManager"); LOGGER_T logger = getLogger("LtsElevationManager");
TRACE_LOG(logger) << Q_FUNC_INFO << " START, trainingAreaId=" << trainingAreaId; TRACE_LOG(logger) << Q_FUNC_INFO << " START, trainingAreaId=" << trainingAreaId;
if (trainingAreaId < 0) if (trainingAreaId < 0)
{ {
ERROR_LOG(logger) << Q_FUNC_INFO << " trainingAreaId invalid, trainingAreaId=" << trainingAreaId; ERROR_LOG(logger) << Q_FUNC_INFO << " trainingAreaId invalid, trainingAreaId=" << trainingAreaId;
return nullptr; return nullptr;
} }
LtsElevatioMgrMapTrainingAreaId& map = getLtsElevationMgrMapTrainingAreaId();
QMap<int, LTS_ELEVATION_MANAGER_TYPE>::iterator it = map.find(trainingAreaId);
LtsElevatioMgrMapTrainingAreaId &map = getLtsElevationMgrMapTrainingAreaId(); if (it != map.end())
QMap<int, LTS_ELEVATION_MANAGER_TYPE>::iterator it = map.find(trainingAreaId); {
DEBUG_LOG(logger) << " LtsElevationMgrMap contains instances: " << map.size();
return it.value();
}
if (!asmDtc)
{
ERROR_LOG(logger) << Q_FUNC_INFO << " no dtcs for trainingAreaId=" << trainingAreaId << ", asmDtc=" << asmDtc;
return nullptr;
}
if (it != map.end()) LTS_ELEVATION_MANAGER_TYPE temp = new LtsElevationManager();
{
DEBUG_LOG(logger) << " LtsElevationMgrMap contains instances: " << map.size();
return it.value();
}
temp->initDDS(nullptr, asmDtc);
if (!asmDtc) const QStringList& filenames = temp->getFilenamesForTrainingArea(trainingAreaId);
{ if (filenames.isEmpty())
ERROR_LOG(logger) << Q_FUNC_INFO << " no dtcs for trainingAreaId=" << trainingAreaId {
<< ", asmDtc=" << asmDtc; ERROR_LOG(logger) << Q_FUNC_INFO << " no filenames for trainingAreaId=" << trainingAreaId;
return nullptr; delete temp;
} return nullptr;
}
LTS_ELEVATION_MANAGER_TYPE temp = new LtsElevationManager(); bool bInitFilenames = temp->init(filenames);
if (!bInitFilenames)
{
ERROR_LOG(logger) << Q_FUNC_INFO << " bInitFilenames failed for trainingAreaId=" << trainingAreaId;
delete temp;
return nullptr;
}
map.insert(trainingAreaId, temp);
temp->initDDS(nullptr, asmDtc); DEBUG_LOG(logger) << " LtsElevationMgrMap contains instances now: " << map.size();
const QStringList &filenames = temp->getFilenamesForTrainingArea(trainingAreaId); TRACE_LOG(logger) << Q_FUNC_INFO << " END, trainingAreaId=" << trainingAreaId;
if (filenames.isEmpty()) return map[trainingAreaId];
{
ERROR_LOG(logger) << Q_FUNC_INFO << " no filenames for trainingAreaId=" << trainingAreaId;
delete temp;
return nullptr;
}
bool bInitFilenames = temp->init(filenames);
if (!bInitFilenames)
{
ERROR_LOG(logger) << Q_FUNC_INFO << " bInitFilenames failed for trainingAreaId=" << trainingAreaId;
delete temp;
return nullptr;
}
map.insert(trainingAreaId, temp);
DEBUG_LOG(logger) << " LtsElevationMgrMap contains instances now: " << map.size();
TRACE_LOG(logger) << Q_FUNC_INFO << " END, trainingAreaId=" << trainingAreaId;
return map[trainingAreaId];
} }
LTS_ELEVATION_MANAGER_TYPE LtsElevationManager::createInstanceUnitTest(int id,
const QStringList& filePaths_rough_to_fine)
LTS_ELEVATION_MANAGER_TYPE LtsElevationManager::createInstanceUnitTest(int id, const QStringList &filePaths_rough_to_fine)
{ {
LOGGER_T logger = getLogger("LtsElevationManager"); LOGGER_T logger = getLogger("LtsElevationManager");
LtsElevatioMgrMapTrainingAreaId &map = getLtsElevationMgrMapTrainingAreaId(); LtsElevatioMgrMapTrainingAreaId& map = getLtsElevationMgrMapTrainingAreaId();
QMap<int, LTS_ELEVATION_MANAGER_TYPE>::iterator it = map.find(id); QMap<int, LTS_ELEVATION_MANAGER_TYPE>::iterator it = map.find(id);
if (it != map.end())
{
DEBUG_LOG(logger) << " LtsElevationMgrMap contains instances: " << map.size();
return it.value();
}
if (it != map.end()) LTS_ELEVATION_MANAGER_TYPE temp = new LtsElevationManager();
{
DEBUG_LOG(logger) << " LtsElevationMgrMap contains instances: " << map.size();
return it.value();
}
bool bInitFilenames = temp->init(filePaths_rough_to_fine);
if (!bInitFilenames)
{
ERROR_LOG(logger) << Q_FUNC_INFO << " bInitFilenames failed for id=" << id;
delete temp;
return nullptr;
}
LTS_ELEVATION_MANAGER_TYPE temp = new LtsElevationManager(); map.insert(id, temp);
bool bInitFilenames = temp->init(filePaths_rough_to_fine);
if (!bInitFilenames)
{
ERROR_LOG(logger) << Q_FUNC_INFO << " bInitFilenames failed for id=" << id;
delete temp;
return nullptr;
}
map.insert(id, temp);
DEBUG_LOG(logger) << " LtsElevationMgrMap contains instances now: " << map.size();
TRACE_LOG(logger) << Q_FUNC_INFO << " END, trainingAreaId=" << id;
return map[id];
DEBUG_LOG(logger) << " LtsElevationMgrMap contains instances now: " << map.size();
TRACE_LOG(logger) << Q_FUNC_INFO << " END, trainingAreaId=" << id;
return map[id];
} }
void LtsElevationManager::cleanupAll() void LtsElevationManager::cleanupAll()
{ {
LOGGER_T logger = getLogger("LtsElevationManager"); LOGGER_T logger = getLogger("LtsElevationManager");
TRACE_LOG(logger) << Q_FUNC_INFO << " START"; TRACE_LOG(logger) << Q_FUNC_INFO << " START";
cleanupLtsElevatioMgrMapTrainingAreaId(); cleanupLtsElevatioMgrMapTrainingAreaId();
TRACE_LOG(logger) << Q_FUNC_INFO << " END"; TRACE_LOG(logger) << Q_FUNC_INFO << " END";
} }
void LtsElevationManager::initDDS(const std::shared_ptr<ExerciseManagement::Interface::Dtc> &exmDtc, const std::shared_ptr<AssetManagement::Interface::Dtc> &asmDtc) void LtsElevationManager::initDDS(const std::shared_ptr<ExerciseManagement::Interface::Dtc>& exmDtc,
const std::shared_ptr<AssetManagement::Interface::Dtc>& asmDtc)
{ {
TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"; TRACE_LOG(m_logger) << Q_FUNC_INFO << " START";
d->m_exmDtc = exmDtc; d->m_exmDtc = exmDtc;
if (d->m_exmDtc) if (d->m_exmDtc)
d->m_exmDtc->waitForHistoricalDataExercise(1000); d->m_exmDtc->waitForHistoricalDataExercise(1000);
d->m_asmDtc = asmDtc; d->m_asmDtc = asmDtc;
if (d->m_asmDtc) if (d->m_asmDtc)
d->m_asmDtc->waitForHistoricalDataTrainingArea(1000); d->m_asmDtc->waitForHistoricalDataTrainingArea(1000);
TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"; TRACE_LOG(m_logger) << Q_FUNC_INFO << " END";
} }
QStringList LtsElevationManager::getFilenamesForExercise(int exerciseId) QStringList LtsElevationManager::getFilenamesForExercise(int exerciseId)
{ {
TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"; TRACE_LOG(m_logger) << Q_FUNC_INFO << " START";
if (!d->m_exmDtc || !d->m_asmDtc) if (!d->m_exmDtc || !d->m_asmDtc)
{ {
ERROR_LOG(m_logger) << Q_FUNC_INFO << " no dtcs" ERROR_LOG(m_logger) << Q_FUNC_INFO << " no dtcs"
<< ", exerciseId=" << exerciseId; << ", exerciseId=" << exerciseId;
return {}; return {};
} }
int trainingAreaId = exerciseIdToTrainingAreaId(exerciseId, d->m_exmDtc);
if (trainingAreaId <= 0)
{
ERROR_LOG(m_logger) << Q_FUNC_INFO << " Error getting trainingAreaId"
<< ", exerciseId=" << exerciseId << ", trainingAreaId=" << trainingAreaId;
return {};
}
int trainingAreaId = exerciseIdToTrainingAreaId(exerciseId, d->m_exmDtc); QStringList filePaths_rough_to_fine = getFilenamesForTrainingArea(trainingAreaId);
if (trainingAreaId <= 0)
{
ERROR_LOG(m_logger) << Q_FUNC_INFO << " Error getting trainingAreaId"
<< ", exerciseId=" << exerciseId
<< ", trainingAreaId=" << trainingAreaId;
return {};
}
QStringList filePaths_rough_to_fine = getFilenamesForTrainingArea(trainingAreaId); TRACE_LOG(m_logger) << Q_FUNC_INFO
<< " END, filePaths_rough_to_fine=" << filePaths_rough_to_fine.join(QStringLiteral(";"));
TRACE_LOG(m_logger) << Q_FUNC_INFO << " END, filePaths_rough_to_fine=" << filePaths_rough_to_fine.join(QStringLiteral(";")); return filePaths_rough_to_fine;
return filePaths_rough_to_fine;
} }
QStringList LtsElevationManager::getFilenamesForTrainingArea(int trainingAreaId) QStringList LtsElevationManager::getFilenamesForTrainingArea(int trainingAreaId)
{ {
TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"; TRACE_LOG(m_logger) << Q_FUNC_INFO << " START";
if (!d->m_asmDtc) if (!d->m_asmDtc)
{
ERROR_LOG(m_logger) << Q_FUNC_INFO << " no dtcs"
<< ", trainingAreaId=" << trainingAreaId;
return {};
}
QStringList filePaths_rough_to_fine;
{
d->m_asmDtc->waitForHistoricalDataTrainingArea(1000);
const AssetManagement::TrainingArea &ta = d->m_asmDtc->trainingArea(trainingAreaId);
if (ta.id() != trainingAreaId)
{ {
ERROR_LOG(m_logger) << Q_FUNC_INFO << " Error on s_asmDtc->trainingArea" ERROR_LOG(m_logger) << Q_FUNC_INFO << " no dtcs"
<< ", trainingAreaId=" << trainingAreaId; << ", trainingAreaId=" << trainingAreaId;
return {}; return {};
} }
const std::vector<AssetManagement::MapDescription> &mdVec = ta.elevation();
filePaths_rough_to_fine.reserve(mdVec.size());
for (const AssetManagement::MapDescription &md : std::as_const(mdVec)) QStringList filePaths_rough_to_fine;
{ {
d->m_asmDtc->waitForHistoricalDataTrainingArea(1000);
const AssetManagement::TrainingArea& ta = d->m_asmDtc->trainingArea(trainingAreaId);
if (ta.id() != trainingAreaId)
{
ERROR_LOG(m_logger) << Q_FUNC_INFO << " Error on s_asmDtc->trainingArea"
<< ", trainingAreaId=" << trainingAreaId;
return {};
}
const std::vector<AssetManagement::MapDescription>& mdVec = ta.elevation();
filePaths_rough_to_fine.reserve(mdVec.size());
QUrl url(QString::fromStdString(md.url())); for (const AssetManagement::MapDescription& md : std::as_const(mdVec))
QString filePathAbs = url.toLocalFile(); {
if (QDir::isRelativePath(filePathAbs))
filePathAbs = SituationMap::getResourcePath() + QStringLiteral("/elevation/") + filePathAbs;
filePaths_rough_to_fine.append(filePathAbs); QUrl url(QString::fromStdString(md.url()));
QString filePathAbs = url.toLocalFile();
if (QDir::isRelativePath(filePathAbs))
filePathAbs = SituationMap::getResourcePath() + QStringLiteral("/elevation/") + filePathAbs;
filePaths_rough_to_fine.append(filePathAbs);
}
} }
} TRACE_LOG(m_logger) << Q_FUNC_INFO
TRACE_LOG(m_logger) << Q_FUNC_INFO << " END, filePaths_rough_to_fine=" << filePaths_rough_to_fine.join(QStringLiteral(";")); << " END, filePaths_rough_to_fine=" << filePaths_rough_to_fine.join(QStringLiteral(";"));
return filePaths_rough_to_fine; return filePaths_rough_to_fine;
} }
bool LtsElevationManager::init(const QStringList &filePaths_rough_to_fine) bool LtsElevationManager::init(const QStringList& filePaths_rough_to_fine)
{ {
delete d->m_elevationManager; delete d->m_elevationManager;
d->m_elevationManager = new SituationMap::ElevationMapManager(); d->m_elevationManager = new SituationMap::ElevationMapManager();
int cnt = d->m_elevationManager->init(filePaths_rough_to_fine); int cnt = d->m_elevationManager->init(filePaths_rough_to_fine);
if (cnt != filePaths_rough_to_fine.size()) if (cnt != filePaths_rough_to_fine.size())
{ {
FATAL_LOG(m_logger) << Q_FUNC_INFO << " ERROR, not all files could be loaded !!!"; FATAL_LOG(m_logger) << Q_FUNC_INFO << " ERROR, not all files could be loaded !!!";
FATAL_LOG(m_logger) << Q_FUNC_INFO << " ERROR, not all files could be loaded !!!"; FATAL_LOG(m_logger) << Q_FUNC_INFO << " ERROR, not all files could be loaded !!!";
FATAL_LOG(m_logger) << Q_FUNC_INFO << " ERROR, not all files could be loaded !!!"; FATAL_LOG(m_logger) << Q_FUNC_INFO << " ERROR, not all files could be loaded !!!";
FATAL_LOG(m_logger) << Q_FUNC_INFO << " ERROR, not all files could be loaded !!!"; FATAL_LOG(m_logger) << Q_FUNC_INFO << " ERROR, not all files could be loaded !!!";
FATAL_LOG(m_logger) << Q_FUNC_INFO << " ERROR, not all files could be loaded !!!"; FATAL_LOG(m_logger) << Q_FUNC_INFO << " ERROR, not all files could be loaded !!!";
FATAL_LOG(m_logger) << Q_FUNC_INFO << " ERROR, not all files could be loaded !!!"; FATAL_LOG(m_logger) << Q_FUNC_INFO << " ERROR, not all files could be loaded !!!";
FATAL_LOG(m_logger) << Q_FUNC_INFO << " ERROR, not all files could be loaded !!!"; FATAL_LOG(m_logger) << Q_FUNC_INFO << " ERROR, not all files could be loaded !!!";
return false; return false;
} }
return true; return true;
} }
int LtsElevationManager::exerciseIdToTrainingAreaId(int exerciseId, const std::shared_ptr<ExerciseManagement::Interface::Dtc> &exmDtc) int LtsElevationManager::exerciseIdToTrainingAreaId(int exerciseId,
const std::shared_ptr<ExerciseManagement::Interface::Dtc>& exmDtc)
{ {
LOGGER_T logger = getLogger("LtsElevationManager"); LOGGER_T logger = getLogger("LtsElevationManager");
if (!exmDtc) if (!exmDtc)
{
ERROR_LOG(logger) << Q_FUNC_INFO << " no dtcs"
<< ", exerciseId=" << exerciseId;
return {};
}
int trainingAreaId = -1;
{
exmDtc->waitForHistoricalDataExercise(1000);
const ExerciseManagement::Exercise &exm = exmDtc->exercise(exerciseId);
if (exm.id() != exerciseId)
{ {
ERROR_LOG(logger) << Q_FUNC_INFO << " Error on m_exmDtc->exercise" ERROR_LOG(logger) << Q_FUNC_INFO << " no dtcs"
<< ", exerciseId=" << exerciseId; << ", exerciseId=" << exerciseId;
return {}; return {};
} }
trainingAreaId = exm.trainingAreaId();
if (trainingAreaId <= 0) int trainingAreaId = -1;
{ {
ERROR_LOG(logger) << Q_FUNC_INFO << " Error getting trainingAreaId" exmDtc->waitForHistoricalDataExercise(1000);
<< ", exerciseId=" << exerciseId
<< ", trainingAreaId=" << trainingAreaId; const ExerciseManagement::Exercise& exm = exmDtc->exercise(exerciseId);
return -1; if (exm.id() != exerciseId)
{
ERROR_LOG(logger) << Q_FUNC_INFO << " Error on m_exmDtc->exercise"
<< ", exerciseId=" << exerciseId;
return {};
}
trainingAreaId = exm.trainingAreaId();
if (trainingAreaId <= 0)
{
ERROR_LOG(logger) << Q_FUNC_INFO << " Error getting trainingAreaId"
<< ", exerciseId=" << exerciseId << ", trainingAreaId=" << trainingAreaId;
return -1;
}
} }
} return trainingAreaId;
return trainingAreaId;
} }
bool LtsElevationManager::waitForInitialization() bool LtsElevationManager::waitForInitialization()
{ {
if (!d->m_elevationManager) if (!d->m_elevationManager)
return false; return false;
return d->m_elevationManager->waitForInitialization(); return d->m_elevationManager->waitForInitialization();
} }
bool LtsElevationManager::isValid() const bool LtsElevationManager::isValid() const
{ {
if (!d->m_elevationManager) if (!d->m_elevationManager)
return false; return false;
return d->m_elevationManager->isValid(); return d->m_elevationManager->isValid();
} }
double LtsElevationManager::elevation(double lon_rad, double lat_rad, double defaultValue, bool *bIsCovered) const double LtsElevationManager::elevation(double lon_rad, double lat_rad, double defaultValue, bool* bIsCovered) const
{ {
if (!d->m_elevationManager) if (!d->m_elevationManager)
return defaultValue; return defaultValue;
return d->m_elevationManager->elevation(lon_rad, lat_rad, defaultValue, bIsCovered); return d->m_elevationManager->elevation(lon_rad, lat_rad, defaultValue, bIsCovered);
} }
LineOfSight LtsElevationManager::lineOfSightCalculation(const LtsUtils::QPoint3D &startPointGeo_absZ, LineOfSight LtsElevationManager::lineOfSightCalculation(const LtsUtils::QPoint3D& startPointGeo_absZ,
const LtsUtils::QPoint3D &endPointGeo_absZ) const LtsUtils::QPoint3D& endPointGeo_absZ)
{ {
TRACE_LOG(m_logger) << Q_FUNC_INFO << " START" << ", startPointGeo_absZ = " << startPointGeo_absZ << ", endPointGeo_absZ = " << endPointGeo_absZ; TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"
<< ", startPointGeo_absZ = " << startPointGeo_absZ
<< ", endPointGeo_absZ = " << endPointGeo_absZ;
if (!isValid()) if (!isValid())
{ {
ERROR_LOG(m_logger) << Q_FUNC_INFO << " Error, LtsElevationManager not valid"; ERROR_LOG(m_logger) << Q_FUNC_INFO << " Error, LtsElevationManager not valid";
return LineOfSight::LOS_ERROR; return LineOfSight::LOS_ERROR;
} }
SituationMap::ElevationMapManager::LineOfSight eleMapMgrResult =
d->m_elevationManager->lineOfSightCalculation(startPointGeo_absZ, endPointGeo_absZ);
SituationMap::ElevationMapManager::LineOfSight eleMapMgrResult = d->m_elevationManager->lineOfSightCalculation(startPointGeo_absZ,endPointGeo_absZ); LtsElevation::LineOfSight result = static_cast<LtsElevation::LineOfSight>(eleMapMgrResult);
TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"
LtsElevation::LineOfSight result = static_cast<LtsElevation::LineOfSight>(eleMapMgrResult); << ", startPointGeo = " << startPointGeo_absZ << ", endPointGeo = " << endPointGeo_absZ
<< " -> LineOfSight " << result;
TRACE_LOG(m_logger) << Q_FUNC_INFO << " END" << ", startPointGeo = " << startPointGeo_absZ << ", endPointGeo = " << endPointGeo_absZ return result;
<< " -> LineOfSight " << result;
return result;
} }
LineOfSight LtsElevationManager::lineOfSightCalculation(const QPointF &startPointGeo, double startHat, const QPointF &endPointGeo, double endHat) LineOfSight LtsElevationManager::lineOfSightCalculation(const QPointF& startPointGeo, double startHat,
const QPointF& endPointGeo, double endHat)
{ {
TRACE_LOG(m_logger) << Q_FUNC_INFO << " START" TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"
<< ", startPointGeo = " << startPointGeo << ", startHat = " << startHat << ", startPointGeo = " << startPointGeo << ", startHat = " << startHat
<< ", endPointGeo = " << endPointGeo << ", endHat = " << endHat; << ", endPointGeo = " << endPointGeo << ", endHat = " << endHat;
SituationMap::ElevationMapManager::LineOfSight eleMapMgrResult =
d->m_elevationManager->lineOfSightCalculation(startPointGeo, startHat, endPointGeo, endHat);
SituationMap::ElevationMapManager::LineOfSight eleMapMgrResult = d->m_elevationManager->lineOfSightCalculation(startPointGeo, startHat, LtsElevation::LineOfSight result = static_cast<LtsElevation::LineOfSight>(eleMapMgrResult);
endPointGeo, endHat);
TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"
LtsElevation::LineOfSight result = static_cast<LtsElevation::LineOfSight>(eleMapMgrResult); << ", startPointGeo = " << startPointGeo << ", startHat = " << startHat
<< ", endPointGeo = " << endPointGeo << ", endHat = " << endHat << " -> LineOfSight "
TRACE_LOG(m_logger) << Q_FUNC_INFO << " END" << static_cast<int>(eleMapMgrResult);
<< ", startPointGeo = " << startPointGeo << ", startHat = " << startHat return result;
<< ", endPointGeo = " << endPointGeo << ", endHat = " << endHat
<< " -> LineOfSight " << static_cast<int>(eleMapMgrResult);
return result;
} }
const QString toString(const LineOfSight& value)
const QString toString(const LineOfSight &value)
{ {
switch (value) switch (value)
{ {
case LineOfSight::LOS_UNDEFINED: case LineOfSight::LOS_UNDEFINED:
return QStringLiteral("LOS_UNDEFINED"); return QStringLiteral("LOS_UNDEFINED");
case LineOfSight::LOS_ERROR: case LineOfSight::LOS_ERROR:
return QStringLiteral("LOS_ERROR"); return QStringLiteral("LOS_ERROR");
case LineOfSight::LOS_VISIBLE: case LineOfSight::LOS_VISIBLE:
return QStringLiteral("LOS_VISIBLE"); return QStringLiteral("LOS_VISIBLE");
case LineOfSight::LOS_INVISIBLE: case LineOfSight::LOS_INVISIBLE:
return QStringLiteral("LOS_INVISIBLE"); return QStringLiteral("LOS_INVISIBLE");
} }
Q_ASSERT(false); Q_ASSERT(false);
return QStringLiteral("LineOfSightERROR"); return QStringLiteral("LineOfSightERROR");
} }
std::ostream &operator<<(std::ostream &stream, const LineOfSight value) std::ostream& operator<<(std::ostream& stream, const LineOfSight value)
{ {
stream << toString(value).toStdString(); stream << toString(value).toStdString();
return stream; return stream;
} }
} } // namespace LtsElevation
+41 -72
View File
@@ -1,23 +1,17 @@
#pragma once #pragma once
#include "logger.h" #include "logger.h"
#include "ltselevation_export.h" #include "ltselevation_export.h"
#include <LtsUtilsCore/qpoint3d.h> #include <LtsUtilsCore/qpoint3d.h>
#include <QCoreApplication>
#include <QObject> #include <QObject>
#include <QPointer> #include <QPointer>
#include <QStringList> #include <QStringList>
#include <QCoreApplication>
#include <memory>
#include <iosfwd> #include <iosfwd>
#include <memory>
namespace LtsSession namespace LtsSession
{ {
@@ -30,7 +24,7 @@ namespace Interface
{ {
class Dtc; class Dtc;
} }
} } // namespace ExerciseManagement
namespace AssetManagement namespace AssetManagement
{ {
@@ -38,92 +32,67 @@ namespace Interface
{ {
class Dtc; class Dtc;
} }
} } // namespace AssetManagement
namespace LtsElevation namespace LtsElevation
{ {
enum class LineOfSight { LOS_UNDEFINED, enum class LineOfSight { LOS_UNDEFINED, LOS_ERROR, LOS_VISIBLE, LOS_INVISIBLE };
LOS_ERROR,
LOS_VISIBLE,
LOS_INVISIBLE };
class LtsElevationManager; class LtsElevationManager;
using LTS_ELEVATION_MANAGER_TYPE = QPointer<LtsElevationManager>; using LTS_ELEVATION_MANAGER_TYPE = QPointer<LtsElevationManager>;
class LTSELEVATION_EXPORT LtsElevationManager : public QObject class LTSELEVATION_EXPORT LtsElevationManager : public QObject
{ {
public: public:
static LTS_ELEVATION_MANAGER_TYPE
createInstance(int exerciseId, const std::shared_ptr<ExerciseManagement::Interface::Dtc>& exmDtc = {},
const std::shared_ptr<AssetManagement::Interface::Dtc>& asmDtc = {});
static LTS_ELEVATION_MANAGER_TYPE getInstance(int exerciseId);
static LTS_ELEVATION_MANAGER_TYPE
createInstanceForTrainingAreaId(int trainingAreaId,
const std::shared_ptr<AssetManagement::Interface::Dtc>& asmDtc = nullptr);
static void cleanupAll();
virtual ~LtsElevationManager();
bool waitForInitialization();
bool isValid() const;
static LTS_ELEVATION_MANAGER_TYPE createInstance(int exerciseId, double elevation(double lon_rad, double lat_rad, double defaultValue = std::numeric_limits<double>::min(),
const std::shared_ptr<ExerciseManagement::Interface::Dtc> &exmDtc = {}, bool* bIsCovered = nullptr) const;
const std::shared_ptr<AssetManagement::Interface::Dtc> &asmDtc = {});
static LTS_ELEVATION_MANAGER_TYPE getInstance(int exerciseId); LineOfSight lineOfSightCalculation(const LtsUtils::QPoint3D& startPointGeo_absZ,
const LtsUtils::QPoint3D& endPointGeo_absZ);
LineOfSight lineOfSightCalculation(const QPointF& startPointGeo, double startHat, const QPointF& endPointGeo,
double endHat);
static LTS_ELEVATION_MANAGER_TYPE createInstanceForTrainingAreaId(int trainingAreaId, protected:
const std::shared_ptr<AssetManagement::Interface::Dtc> &asmDtc = nullptr); explicit LtsElevationManager();
void initDDS(const std::shared_ptr<ExerciseManagement::Interface::Dtc>& exmDtc,
const std::shared_ptr<AssetManagement::Interface::Dtc>& asmDtc);
bool init(const QStringList& filePaths_rough_to_fine);
static int exerciseIdToTrainingAreaId(int exerciseId,
const std::shared_ptr<ExerciseManagement::Interface::Dtc>& exmDtc);
QStringList getFilenamesForExercise(int exerciseId);
QStringList getFilenamesForTrainingArea(int trainingAreaId);
static LTS_ELEVATION_MANAGER_TYPE createInstanceUnitTest(int id, const QStringList& filePaths_rough_to_fine);
static void cleanupAll(); private:
virtual ~LtsElevationManager(); class Private;
Private* d;
bool waitForInitialization(); LOGGER_T m_logger;
bool isValid() const;
double elevation(double lon_rad, double lat_rad, double defaultValue = std::numeric_limits<double>::min(), bool *bIsCovered = nullptr) const;
LineOfSight lineOfSightCalculation(const LtsUtils::QPoint3D &startPointGeo_absZ,
const LtsUtils::QPoint3D &endPointGeo_absZ);
LineOfSight lineOfSightCalculation(const QPointF &startPointGeo, double startHat,
const QPointF &endPointGeo, double endHat);
protected:
explicit LtsElevationManager();
void initDDS(const std::shared_ptr<ExerciseManagement::Interface::Dtc> &exmDtc,
const std::shared_ptr<AssetManagement::Interface::Dtc> &asmDtc);
bool init(const QStringList &filePaths_rough_to_fine);
static int exerciseIdToTrainingAreaId(int exerciseId, const std::shared_ptr<ExerciseManagement::Interface::Dtc> &exmDtc);
QStringList getFilenamesForExercise(int exerciseId);
QStringList getFilenamesForTrainingArea(int trainingAreaId);
static LTS_ELEVATION_MANAGER_TYPE createInstanceUnitTest(int id, const QStringList &filePaths_rough_to_fine);
private:
class Private;
Private *d;
LOGGER_T m_logger;
}; };
LTSELEVATION_EXPORT const QString toString(const LtsElevation::LineOfSight &value); LTSELEVATION_EXPORT const QString toString(const LtsElevation::LineOfSight& value);
LTSELEVATION_EXPORT std::ostream &operator<< (std::ostream &stream, LTSELEVATION_EXPORT std::ostream& operator<<(std::ostream& stream, const LtsElevation::LineOfSight value);
const LtsElevation::LineOfSight value);
} // namespace LtsElevation
}
+138 -185
View File
@@ -1,232 +1,185 @@
#include "aes_crypt.h" #include "aes_crypt.h"
#include <QtCore/QByteArray>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <NGLLogger/NGLLoggerBootstrap.h> #include <NGLLogger/NGLLoggerBootstrap.h>
#include <QtCore/QByteArray>
#include <openssl/err.h>
#include <openssl/evp.h>
namespace LtsLicence namespace LtsLicence
{ {
struct AesCryptPrivate struct AesCryptPrivate
{ {
AesCryptPrivate() AesCryptPrivate()
: passPhrase(QLatin1String("LTS " LTS_VERSION_MAJOR "." LTS_VERSION_MINOR)) : passPhrase(QLatin1String("LTS " LTS_VERSION_MAJOR "." LTS_VERSION_MINOR)),
, logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("LtsLicenceLib.AesCrypt")) logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("LtsLicenceLib.AesCrypt"))
{ {
qsrand(time(nullptr)); qsrand(time(nullptr));
#if OPENSSL_VERSION_NUMBER < 0x1010000fL #if OPENSSL_VERSION_NUMBER < 0x1010000fL
ERR_load_crypto_strings(); ERR_load_crypto_strings();
#endif #endif
} }
~AesCryptPrivate()
{
#if OPENSSL_VERSION_NUMBER < 0x1010000fL
ERR_free_strings();
#endif
}
QString passPhrase; ~AesCryptPrivate()
NGL::INGLLogger &logger; {
#if OPENSSL_VERSION_NUMBER < 0x1010000fL
ERR_free_strings();
#endif
}
QString passPhrase;
NGL::INGLLogger& logger;
}; };
Q_GLOBAL_STATIC(AesCryptPrivate, s_Private) Q_GLOBAL_STATIC(AesCryptPrivate, s_Private)
void setPassPhrase(const QString &passPhrase) void setPassPhrase(const QString& passPhrase)
{ {
s_Private->passPhrase = passPhrase; s_Private->passPhrase = passPhrase;
} }
QString passPhrase() QString passPhrase()
{ {
return s_Private->passPhrase; return s_Private->passPhrase;
} }
QByteArray decryptData(const QByteArray &dataToDecrypt, QByteArray decryptData(const QByteArray& dataToDecrypt, const QString& pw, bool* bOk)
const QString &pw,
bool *bOk)
{ {
if (bOk) if (bOk)
*bOk = false; *bOk = false;
int ret; int ret;
int outSize1 = 0; int outSize1 = 0;
int outSize2 = 0; int outSize2 = 0;
unsigned char key[32]; unsigned char key[32];
const QByteArray baPassword = pw.toUtf8();
const unsigned char* dataPw = reinterpret_cast<const unsigned char*>(baPassword.data());
int i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha1(), nullptr, dataPw, baPassword.size(), 5, key, nullptr);
if (i != 32)
{
ERROR_LOG(s_Private->logger) << "Wrong key size - should be 256 bits";
return QByteArray();
}
const QByteArray baPassword = pw.toUtf8(); const QByteArray baSalt = dataToDecrypt.left(EVP_MAX_IV_LENGTH);
const unsigned char *dataPw = reinterpret_cast<const unsigned char *>(baPassword.data()); const unsigned char* salt = reinterpret_cast<const unsigned char*>(baSalt.data());
int i = EVP_BytesToKey(EVP_aes_256_cbc(),
EVP_sha1(),
nullptr,
dataPw,
baPassword.size(),
5,
key,
nullptr);
if (i != 32)
{
ERROR_LOG(s_Private->logger) << "Wrong key size - should be 256 bits" ;
return QByteArray();
}
const QByteArray baSalt = dataToDecrypt.left(EVP_MAX_IV_LENGTH); const QByteArray bufEncrypted = dataToDecrypt.mid(EVP_MAX_IV_LENGTH);
const unsigned char *salt = reinterpret_cast<const unsigned char *>(baSalt.data());
const QByteArray bufEncrypted = dataToDecrypt.mid(EVP_MAX_IV_LENGTH); EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
ret = EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, key, salt);
if (ret == 0)
{
EVP_CIPHER_CTX_free(ctx);
char errbuf[256];
ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf));
ERROR_LOG(s_Private->logger) << "EVP_DecryptInit_ex failed";
return QByteArray();
}
QByteArray bufDecrypted;
bufDecrypted.resize(bufEncrypted.size() + EVP_CIPHER_CTX_block_size(ctx));
const unsigned char* dataIn = reinterpret_cast<const unsigned char*>(bufEncrypted.data());
unsigned char* dataOut = reinterpret_cast<unsigned char*>(bufDecrypted.data());
ret = EVP_DecryptUpdate(ctx, dataOut, &outSize1, dataIn, bufEncrypted.size());
if (ret == 0)
{
EVP_CIPHER_CTX_free(ctx);
char errbuf[256];
ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf));
ERROR_LOG(s_Private->logger) << "EVP_DecryptUpdate failed";
return QByteArray();
}
ret = EVP_DecryptFinal_ex(ctx, dataOut + outSize1, &outSize2);
if (ret == 0)
{
EVP_CIPHER_CTX_free(ctx);
char errbuf[256];
ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf));
ERROR_LOG(s_Private->logger) << "EVP_DecryptFinal_ex failed";
return QByteArray();
}
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
ret = EVP_DecryptInit_ex(ctx,
EVP_aes_256_cbc(),
nullptr,
key,
salt);
if (ret == 0)
{
EVP_CIPHER_CTX_free(ctx); EVP_CIPHER_CTX_free(ctx);
char errbuf[256];
ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf));
ERROR_LOG(s_Private->logger) << "EVP_DecryptInit_ex failed" ;
return QByteArray();
}
bufDecrypted.resize(outSize1 + outSize2);
QByteArray bufDecrypted; if (bOk)
bufDecrypted.resize(bufEncrypted.size() + EVP_CIPHER_CTX_block_size(ctx)); *bOk = true;
const unsigned char *dataIn = reinterpret_cast<const unsigned char *>(bufEncrypted.data()); return bufDecrypted;
unsigned char *dataOut = reinterpret_cast<unsigned char *>(bufDecrypted.data());
ret = EVP_DecryptUpdate(ctx,
dataOut,
&outSize1,
dataIn,
bufEncrypted.size());
if (ret == 0)
{
EVP_CIPHER_CTX_free(ctx);
char errbuf[256];
ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf));
ERROR_LOG(s_Private->logger) << "EVP_DecryptUpdate failed" ;
return QByteArray();
}
ret = EVP_DecryptFinal_ex(ctx,
dataOut + outSize1,
&outSize2);
if (ret == 0)
{
EVP_CIPHER_CTX_free(ctx);
char errbuf[256];
ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf));
ERROR_LOG(s_Private->logger) << "EVP_DecryptFinal_ex failed" ;
return QByteArray();
}
EVP_CIPHER_CTX_free(ctx);
bufDecrypted.resize(outSize1 + outSize2);
if (bOk)
*bOk = true;
return bufDecrypted;
} }
QByteArray encryptData(const QByteArray& dataToEncrypt, const QString& pw, bool* bOk)
QByteArray encryptData(const QByteArray &dataToEncrypt,
const QString &pw,
bool *bOk)
{ {
if (bOk) if (bOk)
*bOk = false; *bOk = false;
int ret; int ret;
int outSize1 = 0; int outSize1 = 0;
int outSize2 = 0; int outSize2 = 0;
unsigned char key[32]; unsigned char key[32];
QByteArray bufEncrypted; QByteArray bufEncrypted;
const QByteArray baPassword = pw.toUtf8();
const unsigned char* dataPw = reinterpret_cast<const unsigned char*>(baPassword.data());
int i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha1(), nullptr, dataPw, baPassword.size(), 5, key, nullptr);
if (i != 32)
{
ERROR_LOG(s_Private->logger) << "Wrong key size - should be 256 bits";
return QByteArray();
}
const QByteArray baPassword = pw.toUtf8(); QByteArray baSalt(EVP_MAX_IV_LENGTH, 0);
const unsigned char *dataPw = reinterpret_cast<const unsigned char *>(baPassword.data()); for (int i = 0; i < EVP_MAX_IV_LENGTH; ++i)
int i = EVP_BytesToKey(EVP_aes_256_cbc(), baSalt[i] = qrand();
EVP_sha1(), const unsigned char* salt = reinterpret_cast<const unsigned char*>(baSalt.data());
nullptr,
dataPw,
baPassword.size(),
5,
key,
nullptr);
if (i != 32)
{
ERROR_LOG(s_Private->logger) << "Wrong key size - should be 256 bits" ;
return QByteArray();
}
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
ret = EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, key, salt);
if (ret == 0)
{
EVP_CIPHER_CTX_free(ctx);
char errbuf[256];
ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf));
ERROR_LOG(s_Private->logger) << "EVP_EncryptInit_ex failed";
return QByteArray();
}
QByteArray baSalt(EVP_MAX_IV_LENGTH, 0); bufEncrypted = QByteArray::fromRawData(reinterpret_cast<const char*>(salt), EVP_MAX_IV_LENGTH);
for (int i = 0; i < EVP_MAX_IV_LENGTH; ++i) bufEncrypted.resize(bufEncrypted.size() + dataToEncrypt.size() + EVP_CIPHER_CTX_block_size(ctx));
baSalt[i] = qrand(); const unsigned char* dataIn = reinterpret_cast<const unsigned char*>(dataToEncrypt.data());
const unsigned char *salt = reinterpret_cast<const unsigned char *>(baSalt.data()); unsigned char* dataOut = reinterpret_cast<unsigned char*>(bufEncrypted.data());
dataOut += baSalt.size();
ret = EVP_EncryptUpdate(ctx, dataOut, &outSize1, dataIn, dataToEncrypt.size());
if (ret == 0)
{
EVP_CIPHER_CTX_free(ctx);
char errbuf[256];
ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf));
ERROR_LOG(s_Private->logger) << "EVP_EncryptUpdate failed";
return QByteArray();
}
ret = EVP_EncryptFinal_ex(ctx, dataOut + outSize1, &outSize2);
if (ret == 0)
{
EVP_CIPHER_CTX_free(ctx);
char errbuf[256];
ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf));
ERROR_LOG(s_Private->logger) << "EVP_EncryptFinal_ex failed";
return QByteArray();
}
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
ret = EVP_EncryptInit_ex(ctx,
EVP_aes_256_cbc(),
nullptr,
key,
salt);
if (ret == 0)
{
EVP_CIPHER_CTX_free(ctx); EVP_CIPHER_CTX_free(ctx);
char errbuf[256];
ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf));
ERROR_LOG(s_Private->logger) << "EVP_EncryptInit_ex failed" ;
return QByteArray();
}
bufEncrypted.resize(outSize1 + outSize2 + baSalt.size());
bufEncrypted = QByteArray::fromRawData(reinterpret_cast<const char *>(salt), EVP_MAX_IV_LENGTH); if (bOk)
bufEncrypted.resize(bufEncrypted.size() + *bOk = true;
dataToEncrypt.size() + return bufEncrypted;
EVP_CIPHER_CTX_block_size(ctx));
const unsigned char *dataIn = reinterpret_cast<const unsigned char *>(dataToEncrypt.data());
unsigned char *dataOut = reinterpret_cast<unsigned char *>(bufEncrypted.data());
dataOut += baSalt.size();
ret = EVP_EncryptUpdate(ctx,
dataOut,
&outSize1,
dataIn,
dataToEncrypt.size());
if (ret == 0)
{
EVP_CIPHER_CTX_free(ctx);
char errbuf[256];
ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf));
ERROR_LOG(s_Private->logger) << "EVP_EncryptUpdate failed" ;
return QByteArray();
}
ret = EVP_EncryptFinal_ex(ctx,
dataOut + outSize1,
&outSize2);
if (ret == 0)
{
EVP_CIPHER_CTX_free(ctx);
char errbuf[256];
ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf));
ERROR_LOG(s_Private->logger) << "EVP_EncryptFinal_ex failed" ;
return QByteArray();
}
EVP_CIPHER_CTX_free(ctx);
bufEncrypted.resize(outSize1 + outSize2 + baSalt.size());
if (bOk)
*bOk = true;
return bufEncrypted;
} }
} } // namespace LtsLicence
+8 -10
View File
@@ -1,22 +1,20 @@
#pragma once #pragma once
#include <QtCore/QString>
#include "ltslicence_export.h" #include "ltslicence_export.h"
#include <QtCore/QString>
namespace LtsLicence namespace LtsLicence
{ {
LTSLICENCE_EXPORT void setPassPhrase(const QString &passPhrase); LTSLICENCE_EXPORT void setPassPhrase(const QString& passPhrase);
LTSLICENCE_EXPORT QString passPhrase(); LTSLICENCE_EXPORT QString passPhrase();
LTSLICENCE_EXPORT QByteArray decryptData(const QByteArray &dataToDecrypt, LTSLICENCE_EXPORT QByteArray decryptData(const QByteArray& dataToDecrypt, const QString& pw = passPhrase(),
const QString &pw = passPhrase(), bool* bOk = nullptr);
bool *bOk = nullptr);
LTSLICENCE_EXPORT QByteArray encryptData(const QByteArray &dataToEncrypt, LTSLICENCE_EXPORT QByteArray encryptData(const QByteArray& dataToEncrypt, const QString& pw = passPhrase(),
const QString &pw = passPhrase(), bool* bOk = nullptr);
bool *bOk = nullptr); } // namespace LtsLicence
}
+32 -33
View File
@@ -1,54 +1,53 @@
#include "aes_crypt_test.h"
#include <QtCore/QCoreApplication>
#include <QtTest/QTest>
#include <NGLLogger/NGLLoggerBootstrap.h>
#include <openssl/evp.h>
#include "aes_crypt.h" #include "aes_crypt.h"
#include "aes_crypt_test.h"
#include <NGLLogger/NGLLoggerBootstrap.h>
#include <QtCore/QCoreApplication>
#include <QtTest/QTest>
#include <openssl/evp.h>
QTEST_MAIN(aes_crypt_test) QTEST_MAIN(aes_crypt_test)
void aes_crypt_test::initTestCase() void aes_crypt_test::initTestCase()
{ {
NGL::NGLLoggerBootstrap::createNGLRootLogger("log4cxx.props", false); NGL::NGLLoggerBootstrap::createNGLRootLogger("log4cxx.props", false);
} }
void aes_crypt_test::truePassTest() void aes_crypt_test::truePassTest()
{ {
qDebug("Simple TestCase"); qDebug("Simple TestCase");
bool bOk; bool bOk;
const QByteArray content("30.06.2013"); const QByteArray content("30.06.2013");
const QString pw(QStringLiteral("aes_crypt_test")); const QString pw(QStringLiteral("aes_crypt_test"));
const QByteArray enc = LtsLicence::encryptData(content, pw, &bOk); const QByteArray enc = LtsLicence::encryptData(content, pw, &bOk);
QVERIFY2(bOk, "Error encrypting data..."); QVERIFY2(bOk, "Error encrypting data...");
QCOMPARE(((content.size() + 15 + EVP_MAX_IV_LENGTH) / 18) * 16, enc.size()); QCOMPARE(((content.size() + 15 + EVP_MAX_IV_LENGTH) / 18) * 16, enc.size());
const QByteArray dec = LtsLicence::decryptData(enc, pw, &bOk); const QByteArray dec = LtsLicence::decryptData(enc, pw, &bOk);
QVERIFY2(bOk, "Error encrypting data..."); QVERIFY2(bOk, "Error encrypting data...");
QCOMPARE(dec, content); QCOMPARE(dec, content);
const QByteArray bigContent(12345, '1');
const QByteArray bigEnc = LtsLicence::encryptData(bigContent, pw, &bOk);
QVERIFY2(bOk, "Error encrypting data...");
const QByteArray bigContent(12345, '1'); QCOMPARE(((bigContent.size() + 15 + EVP_MAX_IV_LENGTH) / 16) * 16, bigEnc.size());
const QByteArray bigEnc = LtsLicence::encryptData(bigContent, pw, &bOk);
QVERIFY2(bOk, "Error encrypting data...");
QCOMPARE(((bigContent.size() + 15 + EVP_MAX_IV_LENGTH) / 16) * 16, bigEnc.size());
} }
void aes_crypt_test::falsePassTest() void aes_crypt_test::falsePassTest()
{ {
qDebug("False Password TestCase"); qDebug("False Password TestCase");
bool bOk; bool bOk;
const QByteArray content("30.06.2013"); const QByteArray content("30.06.2013");
const QString pw(QStringLiteral("aes_crypt_test")); const QString pw(QStringLiteral("aes_crypt_test"));
const QString pw2(QStringLiteral("aes_crypt_test2")); const QString pw2(QStringLiteral("aes_crypt_test2"));
const QByteArray enc = LtsLicence::encryptData(content, pw, &bOk); const QByteArray enc = LtsLicence::encryptData(content, pw, &bOk);
QVERIFY2(bOk, "Error encrypting data..."); QVERIFY2(bOk, "Error encrypting data...");
QVERIFY2(enc.size() != 20, "Error encrypting data..."); QVERIFY2(enc.size() != 20, "Error encrypting data...");
const QByteArray dec = LtsLicence::decryptData(enc, pw2, &bOk); const QByteArray dec = LtsLicence::decryptData(enc, pw2, &bOk);
QVERIFY2(!bOk, "Error encrypting data..."); QVERIFY2(!bOk, "Error encrypting data...");
QVERIFY2(dec.isEmpty(), "decrypted data is not empty..."); QVERIFY2(dec.isEmpty(), "decrypted data is not empty...");
} }
+5 -7
View File
@@ -1,16 +1,14 @@
#pragma once #pragma once
#include <QObject> #include <QObject>
#include <QtCore/QObject> #include <QtCore/QObject>
class aes_crypt_test : public QObject class aes_crypt_test : public QObject
{ {
Q_OBJECT Q_OBJECT
private Q_SLOTS: private Q_SLOTS:
void initTestCase(); void initTestCase();
void truePassTest(); void truePassTest();
void falsePassTest(); void falsePassTest();
}; };
+108 -131
View File
@@ -1,173 +1,150 @@
#include "lts_licence.h" #include "lts_licence.h"
#include <QDomDocument>
#include <NGLLogger/NGLLoggerBootstrap.h> #include <NGLLogger/NGLLoggerBootstrap.h>
#include <QDomDocument>
#include <QObject> #include <QObject>
namespace LtsLicence namespace LtsLicence
{ {
static bool extractLicence(const QDomElement &licenceElement, QVector<Licence> &licenceVec); static bool extractLicence(const QDomElement& licenceElement, QVector<Licence>& licenceVec);
static NGL::INGLLogger &getLogger()
static NGL::INGLLogger& getLogger()
{ {
return NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("LtsLicence"); return NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("LtsLicence");
} }
QVector<Licence> readLicences(const QByteArray &unencryptedXmlData) QVector<Licence> readLicences(const QByteArray& unencryptedXmlData)
{ {
QVector<Licence> licenceVec; QVector<Licence> licenceVec;
QDomDocument xmlDoc; QDomDocument xmlDoc;
QString errorMsg; QString errorMsg;
int errorLine = 0; int errorLine = 0;
int errorColumn = 0; int errorColumn = 0;
if (!xmlDoc.setContent(unencryptedXmlData, &errorMsg, &errorLine, &errorColumn)) if (!xmlDoc.setContent(unencryptedXmlData, &errorMsg, &errorLine, &errorColumn))
{
ERROR_LOG(getLogger()) << "Error reading xml data, " << "error in line " << errorLine
<< ", column " << errorColumn
<< ", message: " << errorMsg;
return licenceVec;
}
INFO_LOG(getLogger()) << "Try to extract licences";
QDomElement licenceElement = xmlDoc.documentElement().firstChildElement(QLatin1String("licence"));
while (!licenceElement.isNull())
{
if (!extractLicence(licenceElement, licenceVec))
{ {
licenceVec.clear(); ERROR_LOG(getLogger()) << "Error reading xml data, "
return licenceVec; << "error in line " << errorLine << ", column " << errorColumn
<< ", message: " << errorMsg;
return licenceVec;
} }
licenceElement = licenceElement.nextSiblingElement(QLatin1String("licence")); INFO_LOG(getLogger()) << "Try to extract licences";
}
return licenceVec; QDomElement licenceElement = xmlDoc.documentElement().firstChildElement(QLatin1String("licence"));
while (!licenceElement.isNull())
{
if (!extractLicence(licenceElement, licenceVec))
{
licenceVec.clear();
return licenceVec;
}
licenceElement = licenceElement.nextSiblingElement(QLatin1String("licence"));
}
return licenceVec;
} }
QByteArray writeUnencryptedLicences(const QVector<Licence>& licences)
QByteArray writeUnencryptedLicences(const QVector<Licence> &licences)
{ {
QDomDocument xmlDoc; QDomDocument xmlDoc;
QDomProcessingInstruction instr = xmlDoc.createProcessingInstruction(QLatin1String("xml"), QDomProcessingInstruction instr = xmlDoc.createProcessingInstruction(
QLatin1String("version='1.0' encoding='UTF-8' standalone='yes'")); QLatin1String("xml"), QLatin1String("version='1.0' encoding='UTF-8' standalone='yes'"));
xmlDoc.appendChild(instr); xmlDoc.appendChild(instr);
QDomElement root = xmlDoc.createElement(QLatin1String("licences")); QDomElement root = xmlDoc.createElement(QLatin1String("licences"));
xmlDoc.appendChild(root); xmlDoc.appendChild(root);
for (int i = 0; i < licences.size(); ++i) for (int i = 0; i < licences.size(); ++i)
{ {
QDomElement lic = xmlDoc.createElement(QLatin1String("licence")); QDomElement lic = xmlDoc.createElement(QLatin1String("licence"));
root.appendChild(lic); root.appendChild(lic);
QDomElement element = xmlDoc.createElement(QLatin1String("name"));
QDomText text = xmlDoc.createTextNode(licences[i].name);
element.appendChild(text);
lic.appendChild(element);
QDomElement element = xmlDoc.createElement(QLatin1String("name")); element = xmlDoc.createElement(QLatin1String("ignoreMaxCount"));
QDomText text = xmlDoc.createTextNode(licences[i].name); text = xmlDoc.createTextNode(QString::number(licences[i].ignoreMaxCount));
element.appendChild(text); element.appendChild(text);
lic.appendChild(element); lic.appendChild(element);
element = xmlDoc.createElement(QLatin1String("ignoreExpiration"));
text = xmlDoc.createTextNode(QString::number(licences[i].ignoreExpiration));
element.appendChild(text);
lic.appendChild(element);
element = xmlDoc.createElement(QLatin1String("ignoreMaxCount")); element = xmlDoc.createElement(QLatin1String("maxCount"));
text = xmlDoc.createTextNode(QString::number(licences[i].ignoreMaxCount)); text = xmlDoc.createTextNode(QString::number(licences[i].maxCount));
element.appendChild(text); element.appendChild(text);
lic.appendChild(element); lic.appendChild(element);
const QLatin1String format("dd.MM.yyyy hh:mm:ss");
const QString qs = licences[i].expiration.toString(format);
element = xmlDoc.createElement(QLatin1String("ignoreExpiration")); element = xmlDoc.createElement(QLatin1String("expiration"));
text = xmlDoc.createTextNode(QString::number(licences[i].ignoreExpiration)); text = xmlDoc.createTextNode(qs);
element.appendChild(text); element.appendChild(text);
lic.appendChild(element); lic.appendChild(element);
}
INFO_LOG(getLogger()) << "Generated XML Data...\n" << xmlDoc.toByteArray();
return xmlDoc.toByteArray();
}
bool extractLicence(const QDomElement& licenceElement, QVector<Licence>& licenceVec)
{
Licence licence;
element = xmlDoc.createElement(QLatin1String("maxCount")); QDomElement tag = licenceElement.firstChildElement(QLatin1String("name"));
text = xmlDoc.createTextNode(QString::number(licences[i].maxCount)); licence.name = tag.text();
element.appendChild(text);
lic.appendChild(element);
tag = licenceElement.firstChildElement(QLatin1String("ignoreMaxCount"));
licence.ignoreMaxCount = tag.text().toInt();
tag = licenceElement.firstChildElement(QLatin1String("ignoreExpiration"));
licence.ignoreExpiration = tag.text().toInt();
tag = licenceElement.firstChildElement(QLatin1String("maxCount"));
licence.maxCount = tag.text().toInt();
tag = licenceElement.firstChildElement(QLatin1String("expiration"));
const QString qs(tag.text());
const QLatin1String format("dd.MM.yyyy hh:mm:ss"); const QLatin1String format("dd.MM.yyyy hh:mm:ss");
const QString qs = licences[i].expiration.toString(format); const QDateTime qdt = QDateTime::fromString(qs, format);
if (!qdt.isValid())
{
ERROR_LOG(getLogger()) << "Invalid expiration format! " << qs << " used format: " << format;
return false;
}
element = xmlDoc.createElement(QLatin1String("expiration")); licence.expiration = qdt;
text = xmlDoc.createTextNode(qs); INFO_LOG(getLogger()) << "Read licence for:'" << licence.name << "'"
element.appendChild(text); << " IgnoreMaxCount: " << licence.ignoreMaxCount
lic.appendChild(element); << " IgnoreExpiration: " << licence.ignoreExpiration << " MaxCount: " << licence.maxCount
} << " Expiration: " << licence.expiration.date().toString() << " "
INFO_LOG(getLogger()) << "Generated XML Data...\n" << xmlDoc.toByteArray(); << licence.expiration.time().toString() << " RefCount: " << licence.licenceRefCount;
return xmlDoc.toByteArray();
licenceVec.append(licence);
return true;
} }
bool extractLicence(const QDomElement &licenceElement, QVector<Licence> &licenceVec)
{
Licence licence;
QDomElement tag = licenceElement.firstChildElement(QLatin1String("name"));
licence.name = tag.text();
tag = licenceElement.firstChildElement(QLatin1String("ignoreMaxCount"));
licence.ignoreMaxCount = tag.text().toInt();
tag = licenceElement.firstChildElement(QLatin1String("ignoreExpiration"));
licence.ignoreExpiration = tag.text().toInt();
tag = licenceElement.firstChildElement(QLatin1String("maxCount"));
licence.maxCount = tag.text().toInt();
tag = licenceElement.firstChildElement(QLatin1String("expiration"));
const QString qs(tag.text());
const QLatin1String format("dd.MM.yyyy hh:mm:ss");
const QDateTime qdt = QDateTime::fromString(qs, format);
if (!qdt.isValid())
{
ERROR_LOG(getLogger()) << "Invalid expiration format! " << qs
<< " used format: " << format
;
return false;
}
licence.expiration = qdt;
INFO_LOG(getLogger()) << "Read licence for:'" << licence.name << "'"
<< " IgnoreMaxCount: " << licence.ignoreMaxCount
<< " IgnoreExpiration: " << licence.ignoreExpiration
<< " MaxCount: " << licence.maxCount
<< " Expiration: " << licence.expiration.date().toString()
<< " " << licence.expiration.time().toString()
<< " RefCount: " << licence.licenceRefCount
;
licenceVec.append(licence);
return true;
}
QString Licence::toString() const QString Licence::toString() const
{ {
return QObject::tr("Name: %1, Count: %2, ExpireDate: %3, Expires: %4, UseMaxCount: %5") return QObject::tr("Name: %1, Count: %2, ExpireDate: %3, Expires: %4, UseMaxCount: %5")
.arg(name) .arg(name)
.arg(maxCount) .arg(maxCount)
.arg(expiration.toString()) .arg(expiration.toString())
.arg(ignoreExpiration) .arg(ignoreExpiration)
.arg(ignoreMaxCount); .arg(ignoreMaxCount);
} }
} // namespace LtsLicence
}
+12 -16
View File
@@ -1,33 +1,29 @@
#pragma once #pragma once
#include "ltslicence_export.h" #include "ltslicence_export.h"
#include <QDateTime>
#include <QString> #include <QString>
#include <QVector> #include <QVector>
#include <QDateTime>
namespace LtsLicence namespace LtsLicence
{ {
struct LTSLICENCE_EXPORT Licence struct LTSLICENCE_EXPORT Licence
{ {
QString name; QString name;
bool ignoreMaxCount = false; bool ignoreMaxCount = false;
bool ignoreExpiration = false; bool ignoreExpiration = false;
int maxCount = 0; int maxCount = 0;
QDateTime expiration; QDateTime expiration;
int licenceRefCount = 0; int licenceRefCount = 0;
QString toString() const; QString toString() const;
}; };
LTSLICENCE_EXPORT QVector<Licence> readLicences(const QByteArray& unencryptedXmlData);
LTSLICENCE_EXPORT QByteArray writeUnencryptedLicences(const QVector<Licence>& licences);
LTSLICENCE_EXPORT QVector<Licence> readLicences(const QByteArray &unencryptedXmlData); } // namespace LtsLicence
LTSLICENCE_EXPORT QByteArray writeUnencryptedLicences(const QVector<Licence> &licences);
}
+50 -52
View File
@@ -1,94 +1,92 @@
#include "logout_info_dialog.h" #include "logout_info_dialog.h"
#include "ui_logout_info_dialog.h" #include "ui_logout_info_dialog.h"
#include <QTimer> #include <QTimer>
namespace LtsLogin namespace LtsLogin
{ {
LogoutInformationDialog::LogoutInformationDialog(int timeOut, AssetManagement::ShutdownAction shutdownAction, QWidget *parent) LogoutInformationDialog::LogoutInformationDialog(int timeOut, AssetManagement::ShutdownAction shutdownAction,
: LtsWidgets::LtsFramelessDialog(parent, LtsWidgets::Behaviour::Modal) QWidget* parent)
, m_ui(new Ui::LogoutInformationDialog) : LtsWidgets::LtsFramelessDialog(parent, LtsWidgets::Behaviour::Modal), m_ui(new Ui::LogoutInformationDialog),
, m_timer(new QTimer(this)) m_timer(new QTimer(this)), m_timeOut(timeOut), m_secsLeft(timeOut)
, m_timeOut(timeOut)
, m_secsLeft(timeOut)
{ {
m_ui->setupUi(this); m_ui->setupUi(this);
QString actionText; QString actionText;
switch(shutdownAction.underlying()) switch (shutdownAction.underlying())
{ {
case AssetManagement::ShutdownAction::NoAction: case AssetManagement::ShutdownAction::NoAction:
case AssetManagement::ShutdownAction::Logout: case AssetManagement::ShutdownAction::Logout:
actionText = tr("logout"); actionText = tr("logout");
break; break;
case AssetManagement::ShutdownAction::Shutdown: case AssetManagement::ShutdownAction::Shutdown:
actionText = tr("shutdown"); actionText = tr("shutdown");
break; break;
case AssetManagement::ShutdownAction::Reboot: case AssetManagement::ShutdownAction::Reboot:
actionText = tr("reboot"); actionText = tr("reboot");
break; break;
} }
setText(tr("A %1 was triggered by a remote workstation.").arg(actionText)); setText(tr("A %1 was triggered by a remote workstation.").arg(actionText));
connect(m_ui->buttonBox->getButton(LtsWidgets::DialogButton::Ok), &QPushButton::clicked, this, &LogoutInformationDialog::acceptClicked); connect(m_ui->buttonBox->getButton(LtsWidgets::DialogButton::Ok), &QPushButton::clicked, this,
connect(m_ui->buttonBox->getButton(LtsWidgets::DialogButton::Close), &QPushButton::clicked, this, &LogoutInformationDialog::closeClicked); &LogoutInformationDialog::acceptClicked);
connect(m_timer, &QTimer::timeout, this, &LogoutInformationDialog::onTimerTimeout); connect(m_ui->buttonBox->getButton(LtsWidgets::DialogButton::Close), &QPushButton::clicked, this,
&LogoutInformationDialog::closeClicked);
connect(m_timer, &QTimer::timeout, this, &LogoutInformationDialog::onTimerTimeout);
m_timer->setInterval(1000); m_timer->setInterval(1000);
} }
LogoutInformationDialog::~LogoutInformationDialog() LogoutInformationDialog::~LogoutInformationDialog()
{ {
delete m_ui; delete m_ui;
} }
void LogoutInformationDialog::setText(const QString &text) void LogoutInformationDialog::setText(const QString& text)
{ {
m_ui->lblLogoutText->setText(text); m_ui->lblLogoutText->setText(text);
} }
void LogoutInformationDialog::onTimerTimeout() void LogoutInformationDialog::onTimerTimeout()
{ {
if (m_secsLeft > 0) if (m_secsLeft > 0)
{ {
m_secsLeft--; m_secsLeft--;
setCloseButtonText(m_secsLeft); setCloseButtonText(m_secsLeft);
} }
else else
{ {
acceptClicked(); acceptClicked();
} }
} }
void LogoutInformationDialog::acceptClicked() void LogoutInformationDialog::acceptClicked()
{ {
m_timer->stop(); m_timer->stop();
accept(); accept();
} }
void LogoutInformationDialog::closeClicked() void LogoutInformationDialog::closeClicked()
{ {
m_timer->stop(); m_timer->stop();
reject(); reject();
} }
void LogoutInformationDialog::setCloseButtonText(int secsLeft) void LogoutInformationDialog::setCloseButtonText(int secsLeft)
{ {
m_ui->buttonBox->getButton(LtsWidgets::DialogButton::Close)->setText(tr("Abort [%1]").arg(secsLeft)); m_ui->buttonBox->getButton(LtsWidgets::DialogButton::Close)->setText(tr("Abort [%1]").arg(secsLeft));
} }
void LogoutInformationDialog::showEvent(QShowEvent *event) void LogoutInformationDialog::showEvent(QShowEvent* event)
{ {
m_secsLeft = m_timeOut; m_secsLeft = m_timeOut;
setCloseButtonText(m_secsLeft); setCloseButtonText(m_secsLeft);
m_timer->start(); m_timer->start();
LtsWidgets::LtsFramelessDialog::showEvent(event); LtsWidgets::LtsFramelessDialog::showEvent(event);
} }
} } // namespace LtsLogin
+24 -24
View File
@@ -1,44 +1,44 @@
#pragma once #pragma once
#include <QObject>
#include <LtsWidgets/lts_frameless_dialog.h>
#include <AssetManagement/asm.hpp> #include <AssetManagement/asm.hpp>
#include <LtsWidgets/lts_frameless_dialog.h>
#include <QObject>
class QTimer; class QTimer;
namespace Ui { class LogoutInformationDialog; } namespace Ui
{
class LogoutInformationDialog;
}
namespace LtsLogin namespace LtsLogin
{ {
class LogoutInformationDialog : public LtsWidgets::LtsFramelessDialog class LogoutInformationDialog : public LtsWidgets::LtsFramelessDialog
{ {
Q_OBJECT Q_OBJECT
public: public:
LogoutInformationDialog(int timeOut, AssetManagement::ShutdownAction shutdownAction, QWidget *parent = nullptr); LogoutInformationDialog(int timeOut, AssetManagement::ShutdownAction shutdownAction, QWidget* parent = nullptr);
~LogoutInformationDialog(); ~LogoutInformationDialog();
private slots: private slots:
void onTimerTimeout(); void onTimerTimeout();
void acceptClicked(); void acceptClicked();
void closeClicked(); void closeClicked();
private: private:
void setText(const QString &text); void setText(const QString& text);
void setCloseButtonText(int secsLeft); void setCloseButtonText(int secsLeft);
Ui::LogoutInformationDialog *m_ui; Ui::LogoutInformationDialog* m_ui;
QTimer *m_timer; QTimer* m_timer;
int m_timeOut; int m_timeOut;
int m_secsLeft; int m_secsLeft;
protected:
protected: void showEvent(QShowEvent* event) override final;
void showEvent(QShowEvent *event) override final;
}; };
} } // namespace LtsLogin
+193 -223
View File
@@ -1,312 +1,282 @@
#include "lts_login.h" #include "lts_login.h"
#include "logout_info_dialog.h" #include "logout_info_dialog.h"
#include <LtsPluginManager/lts_plugin_manager.h>
#include <LtsAppDescriptor/lts_app_descriptor.h> #include <LtsAppDescriptor/lts_app_descriptor.h>
#include <LtsSession/lts_session_manager.h> #include <LtsPluginManager/lts_plugin_manager.h>
#include <LtsSession/lts_session.h> #include <LtsSession/lts_session.h>
#include <LtsSession/lts_session_data.h> #include <LtsSession/lts_session_data.h>
#include <LtsWidgets/lts_wait_dialog.h> #include <LtsSession/lts_session_manager.h>
#include <LtsUtilsCore/dds_vector.h> #include <LtsUtilsCore/dds_vector.h>
#include <LtsUtilsSettings/settings.h> #include <LtsUtilsSettings/settings.h>
#include <LtsWidgets/lts_wait_dialog.h>
#include <QCoreApplication> #include <QCoreApplication>
#include <QProcess>
#include <QMessageBox>
#include <QDebug> #include <QDebug>
#include <QDir> #include <QDir>
#include <QMessageBox>
#include <QProcess>
namespace LtsLogin namespace LtsLogin
{ {
const int logoutShutdownTimeout = 2 * 60; const int logoutShutdownTimeout = 2 * 60;
LtsLogin::LtsLogin() LtsLogin::LtsLogin()
: m_loginApp(nullptr) : m_loginApp(nullptr), m_shutdownAction(AssetManagement::ShutdownAction::NoAction), m_isInLogoutDialog(false)
, m_shutdownAction(AssetManagement::ShutdownAction::NoAction) {
, m_isInLogoutDialog(false) }
{}
LtsLogin::~LtsLogin() LtsLogin::~LtsLogin()
{ {
delete m_loginApp; delete m_loginApp;
m_loginApp = nullptr; m_loginApp = nullptr;
} }
void LtsLogin::login() void LtsLogin::login()
{ {
LtsAppDescriptor::PluginInfo opmDataPlugin; LtsAppDescriptor::PluginInfo opmDataPlugin;
opmDataPlugin.iid = QStringLiteral("opm"); opmDataPlugin.iid = QStringLiteral("opm");
opmDataPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::DATA; opmDataPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::DATA;
LtsAppDescriptor::PluginInfo pdmDataPlugin; LtsAppDescriptor::PluginInfo pdmDataPlugin;
pdmDataPlugin.iid = QStringLiteral("pdm"); pdmDataPlugin.iid = QStringLiteral("pdm");
pdmDataPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::DATA; pdmDataPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::DATA;
LtsAppDescriptor::PluginInfo asmDataPlugin; LtsAppDescriptor::PluginInfo asmDataPlugin;
asmDataPlugin.iid = QStringLiteral("asm"); asmDataPlugin.iid = QStringLiteral("asm");
asmDataPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::DATA; asmDataPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::DATA;
LtsAppDescriptor::PluginInfo srmDataPlugin; LtsAppDescriptor::PluginInfo srmDataPlugin;
srmDataPlugin.iid = QStringLiteral("srm"); srmDataPlugin.iid = QStringLiteral("srm");
srmDataPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::DATA; srmDataPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::DATA;
LtsAppDescriptor::PluginInfo guiPlugin; LtsAppDescriptor::PluginInfo guiPlugin;
guiPlugin.iid = m_loginPluginIid; guiPlugin.iid = m_loginPluginIid;
guiPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::GUI; guiPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::GUI;
guiPlugin.flags |= LtsAppDescriptor::PluginInfo::Flag::PAYLOAD; guiPlugin.flags |= LtsAppDescriptor::PluginInfo::Flag::PAYLOAD;
QVector<LtsAppDescriptor::PluginInfo> plugins; QVector<LtsAppDescriptor::PluginInfo> plugins;
plugins.append(opmDataPlugin); plugins.append(opmDataPlugin);
plugins.append(pdmDataPlugin); plugins.append(pdmDataPlugin);
plugins.append(asmDataPlugin); plugins.append(asmDataPlugin);
plugins.append(srmDataPlugin); plugins.append(srmDataPlugin);
plugins.append(guiPlugin); plugins.append(guiPlugin);
LtsAppDescriptor::AppDescription app; LtsAppDescriptor::AppDescription app;
app.active = true; app.active = true;
app.appName = QStringLiteral("Login"); app.appName = QStringLiteral("Login");
app.pluginInfos = plugins; app.pluginInfos = plugins;
LtsSession::DdsConnectionParams connParams; LtsSession::DdsConnectionParams connParams;
connParams.domainId = LtsSessionData::LtsSessionData::getInstance()->getDomainIdPreset(); connParams.domainId = LtsSessionData::LtsSessionData::getInstance()->getDomainIdPreset();
connParams.tcpConnectionUrl = LtsSessionData::LtsSessionData::getInstance()->getTcpConnectionUrl(); connParams.tcpConnectionUrl = LtsSessionData::LtsSessionData::getInstance()->getTcpConnectionUrl();
connParams.partitionType = IDL::PartitionType::Global; connParams.partitionType = IDL::PartitionType::Global;
connParams.partitionId = 0; connParams.partitionId = 0;
m_loginApp = new LtsPluginManager::LtsPluginManager(); m_loginApp = new LtsPluginManager::LtsPluginManager();
bool result = m_loginApp->startApp(app, true, connParams); bool result = m_loginApp->startApp(app, true, connParams);
if (!result) if (!result)
{
qWarning() << "no login plugin - probably an offline project";
emit signalLoginDone();
return;
}
connect(m_loginApp, &LtsPluginManager::LtsPluginManager::signalInitializationFinished,
this, [this]()
{
disconnect(m_loginApp, &LtsPluginManager::LtsPluginManager::signalInitializationFinished,
this, nullptr);
LtsSession::LtsSession *session = getAdminSession();
if (!session)
{ {
qCritical() << "I cannot find the Admin Session :( - abort!"; qWarning() << "no login plugin - probably an offline project";
QMessageBox::critical(nullptr, tr("Error loading login app"), tr("Could not load login app - abort.")); emit signalLoginDone();
abort(); return;
} }
if (session->isInitializationDone()) connect(m_loginApp, &LtsPluginManager::LtsPluginManager::signalInitializationFinished, this, [this]() {
QMetaObject::invokeMethod(this, &LtsLogin::slotLoginDone); disconnect(m_loginApp, &LtsPluginManager::LtsPluginManager::signalInitializationFinished, this, nullptr);
else
connect(session, &LtsSession::LtsSession::signalDoneInitializingSession,
this, &LtsLogin::slotLoginDone, Qt::UniqueConnection);
});
}
LtsSession::LtsSession* session = getAdminSession();
if (!session)
{
qCritical() << "I cannot find the Admin Session :( - abort!";
QMessageBox::critical(nullptr, tr("Error loading login app"), tr("Could not load login app - abort."));
abort();
}
if (session->isInitializationDone())
QMetaObject::invokeMethod(this, &LtsLogin::slotLoginDone);
else
connect(session, &LtsSession::LtsSession::signalDoneInitializingSession, this, &LtsLogin::slotLoginDone,
Qt::UniqueConnection);
});
}
void LtsLogin::slotLoginDone() void LtsLogin::slotLoginDone()
{ {
LtsSession::LtsSession *session = getAdminSession(); LtsSession::LtsSession* session = getAdminSession();
if (session != nullptr) if (session != nullptr)
{
disconnect(session, &LtsSession::LtsSession::signalDoneInitializingSession,
this, &LtsLogin::slotLoginDone);
if (session->getDtc<AssetManagement::DataInterface>(m_asmDtc))
{ {
m_asmDtc->enableWorkstationLogout(); disconnect(session, &LtsSession::LtsSession::signalDoneInitializingSession, this, &LtsLogin::slotLoginDone);
connect(m_asmDtc.get(), &AssetManagement::Interface::Dtc::workstationLogoutChanged,
this, &LtsLogin::slotLogoutShutdown); if (session->getDtc<AssetManagement::DataInterface>(m_asmDtc))
{
m_asmDtc->enableWorkstationLogout();
connect(m_asmDtc.get(), &AssetManagement::Interface::Dtc::workstationLogoutChanged, this,
&LtsLogin::slotLogoutShutdown);
}
else
qWarning() << "LtsLogin: no asm dtc, no remote logout/shutdown!";
} }
else else
qWarning() << "LtsLogin: no asm dtc, no remote logout/shutdown!"; {
} qCritical() << "LtsLogin: no admin session for login!!";
else QMessageBox::critical(nullptr, tr("Login error"), tr("Could not finalize login - abort."));
{ abort();
qCritical() << "LtsLogin: no admin session for login!!"; }
QMessageBox::critical(nullptr, tr("Login error"), tr("Could not finalize login - abort."));
abort();
}
emit signalLoginDone(); emit signalLoginDone();
} }
void LtsLogin::showLogoutInformationDialog(AssetManagement::ShutdownAction action) void LtsLogin::showLogoutInformationDialog(AssetManagement::ShutdownAction action)
{ {
LogoutInformationDialog *lid = new LogoutInformationDialog(logoutShutdownTimeout, action, nullptr); LogoutInformationDialog* lid = new LogoutInformationDialog(logoutShutdownTimeout, action, nullptr);
connect(lid, &LogoutInformationDialog::accepted, connect(lid, &LogoutInformationDialog::accepted, this, [this, action]() {
this, [this, action]() m_shutdownAction = action;
{ m_isInLogoutDialog = false;
m_shutdownAction = action; emit signalLogout();
m_isInLogoutDialog = false; });
emit signalLogout();
});
connect(lid, &LogoutInformationDialog::rejected, connect(lid, &LogoutInformationDialog::rejected, this, [this]() { m_isInLogoutDialog = false; });
this, [this]()
{
m_isInLogoutDialog = false;
});
lid->show(); lid->show();
} }
void LtsLogin::slotLogoutShutdown(const AssetManagement::WorkstationLogout& data, DataModification modType)
void LtsLogin::slotLogoutShutdown(const AssetManagement::WorkstationLogout &data, DataModification modType)
{ {
if (m_isInLogoutDialog) if (m_isInLogoutDialog)
return; return;
if (m_asmDtc == nullptr || modType != DataModification::eAdded) if (m_asmDtc == nullptr || modType != DataModification::eAdded)
return; return;
if (!m_asmDtc->isAssetEnabled()) if (!m_asmDtc->isAssetEnabled())
m_asmDtc->enableAsset(); m_asmDtc->enableAsset();
for (int id : data.ids()) for (int id : data.ids())
{
if (QString::fromStdString(m_asmDtc->asset(id).name()).compare(LtsSession::LtsSession::workstationName(), Qt::CaseInsensitive) == 0)
{ {
m_isInLogoutDialog = true; if (QString::fromStdString(m_asmDtc->asset(id).name())
showLogoutInformationDialog(data.shutdownAction()); .compare(LtsSession::LtsSession::workstationName(), Qt::CaseInsensitive) == 0)
break; {
m_isInLogoutDialog = true;
showLogoutInformationDialog(data.shutdownAction());
break;
}
} }
}
} }
LtsSession::LtsSession* LtsLogin::getAdminSession()
LtsSession::LtsSession *LtsLogin::getAdminSession()
{ {
return m_loginApp->m_sessionManager->getSession(IDL::PartitionType::Global, 0); return m_loginApp->m_sessionManager->getSession(IDL::PartitionType::Global, 0);
} }
void LtsLogin::logoff() void LtsLogin::logoff()
{ {
if (m_loginApp == nullptr) if (m_loginApp == nullptr)
{
qCritical() << "LtsLogin::logoff: missing login app!";
return;
}
LtsSession::LtsSession *datSession = getAdminSession();
if (!datSession)
{
qCritical() << "LtsLogin::logoff: no admin session for logout!";
abort();
}
int operatorId = LtsSessionData::LtsSessionData::getInstance()->getOperatorId();
int workstationId = LtsSessionData::LtsSessionData::getInstance()->getWorkstationId();
LtsSessionData::LtsSessionData::getInstance()->clear();
std::shared_ptr<OperatorManagement::Interface::Ftc> opmFtc;
if (operatorId == -1 ||
!datSession->getFtc<OperatorManagement::DataInterface>(opmFtc)
)
{
}
else
{
try
{ {
qCritical() << "LtsLogin::logoff: missing login app!";
LtsUtils::OperatorSettings *os = LtsUtils::OperatorSettings::getInstance(); return;
const QByteArray settings = os->exportSettings();
const auto vec(LtsUtils::convert<std::vector<uint8_t>>(settings));
os->clear();
opmFtc->operatorGetSetSettingsRequest(OperatorManagement::OperatorGetSetSettingsRequest(operatorId, vec));
}
catch (const std::runtime_error &err)
{
qCritical() << "Saving operator settings failed!" << err.what();
} }
LtsSession::LtsSession* datSession = getAdminSession();
std::shared_ptr<SituationReplayManagement::ForeignDataInterface> srmIfc; if (!datSession)
if (datSession->getForeignDataInterface<SituationReplayManagement::DataInterface>(srmIfc))
{ {
try qCritical() << "LtsLogin::logoff: no admin session for logout!";
{ abort();
srmIfc->removeReplayPartitionsWorkstation(workstationId);
}
catch (const std::runtime_error &err)
{
qCritical() << "Removing reply partitions from this workstation failed!" << err.what();
}
try
{
srmIfc->removeReplayPartitionsOperator(operatorId);
}
catch (const std::runtime_error &err)
{
qCritical() << "Removing reply partitions from this operator failed!" << err.what();
}
} }
int operatorId = LtsSessionData::LtsSessionData::getInstance()->getOperatorId();
int workstationId = LtsSessionData::LtsSessionData::getInstance()->getWorkstationId();
try LtsSessionData::LtsSessionData::getInstance()->clear();
std::shared_ptr<OperatorManagement::Interface::Ftc> opmFtc;
if (operatorId == -1 || !datSession->getFtc<OperatorManagement::DataInterface>(opmFtc))
{ {
opmFtc->operatorLogoutRequest(OperatorManagement::OperatorLogoutRequest(operatorId));
} }
catch (const std::runtime_error &err) else
{ {
qCritical() << "Logout failed!" << err.what(); try
{
LtsUtils::OperatorSettings* os = LtsUtils::OperatorSettings::getInstance();
const QByteArray settings = os->exportSettings();
const auto vec(LtsUtils::convert<std::vector<uint8_t>>(settings));
os->clear();
opmFtc->operatorGetSetSettingsRequest(OperatorManagement::OperatorGetSetSettingsRequest(operatorId, vec));
}
catch (const std::runtime_error& err)
{
qCritical() << "Saving operator settings failed!" << err.what();
}
std::shared_ptr<SituationReplayManagement::ForeignDataInterface> srmIfc;
if (datSession->getForeignDataInterface<SituationReplayManagement::DataInterface>(srmIfc))
{
try
{
srmIfc->removeReplayPartitionsWorkstation(workstationId);
}
catch (const std::runtime_error& err)
{
qCritical() << "Removing reply partitions from this workstation failed!" << err.what();
}
try
{
srmIfc->removeReplayPartitionsOperator(operatorId);
}
catch (const std::runtime_error& err)
{
qCritical() << "Removing reply partitions from this operator failed!" << err.what();
}
}
try
{
opmFtc->operatorLogoutRequest(OperatorManagement::OperatorLogoutRequest(operatorId));
}
catch (const std::runtime_error& err)
{
qCritical() << "Logout failed!" << err.what();
}
} }
m_loginApp->deleteLater();
m_loginApp = nullptr;
} QString cmd;
switch (m_shutdownAction.underlying())
m_loginApp->deleteLater(); {
m_loginApp = nullptr; case AssetManagement::ShutdownAction_def::Shutdown:
QString cmd;
switch (m_shutdownAction.underlying())
{
case AssetManagement::ShutdownAction_def::Shutdown:
#ifdef LTS_DEBUG #ifdef LTS_DEBUG
cmd = QStringLiteral("xeyes"); cmd = QStringLiteral("xeyes");
#else #else
cmd = QStringLiteral("systemctl poweroff"); cmd = QStringLiteral("systemctl poweroff");
#endif #endif
break; break;
case AssetManagement::ShutdownAction_def::Reboot: case AssetManagement::ShutdownAction_def::Reboot:
#ifdef LTS_DEBUG #ifdef LTS_DEBUG
cmd = QStringLiteral("kcalc"); cmd = QStringLiteral("kcalc");
#else #else
cmd = QStringLiteral("systemctl reboot"); cmd = QStringLiteral("systemctl reboot");
#endif #endif
break; break;
case AssetManagement::ShutdownAction_def::Logout: case AssetManagement::ShutdownAction_def::Logout:
case AssetManagement::ShutdownAction_def::NoAction: case AssetManagement::ShutdownAction_def::NoAction:
emit signalLogoffDone(); emit signalLogoffDone();
break; break;
} }
if (!cmd.isEmpty()) if (!cmd.isEmpty())
{ {
QProcess::startDetached(cmd); QProcess::startDetached(cmd);
QCoreApplication::quit(); QCoreApplication::quit();
} }
} }
} } // namespace LtsLogin
+33 -31
View File
@@ -1,27 +1,26 @@
#pragma once #pragma once
#include <Plugins/AssetManagement/asm_data_plugin_interface.h>
#include <ltslogin_export.h>
#include <Plugins/OperatorManagement/opm_data_plugin_interface.h> #include <Plugins/OperatorManagement/opm_data_plugin_interface.h>
#include <Plugins/SituationReplayManagement/srm_data_plugin_interface.h> #include <Plugins/SituationReplayManagement/srm_data_plugin_interface.h>
#include <Plugins/AssetManagement/asm_data_plugin_interface.h>
#include <QObject> #include <QObject>
#include <ltslogin_export.h>
namespace LtsPluginManager namespace LtsPluginManager
{ {
class LtsPluginManager; class LtsPluginManager;
} }
namespace LtsUtils namespace LtsUtils
{ {
class RequestHelper; class RequestHelper;
} }
namespace LtsSession namespace LtsSession
{ {
class LtsSession; class LtsSession;
} }
namespace DeveloperTools namespace DeveloperTools
{ {
class DevDialog; class DevDialog;
@@ -32,38 +31,41 @@ namespace LtsLogin
class LTSLOGIN_EXPORT LtsLogin : public QObject class LTSLOGIN_EXPORT LtsLogin : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
LtsLogin(); LtsLogin();
~LtsLogin(); ~LtsLogin();
void login(); void login();
void logoff(); void logoff();
void setLoginPlugin(const QString &loginPluginIid) { m_loginPluginIid = loginPluginIid; }
private: void setLoginPlugin(const QString& loginPluginIid)
friend class DeveloperTools::DevDialog; {
m_loginPluginIid = loginPluginIid;
}
LtsSession::LtsSession *getAdminSession(); private:
void showLogoutInformationDialog(AssetManagement::ShutdownAction action); friend class DeveloperTools::DevDialog;
LtsPluginManager::LtsPluginManager *m_loginApp; LtsSession::LtsSession* getAdminSession();
AssetManagement::ShutdownAction m_shutdownAction; void showLogoutInformationDialog(AssetManagement::ShutdownAction action);
std::shared_ptr<AssetManagement::Interface::Dtc> m_asmDtc;
QString m_loginPluginIid;
bool m_isInLogoutDialog;
private slots: LtsPluginManager::LtsPluginManager* m_loginApp;
void slotLoginDone(); AssetManagement::ShutdownAction m_shutdownAction;
void slotLogoutShutdown(const AssetManagement::WorkstationLogout &data, DataModification modType); std::shared_ptr<AssetManagement::Interface::Dtc> m_asmDtc;
QString m_loginPluginIid;
bool m_isInLogoutDialog;
signals: private slots:
void signalLogout(); void slotLoginDone();
void signalStopBlock(); void slotLogoutShutdown(const AssetManagement::WorkstationLogout& data, DataModification modType);
void signalLoginDone();
void signalLogoffDone();
signals:
void signalLogout();
void signalStopBlock();
void signalLoginDone();
void signalLogoffDone();
}; };
} } // namespace LtsLogin
Loaded 100 of 848 files, more files were not shown because too many files have changed in this diff. Show more