diff --git a/ci/Dockerfile.ci b/ci/Dockerfile.ci index 07023e5ec..741fa3217 100644 --- a/ci/Dockerfile.ci +++ b/ci/Dockerfile.ci @@ -18,9 +18,50 @@ RUN apt-get update && \ qt6-base-dev \ qt6-base-dev-tools \ qt6-tools-dev \ - qt6-tools-dev-tools && \ + qt6-tools-dev-tools \ + qt6-svg-dev \ + qt6-websockets-dev \ + qt6-serialport-dev \ + qt6-multimedia-dev \ + qt6-declarative-dev \ + libpoppler-qt6-dev \ + libpq-dev \ + libbz2-dev \ + libboost-all-dev \ + libxml2-dev \ + libssl-dev \ + libcurl4-openssl-dev && \ rm -rf /var/lib/apt/lists/* +# Install Log4Qt for Qt6 +RUN git clone --depth 1 https://github.com/MEONMedical/Log4Qt.git /tmp/log4qt && \ + cd /tmp/log4qt && \ + mkdir -p build && cd build && \ + cmake -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_CXX_STANDARD=20 \ + -DCMAKE_CXX_EXTENSIONS=OFF \ + -DCMAKE_PREFIX_PATH="/usr" \ + -DCMAKE_INSTALL_PREFIX="/usr/local" \ + -DBUILD_SHARED_LIBS=ON .. && \ + cmake --build . -- -j$(nproc) && \ + cmake --install . && \ + rm -rf /tmp/log4qt + +# Create minimal CMake config for Log4Qt +RUN mkdir -p /usr/local/lib/cmake/Log4Qt && \ + cat > /usr/local/lib/cmake/Log4Qt/Log4QtConfig.cmake << 'EOF' +if (NOT TARGET Log4Qt::log4qt) + add_library(Log4Qt::log4qt UNKNOWN IMPORTED) + set_target_properties(Log4Qt::log4qt PROPERTIES + IMPORTED_LOCATION "/usr/local/lib/liblog4qt.so" + INTERFACE_INCLUDE_DIRECTORIES "/usr/local/include" + ) +endif() +set(Log4Qt_FOUND TRUE CACHE INTERNAL "Log4Qt found by package config") +set(Log4Qt_INCLUDE_DIRS "/usr/local/include" CACHE INTERNAL "Log4Qt include dir") +set(Log4Qt_LIBRARIES "/usr/local/lib/liblog4qt.so" CACHE INTERNAL "Log4Qt library") +EOF + # Set Qt platform for headless testing ENV QT_QPA_PLATFORM=offscreen diff --git a/ci/install-rti-in-docker.sh b/ci/install-rti-in-docker.sh new file mode 100755 index 000000000..dd05fc8f1 --- /dev/null +++ b/ci/install-rti-in-docker.sh @@ -0,0 +1,36 @@ +#!/bin/bash +# Install RTI Connext into existing Docker image + +set -e + +RTI_SOURCE="/home/torsten/swy/sandbox/external/rti_connext_dds-7.7.0" +BASE_IMAGE="lifemaps/ci-cpp:latest" +TARGET_IMAGE="lifemaps/ci-cpp:rti" + +echo "Step 1: Create container from base image..." +CONTAINER_ID=$(docker create --name rti-install-temp $BASE_IMAGE /bin/bash) + +echo "Step 2: Copy RTI Connext into container..." +docker cp "$RTI_SOURCE" "$CONTAINER_ID:/opt/rti_connext_dds-7.7.0" + +echo "Step 3: Commit container as new image..." +docker commit $CONTAINER_ID $TARGET_IMAGE + +echo "Step 4: Remove temporary container..." +docker rm $CONTAINER_ID + +echo "Step 5: Set environment variables in image..." +docker run --rm $TARGET_IMAGE /bin/bash -c ' +echo "RTI Connext installed successfully" +ls -la /opt/rti_connext_dds-7.7.0 | head -10 +' + +echo "" +echo "RTI Connext installed in image: $TARGET_IMAGE" +echo "To use this image, set environment variables:" +echo " docker run -e RTI_CONNEXT_HOME=/opt/rti_connext_dds-7.7.0 \\" +echo " -e NDDSHOME=/opt/rti_connext_dds-7.7.0 \\" +echo " -e PATH=/opt/rti_connext_dds-7.7.0/bin:\$PATH \\" +echo " -e LD_LIBRARY_PATH=/opt/rti_connext_dds-7.7.0/lib/x64Linux4gcc7.3.0:\$LD_LIBRARY_PATH \\" +echo " -e CMAKE_PREFIX_PATH=/opt/rti_connext_dds-7.7.0/lib/cmake:\$CMAKE_PREFIX_PATH \\" +echo " $TARGET_IMAGE" \ No newline at end of file diff --git a/qt6-after/qt6-migrated-legatus/CMakeLists.txt b/qt6-after/qt6-migrated-legatus/CMakeLists.txt index 248eac34b..e415f9ef0 100755 --- a/qt6-after/qt6-migrated-legatus/CMakeLists.txt +++ b/qt6-after/qt6-migrated-legatus/CMakeLists.txt @@ -75,6 +75,10 @@ OPTION(BUILD_PLUGINS_PARTICIPANT_ORG_CHART "Build ParticipantOrgChart (requires OPTION(BUILD_PLUGINS_MSDL "Build MSDL module (requires Qt6 XmlPatterns)" OFF) OPTION(BUILD_PLUGINS_SAAB "Build Saab module (requires Qt6 XmlPatterns)" OFF) OPTION(BUILD_RTI "Build RTI Connext DDS dependent modules" OFF) +OPTION(BUILD_FILTERMANAGEMENT "Build FilterManagement plugins (temporarily disabled for migration)" OFF) +OPTION(BUILD_CODIFICATION "Build CodificationManagement plugins (requires KDReports)" OFF) +OPTION(BUILD_GRANTLEE "Build CodeGen Grantlee templates (requires Grantlee5/Qt5)" OFF) +OPTION(BUILD_LTSWEBSOCKET "Build LtsWebSocket module (requires NGLLogger)" OFF) IF(WIN32) SET(EXTERNAL_LIBRARY_DIR "C:/Development/Projekte/SituationMap/ExtFw" CACHE STRING "Library dir with all external dependencies") @@ -113,21 +117,12 @@ SET(CMAKE_AUTOMOC TRUE) SET(CMAKE_AUTOUIC TRUE) SET(QT_USE_IMPORTED_TARGETS TRUE) # Prefer Qt6, fallback to Qt5. Create Qt6::*-aliases when Qt6 is found so existing CMakeLists continue to work. -# Try to detect Qt6 with a minimal check and then create aliases/placeholders for components used across the project. -# Prefer Qt6, fallback to Qt5. Create Qt6::* aliases only when the corresponding -# Qt6:: component target exists. Avoid creating IMPORTED placeholder targets which -# have no LOCATION and later inject 'NOTFOUND' into autogen timestamp deps. -# Find minimal Qt6 Core first, then probe for other components (non-fatal). -find_package(Qt6 6.8 COMPONENTS Core QUIET) +# Find Qt6 with all required components in one call to ensure all targets are properly created +find_package(Qt6 6.8 COMPONENTS Concurrent Core Gui Location LinguistTools Network OpenGL PrintSupport + Sensors Multimedia Sql Svg SerialPort Test UiTools WebSockets WebEngineCore WebEngineWidgets + Widgets Xml XmlPatterns QUIET) if(Qt6_FOUND) message(STATUS "Found Qt6: ${Qt6Core_VERSION}") - set(_qlist Concurrent Core Gui Location LinguistTools Network OpenGL PrintSupport - Sensors Multimedia Sql Svg SerialPort Test UiTools WebSockets WebEngineCore WebEngineWidgets - Widgets Xml XmlPatterns) - foreach(_comp ${_qlist}) - # Probe for each component (non-fatal). - find_package(Qt6 COMPONENTS ${_comp} QUIET) - endforeach() # Map version variable for compatibility if available if(Qt6Core_VERSION) set(Qt5Core_VERSION ${Qt6Core_VERSION} CACHE INTERNAL "Compatibility Qt5Core_VERSION mapped from Qt6") @@ -146,12 +141,12 @@ if(Qt6_FOUND) endif() endif() else() - find_package(Qt6 5.9.0 COMPONENTS Concurrent Core Gui Location LinguistTools - Network OpenGL PrintSupport Sensors Multimedia + find_package(Qt6 5.9.0 COMPONENTS Concurrent Core Gui LinguistTools + Network OpenGL PrintSupport Multimedia Sql Svg SerialPort Test UiTools WebSockets - WebEngineCore WebEngineWidgets Widgets - Xml XmlPatterns + Widgets Xml REQUIRED) + find_package(Qt6 COMPONENTS Location Sensors WebEngineCore WebEngineWidgets XmlPatterns OPTIONAL) MESSAGE(STATUS "Qt version is ${Qt6Core_VERSION}") endif() diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/CMakeLists.txt b/qt6-after/qt6-migrated-legatus/Lts/Common/CMakeLists.txt index 105f5cc3e..d7c3c455c 100755 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/CMakeLists.txt +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/CMakeLists.txt @@ -36,7 +36,9 @@ ADD_SUBDIRECTORY(LtsTimeline) ADD_SUBDIRECTORY(LtsPrinting) ADD_SUBDIRECTORY(LtsSerialPortQuerry) ADD_SUBDIRECTORY(LtsScriptTimeline) +IF(BUILD_LTSWEBSOCKET) ADD_SUBDIRECTORY(LtsWebSocket) +ENDIF() ADD_SUBDIRECTORY(LtsProjectionWorkstation) ADD_SUBDIRECTORY(LtsVirtualKeyboard) ADD_SUBDIRECTORY(PluginInterfaces) diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/CMakeLists.txt b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/CMakeLists.txt index eb3fa088d..023a98901 100755 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/CMakeLists.txt +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/CMakeLists.txt @@ -5,7 +5,11 @@ # FIND_PACKAGE(RTI) -FIND_PACKAGE(Grantlee5 REQUIRED COMPONENTS Templates) + +# Grantlee5 is Qt5-based and optional for Qt6 migration +IF(BUILD_GRANTLEE) + FIND_PACKAGE(Grantlee5 REQUIRED COMPONENTS Templates) +ENDIF() NGL_ADD_LIBRARY2(ALL codegen_base SHARED codegen_export.h @@ -45,7 +49,8 @@ else() endif() NGL_INSTALL_TARGET(codegen_base) -if (TARGET Grantlee5::Templates) +# Grantlee5 is Qt5-based and optional for Qt6 migration +IF(BUILD_GRANTLEE AND TARGET Grantlee5::Templates) NGL_ADD_LIBRARY(ALL codegen_grantlee STATIC CppTopicGeneratorGrantlee.cpp CppTopicGeneratorGrantlee.h @@ -111,12 +116,8 @@ if (TARGET Grantlee5::Templates) PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/../ ) -else() - message(STATUS "Grantlee not found; skipping codegen_grantlee target") -endif() -# Smoke-test: parse all .grantlee templates in this directory to detect parse/render regressions -if (TARGET Grantlee5::Templates) + # Smoke-test: parse all .grantlee templates in this directory to detect parse/render regressions find_package(Qt6 COMPONENTS Core QUIET) if (Qt6_FOUND) set(QTCORE_TARGET Qt6::Core) @@ -128,30 +129,32 @@ if (TARGET Grantlee5::Templates) add_executable(grantlee_parser_smoke tests/GrantleeParserSmoke.cpp) target_link_libraries(grantlee_parser_smoke PRIVATE Grantlee5::Templates ${QTCORE_TARGET}) add_test(NAME GrantleeParserSmoke COMMAND grantlee_parser_smoke ${CMAKE_CURRENT_SOURCE_DIR}) -endif() -NGL_ADD_EXECUTABLE(ALL ngl_codegen - main_grantlee.cpp -) -NGL_TARGET_LINK_LIBRARIES(ngl_codegen - codegen_grantlee - LtsCommandLineParser - nglcoreapplication - Qt6::Core -) + NGL_ADD_EXECUTABLE(ALL ngl_codegen + main_grantlee.cpp + ) + NGL_TARGET_LINK_LIBRARIES(ngl_codegen + codegen_grantlee + LtsCommandLineParser + nglcoreapplication + Qt6::Core + ) -NGL_WRAP_UI(codegen_gui_uics + NGL_WRAP_UI(codegen_gui_uics + main_grantlee_gui.ui + ) + NGL_ADD_EXECUTABLE(WS AAR SV NO_TRANSLATION codegen_gui + ${codegen_gui_uics} + main_grantlee_gui.cpp main_grantlee_gui.ui -) -NGL_ADD_EXECUTABLE(WS AAR SV NO_TRANSLATION codegen_gui - ${codegen_gui_uics} - main_grantlee_gui.cpp - main_grantlee_gui.ui -) -NGL_TARGET_LINK_LIBRARIES(codegen_gui - codegen_grantlee - LtsCommandLineParser - nglapplication - Qt6::Widgets - Grantlee5::Templates -) + ) + NGL_TARGET_LINK_LIBRARIES(codegen_gui + codegen_grantlee + LtsCommandLineParser + nglapplication + Qt6::Widgets + Grantlee5::Templates + ) +ELSE() + message(STATUS "BUILD_GRANTLEE disabled or Grantlee not found; skipping codegen_grantlee, ngl_codegen, and codegen_gui targets") +ENDIF() diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/CMakeLists.txt b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/CMakeLists.txt index 35e03b8d5..7781d4adf 100755 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/CMakeLists.txt +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/CMakeLists.txt @@ -24,6 +24,7 @@ endif() NGL_TARGET_INCLUDE_DIRECTORIES(LtsCoordTrans PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/../ + ${CMAKE_CURRENT_BINARY_DIR} ) SET(ltsCoordWidget_SRCS @@ -48,6 +49,7 @@ NGL_TARGET_INCLUDE_DIRECTORIES(ltsCoordWidget PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/../ ${CMAKE_CURRENT_SOURCE_DIR}/../LtsUtils/LtsUtilsCore + ${CMAKE_CURRENT_BINARY_DIR} ) IF(TARGET LtsCoordTrans) diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget.h old mode 100755 new mode 100644 index f72e042a3..51b3803f5 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget.h @@ -1,10 +1,9 @@ #pragma once -#include - -#include "sv_export.h" #include +#include +#include #include class QToolButton; @@ -12,68 +11,57 @@ class QToolButton; namespace LtsCoordWidget { class LtsCoordInputWidgetHandler; + class LTSCOORDWIDGET_EXPORT LtsCoordWidget : public QWidget { - Q_OBJECT -public: - enum class DisplayType - { - MGRS5, - MGRS7, - UTM, - WGS84, - MGRS = DisplayType::MGRS5 - }; - Q_ENUM(DisplayType) - Q_PROPERTY(DisplayType displayType READ displayType WRITE setDisplayType) - Q_PROPERTY(bool withResetButton READ withResetButton WRITE setWithResetButton) - Q_PROPERTY(bool showToolTip READ showToolTip WRITE setShowToolTip) - Q_PROPERTY(bool mgrsSquareEditable READ mgrsSquareEditable WRITE setMgrsSquareEditable) + Q_OBJECT + public: + enum class DisplayType { MGRS5, MGRS7, UTM, WGS84, MGRS = DisplayType::MGRS5 }; + Q_ENUM(DisplayType) + Q_PROPERTY(DisplayType displayType READ displayType WRITE setDisplayType) + Q_PROPERTY(bool withResetButton READ withResetButton WRITE setWithResetButton) + Q_PROPERTY(bool showToolTip READ showToolTip WRITE setShowToolTip) + Q_PROPERTY(bool mgrsSquareEditable READ mgrsSquareEditable WRITE setMgrsSquareEditable) - + explicit LtsCoordWidget(QWidget* parent = nullptr) : LtsCoordWidget(LtsCoordWidget::DisplayType::MGRS, parent) {} - explicit LtsCoordWidget(QWidget *parent = nullptr) - : LtsCoordWidget(LtsCoordWidget::DisplayType::MGRS, parent) - {} + explicit LtsCoordWidget(DisplayType dt, QWidget* parent = nullptr); - + QPointF coordinate() const; + DisplayType displayType() const; + bool withResetButton() const; + bool showToolTip() const; + bool mgrsSquareEditable() const; + bool event(QEvent* event) override; + public Q_SLOTS: - explicit LtsCoordWidget(DisplayType dt, QWidget *parent = nullptr); + void setCoordinate(const QPointF& geoCoord, bool bUseAsDefaultValue = true); + void setCoordinate(double lon, double lat, bool bUseAsDefaultValue = true); + void setDisplayType(LtsCoordWidget::DisplayType dt); + void setWithResetButton(bool bWith); + void setShowToolTip(bool bShow); + void setMgrsSquareEditable(bool bEditable); + void setWithSurroundingMgrsSquares(bool bEnable); + void setMgrsSquares(const QVector& geoCoords); + void clear(); - QPointF coordinate() const; - DisplayType displayType() const; - bool withResetButton() const; - bool showToolTip() const; - bool mgrsSquareEditable() const; - bool event(QEvent *event) override; -public Q_SLOTS: - + Q_SIGNALS: + void coordinateChanged(const QPointF& newGeoCoord); + void invalidCoordinate(); - void setCoordinate(const QPointF &geoCoord, bool bUseAsDefaultValue = true); - void setCoordinate(double lon, double lat, bool bUseAsDefaultValue = true); - void setDisplayType(LtsCoordWidget::DisplayType dt); - void setWithResetButton(bool bWith); - void setShowToolTip(bool bShow); - void setMgrsSquareEditable(bool bEditable); - void setWithSurroundingMgrsSquares(bool bEnable); - void setMgrsSquares(const QVector &geoCoords); - void clear(); + private: + void rebuildUi(); + void updateToolTip(); + private Q_SLOTS: + void onResetToDefaultCoordinate(); -Q_SIGNALS: - void coordinateChanged(const QPointF &newGeoCoord); - void invalidCoordinate(); -private: - void rebuildUi(); - void updateToolTip(); -private Q_SLOTS: - void onResetToDefaultCoordinate(); -private: - bool m_bWithResetButton = false; - bool m_bShowToolTip = true; - bool m_bMgrsSquareEditable = false; - LtsCoordWidget::DisplayType m_displayType = LtsCoordWidget::DisplayType::MGRS; - LtsCoordInputWidgetHandler *m_inputWidgetHandler = nullptr; - QPointF m_coordinate; - QPointF m_defaultCoordinate; + private: + bool m_bWithResetButton = false; + bool m_bShowToolTip = true; + bool m_bMgrsSquareEditable = false; + LtsCoordWidget::DisplayType m_displayType = LtsCoordWidget::DisplayType::MGRS; + LtsCoordInputWidgetHandler* m_inputWidgetHandler = nullptr; + QPointF m_coordinate; + QPointF m_defaultCoordinate; }; -} +} // namespace LtsCoordWidget diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPrinting/CMakeLists.txt b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPrinting/CMakeLists.txt index 45e3c2efa..ecbe99528 100755 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPrinting/CMakeLists.txt +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPrinting/CMakeLists.txt @@ -15,7 +15,7 @@ SET(SRCS printing.h ) -if (KDReports_FOUND AND BUILD_RTI) +if (KDReports_FOUND AND BUILD_CODIFICATION) NGL_ADD_LIBRARY2(WS LtsPrinting SHARED ${SRCS}) NGL_TARGET_INCLUDE_DIRECTORIES(LtsPrinting PUBLIC diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsSettings/CMakeLists.txt b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsSettings/CMakeLists.txt index 91eab09e9..cf0e00576 100755 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsSettings/CMakeLists.txt +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsSettings/CMakeLists.txt @@ -13,6 +13,7 @@ NGL_ADD_LIBRARY2(ALL LtsUtilsSettings SHARED ${SRCS}) NGL_TARGET_INCLUDE_DIRECTORIES(LtsUtilsSettings PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/../ + ${CMAKE_CURRENT_BINARY_DIR} ) NGL_TARGET_LINK_LIBRARIES(LtsUtilsSettings diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_connection.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_connection.cpp old mode 100755 new mode 100644 index 1ddecedf0..12b02b300 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_connection.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_connection.cpp @@ -2,82 +2,84 @@ #include "client_connection.h" +#include #include namespace LtsWebSocket { -ClientConnection::ClientConnection(QWebSocket *socket, QObject *parent) - : QThread(parent) - , m_socket(socket ? socket : new QWebSocket) +ClientConnection::ClientConnection(QWebSocket* socket, QObject* parent) + : QThread(parent), m_logger(NGL::NGLLoggerBootstrap::getLogger()), m_socket(socket ? socket : new QWebSocket) { } ClientConnection::~ClientConnection() { - DEBUG_LOG(m_logger) << "Thread closed" << this; - delete m_socket; - qDeleteAll(m_messageQueue); + DEBUG_LOG(m_logger) << "Thread closed" << this; + delete m_socket; + qDeleteAll(m_messageQueue); } bool ClientConnection::init() { - if (m_socket == nullptr) - { - ERROR_LOG(m_logger) << "Initialisation failed due to an invalid socket"; - return false; - } + if (m_socket == nullptr) + { + ERROR_LOG(m_logger) << "Initialisation failed due to an invalid socket"; + return false; + } - DEBUG_LOG(m_logger) << "Started new thread" << this; - connect(m_socket, &QWebSocket::textMessageReceived, this, &ClientConnection::onNewTextMessageFromSocket, Qt::DirectConnection); - connect(m_socket, &QWebSocket::connected, this, &ClientConnection::sendMessagesFromQueue); - connect(m_socket, &QWebSocket::disconnected, this, &ClientConnection::onSocketDisconnect); + DEBUG_LOG(m_logger) << "Started new thread" << this; + connect(m_socket, &QWebSocket::textMessageReceived, this, &ClientConnection::onNewTextMessageFromSocket, + Qt::DirectConnection); + connect(m_socket, &QWebSocket::connected, this, &ClientConnection::sendMessagesFromQueue); + connect(m_socket, &QWebSocket::disconnected, this, &ClientConnection::onSocketDisconnect); - return true; + return true; } -void ClientConnection::addReply(ReplyMessage *message) +void ClientConnection::addReply(ReplyMessage* message) { - if (!m_socket || m_socket->state() != QAbstractSocket::ConnectedState) - { - m_messageQueue.enqueue(message); - DEBUG_LOG(m_logger) << "Adding message to queue, size: " << m_messageQueue.size(); - return; - } - const QString msg(message->toJsonString()); - DEBUG_LOG(m_logger) << "Sending message: " << msg ; - m_socket->sendTextMessage(msg); - delete message; + if (!m_socket || m_socket->state() != QAbstractSocket::ConnectedState) + { + m_messageQueue.enqueue(message); + DEBUG_LOG(m_logger) << "Adding message to queue, size: " << m_messageQueue.size(); + return; + } + const QString msg(message->toJsonString()); + DEBUG_LOG(m_logger) << "Sending message: " << msg; + m_socket->sendTextMessage(msg); + delete message; } -void ClientConnection::onNewTextMessageFromSocket(const QString &message) +void ClientConnection::onNewTextMessageFromSocket(const QString& message) { - DEBUG_LOG(m_logger) << "Recv msg: " << message << this; - emit newTextMessage(this, message); + DEBUG_LOG(m_logger) << "Recv msg: " << message << this; + emit newTextMessage(this, message); } void ClientConnection::sendMessagesFromQueue() { - INFO_LOG(m_logger) << "Client connected ip: " << m_socket->peerAddress().toString() << ":" << m_socket->peerPort(); + INFO_LOG(m_logger) << "Client connected ip: " << m_socket->peerAddress().toString() << ":" << m_socket->peerPort(); - if (m_socket->state() != QAbstractSocket::ConnectedState) - return; - while (!m_messageQueue.isEmpty()) - { - ReplyMessage *message = m_messageQueue.dequeue(); - const QString msg(message->toJsonString()); - TRACE_LOG(m_logger) << "Send msg: " << msg; - m_socket->sendTextMessage(msg); - delete message; - DEBUG_LOG(m_logger) << "Sent message from queue, new size: " << m_messageQueue.size(); - } + if (m_socket->state() != QAbstractSocket::ConnectedState) + return; + while (!m_messageQueue.isEmpty()) + { + ReplyMessage* message = m_messageQueue.dequeue(); + const QString msg(message->toJsonString()); + TRACE_LOG(m_logger) << "Send msg: " << msg; + m_socket->sendTextMessage(msg); + delete message; + DEBUG_LOG(m_logger) << "Sent message from queue, new size: " << m_messageQueue.size(); + } } void ClientConnection::onSocketDisconnect() { - DEBUG_LOG(m_logger) << "Client disconnected ip: " << m_socket->peerAddress().toString() << ":" << m_socket->peerPort(); - exit(0); - emit disconnected(this); + DEBUG_LOG(m_logger) << "Client disconnected ip: " << m_socket->peerAddress().toString() << ":" + << m_socket->peerPort(); + exit(0); + emit disconnected(this); } -} +} // namespace LtsWebSocket diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_connection.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_connection.h old mode 100755 new mode 100644 index e700812d4..fa84e7b5f --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_connection.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_connection.h @@ -1,69 +1,51 @@ #pragma once -#include - -#include -#include - -#include "reply_message.h" #include "logger.h" #include "ltswebsocketserver_export.h" +#include "reply_message.h" + +#include +#include +#include class QWebSocket; namespace LtsWebSocket { - - -class LTSWEBSOCKETSERVER_EXPORT ClientConnection - : public QThread - , public ReplyHandler +class LTSWEBSOCKETSERVER_EXPORT ClientConnection : public QThread, public ReplyHandler { - Q_OBJECT -public: - + Q_OBJECT + public: + explicit ClientConnection(QWebSocket* socket, QObject* parent = nullptr); - explicit ClientConnection(QWebSocket *socket, QObject *parent = nullptr); + ~ClientConnection(); + bool init(); - + void addReply(ReplyMessage* message) override; - ~ClientConnection(); + QWebSocket* webSocket() + { + return m_socket; + } - + signals: - bool init(); + void newTextMessage(ClientConnection* client, const QString& message); - + void disconnected(ClientConnection* client); - void addReply(ReplyMessage *message) override; + private slots: + void onNewTextMessageFromSocket(const QString& message); + void sendMessagesFromQueue(); + void onSocketDisconnect(); - QWebSocket *webSocket() { return m_socket; } -signals: - - - void newTextMessage(ClientConnection *client, const QString &message); - - - - void disconnected(ClientConnection *client); - - -private slots: - void onNewTextMessageFromSocket(const QString &message); - void sendMessagesFromQueue(); - void onSocketDisconnect(); -private: - - - NGL::INGLLogger &m_logger; - void sendMessages(); - -private: - NGL::INGLLogger &m_logger; - QWebSocket *m_socket; - QQueue m_messageQueue; -}; -} + private: + NGL::INGLLogger& m_logger; + void sendMessages(); + QWebSocket* m_socket; + QQueue m_messageQueue; +}; +} // namespace LtsWebSocket diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_message_factory.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_message_factory.h old mode 100755 new mode 100644 index dd78d7ee3..1d778ac55 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_message_factory.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_message_factory.h @@ -3,67 +3,66 @@ #pragma once #include "client_message.h" -#include "reply_message.h" #include "ltswebsocketcommon_export.h" +#include "reply_message.h" -#include #include +#include namespace NGL { class INGLLogger; } + namespace LtsWebSocket { - - class LTSWEBSOCKETCOMMON_EXPORT AbstractClientMessageFactory { -public: - explicit AbstractClientMessageFactory(NGL::INGLLogger &logger) - : m_logger(logger) - {} + public: + explicit AbstractClientMessageFactory(NGL::INGLLogger& logger) : m_logger(logger) {} - virtual ~AbstractClientMessageFactory() {} + virtual ~AbstractClientMessageFactory() {} - + QJsonParseError parseMessage(const QString& message); - QJsonParseError parseMessage(const QString &message); + virtual AbstractClientMessage* createMessage(ReplyHandler* client, const QString& message) = 0; - + protected: + AbstractClientMessage* checkAttributes(ReplyHandler* client, const QString& message) const; + AbstractClientMessage* checkResult(ReplyHandler* client, const QString& message, + AbstractClientMessage* result) const; - virtual AbstractClientMessage *createMessage(ReplyHandler *client, const QString &message) = 0; - -protected: - AbstractClientMessage *checkAttributes(ReplyHandler *client, - const QString &message) const; - AbstractClientMessage *checkResult(ReplyHandler *client, - const QString &message, - AbstractClientMessage *result) const; -protected: - QString m_type; - int m_typeId; - QString m_uuid; - QJsonValue m_data; -}; + protected: + NGL::INGLLogger& m_logger; + QString m_type; + int m_typeId; + QString m_uuid; + QJsonValue m_data; +}; class PongMessage final : public ReplyMessage { -public: - static QString strPong() { return QStringLiteral("pong"); } - static int idPong() { return 2; } - explicit PongMessage(const QString &payload) - : ReplyMessage(strPong(), idPong(), QString()) - , m_payload(payload) - {} + public: + static QString strPong() + { + return QStringLiteral("pong"); + } - QString toJsonString() const override - { - return m_payload.isEmpty() ? strPong() : QStringLiteral("%1 %2").arg(strPong(), m_payload); - } -private: - QString m_payload; + static int idPong() + { + return 2; + } + + explicit PongMessage(const QString& payload) : ReplyMessage(strPong(), idPong(), QString()), m_payload(payload) {} + + QString toJsonString() const override + { + return m_payload.isEmpty() ? strPong() : QStringLiteral("%1 %2").arg(strPong(), m_payload); + } + + private: + QString m_payload; }; -} +} // namespace LtsWebSocket diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/connection_handler.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/connection_handler.cpp old mode 100755 new mode 100644 index 614d17768..fe4ac2bd4 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/connection_handler.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/connection_handler.cpp @@ -1,88 +1,89 @@ #include "connection_handler.h" -#include #include "client_connection.h" +#include #include +#include using namespace LtsWebSocket; -ConnectionHandler::ConnectionHandler(QObject *parent) : QObject(parent) - , m_server(nullptr), - m_logger(NGL::NGLLoggerBootstrap::getLogger()) {} +ConnectionHandler::ConnectionHandler(QObject* parent) + : QObject(parent), m_server(nullptr), m_logger(NGL::NGLLoggerBootstrap::getLogger()) +{ +} ConnectionHandler::~ConnectionHandler() { - for (auto connection : std::as_const(m_connections)) - connection->disconnect(this); + for (auto connection : std::as_const(m_connections)) + connection->disconnect(this); } -bool ConnectionHandler::init(const QString &serviceName, unsigned short port) +bool ConnectionHandler::init(const QString& serviceName, unsigned short port) { - if (m_server != nullptr) - { - m_server->disconnect(); - delete m_server; - } - - m_server = new QWebSocketServer(QStringLiteral("RME-") + serviceName, QWebSocketServer::NonSecureMode, this); + if (m_server != nullptr) + { + m_server->disconnect(); + delete m_server; + } - connect(m_server, &QWebSocketServer::newConnection, this, &ConnectionHandler::onNewConnection); - connect(m_server, &QWebSocketServer::serverError, this, &ConnectionHandler::onServerError); + m_server = new QWebSocketServer(QStringLiteral("RME-") + serviceName, QWebSocketServer::NonSecureMode, this); - DEBUG_LOG(m_logger) << "Trying to listen "; - if (!m_server->listen(QHostAddress::Any, port)) - { - ERROR_LOG(m_logger) << "Not possible to listen to port " << port; - return false; - } - DEBUG_LOG(m_logger) << "... ok, port " << m_server->serverPort(); + connect(m_server, &QWebSocketServer::newConnection, this, &ConnectionHandler::onNewConnection); + connect(m_server, &QWebSocketServer::serverError, this, &ConnectionHandler::onServerError); - return true; + DEBUG_LOG(m_logger) << "Trying to listen "; + if (!m_server->listen(QHostAddress::Any, port)) + { + ERROR_LOG(m_logger) << "Not possible to listen to port " << port; + return false; + } + DEBUG_LOG(m_logger) << "... ok, port " << m_server->serverPort(); + + return true; } -void ConnectionHandler::sendToAllClients(ReplyMessage *message) +void ConnectionHandler::sendToAllClients(ReplyMessage* message) { - for (auto connection : std::as_const(m_connections)) - connection->addReply(new ReplyMessage(*message)); + for (auto connection : std::as_const(m_connections)) + connection->addReply(new ReplyMessage(*message)); - delete message; + delete message; } void ConnectionHandler::onServerError(QWebSocketProtocol::CloseCode closeCode) { - ERROR_LOG(m_logger) << "Got server error with close code " << closeCode; + ERROR_LOG(m_logger) << "Got server error with close code " << closeCode; } void ConnectionHandler::onNewConnection() { - while (m_server->hasPendingConnections()) - { - QWebSocket *socket = m_server->nextPendingConnection(); - - ClientConnection *newConnection = new ClientConnection(socket, this); - connect(newConnection, &ClientConnection::destroyed, this, [this](QObject* o) + while (m_server->hasPendingConnections()) { - m_connections.remove(static_cast(o)); - }); + QWebSocket* socket = m_server->nextPendingConnection(); - if (!newConnection->init()) - { - ERROR_LOG(m_logger) << "Failed to initialise new client"; - delete newConnection; - newConnection = nullptr; - continue; + ClientConnection* newConnection = new ClientConnection(socket, this); + connect(newConnection, &ClientConnection::destroyed, this, + [this](QObject* o) { m_connections.remove(static_cast(o)); }); + + if (!newConnection->init()) + { + ERROR_LOG(m_logger) << "Failed to initialise new client"; + delete newConnection; + newConnection = nullptr; + continue; + } + newConnection->start(); + + connect(newConnection, &ClientConnection::newTextMessage, this, &ConnectionHandler::newTextMessageFromClient); + connect(newConnection, &ClientConnection::disconnected, this, &ConnectionHandler::clientDisconnected); + connect(newConnection, &ClientConnection::finished, newConnection, &ClientConnection::deleteLater); + + m_connections.insert(newConnection); + emit clientConnected(newConnection); + INFO_LOG(m_logger) << "New client connected ip: " << socket->localAddress().toString() << ":" + << socket->localPort(); } - newConnection->start(); - - connect(newConnection, &ClientConnection::newTextMessage, this, &ConnectionHandler::newTextMessageFromClient); - connect(newConnection, &ClientConnection::disconnected, this, &ConnectionHandler::clientDisconnected); - connect(newConnection, &ClientConnection::finished, newConnection, &ClientConnection::deleteLater); - - m_connections.insert(newConnection); - emit clientConnected(newConnection); - INFO_LOG(m_logger) << "New client connected ip: " << socket->localAddress().toString() << ":" << socket->localPort(); - } } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/CMakeLists.txt b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/CMakeLists.txt index 80f4cdf3f..87b658363 100755 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/CMakeLists.txt +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/CMakeLists.txt @@ -172,6 +172,7 @@ NGL_TARGET_LINK_LIBRARIES(LtsWidgets TabBarTabStyle LtsSessionData LtsUtilsSettings + NGLLogger PUBLIC LtsUtilsCore Qt6::Core diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_abstract_sequence_widget.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_abstract_sequence_widget.cpp old mode 100755 new mode 100644 index ad50ce074..d32344cce --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_abstract_sequence_widget.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_abstract_sequence_widget.cpp @@ -2,25 +2,21 @@ #include "lts_abstract_sequence_widget.h" +#include #include namespace LtsWidgets { -LtsAbstractSequenceWidget::LtsAbstractSequenceWidget(QWidget *parent, const bool &readOnly) - : QGroupBox(parent) - , m_readOnly(readOnly) - , m_pbAddMember(new QToolButton) +LtsAbstractSequenceWidget::LtsAbstractSequenceWidget(QWidget* parent, const bool& readOnly) + : QGroupBox(parent), m_readOnly(readOnly), m_pbAddMember(new QToolButton) { - m_pbAddMember->setIcon(QIcon(QLatin1String(":/icons/png/add.png"))); + m_pbAddMember->setIcon(QIcon(QLatin1String(":/icons/png/add.png"))); - connect(m_pbAddMember, &QToolButton::clicked, this, &LtsAbstractSequenceWidget::addMember); + connect(m_pbAddMember, &QToolButton::clicked, this, &LtsAbstractSequenceWidget::addMember); } -LtsAbstractSequenceWidget::~LtsAbstractSequenceWidget() -{ - -} +LtsAbstractSequenceWidget::~LtsAbstractSequenceWidget() {} void LtsAbstractSequenceWidget::addWidget(QWidget* widget, bool isReadOnly, bool isButtonVisible) { @@ -29,92 +25,91 @@ void LtsAbstractSequenceWidget::addWidget(QWidget* widget, bool isReadOnly, bool m_pbAddMember->setVisible(isButtonVisible); } -int LtsAbstractSequenceWidget::getMemberlistSize(){ - return m_memberList.size(); +int LtsAbstractSequenceWidget::getMemberlistSize() +{ + return m_memberList.size(); } -void LtsAbstractSequenceWidget::getValue(QWidget *data, - const QString &findObjectName) const +void LtsAbstractSequenceWidget::getValue(QWidget* data, const QString& findObjectName) const { - if(!findChild(findObjectName)) - return; + if (!findChild(findObjectName)) + return; - data = findChild(findObjectName); + data = findChild(findObjectName); } void LtsAbstractSequenceWidget::setMemberCount(int count) { - QWidget *child = nullptr; - do - { - child = findChild(getObjectName(++count)); - delete child; - } - while (child); - m_memberList.removeAll(nullptr); + QWidget* child = nullptr; + do + { + child = findChild(getObjectName(++count)); + delete child; + } while (child); + m_memberList.removeAll(nullptr); } uint32_t LtsAbstractSequenceWidget::getMemberCount() const { - int count = 0; - QWidget *child = findChild(getObjectName(count+1)); - while(child) - { - count++; - child = findChild(getObjectName(count+1)); - } - return count; + int count = 0; + QWidget* child = findChild(getObjectName(count + 1)); + while (child) + { + count++; + child = findChild(getObjectName(count + 1)); + } + return count; } -QToolButton *LtsAbstractSequenceWidget::pbAddMember() const +QToolButton* LtsAbstractSequenceWidget::pbAddMember() const { - return m_pbAddMember; + return m_pbAddMember; } QString LtsAbstractSequenceWidget::getObjectName(int index) const { - return QString::number(index); + return QString::number(index); } -void LtsAbstractSequenceWidget::addMemberWidget(QWidget *member, bool isReadOnly, bool isButtonVisible) +void LtsAbstractSequenceWidget::addMemberWidget(QWidget* member, bool isReadOnly, bool isButtonVisible) { - QToolButton *button = new QToolButton(); - button->setIcon(QIcon(QLatin1String(":/icons/png/remove.png"))); - button->setDisabled(isReadOnly); + QToolButton* button = new QToolButton(); + button->setIcon(QIcon(QLatin1String(":/icons/png/remove.png"))); + button->setDisabled(isReadOnly); - connect(button, &QToolButton::clicked, member, &QWidget::deleteLater); - connect(member, &QWidget::destroyed, this, &LtsAbstractSequenceWidget::deleteMemberWidget); - connect(member, &QWidget::destroyed, button, &QToolButton::deleteLater); + connect(button, &QToolButton::clicked, member, &QWidget::deleteLater); + connect(member, &QWidget::destroyed, this, &LtsAbstractSequenceWidget::deleteMemberWidget); + connect(member, &QWidget::destroyed, button, &QToolButton::deleteLater); - m_memberList.push_back(member); - setupMemberWidget(member, button, member->objectName(), isButtonVisible); + m_memberList.push_back(member); + setupMemberWidget(member, button, member->objectName(), isButtonVisible); } -void LtsAbstractSequenceWidget::deleteMemberWidget(QObject *member) +void LtsAbstractSequenceWidget::deleteMemberWidget(QObject* member) { - QWidget *w = qobject_cast(member); + QWidget* w = qobject_cast(member); - if(!w) - return; + if (!w) + return; - for(auto child : w->children()) - child->deleteLater(); + for (auto child : w->children()) + child->deleteLater(); - m_memberList.removeAll(w); - for(int i=0; isetObjectName(getObjectName(i + 1)); - - for(auto child : m_memberList[i]->children()) + m_memberList.removeAll(w); + for (int i = 0; i < m_memberList.size(); i++) { - if(child->objectName().isEmpty()) - continue; + m_memberList[i]->setObjectName(getObjectName(i + 1)); - QString childName = child->objectName(); - QString newId = QString::number(i + 1); - child->setObjectName(childName.replace(QRegExp(QLatin1String(".([0-9]*)")), newId)); + for (auto child : m_memberList[i]->children()) + { + if (child->objectName().isEmpty()) + continue; + + QString childName = child->objectName(); + QString newId = QString::number(i + 1); + child->setObjectName(childName.replace(QRegularExpression(QLatin1String("\\.([0-9]*)")), newId)); + } } - } } -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_background_widget.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_background_widget.cpp old mode 100755 new mode 100644 index 57b25508d..748fd5c61 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_background_widget.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_background_widget.cpp @@ -1,137 +1,123 @@ - #include "lts_background_widget.h" +#include +#include #include #include -#include #ifdef Q_OS_WIN #include #endif - namespace LtsWidgets { -LtsBackgroundWidget::LtsBackgroundWidget(QWidget *parent) - : QDialog(parent) - , m_isUltraWide(false) +LtsBackgroundWidget::LtsBackgroundWidget(QWidget* parent) : QDialog(parent), m_isUltraWide(false) { - setMouseTracking(true); - setWindowFlags(windowFlags() | Qt::FramelessWindowHint ); - setWindowTitle(QStringLiteral("Splash")); + setMouseTracking(true); + setWindowFlags(windowFlags() | Qt::FramelessWindowHint); + setWindowTitle(QStringLiteral("Splash")); - setBackground(); + setBackground(); } - void LtsBackgroundWidget::setBackground() { - static const auto backgroundFiles = - { - QStringLiteral(":/project/background.png"), - QStringLiteral(":/project/background.jpg"), - }; - static const auto backgroundFilesWide = - { - QStringLiteral(":/project/background_wide.png"), - QStringLiteral(":/project/background_wide.jpg"), - }; + static const auto backgroundFiles = { + QStringLiteral(":/project/background.png"), + QStringLiteral(":/project/background.jpg"), + }; + static const auto backgroundFilesWide = { + QStringLiteral(":/project/background_wide.png"), + QStringLiteral(":/project/background_wide.jpg"), + }; + + m_pixmap = QPixmap(); + for (const QString& f : m_isUltraWide ? backgroundFilesWide : backgroundFiles) + { + if (!QFile::exists(f)) + continue; + m_pixmap = QPixmap(f); + if (m_pixmap.isNull()) + continue; + break; + } - m_pixmap = QPixmap(); - for (const QString &f : m_isUltraWide ? backgroundFilesWide : backgroundFiles) - { - if (!QFile::exists(f)) - continue; - m_pixmap = QPixmap(f); if (m_pixmap.isNull()) - continue; - break; - } - - if (m_pixmap.isNull()) - { - if (m_isUltraWide) { - m_isUltraWide = false; - setBackground(); + if (m_isUltraWide) + { + m_isUltraWide = false; + setBackground(); + } + else + { + qWarning() << "BackgroundWidget::c_tor: file missing or is not a valid image ':/project/background.png'"; + } } - else - { - qWarning() << "BackgroundWidget::c_tor: file missing or is not a valid image ':/project/background.png'"; - } - } } - void LtsBackgroundWidget::setUltraWide(bool set) { - if (set == m_isUltraWide) - return; + if (set == m_isUltraWide) + return; - m_isUltraWide = set; - setBackground(); - update(); + m_isUltraWide = set; + setBackground(); + update(); } - -void LtsBackgroundWidget::resizeEvent(QResizeEvent *e) +void LtsBackgroundWidget::resizeEvent(QResizeEvent* e) { - setUltraWide(width() > 3000); - QDialog::resizeEvent(e); + setUltraWide(width() > 3000); + QDialog::resizeEvent(e); } - -void LtsBackgroundWidget::paintEvent(QPaintEvent *e) +void LtsBackgroundWidget::paintEvent(QPaintEvent* e) { - if (!m_pixmap.isNull()) - { - QPainter painter(this); - painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); - painter.drawPixmap(0, 0, width(), height(), m_pixmap); - } - QDialog::paintEvent(e); + if (!m_pixmap.isNull()) + { + QPainter painter(this); + painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); + painter.drawPixmap(0, 0, width(), height(), m_pixmap); + } + QDialog::paintEvent(e); } - -bool LtsBackgroundWidget::event(QEvent *e) +bool LtsBackgroundWidget::event(QEvent* e) { - if (e->type() == QEvent::KeyPress || - e->type() == QEvent::MouseButtonPress || - e->type() == QEvent::MouseButtonRelease || - e->type() == QEvent::MouseMove) - { - - emit signalOperatorAction(); - e->ignore(); - return true; - } + if (e->type() == QEvent::KeyPress || e->type() == QEvent::MouseButtonPress || + e->type() == QEvent::MouseButtonRelease || e->type() == QEvent::MouseMove) + { - return QDialog::event(e); + emit signalOperatorAction(); + e->ignore(); + return true; + } + + return QDialog::event(e); } - void LtsBackgroundWidget::showFullScreen() { - + #ifdef Q_OS_WIN - winId(); - QWindowsWindowFunctions::setHasBorderInFullScreen(windowHandle(), true); + winId(); + QWindowsWindowFunctions::setHasBorderInFullScreen(windowHandle(), true); #endif - QDialog::showFullScreen(); - raise(); + QDialog::showFullScreen(); + raise(); } - -void LtsBackgroundWidget::closeEvent(QCloseEvent *e) +void LtsBackgroundWidget::closeEvent(QCloseEvent* e) { #ifdef DEVEL - deleteLater(); + deleteLater(); #else - e->ignore(); + e->ignore(); #endif } -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_base_layout_widget.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_base_layout_widget.cpp old mode 100755 new mode 100644 index 192749d14..33705ae7a --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_base_layout_widget.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_base_layout_widget.cpp @@ -1,31 +1,28 @@ - #include "lts_base_layout_widget.h" -#include -#include "ui_lts_base_layout.h" #include "lts_dialog.h" #include "lts_dialog_helper.h" #include "lts_drag_icon.h" +#include "lts_events.h" #include "lts_grid_layout.h" #include "lts_message_dialog.h" #include "lts_operator_menu.h" -#include "lts_tool_bar_area.h" #include "lts_splash.h" -#include "lts_events.h" +#include "lts_tool_bar_area.h" +#include "ui_lts_base_layout.h" +#include #include #include -#include -#include - #include #include #include #include #include #include +#include #include #include #include @@ -38,1792 +35,1596 @@ #include #include #include -#include -#include - +#include +#include namespace LtsWidgets { -static QVariant splitterInterpolator(const QList &start, const QList &end, qreal progress) +static QVariant splitterInterpolator(const QList& start, const QList& end, qreal progress) { - QList ret; - ret = start; - for (int i = 0; i < start.size(); i++) - { - ret[i] = start[i] + qRound((end[i] - start[i]) * progress); - if (ret[i] <= 0) - ret[i] = 1; - } + QList ret; + ret = start; + for (int i = 0; i < start.size(); i++) + { + ret[i] = start[i] + qRound((end[i] - start[i]) * progress); + if (ret[i] <= 0) + ret[i] = 1; + } - return QVariant::fromValue(ret); + return QVariant::fromValue(ret); } - -LtsBaseLayoutWidget::LtsBaseLayoutWidget(QWidget *parent, bool splitMenu) - : QWidget(parent) - , m_currentAnimation(nullptr) - , m_ui(new Ui::LtsBaseLayoutWidget) - , m_partitionType(IDL::PartitionType::Global) - , m_domainId(-1) - , m_partitionId(-1) - , m_firstShow(true) - , m_showTerminalButton(false) - , m_exerciseTime(0) - , m_setCurrentTimeTimer(new QTimer(this)) - , m_irreplaceableOnce(false) - , m_bg(nullptr) - , m_screenCount(1) - , m_menuCollapsed(true) - , m_notiBox(nullptr) +LtsBaseLayoutWidget::LtsBaseLayoutWidget(QWidget* parent, bool splitMenu) + : QWidget(parent), m_currentAnimation(nullptr), m_ui(new Ui::LtsBaseLayoutWidget), + m_partitionType(IDL::PartitionType::Global), m_domainId(-1), m_partitionId(-1), m_firstShow(true), + m_showTerminalButton(false), m_exerciseTime(0), m_setCurrentTimeTimer(new QTimer(this)), + m_irreplaceableOnce(false), m_bg(nullptr), m_screenCount(1), m_menuCollapsed(true), m_notiBox(nullptr) { - m_ui->setupUi(this); + m_ui->setupUi(this); #ifndef LTS_DEBUG - m_ui->pbDebug->hide(); + m_ui->pbDebug->hide(); #endif - addDebugMenu(); + addDebugMenu(); - - { - - m_ui->lbCurrentTime->setContextMenuPolicy(Qt::CustomContextMenu); - QMenu *currentTimeMenu = new QMenu(m_ui->lbCurrentTime); - currentTimeMenu->addAction(tr("Copy"), this, [this]() { - QGuiApplication::clipboard()->setText(m_ui->lbCurrentTime->text()); - }); - currentTimeMenu->addAction(tr("Copy in milliseconds"), this, []() + + m_ui->lbCurrentTime->setContextMenuPolicy(Qt::CustomContextMenu); + QMenu* currentTimeMenu = new QMenu(m_ui->lbCurrentTime); + currentTimeMenu->addAction(tr("Copy"), this, + [this]() { QGuiApplication::clipboard()->setText(m_ui->lbCurrentTime->text()); }); + currentTimeMenu->addAction(tr("Copy in milliseconds"), this, []() { + QGuiApplication::clipboard()->setText(QString::number(QDateTime::currentMSecsSinceEpoch())); + }); + connect(m_ui->lbCurrentTime, &QLabel::customContextMenuRequested, this, + [this, currentTimeMenu](const QPoint& pos) { + currentTimeMenu->popup(m_ui->lbCurrentTime->mapToGlobal(pos)); + }); + } + { - QGuiApplication::clipboard()->setText(QString::number(QDateTime::currentMSecsSinceEpoch())); - }); - connect(m_ui->lbCurrentTime, &QLabel::customContextMenuRequested, - this, [this, currentTimeMenu](const QPoint &pos) { currentTimeMenu->popup(m_ui->lbCurrentTime->mapToGlobal(pos)); }); - } + m_ui->lbExerciseTime->setContextMenuPolicy(Qt::CustomContextMenu); + QMenu* exerciseTimeMenu = new QMenu(m_ui->lbExerciseTime); + exerciseTimeMenu->addAction(tr("Copy"), this, + [this]() { QGuiApplication::clipboard()->setText(m_ui->lbExerciseTime->text()); }); + exerciseTimeMenu->addAction(tr("Copy in milliseconds"), this, [this]() { + QGuiApplication::clipboard()->setText(QString::number(m_exerciseTime)); + }); + connect(m_ui->lbExerciseTime, &QLabel::customContextMenuRequested, this, + [this, exerciseTimeMenu](const QPoint& pos) { + exerciseTimeMenu->popup(m_ui->lbExerciseTime->mapToGlobal(pos)); + }); + } - { - - m_ui->lbExerciseTime->setContextMenuPolicy(Qt::CustomContextMenu); - QMenu *exerciseTimeMenu = new QMenu(m_ui->lbExerciseTime); - exerciseTimeMenu->addAction(tr("Copy"), this, [this]() + setMinimumSize(1280, 900); + + m_ui->detailWidget->setSubTabsVisible(true); + + qRegisterAnimationInterpolator>(splitterInterpolator); + qRegisterMetaType("LayoutArea"); + + m_ui->mainWidget->setTabBarAutoHide(true); + + m_ui->infoWidget->setActuatorTabStyle(true); + m_ui->infoWidget->setTabBarAutoHide(false); + m_ui->infoWidget->setTabPosition(QTabWidget::West); + + if (m_ui->infoWidget->count() == 0) + m_ui->infoWidget->hide(); + + if (m_ui->detailWidget->count() == 0) + m_ui->detailWidget->hide(); + + if (m_ui->specialWidget->count() == 0) + m_ui->specialWidget->hide(); + + m_ui->masterSplitter->setStretchFactor(m_ui->masterSplitter->indexOf(m_ui->infoWidget), 0); + m_ui->masterSplitter->setStretchFactor(m_ui->masterSplitter->indexOf(m_ui->mainSplitter), 20); + + m_ui->mainSplitter->setStretchFactor(m_ui->mainSplitter->indexOf(m_ui->mainWidget), 20); + m_ui->mainSplitter->setStretchFactor(m_ui->mainSplitter->indexOf(m_ui->detailWidget), 0); + + m_ui->rightSplitter->setStretchFactor(m_ui->rightSplitter->indexOf(m_ui->stackedWidget), 20); + m_ui->rightSplitter->setStretchFactor(m_ui->rightSplitter->indexOf(m_ui->specialWidget), 0); + + m_isHidden = false; + + connect(m_ui->profileButton, &LtsProfileButton::signalClicked, this, &LtsBaseLayoutWidget::slotOperatorMenuClicked); + + m_ui->lbCustomTextBullet->hide(); + m_ui->lbCustomText->hide(); + + m_ui->lbExerciseTime->setText(QStringLiteral(" # ")); + m_ui->lbCurrentTime->setText(QStringLiteral(" # ")); + + connect(m_setCurrentTimeTimer, &QTimer::timeout, this, &LtsBaseLayoutWidget::setCurrentTime); + m_setCurrentTimeTimer->start(200); + + setExerciseData(m_exerciseData); + + if (splitMenu) { - QGuiApplication::clipboard()->setText(m_ui->lbExerciseTime->text()); - }); - exerciseTimeMenu->addAction(tr("Copy in milliseconds"), this, [this]() + m_bg = new QButtonGroup(m_ui->naviWidget); + m_bg->addButton(m_ui->pbPlanning, (int)ExercisePart::ePlanning); + m_bg->addButton(m_ui->pbExecution, (int)ExercisePart::eExecution); + m_bg->addButton(m_ui->pbAfterAction, (int)ExercisePart::eAfterAction); + m_bg->addButton(m_ui->pbSpecial, (int)ExercisePart::eSpecial); + + connect(m_bg, &QButtonGroup::idClicked, m_ui->stackedWidget, + [this](int id) { m_ui->stackedWidget->setCurrentWidget(getToolBox((ExercisePart)id)); }); + m_ui->pbSpecial->click(); + } + else { - QGuiApplication::clipboard()->setText(QString::number(m_exerciseTime)); - }); - connect(m_ui->lbExerciseTime, &QLabel::customContextMenuRequested, - this, [this, exerciseTimeMenu](const QPoint &pos) { exerciseTimeMenu->popup(m_ui->lbExerciseTime->mapToGlobal(pos)); }); - } + m_ui->stackedWidget->setCurrentWidget(getToolBox(ExercisePart::eSpecial)); + } - - setMinimumSize(1280, 900); - - m_ui->detailWidget->setSubTabsVisible(true); - - - qRegisterAnimationInterpolator >(splitterInterpolator); - qRegisterMetaType("LayoutArea"); - - m_ui->mainWidget->setTabBarAutoHide(true); - - m_ui->infoWidget->setActuatorTabStyle(true); - m_ui->infoWidget->setTabBarAutoHide(false); - m_ui->infoWidget->setTabPosition(QTabWidget::West); - - if (m_ui->infoWidget->count() == 0) - m_ui->infoWidget->hide(); - - if (m_ui->detailWidget->count() == 0) - m_ui->detailWidget->hide(); - - if (m_ui->specialWidget->count() == 0) - m_ui->specialWidget->hide(); - - - m_ui->masterSplitter->setStretchFactor(m_ui->masterSplitter->indexOf(m_ui->infoWidget), 0); - m_ui->masterSplitter->setStretchFactor(m_ui->masterSplitter->indexOf(m_ui->mainSplitter), 20); - - - m_ui->mainSplitter->setStretchFactor(m_ui->mainSplitter->indexOf(m_ui->mainWidget), 20); - m_ui->mainSplitter->setStretchFactor(m_ui->mainSplitter->indexOf(m_ui->detailWidget), 0); - - - m_ui->rightSplitter->setStretchFactor(m_ui->rightSplitter->indexOf(m_ui->stackedWidget), 20); - m_ui->rightSplitter->setStretchFactor(m_ui->rightSplitter->indexOf(m_ui->specialWidget), 0); - - m_isHidden = false; - - - connect(m_ui->profileButton, &LtsProfileButton::signalClicked, this, &LtsBaseLayoutWidget::slotOperatorMenuClicked); - - - - - - m_ui->lbCustomTextBullet->hide(); - m_ui->lbCustomText->hide(); - - m_ui->lbExerciseTime->setText(QStringLiteral(" # ")); - m_ui->lbCurrentTime->setText(QStringLiteral(" # ")); - - connect(m_setCurrentTimeTimer, &QTimer::timeout, this, &LtsBaseLayoutWidget::setCurrentTime); - m_setCurrentTimeTimer->start(200); - - setExerciseData(m_exerciseData); - - if (splitMenu) - { - m_bg = new QButtonGroup(m_ui->naviWidget); - m_bg->addButton(m_ui->pbPlanning, (int) ExercisePart::ePlanning); - m_bg->addButton(m_ui->pbExecution, (int) ExercisePart::eExecution); - m_bg->addButton(m_ui->pbAfterAction, (int) ExercisePart::eAfterAction); - m_bg->addButton(m_ui->pbSpecial, (int) ExercisePart::eSpecial); - - connect(m_bg, QOverload::of(&QButtonGroup::buttonClicked), m_ui->stackedWidget, [this](int id) - { - m_ui->stackedWidget->setCurrentWidget(getToolBox((ExercisePart) id)); - }); - m_ui->pbSpecial->click(); - } - else - { - m_ui->stackedWidget->setCurrentWidget(getToolBox(ExercisePart::eSpecial)); - } - - checkExercisePartButtonVisibility(); + checkExercisePartButtonVisibility(); } - LtsBaseLayoutWidget::~LtsBaseLayoutWidget() { - - + if (m_notiBox != nullptr) + m_notiBox->setParent(nullptr); + delete m_notiBox; - if (m_notiBox != nullptr) - m_notiBox->setParent(nullptr); - delete m_notiBox; - - delete m_currentAnimation; - m_currentAnimation = nullptr; - clearMenuActions(); - delete m_ui; - m_ui = nullptr; - + delete m_currentAnimation; + m_currentAnimation = nullptr; + clearMenuActions(); + delete m_ui; + m_ui = nullptr; } - void LtsBaseLayoutWidget::setCurrentTime() { - m_ui->lbCurrentTime->setText(DTG::toString(QDateTime::currentDateTime())); + m_ui->lbCurrentTime->setText(DTG::toString(QDateTime::currentDateTime())); - if (m_exerciseTime > 0) - m_ui->lbExerciseTime->setText(DTG::toStringMSec(m_exerciseTime)); - else - m_ui->lbExerciseTime->setText(QStringLiteral(" # ")); + if (m_exerciseTime > 0) + m_ui->lbExerciseTime->setText(DTG::toStringMSec(m_exerciseTime)); + else + m_ui->lbExerciseTime->setText(QStringLiteral(" # ")); } - void LtsBaseLayoutWidget::slotScreenCountChanged(int count) { - m_screenCount = count; + m_screenCount = count; } - const QString LtsBaseLayoutWidget::customText() const { - return m_ui->lbCustomText->text(); + return m_ui->lbCustomText->text(); } - -void LtsBaseLayoutWidget::setCustomText(const QString &text) +void LtsBaseLayoutWidget::setCustomText(const QString& text) { - if (text.isEmpty()) - { - m_ui->lbCustomText->setText(QString()); - m_ui->lbCustomText->hide(); - m_ui->lbCustomTextBullet->hide(); + if (text.isEmpty()) + { + m_ui->lbCustomText->setText(QString()); + m_ui->lbCustomText->hide(); + m_ui->lbCustomTextBullet->hide(); - return; - } + return; + } - m_ui->lbCustomText->show(); - m_ui->lbCustomTextBullet->show(); - m_ui->lbCustomText->setText(text); + m_ui->lbCustomText->show(); + m_ui->lbCustomTextBullet->show(); + m_ui->lbCustomText->setText(text); } - void LtsBaseLayoutWidget::addDebugMenu() { #ifdef LTS_DEBUG - QMenu *menu = new QMenu(this); + QMenu* menu = new QMenu(this); - menu->addAction(QStringLiteral("NOTE: all actions are delayed by 1s"))->setEnabled(false); + menu->addAction(QStringLiteral("NOTE: all actions are delayed by 1s"))->setEnabled(false); - menu->addSeparator(); + menu->addSeparator(); - menu->addAction(QStringLiteral("logout"), this, [this]() - { - QTimer::singleShot(1000, this, &LtsBaseLayoutWidget::slotLogout); - }); + menu->addAction(QStringLiteral("logout"), this, + [this]() { QTimer::singleShot(1000, this, &LtsBaseLayoutWidget::slotLogout); }); - menu->addAction(QStringLiteral("forced logout"), this, [this]() - { - QTimer::singleShot(1000, this, &LtsBaseLayoutWidget::signalLogout); - }); + menu->addAction(QStringLiteral("forced logout"), this, + [this]() { QTimer::singleShot(1000, this, &LtsBaseLayoutWidget::signalLogout); }); - menu->addAction(QStringLiteral("app exit"), this, [this]() - { - QTimer::singleShot(1000, this, &LtsBaseLayoutWidget::signalClose); - }); + menu->addAction(QStringLiteral("app exit"), this, + [this]() { QTimer::singleShot(1000, this, &LtsBaseLayoutWidget::signalClose); }); - menu->addSeparator(); + menu->addSeparator(); - menu->addAction(QStringLiteral("show test message, unparented"), this, [this]() - { - QTimer::singleShot(1000, this, []() { LtsWidgets::LtsMessageDialog::showMessage(nullptr , QStringLiteral("test"), QStringLiteral("test")); } ); - }); - - menu->addAction(QStringLiteral("show test message"), this, [this]() - { - QTimer::singleShot(1000, this, [this]() { LtsWidgets::LtsMessageDialog::showMessage(this, QStringLiteral("test"), QStringLiteral("test")); } ); - }); - - menu->addSeparator(); - - menu->addAction(QStringLiteral("hide details tab"), this, [this]() - { - QTimer::singleShot(1000, this, [this]() { this->hideWidgets(); } ); - }); - - menu->addAction(QStringLiteral("show details tab"), this, [this]() - { - QTimer::singleShot(1000, this, [this]() { this->showWidgets(); } ); - }); - - menu->addAction(QStringLiteral("hide details tab, animated"), this, [this]() - { - QTimer::singleShot(1000, this, [this]() { this->onHideAnimated(); } ); - }); - - menu->addAction(QStringLiteral("show details tab, animated"), this, [this]() - { - QTimer::singleShot(1000, this, [this]() { this->onReShowAnimated(); } ); - }); - - menu->addSeparator(); - - menu->addAction(QStringLiteral("hide top bar"), this, [this]() - { - QTimer::singleShot(1000, this, [this]() { this->setTopBarVisible(false); } ); - }); - - menu->addSeparator(); - - menu->addAction(QStringLiteral("test NotificationBox with error"), this, [this]() - { - QTimer::singleShot(1000, this, [this]() - { - showMessage(QStringLiteral("Test Title"), QStringLiteral("A long test text that notifies the user about something
that spreads over two lines to fit even more text."), LtsWidgets::LtsNotificationBox::MessageType::Error, - [this](const QString &) - { - new LtsWidgets::LtsMessageDialogNew(this, QStringLiteral("You clicked the link!")); - }, true, QInputDialog::getText(this, QStringLiteral("Identifier"), QStringLiteral("Identifier (keep empty to not set)"))); + menu->addAction(QStringLiteral("show test message, unparented"), this, [this]() { + QTimer::singleShot(1000, this, []() { + LtsWidgets::LtsMessageDialog::showMessage(nullptr, QStringLiteral("test"), QStringLiteral("test")); + }); }); - }); - menu->addAction(QStringLiteral("test NotificationBox with success"), this, [this]() - { - QTimer::singleShot(1000, this, [this]() - { - showMessage(QStringLiteral("Test Title"), QStringLiteral("A long test text that notifies the user about something
that spreads over two lines to fit even more text."), LtsWidgets::LtsNotificationBox::MessageType::Success, - [this](const QString &) - { - new LtsWidgets::LtsMessageDialogNew(this, QStringLiteral("You clicked the link!")); - }, true, QInputDialog::getText(this, QStringLiteral("Identifier"), QStringLiteral("Identifier (keep empty to not set)"))); + menu->addAction(QStringLiteral("show test message"), this, [this]() { + QTimer::singleShot(1000, this, [this]() { + LtsWidgets::LtsMessageDialog::showMessage(this, QStringLiteral("test"), QStringLiteral("test")); + }); }); - }); - menu->addAction(QStringLiteral("test NotificationBox with info"), this, [this]() - { - QTimer::singleShot(1000, this, [this]() - { - showMessage(QStringLiteral("Test Title"), QStringLiteral("A long test text that notifies the user about something
that spreads over two lines to fit even more text."), LtsWidgets::LtsNotificationBox::MessageType::Info, - [this](const QString &) - { - new LtsWidgets::LtsMessageDialogNew(this, QStringLiteral("You clicked the link!")); - }, true, QInputDialog::getText(this, QStringLiteral("Identifier"), QStringLiteral("Identifier (keep empty to not set)"))); + menu->addSeparator(); + + menu->addAction(QStringLiteral("hide details tab"), this, + [this]() { QTimer::singleShot(1000, this, [this]() { this->hideWidgets(); }); }); + + menu->addAction(QStringLiteral("show details tab"), this, + [this]() { QTimer::singleShot(1000, this, [this]() { this->showWidgets(); }); }); + + menu->addAction(QStringLiteral("hide details tab, animated"), this, + [this]() { QTimer::singleShot(1000, this, [this]() { this->onHideAnimated(); }); }); + + menu->addAction(QStringLiteral("show details tab, animated"), this, + [this]() { QTimer::singleShot(1000, this, [this]() { this->onReShowAnimated(); }); }); + + menu->addSeparator(); + + menu->addAction(QStringLiteral("hide top bar"), this, + [this]() { QTimer::singleShot(1000, this, [this]() { this->setTopBarVisible(false); }); }); + + menu->addSeparator(); + + menu->addAction(QStringLiteral("test NotificationBox with error"), this, [this]() { + QTimer::singleShot(1000, this, [this]() { + showMessage( + QStringLiteral("Test Title"), + QStringLiteral( + "A long test text that notifies the user about something
that spreads over two lines to fit even more text."), + LtsWidgets::LtsNotificationBox::MessageType::Error, + [this](const QString&) { + new LtsWidgets::LtsMessageDialogNew(this, QStringLiteral("You clicked the link!")); + }, + true, + QInputDialog::getText(this, QStringLiteral("Identifier"), + QStringLiteral("Identifier (keep empty to not set)"))); + }); }); - }); - menu->addAction(QStringLiteral("test NotificationBox with warning"), this, [this]() - { - QTimer::singleShot(1000, this, [this]() - { - showMessage(QStringLiteral("Test Title"), QStringLiteral("A long test text that notifies the user about something
that spreads over two lines to fit even more text."), LtsWidgets::LtsNotificationBox::MessageType::Warning, - [this](const QString &) - { - new LtsWidgets::LtsMessageDialogNew(this, QStringLiteral("You clicked the link!")); - }, true, QInputDialog::getText(this, QStringLiteral("Identifier"), QStringLiteral("Identifier (keep empty to not set)"))); + menu->addAction(QStringLiteral("test NotificationBox with success"), this, [this]() { + QTimer::singleShot(1000, this, [this]() { + showMessage( + QStringLiteral("Test Title"), + QStringLiteral( + "A long test text that notifies the user about something
that spreads over two lines to fit even more text."), + LtsWidgets::LtsNotificationBox::MessageType::Success, + [this](const QString&) { + new LtsWidgets::LtsMessageDialogNew(this, QStringLiteral("You clicked the link!")); + }, + true, + QInputDialog::getText(this, QStringLiteral("Identifier"), + QStringLiteral("Identifier (keep empty to not set)"))); + }); }); - }); - m_ui->pbDebug->setMenu(menu); + menu->addAction(QStringLiteral("test NotificationBox with info"), this, [this]() { + QTimer::singleShot(1000, this, [this]() { + showMessage( + QStringLiteral("Test Title"), + QStringLiteral( + "A long test text that notifies the user about something
that spreads over two lines to fit even more text."), + LtsWidgets::LtsNotificationBox::MessageType::Info, + [this](const QString&) { + new LtsWidgets::LtsMessageDialogNew(this, QStringLiteral("You clicked the link!")); + }, + true, + QInputDialog::getText(this, QStringLiteral("Identifier"), + QStringLiteral("Identifier (keep empty to not set)"))); + }); + }); + + menu->addAction(QStringLiteral("test NotificationBox with warning"), this, [this]() { + QTimer::singleShot(1000, this, [this]() { + showMessage( + QStringLiteral("Test Title"), + QStringLiteral( + "A long test text that notifies the user about something
that spreads over two lines to fit even more text."), + LtsWidgets::LtsNotificationBox::MessageType::Warning, + [this](const QString&) { + new LtsWidgets::LtsMessageDialogNew(this, QStringLiteral("You clicked the link!")); + }, + true, + QInputDialog::getText(this, QStringLiteral("Identifier"), + QStringLiteral("Identifier (keep empty to not set)"))); + }); + }); + + m_ui->pbDebug->setMenu(menu); #endif } - -void LtsBaseLayoutWidget::showEvent(QShowEvent *event) +void LtsBaseLayoutWidget::showEvent(QShowEvent* event) { - QWidget::showEvent(event); + QWidget::showEvent(event); - if (!m_firstShow) - return; + if (!m_firstShow) + return; - m_firstShow = false; + m_firstShow = false; + QSize rendererSizeHint = m_ui->topLayoutWidget->sizeHint(); + rendererSizeHint.scale(rendererSizeHint.width() * 0.65, rendererSizeHint.height() * 0.65, Qt::IgnoreAspectRatio); + const auto dpr = devicePixelRatioF(); - QSize rendererSizeHint = m_ui->topLayoutWidget->sizeHint(); - rendererSizeHint.scale(rendererSizeHint.width() * 0.65, rendererSizeHint.height() * 0.65, Qt::IgnoreAspectRatio); - const auto dpr = devicePixelRatioF(); - - { - const QSize s(QSize(rendererSizeHint.height(), rendererSizeHint.height()) * dpr); - - QSvgRenderer svgRenderer; - QPixmap pixmap(s); - pixmap.fill(Qt::transparent); - - QPainter painter(&pixmap); - svgRenderer.load(QLatin1String(":rde_splitter_left.svg")); - svgRenderer.render(&painter); - painter.end(); - - pixmap.setDevicePixelRatio(dpr); - m_ui->lbRdeSplitterLeft->setPixmap(pixmap); - } - - { - - QString projectLogoFilename = QLatin1String(":project/logo.png"); - QPixmap pixmap(projectLogoFilename); - pixmap.setDevicePixelRatio(dpr); - - if (pixmap.isNull()) { - qWarning() << "LoginWindow::c_tor: (PROJECT LOGO) file missing or is not an valid image '" << projectLogoFilename << "'"; + const QSize s(QSize(rendererSizeHint.height(), rendererSizeHint.height()) * dpr); + + QSvgRenderer svgRenderer; + QPixmap pixmap(s); + pixmap.fill(Qt::transparent); + + QPainter painter(&pixmap); + svgRenderer.load(QLatin1String(":rde_splitter_left.svg")); + svgRenderer.render(&painter); + painter.end(); + + pixmap.setDevicePixelRatio(dpr); + m_ui->lbRdeSplitterLeft->setPixmap(pixmap); } - else + { - pixmap = pixmap.scaled(rendererSizeHint * dpr, Qt::KeepAspectRatio, Qt::SmoothTransformation); - m_ui->lbProjectLogo->setPixmap(pixmap); + + QString projectLogoFilename = QLatin1String(":project/logo.png"); + QPixmap pixmap(projectLogoFilename); + pixmap.setDevicePixelRatio(dpr); + + if (pixmap.isNull()) + { + qWarning() << "LoginWindow::c_tor: (PROJECT LOGO) file missing or is not an valid image '" + << projectLogoFilename << "'"; + } + else + { + pixmap = pixmap.scaled(rendererSizeHint * dpr, Qt::KeepAspectRatio, Qt::SmoothTransformation); + m_ui->lbProjectLogo->setPixmap(pixmap); + } } - } #ifdef TABLET_MODE - QList scrollWidgets = findChildren(); + QList scrollWidgets = findChildren(); - for (auto i = scrollWidgets.begin(); i != scrollWidgets.end(); ++i) - { - QWidget *widget = *i; + for (auto i = scrollWidgets.begin(); i != scrollWidgets.end(); ++i) + { + QWidget* widget = *i; - QVariant isConst = widget->property("const"); - if (isConst.isValid() && isConst.toBool()) - continue; + QVariant isConst = widget->property("const"); + if (isConst.isValid() && isConst.toBool()) + continue; - addTouchScroll(widget); - } + addTouchScroll(widget); + } #endif - Splash::getInstance()->done(); + Splash::getInstance()->done(); } - -void LtsBaseLayoutWidget::addTouchScroll(QWidget *widget) +void LtsBaseLayoutWidget::addTouchScroll(QWidget* widget) { - if (!widget) - return; - widget->setAttribute(Qt::WA_AcceptTouchEvents); + if (!widget) + return; + widget->setAttribute(Qt::WA_AcceptTouchEvents); - QScrollArea *sca = qobject_cast(widget); - if (sca) - { - QScroller::grabGesture(sca->viewport(), QScroller::LeftMouseButtonGesture); - return; - } + QScrollArea* sca = qobject_cast(widget); + if (sca) + { + QScroller::grabGesture(sca->viewport(), QScroller::LeftMouseButtonGesture); + return; + } - QAbstractItemView *aiv = qobject_cast(widget); - if (aiv) - { - QScroller::grabGesture(aiv->viewport(), QScroller::LeftMouseButtonGesture); - aiv->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel); - aiv->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); - return; - } + QAbstractItemView* aiv = qobject_cast(widget); + if (aiv) + { + QScroller::grabGesture(aiv->viewport(), QScroller::LeftMouseButtonGesture); + aiv->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel); + aiv->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); + return; + } } - -void LtsBaseLayoutWidget::setAppName(const QString &appName) +void LtsBaseLayoutWidget::setAppName(const QString& appName) { - m_ui->lbAppName->setText(appName); + m_ui->lbAppName->setText(appName); } - -void LtsBaseLayoutWidget::setExerciseData(const ExerciseData &data) +void LtsBaseLayoutWidget::setExerciseData(const ExerciseData& data) { - m_exerciseData = data; + m_exerciseData = data; - m_ui->lbExerciseName->setText(data.exName.isEmpty() ? tr("no exercise") : data.exName); + m_ui->lbExerciseName->setText(data.exName.isEmpty() ? tr("no exercise") : data.exName); - QString exerciseNameToolTip(tr("Exercise name")); - if (!data.exName.isEmpty() && m_partitionId > 0) - { - exerciseNameToolTip += tr("\nPartition Id:"); - exerciseNameToolTip += QStringLiteral(" %1").arg(m_partitionId); - } + QString exerciseNameToolTip(tr("Exercise name")); + if (!data.exName.isEmpty() && m_partitionId > 0) + { + exerciseNameToolTip += tr("\nPartition Id:"); + exerciseNameToolTip += QStringLiteral(" %1").arg(m_partitionId); + } - if (!data.exDescription.isEmpty()) - { - exerciseNameToolTip += tr("\nDescription:"); - exerciseNameToolTip += QStringLiteral(" %1").arg(data.exDescription); - } - m_ui->lbExerciseName->setToolTip(exerciseNameToolTip); + if (!data.exDescription.isEmpty()) + { + exerciseNameToolTip += tr("\nDescription:"); + exerciseNameToolTip += QStringLiteral(" %1").arg(data.exDescription); + } + m_ui->lbExerciseName->setToolTip(exerciseNameToolTip); - LtsUtils::ProjectSettings *ps = LtsUtils::ProjectSettings::getInstance(); - const bool enableEditPhases = ps->value(QStringLiteral("exm"), - QStringLiteral("enableEditPhases")).toBool(); - if (!enableEditPhases) - { - m_ui->lbExercisePhase->hide(); - m_ui->bullet1->hide(); - } + LtsUtils::ProjectSettings* ps = LtsUtils::ProjectSettings::getInstance(); + const bool enableEditPhases = ps->value(QStringLiteral("exm"), QStringLiteral("enableEditPhases")).toBool(); + if (!enableEditPhases) + { + m_ui->lbExercisePhase->hide(); + m_ui->bullet1->hide(); + } - m_ui->lbExercisePhase->setText(data.phName.isEmpty() ? tr("no phase") : data.phName); + m_ui->lbExercisePhase->setText(data.phName.isEmpty() ? tr("no phase") : data.phName); - QString phaseNameToolTip(tr("Exercise phase")); - if (!data.phDescription.isEmpty()) - { - phaseNameToolTip += tr("\nDescription:"); - phaseNameToolTip += QStringLiteral(" %1").arg(data.phDescription); - } - m_ui->lbExercisePhase->setToolTip(phaseNameToolTip); + QString phaseNameToolTip(tr("Exercise phase")); + if (!data.phDescription.isEmpty()) + { + phaseNameToolTip += tr("\nDescription:"); + phaseNameToolTip += QStringLiteral(" %1").arg(data.phDescription); + } + m_ui->lbExercisePhase->setToolTip(phaseNameToolTip); - m_ui->lbExerciseStatus->setText(data.exStateString.isEmpty() ? tr("no status") : data.exStateString); + m_ui->lbExerciseStatus->setText(data.exStateString.isEmpty() ? tr("no status") : data.exStateString); - if (data.exStateCol.isValid() && data.exStateCol != QColor()) - { - QPalette p = m_ui->lbExerciseStatus->palette(); - p.setColor(m_ui->lbExerciseStatus->backgroundRole(), data.exStateCol); - p.setColor(m_ui->lbExerciseStatus->foregroundRole(), data.exStateCol); - m_ui->lbExerciseStatus->setPalette(p); - } + if (data.exStateCol.isValid() && data.exStateCol != QColor()) + { + QPalette p = m_ui->lbExerciseStatus->palette(); + p.setColor(m_ui->lbExerciseStatus->backgroundRole(), data.exStateCol); + p.setColor(m_ui->lbExerciseStatus->foregroundRole(), data.exStateCol); + m_ui->lbExerciseStatus->setPalette(p); + } - m_ui->lbPartitionType->setText(data.partitionType); + m_ui->lbPartitionType->setText(data.partitionType); - applyExerciseStateRestricition(); + applyExerciseStateRestricition(); } void LtsBaseLayoutWidget::applyExerciseStateRestricition() { - for (auto it = m_mapButtons.cbegin(); it != m_mapButtons.cend(); ++it) - { - bool visible = it.value().exerciseStates.testFlag(m_exerciseData.exState); - it.key()->setButtonVisible(visible); - } -} - -void LtsBaseLayoutWidget::initilizationFinished() -{ - - - - - - - - -} - -void LtsBaseLayoutWidget::setToolBarActions(const QStringList &actions) -{ - QVector desiredActions; - - m_notFoundYet = actions; - - for (const QString &action : actions) - { - for (auto innerIt = m_mapButtons.cbegin(); innerIt != m_mapButtons.cend(); ++innerIt) + for (auto it = m_mapButtons.cbegin(); it != m_mapButtons.cend(); ++it) { - if (innerIt.value().identifier.compare(action) == 0) - { - desiredActions << innerIt.key(); - m_notFoundYet.removeAll(action); - } + bool visible = it.value().exerciseStates.testFlag(m_exerciseData.exState); + it.key()->setButtonVisible(visible); } - } +} - m_ui->toolBar->setMenuEntries(desiredActions); +void LtsBaseLayoutWidget::initilizationFinished() {} + +void LtsBaseLayoutWidget::setToolBarActions(const QStringList& actions) +{ + QVector desiredActions; + + m_notFoundYet = actions; + + for (const QString& action : actions) + { + for (auto innerIt = m_mapButtons.cbegin(); innerIt != m_mapButtons.cend(); ++innerIt) + { + if (innerIt.value().identifier.compare(action) == 0) + { + desiredActions << innerIt.key(); + m_notFoundYet.removeAll(action); + } + } + } + + m_ui->toolBar->setMenuEntries(desiredActions); } QStringList LtsBaseLayoutWidget::toolBarActions() const { - if (m_ui == nullptr || m_ui->toolBar == nullptr) - return QStringList(); - return m_ui->toolBar->menuEntries(); + if (m_ui == nullptr || m_ui->toolBar == nullptr) + return QStringList(); + return m_ui->toolBar->menuEntries(); } -void LtsBaseLayoutWidget::setFunctionKeys(const QMap &actions) +void LtsBaseLayoutWidget::setFunctionKeys(const QMap& actions) { - for (auto it = actions.cbegin(); it != actions.cend(); ++it) - m_ui->toolBar->setFunctionKey(it.key(), it.value()); + for (auto it = actions.cbegin(); it != actions.cend(); ++it) + m_ui->toolBar->setFunctionKey(it.key(), it.value()); } -QMap LtsBaseLayoutWidget::functionKeys() const +QMap LtsBaseLayoutWidget::functionKeys() const { - if (m_ui == nullptr) - return QMap(); - return m_ui->toolBar->functionKeys(); + if (m_ui == nullptr) + return QMap(); + return m_ui->toolBar->functionKeys(); } -void LtsBaseLayoutWidget::setSessionInfo(const int domainId, const IDL::PartitionType &partitionType, const int partitionId, const QString &workspaceId) +void LtsBaseLayoutWidget::setSessionInfo(const int domainId, const IDL::PartitionType& partitionType, + const int partitionId, const QString& workspaceId) { - m_domainId = domainId; - m_partitionType = partitionType; - m_partitionId = partitionId; - m_workspaceId = workspaceId; + m_domainId = domainId; + m_partitionType = partitionType; + m_partitionId = partitionId; + m_workspaceId = workspaceId; } - - -void LtsBaseLayoutWidget::setOperatorName(const QString &operatorName, bool showTerminalButton) +void LtsBaseLayoutWidget::setOperatorName(const QString& operatorName, bool showTerminalButton) { - m_operatorName = operatorName; - if (m_operatorName.isEmpty()) - m_operatorName = tr("Admin"); + m_operatorName = operatorName; + if (m_operatorName.isEmpty()) + m_operatorName = tr("Admin"); - m_ui->profileButton->setToolTip(tr("Operator Name: %1").arg(m_operatorName)); - m_showTerminalButton = showTerminalButton; + m_ui->profileButton->setToolTip(tr("Operator Name: %1").arg(m_operatorName)); + m_showTerminalButton = showTerminalButton; } - -void LtsBaseLayoutWidget::setProfilePicture(const QPixmap &profilePicture) +void LtsBaseLayoutWidget::setProfilePicture(const QPixmap& profilePicture) { - m_ui->profileButton->setPixmap(profilePicture); + m_ui->profileButton->setPixmap(profilePicture); } - void LtsBaseLayoutWidget::slotOperatorMenuClicked() { - bool debug = false; + bool debug = false; #ifndef LTS_DEBUG - if (LtsSessionData::LtsSessionData::getInstance()->debugFlagValue(QStringLiteral("DeveloperTools.Actions")) == QVariant(true)) + if (LtsSessionData::LtsSessionData::getInstance()->debugFlagValue(QStringLiteral("DeveloperTools.Actions")) == + QVariant(true)) #endif - { - debug = true; - } - - LtsOperatorMenu *operatorMenu = new LtsOperatorMenu(m_operatorName, m_workspaceId, debug, m_screenCount, this); - operatorMenu->setTerminalButton(m_showTerminalButton); - - bool hasOperatorSettings = false; - for (const PluginData &pd : std::as_const(m_mapButtons)) - { - if (pd.identifier == QStringLiteral("_OpmShowOperatorSettings")) { - hasOperatorSettings = true; - break; + debug = true; } - } - operatorMenu->setOperatorSettingsButton(hasOperatorSettings); - connect(operatorMenu, &LtsOperatorMenu::signalLogout, this, &LtsBaseLayoutWidget::slotLogout); - connect(operatorMenu, &LtsOperatorMenu::signalExit, this, &LtsBaseLayoutWidget::slotClose); - connect(operatorMenu, &LtsOperatorMenu::signalShowOperatorSettings, this, &LtsBaseLayoutWidget::signalShowOperatorSettings); - connect(operatorMenu, &LtsOperatorMenu::signalSwap, this, &LtsBaseLayoutWidget::signalSwap); + LtsOperatorMenu* operatorMenu = new LtsOperatorMenu(m_operatorName, m_workspaceId, debug, m_screenCount, this); + operatorMenu->setTerminalButton(m_showTerminalButton); - operatorMenu->show(); + bool hasOperatorSettings = false; + for (const PluginData& pd : std::as_const(m_mapButtons)) + { + if (pd.identifier == QStringLiteral("_OpmShowOperatorSettings")) + { + hasOperatorSettings = true; + break; + } + } + operatorMenu->setOperatorSettingsButton(hasOperatorSettings); + + connect(operatorMenu, &LtsOperatorMenu::signalLogout, this, &LtsBaseLayoutWidget::slotLogout); + connect(operatorMenu, &LtsOperatorMenu::signalExit, this, &LtsBaseLayoutWidget::slotClose); + connect(operatorMenu, &LtsOperatorMenu::signalShowOperatorSettings, this, + &LtsBaseLayoutWidget::signalShowOperatorSettings); + connect(operatorMenu, &LtsOperatorMenu::signalSwap, this, &LtsBaseLayoutWidget::signalSwap); + + operatorMenu->show(); } - bool LtsBaseLayoutWidget::haveUnsavedChanges() { - if (LtsTabWidget::hasUnsavedChanges(getTabFromLayoutArea(LayoutArea::eDialogTab))) - return true; - if (LtsTabWidget::hasUnsavedChanges(getTabFromLayoutArea(LayoutArea::eInfoTab))) - return true; - if (LtsTabWidget::hasUnsavedChanges(getTabFromLayoutArea(LayoutArea::eMainTab))) - return true; - if (LtsTabWidget::hasUnsavedChanges(getTabFromLayoutArea(LayoutArea::eSpecialTab))) - return true; + if (LtsTabWidget::hasUnsavedChanges(getTabFromLayoutArea(LayoutArea::eDialogTab))) + return true; + if (LtsTabWidget::hasUnsavedChanges(getTabFromLayoutArea(LayoutArea::eInfoTab))) + return true; + if (LtsTabWidget::hasUnsavedChanges(getTabFromLayoutArea(LayoutArea::eMainTab))) + return true; + if (LtsTabWidget::hasUnsavedChanges(getTabFromLayoutArea(LayoutArea::eSpecialTab))) + return true; - return false; + return false; } - - - - - - - - - - - bool LtsBaseLayoutWidget::notifyUnsavedChanges() { - if (isSignalConnected(QMetaMethod::fromSignal(&LtsBaseLayoutWidget::signalNotifyUnsavedChanges))) - { - bool reject = false; - emit signalNotifyUnsavedChanges(reject); - return reject; - } - else - { - if (haveUnsavedChanges()) + if (isSignalConnected(QMetaMethod::fromSignal(&LtsBaseLayoutWidget::signalNotifyUnsavedChanges))) { - LtsWidgets::Buttons buttons; - buttons.setFlag(Button::Yes, true); - buttons.setFlag(Button::Cancel, true); - QHash buttonTexts; - buttonTexts.insert(Button::Yes, tr("Discard All")); - const auto ret = LtsMessageDialog::showMessage(this, tr("There are dialogs with unsaved changes.
Please save or discard their changes before closing"), tr("Unsaved changes"),Behaviour::Modal, buttons, buttonTexts); - return ret == Button::Yes; + bool reject = false; + emit signalNotifyUnsavedChanges(reject); + return reject; } - } - return true; + else + { + if (haveUnsavedChanges()) + { + LtsWidgets::Buttons buttons; + buttons.setFlag(Button::Yes, true); + buttons.setFlag(Button::Cancel, true); + QHash buttonTexts; + buttonTexts.insert(Button::Yes, tr("Discard All")); + const auto ret = LtsMessageDialog::showMessage( + this, + tr("There are dialogs with unsaved changes.
Please save or discard their changes before closing"), + tr("Unsaved changes"), Behaviour::Modal, buttons, buttonTexts); + return ret == Button::Yes; + } + } + return true; } - -void LtsBaseLayoutWidget::slotLogout() +void LtsBaseLayoutWidget::slotLogout() { - emit signalLogout(); + emit signalLogout(); } - bool LtsBaseLayoutWidget::slotClose() { - if (!notifyUnsavedChanges()) - return false; + if (!notifyUnsavedChanges()) + return false; - - - - - + hide(); - - - - - - - - - - - - - - - - hide(); - - emit signalClose(); - return true; + emit signalClose(); + return true; } - - - - - - - -void LtsBaseLayoutWidget::closeEvent(QCloseEvent *event) +void LtsBaseLayoutWidget::closeEvent(QCloseEvent* event) { - event->ignore(); + event->ignore(); - slotClose(); + slotClose(); } - -bool LtsBaseLayoutWidget::focusTab(const QString &menuGroup, const QString &identifier, LayoutArea area) +bool LtsBaseLayoutWidget::focusTab(const QString& menuGroup, const QString& identifier, LayoutArea area) { - LtsTabWidget *tab = getTabFromLayoutArea(area); - if (!tab) - { - qWarning() << "LtsBaseLayoutWidget::focusTab: tab, by enum type, not found!"; - return false; - } - - return tab->focusTab(menuGroup, identifier); -} - - -bool LtsBaseLayoutWidget::isDialogFocused(const LtsDialog *dialog, const LtsTabWidget *tab) const -{ - QWidget *w = tab->widget(tab->currentIndex()); - - if (w == nullptr) - return false; - - const LtsTabWidget *secondTab = qobject_cast(w); - - if (secondTab != nullptr) - return isDialogFocused(dialog, secondTab); - - const LtsDialogHelper *helper = qobject_cast(w); - - if (helper != nullptr) - return helper->compare(dialog); - - qWarning() << "LtsBaseLayoutWidget::isDialogFocused(LtsDialog *dialog, LtsTabWidget *tab): i found something weird.." << w->metaObject()->className(); - return false; -} - - -bool LtsBaseLayoutWidget::isDialogFocused(const LtsDialog *dialog, const LayoutArea &layoutArea) const -{ - const LtsTabWidget *tab = getTabFromLayoutArea(layoutArea); - if (tab == nullptr) - { - qWarning() << "LtsBaseLayoutWidget::addWidget: tab, by enum type, not found!"; - return false; - } - - return isDialogFocused(dialog, tab); -} - - -bool LtsBaseLayoutWidget::isDialogFocused(const LtsDialog *dialog) const -{ - return (isDialogFocused(dialog, LayoutArea::eDialogTab) || - isDialogFocused(dialog, LayoutArea::eInfoTab) || - isDialogFocused(dialog, LayoutArea::eSpecialTab) || - isDialogFocused(dialog, LayoutArea::eMainTab)); -} - - -bool LtsBaseLayoutWidget::addOrReplaceWidget(LtsDialog *dialog, const QString &menuGroup, const QString &identifier, LayoutArea area, bool setClosable, bool focusNewTab) -{ - LtsTabWidget *tab = getTabFromLayoutArea(area); - if (tab && dialog && (!identifier.isEmpty())) - { - QWidget *existingWidget = tab->getWidget(menuGroup, identifier); - - if (nullptr != existingWidget) + LtsTabWidget* tab = getTabFromLayoutArea(area); + if (!tab) { - if (tab->removeWidget(existingWidget)) - { - existingWidget->deleteLater(); - - } - else - { - qWarning() << __FUNCTION__ << " : Remove existing widget from TabWidget failed."; - } + qWarning() << "LtsBaseLayoutWidget::focusTab: tab, by enum type, not found!"; + return false; } - } - return addWidget(dialog, menuGroup, identifier, area, setClosable, focusNewTab); -} + return tab->focusTab(menuGroup, identifier); +} -bool LtsBaseLayoutWidget::addWidget(LtsDialog *dialog, const QString &menuGroup, const QString &identifier, LayoutArea area, bool setClosable, bool focusNewTab) +bool LtsBaseLayoutWidget::isDialogFocused(const LtsDialog* dialog, const LtsTabWidget* tab) const { - if (!dialog) - { - qWarning() << "LtsBaseLayoutWidget::addWidget: cannot add null-widget!"; + QWidget* w = tab->widget(tab->currentIndex()); + + if (w == nullptr) + return false; + + const LtsTabWidget* secondTab = qobject_cast(w); + + if (secondTab != nullptr) + return isDialogFocused(dialog, secondTab); + + const LtsDialogHelper* helper = qobject_cast(w); + + if (helper != nullptr) + return helper->compare(dialog); + + qWarning() + << "LtsBaseLayoutWidget::isDialogFocused(LtsDialog *dialog, LtsTabWidget *tab): i found something weird.." + << w->metaObject()->className(); return false; - } +} - LtsTabWidget *tab = getTabFromLayoutArea(area); - if (!tab) - { - qWarning() << "LtsBaseLayoutWidget::addWidget: tab, by enum type, not found!"; - return false; - } - - dialog->setMenuGroup(menuGroup); - dialog->setIdentifier(identifier); - QWidget *helper = dialog->getHelper(); - if (!helper) - { - helper = dialog; - dialog->setAttribute(Qt::WA_DeleteOnClose); - } - - if (!identifier.isEmpty()) - { - QWidget *existingWidget = tab->getWidget(menuGroup, identifier); - if (existingWidget != nullptr) +bool LtsBaseLayoutWidget::isDialogFocused(const LtsDialog* dialog, const LayoutArea& layoutArea) const +{ + const LtsTabWidget* tab = getTabFromLayoutArea(layoutArea); + if (tab == nullptr) { - helper->deleteLater(); - - if (focusNewTab) - tab->focusTab(menuGroup, identifier); - - - int indexOfSplitter = getIndexOfTab(tab); - - if (area == LayoutArea::eDialogTab && !(m_ui->mainSplitter->sizes().at(indexOfSplitter))) - m_ui->mainSplitter->animate(1); - else if (area == LayoutArea::eInfoTab && !(m_ui->masterSplitter->sizes().at(indexOfSplitter))) - m_ui->masterSplitter->animate(1); - - - return false; + qWarning() << "LtsBaseLayoutWidget::addWidget: tab, by enum type, not found!"; + return false; } - } - dialog->setBaseLayoutWidget(this); + return isDialogFocused(dialog, tab); +} - connect(dialog, &LtsDialog::startMainSelect, - this, &LtsBaseLayoutWidget::onHideAnimated); - connect(dialog, &LtsDialog::endMainSelect, - this, &LtsBaseLayoutWidget::onReShowAnimated); +bool LtsBaseLayoutWidget::isDialogFocused(const LtsDialog* dialog) const +{ + return (isDialogFocused(dialog, LayoutArea::eDialogTab) || isDialogFocused(dialog, LayoutArea::eInfoTab) || + isDialogFocused(dialog, LayoutArea::eSpecialTab) || isDialogFocused(dialog, LayoutArea::eMainTab)); +} - - emit signalStapleTopicLockHandler(dialog); - dialog->triggerTopicLock(); - - - - - tab->addTab(menuGroup, identifier, helper, setClosable, focusNewTab); - - if (tab->count() > 1) - { - int indexOfSplitter = getIndexOfTab(tab); - if (area == LayoutArea::eDialogTab && !(m_ui->mainSplitter->sizes().at(indexOfSplitter))) +bool LtsBaseLayoutWidget::addOrReplaceWidget(LtsDialog* dialog, const QString& menuGroup, const QString& identifier, + LayoutArea area, bool setClosable, bool focusNewTab) +{ + LtsTabWidget* tab = getTabFromLayoutArea(area); + if (tab && dialog && (!identifier.isEmpty())) { - qDebug()<<"animate 1a: "; - m_ui->mainSplitter->animate(1); + QWidget* existingWidget = tab->getWidget(menuGroup, identifier); + + if (nullptr != existingWidget) + { + if (tab->removeWidget(existingWidget)) + { + existingWidget->deleteLater(); + } + else + { + qWarning() << __FUNCTION__ << " : Remove existing widget from TabWidget failed."; + } + } } - else if (area == LayoutArea::eInfoTab && !(m_ui->masterSplitter->sizes().at(indexOfSplitter))) + return addWidget(dialog, menuGroup, identifier, area, setClosable, focusNewTab); +} + +bool LtsBaseLayoutWidget::addWidget(LtsDialog* dialog, const QString& menuGroup, const QString& identifier, + LayoutArea area, bool setClosable, bool focusNewTab) +{ + if (!dialog) { - qDebug()<<"animate 1b: "; - m_ui->masterSplitter->animate(1); + qWarning() << "LtsBaseLayoutWidget::addWidget: cannot add null-widget!"; + return false; } - } - + + LtsTabWidget* tab = getTabFromLayoutArea(area); + if (!tab) + { + qWarning() << "LtsBaseLayoutWidget::addWidget: tab, by enum type, not found!"; + return false; + } + + dialog->setMenuGroup(menuGroup); + dialog->setIdentifier(identifier); + QWidget* helper = dialog->getHelper(); + if (!helper) + { + helper = dialog; + dialog->setAttribute(Qt::WA_DeleteOnClose); + } + + if (!identifier.isEmpty()) + { + QWidget* existingWidget = tab->getWidget(menuGroup, identifier); + if (existingWidget != nullptr) + { + helper->deleteLater(); + + if (focusNewTab) + tab->focusTab(menuGroup, identifier); + + int indexOfSplitter = getIndexOfTab(tab); + + if (area == LayoutArea::eDialogTab && !(m_ui->mainSplitter->sizes().at(indexOfSplitter))) + m_ui->mainSplitter->animate(1); + else if (area == LayoutArea::eInfoTab && !(m_ui->masterSplitter->sizes().at(indexOfSplitter))) + m_ui->masterSplitter->animate(1); + + return false; + } + } + + dialog->setBaseLayoutWidget(this); + + connect(dialog, &LtsDialog::startMainSelect, this, &LtsBaseLayoutWidget::onHideAnimated); + connect(dialog, &LtsDialog::endMainSelect, this, &LtsBaseLayoutWidget::onReShowAnimated); + + emit signalStapleTopicLockHandler(dialog); + dialog->triggerTopicLock(); + + tab->addTab(menuGroup, identifier, helper, setClosable, focusNewTab); + + if (tab->count() > 1) + { + int indexOfSplitter = getIndexOfTab(tab); + if (area == LayoutArea::eDialogTab && !(m_ui->mainSplitter->sizes().at(indexOfSplitter))) + { + qDebug() << "animate 1a: "; + m_ui->mainSplitter->animate(1); + } + else if (area == LayoutArea::eInfoTab && !(m_ui->masterSplitter->sizes().at(indexOfSplitter))) + { + qDebug() << "animate 1b: "; + m_ui->masterSplitter->animate(1); + } + } + #ifdef ADJUST_SPLITTER_SIZES_DIALOGTAB - - if (LayoutArea::eDialogTab == area) - { - const QList & sizes = m_ui->mainSplitter->sizes(); - int requestedTabHeight = tab->sizeHint().height(); - int mainHeight = sizes[0]+sizes[1]-requestedTabHeight; + if (LayoutArea::eDialogTab == area) + { + const QList& sizes = m_ui->mainSplitter->sizes(); + int requestedTabHeight = tab->sizeHint().height(); + int mainHeight = sizes[0] + sizes[1] - requestedTabHeight; - m_ui->mainSplitter->setSizes( QList() << mainHeight << requestedTabHeight ); - } -#endif + m_ui->mainSplitter->setSizes(QList() << mainHeight << requestedTabHeight); + } +#endif - return true; + return true; } - -LtsDialog *LtsBaseLayoutWidget::getWidget(const QString &menuGroup, const QString &identifier, LayoutArea area) +LtsDialog* LtsBaseLayoutWidget::getWidget(const QString& menuGroup, const QString& identifier, LayoutArea area) { - LtsTabWidget *tab = getTabFromLayoutArea(area); + LtsTabWidget* tab = getTabFromLayoutArea(area); - if (tab == nullptr) - return nullptr; + if (tab == nullptr) + return nullptr; - QWidget *w = tab->getWidget(menuGroup, identifier); + QWidget* w = tab->getWidget(menuGroup, identifier); - if (w == nullptr) - return nullptr; + if (w == nullptr) + return nullptr; - LtsDialogHelper *helper = qobject_cast(w); + LtsDialogHelper* helper = qobject_cast(w); - if (helper == nullptr) - return nullptr; + if (helper == nullptr) + return nullptr; - LtsDialog *dialog = qobject_cast(helper->getDialog()); - return dialog; + LtsDialog* dialog = qobject_cast(helper->getDialog()); + return dialog; } - void LtsBaseLayoutWidget::clearMenuActions() { - - while (m_ui->naviActionsPlanning->count()) - m_ui->naviActionsPlanning->removeItem(0); - while (m_ui->naviActionsExecution->count()) - m_ui->naviActionsExecution->removeItem(0); - while (m_ui->naviActionsAfterAction->count()) - m_ui->naviActionsAfterAction->removeItem(0); - while (m_ui->naviActionsSpecial->count()) - m_ui->naviActionsSpecial->removeItem(0); - checkExercisePartButtonVisibility(); + while (m_ui->naviActionsPlanning->count()) + m_ui->naviActionsPlanning->removeItem(0); + while (m_ui->naviActionsExecution->count()) + m_ui->naviActionsExecution->removeItem(0); + while (m_ui->naviActionsAfterAction->count()) + m_ui->naviActionsAfterAction->removeItem(0); + while (m_ui->naviActionsSpecial->count()) + m_ui->naviActionsSpecial->removeItem(0); - - for(auto it = m_mapButtons.begin(); it != m_mapButtons.end(); ++it) - delete it.key(); + checkExercisePartButtonVisibility(); - m_mapButtons.clear(); + for (auto it = m_mapButtons.begin(); it != m_mapButtons.end(); ++it) + delete it.key(); + + m_mapButtons.clear(); } - -void LtsBaseLayoutWidget::executeCreateInstantFunctions(const PluginData &plData) +void LtsBaseLayoutWidget::executeCreateInstantFunctions(const PluginData& plData) { - if (plData.createWidgetFunc) - { - LtsDialog *w = plData.createWidgetFunc(this); + if (plData.createWidgetFunc) + { + LtsDialog* w = plData.createWidgetFunc(this); - if (w) - addWidget(w, plData.menuGroup, plData.identifier, plData.layoutArea, plData.closable); - } + if (w) + addWidget(w, plData.menuGroup, plData.identifier, plData.layoutArea, plData.closable); + } - if (plData.directFunc) - { - plData.directFunc(plData); - } + if (plData.directFunc) + { + plData.directFunc(plData); + } } - void LtsBaseLayoutWidget::setExerciseTime(qint64 mSecsSinceEpoch) { - m_exerciseTime = mSecsSinceEpoch; + m_exerciseTime = mSecsSinceEpoch; } -LtsDragIcon *LtsBaseLayoutWidget::addMenuAction(const PluginData &plData, bool isFirstRun) +LtsDragIcon* LtsBaseLayoutWidget::addMenuAction(const PluginData& plData, bool isFirstRun) { - if (!LtsSessionData::LtsSessionData::getInstance()->hasOperatorRight(plData.operatorRight)) - { - qDebug() << " > Action" << plData.menuGroup << ":" << plData.menuText << "was not added due to missing operator right 0x" << QString::number(plData.operatorRight, 16); - return nullptr; - } - - if (isFirstRun) - { - switch (plData.createInstant) + if (!LtsSessionData::LtsSessionData::getInstance()->hasOperatorRight(plData.operatorRight)) { - case CreateInstantType::CreateInstantAndAddAction: - { - executeCreateInstantFunctions(plData); - break; + qDebug() << " > Action" << plData.menuGroup << ":" << plData.menuText + << "was not added due to missing operator right 0x" << QString::number(plData.operatorRight, 16); + return nullptr; } - case CreateInstantType::CreateInstantAndDiscardAction: + if (isFirstRun) { - executeCreateInstantFunctions(plData); - return nullptr; - } + switch (plData.createInstant) + { + case CreateInstantType::CreateInstantAndAddAction: { + executeCreateInstantFunctions(plData); + break; + } - default: + case CreateInstantType::CreateInstantAndDiscardAction: { + executeCreateInstantFunctions(plData); + return nullptr; + } + + default: { + break; + } + } + } + else { - break; + if (plData.createInstant == CreateInstantType::CreateInstantAndDiscardAction) + return nullptr; } - } - } - else - { - if (plData.createInstant == CreateInstantType::CreateInstantAndDiscardAction) - return nullptr; - } - - - bool err = false; - if (plData.identifier.isEmpty()) - { + bool err = false; + if (plData.identifier.isEmpty()) + { #ifdef LTS_DEBUG - LtsWidgets::LtsMessageDialog::showMessage(this, QStringLiteral("STOP!\n" - "Hier wurde ein Menu Entry hinzugefuegt, welcher ueber keinen Identifier verfuegt!\n" - "Bitte aendern!\n" - "Jetzt Debugger attachen und schauen woher der aufruf kommt.\n" - "Da der Identifier fehlt kann ich Dir hier nicht sagen um welchen Menu Entry es sich handelt =)")); + LtsWidgets::LtsMessageDialog::showMessage( + this, + QStringLiteral( + "STOP!\n" + "Hier wurde ein Menu Entry hinzugefuegt, welcher ueber keinen Identifier verfuegt!\n" + "Bitte aendern!\n" + "Jetzt Debugger attachen und schauen woher der aufruf kommt.\n" + "Da der Identifier fehlt kann ich Dir hier nicht sagen um welchen Menu Entry es sich handelt =)")); #endif - err = true; - } + err = true; + } - if (plData.menuGroup.isEmpty()) - { + if (plData.menuGroup.isEmpty()) + { #ifdef LTS_DEBUG - LtsWidgets::LtsMessageDialog::showMessage(this, QStringLiteral("STOP!\n" - "Hier wurde ein Menu Entry hinzugefuegt, welcher ueber keine Menu Group verfuegt!\n" - "Bitte aendern!\n" - "Jetzt Debugger attachen und schauen woher der aufruf kommt.\n" - "Da der Identifier fehlt kann ich Dir hier nicht sagen um welchen Menu Entry es sich handelt =)")); + LtsWidgets::LtsMessageDialog::showMessage( + this, + QStringLiteral( + "STOP!\n" + "Hier wurde ein Menu Entry hinzugefuegt, welcher ueber keine Menu Group verfuegt!\n" + "Bitte aendern!\n" + "Jetzt Debugger attachen und schauen woher der aufruf kommt.\n" + "Da der Identifier fehlt kann ich Dir hier nicht sagen um welchen Menu Entry es sich handelt =)")); #endif - err = true; - } + err = true; + } - if (err) - return nullptr; + if (err) + return nullptr; + bool found = false; + if (!isFirstRun) + { + for (auto it = m_mapButtons.begin(); it != m_mapButtons.end(); ++it) + { + LtsDragIcon* thatIcon = it.key(); - bool found = false; + if (thatIcon->objectName() == plData.identifier) + { + thatIcon->setText(plData.menuText); + thatIcon->setContext(plData.menuGroup); - if (!isFirstRun) - { + bool groupFound = false; + + for (int i = 0; i < m_ui->stackedWidget->count(); ++i) + { + LtsWidgets::LtsToolBox* tb = qobject_cast(m_ui->stackedWidget->widget(i)); + int groupWidgetIndex = tb->indexOf(thatIcon->parentWidget()); + if (groupWidgetIndex >= 0) + { + tb->setItemText(groupWidgetIndex, plData.menuGroup); + groupFound = true; + break; + } + } + if (!groupFound) + { + qWarning() << "group widget not found"; + } + found = true; + break; + } + } + + if (!found) + { + } + else + { + return nullptr; + } + } + + LtsWidgets::LtsToolBox* tb = getToolBox(m_bg ? plData.exercisePart : ExercisePart::eSpecial); + + QWidget* tmpW = tb->findChild(plData.menuGroup); + if (!tmpW) + { + + if (plData.createWidgetFunc == nullptr && plData.directFunc == nullptr) + return nullptr; + + tmpW = new QWidget; + tmpW->setObjectName(plData.menuGroup); + + LtsGridLayout* ltsGridLayout = new LtsGridLayout(LtsWidgets::ButtonSize::eDefault, tmpW); + tmpW->setLayout(ltsGridLayout); + + tb->addItem(tmpW, plData.menuGroup); + connect(tb, &LtsToolBox::resized, ltsGridLayout, &LtsGridLayout::onParentResize); + } + + QLayout* widgetLayout = tmpW->layout(); + LtsGridLayout* ltsGridLayout = qobject_cast(widgetLayout); + if (!ltsGridLayout) + { + + qWarning() << "temp widget has no layout! cannot add action" << plData.menuText + << "to menu! (the bad widget was of type" << tmpW->metaObject()->className() + << ") [did you forget to add the menuGroup to that action?]"; + return nullptr; + } + + if (widgetLayout->count() > 0) + { + QSpacerItem* spacer = dynamic_cast(widgetLayout->itemAt(widgetLayout->count() - 1)); + if (spacer) + { + ltsGridLayout->removeItem(spacer); + delete spacer; + } + } + + LtsDragIcon* dragIcon = nullptr; + if (plData.createWidgetFunc == nullptr && plData.directFunc == nullptr) + { + QFrame* line = new QFrame(tmpW); + line->setLineWidth(2); + line->setFrameStyle(QFrame::HLine); + + ltsGridLayout->add_widget(line); + } + else + { + if (isFirstRun || !found) + { + dragIcon = createButton(plData); + + ltsGridLayout->add_widget(dragIcon); + m_mapButtons.insert(dragIcon, plData); + + auto it = std::find_if(m_notFoundYet.begin(), m_notFoundYet.end(), + [plData](const QString& s) { return s == plData.identifier; }); + + if (it != m_notFoundYet.end()) + { + m_ui->toolBar->addMenuEntry(dragIcon); + m_notFoundYet.erase(it); + } + } + } + + checkExercisePartButtonVisibility(); + + QSpacerItem* spacer = new QSpacerItem(10, 1, QSizePolicy::Minimum, QSizePolicy::MinimumExpanding); + ltsGridLayout->addItem(spacer, ltsGridLayout->rowCount(), 0); + + return dragIcon; +} + +void LtsBaseLayoutWidget::addNotification(QToolButton* noti) +{ + m_ui->notificationLayoutWidget->layout()->addWidget(noti); +} + +bool LtsBaseLayoutWidget::notificationExists(const QString& identifier) const +{ + return (m_ui->notificationLayoutWidget->findChild(identifier, Qt::FindDirectChildrenOnly) != nullptr); +} + +bool LtsBaseLayoutWidget::removeMenuAction(const QString& byIdentifier) +{ for (auto it = m_mapButtons.begin(); it != m_mapButtons.end(); ++it) { - LtsDragIcon *thatIcon = it.key(); - - if (thatIcon->objectName() == plData.identifier) - { - thatIcon->setText(plData.menuText); - thatIcon->setContext(plData.menuGroup); - - bool groupFound = false; - - for (int i = 0; i < m_ui->stackedWidget->count(); ++i) - { - LtsWidgets::LtsToolBox *tb = qobject_cast(m_ui->stackedWidget->widget(i)); - int groupWidgetIndex = tb->indexOf(thatIcon->parentWidget() ); - if (groupWidgetIndex >= 0) - { - tb->setItemText(groupWidgetIndex, plData.menuGroup); - groupFound = true; - break; - } - } - if (!groupFound) - { - qWarning() << "group widget not found"; - } - found = true; - break; - } + if (it.value().identifier == byIdentifier) + return removeMenuAction(it.key()); } - if (!found) - { - - } - else - { - return nullptr; - } - } - - LtsWidgets::LtsToolBox *tb = getToolBox(m_bg ? plData.exercisePart : ExercisePart::eSpecial); - - - QWidget *tmpW = tb->findChild(plData.menuGroup); - if (!tmpW) - { - - if (plData.createWidgetFunc == nullptr && plData.directFunc == nullptr) - return nullptr; - - - tmpW = new QWidget; - tmpW->setObjectName(plData.menuGroup); - - LtsGridLayout *ltsGridLayout = new LtsGridLayout(LtsWidgets::ButtonSize::eDefault, tmpW); - tmpW->setLayout(ltsGridLayout); - - tb->addItem(tmpW, plData.menuGroup); - connect(tb, &LtsToolBox::resized, - ltsGridLayout, &LtsGridLayout::onParentResize); - } - - - QLayout *widgetLayout = tmpW->layout(); - LtsGridLayout *ltsGridLayout = qobject_cast(widgetLayout); - if (!ltsGridLayout) - { - - qWarning() << "temp widget has no layout! cannot add action" << plData.menuText << "to menu! (the bad widget was of type" << tmpW->metaObject()->className() << ") [did you forget to add the menuGroup to that action?]"; - return nullptr; - } - - - if (widgetLayout->count() > 0) - { - QSpacerItem *spacer = dynamic_cast(widgetLayout->itemAt(widgetLayout->count() - 1)); - if (spacer) - { - ltsGridLayout->removeItem(spacer); - delete spacer; - } - } - - - LtsDragIcon *dragIcon = nullptr; - if (plData.createWidgetFunc == nullptr && plData.directFunc == nullptr) - { - QFrame *line = new QFrame(tmpW); - line->setLineWidth(2); - line->setFrameStyle(QFrame::HLine); - - ltsGridLayout->add_widget(line); - } - else - { - if (isFirstRun || !found) - { - dragIcon = createButton(plData); - - ltsGridLayout->add_widget(dragIcon); - m_mapButtons.insert(dragIcon, plData); - - auto it = std::find_if(m_notFoundYet.begin(), m_notFoundYet.end(), [plData](const QString &s) - { - return s == plData.identifier; - }); - - if (it != m_notFoundYet.end()) - { - m_ui->toolBar->addMenuEntry(dragIcon); - m_notFoundYet.erase(it); - } - } - } - - checkExercisePartButtonVisibility(); - - QSpacerItem *spacer = new QSpacerItem(10, 1, QSizePolicy::Minimum, QSizePolicy::MinimumExpanding); - ltsGridLayout->addItem(spacer, ltsGridLayout->rowCount(), 0); - - return dragIcon; -} - - -void LtsBaseLayoutWidget::addNotification(QToolButton *noti) -{ - m_ui->notificationLayoutWidget->layout()->addWidget(noti); -} - - -bool LtsBaseLayoutWidget::notificationExists(const QString &identifier) const -{ - return (m_ui->notificationLayoutWidget->findChild(identifier, Qt::FindDirectChildrenOnly) != nullptr); -} - - -bool LtsBaseLayoutWidget::removeMenuAction(const QString &byIdentifier) -{ - for (auto it = m_mapButtons.begin(); it != m_mapButtons.end(); ++it) - { - if (it.value().identifier == byIdentifier) - return removeMenuAction(it.key()); - } - - return false; -} - - -bool LtsBaseLayoutWidget::removeMenuAction(const PluginData &plData) -{ - for (auto it = m_mapButtons.begin(); it != m_mapButtons.end(); ++it) - { - if (it.value().identifier == plData.identifier) - return removeMenuAction(it.key()); - } - - return false; -} - - -bool LtsBaseLayoutWidget::removeMenuAction(LtsDragIcon *icon) -{ - auto it = m_mapButtons.find(icon); - if (it == m_mapButtons.end()) return false; - - const QString menuGroup = it->menuGroup; - const ExercisePart ep = it->exercisePart; - m_mapButtons.erase(it); - - icon->setParent(nullptr); - icon->deleteLater(); - - checkMenuGroup(menuGroup, ep); - - return true; } -void LtsBaseLayoutWidget::executeAction(const QString &actionIdentifier) +bool LtsBaseLayoutWidget::removeMenuAction(const PluginData& plData) { - const QList plDatas(m_mapButtons.values()); - auto it = std::find_if(plDatas.constBegin(), plDatas.constEnd(), [actionIdentifier](const PluginData &plData) - { - return (plData.identifier == actionIdentifier); - }); - - if (it == plDatas.constEnd()) - return; - executePluginData(*it); -} - - -void LtsBaseLayoutWidget::executePluginData(const PluginData &plData) -{ - const QString &identifier = plData.identifier; - const QString &menuGroup = plData.menuGroup; - - LtsTabWidget *tab = getTabFromLayoutArea(plData.layoutArea); - - if (!tab->focusTab(menuGroup, identifier)) - { - - - if (plData.createWidgetFunc) + for (auto it = m_mapButtons.begin(); it != m_mapButtons.end(); ++it) { - LtsDialog *w = plData.createWidgetFunc(this); - if (w) - { - - addWidget(w, menuGroup, identifier, plData.layoutArea, plData.closable); - } - else - { - - } + if (it.value().identifier == plData.identifier) + return removeMenuAction(it.key()); + } + + return false; +} + +bool LtsBaseLayoutWidget::removeMenuAction(LtsDragIcon* icon) +{ + auto it = m_mapButtons.find(icon); + if (it == m_mapButtons.end()) + return false; + + const QString menuGroup = it->menuGroup; + const ExercisePart ep = it->exercisePart; + m_mapButtons.erase(it); + + icon->setParent(nullptr); + icon->deleteLater(); + + checkMenuGroup(menuGroup, ep); + + return true; +} + +void LtsBaseLayoutWidget::executeAction(const QString& actionIdentifier) +{ + const QList plDatas(m_mapButtons.values()); + auto it = std::find_if(plDatas.constBegin(), plDatas.constEnd(), [actionIdentifier](const PluginData& plData) { + return (plData.identifier == actionIdentifier); + }); + + if (it == plDatas.constEnd()) + return; + executePluginData(*it); +} + +void LtsBaseLayoutWidget::executePluginData(const PluginData& plData) +{ + const QString& identifier = plData.identifier; + const QString& menuGroup = plData.menuGroup; + + LtsTabWidget* tab = getTabFromLayoutArea(plData.layoutArea); + + if (!tab->focusTab(menuGroup, identifier)) + { + + if (plData.createWidgetFunc) + { + LtsDialog* w = plData.createWidgetFunc(this); + if (w) + { + + addWidget(w, menuGroup, identifier, plData.layoutArea, plData.closable); + } + else + { + } + } + else + { + if (plData.directFunc) + plData.directFunc(plData); + } } else { - if (plData.directFunc) - plData.directFunc(plData); } - } - else - { - - } } - void LtsBaseLayoutWidget::onMenuEntryClicked() { - LtsDragIcon *btn = qobject_cast(sender()); - if (!btn) - return; + LtsDragIcon* btn = qobject_cast(sender()); + if (!btn) + return; - if (!m_mapButtons.contains(btn)) - return; + if (!m_mapButtons.contains(btn)) + return; - executePluginData(m_mapButtons.value(btn)); + executePluginData(m_mapButtons.value(btn)); } - void LtsBaseLayoutWidget::resetLayoutVisibility() { - for (auto i = m_oldLayoutVisibilityStates.cbegin(); i != m_oldLayoutVisibilityStates.cend(); ++i) - { - const auto &tabPtr = i.key(); - if (tabPtr) - tabPtr->setVisible(i.value()); - } + for (auto i = m_oldLayoutVisibilityStates.cbegin(); i != m_oldLayoutVisibilityStates.cend(); ++i) + { + const auto& tabPtr = i.key(); + if (tabPtr) + tabPtr->setVisible(i.value()); + } - m_oldLayoutVisibilityStates.clear(); + m_oldLayoutVisibilityStates.clear(); } - void LtsBaseLayoutWidget::hideVisibleLayouts() { - if (!m_oldLayoutVisibilityStates.isEmpty()) - { - qWarning() << "LtsBaseLayoutWidget::hideVisibleLayouts: old states available - ignoring"; - return; - } + if (!m_oldLayoutVisibilityStates.isEmpty()) + { + qWarning() << "LtsBaseLayoutWidget::hideVisibleLayouts: old states available - ignoring"; + return; + } - LtsWidgets::LtsTabWidget *infoTab = getTabFromLayoutArea(LtsWidgets::LayoutArea::eInfoTab); - LtsWidgets::LtsTabWidget *specialTab = getTabFromLayoutArea(LtsWidgets::LayoutArea::eSpecialTab); - LtsWidgets::LtsTabWidget *dialogTab = getTabFromLayoutArea(LtsWidgets::LayoutArea::eDialogTab); + LtsWidgets::LtsTabWidget* infoTab = getTabFromLayoutArea(LtsWidgets::LayoutArea::eInfoTab); + LtsWidgets::LtsTabWidget* specialTab = getTabFromLayoutArea(LtsWidgets::LayoutArea::eSpecialTab); + LtsWidgets::LtsTabWidget* dialogTab = getTabFromLayoutArea(LtsWidgets::LayoutArea::eDialogTab); - m_oldLayoutVisibilityStates.insert(infoTab, infoTab->isVisible()); - m_oldLayoutVisibilityStates.insert(specialTab, specialTab->isVisible()); - m_oldLayoutVisibilityStates.insert(dialogTab, dialogTab->isVisible()); + m_oldLayoutVisibilityStates.insert(infoTab, infoTab->isVisible()); + m_oldLayoutVisibilityStates.insert(specialTab, specialTab->isVisible()); + m_oldLayoutVisibilityStates.insert(dialogTab, dialogTab->isVisible()); - - if (infoTab->isVisible()) - infoTab->setVisible(false); - if (specialTab->isVisible()) - specialTab->setVisible(false); - if (dialogTab->isVisible()) - dialogTab->setVisible(false); + if (infoTab->isVisible()) + infoTab->setVisible(false); + if (specialTab->isVisible()) + specialTab->setVisible(false); + if (dialogTab->isVisible()) + dialogTab->setVisible(false); } - void LtsBaseLayoutWidget::setTopBarVisible(bool visible) { - m_ui->topLayoutWidget->setVisible(visible); + m_ui->topLayoutWidget->setVisible(visible); } - bool LtsBaseLayoutWidget::isTopBarVisible() const { - return m_ui->topLayoutWidget->isVisible(); + return m_ui->topLayoutWidget->isVisible(); } - bool LtsBaseLayoutWidget::isMenuCollapsed() const { - return m_menuCollapsed; + return m_menuCollapsed; } - void LtsBaseLayoutWidget::setMenuVisible(bool visible) { - m_ui->rightSplitter->setVisible(visible); + m_ui->rightSplitter->setVisible(visible); } - bool LtsBaseLayoutWidget::isMenuVisible() const { - return m_ui->rightSplitter->isVisible(); + return m_ui->rightSplitter->isVisible(); } - void LtsBaseLayoutWidget::collapseMenu(bool collapse) { - m_menuCollapsed = collapse; - if (collapse) - { - m_ui->masterSplitter->setSizes(m_menuSplitterSizes); - } - else - { - m_menuSplitterSizes = m_ui->masterSplitter->sizes(); - m_ui->masterSplitter->setSizes(QList() << 1 << 0 ); - } + m_menuCollapsed = collapse; + if (collapse) + { + m_ui->masterSplitter->setSizes(m_menuSplitterSizes); + } + else + { + m_menuSplitterSizes = m_ui->masterSplitter->sizes(); + m_ui->masterSplitter->setSizes(QList() << 1 << 0); + } } - void LtsBaseLayoutWidget::onReShowAnimated() { - QPropertyAnimation *animation = new QPropertyAnimation(m_ui->mainSplitter, "sizes", this); - animation->setDuration(500); - + QPropertyAnimation* animation = new QPropertyAnimation(m_ui->mainSplitter, "sizes", this); + animation->setDuration(500); - QList start = m_mainSplitterSizes; - start[getIndexOfTab(getTabFromLayoutArea(LayoutArea::eDialogTab))] = 0; + QList start = m_mainSplitterSizes; + start[getIndexOfTab(getTabFromLayoutArea(LayoutArea::eDialogTab))] = 0; - QList end = m_mainSplitterSizes; + QList end = m_mainSplitterSizes; - animation->setStartValue(QVariant::fromValue(start)); - animation->setEndValue(QVariant::fromValue(end)); + animation->setStartValue(QVariant::fromValue(start)); + animation->setEndValue(QVariant::fromValue(end)); - connect(animation, &QPropertyAnimation::finished, this, [this]() { m_currentAnimation = nullptr; }); + connect(animation, &QPropertyAnimation::finished, this, [this]() { m_currentAnimation = nullptr; }); - m_ui->detailWidget->show(); - animation->start(QAbstractAnimation::DeleteWhenStopped); - m_isHidden = false; + m_ui->detailWidget->show(); + animation->start(QAbstractAnimation::DeleteWhenStopped); + m_isHidden = false; - delete m_currentAnimation; - m_currentAnimation = animation; + delete m_currentAnimation; + m_currentAnimation = animation; } - void LtsBaseLayoutWidget::onHideAnimated() { - if (m_currentAnimation) - { - delete m_currentAnimation; - m_currentAnimation = nullptr; - } + if (m_currentAnimation) + { + delete m_currentAnimation; + m_currentAnimation = nullptr; + } - QPropertyAnimation *animation = new QPropertyAnimation(m_ui->mainSplitter, "sizes", this); - animation->setDuration(500); - - m_mainSplitterSizes = m_ui->mainSplitter->sizes(); - QList start = m_ui->mainSplitter->sizes(); + QPropertyAnimation* animation = new QPropertyAnimation(m_ui->mainSplitter, "sizes", this); + animation->setDuration(500); - QList end = start; - end[getIndexOfTab(getTabFromLayoutArea(LayoutArea::eDialogTab))] = 1; + m_mainSplitterSizes = m_ui->mainSplitter->sizes(); + QList start = m_ui->mainSplitter->sizes(); - animation->setStartValue(QVariant::fromValue(start)); - animation->setEndValue(QVariant::fromValue(end)); - connect(animation, &QPropertyAnimation::finished, this, &LtsBaseLayoutWidget::hideWidgets); - connect(animation, &QPropertyAnimation::finished, this, [this]() { m_currentAnimation = nullptr; }); + QList end = start; + end[getIndexOfTab(getTabFromLayoutArea(LayoutArea::eDialogTab))] = 1; - animation->start(QAbstractAnimation::DeleteWhenStopped); - m_isHidden = true; - m_currentAnimation = animation; + animation->setStartValue(QVariant::fromValue(start)); + animation->setEndValue(QVariant::fromValue(end)); + connect(animation, &QPropertyAnimation::finished, this, &LtsBaseLayoutWidget::hideWidgets); + connect(animation, &QPropertyAnimation::finished, this, [this]() { m_currentAnimation = nullptr; }); + + animation->start(QAbstractAnimation::DeleteWhenStopped); + m_isHidden = true; + m_currentAnimation = animation; } - void LtsBaseLayoutWidget::retranslate() { - emit signalRetranslateActions(); - setExerciseData(m_exerciseData); - m_ui->retranslateUi(this); - + emit signalRetranslateActions(); + setExerciseData(m_exerciseData); + m_ui->retranslateUi(this); } - -void LtsBaseLayoutWidget::changeEvent(QEvent *e) +void LtsBaseLayoutWidget::changeEvent(QEvent* e) { - QWidget::changeEvent(e); - if (e->type() == QEvent::LanguageChange) - retranslate(); + QWidget::changeEvent(e); + if (e->type() == QEvent::LanguageChange) + retranslate(); } - -int LtsBaseLayoutWidget::getIndexOfTab(LtsTabWidget *tab) +int LtsBaseLayoutWidget::getIndexOfTab(LtsTabWidget* tab) { - int result = 0; + int result = 0; - result = m_ui->masterSplitter->indexOf(tab); + result = m_ui->masterSplitter->indexOf(tab); - if (result > -1) + if (result > -1) + return result; + + result = m_ui->mainSplitter->indexOf(tab); + + if (result > -1) + return result; + + result = m_ui->rightSplitter->indexOf(tab); + + if (result > -1) + return result; + + qWarning() << "LtsBaseLayoutWidget::getIndexOfTab: tab not found in any splitter.."; return result; - - - - result = m_ui->mainSplitter->indexOf(tab); - - if (result > -1) - return result; - - - - result = m_ui->rightSplitter->indexOf(tab); - - if (result > -1) - return result; - - - qWarning() << "LtsBaseLayoutWidget::getIndexOfTab: tab not found in any splitter.."; - return result; } - -LtsToolBox* LtsBaseLayoutWidget::getToolBox(const ExercisePart &exercisePart) const +LtsToolBox* LtsBaseLayoutWidget::getToolBox(const ExercisePart& exercisePart) const { - switch (exercisePart) - { - case ExercisePart::eAfterAction: - return m_ui->naviActionsAfterAction; - case ExercisePart::eExecution: - return m_ui->naviActionsExecution; - case ExercisePart::ePlanning: - return m_ui->naviActionsPlanning; - case ExercisePart::eSpecial: - return m_ui->naviActionsSpecial; - } - Q_ASSERT(false); - return nullptr; + switch (exercisePart) + { + case ExercisePart::eAfterAction: + return m_ui->naviActionsAfterAction; + case ExercisePart::eExecution: + return m_ui->naviActionsExecution; + case ExercisePart::ePlanning: + return m_ui->naviActionsPlanning; + case ExercisePart::eSpecial: + return m_ui->naviActionsSpecial; + } + Q_ASSERT(false); + return nullptr; } - -QPushButton* LtsBaseLayoutWidget::getExercisePartButton(const ExercisePart &exercisePart) const +QPushButton* LtsBaseLayoutWidget::getExercisePartButton(const ExercisePart& exercisePart) const { - switch (exercisePart) - { - case ExercisePart::eAfterAction: - return m_ui->pbAfterAction; - case ExercisePart::eExecution: - return m_ui->pbExecution; - case ExercisePart::ePlanning: - return m_ui->pbPlanning; - case ExercisePart::eSpecial: - return m_ui->pbSpecial; - } - Q_ASSERT(false); - return nullptr; + switch (exercisePart) + { + case ExercisePart::eAfterAction: + return m_ui->pbAfterAction; + case ExercisePart::eExecution: + return m_ui->pbExecution; + case ExercisePart::ePlanning: + return m_ui->pbPlanning; + case ExercisePart::eSpecial: + return m_ui->pbSpecial; + } + Q_ASSERT(false); + return nullptr; } - -void LtsBaseLayoutWidget::checkMenuGroup(const QString &menuGroup, const ExercisePart &exercisePart) +void LtsBaseLayoutWidget::checkMenuGroup(const QString& menuGroup, const ExercisePart& exercisePart) { - QWidget *tmpW = getToolBox(exercisePart)->findChild(menuGroup); - if (!tmpW) - return; + QWidget* tmpW = getToolBox(exercisePart)->findChild(menuGroup); + if (!tmpW) + return; #ifdef NEVER_PRINT_DEBUG - for (int i = 0; i < tmpW->children().size(); i++) - { - QObject * whatEver = tmpW->children().at( i ); - const QString & name = whatEver->objectName(); - qCritical() << "MenuGroup child " << i << " : " << name; - } + for (int i = 0; i < tmpW->children().size(); i++) + { + QObject* whatEver = tmpW->children().at(i); + const QString& name = whatEver->objectName(); + qCritical() << "MenuGroup child " << i << " : " << name; + } #endif - - - - - if (tmpW->children().size() <= 1) - delete tmpW; - checkExercisePartButtonVisibility(); + if (tmpW->children().size() <= 1) + delete tmpW; + checkExercisePartButtonVisibility(); } - void LtsBaseLayoutWidget::checkExercisePartButtonVisibility() { - if (nullptr == m_bg) - { + if (nullptr == m_bg) + { + for (int ep = (int)ExercisePart::ePlanning; ep <= (int)ExercisePart::eSpecial; ++ep) + { + getExercisePartButton(static_cast(ep))->setVisible(false); + } + return; + } + + int visibleButtons = 0; + ExercisePart lastVisibleButton = ExercisePart::ePlanning; for (int ep = (int)ExercisePart::ePlanning; ep <= (int)ExercisePart::eSpecial; ++ep) { - getExercisePartButton(static_cast(ep))->setVisible(false); + bool visible = getToolBox((ExercisePart)ep)->children().count() > 1; + getExercisePartButton((ExercisePart)ep)->setVisible(visible); + if (visible) + { + ++visibleButtons; + lastVisibleButton = (ExercisePart)ep; + } } - return; - } - - int visibleButtons = 0; - ExercisePart lastVisibleButton = ExercisePart::ePlanning; - for (int ep = (int) ExercisePart::ePlanning; ep <= (int) ExercisePart::eSpecial; ++ep) - { - bool visible = getToolBox((ExercisePart) ep)->children().count() > 1; - getExercisePartButton((ExercisePart) ep)->setVisible(visible); - if (visible) - { - ++visibleButtons; - lastVisibleButton = (ExercisePart) ep; - } - } - if (visibleButtons == 0) - lastVisibleButton = ExercisePart::eSpecial; - getExercisePartButton(lastVisibleButton)->setChecked(true); - getExercisePartButton(lastVisibleButton)->setVisible(visibleButtons > 1); + if (visibleButtons == 0) + lastVisibleButton = ExercisePart::eSpecial; + getExercisePartButton(lastVisibleButton)->setChecked(true); + getExercisePartButton(lastVisibleButton)->setVisible(visibleButtons > 1); } - bool LtsBaseLayoutWidget::isWidgetsHidden() const { - return m_ui->detailWidget->isVisible(); + return m_ui->detailWidget->isVisible(); } - void LtsBaseLayoutWidget::showWidgets() { - m_ui->detailWidget->show(); + m_ui->detailWidget->show(); } - void LtsBaseLayoutWidget::hideWidgets() { - m_ui->detailWidget->hide(); + m_ui->detailWidget->hide(); } - -LtsDragIcon *LtsBaseLayoutWidget::createButton(const PluginData &plData) +LtsDragIcon* LtsBaseLayoutWidget::createButton(const PluginData& plData) { - - LtsDragIcon *tmpBtn = new LtsDragIcon(nullptr); - tmpBtn->setObjectName(plData.identifier); - tmpBtn->setButtonStyle(LtsWidgets::ButtonStyle::eTextNextToIcon); - tmpBtn->setIcon(plData.menuIcon); - tmpBtn->setContext(plData.menuGroup); - tmpBtn->setText(plData.menuText); - if (!plData.tooltip.isEmpty()) - tmpBtn->setToolTip(plData.tooltip); - tmpBtn->setDropHandlerKey(plData.dropHandlerKey); - tmpBtn->setIdentifier(plData.identifier); - connect(tmpBtn, &QWidget::destroyed, - this, []() - { - qDebug() << "LtsDragIcon was destroyed"; - }); + LtsDragIcon* tmpBtn = new LtsDragIcon(nullptr); + tmpBtn->setObjectName(plData.identifier); + tmpBtn->setButtonStyle(LtsWidgets::ButtonStyle::eTextNextToIcon); + tmpBtn->setIcon(plData.menuIcon); + tmpBtn->setContext(plData.menuGroup); + tmpBtn->setText(plData.menuText); + if (!plData.tooltip.isEmpty()) + tmpBtn->setToolTip(plData.tooltip); + tmpBtn->setDropHandlerKey(plData.dropHandlerKey); + tmpBtn->setIdentifier(plData.identifier); - connect(tmpBtn, &LtsDragIcon::clicked, this, &LtsBaseLayoutWidget::onMenuEntryClicked); - return tmpBtn; + connect(tmpBtn, &QWidget::destroyed, this, []() { qDebug() << "LtsDragIcon was destroyed"; }); + + connect(tmpBtn, &LtsDragIcon::clicked, this, &LtsBaseLayoutWidget::onMenuEntryClicked); + return tmpBtn; } - -LtsToolBarArea * LtsBaseLayoutWidget::getToolbar() const +LtsToolBarArea* LtsBaseLayoutWidget::getToolbar() const { - return m_ui->toolBar; + return m_ui->toolBar; } - -QWidget *LtsBaseLayoutWidget::getMenu() const +QWidget* LtsBaseLayoutWidget::getMenu() const { - return m_ui->naviWidget; + return m_ui->naviWidget; } - -LtsTabWidget *LtsBaseLayoutWidget::getTabFromLayoutArea(LayoutArea area) const +LtsTabWidget* LtsBaseLayoutWidget::getTabFromLayoutArea(LayoutArea area) const { - switch (area) - { - case LayoutArea::eDialogTab: - return m_ui->detailWidget; - case LayoutArea::eInfoTab: - return m_ui->infoWidget; - case LayoutArea::eSpecialTab: - return m_ui->specialWidget; - case LayoutArea::eMainTab: - return m_ui->mainWidget; - case LayoutArea::eUnknown: - return m_ui->detailWidget; - } - return nullptr; + switch (area) + { + case LayoutArea::eDialogTab: + return m_ui->detailWidget; + case LayoutArea::eInfoTab: + return m_ui->infoWidget; + case LayoutArea::eSpecialTab: + return m_ui->specialWidget; + case LayoutArea::eMainTab: + return m_ui->mainWidget; + case LayoutArea::eUnknown: + return m_ui->detailWidget; + } + return nullptr; } - void LtsBaseLayoutWidget::showNextQueuedMessage() { - if (m_messageQueue.isEmpty()) - { - return; - } - - const Message m = m_messageQueue.takeLast(); - - showMessage(m.title, m.text, m.type, m.clickedLinkCallback, m.closeOnLinkClicked, m.identifier); -} - - -void LtsBaseLayoutWidget::removeQueuedMessage(const QString &messageIdentifier) -{ - if (messageIdentifier.isEmpty()) - { - return; - } - - m_messageQueue.erase(std::remove_if(m_messageQueue.begin(), m_messageQueue.end(), [messageIdentifier](const Message &m) - { - return (m.identifier == messageIdentifier); - }), m_messageQueue.end()); - - if (!m_currentMessage.isEmpty()) - { - if (m_currentMessage.first().identifier == messageIdentifier) + if (m_messageQueue.isEmpty()) { - - m_currentMessage.clear(); - m_notiBox->hide(); - showNextQueuedMessage(); + return; } - } + + const Message m = m_messageQueue.takeLast(); + + showMessage(m.title, m.text, m.type, m.clickedLinkCallback, m.closeOnLinkClicked, m.identifier); } - -void LtsBaseLayoutWidget::showMessage(const QString &title, const QString &text, LtsNotificationBox::MessageType type, const std::function &clickedLinkCallback, bool closeOnLinkClicked, const QString &identifier) +void LtsBaseLayoutWidget::removeQueuedMessage(const QString& messageIdentifier) { - if (m_notiBox == nullptr) - { - m_notiBox = new LtsNotificationBox; - - connect(m_notiBox, &LtsNotificationBox::signalLinkClicked, - this, [this, closeOnLinkClicked, clickedLinkCallback](const QString &link) + if (messageIdentifier.isEmpty()) { - - - auto *event = new LtsLinkEvent(QUrl(link), this); - event->setAccepted(false); - QApplication::postEvent(qApp, event); - - if (clickedLinkCallback) - clickedLinkCallback(link); - - if (closeOnLinkClicked) - { - m_notiBox->hide(); - m_currentMessage.clear(); - showNextQueuedMessage(); - } - }); - - connect(m_notiBox, &QObject::destroyed, - this, [this]() - { - if (qobject_cast(sender()) == m_notiBox) - m_notiBox = nullptr; - }); - - connect(m_notiBox, &LtsNotificationBox::signalClose, - this, [this]() - { - m_notiBox->hide(); - m_currentMessage.clear(); - showNextQueuedMessage(); - }); - - connect(m_notiBox, &LtsNotificationBox::signalAck, - this, [this]() - { - auto *event = new LtsLinkEvent(QUrl(QStringLiteral("lts://NotificationAck/%1").arg(m_currentMessage.first().identifier)), this); - event->setAccepted(false); - QApplication::postEvent(qApp, event); - - m_notiBox->hide(); - m_currentMessage.clear(); - showNextQueuedMessage(); - }); - - m_notiBox->setParent(this); - m_notiBox->setGeometry(0, 0, m_notiBox->width(), m_notiBox->height()); - } - - - m_messageQueue.erase(std::remove_if(m_messageQueue.begin(), m_messageQueue.end(), [identifier](const Message &m) - { - return (!identifier.isEmpty() && m.identifier == identifier); - }), m_messageQueue.end()); - - if (!m_currentMessage.isEmpty()) - { - const auto m = m_currentMessage.takeFirst(); - if (identifier.isEmpty() || m.identifier != identifier) - { - m_messageQueue += m; + return; } - } - m_currentMessage += Message({ title, text, type, clickedLinkCallback, closeOnLinkClicked, identifier }); + m_messageQueue.erase( + std::remove_if(m_messageQueue.begin(), m_messageQueue.end(), + [messageIdentifier](const Message& m) { return (m.identifier == messageIdentifier); }), + m_messageQueue.end()); - m_notiBox->message(title, text, type); + if (!m_currentMessage.isEmpty()) + { + if (m_currentMessage.first().identifier == messageIdentifier) + { - - - auto *animation = new QPropertyAnimation(m_notiBox, "geometry"); - connect(animation, &QPropertyAnimation::finished, animation, &QObject::deleteLater); - animation->setDuration(700); - animation->setStartValue(QRect(width() + 10, height() + 10, m_notiBox->width(), m_notiBox->height())); - animation->setEndValue(QRect(width() - m_notiBox->width() - 15, height() - m_notiBox->height() - 15, m_notiBox->width(), m_notiBox->height())); - animation->setEasingCurve(QEasingCurve::OutElastic); - animation->start(QAbstractAnimation::DeleteWhenStopped); + m_currentMessage.clear(); + m_notiBox->hide(); + showNextQueuedMessage(); + } + } } - -bool LtsBaseLayoutWidget::messageIdentifierExists(const QString &identifier) const +void LtsBaseLayoutWidget::showMessage(const QString& title, const QString& text, LtsNotificationBox::MessageType type, + const std::function& clickedLinkCallback, + bool closeOnLinkClicked, const QString& identifier) { - if (identifier.isEmpty()) - { + if (m_notiBox == nullptr) + { + m_notiBox = new LtsNotificationBox; + + connect(m_notiBox, &LtsNotificationBox::signalLinkClicked, this, + [this, closeOnLinkClicked, clickedLinkCallback](const QString& link) { + auto* event = new LtsLinkEvent(QUrl(link), this); + event->setAccepted(false); + QApplication::postEvent(qApp, event); + + if (clickedLinkCallback) + clickedLinkCallback(link); + + if (closeOnLinkClicked) + { + m_notiBox->hide(); + m_currentMessage.clear(); + showNextQueuedMessage(); + } + }); + + connect(m_notiBox, &QObject::destroyed, this, [this]() { + if (qobject_cast(sender()) == m_notiBox) + m_notiBox = nullptr; + }); + + connect(m_notiBox, &LtsNotificationBox::signalClose, this, [this]() { + m_notiBox->hide(); + m_currentMessage.clear(); + showNextQueuedMessage(); + }); + + connect(m_notiBox, &LtsNotificationBox::signalAck, this, [this]() { + auto* event = new LtsLinkEvent( + QUrl(QStringLiteral("lts://NotificationAck/%1").arg(m_currentMessage.first().identifier)), this); + event->setAccepted(false); + QApplication::postEvent(qApp, event); + + m_notiBox->hide(); + m_currentMessage.clear(); + showNextQueuedMessage(); + }); + + m_notiBox->setParent(this); + m_notiBox->setGeometry(0, 0, m_notiBox->width(), m_notiBox->height()); + } + + m_messageQueue.erase(std::remove_if(m_messageQueue.begin(), m_messageQueue.end(), + [identifier](const Message& m) { + return (!identifier.isEmpty() && m.identifier == identifier); + }), + m_messageQueue.end()); + + if (!m_currentMessage.isEmpty()) + { + const auto m = m_currentMessage.takeFirst(); + if (identifier.isEmpty() || m.identifier != identifier) + { + m_messageQueue += m; + } + } + + m_currentMessage += Message({title, text, type, clickedLinkCallback, closeOnLinkClicked, identifier}); + + m_notiBox->message(title, text, type); + + auto* animation = new QPropertyAnimation(m_notiBox, "geometry"); + connect(animation, &QPropertyAnimation::finished, animation, &QObject::deleteLater); + animation->setDuration(700); + animation->setStartValue(QRect(width() + 10, height() + 10, m_notiBox->width(), m_notiBox->height())); + animation->setEndValue(QRect(width() - m_notiBox->width() - 15, height() - m_notiBox->height() - 15, + m_notiBox->width(), m_notiBox->height())); + animation->setEasingCurve(QEasingCurve::OutElastic); + animation->start(QAbstractAnimation::DeleteWhenStopped); +} + +bool LtsBaseLayoutWidget::messageIdentifierExists(const QString& identifier) const +{ + if (identifier.isEmpty()) + { + return false; + } + + if (!m_currentMessage.isEmpty() && m_currentMessage.first().identifier == identifier) + { + return true; + } + + for (const Message& m : std::as_const(m_messageQueue)) + { + if (m.identifier == identifier) + { + return true; + } + } + return false; - } - - if (!m_currentMessage.isEmpty() && m_currentMessage.first().identifier == identifier) - { - return true; - } - - for (const Message &m : std::as_const(m_messageQueue)) - { - if (m.identifier == identifier) - { - return true; - } - } - - return false; } -} - - - - - - - - - - - - - - - - - - - - +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_column_filter_proxy_model.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_column_filter_proxy_model.h old mode 100755 new mode 100644 index 864de9ff8..948c89fa3 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_column_filter_proxy_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_column_filter_proxy_model.h @@ -1,123 +1,133 @@ - #pragma once -#include - #include "ltswidgets_export.h" -#include +#include #include +#include #include +#include #include #include #include - namespace LtsWidgets { struct ComboboxFilterData { - QString text; - QVariant data; - QIcon icon; + QString text; + QVariant data; + QIcon icon; - inline bool operator<(const ComboboxFilterData &cfd) - { - return LtsUtils::lessThan(data, cfd.data); - } - inline friend QDataStream &operator<<(QDataStream &ds, const ComboboxFilterData &cfd) - { - ds << cfd.text << cfd.data << cfd.icon; - return ds; - } - inline friend QDataStream &operator>>(QDataStream &ds, ComboboxFilterData &cfd) - { - ds >> cfd.text >> cfd.data >> cfd.icon; - return ds; - } + inline bool operator<(const ComboboxFilterData& cfd) + { + return LtsUtils::lessThan(data, cfd.data); + } + + inline friend QDataStream& operator<<(QDataStream& ds, const ComboboxFilterData& cfd) + { + ds << cfd.text << cfd.data << cfd.icon; + return ds; + } + + inline friend QDataStream& operator>>(QDataStream& ds, ComboboxFilterData& cfd) + { + ds >> cfd.text >> cfd.data >> cfd.icon; + return ds; + } }; - struct ComboboxFilterContent { - QVector data; - bool sortItems = false; - bool isValid() const { return m_isValid; } + QVector data; + bool sortItems = false; - QVariant toVariant() const - { - if (!isValid()) - return QVariant(); - QByteArray ba; - QDataStream ds(&ba, QIODevice::WriteOnly); - ds << (*this); - return ba; - } + bool isValid() const + { + return m_isValid; + } - static ComboboxFilterContent fromVariant(const QVariant &v) - { - ComboboxFilterContent ret; - QDataStream ds(v.toByteArray()); - ds.startTransaction(); - ds >> ret; - ds.commitTransaction(); - ret.m_isValid = ds.status() == QDataStream::Ok; + QVariant toVariant() const + { + if (!isValid()) + return QVariant(); + QByteArray ba; + QDataStream ds(&ba, QIODevice::WriteOnly); + ds << (*this); + return ba; + } - return ret; - } + static ComboboxFilterContent fromVariant(const QVariant& v) + { + ComboboxFilterContent ret; + QDataStream ds(v.toByteArray()); + ds.startTransaction(); + ds >> ret; + ds.commitTransaction(); + ret.m_isValid = ds.status() == QDataStream::Ok; - inline friend QDataStream &operator<<(QDataStream &ds, const ComboboxFilterContent &cfc) - { - ds << cfc.data << cfc.sortItems; - return ds; - } - inline friend QDataStream &operator>>(QDataStream &ds, ComboboxFilterContent &cfc) - { - ds >> cfc.data >> cfc.sortItems; - return ds; - } + return ret; + } -private: - bool m_isValid = true; + inline friend QDataStream& operator<<(QDataStream& ds, const ComboboxFilterContent& cfc) + { + ds << cfc.data << cfc.sortItems; + return ds; + } + + inline friend QDataStream& operator>>(QDataStream& ds, ComboboxFilterContent& cfc) + { + ds >> cfc.data >> cfc.sortItems; + return ds; + } + + private: + bool m_isValid = true; }; - class LTSWIDGETS_EXPORT LtsColumnFilterProxyModel : public QSortFilterProxyModel { - Q_OBJECT -public: - static constexpr int ComboboxFilterRole = Qt::UserRole + 17; + Q_OBJECT + public: + static constexpr int ComboboxFilterRole = Qt::UserRole + 17; - explicit LtsColumnFilterProxyModel(QObject *parent = nullptr); + explicit LtsColumnFilterProxyModel(QObject* parent = nullptr); #if QT_VERSION < QT_VERSION_CHECK(5, 10, 0) - void setRecursiveFilteringEnabled(bool recursive); - bool recursiveFilteringEnabled() const; + void setRecursiveFilteringEnabled(bool recursive); + bool recursiveFilteringEnabled() const; #endif - const QHash &columnStringFilters() const { return m_columnStringFilters; } - const QHash &columnDataFilters() const { return m_columnDataFilters; } + const QHash& columnStringFilters() const + { + return m_columnStringFilters; + } - bool lessThan(const QModelIndex &left, const QModelIndex &right) const override; + const QHash& columnDataFilters() const + { + return m_columnDataFilters; + } - virtual void setColumnStringFilter(const QString &newFilterString, int column); - virtual void setColumnDataFilter(const QVariant &newFilterData, int column); + bool lessThan(const QModelIndex& left, const QModelIndex& right) const override; -public slots: - void onSetColumnStringFilter(const QString &newFilterString, int column); - void onSetColumnDataFilter(const QVariant &newFilterData, int column); + virtual void setColumnStringFilter(const QString& newFilterString, int column); + virtual void setColumnDataFilter(const QVariant& newFilterData, int column); -protected: - virtual bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override; + public slots: + void onSetColumnStringFilter(const QString& newFilterString, int column); + void onSetColumnDataFilter(const QVariant& newFilterData, int column); + + protected: + virtual bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const override; #if QT_VERSION < QT_VERSION_CHECK(5, 10, 0) - bool checkIfOneChildIsVisible(const QModelIndex &parent) const; + bool checkIfOneChildIsVisible(const QModelIndex& parent) const; #endif -private: - QHash m_columnStringFilters; - QHash m_columnDataFilters; + private: + QHash m_columnStringFilters; + QHash m_columnDataFilters; #if QT_VERSION < QT_VERSION_CHECK(5, 10, 0) - bool m_bRecursiveFiltering = false; + bool m_bRecursiveFiltering = false; #endif }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_combo_box.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_combo_box.cpp old mode 100755 new mode 100644 index ccbd3bea6..30d20f081 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_combo_box.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_combo_box.cpp @@ -1,118 +1,99 @@ - #include "lts_combo_box.h" -#include "lts_selection_popup.h" + #include "lts_message_dialog.h" +#include "lts_selection_popup.h" #include #include - #ifdef NEVER -# include -#endif +#include +#endif namespace LtsWidgets { bool LtsComboBox::s_useSelectionDialog = false; -LtsComboBox::LtsComboBox(QWidget *parent) - : QComboBox(parent) - , m_currentIndex(-1) +LtsComboBox::LtsComboBox(QWidget* parent) : QComboBox(parent), m_currentIndex(-1) { - connect(this, &LtsComboBox::signalExternallyChanged, - this, &LtsComboBox::signalRefill); + connect(this, &LtsComboBox::signalExternallyChanged, this, &LtsComboBox::signalRefill); } void LtsComboBox::setUseSelectionDialog(bool bUseSelectionDialog) { - s_useSelectionDialog = bUseSelectionDialog; + s_useSelectionDialog = bUseSelectionDialog; } -void LtsComboBox::showEvent(QShowEvent *e) +void LtsComboBox::showEvent(QShowEvent* e) { - QComboBox::showEvent(e); + QComboBox::showEvent(e); - m_currentIndex = currentIndex(); + m_currentIndex = currentIndex(); } -void LtsComboBox::enterEvent(QEvent *e) +void LtsComboBox::enterEvent(QEnterEvent* e) { - BaseClass::enterEvent(e); - emit signalEnterEvent(); + BaseClass::enterEvent(e); + emit signalEnterEvent(); } -void LtsComboBox::leaveEvent(QEvent *e) +void LtsComboBox::leaveEvent(QEvent* e) { - BaseClass::leaveEvent(e); - emit signalLeaveEvent(); + BaseClass::leaveEvent(e); + emit signalLeaveEvent(); } void LtsComboBox::showPopup() { - bool bUseSelectionDialog = s_useSelectionDialog; - if (QGuiApplication::queryKeyboardModifiers() == Qt::ControlModifier) - bUseSelectionDialog = !bUseSelectionDialog; - if (!bUseSelectionDialog) - { - QComboBox::showPopup(); - return; - } + bool bUseSelectionDialog = s_useSelectionDialog; + if (QGuiApplication::queryKeyboardModifiers() == Qt::ControlModifier) + bUseSelectionDialog = !bUseSelectionDialog; + if (!bUseSelectionDialog) + { + QComboBox::showPopup(); + return; + } - if (!model()->rowCount()) - { - LtsWidgets::LtsMessageDialog::showMessage(this, tr("There are no items available!")); - return; - } + if (!model()->rowCount()) + { + LtsWidgets::LtsMessageDialog::showMessage(this, tr("There are no items available!")); + return; + } - - LtsSelectionPopup* popup = new LtsSelectionPopup(model(), currentIndex(), this); - popup->setAttribute(Qt::WA_DeleteOnClose); + LtsSelectionPopup* popup = new LtsSelectionPopup(model(), currentIndex(), this); + popup->setAttribute(Qt::WA_DeleteOnClose); #ifdef NEVER - - + connect(popup, static_cast(&LtsSelectionPopup::currentIndexChanged), this, + [](int idx) { qCritical() << " LtsComboBox: called: currentIndexChanged(int), idx=" << idx; }); + connect(popup, static_cast(&LtsSelectionPopup::activated), this, + [](int idx) { qCritical() << " LtsComboBox: called: activated(int), idx=" << idx; }); +#endif - - connect(popup, static_cast(&LtsSelectionPopup::currentIndexChanged), this, [](int idx){ - qCritical() << " LtsComboBox: called: currentIndexChanged(int), idx=" << idx; - }); + connect(popup, &LtsSelectionPopup::currentIndexChanged, this, &LtsComboBox::userChangedIndex); + connect(popup, &LtsSelectionPopup::activated, this, + static_cast(&LtsComboBox::activated)); - - connect(popup, static_cast(&LtsSelectionPopup::activated), this, [](int idx){ - qCritical() << " LtsComboBox: called: activated(int), idx=" << idx; - }); - -#endif - - - - connect(popup, &LtsSelectionPopup::currentIndexChanged, - this, &LtsComboBox::userChangedIndex); - connect(popup, &LtsSelectionPopup::activated, - this, static_cast(&LtsComboBox::activated)); - - popup->show(); + popup->show(); } - void LtsComboBox::userChangedIndex(int index) { - m_currentIndex = index; - setCurrentIndex(index); + m_currentIndex = index; + setCurrentIndex(index); } - bool LtsComboBox::hasValueChanged() const { - if (m_currentIndex == -1) - return false; - return !(currentIndex() == m_currentIndex); + if (m_currentIndex == -1) + return false; + return !(currentIndex() == m_currentIndex); } -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_combo_box.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_combo_box.h old mode 100755 new mode 100644 index 9c6691c22..6ab01e5dc --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_combo_box.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_combo_box.h @@ -1,60 +1,56 @@ - #pragma once -#include - #include "ltswidgets_export.h" #include - +#include namespace LtsWidgets { - - -class LTSWIDGETS_EXPORT LtsComboBox : public QComboBox +class LTSWIDGETS_EXPORT LtsComboBox : public QComboBox { - Q_OBJECT - using BaseClass = QComboBox; + Q_OBJECT + using BaseClass = QComboBox; -public: - explicit LtsComboBox(QWidget *parent = nullptr); - ~LtsComboBox() = default; + public: + explicit LtsComboBox(QWidget* parent = nullptr); + ~LtsComboBox() = default; - + static void setUseSelectionDialog(bool bUseSelectionDialog); - static void setUseSelectionDialog(bool bUseSelectionDialog); + bool hasValueChanged() const; - + void setExternalContentType(int ect) + { + m_externalContentType = ect; + } - bool hasValueChanged() const; + int externalContentType() const + { + return m_externalContentType; + } - void setExternalContentType(int ect) { m_externalContentType = ect; } - int externalContentType() const { return m_externalContentType; } + protected: + void showPopup() override; -protected: - + void showEvent(QShowEvent* e) override; + void enterEvent(QEnterEvent* e) override; + void leaveEvent(QEvent*) override; - void showPopup() override; + protected slots: + void userChangedIndex(int index); - void showEvent(QShowEvent *e) override; - void enterEvent(QEvent *e) override; - void leaveEvent(QEvent *) override; + signals: + void signalExternallyChanged(); + void signalRefill(); + void signalEnterEvent(); + void signalLeaveEvent(); -protected slots: - void userChangedIndex(int index); - -signals: - void signalExternallyChanged(); - void signalRefill(); - void signalEnterEvent(); - void signalLeaveEvent(); - -private: - int m_currentIndex; - int m_externalContentType; - static bool s_useSelectionDialog; + private: + int m_currentIndex; + int m_externalContentType; + static bool s_useSelectionDialog; }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit.cpp old mode 100755 new mode 100644 index 3883680cb..da2793261 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit.cpp @@ -1,17 +1,11 @@ - #include "lts_date_time_edit.h" -#include -#include "lts_date_time_edit_p.h" +#include "lts_date_time_edit_p.h" #include "ui_lts_date_time_edit_touch.h" - #include - -#include - #include #include #include @@ -25,1762 +19,1697 @@ #include #include #include +#include +#include static constexpr qint64 s_oneSecondMSec = 1000LL; static constexpr qint64 s_oneMinuteMSec = 60 * s_oneSecondMSec; -static constexpr qint64 s_oneHourMSec = 60 * s_oneMinuteMSec; -static constexpr qint64 s_oneDayMSec = 24 * s_oneHourMSec; +static constexpr qint64 s_oneHourMSec = 60 * s_oneMinuteMSec; +static constexpr qint64 s_oneDayMSec = 24 * s_oneHourMSec; namespace Ui { class LtsDateTimeEditLe { -public: - LtsWidgets::DigitsLineEdit *leLongDay = nullptr; - LtsWidgets::DigitsLineEdit *leLongHHMMSS = nullptr; - LtsWidgets::LineEdit *leLongTZ = nullptr; - LtsWidgets::DigitsLineEdit *leLongMonth = nullptr; - LtsWidgets::DigitsLineEdit *leLongYear = nullptr; - QCheckBox *checkBox = nullptr; - QGridLayout *gridLayout = nullptr; - QPushButton *pbBBB = nullptr; - QPushButton *pbBB = nullptr; - QPushButton *pbB = nullptr; - QPushButton *pbF = nullptr; - QPushButton *pbFF = nullptr; - QPushButton *pbFFF = nullptr; - QPushButton *pbNow = nullptr; - QSlider *slTime = nullptr; + public: + LtsWidgets::DigitsLineEdit* leLongDay = nullptr; + LtsWidgets::DigitsLineEdit* leLongHHMMSS = nullptr; + LtsWidgets::LineEdit* leLongTZ = nullptr; + LtsWidgets::DigitsLineEdit* leLongMonth = nullptr; + LtsWidgets::DigitsLineEdit* leLongYear = nullptr; + QCheckBox* checkBox = nullptr; + QGridLayout* gridLayout = nullptr; + QPushButton* pbBBB = nullptr; + QPushButton* pbBB = nullptr; + QPushButton* pbB = nullptr; + QPushButton* pbF = nullptr; + QPushButton* pbFF = nullptr; + QPushButton* pbFFF = nullptr; + QPushButton* pbNow = nullptr; + QSlider* slTime = nullptr; - static void setFixedSize(QLineEdit *le, int charCount) - { - QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); - sizePolicy.setVerticalStretch(0); - sizePolicy.setHeightForWidth(false); + static void setFixedSize(QLineEdit* le, int charCount) + { + QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); + sizePolicy.setVerticalStretch(0); + sizePolicy.setHeightForWidth(false); - const QFontMetricsF fm(le->font()); - const auto textMargins = le->textMargins(); - le->setSizePolicy(sizePolicy); - charCount += 3; + const QFontMetricsF fm(le->font()); + const auto textMargins = le->textMargins(); + le->setSizePolicy(sizePolicy); + charCount += 3; #if QT_VERSION < QT_VERSION_CHECK(5, 11, 0) - const qreal w = fm.width(QLatin1Char('x')) * charCount + textMargins.left() + textMargins.right(); + const qreal w = fm.width(QLatin1Char('x')) * charCount + textMargins.left() + textMargins.right(); #else - const qreal w = fm.horizontalAdvance(QLatin1Char('x')) * charCount + textMargins.left() + textMargins.right(); + const qreal w = fm.horizontalAdvance(QLatin1Char('x')) * charCount + textMargins.left() + textMargins.right(); #endif - le->setMinimumWidth(w); - le->setMaximumWidth(w); - } + le->setMinimumWidth(w); + le->setMaximumWidth(w); + } - void setupUi(QWidget *parent) - { - gridLayout = new QGridLayout(parent); - gridLayout->setMargin(0); + void setupUi(QWidget* parent) + { + gridLayout = new QGridLayout(parent); + gridLayout->setContentsMargins(0, 0, 0, 0); - int iStart = 3; + int iStart = 3; - checkBox = new QCheckBox; - gridLayout->addWidget(checkBox, 0, iStart++, 1, 1); + checkBox = new QCheckBox; + gridLayout->addWidget(checkBox, 0, iStart++, 1, 1); - auto horizontalLayout = new QHBoxLayout; - horizontalLayout->setSpacing(0); - horizontalLayout->setContentsMargins(0, 0, 0, 0); + auto horizontalLayout = new QHBoxLayout; + horizontalLayout->setSpacing(0); + horizontalLayout->setContentsMargins(0, 0, 0, 0); - leLongDay = new LtsWidgets::DigitsLineEdit(parent); - setFixedSize(leLongDay, 2); - leLongDay->setObjectName(QStringLiteral("leLongDay")); - horizontalLayout->addWidget(leLongDay); + leLongDay = new LtsWidgets::DigitsLineEdit(parent); + setFixedSize(leLongDay, 2); + leLongDay->setObjectName(QStringLiteral("leLongDay")); + horizontalLayout->addWidget(leLongDay); - leLongHHMMSS = new LtsWidgets::DigitsLineEdit(parent); - leLongHHMMSS->setExactNumDigits(6); - setFixedSize(leLongHHMMSS, 6); - leLongHHMMSS->setObjectName(QStringLiteral("leLongHHMMSS")); - horizontalLayout->addWidget(leLongHHMMSS); + leLongHHMMSS = new LtsWidgets::DigitsLineEdit(parent); + leLongHHMMSS->setExactNumDigits(6); + setFixedSize(leLongHHMMSS, 6); + leLongHHMMSS->setObjectName(QStringLiteral("leLongHHMMSS")); + horizontalLayout->addWidget(leLongHHMMSS); - leLongTZ = new LtsWidgets::LineEdit(parent); - leLongTZ->setAlignment(Qt::AlignCenter); - setFixedSize(leLongTZ, 1); - leLongTZ->setObjectName(QStringLiteral("leLongTZ")); - horizontalLayout->addWidget(leLongTZ); + leLongTZ = new LtsWidgets::LineEdit(parent); + leLongTZ->setAlignment(Qt::AlignCenter); + setFixedSize(leLongTZ, 1); + leLongTZ->setObjectName(QStringLiteral("leLongTZ")); + horizontalLayout->addWidget(leLongTZ); - leLongMonth = new LtsWidgets::DigitsLineEdit(parent); - leLongMonth->setAlignment(Qt::AlignCenter); - setFixedSize(leLongMonth, 3); - leLongMonth->setObjectName(QStringLiteral("leLongMonth")); - horizontalLayout->addWidget(leLongMonth); + leLongMonth = new LtsWidgets::DigitsLineEdit(parent); + leLongMonth->setAlignment(Qt::AlignCenter); + setFixedSize(leLongMonth, 3); + leLongMonth->setObjectName(QStringLiteral("leLongMonth")); + horizontalLayout->addWidget(leLongMonth); - leLongYear = new LtsWidgets::DigitsLineEdit(parent); - leLongYear->setExactNumDigits(2); - setFixedSize(leLongYear, 2); - leLongYear->setObjectName(QStringLiteral("leLongYear")); - horizontalLayout->addWidget(leLongYear); + leLongYear = new LtsWidgets::DigitsLineEdit(parent); + leLongYear->setExactNumDigits(2); + setFixedSize(leLongYear, 2); + leLongYear->setObjectName(QStringLiteral("leLongYear")); + horizontalLayout->addWidget(leLongYear); - gridLayout->addLayout(horizontalLayout, 0, iStart++, 1, 1); + gridLayout->addLayout(horizontalLayout, 0, iStart++, 1, 1); - pbNow = new QPushButton(QApplication::translate("LtsDateTimeEdit", "Now", nullptr)); - pbNow->setObjectName(QStringLiteral("pbNow")); - gridLayout->addWidget(pbNow, 0, iStart++, 1, 1); + pbNow = new QPushButton(QApplication::translate("LtsDateTimeEdit", "Now", nullptr)); + pbNow->setObjectName(QStringLiteral("pbNow")); + gridLayout->addWidget(pbNow, 0, iStart++, 1, 1); - QWidget::setTabOrder(checkBox, leLongDay); - QWidget::setTabOrder(leLongDay, leLongHHMMSS); - QWidget::setTabOrder(leLongHHMMSS, leLongTZ); - QWidget::setTabOrder(leLongTZ, leLongMonth); - QWidget::setTabOrder(leLongMonth, leLongYear); - QWidget::setTabOrder(leLongYear, pbNow); + QWidget::setTabOrder(checkBox, leLongDay); + QWidget::setTabOrder(leLongDay, leLongHHMMSS); + QWidget::setTabOrder(leLongHHMMSS, leLongTZ); + QWidget::setTabOrder(leLongTZ, leLongMonth); + QWidget::setTabOrder(leLongMonth, leLongYear); + QWidget::setTabOrder(leLongYear, pbNow); - parent->setFocusProxy(leLongDay); - } + parent->setFocusProxy(leLongDay); + } - static QPushButton *addButton(const QString &text, QWidget *parent) - { - QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + static QPushButton* addButton(const QString& text, QWidget* parent) + { + QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - auto pb = new QPushButton(parent); - pb->setMinimumWidth(27); - pb->setMaximumWidth(27); - pb->setText(text); - sizePolicy.setHorizontalStretch(0); - sizePolicy.setVerticalStretch(0); - sizePolicy.setHeightForWidth(pb->sizePolicy().hasHeightForWidth()); - pb->setSizePolicy(sizePolicy); - return pb; - } + auto pb = new QPushButton(parent); + pb->setMinimumWidth(27); + pb->setMaximumWidth(27); + pb->setText(text); + sizePolicy.setHorizontalStretch(0); + sizePolicy.setVerticalStretch(0); + sizePolicy.setHeightForWidth(pb->sizePolicy().hasHeightForWidth()); + pb->setSizePolicy(sizePolicy); + return pb; + } - void addButtons(QWidget *parent) - { - pbBBB = addButton(QLatin1String("<<<"), parent); - pbBB = addButton(QLatin1String("<<"), parent); - pbB = addButton(QLatin1String("<"), parent); - gridLayout->addWidget(pbBBB, 0, 0, 1, 1); - gridLayout->addWidget(pbBB, 0, 1, 1, 1); - gridLayout->addWidget(pbB, 0, 2, 1, 1); + void addButtons(QWidget* parent) + { + pbBBB = addButton(QLatin1String("<<<"), parent); + pbBB = addButton(QLatin1String("<<"), parent); + pbB = addButton(QLatin1String("<"), parent); + gridLayout->addWidget(pbBBB, 0, 0, 1, 1); + gridLayout->addWidget(pbBB, 0, 1, 1, 1); + gridLayout->addWidget(pbB, 0, 2, 1, 1); - int iStart = 5; - pbF = addButton(QLatin1String(">"), parent); - pbFF = addButton(QLatin1String(">>"), parent); - pbFFF = addButton(QLatin1String(">>>"), parent); - gridLayout->addWidget(pbF, 0, iStart++, 1, 1); - gridLayout->addWidget(pbFF, 0, iStart++, 1, 1); - gridLayout->addWidget(pbFFF, 0, iStart++, 1, 1); - } + int iStart = 5; + pbF = addButton(QLatin1String(">"), parent); + pbFF = addButton(QLatin1String(">>"), parent); + pbFFF = addButton(QLatin1String(">>>"), parent); + gridLayout->addWidget(pbF, 0, iStart++, 1, 1); + gridLayout->addWidget(pbFF, 0, iStart++, 1, 1); + gridLayout->addWidget(pbFFF, 0, iStart++, 1, 1); + } - void addSlider(QWidget *parent) - { - slTime = new QSlider(parent); - slTime->setOrientation(Qt::Horizontal); - gridLayout->addWidget(slTime, 1, 0, 1, 7); - } + void addSlider(QWidget* parent) + { + slTime = new QSlider(parent); + slTime->setOrientation(Qt::Horizontal); + gridLayout->addWidget(slTime, 1, 0, 1, 7); + } }; -} - +} // namespace Ui namespace LtsWidgets { - - - -void setItemText(LtsWidgets::LineEdit *lineEdit, const QString &text) +void setItemText(LtsWidgets::LineEdit* lineEdit, const QString& text) { - if (!lineEdit) - return; - lineEdit->setText(text); -} -void setItemText(QComboBox *comboxBox, const QString &text) -{ - if (!comboxBox) - return; - comboxBox->setCurrentIndex(comboxBox->findText(text)); -} -void setItemData(QComboBox *comboxBox, int data) -{ - if (!comboxBox) - return; - comboxBox->setCurrentIndex(comboxBox->findData(data)); -} -void setItemValue(QSpinBox *spinBox, int value) -{ - if (!spinBox) - return; - spinBox->setValue(value); + if (!lineEdit) + return; + lineEdit->setText(text); } - -QString getItemText(LtsWidgets::LineEdit *lineEdit) +void setItemText(QComboBox* comboxBox, const QString& text) { - if (!lineEdit) - return {}; - return lineEdit->text(); -} -QString getItemText(QComboBox *comboxBox) -{ - if (!comboxBox || (comboxBox->count() <= 0)) - return {}; - const QString &curTest = comboxBox->currentText(); - if (curTest.isEmpty()) - return {}; - return curTest.at(0).toUpper(); -} -int getItemData(QComboBox *comboxBox) -{ - if (!comboxBox || (comboxBox->count() <= 0)) - return {}; - int data = comboxBox->currentData().toInt(); - return data; -} -int getItemValue(QSpinBox *spinBox) -{ - if (!spinBox) - return 0; - return spinBox->value(); + if (!comboxBox) + return; + comboxBox->setCurrentIndex(comboxBox->findText(text)); } +void setItemData(QComboBox* comboxBox, int data) +{ + if (!comboxBox) + return; + comboxBox->setCurrentIndex(comboxBox->findData(data)); +} +void setItemValue(QSpinBox* spinBox, int value) +{ + if (!spinBox) + return; + spinBox->setValue(value); +} +QString getItemText(LtsWidgets::LineEdit* lineEdit) +{ + if (!lineEdit) + return {}; + return lineEdit->text(); +} +QString getItemText(QComboBox* comboxBox) +{ + if (!comboxBox || (comboxBox->count() <= 0)) + return {}; + const QString& curTest = comboxBox->currentText(); + if (curTest.isEmpty()) + return {}; + return curTest.at(0).toUpper(); +} +int getItemData(QComboBox* comboxBox) +{ + if (!comboxBox || (comboxBox->count() <= 0)) + return {}; + int data = comboxBox->currentData().toInt(); + return data; +} -LtsDateTimeEdit::LtsDateTimeEdit(QWidget *parent, bool withNowButton, bool checkable) - : QWidget(parent) +int getItemValue(QSpinBox* spinBox) +{ + if (!spinBox) + return 0; + return spinBox->value(); +} - , m_scFixed(new QShortcut(QKeySequence(Qt::ShiftModifier + Qt::Key_F2), this, SLOT(setFixedDateTime()), nullptr, Qt::WidgetWithChildrenShortcut)) - , m_scOffset(new QShortcut(QKeySequence(Qt::Key_F2), this, SLOT(setOffsetDateTime()), nullptr, Qt::WidgetWithChildrenShortcut)) - , m_checkable(checkable) - , m_withNowButton(withNowButton) +LtsDateTimeEdit::LtsDateTimeEdit(QWidget* parent, bool withNowButton, bool checkable) + : QWidget(parent) + + , + m_scFixed(new QShortcut(QKeySequence(Qt::ShiftModifier + Qt::Key_F2), this, SLOT(setFixedDateTime()), nullptr, + Qt::WidgetWithChildrenShortcut)), + m_scOffset(new QShortcut(QKeySequence(Qt::Key_F2), this, SLOT(setOffsetDateTime()), nullptr, + Qt::WidgetWithChildrenShortcut)), + m_checkable(checkable), m_withNowButton(withNowButton) { #ifdef TABLET_MODE - - setupUiTouch(); - return; + + setupUiTouch(); + return; #else - - m_uiLe = new Ui::LtsDateTimeEditLe; - m_uiLe->setupUi(this); - setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); - setFocusPolicy(Qt::StrongFocus); - setContentsMargins(QMargins()); + m_uiLe = new Ui::LtsDateTimeEditLe; + m_uiLe->setupUi(this); - QCompleter *completer = new QCompleter(DTG::months(), this); - completer->setCaseSensitivity(Qt::CaseInsensitive); - completer->setCompletionMode(QCompleter::InlineCompletion); + setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); + setFocusPolicy(Qt::StrongFocus); + setContentsMargins(QMargins()); - QRegularExpression rx(DTG::months().join(QLatin1Char('|'))); - QRegularExpressionValidator *val = new QRegularExpressionValidator(rx, this); - m_uiLe->leLongMonth->setCompleter(completer); - m_uiLe->leLongMonth->setValidator(val); + QCompleter* completer = new QCompleter(DTG::months(), this); + completer->setCaseSensitivity(Qt::CaseInsensitive); + completer->setCompletionMode(QCompleter::InlineCompletion); - connect(m_uiLe->leLongDay, &DigitsLineEdit::textEdited, this, &LtsDateTimeEdit::valueDayChanged); - connect(m_uiLe->leLongMonth, &LineEdit::textEdited, this, &LtsDateTimeEdit::valueMonthChanged2); - connect(m_uiLe->leLongTZ, &LineEdit::textEdited, this, &LtsDateTimeEdit::valueTimezoneChangedStr); - connect(m_uiLe->leLongYear, &DigitsLineEdit::textEdited, this, &LtsDateTimeEdit::valueYearChanged); + QRegularExpression rx(DTG::months().join(QLatin1Char('|'))); + QRegularExpressionValidator* val = new QRegularExpressionValidator(rx, this); + m_uiLe->leLongMonth->setCompleter(completer); + m_uiLe->leLongMonth->setValidator(val); - connect(m_uiLe->leLongHHMMSS, &DigitsLineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutHHMMSS); - connect(m_uiLe->leLongDay, &DigitsLineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutDay); - connect(m_uiLe->leLongMonth, &LineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutMonth); - connect(m_uiLe->leLongTZ, &LineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutTZ); - connect(m_uiLe->leLongYear, &DigitsLineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutYear); + connect(m_uiLe->leLongDay, &DigitsLineEdit::textEdited, this, &LtsDateTimeEdit::valueDayChanged); + connect(m_uiLe->leLongMonth, &LineEdit::textEdited, this, &LtsDateTimeEdit::valueMonthChanged2); + connect(m_uiLe->leLongTZ, &LineEdit::textEdited, this, &LtsDateTimeEdit::valueTimezoneChangedStr); + connect(m_uiLe->leLongYear, &DigitsLineEdit::textEdited, this, &LtsDateTimeEdit::valueYearChanged); - connect(m_uiLe->leLongHHMMSS, &DigitsLineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); - connect(m_uiLe->leLongDay, &DigitsLineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); - connect(m_uiLe->leLongMonth, &LineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); - connect(m_uiLe->leLongTZ, &LineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); - connect(m_uiLe->leLongYear, &DigitsLineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); + connect(m_uiLe->leLongHHMMSS, &DigitsLineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutHHMMSS); + connect(m_uiLe->leLongDay, &DigitsLineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutDay); + connect(m_uiLe->leLongMonth, &LineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutMonth); + connect(m_uiLe->leLongTZ, &LineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutTZ); + connect(m_uiLe->leLongYear, &DigitsLineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutYear); - connect(m_uiLe->leLongHHMMSS, &DigitsLineEdit::wheelEventReceived, this, &LtsDateTimeEdit::onHmsWheelEvent); - connect(m_uiLe->leLongDay, &DigitsLineEdit::wheelEventReceived, this, &LtsDateTimeEdit::onDayWheelEvent); - connect(m_uiLe->leLongMonth, &DigitsLineEdit::wheelEventReceived, this, &LtsDateTimeEdit::onMonthWheelEvent); - connect(m_uiLe->leLongYear, &DigitsLineEdit::wheelEventReceived, this, &LtsDateTimeEdit::onYearWheelEvent); + connect(m_uiLe->leLongHHMMSS, &DigitsLineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); + connect(m_uiLe->leLongDay, &DigitsLineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); + connect(m_uiLe->leLongMonth, &LineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); + connect(m_uiLe->leLongTZ, &LineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); + connect(m_uiLe->leLongYear, &DigitsLineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); - connect(m_uiLe->checkBox, &QCheckBox::toggled, this, &LtsDateTimeEdit::onCheckBoxChanged); - connect(m_uiLe->pbNow, &QPushButton::clicked, this, &LtsDateTimeEdit::setOffsetDateTime); - connect(checkBox(), &QCheckBox::toggled, this, &LtsDateTimeEdit::toggled); + connect(m_uiLe->leLongHHMMSS, &DigitsLineEdit::wheelEventReceived, this, &LtsDateTimeEdit::onHmsWheelEvent); + connect(m_uiLe->leLongDay, &DigitsLineEdit::wheelEventReceived, this, &LtsDateTimeEdit::onDayWheelEvent); + connect(m_uiLe->leLongMonth, &DigitsLineEdit::wheelEventReceived, this, &LtsDateTimeEdit::onMonthWheelEvent); + connect(m_uiLe->leLongYear, &DigitsLineEdit::wheelEventReceived, this, &LtsDateTimeEdit::onYearWheelEvent); - setTimezone(DTG::timezone()); + connect(m_uiLe->checkBox, &QCheckBox::toggled, this, &LtsDateTimeEdit::onCheckBoxChanged); + connect(m_uiLe->pbNow, &QPushButton::clicked, this, &LtsDateTimeEdit::setOffsetDateTime); + connect(checkBox(), &QCheckBox::toggled, this, &LtsDateTimeEdit::toggled); - setCheckable(m_checkable); + setTimezone(DTG::timezone()); - setWithNowButton(m_withNowButton); + setCheckable(m_checkable); - onCheckBoxChanged(); + setWithNowButton(m_withNowButton); + + onCheckBoxChanged(); #endif } LtsDateTimeEdit::~LtsDateTimeEdit() { - delete m_uiLe; + delete m_uiLe; } bool LtsDateTimeEdit::setupUiTouch() { - m_uiTouch = new Ui::LtsDateTimeEdit; - m_uiTouch->setupUi(this); - setFocusPolicy(Qt::StrongFocus); + m_uiTouch = new Ui::LtsDateTimeEdit; + m_uiTouch->setupUi(this); + setFocusPolicy(Qt::StrongFocus); - for (int i = 65; i < 91; i++ ) - { - if (QChar(i).toUpper() == QChar::fromLatin1('I')) - continue; - m_uiTouch->cbxTimeZone->addItem(QChar(i), QChar(i)); - } + for (int i = 65; i < 91; i++) + { + if (QChar(i).toUpper() == QChar::fromLatin1('I')) + continue; + m_uiTouch->cbxTimeZone->addItem(QChar(i), QChar(i)); + } - connect(m_uiTouch->pbNow, &QPushButton::clicked, - this, &LtsDateTimeEdit::setOffsetDateTime); - connect(m_uiTouch->cbxMonth, static_cast(&QComboBox::currentIndexChanged), - this, &LtsDateTimeEdit::dateTimeChanged); - connect(m_uiTouch->spDay, &QSpinBox::editingFinished, - this, &LtsDateTimeEdit::dateTimeChanged); - connect(m_uiTouch->spHour, &QSpinBox::editingFinished, - this, &LtsDateTimeEdit::dateTimeChanged); - connect(m_uiTouch->spMinutes, &QSpinBox::editingFinished, - this, &LtsDateTimeEdit::dateTimeChanged); - connect(m_uiTouch->spSeconds, &QSpinBox::editingFinished, - this, &LtsDateTimeEdit::dateTimeChanged); - connect(m_uiTouch->spYear, &QSpinBox::editingFinished, - this, &LtsDateTimeEdit::dateTimeChanged); + connect(m_uiTouch->pbNow, &QPushButton::clicked, this, &LtsDateTimeEdit::setOffsetDateTime); + connect(m_uiTouch->cbxMonth, static_cast(&QComboBox::currentIndexChanged), this, + &LtsDateTimeEdit::dateTimeChanged); + connect(m_uiTouch->spDay, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::dateTimeChanged); + connect(m_uiTouch->spHour, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::dateTimeChanged); + connect(m_uiTouch->spMinutes, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::dateTimeChanged); + connect(m_uiTouch->spSeconds, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::dateTimeChanged); + connect(m_uiTouch->spYear, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::dateTimeChanged); - connect(m_uiTouch->checkBox, &QCheckBox::toggled, - this, &LtsDateTimeEdit::onCheckBoxChanged); - connect(m_uiTouch->cbxTimeZone, static_cast(&QComboBox::currentIndexChanged), - this, &LtsDateTimeEdit::valueTimezoneChangedInt); + connect(m_uiTouch->checkBox, &QCheckBox::toggled, this, &LtsDateTimeEdit::onCheckBoxChanged); + connect(m_uiTouch->cbxTimeZone, static_cast(&QComboBox::currentIndexChanged), this, + &LtsDateTimeEdit::valueTimezoneChangedInt); - - - connect(m_uiTouch->cbxMonth, &QComboBox::currentTextChanged, - this, &LtsDateTimeEdit::valueMonthChanged); + connect(m_uiTouch->cbxMonth, &QComboBox::currentTextChanged, this, &LtsDateTimeEdit::valueMonthChanged); - connect(checkBox(), &QCheckBox::toggled, this, &LtsDateTimeEdit::toggled); + connect(checkBox(), &QCheckBox::toggled, this, &LtsDateTimeEdit::toggled); - setMinMaxMonth(1,12); + setMinMaxMonth(1, 12); - setTimezone(DTG::timezone()); - + setTimezone(DTG::timezone()); - setCheckable(m_checkable); + setCheckable(m_checkable); - setWithNowButton(m_withNowButton); + setWithNowButton(m_withNowButton); - onCheckBoxChanged(); + onCheckBoxChanged(); - return true; + return true; } - -void LtsDateTimeEdit::setRetrieveCurrentTimeCallback(const CurrentTimeCallback &cb) +void LtsDateTimeEdit::setRetrieveCurrentTimeCallback(const CurrentTimeCallback& cb) { - m_getCurrentTimeCallback = cb; + m_getCurrentTimeCallback = cb; } void LtsDateTimeEdit::setEditTimezone(const bool edit) { - m_editTimezone = edit; - if (m_uiLe) - m_uiLe->leLongTZ->setEnabled(m_editTimezone); - if (m_uiTouch) - m_uiTouch->cbxTimeZone->setEnabled(m_editTimezone); + m_editTimezone = edit; + if (m_uiLe) + m_uiLe->leLongTZ->setEnabled(m_editTimezone); + if (m_uiTouch) + m_uiTouch->cbxTimeZone->setEnabled(m_editTimezone); } void LtsDateTimeEdit::setWithButtons(const bool buttons) { - m_withButtons = buttons; - if (buttons) - { - if (m_uiLe && !m_uiLe->pbBBB) + m_withButtons = buttons; + if (buttons) { - m_uiLe->addButtons(this); - connect(m_uiLe->pbBBB, &QPushButton::clicked, this, &LtsDateTimeEdit::onBackHourClicked); - connect(m_uiLe->pbBB, &QPushButton::clicked, this, &LtsDateTimeEdit::onBackMinuteClicked); - connect(m_uiLe->pbB, &QPushButton::clicked, this, &LtsDateTimeEdit::onBackSecondClicked); - connect(m_uiLe->pbF, &QPushButton::clicked, this, &LtsDateTimeEdit::onForwardSecondClicked); - connect(m_uiLe->pbFF, &QPushButton::clicked, this, &LtsDateTimeEdit::onForwardMinuteClicked); - connect(m_uiLe->pbFFF, &QPushButton::clicked, this, &LtsDateTimeEdit::onForwardHourClicked); - disableControls(); + if (m_uiLe && !m_uiLe->pbBBB) + { + m_uiLe->addButtons(this); + connect(m_uiLe->pbBBB, &QPushButton::clicked, this, &LtsDateTimeEdit::onBackHourClicked); + connect(m_uiLe->pbBB, &QPushButton::clicked, this, &LtsDateTimeEdit::onBackMinuteClicked); + connect(m_uiLe->pbB, &QPushButton::clicked, this, &LtsDateTimeEdit::onBackSecondClicked); + connect(m_uiLe->pbF, &QPushButton::clicked, this, &LtsDateTimeEdit::onForwardSecondClicked); + connect(m_uiLe->pbFF, &QPushButton::clicked, this, &LtsDateTimeEdit::onForwardMinuteClicked); + connect(m_uiLe->pbFFF, &QPushButton::clicked, this, &LtsDateTimeEdit::onForwardHourClicked); + disableControls(); + } } - } - else - { - if (m_uiLe) + else { - delete m_uiLe->pbBBB; - delete m_uiLe->pbBB; - delete m_uiLe->pbB; - delete m_uiLe->pbFFF; - delete m_uiLe->pbFF; - delete m_uiLe->pbF; + if (m_uiLe) + { + delete m_uiLe->pbBBB; + delete m_uiLe->pbBB; + delete m_uiLe->pbB; + delete m_uiLe->pbFFF; + delete m_uiLe->pbFF; + delete m_uiLe->pbF; - m_uiLe->pbBBB = nullptr; - m_uiLe->pbBB = nullptr; - m_uiLe->pbB = nullptr; - m_uiLe->pbFFF = nullptr; - m_uiLe->pbFF = nullptr; - m_uiLe->pbF = nullptr; + m_uiLe->pbBBB = nullptr; + m_uiLe->pbBB = nullptr; + m_uiLe->pbB = nullptr; + m_uiLe->pbFFF = nullptr; + m_uiLe->pbFF = nullptr; + m_uiLe->pbF = nullptr; + } } - } } void LtsDateTimeEdit::setWithSlider(const bool slider) { - m_withSlider = slider; + m_withSlider = slider; - if (!m_uiLe) - return; + if (!m_uiLe) + return; - if (slider) - { - m_uiLe->addSlider(this); - m_uiLe->slTime->setMinimum(m_minTimeMSec / 1000); - m_uiLe->slTime->setMaximum(m_maxTimeMSec > 0 ? m_maxTimeMSec / 1000 : time(nullptr)); - connect(m_uiLe->slTime, &QSlider::sliderMoved, this, &LtsDateTimeEdit::setSliderValue); - disableControls(); - } - else - { - delete m_uiLe->slTime; - m_uiLe->slTime = nullptr; - } + if (slider) + { + m_uiLe->addSlider(this); + m_uiLe->slTime->setMinimum(m_minTimeMSec / 1000); + m_uiLe->slTime->setMaximum(m_maxTimeMSec > 0 ? m_maxTimeMSec / 1000 : time(nullptr)); + connect(m_uiLe->slTime, &QSlider::sliderMoved, this, &LtsDateTimeEdit::setSliderValue); + disableControls(); + } + else + { + delete m_uiLe->slTime; + m_uiLe->slTime = nullptr; + } } void LtsDateTimeEdit::setReadOnly(const bool readOnly) { - if (m_readOnly == readOnly) - return; - m_readOnly = readOnly; + if (m_readOnly == readOnly) + return; + m_readOnly = readOnly; - if (m_uiLe) - { - m_uiLe->leLongDay->setReadOnly(m_readOnly); - m_uiLe->leLongHHMMSS->setReadOnly(m_readOnly); - m_uiLe->leLongMonth->setReadOnly(m_readOnly); - m_uiLe->leLongTZ->setReadOnly(m_readOnly); - m_uiLe->leLongYear->setReadOnly(m_readOnly); - } - if (m_uiTouch) - { - m_uiTouch->spDay->setReadOnly(m_readOnly); - m_uiTouch->spHour->setReadOnly(m_readOnly); - m_uiTouch->spMinutes->setReadOnly(m_readOnly); - m_uiTouch->spSeconds->setReadOnly(m_readOnly); - m_uiTouch->spYear->setReadOnly(m_readOnly); - m_uiTouch->cbxTimeZone->setEnabled(m_readOnly); - } + if (m_uiLe) + { + m_uiLe->leLongDay->setReadOnly(m_readOnly); + m_uiLe->leLongHHMMSS->setReadOnly(m_readOnly); + m_uiLe->leLongMonth->setReadOnly(m_readOnly); + m_uiLe->leLongTZ->setReadOnly(m_readOnly); + m_uiLe->leLongYear->setReadOnly(m_readOnly); + } + if (m_uiTouch) + { + m_uiTouch->spDay->setReadOnly(m_readOnly); + m_uiTouch->spHour->setReadOnly(m_readOnly); + m_uiTouch->spMinutes->setReadOnly(m_readOnly); + m_uiTouch->spSeconds->setReadOnly(m_readOnly); + m_uiTouch->spYear->setReadOnly(m_readOnly); + m_uiTouch->cbxTimeZone->setEnabled(m_readOnly); + } } -QCheckBox *LtsDateTimeEdit::checkBox() const +QCheckBox* LtsDateTimeEdit::checkBox() const { - return m_uiLe ? m_uiLe->checkBox : m_uiTouch ? m_uiTouch->checkBox : nullptr; + return m_uiLe ? m_uiLe->checkBox : m_uiTouch ? m_uiTouch->checkBox : nullptr; } void LtsDateTimeEdit::setCheckable(bool checkable) { - if (!checkBox() || (m_checkable == checkable)) - return; + if (!checkBox() || (m_checkable == checkable)) + return; - m_checkable = checkable; - checkBox()->setVisible(checkable); - if (!checkable) - checkBox()->setChecked(true); + m_checkable = checkable; + checkBox()->setVisible(checkable); + if (!checkable) + checkBox()->setChecked(true); } void LtsDateTimeEdit::setChecked(bool bChecked) { - if (!checkBox()) - return; - checkBox()->setChecked(bChecked); + if (!checkBox()) + return; + checkBox()->setChecked(bChecked); } bool LtsDateTimeEdit::isChecked() const { - if (!checkBox()) - return false; - return checkBox()->isChecked(); + if (!checkBox()) + return false; + return checkBox()->isChecked(); } -QPushButton *LtsDateTimeEdit::pbNow() const +QPushButton* LtsDateTimeEdit::pbNow() const { - return m_uiLe ? m_uiLe->pbNow : m_uiTouch ? m_uiTouch->pbNow : nullptr; + return m_uiLe ? m_uiLe->pbNow : m_uiTouch ? m_uiTouch->pbNow : nullptr; } void LtsDateTimeEdit::setWithNowButton(bool nowButton) { - if (!pbNow()) - return; + if (!pbNow()) + return; - pbNow()->setVisible(nowButton); + pbNow()->setVisible(nowButton); } bool LtsDateTimeEdit::setMsecsSinceEpoch(qint64 msec, bool setToNearestPossible) { - if (msec == 0 && isCheckable()) - { + if (msec == 0 && isCheckable()) + { + if (m_uiLe) + m_uiLe->checkBox->setChecked(false); + m_dateIsAcceptable = true; + return true; + } if (m_uiLe) - m_uiLe->checkBox->setChecked(false); - m_dateIsAcceptable = true; - return true; - } - if (m_uiLe) - m_uiLe->checkBox->setChecked(true); + m_uiLe->checkBox->setChecked(true); - m_dateIsAcceptable = false; - if (msec == 0) - return false; + m_dateIsAcceptable = false; + if (msec == 0) + return false; - - - - + if (!setToNearestPossible) + { + if (!isDataAcceptable()) + return false; + } + else + { + if (msec < m_minTimeMSec && m_minTimeMSec > 0) + msec = m_minTimeMSec; + if (msec > m_maxTimeMSec && m_maxTimeMSec > 0) + msec = m_maxTimeMSec; + } + + m_curTimeMSec = msec; + + const qint64 offsetTimeZoneMsec = getTimezoneAsSecs() * 1000; + const QDateTime datetime(QDateTime::fromMSecsSinceEpoch(m_curTimeMSec + offsetTimeZoneMsec, Qt::UTC)); + const QDate date(datetime.date()); + const QTime time(datetime.time()); + + const int day = date.day(); + const int month = date.month(); + const int year = date.year(); + const int hour = time.hour(); + const int minute = time.minute(); + const int second = time.second(); + + if (!setYear(year) || !setMonth(month) || !setDay(day) || !setHHMMSS(hour, minute, second)) + return false; - if (!setToNearestPossible) - { if (!isDataAcceptable()) - return false; - } - else - { - if (msec < m_minTimeMSec && m_minTimeMSec > 0) - msec = m_minTimeMSec; - if (msec > m_maxTimeMSec && m_maxTimeMSec > 0) - msec = m_maxTimeMSec; - } + return false; - m_curTimeMSec = msec; + enableControls(); - const qint64 offsetTimeZoneMsec = getTimezoneAsSecs() * 1000; - const QDateTime datetime(QDateTime::fromMSecsSinceEpoch(m_curTimeMSec + offsetTimeZoneMsec, Qt::UTC)); - const QDate date(datetime.date()); - const QTime time(datetime.time()); + emit dateTimeChanged(); - const int day = date.day(); - const int month = date.month(); - const int year = date.year(); - const int hour = time.hour(); - const int minute = time.minute(); - const int second = time.second(); - - - if (!setYear(year) || - !setMonth(month) || - !setDay(day) || - !setHHMMSS(hour, minute, second)) - return false; - - if (!isDataAcceptable()) - return false; - - enableControls(); - - emit dateTimeChanged(); - - return true; + return true; } - qint64 LtsDateTimeEdit::msecsSinceEpoch() const { - if (isEmpty()) - return 0; + if (isEmpty()) + return 0; - if (m_uiLe && !m_uiLe->checkBox->isChecked()) - return 0; - if (m_uiTouch && !m_uiTouch->checkBox->isChecked()) - return 0; + if (m_uiLe && !m_uiLe->checkBox->isChecked()) + return 0; + if (m_uiTouch && !m_uiTouch->checkBox->isChecked()) + return 0; - auto that = const_cast(this); - if (!that->isDataAcceptable()) - return 0; + auto that = const_cast(this); + if (!that->isDataAcceptable()) + return 0; - return m_curTimeMSec; + return m_curTimeMSec; } bool LtsDateTimeEdit::setTimezone(char tz) { - tz = toupper(tz); - if (!DTG::isTimezoneValid(tz)) - return false; + tz = toupper(tz); + if (!DTG::isTimezoneValid(tz)) + return false; - if (m_uiLe) - setItemText(m_uiLe->leLongTZ, QString(QLatin1Char(tz))); - if (m_uiTouch) - setItemText(m_uiTouch->cbxTimeZone, QString(QLatin1Char(tz))); + if (m_uiLe) + setItemText(m_uiLe->leLongTZ, QString(QLatin1Char(tz))); + if (m_uiTouch) + setItemText(m_uiTouch->cbxTimeZone, QString(QLatin1Char(tz))); - setMsecsSinceEpoch(m_curTimeMSec); + setMsecsSinceEpoch(m_curTimeMSec); - return true; + return true; } char LtsDateTimeEdit::getTimezone() const { - QString str; - if (m_uiLe) - str = getItemText(m_uiLe->leLongTZ); - if (m_uiTouch) - str = getItemText(m_uiTouch->cbxTimeZone); + QString str; + if (m_uiLe) + str = getItemText(m_uiLe->leLongTZ); + if (m_uiTouch) + str = getItemText(m_uiTouch->cbxTimeZone); - if (str.isEmpty()) - return DTG::timezone(); - return str[0].toUpper().toLatin1(); + if (str.isEmpty()) + return DTG::timezone(); + return str[0].toUpper().toLatin1(); } qint64 LtsDateTimeEdit::getTimezoneAsSecs() const { - const char tzGUI = getTimezone(); - return DTG::timezone2Secs(tzGUI); + const char tzGUI = getTimezone(); + return DTG::timezone2Secs(tzGUI); } void LtsDateTimeEdit::clearTimezone() { - if (m_uiLe) - m_uiLe->leLongTZ->clear(); - if (m_uiTouch) - m_uiTouch->cbxTimeZone->setCurrentIndex(0); + if (m_uiLe) + m_uiLe->leLongTZ->clear(); + if (m_uiTouch) + m_uiTouch->cbxTimeZone->setCurrentIndex(0); } void LtsDateTimeEdit::setMinMaxMonth(int minMonth, int maxMonth) { - if (!m_uiTouch) - return; + if (!m_uiTouch) + return; - m_minMonth = minMonth; - m_maxMonth = maxMonth; + m_minMonth = minMonth; + m_maxMonth = maxMonth; - const int currentMonth = m_uiTouch->cbxMonth->currentData().toInt(); - m_uiTouch->cbxMonth->blockSignals(true); - m_uiTouch->cbxMonth->clear(); - for (int i = 1; i <= 12; ++i) - { - if (i < m_minMonth) - continue; - if (i > m_maxMonth) - break; + const int currentMonth = m_uiTouch->cbxMonth->currentData().toInt(); + m_uiTouch->cbxMonth->blockSignals(true); + m_uiTouch->cbxMonth->clear(); + for (int i = 1; i <= 12; ++i) + { + if (i < m_minMonth) + continue; + if (i > m_maxMonth) + break; - - - const QStringList &monthSl = DTG::months(); - m_uiTouch->cbxMonth->addItem(monthSl[i-1], i); - - - + const QStringList& monthSl = DTG::months(); + m_uiTouch->cbxMonth->addItem(monthSl[i - 1], i); + } - } - - - m_uiTouch->cbxMonth->setCurrentIndex(m_uiTouch->cbxMonth->findData(currentMonth)); - m_uiTouch->cbxMonth->blockSignals(false); + m_uiTouch->cbxMonth->setCurrentIndex(m_uiTouch->cbxMonth->findData(currentMonth)); + m_uiTouch->cbxMonth->blockSignals(false); } - -void LtsDateTimeEdit::setSubWidgetsProperties(const QString &name, const QVariant &value) +void LtsDateTimeEdit::setSubWidgetsProperties(const QString& name, const QVariant& value) { - if (m_uiLe) - { - m_uiLe->leLongDay->setProperty(name.toStdString().c_str(), value); - m_uiLe->leLongHHMMSS->setProperty(name.toStdString().c_str(), value); - m_uiLe->leLongMonth->setProperty(name.toStdString().c_str(), value); - m_uiLe->leLongYear->setProperty(name.toStdString().c_str(), value); - m_uiLe->leLongTZ->setProperty(name.toStdString().c_str(), value); - } - if (m_uiTouch) - { - m_uiTouch->spDay->setProperty(name.toStdString().c_str(), value); - m_uiTouch->spHour->setProperty(name.toStdString().c_str(), value); - m_uiTouch->spMinutes->setProperty(name.toStdString().c_str(), value); - m_uiTouch->spSeconds->setProperty(name.toStdString().c_str(), value); - m_uiTouch->spYear->setProperty(name.toStdString().c_str(), value); - } + if (m_uiLe) + { + m_uiLe->leLongDay->setProperty(name.toStdString().c_str(), value); + m_uiLe->leLongHHMMSS->setProperty(name.toStdString().c_str(), value); + m_uiLe->leLongMonth->setProperty(name.toStdString().c_str(), value); + m_uiLe->leLongYear->setProperty(name.toStdString().c_str(), value); + m_uiLe->leLongTZ->setProperty(name.toStdString().c_str(), value); + } + if (m_uiTouch) + { + m_uiTouch->spDay->setProperty(name.toStdString().c_str(), value); + m_uiTouch->spHour->setProperty(name.toStdString().c_str(), value); + m_uiTouch->spMinutes->setProperty(name.toStdString().c_str(), value); + m_uiTouch->spSeconds->setProperty(name.toStdString().c_str(), value); + m_uiTouch->spYear->setProperty(name.toStdString().c_str(), value); + } } bool LtsDateTimeEdit::setMonth(int month) { - const auto months(DTG::months()); - if (month < 1 || month > months.size()) - return false; + const auto months(DTG::months()); + if (month < 1 || month > months.size()) + return false; - if (m_uiLe) - setItemText(m_uiLe->leLongMonth, months.at(month - 1)); - if (m_uiTouch) - setItemData(m_uiTouch->cbxMonth, month); - return true; + if (m_uiLe) + setItemText(m_uiLe->leLongMonth, months.at(month - 1)); + if (m_uiTouch) + setItemData(m_uiTouch->cbxMonth, month); + return true; } int LtsDateTimeEdit::getMonth() const { - if (m_uiLe) - { - const QString str = getItemText(m_uiLe->leLongMonth); - if (str.length() != 3) - return -1; + if (m_uiLe) + { + const QString str = getItemText(m_uiLe->leLongMonth); + if (str.length() != 3) + return -1; - int idx = DTG::months().indexOf(str); - if (idx < 0) - return -1; - return idx + 1; - } - if (m_uiTouch) - { - int month = getItemData(m_uiTouch->cbxMonth); - return month; - } - return 0; + int idx = DTG::months().indexOf(str); + if (idx < 0) + return -1; + return idx + 1; + } + if (m_uiTouch) + { + int month = getItemData(m_uiTouch->cbxMonth); + return month; + } + return 0; } bool LtsDateTimeEdit::setDay(int day) { - if (day < 1 || day > 31) - return false; + if (day < 1 || day > 31) + return false; - QString oldDay; - if (m_uiLe) - oldDay = m_uiLe->leLongDay->text(); - int oldDayInt = 0; - if (m_uiTouch) - oldDayInt = getItemValue(m_uiTouch->spDay); - - if (m_uiLe) - setItemText(m_uiLe->leLongDay, QStringLiteral("%1").arg(day, 2, 10, QLatin1Char('0'))); - if (m_uiTouch) - setItemValue(m_uiTouch->spDay, day); - - if (!isDayAcceptable()) - { + QString oldDay; if (m_uiLe) - setItemText(m_uiLe->leLongDay, oldDay); + oldDay = m_uiLe->leLongDay->text(); + int oldDayInt = 0; if (m_uiTouch) - setItemValue(m_uiTouch->spDay, oldDayInt); - return false; - } + oldDayInt = getItemValue(m_uiTouch->spDay); - return true; + if (m_uiLe) + setItemText(m_uiLe->leLongDay, QStringLiteral("%1").arg(day, 2, 10, QLatin1Char('0'))); + if (m_uiTouch) + setItemValue(m_uiTouch->spDay, day); + + if (!isDayAcceptable()) + { + if (m_uiLe) + setItemText(m_uiLe->leLongDay, oldDay); + if (m_uiTouch) + setItemValue(m_uiTouch->spDay, oldDayInt); + return false; + } + + return true; } int LtsDateTimeEdit::getDay() const { - if (m_uiLe) - return m_uiLe->leLongDay->getValue(); - if (m_uiTouch) - return getItemValue(m_uiTouch->spDay); - return 0; + if (m_uiLe) + return m_uiLe->leLongDay->getValue(); + if (m_uiTouch) + return getItemValue(m_uiTouch->spDay); + return 0; } bool LtsDateTimeEdit::setHHMMSS(int hour, int minute, int second) { - if (hour < 0 || hour > 23 || - minute < 0 || minute > 59 || - second < 0 || second > 59) - return false; + if (hour < 0 || hour > 23 || minute < 0 || minute > 59 || second < 0 || second > 59) + return false; - if (m_uiLe) - m_uiLe->leLongHHMMSS->setValue(hour * 10000 + minute * 100 + second); - if (m_uiTouch) - { - setItemValue(m_uiTouch->spHour , hour); - setItemValue(m_uiTouch->spMinutes, minute); - setItemValue(m_uiTouch->spSeconds, second); - } + if (m_uiLe) + m_uiLe->leLongHHMMSS->setValue(hour * 10000 + minute * 100 + second); + if (m_uiTouch) + { + setItemValue(m_uiTouch->spHour, hour); + setItemValue(m_uiTouch->spMinutes, minute); + setItemValue(m_uiTouch->spSeconds, second); + } - return true; + return true; } int LtsDateTimeEdit::getHour() const { - if (m_uiLe) - { - const int time = m_uiLe->leLongHHMMSS->getValue(); - return time / 10000; - } - if (m_uiTouch) - { - return getItemValue(m_uiTouch->spHour); - } - return 0; + if (m_uiLe) + { + const int time = m_uiLe->leLongHHMMSS->getValue(); + return time / 10000; + } + if (m_uiTouch) + { + return getItemValue(m_uiTouch->spHour); + } + return 0; } int LtsDateTimeEdit::getMinute() const { - if (m_uiLe) - { - const int time = m_uiLe->leLongHHMMSS->getValue(); - return (time / 100) % 100; - } - if (m_uiTouch) - { - return getItemValue(m_uiTouch->spMinutes); - } - return 0; + if (m_uiLe) + { + const int time = m_uiLe->leLongHHMMSS->getValue(); + return (time / 100) % 100; + } + if (m_uiTouch) + { + return getItemValue(m_uiTouch->spMinutes); + } + return 0; } int LtsDateTimeEdit::getSecond() const { - if (m_uiLe) - { - const int time = m_uiLe->leLongHHMMSS->getValue(); - return time % 100; - } - if (m_uiTouch) - { - return getItemValue(m_uiTouch->spSeconds); - } - return 0; + if (m_uiLe) + { + const int time = m_uiLe->leLongHHMMSS->getValue(); + return time % 100; + } + if (m_uiTouch) + { + return getItemValue(m_uiTouch->spSeconds); + } + return 0; } bool LtsDateTimeEdit::setYear(int year) { - int finalYear = -1; - if (year >= 0 && year <= 99) - finalYear = year; - else if (year >= 2000 && year <= 2099) - finalYear = year - 2000; + int finalYear = -1; + if (year >= 0 && year <= 99) + finalYear = year; + else if (year >= 2000 && year <= 2099) + finalYear = year - 2000; - if (finalYear >= 0) - { - if (m_uiLe) - m_uiLe->leLongYear->setValue(finalYear); - if (m_uiTouch) - setItemValue(m_uiTouch->spYear, finalYear); - return true; - } + if (finalYear >= 0) + { + if (m_uiLe) + m_uiLe->leLongYear->setValue(finalYear); + if (m_uiTouch) + setItemValue(m_uiTouch->spYear, finalYear); + return true; + } - return false; + return false; } int LtsDateTimeEdit::getYear() const { - if (m_uiLe) - return 2000 + m_uiLe->leLongYear->getValue(); - if (m_uiTouch) - return 2000 + m_uiTouch->spYear->value(); - return 2000; + if (m_uiLe) + return 2000 + m_uiLe->leLongYear->getValue(); + if (m_uiTouch) + return 2000 + m_uiTouch->spYear->value(); + return 2000; } bool LtsDateTimeEdit::isEmpty() const { - return (isEmptyDay() || - isEmptyHHMMSS() || - isEmptyMonth() || - isEmptyTimezone() || - isEmptyYear()); + return (isEmptyDay() || isEmptyHHMMSS() || isEmptyMonth() || isEmptyTimezone() || isEmptyYear()); } bool LtsDateTimeEdit::isValidDate() const { - return m_dateIsAcceptable; + return m_dateIsAcceptable; } - bool LtsDateTimeEdit::isEmptyDay() const { - if (m_uiLe) - return m_uiLe->leLongDay->isEmpty(); - return false; + if (m_uiLe) + return m_uiLe->leLongDay->isEmpty(); + return false; } bool LtsDateTimeEdit::isEmptyHHMMSS() const { - if (m_uiLe) - return m_uiLe->leLongHHMMSS->isEmpty(); - return false; + if (m_uiLe) + return m_uiLe->leLongHHMMSS->isEmpty(); + return false; } bool LtsDateTimeEdit::isEmptyMonth() const { - if (m_uiLe) - return m_uiLe->leLongMonth->text().isEmpty(); - return false; + if (m_uiLe) + return m_uiLe->leLongMonth->text().isEmpty(); + return false; } bool LtsDateTimeEdit::isEmptyTimezone() const { - if (m_uiLe) - return m_uiLe->leLongTZ->text().isEmpty(); - return false; + if (m_uiLe) + return m_uiLe->leLongTZ->text().isEmpty(); + return false; } bool LtsDateTimeEdit::isEmptyYear() const { - if (m_uiLe) - return m_uiLe->leLongYear->isEmpty(); - return false; + if (m_uiLe) + return m_uiLe->leLongYear->isEmpty(); + return false; } bool LtsDateTimeEdit::hasFocus() const { - if (!m_uiLe) - return false; - return (m_uiLe->leLongDay->hasFocus() || - m_uiLe->leLongHHMMSS->hasFocus() || - m_uiLe->leLongMonth->hasFocus() || - m_uiLe->leLongTZ->hasFocus() || - m_uiLe->leLongYear->hasFocus()); + if (!m_uiLe) + return false; + return (m_uiLe->leLongDay->hasFocus() || m_uiLe->leLongHHMMSS->hasFocus() || m_uiLe->leLongMonth->hasFocus() || + m_uiLe->leLongTZ->hasFocus() || m_uiLe->leLongYear->hasFocus()); } bool LtsDateTimeEdit::isDataAcceptable() { - m_dateIsAcceptable = false; + m_dateIsAcceptable = false; - bool state = - isDayAcceptable() && - isHHMMSSAcceptable() && - isMonthAcceptable() && - isYearAcceptable() && - QDate::isValid(getYear(), getMonth(), getDay()) && - QTime::isValid(getHour(), getMinute(), getSecond()); + bool state = isDayAcceptable() && isHHMMSSAcceptable() && isMonthAcceptable() && isYearAcceptable() && + QDate::isValid(getYear(), getMonth(), getDay()) && QTime::isValid(getHour(), getMinute(), getSecond()); - if (m_editTimezone && state) - state = isTzAcceptable(); + if (m_editTimezone && state) + state = isTzAcceptable(); - showInvalidData(false); + showInvalidData(false); - if (!state) - { - disableControls(); - return false; - } + if (!state) + { + disableControls(); + return false; + } - qint64 msec = QDateTime(QDate(getYear(), getMonth(), getDay()), QTime(getHour(), getMinute(), getSecond()), Qt::UTC).toMSecsSinceEpoch(); - msec -= DTG::timezone2Secs(getTimezone()) * 1000LL; - if (m_minTimeMSec > 0 && m_maxTimeMSec > 0 && m_minTimeMSec < m_maxTimeMSec) - { - if (msec < m_minTimeMSec || msec > m_maxTimeMSec) - return false; - } + qint64 msec = QDateTime(QDate(getYear(), getMonth(), getDay()), QTime(getHour(), getMinute(), getSecond()), Qt::UTC) + .toMSecsSinceEpoch(); + msec -= DTG::timezone2Secs(getTimezone()) * 1000LL; + if (m_minTimeMSec > 0 && m_maxTimeMSec > 0 && m_minTimeMSec < m_maxTimeMSec) + { + if (msec < m_minTimeMSec || msec > m_maxTimeMSec) + return false; + } - m_curTimeMSec = msec; - enableControls(); - m_dateIsAcceptable = true; - return true; + m_curTimeMSec = msec; + enableControls(); + m_dateIsAcceptable = true; + return true; } bool LtsDateTimeEdit::isDayAcceptable() const { - int value = getDay(); - int max = 31; - if (isMonthAcceptable()) - { - const int month = getMonth(); - switch (month) + int value = getDay(); + int max = 31; + if (isMonthAcceptable()) { - case 2: - { - max = 28; - if (isYearAcceptable()) - { - if (getYear() % 4 == 0 && (getYear() % 100 != 0 || getYear() % 400 == 0)) - - max = 29; - } - break; + const int month = getMonth(); + switch (month) + { + case 2: { + max = 28; + if (isYearAcceptable()) + { + if (getYear() % 4 == 0 && (getYear() % 100 != 0 || getYear() % 400 == 0)) + + max = 29; + } + break; + } + case 4: + case 6: + case 9: + case 11: + max = 30; + break; + default: + break; + } } - case 4: - case 6: - case 9: - case 11: - max = 30; - break; - default: - break; - } - } - return (value > 0 && value <= max); + return (value > 0 && value <= max); } bool LtsDateTimeEdit::isHHMMSSAcceptable() const { - int hh = getHour(); - if (hh < 0 || hh > 23) - return false; + int hh = getHour(); + if (hh < 0 || hh > 23) + return false; - int mm = getMinute(); - if (mm < 0 || mm > 59) - return false; + int mm = getMinute(); + if (mm < 0 || mm > 59) + return false; - int ss = getSecond(); - if (ss < 0 || ss > 59) - return false; + int ss = getSecond(); + if (ss < 0 || ss > 59) + return false; - return true; + return true; } bool LtsDateTimeEdit::isMonthAcceptable() const { - int value = getMonth(); - return (value > 0 && value <= 12); + int value = getMonth(); + return (value > 0 && value <= 12); } bool LtsDateTimeEdit::isYearAcceptable() const { - if (m_uiLe) - return isLineEditDataAcceptable(m_uiLe->leLongYear); - return true; + if (m_uiLe) + return isLineEditDataAcceptable(m_uiLe->leLongYear); + return true; } bool LtsDateTimeEdit::isTzAcceptable() const { - if (m_uiLe) - return isLineEditDataAcceptable(m_uiLe->leLongTZ); - return true; + if (m_uiLe) + return isLineEditDataAcceptable(m_uiLe->leLongTZ); + return true; } void LtsDateTimeEdit::showInvalidData(bool setFocus) { - if (!m_uiLe) - return; + if (!m_uiLe) + return; - bool focus = setFocus; + bool focus = setFocus; - auto check = [&](QLineEdit * le, bool isValid) - { - if (isValid) - le->setStyleSheet(QString()); - else - { - le->setStyleSheet(QLatin1String("background-color: yellow;")); - if (focus) - { - le->setFocus(); - focus = false; - } - } - }; + auto check = [&](QLineEdit* le, bool isValid) { + if (isValid) + le->setStyleSheet(QString()); + else + { + le->setStyleSheet(QLatin1String("background-color: yellow;")); + if (focus) + { + le->setFocus(); + focus = false; + } + } + }; - check(m_uiLe->leLongDay, isDayAcceptable()); - check(m_uiLe->leLongHHMMSS, isHHMMSSAcceptable()); - if (m_editTimezone) - check(m_uiLe->leLongTZ, isTzAcceptable()); - check(m_uiLe->leLongMonth, isMonthAcceptable()); - check(m_uiLe->leLongYear, isYearAcceptable()); + check(m_uiLe->leLongDay, isDayAcceptable()); + check(m_uiLe->leLongHHMMSS, isHHMMSSAcceptable()); + if (m_editTimezone) + check(m_uiLe->leLongTZ, isTzAcceptable()); + check(m_uiLe->leLongMonth, isMonthAcceptable()); + check(m_uiLe->leLongYear, isYearAcceptable()); } -bool LtsDateTimeEdit::isLineEditDataAcceptable(QLineEdit *le) const +bool LtsDateTimeEdit::isLineEditDataAcceptable(QLineEdit* le) const { - const QValidator *pValidator = le->validator(); + const QValidator* pValidator = le->validator(); - if (!pValidator) - return true; + if (!pValidator) + return true; - QString text = le->text(); + QString text = le->text(); - int pos; - QValidator::State state = pValidator->validate(text, pos); + int pos; + QValidator::State state = pValidator->validate(text, pos); - if (state == QValidator::Acceptable || state == QValidator::Intermediate) - return true; + if (state == QValidator::Acceptable || state == QValidator::Intermediate) + return true; - return false; + return false; } void LtsDateTimeEdit::setFixedDateTime() { - setMsecsSinceEpoch(LtsUtils::OperatorSettings::getInstance()->value(QStringLiteral("TimeSettings"), QStringLiteral("FixedTime"), 0).toLongLong()); + setMsecsSinceEpoch(LtsUtils::OperatorSettings::getInstance() + ->value(QStringLiteral("TimeSettings"), QStringLiteral("FixedTime"), 0) + .toLongLong()); } void LtsDateTimeEdit::setOffsetDateTime() { - if (!m_getCurrentTimeCallback) - return; + if (!m_getCurrentTimeCallback) + return; - qint64 offset = LtsUtils::OperatorSettings::getInstance()->value(QStringLiteral("TimeSettings"), QStringLiteral("Offset"), 0).toLongLong(); - - setMsecsSinceEpoch((m_getCurrentTimeCallback() / 1000) * 1000 + offset); + qint64 offset = LtsUtils::OperatorSettings::getInstance() + ->value(QStringLiteral("TimeSettings"), QStringLiteral("Offset"), 0) + .toLongLong(); + + setMsecsSinceEpoch((m_getCurrentTimeCallback() / 1000) * 1000 + offset); } void LtsDateTimeEdit::setSliderValue(int val) { - setMsecsSinceEpoch(val * 1000LL); + setMsecsSinceEpoch(val * 1000LL); } -void LtsDateTimeEdit::valueDayChanged(const QString &str) +void LtsDateTimeEdit::valueDayChanged(const QString& str) { - if (!m_uiLe) - return; - int curpos = m_uiLe->leLongDay->cursorPosition(); - int cp = curpos; + if (!m_uiLe) + return; + int curpos = m_uiLe->leLongDay->cursorPosition(); + int cp = curpos; - bool changed = false; + bool changed = false; - QString tag(str); + QString tag(str); - if (tag.length() > 2) - { - tag = tag.left(2); - changed = true; - } - - bool ok; - int t = tag.toInt(&ok, 10); - - if (ok) - { - if (t > 31) + if (tag.length() > 2) { - tag.remove(curpos - 1, 1); - if (cp >= curpos) - cp--; - changed = true; + tag = tag.left(2); + changed = true; } - } - if (changed) - { - m_uiLe->leLongDay->setText(tag); - m_uiLe->leLongDay->setCursorPosition(cp); - } + bool ok; + int t = tag.toInt(&ok, 10); - if (tag.length() == 2) - { - showInvalidData(false); + if (ok) + { + if (t > 31) + { + tag.remove(curpos - 1, 1); + if (cp >= curpos) + cp--; + changed = true; + } + } - if (m_autoForward) - focusNextPrevChild(true); - } + if (changed) + { + m_uiLe->leLongDay->setText(tag); + m_uiLe->leLongDay->setCursorPosition(cp); + } + + if (tag.length() == 2) + { + showInvalidData(false); + + if (m_autoForward) + focusNextPrevChild(true); + } } void LtsDateTimeEdit::fixupHHMMSS() { - if (!m_uiLe) - return; + if (!m_uiLe) + return; - int curpos = m_uiLe->leLongHHMMSS->cursorPosition(); - int cp = curpos; + int curpos = m_uiLe->leLongHHMMSS->cursorPosition(); + int cp = curpos; - bool changed = false; + bool changed = false; - QString uhrzeit(m_uiLe->leLongHHMMSS->text()); + QString uhrzeit(m_uiLe->leLongHHMMSS->text()); - - - + QString hh; + QString mm; + QString ss; - - QString hh; - QString mm; - QString ss; - - if (uhrzeit.length() > 1) - hh = uhrzeit.left(2); - else - hh = uhrzeit + QLatin1Char('0'); - - if (uhrzeit.length() > 0) - { - if (uhrzeit.length() == 1) - hh = uhrzeit.mid(0, 1) + QLatin1Char('0'); - else if (uhrzeit.length() >= 2) - { - hh = uhrzeit.mid(0, 2); - if (uhrzeit.length() > 2) - { - if (uhrzeit.length() == 3) - mm = uhrzeit.mid(2, 1) + QLatin1Char('0'); - else if (uhrzeit.length() >= 4) - { - mm = uhrzeit.mid(2, 2); - if (uhrzeit.length() == 5) - ss = uhrzeit.mid(4, 1) + QLatin1Char('0'); - else if (uhrzeit.length() == 6) - ss = uhrzeit.mid(4, 2); - } - } - } - } - - bool ok; - - int h = hh.toInt(&ok, 10); - if (ok) - { - if (h > 23) - { - uhrzeit.remove(curpos - 1, 1); - if (cp >= curpos) - cp--; - changed = true; - } - } - - int m = mm.toInt(&ok, 10); - - if (ok) - { - if ((hh.length() == 2) && (m > 59)) - { - uhrzeit.remove(curpos - 1, 1); - if (cp >= curpos) - cp--; - changed = true; - } - } - - int s = ss.toInt(&ok, 10); - - if (ok) - { - if ((hh.length() == 2 && mm.length() == 2) && (s > 59)) - { - uhrzeit.remove(curpos - 1, 1); - if (cp >= curpos) - cp--; - changed = true; - } - } - - if (changed) - { - m_uiLe->leLongHHMMSS->setText(uhrzeit); - m_uiLe->leLongHHMMSS->setCursorPosition(cp); - } - - isDataAcceptable(); - emit dateTimeChanged(); -} - -void LtsDateTimeEdit::valueMonthChanged2(const QString &str) -{ - if (!m_uiLe) - return; - if (str.length() == 3 && m_uiLe->leLongMonth->selectedText().isEmpty()) - focusNextPrevChild(true); -} - -void LtsDateTimeEdit::valueMonthChanged(const QString &str) -{ - if (!m_uiLe) - return; - int curpos = m_uiLe->leLongMonth->cursorPosition(); - int cp = curpos; - - bool changed = false; - - QString monStr = str; - - const auto months = DTG::months(); - for (int i = 0; i < months.size(); ++i) - { - const QString &mon = months.at(i); - if (mon.startsWith(monStr, Qt::CaseInsensitive)) - { - monStr = mon; - changed = true; - break; - } - } - - if (!changed) - { - monStr.remove(curpos - 1, 1); - if (cp >= curpos) - cp--; - changed = true; - } - - if (changed) - { - m_uiLe->leLongMonth->setText(monStr); - - - if (cp > 0) - m_uiLe->leLongMonth->setCursorPosition(cp); + if (uhrzeit.length() > 1) + hh = uhrzeit.left(2); else - m_uiLe->leLongMonth->setCursorPosition(1); - } + hh = uhrzeit + QLatin1Char('0'); + + if (uhrzeit.length() > 0) + { + if (uhrzeit.length() == 1) + hh = uhrzeit.mid(0, 1) + QLatin1Char('0'); + else if (uhrzeit.length() >= 2) + { + hh = uhrzeit.mid(0, 2); + if (uhrzeit.length() > 2) + { + if (uhrzeit.length() == 3) + mm = uhrzeit.mid(2, 1) + QLatin1Char('0'); + else if (uhrzeit.length() >= 4) + { + mm = uhrzeit.mid(2, 2); + if (uhrzeit.length() == 5) + ss = uhrzeit.mid(4, 1) + QLatin1Char('0'); + else if (uhrzeit.length() == 6) + ss = uhrzeit.mid(4, 2); + } + } + } + } + + bool ok; + + int h = hh.toInt(&ok, 10); + if (ok) + { + if (h > 23) + { + uhrzeit.remove(curpos - 1, 1); + if (cp >= curpos) + cp--; + changed = true; + } + } + + int m = mm.toInt(&ok, 10); + + if (ok) + { + if ((hh.length() == 2) && (m > 59)) + { + uhrzeit.remove(curpos - 1, 1); + if (cp >= curpos) + cp--; + changed = true; + } + } + + int s = ss.toInt(&ok, 10); + + if (ok) + { + if ((hh.length() == 2 && mm.length() == 2) && (s > 59)) + { + uhrzeit.remove(curpos - 1, 1); + if (cp >= curpos) + cp--; + changed = true; + } + } + + if (changed) + { + m_uiLe->leLongHHMMSS->setText(uhrzeit); + m_uiLe->leLongHHMMSS->setCursorPosition(cp); + } + + isDataAcceptable(); + emit dateTimeChanged(); +} + +void LtsDateTimeEdit::valueMonthChanged2(const QString& str) +{ + if (!m_uiLe) + return; + if (str.length() == 3 && m_uiLe->leLongMonth->selectedText().isEmpty()) + focusNextPrevChild(true); +} + +void LtsDateTimeEdit::valueMonthChanged(const QString& str) +{ + if (!m_uiLe) + return; + int curpos = m_uiLe->leLongMonth->cursorPosition(); + int cp = curpos; + + bool changed = false; + + QString monStr = str; + + const auto months = DTG::months(); + for (int i = 0; i < months.size(); ++i) + { + const QString& mon = months.at(i); + if (mon.startsWith(monStr, Qt::CaseInsensitive)) + { + monStr = mon; + changed = true; + break; + } + } + + if (!changed) + { + monStr.remove(curpos - 1, 1); + if (cp >= curpos) + cp--; + changed = true; + } + + if (changed) + { + m_uiLe->leLongMonth->setText(monStr); + + if (cp > 0) + m_uiLe->leLongMonth->setCursorPosition(cp); + else + m_uiLe->leLongMonth->setCursorPosition(1); + } + + if (monStr.size() == 3) + { + showInvalidData(false); + if (m_autoForward) + focusNextPrevChild(true); + } +} + +void LtsDateTimeEdit::valueTimezoneChangedStr(const QString& str) +{ + if (str.length() > 1) + { + clearTimezone(); + return; + } + if (str.length() == 0) + return; + QChar c = str.at(0); + if (!c.isLetter() || c.toUpper() == QLatin1Char('J')) + { + clearTimezone(); + return; + } + if (c.isLower()) + setTimezone(c.toUpper().toLatin1()); - if (monStr.size() == 3) - { showInvalidData(false); if (m_autoForward) - focusNextPrevChild(true); - } -} - -void LtsDateTimeEdit::valueTimezoneChangedStr(const QString &str) -{ - if (str.length() > 1) - { - clearTimezone(); - return; - } - if (str.length() == 0) - return; - QChar c = str.at(0); - if (!c.isLetter() || c.toUpper() == QLatin1Char('J')) - { - clearTimezone(); - return; - } - if (c.isLower()) - setTimezone(c.toUpper().toLatin1()); - - showInvalidData(false); - if (m_autoForward) - focusNextPrevChild(true); + focusNextPrevChild(true); } void LtsDateTimeEdit::valueTimezoneChangedInt(int newTimezone) { - Q_UNUSED(newTimezone); - if (!m_uiTouch) - return; - const QString &curText = m_uiTouch->cbxTimeZone->currentText(); - if (curText.isEmpty()) - return; + Q_UNUSED(newTimezone); + if (!m_uiTouch) + return; + const QString& curText = m_uiTouch->cbxTimeZone->currentText(); + if (curText.isEmpty()) + return; - const QChar tz = curText.at(0); - setTimezone(tz.toUpper().toLatin1()); + const QChar tz = curText.at(0); + setTimezone(tz.toUpper().toLatin1()); } -void LtsDateTimeEdit::valueYearChanged(const QString &str) +void LtsDateTimeEdit::valueYearChanged(const QString& str) { - if (!m_uiLe) - return; - int curpos = m_uiLe->leLongYear->cursorPosition(); - int cp = curpos; + if (!m_uiLe) + return; + int curpos = m_uiLe->leLongYear->cursorPosition(); + int cp = curpos; - bool changed = false; + bool changed = false; - const QString &year = str; + const QString& year = str; - QString yy; - if (year.length() > 2) - { - yy = year.left(2); - changed = true; - } + QString yy; + if (year.length() > 2) + { + yy = year.left(2); + changed = true; + } - if (changed) - { - m_uiLe->leLongYear->setText(yy); - m_uiLe->leLongYear->setCursorPosition(cp); - } + if (changed) + { + m_uiLe->leLongYear->setText(yy); + m_uiLe->leLongYear->setCursorPosition(cp); + } - if (year.length() == 2) - { - showInvalidData(false); - if (m_autoForward) - focusNextPrevChild(true); - } + if (year.length() == 2) + { + showInvalidData(false); + if (m_autoForward) + focusNextPrevChild(true); + } } void LtsDateTimeEdit::onBackHourClicked() { - if (!setMsecsSinceEpoch(m_curTimeMSec - s_oneHourMSec)) - setMsecsSinceEpoch(m_minTimeMSec); + if (!setMsecsSinceEpoch(m_curTimeMSec - s_oneHourMSec)) + setMsecsSinceEpoch(m_minTimeMSec); } void LtsDateTimeEdit::onBackMinuteClicked() { - const int ofs = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? 5 : 1; - if (!setMsecsSinceEpoch(m_curTimeMSec - ofs * s_oneMinuteMSec)) - setMsecsSinceEpoch(m_minTimeMSec); + const int ofs = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? 5 : 1; + if (!setMsecsSinceEpoch(m_curTimeMSec - ofs * s_oneMinuteMSec)) + setMsecsSinceEpoch(m_minTimeMSec); } void LtsDateTimeEdit::onBackSecondClicked() { - const int ofs = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? 5 : 1; - if (!setMsecsSinceEpoch(m_curTimeMSec - ofs * s_oneSecondMSec)) - setMsecsSinceEpoch(m_minTimeMSec); + const int ofs = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? 5 : 1; + if (!setMsecsSinceEpoch(m_curTimeMSec - ofs * s_oneSecondMSec)) + setMsecsSinceEpoch(m_minTimeMSec); } void LtsDateTimeEdit::onForwardSecondClicked() { - const int ofs = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? 5 : 1; - if (!setMsecsSinceEpoch(m_curTimeMSec + ofs * s_oneSecondMSec)) - setMsecsSinceEpoch(m_maxTimeMSec); + const int ofs = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? 5 : 1; + if (!setMsecsSinceEpoch(m_curTimeMSec + ofs * s_oneSecondMSec)) + setMsecsSinceEpoch(m_maxTimeMSec); } void LtsDateTimeEdit::onForwardMinuteClicked() { - const int ofs = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? 5 : 1; - if (!setMsecsSinceEpoch(m_curTimeMSec + ofs * s_oneMinuteMSec)) - setMsecsSinceEpoch(m_maxTimeMSec); + const int ofs = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? 5 : 1; + if (!setMsecsSinceEpoch(m_curTimeMSec + ofs * s_oneMinuteMSec)) + setMsecsSinceEpoch(m_maxTimeMSec); } void LtsDateTimeEdit::onForwardHourClicked() { - if (!setMsecsSinceEpoch(m_curTimeMSec + s_oneHourMSec)) - setMsecsSinceEpoch(m_maxTimeMSec); + if (!setMsecsSinceEpoch(m_curTimeMSec + s_oneHourMSec)) + setMsecsSinceEpoch(m_maxTimeMSec); } void LtsDateTimeEdit::onCheckBoxChanged() { - QVector widgets; - bool bEnable = false; + QVector widgets; + bool bEnable = false; - if (m_uiLe) - { - widgets = {m_uiLe->leLongDay, m_uiLe->leLongHHMMSS, m_uiLe->leLongTZ, - m_uiLe->leLongMonth, m_uiLe->leLongYear}; - } + if (m_uiLe) + { + widgets = {m_uiLe->leLongDay, m_uiLe->leLongHHMMSS, m_uiLe->leLongTZ, m_uiLe->leLongMonth, m_uiLe->leLongYear}; + } - if (m_uiTouch) - { - widgets = {m_uiTouch->spDay, m_uiTouch->spHour, m_uiTouch->spMinutes, m_uiTouch->spSeconds, m_uiTouch->spYear, m_uiTouch->cbxMonth, m_uiTouch->cbxTimeZone, m_uiTouch->pbNow}; - } + if (m_uiTouch) + { + widgets = {m_uiTouch->spDay, m_uiTouch->spHour, m_uiTouch->spMinutes, m_uiTouch->spSeconds, + m_uiTouch->spYear, m_uiTouch->cbxMonth, m_uiTouch->cbxTimeZone, m_uiTouch->pbNow}; + } - bEnable = checkBox()->isChecked(); - for (auto w : std::as_const(widgets)) - { - if (w) - w->setEnabled(bEnable); - } - enaDisaControls(bEnable); + bEnable = checkBox()->isChecked(); + for (auto w : std::as_const(widgets)) + { + if (w) + w->setEnabled(bEnable); + } + enaDisaControls(bEnable); } void LtsDateTimeEdit::disableControls() { - enaDisaControls(false); + enaDisaControls(false); } void LtsDateTimeEdit::enableControls() { - if (!m_uiLe) - return; + if (!m_uiLe) + return; - enaDisaControls(true); - if (m_withSlider && - m_minTimeMSec != 0 && - m_maxTimeMSec > 0 && - m_maxTimeMSec > m_minTimeMSec) - { - m_uiLe->slTime->setEnabled(true); - m_uiLe->slTime->setValue(m_curTimeMSec / 1000LL); - } + enaDisaControls(true); + if (m_withSlider && m_minTimeMSec != 0 && m_maxTimeMSec > 0 && m_maxTimeMSec > m_minTimeMSec) + { + m_uiLe->slTime->setEnabled(true); + m_uiLe->slTime->setValue(m_curTimeMSec / 1000LL); + } } void LtsDateTimeEdit::enaDisaControls(bool bEnable) { - if (!m_uiLe) - return; - const QVector widgets({m_uiLe->pbBBB, m_uiLe->pbBB, m_uiLe->pbB, - m_uiLe->pbF, m_uiLe->pbFF, m_uiLe->pbFFF, - m_uiLe->slTime}); - for (auto w : widgets) - { - if (w) - w->setEnabled(bEnable); - } + if (!m_uiLe) + return; + const QVector widgets( + {m_uiLe->pbBBB, m_uiLe->pbBB, m_uiLe->pbB, m_uiLe->pbF, m_uiLe->pbFF, m_uiLe->pbFFF, m_uiLe->slTime}); + for (auto w : widgets) + { + if (w) + w->setEnabled(bEnable); + } } void LtsDateTimeEdit::setMinimumTimeMSec(qint64 msec) { - if (m_minTimeMSec == msec) - return; - m_minTimeMSec = msec; - if (m_minTimeMSec > 0 && m_uiLe && m_uiLe->slTime) - { - m_uiLe->slTime->setMinimum(m_minTimeMSec / 1000LL); - if (m_maxTimeMSec > m_minTimeMSec) - m_uiLe->slTime->setEnabled(true); - } - if (m_curTimeMSec < m_minTimeMSec) - setMsecsSinceEpoch(m_minTimeMSec); + if (m_minTimeMSec == msec) + return; + m_minTimeMSec = msec; + if (m_minTimeMSec > 0 && m_uiLe && m_uiLe->slTime) + { + m_uiLe->slTime->setMinimum(m_minTimeMSec / 1000LL); + if (m_maxTimeMSec > m_minTimeMSec) + m_uiLe->slTime->setEnabled(true); + } + if (m_curTimeMSec < m_minTimeMSec) + setMsecsSinceEpoch(m_minTimeMSec); } void LtsDateTimeEdit::setMaximumTimeMSec(qint64 msec) { - if (m_maxTimeMSec == msec) - return; - m_maxTimeMSec = msec; - if (!m_uiLe || !m_uiLe->slTime) - return; + if (m_maxTimeMSec == msec) + return; + m_maxTimeMSec = msec; + if (!m_uiLe || !m_uiLe->slTime) + return; - m_uiLe->slTime->setMaximum(m_maxTimeMSec / 1000LL); - if (m_minTimeMSec > 0 && m_maxTimeMSec > m_minTimeMSec) - m_uiLe->slTime->setEnabled(true); - if (m_maxTimeMSec > 0 && m_curTimeMSec > m_maxTimeMSec) - setMsecsSinceEpoch(m_maxTimeMSec); + m_uiLe->slTime->setMaximum(m_maxTimeMSec / 1000LL); + if (m_minTimeMSec > 0 && m_maxTimeMSec > m_minTimeMSec) + m_uiLe->slTime->setEnabled(true); + if (m_maxTimeMSec > 0 && m_curTimeMSec > m_maxTimeMSec) + setMsecsSinceEpoch(m_maxTimeMSec); } void LtsDateTimeEdit::clear() { - if (m_uiLe) - { - m_uiLe->leLongDay->clear(); - m_uiLe->leLongHHMMSS->clear(); - m_uiLe->leLongMonth->clear(); - m_uiLe->leLongYear->clear(); - m_uiLe->leLongTZ->clear(); - m_curTimeMSec = 0; - } - if (m_uiTouch) - { - m_uiTouch->spDay->clear(); - m_uiTouch->spHour->clear(); - m_uiTouch->spMinutes->clear(); - m_uiTouch->spSeconds->clear(); - m_uiTouch->spYear->clear(); - } - emit dateTimeChanged(); - + if (m_uiLe) + { + m_uiLe->leLongDay->clear(); + m_uiLe->leLongHHMMSS->clear(); + m_uiLe->leLongMonth->clear(); + m_uiLe->leLongYear->clear(); + m_uiLe->leLongTZ->clear(); + m_curTimeMSec = 0; + } + if (m_uiTouch) + { + m_uiTouch->spDay->clear(); + m_uiTouch->spHour->clear(); + m_uiTouch->spMinutes->clear(); + m_uiTouch->spSeconds->clear(); + m_uiTouch->spYear->clear(); + } + emit dateTimeChanged(); } void LtsDateTimeEdit::onFocusOutDay() { - if (!m_uiLe) - return; - if (m_backspacePressed) - { - m_backspacePressed = false; - return; - } - if (!m_recursionAvoid && !hasFocus()) - onFocusOut(); - - QString value = m_uiLe->leLongDay->text(); - - if (value.length() == 0 && !m_backspacePressed) - { - if (!isEmptyHHMMSS() || - !isEmptyMonth() || - (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) || - !isEmptyYear()) + if (!m_uiLe) + return; + if (m_backspacePressed) { - if (m_getCurrentTimeCallback) - { - const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_getCurrentTimeCallback(), Qt::UTC)); - setDay(dt.date().day()); - } + m_backspacePressed = false; + return; } - } - isDataAcceptable(); - emit dateTimeChanged(); + if (!m_recursionAvoid && !hasFocus()) + onFocusOut(); + + QString value = m_uiLe->leLongDay->text(); + + if (value.length() == 0 && !m_backspacePressed) + { + if (!isEmptyHHMMSS() || !isEmptyMonth() || (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) || + !isEmptyYear()) + { + if (m_getCurrentTimeCallback) + { + const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_getCurrentTimeCallback(), Qt::UTC)); + setDay(dt.date().day()); + } + } + } + isDataAcceptable(); + emit dateTimeChanged(); } void LtsDateTimeEdit::onFocusOutHHMMSS() { - if (!m_uiLe) - return; - if (m_backspacePressed) - { - m_backspacePressed = false; - return; - } - if (!m_recursionAvoid && !hasFocus()) - onFocusOut(); - - QString value = m_uiLe->leLongHHMMSS->text(); - - if (value.length() == 0 && !m_backspacePressed) - { - if (!isEmptyDay() || - !isEmptyMonth() || - !(isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) || - !isEmptyYear()) + if (!m_uiLe) + return; + if (m_backspacePressed) { - if (m_getCurrentTimeCallback) - { - const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_getCurrentTimeCallback(), Qt::UTC)); - setHHMMSS(dt.time().hour(), dt.time().minute(), dt.time().second()); - } + m_backspacePressed = false; + return; } - } - value += QString(6 - value.length(), QLatin1Char('0')); - m_uiLe->leLongHHMMSS->setText(value); - isDataAcceptable(); - emit dateTimeChanged(); + if (!m_recursionAvoid && !hasFocus()) + onFocusOut(); + + QString value = m_uiLe->leLongHHMMSS->text(); + + if (value.length() == 0 && !m_backspacePressed) + { + if (!isEmptyDay() || !isEmptyMonth() || !(isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) || !isEmptyYear()) + { + if (m_getCurrentTimeCallback) + { + const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_getCurrentTimeCallback(), Qt::UTC)); + setHHMMSS(dt.time().hour(), dt.time().minute(), dt.time().second()); + } + } + } + value += QString(6 - value.length(), QLatin1Char('0')); + m_uiLe->leLongHHMMSS->setText(value); + isDataAcceptable(); + emit dateTimeChanged(); } void LtsDateTimeEdit::onFocusOutTZ() { - if (!m_uiLe) - return; - if (m_backspacePressed) - { - m_backspacePressed = false; - return; - } - if (!m_recursionAvoid && !hasFocus()) - onFocusOut(); + if (!m_uiLe) + return; + if (m_backspacePressed) + { + m_backspacePressed = false; + return; + } + if (!m_recursionAvoid && !hasFocus()) + onFocusOut(); - QString value = m_uiLe->leLongTZ->text(); - - if (value.length() == 0 && !m_backspacePressed) - { - if (!isEmptyHHMMSS() || - !isEmptyMonth() || - !isEmptyDay() || - !isEmptyYear()) - setTimezone(DTG::timezone()); - } - isDataAcceptable(); - emit dateTimeChanged(); + QString value = m_uiLe->leLongTZ->text(); + + if (value.length() == 0 && !m_backspacePressed) + { + if (!isEmptyHHMMSS() || !isEmptyMonth() || !isEmptyDay() || !isEmptyYear()) + setTimezone(DTG::timezone()); + } + isDataAcceptable(); + emit dateTimeChanged(); } void LtsDateTimeEdit::onFocusOutMonth() { - if (!m_uiLe) - return; - if (m_backspacePressed) - { - m_backspacePressed = false; - return; - } - - if (!m_recursionAvoid && !hasFocus()) - onFocusOut(); - - QString value = m_uiLe->leLongMonth->text(); - - if (value.length() == 0 && !m_backspacePressed) - { - if (!isEmptyHHMMSS() || - !isEmptyDay() || - (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) || - !isEmptyYear()) + if (!m_uiLe) + return; + if (m_backspacePressed) { - if (m_getCurrentTimeCallback) - { - const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_getCurrentTimeCallback(), Qt::UTC)); - setMonth(dt.date().month()); - } + m_backspacePressed = false; + return; } - } - isDataAcceptable(); - emit dateTimeChanged(); + + if (!m_recursionAvoid && !hasFocus()) + onFocusOut(); + + QString value = m_uiLe->leLongMonth->text(); + + if (value.length() == 0 && !m_backspacePressed) + { + if (!isEmptyHHMMSS() || !isEmptyDay() || (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) || + !isEmptyYear()) + { + if (m_getCurrentTimeCallback) + { + const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_getCurrentTimeCallback(), Qt::UTC)); + setMonth(dt.date().month()); + } + } + } + isDataAcceptable(); + emit dateTimeChanged(); } void LtsDateTimeEdit::onFocusOutYear() { - if (!m_uiLe) - return; - if (m_backspacePressed) - { - m_backspacePressed = false; - return; - } - - if (!m_recursionAvoid && !hasFocus()) - onFocusOut(); - - QString value = m_uiLe->leLongYear->text(); - - if (value.length() == 1) - { - value = QLatin1Char('0') + value; - m_uiLe->leLongYear->setText(value); - } - - if (value.length() == 0 && !m_backspacePressed) - { - if (!isEmptyHHMMSS() || - !isEmptyMonth() || - (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) || - !isEmptyDay()) + if (!m_uiLe) + return; + if (m_backspacePressed) { - if (m_getCurrentTimeCallback) - { - const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_getCurrentTimeCallback(), Qt::UTC)); - setYear(dt.date().year()); - } + m_backspacePressed = false; + return; } - } - isDataAcceptable(); - emit dateTimeChanged(); + + if (!m_recursionAvoid && !hasFocus()) + onFocusOut(); + + QString value = m_uiLe->leLongYear->text(); + + if (value.length() == 1) + { + value = QLatin1Char('0') + value; + m_uiLe->leLongYear->setText(value); + } + + if (value.length() == 0 && !m_backspacePressed) + { + if (!isEmptyHHMMSS() || !isEmptyMonth() || (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) || + !isEmptyDay()) + { + if (m_getCurrentTimeCallback) + { + const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_getCurrentTimeCallback(), Qt::UTC)); + setYear(dt.date().year()); + } + } + } + isDataAcceptable(); + emit dateTimeChanged(); } void LtsDateTimeEdit::onFocusOutBackspace() { - m_backspacePressed = true; + m_backspacePressed = true; } void LtsDateTimeEdit::onFocusOut() { - if (!m_uiLe) - return; - if (m_backspacePressed) - { - m_backspacePressed = false; - return; - } - m_recursionAvoid = true; - onFocusOutDay(); - onFocusOutHHMMSS(); - onFocusOutMonth(); - onFocusOutTZ(); - onFocusOutYear(); - m_recursionAvoid = false; + if (!m_uiLe) + return; + if (m_backspacePressed) + { + m_backspacePressed = false; + return; + } + m_recursionAvoid = true; + onFocusOutDay(); + onFocusOutHHMMSS(); + onFocusOutMonth(); + onFocusOutTZ(); + onFocusOutYear(); + m_recursionAvoid = false; } void LtsDateTimeEdit::onHmsWheelEvent(bool bForward, int cursorPos) { - if (!m_uiLe) - return; - if (m_uiLe->leLongHHMMSS->text().size() != 6) - return; + if (!m_uiLe) + return; + if (m_uiLe->leLongHHMMSS->text().size() != 6) + return; - fixupHHMMSS(); + fixupHHMMSS(); - int selStart = 0; - switch (cursorPos) - { - case 0: - case 1: - case 2: - if (bForward) - onForwardHourClicked(); - else - onBackHourClicked(); - selStart = 0; - break; - case 3: - case 4: - if (bForward) - onForwardMinuteClicked(); - else - onBackMinuteClicked(); - selStart = 2; - break; - case 5: - case 6: - if (bForward) - onForwardSecondClicked(); - else - onBackSecondClicked(); - selStart = 4; - break; - default: - return; - } - m_uiLe->leLongHHMMSS->setCursorPosition(cursorPos); - m_uiLe->leLongHHMMSS->setSelection(selStart, 2); - emit dateTimeChanged(); + int selStart = 0; + switch (cursorPos) + { + case 0: + case 1: + case 2: + if (bForward) + onForwardHourClicked(); + else + onBackHourClicked(); + selStart = 0; + break; + case 3: + case 4: + if (bForward) + onForwardMinuteClicked(); + else + onBackMinuteClicked(); + selStart = 2; + break; + case 5: + case 6: + if (bForward) + onForwardSecondClicked(); + else + onBackSecondClicked(); + selStart = 4; + break; + default: + return; + } + m_uiLe->leLongHHMMSS->setCursorPosition(cursorPos); + m_uiLe->leLongHHMMSS->setSelection(selStart, 2); + emit dateTimeChanged(); } void LtsDateTimeEdit::onDayWheelEvent(bool bForward, int cursorPos) { - if (!m_uiLe) - return; - if (!isDayAcceptable()) - return; - const int ofs = bForward ? 1 : -1; - setMsecsSinceEpoch(m_curTimeMSec + ofs * s_oneDayMSec, true); - m_uiLe->leLongDay->setCursorPosition(cursorPos); - m_uiLe->leLongDay->setSelection(0, 2); - emit dateTimeChanged(); + if (!m_uiLe) + return; + if (!isDayAcceptable()) + return; + const int ofs = bForward ? 1 : -1; + setMsecsSinceEpoch(m_curTimeMSec + ofs * s_oneDayMSec, true); + m_uiLe->leLongDay->setCursorPosition(cursorPos); + m_uiLe->leLongDay->setSelection(0, 2); + emit dateTimeChanged(); } void LtsDateTimeEdit::onMonthWheelEvent(bool bForward, int cursorPos) { - if (!m_uiLe) - return; - if (!isMonthAcceptable()) - return; - const int ofs = bForward ? 1 : -1; - const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_curTimeMSec, Qt::UTC).addMonths(ofs)); - setMsecsSinceEpoch(dt.toMSecsSinceEpoch(), true); - m_uiLe->leLongMonth->setCursorPosition(cursorPos); - m_uiLe->leLongMonth->setSelection(0, 3); - emit dateTimeChanged(); + if (!m_uiLe) + return; + if (!isMonthAcceptable()) + return; + const int ofs = bForward ? 1 : -1; + const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_curTimeMSec, Qt::UTC).addMonths(ofs)); + setMsecsSinceEpoch(dt.toMSecsSinceEpoch(), true); + m_uiLe->leLongMonth->setCursorPosition(cursorPos); + m_uiLe->leLongMonth->setSelection(0, 3); + emit dateTimeChanged(); } void LtsDateTimeEdit::onYearWheelEvent(bool bForward, int cursorPos) { - if (!m_uiLe) - return; - if (!isYearAcceptable()) - return; - const int ofs = bForward ? 1 : -1; - const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_curTimeMSec, Qt::UTC).addYears(ofs)); - setMsecsSinceEpoch(dt.toMSecsSinceEpoch(), true); - m_uiLe->leLongYear->setCursorPosition(cursorPos); - m_uiLe->leLongYear->setSelection(0, 2); - emit dateTimeChanged(); + if (!m_uiLe) + return; + if (!isYearAcceptable()) + return; + const int ofs = bForward ? 1 : -1; + const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_curTimeMSec, Qt::UTC).addYears(ofs)); + setMsecsSinceEpoch(dt.toMSecsSinceEpoch(), true); + m_uiLe->leLongYear->setCursorPosition(cursorPos); + m_uiLe->leLongYear->setSelection(0, 2); + emit dateTimeChanged(); } -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_p.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_p.cpp old mode 100755 new mode 100644 index 2bdf1bed6..ae4d3d85c --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_p.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_p.cpp @@ -1,118 +1,109 @@ #include "lts_date_time_edit_p.h" #include +#include #include #include -#include - namespace LtsWidgets { - - - void LineEdit::clear() { - setStyleSheet(QString()); - QLineEdit::clear(); + setStyleSheet(QString()); + QLineEdit::clear(); } bool LineEdit::isEmpty() const { - return text().isEmpty(); + return text().isEmpty(); } -void LineEdit::keyPressEvent(QKeyEvent *event) +void LineEdit::keyPressEvent(QKeyEvent* event) { - const bool wasEmpty = isEmpty(); - QLineEdit::keyPressEvent(event); - int keyCode = event->key(); - if (keyCode == Qt::Key_Backspace && wasEmpty) - { - emit focusOutBackspace(); - focusPreviousChild(); - event->accept(); - } + const bool wasEmpty = isEmpty(); + QLineEdit::keyPressEvent(event); + int keyCode = event->key(); + if (keyCode == Qt::Key_Backspace && wasEmpty) + { + emit focusOutBackspace(); + focusPreviousChild(); + event->accept(); + } } -void LineEdit::contextMenuEvent(QContextMenuEvent *e) +void LineEdit::contextMenuEvent(QContextMenuEvent* e) { - Q_UNUSED(e); - + Q_UNUSED(e); } -void LineEdit::focusOutEvent(QFocusEvent *event) +void LineEdit::focusOutEvent(QFocusEvent* event) { - QLineEdit::focusOutEvent(event); - emit focusOut(); + QLineEdit::focusOutEvent(event); + emit focusOut(); } - - - -DigitsLineEdit::DigitsLineEdit(QWidget *parent) - : LineEdit(parent) +DigitsLineEdit::DigitsLineEdit(QWidget* parent) : LineEdit(parent) { - setAlignment(Qt::AlignRight); - QRegularExpression rx(QLatin1String("[-]{0,1}[0-9 ]*")); - setValidator(new QRegularExpressionValidator(rx, this)); + setAlignment(Qt::AlignRight); + QRegularExpression rx(QLatin1String("[-]{0,1}[0-9 ]*")); + setValidator(new QRegularExpressionValidator(rx, this)); } void DigitsLineEdit::setExactNumDigits(int num) { - m_exactNumDigits = num; + m_exactNumDigits = num; - QRegularExpression rx(QString::asprintf("^[0-9 ]{%d}$", num)); - setValidator(new QRegularExpressionValidator(rx, this)); + QRegularExpression rx(QString::asprintf("^[0-9 ]{%d}$", num)); + setValidator(new QRegularExpressionValidator(rx, this)); } void DigitsLineEdit::setValue(int val) { - QString str; + QString str; - if (m_exactNumDigits == -1) - str.setNum(val); - else - str = QStringLiteral("%1").arg(val, m_exactNumDigits, 10, QLatin1Char('0')); + if (m_exactNumDigits == -1) + str.setNum(val); + else + str = QStringLiteral("%1").arg(val, m_exactNumDigits, 10, QLatin1Char('0')); - setText(str); + setText(str); } int DigitsLineEdit::getValue() const { - if (text().isEmpty()) - return 0; - return text().remove(QLatin1Char(' ')).toInt(); + if (text().isEmpty()) + return 0; + return text().remove(QLatin1Char(' ')).toInt(); } void DigitsLineEdit::setCursorPosition(int curPos) { - - curPos = curPos < 0 ? 1 : curPos; - QLineEdit::setCursorPosition(curPos); + + curPos = curPos < 0 ? 1 : curPos; + QLineEdit::setCursorPosition(curPos); } -void DigitsLineEdit::wheelEvent(QWheelEvent *event) +void DigitsLineEdit::wheelEvent(QWheelEvent* event) { - LineEdit::wheelEvent(event); - const QString txt = text(); - if (m_exactNumDigits > 0 && txt.length() != m_exactNumDigits) - return; - event->accept(); - int cursorPos = cursorPosition(); - emit wheelEventReceived(event->delta() > 0, cursorPos); + LineEdit::wheelEvent(event); + const QString txt = text(); + if (m_exactNumDigits > 0 && txt.length() != m_exactNumDigits) + return; + event->accept(); + int cursorPos = cursorPosition(); + emit wheelEventReceived(event->angleDelta().y() > 0, cursorPos); } -void DigitsLineEdit::keyPressEvent(QKeyEvent *event) +void DigitsLineEdit::keyPressEvent(QKeyEvent* event) { - LineEdit::keyPressEvent(event); - if (event->key() == Qt::Key_Up || event->key() == Qt::Key_Down) - { - const bool bUp = event->key() == Qt::Key_Up; - const int cursorPos = cursorPosition(); - emit wheelEventReceived(bUp, cursorPos); - } + LineEdit::keyPressEvent(event); + if (event->key() == Qt::Key_Up || event->key() == Qt::Key_Down) + { + const bool bUp = event->key() == Qt::Key_Up; + const int cursorPos = cursorPosition(); + emit wheelEventReceived(bUp, cursorPos); + } } -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_rc.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_rc.cpp old mode 100755 new mode 100644 index d34b1fbea..6d3bf2a4f --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_rc.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_rc.cpp @@ -1,16 +1,10 @@ - #include "lts_date_time_edit.h" #include "lts_date_time_edit_p.h" - #include "ui_lts_date_time_edit_touch.h" - #include - -#include - #include #include #include @@ -24,1769 +18,1704 @@ #include #include #include +#include static constexpr qint64 s_oneSecondMSec = 1000LL; static constexpr qint64 s_oneMinuteMSec = 60 * s_oneSecondMSec; -static constexpr qint64 s_oneHourMSec = 60 * s_oneMinuteMSec; -static constexpr qint64 s_oneDayMSec = 24 * s_oneHourMSec; +static constexpr qint64 s_oneHourMSec = 60 * s_oneMinuteMSec; +static constexpr qint64 s_oneDayMSec = 24 * s_oneHourMSec; namespace Ui { class LtsDateTimeEditLe { -public: - LtsWidgets::DigitsLineEdit *leLongDay = nullptr; - LtsWidgets::DigitsLineEdit *leLongHHMMSS = nullptr; - LtsWidgets::LineEdit *leLongTZ = nullptr; - LtsWidgets::DigitsLineEdit *leLongMonth = nullptr; - LtsWidgets::DigitsLineEdit *leLongYear = nullptr; - QCheckBox *checkBox = nullptr; - QGridLayout *gridLayout = nullptr; - QPushButton *pbBBB = nullptr; - QPushButton *pbBB = nullptr; - QPushButton *pbB = nullptr; - QPushButton *pbF = nullptr; - QPushButton *pbFF = nullptr; - QPushButton *pbFFF = nullptr; - QPushButton *pbNow = nullptr; - QSlider *slTime = nullptr; + public: + LtsWidgets::DigitsLineEdit* leLongDay = nullptr; + LtsWidgets::DigitsLineEdit* leLongHHMMSS = nullptr; + LtsWidgets::LineEdit* leLongTZ = nullptr; + LtsWidgets::DigitsLineEdit* leLongMonth = nullptr; + LtsWidgets::DigitsLineEdit* leLongYear = nullptr; + QCheckBox* checkBox = nullptr; + QGridLayout* gridLayout = nullptr; + QPushButton* pbBBB = nullptr; + QPushButton* pbBB = nullptr; + QPushButton* pbB = nullptr; + QPushButton* pbF = nullptr; + QPushButton* pbFF = nullptr; + QPushButton* pbFFF = nullptr; + QPushButton* pbNow = nullptr; + QSlider* slTime = nullptr; - static void setFixedSize(QLineEdit *le, int charCount) - { - QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); - sizePolicy.setVerticalStretch(0); - sizePolicy.setHeightForWidth(false); + static void setFixedSize(QLineEdit* le, int charCount) + { + QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); + sizePolicy.setVerticalStretch(0); + sizePolicy.setHeightForWidth(false); - const QFontMetricsF fm(le->font()); - const auto textMargins = le->textMargins(); - le->setSizePolicy(sizePolicy); - charCount += 3; + const QFontMetricsF fm(le->font()); + const auto textMargins = le->textMargins(); + le->setSizePolicy(sizePolicy); + charCount += 3; #if QT_VERSION < QT_VERSION_CHECK(5, 11, 0) - const qreal w = fm.width(QLatin1Char('x')) * charCount + textMargins.left() + textMargins.right(); + const qreal w = fm.width(QLatin1Char('x')) * charCount + textMargins.left() + textMargins.right(); #else - const qreal w = fm.horizontalAdvance(QLatin1Char('x')) * charCount + textMargins.left() + textMargins.right(); + const qreal w = fm.horizontalAdvance(QLatin1Char('x')) * charCount + textMargins.left() + textMargins.right(); #endif - le->setMinimumWidth(w); - le->setMaximumWidth(w); - } + le->setMinimumWidth(w); + le->setMaximumWidth(w); + } - void setupUi(QWidget *parent) - { - gridLayout = new QGridLayout(parent); - gridLayout->setMargin(0); + void setupUi(QWidget* parent) + { + gridLayout = new QGridLayout(parent); + gridLayout->setContentsMargins(0, 0, 0, 0); - int iStart = 3; + int iStart = 3; - checkBox = new QCheckBox; - gridLayout->addWidget(checkBox, 0, iStart++, 1, 1); + checkBox = new QCheckBox; + gridLayout->addWidget(checkBox, 0, iStart++, 1, 1); - auto horizontalLayout = new QHBoxLayout; - horizontalLayout->setSpacing(0); - horizontalLayout->setContentsMargins(0, 0, 0, 0); + auto horizontalLayout = new QHBoxLayout; + horizontalLayout->setSpacing(0); + horizontalLayout->setContentsMargins(0, 0, 0, 0); - leLongDay = new LtsWidgets::DigitsLineEdit(parent); - setFixedSize(leLongDay, 2); - leLongDay->setObjectName(QStringLiteral("leLongDay")); - horizontalLayout->addWidget(leLongDay); + leLongDay = new LtsWidgets::DigitsLineEdit(parent); + setFixedSize(leLongDay, 2); + leLongDay->setObjectName(QStringLiteral("leLongDay")); + horizontalLayout->addWidget(leLongDay); - leLongHHMMSS = new LtsWidgets::DigitsLineEdit(parent); - leLongHHMMSS->setExactNumDigits(6); - setFixedSize(leLongHHMMSS, 6); - leLongHHMMSS->setObjectName(QStringLiteral("leLongHHMMSS")); - horizontalLayout->addWidget(leLongHHMMSS); + leLongHHMMSS = new LtsWidgets::DigitsLineEdit(parent); + leLongHHMMSS->setExactNumDigits(6); + setFixedSize(leLongHHMMSS, 6); + leLongHHMMSS->setObjectName(QStringLiteral("leLongHHMMSS")); + horizontalLayout->addWidget(leLongHHMMSS); - leLongTZ = new LtsWidgets::LineEdit(parent); - leLongTZ->setAlignment(Qt::AlignCenter); - setFixedSize(leLongTZ, 1); - leLongTZ->setObjectName(QStringLiteral("leLongTZ")); - horizontalLayout->addWidget(leLongTZ); + leLongTZ = new LtsWidgets::LineEdit(parent); + leLongTZ->setAlignment(Qt::AlignCenter); + setFixedSize(leLongTZ, 1); + leLongTZ->setObjectName(QStringLiteral("leLongTZ")); + horizontalLayout->addWidget(leLongTZ); - leLongMonth = new LtsWidgets::DigitsLineEdit(parent); - leLongMonth->setAlignment(Qt::AlignCenter); - setFixedSize(leLongMonth, 3); - leLongMonth->setObjectName(QStringLiteral("leLongMonth")); - horizontalLayout->addWidget(leLongMonth); + leLongMonth = new LtsWidgets::DigitsLineEdit(parent); + leLongMonth->setAlignment(Qt::AlignCenter); + setFixedSize(leLongMonth, 3); + leLongMonth->setObjectName(QStringLiteral("leLongMonth")); + horizontalLayout->addWidget(leLongMonth); - leLongYear = new LtsWidgets::DigitsLineEdit(parent); - leLongYear->setExactNumDigits(2); - setFixedSize(leLongYear, 2); - leLongYear->setObjectName(QStringLiteral("leLongYear")); - horizontalLayout->addWidget(leLongYear); + leLongYear = new LtsWidgets::DigitsLineEdit(parent); + leLongYear->setExactNumDigits(2); + setFixedSize(leLongYear, 2); + leLongYear->setObjectName(QStringLiteral("leLongYear")); + horizontalLayout->addWidget(leLongYear); - gridLayout->addLayout(horizontalLayout, 0, iStart++, 1, 1); + gridLayout->addLayout(horizontalLayout, 0, iStart++, 1, 1); - pbNow = new QPushButton(QApplication::translate("LtsDateTimeEdit", "Now", nullptr)); - pbNow->setObjectName(QStringLiteral("pbNow")); - gridLayout->addWidget(pbNow, 0, iStart++, 1, 1); + pbNow = new QPushButton(QApplication::translate("LtsDateTimeEdit", "Now", nullptr)); + pbNow->setObjectName(QStringLiteral("pbNow")); + gridLayout->addWidget(pbNow, 0, iStart++, 1, 1); - QWidget::setTabOrder(checkBox, leLongDay); - QWidget::setTabOrder(leLongDay, leLongHHMMSS); - QWidget::setTabOrder(leLongHHMMSS, leLongTZ); - QWidget::setTabOrder(leLongTZ, leLongMonth); - QWidget::setTabOrder(leLongMonth, leLongYear); - QWidget::setTabOrder(leLongYear, pbNow); + QWidget::setTabOrder(checkBox, leLongDay); + QWidget::setTabOrder(leLongDay, leLongHHMMSS); + QWidget::setTabOrder(leLongHHMMSS, leLongTZ); + QWidget::setTabOrder(leLongTZ, leLongMonth); + QWidget::setTabOrder(leLongMonth, leLongYear); + QWidget::setTabOrder(leLongYear, pbNow); - parent->setFocusProxy(leLongDay); - } + parent->setFocusProxy(leLongDay); + } - static QPushButton *addButton(const QString &text, QWidget *parent) - { - QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + static QPushButton* addButton(const QString& text, QWidget* parent) + { + QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - auto pb = new QPushButton(parent); - pb->setMinimumWidth(27); - pb->setMaximumWidth(27); - pb->setText(text); - sizePolicy.setHorizontalStretch(0); - sizePolicy.setVerticalStretch(0); - sizePolicy.setHeightForWidth(pb->sizePolicy().hasHeightForWidth()); - pb->setSizePolicy(sizePolicy); - return pb; - } + auto pb = new QPushButton(parent); + pb->setMinimumWidth(27); + pb->setMaximumWidth(27); + pb->setText(text); + sizePolicy.setHorizontalStretch(0); + sizePolicy.setVerticalStretch(0); + sizePolicy.setHeightForWidth(pb->sizePolicy().hasHeightForWidth()); + pb->setSizePolicy(sizePolicy); + return pb; + } - void addButtons(QWidget *parent) - { - pbBBB = addButton(QLatin1String("<<<"), parent); - pbBB = addButton(QLatin1String("<<"), parent); - pbB = addButton(QLatin1String("<"), parent); - gridLayout->addWidget(pbBBB, 0, 0, 1, 1); - gridLayout->addWidget(pbBB, 0, 1, 1, 1); - gridLayout->addWidget(pbB, 0, 2, 1, 1); + void addButtons(QWidget* parent) + { + pbBBB = addButton(QLatin1String("<<<"), parent); + pbBB = addButton(QLatin1String("<<"), parent); + pbB = addButton(QLatin1String("<"), parent); + gridLayout->addWidget(pbBBB, 0, 0, 1, 1); + gridLayout->addWidget(pbBB, 0, 1, 1, 1); + gridLayout->addWidget(pbB, 0, 2, 1, 1); - int iStart = 5; - pbF = addButton(QLatin1String(">"), parent); - pbFF = addButton(QLatin1String(">>"), parent); - pbFFF = addButton(QLatin1String(">>>"), parent); - gridLayout->addWidget(pbF, 0, iStart++, 1, 1); - gridLayout->addWidget(pbFF, 0, iStart++, 1, 1); - gridLayout->addWidget(pbFFF, 0, iStart++, 1, 1); - } + int iStart = 5; + pbF = addButton(QLatin1String(">"), parent); + pbFF = addButton(QLatin1String(">>"), parent); + pbFFF = addButton(QLatin1String(">>>"), parent); + gridLayout->addWidget(pbF, 0, iStart++, 1, 1); + gridLayout->addWidget(pbFF, 0, iStart++, 1, 1); + gridLayout->addWidget(pbFFF, 0, iStart++, 1, 1); + } - void addSlider(QWidget *parent) - { - slTime = new QSlider(parent); - slTime->setOrientation(Qt::Horizontal); - gridLayout->addWidget(slTime, 1, 0, 1, 7); - } + void addSlider(QWidget* parent) + { + slTime = new QSlider(parent); + slTime->setOrientation(Qt::Horizontal); + gridLayout->addWidget(slTime, 1, 0, 1, 7); + } }; -} - +} // namespace Ui namespace LtsWidgets { - - - -void setItemText(LtsWidgets::LineEdit *lineEdit, const QString &text) +void setItemText(LtsWidgets::LineEdit* lineEdit, const QString& text) { - if (!lineEdit) - return; - lineEdit->setText(text); -} -void setItemText(QComboBox *comboxBox, const QString &text) -{ - if (!comboxBox) - return; - comboxBox->setCurrentIndex(comboxBox->findText(text)); -} -void setItemData(QComboBox *comboxBox, int data) -{ - if (!comboxBox) - return; - comboxBox->setCurrentIndex(comboxBox->findData(data)); -} -void setItemValue(QSpinBox *spinBox, int value) -{ - if (!spinBox) - return; - spinBox->setValue(value); + if (!lineEdit) + return; + lineEdit->setText(text); } - -QString getItemText(LtsWidgets::LineEdit *lineEdit) +void setItemText(QComboBox* comboxBox, const QString& text) { - if (!lineEdit) - return {}; - return lineEdit->text(); -} -QString getItemText(QComboBox *comboxBox) -{ - if (!comboxBox || (comboxBox->count() <= 0)) - return {}; - const QString &curTest = comboxBox->currentText(); - if (curTest.isEmpty()) - return {}; - return curTest.at(0).toUpper(); -} -int getItemData(QComboBox *comboxBox) -{ - if (!comboxBox || (comboxBox->count() <= 0)) - return {}; - int data = comboxBox->currentData().toInt(); - return data; -} -int getItemValue(QSpinBox *spinBox) -{ - if (!spinBox) - return 0; - return spinBox->value(); + if (!comboxBox) + return; + comboxBox->setCurrentIndex(comboxBox->findText(text)); } +void setItemData(QComboBox* comboxBox, int data) +{ + if (!comboxBox) + return; + comboxBox->setCurrentIndex(comboxBox->findData(data)); +} +void setItemValue(QSpinBox* spinBox, int value) +{ + if (!spinBox) + return; + spinBox->setValue(value); +} +QString getItemText(LtsWidgets::LineEdit* lineEdit) +{ + if (!lineEdit) + return {}; + return lineEdit->text(); +} +QString getItemText(QComboBox* comboxBox) +{ + if (!comboxBox || (comboxBox->count() <= 0)) + return {}; + const QString& curTest = comboxBox->currentText(); + if (curTest.isEmpty()) + return {}; + return curTest.at(0).toUpper(); +} +int getItemData(QComboBox* comboxBox) +{ + if (!comboxBox || (comboxBox->count() <= 0)) + return {}; + int data = comboxBox->currentData().toInt(); + return data; +} -LtsDateTimeEdit::LtsDateTimeEdit(QWidget *parent, bool withNowButton, bool withCheckBox) - : QWidget(parent) +int getItemValue(QSpinBox* spinBox) +{ + if (!spinBox) + return 0; + return spinBox->value(); +} - , m_scFixed(new QShortcut(QKeySequence(Qt::ShiftModifier + Qt::Key_F2), this, SLOT(setFixedDateTime()), nullptr, Qt::WidgetWithChildrenShortcut)) - , m_scOffset(new QShortcut(QKeySequence(Qt::Key_F2), this, SLOT(setOffsetDateTime()), nullptr, Qt::WidgetWithChildrenShortcut)) - , m_withCheckBox(withCheckBox) - , m_withNowButton(withNowButton) +LtsDateTimeEdit::LtsDateTimeEdit(QWidget* parent, bool withNowButton, bool withCheckBox) + : QWidget(parent) + + , + m_scFixed(new QShortcut(QKeySequence(Qt::ShiftModifier + Qt::Key_F2), this, SLOT(setFixedDateTime()), nullptr, + Qt::WidgetWithChildrenShortcut)), + m_scOffset(new QShortcut(QKeySequence(Qt::Key_F2), this, SLOT(setOffsetDateTime()), nullptr, + Qt::WidgetWithChildrenShortcut)), + m_withCheckBox(withCheckBox), m_withNowButton(withNowButton) { #ifdef TABLET_MODE - - setupUiTouch(); - return; + + setupUiTouch(); + return; #else - - m_uiLe = new Ui::LtsDateTimeEditLe; - m_uiLe->setupUi(this); - setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); - setFocusPolicy(Qt::StrongFocus); - setContentsMargins(QMargins()); + m_uiLe = new Ui::LtsDateTimeEditLe; + m_uiLe->setupUi(this); - QCompleter *completer = new QCompleter(DTG::months(), this); - completer->setCaseSensitivity(Qt::CaseInsensitive); - completer->setCompletionMode(QCompleter::InlineCompletion); + setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); + setFocusPolicy(Qt::StrongFocus); + setContentsMargins(QMargins()); - QRegularExpression rx(DTG::months().join(QLatin1Char('|'))); - QRegularExpressionValidator *val = new QRegularExpressionValidator(rx, this); - m_uiLe->leLongMonth->setCompleter(completer); - m_uiLe->leLongMonth->setValidator(val); + QCompleter* completer = new QCompleter(DTG::months(), this); + completer->setCaseSensitivity(Qt::CaseInsensitive); + completer->setCompletionMode(QCompleter::InlineCompletion); - connect(m_uiLe->leLongDay, &DigitsLineEdit::textEdited, this, &LtsDateTimeEdit::valueDayChanged); - connect(m_uiLe->leLongMonth, &LineEdit::textEdited, this, &LtsDateTimeEdit::valueMonthChanged2); - connect(m_uiLe->leLongTZ, &LineEdit::textEdited, this, &LtsDateTimeEdit::valueTimezoneChangedStr); - connect(m_uiLe->leLongYear, &DigitsLineEdit::textEdited, this, &LtsDateTimeEdit::valueYearChanged); + QRegularExpression rx(DTG::months().join(QLatin1Char('|'))); + QRegularExpressionValidator* val = new QRegularExpressionValidator(rx, this); + m_uiLe->leLongMonth->setCompleter(completer); + m_uiLe->leLongMonth->setValidator(val); - connect(m_uiLe->leLongHHMMSS, &DigitsLineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutHHMMSS); - connect(m_uiLe->leLongDay, &DigitsLineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutDay); - connect(m_uiLe->leLongMonth, &LineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutMonth); - connect(m_uiLe->leLongTZ, &LineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutTZ); - connect(m_uiLe->leLongYear, &DigitsLineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutYear); + connect(m_uiLe->leLongDay, &DigitsLineEdit::textEdited, this, &LtsDateTimeEdit::valueDayChanged); + connect(m_uiLe->leLongMonth, &LineEdit::textEdited, this, &LtsDateTimeEdit::valueMonthChanged2); + connect(m_uiLe->leLongTZ, &LineEdit::textEdited, this, &LtsDateTimeEdit::valueTimezoneChangedStr); + connect(m_uiLe->leLongYear, &DigitsLineEdit::textEdited, this, &LtsDateTimeEdit::valueYearChanged); - connect(m_uiLe->leLongHHMMSS, &DigitsLineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); - connect(m_uiLe->leLongDay, &DigitsLineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); - connect(m_uiLe->leLongMonth, &LineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); - connect(m_uiLe->leLongTZ, &LineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); - connect(m_uiLe->leLongYear, &DigitsLineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); + connect(m_uiLe->leLongHHMMSS, &DigitsLineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutHHMMSS); + connect(m_uiLe->leLongDay, &DigitsLineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutDay); + connect(m_uiLe->leLongMonth, &LineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutMonth); + connect(m_uiLe->leLongTZ, &LineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutTZ); + connect(m_uiLe->leLongYear, &DigitsLineEdit::focusOut, this, &LtsDateTimeEdit::onFocusOutYear); - connect(m_uiLe->leLongHHMMSS, &DigitsLineEdit::wheelEventReceived, this, &LtsDateTimeEdit::onHmsWheelEvent); - connect(m_uiLe->leLongDay, &DigitsLineEdit::wheelEventReceived, this, &LtsDateTimeEdit::onDayWheelEvent); - connect(m_uiLe->leLongMonth, &DigitsLineEdit::wheelEventReceived, this, &LtsDateTimeEdit::onMonthWheelEvent); - connect(m_uiLe->leLongYear, &DigitsLineEdit::wheelEventReceived, this, &LtsDateTimeEdit::onYearWheelEvent); + connect(m_uiLe->leLongHHMMSS, &DigitsLineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); + connect(m_uiLe->leLongDay, &DigitsLineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); + connect(m_uiLe->leLongMonth, &LineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); + connect(m_uiLe->leLongTZ, &LineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); + connect(m_uiLe->leLongYear, &DigitsLineEdit::focusOutBackspace, this, &LtsDateTimeEdit::onFocusOutBackspace); - connect(m_uiLe->checkBox, &QCheckBox::toggled, this, &LtsDateTimeEdit::onCheckBoxChanged); - connect(m_uiLe->pbNow, &QPushButton::clicked, this, &LtsDateTimeEdit::setOffsetDateTime); + connect(m_uiLe->leLongHHMMSS, &DigitsLineEdit::wheelEventReceived, this, &LtsDateTimeEdit::onHmsWheelEvent); + connect(m_uiLe->leLongDay, &DigitsLineEdit::wheelEventReceived, this, &LtsDateTimeEdit::onDayWheelEvent); + connect(m_uiLe->leLongMonth, &DigitsLineEdit::wheelEventReceived, this, &LtsDateTimeEdit::onMonthWheelEvent); + connect(m_uiLe->leLongYear, &DigitsLineEdit::wheelEventReceived, this, &LtsDateTimeEdit::onYearWheelEvent); - setTimezone(DTG::timezone()); + connect(m_uiLe->checkBox, &QCheckBox::toggled, this, &LtsDateTimeEdit::onCheckBoxChanged); + connect(m_uiLe->pbNow, &QPushButton::clicked, this, &LtsDateTimeEdit::setOffsetDateTime); - bool temp = m_withCheckBox; - m_withCheckBox = !m_withCheckBox; - setWithCheckBox(temp); + setTimezone(DTG::timezone()); - temp = m_withNowButton; - m_withNowButton = !m_withNowButton; - setWithNowButton(temp); + bool temp = m_withCheckBox; + m_withCheckBox = !m_withCheckBox; + setWithCheckBox(temp); - onCheckBoxChanged(); + temp = m_withNowButton; + m_withNowButton = !m_withNowButton; + setWithNowButton(temp); + + onCheckBoxChanged(); #endif } LtsDateTimeEdit::~LtsDateTimeEdit() { - delete m_uiLe; + delete m_uiLe; } bool LtsDateTimeEdit::setupUiTouch() { - m_uiTouch = new Ui::LtsDateTimeEdit; - m_uiTouch->setupUi(this); - setFocusPolicy(Qt::StrongFocus); + m_uiTouch = new Ui::LtsDateTimeEdit; + m_uiTouch->setupUi(this); + setFocusPolicy(Qt::StrongFocus); - for (int i = 65; i < 91; i++ ) - { - if (QChar(i).toUpper() == QChar::fromLatin1('I')) - continue; - m_uiTouch->cbxTimeZone->addItem(QChar(i), QChar(i)); - } + for (int i = 65; i < 91; i++) + { + if (QChar(i).toUpper() == QChar::fromLatin1('I')) + continue; + m_uiTouch->cbxTimeZone->addItem(QChar(i), QChar(i)); + } - connect(m_uiTouch->pbNow, &QPushButton::clicked, - this, &LtsDateTimeEdit::setOffsetDateTime); - connect(m_uiTouch->cbxMonth, static_cast(&QComboBox::currentIndexChanged), - this, &LtsDateTimeEdit::dateTimeChanged); - connect(m_uiTouch->spDay, &QSpinBox::editingFinished, - this, &LtsDateTimeEdit::dateTimeChanged); - connect(m_uiTouch->spHour, &QSpinBox::editingFinished, - this, &LtsDateTimeEdit::dateTimeChanged); - connect(m_uiTouch->spMinutes, &QSpinBox::editingFinished, - this, &LtsDateTimeEdit::dateTimeChanged); - connect(m_uiTouch->spSeconds, &QSpinBox::editingFinished, - this, &LtsDateTimeEdit::dateTimeChanged); - connect(m_uiTouch->spYear, &QSpinBox::editingFinished, - this, &LtsDateTimeEdit::dateTimeChanged); + connect(m_uiTouch->pbNow, &QPushButton::clicked, this, &LtsDateTimeEdit::setOffsetDateTime); + connect(m_uiTouch->cbxMonth, static_cast(&QComboBox::currentIndexChanged), this, + &LtsDateTimeEdit::dateTimeChanged); + connect(m_uiTouch->spDay, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::dateTimeChanged); + connect(m_uiTouch->spHour, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::dateTimeChanged); + connect(m_uiTouch->spMinutes, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::dateTimeChanged); + connect(m_uiTouch->spSeconds, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::dateTimeChanged); + connect(m_uiTouch->spYear, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::dateTimeChanged); - connect(m_uiTouch->checkBox, &QCheckBox::toggled, - this, &LtsDateTimeEdit::onCheckBoxChanged); - connect(m_uiTouch->cbxTimeZone, static_cast(&QComboBox::currentIndexChanged), - this, &LtsDateTimeEdit::valueTimezoneChangedInt); + connect(m_uiTouch->checkBox, &QCheckBox::toggled, this, &LtsDateTimeEdit::onCheckBoxChanged); + connect(m_uiTouch->cbxTimeZone, static_cast(&QComboBox::currentIndexChanged), this, + &LtsDateTimeEdit::valueTimezoneChangedInt); - - - connect(m_uiTouch->cbxMonth, &QComboBox::currentTextChanged, - this, &LtsDateTimeEdit::valueMonthChanged); + connect(m_uiTouch->cbxMonth, &QComboBox::currentTextChanged, this, &LtsDateTimeEdit::valueMonthChanged); + setMinMaxMonth(1, 12); - setMinMaxMonth(1,12); + setTimezone(DTG::timezone()); - setTimezone(DTG::timezone()); - + bool temp = m_withCheckBox; + m_withCheckBox = !m_withCheckBox; + setWithCheckBox(temp); - bool temp = m_withCheckBox; - m_withCheckBox = !m_withCheckBox; - setWithCheckBox(temp); + temp = m_withNowButton; + m_withNowButton = !m_withNowButton; + setWithNowButton(temp); - temp = m_withNowButton; - m_withNowButton = !m_withNowButton; - setWithNowButton(temp); + onCheckBoxChanged(); - onCheckBoxChanged(); - - - return true; + return true; } - -void LtsDateTimeEdit::setRetrieveCurrentTimeCallback(const CurrentTimeCallback &cb) +void LtsDateTimeEdit::setRetrieveCurrentTimeCallback(const CurrentTimeCallback& cb) { - m_getCurrentTimeCallback = cb; + m_getCurrentTimeCallback = cb; } void LtsDateTimeEdit::setEditTimezone(const bool edit) { - m_editTimezone = edit; - if (m_uiLe) - m_uiLe->leLongTZ->setEnabled(m_editTimezone); - if (m_uiTouch) - m_uiTouch->cbxTimeZone->setEnabled(m_editTimezone); + m_editTimezone = edit; + if (m_uiLe) + m_uiLe->leLongTZ->setEnabled(m_editTimezone); + if (m_uiTouch) + m_uiTouch->cbxTimeZone->setEnabled(m_editTimezone); } void LtsDateTimeEdit::setWithButtons(const bool buttons) { - m_withButtons = buttons; - if (buttons) - { - if (!m_uiLe->pbBBB) + m_withButtons = buttons; + if (buttons) { - m_uiLe->addButtons(this); - connect(m_uiLe->pbBBB, &QPushButton::clicked, this, &LtsDateTimeEdit::onBackHourClicked); - connect(m_uiLe->pbBB, &QPushButton::clicked, this, &LtsDateTimeEdit::onBackMinuteClicked); - connect(m_uiLe->pbB, &QPushButton::clicked, this, &LtsDateTimeEdit::onBackSecondClicked); - connect(m_uiLe->pbF, &QPushButton::clicked, this, &LtsDateTimeEdit::onForwardSecondClicked); - connect(m_uiLe->pbFF, &QPushButton::clicked, this, &LtsDateTimeEdit::onForwardMinuteClicked); - connect(m_uiLe->pbFFF, &QPushButton::clicked, this, &LtsDateTimeEdit::onForwardHourClicked); - disableControls(); + if (!m_uiLe->pbBBB) + { + m_uiLe->addButtons(this); + connect(m_uiLe->pbBBB, &QPushButton::clicked, this, &LtsDateTimeEdit::onBackHourClicked); + connect(m_uiLe->pbBB, &QPushButton::clicked, this, &LtsDateTimeEdit::onBackMinuteClicked); + connect(m_uiLe->pbB, &QPushButton::clicked, this, &LtsDateTimeEdit::onBackSecondClicked); + connect(m_uiLe->pbF, &QPushButton::clicked, this, &LtsDateTimeEdit::onForwardSecondClicked); + connect(m_uiLe->pbFF, &QPushButton::clicked, this, &LtsDateTimeEdit::onForwardMinuteClicked); + connect(m_uiLe->pbFFF, &QPushButton::clicked, this, &LtsDateTimeEdit::onForwardHourClicked); + disableControls(); + } } - } - else - { - delete m_uiLe->pbBBB; - delete m_uiLe->pbBB; - delete m_uiLe->pbB; - delete m_uiLe->pbFFF; - delete m_uiLe->pbFF; - delete m_uiLe->pbF; + else + { + delete m_uiLe->pbBBB; + delete m_uiLe->pbBB; + delete m_uiLe->pbB; + delete m_uiLe->pbFFF; + delete m_uiLe->pbFF; + delete m_uiLe->pbF; - m_uiLe->pbBBB = nullptr; - m_uiLe->pbBB = nullptr; - m_uiLe->pbB = nullptr; - m_uiLe->pbFFF = nullptr; - m_uiLe->pbFF = nullptr; - m_uiLe->pbF = nullptr; - } + m_uiLe->pbBBB = nullptr; + m_uiLe->pbBB = nullptr; + m_uiLe->pbB = nullptr; + m_uiLe->pbFFF = nullptr; + m_uiLe->pbFF = nullptr; + m_uiLe->pbF = nullptr; + } } void LtsDateTimeEdit::setWithSlider(const bool slider) { - m_withSlider = slider; + m_withSlider = slider; - if (!m_uiLe) - return; + if (!m_uiLe) + return; - if (slider) - { - m_uiLe->addSlider(this); - m_uiLe->slTime->setMinimum(m_minTimeMSec / 1000); - m_uiLe->slTime->setMaximum(m_maxTimeMSec > 0 ? m_maxTimeMSec / 1000 : time(nullptr)); - connect(m_uiLe->slTime, &QSlider::sliderMoved, this, &LtsDateTimeEdit::setSliderValue); - disableControls(); - } - else - { - delete m_uiLe->slTime; - m_uiLe->slTime = nullptr; - } + if (slider) + { + m_uiLe->addSlider(this); + m_uiLe->slTime->setMinimum(m_minTimeMSec / 1000); + m_uiLe->slTime->setMaximum(m_maxTimeMSec > 0 ? m_maxTimeMSec / 1000 : time(nullptr)); + connect(m_uiLe->slTime, &QSlider::sliderMoved, this, &LtsDateTimeEdit::setSliderValue); + disableControls(); + } + else + { + delete m_uiLe->slTime; + m_uiLe->slTime = nullptr; + } } void LtsDateTimeEdit::setReadOnly(const bool readOnly) { - if (m_readOnly == readOnly) - return; - m_readOnly = readOnly; + if (m_readOnly == readOnly) + return; + m_readOnly = readOnly; - if (m_uiLe) - { - m_uiLe->leLongDay->setReadOnly(m_readOnly); - m_uiLe->leLongHHMMSS->setReadOnly(m_readOnly); - m_uiLe->leLongMonth->setReadOnly(m_readOnly); - m_uiLe->leLongTZ->setReadOnly(m_readOnly); - m_uiLe->leLongYear->setReadOnly(m_readOnly); - } - if (m_uiTouch) - { - m_uiTouch->spDay->setReadOnly(m_readOnly); - m_uiTouch->spHour->setReadOnly(m_readOnly); - m_uiTouch->spMinutes->setReadOnly(m_readOnly); - m_uiTouch->spSeconds->setReadOnly(m_readOnly); - m_uiTouch->spYear->setReadOnly(m_readOnly); - m_uiTouch->cbxTimeZone->setEnabled(m_readOnly); - } + if (m_uiLe) + { + m_uiLe->leLongDay->setReadOnly(m_readOnly); + m_uiLe->leLongHHMMSS->setReadOnly(m_readOnly); + m_uiLe->leLongMonth->setReadOnly(m_readOnly); + m_uiLe->leLongTZ->setReadOnly(m_readOnly); + m_uiLe->leLongYear->setReadOnly(m_readOnly); + } + if (m_uiTouch) + { + m_uiTouch->spDay->setReadOnly(m_readOnly); + m_uiTouch->spHour->setReadOnly(m_readOnly); + m_uiTouch->spMinutes->setReadOnly(m_readOnly); + m_uiTouch->spSeconds->setReadOnly(m_readOnly); + m_uiTouch->spYear->setReadOnly(m_readOnly); + m_uiTouch->cbxTimeZone->setEnabled(m_readOnly); + } } void LtsDateTimeEdit::setWithCheckBox(bool checkBoxEnabled) { - if (m_withCheckBox == checkBoxEnabled) - return; + if (m_withCheckBox == checkBoxEnabled) + return; - m_withCheckBox = checkBoxEnabled; - if (m_uiLe) - { - m_uiLe->checkBox->setVisible(m_withCheckBox); - if (!m_withCheckBox) - m_uiLe->checkBox->setChecked(true); - } - if (m_uiTouch) - { - m_uiTouch->checkBox->setVisible(m_withCheckBox); - if (!m_withCheckBox) - m_uiTouch->checkBox->setChecked(true); - } + m_withCheckBox = checkBoxEnabled; + if (m_uiLe) + { + m_uiLe->checkBox->setVisible(m_withCheckBox); + if (!m_withCheckBox) + m_uiLe->checkBox->setChecked(true); + } + if (m_uiTouch) + { + m_uiTouch->checkBox->setVisible(m_withCheckBox); + if (!m_withCheckBox) + m_uiTouch->checkBox->setChecked(true); + } } void LtsDateTimeEdit::setCheckBoxChecked(bool bChecked) { - if (!m_uiLe) - return; - m_uiLe->checkBox->setChecked(bChecked); + if (!m_uiLe) + return; + m_uiLe->checkBox->setChecked(bChecked); } bool LtsDateTimeEdit::isCheckBoxChecked() const { - if (!m_uiLe) - return false; - return m_uiLe->checkBox->isChecked(); + if (!m_uiLe) + return false; + return m_uiLe->checkBox->isChecked(); } void LtsDateTimeEdit::setWithNowButton(bool nowButton) { - if (m_withNowButton == nowButton) - return; + if (m_withNowButton == nowButton) + return; - m_withNowButton = nowButton; - if (m_uiLe) - m_uiLe->pbNow->setVisible(m_withNowButton); - if (m_uiTouch) - m_uiTouch->pbNow->setVisible(m_withNowButton); + m_withNowButton = nowButton; + if (m_uiLe) + m_uiLe->pbNow->setVisible(m_withNowButton); + if (m_uiTouch) + m_uiTouch->pbNow->setVisible(m_withNowButton); } bool LtsDateTimeEdit::setMsecsSinceEpoch(qint64 msec, bool setToNearestPossible) { - if (msec == 0 && m_withCheckBox) - { + if (msec == 0 && m_withCheckBox) + { + if (m_uiLe) + m_uiLe->checkBox->setChecked(false); + m_dateIsAcceptable = true; + return true; + } if (m_uiLe) - m_uiLe->checkBox->setChecked(false); - m_dateIsAcceptable = true; - return true; - } - if (m_uiLe) - m_uiLe->checkBox->setChecked(true); + m_uiLe->checkBox->setChecked(true); - m_dateIsAcceptable = false; - if (msec == 0) - return false; + m_dateIsAcceptable = false; + if (msec == 0) + return false; - - - - + if (!setToNearestPossible) + { + if (!isDataAcceptable()) + return false; + } + else + { + if (msec < m_minTimeMSec && m_minTimeMSec > 0) + msec = m_minTimeMSec; + if (msec > m_maxTimeMSec && m_maxTimeMSec > 0) + msec = m_maxTimeMSec; + } + + m_curTimeMSec = msec; + + const qint64 offsetTimeZoneMsec = getTimezoneAsSecs() * 1000; + const QDateTime datetime(QDateTime::fromMSecsSinceEpoch(m_curTimeMSec + offsetTimeZoneMsec, Qt::UTC)); + const QDate date(datetime.date()); + const QTime time(datetime.time()); + + const int day = date.day(); + const int month = date.month(); + const int year = date.year(); + const int hour = time.hour(); + const int minute = time.minute(); + const int second = time.second(); + + if (!setYear(year) || !setMonth(month) || !setDay(day) || !setHHMMSS(hour, minute, second)) + return false; - if (!setToNearestPossible) - { if (!isDataAcceptable()) - return false; - } - else - { - if (msec < m_minTimeMSec && m_minTimeMSec > 0) - msec = m_minTimeMSec; - if (msec > m_maxTimeMSec && m_maxTimeMSec > 0) - msec = m_maxTimeMSec; - } + return false; - m_curTimeMSec = msec; + enableControls(); - const qint64 offsetTimeZoneMsec = getTimezoneAsSecs() * 1000; - const QDateTime datetime(QDateTime::fromMSecsSinceEpoch(m_curTimeMSec + offsetTimeZoneMsec, Qt::UTC)); - const QDate date(datetime.date()); - const QTime time(datetime.time()); + emit dateTimeChanged(); - const int day = date.day(); - const int month = date.month(); - const int year = date.year(); - const int hour = time.hour(); - const int minute = time.minute(); - const int second = time.second(); - - - if (!setYear(year) || - !setMonth(month) || - !setDay(day) || - !setHHMMSS(hour, minute, second)) - return false; - - if (!isDataAcceptable()) - return false; - - enableControls(); - - emit dateTimeChanged(); - - return true; + return true; } - qint64 LtsDateTimeEdit::msecsSinceEpoch() const { - if (isEmpty()) - return 0; + if (isEmpty()) + return 0; - if (m_uiLe && !m_uiLe->checkBox->isChecked()) - return 0; - if (m_uiTouch && !m_uiTouch->checkBox->isChecked()) - return 0; + if (m_uiLe && !m_uiLe->checkBox->isChecked()) + return 0; + if (m_uiTouch && !m_uiTouch->checkBox->isChecked()) + return 0; - auto that = const_cast(this); - if (!that->isDataAcceptable()) - return 0; + auto that = const_cast(this); + if (!that->isDataAcceptable()) + return 0; - return m_curTimeMSec; + return m_curTimeMSec; } bool LtsDateTimeEdit::setTimezone(char tz) { - tz = toupper(tz); - if (!DTG::isTimezoneValid(tz)) - return false; + tz = toupper(tz); + if (!DTG::isTimezoneValid(tz)) + return false; - if (m_uiLe) - setItemText(m_uiLe->leLongTZ, QString(QLatin1Char(tz))); - if (m_uiTouch) - setItemText(m_uiTouch->cbxTimeZone, QString(QLatin1Char(tz))); + if (m_uiLe) + setItemText(m_uiLe->leLongTZ, QString(QLatin1Char(tz))); + if (m_uiTouch) + setItemText(m_uiTouch->cbxTimeZone, QString(QLatin1Char(tz))); - setMsecsSinceEpoch(m_curTimeMSec); + setMsecsSinceEpoch(m_curTimeMSec); - return true; + return true; } char LtsDateTimeEdit::getTimezone() const { - QString str; - if (m_uiLe) - str = getItemText(m_uiLe->leLongTZ); - if (m_uiTouch) - str = getItemText(m_uiTouch->cbxTimeZone); + QString str; + if (m_uiLe) + str = getItemText(m_uiLe->leLongTZ); + if (m_uiTouch) + str = getItemText(m_uiTouch->cbxTimeZone); - if (str.isEmpty()) - return DTG::timezone(); - return str[0].toUpper().toLatin1(); + if (str.isEmpty()) + return DTG::timezone(); + return str[0].toUpper().toLatin1(); } qint64 LtsDateTimeEdit::getTimezoneAsSecs() const { - const char tzGUI = getTimezone(); - return DTG::timezone2Secs(tzGUI); + const char tzGUI = getTimezone(); + return DTG::timezone2Secs(tzGUI); } void LtsDateTimeEdit::clearTimezone() { - if (m_uiLe) - m_uiLe->leLongTZ->clear(); - if (m_uiTouch) - m_uiTouch->cbxTimeZone->setCurrentIndex(0); + if (m_uiLe) + m_uiLe->leLongTZ->clear(); + if (m_uiTouch) + m_uiTouch->cbxTimeZone->setCurrentIndex(0); } void LtsDateTimeEdit::setMinMaxMonth(int minMonth, int maxMonth) { - if (!m_uiTouch) - return; + if (!m_uiTouch) + return; - if (m_minMonth != minMonth) - m_minMonth = minMonth; - if (m_maxMonth != maxMonth) - m_maxMonth = maxMonth; + if (m_minMonth != minMonth) + m_minMonth = minMonth; + if (m_maxMonth != maxMonth) + m_maxMonth = maxMonth; - int currentMonth = m_uiTouch->cbxMonth->currentData().toInt(); - m_uiTouch->cbxMonth->blockSignals(true); - m_uiTouch->cbxMonth->clear(); - for (int i =1; i<= 12 ; ++i) - { - if (i < m_minMonth) - continue; - if (i > m_maxMonth) - break; + int currentMonth = m_uiTouch->cbxMonth->currentData().toInt(); + m_uiTouch->cbxMonth->blockSignals(true); + m_uiTouch->cbxMonth->clear(); + for (int i = 1; i <= 12; ++i) + { + if (i < m_minMonth) + continue; + if (i > m_maxMonth) + break; - const QStringList monthSl = DTG::months(); - m_uiTouch->cbxMonth->addItem(monthSl[i-1], i); - - + const QStringList monthSl = DTG::months(); + m_uiTouch->cbxMonth->addItem(monthSl[i - 1], i); + } - } - - - m_uiTouch->cbxMonth->setCurrentIndex(m_uiTouch->cbxMonth->findData(currentMonth)); - m_uiTouch->cbxMonth->blockSignals(false); + m_uiTouch->cbxMonth->setCurrentIndex(m_uiTouch->cbxMonth->findData(currentMonth)); + m_uiTouch->cbxMonth->blockSignals(false); } - -void LtsDateTimeEdit::setSubWidgetsProperties(const QString &name, const QVariant &value) +void LtsDateTimeEdit::setSubWidgetsProperties(const QString& name, const QVariant& value) { - if (m_uiLe) - { - m_uiLe->leLongDay->setProperty(name.toStdString().c_str(), value); - m_uiLe->leLongHHMMSS->setProperty(name.toStdString().c_str(), value); - m_uiLe->leLongMonth->setProperty(name.toStdString().c_str(), value); - m_uiLe->leLongYear->setProperty(name.toStdString().c_str(), value); - m_uiLe->leLongTZ->setProperty(name.toStdString().c_str(), value); - } - if (m_uiTouch) - { - m_uiTouch->spDay->setProperty(name.toStdString().c_str(), value); - m_uiTouch->spHour->setProperty(name.toStdString().c_str(), value); - m_uiTouch->spMinutes->setProperty(name.toStdString().c_str(), value); - m_uiTouch->spSeconds->setProperty(name.toStdString().c_str(), value); - m_uiTouch->spYear->setProperty(name.toStdString().c_str(), value); - } + if (m_uiLe) + { + m_uiLe->leLongDay->setProperty(name.toStdString().c_str(), value); + m_uiLe->leLongHHMMSS->setProperty(name.toStdString().c_str(), value); + m_uiLe->leLongMonth->setProperty(name.toStdString().c_str(), value); + m_uiLe->leLongYear->setProperty(name.toStdString().c_str(), value); + m_uiLe->leLongTZ->setProperty(name.toStdString().c_str(), value); + } + if (m_uiTouch) + { + m_uiTouch->spDay->setProperty(name.toStdString().c_str(), value); + m_uiTouch->spHour->setProperty(name.toStdString().c_str(), value); + m_uiTouch->spMinutes->setProperty(name.toStdString().c_str(), value); + m_uiTouch->spSeconds->setProperty(name.toStdString().c_str(), value); + m_uiTouch->spYear->setProperty(name.toStdString().c_str(), value); + } } bool LtsDateTimeEdit::setMonth(int month) { - const auto months(DTG::months()); - if (month < 1 || month > months.size()) - return false; + const auto months(DTG::months()); + if (month < 1 || month > months.size()) + return false; - if (m_uiLe) - setItemText(m_uiLe->leLongMonth, months.at(month - 1)); - if (m_uiTouch) - setItemData(m_uiTouch->cbxMonth, month); - return true; + if (m_uiLe) + setItemText(m_uiLe->leLongMonth, months.at(month - 1)); + if (m_uiTouch) + setItemData(m_uiTouch->cbxMonth, month); + return true; } int LtsDateTimeEdit::getMonth() const { - if (m_uiLe) - { - const QString str = getItemText(m_uiLe->leLongMonth); - if (str.length() != 3) - return -1; + if (m_uiLe) + { + const QString str = getItemText(m_uiLe->leLongMonth); + if (str.length() != 3) + return -1; - int idx = DTG::months().indexOf(str); - if (idx < 0) - return -1; - return idx + 1; - } - if (m_uiTouch) - { - int month = getItemData(m_uiTouch->cbxMonth); - return month; - } - return 0; + int idx = DTG::months().indexOf(str); + if (idx < 0) + return -1; + return idx + 1; + } + if (m_uiTouch) + { + int month = getItemData(m_uiTouch->cbxMonth); + return month; + } + return 0; } bool LtsDateTimeEdit::setDay(int day) { - if (day < 1 || day > 31) - return false; + if (day < 1 || day > 31) + return false; - QString oldDay; - if (m_uiLe) - oldDay = m_uiLe->leLongDay->text(); - int oldDayInt = 0; - if (m_uiTouch) - oldDayInt = getItemValue(m_uiTouch->spDay); - - if (m_uiLe) - setItemText(m_uiLe->leLongDay, QStringLiteral("%1").arg(day, 2, 10, QLatin1Char('0'))); - if (m_uiTouch) - setItemValue(m_uiTouch->spDay, day); - - if (!isDayAcceptable()) - { + QString oldDay; if (m_uiLe) - setItemText(m_uiLe->leLongDay, oldDay); + oldDay = m_uiLe->leLongDay->text(); + int oldDayInt = 0; if (m_uiTouch) - setItemValue(m_uiTouch->spDay, oldDayInt); - return false; - } + oldDayInt = getItemValue(m_uiTouch->spDay); - return true; + if (m_uiLe) + setItemText(m_uiLe->leLongDay, QStringLiteral("%1").arg(day, 2, 10, QLatin1Char('0'))); + if (m_uiTouch) + setItemValue(m_uiTouch->spDay, day); + + if (!isDayAcceptable()) + { + if (m_uiLe) + setItemText(m_uiLe->leLongDay, oldDay); + if (m_uiTouch) + setItemValue(m_uiTouch->spDay, oldDayInt); + return false; + } + + return true; } int LtsDateTimeEdit::getDay() const { - if (m_uiLe) - return m_uiLe->leLongDay->getValue(); - if (m_uiTouch) - return getItemValue(m_uiTouch->spDay); - return 0; + if (m_uiLe) + return m_uiLe->leLongDay->getValue(); + if (m_uiTouch) + return getItemValue(m_uiTouch->spDay); + return 0; } bool LtsDateTimeEdit::setHHMMSS(int hour, int minute, int second) { - if (hour < 0 || hour > 23 || - minute < 0 || minute > 59 || - second < 0 || second > 59) - return false; + if (hour < 0 || hour > 23 || minute < 0 || minute > 59 || second < 0 || second > 59) + return false; - if (m_uiLe) - m_uiLe->leLongHHMMSS->setValue(hour * 10000 + minute * 100 + second); - if (m_uiTouch) - { - setItemValue(m_uiTouch->spHour , hour); - setItemValue(m_uiTouch->spMinutes, minute); - setItemValue(m_uiTouch->spSeconds, second); - } + if (m_uiLe) + m_uiLe->leLongHHMMSS->setValue(hour * 10000 + minute * 100 + second); + if (m_uiTouch) + { + setItemValue(m_uiTouch->spHour, hour); + setItemValue(m_uiTouch->spMinutes, minute); + setItemValue(m_uiTouch->spSeconds, second); + } - return true; + return true; } int LtsDateTimeEdit::getHour() const { - if (m_uiLe) - { - const int time = m_uiLe->leLongHHMMSS->getValue(); - return time / 10000; - } - if (m_uiTouch) - { - return getItemValue(m_uiTouch->spHour); - } - return 0; + if (m_uiLe) + { + const int time = m_uiLe->leLongHHMMSS->getValue(); + return time / 10000; + } + if (m_uiTouch) + { + return getItemValue(m_uiTouch->spHour); + } + return 0; } int LtsDateTimeEdit::getMinute() const { - if (m_uiLe) - { - const int time = m_uiLe->leLongHHMMSS->getValue(); - return (time / 100) % 100; - } - if (m_uiTouch) - { - return getItemValue(m_uiTouch->spMinutes); - } - return 0; + if (m_uiLe) + { + const int time = m_uiLe->leLongHHMMSS->getValue(); + return (time / 100) % 100; + } + if (m_uiTouch) + { + return getItemValue(m_uiTouch->spMinutes); + } + return 0; } int LtsDateTimeEdit::getSecond() const { - if (m_uiLe) - { - const int time = m_uiLe->leLongHHMMSS->getValue(); - return time % 100; - } - if (m_uiTouch) - { - return getItemValue(m_uiTouch->spSeconds); - } - return 0; + if (m_uiLe) + { + const int time = m_uiLe->leLongHHMMSS->getValue(); + return time % 100; + } + if (m_uiTouch) + { + return getItemValue(m_uiTouch->spSeconds); + } + return 0; } bool LtsDateTimeEdit::setYear(int year) { - int finalYear = -1; - if (year >= 0 && year <= 99) - finalYear = year; - else if (year >= 2000 && year <= 2099) - finalYear = year - 2000; + int finalYear = -1; + if (year >= 0 && year <= 99) + finalYear = year; + else if (year >= 2000 && year <= 2099) + finalYear = year - 2000; - if (finalYear >= 0) - { - if (m_uiLe) - m_uiLe->leLongYear->setValue(finalYear); - if (m_uiTouch) - setItemValue(m_uiTouch->spYear, finalYear); - return true; - } + if (finalYear >= 0) + { + if (m_uiLe) + m_uiLe->leLongYear->setValue(finalYear); + if (m_uiTouch) + setItemValue(m_uiTouch->spYear, finalYear); + return true; + } - return false; + return false; } int LtsDateTimeEdit::getYear() const { - if (m_uiLe) - return 2000 + m_uiLe->leLongYear->getValue(); - if (m_uiTouch) - return 2000 + m_uiTouch->spYear->value(); - return 2000; + if (m_uiLe) + return 2000 + m_uiLe->leLongYear->getValue(); + if (m_uiTouch) + return 2000 + m_uiTouch->spYear->value(); + return 2000; } bool LtsDateTimeEdit::isEmpty() const { - return (isEmptyDay() || - isEmptyHHMMSS() || - isEmptyMonth() || - isEmptyTimezone() || - isEmptyYear()); + return (isEmptyDay() || isEmptyHHMMSS() || isEmptyMonth() || isEmptyTimezone() || isEmptyYear()); } bool LtsDateTimeEdit::isValidDate() const { - return m_dateIsAcceptable; + return m_dateIsAcceptable; } - bool LtsDateTimeEdit::isEmptyDay() const { - if (m_uiLe) - return m_uiLe->leLongDay->isEmpty(); - return false; + if (m_uiLe) + return m_uiLe->leLongDay->isEmpty(); + return false; } bool LtsDateTimeEdit::isEmptyHHMMSS() const { - if (m_uiLe) - return m_uiLe->leLongHHMMSS->isEmpty(); - return false; + if (m_uiLe) + return m_uiLe->leLongHHMMSS->isEmpty(); + return false; } bool LtsDateTimeEdit::isEmptyMonth() const { - if (m_uiLe) - return m_uiLe->leLongMonth->text().isEmpty(); - return false; + if (m_uiLe) + return m_uiLe->leLongMonth->text().isEmpty(); + return false; } bool LtsDateTimeEdit::isEmptyTimezone() const { - if (m_uiLe) - return m_uiLe->leLongTZ->text().isEmpty(); - return false; + if (m_uiLe) + return m_uiLe->leLongTZ->text().isEmpty(); + return false; } bool LtsDateTimeEdit::isEmptyYear() const { - if (m_uiLe) - return m_uiLe->leLongYear->isEmpty(); - return false; + if (m_uiLe) + return m_uiLe->leLongYear->isEmpty(); + return false; } bool LtsDateTimeEdit::hasFocus() const { - if (!m_uiLe) - return false; - return (m_uiLe->leLongDay->hasFocus() || - m_uiLe->leLongHHMMSS->hasFocus() || - m_uiLe->leLongMonth->hasFocus() || - m_uiLe->leLongTZ->hasFocus() || - m_uiLe->leLongYear->hasFocus()); + if (!m_uiLe) + return false; + return (m_uiLe->leLongDay->hasFocus() || m_uiLe->leLongHHMMSS->hasFocus() || m_uiLe->leLongMonth->hasFocus() || + m_uiLe->leLongTZ->hasFocus() || m_uiLe->leLongYear->hasFocus()); } bool LtsDateTimeEdit::isDataAcceptable() { - m_dateIsAcceptable = false; + m_dateIsAcceptable = false; - bool state = - isDayAcceptable() && - isHHMMSSAcceptable() && - isMonthAcceptable() && - isYearAcceptable() && - QDate::isValid(getYear(), getMonth(), getDay()) && - QTime::isValid(getHour(), getMinute(), getSecond()); + bool state = isDayAcceptable() && isHHMMSSAcceptable() && isMonthAcceptable() && isYearAcceptable() && + QDate::isValid(getYear(), getMonth(), getDay()) && QTime::isValid(getHour(), getMinute(), getSecond()); - if (m_editTimezone && state) - state = isTzAcceptable(); + if (m_editTimezone && state) + state = isTzAcceptable(); - showInvalidData(false); + showInvalidData(false); - if (!state) - { - disableControls(); - return false; - } + if (!state) + { + disableControls(); + return false; + } - qint64 msec = QDateTime(QDate(getYear(), getMonth(), getDay()), QTime(getHour(), getMinute(), getSecond()), Qt::UTC).toMSecsSinceEpoch(); - msec -= DTG::timezone2Secs(getTimezone()) * 1000LL; - if (m_minTimeMSec > 0 && m_maxTimeMSec > 0 && m_minTimeMSec < m_maxTimeMSec) - { - if (msec < m_minTimeMSec || msec > m_maxTimeMSec) - return false; - } + qint64 msec = QDateTime(QDate(getYear(), getMonth(), getDay()), QTime(getHour(), getMinute(), getSecond()), Qt::UTC) + .toMSecsSinceEpoch(); + msec -= DTG::timezone2Secs(getTimezone()) * 1000LL; + if (m_minTimeMSec > 0 && m_maxTimeMSec > 0 && m_minTimeMSec < m_maxTimeMSec) + { + if (msec < m_minTimeMSec || msec > m_maxTimeMSec) + return false; + } - m_curTimeMSec = msec; - enableControls(); - m_dateIsAcceptable = true; - return true; + m_curTimeMSec = msec; + enableControls(); + m_dateIsAcceptable = true; + return true; } bool LtsDateTimeEdit::isDayAcceptable() const { - int value = getDay(); - int max = 31; - if (isMonthAcceptable()) - { - const int month = getMonth(); - switch (month) + int value = getDay(); + int max = 31; + if (isMonthAcceptable()) { - case 2: - { - max = 28; - if (isYearAcceptable()) - { - if (getYear() % 4 == 0 && (getYear() % 100 != 0 || getYear() % 400 == 0)) - - max = 29; - } - break; + const int month = getMonth(); + switch (month) + { + case 2: { + max = 28; + if (isYearAcceptable()) + { + if (getYear() % 4 == 0 && (getYear() % 100 != 0 || getYear() % 400 == 0)) + + max = 29; + } + break; + } + case 4: + case 6: + case 9: + case 11: + max = 30; + break; + default: + break; + } } - case 4: - case 6: - case 9: - case 11: - max = 30; - break; - default: - break; - } - } - return (value > 0 && value <= max); + return (value > 0 && value <= max); } bool LtsDateTimeEdit::isHHMMSSAcceptable() const { - int hh = getHour(); - if (hh < 0 || hh > 23) - return false; + int hh = getHour(); + if (hh < 0 || hh > 23) + return false; - int mm = getMinute(); - if (mm < 0 || mm > 59) - return false; + int mm = getMinute(); + if (mm < 0 || mm > 59) + return false; - int ss = getSecond(); - if (ss < 0 || ss > 59) - return false; + int ss = getSecond(); + if (ss < 0 || ss > 59) + return false; - return true; + return true; } bool LtsDateTimeEdit::isMonthAcceptable() const { - int value = getMonth(); - return (value > 0 && value <= 12); + int value = getMonth(); + return (value > 0 && value <= 12); } bool LtsDateTimeEdit::isYearAcceptable() const { - if (m_uiLe) - return isLineEditDataAcceptable(m_uiLe->leLongYear); - return true; + if (m_uiLe) + return isLineEditDataAcceptable(m_uiLe->leLongYear); + return true; } bool LtsDateTimeEdit::isTzAcceptable() const { - if (m_uiLe) - return isLineEditDataAcceptable(m_uiLe->leLongTZ); - return true; + if (m_uiLe) + return isLineEditDataAcceptable(m_uiLe->leLongTZ); + return true; } void LtsDateTimeEdit::showInvalidData(bool setFocus) { - if (!m_uiLe) - return; + if (!m_uiLe) + return; - bool focus = setFocus; + bool focus = setFocus; - auto check = [&](QLineEdit * le, bool isValid) - { - if (isValid) - le->setStyleSheet(QString()); - else - { - le->setStyleSheet(QLatin1String("background-color: yellow;")); - if (focus) - { - le->setFocus(); - focus = false; - } - } - }; + auto check = [&](QLineEdit* le, bool isValid) { + if (isValid) + le->setStyleSheet(QString()); + else + { + le->setStyleSheet(QLatin1String("background-color: yellow;")); + if (focus) + { + le->setFocus(); + focus = false; + } + } + }; - check(m_uiLe->leLongDay, isDayAcceptable()); - check(m_uiLe->leLongHHMMSS, isHHMMSSAcceptable()); - if (m_editTimezone) - check(m_uiLe->leLongTZ, isTzAcceptable()); - check(m_uiLe->leLongMonth, isMonthAcceptable()); - check(m_uiLe->leLongYear, isYearAcceptable()); + check(m_uiLe->leLongDay, isDayAcceptable()); + check(m_uiLe->leLongHHMMSS, isHHMMSSAcceptable()); + if (m_editTimezone) + check(m_uiLe->leLongTZ, isTzAcceptable()); + check(m_uiLe->leLongMonth, isMonthAcceptable()); + check(m_uiLe->leLongYear, isYearAcceptable()); } -bool LtsDateTimeEdit::isLineEditDataAcceptable(QLineEdit *le) const +bool LtsDateTimeEdit::isLineEditDataAcceptable(QLineEdit* le) const { - const QValidator *pValidator = le->validator(); + const QValidator* pValidator = le->validator(); - if (!pValidator) - return true; + if (!pValidator) + return true; - QString text = le->text(); + QString text = le->text(); - int pos; - QValidator::State state = pValidator->validate(text, pos); + int pos; + QValidator::State state = pValidator->validate(text, pos); - if (state == QValidator::Acceptable || state == QValidator::Intermediate) - return true; + if (state == QValidator::Acceptable || state == QValidator::Intermediate) + return true; - return false; + return false; } void LtsDateTimeEdit::setFixedDateTime() { - setMsecsSinceEpoch(LtsUtils::OperatorSettings::getInstance()->value(QStringLiteral("TimeSettings"), QStringLiteral("FixedTime"), 0).toLongLong()); + setMsecsSinceEpoch(LtsUtils::OperatorSettings::getInstance() + ->value(QStringLiteral("TimeSettings"), QStringLiteral("FixedTime"), 0) + .toLongLong()); } void LtsDateTimeEdit::setOffsetDateTime() { - if (!m_getCurrentTimeCallback) - return; + if (!m_getCurrentTimeCallback) + return; - qint64 offset = LtsUtils::OperatorSettings::getInstance()->value(QStringLiteral("TimeSettings"), QStringLiteral("Offset"), 0).toLongLong(); - - setMsecsSinceEpoch((m_getCurrentTimeCallback() / 1000) * 1000 + offset); + qint64 offset = LtsUtils::OperatorSettings::getInstance() + ->value(QStringLiteral("TimeSettings"), QStringLiteral("Offset"), 0) + .toLongLong(); + + setMsecsSinceEpoch((m_getCurrentTimeCallback() / 1000) * 1000 + offset); } void LtsDateTimeEdit::setSliderValue(int val) { - setMsecsSinceEpoch(val * 1000LL); + setMsecsSinceEpoch(val * 1000LL); } -void LtsDateTimeEdit::valueDayChanged(const QString &str) +void LtsDateTimeEdit::valueDayChanged(const QString& str) { - if (!m_uiLe) - return; - int curpos = m_uiLe->leLongDay->cursorPosition(); - int cp = curpos; + if (!m_uiLe) + return; + int curpos = m_uiLe->leLongDay->cursorPosition(); + int cp = curpos; - bool changed = false; + bool changed = false; - QString tag(str); + QString tag(str); - if (tag.length() > 2) - { - tag = tag.left(2); - changed = true; - } - - bool ok; - int t = tag.toInt(&ok, 10); - - if (ok) - { - if (t > 31) + if (tag.length() > 2) { - tag.remove(curpos - 1, 1); - if (cp >= curpos) - cp--; - changed = true; + tag = tag.left(2); + changed = true; } - } - if (changed) - { - m_uiLe->leLongDay->setText(tag); - m_uiLe->leLongDay->setCursorPosition(cp); - } + bool ok; + int t = tag.toInt(&ok, 10); - if (tag.length() == 2) - { - showInvalidData(false); + if (ok) + { + if (t > 31) + { + tag.remove(curpos - 1, 1); + if (cp >= curpos) + cp--; + changed = true; + } + } - if (m_autoForward) - focusNextPrevChild(true); - } + if (changed) + { + m_uiLe->leLongDay->setText(tag); + m_uiLe->leLongDay->setCursorPosition(cp); + } + + if (tag.length() == 2) + { + showInvalidData(false); + + if (m_autoForward) + focusNextPrevChild(true); + } } void LtsDateTimeEdit::fixupHHMMSS() { - if (!m_uiLe) - return; + if (!m_uiLe) + return; - int curpos = m_uiLe->leLongHHMMSS->cursorPosition(); - int cp = curpos; + int curpos = m_uiLe->leLongHHMMSS->cursorPosition(); + int cp = curpos; - bool changed = false; + bool changed = false; - QString uhrzeit(m_uiLe->leLongHHMMSS->text()); + QString uhrzeit(m_uiLe->leLongHHMMSS->text()); - - - + QString hh; + QString mm; + QString ss; - - QString hh; - QString mm; - QString ss; - - if (uhrzeit.length() > 1) - hh = uhrzeit.left(2); - else - hh = uhrzeit + QLatin1Char('0'); - - if (uhrzeit.length() > 0) - { - if (uhrzeit.length() == 1) - hh = uhrzeit.mid(0, 1) + QLatin1Char('0'); - else if (uhrzeit.length() >= 2) - { - hh = uhrzeit.mid(0, 2); - if (uhrzeit.length() > 2) - { - if (uhrzeit.length() == 3) - mm = uhrzeit.mid(2, 1) + QLatin1Char('0'); - else if (uhrzeit.length() >= 4) - { - mm = uhrzeit.mid(2, 2); - if (uhrzeit.length() == 5) - ss = uhrzeit.mid(4, 1) + QLatin1Char('0'); - else if (uhrzeit.length() == 6) - ss = uhrzeit.mid(4, 2); - } - } - } - } - - bool ok; - - int h = hh.toInt(&ok, 10); - if (ok) - { - if (h > 23) - { - uhrzeit.remove(curpos - 1, 1); - if (cp >= curpos) - cp--; - changed = true; - } - } - - int m = mm.toInt(&ok, 10); - - if (ok) - { - if ((hh.length() == 2) && (m > 59)) - { - uhrzeit.remove(curpos - 1, 1); - if (cp >= curpos) - cp--; - changed = true; - } - } - - int s = ss.toInt(&ok, 10); - - if (ok) - { - if ((hh.length() == 2 && mm.length() == 2) && (s > 59)) - { - uhrzeit.remove(curpos - 1, 1); - if (cp >= curpos) - cp--; - changed = true; - } - } - - if (changed) - { - m_uiLe->leLongHHMMSS->setText(uhrzeit); - m_uiLe->leLongHHMMSS->setCursorPosition(cp); - } - - isDataAcceptable(); - emit dateTimeChanged(); -} - -void LtsDateTimeEdit::valueMonthChanged2(const QString &str) -{ - if (!m_uiLe) - return; - if (str.length() == 3 && m_uiLe->leLongMonth->selectedText().isEmpty()) - focusNextPrevChild(true); -} - -void LtsDateTimeEdit::valueMonthChanged(const QString &str) -{ - if (!m_uiLe) - return; - int curpos = m_uiLe->leLongMonth->cursorPosition(); - int cp = curpos; - - bool changed = false; - - QString monStr = str; - - const auto months = DTG::months(); - for (int i = 0; i < months.size(); ++i) - { - const QString &mon = months.at(i); - if (mon.startsWith(monStr, Qt::CaseInsensitive)) - { - monStr = mon; - changed = true; - break; - } - } - - if (!changed) - { - monStr.remove(curpos - 1, 1); - if (cp >= curpos) - cp--; - changed = true; - } - - if (changed) - { - m_uiLe->leLongMonth->setText(monStr); - - - if (cp > 0) - m_uiLe->leLongMonth->setCursorPosition(cp); + if (uhrzeit.length() > 1) + hh = uhrzeit.left(2); else - m_uiLe->leLongMonth->setCursorPosition(1); - } + hh = uhrzeit + QLatin1Char('0'); + + if (uhrzeit.length() > 0) + { + if (uhrzeit.length() == 1) + hh = uhrzeit.mid(0, 1) + QLatin1Char('0'); + else if (uhrzeit.length() >= 2) + { + hh = uhrzeit.mid(0, 2); + if (uhrzeit.length() > 2) + { + if (uhrzeit.length() == 3) + mm = uhrzeit.mid(2, 1) + QLatin1Char('0'); + else if (uhrzeit.length() >= 4) + { + mm = uhrzeit.mid(2, 2); + if (uhrzeit.length() == 5) + ss = uhrzeit.mid(4, 1) + QLatin1Char('0'); + else if (uhrzeit.length() == 6) + ss = uhrzeit.mid(4, 2); + } + } + } + } + + bool ok; + + int h = hh.toInt(&ok, 10); + if (ok) + { + if (h > 23) + { + uhrzeit.remove(curpos - 1, 1); + if (cp >= curpos) + cp--; + changed = true; + } + } + + int m = mm.toInt(&ok, 10); + + if (ok) + { + if ((hh.length() == 2) && (m > 59)) + { + uhrzeit.remove(curpos - 1, 1); + if (cp >= curpos) + cp--; + changed = true; + } + } + + int s = ss.toInt(&ok, 10); + + if (ok) + { + if ((hh.length() == 2 && mm.length() == 2) && (s > 59)) + { + uhrzeit.remove(curpos - 1, 1); + if (cp >= curpos) + cp--; + changed = true; + } + } + + if (changed) + { + m_uiLe->leLongHHMMSS->setText(uhrzeit); + m_uiLe->leLongHHMMSS->setCursorPosition(cp); + } + + isDataAcceptable(); + emit dateTimeChanged(); +} + +void LtsDateTimeEdit::valueMonthChanged2(const QString& str) +{ + if (!m_uiLe) + return; + if (str.length() == 3 && m_uiLe->leLongMonth->selectedText().isEmpty()) + focusNextPrevChild(true); +} + +void LtsDateTimeEdit::valueMonthChanged(const QString& str) +{ + if (!m_uiLe) + return; + int curpos = m_uiLe->leLongMonth->cursorPosition(); + int cp = curpos; + + bool changed = false; + + QString monStr = str; + + const auto months = DTG::months(); + for (int i = 0; i < months.size(); ++i) + { + const QString& mon = months.at(i); + if (mon.startsWith(monStr, Qt::CaseInsensitive)) + { + monStr = mon; + changed = true; + break; + } + } + + if (!changed) + { + monStr.remove(curpos - 1, 1); + if (cp >= curpos) + cp--; + changed = true; + } + + if (changed) + { + m_uiLe->leLongMonth->setText(monStr); + + if (cp > 0) + m_uiLe->leLongMonth->setCursorPosition(cp); + else + m_uiLe->leLongMonth->setCursorPosition(1); + } + + if (monStr.size() == 3) + { + showInvalidData(false); + if (m_autoForward) + focusNextPrevChild(true); + } +} + +void LtsDateTimeEdit::valueTimezoneChangedStr(const QString& str) +{ + if (str.length() > 1) + { + clearTimezone(); + return; + } + if (str.length() == 0) + return; + QChar c = str.at(0); + if (!c.isLetter() || c.toUpper() == QLatin1Char('J')) + { + clearTimezone(); + return; + } + if (c.isLower()) + setTimezone(c.toUpper().toLatin1()); - if (monStr.size() == 3) - { showInvalidData(false); if (m_autoForward) - focusNextPrevChild(true); - } -} - -void LtsDateTimeEdit::valueTimezoneChangedStr(const QString &str) -{ - if (str.length() > 1) - { - clearTimezone(); - return; - } - if (str.length() == 0) - return; - QChar c = str.at(0); - if (!c.isLetter() || c.toUpper() == QLatin1Char('J')) - { - clearTimezone(); - return; - } - if (c.isLower()) - setTimezone(c.toUpper().toLatin1()); - - showInvalidData(false); - if (m_autoForward) - focusNextPrevChild(true); + focusNextPrevChild(true); } void LtsDateTimeEdit::valueTimezoneChangedInt(int newTimezone) { - Q_UNUSED(newTimezone); - if (!m_uiTouch) - return; - const QString &curText = m_uiTouch->cbxTimeZone->currentText(); - if (curText.isEmpty()) - return; + Q_UNUSED(newTimezone); + if (!m_uiTouch) + return; + const QString& curText = m_uiTouch->cbxTimeZone->currentText(); + if (curText.isEmpty()) + return; - const QChar tz = curText.at(0); - setTimezone(tz.toUpper().toLatin1()); + const QChar tz = curText.at(0); + setTimezone(tz.toUpper().toLatin1()); } -void LtsDateTimeEdit::valueYearChanged(const QString &str) +void LtsDateTimeEdit::valueYearChanged(const QString& str) { - if (!m_uiLe) - return; - int curpos = m_uiLe->leLongYear->cursorPosition(); - int cp = curpos; + if (!m_uiLe) + return; + int curpos = m_uiLe->leLongYear->cursorPosition(); + int cp = curpos; - bool changed = false; + bool changed = false; - const QString &year = str; + const QString& year = str; - QString yy; - if (year.length() > 2) - { - yy = year.left(2); - changed = true; - } + QString yy; + if (year.length() > 2) + { + yy = year.left(2); + changed = true; + } - if (changed) - { - m_uiLe->leLongYear->setText(yy); - m_uiLe->leLongYear->setCursorPosition(cp); - } + if (changed) + { + m_uiLe->leLongYear->setText(yy); + m_uiLe->leLongYear->setCursorPosition(cp); + } - if (year.length() == 2) - { - showInvalidData(false); - if (m_autoForward) - focusNextPrevChild(true); - } + if (year.length() == 2) + { + showInvalidData(false); + if (m_autoForward) + focusNextPrevChild(true); + } } void LtsDateTimeEdit::onBackHourClicked() { - if (!setMsecsSinceEpoch(m_curTimeMSec - s_oneHourMSec)) - setMsecsSinceEpoch(m_minTimeMSec); + if (!setMsecsSinceEpoch(m_curTimeMSec - s_oneHourMSec)) + setMsecsSinceEpoch(m_minTimeMSec); } void LtsDateTimeEdit::onBackMinuteClicked() { - const int ofs = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? 5 : 1; - if (!setMsecsSinceEpoch(m_curTimeMSec - ofs * s_oneMinuteMSec)) - setMsecsSinceEpoch(m_minTimeMSec); + const int ofs = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? 5 : 1; + if (!setMsecsSinceEpoch(m_curTimeMSec - ofs * s_oneMinuteMSec)) + setMsecsSinceEpoch(m_minTimeMSec); } void LtsDateTimeEdit::onBackSecondClicked() { - const int ofs = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? 5 : 1; - if (!setMsecsSinceEpoch(m_curTimeMSec - ofs * s_oneSecondMSec)) - setMsecsSinceEpoch(m_minTimeMSec); + const int ofs = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? 5 : 1; + if (!setMsecsSinceEpoch(m_curTimeMSec - ofs * s_oneSecondMSec)) + setMsecsSinceEpoch(m_minTimeMSec); } void LtsDateTimeEdit::onForwardSecondClicked() { - const int ofs = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? 5 : 1; - if (!setMsecsSinceEpoch(m_curTimeMSec + ofs * s_oneSecondMSec)) - setMsecsSinceEpoch(m_maxTimeMSec); + const int ofs = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? 5 : 1; + if (!setMsecsSinceEpoch(m_curTimeMSec + ofs * s_oneSecondMSec)) + setMsecsSinceEpoch(m_maxTimeMSec); } void LtsDateTimeEdit::onForwardMinuteClicked() { - const int ofs = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? 5 : 1; - if (!setMsecsSinceEpoch(m_curTimeMSec + ofs * s_oneMinuteMSec)) - setMsecsSinceEpoch(m_maxTimeMSec); + const int ofs = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? 5 : 1; + if (!setMsecsSinceEpoch(m_curTimeMSec + ofs * s_oneMinuteMSec)) + setMsecsSinceEpoch(m_maxTimeMSec); } void LtsDateTimeEdit::onForwardHourClicked() { - if (!setMsecsSinceEpoch(m_curTimeMSec + s_oneHourMSec)) - setMsecsSinceEpoch(m_maxTimeMSec); + if (!setMsecsSinceEpoch(m_curTimeMSec + s_oneHourMSec)) + setMsecsSinceEpoch(m_maxTimeMSec); } void LtsDateTimeEdit::onCheckBoxChanged() { - QVector widgets; - bool bEnable = false; + QVector widgets; + bool bEnable = false; - if (m_uiLe) - { - widgets = {m_uiLe->leLongDay, m_uiLe->leLongHHMMSS, m_uiLe->leLongTZ, - m_uiLe->leLongMonth, m_uiLe->leLongYear}; - bEnable = m_uiLe->checkBox->isChecked(); - } + if (m_uiLe) + { + widgets = {m_uiLe->leLongDay, m_uiLe->leLongHHMMSS, m_uiLe->leLongTZ, m_uiLe->leLongMonth, m_uiLe->leLongYear}; + bEnable = m_uiLe->checkBox->isChecked(); + } - if (m_uiTouch) - { - widgets = {m_uiTouch->spDay, m_uiTouch->spHour, m_uiTouch->spMinutes, m_uiTouch->spSeconds, m_uiTouch->spYear, m_uiTouch->cbxMonth, m_uiTouch->cbxTimeZone, m_uiTouch->pbNow}; - bEnable = m_uiTouch->checkBox->isChecked(); - } + if (m_uiTouch) + { + widgets = {m_uiTouch->spDay, m_uiTouch->spHour, m_uiTouch->spMinutes, m_uiTouch->spSeconds, + m_uiTouch->spYear, m_uiTouch->cbxMonth, m_uiTouch->cbxTimeZone, m_uiTouch->pbNow}; + bEnable = m_uiTouch->checkBox->isChecked(); + } - for (auto w : widgets) - { - if (w) - w->setEnabled(bEnable); - } - enaDisaControls(bEnable); + for (auto w : widgets) + { + if (w) + w->setEnabled(bEnable); + } + enaDisaControls(bEnable); } void LtsDateTimeEdit::disableControls() { - enaDisaControls(false); + enaDisaControls(false); } void LtsDateTimeEdit::enableControls() { - if (!m_uiLe) - return; + if (!m_uiLe) + return; - enaDisaControls(true); - if (m_withSlider && - m_minTimeMSec != 0 && - m_maxTimeMSec > 0 && - m_maxTimeMSec > m_minTimeMSec) - { - m_uiLe->slTime->setEnabled(true); - m_uiLe->slTime->setValue(m_curTimeMSec / 1000LL); - } + enaDisaControls(true); + if (m_withSlider && m_minTimeMSec != 0 && m_maxTimeMSec > 0 && m_maxTimeMSec > m_minTimeMSec) + { + m_uiLe->slTime->setEnabled(true); + m_uiLe->slTime->setValue(m_curTimeMSec / 1000LL); + } } void LtsDateTimeEdit::enaDisaControls(bool bEnable) { - if (!m_uiLe) - return; - const QVector widgets({m_uiLe->pbBBB, m_uiLe->pbBB, m_uiLe->pbB, - m_uiLe->pbF, m_uiLe->pbFF, m_uiLe->pbFFF, - m_uiLe->slTime}); - for (auto w : widgets) - { - if (w) - w->setEnabled(bEnable); - } + if (!m_uiLe) + return; + const QVector widgets( + {m_uiLe->pbBBB, m_uiLe->pbBB, m_uiLe->pbB, m_uiLe->pbF, m_uiLe->pbFF, m_uiLe->pbFFF, m_uiLe->slTime}); + for (auto w : widgets) + { + if (w) + w->setEnabled(bEnable); + } } void LtsDateTimeEdit::setMinimumTimeMSec(qint64 msec) { - if (m_minTimeMSec == msec) - return; - m_minTimeMSec = msec; - if (m_minTimeMSec > 0 && m_uiLe && m_uiLe->slTime) - { - m_uiLe->slTime->setMinimum(m_minTimeMSec / 1000LL); - if (m_maxTimeMSec > m_minTimeMSec) - m_uiLe->slTime->setEnabled(true); - } - if (m_curTimeMSec < m_minTimeMSec) - setMsecsSinceEpoch(m_minTimeMSec); + if (m_minTimeMSec == msec) + return; + m_minTimeMSec = msec; + if (m_minTimeMSec > 0 && m_uiLe && m_uiLe->slTime) + { + m_uiLe->slTime->setMinimum(m_minTimeMSec / 1000LL); + if (m_maxTimeMSec > m_minTimeMSec) + m_uiLe->slTime->setEnabled(true); + } + if (m_curTimeMSec < m_minTimeMSec) + setMsecsSinceEpoch(m_minTimeMSec); } void LtsDateTimeEdit::setMaximumTimeMSec(qint64 msec) { - if (m_maxTimeMSec == msec) - return; - m_maxTimeMSec = msec; - if (!m_uiLe || !m_uiLe->slTime) - return; + if (m_maxTimeMSec == msec) + return; + m_maxTimeMSec = msec; + if (!m_uiLe || !m_uiLe->slTime) + return; - m_uiLe->slTime->setMaximum(m_maxTimeMSec / 1000LL); - if (m_minTimeMSec > 0 && m_maxTimeMSec > m_minTimeMSec) - m_uiLe->slTime->setEnabled(true); - if (m_maxTimeMSec > 0 && m_curTimeMSec > m_maxTimeMSec) - setMsecsSinceEpoch(m_maxTimeMSec); + m_uiLe->slTime->setMaximum(m_maxTimeMSec / 1000LL); + if (m_minTimeMSec > 0 && m_maxTimeMSec > m_minTimeMSec) + m_uiLe->slTime->setEnabled(true); + if (m_maxTimeMSec > 0 && m_curTimeMSec > m_maxTimeMSec) + setMsecsSinceEpoch(m_maxTimeMSec); } void LtsDateTimeEdit::clear() { - if (m_uiLe) - { - m_uiLe->leLongDay->clear(); - m_uiLe->leLongHHMMSS->clear(); - m_uiLe->leLongMonth->clear(); - m_uiLe->leLongYear->clear(); - m_uiLe->leLongTZ->clear(); - m_curTimeMSec = 0; - } - if (m_uiTouch) - { - m_uiTouch->spDay->clear(); - m_uiTouch->spHour->clear(); - m_uiTouch->spMinutes->clear(); - m_uiTouch->spSeconds->clear(); - m_uiTouch->spYear->clear(); - } - emit dateTimeChanged(); - + if (m_uiLe) + { + m_uiLe->leLongDay->clear(); + m_uiLe->leLongHHMMSS->clear(); + m_uiLe->leLongMonth->clear(); + m_uiLe->leLongYear->clear(); + m_uiLe->leLongTZ->clear(); + m_curTimeMSec = 0; + } + if (m_uiTouch) + { + m_uiTouch->spDay->clear(); + m_uiTouch->spHour->clear(); + m_uiTouch->spMinutes->clear(); + m_uiTouch->spSeconds->clear(); + m_uiTouch->spYear->clear(); + } + emit dateTimeChanged(); } void LtsDateTimeEdit::onFocusOutDay() { - if (!m_uiLe) - return; - if (m_backspacePressed) - { - m_backspacePressed = false; - return; - } - if (!m_recursionAvoid && !hasFocus()) - onFocusOut(); - - QString value = m_uiLe->leLongDay->text(); - - if (value.length() == 0 && !m_backspacePressed) - { - if (!isEmptyHHMMSS() || - !isEmptyMonth() || - (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) || - !isEmptyYear()) + if (!m_uiLe) + return; + if (m_backspacePressed) { - if (m_getCurrentTimeCallback) - { - const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_getCurrentTimeCallback(), Qt::UTC)); - setDay(dt.date().day()); - } + m_backspacePressed = false; + return; } - } - isDataAcceptable(); - emit dateTimeChanged(); + if (!m_recursionAvoid && !hasFocus()) + onFocusOut(); + + QString value = m_uiLe->leLongDay->text(); + + if (value.length() == 0 && !m_backspacePressed) + { + if (!isEmptyHHMMSS() || !isEmptyMonth() || (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) || + !isEmptyYear()) + { + if (m_getCurrentTimeCallback) + { + const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_getCurrentTimeCallback(), Qt::UTC)); + setDay(dt.date().day()); + } + } + } + isDataAcceptable(); + emit dateTimeChanged(); } void LtsDateTimeEdit::onFocusOutHHMMSS() { - if (!m_uiLe) - return; - if (m_backspacePressed) - { - m_backspacePressed = false; - return; - } - if (!m_recursionAvoid && !hasFocus()) - onFocusOut(); - - QString value = m_uiLe->leLongHHMMSS->text(); - - if (value.length() == 0 && !m_backspacePressed) - { - if (!isEmptyDay() || - !isEmptyMonth() || - !(isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) || - !isEmptyYear()) + if (!m_uiLe) + return; + if (m_backspacePressed) { - if (m_getCurrentTimeCallback) - { - const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_getCurrentTimeCallback(), Qt::UTC)); - setHHMMSS(dt.time().hour(), dt.time().minute(), dt.time().second()); - } + m_backspacePressed = false; + return; } - } - value += QString(6 - value.length(), QLatin1Char('0')); - m_uiLe->leLongHHMMSS->setText(value); - isDataAcceptable(); - emit dateTimeChanged(); + if (!m_recursionAvoid && !hasFocus()) + onFocusOut(); + + QString value = m_uiLe->leLongHHMMSS->text(); + + if (value.length() == 0 && !m_backspacePressed) + { + if (!isEmptyDay() || !isEmptyMonth() || !(isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) || !isEmptyYear()) + { + if (m_getCurrentTimeCallback) + { + const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_getCurrentTimeCallback(), Qt::UTC)); + setHHMMSS(dt.time().hour(), dt.time().minute(), dt.time().second()); + } + } + } + value += QString(6 - value.length(), QLatin1Char('0')); + m_uiLe->leLongHHMMSS->setText(value); + isDataAcceptable(); + emit dateTimeChanged(); } void LtsDateTimeEdit::onFocusOutTZ() { - if (!m_uiLe) - return; - if (m_backspacePressed) - { - m_backspacePressed = false; - return; - } - if (!m_recursionAvoid && !hasFocus()) - onFocusOut(); + if (!m_uiLe) + return; + if (m_backspacePressed) + { + m_backspacePressed = false; + return; + } + if (!m_recursionAvoid && !hasFocus()) + onFocusOut(); - QString value = m_uiLe->leLongTZ->text(); - - if (value.length() == 0 && !m_backspacePressed) - { - if (!isEmptyHHMMSS() || - !isEmptyMonth() || - !isEmptyDay() || - !isEmptyYear()) - setTimezone(DTG::timezone()); - } - isDataAcceptable(); - emit dateTimeChanged(); + QString value = m_uiLe->leLongTZ->text(); + + if (value.length() == 0 && !m_backspacePressed) + { + if (!isEmptyHHMMSS() || !isEmptyMonth() || !isEmptyDay() || !isEmptyYear()) + setTimezone(DTG::timezone()); + } + isDataAcceptable(); + emit dateTimeChanged(); } void LtsDateTimeEdit::onFocusOutMonth() { - if (!m_uiLe) - return; - if (m_backspacePressed) - { - m_backspacePressed = false; - return; - } - - if (!m_recursionAvoid && !hasFocus()) - onFocusOut(); - - QString value = m_uiLe->leLongMonth->text(); - - if (value.length() == 0 && !m_backspacePressed) - { - if (!isEmptyHHMMSS() || - !isEmptyDay() || - (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) || - !isEmptyYear()) + if (!m_uiLe) + return; + if (m_backspacePressed) { - if (m_getCurrentTimeCallback) - { - const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_getCurrentTimeCallback(), Qt::UTC)); - setMonth(dt.date().month()); - } + m_backspacePressed = false; + return; } - } - isDataAcceptable(); - emit dateTimeChanged(); + + if (!m_recursionAvoid && !hasFocus()) + onFocusOut(); + + QString value = m_uiLe->leLongMonth->text(); + + if (value.length() == 0 && !m_backspacePressed) + { + if (!isEmptyHHMMSS() || !isEmptyDay() || (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) || + !isEmptyYear()) + { + if (m_getCurrentTimeCallback) + { + const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_getCurrentTimeCallback(), Qt::UTC)); + setMonth(dt.date().month()); + } + } + } + isDataAcceptable(); + emit dateTimeChanged(); } void LtsDateTimeEdit::onFocusOutYear() { - if (!m_uiLe) - return; - if (m_backspacePressed) - { - m_backspacePressed = false; - return; - } - - if (!m_recursionAvoid && !hasFocus()) - onFocusOut(); - - QString value = m_uiLe->leLongYear->text(); - - if (value.length() == 1) - { - value = QLatin1Char('0') + value; - m_uiLe->leLongYear->setText(value); - } - - if (value.length() == 0 && !m_backspacePressed) - { - if (!isEmptyHHMMSS() || - !isEmptyMonth() || - (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) || - !isEmptyDay()) + if (!m_uiLe) + return; + if (m_backspacePressed) { - if (m_getCurrentTimeCallback) - { - const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_getCurrentTimeCallback(), Qt::UTC)); - setYear(dt.date().year()); - } + m_backspacePressed = false; + return; } - } - isDataAcceptable(); - emit dateTimeChanged(); + + if (!m_recursionAvoid && !hasFocus()) + onFocusOut(); + + QString value = m_uiLe->leLongYear->text(); + + if (value.length() == 1) + { + value = QLatin1Char('0') + value; + m_uiLe->leLongYear->setText(value); + } + + if (value.length() == 0 && !m_backspacePressed) + { + if (!isEmptyHHMMSS() || !isEmptyMonth() || (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) || + !isEmptyDay()) + { + if (m_getCurrentTimeCallback) + { + const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_getCurrentTimeCallback(), Qt::UTC)); + setYear(dt.date().year()); + } + } + } + isDataAcceptable(); + emit dateTimeChanged(); } void LtsDateTimeEdit::onFocusOutBackspace() { - m_backspacePressed = true; + m_backspacePressed = true; } void LtsDateTimeEdit::onFocusOut() { - if (!m_uiLe) - return; - if (m_backspacePressed) - { - m_backspacePressed = false; - return; - } - m_recursionAvoid = true; - onFocusOutDay(); - onFocusOutHHMMSS(); - onFocusOutMonth(); - onFocusOutTZ(); - onFocusOutYear(); - m_recursionAvoid = false; + if (!m_uiLe) + return; + if (m_backspacePressed) + { + m_backspacePressed = false; + return; + } + m_recursionAvoid = true; + onFocusOutDay(); + onFocusOutHHMMSS(); + onFocusOutMonth(); + onFocusOutTZ(); + onFocusOutYear(); + m_recursionAvoid = false; } void LtsDateTimeEdit::onHmsWheelEvent(bool bForward, int cursorPos) { - if (!m_uiLe) - return; - if (m_uiLe->leLongHHMMSS->text().size() != 6) - return; + if (!m_uiLe) + return; + if (m_uiLe->leLongHHMMSS->text().size() != 6) + return; - fixupHHMMSS(); + fixupHHMMSS(); - int selStart = 0; - switch (cursorPos) - { - case 0: - case 1: - case 2: - if (bForward) - onForwardHourClicked(); - else - onBackHourClicked(); - selStart = 0; - break; - case 3: - case 4: - if (bForward) - onForwardMinuteClicked(); - else - onBackMinuteClicked(); - selStart = 2; - break; - case 5: - case 6: - if (bForward) - onForwardSecondClicked(); - else - onBackSecondClicked(); - selStart = 4; - break; - default: - return; - } - m_uiLe->leLongHHMMSS->setCursorPosition(cursorPos); - m_uiLe->leLongHHMMSS->setSelection(selStart, 2); - emit dateTimeChanged(); + int selStart = 0; + switch (cursorPos) + { + case 0: + case 1: + case 2: + if (bForward) + onForwardHourClicked(); + else + onBackHourClicked(); + selStart = 0; + break; + case 3: + case 4: + if (bForward) + onForwardMinuteClicked(); + else + onBackMinuteClicked(); + selStart = 2; + break; + case 5: + case 6: + if (bForward) + onForwardSecondClicked(); + else + onBackSecondClicked(); + selStart = 4; + break; + default: + return; + } + m_uiLe->leLongHHMMSS->setCursorPosition(cursorPos); + m_uiLe->leLongHHMMSS->setSelection(selStart, 2); + emit dateTimeChanged(); } void LtsDateTimeEdit::onDayWheelEvent(bool bForward, int cursorPos) { - if (!m_uiLe) - return; - if (!isDayAcceptable()) - return; - const int ofs = bForward ? 1 : -1; - setMsecsSinceEpoch(m_curTimeMSec + ofs * s_oneDayMSec, true); - m_uiLe->leLongDay->setCursorPosition(cursorPos); - m_uiLe->leLongDay->setSelection(0, 2); - emit dateTimeChanged(); + if (!m_uiLe) + return; + if (!isDayAcceptable()) + return; + const int ofs = bForward ? 1 : -1; + setMsecsSinceEpoch(m_curTimeMSec + ofs * s_oneDayMSec, true); + m_uiLe->leLongDay->setCursorPosition(cursorPos); + m_uiLe->leLongDay->setSelection(0, 2); + emit dateTimeChanged(); } void LtsDateTimeEdit::onMonthWheelEvent(bool bForward, int cursorPos) { - if (!m_uiLe) - return; - if (!isMonthAcceptable()) - return; - const int ofs = bForward ? 1 : -1; - const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_curTimeMSec, Qt::UTC).addMonths(ofs)); - setMsecsSinceEpoch(dt.toMSecsSinceEpoch(), true); - m_uiLe->leLongMonth->setCursorPosition(cursorPos); - m_uiLe->leLongMonth->setSelection(0, 3); - emit dateTimeChanged(); + if (!m_uiLe) + return; + if (!isMonthAcceptable()) + return; + const int ofs = bForward ? 1 : -1; + const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_curTimeMSec, Qt::UTC).addMonths(ofs)); + setMsecsSinceEpoch(dt.toMSecsSinceEpoch(), true); + m_uiLe->leLongMonth->setCursorPosition(cursorPos); + m_uiLe->leLongMonth->setSelection(0, 3); + emit dateTimeChanged(); } void LtsDateTimeEdit::onYearWheelEvent(bool bForward, int cursorPos) { - if (!m_uiLe) - return; - if (!isYearAcceptable()) - return; - const int ofs = bForward ? 1 : -1; - const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_curTimeMSec, Qt::UTC).addYears(ofs)); - setMsecsSinceEpoch(dt.toMSecsSinceEpoch(), true); - m_uiLe->leLongYear->setCursorPosition(cursorPos); - m_uiLe->leLongYear->setSelection(0, 2); - emit dateTimeChanged(); + if (!m_uiLe) + return; + if (!isYearAcceptable()) + return; + const int ofs = bForward ? 1 : -1; + const QDateTime dt(QDateTime::fromMSecsSinceEpoch(m_curTimeMSec, Qt::UTC).addYears(ofs)); + setMsecsSinceEpoch(dt.toMSecsSinceEpoch(), true); + m_uiLe->leLongYear->setCursorPosition(cursorPos); + m_uiLe->leLongYear->setSelection(0, 2); + emit dateTimeChanged(); } -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog.cpp old mode 100755 new mode 100644 index dea43d262..9d1125a38 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog.cpp @@ -1,810 +1,699 @@ - #include "lts_dialog.h" -#include "lts_progress_dialog_helper.h" -#include "lts_message_dialog.h" -#include "lts_dialog_helper.h" -#include "lts_dialog_button_box.h" + #include "lts_base_layout_widget.h" #include "lts_date_time_edit.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include +#include "lts_dialog_button_box.h" +#include "lts_dialog_helper.h" +#include "lts_message_dialog.h" +#include "lts_progress_dialog_helper.h" #include - +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include namespace LtsWidgets { int LtsDialog::s_object_count = 0; - class OverlayContainer : public QWidget { - Q_OBJECT -public: - OverlayContainer(QWidget *parent); + Q_OBJECT + public: + OverlayContainer(QWidget* parent); -protected: - void paintEvent(QPaintEvent *e) override; + protected: + void paintEvent(QPaintEvent* e) override; }; - -OverlayContainer::OverlayContainer(QWidget *parent) - : QWidget(parent) +OverlayContainer::OverlayContainer(QWidget* parent) : QWidget(parent) { - setAttribute(Qt::WA_TranslucentBackground); + setAttribute(Qt::WA_TranslucentBackground); } - -void OverlayContainer::paintEvent(QPaintEvent *e) +void OverlayContainer::paintEvent(QPaintEvent* e) { - QPainter p(this); - p.fillRect(rect(), { 80, 80, 80, 200 }); - QWidget::paintEvent(e); + QPainter p(this); + p.fillRect(rect(), {80, 80, 80, 200}); + QWidget::paintEvent(e); } - - - -LtsDialog::LtsDialog(QWidget *parent, ButtonCombination buttonCombination, bool closeable) - : QWidget() - , m_changesMade(false) - , m_firstShow(true) - , m_baseLayoutWidget(nullptr) - , m_isClosable(closeable) - , m_noLockTopic(false) - , m_unchangeableDialog(false) - , m_dialogHelper(new LtsDialogHelper(nullptr)) - - - - , m_buttonBox(nullptr) - , m_uiRequirements(new UiRequirementList()) - .getNGLLogger("LtsWidget.LtsDialog")) +LtsDialog::LtsDialog(QWidget* parent, ButtonCombination buttonCombination, bool closeable) + : QWidget(), m_changesMade(false), m_firstShow(true), m_baseLayoutWidget(nullptr), m_isClosable(closeable), + m_noLockTopic(false), m_unchangeableDialog(false), m_dialogHelper(new LtsDialogHelper(nullptr)), m_topicInfo(), + m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("LtsWidget.LtsDialog")), m_buttonBox(nullptr), + m_uiRequirements(new UiRequirementList()) { - Q_UNUSED(parent); + Q_UNUSED(parent); - s_object_count++; + s_object_count++; - m_dialogHelper->setDialog(this); - m_buttonBox = m_dialogHelper->getButtonBox(); + m_dialogHelper->setDialog(this); + m_buttonBox = m_dialogHelper->getButtonBox(); + addDebugMenuButton(); + connect(m_buttonBox->getButton(DialogButton::Close), &QPushButton::clicked, this, &LtsDialog::slotClose); - - - - - - - - - - - - - addDebugMenuButton(); - - - - - - connect(m_buttonBox->getButton(DialogButton::Close), &QPushButton::clicked, this, &LtsDialog::slotClose); - - switch(buttonCombination) - { - case ButtonCombination::OkCancel: + switch (buttonCombination) { - m_buttonBox->getButton(DialogButton::Close)->setText(tr("Cancel")); - connect(m_buttonBox->getButton(DialogButton::Ok), &QPushButton::clicked, this, &LtsDialog::slotOkay); - break; + case ButtonCombination::OkCancel: { + m_buttonBox->getButton(DialogButton::Close)->setText(tr("Cancel")); + connect(m_buttonBox->getButton(DialogButton::Ok), &QPushButton::clicked, this, &LtsDialog::slotOkay); + break; + } + + case ButtonCombination::OkApplyCancel: { + m_buttonBox->getButton(DialogButton::Close)->setText(tr("Cancel")); + connect(m_buttonBox->getButton(DialogButton::Ok), &QPushButton::clicked, this, &LtsDialog::slotOkay); + connect(m_buttonBox->getButton(DialogButton::Apply), &QPushButton::clicked, this, &LtsDialog::slotApply); + m_buttonBox->getButton(DialogButton::Apply)->setVisible(true); + break; + } + + case ButtonCombination::CloseOnly: { + m_buttonBox->getButton(DialogButton::Ok)->setVisible(false); + setUnchangeable(); + break; + } + + default: + case ButtonCombination::SeamlessDialog: { + m_buttonBox->setVisible(false); + setContentsMargins(0, 0, 0, 0); + m_dialogHelper->setContentsMargins(0, 0, 0, 0); + + QLayout* l = m_dialogHelper->layout(); + + if (l) + { + l->setContentsMargins(0, 0, 0, 0); + } + else + { + qWarning() << "LtsDialog::c_tor: Dialog Helper has no layout to set margins"; + } + + break; + } } - case ButtonCombination::OkApplyCancel: + if (!closeable) { - m_buttonBox->getButton(DialogButton::Close)->setText(tr("Cancel")); - connect(m_buttonBox->getButton(DialogButton::Ok), &QPushButton::clicked, this, &LtsDialog::slotOkay); - connect(m_buttonBox->getButton(DialogButton::Apply), &QPushButton::clicked, this, &LtsDialog::slotApply); - m_buttonBox->getButton(DialogButton::Apply)->setVisible(true); - break; + m_buttonBox->getButton(LtsWidgets::DialogButton::Ok)->setVisible(false); + m_buttonBox->getButton(LtsWidgets::DialogButton::Close)->setVisible(false); } - - case ButtonCombination::CloseOnly: - { - m_buttonBox->getButton(DialogButton::Ok)->setVisible(false); - setUnchangeable(); - break; - } - - default: - case ButtonCombination::SeamlessDialog: - { - m_buttonBox->setVisible(false); - setContentsMargins(0,0,0,0); - m_dialogHelper->setContentsMargins(0,0,0,0); - - QLayout *l = m_dialogHelper->layout(); - - if (l) - { - l->setContentsMargins(0,0,0,0); - l->setMargin(0); - } - else - { - qWarning() << "LtsDialog::c_tor: Dialog Helper has no layout to set margins"; - } - - break; - } - } - - if (!closeable) - { - m_buttonBox->getButton(LtsWidgets::DialogButton::Ok)->setVisible(false); - m_buttonBox->getButton(LtsWidgets::DialogButton::Close)->setVisible(false); - } } - LtsDialog::~LtsDialog() { - delete m_uiRequirements; + delete m_uiRequirements; - if (m_overlayWidget) - m_overlayWidget->setParent(nullptr); + if (m_overlayWidget) + m_overlayWidget->setParent(nullptr); - - - - s_object_count--; + s_object_count--; } - -void LtsDialog::setOverlay(QWidget *widget) +void LtsDialog::setOverlay(QWidget* widget) { - if (m_overlayContainer) - { - if (m_overlayWidget) + if (m_overlayContainer) { - m_overlayWidget->hide(); - m_overlayWidget->setParent(nullptr); - m_overlayWidget->hide(); - m_overlayWidget = nullptr; - + if (m_overlayWidget) + { + m_overlayWidget->hide(); + m_overlayWidget->setParent(nullptr); + m_overlayWidget->hide(); + m_overlayWidget = nullptr; + } + + m_overlayContainer->hide(); + m_overlayContainer->setParent(nullptr); + m_overlayContainer->hide(); + m_overlayContainer->deleteLater(); + m_overlayContainer = nullptr; } - m_overlayContainer->hide(); - m_overlayContainer->setParent(nullptr); - m_overlayContainer->hide(); - m_overlayContainer->deleteLater(); - m_overlayContainer = nullptr; - } + OverlayContainer* overlayContainer = new OverlayContainer(m_dialogHelper); - - OverlayContainer *overlayContainer = new OverlayContainer(m_dialogHelper); + connect(m_dialogHelper.data(), &LtsDialogHelper::signalSizeChanged, overlayContainer, + [overlayContainer](const QSize& size) { overlayContainer->setGeometry(QRect(QPoint(0, 0), size)); }); - connect(m_dialogHelper.data(), &LtsDialogHelper::signalSizeChanged, - overlayContainer, [overlayContainer](const QSize &size) - { - overlayContainer->setGeometry(QRect(QPoint(0, 0), size)); - }); + overlayContainer->setGeometry(QRect(QPoint(0, 0), m_dialogHelper->size())); + m_overlayContainer = overlayContainer; - overlayContainer->setGeometry(QRect(QPoint(0, 0), m_dialogHelper->size())); - m_overlayContainer = overlayContainer; + QHBoxLayout* l = new QHBoxLayout; + m_overlayContainer->setLayout(l); + widget->setAutoFillBackground(true); + l->addWidget(widget, 0, Qt::AlignCenter); + widget->show(); - QHBoxLayout *l = new QHBoxLayout; - m_overlayContainer->setLayout(l); + connect(widget, &QWidget::destroyed, m_overlayContainer.data(), &QObject::deleteLater); - widget->setAutoFillBackground(true); - l->addWidget(widget, 0, Qt::AlignCenter); - widget->show(); + m_overlayWidget = widget; - connect(widget, &QWidget::destroyed, - m_overlayContainer.data(), &QObject::deleteLater); - - m_overlayWidget = widget; - - m_overlayContainer->show(); - m_overlayContainer->raise(); + m_overlayContainer->show(); + m_overlayContainer->raise(); } - void LtsDialog::unsetOverlay() { - if (m_overlayWidget) - m_overlayWidget->setParent(nullptr); + if (m_overlayWidget) + m_overlayWidget->setParent(nullptr); - if (!m_overlayContainer) - return; + if (!m_overlayContainer) + return; - m_overlayContainer->setParent(nullptr); - m_overlayContainer->deleteLater(); + m_overlayContainer->setParent(nullptr); + m_overlayContainer->deleteLater(); } - -LtsDialogHelper *LtsDialog::getHelper() +LtsDialogHelper* LtsDialog::getHelper() { - return m_dialogHelper; + return m_dialogHelper; } - LtsBaseLayoutWidget* LtsDialog::baseLayoutWidget() { - return m_baseLayoutWidget; + return m_baseLayoutWidget; } - -void LtsDialog::setOnlineHelpFilename(const QString &fileName) +void LtsDialog::setOnlineHelpFilename(const QString& fileName) { - m_onlineHelpFileName = fileName; - QPushButton *btn = m_buttonBox->getButton(DialogButton::Help); + m_onlineHelpFileName = fileName; + QPushButton* btn = m_buttonBox->getButton(DialogButton::Help); - if (btn == nullptr) - return; + if (btn == nullptr) + return; - if (LtsSessionData::LtsSessionData::getInstance()->isTablet() && strcmp(PROJECTBUILD, "guez") == 0) - return; + if (LtsSessionData::LtsSessionData::getInstance()->isTablet() && strcmp(PROJECTBUILD, "guez") == 0) + return; - connect(btn, &QPushButton::clicked, - this, [this]() - { - emit signalShowOnlineHelp(m_onlineHelpFileName); - }); + connect(btn, &QPushButton::clicked, this, [this]() { emit signalShowOnlineHelp(m_onlineHelpFileName); }); - btn->setVisible(true); + btn->setVisible(true); } - void LtsDialog::addDebugMenuButton() { -#ifdef LTS_DEBUG - QMenu *menu = new QMenu(this); +#ifdef LTS_DEBUG + QMenu* menu = new QMenu(this); - menu->addAction(QStringLiteral("simulate changes"), this, &LtsDialog::slotChangesMade); - menu->addAction(QStringLiteral("unchange"), this, &LtsDialog::__unchange__); - menu->addAction(QStringLiteral("retranslate"), this, &LtsDialog::retranslate); - menu->addAction(QStringLiteral("force unlock"), this, [this]() { setUnchangeable(false); }); - menu->addAction(QStringLiteral("set unchangeable"), this, [this]() { setUnchangeable(); }); - menu->addAction(QStringLiteral("try lock"), this, &LtsDialog::tryLockTopic); - menu->addAction(QStringLiteral("set closable"), this, [this]() { m_isClosable = true; }); - menu->addAction(QStringLiteral("set unclosable"), this, [this]() { m_isClosable = false; }); - menu->addAction(QStringLiteral("clear requirements"), this, [this] { m_uiRequirements->clear(); }); - menu->addAction(QStringLiteral("enable all button box buttons"), this, [this]() - { - const auto children = m_buttonBox->findChildren(); - for (QPushButton *pb : children) - pb->setEnabled(true); - }); - menu->addAction(QStringLiteral("show button box button .."), this, [this]() - { - QString buttonObjectName = QInputDialog::getText(this, QString(), QStringLiteral("Enter button object name")); - if (buttonObjectName.isEmpty()) - return; + menu->addAction(QStringLiteral("simulate changes"), this, &LtsDialog::slotChangesMade); + menu->addAction(QStringLiteral("unchange"), this, &LtsDialog::__unchange__); + menu->addAction(QStringLiteral("retranslate"), this, &LtsDialog::retranslate); + menu->addAction(QStringLiteral("force unlock"), this, [this]() { setUnchangeable(false); }); + menu->addAction(QStringLiteral("set unchangeable"), this, [this]() { setUnchangeable(); }); + menu->addAction(QStringLiteral("try lock"), this, &LtsDialog::tryLockTopic); + menu->addAction(QStringLiteral("set closable"), this, [this]() { m_isClosable = true; }); + menu->addAction(QStringLiteral("set unclosable"), this, [this]() { m_isClosable = false; }); + menu->addAction(QStringLiteral("clear requirements"), this, [this] { m_uiRequirements->clear(); }); + menu->addAction(QStringLiteral("enable all button box buttons"), this, [this]() { + const auto children = m_buttonBox->findChildren(); + for (QPushButton* pb : children) + pb->setEnabled(true); + }); + menu->addAction(QStringLiteral("show button box button .."), this, [this]() { + QString buttonObjectName = QInputDialog::getText(this, QString(), QStringLiteral("Enter button object name")); + if (buttonObjectName.isEmpty()) + return; - const QList buttons = m_buttonBox->findChildren(buttonObjectName); + const QList buttons = m_buttonBox->findChildren(buttonObjectName); - int btnCount = buttons.count(); - if (btnCount == 0) - { - LtsMessageDialog::showMessage(this, QStringLiteral("button not found")); - return; - } + int btnCount = buttons.count(); + if (btnCount == 0) + { + LtsMessageDialog::showMessage(this, QStringLiteral("button not found")); + return; + } - if (btnCount > 1) - { - QStringList buttonStringList; - buttonStringList.reserve(buttons.size()); - for (QPushButton *pb : buttons) - buttonStringList += pb->objectName(); + if (btnCount > 1) + { + QStringList buttonStringList; + buttonStringList.reserve(buttons.size()); + for (QPushButton* pb : buttons) + buttonStringList += pb->objectName(); - LtsMessageDialog::showMessage(this, QStringLiteral("button ambiguous: %1").arg(buttonStringList.join(QStringLiteral(", ")))); - return; - } + LtsMessageDialog::showMessage( + this, QStringLiteral("button ambiguous: %1").arg(buttonStringList.join(QStringLiteral(", ")))); + return; + } - buttons.at(0)->setVisible(true); - }); + buttons.at(0)->setVisible(true); + }); - QPushButton *debugBtn = m_buttonBox->getButton(DialogButton::_debug_); - debugBtn->setMenu(menu); - debugBtn->setVisible(true); + QPushButton* debugBtn = m_buttonBox->getButton(DialogButton::_debug_); + debugBtn->setMenu(menu); + debugBtn->setVisible(true); #endif } - void LtsDialog::updateWindowTitle() { - QString completeTitle = m_title; + QString completeTitle = m_title; - if (m_changesMade) - completeTitle.insert(0, QStringLiteral("\u2022")); + if (m_changesMade) + completeTitle.insert(0, QStringLiteral("\u2022")); - if (!m_topicLockedBy.isEmpty()) - completeTitle.push_back(QString(QStringLiteral(" - READ-ONLY (%1)")).arg(m_topicLockedBy)); + if (!m_topicLockedBy.isEmpty()) + completeTitle.push_back(QString(QStringLiteral(" - READ-ONLY (%1)")).arg(m_topicLockedBy)); - QWidget::setWindowTitle(completeTitle); - if (m_dialogHelper != nullptr) - m_dialogHelper->setWindowTitle(completeTitle); + QWidget::setWindowTitle(completeTitle); + if (m_dialogHelper != nullptr) + m_dialogHelper->setWindowTitle(completeTitle); } - -void LtsDialog::setWindowTitle(const QString &title) +void LtsDialog::setWindowTitle(const QString& title) { - m_title = title; - updateWindowTitle(); + m_title = title; + updateWindowTitle(); } - -void LtsDialog::setBaseLayoutWidget(LtsBaseLayoutWidget *baseLayoutWidget) +void LtsDialog::setBaseLayoutWidget(LtsBaseLayoutWidget* baseLayoutWidget) { - m_baseLayoutWidget = baseLayoutWidget; + m_baseLayoutWidget = baseLayoutWidget; } -void LtsDialog::setIdentifier(const QString &identifier) +void LtsDialog::setIdentifier(const QString& identifier) { - m_identifier = identifier; - tableColumnOrganiserSetting(); + m_identifier = identifier; + tableColumnOrganiserSetting(); } - -void LtsDialog::addConnections(QWidget *widget) +void LtsDialog::addConnections(QWidget* widget) { - if (addChangesMadeSignal(widget, &QLineEdit::textChanged)) return; - if (addChangesMadeSignal(widget, &QDateTimeEdit::dateTimeChanged)) return; - if (addChangesMadeSignal(widget, &QComboBox::currentTextChanged)) return; - if (addChangesMadeSignal(widget, &QCheckBox::stateChanged)) return; - if (addChangesMadeSignal(widget, static_cast(&QSpinBox::valueChanged))) return; - if (addChangesMadeSignal(widget, static_cast(&QDoubleSpinBox::valueChanged))) return; - if (addChangesMadeSignal(widget, &QSlider::valueChanged)) return; - if (addChangesMadeSignal(widget, &QPlainTextEdit::textChanged)) return; - if (addChangesMadeSignal(widget, &QTextEdit::textChanged)) return; - if (addChangesMadeSignal(widget, &QAbstractButton::toggled)) return; - if (addChangesMadeSignal(widget, &LtsDateTimeEdit::dateTimeChanged)) return; + if (addChangesMadeSignal(widget, &QLineEdit::textChanged)) + return; + if (addChangesMadeSignal(widget, &QDateTimeEdit::dateTimeChanged)) + return; + if (addChangesMadeSignal(widget, &QComboBox::currentTextChanged)) + return; + if (addChangesMadeSignal(widget, &QCheckBox::stateChanged)) + return; + if (addChangesMadeSignal(widget, static_cast(&QSpinBox::valueChanged))) + return; + if (addChangesMadeSignal( + widget, static_cast(&QDoubleSpinBox::valueChanged))) + return; + if (addChangesMadeSignal(widget, &QSlider::valueChanged)) + return; + if (addChangesMadeSignal(widget, &QPlainTextEdit::textChanged)) + return; + if (addChangesMadeSignal(widget, &QTextEdit::textChanged)) + return; + if (addChangesMadeSignal(widget, &QAbstractButton::toggled)) + return; + if (addChangesMadeSignal(widget, &LtsDateTimeEdit::dateTimeChanged)) + return; } - -void LtsDialog::setUnchangeable(bool unchangeable) +void LtsDialog::setUnchangeable(bool unchangeable) { - m_unchangeableDialog = unchangeable; + m_unchangeableDialog = unchangeable; } - -bool LtsDialog::addDialogFixed(LtsDialog *dialog, const char *menuGroupUntranslated, const QString &identifier, const LayoutArea &layoutArea, bool setClosable, bool focusNewTab) +bool LtsDialog::addDialogFixed(LtsDialog* dialog, const char* menuGroupUntranslated, const QString& identifier, + const LayoutArea& layoutArea, bool setClosable, bool focusNewTab) { - return addDialog(dialog, tr(menuGroupUntranslated) , identifier, layoutArea, setClosable, focusNewTab); + return addDialog(dialog, tr(menuGroupUntranslated), identifier, layoutArea, setClosable, focusNewTab); } - -bool LtsDialog::addDialog(LtsDialog *dialog, const QString &menuGroup, const QString &identifier, const LayoutArea &layoutArea, bool setClosable, bool focusNewTab) +bool LtsDialog::addDialog(LtsDialog* dialog, const QString& menuGroup, const QString& identifier, + const LayoutArea& layoutArea, bool setClosable, bool focusNewTab) { - if (!m_baseLayoutWidget) - { - qCritical() << "LtsDialog: addDialog: no base layout set - cannot add Dialog !"; - return false; - } + if (!m_baseLayoutWidget) + { + qCritical() << "LtsDialog: addDialog: no base layout set - cannot add Dialog !"; + return false; + } - return m_baseLayoutWidget->addWidget(dialog, menuGroup, identifier, layoutArea, setClosable, focusNewTab); + return m_baseLayoutWidget->addWidget(dialog, menuGroup, identifier, layoutArea, setClosable, focusNewTab); } - bool LtsDialog::amIFocused() const { - if (!m_baseLayoutWidget) - { - qCritical() << "LtsDialog: addDialog: no base layout set - cannot check for focus!"; - return false; - } + if (!m_baseLayoutWidget) + { + qCritical() << "LtsDialog: addDialog: no base layout set - cannot check for focus!"; + return false; + } - return m_baseLayoutWidget->isDialogFocused(this); + return m_baseLayoutWidget->isDialogFocused(this); } - -bool LtsDialog::focusDialog(const QString &menuGroup, const QString &identifier, const LayoutArea &layoutArea) +bool LtsDialog::focusDialog(const QString& menuGroup, const QString& identifier, const LayoutArea& layoutArea) { - if (!m_baseLayoutWidget) - { - qCritical() << "LtsDialog: addDialog: no base layout set - cannot focus Dialog !"; - return false; - } + if (!m_baseLayoutWidget) + { + qCritical() << "LtsDialog: addDialog: no base layout set - cannot focus Dialog !"; + return false; + } - return m_baseLayoutWidget->focusTab(menuGroup, identifier, layoutArea); + return m_baseLayoutWidget->focusTab(menuGroup, identifier, layoutArea); } - -void LtsDialog::showEvent(QShowEvent *event) +void LtsDialog::showEvent(QShowEvent* event) { - emit visibilityChanged(true); + emit visibilityChanged(true); - bool tmp = m_unchangeableDialog; + bool tmp = m_unchangeableDialog; - if (!m_firstShow) - { - QWidget::showEvent(event); - return; - } + if (!m_firstShow) + { + QWidget::showEvent(event); + return; + } - m_unchangeableDialog = true; - m_firstShow = false; + m_unchangeableDialog = true; + m_firstShow = false; - + QList listenWidgets = findChildren(); - + for (auto i = listenWidgets.begin(); i != listenWidgets.end(); ++i) + { - QList listenWidgets = findChildren(); + QWidget* widget = *i; - for (auto i = listenWidgets.begin(); i != listenWidgets.end(); ++i) - { - - + QVariant isConst = widget->property("const"); + if (isConst.isValid() && isConst.toBool()) + continue; - QWidget *widget = *i; - - QVariant isConst = widget->property("const"); - if (isConst.isValid() && isConst.toBool()) - continue; - - if (!tmp) - addConnections(widget); + if (!tmp) + addConnections(widget); #ifdef TABLET_MODE - LtsWidgets::addTouchScroll(widget); + LtsWidgets::addTouchScroll(widget); #endif - } + } - QWidget::showEvent(event); - m_unchangeableDialog = tmp; + QWidget::showEvent(event); + m_unchangeableDialog = tmp; } - void LtsDialog::tryLockTopic() { - TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"; - if (!m_topicInfo.isValid()) - return; + TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"; + if (!m_topicInfo.isValid()) + return; - if (m_topicInfo.isLocked()) - { - WARNING_LOG(m_logger) << Q_FUNC_INFO << " tried to lock with an already locked topic info, return"; - return; - } + if (m_topicInfo.isLocked()) + { + WARNING_LOG(m_logger) << Q_FUNC_INFO << " tried to lock with an already locked topic info, return"; + return; + } - if (m_noLockTopic) - return; + if (m_noLockTopic) + return; + bool bIsConnected = isSignalConnected(QMetaMethod::fromSignal(&LtsDialog::signalLockTopic)); - - - - - - - bool bIsConnected = isSignalConnected(QMetaMethod::fromSignal(&LtsDialog::signalLockTopic)); + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " signalLockTopic(): " + << ", TopicName =" << m_topicInfo.topicName() << ", entity =" << m_topicInfo.entityId() + << ", signalLockTopic isConnected=" << bIsConnected; - DEBUG_LOG(m_logger) << Q_FUNC_INFO - << " signalLockTopic(): " - << ", TopicName =" << m_topicInfo.topicName() - << ", entity =" << m_topicInfo.entityId() - << ", signalLockTopic isConnected=" << bIsConnected; + if (bIsConnected) + { + emit signalLockTopic(m_topicInfo); - if (bIsConnected) - { - emit signalLockTopic(m_topicInfo); - - m_topicInfo.setLocked(); - } - TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"; + m_topicInfo.setLocked(); + } + TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"; } -void LtsDialog::initTopicLockHandler(const QString &topicName, int entityId) +void LtsDialog::initTopicLockHandler(const QString& topicName, int entityId) { - - m_topicInfo.setTopicName(topicName); - m_topicInfo.setEntity(entityId); - m_topicInfo.setValid(); + m_topicInfo.setTopicName(topicName); + m_topicInfo.setEntity(entityId); + m_topicInfo.setValid(); } - void LtsDialog::tryLockTopicNew() { - TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"; - tryLockTopic(); - TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"; + TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"; + tryLockTopic(); + TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"; } -void LtsDialog::tryLockTopicNew(const QString &topicName, int entityId) +void LtsDialog::tryLockTopicNew(const QString& topicName, int entityId) { - TRACE_LOG(m_logger) << Q_FUNC_INFO << " START" - << ", topicName='" << topicName << "'" - << ", entityId=" << entityId; + TRACE_LOG(m_logger) << Q_FUNC_INFO << " START" + << ", topicName='" << topicName << "'" + << ", entityId=" << entityId; - + if (m_topicInfo.entityId() != entityId) + { + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " topicName='" << topicName << "'" + << " change from " << m_topicInfo.entityId() << " to " << entityId; + m_topicInfo.setLocked(false); + } - if (m_topicInfo.entityId() != entityId) - { - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " topicName='" << topicName << "'" - << " change from " << m_topicInfo.entityId() << " to " << entityId; - m_topicInfo.setLocked(false); - } + m_topicInfo.setTopicName(topicName); + m_topicInfo.setEntity(entityId); + m_topicInfo.setValid(); - - m_topicInfo.setTopicName(topicName); - m_topicInfo.setEntity(entityId); - m_topicInfo.setValid(); - - tryLockTopic(); - TRACE_LOG(m_logger) << Q_FUNC_INFO << " END" - << ", topicName='" << topicName << "'" - << ", entityId=" << entityId; + tryLockTopic(); + TRACE_LOG(m_logger) << Q_FUNC_INFO << " END" + << ", topicName='" << topicName << "'" + << ", entityId=" << entityId; } void LtsDialog::triggerTopicLock() { - TRACE_LOG(m_logger) << Q_FUNC_INFO << " START" << " !!trigger!!"; - tryLockTopic(); - TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"; + TRACE_LOG(m_logger) << Q_FUNC_INFO << " START" + << " !!trigger!!"; + tryLockTopic(); + TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"; } - -void LtsDialog::translate(const QString &title) +void LtsDialog::translate(const QString& title) { - bool isAlreadyUnchangeable = unchangeable(); + bool isAlreadyUnchangeable = unchangeable(); - if (!isAlreadyUnchangeable) - setUnchangeable(true); + if (!isAlreadyUnchangeable) + setUnchangeable(true); - setWindowTitle(title); + setWindowTitle(title); + if (!isAlreadyUnchangeable) + setUnchangeable(false); - - - - if (!isAlreadyUnchangeable) - setUnchangeable(false); - - { - bool isNowAlreadyUnchangeable = unchangeable(); - - QPushButton *b = m_buttonBox->getButton(DialogButton::ReadOnly); - if (b) { - connect(b, &QPushButton::clicked, this, &LtsDialog::onReadOnlyButtonClicked, Qt::UniqueConnection); + bool isNowAlreadyUnchangeable = unchangeable(); - - b->setVisible(isNowAlreadyUnchangeable && !m_topicLockedBy.isEmpty()); - if (b->isVisible()) - b->setToolTip(tr("Locked by: %1").arg(m_topicLockedBy)); - else - b->setToolTip({}); + QPushButton* b = m_buttonBox->getButton(DialogButton::ReadOnly); + if (b) + { + connect(b, &QPushButton::clicked, this, &LtsDialog::onReadOnlyButtonClicked, Qt::UniqueConnection); + + b->setVisible(isNowAlreadyUnchangeable && !m_topicLockedBy.isEmpty()); + if (b->isVisible()) + b->setToolTip(tr("Locked by: %1").arg(m_topicLockedBy)); + else + b->setToolTip({}); + } } - } } - - -void LtsDialog::slotLock(const QString &lockedBy) +void LtsDialog::slotLock(const QString& lockedBy) { - setUnchangeable(true); + setUnchangeable(true); - m_topicLockedBy = lockedBy; + m_topicLockedBy = lockedBy; - lock(); - retranslate(); + lock(); + retranslate(); } - void LtsDialog::slotUnlock() { - setUnchangeable(false); + setUnchangeable(false); - m_topicLockedBy.clear(); + m_topicLockedBy.clear(); - unlock(); - retranslate(); + unlock(); + retranslate(); } - void LtsDialog::lock() { - setWidgetsReadonly(true); - setWidgetsReadonly(true); - - setWidgetsReadonly(true); - setWidgetsReadonly(true); - setWidgetsReadonly(true); - setWidgetsReadonly(true); + setWidgetsReadonly(true); + setWidgetsReadonly(true); - setWidgetsDisabled(true); - setWidgetsDisabled(true); - setWidgetsDisabled(true); - setWidgetsDisabled(true); - setWidgetsDisabled(true); - setWidgetsDisabled(true); - setWidgetsDisabled(true); - setWidgetsDisabled(true); - setWidgetsDisabled(true); + setWidgetsReadonly(true); + setWidgetsReadonly(true); + setWidgetsReadonly(true); + setWidgetsReadonly(true); + + setWidgetsDisabled(true); + setWidgetsDisabled(true); + setWidgetsDisabled(true); + setWidgetsDisabled(true); + setWidgetsDisabled(true); + setWidgetsDisabled(true); + setWidgetsDisabled(true); + setWidgetsDisabled(true); + setWidgetsDisabled(true); } - void LtsDialog::unlock() { - restoreReadonly(); - restoreReadonly(); + restoreReadonly(); + restoreReadonly(); - restoreReadonly(); - restoreReadonly(); - restoreReadonly(); - restoreReadonly(); + restoreReadonly(); + restoreReadonly(); + restoreReadonly(); + restoreReadonly(); - restoreEnabled(); - restoreEnabled(); - restoreEnabled(); - restoreEnabled(); - restoreEnabled(); - restoreEnabled(); - restoreEnabled(); - restoreEnabled(); + restoreEnabled(); + restoreEnabled(); + restoreEnabled(); + restoreEnabled(); + restoreEnabled(); + restoreEnabled(); + restoreEnabled(); + restoreEnabled(); } - -void LtsDialog::slotChangesMade() +void LtsDialog::slotChangesMade() { - if (m_unchangeableDialog) - return; + if (m_unchangeableDialog) + return; - m_changesMade = true; - updateWindowTitle(); + m_changesMade = true; + updateWindowTitle(); - m_buttonBox->getButton(DialogButton::Ok)->setEnabled(true); - m_buttonBox->getButton(DialogButton::Apply)->setEnabled(true); + m_buttonBox->getButton(DialogButton::Ok)->setEnabled(true); + m_buttonBox->getButton(DialogButton::Apply)->setEnabled(true); - emit signalChangesMade(); + emit signalChangesMade(); } - void LtsDialog::resetChanges() { - m_changesMade = false; + m_changesMade = false; - updateWindowTitle(); - - + updateWindowTitle(); - m_buttonBox->getButton(DialogButton::Ok)->setEnabled(false); - m_buttonBox->getButton(DialogButton::Apply)->setEnabled(false); - emit signalChangesReset(); + m_buttonBox->getButton(DialogButton::Ok)->setEnabled(false); + m_buttonBox->getButton(DialogButton::Apply)->setEnabled(false); + emit signalChangesReset(); } - bool LtsDialog::_apply() { - if (m_uiRequirements->checkRequirements(this) && apply()) - { - resetChanges(); - return true; - } + if (m_uiRequirements->checkRequirements(this) && apply()) + { + resetChanges(); + return true; + } - return false; + return false; } - Button LtsDialog::askApplyDiscardCancel() { - return LtsMessageDialog::askApplyDiscardCancel(this); + return LtsMessageDialog::askApplyDiscardCancel(this); } - -void LtsDialog::slotApply() +void LtsDialog::slotApply() { - _apply(); + _apply(); } - -void LtsDialog::slotOkay() +void LtsDialog::slotOkay() { - if (_apply()) - _close(); + if (_apply()) + _close(); } - void LtsDialog::slotHide() { - _hide(); + _hide(); } - -void LtsDialog::slotClose() +void LtsDialog::slotClose() { - - if ((m_changesMade) && (!m_unchangeableDialog)) - { - switch (askApplyDiscardCancel()) + + if ((m_changesMade) && (!m_unchangeableDialog)) { - case Button::Apply: - slotOkay(); - break; - case Button::Discard: - _discard(); - break; - default: - break; + switch (askApplyDiscardCancel()) + { + case Button::Apply: + slotOkay(); + break; + case Button::Discard: + _discard(); + break; + default: + break; + } + } + else + { + _close(); } - } - else - { - _close(); - } } void LtsDialog::onReadOnlyButtonClicked() { - if (m_topicLockedBy.isEmpty()) - return; - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Locked by: %1").arg(m_topicLockedBy)); + if (m_topicLockedBy.isEmpty()) + return; + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Locked by: %1").arg(m_topicLockedBy)); } - void LtsDialog::closeRequest() { - slotClose(); + slotClose(); } - void LtsDialog::_hide() { - if (m_dialogHelper != nullptr) - { - emit signalHide(m_dialogHelper); - - } + if (m_dialogHelper != nullptr) + { + emit signalHide(m_dialogHelper); + } } - void LtsDialog::_close() { - resetChanges(); - aboutToClose(); - if (m_dialogHelper != nullptr) - m_dialogHelper->close(); + resetChanges(); + aboutToClose(); + if (m_dialogHelper != nullptr) + m_dialogHelper->close(); } void LtsDialog::_discard() { - dialogCanceled(); - _close(); + dialogCanceled(); + _close(); } -} - - - +} // namespace LtsWidgets #include "lts_dialog.moc" diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog.h old mode 100755 new mode 100644 index 13f0534df..2695ce992 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog.h @@ -1,57 +1,79 @@ - #pragma once -#include - #include "lts_base.h" +#include "lts_dialog_button_box.h" #include "ltswidgets_export.h" #include "requirement_widget.h" -#include "lts_dialog_button_box.h" #include - -#include -#include -#include #include -#include +#include #include -#include +#include +#include +#include #include +#include +#include +#include +#include +#include #include #include -#include -#include - -#include - namespace LtsWidgets { class TopicInfo { -public: - int entityId() const { return m_entityId; } - const QString &topicName() const { return m_topicName; } - bool isLocked() const { return m_locked; } - bool isValid() const { return m_valid; } + public: + int entityId() const + { + return m_entityId; + } - void setEntity(int entityId) { m_entityId = entityId; } - void setTopicName(const QString &topicName) { m_topicName = topicName; } - void setLocked(bool locked = true) { m_locked = locked; } - void setValid() { m_valid = true; } + const QString& topicName() const + { + return m_topicName; + } -private: + bool isLocked() const + { + return m_locked; + } -NGL::INGLLogger &m_logger; - QString m_topicName; - int m_entityId{0}; - bool m_locked{false}; - bool m_valid{false}; + bool isValid() const + { + return m_valid; + } + + void setEntity(int entityId) + { + m_entityId = entityId; + } + + void setTopicName(const QString& topicName) + { + m_topicName = topicName; + } + + void setLocked(bool locked = true) + { + m_locked = locked; + } + + void setValid() + { + m_valid = true; + } + + private: + QString m_topicName; + int m_entityId{0}; + bool m_locked{false}; + bool m_valid{false}; }; - class LtsBaseLayoutWidget; class LtsDialogHelper; class LtsProgressDialogHelper; @@ -59,416 +81,393 @@ class LtsDialogButtonBox; class LtsToolBarArea; class OverlayContainer; +enum class ButtonCombination { + OkApplyCancel, -enum class ButtonCombination -{ - OkApplyCancel, + OkCancel, - OkCancel, - - - - CloseOnly, - SeamlessDialog, + CloseOnly, + SeamlessDialog, }; - - - class LTSWIDGETS_EXPORT LtsDialog : public QWidget { - Q_OBJECT + Q_OBJECT - Q_PROPERTY(bool unchangeable READ unchangeable WRITE setUnchangeable) -public: - static int s_object_count; + Q_PROPERTY(bool unchangeable READ unchangeable WRITE setUnchangeable) + public: + static int s_object_count; - + explicit LtsDialog(QWidget* parent = nullptr, ButtonCombination buttonCombination = ButtonCombination::CloseOnly, + bool closeable = true); + ~LtsDialog(); - explicit LtsDialog(QWidget *parent = nullptr, ButtonCombination buttonCombination = ButtonCombination::CloseOnly, bool closeable = true); - ~LtsDialog(); + LtsDialogHelper* getHelper(); - - - LtsDialogHelper *getHelper(); - - bool hasUnsavedChanges() const { return m_changesMade || m_currentlyBlocking; } - - - - virtual void retranslate() = 0; - - void closeRequest(); - void setUnchangeable(bool unchangeable = true); - bool unchangeable() const { return m_unchangeableDialog; } - - - - bool addDialog(LtsDialog *dialog, const QString &menuGroup, const QString &identifier, const LayoutArea &layoutArea = LayoutArea::eDialogTab, bool setClosable = true, bool focusNewTab = true); - - - Q_DECL_DEPRECATED bool addDialogFixed(LtsDialog *dialog, const char *menuGroupUntranslated, const QString &identifier, const LayoutArea &layoutArea = LayoutArea::eDialogTab, bool setClosable = true, bool focusNewTab = true); - bool focusDialog(const QString &menuGroup, const QString &identifier, const LayoutArea &layoutArea); - bool amIFocused() const; - void setBaseLayoutWidget(LtsBaseLayoutWidget *baseLayoutWidget); - void __unchange__() { resetChanges(); } - void setClosable(bool closable) { m_isClosable = closable; } - bool isClosable() const { return m_isClosable; } - virtual void aboutToClose() {} - void setMenuGroup(const QString &menuGroup) { m_menuGroup = menuGroup; } - const QString &menuGroup() const { return m_menuGroup; } - void setIdentifier(const QString &identifier); - virtual void tableColumnOrganiserSetting(){}; - const QString &identifier() const { return m_identifier; } - - void setOverlay(QWidget *widget); - void unsetOverlay(); - - - - static inline void setMinWidthForWidgetHelper(QWidget *w) - { - int width = w->sizeHint().width(); - w->setMinimumWidth(width); - } - - QString windowTitle() const - { - return m_title; - } - - - - - - - - - - - - - - - void tryLockTopicNew(); - - - - virtual void tryLockTopicNew (const QString &topicName, int entityId = -1); - - - void triggerTopicLock(); - - void setOnlineHelpFilename(const QString &fileName); - void setCurrentlyBlocking(bool currentlyBlocking = true) { m_currentlyBlocking = currentlyBlocking; } - -signals: - - - void startMainSelect(LtsWidgets::LayoutArea); - - - - void endMainSelect(LtsWidgets::LayoutArea); - - - - void signalChangesMade(); - - void signalHide(QObject *object); - - - - void signalChangesReset(); - - void signalFocused(); - void visibilityChanged(bool visible); - void signalLockTopic(const LtsWidgets::TopicInfo &topicInfo); - void signalShowOnlineHelp(const QString &fileName); - -protected: - - - void translate(const QString &title); - - - - template - - - void translate(T *ui, const QString &title) - { - translate(title); - if (ui) - ui->retranslateUi(this); - - m_uiRequirements->retranslate(); - } - - void hideEvent(QHideEvent *event) override - { - QWidget::hideEvent(event); - emit visibilityChanged(false); - } - - template - - - void translate(T *ui, const QString &custom, bool isNew, const QString &title) - { - QString newTitle; - if (!isNew) + bool hasUnsavedChanges() const { - if (unchangeable()) - { - if (custom.isEmpty()) - newTitle = (tr("Show %1").arg(title)); + return m_changesMade || m_currentlyBlocking; + } + + virtual void retranslate() = 0; + + void closeRequest(); + void setUnchangeable(bool unchangeable = true); + + bool unchangeable() const + { + return m_unchangeableDialog; + } + + bool addDialog(LtsDialog* dialog, const QString& menuGroup, const QString& identifier, + const LayoutArea& layoutArea = LayoutArea::eDialogTab, bool setClosable = true, + bool focusNewTab = true); + + Q_DECL_DEPRECATED bool addDialogFixed(LtsDialog* dialog, const char* menuGroupUntranslated, + const QString& identifier, + const LayoutArea& layoutArea = LayoutArea::eDialogTab, + bool setClosable = true, bool focusNewTab = true); + bool focusDialog(const QString& menuGroup, const QString& identifier, const LayoutArea& layoutArea); + bool amIFocused() const; + void setBaseLayoutWidget(LtsBaseLayoutWidget* baseLayoutWidget); + + void __unchange__() + { + resetChanges(); + } + + void setClosable(bool closable) + { + m_isClosable = closable; + } + + bool isClosable() const + { + return m_isClosable; + } + + virtual void aboutToClose() {} + + void setMenuGroup(const QString& menuGroup) + { + m_menuGroup = menuGroup; + } + + const QString& menuGroup() const + { + return m_menuGroup; + } + + void setIdentifier(const QString& identifier); + virtual void tableColumnOrganiserSetting(){}; + + const QString& identifier() const + { + return m_identifier; + } + + void setOverlay(QWidget* widget); + void unsetOverlay(); + + static inline void setMinWidthForWidgetHelper(QWidget* w) + { + int width = w->sizeHint().width(); + w->setMinimumWidth(width); + } + + QString windowTitle() const + { + return m_title; + } + + void tryLockTopicNew(); + + virtual void tryLockTopicNew(const QString& topicName, int entityId = -1); + + void triggerTopicLock(); + + void setOnlineHelpFilename(const QString& fileName); + + void setCurrentlyBlocking(bool currentlyBlocking = true) + { + m_currentlyBlocking = currentlyBlocking; + } + + signals: + + void startMainSelect(LtsWidgets::LayoutArea); + + void endMainSelect(LtsWidgets::LayoutArea); + + void signalChangesMade(); + + void signalHide(QObject* object); + + void signalChangesReset(); + + void signalFocused(); + void visibilityChanged(bool visible); + void signalLockTopic(const LtsWidgets::TopicInfo& topicInfo); + void signalShowOnlineHelp(const QString& fileName); + + protected: + void translate(const QString& title); + + template + + void translate(T* ui, const QString& title) + { + translate(title); + if (ui) + ui->retranslateUi(this); + + m_uiRequirements->retranslate(); + } + + void hideEvent(QHideEvent* event) override + { + QWidget::hideEvent(event); + emit visibilityChanged(false); + } + + template + + void translate(T* ui, const QString& custom, bool isNew, const QString& title) + { + QString newTitle; + if (!isNew) + { + if (unchangeable()) + { + if (custom.isEmpty()) + newTitle = (tr("Show %1").arg(title)); + else + newTitle = (tr("Show %1: %2").arg(title, custom)); + } + else + { + if (custom.isEmpty()) + newTitle = (tr("Edit %1").arg(title)); + else + newTitle = (tr("Edit %1: %2").arg(title, custom)); + + tryLockTopicNew(); + } + } else - newTitle = (tr("Show %1: %2").arg(title, custom)); - } - else - { - if (custom.isEmpty()) - newTitle = (tr("Edit %1").arg(title)); - else - newTitle = (tr("Edit %1: %2").arg(title, custom)); + { + newTitle = (tr("New %1").arg(title)); + m_buttonBox->getButton(LtsWidgets::DialogButton::Apply)->hide(); + m_buttonBox->getButton(LtsWidgets::DialogButton::Ok)->setText(tr("Create")); + } - - tryLockTopicNew(); - } + translate(ui, newTitle); } - else + + template + + void translate(T* ui, const QString& customUniqueTopicName, int topicId, const QString& custom, + const QString& title) { - newTitle = (tr("New %1").arg(title)); - m_buttonBox->getButton(LtsWidgets::DialogButton::Apply)->hide(); - m_buttonBox->getButton(LtsWidgets::DialogButton::Ok)->setText(tr("Create")); + Q_UNUSED(customUniqueTopicName); + + initTopicLockHandler(customUniqueTopicName, topicId); + + translate(ui, custom, (topicId < 1), title); } - translate(ui, newTitle); - } + template - - template - - - void translate(T* ui, const QString &customUniqueTopicName, int topicId, const QString &custom, const QString &title) - { - Q_UNUSED(customUniqueTopicName); - - initTopicLockHandler(customUniqueTopicName, topicId); - - translate(ui, custom , - (topicId < 1 ), - title); - } - - - template - - - void translate(T *ui, const S &data, const QString &custom, const QString &title) - { - translate(ui, QString::fromUtf8(typeid(data).name()), data.id(), custom , title); - } - - - template - - - void translate(T *ui, const S &data, const QString &title) - { - translate(ui, data, QString::fromStdString(data.name()), title); - } - - - - virtual void dialogCanceled() {} - LtsBaseLayoutWidget* baseLayoutWidget(); - void setNoTopicLock() { m_noLockTopic = true; } - -private: - friend class LtsDialogHelper; - - bool m_changesMade; - bool m_currentlyBlocking { false }; - bool m_firstShow; - QPointer m_baseLayoutWidget; - bool m_isClosable; - TopicInfo m_topicInfo; - -public: - QString m_topicLockedBy; - -private: - bool m_noLockTopic; - bool m_unchangeableDialog; - QPointer m_dialogHelper; - - QString m_title; - QString m_onlineHelpFileName; - QString m_menuGroup; - QString m_identifier; - - - QPointer m_overlayContainer; - QPointer m_overlayWidget; - - bool _apply(); - void _close(); - void _discard(); - void _hide(); - void resetChanges(); - void addDebugMenuButton(); - void tryLockTopic(); - void initTopicLockHandler(const QString &topicName, int entityId); - - - - void setWindowTitle(const QString &title); - void updateWindowTitle(); - void addConnections(QWidget *widget); - - template - bool addChangesMadeSignal(QWidget *widget, SignalFunc signal) - { - WidgetType *concreteWidget = qobject_cast(widget); - - if (!concreteWidget) - return false; - - connect(concreteWidget, signal, this, &LtsDialog::slotChangesMade); - return true; - } - - - template - void setWidgetsReadonly(bool readonly) - { - const auto children = findChildren(); - for (WidgetType *widget : children ) + void translate(T* ui, const S& data, const QString& custom, const QString& title) { - widget->setProperty("lastReadOnlyState", widget->isReadOnly()); - widget->setReadOnly(readonly); + translate(ui, QString::fromUtf8(typeid(data).name()), data.id(), custom, title); } - } + template - template - void setWidgetsDisabled(bool disabled) - { - const auto children = findChildren(); - for (WidgetType *widget : children) + void translate(T* ui, const S& data, const QString& title) { - widget->setProperty("lastEnabledState", widget->isEnabled()); - widget->setEnabled(!disabled); + translate(ui, data, QString::fromStdString(data.name()), title); } - } - template - void restoreReadonly() - { - const auto children = findChildren(); - for (WidgetType *widget : children) + virtual void dialogCanceled() {} + + LtsBaseLayoutWidget* baseLayoutWidget(); + + void setNoTopicLock() { - QVariant lastState = widget->property("lastReadOnlyState"); - if (lastState.isValid() && !lastState.isNull() && lastState.canConvert(QMetaType::Bool)) - widget->setReadOnly(lastState.toBool()); + m_noLockTopic = true; } - } - template - void restoreEnabled() - { - const auto children = findChildren(); - for (WidgetType *widget : children) + private: + friend class LtsDialogHelper; + + bool m_changesMade; + bool m_currentlyBlocking{false}; + bool m_firstShow; + QPointer m_baseLayoutWidget; + bool m_isClosable; + TopicInfo m_topicInfo; + + public: + QString m_topicLockedBy; + + private: + bool m_noLockTopic; + bool m_unchangeableDialog; + QPointer m_dialogHelper; + NGL::INGLLogger& m_logger; + + QString m_title; + QString m_onlineHelpFileName; + QString m_menuGroup; + QString m_identifier; + + QPointer m_overlayContainer; + QPointer m_overlayWidget; + + bool _apply(); + void _close(); + void _discard(); + void _hide(); + void resetChanges(); + void addDebugMenuButton(); + void tryLockTopic(); + void initTopicLockHandler(const QString& topicName, int entityId); + + void setWindowTitle(const QString& title); + void updateWindowTitle(); + void addConnections(QWidget* widget); + + template bool addChangesMadeSignal(QWidget* widget, SignalFunc signal) { - QVariant lastState = widget->property("lastEnabledState"); - if (lastState.isValid() && !lastState.isNull() && lastState.canConvert(QMetaType::Bool)) - widget->setEnabled(lastState.toBool()); + WidgetType* concreteWidget = qobject_cast(widget); + + if (!concreteWidget) + return false; + + connect(concreteWidget, signal, this, &LtsDialog::slotChangesMade); + return true; } - } -public slots: - + template void setWidgetsReadonly(bool readonly) + { + const auto children = findChildren(); + for (WidgetType* widget : children) + { + widget->setProperty("lastReadOnlyState", widget->isReadOnly()); + widget->setReadOnly(readonly); + } + } - void slotChangesMade(); + template void setWidgetsDisabled(bool disabled) + { + const auto children = findChildren(); + for (WidgetType* widget : children) + { + widget->setProperty("lastEnabledState", widget->isEnabled()); + widget->setEnabled(!disabled); + } + } - void slotHide(); - void slotLock(const QString &lockedBy); - void slotUnlock(); + template void restoreReadonly() + { + const auto children = findChildren(); + for (WidgetType* widget : children) + { + QVariant lastState = widget->property("lastReadOnlyState"); + if (lastState.isValid() && !lastState.isNull() && lastState.canConvert(QMetaType::Bool)) + widget->setReadOnly(lastState.toBool()); + } + } -private slots: - void slotApply(); - void slotOkay(); - void slotClose(); - - void onReadOnlyButtonClicked(); + template void restoreEnabled() + { + const auto children = findChildren(); + for (WidgetType* widget : children) + { + QVariant lastState = widget->property("lastEnabledState"); + if (lastState.isValid() && !lastState.isNull() && lastState.canConvert(QMetaType::Bool)) + widget->setEnabled(lastState.toBool()); + } + } -protected: - virtual void lock(); - virtual void unlock(); + public slots: - virtual bool apply() { return true; } - void showEvent(QShowEvent *event) override; - Button askApplyDiscardCancel(); + void slotChangesMade(); - LtsDialogButtonBox *m_buttonBox; - UiRequirementList *m_uiRequirements; + void slotHide(); + void slotLock(const QString& lockedBy); + void slotUnlock(); + + private slots: + void slotApply(); + void slotOkay(); + void slotClose(); + + void onReadOnlyButtonClicked(); + + protected: + virtual void lock(); + virtual void unlock(); + + virtual bool apply() + { + return true; + } + + void showEvent(QShowEvent* event) override; + Button askApplyDiscardCancel(); + + LtsDialogButtonBox* m_buttonBox; + UiRequirementList* m_uiRequirements; }; - - -template -T *initDialog(T *dialog) +template T* initDialog(T* dialog) { - if (!dialog->init()) - { - dialog->deleteLater(); - return nullptr; - } - return dialog; + if (!dialog->init()) + { + dialog->deleteLater(); + return nullptr; + } + return dialog; } - -template -T *initDialog(T *dialog, F&&... f) +template T* initDialog(T* dialog, F&&... f) { - if (!dialog->init(std::forward(f)...)) - { - dialog->deleteLater(); - return nullptr; - } - return dialog; + if (!dialog->init(std::forward(f)...)) + { + dialog->deleteLater(); + return nullptr; + } + return dialog; } - -template -T *createThrowableDialog(F&&... f) +template T* createThrowableDialog(F&&... f) { - T *dlg = nullptr; + T* dlg = nullptr; - try - { - dlg = new T(std::forward(f)...); - } - catch (const char *s) - { - fprintf(stderr, "Dialog could not be created: %s\n", s); - return nullptr; - } - catch (const QString &msg) - { - fprintf(stderr, "Dialog could not be created: %s\n", msg.toStdString().c_str()); - return nullptr; - } - catch (...) - { - fprintf(stderr, "Dialog could not be created: unknown error\n"); - return nullptr; - } + try + { + dlg = new T(std::forward(f)...); + } + catch (const char* s) + { + fprintf(stderr, "Dialog could not be created: %s\n", s); + return nullptr; + } + catch (const QString& msg) + { + fprintf(stderr, "Dialog could not be created: %s\n", msg.toStdString().c_str()); + return nullptr; + } + catch (...) + { + fprintf(stderr, "Dialog could not be created: unknown error\n"); + return nullptr; + } - return dlg; + return dlg; } - -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_drag_icon.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_drag_icon.cpp old mode 100755 new mode 100644 index 9dad4ce61..0280ed1f9 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_drag_icon.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_drag_icon.cpp @@ -1,489 +1,483 @@ - #include "lts_drag_icon.h" +#include +#include #include #include #include #include -#include -#include -#include #include +#include +#include #include #include -#include -#include +#include namespace LtsWidgets { class LtsToolButton : public QToolButton { - Q_OBJECT -public: - explicit LtsToolButton(QWidget *parent) - : QToolButton(parent) - , m_sameWidgetDrop(false) - , m_isDraggable(true) - , m_startPos(QPoint()) - { - setAutoFillBackground(false); - setToolButtonStyle(Qt::ToolButtonTextUnderIcon); - } + Q_OBJECT + public: + explicit LtsToolButton(QWidget* parent) + : QToolButton(parent), m_sameWidgetDrop(false), m_isDraggable(true), m_startPos(QPoint()) + { + setAutoFillBackground(false); + setToolButtonStyle(Qt::ToolButtonTextUnderIcon); + } - virtual ~LtsToolButton() = default; + virtual ~LtsToolButton() = default; - void mousePressEvent(QMouseEvent *event) override; - void mouseReleaseEvent(QMouseEvent *event) override; - void mouseMoveEvent(QMouseEvent *event) override; - void dragEnterEvent(QDragEnterEvent *event) override; - void setSameWidgetDrop(bool drop) { m_sameWidgetDrop = drop; } - bool sameWidgetDrop() const { return m_sameWidgetDrop; } - void setDraggable(bool isDraggable) { m_isDraggable = isDraggable; } - void dropEvent(QDropEvent *event) override - { - emit newDropEvent(event); - QToolButton::dropEvent(event); - } - void addMimeData(const QString &mimeType, const QByteArray &data); - bool removeMimeData(const QString &mimeType); - void removeAllMimeData() { m_mimeData.clear(); } + void mousePressEvent(QMouseEvent* event) override; + void mouseReleaseEvent(QMouseEvent* event) override; + void mouseMoveEvent(QMouseEvent* event) override; + void dragEnterEvent(QDragEnterEvent* event) override; -protected: - void initButton(); + void setSameWidgetDrop(bool drop) + { + m_sameWidgetDrop = drop; + } -signals: - void newDropEvent(QDropEvent *e); - void dropSuc(); + bool sameWidgetDrop() const + { + return m_sameWidgetDrop; + } -private: - void performDrag(QMouseEvent *event); - bool m_sameWidgetDrop; - bool m_isDraggable; - QPoint m_startPos; - QMap m_mimeData; + void setDraggable(bool isDraggable) + { + m_isDraggable = isDraggable; + } + void dropEvent(QDropEvent* event) override + { + emit newDropEvent(event); + QToolButton::dropEvent(event); + } + + void addMimeData(const QString& mimeType, const QByteArray& data); + bool removeMimeData(const QString& mimeType); + + void removeAllMimeData() + { + m_mimeData.clear(); + } + + protected: + void initButton(); + + signals: + void newDropEvent(QDropEvent* e); + void dropSuc(); + + private: + void performDrag(QMouseEvent* event); + bool m_sameWidgetDrop; + bool m_isDraggable; + QPoint m_startPos; + QMap m_mimeData; }; - - -LtsDragIcon::LtsDragIcon(QWidget *parent) - : QWidget(parent) - , m_lay(nullptr) - , m_toolButton(nullptr) - , m_icon() - , m_dragLabel(new QLabel(this)) - , m_text() - , m_style(ButtonStyle::eAll) - , m_forceFixedSize(false) - , m_isDraggable(true) - , m_dropHandlerKey(0L) - , m_buttonSize(ButtonSize::eDefault) - , m_showDragIcon(true) +LtsDragIcon::LtsDragIcon(QWidget* parent) + : QWidget(parent), m_lay(nullptr), m_toolButton(nullptr), m_icon(), m_dragLabel(new QLabel(this)), m_text(), + m_style(ButtonStyle::eAll), m_forceFixedSize(false), m_isDraggable(true), m_dropHandlerKey(0L), + m_buttonSize(ButtonSize::eDefault), m_showDragIcon(true) { - setAutoFillBackground(false); - initButton(); + setAutoFillBackground(false); + initButton(); } - void LtsDragIcon::setStyleToButton() { - if (nullptr == m_toolButton) return; + if (nullptr == m_toolButton) + return; - switch (m_style) - { - case ButtonStyle::eIconOnly: - { - setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - m_toolButton->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); - setFixedSize(QSize(static_cast(m_buttonSize), static_cast(m_buttonSize))); - m_toolButton->setToolButtonStyle(Qt::ToolButtonIconOnly); - } break; + switch (m_style) + { + case ButtonStyle::eIconOnly: { + setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + m_toolButton->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); + setFixedSize(QSize(static_cast(m_buttonSize), static_cast(m_buttonSize))); + m_toolButton->setToolButtonStyle(Qt::ToolButtonIconOnly); + } + break; - case ButtonStyle::eTextOnly: - { - setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed); - m_toolButton->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum); - setFixedSize( QSize(QWIDGETSIZE_MAX,QWIDGETSIZE_MAX) ); - m_toolButton->setToolButtonStyle(Qt::ToolButtonTextOnly); - layout()->setSizeConstraint( QLayout::SetDefaultConstraint ); - } break; + case ButtonStyle::eTextOnly: { + setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed); + m_toolButton->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum); + setFixedSize(QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX)); + m_toolButton->setToolButtonStyle(Qt::ToolButtonTextOnly); + layout()->setSizeConstraint(QLayout::SetDefaultConstraint); + } + break; - case ButtonStyle::eTextNextToIcon: - { - setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed); - m_toolButton->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum); - setFixedSize( QSize(QWIDGETSIZE_MAX,QWIDGETSIZE_MAX) ); - m_toolButton->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); - layout()->setSizeConstraint( QLayout::SetDefaultConstraint ); - } break; - - default: break; - } - -} + case ButtonStyle::eTextNextToIcon: { + setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed); + m_toolButton->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum); + setFixedSize(QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX)); + m_toolButton->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); + layout()->setSizeConstraint(QLayout::SetDefaultConstraint); + } + break; + default: + break; + } +} void LtsDragIcon::initButton() { - setMinimumSize(static_cast(m_buttonSize), static_cast(m_buttonSize)); + setMinimumSize(static_cast(m_buttonSize), static_cast(m_buttonSize)); - delete m_toolButton; - delete m_lay; - delete layout(); + delete m_toolButton; + delete m_lay; + delete layout(); - m_toolButton = new LtsToolButton(this); - m_toolButton->setDraggable(m_isDraggable); - connect(m_toolButton, &LtsToolButton::clicked, this, &LtsDragIcon::clicked); - connect(m_toolButton, &LtsToolButton::toggled, this, &LtsDragIcon::toggled); - connect(m_toolButton, &LtsToolButton::newDropEvent, this, &LtsDragIcon::newDropEvent); - connect(m_toolButton, &LtsToolButton::dropSuc, this, &LtsDragIcon::dropSuc); + m_toolButton = new LtsToolButton(this); + m_toolButton->setDraggable(m_isDraggable); + connect(m_toolButton, &LtsToolButton::clicked, this, &LtsDragIcon::clicked); + connect(m_toolButton, &LtsToolButton::toggled, this, &LtsDragIcon::toggled); + connect(m_toolButton, &LtsToolButton::newDropEvent, this, &LtsDragIcon::newDropEvent); + connect(m_toolButton, &LtsToolButton::dropSuc, this, &LtsDragIcon::dropSuc); - m_toolButton->setIcon(modifyIcon(m_icon)); - m_toolButton->setText(m_text); - generateToolTip(); - m_toolButton->setIconSize(QSize(static_cast(m_buttonSize), static_cast(m_buttonSize))); + m_toolButton->setIcon(modifyIcon(m_icon)); + m_toolButton->setText(m_text); + generateToolTip(); + m_toolButton->setIconSize(QSize(static_cast(m_buttonSize), static_cast(m_buttonSize))); + QVBoxLayout* box = new QVBoxLayout(this); + box->setContentsMargins(0, 0, 0, 0); + box->setSpacing(0); + box->addWidget(m_toolButton); - QVBoxLayout *box = new QVBoxLayout(this); - box->setMargin(0); - box->setSpacing(0); - box->addWidget(m_toolButton); + this->setLayout(box); - this->setLayout(box); + m_toolButton->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); - m_toolButton->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); + if (m_forceFixedSize) + { + m_toolButton->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); + setFixedSize(QSize(static_cast(m_buttonSize), static_cast(m_buttonSize))); + } + else + { + m_toolButton->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum); + setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum); + } - if (m_forceFixedSize) - { - m_toolButton->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); - setFixedSize(QSize(static_cast(m_buttonSize), static_cast(m_buttonSize))); - } - else - { - m_toolButton->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum); - setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum); - } - - setStyleToButton(); + setStyleToButton(); } -void LtsDragIcon::addToButtonGroup(QButtonGroup *btnGrp, int btnGrpId) +void LtsDragIcon::addToButtonGroup(QButtonGroup* btnGrp, int btnGrpId) { - btnGrp->addButton(m_toolButton, btnGrpId); + btnGrp->addButton(m_toolButton, btnGrpId); } - -void LtsDragIcon::setIcon(const QIcon &icon) +void LtsDragIcon::setIcon(const QIcon& icon) { - m_icon = icon; - (m_toolButton) ? m_toolButton->setIcon(modifyIcon(m_icon)) : initButton(); + m_icon = icon; + (m_toolButton) ? m_toolButton->setIcon(modifyIcon(m_icon)) : initButton(); } - -void LtsDragIcon::setMenu(QMenu *menu) +void LtsDragIcon::setMenu(QMenu* menu) { - if (nullptr == m_toolButton) - initButton(); - m_toolButton->setMenu(menu); + if (nullptr == m_toolButton) + initButton(); + m_toolButton->setMenu(menu); } -QMenu *LtsDragIcon::menu() const +QMenu* LtsDragIcon::menu() const { - if (nullptr == m_toolButton) - return nullptr; + if (nullptr == m_toolButton) + return nullptr; - return m_toolButton->menu(); + return m_toolButton->menu(); } - -void LtsDragIcon::setText(const QString &text) +void LtsDragIcon::setText(const QString& text) { - m_text = text; - (m_toolButton) ? generateToolTip() : initButton(); + m_text = text; + (m_toolButton) ? generateToolTip() : initButton(); } -void LtsDragIcon::setContext(const QString &context) +void LtsDragIcon::setContext(const QString& context) { - m_context = context; - generateToolTip(); + m_context = context; + generateToolTip(); } void LtsDragIcon::generateToolTip() { - if (!m_toolButton || m_text.isEmpty()) - return; + if (!m_toolButton || m_text.isEmpty()) + return; - QString text(m_text); - if (!m_context.isEmpty()) - text.prepend(m_context + QLatin1String(" - ")); + QString text(m_text); + if (!m_context.isEmpty()) + text.prepend(m_context + QLatin1String(" - ")); - m_toolButton->setText(m_text); - m_toolButton->setToolTip(text); + m_toolButton->setText(m_text); + m_toolButton->setToolTip(text); } bool LtsDragIcon::isCheckable() { - return (m_toolButton) ? m_toolButton->isCheckable() : false; + return (m_toolButton) ? m_toolButton->isCheckable() : false; } void LtsDragIcon::setDraggable(bool draggable) { - m_isDraggable = draggable; - m_toolButton->setDraggable(m_isDraggable); + m_isDraggable = draggable; + m_toolButton->setDraggable(m_isDraggable); } void LtsDragIcon::setCheckable(bool checkable) { - m_toolButton->setCheckable(checkable); + m_toolButton->setCheckable(checkable); } bool LtsDragIcon::isChecked() const { - return (m_toolButton) ? m_toolButton->isChecked() : false; + return (m_toolButton) ? m_toolButton->isChecked() : false; } void LtsDragIcon::setChecked(bool checked) { - if (nullptr == m_toolButton) - initButton(); - m_toolButton->setChecked(checked); + if (nullptr == m_toolButton) + initButton(); + m_toolButton->setChecked(checked); } void LtsDragIcon::setSameWidgetDrop(bool drop) { - if (nullptr == m_toolButton) - initButton(); - m_toolButton->setSameWidgetDrop(drop); + if (nullptr == m_toolButton) + initButton(); + m_toolButton->setSameWidgetDrop(drop); } bool LtsDragIcon::sameWidgetDrop() const { - if (nullptr == m_toolButton) - return false; - return m_toolButton->sameWidgetDrop(); + if (nullptr == m_toolButton) + return false; + return m_toolButton->sameWidgetDrop(); } -void LtsDragIcon::addMimeData(const QString &mimeType, const QByteArray &data) +void LtsDragIcon::addMimeData(const QString& mimeType, const QByteArray& data) { - if (nullptr == m_toolButton) - initButton(); - m_toolButton->addMimeData(mimeType, data); + if (nullptr == m_toolButton) + initButton(); + m_toolButton->addMimeData(mimeType, data); } -bool LtsDragIcon::removeMimeData(const QString &mimeType) +bool LtsDragIcon::removeMimeData(const QString& mimeType) { - if (nullptr == m_toolButton) - initButton(); - return m_toolButton->removeMimeData(mimeType); + if (nullptr == m_toolButton) + initButton(); + return m_toolButton->removeMimeData(mimeType); } void LtsDragIcon::removeAllMimeData() { - if (nullptr == m_toolButton) - initButton(); - m_toolButton->removeAllMimeData(); + if (nullptr == m_toolButton) + initButton(); + m_toolButton->removeAllMimeData(); } void LtsDragIcon::setAcceptDrops(bool on) { - if (nullptr == m_toolButton) - initButton(); - m_toolButton->setAcceptDrops(on); + if (nullptr == m_toolButton) + initButton(); + m_toolButton->setAcceptDrops(on); } -void LtsDragIcon::dragEnterEvent(QDragEnterEvent *e) +void LtsDragIcon::dragEnterEvent(QDragEnterEvent* e) { - if (m_toolButton) - m_toolButton->dragEnterEvent(e); + if (m_toolButton) + m_toolButton->dragEnterEvent(e); } -void LtsDragIcon::dropEvent(QDropEvent *e) + +void LtsDragIcon::dropEvent(QDropEvent* e) { - QWidget::dropEvent(e); + QWidget::dropEvent(e); } void LtsDragIcon::setButtonStyle(ButtonStyle style) { - m_style = style; - setStyleToButton(); + m_style = style; + setStyleToButton(); } void LtsDragIcon::setIconSize(ButtonSize buttonSize) { - m_buttonSize = buttonSize; - (m_toolButton) ? m_toolButton->setIconSize(QSize(static_cast(m_buttonSize), static_cast(m_buttonSize))) : initButton(); + m_buttonSize = buttonSize; + (m_toolButton) ? m_toolButton->setIconSize(QSize(static_cast(m_buttonSize), static_cast(m_buttonSize))) + : initButton(); } void LtsDragIcon::setForceFixedSize(bool force) { - m_forceFixedSize = force; - initButton(); + m_forceFixedSize = force; + initButton(); } void LtsDragIcon::setButtonVisible(bool visible) { - if (nullptr == m_toolButton) - initButton(); - m_toolButton->setVisible(visible); + if (nullptr == m_toolButton) + initButton(); + m_toolButton->setVisible(visible); } bool LtsDragIcon::buttonVisible() const { - if (nullptr == m_toolButton) - return false; - return m_toolButton->isVisible(); + if (nullptr == m_toolButton) + return false; + return m_toolButton->isVisible(); } -void LtsDragIcon::setAction(QAction *action) +void LtsDragIcon::setAction(QAction* action) { - QIcon icon = action->icon(); - if(!icon.isNull()) - m_icon = icon; - m_toolButton->setDefaultAction(action); - this->setObjectName(action->objectName()); + QIcon icon = action->icon(); + if (!icon.isNull()) + m_icon = icon; + m_toolButton->setDefaultAction(action); + this->setObjectName(action->objectName()); } -void LtsDragIcon::changeEvent(QEvent *event) +void LtsDragIcon::changeEvent(QEvent* event) { - if (event->type() == QEvent::EnabledChange) - emit enabledChanged(isEnabled()); + if (event->type() == QEvent::EnabledChange) + emit enabledChanged(isEnabled()); } - - -void LtsToolButton::mousePressEvent(QMouseEvent *event) +void LtsToolButton::mousePressEvent(QMouseEvent* event) { - if (event->button() == Qt::LeftButton) - m_startPos = event->pos(); - QToolButton::mousePressEvent(event); + if (event->button() == Qt::LeftButton) + m_startPos = event->pos(); + QToolButton::mousePressEvent(event); } - -void LtsToolButton::mouseReleaseEvent(QMouseEvent *event) +void LtsToolButton::mouseReleaseEvent(QMouseEvent* event) { - QToolButton::mouseReleaseEvent(event); + QToolButton::mouseReleaseEvent(event); } -void LtsToolButton::mouseMoveEvent(QMouseEvent *event) +void LtsToolButton::mouseMoveEvent(QMouseEvent* event) { - if (!m_isDraggable) - return; - if (event->buttons() & Qt::LeftButton) { - int distance = (event->pos() - m_startPos).manhattanLength(); - if (distance >= 5) + if (!m_isDraggable) + return; + if (event->buttons() & Qt::LeftButton) { - this->setDown(false); - performDrag(event); - return; + int distance = (event->pos() - m_startPos).manhattanLength(); + if (distance >= 5) + { + this->setDown(false); + performDrag(event); + return; + } } - } - QToolButton::mouseMoveEvent(event); + QToolButton::mouseMoveEvent(event); } -void LtsToolButton::performDrag(QMouseEvent *) +void LtsToolButton::performDrag(QMouseEvent*) { - QWidget *item = this; - if (item) - { - - LtsDragIcon *dragIcon = nullptr; - QString name; - - while (dragIcon == nullptr) + QWidget* item = this; + if (item) { - if ((!item->objectName().isEmpty()) && (name.isNull())) - { - name = item->objectName(); - } - item = item->parentWidget(); - if (nullptr == item) return; - dragIcon = dynamic_cast(item); + + LtsDragIcon* dragIcon = nullptr; + QString name; + + while (dragIcon == nullptr) + { + if ((!item->objectName().isEmpty()) && (name.isNull())) + { + name = item->objectName(); + } + item = item->parentWidget(); + if (nullptr == item) + return; + dragIcon = dynamic_cast(item); + } + QMimeData* mimeData = new QMimeData(); + mimeData->setText(name); + for (auto it = m_mimeData.cbegin(); it != m_mimeData.cend(); ++it) + mimeData->setData(it.key(), it.value()); + + if (dragIcon->dropHandlerKey() != 0L) + { + QByteArray data = QByteArray(QByteArray::number(dragIcon->dropHandlerKey())); + mimeData->setData(QLatin1String("DropHandlerPtr"), data); + } + + QDrag* drag = new QDrag(item); + + drag->setMimeData(mimeData); + + QAction* action = defaultAction(); + + if ((action) && (dragIcon->showDragIcon())) + { + drag->setPixmap(action->icon().pixmap(16, 16)); + } + else + { + drag->setPixmap(dragIcon->icon().pixmap(16, 16)); + } + Qt::DropAction drop = drag->exec(Qt::CopyAction | Qt::MoveAction); + if (drop == Qt::MoveAction || drop == Qt::CopyAction) + emit dropSuc(); } - QMimeData *mimeData = new QMimeData(); - mimeData->setText(name); - for(auto it = m_mimeData.cbegin(); it != m_mimeData.cend(); ++it) - mimeData->setData(it.key(), it.value()); - - - if (dragIcon->dropHandlerKey() != 0L) - { - QByteArray data = QByteArray(QByteArray::number(dragIcon->dropHandlerKey())); - mimeData->setData(QLatin1String("DropHandlerPtr"),data); - } - - QDrag *drag = new QDrag(item); - - drag->setMimeData(mimeData); - - QAction *action = defaultAction(); - - if ((action) && (dragIcon->showDragIcon())) - { - drag->setPixmap(action->icon().pixmap(16,16) ); - } - else - { - drag->setPixmap(dragIcon->icon().pixmap(16, 16)); - } - Qt::DropAction drop = drag->exec(Qt::CopyAction | Qt::MoveAction); - if (drop == Qt::MoveAction || drop == Qt::CopyAction ) - emit dropSuc(); - } - } -void LtsToolButton::dragEnterEvent(QDragEnterEvent *event) +void LtsToolButton::dragEnterEvent(QDragEnterEvent* event) { - QWidget *source = - qobject_cast(event->source()); - if (source && source != this) { - event->setDropAction(Qt::MoveAction); - event->accept(); - } - QWidget::dragEnterEvent(event); + QWidget* source = qobject_cast(event->source()); + if (source && source != this) + { + event->setDropAction(Qt::MoveAction); + event->accept(); + } + QWidget::dragEnterEvent(event); } -void LtsToolButton::addMimeData(const QString &mimeType, const QByteArray &data) +void LtsToolButton::addMimeData(const QString& mimeType, const QByteArray& data) { - m_mimeData.insert(mimeType,data); + m_mimeData.insert(mimeType, data); } -bool LtsToolButton::removeMimeData(const QString &mimeType) +bool LtsToolButton::removeMimeData(const QString& mimeType) { - return (m_mimeData.remove(mimeType) > 0); + return (m_mimeData.remove(mimeType) > 0); } #define SIZE 40 -QIcon LtsDragIcon::modifyIcon(const QIcon &icon) +QIcon LtsDragIcon::modifyIcon(const QIcon& icon) { - if (m_modification.isEmpty()) - return icon; + if (m_modification.isEmpty()) + return icon; - QPixmap iconImage(icon.pixmap(SIZE*0.8, SIZE*0.8)); - QPainter painter(&iconImage); + QPixmap iconImage(icon.pixmap(SIZE * 0.8, SIZE * 0.8)); + QPainter painter(&iconImage); - painter.save(); - painter.setRenderHints(QPainter::TextAntialiasing | QPainter::Antialiasing | QPainter::HighQualityAntialiasing | QPainter::SmoothPixmapTransform); - painter.setBrush(QColor("red")); - painter.setPen(QPen(QColor("red"), 3)); + painter.save(); + painter.setRenderHints(QPainter::TextAntialiasing | QPainter::Antialiasing | QPainter::SmoothPixmapTransform); + painter.setBrush(QColor("red")); + painter.setPen(QPen(QColor("red"), 3)); - QFont f; - f.setFamily(QStringLiteral("Monospace")); - f.setPointSize(12); - f.setBold(true); - painter.setFont(f); + QFont f; + f.setFamily(QStringLiteral("Monospace")); + f.setPointSize(12); + f.setBold(true); + painter.setFont(f); - painter.drawText(QRect(0, 0, 28, 28), m_modification); - painter.restore(); + painter.drawText(QRect(0, 0, 28, 28), m_modification); + painter.restore(); - return iconImage; + return iconImage; } -} - +} // namespace LtsWidgets #include "lts_drag_icon.moc" - diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_frameless_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_frameless_dialog.cpp old mode 100755 new mode 100644 index e26e9451d..8c38ebe1b --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_frameless_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_frameless_dialog.cpp @@ -1,153 +1,126 @@ - #include "lts_frameless_dialog.h" #include #include -#include -#include #include -#include #include -#include +#include #include +#include +#include #include - namespace LtsWidgets { -LtsFramelessDialog::LtsFramelessDialog(QWidget *parent, const Behaviour &behaviour) - : QDialog(parent) +LtsFramelessDialog::LtsFramelessDialog(QWidget* parent, const Behaviour& behaviour) : QDialog(parent) { - - - Qt::WindowFlags wf; - - switch (behaviour) - { - case Behaviour::Modal: + Qt::WindowFlags wf; + + switch (behaviour) { + case Behaviour::Modal: { #ifndef TABLET_MODE - setModal(true); - wf |= Qt::Dialog; + setModal(true); + wf |= Qt::Dialog; #else - wf |= Qt::Window; + wf |= Qt::Window; #endif - wf |= Qt::WindowStaysOnTopHint; - break; + wf |= Qt::WindowStaysOnTopHint; + break; + } + + case Behaviour::Popup: + wf |= Qt::Popup; + break; } - case Behaviour::Popup: - wf |= Qt::Popup; - break; - } + setWindowFlags(wf); - setWindowFlags(wf); - - - QTimer *t = new QTimer(this); - t->setInterval(250); - connect(t, &QTimer::timeout, - this, [this]() - { - - - - QSize s = size(); - setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, s, screenRectFromPoint(QCursor::pos()))); - }); - + QTimer* t = new QTimer(this); + t->setInterval(250); + connect(t, &QTimer::timeout, this, [this]() { + QSize s = size(); + setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, s, screenRectFromPoint(QCursor::pos()))); + }); } +LtsFramelessDialog::~LtsFramelessDialog() {} -LtsFramelessDialog::~LtsFramelessDialog() +QRect LtsFramelessDialog::screenRectFromPoint(const QPoint& pos) const { + const auto screens = QGuiApplication::screens(); + for (QScreen* screen : screens) + { + QRect s = screen->geometry().adjusted(-50, -50, 50, 50); + bool contains = s.contains(pos); + + if (contains) + return screen->geometry(); + } + + return QRect(); } - -QRect LtsFramelessDialog::screenRectFromPoint(const QPoint &pos) const +void LtsFramelessDialog::showEvent(QShowEvent* event) { - const auto screens = QGuiApplication::screens(); - for (QScreen *screen : screens) - { - QRect s = screen->geometry().adjusted(-50, -50, 50, 50); - - bool contains = s.contains(pos); - - - - - - if (contains) - return screen->geometry(); - } - - return QRect(); -} - - -void LtsFramelessDialog::showEvent(QShowEvent *event) -{ - QDialog::showEvent(event); - QTimer::singleShot(0, this, &LtsFramelessDialog::onUpdateGeometry); - + QDialog::showEvent(event); + QTimer::singleShot(0, this, &LtsFramelessDialog::onUpdateGeometry); #ifdef TABLET_MODE - QList scrollWidgets = findChildren(); + QList scrollWidgets = findChildren(); - for (auto i = scrollWidgets.begin(); i != scrollWidgets.end(); ++i) - { - QWidget *widget = *i; + for (auto i = scrollWidgets.begin(); i != scrollWidgets.end(); ++i) + { + QWidget* widget = *i; - QVariant isConst = widget->property("const"); - if (isConst.isValid() && isConst.toBool()) - continue; + QVariant isConst = widget->property("const"); + if (isConst.isValid() && isConst.toBool()) + continue; - addTouchScroll(widget); - } + addTouchScroll(widget); + } #endif } - -void LtsFramelessDialog::addTouchScroll(QWidget *widget) +void LtsFramelessDialog::addTouchScroll(QWidget* widget) { - if (!widget) - return; - widget->setAttribute(Qt::WA_AcceptTouchEvents); + if (!widget) + return; + widget->setAttribute(Qt::WA_AcceptTouchEvents); - QScrollArea *sca = qobject_cast(widget); - if (sca) - { - QScroller::grabGesture(sca->viewport(), QScroller::LeftMouseButtonGesture); - return; - } + QScrollArea* sca = qobject_cast(widget); + if (sca) + { + QScroller::grabGesture(sca->viewport(), QScroller::LeftMouseButtonGesture); + return; + } } - void LtsFramelessDialog::onUpdateGeometry() { - QRect r; - QWidget *p = parentWidget(); + QRect r; + QWidget* p = parentWidget(); - if (p) - { - QWidget *window = p->window(); - QPoint global = window->mapToGlobal(QPoint(0,0)); - QSize size = window->size(); + if (p) + { + QWidget* window = p->window(); + QPoint global = window->mapToGlobal(QPoint(0, 0)); + QSize size = window->size(); - r = QRect(global, size); - } - else - { - r = QGuiApplication::primaryScreen()->geometry(); - } + r = QRect(global, size); + } + else + { + r = QGuiApplication::primaryScreen()->geometry(); + } - QSize s = size(); - setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, s, r)); + QSize s = size(); + setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, s, r)); } -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_grid_layout.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_grid_layout.cpp old mode 100755 new mode 100644 index edd0479d9..d12c1d700 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_grid_layout.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_grid_layout.cpp @@ -1,129 +1,122 @@ - #include "lts_grid_layout.h" -#include + #include +#include namespace LtsWidgets { -LtsGridLayout::LtsGridLayout(LtsWidgets::ButtonSize buttonSize, QWidget *parent, int maxColumn) - : QGridLayout(parent) - , m_buttonSize(buttonSize) - , m_defaultMaxColumn(maxColumn) - , m_maxColumn(maxColumn) - , m_colSize(0) - , m_autoSize(maxColumn < 0) +LtsGridLayout::LtsGridLayout(LtsWidgets::ButtonSize buttonSize, QWidget* parent, int maxColumn) + : QGridLayout(parent), m_buttonSize(buttonSize), m_defaultMaxColumn(maxColumn), m_maxColumn(maxColumn), + m_colSize(0), m_autoSize(maxColumn < 0) { - setSizeConstraint(SizeConstraint::SetNoConstraint); - - setVerticalSpacing(1); - setMargin(0); + setSizeConstraint(SizeConstraint::SetNoConstraint); + + setVerticalSpacing(1); + setContentsMargins(0, 0, 0, 0); } -void LtsGridLayout::add_widget(QWidget *widget) +void LtsGridLayout::add_widget(QWidget* widget) { - for (auto it = m_widgetList.cbegin(); it != m_widgetList.cend(); ++it) - { - if (*it == widget) - return; - } - connect(widget, &QWidget::destroyed, this, &LtsGridLayout::onWidgetDestroyed); - addWidgetInternal(widget); - m_widgetList.push_back(widget); + for (auto it = m_widgetList.cbegin(); it != m_widgetList.cend(); ++it) + { + if (*it == widget) + return; + } + connect(widget, &QWidget::destroyed, this, &LtsGridLayout::onWidgetDestroyed); + addWidgetInternal(widget); + m_widgetList.push_back(widget); } void LtsGridLayout::setAutoSize(bool enable) { - m_autoSize = enable; - if (m_autoSize == false) - setMaxColumn(1); - else - { - m_maxColumn = -1; - m_oldSize = QSize(); - m_oldGeo = QRect(); - QResizeEvent e(sizeHint(), sizeHint()); - onParentResize(&e); - setGeometry(QRect(0, 0, sizeHint().width(), sizeHint().height())); - } + m_autoSize = enable; + if (m_autoSize == false) + setMaxColumn(1); + else + { + m_maxColumn = -1; + m_oldSize = QSize(); + m_oldGeo = QRect(); + QResizeEvent e(sizeHint(), sizeHint()); + onParentResize(&e); + setGeometry(QRect(0, 0, sizeHint().width(), sizeHint().height())); + } } void LtsGridLayout::setMaxColumn(int max) { - m_maxColumn = max; - m_defaultMaxColumn = max; + m_maxColumn = max; + m_defaultMaxColumn = max; - - m_colSize = 0; + m_colSize = 0; - for (QWidget *wid : std::as_const(m_widgetList)) - removeWidget(wid); - - for (QWidget *wid : std::as_const(m_widgetList)) - addWidgetInternal(wid); + for (QWidget* wid : std::as_const(m_widgetList)) + removeWidget(wid); + for (QWidget* wid : std::as_const(m_widgetList)) + addWidgetInternal(wid); } -void LtsGridLayout::addWidgetInternal(QWidget *widget) +void LtsGridLayout::addWidgetInternal(QWidget* widget) { - int current_row = 0; - int current_column = 0; + int current_row = 0; + int current_column = 0; - while (QLayoutItem *item = itemAtPosition(current_row, current_column)) - { - if (!item->widget()) + while (QLayoutItem* item = itemAtPosition(current_row, current_column)) { - removeItem(item); - continue; + if (!item->widget()) + { + removeItem(item); + continue; + } + + if (current_column == (m_maxColumn - 1)) + { + current_column = 0; + ++current_row; + } + else + ++current_column; } - if (current_column == (m_maxColumn - 1)) - { - current_column = 0; - ++current_row; - } - else - ++current_column; - } + if (current_row == 0) + m_colSize += 1; - if (current_row == 0) - m_colSize += 1; - - QGridLayout::addWidget(widget, current_row, current_column); + QGridLayout::addWidget(widget, current_row, current_column); } - -void LtsGridLayout::onParentResize(QResizeEvent *e) +void LtsGridLayout::onParentResize(QResizeEvent* e) { - if (m_autoSize && m_oldSize != e->size()) - { - bool bigger = (e->size().width() > m_oldSize.width()); - m_oldSize = e->size(); - int newWidth = m_oldSize.width(); - int maxIconsInRow = newWidth / (static_cast(m_buttonSize) + 4); + if (m_autoSize && m_oldSize != e->size()) + { + bool bigger = (e->size().width() > m_oldSize.width()); + m_oldSize = e->size(); + int newWidth = m_oldSize.width(); + int maxIconsInRow = newWidth / (static_cast(m_buttonSize) + 4); - if (!bigger && newWidth <= (static_cast(m_buttonSize)*m_colSize - static_cast(m_buttonSize) / 2)) - maxIconsInRow--; - if (m_maxColumn != maxIconsInRow) - setMaxColumn(maxIconsInRow); - } + if (!bigger && newWidth <= (static_cast(m_buttonSize) * m_colSize - static_cast(m_buttonSize) / 2)) + maxIconsInRow--; + if (m_maxColumn != maxIconsInRow) + setMaxColumn(maxIconsInRow); + } } void LtsGridLayout::onWidgetDestroyed() { - QWidget *s = qobject_cast(sender()); - for (auto it = m_widgetList.begin(); it != m_widgetList.end(); ++it) - { - if (*it == s) + QWidget* s = qobject_cast(sender()); + for (auto it = m_widgetList.begin(); it != m_widgetList.end(); ++it) { - QGridLayout::removeWidget(s); - m_widgetList.erase(it); - setMaxColumn(m_maxColumn); - break; + if (*it == s) + { + QGridLayout::removeWidget(s); + m_widgetList.erase(it); + setMaxColumn(m_maxColumn); + break; + } } - } } -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_height_plot_widget.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_height_plot_widget.cpp old mode 100755 new mode 100644 index 2c6f882ec..4e6785d41 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_height_plot_widget.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_height_plot_widget.cpp @@ -1,621 +1,583 @@ - #include "lts_height_plot_widget.h" +#include #include #include #include #include -#include - #include - -static inline double getLength(const QPointF &p1, const QPointF &p2) +static inline double getLength(const QPointF& p1, const QPointF& p2) { - const double x = p1.x() - p2.x(); - const double y = p1.y() - p2.y(); - return sqrt(x * x + y * y); + const double x = p1.x() - p2.x(); + const double y = p1.y() - p2.y(); + return sqrt(x * x + y * y); } class LtsHeightPlotWidget::Private { -public: - Private() - : m_length(0) - , m_minElevation(0) - , m_maxElevation(0) - , m_nullX(0) - , m_nullY(0) - , m_scaleX(0) - , m_scaleY(0) - , m_fillBrush(Qt::gray) - , m_axisPen(Qt::black) - , m_mousePosPen(Qt::blue) - , m_markerPen(Qt::magenta) - , iPositionHint(1) - { - m_axisPen.setWidth(1); - m_viewLinePen.setWidth(1); - m_textFont.setPixelSize(10); - m_markerPen.setWidth(2); - m_markerPen.setCapStyle(Qt::RoundCap); - m_mousePosPen.setStyle(Qt::DashDotDotLine); - m_viewLinePen.setStyle(Qt::DashLine); - } - void clearPixmap(); + public: + Private() + : m_length(0), m_minElevation(0), m_maxElevation(0), m_nullX(0), m_nullY(0), m_scaleX(0), m_scaleY(0), + m_fillBrush(Qt::gray), m_axisPen(Qt::black), m_mousePosPen(Qt::blue), m_markerPen(Qt::magenta), + iPositionHint(1) + { + m_axisPen.setWidth(1); + m_viewLinePen.setWidth(1); + m_textFont.setPixelSize(10); + m_markerPen.setWidth(2); + m_markerPen.setCapStyle(Qt::RoundCap); + m_mousePosPen.setStyle(Qt::DashDotDotLine); + m_viewLinePen.setStyle(Qt::DashLine); + } - double getDataHeight(double pos) const; - QPointF getDataPos(double pos) const; - int findDataPointIdx(const QPointF &point) const; - void clear(); - void recalcData(); - void setData(const QVector > &data); - void setMarks(const QVector &data); - void resize(const QSize &newSize); - void repaint(); - void paintLines(QPainter &p) const; + void clearPixmap(); - QVector< QPair< QPointF, double > > m_data; - QVector< QPointF > m_marks; - QVector< QPair< double, double > > m_heightList; + double getDataHeight(double pos) const; + QPointF getDataPos(double pos) const; + int findDataPointIdx(const QPointF& point) const; + void clear(); + void recalcData(); + void setData(const QVector>& data); + void setMarks(const QVector& data); + void resize(const QSize& newSize); + void repaint(); + void paintLines(QPainter& p) const; - double m_length; - double m_minElevation; - double m_maxElevation; - double m_nullX; - double m_nullY; - double m_scaleX; - double m_scaleY; - QPainterPath m_drawPoints; - QBrush m_fillBrush; - QPen m_axisPen; - QPen m_viewLinePen; - QPen m_mousePosPen; - QPen m_markerPen; - QFont m_textFont; - QPointF m_mousePos; - QPointF m_mouseLeftClickPos; + QVector> m_data; + QVector m_marks; + QVector> m_heightList; - QSize m_curSize; - QTransform m_trans1; - QTransform m_trans2; - QTransform m_transInverted; - QTransform m_transCombined; + double m_length; + double m_minElevation; + double m_maxElevation; + double m_nullX; + double m_nullY; + double m_scaleX; + double m_scaleY; + QPainterPath m_drawPoints; + QBrush m_fillBrush; + QPen m_axisPen; + QPen m_viewLinePen; + QPen m_mousePosPen; + QPen m_markerPen; + QFont m_textFont; + QPointF m_mousePos; + QPointF m_mouseLeftClickPos; - QPixmap m_pixmap; + QSize m_curSize; + QTransform m_trans1; + QTransform m_trans2; + QTransform m_transInverted; + QTransform m_transCombined; - mutable int iPositionHint; + QPixmap m_pixmap; + + mutable int iPositionHint; }; double LtsHeightPlotWidget::Private::getDataHeight(double pos) const { - if (m_heightList.count() <= 1) - return 0; - - if (pos <= 0.) - return m_heightList[0].second; - if (pos >= m_heightList[m_heightList.count() - 1].first) - return m_heightList[m_heightList.count() - 1].second; + if (m_heightList.count() <= 1) + return 0; - if (iPositionHint >= m_heightList.size()) - iPositionHint = 1; - if (pos <= m_heightList[iPositionHint].first) - { - while (iPositionHint > 1 && pos <= m_heightList[iPositionHint - 1].first) - --iPositionHint; - } - else - { - while (iPositionHint < m_heightList.count() - 1 && pos > m_heightList[iPositionHint].first) - ++iPositionHint; - } - const int iFound = iPositionHint; - - const double x = m_heightList[iFound].first - m_heightList[iFound - 1].first; - const double y = m_heightList[iFound].second - m_heightList[iFound - 1].second; - const double m = y / x; - const double n = m_heightList[iFound].second - m * m_heightList[iFound].first; - return m * pos + n; + if (pos <= 0.) + return m_heightList[0].second; + if (pos >= m_heightList[m_heightList.count() - 1].first) + return m_heightList[m_heightList.count() - 1].second; + + if (iPositionHint >= m_heightList.size()) + iPositionHint = 1; + if (pos <= m_heightList[iPositionHint].first) + { + while (iPositionHint > 1 && pos <= m_heightList[iPositionHint - 1].first) + --iPositionHint; + } + else + { + while (iPositionHint < m_heightList.count() - 1 && pos > m_heightList[iPositionHint].first) + ++iPositionHint; + } + const int iFound = iPositionHint; + + const double x = m_heightList[iFound].first - m_heightList[iFound - 1].first; + const double y = m_heightList[iFound].second - m_heightList[iFound - 1].second; + const double m = y / x; + const double n = m_heightList[iFound].second - m * m_heightList[iFound].first; + return m * pos + n; } QPointF LtsHeightPlotWidget::Private::getDataPos(double pos) const { - if (m_heightList.count() <= 1) - return QPointF(); - - if (pos <= 0.) - return m_data[0].first; - if (pos >= m_heightList[m_heightList.count() - 1].first) - return m_data[m_heightList.count() - 1].first; + if (m_heightList.count() <= 1) + return QPointF(); - if (pos <= m_heightList[iPositionHint].first) - { - while (iPositionHint > 1 && pos <= m_heightList[iPositionHint - 1].first) - --iPositionHint; - } - else - { - while (iPositionHint < m_heightList.count() - 1 && pos > m_heightList[iPositionHint].first) - ++iPositionHint; - } - const int iFound = iPositionHint; - - const double diff = m_heightList[iFound].first - m_heightList[iFound - 1].first; - double percentile = (pos - m_heightList[iFound - 1].first) / diff; - const QPointF &p1 = m_data[iFound - 1].first; - const QPointF p2 = m_data[iFound].first - m_data[iFound - 1].first; - return QPointF(p1.x() + p2.x() * percentile, p1.y() + p2.y() * percentile); + if (pos <= 0.) + return m_data[0].first; + if (pos >= m_heightList[m_heightList.count() - 1].first) + return m_data[m_heightList.count() - 1].first; + + if (pos <= m_heightList[iPositionHint].first) + { + while (iPositionHint > 1 && pos <= m_heightList[iPositionHint - 1].first) + --iPositionHint; + } + else + { + while (iPositionHint < m_heightList.count() - 1 && pos > m_heightList[iPositionHint].first) + ++iPositionHint; + } + const int iFound = iPositionHint; + + const double diff = m_heightList[iFound].first - m_heightList[iFound - 1].first; + double percentile = (pos - m_heightList[iFound - 1].first) / diff; + const QPointF& p1 = m_data[iFound - 1].first; + const QPointF p2 = m_data[iFound].first - m_data[iFound - 1].first; + return QPointF(p1.x() + p2.x() * percentile, p1.y() + p2.y() * percentile); } -int LtsHeightPlotWidget::Private::findDataPointIdx(const QPointF &point) const +int LtsHeightPlotWidget::Private::findDataPointIdx(const QPointF& point) const { - for (int i = 0; i < m_heightList.count() - 1; ++i) - { - - const double x = m_data[i + 1].first.x() - m_data[i].first.x(); - const double y = m_data[i + 1].first.y() - m_data[i].first.y(); - const double m = y / x; - const double n = m_data[i].first.y() - m * m_data[i].first.x(); - - - const double yRes = m * point.x() + n; - if (fabs(yRes - point.y()) < 1.) + for (int i = 0; i < m_heightList.count() - 1; ++i) { - - const double len = getLength(m_data[ i ].first, point); - if (len <= m_heightList[i].first) - return i; + + const double x = m_data[i + 1].first.x() - m_data[i].first.x(); + const double y = m_data[i + 1].first.y() - m_data[i].first.y(); + const double m = y / x; + const double n = m_data[i].first.y() - m * m_data[i].first.x(); + + const double yRes = m * point.x() + n; + if (fabs(yRes - point.y()) < 1.) + { + + const double len = getLength(m_data[i].first, point); + if (len <= m_heightList[i].first) + return i; + } } - } - return -1; + return -1; } void LtsHeightPlotWidget::Private::clear() { - m_data.clear(); - m_marks.clear(); - m_length = 0; - m_minElevation = 0; - m_maxElevation = 0; - m_scaleX = 0; - m_scaleY = 0; - m_drawPoints = QPainterPath(); - m_heightList.clear(); - m_curSize = QSize(); + m_data.clear(); + m_marks.clear(); + m_length = 0; + m_minElevation = 0; + m_maxElevation = 0; + m_scaleX = 0; + m_scaleY = 0; + m_drawPoints = QPainterPath(); + m_heightList.clear(); + m_curSize = QSize(); - iPositionHint = 1; + iPositionHint = 1; } void LtsHeightPlotWidget::Private::clearPixmap() { - m_pixmap = QPixmap(); + m_pixmap = QPixmap(); } inline double log5(double x) { - return log10(x) / log10(5.); + return log10(x) / log10(5.); } void LtsHeightPlotWidget::Private::recalcData() { - m_heightList.clear(); - m_drawPoints = QPainterPath(); + m_heightList.clear(); + m_drawPoints = QPainterPath(); - if (m_data.isEmpty()) - { + if (m_data.isEmpty()) + { + clear(); + return; + } + + double length = 0; + double minElevation = m_data.at(0).second; + double maxElevation = minElevation; + + for (int i = 1; i < m_data.count(); ++i) + { + length += getLength(m_data.at(i - 1).first, m_data.at(i).first); + minElevation = std::min(minElevation, m_data.at(i).second); + maxElevation = std::max(maxElevation, m_data.at(i).second); + } + + if (minElevation < -10000.0) + minElevation = -10000.0; + if (maxElevation < -10000.0) + maxElevation = -10000.0; + + if (minElevation > 10000.0) + minElevation = 10000.0; + if (maxElevation > 10000.0) + maxElevation = 10000.0; + + if (qFuzzyCompare(minElevation, maxElevation)) + { + minElevation -= 1.0; + maxElevation += 1.0; + } + + double n2 = pow(5, floor(log5(fabs(minElevation))) - 1); + if (qFuzzyIsNull(n2)) + n2 = 0.1; + + m_minElevation = lrint(floor(minElevation / n2) * n2); + m_maxElevation = lrint(ceil(maxElevation / n2) * n2); + m_scaleY = pow(10, floor(log10(m_maxElevation - m_minElevation)) - 1); + if (m_scaleY < 0.1) + m_scaleY = 0.1; + m_nullY = m_minElevation; + if (m_minElevation < 0 && m_maxElevation > 0) + m_nullY = 0; + + const double n = pow(10, floor(log10(length))) / 2; + m_length = lrint(ceil(length / n) * n); + m_scaleX = pow(10, floor(log10(length)) - 1); + if (m_scaleX < 0.1) + m_scaleX = 0.1; + m_nullX = 0; + + double len = 0; + m_drawPoints.moveTo(len, m_data.at(0).second); + m_heightList.append(QPair(len, m_data.at(0).second)); + for (int i = 1; i < m_data.count(); ++i) + { + len += getLength(m_data.at(i - 1).first, m_data.at(i).first); + m_drawPoints.lineTo(len, m_data.at(i).second); + + m_heightList.append(QPair(len, m_data.at(i).second)); + } + m_drawPoints.lineTo(len, m_minElevation); + m_drawPoints.lineTo(0, m_minElevation); + m_drawPoints.setFillRule(Qt::WindingFill); +} + +void LtsHeightPlotWidget::Private::setData(const QVector>& data) +{ + if (data.isEmpty()) + { + clear(); + return; + } + QSize tmp = m_curSize; clear(); - return; - } - double length = 0; - double minElevation = m_data.at(0).second; - double maxElevation = minElevation; + m_data = data; - for (int i = 1; i < m_data.count(); ++i) - { - length += getLength(m_data.at(i - 1).first, m_data.at(i).first); - minElevation = std::min(minElevation, m_data.at(i).second); - maxElevation = std::max(maxElevation, m_data.at(i).second); - } - - if (minElevation < -10000.0) minElevation = -10000.0; - if (maxElevation < -10000.0) maxElevation = -10000.0; - - if (minElevation > 10000.0) minElevation = 10000.0; - if (maxElevation > 10000.0) maxElevation = 10000.0; - - if (qFuzzyCompare(minElevation, maxElevation)) - { - minElevation -= 1.0; - maxElevation += 1.0; - } - - - double n2 = pow(5, floor(log5(fabs(minElevation))) - 1); - if (qFuzzyIsNull(n2)) - n2 = 0.1; - - m_minElevation = lrint(floor(minElevation / n2) * n2); - m_maxElevation = lrint(ceil(maxElevation / n2) * n2); - m_scaleY = pow(10, floor(log10(m_maxElevation - m_minElevation)) - 1); - if (m_scaleY < 0.1) - m_scaleY = 0.1; - m_nullY = m_minElevation; - if (m_minElevation < 0 && m_maxElevation > 0) - m_nullY = 0; - - - const double n = pow(10, floor(log10(length))) / 2; - m_length = lrint(ceil(length / n) * n); - m_scaleX = pow(10, floor(log10(length)) - 1); - if (m_scaleX < 0.1) - m_scaleX = 0.1; - m_nullX = 0; - - double len = 0; - m_drawPoints.moveTo(len, m_data.at(0).second); - m_heightList.append(QPair(len, m_data.at(0).second)); - for (int i = 1; i < m_data.count(); ++i) - { - len += getLength(m_data.at(i - 1).first, m_data.at(i).first); - m_drawPoints.lineTo(len, m_data.at(i).second); - - m_heightList.append(QPair(len, m_data.at(i).second)); - - } - m_drawPoints.lineTo(len, m_minElevation); - m_drawPoints.lineTo(0, m_minElevation); - m_drawPoints.setFillRule(Qt::WindingFill); + recalcData(); + resize(tmp); } -void LtsHeightPlotWidget::Private::setData(const QVector< QPair< QPointF, double > > &data) +void LtsHeightPlotWidget::Private::setMarks(const QVector& data) { - if (data.isEmpty()) - { - clear(); - return; - } - QSize tmp = m_curSize; - clear(); + m_marks = data; - m_data = data; - - recalcData(); - resize(tmp); + recalcData(); + repaint(); } - -void LtsHeightPlotWidget::Private::setMarks(const QVector< QPointF > &data) +void LtsHeightPlotWidget::Private::resize(const QSize& newSize) { - m_marks = data; + if (newSize == m_curSize) + return; - recalcData(); - repaint(); -} + m_curSize = newSize; -void LtsHeightPlotWidget::Private::resize(const QSize &newSize) -{ - if (newSize == m_curSize) - return; + const int border = 25; + const double width = m_curSize.width(); + const double height = m_curSize.height(); - m_curSize = newSize; + const double minY = m_minElevation - m_scaleY; + const double maxY = m_maxElevation + m_scaleY; + const double wertebereichY = maxY - minY; - const int border = 25; - const double width = m_curSize.width(); - const double height = m_curSize.height(); + const double minX = 0 - m_scaleX; + const double maxX = m_length + m_scaleX; + const double wertebereichX = maxX - minX; - const double minY = m_minElevation - m_scaleY; - const double maxY = m_maxElevation + m_scaleY; - const double wertebereichY = maxY - minY; + m_trans1.reset(); + m_trans2.reset(); - const double minX = 0 - m_scaleX; - const double maxX = m_length + m_scaleX; - const double wertebereichX = maxX - minX; + m_trans1.translate(10, height); - m_trans1.reset(); - m_trans2.reset(); + m_trans1.scale(1, -1); - - m_trans1.translate(10, height); - - m_trans1.scale(1, -1); - - m_trans1.translate(border, border); - - m_trans1.scale(1, -1); + m_trans1.translate(border, border); - - m_trans2.scale((width - 2 * border) / (wertebereichX), - (height - 2 * border) / (wertebereichY)); - - m_trans2.translate(0, minY); - - m_trans2.scale(1, -1); + m_trans1.scale(1, -1); - m_transInverted = m_trans1.inverted() * m_trans2.inverted(); - m_transCombined = m_trans2 * m_trans1; + m_trans2.scale((width - 2 * border) / (wertebereichX), (height - 2 * border) / (wertebereichY)); - repaint(); + m_trans2.translate(0, minY); + + m_trans2.scale(1, -1); + + m_transInverted = m_trans1.inverted() * m_trans2.inverted(); + m_transCombined = m_trans2 * m_trans1; + + repaint(); } void LtsHeightPlotWidget::Private::repaint() { - if (!m_curSize.isValid()) - return; - if (!m_heightList.count()) - return; + if (!m_curSize.isValid()) + return; + if (!m_heightList.count()) + return; - QImage img(m_curSize, QImage::Format_ARGB32); - img.fill(Qt::transparent); - QPainter p(&img); - const QPainter::RenderHints hints = QPainter::HighQualityAntialiasing | - QPainter::SmoothPixmapTransform | - QPainter::TextAntialiasing | - QPainter::Antialiasing; - p.setRenderHints(hints); - p.setTransform(m_trans1); + QImage img(m_curSize, QImage::Format_ARGB32); + img.fill(Qt::transparent); + QPainter p(&img); + const QPainter::RenderHints hints = + QPainter::SmoothPixmapTransform | QPainter::TextAntialiasing | QPainter::Antialiasing; + p.setRenderHints(hints); + p.setTransform(m_trans1); - - p.setPen(QPen(m_fillBrush, 0.1)); - p.setBrush(m_fillBrush); - p.drawPath(m_trans2.map(m_drawPoints)); - p.setRenderHint(QPainter::Antialiasing, false); + p.setPen(QPen(m_fillBrush, 0.1)); + p.setBrush(m_fillBrush); + p.drawPath(m_trans2.map(m_drawPoints)); + p.setRenderHint(QPainter::Antialiasing, false); - - p.setPen(m_markerPen); - for (int i = 0; i < m_marks.count(); ++i) - { - int posIdx = findDataPointIdx(m_marks.at(i)); - if (posIdx < 0) - continue; - double len = getLength(m_data.at(posIdx).first, m_marks.at(i)); - len += m_heightList.at(posIdx).first; - const double height = getDataHeight(len); - const QLineF l(len, m_minElevation, len, height); - - - p.drawLine(m_trans2.map(l)); - } - - - p.setPen(m_axisPen); - p.setFont(m_textFont); - - - p.drawLine(m_trans2.map(QPointF(m_nullX, m_minElevation - m_scaleY)), - m_trans2.map(QPointF(m_nullX, m_maxElevation + m_scaleY))); - - - for (double i = m_minElevation; i <= m_maxElevation; i += m_scaleY) - { - const qreal y = m_trans2.map(QPointF(0, i)).y(); - p.drawLine(QLineF(-2, y, 2, y)); - } - - - for (double i = m_minElevation; i <= m_maxElevation; i += m_scaleY * 5) - { - const qreal y = m_trans2.map(QPointF(0, i)).y(); - p.drawLine(QLineF(-4, y, 4, y)); - } - - QFontMetricsF fm(m_textFont); - for (double i = m_minElevation; i <= m_maxElevation; i += m_scaleY * 5) - { - if (qFuzzyCompare(i, m_nullY)) - continue; - const qreal y = m_trans2.map(QPointF(m_nullX, i)).y(); - const QPointF p1(-20, y); - const QString str = QString::number(i); - QRectF r = fm.boundingRect(str); - r.setWidth(fm.width(str)); - r.moveTo(p1.x() - r.width() / 2., p1.y() - r.height() / 2.); - p.drawText(r, str, Qt::AlignHCenter | Qt::AlignVCenter); - } - - - p.drawLine(m_trans2.map(QPointF(-m_scaleX, m_nullY)), - m_trans2.map(QPointF(m_scaleX + m_length, m_nullY))); - - - for (double i = m_scaleX; i <= m_length; i += m_scaleX) - { - const QPointF point = m_trans2.map(QPointF(i, m_nullY)); - p.drawLine(QLineF(point.x(), point.y() - 2, point.x(), point.y() + 2)); - } - - - for (double i = 0; i <= m_length; i += m_scaleX * 5) - { - const QPointF point = m_trans2.map(QPointF(i, m_nullY)); - p.drawLine(QLineF(point.x(), point.y() - 4, point.x(), point.y() + 4)); - } - - for (double i = 0; i <= m_length; i += m_scaleX * 5) - { - if (qFuzzyCompare(i, m_nullX)) - continue; - const QPointF point = m_trans2.map(QPointF(i, m_nullY)); - const QPointF p1(point.x(), point.y() + 15); - const QString str = QString::number(i); - QRectF r = fm.boundingRect(str); - r.setWidth(fm.width(str)); - r.moveTo(p1.x() - r.width() / 2., p1.y() - r.height() / 2.); - p.drawText(r, str, Qt::AlignHCenter | Qt::AlignVCenter); - } - p.end(); - m_pixmap = QPixmap::fromImage(img); -} - -void LtsHeightPlotWidget::Private::paintLines(QPainter &p) const -{ - if (m_heightList.count() > 0) - { - - QPointF pos = m_mousePos; - if (pos.x() < 0) - pos.setX(0); - if (pos.x() > m_heightList.at(m_heightList.count() - 1).first) - pos.setX(m_heightList.at(m_heightList.count() - 1).first); - - - - const double curHeight = getDataHeight(pos.x()); - p.setPen(m_mousePosPen); - p.drawLine(m_transCombined.map(QLineF(m_nullX, curHeight, pos.x(), curHeight))); - p.drawLine(m_transCombined.map(QLineF(pos.x(), m_nullY, pos.x(), curHeight))); - - - if (!m_mouseLeftClickPos.isNull()) + p.setPen(m_markerPen); + for (int i = 0; i < m_marks.count(); ++i) { - const double y = curHeight > pos.y() ? curHeight : pos.y(); - p.drawLine(m_transCombined.map(QLineF(m_nullX, y, pos.x(), y))); - p.drawLine(m_transCombined.map(QLineF(pos.x(), m_nullY, pos.x(), y))); + int posIdx = findDataPointIdx(m_marks.at(i)); + if (posIdx < 0) + continue; + double len = getLength(m_data.at(posIdx).first, m_marks.at(i)); + len += m_heightList.at(posIdx).first; + const double height = getDataHeight(len); + const QLineF l(len, m_minElevation, len, height); - p.setPen(m_viewLinePen); - const QPointF &c = m_mouseLeftClickPos; - p.drawLine(m_transCombined.map(QLineF(m_nullX, c.y(), c.x(), c.y()))); - p.drawLine(m_transCombined.map(QLineF(c.x(), m_nullY, c.x(), c.y()))); - - - const QLineF line(m_mouseLeftClickPos, QPointF(pos.x(), y)); - p.drawLine(m_transCombined.map(line)); + p.drawLine(m_trans2.map(l)); } - } + + p.setPen(m_axisPen); + p.setFont(m_textFont); + + p.drawLine(m_trans2.map(QPointF(m_nullX, m_minElevation - m_scaleY)), + m_trans2.map(QPointF(m_nullX, m_maxElevation + m_scaleY))); + + for (double i = m_minElevation; i <= m_maxElevation; i += m_scaleY) + { + const qreal y = m_trans2.map(QPointF(0, i)).y(); + p.drawLine(QLineF(-2, y, 2, y)); + } + + for (double i = m_minElevation; i <= m_maxElevation; i += m_scaleY * 5) + { + const qreal y = m_trans2.map(QPointF(0, i)).y(); + p.drawLine(QLineF(-4, y, 4, y)); + } + + QFontMetricsF fm(m_textFont); + for (double i = m_minElevation; i <= m_maxElevation; i += m_scaleY * 5) + { + if (qFuzzyCompare(i, m_nullY)) + continue; + const qreal y = m_trans2.map(QPointF(m_nullX, i)).y(); + const QPointF p1(-20, y); + const QString str = QString::number(i); + QRectF r = fm.boundingRect(str); + r.setWidth(fm.horizontalAdvance(str)); + r.moveTo(p1.x() - r.width() / 2., p1.y() - r.height() / 2.); + p.drawText(r, str, Qt::AlignHCenter | Qt::AlignVCenter); + } + + p.drawLine(m_trans2.map(QPointF(-m_scaleX, m_nullY)), m_trans2.map(QPointF(m_scaleX + m_length, m_nullY))); + + for (double i = m_scaleX; i <= m_length; i += m_scaleX) + { + const QPointF point = m_trans2.map(QPointF(i, m_nullY)); + p.drawLine(QLineF(point.x(), point.y() - 2, point.x(), point.y() + 2)); + } + + for (double i = 0; i <= m_length; i += m_scaleX * 5) + { + const QPointF point = m_trans2.map(QPointF(i, m_nullY)); + p.drawLine(QLineF(point.x(), point.y() - 4, point.x(), point.y() + 4)); + } + + for (double i = 0; i <= m_length; i += m_scaleX * 5) + { + if (qFuzzyCompare(i, m_nullX)) + continue; + const QPointF point = m_trans2.map(QPointF(i, m_nullY)); + const QPointF p1(point.x(), point.y() + 15); + const QString str = QString::number(i); + QRectF r = fm.boundingRect(str); + r.setWidth(fm.horizontalAdvance(str)); + r.moveTo(p1.x() - r.width() / 2., p1.y() - r.height() / 2.); + p.drawText(r, str, Qt::AlignHCenter | Qt::AlignVCenter); + } + p.end(); + m_pixmap = QPixmap::fromImage(img); } -LtsHeightPlotWidget::LtsHeightPlotWidget(QWidget *parent) - : QWidget(parent) - , d(new Private) +void LtsHeightPlotWidget::Private::paintLines(QPainter& p) const { - setMinimumSize(300, 300); - resize(size()); - setMouseTracking(true); + if (m_heightList.count() > 0) + { + + QPointF pos = m_mousePos; + if (pos.x() < 0) + pos.setX(0); + if (pos.x() > m_heightList.at(m_heightList.count() - 1).first) + pos.setX(m_heightList.at(m_heightList.count() - 1).first); + + const double curHeight = getDataHeight(pos.x()); + p.setPen(m_mousePosPen); + p.drawLine(m_transCombined.map(QLineF(m_nullX, curHeight, pos.x(), curHeight))); + p.drawLine(m_transCombined.map(QLineF(pos.x(), m_nullY, pos.x(), curHeight))); + + if (!m_mouseLeftClickPos.isNull()) + { + const double y = curHeight > pos.y() ? curHeight : pos.y(); + p.drawLine(m_transCombined.map(QLineF(m_nullX, y, pos.x(), y))); + p.drawLine(m_transCombined.map(QLineF(pos.x(), m_nullY, pos.x(), y))); + + p.setPen(m_viewLinePen); + const QPointF& c = m_mouseLeftClickPos; + p.drawLine(m_transCombined.map(QLineF(m_nullX, c.y(), c.x(), c.y()))); + p.drawLine(m_transCombined.map(QLineF(c.x(), m_nullY, c.x(), c.y()))); + + const QLineF line(m_mouseLeftClickPos, QPointF(pos.x(), y)); + p.drawLine(m_transCombined.map(line)); + } + } +} + +LtsHeightPlotWidget::LtsHeightPlotWidget(QWidget* parent) : QWidget(parent), d(new Private) +{ + setMinimumSize(300, 300); + resize(size()); + setMouseTracking(true); } LtsHeightPlotWidget::~LtsHeightPlotWidget() { - delete d; + delete d; } void LtsHeightPlotWidget::clearView() { - d->clearPixmap(); - update(); -} - -void LtsHeightPlotWidget::setData(const QVector< QPair< QPointF, double > > &data) -{ - d->setData(data); - update(); -} - -void LtsHeightPlotWidget::setMarks(const QVector &data) -{ - d->setMarks(data); -} - -void LtsHeightPlotWidget::setBackgroundBrush(const QBrush &brush) -{ - QPalette pal = palette(); - pal.setBrush(QPalette::Background, brush); - setPalette(pal); -} - -void LtsHeightPlotWidget::setTextFont(const QFont &f) -{ - d->m_textFont = f; - d->repaint(); -} - -void LtsHeightPlotWidget::setAxisPen(const QPen &pen) -{ - d->m_axisPen = pen; - d->repaint(); -} - -void LtsHeightPlotWidget::setPositionPen(const QPen &pen) -{ - d->m_mousePosPen = pen; -} - -void LtsHeightPlotWidget::setViewLinePen(const QPen &pen) -{ - d->m_viewLinePen = pen; -} - -void LtsHeightPlotWidget::setContourBrush(const QBrush &brush) -{ - d->m_fillBrush = brush; - d->repaint(); -} - -void LtsHeightPlotWidget::setMarkerPen(const QPen &pen) -{ - d->m_markerPen = pen; - d->repaint(); -} - -void LtsHeightPlotWidget::resizeEvent(QResizeEvent *e) -{ - d->resize(size()); - QWidget::resizeEvent(e); -} - -void LtsHeightPlotWidget::paintEvent(QPaintEvent *e) -{ - Q_UNUSED(e); - QPainter p(this); - - const QPainter::RenderHints hints = QPainter::SmoothPixmapTransform | - QPainter::TextAntialiasing | - QPainter::Antialiasing; - p.setRenderHints(hints); - - - p.drawPixmap(0, 0, d->m_pixmap); - - - d->paintLines(p); - p.end(); -} - -void LtsHeightPlotWidget::mouseMoveEvent(QMouseEvent *e) -{ - QWidget::mouseMoveEvent(e); - if (!d->m_heightList.count()) - return; - - const QPointF pos = d->m_transInverted.map(e->localPos()); - emit mousePositionChanged(d->getDataPos(pos.x()), d->getDataHeight(pos.x()), pos.y()); - d->m_mousePos = pos; - update(); -} - -void LtsHeightPlotWidget::mouseReleaseEvent(QMouseEvent *e) -{ - QWidget::mouseReleaseEvent(e); - if (!d->m_heightList.count()) - return; - if (e->button() == Qt::LeftButton) - { - const QPointF &pos = d->m_mousePos; - if (pos.x() < 0) - return; - if (pos.x() > d->m_heightList.at(d->m_heightList.count() - 1).first) - return; - - const double curHeight = d->getDataHeight(pos.x()); - d->m_mouseLeftClickPos = QPointF(pos.x(), curHeight > pos.y() ? curHeight : pos.y()); - emit startLineOfSight(d->getDataPos(pos.x())); - } - else if (e->button() == Qt::RightButton) - { - d->m_mouseLeftClickPos = QPointF(); - emit stopLineOfSight(); + d->clearPixmap(); update(); - } } +void LtsHeightPlotWidget::setData(const QVector>& data) +{ + d->setData(data); + update(); +} + +void LtsHeightPlotWidget::setMarks(const QVector& data) +{ + d->setMarks(data); +} + +void LtsHeightPlotWidget::setBackgroundBrush(const QBrush& brush) +{ + QPalette pal = palette(); + pal.setBrush(QPalette::Window, brush); + setPalette(pal); +} + +void LtsHeightPlotWidget::setTextFont(const QFont& f) +{ + d->m_textFont = f; + d->repaint(); +} + +void LtsHeightPlotWidget::setAxisPen(const QPen& pen) +{ + d->m_axisPen = pen; + d->repaint(); +} + +void LtsHeightPlotWidget::setPositionPen(const QPen& pen) +{ + d->m_mousePosPen = pen; +} + +void LtsHeightPlotWidget::setViewLinePen(const QPen& pen) +{ + d->m_viewLinePen = pen; +} + +void LtsHeightPlotWidget::setContourBrush(const QBrush& brush) +{ + d->m_fillBrush = brush; + d->repaint(); +} + +void LtsHeightPlotWidget::setMarkerPen(const QPen& pen) +{ + d->m_markerPen = pen; + d->repaint(); +} + +void LtsHeightPlotWidget::resizeEvent(QResizeEvent* e) +{ + d->resize(size()); + QWidget::resizeEvent(e); +} + +void LtsHeightPlotWidget::paintEvent(QPaintEvent* e) +{ + Q_UNUSED(e); + QPainter p(this); + + const QPainter::RenderHints hints = + QPainter::SmoothPixmapTransform | QPainter::TextAntialiasing | QPainter::Antialiasing; + p.setRenderHints(hints); + + p.drawPixmap(0, 0, d->m_pixmap); + + d->paintLines(p); + p.end(); +} + +void LtsHeightPlotWidget::mouseMoveEvent(QMouseEvent* e) +{ + QWidget::mouseMoveEvent(e); + if (!d->m_heightList.count()) + return; + + const QPointF pos = d->m_transInverted.map(e->localPos()); + emit mousePositionChanged(d->getDataPos(pos.x()), d->getDataHeight(pos.x()), pos.y()); + d->m_mousePos = pos; + update(); +} + +void LtsHeightPlotWidget::mouseReleaseEvent(QMouseEvent* e) +{ + QWidget::mouseReleaseEvent(e); + if (!d->m_heightList.count()) + return; + if (e->button() == Qt::LeftButton) + { + const QPointF& pos = d->m_mousePos; + if (pos.x() < 0) + return; + if (pos.x() > d->m_heightList.at(d->m_heightList.count() - 1).first) + return; + + const double curHeight = d->getDataHeight(pos.x()); + d->m_mouseLeftClickPos = QPointF(pos.x(), curHeight > pos.y() ? curHeight : pos.y()); + emit startLineOfSight(d->getDataPos(pos.x())); + } + else if (e->button() == Qt::RightButton) + { + d->m_mouseLeftClickPos = QPointF(); + emit stopLineOfSight(); + update(); + } +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_image_editor.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_image_editor.cpp old mode 100755 new mode 100644 index c811a4187..3ec194ef1 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_image_editor.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_image_editor.cpp @@ -1,116 +1,101 @@ - #include "lts_image_editor.h" -#include -#include #include +#include +#include +#include #include #include -#include using namespace LtsWidgets; - -LtsImageEditor::LtsImageEditor(QWidget *parent) - : QWidget(parent) - , m_isHovered(false) - , m_menuEnabled(true) - , m_bDrawOuterRect(true) -{} - - -void LtsImageEditor::setPixmap(const QPixmap &pixmap) +LtsImageEditor::LtsImageEditor(QWidget* parent) + : QWidget(parent), m_isHovered(false), m_menuEnabled(true), m_bDrawOuterRect(true) { - if (pixmap.isNull()) - m_pixmap = QPixmap(QStringLiteral(":style/noimage.png")); - else - m_pixmap = pixmap; - - update(); - emit imageChanged(); } - -void LtsImageEditor::enterEvent(QEvent *) +void LtsImageEditor::setPixmap(const QPixmap& pixmap) { - - m_isHovered = true; - update(); -} + if (pixmap.isNull()) + m_pixmap = QPixmap(QStringLiteral(":style/noimage.png")); + else + m_pixmap = pixmap; - -void LtsImageEditor::leaveEvent(QEvent *) -{ - - m_isHovered = false; - update(); -} - - -bool LtsImageEditor::event(QEvent *event) -{ - if (event->type() == QEvent::MouseButtonPress && m_menuEnabled) - { - emit signalClicked(); - event->accept(); - m_isHovered = false; update(); - return true; - } - - return QWidget::event(event); + emit imageChanged(); } - -void LtsImageEditor::paintEvent(QPaintEvent* event) +void LtsImageEditor::enterEvent(QEnterEvent*) { - QPainter p(this); - - p.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); - QBrush brush = QColor(QStringLiteral("white")); + m_isHovered = true; + update(); +} +void LtsImageEditor::leaveEvent(QEvent*) +{ - if (!m_pixmap.isNull()) - { - if (!(m_isHovered && m_menuEnabled)) + m_isHovered = false; + update(); +} + +bool LtsImageEditor::event(QEvent* event) +{ + if (event->type() == QEvent::MouseButtonPress && m_menuEnabled) { - const QSize s(size()); - const QPixmap pixmap(m_pixmap.scaled(s, Qt::KeepAspectRatio, Qt::SmoothTransformation)); - const int x = qRound((s.width() - pixmap.width()) / 2.); - const int y = qRound((s.height() - pixmap.height()) / 2.); - if (m_bDrawOuterRect) - { - p.setPen(QPen(QColor("gray"), 2)); - p.drawRect(rect()); - } - p.drawPixmap(x, y, pixmap); - event->accept(); - return; + emit signalClicked(); + event->accept(); + m_isHovered = false; + update(); + return true; } - } + return QWidget::event(event); +} - - p.setPen(QPen(QColor("gray"), 2)); - p.setBrush(brush); - p.drawRect(rect()); +void LtsImageEditor::paintEvent(QPaintEvent* event) +{ + QPainter p(this); + p.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); + QBrush brush = QColor(QStringLiteral("white")); - - if (m_isHovered && m_menuEnabled) - { - p.setPen(QPen(QColor(QStringLiteral("gray")), (size().height() / 48 * 2))); + if (!m_pixmap.isNull()) + { + if (!(m_isHovered && m_menuEnabled)) + { + const QSize s(size()); + const QPixmap pixmap(m_pixmap.scaled(s, Qt::KeepAspectRatio, Qt::SmoothTransformation)); + const int x = qRound((s.width() - pixmap.width()) / 2.); + const int y = qRound((s.height() - pixmap.height()) / 2.); + if (m_bDrawOuterRect) + { + p.setPen(QPen(QColor("gray"), 2)); + p.drawRect(rect()); + } + p.drawPixmap(x, y, pixmap); + event->accept(); + return; + } + } - double xc = size().width()/2.012; - double yc = size().height()/2.012; + p.setPen(QPen(QColor("gray"), 2)); + p.setBrush(brush); + p.drawRect(rect()); - p.drawLine(QPointF(xc - (xc/2.01f), yc - (yc/3.01f)), QPointF(xc + (xc/2.02f), yc - (yc/3.02f))); - p.drawLine(QPointF(xc - (xc/2.01f), yc - 0.01f), QPointF(xc + (xc/2.02f), yc - 0)); - p.drawLine(QPointF(xc - (xc/2.01f), yc + (yc/3.01f)), QPointF(xc + (xc/2.02f), yc + (yc/3.02f))); - } + if (m_isHovered && m_menuEnabled) + { + p.setPen(QPen(QColor(QStringLiteral("gray")), (size().height() / 48 * 2))); + + double xc = size().width() / 2.012; + double yc = size().height() / 2.012; + + p.drawLine(QPointF(xc - (xc / 2.01f), yc - (yc / 3.01f)), QPointF(xc + (xc / 2.02f), yc - (yc / 3.02f))); + p.drawLine(QPointF(xc - (xc / 2.01f), yc - 0.01f), QPointF(xc + (xc / 2.02f), yc - 0)); + p.drawLine(QPointF(xc - (xc / 2.01f), yc + (yc / 3.01f)), QPointF(xc + (xc / 2.02f), yc + (yc / 3.02f))); + } - event->accept(); + event->accept(); } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_image_editor.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_image_editor.h old mode 100755 new mode 100644 index 6ed8571fa..c61c677ce --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_image_editor.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_image_editor.h @@ -1,61 +1,68 @@ - #pragma once -#include - #include "ltswidgets_export.h" +#include #include - namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsImageEditor : public QWidget { - Q_OBJECT + Q_OBJECT - Q_PROPERTY(QPixmap pixmap READ pixmap WRITE setPixmap) - Q_PROPERTY(bool menuEnabled READ isMenuEnabled WRITE setMenuEnabled) + Q_PROPERTY(QPixmap pixmap READ pixmap WRITE setPixmap) + Q_PROPERTY(bool menuEnabled READ isMenuEnabled WRITE setMenuEnabled) -public: - explicit LtsImageEditor(QWidget *parent = nullptr); + public: + explicit LtsImageEditor(QWidget* parent = nullptr); - + void setPixmap(const QPixmap& pixmap); - void setPixmap(const QPixmap &pixmap); + QPixmap pixmap() const + { + return m_pixmap; + } - + void setMenuEnabled(bool enabled = true) + { + m_menuEnabled = enabled; + } - QPixmap pixmap() const { return m_pixmap; } + bool isMenuEnabled() const + { + return m_menuEnabled; + } - + void setDrawOuterRect(bool bDraw) + { + m_bDrawOuterRect = bDraw; + } - void setMenuEnabled(bool enabled = true) { m_menuEnabled = enabled; } - bool isMenuEnabled() const { return m_menuEnabled; } + bool drawOuterRect() const + { + return m_bDrawOuterRect; + } - void setDrawOuterRect(bool bDraw) { m_bDrawOuterRect = bDraw; } - bool drawOuterRect() const { return m_bDrawOuterRect; } + protected: + void paintEvent(QPaintEvent* event); + void enterEvent(QEnterEvent*); + void leaveEvent(QEvent*); + bool event(QEvent* event); -protected: - void paintEvent(QPaintEvent *event); - void enterEvent(QEvent *); - void leaveEvent(QEvent *); - bool event(QEvent *event); + private: + QPixmap m_pixmap; + bool m_isHovered; + bool m_menuEnabled; + bool m_bDrawOuterRect; -private: - QPixmap m_pixmap; - bool m_isHovered; - bool m_menuEnabled; - bool m_bDrawOuterRect; + signals: -signals: - + void signalClicked(); - void signalClicked(); - - void imageChanged(); + void imageChanged(); }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_message_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_message_dialog.cpp old mode 100755 new mode 100644 index 144dc54e8..98e001272 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_message_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_message_dialog.cpp @@ -1,133 +1,126 @@ #include "lts_message_dialog.h" + #include "lts_message_dialog_helper.h" #include -#include +#include #include #include -#include - +#include namespace LtsWidgets { namespace LtsMessageDialog { -Button showMessage(QWidget* parent, - const QString& message, - const QString &title, - const Behaviour behaviour, - const Buttons buttons, - const QHash &buttonTexts) +Button showMessage(QWidget* parent, const QString& message, const QString& title, const Behaviour behaviour, + const Buttons buttons, const QHash& buttonTexts) { - static QAtomicInt s_used = 0; + static QAtomicInt s_used = 0; - if (s_used) - qDebug() << "LtsMessageDialog: showMessage called while showMessage is in its Event Loop - do not open more than one Dialog at once !!"; + if (s_used) + qDebug() << "LtsMessageDialog: showMessage called while showMessage is in its Event Loop - do not open more " + "than one Dialog at once !!"; - s_used = 1; + s_used = 1; - LtsMessageDialogHelper *dialog = new LtsMessageDialogHelper(); - Button result = dialog->showMessage(parent, message, title, behaviour, buttons, buttonTexts); - dialog->deleteLater(); + LtsMessageDialogHelper* dialog = new LtsMessageDialogHelper(); + Button result = dialog->showMessage(parent, message, title, behaviour, buttons, buttonTexts); + dialog->deleteLater(); - s_used = 0; + s_used = 0; - return result; + return result; } -Button askApplyDiscardCancel(QWidget *parent) +Button askApplyDiscardCancel(QWidget* parent) { - const QString question = QCoreApplication::translate("LtsDialog", - "
" - "Apply - apply changes and close.
" - "Discard - discard changes and close.
" - "Cancel - do not close."); - const QString title = QCoreApplication::translate("LtsDialog", "Unapplied changes made. Apply the changes?"); - return LtsMessageDialog::showMessage(parent, - question, - title, - Behaviour::Modal, - Button::Apply | Button::Discard | Button::Cancel); + const QString question = QCoreApplication::translate("LtsDialog", "
" + "Apply - apply changes and close.
" + "Discard - discard changes and close.
" + "Cancel - do not close."); + const QString title = QCoreApplication::translate("LtsDialog", "Unapplied changes made. Apply the changes?"); + return LtsMessageDialog::showMessage(parent, question, title, Behaviour::Modal, + Button::Apply | Button::Discard | Button::Cancel); } +} // namespace LtsMessageDialog -} - - - - -LtsMessageDialogNew::LtsMessageDialogNew(QWidget *parent, const QString &message, const QString &title, const Behaviour behaviour, const Buttons buttons, const QHash &buttonTexts, bool deleteOnClose) +LtsMessageDialogNew::LtsMessageDialogNew(QWidget* parent, const QString& message, const QString& title, + const Behaviour behaviour, const Buttons buttons, + const QHash& buttonTexts, bool deleteOnClose) { - m_dialog = new LtsFramelessDialog(parent, behaviour); + m_dialog = new LtsFramelessDialog(parent, behaviour); - if (deleteOnClose) - m_dialog->setAttribute(Qt::WA_DeleteOnClose); + if (deleteOnClose) + m_dialog->setAttribute(Qt::WA_DeleteOnClose); - connect(m_dialog, &LtsFramelessDialog::destroyed, - this, &LtsMessageDialogNew::deleteLater); + connect(m_dialog, &LtsFramelessDialog::destroyed, this, &LtsMessageDialogNew::deleteLater); - QVBoxLayout *mainLayout = new QVBoxLayout(m_dialog); + QVBoxLayout* mainLayout = new QVBoxLayout(m_dialog); - QString text; - if (!title.isEmpty()) - { - text = QStringLiteral("%1

").arg(title); - } + QString text; + if (!title.isEmpty()) + { + text = QStringLiteral("%1

").arg(title); + } - text += message; + text += message; - QLabel *messageLabel = new QLabel(text, m_dialog); - messageLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); - mainLayout->addWidget(messageLabel); + QLabel* messageLabel = new QLabel(text, m_dialog); + messageLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); + mainLayout->addWidget(messageLabel); - QHBoxLayout *buttonLayout = new QHBoxLayout; - buttonLayout->setMargin(0); + QHBoxLayout* buttonLayout = new QHBoxLayout; + buttonLayout->setContentsMargins(0, 0, 0, 0); - - + if (buttons.testFlag(Button::Ok)) + connect(addButton(buttonTexts.value(Button::Ok, tr("Ok")), buttonLayout, m_dialog, Button::Ok, parent), + &QPushButton::clicked, this, &LtsMessageDialogNew::ok); - if (buttons.testFlag(Button::Ok)) - connect(addButton(buttonTexts.value(Button::Ok, tr("Ok")), buttonLayout, m_dialog, Button::Ok, parent), &QPushButton::clicked, this, &LtsMessageDialogNew::ok); + if (buttons.testFlag(Button::Yes)) + connect(addButton(buttonTexts.value(Button::Yes, tr("Yes")), buttonLayout, m_dialog, Button::Yes, parent), + &QPushButton::clicked, this, &LtsMessageDialogNew::yes); - if (buttons.testFlag(Button::Yes)) - connect(addButton(buttonTexts.value(Button::Yes, tr("Yes")), buttonLayout, m_dialog, Button::Yes, parent), &QPushButton::clicked, this, &LtsMessageDialogNew::yes); + if (buttons.testFlag(Button::No)) + connect(addButton(buttonTexts.value(Button::No, tr("No")), buttonLayout, m_dialog, Button::No, parent), + &QPushButton::clicked, this, &LtsMessageDialogNew::no); - if (buttons.testFlag(Button::No)) - connect(addButton(buttonTexts.value(Button::No, tr("No")), buttonLayout, m_dialog, Button::No, parent), &QPushButton::clicked, this, &LtsMessageDialogNew::no); + if (buttons.testFlag(Button::Apply)) + connect(addButton(buttonTexts.value(Button::Apply, tr("Apply")), buttonLayout, m_dialog, Button::Apply, parent), + &QPushButton::clicked, this, &LtsMessageDialogNew::apply); - if (buttons.testFlag(Button::Apply)) - connect(addButton(buttonTexts.value(Button::Apply, tr("Apply")), buttonLayout, m_dialog, Button::Apply, parent), &QPushButton::clicked, this, &LtsMessageDialogNew::apply); + if (buttons.testFlag(Button::Discard)) + connect(addButton(buttonTexts.value(Button::Discard, tr("Discard")), buttonLayout, m_dialog, Button::Discard, + parent), + &QPushButton::clicked, this, &LtsMessageDialogNew::discard); - if (buttons.testFlag(Button::Discard)) - connect(addButton(buttonTexts.value(Button::Discard, tr("Discard")), buttonLayout, m_dialog, Button::Discard, parent), &QPushButton::clicked, this, &LtsMessageDialogNew::discard); + if (buttons.testFlag(Button::Cancel)) + connect( + addButton(buttonTexts.value(Button::Cancel, tr("Cancel")), buttonLayout, m_dialog, Button::Cancel, parent), + &QPushButton::clicked, this, &LtsMessageDialogNew::cancel); - if (buttons.testFlag(Button::Cancel)) - connect(addButton(buttonTexts.value(Button::Cancel, tr("Cancel")), buttonLayout, m_dialog, Button::Cancel, parent), &QPushButton::clicked, this, &LtsMessageDialogNew::cancel); + QWidget* buttonLayoutWidget = new QWidget; + buttonLayoutWidget->setLayout(buttonLayout); - QWidget *buttonLayoutWidget = new QWidget; - buttonLayoutWidget->setLayout(buttonLayout); + mainLayout->addWidget(buttonLayoutWidget); - mainLayout->addWidget(buttonLayoutWidget); - - m_dialog->show(); - m_dialog->raise(); + m_dialog->show(); + m_dialog->raise(); } - -QPushButton* LtsMessageDialogNew::addButton(const QString &text, QHBoxLayout *thatLayout, LtsFramelessDialog *dialog, const Button &button, QWidget *parent) +QPushButton* LtsMessageDialogNew::addButton(const QString& text, QHBoxLayout* thatLayout, LtsFramelessDialog* dialog, + const Button& button, QWidget* parent) { - QPushButton* btn = new QPushButton(text, parent); - connect(btn, &QPushButton::clicked, dialog, &LtsFramelessDialog::accept); - thatLayout->addWidget(btn); + QPushButton* btn = new QPushButton(text, parent); + connect(btn, &QPushButton::clicked, dialog, &LtsFramelessDialog::accept); + thatLayout->addWidget(btn); - if (button == Button::Ok || - button == Button::Cancel) - { - btn->setDefault(true); - } + if (button == Button::Ok || button == Button::Cancel) + { + btn->setDefault(true); + } - return btn; + return btn; } - -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_message_dialog_helper.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_message_dialog_helper.cpp old mode 100755 new mode 100644 index edc56ebf4..e66ffe28a --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_message_dialog_helper.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_message_dialog_helper.cpp @@ -1,155 +1,142 @@ #include "lts_message_dialog_helper.h" -#include -#include +#include #include #include -#include - +#include +#include namespace LtsWidgets { -LtsMessageDialogHelper::LtsMessageDialogHelper(QObject *parent) - : QObject(parent) - , m_result(Button::Cancel) - , m_dialog(nullptr) -{} - - -Button LtsMessageDialogHelper::showMessage(QWidget *parent, - const QString &message, - const QString &title, - Behaviour behaviour, - Buttons buttons, - const QHash &buttonTexts) +LtsMessageDialogHelper::LtsMessageDialogHelper(QObject* parent) + : QObject(parent), m_result(Button::Cancel), m_dialog(nullptr) { - m_dialog = new LtsFramelessDialog(parent, behaviour); - - m_dialog->setAttribute(Qt::WA_DeleteOnClose); - - QVBoxLayout *mainLayout = new QVBoxLayout(m_dialog); - - QString text; - if (!title.isEmpty()) - { - text = QStringLiteral("%1

").arg(title); - } - - text += message; - - QLabel *messageLabel = new QLabel(text, m_dialog); - messageLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); - mainLayout->addWidget(messageLabel); - - QHBoxLayout *buttonLayout = new QHBoxLayout; - buttonLayout->setMargin(0); - - - connect(m_dialog, &LtsFramelessDialog::rejected, this, &LtsMessageDialogHelper::slotCancel); - - if (buttons.testFlag(Button::Ok)) - connect(addButton(buttonTexts.value(Button::Ok, tr("Ok")), buttonLayout, m_dialog, Button::Ok, parent), - &QPushButton::clicked, this, &LtsMessageDialogHelper::slotOkay); - - if (buttons.testFlag(Button::Yes)) - connect(addButton(buttonTexts.value(Button::Yes, tr("Yes")), buttonLayout, m_dialog, Button::Yes, parent), - &QPushButton::clicked, this, &LtsMessageDialogHelper::slotYes); - - if (buttons.testFlag(Button::No)) - connect(addButton(buttonTexts.value(Button::No, tr("No")), buttonLayout, m_dialog, Button::No, parent), - &QPushButton::clicked, this, &LtsMessageDialogHelper::slotNo); - - if (buttons.testFlag(Button::Apply)) - connect(addButton(buttonTexts.value(Button::Apply, tr("Apply")), buttonLayout, m_dialog, Button::Apply, parent), - &QPushButton::clicked, this, &LtsMessageDialogHelper::slotApply); - - if (buttons.testFlag(Button::Discard)) - connect(addButton(buttonTexts.value(Button::Discard, tr("Discard")), buttonLayout, m_dialog, Button::Discard, parent), - &QPushButton::clicked, this, &LtsMessageDialogHelper::slotDiscard); - - if (buttons.testFlag(Button::Cancel)) - connect(addButton(buttonTexts.value(Button::Cancel, tr("Cancel")), buttonLayout, m_dialog, Button::Cancel, parent), - &QPushButton::clicked, this, &LtsMessageDialogHelper::slotCancel); - - QWidget *buttonLayoutWidget = new QWidget; - buttonLayoutWidget->setLayout(buttonLayout); - - mainLayout->addWidget(buttonLayoutWidget); - - m_dialog->show(); - m_dialog->raise(); - - - QEventLoop loop; - connect(this, &LtsMessageDialogHelper::signalQuitEventLoop, &loop, &QEventLoop::quit, Qt::QueuedConnection); - loop.exec(); - - return m_result; } +Button LtsMessageDialogHelper::showMessage(QWidget* parent, const QString& message, const QString& title, + Behaviour behaviour, Buttons buttons, + const QHash& buttonTexts) +{ + m_dialog = new LtsFramelessDialog(parent, behaviour); + + m_dialog->setAttribute(Qt::WA_DeleteOnClose); + + QVBoxLayout* mainLayout = new QVBoxLayout(m_dialog); + + QString text; + if (!title.isEmpty()) + { + text = QStringLiteral("%1

").arg(title); + } + + text += message; + + QLabel* messageLabel = new QLabel(text, m_dialog); + messageLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); + mainLayout->addWidget(messageLabel); + + QHBoxLayout* buttonLayout = new QHBoxLayout; + buttonLayout->setContentsMargins(0, 0, 0, 0); + + connect(m_dialog, &LtsFramelessDialog::rejected, this, &LtsMessageDialogHelper::slotCancel); + + if (buttons.testFlag(Button::Ok)) + connect(addButton(buttonTexts.value(Button::Ok, tr("Ok")), buttonLayout, m_dialog, Button::Ok, parent), + &QPushButton::clicked, this, &LtsMessageDialogHelper::slotOkay); + + if (buttons.testFlag(Button::Yes)) + connect(addButton(buttonTexts.value(Button::Yes, tr("Yes")), buttonLayout, m_dialog, Button::Yes, parent), + &QPushButton::clicked, this, &LtsMessageDialogHelper::slotYes); + + if (buttons.testFlag(Button::No)) + connect(addButton(buttonTexts.value(Button::No, tr("No")), buttonLayout, m_dialog, Button::No, parent), + &QPushButton::clicked, this, &LtsMessageDialogHelper::slotNo); + + if (buttons.testFlag(Button::Apply)) + connect(addButton(buttonTexts.value(Button::Apply, tr("Apply")), buttonLayout, m_dialog, Button::Apply, parent), + &QPushButton::clicked, this, &LtsMessageDialogHelper::slotApply); + + if (buttons.testFlag(Button::Discard)) + connect(addButton(buttonTexts.value(Button::Discard, tr("Discard")), buttonLayout, m_dialog, Button::Discard, + parent), + &QPushButton::clicked, this, &LtsMessageDialogHelper::slotDiscard); + + if (buttons.testFlag(Button::Cancel)) + connect( + addButton(buttonTexts.value(Button::Cancel, tr("Cancel")), buttonLayout, m_dialog, Button::Cancel, parent), + &QPushButton::clicked, this, &LtsMessageDialogHelper::slotCancel); + + QWidget* buttonLayoutWidget = new QWidget; + buttonLayoutWidget->setLayout(buttonLayout); + + mainLayout->addWidget(buttonLayoutWidget); + + m_dialog->show(); + m_dialog->raise(); + + QEventLoop loop; + connect(this, &LtsMessageDialogHelper::signalQuitEventLoop, &loop, &QEventLoop::quit, Qt::QueuedConnection); + loop.exec(); + + return m_result; +} void LtsMessageDialogHelper::slotOkay() { - m_dialog->hide(); - m_result = Button::Ok; - emit signalQuitEventLoop(); + m_dialog->hide(); + m_result = Button::Ok; + emit signalQuitEventLoop(); } - void LtsMessageDialogHelper::slotYes() { - m_dialog->hide(); - m_result = Button::Yes; - emit signalQuitEventLoop(); + m_dialog->hide(); + m_result = Button::Yes; + emit signalQuitEventLoop(); } - void LtsMessageDialogHelper::slotNo() { - m_dialog->hide(); - m_result = Button::No; - emit signalQuitEventLoop(); + m_dialog->hide(); + m_result = Button::No; + emit signalQuitEventLoop(); } - void LtsMessageDialogHelper::slotApply() { - m_dialog->hide(); - m_result = Button::Apply; - emit signalQuitEventLoop(); + m_dialog->hide(); + m_result = Button::Apply; + emit signalQuitEventLoop(); } - void LtsMessageDialogHelper::slotDiscard() { - m_dialog->hide(); - m_result = Button::Discard; - emit signalQuitEventLoop(); + m_dialog->hide(); + m_result = Button::Discard; + emit signalQuitEventLoop(); } - void LtsMessageDialogHelper::slotCancel() { - m_dialog->hide(); - m_result = Button::Cancel; - emit signalQuitEventLoop(); + m_dialog->hide(); + m_result = Button::Cancel; + emit signalQuitEventLoop(); } - -QPushButton* LtsMessageDialogHelper::addButton(const QString &text, QHBoxLayout *thatLayout, LtsFramelessDialog *dialog, const Button &button, QWidget *parent) +QPushButton* LtsMessageDialogHelper::addButton(const QString& text, QHBoxLayout* thatLayout, LtsFramelessDialog* dialog, + const Button& button, QWidget* parent) { - QPushButton* btn = new QPushButton(text, parent); - connect(btn, &QPushButton::clicked, dialog, &LtsFramelessDialog::accept); - thatLayout->addWidget(btn); + QPushButton* btn = new QPushButton(text, parent); + connect(btn, &QPushButton::clicked, dialog, &LtsFramelessDialog::accept); + thatLayout->addWidget(btn); - if (button == Button::Ok || - button == Button::Cancel) - { - btn->setDefault(true); - } + if (button == Button::Ok || button == Button::Cancel) + { + btn->setDefault(true); + } - return btn; + return btn; } -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_multi_range_spinbox.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_multi_range_spinbox.h old mode 100755 new mode 100644 index b39cff581..8f54c4422 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_multi_range_spinbox.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_multi_range_spinbox.h @@ -1,10 +1,10 @@ - #pragma once -#include - #include "ltswidgets_export.h" + +#include +#include #include #include @@ -15,39 +15,37 @@ class LTSWIDGETS_EXPORT LtsMultiRangeSpinBox : public QSpinBox { Q_OBJECT -public: - explicit LtsMultiRangeSpinBox(QWidget *parent = nullptr); + public: + explicit LtsMultiRangeSpinBox(QWidget* parent = nullptr); ~LtsMultiRangeSpinBox() = default; - -public slots: - void setRanges(const QVector> &ranges); + public slots: + void setRanges(const QVector>& ranges); void setRange(int min, int max); void setMinimum(int min); void setMaximum(int max); -protected: - QValidator::State validate(QString &input, int &pos) const override; - void fixup(QString &str) const override; - void focusOutEvent(QFocusEvent *event) override; - void wheelEvent(QWheelEvent *event) override; - void mousePressEvent(QMouseEvent *event) override; - void keyPressEvent(QKeyEvent *event) override; + protected: + QValidator::State validate(QString& input, int& pos) const override; + void fixup(QString& str) const override; + void focusOutEvent(QFocusEvent* event) override; + void wheelEvent(QWheelEvent* event) override; + void mousePressEvent(QMouseEvent* event) override; + void keyPressEvent(QKeyEvent* event) override; -private: - static QVector> sortRanges(const QVector > &ranges); + private: + static QVector> sortRanges(const QVector>& ranges); + + QValidator::State validateAll(QString& input, int& pos); - QValidator::State validateAll(QString &input, int &pos); - int fixupValue(int value) const; int fixupValue(int value, bool higher) const; -private: + + private: QVector> m_rangesList; int m_curVal = minimum(); - QRegExp m_regex; + QRegularExpression m_regex; }; - - -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_notification_box.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_notification_box.cpp old mode 100755 new mode 100644 index f39dbaefd..37610d673 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_notification_box.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_notification_box.cpp @@ -1,198 +1,176 @@ #include "lts_notification_box.h" + #include "ui_lts_notification_box.h" -#include -#include #include #include -#include +#include +#include #include +#include #ifdef NOTIBOX_DEBUG #include #endif - namespace LtsWidgets { const int LtsNotificationBox::margin = 14; -LtsNotificationBox::LtsNotificationBox(QWidget *parent) - : QWidget(parent) - , m_ui(new Ui::NotiBox) +LtsNotificationBox::LtsNotificationBox(QWidget* parent) : QWidget(parent), m_ui(new Ui::NotiBox) { - m_ui->setupUi(this); - m_ui->lblText->setText({}); + m_ui->setupUi(this); + m_ui->lblText->setText({}); - connect(m_ui->lblText, &QLabel::linkActivated, - this, [this](const QString &link) - { - emit signalLinkClicked(link); - }); + connect(m_ui->lblText, &QLabel::linkActivated, this, [this](const QString& link) { emit signalLinkClicked(link); }); - connect(m_ui->tbClose, &QToolButton::clicked, - this, &LtsNotificationBox::signalClose); - connect(m_ui->tbAck, &QToolButton::clicked, - this, &LtsNotificationBox::signalAck); + connect(m_ui->tbClose, &QToolButton::clicked, this, &LtsNotificationBox::signalClose); + connect(m_ui->tbAck, &QToolButton::clicked, this, &LtsNotificationBox::signalAck); - setObjectName(QStringLiteral("NotiBox")); + setObjectName(QStringLiteral("NotiBox")); - QGraphicsDropShadowEffect *shadow = new QGraphicsDropShadowEffect(this); - shadow->setOffset(0, 0); - shadow->setBlurRadius(margin*2); - shadow->setColor(QColor(25, 25, 25)); + QGraphicsDropShadowEffect* shadow = new QGraphicsDropShadowEffect(this); + shadow->setOffset(0, 0); + shadow->setBlurRadius(margin * 2); + shadow->setColor(QColor(25, 25, 25)); - setGraphicsEffect(shadow); + setGraphicsEffect(shadow); } - -void LtsNotificationBox::message(const QString &title, const QString &text, MessageType type) +void LtsNotificationBox::message(const QString& title, const QString& text, MessageType type) { - static QString rgbBaseString(QStringLiteral("%1, %2, %3")); - static QString closeDefault(QStringLiteral("close.svg")); - static QString closeDark(QStringLiteral("close_dark.svg")); - static QString ackDefault(QStringLiteral("ack.svg")); - static QString ackDark(QStringLiteral("ack_dark.svg")); - static QString lightTextColor(QStringLiteral("fbfbfb")); - static QString darkTextColor(QStringLiteral("2c3642")); + static QString rgbBaseString(QStringLiteral("%1, %2, %3")); + static QString closeDefault(QStringLiteral("close.svg")); + static QString closeDark(QStringLiteral("close_dark.svg")); + static QString ackDefault(QStringLiteral("ack.svg")); + static QString ackDark(QStringLiteral("ack_dark.svg")); + static QString lightTextColor(QStringLiteral("fbfbfb")); + static QString darkTextColor(QStringLiteral("2c3642")); - static QColor errorStart(254, 45, 102); - static QColor errorEnd(255, 92, 61); + static QColor errorStart(254, 45, 102); + static QColor errorEnd(255, 92, 61); - static QColor successStart(43, 167, 70); - static QColor successEnd(130, 180, 45); + static QColor successStart(43, 167, 70); + static QColor successEnd(130, 180, 45); - static QColor infoStart(74, 74, 74); - static QColor infoEnd(43, 43, 43); + static QColor infoStart(74, 74, 74); + static QColor infoEnd(43, 43, 43); - static QColor warningStart(253, 151, 4); - static QColor warningEnd(253, 202, 0); + static QColor warningStart(253, 151, 4); + static QColor warningEnd(253, 202, 0); + QColor start; + QColor end; + QString close; + QString closeHover; + QString ack; + QString ackHover; + QString textColor; - QColor start; - QColor end; - QString close; - QString closeHover; - QString ack; - QString ackHover; - QString textColor; - - switch (type) - { - case MessageType::Error: + switch (type) { - start = errorStart; - end = errorEnd; - close = closeDefault; - closeHover = closeDark; - ack = ackDefault; - ackHover = ackDark; - textColor = lightTextColor; - m_ui->lblImage->setPixmap(QPixmap(QStringLiteral(":/error.svg"))); + case MessageType::Error: { + start = errorStart; + end = errorEnd; + close = closeDefault; + closeHover = closeDark; + ack = ackDefault; + ackHover = ackDark; + textColor = lightTextColor; + m_ui->lblImage->setPixmap(QPixmap(QStringLiteral(":/error.svg"))); - break; + break; + } + + case MessageType::Success: { + start = successStart; + end = successEnd; + close = closeDefault; + closeHover = closeDark; + ack = ackDefault; + ackHover = ackDark; + textColor = lightTextColor; + m_ui->lblImage->setPixmap(QPixmap(QStringLiteral(":/success.svg"))); + + break; + } + + case MessageType::Info: { + start = infoStart; + end = infoEnd; + close = closeDefault; + closeHover = closeDark; + ack = ackDefault; + ackHover = ackDark; + textColor = lightTextColor; + m_ui->lblImage->setPixmap(QPixmap(QStringLiteral(":/info.svg"))); + + break; + } + + case MessageType::Warning: { + start = warningStart; + end = warningEnd; + close = closeDark; + closeHover = closeDefault; + ack = ackDark; + ackHover = ackDefault; + textColor = darkTextColor; + m_ui->lblImage->setPixmap(QPixmap(QStringLiteral(":/warning.svg"))); + + break; + } } - case MessageType::Success: - { - start = successStart; - end = successEnd; - close = closeDefault; - closeHover = closeDark; - ack = ackDefault; - ackHover = ackDark; - textColor = lightTextColor; - m_ui->lblImage->setPixmap(QPixmap(QStringLiteral(":/success.svg"))); + QStringList css; - break; - } + css << QStringLiteral("#NotiBox { background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop: 0 rgb(%1), stop: 1 " + "rgb(%2)); border: 1px solid rgb(%3); border-radius: 8px; margin: %4px }") + .arg(rgbBaseString.arg(start.red()).arg(start.green()).arg(start.blue()), + rgbBaseString.arg(end.red()).arg(end.green()).arg(end.blue()), + rgbBaseString.arg(end.red()).arg(end.green()).arg(end.blue())) + .arg(margin); - case MessageType::Info: - { - start = infoStart; - end = infoEnd; - close = closeDefault; - closeHover = closeDark; - ack = ackDefault; - ackHover = ackDark; - textColor = lightTextColor; - m_ui->lblImage->setPixmap(QPixmap(QStringLiteral(":/info.svg"))); + css << QStringLiteral("QToolButton#tbClose { border-image: url(:/%1) 0 0 0 0 stretch stretch; border-width: 0px; " + "background-color: transparent; }") + .arg(close); + css << QStringLiteral("QToolButton#tbClose:hover { border-image: url(:/%1) 0 0 0 0 stretch stretch; border-width: " + "0px; background-color: transparent; }") + .arg(closeHover); - break; - } - - case MessageType::Warning: - { - start = warningStart; - end = warningEnd; - close = closeDark; - closeHover = closeDefault; - ack = ackDark; - ackHover = ackDefault; - textColor = darkTextColor; - m_ui->lblImage->setPixmap(QPixmap(QStringLiteral(":/warning.svg"))); - - break; - } - } - - QStringList css; - - css << QStringLiteral("#NotiBox { background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop: 0 rgb(%1), stop: 1 rgb(%2)); border: 1px solid rgb(%3); border-radius: 8px; margin: %4px }"). - arg(rgbBaseString.arg(start.red()).arg(start.green()).arg(start.blue()), - rgbBaseString.arg(end.red()).arg(end.green()).arg(end.blue()), - rgbBaseString.arg(end.red()).arg(end.green()).arg(end.blue())). - arg(margin); - - css << QStringLiteral("QToolButton#tbClose { border-image: url(:/%1) 0 0 0 0 stretch stretch; border-width: 0px; background-color: transparent; }").arg(close); - css << QStringLiteral("QToolButton#tbClose:hover { border-image: url(:/%1) 0 0 0 0 stretch stretch; border-width: 0px; background-color: transparent; }").arg(closeHover); - - css << QStringLiteral("QToolButton#tbAck { border-image: url(:/%1) 0 0 0 0 stretch stretch; border-width: 0px; background-color: transparent; }").arg(ack); - css << QStringLiteral("QToolButton#tbAck:hover { border-image: url(:/%1) 0 0 0 0 stretch stretch; border-width: 0px; background-color: transparent; }").arg(ackHover); + css << QStringLiteral("QToolButton#tbAck { border-image: url(:/%1) 0 0 0 0 stretch stretch; border-width: 0px; " + "background-color: transparent; }") + .arg(ack); + css << QStringLiteral("QToolButton#tbAck:hover { border-image: url(:/%1) 0 0 0 0 stretch stretch; border-width: " + "0px; background-color: transparent; }") + .arg(ackHover); #ifdef NOTIBOX_DEBUG - qWarning() << "css" << css; + qWarning() << "css" << css; - qWarning() << "exists?" << QFile::exists(QStringLiteral(":/close.svg")); - qWarning() << "exists?" << QFile::exists(QStringLiteral(":/close_dark.svg")); - qWarning() << "exists?" << QFile::exists(QStringLiteral(":/error.svg")); - qWarning() << "exists?" << QFile::exists(QStringLiteral(":/info.svg")); - qWarning() << "exists?" << QFile::exists(QStringLiteral(":/warning.svg")); - qWarning() << "exists?" << QFile::exists(QStringLiteral(":/success.svg")); + qWarning() << "exists?" << QFile::exists(QStringLiteral(":/close.svg")); + qWarning() << "exists?" << QFile::exists(QStringLiteral(":/close_dark.svg")); + qWarning() << "exists?" << QFile::exists(QStringLiteral(":/error.svg")); + qWarning() << "exists?" << QFile::exists(QStringLiteral(":/info.svg")); + qWarning() << "exists?" << QFile::exists(QStringLiteral(":/warning.svg")); + qWarning() << "exists?" << QFile::exists(QStringLiteral(":/success.svg")); #endif - m_ui->lblImage->setStyleSheet(QString()); - setStyleSheet(css.join(QStringLiteral(" "))); + m_ui->lblImage->setStyleSheet(QString()); + setStyleSheet(css.join(QStringLiteral(" "))); - m_ui->lblText->setText(QStringLiteral("

%2

%4

").arg(textColor, title, textColor, text)); + m_ui->lblText->setText( + QStringLiteral("

%2

%4

") + .arg(textColor, title, textColor, text)); - show(); + show(); } - -void LtsNotificationBox::paintEvent(QPaintEvent *) +void LtsNotificationBox::paintEvent(QPaintEvent*) { - QStyleOption opt; - opt.init(this); - QPainter p(this); - style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); + QStyleOption opt; + opt.initFrom(this); + QPainter p(this); + style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); } -} - - - - - - - - - - - - - - - - - - - +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_profile_button.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_profile_button.cpp old mode 100755 new mode 100644 index e29651b58..3ff4711ac --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_profile_button.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_profile_button.cpp @@ -1,133 +1,110 @@ - #include "lts_profile_button.h" +#include +#include +#include #include #include -#include -#include #include #include -#include using namespace LtsWidgets; - -LtsProfileButton::LtsProfileButton(QWidget *parent) - : QWidget(parent) - , m_isHovered(false) - , m_menuEnabled(true) +LtsProfileButton::LtsProfileButton(QWidget* parent) : QWidget(parent), m_isHovered(false), m_menuEnabled(true) { - QSizePolicy qsp = QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); - qsp.setHeightForWidth(true); - setSizePolicy(qsp); + QSizePolicy qsp = QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); + qsp.setHeightForWidth(true); + setSizePolicy(qsp); } - -void LtsProfileButton::setPixmap(const QPixmap &pixmap) +void LtsProfileButton::setPixmap(const QPixmap& pixmap) { - if (pixmap.isNull()) - m_pixmap = QPixmap(QStringLiteral("icon:no_pic.svg")); - else - m_pixmap = pixmap; - - update(); -} - - -void LtsProfileButton::enterEvent(QEvent *event) -{ - - m_isHovered = true; - update(); - QWidget::enterEvent(event); -} - - -void LtsProfileButton::leaveEvent(QEvent *event) -{ - - m_isHovered = false; - update(); - QWidget::leaveEvent(event); -} - - -bool LtsProfileButton::event(QEvent *event) -{ - if (event->type() == QEvent::MouseButtonPress && m_menuEnabled) - { - emit signalClicked(); - event->accept(); + if (pixmap.isNull()) + m_pixmap = QPixmap(QStringLiteral("icon:no_pic.svg")); + else + m_pixmap = pixmap; update(); - return true; - } - - return QWidget::event(event); } - -void LtsProfileButton::paintEvent(QPaintEvent* event) +void LtsProfileButton::enterEvent(QEvent* event) { - QPainter p(this); - p.save(); - int minSize; - QPointF center; - minSize = height() > width() ? width() : height(); - center = QPointF(width() / 2.0, height() / 2.0); - - - - p.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); - - - QPixmap pixmap(minSize, minSize); - pixmap.fill(Qt::white); + m_isHovered = true; + update(); + QWidget::enterEvent(static_cast(event)); +} + +void LtsProfileButton::leaveEvent(QEvent* event) +{ + + m_isHovered = false; + update(); + QWidget::leaveEvent(event); +} + +bool LtsProfileButton::event(QEvent* event) +{ + if (event->type() == QEvent::MouseButtonPress && m_menuEnabled) + { + emit signalClicked(); + event->accept(); - if (!m_pixmap.isNull()) - { - if (!(m_isHovered && m_menuEnabled)) - { - pixmap = m_pixmap.scaled(minSize, minSize, Qt::KeepAspectRatioByExpanding); + update(); + return true; } - } + return QWidget::event(event); +} +void LtsProfileButton::paintEvent(QPaintEvent* event) +{ + QPainter p(this); + p.save(); - QPainterPath path; - path.addEllipse(center, - minSize / 2.0 - 4, - minSize / 2.0 - 4); - p.setClipPath(path); - p.drawPixmap(center - QPointF(minSize/2.0,minSize/2.0),pixmap); + int minSize; + QPointF center; + minSize = height() > width() ? width() : height(); + center = QPointF(width() / 2.0, height() / 2.0); + p.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); + QPixmap pixmap(minSize, minSize); + pixmap.fill(Qt::white); - - p.setPen(QPen(QColor("gray"), 2)); - p.drawEllipse(center, - minSize / 2.0 - 4, - minSize / 2.0 - 4); + if (!m_pixmap.isNull()) + { + if (!(m_isHovered && m_menuEnabled)) + { + pixmap = m_pixmap.scaled(minSize, minSize, Qt::KeepAspectRatioByExpanding); + } + } + QPainterPath path; + path.addEllipse(center, minSize / 2.0 - 4, minSize / 2.0 - 4); + p.setClipPath(path); + p.drawPixmap(center - QPointF(minSize / 2.0, minSize / 2.0), pixmap); - - if (m_isHovered && m_menuEnabled) - { - p.setPen(QPen(QColor(QStringLiteral("gray")), (minSize / 48 * 2))); + p.setPen(QPen(QColor("gray"), 2)); + p.drawEllipse(center, minSize / 2.0 - 4, minSize / 2.0 - 4); - double xc = size().width()/2.012; - double yc = size().height()/2.012; - double diff = minSize/2.012; + if (m_isHovered && m_menuEnabled) + { + p.setPen(QPen(QColor(QStringLiteral("gray")), (minSize / 48 * 2))); - p.drawLine(QPointF(xc - (diff/2.01f), yc - (diff/3.01f)), QPointF(xc + (diff/2.02f), yc - (diff/3.02f))); - p.drawLine(QPointF(xc - (diff/2.01f), yc - 0.01f), QPointF(xc + (diff/2.02f), yc - 0)); - p.drawLine(QPointF(xc - (diff/2.01f), yc + (diff/3.01f)), QPointF(xc + (diff/2.02f), yc + (diff/3.02f))); - } + double xc = size().width() / 2.012; + double yc = size().height() / 2.012; + double diff = minSize / 2.012; + p.drawLine(QPointF(xc - (diff / 2.01f), yc - (diff / 3.01f)), + QPointF(xc + (diff / 2.02f), yc - (diff / 3.02f))); + p.drawLine(QPointF(xc - (diff / 2.01f), yc - 0.01f), QPointF(xc + (diff / 2.02f), yc - 0)); + p.drawLine(QPointF(xc - (diff / 2.01f), yc + (diff / 3.01f)), + QPointF(xc + (diff / 2.02f), yc + (diff / 3.02f))); + } - event->accept(); - p.restore(); + event->accept(); + p.restore(); } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_widget.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_widget.cpp old mode 100755 new mode 100644 index a866a1310..e205c1d84 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_widget.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_widget.cpp @@ -1,894 +1,803 @@ - #include "lts_tab_widget.h" + #include "lts_tab_bar.h" #include #include #include #include -#include +#include +#include +#include #include -#include +#include +#include +#include +#include #include #include -#include -#include -#include #include -#include -#include -#include #include -#include +#include +#include +#include #include -#include +#include namespace LtsWidgets { -LtsTabWidget::LtsTabWidget(QWidget *parent, bool isSecondary) - : QTabWidget(parent) - , m_tabbar(nullptr) - , m_hasSubTabs(false) - , m_isSecondary(isSecondary) - , m_mainSplitterState(QByteArray()) +LtsTabWidget::LtsTabWidget(QWidget* parent, bool isSecondary) + : QTabWidget(parent), m_tabbar(nullptr), m_hasSubTabs(false), m_isSecondary(isSecondary), + m_mainSplitterState(QByteArray()) { - setDocumentMode(true); - setMinimumSize(200, 100); - setSizePolicy(QSizePolicy::Expanding, QSizePolicy::MinimumExpanding); + setDocumentMode(true); + setMinimumSize(200, 100); + setSizePolicy(QSizePolicy::Expanding, QSizePolicy::MinimumExpanding); - LtsTabBar *tabBar = new LtsTabBar(isSecondary, this); - setTabBar(tabBar); + LtsTabBar* tabBar = new LtsTabBar(isSecondary, this); + setTabBar(tabBar); - QFont currentFont = tabBar->font(); + QFont currentFont = tabBar->font(); - QFont::Capitalization c = QFont::SmallCaps; - bool bold = true; + QFont::Capitalization c = QFont::SmallCaps; + bool bold = true; - if (m_isSecondary) - { - c = QFont::MixedCase; - bold = false; - } + if (m_isSecondary) + { + c = QFont::MixedCase; + bold = false; + } + currentFont.setCapitalization(c); + currentFont.setBold(bold); - currentFont.setCapitalization(c); - currentFont.setBold(bold); + tabBar->setFont(currentFont); - tabBar->setFont(currentFont); + connect(this, &LtsTabWidget::currentChanged, this, &LtsTabWidget::slotCurrentChanged); - connect(this, &LtsTabWidget::currentChanged, - this, &LtsTabWidget::slotCurrentChanged); + QSplitter* splitter = static_cast(parent); + if (splitter && splitter->objectName() == QStringLiteral("mainSplitter") && splitter->widget(1) == this && + !isSecondary) + { + int tabBarHeight = m_tabbar->height() * 1.33; + int tabBarWidth = 20; - - QSplitter *splitter = static_cast(parent); - if (splitter && - splitter->objectName() == QStringLiteral("mainSplitter") && - splitter->widget(1) == this && - !isSecondary) - { - int tabBarHeight = m_tabbar->height() * 1.33; - int tabBarWidth = 20; - - setStyleSheet(styleSheet() + QStringLiteral("QTabWidget::tab-bar {" - "left: %1px; " - "} ").arg(tabBarWidth)); - QPushButton *maxBtn = new QPushButton(this); - maxBtn->setObjectName(QStringLiteral("MinMaxTabButton")); - maxBtn->setText(QStringLiteral("▲\n▼")); - maxBtn->setFixedSize(tabBarWidth, tabBarHeight * 2); - maxBtn->setStyleSheet(QStringLiteral("QPushButton { " - "border-radius: 0px; " - "border: 1px solid gray; " - "} ")); - connect(maxBtn, &QPushButton::clicked, this, &LtsTabWidget::slotMaximizeButtonClicked); - } + setStyleSheet(styleSheet() + QStringLiteral("QTabWidget::tab-bar {" + "left: %1px; " + "} ") + .arg(tabBarWidth)); + QPushButton* maxBtn = new QPushButton(this); + maxBtn->setObjectName(QStringLiteral("MinMaxTabButton")); + maxBtn->setText(QStringLiteral("▲\n▼")); + maxBtn->setFixedSize(tabBarWidth, tabBarHeight * 2); + maxBtn->setStyleSheet(QStringLiteral("QPushButton { " + "border-radius: 0px; " + "border: 1px solid gray; " + "} ")); + connect(maxBtn, &QPushButton::clicked, this, &LtsTabWidget::slotMaximizeButtonClicked); + } } - LtsTabWidget::~LtsTabWidget() { - - clearAll(); + clearAll(); } - void LtsTabWidget::slotCurrentChanged(int newIdx) { - if (newIdx < 0) - return; + if (newIdx < 0) + return; - QWidget *w = widget(newIdx); + QWidget* w = widget(newIdx); - if (w == nullptr) - return; + if (w == nullptr) + return; - LtsDialogHelper *dialog1 = qobject_cast(w); + LtsDialogHelper* dialog1 = qobject_cast(w); - if (dialog1 != nullptr) - { - LtsDialog *mainDialog = dialog1->getDialog(); - - if (mainDialog != nullptr) - emit mainDialog->signalFocused(); - - return; - } - - - LtsTabWidget *tab = qobject_cast(w); - - if (tab != nullptr) - { - LtsDialogHelper *dialog2 = qobject_cast(tab->widget(tab->currentIndex())); - - if (dialog2 != nullptr) + if (dialog1 != nullptr) { - LtsDialog *mainDialog = dialog2->getDialog(); + LtsDialog* mainDialog = dialog1->getDialog(); - if (mainDialog != nullptr) - emit mainDialog->signalFocused(); + if (mainDialog != nullptr) + emit mainDialog->signalFocused(); - return; + return; + } + + LtsTabWidget* tab = qobject_cast(w); + + if (tab != nullptr) + { + LtsDialogHelper* dialog2 = qobject_cast(tab->widget(tab->currentIndex())); + + if (dialog2 != nullptr) + { + LtsDialog* mainDialog = dialog2->getDialog(); + + if (mainDialog != nullptr) + emit mainDialog->signalFocused(); + + return; + } } - } } void LtsTabWidget::slotMaximizeButtonClicked() { - LtsSplitter *splitter = static_cast(parent()); - if (splitter) - { - if (splitter->widget(0)->height() != splitter->widget(0)->minimumHeight()) + LtsSplitter* splitter = static_cast(parent()); + if (splitter) { - m_mainSplitterState = splitter->saveState(); - splitter->collapseChild(0); + if (splitter->widget(0)->height() != splitter->widget(0)->minimumHeight()) + { + m_mainSplitterState = splitter->saveState(); + splitter->collapseChild(0); + } + else + { + splitter->restoreState(m_mainSplitterState); + } } - else - { - splitter->restoreState(m_mainSplitterState); - } - } } - -void LtsTabWidget::closeRequestTabWidget(LtsTabWidget *tabWidget) +void LtsTabWidget::closeRequestTabWidget(LtsTabWidget* tabWidget) { - for (int i = 0; i < tabWidget->count(); i++) - { - QWidget *w = tabWidget->widget(i); - - LtsDialogHelper *helper = qobject_cast(w); - - if (helper) + for (int i = 0; i < tabWidget->count(); i++) { - LtsDialog *dlg = qobject_cast(helper->getDialog()); + QWidget* w = tabWidget->widget(i); - if (dlg) - dlg->closeRequest(); + LtsDialogHelper* helper = qobject_cast(w); + + if (helper) + { + LtsDialog* dlg = qobject_cast(helper->getDialog()); + + if (dlg) + dlg->closeRequest(); + } + + LtsTabWidget* tab = qobject_cast(w); + if (tab) + closeRequestTabWidget(tab); } - - LtsTabWidget *tab = qobject_cast(w); - if (tab) - closeRequestTabWidget(tab); - } } - void LtsTabWidget::slotTabCloseRequested(int index) { - QWidget *w = widget(index); + QWidget* w = widget(index); - if (w == nullptr) - return; - - LtsDialogHelper *helper = qobject_cast(w); - - if (helper != nullptr) - { - LtsDialog *dialog = helper->getDialog(); - - if (dialog != nullptr) - { - if (dialog->isClosable()) - { - setCurrentIndex(index); - dialog->closeRequest(); + if (w == nullptr) return; - } - return; + LtsDialogHelper* helper = qobject_cast(w); + + if (helper != nullptr) + { + LtsDialog* dialog = helper->getDialog(); + + if (dialog != nullptr) + { + if (dialog->isClosable()) + { + setCurrentIndex(index); + dialog->closeRequest(); + return; + } + + return; + } } - } - LtsTabWidget *tab = qobject_cast(w); + LtsTabWidget* tab = qobject_cast(w); - if (tab != nullptr) - { - if (LtsTabWidget::hasUnsavedChanges(tab)) + if (tab != nullptr) { - LtsWidgets::Buttons buttons; - buttons.setFlag(Button::Yes, true); - buttons.setFlag(Button::Cancel, true); - QHash buttonTexts; - buttonTexts.insert(Button::Yes, tr("Discard All")); - const auto ret = LtsMessageDialog::showMessage(this, tr("There are dialogs with unsaved changes.
Please save or discard their changes before closing."), tr("Unsaved changes"), Behaviour::Modal, buttons, buttonTexts); - switch (ret) - { - case Button::Yes: - tab->deleteLater(); - return; - default: - return; - } + if (LtsTabWidget::hasUnsavedChanges(tab)) + { + LtsWidgets::Buttons buttons; + buttons.setFlag(Button::Yes, true); + buttons.setFlag(Button::Cancel, true); + QHash buttonTexts; + buttonTexts.insert(Button::Yes, tr("Discard All")); + const auto ret = LtsMessageDialog::showMessage( + this, + tr("There are dialogs with unsaved changes.
Please save or discard their changes before closing."), + tr("Unsaved changes"), Behaviour::Modal, buttons, buttonTexts); + switch (ret) + { + case Button::Yes: + tab->deleteLater(); + return; + default: + return; + } + } + else + { + + closeRequestTabWidget(tab); + } + } + w->deleteLater(); +} + +void LtsTabWidget::onCheckTabBarVisibility() +{ + + if (!m_isSecondary) + { + + if (count() < 1) + setHidden(true); } else { - - closeRequestTabWidget(tab); + if (count() < 1) + deleteLater(); } - } - w->deleteLater(); - - } - -void LtsTabWidget::onCheckTabBarVisibility() -{ - - - if (!m_isSecondary) - { - - if (count() < 1) - setHidden(true); - } - else - { - if (count() < 1) - deleteLater(); - } - - - - - - - - - - - - - - - - - - - - - - - - - - - -} - - void LtsTabWidget::setSubTabsVisible(bool visible) { - if (count()) - { - - return; - } - - m_hasSubTabs = visible; -} - - -void LtsTabWidget::addTab(const QString &menuGroup, const QString &identifier, QWidget *widget, - bool setClosable, bool focusNewTab) -{ - - setFocus(); - LtsTabWidget *tab = this; - QString fullName; - - - - - - if (m_hasSubTabs) - { - fullName = identifier; - tab = qobject_cast(m_tabMap.value(menuGroup, nullptr)); - - if (!tab) + if (count()) { - - tab = new LtsTabWidget(nullptr, true); - tab->setMovable(true); - addWidget(menuGroup, tab, true , focusNewTab); - } - else - { - - tab->setHidden(false); + + return; } - if (focusNewTab) - setCurrentIndex(indexOf(tab)); - } - else - { - fullName = menuGroup + QLatin1Char('.') + identifier; - - } - - setHidden(false); - - tab->addWidget(fullName, widget, setClosable, focusNewTab); - - - - if (m_hasSubTabs) - { - LtsTabBar *tabbar = tab->tabBar(); - - for (int i = 0; i < tabbar->count(); i++) - { - - if (tabbar->tabButton(i, QTabBar::RightSide)->isHidden()) - { - m_tabbar->tabButton(currentIndex(), QTabBar::RightSide)->hide(); - break; - } - } - } + m_hasSubTabs = visible; } - -void LtsTabWidget::addWidget(const QString &fullName, QWidget *widget, bool setClosable, bool focusNewTab) +void LtsTabWidget::addTab(const QString& menuGroup, const QString& identifier, QWidget* widget, bool setClosable, + bool focusNewTab) { - QString theName = fullName; - if (fullName.isEmpty()) - { - - const QString possibleCharacters(QStringLiteral("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")); - const int randomStringLength = 24; - - QString randomString; - for (int i = 0; i < randomStringLength; i++) - { - int index = qrand() % possibleCharacters.length(); - QChar nextChar = possibleCharacters.at(index); - randomString.append(nextChar); - } - - theName = randomString; - } - - widget->setObjectName(theName); - - LtsDialogHelper *helper = qobject_cast(widget); - if (helper) - helper->retranslate(); - - QString title = widget->windowTitle(); - - if (title.isEmpty()) - { - if (helper) - title = QStringLiteral("retranslate() fehlt!"); - else - title = widget->objectName(); - } - - if (helper) - { - connect(helper->getDialog(), &LtsDialog::signalHide, this, static_cast(&LtsTabWidget::onRemoveTab), - static_cast(Qt::QueuedConnection | Qt::UniqueConnection)); - - } - - connect(widget, &QWidget::destroyed, this, static_cast(&LtsTabWidget::onRemoveTab), Qt::DirectConnection); - connect(widget, &QWidget::windowTitleChanged, this, &LtsTabWidget::slotWindowTitleChanged); - - if (helper) - { - m_tabMap.insert(theName, helper); - - } - else - { - m_tabMap.insert(theName, widget); - - } - - int newTabIndex = QTabWidget::addTab(widget, title); - -#ifdef LTS_DEBUG - setTabToolTip(newTabIndex, tr("DEBUG: WindowName: %1").arg(theName)); -#endif - - if (focusNewTab) - setCurrentIndex(newTabIndex); - - LtsTabBar *tabbar = qobject_cast(tabBar()); - - if (tabbar) - { - - CloseButton *closeBtn = new CloseButton(); - connect(closeBtn, &QPushButton::clicked, tabbar, &LtsTabBar::_internal_closeTab); - tabbar->setTabButton(newTabIndex, QTabBar::RightSide, closeBtn); - } - - if (!setClosable) - m_tabbar->tabButton(newTabIndex, QTabBar::RightSide)->hide(); - - if (tabbar) - tabbar->updateCloseButtonColors(); - -} - - -void LtsTabWidget::slotWindowTitleChanged(const QString &title) -{ - QWidget *w = qobject_cast(sender()); - - if (!w) - { - qWarning() << "LtsTabWidget: slotWindowTitleChanged failed! (not a QWidget) " << sender(); - return; - } - - int index = indexOf(w); - - if (index < 0) - { - qWarning() << "LtsTabWidget: slotWindowTitleChanged failed! (widget not found on TabBar)"; - return; - } - - - QString realTitle = title; - QString readOnlyHint; - QStringList sl = title.split(QStringLiteral("- READ-ONLY")); - if (sl.size() == 2) - { - realTitle = sl.first().trimmed(); - readOnlyHint = sl.back().trimmed(); - - - if (readOnlyHint.startsWith(QStringLiteral("("))) - readOnlyHint.remove(0,1); - if (readOnlyHint.endsWith(QStringLiteral(")"))) - readOnlyHint.remove(readOnlyHint.size()-1,1); - - readOnlyHint = tr("Locked by: %1").arg(readOnlyHint); - } - - setTabText(index, realTitle); - - QTabBar *tabBar = this->tabBar(); - - if (!readOnlyHint.isEmpty()) - { - QLabel *readOnly = new QLabel(QStringLiteral("READ-ONLY"), this); - readOnly->setToolTip(readOnlyHint); - readOnly->setPixmap(QIcon(QStringLiteral("icon:warning.svg")).pixmap(QSize(25, 25))); - - tabBar->setTabButton(index, QTabBar::ButtonPosition::LeftSide, readOnly); - } else { - QWidget *readOnly = tabBar->tabButton(index, QTabBar::ButtonPosition::LeftSide); - if (readOnly) - { - - - - - tabBar->setTabButton(index, QTabBar::ButtonPosition::LeftSide, nullptr); - readOnly->setParent(this); - delete readOnly; - } - } -} - - -QWidget *LtsTabWidget::getWidget(const QString &menuGroup, const QString &identifier) -{ - LtsTabWidget *tab = this; - QString fullName; - - if (m_hasSubTabs) - { - fullName = identifier; - tab = qobject_cast(m_tabMap.value(menuGroup, nullptr)); - - if (tab == nullptr) - return nullptr; - } - else - { - fullName = menuGroup + QLatin1Char('.') + identifier; - } - - return tab->getWidget(fullName); -} - - -QWidget *LtsTabWidget::getWidget(const QString &fullName) -{ - return m_tabMap.value(fullName, nullptr); -} - - -bool LtsTabWidget::focusTab(const QString &menuGroup, const QString &identifier) -{ - QPointer tab = this; - QString fullName; - - if (m_hasSubTabs) - { - fullName = identifier; - tab = qobject_cast(m_tabMap.value(menuGroup, nullptr)); - - if (!tab) - { - - return false; - } - setCurrentIndex(indexOf(tab)); - } - else - fullName = menuGroup + QLatin1Char('.') + identifier; - - if (!tab) - return false; - - - LtsSplitter *splitter = static_cast(parent()); - - - - - - QTimer::singleShot(500, this, [splitter, tab] (){ - - - if (splitter && tab && (tab->count() >= 1) && splitter->sizes().count() && !(splitter->sizes().at(1))) - { - splitter->animate(1); - } - }); - return tab->focusWidget(fullName); -} - - -bool LtsTabWidget::focusWidget(const QString &fullName) -{ - QWidget *widget = m_tabMap.value(fullName, nullptr); - - if (widget == nullptr) - return false; - - setCurrentIndex(indexOf(widget)); - widget->setFocus(); - return true; -} - - -bool LtsTabWidget::removeWidget(QWidget * widget) -{ - if (nullptr == widget) - return false; - - for (auto i = m_tabMap.begin(); i != m_tabMap.end(); ++i) - { - QWidget *w = i.value(); - - if (w == nullptr) - continue; - - if (w == widget) - { - m_tabMap.erase(i); - disconnect(widget, &QWidget::destroyed, this, static_cast(&LtsTabWidget::onRemoveTab)); - return true; - } + setFocus(); + LtsTabWidget* tab = this; + QString fullName; if (m_hasSubTabs) { - LtsTabWidget *tab = qobject_cast(w); - if (tab != nullptr && tab->removeWidget(widget)) - { - return true; - } + fullName = identifier; + tab = qobject_cast(m_tabMap.value(menuGroup, nullptr)); + + if (!tab) + { + + tab = new LtsTabWidget(nullptr, true); + tab->setMovable(true); + addWidget(menuGroup, tab, true, focusNewTab); + } + else + { + + tab->setHidden(false); + } + + if (focusNewTab) + setCurrentIndex(indexOf(tab)); } - } - - return false; -} - - -void LtsTabWidget::onRemoveTab(QObject *object) -{ - if (object == nullptr) - { - qWarning() << "onRemoveTab: obj == nullptr"; - return; - } - - QWidget *w = static_cast(object); - - bool rmd = false; - for (auto i = m_tabMap.begin(); i != m_tabMap.end(); ++i) - { - if (i.value() == w) + else { - m_tabMap.erase(i); - rmd = true; - break; + fullName = menuGroup + QLatin1Char('.') + identifier; } - } - if (!rmd) - { - qWarning() << "LtsTabWidget::onRemoveTab: widget to remove was not on tab map!"; - } + setHidden(false); - int index = indexOf(w); - if (index < 0) - { - - qWarning() << "LtsTabWidget::onRemoveTab: cannot remove widget, as it was not found on the tab widget" << (void *)w; - } - else - { - removeTab(index); - } + tab->addWidget(fullName, widget, setClosable, focusNewTab); - onCheckTabBarVisibility(); + if (m_hasSubTabs) + { + LtsTabBar* tabbar = tab->tabBar(); + + for (int i = 0; i < tabbar->count(); i++) + { + + if (tabbar->tabButton(i, QTabBar::RightSide)->isHidden()) + { + m_tabbar->tabButton(currentIndex(), QTabBar::RightSide)->hide(); + break; + } + } + } } +void LtsTabWidget::addWidget(const QString& fullName, QWidget* widget, bool setClosable, bool focusNewTab) +{ + QString theName = fullName; + + if (fullName.isEmpty()) + { + + const QString possibleCharacters( + QStringLiteral("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")); + const int randomStringLength = 24; + + QString randomString; + for (int i = 0; i < randomStringLength; i++) + { + int index = QRandomGenerator::global()->bounded(possibleCharacters.length()); + QChar nextChar = possibleCharacters.at(index); + randomString.append(nextChar); + } + + theName = randomString; + } + + widget->setObjectName(theName); + + LtsDialogHelper* helper = qobject_cast(widget); + if (helper) + helper->retranslate(); + + QString title = widget->windowTitle(); + + if (title.isEmpty()) + { + if (helper) + title = QStringLiteral("retranslate() fehlt!"); + else + title = widget->objectName(); + } + + if (helper) + { + connect(helper->getDialog(), &LtsDialog::signalHide, this, + static_cast(&LtsTabWidget::onRemoveTab), + static_cast(Qt::QueuedConnection | Qt::UniqueConnection)); + } + + connect(widget, &QWidget::destroyed, this, + static_cast(&LtsTabWidget::onRemoveTab), Qt::DirectConnection); + connect(widget, &QWidget::windowTitleChanged, this, &LtsTabWidget::slotWindowTitleChanged); + + if (helper) + { + m_tabMap.insert(theName, helper); + } + else + { + m_tabMap.insert(theName, widget); + } + + int newTabIndex = QTabWidget::addTab(widget, title); + +#ifdef LTS_DEBUG + setTabToolTip(newTabIndex, tr("DEBUG: WindowName: %1").arg(theName)); +#endif + + if (focusNewTab) + setCurrentIndex(newTabIndex); + + LtsTabBar* tabbar = qobject_cast(tabBar()); + + if (tabbar) + { + + CloseButton* closeBtn = new CloseButton(); + connect(closeBtn, &QPushButton::clicked, tabbar, &LtsTabBar::_internal_closeTab); + tabbar->setTabButton(newTabIndex, QTabBar::RightSide, closeBtn); + } + + if (!setClosable) + m_tabbar->tabButton(newTabIndex, QTabBar::RightSide)->hide(); + + if (tabbar) + tabbar->updateCloseButtonColors(); +} + +void LtsTabWidget::slotWindowTitleChanged(const QString& title) +{ + QWidget* w = qobject_cast(sender()); + + if (!w) + { + qWarning() << "LtsTabWidget: slotWindowTitleChanged failed! (not a QWidget) " << sender(); + return; + } + + int index = indexOf(w); + + if (index < 0) + { + qWarning() << "LtsTabWidget: slotWindowTitleChanged failed! (widget not found on TabBar)"; + return; + } + + QString realTitle = title; + QString readOnlyHint; + QStringList sl = title.split(QStringLiteral("- READ-ONLY")); + if (sl.size() == 2) + { + realTitle = sl.first().trimmed(); + readOnlyHint = sl.back().trimmed(); + + if (readOnlyHint.startsWith(QStringLiteral("("))) + readOnlyHint.remove(0, 1); + if (readOnlyHint.endsWith(QStringLiteral(")"))) + readOnlyHint.remove(readOnlyHint.size() - 1, 1); + + readOnlyHint = tr("Locked by: %1").arg(readOnlyHint); + } + + setTabText(index, realTitle); + + QTabBar* tabBar = this->tabBar(); + + if (!readOnlyHint.isEmpty()) + { + QLabel* readOnly = new QLabel(QStringLiteral("READ-ONLY"), this); + readOnly->setToolTip(readOnlyHint); + readOnly->setPixmap(QIcon(QStringLiteral("icon:warning.svg")).pixmap(QSize(25, 25))); + + tabBar->setTabButton(index, QTabBar::ButtonPosition::LeftSide, readOnly); + } + else + { + QWidget* readOnly = tabBar->tabButton(index, QTabBar::ButtonPosition::LeftSide); + if (readOnly) + { + + tabBar->setTabButton(index, QTabBar::ButtonPosition::LeftSide, nullptr); + readOnly->setParent(this); + delete readOnly; + } + } +} + +QWidget* LtsTabWidget::getWidget(const QString& menuGroup, const QString& identifier) +{ + LtsTabWidget* tab = this; + QString fullName; + + if (m_hasSubTabs) + { + fullName = identifier; + tab = qobject_cast(m_tabMap.value(menuGroup, nullptr)); + + if (tab == nullptr) + return nullptr; + } + else + { + fullName = menuGroup + QLatin1Char('.') + identifier; + } + + return tab->getWidget(fullName); +} + +QWidget* LtsTabWidget::getWidget(const QString& fullName) +{ + return m_tabMap.value(fullName, nullptr); +} + +bool LtsTabWidget::focusTab(const QString& menuGroup, const QString& identifier) +{ + QPointer tab = this; + QString fullName; + + if (m_hasSubTabs) + { + fullName = identifier; + tab = qobject_cast(m_tabMap.value(menuGroup, nullptr)); + + if (!tab) + { + + return false; + } + setCurrentIndex(indexOf(tab)); + } + else + fullName = menuGroup + QLatin1Char('.') + identifier; + + if (!tab) + return false; + + LtsSplitter* splitter = static_cast(parent()); + + QTimer::singleShot(500, this, [splitter, tab]() { + if (splitter && tab && (tab->count() >= 1) && splitter->sizes().count() && !(splitter->sizes().at(1))) + { + splitter->animate(1); + } + }); + return tab->focusWidget(fullName); +} + +bool LtsTabWidget::focusWidget(const QString& fullName) +{ + QWidget* widget = m_tabMap.value(fullName, nullptr); + + if (widget == nullptr) + return false; + + setCurrentIndex(indexOf(widget)); + widget->setFocus(); + return true; +} + +bool LtsTabWidget::removeWidget(QWidget* widget) +{ + if (nullptr == widget) + return false; + + for (auto i = m_tabMap.begin(); i != m_tabMap.end(); ++i) + { + QWidget* w = i.value(); + + if (w == nullptr) + continue; + + if (w == widget) + { + m_tabMap.erase(i); + disconnect(widget, &QWidget::destroyed, this, + static_cast(&LtsTabWidget::onRemoveTab)); + return true; + } + + if (m_hasSubTabs) + { + LtsTabWidget* tab = qobject_cast(w); + if (tab != nullptr && tab->removeWidget(widget)) + { + return true; + } + } + } + + return false; +} + +void LtsTabWidget::onRemoveTab(QObject* object) +{ + if (object == nullptr) + { + qWarning() << "onRemoveTab: obj == nullptr"; + return; + } + + QWidget* w = static_cast(object); + + bool rmd = false; + for (auto i = m_tabMap.begin(); i != m_tabMap.end(); ++i) + { + if (i.value() == w) + { + m_tabMap.erase(i); + rmd = true; + break; + } + } + + if (!rmd) + { + qWarning() << "LtsTabWidget::onRemoveTab: widget to remove was not on tab map!"; + } + + int index = indexOf(w); + if (index < 0) + { + + qWarning() << "LtsTabWidget::onRemoveTab: cannot remove widget, as it was not found on the tab widget" + << (void*)w; + } + else + { + removeTab(index); + } + + onCheckTabBarVisibility(); +} void LtsTabWidget::setActuatorTabStyle(bool enable) { - if (enable) - setTabBar(new LtsTabBar(false, this)); + if (enable) + setTabBar(new LtsTabBar(false, this)); } - -LtsTabBar *LtsTabWidget::tabBar() +LtsTabBar* LtsTabWidget::tabBar() { - return m_tabbar; + return m_tabbar; } - -void LtsTabWidget::setTabBar(LtsTabBar *tabbar) +void LtsTabWidget::setTabBar(LtsTabBar* tabbar) { - if (m_tabbar) - m_tabbar->deleteLater(); + if (m_tabbar) + m_tabbar->deleteLater(); - - QFont currentFont = font(); - currentFont.setCapitalization(QFont::SmallCaps); - currentFont.setBold(true); + QFont currentFont = font(); + currentFont.setCapitalization(QFont::SmallCaps); + currentFont.setBold(true); - tabbar->setFont(currentFont); - connect(tabbar, &LtsTabBar::tabCloseRequested, this, &LtsTabWidget::slotTabCloseRequested); + tabbar->setFont(currentFont); + connect(tabbar, &LtsTabBar::tabCloseRequested, this, &LtsTabWidget::slotTabCloseRequested); - m_tabbar = tabbar; - QTabWidget::setTabBar(m_tabbar); + m_tabbar = tabbar; + QTabWidget::setTabBar(m_tabbar); } - void LtsTabWidget::clearAll() { - - for (int i = 0; i < count(); i++) - { - QWidget *w = widget(i); + for (int i = 0; i < count(); i++) + { + QWidget* w = widget(i); - if (w == nullptr) - continue; + if (w == nullptr) + continue; - disconnect(w, &QWidget::destroyed, this, static_cast(&LtsTabWidget::onRemoveTab)); + disconnect(w, &QWidget::destroyed, this, + static_cast(&LtsTabWidget::onRemoveTab)); - w->deleteLater(); - } + w->deleteLater(); + } - clear(); + clear(); } - void LtsTabWidget::aboutToClose() { - for (int i = 0; i < count(); i++) - { - if (m_hasSubTabs) + for (int i = 0; i < count(); i++) { - LtsTabWidget *tab = qobject_cast(widget(i)); - tab->aboutToClose(); - } - else - { - LtsDialogHelper *helper = qobject_cast(widget(i)); - - if (helper == nullptr) - continue; - - LtsDialog *dialog = qobject_cast(helper->getDialog()); - - if (dialog == nullptr) - continue; - - dialog->aboutToClose(); - } - } -} - - -bool LtsTabWidget::hasUnsavedChanges(LtsTabWidget *tabWidget) -{ - for (int i = 0; i < tabWidget->count(); i++) - { - QWidget *w = tabWidget->widget(i); - - LtsDialogHelper *helper = qobject_cast(w); - - if (helper) - { - LtsDialog *dlg = qobject_cast(helper->getDialog()); - - if (dlg != nullptr) - { - - - if (dlg->hasUnsavedChanges()) + if (m_hasSubTabs) { - int dlgIndex = tabWidget->indexOf(helper); - if (dlgIndex != -1) - tabWidget->setCurrentIndex(dlgIndex); + LtsTabWidget* tab = qobject_cast(widget(i)); + tab->aboutToClose(); + } + else + { + LtsDialogHelper* helper = qobject_cast(widget(i)); - - return true; + if (helper == nullptr) + continue; + + LtsDialog* dialog = qobject_cast(helper->getDialog()); + + if (dialog == nullptr) + continue; + + dialog->aboutToClose(); } - } } - - LtsTabWidget *tab = qobject_cast(w); - - if (tab) - { - - - bool _hasUnsavedChanges = hasUnsavedChanges(tab); - if (_hasUnsavedChanges) - { - int tabIndex = tabWidget->indexOf(tab); - if (tabIndex != -1) - tabWidget->setCurrentIndex(tabIndex); - - return true; - } - } - - - - } - - return false; } - - - - - -void CloseButton::paintEvent(QPaintEvent *) +bool LtsTabWidget::hasUnsavedChanges(LtsTabWidget* tabWidget) { - QPainter p(this); + for (int i = 0; i < tabWidget->count(); i++) + { + QWidget* w = tabWidget->widget(i); - p.save(); - p.setPen(QPen(QColor(m_fontColor), 1.5)); - p.setRenderHint(QPainter::Antialiasing); + LtsDialogHelper* helper = qobject_cast(w); - - p.drawLine(line()); + if (helper) + { + LtsDialog* dlg = qobject_cast(helper->getDialog()); - - p.setPen(QPen(QColor(m_fontColor), 2.5)); + if (dlg != nullptr) + { - QRectF c = cross(); + if (dlg->hasUnsavedChanges()) + { + int dlgIndex = tabWidget->indexOf(helper); + if (dlgIndex != -1) + tabWidget->setCurrentIndex(dlgIndex); - p.drawLine(c.topLeft(), c.bottomRight()); - p.drawLine(c.bottomLeft(), c.topRight()); + return true; + } + } + } - p.restore(); + LtsTabWidget* tab = qobject_cast(w); + + if (tab) + { + + bool _hasUnsavedChanges = hasUnsavedChanges(tab); + if (_hasUnsavedChanges) + { + int tabIndex = tabWidget->indexOf(tab); + if (tabIndex != -1) + tabWidget->setCurrentIndex(tabIndex); + + return true; + } + } + } + + return false; } +void CloseButton::paintEvent(QPaintEvent*) +{ + QPainter p(this); + + p.save(); + p.setPen(QPen(QColor(m_fontColor), 1.5)); + p.setRenderHint(QPainter::Antialiasing); + + p.drawLine(line()); + + p.setPen(QPen(QColor(m_fontColor), 2.5)); + + QRectF c = cross(); + + p.drawLine(c.topLeft(), c.bottomRight()); + p.drawLine(c.bottomLeft(), c.topRight()); + + p.restore(); +} QLineF CloseButton::line() const { - qreal forceBlur = 0.001; - qreal lineStart = height() * (0.25 / 2) + forceBlur; - qreal lineSize = height() - lineStart; + qreal forceBlur = 0.001; + qreal lineStart = height() * (0.25 / 2) + forceBlur; + qreal lineSize = height() - lineStart; - return QLineF(QPointF(lineStart, lineStart), QPointF(lineStart, lineSize)); + return QLineF(QPointF(lineStart, lineStart), QPointF(lineStart, lineSize)); } - QRectF CloseButton::cross() const { - QLineF l = line(); + QLineF l = line(); - qreal lineLeft = l.x1(); - qreal forceBlur = 0.001; + qreal lineLeft = l.x1(); + qreal forceBlur = 0.001; - qreal crossStartX = lineLeft * 3; - qreal crossStartY = lineLeft * 2; - qreal crossEndX = width(); crossEndX -= crossEndX * 0.15 + forceBlur; - qreal crossEndY = height() - crossStartY; + qreal crossStartX = lineLeft * 3; + qreal crossStartY = lineLeft * 2; + qreal crossEndX = width(); + crossEndX -= crossEndX * 0.15 + forceBlur; + qreal crossEndY = height() - crossStartY; - return QRectF(QPointF(crossStartX, crossStartY), QPointF(crossEndX, crossEndY)); + return QRectF(QPointF(crossStartX, crossStartY), QPointF(crossEndX, crossEndY)); } - QSize CloseButton::sizeHint() const { - QFontMetrics fm (QApplication::font()); - int fontHeight = fm.height(); + QFontMetrics fm(QApplication::font()); + int fontHeight = fm.height(); - int fontHeightQuarter = fontHeight * 0.25; - int finalSize = fontHeight + fontHeightQuarter; + int fontHeightQuarter = fontHeight * 0.25; + int finalSize = fontHeight + fontHeightQuarter; #ifdef TABLET_MODE - finalSize = finalSize*1.5; + finalSize = finalSize * 1.5; #endif - return QSize(finalSize, finalSize); + return QSize(finalSize, finalSize); } - -void CloseButton::mousePressEvent(QMouseEvent *e) +void CloseButton::mousePressEvent(QMouseEvent* e) { - e->ignore(); - m_isPressed = true; + e->ignore(); + m_isPressed = true; } - -void CloseButton::mouseReleaseEvent(QMouseEvent *e) +void CloseButton::mouseReleaseEvent(QMouseEvent* e) { - bool isPressed = m_isPressed; - m_isPressed = false; + bool isPressed = m_isPressed; + m_isPressed = false; - if (!isPressed) - { - e->ignore(); - return; - } + if (!isPressed) + { + e->ignore(); + return; + } - QRectF c = cross(); - QRect adjusted = QRect(QPoint(floor(c.x()), floor(c.y())), QPoint(ceil(c.right()), ceil(c.bottom() +1 ))); + QRectF c = cross(); + QRect adjusted = QRect(QPoint(floor(c.x()), floor(c.y())), QPoint(ceil(c.right()), ceil(c.bottom() + 1))); - if (!adjusted.contains(e->localPos().toPoint())) - { - - e->ignore(); - return; - } + if (!adjusted.contains(e->localPos().toPoint())) + { - - e->accept(); - emit clicked(); + e->ignore(); + return; + } + + e->accept(); + emit clicked(); } -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_editor.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_editor.cpp old mode 100755 new mode 100644 index 54fb681ef..57d4d827d --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_editor.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_editor.cpp @@ -2,390 +2,351 @@ #include "ui_lts_text_editor.h" -#include -#include #include #include -#include -#include -#include -#include - +#include #include +#include +#include +#include +#include +#include namespace LtsWidgets { -LtsTextEditor::LtsTextEditor(QWidget *parent) - : QWidget(parent) - , m_ui(new Ui::LtsTextEditor) +LtsTextEditor::LtsTextEditor(QWidget* parent) : QWidget(parent), m_ui(new Ui::LtsTextEditor) { - m_ui->setupUi(this); + m_ui->setupUi(this); - connect(m_ui->textEdit, &QTextEdit::currentCharFormatChanged, - this, &LtsTextEditor::slotCurrentCharFormatChanged); - connect(m_ui->textEdit, &QTextEdit::cursorPositionChanged, - this, &LtsTextEditor::slotAlignmentChanged); + connect(m_ui->textEdit, &QTextEdit::currentCharFormatChanged, this, &LtsTextEditor::slotCurrentCharFormatChanged); + connect(m_ui->textEdit, &QTextEdit::cursorPositionChanged, this, &LtsTextEditor::slotAlignmentChanged); - connect(m_ui->textEdit->document(), &QTextDocument::undoAvailable, - m_ui->pbUndo, &QToolButton::setEnabled); - connect(m_ui->textEdit->document(), &QTextDocument::redoAvailable, - m_ui->pbRedo, &QToolButton::setEnabled); + connect(m_ui->textEdit->document(), &QTextDocument::undoAvailable, m_ui->pbUndo, &QToolButton::setEnabled); + connect(m_ui->textEdit->document(), &QTextDocument::redoAvailable, m_ui->pbRedo, &QToolButton::setEnabled); - m_ui->pbUndo->setEnabled(m_ui->textEdit->document()->isUndoAvailable()); - m_ui->pbRedo->setEnabled(m_ui->textEdit->document()->isRedoAvailable()); + m_ui->pbUndo->setEnabled(m_ui->textEdit->document()->isUndoAvailable()); + m_ui->pbRedo->setEnabled(m_ui->textEdit->document()->isRedoAvailable()); - connect(QApplication::clipboard(), &QClipboard::dataChanged, - this, &LtsTextEditor::slotClipboardDataChanged); + connect(QApplication::clipboard(), &QClipboard::dataChanged, this, &LtsTextEditor::slotClipboardDataChanged); + connect(m_ui->pbCut, &QToolButton::clicked, m_ui->textEdit, &QTextEdit::cut); + connect(m_ui->pbCopy, &QToolButton::clicked, m_ui->textEdit, &QTextEdit::copy); + connect(m_ui->pbPaste, &QToolButton::clicked, m_ui->textEdit, &QTextEdit::paste); - connect(m_ui->pbCut, &QToolButton::clicked, - m_ui->textEdit, &QTextEdit::cut); - connect(m_ui->pbCopy, &QToolButton::clicked, - m_ui->textEdit, &QTextEdit::copy); - connect(m_ui->pbPaste, &QToolButton::clicked, - m_ui->textEdit, &QTextEdit::paste); + connect(m_ui->pbUndo, &QToolButton::clicked, m_ui->textEdit, &QTextEdit::undo); + connect(m_ui->pbRedo, &QToolButton::clicked, m_ui->textEdit, &QTextEdit::redo); - connect(m_ui->pbUndo, &QToolButton::clicked, - m_ui->textEdit, &QTextEdit::undo); - connect(m_ui->pbRedo, &QToolButton::clicked, - m_ui->textEdit, &QTextEdit::redo); + connect(m_ui->pbBold, &QToolButton::clicked, this, &LtsTextEditor::slotTextBold); + connect(m_ui->pbItalic, &QToolButton::clicked, this, &LtsTextEditor::slotTextItalic); + connect(m_ui->pbUnderline, &QToolButton::clicked, this, &LtsTextEditor::slotTextUnderline); - connect(m_ui->pbBold, &QToolButton::clicked, - this, &LtsTextEditor::slotTextBold); - connect(m_ui->pbItalic, &QToolButton::clicked, - this, &LtsTextEditor::slotTextItalic); - connect(m_ui->pbUnderline, &QToolButton::clicked, - this, &LtsTextEditor::slotTextUnderline); + connect(m_ui->pbTextColor, &QToolButton::clicked, this, &LtsTextEditor::slotTextColor); + connect(m_ui->pbBackgroundColor, &QToolButton::clicked, this, &LtsTextEditor::slotBackgroundColor); - connect(m_ui->pbTextColor, &QToolButton::clicked, - this, &LtsTextEditor::slotTextColor); - connect(m_ui->pbBackgroundColor, &QToolButton::clicked, - this, &LtsTextEditor::slotBackgroundColor); + connect(m_ui->pbAlignLeft, &QToolButton::toggled, this, &LtsTextEditor::slotTextAlign); + connect(m_ui->pbAlignCenter, &QToolButton::toggled, this, &LtsTextEditor::slotTextAlign); + connect(m_ui->pbAlignRight, &QToolButton::toggled, this, &LtsTextEditor::slotTextAlign); + connect(m_ui->pbAlignJustify, &QToolButton::toggled, this, &LtsTextEditor::slotTextAlign); - connect(m_ui->pbAlignLeft, &QToolButton::toggled, - this, &LtsTextEditor::slotTextAlign); - connect(m_ui->pbAlignCenter, &QToolButton::toggled, - this, &LtsTextEditor::slotTextAlign); - connect(m_ui->pbAlignRight, &QToolButton::toggled, - this, &LtsTextEditor::slotTextAlign); - connect(m_ui->pbAlignJustify, &QToolButton::toggled, - this, &LtsTextEditor::slotTextAlign); + QFont textFont(QStringLiteral("Sans Serif")); + textFont.setStyleHint(QFont::SansSerif); + m_ui->textEdit->setFont(textFont); + slotFontChanged(m_ui->textEdit->font()); + slotTextColorChanged(m_ui->textEdit->textColor()); + slotAlignmentChanged(); + slotBackgroundColorChanged(m_backgroundColor); - QFont textFont(QStringLiteral("Sans Serif")); - textFont.setStyleHint(QFont::SansSerif); - m_ui->textEdit->setFont(textFont); - slotFontChanged(m_ui->textEdit->font()); - slotTextColorChanged(m_ui->textEdit->textColor()); - slotAlignmentChanged(); + connect(m_ui->cbFonts, &QComboBox::currentTextChanged, this, &LtsTextEditor::slotTextFamily); - slotBackgroundColorChanged(m_backgroundColor); + const QList standardSizes = QFontDatabase::standardSizes(); + for (int size : standardSizes) + m_ui->cbFontSize->addItem(QString::number(size)); + m_ui->cbFontSize->setCurrentIndex(standardSizes.indexOf(QApplication::font().pointSize())); + connect(m_ui->cbFontSize, &QComboBox::currentTextChanged, this, &LtsTextEditor::slotTextSize); - connect(m_ui->cbFonts, QOverload::of(&QComboBox::activated), - this, &LtsTextEditor::slotTextFamily); + connect(m_ui->cbFontSize->lineEdit(), &QLineEdit::editingFinished, this, + &LtsTextEditor::slotTextSizeEditingFinished); - const QList standardSizes = QFontDatabase::standardSizes(); - for (int size : standardSizes) - m_ui->cbFontSize->addItem(QString::number(size)); - m_ui->cbFontSize->setCurrentIndex(standardSizes.indexOf(QApplication::font().pointSize())); - - connect(m_ui->cbFontSize, QOverload::of(&QComboBox::activated), - this, &LtsTextEditor::slotTextSize); - - connect(m_ui->cbFontSize->lineEdit(), &QLineEdit::editingFinished, - this, &LtsTextEditor::slotTextSizeEditingFinished); - - m_ui->textEdit->setFocus(); + m_ui->textEdit->setFocus(); } - LtsTextEditor::~LtsTextEditor() { - delete m_ui; + delete m_ui; } - -QTextEdit *LtsTextEditor::textEdit() +QTextEdit* LtsTextEditor::textEdit() { - return m_ui->textEdit; + return m_ui->textEdit; } QColor LtsTextEditor::backgroundColor() const { - return m_backgroundColor; + return m_backgroundColor; } void LtsTextEditor::enableBackgroundColor(bool onOff) { - m_ui->pbBackgroundColor->setVisible(onOff); + m_ui->pbBackgroundColor->setVisible(onOff); } -void LtsTextEditor::setInitialBackgroundColor(const QColor &bgColor) +void LtsTextEditor::setInitialBackgroundColor(const QColor& bgColor) { - if (bgColor.isValid()) - m_backgroundColor = bgColor; - slotBackgroundColorChanged(m_backgroundColor); + if (bgColor.isValid()) + m_backgroundColor = bgColor; + slotBackgroundColorChanged(m_backgroundColor); } - void LtsTextEditor::slotTextBold() { - QTextCharFormat fmt; - fmt.setFontItalic(m_ui->pbItalic->isChecked()); - fmt.setFontUnderline(m_ui->pbUnderline->isChecked()); - fmt.setFontWeight(m_ui->pbBold->isChecked() ? QFont::Bold : QFont::Normal); - if (m_ui->textEdit->document()->isEmpty()) - { - const QString &f = m_ui->cbFonts->currentText(); - fmt.setFontFamily(f); - fmt.setFontFamilies({f}); - fmt.setForeground(m_foregroundColor); - const qreal pointSize = (m_ui->cbFontSize->currentText().toFloat() > 0 ? m_ui->cbFontSize->currentText().toFloat() : 11); - fmt.setFontPointSize(pointSize); - } - slotMergeFormatOnWordOrSelection(fmt); -} - - -void LtsTextEditor::slotTextUnderline() -{ - QTextCharFormat fmt; - fmt.setFontItalic(m_ui->pbItalic->isChecked()); - fmt.setFontUnderline(m_ui->pbUnderline->isChecked()); - fmt.setFontWeight(m_ui->pbBold->isChecked() ? QFont::Bold : QFont::Normal); - if (m_ui->textEdit->document()->isEmpty()) - { - const QString &f = m_ui->cbFonts->currentText(); - fmt.setFontFamily(f); - fmt.setFontFamilies({f}); - fmt.setForeground(m_foregroundColor); - const qreal pointSize = (m_ui->cbFontSize->currentText().toFloat() > 0 ? m_ui->cbFontSize->currentText().toFloat() : 11); - fmt.setFontPointSize(pointSize); - } - slotMergeFormatOnWordOrSelection(fmt); -} - - -void LtsTextEditor::slotTextItalic() -{ - QTextCharFormat fmt; - fmt.setFontItalic(m_ui->pbItalic->isChecked()); - fmt.setFontUnderline(m_ui->pbUnderline->isChecked()); - fmt.setFontWeight(m_ui->pbBold->isChecked() ? QFont::Bold : QFont::Normal); - if (m_ui->textEdit->document()->isEmpty()) - { - const QString &f = m_ui->cbFonts->currentText(); - fmt.setFontFamily(f); - fmt.setFontFamilies({f}); - fmt.setForeground(m_foregroundColor); - const qreal pointSize = (m_ui->cbFontSize->currentText().toFloat() > 0 ? m_ui->cbFontSize->currentText().toFloat() : 11); - fmt.setFontPointSize(pointSize); - } - slotMergeFormatOnWordOrSelection(fmt); -} - - -void LtsTextEditor::slotTextFamily(const QString &f) -{ - QTextCharFormat fmt; - if (m_ui->textEdit->document()->isEmpty()) - { + QTextCharFormat fmt; fmt.setFontItalic(m_ui->pbItalic->isChecked()); fmt.setFontUnderline(m_ui->pbUnderline->isChecked()); fmt.setFontWeight(m_ui->pbBold->isChecked() ? QFont::Bold : QFont::Normal); - - const qreal pointSize = (m_ui->cbFontSize->currentText().toFloat() > 0 ? m_ui->cbFontSize->currentText().toFloat() : 11); - fmt.setFontPointSize(pointSize); - fmt.setForeground(m_foregroundColor); - } - fmt.setFontFamily(f); - fmt.setFontFamilies({f}); - slotMergeFormatOnWordOrSelection(fmt); + if (m_ui->textEdit->document()->isEmpty()) + { + const QString& f = m_ui->cbFonts->currentText(); + fmt.setFontFamily(f); + fmt.setFontFamilies({f}); + fmt.setForeground(m_foregroundColor); + const qreal pointSize = + (m_ui->cbFontSize->currentText().toFloat() > 0 ? m_ui->cbFontSize->currentText().toFloat() : 11); + fmt.setFontPointSize(pointSize); + } + slotMergeFormatOnWordOrSelection(fmt); } - -void LtsTextEditor::slotTextSize(const QString &p) +void LtsTextEditor::slotTextUnderline() { - qreal pointSize = p.toFloat(); + QTextCharFormat fmt; + fmt.setFontItalic(m_ui->pbItalic->isChecked()); + fmt.setFontUnderline(m_ui->pbUnderline->isChecked()); + fmt.setFontWeight(m_ui->pbBold->isChecked() ? QFont::Bold : QFont::Normal); + if (m_ui->textEdit->document()->isEmpty()) + { + const QString& f = m_ui->cbFonts->currentText(); + fmt.setFontFamily(f); + fmt.setFontFamilies({f}); + fmt.setForeground(m_foregroundColor); + const qreal pointSize = + (m_ui->cbFontSize->currentText().toFloat() > 0 ? m_ui->cbFontSize->currentText().toFloat() : 11); + fmt.setFontPointSize(pointSize); + } + slotMergeFormatOnWordOrSelection(fmt); +} - if (p.toFloat() > 0) - { - QSignalBlocker signalBlocker(m_ui->cbFontSize->lineEdit()); - m_ui->cbFontSize->clearFocus(); +void LtsTextEditor::slotTextItalic() +{ + QTextCharFormat fmt; + fmt.setFontItalic(m_ui->pbItalic->isChecked()); + fmt.setFontUnderline(m_ui->pbUnderline->isChecked()); + fmt.setFontWeight(m_ui->pbBold->isChecked() ? QFont::Bold : QFont::Normal); + if (m_ui->textEdit->document()->isEmpty()) + { + const QString& f = m_ui->cbFonts->currentText(); + fmt.setFontFamily(f); + fmt.setFontFamilies({f}); + fmt.setForeground(m_foregroundColor); + const qreal pointSize = + (m_ui->cbFontSize->currentText().toFloat() > 0 ? m_ui->cbFontSize->currentText().toFloat() : 11); + fmt.setFontPointSize(pointSize); + } + slotMergeFormatOnWordOrSelection(fmt); +} +void LtsTextEditor::slotTextFamily(const QString& f) +{ QTextCharFormat fmt; if (m_ui->textEdit->document()->isEmpty()) { - const QString &f = m_ui->cbFonts->currentText(); - fmt.setFontFamily(f); - fmt.setFontFamilies({f}); - fmt.setForeground(m_foregroundColor); - - fmt.setFontItalic(m_ui->pbItalic->isChecked()); - fmt.setFontUnderline(m_ui->pbUnderline->isChecked()); - fmt.setFontWeight(m_ui->pbBold->isChecked() ? QFont::Bold : QFont::Normal); + fmt.setFontItalic(m_ui->pbItalic->isChecked()); + fmt.setFontUnderline(m_ui->pbUnderline->isChecked()); + fmt.setFontWeight(m_ui->pbBold->isChecked() ? QFont::Bold : QFont::Normal); + const qreal pointSize = + (m_ui->cbFontSize->currentText().toFloat() > 0 ? m_ui->cbFontSize->currentText().toFloat() : 11); + fmt.setFontPointSize(pointSize); + fmt.setForeground(m_foregroundColor); } - fmt.setFontPointSize(pointSize); + fmt.setFontFamily(f); + fmt.setFontFamilies({f}); slotMergeFormatOnWordOrSelection(fmt); - } +} + +void LtsTextEditor::slotTextSize(const QString& p) +{ + qreal pointSize = p.toFloat(); + + if (p.toFloat() > 0) + { + QSignalBlocker signalBlocker(m_ui->cbFontSize->lineEdit()); + m_ui->cbFontSize->clearFocus(); + + QTextCharFormat fmt; + if (m_ui->textEdit->document()->isEmpty()) + { + const QString& f = m_ui->cbFonts->currentText(); + fmt.setFontFamily(f); + fmt.setFontFamilies({f}); + fmt.setForeground(m_foregroundColor); + + fmt.setFontItalic(m_ui->pbItalic->isChecked()); + fmt.setFontUnderline(m_ui->pbUnderline->isChecked()); + fmt.setFontWeight(m_ui->pbBold->isChecked() ? QFont::Bold : QFont::Normal); + } + fmt.setFontPointSize(pointSize); + slotMergeFormatOnWordOrSelection(fmt); + } } void LtsTextEditor::slotTextSizeEditingFinished() { - qreal pointSize = m_ui->cbFontSize->currentText().toFloat(); + qreal pointSize = m_ui->cbFontSize->currentText().toFloat(); - if (pointSize > 0) - { - QTextCharFormat textCharFormat; + if (pointSize > 0) + { + QTextCharFormat textCharFormat; - textCharFormat.setFontPointSize(pointSize); + textCharFormat.setFontPointSize(pointSize); - QTextCursor cursor = m_ui->textEdit->textCursor(); + QTextCursor cursor = m_ui->textEdit->textCursor(); - if (cursor.charFormat().font().pointSizeF() == pointSize) - return; + if (cursor.charFormat().font().pointSizeF() == pointSize) + return; - if (!cursor.hasSelection()) - cursor.select(QTextCursor::WordUnderCursor); + if (!cursor.hasSelection()) + cursor.select(QTextCursor::WordUnderCursor); - cursor.mergeCharFormat(textCharFormat); - } + cursor.mergeCharFormat(textCharFormat); + } } void LtsTextEditor::slotTextColor() { - QColor col = QColorDialog::getColor(m_ui->textEdit->textColor(), this); - if (!col.isValid()) - return; + QColor col = QColorDialog::getColor(m_ui->textEdit->textColor(), this); + if (!col.isValid()) + return; - QTextCharFormat fmt; - if (m_ui->textEdit->document()->isEmpty()) - { - fmt.setFontItalic(m_ui->pbItalic->isChecked()); - fmt.setFontUnderline(m_ui->pbUnderline->isChecked()); - fmt.setFontWeight(m_ui->pbBold->isChecked() ? QFont::Bold : QFont::Normal); + QTextCharFormat fmt; + if (m_ui->textEdit->document()->isEmpty()) + { + fmt.setFontItalic(m_ui->pbItalic->isChecked()); + fmt.setFontUnderline(m_ui->pbUnderline->isChecked()); + fmt.setFontWeight(m_ui->pbBold->isChecked() ? QFont::Bold : QFont::Normal); - const QString &f = m_ui->cbFonts->currentText(); - fmt.setFontFamily(f); - fmt.setFontFamilies({f}); - const qreal pointSize = (m_ui->cbFontSize->currentText().toFloat() > 0 ? m_ui->cbFontSize->currentText().toFloat() : 11); - fmt.setFontPointSize(pointSize); - } - fmt.setForeground(col); - slotMergeFormatOnWordOrSelection(fmt); - slotTextColorChanged(col); + const QString& f = m_ui->cbFonts->currentText(); + fmt.setFontFamily(f); + fmt.setFontFamilies({f}); + const qreal pointSize = + (m_ui->cbFontSize->currentText().toFloat() > 0 ? m_ui->cbFontSize->currentText().toFloat() : 11); + fmt.setFontPointSize(pointSize); + } + fmt.setForeground(col); + slotMergeFormatOnWordOrSelection(fmt); + slotTextColorChanged(col); } void LtsTextEditor::slotBackgroundColor() { - QColor col = QColorDialog::getColor(m_backgroundColor.isValid() ? m_backgroundColor : Qt::white, this); - if (!col.isValid()) - return; + QColor col = QColorDialog::getColor(m_backgroundColor.isValid() ? m_backgroundColor : Qt::white, this); + if (!col.isValid()) + return; - m_backgroundColor = col; - slotBackgroundColorChanged(m_backgroundColor); - emit backgroundColorChanged(m_backgroundColor); + m_backgroundColor = col; + slotBackgroundColorChanged(m_backgroundColor); + emit backgroundColorChanged(m_backgroundColor); } - -void LtsTextEditor::slotCurrentCharFormatChanged(const QTextCharFormat &format) +void LtsTextEditor::slotCurrentCharFormatChanged(const QTextCharFormat& format) { - slotFontChanged(format.font()); - slotTextColorChanged(format.foreground().color()); + slotFontChanged(format.font()); + slotTextColorChanged(format.foreground().color()); } - -void LtsTextEditor::slotFontChanged(const QFont &f) +void LtsTextEditor::slotFontChanged(const QFont& f) { - m_ui->cbFonts->setCurrentIndex(m_ui->cbFonts->findText(f.family())); + m_ui->cbFonts->setCurrentIndex(m_ui->cbFonts->findText(f.family())); - QSignalBlocker comboBoxsignalBlocker(m_ui->cbFontSize); - QSignalBlocker lineEditSignalBlocker(m_ui->cbFontSize->lineEdit()); - QString fontSizeString = QString::number(f.pointSize()); - int32_t fontSizeIndex = m_ui->cbFontSize->findText(fontSizeString); + QSignalBlocker comboBoxsignalBlocker(m_ui->cbFontSize); + QSignalBlocker lineEditSignalBlocker(m_ui->cbFontSize->lineEdit()); + QString fontSizeString = QString::number(f.pointSize()); + int32_t fontSizeIndex = m_ui->cbFontSize->findText(fontSizeString); - if (fontSizeIndex >= 0) - m_ui->cbFontSize->setCurrentIndex(fontSizeIndex); - else if (m_ui->cbFontSize->currentText() != fontSizeString) - m_ui->cbFontSize->setCurrentText(fontSizeString); + if (fontSizeIndex >= 0) + m_ui->cbFontSize->setCurrentIndex(fontSizeIndex); + else if (m_ui->cbFontSize->currentText() != fontSizeString) + m_ui->cbFontSize->setCurrentText(fontSizeString); - m_ui->pbBold->setChecked(f.bold()); - m_ui->pbItalic->setChecked(f.italic()); - m_ui->pbUnderline->setChecked(f.underline()); + m_ui->pbBold->setChecked(f.bold()); + m_ui->pbItalic->setChecked(f.italic()); + m_ui->pbUnderline->setChecked(f.underline()); } - -void LtsTextEditor::slotMergeFormatOnWordOrSelection(const QTextCharFormat &format) +void LtsTextEditor::slotMergeFormatOnWordOrSelection(const QTextCharFormat& format) { - QTextCursor cursor = m_ui->textEdit->textCursor(); - if (!cursor.hasSelection()) - cursor.select(QTextCursor::WordUnderCursor); + QTextCursor cursor = m_ui->textEdit->textCursor(); + if (!cursor.hasSelection()) + cursor.select(QTextCursor::WordUnderCursor); - cursor.mergeCharFormat(format); - - - if (m_ui->textEdit->document()->isEmpty()) - m_ui->textEdit->setTextCursor(cursor); + cursor.mergeCharFormat(format); + + if (m_ui->textEdit->document()->isEmpty()) + m_ui->textEdit->setTextCursor(cursor); } - -void LtsTextEditor::slotTextColorChanged(const QColor &c) +void LtsTextEditor::slotTextColorChanged(const QColor& c) { - QPixmap pix(32, 32); - pix.fill(c); - m_ui->pbTextColor->setIcon(pix); - m_foregroundColor = c; + QPixmap pix(32, 32); + pix.fill(c); + m_ui->pbTextColor->setIcon(pix); + m_foregroundColor = c; } - -void LtsTextEditor::slotBackgroundColorChanged(const QColor &bgColor) +void LtsTextEditor::slotBackgroundColorChanged(const QColor& bgColor) { - QPixmap pix(32, 32); - pix.fill(bgColor); - m_ui->pbBackgroundColor->setIcon(pix); + QPixmap pix(32, 32); + pix.fill(bgColor); + m_ui->pbBackgroundColor->setIcon(pix); } - void LtsTextEditor::slotTextAlign() { - QToolButton *b = qobject_cast(sender()); + QToolButton* b = qobject_cast(sender()); - if (b == nullptr) - return; + if (b == nullptr) + return; - if (b == m_ui->pbAlignLeft) - m_ui->textEdit->setAlignment(Qt::AlignLeft | Qt::AlignAbsolute); - else if (b == m_ui->pbAlignCenter) - m_ui->textEdit->setAlignment(Qt::AlignHCenter); - else if (b == m_ui->pbAlignRight) - m_ui->textEdit->setAlignment(Qt::AlignRight | Qt::AlignAbsolute); - else if (b == m_ui->pbAlignJustify) - m_ui->textEdit->setAlignment(Qt::AlignJustify); + if (b == m_ui->pbAlignLeft) + m_ui->textEdit->setAlignment(Qt::AlignLeft | Qt::AlignAbsolute); + else if (b == m_ui->pbAlignCenter) + m_ui->textEdit->setAlignment(Qt::AlignHCenter); + else if (b == m_ui->pbAlignRight) + m_ui->textEdit->setAlignment(Qt::AlignRight | Qt::AlignAbsolute); + else if (b == m_ui->pbAlignJustify) + m_ui->textEdit->setAlignment(Qt::AlignJustify); } - void LtsTextEditor::slotAlignmentChanged() { - auto a = m_ui->textEdit->alignment(); + auto a = m_ui->textEdit->alignment(); - if (a & Qt::AlignLeft) - m_ui->pbAlignLeft->setChecked(true); - if (a & Qt::AlignHCenter) - m_ui->pbAlignCenter->setChecked(true); - if (a & Qt::AlignRight) - m_ui->pbAlignRight->setChecked(true); - if (a & Qt::AlignJustify) - m_ui->pbAlignJustify->setChecked(true); + if (a & Qt::AlignLeft) + m_ui->pbAlignLeft->setChecked(true); + if (a & Qt::AlignHCenter) + m_ui->pbAlignCenter->setChecked(true); + if (a & Qt::AlignRight) + m_ui->pbAlignRight->setChecked(true); + if (a & Qt::AlignJustify) + m_ui->pbAlignJustify->setChecked(true); } - void LtsTextEditor::slotClipboardDataChanged() { - if (const QMimeData *md = QApplication::clipboard()->mimeData()) - m_ui->pbPaste->setEnabled(md->hasText()); + if (const QMimeData* md = QApplication::clipboard()->mimeData()) + m_ui->pbPaste->setEnabled(md->hasText()); } -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_editor2.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_editor2.cpp old mode 100755 new mode 100644 index 0a0540c85..6be1a2d21 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_editor2.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_editor2.cpp @@ -1,33 +1,31 @@ - - #include "lts_text_editor2.h" #include +#include #include #include +#include #include #include -#include #include #include #include +#include #include #include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include #include #include +#include +#include +#include +#include +#include +#include +#include #if defined(QT_PRINTSUPPORT_LIB) #include #if QT_CONFIG(printer) @@ -41,880 +39,902 @@ #endif #endif - #include #ifdef Q_OS_MAC -inline QString rsrcPath(){ QStringLiteral(":/images/mac");} +inline QString rsrcPath() +{ + QStringLiteral(":/images/mac"); +} #else -inline QString rsrcPath(){return QStringLiteral(":/images/win");} +inline QString rsrcPath() +{ + return QStringLiteral(":/images/win"); +} #endif namespace LtsWidgets { -LtsTextEditor2::LtsTextEditor2(QWidget *parent) - : QMainWindow(parent) +LtsTextEditor2::LtsTextEditor2(QWidget* parent) : QMainWindow(parent) { - setWindowFlags(Qt::CustomizeWindowHint ); - setWindowTitle(QCoreApplication::applicationName()); + setWindowFlags(Qt::CustomizeWindowHint); + setWindowTitle(QCoreApplication::applicationName()); - m_textEdit = new QTextEdit(this); - connect(m_textEdit, &QTextEdit::currentCharFormatChanged, - this, &LtsTextEditor2::currentCharFormatChanged); - connect(m_textEdit, &QTextEdit::cursorPositionChanged, - this, &LtsTextEditor2::cursorPositionChanged); - setCentralWidget(m_textEdit); + m_textEdit = new QTextEdit(this); + connect(m_textEdit, &QTextEdit::currentCharFormatChanged, this, &LtsTextEditor2::currentCharFormatChanged); + connect(m_textEdit, &QTextEdit::cursorPositionChanged, this, &LtsTextEditor2::cursorPositionChanged); + setCentralWidget(m_textEdit); - setToolButtonStyle(Qt::ToolButtonFollowStyle); - setupFileActions(); - setupEditActions(); - setupTextActions(); + setToolButtonStyle(Qt::ToolButtonFollowStyle); + setupFileActions(); + setupEditActions(); + setupTextActions(); - { - QMenu *helpMenu = menuBar()->addMenu(tr("Help")); - helpMenu->addAction(tr("About"), this, &LtsTextEditor2::about); - helpMenu->addAction(tr("About &Qt"), qApp, &QApplication::aboutQt); - } + { + QMenu* helpMenu = menuBar()->addMenu(tr("Help")); + helpMenu->addAction(tr("About"), this, &LtsTextEditor2::about); + helpMenu->addAction(tr("About &Qt"), qApp, &QApplication::aboutQt); + } - QFont textFont(QStringLiteral("Helvetica")); - textFont.setStyleHint(QFont::SansSerif); - m_textEdit->setFont(textFont); - fontChanged(m_textEdit->font()); - colorChanged(m_textEdit->textColor()); - alignmentChanged(m_textEdit->alignment()); + QFont textFont(QStringLiteral("Helvetica")); + textFont.setStyleHint(QFont::SansSerif); + m_textEdit->setFont(textFont); + fontChanged(m_textEdit->font()); + colorChanged(m_textEdit->textColor()); + alignmentChanged(m_textEdit->alignment()); - connect(m_textEdit->document(), &QTextDocument::modificationChanged, - m_actionSave, &QAction::setEnabled); - connect(m_textEdit->document(), &QTextDocument::modificationChanged, - this, &QWidget::setWindowModified); - connect(m_textEdit->document(), &QTextDocument::undoAvailable, - m_actionUndo, &QAction::setEnabled); - connect(m_textEdit->document(), &QTextDocument::redoAvailable, - m_actionRedo, &QAction::setEnabled); + connect(m_textEdit->document(), &QTextDocument::modificationChanged, m_actionSave, &QAction::setEnabled); + connect(m_textEdit->document(), &QTextDocument::modificationChanged, this, &QWidget::setWindowModified); + connect(m_textEdit->document(), &QTextDocument::undoAvailable, m_actionUndo, &QAction::setEnabled); + connect(m_textEdit->document(), &QTextDocument::redoAvailable, m_actionRedo, &QAction::setEnabled); - setWindowModified(m_textEdit->document()->isModified()); - m_actionSave->setEnabled(m_textEdit->document()->isModified()); - m_actionUndo->setEnabled(m_textEdit->document()->isUndoAvailable()); - m_actionRedo->setEnabled(m_textEdit->document()->isRedoAvailable()); + setWindowModified(m_textEdit->document()->isModified()); + m_actionSave->setEnabled(m_textEdit->document()->isModified()); + m_actionUndo->setEnabled(m_textEdit->document()->isUndoAvailable()); + m_actionRedo->setEnabled(m_textEdit->document()->isRedoAvailable()); #ifndef QT_NO_CLIPBOARD - m_actionCut->setEnabled(false); - connect(m_textEdit, &QTextEdit::copyAvailable, m_actionCut, &QAction::setEnabled); - m_actionCopy->setEnabled(false); - connect(m_textEdit, &QTextEdit::copyAvailable, m_actionCopy, &QAction::setEnabled); + m_actionCut->setEnabled(false); + connect(m_textEdit, &QTextEdit::copyAvailable, m_actionCut, &QAction::setEnabled); + m_actionCopy->setEnabled(false); + connect(m_textEdit, &QTextEdit::copyAvailable, m_actionCopy, &QAction::setEnabled); - connect(QApplication::clipboard(), &QClipboard::dataChanged, this, &LtsTextEditor2::clipboardDataChanged); + connect(QApplication::clipboard(), &QClipboard::dataChanged, this, &LtsTextEditor2::clipboardDataChanged); #endif - m_textEdit->setFocus(); - setCurrentFileName(QString()); + m_textEdit->setFocus(); + setCurrentFileName(QString()); - this->menuBar()->hide(); - m_actionSave->setVisible(false); - m_actionOpen->setVisible(false); - m_actionQuit->setVisible(false); - m_actionSaveAs->setVisible(false); - m_actionNew->setVisible(false); + this->menuBar()->hide(); + m_actionSave->setVisible(false); + m_actionOpen->setVisible(false); + m_actionQuit->setVisible(false); + m_actionSaveAs->setVisible(false); + m_actionNew->setVisible(false); #if defined(QT_PRINTSUPPORT_LIB) && QT_CONFIG(printer) - actionPrint->setVisible(false); - actionPreview->setVisible(false); - actionExport->setVisible(false); + actionPrint->setVisible(false); + actionPreview->setVisible(false); + actionExport->setVisible(false); #endif - m_actionToggleCheckState->setVisible(false); - m_actionToggleCheckState->setVisible(false); - m_actionIndentLess->setVisible(false); - m_actionIndentMore->setVisible(false); - m_comboStyleAction->setVisible(false); - m_actionToggleCheckState->setVisible(false); - - + m_actionToggleCheckState->setVisible(false); + m_actionToggleCheckState->setVisible(false); + m_actionIndentLess->setVisible(false); + m_actionIndentMore->setVisible(false); + m_comboStyleAction->setVisible(false); + m_actionToggleCheckState->setVisible(false); } -LtsTextEditor2::~LtsTextEditor2() +LtsTextEditor2::~LtsTextEditor2() {} + +QTextEdit* LtsTextEditor2::textEdit() { - + return m_textEdit; } -QTextEdit *LtsTextEditor2::textEdit() -{ - return m_textEdit; -} QColor LtsTextEditor2::backgroundColor() const { - return m_backgroundColor; + return m_backgroundColor; } -void LtsTextEditor2::setInitialBackgroundColor(const QColor &bgColor) +void LtsTextEditor2::setInitialBackgroundColor(const QColor& bgColor) { - if (bgColor.isValid()) - m_backgroundColor = bgColor; - slotBackgroundColorChanged(m_backgroundColor); + if (bgColor.isValid()) + m_backgroundColor = bgColor; + slotBackgroundColorChanged(m_backgroundColor); } + void LtsTextEditor2::enableBackgroundColor(bool onOff) { - m_actionBackgroundColor->setVisible(onOff); + m_actionBackgroundColor->setVisible(onOff); } - - -void LtsTextEditor2::slotBackgroundColorChanged(const QColor &bgColor) +void LtsTextEditor2::slotBackgroundColorChanged(const QColor& bgColor) { - QPixmap pix(16, 16); - pix.fill(bgColor); - m_actionBackgroundColor->setIcon(pix); + QPixmap pix(16, 16); + pix.fill(bgColor); + m_actionBackgroundColor->setIcon(pix); } + void LtsTextEditor2::slotBackgroundColor() { - QColor col = QColorDialog::getColor(m_backgroundColor.isValid() ? m_backgroundColor : Qt::white, this); - if (!col.isValid()) - return; + QColor col = QColorDialog::getColor(m_backgroundColor.isValid() ? m_backgroundColor : Qt::white, this); + if (!col.isValid()) + return; - m_backgroundColor = col; - slotBackgroundColorChanged(m_backgroundColor); - emit backgroundColorChanged(m_backgroundColor); + m_backgroundColor = col; + slotBackgroundColorChanged(m_backgroundColor); + emit backgroundColorChanged(m_backgroundColor); } - void LtsTextEditor2::setupFileActions() { - QToolBar *tb = addToolBar(tr("File Actions")); - QMenu *menu = menuBar()->addMenu(tr("&File")); + QToolBar* tb = addToolBar(tr("File Actions")); + QMenu* menu = menuBar()->addMenu(tr("&File")); - const QIcon newIcon = QIcon::fromTheme(QStringLiteral("document-new"), QIcon(rsrcPath() + QStringLiteral("/filenew.png"))); - m_actionNew = menu->addAction(newIcon, tr("&New"), this, &LtsTextEditor2::onFileNew); - tb->addAction(m_actionNew); - m_actionNew->setPriority(QAction::LowPriority); - m_actionNew->setShortcut(QKeySequence::New); + const QIcon newIcon = + QIcon::fromTheme(QStringLiteral("document-new"), QIcon(rsrcPath() + QStringLiteral("/filenew.png"))); + m_actionNew = menu->addAction(newIcon, tr("&New"), this, &LtsTextEditor2::onFileNew); + tb->addAction(m_actionNew); + m_actionNew->setPriority(QAction::LowPriority); + m_actionNew->setShortcut(QKeySequence::New); - const QIcon openIcon = QIcon::fromTheme(QStringLiteral("document-open"), QIcon(rsrcPath() + QStringLiteral("/fileopen.png"))); - m_actionOpen = menu->addAction(openIcon, tr("&Open..."), this, &LtsTextEditor2::onFileOpen); - m_actionOpen->setShortcut(QKeySequence::Open); - tb->addAction(m_actionOpen); + const QIcon openIcon = + QIcon::fromTheme(QStringLiteral("document-open"), QIcon(rsrcPath() + QStringLiteral("/fileopen.png"))); + m_actionOpen = menu->addAction(openIcon, tr("&Open..."), this, &LtsTextEditor2::onFileOpen); + m_actionOpen->setShortcut(QKeySequence::Open); + tb->addAction(m_actionOpen); - menu->addSeparator(); + menu->addSeparator(); - const QIcon saveIcon = QIcon::fromTheme(QStringLiteral("document-save"), QIcon(rsrcPath()+ QStringLiteral("/filesave.png"))); - m_actionSave = menu->addAction(saveIcon, tr("&Save"), this, &LtsTextEditor2::onFileSave); - m_actionSave->setShortcut(QKeySequence::Save); - m_actionSave->setEnabled(false); - tb->addAction(m_actionSave); + const QIcon saveIcon = + QIcon::fromTheme(QStringLiteral("document-save"), QIcon(rsrcPath() + QStringLiteral("/filesave.png"))); + m_actionSave = menu->addAction(saveIcon, tr("&Save"), this, &LtsTextEditor2::onFileSave); + m_actionSave->setShortcut(QKeySequence::Save); + m_actionSave->setEnabled(false); + tb->addAction(m_actionSave); - m_actionSaveAs = menu->addAction(tr("Save &As..."), this, &LtsTextEditor2::onFileSaveAs); - m_actionSaveAs->setPriority(QAction::LowPriority); - menu->addSeparator(); + m_actionSaveAs = menu->addAction(tr("Save &As..."), this, &LtsTextEditor2::onFileSaveAs); + m_actionSaveAs->setPriority(QAction::LowPriority); + menu->addSeparator(); #if defined(QT_PRINTSUPPORT_LIB) && QT_CONFIG(printer) - const QIcon printIcon = QIcon::fromTheme(QStringLiteral("document-print"), QIcon(rsrcPath()+ QStringLiteral("/fileprint.png"))); - actionPrint = menu->addAction(printIcon, tr("&Print..."), this, &LtsTextEditor2::filePrint); - actionPrint->setPriority(QAction::LowPriority); - actionPrint->setShortcut(QKeySequence::Print); - tb->addAction(actionPrint); + const QIcon printIcon = + QIcon::fromTheme(QStringLiteral("document-print"), QIcon(rsrcPath() + QStringLiteral("/fileprint.png"))); + actionPrint = menu->addAction(printIcon, tr("&Print..."), this, &LtsTextEditor2::filePrint); + actionPrint->setPriority(QAction::LowPriority); + actionPrint->setShortcut(QKeySequence::Print); + tb->addAction(actionPrint); - const QIcon filePrintIcon = QIcon::fromTheme(QStringLiteral("fileprint"), QIcon(rsrcPath()+ QStringLiteral("/fileprint.png"))); - actionPreview = menu->addAction(filePrintIcon, tr("Print Preview..."), this, &LtsTextEditor2::filePrintPreview); + const QIcon filePrintIcon = + QIcon::fromTheme(QStringLiteral("fileprint"), QIcon(rsrcPath() + QStringLiteral("/fileprint.png"))); + actionPreview = menu->addAction(filePrintIcon, tr("Print Preview..."), this, &LtsTextEditor2::filePrintPreview); - const QIcon exportPdfIcon = QIcon::fromTheme(QStringLiteral("exportpdf"), QIcon(rsrcPath()+ QStringLiteral("/exportpdf.png"))); - actionExport = menu->addAction(exportPdfIcon, tr("&Export PDF..."), this, &LtsTextEditor2::filePrintPdf); - actionExport->setPriority(QAction::LowPriority); - actionExport->setShortcut(Qt::CTRL + Qt::Key_D); - tb->addAction(actionExport); + const QIcon exportPdfIcon = + QIcon::fromTheme(QStringLiteral("exportpdf"), QIcon(rsrcPath() + QStringLiteral("/exportpdf.png"))); + actionExport = menu->addAction(exportPdfIcon, tr("&Export PDF..."), this, &LtsTextEditor2::filePrintPdf); + actionExport->setPriority(QAction::LowPriority); + actionExport->setShortcut(Qt::CTRL + Qt::Key_D); + tb->addAction(actionExport); - menu->addSeparator(); + menu->addSeparator(); #endif - m_actionQuit = menu->addAction(tr("&Quit"), this, &QWidget::close); - m_actionQuit->setShortcut(Qt::CTRL + Qt::Key_Q); + m_actionQuit = menu->addAction(tr("&Quit"), this, &QWidget::close); + m_actionQuit->setShortcut(Qt::CTRL + Qt::Key_Q); } void LtsTextEditor2::setupEditActions() { - QToolBar *tb = addToolBar(tr("Edit Actions")); - QMenu *menu = menuBar()->addMenu(tr("&Edit")); + QToolBar* tb = addToolBar(tr("Edit Actions")); + QMenu* menu = menuBar()->addMenu(tr("&Edit")); - const QIcon undoIcon = QIcon::fromTheme(QStringLiteral("icon:undo.svg")); - m_actionUndo = menu->addAction(undoIcon, {}, m_textEdit, &QTextEdit::undo); - m_actionUndo->setToolTip(tr("&Undo")); - m_actionUndo->setShortcut(QKeySequence::Undo); - tb->addAction(m_actionUndo); + const QIcon undoIcon = QIcon::fromTheme(QStringLiteral("icon:undo.svg")); + m_actionUndo = menu->addAction(undoIcon, {}, m_textEdit, &QTextEdit::undo); + m_actionUndo->setToolTip(tr("&Undo")); + m_actionUndo->setShortcut(QKeySequence::Undo); + tb->addAction(m_actionUndo); - const QIcon redoIcon = QIcon::fromTheme(QStringLiteral("icon:redo.svg")); - m_actionRedo = menu->addAction(redoIcon, tr("&Redo"), m_textEdit, &QTextEdit::redo); - m_actionRedo->setPriority(QAction::LowPriority); - m_actionRedo->setShortcut(QKeySequence::Redo); - tb->addAction(m_actionRedo); - menu->addSeparator(); + const QIcon redoIcon = QIcon::fromTheme(QStringLiteral("icon:redo.svg")); + m_actionRedo = menu->addAction(redoIcon, tr("&Redo"), m_textEdit, &QTextEdit::redo); + m_actionRedo->setPriority(QAction::LowPriority); + m_actionRedo->setShortcut(QKeySequence::Redo); + tb->addAction(m_actionRedo); + menu->addSeparator(); #ifndef QT_NO_CLIPBOARD - const QIcon cutIcon = QIcon::fromTheme(QStringLiteral("icon:edit-cut.svg")); - m_actionCut = menu->addAction(cutIcon, tr("Cu&t"), m_textEdit, &QTextEdit::cut); - m_actionCut->setPriority(QAction::LowPriority); - m_actionCut->setShortcut(QKeySequence::Cut); - tb->addAction(m_actionCut); + const QIcon cutIcon = QIcon::fromTheme(QStringLiteral("icon:edit-cut.svg")); + m_actionCut = menu->addAction(cutIcon, tr("Cu&t"), m_textEdit, &QTextEdit::cut); + m_actionCut->setPriority(QAction::LowPriority); + m_actionCut->setShortcut(QKeySequence::Cut); + tb->addAction(m_actionCut); - const QIcon copyIcon = QIcon::fromTheme(QStringLiteral("icon:edit-copy.svg")); - m_actionCopy = menu->addAction(copyIcon, tr("&Copy"), m_textEdit, &QTextEdit::copy); - m_actionCopy->setPriority(QAction::LowPriority); - m_actionCopy->setShortcut(QKeySequence::Copy); - tb->addAction(m_actionCopy); + const QIcon copyIcon = QIcon::fromTheme(QStringLiteral("icon:edit-copy.svg")); + m_actionCopy = menu->addAction(copyIcon, tr("&Copy"), m_textEdit, &QTextEdit::copy); + m_actionCopy->setPriority(QAction::LowPriority); + m_actionCopy->setShortcut(QKeySequence::Copy); + tb->addAction(m_actionCopy); - const QIcon pasteIcon = QIcon::fromTheme(QStringLiteral("icon:edit-paste.svg")); - m_actionPaste = menu->addAction(pasteIcon, tr("&Paste"), m_textEdit, &QTextEdit::paste); - m_actionPaste->setPriority(QAction::LowPriority); - m_actionPaste->setShortcut(QKeySequence::Paste); - tb->addAction(m_actionPaste); - if (const QMimeData *md = QApplication::clipboard()->mimeData()) - m_actionPaste->setEnabled(md->hasText()); + const QIcon pasteIcon = QIcon::fromTheme(QStringLiteral("icon:edit-paste.svg")); + m_actionPaste = menu->addAction(pasteIcon, tr("&Paste"), m_textEdit, &QTextEdit::paste); + m_actionPaste->setPriority(QAction::LowPriority); + m_actionPaste->setShortcut(QKeySequence::Paste); + tb->addAction(m_actionPaste); + if (const QMimeData* md = QApplication::clipboard()->mimeData()) + m_actionPaste->setEnabled(md->hasText()); #endif } void LtsTextEditor2::setupTextActions() { - QToolBar *tb = addToolBar(tr("Format Actions")); - QMenu *menu = menuBar()->addMenu(tr("F&ormat")); + QToolBar* tb = addToolBar(tr("Format Actions")); + QMenu* menu = menuBar()->addMenu(tr("F&ormat")); - const QIcon boldIcon = QIcon::fromTheme(QStringLiteral(":icons/22x22/format-text-bold.png")); - m_actionTextBold = menu->addAction(boldIcon, tr("&Bold"), this, &LtsTextEditor2::onTextBold); - m_actionTextBold->setShortcut(Qt::CTRL + Qt::Key_B); - m_actionTextBold->setPriority(QAction::LowPriority); - QFont bold; - bold.setBold(true); - m_actionTextBold->setFont(bold); - tb->addAction(m_actionTextBold); - m_actionTextBold->setCheckable(true); + const QIcon boldIcon = QIcon::fromTheme(QStringLiteral(":icons/22x22/format-text-bold.png")); + m_actionTextBold = menu->addAction(boldIcon, tr("&Bold"), this, &LtsTextEditor2::onTextBold); + m_actionTextBold->setShortcut(Qt::CTRL + Qt::Key_B); + m_actionTextBold->setPriority(QAction::LowPriority); + QFont bold; + bold.setBold(true); + m_actionTextBold->setFont(bold); + tb->addAction(m_actionTextBold); + m_actionTextBold->setCheckable(true); - const QIcon italicIcon = QIcon::fromTheme(QStringLiteral(":icons/22x22/format-text-italic.png")); - m_actionTextItalic = menu->addAction(italicIcon, tr("&Italic"), this, &LtsTextEditor2::onTextItalic); - m_actionTextItalic->setPriority(QAction::LowPriority); - m_actionTextItalic->setShortcut(Qt::CTRL + Qt::Key_I); - QFont italic; - italic.setItalic(true); - m_actionTextItalic->setFont(italic); - tb->addAction(m_actionTextItalic); - m_actionTextItalic->setCheckable(true); + const QIcon italicIcon = QIcon::fromTheme(QStringLiteral(":icons/22x22/format-text-italic.png")); + m_actionTextItalic = menu->addAction(italicIcon, tr("&Italic"), this, &LtsTextEditor2::onTextItalic); + m_actionTextItalic->setPriority(QAction::LowPriority); + m_actionTextItalic->setShortcut(Qt::CTRL + Qt::Key_I); + QFont italic; + italic.setItalic(true); + m_actionTextItalic->setFont(italic); + tb->addAction(m_actionTextItalic); + m_actionTextItalic->setCheckable(true); - const QIcon underlineIcon = QIcon::fromTheme(QStringLiteral(":icons/22x22/format-text-underline.png")); - m_actionTextUnderline = menu->addAction(underlineIcon, tr("&Underline"), this, &LtsTextEditor2::onTextUnderline); - m_actionTextUnderline->setShortcut(Qt::CTRL + Qt::Key_U); - m_actionTextUnderline->setPriority(QAction::LowPriority); - QFont underline; - underline.setUnderline(true); - m_actionTextUnderline->setFont(underline); - tb->addAction(m_actionTextUnderline); - m_actionTextUnderline->setCheckable(true); + const QIcon underlineIcon = QIcon::fromTheme(QStringLiteral(":icons/22x22/format-text-underline.png")); + m_actionTextUnderline = menu->addAction(underlineIcon, tr("&Underline"), this, &LtsTextEditor2::onTextUnderline); + m_actionTextUnderline->setShortcut(Qt::CTRL + Qt::Key_U); + m_actionTextUnderline->setPriority(QAction::LowPriority); + QFont underline; + underline.setUnderline(true); + m_actionTextUnderline->setFont(underline); + tb->addAction(m_actionTextUnderline); + m_actionTextUnderline->setCheckable(true); - menu->addSeparator(); + menu->addSeparator(); - const QIcon leftIcon = QIcon::fromTheme(QStringLiteral(":icons/22x22/format-justify-left.png")); - m_actionAlignLeft = new QAction(leftIcon, tr("&Left"), this); - m_actionAlignLeft->setShortcut(Qt::CTRL + Qt::Key_L); - m_actionAlignLeft->setCheckable(true); - m_actionAlignLeft->setPriority(QAction::LowPriority); - const QIcon centerIcon = QIcon::fromTheme(QStringLiteral(":icons/22x22/format-justify-center.png")); - m_actionAlignCenter = new QAction(centerIcon, tr("C&enter"), this); - m_actionAlignCenter->setShortcut(Qt::CTRL + Qt::Key_E); - m_actionAlignCenter->setCheckable(true); - m_actionAlignCenter->setPriority(QAction::LowPriority); - const QIcon rightIcon = QIcon::fromTheme(QStringLiteral(":icons/22x22/format-justify-right.png")); - m_actionAlignRight = new QAction(rightIcon, tr("&Right"), this); - m_actionAlignRight->setShortcut(Qt::CTRL + Qt::Key_R); - m_actionAlignRight->setCheckable(true); - m_actionAlignRight->setPriority(QAction::LowPriority); - const QIcon fillIcon = QIcon::fromTheme(QStringLiteral(":icons/22x22/format-justify-fill.png")); - m_actionAlignJustify = new QAction(fillIcon, tr("&Justify"), this); - m_actionAlignJustify->setShortcut(Qt::CTRL + Qt::Key_J); - m_actionAlignJustify->setCheckable(true); - m_actionAlignJustify->setPriority(QAction::LowPriority); - const QIcon indentMoreIcon = QIcon::fromTheme(QStringLiteral("format-indent-more"), QIcon(rsrcPath()+ QStringLiteral("/format-indent-more.png"))); - m_actionIndentMore = menu->addAction(indentMoreIcon, tr("&Indent"), this, &LtsTextEditor2::indent); - m_actionIndentMore->setShortcut(Qt::CTRL + Qt::Key_BracketRight); - m_actionIndentMore->setPriority(QAction::LowPriority); - const QIcon indentLessIcon = QIcon::fromTheme(QStringLiteral("format-indent-less"), QIcon(rsrcPath()+ QStringLiteral("/format-indent-less.png"))); - m_actionIndentLess = menu->addAction(indentLessIcon, tr("&Unindent"), this, &LtsTextEditor2::unindent); - m_actionIndentLess->setShortcut(Qt::CTRL + Qt::Key_BracketLeft); - m_actionIndentLess->setPriority(QAction::LowPriority); + const QIcon leftIcon = QIcon::fromTheme(QStringLiteral(":icons/22x22/format-justify-left.png")); + m_actionAlignLeft = new QAction(leftIcon, tr("&Left"), this); + m_actionAlignLeft->setShortcut(Qt::CTRL + Qt::Key_L); + m_actionAlignLeft->setCheckable(true); + m_actionAlignLeft->setPriority(QAction::LowPriority); + const QIcon centerIcon = QIcon::fromTheme(QStringLiteral(":icons/22x22/format-justify-center.png")); + m_actionAlignCenter = new QAction(centerIcon, tr("C&enter"), this); + m_actionAlignCenter->setShortcut(Qt::CTRL + Qt::Key_E); + m_actionAlignCenter->setCheckable(true); + m_actionAlignCenter->setPriority(QAction::LowPriority); + const QIcon rightIcon = QIcon::fromTheme(QStringLiteral(":icons/22x22/format-justify-right.png")); + m_actionAlignRight = new QAction(rightIcon, tr("&Right"), this); + m_actionAlignRight->setShortcut(Qt::CTRL + Qt::Key_R); + m_actionAlignRight->setCheckable(true); + m_actionAlignRight->setPriority(QAction::LowPriority); + const QIcon fillIcon = QIcon::fromTheme(QStringLiteral(":icons/22x22/format-justify-fill.png")); + m_actionAlignJustify = new QAction(fillIcon, tr("&Justify"), this); + m_actionAlignJustify->setShortcut(Qt::CTRL + Qt::Key_J); + m_actionAlignJustify->setCheckable(true); + m_actionAlignJustify->setPriority(QAction::LowPriority); + const QIcon indentMoreIcon = QIcon::fromTheme(QStringLiteral("format-indent-more"), + QIcon(rsrcPath() + QStringLiteral("/format-indent-more.png"))); + m_actionIndentMore = menu->addAction(indentMoreIcon, tr("&Indent"), this, &LtsTextEditor2::indent); + m_actionIndentMore->setShortcut(Qt::CTRL + Qt::Key_BracketRight); + m_actionIndentMore->setPriority(QAction::LowPriority); + const QIcon indentLessIcon = QIcon::fromTheme(QStringLiteral("format-indent-less"), + QIcon(rsrcPath() + QStringLiteral("/format-indent-less.png"))); + m_actionIndentLess = menu->addAction(indentLessIcon, tr("&Unindent"), this, &LtsTextEditor2::unindent); + m_actionIndentLess->setShortcut(Qt::CTRL + Qt::Key_BracketLeft); + m_actionIndentLess->setPriority(QAction::LowPriority); - - QActionGroup *alignGroup = new QActionGroup(this); - connect(alignGroup, &QActionGroup::triggered, this, &LtsTextEditor2::onTextAlign); + QActionGroup* alignGroup = new QActionGroup(this); + connect(alignGroup, &QActionGroup::triggered, this, &LtsTextEditor2::onTextAlign); - if (QApplication::isLeftToRight()) { - alignGroup->addAction(m_actionAlignLeft); - alignGroup->addAction(m_actionAlignCenter); - alignGroup->addAction(m_actionAlignRight); - } else { - alignGroup->addAction(m_actionAlignRight); - alignGroup->addAction(m_actionAlignCenter); - alignGroup->addAction(m_actionAlignLeft); - } - alignGroup->addAction(m_actionAlignJustify); + if (QApplication::isLeftToRight()) + { + alignGroup->addAction(m_actionAlignLeft); + alignGroup->addAction(m_actionAlignCenter); + alignGroup->addAction(m_actionAlignRight); + } + else + { + alignGroup->addAction(m_actionAlignRight); + alignGroup->addAction(m_actionAlignCenter); + alignGroup->addAction(m_actionAlignLeft); + } + alignGroup->addAction(m_actionAlignJustify); - tb->addActions(alignGroup->actions()); - menu->addActions(alignGroup->actions()); - tb->addAction(m_actionIndentMore); - tb->addAction(m_actionIndentLess); - menu->addAction(m_actionIndentMore); - menu->addAction(m_actionIndentLess); + tb->addActions(alignGroup->actions()); + menu->addActions(alignGroup->actions()); + tb->addAction(m_actionIndentMore); + tb->addAction(m_actionIndentLess); + menu->addAction(m_actionIndentMore); + menu->addAction(m_actionIndentLess); - menu->addSeparator(); + menu->addSeparator(); - QPixmap pix(16, 16); - pix.fill(Qt::black); - m_actionTextColor = menu->addAction(pix, tr("&Color..."), this, &LtsTextEditor2::onTextColor); - m_actionTextColor->setPriority(QAction::LowPriority); - tb->addAction(m_actionTextColor); + QPixmap pix(16, 16); + pix.fill(Qt::black); + m_actionTextColor = menu->addAction(pix, tr("&Color..."), this, &LtsTextEditor2::onTextColor); + m_actionTextColor->setPriority(QAction::LowPriority); + tb->addAction(m_actionTextColor); - QPixmap pix2(16, 16); - pix2.fill(Qt::white); - m_actionBackgroundColor = new QAction(pix2, tr("&Background Color"), this); - m_actionBackgroundColor->setIcon(pix2); - m_actionBackgroundColor->setPriority(QAction::LowPriority); - connect(m_actionBackgroundColor, &QAction::triggered, this, &LtsTextEditor2::slotBackgroundColor); - tb->addAction(m_actionBackgroundColor); - menu->addSeparator(); + QPixmap pix2(16, 16); + pix2.fill(Qt::white); + m_actionBackgroundColor = new QAction(pix2, tr("&Background Color"), this); + m_actionBackgroundColor->setIcon(pix2); + m_actionBackgroundColor->setPriority(QAction::LowPriority); + connect(m_actionBackgroundColor, &QAction::triggered, this, &LtsTextEditor2::slotBackgroundColor); + tb->addAction(m_actionBackgroundColor); + menu->addSeparator(); - const QIcon checkboxIcon = QIcon::fromTheme(QStringLiteral("status-checkbox-checked"), QIcon(rsrcPath()+ QStringLiteral("/checkbox-checked.png"))); - m_actionToggleCheckState = menu->addAction(checkboxIcon, tr("Chec&ked"), this, &LtsTextEditor2::setChecked); - m_actionToggleCheckState->setShortcut(Qt::CTRL + Qt::Key_K); - m_actionToggleCheckState->setCheckable(true); - m_actionToggleCheckState->setPriority(QAction::LowPriority); - tb->addAction(m_actionToggleCheckState); + const QIcon checkboxIcon = QIcon::fromTheme(QStringLiteral("status-checkbox-checked"), + QIcon(rsrcPath() + QStringLiteral("/checkbox-checked.png"))); + m_actionToggleCheckState = menu->addAction(checkboxIcon, tr("Chec&ked"), this, &LtsTextEditor2::setChecked); + m_actionToggleCheckState->setShortcut(Qt::CTRL + Qt::Key_K); + m_actionToggleCheckState->setCheckable(true); + m_actionToggleCheckState->setPriority(QAction::LowPriority); + tb->addAction(m_actionToggleCheckState); - - - - + m_comboStyle = new QComboBox(tb); + m_comboStyleAction = tb->addWidget(m_comboStyle); + m_comboStyle->addItem(QStringLiteral("Standard")); + m_comboStyle->addItem(QStringLiteral("Bullet List (Disc)")); + m_comboStyle->addItem(QStringLiteral("Bullet List (Circle)")); + m_comboStyle->addItem(QStringLiteral("Bullet List (Square)")); + m_comboStyle->addItem(QStringLiteral("Task List (Unchecked)")); + m_comboStyle->addItem(QStringLiteral("Task List (Checked)")); + m_comboStyle->addItem(QStringLiteral("Ordered List (Decimal)")); + m_comboStyle->addItem(QStringLiteral("Ordered List (Alpha lower)")); + m_comboStyle->addItem(QStringLiteral("Ordered List (Alpha upper)")); + m_comboStyle->addItem(QStringLiteral("Ordered List (Roman lower)")); + m_comboStyle->addItem(QStringLiteral("Ordered List (Roman upper)")); + m_comboStyle->addItem(QStringLiteral("Heading 1")); + m_comboStyle->addItem(QStringLiteral("Heading 2")); + m_comboStyle->addItem(QStringLiteral("Heading 3")); + m_comboStyle->addItem(QStringLiteral("Heading 4")); + m_comboStyle->addItem(QStringLiteral("Heading 5")); + m_comboStyle->addItem(QStringLiteral("Heading 6")); - m_comboStyle = new QComboBox(tb); - m_comboStyleAction = tb->addWidget(m_comboStyle); - m_comboStyle->addItem(QStringLiteral("Standard")); - m_comboStyle->addItem(QStringLiteral("Bullet List (Disc)")); - m_comboStyle->addItem(QStringLiteral("Bullet List (Circle)")); - m_comboStyle->addItem(QStringLiteral("Bullet List (Square)")); - m_comboStyle->addItem(QStringLiteral("Task List (Unchecked)")); - m_comboStyle->addItem(QStringLiteral("Task List (Checked)")); - m_comboStyle->addItem(QStringLiteral("Ordered List (Decimal)")); - m_comboStyle->addItem(QStringLiteral("Ordered List (Alpha lower)")); - m_comboStyle->addItem(QStringLiteral("Ordered List (Alpha upper)")); - m_comboStyle->addItem(QStringLiteral("Ordered List (Roman lower)")); - m_comboStyle->addItem(QStringLiteral("Ordered List (Roman upper)")); - m_comboStyle->addItem(QStringLiteral("Heading 1")); - m_comboStyle->addItem(QStringLiteral("Heading 2")); - m_comboStyle->addItem(QStringLiteral("Heading 3")); - m_comboStyle->addItem(QStringLiteral("Heading 4")); - m_comboStyle->addItem(QStringLiteral("Heading 5")); - m_comboStyle->addItem(QStringLiteral("Heading 6")); + connect(m_comboStyle, QOverload::of(&QComboBox::activated), this, &LtsTextEditor2::onTextStyle); - connect(m_comboStyle, QOverload::of(&QComboBox::activated), this, &LtsTextEditor2::onTextStyle); + m_comboFont = new QFontComboBox(tb); + tb->addWidget(m_comboFont); + connect(m_comboFont, &QComboBox::textActivated, this, &LtsTextEditor2::onTextFamily); - m_comboFont = new QFontComboBox(tb); - tb->addWidget(m_comboFont); - connect(m_comboFont, &QComboBox::textActivated, this, &LtsTextEditor2::onTextFamily); + m_comboSize = new QComboBox(tb); + m_comboSize->setObjectName(QStringLiteral("comboSize")); + tb->addWidget(m_comboSize); + m_comboSize->setEditable(true); - m_comboSize = new QComboBox(tb); - m_comboSize->setObjectName(QStringLiteral("comboSize")); - tb->addWidget(m_comboSize); - m_comboSize->setEditable(true); + const QList standardSizes = QFontDatabase::standardSizes(); + for (int size : standardSizes) + m_comboSize->addItem(QString::number(size)); + m_comboSize->setCurrentIndex(standardSizes.indexOf(QApplication::font().pointSize())); - const QList standardSizes = QFontDatabase::standardSizes(); - for (int size : standardSizes) - m_comboSize->addItem(QString::number(size)); - m_comboSize->setCurrentIndex(standardSizes.indexOf(QApplication::font().pointSize())); - - connect(m_comboSize, &QComboBox::textActivated, this, &LtsTextEditor2::onTextSize); + connect(m_comboSize, &QComboBox::textActivated, this, &LtsTextEditor2::onTextSize); } -bool LtsTextEditor2::load(const QString &f) +bool LtsTextEditor2::load(const QString& f) { - if (!QFile::exists(f)) - return false; - QFile file(f); - if (!file.open(QFile::ReadOnly)) - return false; + if (!QFile::exists(f)) + return false; + QFile file(f); + if (!file.open(QFile::ReadOnly)) + return false; - QByteArray data = file.readAll(); - QTextCodec *codec = Qt::codecForHtml(data); - QString str = codec->toUnicode(data); - if (Qt::mightBeRichText(str)) { - QUrl baseUrl = (f.front() == QLatin1Char(':') ? QUrl(f) : QUrl::fromLocalFile(f)).adjusted(QUrl::RemoveFilename); - m_textEdit->document()->setBaseUrl(baseUrl); - m_textEdit->setHtml(str); - } else { -#if QT_CONFIG(textmarkdownreader) - QMimeDatabase db; - if (db.mimeTypeForFileNameAndData(f, data).name() == QStringLiteral("text/markdown")) - m_textEdit->setMarkdown(QString::fromUtf8(data)); + QByteArray data = file.readAll(); + QString str = QString::fromUtf8(data); + if (Qt::mightBeRichText(str)) + { + QUrl baseUrl = + (f.front() == QLatin1Char(':') ? QUrl(f) : QUrl::fromLocalFile(f)).adjusted(QUrl::RemoveFilename); + m_textEdit->document()->setBaseUrl(baseUrl); + m_textEdit->setHtml(str); + } else + { +#if QT_CONFIG(textmarkdownreader) + QMimeDatabase db; + if (db.mimeTypeForFileNameAndData(f, data).name() == QStringLiteral("text/markdown")) + m_textEdit->setMarkdown(QString::fromUtf8(data)); + else #endif - m_textEdit->setPlainText(QString::fromUtf8(data)); - } + m_textEdit->setPlainText(QString::fromUtf8(data)); + } - setCurrentFileName(f); - return true; + setCurrentFileName(f); + return true; } bool LtsTextEditor2::maybeSave() { - if (!m_textEdit->document()->isModified()) - return true; + if (!m_textEdit->document()->isModified()) + return true; - const QMessageBox::StandardButton ret = - QMessageBox::warning(this, QCoreApplication::applicationName(), - tr("The document has been modified.\n" - "Do you want to save your changes?"), - QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); - if (ret == QMessageBox::Save) - return onFileSave(); - else if (ret == QMessageBox::Cancel) - return false; - return true; + const QMessageBox::StandardButton ret = + QMessageBox::warning(this, QCoreApplication::applicationName(), + tr("The document has been modified.\n" + "Do you want to save your changes?"), + QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); + if (ret == QMessageBox::Save) + return onFileSave(); + else if (ret == QMessageBox::Cancel) + return false; + return true; } -void LtsTextEditor2::setCurrentFileName(const QString &fileName) +void LtsTextEditor2::setCurrentFileName(const QString& fileName) { - this->m_fileName = fileName; - m_textEdit->document()->setModified(false); + this->m_fileName = fileName; + m_textEdit->document()->setModified(false); - QString shownName; - if (fileName.isEmpty()) - shownName = QStringLiteral("untitled.txt"); - else - shownName = QFileInfo(fileName).fileName(); + QString shownName; + if (fileName.isEmpty()) + shownName = QStringLiteral("untitled.txt"); + else + shownName = QFileInfo(fileName).fileName(); - setWindowTitle(tr("%1[*] - %2").arg(shownName, QCoreApplication::applicationName())); - setWindowModified(false); + setWindowTitle(tr("%1[*] - %2").arg(shownName, QCoreApplication::applicationName())); + setWindowModified(false); } void LtsTextEditor2::onFileNew() { - if (maybeSave()) { - m_textEdit->clear(); - setCurrentFileName(QString()); - } + if (maybeSave()) + { + m_textEdit->clear(); + setCurrentFileName(QString()); + } } void LtsTextEditor2::onFileOpen() { - QFileDialog fileDialog(this, tr("Open File...")); - fileDialog.setAcceptMode(QFileDialog::AcceptOpen); - fileDialog.setFileMode(QFileDialog::ExistingFile); - fileDialog.setMimeTypeFilters(QStringList() - #if QT_CONFIG(texthtmlparser) - << QStringLiteral("text/html") - #endif - #if QT_CONFIG(textmarkdownreader) + QFileDialog fileDialog(this, tr("Open File...")); + fileDialog.setAcceptMode(QFileDialog::AcceptOpen); + fileDialog.setFileMode(QFileDialog::ExistingFile); + fileDialog.setMimeTypeFilters(QStringList() +#if QT_CONFIG(texthtmlparser) + << QStringLiteral("text/html") +#endif +#if QT_CONFIG(textmarkdownreader) - << QStringLiteral("text/markdown") - #endif - << QStringLiteral("text/plain")); - if (fileDialog.exec() != QDialog::Accepted) - return; - const QStringList &fileNameList = fileDialog.selectedFiles(); - if (fileNameList.isEmpty()) - return; - QString fn = fileNameList.constFirst(); - if (load(fn)) - statusBar()->showMessage(tr("Opened \"%1\"").arg(QDir::toNativeSeparators(fn))); - else - statusBar()->showMessage(tr("Could not open \"%1\"").arg(QDir::toNativeSeparators(fn))); + << QStringLiteral("text/markdown") +#endif + << QStringLiteral("text/plain")); + if (fileDialog.exec() != QDialog::Accepted) + return; + const QStringList& fileNameList = fileDialog.selectedFiles(); + if (fileNameList.isEmpty()) + return; + QString fn = fileNameList.constFirst(); + if (load(fn)) + statusBar()->showMessage(tr("Opened \"%1\"").arg(QDir::toNativeSeparators(fn))); + else + statusBar()->showMessage(tr("Could not open \"%1\"").arg(QDir::toNativeSeparators(fn))); } bool LtsTextEditor2::onFileSave() { - if (m_fileName.isEmpty()) - return onFileSaveAs(); - if (m_fileName.startsWith(QStringLiteral(":/"))) - return onFileSaveAs(); + if (m_fileName.isEmpty()) + return onFileSaveAs(); + if (m_fileName.startsWith(QStringLiteral(":/"))) + return onFileSaveAs(); - QTextDocumentWriter writer(m_fileName); - bool success = writer.write(m_textEdit->document()); - if (success) { - m_textEdit->document()->setModified(false); - statusBar()->showMessage(tr("Wrote \"%1\"").arg(QDir::toNativeSeparators(m_fileName))); - } else { - statusBar()->showMessage(tr("Could not write to file \"%1\"") - .arg(QDir::toNativeSeparators(m_fileName))); - } - return success; + QTextDocumentWriter writer(m_fileName); + bool success = writer.write(m_textEdit->document()); + if (success) + { + m_textEdit->document()->setModified(false); + statusBar()->showMessage(tr("Wrote \"%1\"").arg(QDir::toNativeSeparators(m_fileName))); + } + else + { + statusBar()->showMessage(tr("Could not write to file \"%1\"").arg(QDir::toNativeSeparators(m_fileName))); + } + return success; } bool LtsTextEditor2::onFileSaveAs() { - QFileDialog fileDialog(this, tr("Save as...")); - fileDialog.setAcceptMode(QFileDialog::AcceptSave); - QStringList mimeTypes; - mimeTypes << QStringLiteral("text/plain") - #if QT_CONFIG(textodfwriter) - << QStringLiteral("application/vnd.oasis.opendocument.text") - #endif - #if QT_CONFIG(textmarkdownwriter) - << QStringLiteral("text/markdown") - #endif - << QStringLiteral("text/html"); - fileDialog.setMimeTypeFilters(mimeTypes); + QFileDialog fileDialog(this, tr("Save as...")); + fileDialog.setAcceptMode(QFileDialog::AcceptSave); + QStringList mimeTypes; + mimeTypes << QStringLiteral("text/plain") #if QT_CONFIG(textodfwriter) - fileDialog.setDefaultSuffix(QStringLiteral("odt")); + << QStringLiteral("application/vnd.oasis.opendocument.text") #endif - if (fileDialog.exec() != QDialog::Accepted) - return false; - const QStringList &fileNameList = fileDialog.selectedFiles(); - if (fileNameList.isEmpty()) - return false; - QString fn = fileNameList.constFirst(); - setCurrentFileName(fn); - return onFileSave(); +#if QT_CONFIG(textmarkdownwriter) + << QStringLiteral("text/markdown") +#endif + << QStringLiteral("text/html"); + fileDialog.setMimeTypeFilters(mimeTypes); +#if QT_CONFIG(textodfwriter) + fileDialog.setDefaultSuffix(QStringLiteral("odt")); +#endif + if (fileDialog.exec() != QDialog::Accepted) + return false; + const QStringList& fileNameList = fileDialog.selectedFiles(); + if (fileNameList.isEmpty()) + return false; + QString fn = fileNameList.constFirst(); + setCurrentFileName(fn); + return onFileSave(); } void LtsTextEditor2::onFilePrint() { #if defined(QT_PRINTSUPPORT_LIB) && QT_CONFIG(printdialog) - QPrinter printer(QPrinter::HighResolution); - QPrintDialog *dlg = new QPrintDialog(&printer, this); - if (textEdit->textCursor().hasSelection()) - dlg->addEnabledOption(QAbstractPrintDialog::PrintSelection); - dlg->setWindowTitle(tr("Print Document")); - if (dlg->exec() == QDialog::Accepted) - textEdit->print(&printer); - delete dlg; + QPrinter printer(QPrinter::HighResolution); + QPrintDialog* dlg = new QPrintDialog(&printer, this); + if (textEdit->textCursor().hasSelection()) + dlg->addEnabledOption(QAbstractPrintDialog::PrintSelection); + dlg->setWindowTitle(tr("Print Document")); + if (dlg->exec() == QDialog::Accepted) + textEdit->print(&printer); + delete dlg; #endif } void LtsTextEditor2::onFilePrintPreview() { #if defined(QT_PRINTSUPPORT_LIB) && QT_CONFIG(printpreviewdialog) - QPrinter printer(QPrinter::HighResolution); - QPrintPreviewDialog preview(&printer, this); - connect(&preview, &QPrintPreviewDialog::paintRequested, this, &LtsTextEditor2::printPreview); - preview.exec(); + QPrinter printer(QPrinter::HighResolution); + QPrintPreviewDialog preview(&printer, this); + connect(&preview, &QPrintPreviewDialog::paintRequested, this, &LtsTextEditor2::printPreview); + preview.exec(); #endif } -void LtsTextEditor2::printPreview(QPrinter *printer) +void LtsTextEditor2::printPreview(QPrinter* printer) { #if defined(QT_PRINTSUPPORT_LIB) && QT_CONFIG(printer) - textEdit->print(printer); + textEdit->print(printer); #else - Q_UNUSED(printer) + Q_UNUSED(printer) #endif } - void LtsTextEditor2::onFilePrintPdf() { #if defined(QT_PRINTSUPPORT_LIB) && QT_CONFIG(printer) - - QFileDialog fileDialog(this, tr("Export PDF")); - fileDialog.setAcceptMode(QFileDialog::AcceptSave); - fileDialog.setMimeTypeFilters(QStringList(QStringLiteral("application/pdf"))); - fileDialog.setDefaultSuffix(QStringLiteral("pdf")); - if (fileDialog.exec() != QDialog::Accepted) - return; - const QStringList &fileNameList = fileDialog.selectedFiles(); - if (fileNameList.isEmpty()) - return; - QString fileName = fileNameList.constFirst(); - QPrinter printer(QPrinter::HighResolution); - printer.setOutputFormat(QPrinter::PdfFormat); - printer.setOutputFileName(fileName); - textEdit->document()->print(&printer); - statusBar()->showMessage(tr("Exported \"%1\"") - .arg(QDir::toNativeSeparators(fileName))); - + + QFileDialog fileDialog(this, tr("Export PDF")); + fileDialog.setAcceptMode(QFileDialog::AcceptSave); + fileDialog.setMimeTypeFilters(QStringList(QStringLiteral("application/pdf"))); + fileDialog.setDefaultSuffix(QStringLiteral("pdf")); + if (fileDialog.exec() != QDialog::Accepted) + return; + const QStringList& fileNameList = fileDialog.selectedFiles(); + if (fileNameList.isEmpty()) + return; + QString fileName = fileNameList.constFirst(); + QPrinter printer(QPrinter::HighResolution); + printer.setOutputFormat(QPrinter::PdfFormat); + printer.setOutputFileName(fileName); + textEdit->document()->print(&printer); + statusBar()->showMessage(tr("Exported \"%1\"").arg(QDir::toNativeSeparators(fileName))); + #endif } void LtsTextEditor2::onTextBold() { - QTextCharFormat fmt; - fmt.setFontWeight(m_actionTextBold->isChecked() ? QFont::Bold : QFont::Normal); - mergeFormatOnWordOrSelection(fmt); + QTextCharFormat fmt; + fmt.setFontWeight(m_actionTextBold->isChecked() ? QFont::Bold : QFont::Normal); + mergeFormatOnWordOrSelection(fmt); } void LtsTextEditor2::onTextUnderline() { - QTextCharFormat fmt; - fmt.setFontUnderline(m_actionTextUnderline->isChecked()); - mergeFormatOnWordOrSelection(fmt); + QTextCharFormat fmt; + fmt.setFontUnderline(m_actionTextUnderline->isChecked()); + mergeFormatOnWordOrSelection(fmt); } void LtsTextEditor2::onTextItalic() { - QTextCharFormat fmt; - fmt.setFontItalic(m_actionTextItalic->isChecked()); - mergeFormatOnWordOrSelection(fmt); -} - -void LtsTextEditor2::onTextFamily(const QString &f) -{ - QTextCharFormat fmt; - fmt.setFontFamily(f); - mergeFormatOnWordOrSelection(fmt); -} - -void LtsTextEditor2::onTextSize(const QString &p) -{ - qreal pointSize = p.toFloat(); - if (p.toFloat() > 0) { QTextCharFormat fmt; - fmt.setFontPointSize(pointSize); + fmt.setFontItalic(m_actionTextItalic->isChecked()); mergeFormatOnWordOrSelection(fmt); - } +} + +void LtsTextEditor2::onTextFamily(const QString& f) +{ + QTextCharFormat fmt; + fmt.setFontFamily(f); + mergeFormatOnWordOrSelection(fmt); +} + +void LtsTextEditor2::onTextSize(const QString& p) +{ + qreal pointSize = p.toFloat(); + if (p.toFloat() > 0) + { + QTextCharFormat fmt; + fmt.setFontPointSize(pointSize); + mergeFormatOnWordOrSelection(fmt); + } } void LtsTextEditor2::onTextStyle(int styleIndex) { - QTextCursor cursor = m_textEdit->textCursor(); - QTextListFormat::Style style = QTextListFormat::ListStyleUndefined; - QTextBlockFormat::MarkerType marker = QTextBlockFormat::MarkerType::NoMarker; + QTextCursor cursor = m_textEdit->textCursor(); + QTextListFormat::Style style = QTextListFormat::ListStyleUndefined; + QTextBlockFormat::MarkerType marker = QTextBlockFormat::MarkerType::NoMarker; - switch (styleIndex) { - case 1: - style = QTextListFormat::ListDisc; - break; - case 2: - style = QTextListFormat::ListCircle; - break; - case 3: - style = QTextListFormat::ListSquare; - break; - case 4: - if (cursor.currentList()) - style = cursor.currentList()->format().style(); - else - style = QTextListFormat::ListDisc; - marker = QTextBlockFormat::MarkerType::Unchecked; - break; - case 5: - if (cursor.currentList()) - style = cursor.currentList()->format().style(); - else - style = QTextListFormat::ListDisc; - marker = QTextBlockFormat::MarkerType::Checked; - break; - case 6: - style = QTextListFormat::ListDecimal; - break; - case 7: - style = QTextListFormat::ListLowerAlpha; - break; - case 8: - style = QTextListFormat::ListUpperAlpha; - break; - case 9: - style = QTextListFormat::ListLowerRoman; - break; - case 10: - style = QTextListFormat::ListUpperRoman; - break; - default: - break; - } - - cursor.beginEditBlock(); - - QTextBlockFormat blockFmt = cursor.blockFormat(); - - if (style == QTextListFormat::ListStyleUndefined) { - blockFmt.setObjectIndex(-1); - int headingLevel = styleIndex >= 11 ? styleIndex - 11 + 1 : 0; - blockFmt.setHeadingLevel(headingLevel); - cursor.setBlockFormat(blockFmt); - - int sizeAdjustment = headingLevel ? 4 - headingLevel : 0; - QTextCharFormat fmt; - fmt.setFontWeight(headingLevel ? QFont::Bold : QFont::Normal); - fmt.setProperty(QTextFormat::FontSizeAdjustment, sizeAdjustment); - cursor.select(QTextCursor::LineUnderCursor); - cursor.mergeCharFormat(fmt); - m_textEdit->mergeCurrentCharFormat(fmt); - } else { - blockFmt.setMarker(marker); - cursor.setBlockFormat(blockFmt); - QTextListFormat listFmt; - if (cursor.currentList()) { - listFmt = cursor.currentList()->format(); - } else { - listFmt.setIndent(blockFmt.indent() + 1); - blockFmt.setIndent(0); - cursor.setBlockFormat(blockFmt); + switch (styleIndex) + { + case 1: + style = QTextListFormat::ListDisc; + break; + case 2: + style = QTextListFormat::ListCircle; + break; + case 3: + style = QTextListFormat::ListSquare; + break; + case 4: + if (cursor.currentList()) + style = cursor.currentList()->format().style(); + else + style = QTextListFormat::ListDisc; + marker = QTextBlockFormat::MarkerType::Unchecked; + break; + case 5: + if (cursor.currentList()) + style = cursor.currentList()->format().style(); + else + style = QTextListFormat::ListDisc; + marker = QTextBlockFormat::MarkerType::Checked; + break; + case 6: + style = QTextListFormat::ListDecimal; + break; + case 7: + style = QTextListFormat::ListLowerAlpha; + break; + case 8: + style = QTextListFormat::ListUpperAlpha; + break; + case 9: + style = QTextListFormat::ListLowerRoman; + break; + case 10: + style = QTextListFormat::ListUpperRoman; + break; + default: + break; } - listFmt.setStyle(style); - cursor.createList(listFmt); - } - cursor.endEditBlock(); + cursor.beginEditBlock(); + + QTextBlockFormat blockFmt = cursor.blockFormat(); + + if (style == QTextListFormat::ListStyleUndefined) + { + blockFmt.setObjectIndex(-1); + int headingLevel = styleIndex >= 11 ? styleIndex - 11 + 1 : 0; + blockFmt.setHeadingLevel(headingLevel); + cursor.setBlockFormat(blockFmt); + + int sizeAdjustment = headingLevel ? 4 - headingLevel : 0; + QTextCharFormat fmt; + fmt.setFontWeight(headingLevel ? QFont::Bold : QFont::Normal); + fmt.setProperty(QTextFormat::FontSizeAdjustment, sizeAdjustment); + cursor.select(QTextCursor::LineUnderCursor); + cursor.mergeCharFormat(fmt); + m_textEdit->mergeCurrentCharFormat(fmt); + } + else + { + blockFmt.setMarker(marker); + cursor.setBlockFormat(blockFmt); + QTextListFormat listFmt; + if (cursor.currentList()) + { + listFmt = cursor.currentList()->format(); + } + else + { + listFmt.setIndent(blockFmt.indent() + 1); + blockFmt.setIndent(0); + cursor.setBlockFormat(blockFmt); + } + listFmt.setStyle(style); + cursor.createList(listFmt); + } + + cursor.endEditBlock(); } void LtsTextEditor2::onTextColor() { - QColor col = QColorDialog::getColor(m_textEdit->textColor(), this); - if (!col.isValid()) - return; - QTextCharFormat fmt; - fmt.setForeground(col); - mergeFormatOnWordOrSelection(fmt); - colorChanged(col); + QColor col = QColorDialog::getColor(m_textEdit->textColor(), this); + if (!col.isValid()) + return; + QTextCharFormat fmt; + fmt.setForeground(col); + mergeFormatOnWordOrSelection(fmt); + colorChanged(col); } -void LtsTextEditor2::onTextAlign(QAction *a) +void LtsTextEditor2::onTextAlign(QAction* a) { - if (a == m_actionAlignLeft) - m_textEdit->setAlignment(Qt::AlignLeft | Qt::AlignAbsolute); - else if (a == m_actionAlignCenter) - m_textEdit->setAlignment(Qt::AlignHCenter); - else if (a == m_actionAlignRight) - m_textEdit->setAlignment(Qt::AlignRight | Qt::AlignAbsolute); - else if (a == m_actionAlignJustify) - m_textEdit->setAlignment(Qt::AlignJustify); + if (a == m_actionAlignLeft) + m_textEdit->setAlignment(Qt::AlignLeft | Qt::AlignAbsolute); + else if (a == m_actionAlignCenter) + m_textEdit->setAlignment(Qt::AlignHCenter); + else if (a == m_actionAlignRight) + m_textEdit->setAlignment(Qt::AlignRight | Qt::AlignAbsolute); + else if (a == m_actionAlignJustify) + m_textEdit->setAlignment(Qt::AlignJustify); } void LtsTextEditor2::setChecked(bool checked) { - onTextStyle(checked ? 5 : 4); + onTextStyle(checked ? 5 : 4); } void LtsTextEditor2::indent() { - modifyIndentation(1); + modifyIndentation(1); } void LtsTextEditor2::unindent() { - modifyIndentation(-1); + modifyIndentation(-1); } void LtsTextEditor2::modifyIndentation(int amount) { - QTextCursor cursor = m_textEdit->textCursor(); - cursor.beginEditBlock(); - if (cursor.currentList()) { - QTextListFormat listFmt = cursor.currentList()->format(); - - - QTextCursor above(cursor); - above.movePosition(QTextCursor::Up); - if (above.currentList() && listFmt.indent() + amount == above.currentList()->format().indent()) { - above.currentList()->add(cursor.block()); - } else { - listFmt.setIndent(listFmt.indent() + amount); - cursor.createList(listFmt); + QTextCursor cursor = m_textEdit->textCursor(); + cursor.beginEditBlock(); + if (cursor.currentList()) + { + QTextListFormat listFmt = cursor.currentList()->format(); + + QTextCursor above(cursor); + above.movePosition(QTextCursor::Up); + if (above.currentList() && listFmt.indent() + amount == above.currentList()->format().indent()) + { + above.currentList()->add(cursor.block()); + } + else + { + listFmt.setIndent(listFmt.indent() + amount); + cursor.createList(listFmt); + } } - } else { - QTextBlockFormat blockFmt = cursor.blockFormat(); - blockFmt.setIndent(blockFmt.indent() + amount); - cursor.setBlockFormat(blockFmt); - } - cursor.endEditBlock(); + else + { + QTextBlockFormat blockFmt = cursor.blockFormat(); + blockFmt.setIndent(blockFmt.indent() + amount); + cursor.setBlockFormat(blockFmt); + } + cursor.endEditBlock(); } -void LtsTextEditor2::currentCharFormatChanged(const QTextCharFormat &format) +void LtsTextEditor2::currentCharFormatChanged(const QTextCharFormat& format) { - fontChanged(format.font()); - colorChanged(format.foreground().color()); + fontChanged(format.font()); + colorChanged(format.foreground().color()); } void LtsTextEditor2::cursorPositionChanged() { - alignmentChanged(m_textEdit->alignment()); - QTextList *list = m_textEdit->textCursor().currentList(); - if (list) { - switch (list->format().style()) { - case QTextListFormat::ListDisc: - m_comboStyle->setCurrentIndex(1); - break; - case QTextListFormat::ListCircle: - m_comboStyle->setCurrentIndex(2); - break; - case QTextListFormat::ListSquare: - m_comboStyle->setCurrentIndex(3); - break; - case QTextListFormat::ListDecimal: - m_comboStyle->setCurrentIndex(6); - break; - case QTextListFormat::ListLowerAlpha: - m_comboStyle->setCurrentIndex(7); - break; - case QTextListFormat::ListUpperAlpha: - m_comboStyle->setCurrentIndex(8); - break; - case QTextListFormat::ListLowerRoman: - m_comboStyle->setCurrentIndex(9); - break; - case QTextListFormat::ListUpperRoman: - m_comboStyle->setCurrentIndex(10); - break; - default: - m_comboStyle->setCurrentIndex(-1); - break; + alignmentChanged(m_textEdit->alignment()); + QTextList* list = m_textEdit->textCursor().currentList(); + if (list) + { + switch (list->format().style()) + { + case QTextListFormat::ListDisc: + m_comboStyle->setCurrentIndex(1); + break; + case QTextListFormat::ListCircle: + m_comboStyle->setCurrentIndex(2); + break; + case QTextListFormat::ListSquare: + m_comboStyle->setCurrentIndex(3); + break; + case QTextListFormat::ListDecimal: + m_comboStyle->setCurrentIndex(6); + break; + case QTextListFormat::ListLowerAlpha: + m_comboStyle->setCurrentIndex(7); + break; + case QTextListFormat::ListUpperAlpha: + m_comboStyle->setCurrentIndex(8); + break; + case QTextListFormat::ListLowerRoman: + m_comboStyle->setCurrentIndex(9); + break; + case QTextListFormat::ListUpperRoman: + m_comboStyle->setCurrentIndex(10); + break; + default: + m_comboStyle->setCurrentIndex(-1); + break; + } + switch (m_textEdit->textCursor().block().blockFormat().marker()) + { + case QTextBlockFormat::MarkerType::NoMarker: + m_actionToggleCheckState->setChecked(false); + break; + case QTextBlockFormat::MarkerType::Unchecked: + m_comboStyle->setCurrentIndex(4); + m_actionToggleCheckState->setChecked(false); + break; + case QTextBlockFormat::MarkerType::Checked: + m_comboStyle->setCurrentIndex(5); + m_actionToggleCheckState->setChecked(true); + break; + } } - switch (m_textEdit->textCursor().block().blockFormat().marker()) { - case QTextBlockFormat::MarkerType::NoMarker: - m_actionToggleCheckState->setChecked(false); - break; - case QTextBlockFormat::MarkerType::Unchecked: - m_comboStyle->setCurrentIndex(4); - m_actionToggleCheckState->setChecked(false); - break; - case QTextBlockFormat::MarkerType::Checked: - m_comboStyle->setCurrentIndex(5); - m_actionToggleCheckState->setChecked(true); - break; + else + { + int headingLevel = m_textEdit->textCursor().blockFormat().headingLevel(); + m_comboStyle->setCurrentIndex(headingLevel ? headingLevel + 10 : 0); } - } else { - int headingLevel = m_textEdit->textCursor().blockFormat().headingLevel(); - m_comboStyle->setCurrentIndex(headingLevel ? headingLevel + 10 : 0); - } } void LtsTextEditor2::clipboardDataChanged() { #ifndef QT_NO_CLIPBOARD - if (const QMimeData *md = QApplication::clipboard()->mimeData()) - m_actionPaste->setEnabled(md->hasText()); + if (const QMimeData* md = QApplication::clipboard()->mimeData()) + m_actionPaste->setEnabled(md->hasText()); #endif } void LtsTextEditor2::about() { - QMessageBox::about(this, tr("About"), tr("This example demonstrates Qt's " - "rich text editing facilities in action, providing an example " - "document for you to experiment with.")); + QMessageBox::about(this, tr("About"), + tr("This example demonstrates Qt's " + "rich text editing facilities in action, providing an example " + "document for you to experiment with.")); } -void LtsTextEditor2::mergeFormatOnWordOrSelection(const QTextCharFormat &format) +void LtsTextEditor2::mergeFormatOnWordOrSelection(const QTextCharFormat& format) { - QTextCursor cursor = m_textEdit->textCursor(); - if (!cursor.hasSelection()) - cursor.select(QTextCursor::WordUnderCursor); - cursor.mergeCharFormat(format); - m_textEdit->mergeCurrentCharFormat(format); + QTextCursor cursor = m_textEdit->textCursor(); + if (!cursor.hasSelection()) + cursor.select(QTextCursor::WordUnderCursor); + cursor.mergeCharFormat(format); + m_textEdit->mergeCurrentCharFormat(format); } -void LtsTextEditor2::fontChanged(const QFont &f) +void LtsTextEditor2::fontChanged(const QFont& f) { - m_comboFont->setCurrentIndex(m_comboFont->findText(QFontInfo(f).family())); - m_comboSize->setCurrentIndex(m_comboSize->findText(QString::number(f.pointSize()))); - m_actionTextBold->setChecked(f.bold()); - m_actionTextItalic->setChecked(f.italic()); - m_actionTextUnderline->setChecked(f.underline()); + m_comboFont->setCurrentIndex(m_comboFont->findText(QFontInfo(f).family())); + m_comboSize->setCurrentIndex(m_comboSize->findText(QString::number(f.pointSize()))); + m_actionTextBold->setChecked(f.bold()); + m_actionTextItalic->setChecked(f.italic()); + m_actionTextUnderline->setChecked(f.underline()); } -void LtsTextEditor2::colorChanged(const QColor &c) +void LtsTextEditor2::colorChanged(const QColor& c) { - QPixmap pix(16, 16); - pix.fill(c); - m_actionTextColor->setIcon(pix); + QPixmap pix(16, 16); + pix.fill(c); + m_actionTextColor->setIcon(pix); } void LtsTextEditor2::alignmentChanged(Qt::Alignment a) { - if (a & Qt::AlignLeft) - m_actionAlignLeft->setChecked(true); - else if (a & Qt::AlignHCenter) - m_actionAlignCenter->setChecked(true); - else if (a & Qt::AlignRight) - m_actionAlignRight->setChecked(true); - else if (a & Qt::AlignJustify) - m_actionAlignJustify->setChecked(true); + if (a & Qt::AlignLeft) + m_actionAlignLeft->setChecked(true); + else if (a & Qt::AlignHCenter) + m_actionAlignCenter->setChecked(true); + else if (a & Qt::AlignRight) + m_actionAlignRight->setChecked(true); + else if (a & Qt::AlignJustify) + m_actionAlignJustify->setChecked(true); } -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_bar.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_bar.cpp old mode 100755 new mode 100644 index 1bd1fd012..f6d1dd17e --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_bar.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_bar.cpp @@ -1,31 +1,27 @@ - #include "lts_tool_bar.h" using namespace LtsWidgets; -LtsToolBar::LtsToolBar(QWidget *parent) - : QToolBar(parent) +LtsToolBar::LtsToolBar(QWidget* parent) : QToolBar(parent) { - setMaximumHeight(1); - setMinimumHeight(1); + setMaximumHeight(1); + setMinimumHeight(1); } -LtsToolBar::~LtsToolBar() +LtsToolBar::~LtsToolBar() {} + +void LtsToolBar::enterEvent(QEnterEvent* e) { + setMaximumHeight(50); + setMinimumHeight(50); + QToolBar::enterEvent(e); } -void LtsToolBar::enterEvent(QEvent *e) +void LtsToolBar::leaveEvent(QEvent* e) { - setMaximumHeight(50); - setMinimumHeight(50); - QToolBar::enterEvent(e); -} - -void LtsToolBar::leaveEvent(QEvent *e) -{ - setMaximumHeight(1); - setMinimumHeight(1); - QToolBar::leaveEvent(e); + setMaximumHeight(1); + setMinimumHeight(1); + QToolBar::leaveEvent(e); } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_bar.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_bar.h old mode 100755 new mode 100644 index a6042aabc..7f8f2fc04 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_bar.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_bar.h @@ -1,28 +1,25 @@ - #pragma once -#include - -#include #include "ltswidgets_export.h" +#include +#include + namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsToolBar : public QToolBar { - Q_OBJECT -public: - explicit LtsToolBar(QWidget *parent = nullptr); - ~LtsToolBar(); - -protected: - void enterEvent(QEvent *e) override; - void leaveEvent(QEvent *e) override; - + Q_OBJECT + public: + explicit LtsToolBar(QWidget* parent = nullptr); + ~LtsToolBar(); + protected: + void enterEvent(QEnterEvent* e) override; + void leaveEvent(QEvent* e) override; }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_bar_area.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_bar_area.cpp old mode 100755 new mode 100644 index 98f304b38..a10945bcd --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_bar_area.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_bar_area.cpp @@ -1,385 +1,345 @@ - #include "lts_tool_bar_area.h" -#include -#include "ui_lts_tool_bar_area.h" + #include "lts_drag_icon.h" +#include "ui_lts_tool_bar_area.h" #include +#include #include #include #include -#include #include -#include #include - +#include +#include +#include namespace LtsWidgets { - - void ShortCut::clear() { - name.clear(); - identifier.clear(); - icon = nullptr; - shortcut->disconnect(icon); + name.clear(); + identifier.clear(); + icon = nullptr; + shortcut->disconnect(icon); } - - - -LtsToolBarArea::LtsToolBarArea(QWidget *parent) - : QWidget(parent) - , m_dummyLabel(nullptr) - , m_ui(new Ui::LtsToolBarArea) +LtsToolBarArea::LtsToolBarArea(QWidget* parent) : QWidget(parent), m_dummyLabel(nullptr), m_ui(new Ui::LtsToolBarArea) { - m_ui->setupUi(this); + m_ui->setupUi(this); - setAcceptDrops(true); - clearToolBarArea(); + setAcceptDrops(true); + clearToolBarArea(); - - for(int i=Qt::Key_F5; i<=Qt::Key_F12; ++i) - { - ShortCut sc(this); - sc.shortcut->setKey(QKeySequence(i)); - sc.key = i; - m_functionKeys.insert(i, sc); - } + for (int i = Qt::Key_F5; i <= Qt::Key_F12; ++i) + { + ShortCut sc(this); + sc.shortcut->setKey(QKeySequence(i)); + sc.key = i; + m_functionKeys.insert(i, sc); + } } LtsToolBarArea::~LtsToolBarArea() { - delete m_ui; + delete m_ui; } -void LtsToolBarArea::addMenuEntry(LtsDragIcon *entry, LtsDragIcon *after) +void LtsToolBarArea::addMenuEntry(LtsDragIcon* entry, LtsDragIcon* after) { - if (!entry) - return; - - if (m_foreignButtonMap.contains(entry)) - return; - - delete m_dummyLabel; - m_dummyLabel = nullptr; - - bool isInternalMove = false; - LtsDragIcon *foreignDragIcon = entry; - - for (int i = 0; i < m_buttonMap.size(); ++i) - { - if (m_buttonMap.at(i) == entry) - { - isInternalMove = true; - - if (after == nullptr) + if (!entry) return; - m_buttonMap.removeAt(i); - foreignDragIcon = m_foreignButtonMap.at(i); - m_foreignButtonMap.removeAt(i); - m_ui->layToolbar->removeWidget(entry); - break; - } - } - - int index = m_buttonMap.size(); - for(int i = 0; i < m_buttonMap.size(); ++i) - { - if (m_buttonMap.at(i) == after || - m_foreignButtonMap.at(i) == after) + if (m_foreignButtonMap.contains(entry)) + return; + + delete m_dummyLabel; + m_dummyLabel = nullptr; + + bool isInternalMove = false; + LtsDragIcon* foreignDragIcon = entry; + + for (int i = 0; i < m_buttonMap.size(); ++i) { - index = i + 1; - break; + if (m_buttonMap.at(i) == entry) + { + isInternalMove = true; + + if (after == nullptr) + return; + m_buttonMap.removeAt(i); + foreignDragIcon = m_foreignButtonMap.at(i); + m_foreignButtonMap.removeAt(i); + m_ui->layToolbar->removeWidget(entry); + break; + } } - } - - LtsDragIcon *newAction = entry; + int index = m_buttonMap.size(); + for (int i = 0; i < m_buttonMap.size(); ++i) + { + if (m_buttonMap.at(i) == after || m_foreignButtonMap.at(i) == after) + { + index = i + 1; + break; + } + } - if (!isInternalMove) - { - newAction = new LtsDragIcon(this); - newAction->setIcon(entry->icon()); - newAction->setText(entry->text()); - newAction->setContext(entry->context()); - if (!entry->toolTip().isEmpty()) - newAction->setToolTip(entry->toolTip()); - newAction->setIconSize(ButtonSize::eDefault); - newAction->setButtonStyle(ButtonStyle::eIconOnly); - newAction->setIdentifier(entry->identifier()); + LtsDragIcon* newAction = entry; - connect(newAction, &LtsDragIcon::clicked, entry, &LtsDragIcon::clicked); - connect(entry, &LtsDragIcon::destroyed, newAction, - [this, newAction]() { m_buttonMap.removeAll(newAction); newAction->deleteLater(); }); - newAction->setVisible(!entry->text().isEmpty()); - } - newAction->setContextMenuPolicy(Qt::CustomContextMenu); - connect(newAction, &LtsDragIcon::customContextMenuRequested, - this, &LtsToolBarArea::showContextMenu); + if (!isInternalMove) + { + newAction = new LtsDragIcon(this); + newAction->setIcon(entry->icon()); + newAction->setText(entry->text()); + newAction->setContext(entry->context()); + if (!entry->toolTip().isEmpty()) + newAction->setToolTip(entry->toolTip()); + newAction->setIconSize(ButtonSize::eDefault); + newAction->setButtonStyle(ButtonStyle::eIconOnly); + newAction->setIdentifier(entry->identifier()); - m_foreignButtonMap.insert(index, foreignDragIcon); - m_buttonMap.insert(index, newAction); + connect(newAction, &LtsDragIcon::clicked, entry, &LtsDragIcon::clicked); + connect(entry, &LtsDragIcon::destroyed, newAction, [this, newAction]() { + m_buttonMap.removeAll(newAction); + newAction->deleteLater(); + }); + newAction->setVisible(!entry->text().isEmpty()); + } + newAction->setContextMenuPolicy(Qt::CustomContextMenu); + connect(newAction, &LtsDragIcon::customContextMenuRequested, this, &LtsToolBarArea::showContextMenu); - connect(foreignDragIcon, &LtsDragIcon::enabledChanged, newAction, &LtsDragIcon::setEnabled); + m_foreignButtonMap.insert(index, foreignDragIcon); + m_buttonMap.insert(index, newAction); - - m_ui->layToolbar->insertWidget(index + 1, newAction); - saveSettings(); + connect(foreignDragIcon, &LtsDragIcon::enabledChanged, newAction, &LtsDragIcon::setEnabled); + + m_ui->layToolbar->insertWidget(index + 1, newAction); + saveSettings(); } void LtsToolBarArea::clearToolBarArea() { - qDeleteAll(m_buttonMap); - m_buttonMap.clear(); - m_foreignButtonMap.clear(); - for(ShortCut &item : m_functionKeys) - item.clear(); + qDeleteAll(m_buttonMap); + m_buttonMap.clear(); + m_foreignButtonMap.clear(); + for (ShortCut& item : m_functionKeys) + item.clear(); - delete m_dummyLabel; - - m_dummyLabel = new QLabel(tr("Drop menu entry here"), this); - m_ui->layToolbar->addWidget(m_dummyLabel); + delete m_dummyLabel; + + m_dummyLabel = new QLabel(tr("Drop menu entry here"), this); + m_ui->layToolbar->addWidget(m_dummyLabel); } -void LtsToolBarArea::setMenuEntries(const QVector &actions) +void LtsToolBarArea::setMenuEntries(const QVector& actions) { - clearToolBarArea(); + clearToolBarArea(); - for (LtsDragIcon* ico : actions) - addMenuEntry(ico); + for (LtsDragIcon* ico : actions) + addMenuEntry(ico); } QStringList LtsToolBarArea::menuEntries() const { - QStringList ret; - ret.reserve(m_foreignButtonMap.size()); - for (LtsDragIcon *dragIcon : m_foreignButtonMap) - ret << dragIcon->identifier(); + QStringList ret; + ret.reserve(m_foreignButtonMap.size()); + for (LtsDragIcon* dragIcon : m_foreignButtonMap) + ret << dragIcon->identifier(); - return ret; + return ret; } - - - -void LtsToolBarArea::dragEnterEvent(QDragEnterEvent *event) +void LtsToolBarArea::dragEnterEvent(QDragEnterEvent* event) { - LtsDragIcon *source = - qobject_cast(event->source()); - if (source) - { - if (!m_foreignButtonMap.contains(source)) + LtsDragIcon* source = qobject_cast(event->source()); + if (source) { - event->setDropAction(Qt::MoveAction); - event->accept(); + if (!m_foreignButtonMap.contains(source)) + { + event->setDropAction(Qt::MoveAction); + event->accept(); + } } - } } -void LtsToolBarArea::dropEvent(QDropEvent *event) +void LtsToolBarArea::dropEvent(QDropEvent* event) { - LtsDragIcon *source = qobject_cast(event->source()); - - LtsDragIcon *after = nullptr; - QWidget *w = childAt(event->pos()); - while (w) - { - after = qobject_cast(w); - if (after) - break; - w = w->parentWidget(); - } + LtsDragIcon* source = qobject_cast(event->source()); - addMenuEntry(source, after); + LtsDragIcon* after = nullptr; + QWidget* w = childAt(event->pos()); + while (w) + { + after = qobject_cast(w); + if (after) + break; + w = w->parentWidget(); + } + + addMenuEntry(source, after); } -QMenu *LtsToolBarArea::functionKeyMenu(QWidget *parent) +QMenu* LtsToolBarArea::functionKeyMenu(QWidget* parent) { - QMenu* menu = new QMenu(parent); - menu->setTitle(tr("Function Key")); - QAction *act; - for(auto val = m_functionKeys.begin(); val != m_functionKeys.end(); ++val) - { - ShortCut &shorty = val.value(); - act = menu->addAction(QStringLiteral("%1%2").arg(shorty.keyName(), !shorty.name.isEmpty() ? QStringLiteral(" - %1").arg(shorty.name) : QString())); - act->setData(shorty.shortcut->key()[0]); + QMenu* menu = new QMenu(parent); + menu->setTitle(tr("Function Key")); + QAction* act; + for (auto val = m_functionKeys.begin(); val != m_functionKeys.end(); ++val) + { + ShortCut& shorty = val.value(); + act = menu->addAction(QStringLiteral("%1%2").arg( + shorty.keyName(), !shorty.name.isEmpty() ? QStringLiteral(" - %1").arg(shorty.name) : QString())); + act->setData(QVariant::fromValue(shorty.shortcut->key()[0])); + connect(act, &QAction::triggered, this, &LtsToolBarArea::functionKeyMenuTriggered); + } + menu->addSeparator(); + act = menu->addAction(tr("Remove Function Key")); + act->setData(-1); connect(act, &QAction::triggered, this, &LtsToolBarArea::functionKeyMenuTriggered); - } - menu->addSeparator(); - act = menu->addAction(tr("Remove Function Key")); - act->setData(-1); - connect(act, &QAction::triggered, this, &LtsToolBarArea::functionKeyMenuTriggered); - return menu; + return menu; } void LtsToolBarArea::functionKeyMenuTriggered() { - QAction* act = qobject_cast(sender()); - if (!act) - return; - int fkey = act->data().toInt(); + QAction* act = qobject_cast(sender()); + if (!act) + return; + int fkey = act->data().toInt(); - if (fkey == -1) - removeFunctionKey(m_currentIdentifierForContextMenue); - else if (fkey > 0) - setFunctionKey(fkey, m_currentIdentifierForContextMenue); + if (fkey == -1) + removeFunctionKey(m_currentIdentifierForContextMenue); + else if (fkey > 0) + setFunctionKey(fkey, m_currentIdentifierForContextMenue); } - -bool LtsToolBarArea::removeFunctionKey(const QString &action) +bool LtsToolBarArea::removeFunctionKey(const QString& action) { - if (action.isEmpty()) + if (action.isEmpty()) + return true; + + for (auto val = m_functionKeys.begin(); val != m_functionKeys.end(); ++val) + { + ShortCut& itShortcut = val.value(); + if (itShortcut.identifier == action) + { + itShortcut.icon->removeModification(); + itShortcut.clear(); + break; + } + } + saveSettings(); return true; - - - for(auto val = m_functionKeys.begin(); val != m_functionKeys.end(); ++val) - { - ShortCut &itShortcut = val.value(); - if (itShortcut.identifier == action) - { - itShortcut.icon->removeModification(); - itShortcut.clear(); - break; - } - } - saveSettings(); - return true; } -bool LtsToolBarArea::setFunctionKey(int fkey, const QString &action) +bool LtsToolBarArea::setFunctionKey(int fkey, const QString& action) { - - if (fkey < Qt::Key_F5 || fkey > Qt::Key_F12) - return false; - - LtsDragIcon *icon = nullptr; - for (LtsDragIcon *ic : std::as_const(m_buttonMap)) - { - if (ic->identifier() == action) + if (fkey < Qt::Key_F5 || fkey > Qt::Key_F12) + return false; + + LtsDragIcon* icon = nullptr; + for (LtsDragIcon* ic : std::as_const(m_buttonMap)) { - icon = ic; - break; + if (ic->identifier() == action) + { + icon = ic; + break; + } } - } - if (!icon) - return false; + if (!icon) + return false; - - ShortCut &shorty = m_functionKeys[fkey]; + ShortCut& shorty = m_functionKeys[fkey]; - - for (LtsDragIcon *ic : std::as_const(m_buttonMap)) - if (ic->identifier() == shorty.identifier) - ic->removeModification(); + for (LtsDragIcon* ic : std::as_const(m_buttonMap)) + if (ic->identifier() == shorty.identifier) + ic->removeModification(); - - for(auto val = m_functionKeys.begin(); val != m_functionKeys.end(); ++val) - { - ShortCut &itShortcut = val.value(); - if (itShortcut.identifier == action) + for (auto val = m_functionKeys.begin(); val != m_functionKeys.end(); ++val) { - itShortcut.clear(); - break; + ShortCut& itShortcut = val.value(); + if (itShortcut.identifier == action) + { + itShortcut.clear(); + break; + } } - } - - shorty.clear(); - shorty.identifier = icon->identifier(); - shorty.name = icon->text(); - shorty.icon = icon; - shorty.icon->setModification(shorty.keyName()); - connect(shorty.shortcut, &QShortcut::activated, icon, &LtsDragIcon::clicked); - saveSettings(); - return true; + shorty.clear(); + shorty.identifier = icon->identifier(); + shorty.name = icon->text(); + shorty.icon = icon; + shorty.icon->setModification(shorty.keyName()); + connect(shorty.shortcut, &QShortcut::activated, icon, &LtsDragIcon::clicked); + saveSettings(); + return true; } QMap LtsToolBarArea::functionKeys() const { - QMap retVal; - for(auto val = m_functionKeys.begin(); val != m_functionKeys.end(); ++val) - { - const ShortCut &itShortcut = val.value(); - if (!itShortcut.identifier.isEmpty()) - retVal[itShortcut.key] = itShortcut.identifier; - } - return retVal; -} - -void LtsToolBarArea::removeMenuAction(LtsDragIcon *icon) -{ - - for(auto val = m_functionKeys.begin(); val != m_functionKeys.end(); ++val) - { - ShortCut &itShortcut = val.value(); - if (itShortcut.identifier == icon->identifier()) - itShortcut.clear(); - } - for (LtsDragIcon *ic : std::as_const(m_foreignButtonMap)) - { - if(ic->identifier() == icon->identifier()) + QMap retVal; + for (auto val = m_functionKeys.begin(); val != m_functionKeys.end(); ++val) { - m_foreignButtonMap.removeAll(ic); - break; + const ShortCut& itShortcut = val.value(); + if (!itShortcut.identifier.isEmpty()) + retVal[itShortcut.key] = itShortcut.identifier; } - } - m_buttonMap.removeAll(icon); - m_ui->layToolbar->removeWidget(icon); - delete icon; - saveSettings(); + return retVal; } -void LtsToolBarArea::showContextMenu(const QPoint &pos) -{ - QPointer icon = qobject_cast(sender()); - if (!icon) - return; - - const QPoint &globalPos = icon->mapToGlobal(pos); - - QMenu *contextMenu = new QMenu(this); - contextMenu->setAttribute(Qt::WA_DeleteOnClose); - - - m_currentIdentifierForContextMenue = icon->identifier(); - connect(contextMenu, &QObject::destroyed, this, [this](){ - - m_currentIdentifierForContextMenue.clear(); - }); - - - QAction *delAction = contextMenu->addAction(tr("Remove")); - connect(delAction, &QAction::triggered, this, [this, icon] () { - if (icon) - removeMenuAction(icon); - }); - - - QMenu *fkeyMenu = functionKeyMenu(contextMenu); - contextMenu->addMenu(fkeyMenu); - - contextMenu->popup(globalPos); -} - - -void LtsToolBarArea::saveSettings() +void LtsToolBarArea::removeMenuAction(LtsDragIcon* icon) { - - - - - - - - + for (auto val = m_functionKeys.begin(); val != m_functionKeys.end(); ++val) + { + ShortCut& itShortcut = val.value(); + if (itShortcut.identifier == icon->identifier()) + itShortcut.clear(); + } + for (LtsDragIcon* ic : std::as_const(m_foreignButtonMap)) + { + if (ic->identifier() == icon->identifier()) + { + m_foreignButtonMap.removeAll(ic); + break; + } + } + m_buttonMap.removeAll(icon); + m_ui->layToolbar->removeWidget(icon); + delete icon; + saveSettings(); } -} + +void LtsToolBarArea::showContextMenu(const QPoint& pos) +{ + QPointer icon = qobject_cast(sender()); + if (!icon) + return; + + const QPoint& globalPos = icon->mapToGlobal(pos); + + QMenu* contextMenu = new QMenu(this); + contextMenu->setAttribute(Qt::WA_DeleteOnClose); + + m_currentIdentifierForContextMenue = icon->identifier(); + connect(contextMenu, &QObject::destroyed, this, [this]() { m_currentIdentifierForContextMenue.clear(); }); + + QAction* delAction = contextMenu->addAction(tr("Remove")); + connect(delAction, &QAction::triggered, this, [this, icon]() { + if (icon) + removeMenuAction(icon); + }); + + QMenu* fkeyMenu = functionKeyMenu(contextMenu); + contextMenu->addMenu(fkeyMenu); + + contextMenu->popup(globalPos); +} + +void LtsToolBarArea::saveSettings() {} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CMakeLists.txt b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CMakeLists.txt index 893a4cdda..e41417704 100755 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CMakeLists.txt +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CMakeLists.txt @@ -13,8 +13,10 @@ ADD_SUBDIRECTORY(Battery) ADD_SUBDIRECTORY(Buildings) ADD_SUBDIRECTORY(BuildingViewer) # uses ZW connections (uses sql, ace, ..) ADD_SUBDIRECTORY(CentralEffectSimulation) -ADD_SUBDIRECTORY(CodificationManagement) -ADD_SUBDIRECTORY(CodificationManagement/Test) +IF(BUILD_CODIFICATION) + ADD_SUBDIRECTORY(CodificationManagement) + ADD_SUBDIRECTORY(CodificationManagement/Test) +ENDIF() ADD_SUBDIRECTORY(CollateralDamageSimulation) ADD_SUBDIRECTORY(EffectManagement) ADD_SUBDIRECTORY(EffectShowClient) @@ -22,7 +24,9 @@ ADD_SUBDIRECTORY(EffectShowManagement) ADD_SUBDIRECTORY(Evaluations) ADD_SUBDIRECTORY(ExerciseManagement) ADD_SUBDIRECTORY(FileManagement) -ADD_SUBDIRECTORY(FilterManagement) +IF(BUILD_FILTERMANAGEMENT) + ADD_SUBDIRECTORY(FilterManagement) +ENDIF() ADD_SUBDIRECTORY(FreeSpace) ADD_SUBDIRECTORY(GuezIedManagement) ADD_SUBDIRECTORY(GuezNasat) diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CollateralDamageSimulation/Gui/CreateSimulation/CMakeLists.txt b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CollateralDamageSimulation/Gui/CreateSimulation/CMakeLists.txt index 5cc5889b6..2c6f7df28 100755 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CollateralDamageSimulation/Gui/CreateSimulation/CMakeLists.txt +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CollateralDamageSimulation/Gui/CreateSimulation/CMakeLists.txt @@ -5,7 +5,12 @@ # Created by Hannes Fritsche, ESZS, 2024-08-05 # -FIND_PACKAGE(KDReports REQUIRED) +FIND_PACKAGE(KDReports) + +IF(NOT KDReports_FOUND) + MESSAGE(STATUS "KDReports not found; skipping CdsSimulationGuiPlugin") + RETURN() +ENDIF() SET(cds_gui_SRCS cds_building_model.cpp diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/InfrastructureManagement/CMakeLists.txt b/qt6-after/qt6-migrated-legatus/Lts/Plugins/InfrastructureManagement/CMakeLists.txt index b7edf126a..821bb93e6 100755 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/InfrastructureManagement/CMakeLists.txt +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/InfrastructureManagement/CMakeLists.txt @@ -37,11 +37,18 @@ ADD_INTERFACE_LIBRARY( # # need top be shared due to signals/slots NGL_ADD_LIBRARY2(WS IsmDataPluginInterface SHARED ism_data_plugin_interface.h) +IF(BUILD_RTI) NGL_TARGET_LINK_LIBRARIES(IsmDataPluginInterface Qt6::Core svcIsmCommon DataPluginInterface ) +ELSE() +NGL_TARGET_LINK_LIBRARIES(IsmDataPluginInterface + Qt6::Core + DataPluginInterface +) +ENDIF(BUILD_RTI) NGL_INSTALL_TARGET(IsmDataPluginInterface) # diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ReportManagement/Gui/ReportViewer/CMakeLists.txt b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ReportManagement/Gui/ReportViewer/CMakeLists.txt index 612e628de..4f3a5d424 100755 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ReportManagement/Gui/ReportViewer/CMakeLists.txt +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ReportManagement/Gui/ReportViewer/CMakeLists.txt @@ -7,8 +7,8 @@ FIND_PACKAGE(KDReports) FIND_PACKAGE(KDChart) -IF (NOT KDReports_FOUND OR NOT KDChart_FOUND) - MESSAGE(WARNING "KDReports or KDChart not found; skipping ReportViewer") +IF ((NOT KDReports_FOUND OR NOT KDChart_FOUND) OR NOT BUILD_CODIFICATION) + MESSAGE(WARNING "KDReports, KDChart not found or BUILD_CODIFICATION disabled; skipping ReportViewer") RETURN() ENDIF() diff --git a/qt6-after/qt6-migrated-legatus/Lts/Proxies/WirelessLocationSystem/wls_sfm_message.h b/qt6-after/qt6-migrated-legatus/Lts/Proxies/WirelessLocationSystem/wls_sfm_message.h old mode 100755 new mode 100644 index ee3319ff5..7a0b74502 --- a/qt6-after/qt6-migrated-legatus/Lts/Proxies/WirelessLocationSystem/wls_sfm_message.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Proxies/WirelessLocationSystem/wls_sfm_message.h @@ -1,289 +1,305 @@ - #pragma once -#include "sv_export.h" - #include +#include namespace WirelessLocationSystem { - class SfmMessage { -public: - enum class MsgId - { - TacticalState = 37, - SfmRestartNotification = 76, - GpsControl = 79, - RequestGpsControl = 79 | 0x8000, - EquipmentId = 478, - RequestEquipmentId = 478 | 0x8000, - Acknowledge = 1098, - LicenseState = 1099, - TetraMessage = 1100 - }; + public: + enum class MsgId { + TacticalState = 37, + SfmRestartNotification = 76, + GpsControl = 79, + RequestGpsControl = 79 | 0x8000, + EquipmentId = 478, + RequestEquipmentId = 478 | 0x8000, + Acknowledge = 1098, + LicenseState = 1099, + TetraMessage = 1100 + }; -protected: - explicit SfmMessage(MsgId id) - : m_id(id) - {} + protected: + explicit SfmMessage(MsgId id) : m_id(id) {} -public: - virtual ~SfmMessage() = default; + public: + virtual ~SfmMessage() = default; - MsgId getId() const { return m_id; } -private: - MsgId m_id; + MsgId getId() const + { + return m_id; + } + + private: + MsgId m_id; }; - - - class SfmMessage_tx : public SfmMessage { -public: - using SfmMessage::SfmMessage; + public: + using SfmMessage::SfmMessage; - - - virtual QByteArray getPayload() const = 0; + virtual QByteArray getPayload() const = 0; }; - - - class SfmMessage_rx : public SfmMessage { -public: - using SfmMessage::SfmMessage; + public: + using SfmMessage::SfmMessage; - - - virtual bool setPayload(const QByteArray &payload) = 0; + virtual bool setPayload(const QByteArray& payload) = 0; }; - - - - class SfmMsgGpsControl_tx final : public SfmMessage_tx { -public: - explicit SfmMsgGpsControl_tx(bool gpsOn = false) - : SfmMessage_tx(SfmMessage::MsgId::GpsControl) - , m_gpsOn(gpsOn) - {} + public: + explicit SfmMsgGpsControl_tx(bool gpsOn = false) : SfmMessage_tx(SfmMessage::MsgId::GpsControl), m_gpsOn(gpsOn) {} - QByteArray getPayload() const override; + QByteArray getPayload() const override; - void setGpsOn(bool bOn) { m_gpsOn = bOn; } - bool isGpsOn() const { return m_gpsOn; } + void setGpsOn(bool bOn) + { + m_gpsOn = bOn; + } -private: - bool m_gpsOn; + bool isGpsOn() const + { + return m_gpsOn; + } + + private: + bool m_gpsOn; }; - - - class SfmMsgRequestGpsControl_rx final : public SfmMessage_rx { -public: - SfmMsgRequestGpsControl_rx() - : SfmMessage_rx(SfmMessage::MsgId::RequestGpsControl) - {} + public: + SfmMsgRequestGpsControl_rx() : SfmMessage_rx(SfmMessage::MsgId::RequestGpsControl) {} - bool setPayload(const QByteArray &payload) override - { - return (payload.size() == 0); - } + bool setPayload(const QByteArray& payload) override + { + return (payload.size() == 0); + } }; - - - - class SfmMsgRequestEquipmentId_tx final : public SfmMessage_tx { -public: - SfmMsgRequestEquipmentId_tx() - : SfmMessage_tx(SfmMessage::MsgId::RequestEquipmentId) - {} + public: + SfmMsgRequestEquipmentId_tx() : SfmMessage_tx(SfmMessage::MsgId::RequestEquipmentId) {} - QByteArray getPayload() const override - { - return QByteArray(); - } + QByteArray getPayload() const override + { + return QByteArray(); + } }; - - - class SFMCONVERTER_EXPORT SfmMsgEquipmentId final : public SfmMessage_rx, public SfmMessage_tx { -public: - SfmMsgEquipmentId() - : SfmMessage_rx(SfmMessage::MsgId::EquipmentId) - , SfmMessage_tx(SfmMessage::MsgId::EquipmentId) - {} + public: + SfmMsgEquipmentId() : SfmMessage_rx(SfmMessage::MsgId::EquipmentId), SfmMessage_tx(SfmMessage::MsgId::EquipmentId) + { + } - bool setPayload(const QByteArray &) override; - QByteArray getPayload() const override; + bool setPayload(const QByteArray&) override; + QByteArray getPayload() const override; - static constexpr int s_payloadSize = 3; + static constexpr int s_payloadSize = 3; - unsigned short getEquipmentNumber() const - { - return m_equipmentNumber; - } - void setEquipmentNumber(quint16 equipmentNumber) { m_equipmentNumber = equipmentNumber; } + unsigned short getEquipmentNumber() const + { + return m_equipmentNumber; + } -private: - unsigned short m_equipmentNumber = 0; + void setEquipmentNumber(quint16 equipmentNumber) + { + m_equipmentNumber = equipmentNumber; + } + + private: + unsigned short m_equipmentNumber = 0; }; - - - class SfmMsgSfmRestart_rx final : public SfmMessage_rx { -public: - SfmMsgSfmRestart_rx() - : SfmMessage_rx(SfmMessage::MsgId::SfmRestartNotification) - {} - bool setPayload(const QByteArray &payload) override - { - return (payload.size() == 0); - } + public: + SfmMsgSfmRestart_rx() : SfmMessage_rx(SfmMessage::MsgId::SfmRestartNotification) {} + + bool setPayload(const QByteArray& payload) override + { + return (payload.size() == 0); + } }; - - - class SfmMsgTacticalState_rx final : public SfmMessage_rx { -public: - SfmMsgTacticalState_rx() - : SfmMessage_rx(SfmMessage::MsgId::TacticalState) - {} + public: + SfmMsgTacticalState_rx() : SfmMessage_rx(SfmMessage::MsgId::TacticalState) {} - static constexpr int s_payloadSize = 1; + static constexpr int s_payloadSize = 1; - bool setPayload(const QByteArray &) override; + bool setPayload(const QByteArray&) override; - unsigned char getTacticalState() const { return m_tacticalState; } + unsigned char getTacticalState() const + { + return m_tacticalState; + } -private: - unsigned char m_tacticalState = 0; + private: + unsigned char m_tacticalState = 0; }; - - - class SfmMsgTetra_rx final : public SfmMessage_rx { -public: - SfmMsgTetra_rx() - : SfmMessage_rx(SfmMessage::MsgId::TetraMessage) - {} + public: + SfmMsgTetra_rx() : SfmMessage_rx(SfmMessage::MsgId::TetraMessage) {} - bool setPayload(const QByteArray &p_data) override; + bool setPayload(const QByteArray& p_data) override; - uint8_t sendCounter() const { return m_sendCounter; } - bool isFragmented() const { return fragmentCount() > 1; } - uint8_t fragmentNumber() const { return m_fragmentByte & 0x0f; } - uint8_t fragmentCount() const { return (m_fragmentByte & 0xf0) >> 4;} + uint8_t sendCounter() const + { + return m_sendCounter; + } - const QByteArray &payload() const { return m_payload; } + bool isFragmented() const + { + return fragmentCount() > 1; + } -private: - QByteArray m_payload; - uint8_t m_sendCounter = 0; - uint8_t m_fragmentByte = 0; + uint8_t fragmentNumber() const + { + return m_fragmentByte & 0x0f; + } + + uint8_t fragmentCount() const + { + return (m_fragmentByte & 0xf0) >> 4; + } + + const QByteArray& payload() const + { + return m_payload; + } + + private: + QByteArray m_payload; + uint8_t m_sendCounter = 0; + uint8_t m_fragmentByte = 0; }; class SfmMsgTetra_tx final : public SfmMessage_tx { -public: - explicit SfmMsgTetra_tx(uint8_t sendCounter, int fragmentCount, int fragmentNumber, const QByteArray &data) - : SfmMessage_tx(SfmMessage::MsgId::TetraMessage) - { - m_data.reserve(data.size() + 2); - m_data += sendCounter; - m_data += fragmentByte(fragmentCount, fragmentNumber); - m_data += data; - } + public: + explicit SfmMsgTetra_tx(uint8_t sendCounter, int fragmentCount, int fragmentNumber, const QByteArray& data) + : SfmMessage_tx(SfmMessage::MsgId::TetraMessage) + { + m_data.reserve(data.size() + 2); + m_data += sendCounter; + m_data += fragmentByte(fragmentCount, fragmentNumber); + m_data += data; + } - static char fragmentByte(int fragmentCount, int fragmentNumber) - { - Q_ASSERT(fragmentCount >= 0 && fragmentCount < 16); - Q_ASSERT(fragmentNumber >= 0 && fragmentNumber <= fragmentCount); - return ((fragmentCount & 0x0f) << 4 ) | (fragmentNumber & 0x0f); - } - QByteArray getPayload() const override { return m_data; } -private: - QByteArray m_data; + static char fragmentByte(int fragmentCount, int fragmentNumber) + { + Q_ASSERT(fragmentCount >= 0 && fragmentCount < 16); + Q_ASSERT(fragmentNumber >= 0 && fragmentNumber <= fragmentCount); + return ((fragmentCount & 0x0f) << 4) | (fragmentNumber & 0x0f); + } + + QByteArray getPayload() const override + { + return m_data; + } + + private: + QByteArray m_data; }; - class Acknowledge_rx final : public SfmMessage_rx { -public: - Acknowledge_rx() - : SfmMessage_rx(SfmMessage::MsgId::Acknowledge) - {} + public: + Acknowledge_rx() : SfmMessage_rx(SfmMessage::MsgId::Acknowledge) {} - static constexpr int s_payloadSize = 2; + static constexpr int s_payloadSize = 2; - bool setPayload(const QByteArray &p_data) override; - uint8_t recvCounter() const { return m_recvCounter; } - bool isOk() const { return m_ackState == 0; } - bool isCrcError() const { return (m_ackState & 0x20) == 0x20; } - bool isFragmentError() const { return (m_ackState & 0x10) == 0x10; } - uint8_t missingFragment() const { return (m_ackState & 0x0f)!= 0; } -private: - uint8_t m_recvCounter = 0; - uint8_t m_ackState = 0; + bool setPayload(const QByteArray& p_data) override; + + uint8_t recvCounter() const + { + return m_recvCounter; + } + + bool isOk() const + { + return m_ackState == 0; + } + + bool isCrcError() const + { + return (m_ackState & 0x20) == 0x20; + } + + bool isFragmentError() const + { + return (m_ackState & 0x10) == 0x10; + } + + uint8_t missingFragment() const + { + return (m_ackState & 0x0f) != 0; + } + + private: + uint8_t m_recvCounter = 0; + uint8_t m_ackState = 0; }; class Acknowledge_tx final : public SfmMessage_tx { -public: - explicit Acknowledge_tx() - : SfmMessage_tx(SfmMessage::MsgId::Acknowledge) - {} + public: + explicit Acknowledge_tx() : SfmMessage_tx(SfmMessage::MsgId::Acknowledge) {} - QByteArray getPayload() const override; + QByteArray getPayload() const override; - void setRecvCounter(uint8_t recvCounter) { m_recvCounter = recvCounter; } - void setCrcError() { m_ackState |= 0x20; } - void setFragmentError(uint8_t missingFrag) { m_ackState |= (0x10 | (0x0f & missingFrag)); } -private: - uint8_t m_recvCounter = 0; - uint8_t m_ackState = 0; + void setRecvCounter(uint8_t recvCounter) + { + m_recvCounter = recvCounter; + } + + void setCrcError() + { + m_ackState |= 0x20; + } + + void setFragmentError(uint8_t missingFrag) + { + m_ackState |= (0x10 | (0x0f & missingFrag)); + } + + private: + uint8_t m_recvCounter = 0; + uint8_t m_ackState = 0; }; - - - class SfmMsgLicenseState_rx final : public SfmMessage_rx { -public: - SfmMsgLicenseState_rx() - : SfmMessage_rx(SfmMessage::MsgId::LicenseState) - {} + public: + SfmMsgLicenseState_rx() : SfmMessage_rx(SfmMessage::MsgId::LicenseState) {} - static constexpr int s_payloadSize = 1; + static constexpr int s_payloadSize = 1; - bool setPayload(const QByteArray &p_data) override; - bool isLicensed() const { return m_isLicensed; } + bool setPayload(const QByteArray& p_data) override; -private: - bool m_isLicensed = false; + bool isLicensed() const + { + return m_isLicensed; + } + + private: + bool m_isLicensed = false; }; -} +} // namespace WirelessLocationSystem diff --git a/qt6-after/qt6-migrated-legatus/Lts/Services/CMakeLists.txt b/qt6-after/qt6-migrated-legatus/Lts/Services/CMakeLists.txt index 726a2b86c..23f90b1ee 100755 --- a/qt6-after/qt6-migrated-legatus/Lts/Services/CMakeLists.txt +++ b/qt6-after/qt6-migrated-legatus/Lts/Services/CMakeLists.txt @@ -18,7 +18,9 @@ ADD_SUBDIRECTORY(Evaluations) ADD_SUBDIRECTORY(ExerciseManagement) ADD_SUBDIRECTORY(ExerciseEventManagement) ADD_SUBDIRECTORY(FileManagement) -ADD_SUBDIRECTORY(FilterManagement) +IF(BUILD_FILTERMANAGEMENT) + ADD_SUBDIRECTORY(FilterManagement) +ENDIF() ADD_SUBDIRECTORY(GuezIedManagement) ADD_SUBDIRECTORY(GuezMinelayerProcessing) IF(BUILD_RTI) diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvRadioTelegram.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvRadioTelegram.cpp index 0d51a98da..a81c40fbf 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvRadioTelegram.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvRadioTelegram.cpp @@ -1,27 +1,14 @@ - - - - - - - - - - - - #include "CoPrtCnvRadioTelegram.hpp" -#include + #include +#include using N_CoPrtCnv::CoPrtCnvRadioTelegram; using namespace N_CoPrtCnv; - - constexpr uint8_t CoPrtCnvRadioTelegram::MAGIC_NUMBER; constexpr uint16_t CoPrtCnvRadioTelegram::DATA_IND_REQ_WITH_TL_HEADER_LENGTH; constexpr uint16_t CoPrtCnvRadioTelegram::DATA_IND_REQ_HEADER_LENGTH; @@ -35,1752 +22,1365 @@ int CoPrtCnvRadioTelegram::s_3rdDelay = 60; int CoPrtCnvRadioTelegram::s_maxBroadcastSendCnt = 0; bool CoPrtCnvRadioTelegram::s_etsMode = false; -static const N_CoPrtCnv::CoPrtCnvRadioTelegram::E_ProtocolIdentifier -s_protocolIdentifier = N_CoPrtCnv::CoPrtCnvRadioTelegram::e_TDSMessageWithoutSDS_TL; - - - +static const N_CoPrtCnv::CoPrtCnvRadioTelegram::E_ProtocolIdentifier s_protocolIdentifier = + N_CoPrtCnv::CoPrtCnvRadioTelegram::e_TDSMessageWithoutSDS_TL; CoPrtCnvRadioTelegram::CoPrtCnvRadioTelegram(const uint32_t a_sourceISSI) - : m_data(9, Qt::Uninitialized), - m_PayloadIndex(0), - m_BroadcastCounter(0), - m_NextSendTime(0), - m_IsBroadcastOnly(false), - m_BroadcastOnlyTelegram(nullptr) + : m_data(9, Qt::Uninitialized), m_PayloadIndex(0), m_BroadcastCounter(0), m_NextSendTime(0), + m_IsBroadcastOnly(false), m_BroadcastOnlyTelegram(nullptr), + m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("CoPrtCnvRadioTelegram")) { - - - setHeader(m_data, e_RegisterInd); - setSrcISSI(a_sourceISSI); + setHeader(m_data, e_RegisterInd); + + setSrcISSI(a_sourceISSI); } - - - -CoPrtCnvRadioTelegram::CoPrtCnvRadioTelegram(const uint32_t a_sourceISSI, - const std::set &groups) - : m_PayloadIndex(0), - m_BroadcastCounter(0), - m_NextSendTime(0), - m_IsBroadcastOnly(false), - m_BroadcastOnlyTelegram(nullptr) +CoPrtCnvRadioTelegram::CoPrtCnvRadioTelegram(const uint32_t a_sourceISSI, const std::set& groups) + : m_PayloadIndex(0), m_BroadcastCounter(0), m_NextSendTime(0), m_IsBroadcastOnly(false), + m_BroadcastOnlyTelegram(nullptr), + m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("CoPrtCnvRadioTelegram")) { - uint16_t len = groups.size(); - if (len > 5) - len = 5; - m_data.resize(12 + len * 4); - setHeader(m_data, e_GroupMonitorReq); + uint16_t len = groups.size(); + if (len > 5) + len = 5; + m_data.resize(12 + len * 4); + setHeader(m_data, e_GroupMonitorReq); - - setSrcISSI(a_sourceISSI); + setSrcISSI(a_sourceISSI); - uint8_t mode = 1; - set1Byte(m_data, 9, mode); - set2Byte(m_data, 10, len); - std::set::iterator it = groups.begin(); - for (uint16_t i = 0; i < len; i++) - { - set4Byte(m_data, 12 + i * 4, *it); - ++it; - } + uint8_t mode = 1; + set1Byte(m_data, 9, mode); + set2Byte(m_data, 10, len); + std::set::iterator it = groups.begin(); + for (uint16_t i = 0; i < len; i++) + { + set4Byte(m_data, 12 + i * 4, *it); + ++it; + } } - - - -CoPrtCnvRadioTelegram::CoPrtCnvRadioTelegram(const uint32_t a_sourceISSI, - const E_DeliveryStatusForTL_Report a_delivery) - : m_data(17, Qt::Uninitialized), - m_PayloadIndex(0), - m_BroadcastCounter(0), - m_NextSendTime(0), - m_IsBroadcastOnly(false), - m_BroadcastOnlyTelegram(nullptr) +CoPrtCnvRadioTelegram::CoPrtCnvRadioTelegram(const uint32_t a_sourceISSI, const E_DeliveryStatusForTL_Report a_delivery) + : m_data(17, Qt::Uninitialized), m_PayloadIndex(0), m_BroadcastCounter(0), m_NextSendTime(0), + m_IsBroadcastOnly(false), m_BroadcastOnlyTelegram(nullptr), + m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("CoPrtCnvRadioTelegram")) { - - - setHeader(m_data, e_ReportIndReq); - - setSrcISSI(a_sourceISSI); - setDestISSI(a_sourceISSI); - set1Byte(m_data, 13, s_protocolIdentifier); - set1Byte(m_data, 14, 0); - set1Byte(m_data, 15, 0); - set1Byte(m_data, 16, a_delivery); + + setHeader(m_data, e_ReportIndReq); + + setSrcISSI(a_sourceISSI); + setDestISSI(a_sourceISSI); + set1Byte(m_data, 13, s_protocolIdentifier); + set1Byte(m_data, 14, 0); + set1Byte(m_data, 15, 0); + set1Byte(m_data, 16, a_delivery); } - - - - - -CoPrtCnvRadioTelegram::CoPrtCnvRadioTelegram(const QByteArray &a_data) - : m_data(a_data), - m_PayloadIndex(0), - m_BroadcastCounter(0), - m_NextSendTime(0), - m_IsBroadcastOnly(false), - m_BroadcastOnlyTelegram(nullptr) +CoPrtCnvRadioTelegram::CoPrtCnvRadioTelegram(const QByteArray& a_data) + : m_data(a_data), m_PayloadIndex(0), m_BroadcastCounter(0), m_NextSendTime(0), m_IsBroadcastOnly(false), + m_BroadcastOnlyTelegram(nullptr), + m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("CoPrtCnvRadioTelegram")) { } - - - - -CoPrtCnvRadioTelegram::CoPrtCnvRadioTelegram(const gef_telegramm_id_et a_telegramId, const uint16_t a_payloadSize, const uint16_t a_identity) - : m_data(a_payloadSize + DATA_IND_REQ_HEADER_LENGTH, '\0'), - m_PayloadIndex(0), - m_BroadcastCounter(0), - m_NextSendTime(0), - m_IsBroadcastOnly(false), - m_BroadcastOnlyTelegram(nullptr) +CoPrtCnvRadioTelegram::CoPrtCnvRadioTelegram(const gef_telegramm_id_et a_telegramId, const uint16_t a_payloadSize, + const uint16_t a_identity) + : m_data(a_payloadSize + DATA_IND_REQ_HEADER_LENGTH, '\0'), m_PayloadIndex(0), m_BroadcastCounter(0), + m_NextSendTime(0), m_IsBroadcastOnly(false), m_BroadcastOnlyTelegram(nullptr), + m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("CoPrtCnvRadioTelegram")) { - - - setHeader(m_data, e_DataIndReq); - fillDataIndReqHeader(m_data); - m_PayloadIndex = DATA_IND_REQ_HEADER_LENGTH - PAYLOAD_STATUS_LENGTH; - set1Byte(m_data, m_PayloadIndex++, e_NotFragmented); - - set1Byte(m_data, m_PayloadIndex++, a_telegramId); - set1Byte(m_data, m_PayloadIndex++, 0); - set1Byte(m_data, m_PayloadIndex--, 0); - setIdentity(a_identity); - m_PayloadIndex += 2; + setHeader(m_data, e_DataIndReq); + fillDataIndReqHeader(m_data); + + m_PayloadIndex = DATA_IND_REQ_HEADER_LENGTH - PAYLOAD_STATUS_LENGTH; + set1Byte(m_data, m_PayloadIndex++, e_NotFragmented); + + set1Byte(m_data, m_PayloadIndex++, a_telegramId); + set1Byte(m_data, m_PayloadIndex++, 0); + set1Byte(m_data, m_PayloadIndex--, 0); + setIdentity(a_identity); + m_PayloadIndex += 2; } - - - - -CoPrtCnvRadioTelegram::CoPrtCnvRadioTelegram(const E_LoginStatus a_loginTelegramStatus, const uint16_t a_identity, uint32_t a_issi) - : m_PayloadIndex(0), - m_BroadcastCounter(0), - m_NextSendTime(0), - m_IsBroadcastOnly(false), - m_BroadcastOnlyTelegram(nullptr) +CoPrtCnvRadioTelegram::CoPrtCnvRadioTelegram(const E_LoginStatus a_loginTelegramStatus, const uint16_t a_identity, + uint32_t a_issi) + : m_PayloadIndex(0), m_BroadcastCounter(0), m_NextSendTime(0), m_IsBroadcastOnly(false), + m_BroadcastOnlyTelegram(nullptr), + m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("CoPrtCnvRadioTelegram")) { - - - const bool withGroupIssis = (a_loginTelegramStatus & e_LoginOtherExercise) == e_LoginOtherExercise; - m_data.resize(DATA_IND_REQ_HEADER_LENGTH + (withGroupIssis ? 12 : 3)); - setHeader(m_data, e_DataIndReq); - fillDataIndReqHeader(m_data); - setDestISSI(a_issi); - - uint16_t size = m_data.size(); - set2Byte(m_data, DATA_IND_REQ_WITH_TL_HEADER_LENGTH, 8 * (size - DATA_IND_REQ_HEADER_LENGTH_WITHOUT_PAYLOAD_HEADER)); + const bool withGroupIssis = (a_loginTelegramStatus & e_LoginOtherExercise) == e_LoginOtherExercise; + m_data.resize(DATA_IND_REQ_HEADER_LENGTH + (withGroupIssis ? 12 : 3)); + setHeader(m_data, e_DataIndReq); + fillDataIndReqHeader(m_data); + setDestISSI(a_issi); - m_PayloadIndex = DATA_IND_REQ_HEADER_LENGTH - PAYLOAD_STATUS_LENGTH; - set1Byte(m_data, m_PayloadIndex++, e_NotFragmented + e_LoginTelegram); - - set1Byte(m_data, m_PayloadIndex++, (a_identity >> 8) & 0x00FF); - set1Byte(m_data, m_PayloadIndex++, a_identity & 0x00FF); - set1Byte(m_data, m_PayloadIndex++, a_loginTelegramStatus); + uint16_t size = m_data.size(); + set2Byte(m_data, DATA_IND_REQ_WITH_TL_HEADER_LENGTH, + 8 * (size - DATA_IND_REQ_HEADER_LENGTH_WITHOUT_PAYLOAD_HEADER)); + + m_PayloadIndex = DATA_IND_REQ_HEADER_LENGTH - PAYLOAD_STATUS_LENGTH; + set1Byte(m_data, m_PayloadIndex++, e_NotFragmented + e_LoginTelegram); + + set1Byte(m_data, m_PayloadIndex++, (a_identity >> 8) & 0x00FF); + set1Byte(m_data, m_PayloadIndex++, a_identity & 0x00FF); + set1Byte(m_data, m_PayloadIndex++, a_loginTelegramStatus); } void CoPrtCnvRadioTelegram::setLoginIssis(int hostIssi, int groupIssi1, int groupIssi2) { - - - setPayload3Byte(hostIssi); - - setPayload3Byte(groupIssi1); - - setPayload3Byte(groupIssi2); + + setPayload3Byte(hostIssi); + + setPayload3Byte(groupIssi1); + + setPayload3Byte(groupIssi2); } - - - - - -CoPrtCnvRadioTelegram::CoPrtCnvRadioTelegram(const std::shared_ptr &a_bigTelegram, - const uint8_t a_fragmentIndex, - bool &a_error) - : m_data(), - m_PayloadIndex(0), - m_BroadcastCounter(0), - m_NextSendTime(0), - m_IsBroadcastOnly(false), - m_BroadcastOnlyTelegram(nullptr) +CoPrtCnvRadioTelegram::CoPrtCnvRadioTelegram(const std::shared_ptr& a_bigTelegram, + const uint8_t a_fragmentIndex, bool& a_error) + : m_data(), m_PayloadIndex(0), m_BroadcastCounter(0), m_NextSendTime(0), m_IsBroadcastOnly(false), + m_BroadcastOnlyTelegram(nullptr), + m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("CoPrtCnvRadioTelegram")) { - - static const uint16_t MAX_TELEGRAM_SIZE = MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH - PAYLOAD_STATUS_LENGTH; - const int payloadSize = a_bigTelegram->getSize() - DATA_IND_REQ_HEADER_LENGTH; - const uint8_t nbrOfFragmentedTelegrams = uint8_t((payloadSize - 1) / MAX_TELEGRAM_SIZE); - if (nbrOfFragmentedTelegrams > (MAX_NBR_OF_FRAGMENTS - 1)) - { - ERROR_LOG(m_logger) << "Radio-telegram is too big (" << nbrOfFragmentedTelegrams + 1 - << " fragments). There are max " << MAX_NBR_OF_FRAGMENTS - << " fragments of size=" << MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH - << " (=" << MAX_NBR_OF_FRAGMENTS *MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH - << " bytes) possible."; - a_error = true; - return; - } - if (nbrOfFragmentedTelegrams == 0) - { - ERROR_LOG(m_logger) << "Radio-telegram is too small for fragmentation. It must have at least a size of " - << (MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH + 1); - a_error = true; - return; - } - uint8_t payloadStatus = e_FirstFragment | nbrOfFragmentedTelegrams; + static const uint16_t MAX_TELEGRAM_SIZE = MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH - PAYLOAD_STATUS_LENGTH; - - const uint16_t payloadSizeNormal = uint16_t(payloadSize / (nbrOfFragmentedTelegrams + 1)); - const uint16_t payloadSizeLast = uint16_t(payloadSize - (nbrOfFragmentedTelegrams * payloadSizeNormal)); - - uint16_t size = payloadSizeNormal; - if (0 != a_fragmentIndex) - { - if (nbrOfFragmentedTelegrams != a_fragmentIndex) + const int payloadSize = a_bigTelegram->getSize() - DATA_IND_REQ_HEADER_LENGTH; + const uint8_t nbrOfFragmentedTelegrams = uint8_t((payloadSize - 1) / MAX_TELEGRAM_SIZE); + if (nbrOfFragmentedTelegrams > (MAX_NBR_OF_FRAGMENTS - 1)) { - - payloadStatus = e_MiddleFragment | (nbrOfFragmentedTelegrams - a_fragmentIndex); + ERROR_LOG(m_logger) << "Radio-telegram is too big (" << nbrOfFragmentedTelegrams + 1 + << " fragments). There are max " << MAX_NBR_OF_FRAGMENTS + << " fragments of size=" << MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH + << " (=" << MAX_NBR_OF_FRAGMENTS * MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH << " bytes) possible."; + a_error = true; + return; + } + if (nbrOfFragmentedTelegrams == 0) + { + ERROR_LOG(m_logger) << "Radio-telegram is too small for fragmentation. It must have at least a size of " + << (MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH + 1); + a_error = true; + return; + } + uint8_t payloadStatus = e_FirstFragment | nbrOfFragmentedTelegrams; + + const uint16_t payloadSizeNormal = uint16_t(payloadSize / (nbrOfFragmentedTelegrams + 1)); + const uint16_t payloadSizeLast = uint16_t(payloadSize - (nbrOfFragmentedTelegrams * payloadSizeNormal)); + + uint16_t size = payloadSizeNormal; + if (0 != a_fragmentIndex) + { + if (nbrOfFragmentedTelegrams != a_fragmentIndex) + { + + payloadStatus = e_MiddleFragment | (nbrOfFragmentedTelegrams - a_fragmentIndex); + } + else + { + + payloadStatus = e_LastFragment; + size = payloadSizeLast; + } + } + size += PAYLOAD_STATUS_LENGTH; + + m_data.resize(size + DATA_IND_REQ_WITH_TL_HEADER_LENGTH + sizeof(PrtCnvRadioGwHeader)); + setHeader(m_data, e_DataIndReq); + fillDataIndReqHeader(m_data); + m_PayloadIndex = DATA_IND_REQ_HEADER_LENGTH - PAYLOAD_STATUS_LENGTH; + set1Byte(m_data, m_PayloadIndex++, payloadStatus); + + if (size > 1) + { + const char* srcData = + a_bigTelegram->getData() + DATA_IND_REQ_HEADER_LENGTH + a_fragmentIndex * payloadSizeNormal; + const uint8_t* ptr = reinterpret_cast(srcData); + setPayloadData(ptr, size - 1); } else { - - payloadStatus = e_LastFragment; - size = payloadSizeLast; + + ERROR_LOG(m_logger) << "Internal error: size must be bigger than 1"; + a_error = true; + return; } - } - size += PAYLOAD_STATUS_LENGTH; - - - m_data.resize(size + DATA_IND_REQ_WITH_TL_HEADER_LENGTH + sizeof(PrtCnvRadioGwHeader)); - setHeader(m_data, e_DataIndReq); - fillDataIndReqHeader(m_data); - m_PayloadIndex = DATA_IND_REQ_HEADER_LENGTH - PAYLOAD_STATUS_LENGTH; - set1Byte(m_data, m_PayloadIndex++, payloadStatus); - - if (size > 1) - { - const char *srcData = a_bigTelegram->getData() + DATA_IND_REQ_HEADER_LENGTH + a_fragmentIndex * payloadSizeNormal; - const uint8_t *ptr = reinterpret_cast(srcData); - setPayloadData(ptr, size - 1); - } - else - { - - ERROR_LOG(m_logger) << "Internal error: size must be bigger than 1"; - a_error = true; - return; - } - a_error = false; + a_error = false; } - - CoPrtCnvRadioTelegram::~CoPrtCnvRadioTelegram() { - if (m_BroadcastOnlyTelegram != nullptr) - ERROR_LOG(m_logger) << "Internal error: m_BroadcastOnlyTelegram was not nullptr while deletion of radio-telegram"; + if (m_BroadcastOnlyTelegram != nullptr) + ERROR_LOG(m_logger) + << "Internal error: m_BroadcastOnlyTelegram was not nullptr while deletion of radio-telegram"; } - - - - void CoPrtCnvRadioTelegram::setPayload1Byte(const uint8_t a_value) { - set1Byte(m_data, m_PayloadIndex, a_value); - m_PayloadIndex += 1; + set1Byte(m_data, m_PayloadIndex, a_value); + m_PayloadIndex += 1; } void CoPrtCnvRadioTelegram::setPayload2Byte(const uint16_t a_value) { - setPayloadData(a_value, 2); + setPayloadData(a_value, 2); } void CoPrtCnvRadioTelegram::setPayload3Byte(const uint32_t a_value) { - setPayloadData(a_value, 3); + setPayloadData(a_value, 3); } void CoPrtCnvRadioTelegram::setPayload4Byte(const uint32_t a_value) { - setPayloadData(a_value, 4); + setPayloadData(a_value, 4); } void CoPrtCnvRadioTelegram::setPayloadData(uint32_t a_value, const uint8_t a_size) { - for (int i = m_PayloadIndex + a_size - 1; i >= m_PayloadIndex; i--) - { - set1Byte(m_data, i, a_value & 0xFF); - a_value >>= 8; - } - m_PayloadIndex += a_size; + for (int i = m_PayloadIndex + a_size - 1; i >= m_PayloadIndex; i--) + { + set1Byte(m_data, i, a_value & 0xFF); + a_value >>= 8; + } + m_PayloadIndex += a_size; } - - - - -void CoPrtCnvRadioTelegram::setPayloadData(const uint8_t *a_data, const uint16_t a_size) +void CoPrtCnvRadioTelegram::setPayloadData(const uint8_t* a_data, const uint16_t a_size) { - uint8_t *ptr = reinterpret_cast(m_data.data()); - memcpy(&ptr[m_PayloadIndex], a_data, a_size); - m_PayloadIndex += a_size; + uint8_t* ptr = reinterpret_cast(m_data.data()); + memcpy(&ptr[m_PayloadIndex], a_data, a_size); + m_PayloadIndex += a_size; } - - - void CoPrtCnvRadioTelegram::fixupTelegramIdForEts(bool convertToEtsId) { - if (!s_etsMode) - return; - char *ptr = &m_data.data()[DATA_IND_REQ_HEADER_LENGTH]; - if (convertToEtsId) - ++(*ptr); - else - --(*ptr); + if (!s_etsMode) + return; + char* ptr = &m_data.data()[DATA_IND_REQ_HEADER_LENGTH]; + if (convertToEtsId) + ++(*ptr); + else + --(*ptr); } void CoPrtCnvRadioTelegram::setEtsMode(bool bIsEtsMode) { - s_etsMode = bIsEtsMode; + s_etsMode = bIsEtsMode; } - - - gef_telegramm_id_et CoPrtCnvRadioTelegram::getTelID() const { - return static_cast(static_cast(m_data.at(DATA_IND_REQ_HEADER_LENGTH))); + return static_cast(static_cast(m_data.at(DATA_IND_REQ_HEADER_LENGTH))); } - - - - uint8_t CoPrtCnvRadioTelegram::zaehler() const { - return static_cast(m_data.at(1)); + return static_cast(m_data.at(1)); } - - - - void CoPrtCnvRadioTelegram::setZaehler(const uint8_t a_counter) { - set1Byte(m_data, 1, a_counter); + set1Byte(m_data, 1, a_counter); } - - - - uint32_t CoPrtCnvRadioTelegram::getPayloadDataUInt32(size_t a_offset, uint16_t a_size) const { - uint32_t value = 0; - const uint8_t *ptr = reinterpret_cast(m_data.data()); - uint8_t *ptrValue = reinterpret_cast(&value); - a_offset += DATA_IND_REQ_HEADER_LENGTH; - switch (a_size) - { - case 4: - ptrValue[3] = ptr[a_offset++]; - Q_FALLTHROUGH(); - case 3: - ptrValue[2] = ptr[a_offset++]; - Q_FALLTHROUGH(); - case 2: - ptrValue[1] = ptr[a_offset++]; - Q_FALLTHROUGH(); - case 1: - ptrValue[0] = ptr[a_offset++]; - break; - default: - Q_ASSERT(false); - ERROR_LOG(m_logger) << "a_size must be between 1..4"; - } + uint32_t value = 0; + const uint8_t* ptr = reinterpret_cast(m_data.data()); + uint8_t* ptrValue = reinterpret_cast(&value); + a_offset += DATA_IND_REQ_HEADER_LENGTH; + switch (a_size) + { + case 4: + ptrValue[3] = ptr[a_offset++]; + Q_FALLTHROUGH(); + case 3: + ptrValue[2] = ptr[a_offset++]; + Q_FALLTHROUGH(); + case 2: + ptrValue[1] = ptr[a_offset++]; + Q_FALLTHROUGH(); + case 1: + ptrValue[0] = ptr[a_offset++]; + break; + default: + Q_ASSERT(false); + ERROR_LOG(m_logger) << "a_size must be between 1..4"; + } - return value; + return value; } - - - - uint8_t CoPrtCnvRadioTelegram::getPayloadDataUInt8(size_t a_offset) const { - return static_cast(m_data.at(DATA_IND_REQ_HEADER_LENGTH + a_offset)); + return static_cast(m_data.at(DATA_IND_REQ_HEADER_LENGTH + a_offset)); } - - - - uint32_t CoPrtCnvRadioTelegram::getDestISSI() const { - return getUInt32(9); + return getUInt32(9); } - - - - uint16_t CoPrtCnvRadioTelegram::getIdentity() const { - return isLoginTelegram() ? getPayloadDataUInt32(0, 2) : getPayloadDataUInt32(1, 2); + return isLoginTelegram() ? getPayloadDataUInt32(0, 2) : getPayloadDataUInt32(1, 2); } - - - - void CoPrtCnvRadioTelegram::setSrcISSI(const uint32_t a_ISSI) { - setSrcISSI_Internal(m_data, a_ISSI); + setSrcISSI_Internal(m_data, a_ISSI); } - - - - - bool CoPrtCnvRadioTelegram::mustBroadcastBeSet() const { - - - if (isNormalTelegram()) - return getIdentity() == 0 && getBroadcastIndex() == 0; - return false; + if (isNormalTelegram()) + return getIdentity() == 0 && getBroadcastIndex() == 0; + + return false; } - - - - void CoPrtCnvRadioTelegram::setBroadcastIndex(const uint16_t a_broadcastIndex) { - set1Byte(m_data, DATA_IND_REQ_HEADER_LENGTH + 3, (a_broadcastIndex >> 8) & 0xFF); - set1Byte(m_data, DATA_IND_REQ_HEADER_LENGTH + 4, a_broadcastIndex & 0xFF); + set1Byte(m_data, DATA_IND_REQ_HEADER_LENGTH + 3, (a_broadcastIndex >> 8) & 0xFF); + set1Byte(m_data, DATA_IND_REQ_HEADER_LENGTH + 4, a_broadcastIndex & 0xFF); } - - - - void CoPrtCnvRadioTelegram::setDestISSI(const uint32_t a_ISSI) { - setDestISSI_Internal(m_data, a_ISSI); + setDestISSI_Internal(m_data, a_ISSI); } - - - - CoPrtCnvRadioTelegram::E_PDU_Type CoPrtCnvRadioTelegram::getPDU_Type() const { - return static_cast(m_data.at(4)); + return static_cast(m_data.at(4)); } - - - - CoPrtCnvRadioTelegram::E_FragmentStatus CoPrtCnvRadioTelegram::getFragmentStatus() const { - return static_cast(m_data.at(26) & e_FragmentStatusMask); + return static_cast(m_data.at(26) & e_FragmentStatusMask); } - - - - uint8_t CoPrtCnvRadioTelegram::getFragmentCounter() const { - return static_cast(m_data.at(26) & e_CounterMask); + return static_cast(m_data.at(26) & e_CounterMask); } - - - - - - bool CoPrtCnvRadioTelegram::isCrcOk() const { - if ((m_data.at(26) & e_Checksum) == e_Checksum) - { - - uint32_t sum = getProtocolIdentifier(); - for (int i = DATA_IND_REQ_HEADER_LENGTH - PAYLOAD_STATUS_LENGTH; i < m_data.size() - 2; i++) - sum += static_cast(m_data.at(i)); - - uint16_t checksum = getUInt8(m_data.size() - 2) * 256 + getUInt8(m_data.size() - 1); - checksum = ~checksum; - checksum++; - - auto that = const_cast(this); - that->m_data.resize(m_data.size() - 2); - that->m_data[26] = (m_data.at(26) & ~e_Checksum); - - if (sum != checksum) + if ((m_data.at(26) & e_Checksum) == e_Checksum) { - ERROR_LOG(m_logger) << "Checksum of telegram is wrong: " << QString::number(checksum, 16) - << " (expected: " << QString::number(sum, 16) << "), issi: " << getUInt32(5); - return true; + + uint32_t sum = getProtocolIdentifier(); + for (int i = DATA_IND_REQ_HEADER_LENGTH - PAYLOAD_STATUS_LENGTH; i < m_data.size() - 2; i++) + sum += static_cast(m_data.at(i)); + + uint16_t checksum = getUInt8(m_data.size() - 2) * 256 + getUInt8(m_data.size() - 1); + checksum = ~checksum; + checksum++; + + auto that = const_cast(this); + that->m_data.resize(m_data.size() - 2); + that->m_data[26] = (m_data.at(26) & ~e_Checksum); + + if (sum != checksum) + { + ERROR_LOG(m_logger) << "Checksum of telegram is wrong: " << QString::number(checksum, 16) + << " (expected: " << QString::number(sum, 16) << "), issi: " << getUInt32(5); + return true; + } } - } - return true; + return true; } - - - - uint32_t CoPrtCnvRadioTelegram::getSrcISSI() const { - return getUInt32(5); + return getUInt32(5); } - - - - bool CoPrtCnvRadioTelegram::isLoginTelegram() const { - if (e_DataIndReq == getPDU_Type()) - return (e_LoginTelegram == ((e_FragmentStatusMask | e_CounterMask) & m_data.at(26))); - return false; + if (e_DataIndReq == getPDU_Type()) + return (e_LoginTelegram == ((e_FragmentStatusMask | e_CounterMask) & m_data.at(26))); + return false; } - - - - bool CoPrtCnvRadioTelegram::mustBeFragmented() const { - if (e_DataIndReq == getPDU_Type()) - return size_t(getSize()) > (MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH + DATA_IND_REQ_WITH_TL_HEADER_LENGTH + sizeof(PrtCnvRadioGwHeader)); - return false; + if (e_DataIndReq == getPDU_Type()) + return size_t(getSize()) > + (MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH + DATA_IND_REQ_WITH_TL_HEADER_LENGTH + sizeof(PrtCnvRadioGwHeader)); + return false; } - - - - - -const uint8_t *CoPrtCnvRadioTelegram::getPayloadDataPtr(uint16_t a_offset) const +const uint8_t* CoPrtCnvRadioTelegram::getPayloadDataPtr(uint16_t a_offset) const { - return reinterpret_cast(&m_data.data()[DATA_IND_REQ_HEADER_LENGTH + a_offset]); + return reinterpret_cast(&m_data.data()[DATA_IND_REQ_HEADER_LENGTH + a_offset]); } -uint8_t *CoPrtCnvRadioTelegram::getPayloadDataPtr(uint16_t a_offset) +uint8_t* CoPrtCnvRadioTelegram::getPayloadDataPtr(uint16_t a_offset) { - return reinterpret_cast(&m_data.data()[DATA_IND_REQ_HEADER_LENGTH + a_offset]); + return reinterpret_cast(&m_data.data()[DATA_IND_REQ_HEADER_LENGTH + a_offset]); } - - - - uint16_t CoPrtCnvRadioTelegram::getPayloadSize() const { - return static_cast((getPDU_Type() == e_DataIndReq) ? m_data.size() - DATA_IND_REQ_HEADER_LENGTH : 0); + return static_cast((getPDU_Type() == e_DataIndReq) ? m_data.size() - DATA_IND_REQ_HEADER_LENGTH : 0); } - - - - - - - - - -QByteArray CoPrtCnvRadioTelegram::getUnfragmentedData(const std::multimap &a_fragTelegramList) +QByteArray +CoPrtCnvRadioTelegram::getUnfragmentedData(const std::multimap& a_fragTelegramList) { - NGL::INGLLogger &l = NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("CoPrtCnvRadioTelegram"); - - uint16_t totalSize = 0; - bool first = true; - uint8_t expectedNextFragment = 0; - CoPrtCnvRadioTelegram *firstFragment = nullptr; - std::multimap::const_reverse_iterator rit; - for (rit = a_fragTelegramList.rbegin(); rit != a_fragTelegramList.rend(); ++rit) - { - CoPrtCnvRadioTelegram *fragRadioTelegram = rit->second; - if (first) + NGL::INGLLogger& l = NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("CoPrtCnvRadioTelegram"); + + uint16_t totalSize = 0; + bool first = true; + uint8_t expectedNextFragment = 0; + CoPrtCnvRadioTelegram* firstFragment = nullptr; + std::multimap::const_reverse_iterator rit; + for (rit = a_fragTelegramList.rbegin(); rit != a_fragTelegramList.rend(); ++rit) { - if (e_FirstFragment == fragRadioTelegram->getFragmentStatus()) - { - totalSize += fragRadioTelegram->getSize(); - expectedNextFragment = fragRadioTelegram->getFragmentCounter() - 1; - firstFragment = fragRadioTelegram; - first = false; - } - else - { - ERROR_LOG(l) << "The fragment with the highest counter is not marked as first fragment"; - return nullptr; - } - } - else - { - if (e_MiddleFragment == fragRadioTelegram->getFragmentStatus() || e_LastFragment == fragRadioTelegram->getFragmentStatus()) - { - if (expectedNextFragment-- == fragRadioTelegram->getFragmentCounter()) + CoPrtCnvRadioTelegram* fragRadioTelegram = rit->second; + if (first) { - if (e_LastFragment == fragRadioTelegram->getFragmentStatus() && 0 != fragRadioTelegram->getFragmentCounter()) - { - ERROR_LOG(l) << "The last fragment must have a counter of 0, but the counter is " << (int)fragRadioTelegram->getFragmentCounter(); - return nullptr; - } - totalSize += fragRadioTelegram->getPayloadSize(); + if (e_FirstFragment == fragRadioTelegram->getFragmentStatus()) + { + totalSize += fragRadioTelegram->getSize(); + expectedNextFragment = fragRadioTelegram->getFragmentCounter() - 1; + firstFragment = fragRadioTelegram; + first = false; + } + else + { + ERROR_LOG(l) << "The fragment with the highest counter is not marked as first fragment"; + return nullptr; + } } else { - ERROR_LOG(l) << "The fragmented Radio-Telegram from TNE with id=" << fragRadioTelegram->getIdentity() << " with fragment-counter=" << (expectedNextFragment + 1) << " was lost"; - return nullptr; + if (e_MiddleFragment == fragRadioTelegram->getFragmentStatus() || + e_LastFragment == fragRadioTelegram->getFragmentStatus()) + { + if (expectedNextFragment-- == fragRadioTelegram->getFragmentCounter()) + { + if (e_LastFragment == fragRadioTelegram->getFragmentStatus() && + 0 != fragRadioTelegram->getFragmentCounter()) + { + ERROR_LOG(l) << "The last fragment must have a counter of 0, but the counter is " + << (int)fragRadioTelegram->getFragmentCounter(); + return nullptr; + } + totalSize += fragRadioTelegram->getPayloadSize(); + } + else + { + ERROR_LOG(l) << "The fragmented Radio-Telegram from TNE with id=" + << fragRadioTelegram->getIdentity() + << " with fragment-counter=" << (expectedNextFragment + 1) << " was lost"; + return nullptr; + } + } + else + { + ERROR_LOG(l) << "A fragment which is not the first one, is not marked as middle or last fragment"; + return nullptr; + } } - } - else - { - ERROR_LOG(l) << "A fragment which is not the first one, is not marked as middle or last fragment"; - return nullptr; - } } - } - - if (firstFragment - && totalSize <= (DATA_IND_REQ_HEADER_LENGTH + MAX_NBR_OF_FRAGMENTS * (MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH - PAYLOAD_STATUS_LENGTH)) - && totalSize > DATA_IND_REQ_HEADER_LENGTH) - { - QByteArray data(totalSize, Qt::Uninitialized); - - setHeader(data, e_DataIndReq); - fillDataIndReqHeader(data); - setSrcISSI_Internal(data, firstFragment->getSrcISSI()); - setDestISSI_Internal(data, firstFragment->getDestISSI()); - uint16_t index = DATA_IND_REQ_HEADER_LENGTH - PAYLOAD_STATUS_LENGTH; - set1Byte(data, index++, e_NotFragmented); - - - for (rit = a_fragTelegramList.rbegin(); rit != a_fragTelegramList.rend(); ++rit) + if (firstFragment && + totalSize <= (DATA_IND_REQ_HEADER_LENGTH + + MAX_NBR_OF_FRAGMENTS * (MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH - PAYLOAD_STATUS_LENGTH)) && + totalSize > DATA_IND_REQ_HEADER_LENGTH) { - CoPrtCnvRadioTelegram *fragRadioTelegram = rit->second; - uint16_t fragSize = fragRadioTelegram->getPayloadSize(); - if (index + fragSize <= totalSize) - { - memcpy(&data.data()[index], fragRadioTelegram->getPayloadDataPtr(0), fragSize); - index += fragSize; - } - else - { - - ERROR_LOG(l) << "Internal error: size of allocated datablock is too small"; - return QByteArray(); - } + QByteArray data(totalSize, Qt::Uninitialized); + + setHeader(data, e_DataIndReq); + fillDataIndReqHeader(data); + setSrcISSI_Internal(data, firstFragment->getSrcISSI()); + setDestISSI_Internal(data, firstFragment->getDestISSI()); + uint16_t index = DATA_IND_REQ_HEADER_LENGTH - PAYLOAD_STATUS_LENGTH; + set1Byte(data, index++, e_NotFragmented); + + for (rit = a_fragTelegramList.rbegin(); rit != a_fragTelegramList.rend(); ++rit) + { + CoPrtCnvRadioTelegram* fragRadioTelegram = rit->second; + uint16_t fragSize = fragRadioTelegram->getPayloadSize(); + if (index + fragSize <= totalSize) + { + memcpy(&data.data()[index], fragRadioTelegram->getPayloadDataPtr(0), fragSize); + index += fragSize; + } + else + { + + ERROR_LOG(l) << "Internal error: size of allocated datablock is too small"; + return QByteArray(); + } + } + + return data; } - return data; - } - - ERROR_LOG(l) << "Internal error while building unfragmented radio-telegram: fragTelegram=" << firstFragment << " totalSize=" << totalSize; - return QByteArray(); + ERROR_LOG(l) << "Internal error while building unfragmented radio-telegram: fragTelegram=" << firstFragment + << " totalSize=" << totalSize; + return QByteArray(); } - - - - bool CoPrtCnvRadioTelegram::isTelegramLengthOk(const uint16_t a_lengthWithoutFrame) { - return (a_lengthWithoutFrame <= (MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH + DATA_IND_REQ_HEADER_LENGTH - sizeof(PrtCnvRadioGwHeader) - PAYLOAD_STATUS_LENGTH)); + return (a_lengthWithoutFrame <= (MAX_RADIO_TELEGRAM_PAYLOAD_LENGTH + DATA_IND_REQ_HEADER_LENGTH - + sizeof(PrtCnvRadioGwHeader) - PAYLOAD_STATUS_LENGTH)); } - - - - - bool CoPrtCnvRadioTelegram::isNormalTelegram() const { - return (e_DataIndReq == getPDU_Type() && (e_NormalTelegram == ((e_FragmentStatusMask | e_CounterMask) & m_data.at(26)))); + return (e_DataIndReq == getPDU_Type() && + (e_NormalTelegram == ((e_FragmentStatusMask | e_CounterMask) & m_data.at(26)))); } - - - - uint8_t CoPrtCnvRadioTelegram::getPriority() const { - if (isNormalTelegram()) - { - switch (getTelID()) + if (isNormalTelegram()) { - case GEF_INIT: - case GEF_DEAKTIVIERUNG_EINZELMINE: - case GEF_TREFFER_EREIGNIS_SEKUNDAERWIRKUNG: - case GEF_SANITAETSDIENST_INSTANDSETZUNG: - case GEF_SANITAETSDIENST_INSTANDSETZUNG_PVSAN: - return 2; - case GEF_WIRKFELD_EINZELGESCHOSS: - case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER: - case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_STOP: - case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_FORTSETZEN: - case GEF_WIRKFELD_MINENSPERRE: - case GEF_WIRKFELD_STATUS_MINENSPERRE: - case GEF_WIRKFELD_A_KAMPFMITTEL: - case GEF_WIRKFELD_C_KAMPFMITTEL: - case GEF_DEAKTIVIERUNG_WIRKFELD: - case GEF_REAKTIVIERUNG_DUS_MINE: - case GEF_TECHNIK_FUNKTIONSRAUM: - case GEF_FUNKTIONSRAUM: - case GEF_DEAKTIVIEREN_FUNKTIONSRAUM: - case GEF_DATENVERKEHR_TDS_GEOP: - case GEF_WIRKFELD_EINZELMINENSIMULATOR: - case GEF_POSITIONS_MELDUNG: - return 3; - case GEF_UMGEBUNGS_MELDUNG2: - case GEF_AUFFORDERUNG_BITE_MELDUNG: - case GEF_LIZENSIERUNG_TNE: - case GEF_TREFFER_AUSLOESUNG: - case GEF_SPRACHAUSWAHL: - case GEF_BESTANDSMELDUNG_SANITAETSMATERIAL: - case GEF_SELEKTIVE_AUFMUNITIONIERUNG: - case GEF_SCHIEDSRICHTERKOMMANDO: - return 4; - case GEF_KONFIGURATION_WIRKMODELL: - case GEF_ANFORDERUNG_KONFIGURATIONSDATEN: - case GEF_WIRKFELD_AENDERUNG_BEZEICHNER: - case GEF_DATENVERKEHR_TDS_SRT: - case GEF_DATENVERKEHR_TDS_DMF: - case GEF_DATENVERKEHR_TDS_TGTC: - case GEF_TEILNEHMERMODE_SETZEN: - case GEF_TEILNEHMER_KONFIG_ANFORDERN: - case GEF_TEILNEHMER_KONFIG_SETZEN: - return 5; - case GEF_ALLGEMEINE_NACHRICHT: - return 6; - case GEF_SW_VERSIONSMELDUNG: - return 7; - - case GEF_NOP: - case GEF_WF_SAMMELDEAKTIVIERUNG: - case GEF_WF_SAMMELDEAKTIVIERUNG_DUS_MINEN: - case GEF_WF_SAMMELDEAKTIVIERUNG_FUNKTIONSRAUM: - return 99; - default: - ERROR_LOG(m_logger) << "Priority of telegram with telId=" << getTelID() << " not defined."; - + switch (getTelID()) + { + case GEF_INIT: + case GEF_DEAKTIVIERUNG_EINZELMINE: + case GEF_TREFFER_EREIGNIS_SEKUNDAERWIRKUNG: + case GEF_SANITAETSDIENST_INSTANDSETZUNG: + case GEF_SANITAETSDIENST_INSTANDSETZUNG_PVSAN: + return 2; + case GEF_WIRKFELD_EINZELGESCHOSS: + case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER: + case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_STOP: + case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_FORTSETZEN: + case GEF_WIRKFELD_MINENSPERRE: + case GEF_WIRKFELD_STATUS_MINENSPERRE: + case GEF_WIRKFELD_A_KAMPFMITTEL: + case GEF_WIRKFELD_C_KAMPFMITTEL: + case GEF_DEAKTIVIERUNG_WIRKFELD: + case GEF_REAKTIVIERUNG_DUS_MINE: + case GEF_TECHNIK_FUNKTIONSRAUM: + case GEF_FUNKTIONSRAUM: + case GEF_DEAKTIVIEREN_FUNKTIONSRAUM: + case GEF_DATENVERKEHR_TDS_GEOP: + case GEF_WIRKFELD_EINZELMINENSIMULATOR: + case GEF_POSITIONS_MELDUNG: + return 3; + case GEF_UMGEBUNGS_MELDUNG2: + case GEF_AUFFORDERUNG_BITE_MELDUNG: + case GEF_LIZENSIERUNG_TNE: + case GEF_TREFFER_AUSLOESUNG: + case GEF_SPRACHAUSWAHL: + case GEF_BESTANDSMELDUNG_SANITAETSMATERIAL: + case GEF_SELEKTIVE_AUFMUNITIONIERUNG: + case GEF_SCHIEDSRICHTERKOMMANDO: + return 4; + case GEF_KONFIGURATION_WIRKMODELL: + case GEF_ANFORDERUNG_KONFIGURATIONSDATEN: + case GEF_WIRKFELD_AENDERUNG_BEZEICHNER: + case GEF_DATENVERKEHR_TDS_SRT: + case GEF_DATENVERKEHR_TDS_DMF: + case GEF_DATENVERKEHR_TDS_TGTC: + case GEF_TEILNEHMERMODE_SETZEN: + case GEF_TEILNEHMER_KONFIG_ANFORDERN: + case GEF_TEILNEHMER_KONFIG_SETZEN: + return 5; + case GEF_ALLGEMEINE_NACHRICHT: + return 6; + case GEF_SW_VERSIONSMELDUNG: + return 7; + + case GEF_NOP: + case GEF_WF_SAMMELDEAKTIVIERUNG: + case GEF_WF_SAMMELDEAKTIVIERUNG_DUS_MINEN: + case GEF_WF_SAMMELDEAKTIVIERUNG_FUNKTIONSRAUM: + return 99; + default: + ERROR_LOG(m_logger) << "Priority of telegram with telId=" << getTelID() << " not defined."; + #ifdef DEBUG - abort(); + abort(); #endif + } } - } - else if (isLoginTelegram()) - return 4; - return 10; + else if (isLoginTelegram()) + return 4; + return 10; } - - - - uint16_t CoPrtCnvRadioTelegram::getBroadcastIndex() const { - if (isNormalTelegram() && m_data.size() > (DATA_IND_REQ_HEADER_LENGTH + 4)) - return getPayloadDataUInt32(3, 2); - return 0; + if (isNormalTelegram() && m_data.size() > (DATA_IND_REQ_HEADER_LENGTH + 4)) + return getPayloadDataUInt32(3, 2); + return 0; } - - - - -void CoPrtCnvRadioTelegram::setPayloadDataWithIndex(const uint16_t a_index, const uint32_t a_value, const uint16_t a_size) +void CoPrtCnvRadioTelegram::setPayloadDataWithIndex(const uint16_t a_index, const uint32_t a_value, + const uint16_t a_size) { - - if (1 == a_size) - set1Byte(m_data, DATA_IND_REQ_HEADER_LENGTH + a_index, a_value); - else - { - uint16_t savedPayloadIndex = m_PayloadIndex; - m_PayloadIndex = DATA_IND_REQ_HEADER_LENGTH + a_index; - setPayloadData(a_value, a_size); - m_PayloadIndex = savedPayloadIndex; - } + if (1 == a_size) + set1Byte(m_data, DATA_IND_REQ_HEADER_LENGTH + a_index, a_value); + else + { + uint16_t savedPayloadIndex = m_PayloadIndex; + m_PayloadIndex = DATA_IND_REQ_HEADER_LENGTH + a_index; + setPayloadData(a_value, a_size); + m_PayloadIndex = savedPayloadIndex; + } } - - - - -void CoPrtCnvRadioTelegram::setPayloadDataComplete(const QByteArray &payload) +void CoPrtCnvRadioTelegram::setPayloadDataComplete(const QByteArray& payload) { - m_data.resize(payload.size() + DATA_IND_REQ_HEADER_LENGTH); - setHeader(m_data, getPDU_Type()); - memcpy(&m_data.data()[DATA_IND_REQ_HEADER_LENGTH], payload.data(), payload.size()); + m_data.resize(payload.size() + DATA_IND_REQ_HEADER_LENGTH); + setHeader(m_data, getPDU_Type()); + memcpy(&m_data.data()[DATA_IND_REQ_HEADER_LENGTH], payload.data(), payload.size()); } - - - - - - - - void CoPrtCnvRadioTelegram::resetPayloadSize(const uint16_t a_newPayloadSize) { - m_data.resize(a_newPayloadSize + DATA_IND_REQ_HEADER_LENGTH); - setHeader(m_data, getPDU_Type()); - - uint16_t size = m_data.size(); - set2Byte(m_data, 22, (size - DATA_IND_REQ_HEADER_LENGTH + PAYLOAD_STATUS_LENGTH) * 8); - set2Byte(m_data, 24, (size - DATA_IND_REQ_HEADER_LENGTH + PAYLOAD_STATUS_LENGTH)); + m_data.resize(a_newPayloadSize + DATA_IND_REQ_HEADER_LENGTH); + setHeader(m_data, getPDU_Type()); + + uint16_t size = m_data.size(); + set2Byte(m_data, 22, (size - DATA_IND_REQ_HEADER_LENGTH + PAYLOAD_STATUS_LENGTH) * 8); + set2Byte(m_data, 24, (size - DATA_IND_REQ_HEADER_LENGTH + PAYLOAD_STATUS_LENGTH)); } - - - - void CoPrtCnvRadioTelegram::setIdentity(const uint16_t a_identity) { - setPayloadDataWithIndex(isLoginTelegram() ? 0 : 1, a_identity, 2); + setPayloadDataWithIndex(isLoginTelegram() ? 0 : 1, a_identity, 2); } - - - - void CoPrtCnvRadioTelegram::setProtocolIdentifier(const E_ProtocolIdentifier a_ProtocolIdentifier) { - if (e_DataIndReq == getPDU_Type()) - set1Byte(m_data, 13, a_ProtocolIdentifier); + if (e_DataIndReq == getPDU_Type()) + set1Byte(m_data, 13, a_ProtocolIdentifier); } - - - - void CoPrtCnvRadioTelegram::setMessageReference(const uint8_t a_MessageReference) { - if (isSDSTL()) - set1Byte(m_data, 14, a_MessageReference); + if (isSDSTL()) + set1Byte(m_data, 14, a_MessageReference); } - - - - bool CoPrtCnvRadioTelegram::isSDSTL() const { - return (e_DataIndReq == getPDU_Type() && (e_UsingSDS_TL == (e_UsingSDS_TL & getProtocolIdentifier()))); + return (e_DataIndReq == getPDU_Type() && (e_UsingSDS_TL == (e_UsingSDS_TL & getProtocolIdentifier()))); } - - - - - CoPrtCnvRadioTelegram::E_RegistrationStatus CoPrtCnvRadioTelegram::getRegistrationStatus() const { - return static_cast(m_data.at(5)); + return static_cast(m_data.at(5)); } - - - - - std::string CoPrtCnvRadioTelegram::getRegistrationStatusAsText() const { - switch (getRegistrationStatus()) - { - case e_IssiSuccessfulRegistered: - return "IssiSuccessfulRegistered"; - case e_DuplicateISSI: - return "DuplicateISSI"; - case e_InvalidISSI: - return "InvalidISSI"; - case e_InvalidIpAddress: - return "InvalidIpAddress"; - } - return std::to_string(getRegistrationStatus()); + switch (getRegistrationStatus()) + { + case e_IssiSuccessfulRegistered: + return "IssiSuccessfulRegistered"; + case e_DuplicateISSI: + return "DuplicateISSI"; + case e_InvalidISSI: + return "InvalidISSI"; + case e_InvalidIpAddress: + return "InvalidIpAddress"; + } + return std::to_string(getRegistrationStatus()); } - - - - CoPrtCnvRadioTelegram::E_ProtocolIdentifier CoPrtCnvRadioTelegram::getProtocolIdentifier() const { - return static_cast(m_data.at(13)); + return static_cast(m_data.at(13)); } - - - - - std::string CoPrtCnvRadioTelegram::getProtocolIdentifierAsText() const { - switch (getProtocolIdentifier()) - { - case e_SimpleTextMessagingWithoutSDS_TL: - return "Simple Text Messaging w/o SDS/TL"; - case e_SimpleGPS_WithoutSDS_TL: - return "Simple GPS w/o SDS/TL"; - case e_TDSMessageWithoutSDS_TL: - return "TDS Message w/o SDS/TL"; - case e_UsingSDS_TL: - return "SDS/TL"; - case e_SimpleTextMessagingUsingSDS_TL: - return "Simple Text Messaging with SDS/TL"; - case e_SimpleGPS_UsingSDS_TL: - return "Simple GPS with SDS/TL"; - case e_LoginTest: - return "Login-Test / Hohenfels"; - } - return std::to_string(getProtocolIdentifier()); + switch (getProtocolIdentifier()) + { + case e_SimpleTextMessagingWithoutSDS_TL: + return "Simple Text Messaging w/o SDS/TL"; + case e_SimpleGPS_WithoutSDS_TL: + return "Simple GPS w/o SDS/TL"; + case e_TDSMessageWithoutSDS_TL: + return "TDS Message w/o SDS/TL"; + case e_UsingSDS_TL: + return "SDS/TL"; + case e_SimpleTextMessagingUsingSDS_TL: + return "Simple Text Messaging with SDS/TL"; + case e_SimpleGPS_UsingSDS_TL: + return "Simple GPS with SDS/TL"; + case e_LoginTest: + return "Login-Test / Hohenfels"; + } + return std::to_string(getProtocolIdentifier()); } - - - - uint8_t CoPrtCnvRadioTelegram::getMessageReference() const { - return static_cast(m_data.at(14)); + return static_cast(m_data.at(14)); } - - - - uint8_t CoPrtCnvRadioTelegram::getAreaSelection() const { - return static_cast(m_data.at(15)); + return static_cast(m_data.at(15)); } - - - - uint8_t CoPrtCnvRadioTelegram::getValidityPeriod() const { - return static_cast(m_data.at(16)); + return static_cast(m_data.at(16)); } - - - - uint32_t CoPrtCnvRadioTelegram::getForwardAddress() const { - return getUInt32(17); + return getUInt32(17); } - - - - CoPrtCnvRadioTelegram::E_Flags CoPrtCnvRadioTelegram::getFlags() const { - return static_cast(m_data.at(21)); + return static_cast(m_data.at(21)); } - - - - std::string CoPrtCnvRadioTelegram::getFlagsAsText() const { - switch (getFlags()) - { - case e_FlagsNone: - return "No Flags"; + switch (getFlags()) + { + case e_FlagsNone: + return "No Flags"; - case e_StorageAllowed: - return "Storage Allowed"; + case e_StorageAllowed: + return "Storage Allowed"; - case e_GroupServiceOrOnlyStandardReportAllowed: - return "Group Service or only Standard Report Allowed"; + case e_GroupServiceOrOnlyStandardReportAllowed: + return "Group Service or only Standard Report Allowed"; - case e_ReceivedConfirmationRequested: - return "Received Confirmation Requested"; + case e_ReceivedConfirmationRequested: + return "Received Confirmation Requested"; - case e_ConsumedConfirmationRequested: - return "Consumed Confirmation Requested"; - - } - std::ostringstream str; - str << getFlags(); - return str.str(); + case e_ConsumedConfirmationRequested: + return "Consumed Confirmation Requested"; + } + std::ostringstream str; + str << getFlags(); + return str.str(); } - - - - uint16_t CoPrtCnvRadioTelegram::getLengthInBits() const { - return getUInt16(22); + return getUInt16(22); } - - - - uint16_t CoPrtCnvRadioTelegram::getLengthInBytes() const { - return getUInt16(24); + return getUInt16(24); } - - - bool CoPrtCnvRadioTelegram::getWithCrc() const { - if (getSize() > 26) - return ((m_data.at(26) & e_Checksum) == e_Checksum); - return false; + if (getSize() > 26) + return ((m_data.at(26) & e_Checksum) == e_Checksum); + return false; } - - - - - CoPrtCnvRadioTelegram::E_DeliveryStatusForTL_Report CoPrtCnvRadioTelegram::getDelivery() const { - return static_cast(m_data.at(16)); + return static_cast(m_data.at(16)); } - - - - - std::string CoPrtCnvRadioTelegram::getDeliveryAsText() const { - switch (getDelivery()) - { - case e_SDS_ReceiptAcknowledgedByDestination: - return "SDS receipt acknowledged by destination"; + switch (getDelivery()) + { + case e_SDS_ReceiptAcknowledgedByDestination: + return "SDS receipt acknowledged by destination"; - case e_SDS_ConsumedByDestination: - return "SDS consumed by destination"; + case e_SDS_ConsumedByDestination: + return "SDS consumed by destination"; - case e_SourceIsNotAuthorizedForSDS: - return "Source is not authorized for SDS"; + case e_SourceIsNotAuthorizedForSDS: + return "Source is not authorized for SDS"; - case e_DestinationIsNotAuthorizedForSDS: - return "Destination is not authorized for SDS"; + case e_DestinationIsNotAuthorizedForSDS: + return "Destination is not authorized for SDS"; - case e_UnknownDestinationAddress: - return "Unknown destination address"; + case e_UnknownDestinationAddress: + return "Unknown destination address"; - case e_DeliveryFailed: - return "Delivery failed"; + case e_DeliveryFailed: + return "Delivery failed"; - case e_DestinationNotRegisteredOnSystem: - return "Destination not registered on system"; + case e_DestinationNotRegisteredOnSystem: + return "Destination not registered on system"; - case e_DestinationQueueFull: - return "Destination queue full"; + case e_DestinationQueueFull: + return "Destination queue full"; - case e_MessageTooLong: - return "Message too long"; + case e_MessageTooLong: + return "Message too long"; - case e_DestinationHostPC_NotConnected: - return "Destination host PC not connected"; + case e_DestinationHostPC_NotConnected: + return "Destination host PC not connected"; - case e_ProtocolNotSupported: - return "Protocol not supported"; + case e_ProtocolNotSupported: + return "Protocol not supported"; - case e_DataCodingSchemeNotSupported: - return "Datat coding scheme not supported"; + case e_DataCodingSchemeNotSupported: + return "Datat coding scheme not supported"; - case e_DestinationNotReachable: - return "Destination not reachable"; - - } - std::ostringstream str; - str << getDelivery(); - return str.str(); + case e_DestinationNotReachable: + return "Destination not reachable"; + } + std::ostringstream str; + str << getDelivery(); + return str.str(); } - - - - - int32_t CoPrtCnvRadioTelegram::getPayloadDataSInt24(uint16_t a_offset) const { - uint32_t value = getPayloadDataUInt32(a_offset, 3); - - if (value & 0x800000) - value |= 0xFF800000; + uint32_t value = getPayloadDataUInt32(a_offset, 3); - return value; + if (value & 0x800000) + value |= 0xFF800000; + + return value; } - - - - bool CoPrtCnvRadioTelegram::needsLicensing() const { - if (isNormalTelegram()) - { - switch (getTelID()) + if (isNormalTelegram()) { - - case GEF_UMGEBUNGS_MELDUNG2: - case GEF_LIZENSIERUNG_TNE: - case GEF_AUFFORDERUNG_BITE_MELDUNG: - case GEF_ALLGEMEINE_NACHRICHT: - return false; - default: - - break; + switch (getTelID()) + { + + case GEF_UMGEBUNGS_MELDUNG2: + case GEF_LIZENSIERUNG_TNE: + case GEF_AUFFORDERUNG_BITE_MELDUNG: + case GEF_ALLGEMEINE_NACHRICHT: + return false; + default: + + break; + } + return true; } - return true; - } - return false; + return false; } - - - - - - bool CoPrtCnvRadioTelegram::hasExpired() const { - uint32_t expireTime = getExpireTime(); - if (expireTime > 0) - { - uint32_t now = time(nullptr); - return (now >= expireTime); - } - return false; + uint32_t expireTime = getExpireTime(); + if (expireTime > 0) + { + uint32_t now = time(nullptr); + return (now >= expireTime); + } + return false; } - - - - - uint32_t CoPrtCnvRadioTelegram::getExpireTime() const { - if (isNormalTelegram()) - { - uint32_t wirkBegin = 0; - uint32_t wirkDauer = 0; - switch (getTelID()) + if (isNormalTelegram()) { - case GEF_WIRKFELD_EINZELGESCHOSS: - wirkBegin = getPayloadDataUInt32(11 + 5, 4); - wirkDauer = 5; - break; - case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER: - wirkBegin = getPayloadDataUInt32(11 + 5, 4); - wirkDauer = getPayloadDataUInt32(15 + 5, 2); - break; - case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_FORTSETZEN: - wirkBegin = getPayloadDataUInt32(11, 4); - wirkDauer = getPayloadDataUInt32(15, 2); - break; - case GEF_WIRKFELD_A_KAMPFMITTEL: - wirkBegin = getPayloadDataUInt32(11 + 5, 4); - wirkDauer = getPayloadDataUInt32(15 + 5, 2) * 60 * 10; - break; - case GEF_WIRKFELD_C_KAMPFMITTEL: - wirkBegin = getPayloadDataUInt32(11 + 5, 4); - wirkDauer = getPayloadDataUInt32(15 + 5, 1) * 60; - break; - case GEF_WIRKFELD_MINENSPERRE: - wirkBegin = getPayloadDataUInt32(11 + 5, 4); - wirkDauer = getPayloadDataUInt32(15 + 5, 1) * 60 * 60; - break; - default: - return 0; + uint32_t wirkBegin = 0; + uint32_t wirkDauer = 0; + switch (getTelID()) + { + case GEF_WIRKFELD_EINZELGESCHOSS: + wirkBegin = getPayloadDataUInt32(11 + 5, 4); + wirkDauer = 5; + break; + case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER: + wirkBegin = getPayloadDataUInt32(11 + 5, 4); + wirkDauer = getPayloadDataUInt32(15 + 5, 2); + break; + case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_FORTSETZEN: + wirkBegin = getPayloadDataUInt32(11, 4); + wirkDauer = getPayloadDataUInt32(15, 2); + break; + case GEF_WIRKFELD_A_KAMPFMITTEL: + wirkBegin = getPayloadDataUInt32(11 + 5, 4); + wirkDauer = getPayloadDataUInt32(15 + 5, 2) * 60 * 10; + break; + case GEF_WIRKFELD_C_KAMPFMITTEL: + wirkBegin = getPayloadDataUInt32(11 + 5, 4); + wirkDauer = getPayloadDataUInt32(15 + 5, 1) * 60; + break; + case GEF_WIRKFELD_MINENSPERRE: + wirkBegin = getPayloadDataUInt32(11 + 5, 4); + wirkDauer = getPayloadDataUInt32(15 + 5, 1) * 60 * 60; + break; + default: + return 0; + } + + if (0 == wirkDauer) + { + return 0; + } + + if (wirkBegin > 0) + return (wirkBegin + wirkDauer); } - - if (0 == wirkDauer) - { - return 0; - } - - if (wirkBegin > 0) - return (wirkBegin + wirkDauer); - } - return 0; + return 0; } - - - - - - - - bool CoPrtCnvRadioTelegram::isContentValid() { - if (isNormalTelegram()) - { - uint16_t wirkfeldkennung = 0; - uint8_t wirkfeldtyp = 0; - switch (getTelID()) + if (isNormalTelegram()) { - case GEF_WIRKFELD_EINZELGESCHOSS: - case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER: - case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_STOP: - case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_FORTSETZEN: - case GEF_WIRKFELD_MINENSPERRE: - case GEF_WIRKFELD_STATUS_MINENSPERRE: - case GEF_WIRKFELD_A_KAMPFMITTEL: - case GEF_WIRKFELD_C_KAMPFMITTEL: - case GEF_WIRKFELD_EINZELMINENSIMULATOR: - wirkfeldkennung = getPayloadDataUInt32(5, 2); - wirkfeldtyp = 3; - Q_FALLTHROUGH(); - case GEF_DEAKTIVIERUNG_WIRKFELD: - case GEF_WIRKFELD_AENDERUNG_BEZEICHNER: - if (GEF_DEAKTIVIERUNG_WIRKFELD == getTelID() || GEF_WIRKFELD_AENDERUNG_BEZEICHNER == getTelID()) - { - wirkfeldtyp = getPayloadDataUInt8(5); - wirkfeldkennung = getPayloadDataUInt32(6, 2); - } - - if ((wirkfeldtyp >= 1 && wirkfeldtyp <= 5) || (wirkfeldtyp == 8)) - { - if (wirkfeldkennung > 0 && wirkfeldkennung <= 32767) - return true; - ERROR_LOG(m_logger) << "Wirkfeldkennung (" << wirkfeldkennung << ") of telegram with telId=" << getTelID() << " is invalid. Must be 1..32768."; - return false; - } - if (GEF_WIRKFELD_AENDERUNG_BEZEICHNER == getTelID() && wirkfeldkennung > 0) - return true; - - - - ERROR_LOG(m_logger) << "Wirkfeldtyp (" << wirkfeldtyp << ") of telegram with telId=" << getTelID() << " is invalid. Must be 1..5 or 8."; - return false; - - case GEF_DEAKTIVIERUNG_EINZELMINE: - if (isPayloadLengthOk(13)) - { - wirkfeldkennung = getPayloadDataUInt32(9, 2); + uint16_t wirkfeldkennung = 0; + uint8_t wirkfeldtyp = 0; + switch (getTelID()) { - if (wirkfeldkennung > 32767) - { - ERROR_LOG(m_logger) << "DeaktivierungEinzelmine: wirkfeldkennung=" << wirkfeldkennung << " too big. Must be 1..32767"; - return false; - } + case GEF_WIRKFELD_EINZELGESCHOSS: + case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER: + case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_STOP: + case GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_FORTSETZEN: + case GEF_WIRKFELD_MINENSPERRE: + case GEF_WIRKFELD_STATUS_MINENSPERRE: + case GEF_WIRKFELD_A_KAMPFMITTEL: + case GEF_WIRKFELD_C_KAMPFMITTEL: + case GEF_WIRKFELD_EINZELMINENSIMULATOR: + wirkfeldkennung = getPayloadDataUInt32(5, 2); + wirkfeldtyp = 3; + Q_FALLTHROUGH(); + case GEF_DEAKTIVIERUNG_WIRKFELD: + case GEF_WIRKFELD_AENDERUNG_BEZEICHNER: + if (GEF_DEAKTIVIERUNG_WIRKFELD == getTelID() || GEF_WIRKFELD_AENDERUNG_BEZEICHNER == getTelID()) + { + wirkfeldtyp = getPayloadDataUInt8(5); + wirkfeldkennung = getPayloadDataUInt32(6, 2); + } + + if ((wirkfeldtyp >= 1 && wirkfeldtyp <= 5) || (wirkfeldtyp == 8)) + { + if (wirkfeldkennung > 0 && wirkfeldkennung <= 32767) + return true; + ERROR_LOG(m_logger) << "Wirkfeldkennung (" << wirkfeldkennung + << ") of telegram with telId=" << getTelID() + << " is invalid. Must be 1..32768."; + return false; + } + if (GEF_WIRKFELD_AENDERUNG_BEZEICHNER == getTelID() && wirkfeldkennung > 0) + return true; + + ERROR_LOG(m_logger) << "Wirkfeldtyp (" << wirkfeldtyp << ") of telegram with telId=" << getTelID() + << " is invalid. Must be 1..5 or 8."; + return false; + + case GEF_DEAKTIVIERUNG_EINZELMINE: + if (isPayloadLengthOk(13)) + { + wirkfeldkennung = getPayloadDataUInt32(9, 2); + { + if (wirkfeldkennung > 32767) + { + ERROR_LOG(m_logger) << "DeaktivierungEinzelmine: wirkfeldkennung=" << wirkfeldkennung + << " too big. Must be 1..32767"; + return false; + } + } + return true; + } + return false; + + case GEF_TECHNIK_FUNKTIONSRAUM: + case GEF_FUNKTIONSRAUM: + case GEF_DEAKTIVIEREN_FUNKTIONSRAUM: { + uint32_t funktionsraumkennung = getPayloadDataUInt32(5, 2); + if (funktionsraumkennung > 0) + return true; + + ERROR_LOG(m_logger) << "Funktionsraumkennung (" << funktionsraumkennung + << ") of telegram with telId=" << getTelID() << " is invalid. Must be 1..65535."; + return false; + } + case GEF_EINTRETEN_FUNKTIONSRAUM: + if (isPayloadLengthOk(15)) + { + uint32_t funktionsraumkennung = getPayloadDataUInt32(13, 2); + if (funktionsraumkennung > 0) + return true; + + ERROR_LOG(m_logger) << "Funktionsraumkennung (" << funktionsraumkennung + << ") of telegram with telId=" << getTelID() + << " is invalid. Must be 1..65535."; + return false; + } + return false; + + case GEF_SPRACHAUSWAHL: { + uint8_t sprache = getPayloadDataUInt8(5); + if (sprache <= 3) + return true; + + ERROR_LOG(m_logger) << "Sprache (" << sprache << ") of telegram with telId=" << getTelID() + << " is invalid. Must be 0..3."; + return false; + } + + case GEF_MANIPULATIONSMELDUNG: + return isPayloadLengthOk(12); + + case GEF_BITE_MELDUNG2: + return isPayloadLengthOk(27, 19, 7); + + case GEF_BETRIEBSZUSTAND_AUSSTATTUNG: + return isPayloadLengthOk(9); + + case GEF_FEHLERMELDUNG_GFD: + return isPayloadLengthOk(9); + + case GEF_POSITIONS_MELDUNG: + return isPayloadLengthOk(14); + + case GEF_POSITIONS_MELDUNG_MIT_TEILNEHMER: + return isPayloadLengthOk(15, 14, 2); + + case GEF_POSITIONS_MELDUNG_LFZ: + return isPayloadLengthOk(15); + + case GEF_TREFFER_EREIGNIS_DUS: + return isPayloadLengthOk(23); + + case GEF_TREFFER_EREIGNIS_WIRKSIMULATION: + return isPayloadLengthOk(22); + + case GEF_SCHIEDSRICHTEREINGRIFF: + return isPayloadLengthOk(16); + + case GEF_SELEKTIVE_AUFMUNITIONIERUNG: + return isPayloadLengthOk(8, 7, 8); + + case GEF_TAKTISCHER_STATUS: + return isPayloadLengthOk(16); + + case GEF_DATENVERKEHR_SRT_TDS: + case GEF_DATENVERKEHR_DMF_TDS: { + uint16_t length = m_data.size() - DATA_IND_REQ_HEADER_LENGTH; + + const uint16_t MIN_LENGTH = 7; + if (length >= MIN_LENGTH) + return true; + + ERROR_LOG(m_logger) << "The payload-length of telegram with telId=" << getTelID() + << " must be at least " << MIN_LENGTH << ", but it is only " << length; + return false; + } + + case GEF_NACHFORDERUNG_BROADCAST_TELEGRAMME: + return isPayloadLengthOk(10); + + case GEF_SONDERSENSORIK_BETRIEBSZUSTAND: + return isPayloadLengthOk(9); + + case GEF_SONDERSENSORIK_FAHRSPUR: + return isPayloadLengthOk(15); + + case GEF_SONDERSENSORIK_DATEN: + return isPayloadLengthOk(17); + + case GEF_SONDERSENSORIK_MIVANH_VERLEGEDATEN: + return isPayloadLengthOk(24); + + case GEF_SONDERSENSORIK_WMIV_VERLEGEDATEN: + return isPayloadLengthOk(25); + + case GEF_SONDERSENSORIK_MIVANH_VERLEGEPOSITION: + return isPayloadLengthOk(16); + + case GEF_DATENVERKEHR_GEOP_TDS: + + return isPayloadLengthOk(15, 14, 1); + + case GEF_DATENVERKEHR_TGTC_TDS: + + return isPayloadLengthOk(8, 7, 1); + + case GEF_GERAETEEREIGNIS: + + return isPayloadLengthOk(25, 24, 1); + + case GEF_WAFFENZUORDNUNG: + + return isPayloadLengthOk(8, 7, 6); + + case GEF_MUNITIONSVORRAT_EINER_ZUGEORDNETEN_WAFFE: + + return isPayloadLengthOk(13, 12, 5); + + case GEF_IPS_POSITIONSDATEN: + + return isPayloadLengthOk(8, 7, 2); + + case GEF_TREFFER_EREIGNIS_SEKUNDAERWIRKUNG: + return isPayloadLengthOk({13, 17}); + + case GEF_TEILNEHMERMODE_MELDUNG: + return isPayloadLengthOk(15); + + case GEF_TEILNEHMER_KONFIG_ANTWORT: + return isPayloadLengthOk(27); + + case GEF_DEFINITION_IED: + return isPayloadLengthOk(24); + + case GEF_ZUSTAND_IED: + return isPayloadLengthOk(16); + + case GEF_STATUS_EINZELMINENSIMULATOR: + return isPayloadLengthOk(17); + + default: + + break; } - return true; - } - return false; - - case GEF_TECHNIK_FUNKTIONSRAUM: - case GEF_FUNKTIONSRAUM: - case GEF_DEAKTIVIEREN_FUNKTIONSRAUM: - { - uint32_t funktionsraumkennung = getPayloadDataUInt32(5, 2); - if (funktionsraumkennung > 0) - return true; - - ERROR_LOG(m_logger) << "Funktionsraumkennung (" << funktionsraumkennung << ") of telegram with telId=" << getTelID() << " is invalid. Must be 1..65535."; - return false; } - case GEF_EINTRETEN_FUNKTIONSRAUM: - if (isPayloadLengthOk(15)) - { - uint32_t funktionsraumkennung = getPayloadDataUInt32(13, 2); - if (funktionsraumkennung > 0) - return true; - - ERROR_LOG(m_logger) << "Funktionsraumkennung (" << funktionsraumkennung << ") of telegram with telId=" << getTelID() << " is invalid. Must be 1..65535."; - return false; - } - return false; - - case GEF_SPRACHAUSWAHL: - { - uint8_t sprache = getPayloadDataUInt8(5); - if (sprache <= 3) - return true; - - ERROR_LOG(m_logger) << "Sprache (" << sprache << ") of telegram with telId=" << getTelID() << " is invalid. Must be 0..3."; - return false; - } - - - - case GEF_MANIPULATIONSMELDUNG: - return isPayloadLengthOk(12); - - case GEF_BITE_MELDUNG2: - return isPayloadLengthOk(27, 19, 7); - - case GEF_BETRIEBSZUSTAND_AUSSTATTUNG: - return isPayloadLengthOk(9); - - case GEF_FEHLERMELDUNG_GFD: - return isPayloadLengthOk(9); - - case GEF_POSITIONS_MELDUNG: - return isPayloadLengthOk(14); - - case GEF_POSITIONS_MELDUNG_MIT_TEILNEHMER: - return isPayloadLengthOk(15, 14, 2); - - case GEF_POSITIONS_MELDUNG_LFZ: - return isPayloadLengthOk(15); - - case GEF_TREFFER_EREIGNIS_DUS: - return isPayloadLengthOk(23); - - case GEF_TREFFER_EREIGNIS_WIRKSIMULATION: - return isPayloadLengthOk(22); - - case GEF_SCHIEDSRICHTEREINGRIFF: - return isPayloadLengthOk(16); - - case GEF_SELEKTIVE_AUFMUNITIONIERUNG: - return isPayloadLengthOk(8,7,8); - - case GEF_TAKTISCHER_STATUS: - return isPayloadLengthOk(16); - - case GEF_DATENVERKEHR_SRT_TDS: - case GEF_DATENVERKEHR_DMF_TDS: - { - uint16_t length = m_data.size() - DATA_IND_REQ_HEADER_LENGTH; - - const uint16_t MIN_LENGTH = 7; - if (length >= MIN_LENGTH) - return true; - - ERROR_LOG(m_logger) << "The payload-length of telegram with telId=" << getTelID() << " must be at least " << MIN_LENGTH << ", but it is only " << length; - return false; - } - - case GEF_NACHFORDERUNG_BROADCAST_TELEGRAMME: - return isPayloadLengthOk(10); - - case GEF_SONDERSENSORIK_BETRIEBSZUSTAND: - return isPayloadLengthOk(9); - - case GEF_SONDERSENSORIK_FAHRSPUR: - return isPayloadLengthOk(15); - - case GEF_SONDERSENSORIK_DATEN: - return isPayloadLengthOk(17); - - case GEF_SONDERSENSORIK_MIVANH_VERLEGEDATEN: - return isPayloadLengthOk(24); - - case GEF_SONDERSENSORIK_WMIV_VERLEGEDATEN: - return isPayloadLengthOk(25); - - case GEF_SONDERSENSORIK_MIVANH_VERLEGEPOSITION: - return isPayloadLengthOk(16); - - case GEF_DATENVERKEHR_GEOP_TDS: - - return isPayloadLengthOk(15, 14, 1); - - case GEF_DATENVERKEHR_TGTC_TDS: - - return isPayloadLengthOk(8, 7, 1); - - case GEF_GERAETEEREIGNIS: - - return isPayloadLengthOk(25, 24, 1); - - case GEF_WAFFENZUORDNUNG: - - return isPayloadLengthOk(8, 7, 6); - - case GEF_MUNITIONSVORRAT_EINER_ZUGEORDNETEN_WAFFE: - - return isPayloadLengthOk(13, 12, 5); - - case GEF_IPS_POSITIONSDATEN: - - return isPayloadLengthOk(8, 7, 2); - - case GEF_TREFFER_EREIGNIS_SEKUNDAERWIRKUNG: - return isPayloadLengthOk({13, 17}); - - case GEF_TEILNEHMERMODE_MELDUNG: - return isPayloadLengthOk(15); - - case GEF_TEILNEHMER_KONFIG_ANTWORT: - return isPayloadLengthOk(27); - - case GEF_DEFINITION_IED: - return isPayloadLengthOk(24); - - case GEF_ZUSTAND_IED: - return isPayloadLengthOk(16); - - case GEF_STATUS_EINZELMINENSIMULATOR: - return isPayloadLengthOk(17); - - default: - - - break; - } - } - return true; + return true; } - - - - - - -bool CoPrtCnvRadioTelegram::isPayloadLengthOk(uint16_t a_minLength, - const uint16_t a_dataAmountOffset, +bool CoPrtCnvRadioTelegram::isPayloadLengthOk(uint16_t a_minLength, const uint16_t a_dataAmountOffset, const uint8_t a_variableDataElementSize) const { - if (0 == a_variableDataElementSize) - return isPayloadLengthOk(a_minLength); + if (0 == a_variableDataElementSize) + return isPayloadLengthOk(a_minLength); - const uint16_t length = getPayloadSize(); - if (length >= a_minLength) - { - uint8_t dataAmount = getPayloadDataUInt8(a_dataAmountOffset); - uint16_t dataSize = a_variableDataElementSize * dataAmount; - uint16_t expectedLength = dataSize + a_minLength; - if (expectedLength != length) + const uint16_t length = getPayloadSize(); + if (length >= a_minLength) { - WARNING_LOG(m_logger) << "The payload-length of telegram with telId: " - << getTelID() << " must be " << expectedLength - << ", but it is " << length << " (the amount of variable data in telegram was " - << dataAmount << " => " << dataSize << " bytes)"; - return false; + uint8_t dataAmount = getPayloadDataUInt8(a_dataAmountOffset); + uint16_t dataSize = a_variableDataElementSize * dataAmount; + uint16_t expectedLength = dataSize + a_minLength; + if (expectedLength != length) + { + WARNING_LOG(m_logger) << "The payload-length of telegram with telId: " << getTelID() << " must be " + << expectedLength << ", but it is " << length + << " (the amount of variable data in telegram was " << dataAmount << " => " + << dataSize << " bytes)"; + return false; + } } - } - else - { - WARNING_LOG(m_logger) << "The payload-length of telegram with telId: " << getTelID() - << " must be at least " << a_minLength << ", but it is only " << length; - return false; - } - return true; + else + { + WARNING_LOG(m_logger) << "The payload-length of telegram with telId: " << getTelID() << " must be at least " + << a_minLength << ", but it is only " << length; + return false; + } + return true; } -bool CoPrtCnvRadioTelegram::isPayloadLengthOk(uint16_t a_minLength, - uint16_t a_maxLength) const +bool CoPrtCnvRadioTelegram::isPayloadLengthOk(uint16_t a_minLength, uint16_t a_maxLength) const { - if (a_maxLength == 0) - return isPayloadLengthOk(a_minLength); + if (a_maxLength == 0) + return isPayloadLengthOk(a_minLength); - const uint16_t length = getPayloadSize(); - if (length < a_minLength) - { - WARNING_LOG(m_logger) << "The payload-length of telegram with telId: " - << getTelID() << " must be greater or equal to " - << a_minLength << ", but it is " << length; - return false; - } + const uint16_t length = getPayloadSize(); + if (length < a_minLength) + { + WARNING_LOG(m_logger) << "The payload-length of telegram with telId: " << getTelID() + << " must be greater or equal to " << a_minLength << ", but it is " << length; + return false; + } - if (length > a_maxLength) - { - WARNING_LOG(m_logger) << "The payload-length of telegram with telId: " - << getTelID() << " must be fewer than " - << a_minLength << ", but it is " << length; - return false; - } - return true; + if (length > a_maxLength) + { + WARNING_LOG(m_logger) << "The payload-length of telegram with telId: " << getTelID() << " must be fewer than " + << a_minLength << ", but it is " << length; + return false; + } + return true; } bool CoPrtCnvRadioTelegram::isPayloadLengthOk(uint16_t a_length) const { - const uint16_t length = getPayloadSize(); - if (length == a_length) - return true; + const uint16_t length = getPayloadSize(); + if (length == a_length) + return true; - WARNING_LOG(m_logger) << "The payload-length of telegram with telId: " - << getTelID() << " must be " - << a_length << ", but it is " << length; - return false; + WARNING_LOG(m_logger) << "The payload-length of telegram with telId: " << getTelID() << " must be " << a_length + << ", but it is " << length; + return false; } -bool CoPrtCnvRadioTelegram::isPayloadLengthOk(const std::vector &a_lengths) const +bool CoPrtCnvRadioTelegram::isPayloadLengthOk(const std::vector& a_lengths) const { - const uint16_t length = getPayloadSize(); - if (std::any_of(a_lengths.begin(), a_lengths.end(), [length](int len) { return len == length;})) - return true; + const uint16_t length = getPayloadSize(); + if (std::any_of(a_lengths.begin(), a_lengths.end(), [length](int len) { return len == length; })) + return true; - WARNING_LOG(m_logger) << "The payload-length of telegram with telId: " - << getTelID() << ", is: " << length; - return false; + WARNING_LOG(m_logger) << "The payload-length of telegram with telId: " << getTelID() << ", is: " << length; + return false; } - - - - -bool CoPrtCnvRadioTelegram::mustBeSentAsBroadcast(time_t a_currentTime, bool &a_wasLastBroadcast, const bool a_updateBroadcastCounter) +bool CoPrtCnvRadioTelegram::mustBeSentAsBroadcast(time_t a_currentTime, bool& a_wasLastBroadcast, + const bool a_updateBroadcastCounter) { - a_wasLastBroadcast = false; - - if (m_BroadcastCounter < s_maxBroadcastSendCnt && m_NextSendTime <= a_currentTime) - { - if (a_updateBroadcastCounter) + a_wasLastBroadcast = false; + + if (m_BroadcastCounter < s_maxBroadcastSendCnt && m_NextSendTime <= a_currentTime) { - - switch (m_BroadcastCounter) - { - case 0: - if (s_2ndDelay >= 0) + if (a_updateBroadcastCounter) { - m_NextSendTime = time(nullptr) + s_2ndDelay; - INFO_LOG(m_logger) << "1st Broadcast-Telegram telId=" << getTelID() << " BC=" << getBroadcastIndex(); - break; + + switch (m_BroadcastCounter) + { + case 0: + if (s_2ndDelay >= 0) + { + m_NextSendTime = time(nullptr) + s_2ndDelay; + INFO_LOG(m_logger) + << "1st Broadcast-Telegram telId=" << getTelID() << " BC=" << getBroadcastIndex(); + break; + } + ++m_BroadcastCounter; + Q_FALLTHROUGH(); + case 1: + if (s_3rdDelay >= 0) + { + m_NextSendTime = time(nullptr) + s_3rdDelay; + INFO_LOG(m_logger) + << "2nd Broadcast-Telegram telId=" << getTelID() << " BC=" << getBroadcastIndex(); + break; + } + ++m_BroadcastCounter; + Q_FALLTHROUGH(); + default: + INFO_LOG(m_logger) << "3rd Broadcast-Telegram telId=" << getTelID() + << " BC=" << getBroadcastIndex(); + m_NextSendTime = 0; + a_wasLastBroadcast = true; + } + ++m_BroadcastCounter; } - ++m_BroadcastCounter; - Q_FALLTHROUGH(); - case 1: - if (s_3rdDelay >= 0) - { - m_NextSendTime = time(nullptr) + s_3rdDelay; - INFO_LOG(m_logger) << "2nd Broadcast-Telegram telId=" << getTelID() << " BC=" << getBroadcastIndex(); - break; - } - ++m_BroadcastCounter; - Q_FALLTHROUGH(); - default: - INFO_LOG(m_logger) << "3rd Broadcast-Telegram telId=" << getTelID() << " BC=" << getBroadcastIndex(); - m_NextSendTime = 0; - a_wasLastBroadcast = true; - } - ++m_BroadcastCounter; + return true; } - return true; - } - return false; + return false; } - - - - void CoPrtCnvRadioTelegram::setBroadcastDelayTimes(int a_2ndDelay, int a_3rdDelay) { - s_2ndDelay = a_2ndDelay; - s_3rdDelay = a_3rdDelay; + s_2ndDelay = a_2ndDelay; + s_3rdDelay = a_3rdDelay; } - - - - void CoPrtCnvRadioTelegram::setMaxBroadcastSendCnt(int a_maxSendCnt) { - s_maxBroadcastSendCnt = a_maxSendCnt; + s_maxBroadcastSendCnt = a_maxSendCnt; } - - - - - bool CoPrtCnvRadioTelegram::isMovedToBroadcastList() const { - return (m_BroadcastCounter >= 1); + return (m_BroadcastCounter >= 1); } - - - - void CoPrtCnvRadioTelegram::setBroadcastOnly(const bool a_doSet) { - m_IsBroadcastOnly = a_doSet; + m_IsBroadcastOnly = a_doSet; } - - - - bool CoPrtCnvRadioTelegram::isBroadcastOnly() const { - return m_IsBroadcastOnly; + return m_IsBroadcastOnly; } - - - - - -void CoPrtCnvRadioTelegram::setBroadcastonlyTelegram(const std::shared_ptr &a_radioTelegram) +void CoPrtCnvRadioTelegram::setBroadcastonlyTelegram( + const std::shared_ptr& a_radioTelegram) { - if (a_radioTelegram != nullptr && m_BroadcastOnlyTelegram != nullptr) - ERROR_LOG(m_logger) << "Internal error: m_BroadcastOnlyTelegram was not nullptr"; - if (a_radioTelegram != nullptr) - { - INFO_LOG(m_logger) << "Set braodcastonly-telegram: telId=" << a_radioTelegram->getTelID() - << " BC=" << a_radioTelegram->getBroadcastIndex(); - } - m_BroadcastOnlyTelegram = a_radioTelegram; + if (a_radioTelegram != nullptr && m_BroadcastOnlyTelegram != nullptr) + ERROR_LOG(m_logger) << "Internal error: m_BroadcastOnlyTelegram was not nullptr"; + if (a_radioTelegram != nullptr) + { + INFO_LOG(m_logger) << "Set braodcastonly-telegram: telId=" << a_radioTelegram->getTelID() + << " BC=" << a_radioTelegram->getBroadcastIndex(); + } + m_BroadcastOnlyTelegram = a_radioTelegram; } - - - - - std::shared_ptr CoPrtCnvRadioTelegram::getBroadcastonlyTelegram() const { - return m_BroadcastOnlyTelegram; + return m_BroadcastOnlyTelegram; } - - - - -void CoPrtCnvRadioTelegram::set1Byte(QByteArray &a_data, uint16_t a_offset, uint8_t a_value) +void CoPrtCnvRadioTelegram::set1Byte(QByteArray& a_data, uint16_t a_offset, uint8_t a_value) { - Q_ASSERT(a_offset < a_data.size()); - uint8_t *ptr = reinterpret_cast(&a_data.data()[a_offset]); - *ptr = a_value; + Q_ASSERT(a_offset < a_data.size()); + uint8_t* ptr = reinterpret_cast(&a_data.data()[a_offset]); + *ptr = a_value; } - - - - -void CoPrtCnvRadioTelegram::set2Byte(QByteArray &a_data, uint16_t a_offset, uint16_t a_value) +void CoPrtCnvRadioTelegram::set2Byte(QByteArray& a_data, uint16_t a_offset, uint16_t a_value) { - Q_ASSERT(a_offset < a_data.size()); - uint16_t *ptr = reinterpret_cast(&a_data.data()[a_offset]); - *ptr = a_value; + Q_ASSERT(a_offset < a_data.size()); + uint16_t* ptr = reinterpret_cast(&a_data.data()[a_offset]); + *ptr = a_value; } - - - - -void CoPrtCnvRadioTelegram::set4Byte(QByteArray &a_data, uint16_t a_offset, uint32_t a_value) +void CoPrtCnvRadioTelegram::set4Byte(QByteArray& a_data, uint16_t a_offset, uint32_t a_value) { - Q_ASSERT(a_offset < a_data.size()); - uint32_t *ptr = reinterpret_cast(&a_data.data()[a_offset]); - *ptr = a_value; + Q_ASSERT(a_offset < a_data.size()); + uint32_t* ptr = reinterpret_cast(&a_data.data()[a_offset]); + *ptr = a_value; } - - - - - - - uint16_t CoPrtCnvRadioTelegram::getUInt16(const uint16_t a_offset) const { - const uint16_t *ptr = reinterpret_cast(&m_data.data()[a_offset]); - return *ptr; + const uint16_t* ptr = reinterpret_cast(&m_data.data()[a_offset]); + return *ptr; } - - - - - - - uint32_t CoPrtCnvRadioTelegram::getUInt32(const uint16_t a_offset) const { - const uint32_t *ptr = reinterpret_cast(&m_data.data()[a_offset]); - return *ptr; + const uint32_t* ptr = reinterpret_cast(&m_data.data()[a_offset]); + return *ptr; } - - - - - -void CoPrtCnvRadioTelegram::setHeader(QByteArray &data, E_PDU_Type pduType) +void CoPrtCnvRadioTelegram::setHeader(QByteArray& data, E_PDU_Type pduType) { - - set1Byte(data, 0, MAGIC_NUMBER); - set1Byte(data, 1, 0); - set2Byte(data, 2, data.size() - sizeof(PrtCnvRadioGwHeader)); - set1Byte(data, 4, pduType); + + set1Byte(data, 0, MAGIC_NUMBER); + set1Byte(data, 1, 0); + set2Byte(data, 2, data.size() - sizeof(PrtCnvRadioGwHeader)); + set1Byte(data, 4, pduType); } - - - - - - - - -void CoPrtCnvRadioTelegram::fillDataIndReqHeader(QByteArray &a_data) +void CoPrtCnvRadioTelegram::fillDataIndReqHeader(QByteArray& a_data) { - set1Byte(a_data, 4, e_DataIndReq); - setSrcISSI_Internal(a_data, 0); - setDestISSI_Internal(a_data, 0); + set1Byte(a_data, 4, e_DataIndReq); + setSrcISSI_Internal(a_data, 0); + setDestISSI_Internal(a_data, 0); - set1Byte(a_data, 13, s_protocolIdentifier); - set1Byte(a_data, 14, 0); - set1Byte(a_data, 15, 0); - set1Byte(a_data, 16, 0); - set1Byte(a_data, 17, 0); - set1Byte(a_data, 18, 0); - set1Byte(a_data, 19, 0); - set1Byte(a_data, 20, 0); - set1Byte(a_data, 21, e_FlagsNone); - - uint16_t size = a_data.size(); - set2Byte(a_data, 22, (size - DATA_IND_REQ_HEADER_LENGTH + PAYLOAD_STATUS_LENGTH) * 8); - set2Byte(a_data, 24, (size - DATA_IND_REQ_HEADER_LENGTH + PAYLOAD_STATUS_LENGTH)); + set1Byte(a_data, 13, s_protocolIdentifier); + set1Byte(a_data, 14, 0); + set1Byte(a_data, 15, 0); + set1Byte(a_data, 16, 0); + set1Byte(a_data, 17, 0); + set1Byte(a_data, 18, 0); + set1Byte(a_data, 19, 0); + set1Byte(a_data, 20, 0); + set1Byte(a_data, 21, e_FlagsNone); + + uint16_t size = a_data.size(); + set2Byte(a_data, 22, (size - DATA_IND_REQ_HEADER_LENGTH + PAYLOAD_STATUS_LENGTH) * 8); + set2Byte(a_data, 24, (size - DATA_IND_REQ_HEADER_LENGTH + PAYLOAD_STATUS_LENGTH)); } - - - - -void CoPrtCnvRadioTelegram::setSrcISSI_Internal(QByteArray &data, const uint32_t issi) +void CoPrtCnvRadioTelegram::setSrcISSI_Internal(QByteArray& data, const uint32_t issi) { - set4Byte(data, 5, issi); + set4Byte(data, 5, issi); } - - - - - uint16_t CoPrtCnvRadioTelegram::getBroadcastCounter() const { - return m_BroadcastCounter; + return m_BroadcastCounter; } - - - - -void CoPrtCnvRadioTelegram::setDestISSI_Internal(QByteArray &data, const uint32_t issi) +void CoPrtCnvRadioTelegram::setDestISSI_Internal(QByteArray& data, const uint32_t issi) { - set4Byte(data, 9, issi); + set4Byte(data, 9, issi); } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvRadioTelegram.hpp b/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvRadioTelegram.hpp index 75047cb77..583323bf2 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvRadioTelegram.hpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvRadioTelegram.hpp @@ -595,6 +595,10 @@ protected: static void setDestISSI_Internal(QByteArray &data, const uint32_t issi); private: + /** + * The logger object + */ + NGL::INGLLogger &m_logger; }; } diff --git a/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvTelegramConverterNewIcd.cpp b/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvTelegramConverterNewIcd.cpp index e273355f1..ed27c6471 100644 --- a/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvTelegramConverterNewIcd.cpp +++ b/qt6-after/qt6-migrated-legatus/TetraIF/CoPrtCnv/CoPrtCnvTelegramConverterNewIcd.cpp @@ -1,2132 +1,1815 @@ - - - - - - - - - - - - +#include "CoPrtCnvCentralTelegram.hpp" +#include "CoPrtCnvRadioTelegram.hpp" #include "CoPrtCnvTelegramConverter.hpp" -#include - +#include #include #include #include -#include -#include "CoPrtCnvCentralTelegram.hpp" -#include "CoPrtCnvRadioTelegram.hpp" -#include #include #include +#include #include using namespace TrainingAreaBase::TetraIcd; + namespace N_CoPrtCnv { namespace CoPrtCnvTelegramConverter { -static QTextCodec *s_TetraTextCodec = nullptr; -static bool s_needTextCodec = false; static bool s_use2BytesForSingleFireDiameter = true; static bool s_usePvSan = false; -static inline NGL::INGLLogger &logger() +static inline NGL::INGLLogger& logger() { - return NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("CoPrtCnvTelegramConverter"); + return NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("CoPrtCnvTelegramConverter"); } -template -static inline bool checkBitmask(const T &d, int bitmask) +template static inline bool checkBitmask(const T& d, int bitmask) { - return ((d & bitmask) == bitmask); + return ((d & bitmask) == bitmask); } -template -void getSpecialSensorData(const CoPrtCnvRadioTelegram *a_radioTelegram, size_t offset, T *tele) +template void getSpecialSensorData(const CoPrtCnvRadioTelegram* a_radioTelegram, size_t offset, T* tele) { - const uint8_t betrZust = a_radioTelegram->getPayloadDataUInt32(offset, 1); - const uint8_t spuerfunktion = a_radioTelegram->getPayloadDataUInt32(offset + 1, 1); - tele->operationalState = betrZust; - tele->airSensor = checkBitmask(spuerfunktion, 0x80); - tele->tireSensor = checkBitmask(spuerfunktion, 0x40); - tele->pointSensor = checkBitmask(spuerfunktion, 0x20); - tele->solidMatterSampleExtractor = checkBitmask(spuerfunktion, 0x10); + const uint8_t betrZust = a_radioTelegram->getPayloadDataUInt32(offset, 1); + const uint8_t spuerfunktion = a_radioTelegram->getPayloadDataUInt32(offset + 1, 1); + tele->operationalState = betrZust; + tele->airSensor = checkBitmask(spuerfunktion, 0x80); + tele->tireSensor = checkBitmask(spuerfunktion, 0x40); + tele->pointSensor = checkBitmask(spuerfunktion, 0x20); + tele->solidMatterSampleExtractor = checkBitmask(spuerfunktion, 0x10); } int getVitality(uint32_t index) { - uint32_t vitalty = (index &= 0xF000); - uint32_t retVitalty = 0; - retVitalty = vitalty >> 12; - if (retVitalty > 0) - { - retVitalty -= 1; - return retVitalty * 10; - } - return UINT16_MAX; -} - -void setVitality(uint16_t &index, uint16_t vitality) -{ - if (vitality == UINT16_MAX) - vitality = 0; - else - { - vitality /= 10; - vitality += 1; - if (vitality > 11) + uint32_t vitalty = (index &= 0xF000); + uint32_t retVitalty = 0; + retVitalty = vitalty >> 12; + if (retVitalty > 0) { - ERROR_LOG(logger()) << "Cant convert Vitality!"; - return; + retVitalty -= 1; + return retVitalty * 10; } - } - for (int i = 0; i <= 3; i++) - { - if (((vitality) & (1 << (i)))) - index |= (1UL << (i + 12)); - } + return UINT16_MAX; } -template -void getTaktZustand(const CoPrtCnvRadioTelegram *a_radioTelegram, size_t iOffset, T *tele) + +void setVitality(uint16_t& index, uint16_t vitality) { - tele->vulnerabilityState = static_cast( - a_radioTelegram->getPayloadDataUInt32(iOffset + 0, 1)); - - const uint32_t teilnehmertyp = a_radioTelegram->getPayloadDataUInt32(iOffset + 1, 1); - const uint32_t index = a_radioTelegram->getPayloadDataUInt32(iOffset + 2, 2); - if (index) - { - uint32_t indexForVulnerabilit = index; - indexForVulnerabilit &= 0x0FFF; - tele->tasVulnerabilityKindId = teilnehmertyp; - tele->tasVulnerabilityKindId <<= 16; - tele->tasVulnerabilityKindId |= indexForVulnerabilit; - tele->tasVitality = getVitality(index); - } - else - tele->tasVulnerabilityKindId = 0; - - - tele->vulnerabilityBits = 0; - int tmp = a_radioTelegram->getPayloadDataUInt32(iOffset + 4, 2); - - if (tmp == 0) - tele->vulnerabilityBits |= 0x1; - else - { - - for (int i = 1; i <= static_cast(VulnerabilityState::CContamination); ++i) - tele->vulnerabilityBits |= ((tmp >> (16 - i)) & 0x1) << (i); - } + if (vitality == UINT16_MAX) + vitality = 0; + else + { + vitality /= 10; + vitality += 1; + if (vitality > 11) + { + ERROR_LOG(logger()) << "Cant convert Vitality!"; + return; + } + } + for (int i = 0; i <= 3; i++) + { + if (((vitality) & (1 << (i)))) + index |= (1UL << (i + 12)); + } } -static BiteError getBiteError(const CoPrtCnvRadioTelegram *a_radioTelegram, size_t iOffset) +template void getTaktZustand(const CoPrtCnvRadioTelegram* a_radioTelegram, size_t iOffset, T* tele) { - BiteError ret; - ret.canDeviceNumber = a_radioTelegram->getPayloadDataUInt8(iOffset + 0); - ret.subdeviceNumber = a_radioTelegram->getPayloadDataUInt8(iOffset + 1); - ret.uniqueId = a_radioTelegram->getPayloadDataUInt32(iOffset + 2, 4); - ret.errorNumber = a_radioTelegram->getPayloadDataUInt8(iOffset + 6); + tele->vulnerabilityState = static_cast( + a_radioTelegram->getPayloadDataUInt32(iOffset + 0, 1)); - return ret; + const uint32_t teilnehmertyp = a_radioTelegram->getPayloadDataUInt32(iOffset + 1, 1); + const uint32_t index = a_radioTelegram->getPayloadDataUInt32(iOffset + 2, 2); + if (index) + { + uint32_t indexForVulnerabilit = index; + indexForVulnerabilit &= 0x0FFF; + tele->tasVulnerabilityKindId = teilnehmertyp; + tele->tasVulnerabilityKindId <<= 16; + tele->tasVulnerabilityKindId |= indexForVulnerabilit; + tele->tasVitality = getVitality(index); + } + else + tele->tasVulnerabilityKindId = 0; + + tele->vulnerabilityBits = 0; + int tmp = a_radioTelegram->getPayloadDataUInt32(iOffset + 4, 2); + + if (tmp == 0) + tele->vulnerabilityBits |= 0x1; + else + { + + for (int i = 1; i <= static_cast(VulnerabilityState::CContamination); ++i) + tele->vulnerabilityBits |= ((tmp >> (16 - i)) & 0x1) << (i); + } } -static void convertToTetraEncoding(N_CoPrtCnv::CoPrtCnvRadioTelegram *radioTelegramm, - const std::string &stdString, +static BiteError getBiteError(const CoPrtCnvRadioTelegram* a_radioTelegram, size_t iOffset) +{ + BiteError ret; + ret.canDeviceNumber = a_radioTelegram->getPayloadDataUInt8(iOffset + 0); + ret.subdeviceNumber = a_radioTelegram->getPayloadDataUInt8(iOffset + 1); + ret.uniqueId = a_radioTelegram->getPayloadDataUInt32(iOffset + 2, 4); + ret.errorNumber = a_radioTelegram->getPayloadDataUInt8(iOffset + 6); + + return ret; +} + +static void convertToTetraEncoding(N_CoPrtCnv::CoPrtCnvRadioTelegram* radioTelegramm, const std::string& stdString, const uint16_t a_size) { - QByteArray encodedData; - if (s_needTextCodec && s_TetraTextCodec) - { - - const QString str = QString::fromUtf8(stdString.c_str()); - - encodedData = s_TetraTextCodec->fromUnicode(str); - } - else - encodedData = QByteArray(stdString.c_str(), a_size); - - encodedData = encodedData.leftJustified(a_size, '\0', true); - - encodedData[a_size - 1] = '\0'; + QByteArray encodedData = QByteArray::fromStdString(stdString); + encodedData = encodedData.leftJustified(a_size, '\0', true); + encodedData[a_size - 1] = '\0'; - const uint8_t *data = reinterpret_cast(encodedData.data()); - radioTelegramm->setPayloadData(data, a_size); + const uint8_t* data = reinterpret_cast(encodedData.data()); + radioTelegramm->setPayloadData(data, a_size); } -void setTetraTextCodec(const char *codecName) +void setTetraTextCodec(const char* /*codecName*/) { - if (codecName) - s_TetraTextCodec = QTextCodec::codecForName(codecName); - else - s_TetraTextCodec = nullptr; - s_needTextCodec = (s_TetraTextCodec != nullptr); + // Qt6 uses UTF-8 by default, QTextCodec is no longer available } void setUse2BytesForSingleFireDiameter(bool bUse) { - s_use2BytesForSingleFireDiameter = bUse; + s_use2BytesForSingleFireDiameter = bUse; } void setUsePvSan(bool bUse) { - s_usePvSan = bUse; + s_usePvSan = bUse; } -template -T fromJson(CoPrtCnvCentralTelegram *radioTelegram) +template T fromJson(CoPrtCnvCentralTelegram* radioTelegram) { - return T::fromJson(radioTelegram->jsonData()); + return T::fromJson(radioTelegram->jsonData()); } -template -const T &fromJson(const TrainingAreaBase::TetraIcd::TrainingAreaTelegram *tabTelegram) +template const T& fromJson(const TrainingAreaBase::TetraIcd::TrainingAreaTelegram* tabTelegram) { - return static_cast(*tabTelegram); + return static_cast(*tabTelegram); } -TrainingAreaBase::TetraIcd::TelegramId getTelegramId(CoPrtCnvCentralTelegram *centralTelegram) +TrainingAreaBase::TetraIcd::TelegramId getTelegramId(CoPrtCnvCentralTelegram* centralTelegram) { - return TrainingAreaBase::TetraIcd::TelegramId(centralTelegram->telegramId()); + return TrainingAreaBase::TetraIcd::TelegramId(centralTelegram->telegramId()); } -TrainingAreaBase::TetraIcd::TelegramId getTelegramId( - const TrainingAreaBase::TetraIcd::TrainingAreaTelegram *tabTelegram) +TrainingAreaBase::TetraIcd::TelegramId +getTelegramId(const TrainingAreaBase::TetraIcd::TrainingAreaTelegram* tabTelegram) { - return tabTelegram->id(); + return tabTelegram->id(); } -void convertToSecAndSetTime(int64_t timeStamp, N_CoPrtCnv::CoPrtCnvRadioTelegram *radioTelegram) +void convertToSecAndSetTime(int64_t timeStamp, N_CoPrtCnv::CoPrtCnvRadioTelegram* radioTelegram) { - radioTelegram->setPayloadData((uint32_t)(timeStamp / 1000), 4); + radioTelegram->setPayloadData((uint32_t)(timeStamp / 1000), 4); } -template -void setCommonAesParams(const T &tele, CoPrtCnvRadioTelegram *radioTelegram) +template void setCommonAesParams(const T& tele, CoPrtCnvRadioTelegram* radioTelegram) { - radioTelegram->setPayloadData((uint32_t) 0, 2); - radioTelegram->setPayloadData(tele.aesDdsId, 2); - convertToTetraEncoding(radioTelegram, tele.name, 8); - radioTelegram->setPayloadData(tele.partyId, 1); - convertToSecAndSetTime(tele.effectStart, radioTelegram); + radioTelegram->setPayloadData((uint32_t)0, 2); + radioTelegram->setPayloadData(tele.aesDdsId, 2); + convertToTetraEncoding(radioTelegram, tele.name, 8); + radioTelegram->setPayloadData(tele.partyId, 1); + convertToSecAndSetTime(tele.effectStart, radioTelegram); } -template -void setAesPosition(const T &tele, CoPrtCnvRadioTelegram *radioTelegram) +template void setAesPosition(const T& tele, CoPrtCnvRadioTelegram* radioTelegram) { - radioTelegram->setPayloadData(tele.relEffectPosition.offsetY, 3); - radioTelegram->setPayloadData(tele.relEffectPosition.offsetX, 3); + radioTelegram->setPayloadData(tele.relEffectPosition.offsetY, 3); + radioTelegram->setPayloadData(tele.relEffectPosition.offsetX, 3); } - static inline int compassToMathAngleForSfm(double compassDegree) { - int ret = qRound((90.0 - compassDegree) * 100.0); - while (ret < 0) - ret += 36000; - while (ret > 36000) - ret -= 36000; - return ret; + int ret = qRound((90.0 - compassDegree) * 100.0); + while (ret < 0) + ret += 36000; + while (ret > 36000) + ret -= 36000; + return ret; } - - - - -template -static CoPrtCnvRadioTelegram *convertToRadioInternal(T *a_telegram) +template static CoPrtCnvRadioTelegram* convertToRadioInternal(T* a_telegram) { - N_CoPrtCnv::CoPrtCnvRadioTelegram *radioTelegram = nullptr; - switch (getTelegramId(a_telegram)) - { - case Constraints::id(): - { - const Init &tele(fromJson(a_telegram)); - - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_INIT, 4, tele.header.equipmentNumber); - uint8_t initialisierungsdaten = 0; - initialisierungsdaten |= ((uint8_t(tele.resetVulnerabilityState) & 0x01) << 6); - initialisierungsdaten |= ((uint8_t(tele.restockCharges) & 0x01) << 5); - initialisierungsdaten |= ((uint8_t(tele.resetManipulation) & 0x01) << 0); - initialisierungsdaten |= ((uint8_t(tele.restockSanitationMaterial) & 0x01) << 1); - - - - radioTelegram->setPayloadData(initialisierungsdaten); - break; - } - - case Constraints::id(): - { - const SetVulnerabilityModel &tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_KONFIGURATION_WIRKMODELL, - 9, - tele.header.equipmentNumber); - radioTelegram->setPayloadData((uint32_t) 0, - 2); - radioTelegram->setPayloadData((uint8_t) tele.vulnerabilityModelMineIed); - radioTelegram->setPayloadData((uint8_t) tele.vulnerabilityModelAreaFire); - radioTelegram->setPayloadData((uint8_t) tele.vulnerabilityModelOperatingResource); - radioTelegram->setPayloadData((uint8_t) tele.vulnerabilityModelAcWeaponry); - break; - } - case Constraints::id(): - { - const DemandEquipmentConfigurationReport &tele( - fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_ANFORDERUNG_KONFIGURATIONSDATEN, - 3, - tele.header.equipmentNumber); - break; - } - case Constraints::id(): - { - const StateChange &tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TAKTISCHER_STATUS, - 16, - tele.header.equipmentNumber); - - convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); - - radioTelegram->setPayloadData((uint8_t) tele.vulnerabilityState); - radioTelegram->setPayloadData((uint8_t)(tele.tasVulnerabilityKindId & 0xFF)); - uint16_t vulnerabilityVitalityIndex = 0; - vulnerabilityVitalityIndex = (uint16_t)((tele.tasVulnerabilityKindId >> 16) & 0xFFFF); - setVitality(vulnerabilityVitalityIndex, tele.tasVitality); - radioTelegram->setPayloadData((uint16_t) vulnerabilityVitalityIndex, 2); - - - radioTelegram->setPayloadData((uint16_t) tele.vulnerabilityBits, 2); - - radioTelegram->setPayloadData((uint8_t) tele.originatorId); - radioTelegram->setPayloadData((uint16_t) tele.originatorType, 2); - break; - } - case Constraints::id(): - { - const BiteReport &tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_BITE_MELDUNG2, - 27, - tele.header.equipmentNumber); - convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); - radioTelegram->setPayloadData((uint8_t) tele.loginType); - radioTelegram->setPayloadData((uint32_t) tele.biteState, 3); - radioTelegram->setPayloadData((uint8_t) tele.batteryState); - - if (tele.biteErrors.size() > 0) + N_CoPrtCnv::CoPrtCnvRadioTelegram* radioTelegram = nullptr; + switch (getTelegramId(a_telegram)) { - radioTelegram->setPayloadData((uint8_t) tele.biteErrors[0].canDeviceNumber); - radioTelegram->setPayloadData((uint8_t) tele.biteErrors[0].subdeviceNumber); - radioTelegram->setPayloadData((uint32_t) tele.biteErrors[0].uniqueId, 4); - radioTelegram->setPayloadData((uint8_t) tele.biteErrors[0].errorNumber); - radioTelegram->setPayloadData((uint8_t) tele.biteErrors.size() - 1); - } - else - { - radioTelegram->setPayloadData((uint8_t) 0); - radioTelegram->setPayloadData((uint8_t) 0); - radioTelegram->setPayloadData((uint32_t) 0, 4); - radioTelegram->setPayloadData((uint8_t) 0); - radioTelegram->setPayloadData((uint8_t) 0); - } + case Constraints::id(): { + const Init& tele(fromJson(a_telegram)); - radioTelegram->setPayloadData((uint32_t) 0, 3); - radioTelegram->setPayloadData((uint8_t) tele.configError); - radioTelegram->setPayloadData((uint32_t) tele.configState, 3); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_INIT, 4, tele.header.equipmentNumber); + uint8_t initialisierungsdaten = 0; + initialisierungsdaten |= ((uint8_t(tele.resetVulnerabilityState) & 0x01) << 6); + initialisierungsdaten |= ((uint8_t(tele.restockCharges) & 0x01) << 5); + initialisierungsdaten |= ((uint8_t(tele.resetManipulation) & 0x01) << 0); + initialisierungsdaten |= ((uint8_t(tele.restockSanitationMaterial) & 0x01) << 1); - for (const BiteError &be : tele.biteErrors) - { - radioTelegram->setPayloadData((uint8_t) be.canDeviceNumber); - radioTelegram->setPayloadData((uint8_t) be.subdeviceNumber); - radioTelegram->setPayloadData((uint32_t) be.uniqueId, 4); - radioTelegram->setPayloadData((uint8_t) be.errorNumber); - } - break; - } - case Constraints::id(): - { - const ExerciseEnvironmentData &tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_UMGEBUNGS_MELDUNG2, - 20, - tele.header.equipmentNumber); - radioTelegram->setPayloadData((uint32_t) 0, - 2); - radioTelegram->setPayloadData(tele.exerciseId, 2); - radioTelegram->setPayloadData((uint8_t) 0); - radioTelegram->setPayloadData( - (uint8_t) 0); - radioTelegram->setPayloadData((uint8_t) tele.timeZone); - radioTelegram->setPayloadData((uint8_t) tele.utmZone); - radioTelegram->setPayloadData(tele.utmBand); - radioTelegram->setPayloadData((uint8_t *) tele.grid.c_str(), 2); - radioTelegram->setPayloadData((uint8_t) 0); - radioTelegram->setPayloadData((uint8_t) 0); - radioTelegram->setPayloadData((uint32_t) 0, - 4); - break; - } - case Constraints::id(): - { - const DemandBite &tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_AUFFORDERUNG_BITE_MELDUNG, - 4, - tele.header.equipmentNumber); - radioTelegram->setPayloadData(tele.withSelfTest, 1); - break; - } - case Constraints::id(): - { - const PositionReport &tele(fromJson(a_telegram)); - - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_POSITIONS_MELDUNG, - 14, - tele.header.equipmentNumber); - convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); - radioTelegram->setPayloadData(tele.relPosition.offsetY, 3); - radioTelegram->setPayloadData(tele.relPosition.offsetX, 3); - radioTelegram->setPayloadData((uint8_t)(((tele.gpsQuality.moreThan4SatellitesAvailable) ? 0x80 - : 0) - | ((tele.gpsQuality.dgpsModeAvailable) ? 0x40 : 0) - | (tele.gpsQuality.pdopValue & 0x3f)), - 1); - break; - } - case Constraints::id(): - { - const CreateSingleExplosion &tele(fromJson(a_telegram)); - - const int teleSize = s_use2BytesForSingleFireDiameter ? 29 : 28; - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_EINZELGESCHOSS, - teleSize, - tele.header.equipmentNumber); - setCommonAesParams(tele, radioTelegram); - setAesPosition(tele, radioTelegram); - if (s_use2BytesForSingleFireDiameter) - { - Q_ASSERT(tele.effectDiameter < 256 * 256 && tele.effectDiameter >= 0); - radioTelegram->setPayloadData(tele.effectDiameter, 2); - } - else - { - Q_ASSERT(tele.effectDiameter < 256 && tele.effectDiameter >= 0); - radioTelegram->setPayloadData(tele.effectDiameter, 1); - } - radioTelegram->setPayloadData(tele.chargeTypeId, 1); - break; - } - case Constraints::id(): - { - const CreateAreaExplosion &tele(fromJson(a_telegram)); + radioTelegram->setPayloadData(initialisierungsdaten); + break; + } + + case Constraints::id(): { + const SetVulnerabilityModel& tele(fromJson(a_telegram)); + radioTelegram = + new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_KONFIGURATION_WIRKMODELL, 9, tele.header.equipmentNumber); + radioTelegram->setPayloadData((uint32_t)0, 2); + radioTelegram->setPayloadData((uint8_t)tele.vulnerabilityModelMineIed); + radioTelegram->setPayloadData((uint8_t)tele.vulnerabilityModelAreaFire); + radioTelegram->setPayloadData((uint8_t)tele.vulnerabilityModelOperatingResource); + radioTelegram->setPayloadData((uint8_t)tele.vulnerabilityModelAcWeaponry); + break; + } + case Constraints::id(): { + const DemandEquipmentConfigurationReport& tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_ANFORDERUNG_KONFIGURATIONSDATEN, 3, + tele.header.equipmentNumber); + break; + } + case Constraints::id(): { + const StateChange& tele(fromJson(a_telegram)); + radioTelegram = + new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TAKTISCHER_STATUS, 16, tele.header.equipmentNumber); + + convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); + + radioTelegram->setPayloadData((uint8_t)tele.vulnerabilityState); + radioTelegram->setPayloadData((uint8_t)(tele.tasVulnerabilityKindId & 0xFF)); + uint16_t vulnerabilityVitalityIndex = 0; + vulnerabilityVitalityIndex = (uint16_t)((tele.tasVulnerabilityKindId >> 16) & 0xFFFF); + setVitality(vulnerabilityVitalityIndex, tele.tasVitality); + radioTelegram->setPayloadData((uint16_t)vulnerabilityVitalityIndex, 2); + + radioTelegram->setPayloadData((uint16_t)tele.vulnerabilityBits, 2); + + radioTelegram->setPayloadData((uint8_t)tele.originatorId); + radioTelegram->setPayloadData((uint16_t)tele.originatorType, 2); + break; + } + case Constraints::id(): { + const BiteReport& tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_BITE_MELDUNG2, 27, tele.header.equipmentNumber); + convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); + radioTelegram->setPayloadData((uint8_t)tele.loginType); + radioTelegram->setPayloadData((uint32_t)tele.biteState, 3); + radioTelegram->setPayloadData((uint8_t)tele.batteryState); + + if (tele.biteErrors.size() > 0) + { + radioTelegram->setPayloadData((uint8_t)tele.biteErrors[0].canDeviceNumber); + radioTelegram->setPayloadData((uint8_t)tele.biteErrors[0].subdeviceNumber); + radioTelegram->setPayloadData((uint32_t)tele.biteErrors[0].uniqueId, 4); + radioTelegram->setPayloadData((uint8_t)tele.biteErrors[0].errorNumber); + radioTelegram->setPayloadData((uint8_t)tele.biteErrors.size() - 1); + } + else + { + radioTelegram->setPayloadData((uint8_t)0); + radioTelegram->setPayloadData((uint8_t)0); + radioTelegram->setPayloadData((uint32_t)0, 4); + radioTelegram->setPayloadData((uint8_t)0); + radioTelegram->setPayloadData((uint8_t)0); + } + + radioTelegram->setPayloadData((uint32_t)0, 3); + radioTelegram->setPayloadData((uint8_t)tele.configError); + radioTelegram->setPayloadData((uint32_t)tele.configState, 3); + + for (const BiteError& be : tele.biteErrors) + { + radioTelegram->setPayloadData((uint8_t)be.canDeviceNumber); + radioTelegram->setPayloadData((uint8_t)be.subdeviceNumber); + radioTelegram->setPayloadData((uint32_t)be.uniqueId, 4); + radioTelegram->setPayloadData((uint8_t)be.errorNumber); + } + break; + } + case Constraints::id(): { + const ExerciseEnvironmentData& tele(fromJson(a_telegram)); + radioTelegram = + new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_UMGEBUNGS_MELDUNG2, 20, tele.header.equipmentNumber); + radioTelegram->setPayloadData((uint32_t)0, 2); + radioTelegram->setPayloadData(tele.exerciseId, 2); + radioTelegram->setPayloadData((uint8_t)0); + radioTelegram->setPayloadData((uint8_t)0); + radioTelegram->setPayloadData((uint8_t)tele.timeZone); + radioTelegram->setPayloadData((uint8_t)tele.utmZone); + radioTelegram->setPayloadData(tele.utmBand); + radioTelegram->setPayloadData((uint8_t*)tele.grid.c_str(), 2); + radioTelegram->setPayloadData((uint8_t)0); + radioTelegram->setPayloadData((uint8_t)0); + radioTelegram->setPayloadData((uint32_t)0, 4); + break; + } + case Constraints::id(): { + const DemandBite& tele(fromJson(a_telegram)); + radioTelegram = + new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_AUFFORDERUNG_BITE_MELDUNG, 4, tele.header.equipmentNumber); + radioTelegram->setPayloadData(tele.withSelfTest, 1); + break; + } + case Constraints::id(): { + const PositionReport& tele(fromJson(a_telegram)); + + radioTelegram = + new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_POSITIONS_MELDUNG, 14, tele.header.equipmentNumber); + convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); + radioTelegram->setPayloadData(tele.relPosition.offsetY, 3); + radioTelegram->setPayloadData(tele.relPosition.offsetX, 3); + radioTelegram->setPayloadData((uint8_t)(((tele.gpsQuality.moreThan4SatellitesAvailable) ? 0x80 : 0) | + ((tele.gpsQuality.dgpsModeAvailable) ? 0x40 : 0) | + (tele.gpsQuality.pdopValue & 0x3f)), + 1); + break; + } + case Constraints::id(): { + const CreateSingleExplosion& tele(fromJson(a_telegram)); + + const int teleSize = s_use2BytesForSingleFireDiameter ? 29 : 28; + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_EINZELGESCHOSS, teleSize, + tele.header.equipmentNumber); + setCommonAesParams(tele, radioTelegram); + setAesPosition(tele, radioTelegram); + if (s_use2BytesForSingleFireDiameter) + { + Q_ASSERT(tele.effectDiameter < 256 * 256 && tele.effectDiameter >= 0); + radioTelegram->setPayloadData(tele.effectDiameter, 2); + } + else + { + Q_ASSERT(tele.effectDiameter < 256 && tele.effectDiameter >= 0); + radioTelegram->setPayloadData(tele.effectDiameter, 1); + } + radioTelegram->setPayloadData(tele.chargeTypeId, 1); + break; + } + case Constraints::id(): { + const CreateAreaExplosion& tele(fromJson(a_telegram)); #ifdef GUEZ_MODE - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_FLAECHENDECKENDES_FEUER, - 44 + tele.mhPoints.size() * 6, - tele.header.equipmentNumber); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram( + GEF_WIRKFELD_FLAECHENDECKENDES_FEUER, 44 + tele.mhPoints.size() * 6, tele.header.equipmentNumber); #else - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_FLAECHENDECKENDES_FEUER, - 36, - tele.header.equipmentNumber); -#endif - - setCommonAesParams(tele, radioTelegram); - radioTelegram->setPayloadData(tele.effectDuration / 1000, 2); - - - - - - - - - - - - - - - - - radioTelegram->setPayloadData(tele.relCorner.offsetY, 3); - radioTelegram->setPayloadData(tele.relCorner.offsetX, 3); - radioTelegram->setPayloadData(tele.width / 5, 1); - radioTelegram->setPayloadData(tele.height / 5, 1); - radioTelegram->setPayloadData( - compassToMathAngleForSfm(tele.rotationAngle + 90.0), - 2); - -#ifdef GUEZ_MODE - - radioTelegram->setPayloadData(tele.mhpWidth / 5, 1); - radioTelegram->setPayloadData(tele.mhpLength / 5, 1); - - radioTelegram->setPayloadData( - compassToMathAngleForSfm(tele.mhpRotation + 90.0), - 2); -#endif - radioTelegram->setPayloadData(tele.impactCount, 2); -#ifdef GUEZ_MODE - radioTelegram->setPayloadData(tele.impactRadius, 2); -#else - radioTelegram->setPayloadData(tele.impactEdgeLength, 1); -#endif - radioTelegram->setPayloadData(tele.chargeTypeId, 1); -#ifdef GUEZ_MODE - - radioTelegram->setPayloadData((tele.hazardDistance / 5), 1); - radioTelegram->setPayloadData((uint8_t) 0); - - radioTelegram->setPayloadData(tele.mhPoints.size(), 1); - for(auto pos : std::as_const(tele.mhPoints)) - { - radioTelegram->setPayloadData(pos.offsetY, 3); - radioTelegram->setPayloadData(pos.offsetX, 3); - } -#endif - - break; - } - case Constraints::id(): - { - const PauseEffectSimulation &tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_STOP, - 7, - 0); - radioTelegram->setPayloadData((uint32_t) 0, - 2); - radioTelegram->setPayloadData(tele.aesDdsId, 2); - break; - } - case Constraints::id(): - { - const ResumeEffectSimulation &tele(fromJson(a_telegram)); - radioTelegram - = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_FORTSETZEN, - 17, - 0); - radioTelegram->setPayloadData((uint32_t) 0, - 2); - radioTelegram->setPayloadData(tele.aesDdsId, 2); - radioTelegram->setPayloadData(tele.sequelNumber, 2); - radioTelegram->setPayloadData(tele.nextImpact, 2); - convertToSecAndSetTime(tele.resumeTime, radioTelegram); - radioTelegram->setPayloadData(tele.remainDuration / 1000, 2); - break; - } - case Constraints::id(): - { - const CreateMineArea &tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_MINENSPERRE, 5 + 22 + tele.segments.size() * 12, tele.header.equipmentNumber); - setCommonAesParams(tele, radioTelegram); - - radioTelegram->setPayloadData(tele.effectDuration / (1000 * 60 * 60), 1); - - - - radioTelegram->setPayloadData(qRound(tele.layingDepth), 1); - radioTelegram->setPayloadData(qRound(tele.layingDensity * 100), 1); - radioTelegram->setPayloadData(tele.chargeTypeId, 1); - - double length =0; - for (const MineAreaSegment &ms : tele.segments) - { - length+= QLineF(ms.relStart.offsetX, ms.relStart.offsetY, ms.relEnd.offsetX, ms.relEnd.offsetY).length(); - } - int minecount = qRound(length*tele.layingDensity); - if (minecount > 1200) - minecount = 1200; - radioTelegram->setPayloadData((uint32_t)minecount, 2); - radioTelegram->setPayloadData(tele.segments.size(), 1); - for (const MineAreaSegment &ms : tele.segments) - { - radioTelegram->setPayloadData(ms.relStart.offsetY, 3); - radioTelegram->setPayloadData(ms.relStart.offsetX, 3); - radioTelegram->setPayloadData(ms.relEnd.offsetY, 3); - radioTelegram->setPayloadData(ms.relEnd.offsetX, 3); - } - break; - } - case Constraints::id(): - { - const MineAreaSingleMineState &tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_STATUS_MINENSPERRE, - 5 + 4 + tele.mineState.size(), - 0); - radioTelegram->setPayloadData((uint32_t) 0, - 2); - radioTelegram->setPayloadData(tele.aesDdsId, 2); - radioTelegram->setPayloadData(tele.mineCount, 2); - radioTelegram->setPayloadData((uint8_t *)(tele.mineState.data()), tele.mineState.size()); - break; - } - case Constraints::id(): - { - const CreateNContamination &tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_A_KAMPFMITTEL, - 38, - tele.header.equipmentNumber); - setCommonAesParams(tele, radioTelegram); - radioTelegram->setPayloadData(tele.effectDuration / (1000 * 60), 2); - setAesPosition(tele, radioTelegram); - radioTelegram->setPayloadData(tele.innerRadius, 2); - radioTelegram->setPayloadData(tele.borderLengthInner, 2); - radioTelegram->setPayloadData(tele.borderLengthOuter, 2); - radioTelegram->setPayloadData(qRound(tele.spanAngle * 100), 2); - radioTelegram->setPayloadData(compassToMathAngleForSfm(tele.rotationAngle), - 2); - break; - } - case Constraints::id(): - { - const CreateCContamination &tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_C_KAMPFMITTEL, - 45, - tele.header.equipmentNumber); - setCommonAesParams(tele, radioTelegram); - radioTelegram->setPayloadData(tele.effectDuration / (1000 * 60), 1); - setAesPosition(tele, radioTelegram); - radioTelegram->setPayloadData(tele.effectRadius, 2); - radioTelegram->setPayloadData(qRound(tele.expansionFactor * 100), 1); - radioTelegram->setPayloadData(compassToMathAngleForSfm(tele.propagationDirection), - 2); - radioTelegram->setPayloadData(tele.windSpeed, 1); - convertToSecAndSetTime(tele.validityTimeWind, radioTelegram); - radioTelegram->setPayloadData(tele.relPositionValidityTimeWind.offsetY, 3); - radioTelegram->setPayloadData(tele.relPositionValidityTimeWind.offsetX, 3); - radioTelegram->setPayloadData(tele.chargeTypeId, 1); - radioTelegram->setPayloadData((uint8_t) tele.volatility, 1); - break; - } - case Constraints::id(): - { - const DeactivateEffectSimulation &tele(fromJson(a_telegram)); - if (tele.aesType == AreaEffectSimulationType::FunctionalArea) - { - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_DEAKTIVIEREN_FUNKTIONSRAUM, 7, 0); - radioTelegram->setPayloadData((uint32_t) 0, - 2); - radioTelegram->setPayloadData(tele.aesDdsId, 2); - } - else - { - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_DEAKTIVIERUNG_WIRKFELD, 8, 0); - radioTelegram->setPayloadData((uint32_t) 0, - 2); - radioTelegram->setPayloadData((uint8_t) tele.aesType, 1); - radioTelegram->setPayloadData(tele.aesDdsId, 2); - } - break; - } - case Constraints::id(): - { - const ModifyAreaEffectSimulationName &tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_AENDERUNG_BEZEICHNER, 16, 0); - radioTelegram->setPayloadData((uint32_t) 0, - 2); - radioTelegram->setPayloadData((uint8_t) tele.aesType, 1); - radioTelegram->setPayloadData(tele.aesDdsId, 2); - convertToTetraEncoding(radioTelegram, tele.name, 8); - break; - } - case Constraints::id(): - { - const MineTriggered &tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_DEAKTIVIERUNG_EINZELMINE, - 13, - tele.header.equipmentNumber); - radioTelegram->setPayloadData((uint32_t) 0, - 2); - convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); - radioTelegram->setPayloadData(tele.mineAreaId, 2); - radioTelegram->setPayloadData(tele.mineIndex, 2); - break; - } - case Constraints::id(): - { - const DusMineReactivation &tele(fromJson(a_telegram)); - - const size_t cnt = tele.dusSerialNumbers.size() > 500 ? 500 : tele.dusSerialNumbers.size(); - - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_REAKTIVIERUNG_DUS_MINE, - 3 + 2 + 2 + 2 * cnt, - tele.header.equipmentNumber); - radioTelegram->setPayload2Byte(0); - radioTelegram->setPayload2Byte(cnt); - for (size_t i = 0; i < cnt; i++) - radioTelegram->setPayload2Byte(tele.dusSerialNumbers.at(i)); - break; - } - case Constraints::id(): - { - const CreateDusSingleMine &tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_EINZELMINENSIMULATOR, - 21, - tele.header.equipmentNumber); - radioTelegram->setPayloadData((uint32_t) 0, - 2); - radioTelegram->setPayloadData(tele.aesDdsId, 2); - radioTelegram->setPayloadData(tele.partyId, 1); - radioTelegram->setPayloadData(tele.mineId, 2); - convertToSecAndSetTime(tele.effectStart, radioTelegram); - radioTelegram->setPayloadData(tele.relEffectPosition.offsetY, 3); - radioTelegram->setPayloadData(tele.relEffectPosition.offsetX, 3); - radioTelegram->setPayloadData(tele.chargeTypeId, 1); - break; - } - case Constraints::id(): - { - const DemandVulnerabilityStateChange &tele(fromJson(a_telegram)); -#ifdef GUEZ_MODE - if (s_usePvSan) - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TREFFER_AUSLOESUNG, - 10, - tele.header.equipmentNumber); - else - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TREFFER_AUSLOESUNG, - 8, - tele.header.equipmentNumber); -#else - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TREFFER_AUSLOESUNG, - 8, - tele.header.equipmentNumber); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_FLAECHENDECKENDES_FEUER, 36, + tele.header.equipmentNumber); #endif - convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); - radioTelegram->setPayloadData((uint8_t) tele.reqestedState, 1); + setCommonAesParams(tele, radioTelegram); + radioTelegram->setPayloadData(tele.effectDuration / 1000, 2); + + radioTelegram->setPayloadData(tele.relCorner.offsetY, 3); + radioTelegram->setPayloadData(tele.relCorner.offsetX, 3); + radioTelegram->setPayloadData(tele.width / 5, 1); + radioTelegram->setPayloadData(tele.height / 5, 1); + radioTelegram->setPayloadData(compassToMathAngleForSfm(tele.rotationAngle + 90.0), 2); #ifdef GUEZ_MODE - if (s_usePvSan) - radioTelegram->setPayloadData((uint16_t) tele.vulnerabilityVitalityIndex, 2); + + radioTelegram->setPayloadData(tele.mhpWidth / 5, 1); + radioTelegram->setPayloadData(tele.mhpLength / 5, 1); + + radioTelegram->setPayloadData(compassToMathAngleForSfm(tele.mhpRotation + 90.0), 2); +#endif + radioTelegram->setPayloadData(tele.impactCount, 2); +#ifdef GUEZ_MODE + radioTelegram->setPayloadData(tele.impactRadius, 2); +#else + radioTelegram->setPayloadData(tele.impactEdgeLength, 1); +#endif + radioTelegram->setPayloadData(tele.chargeTypeId, 1); +#ifdef GUEZ_MODE + + radioTelegram->setPayloadData((tele.hazardDistance / 5), 1); + radioTelegram->setPayloadData((uint8_t)0); + + radioTelegram->setPayloadData(tele.mhPoints.size(), 1); + for (auto pos : std::as_const(tele.mhPoints)) + { + radioTelegram->setPayloadData(pos.offsetY, 3); + radioTelegram->setPayloadData(pos.offsetX, 3); + } #endif - break; - } - case Constraints::id(): - { - const TechnicalArea &tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TECHNIK_FUNKTIONSRAUM, - 34, - tele.header.equipmentNumber); - radioTelegram->setPayloadData((uint32_t) 0, - 2); - radioTelegram->setPayloadData(tele.aesDdsId, 2); - radioTelegram->setPayloadData(tele.taType, 1); - convertToTetraEncoding(radioTelegram, tele.name, 8); - radioTelegram->setPayloadData(tele.relCorner.offsetY, 3); - radioTelegram->setPayloadData(tele.relCorner.offsetX, 3); - radioTelegram->setPayloadData(tele.width, 2); - radioTelegram->setPayloadData(tele.height, 2); - radioTelegram->setPayloadData((uint32_t) 0, 4); - radioTelegram->setPayloadData((uint32_t) 0, 4); - break; - } - case Constraints::id(): - { - const CreateFunctionalArea &tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_FUNKTIONSRAUM, - 30, - tele.header.equipmentNumber); - radioTelegram->setPayloadData((uint32_t) 0, - 2); - radioTelegram->setPayloadData(tele.aesDdsId, 2); - convertToTetraEncoding(radioTelegram, tele.name, 8); - radioTelegram->setPayloadData(tele.partyId, 1); - radioTelegram->setPayloadData(tele.relEffectPosition.offsetY, 3); - radioTelegram->setPayloadData(tele.relEffectPosition.offsetX, 3); - radioTelegram->setPayloadData(tele.width / 5, 1); - radioTelegram->setPayloadData(tele.height / 5, 1); - radioTelegram->setPayloadData((uint8_t) tele.deconMode, 1); - radioTelegram->setPayloadData(tele.deconTimeout / 1000 / 60 / 10, - 1); - radioTelegram->setPayloadData((uint8_t) tele.maintenanceMode, 1); - radioTelegram->setPayloadData(tele.maintenanceTimeout / 1000 / 60 / 10, - 1); - radioTelegram->setPayloadData((uint8_t) tele.medicalMode, 1); - radioTelegram->setPayloadData(tele.medicalTimeout / 1000 / 60 / 10, - 1); - break; - } - case Constraints::id(): - { - const LanguageSelection &tele(fromJson(a_telegram)); - - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_SPRACHAUSWAHL, - 6, - tele.header.equipmentNumber); - radioTelegram->setPayloadData((uint32_t) 0, - 2); - radioTelegram->setPayloadData((uint8_t) tele.languageSelection, 1); - break; - } - case Constraints::id(): - { - - const EquipmentMessage &tele(fromJson(a_telegram)); - - - - - int len = 0; - int messageLength = (tele.message.size() > 81) - ? 81 - : tele.message.size(); - if (tele.msgId == -1) - len = messageLength + 6; - - - else - len = 9; - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_ALLGEMEINE_NACHRICHT, - len, - tele.header.equipmentNumber); - radioTelegram->setPayloadData((uint32_t) 0, - 2); - if (tele.msgId != -1) - { - - - radioTelegram->setPayloadData(3, 1); - - + break; + } + case Constraints::id(): { + const PauseEffectSimulation& tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_STOP, 7, 0); + radioTelegram->setPayloadData((uint32_t)0, 2); + radioTelegram->setPayloadData(tele.aesDdsId, 2); + break; + } + case Constraints::id(): { + const ResumeEffectSimulation& tele(fromJson(a_telegram)); + radioTelegram = + new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_FLAECHENDECKENDES_FEUER_FORTSETZEN, 17, 0); + radioTelegram->setPayloadData((uint32_t)0, 2); + radioTelegram->setPayloadData(tele.aesDdsId, 2); + radioTelegram->setPayloadData(tele.sequelNumber, 2); + radioTelegram->setPayloadData(tele.nextImpact, 2); + convertToSecAndSetTime(tele.resumeTime, radioTelegram); + radioTelegram->setPayloadData(tele.remainDuration / 1000, 2); + break; + } + case Constraints::id(): { + const CreateMineArea& tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram( + GEF_WIRKFELD_MINENSPERRE, 5 + 22 + tele.segments.size() * 12, tele.header.equipmentNumber); + setCommonAesParams(tele, radioTelegram); - radioTelegram->setPayloadData((uint32_t) 0, 1); - radioTelegram->setPayloadData(tele.msgId, 2); + radioTelegram->setPayloadData(tele.effectDuration / (1000 * 60 * 60), 1); - - + radioTelegram->setPayloadData(qRound(tele.layingDepth), 1); + radioTelegram->setPayloadData(qRound(tele.layingDensity * 100), 1); + radioTelegram->setPayloadData(tele.chargeTypeId, 1); + + double length = 0; + for (const MineAreaSegment& ms : tele.segments) + { + length += + QLineF(ms.relStart.offsetX, ms.relStart.offsetY, ms.relEnd.offsetX, ms.relEnd.offsetY).length(); + } + int minecount = qRound(length * tele.layingDensity); + if (minecount > 1200) + minecount = 1200; + radioTelegram->setPayloadData((uint32_t)minecount, 2); + radioTelegram->setPayloadData(tele.segments.size(), 1); + for (const MineAreaSegment& ms : tele.segments) + { + radioTelegram->setPayloadData(ms.relStart.offsetY, 3); + radioTelegram->setPayloadData(ms.relStart.offsetX, 3); + radioTelegram->setPayloadData(ms.relEnd.offsetY, 3); + radioTelegram->setPayloadData(ms.relEnd.offsetX, 3); + } + break; + } + case Constraints::id(): { + const MineAreaSingleMineState& tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_STATUS_MINENSPERRE, + 5 + 4 + tele.mineState.size(), 0); + radioTelegram->setPayloadData((uint32_t)0, 2); + radioTelegram->setPayloadData(tele.aesDdsId, 2); + radioTelegram->setPayloadData(tele.mineCount, 2); + radioTelegram->setPayloadData((uint8_t*)(tele.mineState.data()), tele.mineState.size()); + break; + } + case Constraints::id(): { + const CreateNContamination& tele(fromJson(a_telegram)); + radioTelegram = + new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_A_KAMPFMITTEL, 38, tele.header.equipmentNumber); + setCommonAesParams(tele, radioTelegram); + radioTelegram->setPayloadData(tele.effectDuration / (1000 * 60), 2); + setAesPosition(tele, radioTelegram); + radioTelegram->setPayloadData(tele.innerRadius, 2); + radioTelegram->setPayloadData(tele.borderLengthInner, 2); + radioTelegram->setPayloadData(tele.borderLengthOuter, 2); + radioTelegram->setPayloadData(qRound(tele.spanAngle * 100), 2); + radioTelegram->setPayloadData(compassToMathAngleForSfm(tele.rotationAngle), 2); + break; + } + case Constraints::id(): { + const CreateCContamination& tele(fromJson(a_telegram)); + radioTelegram = + new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_C_KAMPFMITTEL, 45, tele.header.equipmentNumber); + setCommonAesParams(tele, radioTelegram); + radioTelegram->setPayloadData(tele.effectDuration / (1000 * 60), 1); + setAesPosition(tele, radioTelegram); + radioTelegram->setPayloadData(tele.effectRadius, 2); + radioTelegram->setPayloadData(qRound(tele.expansionFactor * 100), 1); + radioTelegram->setPayloadData(compassToMathAngleForSfm(tele.propagationDirection), 2); + radioTelegram->setPayloadData(tele.windSpeed, 1); + convertToSecAndSetTime(tele.validityTimeWind, radioTelegram); + radioTelegram->setPayloadData(tele.relPositionValidityTimeWind.offsetY, 3); + radioTelegram->setPayloadData(tele.relPositionValidityTimeWind.offsetX, 3); + radioTelegram->setPayloadData(tele.chargeTypeId, 1); + radioTelegram->setPayloadData((uint8_t)tele.volatility, 1); + break; + } + case Constraints::id(): { + const DeactivateEffectSimulation& tele(fromJson(a_telegram)); + if (tele.aesType == AreaEffectSimulationType::FunctionalArea) + { + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_DEAKTIVIEREN_FUNKTIONSRAUM, 7, 0); + radioTelegram->setPayloadData((uint32_t)0, 2); + radioTelegram->setPayloadData(tele.aesDdsId, 2); + } + else + { + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_DEAKTIVIERUNG_WIRKFELD, 8, 0); + radioTelegram->setPayloadData((uint32_t)0, 2); + radioTelegram->setPayloadData((uint8_t)tele.aesType, 1); + radioTelegram->setPayloadData(tele.aesDdsId, 2); + } + break; + } + case Constraints::id(): { + const ModifyAreaEffectSimulationName& tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_AENDERUNG_BEZEICHNER, 16, 0); + radioTelegram->setPayloadData((uint32_t)0, 2); + radioTelegram->setPayloadData((uint8_t)tele.aesType, 1); + radioTelegram->setPayloadData(tele.aesDdsId, 2); + convertToTetraEncoding(radioTelegram, tele.name, 8); + break; + } + case Constraints::id(): { + const MineTriggered& tele(fromJson(a_telegram)); + radioTelegram = + new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_DEAKTIVIERUNG_EINZELMINE, 13, tele.header.equipmentNumber); + radioTelegram->setPayloadData((uint32_t)0, 2); + convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); + radioTelegram->setPayloadData(tele.mineAreaId, 2); + radioTelegram->setPayloadData(tele.mineIndex, 2); + break; + } + case Constraints::id(): { + const DusMineReactivation& tele(fromJson(a_telegram)); + + const size_t cnt = tele.dusSerialNumbers.size() > 500 ? 500 : tele.dusSerialNumbers.size(); + + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_REAKTIVIERUNG_DUS_MINE, 3 + 2 + 2 + 2 * cnt, + tele.header.equipmentNumber); + radioTelegram->setPayload2Byte(0); + radioTelegram->setPayload2Byte(cnt); + for (size_t i = 0; i < cnt; i++) + radioTelegram->setPayload2Byte(tele.dusSerialNumbers.at(i)); + break; + } + case Constraints::id(): { + const CreateDusSingleMine& tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_WIRKFELD_EINZELMINENSIMULATOR, 21, + tele.header.equipmentNumber); + radioTelegram->setPayloadData((uint32_t)0, 2); + radioTelegram->setPayloadData(tele.aesDdsId, 2); + radioTelegram->setPayloadData(tele.partyId, 1); + radioTelegram->setPayloadData(tele.mineId, 2); + convertToSecAndSetTime(tele.effectStart, radioTelegram); + radioTelegram->setPayloadData(tele.relEffectPosition.offsetY, 3); + radioTelegram->setPayloadData(tele.relEffectPosition.offsetX, 3); + radioTelegram->setPayloadData(tele.chargeTypeId, 1); + break; + } + case Constraints::id(): { + const DemandVulnerabilityStateChange& tele(fromJson(a_telegram)); +#ifdef GUEZ_MODE + if (s_usePvSan) + radioTelegram = + new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TREFFER_AUSLOESUNG, 10, tele.header.equipmentNumber); + else + radioTelegram = + new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TREFFER_AUSLOESUNG, 8, tele.header.equipmentNumber); +#else + radioTelegram = + new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TREFFER_AUSLOESUNG, 8, tele.header.equipmentNumber); +#endif + + convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); + radioTelegram->setPayloadData((uint8_t)tele.reqestedState, 1); + +#ifdef GUEZ_MODE + if (s_usePvSan) + radioTelegram->setPayloadData((uint16_t)tele.vulnerabilityVitalityIndex, 2); +#endif + + break; + } + case Constraints::id(): { + const TechnicalArea& tele(fromJson(a_telegram)); + radioTelegram = + new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TECHNIK_FUNKTIONSRAUM, 34, tele.header.equipmentNumber); + radioTelegram->setPayloadData((uint32_t)0, 2); + radioTelegram->setPayloadData(tele.aesDdsId, 2); + radioTelegram->setPayloadData(tele.taType, 1); + convertToTetraEncoding(radioTelegram, tele.name, 8); + radioTelegram->setPayloadData(tele.relCorner.offsetY, 3); + radioTelegram->setPayloadData(tele.relCorner.offsetX, 3); + radioTelegram->setPayloadData(tele.width, 2); + radioTelegram->setPayloadData(tele.height, 2); + radioTelegram->setPayloadData((uint32_t)0, 4); + radioTelegram->setPayloadData((uint32_t)0, 4); + break; + } + case Constraints::id(): { + const CreateFunctionalArea& tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_FUNKTIONSRAUM, 30, tele.header.equipmentNumber); + radioTelegram->setPayloadData((uint32_t)0, 2); + radioTelegram->setPayloadData(tele.aesDdsId, 2); + convertToTetraEncoding(radioTelegram, tele.name, 8); + radioTelegram->setPayloadData(tele.partyId, 1); + radioTelegram->setPayloadData(tele.relEffectPosition.offsetY, 3); + radioTelegram->setPayloadData(tele.relEffectPosition.offsetX, 3); + radioTelegram->setPayloadData(tele.width / 5, 1); + radioTelegram->setPayloadData(tele.height / 5, 1); + radioTelegram->setPayloadData((uint8_t)tele.deconMode, 1); + radioTelegram->setPayloadData(tele.deconTimeout / 1000 / 60 / 10, 1); + radioTelegram->setPayloadData((uint8_t)tele.maintenanceMode, 1); + radioTelegram->setPayloadData(tele.maintenanceTimeout / 1000 / 60 / 10, 1); + radioTelegram->setPayloadData((uint8_t)tele.medicalMode, 1); + radioTelegram->setPayloadData(tele.medicalTimeout / 1000 / 60 / 10, 1); + break; + } + case Constraints::id(): { + const LanguageSelection& tele(fromJson(a_telegram)); + + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_SPRACHAUSWAHL, 6, tele.header.equipmentNumber); + radioTelegram->setPayloadData((uint32_t)0, 2); + radioTelegram->setPayloadData((uint8_t)tele.languageSelection, 1); + break; + } + case Constraints::id(): { + + const EquipmentMessage& tele(fromJson(a_telegram)); + + int len = 0; + int messageLength = (tele.message.size() > 81) ? 81 : tele.message.size(); + if (tele.msgId == -1) + len = messageLength + 6; + + else + len = 9; + radioTelegram = + new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_ALLGEMEINE_NACHRICHT, len, tele.header.equipmentNumber); + radioTelegram->setPayloadData((uint32_t)0, 2); + if (tele.msgId != -1) + { + + radioTelegram->setPayloadData(3, 1); + + radioTelegram->setPayloadData((uint32_t)0, 1); + radioTelegram->setPayloadData(tele.msgId, 2); + } + else + { + radioTelegram->setPayloadData(tele.message.size(), 1); + radioTelegram->setPayloadData((uint8_t*)(tele.message.c_str()), messageLength); + } + break; + } + case Constraints::id(): { + const OpaquePayloadDataOut& tele(fromJson(a_telegram)); + switch (tele.payloadType) + { + case TrainingAreaBase::TetraIcd::OpaquePayloadDataBase::Type::FireSmokeMarker: + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram( + GEF_DATENVERKEHR_TDS_DMF, tele.payload.size() + 3, tele.header.equipmentNumber); + break; + case TrainingAreaBase::TetraIcd::OpaquePayloadDataBase::Type::Geopairing: + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram( + GEF_DATENVERKEHR_TDS_GEOP, tele.payload.size() + 4, tele.header.equipmentNumber); + radioTelegram->setPayloadData(tele.payload.size(), 1); + break; + case TrainingAreaBase::TetraIcd::OpaquePayloadDataBase::Type::Target: + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram( + GEF_DATENVERKEHR_TDS_TGTC, tele.payload.size() + 4, tele.header.equipmentNumber); + radioTelegram->setPayloadData(tele.payload.size(), 1); + break; + case TrainingAreaBase::TetraIcd::OpaquePayloadDataBase::Type::OC: + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram( + GEF_DATENVERKEHR_TDS_SRT, tele.payload.size() + 3, tele.header.equipmentNumber); + break; + } + + radioTelegram->setPayloadData((uint8_t*)(tele.payload.data()), tele.payload.size()); + break; + } + + case Constraints::id(): { + const CesHitInformation& tele(fromJson(a_telegram)); + radioTelegram = + new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_AUSLOESUNG_DUS_TREFFER, 16, tele.header.equipmentNumber); + convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); + radioTelegram->setPayloadData(tele.chargeTasCodeDirect, 2); + radioTelegram->setPayloadData(tele.directionDegree, 2); + radioTelegram->setPayloadData(tele.distance, 2); + radioTelegram->setPayloadData(tele.effectPercent, 1); + radioTelegram->setPayloadData(tele.originatorEquipmentNumber, 2); + break; + } + + case Constraints::id(): { + const ParticipantSwVersionsRequest& tele(fromJson(a_telegram)); + radioTelegram = + new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_ANFORDERUNG_SW_VERSION, 4, tele.header.equipmentNumber); + radioTelegram->setPayloadData(tele.equipmentFunctionId, 1); + break; + } + + case Constraints::id(): { + const ParticipantMode& tele(fromJson(a_telegram)); + radioTelegram = + new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TEILNEHMERMODE_SETZEN, 13, tele.header.equipmentNumber); + radioTelegram->setPayloadData((uint32_t)0, 2); + radioTelegram->setPayloadData((uint8_t)tele.language, 1); + radioTelegram->setPayloadData((uint8_t)tele.operationMode, 1); + radioTelegram->setPayloadData(tele.reactivationDetoxication / 10, 1); + radioTelegram->setPayloadData(tele.reactivationMaintenance / 10, 1); + radioTelegram->setPayloadData(tele.reactivationMedic / 10, 1); + unsigned char wph_mode = 0; + wph_mode |= ((uint8_t)tele.modeHelmet & 0x03); + wph_mode |= ((uint8_t)tele.modeVest & 0x03) << 2; + wph_mode |= ((uint8_t)tele.personellProtectionMode & 0x07) << 4; + radioTelegram->setPayloadData(wph_mode, 1); + + unsigned char protection_mode = 0; + protection_mode |= ((uint8_t)tele.protectionLevel & 0x07); + protection_mode |= ((uint8_t)tele.abcProtectionMode & 0x03) << 3; + radioTelegram->setPayloadData(protection_mode, 1); + + unsigned char specialFunction = 0; + specialFunction |= ((uint8_t)tele.handgrenadeSearchMode & 0x03); + specialFunction |= ((uint8_t)tele.internationalMode & 0x03) << 2; + specialFunction |= ((uint8_t)tele.abcProtectionMode & 0x03) << 3; + radioTelegram->setPayloadData(specialFunction, 1); + break; + } + case Constraints::id(): { + const DemandParticipantMode& tele(fromJson(a_telegram)); + radioTelegram = + new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TEILNEHMERMODE_ANFORDERN, 3, tele.header.equipmentNumber); + break; + } + case Constraints::id(): { + const ParticipantConfiguration& tele(fromJson(a_telegram)); + radioTelegram = + new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TEILNEHMER_KONFIG_SETZEN, 25, tele.header.equipmentNumber); + radioTelegram->setPayloadData((uint32_t)0, 2); + radioTelegram->setPayloadData(tele.positionIntervallVehicle, 2); + radioTelegram->setPayloadData(tele.positionIntervallPersonell, 2); + radioTelegram->setPayloadData(tele.positionIntervallAircraft, 2); + radioTelegram->setPayloadData(tele.positionTransmissionIntervall, 2); + radioTelegram->setPayloadData(tele.heightbarrier, 2); + unsigned char tmp = ((uint8_t)tele.faultPositionHandling & 0x03) << 6; + tmp |= ((uint8_t)tele.switchingPositionIntervall & 0x03); + radioTelegram->setPayloadData(tmp, 1); + radioTelegram->setPayloadData(tele.waittimeAdditionalBroadcastDemand, 2); + radioTelegram->setPayloadData(tele.factorWaittimeIncreaseAtHighload, 1); + radioTelegram->setPayloadData(tele.waittimeAutomaticVulnerabilityIncreaseLevel1, 1); + radioTelegram->setPayloadData(tele.waittimeAutomaticVulnerabilityIncreaseLevel2, 1); + radioTelegram->setPayloadData(tele.waittimeAutomaticVulnerabilityIncreaseLevel3, 1); + radioTelegram->setPayloadData((uint8_t)tele.opticalCode, 1); + radioTelegram->setPayloadData(tele.vulnerabilityModel, 1); + radioTelegram->setPayloadData(tele.validTimeOps, 1); + break; + } + case Constraints::id(): { + const DemandParticipantConfiguration& tele(fromJson(a_telegram)); + radioTelegram = + new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TEILNEHMER_KONFIG_ANFORDERN, 3, tele.header.equipmentNumber); + break; + } + case Constraints::id(): { + const SanitationRepair& tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_SANITAETSDIENST_INSTANDSETZUNG, 19, + tele.header.equipmentNumber); + convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); + + radioTelegram->setPayload1Byte(uint8_t(tele.originatorType)); + radioTelegram->setPayload2Byte(tele.equipmentNumberOrigin); + radioTelegram->setPayload1Byte(uint8_t(tele.stateStart)); + + unsigned int bitfield1 = 0; + if (tele.timeOfTreatment) + bitfield1 |= 0x7F; + if (tele.triage) + bitfield1 |= 0x80; + radioTelegram->setPayload1Byte(bitfield1); + + radioTelegram->setPayload1Byte(tele.tyeOfDamage); + + unsigned int bitfield2 = 0; + bitfield2 |= (uint8_t(tele.stateResult) | 0x0F); + bitfield2 |= ((uint8_t(tele.treatmentResult) | 0x30) << 4); + bitfield2 |= (0xC0 << 6); + radioTelegram->setPayload1Byte(bitfield2); + + radioTelegram->setPayload1Byte(tele.fullState); + radioTelegram->setPayloadData(tele.timeOfTreatment, 2); + radioTelegram->setPayloadData(tele.timeOfRecovery, 2); + break; + } + case Constraints::id(): { + const SanitaryMaterialStockReport& tele(fromJson(a_telegram)); + + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram( + GEF_BESTANDSMELDUNG_SANITAETSMATERIAL, 15 + tele.sanitaryMaterialCount, tele.header.equipmentNumber); + convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); + radioTelegram->setPayload4Byte(tele.uniqueId); + radioTelegram->setPayload2Byte(tele.originatorEquipmentNumber); + radioTelegram->setPayload1Byte((uint8_t)tele.qualification); + + radioTelegram->setPayload1Byte(tele.sanitaryMaterialCount); + + for (const auto stock : tele.sanitaryMaterialStock) + radioTelegram->setPayloadData(stock, 1); + + break; + } + case Constraints::id(): { + const Sanitation& tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_SANITAETSDIENST_INSTANDSETZUNG_PVSAN, 23, + tele.header.equipmentNumber); + convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); + + int p1 = tele.proceduresTaken & 0xFFFFFFFF; + int p2 = tele.proceduresTaken >> 32; + + radioTelegram->setPayloadData(p2, 4); + radioTelegram->setPayloadData(p1, 4); + radioTelegram->setPayloadData(tele.uniqeId, 4); + radioTelegram->setPayloadData(tele.originatorEquipmentNumber, 2); + radioTelegram->setPayloadData((uint8_t)tele.qualification, 1); + + quint8 sanResultAndEvaluation = + (((uint8_t)tele.sanitationEvaluation & 0x03) << 6) + ((uint8_t)tele.sanitationResult & 0x3f); + radioTelegram->setPayloadData(sanResultAndEvaluation, 1); + + break; + } + case Constraints::id(): { + const CesHitRequest& tele(fromJson(a_telegram)); + + int chargeTasCode = tele.chargeTasCodeDirect; + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TREFFER_EREIGNIS_SEKUNDAERWIRKUNG, 17, + tele.header.equipmentNumber); + const bool insideBuilding = (tele.roomId > 0 && tele.buildingId > 0); + int remainEffectOrTasCodeDirect = 0; + int reserve1 = tele.mineId; + int reserve2 = 0; + int gpsZeit = tele.header.timeStamp; + switch (tele.aesType) + { + case AreaEffectSimulationType::Unknown: + + remainEffectOrTasCodeDirect = tele.remainEffectTasCodeDirect; + if (remainEffectOrTasCodeDirect == 100) + { + remainEffectOrTasCodeDirect = 49; + } + break; + case AreaEffectSimulationType::FunctionalArea: + + remainEffectOrTasCodeDirect = tele.remainEffectTasCodeDirect; + + chargeTasCode = tele.chargeTasCodeIndirect; + reserve1 = tele.reserve1; + reserve2 = tele.reserve2; + break; + case AreaEffectSimulationType::AirSupport: + case AreaEffectSimulationType::NContamination: + case AreaEffectSimulationType::MineArea: + case AreaEffectSimulationType::CContamination: + remainEffectOrTasCodeDirect = tele.remainEffectTasCodeDirect; + chargeTasCode = tele.chargeTasCodeIndirect; + break; + case AreaEffectSimulationType::DangerZoneExplosion: + remainEffectOrTasCodeDirect = tele.remainEffectTasCodeDirect; + chargeTasCode = tele.chargeTasCodeIndirect; + reserve1 = tele.reserve1; + break; + case AreaEffectSimulationType::ExplosionArea: + case AreaEffectSimulationType::ExplosionSingle: + if (insideBuilding) + { + + remainEffectOrTasCodeDirect = tele.remainEffectTasCodeDirect; + } + else + { + + remainEffectOrTasCodeDirect = 255; + chargeTasCode = tele.chargeTasCodeIndirect; + } + break; + case AreaEffectSimulationType::GasPipeDetonation: + + remainEffectOrTasCodeDirect = tele.remainEffectTasCodeDirect; + break; + default: + + remainEffectOrTasCodeDirect = tele.remainEffectPercent; + chargeTasCode = tele.chargeTasCodeIndirect; + break; + } + + radioTelegram->setPayloadData((uint32_t)gpsZeit, 4); + radioTelegram->setPayload2Byte(chargeTasCode); + if (tele.aesDdsId != 0) + radioTelegram->setPayload2Byte(tele.aesDdsId); + else + radioTelegram->setPayload2Byte(tele.originatorEquipmentNumber); + + radioTelegram->setPayload1Byte(uint8_t(tele.aesType)); + radioTelegram->setPayload1Byte(remainEffectOrTasCodeDirect); + radioTelegram->setPayload2Byte(reserve1); + radioTelegram->setPayload2Byte(reserve2); + DEBUG_LOG(logger()) << "Reserve1 of CesHitRequest: " << reserve1 << " Reserve2: " << reserve2; + + break; + } + case Constraints::id(): { + const SelectiveReammunition& tele(fromJson(a_telegram)); + radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram( + GEF_SELEKTIVE_AUFMUNITIONIERUNG, 8 + tele.reammunitions.size() * 8, tele.header.equipmentNumber); + radioTelegram->setPayload4Byte(tele.gearId); + radioTelegram->setPayload1Byte(tele.reammunitions.size()); + for (const auto& reammunition : tele.reammunitions) + { + radioTelegram->setPayload2Byte(reammunition.chargeTypeId); + radioTelegram->setPayload1Byte(reammunition.location); + radioTelegram->setPayload2Byte(reammunition.newStock); + radioTelegram->setPayload2Byte(reammunition.newDefaultStock); + radioTelegram->setPayload1Byte(reammunition.tracerRatio); + } + break; + } + case Constraints::id(): { + const OcCommand& tele(fromJson(a_telegram)); + radioTelegram = + new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_SCHIEDSRICHTERKOMMANDO, 4, tele.header.equipmentNumber); + radioTelegram->setPayloadData(tele.action, 1); + break; + } + default: { + ERROR_LOG(logger()) << "Conversion of Central-Telegram to Radio-Telegram with telId=" + << getTelegramId(a_telegram) << " not implemented!"; + } } - else + return radioTelegram; +} + +CoPrtCnvRadioTelegram* convertToRadio(CoPrtCnvCentralTelegram* a_telegram) +{ + return convertToRadioInternal(a_telegram); +} + +CoPrtCnvRadioTelegram* convertToRadio(const TrainingAreaBase::TetraIcd::TrainingAreaTelegram* a_telegram) +{ + return convertToRadioInternal(a_telegram); +} + +static inline Header getHeader(const CoPrtCnvRadioTelegram* a_radioTelegram, size_t tsOffset) +{ + Header hdr; + hdr.equipmentNumber = a_radioTelegram->getIdentity(); + hdr.timeStamp = a_radioTelegram->getPayloadDataUInt32(tsOffset, 4) * 1000LL; + return hdr; +} + +static inline RelativePosition getRelativePosition(const CoPrtCnvRadioTelegram* a_radioTelegram, size_t offset) +{ + RelativePosition pos; + pos.offsetY = a_radioTelegram->getPayloadDataSInt24(offset); + pos.offsetX = a_radioTelegram->getPayloadDataSInt24(offset + 3); + return pos; +} + +static inline GpsQuality getGpsQuality(const CoPrtCnvRadioTelegram* a_radioTelegram, size_t offset) +{ + const uint8_t gps = a_radioTelegram->getPayloadDataUInt8(offset); + GpsQuality ret; + ret.moreThan4SatellitesAvailable = ((gps & 0x80) == 0x80); + ret.dgpsModeAvailable = ((gps & 0x40) == 0x40); + ret.pdopValue = (gps & 0x3f); + return ret; +} + +static inline OpsPosition getOpsPosition(const CoPrtCnvRadioTelegram* a_radioTelegram, size_t offset, + size_t* newOffset = nullptr) +{ + const uint8_t opsLen = a_radioTelegram->getPayloadDataUInt8(offset); + offset += 1; + OpsPosition pos; + pos.opsId = -1; + if (opsLen > 0) { - radioTelegram->setPayloadData(tele.message.size(), 1); - radioTelegram->setPayloadData((uint8_t *)(tele.message.c_str()), messageLength); + std::vector opse; + opse.reserve(opsLen); + for (uint32_t i = 0; i < opsLen; i++) + { + opse.push_back(a_radioTelegram->getPayloadDataUInt32(offset, 2)); + offset += 2; + } + pos.opsId = opse.at(opse.size() - 1); } - break; - } - case Constraints::id(): - { - const OpaquePayloadDataOut &tele(fromJson(a_telegram)); - switch (tele.payloadType) + if (newOffset) + *newOffset = offset; + return pos; +} + +static inline std::vector getPayload(const CoPrtCnvRadioTelegram* a_radioTelegram, size_t offsetData) +{ + int payloadLen = a_radioTelegram->getPayloadSize(); + payloadLen -= offsetData; + if (payloadLen <= 0) { - case TrainingAreaBase::TetraIcd::OpaquePayloadDataBase::Type::FireSmokeMarker: - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_DATENVERKEHR_TDS_DMF, - tele.payload.size() + 3, - tele.header.equipmentNumber); - break; - case TrainingAreaBase::TetraIcd::OpaquePayloadDataBase::Type::Geopairing: - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_DATENVERKEHR_TDS_GEOP, - tele.payload.size() + 4, - tele.header.equipmentNumber); - radioTelegram->setPayloadData(tele.payload.size(), 1); - break; - case TrainingAreaBase::TetraIcd::OpaquePayloadDataBase::Type::Target: - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_DATENVERKEHR_TDS_TGTC, - tele.payload.size() + 4, - tele.header.equipmentNumber); - radioTelegram->setPayloadData(tele.payload.size(), 1); - break; - case TrainingAreaBase::TetraIcd::OpaquePayloadDataBase::Type::OC: - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_DATENVERKEHR_TDS_SRT, - tele.payload.size() + 3, - tele.header.equipmentNumber); - break; + ERROR_LOG(logger()) << "Radio-Telegram Datenverkehr SRT-TDS contains too less data: " << payloadLen; + return {}; } - - radioTelegram->setPayloadData((uint8_t *)(tele.payload.data()), tele.payload.size()); - break; - } - - case Constraints::id(): - { - const CesHitInformation &tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_AUSLOESUNG_DUS_TREFFER, - 16, - tele.header.equipmentNumber); - convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); - radioTelegram->setPayloadData(tele.chargeTasCodeDirect, 2); - radioTelegram->setPayloadData(tele.directionDegree, 2); - radioTelegram->setPayloadData(tele.distance, 2); - radioTelegram->setPayloadData(tele.effectPercent, 1); - radioTelegram->setPayloadData(tele.originatorEquipmentNumber, 2); - break; - } - - case Constraints::id(): - { - const ParticipantSwVersionsRequest &tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_ANFORDERUNG_SW_VERSION, - 4, - tele.header.equipmentNumber); - radioTelegram->setPayloadData(tele.equipmentFunctionId, 1); - break; - } - - case Constraints::id(): - { - const ParticipantMode &tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TEILNEHMERMODE_SETZEN, - 13, - tele.header.equipmentNumber); - radioTelegram->setPayloadData((uint32_t) 0, - 2); - radioTelegram->setPayloadData((uint8_t) tele.language, 1); - radioTelegram->setPayloadData((uint8_t) tele.operationMode, 1); - radioTelegram->setPayloadData(tele.reactivationDetoxication / 10, 1); - radioTelegram->setPayloadData(tele.reactivationMaintenance / 10, 1); - radioTelegram->setPayloadData(tele.reactivationMedic / 10, 1); - unsigned char wph_mode = 0; - wph_mode |= ((uint8_t) tele.modeHelmet & 0x03); - wph_mode |= ((uint8_t) tele.modeVest & 0x03) << 2; - wph_mode |= ((uint8_t) tele.personellProtectionMode & 0x07) << 4; - radioTelegram->setPayloadData(wph_mode, 1); - - unsigned char protection_mode = 0; - protection_mode |= ((uint8_t) tele.protectionLevel & 0x07); - protection_mode |= ((uint8_t) tele.abcProtectionMode & 0x03) << 3; - radioTelegram->setPayloadData(protection_mode, 1); - - unsigned char specialFunction = 0; - specialFunction |= ((uint8_t) tele.handgrenadeSearchMode & 0x03); - specialFunction |= ((uint8_t) tele.internationalMode & 0x03) << 2; - specialFunction |= ((uint8_t) tele.abcProtectionMode & 0x03) << 3; - radioTelegram->setPayloadData(specialFunction, 1); - break; - } - case Constraints::id(): - { - const DemandParticipantMode &tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TEILNEHMERMODE_ANFORDERN, - 3, - tele.header.equipmentNumber); - break; - } - case Constraints::id(): - { - const ParticipantConfiguration &tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TEILNEHMER_KONFIG_SETZEN, - 25, - tele.header.equipmentNumber); - radioTelegram->setPayloadData((uint32_t) 0, - 2); - radioTelegram->setPayloadData(tele.positionIntervallVehicle, 2); - radioTelegram->setPayloadData(tele.positionIntervallPersonell, 2); - radioTelegram->setPayloadData(tele.positionIntervallAircraft, 2); - radioTelegram->setPayloadData(tele.positionTransmissionIntervall, 2); - radioTelegram->setPayloadData(tele.heightbarrier, 2); - unsigned char tmp = ((uint8_t) tele.faultPositionHandling & 0x03) << 6; - tmp |= ((uint8_t) tele.switchingPositionIntervall & 0x03); - radioTelegram->setPayloadData(tmp, 1); - radioTelegram->setPayloadData(tele.waittimeAdditionalBroadcastDemand, 2); - radioTelegram->setPayloadData(tele.factorWaittimeIncreaseAtHighload, 1); - radioTelegram->setPayloadData(tele.waittimeAutomaticVulnerabilityIncreaseLevel1, 1); - radioTelegram->setPayloadData(tele.waittimeAutomaticVulnerabilityIncreaseLevel2, 1); - radioTelegram->setPayloadData(tele.waittimeAutomaticVulnerabilityIncreaseLevel3, 1); - radioTelegram->setPayloadData((uint8_t) tele.opticalCode, 1); - radioTelegram->setPayloadData(tele.vulnerabilityModel, 1); - radioTelegram->setPayloadData(tele.validTimeOps, 1); - break; - } - case Constraints::id(): - { - const DemandParticipantConfiguration &tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TEILNEHMER_KONFIG_ANFORDERN, - 3, - tele.header.equipmentNumber); - break; - } - case Constraints::id(): - { - const SanitationRepair &tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_SANITAETSDIENST_INSTANDSETZUNG, - 19, - tele.header.equipmentNumber); - convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); - - radioTelegram->setPayload1Byte(uint8_t(tele.originatorType)); - radioTelegram->setPayload2Byte(tele.equipmentNumberOrigin); - radioTelegram->setPayload1Byte(uint8_t(tele.stateStart)); - - unsigned int bitfield1 = 0; - if (tele.timeOfTreatment) - bitfield1 |= 0x7F; - if (tele.triage) - bitfield1 |= 0x80; - radioTelegram->setPayload1Byte(bitfield1); - - radioTelegram->setPayload1Byte(tele.tyeOfDamage); - - unsigned int bitfield2 = 0; - bitfield2 |= (uint8_t(tele.stateResult) | 0x0F); - bitfield2 |= ((uint8_t(tele.treatmentResult) | 0x30) << 4); - bitfield2 |= (0xC0 << 6); - radioTelegram->setPayload1Byte(bitfield2); - - radioTelegram->setPayload1Byte(tele.fullState); - radioTelegram->setPayloadData(tele.timeOfTreatment, 2); - radioTelegram->setPayloadData(tele.timeOfRecovery, 2); - break; - } - case Constraints::id(): - { - const SanitaryMaterialStockReport &tele(fromJson(a_telegram)); - - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_BESTANDSMELDUNG_SANITAETSMATERIAL, - 15 + tele.sanitaryMaterialCount, - tele.header.equipmentNumber); - convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); - radioTelegram->setPayload4Byte(tele.uniqueId); - radioTelegram->setPayload2Byte(tele.originatorEquipmentNumber); - radioTelegram->setPayload1Byte((uint8_t) tele.qualification); - - radioTelegram->setPayload1Byte(tele.sanitaryMaterialCount); - - for (const auto stock : tele.sanitaryMaterialStock) - radioTelegram->setPayloadData(stock, 1); - - break; - } - case Constraints::id(): - { - const Sanitation &tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_SANITAETSDIENST_INSTANDSETZUNG_PVSAN, - 23, - tele.header.equipmentNumber); - convertToSecAndSetTime(tele.header.timeStamp, radioTelegram); - - int p1 = tele.proceduresTaken & 0xFFFFFFFF; - int p2 = tele.proceduresTaken >> 32; - - radioTelegram->setPayloadData(p2, 4); - radioTelegram->setPayloadData(p1, 4); - radioTelegram->setPayloadData(tele.uniqeId, 4); - radioTelegram->setPayloadData(tele.originatorEquipmentNumber, 2); - radioTelegram->setPayloadData((uint8_t) tele.qualification, 1); - - quint8 sanResultAndEvaluation = (((uint8_t) tele.sanitationEvaluation & 0x03) << 6) - + ((uint8_t) tele.sanitationResult & 0x3f); - radioTelegram->setPayloadData(sanResultAndEvaluation, 1); - - break; - } - case Constraints::id(): - { - const CesHitRequest &tele(fromJson(a_telegram)); - - - - - - - - - - - - - - int chargeTasCode = tele.chargeTasCodeDirect; - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_TREFFER_EREIGNIS_SEKUNDAERWIRKUNG, - 17, - tele.header.equipmentNumber); - const bool insideBuilding = (tele.roomId > 0 && tele.buildingId > 0); - int remainEffectOrTasCodeDirect = 0; - int reserve1 = tele.mineId; - int reserve2 = 0; - int gpsZeit = tele.header.timeStamp ; - switch (tele.aesType) - { - case AreaEffectSimulationType::Unknown: - - - remainEffectOrTasCodeDirect = tele.remainEffectTasCodeDirect; - if (remainEffectOrTasCodeDirect == 100) - { - remainEffectOrTasCodeDirect = 49; - } - break; - case AreaEffectSimulationType::FunctionalArea: - - - - - - - - - - - remainEffectOrTasCodeDirect = tele.remainEffectTasCodeDirect; - - - - chargeTasCode = tele.chargeTasCodeIndirect; - reserve1 = tele.reserve1; - reserve2 = tele.reserve2; - break; - case AreaEffectSimulationType::AirSupport: - case AreaEffectSimulationType::NContamination: - case AreaEffectSimulationType::MineArea: - case AreaEffectSimulationType::CContamination: - remainEffectOrTasCodeDirect = tele.remainEffectTasCodeDirect; - chargeTasCode = tele.chargeTasCodeIndirect; - break; - case AreaEffectSimulationType::DangerZoneExplosion: - remainEffectOrTasCodeDirect = tele.remainEffectTasCodeDirect; - chargeTasCode = tele.chargeTasCodeIndirect; - reserve1 = tele.reserve1; - break; - case AreaEffectSimulationType::ExplosionArea: - case AreaEffectSimulationType::ExplosionSingle: - if (insideBuilding) - { - - remainEffectOrTasCodeDirect = tele.remainEffectTasCodeDirect; - } - else - { - - remainEffectOrTasCodeDirect = 255; - chargeTasCode = tele.chargeTasCodeIndirect; - } - break; - case AreaEffectSimulationType::GasPipeDetonation: - - remainEffectOrTasCodeDirect = tele.remainEffectTasCodeDirect; - break; - default: - - remainEffectOrTasCodeDirect = tele.remainEffectPercent; - chargeTasCode = tele.chargeTasCodeIndirect; - break; - } - - radioTelegram->setPayloadData((uint32_t) gpsZeit, 4); - radioTelegram->setPayload2Byte(chargeTasCode); - if (tele.aesDdsId != 0) - radioTelegram->setPayload2Byte(tele.aesDdsId); - else - radioTelegram->setPayload2Byte(tele.originatorEquipmentNumber); - - radioTelegram->setPayload1Byte(uint8_t(tele.aesType)); - radioTelegram->setPayload1Byte(remainEffectOrTasCodeDirect); - radioTelegram->setPayload2Byte(reserve1); - radioTelegram->setPayload2Byte(reserve2); - DEBUG_LOG(logger()) << "Reserve1 of CesHitRequest: " << reserve1 << " Reserve2: " << reserve2; - - break; - } - case Constraints::id(): - { - const SelectiveReammunition &tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_SELEKTIVE_AUFMUNITIONIERUNG, - 8 + tele.reammunitions.size() * 8, - tele.header.equipmentNumber); - radioTelegram->setPayload4Byte(tele.gearId); - radioTelegram->setPayload1Byte(tele.reammunitions.size()); - for (const auto &reammunition : tele.reammunitions) - { - radioTelegram->setPayload2Byte(reammunition.chargeTypeId); - radioTelegram->setPayload1Byte(reammunition.location); - radioTelegram->setPayload2Byte(reammunition.newStock); - radioTelegram->setPayload2Byte(reammunition.newDefaultStock); - radioTelegram->setPayload1Byte(reammunition.tracerRatio); - } - break; - } - case Constraints::id(): - { - const OcCommand &tele(fromJson(a_telegram)); - radioTelegram = new N_CoPrtCnv::CoPrtCnvRadioTelegram(GEF_SCHIEDSRICHTERKOMMANDO, - 4, - tele.header.equipmentNumber); - radioTelegram->setPayloadData(tele.action, 1); - break; - } - default: - { - ERROR_LOG(logger()) << "Conversion of Central-Telegram to Radio-Telegram with telId=" - << getTelegramId(a_telegram) << " not implemented!"; - } - - - } - return radioTelegram; + std::vector ret; + ret.resize(payloadLen); + memcpy(ret.data(), a_radioTelegram->getPayloadDataPtr(offsetData), payloadLen); + return ret; } -CoPrtCnvRadioTelegram *convertToRadio(CoPrtCnvCentralTelegram *a_telegram) -{ - return convertToRadioInternal(a_telegram); -} - -CoPrtCnvRadioTelegram *convertToRadio( - const TrainingAreaBase::TetraIcd::TrainingAreaTelegram *a_telegram) -{ - return convertToRadioInternal(a_telegram); -} - -static inline Header getHeader(const CoPrtCnvRadioTelegram *a_radioTelegram, size_t tsOffset) -{ - Header hdr; - hdr.equipmentNumber = a_radioTelegram->getIdentity(); - hdr.timeStamp = a_radioTelegram->getPayloadDataUInt32(tsOffset, 4) * 1000LL; - return hdr; -} - -static inline RelativePosition getRelativePosition(const CoPrtCnvRadioTelegram *a_radioTelegram, - size_t offset) -{ - RelativePosition pos; - pos.offsetY = a_radioTelegram->getPayloadDataSInt24(offset); - pos.offsetX = a_radioTelegram->getPayloadDataSInt24(offset + 3); - return pos; -} - -static inline GpsQuality getGpsQuality(const CoPrtCnvRadioTelegram *a_radioTelegram, size_t offset) -{ - const uint8_t gps = a_radioTelegram->getPayloadDataUInt8(offset); - GpsQuality ret; - ret.moreThan4SatellitesAvailable = ((gps & 0x80) == 0x80); - ret.dgpsModeAvailable = ((gps & 0x40) == 0x40); - ret.pdopValue = (gps & 0x3f); - return ret; -} - -static inline OpsPosition getOpsPosition(const CoPrtCnvRadioTelegram *a_radioTelegram, - size_t offset, - size_t *newOffset = nullptr) -{ - const uint8_t opsLen = a_radioTelegram->getPayloadDataUInt8(offset); - offset += 1; - OpsPosition pos; - pos.opsId = -1; - if (opsLen > 0) - { - std::vector opse; - opse.reserve(opsLen); - for (uint32_t i = 0; i < opsLen; i++) - { - opse.push_back(a_radioTelegram->getPayloadDataUInt32(offset, 2)); - offset += 2; - } - pos.opsId = opse.at(opse.size() - 1); - } - if (newOffset) - *newOffset = offset; - return pos; -} - -static inline std::vector getPayload(const CoPrtCnvRadioTelegram *a_radioTelegram, +static inline std::vector getPayload(const CoPrtCnvRadioTelegram* a_radioTelegram, size_t offsetLen, size_t offsetData) { - int payloadLen = a_radioTelegram->getPayloadSize(); - payloadLen -= offsetData; - if (payloadLen <= 0) - { - ERROR_LOG(logger()) << "Radio-Telegram Datenverkehr SRT-TDS contains too less data: " - << payloadLen; - return {}; - } - std::vector ret; - ret.resize(payloadLen); - memcpy(ret.data(), a_radioTelegram->getPayloadDataPtr(offsetData), payloadLen); - return ret; + int payloadLen = a_radioTelegram->getPayloadDataUInt8(offsetLen); + if (payloadLen <= 0) + { + ERROR_LOG(logger()) << "Radio-Telegram Datenverkehr SRT-TDS contains too less data: " << payloadLen; + return {}; + } + std::vector ret; + ret.resize(payloadLen); + memcpy(ret.data(), a_radioTelegram->getPayloadDataPtr(offsetData), payloadLen); + return ret; } -static inline std::vector getPayload(const CoPrtCnvRadioTelegram *a_radioTelegram, - size_t offsetLen, - size_t offsetData) +static N_CoPrtCnv::CoPrtCnvCentralTelegram* toCentral(const TrainingAreaBase::TetraIcd::TrainingAreaTelegram* data) { - int payloadLen = a_radioTelegram->getPayloadDataUInt8(offsetLen); - if (payloadLen <= 0) - { - ERROR_LOG(logger()) << "Radio-Telegram Datenverkehr SRT-TDS contains too less data: " - << payloadLen; - return {}; - } - std::vector ret; - ret.resize(payloadLen); - memcpy(ret.data(), a_radioTelegram->getPayloadDataPtr(offsetData), payloadLen); - return ret; + QJsonObject obj; + obj[QStringLiteral("data")] = data->toJson(); + obj[QStringLiteral("type")] = data->type(); + obj[QStringLiteral("typeId")] = data->id(); + const QByteArray ba = QJsonDocument(obj).toJson(QJsonDocument::Compact); + return new N_CoPrtCnv::CoPrtCnvCentralTelegram(ba, static_cast(data->id())); } -static N_CoPrtCnv::CoPrtCnvCentralTelegram *toCentral( - const TrainingAreaBase::TetraIcd::TrainingAreaTelegram *data) +template void fixupEnum(T lowerBound, T upperBound, T defaultVal, T& valToFixup) { - QJsonObject obj; - obj[QStringLiteral("data")] = data->toJson(); - obj[QStringLiteral("type")] = data->type(); - obj[QStringLiteral("typeId")] = data->id(); - const QByteArray ba = QJsonDocument(obj).toJson(QJsonDocument::Compact); - return new N_CoPrtCnv::CoPrtCnvCentralTelegram(ba, - static_cast( - data->id())); + if (valToFixup >= lowerBound && valToFixup <= upperBound) + return; + valToFixup = defaultVal; } -template -void fixupEnum(T lowerBound, T upperBound, T defaultVal, T &valToFixup) +static bool isPayloadLengthOk(const CoPrtCnvRadioTelegram* tele, uint16_t a_length) { - if (valToFixup >= lowerBound && valToFixup <= upperBound) - return; - valToFixup = defaultVal; + const uint16_t length = tele->getPayloadSize(); + if (length >= a_length) + return true; + + WARNING_LOG(logger()) << "The payload-length of telegram with telId: " << tele->getTelID() << " must be " + << a_length << ", but it is " << length; + return false; } - - - - - -static bool isPayloadLengthOk(const CoPrtCnvRadioTelegram *tele, uint16_t a_length) -{ - const uint16_t length = tele->getPayloadSize(); - if (length >= a_length) - return true; - - WARNING_LOG(logger()) << "The payload-length of telegram with telId: " << tele->getTelID() - << " must be " << a_length << ", but it is " << length; - return false; -} - -static bool isPayloadLengthOk(const CoPrtCnvRadioTelegram *tele, - uint16_t a_minLength, - const uint16_t a_dataAmountOffset, - const uint8_t a_variableDataElementSize, +static bool isPayloadLengthOk(const CoPrtCnvRadioTelegram* tele, uint16_t a_minLength, + const uint16_t a_dataAmountOffset, const uint8_t a_variableDataElementSize, bool useHalf = false) { - if (0 == a_variableDataElementSize) - return isPayloadLengthOk(tele, a_minLength); + if (0 == a_variableDataElementSize) + return isPayloadLengthOk(tele, a_minLength); - const uint16_t length = tele->getPayloadSize(); - if (length >= a_minLength) - { - uint8_t dataAmount = tele->getPayloadDataUInt8(a_dataAmountOffset); - uint16_t dataSize = a_variableDataElementSize * dataAmount; - if (useHalf) + const uint16_t length = tele->getPayloadSize(); + if (length >= a_minLength) { - if ((dataAmount % 2) == 1) - dataSize = a_variableDataElementSize * ((dataAmount / 2.0) + 0.5); - else - dataSize = a_variableDataElementSize * (dataAmount / 2); - } - uint16_t expectedLength = dataSize + a_minLength; - if (expectedLength != length) - { - WARNING_LOG(logger()) << "The payload-length of telegram with telId: " << tele->getTelID() - << " must be " << expectedLength << ", but it is " << length - << " (the amount of variable data in telegram was " << dataAmount - << " => " << dataSize << " bytes)"; - return false; - } - } - else - { - WARNING_LOG(logger()) << "The payload-length of telegram with telId: " << tele->getTelID() - << " must be at least " << a_minLength << ", but it is only " << length; - return false; - } - return true; -} - - - - - -N_CoPrtCnv::CoPrtCnvCentralTelegram *convertToCentral(const CoPrtCnvRadioTelegram *a_radioTelegram) -{ - auto tab = convertToTabTele(a_radioTelegram); - if (!tab) - return nullptr; - auto ret = toCentral(tab); - delete tab; - return ret; -} - -TrainingAreaTelegram *convertToTabTele(const CoPrtCnvRadioTelegram *a_radioTelegram) -{ - switch (a_radioTelegram->getTelID()) - { - case GEF_MANIPULATIONSMELDUNG: - { - if (!isPayloadLengthOk(a_radioTelegram, 12)) - return nullptr; - - auto tele = new ManipulationReport; - tele->header = getHeader(a_radioTelegram, 3); - tele->isManipulation = a_radioTelegram->getPayloadDataUInt32(7, 1); - tele->equipmentFunctionId = a_radioTelegram->getPayloadDataUInt32(8, 1); - - - - - return tele; - } - - case GEF_BITE_MELDUNG2: - { - - if (!isPayloadLengthOk(a_radioTelegram, 27, 19, 7)) - return nullptr; - - auto tele = new BiteReport; - tele->header = getHeader(a_radioTelegram, 3); - tele->loginType = static_cast(a_radioTelegram->getPayloadDataUInt8(7)); - - uint32_t ergebnisCAN = a_radioTelegram->getPayloadDataUInt32(8, 3); - tele->biteState = ergebnisCAN; - - uint8_t ergebnisAusstattung = a_radioTelegram->getPayloadDataUInt8(11); - tele->batteryState = ergebnisAusstattung; - - const auto nonDynamic = getBiteError(a_radioTelegram, 12); - if (nonDynamic.errorNumber != 0 || nonDynamic.canDeviceNumber != 0 - || nonDynamic.subdeviceNumber != 0 || nonDynamic.uniqueId != 0) - tele->biteErrors.push_back(nonDynamic); - - const uint8_t fehlerLen = a_radioTelegram->getPayloadDataUInt8(19); - tele->biteErrors.reserve(tele->biteErrors.size() + fehlerLen); - for (uint8_t i = 0; i < fehlerLen; ++i) - { - const uint8_t iPos = 27 + i * 7; - tele->biteErrors.push_back(getBiteError(a_radioTelegram, iPos)); - } - a_radioTelegram->getPayloadDataUInt32(20, 3); - - tele->configError = a_radioTelegram->getPayloadDataUInt8(23); - uint32_t aktuelleKonfiguration = a_radioTelegram->getPayloadDataUInt32(24, 3); - tele->configState = aktuelleKonfiguration; - return tele; - } - - case GEF_FEUEREREIGNIS_MIT_WAFFENZUORDNUNG: - { - if (!isPayloadLengthOk(a_radioTelegram, 18)) - return nullptr; - - auto tele = new EquipmentGearEvent; - tele->header = getHeader(a_radioTelegram, 3); - tele->charge.gearSerialNumber = a_radioTelegram->getPayloadDataUInt32(7, 4); - tele->charge.gearTasCode = a_radioTelegram->getPayloadDataUInt8(11); - tele->charge.chargeTypeId = a_radioTelegram->getPayloadDataUInt32(12, 2); - tele->chargeAmount = a_radioTelegram->getPayloadDataUInt32(14, 2); - const short remain = a_radioTelegram->getPayloadDataUInt32(16, 2); - tele->charge.remain = remain; - return tele; - } - - case GEF_SW_VERSIONSMELDUNG: - { - - if (!isPayloadLengthOk(a_radioTelegram, 8, 7, 8)) - return nullptr; - - auto tele = new ParticipantSwVersions; - tele->header = getHeader(a_radioTelegram, 3); - - const uint8_t versionsliste_len = a_radioTelegram->getPayloadDataUInt8(7); - tele->equipments.reserve(versionsliste_len); - for (uint32_t i = 0; i < versionsliste_len; i++) - { - const uint8_t iPos = 8 + i * 8; - EquipmentSwVersion ver; - ver.equipmentFunctionId = a_radioTelegram->getPayloadDataUInt8(iPos); - ver.subDeviceId = a_radioTelegram->getPayloadDataUInt8(iPos + 1); - ver.uniqueId = a_radioTelegram->getPayloadDataUInt32(iPos + 2, 4); - ver.swVersion = a_radioTelegram->getPayloadDataUInt32(iPos + 6, 2); - } - return tele; - } - - case GEF_SANITAETSDIENST_INSTANDSETZUNG: - { - if (!isPayloadLengthOk(a_radioTelegram, 19)) - return nullptr; - - auto tele = new SanitationRepair; - tele->header = getHeader(a_radioTelegram, 3); - tele->originatorType = static_cast( - a_radioTelegram->getPayloadDataUInt8(7)); - tele->equipmentNumberOrigin = a_radioTelegram->getPayloadDataUInt32(8, 2); - tele->stateStart = static_cast( - a_radioTelegram->getPayloadDataUInt8(10)); - unsigned int bitfield1 = a_radioTelegram->getPayloadDataUInt8(11); - tele->typeOfTreatment = bitfield1 & 0x7F; - tele->triage = (bitfield1 & 0x80) >> 7; - tele->tyeOfDamage = a_radioTelegram->getPayloadDataUInt8(12); - unsigned int bitfield2 = a_radioTelegram->getPayloadDataUInt8(13); - tele->stateResult = static_cast( - bitfield2 & 0x0F); - tele->treatmentResult - = static_cast( - (bitfield2 & 0x30) >> 4); - tele->triagePriority = ((bitfield2 & 0xC0) >> 6); - tele->fullState = a_radioTelegram->getPayloadDataUInt8(14); - tele->timeOfTreatment = a_radioTelegram->getPayloadDataUInt32(15, 2); - tele->timeOfRecovery = a_radioTelegram->getPayloadDataUInt32(17, 2); - return tele; - } - - case GEF_BESTANDSMELDUNG_SANITAETSMATERIAL: - { - if (!isPayloadLengthOk(a_radioTelegram, 15, 14, 1)) - return nullptr; - - auto tele = new SanitaryMaterialStockReport; - tele->header = getHeader(a_radioTelegram, 3); - - tele->uniqueId = a_radioTelegram->getPayloadDataUInt32(7, 4); - tele->originatorEquipmentNumber = a_radioTelegram->getPayloadDataUInt32(11, 2); - tele->qualification = static_cast(a_radioTelegram->getPayloadDataUInt8(13)); - - const uint16_t sanitaryMaterialCount = a_radioTelegram->getPayloadDataUInt8(14); - - tele->sanitaryMaterialCount = sanitaryMaterialCount; - double size = sanitaryMaterialCount; - - - if (tele->sanitaryMaterialCount != 0) - { - int pos = 15; - std::vector stock; - stock.reserve(sanitaryMaterialCount); - for (int i = 0; i < size; i++) - { - - unsigned int in = a_radioTelegram->getPayloadDataUInt8(pos++); - stock.emplace_back(in); - } - - tele->sanitaryMaterialStock = stock; + uint8_t dataAmount = tele->getPayloadDataUInt8(a_dataAmountOffset); + uint16_t dataSize = a_variableDataElementSize * dataAmount; + if (useHalf) + { + if ((dataAmount % 2) == 1) + dataSize = a_variableDataElementSize * ((dataAmount / 2.0) + 0.5); + else + dataSize = a_variableDataElementSize * (dataAmount / 2); + } + uint16_t expectedLength = dataSize + a_minLength; + if (expectedLength != length) + { + WARNING_LOG(logger()) << "The payload-length of telegram with telId: " << tele->getTelID() << " must be " + << expectedLength << ", but it is " << length + << " (the amount of variable data in telegram was " << dataAmount << " => " + << dataSize << " bytes)"; + return false; + } } else - tele->sanitaryMaterialStock = std::vector(); - return tele; - } - - case GEF_SANITAETSDIENST_INSTANDSETZUNG_PVSAN: - { - if (!isPayloadLengthOk(a_radioTelegram, 23)) - return nullptr; - auto tele = new Sanitation; - tele->header = getHeader(a_radioTelegram, 3); - - qint64 proceduresP1 = a_radioTelegram->getPayloadDataUInt32(7, 4); - qint64 proceduresP2 = a_radioTelegram->getPayloadDataUInt32(11, 4); - - tele->proceduresTaken = (proceduresP1 << 32) + proceduresP2; - - tele->uniqeId = a_radioTelegram->getPayloadDataUInt32(15, 4); - tele->originatorEquipmentNumber = a_radioTelegram->getPayloadDataUInt32(19, 2); - tele->qualification = static_cast(a_radioTelegram->getPayloadDataUInt8(21)); - quint8 enumByte = a_radioTelegram->getPayloadDataUInt8(22); - tele->sanitationEvaluation = static_cast((enumByte & 0xc0) >> 6); - tele->sanitationResult = static_cast(enumByte & 0x3f); - return tele; - } - case GEF_BETRIEBSZUSTAND_AUSSTATTUNG: - { - if (!isPayloadLengthOk(a_radioTelegram, 9)) - return nullptr; - - auto tele = new EquipmentOperationalState; - tele->header = getHeader(a_radioTelegram, 3); - - - - - - - - uint8_t abcSchutz = a_radioTelegram->getPayloadDataUInt8(8); - - tele->nbcProtectionActive = checkBitmask(abcSchutz, 0x40); - return tele; - } - case GEF_FEHLERMELDUNG_GFD: - { - if (!isPayloadLengthOk(a_radioTelegram, 9)) - return nullptr; - - auto tele = new CtaDataError; - tele->header = getHeader(a_radioTelegram, 3); - tele->reason = static_cast(a_radioTelegram->getPayloadDataUInt8(7)); - tele->originTelegramId = a_radioTelegram->getPayloadDataUInt8(8); - return tele; - } - case GEF_WIEDERHERSTELLUNG_FUNKBEREITSCHAFT: - { - if (!isPayloadLengthOk(a_radioTelegram, 31)) - return nullptr; - - auto tele = new RestoreRadioReadiness; - - tele->header = getHeader(a_radioTelegram, 3); - tele->readinessLossPosition = getRelativePosition(a_radioTelegram, 7); - tele->readinessLossTime = a_radioTelegram->getPayloadDataUInt32(13, 4); - tele->readinessRestorePosition = getRelativePosition(a_radioTelegram, 17); - tele->readinessRestoreTime = a_radioTelegram->getPayloadDataUInt32(23, 4); - - return tele; - } - case GEF_POSITIONS_MELDUNG: - { - if (!isPayloadLengthOk(a_radioTelegram, 14)) - return nullptr; - - auto tele = new PositionReport; - tele->header = getHeader(a_radioTelegram, 3); - tele->relPosition = getRelativePosition(a_radioTelegram, 7); - tele->gpsQuality = getGpsQuality(a_radioTelegram, 13); - return tele; - } - case GEF_POSITIONS_MELDUNG_MIT_TEILNEHMER: - { - - if (!isPayloadLengthOk(a_radioTelegram, 15, 14, 2)) - return nullptr; - - auto tele = new PositionReportWithMountedEquipments; - tele->header = getHeader(a_radioTelegram, 3); - tele->relPosition = getRelativePosition(a_radioTelegram, 7); - const uint8_t gps = a_radioTelegram->getPayloadDataUInt8(13); - tele->gpsQuality.moreThan4SatellitesAvailable = ((gps & 0x80) == 0x80); - tele->gpsQuality.dgpsModeAvailable = ((gps & 0x40) == 0x40); - tele->gpsQuality.pdopValue = (gps & 0x3f); - - const uint8_t aufgesessene_teilnehmer_len = a_radioTelegram->getPayloadDataUInt8(14); - tele->mountedEquipments.reserve(aufgesessene_teilnehmer_len); - - for (uint8_t i = 0; i < aufgesessene_teilnehmer_len; i++) { - int eqId = a_radioTelegram->getPayloadDataUInt32(15 + 2 * i, 2); - tele->mountedEquipments.push_back(eqId); + WARNING_LOG(logger()) << "The payload-length of telegram with telId: " << tele->getTelID() + << " must be at least " << a_minLength << ", but it is only " << length; + return false; } - return tele; - } - - - case GEF_DEAKTIVIERUNG_EINZELMINE: - { - if (!isPayloadLengthOk(a_radioTelegram, 13)) - return nullptr; - - auto tele = new MineTriggered; - tele->header = getHeader(a_radioTelegram, 5); - tele->mineAreaId = a_radioTelegram->getPayloadDataUInt32(9, 2); - tele->mineIndex = a_radioTelegram->getPayloadDataUInt32(11, 2); - return tele; - } - case GEF_DEFINITION_IED: - { - if (!isPayloadLengthOk(a_radioTelegram, 24)) - return nullptr; - - auto tele = new DefinitionIed; - tele->header = getHeader(a_radioTelegram, 3); - tele->iedId = a_radioTelegram->getPayloadDataUInt32(7, 2); - tele->iedType = static_cast(a_radioTelegram->getPayloadDataUInt8(9)); - tele->trigger = a_radioTelegram->getPayloadDataUInt8(10); - tele->explosiveForce = a_radioTelegram->getPayloadDataUInt8(11); - tele->relPosition = getRelativePosition(a_radioTelegram, 12); - tele->partyId = a_radioTelegram->getPayloadDataUInt8(18); - tele->pairingState = static_cast(a_radioTelegram->getPayloadDataUInt8(19)); - tele->pairedId = a_radioTelegram->getPayloadDataUInt32(20, 2); - tele->tacticalState = static_cast(a_radioTelegram->getPayloadDataUInt8(22)); - tele->statePyrotechnics = a_radioTelegram->getPayloadDataUInt8(23); - - - fixupEnum(IedType::SuicideIed, IedType::IedBigPyro, IedType::SuicideIed, tele->iedType); - fixupEnum(IedPairingState::NotPaired, - IedPairingState::PairedToOps, - IedPairingState::NotPaired, - tele->pairingState); - fixupEnum(IedTacticalState::NotActive, - IedTacticalState::TriggeredByControlDevice, - IedTacticalState::Unknown, - tele->tacticalState); - return tele; - } - case GEF_ZUSTAND_IED: - { - if (!isPayloadLengthOk(a_radioTelegram, 16)) - return nullptr; - - auto tele = new StateIed; - tele->header = getHeader(a_radioTelegram, 3); - tele->iedId = a_radioTelegram->getPayloadDataUInt32(7, 2); - tele->tacticalState = static_cast(a_radioTelegram->getPayloadDataUInt8(9)); - tele->statePyrotechnics = a_radioTelegram->getPayloadDataUInt8(10); - tele->batteryWarnings = a_radioTelegram->getPayloadDataUInt8(11); - tele->errorStateElectronics = static_cast(a_radioTelegram->getPayloadDataUInt8(12)); - tele->errorStatePyrotechnics1 = static_cast(a_radioTelegram->getPayloadDataUInt8(13)); - tele->errorStatePyrotechnics2 = static_cast(a_radioTelegram->getPayloadDataUInt8(14)); - tele->errorStatePyrotechnics3 = static_cast(a_radioTelegram->getPayloadDataUInt8(15)); - - - fixupEnum(IedTacticalState::NotActive, - IedTacticalState::TriggeredByControlDevice, - IedTacticalState::Unknown, - tele->tacticalState); - fixupEnum(IedError::NoError, - IedError::DeviceMissing, - IedError::DeviceMissing, - tele->errorStateElectronics); - fixupEnum(IedError::NoError, - IedError::DeviceMissing, - IedError::DeviceMissing, - tele->errorStatePyrotechnics1); - fixupEnum(IedError::NoError, - IedError::DeviceMissing, - IedError::DeviceMissing, - tele->errorStatePyrotechnics2); - fixupEnum(IedError::NoError, - IedError::DeviceMissing, - IedError::DeviceMissing, - tele->errorStatePyrotechnics3); - return tele; - } - case GEF_STATUS_EINZELMINENSIMULATOR: - { - if (!isPayloadLengthOk(a_radioTelegram, 17)) - return nullptr; - - auto tele = new DusSingleMineState; - tele->header = getHeader(a_radioTelegram, 3); - tele->mineId = a_radioTelegram->getPayloadDataUInt32(7, 2); - tele->relPosition = getRelativePosition(a_radioTelegram, 9); - tele->chargeTypeId = a_radioTelegram->getPayloadDataUInt8(15); - tele->state = a_radioTelegram->getPayloadDataUInt8(16); - tele->effectStart = tele->header.timeStamp; - return tele; - } - case GEF_TREFFER_EREIGNIS_DUS: - { - if (!isPayloadLengthOk(a_radioTelegram, 23)) - return nullptr; - - auto tele = new StateChangeDirect; - tele->header = getHeader(a_radioTelegram, 3); - tele->relPosition = getRelativePosition(a_radioTelegram, 7); - getTaktZustand(a_radioTelegram, 13, tele); - tele->chargeTypeId = a_radioTelegram->getPayloadDataUInt32(19, 2); - tele->originatorId = a_radioTelegram->getPayloadDataUInt32(21, 2); - return tele; - } - case GEF_TREFFER_EREIGNIS_WIRKSIMULATION: - { - if (!isPayloadLengthOk(a_radioTelegram, 22)) - return nullptr; - - auto tele = new StateChangeIndirect; - tele->header = getHeader(a_radioTelegram, 3); - tele->relPosition = getRelativePosition(a_radioTelegram, 7); - getTaktZustand(a_radioTelegram, 13, tele); - - - tele->originatorId = a_radioTelegram->getPayloadDataUInt32(20, 2); - return tele; - } - case GEF_SCHIEDSRICHTEREINGRIFF: - { - if (!isPayloadLengthOk(a_radioTelegram, 16)) - return nullptr; - - auto tele = new OperatorAction; - tele->header = getHeader(a_radioTelegram, 3); - tele->relPosition = getRelativePosition(a_radioTelegram, 7); - tele->action = a_radioTelegram->getPayloadDataUInt8(13); - tele->operatorId = a_radioTelegram->getPayloadDataUInt32(14, 2); - return tele; - } - case GEF_TREFFER_EREIGNIS_DUS_IPS: - { - - if (!isPayloadLengthOk(a_radioTelegram, 18, 17, 2)) - return nullptr; - - auto tele = new StateChangeDirect; - tele->header = getHeader(a_radioTelegram, 3); - getTaktZustand(a_radioTelegram, 7, tele); - tele->chargeTypeId = a_radioTelegram->getPayloadDataUInt32(13, 2); - tele->originatorId = a_radioTelegram->getPayloadDataUInt32(15, 2); - - size_t iPos = 17; - tele->opsPosition = getOpsPosition(a_radioTelegram, iPos); - return tele; - } - case GEF_TREFFER_EREIGNIS_WIRKSIMULATION_IPS: - { - - if (!isPayloadLengthOk(a_radioTelegram, 17, 16, 2)) - return nullptr; - - auto tele = new StateChangeIndirect; - tele->header = getHeader(a_radioTelegram, 3); - getTaktZustand(a_radioTelegram, 7, tele); - - - tele->originatorId = a_radioTelegram->getPayloadDataUInt32(14, 2); - size_t iPos = 16; - tele->opsPosition = getOpsPosition(a_radioTelegram, iPos); - tele->isSecondaryEffect = true; - return tele; - } - case GEF_TAKTISCHER_STATUS: - { - if (!isPayloadLengthOk(a_radioTelegram, 16)) - return nullptr; - - auto tele = new StateChange; - tele->header = getHeader(a_radioTelegram, 3); - getTaktZustand(a_radioTelegram, 7, tele); - - tele->originatorType = static_cast( - a_radioTelegram->getPayloadDataUInt8(13)); - tele->originatorId = a_radioTelegram->getPayloadDataUInt32(14, 2); - return tele; - } - - case GEF_EINTRETEN_FUNKTIONSRAUM: - { - if (!isPayloadLengthOk(a_radioTelegram, 15)) - return nullptr; - - auto tele = new FunctionalAreaEntry; - tele->header = getHeader(a_radioTelegram, 3); - tele->relPosition = getRelativePosition(a_radioTelegram, 7); - tele->aesDdsId = a_radioTelegram->getPayloadDataUInt32(13, 2); - return tele; - } - case GEF_SONDERSENSORIK_BETRIEBSZUSTAND: - { - if (!isPayloadLengthOk(a_radioTelegram, 9)) - return nullptr; - - auto tele = new SpecialSensorData; - tele->header = getHeader(a_radioTelegram, 3); - getSpecialSensorData(a_radioTelegram, 7, tele); - return tele; - } - case GEF_SONDERSENSORIK_FAHRSPUR: - { - if (!isPayloadLengthOk(a_radioTelegram, 15)) - return nullptr; - - auto tele = new SpecialSensorData; - tele->header = getHeader(a_radioTelegram, 3); - tele->relPosition = getRelativePosition(a_radioTelegram, 7); - getSpecialSensorData(a_radioTelegram, 13, tele); - return tele; - } - case GEF_SONDERSENSORIK_DATEN: - { - if (!isPayloadLengthOk(a_radioTelegram, 16)) - return nullptr; - - auto tele = new SpecialSensorData; - tele->header = getHeader(a_radioTelegram, 3); - tele->relPosition = getRelativePosition(a_radioTelegram, 7); - tele->type = a_radioTelegram->getPayloadDataUInt32(13, 1); - getSpecialSensorData(a_radioTelegram, 14, tele); - tele->nbcType = a_radioTelegram->getPayloadDataUInt32(16, 1); - return tele; - } - case GEF_SONDERSENSORIK_MIVANH_VERLEGEDATEN: - { - if (!isPayloadLengthOk(a_radioTelegram, 24)) - return nullptr; - - auto tele = new MinelayerTrailerData; - tele->header = getHeader(a_radioTelegram, 3); - tele->relPosition = getRelativePosition(a_radioTelegram, 7); - tele->barrierId = a_radioTelegram->getPayloadDataUInt32(13, 2); - tele->layingDensity = a_radioTelegram->getPayloadDataUInt32(15, 1); - tele->effectStart = a_radioTelegram->getPayloadDataUInt32(16, 4) * 1000LL; - tele->effectDuration = a_radioTelegram->getPayloadDataUInt32(20, 1); - tele->indirectChargeTasCode = a_radioTelegram->getPayloadDataUInt32(21, 1); - tele->mineCount = a_radioTelegram->getPayloadDataUInt32(22, 2); - return tele; - } - case GEF_SONDERSENSORIK_WMIV_VERLEGEDATEN: - { - if (!isPayloadLengthOk(a_radioTelegram, 25)) - return nullptr; - - auto tele = new MinelayerThrowerData; - tele->header = getHeader(a_radioTelegram, 3); - tele->relPosition = getRelativePosition(a_radioTelegram, 7); - tele->barrierId = a_radioTelegram->getPayloadDataUInt32(13, 2); - tele->layingDensity = a_radioTelegram->getPayloadDataUInt32(15, 1); - tele->effectStart = a_radioTelegram->getPayloadDataUInt32(16, 4) * 1000LL; - tele->effectDuration = a_radioTelegram->getPayloadDataUInt32(20, 1); - tele->indirectChargeTasCode = a_radioTelegram->getPayloadDataUInt32(21, 1); - tele->throwingType = static_cast( - a_radioTelegram->getPayloadDataUInt32(22, 2)); - tele->mineCount = a_radioTelegram->getPayloadDataUInt32(23, 2); - return tele; - } - case GEF_SONDERSENSORIK_MIVANH_VERLEGEPOSITION: - { - if (!isPayloadLengthOk(a_radioTelegram, 16)) - return nullptr; - - auto tele = new MinelayerTrailerPosition; - tele->header = getHeader(a_radioTelegram, 3); - tele->relPosition = getRelativePosition(a_radioTelegram, 7); - tele->dusSerialNo = a_radioTelegram->getPayloadDataUInt32(13, 2); - tele->indirectChargeTasCode = a_radioTelegram->getPayloadDataUInt32(15, 1); - return tele; - } - case GEF_DATENVERKEHR_SRT_TDS: - { - if (!isPayloadLengthOk(a_radioTelegram, 7)) - return nullptr; - - auto tele = new OpaquePayloadDataIn; - tele->header = getHeader(a_radioTelegram, 3); - tele->relPosition = getRelativePosition(a_radioTelegram, 7); - tele->payloadType = OpaquePayloadDataBase::Type::OC; - tele->payload = getPayload(a_radioTelegram, 7); - return tele; - } - case GEF_DATENVERKEHR_DMF_TDS: - { - if (!isPayloadLengthOk(a_radioTelegram, 7)) - return nullptr; - - auto tele = new OpaquePayloadDataIn; - tele->header = getHeader(a_radioTelegram, 3); - tele->relPosition = getRelativePosition(a_radioTelegram, 7); - tele->payloadType = OpaquePayloadDataBase::Type::FireSmokeMarker; - tele->payload = getPayload(a_radioTelegram, 7); - return tele; - } - case GEF_DATENVERKEHR_GEOP_TDS: - { - if (!isPayloadLengthOk(a_radioTelegram, 14)) - return nullptr; - - auto tele = new OpaquePayloadDataIn; - tele->header = getHeader(a_radioTelegram, 3); - tele->relPosition = getRelativePosition(a_radioTelegram, 7); - tele->gpsQuality = getGpsQuality(a_radioTelegram, 13); - tele->payloadType = OpaquePayloadDataBase::Type::Geopairing; - tele->payload = getPayload(a_radioTelegram, 14, 15); - return tele; - } - case GEF_DATENVERKEHR_TGTC_TDS: - { - if (!isPayloadLengthOk(a_radioTelegram, 7)) - return nullptr; - - auto tele = new OpaquePayloadDataIn; - tele->header = getHeader(a_radioTelegram, 3); - tele->relPosition = getRelativePosition(a_radioTelegram, 7); - tele->payloadType = OpaquePayloadDataBase::Type::Target; - tele->payload = getPayload(a_radioTelegram, 7, 8); - return tele; - } - case GEF_GERAETEEREIGNIS: - { - if (!isPayloadLengthOk(a_radioTelegram, 24)) - return nullptr; - - auto tele = new EquipmentEvent; - tele->header = getHeader(a_radioTelegram, 3); - tele->relPosition = getRelativePosition(a_radioTelegram, 7); - tele->equipmentFunctionId = a_radioTelegram->getPayloadDataUInt8(13); - tele->subDeviceId = a_radioTelegram->getPayloadDataUInt8(14); - tele->uniqueId = a_radioTelegram->getPayloadDataUInt32(15, 4); - tele->code = a_radioTelegram->getPayloadDataUInt8(23); - tele->payload = getPayload(a_radioTelegram, 24, 25); - return tele; - } - - case GEF_WAFFENZUORDNUNG: - { - - if (!isPayloadLengthOk(a_radioTelegram, 8, 7, 6)) - return nullptr; - - auto tele = new EquipmentGearAssignment; - tele->header = getHeader(a_radioTelegram, 3); - - const uint8_t waffen_len = a_radioTelegram->getPayloadDataUInt8(7); - tele->gears.reserve(waffen_len); - for (uint32_t i = 0; i < waffen_len && i < 10; i++) - { - const uint8_t iPos = 8 + i * 6; - - Gear gear; - gear.gearSerialNumber = a_radioTelegram->getPayloadDataUInt32(iPos, 4); - gear.gearTasCode = a_radioTelegram->getPayloadDataUInt8(iPos + 4); - gear.chargeCounting = a_radioTelegram->getPayloadDataUInt8(iPos + 5) != 0; - tele->gears.push_back(std::move(gear)); - } - return tele; - } - case GEF_IPS_POSITIONSDATEN: - { - - if (!isPayloadLengthOk(a_radioTelegram, 8, 7, 2)) - return nullptr; - - auto tele = new PositionReport; - tele->header = getHeader(a_radioTelegram, 3); - tele->header.timeStamp - += 1; - size_t iPos = 7; - tele->opsPosition = getOpsPosition(a_radioTelegram, iPos); - if (tele->opsPosition.opsId == -1) - { - delete tele; - tele = nullptr; - } - return tele; - } - case GEF_MUNITIONSVORRAT_EINER_ZUGEORDNETEN_WAFFE: - { - - constexpr int varSize = 5; - - if (!isPayloadLengthOk(a_radioTelegram, 13, 12, varSize)) - return nullptr; - - auto tele = new EquipmentGearChargeState; - tele->header = getHeader(a_radioTelegram, 3); - GearCharge gc; - gc.gearSerialNumber = a_radioTelegram->getPayloadDataUInt32(7, 4); - gc.gearTasCode = a_radioTelegram->getPayloadDataUInt8(11); - const uint8_t munitionsliste_len = a_radioTelegram->getPayloadDataUInt8(12); - tele->charges.reserve(munitionsliste_len); - for (uint32_t i = 0; i < munitionsliste_len; i++) - { - int iPos = 13; - const int offset = 5 * i; - gc.location = a_radioTelegram->getPayloadDataUInt8(iPos + offset); - iPos++; - short munitionsmenge = a_radioTelegram - ->getPayloadDataUInt32(iPos + offset, - 2); - iPos += 2; - gc.remain = munitionsmenge < 0 ? -1 : munitionsmenge; - gc.chargeTypeId = a_radioTelegram->getPayloadDataUInt32(iPos + offset, 2); - tele->charges.push_back(gc); - } - return tele; - } - case GEF_TREFFER_EREIGNIS_SEKUNDAERWIRKUNG: - { - if (!isPayloadLengthOk(a_radioTelegram, 13)) - return nullptr; - - auto tele = new CesHitRequest; - tele->header = getHeader(a_radioTelegram, 3); - tele->chargeTasCodeDirect = a_radioTelegram->getPayloadDataUInt32(7, 2); - tele->aesDdsId = a_radioTelegram->getPayloadDataUInt32(9, 2); - tele->aesType = static_cast(a_radioTelegram->getPayloadDataUInt8(11)); - tele->remainEffectTasCodeDirect = a_radioTelegram->getPayloadDataUInt8(12); - return tele; - } - case GEF_TEILNEHMERMODE_MELDUNG: - { - if (!isPayloadLengthOk(a_radioTelegram, 15)) - return nullptr; - - auto tele = new ParticipantModeReport; - tele->header = getHeader(a_radioTelegram, 3); - tele->language = static_cast(a_radioTelegram->getPayloadDataUInt8(7)); - tele->operationMode = static_cast( - a_radioTelegram->getPayloadDataUInt8(8)); - tele->reactivationDetoxication = a_radioTelegram->getPayloadDataUInt8(9) - * 10; - tele->reactivationMaintenance = a_radioTelegram->getPayloadDataUInt8(10) - * 10; - tele->reactivationMedic = a_radioTelegram->getPayloadDataUInt8(11) * 10; - unsigned char wph_mode = a_radioTelegram->getPayloadDataUInt8(12); - tele->modeHelmet = static_cast(wph_mode & 0x03); - tele->modeVest = static_cast((wph_mode >> 2) & 0x03); - tele->personellProtectionMode = static_cast((wph_mode >> 4) & 0x07); - - unsigned char protection_mode = a_radioTelegram->getPayloadDataUInt8(13); - tele->protectionLevel = static_cast(protection_mode & 0x06); - tele->abcProtectionMode = static_cast((protection_mode >> 3) & 0x03); - - unsigned char specialFunction = a_radioTelegram->getPayloadDataUInt8( - 14); - tele->handgrenadeSearchMode = static_cast( - specialFunction & 0b11); - tele->internationalMode = static_cast( - (specialFunction >> 2) & 0b11); - return tele; - } - case GEF_TEILNEHMER_KONFIG_ANTWORT: - { - if (!isPayloadLengthOk(a_radioTelegram, 27)) - return nullptr; - - auto tele = new ParticipantConfigurationReport; - tele->header = getHeader(a_radioTelegram, 3); - tele->positionIntervallVehicle = a_radioTelegram->getPayloadDataUInt32(7, 2); - tele->positionIntervallPersonell = a_radioTelegram->getPayloadDataUInt32(9, 2); - tele->positionIntervallAircraft = a_radioTelegram->getPayloadDataUInt32(11, 2); - tele->positionTransmissionIntervall = a_radioTelegram->getPayloadDataUInt32(13, 2); - tele->heightbarrier = a_radioTelegram->getPayloadDataUInt32(15, 2); - unsigned char tmp = a_radioTelegram->getPayloadDataUInt8(17); - tele->faultPositionHandling = static_cast( - (tmp >> 6) & 0x03); - tele->switchingPositionIntervall - = static_cast( - tmp & 0x03); - tele->waittimeAdditionalBroadcastDemand = a_radioTelegram->getPayloadDataUInt32(18, 2); - tele->factorWaittimeIncreaseAtHighload = a_radioTelegram->getPayloadDataUInt8(20); - tele->waittimeAutomaticVulnerabilityIncreaseLevel1 = a_radioTelegram->getPayloadDataUInt8(21); - tele->waittimeAutomaticVulnerabilityIncreaseLevel2 = a_radioTelegram->getPayloadDataUInt8(22); - tele->waittimeAutomaticVulnerabilityIncreaseLevel3 = a_radioTelegram->getPayloadDataUInt8(23); - tele->opticalCode = static_cast( - a_radioTelegram->getPayloadDataUInt8(24)); - tele->vulnerabilityModel = a_radioTelegram->getPayloadDataUInt8(25); - tele->validTimeOps = a_radioTelegram->getPayloadDataUInt8(26); - return tele; - } - case GEF_ESW_MELDUNG: - - return nullptr; - case GEF_NACHFORDERUNG_BROADCAST_TELEGRAMME: - { - if (!isPayloadLengthOk(a_radioTelegram, 10)) - return nullptr; - - auto tele = new RequestBroadcastTelegrams; - tele->header = getHeader(a_radioTelegram, 3); - tele->resetCounter = a_radioTelegram->getPayloadDataUInt8(7); - tele->broadcastIndex = a_radioTelegram->getPayloadDataUInt32(8, 2); - return tele; - } - case GEF_LASER_TARGET_DESIGNATOR_UPDATE: - { - auto tele = new ApacheLaserDesignation; - - tele->header = getHeader(a_radioTelegram, 3); - tele->code = a_radioTelegram->getPayloadDataUInt32(7, 2); - tele->outputPower = a_radioTelegram->getPayloadDataUInt8(9); - tele->gearId = a_radioTelegram->getPayloadDataUInt32(10, 4); - - return tele; - } - default: - { - ERROR_LOG(logger()) << "Conversion of Radio-Telegram to Central-Telegram with telId=" - << a_radioTelegram->getTelID() << " not implemented."; - } - } - return nullptr; + return true; } -} +N_CoPrtCnv::CoPrtCnvCentralTelegram* convertToCentral(const CoPrtCnvRadioTelegram* a_radioTelegram) +{ + auto tab = convertToTabTele(a_radioTelegram); + if (!tab) + return nullptr; + auto ret = toCentral(tab); + delete tab; + return ret; +} -} +TrainingAreaTelegram* convertToTabTele(const CoPrtCnvRadioTelegram* a_radioTelegram) +{ + switch (a_radioTelegram->getTelID()) + { + case GEF_MANIPULATIONSMELDUNG: { + if (!isPayloadLengthOk(a_radioTelegram, 12)) + return nullptr; + + auto tele = new ManipulationReport; + tele->header = getHeader(a_radioTelegram, 3); + tele->isManipulation = a_radioTelegram->getPayloadDataUInt32(7, 1); + tele->equipmentFunctionId = a_radioTelegram->getPayloadDataUInt32(8, 1); + + return tele; + } + + case GEF_BITE_MELDUNG2: { + + if (!isPayloadLengthOk(a_radioTelegram, 27, 19, 7)) + return nullptr; + + auto tele = new BiteReport; + tele->header = getHeader(a_radioTelegram, 3); + tele->loginType = static_cast(a_radioTelegram->getPayloadDataUInt8(7)); + + uint32_t ergebnisCAN = a_radioTelegram->getPayloadDataUInt32(8, 3); + tele->biteState = ergebnisCAN; + + uint8_t ergebnisAusstattung = a_radioTelegram->getPayloadDataUInt8(11); + tele->batteryState = ergebnisAusstattung; + + const auto nonDynamic = getBiteError(a_radioTelegram, 12); + if (nonDynamic.errorNumber != 0 || nonDynamic.canDeviceNumber != 0 || nonDynamic.subdeviceNumber != 0 || + nonDynamic.uniqueId != 0) + tele->biteErrors.push_back(nonDynamic); + + const uint8_t fehlerLen = a_radioTelegram->getPayloadDataUInt8(19); + tele->biteErrors.reserve(tele->biteErrors.size() + fehlerLen); + for (uint8_t i = 0; i < fehlerLen; ++i) + { + const uint8_t iPos = 27 + i * 7; + tele->biteErrors.push_back(getBiteError(a_radioTelegram, iPos)); + } + a_radioTelegram->getPayloadDataUInt32(20, 3); + + tele->configError = a_radioTelegram->getPayloadDataUInt8(23); + uint32_t aktuelleKonfiguration = a_radioTelegram->getPayloadDataUInt32(24, 3); + tele->configState = aktuelleKonfiguration; + return tele; + } + + case GEF_FEUEREREIGNIS_MIT_WAFFENZUORDNUNG: { + if (!isPayloadLengthOk(a_radioTelegram, 18)) + return nullptr; + + auto tele = new EquipmentGearEvent; + tele->header = getHeader(a_radioTelegram, 3); + tele->charge.gearSerialNumber = a_radioTelegram->getPayloadDataUInt32(7, 4); + tele->charge.gearTasCode = a_radioTelegram->getPayloadDataUInt8(11); + tele->charge.chargeTypeId = a_radioTelegram->getPayloadDataUInt32(12, 2); + tele->chargeAmount = a_radioTelegram->getPayloadDataUInt32(14, 2); + const short remain = a_radioTelegram->getPayloadDataUInt32(16, 2); + tele->charge.remain = remain; + return tele; + } + + case GEF_SW_VERSIONSMELDUNG: { + + if (!isPayloadLengthOk(a_radioTelegram, 8, 7, 8)) + return nullptr; + + auto tele = new ParticipantSwVersions; + tele->header = getHeader(a_radioTelegram, 3); + + const uint8_t versionsliste_len = a_radioTelegram->getPayloadDataUInt8(7); + tele->equipments.reserve(versionsliste_len); + for (uint32_t i = 0; i < versionsliste_len; i++) + { + const uint8_t iPos = 8 + i * 8; + EquipmentSwVersion ver; + ver.equipmentFunctionId = a_radioTelegram->getPayloadDataUInt8(iPos); + ver.subDeviceId = a_radioTelegram->getPayloadDataUInt8(iPos + 1); + ver.uniqueId = a_radioTelegram->getPayloadDataUInt32(iPos + 2, 4); + ver.swVersion = a_radioTelegram->getPayloadDataUInt32(iPos + 6, 2); + } + return tele; + } + + case GEF_SANITAETSDIENST_INSTANDSETZUNG: { + if (!isPayloadLengthOk(a_radioTelegram, 19)) + return nullptr; + + auto tele = new SanitationRepair; + tele->header = getHeader(a_radioTelegram, 3); + tele->originatorType = + static_cast(a_radioTelegram->getPayloadDataUInt8(7)); + tele->equipmentNumberOrigin = a_radioTelegram->getPayloadDataUInt32(8, 2); + tele->stateStart = + static_cast(a_radioTelegram->getPayloadDataUInt8(10)); + unsigned int bitfield1 = a_radioTelegram->getPayloadDataUInt8(11); + tele->typeOfTreatment = bitfield1 & 0x7F; + tele->triage = (bitfield1 & 0x80) >> 7; + tele->tyeOfDamage = a_radioTelegram->getPayloadDataUInt8(12); + unsigned int bitfield2 = a_radioTelegram->getPayloadDataUInt8(13); + tele->stateResult = static_cast(bitfield2 & 0x0F); + tele->treatmentResult = + static_cast((bitfield2 & 0x30) >> 4); + tele->triagePriority = ((bitfield2 & 0xC0) >> 6); + tele->fullState = a_radioTelegram->getPayloadDataUInt8(14); + tele->timeOfTreatment = a_radioTelegram->getPayloadDataUInt32(15, 2); + tele->timeOfRecovery = a_radioTelegram->getPayloadDataUInt32(17, 2); + return tele; + } + + case GEF_BESTANDSMELDUNG_SANITAETSMATERIAL: { + if (!isPayloadLengthOk(a_radioTelegram, 15, 14, 1)) + return nullptr; + + auto tele = new SanitaryMaterialStockReport; + tele->header = getHeader(a_radioTelegram, 3); + + tele->uniqueId = a_radioTelegram->getPayloadDataUInt32(7, 4); + tele->originatorEquipmentNumber = a_radioTelegram->getPayloadDataUInt32(11, 2); + tele->qualification = static_cast(a_radioTelegram->getPayloadDataUInt8(13)); + + const uint16_t sanitaryMaterialCount = a_radioTelegram->getPayloadDataUInt8(14); + + tele->sanitaryMaterialCount = sanitaryMaterialCount; + double size = sanitaryMaterialCount; + + if (tele->sanitaryMaterialCount != 0) + { + int pos = 15; + std::vector stock; + stock.reserve(sanitaryMaterialCount); + for (int i = 0; i < size; i++) + { + + unsigned int in = a_radioTelegram->getPayloadDataUInt8(pos++); + stock.emplace_back(in); + } + + tele->sanitaryMaterialStock = stock; + } + else + tele->sanitaryMaterialStock = std::vector(); + return tele; + } + + case GEF_SANITAETSDIENST_INSTANDSETZUNG_PVSAN: { + if (!isPayloadLengthOk(a_radioTelegram, 23)) + return nullptr; + auto tele = new Sanitation; + tele->header = getHeader(a_radioTelegram, 3); + + qint64 proceduresP1 = a_radioTelegram->getPayloadDataUInt32(7, 4); + qint64 proceduresP2 = a_radioTelegram->getPayloadDataUInt32(11, 4); + + tele->proceduresTaken = (proceduresP1 << 32) + proceduresP2; + + tele->uniqeId = a_radioTelegram->getPayloadDataUInt32(15, 4); + tele->originatorEquipmentNumber = a_radioTelegram->getPayloadDataUInt32(19, 2); + tele->qualification = static_cast(a_radioTelegram->getPayloadDataUInt8(21)); + quint8 enumByte = a_radioTelegram->getPayloadDataUInt8(22); + tele->sanitationEvaluation = static_cast((enumByte & 0xc0) >> 6); + tele->sanitationResult = static_cast(enumByte & 0x3f); + return tele; + } + case GEF_BETRIEBSZUSTAND_AUSSTATTUNG: { + if (!isPayloadLengthOk(a_radioTelegram, 9)) + return nullptr; + + auto tele = new EquipmentOperationalState; + tele->header = getHeader(a_radioTelegram, 3); + + uint8_t abcSchutz = a_radioTelegram->getPayloadDataUInt8(8); + + tele->nbcProtectionActive = checkBitmask(abcSchutz, 0x40); + return tele; + } + case GEF_FEHLERMELDUNG_GFD: { + if (!isPayloadLengthOk(a_radioTelegram, 9)) + return nullptr; + + auto tele = new CtaDataError; + tele->header = getHeader(a_radioTelegram, 3); + tele->reason = static_cast(a_radioTelegram->getPayloadDataUInt8(7)); + tele->originTelegramId = a_radioTelegram->getPayloadDataUInt8(8); + return tele; + } + case GEF_WIEDERHERSTELLUNG_FUNKBEREITSCHAFT: { + if (!isPayloadLengthOk(a_radioTelegram, 31)) + return nullptr; + + auto tele = new RestoreRadioReadiness; + + tele->header = getHeader(a_radioTelegram, 3); + tele->readinessLossPosition = getRelativePosition(a_radioTelegram, 7); + tele->readinessLossTime = a_radioTelegram->getPayloadDataUInt32(13, 4); + tele->readinessRestorePosition = getRelativePosition(a_radioTelegram, 17); + tele->readinessRestoreTime = a_radioTelegram->getPayloadDataUInt32(23, 4); + + return tele; + } + case GEF_POSITIONS_MELDUNG: { + if (!isPayloadLengthOk(a_radioTelegram, 14)) + return nullptr; + + auto tele = new PositionReport; + tele->header = getHeader(a_radioTelegram, 3); + tele->relPosition = getRelativePosition(a_radioTelegram, 7); + tele->gpsQuality = getGpsQuality(a_radioTelegram, 13); + return tele; + } + case GEF_POSITIONS_MELDUNG_MIT_TEILNEHMER: { + + if (!isPayloadLengthOk(a_radioTelegram, 15, 14, 2)) + return nullptr; + + auto tele = new PositionReportWithMountedEquipments; + tele->header = getHeader(a_radioTelegram, 3); + tele->relPosition = getRelativePosition(a_radioTelegram, 7); + const uint8_t gps = a_radioTelegram->getPayloadDataUInt8(13); + tele->gpsQuality.moreThan4SatellitesAvailable = ((gps & 0x80) == 0x80); + tele->gpsQuality.dgpsModeAvailable = ((gps & 0x40) == 0x40); + tele->gpsQuality.pdopValue = (gps & 0x3f); + + const uint8_t aufgesessene_teilnehmer_len = a_radioTelegram->getPayloadDataUInt8(14); + tele->mountedEquipments.reserve(aufgesessene_teilnehmer_len); + + for (uint8_t i = 0; i < aufgesessene_teilnehmer_len; i++) + { + int eqId = a_radioTelegram->getPayloadDataUInt32(15 + 2 * i, 2); + tele->mountedEquipments.push_back(eqId); + } + return tele; + } + + case GEF_DEAKTIVIERUNG_EINZELMINE: { + if (!isPayloadLengthOk(a_radioTelegram, 13)) + return nullptr; + + auto tele = new MineTriggered; + tele->header = getHeader(a_radioTelegram, 5); + tele->mineAreaId = a_radioTelegram->getPayloadDataUInt32(9, 2); + tele->mineIndex = a_radioTelegram->getPayloadDataUInt32(11, 2); + return tele; + } + case GEF_DEFINITION_IED: { + if (!isPayloadLengthOk(a_radioTelegram, 24)) + return nullptr; + + auto tele = new DefinitionIed; + tele->header = getHeader(a_radioTelegram, 3); + tele->iedId = a_radioTelegram->getPayloadDataUInt32(7, 2); + tele->iedType = static_cast(a_radioTelegram->getPayloadDataUInt8(9)); + tele->trigger = a_radioTelegram->getPayloadDataUInt8(10); + tele->explosiveForce = a_radioTelegram->getPayloadDataUInt8(11); + tele->relPosition = getRelativePosition(a_radioTelegram, 12); + tele->partyId = a_radioTelegram->getPayloadDataUInt8(18); + tele->pairingState = static_cast(a_radioTelegram->getPayloadDataUInt8(19)); + tele->pairedId = a_radioTelegram->getPayloadDataUInt32(20, 2); + tele->tacticalState = static_cast(a_radioTelegram->getPayloadDataUInt8(22)); + tele->statePyrotechnics = a_radioTelegram->getPayloadDataUInt8(23); + + fixupEnum(IedType::SuicideIed, IedType::IedBigPyro, IedType::SuicideIed, tele->iedType); + fixupEnum(IedPairingState::NotPaired, IedPairingState::PairedToOps, IedPairingState::NotPaired, + tele->pairingState); + fixupEnum(IedTacticalState::NotActive, IedTacticalState::TriggeredByControlDevice, + IedTacticalState::Unknown, tele->tacticalState); + return tele; + } + case GEF_ZUSTAND_IED: { + if (!isPayloadLengthOk(a_radioTelegram, 16)) + return nullptr; + + auto tele = new StateIed; + tele->header = getHeader(a_radioTelegram, 3); + tele->iedId = a_radioTelegram->getPayloadDataUInt32(7, 2); + tele->tacticalState = static_cast(a_radioTelegram->getPayloadDataUInt8(9)); + tele->statePyrotechnics = a_radioTelegram->getPayloadDataUInt8(10); + tele->batteryWarnings = a_radioTelegram->getPayloadDataUInt8(11); + tele->errorStateElectronics = static_cast(a_radioTelegram->getPayloadDataUInt8(12)); + tele->errorStatePyrotechnics1 = static_cast(a_radioTelegram->getPayloadDataUInt8(13)); + tele->errorStatePyrotechnics2 = static_cast(a_radioTelegram->getPayloadDataUInt8(14)); + tele->errorStatePyrotechnics3 = static_cast(a_radioTelegram->getPayloadDataUInt8(15)); + + fixupEnum(IedTacticalState::NotActive, IedTacticalState::TriggeredByControlDevice, + IedTacticalState::Unknown, tele->tacticalState); + fixupEnum(IedError::NoError, IedError::DeviceMissing, IedError::DeviceMissing, tele->errorStateElectronics); + fixupEnum(IedError::NoError, IedError::DeviceMissing, IedError::DeviceMissing, + tele->errorStatePyrotechnics1); + fixupEnum(IedError::NoError, IedError::DeviceMissing, IedError::DeviceMissing, + tele->errorStatePyrotechnics2); + fixupEnum(IedError::NoError, IedError::DeviceMissing, IedError::DeviceMissing, + tele->errorStatePyrotechnics3); + return tele; + } + case GEF_STATUS_EINZELMINENSIMULATOR: { + if (!isPayloadLengthOk(a_radioTelegram, 17)) + return nullptr; + + auto tele = new DusSingleMineState; + tele->header = getHeader(a_radioTelegram, 3); + tele->mineId = a_radioTelegram->getPayloadDataUInt32(7, 2); + tele->relPosition = getRelativePosition(a_radioTelegram, 9); + tele->chargeTypeId = a_radioTelegram->getPayloadDataUInt8(15); + tele->state = a_radioTelegram->getPayloadDataUInt8(16); + tele->effectStart = tele->header.timeStamp; + return tele; + } + case GEF_TREFFER_EREIGNIS_DUS: { + if (!isPayloadLengthOk(a_radioTelegram, 23)) + return nullptr; + + auto tele = new StateChangeDirect; + tele->header = getHeader(a_radioTelegram, 3); + tele->relPosition = getRelativePosition(a_radioTelegram, 7); + getTaktZustand(a_radioTelegram, 13, tele); + tele->chargeTypeId = a_radioTelegram->getPayloadDataUInt32(19, 2); + tele->originatorId = a_radioTelegram->getPayloadDataUInt32(21, 2); + return tele; + } + case GEF_TREFFER_EREIGNIS_WIRKSIMULATION: { + if (!isPayloadLengthOk(a_radioTelegram, 22)) + return nullptr; + + auto tele = new StateChangeIndirect; + tele->header = getHeader(a_radioTelegram, 3); + tele->relPosition = getRelativePosition(a_radioTelegram, 7); + getTaktZustand(a_radioTelegram, 13, tele); + + tele->originatorId = a_radioTelegram->getPayloadDataUInt32(20, 2); + return tele; + } + case GEF_SCHIEDSRICHTEREINGRIFF: { + if (!isPayloadLengthOk(a_radioTelegram, 16)) + return nullptr; + + auto tele = new OperatorAction; + tele->header = getHeader(a_radioTelegram, 3); + tele->relPosition = getRelativePosition(a_radioTelegram, 7); + tele->action = a_radioTelegram->getPayloadDataUInt8(13); + tele->operatorId = a_radioTelegram->getPayloadDataUInt32(14, 2); + return tele; + } + case GEF_TREFFER_EREIGNIS_DUS_IPS: { + + if (!isPayloadLengthOk(a_radioTelegram, 18, 17, 2)) + return nullptr; + + auto tele = new StateChangeDirect; + tele->header = getHeader(a_radioTelegram, 3); + getTaktZustand(a_radioTelegram, 7, tele); + tele->chargeTypeId = a_radioTelegram->getPayloadDataUInt32(13, 2); + tele->originatorId = a_radioTelegram->getPayloadDataUInt32(15, 2); + + size_t iPos = 17; + tele->opsPosition = getOpsPosition(a_radioTelegram, iPos); + return tele; + } + case GEF_TREFFER_EREIGNIS_WIRKSIMULATION_IPS: { + + if (!isPayloadLengthOk(a_radioTelegram, 17, 16, 2)) + return nullptr; + + auto tele = new StateChangeIndirect; + tele->header = getHeader(a_radioTelegram, 3); + getTaktZustand(a_radioTelegram, 7, tele); + + tele->originatorId = a_radioTelegram->getPayloadDataUInt32(14, 2); + size_t iPos = 16; + tele->opsPosition = getOpsPosition(a_radioTelegram, iPos); + tele->isSecondaryEffect = true; + return tele; + } + case GEF_TAKTISCHER_STATUS: { + if (!isPayloadLengthOk(a_radioTelegram, 16)) + return nullptr; + + auto tele = new StateChange; + tele->header = getHeader(a_radioTelegram, 3); + getTaktZustand(a_radioTelegram, 7, tele); + + tele->originatorType = + static_cast(a_radioTelegram->getPayloadDataUInt8(13)); + tele->originatorId = a_radioTelegram->getPayloadDataUInt32(14, 2); + return tele; + } + + case GEF_EINTRETEN_FUNKTIONSRAUM: { + if (!isPayloadLengthOk(a_radioTelegram, 15)) + return nullptr; + + auto tele = new FunctionalAreaEntry; + tele->header = getHeader(a_radioTelegram, 3); + tele->relPosition = getRelativePosition(a_radioTelegram, 7); + tele->aesDdsId = a_radioTelegram->getPayloadDataUInt32(13, 2); + return tele; + } + case GEF_SONDERSENSORIK_BETRIEBSZUSTAND: { + if (!isPayloadLengthOk(a_radioTelegram, 9)) + return nullptr; + + auto tele = new SpecialSensorData; + tele->header = getHeader(a_radioTelegram, 3); + getSpecialSensorData(a_radioTelegram, 7, tele); + return tele; + } + case GEF_SONDERSENSORIK_FAHRSPUR: { + if (!isPayloadLengthOk(a_radioTelegram, 15)) + return nullptr; + + auto tele = new SpecialSensorData; + tele->header = getHeader(a_radioTelegram, 3); + tele->relPosition = getRelativePosition(a_radioTelegram, 7); + getSpecialSensorData(a_radioTelegram, 13, tele); + return tele; + } + case GEF_SONDERSENSORIK_DATEN: { + if (!isPayloadLengthOk(a_radioTelegram, 16)) + return nullptr; + + auto tele = new SpecialSensorData; + tele->header = getHeader(a_radioTelegram, 3); + tele->relPosition = getRelativePosition(a_radioTelegram, 7); + tele->type = a_radioTelegram->getPayloadDataUInt32(13, 1); + getSpecialSensorData(a_radioTelegram, 14, tele); + tele->nbcType = a_radioTelegram->getPayloadDataUInt32(16, 1); + return tele; + } + case GEF_SONDERSENSORIK_MIVANH_VERLEGEDATEN: { + if (!isPayloadLengthOk(a_radioTelegram, 24)) + return nullptr; + + auto tele = new MinelayerTrailerData; + tele->header = getHeader(a_radioTelegram, 3); + tele->relPosition = getRelativePosition(a_radioTelegram, 7); + tele->barrierId = a_radioTelegram->getPayloadDataUInt32(13, 2); + tele->layingDensity = a_radioTelegram->getPayloadDataUInt32(15, 1); + tele->effectStart = a_radioTelegram->getPayloadDataUInt32(16, 4) * 1000LL; + tele->effectDuration = a_radioTelegram->getPayloadDataUInt32(20, 1); + tele->indirectChargeTasCode = a_radioTelegram->getPayloadDataUInt32(21, 1); + tele->mineCount = a_radioTelegram->getPayloadDataUInt32(22, 2); + return tele; + } + case GEF_SONDERSENSORIK_WMIV_VERLEGEDATEN: { + if (!isPayloadLengthOk(a_radioTelegram, 25)) + return nullptr; + + auto tele = new MinelayerThrowerData; + tele->header = getHeader(a_radioTelegram, 3); + tele->relPosition = getRelativePosition(a_radioTelegram, 7); + tele->barrierId = a_radioTelegram->getPayloadDataUInt32(13, 2); + tele->layingDensity = a_radioTelegram->getPayloadDataUInt32(15, 1); + tele->effectStart = a_radioTelegram->getPayloadDataUInt32(16, 4) * 1000LL; + tele->effectDuration = a_radioTelegram->getPayloadDataUInt32(20, 1); + tele->indirectChargeTasCode = a_radioTelegram->getPayloadDataUInt32(21, 1); + tele->throwingType = + static_cast(a_radioTelegram->getPayloadDataUInt32(22, 2)); + tele->mineCount = a_radioTelegram->getPayloadDataUInt32(23, 2); + return tele; + } + case GEF_SONDERSENSORIK_MIVANH_VERLEGEPOSITION: { + if (!isPayloadLengthOk(a_radioTelegram, 16)) + return nullptr; + + auto tele = new MinelayerTrailerPosition; + tele->header = getHeader(a_radioTelegram, 3); + tele->relPosition = getRelativePosition(a_radioTelegram, 7); + tele->dusSerialNo = a_radioTelegram->getPayloadDataUInt32(13, 2); + tele->indirectChargeTasCode = a_radioTelegram->getPayloadDataUInt32(15, 1); + return tele; + } + case GEF_DATENVERKEHR_SRT_TDS: { + if (!isPayloadLengthOk(a_radioTelegram, 7)) + return nullptr; + + auto tele = new OpaquePayloadDataIn; + tele->header = getHeader(a_radioTelegram, 3); + tele->relPosition = getRelativePosition(a_radioTelegram, 7); + tele->payloadType = OpaquePayloadDataBase::Type::OC; + tele->payload = getPayload(a_radioTelegram, 7); + return tele; + } + case GEF_DATENVERKEHR_DMF_TDS: { + if (!isPayloadLengthOk(a_radioTelegram, 7)) + return nullptr; + + auto tele = new OpaquePayloadDataIn; + tele->header = getHeader(a_radioTelegram, 3); + tele->relPosition = getRelativePosition(a_radioTelegram, 7); + tele->payloadType = OpaquePayloadDataBase::Type::FireSmokeMarker; + tele->payload = getPayload(a_radioTelegram, 7); + return tele; + } + case GEF_DATENVERKEHR_GEOP_TDS: { + if (!isPayloadLengthOk(a_radioTelegram, 14)) + return nullptr; + + auto tele = new OpaquePayloadDataIn; + tele->header = getHeader(a_radioTelegram, 3); + tele->relPosition = getRelativePosition(a_radioTelegram, 7); + tele->gpsQuality = getGpsQuality(a_radioTelegram, 13); + tele->payloadType = OpaquePayloadDataBase::Type::Geopairing; + tele->payload = getPayload(a_radioTelegram, 14, 15); + return tele; + } + case GEF_DATENVERKEHR_TGTC_TDS: { + if (!isPayloadLengthOk(a_radioTelegram, 7)) + return nullptr; + + auto tele = new OpaquePayloadDataIn; + tele->header = getHeader(a_radioTelegram, 3); + tele->relPosition = getRelativePosition(a_radioTelegram, 7); + tele->payloadType = OpaquePayloadDataBase::Type::Target; + tele->payload = getPayload(a_radioTelegram, 7, 8); + return tele; + } + case GEF_GERAETEEREIGNIS: { + if (!isPayloadLengthOk(a_radioTelegram, 24)) + return nullptr; + + auto tele = new EquipmentEvent; + tele->header = getHeader(a_radioTelegram, 3); + tele->relPosition = getRelativePosition(a_radioTelegram, 7); + tele->equipmentFunctionId = a_radioTelegram->getPayloadDataUInt8(13); + tele->subDeviceId = a_radioTelegram->getPayloadDataUInt8(14); + tele->uniqueId = a_radioTelegram->getPayloadDataUInt32(15, 4); + tele->code = a_radioTelegram->getPayloadDataUInt8(23); + tele->payload = getPayload(a_radioTelegram, 24, 25); + return tele; + } + + case GEF_WAFFENZUORDNUNG: { + + if (!isPayloadLengthOk(a_radioTelegram, 8, 7, 6)) + return nullptr; + + auto tele = new EquipmentGearAssignment; + tele->header = getHeader(a_radioTelegram, 3); + + const uint8_t waffen_len = a_radioTelegram->getPayloadDataUInt8(7); + tele->gears.reserve(waffen_len); + for (uint32_t i = 0; i < waffen_len && i < 10; i++) + { + const uint8_t iPos = 8 + i * 6; + + Gear gear; + gear.gearSerialNumber = a_radioTelegram->getPayloadDataUInt32(iPos, 4); + gear.gearTasCode = a_radioTelegram->getPayloadDataUInt8(iPos + 4); + gear.chargeCounting = a_radioTelegram->getPayloadDataUInt8(iPos + 5) != 0; + tele->gears.push_back(std::move(gear)); + } + return tele; + } + case GEF_IPS_POSITIONSDATEN: { + + if (!isPayloadLengthOk(a_radioTelegram, 8, 7, 2)) + return nullptr; + + auto tele = new PositionReport; + tele->header = getHeader(a_radioTelegram, 3); + tele->header.timeStamp += 1; + size_t iPos = 7; + tele->opsPosition = getOpsPosition(a_radioTelegram, iPos); + if (tele->opsPosition.opsId == -1) + { + delete tele; + tele = nullptr; + } + return tele; + } + case GEF_MUNITIONSVORRAT_EINER_ZUGEORDNETEN_WAFFE: { + + constexpr int varSize = 5; + + if (!isPayloadLengthOk(a_radioTelegram, 13, 12, varSize)) + return nullptr; + + auto tele = new EquipmentGearChargeState; + tele->header = getHeader(a_radioTelegram, 3); + GearCharge gc; + gc.gearSerialNumber = a_radioTelegram->getPayloadDataUInt32(7, 4); + gc.gearTasCode = a_radioTelegram->getPayloadDataUInt8(11); + const uint8_t munitionsliste_len = a_radioTelegram->getPayloadDataUInt8(12); + tele->charges.reserve(munitionsliste_len); + for (uint32_t i = 0; i < munitionsliste_len; i++) + { + int iPos = 13; + const int offset = 5 * i; + gc.location = a_radioTelegram->getPayloadDataUInt8(iPos + offset); + iPos++; + short munitionsmenge = a_radioTelegram->getPayloadDataUInt32(iPos + offset, 2); + iPos += 2; + gc.remain = munitionsmenge < 0 ? -1 : munitionsmenge; + gc.chargeTypeId = a_radioTelegram->getPayloadDataUInt32(iPos + offset, 2); + tele->charges.push_back(gc); + } + return tele; + } + case GEF_TREFFER_EREIGNIS_SEKUNDAERWIRKUNG: { + if (!isPayloadLengthOk(a_radioTelegram, 13)) + return nullptr; + + auto tele = new CesHitRequest; + tele->header = getHeader(a_radioTelegram, 3); + tele->chargeTasCodeDirect = a_radioTelegram->getPayloadDataUInt32(7, 2); + tele->aesDdsId = a_radioTelegram->getPayloadDataUInt32(9, 2); + tele->aesType = static_cast(a_radioTelegram->getPayloadDataUInt8(11)); + tele->remainEffectTasCodeDirect = a_radioTelegram->getPayloadDataUInt8(12); + return tele; + } + case GEF_TEILNEHMERMODE_MELDUNG: { + if (!isPayloadLengthOk(a_radioTelegram, 15)) + return nullptr; + + auto tele = new ParticipantModeReport; + tele->header = getHeader(a_radioTelegram, 3); + tele->language = static_cast(a_radioTelegram->getPayloadDataUInt8(7)); + tele->operationMode = + static_cast(a_radioTelegram->getPayloadDataUInt8(8)); + tele->reactivationDetoxication = a_radioTelegram->getPayloadDataUInt8(9) * 10; + tele->reactivationMaintenance = a_radioTelegram->getPayloadDataUInt8(10) * 10; + tele->reactivationMedic = a_radioTelegram->getPayloadDataUInt8(11) * 10; + unsigned char wph_mode = a_radioTelegram->getPayloadDataUInt8(12); + tele->modeHelmet = static_cast(wph_mode & 0x03); + tele->modeVest = static_cast((wph_mode >> 2) & 0x03); + tele->personellProtectionMode = + static_cast((wph_mode >> 4) & 0x07); + + unsigned char protection_mode = a_radioTelegram->getPayloadDataUInt8(13); + tele->protectionLevel = static_cast(protection_mode & 0x06); + tele->abcProtectionMode = + static_cast((protection_mode >> 3) & 0x03); + + unsigned char specialFunction = a_radioTelegram->getPayloadDataUInt8(14); + tele->handgrenadeSearchMode = + static_cast(specialFunction & 0b11); + tele->internationalMode = + static_cast((specialFunction >> 2) & 0b11); + return tele; + } + case GEF_TEILNEHMER_KONFIG_ANTWORT: { + if (!isPayloadLengthOk(a_radioTelegram, 27)) + return nullptr; + + auto tele = new ParticipantConfigurationReport; + tele->header = getHeader(a_radioTelegram, 3); + tele->positionIntervallVehicle = a_radioTelegram->getPayloadDataUInt32(7, 2); + tele->positionIntervallPersonell = a_radioTelegram->getPayloadDataUInt32(9, 2); + tele->positionIntervallAircraft = a_radioTelegram->getPayloadDataUInt32(11, 2); + tele->positionTransmissionIntervall = a_radioTelegram->getPayloadDataUInt32(13, 2); + tele->heightbarrier = a_radioTelegram->getPayloadDataUInt32(15, 2); + unsigned char tmp = a_radioTelegram->getPayloadDataUInt8(17); + tele->faultPositionHandling = + static_cast((tmp >> 6) & 0x03); + tele->switchingPositionIntervall = + static_cast(tmp & 0x03); + tele->waittimeAdditionalBroadcastDemand = a_radioTelegram->getPayloadDataUInt32(18, 2); + tele->factorWaittimeIncreaseAtHighload = a_radioTelegram->getPayloadDataUInt8(20); + tele->waittimeAutomaticVulnerabilityIncreaseLevel1 = a_radioTelegram->getPayloadDataUInt8(21); + tele->waittimeAutomaticVulnerabilityIncreaseLevel2 = a_radioTelegram->getPayloadDataUInt8(22); + tele->waittimeAutomaticVulnerabilityIncreaseLevel3 = a_radioTelegram->getPayloadDataUInt8(23); + tele->opticalCode = + static_cast(a_radioTelegram->getPayloadDataUInt8(24)); + tele->vulnerabilityModel = a_radioTelegram->getPayloadDataUInt8(25); + tele->validTimeOps = a_radioTelegram->getPayloadDataUInt8(26); + return tele; + } + case GEF_ESW_MELDUNG: + + return nullptr; + case GEF_NACHFORDERUNG_BROADCAST_TELEGRAMME: { + if (!isPayloadLengthOk(a_radioTelegram, 10)) + return nullptr; + + auto tele = new RequestBroadcastTelegrams; + tele->header = getHeader(a_radioTelegram, 3); + tele->resetCounter = a_radioTelegram->getPayloadDataUInt8(7); + tele->broadcastIndex = a_radioTelegram->getPayloadDataUInt32(8, 2); + return tele; + } + case GEF_LASER_TARGET_DESIGNATOR_UPDATE: { + auto tele = new ApacheLaserDesignation; + + tele->header = getHeader(a_radioTelegram, 3); + tele->code = a_radioTelegram->getPayloadDataUInt32(7, 2); + tele->outputPower = a_radioTelegram->getPayloadDataUInt8(9); + tele->gearId = a_radioTelegram->getPayloadDataUInt32(10, 4); + + return tele; + } + default: { + ERROR_LOG(logger()) << "Conversion of Radio-Telegram to Central-Telegram with telId=" + << a_radioTelegram->getTelID() << " not implemented."; + } + } + return nullptr; +} + +} // namespace CoPrtCnvTelegramConverter + +} // namespace N_CoPrtCnv diff --git a/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/CMakeLists.txt b/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/CMakeLists.txt index 4614f162e..5f400697d 100755 --- a/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/CMakeLists.txt +++ b/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/CMakeLists.txt @@ -19,7 +19,7 @@ SET(NGLLogger_HDRS ADD_DEFINITIONS(-DBUILDING_NGLLOGGER) NGL_ADD_LIBRARY2(ALL NGLLogger SHARED ${NGLLogger_SRCS} ${NGLLogger_HDRS}) NGL_TARGET_INCLUDE_DIRECTORIES(NGLLogger - INTERFACE + PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/../ ${CMAKE_CURRENT_BINARY_DIR} diff --git a/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/INGLLogger.h b/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/INGLLogger.h old mode 100755 new mode 100644 index 981dcf1bb..dfe0c99a6 --- a/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/INGLLogger.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/INGLLogger.h @@ -1,59 +1,56 @@ /** - * Logger interface - * $Id$ - * $HeadURL$ - * $Author$ - */ + * Logger interface + * $Id$ + * $HeadURL$ + * $Author$ + */ #pragma once -#include -#include -#include +#include #include -#include #include #include -#include -#include "ngllogger_export.h" +#include +#include +#include +#include +#include namespace NGL { class INGLLogger; // keep in sync with log4qt/level.h -enum class LogLevel -{ - Undefined = 0, - Trace = 64, - Debug = 96, - Info = 128, - Warning = 150, - Error = 182, - Fatal = 214, +enum class LogLevel { + Undefined = 0, + Trace = 64, + Debug = 96, + Info = 128, + Warning = 150, + Error = 182, + Fatal = 214, }; class LogStreamHelper { -public: - inline LogStreamHelper(INGLLogger &logger, LogLevel level, const char *const file, int line, const char *const function) - : m_logger(logger) - , m_level(level) - , m_line(line) - , m_file(file) - , m_func(function) - {} - inline ~LogStreamHelper(); // after INGLLogger class definition + public: + inline LogStreamHelper(INGLLogger& logger, LogLevel level, const char* const file, int line, + const char* const function) + : m_logger(logger), m_level(level), m_line(line), m_file(file), m_func(function) + { + } - template - inline LogStreamHelper &operator<<(const T &val); + inline ~LogStreamHelper(); // after INGLLogger class definition -private: - std::ostringstream m_buffer; - NGL::INGLLogger &m_logger; - const LogLevel m_level; - const int m_line; - const char *const m_file; - const char *const m_func; + template inline LogStreamHelper& operator<<(const T& val); + + private: + std::ostringstream m_buffer; + NGL::INGLLogger& m_logger; + const LogLevel m_level; + const int m_line; + const char* const m_file; + const char* const m_func; }; // Interface class for source code logging. @@ -64,58 +61,64 @@ private: // information on logger-hierarchies, logging-levels, and configuration files. class INGLLogger { -public: - INGLLogger(const INGLLogger &) = delete; - INGLLogger &operator=(const INGLLogger &) = delete; - INGLLogger() = default; - virtual ~INGLLogger() = default; + public: + INGLLogger(const INGLLogger&) = delete; + INGLLogger& operator=(const INGLLogger&) = delete; + INGLLogger() = default; + virtual ~INGLLogger() = default; - using String = std::string; + using String = std::string; - // Creates an instance of an INGLLogger interface. The fullqualifiedname is - // a dottet sequence (i.e. "NGL.thisandthat.mylogger"). The same name will - // always return the same interface-instance. It is not required to create - // the parent nodes. - virtual INGLLogger &getNGLLogger(const char *fullqualifiedname) = 0; - virtual INGLLogger &getNGLLogger(const std::string &fullqualifiedname) = 0; + // Creates an instance of an INGLLogger interface. The fullqualifiedname is + // a dottet sequence (i.e. "NGL.thisandthat.mylogger"). The same name will + // always return the same interface-instance. It is not required to create + // the parent nodes. + virtual INGLLogger& getNGLLogger(const char* fullqualifiedname) = 0; + virtual INGLLogger& getNGLLogger(const std::string& fullqualifiedname) = 0; + // True if this level is enabled. + virtual bool isTraceEnabled() const = 0; + virtual bool isDebugEnabled() const = 0; + virtual bool isInfoEnabled() const = 0; + virtual bool isWarningEnabled() const = 0; + virtual bool isErrorEnabled() const = 0; + virtual bool isFatalEnabled() const = 0; + virtual bool isLevelEnabled(LogLevel level) const = 0; - // True if this level is enabled. - virtual bool isTraceEnabled() const = 0; - virtual bool isDebugEnabled() const = 0; - virtual bool isInfoEnabled() const = 0; - virtual bool isWarningEnabled() const = 0; - virtual bool isErrorEnabled() const = 0; - virtual bool isFatalEnabled() const = 0; - virtual bool isLevelEnabled(LogLevel level) const = 0; + // Submit a LOG message. + // Use __FILE__ and __NAME__ macros. + virtual void log(LogLevel level, const INGLLogger::String& message, const char* file = nullptr, int line = -1, + const char* function = nullptr) = 0; - // Submit a LOG message. - // Use __FILE__ and __NAME__ macros. - virtual void log(LogLevel level, const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0; + // Submit an TRACE message. + virtual void logTrace(const INGLLogger::String& message, const char* file = nullptr, int line = -1, + const char* function = nullptr) = 0; + // Submit an DEBUG message. + virtual void logDebug(const INGLLogger::String& message, const char* file = nullptr, int line = -1, + const char* function = nullptr) = 0; + // Submit an INFO message. + virtual void logInfo(const INGLLogger::String& message, const char* file = nullptr, int line = -1, + const char* function = nullptr) = 0; + // Submit a WARNING message. + virtual void logWarning(const INGLLogger::String& message, const char* file = nullptr, int line = -1, + const char* function = nullptr) = 0; + // Submit an ERROR message. + virtual void logError(const INGLLogger::String& message, const char* file = nullptr, int line = -1, + const char* function = nullptr) = 0; + // Submit a FATAL message. + virtual void logFatal(const INGLLogger::String& message, const char* file = nullptr, int line = -1, + const char* function = nullptr) = 0; - // Submit an TRACE message. - virtual void logTrace(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0; - // Submit an DEBUG message. - virtual void logDebug(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0; - // Submit an INFO message. - virtual void logInfo(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0; - // Submit a WARNING message. - virtual void logWarning(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0; - // Submit an ERROR message. - virtual void logError(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0; - // Submit a FATAL message. - virtual void logFatal(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0; + // Writes a startup message into the logfile + virtual void logStartup(const char* file, int line, const char* function = nullptr) = 0; + // Writes a shutdown message into the logfile + virtual void logShutdown(const char* file, int line, const char* function = nullptr) = 0; - // Writes a startup message into the logfile - virtual void logStartup(const char *file, int line, const char *function = nullptr) = 0; - // Writes a shutdown message into the logfile - virtual void logShutdown(const char *file, int line, const char *function = nullptr) = 0; + // Get this loggers fullqualified name. + virtual std::string getLoggerName() const = 0; - // Get this loggers fullqualified name. - virtual std::string getLoggerName() const = 0; - - virtual void setNoSpace(bool bNoSpace) = 0; - virtual bool noSpace() const = 0; + virtual void setNoSpace(bool bNoSpace) = 0; + virtual bool noSpace() const = 0; }; // @@ -123,112 +126,90 @@ public: // inline LogStreamHelper::~LogStreamHelper() { - m_logger.log(m_level, m_buffer.str(), m_file, m_line, m_func); + m_logger.log(m_level, m_buffer.str(), m_file, m_line, m_func); } -template -inline LogStreamHelper &LogStreamHelper::operator<<(const T &val) +template inline LogStreamHelper& LogStreamHelper::operator<<(const T& val) { - m_buffer << val; - if (!m_logger.noSpace()) - m_buffer << " "; - return *this; + m_buffer << val; + if (!m_logger.noSpace()) + m_buffer << " "; + return *this; } +} // namespace NGL -} //namespace NGL - -inline std::ostream &operator<<(std::ostream &stream, const QByteArray &str) +inline std::ostream& operator<<(std::ostream& stream, const QByteArray& str) { - stream << std::string(str.data(), str.size()); - return stream; + stream << std::string(str.data(), str.size()); + return stream; } // // operator to ease logging (at least via NglLogging) // -inline std::ostream &operator<<(std::ostream &stream, - const QPointF &value) +inline std::ostream& operator<<(std::ostream& stream, const QPointF& value) { - stream << "QPointF(" << QString::number(value.x(), 'f', 6).toStdString() << "#" << QString::number(value.y(), 'f', 6).toStdString() << ")"; - return stream; + stream << "QPointF(" << QString::number(value.x(), 'f', 6).toStdString() << "#" + << QString::number(value.y(), 'f', 6).toStdString() << ")"; + return stream; } //---------------------------------------------------------------------------- -inline std::ostream &operator<< (std::ostream &stream, - const QPoint &value) +inline std::ostream& operator<<(std::ostream& stream, const QPoint& value) { - stream << "QPoint(" << value.x() << "#" << value.y() << ")"; - return stream; + stream << "QPoint(" << value.x() << "#" << value.y() << ")"; + return stream; } -inline std::ostream &operator<< (std::ostream &stream, - const QSize &value) +inline std::ostream& operator<<(std::ostream& stream, const QSize& value) { - stream << "QSize(w=" << value.width() << ";h=" << value.height() << ")"; - return stream; -} -inline std::ostream &operator<< (std::ostream &stream, - const QSizeF &value) -{ - stream << "QSize(w=" - << QString::number(value.width(), 'f', 6).toStdString() << ";h=" - << QString::number(value.height(), 'f', 6).toStdString() - << ")"; - return stream; + stream << "QSize(w=" << value.width() << ";h=" << value.height() << ")"; + return stream; } - -inline std::ostream &operator<< (std::ostream &stream, - const QRect &value) +inline std::ostream& operator<<(std::ostream& stream, const QSizeF& value) { - stream << "QRect(center=" << value.center() - << " w=" << value.width() - << ";h=" << value.height() - << " bottomLeft=" << value.bottomLeft() - << " topRight=" << value.topRight() - << ")"; - return stream; + stream << "QSize(w=" << QString::number(value.width(), 'f', 6).toStdString() + << ";h=" << QString::number(value.height(), 'f', 6).toStdString() << ")"; + return stream; } -inline std::ostream &operator<< (std::ostream &stream, - const QRectF &value) +inline std::ostream& operator<<(std::ostream& stream, const QRect& value) { - stream << "QRectF(center=" << value.center() - << " w=" << QString::number(value.width(), 'f', 3).toStdString() - << ";h=" << QString::number(value.height(), 'f', 3).toStdString() - << " bottomLeft=" << value.bottomLeft() - << " topRight=" << value.topRight() - << ")"; - return stream; + stream << "QRect(center=" << value.center() << " w=" << value.width() << ";h=" << value.height() + << " bottomLeft=" << value.bottomLeft() << " topRight=" << value.topRight() << ")"; + return stream; } - - -inline std::ostream &operator<< (std::ostream &stream, - const QList &value) +inline std::ostream& operator<<(std::ostream& stream, const QRectF& value) { - stream << "QList(" << value.size() << "): "; - for (int i : value) - stream << i << ";"; - return stream; + stream << "QRectF(center=" << value.center() << " w=" << QString::number(value.width(), 'f', 3).toStdString() + << ";h=" << QString::number(value.height(), 'f', 3).toStdString() << " bottomLeft=" << value.bottomLeft() + << " topRight=" << value.topRight() << ")"; + return stream; } - -inline std::ostream &operator<< (std::ostream &stream, - const QList &value) +inline std::ostream& operator<<(std::ostream& stream, const QList& value) { - stream << "QList(" << value.size() << "): "; - for (const QPointF &item : value) - stream << item << ";"; - return stream; + stream << "QList(" << value.size() << "): "; + for (int i : value) + stream << i << ";"; + return stream; } - -inline std::ostream &operator<<(std::ostream &stream, const QString &str) +inline std::ostream& operator<<(std::ostream& stream, const QList& value) { - return stream << str.toUtf8(); + stream << "QList(" << value.size() << "): "; + for (const QPointF& item : value) + stream << item << ";"; + return stream; +} + +inline std::ostream& operator<<(std::ostream& stream, const QString& str) +{ + return stream << str.toUtf8(); } namespace NGL @@ -236,15 +217,12 @@ namespace NGL namespace NGLLoggerHelper { -NGLLOGGER_EXPORT void hexDumpHelper(NGL::INGLLogger &logger, - NGL::LogLevel level, - const void *a_data, +NGLLOGGER_EXPORT void hexDumpHelper(NGL::INGLLogger& logger, NGL::LogLevel level, const void* a_data, const unsigned int a_size); -inline void hexDumpHelper(NGL::INGLLogger &logger, - NGL::LogLevel level, - const QByteArray &data) + +inline void hexDumpHelper(NGL::INGLLogger& logger, NGL::LogLevel level, const QByteArray& data) { - return hexDumpHelper(logger, level, data.data(), data.size()); + return hexDumpHelper(logger, level, data.data(), data.size()); } } // namespace NGLLoggerHelper @@ -260,41 +238,46 @@ NGLLOGGER_EXPORT std::string getMemoryData(); #define LOGFUNCTION Q_FUNC_INFO // log this output every time, no matter what log level is enabled -#define NOTICE_LOG(logger) \ - NGL::LogStreamHelper(logger, NGL::LogLevel::Info, __FILE__,__LINE__, Q_FUNC_INFO) +#define NOTICE_LOG(logger) NGL::LogStreamHelper(logger, NGL::LogLevel::Info, __FILE__, __LINE__, Q_FUNC_INFO) #ifdef LTS_DEBUG -#define TRACE_LOG(logger) \ - for (bool log_level_enabled = (logger).isTraceEnabled(); log_level_enabled; log_level_enabled = false) \ - NGL::LogStreamHelper(logger, NGL::LogLevel::Trace, __FILE__,__LINE__, Q_FUNC_INFO) +#define TRACE_LOG(logger) \ + for (bool log_level_enabled = (logger).isTraceEnabled(); log_level_enabled; log_level_enabled = false) \ + NGL::LogStreamHelper(logger, NGL::LogLevel::Trace, __FILE__, __LINE__, Q_FUNC_INFO) #else -#define TRACE_LOG(logger) \ - for ( ; false; ) \ - NGL::LogStreamHelper(logger, NGL::LogLevel::Trace, __FILE__,__LINE__, Q_FUNC_INFO) +#define TRACE_LOG(logger) \ + for (; false;) \ + NGL::LogStreamHelper(logger, NGL::LogLevel::Trace, __FILE__, __LINE__, Q_FUNC_INFO) #endif -#define DEBUG_LOG(logger) \ - for (bool log_level_enabled = (logger).isDebugEnabled(); log_level_enabled; log_level_enabled = false) \ - NGL::LogStreamHelper(logger, NGL::LogLevel::Debug, __FILE__,__LINE__, Q_FUNC_INFO) +#define DEBUG_LOG(logger) \ + for (bool log_level_enabled = (logger).isDebugEnabled(); log_level_enabled; log_level_enabled = false) \ + NGL::LogStreamHelper(logger, NGL::LogLevel::Debug, __FILE__, __LINE__, Q_FUNC_INFO) -#define INFO_LOG(logger) \ - for (bool log_level_enabled = (logger).isInfoEnabled(); log_level_enabled; log_level_enabled = false) \ - NGL::LogStreamHelper(logger, NGL::LogLevel::Info, __FILE__,__LINE__, Q_FUNC_INFO) +#define INFO_LOG(logger) \ + for (bool log_level_enabled = (logger).isInfoEnabled(); log_level_enabled; log_level_enabled = false) \ + NGL::LogStreamHelper(logger, NGL::LogLevel::Info, __FILE__, __LINE__, Q_FUNC_INFO) -#define WARNING_LOG(logger) \ - for (bool log_level_enabled = (logger).isWarningEnabled(); log_level_enabled; log_level_enabled = false) \ - NGL::LogStreamHelper(logger, NGL::LogLevel::Warning, __FILE__,__LINE__, Q_FUNC_INFO) +#define WARNING_LOG(logger) \ + for (bool log_level_enabled = (logger).isWarningEnabled(); log_level_enabled; log_level_enabled = false) \ + NGL::LogStreamHelper(logger, NGL::LogLevel::Warning, __FILE__, __LINE__, Q_FUNC_INFO) -#define ERROR_LOG(logger) \ - for (bool log_level_enabled = (logger).isErrorEnabled(); log_level_enabled; log_level_enabled = false) \ - NGL::LogStreamHelper(logger, NGL::LogLevel::Error, __FILE__,__LINE__, Q_FUNC_INFO) +#define ERROR_LOG(logger) \ + for (bool log_level_enabled = (logger).isErrorEnabled(); log_level_enabled; log_level_enabled = false) \ + NGL::LogStreamHelper(logger, NGL::LogLevel::Error, __FILE__, __LINE__, Q_FUNC_INFO) -#define FATAL_LOG(logger) \ - for (bool log_level_enabled = (logger).isFatalEnabled(); log_level_enabled; log_level_enabled = false) \ - NGL::LogStreamHelper(logger, NGL::LogLevel::Fatal, __FILE__,__LINE__, Q_FUNC_INFO) +#define FATAL_LOG(logger) \ + for (bool log_level_enabled = (logger).isFatalEnabled(); log_level_enabled; log_level_enabled = false) \ + NGL::LogStreamHelper(logger, NGL::LogLevel::Fatal, __FILE__, __LINE__, Q_FUNC_INFO) -#define STARTUP_LOG(logger) { (logger).logStartup(__FILE__, __LINE__, Q_FUNC_INFO); } -#define SHUTDOWN_LOG(logger) { (logger).logShutdown(__FILE__, __LINE__, Q_FUNC_INFO); } +#define STARTUP_LOG(logger) \ + { \ + (logger).logStartup(__FILE__, __LINE__, Q_FUNC_INFO); \ + } +#define SHUTDOWN_LOG(logger) \ + { \ + (logger).logShutdown(__FILE__, __LINE__, Q_FUNC_INFO); \ + } //============================================================================== @@ -303,8 +286,10 @@ NGLLOGGER_EXPORT std::string getMemoryData(); // do something nasty // MEMORY_LOG() << " after something nasty"; -#define MEMORY_LOG() \ - for (bool log_level_enabled = (NGL::getMemoryLogger()).isInfoEnabled(); log_level_enabled; log_level_enabled = false) \ - NGL::LogStreamHelper(NGL::getMemoryLogger(), NGL::LogLevel::Info, __FILE__,__LINE__, Q_FUNC_INFO) << NGL::getMemoryData() +#define MEMORY_LOG() \ + for (bool log_level_enabled = (NGL::getMemoryLogger()).isInfoEnabled(); log_level_enabled; \ + log_level_enabled = false) \ + NGL::LogStreamHelper(NGL::getMemoryLogger(), NGL::LogLevel::Info, __FILE__, __LINE__, Q_FUNC_INFO) \ + << NGL::getMemoryData() //============================================================================== diff --git a/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/NGLLoggerBootstrap.h b/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/NGLLoggerBootstrap.h old mode 100755 new mode 100644 index 6e7055f59..fc74587cf --- a/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/NGLLoggerBootstrap.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/NGLLogger/NGLLoggerBootstrap.h @@ -1,11 +1,10 @@ - #ifndef NGLLOGGERBOOTSTRAP_H #define NGLLOGGERBOOTSTRAP_H #include -#include "ngllogger_export.h" +#include namespace NGL { @@ -14,46 +13,33 @@ namespace NGLLoggerBootstrap { class AlreadyCreatedError final : public std::exception { - const char* what() const noexcept override - { - return "NGLLogger rootlogger already created!"; - } + const char* what() const noexcept override + { + return "NGLLogger rootlogger already created!"; + } }; class NotCreatedError final : public std::exception { - const char* what() const noexcept override - { - return "NGLLogger rootlogger not yet created!"; - } + const char* what() const noexcept override + { + return "NGLLogger rootlogger not yet created!"; + } }; +NGLLOGGER_EXPORT INGLLogger& getNGLRootLogger(); +NGLLOGGER_EXPORT INGLLogger& createNGLRootLogger(const QString& configfilename, bool ignorealreadycreated, + const QString& logOutputName = QString(), bool quiet = false); - -NGLLOGGER_EXPORT INGLLogger &getNGLRootLogger(); - - - - - - - - -NGLLOGGER_EXPORT INGLLogger &createNGLRootLogger(const QString &configfilename, - bool ignorealreadycreated, - const QString &logOutputName = QString(), - bool quiet = false); -inline INGLLogger &createNGLRootLogger(const char *configfilename, - bool ignorealreadycreated, - const QString &logOutputName = QString()) +inline INGLLogger& createNGLRootLogger(const char* configfilename, bool ignorealreadycreated, + const QString& logOutputName = QString()) { - return createNGLRootLogger(QString::fromUtf8(configfilename), ignorealreadycreated, logOutputName); + return createNGLRootLogger(QString::fromUtf8(configfilename), ignorealreadycreated, logOutputName); } -} +} // namespace NGLLoggerBootstrap -} +} // namespace NGL - -#endif +#endif diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_bzip2iodevice.cpp b/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_bzip2iodevice.cpp old mode 100755 new mode 100644 index f49da4edf..4f790d5be --- a/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_bzip2iodevice.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_bzip2iodevice.cpp @@ -1,360 +1,341 @@ - - - #include "nglcomp_bzip2iodevice.h" #include #include - #include - - - class BZip2IODevice::Private { -public: - Private(BZip2IODevice *parent_, QIODevice *dev, int bs) - : parent(parent_) - , device(dev) - , iCurPos(0) - , iMaxBufSize(1024 * 1024) - , blocksize(bs) - , initialized(false) - , decomressStreamEnd(false) - { - buffer.resize(iMaxBufSize); - } + public: + Private(BZip2IODevice* parent_, QIODevice* dev, int bs) + : parent(parent_), device(dev), iCurPos(0), iMaxBufSize(1024 * 1024), blocksize(bs), initialized(false), + decomressStreamEnd(false) + { + buffer.resize(iMaxBufSize); + } - bool initializeCompress(); - qint64 doCompress(const char *in, qint64 iMaxLen); - bool finishCompress(); - bool initializeDecompress(); - qint64 doDecompress(char *out, qint64 iMaxLen); - bool finishDecompress(); - static QString bzipError2String(int errCode); + bool initializeCompress(); + qint64 doCompress(const char* in, qint64 iMaxLen); + bool finishCompress(); + bool initializeDecompress(); + qint64 doDecompress(char* out, qint64 iMaxLen); + bool finishDecompress(); + static QString bzipError2String(int errCode); - QAtomicInt aborted { 0 }; - BZip2IODevice *parent; - QIODevice *device; - unsigned int iCurPos; - unsigned int iMaxBufSize; - unsigned int blocksize; - bool initialized; - bool decomressStreamEnd; - QByteArray buffer; - bz_stream stream; + QAtomicInt aborted{0}; + BZip2IODevice* parent; + QIODevice* device; + unsigned int iCurPos; + unsigned int iMaxBufSize; + unsigned int blocksize; + bool initialized; + bool decomressStreamEnd; + QByteArray buffer; + bz_stream stream; }; bool BZip2IODevice::Private::initializeCompress() { - if (initialized) - return true; - memset(&stream, 0, sizeof(stream)); - int blockSize = (blocksize > 0 && blocksize < 10) ? blocksize : 10; - int ret = BZ2_bzCompressInit(&stream, blockSize, 0, 0); - if (ret != BZ_OK) - { - parent->setErrorString(QStringLiteral("Error initializing bzip2 %1").arg(bzipError2String(ret))); - initialized = false; - } - else - initialized = true; + if (initialized) + return true; + memset(&stream, 0, sizeof(stream)); + int blockSize = (blocksize > 0 && blocksize < 10) ? blocksize : 10; + int ret = BZ2_bzCompressInit(&stream, blockSize, 0, 0); + if (ret != BZ_OK) + { + parent->setErrorString(QStringLiteral("Error initializing bzip2 %1").arg(bzipError2String(ret))); + initialized = false; + } + else + initialized = true; - return initialized; + return initialized; } -qint64 BZip2IODevice::Private::doCompress(const char *in, qint64 iMaxLen) +qint64 BZip2IODevice::Private::doCompress(const char* in, qint64 iMaxLen) { - if (!initialized) - { - if (parent->errorString().isEmpty()) - parent->setErrorString(QLatin1String("Internal Error - bzip not initialized")); - finishCompress(); - return -1; - } - if (iMaxLen > 2 * 1024 * 1024 * 1024LL) - { - finishCompress(); - parent->setErrorString(QLatin1String("Currently can't handle more than 2GB!")); - return -1; - } - - stream.next_in = const_cast(in); - stream.avail_in = iMaxLen; - - do - { - if (aborted) return 0; - - stream.next_out = buffer.data(); - stream.avail_out = buffer.size(); - - const int ret = BZ2_bzCompress(&stream, BZ_RUN); - if (ret != BZ_RUN_OK) + if (!initialized) { - finishCompress(); - parent->setErrorString(QStringLiteral("Error executing BZ2_bzCompress: %1").arg(bzipError2String(ret))); - return -1; - } - int iBytesToWrite = buffer.size() - stream.avail_out; - if (iBytesToWrite) - { - if (device->write(buffer.constData(), iBytesToWrite) != iBytesToWrite) - { + if (parent->errorString().isEmpty()) + parent->setErrorString(QLatin1String("Internal Error - bzip not initialized")); finishCompress(); - parent->setErrorString(QLatin1String("Error writing to QIODevice")); return -1; - } } - } - while (stream.avail_in != 0); + if (iMaxLen > 2 * 1024 * 1024 * 1024LL) + { + finishCompress(); + parent->setErrorString(QLatin1String("Currently can't handle more than 2GB!")); + return -1; + } - return stream.next_in - in; + stream.next_in = const_cast(in); + stream.avail_in = iMaxLen; + + do + { + if (aborted) + return 0; + + stream.next_out = buffer.data(); + stream.avail_out = buffer.size(); + + const int ret = BZ2_bzCompress(&stream, BZ_RUN); + if (ret != BZ_RUN_OK) + { + finishCompress(); + parent->setErrorString(QStringLiteral("Error executing BZ2_bzCompress: %1").arg(bzipError2String(ret))); + return -1; + } + int iBytesToWrite = buffer.size() - stream.avail_out; + if (iBytesToWrite) + { + if (device->write(buffer.constData(), iBytesToWrite) != iBytesToWrite) + { + finishCompress(); + parent->setErrorString(QLatin1String("Error writing to QIODevice")); + return -1; + } + } + } while (stream.avail_in != 0); + + return stream.next_in - in; } bool BZip2IODevice::Private::finishCompress() { - if (!initialized || aborted) + if (!initialized || aborted) + return true; + + int ret = -1; + + do + { + stream.next_out = buffer.data(); + stream.avail_out = buffer.size(); + ret = BZ2_bzCompress(&stream, BZ_FINISH); + if (ret != BZ_FINISH_OK && ret != BZ_STREAM_END) + { + finishCompress(); + parent->setErrorString(QStringLiteral("Error executing BZ2_bzCompress: %1").arg(bzipError2String(ret))); + return false; + } + int iBytesToWrite = buffer.size() - stream.avail_out; + if (device->write(buffer.constData(), iBytesToWrite) != iBytesToWrite) + { + finishCompress(); + parent->setErrorString(QLatin1String("Error writing to QIODevice")); + return false; + } + } while (ret != BZ_STREAM_END); + BZ2_bzCompressEnd(&stream); + + initialized = false; return true; - - int ret = -1; - - do - { - stream.next_out = buffer.data(); - stream.avail_out = buffer.size(); - ret = BZ2_bzCompress(&stream, BZ_FINISH); - if (ret != BZ_FINISH_OK && ret != BZ_STREAM_END) - { - finishCompress(); - parent->setErrorString(QStringLiteral("Error executing BZ2_bzCompress: %1").arg(bzipError2String(ret))); - return false; - } - int iBytesToWrite = buffer.size() - stream.avail_out; - if (device->write(buffer.constData(), iBytesToWrite) != iBytesToWrite) - { - finishCompress(); - parent->setErrorString(QLatin1String("Error writing to QIODevice")); - return false; - } - } - while (ret != BZ_STREAM_END); - BZ2_bzCompressEnd(&stream); - - initialized = false; - return true; } bool BZip2IODevice::Private::initializeDecompress() { - if (initialized) - return true; - memset(&stream, 0, sizeof(stream)); - int ret = BZ2_bzDecompressInit(&stream, 0, 0); - if (ret != BZ_OK) - { - parent->setErrorString(QStringLiteral("Error initializing bzip2: %1").arg(bzipError2String(ret))); - initialized = false; - } - else - initialized = true; - decomressStreamEnd = false; - return initialized; + if (initialized) + return true; + memset(&stream, 0, sizeof(stream)); + int ret = BZ2_bzDecompressInit(&stream, 0, 0); + if (ret != BZ_OK) + { + parent->setErrorString(QStringLiteral("Error initializing bzip2: %1").arg(bzipError2String(ret))); + initialized = false; + } + else + initialized = true; + decomressStreamEnd = false; + return initialized; } -qint64 BZip2IODevice::Private::doDecompress(char *out, qint64 iMaxLen) +qint64 BZip2IODevice::Private::doDecompress(char* out, qint64 iMaxLen) { - int ret = -1; - if (!initialized) - { - if (parent->errorString().isEmpty()) - parent->setErrorString(QLatin1String("Internal Error - bzip not initialized")); - finishDecompress(); - return -1; - } - if (decomressStreamEnd) - return 0; - - if (iMaxLen > 2 * 1024 * 1024 * 1024LL) - { - finishCompress(); - parent->setErrorString(QLatin1String("Currently can't handle more than 2GB!")); - return -1; - } - - stream.next_out = out; - stream.avail_out = iMaxLen; - - do - { - if (ret != BZ_STREAM_END && stream.avail_in == 0) + int ret = -1; + if (!initialized) { - qint64 iReadCnt = device->read(buffer.data(), buffer.size()); - if (iReadCnt <= 0) + if (parent->errorString().isEmpty()) + parent->setErrorString(QLatin1String("Internal Error - bzip not initialized")); + finishDecompress(); + return -1; + } + if (decomressStreamEnd) + return 0; + + if (iMaxLen > 2 * 1024 * 1024 * 1024LL) + { + finishCompress(); + parent->setErrorString(QLatin1String("Currently can't handle more than 2GB!")); return -1; - stream.next_in = buffer.data(); - stream.avail_in = iReadCnt; } - ret = BZ2_bzDecompress(&stream); - if (ret != BZ_OK && ret != BZ_STREAM_END) + stream.next_out = out; + stream.avail_out = iMaxLen; + + do { - parent->setErrorString(QStringLiteral("Error executing BZ2_bzCompress: %1").arg(bzipError2String(ret))); - finishDecompress(); - return -1; - } - } - while (stream.avail_out != 0 && ret != BZ_STREAM_END); - decomressStreamEnd = (ret == BZ_STREAM_END); - return stream.next_out - out; + if (ret != BZ_STREAM_END && stream.avail_in == 0) + { + qint64 iReadCnt = device->read(buffer.data(), buffer.size()); + if (iReadCnt <= 0) + return -1; + stream.next_in = buffer.data(); + stream.avail_in = iReadCnt; + } + + ret = BZ2_bzDecompress(&stream); + if (ret != BZ_OK && ret != BZ_STREAM_END) + { + parent->setErrorString(QStringLiteral("Error executing BZ2_bzCompress: %1").arg(bzipError2String(ret))); + finishDecompress(); + return -1; + } + } while (stream.avail_out != 0 && ret != BZ_STREAM_END); + decomressStreamEnd = (ret == BZ_STREAM_END); + return stream.next_out - out; } bool BZip2IODevice::Private::finishDecompress() { - if (!initialized) - return true; - BZ2_bzDecompressEnd(&stream); + if (!initialized) + return true; + BZ2_bzDecompressEnd(&stream); - initialized = false; - return true; + initialized = false; + return true; } QString BZip2IODevice::Private::bzipError2String(int errCode) { - switch (errCode) - { - case BZ_SEQUENCE_ERROR: - return QLatin1String("Sequence error"); - case BZ_PARAM_ERROR: - return QLatin1String("Parameter not correct"); - case BZ_MEM_ERROR: - return QLatin1String("Memory allocation error"); - case BZ_DATA_ERROR: - return QLatin1String("Invalid input data"); - case BZ_DATA_ERROR_MAGIC: - return QLatin1String("Not a bzip2 file"); - case BZ_IO_ERROR: - return QLatin1String("I/O error"); - case BZ_UNEXPECTED_EOF: - return QLatin1String("Unexpected end of file"); - case BZ_OUTBUFF_FULL: - return QLatin1String("Output buffer full"); - case BZ_CONFIG_ERROR: - return QLatin1String("Wrong config parameter"); - }; - return QString::number(errCode); + switch (errCode) + { + case BZ_SEQUENCE_ERROR: + return QLatin1String("Sequence error"); + case BZ_PARAM_ERROR: + return QLatin1String("Parameter not correct"); + case BZ_MEM_ERROR: + return QLatin1String("Memory allocation error"); + case BZ_DATA_ERROR: + return QLatin1String("Invalid input data"); + case BZ_DATA_ERROR_MAGIC: + return QLatin1String("Not a bzip2 file"); + case BZ_IO_ERROR: + return QLatin1String("I/O error"); + case BZ_UNEXPECTED_EOF: + return QLatin1String("Unexpected end of file"); + case BZ_OUTBUFF_FULL: + return QLatin1String("Output buffer full"); + case BZ_CONFIG_ERROR: + return QLatin1String("Wrong config parameter"); + }; + return QString::number(errCode); } - - - -BZip2IODevice::BZip2IODevice(QIODevice *dev, int blocksize) - : d(new Private(this, dev, blocksize)) -{} +BZip2IODevice::BZip2IODevice(QIODevice* dev, int blocksize) : d(new Private(this, dev, blocksize)) {} BZip2IODevice::~BZip2IODevice() { - close(); - delete d; + close(); + delete d; } void BZip2IODevice::setBufferSize(unsigned int size) { - d->iMaxBufSize = size > 1024 ? size : 1024; - d->buffer.resize(d->iMaxBufSize); + d->iMaxBufSize = size > 1024 ? size : 1024; + d->buffer.resize(d->iMaxBufSize); } void BZip2IODevice::setBlockSize(unsigned int size) { - if (isOpen()) - return; - d->blocksize = size; + if (isOpen()) + return; + d->blocksize = size; } bool BZip2IODevice::isSequential() const { - return true; + return true; } bool BZip2IODevice::open(OpenMode mode) { - if ((mode & QIODevice::ReadWrite) == 0) - { - setErrorString(QStringLiteral("Unsupported OpenMode %1").arg(mode)); - return false; - } - if ((mode & QIODevice::ReadWrite) == QIODevice::ReadWrite) - { - setErrorString(QLatin1String("Can't read and write simultaniously")); - return false; - } - if ((mode & QIODevice::ReadOnly) == QIODevice::ReadOnly) - { - if (!d->device) + if ((mode & QIODevice::ReadWrite) == 0) { - setErrorString(QLatin1String("No QIODevice for reading available")); - return false; + setErrorString(QStringLiteral("Unsupported OpenMode %1").arg(static_cast(mode))); + return false; } - if ((d->device->openMode() & QIODevice::ReadOnly) == 0) + if ((mode & QIODevice::ReadWrite) == QIODevice::ReadWrite) { - setErrorString(QLatin1String("QIODevice not opened for reading")); - return false; + setErrorString(QLatin1String("Can't read and write simultaniously")); + return false; } - if (!d->initializeDecompress()) - return false; - } - else - { - if (!d->device) + if ((mode & QIODevice::ReadOnly) == QIODevice::ReadOnly) { - setErrorString(QLatin1String("No QIODevice for writing available")); - return false; + if (!d->device) + { + setErrorString(QLatin1String("No QIODevice for reading available")); + return false; + } + if ((d->device->openMode() & QIODevice::ReadOnly) == 0) + { + setErrorString(QLatin1String("QIODevice not opened for reading")); + return false; + } + if (!d->initializeDecompress()) + return false; } - if ((d->device->openMode() & QIODevice::WriteOnly) == 0) + else { - setErrorString(QLatin1String("QIODevice not opened for writing")); - return false; + if (!d->device) + { + setErrorString(QLatin1String("No QIODevice for writing available")); + return false; + } + if ((d->device->openMode() & QIODevice::WriteOnly) == 0) + { + setErrorString(QLatin1String("QIODevice not opened for writing")); + return false; + } + if (!d->initializeCompress()) + return false; } - if (!d->initializeCompress()) - return false; - } - setErrorString(QString()); - setOpenMode(mode); - return QIODevice::open(mode); + setErrorString(QString()); + setOpenMode(mode); + return QIODevice::open(mode); } void BZip2IODevice::abort() { - d->aborted = 1; + d->aborted = 1; } void BZip2IODevice::close() { - if (!isOpen()) - return; - if ((openMode() & QIODevice::ReadOnly) == QIODevice::ReadOnly) - d->finishDecompress(); - else - d->finishCompress(); - QIODevice::close(); + if (!isOpen()) + return; + if ((openMode() & QIODevice::ReadOnly) == QIODevice::ReadOnly) + d->finishDecompress(); + else + d->finishCompress(); + QIODevice::close(); } bool BZip2IODevice::atEnd() const { - if (!d->device) - return true; - return d->device->atEnd() && d->decomressStreamEnd && QIODevice::atEnd(); + if (!d->device) + return true; + return d->device->atEnd() && d->decomressStreamEnd && QIODevice::atEnd(); } -qint64 BZip2IODevice::readData(char *data, qint64 maxSize) +qint64 BZip2IODevice::readData(char* data, qint64 maxSize) { - return d->doDecompress(data, maxSize); + return d->doDecompress(data, maxSize); } -qint64 BZip2IODevice::writeData(const char *data, qint64 maxSize) +qint64 BZip2IODevice::writeData(const char* data, qint64 maxSize) { - return d->doCompress(data, maxSize); + return d->doCompress(data, maxSize); } diff --git a/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_compress.cpp b/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_compress.cpp old mode 100755 new mode 100644 index 9ed48ee2d..eb7649eb2 --- a/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_compress.cpp +++ b/qt6-after/qt6-migrated-legatus/Z/src/nglcompression/nglcomp_compress.cpp @@ -1,569 +1,529 @@ #include "nglcomp_compress.h" + #include "nglcomp_bzip2iodevice.h" #include "nglcomp_tarfilter.h" #include - #include -#include #include +#include #include #include #include #include #include +#include #include #include - - - - - - - - - - -#include - - - - - - - - - - - - namespace NGL { -Compress::Compress(QObject *parent) - : QObject(parent) - , m_u2_memFiles() - , m_aborted(0) +Compress::Compress(QObject* parent) + : QObject(parent), m_u2_memFiles(), m_aborted(0), + m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("nglcompress")) { - DEBUG_LOG(m_logger) << "c_tor"; + DEBUG_LOG(m_logger) << "c_tor"; - - - - - - - - - QTimer *t = new QTimer(this); - t->setInterval(1000); - connect(t, &QTimer::timeout, this, [](){qWarning() << "still alive ...";}); - t->start(); + QTimer* t = new QTimer(this); + t->setInterval(1000); + connect(t, &QTimer::timeout, this, []() { qWarning() << "still alive ..."; }); + t->start(); } Compress::~Compress() { - qWarning() << "## COMPRESS DTOR!!!!"; + qWarning() << "## COMPRESS DTOR!!!!"; - - DEBUG_LOG(m_logger) << "~"; + DEBUG_LOG(m_logger) << "~"; - abort(); - m_future.waitForFinished(); - DEBUG_LOG(m_logger) << "~ finished"; + abort(); + m_future.waitForFinished(); + DEBUG_LOG(m_logger) << "~ finished"; } void Compress::abort() { - DEBUG_LOG(m_logger) << "ABORT"; + DEBUG_LOG(m_logger) << "ABORT"; - m_aborted = 1; - m_lastError = tr("Aborted"); + m_aborted = 1; + m_lastError = tr("Aborted"); - if (m_currentTarFilter != nullptr) - { - DEBUG_LOG(m_logger) << "aborting tar"; - m_currentTarFilter->abort(); - } + if (m_currentTarFilter != nullptr) + { + DEBUG_LOG(m_logger) << "aborting tar"; + m_currentTarFilter->abort(); + } - if (m_currentBzipDevice != nullptr) - { - DEBUG_LOG(m_logger) << "aborting bzip"; - m_currentBzipDevice->abort(); - } + if (m_currentBzipDevice != nullptr) + { + DEBUG_LOG(m_logger) << "aborting bzip"; + m_currentBzipDevice->abort(); + } } -void Compress::compress(QIODevice *out, - const QString &filesRootDir, - const QVector &files, - const QVector &memFiles, - const QString &destRootDir) +void Compress::compress(QIODevice* out, const QString& filesRootDir, const QVector& files, + const QVector& memFiles, const QString& destRootDir) { - DEBUG_LOG(m_logger) << "compress #2"; - reset(); - setupFutureWatcher(QtConcurrent::run([this, out, filesRootDir, files, memFiles, destRootDir]() { - return this->_compress(out, filesRootDir, files, memFiles, destRootDir); - })); + DEBUG_LOG(m_logger) << "compress #2"; + reset(); + setupFutureWatcher(QtConcurrent::run([this, out, filesRootDir, files, memFiles, destRootDir]() { + return this->_compress(out, filesRootDir, files, memFiles, destRootDir); + })); } -void Compress::compress(QIODevice *out, const QString &sourceDir, const QString &destRootDir) +void Compress::compress(QIODevice* out, const QString& sourceDir, const QString& destRootDir) { - DEBUG_LOG(m_logger) << "compress #1 source dir: " << sourceDir << ", destRootDir: " << destRootDir; - reset(); + DEBUG_LOG(m_logger) << "compress #1 source dir: " << sourceDir << ", destRootDir: " << destRootDir; + reset(); - QVector inFiles = directoryFileList(sourceDir, true); + QVector inFiles = directoryFileList(sourceDir, true); - - int len = sourceDir.length(); - if (!sourceDir.endsWith(QLatin1Char('/'))) - len += 1; - for (auto &fi : inFiles) - { - fi.inputFileName = fi.inputFileName.mid(len); - fi.bAbsInputPath = false; - DEBUG_LOG(m_logger) << "fi: ifm = " << fi.inputFileName << ", abs = " << fi.bAbsInputPath; - } + int len = sourceDir.length(); + if (!sourceDir.endsWith(QLatin1Char('/'))) + len += 1; + for (auto& fi : inFiles) + { + fi.inputFileName = fi.inputFileName.mid(len); + fi.bAbsInputPath = false; + DEBUG_LOG(m_logger) << "fi: ifm = " << fi.inputFileName << ", abs = " << fi.bAbsInputPath; + } - DEBUG_LOG(m_logger) << "FI list size: " << inFiles.count(); + DEBUG_LOG(m_logger) << "FI list size: " << inFiles.count(); - compress(out, sourceDir, inFiles, {}, destRootDir); + compress(out, sourceDir, inFiles, {}, destRootDir); } -bool Compress::_compress(QIODevice *output, - const QString &filesRootDir, - const QVector &files, - const QVector &memFiles, - const QString &_destRootDir) +bool Compress::_compress(QIODevice* output, const QString& filesRootDir, const QVector& files, + const QVector& memFiles, const QString& _destRootDir) { - std::shared_ptr invalidatePointersOnScopeLeave(nullptr, [this](int *) - { - DEBUG_LOG(m_logger) << "invalidatePointersOnScopeLeave #1"; - m_currentTarFilter = nullptr; - m_currentBzipDevice = nullptr; - }); - (void)invalidatePointersOnScopeLeave; + std::shared_ptr invalidatePointersOnScopeLeave(nullptr, [this](int*) { + DEBUG_LOG(m_logger) << "invalidatePointersOnScopeLeave #1"; + m_currentTarFilter = nullptr; + m_currentBzipDevice = nullptr; + }); + (void)invalidatePointersOnScopeLeave; - - if (!output || !output->isWritable()) - { - m_lastError = tr("Device is not writeable"); - ERROR_LOG(m_logger) << "compress failed: " << m_lastError;; - - return false; - } - - const QString destRootDir = _destRootDir.endsWith(QLatin1Char('/')) ? - _destRootDir : _destRootDir + QLatin1Char('/'); - - const qint64 maxCount = files.count() + memFiles.count(); - qint64 count = 0; - - DEBUG_LOG(m_logger) << "destRootDir = " << destRootDir << ", maxCount = " << maxCount << ", count = " << count; - - BZip2IODevice bzip2(output, 9); - m_currentBzipDevice = &bzip2; - - if (!bzip2.open(QIODevice::WriteOnly)) - { - m_lastError = bzip2.errorString(); - ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - - return false; - } - - - - qint64 bytesTotal = 0; - for (const FileInformations &file : std::as_const(files)) - { - if (m_aborted) return false; - - const QString in = file.bAbsInputPath ? file.inputFileName : filesRootDir + QLatin1Char('/') + file.inputFileName; - const QFileInfo fi(in); - - bytesTotal += fi.size(); - } - - - qint64 currentFileSize = 0; - QString currentFileName; - auto readCallback = [this, &maxCount, &count, ¤tFileSize, ¤tFileName, &bytesTotal](const qint64 iSize) - { - DEBUG_LOG(m_logger) << "readCallback: maxCount = " << maxCount << ", count = " << count - << ", currentFileSize = " << currentFileSize << ", currentFileName = " << currentFileName << ", iSize = " << iSize; - emit compressInfoEx(maxCount, count, currentFileSize, (currentFileSize - iSize), currentFileName, bytesTotal); - }; - - - TarFilter tf(&bzip2, readCallback); - m_currentTarFilter = &tf; - const QStringList paths = destRootDir.split(QLatin1Char('/'), Qt::SkipEmptyParts); - QString curPath; - - - DEBUG_LOG(m_logger) << "prepairing tar filter"; - for (const QString &path : paths) - { - DEBUG_LOG(m_logger) << "path = " << path; - if (m_aborted) return false; - - if (curPath.isEmpty()) - curPath = path + QLatin1Char('/'); - else - curPath += path + QLatin1Char('/'); - - DEBUG_LOG(m_logger) << "curPath = " << curPath << ", filesRootDir.isEmpty() = " << filesRootDir.isEmpty(); - - if (filesRootDir.isEmpty()) + if (!output || !output->isWritable()) { - if (!tf.addData(curPath, QByteArray(), true)) - { - m_lastError = tf.lastError(); + m_lastError = tr("Device is not writeable"); ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - + ; + return false; - } } - else + + const QString destRootDir = + _destRootDir.endsWith(QLatin1Char('/')) ? _destRootDir : _destRootDir + QLatin1Char('/'); + + const qint64 maxCount = files.count() + memFiles.count(); + qint64 count = 0; + + DEBUG_LOG(m_logger) << "destRootDir = " << destRootDir << ", maxCount = " << maxCount << ", count = " << count; + + BZip2IODevice bzip2(output, 9); + m_currentBzipDevice = &bzip2; + + if (!bzip2.open(QIODevice::WriteOnly)) { - if (!tf.addFile(filesRootDir, curPath)) - { - m_lastError = tf.lastError(); + m_lastError = bzip2.errorString(); ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - + return false; - } } - } - m_c_sizeInfo.realSize = 0; - for (const FileInformations &file : std::as_const(files)) - { - DEBUG_LOG(m_logger) << "file = " << file.inputFileName; - emit compressInfo(maxCount, ++count, file.inputFileName); - - if (m_aborted) return false; - - QString in = file.bAbsInputPath ? file.inputFileName : filesRootDir + QLatin1Char('/') + file.inputFileName; - QString out = destRootDir + (file.outputFileName.isEmpty() ? file.inputFileName : file.outputFileName); - - DEBUG_LOG(m_logger) << "in = " << in << ", out = " << out; - - QFileInfo fi(in); - - currentFileName = fi.fileName(); - currentFileSize = fi.size(); - m_c_sizeInfo.realSize += currentFileSize; - - DEBUG_LOG(m_logger) << "currentFileName = " << currentFileName << ", currentFileSize = " << currentFileSize << "m_c_sizeInfo.realSize" << m_c_sizeInfo.realSize; - - if (!tf.addFile(in, out)) + qint64 bytesTotal = 0; + for (const FileInformations& file : std::as_const(files)) { - m_lastError = tf.lastError(); - ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - - return false; + if (m_aborted) + return false; + + const QString in = + file.bAbsInputPath ? file.inputFileName : filesRootDir + QLatin1Char('/') + file.inputFileName; + const QFileInfo fi(in); + + bytesTotal += fi.size(); } - } - for (const FileInformations &file : std::as_const(memFiles)) - { - DEBUG_LOG(m_logger) << "(mem) file = " << file.inputFileName; - emit compressInfo(maxCount, ++count, file.inputFileName); - - if (m_aborted) return false; + qint64 currentFileSize = 0; + QString currentFileName; + auto readCallback = [this, &maxCount, &count, ¤tFileSize, ¤tFileName, &bytesTotal](const qint64 iSize) { + DEBUG_LOG(m_logger) << "readCallback: maxCount = " << maxCount << ", count = " << count + << ", currentFileSize = " << currentFileSize << ", currentFileName = " << currentFileName + << ", iSize = " << iSize; + emit compressInfoEx(maxCount, count, currentFileSize, (currentFileSize - iSize), currentFileName, bytesTotal); + }; - currentFileName = file.inputFileName; - currentFileSize = file.fileData.size(); - m_c_sizeInfo.compressedSize += currentFileSize; + TarFilter tf(&bzip2, readCallback); + m_currentTarFilter = &tf; + const QStringList paths = destRootDir.split(QLatin1Char('/'), Qt::SkipEmptyParts); + QString curPath; - DEBUG_LOG(m_logger) << "(mem) currentFileName = " << currentFileName << ", currentFileSize = " << currentFileSize << "m_c_sizeInfo.realSize" << m_c_sizeInfo.realSize; - - if (!tf.addData(file.inputFileName, file.fileData)) + DEBUG_LOG(m_logger) << "prepairing tar filter"; + for (const QString& path : paths) { - m_lastError = tf.lastError(); - ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - - return false; + DEBUG_LOG(m_logger) << "path = " << path; + if (m_aborted) + return false; + + if (curPath.isEmpty()) + curPath = path + QLatin1Char('/'); + else + curPath += path + QLatin1Char('/'); + + DEBUG_LOG(m_logger) << "curPath = " << curPath << ", filesRootDir.isEmpty() = " << filesRootDir.isEmpty(); + + if (filesRootDir.isEmpty()) + { + if (!tf.addData(curPath, QByteArray(), true)) + { + m_lastError = tf.lastError(); + ERROR_LOG(m_logger) << "compress failed: " << m_lastError; + + return false; + } + } + else + { + if (!tf.addFile(filesRootDir, curPath)) + { + m_lastError = tf.lastError(); + ERROR_LOG(m_logger) << "compress failed: " << m_lastError; + + return false; + } + } } - } + m_c_sizeInfo.realSize = 0; + for (const FileInformations& file : std::as_const(files)) + { + DEBUG_LOG(m_logger) << "file = " << file.inputFileName; + emit compressInfo(maxCount, ++count, file.inputFileName); - DEBUG_LOG(m_logger) << "writing eos"; - tf.writeEOS(); + if (m_aborted) + return false; - DEBUG_LOG(m_logger) << "closing bzip"; - bzip2.close(); + QString in = file.bAbsInputPath ? file.inputFileName : filesRootDir + QLatin1Char('/') + file.inputFileName; + QString out = destRootDir + (file.outputFileName.isEmpty() ? file.inputFileName : file.outputFileName); - m_c_sizeInfo.compressedSize = output->size(); - DEBUG_LOG(m_logger) << "m_c_sizeInfo.compressedSize = " << m_c_sizeInfo.compressedSize; + DEBUG_LOG(m_logger) << "in = " << in << ", out = " << out; - m_success = true; + QFileInfo fi(in); - DEBUG_LOG(m_logger) << "DONE!"; + currentFileName = fi.fileName(); + currentFileSize = fi.size(); + m_c_sizeInfo.realSize += currentFileSize; - return true; + DEBUG_LOG(m_logger) << "currentFileName = " << currentFileName << ", currentFileSize = " << currentFileSize + << "m_c_sizeInfo.realSize" << m_c_sizeInfo.realSize; + + if (!tf.addFile(in, out)) + { + m_lastError = tf.lastError(); + ERROR_LOG(m_logger) << "compress failed: " << m_lastError; + + return false; + } + } + + for (const FileInformations& file : std::as_const(memFiles)) + { + DEBUG_LOG(m_logger) << "(mem) file = " << file.inputFileName; + emit compressInfo(maxCount, ++count, file.inputFileName); + + if (m_aborted) + return false; + + currentFileName = file.inputFileName; + currentFileSize = file.fileData.size(); + m_c_sizeInfo.compressedSize += currentFileSize; + + DEBUG_LOG(m_logger) << "(mem) currentFileName = " << currentFileName + << ", currentFileSize = " << currentFileSize << "m_c_sizeInfo.realSize" + << m_c_sizeInfo.realSize; + + if (!tf.addData(file.inputFileName, file.fileData)) + { + m_lastError = tf.lastError(); + ERROR_LOG(m_logger) << "compress failed: " << m_lastError; + + return false; + } + } + + DEBUG_LOG(m_logger) << "writing eos"; + tf.writeEOS(); + + DEBUG_LOG(m_logger) << "closing bzip"; + bzip2.close(); + + m_c_sizeInfo.compressedSize = output->size(); + DEBUG_LOG(m_logger) << "m_c_sizeInfo.compressedSize = " << m_c_sizeInfo.compressedSize; + + m_success = true; + + DEBUG_LOG(m_logger) << "DONE!"; + + return true; } -void Compress::uncompress(QIODevice *in, const QString &outDir) +void Compress::uncompress(QIODevice* in, const QString& outDir) { - DEBUG_LOG(m_logger) << "uncompress #1"; - reset(); - setupFutureWatcher(QtConcurrent::run([this, in, outDir](){ return this->_uncompressDirectory(in, outDir); })); + DEBUG_LOG(m_logger) << "uncompress #1"; + reset(); + setupFutureWatcher(QtConcurrent::run([this, in, outDir]() { return this->_uncompressDirectory(in, outDir); })); } -bool Compress::_uncompressDirectory(QIODevice *input, const QString &outDir) +bool Compress::_uncompressDirectory(QIODevice* input, const QString& outDir) { - DEBUG_LOG(m_logger) << "_uncompressDirectory"; + DEBUG_LOG(m_logger) << "_uncompressDirectory"; - std::shared_ptr invalidatePointersOnScopeLeave(nullptr, [this](int *) - { - DEBUG_LOG(m_logger) << "invalidatePointersOnScopeLeave #2"; - m_currentTarFilter = nullptr; - m_currentBzipDevice = nullptr; - }); - (void)invalidatePointersOnScopeLeave; + std::shared_ptr invalidatePointersOnScopeLeave(nullptr, [this](int*) { + DEBUG_LOG(m_logger) << "invalidatePointersOnScopeLeave #2"; + m_currentTarFilter = nullptr; + m_currentBzipDevice = nullptr; + }); + (void)invalidatePointersOnScopeLeave; - - if (!input || !input->isReadable()) - { - m_lastError = tr("Device is not readable"); - ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - - return false; - } - - BZip2IODevice bzip2(input, 9); - m_currentBzipDevice = &bzip2; - if (!bzip2.open(QIODevice::ReadOnly)) - { - m_lastError = bzip2.errorString(); - ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - - return false; - } - - TarFilter tf(&bzip2); - m_currentTarFilter = &tf; - TarFilter::FileInformations tfi; - QDir dir(outDir); - - DEBUG_LOG(m_logger) << "dir = " << dir.path(); - - while (tf.getData(tfi)) - { - DEBUG_LOG(m_logger) << "tfi.fileName = " << tfi.fileName; - emit uncompressInfo(input->size(), input->pos(), tfi.fileName); - if (m_aborted) return false; - - QString path = outDir + QLatin1Char('/') + tfi.fileName; - DEBUG_LOG(m_logger) << "path = " << path; - if (tfi.fileType == TarFilter::directory) + if (!input || !input->isReadable()) { - DEBUG_LOG(m_logger) << "tfi.fileType == TarFilter::directory"; - if (!dir.exists(path) && !dir.mkpath(path)) - { - m_lastError = tr("Error creating directory %1").arg(outDir); + m_lastError = tr("Device is not readable"); ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - - return false; - } - } - else - { - - QString pathName = QFileInfo(path).absolutePath(); - if (!dir.exists(pathName) && !dir.mkpath(pathName)) - { - m_lastError = tr("Error creating directory %1").arg(pathName); - ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - - return false; - } - QFile f(path); - if (!f.open(QIODevice::WriteOnly)) - { - m_lastError = tr("Error opening %1 for writing (%2)").arg(path, f.errorString()); - ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - - return false; - } - if (!tf.getData(&f)) - { - m_lastError = tf.lastError(); - ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - - return false; - } - } - } - DEBUG_LOG(m_logger) << "uncompress done!"; - m_success = true; - return true; + return false; + } + + BZip2IODevice bzip2(input, 9); + m_currentBzipDevice = &bzip2; + if (!bzip2.open(QIODevice::ReadOnly)) + { + m_lastError = bzip2.errorString(); + ERROR_LOG(m_logger) << "compress failed: " << m_lastError; + + return false; + } + + TarFilter tf(&bzip2); + m_currentTarFilter = &tf; + TarFilter::FileInformations tfi; + QDir dir(outDir); + + DEBUG_LOG(m_logger) << "dir = " << dir.path(); + + while (tf.getData(tfi)) + { + DEBUG_LOG(m_logger) << "tfi.fileName = " << tfi.fileName; + emit uncompressInfo(input->size(), input->pos(), tfi.fileName); + if (m_aborted) + return false; + + QString path = outDir + QLatin1Char('/') + tfi.fileName; + DEBUG_LOG(m_logger) << "path = " << path; + if (tfi.fileType == TarFilter::directory) + { + DEBUG_LOG(m_logger) << "tfi.fileType == TarFilter::directory"; + if (!dir.exists(path) && !dir.mkpath(path)) + { + m_lastError = tr("Error creating directory %1").arg(outDir); + ERROR_LOG(m_logger) << "compress failed: " << m_lastError; + + return false; + } + } + else + { + + QString pathName = QFileInfo(path).absolutePath(); + if (!dir.exists(pathName) && !dir.mkpath(pathName)) + { + m_lastError = tr("Error creating directory %1").arg(pathName); + ERROR_LOG(m_logger) << "compress failed: " << m_lastError; + + return false; + } + QFile f(path); + if (!f.open(QIODevice::WriteOnly)) + { + m_lastError = tr("Error opening %1 for writing (%2)").arg(path, f.errorString()); + ERROR_LOG(m_logger) << "compress failed: " << m_lastError; + + return false; + } + if (!tf.getData(&f)) + { + m_lastError = tf.lastError(); + ERROR_LOG(m_logger) << "compress failed: " << m_lastError; + + return false; + } + } + } + + DEBUG_LOG(m_logger) << "uncompress done!"; + m_success = true; + return true; } -void Compress::uncompress(QIODevice *in) +void Compress::uncompress(QIODevice* in) { - DEBUG_LOG(m_logger) << "uncompress #2!"; - reset(); - setupFutureWatcher(QtConcurrent::run([this, in](){ return this->_uncompressBuffer(in); })); + DEBUG_LOG(m_logger) << "uncompress #2!"; + reset(); + setupFutureWatcher(QtConcurrent::run([this, in]() { return this->_uncompressBuffer(in); })); } -bool Compress::_uncompressBuffer(QIODevice *input) +bool Compress::_uncompressBuffer(QIODevice* input) { - DEBUG_LOG(m_logger) << "uncompressBuffer"; + DEBUG_LOG(m_logger) << "uncompressBuffer"; - std::shared_ptr invalidatePointersOnScopeLeave(nullptr, [this](int *) - { - DEBUG_LOG(m_logger) << "invalidatePointersOnScopeLeave #2"; - m_currentTarFilter = nullptr; - m_currentBzipDevice = nullptr; - }); - (void)invalidatePointersOnScopeLeave; + std::shared_ptr invalidatePointersOnScopeLeave(nullptr, [this](int*) { + DEBUG_LOG(m_logger) << "invalidatePointersOnScopeLeave #2"; + m_currentTarFilter = nullptr; + m_currentBzipDevice = nullptr; + }); + (void)invalidatePointersOnScopeLeave; - - if (!input->isReadable()) - { - m_lastError = tr("Device is not readable"); - ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - - return false; - } - - BZip2IODevice bzip2(input, 9); - m_currentBzipDevice = &bzip2; - if (!bzip2.open(QIODevice::ReadOnly)) - { - m_lastError = bzip2.errorString(); - ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - - return false; - } - - TarFilter tf(&bzip2); - m_currentTarFilter = &tf; - TarFilter::FileInformations tfi; - while (tf.getData(tfi)) - { - DEBUG_LOG(m_logger) << "tfi.fileName = " << tfi.fileName; - emit uncompressInfo(input->size(), input->pos(), tfi.fileName); - if (m_aborted) return false; - - FileInformations fi; - fi.outputFileName = tfi.fileName; - - DEBUG_LOG(m_logger) << "fi.outputFileName = " << fi.outputFileName; - - if (tfi.fileType == TarFilter::directory) + if (!input->isReadable()) { - fi.outputFileName += QLatin1Char('/'); - DEBUG_LOG(m_logger) << "> fi.outputFileName = " << fi.outputFileName; - } - else - { - DEBUG_LOG(m_logger) << "stuff"; + m_lastError = tr("Device is not readable"); + ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - QBuffer buf(&fi.fileData); - if (!buf.open(QIODevice::WriteOnly)) - { - m_lastError = tr("Error opening buffer for writing (%1)").arg(buf.errorString()); - ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - return false; - } - if (!tf.getData(&buf)) - { - m_lastError = tf.lastError(); - ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - - return false; - } } - fi.bAbsInputPath = fi.outputFileName.startsWith(QLatin1Char('/')); - DEBUG_LOG(m_logger) << "added fi.bAbsInputPath = " << fi.bAbsInputPath; - m_u2_memFiles += fi; - } + BZip2IODevice bzip2(input, 9); + m_currentBzipDevice = &bzip2; + if (!bzip2.open(QIODevice::ReadOnly)) + { + m_lastError = bzip2.errorString(); + ERROR_LOG(m_logger) << "compress failed: " << m_lastError; - m_success = true; - return true; + return false; + } + + TarFilter tf(&bzip2); + m_currentTarFilter = &tf; + TarFilter::FileInformations tfi; + while (tf.getData(tfi)) + { + DEBUG_LOG(m_logger) << "tfi.fileName = " << tfi.fileName; + emit uncompressInfo(input->size(), input->pos(), tfi.fileName); + if (m_aborted) + return false; + + FileInformations fi; + fi.outputFileName = tfi.fileName; + + DEBUG_LOG(m_logger) << "fi.outputFileName = " << fi.outputFileName; + + if (tfi.fileType == TarFilter::directory) + { + fi.outputFileName += QLatin1Char('/'); + DEBUG_LOG(m_logger) << "> fi.outputFileName = " << fi.outputFileName; + } + else + { + DEBUG_LOG(m_logger) << "stuff"; + + QBuffer buf(&fi.fileData); + if (!buf.open(QIODevice::WriteOnly)) + { + m_lastError = tr("Error opening buffer for writing (%1)").arg(buf.errorString()); + ERROR_LOG(m_logger) << "compress failed: " << m_lastError; + + return false; + } + if (!tf.getData(&buf)) + { + m_lastError = tf.lastError(); + ERROR_LOG(m_logger) << "compress failed: " << m_lastError; + + return false; + } + } + + fi.bAbsInputPath = fi.outputFileName.startsWith(QLatin1Char('/')); + DEBUG_LOG(m_logger) << "added fi.bAbsInputPath = " << fi.bAbsInputPath; + m_u2_memFiles += fi; + } + + m_success = true; + return true; } bool Compress::success() const { - - ERROR_LOG(m_logger) << "success? " << (m_future.isFinished() && !m_future.isCanceled() && m_success); - ERROR_LOG(m_logger) << "success details: " - << "success m_future.isFinished() = " << (m_future.isFinished()) - << " !m_future.isCanceled() = " << !m_future.isCanceled() - << " m_success = " << m_success; - return (m_future.isFinished() && !m_future.isCanceled() && m_success); + + ERROR_LOG(m_logger) << "success? " << (m_future.isFinished() && !m_future.isCanceled() && m_success); + ERROR_LOG(m_logger) << "success details: " + << "success m_future.isFinished() = " << (m_future.isFinished()) + << " !m_future.isCanceled() = " << !m_future.isCanceled() << " m_success = " << m_success; + return (m_future.isFinished() && !m_future.isCanceled() && m_success); } bool Compress::waitForFinished() { - DEBUG_LOG(m_logger) << "waitForFinished..."; - m_future.waitForFinished(); - DEBUG_LOG(m_logger) << "waitForFinished... done!"; - return success(); + DEBUG_LOG(m_logger) << "waitForFinished..."; + m_future.waitForFinished(); + DEBUG_LOG(m_logger) << "waitForFinished... done!"; + return success(); } -QVector Compress::directoryFileList(const QString &dir, bool recursive) +QVector Compress::directoryFileList(const QString& dir, bool recursive) { - DEBUG_LOG(m_logger) << "directoryFileList"; + DEBUG_LOG(m_logger) << "directoryFileList"; - QVector sl_absolute; - QDir d(dir); + QVector sl_absolute; + QDir d(dir); - if (d.exists()) - { - DEBUG_LOG(m_logger) << "exists"; - const auto entries = d.entryList(QDir::Files); - sl_absolute.reserve(sl_absolute.size() + entries.size()); - for (const QString &entry : entries) - sl_absolute << FileInformations(QFileInfo(d, entry).absoluteFilePath(), true); - } + if (d.exists()) + { + DEBUG_LOG(m_logger) << "exists"; + const auto entries = d.entryList(QDir::Files); + sl_absolute.reserve(sl_absolute.size() + entries.size()); + for (const QString& entry : entries) + sl_absolute << FileInformations(QFileInfo(d, entry).absoluteFilePath(), true); + } - if (recursive) - { - DEBUG_LOG(m_logger) << "recursive"; - const auto entries = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot); - sl_absolute.reserve(sl_absolute.size() + entries.size()); - for (const QString &s : entries) - sl_absolute << directoryFileList(dir + QLatin1Char('/') + s, true); - } + if (recursive) + { + DEBUG_LOG(m_logger) << "recursive"; + const auto entries = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot); + sl_absolute.reserve(sl_absolute.size() + entries.size()); + for (const QString& s : entries) + sl_absolute << directoryFileList(dir + QLatin1Char('/') + s, true); + } - DEBUG_LOG(m_logger) << "done"; - return sl_absolute; + DEBUG_LOG(m_logger) << "done"; + return sl_absolute; } void Compress::reset() { - DEBUG_LOG(m_logger) << "reset"; - m_u2_memFiles.clear(); + DEBUG_LOG(m_logger) << "reset"; + m_u2_memFiles.clear(); - m_lastError.clear(); + m_lastError.clear(); - m_c_sizeInfo.realSize = 0; - m_c_sizeInfo.compressedSize = 0; + m_c_sizeInfo.realSize = 0; + m_c_sizeInfo.compressedSize = 0; - m_success = false; + m_success = false; } -void Compress::setupFutureWatcher(const QFuture &future) +void Compress::setupFutureWatcher(const QFuture& future) { - DEBUG_LOG(m_logger) << "setupFutureWatcher"; - m_future = future; - QFutureWatcher *fw = new QFutureWatcher(this); - QObject::connect(fw, &QObject::destroyed, this, [this]() { DEBUG_LOG(m_logger) << "Future Watcher destroyed"; }); - QObject::connect(fw, &QFutureWatcher::finished, this, &Compress::finished); - QObject::connect(fw, &QFutureWatcher::finished, fw, &QObject::deleteLater); - QObject::connect(fw, &QFutureWatcher::finished, fw, [this]() { DEBUG_LOG(m_logger) << "Future Watcher about to be deleted"; }); - fw->setFuture(m_future); + DEBUG_LOG(m_logger) << "setupFutureWatcher"; + m_future = future; + QFutureWatcher* fw = new QFutureWatcher(this); + QObject::connect(fw, &QObject::destroyed, this, [this]() { DEBUG_LOG(m_logger) << "Future Watcher destroyed"; }); + QObject::connect(fw, &QFutureWatcher::finished, this, &Compress::finished); + QObject::connect(fw, &QFutureWatcher::finished, fw, &QObject::deleteLater); + QObject::connect(fw, &QFutureWatcher::finished, fw, + [this]() { DEBUG_LOG(m_logger) << "Future Watcher about to be deleted"; }); + fw->setFuture(m_future); } -} +} // namespace NGL diff --git a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_help.h b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_help.h old mode 100755 new mode 100644 index 0f31de93c..4c7812498 --- a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_help.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_help.h @@ -1,19 +1,16 @@ - #pragma once #include "commandinterface.h" -#include "sv_export.h" - - +#include "tcpserver_export.h" class TCPSERVER_EXPORT CBI_Help : public CommandInterface { - Q_OBJECT -public: - explicit CBI_Help(unsigned short port); + Q_OBJECT + public: + explicit CBI_Help(unsigned short port); - void handleCommandInternal(const QVector &args) override; - QString help() const override; + void handleCommandInternal(const QVector& args) override; + QString help() const override; }; diff --git a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_pingpong.h b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_pingpong.h old mode 100755 new mode 100644 index 10fa66549..f8a370368 --- a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_pingpong.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_pingpong.h @@ -1,19 +1,16 @@ - #pragma once #include "commandinterface.h" -#include "sv_export.h" - - +#include "tcpserver_export.h" class CBI_PingPong : public CommandInterface { - Q_OBJECT -public: - explicit CBI_PingPong(unsigned short port); + Q_OBJECT + public: + explicit CBI_PingPong(unsigned short port); - void handleCommandInternal(const QVector &args) override; - QString help() const override; + void handleCommandInternal(const QVector& args) override; + QString help() const override; }; diff --git a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_quit.h b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_quit.h old mode 100755 new mode 100644 index c3a460987..09733a861 --- a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_quit.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_quit.h @@ -1,19 +1,16 @@ - #pragma once #include "commandinterface.h" -#include "sv_export.h" - - +#include "tcpserver_export.h" class TCPSERVER_EXPORT CBI_Quit : public CommandInterface { - Q_OBJECT -public: - explicit CBI_Quit(unsigned short port); + Q_OBJECT + public: + explicit CBI_Quit(unsigned short port); - void handleCommandInternal(const QVector &args) override; - QString help() const override; + void handleCommandInternal(const QVector& args) override; + QString help() const override; }; diff --git a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_recvfile.h b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_recvfile.h old mode 100755 new mode 100644 index 1175dae4d..3a6d29a5d --- a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_recvfile.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_recvfile.h @@ -1,23 +1,25 @@ - #pragma once #include "commandinterface.h" -#include "sv_export.h" +#include "tcpserver_export.h" + #include #include class QIODevice; + class CBI_Recvfile : public CommandInterface { - Q_OBJECT -public: - explicit CBI_Recvfile(unsigned short port); + Q_OBJECT + public: + explicit CBI_Recvfile(unsigned short port); - void handleCommandInternal(const QVector &args) override; - QString help() const override; - void newPlainData() override; -protected: - QMap > m_wbMap; + void handleCommandInternal(const QVector& args) override; + QString help() const override; + void newPlainData() override; + + protected: + QMap> m_wbMap; }; diff --git a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_sendfile.h b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_sendfile.h old mode 100755 new mode 100644 index 6a137532e..bba7295d1 --- a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_sendfile.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_sendfile.h @@ -1,17 +1,16 @@ - #pragma once #include "commandinterface.h" -#include "sv_export.h" +#include "tcpserver_export.h" class CBI_Sendfile : public CommandInterface { - Q_OBJECT -public: - explicit CBI_Sendfile(unsigned short port); + Q_OBJECT + public: + explicit CBI_Sendfile(unsigned short port); - void handleCommandInternal(const QVector &args) override; - QString help() const override; + void handleCommandInternal(const QVector& args) override; + QString help() const override; }; diff --git a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_shutdown.h b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_shutdown.h old mode 100755 new mode 100644 index a00389fcd..4d4a12704 --- a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_shutdown.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/cbi_shutdown.h @@ -1,25 +1,22 @@ - #pragma once #include "commandinterface.h" -#include "sv_export.h" - - +#include "tcpserver_export.h" class TCPSERVER_EXPORT CBI_Shutdown : public CommandInterface { - Q_OBJECT -public: - explicit CBI_Shutdown(unsigned short port); + Q_OBJECT + public: + explicit CBI_Shutdown(unsigned short port); - void handleCommandInternal(const QVector &args) override; - QString help() const override; + void handleCommandInternal(const QVector& args) override; + QString help() const override; -Q_SIGNALS: - + Q_SIGNALS: - void shutdownRequest(); -private: + void shutdownRequest(); + + private: }; diff --git a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/commandinterface.h b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/commandinterface.h old mode 100755 new mode 100644 index 8c3d61be3..c0e7aeba6 --- a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/commandinterface.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/commandinterface.h @@ -1,158 +1,107 @@ - - #pragma once +#include "tcpserver_export.h" + #include #include #include -#include "sv_export.h" - class QAbstractSocket; class QByteArray; class WorkerBase; - class TCPSERVER_EXPORT CommandInterface : public QObject { - Q_OBJECT -public: - + Q_OBJECT + public: + explicit CommandInterface(unsigned short port, const QByteArray& command = QByteArray()); - explicit CommandInterface(unsigned short port, const QByteArray &command = QByteArray()); + virtual ~CommandInterface(); - + void handleCommand(const QVector& args); - virtual ~CommandInterface(); - + virtual void newPlainData(); - void handleCommand(const QVector &args); - + virtual QString help() const = 0; - virtual void newPlainData(); - + QByteArray command() const; - virtual QString help() const = 0; - + void setAutoWriteEOL(bool newAutoWriteEOL); - QByteArray command() const; + bool autoWriteEOL() const; - + bool errorOccured() const; - void setAutoWriteEOL(bool newAutoWriteEOL); + static void setDefaultSuccessMessage(const QString& msg); - + static void setDefaultErrorMessage(const QString& msg); - bool autoWriteEOL() const; + template static CommandInterface* factory(unsigned short port) + { + return new T(port); + } - + virtual void aboutToDestroy() {} - bool errorOccured() const; + protected: + virtual void handleCommandInternal(const QVector& args) = 0; - + void setWriteTimeout(int iMS); - static void setDefaultSuccessMessage(const QString &msg); + void writeData(const QByteArray& payload); - + void writeData(const char* payload); - static void setDefaultErrorMessage(const QString &msg); + void writeData(const QString& payload); - template - static CommandInterface *factory(unsigned short port) { return new T(port); } + void writeData(const QStringList& payload); - + void writeData(const QList& payload); - virtual void aboutToDestroy() {} -protected: - + void writeOk(const QString& additionalMsg = QString()); - virtual void handleCommandInternal(const QVector &args) = 0; - + void writeError(const QString& additionalMsg = QString()); - void setWriteTimeout(int iMS); - + void writeEOL(); - void writeData(const QByteArray &payload); - + QByteArray quote(const QByteArray& payload); - void writeData(const char *payload); - + QAbstractSocket* socket(); - void writeData(const QString &payload); - + void setSocket(QAbstractSocket* socket); - void writeData(const QStringList &payload); - + WorkerBase* workerBase(); - void writeData(const QList &payload); - + void setWorkerBase(WorkerBase* wb); - void writeOk(const QString &additionalMsg = QString()); - + void conversionError(const QByteArray& arg, const QByteArray& type); - void writeError(const QString &additionalMsg = QString()); - + bool getValue(const QByteArray& arg, bool& value); - void writeEOL(); - + bool getValue(const QByteArray& arg, long& value); - QByteArray quote(const QByteArray &payload); - + bool getValue(const QByteArray& arg, unsigned long& value); - QAbstractSocket *socket(); - + bool getValue(const QByteArray& arg, int& value); - void setSocket(QAbstractSocket *socket); - + bool getValue(const QByteArray& arg, unsigned int& value); - WorkerBase *workerBase(); - + bool getValue(const QByteArray& arg, float& value); - void setWorkerBase(WorkerBase *wb); - + bool getValue(const QByteArray& arg, double& value); - void conversionError(const QByteArray &arg, const QByteArray &type); - + unsigned short port() const; - bool getValue(const QByteArray &arg, bool &value); - + void closeConnection(); - bool getValue(const QByteArray &arg, long &value); - + bool socketIsOpen() const; - bool getValue(const QByteArray &arg, unsigned long &value); - + private: + friend class WorkerBase; - bool getValue(const QByteArray &arg, int &value); - + class Private; - bool getValue(const QByteArray &arg, unsigned int &value); - - - bool getValue(const QByteArray &arg, float &value); - - - bool getValue(const QByteArray &arg, double &value); - - - - unsigned short port() const; - - - - void closeConnection(); - - - - bool socketIsOpen() const; - -private: - friend class WorkerBase; - - class Private; - - - Private *const d; + Private* const d; }; diff --git a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/tcpserver.h b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/tcpserver.h old mode 100755 new mode 100644 index f151f26d5..a58043469 --- a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/tcpserver.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/tcpserver.h @@ -1,96 +1,64 @@ - - #pragma once -#include +#include "tcpserver_export.h" -#include "sv_export.h" +#include class WorkerInstance; class CommandInterface; - - class TCPSERVER_EXPORT TcpServer : public QTcpServer { - Q_OBJECT -public: - typedef QVector CommandInterfaceList; -public: - + Q_OBJECT + public: + typedef QVector CommandInterfaceList; - virtual ~TcpServer(); - + public: + virtual ~TcpServer(); - static TcpServer *instance(unsigned short port); + static TcpServer* instance(unsigned short port); - + bool listen(const QHostAddress& address = QHostAddress::Any); - bool listen(const QHostAddress &address = QHostAddress::Any); + void setUseWorkerThreads(bool bEnable); - + bool useWorkerThreads() const; - void setUseWorkerThreads(bool bEnable); + QVector workers() const; - + unsigned short getListenPort() const; - bool useWorkerThreads() const; + static bool registerCommand(unsigned short port, CommandInterface* (*factory)(unsigned short)); - + static bool unregisterCommand(unsigned short port, CommandInterface* (*factory)(unsigned short)); - QVector workers() const; + static CommandInterfaceList registeredCommands(unsigned short port); - + void setUserData(void* userData); - unsigned short getListenPort() const; + void* userData() const; - + Q_SIGNALS: - static bool registerCommand(unsigned short port, CommandInterface * (*factory)(unsigned short)); + void aboutToQuit(unsigned short port); - + public Q_SLOTS: - static bool unregisterCommand(unsigned short port, CommandInterface * (*factory)(unsigned short)); + void shutdownRequest(); - + void workerFinished(); - static CommandInterfaceList registeredCommands(unsigned short port); + protected: + void incomingConnection(qintptr socketDescriptor); - + private: + class Private; - void setUserData(void *userData); + Private* const d; - + explicit TcpServer(unsigned short port); - void *userData() const; - -Q_SIGNALS: - - - void aboutToQuit(unsigned short port); - -public Q_SLOTS: - - - void shutdownRequest(); - - - void workerFinished(); - -protected: - void incomingConnection(qintptr socketDescriptor); - -private: - class Private; - - - Private *const d; - - explicit TcpServer(unsigned short port); - - - - bool listen(const QHostAddress &address, quint16 port); + bool listen(const QHostAddress& address, quint16 port); }; diff --git a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/workerbase.h b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/workerbase.h old mode 100755 new mode 100644 index 6d4ed1272..e9132d4e0 --- a/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/workerbase.h +++ b/qt6-after/qt6-migrated-legatus/Z/src/tcpserver/workerbase.h @@ -1,128 +1,87 @@ - #pragma once +#include "tcpserver_export.h" + #include #include -#include #include - -#include "sv_export.h" +#include class QAbstractSocket; class CommandInterface; - - class TCPSERVER_EXPORT WorkerBase { -public: - typedef QMap< QByteArray, CommandInterface *> CommandMap; -public: - + public: + typedef QMap CommandMap; - WorkerBase(qintptr sd, unsigned short port); - + public: + WorkerBase(qintptr sd, unsigned short port); - virtual ~WorkerBase() = default; - + virtual ~WorkerBase() = default; - QAbstractSocket *connection(); + QAbstractSocket* connection(); - + const QAbstractSocket* connection() const; - const QAbstractSocket *connection() const; + void redirectDataHandling(bool bDoRedirect, CommandInterface* newDataHandler = nullptr); - + static QByteArray formatForDebug(const QByteArray& data); - void redirectDataHandling(bool bDoRedirect, CommandInterface *newDataHandler = nullptr); + static QByteArray formatForDebug(const QAbstractSocket* dev); - + CommandMap getCommands() const; - static QByteArray formatForDebug(const QByteArray &data); + protected: + void newDataInternal(); - + int initCommands(unsigned short port); - static QByteArray formatForDebug(const QAbstractSocket *dev); + void cleanupCommands(); - + qintptr m_socketDescriptor; - CommandMap getCommands() const; + QPointer m_connection; -protected: - + unsigned short m_port; - void newDataInternal(); - + QByteArray m_connString; - int initCommands(unsigned short port); + bool m_bRedirectIncomingData; - + CommandInterface* m_bRedirectDataHandler; - void cleanupCommands(); - - - - qintptr m_socketDescriptor; - - - QPointer m_connection; - - - unsigned short m_port; - - - QByteArray m_connString; - - - bool m_bRedirectIncomingData; - - - CommandInterface *m_bRedirectDataHandler; - - - - CommandMap m_registeredCommands; + CommandMap m_registeredCommands; }; - - class WorkerInstance final : public QObject, public WorkerBase { - Q_OBJECT -public: - WorkerInstance(qintptr sd, unsigned short port, QObject *parent = nullptr); - virtual ~WorkerInstance(); + Q_OBJECT + public: + WorkerInstance(qintptr sd, unsigned short port, QObject* parent = nullptr); + virtual ~WorkerInstance(); - + bool isRunning() const; - bool isRunning() const; - + bool isFinished() const; - bool isFinished() const; + public Q_SLOTS: -public Q_SLOTS: - + void quit(); - void quit(); + void doWork(); - + protected Q_SLOTS: - void doWork(); + void newData(); -protected Q_SLOTS: - + void connectionDisconnected(); - void newData(); - + Q_SIGNALS: + void finished(); - void connectionDisconnected(); - -Q_SIGNALS: - void finished(); - -private: - bool m_bFinished; + private: + bool m_bFinished; }; - diff --git a/qt6-after/qt6-migrated-legatus/cmake/MacroCodeGenIdl.cmake b/qt6-after/qt6-migrated-legatus/cmake/MacroCodeGenIdl.cmake index f6c100102..7f7c396a1 100755 --- a/qt6-after/qt6-migrated-legatus/cmake/MacroCodeGenIdl.cmake +++ b/qt6-after/qt6-migrated-legatus/cmake/MacroCodeGenIdl.cmake @@ -163,25 +163,31 @@ MACRO(INSTALL_SHARED_FILES srcList) ENDMACRO() MACRO(CODEGEN_SQL srcList xmlFile_in) - _GET_SERVICENAME( "${xmlFile_in}" svcNameOut ) - SET(out_dir_sql "${CMAKE_BINARY_DIR}/share/Lts/sql/") - SET(out_file_sql "${out_dir_sql}/${svcNameOut}.sql") - SET(action "SQL") - ADD_CUSTOM_COMMAND(OUTPUT ${out_file_sql} - COMMAND ${CMAKE_COMMAND} - ARGS -E make_directory ${out_dir_sql} - COMMAND ngl_codegen - ARGS -s ${xmlFile_in} - -a ${action} - -o ${out_dir_sql} - -i ${CMAKE_BINARY_DIR}/service_idl_files.txt - DEPENDS ngl_codegen ${xmlFile_in} - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} - ) - LIST(APPEND ${srcList} ${out_file_sql}) + IF(BUILD_GRANTLEE) + _GET_SERVICENAME( "${xmlFile_in}" svcNameOut ) + SET(out_dir_sql "${CMAKE_BINARY_DIR}/share/Lts/sql/") + SET(out_file_sql "${out_dir_sql}/${svcNameOut}.sql") + SET(action "SQL") + ADD_CUSTOM_COMMAND(OUTPUT ${out_file_sql} + COMMAND ${CMAKE_COMMAND} + ARGS -E make_directory ${out_dir_sql} + COMMAND ngl_codegen + ARGS -s ${xmlFile_in} + -a ${action} + -o ${out_dir_sql} + -i ${CMAKE_BINARY_DIR}/service_idl_files.txt + DEPENDS ngl_codegen ${xmlFile_in} + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} + ) + LIST(APPEND ${srcList} ${out_file_sql}) - - NGL_INSTALL(SV AAR FILES ${out_file_sql} DESTINATION share/Lts/sql) + + NGL_INSTALL(SV AAR FILES ${out_file_sql} DESTINATION share/Lts/sql) + ELSE() + # BUILD_GRANTLEE disabled: skip SQL generation + # SQL files will not be generated; modules may need pre-generated SQL files + MESSAGE(STATUS "BUILD_GRANTLEE disabled: skipping SQL generation for ${xmlFile_in}") + ENDIF() ENDMACRO() MACRO(CODEGEN_HANDLE_SVC_XML srcList xmlFile_in) diff --git a/qt6-after/qt6-migrated-legatus/include/NGLLogger/INGLLogger.h b/qt6-after/qt6-migrated-legatus/include/NGLLogger/INGLLogger.h old mode 100755 new mode 100644 index 981dcf1bb..dfe0c99a6 --- a/qt6-after/qt6-migrated-legatus/include/NGLLogger/INGLLogger.h +++ b/qt6-after/qt6-migrated-legatus/include/NGLLogger/INGLLogger.h @@ -1,59 +1,56 @@ /** - * Logger interface - * $Id$ - * $HeadURL$ - * $Author$ - */ + * Logger interface + * $Id$ + * $HeadURL$ + * $Author$ + */ #pragma once -#include -#include -#include +#include #include -#include #include #include -#include -#include "ngllogger_export.h" +#include +#include +#include +#include +#include namespace NGL { class INGLLogger; // keep in sync with log4qt/level.h -enum class LogLevel -{ - Undefined = 0, - Trace = 64, - Debug = 96, - Info = 128, - Warning = 150, - Error = 182, - Fatal = 214, +enum class LogLevel { + Undefined = 0, + Trace = 64, + Debug = 96, + Info = 128, + Warning = 150, + Error = 182, + Fatal = 214, }; class LogStreamHelper { -public: - inline LogStreamHelper(INGLLogger &logger, LogLevel level, const char *const file, int line, const char *const function) - : m_logger(logger) - , m_level(level) - , m_line(line) - , m_file(file) - , m_func(function) - {} - inline ~LogStreamHelper(); // after INGLLogger class definition + public: + inline LogStreamHelper(INGLLogger& logger, LogLevel level, const char* const file, int line, + const char* const function) + : m_logger(logger), m_level(level), m_line(line), m_file(file), m_func(function) + { + } - template - inline LogStreamHelper &operator<<(const T &val); + inline ~LogStreamHelper(); // after INGLLogger class definition -private: - std::ostringstream m_buffer; - NGL::INGLLogger &m_logger; - const LogLevel m_level; - const int m_line; - const char *const m_file; - const char *const m_func; + template inline LogStreamHelper& operator<<(const T& val); + + private: + std::ostringstream m_buffer; + NGL::INGLLogger& m_logger; + const LogLevel m_level; + const int m_line; + const char* const m_file; + const char* const m_func; }; // Interface class for source code logging. @@ -64,58 +61,64 @@ private: // information on logger-hierarchies, logging-levels, and configuration files. class INGLLogger { -public: - INGLLogger(const INGLLogger &) = delete; - INGLLogger &operator=(const INGLLogger &) = delete; - INGLLogger() = default; - virtual ~INGLLogger() = default; + public: + INGLLogger(const INGLLogger&) = delete; + INGLLogger& operator=(const INGLLogger&) = delete; + INGLLogger() = default; + virtual ~INGLLogger() = default; - using String = std::string; + using String = std::string; - // Creates an instance of an INGLLogger interface. The fullqualifiedname is - // a dottet sequence (i.e. "NGL.thisandthat.mylogger"). The same name will - // always return the same interface-instance. It is not required to create - // the parent nodes. - virtual INGLLogger &getNGLLogger(const char *fullqualifiedname) = 0; - virtual INGLLogger &getNGLLogger(const std::string &fullqualifiedname) = 0; + // Creates an instance of an INGLLogger interface. The fullqualifiedname is + // a dottet sequence (i.e. "NGL.thisandthat.mylogger"). The same name will + // always return the same interface-instance. It is not required to create + // the parent nodes. + virtual INGLLogger& getNGLLogger(const char* fullqualifiedname) = 0; + virtual INGLLogger& getNGLLogger(const std::string& fullqualifiedname) = 0; + // True if this level is enabled. + virtual bool isTraceEnabled() const = 0; + virtual bool isDebugEnabled() const = 0; + virtual bool isInfoEnabled() const = 0; + virtual bool isWarningEnabled() const = 0; + virtual bool isErrorEnabled() const = 0; + virtual bool isFatalEnabled() const = 0; + virtual bool isLevelEnabled(LogLevel level) const = 0; - // True if this level is enabled. - virtual bool isTraceEnabled() const = 0; - virtual bool isDebugEnabled() const = 0; - virtual bool isInfoEnabled() const = 0; - virtual bool isWarningEnabled() const = 0; - virtual bool isErrorEnabled() const = 0; - virtual bool isFatalEnabled() const = 0; - virtual bool isLevelEnabled(LogLevel level) const = 0; + // Submit a LOG message. + // Use __FILE__ and __NAME__ macros. + virtual void log(LogLevel level, const INGLLogger::String& message, const char* file = nullptr, int line = -1, + const char* function = nullptr) = 0; - // Submit a LOG message. - // Use __FILE__ and __NAME__ macros. - virtual void log(LogLevel level, const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0; + // Submit an TRACE message. + virtual void logTrace(const INGLLogger::String& message, const char* file = nullptr, int line = -1, + const char* function = nullptr) = 0; + // Submit an DEBUG message. + virtual void logDebug(const INGLLogger::String& message, const char* file = nullptr, int line = -1, + const char* function = nullptr) = 0; + // Submit an INFO message. + virtual void logInfo(const INGLLogger::String& message, const char* file = nullptr, int line = -1, + const char* function = nullptr) = 0; + // Submit a WARNING message. + virtual void logWarning(const INGLLogger::String& message, const char* file = nullptr, int line = -1, + const char* function = nullptr) = 0; + // Submit an ERROR message. + virtual void logError(const INGLLogger::String& message, const char* file = nullptr, int line = -1, + const char* function = nullptr) = 0; + // Submit a FATAL message. + virtual void logFatal(const INGLLogger::String& message, const char* file = nullptr, int line = -1, + const char* function = nullptr) = 0; - // Submit an TRACE message. - virtual void logTrace(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0; - // Submit an DEBUG message. - virtual void logDebug(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0; - // Submit an INFO message. - virtual void logInfo(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0; - // Submit a WARNING message. - virtual void logWarning(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0; - // Submit an ERROR message. - virtual void logError(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0; - // Submit a FATAL message. - virtual void logFatal(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0; + // Writes a startup message into the logfile + virtual void logStartup(const char* file, int line, const char* function = nullptr) = 0; + // Writes a shutdown message into the logfile + virtual void logShutdown(const char* file, int line, const char* function = nullptr) = 0; - // Writes a startup message into the logfile - virtual void logStartup(const char *file, int line, const char *function = nullptr) = 0; - // Writes a shutdown message into the logfile - virtual void logShutdown(const char *file, int line, const char *function = nullptr) = 0; + // Get this loggers fullqualified name. + virtual std::string getLoggerName() const = 0; - // Get this loggers fullqualified name. - virtual std::string getLoggerName() const = 0; - - virtual void setNoSpace(bool bNoSpace) = 0; - virtual bool noSpace() const = 0; + virtual void setNoSpace(bool bNoSpace) = 0; + virtual bool noSpace() const = 0; }; // @@ -123,112 +126,90 @@ public: // inline LogStreamHelper::~LogStreamHelper() { - m_logger.log(m_level, m_buffer.str(), m_file, m_line, m_func); + m_logger.log(m_level, m_buffer.str(), m_file, m_line, m_func); } -template -inline LogStreamHelper &LogStreamHelper::operator<<(const T &val) +template inline LogStreamHelper& LogStreamHelper::operator<<(const T& val) { - m_buffer << val; - if (!m_logger.noSpace()) - m_buffer << " "; - return *this; + m_buffer << val; + if (!m_logger.noSpace()) + m_buffer << " "; + return *this; } +} // namespace NGL -} //namespace NGL - -inline std::ostream &operator<<(std::ostream &stream, const QByteArray &str) +inline std::ostream& operator<<(std::ostream& stream, const QByteArray& str) { - stream << std::string(str.data(), str.size()); - return stream; + stream << std::string(str.data(), str.size()); + return stream; } // // operator to ease logging (at least via NglLogging) // -inline std::ostream &operator<<(std::ostream &stream, - const QPointF &value) +inline std::ostream& operator<<(std::ostream& stream, const QPointF& value) { - stream << "QPointF(" << QString::number(value.x(), 'f', 6).toStdString() << "#" << QString::number(value.y(), 'f', 6).toStdString() << ")"; - return stream; + stream << "QPointF(" << QString::number(value.x(), 'f', 6).toStdString() << "#" + << QString::number(value.y(), 'f', 6).toStdString() << ")"; + return stream; } //---------------------------------------------------------------------------- -inline std::ostream &operator<< (std::ostream &stream, - const QPoint &value) +inline std::ostream& operator<<(std::ostream& stream, const QPoint& value) { - stream << "QPoint(" << value.x() << "#" << value.y() << ")"; - return stream; + stream << "QPoint(" << value.x() << "#" << value.y() << ")"; + return stream; } -inline std::ostream &operator<< (std::ostream &stream, - const QSize &value) +inline std::ostream& operator<<(std::ostream& stream, const QSize& value) { - stream << "QSize(w=" << value.width() << ";h=" << value.height() << ")"; - return stream; -} -inline std::ostream &operator<< (std::ostream &stream, - const QSizeF &value) -{ - stream << "QSize(w=" - << QString::number(value.width(), 'f', 6).toStdString() << ";h=" - << QString::number(value.height(), 'f', 6).toStdString() - << ")"; - return stream; + stream << "QSize(w=" << value.width() << ";h=" << value.height() << ")"; + return stream; } - -inline std::ostream &operator<< (std::ostream &stream, - const QRect &value) +inline std::ostream& operator<<(std::ostream& stream, const QSizeF& value) { - stream << "QRect(center=" << value.center() - << " w=" << value.width() - << ";h=" << value.height() - << " bottomLeft=" << value.bottomLeft() - << " topRight=" << value.topRight() - << ")"; - return stream; + stream << "QSize(w=" << QString::number(value.width(), 'f', 6).toStdString() + << ";h=" << QString::number(value.height(), 'f', 6).toStdString() << ")"; + return stream; } -inline std::ostream &operator<< (std::ostream &stream, - const QRectF &value) +inline std::ostream& operator<<(std::ostream& stream, const QRect& value) { - stream << "QRectF(center=" << value.center() - << " w=" << QString::number(value.width(), 'f', 3).toStdString() - << ";h=" << QString::number(value.height(), 'f', 3).toStdString() - << " bottomLeft=" << value.bottomLeft() - << " topRight=" << value.topRight() - << ")"; - return stream; + stream << "QRect(center=" << value.center() << " w=" << value.width() << ";h=" << value.height() + << " bottomLeft=" << value.bottomLeft() << " topRight=" << value.topRight() << ")"; + return stream; } - - -inline std::ostream &operator<< (std::ostream &stream, - const QList &value) +inline std::ostream& operator<<(std::ostream& stream, const QRectF& value) { - stream << "QList(" << value.size() << "): "; - for (int i : value) - stream << i << ";"; - return stream; + stream << "QRectF(center=" << value.center() << " w=" << QString::number(value.width(), 'f', 3).toStdString() + << ";h=" << QString::number(value.height(), 'f', 3).toStdString() << " bottomLeft=" << value.bottomLeft() + << " topRight=" << value.topRight() << ")"; + return stream; } - -inline std::ostream &operator<< (std::ostream &stream, - const QList &value) +inline std::ostream& operator<<(std::ostream& stream, const QList& value) { - stream << "QList(" << value.size() << "): "; - for (const QPointF &item : value) - stream << item << ";"; - return stream; + stream << "QList(" << value.size() << "): "; + for (int i : value) + stream << i << ";"; + return stream; } - -inline std::ostream &operator<<(std::ostream &stream, const QString &str) +inline std::ostream& operator<<(std::ostream& stream, const QList& value) { - return stream << str.toUtf8(); + stream << "QList(" << value.size() << "): "; + for (const QPointF& item : value) + stream << item << ";"; + return stream; +} + +inline std::ostream& operator<<(std::ostream& stream, const QString& str) +{ + return stream << str.toUtf8(); } namespace NGL @@ -236,15 +217,12 @@ namespace NGL namespace NGLLoggerHelper { -NGLLOGGER_EXPORT void hexDumpHelper(NGL::INGLLogger &logger, - NGL::LogLevel level, - const void *a_data, +NGLLOGGER_EXPORT void hexDumpHelper(NGL::INGLLogger& logger, NGL::LogLevel level, const void* a_data, const unsigned int a_size); -inline void hexDumpHelper(NGL::INGLLogger &logger, - NGL::LogLevel level, - const QByteArray &data) + +inline void hexDumpHelper(NGL::INGLLogger& logger, NGL::LogLevel level, const QByteArray& data) { - return hexDumpHelper(logger, level, data.data(), data.size()); + return hexDumpHelper(logger, level, data.data(), data.size()); } } // namespace NGLLoggerHelper @@ -260,41 +238,46 @@ NGLLOGGER_EXPORT std::string getMemoryData(); #define LOGFUNCTION Q_FUNC_INFO // log this output every time, no matter what log level is enabled -#define NOTICE_LOG(logger) \ - NGL::LogStreamHelper(logger, NGL::LogLevel::Info, __FILE__,__LINE__, Q_FUNC_INFO) +#define NOTICE_LOG(logger) NGL::LogStreamHelper(logger, NGL::LogLevel::Info, __FILE__, __LINE__, Q_FUNC_INFO) #ifdef LTS_DEBUG -#define TRACE_LOG(logger) \ - for (bool log_level_enabled = (logger).isTraceEnabled(); log_level_enabled; log_level_enabled = false) \ - NGL::LogStreamHelper(logger, NGL::LogLevel::Trace, __FILE__,__LINE__, Q_FUNC_INFO) +#define TRACE_LOG(logger) \ + for (bool log_level_enabled = (logger).isTraceEnabled(); log_level_enabled; log_level_enabled = false) \ + NGL::LogStreamHelper(logger, NGL::LogLevel::Trace, __FILE__, __LINE__, Q_FUNC_INFO) #else -#define TRACE_LOG(logger) \ - for ( ; false; ) \ - NGL::LogStreamHelper(logger, NGL::LogLevel::Trace, __FILE__,__LINE__, Q_FUNC_INFO) +#define TRACE_LOG(logger) \ + for (; false;) \ + NGL::LogStreamHelper(logger, NGL::LogLevel::Trace, __FILE__, __LINE__, Q_FUNC_INFO) #endif -#define DEBUG_LOG(logger) \ - for (bool log_level_enabled = (logger).isDebugEnabled(); log_level_enabled; log_level_enabled = false) \ - NGL::LogStreamHelper(logger, NGL::LogLevel::Debug, __FILE__,__LINE__, Q_FUNC_INFO) +#define DEBUG_LOG(logger) \ + for (bool log_level_enabled = (logger).isDebugEnabled(); log_level_enabled; log_level_enabled = false) \ + NGL::LogStreamHelper(logger, NGL::LogLevel::Debug, __FILE__, __LINE__, Q_FUNC_INFO) -#define INFO_LOG(logger) \ - for (bool log_level_enabled = (logger).isInfoEnabled(); log_level_enabled; log_level_enabled = false) \ - NGL::LogStreamHelper(logger, NGL::LogLevel::Info, __FILE__,__LINE__, Q_FUNC_INFO) +#define INFO_LOG(logger) \ + for (bool log_level_enabled = (logger).isInfoEnabled(); log_level_enabled; log_level_enabled = false) \ + NGL::LogStreamHelper(logger, NGL::LogLevel::Info, __FILE__, __LINE__, Q_FUNC_INFO) -#define WARNING_LOG(logger) \ - for (bool log_level_enabled = (logger).isWarningEnabled(); log_level_enabled; log_level_enabled = false) \ - NGL::LogStreamHelper(logger, NGL::LogLevel::Warning, __FILE__,__LINE__, Q_FUNC_INFO) +#define WARNING_LOG(logger) \ + for (bool log_level_enabled = (logger).isWarningEnabled(); log_level_enabled; log_level_enabled = false) \ + NGL::LogStreamHelper(logger, NGL::LogLevel::Warning, __FILE__, __LINE__, Q_FUNC_INFO) -#define ERROR_LOG(logger) \ - for (bool log_level_enabled = (logger).isErrorEnabled(); log_level_enabled; log_level_enabled = false) \ - NGL::LogStreamHelper(logger, NGL::LogLevel::Error, __FILE__,__LINE__, Q_FUNC_INFO) +#define ERROR_LOG(logger) \ + for (bool log_level_enabled = (logger).isErrorEnabled(); log_level_enabled; log_level_enabled = false) \ + NGL::LogStreamHelper(logger, NGL::LogLevel::Error, __FILE__, __LINE__, Q_FUNC_INFO) -#define FATAL_LOG(logger) \ - for (bool log_level_enabled = (logger).isFatalEnabled(); log_level_enabled; log_level_enabled = false) \ - NGL::LogStreamHelper(logger, NGL::LogLevel::Fatal, __FILE__,__LINE__, Q_FUNC_INFO) +#define FATAL_LOG(logger) \ + for (bool log_level_enabled = (logger).isFatalEnabled(); log_level_enabled; log_level_enabled = false) \ + NGL::LogStreamHelper(logger, NGL::LogLevel::Fatal, __FILE__, __LINE__, Q_FUNC_INFO) -#define STARTUP_LOG(logger) { (logger).logStartup(__FILE__, __LINE__, Q_FUNC_INFO); } -#define SHUTDOWN_LOG(logger) { (logger).logShutdown(__FILE__, __LINE__, Q_FUNC_INFO); } +#define STARTUP_LOG(logger) \ + { \ + (logger).logStartup(__FILE__, __LINE__, Q_FUNC_INFO); \ + } +#define SHUTDOWN_LOG(logger) \ + { \ + (logger).logShutdown(__FILE__, __LINE__, Q_FUNC_INFO); \ + } //============================================================================== @@ -303,8 +286,10 @@ NGLLOGGER_EXPORT std::string getMemoryData(); // do something nasty // MEMORY_LOG() << " after something nasty"; -#define MEMORY_LOG() \ - for (bool log_level_enabled = (NGL::getMemoryLogger()).isInfoEnabled(); log_level_enabled; log_level_enabled = false) \ - NGL::LogStreamHelper(NGL::getMemoryLogger(), NGL::LogLevel::Info, __FILE__,__LINE__, Q_FUNC_INFO) << NGL::getMemoryData() +#define MEMORY_LOG() \ + for (bool log_level_enabled = (NGL::getMemoryLogger()).isInfoEnabled(); log_level_enabled; \ + log_level_enabled = false) \ + NGL::LogStreamHelper(NGL::getMemoryLogger(), NGL::LogLevel::Info, __FILE__, __LINE__, Q_FUNC_INFO) \ + << NGL::getMemoryData() //============================================================================== diff --git a/qt6-after/qt6-migrated-legatus/tests/CMakeLists.txt b/qt6-after/qt6-migrated-legatus/tests/CMakeLists.txt index 7764c6e0c..136ad1997 100644 --- a/qt6-after/qt6-migrated-legatus/tests/CMakeLists.txt +++ b/qt6-after/qt6-migrated-legatus/tests/CMakeLists.txt @@ -13,7 +13,7 @@ if(NOT TARGET GTest::gtest_main) FetchContent_Declare( googletest GIT_REPOSITORY https://github.com/google/googletest.git - GIT_TAG release-1.13.0 + GIT_TAG v1.13.0 ) # For Windows: Prevent overriding the parent project's compiler/linker settings set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) @@ -31,6 +31,7 @@ if(BUILD_TESTING) test_symbology_xml.cpp test_saa_telegrams.cpp test_rti_integration.cpp + test_ltswidgets_qt6.cpp ) # Check which files actually exist diff --git a/qt6-after/qt6-migrated-legatus/tests/test_ltswidgets_qt6.cpp b/qt6-after/qt6-migrated-legatus/tests/test_ltswidgets_qt6.cpp new file mode 100644 index 000000000..269878e3e --- /dev/null +++ b/qt6-after/qt6-migrated-legatus/tests/test_ltswidgets_qt6.cpp @@ -0,0 +1,224 @@ +/** + * @file test_ltswidgets_qt6.cpp + * @brief Tests für LtsWidgets Qt6-Migration + * + * Tests verify Qt6 API compatibility changes: + * 1. QRandomGenerator usage (replacing qrand()) + * 2. Signal/slot connections with Qt6 signatures + * 3. QWheelEvent angleDelta() usage + * 4. QStyleOption::initFrom() usage + */ + +#include +#include +#include +#include +#include +#include +#include + +// Ensure QApplication is initialized for widget tests +static bool appInitialized = false; +static void ensureAppInitialized() { + if (!appInitialized) { + static int argc = 1; + static char* argv[] = { (char*)"test_ltswidgets_qt6", nullptr }; + static QApplication app(argc, argv); + appInitialized = true; + } +} + +// Test 1: QRandomGenerator bounded generation (used in lts_tab_widget.cpp) +TEST(LtsWidgetsQt6, QRandomGeneratorBounded) { + auto* generator = QRandomGenerator::global(); + ASSERT_NE(generator, nullptr); + + // Test multiple bounded calls to ensure stability + for (int i = 0; i < 100; ++i) { + int value = generator->bounded(10); + EXPECT_GE(value, 0); + EXPECT_LT(value, 10); + } +} + +// Test 2: QRandomGenerator produces different values +TEST(LtsWidgetsQt6, QRandomGeneratorVariation) { + auto* generator = QRandomGenerator::global(); + + QVector values; + for (int i = 0; i < 50; ++i) { + values.append(generator->bounded(1000)); + } + + // Check that we get some variation (not all same value) + bool hasDifferent = false; + for (int i = 1; i < values.size(); ++i) { + if (values[i] != values[0]) { + hasDifferent = true; + break; + } + } + EXPECT_TRUE(hasDifferent); +} + +// Test 3: QRandomGenerator seeded reproducibility +TEST(LtsWidgetsQt6, QRandomGeneratorSeeded) { + QRandomGenerator gen1(12345); + QRandomGenerator gen2(12345); + + // Same seed should produce same sequence + for (int i = 0; i < 10; ++i) { + EXPECT_EQ(gen1.bounded(1000), gen2.bounded(1000)); + } +} + +// Test 4: QComboBox currentTextChanged signal (Qt6 compatible) +// This tests the signal used in lts_text_editor.cpp +TEST(LtsWidgetsQt6, QComboBoxCurrentTextChangedSignal) { + ensureAppInitialized(); + + QComboBox comboBox; + comboBox.addItem("Option1"); + comboBox.addItem("Option2"); + comboBox.addItem("Option3"); + + bool signalReceived = false; + QString receivedText; + + QObject::connect(&comboBox, &QComboBox::currentTextChanged, + [&signalReceived, &receivedText](const QString& text) { + signalReceived = true; + receivedText = text; + }); + + comboBox.setCurrentIndex(1); + + EXPECT_TRUE(signalReceived); + EXPECT_EQ(receivedText, "Option2"); +} + +// Test 5: QComboBox activated signal with int parameter (Qt6) +// Note: activated signal is only emitted on user interaction, not on setCurrentIndex +TEST(LtsWidgetsQt6, QComboBoxActivatedIntSignal) { + ensureAppInitialized(); + + QComboBox comboBox; + comboBox.addItem("First"); + comboBox.addItem("Second"); + comboBox.addItem("Third"); + + bool signalReceived = false; + int receivedIndex = -1; + + // Connect using Qt6 syntax - activated emits int index + QObject::connect(&comboBox, QOverload::of(&QComboBox::activated), + [&signalReceived, &receivedIndex](int index) { + signalReceived = true; + receivedIndex = index; + }); + + // Simulate user interaction by emitting the signal manually + // (setCurrentIndex does not trigger activated signal) + QMetaObject::invokeMethod(&comboBox, "activated", Qt::QueuedConnection, Q_ARG(int, 2)); + QCoreApplication::processEvents(); + + // Verify the connection works with int parameter + EXPECT_TRUE(signalReceived); + EXPECT_EQ(receivedIndex, 2); +} + +// Test 6: QStyleOption::initFrom() (Qt6 replacement for init()) +// This tests the API used in lts_notification_box.cpp +TEST(LtsWidgetsQt6, QStyleOptionInitFrom) { + ensureAppInitialized(); + + QPushButton button("Test"); + button.resize(100, 30); + button.setEnabled(true); + + QStyleOption opt; + opt.initFrom(&button); + + // Verify initFrom sets up the option correctly + // State_Enabled should be set (among other states) + EXPECT_TRUE(opt.state & QStyle::State_Enabled); + EXPECT_FALSE(opt.rect.isNull()); +} + +// Test 7: QStyleOption multiple widgets +TEST(LtsWidgetsQt6, QStyleOptionInitFromMultipleWidgets) { + ensureAppInitialized(); + + QPushButton button1("Btn1"); + QPushButton button2("Btn2"); + button1.setEnabled(true); + button2.setEnabled(false); + + QStyleOption opt1; + opt1.initFrom(&button1); + + QStyleOption opt2; + opt2.initFrom(&button2); + + // Verify different widget states are captured + EXPECT_TRUE(opt1.state & QStyle::State_Enabled); + EXPECT_FALSE(opt2.state & QStyle::State_Enabled); +} + +// Test 8: QWheelEvent angleDelta() availability +// This verifies the API used in lts_date_time_edit_p.cpp +TEST(LtsWidgetsQt6, QWheelEventAngleDelta) { + ensureAppInitialized(); + + QPoint pos(100, 100); + QPoint globalPos(200, 200); + QPoint pixelDelta(0, 0); + QPoint angleDelta(0, 120); // Standard wheel step + + QWheelEvent wheelEvent(pos, globalPos, pixelDelta, angleDelta, + Qt::NoButton, Qt::NoModifier, + Qt::NoScrollPhase, false); + + // Verify angleDelta() is accessible and returns correct value + QPoint delta = wheelEvent.angleDelta(); + EXPECT_EQ(delta.y(), 120); + EXPECT_EQ(delta.x(), 0); +} + +// Test 9: QWheelEvent negative angleDelta +TEST(LtsWidgetsQt6, QWheelEventNegativeAngleDelta) { + ensureAppInitialized(); + + QPoint pos(100, 100); + QPoint globalPos(200, 200); + QPoint pixelDelta(0, 0); + QPoint angleDelta(0, -120); // Scroll down + + QWheelEvent wheelEvent(pos, globalPos, pixelDelta, angleDelta, + Qt::NoButton, Qt::NoModifier, + Qt::NoScrollPhase, false); + + QPoint delta = wheelEvent.angleDelta(); + EXPECT_EQ(delta.y(), -120); + + // Test the logic used in lts_date_time_edit_p.cpp + bool isUp = delta.y() > 0; + EXPECT_FALSE(isUp); +} + +// Test 10: QWheelEvent angleDelta direction detection +TEST(LtsWidgetsQt6, QWheelEventDirectionDetection) { + ensureAppInitialized(); + + // Simulate wheel up (positive delta) + QPoint angleDeltaUp(0, 120); + QWheelEvent wheelUp(QPoint(0, 0), QPoint(0, 0), QPoint(0, 0), angleDeltaUp, + Qt::NoButton, Qt::NoModifier, Qt::NoScrollPhase, false); + EXPECT_TRUE(wheelUp.angleDelta().y() > 0); + + // Simulate wheel down (negative delta) + QPoint angleDeltaDown(0, -120); + QWheelEvent wheelDown(QPoint(0, 0), QPoint(0, 0), QPoint(0, 0), angleDeltaDown, + Qt::NoButton, Qt::NoModifier, Qt::NoScrollPhase, false); + EXPECT_FALSE(wheelDown.angleDelta().y() > 0); +} \ No newline at end of file