Qt6 migration: LtsWidgets API fixes, LtsWebSocket logger init, RTI Docker install

- LtsWidgets: Fixed Qt6 API compatibility issues
  - QWheelEvent::delta() → angleDelta().y()
  - QStyleOption::init() → initFrom()
  - QComboBox activated signal signature change
  - QTextCodec removal (UTF-8 default in Qt6)
  - Missing widget includes added

- LtsWebSocket: Fixed m_logger reference initialization
  - Added NGLLoggerBootstrap includes
  - Proper initialization in constructor initializer lists

- CMake: Added BUILD_LTSWEBSOCKET option for temporary exclusion

- Docker: RTI Connext permanent installation script added
  - ci/install-rti-in-docker.sh for persistent RTI setup
  - Removes need for volume mounting RTI into container

- BUILD options: FilterManagement, RTI, Codification, Grantlee, LtsWebSocket
  can be disabled for partial builds during migration

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
torstenandCopilot committed 2026-08-19 14:04:26 +02:00
1 parent 3bb6e89496
commit bafed3705f
69 files changed
+2128 -3565

No files matched your search

+42 -1
View File
@@ -18,9 +18,50 @@ RUN apt-get update && \
qt6-base-dev \ qt6-base-dev \
qt6-base-dev-tools \ qt6-base-dev-tools \
qt6-tools-dev \ 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/* 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 # Set Qt platform for headless testing
ENV QT_QPA_PLATFORM=offscreen ENV QT_QPA_PLATFORM=offscreen
+36
View File
@@ -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"
+12 -17
View File
@@ -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_MSDL "Build MSDL module (requires Qt6 XmlPatterns)" OFF)
OPTION(BUILD_PLUGINS_SAAB "Build Saab 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_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) IF(WIN32)
SET(EXTERNAL_LIBRARY_DIR "C:/Development/Projekte/SituationMap/ExtFw" CACHE STRING "Library dir with all external dependencies") 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(CMAKE_AUTOUIC TRUE)
SET(QT_USE_IMPORTED_TARGETS 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. # 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. # Find Qt6 with all required components in one call to ensure all targets are properly created
# Prefer Qt6, fallback to Qt5. Create Qt6::* aliases only when the corresponding find_package(Qt6 6.8 COMPONENTS Concurrent Core Gui Location LinguistTools Network OpenGL PrintSupport
# Qt6:: component target exists. Avoid creating IMPORTED placeholder targets which Sensors Multimedia Sql Svg SerialPort Test UiTools WebSockets WebEngineCore WebEngineWidgets
# have no LOCATION and later inject 'NOTFOUND' into autogen timestamp deps. Widgets Xml XmlPatterns QUIET)
# Find minimal Qt6 Core first, then probe for other components (non-fatal).
find_package(Qt6 6.8 COMPONENTS Core QUIET)
if(Qt6_FOUND) if(Qt6_FOUND)
message(STATUS "Found Qt6: ${Qt6Core_VERSION}") 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 # Map version variable for compatibility if available
if(Qt6Core_VERSION) if(Qt6Core_VERSION)
set(Qt5Core_VERSION ${Qt6Core_VERSION} CACHE INTERNAL "Compatibility Qt5Core_VERSION mapped from Qt6") set(Qt5Core_VERSION ${Qt6Core_VERSION} CACHE INTERNAL "Compatibility Qt5Core_VERSION mapped from Qt6")
@@ -146,12 +141,12 @@ if(Qt6_FOUND)
endif() endif()
endif() endif()
else() else()
find_package(Qt6 5.9.0 COMPONENTS Concurrent Core Gui Location LinguistTools find_package(Qt6 5.9.0 COMPONENTS Concurrent Core Gui LinguistTools
Network OpenGL PrintSupport Sensors Multimedia Network OpenGL PrintSupport Multimedia
Sql Svg SerialPort Test UiTools WebSockets Sql Svg SerialPort Test UiTools WebSockets
WebEngineCore WebEngineWidgets Widgets Widgets Xml
Xml XmlPatterns
REQUIRED) REQUIRED)
find_package(Qt6 COMPONENTS Location Sensors WebEngineCore WebEngineWidgets XmlPatterns OPTIONAL)
MESSAGE(STATUS "Qt version is ${Qt6Core_VERSION}") MESSAGE(STATUS "Qt version is ${Qt6Core_VERSION}")
endif() endif()
@@ -36,7 +36,9 @@ ADD_SUBDIRECTORY(LtsTimeline)
ADD_SUBDIRECTORY(LtsPrinting) ADD_SUBDIRECTORY(LtsPrinting)
ADD_SUBDIRECTORY(LtsSerialPortQuerry) ADD_SUBDIRECTORY(LtsSerialPortQuerry)
ADD_SUBDIRECTORY(LtsScriptTimeline) ADD_SUBDIRECTORY(LtsScriptTimeline)
IF(BUILD_LTSWEBSOCKET)
ADD_SUBDIRECTORY(LtsWebSocket) ADD_SUBDIRECTORY(LtsWebSocket)
ENDIF()
ADD_SUBDIRECTORY(LtsProjectionWorkstation) ADD_SUBDIRECTORY(LtsProjectionWorkstation)
ADD_SUBDIRECTORY(LtsVirtualKeyboard) ADD_SUBDIRECTORY(LtsVirtualKeyboard)
ADD_SUBDIRECTORY(PluginInterfaces) ADD_SUBDIRECTORY(PluginInterfaces)
@@ -5,7 +5,11 @@
# #
FIND_PACKAGE(RTI) FIND_PACKAGE(RTI)
# Grantlee5 is Qt5-based and optional for Qt6 migration
IF(BUILD_GRANTLEE)
FIND_PACKAGE(Grantlee5 REQUIRED COMPONENTS Templates) FIND_PACKAGE(Grantlee5 REQUIRED COMPONENTS Templates)
ENDIF()
NGL_ADD_LIBRARY2(ALL codegen_base SHARED NGL_ADD_LIBRARY2(ALL codegen_base SHARED
codegen_export.h codegen_export.h
@@ -45,7 +49,8 @@ else()
endif() endif()
NGL_INSTALL_TARGET(codegen_base) 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 NGL_ADD_LIBRARY(ALL codegen_grantlee STATIC
CppTopicGeneratorGrantlee.cpp CppTopicGeneratorGrantlee.cpp
CppTopicGeneratorGrantlee.h CppTopicGeneratorGrantlee.h
@@ -111,12 +116,8 @@ if (TARGET Grantlee5::Templates)
PUBLIC PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/../ ${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 # Smoke-test: parse all .grantlee templates in this directory to detect parse/render regressions
if (TARGET Grantlee5::Templates)
find_package(Qt6 COMPONENTS Core QUIET) find_package(Qt6 COMPONENTS Core QUIET)
if (Qt6_FOUND) if (Qt6_FOUND)
set(QTCORE_TARGET Qt6::Core) set(QTCORE_TARGET Qt6::Core)
@@ -128,7 +129,6 @@ if (TARGET Grantlee5::Templates)
add_executable(grantlee_parser_smoke tests/GrantleeParserSmoke.cpp) add_executable(grantlee_parser_smoke tests/GrantleeParserSmoke.cpp)
target_link_libraries(grantlee_parser_smoke PRIVATE Grantlee5::Templates ${QTCORE_TARGET}) target_link_libraries(grantlee_parser_smoke PRIVATE Grantlee5::Templates ${QTCORE_TARGET})
add_test(NAME GrantleeParserSmoke COMMAND grantlee_parser_smoke ${CMAKE_CURRENT_SOURCE_DIR}) add_test(NAME GrantleeParserSmoke COMMAND grantlee_parser_smoke ${CMAKE_CURRENT_SOURCE_DIR})
endif()
NGL_ADD_EXECUTABLE(ALL ngl_codegen NGL_ADD_EXECUTABLE(ALL ngl_codegen
main_grantlee.cpp main_grantlee.cpp
@@ -155,3 +155,6 @@ NGL_TARGET_LINK_LIBRARIES(codegen_gui
Qt6::Widgets Qt6::Widgets
Grantlee5::Templates Grantlee5::Templates
) )
ELSE()
message(STATUS "BUILD_GRANTLEE disabled or Grantlee not found; skipping codegen_grantlee, ngl_codegen, and codegen_gui targets")
ENDIF()
@@ -24,6 +24,7 @@ endif()
NGL_TARGET_INCLUDE_DIRECTORIES(LtsCoordTrans NGL_TARGET_INCLUDE_DIRECTORIES(LtsCoordTrans
PUBLIC PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/../ ${CMAKE_CURRENT_SOURCE_DIR}/../
${CMAKE_CURRENT_BINARY_DIR}
) )
SET(ltsCoordWidget_SRCS SET(ltsCoordWidget_SRCS
@@ -48,6 +49,7 @@ NGL_TARGET_INCLUDE_DIRECTORIES(ltsCoordWidget
PUBLIC PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/../ ${CMAKE_CURRENT_SOURCE_DIR}/../
${CMAKE_CURRENT_SOURCE_DIR}/../LtsUtils/LtsUtilsCore ${CMAKE_CURRENT_SOURCE_DIR}/../LtsUtils/LtsUtilsCore
${CMAKE_CURRENT_BINARY_DIR}
) )
IF(TARGET LtsCoordTrans) IF(TARGET LtsCoordTrans)
+8 -20
View File
@@ -1,10 +1,9 @@
#pragma once #pragma once
#include <QObject>
#include "sv_export.h"
#include <LtsCoordTrans/lts_coord_trans.h> #include <LtsCoordTrans/lts_coord_trans.h>
#include <LtsCoordTrans/ltscoordwidget_export.h>
#include <QObject>
#include <QWidget> #include <QWidget>
class QToolButton; class QToolButton;
@@ -12,31 +11,19 @@ class QToolButton;
namespace LtsCoordWidget namespace LtsCoordWidget
{ {
class LtsCoordInputWidgetHandler; class LtsCoordInputWidgetHandler;
class LTSCOORDWIDGET_EXPORT LtsCoordWidget : public QWidget class LTSCOORDWIDGET_EXPORT LtsCoordWidget : public QWidget
{ {
Q_OBJECT Q_OBJECT
public: public:
enum class DisplayType enum class DisplayType { MGRS5, MGRS7, UTM, WGS84, MGRS = DisplayType::MGRS5 };
{
MGRS5,
MGRS7,
UTM,
WGS84,
MGRS = DisplayType::MGRS5
};
Q_ENUM(DisplayType) Q_ENUM(DisplayType)
Q_PROPERTY(DisplayType displayType READ displayType WRITE setDisplayType) Q_PROPERTY(DisplayType displayType READ displayType WRITE setDisplayType)
Q_PROPERTY(bool withResetButton READ withResetButton WRITE setWithResetButton) Q_PROPERTY(bool withResetButton READ withResetButton WRITE setWithResetButton)
Q_PROPERTY(bool showToolTip READ showToolTip WRITE setShowToolTip) Q_PROPERTY(bool showToolTip READ showToolTip WRITE setShowToolTip)
Q_PROPERTY(bool mgrsSquareEditable READ mgrsSquareEditable WRITE setMgrsSquareEditable) 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); explicit LtsCoordWidget(DisplayType dt, QWidget* parent = nullptr);
@@ -48,7 +35,6 @@ public:
bool event(QEvent* event) override; bool event(QEvent* event) override;
public Q_SLOTS: public Q_SLOTS:
void setCoordinate(const QPointF& geoCoord, bool bUseAsDefaultValue = true); void setCoordinate(const QPointF& geoCoord, bool bUseAsDefaultValue = true);
void setCoordinate(double lon, double lat, bool bUseAsDefaultValue = true); void setCoordinate(double lon, double lat, bool bUseAsDefaultValue = true);
void setDisplayType(LtsCoordWidget::DisplayType dt); void setDisplayType(LtsCoordWidget::DisplayType dt);
@@ -62,11 +48,13 @@ public Q_SLOTS:
Q_SIGNALS: Q_SIGNALS:
void coordinateChanged(const QPointF& newGeoCoord); void coordinateChanged(const QPointF& newGeoCoord);
void invalidCoordinate(); void invalidCoordinate();
private: private:
void rebuildUi(); void rebuildUi();
void updateToolTip(); void updateToolTip();
private Q_SLOTS: private Q_SLOTS:
void onResetToDefaultCoordinate(); void onResetToDefaultCoordinate();
private: private:
bool m_bWithResetButton = false; bool m_bWithResetButton = false;
bool m_bShowToolTip = true; bool m_bShowToolTip = true;
@@ -76,4 +64,4 @@ private:
QPointF m_coordinate; QPointF m_coordinate;
QPointF m_defaultCoordinate; QPointF m_defaultCoordinate;
}; };
} } // namespace LtsCoordWidget
@@ -15,7 +15,7 @@ SET(SRCS
printing.h printing.h
) )
if (KDReports_FOUND AND BUILD_RTI) if (KDReports_FOUND AND BUILD_CODIFICATION)
NGL_ADD_LIBRARY2(WS LtsPrinting SHARED ${SRCS}) NGL_ADD_LIBRARY2(WS LtsPrinting SHARED ${SRCS})
NGL_TARGET_INCLUDE_DIRECTORIES(LtsPrinting NGL_TARGET_INCLUDE_DIRECTORIES(LtsPrinting
PUBLIC PUBLIC
@@ -13,6 +13,7 @@ NGL_ADD_LIBRARY2(ALL LtsUtilsSettings SHARED ${SRCS})
NGL_TARGET_INCLUDE_DIRECTORIES(LtsUtilsSettings NGL_TARGET_INCLUDE_DIRECTORIES(LtsUtilsSettings
PUBLIC PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/../ ${CMAKE_CURRENT_SOURCE_DIR}/../
${CMAKE_CURRENT_BINARY_DIR}
) )
NGL_TARGET_LINK_LIBRARIES(LtsUtilsSettings NGL_TARGET_LINK_LIBRARIES(LtsUtilsSettings
+7 -5
View File
@@ -2,14 +2,14 @@
#include "client_connection.h" #include "client_connection.h"
#include <NGLLogger/NGLLoggerBootstrap.h>
#include <QWebSocket> #include <QWebSocket>
namespace LtsWebSocket namespace LtsWebSocket
{ {
ClientConnection::ClientConnection(QWebSocket* socket, QObject* parent) ClientConnection::ClientConnection(QWebSocket* socket, QObject* parent)
: QThread(parent) : QThread(parent), m_logger(NGL::NGLLoggerBootstrap::getLogger()), m_socket(socket ? socket : new QWebSocket)
, m_socket(socket ? socket : new QWebSocket)
{ {
} }
@@ -29,7 +29,8 @@ bool ClientConnection::init()
} }
DEBUG_LOG(m_logger) << "Started new thread" << this; DEBUG_LOG(m_logger) << "Started new thread" << this;
connect(m_socket, &QWebSocket::textMessageReceived, this, &ClientConnection::onNewTextMessageFromSocket, Qt::DirectConnection); connect(m_socket, &QWebSocket::textMessageReceived, this, &ClientConnection::onNewTextMessageFromSocket,
Qt::DirectConnection);
connect(m_socket, &QWebSocket::connected, this, &ClientConnection::sendMessagesFromQueue); connect(m_socket, &QWebSocket::connected, this, &ClientConnection::sendMessagesFromQueue);
connect(m_socket, &QWebSocket::disconnected, this, &ClientConnection::onSocketDisconnect); connect(m_socket, &QWebSocket::disconnected, this, &ClientConnection::onSocketDisconnect);
@@ -75,9 +76,10 @@ void ClientConnection::sendMessagesFromQueue()
void ClientConnection::onSocketDisconnect() void ClientConnection::onSocketDisconnect()
{ {
DEBUG_LOG(m_logger) << "Client disconnected ip: " << m_socket->peerAddress().toString() << ":" << m_socket->peerPort(); DEBUG_LOG(m_logger) << "Client disconnected ip: " << m_socket->peerAddress().toString() << ":"
<< m_socket->peerPort();
exit(0); exit(0);
emit disconnected(this); emit disconnected(this);
} }
} } // namespace LtsWebSocket
+13 -31
View File
@@ -1,69 +1,51 @@
#pragma once #pragma once
#include <QObject>
#include <QtCore/QThread>
#include <QtCore/QQueue>
#include "reply_message.h"
#include "logger.h" #include "logger.h"
#include "ltswebsocketserver_export.h" #include "ltswebsocketserver_export.h"
#include "reply_message.h"
#include <QObject>
#include <QtCore/QQueue>
#include <QtCore/QThread>
class QWebSocket; class QWebSocket;
namespace LtsWebSocket namespace LtsWebSocket
{ {
class LTSWEBSOCKETSERVER_EXPORT ClientConnection : public QThread, public ReplyHandler
class LTSWEBSOCKETSERVER_EXPORT ClientConnection
: public QThread
, public ReplyHandler
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit ClientConnection(QWebSocket* socket, QObject* parent = nullptr); explicit ClientConnection(QWebSocket* socket, QObject* parent = nullptr);
~ClientConnection(); ~ClientConnection();
bool init(); bool init();
void addReply(ReplyMessage* message) override; void addReply(ReplyMessage* message) override;
QWebSocket *webSocket() { return m_socket; } QWebSocket* webSocket()
signals: {
return m_socket;
}
signals:
void newTextMessage(ClientConnection* client, const QString& message); void newTextMessage(ClientConnection* client, const QString& message);
void disconnected(ClientConnection* client); void disconnected(ClientConnection* client);
private slots: private slots:
void onNewTextMessageFromSocket(const QString& message); void onNewTextMessageFromSocket(const QString& message);
void sendMessagesFromQueue(); void sendMessagesFromQueue();
void onSocketDisconnect(); void onSocketDisconnect();
private: private:
NGL::INGLLogger& m_logger; NGL::INGLLogger& m_logger;
void sendMessages(); void sendMessages();
private:
NGL::INGLLogger &m_logger;
QWebSocket* m_socket; QWebSocket* m_socket;
QQueue<ReplyMessage*> m_messageQueue; QQueue<ReplyMessage*> m_messageQueue;
}; };
} } // namespace LtsWebSocket
+21 -22
View File
@@ -3,45 +3,38 @@
#pragma once #pragma once
#include "client_message.h" #include "client_message.h"
#include "reply_message.h"
#include "ltswebsocketcommon_export.h" #include "ltswebsocketcommon_export.h"
#include "reply_message.h"
#include <QString>
#include <QJsonParseError> #include <QJsonParseError>
#include <QString>
namespace NGL namespace NGL
{ {
class INGLLogger; class INGLLogger;
} }
namespace LtsWebSocket namespace LtsWebSocket
{ {
class LTSWEBSOCKETCOMMON_EXPORT AbstractClientMessageFactory class LTSWEBSOCKETCOMMON_EXPORT AbstractClientMessageFactory
{ {
public: public:
explicit AbstractClientMessageFactory(NGL::INGLLogger &logger) explicit AbstractClientMessageFactory(NGL::INGLLogger& logger) : m_logger(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; virtual AbstractClientMessage* createMessage(ReplyHandler* client, const QString& message) = 0;
protected: protected:
AbstractClientMessage *checkAttributes(ReplyHandler *client, AbstractClientMessage* checkAttributes(ReplyHandler* client, const QString& message) const;
const QString &message) const; AbstractClientMessage* checkResult(ReplyHandler* client, const QString& message,
AbstractClientMessage *checkResult(ReplyHandler *client,
const QString &message,
AbstractClientMessage* result) const; AbstractClientMessage* result) const;
protected: protected:
NGL::INGLLogger& m_logger;
QString m_type; QString m_type;
int m_typeId; int m_typeId;
QString m_uuid; QString m_uuid;
@@ -51,19 +44,25 @@ protected:
class PongMessage final : public ReplyMessage class PongMessage final : public ReplyMessage
{ {
public: public:
static QString strPong() { return QStringLiteral("pong"); } static QString strPong()
static int idPong() { return 2; } {
explicit PongMessage(const QString &payload) return QStringLiteral("pong");
: ReplyMessage(strPong(), idPong(), QString()) }
, m_payload(payload)
{} static int idPong()
{
return 2;
}
explicit PongMessage(const QString& payload) : ReplyMessage(strPong(), idPong(), QString()), m_payload(payload) {}
QString toJsonString() const override QString toJsonString() const override
{ {
return m_payload.isEmpty() ? strPong() : QStringLiteral("%1 %2").arg(strPong(), m_payload); return m_payload.isEmpty() ? strPong() : QStringLiteral("%1 %2").arg(strPong(), m_payload);
} }
private: private:
QString m_payload; QString m_payload;
}; };
} } // namespace LtsWebSocket
+10 -9
View File
@@ -1,17 +1,19 @@
#include "connection_handler.h" #include "connection_handler.h"
#include <utility>
#include "client_connection.h" #include "client_connection.h"
#include <NGLLogger/NGLLoggerBootstrap.h>
#include <QtWebSockets/QWebSocket> #include <QtWebSockets/QWebSocket>
#include <utility>
using namespace LtsWebSocket; using namespace LtsWebSocket;
ConnectionHandler::ConnectionHandler(QObject *parent) : QObject(parent) ConnectionHandler::ConnectionHandler(QObject* parent)
, m_server(nullptr), : QObject(parent), m_server(nullptr), m_logger(NGL::NGLLoggerBootstrap::getLogger())
m_logger(NGL::NGLLoggerBootstrap::getLogger()) {} {
}
ConnectionHandler::~ConnectionHandler() ConnectionHandler::~ConnectionHandler()
{ {
@@ -63,10 +65,8 @@ void ConnectionHandler::onNewConnection()
QWebSocket* socket = m_server->nextPendingConnection(); QWebSocket* socket = m_server->nextPendingConnection();
ClientConnection* newConnection = new ClientConnection(socket, this); ClientConnection* newConnection = new ClientConnection(socket, this);
connect(newConnection, &ClientConnection::destroyed, this, [this](QObject* o) connect(newConnection, &ClientConnection::destroyed, this,
{ [this](QObject* o) { m_connections.remove(static_cast<ClientConnection*>(o)); });
m_connections.remove(static_cast<ClientConnection*>(o));
});
if (!newConnection->init()) if (!newConnection->init())
{ {
@@ -83,6 +83,7 @@ void ConnectionHandler::onNewConnection()
m_connections.insert(newConnection); m_connections.insert(newConnection);
emit clientConnected(newConnection); emit clientConnected(newConnection);
INFO_LOG(m_logger) << "New client connected ip: " << socket->localAddress().toString() << ":" << socket->localPort(); INFO_LOG(m_logger) << "New client connected ip: " << socket->localAddress().toString() << ":"
<< socket->localPort();
} }
} }
@@ -172,6 +172,7 @@ NGL_TARGET_LINK_LIBRARIES(LtsWidgets
TabBarTabStyle TabBarTabStyle
LtsSessionData LtsSessionData
LtsUtilsSettings LtsUtilsSettings
NGLLogger
PUBLIC PUBLIC
LtsUtilsCore LtsUtilsCore
Qt6::Core Qt6::Core
@@ -2,25 +2,21 @@
#include "lts_abstract_sequence_widget.h" #include "lts_abstract_sequence_widget.h"
#include <QRegularExpression>
#include <QToolButton> #include <QToolButton>
namespace LtsWidgets namespace LtsWidgets
{ {
LtsAbstractSequenceWidget::LtsAbstractSequenceWidget(QWidget* parent, const bool& readOnly) LtsAbstractSequenceWidget::LtsAbstractSequenceWidget(QWidget* parent, const bool& readOnly)
: QGroupBox(parent) : QGroupBox(parent), m_readOnly(readOnly), m_pbAddMember(new QToolButton)
, 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) void LtsAbstractSequenceWidget::addWidget(QWidget* widget, bool isReadOnly, bool isButtonVisible)
{ {
@@ -29,12 +25,12 @@ void LtsAbstractSequenceWidget::addWidget(QWidget* widget, bool isReadOnly, bool
m_pbAddMember->setVisible(isButtonVisible); m_pbAddMember->setVisible(isButtonVisible);
} }
int LtsAbstractSequenceWidget::getMemberlistSize(){ int LtsAbstractSequenceWidget::getMemberlistSize()
{
return m_memberList.size(); return m_memberList.size();
} }
void LtsAbstractSequenceWidget::getValue(QWidget *data, void LtsAbstractSequenceWidget::getValue(QWidget* data, const QString& findObjectName) const
const QString &findObjectName) const
{ {
if (!findChild<QWidget*>(findObjectName)) if (!findChild<QWidget*>(findObjectName))
@@ -50,8 +46,7 @@ void LtsAbstractSequenceWidget::setMemberCount(int count)
{ {
child = findChild<QWidget*>(getObjectName(++count)); child = findChild<QWidget*>(getObjectName(++count));
delete child; delete child;
} } while (child);
while (child);
m_memberList.removeAll(nullptr); m_memberList.removeAll(nullptr);
} }
@@ -113,8 +108,8 @@ void LtsAbstractSequenceWidget::deleteMemberWidget(QObject *member)
QString childName = child->objectName(); QString childName = child->objectName();
QString newId = QString::number(i + 1); QString newId = QString::number(i + 1);
child->setObjectName(childName.replace(QRegExp(QLatin1String(".([0-9]*)")), newId)); child->setObjectName(childName.replace(QRegularExpression(QLatin1String("\\.([0-9]*)")), newId));
}
} }
} }
} }
} // namespace LtsWidgets
+8 -22
View File
@@ -1,23 +1,20 @@
#include "lts_background_widget.h" #include "lts_background_widget.h"
#include <QDebug>
#include <QFile>
#include <QPaintEvent> #include <QPaintEvent>
#include <QPainter> #include <QPainter>
#include <QDebug>
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
#include <QtPlatformHeaders/qwindowswindowfunctions.h> #include <QtPlatformHeaders/qwindowswindowfunctions.h>
#endif #endif
namespace LtsWidgets namespace LtsWidgets
{ {
LtsBackgroundWidget::LtsBackgroundWidget(QWidget *parent) LtsBackgroundWidget::LtsBackgroundWidget(QWidget* parent) : QDialog(parent), m_isUltraWide(false)
: QDialog(parent)
, m_isUltraWide(false)
{ {
setMouseTracking(true); setMouseTracking(true);
setWindowFlags(windowFlags() | Qt::FramelessWindowHint); setWindowFlags(windowFlags() | Qt::FramelessWindowHint);
@@ -26,16 +23,13 @@ LtsBackgroundWidget::LtsBackgroundWidget(QWidget *parent)
setBackground(); setBackground();
} }
void LtsBackgroundWidget::setBackground() void LtsBackgroundWidget::setBackground()
{ {
static const auto backgroundFiles = static const auto backgroundFiles = {
{
QStringLiteral(":/project/background.png"), QStringLiteral(":/project/background.png"),
QStringLiteral(":/project/background.jpg"), QStringLiteral(":/project/background.jpg"),
}; };
static const auto backgroundFilesWide = static const auto backgroundFilesWide = {
{
QStringLiteral(":/project/background_wide.png"), QStringLiteral(":/project/background_wide.png"),
QStringLiteral(":/project/background_wide.jpg"), QStringLiteral(":/project/background_wide.jpg"),
}; };
@@ -65,7 +59,6 @@ void LtsBackgroundWidget::setBackground()
} }
} }
void LtsBackgroundWidget::setUltraWide(bool set) void LtsBackgroundWidget::setUltraWide(bool set)
{ {
if (set == m_isUltraWide) if (set == m_isUltraWide)
@@ -76,14 +69,12 @@ void LtsBackgroundWidget::setUltraWide(bool set)
update(); update();
} }
void LtsBackgroundWidget::resizeEvent(QResizeEvent* e) void LtsBackgroundWidget::resizeEvent(QResizeEvent* e)
{ {
setUltraWide(width() > 3000); setUltraWide(width() > 3000);
QDialog::resizeEvent(e); QDialog::resizeEvent(e);
} }
void LtsBackgroundWidget::paintEvent(QPaintEvent* e) void LtsBackgroundWidget::paintEvent(QPaintEvent* e)
{ {
if (!m_pixmap.isNull()) if (!m_pixmap.isNull())
@@ -95,13 +86,10 @@ void LtsBackgroundWidget::paintEvent(QPaintEvent *e)
QDialog::paintEvent(e); QDialog::paintEvent(e);
} }
bool LtsBackgroundWidget::event(QEvent* e) bool LtsBackgroundWidget::event(QEvent* e)
{ {
if (e->type() == QEvent::KeyPress || if (e->type() == QEvent::KeyPress || e->type() == QEvent::MouseButtonPress ||
e->type() == QEvent::MouseButtonPress || e->type() == QEvent::MouseButtonRelease || e->type() == QEvent::MouseMove)
e->type() == QEvent::MouseButtonRelease ||
e->type() == QEvent::MouseMove)
{ {
emit signalOperatorAction(); emit signalOperatorAction();
@@ -112,7 +100,6 @@ bool LtsBackgroundWidget::event(QEvent *e)
return QDialog::event(e); return QDialog::event(e);
} }
void LtsBackgroundWidget::showFullScreen() void LtsBackgroundWidget::showFullScreen()
{ {
@@ -124,7 +111,6 @@ void LtsBackgroundWidget::showFullScreen()
raise(); raise();
} }
void LtsBackgroundWidget::closeEvent(QCloseEvent* e) void LtsBackgroundWidget::closeEvent(QCloseEvent* e)
{ {
#ifdef DEVEL #ifdef DEVEL
@@ -134,4 +120,4 @@ void LtsBackgroundWidget::closeEvent(QCloseEvent *e)
#endif #endif
} }
} } // namespace LtsWidgets
File diff suppressed because it is too large. Load diff
@@ -1,19 +1,17 @@
#pragma once #pragma once
#include <QObject>
#include "ltswidgets_export.h" #include "ltswidgets_export.h"
#include <LtsUtilsCore/variant_operators.h>
#include <LtsUtilsCore/variant_operators.h>
#include <QDataStream> #include <QDataStream>
#include <QIODevice>
#include <QIcon> #include <QIcon>
#include <QObject>
#include <QRegularExpression> #include <QRegularExpression>
#include <QSortFilterProxyModel> #include <QSortFilterProxyModel>
#include <QVector> #include <QVector>
namespace LtsWidgets namespace LtsWidgets
{ {
struct ComboboxFilterData struct ComboboxFilterData
@@ -26,11 +24,13 @@ struct ComboboxFilterData
{ {
return LtsUtils::lessThan(data, cfd.data); return LtsUtils::lessThan(data, cfd.data);
} }
inline friend QDataStream& operator<<(QDataStream& ds, const ComboboxFilterData& cfd) inline friend QDataStream& operator<<(QDataStream& ds, const ComboboxFilterData& cfd)
{ {
ds << cfd.text << cfd.data << cfd.icon; ds << cfd.text << cfd.data << cfd.icon;
return ds; return ds;
} }
inline friend QDataStream& operator>>(QDataStream& ds, ComboboxFilterData& cfd) inline friend QDataStream& operator>>(QDataStream& ds, ComboboxFilterData& cfd)
{ {
ds >> cfd.text >> cfd.data >> cfd.icon; ds >> cfd.text >> cfd.data >> cfd.icon;
@@ -38,12 +38,15 @@ struct ComboboxFilterData
} }
}; };
struct ComboboxFilterContent struct ComboboxFilterContent
{ {
QVector<ComboboxFilterData> data; QVector<ComboboxFilterData> data;
bool sortItems = false; bool sortItems = false;
bool isValid() const { return m_isValid; }
bool isValid() const
{
return m_isValid;
}
QVariant toVariant() const QVariant toVariant() const
{ {
@@ -72,6 +75,7 @@ struct ComboboxFilterContent
ds << cfc.data << cfc.sortItems; ds << cfc.data << cfc.sortItems;
return ds; return ds;
} }
inline friend QDataStream& operator>>(QDataStream& ds, ComboboxFilterContent& cfc) inline friend QDataStream& operator>>(QDataStream& ds, ComboboxFilterContent& cfc)
{ {
ds >> cfc.data >> cfc.sortItems; ds >> cfc.data >> cfc.sortItems;
@@ -82,7 +86,6 @@ private:
bool m_isValid = true; bool m_isValid = true;
}; };
class LTSWIDGETS_EXPORT LtsColumnFilterProxyModel : public QSortFilterProxyModel class LTSWIDGETS_EXPORT LtsColumnFilterProxyModel : public QSortFilterProxyModel
{ {
Q_OBJECT Q_OBJECT
@@ -96,8 +99,15 @@ public:
bool recursiveFilteringEnabled() const; bool recursiveFilteringEnabled() const;
#endif #endif
const QHash<int, QRegularExpression> &columnStringFilters() const { return m_columnStringFilters; } const QHash<int, QRegularExpression>& columnStringFilters() const
const QHash<int, QVariant> &columnDataFilters() const { return m_columnDataFilters; } {
return m_columnStringFilters;
}
const QHash<int, QVariant>& columnDataFilters() const
{
return m_columnDataFilters;
}
bool lessThan(const QModelIndex& left, const QModelIndex& right) const override; bool lessThan(const QModelIndex& left, const QModelIndex& right) const override;
@@ -120,4 +130,4 @@ private:
bool m_bRecursiveFiltering = false; bool m_bRecursiveFiltering = false;
#endif #endif
}; };
} } // namespace LtsWidgets
+13 -32
View File
@@ -1,14 +1,13 @@
#include "lts_combo_box.h" #include "lts_combo_box.h"
#include "lts_selection_popup.h"
#include "lts_message_dialog.h" #include "lts_message_dialog.h"
#include "lts_selection_popup.h"
#include <QGuiApplication> #include <QGuiApplication>
#include <QShowEvent> #include <QShowEvent>
#ifdef NEVER #ifdef NEVER
#include <QDebug> #include <QDebug>
#endif #endif
@@ -18,12 +17,9 @@ namespace LtsWidgets
bool LtsComboBox::s_useSelectionDialog = false; bool LtsComboBox::s_useSelectionDialog = false;
LtsComboBox::LtsComboBox(QWidget *parent) LtsComboBox::LtsComboBox(QWidget* parent) : QComboBox(parent), m_currentIndex(-1)
: QComboBox(parent)
, m_currentIndex(-1)
{ {
connect(this, &LtsComboBox::signalExternallyChanged, connect(this, &LtsComboBox::signalExternallyChanged, this, &LtsComboBox::signalRefill);
this, &LtsComboBox::signalRefill);
} }
void LtsComboBox::setUseSelectionDialog(bool bUseSelectionDialog) void LtsComboBox::setUseSelectionDialog(bool bUseSelectionDialog)
@@ -38,7 +34,7 @@ void LtsComboBox::showEvent(QShowEvent *e)
m_currentIndex = currentIndex(); m_currentIndex = currentIndex();
} }
void LtsComboBox::enterEvent(QEvent *e) void LtsComboBox::enterEvent(QEnterEvent* e)
{ {
BaseClass::enterEvent(e); BaseClass::enterEvent(e);
emit signalEnterEvent(); emit signalEnterEvent();
@@ -67,47 +63,32 @@ void LtsComboBox::showPopup()
return; return;
} }
LtsSelectionPopup* popup = new LtsSelectionPopup(model(), currentIndex(), this); LtsSelectionPopup* popup = new LtsSelectionPopup(model(), currentIndex(), this);
popup->setAttribute(Qt::WA_DeleteOnClose); popup->setAttribute(Qt::WA_DeleteOnClose);
#ifdef NEVER #ifdef NEVER
connect(popup, static_cast<void (LtsSelectionPopup::*)(int)>(&LtsSelectionPopup::currentIndexChanged), this,
[](int idx) { qCritical() << " LtsComboBox: called: currentIndexChanged(int), idx=" << idx; });
connect(popup, static_cast<void (LtsSelectionPopup::*)(int)>(&LtsSelectionPopup::activated), this,
[](int idx) { qCritical() << " LtsComboBox: called: activated(int), idx=" << idx; });
connect(popup, static_cast<void (LtsSelectionPopup::*)(int)>(&LtsSelectionPopup::currentIndexChanged), this, [](int idx){
qCritical() << " LtsComboBox: called: currentIndexChanged(int), idx=" << idx;
});
connect(popup, static_cast<void (LtsSelectionPopup::*)(int)>(&LtsSelectionPopup::activated), this, [](int idx){
qCritical() << " LtsComboBox: called: activated(int), idx=" << idx;
});
#endif #endif
connect(popup, &LtsSelectionPopup::currentIndexChanged, this, &LtsComboBox::userChangedIndex);
connect(popup, &LtsSelectionPopup::activated, this,
connect(popup, &LtsSelectionPopup::currentIndexChanged, static_cast<void (LtsComboBox::*)(int)>(&LtsComboBox::activated));
this, &LtsComboBox::userChangedIndex);
connect(popup, &LtsSelectionPopup::activated,
this, static_cast<void (LtsComboBox::*)(int)>(&LtsComboBox::activated));
popup->show(); popup->show();
} }
void LtsComboBox::userChangedIndex(int index) void LtsComboBox::userChangedIndex(int index)
{ {
m_currentIndex = index; m_currentIndex = index;
setCurrentIndex(index); setCurrentIndex(index);
} }
bool LtsComboBox::hasValueChanged() const bool LtsComboBox::hasValueChanged() const
{ {
if (m_currentIndex == -1) if (m_currentIndex == -1)
@@ -115,4 +96,4 @@ bool LtsComboBox::hasValueChanged() const
return !(currentIndex() == m_currentIndex); return !(currentIndex() == m_currentIndex);
} }
} } // namespace LtsWidgets
+12 -16
View File
@@ -1,19 +1,14 @@
#pragma once #pragma once
#include <QObject>
#include "ltswidgets_export.h" #include "ltswidgets_export.h"
#include <QComboBox> #include <QComboBox>
#include <QObject>
namespace LtsWidgets namespace LtsWidgets
{ {
class LTSWIDGETS_EXPORT LtsComboBox : public QComboBox class LTSWIDGETS_EXPORT LtsComboBox : public QComboBox
{ {
Q_OBJECT Q_OBJECT
@@ -23,24 +18,25 @@ public:
explicit LtsComboBox(QWidget* parent = nullptr); explicit LtsComboBox(QWidget* parent = nullptr);
~LtsComboBox() = default; ~LtsComboBox() = default;
static void setUseSelectionDialog(bool bUseSelectionDialog); static void setUseSelectionDialog(bool bUseSelectionDialog);
bool hasValueChanged() const; bool hasValueChanged() const;
void setExternalContentType(int ect) { m_externalContentType = ect; } void setExternalContentType(int ect)
int externalContentType() const { return m_externalContentType; } {
m_externalContentType = ect;
}
int externalContentType() const
{
return m_externalContentType;
}
protected: protected:
void showPopup() override; void showPopup() override;
void showEvent(QShowEvent* e) override; void showEvent(QShowEvent* e) override;
void enterEvent(QEvent *e) override; void enterEvent(QEnterEvent* e) override;
void leaveEvent(QEvent*) override; void leaveEvent(QEvent*) override;
protected slots: protected slots:
@@ -57,4 +53,4 @@ private:
int m_externalContentType; int m_externalContentType;
static bool s_useSelectionDialog; static bool s_useSelectionDialog;
}; };
} } // namespace LtsWidgets
+58 -129
View File
@@ -1,17 +1,11 @@
#include "lts_date_time_edit.h" #include "lts_date_time_edit.h"
#include <utility>
#include "lts_date_time_edit_p.h"
#include "lts_date_time_edit_p.h"
#include "ui_lts_date_time_edit_touch.h" #include "ui_lts_date_time_edit_touch.h"
#include <LtsUtilsSettings/settings.h> #include <LtsUtilsSettings/settings.h>
#include <ngltools/ngltools_dtg.h>
#include <QApplication> #include <QApplication>
#include <QCheckBox> #include <QCheckBox>
#include <QCompleter> #include <QCompleter>
@@ -25,6 +19,8 @@
#include <QShortcut> #include <QShortcut>
#include <QSlider> #include <QSlider>
#include <QToolButton> #include <QToolButton>
#include <ngltools/ngltools_dtg.h>
#include <utility>
static constexpr qint64 s_oneSecondMSec = 1000LL; static constexpr qint64 s_oneSecondMSec = 1000LL;
static constexpr qint64 s_oneMinuteMSec = 60 * s_oneSecondMSec; static constexpr qint64 s_oneMinuteMSec = 60 * s_oneSecondMSec;
@@ -74,7 +70,7 @@ public:
void setupUi(QWidget* parent) void setupUi(QWidget* parent)
{ {
gridLayout = new QGridLayout(parent); gridLayout = new QGridLayout(parent);
gridLayout->setMargin(0); gridLayout->setContentsMargins(0, 0, 0, 0);
int iStart = 3; int iStart = 3;
@@ -170,33 +166,32 @@ public:
gridLayout->addWidget(slTime, 1, 0, 1, 7); gridLayout->addWidget(slTime, 1, 0, 1, 7);
} }
}; };
} } // namespace Ui
namespace LtsWidgets namespace LtsWidgets
{ {
void setItemText(LtsWidgets::LineEdit* lineEdit, const QString& text) void setItemText(LtsWidgets::LineEdit* lineEdit, const QString& text)
{ {
if (!lineEdit) if (!lineEdit)
return; return;
lineEdit->setText(text); lineEdit->setText(text);
} }
void setItemText(QComboBox* comboxBox, const QString& text) void setItemText(QComboBox* comboxBox, const QString& text)
{ {
if (!comboxBox) if (!comboxBox)
return; return;
comboxBox->setCurrentIndex(comboxBox->findText(text)); comboxBox->setCurrentIndex(comboxBox->findText(text));
} }
void setItemData(QComboBox* comboxBox, int data) void setItemData(QComboBox* comboxBox, int data)
{ {
if (!comboxBox) if (!comboxBox)
return; return;
comboxBox->setCurrentIndex(comboxBox->findData(data)); comboxBox->setCurrentIndex(comboxBox->findData(data));
} }
void setItemValue(QSpinBox* spinBox, int value) void setItemValue(QSpinBox* spinBox, int value)
{ {
if (!spinBox) if (!spinBox)
@@ -204,13 +199,13 @@ void setItemValue(QSpinBox *spinBox, int value)
spinBox->setValue(value); spinBox->setValue(value);
} }
QString getItemText(LtsWidgets::LineEdit* lineEdit) QString getItemText(LtsWidgets::LineEdit* lineEdit)
{ {
if (!lineEdit) if (!lineEdit)
return {}; return {};
return lineEdit->text(); return lineEdit->text();
} }
QString getItemText(QComboBox* comboxBox) QString getItemText(QComboBox* comboxBox)
{ {
if (!comboxBox || (comboxBox->count() <= 0)) if (!comboxBox || (comboxBox->count() <= 0))
@@ -220,6 +215,7 @@ QString getItemText(QComboBox *comboxBox)
return {}; return {};
return curTest.at(0).toUpper(); return curTest.at(0).toUpper();
} }
int getItemData(QComboBox* comboxBox) int getItemData(QComboBox* comboxBox)
{ {
if (!comboxBox || (comboxBox->count() <= 0)) if (!comboxBox || (comboxBox->count() <= 0))
@@ -227,6 +223,7 @@ int getItemData(QComboBox *comboxBox)
int data = comboxBox->currentData().toInt(); int data = comboxBox->currentData().toInt();
return data; return data;
} }
int getItemValue(QSpinBox* spinBox) int getItemValue(QSpinBox* spinBox)
{ {
if (!spinBox) if (!spinBox)
@@ -234,18 +231,15 @@ int getItemValue(QSpinBox *spinBox)
return spinBox->value(); return spinBox->value();
} }
LtsDateTimeEdit::LtsDateTimeEdit(QWidget* parent, bool withNowButton, bool checkable) LtsDateTimeEdit::LtsDateTimeEdit(QWidget* parent, bool withNowButton, bool checkable)
: QWidget(parent) : 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_scFixed(new QShortcut(QKeySequence(Qt::ShiftModifier + Qt::Key_F2), this, SLOT(setFixedDateTime()), nullptr,
, m_checkable(checkable) Qt::WidgetWithChildrenShortcut)),
, m_withNowButton(withNowButton) m_scOffset(new QShortcut(QKeySequence(Qt::Key_F2), this, SLOT(setOffsetDateTime()), nullptr,
Qt::WidgetWithChildrenShortcut)),
m_checkable(checkable), m_withNowButton(withNowButton)
{ {
#ifdef TABLET_MODE #ifdef TABLET_MODE
@@ -324,30 +318,20 @@ bool LtsDateTimeEdit::setupUiTouch()
m_uiTouch->cbxTimeZone->addItem(QChar(i), QChar(i)); m_uiTouch->cbxTimeZone->addItem(QChar(i), QChar(i));
} }
connect(m_uiTouch->pbNow, &QPushButton::clicked, connect(m_uiTouch->pbNow, &QPushButton::clicked, this, &LtsDateTimeEdit::setOffsetDateTime);
this, &LtsDateTimeEdit::setOffsetDateTime); connect(m_uiTouch->cbxMonth, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this,
connect(m_uiTouch->cbxMonth, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), &LtsDateTimeEdit::dateTimeChanged);
this, &LtsDateTimeEdit::dateTimeChanged); connect(m_uiTouch->spDay, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::dateTimeChanged);
connect(m_uiTouch->spDay, &QSpinBox::editingFinished, connect(m_uiTouch->spHour, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::dateTimeChanged);
this, &LtsDateTimeEdit::dateTimeChanged); connect(m_uiTouch->spMinutes, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::dateTimeChanged);
connect(m_uiTouch->spHour, &QSpinBox::editingFinished, connect(m_uiTouch->spSeconds, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::dateTimeChanged);
this, &LtsDateTimeEdit::dateTimeChanged); connect(m_uiTouch->spYear, &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, connect(m_uiTouch->checkBox, &QCheckBox::toggled, this, &LtsDateTimeEdit::onCheckBoxChanged);
this, &LtsDateTimeEdit::onCheckBoxChanged); connect(m_uiTouch->cbxTimeZone, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this,
connect(m_uiTouch->cbxTimeZone, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), &LtsDateTimeEdit::valueTimezoneChangedInt);
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);
@@ -355,7 +339,6 @@ bool LtsDateTimeEdit::setupUiTouch()
setTimezone(DTG::timezone()); setTimezone(DTG::timezone());
setCheckable(m_checkable); setCheckable(m_checkable);
setWithNowButton(m_withNowButton); setWithNowButton(m_withNowButton);
@@ -365,7 +348,6 @@ bool LtsDateTimeEdit::setupUiTouch()
return true; return true;
} }
void LtsDateTimeEdit::setRetrieveCurrentTimeCallback(const CurrentTimeCallback& cb) void LtsDateTimeEdit::setRetrieveCurrentTimeCallback(const CurrentTimeCallback& cb)
{ {
m_getCurrentTimeCallback = cb; m_getCurrentTimeCallback = cb;
@@ -524,11 +506,6 @@ bool LtsDateTimeEdit::setMsecsSinceEpoch(qint64 msec, bool setToNearestPossible)
if (msec == 0) if (msec == 0)
return false; return false;
if (!setToNearestPossible) if (!setToNearestPossible)
{ {
if (!isDataAcceptable()) if (!isDataAcceptable())
@@ -556,11 +533,7 @@ bool LtsDateTimeEdit::setMsecsSinceEpoch(qint64 msec, bool setToNearestPossible)
const int minute = time.minute(); const int minute = time.minute();
const int second = time.second(); const int second = time.second();
if (!setYear(year) || !setMonth(month) || !setDay(day) || !setHHMMSS(hour, minute, second))
if (!setYear(year) ||
!setMonth(month) ||
!setDay(day) ||
!setHHMMSS(hour, minute, second))
return false; return false;
if (!isDataAcceptable()) if (!isDataAcceptable())
@@ -573,7 +546,6 @@ bool LtsDateTimeEdit::setMsecsSinceEpoch(qint64 msec, bool setToNearestPossible)
return true; return true;
} }
qint64 LtsDateTimeEdit::msecsSinceEpoch() const qint64 LtsDateTimeEdit::msecsSinceEpoch() const
{ {
if (isEmpty()) if (isEmpty())
@@ -652,22 +624,14 @@ void LtsDateTimeEdit::setMinMaxMonth(int minMonth, int maxMonth)
if (i > m_maxMonth) if (i > m_maxMonth)
break; break;
const QStringList& monthSl = DTG::months(); const QStringList& monthSl = DTG::months();
m_uiTouch->cbxMonth->addItem(monthSl[i - 1], i); m_uiTouch->cbxMonth->addItem(monthSl[i - 1], i);
} }
m_uiTouch->cbxMonth->setCurrentIndex(m_uiTouch->cbxMonth->findData(currentMonth)); m_uiTouch->cbxMonth->setCurrentIndex(m_uiTouch->cbxMonth->findData(currentMonth));
m_uiTouch->cbxMonth->blockSignals(false); 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) if (m_uiLe)
@@ -762,9 +726,7 @@ int LtsDateTimeEdit::getDay() const
bool LtsDateTimeEdit::setHHMMSS(int hour, int minute, int second) bool LtsDateTimeEdit::setHHMMSS(int hour, int minute, int second)
{ {
if (hour < 0 || hour > 23 || if (hour < 0 || hour > 23 || minute < 0 || minute > 59 || second < 0 || second > 59)
minute < 0 || minute > 59 ||
second < 0 || second > 59)
return false; return false;
if (m_uiLe) if (m_uiLe)
@@ -852,11 +814,7 @@ int LtsDateTimeEdit::getYear() const
bool LtsDateTimeEdit::isEmpty() const bool LtsDateTimeEdit::isEmpty() const
{ {
return (isEmptyDay() || return (isEmptyDay() || isEmptyHHMMSS() || isEmptyMonth() || isEmptyTimezone() || isEmptyYear());
isEmptyHHMMSS() ||
isEmptyMonth() ||
isEmptyTimezone() ||
isEmptyYear());
} }
bool LtsDateTimeEdit::isValidDate() const bool LtsDateTimeEdit::isValidDate() const
@@ -864,7 +822,6 @@ bool LtsDateTimeEdit::isValidDate() const
return m_dateIsAcceptable; return m_dateIsAcceptable;
} }
bool LtsDateTimeEdit::isEmptyDay() const bool LtsDateTimeEdit::isEmptyDay() const
{ {
if (m_uiLe) if (m_uiLe)
@@ -904,24 +861,16 @@ bool LtsDateTimeEdit::hasFocus() const
{ {
if (!m_uiLe) if (!m_uiLe)
return false; return false;
return (m_uiLe->leLongDay->hasFocus() || return (m_uiLe->leLongDay->hasFocus() || m_uiLe->leLongHHMMSS->hasFocus() || m_uiLe->leLongMonth->hasFocus() ||
m_uiLe->leLongHHMMSS->hasFocus() || m_uiLe->leLongTZ->hasFocus() || m_uiLe->leLongYear->hasFocus());
m_uiLe->leLongMonth->hasFocus() ||
m_uiLe->leLongTZ->hasFocus() ||
m_uiLe->leLongYear->hasFocus());
} }
bool LtsDateTimeEdit::isDataAcceptable() bool LtsDateTimeEdit::isDataAcceptable()
{ {
m_dateIsAcceptable = false; m_dateIsAcceptable = false;
bool state = bool state = isDayAcceptable() && isHHMMSSAcceptable() && isMonthAcceptable() && isYearAcceptable() &&
isDayAcceptable() && QDate::isValid(getYear(), getMonth(), getDay()) && QTime::isValid(getHour(), getMinute(), getSecond());
isHHMMSSAcceptable() &&
isMonthAcceptable() &&
isYearAcceptable() &&
QDate::isValid(getYear(), getMonth(), getDay()) &&
QTime::isValid(getHour(), getMinute(), getSecond());
if (m_editTimezone && state) if (m_editTimezone && state)
state = isTzAcceptable(); state = isTzAcceptable();
@@ -934,7 +883,8 @@ bool LtsDateTimeEdit::isDataAcceptable()
return false; return false;
} }
qint64 msec = QDateTime(QDate(getYear(), getMonth(), getDay()), QTime(getHour(), getMinute(), getSecond()), Qt::UTC).toMSecsSinceEpoch(); qint64 msec = QDateTime(QDate(getYear(), getMonth(), getDay()), QTime(getHour(), getMinute(), getSecond()), Qt::UTC)
.toMSecsSinceEpoch();
msec -= DTG::timezone2Secs(getTimezone()) * 1000LL; msec -= DTG::timezone2Secs(getTimezone()) * 1000LL;
if (m_minTimeMSec > 0 && m_maxTimeMSec > 0 && m_minTimeMSec < m_maxTimeMSec) if (m_minTimeMSec > 0 && m_maxTimeMSec > 0 && m_minTimeMSec < m_maxTimeMSec)
{ {
@@ -957,8 +907,7 @@ bool LtsDateTimeEdit::isDayAcceptable() const
const int month = getMonth(); const int month = getMonth();
switch (month) switch (month)
{ {
case 2: case 2: {
{
max = 28; max = 28;
if (isYearAcceptable()) if (isYearAcceptable())
{ {
@@ -1025,8 +974,7 @@ void LtsDateTimeEdit::showInvalidData(bool setFocus)
bool focus = setFocus; bool focus = setFocus;
auto check = [&](QLineEdit * le, bool isValid) auto check = [&](QLineEdit* le, bool isValid) {
{
if (isValid) if (isValid)
le->setStyleSheet(QString()); le->setStyleSheet(QString());
else else
@@ -1068,7 +1016,9 @@ bool LtsDateTimeEdit::isLineEditDataAcceptable(QLineEdit *le) const
void LtsDateTimeEdit::setFixedDateTime() 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() void LtsDateTimeEdit::setOffsetDateTime()
@@ -1076,7 +1026,9 @@ void LtsDateTimeEdit::setOffsetDateTime()
if (!m_getCurrentTimeCallback) if (!m_getCurrentTimeCallback)
return; return;
qint64 offset = LtsUtils::OperatorSettings::getInstance()->value(QStringLiteral("TimeSettings"), QStringLiteral("Offset"), 0).toLongLong(); qint64 offset = LtsUtils::OperatorSettings::getInstance()
->value(QStringLiteral("TimeSettings"), QStringLiteral("Offset"), 0)
.toLongLong();
setMsecsSinceEpoch((m_getCurrentTimeCallback() / 1000) * 1000 + offset); setMsecsSinceEpoch((m_getCurrentTimeCallback() / 1000) * 1000 + offset);
} }
@@ -1144,11 +1096,6 @@ void LtsDateTimeEdit::fixupHHMMSS()
QString uhrzeit(m_uiLe->leLongHHMMSS->text()); QString uhrzeit(m_uiLe->leLongHHMMSS->text());
QString hh; QString hh;
QString mm; QString mm;
QString ss; QString ss;
@@ -1274,7 +1221,6 @@ void LtsDateTimeEdit::valueMonthChanged(const QString &str)
{ {
m_uiLe->leLongMonth->setText(monStr); m_uiLe->leLongMonth->setText(monStr);
if (cp > 0) if (cp > 0)
m_uiLe->leLongMonth->setCursorPosition(cp); m_uiLe->leLongMonth->setCursorPosition(cp);
else else
@@ -1404,13 +1350,13 @@ void LtsDateTimeEdit::onCheckBoxChanged()
if (m_uiLe) if (m_uiLe)
{ {
widgets = {m_uiLe->leLongDay, m_uiLe->leLongHHMMSS, m_uiLe->leLongTZ, widgets = {m_uiLe->leLongDay, m_uiLe->leLongHHMMSS, m_uiLe->leLongTZ, m_uiLe->leLongMonth, m_uiLe->leLongYear};
m_uiLe->leLongMonth, m_uiLe->leLongYear};
} }
if (m_uiTouch) 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}; 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(); bEnable = checkBox()->isChecked();
@@ -1433,10 +1379,7 @@ void LtsDateTimeEdit::enableControls()
return; return;
enaDisaControls(true); enaDisaControls(true);
if (m_withSlider && if (m_withSlider && m_minTimeMSec != 0 && m_maxTimeMSec > 0 && m_maxTimeMSec > m_minTimeMSec)
m_minTimeMSec != 0 &&
m_maxTimeMSec > 0 &&
m_maxTimeMSec > m_minTimeMSec)
{ {
m_uiLe->slTime->setEnabled(true); m_uiLe->slTime->setEnabled(true);
m_uiLe->slTime->setValue(m_curTimeMSec / 1000LL); m_uiLe->slTime->setValue(m_curTimeMSec / 1000LL);
@@ -1447,9 +1390,8 @@ void LtsDateTimeEdit::enaDisaControls(bool bEnable)
{ {
if (!m_uiLe) if (!m_uiLe)
return; return;
const QVector<QWidget *> widgets({m_uiLe->pbBBB, m_uiLe->pbBB, m_uiLe->pbB, const QVector<QWidget*> widgets(
m_uiLe->pbF, m_uiLe->pbFF, m_uiLe->pbFFF, {m_uiLe->pbBBB, m_uiLe->pbBB, m_uiLe->pbB, m_uiLe->pbF, m_uiLe->pbFF, m_uiLe->pbFFF, m_uiLe->slTime});
m_uiLe->slTime});
for (auto w : widgets) for (auto w : widgets)
{ {
if (w) if (w)
@@ -1507,7 +1449,6 @@ void LtsDateTimeEdit::clear()
m_uiTouch->spYear->clear(); m_uiTouch->spYear->clear();
} }
emit dateTimeChanged(); emit dateTimeChanged();
} }
void LtsDateTimeEdit::onFocusOutDay() void LtsDateTimeEdit::onFocusOutDay()
@@ -1526,9 +1467,7 @@ void LtsDateTimeEdit::onFocusOutDay()
if (value.length() == 0 && !m_backspacePressed) if (value.length() == 0 && !m_backspacePressed)
{ {
if (!isEmptyHHMMSS() || if (!isEmptyHHMMSS() || !isEmptyMonth() || (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) ||
!isEmptyMonth() ||
(!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) ||
!isEmptyYear()) !isEmptyYear())
{ {
if (m_getCurrentTimeCallback) if (m_getCurrentTimeCallback)
@@ -1558,10 +1497,7 @@ void LtsDateTimeEdit::onFocusOutHHMMSS()
if (value.length() == 0 && !m_backspacePressed) if (value.length() == 0 && !m_backspacePressed)
{ {
if (!isEmptyDay() || if (!isEmptyDay() || !isEmptyMonth() || !(isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) || !isEmptyYear())
!isEmptyMonth() ||
!(isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) ||
!isEmptyYear())
{ {
if (m_getCurrentTimeCallback) if (m_getCurrentTimeCallback)
{ {
@@ -1592,10 +1528,7 @@ void LtsDateTimeEdit::onFocusOutTZ()
if (value.length() == 0 && !m_backspacePressed) if (value.length() == 0 && !m_backspacePressed)
{ {
if (!isEmptyHHMMSS() || if (!isEmptyHHMMSS() || !isEmptyMonth() || !isEmptyDay() || !isEmptyYear())
!isEmptyMonth() ||
!isEmptyDay() ||
!isEmptyYear())
setTimezone(DTG::timezone()); setTimezone(DTG::timezone());
} }
isDataAcceptable(); isDataAcceptable();
@@ -1619,9 +1552,7 @@ void LtsDateTimeEdit::onFocusOutMonth()
if (value.length() == 0 && !m_backspacePressed) if (value.length() == 0 && !m_backspacePressed)
{ {
if (!isEmptyHHMMSS() || if (!isEmptyHHMMSS() || !isEmptyDay() || (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) ||
!isEmptyDay() ||
(!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) ||
!isEmptyYear()) !isEmptyYear())
{ {
if (m_getCurrentTimeCallback) if (m_getCurrentTimeCallback)
@@ -1658,9 +1589,7 @@ void LtsDateTimeEdit::onFocusOutYear()
if (value.length() == 0 && !m_backspacePressed) if (value.length() == 0 && !m_backspacePressed)
{ {
if (!isEmptyHHMMSS() || if (!isEmptyHHMMSS() || !isEmptyMonth() || (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) ||
!isEmptyMonth() ||
(!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) ||
!isEmptyDay()) !isEmptyDay())
{ {
if (m_getCurrentTimeCallback) if (m_getCurrentTimeCallback)
@@ -1783,4 +1712,4 @@ void LtsDateTimeEdit::onYearWheelEvent(bool bForward, int cursorPos)
emit dateTimeChanged(); emit dateTimeChanged();
} }
} } // namespace LtsWidgets
+4 -13
View File
@@ -1,17 +1,13 @@
#include "lts_date_time_edit_p.h" #include "lts_date_time_edit_p.h"
#include <QApplication> #include <QApplication>
#include <QKeyEvent>
#include <QRegularExpression> #include <QRegularExpression>
#include <QValidator> #include <QValidator>
#include <QKeyEvent>
namespace LtsWidgets namespace LtsWidgets
{ {
void LineEdit::clear() void LineEdit::clear()
{ {
setStyleSheet(QString()); setStyleSheet(QString());
@@ -39,7 +35,6 @@ void LineEdit::keyPressEvent(QKeyEvent *event)
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)
@@ -48,11 +43,7 @@ void LineEdit::focusOutEvent(QFocusEvent *event)
emit focusOut(); emit focusOut();
} }
DigitsLineEdit::DigitsLineEdit(QWidget* parent) : LineEdit(parent)
DigitsLineEdit::DigitsLineEdit(QWidget *parent)
: LineEdit(parent)
{ {
setAlignment(Qt::AlignRight); setAlignment(Qt::AlignRight);
QRegularExpression rx(QLatin1String("[-]{0,1}[0-9 ]*")); QRegularExpression rx(QLatin1String("[-]{0,1}[0-9 ]*"));
@@ -101,7 +92,7 @@ void DigitsLineEdit::wheelEvent(QWheelEvent *event)
return; return;
event->accept(); event->accept();
int cursorPos = cursorPosition(); int cursorPos = cursorPosition();
emit wheelEventReceived(event->delta() > 0, cursorPos); emit wheelEventReceived(event->angleDelta().y() > 0, cursorPos);
} }
void DigitsLineEdit::keyPressEvent(QKeyEvent* event) void DigitsLineEdit::keyPressEvent(QKeyEvent* event)
@@ -115,4 +106,4 @@ void DigitsLineEdit::keyPressEvent(QKeyEvent *event)
} }
} }
} } // namespace LtsWidgets
+56 -127
View File
@@ -1,16 +1,10 @@
#include "lts_date_time_edit.h" #include "lts_date_time_edit.h"
#include "lts_date_time_edit_p.h" #include "lts_date_time_edit_p.h"
#include "ui_lts_date_time_edit_touch.h" #include "ui_lts_date_time_edit_touch.h"
#include <LtsUtilsSettings/settings.h> #include <LtsUtilsSettings/settings.h>
#include <ngltools/ngltools_dtg.h>
#include <QApplication> #include <QApplication>
#include <QCheckBox> #include <QCheckBox>
#include <QCompleter> #include <QCompleter>
@@ -24,6 +18,7 @@
#include <QShortcut> #include <QShortcut>
#include <QSlider> #include <QSlider>
#include <QToolButton> #include <QToolButton>
#include <ngltools/ngltools_dtg.h>
static constexpr qint64 s_oneSecondMSec = 1000LL; static constexpr qint64 s_oneSecondMSec = 1000LL;
static constexpr qint64 s_oneMinuteMSec = 60 * s_oneSecondMSec; static constexpr qint64 s_oneMinuteMSec = 60 * s_oneSecondMSec;
@@ -73,7 +68,7 @@ public:
void setupUi(QWidget* parent) void setupUi(QWidget* parent)
{ {
gridLayout = new QGridLayout(parent); gridLayout = new QGridLayout(parent);
gridLayout->setMargin(0); gridLayout->setContentsMargins(0, 0, 0, 0);
int iStart = 3; int iStart = 3;
@@ -169,33 +164,32 @@ public:
gridLayout->addWidget(slTime, 1, 0, 1, 7); gridLayout->addWidget(slTime, 1, 0, 1, 7);
} }
}; };
} } // namespace Ui
namespace LtsWidgets namespace LtsWidgets
{ {
void setItemText(LtsWidgets::LineEdit* lineEdit, const QString& text) void setItemText(LtsWidgets::LineEdit* lineEdit, const QString& text)
{ {
if (!lineEdit) if (!lineEdit)
return; return;
lineEdit->setText(text); lineEdit->setText(text);
} }
void setItemText(QComboBox* comboxBox, const QString& text) void setItemText(QComboBox* comboxBox, const QString& text)
{ {
if (!comboxBox) if (!comboxBox)
return; return;
comboxBox->setCurrentIndex(comboxBox->findText(text)); comboxBox->setCurrentIndex(comboxBox->findText(text));
} }
void setItemData(QComboBox* comboxBox, int data) void setItemData(QComboBox* comboxBox, int data)
{ {
if (!comboxBox) if (!comboxBox)
return; return;
comboxBox->setCurrentIndex(comboxBox->findData(data)); comboxBox->setCurrentIndex(comboxBox->findData(data));
} }
void setItemValue(QSpinBox* spinBox, int value) void setItemValue(QSpinBox* spinBox, int value)
{ {
if (!spinBox) if (!spinBox)
@@ -203,13 +197,13 @@ void setItemValue(QSpinBox *spinBox, int value)
spinBox->setValue(value); spinBox->setValue(value);
} }
QString getItemText(LtsWidgets::LineEdit* lineEdit) QString getItemText(LtsWidgets::LineEdit* lineEdit)
{ {
if (!lineEdit) if (!lineEdit)
return {}; return {};
return lineEdit->text(); return lineEdit->text();
} }
QString getItemText(QComboBox* comboxBox) QString getItemText(QComboBox* comboxBox)
{ {
if (!comboxBox || (comboxBox->count() <= 0)) if (!comboxBox || (comboxBox->count() <= 0))
@@ -219,6 +213,7 @@ QString getItemText(QComboBox *comboxBox)
return {}; return {};
return curTest.at(0).toUpper(); return curTest.at(0).toUpper();
} }
int getItemData(QComboBox* comboxBox) int getItemData(QComboBox* comboxBox)
{ {
if (!comboxBox || (comboxBox->count() <= 0)) if (!comboxBox || (comboxBox->count() <= 0))
@@ -226,6 +221,7 @@ int getItemData(QComboBox *comboxBox)
int data = comboxBox->currentData().toInt(); int data = comboxBox->currentData().toInt();
return data; return data;
} }
int getItemValue(QSpinBox* spinBox) int getItemValue(QSpinBox* spinBox)
{ {
if (!spinBox) if (!spinBox)
@@ -233,18 +229,15 @@ int getItemValue(QSpinBox *spinBox)
return spinBox->value(); return spinBox->value();
} }
LtsDateTimeEdit::LtsDateTimeEdit(QWidget* parent, bool withNowButton, bool withCheckBox) LtsDateTimeEdit::LtsDateTimeEdit(QWidget* parent, bool withNowButton, bool withCheckBox)
: QWidget(parent) : 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_scFixed(new QShortcut(QKeySequence(Qt::ShiftModifier + Qt::Key_F2), this, SLOT(setFixedDateTime()), nullptr,
, m_withCheckBox(withCheckBox) Qt::WidgetWithChildrenShortcut)),
, m_withNowButton(withNowButton) m_scOffset(new QShortcut(QKeySequence(Qt::Key_F2), this, SLOT(setOffsetDateTime()), nullptr,
Qt::WidgetWithChildrenShortcut)),
m_withCheckBox(withCheckBox), m_withNowButton(withNowButton)
{ {
#ifdef TABLET_MODE #ifdef TABLET_MODE
@@ -326,37 +319,25 @@ bool LtsDateTimeEdit::setupUiTouch()
m_uiTouch->cbxTimeZone->addItem(QChar(i), QChar(i)); m_uiTouch->cbxTimeZone->addItem(QChar(i), QChar(i));
} }
connect(m_uiTouch->pbNow, &QPushButton::clicked, connect(m_uiTouch->pbNow, &QPushButton::clicked, this, &LtsDateTimeEdit::setOffsetDateTime);
this, &LtsDateTimeEdit::setOffsetDateTime); connect(m_uiTouch->cbxMonth, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this,
connect(m_uiTouch->cbxMonth, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), &LtsDateTimeEdit::dateTimeChanged);
this, &LtsDateTimeEdit::dateTimeChanged); connect(m_uiTouch->spDay, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::dateTimeChanged);
connect(m_uiTouch->spDay, &QSpinBox::editingFinished, connect(m_uiTouch->spHour, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::dateTimeChanged);
this, &LtsDateTimeEdit::dateTimeChanged); connect(m_uiTouch->spMinutes, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::dateTimeChanged);
connect(m_uiTouch->spHour, &QSpinBox::editingFinished, connect(m_uiTouch->spSeconds, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::dateTimeChanged);
this, &LtsDateTimeEdit::dateTimeChanged); connect(m_uiTouch->spYear, &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, connect(m_uiTouch->checkBox, &QCheckBox::toggled, this, &LtsDateTimeEdit::onCheckBoxChanged);
this, &LtsDateTimeEdit::onCheckBoxChanged); connect(m_uiTouch->cbxTimeZone, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this,
connect(m_uiTouch->cbxTimeZone, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), &LtsDateTimeEdit::valueTimezoneChangedInt);
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; bool temp = m_withCheckBox;
m_withCheckBox = !m_withCheckBox; m_withCheckBox = !m_withCheckBox;
setWithCheckBox(temp); setWithCheckBox(temp);
@@ -367,11 +348,9 @@ bool LtsDateTimeEdit::setupUiTouch()
onCheckBoxChanged(); onCheckBoxChanged();
return true; return true;
} }
void LtsDateTimeEdit::setRetrieveCurrentTimeCallback(const CurrentTimeCallback& cb) void LtsDateTimeEdit::setRetrieveCurrentTimeCallback(const CurrentTimeCallback& cb)
{ {
m_getCurrentTimeCallback = cb; m_getCurrentTimeCallback = cb;
@@ -530,11 +509,6 @@ bool LtsDateTimeEdit::setMsecsSinceEpoch(qint64 msec, bool setToNearestPossible)
if (msec == 0) if (msec == 0)
return false; return false;
if (!setToNearestPossible) if (!setToNearestPossible)
{ {
if (!isDataAcceptable()) if (!isDataAcceptable())
@@ -562,11 +536,7 @@ bool LtsDateTimeEdit::setMsecsSinceEpoch(qint64 msec, bool setToNearestPossible)
const int minute = time.minute(); const int minute = time.minute();
const int second = time.second(); const int second = time.second();
if (!setYear(year) || !setMonth(month) || !setDay(day) || !setHHMMSS(hour, minute, second))
if (!setYear(year) ||
!setMonth(month) ||
!setDay(day) ||
!setHHMMSS(hour, minute, second))
return false; return false;
if (!isDataAcceptable()) if (!isDataAcceptable())
@@ -579,7 +549,6 @@ bool LtsDateTimeEdit::setMsecsSinceEpoch(qint64 msec, bool setToNearestPossible)
return true; return true;
} }
qint64 LtsDateTimeEdit::msecsSinceEpoch() const qint64 LtsDateTimeEdit::msecsSinceEpoch() const
{ {
if (isEmpty()) if (isEmpty())
@@ -662,17 +631,12 @@ void LtsDateTimeEdit::setMinMaxMonth(int minMonth, int maxMonth)
const QStringList monthSl = DTG::months(); const QStringList monthSl = DTG::months();
m_uiTouch->cbxMonth->addItem(monthSl[i - 1], i); m_uiTouch->cbxMonth->addItem(monthSl[i - 1], i);
} }
m_uiTouch->cbxMonth->setCurrentIndex(m_uiTouch->cbxMonth->findData(currentMonth)); m_uiTouch->cbxMonth->setCurrentIndex(m_uiTouch->cbxMonth->findData(currentMonth));
m_uiTouch->cbxMonth->blockSignals(false); 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) if (m_uiLe)
@@ -767,9 +731,7 @@ int LtsDateTimeEdit::getDay() const
bool LtsDateTimeEdit::setHHMMSS(int hour, int minute, int second) bool LtsDateTimeEdit::setHHMMSS(int hour, int minute, int second)
{ {
if (hour < 0 || hour > 23 || if (hour < 0 || hour > 23 || minute < 0 || minute > 59 || second < 0 || second > 59)
minute < 0 || minute > 59 ||
second < 0 || second > 59)
return false; return false;
if (m_uiLe) if (m_uiLe)
@@ -857,11 +819,7 @@ int LtsDateTimeEdit::getYear() const
bool LtsDateTimeEdit::isEmpty() const bool LtsDateTimeEdit::isEmpty() const
{ {
return (isEmptyDay() || return (isEmptyDay() || isEmptyHHMMSS() || isEmptyMonth() || isEmptyTimezone() || isEmptyYear());
isEmptyHHMMSS() ||
isEmptyMonth() ||
isEmptyTimezone() ||
isEmptyYear());
} }
bool LtsDateTimeEdit::isValidDate() const bool LtsDateTimeEdit::isValidDate() const
@@ -869,7 +827,6 @@ bool LtsDateTimeEdit::isValidDate() const
return m_dateIsAcceptable; return m_dateIsAcceptable;
} }
bool LtsDateTimeEdit::isEmptyDay() const bool LtsDateTimeEdit::isEmptyDay() const
{ {
if (m_uiLe) if (m_uiLe)
@@ -909,24 +866,16 @@ bool LtsDateTimeEdit::hasFocus() const
{ {
if (!m_uiLe) if (!m_uiLe)
return false; return false;
return (m_uiLe->leLongDay->hasFocus() || return (m_uiLe->leLongDay->hasFocus() || m_uiLe->leLongHHMMSS->hasFocus() || m_uiLe->leLongMonth->hasFocus() ||
m_uiLe->leLongHHMMSS->hasFocus() || m_uiLe->leLongTZ->hasFocus() || m_uiLe->leLongYear->hasFocus());
m_uiLe->leLongMonth->hasFocus() ||
m_uiLe->leLongTZ->hasFocus() ||
m_uiLe->leLongYear->hasFocus());
} }
bool LtsDateTimeEdit::isDataAcceptable() bool LtsDateTimeEdit::isDataAcceptable()
{ {
m_dateIsAcceptable = false; m_dateIsAcceptable = false;
bool state = bool state = isDayAcceptable() && isHHMMSSAcceptable() && isMonthAcceptable() && isYearAcceptable() &&
isDayAcceptable() && QDate::isValid(getYear(), getMonth(), getDay()) && QTime::isValid(getHour(), getMinute(), getSecond());
isHHMMSSAcceptable() &&
isMonthAcceptable() &&
isYearAcceptable() &&
QDate::isValid(getYear(), getMonth(), getDay()) &&
QTime::isValid(getHour(), getMinute(), getSecond());
if (m_editTimezone && state) if (m_editTimezone && state)
state = isTzAcceptable(); state = isTzAcceptable();
@@ -939,7 +888,8 @@ bool LtsDateTimeEdit::isDataAcceptable()
return false; return false;
} }
qint64 msec = QDateTime(QDate(getYear(), getMonth(), getDay()), QTime(getHour(), getMinute(), getSecond()), Qt::UTC).toMSecsSinceEpoch(); qint64 msec = QDateTime(QDate(getYear(), getMonth(), getDay()), QTime(getHour(), getMinute(), getSecond()), Qt::UTC)
.toMSecsSinceEpoch();
msec -= DTG::timezone2Secs(getTimezone()) * 1000LL; msec -= DTG::timezone2Secs(getTimezone()) * 1000LL;
if (m_minTimeMSec > 0 && m_maxTimeMSec > 0 && m_minTimeMSec < m_maxTimeMSec) if (m_minTimeMSec > 0 && m_maxTimeMSec > 0 && m_minTimeMSec < m_maxTimeMSec)
{ {
@@ -962,8 +912,7 @@ bool LtsDateTimeEdit::isDayAcceptable() const
const int month = getMonth(); const int month = getMonth();
switch (month) switch (month)
{ {
case 2: case 2: {
{
max = 28; max = 28;
if (isYearAcceptable()) if (isYearAcceptable())
{ {
@@ -1030,8 +979,7 @@ void LtsDateTimeEdit::showInvalidData(bool setFocus)
bool focus = setFocus; bool focus = setFocus;
auto check = [&](QLineEdit * le, bool isValid) auto check = [&](QLineEdit* le, bool isValid) {
{
if (isValid) if (isValid)
le->setStyleSheet(QString()); le->setStyleSheet(QString());
else else
@@ -1073,7 +1021,9 @@ bool LtsDateTimeEdit::isLineEditDataAcceptable(QLineEdit *le) const
void LtsDateTimeEdit::setFixedDateTime() 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() void LtsDateTimeEdit::setOffsetDateTime()
@@ -1081,7 +1031,9 @@ void LtsDateTimeEdit::setOffsetDateTime()
if (!m_getCurrentTimeCallback) if (!m_getCurrentTimeCallback)
return; return;
qint64 offset = LtsUtils::OperatorSettings::getInstance()->value(QStringLiteral("TimeSettings"), QStringLiteral("Offset"), 0).toLongLong(); qint64 offset = LtsUtils::OperatorSettings::getInstance()
->value(QStringLiteral("TimeSettings"), QStringLiteral("Offset"), 0)
.toLongLong();
setMsecsSinceEpoch((m_getCurrentTimeCallback() / 1000) * 1000 + offset); setMsecsSinceEpoch((m_getCurrentTimeCallback() / 1000) * 1000 + offset);
} }
@@ -1149,11 +1101,6 @@ void LtsDateTimeEdit::fixupHHMMSS()
QString uhrzeit(m_uiLe->leLongHHMMSS->text()); QString uhrzeit(m_uiLe->leLongHHMMSS->text());
QString hh; QString hh;
QString mm; QString mm;
QString ss; QString ss;
@@ -1279,7 +1226,6 @@ void LtsDateTimeEdit::valueMonthChanged(const QString &str)
{ {
m_uiLe->leLongMonth->setText(monStr); m_uiLe->leLongMonth->setText(monStr);
if (cp > 0) if (cp > 0)
m_uiLe->leLongMonth->setCursorPosition(cp); m_uiLe->leLongMonth->setCursorPosition(cp);
else else
@@ -1409,14 +1355,14 @@ void LtsDateTimeEdit::onCheckBoxChanged()
if (m_uiLe) if (m_uiLe)
{ {
widgets = {m_uiLe->leLongDay, m_uiLe->leLongHHMMSS, m_uiLe->leLongTZ, widgets = {m_uiLe->leLongDay, m_uiLe->leLongHHMMSS, m_uiLe->leLongTZ, m_uiLe->leLongMonth, m_uiLe->leLongYear};
m_uiLe->leLongMonth, m_uiLe->leLongYear};
bEnable = m_uiLe->checkBox->isChecked(); bEnable = m_uiLe->checkBox->isChecked();
} }
if (m_uiTouch) 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}; 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(); bEnable = m_uiTouch->checkBox->isChecked();
} }
@@ -1439,10 +1385,7 @@ void LtsDateTimeEdit::enableControls()
return; return;
enaDisaControls(true); enaDisaControls(true);
if (m_withSlider && if (m_withSlider && m_minTimeMSec != 0 && m_maxTimeMSec > 0 && m_maxTimeMSec > m_minTimeMSec)
m_minTimeMSec != 0 &&
m_maxTimeMSec > 0 &&
m_maxTimeMSec > m_minTimeMSec)
{ {
m_uiLe->slTime->setEnabled(true); m_uiLe->slTime->setEnabled(true);
m_uiLe->slTime->setValue(m_curTimeMSec / 1000LL); m_uiLe->slTime->setValue(m_curTimeMSec / 1000LL);
@@ -1453,9 +1396,8 @@ void LtsDateTimeEdit::enaDisaControls(bool bEnable)
{ {
if (!m_uiLe) if (!m_uiLe)
return; return;
const QVector<QWidget *> widgets({m_uiLe->pbBBB, m_uiLe->pbBB, m_uiLe->pbB, const QVector<QWidget*> widgets(
m_uiLe->pbF, m_uiLe->pbFF, m_uiLe->pbFFF, {m_uiLe->pbBBB, m_uiLe->pbBB, m_uiLe->pbB, m_uiLe->pbF, m_uiLe->pbFF, m_uiLe->pbFFF, m_uiLe->slTime});
m_uiLe->slTime});
for (auto w : widgets) for (auto w : widgets)
{ {
if (w) if (w)
@@ -1513,7 +1455,6 @@ void LtsDateTimeEdit::clear()
m_uiTouch->spYear->clear(); m_uiTouch->spYear->clear();
} }
emit dateTimeChanged(); emit dateTimeChanged();
} }
void LtsDateTimeEdit::onFocusOutDay() void LtsDateTimeEdit::onFocusOutDay()
@@ -1532,9 +1473,7 @@ void LtsDateTimeEdit::onFocusOutDay()
if (value.length() == 0 && !m_backspacePressed) if (value.length() == 0 && !m_backspacePressed)
{ {
if (!isEmptyHHMMSS() || if (!isEmptyHHMMSS() || !isEmptyMonth() || (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) ||
!isEmptyMonth() ||
(!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) ||
!isEmptyYear()) !isEmptyYear())
{ {
if (m_getCurrentTimeCallback) if (m_getCurrentTimeCallback)
@@ -1564,10 +1503,7 @@ void LtsDateTimeEdit::onFocusOutHHMMSS()
if (value.length() == 0 && !m_backspacePressed) if (value.length() == 0 && !m_backspacePressed)
{ {
if (!isEmptyDay() || if (!isEmptyDay() || !isEmptyMonth() || !(isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) || !isEmptyYear())
!isEmptyMonth() ||
!(isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) ||
!isEmptyYear())
{ {
if (m_getCurrentTimeCallback) if (m_getCurrentTimeCallback)
{ {
@@ -1598,10 +1534,7 @@ void LtsDateTimeEdit::onFocusOutTZ()
if (value.length() == 0 && !m_backspacePressed) if (value.length() == 0 && !m_backspacePressed)
{ {
if (!isEmptyHHMMSS() || if (!isEmptyHHMMSS() || !isEmptyMonth() || !isEmptyDay() || !isEmptyYear())
!isEmptyMonth() ||
!isEmptyDay() ||
!isEmptyYear())
setTimezone(DTG::timezone()); setTimezone(DTG::timezone());
} }
isDataAcceptable(); isDataAcceptable();
@@ -1625,9 +1558,7 @@ void LtsDateTimeEdit::onFocusOutMonth()
if (value.length() == 0 && !m_backspacePressed) if (value.length() == 0 && !m_backspacePressed)
{ {
if (!isEmptyHHMMSS() || if (!isEmptyHHMMSS() || !isEmptyDay() || (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) ||
!isEmptyDay() ||
(!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) ||
!isEmptyYear()) !isEmptyYear())
{ {
if (m_getCurrentTimeCallback) if (m_getCurrentTimeCallback)
@@ -1664,9 +1595,7 @@ void LtsDateTimeEdit::onFocusOutYear()
if (value.length() == 0 && !m_backspacePressed) if (value.length() == 0 && !m_backspacePressed)
{ {
if (!isEmptyHHMMSS() || if (!isEmptyHHMMSS() || !isEmptyMonth() || (!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) ||
!isEmptyMonth() ||
(!isEmptyTimezone() && m_uiLe->leLongTZ->isEnabled()) ||
!isEmptyDay()) !isEmptyDay())
{ {
if (m_getCurrentTimeCallback) if (m_getCurrentTimeCallback)
@@ -1789,4 +1718,4 @@ void LtsDateTimeEdit::onYearWheelEvent(bool bForward, int cursorPos)
emit dateTimeChanged(); emit dateTimeChanged();
} }
} } // namespace LtsWidgets
+78 -189
View File
@@ -1,50 +1,44 @@
#include "lts_dialog.h" #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_base_layout_widget.h"
#include "lts_date_time_edit.h" #include "lts_date_time_edit.h"
#include "lts_dialog_button_box.h"
#include <QHBoxLayout> #include "lts_dialog_helper.h"
#include <QProgressBar> #include "lts_message_dialog.h"
#include <QLineEdit> #include "lts_progress_dialog_helper.h"
#include <QComboBox>
#include <QCheckBox>
#include <QSpinBox>
#include <QDateTimeEdit>
#include <QSlider>
#include <QPlainTextEdit>
#include <QTextEdit>
#include <QWidget>
#include <QRadioButton>
#include <QTableView>
#include <QTableWidget>
#include <QListView>
#include <QListWidget>
#include <QSlider>
#include <QScroller>
#include <QScrollArea>
#include <QMenu>
#include <QInputDialog>
#include <QHBoxLayout>
#include <QPainter>
#include <QColor>
#include <QMetaMethod>
#include <QDebug>
#include <LtsSession/lts_session_data.h> #include <LtsSession/lts_session_data.h>
#include <QCheckBox>
#include <QColor>
#include <QComboBox>
#include <QDateTimeEdit>
#include <QDebug>
#include <QHBoxLayout>
#include <QInputDialog>
#include <QLineEdit>
#include <QListView>
#include <QListWidget>
#include <QMenu>
#include <QMetaMethod>
#include <QPainter>
#include <QPlainTextEdit>
#include <QProgressBar>
#include <QRadioButton>
#include <QScrollArea>
#include <QScroller>
#include <QSlider>
#include <QSpinBox>
#include <QTableView>
#include <QTableWidget>
#include <QTextEdit>
#include <QWidget>
namespace LtsWidgets namespace LtsWidgets
{ {
int LtsDialog::s_object_count = 0; int LtsDialog::s_object_count = 0;
class OverlayContainer : public QWidget class OverlayContainer : public QWidget
{ {
Q_OBJECT Q_OBJECT
@@ -55,14 +49,11 @@ protected:
void paintEvent(QPaintEvent* e) override; 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); QPainter p(this);
@@ -70,24 +61,11 @@ void OverlayContainer::paintEvent(QPaintEvent *e)
QWidget::paintEvent(e); QWidget::paintEvent(e);
} }
LtsDialog::LtsDialog(QWidget* parent, ButtonCombination buttonCombination, bool closeable) LtsDialog::LtsDialog(QWidget* parent, ButtonCombination buttonCombination, bool closeable)
: QWidget() : QWidget(), m_changesMade(false), m_firstShow(true), m_baseLayoutWidget(nullptr), m_isClosable(closeable),
, m_changesMade(false) m_noLockTopic(false), m_unchangeableDialog(false), m_dialogHelper(new LtsDialogHelper(nullptr)), m_topicInfo(),
, m_firstShow(true) m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("LtsWidget.LtsDialog")), m_buttonBox(nullptr),
, m_baseLayoutWidget(nullptr) m_uiRequirements(new UiRequirementList())
, m_isClosable(closeable)
, m_noLockTopic(false)
, m_unchangeableDialog(false)
, m_dialogHelper(new LtsDialogHelper(nullptr))
, m_buttonBox(nullptr)
, m_uiRequirements(new UiRequirementList())
.getNGLLogger("LtsWidget.LtsDialog"))
{ {
Q_UNUSED(parent); Q_UNUSED(parent);
@@ -96,39 +74,19 @@ LtsDialog::LtsDialog(QWidget *parent, ButtonCombination buttonCombination, bool
m_dialogHelper->setDialog(this); m_dialogHelper->setDialog(this);
m_buttonBox = m_dialogHelper->getButtonBox(); m_buttonBox = m_dialogHelper->getButtonBox();
addDebugMenuButton(); addDebugMenuButton();
connect(m_buttonBox->getButton(DialogButton::Close), &QPushButton::clicked, this, &LtsDialog::slotClose); connect(m_buttonBox->getButton(DialogButton::Close), &QPushButton::clicked, this, &LtsDialog::slotClose);
switch (buttonCombination) switch (buttonCombination)
{ {
case ButtonCombination::OkCancel: case ButtonCombination::OkCancel: {
{
m_buttonBox->getButton(DialogButton::Close)->setText(tr("Cancel")); m_buttonBox->getButton(DialogButton::Close)->setText(tr("Cancel"));
connect(m_buttonBox->getButton(DialogButton::Ok), &QPushButton::clicked, this, &LtsDialog::slotOkay); connect(m_buttonBox->getButton(DialogButton::Ok), &QPushButton::clicked, this, &LtsDialog::slotOkay);
break; break;
} }
case ButtonCombination::OkApplyCancel: case ButtonCombination::OkApplyCancel: {
{
m_buttonBox->getButton(DialogButton::Close)->setText(tr("Cancel")); m_buttonBox->getButton(DialogButton::Close)->setText(tr("Cancel"));
connect(m_buttonBox->getButton(DialogButton::Ok), &QPushButton::clicked, this, &LtsDialog::slotOkay); connect(m_buttonBox->getButton(DialogButton::Ok), &QPushButton::clicked, this, &LtsDialog::slotOkay);
connect(m_buttonBox->getButton(DialogButton::Apply), &QPushButton::clicked, this, &LtsDialog::slotApply); connect(m_buttonBox->getButton(DialogButton::Apply), &QPushButton::clicked, this, &LtsDialog::slotApply);
@@ -136,16 +94,14 @@ LtsDialog::LtsDialog(QWidget *parent, ButtonCombination buttonCombination, bool
break; break;
} }
case ButtonCombination::CloseOnly: case ButtonCombination::CloseOnly: {
{
m_buttonBox->getButton(DialogButton::Ok)->setVisible(false); m_buttonBox->getButton(DialogButton::Ok)->setVisible(false);
setUnchangeable(); setUnchangeable();
break; break;
} }
default: default:
case ButtonCombination::SeamlessDialog: case ButtonCombination::SeamlessDialog: {
{
m_buttonBox->setVisible(false); m_buttonBox->setVisible(false);
setContentsMargins(0, 0, 0, 0); setContentsMargins(0, 0, 0, 0);
m_dialogHelper->setContentsMargins(0, 0, 0, 0); m_dialogHelper->setContentsMargins(0, 0, 0, 0);
@@ -155,7 +111,6 @@ LtsDialog::LtsDialog(QWidget *parent, ButtonCombination buttonCombination, bool
if (l) if (l)
{ {
l->setContentsMargins(0, 0, 0, 0); l->setContentsMargins(0, 0, 0, 0);
l->setMargin(0);
} }
else else
{ {
@@ -173,7 +128,6 @@ LtsDialog::LtsDialog(QWidget *parent, ButtonCombination buttonCombination, bool
} }
} }
LtsDialog::~LtsDialog() LtsDialog::~LtsDialog()
{ {
delete m_uiRequirements; delete m_uiRequirements;
@@ -181,13 +135,9 @@ LtsDialog::~LtsDialog()
if (m_overlayWidget) if (m_overlayWidget)
m_overlayWidget->setParent(nullptr); 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_overlayContainer)
@@ -198,7 +148,6 @@ void LtsDialog::setOverlay(QWidget *widget)
m_overlayWidget->setParent(nullptr); m_overlayWidget->setParent(nullptr);
m_overlayWidget->hide(); m_overlayWidget->hide();
m_overlayWidget = nullptr; m_overlayWidget = nullptr;
} }
m_overlayContainer->hide(); m_overlayContainer->hide();
@@ -208,19 +157,14 @@ void LtsDialog::setOverlay(QWidget *widget)
m_overlayContainer = nullptr; m_overlayContainer = nullptr;
} }
OverlayContainer* overlayContainer = new OverlayContainer(m_dialogHelper); OverlayContainer* overlayContainer = new OverlayContainer(m_dialogHelper);
connect(m_dialogHelper.data(), &LtsDialogHelper::signalSizeChanged, connect(m_dialogHelper.data(), &LtsDialogHelper::signalSizeChanged, overlayContainer,
overlayContainer, [overlayContainer](const QSize &size) [overlayContainer](const QSize& size) { overlayContainer->setGeometry(QRect(QPoint(0, 0), size)); });
{
overlayContainer->setGeometry(QRect(QPoint(0, 0), size));
});
overlayContainer->setGeometry(QRect(QPoint(0, 0), m_dialogHelper->size())); overlayContainer->setGeometry(QRect(QPoint(0, 0), m_dialogHelper->size()));
m_overlayContainer = overlayContainer; m_overlayContainer = overlayContainer;
QHBoxLayout* l = new QHBoxLayout; QHBoxLayout* l = new QHBoxLayout;
m_overlayContainer->setLayout(l); m_overlayContainer->setLayout(l);
@@ -228,8 +172,7 @@ void LtsDialog::setOverlay(QWidget *widget)
l->addWidget(widget, 0, Qt::AlignCenter); l->addWidget(widget, 0, Qt::AlignCenter);
widget->show(); widget->show();
connect(widget, &QWidget::destroyed, connect(widget, &QWidget::destroyed, m_overlayContainer.data(), &QObject::deleteLater);
m_overlayContainer.data(), &QObject::deleteLater);
m_overlayWidget = widget; m_overlayWidget = widget;
@@ -237,7 +180,6 @@ void LtsDialog::setOverlay(QWidget *widget)
m_overlayContainer->raise(); m_overlayContainer->raise();
} }
void LtsDialog::unsetOverlay() void LtsDialog::unsetOverlay()
{ {
if (m_overlayWidget) if (m_overlayWidget)
@@ -250,19 +192,16 @@ void LtsDialog::unsetOverlay()
m_overlayContainer->deleteLater(); m_overlayContainer->deleteLater();
} }
LtsDialogHelper* LtsDialog::getHelper() LtsDialogHelper* LtsDialog::getHelper()
{ {
return m_dialogHelper; return m_dialogHelper;
} }
LtsBaseLayoutWidget* LtsDialog::baseLayoutWidget() LtsBaseLayoutWidget* LtsDialog::baseLayoutWidget()
{ {
return m_baseLayoutWidget; return m_baseLayoutWidget;
} }
void LtsDialog::setOnlineHelpFilename(const QString& fileName) void LtsDialog::setOnlineHelpFilename(const QString& fileName)
{ {
m_onlineHelpFileName = fileName; m_onlineHelpFileName = fileName;
@@ -274,16 +213,11 @@ void LtsDialog::setOnlineHelpFilename(const QString &fileName)
if (LtsSessionData::LtsSessionData::getInstance()->isTablet() && strcmp(PROJECTBUILD, "guez") == 0) if (LtsSessionData::LtsSessionData::getInstance()->isTablet() && strcmp(PROJECTBUILD, "guez") == 0)
return; return;
connect(btn, &QPushButton::clicked, connect(btn, &QPushButton::clicked, this, [this]() { emit signalShowOnlineHelp(m_onlineHelpFileName); });
this, [this]()
{
emit signalShowOnlineHelp(m_onlineHelpFileName);
});
btn->setVisible(true); btn->setVisible(true);
} }
void LtsDialog::addDebugMenuButton() void LtsDialog::addDebugMenuButton()
{ {
#ifdef LTS_DEBUG #ifdef LTS_DEBUG
@@ -298,14 +232,12 @@ void LtsDialog::addDebugMenuButton()
menu->addAction(QStringLiteral("set closable"), this, [this]() { m_isClosable = true; }); menu->addAction(QStringLiteral("set closable"), this, [this]() { m_isClosable = true; });
menu->addAction(QStringLiteral("set unclosable"), this, [this]() { m_isClosable = false; }); menu->addAction(QStringLiteral("set unclosable"), this, [this]() { m_isClosable = false; });
menu->addAction(QStringLiteral("clear requirements"), this, [this] { m_uiRequirements->clear(); }); menu->addAction(QStringLiteral("clear requirements"), this, [this] { m_uiRequirements->clear(); });
menu->addAction(QStringLiteral("enable all button box buttons"), this, [this]() menu->addAction(QStringLiteral("enable all button box buttons"), this, [this]() {
{
const auto children = m_buttonBox->findChildren<QPushButton*>(); const auto children = m_buttonBox->findChildren<QPushButton*>();
for (QPushButton* pb : children) for (QPushButton* pb : children)
pb->setEnabled(true); pb->setEnabled(true);
}); });
menu->addAction(QStringLiteral("show button box button .."), this, [this]() menu->addAction(QStringLiteral("show button box button .."), this, [this]() {
{
QString buttonObjectName = QInputDialog::getText(this, QString(), QStringLiteral("Enter button object name")); QString buttonObjectName = QInputDialog::getText(this, QString(), QStringLiteral("Enter button object name"));
if (buttonObjectName.isEmpty()) if (buttonObjectName.isEmpty())
return; return;
@@ -326,7 +258,8 @@ void LtsDialog::addDebugMenuButton()
for (QPushButton* pb : buttons) for (QPushButton* pb : buttons)
buttonStringList += pb->objectName(); buttonStringList += pb->objectName();
LtsMessageDialog::showMessage(this, QStringLiteral("button ambiguous: %1").arg(buttonStringList.join(QStringLiteral(", ")))); LtsMessageDialog::showMessage(
this, QStringLiteral("button ambiguous: %1").arg(buttonStringList.join(QStringLiteral(", "))));
return; return;
} }
@@ -339,7 +272,6 @@ void LtsDialog::addDebugMenuButton()
#endif #endif
} }
void LtsDialog::updateWindowTitle() void LtsDialog::updateWindowTitle()
{ {
QString completeTitle = m_title; QString completeTitle = m_title;
@@ -355,14 +287,12 @@ void LtsDialog::updateWindowTitle()
m_dialogHelper->setWindowTitle(completeTitle); m_dialogHelper->setWindowTitle(completeTitle);
} }
void LtsDialog::setWindowTitle(const QString& title) void LtsDialog::setWindowTitle(const QString& title)
{ {
m_title = title; m_title = title;
updateWindowTitle(); updateWindowTitle();
} }
void LtsDialog::setBaseLayoutWidget(LtsBaseLayoutWidget* baseLayoutWidget) void LtsDialog::setBaseLayoutWidget(LtsBaseLayoutWidget* baseLayoutWidget)
{ {
m_baseLayoutWidget = baseLayoutWidget; m_baseLayoutWidget = baseLayoutWidget;
@@ -374,36 +304,46 @@ void LtsDialog::setIdentifier(const QString &identifier)
tableColumnOrganiserSetting(); tableColumnOrganiserSetting();
} }
void LtsDialog::addConnections(QWidget* widget) void LtsDialog::addConnections(QWidget* widget)
{ {
if (addChangesMadeSignal<QLineEdit>(widget, &QLineEdit::textChanged)) return; if (addChangesMadeSignal<QLineEdit>(widget, &QLineEdit::textChanged))
if (addChangesMadeSignal<QDateTimeEdit>(widget, &QDateTimeEdit::dateTimeChanged)) return; return;
if (addChangesMadeSignal<QComboBox>(widget, &QComboBox::currentTextChanged)) return; if (addChangesMadeSignal<QDateTimeEdit>(widget, &QDateTimeEdit::dateTimeChanged))
if (addChangesMadeSignal<QCheckBox>(widget, &QCheckBox::stateChanged)) return; return;
if (addChangesMadeSignal<QSpinBox>(widget, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged))) return; if (addChangesMadeSignal<QComboBox>(widget, &QComboBox::currentTextChanged))
if (addChangesMadeSignal<QDoubleSpinBox>(widget, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged))) return; return;
if (addChangesMadeSignal<QSlider>(widget, &QSlider::valueChanged)) return; if (addChangesMadeSignal<QCheckBox>(widget, &QCheckBox::stateChanged))
if (addChangesMadeSignal<QPlainTextEdit>(widget, &QPlainTextEdit::textChanged)) return; return;
if (addChangesMadeSignal<QTextEdit>(widget, &QTextEdit::textChanged)) return; if (addChangesMadeSignal<QSpinBox>(widget, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged)))
if (addChangesMadeSignal<QAbstractButton>(widget, &QAbstractButton::toggled)) return; return;
if (addChangesMadeSignal<LtsDateTimeEdit>(widget, &LtsDateTimeEdit::dateTimeChanged)) return; if (addChangesMadeSignal<QDoubleSpinBox>(
widget, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged)))
return;
if (addChangesMadeSignal<QSlider>(widget, &QSlider::valueChanged))
return;
if (addChangesMadeSignal<QPlainTextEdit>(widget, &QPlainTextEdit::textChanged))
return;
if (addChangesMadeSignal<QTextEdit>(widget, &QTextEdit::textChanged))
return;
if (addChangesMadeSignal<QAbstractButton>(widget, &QAbstractButton::toggled))
return;
if (addChangesMadeSignal<LtsDateTimeEdit>(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,
bool LtsDialog::addDialogFixed(LtsDialog *dialog, const char *menuGroupUntranslated, const QString &identifier, const LayoutArea &layoutArea, bool setClosable, bool focusNewTab) 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,
bool LtsDialog::addDialog(LtsDialog *dialog, const QString &menuGroup, const QString &identifier, const LayoutArea &layoutArea, bool setClosable, bool focusNewTab) const LayoutArea& layoutArea, bool setClosable, bool focusNewTab)
{ {
if (!m_baseLayoutWidget) if (!m_baseLayoutWidget)
{ {
@@ -414,7 +354,6 @@ bool LtsDialog::addDialog(LtsDialog *dialog, const QString &menuGroup, const QSt
return m_baseLayoutWidget->addWidget(dialog, menuGroup, identifier, layoutArea, setClosable, focusNewTab); return m_baseLayoutWidget->addWidget(dialog, menuGroup, identifier, layoutArea, setClosable, focusNewTab);
} }
bool LtsDialog::amIFocused() const bool LtsDialog::amIFocused() const
{ {
if (!m_baseLayoutWidget) if (!m_baseLayoutWidget)
@@ -426,7 +365,6 @@ bool LtsDialog::amIFocused() const
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) if (!m_baseLayoutWidget)
@@ -438,7 +376,6 @@ bool LtsDialog::focusDialog(const QString &menuGroup, const QString &identifier,
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);
@@ -454,17 +391,11 @@ void LtsDialog::showEvent(QShowEvent *event)
m_unchangeableDialog = true; m_unchangeableDialog = true;
m_firstShow = false; m_firstShow = false;
QList<QWidget*> listenWidgets = findChildren<QWidget*>(); QList<QWidget*> listenWidgets = findChildren<QWidget*>();
for (auto i = listenWidgets.begin(); i != listenWidgets.end(); ++i) for (auto i = listenWidgets.begin(); i != listenWidgets.end(); ++i)
{ {
QWidget* widget = *i; QWidget* widget = *i;
QVariant isConst = widget->property("const"); QVariant isConst = widget->property("const");
@@ -483,7 +414,6 @@ void LtsDialog::showEvent(QShowEvent *event)
m_unchangeableDialog = tmp; m_unchangeableDialog = tmp;
} }
void LtsDialog::tryLockTopic() void LtsDialog::tryLockTopic()
{ {
TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"; TRACE_LOG(m_logger) << Q_FUNC_INFO << " START";
@@ -499,19 +429,10 @@ void LtsDialog::tryLockTopic()
if (m_noLockTopic) if (m_noLockTopic)
return; return;
bool bIsConnected = isSignalConnected(QMetaMethod::fromSignal(&LtsDialog::signalLockTopic)); bool bIsConnected = isSignalConnected(QMetaMethod::fromSignal(&LtsDialog::signalLockTopic));
DEBUG_LOG(m_logger) << Q_FUNC_INFO DEBUG_LOG(m_logger) << Q_FUNC_INFO << " signalLockTopic(): "
<< " signalLockTopic(): " << ", TopicName =" << m_topicInfo.topicName() << ", entity =" << m_topicInfo.entityId()
<< ", TopicName =" << m_topicInfo.topicName()
<< ", entity =" << m_topicInfo.entityId()
<< ", signalLockTopic isConnected=" << bIsConnected; << ", signalLockTopic isConnected=" << bIsConnected;
if (bIsConnected) if (bIsConnected)
@@ -526,13 +447,11 @@ void LtsDialog::tryLockTopic()
void LtsDialog::initTopicLockHandler(const QString& topicName, int entityId) void LtsDialog::initTopicLockHandler(const QString& topicName, int entityId)
{ {
m_topicInfo.setTopicName(topicName); m_topicInfo.setTopicName(topicName);
m_topicInfo.setEntity(entityId); m_topicInfo.setEntity(entityId);
m_topicInfo.setValid(); m_topicInfo.setValid();
} }
void LtsDialog::tryLockTopicNew() void LtsDialog::tryLockTopicNew()
{ {
TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"; TRACE_LOG(m_logger) << Q_FUNC_INFO << " START";
@@ -546,8 +465,6 @@ void LtsDialog::tryLockTopicNew(const QString &topicName, int entityId)
<< ", topicName='" << topicName << "'" << ", topicName='" << topicName << "'"
<< ", entityId=" << entityId; << ", entityId=" << entityId;
if (m_topicInfo.entityId() != entityId) if (m_topicInfo.entityId() != entityId)
{ {
DEBUG_LOG(m_logger) << Q_FUNC_INFO << " topicName='" << topicName << "'" DEBUG_LOG(m_logger) << Q_FUNC_INFO << " topicName='" << topicName << "'"
@@ -555,7 +472,6 @@ void LtsDialog::tryLockTopicNew(const QString &topicName, int entityId)
m_topicInfo.setLocked(false); m_topicInfo.setLocked(false);
} }
m_topicInfo.setTopicName(topicName); m_topicInfo.setTopicName(topicName);
m_topicInfo.setEntity(entityId); m_topicInfo.setEntity(entityId);
m_topicInfo.setValid(); m_topicInfo.setValid();
@@ -568,12 +484,12 @@ void LtsDialog::tryLockTopicNew(const QString &topicName, int entityId)
void LtsDialog::triggerTopicLock() void LtsDialog::triggerTopicLock()
{ {
TRACE_LOG(m_logger) << Q_FUNC_INFO << " START" << " !!trigger!!"; TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"
<< " !!trigger!!";
tryLockTopic(); tryLockTopic();
TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"; 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();
@@ -583,10 +499,6 @@ void LtsDialog::translate(const QString &title)
setWindowTitle(title); setWindowTitle(title);
if (!isAlreadyUnchangeable) if (!isAlreadyUnchangeable)
setUnchangeable(false); setUnchangeable(false);
@@ -598,7 +510,6 @@ void LtsDialog::translate(const QString &title)
{ {
connect(b, &QPushButton::clicked, this, &LtsDialog::onReadOnlyButtonClicked, Qt::UniqueConnection); connect(b, &QPushButton::clicked, this, &LtsDialog::onReadOnlyButtonClicked, Qt::UniqueConnection);
b->setVisible(isNowAlreadyUnchangeable && !m_topicLockedBy.isEmpty()); b->setVisible(isNowAlreadyUnchangeable && !m_topicLockedBy.isEmpty());
if (b->isVisible()) if (b->isVisible())
b->setToolTip(tr("Locked by: %1").arg(m_topicLockedBy)); b->setToolTip(tr("Locked by: %1").arg(m_topicLockedBy));
@@ -608,8 +519,6 @@ void LtsDialog::translate(const QString &title)
} }
} }
void LtsDialog::slotLock(const QString& lockedBy) void LtsDialog::slotLock(const QString& lockedBy)
{ {
setUnchangeable(true); setUnchangeable(true);
@@ -620,7 +529,6 @@ void LtsDialog::slotLock(const QString &lockedBy)
retranslate(); retranslate();
} }
void LtsDialog::slotUnlock() void LtsDialog::slotUnlock()
{ {
setUnchangeable(false); setUnchangeable(false);
@@ -631,7 +539,6 @@ void LtsDialog::slotUnlock()
retranslate(); retranslate();
} }
void LtsDialog::lock() void LtsDialog::lock()
{ {
setWidgetsReadonly<QLineEdit>(true); setWidgetsReadonly<QLineEdit>(true);
@@ -653,7 +560,6 @@ void LtsDialog::lock()
setWidgetsDisabled<QPushButton>(true); setWidgetsDisabled<QPushButton>(true);
} }
void LtsDialog::unlock() void LtsDialog::unlock()
{ {
restoreReadonly<QLineEdit>(); restoreReadonly<QLineEdit>();
@@ -674,7 +580,6 @@ void LtsDialog::unlock()
restoreEnabled<QListWidget>(); restoreEnabled<QListWidget>();
} }
void LtsDialog::slotChangesMade() void LtsDialog::slotChangesMade()
{ {
if (m_unchangeableDialog) if (m_unchangeableDialog)
@@ -689,21 +594,17 @@ void LtsDialog::slotChangesMade()
emit signalChangesMade(); emit signalChangesMade();
} }
void LtsDialog::resetChanges() void LtsDialog::resetChanges()
{ {
m_changesMade = false; m_changesMade = false;
updateWindowTitle(); updateWindowTitle();
m_buttonBox->getButton(DialogButton::Ok)->setEnabled(false); m_buttonBox->getButton(DialogButton::Ok)->setEnabled(false);
m_buttonBox->getButton(DialogButton::Apply)->setEnabled(false); m_buttonBox->getButton(DialogButton::Apply)->setEnabled(false);
emit signalChangesReset(); emit signalChangesReset();
} }
bool LtsDialog::_apply() bool LtsDialog::_apply()
{ {
if (m_uiRequirements->checkRequirements(this) && apply()) if (m_uiRequirements->checkRequirements(this) && apply())
@@ -715,32 +616,27 @@ bool LtsDialog::_apply()
return false; return false;
} }
Button LtsDialog::askApplyDiscardCancel() 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()) if (_apply())
_close(); _close();
} }
void LtsDialog::slotHide() void LtsDialog::slotHide()
{ {
_hide(); _hide();
} }
void LtsDialog::slotClose() void LtsDialog::slotClose()
{ {
@@ -771,23 +667,19 @@ void LtsDialog::onReadOnlyButtonClicked()
LtsWidgets::LtsMessageDialog::showMessage(this, tr("Locked by: %1").arg(m_topicLockedBy)); LtsWidgets::LtsMessageDialog::showMessage(this, tr("Locked by: %1").arg(m_topicLockedBy));
} }
void LtsDialog::closeRequest() void LtsDialog::closeRequest()
{ {
slotClose(); slotClose();
} }
void LtsDialog::_hide() void LtsDialog::_hide()
{ {
if (m_dialogHelper != nullptr) if (m_dialogHelper != nullptr)
{ {
emit signalHide(m_dialogHelper); emit signalHide(m_dialogHelper);
} }
} }
void LtsDialog::_close() void LtsDialog::_close()
{ {
resetChanges(); resetChanges();
@@ -802,9 +694,6 @@ void LtsDialog::_discard()
_close(); _close();
} }
} } // namespace LtsWidgets
#include "lts_dialog.moc" #include "lts_dialog.moc"
+127 -128
View File
@@ -1,57 +1,79 @@
#pragma once #pragma once
#include <QObject>
#include "lts_base.h" #include "lts_base.h"
#include "lts_dialog_button_box.h"
#include "ltswidgets_export.h" #include "ltswidgets_export.h"
#include "requirement_widget.h" #include "requirement_widget.h"
#include "lts_dialog_button_box.h"
#include <NGLLogger/NGLLoggerBootstrap.h> #include <NGLLogger/NGLLoggerBootstrap.h>
#include <QPushButton>
#include <QLineEdit>
#include <QComboBox>
#include <QCheckBox> #include <QCheckBox>
#include <QSpinBox> #include <QComboBox>
#include <QDateTimeEdit> #include <QDateTimeEdit>
#include <QSlider> #include <QDebug>
#include <QLineEdit>
#include <QObject>
#include <QPlainTextEdit> #include <QPlainTextEdit>
#include <QPointer>
#include <QPushButton>
#include <QRadioButton>
#include <QSlider>
#include <QSpinBox>
#include <QTextEdit> #include <QTextEdit>
#include <QWidget> #include <QWidget>
#include <QRadioButton>
#include <QPointer>
#include <QDebug>
namespace LtsWidgets namespace LtsWidgets
{ {
class TopicInfo class TopicInfo
{ {
public: public:
int entityId() const { return m_entityId; } int entityId() const
const QString &topicName() const { return m_topicName; } {
bool isLocked() const { return m_locked; } return m_entityId;
bool isValid() const { return m_valid; } }
void setEntity(int entityId) { m_entityId = entityId; } const QString& topicName() const
void setTopicName(const QString &topicName) { m_topicName = topicName; } {
void setLocked(bool locked = true) { m_locked = locked; } return m_topicName;
void setValid() { m_valid = true; } }
bool isLocked() const
{
return m_locked;
}
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: private:
NGL::INGLLogger &m_logger;
QString m_topicName; QString m_topicName;
int m_entityId{0}; int m_entityId{0};
bool m_locked{false}; bool m_locked{false};
bool m_valid{false}; bool m_valid{false};
}; };
class LtsBaseLayoutWidget; class LtsBaseLayoutWidget;
class LtsDialogHelper; class LtsDialogHelper;
class LtsProgressDialogHelper; class LtsProgressDialogHelper;
@@ -59,22 +81,15 @@ class LtsDialogButtonBox;
class LtsToolBarArea; class LtsToolBarArea;
class OverlayContainer; class OverlayContainer;
enum class ButtonCombination {
enum class ButtonCombination
{
OkApplyCancel, OkApplyCancel,
OkCancel, OkCancel,
CloseOnly, CloseOnly,
SeamlessDialog, SeamlessDialog,
}; };
class LTSWIDGETS_EXPORT LtsDialog : public QWidget class LTSWIDGETS_EXPORT LtsDialog : public QWidget
{ {
Q_OBJECT Q_OBJECT
@@ -83,49 +98,77 @@ class LTSWIDGETS_EXPORT LtsDialog : public QWidget
public: public:
static int s_object_count; static int s_object_count;
explicit LtsDialog(QWidget* parent = nullptr, ButtonCombination buttonCombination = ButtonCombination::CloseOnly,
bool closeable = true);
explicit LtsDialog(QWidget *parent = nullptr, ButtonCombination buttonCombination = ButtonCombination::CloseOnly, bool closeable = true);
~LtsDialog(); ~LtsDialog();
LtsDialogHelper* getHelper(); LtsDialogHelper* getHelper();
bool hasUnsavedChanges() const { return m_changesMade || m_currentlyBlocking; } bool hasUnsavedChanges() const
{
return m_changesMade || m_currentlyBlocking;
}
virtual void retranslate() = 0; virtual void retranslate() = 0;
void closeRequest(); void closeRequest();
void setUnchangeable(bool unchangeable = true); void setUnchangeable(bool unchangeable = true);
bool unchangeable() const { return m_unchangeableDialog; }
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);
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,
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 setClosable = true, bool focusNewTab = true);
bool focusDialog(const QString& menuGroup, const QString& identifier, const LayoutArea& layoutArea); bool focusDialog(const QString& menuGroup, const QString& identifier, const LayoutArea& layoutArea);
bool amIFocused() const; bool amIFocused() const;
void setBaseLayoutWidget(LtsBaseLayoutWidget* baseLayoutWidget); void setBaseLayoutWidget(LtsBaseLayoutWidget* baseLayoutWidget);
void __unchange__() { resetChanges(); }
void setClosable(bool closable) { m_isClosable = closable; } void __unchange__()
bool isClosable() const { return m_isClosable; } {
resetChanges();
}
void setClosable(bool closable)
{
m_isClosable = closable;
}
bool isClosable() const
{
return m_isClosable;
}
virtual void aboutToClose() {} virtual void aboutToClose() {}
void setMenuGroup(const QString &menuGroup) { m_menuGroup = menuGroup; }
const QString &menuGroup() const { return m_menuGroup; } void setMenuGroup(const QString& menuGroup)
{
m_menuGroup = menuGroup;
}
const QString& menuGroup() const
{
return m_menuGroup;
}
void setIdentifier(const QString& identifier); void setIdentifier(const QString& identifier);
virtual void tableColumnOrganiserSetting(){}; virtual void tableColumnOrganiserSetting(){};
const QString &identifier() const { return m_identifier; }
const QString& identifier() const
{
return m_identifier;
}
void setOverlay(QWidget* widget); void setOverlay(QWidget* widget);
void unsetOverlay(); void unsetOverlay();
static inline void setMinWidthForWidgetHelper(QWidget* w) static inline void setMinWidthForWidgetHelper(QWidget* w)
{ {
int width = w->sizeHint().width(); int width = w->sizeHint().width();
@@ -137,48 +180,29 @@ public:
return m_title; return m_title;
} }
void tryLockTopicNew(); void tryLockTopicNew();
virtual void tryLockTopicNew(const QString& topicName, int entityId = -1); virtual void tryLockTopicNew(const QString& topicName, int entityId = -1);
void triggerTopicLock(); void triggerTopicLock();
void setOnlineHelpFilename(const QString& fileName); void setOnlineHelpFilename(const QString& fileName);
void setCurrentlyBlocking(bool currentlyBlocking = true) { m_currentlyBlocking = currentlyBlocking; }
void setCurrentlyBlocking(bool currentlyBlocking = true)
{
m_currentlyBlocking = currentlyBlocking;
}
signals: signals:
void startMainSelect(LtsWidgets::LayoutArea); void startMainSelect(LtsWidgets::LayoutArea);
void endMainSelect(LtsWidgets::LayoutArea); void endMainSelect(LtsWidgets::LayoutArea);
void signalChangesMade(); void signalChangesMade();
void signalHide(QObject* object); void signalHide(QObject* object);
void signalChangesReset(); void signalChangesReset();
void signalFocused(); void signalFocused();
@@ -187,15 +211,10 @@ signals:
void signalShowOnlineHelp(const QString& fileName); void signalShowOnlineHelp(const QString& fileName);
protected: protected:
void translate(const QString& title); void translate(const QString& title);
template <typename T> template <typename T>
void translate(T* ui, const QString& title) void translate(T* ui, const QString& title)
{ {
translate(title); translate(title);
@@ -213,7 +232,6 @@ protected:
template <typename T> template <typename T>
void translate(T* ui, const QString& custom, bool isNew, const QString& title) void translate(T* ui, const QString& custom, bool isNew, const QString& title)
{ {
QString newTitle; QString newTitle;
@@ -233,7 +251,6 @@ protected:
else else
newTitle = (tr("Edit %1: %2").arg(title, custom)); newTitle = (tr("Edit %1: %2").arg(title, custom));
tryLockTopicNew(); tryLockTopicNew();
} }
} }
@@ -247,44 +264,40 @@ protected:
translate(ui, newTitle); translate(ui, newTitle);
} }
template <typename T> template <typename T>
void translate(T* ui, const QString& customUniqueTopicName, int topicId, const QString& custom,
void translate(T* ui, const QString &customUniqueTopicName, int topicId, const QString &custom, const QString &title) const QString& title)
{ {
Q_UNUSED(customUniqueTopicName); Q_UNUSED(customUniqueTopicName);
initTopicLockHandler(customUniqueTopicName, topicId); initTopicLockHandler(customUniqueTopicName, topicId);
translate(ui, custom , translate(ui, custom, (topicId < 1), title);
(topicId < 1 ),
title);
} }
template <typename T, typename S> template <typename T, typename S>
void translate(T* ui, const S& data, const QString& custom, const QString& title) void translate(T* ui, const S& data, const QString& custom, const QString& title)
{ {
translate(ui, QString::fromUtf8(typeid(data).name()), data.id(), custom, title); translate(ui, QString::fromUtf8(typeid(data).name()), data.id(), custom, title);
} }
template <typename T, typename S> template <typename T, typename S>
void translate(T* ui, const S& data, const QString& title) void translate(T* ui, const S& data, const QString& title)
{ {
translate(ui, data, QString::fromStdString(data.name()), title); translate(ui, data, QString::fromStdString(data.name()), title);
} }
virtual void dialogCanceled() {} virtual void dialogCanceled() {}
LtsBaseLayoutWidget* baseLayoutWidget(); LtsBaseLayoutWidget* baseLayoutWidget();
void setNoTopicLock() { m_noLockTopic = true; }
void setNoTopicLock()
{
m_noLockTopic = true;
}
private: private:
friend class LtsDialogHelper; friend class LtsDialogHelper;
@@ -303,13 +316,13 @@ private:
bool m_noLockTopic; bool m_noLockTopic;
bool m_unchangeableDialog; bool m_unchangeableDialog;
QPointer<LtsDialogHelper> m_dialogHelper; QPointer<LtsDialogHelper> m_dialogHelper;
NGL::INGLLogger& m_logger;
QString m_title; QString m_title;
QString m_onlineHelpFileName; QString m_onlineHelpFileName;
QString m_menuGroup; QString m_menuGroup;
QString m_identifier; QString m_identifier;
QPointer<OverlayContainer> m_overlayContainer; QPointer<OverlayContainer> m_overlayContainer;
QPointer<QWidget> m_overlayWidget; QPointer<QWidget> m_overlayWidget;
@@ -322,14 +335,11 @@ private:
void tryLockTopic(); void tryLockTopic();
void initTopicLockHandler(const QString& topicName, int entityId); void initTopicLockHandler(const QString& topicName, int entityId);
void setWindowTitle(const QString& title); void setWindowTitle(const QString& title);
void updateWindowTitle(); void updateWindowTitle();
void addConnections(QWidget* widget); void addConnections(QWidget* widget);
template <typename WidgetType, typename SignalFunc> template <typename WidgetType, typename SignalFunc> bool addChangesMadeSignal(QWidget* widget, SignalFunc signal)
bool addChangesMadeSignal(QWidget *widget, SignalFunc signal)
{ {
WidgetType* concreteWidget = qobject_cast<WidgetType*>(widget); WidgetType* concreteWidget = qobject_cast<WidgetType*>(widget);
@@ -340,9 +350,7 @@ private:
return true; return true;
} }
template <typename WidgetType> void setWidgetsReadonly(bool readonly)
template <typename WidgetType>
void setWidgetsReadonly(bool readonly)
{ {
const auto children = findChildren<WidgetType*>(); const auto children = findChildren<WidgetType*>();
for (WidgetType* widget : children) for (WidgetType* widget : children)
@@ -352,9 +360,7 @@ private:
} }
} }
template <typename WidgetType> void setWidgetsDisabled(bool disabled)
template <typename WidgetType>
void setWidgetsDisabled(bool disabled)
{ {
const auto children = findChildren<WidgetType*>(); const auto children = findChildren<WidgetType*>();
for (WidgetType* widget : children) for (WidgetType* widget : children)
@@ -364,8 +370,7 @@ private:
} }
} }
template <typename WidgetType> template <typename WidgetType> void restoreReadonly()
void restoreReadonly()
{ {
const auto children = findChildren<WidgetType*>(); const auto children = findChildren<WidgetType*>();
for (WidgetType* widget : children) for (WidgetType* widget : children)
@@ -376,8 +381,7 @@ private:
} }
} }
template <typename WidgetType> template <typename WidgetType> void restoreEnabled()
void restoreEnabled()
{ {
const auto children = findChildren<WidgetType*>(); const auto children = findChildren<WidgetType*>();
for (WidgetType* widget : children) for (WidgetType* widget : children)
@@ -390,7 +394,6 @@ private:
public slots: public slots:
void slotChangesMade(); void slotChangesMade();
void slotHide(); void slotHide();
@@ -408,7 +411,11 @@ protected:
virtual void lock(); virtual void lock();
virtual void unlock(); virtual void unlock();
virtual bool apply() { return true; } virtual bool apply()
{
return true;
}
void showEvent(QShowEvent* event) override; void showEvent(QShowEvent* event) override;
Button askApplyDiscardCancel(); Button askApplyDiscardCancel();
@@ -416,10 +423,7 @@ protected:
UiRequirementList* m_uiRequirements; UiRequirementList* m_uiRequirements;
}; };
template <typename T> T* initDialog(T* dialog)
template<typename T>
T *initDialog(T *dialog)
{ {
if (!dialog->init()) if (!dialog->init())
{ {
@@ -429,9 +433,7 @@ T *initDialog(T *dialog)
return dialog; return dialog;
} }
template <typename T, typename... F> T* initDialog(T* dialog, F&&... f)
template<typename T, typename ... F>
T *initDialog(T *dialog, F&&... f)
{ {
if (!dialog->init(std::forward<F>(f)...)) if (!dialog->init(std::forward<F>(f)...))
{ {
@@ -441,9 +443,7 @@ T *initDialog(T *dialog, F&&... f)
return dialog; return dialog;
} }
template <typename T, typename... F> T* createThrowableDialog(F&&... f)
template<typename T, typename ... F>
T *createThrowableDialog(F&&... f)
{ {
T* dlg = nullptr; T* dlg = nullptr;
@@ -470,5 +470,4 @@ T *createThrowableDialog(F&&... f)
return dlg; return dlg;
} }
} // namespace LtsWidgets
}
+57 -63
View File
@@ -1,20 +1,19 @@
#include "lts_drag_icon.h" #include "lts_drag_icon.h"
#include <QAction>
#include <QButtonGroup>
#include <QDrag> #include <QDrag>
#include <QDragEnterEvent> #include <QDragEnterEvent>
#include <QDragLeaveEvent> #include <QDragLeaveEvent>
#include <QDropEvent> #include <QDropEvent>
#include <QMimeData>
#include <QAction>
#include <QVBoxLayout>
#include <QLabel> #include <QLabel>
#include <QMimeData>
#include <QPainter>
#include <QPixmap> #include <QPixmap>
#include <QToolButton> #include <QToolButton>
#include <QButtonGroup> #include <QVBoxLayout>
#include <QPainter>
namespace LtsWidgets namespace LtsWidgets
{ {
@@ -24,10 +23,7 @@ class LtsToolButton : public QToolButton
Q_OBJECT Q_OBJECT
public: public:
explicit LtsToolButton(QWidget* parent) explicit LtsToolButton(QWidget* parent)
: QToolButton(parent) : QToolButton(parent), m_sameWidgetDrop(false), m_isDraggable(true), m_startPos(QPoint())
, m_sameWidgetDrop(false)
, m_isDraggable(true)
, m_startPos(QPoint())
{ {
setAutoFillBackground(false); setAutoFillBackground(false);
setToolButtonStyle(Qt::ToolButtonTextUnderIcon); setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
@@ -39,17 +35,35 @@ public:
void mouseReleaseEvent(QMouseEvent* event) override; void mouseReleaseEvent(QMouseEvent* event) override;
void mouseMoveEvent(QMouseEvent* event) override; void mouseMoveEvent(QMouseEvent* event) override;
void dragEnterEvent(QDragEnterEvent* event) override; void dragEnterEvent(QDragEnterEvent* event) override;
void setSameWidgetDrop(bool drop) { m_sameWidgetDrop = drop; }
bool sameWidgetDrop() const { return m_sameWidgetDrop; } void setSameWidgetDrop(bool drop)
void setDraggable(bool isDraggable) { m_isDraggable = isDraggable; } {
m_sameWidgetDrop = drop;
}
bool sameWidgetDrop() const
{
return m_sameWidgetDrop;
}
void setDraggable(bool isDraggable)
{
m_isDraggable = isDraggable;
}
void dropEvent(QDropEvent* event) override void dropEvent(QDropEvent* event) override
{ {
emit newDropEvent(event); emit newDropEvent(event);
QToolButton::dropEvent(event); QToolButton::dropEvent(event);
} }
void addMimeData(const QString& mimeType, const QByteArray& data); void addMimeData(const QString& mimeType, const QByteArray& data);
bool removeMimeData(const QString& mimeType); bool removeMimeData(const QString& mimeType);
void removeAllMimeData() { m_mimeData.clear(); }
void removeAllMimeData()
{
m_mimeData.clear();
}
protected: protected:
void initButton(); void initButton();
@@ -64,67 +78,54 @@ private:
bool m_isDraggable; bool m_isDraggable;
QPoint m_startPos; QPoint m_startPos;
QMap<QString, QByteArray> m_mimeData; QMap<QString, QByteArray> m_mimeData;
}; };
LtsDragIcon::LtsDragIcon(QWidget* parent) LtsDragIcon::LtsDragIcon(QWidget* parent)
: QWidget(parent) : QWidget(parent), m_lay(nullptr), m_toolButton(nullptr), m_icon(), m_dragLabel(new QLabel(this)), m_text(),
, m_lay(nullptr) m_style(ButtonStyle::eAll), m_forceFixedSize(false), m_isDraggable(true), m_dropHandlerKey(0L),
, m_toolButton(nullptr) m_buttonSize(ButtonSize::eDefault), m_showDragIcon(true)
, 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); setAutoFillBackground(false);
initButton(); initButton();
} }
void LtsDragIcon::setStyleToButton() void LtsDragIcon::setStyleToButton()
{ {
if (nullptr == m_toolButton) return; if (nullptr == m_toolButton)
return;
switch (m_style) switch (m_style)
{ {
case ButtonStyle::eIconOnly: case ButtonStyle::eIconOnly: {
{
setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
m_toolButton->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); m_toolButton->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
setFixedSize(QSize(static_cast<int>(m_buttonSize), static_cast<int>(m_buttonSize))); setFixedSize(QSize(static_cast<int>(m_buttonSize), static_cast<int>(m_buttonSize)));
m_toolButton->setToolButtonStyle(Qt::ToolButtonIconOnly); m_toolButton->setToolButtonStyle(Qt::ToolButtonIconOnly);
} break; }
break;
case ButtonStyle::eTextOnly: case ButtonStyle::eTextOnly: {
{
setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed); setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
m_toolButton->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum); m_toolButton->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum);
setFixedSize(QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX)); setFixedSize(QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX));
m_toolButton->setToolButtonStyle(Qt::ToolButtonTextOnly); m_toolButton->setToolButtonStyle(Qt::ToolButtonTextOnly);
layout()->setSizeConstraint(QLayout::SetDefaultConstraint); layout()->setSizeConstraint(QLayout::SetDefaultConstraint);
} break; }
break;
case ButtonStyle::eTextNextToIcon: case ButtonStyle::eTextNextToIcon: {
{
setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed); setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
m_toolButton->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum); m_toolButton->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum);
setFixedSize(QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX)); setFixedSize(QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX));
m_toolButton->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); m_toolButton->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
layout()->setSizeConstraint(QLayout::SetDefaultConstraint); layout()->setSizeConstraint(QLayout::SetDefaultConstraint);
} break;
default: break;
} }
break;
default:
break;
}
} }
void LtsDragIcon::initButton() void LtsDragIcon::initButton()
{ {
@@ -146,9 +147,8 @@ void LtsDragIcon::initButton()
generateToolTip(); generateToolTip();
m_toolButton->setIconSize(QSize(static_cast<int>(m_buttonSize), static_cast<int>(m_buttonSize))); m_toolButton->setIconSize(QSize(static_cast<int>(m_buttonSize), static_cast<int>(m_buttonSize)));
QVBoxLayout* box = new QVBoxLayout(this); QVBoxLayout* box = new QVBoxLayout(this);
box->setMargin(0); box->setContentsMargins(0, 0, 0, 0);
box->setSpacing(0); box->setSpacing(0);
box->addWidget(m_toolButton); box->addWidget(m_toolButton);
@@ -175,14 +175,12 @@ 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_icon = icon;
(m_toolButton) ? m_toolButton->setIcon(modifyIcon(m_icon)) : initButton(); (m_toolButton) ? m_toolButton->setIcon(modifyIcon(m_icon)) : initButton();
} }
void LtsDragIcon::setMenu(QMenu* menu) void LtsDragIcon::setMenu(QMenu* menu)
{ {
if (nullptr == m_toolButton) if (nullptr == m_toolButton)
@@ -198,7 +196,6 @@ QMenu *LtsDragIcon::menu() const
return m_toolButton->menu(); return m_toolButton->menu();
} }
void LtsDragIcon::setText(const QString& text) void LtsDragIcon::setText(const QString& text)
{ {
m_text = text; m_text = text;
@@ -299,6 +296,7 @@ void LtsDragIcon::dragEnterEvent(QDragEnterEvent *e)
if (m_toolButton) if (m_toolButton)
m_toolButton->dragEnterEvent(e); m_toolButton->dragEnterEvent(e);
} }
void LtsDragIcon::dropEvent(QDropEvent* e) void LtsDragIcon::dropEvent(QDropEvent* e)
{ {
QWidget::dropEvent(e); QWidget::dropEvent(e);
@@ -313,7 +311,8 @@ void LtsDragIcon::setButtonStyle(ButtonStyle style)
void LtsDragIcon::setIconSize(ButtonSize buttonSize) void LtsDragIcon::setIconSize(ButtonSize buttonSize)
{ {
m_buttonSize = buttonSize; m_buttonSize = buttonSize;
(m_toolButton) ? m_toolButton->setIconSize(QSize(static_cast<int>(m_buttonSize), static_cast<int>(m_buttonSize))) : initButton(); (m_toolButton) ? m_toolButton->setIconSize(QSize(static_cast<int>(m_buttonSize), static_cast<int>(m_buttonSize)))
: initButton();
} }
void LtsDragIcon::setForceFixedSize(bool force) void LtsDragIcon::setForceFixedSize(bool force)
@@ -351,8 +350,6 @@ void LtsDragIcon::changeEvent(QEvent *event)
emit enabledChanged(isEnabled()); emit enabledChanged(isEnabled());
} }
void LtsToolButton::mousePressEvent(QMouseEvent* event) void LtsToolButton::mousePressEvent(QMouseEvent* event)
{ {
if (event->button() == Qt::LeftButton) if (event->button() == Qt::LeftButton)
@@ -360,7 +357,6 @@ void LtsToolButton::mousePressEvent(QMouseEvent *event)
QToolButton::mousePressEvent(event); QToolButton::mousePressEvent(event);
} }
void LtsToolButton::mouseReleaseEvent(QMouseEvent* event) void LtsToolButton::mouseReleaseEvent(QMouseEvent* event)
{ {
QToolButton::mouseReleaseEvent(event); QToolButton::mouseReleaseEvent(event);
@@ -370,7 +366,8 @@ void LtsToolButton::mouseMoveEvent(QMouseEvent *event)
{ {
if (!m_isDraggable) if (!m_isDraggable)
return; return;
if (event->buttons() & Qt::LeftButton) { if (event->buttons() & Qt::LeftButton)
{
int distance = (event->pos() - m_startPos).manhattanLength(); int distance = (event->pos() - m_startPos).manhattanLength();
if (distance >= 5) if (distance >= 5)
{ {
@@ -398,7 +395,8 @@ void LtsToolButton::performDrag(QMouseEvent *)
name = item->objectName(); name = item->objectName();
} }
item = item->parentWidget(); item = item->parentWidget();
if (nullptr == item) return; if (nullptr == item)
return;
dragIcon = dynamic_cast<LtsDragIcon*>(item); dragIcon = dynamic_cast<LtsDragIcon*>(item);
} }
QMimeData* mimeData = new QMimeData(); QMimeData* mimeData = new QMimeData();
@@ -406,7 +404,6 @@ void LtsToolButton::performDrag(QMouseEvent *)
for (auto it = m_mimeData.cbegin(); it != m_mimeData.cend(); ++it) for (auto it = m_mimeData.cbegin(); it != m_mimeData.cend(); ++it)
mimeData->setData(it.key(), it.value()); mimeData->setData(it.key(), it.value());
if (dragIcon->dropHandlerKey() != 0L) if (dragIcon->dropHandlerKey() != 0L)
{ {
QByteArray data = QByteArray(QByteArray::number(dragIcon->dropHandlerKey())); QByteArray data = QByteArray(QByteArray::number(dragIcon->dropHandlerKey()));
@@ -431,14 +428,13 @@ void LtsToolButton::performDrag(QMouseEvent *)
if (drop == Qt::MoveAction || drop == Qt::CopyAction) if (drop == Qt::MoveAction || drop == Qt::CopyAction)
emit dropSuc(); emit dropSuc();
} }
} }
void LtsToolButton::dragEnterEvent(QDragEnterEvent* event) void LtsToolButton::dragEnterEvent(QDragEnterEvent* event)
{ {
QWidget *source = QWidget* source = qobject_cast<QWidget*>(event->source());
qobject_cast<QWidget *>(event->source()); if (source && source != this)
if (source && source != this) { {
event->setDropAction(Qt::MoveAction); event->setDropAction(Qt::MoveAction);
event->accept(); event->accept();
} }
@@ -466,7 +462,7 @@ QIcon LtsDragIcon::modifyIcon(const QIcon &icon)
QPainter painter(&iconImage); QPainter painter(&iconImage);
painter.save(); painter.save();
painter.setRenderHints(QPainter::TextAntialiasing | QPainter::Antialiasing | QPainter::HighQualityAntialiasing | QPainter::SmoothPixmapTransform); painter.setRenderHints(QPainter::TextAntialiasing | QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
painter.setBrush(QColor("red")); painter.setBrush(QColor("red"));
painter.setPen(QPen(QColor("red"), 3)); painter.setPen(QPen(QColor("red"), 3));
@@ -482,8 +478,6 @@ QIcon LtsDragIcon::modifyIcon(const QIcon &icon)
return iconImage; return iconImage;
} }
} } // namespace LtsWidgets
#include "lts_drag_icon.moc" #include "lts_drag_icon.moc"
+8 -35
View File
@@ -1,34 +1,27 @@
#include "lts_frameless_dialog.h" #include "lts_frameless_dialog.h"
#include <QApplication> #include <QApplication>
#include <QRect> #include <QRect>
#include <QStyle>
#include <QSize>
#include <QScreen> #include <QScreen>
#include <QScroller>
#include <QScrollArea> #include <QScrollArea>
#include <QDesktopWidget> #include <QScroller>
#include <QShowEvent> #include <QShowEvent>
#include <QSize>
#include <QStyle>
#include <QTimer> #include <QTimer>
namespace LtsWidgets namespace LtsWidgets
{ {
LtsFramelessDialog::LtsFramelessDialog(QWidget *parent, const Behaviour &behaviour) LtsFramelessDialog::LtsFramelessDialog(QWidget* parent, const Behaviour& behaviour) : QDialog(parent)
: QDialog(parent)
{ {
Qt::WindowFlags wf; Qt::WindowFlags wf;
switch (behaviour) switch (behaviour)
{ {
case Behaviour::Modal: case Behaviour::Modal: {
{
#ifndef TABLET_MODE #ifndef TABLET_MODE
setModal(true); setModal(true);
@@ -47,27 +40,15 @@ LtsFramelessDialog::LtsFramelessDialog(QWidget *parent, const Behaviour &behavio
setWindowFlags(wf); setWindowFlags(wf);
QTimer* t = new QTimer(this); QTimer* t = new QTimer(this);
t->setInterval(250); t->setInterval(250);
connect(t, &QTimer::timeout, connect(t, &QTimer::timeout, this, [this]() {
this, [this]()
{
QSize s = size(); QSize s = size();
setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, s, screenRectFromPoint(QCursor::pos()))); setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, s, screenRectFromPoint(QCursor::pos())));
}); });
}
LtsFramelessDialog::~LtsFramelessDialog()
{
} }
LtsFramelessDialog::~LtsFramelessDialog() {}
QRect LtsFramelessDialog::screenRectFromPoint(const QPoint& pos) const QRect LtsFramelessDialog::screenRectFromPoint(const QPoint& pos) const
{ {
@@ -78,10 +59,6 @@ QRect LtsFramelessDialog::screenRectFromPoint(const QPoint &pos) const
bool contains = s.contains(pos); bool contains = s.contains(pos);
if (contains) if (contains)
return screen->geometry(); return screen->geometry();
} }
@@ -89,13 +66,11 @@ QRect LtsFramelessDialog::screenRectFromPoint(const QPoint &pos) const
return QRect(); return QRect();
} }
void LtsFramelessDialog::showEvent(QShowEvent* event) void LtsFramelessDialog::showEvent(QShowEvent* event)
{ {
QDialog::showEvent(event); QDialog::showEvent(event);
QTimer::singleShot(0, this, &LtsFramelessDialog::onUpdateGeometry); QTimer::singleShot(0, this, &LtsFramelessDialog::onUpdateGeometry);
#ifdef TABLET_MODE #ifdef TABLET_MODE
QList<QWidget*> scrollWidgets = findChildren<QWidget*>(); QList<QWidget*> scrollWidgets = findChildren<QWidget*>();
@@ -112,7 +87,6 @@ void LtsFramelessDialog::showEvent(QShowEvent *event)
#endif #endif
} }
void LtsFramelessDialog::addTouchScroll(QWidget* widget) void LtsFramelessDialog::addTouchScroll(QWidget* widget)
{ {
if (!widget) if (!widget)
@@ -127,7 +101,6 @@ void LtsFramelessDialog::addTouchScroll(QWidget *widget)
} }
} }
void LtsFramelessDialog::onUpdateGeometry() void LtsFramelessDialog::onUpdateGeometry()
{ {
QRect r; QRect r;
@@ -150,4 +123,4 @@ void LtsFramelessDialog::onUpdateGeometry()
setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, s, r)); setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, s, r));
} }
} } // namespace LtsWidgets
+6 -13
View File
@@ -1,25 +1,21 @@
#include "lts_grid_layout.h" #include "lts_grid_layout.h"
#include <utility>
#include <QResizeEvent> #include <QResizeEvent>
#include <utility>
namespace LtsWidgets namespace LtsWidgets
{ {
LtsGridLayout::LtsGridLayout(LtsWidgets::ButtonSize buttonSize, QWidget* parent, int maxColumn) LtsGridLayout::LtsGridLayout(LtsWidgets::ButtonSize buttonSize, QWidget* parent, int maxColumn)
: QGridLayout(parent) : QGridLayout(parent), m_buttonSize(buttonSize), m_defaultMaxColumn(maxColumn), m_maxColumn(maxColumn),
, m_buttonSize(buttonSize) m_colSize(0), m_autoSize(maxColumn < 0)
, m_defaultMaxColumn(maxColumn)
, m_maxColumn(maxColumn)
, m_colSize(0)
, m_autoSize(maxColumn < 0)
{ {
setSizeConstraint(SizeConstraint::SetNoConstraint); setSizeConstraint(SizeConstraint::SetNoConstraint);
setVerticalSpacing(1); setVerticalSpacing(1);
setMargin(0); setContentsMargins(0, 0, 0, 0);
} }
void LtsGridLayout::add_widget(QWidget* widget) void LtsGridLayout::add_widget(QWidget* widget)
@@ -55,7 +51,6 @@ void LtsGridLayout::setMaxColumn(int max)
m_maxColumn = max; m_maxColumn = max;
m_defaultMaxColumn = max; m_defaultMaxColumn = max;
m_colSize = 0; m_colSize = 0;
for (QWidget* wid : std::as_const(m_widgetList)) for (QWidget* wid : std::as_const(m_widgetList))
@@ -63,7 +58,6 @@ void LtsGridLayout::setMaxColumn(int max)
for (QWidget* wid : std::as_const(m_widgetList)) for (QWidget* wid : std::as_const(m_widgetList))
addWidgetInternal(wid); addWidgetInternal(wid);
} }
void LtsGridLayout::addWidgetInternal(QWidget* widget) void LtsGridLayout::addWidgetInternal(QWidget* widget)
@@ -94,7 +88,6 @@ void LtsGridLayout::addWidgetInternal(QWidget *widget)
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()) if (m_autoSize && m_oldSize != e->size())
@@ -126,4 +119,4 @@ void LtsGridLayout::onWidgetDestroyed()
} }
} }
} } // namespace LtsWidgets
+23 -61
View File
@@ -1,17 +1,14 @@
#include "lts_height_plot_widget.h" #include "lts_height_plot_widget.h"
#include <QMouseEvent>
#include <QPainter> #include <QPainter>
#include <QPainterPath> #include <QPainterPath>
#include <QPen> #include <QPen>
#include <QTransform> #include <QTransform>
#include <QMouseEvent>
#include <cmath> #include <cmath>
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 x = p1.x() - p2.x();
@@ -23,18 +20,9 @@ class LtsHeightPlotWidget::Private
{ {
public: public:
Private() Private()
: m_length(0) : m_length(0), m_minElevation(0), m_maxElevation(0), m_nullX(0), m_nullY(0), m_scaleX(0), m_scaleY(0),
, m_minElevation(0) m_fillBrush(Qt::gray), m_axisPen(Qt::black), m_mousePosPen(Qt::blue), m_markerPen(Qt::magenta),
, m_maxElevation(0) iPositionHint(1)
, 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_axisPen.setWidth(1);
m_viewLinePen.setWidth(1); m_viewLinePen.setWidth(1);
@@ -44,6 +32,7 @@ public:
m_mousePosPen.setStyle(Qt::DashDotDotLine); m_mousePosPen.setStyle(Qt::DashDotDotLine);
m_viewLinePen.setStyle(Qt::DashLine); m_viewLinePen.setStyle(Qt::DashLine);
} }
void clearPixmap(); void clearPixmap();
double getDataHeight(double pos) const; double getDataHeight(double pos) const;
@@ -159,7 +148,6 @@ int LtsHeightPlotWidget::Private::findDataPointIdx(const QPointF &point) const
const double m = y / x; const double m = y / x;
const double n = m_data[i].first.y() - m * m_data[i].first.x(); const double n = m_data[i].first.y() - m * m_data[i].first.x();
const double yRes = m * point.x() + n; const double yRes = m * point.x() + n;
if (fabs(yRes - point.y()) < 1.) if (fabs(yRes - point.y()) < 1.)
{ {
@@ -220,11 +208,15 @@ void LtsHeightPlotWidget::Private::recalcData()
maxElevation = std::max(maxElevation, m_data.at(i).second); maxElevation = std::max(maxElevation, m_data.at(i).second);
} }
if (minElevation < -10000.0) minElevation = -10000.0; if (minElevation < -10000.0)
if (maxElevation < -10000.0) maxElevation = -10000.0; minElevation = -10000.0;
if (maxElevation < -10000.0)
maxElevation = -10000.0;
if (minElevation > 10000.0) minElevation = 10000.0; if (minElevation > 10000.0)
if (maxElevation > 10000.0) maxElevation = 10000.0; minElevation = 10000.0;
if (maxElevation > 10000.0)
maxElevation = 10000.0;
if (qFuzzyCompare(minElevation, maxElevation)) if (qFuzzyCompare(minElevation, maxElevation))
{ {
@@ -232,7 +224,6 @@ void LtsHeightPlotWidget::Private::recalcData()
maxElevation += 1.0; maxElevation += 1.0;
} }
double n2 = pow(5, floor(log5(fabs(minElevation))) - 1); double n2 = pow(5, floor(log5(fabs(minElevation))) - 1);
if (qFuzzyIsNull(n2)) if (qFuzzyIsNull(n2))
n2 = 0.1; n2 = 0.1;
@@ -246,7 +237,6 @@ void LtsHeightPlotWidget::Private::recalcData()
if (m_minElevation < 0 && m_maxElevation > 0) if (m_minElevation < 0 && m_maxElevation > 0)
m_nullY = 0; m_nullY = 0;
const double n = pow(10, floor(log10(length))) / 2; const double n = pow(10, floor(log10(length))) / 2;
m_length = lrint(ceil(length / n) * n); m_length = lrint(ceil(length / n) * n);
m_scaleX = pow(10, floor(log10(length)) - 1); m_scaleX = pow(10, floor(log10(length)) - 1);
@@ -263,7 +253,6 @@ void LtsHeightPlotWidget::Private::recalcData()
m_drawPoints.lineTo(len, m_data.at(i).second); m_drawPoints.lineTo(len, m_data.at(i).second);
m_heightList.append(QPair<double, double>(len, m_data.at(i).second)); m_heightList.append(QPair<double, double>(len, m_data.at(i).second));
} }
m_drawPoints.lineTo(len, m_minElevation); m_drawPoints.lineTo(len, m_minElevation);
m_drawPoints.lineTo(0, m_minElevation); m_drawPoints.lineTo(0, m_minElevation);
@@ -286,7 +275,6 @@ void LtsHeightPlotWidget::Private::setData(const QVector< QPair< QPointF, double
resize(tmp); resize(tmp);
} }
void LtsHeightPlotWidget::Private::setMarks(const QVector<QPointF>& data) void LtsHeightPlotWidget::Private::setMarks(const QVector<QPointF>& data)
{ {
m_marks = data; m_marks = data;
@@ -317,7 +305,6 @@ void LtsHeightPlotWidget::Private::resize(const QSize &newSize)
m_trans1.reset(); m_trans1.reset();
m_trans2.reset(); m_trans2.reset();
m_trans1.translate(10, height); m_trans1.translate(10, height);
m_trans1.scale(1, -1); m_trans1.scale(1, -1);
@@ -326,9 +313,7 @@ void LtsHeightPlotWidget::Private::resize(const QSize &newSize)
m_trans1.scale(1, -1); m_trans1.scale(1, -1);
m_trans2.scale((width - 2 * border) / (wertebereichX), (height - 2 * border) / (wertebereichY));
m_trans2.scale((width - 2 * border) / (wertebereichX),
(height - 2 * border) / (wertebereichY));
m_trans2.translate(0, minY); m_trans2.translate(0, minY);
@@ -350,20 +335,16 @@ void LtsHeightPlotWidget::Private::repaint()
QImage img(m_curSize, QImage::Format_ARGB32); QImage img(m_curSize, QImage::Format_ARGB32);
img.fill(Qt::transparent); img.fill(Qt::transparent);
QPainter p(&img); QPainter p(&img);
const QPainter::RenderHints hints = QPainter::HighQualityAntialiasing | const QPainter::RenderHints hints =
QPainter::SmoothPixmapTransform | QPainter::SmoothPixmapTransform | QPainter::TextAntialiasing | QPainter::Antialiasing;
QPainter::TextAntialiasing |
QPainter::Antialiasing;
p.setRenderHints(hints); p.setRenderHints(hints);
p.setTransform(m_trans1); p.setTransform(m_trans1);
p.setPen(QPen(m_fillBrush, 0.1)); p.setPen(QPen(m_fillBrush, 0.1));
p.setBrush(m_fillBrush); p.setBrush(m_fillBrush);
p.drawPath(m_trans2.map(m_drawPoints)); p.drawPath(m_trans2.map(m_drawPoints));
p.setRenderHint(QPainter::Antialiasing, false); p.setRenderHint(QPainter::Antialiasing, false);
p.setPen(m_markerPen); p.setPen(m_markerPen);
for (int i = 0; i < m_marks.count(); ++i) for (int i = 0; i < m_marks.count(); ++i)
{ {
@@ -375,26 +356,21 @@ void LtsHeightPlotWidget::Private::repaint()
const double height = getDataHeight(len); const double height = getDataHeight(len);
const QLineF l(len, m_minElevation, len, height); const QLineF l(len, m_minElevation, len, height);
p.drawLine(m_trans2.map(l)); p.drawLine(m_trans2.map(l));
} }
p.setPen(m_axisPen); p.setPen(m_axisPen);
p.setFont(m_textFont); p.setFont(m_textFont);
p.drawLine(m_trans2.map(QPointF(m_nullX, m_minElevation - m_scaleY)), p.drawLine(m_trans2.map(QPointF(m_nullX, m_minElevation - m_scaleY)),
m_trans2.map(QPointF(m_nullX, m_maxElevation + m_scaleY))); m_trans2.map(QPointF(m_nullX, m_maxElevation + m_scaleY)));
for (double i = m_minElevation; i <= m_maxElevation; i += m_scaleY) for (double i = m_minElevation; i <= m_maxElevation; i += m_scaleY)
{ {
const qreal y = m_trans2.map(QPointF(0, i)).y(); const qreal y = m_trans2.map(QPointF(0, i)).y();
p.drawLine(QLineF(-2, y, 2, y)); p.drawLine(QLineF(-2, y, 2, y));
} }
for (double i = m_minElevation; i <= m_maxElevation; i += m_scaleY * 5) for (double i = m_minElevation; i <= m_maxElevation; i += m_scaleY * 5)
{ {
const qreal y = m_trans2.map(QPointF(0, i)).y(); const qreal y = m_trans2.map(QPointF(0, i)).y();
@@ -410,15 +386,12 @@ void LtsHeightPlotWidget::Private::repaint()
const QPointF p1(-20, y); const QPointF p1(-20, y);
const QString str = QString::number(i); const QString str = QString::number(i);
QRectF r = fm.boundingRect(str); QRectF r = fm.boundingRect(str);
r.setWidth(fm.width(str)); r.setWidth(fm.horizontalAdvance(str));
r.moveTo(p1.x() - r.width() / 2., p1.y() - r.height() / 2.); r.moveTo(p1.x() - r.width() / 2., p1.y() - r.height() / 2.);
p.drawText(r, str, Qt::AlignHCenter | Qt::AlignVCenter); 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)));
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) for (double i = m_scaleX; i <= m_length; i += m_scaleX)
{ {
@@ -426,7 +399,6 @@ void LtsHeightPlotWidget::Private::repaint()
p.drawLine(QLineF(point.x(), point.y() - 2, point.x(), point.y() + 2)); p.drawLine(QLineF(point.x(), point.y() - 2, point.x(), point.y() + 2));
} }
for (double i = 0; i <= m_length; i += m_scaleX * 5) for (double i = 0; i <= m_length; i += m_scaleX * 5)
{ {
const QPointF point = m_trans2.map(QPointF(i, m_nullY)); const QPointF point = m_trans2.map(QPointF(i, m_nullY));
@@ -441,7 +413,7 @@ void LtsHeightPlotWidget::Private::repaint()
const QPointF p1(point.x(), point.y() + 15); const QPointF p1(point.x(), point.y() + 15);
const QString str = QString::number(i); const QString str = QString::number(i);
QRectF r = fm.boundingRect(str); QRectF r = fm.boundingRect(str);
r.setWidth(fm.width(str)); r.setWidth(fm.horizontalAdvance(str));
r.moveTo(p1.x() - r.width() / 2., p1.y() - r.height() / 2.); r.moveTo(p1.x() - r.width() / 2., p1.y() - r.height() / 2.);
p.drawText(r, str, Qt::AlignHCenter | Qt::AlignVCenter); p.drawText(r, str, Qt::AlignHCenter | Qt::AlignVCenter);
} }
@@ -460,14 +432,11 @@ void LtsHeightPlotWidget::Private::paintLines(QPainter &p) const
if (pos.x() > m_heightList.at(m_heightList.count() - 1).first) if (pos.x() > m_heightList.at(m_heightList.count() - 1).first)
pos.setX(m_heightList.at(m_heightList.count() - 1).first); pos.setX(m_heightList.at(m_heightList.count() - 1).first);
const double curHeight = getDataHeight(pos.x()); const double curHeight = getDataHeight(pos.x());
p.setPen(m_mousePosPen); p.setPen(m_mousePosPen);
p.drawLine(m_transCombined.map(QLineF(m_nullX, curHeight, pos.x(), curHeight))); 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))); p.drawLine(m_transCombined.map(QLineF(pos.x(), m_nullY, pos.x(), curHeight)));
if (!m_mouseLeftClickPos.isNull()) if (!m_mouseLeftClickPos.isNull())
{ {
const double y = curHeight > pos.y() ? curHeight : pos.y(); const double y = curHeight > pos.y() ? curHeight : pos.y();
@@ -479,16 +448,13 @@ void LtsHeightPlotWidget::Private::paintLines(QPainter &p) const
p.drawLine(m_transCombined.map(QLineF(m_nullX, c.y(), c.x(), c.y()))); 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()))); p.drawLine(m_transCombined.map(QLineF(c.x(), m_nullY, c.x(), c.y())));
const QLineF line(m_mouseLeftClickPos, QPointF(pos.x(), y)); const QLineF line(m_mouseLeftClickPos, QPointF(pos.x(), y));
p.drawLine(m_transCombined.map(line)); p.drawLine(m_transCombined.map(line));
} }
} }
} }
LtsHeightPlotWidget::LtsHeightPlotWidget(QWidget *parent) LtsHeightPlotWidget::LtsHeightPlotWidget(QWidget* parent) : QWidget(parent), d(new Private)
: QWidget(parent)
, d(new Private)
{ {
setMinimumSize(300, 300); setMinimumSize(300, 300);
resize(size()); resize(size());
@@ -520,7 +486,7 @@ void LtsHeightPlotWidget::setMarks(const QVector<QPointF> &data)
void LtsHeightPlotWidget::setBackgroundBrush(const QBrush& brush) void LtsHeightPlotWidget::setBackgroundBrush(const QBrush& brush)
{ {
QPalette pal = palette(); QPalette pal = palette();
pal.setBrush(QPalette::Background, brush); pal.setBrush(QPalette::Window, brush);
setPalette(pal); setPalette(pal);
} }
@@ -569,15 +535,12 @@ void LtsHeightPlotWidget::paintEvent(QPaintEvent *e)
Q_UNUSED(e); Q_UNUSED(e);
QPainter p(this); QPainter p(this);
const QPainter::RenderHints hints = QPainter::SmoothPixmapTransform | const QPainter::RenderHints hints =
QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform | QPainter::TextAntialiasing | QPainter::Antialiasing;
QPainter::Antialiasing;
p.setRenderHints(hints); p.setRenderHints(hints);
p.drawPixmap(0, 0, d->m_pixmap); p.drawPixmap(0, 0, d->m_pixmap);
d->paintLines(p); d->paintLines(p);
p.end(); p.end();
} }
@@ -618,4 +581,3 @@ void LtsHeightPlotWidget::mouseReleaseEvent(QMouseEvent *e)
update(); update();
} }
} }
+7 -22
View File
@@ -1,25 +1,20 @@
#include "lts_image_editor.h" #include "lts_image_editor.h"
#include <QPainter>
#include <QPaintEvent>
#include <QBrush> #include <QBrush>
#include <QEvent>
#include <QPaintEvent>
#include <QPainter>
#include <QPen> #include <QPen>
#include <QRect> #include <QRect>
#include <QEvent>
using namespace LtsWidgets; using namespace LtsWidgets;
LtsImageEditor::LtsImageEditor(QWidget* parent) LtsImageEditor::LtsImageEditor(QWidget* parent)
: QWidget(parent) : QWidget(parent), m_isHovered(false), m_menuEnabled(true), m_bDrawOuterRect(true)
, m_isHovered(false) {
, m_menuEnabled(true) }
, m_bDrawOuterRect(true)
{}
void LtsImageEditor::setPixmap(const QPixmap& pixmap) void LtsImageEditor::setPixmap(const QPixmap& pixmap)
{ {
@@ -32,15 +27,13 @@ void LtsImageEditor::setPixmap(const QPixmap &pixmap)
emit imageChanged(); emit imageChanged();
} }
void LtsImageEditor::enterEvent(QEnterEvent*)
void LtsImageEditor::enterEvent(QEvent *)
{ {
m_isHovered = true; m_isHovered = true;
update(); update();
} }
void LtsImageEditor::leaveEvent(QEvent*) void LtsImageEditor::leaveEvent(QEvent*)
{ {
@@ -48,7 +41,6 @@ void LtsImageEditor::leaveEvent(QEvent *)
update(); update();
} }
bool LtsImageEditor::event(QEvent* event) bool LtsImageEditor::event(QEvent* event)
{ {
if (event->type() == QEvent::MouseButtonPress && m_menuEnabled) if (event->type() == QEvent::MouseButtonPress && m_menuEnabled)
@@ -63,16 +55,13 @@ bool LtsImageEditor::event(QEvent *event)
return QWidget::event(event); return QWidget::event(event);
} }
void LtsImageEditor::paintEvent(QPaintEvent* event) void LtsImageEditor::paintEvent(QPaintEvent* event)
{ {
QPainter p(this); QPainter p(this);
p.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); p.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
QBrush brush = QColor(QStringLiteral("white")); QBrush brush = QColor(QStringLiteral("white"));
if (!m_pixmap.isNull()) if (!m_pixmap.isNull())
{ {
if (!(m_isHovered && m_menuEnabled)) if (!(m_isHovered && m_menuEnabled))
@@ -92,14 +81,10 @@ void LtsImageEditor::paintEvent(QPaintEvent* event)
} }
} }
p.setPen(QPen(QColor("gray"), 2)); p.setPen(QPen(QColor("gray"), 2));
p.setBrush(brush); p.setBrush(brush);
p.drawRect(rect()); p.drawRect(rect());
if (m_isHovered && m_menuEnabled) if (m_isHovered && m_menuEnabled)
{ {
p.setPen(QPen(QColor(QStringLiteral("gray")), (size().height() / 48 * 2))); p.setPen(QPen(QColor(QStringLiteral("gray")), (size().height() / 48 * 2)));
+23 -16
View File
@@ -1,14 +1,11 @@
#pragma once #pragma once
#include <QObject>
#include "ltswidgets_export.h" #include "ltswidgets_export.h"
#include <QObject>
#include <QWidget> #include <QWidget>
namespace LtsWidgets namespace LtsWidgets
{ {
@@ -22,25 +19,36 @@ class LTSWIDGETS_EXPORT LtsImageEditor : public QWidget
public: public:
explicit LtsImageEditor(QWidget* parent = nullptr); 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;
}
bool drawOuterRect() const
void setMenuEnabled(bool enabled = true) { m_menuEnabled = enabled; } {
bool isMenuEnabled() const { return m_menuEnabled; } return m_bDrawOuterRect;
}
void setDrawOuterRect(bool bDraw) { m_bDrawOuterRect = bDraw; }
bool drawOuterRect() const { return m_bDrawOuterRect; }
protected: protected:
void paintEvent(QPaintEvent* event); void paintEvent(QPaintEvent* event);
void enterEvent(QEvent *); void enterEvent(QEnterEvent*);
void leaveEvent(QEvent*); void leaveEvent(QEvent*);
bool event(QEvent* event); bool event(QEvent* event);
@@ -52,10 +60,9 @@ private:
signals: signals:
void signalClicked(); void signalClicked();
void imageChanged(); void imageChanged();
}; };
} } // namespace LtsWidgets
+33 -40
View File
@@ -1,28 +1,25 @@
#include "lts_message_dialog.h" #include "lts_message_dialog.h"
#include "lts_message_dialog_helper.h" #include "lts_message_dialog_helper.h"
#include <QCoreApplication> #include <QCoreApplication>
#include <QVBoxLayout> #include <QDebug>
#include <QLabel> #include <QLabel>
#include <QPushButton> #include <QPushButton>
#include <QDebug> #include <QVBoxLayout>
namespace LtsWidgets namespace LtsWidgets
{ {
namespace LtsMessageDialog namespace LtsMessageDialog
{ {
Button showMessage(QWidget* parent, Button showMessage(QWidget* parent, const QString& message, const QString& title, const Behaviour behaviour,
const QString& message, const Buttons buttons, const QHash<Button, QString>& buttonTexts)
const QString &title,
const Behaviour behaviour,
const Buttons buttons,
const QHash<Button, QString> &buttonTexts)
{ {
static QAtomicInt s_used = 0; static QAtomicInt s_used = 0;
if (s_used) if (s_used)
qDebug() << "LtsMessageDialog: showMessage called while showMessage is in its Event Loop - do not open more than one Dialog at once !!"; 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;
@@ -37,34 +34,27 @@ Button showMessage(QWidget* parent,
Button askApplyDiscardCancel(QWidget* parent) Button askApplyDiscardCancel(QWidget* parent)
{ {
const QString question = QCoreApplication::translate("LtsDialog", const QString question = QCoreApplication::translate("LtsDialog", "<br>"
"<br>"
"Apply - apply changes and close.<br>" "Apply - apply changes and close.<br>"
"Discard - discard changes and close.<br>" "Discard - discard changes and close.<br>"
"Cancel - do not close."); "Cancel - do not close.");
const QString title = QCoreApplication::translate("LtsDialog", "Unapplied changes made. Apply the changes?"); const QString title = QCoreApplication::translate("LtsDialog", "Unapplied changes made. Apply the changes?");
return LtsMessageDialog::showMessage(parent, return LtsMessageDialog::showMessage(parent, question, title, Behaviour::Modal,
question,
title,
Behaviour::Modal,
Button::Apply | Button::Discard | Button::Cancel); 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<Button, QString>& buttonTexts, bool deleteOnClose)
LtsMessageDialogNew::LtsMessageDialogNew(QWidget *parent, const QString &message, const QString &title, const Behaviour behaviour, const Buttons buttons, const QHash<Button, QString> &buttonTexts, bool deleteOnClose)
{ {
m_dialog = new LtsFramelessDialog(parent, behaviour); m_dialog = new LtsFramelessDialog(parent, behaviour);
if (deleteOnClose) if (deleteOnClose)
m_dialog->setAttribute(Qt::WA_DeleteOnClose); m_dialog->setAttribute(Qt::WA_DeleteOnClose);
connect(m_dialog, &LtsFramelessDialog::destroyed, connect(m_dialog, &LtsFramelessDialog::destroyed, this, &LtsMessageDialogNew::deleteLater);
this, &LtsMessageDialogNew::deleteLater);
QVBoxLayout* mainLayout = new QVBoxLayout(m_dialog); QVBoxLayout* mainLayout = new QVBoxLayout(m_dialog);
@@ -81,28 +71,33 @@ LtsMessageDialogNew::LtsMessageDialogNew(QWidget *parent, const QString &message
mainLayout->addWidget(messageLabel); mainLayout->addWidget(messageLabel);
QHBoxLayout* buttonLayout = new QHBoxLayout; QHBoxLayout* buttonLayout = new QHBoxLayout;
buttonLayout->setMargin(0); buttonLayout->setContentsMargins(0, 0, 0, 0);
if (buttons.testFlag(Button::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); connect(addButton(buttonTexts.value(Button::Ok, tr("Ok")), buttonLayout, m_dialog, Button::Ok, parent),
&QPushButton::clicked, this, &LtsMessageDialogNew::ok);
if (buttons.testFlag(Button::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); connect(addButton(buttonTexts.value(Button::Yes, tr("Yes")), buttonLayout, m_dialog, Button::Yes, parent),
&QPushButton::clicked, this, &LtsMessageDialogNew::yes);
if (buttons.testFlag(Button::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); connect(addButton(buttonTexts.value(Button::No, tr("No")), buttonLayout, m_dialog, Button::No, parent),
&QPushButton::clicked, this, &LtsMessageDialogNew::no);
if (buttons.testFlag(Button::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); connect(addButton(buttonTexts.value(Button::Apply, tr("Apply")), buttonLayout, m_dialog, Button::Apply, parent),
&QPushButton::clicked, this, &LtsMessageDialogNew::apply);
if (buttons.testFlag(Button::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); connect(addButton(buttonTexts.value(Button::Discard, tr("Discard")), buttonLayout, m_dialog, Button::Discard,
parent),
&QPushButton::clicked, this, &LtsMessageDialogNew::discard);
if (buttons.testFlag(Button::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); connect(
addButton(buttonTexts.value(Button::Cancel, tr("Cancel")), buttonLayout, m_dialog, Button::Cancel, parent),
&QPushButton::clicked, this, &LtsMessageDialogNew::cancel);
QWidget* buttonLayoutWidget = new QWidget; QWidget* buttonLayoutWidget = new QWidget;
buttonLayoutWidget->setLayout(buttonLayout); buttonLayoutWidget->setLayout(buttonLayout);
@@ -113,15 +108,14 @@ LtsMessageDialogNew::LtsMessageDialogNew(QWidget *parent, const QString &message
m_dialog->raise(); m_dialog->raise();
} }
QPushButton* LtsMessageDialogNew::addButton(const QString& text, QHBoxLayout* thatLayout, LtsFramelessDialog* dialog,
QPushButton* LtsMessageDialogNew::addButton(const QString &text, QHBoxLayout *thatLayout, LtsFramelessDialog *dialog, const Button &button, QWidget *parent) const Button& button, QWidget* parent)
{ {
QPushButton* btn = new QPushButton(text, parent); QPushButton* btn = new QPushButton(text, parent);
connect(btn, &QPushButton::clicked, dialog, &LtsFramelessDialog::accept); connect(btn, &QPushButton::clicked, dialog, &LtsFramelessDialog::accept);
thatLayout->addWidget(btn); thatLayout->addWidget(btn);
if (button == Button::Ok || if (button == Button::Ok || button == Button::Cancel)
button == Button::Cancel)
{ {
btn->setDefault(true); btn->setDefault(true);
} }
@@ -129,5 +123,4 @@ QPushButton* LtsMessageDialogNew::addButton(const QString &text, QHBoxLayout *th
return btn; return btn;
} }
} // namespace LtsWidgets
}
+17 -30
View File
@@ -1,27 +1,21 @@
#include "lts_message_dialog_helper.h" #include "lts_message_dialog_helper.h"
#include <QPushButton> #include <QEventLoop>
#include <QVBoxLayout>
#include <QHBoxLayout> #include <QHBoxLayout>
#include <QLabel> #include <QLabel>
#include <QEventLoop> #include <QPushButton>
#include <QVBoxLayout>
namespace LtsWidgets namespace LtsWidgets
{ {
LtsMessageDialogHelper::LtsMessageDialogHelper(QObject* parent) LtsMessageDialogHelper::LtsMessageDialogHelper(QObject* parent)
: QObject(parent) : QObject(parent), m_result(Button::Cancel), m_dialog(nullptr)
, m_result(Button::Cancel) {
, m_dialog(nullptr) }
{}
Button LtsMessageDialogHelper::showMessage(QWidget* parent, const QString& message, const QString& title,
Button LtsMessageDialogHelper::showMessage(QWidget *parent, Behaviour behaviour, Buttons buttons,
const QString &message,
const QString &title,
Behaviour behaviour,
Buttons buttons,
const QHash<Button, QString>& buttonTexts) const QHash<Button, QString>& buttonTexts)
{ {
m_dialog = new LtsFramelessDialog(parent, behaviour); m_dialog = new LtsFramelessDialog(parent, behaviour);
@@ -43,8 +37,7 @@ Button LtsMessageDialogHelper::showMessage(QWidget *parent,
mainLayout->addWidget(messageLabel); mainLayout->addWidget(messageLabel);
QHBoxLayout* buttonLayout = new QHBoxLayout; QHBoxLayout* buttonLayout = new QHBoxLayout;
buttonLayout->setMargin(0); buttonLayout->setContentsMargins(0, 0, 0, 0);
connect(m_dialog, &LtsFramelessDialog::rejected, this, &LtsMessageDialogHelper::slotCancel); connect(m_dialog, &LtsFramelessDialog::rejected, this, &LtsMessageDialogHelper::slotCancel);
@@ -65,11 +58,13 @@ Button LtsMessageDialogHelper::showMessage(QWidget *parent,
&QPushButton::clicked, this, &LtsMessageDialogHelper::slotApply); &QPushButton::clicked, this, &LtsMessageDialogHelper::slotApply);
if (buttons.testFlag(Button::Discard)) if (buttons.testFlag(Button::Discard))
connect(addButton(buttonTexts.value(Button::Discard, tr("Discard")), buttonLayout, m_dialog, Button::Discard, parent), connect(addButton(buttonTexts.value(Button::Discard, tr("Discard")), buttonLayout, m_dialog, Button::Discard,
parent),
&QPushButton::clicked, this, &LtsMessageDialogHelper::slotDiscard); &QPushButton::clicked, this, &LtsMessageDialogHelper::slotDiscard);
if (buttons.testFlag(Button::Cancel)) if (buttons.testFlag(Button::Cancel))
connect(addButton(buttonTexts.value(Button::Cancel, tr("Cancel")), buttonLayout, m_dialog, Button::Cancel, parent), connect(
addButton(buttonTexts.value(Button::Cancel, tr("Cancel")), buttonLayout, m_dialog, Button::Cancel, parent),
&QPushButton::clicked, this, &LtsMessageDialogHelper::slotCancel); &QPushButton::clicked, this, &LtsMessageDialogHelper::slotCancel);
QWidget* buttonLayoutWidget = new QWidget; QWidget* buttonLayoutWidget = new QWidget;
@@ -80,7 +75,6 @@ Button LtsMessageDialogHelper::showMessage(QWidget *parent,
m_dialog->show(); m_dialog->show();
m_dialog->raise(); m_dialog->raise();
QEventLoop loop; QEventLoop loop;
connect(this, &LtsMessageDialogHelper::signalQuitEventLoop, &loop, &QEventLoop::quit, Qt::QueuedConnection); connect(this, &LtsMessageDialogHelper::signalQuitEventLoop, &loop, &QEventLoop::quit, Qt::QueuedConnection);
loop.exec(); loop.exec();
@@ -88,7 +82,6 @@ Button LtsMessageDialogHelper::showMessage(QWidget *parent,
return m_result; return m_result;
} }
void LtsMessageDialogHelper::slotOkay() void LtsMessageDialogHelper::slotOkay()
{ {
m_dialog->hide(); m_dialog->hide();
@@ -96,7 +89,6 @@ void LtsMessageDialogHelper::slotOkay()
emit signalQuitEventLoop(); emit signalQuitEventLoop();
} }
void LtsMessageDialogHelper::slotYes() void LtsMessageDialogHelper::slotYes()
{ {
m_dialog->hide(); m_dialog->hide();
@@ -104,7 +96,6 @@ void LtsMessageDialogHelper::slotYes()
emit signalQuitEventLoop(); emit signalQuitEventLoop();
} }
void LtsMessageDialogHelper::slotNo() void LtsMessageDialogHelper::slotNo()
{ {
m_dialog->hide(); m_dialog->hide();
@@ -112,7 +103,6 @@ void LtsMessageDialogHelper::slotNo()
emit signalQuitEventLoop(); emit signalQuitEventLoop();
} }
void LtsMessageDialogHelper::slotApply() void LtsMessageDialogHelper::slotApply()
{ {
m_dialog->hide(); m_dialog->hide();
@@ -120,7 +110,6 @@ void LtsMessageDialogHelper::slotApply()
emit signalQuitEventLoop(); emit signalQuitEventLoop();
} }
void LtsMessageDialogHelper::slotDiscard() void LtsMessageDialogHelper::slotDiscard()
{ {
m_dialog->hide(); m_dialog->hide();
@@ -128,7 +117,6 @@ void LtsMessageDialogHelper::slotDiscard()
emit signalQuitEventLoop(); emit signalQuitEventLoop();
} }
void LtsMessageDialogHelper::slotCancel() void LtsMessageDialogHelper::slotCancel()
{ {
m_dialog->hide(); m_dialog->hide();
@@ -136,15 +124,14 @@ void LtsMessageDialogHelper::slotCancel()
emit signalQuitEventLoop(); emit signalQuitEventLoop();
} }
QPushButton* LtsMessageDialogHelper::addButton(const QString& text, QHBoxLayout* thatLayout, LtsFramelessDialog* dialog,
QPushButton* LtsMessageDialogHelper::addButton(const QString &text, QHBoxLayout *thatLayout, LtsFramelessDialog *dialog, const Button &button, QWidget *parent) const Button& button, QWidget* parent)
{ {
QPushButton* btn = new QPushButton(text, parent); QPushButton* btn = new QPushButton(text, parent);
connect(btn, &QPushButton::clicked, dialog, &LtsFramelessDialog::accept); connect(btn, &QPushButton::clicked, dialog, &LtsFramelessDialog::accept);
thatLayout->addWidget(btn); thatLayout->addWidget(btn);
if (button == Button::Ok || if (button == Button::Ok || button == Button::Cancel)
button == Button::Cancel)
{ {
btn->setDefault(true); btn->setDefault(true);
} }
@@ -152,4 +139,4 @@ QPushButton* LtsMessageDialogHelper::addButton(const QString &text, QHBoxLayout
return btn; return btn;
} }
} } // namespace LtsWidgets
+6 -8
View File
@@ -1,10 +1,10 @@
#pragma once #pragma once
#include <QObject>
#include "ltswidgets_export.h" #include "ltswidgets_export.h"
#include <QObject>
#include <QRegularExpression>
#include <QSet> #include <QSet>
#include <QSpinBox> #include <QSpinBox>
@@ -19,7 +19,6 @@ public:
explicit LtsMultiRangeSpinBox(QWidget* parent = nullptr); explicit LtsMultiRangeSpinBox(QWidget* parent = nullptr);
~LtsMultiRangeSpinBox() = default; ~LtsMultiRangeSpinBox() = default;
public slots: public slots:
void setRanges(const QVector<QPair<int, int>>& ranges); void setRanges(const QVector<QPair<int, int>>& ranges);
void setRange(int min, int max); void setRange(int min, int max);
@@ -41,13 +40,12 @@ private:
int fixupValue(int value) const; int fixupValue(int value) const;
int fixupValue(int value, bool higher) const; int fixupValue(int value, bool higher) const;
private: private:
QVector<QPair<int, int>> m_rangesList; QVector<QPair<int, int>> m_rangesList;
int m_curVal = minimum(); int m_curVal = minimum();
QRegExp m_regex; QRegularExpression m_regex;
}; };
} // namespace LtsWidgets
}
+35 -57
View File
@@ -1,38 +1,30 @@
#include "lts_notification_box.h" #include "lts_notification_box.h"
#include "ui_lts_notification_box.h" #include "ui_lts_notification_box.h"
#include <QPainter>
#include <QLinearGradient>
#include <QColor> #include <QColor>
#include <QGraphicsDropShadowEffect> #include <QGraphicsDropShadowEffect>
#include <QStyleOption> #include <QLinearGradient>
#include <QPainter>
#include <QStyle> #include <QStyle>
#include <QStyleOption>
#ifdef NOTIBOX_DEBUG #ifdef NOTIBOX_DEBUG
#include <QDebug> #include <QDebug>
#endif #endif
namespace LtsWidgets namespace LtsWidgets
{ {
const int LtsNotificationBox::margin = 14; const int LtsNotificationBox::margin = 14;
LtsNotificationBox::LtsNotificationBox(QWidget *parent) LtsNotificationBox::LtsNotificationBox(QWidget* parent) : QWidget(parent), m_ui(new Ui::NotiBox)
: QWidget(parent)
, m_ui(new Ui::NotiBox)
{ {
m_ui->setupUi(this); m_ui->setupUi(this);
m_ui->lblText->setText({}); m_ui->lblText->setText({});
connect(m_ui->lblText, &QLabel::linkActivated, connect(m_ui->lblText, &QLabel::linkActivated, this, [this](const QString& link) { emit signalLinkClicked(link); });
this, [this](const QString &link)
{
emit signalLinkClicked(link);
});
connect(m_ui->tbClose, &QToolButton::clicked, connect(m_ui->tbClose, &QToolButton::clicked, this, &LtsNotificationBox::signalClose);
this, &LtsNotificationBox::signalClose); connect(m_ui->tbAck, &QToolButton::clicked, this, &LtsNotificationBox::signalAck);
connect(m_ui->tbAck, &QToolButton::clicked,
this, &LtsNotificationBox::signalAck);
setObjectName(QStringLiteral("NotiBox")); setObjectName(QStringLiteral("NotiBox"));
@@ -44,7 +36,6 @@ LtsNotificationBox::LtsNotificationBox(QWidget *parent)
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 rgbBaseString(QStringLiteral("%1, %2, %3"));
@@ -67,7 +58,6 @@ void LtsNotificationBox::message(const QString &title, const QString &text, Mess
static QColor warningStart(253, 151, 4); static QColor warningStart(253, 151, 4);
static QColor warningEnd(253, 202, 0); static QColor warningEnd(253, 202, 0);
QColor start; QColor start;
QColor end; QColor end;
QString close; QString close;
@@ -78,8 +68,7 @@ void LtsNotificationBox::message(const QString &title, const QString &text, Mess
switch (type) switch (type)
{ {
case MessageType::Error: case MessageType::Error: {
{
start = errorStart; start = errorStart;
end = errorEnd; end = errorEnd;
close = closeDefault; close = closeDefault;
@@ -92,8 +81,7 @@ void LtsNotificationBox::message(const QString &title, const QString &text, Mess
break; break;
} }
case MessageType::Success: case MessageType::Success: {
{
start = successStart; start = successStart;
end = successEnd; end = successEnd;
close = closeDefault; close = closeDefault;
@@ -106,8 +94,7 @@ void LtsNotificationBox::message(const QString &title, const QString &text, Mess
break; break;
} }
case MessageType::Info: case MessageType::Info: {
{
start = infoStart; start = infoStart;
end = infoEnd; end = infoEnd;
close = closeDefault; close = closeDefault;
@@ -120,8 +107,7 @@ void LtsNotificationBox::message(const QString &title, const QString &text, Mess
break; break;
} }
case MessageType::Warning: case MessageType::Warning: {
{
start = warningStart; start = warningStart;
end = warningEnd; end = warningEnd;
close = closeDark; close = closeDark;
@@ -137,17 +123,26 @@ void LtsNotificationBox::message(const QString &title, const QString &text, Mess
QStringList css; 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 }"). css << QStringLiteral("#NotiBox { background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop: 0 rgb(%1), stop: 1 "
arg(rgbBaseString.arg(start.red()).arg(start.green()).arg(start.blue()), "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()),
rgbBaseString.arg(end.red()).arg(end.green()).arg(end.blue())). rgbBaseString.arg(end.red()).arg(end.green()).arg(end.blue()))
arg(margin); .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 { border-image: url(:/%1) 0 0 0 0 stretch stretch; border-width: 0px; "
css << QStringLiteral("QToolButton#tbClose:hover { border-image: url(:/%1) 0 0 0 0 stretch stretch; border-width: 0px; background-color: transparent; }").arg(closeHover); "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 { border-image: url(:/%1) 0 0 0 0 stretch stretch; border-width: 0px; "
css << QStringLiteral("QToolButton#tbAck:hover { border-image: url(:/%1) 0 0 0 0 stretch stretch; border-width: 0px; background-color: transparent; }").arg(ackHover); "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 #ifdef NOTIBOX_DEBUG
qWarning() << "css" << css; qWarning() << "css" << css;
@@ -163,36 +158,19 @@ void LtsNotificationBox::message(const QString &title, const QString &text, Mess
m_ui->lblImage->setStyleSheet(QString()); m_ui->lblImage->setStyleSheet(QString());
setStyleSheet(css.join(QStringLiteral(" "))); setStyleSheet(css.join(QStringLiteral(" ")));
m_ui->lblText->setText(QStringLiteral("<p><span style='font-size:14pt; font-weight:600; color:#%1;'>%2</span></p><p><span style='font-size:14pt; color:#%3;'>%4</span></p>").arg(textColor, title, textColor, text)); m_ui->lblText->setText(
QStringLiteral("<p><span style='font-size:14pt; font-weight:600; color:#%1;'>%2</span></p><p><span "
"style='font-size:14pt; color:#%3;'>%4</span></p>")
.arg(textColor, title, textColor, text));
show(); show();
} }
void LtsNotificationBox::paintEvent(QPaintEvent*) void LtsNotificationBox::paintEvent(QPaintEvent*)
{ {
QStyleOption opt; QStyleOption opt;
opt.init(this); opt.initFrom(this);
QPainter p(this); QPainter p(this);
style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
} }
} } // namespace LtsWidgets
+11 -34
View File
@@ -1,30 +1,24 @@
#include "lts_profile_button.h" #include "lts_profile_button.h"
#include <QBrush>
#include <QEvent>
#include <QPaintEvent>
#include <QPainter> #include <QPainter>
#include <QPainterPath> #include <QPainterPath>
#include <QPaintEvent>
#include <QBrush>
#include <QPen> #include <QPen>
#include <QRect> #include <QRect>
#include <QEvent>
using namespace LtsWidgets; 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); QSizePolicy qsp = QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
qsp.setHeightForWidth(true); qsp.setHeightForWidth(true);
setSizePolicy(qsp); setSizePolicy(qsp);
} }
void LtsProfileButton::setPixmap(const QPixmap& pixmap) void LtsProfileButton::setPixmap(const QPixmap& pixmap)
{ {
if (pixmap.isNull()) if (pixmap.isNull())
@@ -35,16 +29,14 @@ void LtsProfileButton::setPixmap(const QPixmap &pixmap)
update(); update();
} }
void LtsProfileButton::enterEvent(QEvent* event) void LtsProfileButton::enterEvent(QEvent* event)
{ {
m_isHovered = true; m_isHovered = true;
update(); update();
QWidget::enterEvent(event); QWidget::enterEvent(static_cast<QEnterEvent*>(event));
} }
void LtsProfileButton::leaveEvent(QEvent* event) void LtsProfileButton::leaveEvent(QEvent* event)
{ {
@@ -53,7 +45,6 @@ void LtsProfileButton::leaveEvent(QEvent *event)
QWidget::leaveEvent(event); QWidget::leaveEvent(event);
} }
bool LtsProfileButton::event(QEvent* event) bool LtsProfileButton::event(QEvent* event)
{ {
if (event->type() == QEvent::MouseButtonPress && m_menuEnabled) if (event->type() == QEvent::MouseButtonPress && m_menuEnabled)
@@ -68,7 +59,6 @@ bool LtsProfileButton::event(QEvent *event)
return QWidget::event(event); return QWidget::event(event);
} }
void LtsProfileButton::paintEvent(QPaintEvent* event) void LtsProfileButton::paintEvent(QPaintEvent* event)
{ {
QPainter p(this); QPainter p(this);
@@ -79,11 +69,8 @@ void LtsProfileButton::paintEvent(QPaintEvent* event)
minSize = height() > width() ? width() : height(); minSize = height() > width() ? width() : height();
center = QPointF(width() / 2.0, height() / 2.0); center = QPointF(width() / 2.0, height() / 2.0);
p.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); p.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
QPixmap pixmap(minSize, minSize); QPixmap pixmap(minSize, minSize);
pixmap.fill(Qt::white); pixmap.fill(Qt::white);
@@ -95,24 +82,13 @@ void LtsProfileButton::paintEvent(QPaintEvent* event)
} }
} }
QPainterPath path; QPainterPath path;
path.addEllipse(center, path.addEllipse(center, minSize / 2.0 - 4, minSize / 2.0 - 4);
minSize / 2.0 - 4,
minSize / 2.0 - 4);
p.setClipPath(path); p.setClipPath(path);
p.drawPixmap(center - QPointF(minSize / 2.0, minSize / 2.0), pixmap); p.drawPixmap(center - QPointF(minSize / 2.0, minSize / 2.0), pixmap);
p.setPen(QPen(QColor("gray"), 2)); p.setPen(QPen(QColor("gray"), 2));
p.drawEllipse(center, p.drawEllipse(center, minSize / 2.0 - 4, minSize / 2.0 - 4);
minSize / 2.0 - 4,
minSize / 2.0 - 4);
if (m_isHovered && m_menuEnabled) if (m_isHovered && m_menuEnabled)
{ {
@@ -122,12 +98,13 @@ void LtsProfileButton::paintEvent(QPaintEvent* event)
double yc = size().height() / 2.012; double yc = size().height() / 2.012;
double diff = minSize / 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 - (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 - 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))); p.drawLine(QPointF(xc - (diff / 2.01f), yc + (diff / 3.01f)),
QPointF(xc + (diff / 2.02f), yc + (diff / 3.02f)));
} }
event->accept(); event->accept();
p.restore(); p.restore();
} }
+43 -134
View File
@@ -1,38 +1,36 @@
#include "lts_tab_widget.h" #include "lts_tab_widget.h"
#include "lts_tab_bar.h" #include "lts_tab_bar.h"
#include <LtsWidgets/lts_dialog.h> #include <LtsWidgets/lts_dialog.h>
#include <LtsWidgets/lts_dialog_helper.h> #include <LtsWidgets/lts_dialog_helper.h>
#include <LtsWidgets/lts_splitter.h> #include <LtsWidgets/lts_splitter.h>
#include <QAbstractButton> #include <QAbstractButton>
#include <QDialog> #include <QApplication>
#include <QBrush>
#include <QColor>
#include <QDebug> #include <QDebug>
#include <QSize> #include <QDialog>
#include <QFontMetrics>
#include <QLabel>
#include <QLineF>
#include <QPaintEvent> #include <QPaintEvent>
#include <QPainter> #include <QPainter>
#include <QBrush>
#include <QApplication>
#include <QColor>
#include <QPen> #include <QPen>
#include <QFontMetrics>
#include <QRectF>
#include <QLineF>
#include <QPointF> #include <QPointF>
#include <math.h> #include <QRandomGenerator>
#include <QRectF>
#include <QSize>
#include <QTimer> #include <QTimer>
#include <QLabel> #include <math.h>
namespace LtsWidgets namespace LtsWidgets
{ {
LtsTabWidget::LtsTabWidget(QWidget* parent, bool isSecondary) LtsTabWidget::LtsTabWidget(QWidget* parent, bool isSecondary)
: QTabWidget(parent) : QTabWidget(parent), m_tabbar(nullptr), m_hasSubTabs(false), m_isSecondary(isSecondary),
, m_tabbar(nullptr) m_mainSplitterState(QByteArray())
, m_hasSubTabs(false)
, m_isSecondary(isSecondary)
, m_mainSplitterState(QByteArray())
{ {
setDocumentMode(true); setDocumentMode(true);
setMinimumSize(200, 100); setMinimumSize(200, 100);
@@ -52,20 +50,15 @@ LtsTabWidget::LtsTabWidget(QWidget *parent, bool isSecondary)
bold = false; bold = false;
} }
currentFont.setCapitalization(c); currentFont.setCapitalization(c);
currentFont.setBold(bold); currentFont.setBold(bold);
tabBar->setFont(currentFont); tabBar->setFont(currentFont);
connect(this, &LtsTabWidget::currentChanged, connect(this, &LtsTabWidget::currentChanged, this, &LtsTabWidget::slotCurrentChanged);
this, &LtsTabWidget::slotCurrentChanged);
QSplitter* splitter = static_cast<QSplitter*>(parent); QSplitter* splitter = static_cast<QSplitter*>(parent);
if (splitter && if (splitter && splitter->objectName() == QStringLiteral("mainSplitter") && splitter->widget(1) == this &&
splitter->objectName() == QStringLiteral("mainSplitter") &&
splitter->widget(1) == this &&
!isSecondary) !isSecondary)
{ {
int tabBarHeight = m_tabbar->height() * 1.33; int tabBarHeight = m_tabbar->height() * 1.33;
@@ -73,7 +66,8 @@ LtsTabWidget::LtsTabWidget(QWidget *parent, bool isSecondary)
setStyleSheet(styleSheet() + QStringLiteral("QTabWidget::tab-bar {" setStyleSheet(styleSheet() + QStringLiteral("QTabWidget::tab-bar {"
"left: %1px; " "left: %1px; "
"} ").arg(tabBarWidth)); "} ")
.arg(tabBarWidth));
QPushButton* maxBtn = new QPushButton(this); QPushButton* maxBtn = new QPushButton(this);
maxBtn->setObjectName(QStringLiteral("MinMaxTabButton")); maxBtn->setObjectName(QStringLiteral("MinMaxTabButton"));
maxBtn->setText(QStringLiteral("▲\n▼")); maxBtn->setText(QStringLiteral("▲\n▼"));
@@ -86,15 +80,12 @@ LtsTabWidget::LtsTabWidget(QWidget *parent, bool isSecondary)
} }
} }
LtsTabWidget::~LtsTabWidget() LtsTabWidget::~LtsTabWidget()
{ {
clearAll(); clearAll();
} }
void LtsTabWidget::slotCurrentChanged(int newIdx) void LtsTabWidget::slotCurrentChanged(int newIdx)
{ {
if (newIdx < 0) if (newIdx < 0)
@@ -117,7 +108,6 @@ void LtsTabWidget::slotCurrentChanged(int newIdx)
return; return;
} }
LtsTabWidget* tab = qobject_cast<LtsTabWidget*>(w); LtsTabWidget* tab = qobject_cast<LtsTabWidget*>(w);
if (tab != nullptr) if (tab != nullptr)
@@ -153,7 +143,6 @@ void LtsTabWidget::slotMaximizeButtonClicked()
} }
} }
void LtsTabWidget::closeRequestTabWidget(LtsTabWidget* tabWidget) void LtsTabWidget::closeRequestTabWidget(LtsTabWidget* tabWidget)
{ {
for (int i = 0; i < tabWidget->count(); i++) for (int i = 0; i < tabWidget->count(); i++)
@@ -176,7 +165,6 @@ void LtsTabWidget::closeRequestTabWidget(LtsTabWidget *tabWidget)
} }
} }
void LtsTabWidget::slotTabCloseRequested(int index) void LtsTabWidget::slotTabCloseRequested(int index)
{ {
QWidget* w = widget(index); QWidget* w = widget(index);
@@ -214,7 +202,10 @@ void LtsTabWidget::slotTabCloseRequested(int index)
buttons.setFlag(Button::Cancel, true); buttons.setFlag(Button::Cancel, true);
QHash<Button, QString> buttonTexts; QHash<Button, QString> buttonTexts;
buttonTexts.insert(Button::Yes, tr("Discard All")); buttonTexts.insert(Button::Yes, tr("Discard All"));
const auto ret = LtsMessageDialog::showMessage(this, tr("There are dialogs with unsaved changes.<br>Please save or discard their changes before closing."), tr("Unsaved changes"), Behaviour::Modal, buttons, buttonTexts); const auto ret = LtsMessageDialog::showMessage(
this,
tr("There are dialogs with unsaved changes.<br>Please save or discard their changes before closing."),
tr("Unsaved changes"), Behaviour::Modal, buttons, buttonTexts);
switch (ret) switch (ret)
{ {
case Button::Yes: case Button::Yes:
@@ -231,15 +222,11 @@ void LtsTabWidget::slotTabCloseRequested(int index)
} }
} }
w->deleteLater(); w->deleteLater();
} }
void LtsTabWidget::onCheckTabBarVisibility() void LtsTabWidget::onCheckTabBarVisibility()
{ {
if (!m_isSecondary) if (!m_isSecondary)
{ {
@@ -251,36 +238,8 @@ void LtsTabWidget::onCheckTabBarVisibility()
if (count() < 1) if (count() < 1)
deleteLater(); deleteLater();
} }
} }
void LtsTabWidget::setSubTabsVisible(bool visible) void LtsTabWidget::setSubTabsVisible(bool visible)
{ {
if (count()) if (count())
@@ -292,19 +251,14 @@ void LtsTabWidget::setSubTabsVisible(bool visible)
m_hasSubTabs = visible; m_hasSubTabs = visible;
} }
void LtsTabWidget::addTab(const QString& menuGroup, const QString& identifier, QWidget* widget, bool setClosable,
void LtsTabWidget::addTab(const QString &menuGroup, const QString &identifier, QWidget *widget, bool focusNewTab)
bool setClosable, bool focusNewTab)
{ {
setFocus(); setFocus();
LtsTabWidget* tab = this; LtsTabWidget* tab = this;
QString fullName; QString fullName;
if (m_hasSubTabs) if (m_hasSubTabs)
{ {
fullName = identifier; fullName = identifier;
@@ -329,15 +283,12 @@ void LtsTabWidget::addTab(const QString &menuGroup, const QString &identifier, Q
else else
{ {
fullName = menuGroup + QLatin1Char('.') + identifier; fullName = menuGroup + QLatin1Char('.') + identifier;
} }
setHidden(false); setHidden(false);
tab->addWidget(fullName, widget, setClosable, focusNewTab); tab->addWidget(fullName, widget, setClosable, focusNewTab);
if (m_hasSubTabs) if (m_hasSubTabs)
{ {
LtsTabBar* tabbar = tab->tabBar(); LtsTabBar* tabbar = tab->tabBar();
@@ -354,7 +305,6 @@ void LtsTabWidget::addTab(const QString &menuGroup, const QString &identifier, Q
} }
} }
void LtsTabWidget::addWidget(const QString& fullName, QWidget* widget, bool setClosable, bool focusNewTab) void LtsTabWidget::addWidget(const QString& fullName, QWidget* widget, bool setClosable, bool focusNewTab)
{ {
QString theName = fullName; QString theName = fullName;
@@ -362,13 +312,14 @@ void LtsTabWidget::addWidget(const QString &fullName, QWidget *widget, bool setC
if (fullName.isEmpty()) if (fullName.isEmpty())
{ {
const QString possibleCharacters(QStringLiteral("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")); const QString possibleCharacters(
QStringLiteral("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"));
const int randomStringLength = 24; const int randomStringLength = 24;
QString randomString; QString randomString;
for (int i = 0; i < randomStringLength; i++) for (int i = 0; i < randomStringLength; i++)
{ {
int index = qrand() % possibleCharacters.length(); int index = QRandomGenerator::global()->bounded(possibleCharacters.length());
QChar nextChar = possibleCharacters.at(index); QChar nextChar = possibleCharacters.at(index);
randomString.append(nextChar); randomString.append(nextChar);
} }
@@ -394,23 +345,22 @@ void LtsTabWidget::addWidget(const QString &fullName, QWidget *widget, bool setC
if (helper) if (helper)
{ {
connect(helper->getDialog(), &LtsDialog::signalHide, this, static_cast<void (LtsTabWidget::*)(QObject*)>(&LtsTabWidget::onRemoveTab), connect(helper->getDialog(), &LtsDialog::signalHide, this,
static_cast<void (LtsTabWidget::*)(QObject*)>(&LtsTabWidget::onRemoveTab),
static_cast<Qt::ConnectionType>(Qt::QueuedConnection | Qt::UniqueConnection)); static_cast<Qt::ConnectionType>(Qt::QueuedConnection | Qt::UniqueConnection));
} }
connect(widget, &QWidget::destroyed, this, static_cast<void (LtsTabWidget::*)(QObject*)>(&LtsTabWidget::onRemoveTab), Qt::DirectConnection); connect(widget, &QWidget::destroyed, this,
static_cast<void (LtsTabWidget::*)(QObject*)>(&LtsTabWidget::onRemoveTab), Qt::DirectConnection);
connect(widget, &QWidget::windowTitleChanged, this, &LtsTabWidget::slotWindowTitleChanged); connect(widget, &QWidget::windowTitleChanged, this, &LtsTabWidget::slotWindowTitleChanged);
if (helper) if (helper)
{ {
m_tabMap.insert(theName, helper); m_tabMap.insert(theName, helper);
} }
else else
{ {
m_tabMap.insert(theName, widget); m_tabMap.insert(theName, widget);
} }
int newTabIndex = QTabWidget::addTab(widget, title); int newTabIndex = QTabWidget::addTab(widget, title);
@@ -437,10 +387,8 @@ void LtsTabWidget::addWidget(const QString &fullName, QWidget *widget, bool setC
if (tabbar) if (tabbar)
tabbar->updateCloseButtonColors(); tabbar->updateCloseButtonColors();
} }
void LtsTabWidget::slotWindowTitleChanged(const QString& title) void LtsTabWidget::slotWindowTitleChanged(const QString& title)
{ {
QWidget* w = qobject_cast<QWidget*>(sender()); QWidget* w = qobject_cast<QWidget*>(sender());
@@ -459,7 +407,6 @@ void LtsTabWidget::slotWindowTitleChanged(const QString &title)
return; return;
} }
QString realTitle = title; QString realTitle = title;
QString readOnlyHint; QString readOnlyHint;
QStringList sl = title.split(QStringLiteral("- READ-ONLY")); QStringList sl = title.split(QStringLiteral("- READ-ONLY"));
@@ -468,7 +415,6 @@ void LtsTabWidget::slotWindowTitleChanged(const QString &title)
realTitle = sl.first().trimmed(); realTitle = sl.first().trimmed();
readOnlyHint = sl.back().trimmed(); readOnlyHint = sl.back().trimmed();
if (readOnlyHint.startsWith(QStringLiteral("("))) if (readOnlyHint.startsWith(QStringLiteral("(")))
readOnlyHint.remove(0, 1); readOnlyHint.remove(0, 1);
if (readOnlyHint.endsWith(QStringLiteral(")"))) if (readOnlyHint.endsWith(QStringLiteral(")")))
@@ -488,14 +434,13 @@ void LtsTabWidget::slotWindowTitleChanged(const QString &title)
readOnly->setPixmap(QIcon(QStringLiteral("icon:warning.svg")).pixmap(QSize(25, 25))); readOnly->setPixmap(QIcon(QStringLiteral("icon:warning.svg")).pixmap(QSize(25, 25)));
tabBar->setTabButton(index, QTabBar::ButtonPosition::LeftSide, readOnly); tabBar->setTabButton(index, QTabBar::ButtonPosition::LeftSide, readOnly);
} else { }
else
{
QWidget* readOnly = tabBar->tabButton(index, QTabBar::ButtonPosition::LeftSide); QWidget* readOnly = tabBar->tabButton(index, QTabBar::ButtonPosition::LeftSide);
if (readOnly) if (readOnly)
{ {
tabBar->setTabButton(index, QTabBar::ButtonPosition::LeftSide, nullptr); tabBar->setTabButton(index, QTabBar::ButtonPosition::LeftSide, nullptr);
readOnly->setParent(this); readOnly->setParent(this);
delete readOnly; delete readOnly;
@@ -503,7 +448,6 @@ void LtsTabWidget::slotWindowTitleChanged(const QString &title)
} }
} }
QWidget* LtsTabWidget::getWidget(const QString& menuGroup, const QString& identifier) QWidget* LtsTabWidget::getWidget(const QString& menuGroup, const QString& identifier)
{ {
LtsTabWidget* tab = this; LtsTabWidget* tab = this;
@@ -525,13 +469,11 @@ QWidget *LtsTabWidget::getWidget(const QString &menuGroup, const QString &identi
return tab->getWidget(fullName); return tab->getWidget(fullName);
} }
QWidget* LtsTabWidget::getWidget(const QString& fullName) QWidget* LtsTabWidget::getWidget(const QString& fullName)
{ {
return m_tabMap.value(fullName, nullptr); return m_tabMap.value(fullName, nullptr);
} }
bool LtsTabWidget::focusTab(const QString& menuGroup, const QString& identifier) bool LtsTabWidget::focusTab(const QString& menuGroup, const QString& identifier)
{ {
QPointer<LtsTabWidget> tab = this; QPointer<LtsTabWidget> tab = this;
@@ -555,16 +497,9 @@ bool LtsTabWidget::focusTab(const QString &menuGroup, const QString &identifier)
if (!tab) if (!tab)
return false; return false;
LtsSplitter* splitter = static_cast<LtsSplitter*>(parent()); LtsSplitter* splitter = static_cast<LtsSplitter*>(parent());
QTimer::singleShot(500, this, [splitter, tab]() { QTimer::singleShot(500, this, [splitter, tab]() {
if (splitter && tab && (tab->count() >= 1) && splitter->sizes().count() && !(splitter->sizes().at(1))) if (splitter && tab && (tab->count() >= 1) && splitter->sizes().count() && !(splitter->sizes().at(1)))
{ {
splitter->animate(1); splitter->animate(1);
@@ -573,7 +508,6 @@ bool LtsTabWidget::focusTab(const QString &menuGroup, const QString &identifier)
return tab->focusWidget(fullName); return tab->focusWidget(fullName);
} }
bool LtsTabWidget::focusWidget(const QString& fullName) bool LtsTabWidget::focusWidget(const QString& fullName)
{ {
QWidget* widget = m_tabMap.value(fullName, nullptr); QWidget* widget = m_tabMap.value(fullName, nullptr);
@@ -586,7 +520,6 @@ bool LtsTabWidget::focusWidget(const QString &fullName)
return true; return true;
} }
bool LtsTabWidget::removeWidget(QWidget* widget) bool LtsTabWidget::removeWidget(QWidget* widget)
{ {
if (nullptr == widget) if (nullptr == widget)
@@ -602,7 +535,8 @@ bool LtsTabWidget::removeWidget(QWidget * widget)
if (w == widget) if (w == widget)
{ {
m_tabMap.erase(i); m_tabMap.erase(i);
disconnect(widget, &QWidget::destroyed, this, static_cast<void (LtsTabWidget::*)(QObject*)>(&LtsTabWidget::onRemoveTab)); disconnect(widget, &QWidget::destroyed, this,
static_cast<void (LtsTabWidget::*)(QObject*)>(&LtsTabWidget::onRemoveTab));
return true; return true;
} }
@@ -619,7 +553,6 @@ bool LtsTabWidget::removeWidget(QWidget * widget)
return false; return false;
} }
void LtsTabWidget::onRemoveTab(QObject* object) void LtsTabWidget::onRemoveTab(QObject* object)
{ {
if (object == nullptr) if (object == nullptr)
@@ -650,7 +583,8 @@ void LtsTabWidget::onRemoveTab(QObject *object)
if (index < 0) if (index < 0)
{ {
qWarning() << "LtsTabWidget::onRemoveTab: cannot remove widget, as it was not found on the tab widget" << (void *)w; qWarning() << "LtsTabWidget::onRemoveTab: cannot remove widget, as it was not found on the tab widget"
<< (void*)w;
} }
else else
{ {
@@ -660,26 +594,22 @@ void LtsTabWidget::onRemoveTab(QObject *object)
onCheckTabBarVisibility(); onCheckTabBarVisibility();
} }
void LtsTabWidget::setActuatorTabStyle(bool enable) void LtsTabWidget::setActuatorTabStyle(bool enable)
{ {
if (enable) if (enable)
setTabBar(new LtsTabBar(false, this)); 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) if (m_tabbar)
m_tabbar->deleteLater(); m_tabbar->deleteLater();
QFont currentFont = font(); QFont currentFont = font();
currentFont.setCapitalization(QFont::SmallCaps); currentFont.setCapitalization(QFont::SmallCaps);
currentFont.setBold(true); currentFont.setBold(true);
@@ -691,11 +621,9 @@ void LtsTabWidget::setTabBar(LtsTabBar *tabbar)
QTabWidget::setTabBar(m_tabbar); QTabWidget::setTabBar(m_tabbar);
} }
void LtsTabWidget::clearAll() void LtsTabWidget::clearAll()
{ {
for (int i = 0; i < count(); i++) for (int i = 0; i < count(); i++)
{ {
QWidget* w = widget(i); QWidget* w = widget(i);
@@ -703,7 +631,8 @@ void LtsTabWidget::clearAll()
if (w == nullptr) if (w == nullptr)
continue; continue;
disconnect(w, &QWidget::destroyed, this, static_cast<void (LtsTabWidget::*)(QObject*)>(&LtsTabWidget::onRemoveTab)); disconnect(w, &QWidget::destroyed, this,
static_cast<void (LtsTabWidget::*)(QObject*)>(&LtsTabWidget::onRemoveTab));
w->deleteLater(); w->deleteLater();
} }
@@ -711,7 +640,6 @@ void LtsTabWidget::clearAll()
clear(); clear();
} }
void LtsTabWidget::aboutToClose() void LtsTabWidget::aboutToClose()
{ {
for (int i = 0; i < count(); i++) for (int i = 0; i < count(); i++)
@@ -738,7 +666,6 @@ void LtsTabWidget::aboutToClose()
} }
} }
bool LtsTabWidget::hasUnsavedChanges(LtsTabWidget* tabWidget) bool LtsTabWidget::hasUnsavedChanges(LtsTabWidget* tabWidget)
{ {
for (int i = 0; i < tabWidget->count(); i++) for (int i = 0; i < tabWidget->count(); i++)
@@ -754,14 +681,12 @@ bool LtsTabWidget::hasUnsavedChanges(LtsTabWidget *tabWidget)
if (dlg != nullptr) if (dlg != nullptr)
{ {
if (dlg->hasUnsavedChanges()) if (dlg->hasUnsavedChanges())
{ {
int dlgIndex = tabWidget->indexOf(helper); int dlgIndex = tabWidget->indexOf(helper);
if (dlgIndex != -1) if (dlgIndex != -1)
tabWidget->setCurrentIndex(dlgIndex); tabWidget->setCurrentIndex(dlgIndex);
return true; return true;
} }
} }
@@ -772,7 +697,6 @@ bool LtsTabWidget::hasUnsavedChanges(LtsTabWidget *tabWidget)
if (tab) if (tab)
{ {
bool _hasUnsavedChanges = hasUnsavedChanges(tab); bool _hasUnsavedChanges = hasUnsavedChanges(tab);
if (_hasUnsavedChanges) if (_hasUnsavedChanges)
{ {
@@ -783,19 +707,11 @@ bool LtsTabWidget::hasUnsavedChanges(LtsTabWidget *tabWidget)
return true; return true;
} }
} }
} }
return false; return false;
} }
void CloseButton::paintEvent(QPaintEvent*) void CloseButton::paintEvent(QPaintEvent*)
{ {
QPainter p(this); QPainter p(this);
@@ -804,10 +720,8 @@ void CloseButton::paintEvent(QPaintEvent *)
p.setPen(QPen(QColor(m_fontColor), 1.5)); p.setPen(QPen(QColor(m_fontColor), 1.5));
p.setRenderHint(QPainter::Antialiasing); p.setRenderHint(QPainter::Antialiasing);
p.drawLine(line()); p.drawLine(line());
p.setPen(QPen(QColor(m_fontColor), 2.5)); p.setPen(QPen(QColor(m_fontColor), 2.5));
QRectF c = cross(); QRectF c = cross();
@@ -818,7 +732,6 @@ void CloseButton::paintEvent(QPaintEvent *)
p.restore(); p.restore();
} }
QLineF CloseButton::line() const QLineF CloseButton::line() const
{ {
qreal forceBlur = 0.001; qreal forceBlur = 0.001;
@@ -828,7 +741,6 @@ QLineF CloseButton::line() const
return QLineF(QPointF(lineStart, lineStart), QPointF(lineStart, lineSize)); return QLineF(QPointF(lineStart, lineStart), QPointF(lineStart, lineSize));
} }
QRectF CloseButton::cross() const QRectF CloseButton::cross() const
{ {
QLineF l = line(); QLineF l = line();
@@ -838,13 +750,13 @@ QRectF CloseButton::cross() const
qreal crossStartX = lineLeft * 3; qreal crossStartX = lineLeft * 3;
qreal crossStartY = lineLeft * 2; qreal crossStartY = lineLeft * 2;
qreal crossEndX = width(); crossEndX -= crossEndX * 0.15 + forceBlur; qreal crossEndX = width();
crossEndX -= crossEndX * 0.15 + forceBlur;
qreal crossEndY = height() - crossStartY; qreal crossEndY = height() - crossStartY;
return QRectF(QPointF(crossStartX, crossStartY), QPointF(crossEndX, crossEndY)); return QRectF(QPointF(crossStartX, crossStartY), QPointF(crossEndX, crossEndY));
} }
QSize CloseButton::sizeHint() const QSize CloseButton::sizeHint() const
{ {
QFontMetrics fm(QApplication::font()); QFontMetrics fm(QApplication::font());
@@ -858,14 +770,12 @@ QSize CloseButton::sizeHint() const
return QSize(finalSize, finalSize); return QSize(finalSize, finalSize);
} }
void CloseButton::mousePressEvent(QMouseEvent* e) void CloseButton::mousePressEvent(QMouseEvent* e)
{ {
e->ignore(); e->ignore();
m_isPressed = true; m_isPressed = true;
} }
void CloseButton::mouseReleaseEvent(QMouseEvent* e) void CloseButton::mouseReleaseEvent(QMouseEvent* e)
{ {
bool isPressed = m_isPressed; bool isPressed = m_isPressed;
@@ -887,8 +797,7 @@ void CloseButton::mouseReleaseEvent(QMouseEvent *e)
return; return;
} }
e->accept(); e->accept();
emit clicked(); emit clicked();
} }
} } // namespace LtsWidgets
+41 -80
View File
@@ -2,76 +2,52 @@
#include "ui_lts_text_editor.h" #include "ui_lts_text_editor.h"
#include <QColorDialog>
#include <QTextCursor>
#include <QApplication> #include <QApplication>
#include <QClipboard> #include <QClipboard>
#include <QTextCharFormat> #include <QColorDialog>
#include <QMimeData>
#include <QTextList>
#include <QLineEdit>
#include <QDebug> #include <QDebug>
#include <QLineEdit>
#include <QMimeData>
#include <QTextCharFormat>
#include <QTextCursor>
#include <QTextList>
namespace LtsWidgets namespace LtsWidgets
{ {
LtsTextEditor::LtsTextEditor(QWidget *parent) LtsTextEditor::LtsTextEditor(QWidget* parent) : QWidget(parent), m_ui(new Ui::LtsTextEditor)
: QWidget(parent)
, m_ui(new Ui::LtsTextEditor)
{ {
m_ui->setupUi(this); m_ui->setupUi(this);
connect(m_ui->textEdit, &QTextEdit::currentCharFormatChanged, connect(m_ui->textEdit, &QTextEdit::currentCharFormatChanged, this, &LtsTextEditor::slotCurrentCharFormatChanged);
this, &LtsTextEditor::slotCurrentCharFormatChanged); connect(m_ui->textEdit, &QTextEdit::cursorPositionChanged, this, &LtsTextEditor::slotAlignmentChanged);
connect(m_ui->textEdit, &QTextEdit::cursorPositionChanged,
this, &LtsTextEditor::slotAlignmentChanged);
connect(m_ui->textEdit->document(), &QTextDocument::undoAvailable, connect(m_ui->textEdit->document(), &QTextDocument::undoAvailable, m_ui->pbUndo, &QToolButton::setEnabled);
m_ui->pbUndo, &QToolButton::setEnabled); connect(m_ui->textEdit->document(), &QTextDocument::redoAvailable, m_ui->pbRedo, &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->pbUndo->setEnabled(m_ui->textEdit->document()->isUndoAvailable());
m_ui->pbRedo->setEnabled(m_ui->textEdit->document()->isRedoAvailable()); m_ui->pbRedo->setEnabled(m_ui->textEdit->document()->isRedoAvailable());
connect(QApplication::clipboard(), &QClipboard::dataChanged, connect(QApplication::clipboard(), &QClipboard::dataChanged, this, &LtsTextEditor::slotClipboardDataChanged);
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, connect(m_ui->pbUndo, &QToolButton::clicked, m_ui->textEdit, &QTextEdit::undo);
m_ui->textEdit, &QTextEdit::cut); connect(m_ui->pbRedo, &QToolButton::clicked, m_ui->textEdit, &QTextEdit::redo);
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, connect(m_ui->pbBold, &QToolButton::clicked, this, &LtsTextEditor::slotTextBold);
m_ui->textEdit, &QTextEdit::undo); connect(m_ui->pbItalic, &QToolButton::clicked, this, &LtsTextEditor::slotTextItalic);
connect(m_ui->pbRedo, &QToolButton::clicked, connect(m_ui->pbUnderline, &QToolButton::clicked, this, &LtsTextEditor::slotTextUnderline);
m_ui->textEdit, &QTextEdit::redo);
connect(m_ui->pbBold, &QToolButton::clicked, connect(m_ui->pbTextColor, &QToolButton::clicked, this, &LtsTextEditor::slotTextColor);
this, &LtsTextEditor::slotTextBold); connect(m_ui->pbBackgroundColor, &QToolButton::clicked, this, &LtsTextEditor::slotBackgroundColor);
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->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")); QFont textFont(QStringLiteral("Sans Serif"));
textFont.setStyleHint(QFont::SansSerif); textFont.setStyleHint(QFont::SansSerif);
@@ -82,31 +58,26 @@ LtsTextEditor::LtsTextEditor(QWidget *parent)
slotBackgroundColorChanged(m_backgroundColor); slotBackgroundColorChanged(m_backgroundColor);
connect(m_ui->cbFonts, &QComboBox::currentTextChanged, this, &LtsTextEditor::slotTextFamily);
connect(m_ui->cbFonts, QOverload<const QString &>::of(&QComboBox::activated),
this, &LtsTextEditor::slotTextFamily);
const QList<int> standardSizes = QFontDatabase::standardSizes(); const QList<int> standardSizes = QFontDatabase::standardSizes();
for (int size : standardSizes) for (int size : standardSizes)
m_ui->cbFontSize->addItem(QString::number(size)); m_ui->cbFontSize->addItem(QString::number(size));
m_ui->cbFontSize->setCurrentIndex(standardSizes.indexOf(QApplication::font().pointSize())); m_ui->cbFontSize->setCurrentIndex(standardSizes.indexOf(QApplication::font().pointSize()));
connect(m_ui->cbFontSize, QOverload<const QString &>::of(&QComboBox::activated), connect(m_ui->cbFontSize, &QComboBox::currentTextChanged, this, &LtsTextEditor::slotTextSize);
this, &LtsTextEditor::slotTextSize);
connect(m_ui->cbFontSize->lineEdit(), &QLineEdit::editingFinished, connect(m_ui->cbFontSize->lineEdit(), &QLineEdit::editingFinished, this,
this, &LtsTextEditor::slotTextSizeEditingFinished); &LtsTextEditor::slotTextSizeEditingFinished);
m_ui->textEdit->setFocus(); m_ui->textEdit->setFocus();
} }
LtsTextEditor::~LtsTextEditor() LtsTextEditor::~LtsTextEditor()
{ {
delete m_ui; delete m_ui;
} }
QTextEdit* LtsTextEditor::textEdit() QTextEdit* LtsTextEditor::textEdit()
{ {
return m_ui->textEdit; return m_ui->textEdit;
@@ -129,7 +100,6 @@ void LtsTextEditor::setInitialBackgroundColor(const QColor &bgColor)
slotBackgroundColorChanged(m_backgroundColor); slotBackgroundColorChanged(m_backgroundColor);
} }
void LtsTextEditor::slotTextBold() void LtsTextEditor::slotTextBold()
{ {
QTextCharFormat fmt; QTextCharFormat fmt;
@@ -142,13 +112,13 @@ void LtsTextEditor::slotTextBold()
fmt.setFontFamily(f); fmt.setFontFamily(f);
fmt.setFontFamilies({f}); fmt.setFontFamilies({f});
fmt.setForeground(m_foregroundColor); fmt.setForeground(m_foregroundColor);
const qreal pointSize = (m_ui->cbFontSize->currentText().toFloat() > 0 ? m_ui->cbFontSize->currentText().toFloat() : 11); const qreal pointSize =
(m_ui->cbFontSize->currentText().toFloat() > 0 ? m_ui->cbFontSize->currentText().toFloat() : 11);
fmt.setFontPointSize(pointSize); fmt.setFontPointSize(pointSize);
} }
slotMergeFormatOnWordOrSelection(fmt); slotMergeFormatOnWordOrSelection(fmt);
} }
void LtsTextEditor::slotTextUnderline() void LtsTextEditor::slotTextUnderline()
{ {
QTextCharFormat fmt; QTextCharFormat fmt;
@@ -161,13 +131,13 @@ void LtsTextEditor::slotTextUnderline()
fmt.setFontFamily(f); fmt.setFontFamily(f);
fmt.setFontFamilies({f}); fmt.setFontFamilies({f});
fmt.setForeground(m_foregroundColor); fmt.setForeground(m_foregroundColor);
const qreal pointSize = (m_ui->cbFontSize->currentText().toFloat() > 0 ? m_ui->cbFontSize->currentText().toFloat() : 11); const qreal pointSize =
(m_ui->cbFontSize->currentText().toFloat() > 0 ? m_ui->cbFontSize->currentText().toFloat() : 11);
fmt.setFontPointSize(pointSize); fmt.setFontPointSize(pointSize);
} }
slotMergeFormatOnWordOrSelection(fmt); slotMergeFormatOnWordOrSelection(fmt);
} }
void LtsTextEditor::slotTextItalic() void LtsTextEditor::slotTextItalic()
{ {
QTextCharFormat fmt; QTextCharFormat fmt;
@@ -180,13 +150,13 @@ void LtsTextEditor::slotTextItalic()
fmt.setFontFamily(f); fmt.setFontFamily(f);
fmt.setFontFamilies({f}); fmt.setFontFamilies({f});
fmt.setForeground(m_foregroundColor); fmt.setForeground(m_foregroundColor);
const qreal pointSize = (m_ui->cbFontSize->currentText().toFloat() > 0 ? m_ui->cbFontSize->currentText().toFloat() : 11); const qreal pointSize =
(m_ui->cbFontSize->currentText().toFloat() > 0 ? m_ui->cbFontSize->currentText().toFloat() : 11);
fmt.setFontPointSize(pointSize); fmt.setFontPointSize(pointSize);
} }
slotMergeFormatOnWordOrSelection(fmt); slotMergeFormatOnWordOrSelection(fmt);
} }
void LtsTextEditor::slotTextFamily(const QString& f) void LtsTextEditor::slotTextFamily(const QString& f)
{ {
QTextCharFormat fmt; QTextCharFormat fmt;
@@ -196,7 +166,8 @@ void LtsTextEditor::slotTextFamily(const QString &f)
fmt.setFontUnderline(m_ui->pbUnderline->isChecked()); fmt.setFontUnderline(m_ui->pbUnderline->isChecked());
fmt.setFontWeight(m_ui->pbBold->isChecked() ? QFont::Bold : QFont::Normal); 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); const qreal pointSize =
(m_ui->cbFontSize->currentText().toFloat() > 0 ? m_ui->cbFontSize->currentText().toFloat() : 11);
fmt.setFontPointSize(pointSize); fmt.setFontPointSize(pointSize);
fmt.setForeground(m_foregroundColor); fmt.setForeground(m_foregroundColor);
} }
@@ -205,7 +176,6 @@ void LtsTextEditor::slotTextFamily(const QString &f)
slotMergeFormatOnWordOrSelection(fmt); slotMergeFormatOnWordOrSelection(fmt);
} }
void LtsTextEditor::slotTextSize(const QString& p) void LtsTextEditor::slotTextSize(const QString& p)
{ {
qreal pointSize = p.toFloat(); qreal pointSize = p.toFloat();
@@ -226,7 +196,6 @@ void LtsTextEditor::slotTextSize(const QString &p)
fmt.setFontItalic(m_ui->pbItalic->isChecked()); fmt.setFontItalic(m_ui->pbItalic->isChecked());
fmt.setFontUnderline(m_ui->pbUnderline->isChecked()); fmt.setFontUnderline(m_ui->pbUnderline->isChecked());
fmt.setFontWeight(m_ui->pbBold->isChecked() ? QFont::Bold : QFont::Normal); fmt.setFontWeight(m_ui->pbBold->isChecked() ? QFont::Bold : QFont::Normal);
} }
fmt.setFontPointSize(pointSize); fmt.setFontPointSize(pointSize);
slotMergeFormatOnWordOrSelection(fmt); slotMergeFormatOnWordOrSelection(fmt);
@@ -271,7 +240,8 @@ void LtsTextEditor::slotTextColor()
const QString& f = m_ui->cbFonts->currentText(); const QString& f = m_ui->cbFonts->currentText();
fmt.setFontFamily(f); fmt.setFontFamily(f);
fmt.setFontFamilies({f}); fmt.setFontFamilies({f});
const qreal pointSize = (m_ui->cbFontSize->currentText().toFloat() > 0 ? m_ui->cbFontSize->currentText().toFloat() : 11); const qreal pointSize =
(m_ui->cbFontSize->currentText().toFloat() > 0 ? m_ui->cbFontSize->currentText().toFloat() : 11);
fmt.setFontPointSize(pointSize); fmt.setFontPointSize(pointSize);
} }
fmt.setForeground(col); fmt.setForeground(col);
@@ -290,14 +260,12 @@ void LtsTextEditor::slotBackgroundColor()
emit backgroundColorChanged(m_backgroundColor); emit backgroundColorChanged(m_backgroundColor);
} }
void LtsTextEditor::slotCurrentCharFormatChanged(const QTextCharFormat& format) void LtsTextEditor::slotCurrentCharFormatChanged(const QTextCharFormat& format)
{ {
slotFontChanged(format.font()); slotFontChanged(format.font());
slotTextColorChanged(format.foreground().color()); 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()));
@@ -317,7 +285,6 @@ void LtsTextEditor::slotFontChanged(const QFont &f)
m_ui->pbUnderline->setChecked(f.underline()); m_ui->pbUnderline->setChecked(f.underline());
} }
void LtsTextEditor::slotMergeFormatOnWordOrSelection(const QTextCharFormat& format) void LtsTextEditor::slotMergeFormatOnWordOrSelection(const QTextCharFormat& format)
{ {
QTextCursor cursor = m_ui->textEdit->textCursor(); QTextCursor cursor = m_ui->textEdit->textCursor();
@@ -326,12 +293,10 @@ void LtsTextEditor::slotMergeFormatOnWordOrSelection(const QTextCharFormat &form
cursor.mergeCharFormat(format); cursor.mergeCharFormat(format);
if (m_ui->textEdit->document()->isEmpty()) if (m_ui->textEdit->document()->isEmpty())
m_ui->textEdit->setTextCursor(cursor); m_ui->textEdit->setTextCursor(cursor);
} }
void LtsTextEditor::slotTextColorChanged(const QColor& c) void LtsTextEditor::slotTextColorChanged(const QColor& c)
{ {
QPixmap pix(32, 32); QPixmap pix(32, 32);
@@ -340,7 +305,6 @@ void LtsTextEditor::slotTextColorChanged(const QColor &c)
m_foregroundColor = c; m_foregroundColor = c;
} }
void LtsTextEditor::slotBackgroundColorChanged(const QColor& bgColor) void LtsTextEditor::slotBackgroundColorChanged(const QColor& bgColor)
{ {
QPixmap pix(32, 32); QPixmap pix(32, 32);
@@ -348,7 +312,6 @@ void LtsTextEditor::slotBackgroundColorChanged(const QColor &bgColor)
m_ui->pbBackgroundColor->setIcon(pix); m_ui->pbBackgroundColor->setIcon(pix);
} }
void LtsTextEditor::slotTextAlign() void LtsTextEditor::slotTextAlign()
{ {
QToolButton* b = qobject_cast<QToolButton*>(sender()); QToolButton* b = qobject_cast<QToolButton*>(sender());
@@ -366,7 +329,6 @@ void LtsTextEditor::slotTextAlign()
m_ui->textEdit->setAlignment(Qt::AlignJustify); m_ui->textEdit->setAlignment(Qt::AlignJustify);
} }
void LtsTextEditor::slotAlignmentChanged() void LtsTextEditor::slotAlignmentChanged()
{ {
auto a = m_ui->textEdit->alignment(); auto a = m_ui->textEdit->alignment();
@@ -381,11 +343,10 @@ void LtsTextEditor::slotAlignmentChanged()
m_ui->pbAlignJustify->setChecked(true); m_ui->pbAlignJustify->setChecked(true);
} }
void LtsTextEditor::slotClipboardDataChanged() void LtsTextEditor::slotClipboardDataChanged()
{ {
if (const QMimeData* md = QApplication::clipboard()->mimeData()) if (const QMimeData* md = QApplication::clipboard()->mimeData())
m_ui->pbPaste->setEnabled(md->hasText()); m_ui->pbPaste->setEnabled(md->hasText());
} }
} } // namespace LtsWidgets
+105 -85
View File
@@ -1,33 +1,31 @@
#include "lts_text_editor2.h" #include "lts_text_editor2.h"
#include <QAction> #include <QAction>
#include <QActionGroup>
#include <QApplication> #include <QApplication>
#include <QClipboard> #include <QClipboard>
#include <QCloseEvent>
#include <QColorDialog> #include <QColorDialog>
#include <QComboBox> #include <QComboBox>
#include <QFontComboBox>
#include <QFile> #include <QFile>
#include <QFileDialog> #include <QFileDialog>
#include <QFileInfo> #include <QFileInfo>
#include <QFontComboBox>
#include <QFontDatabase> #include <QFontDatabase>
#include <QMenu> #include <QMenu>
#include <QMenuBar> #include <QMenuBar>
#include <QTextCodec>
#include <QTextEdit>
#include <QStatusBar>
#include <QToolBar>
#include <QTextCursor>
#include <QTextDocumentWriter>
#include <QTextList>
#include <QtDebug>
#include <QCloseEvent>
#include <QMessageBox> #include <QMessageBox>
#include <QMimeData> #include <QMimeData>
#include <QMimeDatabase> #include <QMimeDatabase>
#include <QStatusBar>
#include <QTextCursor>
#include <QTextDocumentWriter>
#include <QTextEdit>
#include <QTextList>
#include <QToolBar>
#include <QtDebug>
#if defined(QT_PRINTSUPPORT_LIB) #if defined(QT_PRINTSUPPORT_LIB)
#include <QtPrintSupport/qtprintsupportglobal.h> #include <QtPrintSupport/qtprintsupportglobal.h>
#if QT_CONFIG(printer) #if QT_CONFIG(printer)
@@ -41,27 +39,29 @@
#endif #endif
#endif #endif
#include <LtsUtilsSettings/settings.h> #include <LtsUtilsSettings/settings.h>
#ifdef Q_OS_MAC #ifdef Q_OS_MAC
inline QString rsrcPath(){ QStringLiteral(":/images/mac");} inline QString rsrcPath()
{
QStringLiteral(":/images/mac");
}
#else #else
inline QString rsrcPath(){return QStringLiteral(":/images/win");} inline QString rsrcPath()
{
return QStringLiteral(":/images/win");
}
#endif #endif
namespace LtsWidgets namespace LtsWidgets
{ {
LtsTextEditor2::LtsTextEditor2(QWidget *parent) LtsTextEditor2::LtsTextEditor2(QWidget* parent) : QMainWindow(parent)
: QMainWindow(parent)
{ {
setWindowFlags(Qt::CustomizeWindowHint); setWindowFlags(Qt::CustomizeWindowHint);
setWindowTitle(QCoreApplication::applicationName()); setWindowTitle(QCoreApplication::applicationName());
m_textEdit = new QTextEdit(this); m_textEdit = new QTextEdit(this);
connect(m_textEdit, &QTextEdit::currentCharFormatChanged, connect(m_textEdit, &QTextEdit::currentCharFormatChanged, this, &LtsTextEditor2::currentCharFormatChanged);
this, &LtsTextEditor2::currentCharFormatChanged); connect(m_textEdit, &QTextEdit::cursorPositionChanged, this, &LtsTextEditor2::cursorPositionChanged);
connect(m_textEdit, &QTextEdit::cursorPositionChanged,
this, &LtsTextEditor2::cursorPositionChanged);
setCentralWidget(m_textEdit); setCentralWidget(m_textEdit);
setToolButtonStyle(Qt::ToolButtonFollowStyle); setToolButtonStyle(Qt::ToolButtonFollowStyle);
@@ -82,14 +82,10 @@ LtsTextEditor2::LtsTextEditor2(QWidget *parent)
colorChanged(m_textEdit->textColor()); colorChanged(m_textEdit->textColor());
alignmentChanged(m_textEdit->alignment()); alignmentChanged(m_textEdit->alignment());
connect(m_textEdit->document(), &QTextDocument::modificationChanged, connect(m_textEdit->document(), &QTextDocument::modificationChanged, m_actionSave, &QAction::setEnabled);
m_actionSave, &QAction::setEnabled); connect(m_textEdit->document(), &QTextDocument::modificationChanged, this, &QWidget::setWindowModified);
connect(m_textEdit->document(), &QTextDocument::modificationChanged, connect(m_textEdit->document(), &QTextDocument::undoAvailable, m_actionUndo, &QAction::setEnabled);
this, &QWidget::setWindowModified); connect(m_textEdit->document(), &QTextDocument::redoAvailable, m_actionRedo, &QAction::setEnabled);
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()); setWindowModified(m_textEdit->document()->isModified());
m_actionSave->setEnabled(m_textEdit->document()->isModified()); m_actionSave->setEnabled(m_textEdit->document()->isModified());
@@ -126,19 +122,15 @@ LtsTextEditor2::LtsTextEditor2(QWidget *parent)
m_actionIndentMore->setVisible(false); m_actionIndentMore->setVisible(false);
m_comboStyleAction->setVisible(false); m_comboStyleAction->setVisible(false);
m_actionToggleCheckState->setVisible(false); m_actionToggleCheckState->setVisible(false);
} }
LtsTextEditor2::~LtsTextEditor2() LtsTextEditor2::~LtsTextEditor2() {}
{
}
QTextEdit* LtsTextEditor2::textEdit() QTextEdit* LtsTextEditor2::textEdit()
{ {
return m_textEdit; return m_textEdit;
} }
QColor LtsTextEditor2::backgroundColor() const QColor LtsTextEditor2::backgroundColor() const
{ {
return m_backgroundColor; return m_backgroundColor;
@@ -150,19 +142,19 @@ void LtsTextEditor2::setInitialBackgroundColor(const QColor &bgColor)
m_backgroundColor = bgColor; m_backgroundColor = bgColor;
slotBackgroundColorChanged(m_backgroundColor); slotBackgroundColorChanged(m_backgroundColor);
} }
void LtsTextEditor2::enableBackgroundColor(bool onOff) 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); QPixmap pix(16, 16);
pix.fill(bgColor); pix.fill(bgColor);
m_actionBackgroundColor->setIcon(pix); m_actionBackgroundColor->setIcon(pix);
} }
void LtsTextEditor2::slotBackgroundColor() void LtsTextEditor2::slotBackgroundColor()
{ {
QColor col = QColorDialog::getColor(m_backgroundColor.isValid() ? m_backgroundColor : Qt::white, this); QColor col = QColorDialog::getColor(m_backgroundColor.isValid() ? m_backgroundColor : Qt::white, this);
@@ -174,26 +166,28 @@ void LtsTextEditor2::slotBackgroundColor()
emit backgroundColorChanged(m_backgroundColor); emit backgroundColorChanged(m_backgroundColor);
} }
void LtsTextEditor2::setupFileActions() void LtsTextEditor2::setupFileActions()
{ {
QToolBar* tb = addToolBar(tr("File Actions")); QToolBar* tb = addToolBar(tr("File Actions"));
QMenu* menu = menuBar()->addMenu(tr("&File")); QMenu* menu = menuBar()->addMenu(tr("&File"));
const QIcon newIcon = QIcon::fromTheme(QStringLiteral("document-new"), QIcon(rsrcPath() + QStringLiteral("/filenew.png"))); const QIcon newIcon =
QIcon::fromTheme(QStringLiteral("document-new"), QIcon(rsrcPath() + QStringLiteral("/filenew.png")));
m_actionNew = menu->addAction(newIcon, tr("&New"), this, &LtsTextEditor2::onFileNew); m_actionNew = menu->addAction(newIcon, tr("&New"), this, &LtsTextEditor2::onFileNew);
tb->addAction(m_actionNew); tb->addAction(m_actionNew);
m_actionNew->setPriority(QAction::LowPriority); m_actionNew->setPriority(QAction::LowPriority);
m_actionNew->setShortcut(QKeySequence::New); m_actionNew->setShortcut(QKeySequence::New);
const QIcon openIcon = QIcon::fromTheme(QStringLiteral("document-open"), QIcon(rsrcPath() + QStringLiteral("/fileopen.png"))); 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 = menu->addAction(openIcon, tr("&Open..."), this, &LtsTextEditor2::onFileOpen);
m_actionOpen->setShortcut(QKeySequence::Open); m_actionOpen->setShortcut(QKeySequence::Open);
tb->addAction(m_actionOpen); tb->addAction(m_actionOpen);
menu->addSeparator(); menu->addSeparator();
const QIcon saveIcon = QIcon::fromTheme(QStringLiteral("document-save"), QIcon(rsrcPath()+ QStringLiteral("/filesave.png"))); 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 = menu->addAction(saveIcon, tr("&Save"), this, &LtsTextEditor2::onFileSave);
m_actionSave->setShortcut(QKeySequence::Save); m_actionSave->setShortcut(QKeySequence::Save);
m_actionSave->setEnabled(false); m_actionSave->setEnabled(false);
@@ -204,16 +198,19 @@ void LtsTextEditor2::setupFileActions()
menu->addSeparator(); menu->addSeparator();
#if defined(QT_PRINTSUPPORT_LIB) && QT_CONFIG(printer) #if defined(QT_PRINTSUPPORT_LIB) && QT_CONFIG(printer)
const QIcon printIcon = QIcon::fromTheme(QStringLiteral("document-print"), QIcon(rsrcPath()+ QStringLiteral("/fileprint.png"))); const QIcon printIcon =
QIcon::fromTheme(QStringLiteral("document-print"), QIcon(rsrcPath() + QStringLiteral("/fileprint.png")));
actionPrint = menu->addAction(printIcon, tr("&Print..."), this, &LtsTextEditor2::filePrint); actionPrint = menu->addAction(printIcon, tr("&Print..."), this, &LtsTextEditor2::filePrint);
actionPrint->setPriority(QAction::LowPriority); actionPrint->setPriority(QAction::LowPriority);
actionPrint->setShortcut(QKeySequence::Print); actionPrint->setShortcut(QKeySequence::Print);
tb->addAction(actionPrint); tb->addAction(actionPrint);
const QIcon filePrintIcon = QIcon::fromTheme(QStringLiteral("fileprint"), QIcon(rsrcPath()+ QStringLiteral("/fileprint.png"))); const QIcon filePrintIcon =
QIcon::fromTheme(QStringLiteral("fileprint"), QIcon(rsrcPath() + QStringLiteral("/fileprint.png")));
actionPreview = menu->addAction(filePrintIcon, tr("Print Preview..."), this, &LtsTextEditor2::filePrintPreview); actionPreview = menu->addAction(filePrintIcon, tr("Print Preview..."), this, &LtsTextEditor2::filePrintPreview);
const QIcon exportPdfIcon = QIcon::fromTheme(QStringLiteral("exportpdf"), QIcon(rsrcPath()+ QStringLiteral("/exportpdf.png"))); const QIcon exportPdfIcon =
QIcon::fromTheme(QStringLiteral("exportpdf"), QIcon(rsrcPath() + QStringLiteral("/exportpdf.png")));
actionExport = menu->addAction(exportPdfIcon, tr("&Export PDF..."), this, &LtsTextEditor2::filePrintPdf); actionExport = menu->addAction(exportPdfIcon, tr("&Export PDF..."), this, &LtsTextEditor2::filePrintPdf);
actionExport->setPriority(QAction::LowPriority); actionExport->setPriority(QAction::LowPriority);
actionExport->setShortcut(Qt::CTRL + Qt::Key_D); actionExport->setShortcut(Qt::CTRL + Qt::Key_D);
@@ -324,24 +321,28 @@ void LtsTextEditor2::setupTextActions()
m_actionAlignJustify->setShortcut(Qt::CTRL + Qt::Key_J); m_actionAlignJustify->setShortcut(Qt::CTRL + Qt::Key_J);
m_actionAlignJustify->setCheckable(true); m_actionAlignJustify->setCheckable(true);
m_actionAlignJustify->setPriority(QAction::LowPriority); m_actionAlignJustify->setPriority(QAction::LowPriority);
const QIcon indentMoreIcon = QIcon::fromTheme(QStringLiteral("format-indent-more"), QIcon(rsrcPath()+ QStringLiteral("/format-indent-more.png"))); 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 = menu->addAction(indentMoreIcon, tr("&Indent"), this, &LtsTextEditor2::indent);
m_actionIndentMore->setShortcut(Qt::CTRL + Qt::Key_BracketRight); m_actionIndentMore->setShortcut(Qt::CTRL + Qt::Key_BracketRight);
m_actionIndentMore->setPriority(QAction::LowPriority); m_actionIndentMore->setPriority(QAction::LowPriority);
const QIcon indentLessIcon = QIcon::fromTheme(QStringLiteral("format-indent-less"), QIcon(rsrcPath()+ QStringLiteral("/format-indent-less.png"))); 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 = menu->addAction(indentLessIcon, tr("&Unindent"), this, &LtsTextEditor2::unindent);
m_actionIndentLess->setShortcut(Qt::CTRL + Qt::Key_BracketLeft); m_actionIndentLess->setShortcut(Qt::CTRL + Qt::Key_BracketLeft);
m_actionIndentLess->setPriority(QAction::LowPriority); m_actionIndentLess->setPriority(QAction::LowPriority);
QActionGroup* alignGroup = new QActionGroup(this); QActionGroup* alignGroup = new QActionGroup(this);
connect(alignGroup, &QActionGroup::triggered, this, &LtsTextEditor2::onTextAlign); connect(alignGroup, &QActionGroup::triggered, this, &LtsTextEditor2::onTextAlign);
if (QApplication::isLeftToRight()) { if (QApplication::isLeftToRight())
{
alignGroup->addAction(m_actionAlignLeft); alignGroup->addAction(m_actionAlignLeft);
alignGroup->addAction(m_actionAlignCenter); alignGroup->addAction(m_actionAlignCenter);
alignGroup->addAction(m_actionAlignRight); alignGroup->addAction(m_actionAlignRight);
} else { }
else
{
alignGroup->addAction(m_actionAlignRight); alignGroup->addAction(m_actionAlignRight);
alignGroup->addAction(m_actionAlignCenter); alignGroup->addAction(m_actionAlignCenter);
alignGroup->addAction(m_actionAlignLeft); alignGroup->addAction(m_actionAlignLeft);
@@ -372,18 +373,14 @@ void LtsTextEditor2::setupTextActions()
tb->addAction(m_actionBackgroundColor); tb->addAction(m_actionBackgroundColor);
menu->addSeparator(); menu->addSeparator();
const QIcon checkboxIcon = QIcon::fromTheme(QStringLiteral("status-checkbox-checked"), QIcon(rsrcPath()+ QStringLiteral("/checkbox-checked.png"))); 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 = menu->addAction(checkboxIcon, tr("Chec&ked"), this, &LtsTextEditor2::setChecked);
m_actionToggleCheckState->setShortcut(Qt::CTRL + Qt::Key_K); m_actionToggleCheckState->setShortcut(Qt::CTRL + Qt::Key_K);
m_actionToggleCheckState->setCheckable(true); m_actionToggleCheckState->setCheckable(true);
m_actionToggleCheckState->setPriority(QAction::LowPriority); m_actionToggleCheckState->setPriority(QAction::LowPriority);
tb->addAction(m_actionToggleCheckState); tb->addAction(m_actionToggleCheckState);
m_comboStyle = new QComboBox(tb); m_comboStyle = new QComboBox(tb);
m_comboStyleAction = tb->addWidget(m_comboStyle); m_comboStyleAction = tb->addWidget(m_comboStyle);
m_comboStyle->addItem(QStringLiteral("Standard")); m_comboStyle->addItem(QStringLiteral("Standard"));
@@ -432,13 +429,16 @@ bool LtsTextEditor2::load(const QString &f)
return false; return false;
QByteArray data = file.readAll(); QByteArray data = file.readAll();
QTextCodec *codec = Qt::codecForHtml(data); QString str = QString::fromUtf8(data);
QString str = codec->toUnicode(data); if (Qt::mightBeRichText(str))
if (Qt::mightBeRichText(str)) { {
QUrl baseUrl = (f.front() == QLatin1Char(':') ? QUrl(f) : QUrl::fromLocalFile(f)).adjusted(QUrl::RemoveFilename); QUrl baseUrl =
(f.front() == QLatin1Char(':') ? QUrl(f) : QUrl::fromLocalFile(f)).adjusted(QUrl::RemoveFilename);
m_textEdit->document()->setBaseUrl(baseUrl); m_textEdit->document()->setBaseUrl(baseUrl);
m_textEdit->setHtml(str); m_textEdit->setHtml(str);
} else { }
else
{
#if QT_CONFIG(textmarkdownreader) #if QT_CONFIG(textmarkdownreader)
QMimeDatabase db; QMimeDatabase db;
if (db.mimeTypeForFileNameAndData(f, data).name() == QStringLiteral("text/markdown")) if (db.mimeTypeForFileNameAndData(f, data).name() == QStringLiteral("text/markdown"))
@@ -486,7 +486,8 @@ void LtsTextEditor2::setCurrentFileName(const QString &fileName)
void LtsTextEditor2::onFileNew() void LtsTextEditor2::onFileNew()
{ {
if (maybeSave()) { if (maybeSave())
{
m_textEdit->clear(); m_textEdit->clear();
setCurrentFileName(QString()); setCurrentFileName(QString());
} }
@@ -527,12 +528,14 @@ bool LtsTextEditor2::onFileSave()
QTextDocumentWriter writer(m_fileName); QTextDocumentWriter writer(m_fileName);
bool success = writer.write(m_textEdit->document()); bool success = writer.write(m_textEdit->document());
if (success) { if (success)
{
m_textEdit->document()->setModified(false); m_textEdit->document()->setModified(false);
statusBar()->showMessage(tr("Wrote \"%1\"").arg(QDir::toNativeSeparators(m_fileName))); statusBar()->showMessage(tr("Wrote \"%1\"").arg(QDir::toNativeSeparators(m_fileName)));
} else { }
statusBar()->showMessage(tr("Could not write to file \"%1\"") else
.arg(QDir::toNativeSeparators(m_fileName))); {
statusBar()->showMessage(tr("Could not write to file \"%1\"").arg(QDir::toNativeSeparators(m_fileName)));
} }
return success; return success;
} }
@@ -597,7 +600,6 @@ void LtsTextEditor2::printPreview(QPrinter *printer)
#endif #endif
} }
void LtsTextEditor2::onFilePrintPdf() void LtsTextEditor2::onFilePrintPdf()
{ {
#if defined(QT_PRINTSUPPORT_LIB) && QT_CONFIG(printer) #if defined(QT_PRINTSUPPORT_LIB) && QT_CONFIG(printer)
@@ -616,8 +618,7 @@ void LtsTextEditor2::onFilePrintPdf()
printer.setOutputFormat(QPrinter::PdfFormat); printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName(fileName); printer.setOutputFileName(fileName);
textEdit->document()->print(&printer); textEdit->document()->print(&printer);
statusBar()->showMessage(tr("Exported \"%1\"") statusBar()->showMessage(tr("Exported \"%1\"").arg(QDir::toNativeSeparators(fileName)));
.arg(QDir::toNativeSeparators(fileName)));
#endif #endif
} }
@@ -653,7 +654,8 @@ void LtsTextEditor2::onTextFamily(const QString &f)
void LtsTextEditor2::onTextSize(const QString& p) void LtsTextEditor2::onTextSize(const QString& p)
{ {
qreal pointSize = p.toFloat(); qreal pointSize = p.toFloat();
if (p.toFloat() > 0) { if (p.toFloat() > 0)
{
QTextCharFormat fmt; QTextCharFormat fmt;
fmt.setFontPointSize(pointSize); fmt.setFontPointSize(pointSize);
mergeFormatOnWordOrSelection(fmt); mergeFormatOnWordOrSelection(fmt);
@@ -666,7 +668,8 @@ void LtsTextEditor2::onTextStyle(int styleIndex)
QTextListFormat::Style style = QTextListFormat::ListStyleUndefined; QTextListFormat::Style style = QTextListFormat::ListStyleUndefined;
QTextBlockFormat::MarkerType marker = QTextBlockFormat::MarkerType::NoMarker; QTextBlockFormat::MarkerType marker = QTextBlockFormat::MarkerType::NoMarker;
switch (styleIndex) { switch (styleIndex)
{
case 1: case 1:
style = QTextListFormat::ListDisc; style = QTextListFormat::ListDisc;
break; break;
@@ -713,7 +716,8 @@ void LtsTextEditor2::onTextStyle(int styleIndex)
QTextBlockFormat blockFmt = cursor.blockFormat(); QTextBlockFormat blockFmt = cursor.blockFormat();
if (style == QTextListFormat::ListStyleUndefined) { if (style == QTextListFormat::ListStyleUndefined)
{
blockFmt.setObjectIndex(-1); blockFmt.setObjectIndex(-1);
int headingLevel = styleIndex >= 11 ? styleIndex - 11 + 1 : 0; int headingLevel = styleIndex >= 11 ? styleIndex - 11 + 1 : 0;
blockFmt.setHeadingLevel(headingLevel); blockFmt.setHeadingLevel(headingLevel);
@@ -726,13 +730,18 @@ void LtsTextEditor2::onTextStyle(int styleIndex)
cursor.select(QTextCursor::LineUnderCursor); cursor.select(QTextCursor::LineUnderCursor);
cursor.mergeCharFormat(fmt); cursor.mergeCharFormat(fmt);
m_textEdit->mergeCurrentCharFormat(fmt); m_textEdit->mergeCurrentCharFormat(fmt);
} else { }
else
{
blockFmt.setMarker(marker); blockFmt.setMarker(marker);
cursor.setBlockFormat(blockFmt); cursor.setBlockFormat(blockFmt);
QTextListFormat listFmt; QTextListFormat listFmt;
if (cursor.currentList()) { if (cursor.currentList())
{
listFmt = cursor.currentList()->format(); listFmt = cursor.currentList()->format();
} else { }
else
{
listFmt.setIndent(blockFmt.indent() + 1); listFmt.setIndent(blockFmt.indent() + 1);
blockFmt.setIndent(0); blockFmt.setIndent(0);
cursor.setBlockFormat(blockFmt); cursor.setBlockFormat(blockFmt);
@@ -786,19 +795,24 @@ void LtsTextEditor2::modifyIndentation(int amount)
{ {
QTextCursor cursor = m_textEdit->textCursor(); QTextCursor cursor = m_textEdit->textCursor();
cursor.beginEditBlock(); cursor.beginEditBlock();
if (cursor.currentList()) { if (cursor.currentList())
{
QTextListFormat listFmt = cursor.currentList()->format(); QTextListFormat listFmt = cursor.currentList()->format();
QTextCursor above(cursor); QTextCursor above(cursor);
above.movePosition(QTextCursor::Up); above.movePosition(QTextCursor::Up);
if (above.currentList() && listFmt.indent() + amount == above.currentList()->format().indent()) { if (above.currentList() && listFmt.indent() + amount == above.currentList()->format().indent())
{
above.currentList()->add(cursor.block()); above.currentList()->add(cursor.block());
} else { }
else
{
listFmt.setIndent(listFmt.indent() + amount); listFmt.setIndent(listFmt.indent() + amount);
cursor.createList(listFmt); cursor.createList(listFmt);
} }
} else { }
else
{
QTextBlockFormat blockFmt = cursor.blockFormat(); QTextBlockFormat blockFmt = cursor.blockFormat();
blockFmt.setIndent(blockFmt.indent() + amount); blockFmt.setIndent(blockFmt.indent() + amount);
cursor.setBlockFormat(blockFmt); cursor.setBlockFormat(blockFmt);
@@ -816,8 +830,10 @@ void LtsTextEditor2::cursorPositionChanged()
{ {
alignmentChanged(m_textEdit->alignment()); alignmentChanged(m_textEdit->alignment());
QTextList* list = m_textEdit->textCursor().currentList(); QTextList* list = m_textEdit->textCursor().currentList();
if (list) { if (list)
switch (list->format().style()) { {
switch (list->format().style())
{
case QTextListFormat::ListDisc: case QTextListFormat::ListDisc:
m_comboStyle->setCurrentIndex(1); m_comboStyle->setCurrentIndex(1);
break; break;
@@ -846,7 +862,8 @@ void LtsTextEditor2::cursorPositionChanged()
m_comboStyle->setCurrentIndex(-1); m_comboStyle->setCurrentIndex(-1);
break; break;
} }
switch (m_textEdit->textCursor().block().blockFormat().marker()) { switch (m_textEdit->textCursor().block().blockFormat().marker())
{
case QTextBlockFormat::MarkerType::NoMarker: case QTextBlockFormat::MarkerType::NoMarker:
m_actionToggleCheckState->setChecked(false); m_actionToggleCheckState->setChecked(false);
break; break;
@@ -859,7 +876,9 @@ void LtsTextEditor2::cursorPositionChanged()
m_actionToggleCheckState->setChecked(true); m_actionToggleCheckState->setChecked(true);
break; break;
} }
} else { }
else
{
int headingLevel = m_textEdit->textCursor().blockFormat().headingLevel(); int headingLevel = m_textEdit->textCursor().blockFormat().headingLevel();
m_comboStyle->setCurrentIndex(headingLevel ? headingLevel + 10 : 0); m_comboStyle->setCurrentIndex(headingLevel ? headingLevel + 10 : 0);
} }
@@ -875,7 +894,8 @@ void LtsTextEditor2::clipboardDataChanged()
void LtsTextEditor2::about() void LtsTextEditor2::about()
{ {
QMessageBox::about(this, tr("About"), tr("This example demonstrates Qt's " QMessageBox::about(this, tr("About"),
tr("This example demonstrates Qt's "
"rich text editing facilities in action, providing an example " "rich text editing facilities in action, providing an example "
"document for you to experiment with.")); "document for you to experiment with."));
} }
@@ -917,4 +937,4 @@ void LtsTextEditor2::alignmentChanged(Qt::Alignment a)
m_actionAlignJustify->setChecked(true); m_actionAlignJustify->setChecked(true);
} }
} } // namespace LtsWidgets
+3 -7
View File
@@ -1,22 +1,18 @@
#include "lts_tool_bar.h" #include "lts_tool_bar.h"
using namespace LtsWidgets; using namespace LtsWidgets;
LtsToolBar::LtsToolBar(QWidget *parent) LtsToolBar::LtsToolBar(QWidget* parent) : QToolBar(parent)
: QToolBar(parent)
{ {
setMaximumHeight(1); setMaximumHeight(1);
setMinimumHeight(1); setMinimumHeight(1);
} }
LtsToolBar::~LtsToolBar() LtsToolBar::~LtsToolBar() {}
{
}
void LtsToolBar::enterEvent(QEvent *e) void LtsToolBar::enterEvent(QEnterEvent* e)
{ {
setMaximumHeight(50); setMaximumHeight(50);
setMinimumHeight(50); setMinimumHeight(50);
+5 -8
View File
@@ -1,12 +1,11 @@
#pragma once #pragma once
#include <QObject>
#include <QToolBar>
#include "ltswidgets_export.h" #include "ltswidgets_export.h"
#include <QObject>
#include <QToolBar>
namespace LtsWidgets namespace LtsWidgets
{ {
@@ -19,10 +18,8 @@ public:
~LtsToolBar(); ~LtsToolBar();
protected: protected:
void enterEvent(QEvent *e) override; void enterEvent(QEnterEvent* e) override;
void leaveEvent(QEvent* e) override; void leaveEvent(QEvent* e) override;
}; };
} } // namespace LtsWidgets
+20 -60
View File
@@ -1,26 +1,24 @@
#include "lts_tool_bar_area.h" #include "lts_tool_bar_area.h"
#include <utility>
#include "ui_lts_tool_bar_area.h"
#include "lts_drag_icon.h" #include "lts_drag_icon.h"
#include "ui_lts_tool_bar_area.h"
#include <LtsUtilsSettings/settings.h> #include <LtsUtilsSettings/settings.h>
#include <QDebug>
#include <QDragEnterEvent> #include <QDragEnterEvent>
#include <QDropEvent> #include <QDropEvent>
#include <QLabel> #include <QLabel>
#include <QDebug>
#include <QMenu> #include <QMenu>
#include <QShortcut>
#include <QPointer> #include <QPointer>
#include <QShortcut>
#include <QVariant>
#include <utility>
namespace LtsWidgets namespace LtsWidgets
{ {
void ShortCut::clear() void ShortCut::clear()
{ {
name.clear(); name.clear();
@@ -29,20 +27,13 @@ void ShortCut::clear()
shortcut->disconnect(icon); 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); setAcceptDrops(true);
clearToolBarArea(); clearToolBarArea();
for (int i = Qt::Key_F5; i <= Qt::Key_F12; ++i) for (int i = Qt::Key_F5; i <= Qt::Key_F12; ++i)
{ {
ShortCut sc(this); ShortCut sc(this);
@@ -87,19 +78,16 @@ void LtsToolBarArea::addMenuEntry(LtsDragIcon *entry, LtsDragIcon *after)
} }
} }
int index = m_buttonMap.size(); int index = m_buttonMap.size();
for (int i = 0; i < m_buttonMap.size(); ++i) for (int i = 0; i < m_buttonMap.size(); ++i)
{ {
if (m_buttonMap.at(i) == after || if (m_buttonMap.at(i) == after || m_foreignButtonMap.at(i) == after)
m_foreignButtonMap.at(i) == after)
{ {
index = i + 1; index = i + 1;
break; break;
} }
} }
LtsDragIcon* newAction = entry; LtsDragIcon* newAction = entry;
if (!isInternalMove) if (!isInternalMove)
@@ -115,20 +103,20 @@ void LtsToolBarArea::addMenuEntry(LtsDragIcon *entry, LtsDragIcon *after)
newAction->setIdentifier(entry->identifier()); newAction->setIdentifier(entry->identifier());
connect(newAction, &LtsDragIcon::clicked, entry, &LtsDragIcon::clicked); connect(newAction, &LtsDragIcon::clicked, entry, &LtsDragIcon::clicked);
connect(entry, &LtsDragIcon::destroyed, newAction, connect(entry, &LtsDragIcon::destroyed, newAction, [this, newAction]() {
[this, newAction]() { m_buttonMap.removeAll(newAction); newAction->deleteLater(); }); m_buttonMap.removeAll(newAction);
newAction->deleteLater();
});
newAction->setVisible(!entry->text().isEmpty()); newAction->setVisible(!entry->text().isEmpty());
} }
newAction->setContextMenuPolicy(Qt::CustomContextMenu); newAction->setContextMenuPolicy(Qt::CustomContextMenu);
connect(newAction, &LtsDragIcon::customContextMenuRequested, connect(newAction, &LtsDragIcon::customContextMenuRequested, this, &LtsToolBarArea::showContextMenu);
this, &LtsToolBarArea::showContextMenu);
m_foreignButtonMap.insert(index, foreignDragIcon); m_foreignButtonMap.insert(index, foreignDragIcon);
m_buttonMap.insert(index, newAction); m_buttonMap.insert(index, newAction);
connect(foreignDragIcon, &LtsDragIcon::enabledChanged, newAction, &LtsDragIcon::setEnabled); connect(foreignDragIcon, &LtsDragIcon::enabledChanged, newAction, &LtsDragIcon::setEnabled);
m_ui->layToolbar->insertWidget(index + 1, newAction); m_ui->layToolbar->insertWidget(index + 1, newAction);
saveSettings(); saveSettings();
} }
@@ -165,13 +153,9 @@ QStringList LtsToolBarArea::menuEntries() const
return ret; return ret;
} }
void LtsToolBarArea::dragEnterEvent(QDragEnterEvent* event) void LtsToolBarArea::dragEnterEvent(QDragEnterEvent* event)
{ {
LtsDragIcon *source = LtsDragIcon* source = qobject_cast<LtsDragIcon*>(event->source());
qobject_cast<LtsDragIcon *>(event->source());
if (source) if (source)
{ {
if (!m_foreignButtonMap.contains(source)) if (!m_foreignButtonMap.contains(source))
@@ -207,8 +191,9 @@ QMenu *LtsToolBarArea::functionKeyMenu(QWidget *parent)
for (auto val = m_functionKeys.begin(); val != m_functionKeys.end(); ++val) for (auto val = m_functionKeys.begin(); val != m_functionKeys.end(); ++val)
{ {
ShortCut& shorty = val.value(); ShortCut& shorty = val.value();
act = menu->addAction(QStringLiteral("%1%2").arg(shorty.keyName(), !shorty.name.isEmpty() ? QStringLiteral(" - %1").arg(shorty.name) : QString())); act = menu->addAction(QStringLiteral("%1%2").arg(
act->setData(shorty.shortcut->key()[0]); 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); connect(act, &QAction::triggered, this, &LtsToolBarArea::functionKeyMenuTriggered);
} }
menu->addSeparator(); menu->addSeparator();
@@ -231,13 +216,11 @@ void LtsToolBarArea::functionKeyMenuTriggered()
setFunctionKey(fkey, m_currentIdentifierForContextMenue); setFunctionKey(fkey, m_currentIdentifierForContextMenue);
} }
bool LtsToolBarArea::removeFunctionKey(const QString& action) bool LtsToolBarArea::removeFunctionKey(const QString& action)
{ {
if (action.isEmpty()) if (action.isEmpty())
return true; return true;
for (auto val = m_functionKeys.begin(); val != m_functionKeys.end(); ++val) for (auto val = m_functionKeys.begin(); val != m_functionKeys.end(); ++val)
{ {
ShortCut& itShortcut = val.value(); ShortCut& itShortcut = val.value();
@@ -258,7 +241,6 @@ bool LtsToolBarArea::setFunctionKey(int fkey, const QString &action)
if (fkey < Qt::Key_F5 || fkey > Qt::Key_F12) if (fkey < Qt::Key_F5 || fkey > Qt::Key_F12)
return false; return false;
LtsDragIcon* icon = nullptr; LtsDragIcon* icon = nullptr;
for (LtsDragIcon* ic : std::as_const(m_buttonMap)) for (LtsDragIcon* ic : std::as_const(m_buttonMap))
{ {
@@ -272,15 +254,12 @@ bool LtsToolBarArea::setFunctionKey(int fkey, const QString &action)
if (!icon) if (!icon)
return false; return false;
ShortCut& shorty = m_functionKeys[fkey]; ShortCut& shorty = m_functionKeys[fkey];
for (LtsDragIcon* ic : std::as_const(m_buttonMap)) for (LtsDragIcon* ic : std::as_const(m_buttonMap))
if (ic->identifier() == shorty.identifier) if (ic->identifier() == shorty.identifier)
ic->removeModification(); ic->removeModification();
for (auto val = m_functionKeys.begin(); val != m_functionKeys.end(); ++val) for (auto val = m_functionKeys.begin(); val != m_functionKeys.end(); ++val)
{ {
ShortCut& itShortcut = val.value(); ShortCut& itShortcut = val.value();
@@ -291,7 +270,6 @@ bool LtsToolBarArea::setFunctionKey(int fkey, const QString &action)
} }
} }
shorty.clear(); shorty.clear();
shorty.identifier = icon->identifier(); shorty.identifier = icon->identifier();
shorty.name = icon->text(); shorty.name = icon->text();
@@ -348,13 +326,8 @@ void LtsToolBarArea::showContextMenu(const QPoint &pos)
QMenu* contextMenu = new QMenu(this); QMenu* contextMenu = new QMenu(this);
contextMenu->setAttribute(Qt::WA_DeleteOnClose); contextMenu->setAttribute(Qt::WA_DeleteOnClose);
m_currentIdentifierForContextMenue = icon->identifier(); m_currentIdentifierForContextMenue = icon->identifier();
connect(contextMenu, &QObject::destroyed, this, [this](){ connect(contextMenu, &QObject::destroyed, this, [this]() { m_currentIdentifierForContextMenue.clear(); });
m_currentIdentifierForContextMenue.clear();
});
QAction* delAction = contextMenu->addAction(tr("Remove")); QAction* delAction = contextMenu->addAction(tr("Remove"));
connect(delAction, &QAction::triggered, this, [this, icon]() { connect(delAction, &QAction::triggered, this, [this, icon]() {
@@ -362,24 +335,11 @@ void LtsToolBarArea::showContextMenu(const QPoint &pos)
removeMenuAction(icon); removeMenuAction(icon);
}); });
QMenu* fkeyMenu = functionKeyMenu(contextMenu); QMenu* fkeyMenu = functionKeyMenu(contextMenu);
contextMenu->addMenu(fkeyMenu); contextMenu->addMenu(fkeyMenu);
contextMenu->popup(globalPos); contextMenu->popup(globalPos);
} }
void LtsToolBarArea::saveSettings() {}
void LtsToolBarArea::saveSettings() } // namespace LtsWidgets
{
}
}
@@ -13,8 +13,10 @@ ADD_SUBDIRECTORY(Battery)
ADD_SUBDIRECTORY(Buildings) ADD_SUBDIRECTORY(Buildings)
ADD_SUBDIRECTORY(BuildingViewer) # uses ZW connections (uses sql, ace, ..) ADD_SUBDIRECTORY(BuildingViewer) # uses ZW connections (uses sql, ace, ..)
ADD_SUBDIRECTORY(CentralEffectSimulation) ADD_SUBDIRECTORY(CentralEffectSimulation)
IF(BUILD_CODIFICATION)
ADD_SUBDIRECTORY(CodificationManagement) ADD_SUBDIRECTORY(CodificationManagement)
ADD_SUBDIRECTORY(CodificationManagement/Test) ADD_SUBDIRECTORY(CodificationManagement/Test)
ENDIF()
ADD_SUBDIRECTORY(CollateralDamageSimulation) ADD_SUBDIRECTORY(CollateralDamageSimulation)
ADD_SUBDIRECTORY(EffectManagement) ADD_SUBDIRECTORY(EffectManagement)
ADD_SUBDIRECTORY(EffectShowClient) ADD_SUBDIRECTORY(EffectShowClient)
@@ -22,7 +24,9 @@ ADD_SUBDIRECTORY(EffectShowManagement)
ADD_SUBDIRECTORY(Evaluations) ADD_SUBDIRECTORY(Evaluations)
ADD_SUBDIRECTORY(ExerciseManagement) ADD_SUBDIRECTORY(ExerciseManagement)
ADD_SUBDIRECTORY(FileManagement) ADD_SUBDIRECTORY(FileManagement)
IF(BUILD_FILTERMANAGEMENT)
ADD_SUBDIRECTORY(FilterManagement) ADD_SUBDIRECTORY(FilterManagement)
ENDIF()
ADD_SUBDIRECTORY(FreeSpace) ADD_SUBDIRECTORY(FreeSpace)
ADD_SUBDIRECTORY(GuezIedManagement) ADD_SUBDIRECTORY(GuezIedManagement)
ADD_SUBDIRECTORY(GuezNasat) ADD_SUBDIRECTORY(GuezNasat)
@@ -5,7 +5,12 @@
# Created by Hannes Fritsche, ESZS, 2024-08-05 # 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 SET(cds_gui_SRCS
cds_building_model.cpp cds_building_model.cpp
@@ -37,11 +37,18 @@ ADD_INTERFACE_LIBRARY(
# #
# need top be shared due to signals/slots # need top be shared due to signals/slots
NGL_ADD_LIBRARY2(WS IsmDataPluginInterface SHARED ism_data_plugin_interface.h) NGL_ADD_LIBRARY2(WS IsmDataPluginInterface SHARED ism_data_plugin_interface.h)
IF(BUILD_RTI)
NGL_TARGET_LINK_LIBRARIES(IsmDataPluginInterface NGL_TARGET_LINK_LIBRARIES(IsmDataPluginInterface
Qt6::Core Qt6::Core
svcIsmCommon svcIsmCommon
DataPluginInterface DataPluginInterface
) )
ELSE()
NGL_TARGET_LINK_LIBRARIES(IsmDataPluginInterface
Qt6::Core
DataPluginInterface
)
ENDIF(BUILD_RTI)
NGL_INSTALL_TARGET(IsmDataPluginInterface) NGL_INSTALL_TARGET(IsmDataPluginInterface)
# #
@@ -7,8 +7,8 @@
FIND_PACKAGE(KDReports) FIND_PACKAGE(KDReports)
FIND_PACKAGE(KDChart) FIND_PACKAGE(KDChart)
IF (NOT KDReports_FOUND OR NOT KDChart_FOUND) IF ((NOT KDReports_FOUND OR NOT KDChart_FOUND) OR NOT BUILD_CODIFICATION)
MESSAGE(WARNING "KDReports or KDChart not found; skipping ReportViewer") MESSAGE(WARNING "KDReports, KDChart not found or BUILD_CODIFICATION disabled; skipping ReportViewer")
RETURN() RETURN()
ENDIF() ENDIF()
+115 -99
View File
@@ -1,21 +1,17 @@
#pragma once #pragma once
#include "sv_export.h"
#include <QByteArray> #include <QByteArray>
#include <WirelessLocationSystem/sfmconverter_export.h>
namespace WirelessLocationSystem namespace WirelessLocationSystem
{ {
class SfmMessage class SfmMessage
{ {
public: public:
enum class MsgId enum class MsgId {
{
TacticalState = 37, TacticalState = 37,
SfmRestartNotification = 76, SfmRestartNotification = 76,
GpsControl = 79, GpsControl = 79,
@@ -28,74 +24,61 @@ public:
}; };
protected: protected:
explicit SfmMessage(MsgId id) explicit SfmMessage(MsgId id) : m_id(id) {}
: m_id(id)
{}
public: public:
virtual ~SfmMessage() = default; virtual ~SfmMessage() = default;
MsgId getId() const { return m_id; } MsgId getId() const
{
return m_id;
}
private: private:
MsgId m_id; MsgId m_id;
}; };
class SfmMessage_tx : public SfmMessage class SfmMessage_tx : public SfmMessage
{ {
public: public:
using SfmMessage::SfmMessage; using SfmMessage::SfmMessage;
virtual QByteArray getPayload() const = 0; virtual QByteArray getPayload() const = 0;
}; };
class SfmMessage_rx : public SfmMessage class SfmMessage_rx : public SfmMessage
{ {
public: public:
using SfmMessage::SfmMessage; using SfmMessage::SfmMessage;
virtual bool setPayload(const QByteArray& payload) = 0; virtual bool setPayload(const QByteArray& payload) = 0;
}; };
class SfmMsgGpsControl_tx final : public SfmMessage_tx class SfmMsgGpsControl_tx final : public SfmMessage_tx
{ {
public: public:
explicit SfmMsgGpsControl_tx(bool gpsOn = false) explicit SfmMsgGpsControl_tx(bool gpsOn = false) : SfmMessage_tx(SfmMessage::MsgId::GpsControl), m_gpsOn(gpsOn) {}
: SfmMessage_tx(SfmMessage::MsgId::GpsControl)
, m_gpsOn(gpsOn)
{}
QByteArray getPayload() const override; QByteArray getPayload() const override;
void setGpsOn(bool bOn) { m_gpsOn = bOn; } void setGpsOn(bool bOn)
bool isGpsOn() const { return m_gpsOn; } {
m_gpsOn = bOn;
}
bool isGpsOn() const
{
return m_gpsOn;
}
private: private:
bool m_gpsOn; bool m_gpsOn;
}; };
class SfmMsgRequestGpsControl_rx final : public SfmMessage_rx class SfmMsgRequestGpsControl_rx final : public SfmMessage_rx
{ {
public: public:
SfmMsgRequestGpsControl_rx() SfmMsgRequestGpsControl_rx() : SfmMessage_rx(SfmMessage::MsgId::RequestGpsControl) {}
: SfmMessage_rx(SfmMessage::MsgId::RequestGpsControl)
{}
bool setPayload(const QByteArray& payload) override bool setPayload(const QByteArray& payload) override
{ {
@@ -103,16 +86,10 @@ public:
} }
}; };
class SfmMsgRequestEquipmentId_tx final : public SfmMessage_tx class SfmMsgRequestEquipmentId_tx final : public SfmMessage_tx
{ {
public: public:
SfmMsgRequestEquipmentId_tx() SfmMsgRequestEquipmentId_tx() : SfmMessage_tx(SfmMessage::MsgId::RequestEquipmentId) {}
: SfmMessage_tx(SfmMessage::MsgId::RequestEquipmentId)
{}
QByteArray getPayload() const override QByteArray getPayload() const override
{ {
@@ -120,16 +97,12 @@ public:
} }
}; };
class SFMCONVERTER_EXPORT SfmMsgEquipmentId final : public SfmMessage_rx, public SfmMessage_tx class SFMCONVERTER_EXPORT SfmMsgEquipmentId final : public SfmMessage_rx, public SfmMessage_tx
{ {
public: public:
SfmMsgEquipmentId() SfmMsgEquipmentId() : SfmMessage_rx(SfmMessage::MsgId::EquipmentId), SfmMessage_tx(SfmMessage::MsgId::EquipmentId)
: SfmMessage_rx(SfmMessage::MsgId::EquipmentId) {
, SfmMessage_tx(SfmMessage::MsgId::EquipmentId) }
{}
bool setPayload(const QByteArray&) override; bool setPayload(const QByteArray&) override;
QByteArray getPayload() const override; QByteArray getPayload() const override;
@@ -140,65 +113,76 @@ public:
{ {
return m_equipmentNumber; return m_equipmentNumber;
} }
void setEquipmentNumber(quint16 equipmentNumber) { m_equipmentNumber = equipmentNumber; }
void setEquipmentNumber(quint16 equipmentNumber)
{
m_equipmentNumber = equipmentNumber;
}
private: private:
unsigned short m_equipmentNumber = 0; unsigned short m_equipmentNumber = 0;
}; };
class SfmMsgSfmRestart_rx final : public SfmMessage_rx class SfmMsgSfmRestart_rx final : public SfmMessage_rx
{ {
public: public:
SfmMsgSfmRestart_rx() SfmMsgSfmRestart_rx() : SfmMessage_rx(SfmMessage::MsgId::SfmRestartNotification) {}
: SfmMessage_rx(SfmMessage::MsgId::SfmRestartNotification)
{}
bool setPayload(const QByteArray& payload) override bool setPayload(const QByteArray& payload) override
{ {
return (payload.size() == 0); return (payload.size() == 0);
} }
}; };
class SfmMsgTacticalState_rx final : public SfmMessage_rx class SfmMsgTacticalState_rx final : public SfmMessage_rx
{ {
public: public:
SfmMsgTacticalState_rx() SfmMsgTacticalState_rx() : SfmMessage_rx(SfmMessage::MsgId::TacticalState) {}
: 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: private:
unsigned char m_tacticalState = 0; unsigned char m_tacticalState = 0;
}; };
class SfmMsgTetra_rx final : public SfmMessage_rx class SfmMsgTetra_rx final : public SfmMessage_rx
{ {
public: public:
SfmMsgTetra_rx() SfmMsgTetra_rx() : SfmMessage_rx(SfmMessage::MsgId::TetraMessage) {}
: 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; } uint8_t sendCounter() const
bool isFragmented() const { return fragmentCount() > 1; } {
uint8_t fragmentNumber() const { return m_fragmentByte & 0x0f; } return m_sendCounter;
uint8_t fragmentCount() const { return (m_fragmentByte & 0xf0) >> 4;} }
const QByteArray &payload() const { return m_payload; } bool isFragmented() const
{
return fragmentCount() > 1;
}
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: private:
QByteArray m_payload; QByteArray m_payload;
@@ -224,27 +208,50 @@ public:
Q_ASSERT(fragmentNumber >= 0 && fragmentNumber <= fragmentCount); Q_ASSERT(fragmentNumber >= 0 && fragmentNumber <= fragmentCount);
return ((fragmentCount & 0x0f) << 4) | (fragmentNumber & 0x0f); return ((fragmentCount & 0x0f) << 4) | (fragmentNumber & 0x0f);
} }
QByteArray getPayload() const override { return m_data; }
QByteArray getPayload() const override
{
return m_data;
}
private: private:
QByteArray m_data; QByteArray m_data;
}; };
class Acknowledge_rx final : public SfmMessage_rx class Acknowledge_rx final : public SfmMessage_rx
{ {
public: public:
Acknowledge_rx() Acknowledge_rx() : SfmMessage_rx(SfmMessage::MsgId::Acknowledge) {}
: SfmMessage_rx(SfmMessage::MsgId::Acknowledge)
{}
static constexpr int s_payloadSize = 2; static constexpr int s_payloadSize = 2;
bool setPayload(const QByteArray& p_data) override; bool setPayload(const QByteArray& p_data) override;
uint8_t recvCounter() const { return m_recvCounter; }
bool isOk() const { return m_ackState == 0; } uint8_t recvCounter() const
bool isCrcError() const { return (m_ackState & 0x20) == 0x20; } {
bool isFragmentError() const { return (m_ackState & 0x10) == 0x10; } return m_recvCounter;
uint8_t missingFragment() const { return (m_ackState & 0x0f)!= 0; } }
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: private:
uint8_t m_recvCounter = 0; uint8_t m_recvCounter = 0;
uint8_t m_ackState = 0; uint8_t m_ackState = 0;
@@ -253,37 +260,46 @@ private:
class Acknowledge_tx final : public SfmMessage_tx class Acknowledge_tx final : public SfmMessage_tx
{ {
public: public:
explicit Acknowledge_tx() explicit Acknowledge_tx() : SfmMessage_tx(SfmMessage::MsgId::Acknowledge) {}
: SfmMessage_tx(SfmMessage::MsgId::Acknowledge)
{}
QByteArray getPayload() const override; QByteArray getPayload() const override;
void setRecvCounter(uint8_t recvCounter) { m_recvCounter = recvCounter; } void setRecvCounter(uint8_t recvCounter)
void setCrcError() { m_ackState |= 0x20; } {
void setFragmentError(uint8_t missingFrag) { m_ackState |= (0x10 | (0x0f & missingFrag)); } m_recvCounter = recvCounter;
}
void setCrcError()
{
m_ackState |= 0x20;
}
void setFragmentError(uint8_t missingFrag)
{
m_ackState |= (0x10 | (0x0f & missingFrag));
}
private: private:
uint8_t m_recvCounter = 0; uint8_t m_recvCounter = 0;
uint8_t m_ackState = 0; uint8_t m_ackState = 0;
}; };
class SfmMsgLicenseState_rx final : public SfmMessage_rx class SfmMsgLicenseState_rx final : public SfmMessage_rx
{ {
public: public:
SfmMsgLicenseState_rx() SfmMsgLicenseState_rx() : SfmMessage_rx(SfmMessage::MsgId::LicenseState) {}
: 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 setPayload(const QByteArray& p_data) override;
bool isLicensed() const { return m_isLicensed; }
bool isLicensed() const
{
return m_isLicensed;
}
private: private:
bool m_isLicensed = false; bool m_isLicensed = false;
}; };
} } // namespace WirelessLocationSystem
@@ -18,7 +18,9 @@ ADD_SUBDIRECTORY(Evaluations)
ADD_SUBDIRECTORY(ExerciseManagement) ADD_SUBDIRECTORY(ExerciseManagement)
ADD_SUBDIRECTORY(ExerciseEventManagement) ADD_SUBDIRECTORY(ExerciseEventManagement)
ADD_SUBDIRECTORY(FileManagement) ADD_SUBDIRECTORY(FileManagement)
IF(BUILD_FILTERMANAGEMENT)
ADD_SUBDIRECTORY(FilterManagement) ADD_SUBDIRECTORY(FilterManagement)
ENDIF()
ADD_SUBDIRECTORY(GuezIedManagement) ADD_SUBDIRECTORY(GuezIedManagement)
ADD_SUBDIRECTORY(GuezMinelayerProcessing) ADD_SUBDIRECTORY(GuezMinelayerProcessing)
IF(BUILD_RTI) IF(BUILD_RTI)
File diff suppressed because it is too large. Load diff
@@ -595,6 +595,10 @@ protected:
static void setDestISSI_Internal(QByteArray &data, const uint32_t issi); static void setDestISSI_Internal(QByteArray &data, const uint32_t issi);
private: private:
/**
* The logger object
*/
NGL::INGLLogger &m_logger;
}; };
} }
File diff suppressed because it is too large. Load diff
@@ -19,7 +19,7 @@ SET(NGLLogger_HDRS
ADD_DEFINITIONS(-DBUILDING_NGLLOGGER) ADD_DEFINITIONS(-DBUILDING_NGLLOGGER)
NGL_ADD_LIBRARY2(ALL NGLLogger SHARED ${NGLLogger_SRCS} ${NGLLogger_HDRS}) NGL_ADD_LIBRARY2(ALL NGLLogger SHARED ${NGLLogger_SRCS} ${NGLLogger_HDRS})
NGL_TARGET_INCLUDE_DIRECTORIES(NGLLogger NGL_TARGET_INCLUDE_DIRECTORIES(NGLLogger
INTERFACE PUBLIC
${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/../ ${CMAKE_CURRENT_SOURCE_DIR}/../
${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_BINARY_DIR}
+63 -78
View File
@@ -7,22 +7,21 @@
#pragma once #pragma once
#include <string> #include <QList>
#include <sstream>
#include <QString>
#include <QPointF> #include <QPointF>
#include <QSize>
#include <QRect> #include <QRect>
#include <QRectF> #include <QRectF>
#include <QList> #include <QSize>
#include "ngllogger_export.h" #include <QString>
#include <ngllogger_export.h>
#include <sstream>
#include <string>
namespace NGL namespace NGL
{ {
class INGLLogger; class INGLLogger;
// keep in sync with log4qt/level.h // keep in sync with log4qt/level.h
enum class LogLevel enum class LogLevel {
{
Undefined = 0, Undefined = 0,
Trace = 64, Trace = 64,
Debug = 96, Debug = 96,
@@ -35,17 +34,15 @@ enum class LogLevel
class LogStreamHelper class LogStreamHelper
{ {
public: public:
inline LogStreamHelper(INGLLogger &logger, LogLevel level, const char *const file, int line, const char *const function) inline LogStreamHelper(INGLLogger& logger, LogLevel level, const char* const file, int line,
: m_logger(logger) const char* const function)
, m_level(level) : m_logger(logger), m_level(level), m_line(line), m_file(file), m_func(function)
, m_line(line) {
, m_file(file) }
, m_func(function)
{}
inline ~LogStreamHelper(); // after INGLLogger class definition inline ~LogStreamHelper(); // after INGLLogger class definition
template<typename T> template <typename T> inline LogStreamHelper& operator<<(const T& val);
inline LogStreamHelper &operator<<(const T &val);
private: private:
std::ostringstream m_buffer; std::ostringstream m_buffer;
@@ -79,7 +76,6 @@ public:
virtual INGLLogger& getNGLLogger(const char* fullqualifiedname) = 0; virtual INGLLogger& getNGLLogger(const char* fullqualifiedname) = 0;
virtual INGLLogger& getNGLLogger(const std::string& fullqualifiedname) = 0; virtual INGLLogger& getNGLLogger(const std::string& fullqualifiedname) = 0;
// True if this level is enabled. // True if this level is enabled.
virtual bool isTraceEnabled() const = 0; virtual bool isTraceEnabled() const = 0;
virtual bool isDebugEnabled() const = 0; virtual bool isDebugEnabled() const = 0;
@@ -91,20 +87,27 @@ public:
// Submit a LOG message. // Submit a LOG message.
// Use __FILE__ and __NAME__ macros. // 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; 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. // Submit an TRACE message.
virtual void logTrace(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0; virtual void logTrace(const INGLLogger::String& message, const char* file = nullptr, int line = -1,
const char* function = nullptr) = 0;
// Submit an DEBUG message. // Submit an DEBUG message.
virtual void logDebug(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0; virtual void logDebug(const INGLLogger::String& message, const char* file = nullptr, int line = -1,
const char* function = nullptr) = 0;
// Submit an INFO message. // Submit an INFO message.
virtual void logInfo(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0; virtual void logInfo(const INGLLogger::String& message, const char* file = nullptr, int line = -1,
const char* function = nullptr) = 0;
// Submit a WARNING message. // Submit a WARNING message.
virtual void logWarning(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0; virtual void logWarning(const INGLLogger::String& message, const char* file = nullptr, int line = -1,
const char* function = nullptr) = 0;
// Submit an ERROR message. // Submit an ERROR message.
virtual void logError(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0; virtual void logError(const INGLLogger::String& message, const char* file = nullptr, int line = -1,
const char* function = nullptr) = 0;
// Submit a FATAL message. // Submit a FATAL message.
virtual void logFatal(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0; 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 // Writes a startup message into the logfile
virtual void logStartup(const char* file, int line, const char* function = nullptr) = 0; virtual void logStartup(const char* file, int line, const char* function = nullptr) = 0;
@@ -126,8 +129,7 @@ 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<typename T> template <typename T> inline LogStreamHelper& LogStreamHelper::operator<<(const T& val)
inline LogStreamHelper &LogStreamHelper::operator<<(const T &val)
{ {
m_buffer << val; m_buffer << val;
if (!m_logger.noSpace()) if (!m_logger.noSpace())
@@ -135,7 +137,6 @@ inline LogStreamHelper &LogStreamHelper::operator<<(const T &val)
return *this; 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)
@@ -147,67 +148,50 @@ inline std::ostream &operator<<(std::ostream &stream, const QByteArray &str)
// //
// operator to ease logging (at least via NglLogging) // operator to ease logging (at least via NglLogging)
// //
inline std::ostream &operator<<(std::ostream &stream, inline std::ostream& operator<<(std::ostream& stream, const QPointF& value)
const QPointF &value)
{ {
stream << "QPointF(" << QString::number(value.x(), 'f', 6).toStdString() << "#" << QString::number(value.y(), 'f', 6).toStdString() << ")"; stream << "QPointF(" << QString::number(value.x(), 'f', 6).toStdString() << "#"
<< QString::number(value.y(), 'f', 6).toStdString() << ")";
return stream; return stream;
} }
//---------------------------------------------------------------------------- //----------------------------------------------------------------------------
inline std::ostream &operator<< (std::ostream &stream, inline std::ostream& operator<<(std::ostream& stream, const QPoint& value)
const QPoint &value)
{ {
stream << "QPoint(" << value.x() << "#" << value.y() << ")"; stream << "QPoint(" << value.x() << "#" << value.y() << ")";
return stream; return stream;
} }
inline std::ostream &operator<< (std::ostream &stream, inline std::ostream& operator<<(std::ostream& stream, const QSize& value)
const QSize &value)
{ {
stream << "QSize(w=" << value.width() << ";h=" << value.height() << ")"; stream << "QSize(w=" << value.width() << ";h=" << value.height() << ")";
return stream; return stream;
} }
inline std::ostream &operator<< (std::ostream &stream,
const QSizeF &value) inline std::ostream& operator<<(std::ostream& stream, const QSizeF& value)
{ {
stream << "QSize(w=" stream << "QSize(w=" << QString::number(value.width(), 'f', 6).toStdString()
<< QString::number(value.width(), 'f', 6).toStdString() << ";h=" << ";h=" << QString::number(value.height(), 'f', 6).toStdString() << ")";
<< QString::number(value.height(), 'f', 6).toStdString()
<< ")";
return stream; return stream;
} }
inline std::ostream& operator<<(std::ostream& stream, const QRect& value)
inline std::ostream &operator<< (std::ostream &stream,
const QRect &value)
{ {
stream << "QRect(center=" << value.center() stream << "QRect(center=" << value.center() << " w=" << value.width() << ";h=" << value.height()
<< " w=" << value.width() << " bottomLeft=" << value.bottomLeft() << " topRight=" << value.topRight() << ")";
<< ";h=" << value.height()
<< " bottomLeft=" << value.bottomLeft()
<< " topRight=" << value.topRight()
<< ")";
return stream; return stream;
} }
inline std::ostream &operator<< (std::ostream &stream, inline std::ostream& operator<<(std::ostream& stream, const QRectF& value)
const QRectF &value)
{ {
stream << "QRectF(center=" << value.center() stream << "QRectF(center=" << value.center() << " w=" << QString::number(value.width(), 'f', 3).toStdString()
<< " w=" << QString::number(value.width(), 'f', 3).toStdString() << ";h=" << QString::number(value.height(), 'f', 3).toStdString() << " bottomLeft=" << value.bottomLeft()
<< ";h=" << QString::number(value.height(), 'f', 3).toStdString() << " topRight=" << value.topRight() << ")";
<< " bottomLeft=" << value.bottomLeft()
<< " topRight=" << value.topRight()
<< ")";
return stream; return stream;
} }
inline std::ostream& operator<<(std::ostream& stream, const QList<int>& value)
inline std::ostream &operator<< (std::ostream &stream,
const QList<int> &value)
{ {
stream << "QList<int>(" << value.size() << "): "; stream << "QList<int>(" << value.size() << "): ";
for (int i : value) for (int i : value)
@@ -215,9 +199,7 @@ inline std::ostream &operator<< (std::ostream &stream,
return stream; return stream;
} }
inline std::ostream& operator<<(std::ostream& stream, const QList<QPointF>& value)
inline std::ostream &operator<< (std::ostream &stream,
const QList<QPointF> &value)
{ {
stream << "QList<QPointF>(" << value.size() << "): "; stream << "QList<QPointF>(" << value.size() << "): ";
for (const QPointF& item : value) for (const QPointF& item : value)
@@ -225,7 +207,6 @@ inline std::ostream &operator<< (std::ostream &stream,
return stream; return stream;
} }
inline std::ostream& operator<<(std::ostream& stream, const QString& str) inline std::ostream& operator<<(std::ostream& stream, const QString& str)
{ {
return stream << str.toUtf8(); return stream << str.toUtf8();
@@ -236,13 +217,10 @@ namespace NGL
namespace NGLLoggerHelper namespace NGLLoggerHelper
{ {
NGLLOGGER_EXPORT void hexDumpHelper(NGL::INGLLogger &logger, NGLLOGGER_EXPORT void hexDumpHelper(NGL::INGLLogger& logger, NGL::LogLevel level, const void* a_data,
NGL::LogLevel level,
const void *a_data,
const unsigned int a_size); const unsigned int a_size);
inline void hexDumpHelper(NGL::INGLLogger &logger,
NGL::LogLevel level, inline void hexDumpHelper(NGL::INGLLogger& logger, NGL::LogLevel level, const QByteArray& data)
const QByteArray &data)
{ {
return hexDumpHelper(logger, level, data.data(), data.size()); return hexDumpHelper(logger, level, data.data(), data.size());
} }
@@ -260,8 +238,7 @@ NGLLOGGER_EXPORT std::string getMemoryData();
#define LOGFUNCTION Q_FUNC_INFO #define LOGFUNCTION Q_FUNC_INFO
// log this output every time, no matter what log level is enabled // log this output every time, no matter what log level is enabled
#define NOTICE_LOG(logger) \ #define NOTICE_LOG(logger) NGL::LogStreamHelper(logger, NGL::LogLevel::Info, __FILE__, __LINE__, Q_FUNC_INFO)
NGL::LogStreamHelper(logger, NGL::LogLevel::Info, __FILE__,__LINE__, Q_FUNC_INFO)
#ifdef LTS_DEBUG #ifdef LTS_DEBUG
#define TRACE_LOG(logger) \ #define TRACE_LOG(logger) \
@@ -293,8 +270,14 @@ NGLLOGGER_EXPORT std::string getMemoryData();
for (bool log_level_enabled = (logger).isFatalEnabled(); log_level_enabled; log_level_enabled = false) \ 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) NGL::LogStreamHelper(logger, NGL::LogLevel::Fatal, __FILE__, __LINE__, Q_FUNC_INFO)
#define STARTUP_LOG(logger) { (logger).logStartup(__FILE__, __LINE__, Q_FUNC_INFO); } #define STARTUP_LOG(logger) \
#define SHUTDOWN_LOG(logger) { (logger).logShutdown(__FILE__, __LINE__, Q_FUNC_INFO); } { \
(logger).logStartup(__FILE__, __LINE__, Q_FUNC_INFO); \
}
#define SHUTDOWN_LOG(logger) \
{ \
(logger).logShutdown(__FILE__, __LINE__, Q_FUNC_INFO); \
}
//============================================================================== //==============================================================================
@@ -304,7 +287,9 @@ NGLLOGGER_EXPORT std::string getMemoryData();
// MEMORY_LOG() << " after something nasty"; // MEMORY_LOG() << " after something nasty";
#define MEMORY_LOG() \ #define MEMORY_LOG() \
for (bool log_level_enabled = (NGL::getMemoryLogger()).isInfoEnabled(); log_level_enabled; log_level_enabled = false) \ for (bool log_level_enabled = (NGL::getMemoryLogger()).isInfoEnabled(); log_level_enabled; \
NGL::LogStreamHelper(NGL::getMemoryLogger(), NGL::LogLevel::Info, __FILE__,__LINE__, Q_FUNC_INFO) << NGL::getMemoryData() log_level_enabled = false) \
NGL::LogStreamHelper(NGL::getMemoryLogger(), NGL::LogLevel::Info, __FILE__, __LINE__, Q_FUNC_INFO) \
<< NGL::getMemoryData()
//============================================================================== //==============================================================================
+6 -20
View File
@@ -1,11 +1,10 @@
#ifndef NGLLOGGERBOOTSTRAP_H #ifndef NGLLOGGERBOOTSTRAP_H
#define NGLLOGGERBOOTSTRAP_H #define NGLLOGGERBOOTSTRAP_H
#include <NGLLogger/INGLLogger.h> #include <NGLLogger/INGLLogger.h>
#include "ngllogger_export.h" #include <ngllogger_export.h>
namespace NGL namespace NGL
{ {
@@ -28,32 +27,19 @@ class NotCreatedError final : public std::exception
} }
}; };
NGLLOGGER_EXPORT INGLLogger& getNGLRootLogger(); 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,
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()) const QString& logOutputName = QString())
{ {
return createNGLRootLogger(QString::fromUtf8(configfilename), ignorealreadycreated, logOutputName); return createNGLRootLogger(QString::fromUtf8(configfilename), ignorealreadycreated, logOutputName);
} }
} } // namespace NGLLoggerBootstrap
}
} // namespace NGL
#endif #endif
+9 -28
View File
@@ -1,29 +1,17 @@
#include "nglcomp_bzip2iodevice.h" #include "nglcomp_bzip2iodevice.h"
#include <QIODevice> #include <QIODevice>
#include <QString> #include <QString>
#include <bzlib.h> #include <bzlib.h>
class BZip2IODevice::Private class BZip2IODevice::Private
{ {
public: public:
Private(BZip2IODevice* parent_, QIODevice* dev, int bs) Private(BZip2IODevice* parent_, QIODevice* dev, int bs)
: parent(parent_) : parent(parent_), device(dev), iCurPos(0), iMaxBufSize(1024 * 1024), blocksize(bs), initialized(false),
, device(dev) decomressStreamEnd(false)
, iCurPos(0)
, iMaxBufSize(1024 * 1024)
, blocksize(bs)
, initialized(false)
, decomressStreamEnd(false)
{ {
buffer.resize(iMaxBufSize); buffer.resize(iMaxBufSize);
} }
@@ -87,7 +75,8 @@ qint64 BZip2IODevice::Private::doCompress(const char *in, qint64 iMaxLen)
do do
{ {
if (aborted) return 0; if (aborted)
return 0;
stream.next_out = buffer.data(); stream.next_out = buffer.data();
stream.avail_out = buffer.size(); stream.avail_out = buffer.size();
@@ -109,8 +98,7 @@ qint64 BZip2IODevice::Private::doCompress(const char *in, qint64 iMaxLen)
return -1; return -1;
} }
} }
} } while (stream.avail_in != 0);
while (stream.avail_in != 0);
return stream.next_in - in; return stream.next_in - in;
} }
@@ -140,8 +128,7 @@ bool BZip2IODevice::Private::finishCompress()
parent->setErrorString(QLatin1String("Error writing to QIODevice")); parent->setErrorString(QLatin1String("Error writing to QIODevice"));
return false; return false;
} }
} } while (ret != BZ_STREAM_END);
while (ret != BZ_STREAM_END);
BZ2_bzCompressEnd(&stream); BZ2_bzCompressEnd(&stream);
initialized = false; initialized = false;
@@ -206,8 +193,7 @@ qint64 BZip2IODevice::Private::doDecompress(char *out, qint64 iMaxLen)
finishDecompress(); finishDecompress();
return -1; return -1;
} }
} } while (stream.avail_out != 0 && ret != BZ_STREAM_END);
while (stream.avail_out != 0 && ret != BZ_STREAM_END);
decomressStreamEnd = (ret == BZ_STREAM_END); decomressStreamEnd = (ret == BZ_STREAM_END);
return stream.next_out - out; return stream.next_out - out;
} }
@@ -248,12 +234,7 @@ QString BZip2IODevice::Private::bzipError2String(int errCode)
return QString::number(errCode); 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() BZip2IODevice::~BZip2IODevice()
{ {
@@ -283,7 +264,7 @@ bool BZip2IODevice::open(OpenMode mode)
{ {
if ((mode & QIODevice::ReadWrite) == 0) if ((mode & QIODevice::ReadWrite) == 0)
{ {
setErrorString(QStringLiteral("Unsupported OpenMode %1").arg(mode)); setErrorString(QStringLiteral("Unsupported OpenMode %1").arg(static_cast<int>(mode)));
return false; return false;
} }
if ((mode & QIODevice::ReadWrite) == QIODevice::ReadWrite) if ((mode & QIODevice::ReadWrite) == QIODevice::ReadWrite)
+42 -82
View File
@@ -1,63 +1,32 @@
#include "nglcomp_compress.h" #include "nglcomp_compress.h"
#include "nglcomp_bzip2iodevice.h" #include "nglcomp_bzip2iodevice.h"
#include "nglcomp_tarfilter.h" #include "nglcomp_tarfilter.h"
#include <NGLLogger/NGLLoggerBootstrap.h> #include <NGLLogger/NGLLoggerBootstrap.h>
#include <QBuffer> #include <QBuffer>
#include <QtConcurrent>
#include <QCoreApplication> #include <QCoreApplication>
#include <QDebug>
#include <QDir> #include <QDir>
#include <QFileInfo> #include <QFileInfo>
#include <QFutureWatcher> #include <QFutureWatcher>
#include <QIODevice> #include <QIODevice>
#include <QStringList> #include <QStringList>
#include <QtConcurrent>
#include <memory> #include <memory>
#include <utility> #include <utility>
#include <QDebug>
namespace NGL namespace NGL
{ {
Compress::Compress(QObject* parent) Compress::Compress(QObject* parent)
: QObject(parent) : QObject(parent), m_u2_memFiles(), m_aborted(0),
, m_u2_memFiles() m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("nglcompress"))
, m_aborted(0)
{ {
DEBUG_LOG(m_logger) << "c_tor"; DEBUG_LOG(m_logger) << "c_tor";
QTimer* t = new QTimer(this); QTimer* t = new QTimer(this);
t->setInterval(1000); t->setInterval(1000);
connect(t, &QTimer::timeout, this, []() { qWarning() << "still alive ..."; }); connect(t, &QTimer::timeout, this, []() { qWarning() << "still alive ..."; });
@@ -68,7 +37,6 @@ Compress::~Compress()
{ {
qWarning() << "## COMPRESS DTOR!!!!"; qWarning() << "## COMPRESS DTOR!!!!";
DEBUG_LOG(m_logger) << "~"; DEBUG_LOG(m_logger) << "~";
abort(); abort();
@@ -96,11 +64,8 @@ void Compress::abort()
} }
} }
void Compress::compress(QIODevice *out, void Compress::compress(QIODevice* out, const QString& filesRootDir, const QVector<FileInformations>& files,
const QString &filesRootDir, const QVector<FileInformations>& memFiles, const QString& destRootDir)
const QVector<FileInformations> &files,
const QVector<FileInformations> &memFiles,
const QString &destRootDir)
{ {
DEBUG_LOG(m_logger) << "compress #2"; DEBUG_LOG(m_logger) << "compress #2";
reset(); reset();
@@ -116,7 +81,6 @@ void Compress::compress(QIODevice *out, const QString &sourceDir, const QString
QVector<Compress::FileInformations> inFiles = directoryFileList(sourceDir, true); QVector<Compress::FileInformations> inFiles = directoryFileList(sourceDir, true);
int len = sourceDir.length(); int len = sourceDir.length();
if (!sourceDir.endsWith(QLatin1Char('/'))) if (!sourceDir.endsWith(QLatin1Char('/')))
len += 1; len += 1;
@@ -132,31 +96,27 @@ void Compress::compress(QIODevice *out, const QString &sourceDir, const QString
compress(out, sourceDir, inFiles, {}, destRootDir); compress(out, sourceDir, inFiles, {}, destRootDir);
} }
bool Compress::_compress(QIODevice *output, bool Compress::_compress(QIODevice* output, const QString& filesRootDir, const QVector<FileInformations>& files,
const QString &filesRootDir, const QVector<FileInformations>& memFiles, const QString& _destRootDir)
const QVector<FileInformations> &files,
const QVector<FileInformations> &memFiles,
const QString &_destRootDir)
{
std::shared_ptr<int> invalidatePointersOnScopeLeave(nullptr, [this](int *)
{ {
std::shared_ptr<int> invalidatePointersOnScopeLeave(nullptr, [this](int*) {
DEBUG_LOG(m_logger) << "invalidatePointersOnScopeLeave #1"; DEBUG_LOG(m_logger) << "invalidatePointersOnScopeLeave #1";
m_currentTarFilter = nullptr; m_currentTarFilter = nullptr;
m_currentBzipDevice = nullptr; m_currentBzipDevice = nullptr;
}); });
(void)invalidatePointersOnScopeLeave; (void)invalidatePointersOnScopeLeave;
if (!output || !output->isWritable()) if (!output || !output->isWritable())
{ {
m_lastError = tr("Device is not writeable"); m_lastError = tr("Device is not writeable");
ERROR_LOG(m_logger) << "compress failed: " << m_lastError;; ERROR_LOG(m_logger) << "compress failed: " << m_lastError;
;
return false; return false;
} }
const QString destRootDir = _destRootDir.endsWith(QLatin1Char('/')) ? const QString destRootDir =
_destRootDir : _destRootDir + QLatin1Char('/'); _destRootDir.endsWith(QLatin1Char('/')) ? _destRootDir : _destRootDir + QLatin1Char('/');
const qint64 maxCount = files.count() + memFiles.count(); const qint64 maxCount = files.count() + memFiles.count();
qint64 count = 0; qint64 count = 0;
@@ -174,41 +134,39 @@ bool Compress::_compress(QIODevice *output,
return false; return false;
} }
qint64 bytesTotal = 0; qint64 bytesTotal = 0;
for (const FileInformations& file : std::as_const(files)) for (const FileInformations& file : std::as_const(files))
{ {
if (m_aborted) return false; if (m_aborted)
return false;
const QString in = file.bAbsInputPath ? file.inputFileName : filesRootDir + QLatin1Char('/') + file.inputFileName; const QString in =
file.bAbsInputPath ? file.inputFileName : filesRootDir + QLatin1Char('/') + file.inputFileName;
const QFileInfo fi(in); const QFileInfo fi(in);
bytesTotal += fi.size(); bytesTotal += fi.size();
} }
qint64 currentFileSize = 0; qint64 currentFileSize = 0;
QString currentFileName; QString currentFileName;
auto readCallback = [this, &maxCount, &count, &currentFileSize, &currentFileName, &bytesTotal](const qint64 iSize) auto readCallback = [this, &maxCount, &count, &currentFileSize, &currentFileName, &bytesTotal](const qint64 iSize) {
{
DEBUG_LOG(m_logger) << "readCallback: maxCount = " << maxCount << ", count = " << count DEBUG_LOG(m_logger) << "readCallback: maxCount = " << maxCount << ", count = " << count
<< ", currentFileSize = " << currentFileSize << ", currentFileName = " << currentFileName << ", iSize = " << iSize; << ", currentFileSize = " << currentFileSize << ", currentFileName = " << currentFileName
<< ", iSize = " << iSize;
emit compressInfoEx(maxCount, count, currentFileSize, (currentFileSize - iSize), currentFileName, bytesTotal); emit compressInfoEx(maxCount, count, currentFileSize, (currentFileSize - iSize), currentFileName, bytesTotal);
}; };
TarFilter tf(&bzip2, readCallback); TarFilter tf(&bzip2, readCallback);
m_currentTarFilter = &tf; m_currentTarFilter = &tf;
const QStringList paths = destRootDir.split(QLatin1Char('/'), Qt::SkipEmptyParts); const QStringList paths = destRootDir.split(QLatin1Char('/'), Qt::SkipEmptyParts);
QString curPath; QString curPath;
DEBUG_LOG(m_logger) << "prepairing tar filter"; DEBUG_LOG(m_logger) << "prepairing tar filter";
for (const QString& path : paths) for (const QString& path : paths)
{ {
DEBUG_LOG(m_logger) << "path = " << path; DEBUG_LOG(m_logger) << "path = " << path;
if (m_aborted) return false; if (m_aborted)
return false;
if (curPath.isEmpty()) if (curPath.isEmpty())
curPath = path + QLatin1Char('/'); curPath = path + QLatin1Char('/');
@@ -245,7 +203,8 @@ bool Compress::_compress(QIODevice *output,
DEBUG_LOG(m_logger) << "file = " << file.inputFileName; DEBUG_LOG(m_logger) << "file = " << file.inputFileName;
emit compressInfo(maxCount, ++count, file.inputFileName); emit compressInfo(maxCount, ++count, file.inputFileName);
if (m_aborted) return false; if (m_aborted)
return false;
QString in = file.bAbsInputPath ? file.inputFileName : filesRootDir + QLatin1Char('/') + file.inputFileName; QString in = file.bAbsInputPath ? file.inputFileName : filesRootDir + QLatin1Char('/') + file.inputFileName;
QString out = destRootDir + (file.outputFileName.isEmpty() ? file.inputFileName : file.outputFileName); QString out = destRootDir + (file.outputFileName.isEmpty() ? file.inputFileName : file.outputFileName);
@@ -258,7 +217,8 @@ bool Compress::_compress(QIODevice *output,
currentFileSize = fi.size(); currentFileSize = fi.size();
m_c_sizeInfo.realSize += currentFileSize; m_c_sizeInfo.realSize += currentFileSize;
DEBUG_LOG(m_logger) << "currentFileName = " << currentFileName << ", currentFileSize = " << currentFileSize << "m_c_sizeInfo.realSize" << m_c_sizeInfo.realSize; DEBUG_LOG(m_logger) << "currentFileName = " << currentFileName << ", currentFileSize = " << currentFileSize
<< "m_c_sizeInfo.realSize" << m_c_sizeInfo.realSize;
if (!tf.addFile(in, out)) if (!tf.addFile(in, out))
{ {
@@ -274,13 +234,16 @@ bool Compress::_compress(QIODevice *output,
DEBUG_LOG(m_logger) << "(mem) file = " << file.inputFileName; DEBUG_LOG(m_logger) << "(mem) file = " << file.inputFileName;
emit compressInfo(maxCount, ++count, file.inputFileName); emit compressInfo(maxCount, ++count, file.inputFileName);
if (m_aborted) return false; if (m_aborted)
return false;
currentFileName = file.inputFileName; currentFileName = file.inputFileName;
currentFileSize = file.fileData.size(); currentFileSize = file.fileData.size();
m_c_sizeInfo.compressedSize += currentFileSize; m_c_sizeInfo.compressedSize += currentFileSize;
DEBUG_LOG(m_logger) << "(mem) currentFileName = " << currentFileName << ", currentFileSize = " << currentFileSize << "m_c_sizeInfo.realSize" << m_c_sizeInfo.realSize; DEBUG_LOG(m_logger) << "(mem) currentFileName = " << currentFileName
<< ", currentFileSize = " << currentFileSize << "m_c_sizeInfo.realSize"
<< m_c_sizeInfo.realSize;
if (!tf.addData(file.inputFileName, file.fileData)) if (!tf.addData(file.inputFileName, file.fileData))
{ {
@@ -291,7 +254,6 @@ bool Compress::_compress(QIODevice *output,
} }
} }
DEBUG_LOG(m_logger) << "writing eos"; DEBUG_LOG(m_logger) << "writing eos";
tf.writeEOS(); tf.writeEOS();
@@ -319,15 +281,13 @@ bool Compress::_uncompressDirectory(QIODevice *input, const QString &outDir)
{ {
DEBUG_LOG(m_logger) << "_uncompressDirectory"; DEBUG_LOG(m_logger) << "_uncompressDirectory";
std::shared_ptr<int> invalidatePointersOnScopeLeave(nullptr, [this](int *) std::shared_ptr<int> invalidatePointersOnScopeLeave(nullptr, [this](int*) {
{
DEBUG_LOG(m_logger) << "invalidatePointersOnScopeLeave #2"; DEBUG_LOG(m_logger) << "invalidatePointersOnScopeLeave #2";
m_currentTarFilter = nullptr; m_currentTarFilter = nullptr;
m_currentBzipDevice = nullptr; m_currentBzipDevice = nullptr;
}); });
(void)invalidatePointersOnScopeLeave; (void)invalidatePointersOnScopeLeave;
if (!input || !input->isReadable()) if (!input || !input->isReadable())
{ {
m_lastError = tr("Device is not readable"); m_lastError = tr("Device is not readable");
@@ -357,7 +317,8 @@ bool Compress::_uncompressDirectory(QIODevice *input, const QString &outDir)
{ {
DEBUG_LOG(m_logger) << "tfi.fileName = " << tfi.fileName; DEBUG_LOG(m_logger) << "tfi.fileName = " << tfi.fileName;
emit uncompressInfo(input->size(), input->pos(), tfi.fileName); emit uncompressInfo(input->size(), input->pos(), tfi.fileName);
if (m_aborted) return false; if (m_aborted)
return false;
QString path = outDir + QLatin1Char('/') + tfi.fileName; QString path = outDir + QLatin1Char('/') + tfi.fileName;
DEBUG_LOG(m_logger) << "path = " << path; DEBUG_LOG(m_logger) << "path = " << path;
@@ -417,15 +378,13 @@ bool Compress::_uncompressBuffer(QIODevice *input)
{ {
DEBUG_LOG(m_logger) << "uncompressBuffer"; DEBUG_LOG(m_logger) << "uncompressBuffer";
std::shared_ptr<int> invalidatePointersOnScopeLeave(nullptr, [this](int *) std::shared_ptr<int> invalidatePointersOnScopeLeave(nullptr, [this](int*) {
{
DEBUG_LOG(m_logger) << "invalidatePointersOnScopeLeave #2"; DEBUG_LOG(m_logger) << "invalidatePointersOnScopeLeave #2";
m_currentTarFilter = nullptr; m_currentTarFilter = nullptr;
m_currentBzipDevice = nullptr; m_currentBzipDevice = nullptr;
}); });
(void)invalidatePointersOnScopeLeave; (void)invalidatePointersOnScopeLeave;
if (!input->isReadable()) if (!input->isReadable())
{ {
m_lastError = tr("Device is not readable"); m_lastError = tr("Device is not readable");
@@ -451,7 +410,8 @@ bool Compress::_uncompressBuffer(QIODevice *input)
{ {
DEBUG_LOG(m_logger) << "tfi.fileName = " << tfi.fileName; DEBUG_LOG(m_logger) << "tfi.fileName = " << tfi.fileName;
emit uncompressInfo(input->size(), input->pos(), tfi.fileName); emit uncompressInfo(input->size(), input->pos(), tfi.fileName);
if (m_aborted) return false; if (m_aborted)
return false;
FileInformations fi; FileInformations fi;
fi.outputFileName = tfi.fileName; fi.outputFileName = tfi.fileName;
@@ -499,8 +459,7 @@ bool Compress::success() const
ERROR_LOG(m_logger) << "success? " << (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: " ERROR_LOG(m_logger) << "success details: "
<< "success m_future.isFinished() = " << (m_future.isFinished()) << "success m_future.isFinished() = " << (m_future.isFinished())
<< " !m_future.isCanceled() = " << !m_future.isCanceled() << " !m_future.isCanceled() = " << !m_future.isCanceled() << " m_success = " << m_success;
<< " m_success = " << m_success;
return (m_future.isFinished() && !m_future.isCanceled() && m_success); return (m_future.isFinished() && !m_future.isCanceled() && m_success);
} }
@@ -562,8 +521,9 @@ void Compress::setupFutureWatcher(const QFuture<bool> &future)
QObject::connect(fw, &QObject::destroyed, this, [this]() { DEBUG_LOG(m_logger) << "Future Watcher destroyed"; }); QObject::connect(fw, &QObject::destroyed, this, [this]() { DEBUG_LOG(m_logger) << "Future Watcher destroyed"; });
QObject::connect(fw, &QFutureWatcher<bool>::finished, this, &Compress::finished); QObject::connect(fw, &QFutureWatcher<bool>::finished, this, &Compress::finished);
QObject::connect(fw, &QFutureWatcher<bool>::finished, fw, &QObject::deleteLater); QObject::connect(fw, &QFutureWatcher<bool>::finished, fw, &QObject::deleteLater);
QObject::connect(fw, &QFutureWatcher<bool>::finished, fw, [this]() { DEBUG_LOG(m_logger) << "Future Watcher about to be deleted"; }); QObject::connect(fw, &QFutureWatcher<bool>::finished, fw,
[this]() { DEBUG_LOG(m_logger) << "Future Watcher about to be deleted"; });
fw->setFuture(m_future); fw->setFuture(m_future);
} }
} } // namespace NGL
+1 -4
View File
@@ -1,12 +1,9 @@
#pragma once #pragma once
#include "commandinterface.h" #include "commandinterface.h"
#include "sv_export.h" #include "tcpserver_export.h"
class TCPSERVER_EXPORT CBI_Help : public CommandInterface class TCPSERVER_EXPORT CBI_Help : public CommandInterface
{ {
+1 -4
View File
@@ -1,12 +1,9 @@
#pragma once #pragma once
#include "commandinterface.h" #include "commandinterface.h"
#include "sv_export.h" #include "tcpserver_export.h"
class CBI_PingPong : public CommandInterface class CBI_PingPong : public CommandInterface
{ {
+1 -4
View File
@@ -1,12 +1,9 @@
#pragma once #pragma once
#include "commandinterface.h" #include "commandinterface.h"
#include "sv_export.h" #include "tcpserver_export.h"
class TCPSERVER_EXPORT CBI_Quit : public CommandInterface class TCPSERVER_EXPORT CBI_Quit : public CommandInterface
{ {
+4 -2
View File
@@ -1,14 +1,15 @@
#pragma once #pragma once
#include "commandinterface.h" #include "commandinterface.h"
#include "sv_export.h" #include "tcpserver_export.h"
#include <QMap> #include <QMap>
#include <QPair> #include <QPair>
class QIODevice; class QIODevice;
class CBI_Recvfile : public CommandInterface class CBI_Recvfile : public CommandInterface
{ {
Q_OBJECT Q_OBJECT
@@ -18,6 +19,7 @@ public:
void handleCommandInternal(const QVector<QByteArray>& args) override; void handleCommandInternal(const QVector<QByteArray>& args) override;
QString help() const override; QString help() const override;
void newPlainData() override; void newPlainData() override;
protected: protected:
QMap<WorkerBase*, QPair<QIODevice*, int>> m_wbMap; QMap<WorkerBase*, QPair<QIODevice*, int>> m_wbMap;
}; };
+1 -2
View File
@@ -1,10 +1,9 @@
#pragma once #pragma once
#include "commandinterface.h" #include "commandinterface.h"
#include "sv_export.h" #include "tcpserver_export.h"
class CBI_Sendfile : public CommandInterface class CBI_Sendfile : public CommandInterface
{ {
+2 -5
View File
@@ -1,12 +1,9 @@
#pragma once #pragma once
#include "commandinterface.h" #include "commandinterface.h"
#include "sv_export.h" #include "tcpserver_export.h"
class TCPSERVER_EXPORT CBI_Shutdown : public CommandInterface class TCPSERVER_EXPORT CBI_Shutdown : public CommandInterface
{ {
@@ -19,7 +16,7 @@ public:
Q_SIGNALS: Q_SIGNALS:
void shutdownRequest(); void shutdownRequest();
private: private:
}; };
+7 -58
View File
@@ -1,151 +1,101 @@
#pragma once #pragma once
#include "tcpserver_export.h"
#include <QObject> #include <QObject>
#include <QString> #include <QString>
#include <QVector> #include <QVector>
#include "sv_export.h"
class QAbstractSocket; class QAbstractSocket;
class QByteArray; class QByteArray;
class WorkerBase; class WorkerBase;
class TCPSERVER_EXPORT CommandInterface : public QObject class TCPSERVER_EXPORT CommandInterface : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit CommandInterface(unsigned short port, const QByteArray& command = QByteArray()); explicit CommandInterface(unsigned short port, const QByteArray& command = QByteArray());
virtual ~CommandInterface(); virtual ~CommandInterface();
void handleCommand(const QVector<QByteArray>& args); void handleCommand(const QVector<QByteArray>& args);
virtual void newPlainData(); virtual void newPlainData();
virtual QString help() const = 0; virtual QString help() const = 0;
QByteArray command() const; QByteArray command() const;
void setAutoWriteEOL(bool newAutoWriteEOL); void setAutoWriteEOL(bool newAutoWriteEOL);
bool autoWriteEOL() const; bool autoWriteEOL() const;
bool errorOccured() const; bool errorOccured() const;
static void setDefaultSuccessMessage(const QString& msg); static void setDefaultSuccessMessage(const QString& msg);
static void setDefaultErrorMessage(const QString& msg); static void setDefaultErrorMessage(const QString& msg);
template<class T> template <class T> static CommandInterface* factory(unsigned short port)
static CommandInterface *factory(unsigned short port) { return new T(port); } {
return new T(port);
}
virtual void aboutToDestroy() {} virtual void aboutToDestroy() {}
protected: protected:
virtual void handleCommandInternal(const QVector<QByteArray>& args) = 0; virtual void handleCommandInternal(const QVector<QByteArray>& args) = 0;
void setWriteTimeout(int iMS); void setWriteTimeout(int iMS);
void writeData(const QByteArray& payload); void writeData(const QByteArray& payload);
void writeData(const char* payload); void writeData(const char* payload);
void writeData(const QString& payload); void writeData(const QString& payload);
void writeData(const QStringList& payload); void writeData(const QStringList& payload);
void writeData(const QList<QByteArray>& payload); void writeData(const QList<QByteArray>& payload);
void writeOk(const QString& additionalMsg = QString()); void writeOk(const QString& additionalMsg = QString());
void writeError(const QString& additionalMsg = QString()); void writeError(const QString& additionalMsg = QString());
void writeEOL(); void writeEOL();
QByteArray quote(const QByteArray& payload); QByteArray quote(const QByteArray& payload);
QAbstractSocket* socket(); QAbstractSocket* socket();
void setSocket(QAbstractSocket* socket); void setSocket(QAbstractSocket* socket);
WorkerBase* workerBase(); WorkerBase* workerBase();
void setWorkerBase(WorkerBase* wb); void setWorkerBase(WorkerBase* wb);
void conversionError(const QByteArray& arg, const QByteArray& type); void conversionError(const QByteArray& arg, const QByteArray& type);
bool getValue(const QByteArray& arg, bool& value); bool getValue(const QByteArray& arg, bool& value);
bool getValue(const QByteArray& arg, long& value); bool getValue(const QByteArray& arg, long& value);
bool getValue(const QByteArray& arg, unsigned long& value); bool getValue(const QByteArray& arg, unsigned long& value);
bool getValue(const QByteArray& arg, int& value); bool getValue(const QByteArray& arg, int& value);
bool getValue(const QByteArray& arg, unsigned int& value); bool getValue(const QByteArray& arg, unsigned int& value);
bool getValue(const QByteArray& arg, float& value); bool getValue(const QByteArray& arg, float& value);
bool getValue(const QByteArray& arg, double& value); bool getValue(const QByteArray& arg, double& value);
unsigned short port() const; unsigned short port() const;
void closeConnection(); void closeConnection();
bool socketIsOpen() const; bool socketIsOpen() const;
private: private:
@@ -153,6 +103,5 @@ private:
class Private; class Private;
Private* const d; Private* const d;
}; };
+3 -35
View File
@@ -1,82 +1,53 @@
#pragma once #pragma once
#include <QTcpServer> #include "tcpserver_export.h"
#include "sv_export.h" #include <QTcpServer>
class WorkerInstance; class WorkerInstance;
class CommandInterface; class CommandInterface;
class TCPSERVER_EXPORT TcpServer : public QTcpServer class TCPSERVER_EXPORT TcpServer : public QTcpServer
{ {
Q_OBJECT Q_OBJECT
public: public:
typedef QVector<CommandInterface* (*)(unsigned short)> CommandInterfaceList; typedef QVector<CommandInterface* (*)(unsigned short)> CommandInterfaceList;
public: public:
virtual ~TcpServer(); 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); void setUseWorkerThreads(bool bEnable);
bool useWorkerThreads() const; bool useWorkerThreads() const;
QVector<WorkerInstance*> workers() const; QVector<WorkerInstance*> workers() const;
unsigned short getListenPort() const; unsigned short getListenPort() const;
static bool registerCommand(unsigned short port, CommandInterface* (*factory)(unsigned short)); static bool registerCommand(unsigned short port, CommandInterface* (*factory)(unsigned short));
static bool unregisterCommand(unsigned short port, CommandInterface* (*factory)(unsigned short)); static bool unregisterCommand(unsigned short port, CommandInterface* (*factory)(unsigned short));
static CommandInterfaceList registeredCommands(unsigned short port); static CommandInterfaceList registeredCommands(unsigned short port);
void setUserData(void* userData); void setUserData(void* userData);
void* userData() const; void* userData() const;
Q_SIGNALS: Q_SIGNALS:
void aboutToQuit(unsigned short port); void aboutToQuit(unsigned short port);
public Q_SLOTS: public Q_SLOTS:
void shutdownRequest(); void shutdownRequest();
void workerFinished(); void workerFinished();
protected: protected:
@@ -85,12 +56,9 @@ protected:
private: private:
class Private; class Private;
Private* const d; Private* const d;
explicit TcpServer(unsigned short port); explicit TcpServer(unsigned short port);
bool listen(const QHostAddress& address, quint16 port); bool listen(const QHostAddress& address, quint16 port);
}; };
+4 -45
View File
@@ -1,93 +1,61 @@
#pragma once #pragma once
#include "tcpserver_export.h"
#include <QByteArray> #include <QByteArray>
#include <QMap> #include <QMap>
#include <QPointer>
#include <QObject> #include <QObject>
#include <QPointer>
#include "sv_export.h"
class QAbstractSocket; class QAbstractSocket;
class CommandInterface; class CommandInterface;
class TCPSERVER_EXPORT WorkerBase class TCPSERVER_EXPORT WorkerBase
{ {
public: public:
typedef QMap<QByteArray, CommandInterface*> CommandMap; typedef QMap<QByteArray, CommandInterface*> CommandMap;
public: public:
WorkerBase(qintptr sd, unsigned short port); 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); void redirectDataHandling(bool bDoRedirect, CommandInterface* newDataHandler = nullptr);
static QByteArray formatForDebug(const QByteArray& data); static QByteArray formatForDebug(const QByteArray& data);
static QByteArray formatForDebug(const QAbstractSocket* dev); static QByteArray formatForDebug(const QAbstractSocket* dev);
CommandMap getCommands() const; CommandMap getCommands() const;
protected: protected:
void newDataInternal(); void newDataInternal();
int initCommands(unsigned short port); int initCommands(unsigned short port);
void cleanupCommands(); void cleanupCommands();
qintptr m_socketDescriptor; qintptr m_socketDescriptor;
QPointer<QAbstractSocket> m_connection; QPointer<QAbstractSocket> m_connection;
unsigned short m_port; unsigned short m_port;
QByteArray m_connString; QByteArray m_connString;
bool m_bRedirectIncomingData; bool m_bRedirectIncomingData;
CommandInterface* m_bRedirectDataHandler; CommandInterface* m_bRedirectDataHandler;
CommandMap m_registeredCommands; CommandMap m_registeredCommands;
}; };
class WorkerInstance final : public QObject, public WorkerBase class WorkerInstance final : public QObject, public WorkerBase
{ {
Q_OBJECT Q_OBJECT
@@ -95,28 +63,20 @@ public:
WorkerInstance(qintptr sd, unsigned short port, QObject* parent = nullptr); WorkerInstance(qintptr sd, unsigned short port, QObject* parent = nullptr);
virtual ~WorkerInstance(); 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(); void doWork();
protected Q_SLOTS: protected Q_SLOTS:
void newData(); void newData();
void connectionDisconnected(); void connectionDisconnected();
Q_SIGNALS: Q_SIGNALS:
@@ -125,4 +85,3 @@ Q_SIGNALS:
private: private:
bool m_bFinished; bool m_bFinished;
}; };
@@ -163,6 +163,7 @@ MACRO(INSTALL_SHARED_FILES srcList)
ENDMACRO() ENDMACRO()
MACRO(CODEGEN_SQL srcList xmlFile_in) MACRO(CODEGEN_SQL srcList xmlFile_in)
IF(BUILD_GRANTLEE)
_GET_SERVICENAME( "${xmlFile_in}" svcNameOut ) _GET_SERVICENAME( "${xmlFile_in}" svcNameOut )
SET(out_dir_sql "${CMAKE_BINARY_DIR}/share/Lts/sql/") SET(out_dir_sql "${CMAKE_BINARY_DIR}/share/Lts/sql/")
SET(out_file_sql "${out_dir_sql}/${svcNameOut}.sql") SET(out_file_sql "${out_dir_sql}/${svcNameOut}.sql")
@@ -182,6 +183,11 @@ MACRO(CODEGEN_SQL srcList xmlFile_in)
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() ENDMACRO()
MACRO(CODEGEN_HANDLE_SVC_XML srcList xmlFile_in) MACRO(CODEGEN_HANDLE_SVC_XML srcList xmlFile_in)
+63 -78
View File
@@ -7,22 +7,21 @@
#pragma once #pragma once
#include <string> #include <QList>
#include <sstream>
#include <QString>
#include <QPointF> #include <QPointF>
#include <QSize>
#include <QRect> #include <QRect>
#include <QRectF> #include <QRectF>
#include <QList> #include <QSize>
#include "ngllogger_export.h" #include <QString>
#include <ngllogger_export.h>
#include <sstream>
#include <string>
namespace NGL namespace NGL
{ {
class INGLLogger; class INGLLogger;
// keep in sync with log4qt/level.h // keep in sync with log4qt/level.h
enum class LogLevel enum class LogLevel {
{
Undefined = 0, Undefined = 0,
Trace = 64, Trace = 64,
Debug = 96, Debug = 96,
@@ -35,17 +34,15 @@ enum class LogLevel
class LogStreamHelper class LogStreamHelper
{ {
public: public:
inline LogStreamHelper(INGLLogger &logger, LogLevel level, const char *const file, int line, const char *const function) inline LogStreamHelper(INGLLogger& logger, LogLevel level, const char* const file, int line,
: m_logger(logger) const char* const function)
, m_level(level) : m_logger(logger), m_level(level), m_line(line), m_file(file), m_func(function)
, m_line(line) {
, m_file(file) }
, m_func(function)
{}
inline ~LogStreamHelper(); // after INGLLogger class definition inline ~LogStreamHelper(); // after INGLLogger class definition
template<typename T> template <typename T> inline LogStreamHelper& operator<<(const T& val);
inline LogStreamHelper &operator<<(const T &val);
private: private:
std::ostringstream m_buffer; std::ostringstream m_buffer;
@@ -79,7 +76,6 @@ public:
virtual INGLLogger& getNGLLogger(const char* fullqualifiedname) = 0; virtual INGLLogger& getNGLLogger(const char* fullqualifiedname) = 0;
virtual INGLLogger& getNGLLogger(const std::string& fullqualifiedname) = 0; virtual INGLLogger& getNGLLogger(const std::string& fullqualifiedname) = 0;
// True if this level is enabled. // True if this level is enabled.
virtual bool isTraceEnabled() const = 0; virtual bool isTraceEnabled() const = 0;
virtual bool isDebugEnabled() const = 0; virtual bool isDebugEnabled() const = 0;
@@ -91,20 +87,27 @@ public:
// Submit a LOG message. // Submit a LOG message.
// Use __FILE__ and __NAME__ macros. // 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; 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. // Submit an TRACE message.
virtual void logTrace(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0; virtual void logTrace(const INGLLogger::String& message, const char* file = nullptr, int line = -1,
const char* function = nullptr) = 0;
// Submit an DEBUG message. // Submit an DEBUG message.
virtual void logDebug(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0; virtual void logDebug(const INGLLogger::String& message, const char* file = nullptr, int line = -1,
const char* function = nullptr) = 0;
// Submit an INFO message. // Submit an INFO message.
virtual void logInfo(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0; virtual void logInfo(const INGLLogger::String& message, const char* file = nullptr, int line = -1,
const char* function = nullptr) = 0;
// Submit a WARNING message. // Submit a WARNING message.
virtual void logWarning(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0; virtual void logWarning(const INGLLogger::String& message, const char* file = nullptr, int line = -1,
const char* function = nullptr) = 0;
// Submit an ERROR message. // Submit an ERROR message.
virtual void logError(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0; virtual void logError(const INGLLogger::String& message, const char* file = nullptr, int line = -1,
const char* function = nullptr) = 0;
// Submit a FATAL message. // Submit a FATAL message.
virtual void logFatal(const INGLLogger::String &message, const char *file = nullptr, int line = -1, const char *function = nullptr) = 0; 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 // Writes a startup message into the logfile
virtual void logStartup(const char* file, int line, const char* function = nullptr) = 0; virtual void logStartup(const char* file, int line, const char* function = nullptr) = 0;
@@ -126,8 +129,7 @@ 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<typename T> template <typename T> inline LogStreamHelper& LogStreamHelper::operator<<(const T& val)
inline LogStreamHelper &LogStreamHelper::operator<<(const T &val)
{ {
m_buffer << val; m_buffer << val;
if (!m_logger.noSpace()) if (!m_logger.noSpace())
@@ -135,7 +137,6 @@ inline LogStreamHelper &LogStreamHelper::operator<<(const T &val)
return *this; 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)
@@ -147,67 +148,50 @@ inline std::ostream &operator<<(std::ostream &stream, const QByteArray &str)
// //
// operator to ease logging (at least via NglLogging) // operator to ease logging (at least via NglLogging)
// //
inline std::ostream &operator<<(std::ostream &stream, inline std::ostream& operator<<(std::ostream& stream, const QPointF& value)
const QPointF &value)
{ {
stream << "QPointF(" << QString::number(value.x(), 'f', 6).toStdString() << "#" << QString::number(value.y(), 'f', 6).toStdString() << ")"; stream << "QPointF(" << QString::number(value.x(), 'f', 6).toStdString() << "#"
<< QString::number(value.y(), 'f', 6).toStdString() << ")";
return stream; return stream;
} }
//---------------------------------------------------------------------------- //----------------------------------------------------------------------------
inline std::ostream &operator<< (std::ostream &stream, inline std::ostream& operator<<(std::ostream& stream, const QPoint& value)
const QPoint &value)
{ {
stream << "QPoint(" << value.x() << "#" << value.y() << ")"; stream << "QPoint(" << value.x() << "#" << value.y() << ")";
return stream; return stream;
} }
inline std::ostream &operator<< (std::ostream &stream, inline std::ostream& operator<<(std::ostream& stream, const QSize& value)
const QSize &value)
{ {
stream << "QSize(w=" << value.width() << ";h=" << value.height() << ")"; stream << "QSize(w=" << value.width() << ";h=" << value.height() << ")";
return stream; return stream;
} }
inline std::ostream &operator<< (std::ostream &stream,
const QSizeF &value) inline std::ostream& operator<<(std::ostream& stream, const QSizeF& value)
{ {
stream << "QSize(w=" stream << "QSize(w=" << QString::number(value.width(), 'f', 6).toStdString()
<< QString::number(value.width(), 'f', 6).toStdString() << ";h=" << ";h=" << QString::number(value.height(), 'f', 6).toStdString() << ")";
<< QString::number(value.height(), 'f', 6).toStdString()
<< ")";
return stream; return stream;
} }
inline std::ostream& operator<<(std::ostream& stream, const QRect& value)
inline std::ostream &operator<< (std::ostream &stream,
const QRect &value)
{ {
stream << "QRect(center=" << value.center() stream << "QRect(center=" << value.center() << " w=" << value.width() << ";h=" << value.height()
<< " w=" << value.width() << " bottomLeft=" << value.bottomLeft() << " topRight=" << value.topRight() << ")";
<< ";h=" << value.height()
<< " bottomLeft=" << value.bottomLeft()
<< " topRight=" << value.topRight()
<< ")";
return stream; return stream;
} }
inline std::ostream &operator<< (std::ostream &stream, inline std::ostream& operator<<(std::ostream& stream, const QRectF& value)
const QRectF &value)
{ {
stream << "QRectF(center=" << value.center() stream << "QRectF(center=" << value.center() << " w=" << QString::number(value.width(), 'f', 3).toStdString()
<< " w=" << QString::number(value.width(), 'f', 3).toStdString() << ";h=" << QString::number(value.height(), 'f', 3).toStdString() << " bottomLeft=" << value.bottomLeft()
<< ";h=" << QString::number(value.height(), 'f', 3).toStdString() << " topRight=" << value.topRight() << ")";
<< " bottomLeft=" << value.bottomLeft()
<< " topRight=" << value.topRight()
<< ")";
return stream; return stream;
} }
inline std::ostream& operator<<(std::ostream& stream, const QList<int>& value)
inline std::ostream &operator<< (std::ostream &stream,
const QList<int> &value)
{ {
stream << "QList<int>(" << value.size() << "): "; stream << "QList<int>(" << value.size() << "): ";
for (int i : value) for (int i : value)
@@ -215,9 +199,7 @@ inline std::ostream &operator<< (std::ostream &stream,
return stream; return stream;
} }
inline std::ostream& operator<<(std::ostream& stream, const QList<QPointF>& value)
inline std::ostream &operator<< (std::ostream &stream,
const QList<QPointF> &value)
{ {
stream << "QList<QPointF>(" << value.size() << "): "; stream << "QList<QPointF>(" << value.size() << "): ";
for (const QPointF& item : value) for (const QPointF& item : value)
@@ -225,7 +207,6 @@ inline std::ostream &operator<< (std::ostream &stream,
return stream; return stream;
} }
inline std::ostream& operator<<(std::ostream& stream, const QString& str) inline std::ostream& operator<<(std::ostream& stream, const QString& str)
{ {
return stream << str.toUtf8(); return stream << str.toUtf8();
@@ -236,13 +217,10 @@ namespace NGL
namespace NGLLoggerHelper namespace NGLLoggerHelper
{ {
NGLLOGGER_EXPORT void hexDumpHelper(NGL::INGLLogger &logger, NGLLOGGER_EXPORT void hexDumpHelper(NGL::INGLLogger& logger, NGL::LogLevel level, const void* a_data,
NGL::LogLevel level,
const void *a_data,
const unsigned int a_size); const unsigned int a_size);
inline void hexDumpHelper(NGL::INGLLogger &logger,
NGL::LogLevel level, inline void hexDumpHelper(NGL::INGLLogger& logger, NGL::LogLevel level, const QByteArray& data)
const QByteArray &data)
{ {
return hexDumpHelper(logger, level, data.data(), data.size()); return hexDumpHelper(logger, level, data.data(), data.size());
} }
@@ -260,8 +238,7 @@ NGLLOGGER_EXPORT std::string getMemoryData();
#define LOGFUNCTION Q_FUNC_INFO #define LOGFUNCTION Q_FUNC_INFO
// log this output every time, no matter what log level is enabled // log this output every time, no matter what log level is enabled
#define NOTICE_LOG(logger) \ #define NOTICE_LOG(logger) NGL::LogStreamHelper(logger, NGL::LogLevel::Info, __FILE__, __LINE__, Q_FUNC_INFO)
NGL::LogStreamHelper(logger, NGL::LogLevel::Info, __FILE__,__LINE__, Q_FUNC_INFO)
#ifdef LTS_DEBUG #ifdef LTS_DEBUG
#define TRACE_LOG(logger) \ #define TRACE_LOG(logger) \
@@ -293,8 +270,14 @@ NGLLOGGER_EXPORT std::string getMemoryData();
for (bool log_level_enabled = (logger).isFatalEnabled(); log_level_enabled; log_level_enabled = false) \ 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) NGL::LogStreamHelper(logger, NGL::LogLevel::Fatal, __FILE__, __LINE__, Q_FUNC_INFO)
#define STARTUP_LOG(logger) { (logger).logStartup(__FILE__, __LINE__, Q_FUNC_INFO); } #define STARTUP_LOG(logger) \
#define SHUTDOWN_LOG(logger) { (logger).logShutdown(__FILE__, __LINE__, Q_FUNC_INFO); } { \
(logger).logStartup(__FILE__, __LINE__, Q_FUNC_INFO); \
}
#define SHUTDOWN_LOG(logger) \
{ \
(logger).logShutdown(__FILE__, __LINE__, Q_FUNC_INFO); \
}
//============================================================================== //==============================================================================
@@ -304,7 +287,9 @@ NGLLOGGER_EXPORT std::string getMemoryData();
// MEMORY_LOG() << " after something nasty"; // MEMORY_LOG() << " after something nasty";
#define MEMORY_LOG() \ #define MEMORY_LOG() \
for (bool log_level_enabled = (NGL::getMemoryLogger()).isInfoEnabled(); log_level_enabled; log_level_enabled = false) \ for (bool log_level_enabled = (NGL::getMemoryLogger()).isInfoEnabled(); log_level_enabled; \
NGL::LogStreamHelper(NGL::getMemoryLogger(), NGL::LogLevel::Info, __FILE__,__LINE__, Q_FUNC_INFO) << NGL::getMemoryData() log_level_enabled = false) \
NGL::LogStreamHelper(NGL::getMemoryLogger(), NGL::LogLevel::Info, __FILE__, __LINE__, Q_FUNC_INFO) \
<< NGL::getMemoryData()
//============================================================================== //==============================================================================
@@ -13,7 +13,7 @@ if(NOT TARGET GTest::gtest_main)
FetchContent_Declare( FetchContent_Declare(
googletest googletest
GIT_REPOSITORY https://github.com/google/googletest.git 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 # For Windows: Prevent overriding the parent project's compiler/linker settings
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
@@ -31,6 +31,7 @@ if(BUILD_TESTING)
test_symbology_xml.cpp test_symbology_xml.cpp
test_saa_telegrams.cpp test_saa_telegrams.cpp
test_rti_integration.cpp test_rti_integration.cpp
test_ltswidgets_qt6.cpp
) )
# Check which files actually exist # Check which files actually exist
@@ -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 <gtest/gtest.h>
#include <QRandomGenerator>
#include <QComboBox>
#include <QWheelEvent>
#include <QStyleOption>
#include <QPushButton>
#include <QApplication>
// 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<int> 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<int>::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);
}